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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6ae497a880f38008a5dc1a405253bb459b4ac094 | C++ | Zzzode/My-Compiler | /c_minus.cpp | UTF-8 | 4,662 | 2.734375 | 3 | [] | no_license | // main function
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <vector>
#include <unordered_map>
// system call about files
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
// user defile
#include "c_minus.h"
#include "vmachine.h"
using namespace std;
int token; //type of the token we got
int lineno = 1; //line number of program
int decl_type; //type of the whole declaration
int exp_type; //type of expression answer
long long Hash; //mark the cuurent id in lexical
int layer; //mark which layer an id belongs to in symtab
bool is_decl = true;
//when lexical parse an id, judge legal or not
//if in decl mode, new id can be add into symtab, else illegal
int token_val = 0; //default literal int value
double token_d_val = 0; //literal double value
char token_str_val[64]; //store literal constant of string
// char *src; //buffer of file input
char *reserve[12] = {"char", "int", "double", "else", "enum", "if",
"return", "sizeof", "while", "and", "or", "not"};
// system function name
char *sys[8] = {"open", "read", "close", "printf",
"malloc", "memset", "memcmp", "exit"};
//notice we onlt deal with dec value
/**
* symbal table, using hash to find an id quickly
* hash value is key, ID info is the value
* symtab.back() is the current layer
* search id from back to begin
* initiate only one global layer
* push back when enter a local area
* pop back when leave a local area
*/
vector<unordered_map<long long, ID>> symtab(1);
vector<unordered_map<long long, ID>> ID_MAIN(1);
//TODO add function stack
//unordered_map<int, vector<int>> func_inst; // + fun_para
//unordered_map<int, vector<int>> func_var; // + fun_var
//int * 数组不太好动态伸缩长度,这里改用vector变长数组
//calculat the hash value of an id
long long hash_str(char *s)
{
long long ans = 0;
while (*s != '\0')
ans = ans * 147 + *s++;
return ans;
}
void open_src(int fd, char **argv)
{
int n;
if((fd = open(*argv, 0)) < 0)
{ // fail to open target file
cout << "couldn't open source file!\n";
exit(1);
}
src = new char[BUFSIZE];
if((n = read(fd, src, BUFSIZE)) < 0)
{ // faile to read target file
cout << "read file error\n";
exit(1);
}
lineno = 1;
src[n] = '\0'; //add EOF
close(fd);
}
//put build-in function into symtab
void init_symtab(int fd, char **argv)
{
int i;
long long hash;
int j = OPEN;
for (i = 0; i < 8; i++)
{
hash = hash_str(sys[i]);
symtab[0][hash].Class = Sys; //system function
symtab[0][hash].Type = INT; //variable data type or function return type
symtab[0][hash].In_value = j++; //build-in function type
// TODO initiate system function instruction stack
symtab[0][hash].Name = sys[i];
}
next(); symtab[0][Hash].TOKEN = Char; // handle void type
//next(); // ID_MAIN[0][Hash] = symtab[0][Hash]; // keep track of main
//ID_MAIN_addr = (int *)ID_MAIN[0][hash].In_value;
// read the source file
if ((fd = open(*argv, 0)) < 0)
{
printf("could not open(%s)\n", *argv);
exit(1);
}
if (!(src = oldsrc = (char*)malloc(poolsize)))
{
printf("could not malloc(%d) for source area\n", poolsize);
exit(1);
}
// read the source file
if ((i = read(fd, src, poolsize - 1)) <= 0)
{
printf("read() returned %d\n", i);
exit(1);
}
src[i] = 0; // add EOF character
close(fd);
}
int main(int argc, char **argv)
{
int fd; // linux系统调用文件操作
long long *temp;
argc--;
argv++;
if (argc > 0 && **argv == '-' && (*argv)[1] == 's') {
assembly = 1;
--argc;
++argv;
}
/* 初始化编译器系统 */
open_src(fd, argv);
initVirtulMachine();
init_symtab(fd, argv);
/* 初始化完毕 */
/* program: {glo_decl}+ */
program();
/* 如果没有main() */
if (!(PC = (long long *)symtab[0][348352625].In_value))
{
cout << "main() not defined" << endl;
return -1;
}
// dump_text();
if (assembly) {
// only for compile
return 0;
}
// 初始化虚拟机的栈,当 main 函数结束时退出进程
// stack位栈段,地址为栈底地址
SP = (long long *)((long long)(stack) + poolsize);
*--SP = EXIT; // call exit if main returns
*--SP = PUSH;
temp = SP;
*--SP = argc;
*--SP = (long long)(argv);
*--SP = (long long)(temp);
return eval();
}
| true |
2522bd65ff855956307ba92e56afdf5a7996813d | C++ | MasterAdminAlex21/sistemas-distribuidos | /proyect4_final/cliente.cpp | UTF-8 | 4,300 | 2.734375 | 3 | [] | no_license | //cliente que envia los datos
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netdb.h>
#include <strings.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
using namespace std;
int puerto = 9876;
int armonico=1;
struct coordenada{
int bandera;//0 para limpiar, 1 para imprimir
double x;
double y;
};
struct datos{
int s;
struct sockaddr_in addr;
};
//pthread_mutex_t semaforo;
void* generar(void *dato){//socket s,struct sockaddr_in addr){
//enviamos las coordenadas que se generan
while(1){
//pthread_mutex_lock(&semaforo);
printf("Empieza a generar\n");
struct datos *d=(struct datos*)dato;
double y1=M_PI/2;
for( double aux=-1;aux<=1;aux+=0.0001){
for(int i=1;i<=armonico;i++){
y1+=((4*sin(aux*((i*2)-1)*M_PI))/(M_PI*((i*2)-1)));
}
struct coordenada *c;
c=(struct coordenada*)malloc(sizeof(struct coordenada));
c->bandera=1;
c->x=aux;
c->y=y1;
sendto(d->s,(void*)c,sizeof(struct coordenada),0,(struct sockaddr*)&d->addr,sizeof(d->addr));
free(c);
char reply[10];
recvfrom(d->s,reply,sizeof(reply),0,(struct sockaddr*)&d->addr,(unsigned int*)sizeof(d->addr));
//printf("valores: x: %f\t y: %.16f\n",aux,c->y);*/
y1=M_PI/2;
//printf("Paquete enviado\n");
usleep(300);
}
//pthread_mutex_unlock(&semaforo);
if(armonico==50){
armonico=1;
}else{
armonico+=1;
}
//sleep(2);
}
//sleep(5);
//armonico+=1;
pthread_exit(0);
}
void* eliminar(void *dato){//socket s, struct sockaddr_in addr){
//aqui eliminamos los puntitos
while(1){
// pthread_mutex_lock(&semaforo);
printf("Empieza a borrar\n");
int arm=armonico;
struct datos *d=(struct datos*)dato;
double y1=M_PI/2;
for( double aux=-1;aux<1;aux+=0.0001){
for(int i=1;i<=arm;i++){
y1+=((4*sin(aux*((i*2)-1)*M_PI))/(M_PI*((i*2)-1)));
}
struct coordenada *c;
c=(struct coordenada*)malloc(sizeof(struct coordenada));
c->bandera=0;
c->x=aux;
c->y=y1;
sendto(d->s,(void*)c,sizeof(struct coordenada),0,(struct sockaddr*)&d->addr,sizeof(d->addr));
free(c);
char reply[10];
recvfrom(d->s,reply,sizeof(reply),0,(struct sockaddr*)&d->addr,(unsigned int*)sizeof(d->addr));
//printf("valores: x: %f\t y: %.16f\n",aux,y1);*/
y1=M_PI/2;
usleep(300);
}
//sleep(5);
/*
if(armonico==50){
armonico=1;
}else{
armonico+=1;
}*/
// pthread_mutex_unlock(&semaforo);
//sleep(2);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
if(argc!=2){
printf("uso: %s <ip_server>",argv[0]);
exit(0);
}
struct sockaddr_in msg_to_server_addr, client_addr;
int s;
s = socket(AF_INET, SOCK_DGRAM, 0);
/* rellena la dirección del servidor */
bzero((char *)&msg_to_server_addr, sizeof(msg_to_server_addr));
msg_to_server_addr.sin_family = AF_INET;
msg_to_server_addr.sin_addr.s_addr = inet_addr(argv[1]);//("10.100.70.252");
msg_to_server_addr.sin_port = htons(puerto);
/* rellena la direcciòn del cliente*/
bzero((char *)&client_addr, sizeof(client_addr));
client_addr.sin_family = AF_INET;
client_addr.sin_addr.s_addr = INADDR_ANY;
/*cuando se utiliza por numero de puerto el 0, el sistema se encarga de asignarle uno */
client_addr.sin_port = htons(0);
bind(s, (struct sockaddr *)&client_addr,sizeof(client_addr));
struct datos *d;
d=(struct datos*)malloc(sizeof(struct datos));
d->s=s;
d->addr=msg_to_server_addr;
printf("crea los hilos\n");
//aqui creamos los hilos
pthread_t envia,borra;
//pthread_mutex_init(&semaforo,NULL);
pthread_create(&envia,NULL,&generar,d);
sleep(6);
pthread_create(&borra,NULL,&eliminar,d);
pthread_join(envia,NULL);
pthread_join(borra,NULL);
//while(1){
//aqui enviamos las coordenadas
/*pthread_t envia;
pthread_create(&envia,NULL,&generar,d);
pthread_join(envia,NULL);
pthread_t borra;
pthread_create(&borra,NULL,&eliminar,d);
pthread_join(borra,NULL);
*/
//break;
//}
close(s);
}
| true |
3e3b2f628c628ad379fc8c79b5940564a395cb59 | C++ | Oroles/FSM | /components/state.h | UTF-8 | 495 | 2.984375 | 3 | [] | no_license | #ifndef _STATE_H_
#define _STATE_H_
#include <string>
#include <iostream>
#include <cassert>
class State
{
public:
State();
State(const std::string n);
State(const State& rhs);
State(State&& rhs);
State& operator=(const State& rhs);
bool operator==(const State& rhs) const;
bool operator!=(const State& rhs) const;
friend std::ostream& operator<<(std::ostream& o, const State& rhs);
std::string getName() const;
void setName(std::string n);
private:
std::string name;
};
#endif | true |
662239649f63ecb78291b697ca2d2ed3c90220ae | C++ | bruler/Notebook | /collection/cp/Algorithm_Collection-master/mininum_path_sum.cpp | UTF-8 | 612 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int> > a(m, vector<int>(n,0));
a[0][0] = grid[0][0];
for(int i=1;i<n;i++){
a[0][i] = a[0][i-1] + grid[0][i];
}
for(int i=1;i<m;i++){
a[i][0] = a[i-1][0] + grid[i][0];
}
for (int i=1; i<m;i++){
for(int j=1;j<n;j++){
a[i][j] = grid[i][j]+ min(a[i-1][j],a[i][j-1]);
}
}
return a[m-1][n-1];
}
};
| true |
1f7d5aa7a252e9a4ea31bc7f974569de2032ea88 | C++ | cdeister/csVisual | /microcontrollerCode/csAnalogCapSenseWHWRelay/csAnalogCapSenseWHWRelay.ino | UTF-8 | 1,388 | 3.015625 | 3 | [
"MIT"
] | permissive | /* ~~~~ Teensey Analog Cap Relay ~~~~
Notes: Teensey 3.6 has two built in 12 bit dacs.
Teensey(s) LC,3.1/2, 3.5 have built in cap sensing.
The cap sensing is awesome! But, it is blocking.
So, I sense on a 3.6 teensy and use its nice dacs to stream analog version of the data.
This assumes you are using a 3.6 and wanting to convert two cap reads to an anlaog signal.
v1.0
cdeister@brown.edu
*/
#define tSer Serial1
const int capSensPinL = 29;
const int capSensPinR = 30;
const int dacPinL=A22;
const int dacPinR=A21;
int lickValA = 0;
int lickValB = 0;
int writeValA = 0;
int writeValB = 0;
// teensey cap is 16 bit so max val is 65535;
int maxCapVal = 65536;
int minCapVal = 0;
// teensey dac can do 12 bit of 3.3V.
// so let's round and assume 0.000-3.299 V range
int minDACVal=0;
int maxDACVal=3299;
void setup() {
analogWriteResolution(12);
Serial.begin(9600);
tSer.begin(9600);
}
void loop() {
if (Serial.available()) {
Serial1.write(Serial.read());
}
if (Serial1.available()) {
Serial.write(Serial1.read());
}
// read, map teensey vals into
lickValA = touchRead(capSensPinL);
writeValA = map(lickValA, minCapVal, maxCapVal, minDACVal, maxDACVal);
analogWrite(dacPinL, lickValA);
lickValB = touchRead(capSensPinR);
writeValB = map(lickValB, minCapVal, maxCapVal, minDACVal, maxDACVal);
analogWrite(dacPinR, lickValB);
}
| true |
664553e03732eefbc3ffd4008453f285a111cb3e | C++ | eduardohmrodrigues/competitive-programming | /UVa/cpp/11340.cpp | UTF-8 | 541 | 3.046875 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
void clear(double price[256]){
for(int i=0; i<256; i++){
price[i] = 0;
}
}
int main(){
double price[256], value;
int n, k, m;
char c;
std::string str;
std::cin >> n;
while(n--){
clear(price);
std::cin >> k;
while(k--){
std::cin >> c >> value;
price[c] = value;
}
scanf("%d%*c", &m);
value = 0;
while(m--){
std::getline(std::cin, str);
for(int i=0; i<str.length(); i++){
value += price[str[i]];
}
}
printf("%.2lf$\n", value/100.0);
}
return 0;
}
| true |
83228db1ff335e12bbe28c44693465305ae4a509 | C++ | VanKhaos/CPlusPlus_2020 | /Projects/Aufgaben/Aufgabe 16 - Summe bilden und Mittelwert berechnen/Aufgabe 16 - Summe bilden und Mittelwert berechnen.cpp | UTF-8 | 946 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include "../../lib/abfragewiederholung.h"
using namespace std;
int Fehlercode = 0;
bool abfrageWiederholung(char weiter = 'j');
double berechneSumme(double& mittelwert, double liste[], int anzahl) {
double summe = 0;
for (int i = 0; i < anzahl; i = i + 1) {
// ALTERNATIV
// summe += liste[i];
summe = summe + liste[i];
}
mittelwert = summe / anzahl;
return summe;
}
int main() {
bool Bedingung = false;
char Weiter = 'j';
// Daten für die Funktion
double liste[10] = { 1.1, 1.4, 2.3 };
int anzahl = 3;
double mittelwert, summe;
do {
// AUFRUF
summe = berechneSumme(mittelwert, liste, anzahl);
// AUSGABE
cout << "Mittelwert: " << mittelwert << endl;
cout << "Summe: " << summe << endl;
Bedingung = abfrageWiederholung();
} while (Bedingung);
return Fehlercode;
}
| true |
130203a95ffe53a6ae2629481fb8227b26e7e43c | C++ | RuiqingQiu/CSE165_Projects | /Sphere.cpp | UTF-8 | 1,407 | 2.625 | 3 | [] | no_license | //
// Sphere.cpp
// CSE167HW1
//
// Created by Ruiqing Qiu on 11/10/14.
// Copyright (c) 2014 Ruiqing Qiu. All rights reserved.
//
#include "Sphere.h"
#include "main.h"
Sphere::Sphere(){
//center_c = Vector4(0, 0, 0, 1);
center = Vector4(0, 0, 0, 1);
scale = Vector4(0.5, 0.5, 0.5, 0);
radius = 2;
}
void Sphere::render(){
glColor3f(color.x, color.y, color.z);
glutSolidSphere(1.0, 20.0, 20.0);
}
void Sphere::update(){
}
void Sphere::updateColor(Vector3 color_a){
color = color_a;
}
void Sphere::BoundBox(Matrix4 C){
//cout << Globals::boundOn << endl;
center = Vector4(0, 0, 0, 1);
scale = Vector4(0.5, 0.5, 0.5, 0);
Vector4 new_center = C * center;
Vector4 new_scale = C * scale;
center = new_center;
scale = new_scale;
double magnitude = new_scale.length();
radius = magnitude;
glPushMatrix();
Matrix4 trans = Matrix4(Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1), Vector3(new_center.x, new_center.y, new_center.z));
Matrix4 scaling = Matrix4(Vector3(magnitude, 0, 0), Vector3(0, magnitude, 0), Vector3(0,0, magnitude), Vector3(0, 0, 0));
Matrix4 glmatrix = trans * scaling;
glmatrix.transpose();
glLoadMatrixd(glmatrix.getPointer());
glColor3f(color.x, color.y, color.z);
glutWireSphere(1.2, 20, 20);
glPopMatrix();
}
| true |
89cff1437fe413be9efa35d3595d185abeae09b8 | C++ | nabilalimura/HALLO-I-M-NABIL-ALIMURA | /Konversi Waktu.cpp | UTF-8 | 429 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main ()
{
int idetik,detik,hari,jam,menit,dtk1,dtk2;
cout<<"PROGRAM KONVERSI WAKTU"<<endl;
cout<<"MASUKKAN DETIK = ";
cin>>idetik;
hari=idetik/86400;
dtk1=idetik%86400;
jam=dtk1/3600;
dtk2=dtk1%3600;
menit=dtk2/60;
detik=dtk2%60;
cout<<"HARI = "<<hari<<endl;
cout<<"JAM = "<<jam<<endl;
cout<<"MENIT = "<<menit<<endl;
cout<<"DETIK = "<<detik<<endl;
}
| true |
57ce4daa1ec641ea2149dd382584f1eda5e621d4 | C++ | HeyChobe/Portafolio_00204119 | /Laboratorios/Laboratorio 1/17.cpp | UTF-8 | 424 | 3.734375 | 4 | [] | no_license | //Ejercicio 17
#include <iostream>
using namespace std;
int suma(){
int entero[10], i=0, promedio=0, suma=0;
cout<<"---Digite 10 numeros enteros---"<<endl;
while(i!=10){
cout<<"Ingrese el "<<i+1<<" entero: ";
cin>>entero[i];
suma=entero[i]+suma;
i++;
}
promedio=suma/10;
cout<<"Suma de los enteros: "<<suma<<endl;
cout<<"Promedio de los enteros: "<<promedio<<endl;
}
int main(){
suma();
return 0;
}
| true |
79fe7a7f02aed1e337abc6cc318b93db07dfdb51 | C++ | BiPaulEr/Rendering_PhotorealisticShaders | /Sources/Mesh.cpp | UTF-8 | 6,189 | 3.0625 | 3 | [] | no_license | #define _USE_MATH_DEFINES
#include "Mesh.h"
#include <cmath>
#include <algorithm>
#include <iostream>
#include <limits>
using namespace std;
Mesh::~Mesh () {
clear ();
}
void Mesh::computeBoundingSphere (glm::vec3 & center, float & radius) const {
center = glm::vec3 (0.0);
radius = 0.f;
for (const auto & p : m_vertexPositions)
center += p;
center /= m_vertexPositions.size ();
for (const auto & p : m_vertexPositions)
radius = std::max (radius, distance (center, p));
}
void Mesh::recomputePerVertexNormals (bool angleBased) {
m_vertexNormals.clear ();
// Change the following code to compute a proper per-vertex normal
m_vertexNormals.resize (m_vertexPositions.size (), glm::vec3 (0.0, 0.0, 0.0));
glm::vec3 p0;
glm::vec3 p1;
glm::vec3 p2;
float angle0;
float angle1;
float angle2;
glm::vec3 normal;
std::vector<glm::vec3> vertexIncidentNormalsSum;
vertexIncidentNormalsSum.resize(m_vertexPositions.size (), glm::vec3 (0.0, 0.0, 0.0));
std::vector<float> vertexIncidentAnglesSum;
vertexIncidentAnglesSum.resize(m_vertexPositions.size (), 0.0);
for (int i = 0; i < m_triangleIndices.size (); i++) {
p0 = m_vertexPositions[m_triangleIndices[i][0]];
p1 = m_vertexPositions[m_triangleIndices[i][1]];
p2 = m_vertexPositions[m_triangleIndices[i][2]];
if (angleBased) {
angle0 = acos(dot(normalize(p1-p0), normalize(p2-p0)));
angle1 = acos(dot(normalize(p2-p1), normalize(p0-p1)));
angle2 = acos(dot(normalize(p0-p2), normalize(p1-p2)));
}
else {
angle0 = 1;
angle1 = 1;
angle2 = 1;
}
normal = normalize(cross(p1-p0, p2-p0));
vertexIncidentNormalsSum[m_triangleIndices[i][0]] += angle0*normal;
vertexIncidentNormalsSum[m_triangleIndices[i][1]] += angle1*normal;
vertexIncidentNormalsSum[m_triangleIndices[i][2]] += angle2*normal;
vertexIncidentAnglesSum[m_triangleIndices[i][0]] += angle0;
vertexIncidentAnglesSum[m_triangleIndices[i][1]] += angle1;
vertexIncidentAnglesSum[m_triangleIndices[i][2]] += angle2;
}
for (int i = 0; i < m_vertexNormals.size (); i++) {
//m_vertexNormals[i] = (1/vertexIncidentAnglesSum[i])*vertexIncidentNormalsSum[i];
m_vertexNormals[i] = normalize(vertexIncidentNormalsSum[i]);
}
}
void Mesh::init () {
glCreateBuffers (1, &m_posVbo); // Generate a GPU buffer to store the positions of the vertices
size_t vertexBufferSize = sizeof (glm::vec3) * m_vertexPositions.size (); // Gather the size of the buffer from the CPU-side vector
glNamedBufferStorage (m_posVbo, vertexBufferSize, NULL, GL_DYNAMIC_STORAGE_BIT); // Create a data store on the GPU
glNamedBufferSubData (m_posVbo, 0, vertexBufferSize, m_vertexPositions.data ()); // Fill the data store from a CPU array
glCreateBuffers (1, &m_normalVbo); // Same for normal
glNamedBufferStorage (m_normalVbo, vertexBufferSize, NULL, GL_DYNAMIC_STORAGE_BIT);
glNamedBufferSubData (m_normalVbo, 0, vertexBufferSize, m_vertexNormals.data ());
glCreateBuffers (1, &m_texCoordVbo); // Same for texture coordinates
size_t texCoordBufferSize = sizeof (glm::vec2) * m_vertexTexCoords.size ();
glNamedBufferStorage (m_texCoordVbo, texCoordBufferSize, NULL, GL_DYNAMIC_STORAGE_BIT);
glNamedBufferSubData (m_texCoordVbo, 0, texCoordBufferSize, m_vertexTexCoords.data ());
glCreateBuffers (1, &m_ibo); // Same for the index buffer, that stores the list of indices of the triangles forming the mesh
size_t indexBufferSize = sizeof (glm::uvec3) * m_triangleIndices.size ();
glNamedBufferStorage (m_ibo, indexBufferSize, NULL, GL_DYNAMIC_STORAGE_BIT);
glNamedBufferSubData (m_ibo, 0, indexBufferSize, m_triangleIndices.data ());
glCreateVertexArrays (1, &m_vao); // Create a single handle that joins together attributes (vertex positions, normals) and connectivity (triangles indices)
glBindVertexArray (m_vao);
glEnableVertexAttribArray (0);
glBindBuffer (GL_ARRAY_BUFFER, m_posVbo);
glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof (GLfloat), 0);
glEnableVertexAttribArray (1);
glBindBuffer (GL_ARRAY_BUFFER, m_normalVbo);
glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof (GLfloat), 0);
glEnableVertexAttribArray (2);
glBindBuffer (GL_ARRAY_BUFFER, m_texCoordVbo);
glVertexAttribPointer (2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof (GLfloat), 0);
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBindVertexArray (0); // Desactive the VAO just created. Will be activated at rendering time.
}
void Mesh::render () {
glBindVertexArray (m_vao); // Activate the VAO storing geometry data
glDrawElements (GL_TRIANGLES, static_cast<GLsizei> (m_triangleIndices.size () * 3), GL_UNSIGNED_INT, 0); // Call for rendering: stream the current GPU geometry through the current GPU program
}
void Mesh::clear () {
m_vertexPositions.clear ();
m_vertexNormals.clear ();
m_vertexTexCoords.clear ();
m_triangleIndices.clear ();
if (m_vao) {
glDeleteVertexArrays (1, &m_vao);
m_vao = 0;
}
if(m_posVbo) {
glDeleteBuffers (1, &m_posVbo);
m_posVbo = 0;
}
if (m_normalVbo) {
glDeleteBuffers (1, &m_normalVbo);
m_normalVbo = 0;
}
if (m_texCoordVbo) {
glDeleteBuffers (1, &m_texCoordVbo);
m_texCoordVbo = 0;
}
if (m_ibo) {
glDeleteBuffers (1, &m_ibo);
m_ibo = 0;
}
}
void Mesh::computePlanarParameterization() {
float xMin = numeric_limits<float>::max();
float xMax = -numeric_limits<float>::max();
float yMin = numeric_limits<float>::max();
float yMax = -numeric_limits<float>::max();
//determining the positions min and max for x and y among the vertices of the mesh
for (int i = 0; i < m_vertexPositions.size (); i++) {
if (m_vertexPositions[i][0] < xMin) {
xMin = m_vertexPositions[i][0];
}
if (m_vertexPositions[i][0] > xMax) {
xMax = m_vertexPositions[i][0];
}
if (m_vertexPositions[i][1] < yMin) {
yMin = m_vertexPositions[i][1];
}
if (m_vertexPositions[i][1] > yMax) {
yMax = m_vertexPositions[i][1];
}
}
//to compute U and V (texture coordinates), we do a linear parametrization of X and Y (vertex coordinates)
for (int i = 0; i < m_vertexTexCoords.size (); i++) {
m_vertexTexCoords[i][0] = (m_vertexPositions[i][0] - xMin)/(xMax - xMin);
m_vertexTexCoords[i][1] = (m_vertexPositions[i][1] - yMin)/(yMax - yMin);
}
}
| true |
78c9a54b206fc4a5a8857c06639d105773edbdaa | C++ | Exxxasens/Programming | /Practice/03/С++/Project/Project.cpp | UTF-8 | 1,218 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
setlocale(LC_ALL, "Rus");
int a, b;
cout << "Введите пару int int" << endl;
cin >> a >> b;
cout << "Сложение: " << a + b << endl;
cout << "Вычитание: " << a - b << endl;
cout << "Умножение: " << a * b << endl;
cout << "Деление: " << a / b << endl;
int c;
double d;
cout << "Введите пару int double" << endl;
cin >> c >> d;
cout << "Сложение: " << c + d << endl;
cout << "Вычитание: " << c - d << endl;
cout << "Умножение: " << c * d << endl;
cout << "Деление: " << c / d << endl;
double e, f;
cout << "Введите пару double double" << endl;
cin >> e >> f;
cout << "Сложение: " << e + f << endl;
cout << "Вычитание: " << e - f << endl;
cout << "Умножение: " << e * f << endl;
cout << "Деление: " << e / f << endl;
double g;
int h;
cout << "Введите пару double int" << endl;
cin >> g >> h;
cout << "Сложение: " << g + h << endl;
cout << "Вычитание: " << g - h << endl;
cout << "Умножение: " << g * h << endl;
cout << "Деление: " << g / h;
return 0;
} | true |
11056a4669f4cfbb8f7a7a721671d98a45e77038 | C++ | kaiser4900/LP2 | /sort_abstrac/insert.inl | UTF-8 | 545 | 3.15625 | 3 | [] | no_license | template <class T>
void insert<T> :: fsort(T *A, int n)
{
for(int i=1; i<n; i++)
{
int temp = A[i];
int min_ = 0;
int n = i-1;
while(min_ <= n)
{
int m = (min_+n)/2;
if (temp < A[m])
n = m - 1;
else
min_ = m + 1;
}
for (int j=i-1; j>=min_; j--)
{
A[j+1]=A[j];
}
A[min_] = temp;
}
}
template<class T>
insert<T> ::~insert()
{
delete [] A;
}
| true |
01fb15fc23a078cf655226d4b07d13402368708a | C++ | fish-ball/acm.zju.edu.cn | /25XX/zoj.2572.src.1.cpp | GB18030 | 3,625 | 2.6875 | 3 | [] | no_license | // 2959007 2008-06-30 23:12:00 Accepted 2572 C++ 00:00.21 1412K ͵
// С̬ģ⣬һ DFS DFS ˣˣûɶѵ
// עʽԼ PE ⣬עͱˣ PE
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool visited[100][100];
bool agree[128][128];
int color[100][100];
int N, M, Q, X, Y, C;
vector<string> V;
const int D[8][2] = {
{ -1, 0 },
{ 1, 0 },
{ 0, 1 },
{ 0, -1 },
{ -1, 1 },
{ 1, -1 },
{ 1, 1 },
{ -1, -1 }
};
const char* T = "||--//\\\\";
inline bool isValid( int x, int y ) {
return x >= 0 && x < N &&
y >= 0 && y < V[x].size();
}
void paint( int x, int y, const int& c, char type ) {
if( !agree[type][V[x][y]] ) return;
visited[x][y] = true;
color[x][y] = c;
int i, j;
switch( V[x][y] ) {
case '|': i = 0; j = 1; break;
case '-': i = 2; j = 3; break;
case '/': i = 4; j = 5; break;
case '\\': i = 6; j = 7; break;
case '+': i = 0; j = 3; break;
case 'X': i = 4; j = 7; break;
case '*': i = 0; j = 7; break;
}
while( i <= j ) {
int dx = x + D[i][0],
dy = y + D[i][1];
if( isValid( dx, dy ) && !visited[dx][dy] )
paint( dx, dy, c, T[i] );
++i;
}
}
void draw() {
string temp;
int clr;
for( int i = 0; i < V.size(); ++i ) {
temp.erase();
clr = -1;
for( int j = 0; j < V[i].size(); ++j ) {
if( color[i][j] == clr )
temp += V[i][j];
else {
if( clr == -1 )
cout << temp;
else
cout << "[m" << clr << temp << "m]";
clr = color[i][j];
temp.erase();
temp += V[i][j];
}
}
if( clr == -1 )
cout << temp;
else
cout << "[m" << clr << temp << "m]";
cout << endl;
}
// cout << endl;
}
int main() {
memset( agree, 0, sizeof( agree ) );
agree['-']['-'] = agree['-']['+'] = agree['-']['*'] =
agree['|']['|'] = agree['|']['+'] = agree['|']['*'] =
agree['\\']['\\'] = agree['\\']['X'] = agree['\\']['*'] =
agree['/']['/'] = agree['/']['X'] = agree['/']['*'] =
agree['+']['+'] = agree['+']['-'] = agree['+']['|'] = agree['+']['*'] =
agree['X']['X'] = agree['X']['/'] = agree['X']['\\'] = agree['X']['*'] =
agree['*']['*'] = agree['*']['+'] = agree['*']['X'] =
agree['*']['-'] = agree['*']['|'] = agree['*']['/'] =
agree['*']['\\'] = true;
while( cin >> N >> M ) {
V.resize( N );
getline( cin, V[0] );
for( int i = 0; i < N; ++i ) {
getline( cin, V[i] );
// ҿطԭͺãͼĶκйؿոΪֻᵼ PE
// V[i].erase( V[i].find_last_not_of( ' ' ) + 1 );
}
// You can assume that no character will be colored twice.
// ˵ÿͿɫһΣֻʼһηʱǼ
memset( color, -1, sizeof( color ) );
memset( visited, 0, sizeof( visited ) );
for( cin >> Q; Q--; ) {
cin >> X >> Y >> C;
if( isValid( X, Y ) )
paint( X, Y, C, V[X][Y] );
}
draw();
}
}
| true |
8b0131fe9721af93876836254e193255d2fa9e15 | C++ | Korshikov/cpp | /computersince/aads/ht6/A/main.cpp | UTF-8 | 482 | 2.515625 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
#include <climits>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main() {
freopen("incrementator.in","r",stdin);
//freopen("incrementator.out","w+",stdout);
std::unordered_map<string, int> mymap;
char var[100000];
int delta;
while (scanf("%s %d\n",var,&delta) != EOF)
{
printf("%d\n",mymap[string(var)]+=delta);
}
fclose(stdin);
fclose(stdout);
return 0;
}
| true |
aceb9fec266c2b6f098ddd27c38e40061afe719b | C++ | matthewcpp/recondite | /include/ui/ruiEvents.hpp | UTF-8 | 2,322 | 2.5625 | 3 | [] | no_license | #ifndef RUI_EVENTS_HPP
#define RUI_EVENTS_HPP
#include "rEvent.hpp"
#include "rEventHandler.hpp"
#include "input/rMouse.hpp"
#include "ui/ruiMenu.hpp"
#include "input/rKeyboard.hpp"
class ruiWidget;
enum ruiEventType{
ruiEVT_MOUSE_DOWN,
ruiEVT_MOUSE_UP,
ruiEVT_MOUSE_MOTION,
ruiEVT_MOUSE_WHEEL,
ruiEVT_MOUSE_ENTER,
ruiEVT_MOUSE_LEAVE,
ruiEVT_KEY_DOWN,
ruiEVT_KEY_UP,
ruiEVT_TOUCH_DOWN,
ruiEVT_TOUCH_MOVE,
ruiEVT_TOUCH_UP,
ruiEVT_MENU,
ruiEVENT_BUTTON_CLICK,
ruiEVENT_CHECKBOX_CHANGE,
ruiEVENT_SLIDER_CHANGE,
ruiEVENT_SLIDER_DRAG_BEGIN,
ruiEVENT_SLIDER_DRAG_MOVE,
ruiEVENT_SLIDER_DRAG_END,
ruiEVENT_PICKER_CHANGE
};
class ruiMouseEvent : public rEvent{
public:
ruiMouseEvent(const rPoint& position) : m_button(rMOUSE_BUTTON_NONE), m_buttonState(rBUTTON_STATE_NONE), m_position(position), m_wheelDirection(rMOUSEWHEEL_NONE){}
ruiMouseEvent(rMouseButton button, rButtonState buttonState, const rPoint& position) : m_button(button), m_buttonState(buttonState), m_position(position), m_wheelDirection(rMOUSEWHEEL_NONE) {}
ruiMouseEvent(rMouseWheelDirection wheelDirection, const rPoint& position) : m_button(rMOUSE_BUTTON_NONE), m_buttonState(rBUTTON_STATE_NONE), m_position(position), m_wheelDirection(wheelDirection){}
rMouseButton Button() const {return m_button;}
rMouseWheelDirection WheelDirection() const {return m_wheelDirection;}
rPoint Position () const {return m_position;}
private:
rMouseButton m_button;
rPoint m_position;
rMouseWheelDirection m_wheelDirection;
rButtonState m_buttonState;
};
class ruiWidgetEvent : public rEvent{
public:
ruiWidgetEvent(ruiWidget* widget) : m_widget(widget){}
ruiWidget* Widget() const { return m_widget; }
private:
ruiWidget* m_widget;
};
class ruiMenuEvent : public rEvent{
public:
ruiMenuEvent(ruiMenu* menu, int selection): m_menu(menu), m_selection(selection) {}
ruiMenu* Menu() const {return m_menu;}
int Selection() const {return m_selection;}
private:
ruiMenu* m_menu;
int m_selection;
};
class ruiKeyEvent : public rEvent{
public:
ruiKeyEvent(rKey key, rKeyState state) : _key(key), _state(state){}
rKey Key() const { return _key; }
rKeyState State() const { return _state; }
private:
rKey _key;
rKeyState _state;
};
#endif | true |
80d1c98fcd64c76f3d69d02203da04b0ccc590c0 | C++ | sypark0720/Visual-SLAM | /plane_ransac/plane_ransac.cpp | UTF-8 | 2,870 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <time.h>
#include <tuple>
#include <vector>
using namespace std;
struct Point3 {
double x;
double y;
double z;
};
// Hint: Given p1, p2, p3, the plane normal from the 3 points is (p1-p2) X (p1-p3), X is cross product.
// Given the points and the plane(depicted by 3 point indices),
// find the inliers and store the indices into inlier_points.
void FindInlier(const std::vector<Point3>& points, double threshold,
int idx1, int idx2, int idx3, std::vector<int>& inlier_points) {
// compute normal vector;
Point3 p1 ;
p1.x = points[idx1].x-points[idx2].x;
p1.y = points[idx1].y-points[idx2].y;
p1.z = points[idx1].z-points[idx2].z;
Point3 p2;
p2.x = points[idx1].x-points[idx3].x;
p2.y = points[idx1].y-points[idx3].y;
p2.z = points[idx1].z-points[idx3].z;
Point3 normal_vector;
normal_vector.x = p1.y*p2.z-p1.z*p2.y;
normal_vector.y = p1.z*p2.x-p1.x*p2.z;
normal_vector.z = p1.x*p2.y-p1.y*p2.x;
for(int i=0; i< points.size();i++){
double pt[3] = {points[i].x-points[idx1].x,
points[i].y-points[idx1].y,
points[i].z-points[idx1].z};
double d = (double)(normal_vector.x*pt[0]+normal_vector.y*pt[1]+normal_vector.z*pt[2])
/sqrt(normal_vector.x*normal_vector.x+normal_vector.y*normal_vector.y+normal_vector.z*normal_vector.z);
if(abs(d) < threshold)
inlier_points.push_back(i);
}
}
void PlaneRANSAC(const std::vector<Point3>& points,
double threshold, int iteration, std::vector<int>& inlier_points) {
int iterator_num = 0;
int N = points.size();
int idx1, idx2,idx3;
while(iterator_num < iteration){
iterator_num++;
inlier_points.clear();
//select 3 different points
srand((int)time(0));
idx1 = rand()%N;
while(1){
idx2 = rand()%N;
if(idx2!=idx1)
break;
}
while(1){
idx3 = rand()%N;
if(idx3!=idx2 && idx3!=idx1)
break;
}
FindInlier(points, threshold, idx1, idx2, idx3, inlier_points);
if(inlier_points.size()>0.7*N)
break;
}
}
int main() {
srand(time(0));
std::vector<Point3> points;
Point3 p;
double a = 1, b = 2, c = 3;
// Generate ax + by + cz = 1;
for (int i = 0; i < 20; ++i) {
p.x = (double)rand()/(double)RAND_MAX;
p.y = (double)rand()/(double)RAND_MAX;
p.z = (1.0 - a*p.x - b*p.y) / c;
points.push_back(p);
}
// Insert outlier points
for (int i = 0; i < 5; ++i) {
p.x = (double)rand()/(double)RAND_MAX;
p.y = (double)rand()/(double)RAND_MAX;
p.z = (1.0 - a*p.x - b*p.y) / c + 100.0;
points.push_back(p);
}
std::vector<int> inlier_indices;
PlaneRANSAC(points, 0.1, 20, inlier_indices);
for (int i = 0; i < inlier_indices.size(); ++i) {
cout << inlier_indices[i] << endl;
}
return 0;
}
| true |
e414c5dcc2b5cc55d5165cc2e4946ba18cc4622a | C++ | MCJack123/LinuxCC | /textutils.cpp | UTF-8 | 3,512 | 2.796875 | 3 | [] | no_license | #include "textutils.hpp"
#include "term.hpp"
#include "math.hpp"
#include "os.hpp"
#include <unistd.h>
#include <typeinfo>
#include <sstream>
#include <iomanip>
TextutilsAPI textutils;
int tabulate(std::vector<string> v, int x, int y) {
int max = 0;
for (int i = 0; i < v.size() && i < y + term.getSize().second; i++) {
term.setCursorPos(x, y + i);
term.write(v[i]);
if (v[i].size() > max) max = v[i].size();
}
return x + max + 1;
}
void TextutilsAPI::slowWrite(string text, int rate) {
for (char c : text) {
term.write(string(&c, 1));
usleep(1000000 / rate);
}
}
string TextutilsAPI::formatTime(double time, bool hour24) {
int hour = math.floor(time);
if (hour < 6) hour += 18;
else hour -= 6;
int minute = ((int)(time * 1000) % 1000) / (1000.0/60.0);
if (hour24) return string(std::to_string(hour) + ":" + std::to_string(minute));
else {
bool pm = hour >= 12;
int newHour = hour % 12;
if (hour == 0) hour = 12;
return string(std::to_string(newHour) + ":" + std::to_string(minute) + (pm ? " PM" : " AM"));
}
}
template <typename T, typename ... Args>
void TextutilsAPI::tabulate(T first, Args... args) {
if (typeid first == typeid int) term.setTextColor(first);
else {
int y = term.getCursorPos().second;
_tabulate(::tabulate(first, 0, y), y, args...);
}
}
template<typename T, typename ... Args>
void _tabulate(int x, int y, T first, Args... args) {
int next = x;
if (typeid first == typeid int) term.setTextColor(first);
else next = ::tabulate(first, x, y);
_tabulate(next, y, args...);
}
template<typename T>
void _tabulate(int x, int y, T first) {
if (typeid first == typeid int) term.setTextColor(first);
else ::tabulate(first, x, y);
}
template <typename T, typename ... Args>
void TextutilsAPI::pagedTabulate(T first, Args... args) {
// soon(tm)
}
int TextutilsAPI::pagedPrint(string text, int freeLines) {
std::stringstream ss(text);
string s;
int lines;
for (lines = 0; lines < freeLines; lines++) {
if (!std::getline(ss, s)) return lines;
print(s);
}
while (true) {
if (!std::getline(ss, s)) return lines;
print(s);
lines++;
if (!std::getline(ss, s)) return lines;
print(s);
lines++;
term.write("Press any key to continue");
os.pullEvent("key");
term.clearLine();
}
}
template <typename T>
string TextutilsAPI::serialize(T value) {
Json::Value v(value);
std::stringstream ss;
ss << v;
return ss.str();
}
Json::Value TextutilsAPI::unserialize(string value) {
Json::Value v;
std::stringstream ss(value);
ss >> v;
return v;
}
string TextutilsAPI::urlEncode(string value) {
// stolen shamelessly from stackoverflow (credit to xperroni)
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << std::uppercase;
escaped << '%' << std::setw(2) << int((unsigned char) c);
escaped << std::nouppercase;
}
return escaped.str();
} | true |
9f84ac8f4fd0b2ce525d2e278a150aaa15f21251 | C++ | Robert-Mellberg/Kattis-solutions | /Easy (1-3p)/Bus(1,7p).cpp | UTF-8 | 837 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <map>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
using namespace std;
//https://open.kattis.com/problems/bus
//Solve by approaching the problem from the end. At the last stop there are 0 people, the stop before that (0+0,5)*2 = 1,
//the stop before that (1+0,5)*2 etc.
int main()
{
int cases;
cin >> cases;
for (int i = 1; i <= cases; i++) {
int initialPassengers = 0;
int stops;
cin >> stops;
for (int p = 0; p < stops; p++) {
initialPassengers = initialPassengers * 2 + 1;
}
cout << initialPassengers << "\n";
}
return 0;
}
| true |
476cae9655f5f97a6eb844744222c5d7dbe76480 | C++ | a1tSign/swengine | /sources/Engine/Components/GUI/Widgets/GUIImage.cpp | UTF-8 | 730 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "GUIImage.h"
#include <Engine/assertions.h>
GUIImage::GUIImage(Texture * image)
: m_image(image)
{
}
GUIImage::~GUIImage()
{
}
Texture* GUIImage::getImage() const
{
return m_image;
}
void GUIImage::setImage(Texture* image)
{
_assert(image != nullptr);
m_image = image;
}
void GUIImage::render(GeometryInstance* quad, GpuProgram* program)
{
m_image->bind(0);
program->setParameter("transform.localToWorld", getTransformationMatrix());
program->setParameter("quad.texture", 0);
program->setParameter("quad.useTexture", true);
program->setParameter("quad.useFirstChannel", false);
quad->draw(GeometryInstance::DrawMode::Triangles, 0, 6);
}
void GUIImage::update(const MousePosition & mousePosition)
{
}
| true |
65461e6962dc90adf48aed56d80c9c6ad1f6e2eb | C++ | Flower35/ZookieWizard | /source/ElephantEngine/Namespace.cpp | UTF-8 | 4,950 | 2.734375 | 3 | [] | no_license | #include <ElephantEngine/Namespace.h>
#include <ElephantBase/Archive.h>
namespace ZookieWizard
{
////////////////////////////////////////////////////////////////
// Namespace interface
// <kao2.0059D160> (constructor)
// <kao2.0059D2B0> (destructor)
////////////////////////////////////////////////////////////////
TypeInfo E_NAMESPACE_TYPEINFO
(
E_NAMESPACE_ID,
"Namespace",
&E_STATE_TYPEINFO,
[]() -> eObject*
{
return new Namespace;
}
);
const TypeInfo* Namespace::getType() const
{
return &E_NAMESPACE_TYPEINFO;
}
Namespace::Namespace()
: State("", nullptr)
{
clearNewNamespace();
}
Namespace::~Namespace()
{
if (nullptr != nodeRefNames)
{
delete[](nodeRefNames);
}
unknown_0078->decRef();
}
////////////////////////////////////////////////////////////////
// Namespace: cloning the object
////////////////////////////////////////////////////////////////
void Namespace::createFromOtherObject(const Namespace &other)
{
throw ErrorMessage
(
"CRITICAL ERROR while cloning the \"Namespace\" object:\n" \
"cloning << namespaces >> without context is not supported!!!"
);
}
Namespace::Namespace(const Namespace &other)
: State(other)
{
clearNewNamespace();
/****************/
createFromOtherObject(other);
}
Namespace& Namespace::operator = (const Namespace &other)
{
if ((&other) != this)
{
State::operator = (other);
/****************/
createFromOtherObject(other);
}
return (*this);
}
eObject* Namespace::cloneFromMe() const
{
return new Namespace(*this);
}
////////////////////////////////////////////////////////////////
// Namespace: serialization
// <kao2.0059D3D0>
////////////////////////////////////////////////////////////////
void Namespace::serialize(Archive &ar)
{
int32_t i;
if (ar.getVersion() <= 0x88)
{
exportable = true;
/* [0x78] unknown */
ArFunctions::serialize_eRefCounter(ar, (eRefCounter**)&unknown_0078, &E_NAMESPACE_TYPEINFO);
/* State */
State::serialize(ar);
/* [0x80] The "persistent" modifier */
if (ar.getVersion() >= 0x7B)
{
ar.readOrWrite(&isPersistent, 0x01);
}
else
{
isPersistent = false;
}
}
else if (ar.getVersion() >= 0x89)
{
State::serialize(ar);
/* [0x78/0x7C] unknown */
ArFunctions::serialize_eRefCounter(ar, (eRefCounter**)&unknown_0078, &E_NAMESPACE_TYPEINFO);
/* [0x80/0x84] unknown */
ar.readOrWrite(&isPersistent, 0x01);
/* [0x88] unknown */
ar.readOrWrite(&unknown_0088, 0x04);
/* [0x8C] unknown */
ar.readOrWrite(&unknown_008C, 0x04);
/* [0x90] NodeRef names in Scene */
if (ar.isInReadMode())
{
if (nullptr != nodeRefNames)
{
delete[](nodeRefNames);
nodeRefNames = nullptr;
nodeRefNames_maxLength = 0;
nodeRefNames_count = 0;
}
ar.readOrWrite(&nodeRefNames_maxLength, 0x04);
nodeRefNames = new eString [nodeRefNames_maxLength];
for (i = 0; i < nodeRefNames_maxLength; i++)
{
ar.serializeString(nodeRefNames[i]);
nodeRefNames_count = (i+1);
}
}
else
{
ar.readOrWrite(&nodeRefNames_count, 0x04);
for (i = 0; i < nodeRefNames_count; i++)
{
ar.serializeString(nodeRefNames[i]);
}
}
}
}
////////////////////////////////////////////////////////////////
// Namespace: is the script ready to be exported?
////////////////////////////////////////////////////////////////
bool Namespace::canBeExported() const
{
/* Only scripts from the Retail version of KAO2 are supported */
return exportable;
}
////////////////////////////////////////////////////////////////
// Namespace: clear this object
////////////////////////////////////////////////////////////////
void Namespace::clearNewNamespace()
{
/*[0x78]*/ unknown_0078 = nullptr;
/*[0x80]*/ isPersistent = false;
nodeRefNames_count = 0;
nodeRefNames_maxLength = 0;
nodeRefNames = nullptr;
exportable = false;
}
}
| true |
868a07877359826d9f7882a4343a4dc80c1d5bde | C++ | IonutCava/Divide-Framework | /3rdParty/boost/boost/process/v2/execute.hpp | UTF-8 | 3,920 | 2.65625 | 3 | [
"LicenseRef-scancode-proprietary-license",
"BSL-1.0",
"MIT",
"LGPL-3.0-only",
"GPL-3.0-only",
"MPL-2.0",
"BSD-3-Clause",
"GPL-2.0-only"
] | permissive | // Copyright (c) 2022 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_PROCESS_V2_EXECUTE_HPP
#define BOOST_PROCESS_V2_EXECUTE_HPP
#include <boost/process/v2/process.hpp>
#if defined(BOOST_PROCESS_V2_STANDALONE)
#include <asio/bind_cancellation_slot.hpp>
#else
#include <boost/asio/bind_cancellation_slot.hpp>
#endif
BOOST_PROCESS_V2_BEGIN_NAMESPACE
/**
* @brief Run a process and wait for it to complete.
*
* @tparam Executor The asio executor of the process handle
* @param proc The process to be run.
* @return int The exit code of the process
* @exception system_error An error that might have occured during the wait.
*/
template<typename Executor>
inline int execute(basic_process<Executor> proc)
{
return proc.wait();
}
/** \overload int execute(const basic_process<Executor> proc) */
template<typename Executor>
inline int execute(basic_process<Executor> proc, error_code & ec)
{
return proc.wait(ec);
}
namespace detail
{
template<typename Executor>
struct execute_op
{
std::unique_ptr<basic_process<Executor>> proc;
struct cancel
{
using cancellation_type = BOOST_PROCESS_V2_ASIO_NAMESPACE::cancellation_type;
basic_process<Executor> * proc;
cancel(basic_process<Executor> * proc) : proc(proc) {}
void operator()(cancellation_type tp)
{
error_code ign;
if ((tp & cancellation_type::total) != cancellation_type::none)
proc->interrupt(ign);
else if ((tp & cancellation_type::partial) != cancellation_type::none)
proc->request_exit(ign);
else if ((tp & cancellation_type::terminal) != cancellation_type::none)
proc->terminate(ign);
}
};
template<typename Self>
void operator()(Self && self)
{
self.reset_cancellation_state();
BOOST_PROCESS_V2_ASIO_NAMESPACE::cancellation_slot s = self.get_cancellation_state().slot();
if (s.is_connected())
s.emplace<cancel>(proc.get());
auto pro_ = proc.get();
pro_->async_wait(
BOOST_PROCESS_V2_ASIO_NAMESPACE::bind_cancellation_slot(
BOOST_PROCESS_V2_ASIO_NAMESPACE::cancellation_slot(),
std::move(self)));
}
template<typename Self>
void operator()(Self && self, error_code ec, int res)
{
self.get_cancellation_state().slot().clear();
self.complete(ec, res);
}
};
}
/// Execute a process asynchronously
/** This function asynchronously for a process to complete.
*
* Cancelling the execution will signal the child process to exit
* with the following intepretations:
*
* - cancellation_type::total -> interrupt
* - cancellation_type::partial -> request_exit
* - cancellation_type::terminal -> terminate
*
* It is to note that `async_execute` will us the lowest seelected cancellation
* type. A subprocess might ignore anything not terminal.
*/
template<typename Executor = BOOST_PROCESS_V2_ASIO_NAMESPACE::any_io_executor,
BOOST_PROCESS_V2_COMPLETION_TOKEN_FOR(void (error_code, int))
WaitHandler BOOST_PROCESS_V2_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)>
inline
BOOST_PROCESS_V2_INITFN_AUTO_RESULT_TYPE(WaitHandler, void (error_code, int))
async_execute(basic_process<Executor> proc,
WaitHandler && handler BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(Executor))
{
std::unique_ptr<basic_process<Executor>> pro_(new basic_process<Executor>(std::move(proc)));
auto exec = proc.get_executor();
return BOOST_PROCESS_V2_ASIO_NAMESPACE::async_compose<WaitHandler, void(error_code, int)>(
detail::execute_op<Executor>{std::move(pro_)}, handler, exec);
}
BOOST_PROCESS_V2_END_NAMESPACE
#endif //BOOST_PROCESS_V2_EXECUTE_HPP
| true |
3190a79ab2c637a99ecc0ed5b6874570134a6042 | C++ | ClaytonBrezinski/CS-340---Sorting-Algorithms-Analysis | /sortingFunctions.cpp | UTF-8 | 2,602 | 3.78125 | 4 | [] | no_license | #ifndef SORTINGFUNCTIONS_CPP
#define SORTINGFUNCTIONS_CPP
#include "Header.h"
void insertionSort(int arr[], int length)
{
cout << "Insertion Sort -- " << endl;
int j, temp;
for (int i = 0; i < length; i++)// may have to change i=#
{
j = i;
while (j > 0 && arr[j] < arr[j - 1])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
printOut(arr);
}
/**
* Quicksort.
* @param a - The array to be sorted.
* @param first - The start of the sequence to be sorted.
* @param last - The end of the sequence to be sorted.
*/
void quickSort(int a[], int first, int last)
{
int pivotElement;
if (first < last)
{
pivotElement = pivot(a, first, last);
quickSort(a, first, pivotElement - 1);
quickSort(a, pivotElement + 1, last);
}
}
/**
* Find and return the index of pivot element.
* @param a - The array.
* @param first - The start of the sequence.
* @param last - The end of the sequence.
* @return - the pivot element
*/
int pivot(int a[], int first, int last)
{
int p = first;
int pivotElement = a[first];
for (int i = first + 1; i <= last; i++)
{
/* If you want to sort the list in the other order, change "<=" to ">" */
if (a[i] <= pivotElement)
{
p++;
swap(a[i], a[p]);
}
}
swap(a[p], a[first]);
return p;
}
/**
* Swap the parameters.
* @param a - The first parameter.
* @param b - The second parameter.
*/
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
/**
* Swap the parameters without a temp variable.
* Warning! Prone to overflow/underflow.
* @param a - The first parameter.
* @param b - The second parameter.
*/
void swapNoTemp(int& a, int& b)
{
a -= b;
b += a;// b gets the original value of a
a = (b - a);// a gets the original value of b
}
/**
* Print an array.
* @param a - The array.
* @param N - The size of the array.
*/
void print(int a[], const int& N)
{
for (int i = 0; i < N; i++)
cout << "array[" << i << "] = " << a[i] << endl;
}
void merge(int a[], int, int, int);
void mergeSort(int a[], int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);
merge(a, low, high, mid);
}
return;
}
void merge(int a[], int low, int high, int mid)
{
int i, j, k, c[50];
i = low;
k = low;
j = mid + 1;
while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
c[k] = a[i];
k++;
i++;
}
else
{
c[k] = a[j];
k++;
j++;
}
}
while (i <= mid)
{
c[k] = a[i];
k++;
i++;
}
while (j <= high)
{
c[k] = a[j];
k++;
j++;
}
for (i = low; i < k; i++)
{
a[i] = c[i];
}
}
#endif
| true |
22362cd61c101105a46245c2a6696cf24fd7b19c | C++ | BlitW0/cp-codes | /codechef/RECTANGL.cpp | UTF-8 | 293 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t; cin >> t;
while(t--)
{
int a[4];
for(int i = 0; i < 4; i++)
cin >> a[i];
sort(a, a + 4);
if(a[0] == a[1] && a[2] == a[3])
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
| true |
d5c756eef9a50e845e92b905d57013084873de9d | C++ | loachana/samples | /ex36.cpp | UTF-8 | 472 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
string password;
cout << "user name: ";
cin >> name;
if (name == "lochana")
{
cout << "password: ";
cin >> password;
if (password == "1234")
{
cout << "logged in\n";
}
else
{
cout << "wrong password!\n";
}
}
else
{
cout << "wring user name\n";
}
return 0;
}
| true |
be3faf5f7fa373b1c80c3caff460e8dd01244029 | C++ | eightcloud83/Class21 | /Hello/Hello0_C/Hello4.cpp | UTF-8 | 1,101 | 2.90625 | 3 | [] | no_license | #include <stdio.h>
#include <Windows.h>
#include "Tower.h"
void scrGoto(int x, int y);
void scrClr();
void printA(int x, int y, int* A, int n, int m);
struct Tower;
void Tower_Init(struct Tower* t, int i, int m);
int Tower_Add(struct Tower* t, int v);
int Tower_Show(struct Tower* t);
extern struct Tower towerS[];
int Tower_Rm(struct Tower *t)
{
int p=t->n;
if (p==0)
return -1;
p--;
int r=t->A[p];
t->n=p;
return r;
}
void TowerShow()
{
int i;
scrGoto(1, 1);
scrClr();
for (i=0; i <3; i++)
Tower_Show(towerS+i);
}
void TowerMove(struct Tower* src, struct Tower* tgt,struct Tower* tmp, int n)
{
if (n==1)
{
int v=Tower_Rm(src);
Tower_Add(tgt,v);
TowerShow();
Sleep(250);
return;
}
TowerMove(src,tmp,tgt,n-1);
TowerMove(src,tgt,tmp,1);
TowerMove(tmp,tgt,src,n-1);
}
void Hello4()
{
int i;
for (i=0; i <3; i++)
Tower_Init(towerS+i, i, 8);
for (i=8; i>=1; i--)
Tower_Add(towerS, i);
TowerShow();
TowerMove(towerS+0,towerS+2,towerS+1,8);
}
| true |
4e0ab7adcc76a7f0524c49e11edf09ac0dc5b2e5 | C++ | blmarket/icpc | /OldArchive/GCJ/0310/B.cpp | UTF-8 | 2,974 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <cstdio>
#include <sstream>
#include <numeric>
#include <iterator>
#include <queue>
#include <set>
#include <map>
#include <vector>
#define mp make_pair
#define pb push_back
#define sqr(x) ((x)*(x))
#define foreach(it,c) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it)
using namespace std;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int,int> PII;
template<typename T> int size(const T &a) { return a.size(); }
string arr[] = { "Do", "Gae", "Gul", "Yut", "Mo" };
int onmove[] = { -2, 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,0,21,22,23,24,15,26,22,28,0 };
int spmove[] = { -2, 2,3,4,5,20,7,8,9,10,25,12,13,14,15,16,17,18,19,0,21,22,27,24,15,26,22,28,0 };
vector<int> seq;
void move(int &cur, int m)
{
int prev = cur;
if(cur == -2) return;
if(cur == -1)
cur = 1;
else
cur = spmove[cur];
for(int i=0;i<m;i++)
{
if(cur == -2) continue;
if(prev == 26 && cur == 22) { cur = 27; continue; }
prev = cur;
cur = onmove[cur];
}
}
struct state
{
int ap[2][2];
int idx, turn;
bool operator<(const state &rhs)
{
if(ap[0][0] != rhs.ap[0][0]) return ap[0][0] < rhs.ap[0][0];
if(ap[0][1] != rhs.ap[0][1]) return ap[0][1] < rhs.ap[0][1];
if(ap[1][0] != rhs.ap[1][0]) return ap[1][0] < rhs.ap[1][0];
return ap[1][1] < rhs.ap[1][1];
}
};
set<state> S;
int u;
bool go(const state &st)
{
if(S.count(st) != 0) return false;
S.insert(st);
int turn = st.turn;
int turn = 0;
for(int i=0;i<size(seq);i++)
{
bool eat = false;
move(ap[turn], seq[i]);
if(ap[0] == ap[1])
{
ap[!turn] = -1;
eat = true;
}
cerr << arr[seq[i]] << " " << ap[0] << " " << ap[1] << endl;
if(ap[turn] == -2)
{
turn = !turn;
continue;
}
if(seq[i] != 3 && seq[i] != 4 && eat == false)
turn = !turn;
}
cerr << "Result " << ap[0] << " " << ap[1] << endl;
if(ap[0] == -2) ap[0] = -1;
if(ap[1] == -2) ap[1] = -1;
if(ap[0] == apos && ap[1] == bpos)
return true;
if(ap[1] == apos && ap[0] == bpos)
return true;
return false;
}
void process(void)
{
int n,a,b;
int apos, bpos;
seq.clear();
cin >> u >> n >> a >> b;
apos = bpos = -1;
for(int i=0;i<n;i++)
{
string tmp;
cin >> tmp;
for(int j=0;j<5;j++) if(arr[j] == tmp)
{
seq.pb(j);
break;
}
}
if(a) cin >> apos;
if(b) cin >> bpos;
S.clear();
state tmp;
memset(tmp, -1, sizeof(tmp));
tmp.idx = 0;
tmp.turn = 0;
go(tmp);
}
int main(void)
{
int N;
cin >> N;
for(int i=1;i<=N;i++)
{
printf("Case #%d: ",i);
process();
cerr << i << endl;
}
}
| true |
25a1b5bd22565c8163be5e80e622287592302524 | C++ | martiramon/PracticaPRO2Calculadora | /Resultat.hh | UTF-8 | 3,670 | 3.328125 | 3 | [] | no_license | /** @file Resultat.hh
@brief Especificació de la classe Resultat
*/
#ifndef Resultat_HH
#define Resultat_HH
#include "Resultat.hh"
#ifndef NO_DIAGRAM
#include <iostream>
#include <stdlib.h>
#include <list>
#include <string>
#endif
using namespace std;
/** @class Resultat
@brief Classe per representar els resultats obtinguts per la calculadora
*/
class Resultat {
private:
bool definit;
bool enter;
list<int> val;
public:
//Constructores
/** @brief Creadora per defecte
S'executa automàticament al declarar un resultat
\pre Cert
\post Crea un resultat no definit, no enter, i amb llista val buida
*/
Resultat();
/** @brief Creadora de Resultat enter expressat en un string
\pre s és un string d'un número enter
\post Crea un resultat definit, enter, i amb llista val amb l'enter de l'string s
*/
void Resultat_enter(const string& s);
/** @brief Creadora de Resultat enter expressat en un enter
\pre e és un enter
\post Crea un resultat definit, enter, i amb llista val amb l'enter e
*/
void crear_res_ent(int e);
/** @brief Creadora de Resultat llista buida
\pre Cert
\post Crea un resultat definit, no enter, i amb llista val buida
*/
void crear_list();
/** @brief Creadora de Resultat comparació igualtat de dos Resultats
\pre r1 i r2 són Resultats creats
\post Crea un objecte Resultat definit, enter, i com a únic element
de llista val, 1 si r1 i r2 són iguals, 0 altrement
*/
void fer_igual(Resultat& r1, Resultat& r2);
/** @brief Creadora de Resultat comparació inferioritat de dos Resultats
\pre r1 i r2 són Resultats creats
\post Crea un objecte resultat definit, enter i com a únic element
de llista val, 1 si r1<r2, 0 altrement
*/
void fer_inferior(Resultat& r1, Resultat& r2);
//Consultores
/** @brief Consulta si el resultat és un enter
\pre Cert
\post Retorna true si el P.I. és un enter, false altrement
*/
bool ets_enter();
/** @brief Consulta si el resultat éstà definit
\pre Cert
\post Retorna true si el P.I. està definit, false altrement
*/
bool ets_definit();
/** @brief Obté el resultat enter
\pre El resultat és enter, i té una llista val amb un sol enter
\post Retorna l'enter de la llista val del P.I.
*/
int obtenir_enter();
/** @brief Consulta si el resultat és una llista buida
\pre Cert
\post Retorna true si el P.I. no és enter i llista val està buida. False altrement
*/
bool llista_buida();
//Modificadores
/** @brief Neteja el Resultat
\pre El P.I. no està buit
\post Neteja el P.I., deixant definit false, enter false, i llista val buida
*/
void clear();
/** @brief Afegeix un enter al final de P.I.
\pre e és un enter
\post Afegeix un enter e al final de llista val del P.I., enter passa a ser fals
*/
void afegir_enter(int e);
/** @brief Afegeix un enter al principi de P.I.
\pre e és un enter
\post Afegeix un enter e al principi de la llista val del P.I., enter passa a ser fals
*/
void afegir_principi(int e);
/** @brief Modifica si el Resultat està definit
\pre b és un booleà
\post Canvia el P.I. definit per b
*/
void modificar_definit(bool b);
/** @brief Elimina el primer enter del P.I.
\pre Cert
\post Elimina el primer element de la llista val del P.I.
*/
void eliminar_front();
//Escriptura
/** @brief Operació d'escriptura
\pre Cert
\post Escriu el Resultat pel canal estàndar de sortida.
Si el resultat és enter, en forma d'enter. Si no és enter, en forma de llista d'enters.
Si no està definit, escriu "indefinit"
*/
void escriure();
};
#endif
| true |
fee37aff5b73b8669ddc49f1a15ad219889a8672 | C++ | Howard725/offer | /20_PrintMatrix/main.cpp | UTF-8 | 1,681 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
template <typename T>
T Min( T val1, T val2 )
{
return val1 < val2 ? val1 : val2 ;
}
void PrintMatrixClockwisely( int** matrix, int rows, int columns )
{
if ( NULL == matrix || rows <= 0 || columns <= 0 )
return;
//确定有几个顺时针的循环
int circle = Min( ( rows + 1 ) / 2, ( columns + 1 ) / 2 );
for ( int i = 0; i < circle; ++i )
{
//分为四步打印
for ( int j = i; j < columns - i; ++j )
cout << matrix[i][j] << '\t';
cout << endl;
for ( int j = i + 1; j < rows- i; ++j )
cout << matrix[j][columns-1-i] << '\t';
cout << endl;
if ( rows - 1 - i > i )
{
for ( int j = columns - i - 2; j > i - 1; --j )
cout << matrix[rows-1-i][j] << '\t';
cout << endl;
}
if ( i < columns - 1 - i )
{
for ( int j = rows - i - 2; j > i; --j )
cout << matrix[j][i] << '\t';
cout << endl;
}
}
}
int **CreateMatrix( int rows, int columns )
{
if ( rows <= 0 || columns <= 0 )
throw "invalid input.";
int **matrix = new int*[rows];
for ( int i = 0; i < rows; ++i )
{
matrix[i] = new int[columns];
for ( int j = 0; j < columns; ++j )
matrix[i][j] = i * columns + j;
}
return matrix;
}
int main() {
cout << "Hello, World!" << endl;
int rows = 1;
int columns = 1;
int **matrix = CreateMatrix( rows, columns );
PrintMatrixClockwisely( matrix, rows, columns);
system("PAUSE");
return 0;
} | true |
350853132aa677551e4b23cdce9428a7424d6231 | C++ | ChandrasekarPerumal/ProgramCode | /Stock Span Problem-stack.cpp | UTF-8 | 1,113 | 3.09375 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
#include<stack>
#include<vector>
using namespace std;
void StockSpan(int *arr,int L)
{
stack < pair<int,int> > s;
vector<int> v;
for(int i=0;i<L;i++)
{
if(s.size()==0)
v.push_back(-1);
else if(s.top().first>arr[i] && s.size()>0)
v.push_back(s.top().second);
else if(s.top().first<arr[i] && s.size()>0)
{
while(s.top().first<arr[i]&&s.size()>0)
{
s.pop();
}
if(s.size()==0)
v.push_back(-1);
else
v.push_back(s.top().second);
}
s.push({arr[i],i});
}
for(int i=0;i<v.size();i++)
{
v[i]=i-v[i];
}
cout<<"O/P:\n";
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}
}
int main()
{
int L;
cout<<"length of the array\n";
cin>>L;
int arr[L];
cout<<"Array Elements\n";
for(int i=0;i<L;i++)
{
cin>>arr[i];
}
StockSpan(arr,L);
}
| true |
df1df077202cc9b2a05a38c2c59011ee7fc69d08 | C++ | BrunoAltadill/HomeControlCenter | /code/mainDoor/mainDoor.ino | UTF-8 | 1,461 | 2.890625 | 3 | [
"MIT"
] | permissive | /****************************************************************************************************
* Home Control Center (HCC) *
* *
* This code controll main door. *
* Send a message each time door state change. *
* The communication channel is a Xbee module. *
* When door is closed, the state value is 0, and when door is open, the state value is 1 *
****************************************************************************************************/
//PINS DEFINITION
#define doorSensor 4
//GLOBAL VARIABLES
int doorState = 0;
int doorStateOld = 0;
//SETUP
void setup() {
//Initialization serial comunication in 9600 bauds
Serial.begin(9600);
//Define mode of pin doorState
pinMode(doorState, INPUT);
}
//MAIN
void loop () {
//Read main door state
doorState = digitalRead(doorSensor);
//If door state change, notify the new state
if (doorState != doorStateOld) {
if (doorState == 1) {
Serial.println("Main door is open!");
} else {
Serial.println("Main door is closed!");
}
doorStateOld = doorState;
}
//Delay 1"
delay(1000);
}
| true |
ab61da38bdbf676fa57df2e00da05c2a095acde4 | C++ | twyleg/mfrc522-cpp | /apps/spidev_read_example/sys_gpio_impl.h | UTF-8 | 499 | 2.640625 | 3 | [] | no_license | // Copyright (C) 2021 twyleg
#pragma once
#include <mfrc522/igpio.h>
#include <spidevpp/gpio.h>
class SysGpio : public mfrc522::IGpio{
public:
SysGpio(unsigned int pin, spidevpp::Gpio::Direction direction, spidevpp::Gpio::Value value)
: mGpio(pin, direction, value)
{}
void setValue(Value value) final {
mGpio.setValue(static_cast<spidevpp::Gpio::Value>(value));
}
Value getValue() final {
return static_cast<mfrc522::IGpio::Value>(mGpio.getValue());
}
spidevpp::Gpio mGpio;
};
| true |
d23a63c8c9f1f64d76afd8cca9b3731918e91245 | C++ | Amit-Gohri/Cpp | /Intervewbit/array/Spiral Order 2.cpp | UTF-8 | 1,254 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> spiral(int A)
{
int sq = sqrt(A);
int count(1);
int row(0), col(0);
int rdir(1), cdir(1);
vector<vector<int>> sol(A, vector<int>(A, 0));
for (int i = A; i > 0; i--)
{
if (i == A)
{
for (int j = 0; j < i; j++)
{
sol[row][col] = count;
col += cdir;
count++;
}
col += -cdir;
cdir = cdir == 1 ? -1 : 1;
row += rdir;
}
else
{
//loop itimes for row
for (int j = 0; j < i; j++)
{
sol[row][col] = count;
count++;
row += rdir;
}
row += -rdir;
rdir = rdir == 1 ? -1 : 1;
col += cdir;
//loop itimes for col
for (int j = 0; j < i; j++)
{
sol[row][col] = count;
count++;
col += cdir;
}
col += -cdir;
cdir = cdir == 1 ? -1 : 1;
row += rdir;
}
}
return sol;
}
int main()
{
vector<vector<int>> ans = spiral(5);
} | true |
65ac20c93f7afe62ac0d78dcedf408811a8a9c99 | C++ | microsoft/DirectML | /Samples/DirectMLSuperResolution/Kits/DirectXTK12/Src/DemandCreate.h | UTF-8 | 1,207 | 2.609375 | 3 | [
"LGPL-2.1-or-later",
"MIT",
"Apache-2.0",
"GPL-3.0-only",
"LicenseRef-scancode-generic-cla"
] | permissive | //--------------------------------------------------------------------------------------
// File: DemandCreate.h
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
// http://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#pragma once
#include "PlatformHelpers.h"
namespace DirectX
{
// Helper for lazily creating a D3D resource.
template<typename T, typename TCreateFunc>
inline T* DemandCreate(Microsoft::WRL::ComPtr<T>& comPtr, std::mutex& mutex, TCreateFunc createFunc)
{
T* result = comPtr.Get();
// Double-checked lock pattern.
MemoryBarrier();
if (!result)
{
std::lock_guard<std::mutex> lock(mutex);
result = comPtr.Get();
if (!result)
{
// Create the new object.
ThrowIfFailed(
createFunc(&result)
);
MemoryBarrier();
comPtr.Attach(result);
}
}
return result;
}
}
| true |
c142ad525a5a13093cf3036419549ae06be2c1e1 | C++ | rjlauer/aerie-liff | /src/hawcnest/include/hawcnest/processing/Source.h | UTF-8 | 818 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | /*!
* @file Source.h
* @brief Generic interface for a source of data for processing.
* @author John Pretz
* @date 25 Aug 2008
* @version $Id: Source.h 23073 2014-12-01 17:23:33Z sybenzvi $
*/
#ifndef HAWCNEST_SOURCE_H_INCLUDED
#define HAWCNEST_SOURCE_H_INCLUDED
#include <hawcnest/processing/Bag.h>
#include <boost/shared_ptr.hpp>
/*!
* @author John Pretz
* @ingroup hawcnest_api
* @brief A unique kind of service that provides a stream of events
*/
class Source {
public:
virtual ~Source() { }
/// Get next Bag in data stream; should return empty pointer when done
virtual BagPtr Next() = 0;
/// Get previous Bag in data stream; defaults to empty pointer
virtual BagPtr Previous()
{ return BagPtr(); }
};
SHARED_POINTER_TYPEDEFS(Source);
#endif // HAWCNEST_SOURCE_H_INCLUDED
| true |
92ebcb3864ace4a9db3820a9b90a14fbecfd4297 | C++ | SayaUrobuchi/uvachan | /UVa/10097.cpp | UTF-8 | 1,544 | 2.984375 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int map[101][101];
int queue1[10000], queue2[10000];
int step[10000];
int chk[101][101];
int min(int p, int q)
{
if(p < q)
{
return p;
}
return q;
}
int max(int p, int q)
{
if(p > q)
{
return p;
}
return q;
}
int main()
{
int cas, n, i, j, s, t1, t2, next1, next2, target;
cas = 0;
while(scanf("%d", &n) == 1)
{
if(!n)
{
break;
}
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
scanf("%d", &map[i][j]);
}
}
scanf("%d%d%d", &t1, &t2, &target);
queue1[0] = min(t1, t2);
queue2[0] = max(t1, t2);
step[0] = 0;
memset(chk, 0, sizeof(chk));
chk[queue1[0]][queue2[0]] = 1;
for(i=0, j=1; i<j; i++)
{
t1 = queue1[i];
t2 = queue2[i];
s = step[i] + 1;
if(map[t1][t2])
{
next1 = min(map[t1][t2], t2);
next2 = max(map[t1][t2], t2);
if(!chk[next1][next2])
{
if(next1 == target || next2 == target)
{
break;
}
chk[next1][next2] = 1;
queue1[j] = next1;
queue2[j] = next2;
step[j++] = s;
}
}
if(map[t2][t1])
{
next1 = min(t1, map[t2][t1]);
next2 = max(t1, map[t2][t1]);
if(!chk[next1][next2])
{
if(next1 == target || next2 == target)
{
break;
}
chk[next1][next2] = 1;
queue1[j] = next1;
queue2[j] = next2;
step[j++] = s;
}
}
}
if(i == j)
{
printf("Game #%d\nDestination is Not Reachable !\n\n", ++cas);
}
else
{
printf("Game #%d\nMinimum Number of Moves = %d\n\n", ++cas, s);
}
}
return 0;
}
| true |
9aa88c47a0cad5aea6a5c4eb844f652718864d02 | C++ | alexandraback/datacollection | /solutions_5690574640250880_0/C++/juho/C_MinesweeperMaster.cpp | UTF-8 | 3,157 | 3.203125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#define PRIMPOSSIBLE printf("Impossible\n");
int R, C, M;
bool transpose;
int r, c;
char grid[50][50];
void printGrid()
{
if (transpose) {
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
printf("%c", grid[j][i]);
}
printf("\n");
}
} else {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("%c", grid[i][j]);
}
printf("\n");
}
}
}
void fillAllMine()
{
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
grid[i][j] = '*';
}
}
grid[r-1][c-1] = 'c';
}
void fillOneLine()
{
int i = 0;
while (i < M) {
grid[0][i] = '*';
i++;
}
while (i < c - 1) {
grid[0][i] = '.';
i++;
}
grid[0][c-1] = 'c';
}
void fillTwoLine()
{
int i = 0;
while (i < M / 2) {
grid[0][i] = '*';
grid[1][i] = '*';
i++;
}
while (i < c) {
grid[0][i] = '.';
grid[1][i] = '.';
i++;
}
grid[1][c-1] = 'c';
}
void fillSparse()
{
// r >= 3
int mc = M / r;
int mr = M % r;
for (int i = 0; i < r; i++) {
for (int j = 0; j < mc; j++) {
grid[i][j] = '*';
}
}
for (int i = 0; i < mr; i++) {
grid[i][mc] = '*';
}
for (int i = mr; i < r; i++) {
grid[i][mc] = '.';
}
for (int i = 0; i < r; i++) {
for (int j = mc + 1; j < c; j++) {
grid[i][j] = '.';
}
}
grid[r-1][c-1] = 'c';
if (mr == r - 1) {
// swap
grid[mr-1][mc] = '.';
grid[0][mc+1] = '*';
}
}
void setLastThreeLines()
{
// 3 <= r <= c
int E = r * c - M;
// E = 6, 8, 10, 11, 12, ...
int er = E / 3;
int ec = E % 3;
for (int i = r - er; i < r; i++) {
for (int j = c - 3; j < c; j++) {
grid[i][j] = '.';
}
}
if (ec == 1) {
// E > 10. E != 8. E != 6.
// er >= 3
grid[r - er][c - 3] = '*';
grid[r - er - 1][c - 2] = '.';
grid[r - er - 1][c - 1] = '.';
} else if (ec == 2) {
// E can be 8 or more
grid[r - er - 1][c - 2] = '.';
grid[r - er - 1][c - 1] = '.';
}
grid[r-1][c-1] = 'c';
}
void set4Points()
{
grid[r-2][c-2] = '.';
grid[r-2][c-1] = '.';
grid[r-1][c-2] = '.';
grid[r-1][c-1] = 'c';
}
void solve()
{
int E = R * C - M;
if (R > C) {
r = C;
c = R;
transpose = true;
} else {
r = R;
c = C;
transpose = false;
}
// now r <= c
if (E == 1) {
fillAllMine();
printGrid();
return;
}
if (r == 1) {
fillOneLine();
printGrid();
return;
}
if (E == 2 || E == 3 || E == 5 || E == 7) {
PRIMPOSSIBLE;
return;
}
if (r == 2) {
if (M & 1) {
PRIMPOSSIBLE;
return;
}
fillTwoLine();
printGrid();
return;
}
// now 3 <= r <= c
if (E >= 3 * r) {
fillSparse();
printGrid();
return;
}
// now E < 3 * r
fillAllMine();
if (E > 4) {
// E == 6, 8, 9, 10, 11, 12, ...
setLastThreeLines();
} else {
// E == 4
set4Points();
}
printGrid();
}
int main()
{
int T;
scanf("%d", &T);
for (int i = 1; i <= T; i++) {
printf("Case #%d:\n", i);
scanf("%d %d %d", &R, &C, &M);
solve();
}
return 0;
}
| true |
8d459b3834b040b7f5ab678dd15c8f1a5f8ed6e7 | C++ | cualquiercosa327/PeteOpenGL2Tweak | /gpuPeteOpenGL2Tweak/deposterize.h | UTF-8 | 2,095 | 2.828125 | 3 | [] | no_license | #pragma once
#include "Types.h"
#include <vector>
// deposterization: smoothes posterized gradients from low-color-depth (e.g. 444, 565, compressed) sources
// Copyright (c) 2012- PPSSPP Project.
static
void deposterizeH(const u32* data, u32* out, int w, int l, int u) {
static const int T = 8;
for (int y = l; y < u; ++y) {
for (int x = 0; x < w; ++x) {
int inpos = y*w + x;
u32 center = data[inpos];
if (x == 0 || x == w - 1) {
out[y*w + x] = center;
continue;
}
u32 left = data[inpos - 1];
u32 right = data[inpos + 1];
out[y*w + x] = 0;
for (int c = 0; c < 4; ++c) {
u8 lc = ((left >> c * 8) & 0xFF);
u8 cc = ((center >> c * 8) & 0xFF);
u8 rc = ((right >> c * 8) & 0xFF);
if ((lc != rc) && ((lc == cc && abs((int)((int)rc) - cc) <= T) || (rc == cc && abs((int)((int)lc) - cc) <= T))) {
// blend this component
out[y*w + x] |= ((rc + lc) / 2) << (c * 8);
}
else {
// no change for this component
out[y*w + x] |= cc << (c * 8);
}
}
}
}
}
static
void deposterizeV(const u32* data, u32* out, int w, int h, int l, int u) {
static const int BLOCK_SIZE = 32;
static const int T = 8;
for (int xb = 0; xb < w / BLOCK_SIZE + 1; ++xb) {
for (int y = l; y < u; ++y) {
for (int x = xb*BLOCK_SIZE; x < (xb + 1)*BLOCK_SIZE && x < w; ++x) {
u32 center = data[y * w + x];
if (y == 0 || y == h - 1) {
out[y*w + x] = center;
continue;
}
u32 upper = data[(y - 1) * w + x];
u32 lower = data[(y + 1) * w + x];
out[y*w + x] = 0;
for (int c = 0; c < 4; ++c) {
u8 uc = ((upper >> c * 8) & 0xFF);
u8 cc = ((center >> c * 8) & 0xFF);
u8 lc = ((lower >> c * 8) & 0xFF);
if ((uc != lc) && ((uc == cc && abs((int)((int)lc) - cc) <= T) || (lc == cc && abs((int)((int)uc) - cc) <= T))) {
// blend this component
out[y*w + x] |= ((lc + uc) / 2) << (c * 8);
}
else {
// no change for this component
out[y*w + x] |= cc << (c * 8);
}
}
}
}
}
}
| true |
52644ae0ad21ba78ffdd70f932df6a290bf2a8f0 | C++ | acb123/GitFrst | /stringrev.cpp | UTF-8 | 510 | 3.140625 | 3 | [] | no_license | /*
CPP Program to reverse a String using Stack
Author : cvsabhishek@gmail.com
*/
#include<stdio.h>
#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
int main()
{
int n,k=0;
stack<char> s;
char str[100];
fgets(str,100,stdin);
int x=strlen(str);
cout<<x<<endl;
for(int i=0;i<=strlen(str);i++)
{
if(str[i]==' ' || (i==(x-1)))
{
n=i-1;
for(int j=k;j<=n;j++)
s.push(str[j]);
for(int j=k;j<=n;j++)
{
cout<<s.top();
s.pop();
}
cout<<' ';
k=i+1;
}
}
cout<<endl;
}
| true |
bf73947d28e3e959624037f64b824c5f31de4139 | C++ | TankNee/VisualStudioProduct | /网络Demo/网络Demo/网络Demo.cpp | UTF-8 | 4,139 | 2.703125 | 3 | [] | no_license | #include<stdio.h>
#include<Windows.h>
#include "pch.h"
#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
#include<time.h>
#include <iostream>
//宏定义
#define LEFT 0x4B00
#define RIGHT 0x4D00
#define UP 0x4800
#define DOWN 0x5000
#define ESC 0x011B
#define ENTER 0x1C0D
#define SIZE 10
#define GAMEFRAME_WIDTH 64
#define FRAME_HEIGHTH 48
#define DATAFRAME_WIDTH 48
//函数声明
void startup();
//循环变量
int i, j;
//蛇身的长度
int length = 4;
//食物的结构体
struct food
{
int x;
int y;
} food1;
//毒药的结构体
struct poison
{
int x;
int y;
}poison1;
//蛇的结构体
struct snakeNode
{
int x;
int y;
int number;
struct snakeNode *previous = NULL;
struct snakeNode *next = NULL;
} *snakept_1, *snakept_2, snake, *head;
void iniSnake()
{
head = (struct snakeNode *)malloc(sizeof(struct snakeNode));
head->number = 1;
head->next = NULL;
head->previous = NULL;
head->x = GAMEFRAME_WIDTH / 2;
head->y = FRAME_HEIGHTH / 2;
snakept_2 = head;
for (i = 2; i <= length; i++)
{
snakept_1 = (struct snakeNode *)malloc(sizeof(struct snakeNode));
snakept_1->number = i;
snakept_1->x = snakept_2->x - 1;
snakept_1->y = snakept_2->y;
snakept_1->next = snakept_2->next;
snakept_2->next = snakept_1;
snakept_1->previous = snakept_2;
snakept_2 = snakept_1;
}
}
//毒药的生成
void creatPoison()
{
srand((unsigned)time(NULL));
poison1.x = (rand() * 100) % 53 + 1;
poison1.y = (rand() * 100) % 54 + 1;
moveto(poison1.x*SIZE, poison1.y*SIZE);
setfillcolor(GREEN);
fillcircle(poison1.x*SIZE + SIZE / 2, poison1.y*SIZE + SIZE / 2, SIZE / 2);
}
//食物的生成
void creatFood()
{
srand((unsigned)time(NULL));
food1.x = (rand() * 100) % 34 + 1;
food1.y = (rand() * 100) % 15 + 1;
moveto(food1.x*SIZE, food1.y*SIZE);
setfillcolor(RED);
fillcircle(food1.x*SIZE + SIZE / 2, food1.y*SIZE + SIZE / 2, SIZE / 2);
}
void snakePaint()
{
struct snakeNode *point;
point = head;
moveto(point->x*SIZE, point->y*SIZE);
setfillcolor(YELLOW);
fillcircle(point->x*SIZE + SIZE / 2, point->y*SIZE + SIZE / 2, SIZE / 2);
point = point->next;
while (point != NULL)
{
moveto(point->x*SIZE, point->y*SIZE);
setfillcolor(LIGHTBLUE);
fillcircle(point->x*SIZE + SIZE / 2, point->y*SIZE + SIZE / 2, SIZE / 2);
point = point->next;
}
}
//初始化界面
void welcomeUI()
{
IMAGE img1;
loadimage(&img1, _T("G:\\图片\\Saved Pictures\\微信图片_20180808214022.jpg"));
putimage(0, 0, &img1);
MOUSEMSG m;
while (true)
{
m = GetMouseMsg();
if (m.mkLButton)
{
startup();
break;
}
}
}
//数据初始化函数
void startup()
{
//打印边框
for (i = 0; i < GAMEFRAME_WIDTH; i++)
{
moveto(i*SIZE, 0);
setfillcolor(BLUE);
fillrectangle(i*SIZE, 0, (i + 1)*SIZE, SIZE);
moveto(i*SIZE, (FRAME_HEIGHTH - 1)*SIZE);
setfillcolor(BLUE);
fillrectangle(i*SIZE, (FRAME_HEIGHTH - 1)*SIZE, (i + 1)*SIZE, (FRAME_HEIGHTH)*SIZE);
}
for (j = 0; j < FRAME_HEIGHTH; j++)
{
moveto(0, j*SIZE);
setfillcolor(BLUE);
fillrectangle(0, j*SIZE, SIZE, (j + 1)*SIZE);
moveto((GAMEFRAME_WIDTH - 1)*SIZE, j*SIZE);
setfillcolor(BLUE);
fillrectangle((GAMEFRAME_WIDTH - 1)*SIZE, j*SIZE, GAMEFRAME_WIDTH*SIZE, (j + 1)*SIZE);
}
//初始化蛇身
iniSnake();
//打印蛇身
snakePaint();
//打印食物与毒药
creatFood();
creatPoison();
}
//移动方法:新建一个头节点,删除一个尾节点
void Move(char input)
{
struct snakeNode *point;
point = (struct snakeNode *)malloc(sizeof(struct snakeNode));
point->x = head->x;
point->y = head->y;
point->number = 0;
point->next = head;
head->previous = point;
head = point;
while (point->next != NULL)
{
point = point->next;
}
free(point);
switch (input)
{
case 'w':
head->y -= 1;
break;
case 'a':
head->x -= 1;
break;
case 's':
head->y += 1;
break;
case 'd':
head->x += 1;
break;
default:
break;
}
}
void inputConcerned()
{
char input;
if (_kbhit())
{
input = _getch();
Move(input);
snakePaint();
}
}
//主函数
int main()
{
initgraph(1120, 480);
//welcomeUI();
startup();
while (1)
{
Move;
inputConcerned;
}
getchar();
closegraph();
} | true |
5d14ad62bf317d66866ccfb3b173d51fd7b01a9a | C++ | feel-coding/algorithm-practice | /백준 1182.cpp | UTF-8 | 1,127 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <tuple>
using namespace std;
int n;
int s;
vector<int> v;
int cnt = 0;
void combination(vector<bool> visited, vector<pair<int, int>> result, int num, int k) {
if (num == k) {
int total = 0;
for (int i = 0; i < result.size(); i++) {
total += result[i].first;
}
if (total == s) cnt++;
return;
}
for (int i = 0; i < n; i++) {
if (num == 0) {
if (!visited[i]) {
visited[i] = true;
result[num].first = v[i];
result[num].second = i;
combination(visited, result, num + 1, k);
visited[i] = false;
}
}
else {
if (result[num - 1].second < i && !visited[i]) {
visited[i] = true;
result[num].first = v[i];
result[num].second = i;
combination(visited, result, num + 1, k);
visited[i] = false;
}
}
}
}
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
cin >> n >> s;
v = vector<int>(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
for (int i = 1; i <= n; i++) {
vector<bool> visited(n);
vector<pair<int, int>> result(i);
combination(visited, result, 0, i);
}
cout << cnt;
return 0;
} | true |
308a4abcaa8ffe36b027ed3c42950c5482536393 | C++ | HKAMUSINSKI/Blackjack | /Blackjack/Player.h | WINDOWS-1250 | 1,035 | 2.890625 | 3 | [] | no_license | #pragma once
#include "Card.h"
#include<vector>
#include <memory>
#include <iostream>
#include <string>
#include <windows.h>
#include <conio.h>
class Player
{
protected:
void count_hand();
std::vector < std::unique_ptr <Card> > hand;
bool playing = true;
int hand_power = 0;
int number_ACE = 0;
std::string name = "NN";
public:
Player() = default;
Player(std::string _name) { name = _name; };
Player(const Player& player) { name = player.name; };
~Player() = default;
void take_card(std::unique_ptr <Card> card);
bool is_playing();
int power_hand();
void end_game();
void show_hand();
std::string get_name();
virtual char move() =0; // do przesoniecia
};
class Dealer : public Player
{
public:
Dealer(std::string _name) { name = _name;};
Dealer() { name = "CROUPIER"; };
~Dealer() = default;
char move() override;
std::string first_card();
};
class Human : public Player
{
public:
Human(std::string _name) { name = _name; };
Human() {};
~Human() = default;
char move() override;
};
| true |
9e8777195c766d78cad2cf244443429436129ebc | C++ | SUMUKHA-PK/Heterogenous-Parallel-Computing | /A4/2.Histogramming-ASCII/dataset_generator.cpp | UTF-8 | 2,490 | 3.328125 | 3 | [] | no_license | // 16CO145 Sumukha PK
// 16CO234 Prajval M
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
using namespace std;
static char *base_dir;
const size_t NUM_BINS = 128;
int *compute(int *bins, const char *input, int num)
{
for (int i = 0; i < num; ++i)
++bins[(int)input[i]];
return bins;
}
static char *generate_data(size_t n)
{
char *data = (char *)malloc(n + 1);
for (unsigned int i = 0; i < n; i++)
{
data[i] = (rand() % (128 - 32)) + 32; // random printable character
}
data[n] = 0; // null-terminated
return data;
}
static void write_data_str(char *file_name, const char *data, int num)
{
FILE *handle = fopen(file_name, "w");
for (int ii = 0; ii < num; ii++)
{
fprintf(handle, "%c", *data++);
}
fflush(handle);
fclose(handle);
}
void write_data_int(char *file_name, int *data, int num)
{
std::ofstream handle(file_name);
handle << num << std::endl;
for(int ii = 0; ii <NUM_BINS; ii++)
{
handle << data[ii] << std::endl;
}
}
static void create_dataset_fixed(int datasetNum, const char *str)
{
const char *dir_name = base_dir;
char *input_file_name = (char *)"input.raw";
char *output_file_name = (char *)"output.raw";
int *output_data = (int *)calloc(NUM_BINS, sizeof(int));
for (int i = 0; i < NUM_BINS; i++)
output_data[i] = 0;
output_data = compute(output_data, str, strlen(str));
write_data_str(input_file_name, str, strlen(str));
write_data_int(output_file_name, output_data, NUM_BINS);
free(output_data);
free(input_file_name);
free(output_file_name);
}
static void create_dataset_random(int datasetNum, size_t input_length)
{
const char *dir_name = base_dir;
char *input_file_name = (char *)"input.raw";
char *output_file_name = (char *)"output.raw";
char *str = generate_data(input_length);
int *output_data = (int *)calloc(NUM_BINS, sizeof(int));
for(int i=0; i < NUM_BINS; i++)
output_data[i] = 0;
output_data = compute(output_data, str, input_length);
write_data_str(input_file_name, str, input_length);
write_data_int(output_file_name, output_data, NUM_BINS);
free(str);
free(output_data);
free(input_file_name);
free(output_file_name);
}
int main()
{
base_dir = (char *)"";
// create_dataset_fixed(0, "the quick brown fox jumps over the lazy dog");
// create_dataset_fixed(1, "gpu teaching kit - accelerated computing");
// create_dataset_random(2, 16);
create_dataset_random(3, 513);
// create_dataset_random(4, 511);
// create_dataset_random(5, 1);
return 0;
}
| true |
8e5b6ac7fb26baa57252f6715cd4eb33e18ef94d | C++ | korotindev/c-plus-plus-belts | /solutions/black/week5/4_transport_catalog_r/src/solution/requests.cpp | UTF-8 | 5,721 | 2.671875 | 3 | [] | no_license | #include "requests.h"
#include "transport_router.h"
#include <vector>
using namespace std;
namespace Requests {
Json::Dict Stop::Process(const TransportCatalog& db) const {
const auto* stop = db.GetStop(name);
Json::Dict dict;
if (!stop) {
dict["error_message"] = Json::Node("not found"s);
} else {
Json::Array bus_nodes;
bus_nodes.reserve(stop->bus_names.size());
for (const auto& bus_name : stop->bus_names) {
bus_nodes.emplace_back(bus_name);
}
dict["buses"] = Json::Node(move(bus_nodes));
}
return dict;
}
Json::Dict Bus::Process(const TransportCatalog& db) const {
const auto* bus = db.GetBus(name);
Json::Dict dict;
if (!bus) {
dict["error_message"] = Json::Node("not found"s);
} else {
dict = {
{"stop_count", Json::Node(static_cast<int>(bus->stop_count))},
{"unique_stop_count", Json::Node(static_cast<int>(bus->unique_stop_count))},
{"route_length", Json::Node(static_cast<int>(bus->road_route_length))},
{"curvature", Json::Node(bus->road_route_length / bus->geo_route_length)},
};
}
return dict;
}
struct RouteItemResponseBuilder {
Json::Dict operator()(const TransportRouter::RouteInfo::BusItem& bus_item) const {
return Json::Dict{
{"type", Json::Node("Bus"s)},
{"bus", Json::Node(bus_item.bus_name)},
{"time", Json::Node(bus_item.time)},
{"span_count", Json::Node(static_cast<int>(bus_item.span_count))}
};
}
Json::Dict operator()(const TransportRouter::RouteInfo::WaitItem& wait_item) const {
return Json::Dict{
{"type", Json::Node("Wait"s)},
{"stop_name", Json::Node(wait_item.stop_name)},
{"time", Json::Node(wait_item.time)},
};
}
};
Json::Dict Route::Process(const TransportCatalog& db) const {
Json::Dict dict;
const auto route = db.FindRoute(stop_from, stop_to);
if (!route) {
dict["error_message"] = Json::Node("not found"s);
} else {
dict["total_time"] = Json::Node(route->total_time);
Json::Array items;
items.reserve(route->items.size());
for (const auto& item : route->items) {
items.push_back(visit(RouteItemResponseBuilder{}, item));
}
dict["items"] = move(items);
dict["map"] = Json::Node(db.RenderRoute(*route));
}
return dict;
}
Json::Dict Map::Process(const TransportCatalog& db) const {
return Json::Dict{
{"map", Json::Node(db.RenderMap())},
};
}
Json::Dict FindCompanies::Process(const TransportCatalog& db) const {
const auto companies = db.FilterCompanies(names, rubrics, urls, phones);
Json::Array items;
items.reserve(companies.size());
for(auto &company : companies){
items.push_back(move(company));
}
return Json::Dict{
{"companies", move(items)}
};
}
variant<Stop, Bus, Route, Map, FindCompanies> Read(const Json::Dict& attrs) {
const string& type = attrs.at("type").AsString();
if (type == "Bus") {
return Bus{attrs.at("name").AsString()};
} else if (type == "Stop") {
return Stop{attrs.at("name").AsString()};
} else if (type == "Route") {
return Route{attrs.at("from").AsString(), attrs.at("to").AsString()};
} else if (type == "FindCompanies") {
FindCompanies fc;
if(attrs.count("names")) {
for(const auto &name : attrs.at("names").AsArray()) {
fc.names.push_back(name.AsString());
}
}
if(attrs.count("urls")) {
for(const auto &url : attrs.at("urls").AsArray()) {
fc.urls.push_back(url.AsString());
}
}
if(attrs.count("rubrics")) {
for(const auto &rubric : attrs.at("rubrics").AsArray()) {
fc.rubrics.push_back(rubric.AsString());
}
}
if (attrs.count("phones")) {
for(const auto &phone_node : attrs.at("phones").AsArray()) {
const auto& phone_dict = phone_node.AsMap();
YellowPages::Phone phone;
if(phone_dict.count("type")) {
if(phone_dict.at("type").AsString() == "FAX") {
phone.set_type(YellowPages::Phone_Type::Phone_Type_FAX);
} else {
phone.set_type(YellowPages::Phone_Type::Phone_Type_PHONE);
}
} else {
phone.set_type(YellowPages::Phone_Type::Phone_Type_UNKNOWN);
}
if (phone_dict.count("country_code")) {
*phone.mutable_country_code() = phone_dict.at("country_code").AsString();
}
if (phone_dict.count("local_code")) {
*phone.mutable_local_code() = phone_dict.at("local_code").AsString();
}
if (phone_dict.count("number")) {
*phone.mutable_number() = phone_dict.at("number").AsString();
}
if (phone_dict.count("extension")) {
*phone.mutable_extension() = phone_dict.at("extension").AsString();
}
fc.phones.push_back(move(phone));
}
}
return fc;
} else {
return Map{};
}
}
Json::Array ProcessAll(const TransportCatalog& db, const Json::Array& requests) {
Json::Array responses;
responses.reserve(requests.size());
for (const Json::Node& request_node : requests) {
Json::Dict dict = visit([&db](const auto& request) {
return request.Process(db);
},
Requests::Read(request_node.AsMap()));
dict["request_id"] = Json::Node(request_node.AsMap().at("id").AsInt());
responses.push_back(Json::Node(dict));
}
return responses;
}
}
| true |
00dc83e2e9f4fd076252b10e88e5c5a3e5d54d4f | C++ | Matzge/C- | /familyTree.h | UTF-8 | 539 | 2.78125 | 3 | [] | no_license | #ifndef _familyTree_H_
#define _familyTree_H_
#include <iostream>
#include <vector>
#include "person.h"
class Tree
{
public:
Tree();
void addPerson(Person* person);
Person* getPerson(const int gid) const;
void printChildren(const int gid) const;
void printParents(const int gid) const;
void printSiblings(const int gid) const;
void printGrandparents(const int gid) const;
void printUncle(const int gid) const;
private:
std::vector<Person*> _gids;
};
#endif // _familyTree_H_
| true |
6a1cc475a271d6b352a09d81a04bded5651ffe46 | C++ | sjy234sjy234/Coding-Test | /PTA:PAT/A1050.cpp | GB18030 | 644 | 2.65625 | 3 | [] | no_license | #include<iostream> //ͨ漰ַ,϶漰ϣ;
#include<algorithm>
#include<string.h>
#include<ctype.h>
#include<stdio.h>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<math.h>
#include<map>
using namespace std;
bool Mark[128];
char S1[10010],S2[10010];
void Input(){
int i;
gets(S1);
gets(S2);
for(i=0;i<128;i++)
Mark[i]=true;
for(i=0;S2[i]!='\0';i++)
Mark[S2[i]]=false;
for(i=0;S1[i]!='\0';i++)
if(Mark[S1[i]])
printf("%c",S1[i]);
printf("\n");
}
void Process(){
}
void Display(){
}
int main(){
// while(true){
Input();
Process();
Display();
// }
return 0;
} | true |
c924532d277a0e163807b1425768ebb9ec009806 | C++ | Byeong-Chan/ByeongChan_PS_Note | /C:C++/1238.cpp | UTF-8 | 1,380 | 2.59375 | 3 | [] | no_license | #include <cstdio>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
struct node {
int pos;
int cst;
bool operator< (const node &a) const {
return this->cst > a.cst;
}
};
int o[101010];
int u[101010];
vector<node> edge[101010];
vector<node> inverse_edge[101010];
priority_queue<node> q;
int main() {
int i;
int n, k, m;
int x, y, z;
node here, nxt;
scanf("%d %d %d",&n,&m,&k);
for (i=1;i<=m;i++) {
scanf("%d %d %d",&x,&y,&z);
edge[x].push_back({y, z});
inverse_edge[y].push_back({x, z});
}
q.push({k, 1});
while (q.size()) {
here = q.top();
q.pop();
if (o[here.pos]) continue;
o[here.pos] = here.cst;
for (i=0;i<edge[here.pos].size();i++) {
nxt = edge[here.pos][i];
q.push({nxt.pos, here.cst + nxt.cst});
}
}
q.push({k, 1});
while (q.size()) {
here = q.top();
q.pop();
if (u[here.pos]) continue;
u[here.pos] = here.cst;
for (i=0;i<inverse_edge[here.pos].size();i++) {
nxt = inverse_edge[here.pos][i];
q.push({nxt.pos, here.cst + nxt.cst});
}
}
int ans = 0;
for(i=1;i<=n;i++) {
x = o[i] + u[i] - 2;
if (ans < x) ans = x;
}
printf("%d",ans);
return 0;
} | true |
c26af0b4b1daa1be59cb3fa48f356aa79b031015 | C++ | fedepiz/osdev-art | /src/util/heap_common.cpp | UTF-8 | 3,784 | 2.953125 | 3 | [] | no_license | #include <util/heap_common.h>
#include <kstdio.h>
#include <kstdlib.h>
namespace util {
namespace heap_common {
#define MIN_BLOCK_SIZE (sizeof(heapBlockHeader)*4)
//Use 32-bit alignment for blocks
const int alignment = 4;
using kstd::log;
using kstd::itoa;
//Inserts a memory block, with the header starting at startAddress. Total size
//is the total size of the memory block, INCLUDING THE HEADER
heapBlockHeader* makeMemoryBlock(uint8_t* startAddress, size_t totalSize) {
heapBlockHeader* header = (heapBlockHeader*)startAddress;
size_t regionSize = totalSize - sizeof(heapBlockHeader);
header->magic = HEAP_HEADER_MAGIC;
header->size = regionSize;
header->nextBlock = nullptr;
header->isFree = true;
return header;
}
heapBlockHeader* findFreeBlock(heapBlockHeader* head, size_t minSize) {
while(head != nullptr) {
if(head->isFree && head->size >= minSize) {
return head;
}
head = head->nextBlock;
}
//Not found
return nullptr;
}
heapBlockHeader* blockAt(void* genPtr) {
uint8_t* ptr = (uint8_t*)genPtr;
heapBlockHeader* header = (heapBlockHeader*)(ptr - sizeof(heapBlockHeader));
if(header->magic != HEAP_HEADER_MAGIC) {
return nullptr;//panic("Magic number mismatch, not a valid heap block header");
}
return header;
}
//Allocates a block of memory, splitting it off a current existing block
uint8_t* allocate(heapBlockHeader* master, size_t splitSize) {
//Make split-size aligned on a 32-bit bounduary
if(splitSize % alignment != 0) splitSize += alignment - (splitSize % alignment);
if(master->size < splitSize) {
//Not enough memory in block
return nullptr;
}
if(master->size < MIN_BLOCK_SIZE) {
//The block is already of minimal size, simply mark as allocated and
//return the pointer to the memory
master->isFree = false;
uint8_t* basePtr = (uint8_t*)master;
return basePtr + sizeof(heapBlockHeader);
}
//Block is big enough to split
uint8_t* basePtr = (uint8_t*)master;
//advance the base pointer after the size
uint8_t* newBlockHeaderPtr = basePtr + sizeof(heapBlockHeader) + splitSize;
//make the new chld block
heapBlockHeader *newBlock = makeMemoryBlock(newBlockHeaderPtr, master->size - splitSize);
//Adjust the block links
newBlock->nextBlock = master->nextBlock;
master->nextBlock = newBlock;
//Shrink master and allocate it
master->size = master->size - (sizeof(heapBlockHeader) + newBlock->size);
master->isFree = false;
return basePtr + sizeof(heapBlockHeader);
}
bool tryMergeBlockWithSuccessor(heapBlockHeader* first) {
if(first == nullptr ||
first->isFree == false ||
first->nextBlock == nullptr ||
first->nextBlock->isFree == false) {
return false;
}
auto second = first->nextBlock;
first->size = first->size + second->size + sizeof(heapBlockHeader);
first->nextBlock = second->nextBlock;
//Erease magic
second->magic = 0;
return true;
}
void debugBlock(heapBlockHeader* header) {
log("Debugging header block\n");
if(header == nullptr) {
log("Null block address\n");
}
uint32_t address = (uint32_t)header;
log("Header address:");
log(itoa(address,16).str);
log("\nMagic: ");
log(itoa(header->magic).str);
log("\nSize: ");
log(itoa(header->size).str);
log("\nFree: ");
if(header->isFree)
log("Y\n");
else
log("N\n");
}
void debugBlockChain(heapBlockHeader* header) {
log("Debugging heap block chain\n...\n");
while(true) {
debugBlock(header);
header = header->nextBlock;
if(header == nullptr) {
return;
}
}
}
};
}; | true |
b15678e46e1632c6711df98bbd95ac110eba53c7 | C++ | LoveXanome/Lutin-Interpreter | /Includes/AnalyseStatique.hpp | UTF-8 | 1,633 | 2.875 | 3 | [] | no_license | #ifndef ANALYSE_STATIQUE_HPP
#define ANALYSE_STATIQUE_HPP
class Programme;
#include <string>
#include "Programme.hpp"
#include "Logger.hpp"
#include "StringHelper.hpp"
#include "EtatIdentifiant.hpp"
#include "Declaration.hpp"
#include "InstructionAffectation.hpp"
#include "InstructionLecture.hpp"
#include "InstructionEcriture.hpp"
class AnalyseStatique
{
public:
AnalyseStatique(TableDesSymboles* tableDesSymboles, Programme* programme);
virtual ~AnalyseStatique();
// Realise l'analyse statique a l'aide des deux tables en attributs
void check();
private:
TableDesSymboles* tableDesSymboles;
TableAnalyseStatique tableAnalyseStatique;
Programme* programme;
void fillTableSymboles();
void fillTableStatique();
void addSymboleToTableSymbole(const std::string& key, Declaration* value);
bool symbolExists(const std::string& key);
void printWarning(const std::string& msg) const;
void throwError(const std::string& msg);
void addEtatIdentifiantToTableStatique(const std::string& key, EtatIdentifiant* strucIdentifiant);
void handleInstruction(Instruction* instruction);
void handleInstructionAffectation(InstructionAffectation* affectation);
void handleInstructionLecture(InstructionLecture* lecture);
void handleInstructionEcriture(InstructionEcriture* ecriture);
bool isVariable(const std::string& id) const;
void checkVariable(const std::string& id, EtatIdentifiant* const etat);
bool isConstant(const std::string& id) const;
void checkConstant(const std::string& id, EtatIdentifiant* const etat);
void deleteTableStatique();
static const Logger logger;
};
#endif // ANALYSE_STATIQUE_HPP
| true |
1b3e4c84de058709f31b70e555fa31ce9a228aad | C++ | christosg88/hackerrank | /Algorithms/04-Sorting/Insertion_Sort_Part_2/main.cpp | UTF-8 | 725 | 3.390625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &stream, std::vector<T> const &vec) {
for (int i = 0, last = vec.size() - 1; i < last; ++i) {
stream << vec[i] << ' ';
}
stream << vec.back() << '\n';
return stream;
}
int main() {
int size;
std::cin >> size;
std::vector<int> nums(size);
for (auto &num : nums) {
std::cin >> num;
}
for (int j = 2; j <= size; ++j) {
int inserted = nums[j - 1];
int i = j - 2;
while (i >= 0 && nums[i] > inserted) {
nums[i + 1] = nums[i];
--i;
}
nums[i + 1] = inserted;
std::cout << nums;
}
return 0;
}
| true |
a3a1c1c42dd1f1091ae0871fa6ce90e7dbfc9eca | C++ | rouies/MachineProcessMonitor | /filerecordqueue.cpp | UTF-8 | 10,626 | 2.765625 | 3 | [] | no_license | #include "filerecordqueue.h"
#include "qdebug.h"
FileRecordQueue::FileRecordQueue(QString name,QString filePath,QObject *parent) : QObject(parent)
{
this->name = name;
this->queueFile = new QFile(filePath);
this->semaphore = new QSemaphore(1);
this->timeout = 3000;
}
FileRecordQueue::~FileRecordQueue()
{
if(this->queueFile->isOpen())
{
this->queueFile->close();
}
delete this->queueFile;
delete this->semaphore;
}
QString FileRecordQueue::queueName()
{
return this->name;
}
int FileRecordQueue::open()
{
if(!this->queueFile->open(QIODevice::ReadWrite))
{
return FILE_RECORD_QUEUE_FILE_OPEN_ERROR;
}
QDataStream queueStream(this->queueFile);
queueStream.setVersion(QDataStream::Qt_5_10);
queueStream.setByteOrder(QDataStream::LittleEndian);
//获取队列头信息
queueStream >> this->queueCount;
queueStream >> this->itemSize;
queueStream >> this->de;
queueStream >> this->en;
this->fileSize = this->itemSize * this->queueCount + 16;
return FILE_RECORD_QUEUE_SUCCESS;
}
void FileRecordQueue::close()
{
if(this->queueFile->isOpen())
{
this->queueFile->close();
}
}
FileRecordQueue* FileRecordQueue::createFileRecordQueue(QString name,QString filePath,int itemSize,int queueCount,QObject *parent)
{
QFile file(filePath);
if(!file.exists())
{
if(file.open(QIODevice::WriteOnly)){
//开头四个项 队列总数 单元大小 队头指针 队尾指针
QDataStream out(&file);
out.setVersion(QDataStream::Qt_5_10);
out.setByteOrder(QDataStream::LittleEndian);
out << (qint32)queueCount << (qint32)itemSize << (qint32)0 << (qint32)0;
file.resize(queueCount * itemSize + 16);
file.close();
} else {
return nullptr;
}
}
return new FileRecordQueue(name,filePath,parent);
}
qint64 FileRecordQueue::size()
{
if(this->en == this->de)
{
return 0;
}
else if(this->en > this->de)
{
return this->en - this->de;
}
else
{
return this->queueCount - (this->de - this->en);
}
}
int FileRecordQueue::enquque(QByteArray& item)
{
if(!this->semaphore->tryAcquire(1,this->timeout))
{
return FILE_RECORD_QUEUE_SEMAPHORE_TIMEOUT;//超时
}
if(item.size() != this->itemSize)
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_ENQUEUE_SIZE_ERROR;
}
if((this->en + 1) % this->queueCount == this->de)
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_ENQUEUE_IS_FULL;
}
if(!this->queueFile->seek(this->en * this->itemSize + 16))
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_FILE_SEEK_ERROR;
}
if(this->queueFile->write(item.data(),this->itemSize) != this->itemSize)
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_FILE_RW_ERROR;
}
if(!this->queueFile->flush())
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_FILE_RW_ERROR;
}
int cren = this->en;
cren = (cren + 1) % this->queueCount;
//更新队尾指针
if(!this->queueFile->seek(sizeof(int) * 3))
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_FILE_SEEK_ERROR;
}
QDataStream queueStream(this->queueFile);
queueStream.setVersion(QDataStream::Qt_5_10);
queueStream.setByteOrder(QDataStream::LittleEndian);
queueStream << cren;
if(!this->queueFile->flush() || this->queueFile->error() != QFile::NoError)
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_FILE_MODIFY_PTR_ERROR;
}
this->en = cren;
this->semaphore->release(1);
emit this->onEnQueue(this);
return FILE_RECORD_QUEUE_SUCCESS;
}
QByteArray FileRecordQueue::dequeue(int* error)
{
if(!this->semaphore->tryAcquire(1,this->timeout))
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_SEMAPHORE_TIMEOUT;//超时
}
return QByteArray();
}
else
{
if(this->en == this->de)
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_DEQUEUE_IS_EMPTY;//空队列
}
this->semaphore->release(1);
return QByteArray();
}
qint64 len = this->itemSize;
if(!this->queueFile->seek(this->de * this->itemSize + 16))
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_FILE_SEEK_ERROR;
}
this->semaphore->release(1);
return QByteArray();
}
QByteArray res = this->queueFile->read(len);
if(this->queueFile->error() != QFile::NoError)
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_FILE_RW_ERROR;
}
this->semaphore->release(1);
return QByteArray();
}
int crde = this->de;
crde = (crde + 1) % this->queueCount;
//更新队头指针
if(!this->queueFile->seek(sizeof(int) * 2))
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_FILE_SEEK_ERROR;
}
this->semaphore->release(1);
return QByteArray();
}
QDataStream queueStream(this->queueFile);
queueStream.setVersion(QDataStream::Qt_5_10);
queueStream.setByteOrder(QDataStream::LittleEndian);
queueStream << crde;
if(!this->queueFile->flush() || this->queueFile->error() != QFile::NoError)
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_FILE_MODIFY_PTR_ERROR;
}
this->semaphore->release(1);
return QByteArray();
}
this->de = crde;
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_SUCCESS;
}
this->semaphore->release(1);
return res;
}
}
int FileRecordQueue::get(QList<QByteArray>& list,int* error,int size)
{
if(!this->semaphore->tryAcquire(1,this->timeout))
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_SEMAPHORE_TIMEOUT;//超时
}
return 0;
}
else
{
list.clear();
if(size <= 0)
{
size = this->size();
}
if(this->size() < size)
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_GET_SIZE_TOO_LARGE;
}
this->semaphore->release(1);
return 0;
}
int crde = this->de;
qint64 len = this->itemSize;
this->queueFile->seek(crde * this->itemSize + 16);
for(int i=0 ; i<size ; i++)
{
QByteArray res = this->queueFile->read(len);
if(this->queueFile->error() != QFile::NoError)
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_FILE_RW_ERROR;
}
this->semaphore->release(1);
return 0;
}
crde = (crde + 1) % this->queueCount;
if(crde == 0)
{
if(!this->queueFile->seek(16))
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_FILE_SEEK_ERROR;
}
this->semaphore->release(1);
return 0;
}
}
list << res;
}
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_SUCCESS;
}
this->semaphore->release(1);
return size;
}
}
int FileRecordQueue::get(QByteArray& data,int* error,int size)
{
if(!this->semaphore->tryAcquire(1,this->timeout))
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_SEMAPHORE_TIMEOUT;//超时
}
return 0;
}
else
{
data.clear();
if(size <= 0)
{
size = this->size();
}
if(this->size() < size)
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_GET_SIZE_TOO_LARGE;
}
this->semaphore->release(1);
return 0;
}
int crde = this->de;
qint64 len = this->itemSize;
this->queueFile->seek(crde * this->itemSize + 16);
for(int i=0 ; i<size ; i++)
{
QByteArray res = this->queueFile->read(len);
if(this->queueFile->error() != QFile::NoError)
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_FILE_RW_ERROR;
}
this->semaphore->release(1);
return 0;
}
crde = (crde + 1) % this->queueCount;
if(crde == 0)
{
if(!this->queueFile->seek(16))
{
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_FILE_SEEK_ERROR;
}
this->semaphore->release(1);
return 0;
}
}
data.append(res);
}
if(error != nullptr)
{
*error = FILE_RECORD_QUEUE_SUCCESS;
}
this->semaphore->release(1);
return size;
}
}
int FileRecordQueue::removeQueueHeader(int size)
{
if(!this->semaphore->tryAcquire(1,this->timeout))
{
return FILE_RECORD_QUEUE_SEMAPHORE_TIMEOUT;//超时
}
if(size > this->size())
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_GET_SIZE_TOO_LARGE;
}
int crde = this->de;
crde = (crde + size) % this->queueCount;
//更新队头指针
if(!this->queueFile->seek(sizeof(int) * 2))
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_FILE_SEEK_ERROR;
}
QDataStream queueStream(this->queueFile);
queueStream.setVersion(QDataStream::Qt_5_10);
queueStream.setByteOrder(QDataStream::LittleEndian);
queueStream << crde;
if(!this->queueFile->flush() || this->queueFile->error() != QFile::NoError)
{
this->semaphore->release(1);
return FILE_RECORD_QUEUE_FILE_MODIFY_PTR_ERROR;
}
this->de = crde;
this->semaphore->release(1);
return FILE_RECORD_QUEUE_SUCCESS;
}
| true |
2226fd8ab50b1b7e3fd85e46563ae206ece68033 | C++ | karunmatharu/Android-4.4-Pay-by-Data | /external/marisa-trie/v0_1_5/lib/marisa_alpha/intvector.cc | UTF-8 | 3,054 | 2.796875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #include "intvector.h"
namespace marisa_alpha {
IntVector::IntVector()
: units_(), num_bits_per_int_(0), mask_(0), size_(0) {}
void IntVector::build(const Vector<UInt32> &ints) {
UInt32 max_int = 0;
for (UInt32 i = 0; i < ints.size(); ++i) {
if (ints[i] > max_int) {
max_int = ints[i];
}
}
build(max_int, ints.size());
for (UInt32 i = 0; i < ints.size(); ++i) {
set(i, ints[i]);
}
}
void IntVector::build(UInt32 max_int, std::size_t size) {
UInt32 num_bits_per_int = 0;
do {
++num_bits_per_int;
max_int >>= 1;
} while (max_int != 0);
const std::size_t new_size = (std::size_t)(
(((UInt64)num_bits_per_int * size) + 31) / 32);
Vector<UInt32> temp_units;
temp_units.resize(new_size, 0);
units_.swap(&temp_units);
num_bits_per_int_ = num_bits_per_int;
mask_ = ~0U;
if (num_bits_per_int != 32) {
mask_ = (1U << num_bits_per_int) - 1;
}
size_ = (UInt32)size;
}
void IntVector::mmap(Mapper *mapper, const char *filename,
long offset, int whence) {
MARISA_ALPHA_THROW_IF(mapper == NULL, MARISA_ALPHA_PARAM_ERROR);
Mapper temp_mapper;
temp_mapper.open(filename, offset, whence);
map(temp_mapper);
temp_mapper.swap(mapper);
}
void IntVector::map(const void *ptr, std::size_t size) {
Mapper mapper(ptr, size);
map(mapper);
}
void IntVector::map(Mapper &mapper) {
IntVector temp;
temp.units_.map(mapper);
mapper.map(&temp.num_bits_per_int_);
mapper.map(&temp.mask_);
mapper.map(&temp.size_);
temp.swap(this);
}
void IntVector::load(const char *filename,
long offset, int whence) {
Reader reader;
reader.open(filename, offset, whence);
read(reader);
}
void IntVector::fread(std::FILE *file) {
Reader reader(file);
read(reader);
}
void IntVector::read(int fd) {
Reader reader(fd);
read(reader);
}
void IntVector::read(std::istream &stream) {
Reader reader(&stream);
read(reader);
}
void IntVector::read(Reader &reader) {
IntVector temp;
temp.units_.read(reader);
reader.read(&temp.num_bits_per_int_);
reader.read(&temp.mask_);
reader.read(&temp.size_);
temp.swap(this);
}
void IntVector::save(const char *filename, bool trunc_flag,
long offset, int whence) const {
Writer writer;
writer.open(filename, trunc_flag, offset, whence);
write(writer);
}
void IntVector::fwrite(std::FILE *file) const {
Writer writer(file);
write(writer);
}
void IntVector::write(int fd) const {
Writer writer(fd);
write(writer);
}
void IntVector::write(std::ostream &stream) const {
Writer writer(&stream);
write(writer);
}
void IntVector::write(Writer &writer) const {
units_.write(writer);
writer.write(num_bits_per_int_);
writer.write(mask_);
writer.write(size_);
}
void IntVector::clear() {
IntVector().swap(this);
}
void IntVector::swap(IntVector *rhs) {
MARISA_ALPHA_THROW_IF(rhs == NULL, MARISA_ALPHA_PARAM_ERROR);
units_.swap(&rhs->units_);
Swap(&num_bits_per_int_, &rhs->num_bits_per_int_);
Swap(&mask_, &rhs->mask_);
Swap(&size_, &rhs->size_);
}
} // namespace marisa_alpha
| true |
82f0b425cccae97a49de89e58b57df93919cc149 | C++ | mkoldaev/bible50cpp | /lang/et/gen/Bible54.h | UTF-8 | 14,891 | 2.59375 | 3 | [] | no_license | #include <map>
#include <string>
class Bible54
{
struct et1 { int val; const char *msg; };
struct et2 { int val; const char *msg; };
struct et3 { int val; const char *msg; };
struct et4 { int val; const char *msg; };
struct et5 { int val; const char *msg; };
struct et6 { int val; const char *msg; };
public:
static void view1() {
struct et1 poems[] = {
{1, "1 Paulus, Kristuse Jeesuse apostel, Jumala, meie Päästja, ja Kristuse Jeesuse, meie lootuse käskimist mööda - "},
{2, "2 Timoteosele, oma tõelisele pojale usus: Armu, halastust, rahu Jumalalt, meie Isalt, ja Kristuselt Jeesuselt, meie Issandalt!"},
{3, "3 Makedooniasse minnes manitsesin ma sind jääma Efesosse keelama mõningaid, et nad ei õpetaks võõriti "},
{4, "4 ega hooliks müütidest ja lõpututest sugupuudest, mis soodustavad pigem vaidlusi kui Jumala majapidamist, mis on usus. "},
{5, "5 Selle korralduse eesmärk on armastus puhtast südamest ja heast südametunnistusest ja siirast usust. "},
{6, "6 Mõned neist on kaldunud kõrvale ja hakanud lobisema, "},
{7, "7 tahtes olla seaduseõpetajad, mõistmata ise, mida nad räägivad või mida nad tõe pähe pakuvad."},
{8, "8 Me ju teame, et Seadus on hea, kui keegi seda kasutab korrakohaselt, "},
{9, "9 teades seda, et Seadust pole seatud kõigile, vaid ülekohtustele ja tõrkujatele, jumalakartmatutele ja patustele, nurjatutele ja labastele, isa- ja ematapjaile, mõrtsukaile, "},
{10, "10 hoorajaile, poisipilastajaile, inimröövijaile, valetajaile, valevandujaile ja kellele tahes muule, mis käib terve õpetuse vastu. "},
{11, "11 Terve õpetus vastab õndsa Jumala kirkuse evangeeliumile, mis on usaldatud minu kätte."},
{12, "12 Ma olen tänulik Kristusele Jeesusele, meie Issandale, kes on mu teinud vägevaks sellega, et ta oma teenistusse pannes on pidanud ustavaks mind, "},
{13, "13 endist Jumala teotajat ja tagakiusajat ja julmurit. Kuid ta on mu peale halastanud, sest uskmatuses ma tegutsesin arutult. "},
{14, "14 Aga meie Issanda arm on olnud minu vastu üliväga suur koos usu ja armastusega, mis meile on antud Kristuses Jeesuses. "},
{15, "15 Ustav on see sõna ja väärib igati vastuvõtmist, et Kristus Jeesus on tulnud maailma päästma patuseid, kelle seast esimene olen mina. "},
{16, "16 Kuid minu peale on halastatud seepärast, et Kristus Jeesus saaks osutada kogu oma pikka meelt kõigepealt mind eeskujuks tuues neile, kes edaspidi hakkavad temasse uskuma ja pärivad igavese elu. "},
{17, "17 Aga ajastute Kuningale, surematule, nähtamatule, ainsale Jumalale olgu au ja kirkus igavesest ajast igavesti! Aamen."},
{18, "18 Selle korralduse ma annan sulle, mu poeg Timoteos, varasemate sinu kohta käivate ennustuste põhjal, et sa nende toel võitleksid head võitlust, "},
{19, "19 säilitades usku ja puhast südametunnistust, mille mõned on enesest ära tõuganud, ja nende usulaev on läinud põhja. "},
{20, "20 Nende seas on Hümenaios ja Aleksandros; nemad ma olen loovutanud saatanale, et nad karistatuna loobuksid Jumala teotamisest."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view2() {
struct et2 poems[] = {
{1, "1 Ma kutsun siis üles anuma, palvetama, tegema eestpalveid ja tänupalveid kõigi inimeste eest, "},
{2, "2 kuningate ja kõigi ülemuste eest, et me võiksime elada vaikset ja rahulikku elu kõiges jumalakartuses ja väärikuses. "},
{3, "3 See on hea ja meeldiv Jumala, meie Päästja silmis, "},
{4, "4 kes tahab, et kõik inimesed pääseksid ja tuleksid tõe tundmisele."},
{5, "5 Sest üks on Jumal, üks on ka vahemees Jumala ja inimeste vahel: inimene Kristus Jeesus, "},
{6, "6 kes on iseenese loovutanud lunastushinnaks kõikide eest, tunnistusena selleks määratud ajal. "},
{7, "7 Selle sõnumi kuulutajaks ja apostliks olen ma pandud - ma räägin tõtt, ma ei valeta -, paganate õpetajaks usus ja tões."},
{8, "8 Ma tahan siis, et mehed igal pool palvetaksid, tõstes üles pühad käed ilma viha ja kahtlemiseta."},
{9, "9 Niisamuti ka naised, kombekalt rõivastatuna, ehtigu end häbelikkuse ja mõõdukusega, mitte soengute ega kulla ega pärlite ega kallite riietega, "},
{10, "10 vaid heade tegudega, nagu on kohane naistele, kes end tunnistavad jumalakartlikeks."},
{11, "11 Naine õppigu vaikselt täielikus alistumises; "},
{12, "12 ma ei luba naisel õpetada ega mehe üle valitseda, vaid ta olgu vaikne. "},
{13, "13 Sest Aadam loodi enne, seejärel Eeva, "},
{14, "14 ka ei petetud Aadamat, vaid naine peteti ära ja ta sattus üleastumisse, "},
{15, "15 ent ta pääseb lastesünnitamise kaudu, kui ta mõõdukuses jääb usku ja armastusse ja pühitsusse."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view3() {
struct et3 poems[] = {
{1, "1 See on ustav sõna. Kui keegi igatseb ülevaatajaametit, siis ta igatseb üllast tööd. "},
{2, "2 Ülevaataja peab siis olema laitmatu: ühenaisemees, kaine, mõõdukas, kombekas, külalislahke, osav õpetama, "},
{3, "3 kes ei ole joomar ega kakleja, vaid leebe, rahupüüdlik ja rahahimuta, "},
{4, "4 kes oma peret hästi juhatab ja kelle lapsed elavad kuulekuses ja kõigiti väärikalt. "},
{5, "5 Sest kui keegi ei oska juhatada oma peret, kuidas ta võib kanda hoolt Jumala koguduse eest? "},
{6, "6 Ta ärgu olgu ka vastpöördunu, et ta ei läheks upsakaks ega langeks sama süü sisse kui kurat. "},
{7, "7 Tal peab olema hea tunnistus ka neilt, kes on väljaspool kogudust, et ta ei langeks hurjutamise alla ega kuradi silmusesse."},
{8, "8 Niisamuti peavad abilised olema väärikad, kes ei ole kahekeelsed, kes ei tarvita liialt veini, kes ei ole liigkasuvõtjad, "},
{9, "9 vaid kellel usu saladus on puhtas südametunnistuses. "},
{10, "10 Neidki aga katsutagu enne läbi ja seejärel nad asugu teenima, kui on laitmatud. "},
{11, "11 Niisamuti olgu naised väärikad, mitte keelepeksjad, vaid kained, ustavad kõigis asjus. "},
{12, "12 Abilised olgu ühenaisemehed, kes lapsi ja oma peret hästi juhatavad. "},
{13, "13 Sest kes hästi peavad oma ametit, saavad tunnustuse ja rohkesti julgust usus Kristusesse Jeesusesse."},
{14, "14 Seda ma kirjutan sulle, lootes ise peatselt tulla sinu juurde. "},
{15, "15 Kui mu tulek siiski viibib, sa teaksid, milline peab olema eluviis Jumala kojas, mis on elava Jumala kogudus, tõe sammas ja alustugi."},
{16, "16 Tunnistatavalt suur on jumalakartuse saladus: Jumal on avalikuks saanud lihas, õigeks tunnistatud vaimus, nähtav olnud inglitele, kuulutatud paganatele, usutud maailmas, võetud üles kirkusesse."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view4() {
struct et4 poems[] = {
{1, "1 Aga Vaim ütleb selge sõnaga, et tulevastel aegadel mõned taganevad usust ja hoiavad eksitajate vaimude ja kurjade vaimude õpetuste poole "},
{2, "2 nende valerääkijate silmakirjalikkuse mõjul, kes on põletanud tulemärgi oma südametunnistusse. "},
{3, "3 Nad keelavad abiellumast ja käsivad hoiduda roogadest, mis Jumal on loonud usklikele ja tõde juba mõistnutele tänuga vastuvõtmiseks. "},
{4, "4 Sest kõik, mis Jumal on loonud, on hea ja miski pole taunitav, mida võetakse vastu tänuga, "},
{5, "5 sest seda pühitsetakse Jumala sõna ja palve läbi."},
{6, "6 Kui sa seda vendadele õpetad, siis sa oled Kristuse Jeesuse tubli teenija, üles kasvanud usu ja hea õpetuse sõnades, mille järgi sa oled hakanud käima. "},
{7, "7 Aga labased kõned ja vananaistejutud lükka tagasi, harjuta end jumalakartuses! "},
{8, "8 Sest kehalisest harjutamisest on vähe kasu, aga jumalakartus on kasulik kõigeks ning sellel on praeguse ja tulevase elu tõotus. "},
{9, "9 See sõna on ustav ja väärib igati vastuvõtmist: "},
{10, "10 selleks me ju näeme vaeva ja võitleme, sest me oleme oma lootuse pannud elava Jumala peale, kes on kõigi inimeste, iseäranis usklike Päästja."},
{11, "11 Seda käsi ja õpeta! "},
{12, "12 Ärgu keegi mõtelgu üleolevalt sinu noorusest, vaid saa usklikele eeskujuks kõnes, käitumises, armastuses, usus, puhtuses! "},
{13, "13 Ole hoolas ette lugema, ergutama, õpetama, kuni ma tulen! "},
{14, "14 Ära jäta hooletusse vaimuandi, mis sulle anti ennustuse läbi, kui vanemad panid oma käed sinu peale! "},
{15, "15 Nende asjade peale mõtle, ela selles, et su edenemine oleks avalik kõigile! "},
{16, "16 Pane tähele iseennast ja õpetust, jää kõigesse sellesse püsima, kui sa seda teed, siis sa päästad enda ja need, kes sind kuulavad."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view5() {
struct et5 poems[] = {
{1, "1 Vana mehega ära kärgi, vaid räägi lahkesti nagu isaga, noorematega nagu vendadega, "},
{2, "2 vanemate naistega nagu emadega, noorematega nagu õdedega - kõiges puhtuses."},
{3, "3 Austa lesknaisi, kes on tõeliselt lesed! "},
{4, "4 Aga kui kellelgi lesknaisel on lapsi või lapselapsi, siis need õppigu esmalt ise kohtlema jumalakartlikult oma peret ja tänulikult tasuma, mis nad on võlgu oma vanematele; sest see on meelepärane Jumala silmis. "},
{5, "5 Kes on aga lesknaine tõeliselt ja üksi maha jäänuna loodab Jumala peale, see jääb anuma ja palvetama nii ööd kui päevad. "},
{6, "6 Kes aga liiderdab, see on elusalt surnud. "},
{7, "7 Ja käsi neid, et nad elaksid laitmatult. "},
{8, "8 Kui aga keegi omaste ja kõige lähedasemate eest ei hoolitse, siis see on salanud ära usu ja on halvem kui uskmatu."},
{9, "9 Leskede hulka loetagu see, kes on vähemalt kuuekümneaastane ning on olnud ühemehenaine, "},
{10, "10 kelle heade tegude kohta on tunnistajaid, olgu ta lapsi üles kasvatanud või võõraid vastu võtnud või pühade jalgu pesnud või viletsaid abistanud või otsinud võimalust teha mis tahes heategusid."},
{11, "11 Nooremad lesed aga jäta välja, sest kui neid haarab iharus, hoolimata Kristusest, siis nad tahavad abielluda "},
{12, "12 ja neile saab süüks, et nad on murdnud truudust esimesele lepingule. "},
{13, "13 Pealegi nad õpivad olema jõude ja käima mööda maju, ent nad ei ole üksnes jõude, vaid nad on ka lobisejad ja uudishimutsejad ning räägivad seda, mida ei sobi. "},
{14, "14 Ma tahan siis, et nooremad abielluksid, sünnitaksid lapsi, hoiaksid kodu ega annaks meie vastastele mingit alust halvustamiseks. "},
{15, "15 Sest mõned on juba saatana jälgedesse pöördunud."},
{16, "16 Kui uskliku peres on lesknaisi, siis ta toetagu neid ja ärgu tulgu see koormaks kogudusele, et kogudus võiks toetada neid, kes on lesknaised tõeliselt."},
{17, "17 Vanemaid, kes hästi juhatavad kogudusi, peetagu kahevõrra austusväärseiks, eriti neid, kes näevad vaeva sõna ja õpetamisega. "},
{18, "18 Pühakiri ütleb ju: 'Sa ei tohi siduda kinni pahmast tallava härja suud!' ja 'Tööline on väärt oma palka'."},
{19, "19 Vanema vastu tõstetud kaebust ära võta muidu kuulda, kui et on kaks või kolm tunnistajat. "},
{20, "20 Patustajaid noomi kõikide ees, et ka teised hakkaksid kartma."},
{21, "21 Ma vannutan sind Jumala ja Issanda Jeesuse Kristuse ja valitud inglite ees, et sa seda kõike silmas peaksid ilma eelarvamusteta ega teeks midagi erapoolikult!"},
{22, "22 Ära ole kärmas käsi kellegi peale panema, ära ka tee end võõraste pattude osaliseks! Hoia end puhtana!"},
{23, "23 Ära joo enam vett, vaid kasuta veidi veini oma kõhu ja oma sagedaste põdemiste pärast."},
{24, "24 Mõne inimese patud on kohe ilmsed ja viivad kohtumõistmisele, aga mõne patud järgnevad neile. "},
{25, "25 Niisamuti on ka head teod ilmsed ning needki, mis seda ei ole, ei saa jääda varjule."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view6() {
struct et6 poems[] = {
{1, "1 Kes iganes on orjana ikke all, pidagu oma peremehi kogu austuse vääriliseks, et Jumala nime ja õpetust ei teotataks. "},
{2, "2 Aga kellel on usklikud peremehed, ärgu mõtelgu neist üleolevalt sellepärast, et nad on vennad, vaid teenigu neid veel enam, sest nad on usklikud ja armsad ning heategevuses püüdlikud. Seda õpeta ja manitse! "},
{3, "3 Kui keegi õpetab teisiti ega jää meie Issanda Jeesuse Kristuse tervete sõnade ja jumalakartusele vastava õpetuse juurde, "},
{4, "4 siis see on iseennast täis ega saa millestki aru, vaid on haige vaidlemisest ja sõnelemisest, millest tekib kadedust, riidu, teotust, kurje kahtlustusi, "},
{5, "5 lõputuid hõõrumisi inimeste vahel, kes on mõistuse poolest rikutud ja ilma jäänud tõest, ning kes arvavad jumalakartuse olevat tuluallika."},
{6, "6 Ent jumalakartus on suur tuluallikas, kui inimesele piisab sellest, mis tal on. "},
{7, "7 Ei ole me ju midagi toonud maailma, nii ei suuda me ka midagi maailmast ära viia. "},
{8, "8 Kui meil on aga elatist ja ihukatet, siis olgu neist meile küll."},
{9, "9 Kes tahavad aga rikastuda, need langevad kiusatusse ja lõksu, paljudesse rumalaisse ja kahjulikesse himudesse, mis vajutavad inimesed sügavale hävingusse ja hukatusse. "},
{10, "10 Jah, kõige kurja juur on rahaarmastus, sest raha ihaldades on mõnedki eksinud ära usust ja on ise endale valmistanud palju valu."},
{11, "11 Sina aga, Jumala inimene, põgene selle eest! Taotle õigust, jumalakartust, usku, armastust, kannatlikkust, tasadust! "},
{12, "12 Võitle head usuvõitlust, hakka kinni igavesest elust, millele sa oled kutsutud, kui sa oled andnud hea tunnistuse paljude tunnistajate ees."},
{13, "13 Ma käsin sind Jumala ees, kes teeb kõik elavaks, ja Kristuse Jeesuse ees, kes Pontius Pilaatuse ees andis hea tunnistuse, "},
{14, "14 et sa käsku säilitaksid puhtalt ja laitmatult meie Issanda Jeesuse Kristuse ilmumiseni, "},
{15, "15 mille parajal ajal toob nähtavale õnnis ja ainus võimas valitseja, kuningate Kuningas ja isandate Issand, "},
{16, "16 kellel ainsana on surematus, kes elab ligipääsmatus valguses, keda ükski inimene pole näinud ega suudagi näha. Tema päralt olgu au ja igavene võimus! Aamen."},
{17, "17 Neid, kes on nüüdsel ajal rikkad, käsi, et nad ei oleks ülbed ega loodaks ebakindlale rikkusele, vaid Jumalale, kes valmistab meile kõike rikkalikult maitsmiseks; "},
{18, "18 käsi neil teha head, saada rikkaks headelt tegudelt, olla lahke ja helde käega, "},
{19, "19 talletades enesele vara heaks aluskiviks tuleviku tarvis, et haarata kinni tõelisest elust."},
{20, "20 Oh Timoteos, hoia, mis su hoolde on usaldatud, pöördu ära labastest tühijuttudest ja valeliku tunnetuse vastuväidetest, "},
{21, "21 mida omaks tunnistades mõned on kaldunud kõrvale usust. Arm olgu teiega!"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
}; | true |
6492f0f37eb7afd90eb4c3ff04a3e77a716df23c | C++ | sumanth1462/CipherSchools_Assignments | /Stacks&Queues/SortStack.cpp | UTF-8 | 733 | 3.40625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void print(stack<int>s){
while(!s.empty()){
cout<<s.top()<<' ';
s.pop();
}
cout<<endl;
}
void addInStack(stack<int>&s,int element){
if(s.empty()||element>s.top()){
s.push(element);
return;
}
int temp=s.top();
s.pop();
addInStack(s,element);
s.push(temp);
}
void sort(stack<int>&s){
if(s.empty()){
return;
}
int element=s.top();
s.pop();
sort(s);
addInStack(s,element);
}
int main(){
stack<int>s;
s.push(50);
s.push(40);
s.push(-3);
s.push(30);
cout<<"Original Order"<<endl;
print(s);
sort(s);
cout<<"Sorted Order"<<endl;
print(s);
return 0;
}
| true |
7a64ba7af6683d56f3a700de0ffd354b050fd2e4 | C++ | cv21rgt/Project-Euler-CPP | /Problem_9.cpp | UTF-8 | 1,799 | 4.21875 | 4 | [] | no_license | /*
* Problem: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
* a^2 + b^2 = c^2
*
* For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
*
* There exists exactly one Pythagorean triplet for which a + b + c = 1000.
* Find the product abc.
*
* Solution: 31875000
*/
#include <iostream>
int main()
{
// initialize variables to hold the Pythagorean triplets
int a {1};
int b {1};
int c {1};
// variable to hold the product of a x b x c
long long product {1};
// variables for the three conditions that must be met
// by a Pythagorean triplet
bool condition_1 {false};
bool condition_2 {false};
bool condition_3 {false};
// variable to help exit loop early when we find the solution
bool track { false };
for (a; a < 1000; ++a)
{
for (b = a + 1; b < 1000; ++b)
{
for (c = b + 1; c < 1000; ++c)
{
condition_1 = (a < b < c) ? true: false;
condition_2 = ((a*a + b*b) == c*c) ? true: false;
condition_3 = ((a + b + c) == 1000) ? true: false;
if (condition_1 == true && condition_2 == true && condition_3 == true)
{
product = a * b * c;
track = true;
break;
}
}
if (track)
break;
}
if (track)
break;
}
std::cout << "Pythagorean triplet for which a + b + c = 1000 is "
<< a << "^2 + "
<< b << "^2 = "
<< c << "^2" << '\n';
std::cout << "The product of abc is "
<< product << '\n';
return 0;
} | true |
5193b13d6b6c8b0c1685741b996aeea286e7b07a | C++ | giannissterg/compiler | /compiler/parser/matcher/rule.h | UTF-8 | 2,271 | 3.296875 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include "stream.h"
#include <variant>
#include <tuple>
#include <optional>
class Rule
{
public:
Rule() = default;
virtual ~Rule() = 0;
virtual bool match(Stream<char>* inputStream) = 0;
};
class CharacterRule : public Rule
{
public:
CharacterRule(char character) : m_character(character) {}
bool match(Stream<char>* inputStream)
{
char nextChar = inputStream->top();
return (nextChar == m_character);
}
private:
char m_character;
};
class OrRule : public Rule
{
public:
OrRule(std::vector<Rule*> rules) : m_rules(rules) {}
bool match(Stream<char>* inputStream)
{
for (auto rule : m_rules)
{
if (rule->match(inputStream))
{
return true;
}
}
return false;
}
private:
std::vector<Rule*> m_rules;
};
class OptionalRule : public Rule
{
public:
OptionalRule(Rule* rule) : m_rule(rule) {}
bool match(Stream<char>* inputStream) { return true; }
private:
Rule* m_rule;
};
class ChainRule : public Rule
{
public:
ChainRule(std::vector<Rule*> rules) : m_rules(rules) {}
bool match(Stream<char>* inputStream)
{
for (auto rule : m_rules)
{
if (!rule->match(inputStream)) {
return false;
}
inputStream->next();
}
return true;
}
std::vector<Rule*> getRules() const { return m_rules; }
private:
std::vector<Rule*> m_rules;
};
class DigitRule : public OrRule
{
public:
DigitRule() : OrRule({ new CharacterRule('0'), new CharacterRule('1'), new CharacterRule('2')}) {}
};
class RepeatingRule : public Rule
{
public:
RepeatingRule(Rule* rule) : m_rule(rule) {}
private:
Rule* m_rule;
};
class WordRule : public Rule
{
public:
WordRule(std::string word) : m_word(word) {}
bool match(Stream<char>* inputStream)
{
Stream<char>* input = inputStream;
for (unsigned int i = 0; i < m_word.size(); ++i)
{
if (m_word[i] == input->top())
{
input->next();
}
else
{
return false;
}
}
return true;
}
std::string getWord() const { return m_word; }
private:
std::string m_word;
};
class ScopeRule : public ChainRule
{
public:
ScopeRule(char openScopeCharacter, Rule* innerRule, char closeScopeCharacter) :
ChainRule({
new CharacterRule(openScopeCharacter),
innerRule,
new CharacterRule(closeScopeCharacter)
}) {}
};
| true |
22f1b38cfe10e4785bb648976802549818b631f3 | C++ | LewisWakeford/FirstPersonPlatformer | /game/include/ArrayBuffer.h | UTF-8 | 1,395 | 3.046875 | 3 | [] | no_license | #ifndef ARRAYBUFFER_H
#define ARRAYBUFFER_H
#include <Buffer.h>
/*
Class: ArrayBuffer
A sub class of buffer that contains functionality for sub-arrays.
Contains an internal class to manage arrays, which can be used by VAOs to bind attributes.
*/
class ArrayBuffer : public Buffer
{
public:
ArrayBuffer(GLenum type);
virtual ~ArrayBuffer();
class Array
{
public:
unsigned int mName; //The name of this array, for future reference.
unsigned int mElementsPerVertex; //Order of this array in the bufffer.
unsigned int mElementType; //Size of each object in the array. This is each float or byte for example, not each entire structure.
unsigned int mStride; //Bytes to skip between vertices.
unsigned int mOffset; //Offset from the start of the array.
};
//Creates or overwrites an array with name: arrayName.
void setArray(unsigned int arrayName, unsigned int elementsPerVertex, unsigned int elementType, unsigned int stride, unsigned int offset, unsigned int vertexAttrib);
//Returns the array with name: arrayName or null if not found.
const Array* getArray(unsigned int arrayName) const;
void clearArrays();
protected:
std::vector<Array> mArrays;
private:
};
#endif // VERTEXBUFFER_H
| true |
9c9eca19f2c791fa073bde89457ec37adb5ca60a | C++ | xlnx/koi | /src/traits/function.hpp | UTF-8 | 1,892 | 3.0625 | 3 | [] | no_license | #pragma once
#include <type_traits>
#include <functional>
#include <tuple>
namespace koi
{
namespace traits
{
template <typename T>
struct Helper;
template <typename T>
struct HelperImpl : Helper<decltype( &T::operator() )>
{
};
template <typename T>
struct Helper : HelperImpl<typename std::decay<T>::type>
{
};
template <typename Ret, typename Cls, typename... Args>
struct Helper<Ret ( Cls::* )( Args... )>
{
using return_type = Ret;
using argument_type = std::tuple<Args...>;
};
template <typename Ret, typename Cls, typename... Args>
struct Helper<Ret ( Cls::* )( Args... ) const>
{
using return_type = Ret;
using argument_type = std::tuple<Args...>;
};
template <typename R, typename... Args>
struct Helper<R( Args... )>
{
using return_type = R;
using argument_type = std::tuple<Args...>;
};
template <typename R, typename... Args>
struct Helper<R ( * )( Args... )>
{
using return_type = R;
using argument_type = std::tuple<Args...>;
};
template <typename R, typename... Args>
struct Helper<R ( *const )( Args... )>
{
using return_type = R;
using argument_type = std::tuple<Args...>;
};
template <typename R, typename... Args>
struct Helper<R ( *volatile )( Args... )>
{
using return_type = R;
using argument_type = std::tuple<Args...>;
};
template <typename F>
struct InvokeResultOf
{
using type = typename Helper<F>::return_type;
};
template <typename F>
struct ArgumentTypeOf
{
using type = typename Helper<F>::argument_type;
};
template <typename Ret, typename Args>
struct InferFunctionAux
{
};
template <typename Ret, typename... Args>
struct InferFunctionAux<Ret, std::tuple<Args...>>
{
using type = std::function<Ret( Args... )>;
};
template <typename F>
struct InferFunction
{
using type = typename InferFunctionAux<
typename InvokeResultOf<F>::type,
typename ArgumentTypeOf<F>::type>::type;
};
} // namespace traits
} // namespace koi
| true |
d34f2db800037a170583538424e00dec9ee7246f | C++ | Darptolus/SCM | /SCMUlate/src/common/instructions.cpp | UTF-8 | 4,753 | 2.578125 | 3 | [] | no_license | #include "instructions.hpp"
namespace scm {
bool
decoded_instruction_t::decodeOperands(reg_file_module * const reg_file_m) {
// TODO: JMPLBL cannot be decoded because the potential of labels that have not been
// parsed yet. Probably need to find a solution for this.
if (this->instruction != "JMPLBL") {
if (op1_s != "" && op1.type == operand_t::UNKNOWN) {
// Check for imm or regisiter
if (!instructions::isRegister(op1_s)) {
// IMMEDIATE VALUE CASE
// TODO: Think about the signed option of these operands
op1.type = operand_t::IMMEDIATE_VAL;
op1.value.immediate = std::stoull(op1_s);
} else {
// REGISTER REGISTER ADD CASE
op1.type = operand_t::REGISTER;
op1.value.reg = instructions::decodeRegister(op1_s);
op1.value.reg.reg_ptr = reg_file_m->getRegisterByName(op1.value.reg.reg_size, op1.value.reg.reg_number);
op1.value.reg.reg_size_bytes = reg_file_m->getRegisterSizeInBytes(op1.value.reg.reg_size);
}
op1.read = OP_IO::OP1_RD & this->op_in_out;
op1.write = OP_IO::OP1_WR & this->op_in_out;
}
if (op2_s != "" && op2.type == operand_t::UNKNOWN) {
// Check for imm or regisiter
if (!instructions::isRegister(op2_s)) {
// IMMEDIATE VALUE CASE
// TODO: Think about the signed option of these operands
op2.type = operand_t::IMMEDIATE_VAL;
op2.value.immediate = std::stoull(op2_s);
} else {
// REGISTER REGISTER ADD CASE
op2.type = operand_t::REGISTER;
op2.value.reg = instructions::decodeRegister(op2_s);
op2.value.reg.reg_ptr = reg_file_m->getRegisterByName(op2.value.reg.reg_size, op2.value.reg.reg_number);
op2.value.reg.reg_size_bytes = reg_file_m->getRegisterSizeInBytes(op2.value.reg.reg_size);
}
op2.read = OP_IO::OP2_RD & this->op_in_out;
op2.write = OP_IO::OP2_WR & this->op_in_out;
}
if (op3_s != "" && op3.type == operand_t::UNKNOWN) {
// Check for imm or regisiter
if (!instructions::isRegister(op3_s)) {
// IMMEDIATE VALUE CASE
// TODO: Think about the signed option of these operands
op3.type = operand_t::IMMEDIATE_VAL;
op3.value.immediate = std::stoull(op3_s);
} else {
// REGISTER REGISTER ADD CASE
op3.type = operand_t::REGISTER;
op3.value.reg = instructions::decodeRegister(op3_s);
op3.value.reg.reg_ptr = reg_file_m->getRegisterByName(op3.value.reg.reg_size, op3.value.reg.reg_number);
op3.value.reg.reg_size_bytes = reg_file_m->getRegisterSizeInBytes(op3.value.reg.reg_size);
}
op3.read = OP_IO::OP3_RD & this->op_in_out;
op3.write = OP_IO::OP3_WR & this->op_in_out;
}
}
// For codelets
if (type == EXECUTE_INST) {
// TODO: To change the number oof arguments, wee should change this number
unsigned char ** newArgs = new unsigned char*[3];
if (op1.type == operand_t::IMMEDIATE_VAL) {
newArgs[0] = reinterpret_cast<unsigned char *>(op1.value.immediate);
} else if (op1.type == operand_t::REGISTER) {
newArgs[0] = op1.value.reg.reg_ptr;
} else {
newArgs[0] = nullptr;
}
if (op2.type == operand_t::IMMEDIATE_VAL) {
newArgs[1] = reinterpret_cast<unsigned char *>(op2.value.immediate);
} else if (op2.type == operand_t::REGISTER) {
newArgs[1] = op2.value.reg.reg_ptr;
} else {
newArgs[1] = nullptr;
}
if (op3.type == operand_t::IMMEDIATE_VAL) {
newArgs[2] = reinterpret_cast<unsigned char *>(op3.value.immediate);
} else if (op3.type == operand_t::REGISTER) {
newArgs[2] = op3.value.reg.reg_ptr;
} else {
newArgs[2] = nullptr;
}
cod_exec = scm::codeletFactory::createCodelet(this->getInstruction(), newArgs);
if (cod_exec == nullptr)
return false;
op1.read = OP_IO::OP1_RD & cod_exec->getOpIO();
op1.write = OP_IO::OP1_WR & cod_exec->getOpIO();
op2.read = OP_IO::OP2_RD & cod_exec->getOpIO();
op2.write = OP_IO::OP2_WR & cod_exec->getOpIO();
op3.read = OP_IO::OP3_RD & cod_exec->getOpIO();
op3.write = OP_IO::OP3_WR & cod_exec->getOpIO();
}
return true;
}
} | true |
b580f56ce3b945dc4a2ae544abf3d2231af63dc3 | C++ | MrrrrFox/OOP | /CPP/3rd semester - Fundamental Concepts of Object-Oriented Programming/lab08/intLinkedList.h | UTF-8 | 818 | 3.15625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
class IntLinkedList;
class Element
{
friend class IntLinkedList;
public:
int value;
Element * next;
Element(); // bezparametrowy
Element(int); // ustawiajacy wartosc
Element(Element&); // kopiujacy
~Element(); // destruktor
};
class IntLinkedList
{
Element *head;
Element *tail;
std::string name;
public:
IntLinkedList();
IntLinkedList(std::string);
~IntLinkedList();
int size();
int isEmpty();
void print();
friend void print(IntLinkedList&);
void append(int);
void append(Element&);
void append(IntLinkedList&);
void addSorted(int, bool = false);
void addSorted(Element&, bool = false);
void addSorted(IntLinkedList&);
void removeFirst();
void removeLast();
void removeValue(int);
bool contains(int);
};
| true |
8215f6d5aa313e0d5cdffa672f56fb795593ecf8 | C++ | azy2/UEVoxel | /Source/Voxel/BlockGrass.cpp | UTF-8 | 271 | 2.546875 | 3 | [] | no_license | #include "BlockGrass.h"
FVector2D FBlockGrass::texturePosition(Direction dir) {
switch (dir) {
case Up:
return FVector2D(0, 0);
case Down:
return FVector2D(2, 0);
default:
return FVector2D(3, 0);
}
}
bool FBlockGrass::isSolid(Direction dir) {
return true;
} | true |
1d9bae560c32643887020a785cf3a5851e89b937 | C++ | sushiljacksparrow/Code | /MAXSUB.cpp | UTF-8 | 626 | 2.59375 | 3 | [] | no_license | #include <cstdio>
using namespace std;
#define M 1000000009
int modxp(int p) {
long long r = 1, b = 2;
while(p>0) {
if(p&1) r = (r*b)%M;
p >>= 1;
b = (b*b)%M;
}
return (int)r;
}
int main() {
int t, n, i, z, m, a, s;
long long p;
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
m = -2147483648, p = z = 0, s = 1;
for(i = 0; i < n; i++) {
scanf("%d", &a);
if(a > m) {
m = a;
s = 1;
}
else if(a == m) s++;
if(!a) z++;
if(a > 0) p += a;
}
if(m < 0) printf("%d %d\n", m, s);
else if(m==0) printf("0 %d\n", modxp(z)-1);
else printf("%lld %d\n", p, modxp(z));
}
return 0;
}
| true |
59ec66810d2b0d06813491d75ddc017d8230a7a6 | C++ | skJack/Leetcode | /DFS/200.岛屿数量.cpp | UTF-8 | 1,948 | 3.453125 | 3 | [] | no_license | /*
岛屿数量
Category Difficulty Likes Dislikes
algorithms Medium (46.40%) 318 -
Tags
Companies
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
*/
//方法一:dfs
class Solution {
public:
void helper(int i,int j,int row,int col,vector<vector<char>>& grid,vector<vector<bool>> &visit)
{
if(i==-1||i>row-1||j==-1||j>col-1)
//if(i==-1||j==-1)
{
return;
}
else if(grid[i][j]=='0'||visit[i][j]==true)
{
return;
}
else
{
visit[i][j] = true;
helper(i+1,j,row,col,grid,visit);
helper(i-1,j,row,col,grid,visit);
helper(i,j+1,row,col,grid,visit);
helper(i,j-1,row,col,grid,visit);
}
}
//方法一:dfs遍历,并每次记录根节点的数量
int numIslands(vector<vector<char>>& grid) {
int row = grid.size();
if(row==0)
return 0;
int col = grid[0].size();
vector<vector<bool>>visit(row,vector<bool>(col,false));
int ans = 0;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(grid[i][j]=='1'&&visit[i][j]==false)
{
//发现新大陆
ans++;
helper(i,j,row,col,grid,visit);
}
}
}
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cout<<visit[i][j]<<" ";
}
cout<<endl;
}
return ans;
}
//方法二:并查集,todo
};
| true |
648ee0426be94fb5f6e52e6bd67762ee9ee22fe1 | C++ | jojo4444/-practice | /bfu/lab2/кватернионы/gcomplex.h | WINDOWS-1251 | 1,484 | 3.1875 | 3 | [] | no_license | #pragma once
#include <complex>
#include "vector3.h"
class gcomplex {
public:
gcomplex();
gcomplex(ld w, ld x, ld y, ld z);
gcomplex(ld w, const vector3& u);
gcomplex(const vector3& u, ld w);
gcomplex(std::complex<ld> z1, std::complex<ld> z2);
ld getW() const;
ld getX() const;
ld getY() const;
ld getZ() const;
vector3 getVec() const;
void setW(ld w);
void setX(ld x);
void setY(ld y);
void setZ(ld z);
void setVec(vector3 u);
gcomplex& operator= (const gcomplex& u);
gcomplex operator+ (const gcomplex& u);
gcomplex operator* (const gcomplex& u);
gcomplex operator* (ld k);
friend std::ostream& operator<< (std::ostream& out, const gcomplex& u) {
char sgnX = (u.getX() > 0)?'+':'-';
char sgnY = (u.getY() > 0)?'+':'-';
char sgnZ = (u.getZ() > 0)?'+':'-';
out << std::fixed << "(" << u.getW() << sgnX << fabs(u.getX()) << "i" << sgnY << fabs(u.getY()) << "j" << sgnZ << fabs(u.getZ()) << "k)";
return out;
}
friend std::istream& operator>> (std::istream& in, gcomplex& u) {
ld w;
in >> w;
u.setW(w);
vector3 v;
in >> v;
u.setVec(v);
return in;
}
private:
ld w_;
vector3 v_;
};
gcomplex conjugate(const gcomplex u);//
ld lenght(const gcomplex u);
gcomplex invert(const gcomplex u);//u^-1 = conj(q)/|q|^2
| true |
a36300d5f64fee413a92a5952d353f74f8425691 | C++ | HelenXR/design_patterns_HelenXR-Dev- | /behavioral_patterns/memento/source/player.cc | UTF-8 | 325 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "player.h"
Player::Player(string date){
date_ = date;
}
Player::~Player(){
}
void Player::SetDate(string date){
date_ = date;
}
string Player::GetDate(){
return date_;
}
void Player::CreateMemento(){
memento_ = new Memento(date_);
}
void Player::Recovery(Memento *memento){
SetDate(memento->GetDate());
} | true |
b96b73541e6a056d943d433dd2cb96b34fad6e5c | C++ | autul2017831021/Codeforces_Atcoder_Solved_Problems | /codeforces/1030/A.cpp | UTF-8 | 244 | 2.59375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
main()
{
int n,c=0;
cin>>n;
while(n--)
{
int x;cin>>x;
if(x==1)
c++;
}
if(c==0)
cout<<"EASY"<<endl;
else
cout<<"HARD"<<endl;
}
| true |
fdb81993ec29d4cfc8c06974211ac8f079c53196 | C++ | eazlong/cashback | /source/server/src/codec.cpp | UTF-8 | 9,545 | 2.609375 | 3 | [] | no_license | #include "codec.h"
#include "datas.h"
#include <assert.h>
#include <sstream>
#include "user.h"
void* key_value_codec::decode( const std::string& message )
{
if ( message.empty() )
return NULL;
std::stringstream ss( message );
std::string temp;
void* buf = get_buffer();
while ( getline( ss, temp ) )
{
if ( !temp.empty() )
{
size_t s = temp.find(SEPARATOR_1);
std::string& key = temp.substr( 0, s );
std::string& val = temp.substr( s+1 );
if ( !fill_buffer( buf, key, val ) )
{
release_buffer( buf );
return NULL;
}
}
}
return buf;
}
bool user_info_codec::fill_buffer( void* buf, const std::string& key, const std::string& val )
{
user_info* info = (user_info*)buf;
if ( key == "user_name" )
{
info->name = val;
}
else if ( key == "password" )
{
info->password = val;
}
else if ( key == "type" )
{
info->type = (user_type)atoi(val.c_str());
}
else if ( key == "token" )
{
info->token = atoi(val.c_str());
}
else
{
return false;
}
return true;
}
void* user_info_codec::get_buffer()
{
return new user_info( "" );
}
void user_info_codec::release_buffer( void* buf )
{
assert( buf != NULL );
delete (user_info*)buf;
}
std::string user_info_codec::encode( void* data )
{
assert( data != NULL );
user* usr = (user*)data;
std::ostringstream ss;
ss << "token:" << usr->get_token();
return ss.str();
}
bool cashback_generate_request_codec::fill_buffer( void* buf, const std::string& key, const std::string& val )
{
cashback_request* gen = (cashback_request*)buf;
if ( key == "user_name" )
{
gen->base.name = val;
}
else if ( key == "type" )
{
gen->base.type = (user_type)atoi(val.c_str());
}
else if ( key == "token" )
{
gen->base.token = atoi(val.c_str());
}
else if ( key == "clerk" )
{
gen->clerk = val;
}
else if ( key == "cash" )
{
gen->cash = (float)atof(val.c_str());
}
else if ( key == "merchant" )
{
gen->merchant_name = val;
}
else if ( key == "tradetype" )
{
gen->ttype = (trade_type)atoi(val.c_str());
}
else if ( key == "shared_list" )
{
decode_shared_list( val, gen->shares );
}
else
{
return false;
}
return true;
}
void cashback_generate_request_codec::decode_shared_list( const std::string& msg, std::map<std::string, shared_info>& shares )
{
std::stringstream ss( msg );
std::string temp;
while ( getline( ss, temp, SEPARATOR_2.at(0) ) )
{
if ( temp.empty() )
continue;
shared_info info;
std::string name;
std::istringstream iss(temp);
iss >> name >> info.merchant >> info.amount >> info.expiration;
info.group = "";
shares.insert( make_pair( name, info ) );
}
}
void* cashback_generate_request_codec::get_buffer()
{
return new cashback_request();
}
void cashback_generate_request_codec::release_buffer( void* buf )
{
assert( buf != NULL );
delete (cashback_request*)buf;
}
std::string cashback_generate_request_codec::encode( void* data )
{
assert( data != NULL );
cashback_generate_ack* ack = (cashback_generate_ack*)data;
std::ostringstream ss;
ss << "name:" << ack->name << "\ntype:" << (int)ack->type << "\nbtoken:" << ack->btoken << "\ncashback:" << ack->cashback;
return ss.str();
}
bool cashback_confirm_request_codec::fill_buffer( void* buf, const std::string& key, const std::string& val )
{
cashback_confirm_request* confirm = (cashback_confirm_request*)buf;
if ( key == "user_name" )
{
confirm->base.name = val;
}
else if ( key == "type" )
{
confirm->base.type = (user_type)atoi(val.c_str());
}
else if ( key == "token" )
{
confirm->base.token = atoi(val.c_str());
}
else if ( key == "clerk" )
{
confirm->clerk = val;
}
else if ( key == "cash" )
{
confirm->cash = (float)atof(val.c_str());
}
else if ( key == "cashback" )
{
confirm->cashback = (float)atof(val.c_str());
}
else if ( key == "btoken" )
{
confirm->btoken = atoi(val.c_str());
}
else if ( key == "merchant" )
{
confirm->merchant_name = val;
}
else if ( key== "customer" )
{
confirm->customer_name = val;
}
else if ( key== "tradetype" )
{
confirm->ttype = (trade_type)atoi(val.c_str());
}
else
{
return false;
}
return true;
}
void* cashback_confirm_request_codec::get_buffer()
{
return new cashback_confirm_request();
}
void cashback_confirm_request_codec::release_buffer( void* buf )
{
assert( buf != NULL );
delete (cashback_confirm_request*)buf;
}
std::string cashback_confirm_request_codec::encode( void* data )
{
assert( data != NULL );
std::ostringstream ss;
ss << "balance:" << *(float*)data;
return ss.str();
}
bool get_requesting_trade_codec::fill_buffer( void* buf, const std::string& key, const std::string& val )
{
get_reqeusting_trade_request* requesting = (get_reqeusting_trade_request*)buf;
if ( key == "user_name" )
{
requesting->base.name = val;
}
else if ( key == "type" )
{
requesting->base.type = (user_type)atoi(val.c_str());
}
else if ( key == "token" )
{
requesting->base.token = atoi(val.c_str());
}
else if ( key == "clerk" )
{
requesting->clerk = val;
}
else
{
return false;
}
return true;
}
void* get_requesting_trade_codec::get_buffer()
{
return new get_reqeusting_trade_request();
}
void get_requesting_trade_codec::release_buffer( void* buf )
{
assert( buf != NULL );
delete (get_reqeusting_trade_request*)buf;
}
std::string get_requesting_trade_codec::encode( void* data )
{
assert( data != NULL );
trade* ack = (trade*)data;
std::ostringstream ss;
ss << "cash:" << ack->cash << "\ncashback:" << ack->cashback << "\ncustomer:" << ack->name << "\ntradetype:" << ack->ttype;
return ss.str();
}
//base; operation; friend_name; nickname; group;
//base; operation; friend_name;
//base; operation;
// add del get
std::string friend_manager_codec::encode( void* data )
{
if ( data == NULL )
return "";
std::list<friend_info>* friends = (std::list<friend_info>*)data;
std::ostringstream ss;
ss << "friends_list:";
for ( std::list<friend_info>::iterator it = friends->begin();
it != friends->end(); it++ )
{
ss << it->name << SEPARATOR_SPACE << it->group << SEPARATOR_SPACE << it->nickname << ";";
}
return ss.str();
}
bool friend_manager_codec::fill_buffer( void* buf, const std::string& key, const std::string& val )
{
friend_manager_request* requesting = (friend_manager_request*)buf;
if ( key == "user_name" )
{
requesting->base.name = val;
}
else if ( key == "type" )
{
requesting->base.type = (user_type)atoi(val.c_str());
}
else if ( key == "token" )
{
requesting->base.token = atoi(val.c_str());
}
else if ( key == OPERATION )
{
requesting->otype = (operation_type)atoi(val.c_str());
}
else if ( key == "friend_name" )
{
requesting->friends.name = val;
}
else if ( key == "group" )
{
requesting->friends.group = val;
}
else if ( key == "nickname" )
{
requesting->friends.nickname = val;
}
else
{
return false;
}
return true;
}
void* friend_manager_codec::get_buffer()
{
return new friend_manager_request();
}
void friend_manager_codec::release_buffer( void* buf )
{
assert( buf != NULL );
delete (friend_manager_request*)buf;
}
std::string shared_manager_codec::encode( void* data )
{
if ( data == NULL )
return "";
std::ostringstream ss;
ss << "shared_list:";
std::map< std::string,std::list<shared_info> >* shares_map = (std::map< std::string,std::list<shared_info> >*)data;
for ( std::map< std::string,std::list<shared_info> >::iterator it_map=shares_map->begin();
it_map != shares_map->end(); it_map ++ )
{
std::list<shared_info>& shareds = it_map->second;
for ( std::list<shared_info>::iterator it = shareds.begin();
it != shareds.end(); it++ )
{
ss << it_map->first << SEPARATOR_SPACE << it->merchant << SEPARATOR_SPACE << it->amount << SEPARATOR_SPACE << it->expiration << ";";
}
}
return ss.str();
}
//base; merchant; type-self or shared
//base; merchant; group; cash; expiration;
//base; merchant; group;
//base; merchant; group; cash; expiration; friend_name;
bool shared_manager_codec::fill_buffer( void* buf, const std::string& key, const std::string& val )
{
shared_manager_request* requesting = (shared_manager_request*)buf;
if ( key == USER_NAME )
{
requesting->base.name = val;
}
else if ( key == "type" )
{
requesting->base.type = (user_type)atoi(val.c_str());
}
else if ( key == "token" )
{
requesting->base.token = atoi(val.c_str());
}
else if ( key == OPERATION )
{
requesting->otype = (operation_type)atoi(val.c_str());
}
else if ( key == "get" )
{
requesting->get_from = val;
}
else if ( key == "merchant" )
{
requesting->shared.merchant = val;
}
else if ( key == "group" )
{
requesting->shared.group = val;
}
else if ( key == "cash" )
{
requesting->shared.amount = (float)atof(val.c_str());
}
else if ( key == "expiration" )
{
requesting->shared.expiration = atof(val.c_str());
}
else
{
return false;
}
return true;
}
void* shared_manager_codec::get_buffer()
{
return new shared_manager_request();
}
void shared_manager_codec::release_buffer( void* buf )
{
assert( buf != NULL );
delete (shared_manager_request*)buf;
}
| true |
e76f68b9dea36d971a75a9f654f3b2bcd106afde | C++ | yourblacksky/spengine | /SPENGINE/SPStringMap.h | UTF-8 | 6,498 | 3.359375 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////
/// @file SPStringMap.h the header file of template SPStringMap class.
/// @author Ken.J
/// @version Alpha 0.7
/// @date 2012-7-10
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "SPString.h"
#include <map>
#include "SPLogHelper.h"
#include "SPIterator.h"
using namespace std;
namespace SPEngine
{
/// @brief A SPString comparing struct.
struct IsLessWString
{
bool operator () (const wstring& left, const wstring& right) const
{
//return wcscmp(left.c_str(), right.c_str()) < 0;
return wcscmp(left.c_str(), right.c_str()) < 0;
}
};
/// @brief A SPString comparing struct.
struct IsLessString
{
bool operator () (const string& left, const string& right) const
{
//return wcscmp(left.c_str(), right.c_str()) < 0;
return strcmp(left.c_str(), right.c_str()) < 0;
}
};
///////////////////////////////////////////////////////////////////////
/// @brief SPStringMap to produce a map indexed by SPString.
///
///////////////////////////////////////////////////////////////////////
template <typename T>
class SPWStringMap
{
map<wstring, T, IsLessWString> stringMap; ///< Inner map.
typedef typename map<wstring, T, IsLessWString>::iterator Iter; ///< Map iterator.
public:
/// @name Operation
/// @{
void Clear()
{
stringMap.clear();
}
pair<wstring, T>& Get(int num)
{
assert(abs(num) < GetCount());
if (num >= 0)
{
int pos = 0;
Iter iter = stringMap.begin();
while(pos < num)
{
iter++;
}
}
else
{
int pos = 0;
Iter iter = stringMap.rbegin();
while(pos > num)
{
iter++;
}
}
}
T& Get(wstring index)
{
if (IsSet(index))
{
return stringMap[index];
}
SPLogHelper::WriteLog("[Game] WARNING: Trying to get an nonexistent object from map!");
Add(index);
return stringMap[index];
}
T& operator [] (wstring index)
{
return Get(index);
}
void Add(wstring index)
{
stringMap[index] = T();
}
void Set(wstring index, T object)
{
stringMap[index] = object;
}
void Remove(wstring index)
{
map<wstring, T, IsLessWString>::iterator iter = stringMap.find(index);
if (iter != stringMap.end())
{
stringMap.erase(iter);
}
else
{
SPLogHelper::WriteLog("[Game] WARNING: Removing an nonexistent index from map!");
}
}
int GetCount()
{
return stringMap.size();
}
bool IsSet(wstring index)
{
if (stringMap.find(index) == stringMap.end())
{
return false;
}
return true;
}
const map<wstring, T, IsLessWString>* GetMap() const
{
return &stringMap;
}
/// @}
public:
SPWStringMap(void) { Clear(); }
~SPWStringMap(void) {}
};
///////////////////////////////////////////////////////////////////////
/// @brief SPStringMapIterator to go through a SPString map.
///
/// usage:
/// SPStringMapIterator<Type> iter(stringMapPtr);
/// for (iter.First(); !iter.IsDone(); iter.Next())
/// {
/// ...
/// }
///////////////////////////////////////////////////////////////////////
template<typename T>
class SPWStringMapIterator : public SPIterator<T>
{
public:
SPWStringMapIterator(const SPWStringMap<T>* setMap)
{
theMap = setMap;
First();
}
virtual void First()
{
current = theMap->GetMap()->begin();
}
virtual void Next()
{
current++;
}
virtual bool IsDone() const
{
return current == theMap->GetMap()->end();
}
virtual T CurrentItem() const
{
assert(!IsDone());
return current->second;
}
wstring CurrentIndex() const
{
return current->first;
}
private:
const SPWStringMap<T>* theMap;
typename map<wstring, T, IsLessWString>::const_iterator current;
};
template <typename T>
class SPStringMap
{
map<string, T, IsLessString> stringMap; ///< Inner map.
typedef typename map<string, T, IsLessString>::iterator Iter; ///< Map iterator.
public:
/// @name Operation
/// @{
void Clear()
{
stringMap.clear();
}
pair<string, T>& Get(int num)
{
assert(abs(num) < GetCount());
if (num >= 0)
{
int pos = 0;
Iter iter = stringMap.begin();
while(pos < num)
{
iter++;
}
}
else
{
int pos = 0;
Iter iter = stringMap.rbegin();
while(pos > num)
{
iter++;
}
}
}
T& Get(string index)
{
if (IsSet(index))
{
return stringMap[index];
}
SPLogHelper::WriteLog("[Game] WARNING: Trying to get an nonexistent object from map!");
Add(index);
return stringMap[index];
}
T& operator [] (string index)
{
return Get(index);
}
void Add(string index)
{
stringMap[index] = T();
}
void Set(string index, T object)
{
stringMap[index] = object;
}
void Remove(string index)
{
map<string, T, IsLessString>::iterator iter = stringMap.find(index);
if (iter != stringMap.end())
{
stringMap.erase(iter);
}
else
{
SPLogHelper::WriteLog("[Game] WARNING: Removing an nonexistent index from map!");
}
}
int GetCount()
{
return stringMap.size();
}
bool IsSet(string index)
{
if (stringMap.find(index) == stringMap.end())
{
return false;
}
return true;
}
const map<string, T, IsLessString>* GetMap() const
{
return &stringMap;
}
/// @}
public:
SPStringMap(void) {Clear();}
~SPStringMap(void) {}
};
///////////////////////////////////////////////////////////////////////
/// @brief SPStringMapIterator to go through a SPString map.
///
/// usage:
/// SPStringMapIterator<Type> iter(stringMapPtr);
/// for (iter.First(); !iter.IsDone(); iter.Next())
/// {
/// ...
/// }
///////////////////////////////////////////////////////////////////////
template<typename T>
class SPStringMapIterator : public SPIterator<T>
{
public:
SPStringMapIterator(const SPStringMap<T>* setMap)
{
theMap = setMap;
First();
}
virtual void First()
{
current = theMap->GetMap()->begin();
}
virtual void Next()
{
current++;
}
virtual bool IsDone() const
{
return current == theMap->GetMap()->end();
}
virtual T CurrentItem() const
{
assert(!IsDone());
return current->second;
}
string CurrentIndex() const
{
return current->first;
}
private:
const SPStringMap<T>* theMap;
typename map<string, T, IsLessString>::const_iterator current;
};
}
| true |
2568a6c27b173ea4823a05347155ec10e0668828 | C++ | fanzhijun301/leetcode | /InterleavingString.cpp | UTF-8 | 2,673 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <set>
using namespace std;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int len1 = s1.size(), len2 = s2.size(), len3 = s3.size();
if (len1 == 0) {if (s2 == s3) return true; else return false;}
if (len2 == 0) {if (s1 == s3) return true; else return false;}
if (len3 == 0) {if (len1==0 && len2==0) return true; else return false;}
vector<vector<pair<int,int>>> pos_vec;
pos_vec.resize(len3);
int pos1 = -1, po2 = -1;
for (int i = 0; i < len3; i++) {
char c3 = s3.at(i);
set<pair<int,int>> pos_set;
if (i == 0) {
if (s1.at(0) == c3) pos_set.insert(pair<int,int>(0,-1));
if (s2.at(0) == c3) pos_set.insert(pair<int,int>(-1,0));
} else {
vector<pair<int,int>> &last_vec = pos_vec.at(i-1);
vector<pair<int,int>>::iterator it_vec;
for (it_vec = last_vec.begin(); it_vec != last_vec.end(); it_vec++) {
pair<int,int> in_pair = *it_vec;
if (in_pair.first + 1 < len1 && s1.at(in_pair.first+1) == c3)
pos_set.insert(pair<int,int>(in_pair.first + 1, in_pair.second));
if (in_pair.second + 1 < len2 && s2.at(in_pair.second+1) == c3)
pos_set.insert(pair<int,int>(in_pair.first, in_pair.second + 1));
}
}
if (pos_set.size() == 0) return false;
vector<pair<int,int>> in_vec;
set<pair<int,int>>::iterator it_set;
for (it_set = pos_set.begin(); it_set != pos_set.end(); it_set++) {
pair<int,int> in_pair = *it_set;
in_vec.push_back(pair<int,int>(in_pair.first,in_pair.second));
}
pos_vec[i] = in_vec;
}
vector<pair<int,int>> &last_vec = pos_vec.at(len3-1);
vector<pair<int,int>>::iterator it_vec;
for (it_vec = last_vec.begin(); it_vec != last_vec.end(); it_vec++) {
pair<int,int> in_pair = *it_vec;
if (in_pair.first == len1-1 && in_pair.second == len2-1) return true;
}
return false;
}
};
void isInterleave_test_case1() {
string s1 = "aabcc";
string s2 = "dbbca";
string s3 = "aadbbcbcac";
string s32 = "aadbbbaccc";
Solution solution;
bool is_inter = solution.isInterleave(s1,s2,s3);
cout << is_inter << endl;
}
void isInterleave_test_case2() {
string s1 = "aa";
string s2 = "ab";
string s3 = "aaba";
Solution solution;
bool is_inter = solution.isInterleave(s1,s2,s3);
cout << is_inter << endl;
}
void isInterleave_test_case3() {
string s1 = "a";
string s2 = "b";
string s3 = "a";
Solution solution;
bool is_inter = solution.isInterleave(s1,s2,s3);
cout << is_inter << endl;
}
int main_interleavingString(int argc, char **argv) {
isInterleave_test_case1();
isInterleave_test_case2();
isInterleave_test_case3();
return 0;
} | true |
aaddfb7173fe8f947be530669cf986d48cfcc6ee | C++ | tthheusalmeida/URI_Online_Judge | /C++/2630.cpp | UTF-8 | 936 | 2.953125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;;
int main() {
int iterator;
int r, g, b;
cin >> iterator;
string name;
for (int i = 0; i < iterator; i++) {
cin >> name >> r >> g >> b;
cout << "Caso #" << i+1 << ": ";
if (name == "eye")
cout << (30*r + 59*g + 11*b)/100 << endl;
else if (name == "mean")
cout << fixed << setprecision(0) << (r + g + b)/3 << endl;
else if (name == "max"){
if( r >= g && r >= b)
cout << r << endl;
else if( g >= r && g >= b)
cout << g << endl;
else
cout << b << endl;
}
else if (name == "min"){
if( r <= g && r <= b)
cout << r << endl;
else if( g <= r && g <= b)
cout << g << endl;
else
cout << b << endl;
}
}
return 0;
}
| true |
9a9625c2263cd29fdbd4f5cb551e34733939dd0d | C++ | ashoknar/SP_LAB | /9-firstAndFollow/firstAndFollowMinimum.cpp | UTF-8 | 3,929 | 3 | 3 | [] | no_license | #include "iostream"
#include "string"
#include "fstream"
#include "sstream"
#include "ctype.h"
#include "map"
#include "set"
#include "list"
#define epsilon "epsilon"
#define terminator "$"
using namespace std;
class FnF
{
public:
set<string> first;
set<string> follow;
FnF(){}
FnF(string s, bool toFollow=0){toFollow?follow.insert(s):first.insert(s);}
void print()
{
cout<<"First : ";
for(set<string>::iterator iter=first.begin(); iter!=first.end();iter++)
cout<<(*iter)<<", ";
cout<<endl<<"Follow : ";
for(set<string>::iterator iter=follow.begin(); iter!=follow.end();iter++)
cout<<(*iter)<<", ";
cout<<endl;
}
};
map<string,FnF> elements;
map<string,list<list<string> > > productions;
bool isTerminal(string element){return !isupper(element[0]);}
pair<string,list<list<string> > > split(string line)
{
pair<string,list<list<string> > > temp;
string element,productionString;
stringstream s(line);
s>>temp.first;
s>>productionString;
while(getline(s,productionString,'|'))
{
list<string> production;
stringstream t(productionString);
while(getline(t,element,' '))
{
if(element!="")
production.push_back(element);
}
temp.second.push_back(production);
}
return temp;
}
int insertFirstOfNext(string variable,list<string>::iterator next,list<string>::iterator end)
{
int repeat=0;
if(next!=end)
for(set<string>::iterator setItor=elements[*next].first.begin();setItor!=elements[*next].first.end(); setItor++)
if(elements[variable].first.insert(*setItor).second)
repeat=1;
if(elements[*next].first.find(epsilon)!=elements[*next].first.end())
if(insertFirstOfNext(variable,++next,end))
repeat=1;
return repeat;
}
int insertFollowFromNext(string superVariable,list<string>::iterator next,list<string>::iterator end)
{
bool repeat = 0;
string variable=*next;
next++;
if(next!=end)
if(isTerminal(*next) && elements[variable].follow.insert(*next).second)
repeat=1;
else
{
for(set<string>::iterator iter=elements[*next].first.begin();iter!=elements[*next].first.end();iter++)
if(*iter!=epsilon && elements[variable].follow.insert(*iter).second)
repeat = 1;
if(elements[*next].first.find(epsilon)!=elements[*next].first.end())
for(set<string>::iterator iter=elements[*next].follow.begin();iter!=elements[*next].follow.end();iter++)
if(elements[variable].follow.insert(*iter).second)
repeat=1;
}
else
for(set<string>::iterator iter=elements[superVariable].follow.begin();iter!=elements[superVariable].follow.end();iter++)
if(elements[variable].follow.insert(*iter).second)
repeat=1;
return repeat;
}
void addFirstAndFollow()
{
bool repeat=0,flag=1;
for(map<string, list<list<string> > >::iterator iter = productions.begin(); iter!=productions.end(); iter++)
for(list<list<string> >::iterator liter = (iter->second).begin(); liter!=(iter->second).end(); liter++)
{
flag=1;
for(list<string>::iterator siter = (*liter).begin(); siter!=(*liter).end(); siter++)
{
if(flag)
{
if(isTerminal(*siter))
{
if(elements.find(*siter)==elements.end())
elements[*siter]=FnF(*siter);
if(elements[iter->first].first.insert(*siter).second)
repeat=1;
}
else
repeat=insertFirstOfNext(iter->first,siter,(*liter).end());
flag=0;
}
if(insertFollowFromNext(iter->first,siter,(*liter).end()))
repeat=1;
}
}
if(repeat) addFirstAndFollow();
}
int main()
{
ifstream f("input");
string line;
while(getline(f,line,'\n'))
{
productions[split(line).first]=split(line).second;
elements[split(line).first]=elements.size()?FnF():FnF(terminator,1);
}
addFirstAndFollow();
for(map<string,FnF>::iterator iter=elements.begin();iter!=elements.end();iter++)
{
if(!isTerminal(iter->first))
{
cout<<iter->first<<endl<<string(iter->first.length(),'-')<<endl;
iter->second.print();
cout<<endl;
}
}
f.close();
return 0;
} | true |
3c4026fd44e7f78475807bd2937edbc67cbac303 | C++ | rajattarade/Arduino_codes | /FPS/FPS.ino | UTF-8 | 899 | 2.71875 | 3 | [] | no_license | #include <SoftwareSerial.h>
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
// need a serial port to communicate with the GT-511C3
SoftwareSerial btSerial(8, 7); // Arduino RX (GT TX), Arduino TX (GT RX)
// the Arduino TX pin needs a voltage divider, see wiring diagram at:
// http://startingelectronics.com/articles/GT-511C3-fingerprint-scanner-hardware/
void setup() {
Serial.begin(9600); // serial connection to processing app.
lcd.begin(16, 2);
btSerial.begin(9600); // for communicating with the GT-511C3
}
byte rx_byte = 0; // stores received byte
void loop() {
// check for a byte from the GT-511C3
if (btSerial.available()) {
// get a byte from the FPS and send it to the processing app.
rx_byte = btSerial.read();
lcd.write(rx_byte);
}
}
| true |
223b006942b02d52b34de86cdaf96f35db87ce23 | C++ | zhxhxlzt/opengl_trunk | /learnopengl/learnopengl/Timer.h | UTF-8 | 977 | 3.03125 | 3 | [] | no_license | #pragma once
#include "Object.h"
namespace yk
{
using namespace std::chrono;
class Timer : Object
{
TYPE(yk::Timer, Object);
private:
time_point<system_clock> m_prevPoint;
function<void(Timer &timer)> m_callfunc;
public:
Timer() = default;
Timer(function<void(Timer &timer)> func, unsigned int milliseconds) :
m_prevPoint(system_clock::now()),
m_callfunc(func),
m_milliseconds(milliseconds)
{
}
unsigned int m_milliseconds; // 允许调用者自行修改下次调用的时间间隔
bool m_oneshot = false; // 只调用一次,然后disable
bool enabled = true;
bool dead = false; // 如果为true,则此定时器会被移除
private:
friend class Application;
void Update()
{
auto diff = system_clock::now() - m_prevPoint;
if (m_milliseconds <= duration_cast<milliseconds>(diff).count())
{
if (m_oneshot) enabled = false;
m_callfunc(*this);
m_prevPoint = system_clock::now();
}
}
};
} | true |
3344a96f5d0af955eeb2d502d61af6f5c340542f | C++ | VGKanri/EGP410_Final | /GameAI/pathfinding/Pathfinding/steering/CohesionSteering.cpp | UTF-8 | 891 | 2.65625 | 3 | [] | no_license | #include "CohesionSteering.h"
#include "KinematicUnit.h"
#include "UnitManager.h"
CohesionSteering::CohesionSteering(KinematicUnit* pMover, std::map<std::string, KinematicUnit*>* unitList, float cohesionRadius)
{
mpMover = pMover;
mpUnitList = unitList;
mCohesionRadius = cohesionRadius;
}
Steering* CohesionSteering::getSteering()
{
int neighborCount = 0;
mLinear = Vector2D(0, 0);
for (auto it : *mpUnitList)
{
if (it.first != "player" && it.second != mpMover)
{
if ((mpMover->getPosition() - it.second->getPosition()).getLength() < mCohesionRadius &&
(mpMover->getPosition() - it.second->getPosition()).getLength() > -mCohesionRadius)
{
mLinear += it.second->getPosition();
++neighborCount;
}
}
}
if (neighborCount == 0)
return this;
mLinear /= neighborCount;
mLinear = mLinear - mpMover->getPosition();
mLinear.normalize();
return this;
} | true |
7a59dee2854c8ca1522b9d4ef7c6ff9c64821d6b | C++ | AgelkazzWrenchsprocket/PJATK_CPP_PJC | /lab2/zad6/main.cpp | UTF-8 | 613 | 3.65625 | 4 | [] | no_license | /*
* Utwórz 5 elementowa statyczna tablice zmiennych typu int i wypełnij ją dowolnymi wartościami.
* Następnie utwórz wskaźnik pokazujący ostatni element tej tablicy.
* Dysponując wskaźnikami pokazującymi elementy pierwszy i ostatni, napisz pętlę wykorzystującą te wskaźniki sumującą wszystkie elementy tej tablicy.
*/
#include <iostream>
int main() {
int tab[5] = {1, 3, 5, 7, 11},
len = sizeof(tab) / sizeof(int),
*pfirst = &tab[0],
*plast = &tab[len-1],
sum = 0;
while (pfirst <= plast) {
sum += *pfirst;
pfirst++;
}
std::cout << sum;
}
| true |
1e807126c937e960503768e45ba4934c25d17834 | C++ | zenmaee/temp | /Q4/Q4.cpp | UTF-8 | 824 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include "Q4.h"
#include <string>
using namespace std;
//Part A
Complex::Complex() {
a = 0;
b = 0;
}
Complex::Complex(int a, int b) {
this->a = a;
this->b = b;
}
int Complex::getA() {
return this->a;
}
void Complex::setA(int a) {
this->a = a;
}
int Complex::getB() {
return this->b;
}
void Complex::setB(int b) {
this->b = b;
}
//Part B
string Complex::toString() const {
string astring = to_string(this->a);
string bstring = to_string(this->b);
return astring + "+" + bstring + "i";
}
//Part C
Complex Complex::operator +(const Complex &c2) {
int newa = this->a + c2.a;
int newb = this->b + c2.b;
return Complex(newa, newb);
}
bool operator ==(const Complex &c1, const Complex &c2) {
return (c1.a == c2.a && c1.b == c2.b);
}
| true |
e12ef787f57cb3be23459481ace2c7c2e5fb0541 | C++ | pouloghost/weexuikit | /RenderCore/render/gesture/foundation/Listenable.h | UTF-8 | 1,033 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by furture on 2018/10/23.
//
#ifndef WEEX_UIKIT_GESTURE_LISTENABLE_H
#define WEEX_UIKIT_GESTURE_LISTENABLE_H
#include <functional>
namespace weexuikit {
class ListenVoidCallback {
public:
virtual void onListenEvent() {
}
};
class Listenable {
public:
/// Register a closure to be called when the object notifies its listeners.
virtual void addListener(ListenVoidCallback *listener) {};
/// Remove a previously registered closure from the list of closures that the
/// object notifies.
virtual void removeListener(ListenVoidCallback *listener) {};
};
// An interface for subclasses of [Listenable] that expose a [value].
///
/// This interface is implemented by [ValueNotifier<T>] and [Animation<T>], and
/// allows other APIs to accept either of those implementations interchangeably.
template<typename T>
class ValueListenable {
public:
virtual T value()=0;
};
}
#endif //WEEX_UIKIT_GESTURE_LISTENABLE_H
| true |
01db7f495c969da4e2f638efec817964ce67c123 | C++ | futureshocked/ArduinoSbSGettingStarted | /_0560_-_Digital_sound_sensor/_0560_-_Digital_sound_sensor.ino | UTF-8 | 2,132 | 3.140625 | 3 | [
"MIT"
] | permissive | /* Digital sound sensor demo sketch
*
* This sketch detects loud noises using a digital sound sensor.
*
* When the sensor detects a loud noise, it sends a message to the
* serial monitor.
*
* This sketch was written for Arduino Step by Step by Peter Dalmaris.
*
* Components
* ----------
* - Arduino Uno
* - Digital sound sensor
*
* Libraries
* ---------
* - None
*
* Connections
* -----------
* Break out | Arduino Uno
* -----------------------------
* + | 5V
* G | GND
* D0 | A0
*
* Other information
* -----------------
* This code is useful if you want to do things like detect a knock on a door,
* hands clapping, etc.
*
* Created on October 14 2016 by Peter Dalmaris
*
*/
int soundDetectedPin = 10; // Use Pin 10 as our Input
int soundDetectedVal = HIGH; // This is where we record our Sound Measurement
boolean bAlarm = false;
unsigned long lastSoundDetectTime; // Record the time that we measured a sound
int soundAlarmTime = 500; // Number of milli seconds to keep the sound alarm high
int ledpin = 7;
void setup ()
{
Serial.begin(9600);
pinMode (soundDetectedPin, INPUT) ; // input from the Sound Detection Module
pinMode (ledpin, OUTPUT); // The built-in LED on pin 13 will light
// up when there is a noise.
}
void loop ()
{
soundDetectedVal = digitalRead (soundDetectedPin) ; // read the sound alarm time
if (soundDetectedVal == HIGH) // If we hear a sound
{
digitalWrite(ledpin,HIGH); // Turn the LED on to show there was a loud noise
lastSoundDetectTime = millis(); // record the time of the sound alarm
// This will output the LOUD message only once even if the signal remains
// at HIGH. This way it will not scroll out of the window with the same message.
if (!bAlarm){
Serial.println("LOUD!");
bAlarm = true;
}
}
if( (millis()-lastSoundDetectTime) > soundAlarmTime && bAlarm){
Serial.println("quiet");
digitalWrite(ledpin,LOW);
bAlarm = false;
}
}
| true |
f86d8786d557db4c4a317bc9feebab8ece7cd0ea | C++ | Interstell/courses | /courses/prog_base_2/labs/lab2/Lab2DLL1/main.cpp | UTF-8 | 1,108 | 2.765625 | 3 | [] | no_license | #include "main.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check(stack_t self, char* str) {
int num;
int numOfScanned = sscanf(str, "pop %i", &num);
char numAsStr[20];
itoa(num, numAsStr, 10);
if (numOfScanned == 1 && num > 0 && strlen("pop ") + strlen(numAsStr) == strlen(str)) return 1;
return 0;
}
void reaction(stack_t self, char* str){
int numToDelete;
sscanf(str, "pop %i", &numToDelete);
for (int i = 0; i<numToDelete; i++){
printf("Popped: %s\n", stack_pop(self));
}
}
extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// attach to process
// return FALSE to fail DLL load
break;
case DLL_PROCESS_DETACH:
// detach from process
break;
case DLL_THREAD_ATTACH:
// attach to thread
break;
case DLL_THREAD_DETACH:
// detach from thread
break;
}
return TRUE; // succesful
}
| true |
3145745a13eae318cce153ab924fcc7fff6bcc27 | C++ | karangovil/ray_tracer | /tests/shapes/testObject.cpp | UTF-8 | 2,179 | 2.625 | 3 | [
"MIT"
] | permissive | #include "catch.hpp"
#include <math.h>
#include "testObject.h"
#include "graphics/intersection.h"
#include "math/transformations.h"
using namespace Catch::literals;
using namespace RT;
TEST_CASE("testObject should work")
{
SECTION("default testObject should work")
{
test_object o {};
REQUIRE(o.transform() == matrix4x4 {});
o.set_transform(translation(2, 3, 4));
REQUIRE(o.transform() == translation(2, 3, 4));
REQUIRE(o.mat() == material {});
material m;
m.set_ambient(1);
o.set_material(m);
REQUIRE(o.mat() == m);
}
SECTION("intersecting a ray with a scaled test object should work")
{
test_object o {};
o.set_transform(scaling(2, 2, 2));
ray r {point(0, 0, -5), vector(0, 0, 1)};
o.intersect(r);
REQUIRE(o.saved_ray().origin() == point(0, 0, -2.5));
REQUIRE(o.saved_ray().direction() == vector(0, 0, 0.5));
}
SECTION("intersecting a ray with a translated test object should work")
{
test_object o {};
o.set_transform(translation(5, 0, 0));
ray r {point(0, 0, -5), vector(0, 0, 1)};
o.intersect(r);
REQUIRE(o.saved_ray().origin() == point(-5, 0, -5));
REQUIRE(o.saved_ray().direction() == vector(0, 0, 1));
}
SECTION("normal on a translated test object should work")
{
test_object o {};
o.set_transform(translation(0, 1, 0));
auto n = o.normal_at(point(0, 1.70711, -0.70711));
REQUIRE(n.x == 0_a);
REQUIRE(n.y == 0.70711_a);
REQUIRE(n.z == -0.70711_a);
}
SECTION("normal on a transformed test object should work")
{
test_object o {};
o.set_transform(scaling(1, 0.5, 1) * rotation_z(M_PI / 5));
auto n = o.normal_at(point(0, sqrt(2) / 2, -sqrt(2) / 2));
REQUIRE(n.x == 0_a);
REQUIRE(n.y == 0.97014_a);
REQUIRE(n.z == Approx(-0.24254).margin(1e-5));
}
SECTION("get_object_sp should work")
{
std::shared_ptr<object> o = std::make_shared<test_object>();
REQUIRE_FALSE(o->get_object_sp() == nullptr);
}
}
| true |
bd111f738a779103a143cd534be532065e4f9c27 | C++ | CleverFroge/EndlessWar | /FrogEngine/Src/Camera.cpp | UTF-8 | 912 | 2.578125 | 3 | [] | no_license | #include "FrogEngine.h"
using namespace FrogEngine;
Camera::Camera()
{
AspectRatio = 800.0 / 600.0;
}
Camera::~Camera()
{
if (_skyBox)
{
delete _skyBox;
}
}
//
//void Camera::ProcessMouseScroll(float scroll)
//{
// if (_zoom >= 1.0f && _zoom <= 45.0f)
// _zoom -= scroll;
// if (_zoom <= 1.0f)
// _zoom = 1.0f;
// if (_zoom >= 45.0f)
// _zoom = 45.0f;
//}
Matrix4 Camera::GetProjectionMatrix() const
{
Matrix4 projection;
projection.Perspective(45, AspectRatio, 0.1f, 1000.0f);
return projection;
}
Matrix4 Camera::GetLookAtMatrix() const
{
Matrix4 view;
/*
GetPosition().Print();
GetForward().Print();
GetUp().Print();
std::cout << std::endl;
*/
view.LookAt(GetPosition(), GetPosition() + GetForward(), GetUp());
return view;
}
void Camera::SetSkyBox(SkyBox* skyBox)
{
if (_skyBox)
{
delete _skyBox;
}
_skyBox = skyBox;
}
SkyBox* Camera::GetSkyBox() const
{
return _skyBox;
} | true |
567c33705453b7ca264f253f154572eb188be16d | C++ | dvno-v/su | /First Year/Second Half/Object Oriented Programming/Practicum/Week-8/Task1/Menu.h | UTF-8 | 353 | 2.75 | 3 | [] | no_license | #ifndef MENU_H
#define MENU_H
#include <vector>
#include "Food.h"
class Menu
{
private:
std::vector<Food*> foods;
Food* get_food_by_id(int) const;
public:
Menu();
Menu(std::vector<Food*>);
~Menu();
void add_food(Food&);
void consume_food(int, int);
Food* get_cheapest() const;
};
#endif
| true |
d1ceead8b5406025cdfba6fcc3d5ead08caa2d76 | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/14_18972_55.cpp | UTF-8 | 833 | 2.5625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
int main()
{
int T,i,j,k,A[4][4],B[4],C[4],x,y,count,ele;
FILE *f=fopen("A-small-attempt1.txt","r");
FILE *fp=fopen("output.txt","w");
fscanf(f,"%d",&T);
for(i=0;i<T;i++)
{
count=0;
fscanf(f,"%d",&x);
for(j=0;j<4;j++)
for(k=0;k<4;k++)
fscanf(f,"%d",&A[j][k]);
for(j=0;j<4;j++)
B[j]=A[x-1][j];
fscanf(f,"%d",&y);
for(j=0;j<4;j++)
for(k=0;k<4;k++)
fscanf(f,"%d",&A[j][k]);
for(j=0;j<4;j++)
C[j]=A[y-1][j];
for(j=0;j<4;j++)
{
for(k=0;k<4;k++)
{
if(B[j]==C[k])
{
ele=B[j];
count++;
}
}
}
if(count==1)
fprintf(fp,"Case #%d: %d\n",i+1,ele);
else if(count==0)
fprintf(fp,"Case #%d: Volunteer cheated!\n",i+1);
else
fprintf(fp,"Case #%d: Bad magician!\n",i+1);
}
return 0;
}
| true |
c1a8abe20d96fee8c3efb223ddbbf0c231799f8a | C++ | joao-frohlich/AlmanaqueBrute | /Matemática/Primos/miller_rabin.cpp | UTF-8 | 860 | 2.84375 | 3 | [] | no_license | long long power(long long base, long long e, long long mod) {
long long result = 1;
base %= mod;
while (e) {
if (e & 1) result = (__int128)result * base % mod;
base = (__int128)base * base % mod;
e >>= 1;
}
return result;
}
bool is_composite(long long n, long long a, long long d, int s) {
long long x = power(a, d, n);
if (x == 1 || x == n - 1) return false;
for (int r = 1; r < s; r++) {
x = (__int128)x * x % n;
if (x == n - 1) return false;
}
return true;
}
bool miller_rabin(long long n) {
if (n < 2) return false;
int r = 0;
long long d = n - 1;
while ((d & 1) == 0) d >>= 1, ++r;
for (int a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
if (n == a) return true;
if (is_composite(n, a, d, r)) return false;
}
return true;
}
| true |
6d7612987fa475200523d0f295877171b514836b | C++ | tomalbrc/rawket-engine | /src/actions/easing_function.cpp | UTF-8 | 3,748 | 2.921875 | 3 | [
"MIT"
] | permissive | //
// easing_function.cpp
// rawket
//
// Created by Tom Albrecht on 23.05.16.
//
//
#include "easing_function.hpp"
#include <math.h>
RKT_NAMESPACE_BEGIN
/**
* BounceEase- Out, In, InOut
*/
float animationBounceEaseOut(float t,float b , float c, float d) {
if ((t/=d) < (1/2.75f)) {
return c*(7.5625f*t*t) + b;
} else if (t < (2/2.75f)) {
float postFix = t-=(1.5f/2.75f);
return c*(7.5625f*(postFix)*t + .75f) + b;
} else if (t < (2.5/2.75)) {
float postFix = t-=(2.25f/2.75f);
return c*(7.5625f*(postFix)*t + .9375f) + b;
} else {
float postFix = t-=(2.625f/2.75f);
return c*(7.5625f*(postFix)*t + .984375f) + b;
}
}
float animationBounceEaseIn (float t,float b , float c, float d) {
return c - animationBounceEaseOut(d-t, 0, c, d) + b;
}
float animationBounceEaseInOut(float t,float b , float c, float d) {
if (t < d/2) return animationBounceEaseIn (t*2, 0, c, d) * .5f + b;
else return animationBounceEaseOut (t*2-d, 0, c, d) * .5f + c*.5f + b;
}
/**
* Back Out, In, InOut
*/
float animationBackEaseIn (float t,float b , float c, float d) {
float s = 1.70158f;
float postFix = t/=d;
return c*(postFix)*t*((s+1)*t - s) + b;
}
float animationBackEaseOut(float t,float b , float c, float d) {
t=t/d-1;
float s = 1.70158f;
return c*((t)*t*((s+1)*t + s) + 1) + b;
}
float animationBackEaseInOut(float t,float b , float c, float d) {
float s = 1.70158f;
(s*=(1.525f)); // TODO: Check for bugs
if ((t/=d/2) < 1) return c/2*(t*t*((+1)*t - s)) + b;
float postFix = t-=2;
s*=(1.525f);
return c/2*((postFix)*t*(((s)+1)*t + s) + 2) + b;
}
/**
* Linear
*/
float animationLinear(float time, float startValue, float changeInValue, float duration) {
//RKTLog("Linear percentage: "<<time/duration);
return changeInValue*time/duration + startValue;
}
/**
* Quad Ease In, Out, InOut
*/
float animationQuadEaseIn (float t,float b , float c, float d) {
t /= d;
return c*t*t + b;
}
float animationQuadEaseOut(float t,float b , float c, float d) {
t /= d;
return -c *t*(t-2) + b;
}
float animationQuadEaseInOut(float t,float b , float c, float d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
}
/**
* Elastic animation
*/
float animationElasticEaseIn (float t,float b , float c, float d) {
if (t==0) return b; if ((t/=d)==1) return b+c;
float p=d*.3f;
float a=c;
float s=p/4;
t--;
float postFix =a*pow(2,10*t); // this is a fix, again, with post-increment operators
return -(postFix * sin((t*d-s)*(2*M_PI)/p )) + b;
}
float animationElasticEaseOut(float t,float b , float c, float d) {
if (t==0) return b; if ((t/=d)==1) return b+c;
float p=d*.3f;
float a=c;
float s=p/4;
return (a*pow(2,-10*t) * sin( (t*d-s)*(2*M_PI)/p ) + c + b);
}
float animationElasticEaseInOut(float t,float b , float c, float d) {
if (t==0) return b; if ((t/=d/2)==2) return b+c;
float p=d*(.3f*1.5f);
float a=c;
float s=p/4;
if (t < 1) {
float postFix =a*pow(2,10*(t-=1)); // postIncrement is evil
return -.5f*(postFix* sin( (t*d-s)*(2*M_PI)/p )) + b;
}
float postFix = a*pow(2,-10*(t-=1)); // postIncrement is evil
return postFix * sin( (t*d-s)*(2*M_PI)/p )*.5f + c + b;
}
/**
* Sine animation
*/
float animationSineEaseIn (float t,float b , float c, float d) {
return -c * cos(t/d * (M_PI/2)) + c + b;
}
float animationSineEaseOut(float t,float b , float c, float d) {
return c * sin(t/d * (M_PI/2)) + b;
}
float animationSineEaseInOut(float t,float b , float c, float d) {
return -c/2 * (cos(M_PI*t/d) - 1) + b;
}
RKT_NAMESPACE_END
| true |
60636af0a36c36726983aef29763b13c9d160dc1 | C++ | dv66/programming_problems_cpp | /recursion8.cpp | UTF-8 | 485 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int checkPrime(int n, int k)
{
if(n==1) return 0;
if(k==1) return 1;
if(n%k==0) return 0;
return checkPrime(n,k-1);
}
int main()
{
int a[100], i = 0, n;
while(1)
{
scanf("%d", &n);
if(!n) break;
else a[i] = checkPrime(n, sqrt(n)), i++;
}
int SIZE = i;
for(i = 0; i<SIZE; i++){
if(a[i]) printf("prime\n");
else printf("not prime\n");
}
return 0;
}
| true |
0db52ea7fda963cc6fb69ba5bd49ac6acd719a96 | C++ | zhaohuanzhendl/algorithm | /leetcode/tree/Binary_Tree_Preorder_Traversal.cc | UTF-8 | 1,831 | 3.515625 | 4 | [] | no_license | /*
* Filename Binary_Tree_Preorder_Traversal.cc
* CreateTime 2017-03-14 17:27:53
*
* Copyright (C) Zhao Huanzhen
* Copyright (C) zhzcsp@gmail.com
*/
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr);
};
//stack
class Solution_s {
public:
vector<int> preorderT(TreeNode *root)
{
vector<int> result;
const TreeNode *p;
stack<const TreeNode *> s;
p = root;
if (p != nullptr) s.push(p);
while(!s.empty) {
p = s.top();
s.pop();
result.push_back(p->value);
if (p->right != nullptr) s.push(p->right);
if (p->left != nullptr) s.push(p->left);
}
}
};
//morris
class Solution_m {
public:
vector<int> preorderT(TreeNode *root)
{
vector<int> result;
TreeNode *cur, *prev;
cur = root;
while (cur != nullptr) {
if (cur->left == nullptr) {
result.push_back(cur->val);
prev = cur;
cur = cur->left;
} else {
/*search the prev point*/
TreeNode *node = cur->left;
while (node->right != nullptr && node->right != cur) {
node = node->right;
}
if (node->right == nullptr) {
result.push_back(cur->val);
node->right = cur;
prev = cur;
cur = cur->left;
} else {
node->right = nullptr;
cur = cur->right;
}
}
}
return result;
}
};
| true |
76d7add6db4145483998b6ee1d7eb46e050fe5f4 | C++ | pragyajaiswa05l/Data_structure_algorithm | /character array/remove_consecutive_duplicates.cpp | UTF-8 | 458 | 3.40625 | 3 | [] | no_license | #include<iostream>
using namespace std;
void removeConsecutiveDuplicates(char *input){
int j = 1;
char lastchar = input[0];
for(int i = 1 ; input[i] !='\0' ; i++){
if(input[i] != lastchar){
input[j] = input[i];
lastchar = input[j];
j++;
}
}
input[j] = '\0';
return;
}
int main(){
char input[100];
cin>>input;
removeConsecutiveDuplicates(input);
cout<<input<<endl;
}
| true |
cfd86e27403f16135bb7e224a2a6c590bb8d3f1e | C++ | denmats/CppII_2020 | /cppII_2020/zestaw_4/zestaw_zadan4_2.cpp | UTF-8 | 3,207 | 3.71875 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Punkt
{
protected:
int x;
int y;
public:
Punkt(){}
Punkt(int a, int b)
{
x = a;
y = b;
}
int getPunktX()
{
return x;
}
int getPunktY()
{
return y;
}
};
class Wektor :public Punkt
{
Punkt start;
Punkt finish;
string name;
static int counter;
public:
Wektor()
{
counter++;
}
Wektor(string n, Punkt s, Punkt f)
:Punkt()
{
name = n;
start = s;
finish = f;
counter++;
}
~Wektor()
{
name = "";
delete &start;
delete &finish;
}
static int getCounter()
{
return counter;
}
Punkt getPunktStart()
{
return start;
}
Punkt getPunktFinish()
{
return finish;
}
void display_wektor()
{
cout<<name<<"("<<start.getPunktX()<<","<<start.getPunktY()<<";"<<finish.getPunktX()<<","<<finish.getPunktY()<<")"<<endl;
}
Wektor static add(Wektor w1, Wektor w2)
{
int x1 = w1.getPunktStart().getPunktX()+w2.getPunktStart().getPunktX();
int y1 = w1.getPunktStart().getPunktY()+w2.getPunktStart().getPunktY();
Punkt a(x1,y1);
int x2 = w1.getPunktFinish().getPunktX()+w2.getPunktFinish().getPunktX();
int y2 = w1.getPunktFinish().getPunktY()+w2.getPunktFinish().getPunktY();
Punkt b(x2,y2);
Wektor result("addition",a,b);
return result;
}
Wektor static substract(Wektor w1, Wektor w2)
{
int x1 = w1.getPunktStart().getPunktX()-w2.getPunktStart().getPunktX();
int y1 = w1.getPunktStart().getPunktY()-w2.getPunktStart().getPunktY();
Punkt a(x1,y1);
int x2 = w1.getPunktFinish().getPunktX()-w2.getPunktFinish().getPunktX();
int y2 = w1.getPunktFinish().getPunktY()-w2.getPunktFinish().getPunktY();
Punkt b(x2,y2);
Wektor result("subtraction",a,b);
return result;
}
Wektor static multiply(Wektor w1, Wektor w2)
{
int x1 = w1.getPunktStart().getPunktX()*w2.getPunktStart().getPunktX();
int y1 = w1.getPunktStart().getPunktY()*w2.getPunktStart().getPunktY();
Punkt a(x1,y1);
int x2 = w1.getPunktFinish().getPunktX()*w2.getPunktFinish().getPunktX();
int y2 = w1.getPunktFinish().getPunktY()*w2.getPunktFinish().getPunktY();
Punkt b(x2,y2);
Wektor result("multiplication",a,b);
return result;
}
};
int Wektor::counter = 0;
int main()
{
Wektor w1("w1",Punkt(2,3),Punkt(-5,3));
Wektor w2("w2",Punkt(0,1),Punkt(-9,-2));
Wektor::add(w1,w2).display_wektor();
Wektor w3("w3",Punkt(2,23),Punkt(-5,13));
Wektor w4("w4",Punkt(10,11),Punkt(-19,-2));
Wektor::substract(w3,w4).display_wektor();
Wektor w5("w5",Punkt(2,-23),Punkt(-5,-13));
Wektor w6("w6",Punkt(-10,-11),Punkt(-19,-2));
Wektor::substract(w5,w6).display_wektor();
cout<<"Created "<<Wektor::getCounter()<<" vectors"<<endl;
return 0;
}
| true |
3219715a3025f8194aef1e714572409e5d5faa09 | C++ | AleLudovici/algorithms_part1_coursera | /HW2/quicksort_mid.cpp | UTF-8 | 2,074 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <math.h>
#include <boost/lexical_cast.hpp>
/*
* Compute the total number of comparisons used to sort the given input file by QuickSort.
* This version of QuickSort uses the "median-of-three" pivot rule. element of the array as the pivot
*/
using namespace std;
unsigned int cmp = 0;
/*
* Consider the first, middle, and final elements of the given array.
* The pivot is the median of these (i.e., the one whose value is in between the other two)
*/
int pivot(int l, int mid, int r){
// choose the medium
if ((l < mid && mid <= r) || (r < mid && mid < l))
return 1;
else if ((mid < l && l < r) || (r < l && l <=mid))
return 0;
else if ((mid < r && r < l) || (l < r && r < mid))
return 2;
}
// partition the array around the pivot
int partition (vector <int> &A, int l, int r){
int mid = floor((r+l)/2);
int i = l+1;
int tmp = 0;
int p = 0;
int x;
x = pivot(A[l], A[mid], A[r]);
switch (x){
case 0: p = l;
break;
case 1: p = mid;
break;
case 2: p = r;
break;
}
//preprocessing step
if(p != l){
tmp = A[p];
A[p] = A[l];
A[l] = tmp;
p = l;
}
for(int j = i; j <= r; ++j){
if (A[j] < A[p]){
tmp = A[j];
A[j] = A[i];
A[i] = tmp;
++i;
}
}
cmp += r - l;
tmp = A[p];
A[p] = A[i-1];
A[i-1] = tmp;
return i-1;
}
void quick_sort (vector <int> &A, int l, int r){
int p;
if (l < r ){
p = partition(A, l, r);
cout << p << endl;
quick_sort(A, l, p-1);
quick_sort(A, p+1, r);
}
return;
}
int main(){
ifstream myfile ("QuickSort.txt");
vector <int> A;
vector <string> S;
string line;
int num;
if (myfile.is_open()){
while(!myfile.eof()){
getline(myfile,line);
num = stoi( line );
A.push_back(num);
}
myfile.close();
} else {
cout << "Unable to open file" << endl;
}
quick_sort(A, 0, static_cast<int>(A.size()) -1 );
cout << "sorted: " << endl;
for(auto &i: A)
cout << i << " ";
cout << endl;
cout << "comparisons are: " << cmp << endl;
return 0;
} | true |
a95bd3e8b3c86e4c9d2d246a01327e9d39e59ac5 | C++ | gchudnov/cpp-json-qi | /include/cpp-json-qi/json_error.h | UTF-8 | 801 | 2.8125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "json_types.h"
#include <string>
#include <utility>
#include <stdexcept>
namespace jsonqi {
class json_error
: public std::runtime_error {
public:
typedef std::pair<size_t, size_t> position_type;
private:
size_t line_;
size_t column_;
public:
json_error(const std::string& message)
: runtime_error(message),
line_(0),
column_(0) {
}
json_error(const std::string& message, size_t line, size_t column)
: runtime_error(message),
line_(line),
column_(column) {
}
public:
size_t line() const {
return line_;
}
size_t column() const {
return column_;
}
position_type position() const {
return std::make_pair(line_, column_);
}
};
} // namespace jsonqi
| true |
88bfc16c3f6849e4e703c8e5e72e068d2a648956 | C++ | anghene/LAB | /C/Lab10/p2lab11.CPP | UTF-8 | 198 | 3 | 3 | [] | no_license | #include <stdio.h>
long fact(int x)
{
if (x==1) return(1);
else return(fact(x-1)*x);
}
void main ()
{
int n;
printf ("Introduce-ti nr ");
scanf ("%d",&n);
printf ("Rezultatul este %d",fact(n));
}
| true |
6d4f45d535f8eed34b19b1cbb4266d0ca1a602a7 | C++ | magusk/pet-fera | /src/InsetoNativo.cpp | UTF-8 | 2,737 | 2.765625 | 3 | [] | no_license | #include "InsetoNativo.h"
InsetoNativo::InsetoNativo() {
};
InsetoNativo::InsetoNativo(int id, string nome_cientifico, char sexo,
double tamanho, string dieta, shared_ptr<Veterinario> veterinario,
shared_ptr<Tratador> tratador, string nome_batismo, int total_de_mudas, string tipo_metamorfose,
int day, int month, int year, string autorizacao_ibama, string uf_origem):
Inseto(id, "Insecta", nome_cientifico, sexo, tamanho, dieta, veterinario,
tratador, nome_batismo, total_de_mudas, tipo_metamorfose, day, month, year),
AnimalNativo(autorizacao_ibama, uf_origem) {
};
InsetoNativo::~InsetoNativo() {
};
void InsetoNativo::set_autorizacao_ibama(string autorizacao_ibama){
m_autorizacao_ibama = autorizacao_ibama;
};
string InsetoNativo::write(){
ostringstream str;
str<<"InsetoNativo;";
str<<m_id<<";";
str<<m_classe<<";";
str<<m_nome_cientifico<<";";
str<<m_sexo<<";";
str<<m_tamanho<<";";
str<<m_dieta<<";";
str<<m_veterinario->get_id()<<";";
str<<m_tratador->get_id()<<";";
str<<m_nome_batismo<<";";
// Total de Mudas
str<<m_total_de_mudas<<";";
// Tipo de metamorfose
str<<m_tipo_metamorfose<<";";
// Última muda
str<<m_ultima_muda<<";";
//Autorização do Ibama
str<<m_autorizacao_ibama<<";";
// UF de origem
str<<m_uf_origem<<endl;
return str.str();
};
string InsetoNativo::Tipo(){
return "InsetoNativo";
};
ostream& InsetoNativo::print(ostream& os)const{
os<<"Campo \tTipo de Dados \tValores"<<endl;
os<<"Identificador Do animal \tInteiro \t"<<m_id<<endl;
os<<"Classe do animal \tCadeia de caracteres \t"<<m_classe<<endl;
os<<"Nome científico do animal \tCadeia de caracteres \t"<<m_nome_cientifico<<endl;
os<<"Sexo do animal \tCaractere \t"<<m_sexo<<endl;
os<<"Tamanho média em métros\tDecimal\t"<<m_tamanho<<endl;
os<<"Dieta Predominante \tCadeia de caracteres \t"<<m_dieta<<endl;
os<<"Veterinário associado \tInteiro \t"<<m_veterinario->get_id()<<endl;
os<<"Tratador responsável \tInteiro \t"<<m_tratador->get_id()<<endl;
os<<"Nome de batismo \tCadeia de caracteres \t"<<m_nome_batismo<<endl;
os<<"Total de mudas \tInteiro \t"<<m_total_de_mudas<<endl;
os<<"Data da última muda \tclasse date \t"<<m_ultima_muda<<endl;
os<<"Tipo de metamorfose \tCadeia de caracteres \t"<<m_tipo_metamorfose<<endl;
os<<"Autorização do Ibama \tCadeia de caracteres \t"<<m_autorizacao_ibama<<endl;
os<<"UF de origem \tCadeia de caracteres \t"<<m_uf_origem<<endl;
return os;
};
void InsetoNativo::inicializar_animal(int id){
inicializar_inseto(id);
inicializar_nativo();
};
void InsetoNativo::alterar_animal(string atributo){
alterar_inseto(atributo);
alterar_nativo(atributo);
}; | true |
3ef2228cbf02d4866cce2130487a0b3c1370b153 | C++ | Pengsc0616/IAmAwesome | /654. Medium - Maximum Binary Tree.hpp | UTF-8 | 871 | 3.46875 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if(nums.empty()) return nullptr;
auto it = max_element(nums.begin(), nums.end());
TreeNode * root = new TreeNode(*it);
vector<int> leftNums(nums.begin(),it);
vector<int> rightNums(it+1, nums.end());
root->left = constructMaximumBinaryTree(leftNums);
root->right = constructMaximumBinaryTree(rightNums);
return root;
}
}; | true |
e567db2ad6f03c3c2bf732bc827bca56dcbd7ebc | C++ | yeah2569/LearnOpenGL | /HelloOpenGL.cpp | UTF-8 | 867 | 2.640625 | 3 | [] | no_license | #include <GL/glut.h>
#include <stdlib.h>
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 0.0, 0.0);
glPolygonMode(GL_FRONT,GL_LINE);
glBegin(GL_POLYGON);
glEdgeFlag(GL_TRUE);
glVertex3f(20,50,10);
glEdgeFlag(GLU_FALSE);
glVertex3f(100,50,-50);
glEdgeFlag(GL_TRUE);
glVertex3f(50,150,60);
glEnd();
glFlush ();
}
void init (void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 250.0, 0.0, 250.0, -100.0, 100.0);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (250, 250);
glutInitWindowPosition (100, 100);
glutCreateWindow ("hello");
init ();
glutDisplayFunc(display);
glutMainLoop();
return 0; /* ANSI C requires main to return int. */
}
| true |
afe4d52e3088509af8064d208a7b852543b9a0db | C++ | PierceRTarleton/class_work | /queue/ListQueue.h | UTF-8 | 1,796 | 3.828125 | 4 | [] | no_license | /*
* Name:Pierce Tarleton
* Date Submitted:1/30/2019
* Lab Section: 4
* Assignment Name: Lab_2_Queue
*/
//Do we use the stuff from the linked list lab and change the class definition or use the template shown to be used in the class definition
#pragma once
#include <iostream>
#include <string>
#include "List.h"
using namespace std;
//This class represents a Queue implemented via Linked List
//Do not modify anything in the class interface
template <class T>
class ListQueue{
private:
List<T> queue;
public:
ListQueue();
~ListQueue();
int size();
bool empty();
void enqueue(T);
T dequeue();
//Print the name and this ListQueue's size and values to stdout
//This function is already implemented (no need to change it)
void print(string name){
queue.print(name);
}
}; //end of class interface (you may modify the code below)
//Implement all of the functions below
//Construct an empty ListQueue by initializig this ListQueue's instance variables
template <class T>
ListQueue<T>::ListQueue(){
List<T> queue;
}
//Destroy all nodes in this ListQueue to prevent memory leaks
template <class T>
ListQueue<T>::~ListQueue(){
}
//Return the size of this ListQueue
template <class T>
int ListQueue<T>::size(){
return queue.size();
}
//Return true if this ListQueue is empty
//Otherwise, return false
template <class T>
bool ListQueue<T>::empty(){
return queue.empty();
}
//Create a new node with value, and insert that new node
//into this ListQueue in its correct position
template <class T>
void ListQueue<T>::enqueue(T value){
queue.insert(value);
}
//Dequeue an element from the queue.
//Note that here that means both removing it from the list
//AND returning the value
template <class T>
T ListQueue<T>::dequeue(){
return queue.getFirst();
}
| true |
a91b9da49f7ecc1e796235cbbfe6ad38433fc40a | C++ | jurayev/system-monitor | /src/format.cpp | UTF-8 | 328 | 3.265625 | 3 | [
"MIT"
] | permissive | #include "format.h"
#include <string>
// INPUT: Long int measuring seconds
// OUTPUT: HH:MM:SS
std::string Format::Time(long time) {
char buffer[100];
int hours = time / (60 * 60);
int minutes = (time / 60) % 60;
int seconds = time % 60;
sprintf(buffer, "%02d:%02d:%02d", hours, minutes, seconds);
return buffer;
} | true |
8aa30c8c1d9fdbf9067d2d26e28263af0b02e635 | C++ | Plokana/TCPSockets | /client.cpp | UTF-8 | 1,414 | 3.359375 | 3 | [] | no_license | #include "client.h"
using namespace std;
void ClientSocket::CreateSocket(string hostname, int port){
m_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(m_sockfd <0){ perror("Sockfd error ");}
cout<<"sockfd : "<<m_sockfd<<"\n";
m_serveraddr.sin_addr.s_addr = inet_addr(hostname.c_str());
m_serveraddr.sin_family = AF_INET;
m_serveraddr.sin_port = htons(port);
cout<<"port : "<<port<<" htons(port): "<<htons(port)<<endl;
}
void ClientSocket::Connect(string hostname, int port){
cout<<"ClientSocket::Connect\n";
cout<<"Port : "<<port<<"htons(port): "<<htons(port);
int success = connect(m_sockfd, (struct sockaddr *)&m_serveraddr, sizeof(m_serveraddr));
if(success<0){perror("Connect error "); m_connected = false;}
else m_connected = true;
}
int ClientSocket::SendData(char * data){
char buf[300];
strcpy(buf,data);
int nBytes=0;
if(isConnected()){
nBytes=send(m_sockfd, buf, sizeof(buf), 0);
cout<<"bytes send : "<<nBytes<<"\n";
}
return nBytes;
}
int ClientSocket::ReceiveData(){
char buf[300];
int nBytes=0;
if(isConnected()){
nBytes=recv(m_sockfd, buf, sizeof(buf), 0);
cout<<"bytes received : "<<nBytes<<" "<<buf<<" \n";
}
return nBytes;
}
int main(int argc, char *argv[]){
ClientSocket s;
s.CreateSocket(argv[1], atoi(argv[2]));
s.Connect(argv[1], atoi(argv[2]));
s.SendData(argv[3]);
s.ReceiveData();
s.Disconnect();
}
| true |
a9ded2802c502c7658f2497a4d74264add988409 | C++ | loadbyte/multithreading-in-cpp-analysis | /1thread_sum.cpp | UTF-8 | 972 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <thread>
#include <atomic>
#include <bits/stdc++.h>
#include <chrono>
using namespace std;
// sum function
void sum(long start, long end)
{
unsigned long long cnt = 0;
for (int i = start; i < end; i++) {
cnt+=i;
}
cout<<cnt<<endl;
cout << "sum thread ends" << endl;
}
int main()
{
auto start = chrono::high_resolution_clock::now();
// unsync the I/O of C and C++.
ios_base::sync_with_stdio(false);
cout << "main thread starts" << endl;
thread th1(sum, 1,1000000000);
// Wait for thread t1 to finish
th1.join();
cout << "main thread ends" << endl;
auto end = chrono::high_resolution_clock::now();
// Calculating total time taken by the program.
double time_taken =
chrono::duration_cast<chrono::nanoseconds>(end - start).count();
time_taken *= 1e-9;
cout << "Time taken by program is : " << fixed
<< time_taken << setprecision(9);
cout << " sec" << endl;
return 0;
}
| true |
90cc5a0fba856b53dd77b950364d94e3d646b363 | C++ | aalto-speech/ftk | /src/MSFG.cc | UTF-8 | 13,975 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | #include <algorithm>
#include <sstream>
#include "MSFG.hh"
using namespace std;
MultiStringFactorGraph::~MultiStringFactorGraph() {
vector<Arc*> arcs;
collect_arcs(arcs);
for (auto it = arcs.begin(); it != arcs.end(); ++it)
delete *it;
}
bool ascending_by_first(pair<int, int> i,pair<int, int> j) { return (i.first < j.first); }
void
MultiStringFactorGraph::add(const FactorGraph &text,
bool lookahead)
{
map<fg_node_idx_t, msfg_node_idx_t> visited_nodes;
multimap<fg_node_idx_t, pair<msfg_node_idx_t, FactorGraph::Arc*> > arcs_to_process;
// multimap key is target index in fg, value pair source index in msfg, arc in fg
// ordering arcs by target index ensures topological order for text nodes in msfg
const FactorGraph::Node &fg_node = text.nodes[0];
for (auto fg_arcit = fg_node.outgoing.cbegin(); fg_arcit != fg_node.outgoing.cend(); ++fg_arcit)
arcs_to_process.insert(make_pair((**fg_arcit).target_node, make_pair(0, *fg_arcit)));
while (arcs_to_process.size() > 0) {
auto arc_to_process = arcs_to_process.begin();
FactorGraph::Arc *arc = (*arc_to_process).second.second;
fg_node_idx_t fg_target_node = arc->target_node;
msfg_node_idx_t msfg_source_node = (*arc_to_process).second.first;
arcs_to_process.erase(arc_to_process);
string target_node_factor = text.get_factor(fg_target_node);
msfg_node_idx_t msfg_target_node = 0;
// Check if have connected to this fg node already from some other node
// Just find or add arc and continue
if (visited_nodes.find(fg_target_node) != visited_nodes.end()) {
msfg_target_node = visited_nodes[fg_target_node];
find_or_create_arc(msfg_source_node, msfg_target_node);
continue;
}
// Check if node exists in msfg, just not visited yet
if (lookahead) {
auto flait = factor_lookahead.find(msfg_source_node);
if (flait != factor_lookahead.end()) {
auto flait2 = flait->second.find(target_node_factor);
if (flait2 != flait->second.end())
msfg_target_node = flait2->second;
}
}
else {
MultiStringFactorGraph::Node &msfg_node = nodes[msfg_source_node];
for (auto msfg_arcit = msfg_node.outgoing.begin(); msfg_arcit != msfg_node.outgoing.end(); ++msfg_arcit)
if (nodes[(**msfg_arcit).target_node].factor == target_node_factor) {
msfg_target_node = (**msfg_arcit).target_node;
break;
}
}
if (msfg_target_node != 0) {
visited_nodes[fg_target_node] = msfg_target_node;
const FactorGraph::Node &fg_node = text.nodes[fg_target_node];
for (auto fg_arcit = fg_node.outgoing.cbegin(); fg_arcit != fg_node.outgoing.cend(); ++fg_arcit)
arcs_to_process.insert(make_pair((**fg_arcit).target_node, make_pair(msfg_target_node, *fg_arcit)));
continue;
}
// Create new node and arc
nodes.push_back(Node(target_node_factor));
msfg_target_node = nodes.size()-1;
visited_nodes[fg_target_node] = msfg_target_node;
if (lookahead) factor_lookahead[msfg_source_node][target_node_factor] = msfg_target_node;
const FactorGraph::Node &fg_node = text.nodes[fg_target_node];
for (auto fg_arcit = fg_node.outgoing.cbegin(); fg_arcit != fg_node.outgoing.cend(); ++fg_arcit)
arcs_to_process.insert(make_pair((**fg_arcit).target_node, make_pair(msfg_target_node, *fg_arcit)));
create_arc(msfg_source_node, msfg_target_node);
}
string_end_nodes[text.text] = visited_nodes[text.nodes.size()-1];
reverse_string_end_nodes[visited_nodes[text.nodes.size()-1]] = text.text;
}
int
MultiStringFactorGraph::num_paths(const std::string &text) const
{
if (nodes.size() == 0) return 0;
if (string_end_nodes.find(text) == string_end_nodes.end()) return 0;
msfg_node_idx_t end_node = string_end_nodes.at(text);
map<msfg_node_idx_t, int> path_counts; path_counts[end_node] = 1;
set<msfg_node_idx_t> nodes_to_process; nodes_to_process.insert(end_node);
while(nodes_to_process.size() > 0) {
msfg_node_idx_t i = *(nodes_to_process.rbegin());
const Node &node = nodes[i];
for (auto arc = node.incoming.begin(); arc != node.incoming.end(); ++arc) {
path_counts[(**arc).source_node] += path_counts[i];
nodes_to_process.insert((**arc).source_node);
}
nodes_to_process.erase(i);
}
return path_counts[0];
}
void
MultiStringFactorGraph::get_paths(const string &text,
vector<vector<string> > &paths) const
{
if (string_end_nodes.find(text) == string_end_nodes.end()) return;
msfg_node_idx_t end_node = string_end_nodes.at(text);
vector<string> curr_string;
advance(paths, curr_string, end_node);
for (auto it = paths.begin(); it != paths.end(); ++it)
std::reverse(it->begin(), it->end());
}
void
MultiStringFactorGraph::print_paths(const string &text) const
{
vector<vector<string> > paths;
get_paths(text, paths);
for (auto pathit = paths.begin(); pathit != paths.end(); ++pathit) {
for (auto it = pathit->begin(); it != pathit->end(); ++it)
cout << *it << " ";
cout << endl;
}
}
void
MultiStringFactorGraph::advance(vector<vector<string> > &paths,
vector<string> &curr_string,
msfg_node_idx_t node_idx) const
{
const MultiStringFactorGraph::Node &node = nodes[node_idx];
curr_string.push_back(node.factor);
if (node_idx == 0) {
paths.push_back(curr_string);
return;
}
for (auto arc = node.incoming.begin(); arc != node.incoming.end(); ++arc) {
vector<string> curr_copy(curr_string);
advance(paths, curr_copy, (**arc).source_node);
}
}
void
MultiStringFactorGraph::create_arc(msfg_node_idx_t src_node,
msfg_node_idx_t tgt_node)
{
Arc *arc = new Arc(src_node, tgt_node, NULL);
nodes[src_node].outgoing.insert(arc);
nodes[tgt_node].incoming.insert(arc);
}
void
MultiStringFactorGraph::find_or_create_arc(msfg_node_idx_t src_node,
msfg_node_idx_t tgt_node)
{
for (auto ait = nodes[tgt_node].incoming.begin(); ait != nodes[tgt_node].incoming.end(); ++ait)
if ((**ait).source_node == src_node) return;
create_arc(src_node, tgt_node);
}
void
MultiStringFactorGraph::remove_arc(Arc *arc)
{
Node &src_node = nodes[(*arc).source_node];
src_node.outgoing.erase(arc);
Node &tgt_node = nodes[(*arc).target_node];
tgt_node.incoming.erase(arc);
delete arc;
}
void
MultiStringFactorGraph::remove_arcs(const std::string &factor)
{
if (factor.length() < 2) {
cerr << "Trying to remove factor of length 1: " << factor << endl;
exit(EXIT_FAILURE);
}
for (auto ndit = factor_node_map[factor].begin(); ndit != factor_node_map[factor].end(); ++ndit) {
Node &node = nodes[*ndit];
while (node.incoming.size() > 0)
remove_arc(*(node.incoming.begin()));
while (node.outgoing.size() > 0)
remove_arc(*(node.outgoing.begin()));
}
factor_node_map.erase(factor);
}
void
MultiStringFactorGraph::prune_unreachable()
{
for (auto it = nodes.begin(); it != nodes.end(); it++) {
if (it->factor == start_end_symbol) continue;
if (it->incoming.size() == 0)
while (it->outgoing.size() > 0)
remove_arc(*(it->outgoing.begin()));
if (it->outgoing.size() == 0)
while (it->incoming.size() > 0)
remove_arc(*(it->incoming.begin()));
}
}
void
MultiStringFactorGraph::prune_unused(transitions_t &transitions)
{
if (transitions.size() < factor_node_map.size()) {
vector<string> to_remove;
cerr << "Pruning " << factor_node_map.size()-transitions.size() << " unused factors from msfg." << endl;
for (auto it = factor_node_map.begin(); it != factor_node_map.end(); ++it)
if (transitions.find(it->first) == transitions.end())
to_remove.push_back(it->first);
for (auto it = to_remove.begin(); it != to_remove.end(); ++it)
remove_arcs(*it);
}
}
void
MultiStringFactorGraph::write(const std::string &filename) const
{
ofstream outfile(filename);
if (!outfile) return;
vector<Arc*> arcs; collect_arcs(arcs);
outfile << nodes.size() << " " << arcs.size() << " " << string_end_nodes.size() << endl;
for (unsigned int i=0; i<nodes.size(); i++)
outfile << "n " << i << " " << nodes[i].factor << endl;
for (auto it = arcs.begin(); it != arcs.end(); ++it)
outfile << "a " << (**it).source_node << " " << (**it).target_node << endl;
for (auto it = string_end_nodes.cbegin(); it != string_end_nodes.cend(); ++it)
outfile << "e " << it->first << " " << it->second << endl;
outfile.close();
}
void
MultiStringFactorGraph::read(const std::string &filename)
{
ifstream infile(filename);
if (!infile) return;
int node_count, arc_count, end_node_count;
char type;
string line;
getline(infile, line);
stringstream ss(line);
ss >> node_count >> arc_count >> end_node_count;
nodes.clear();
string_end_nodes.clear();
reverse_string_end_nodes.clear();
nodes.resize(node_count);
msfg_node_idx_t node_idx;
string factor;
for (int i=0; i<node_count; i++) {
getline(infile, line);
stringstream nodess(line);
nodess >> type;
if (type != 'n') {
cerr << "Some problem reading MSFG file" << endl;
exit(EXIT_FAILURE);
}
nodess >> node_idx >> factor;
nodes[node_idx].factor.assign(factor);
factor_node_map[factor].push_back(node_idx);
}
msfg_node_idx_t src_node, tgt_node;
for (int i=0; i<arc_count; i++) {
getline(infile, line);
stringstream arcss(line);
arcss >> type;
if (type != 'a') {
cerr << "Some problem reading MSFG file" << endl;
exit(EXIT_FAILURE);
}
arcss >> src_node >> tgt_node;
create_arc(src_node, tgt_node);
}
msfg_node_idx_t end_node_idx;
string curr_string;
for (int i=0; i<arc_count; i++) {
getline(infile, line);
stringstream endnss(line);
endnss >> type;
if (type != 'e') {
cerr << "Some problem reading MSFG file" << endl;
exit(EXIT_FAILURE);
}
endnss >> curr_string >> end_node_idx;
string_end_nodes[curr_string] = end_node_idx;
reverse_string_end_nodes[end_node_idx] = curr_string;
}
infile.close();
}
void
MultiStringFactorGraph::update_factor_node_map()
{
factor_node_map.clear();
for (msfg_node_idx_t idx=0; idx < nodes.size(); idx++) {
Node &nd = nodes[idx];
factor_node_map[nd.factor].push_back(idx);
}
}
void
MultiStringFactorGraph::collect_arcs(vector<Arc*> &arcs) const
{
for (auto ndit = nodes.begin(); ndit != nodes.end(); ++ndit)
for (auto arcit = ndit->outgoing.begin(); arcit != ndit->outgoing.end(); ++arcit)
arcs.push_back(*arcit);
}
void
MultiStringFactorGraph::collect_arcs(const string &text,
map<msfg_node_idx_t, vector<Arc*> > &arcs) const
{
msfg_node_idx_t end_node = string_end_nodes.at(text);
set<msfg_node_idx_t> nodes_to_process; nodes_to_process.insert(end_node);
while(nodes_to_process.size() > 0) {
msfg_node_idx_t i = *(nodes_to_process.rbegin());
const Node &node = nodes[i];
for (auto arc = node.incoming.begin(); arc != node.incoming.end(); ++arc) {
arcs[(**arc).source_node].push_back(*arc);
nodes_to_process.insert((**arc).source_node);
}
nodes_to_process.erase(i);
}
}
void
MultiStringFactorGraph::collect_factors(const string &text,
set<string> &factors) const
{
msfg_node_idx_t end_node = string_end_nodes.at(text);
set<msfg_node_idx_t> nodes_to_process; nodes_to_process.insert(end_node);
while(nodes_to_process.size() > 0) {
msfg_node_idx_t i = *(nodes_to_process.rbegin());
const Node &node = nodes[i];
factors.insert(node.factor);
for (auto arc = node.incoming.begin(); arc != node.incoming.end(); ++arc)
nodes_to_process.insert((**arc).source_node);
nodes_to_process.erase(i);
}
}
void MultiStringFactorGraph::print_dot_digraph(ostream &fstr)
{
fstr << "digraph {" << endl << endl;
fstr << "\tnode [shape=ellipse,fontsize=30,fixedsize=false,width=0.95];" << endl;
fstr << "\tedge [fontsize=12];" << endl;
fstr << "\trankdir=LR;" << endl << endl;
for (msfg_node_idx_t ni=0; ni<nodes.size(); ++ni) {
fstr << "\t" << ni;
string label = nodes[ni].factor;
if (label == start_end_symbol && ni > 0) {
label += " / " + reverse_string_end_nodes[ni];
fstr << " [label=\"" << label << "\", style=filled, fillcolor=grey]" << endl;
}
else
fstr << " [label=\"" << label << "\"]" << endl;
}
fstr << endl;
for (msfg_node_idx_t ni=0; ni<nodes.size(); ++ni) {
Node &nd = nodes[ni];
for (auto ait = nd.outgoing.begin(); ait != nd.outgoing.end(); ++ait) {
fstr << "\t" << (*ait)->source_node << " -> " << (*ait)->target_node;
flt_type *cost = (*(*ait)).cost;
if (cost != nullptr)
fstr << "[label=\"" << *cost << "\"];";
fstr << endl;
}
}
fstr << "}" << endl;
}
| true |