blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
201edb3b828a097061b044e44d2fce638f894152
|
5f79d7500df648a6405816f2e2d8935a458bd7d9
|
/Function/static_DataMember_method.cpp
|
496e84925917eaeb00371721c282e8607fa1d7b4
|
[] |
no_license
|
radheshyam0508/C-_Files
|
9126180f6b3431e5db4343dea8b3bd246fa6440d
|
1cd9f46dd9c4e3b50c0d09ff29c1b3e181372a83
|
refs/heads/master
| 2023-01-23T02:15:44.074989
| 2020-11-04T14:52:36
| 2020-11-04T14:52:36
| 310,030,465
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 939
|
cpp
|
static_DataMember_method.cpp
|
#include<iostream>
using namespace std;
class Employee{
int ID;
static int count; // By default it initialized with zero 0'
public:
void SetData(){
cout<<"Enter the ID of the Employee "<<endl;
cin>>ID;
count++;
}
void GetData(){
cout<<"The ID of the employee is " <<ID<< " and the employee count is "<<count<<endl;
}
static void getCount(){
cout<<"The value of count is "<<count<<endl;
}
};
int Employee ::count;
int main(){
Employee Radhe, manu, Ram;
//Radhe.ID=1; //---------Can not do this beacuse ID and Count is private
//Radhe.count=1;
Radhe.SetData();
Radhe.GetData();
Employee::getCount(); // To RUN the STATIC function, STATIC function uses only the static member
manu.SetData();
manu.GetData();
Employee::getCount();
Ram.SetData();
Ram.GetData();
Employee::getCount();
return 0;
}
|
8f0ead3621ace1121d3ced3c458519ceca5b7c4d
|
60729446e7e6b60f2b4013450363d4a6d62cc6a1
|
/2.Firmware/Ctrl-Step-Driver-STM32F1-fw/Ctrl/Driver/tb67h450_base.cpp
|
54d47b9d4884a5525c28e4037b6a5589e23f42e1
|
[] |
no_license
|
asdlei99/Dummy-Robot
|
7a3258ed5314ff32928566dd6a51f4ff4c2b6605
|
84453f1391c4442b5387a799571b7f67418afa2d
|
refs/heads/main
| 2023-09-04T05:49:51.175035
| 2022-10-20T16:38:31
| 2022-10-20T16:38:31
| 415,791,815
| 0
| 0
| null | 2021-10-11T05:37:45
| 2021-10-11T05:37:44
| null |
UTF-8
|
C++
| false
| false
| 2,074
|
cpp
|
tb67h450_base.cpp
|
#include "tb67h450_base.h"
#include "sin_map.h"
void TB67H450Base::Init()
{
InitGpio();
InitPwm();
}
void TB67H450Base::SetFocCurrentVector(uint32_t _directionInCount, int32_t _current_mA)
{
phaseB.sinMapPtr = (_directionInCount) & (0x000003FF);
phaseA.sinMapPtr = (phaseB.sinMapPtr + (256)) & (0x000003FF);
phaseA.sinMapData = sin_pi_m2[phaseA.sinMapPtr];
phaseB.sinMapData = sin_pi_m2[phaseB.sinMapPtr];
uint32_t dac_reg = abs(_current_mA);
dac_reg = (uint32_t) (dac_reg * 5083) >> 12;
dac_reg = dac_reg & (0x00000FFF);
phaseA.dacValue12Bits =
(uint32_t) (dac_reg * abs(phaseA.sinMapData)) >> sin_pi_m2_dpiybit;
phaseB.dacValue12Bits =
(uint32_t) (dac_reg * abs(phaseB.sinMapData)) >> sin_pi_m2_dpiybit;
SetTwoCoilsCurrent(phaseA.dacValue12Bits, phaseB.dacValue12Bits);
if (phaseA.sinMapData > 0)
SetInputA(true, false);
else if (phaseA.sinMapData < 0)
SetInputA(false, true);
else
SetInputA(true, true);
if (phaseB.sinMapData > 0)
SetInputB(true, false);
else if (phaseB.sinMapData < 0)
SetInputB(false, true);
else
SetInputB(true, true);
}
void TB67H450Base::SetTwoCoilsCurrent(uint16_t _currentA_3300mAIn12Bits, uint16_t _currentB_3300mAIn12Bits)
{
/*
* After SetFocCurrentVector calculation a 12bits value was mapped to 0~3300mA.
* And due to used 0.1Ohm shank resistor, 0~3300mV V-ref means 0~3300mA CurrentSetPoint,
* For more details, see TB67H450 Datasheet page.10 .
*/
DacOutputVoltage(_currentA_3300mAIn12Bits, _currentB_3300mAIn12Bits);
}
void TB67H450Base::Sleep()
{
phaseA.dacValue12Bits = 0;
phaseB.dacValue12Bits = 0;
SetTwoCoilsCurrent(phaseA.dacValue12Bits, phaseB.dacValue12Bits);
SetInputA(false, false);
SetInputB(false, false);
}
void TB67H450Base::Brake()
{
phaseA.dacValue12Bits = 0;
phaseB.dacValue12Bits = 0;
SetTwoCoilsCurrent(phaseA.dacValue12Bits, phaseB.dacValue12Bits);
SetInputA(true, true);
SetInputB(true, true);
}
|
47c29288a7561f0e01d282383e8843942dc83093
|
8d2698238e80bec9660e700f81a902f543db3b83
|
/P/P2/CW/5/3dArray.cpp
|
48ce6c526b0ebd0baf4d0accc7c3bb11d60eaa08
|
[] |
no_license
|
lukmccall/UJ
|
5d672d06cd9b086ff527517a4c215da5c967e102
|
05bb2cf258ba734b2db41a999a4136019271960c
|
refs/heads/master
| 2020-09-14T21:47:57.824883
| 2019-11-21T21:35:22
| 2019-11-21T21:35:22
| 223,267,173
| 5
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,112
|
cpp
|
3dArray.cpp
|
#include <iostream>
#include <stdlib.h>
class Array3D{
private:
int width;
int height;
int deep;
int*** pointer;
public:
Array3D( int w = 0, int h = 0, int d = 0 ){
width = w;
height = h;
deep = d;
pointer = new int**[ width ];
for( int i = 0; i < width; i++ ){
pointer[ i ] = new int*[ height ];
for( int j = 0; j < height; j++ ){
pointer[i][j] = new int[ deep ];
for( int t = 0; t < deep; t++ )
pointer[i][j][t] = 0;
}
}
}
Array3D( const Array3D& array ){
width = array.width;
height = array.height;
deep = array.deep;
pointer = new int**[ width ];
for( int i = 0; i < width; i++ ){
pointer[ i ] = new int*[ height ];
for( int j = 0; j < height; j++ ){
pointer[i][j] = new int[ deep ];
for( int t = 0; t < deep; t++ )
pointer[i][j][t] = array.pointer[i][j][t] ;
}
}
}
~Array3D(){
std::cout << "Sprzatanie pamieci" << std::endl;
for( int i = 0; i < width; i++ ){
for( int j = 0; j < height; j++ )
delete[] pointer[i][j];
delete[] pointer[i];
}
delete[] pointer;
}
void print(){
for( int i = 0; i < width; i++ ){
std::cout << "W: " << i << std::endl;
for( int j = 0; j < height; j++ ){
for( int t = 0; t < deep; t++ ){
std::cout << pointer[i][j][t] << " ";
}
std::cout << std::endl;
}
}
}
void insert( int val, int w, int h, int d ){
if( w >= 0 && w < width && h >= 0 && h < height && d >= 0 && d < deep )
pointer[ w ][ h ][ d ] = val;
}
void resize( int w, int h, int d ){
int*** newPointer = new int**[ w ];
for( int i = 0; i < w; i++ ){
newPointer[ i ] = new int*[ h ];
for( int j = 0; j < h; j++ ){
newPointer[i][j] = new int[ d ];
for( int t = 0; t < d; t++ )
if( i >= 0 && i < width && j >= 0 && j < height && t >= 0 && t < deep )
newPointer[i][j][t] = pointer[i][j][t];
else
newPointer[i][j][t] = 0;
}
}
for( int i = 0; i < width; i++ ){
for( int j = 0; j < height; j++ )
delete[] pointer[i][j];
delete[] pointer[i];
}
delete[] pointer;
pointer = newPointer;
width = w;
height = h;
deep = d;
/*
if( w != width ){
std::cout << "cos";
width = w;
pointer = (int***)realloc(pointer, sizeof(int**) * width );
}
if( h != height ){
std::cout << "cos2";
height = h;
for( int i = 0; i < width; i++ )
pointer[ i ] = (int**)realloc(pointer[ i ], sizeof(int*) * height);
}
if( d != deep){
std::cout << "cos3";
deep = d;
for( int i = 0; i < width; i++ )
for( int j = 0; j < height; j++ )
pointer[i][j] = (int*)realloc(pointer[i][j], sizeof(int) * deep);
}
*/
}
};
int main(){
Array3D array(5,5,5);
array.print();
std::cout << std::endl;
for( int i = 0; i < 5; i++ )
for( int j = 0; j < 5; j++ )
for( int t = 0; t < 5; t++ )
array.insert(i*100+j*10+t,i,j,t);
array.print();
std::cout << std::endl;
array.resize(3,3,3);
array.print();
std::cout << std::endl;
Array3D copy( array );
copy.print();
copy.resize( 6,6,6);
array.print();
std::cout << std::endl;
copy.print();
return 0;
}
|
2e818d4a6d2fa95007f2a0fc3173f6bf70a7f802
|
9fd511af17219366e7826ed95bfa0c181fde32a5
|
/Lab Work 4/Question 2/Vector.cpp
|
8bf986946d9ae43a071b305a831c98854bda343d
|
[] |
no_license
|
SaskarKhadka/labworksFirstSem
|
4162f916a4a03c5d093fde17cc3d3bf833b9cc14
|
bc006c0f5fa3d2ce7a96d5d13af2ff9f0b7a6309
|
refs/heads/main
| 2023-04-01T02:59:57.137236
| 2021-03-28T12:28:05
| 2021-03-28T12:28:05
| 316,514,596
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,952
|
cpp
|
Vector.cpp
|
#include "Vector.h"
#include <iostream>
//default constructor
Vector::Vector() {
x = 0;
y = 0;
z = 0;
isRowVector = true;
}
//parameterized constructor
Vector::Vector(double x, double y, double z, bool isRowVector) {
this->x = x;
this->y = y;
this->z = z;
this->isRowVector = isRowVector;
}
//copy assignmnent operator
Vector::Vector(const Vector & another) {
this->x = another.x;
this->y = another.y;
this->z = another.z;
}
//getters and setters
void Vector::setX(const double& x) {
this->x = x;
}
double Vector::getX() const{
return this->x;
}
void Vector::setY(const double& y) {
this->y = y;
}
double Vector::getY() const{
return this->y;
}
void Vector::setZ(const double& z) {
this->z = z;
}
double Vector::getZ() const {
return this->z;
}
bool Vector::rowVector() const{
return this->isRowVector;
}
//member function to overload + operator
Vector Vector::operator+(const Vector& v2) {
if(this->rowVector() == v2.rowVector()) {
Vector v3;
v3.x = this->getX() + v2.getX();
v3.y = this->getY() + v2.getY();
v3.z = this->getZ() + v2.getZ();
return v3;
}
else {
std::cout << "\nA row vector and a column vector or vice versa cannot be added" << std::endl;
Vector v4;
return v4; //returns a vector whose all elements are zero with an error message
}
}
//member function to overload += operator
Vector& Vector::operator+=(const Vector& v1) {
if(this->rowVector() == v1.rowVector()) {
this->x += v1.x;
this->y += v1.y;
this->z += v1.z;
return *this;
}
else {
std::cout << "\nA row vector and a column vector or vice versa cannot be added" << std::endl;
return *this; //returns the initial vector with an error message
}
}
//friend function to overload greater than operator
bool operator>(const Vector& v1, const Vector& v2) {
return v1.x > v2.x && v1.y > v2.y && v1.z > v2.z;
}
//friend function to overload input stream operator
std::istream& operator>>(std::istream& input, Vector& v1) {
return input >> v1.x >> v1.y >> v1.z >> v1.isRowVector;
}
//normal function to overload output stream operator
std::ostream& operator<<(std::ostream& print, const Vector& v1) {
if(v1.rowVector())
return print << "[" << v1.getX() << " " << v1.getY() << " " << v1.getZ() << "]" << std::endl;
else
return print << v1.getX() << std::endl << "\t\t " << v1.getY() << std::endl << "\t\t " << v1.getZ() << std::endl;
}
//normal function to overload minus operator
Vector operator-(const Vector& v1, const Vector& v2) {
if(v1.rowVector() == v2.rowVector()) {
Vector v3;
v3.setX(v1.getX() - v2.getX());
v3.setY(v1.getY() - v2.getY());
v3.setZ(v1.getZ() - v2.getZ());
return v3;
}
else {
std::cout << "\nA row vector and a column vector or vice versa cannot be subtracted" << std::endl;
Vector v4;
return v4; //returns a vector whose all elements are zero with an error message
}
}
//normal function to overload comparision operator
bool operator==(const Vector& v1, const Vector& v2) {
return v1.getX() == v2.getX() && v1.getY() == v2.getY() && v1.getZ() == v2.getZ();
}
//normal function to overload multiplication operator
double operator*(const Vector& v1, const Vector& v2) {
if(v1.rowVector()) {
if(!v2.rowVector()) {
return v1.getX() * v2.getX() + v1.getY() * v2.getY() + v1.getZ() * v2.getZ();
}else {
std::cout << "\nA row Vector cannot be multiplied with another Row Vector" << std::endl;
return 0; //returning 0 with an error message
}
}
else {
std::cout << "\nThis function is only limited to the multiplication of a Row Vector with a Column Vector not the other way around" << std::endl;
return 0; //returning 0 with an error message
}
}
|
7911df998cd18af5d7bb051dbf1ee6f379311eab
|
040abee992b3cb04926602cb3fb80a6ae7eb776c
|
/examples/hello_world/hello_world.ino
|
2d9f65f731d3d1b2038aca324d2d69a09ad79251
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
madleech/CrossingFlasher
|
2bb1399dfd75f6f5b6a445d8d6ae77c8d269bcb7
|
a469903ad3ef0770de72f50fef2683955deb9548
|
refs/heads/master
| 2021-01-19T10:57:41.462849
| 2013-09-30T09:24:53
| 2013-09-30T09:24:53
| 13,210,886
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 339
|
ino
|
hello_world.ino
|
/**
* Hello World
* ===========
* Simple demo that turns on the cross bucks and then flashes them for ever.
*
* For more info, see http://utrainia.michael.net.nz/46-simulating-railroad-crossing-lights
*/
#include <CrossingFlasher.h>
CrossingFlasher bucks(2, 3);
void setup() {
bucks.on();
}
void loop() {
bucks.update();
}
|
31674c73c1b8f49caeed957e33aac65b1cc64a3e
|
39f56b90559f2fe1fe0b8892cf1f6480b5c317b2
|
/swdnn_test/src/test_relu.cpp
|
bffc7fbf48c5266f744fb37e1383df314e362fec
|
[] |
no_license
|
sspeng/SWCaffe
|
c7f631ebc005690df55fa66bd775fac92ffb24cc
|
679db37006acfd7ed1cae9a1ccef986b4d05e4e7
|
refs/heads/master
| 2021-01-20T03:56:36.242752
| 2017-08-14T03:17:10
| 2017-08-14T03:17:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,008
|
cpp
|
test_relu.cpp
|
extern "C" {
#include "caffe/swlayers/sw_relu_layer_impl.h"
}
#include "test_relu_layer_impl.hpp"
#include <math.h>
#include <stdio.h>
#include "athread.h"
#include "timer.h"
void test_relu_main() {
//test_relu_forward();
//test_relu_backward();
//test_relu_forward_f();
//test_relu_backward_f();
}
void test_relu_forward_f() {
printf("Test relu forward-float...\n");
int count;
float negative_slope;
count = 2*1024*1024; // 16M
negative_slope = rand()/(float)RAND_MAX - 0.5;
float* in = (float*)malloc(sizeof(float)*count);
float* out = (float*)malloc(sizeof(float)*count);
float* out_ref = (float*)malloc(sizeof(float)*count);
for( int i = 0; i < count; ++i )
in[i] = rand()/(float)RAND_MAX - 0.5;
for( int st = 0; st < 1; ++st ){
begin_timer("sw_relu_forward_impl_f");
sw_relu_forward_impl_f(
in,
out,
negative_slope,
count);
stop_timer();
begin_timer("test_relu_forward_impl_f");
test_relu_forward_impl_f(
in,
out_ref,
negative_slope,
count);
stop_timer();
printf("inner loop %d OK!\n",st);
}
//if(!athread_halt())
// printf("athread halt not OK!\n");
printf("now calculating errors.\n");
double sum = 0, sum_ref = 0;
for( int i = 0; i < count; ++i ) {
#ifdef DEBUG_INFO
printf("%d: input: %lf\n",i,in[i]);
printf("%d: swdnn-relu:%lf ori-relu:%lf\n",i,out[i],out_ref[i]);
printf("%d: swdnn-relu - ori-relu = %lf\n",i,out[i]-out_ref[i]);
#endif
if( fabs(out_ref[i] - out[i]) > 1e-4) {
printf("ERROR at %d: %lf vs %lf\n", i, out_ref[i], out[i]);
printf("\tinput: %lf negative_slope: %lf\n", in[i],negative_slope);
printf("\tlocal_count for id=0: %d\n",count/64 + (0<(count%64)));
printf("\tlocal_start for id=1: %d\n",(count/64)+(1<(count%64)));
#define DEBUG
#ifdef DEBUG
void *param_in = in;
float* in_ptr = &((float*)param_in)[(count/64)+(1<(count%64))];
printf("\t%lf\n",in_ptr[0]);
printf("\tsearching...\n");
for(int j = 0; j<count; ++j ) {
if(fabs(out_ref[j] - out[i]) < 1e-4)
printf("Maybe this one: index=%d, out_ref=%lf, out=%lf\n",j,out_ref[j],out[i]);
break;
}
#endif
printf("************** athread forward failed ****************\n");
free(out_ref);
free(out);
free(in);
return ;
}
sum += out[i];
sum_ref += out_ref[i];
}
free(out_ref);
free(out);
free(in);
printf("sum %lf vs sum_ref %lf athread forward OK!\n", sum, sum_ref);
}
void test_relu_backward_f() {
printf("Test relu backward-float...\n");
int count;
float negative_slope;
count = 2*1024*1024;
negative_slope = rand()/(float)RAND_MAX - 0.5;
int in_size = count;
int out_size = count;
float* in = (float*)malloc(sizeof(float)*in_size);
float* in_diff = (float*)malloc(sizeof(float)*in_size);
float* in_diff_ref = (float*)malloc(sizeof(float)*in_size);
float* out_diff = (float*)malloc(sizeof(float)*out_size);
for( int i = 0; i < in_size; ++i )
in[i] = rand()/(float)RAND_MAX - 0.5;
for( int i = 0; i < out_size; ++i )
out_diff[i] = rand()/(float)RAND_MAX - 0.5;
printf("now calculating swdnn value...\n");
begin_timer("sw_relu_backward_impl_f");
sw_relu_backward_impl_f(
in,
out_diff,
in_diff,
negative_slope,
count);
stop_timer();
printf("now calculating reference value...\n");
begin_timer("test_relu_backward_impl_f");
test_relu_backward_impl_f(
in,
out_diff,
in_diff_ref,
negative_slope,
count);
stop_timer();
for( int i = 0; i < in_size; ++i )
if(fabs(in_diff[i] - in_diff_ref[i]) > 1e-4) {
printf("ERROR at %d: in_diff %lf vs ref %lf\n", i, in_diff[i], in_diff_ref[i]);
printf("\tinput: %lf out_diff: %lf negative_slope: %lf\n",in[i],out_diff[i],negative_slope);
printf("************** athread backward failed ****************\n");
free(in_diff_ref);
free(out_diff);
free(in);
free(in_diff);
return ;
}
printf("backward test OK!");
free(in);
free(in_diff);
free(in_diff_ref);
free(out_diff);
}
void test_relu_forward() {
printf("Test relu forward...\n");
int count;
double negative_slope;
count = 2*1024*1024; // 16M
negative_slope = rand()/(double)RAND_MAX - 0.5;
double* in = (double*)malloc(sizeof(double)*count);
double* out = (double*)malloc(sizeof(double)*count);
double* out_ref = (double*)malloc(sizeof(double)*count);
for( int i = 0; i < count; ++i )
in[i] = rand()/(double)RAND_MAX - 0.5;
for( int st = 0; st < 1; ++st ){
begin_timer("sw_relu_forward_impl_d");
sw_relu_forward_impl_d(
in,
out,
negative_slope,
count);
stop_timer();
begin_timer("test_relu_forward_impl_d");
test_relu_forward_impl_d(
in,
out_ref,
negative_slope,
count);
stop_timer();
printf("inner loop %d OK!\n",st);
}
//if(!athread_halt())
// printf("athread halt not OK!\n");
printf("now calculating errors.\n");
double sum = 0, sum_ref = 0;
for( int i = 0; i < count; ++i ) {
#ifdef DEBUG_INFO
printf("%d: input: %lf\n",i,in[i]);
printf("%d: swdnn-relu:%lf ori-relu:%lf\n",i,out[i],out_ref[i]);
printf("%d: swdnn-relu - ori-relu = %lf\n",i,out[i]-out_ref[i]);
#endif
if( fabs(out_ref[i] - out[i]) > 1e-4) {
printf("ERROR at %d: %lf vs %lf\n", i, out_ref[i], out[i]);
printf("\tinput: %lf negative_slope: %lf\n", in[i],negative_slope);
printf("\tlocal_count for id=0: %d\n",count/64 + (0<(count%64)));
printf("\tlocal_start for id=1: %d\n",(count/64)+(1<(count%64)));
#define DEBUG
#ifdef DEBUG
void *param_in = in;
double* in_ptr = &((double*)param_in)[(count/64)+(1<(count%64))];
printf("\t%lf\n",in_ptr[0]);
printf("\tsearching...\n");
for(int j = 0; j<count; ++j ) {
if(fabs(out_ref[j] - out[i]) < 1e-4)
printf("Maybe this one: index=%d, out_ref=%lf, out=%lf\n",j,out_ref[j],out[i]);
break;
}
#endif
printf("************** athread forward failed ****************\n");
free(out_ref);
free(out);
free(in);
return ;
}
sum += out[i];
sum_ref += out_ref[i];
}
free(out_ref);
free(out);
free(in);
printf("sum %lf vs sum_ref %lf athread forward OK!\n", sum, sum_ref);
}
void test_relu_backward() {
printf("Test relu backward...\n");
int count;
double negative_slope;
count = 2*1024*1024;
negative_slope = rand()/(double)RAND_MAX - 0.5;
int in_size = count;
int out_size = count;
double* in = (double*)malloc(sizeof(double)*in_size);
double* in_diff = (double*)malloc(sizeof(double)*in_size);
double* in_diff_ref = (double*)malloc(sizeof(double)*in_size);
double* out_diff = (double*)malloc(sizeof(double)*out_size);
for( int i = 0; i < in_size; ++i )
in[i] = rand()/(double)RAND_MAX - 0.5;
for( int i = 0; i < out_size; ++i )
out_diff[i] = rand()/(double)RAND_MAX - 0.5;
printf("now calculating swdnn value...\n");
begin_timer("sw_relu_backward_impl_d");
sw_relu_backward_impl_d(
in,
out_diff,
in_diff,
negative_slope,
count);
stop_timer();
printf("now calculating reference value...\n");
begin_timer("test_relu_backward_impl_d");
test_relu_backward_impl_d(
in,
out_diff,
in_diff_ref,
negative_slope,
count);
stop_timer();
for( int i = 0; i < in_size; ++i )
if(fabs(in_diff[i] - in_diff_ref[i]) > 1e-4) {
printf("ERROR at %d: in_diff %lf vs ref %lf\n", i, in_diff[i], in_diff_ref[i]);
printf("\tinput: %lf out_diff: %lf negative_slope: %lf\n",in[i],out_diff[i],negative_slope);
printf("************** athread backward failed ****************\n");
free(in_diff_ref);
free(out_diff);
free(in);
free(in_diff);
return ;
}
printf("backward test OK!");
free(in);
free(in_diff);
free(in_diff_ref);
free(out_diff);
}
|
bc281d47f2089d4cbb74ba5f34a5b0633e5d68e4
|
8d93dc78155c613a2b62796c31cfa7ed61efea43
|
/fdbserver/RestoreMaster.actor.cpp
|
f7dfc13b565398ba28e9d0cc825db439721ad4f0
|
[
"Apache-2.0"
] |
permissive
|
satherton/foundationdb
|
5a8120b625878a4f780e8db9f4949e51898fb938
|
f3ed3f462be308f825242ea04d83125b03e27deb
|
refs/heads/master
| 2021-06-24T10:41:04.019669
| 2019-12-03T17:44:15
| 2019-12-03T17:44:15
| 130,928,527
| 4
| 1
| null | 2018-04-25T00:24:40
| 2018-04-25T00:24:39
| null |
UTF-8
|
C++
| false
| false
| 21,871
|
cpp
|
RestoreMaster.actor.cpp
|
/*
* RestoreMaster.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This file implements the functions for RestoreMaster role
#include "fdbclient/NativeAPI.actor.h"
#include "fdbclient/SystemData.h"
#include "fdbclient/BackupAgent.actor.h"
#include "fdbclient/ManagementAPI.actor.h"
#include "fdbclient/MutationList.h"
#include "fdbclient/BackupContainer.h"
#include "fdbserver/RestoreUtil.h"
#include "fdbserver/RestoreCommon.actor.h"
#include "fdbserver/RestoreRoleCommon.actor.h"
#include "fdbserver/RestoreMaster.actor.h"
#include "fdbserver/RestoreApplier.actor.h"
#include "fdbserver/RestoreLoader.actor.h"
#include "flow/actorcompiler.h" // This must be the last #include.
ACTOR static Future<Void> clearDB(Database cx);
ACTOR static Future<Void> collectBackupFiles(Reference<IBackupContainer> bc, std::vector<RestoreFileFR>* files,
Database cx, RestoreRequest request);
ACTOR static Future<Version> processRestoreRequest(Reference<RestoreMasterData> self, Database cx, RestoreRequest request);
ACTOR static Future<Void> startProcessRestoreRequests(Reference<RestoreMasterData> self, Database cx);
ACTOR static Future<Void> distributeWorkloadPerVersionBatch(Reference<RestoreMasterData> self, Database cx,
RestoreRequest request, VersionBatch versionBatch);
ACTOR static Future<Void> recruitRestoreRoles(Reference<RestoreWorkerData> masterWorker,
Reference<RestoreMasterData> masterData);
ACTOR static Future<Void> distributeRestoreSysInfo(Reference<RestoreWorkerData> masterWorker,
Reference<RestoreMasterData> masterData);
ACTOR static Future<Standalone<VectorRef<RestoreRequest>>> collectRestoreRequests(Database cx);
ACTOR static Future<Void> initializeVersionBatch(Reference<RestoreMasterData> self);
ACTOR static Future<Void> notifyApplierToApplyMutations(Reference<RestoreMasterData> self);
ACTOR static Future<Void> notifyRestoreCompleted(Reference<RestoreMasterData> self, Database cx);
void dummySampleWorkload(Reference<RestoreMasterData> self);
ACTOR Future<Void> startRestoreMaster(Reference<RestoreWorkerData> masterWorker, Database cx) {
state Reference<RestoreMasterData> self = Reference<RestoreMasterData>(new RestoreMasterData());
try {
// recruitRestoreRoles must come after masterWorker has finished collectWorkerInterface
wait(recruitRestoreRoles(masterWorker, self));
wait(distributeRestoreSysInfo(masterWorker, self));
wait(startProcessRestoreRequests(self, cx));
} catch (Error& e) {
TraceEvent(SevError, "FastRestore")
.detail("StartRestoreMaster", "Unexpectedly unhandled error")
.detail("Error", e.what())
.detail("ErrorCode", e.code());
}
return Void();
}
// RestoreWorker that has restore master role: Recruite a role for each worker
ACTOR Future<Void> recruitRestoreRoles(Reference<RestoreWorkerData> masterWorker,
Reference<RestoreMasterData> masterData) {
TraceEvent("FastRestore")
.detail("RecruitRestoreRoles", masterWorker->workerInterfaces.size())
.detail("NumLoaders", opConfig.num_loaders)
.detail("NumAppliers", opConfig.num_appliers);
ASSERT(masterData->loadersInterf.empty() && masterData->appliersInterf.empty());
ASSERT(masterData.isValid());
ASSERT(opConfig.num_loaders > 0 && opConfig.num_appliers > 0);
// We assign 1 role per worker for now
ASSERT(opConfig.num_loaders + opConfig.num_appliers <= masterWorker->workerInterfaces.size());
// Assign a role to each worker
state int nodeIndex = 0;
state RestoreRole role;
std::map<UID, RestoreRecruitRoleRequest> requests;
for (auto& workerInterf : masterWorker->workerInterfaces) {
if (nodeIndex >= 0 && nodeIndex < opConfig.num_appliers) {
// [0, numApplier) are appliers
role = RestoreRole::Applier;
} else if (nodeIndex >= opConfig.num_appliers && nodeIndex < opConfig.num_loaders + opConfig.num_appliers) {
// [numApplier, numApplier + numLoader) are loaders
role = RestoreRole::Loader;
} else {
break;
}
TraceEvent("FastRestore")
.detail("Role", getRoleStr(role))
.detail("NodeIndex", nodeIndex)
.detail("WorkerNode", workerInterf.first);
requests[workerInterf.first] = RestoreRecruitRoleRequest(role, nodeIndex);
nodeIndex++;
}
state std::vector<RestoreRecruitRoleReply> replies;
wait(getBatchReplies(&RestoreWorkerInterface::recruitRole, masterWorker->workerInterfaces, requests, &replies));
for (auto& reply : replies) {
if (reply.role == RestoreRole::Applier) {
ASSERT_WE_THINK(reply.applier.present());
masterData->appliersInterf[reply.applier.get().id()] = reply.applier.get();
} else if (reply.role == RestoreRole::Loader) {
ASSERT_WE_THINK(reply.loader.present());
masterData->loadersInterf[reply.loader.get().id()] = reply.loader.get();
} else {
TraceEvent(SevError, "FastRestore").detail("RecruitRestoreRoles_InvalidRole", reply.role);
}
}
TraceEvent("FastRestore").detail("RecruitRestoreRolesDone", masterWorker->workerInterfaces.size());
return Void();
}
ACTOR Future<Void> distributeRestoreSysInfo(Reference<RestoreWorkerData> masterWorker,
Reference<RestoreMasterData> masterData) {
ASSERT(masterData.isValid());
ASSERT(!masterData->loadersInterf.empty());
RestoreSysInfo sysInfo(masterData->appliersInterf);
std::vector<std::pair<UID, RestoreSysInfoRequest>> requests;
for (auto& loader : masterData->loadersInterf) {
requests.push_back(std::make_pair(loader.first, RestoreSysInfoRequest(sysInfo)));
}
TraceEvent("FastRestore").detail("DistributeRestoreSysInfoToLoaders", masterData->loadersInterf.size());
wait(sendBatchRequests(&RestoreLoaderInterface::updateRestoreSysInfo, masterData->loadersInterf, requests));
return Void();
}
// The server of the restore master. It drives the restore progress with the following steps:
// 1) Lock database and clear the normal keyspace
// 2) Wait on each RestoreRequest, which is sent by RestoreAgent operated by DBA
// 3) Process each restore request in actor processRestoreRequest;
// 3.1) Sample workload to decide the key range for each applier, which is implemented as a dummy sampling;
// 3.2) Send each loader the map of key-range to applier interface;
// 3.3) Construct requests of which file should be loaded by which loader, and send requests to loaders;
// 4) After process all restore requests, finish restore by cleaning up the restore related system key
// and ask all restore roles to quit.
ACTOR Future<Void> startProcessRestoreRequests(Reference<RestoreMasterData> self, Database cx) {
state UID randomUID = deterministicRandom()->randomUniqueID();
TraceEvent("FastRestore").detail("RestoreMaster", "WaitOnRestoreRequests");
state Standalone<VectorRef<RestoreRequest>> restoreRequests = wait(collectRestoreRequests(cx));
// lock DB for restore
state int numTries = 0;
loop {
try {
wait(lockDatabase(cx, randomUID));
state Reference<ReadYourWritesTransaction> tr =
Reference<ReadYourWritesTransaction>(new ReadYourWritesTransaction(cx));
tr->reset();
tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr->setOption(FDBTransactionOptions::LOCK_AWARE);
wait(checkDatabaseLock(tr, randomUID));
TraceEvent("FastRestore").detail("DBIsLocked", randomUID);
break;
} catch (Error& e) {
TraceEvent("FastRestore").detail("CheckLockError", e.what());
TraceEvent(numTries > 50 ? SevError : SevWarnAlways, "FastRestoreMayFail")
.detail("Reason", "DB is not properly locked")
.detail("ExpectedLockID", randomUID);
numTries++;
wait(delay(5.0));
}
}
wait(clearDB(cx));
// Step: Perform the restore requests
state int restoreIndex = 0;
try {
for (restoreIndex = 0; restoreIndex < restoreRequests.size(); restoreIndex++) {
RestoreRequest& request = restoreRequests[restoreIndex];
TraceEvent("FastRestore").detail("RestoreRequestInfo", request.toString());
wait(success(processRestoreRequest(self, cx, request)));
}
} catch (Error& e) {
TraceEvent(SevError, "FastRestoreFailed").detail("RestoreRequest", restoreRequests[restoreIndex].toString());
}
// Step: Notify all restore requests have been handled by cleaning up the restore keys
wait(notifyRestoreCompleted(self, cx));
try {
wait(unlockDatabase(cx, randomUID));
} catch (Error& e) {
TraceEvent(SevError, "UnlockDBFailed").detail("UID", randomUID.toString());
ASSERT_WE_THINK(false); // This unlockDatabase should always succeed, we think.
}
TraceEvent("FastRestore").detail("RestoreMasterComplete", self->id());
return Void();
}
ACTOR static Future<Version> processRestoreRequest(Reference<RestoreMasterData> self, Database cx,
RestoreRequest request) {
state std::vector<RestoreFileFR> files;
state std::vector<RestoreFileFR> allFiles;
self->initBackupContainer(request.url);
// Get all backup files' description and save them to files
wait(collectBackupFiles(self->bc, &files, cx, request));
self->buildVersionBatches(files, &self->versionBatches); // Divide files into version batches
state std::map<Version, VersionBatch>::iterator versionBatch;
for (versionBatch = self->versionBatches.begin(); versionBatch != self->versionBatches.end(); versionBatch++) {
wait(initializeVersionBatch(self));
wait(distributeWorkloadPerVersionBatch(self, cx, request, versionBatch->second));
self->batchIndex++;
}
TraceEvent("FastRestore").detail("RestoreToVersion", request.targetVersion);
return request.targetVersion;
}
ACTOR static Future<Void> loadFilesOnLoaders(Reference<RestoreMasterData> self, Database cx, RestoreRequest request,
VersionBatch versionBatch, bool isRangeFile) {
TraceEvent("FastRestore")
.detail("FileTypeLoadedInVersionBatch", isRangeFile)
.detail("BeginVersion", versionBatch.beginVersion)
.detail("EndVersion", versionBatch.endVersion);
Key mutationLogPrefix;
std::vector<RestoreFileFR>* files;
if (isRangeFile) {
files = &versionBatch.rangeFiles;
} else {
files = &versionBatch.logFiles;
Reference<RestoreConfigFR> restoreConfig(new RestoreConfigFR(request.randomUid));
mutationLogPrefix = restoreConfig->mutationLogPrefix();
}
// sort files in increasing order of beginVersion
std::sort(files->begin(), files->end());
std::vector<std::pair<UID, RestoreLoadFileRequest>> requests;
std::map<UID, RestoreLoaderInterface>::iterator loader = self->loadersInterf.begin();
// TODO: Remove files that are empty before proceed
// ASSERT(files->size() > 0); // files should not be empty
Version prevVersion = 0;
for (auto& file : *files) {
// NOTE: Cannot skip empty files because empty files, e.g., log file, still need to generate dummy mutation to
// drive applier's NotifiedVersion.
if (loader == self->loadersInterf.end()) {
loader = self->loadersInterf.begin();
}
// Prepare loading
LoadingParam param;
param.prevVersion = 0; // Each file's NotifiedVersion starts from 0
param.endVersion = file.isRange ? file.version : file.endVersion;
param.fileIndex = file.fileIndex;
param.url = request.url;
param.isRangeFile = file.isRange;
param.version = file.version;
param.filename = file.fileName;
param.offset = 0;
param.length = file.fileSize; // We load file by file, instead of data block by data block for now
param.blockSize = file.blockSize;
param.restoreRange = request.range;
param.addPrefix = request.addPrefix;
param.removePrefix = request.removePrefix;
param.mutationLogPrefix = mutationLogPrefix;
prevVersion = param.endVersion;
// Log file to be loaded
TraceEvent("FastRestore").detail("LoadParam", param.toString()).detail("LoaderID", loader->first.toString());
ASSERT_WE_THINK(param.length >= 0); // we may load an empty file
ASSERT_WE_THINK(param.offset >= 0);
ASSERT_WE_THINK(param.offset <= file.fileSize);
ASSERT_WE_THINK(param.prevVersion <= param.endVersion);
requests.push_back(std::make_pair(loader->first, RestoreLoadFileRequest(param)));
loader++;
}
// Wait on the batch of load files or log files
wait(sendBatchRequests(&RestoreLoaderInterface::loadFile, self->loadersInterf, requests));
return Void();
}
// Ask loaders to send its buffered mutations to appliers
ACTOR static Future<Void> sendMutationsFromLoaders(Reference<RestoreMasterData> self, bool useRangeFile) {
TraceEvent("FastRestore")
.detail("SendMutationsFromLoaders", self->batchIndex)
.detail("UseRangeFiles", useRangeFile);
std::vector<std::pair<UID, RestoreSendMutationsToAppliersRequest>> requests;
for (auto& loader : self->loadersInterf) {
requests.emplace_back(loader.first, RestoreSendMutationsToAppliersRequest(self->rangeToApplier, useRangeFile));
}
wait(sendBatchRequests(&RestoreLoaderInterface::sendMutations, self->loadersInterf, requests));
return Void();
}
ACTOR static Future<Void> distributeWorkloadPerVersionBatch(Reference<RestoreMasterData> self, Database cx,
RestoreRequest request, VersionBatch versionBatch) {
ASSERT(!versionBatch.isEmpty());
ASSERT(self->loadersInterf.size() > 0);
ASSERT(self->appliersInterf.size() > 0);
dummySampleWorkload(self); // TODO: Delete
// Parse log files and send mutations to appliers before we parse range files
// TODO: Allow loading both range and log files in parallel
wait(loadFilesOnLoaders(self, cx, request, versionBatch, false));
wait(loadFilesOnLoaders(self, cx, request, versionBatch, true));
// Loaders should ensure log files' mutations sent to appliers before range files' mutations
// TODO: Let applier buffer mutations from log and range files differently so that loaders can send mutations in
// parallel
wait(sendMutationsFromLoaders(self, false));
wait(sendMutationsFromLoaders(self, true));
wait(notifyApplierToApplyMutations(self));
return Void();
}
// Placehold for sample workload
// Produce the key-range for each applier
void dummySampleWorkload(Reference<RestoreMasterData> self) {
int numAppliers = self->appliersInterf.size();
std::vector<Key> keyrangeSplitter;
// We will use the splitter at [1, numAppliers - 1]. The first splitter is normalKeys.begin
int i;
for (i = 0; i < numAppliers; i++) {
keyrangeSplitter.push_back(Key(deterministicRandom()->randomUniqueID().toString()));
}
std::sort(keyrangeSplitter.begin(), keyrangeSplitter.end());
i = 0;
self->rangeToApplier.clear();
for (auto& applier : self->appliersInterf) {
if (i == 0) {
self->rangeToApplier[normalKeys.begin] = applier.first;
} else {
self->rangeToApplier[keyrangeSplitter[i]] = applier.first;
}
i++;
}
self->logApplierKeyRange();
}
ACTOR static Future<Standalone<VectorRef<RestoreRequest>>> collectRestoreRequests(Database cx) {
state Standalone<VectorRef<RestoreRequest>> restoreRequests;
state Future<Void> watch4RestoreRequest;
// wait for the restoreRequestTriggerKey to be set by the client/test workload
state ReadYourWritesTransaction tr(cx);
loop {
try {
tr.reset();
tr.setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr.setOption(FDBTransactionOptions::LOCK_AWARE);
Optional<Value> numRequests = wait(tr.get(restoreRequestTriggerKey));
if (!numRequests.present()) {
watch4RestoreRequest = tr.watch(restoreRequestTriggerKey);
wait(tr.commit());
wait(watch4RestoreRequest);
} else {
Standalone<RangeResultRef> restoreRequestValues =
wait(tr.getRange(restoreRequestKeys, CLIENT_KNOBS->TOO_MANY));
ASSERT(!restoreRequestValues.more);
if (restoreRequestValues.size()) {
for (auto& it : restoreRequestValues) {
restoreRequests.push_back(restoreRequests.arena(), decodeRestoreRequestValue(it.value));
TraceEvent("FastRestore").detail("RestoreRequest", restoreRequests.back().toString());
}
}
break;
}
} catch (Error& e) {
wait(tr.onError(e));
}
}
return restoreRequests;
}
// Collect the backup files' description into output_files by reading the backupContainer bc.
ACTOR static Future<Void> collectBackupFiles(Reference<IBackupContainer> bc, std::vector<RestoreFileFR>* files,
Database cx, RestoreRequest request) {
state BackupDescription desc = wait(bc->describeBackup());
// Convert version to real time for operators to read the BackupDescription desc.
wait(desc.resolveVersionTimes(cx));
TraceEvent("FastRestore").detail("BackupDesc", desc.toString());
if (request.targetVersion == invalidVersion && desc.maxRestorableVersion.present())
request.targetVersion = desc.maxRestorableVersion.get();
Optional<RestorableFileSet> restorable = wait(bc->getRestoreSet(request.targetVersion));
if (!restorable.present()) {
TraceEvent(SevWarn, "FastRestore").detail("NotRestorable", request.targetVersion);
throw restore_missing_data();
}
if (!files->empty()) {
TraceEvent(SevError, "FastRestore").detail("ClearOldFiles", files->size());
files->clear();
}
for (const RangeFile& f : restorable.get().ranges) {
TraceEvent("FastRestore").detail("RangeFile", f.toString());
RestoreFileFR file(f.version, f.fileName, true, f.blockSize, f.fileSize, f.version, f.version);
TraceEvent("FastRestore").detail("RangeFileFR", file.toString());
files->push_back(file);
}
for (const LogFile& f : restorable.get().logs) {
TraceEvent("FastRestore").detail("LogFile", f.toString());
RestoreFileFR file(f.beginVersion, f.fileName, false, f.blockSize, f.fileSize, f.endVersion, f.beginVersion);
TraceEvent("FastRestore").detail("LogFileFR", file.toString());
files->push_back(file);
}
return Void();
}
ACTOR static Future<Void> clearDB(Database cx) {
wait(runRYWTransaction(cx, [](Reference<ReadYourWritesTransaction> tr) -> Future<Void> {
tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr->setOption(FDBTransactionOptions::LOCK_AWARE);
tr->clear(normalKeys);
return Void();
}));
return Void();
}
ACTOR static Future<Void> initializeVersionBatch(Reference<RestoreMasterData> self) {
std::vector<std::pair<UID, RestoreVersionBatchRequest>> requestsToAppliers;
for (auto& applier : self->appliersInterf) {
requestsToAppliers.push_back(std::make_pair(applier.first, RestoreVersionBatchRequest(self->batchIndex)));
}
wait(sendBatchRequests(&RestoreApplierInterface::initVersionBatch, self->appliersInterf, requestsToAppliers));
std::vector<std::pair<UID, RestoreVersionBatchRequest>> requestsToLoaders;
for (auto& loader : self->loadersInterf) {
requestsToLoaders.push_back(std::make_pair(loader.first, RestoreVersionBatchRequest(self->batchIndex)));
}
wait(sendBatchRequests(&RestoreLoaderInterface::initVersionBatch, self->loadersInterf, requestsToLoaders));
return Void();
}
// Ask each applier to apply its received mutations to DB
ACTOR static Future<Void> notifyApplierToApplyMutations(Reference<RestoreMasterData> self) {
// Prepare the applyToDB requests
std::vector<std::pair<UID, RestoreVersionBatchRequest>> requests;
for (auto& applier : self->appliersInterf) {
requests.push_back(std::make_pair(applier.first, RestoreVersionBatchRequest(self->batchIndex)));
}
wait(sendBatchRequests(&RestoreApplierInterface::applyToDB, self->appliersInterf, requests));
TraceEvent("FastRestore").detail("Master", self->id()).detail("ApplyToDB", "Completed");
return Void();
}
// Ask all loaders and appliers to perform housecleaning at the end of restore and
// Register the restoreRequestDoneKey to signal the end of restore
ACTOR static Future<Void> notifyRestoreCompleted(Reference<RestoreMasterData> self, Database cx) {
std::vector<std::pair<UID, RestoreVersionBatchRequest>> requests;
for (auto& loader : self->loadersInterf) {
requests.push_back(std::make_pair(loader.first, RestoreVersionBatchRequest(self->batchIndex)));
}
// A loader exits immediately after it receives the request. Master may not receive acks.
Future<Void> endLoaders = sendBatchRequests(&RestoreLoaderInterface::finishRestore, self->loadersInterf, requests);
requests.clear();
for (auto& applier : self->appliersInterf) {
requests.push_back(std::make_pair(applier.first, RestoreVersionBatchRequest(self->batchIndex)));
}
Future<Void> endApplier =
sendBatchRequests(&RestoreApplierInterface::finishRestore, self->appliersInterf, requests);
wait(delay(5.0)); // Give some time for loaders and appliers to exit
// Notify tester that the restore has finished
state Reference<ReadYourWritesTransaction> tr(new ReadYourWritesTransaction(cx));
loop {
try {
tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr->setOption(FDBTransactionOptions::LOCK_AWARE);
tr->clear(restoreRequestTriggerKey);
tr->clear(restoreRequestKeys);
Version readVersion = wait(tr->getReadVersion());
tr->set(restoreRequestDoneKey, restoreRequestDoneVersionValue(readVersion));
wait(tr->commit());
break;
} catch (Error& e) {
wait(tr->onError(e));
}
}
TraceEvent("FastRestore").detail("RestoreMaster", "RestoreCompleted");
return Void();
}
|
152294de796f7248357d5387bd91dc270dd9e4e5
|
d21c5721fe062154481d6b5a0cad1b27923646c9
|
/Ventus/tile/tile.h
|
fb4760cdb3a93b19c219bc64220a6d434375fa8c
|
[] |
no_license
|
Shawn-Gallea123/Ventus
|
570a94938356e321c079f16e0a558691fef9b879
|
7152c81d8ad4457cb56c3be90a60f57afc581ecf
|
refs/heads/master
| 2022-07-24T05:18:20.703778
| 2020-05-23T18:35:54
| 2020-05-23T18:35:54
| 266,242,770
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 501
|
h
|
tile.h
|
#pragma once
#include <glm/glm.hpp>
#include <string>
#include <vector>
class Tile {
public:
explicit Tile(const unsigned int shader_program);
virtual void Draw();
protected:
unsigned int LoadTexture(const std::string& texture_path);
glm::mat4 model_matrix_;
glm::mat4 view_matrix_;
const unsigned int shader_program_;
std::vector<unsigned int> textures_;
private:
void Init();
virtual unsigned int GetActiveTexture() = 0;
unsigned int vao_;
unsigned int vbo_;
unsigned int ebo_;
};
|
87d958398e3923d1fd4894b8c0efc20c6acc5a00
|
f5788f77442b55c9e7bb40a1a6849f3df2d4600b
|
/10_Skybox/freeTypeFont.h
|
079e18c880cdc980a60eada0fe153d1395956ca8
|
[] |
no_license
|
computeristgeek/OpenGL3.3-Tutorials-MichalBB-based-
|
fa46de30fa5e4ccada9b12deaccacf5f66caa1ac
|
84061fc34c0b85bf98892f7161554c7147c274a4
|
refs/heads/master
| 2016-08-11T15:36:30.297837
| 2015-12-19T22:18:31
| 2015-12-19T22:18:31
| 47,404,326
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,063
|
h
|
freeTypeFont.h
|
#pragma once
#include <ft2build.h>
#include FT_FREETYPE_H
#include "texture.h"
#include "shaders.h"
#include "vertexBufferObject.h"
/********************************
Class: CFreeTypeFont
Purpose: Wraps FreeType fonts and
their usage with OpenGL.
********************************/
class CFreeTypeFont
{
public:
GLboolean loadFont(string sFile, GLint iPXSize);
GLboolean loadSystemFont(string sName, GLint iPXSize);
GLint getTextWidth(string sText, GLint iPXSize);
GLvoid print(string sText, GLint x, GLint y, GLint iPXSize = -1);
GLvoid releaseFont();
GLvoid setShaderProgram(CShaderProgram* a_shShaderProgram);
CFreeTypeFont();
private:
GLvoid createChar(GLint iIndex);
CTexture tCharTextures[256];
GLint iAdvX[256], iAdvY[256];
GLint iBearingX[256], iBearingY[256];
GLint iCharWidth[256], iCharHeight[256];
GLint iLoadedPixelSize, iNewLine;
GLboolean bLoaded;
GLuint uiVAO;
CVertexBufferObject vboData;
FT_Library ftLib;
FT_Face ftFace;
CShaderProgram* shShaderProgram;
};
|
7cd14657ae614440c9977fc33aac336214c1a693
|
2b0b79da5c07eb0a0bd127d3834e538b7860b8b8
|
/common/tree/binary_tree/test_btree.cpp
|
56220468ad339e64590426fc640d0b66b74abf8c
|
[] |
no_license
|
kevinlighter/code
|
723356c6308669398b5beb5122a450f5107e6d26
|
1134a62984840ecd1998cb1f1f0b7b46a74fdf0f
|
refs/heads/master
| 2022-02-20T05:53:12.448857
| 2022-02-15T21:39:10
| 2022-02-15T21:39:10
| 140,362,184
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 690
|
cpp
|
test_btree.cpp
|
#include "btree.h"
#include <iostream>
using namespace common::tree::BTree;
template <typename T>
NodeT<T>* test_btree_constructor()
{
Noded node1(5);
Nodes node2("abc");
return &node2;
}
template <typename T>
void test_btree_print(std::shared_ptr<NodeT<T>> nodePtr)
{
NodeT<T>::print(nodePtr);
}
int main() {
Noded node1(5);
Nodes node2("abc");
node1.insert(10);
node1.insert(18);
node1.insert(7);
node1.insert(-1);
node1.insert(-10);
node1.insert(6);
node1.insert(4);
node1.insert(2);
node1.insert(9);
node1.insert(13);
node1.insert(3);
test_btree_print<double>(std::make_shared<Noded>(node1));
//print<double>(std::make_shared<Noded>(node1));
return 0;
}
|
f96e78f77f1348c5df78f57cf4a3368f402c78ec
|
14527c700343ec8c91f7201e4fbe16b36c20492b
|
/CANTON.cpp
|
fd1ceb5c0e2baa5f90868241491b207fffefae16
|
[] |
no_license
|
Gopinath-ceg/SPOJ
|
5ea24c29905474d361b51ae89402f476907225a1
|
60737853d082820479437edcc4299aa3f8cabbae
|
refs/heads/master
| 2016-09-06T12:38:36.698299
| 2013-07-23T17:04:42
| 2013-07-23T17:04:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 344
|
cpp
|
CANTON.cpp
|
#include<iostream>
using namespace std;
int main()
{
int t,i,x,y;
long long unsigned int n,a,b;
cin>>t;
while(t--)
{
cin>>n;
a=1;
for(i=1;(i*(i+1))/2<n;i++);
i--;
a=(i*(i+1))/2;
b=n-a;
if(i%2==1)
{
x=b;
y=i-b+2;
}
else
{
y=b;
x=i-b+2;
}
cout<<"TERM "<<n<<" IS "<<x<<'/'<<y<<endl;
}
return 0;
}
|
b14597e9ec11d14b80f34a5a83e3e07e2a5cc5a3
|
aabe8cf0784bcf850c353e6ee5012285a7a4091a
|
/Classes/IngameObject/Skill/PassiveSkill.cpp
|
cd2390122159331e025e62391234ff7c90ae4ea0
|
[] |
no_license
|
ImaginysLight/CodingTD
|
fda402e8c08e9806ed0a31604ba465c94967226e
|
d6d773f316054011f81df680993c17d4d08579ee
|
refs/heads/master
| 2020-05-16T18:18:13.226060
| 2019-09-07T05:47:58
| 2019-09-07T05:47:58
| 183,215,615
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,904
|
cpp
|
PassiveSkill.cpp
|
#include"PassiveSkill.h"
float PassiveSkill::Bonus_Attack = 0.17;
float PassiveSkill::Bonus_Defense = 0.05;
float PassiveSkill::Bonus_Health = 0.05;
float PassiveSkill::Bonus_Regeneration = 2;
float PassiveSkill::Bonus_AttackSpeed = 8;
int PassiveSkill::fireLevel = 0;
int PassiveSkill::iceLevel = 0;
int PassiveSkill::natureLevel = 0;
void PassiveSkill::IcySoul(BaseUnitClass*& unit)
{
unit->baseDefense += (unit->baseDefense*PassiveSkill::Bonus_Defense);
unit->ReprocessAllStatus("Defense");
unit->currentHealth += (unit->maxHealth*PassiveSkill::Bonus_Health);
unit->maxHealth += (unit->maxHealth*PassiveSkill::Bonus_Health);
}
void PassiveSkill::FierySprit(BaseUnitClass*& unit)
{
unit->baseAttack += (unit->baseAttack*PassiveSkill::Bonus_Attack);
unit->ReprocessAllStatus("Attack");
}
void PassiveSkill::PureHeart(BaseUnitClass*& unit)
{
unit->baseRegeneration += PassiveSkill::Bonus_Regeneration;
unit->ReprocessAllStatus("Regeneration");
unit->baseAttackSpeed += PassiveSkill::Bonus_AttackSpeed;
unit->ReprocessAllStatus("AttackSpeed");
}
void PassiveSkill::ApplyPassive(int unitId, string elementName)
{
auto unit = BaseUnitClass::GetUnitById(unitId);
if (unit->isAlive && unit->action != "Die" && unit->description != "Kingdom") {
if (elementName == "Fire") PassiveSkill::FierySprit(unit);
else if (elementName == "Ice") PassiveSkill::IcySoul(unit);
else if (elementName == "Nature") PassiveSkill::PureHeart(unit);
}
}
void PassiveSkill::Improve(string elementName)
{
if (elementName == "Fire") {
PassiveSkill::Bonus_Attack += 0.008;
PassiveSkill::fireLevel++;
}
else if (elementName == "Ice") {
PassiveSkill::Bonus_Defense += 0.005;
PassiveSkill::Bonus_Health += 0.005;
PassiveSkill::iceLevel++;
}
else if (elementName == "Nature") {
PassiveSkill::Bonus_Regeneration += 0.2;
PassiveSkill::Bonus_AttackSpeed += 0.4;
PassiveSkill::natureLevel++;
}
}
|
5732d368c1cd913d1d6372e24d88cdbc8aab2070
|
ca5481ff0cae3a207e8651867e7dbd92699db511
|
/UnrealCourse/Section_02/main.cpp
|
21ebd6167b488dc8bb1db39578e6f7bcec8054ea
|
[] |
no_license
|
kamiranoff/cplusplus
|
0d6523295505b21835c541e9ef977fff7054d2be
|
c88caf0bf4eaa55854b77bc883b95132db9ea512
|
refs/heads/master
| 2021-01-10T23:00:28.452900
| 2016-11-01T13:32:58
| 2016-11-01T13:32:58
| 70,433,862
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,107
|
cpp
|
main.cpp
|
//
// Created by Kevin Amiranoff on 08/10/2016.
// Copyright © 2016 Kevin Amiranoff. All rights reserved.
//
#include <iostream>
#include "FCowBullGame.h"
using FText = std::string; //Unreal immutable string type
using int32 = int; // Unreal integer
// Prototypes.
FBullCowGame BCGame; //instanciate a new game
void PlayGame();
void PrintGameIntro();
void LoopThroughGuesses(int32 limit);
FText GetValidGuessFromPlayer(int32 currentTry);
void PrintBullCowCount(FBullCowCount bullCowCount);
void PrintGameResult();
bool AskToPlayAgain();
// Entry point
int main(int32 argc, const char *argv[]) {
PlayGame();
return 0;
}
void PrintGameIntro() {
int32 HiddenWordLength = BCGame.GetHiddenWordLength();
std::cout << std::endl;
std::cout << "Welcome to Bulls and Cows, a fun word game\n\n";
std::cout << std::endl;
std::cout << " __.----.___\n"
" || || (\\(__)/)-'|| ;--` ||\n"
" _||____________||___`(QQ)'___||______;____||_\n"
" -||------------||----) (----||-----------||-\n"
" _||____________||___(o o)___||______;____||_\n"
" -||------------||----`--'----||-----------||-\n"
" || || `|| ||| || || || \n"
"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\n";
std::cout << "Can you guess the " << HiddenWordLength << " letters isogram I'm thinking of\n";
std::cout << "Bull mean you got the letter right, Cow means right letter wrong place\n";
std::cout << std::endl;
return;
}
void LoopThroughGuesses(int32 limit) {
while (BCGame.IsGameWon() != true && BCGame.GetCurrentTry() <= limit) {
FText Guess = GetValidGuessFromPlayer(BCGame.GetCurrentTry()); // TODO make loop checking valid
FBullCowCount BullCowCount = BCGame.SubmitValidGuess(Guess);
PrintBullCowCount(BullCowCount);
}
}
FText GetValidGuessFromPlayer(int32 currentTry) {
// cin >> Guess;// by default cin stops after whitespace. To get the entire line we need to use getline
EGuessStatus Status = EGuessStatus::Invalid_Status;
FText Guess = "";
do {
std::cout << "Trial n'" << currentTry << " of " << BCGame.GetMaxTries() << ". Enter your guess: ";
std::getline(std::cin, Guess);
Status = BCGame.CheckGuessValidity(Guess);
switch (Status) {
case EGuessStatus::Wrong_Number_Of_Letters:
std::cout << "Please enter a " << BCGame.GetHiddenWordLength() << " letter word.\n";
break;
case EGuessStatus::Not_Isogram:
std::cout << "Please enter a word with no repeating letters (an isogram).\n";
break;
case EGuessStatus::Not_Lowercase:
std::cout << "Your word must be all lowercase.\n";
break;
default:
//assuming Guess is valid
break;
}
} while (Status != EGuessStatus::OK);
return Guess;
}
void PrintBullCowCount(FBullCowCount bullCowCount) {
std::cout << "Bulls = " << bullCowCount.Bulls;
std::cout << " Cows = " << bullCowCount.Cows;
std::cout << std::endl << std::endl;
}
void PrintGameResult() {
if (BCGame.IsGameWon()) {
std::cout << "Well done, victor.\n";
} else {
std::cout << "You did not guess the word, maybe next time.\n";
}
}
bool AskToPlayAgain() {
bool playAgain = false;
FText Response = "";
std::cout << "Do you want to play again with the same word ? [y,n]";
std::getline(std::cin, Response);
char FirstLetter = Response[0];
if (FirstLetter == 'y' || FirstLetter == 'Y') {
playAgain = true;
}
return playAgain;
}
void PlayGame() {
bool bPlayAgain = false;
do {
BCGame.Reset(); // Reset the game to base settings.
int32 MaxTries = BCGame.GetMaxTries();
PrintGameIntro();
LoopThroughGuesses(MaxTries);
PrintGameResult();
bPlayAgain = AskToPlayAgain();
} while (bPlayAgain);
}
|
c2e7dd8db0faf0ac3e337d5e193899677c19d6a5
|
cbb404e9dd041359b4827d2be73b7d6b3486ed2f
|
/flibProject/programs/include/CpuTimer.hpp
|
a95299befb051296b39198dfbcab2d21eea43ddd
|
[] |
no_license
|
tiagofgon/thesis-project
|
20a1febf50dba1f4c325709c33ffbf100b4307f2
|
d9014901782786e0dff73ead1f6503de446a9d72
|
refs/heads/master
| 2020-08-15T04:54:53.420362
| 2019-12-06T22:45:17
| 2019-12-06T22:45:17
| 215,282,718
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,221
|
hpp
|
CpuTimer.hpp
|
// AUTHOR: Victor Alessandrini, 2015
// VATH libray,in book "Shared Memory Application
// Programming"
// *********************************************
// CpuTimer.h
//
// Measurine execution times. Reports wall, user
// (total computation time of all threads) and
// system times in Pthreads. In Windows and C++11,
// only wall times are reported
// ---------------------------------------
#ifndef CPU_TIMER_H
#define CPU_TIMER_H
#include <iostream>
#include <chrono>
class CpuTimer
{
private:
///////
std::chrono::steady_clock::time_point start;
std::chrono::steady_clock::time_point stop;
public:
//////
void Start( )
{ start = std::chrono::steady_clock::now(); }
void Stop( )
{ stop = std::chrono::steady_clock::now(); }
void Report()
{
std::chrono::steady_clock::duration d_start = start.time_since_epoch();
std::chrono::steady_clock::duration d_stop = stop.time_since_epoch();
std::chrono::steady_clock::duration d = d_stop - d_start;
std::chrono::duration<double, std::ratio<1, 1>> dsecs(d);
std::cout << "\n Wall time is " << dsecs.count() << " seconds"
<< std::endl;
}
};
#endif
|
0dbc20eb5af6af3ca49efa572ffb758471ffcc82
|
087cbbd3099ff8fd8d2051c60461a0458333dbac
|
/ICPC/ACM_ICPC pratice Contest 2016 /A.cpp
|
74e732ef050ad7475db1277823aec9bcb89b4311
|
[] |
no_license
|
1998factorial/Codeforces
|
1046ffb2dbee582191fa59e7290c53e902c0af5c
|
f5b8139810e0724828e6ce7e26f3f8228589b00a
|
refs/heads/master
| 2021-07-05T21:34:45.053171
| 2021-04-10T06:21:33
| 2021-04-10T06:21:33
| 228,158,437
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 337
|
cpp
|
A.cpp
|
#include <bits/stdc++.h>
using namespace std;
int a[3],b[3];
int ans[2];
int main(){
for(int i = 0; i < 3; i++)cin >> a[i];
for(int i = 0; i < 3; i++)cin >> b[i];
ans[0] = 0, ans[1] = 0;
for(int i = 0; i < 3; i++){
if(a[i] > b[i])ans[0]++;
else if(a[i] < b[i])ans[1]++;
}
cout << ans[0] << " " << ans[1] << endl;
return 0;
}
|
bdcc3c6553ea5eb91b5034e574b0f97974cedb42
|
2c5261fa9a78f880e79b7918200225955d0cec6d
|
/src/mc_cable_regrasp_primitive1_fsm.h
|
a084b97d98b748f8780e7b53efe9e3b75e899bea
|
[] |
no_license
|
YiliQin/mc_cable_regrasp
|
ecb25e023c13a05acd2158a73f15b6a50ea61e41
|
d13e05a04f9a9ebc49df17e13c0871d471b292cd
|
refs/heads/master
| 2020-03-17T06:17:25.514368
| 2018-07-25T03:05:27
| 2018-07-25T03:12:19
| 133,349,383
| 0
| 0
| null | 2018-08-17T02:42:34
| 2018-05-14T11:17:18
|
C++
|
UTF-8
|
C++
| false
| false
| 1,895
|
h
|
mc_cable_regrasp_primitive1_fsm.h
|
#pragma once
#include <iostream>
#include <Eigen/Core>
#include "mc_cable_regrasp_controller.h"
#include "mc_cable_regrasp_linear_trajectory.h"
namespace mc_control
{
struct Prim1Step
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
public:
Prim1Step(const std::string & name);
virtual ~Prim1Step() {};
Prim1Step * update(MCCableRegraspController & ctl);
protected:
virtual void __init(MCCableRegraspController & ctl) = 0;
virtual Prim1Step * __update(MCCableRegraspController & ctl) = 0;
public:
bool first_call = true;
std::string name;
};
#define CREATE_STEP(NAME, DESC, MEMBERS)\
struct NAME : public Prim1Step\
{\
EIGEN_MAKE_ALIGNED_OPERATOR_NEW\
NAME() : Prim1Step(DESC) {}\
virtual void __init(MCCableRegraspController & ctl) override;\
virtual Prim1Step * __update(MCCableRegraspController & ctl) override;\
MEMBERS\
};
CREATE_STEP(Prim1InitStep, "Primitive1 Initialization Step",
bool stepByStep_ = true;
)
CREATE_STEP(Prim1OpenGripperStep, "Primitive1 Open Gripper Step",
bool stepByStep_ = true;
int cntRun = 0;
)
CREATE_STEP(Prim1SpreadStep, "Primitive1 Spread Step",
bool stepByStep_ = true;
LinearTrajectory * leftHandLinearTraj;
LinearTrajectory * rightHandLinearTraj;
int nr_points_traj = 100;
int cntRun = 0;
)
CREATE_STEP(Prim1CloseGripperStep, "Primitive1 Close Gripper Step",
bool stepByStep_ = true;
int cntRun = 0;
)
CREATE_STEP(Prim1InitPoseStep, "Primitive1 Initial Pose Step",
bool stepByStep_ = true;
int cntRun = 0;
)
CREATE_STEP(Prim1EndStep, "Primitive1 End Step",
)
#undef CREATE_STEP
}
|
c8a3118ebbd9af7773e6935fffb4d713e7e3728e
|
0536fc42ef43a8721b0ee156cad1b18140ebdfea
|
/Algorithms/Distinct Count.cpp
|
9c88f5771cbd2a3c93a3fd72e70c93363d8c16cd
|
[] |
no_license
|
DuyHuynhMinh/Project
|
b056961db818a8e8178572bc3a672c919d817bd2
|
146f8e2b8a6028437a14caad52fd0f48a95d7a79
|
refs/heads/master
| 2022-12-06T03:55:28.283333
| 2021-12-06T02:55:25
| 2021-12-06T02:55:25
| 133,676,929
| 1
| 0
| null | 2022-11-24T09:56:18
| 2018-05-16T14:20:21
|
Java
|
UTF-8
|
C++
| false
| false
| 780
|
cpp
|
Distinct Count.cpp
|
#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
#include <set>
using namespace std;
int main() {
int T, N, X;
cin >> T;
while (T-- > 0) {
cin >> N;
cin >> X;
set<int> s;
for (int i = 0; i < N; ++i) {
int tmp;
cin >> tmp;
s.insert(tmp);
}
int size = s.size();
if (size == X) {
cout << "Good";
}
else if (size<X) {
cout << "Bad";
}
else {
cout<<"Average";
}
}
//system("pause");
return 0;
}
int binary_search(vector<int> v, int value) {
int left = 0;
int right = v.size() - 1;
while (left<=right) {
int mid = left + (right - left) / 2;
if (v[mid] == value) return mid;
if (v[mid] > value) {
right = mid-1;
}
else {
left = mid+1;
}
}
return -1*right;
}
|
73344ca8ad6dc011934d362c739340c86e48c196
|
f7f09782d15ee7bdd14e637bd717dfb8327bc57c
|
/2016Contest/Hefei/D.cpp
|
a9f7e0eec27822798b1063d38a3eca2372f8704d
|
[] |
no_license
|
whywhyzhang/ACM-ICPC-Code
|
14f3f6b0532c18da9694d7f70914a97e0983913f
|
d15bd475774ff104ebfe9504f8ea0acffdb5ddb0
|
refs/heads/master
| 2022-12-09T06:27:14.893967
| 2017-03-09T14:31:49
| 2017-03-09T14:31:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,125
|
cpp
|
D.cpp
|
// ━━━━━━神兽出没━━━━━━
// ┏┓ ┏┓
// ┏┛┻━━━━━━━┛┻┓
// ┃ ┃
// ┃ ━ ┃
// ████━████ ┃
// ┃ ┃
// ┃ ┻ ┃
// ┃ ┃
// ┗━┓ ┏━┛
// ┃ ┃
// ┃ ┃
// ┃ ┗━━━┓
// ┃ ┣┓
// ┃ ┏┛
// ┗┓┓┏━━━━━┳┓┏┛
// ┃┫┫ ┃┫┫
// ┗┻┛ ┗┻┛
//
// ━━━━━━感觉萌萌哒━━━━━━
// Author : WhyWhy
// Created Time : 2016年11月17日 星期四 00时47分57秒
// File Name : D.cpp
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const long long INF=5000000000000000000LL;
long long a1,b1,a2,b2;
long long maxn,minn;
inline long long f1(long long x,long long y) {
return b1*x*y+a1*x*x;
}
inline long long f2(long long x,long long y) {
return (a1*b2+a2*b1)*x*y+a1*a2*x*x+b1*b2*y*y;
}
inline bool read(long long &ret) {
int c=getchar(),sgn;
if(c==-1) return 0;
while(c!='-' && (c<'0' || c>'9')) {
if(c==-1) return 0;
c=getchar();
}
sgn=(c=='-') ? -1 : 1;
ret=(c=='-') ? 0 : c-'0';
while(c=getchar(),c>='0' && c<='9') ret=ret*10+c-'0';
ret*=sgn;
return 1;
}
int main() {
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
long long (*f)(long long,long long);
long long base,t;
long long N,x,y;
//while(~scanf("%I64 %I64 %I64 %I64",&a1,&b1,&a2,&b2)) {
while(read(a1)) {
read(b1); read(a2); read(b2);
if(b1==0) {
swap(a1,a2);
swap(b1,b2);
}
if(b2==0) f=f1,base=abs(b1);
else f=f2,base=abs(a2*b1-a1*b2);
maxn=-INF;
minn=INF;
read(N);
while(N--) {
read(x); read(y);
t=f(x,y);
minn=min(minn,t);
maxn=max(maxn,t);
}
printf("%.0f\n",(maxn-minn+0.0)/base);
}
return 0;
}
|
bd890e2aa15a11dc7f6804c37ebd57e6fd0a64ce
|
bbcda48854d6890ad029d5973e011d4784d248d2
|
/trunk/win/Source/BT_Nameable.cpp
|
1b566aa60d258cd1e802a44b295a758ce14d1bb3
|
[
"Apache-2.0",
"MIT",
"curl",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"Zlib",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"MS-LPL"
] |
permissive
|
dyzmapl/BumpTop
|
9c396f876e6a9ace1099b3b32e45612a388943ff
|
1329ea41411c7368516b942d19add694af3d602f
|
refs/heads/master
| 2020-12-20T22:42:55.100473
| 2020-01-25T21:00:08
| 2020-01-25T21:00:08
| 236,229,087
| 0
| 0
|
Apache-2.0
| 2020-01-25T20:58:59
| 2020-01-25T20:58:58
| null |
UTF-8
|
C++
| false
| false
| 4,448
|
cpp
|
BT_Nameable.cpp
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "BT_Common.h"
#include "BT_AnimationManager.h"
#include "BT_FontManager.h"
#include "BT_Nameable.h"
#include "BT_NxActorWrapper.h"
#include "BT_OverlayComponent.h"
#include "BT_SceneManager.h"
#include "BT_TextManager.h"
#include "BT_Util.h"
Nameable::Nameable(bool registerWithOverlay)
: _useTruncatedText(false)
, _hasExtension(false)
, _overlay(NULL)
, _register(registerWithOverlay)
, _respectIconExtensionVisibility(false)
{
// show the text by default
showText(false);
}
Nameable::~Nameable()
{
// Destroy the actor
scnManager->nameables()->deleteItem(_overlay);
_overlay = NULL;
}
void Nameable::showText(bool skipAnimation)
{
if (!_overlay)
{
// register the Nameable
_overlay = new NameableOverlay(this);
_overlay->setAlpha(1.0f);
if (_register)
{
AbsoluteOverlayLayout * nameables = scnManager->nameables();
nameables->addItem(_overlay);
}
}
else
{
if (!skipAnimation)
{
// animate the 'show'
_overlay->finishAnimation();
_overlay->setAlphaAnim(_overlay->getStyle().getAlpha(), 1.0f, 5);
}
else
{
_overlay->finishAnimation();
_overlay->setAlpha(1.0f);
}
}
}
void Nameable::showTextAnimated(int duration)
{
if (!_overlay)
{
// register the Nameable
_overlay = new NameableOverlay(this);
_overlay->setAlpha(1.0f);
if (_register)
{
AbsoluteOverlayLayout * nameables = scnManager->nameables();
nameables->addItem(_overlay);
}
}
else
{
// animate the 'show'
_overlay->finishAnimation();
_overlay->setAlphaAnim(_overlay->getStyle().getAlpha(), 1.0f, duration);
}
}
void Nameable::hideText(bool skipAnimation /*=false*/)
{
if (_overlay)
{
if (!skipAnimation)
{
// animate the hide
_overlay->finishAnimation();
_overlay->setAlphaAnim(_overlay->getStyle().getAlpha(), 0.0f, 5);
}
else
{
_overlay->finishAnimation();
_overlay->setAlpha(0.0f);
}
}
}
QString Nameable::getText() const
{
if (_useTruncatedText)
return _truncatedText;
return _text;
}
QString Nameable::getFullText() const
{
return _text;
}
void Nameable::setText( QString text )
{
// set the text and truncate the truncated version
_text = _truncatedText = text;
// update the overlay
if (_overlay)
_overlay->updateTextFromNameable();
}
QString Nameable::getTextIcon() const
{
return _iconTextureId;
}
void Nameable::setTextIcon( QString textureId )
{
_iconTextureId = textureId;
}
const Vec3& Nameable::getRelativeTextPosition() const
{
return _relativeTextPosition;
}
void Nameable::setRelativeTextPosition( const Vec3& relPos )
{
_relativeTextPosition = relPos;
}
bool Nameable::hasExtension() const
{
return _hasExtension;
}
void Nameable::hasExtension(bool hasExtension)
{
_hasExtension = hasExtension;
}
bool Nameable::isTextTruncated() const
{
return _useTruncatedText;
}
void Nameable::setTextTruncation( bool truncated )
{
_useTruncatedText = truncated;
// update the overlay
if (_overlay)
_overlay->updateTextFromNameable();
}
bool Nameable::isTextHidden() const
{
return (_overlay == NULL || (_overlay->getStyle().getAlpha() <= 0.0f));
}
NameableOverlay * Nameable::getNameableOverlay() const
{
return _overlay;
}
void Nameable::setRespectIconExtensionVisibility(bool respect)
{
_respectIconExtensionVisibility = respect;
}
void Nameable::onRenderText()
{
const Vec3& pos = getNameableOverlay()->getPosition();
#ifdef DXRENDER
Bounds bounds;
bounds.setInfinite();
getNameableOverlay()->onRender(pos, bounds);
#else
//switchToOrtho();
glPushMatrix();
glTranslatef(pos.x, pos.y, pos.z);
getNameableOverlay()->onRender();
glPopMatrix();
//switchToPerspective();
#endif
}
|
22a70b5f32a031228ff5b434bd00d979e3dda4be
|
3a084d9aaa81dcf7298aa320ee34b70854a3b43c
|
/Ariadne/State.cpp
|
91e23fba113912c06baf75ca55e43b7cc776ba0e
|
[] |
no_license
|
dgist-d-ace/Ariadne
|
b350d0f751ae954da5ec690b2997558fee42b974
|
2e1913e37aaedc8c1d657517383360ab4b650844
|
refs/heads/master
| 2020-06-15T05:38:15.655504
| 2019-09-16T10:53:39
| 2019-09-16T10:53:39
| 195,215,597
| 2
| 1
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,617
|
cpp
|
State.cpp
|
#include "State.hpp"
State::State(float x, float y, float heading, float steer, float speed) {
this->x=x;
this->y=y;
this->heading=heading;
this->steer=steer;
this->speed=speed;
this->gx=x/Grid_ResX;
this->gy=y/Grid_ResY;
this->gtheta=heading/Theta_Res;
}
State::State() {
this->x = -1;
this->y = -1;
this->heading = -1;
this->steer = -1;
this->speed = -1;
}
vector<State> State::getNextStates() { // 현재 나의 위치: x, y, 현재 나의 헤딩: theta
vector<State> next;
State n;
int alphaList[11] = { 0, 15, -15, 10, -10, 20, -20, 5, -5, 25, -25 };
float alpha, beta, r, d = BOT_V * BOT_T; // BOT_L*BOT_CEN_MASS; // alpha: 조향각, beta: d/r_r, r: 회전반경, d: 뒷바퀴에서 무게중심까지 거리
for (alpha = -BOT_M_ALPHA; alpha <= BOT_M_ALPHA + 0.01; alpha += 3) //(int i = 0; i < 11; i++)
{
//alpha = alphaList[i];
beta=d*tan(alpha*PI/180)/BOT_L;
if(abs(beta)<0.001){ // 직진
n.x = x + d * cos(heading * Deg2Rad);
n.y = y + d * sin(heading * Deg2Rad);
n.heading=heading;
n.steer = alpha;
}
else{ // 회전
r=BOT_L/tan(alpha*PI/180);
n.x = x + r * sin(heading * Deg2Rad + beta) - r * sin(heading * Deg2Rad);
n.y = y - r * cos(heading * Deg2Rad + beta) + r * cos(heading * Deg2Rad);
n.heading = heading + beta / Deg2Rad;
n.steer = alpha;
}
n.gx=n.x/Grid_ResX;
n.gy=n.y/Grid_ResY;
n.gtheta=n.heading/Theta_Res;
next.push_back(n);
}
// cout<<"getNextStates() called from "<<x<<","<<y<<","<<heading<<endl;
//for(int i=0;i<3;i++) cout<<next[i].x<<","<<next[i].y<<","<<next[i].heading<<" "; cout<<endl;
return next;
}
|
552847702d7da4a186c15fbf087dbe3d3e37d1c6
|
6d54a7b26d0eb82152a549a6a9dfde656687752c
|
/examples/common/pigweed/system_rpc_server.cc
|
6778499c54ab3c8ef37f252edb0e09fd1877402a
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
project-chip/connectedhomeip
|
81a123d675cf527773f70047d1ed1c43be5ffe6d
|
ea3970a7f11cd227ac55917edaa835a2a9bc4fc8
|
refs/heads/master
| 2023-09-01T11:43:37.546040
| 2023-09-01T08:01:32
| 2023-09-01T08:01:32
| 244,694,174
| 6,409
| 1,789
|
Apache-2.0
| 2023-09-14T20:56:31
| 2020-03-03T17:05:10
|
C++
|
UTF-8
|
C++
| false
| false
| 2,387
|
cc
|
system_rpc_server.cc
|
// Copyright 2020 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// THIS FILE IS DEPRECATED, keep only until examples/pigweed-app depends on
// third_party/pigweed/repo/pw_hdlc/rpc_example/hdlc_rpc_server.cc
#include <cstddef>
#include "pw_hdlc/rpc_channel.h"
#include "pw_hdlc/rpc_packets.h"
#include "pw_log/log.h"
#include "pw_rpc_system_server/rpc_server.h"
#include "pw_stream/sys_io_stream.h"
namespace pw::rpc::system_server {
namespace {
constexpr size_t kMaxTransmissionUnit = 256;
// Used to write HDLC data to pw::sys_io.
stream::SysIoWriter writer;
stream::SysIoReader reader;
// Set up the output channel for the pw_rpc server to use.
hdlc::RpcChannelOutput hdlc_channel_output(writer, pw::hdlc::kDefaultRpcAddress, "HDLC channel");
Channel channels[] = { pw::rpc::Channel::Create<1>(&hdlc_channel_output) };
rpc::Server server(channels);
} // namespace
void Init()
{
// Send log messages to HDLC address 1. This prevents logs from interfering
// with pw_rpc communications.
pw::log_basic::SetOutput([](std::string_view log) { pw::hdlc::WriteUIFrame(1, pw::as_bytes(pw::span(log)), writer); });
}
rpc::Server & Server()
{
return server;
}
Status Start()
{
// Declare a buffer for decoding incoming HDLC frames.
std::array<std::byte, kMaxTransmissionUnit> input_buffer;
hdlc::Decoder decoder(input_buffer);
while (true)
{
std::byte byte;
Status ret_val = pw::sys_io::ReadByte(&byte);
if (!ret_val.ok())
{
return ret_val;
}
if (auto result = decoder.Process(byte); result.ok())
{
hdlc::Frame & frame = result.value();
if (frame.address() == hdlc::kDefaultRpcAddress)
{
server.ProcessPacket(frame.data());
}
}
}
}
} // namespace pw::rpc::system_server
|
5ae8546cf264ca9f23e95a9d1b1136c5f8f55038
|
f046e73335ea889a7269fbdbc3c51fd45ad46fa5
|
/SourceCode/ConstantBuffer.cpp
|
ef357c98d82b2dd273108881fbf049ef6249af86
|
[
"MIT"
] |
permissive
|
Sission/CollisionDetection
|
d408c0a1d2dac35dd3a0548159cf35a7a4bba079
|
cf84fc7639d0e3763ace16a6b399532bc1654067
|
refs/heads/main
| 2022-12-29T11:44:38.016015
| 2020-10-15T03:08:12
| 2020-10-15T03:08:12
| 303,867,265
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,015
|
cpp
|
ConstantBuffer.cpp
|
#include "ConstantBuffer.h"
#include "RenderSystem.h"
#include "DeviceContext.h"
#include <exception>
ConstantBuffer::ConstantBuffer(void * buffer, UINT size_buffer,RenderSystem * system) : m_system(system)
{
D3D11_BUFFER_DESC buff_desc = {};
buff_desc.Usage = D3D11_USAGE_DEFAULT;
buff_desc.ByteWidth = size_buffer;
buff_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
buff_desc.CPUAccessFlags = 0;
buff_desc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA init_data = {};
init_data.pSysMem = buffer;
if (FAILED(m_system->m_d3d_device->CreateBuffer(&buff_desc, &init_data, &m_buffer)))
{
throw std::exception("ConstantBuffer not created successfully");
}
}
void ConstantBuffer::update(DeviceContextPtr context, void * buffer)
{
context->m_device_context->UpdateSubresource(this->m_buffer, NULL, NULL, buffer, NULL, NULL);
}
ID3D11Buffer* ConstantBuffer::getD3DBuffer()
{
return m_buffer;
}
ConstantBuffer::~ConstantBuffer()
{
if (m_buffer)m_buffer->Release();
}
|
8e6b4c09d51b1066f4513ed67a1283da2e87a2d4
|
97a8ee0343c780c11372dc73a8f5c6f4c0257a74
|
/lib/cqwrap/src/util/ResUpdater.cpp
|
22cfca0c859622660cc575daece679e8c5fdcf6c
|
[] |
no_license
|
yovae/go
|
ea73a5e09f88b4aa95bb17de394adcaa32222db6
|
a0b407e1829d3d8105982b35611e1593d32b505c
|
refs/heads/master
| 2021-01-24T21:53:04.929506
| 2014-08-11T08:54:11
| 2014-08-11T08:54:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,643
|
cpp
|
ResUpdater.cpp
|
//
// ResUpdater.cpp
// Chick1024
//
// Created by akira_cn on 14-5-24.
//
//
#include "ResUpdater.h"
#include "cocos2d.h"
#include "cocos-ext.h"
#include "ScriptingCore.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
#include <dirent.h>
#include <sys/stat.h>
#endif
USING_NS_CC;
USING_NS_CC_EXT;
using namespace std;
ResUpdater* ResUpdater::s_updater = NULL;
AssetsManager* ResUpdater::s_manager = NULL;
ResUpdater::ResUpdater(){
}
ResUpdater* ResUpdater::getInstance(){
if (NULL == ResUpdater::s_updater)
{
ResUpdater::s_updater = new ResUpdater();
}
return ResUpdater::s_updater;
}
void ResUpdater::purgeResUpdater(){
if(NULL != ResUpdater::s_updater){
CC_SAFE_DELETE(ResUpdater::s_updater);
}
}
AssetsManager* ResUpdater::getAssetsManager(const char* packageUrl/* =NULL */, const char* versionFileUrl/* =NULL */, const char* storagePath/* =NULL */)
{
if (NULL == ResUpdater::s_manager){
createDownloadedDir(storagePath);
//CCLOG("%s", pathToSave.c_str());
ResUpdater::s_manager = new AssetsManager(packageUrl,
versionFileUrl,
pathToSave.c_str());
ResUpdater::s_manager->setDelegate(this);
ResUpdater::s_manager->setConnectionTimeout(3);
}
return ResUpdater::s_manager;
}
void ResUpdater::onError(AssetsManager::ErrorCode errorCode)
{
ScriptingCore::getInstance()->evalString("cc.onResourcesUpdateFail && cc.onResourcesUpdateFail()",NULL);
}
void ResUpdater::onProgress(int percent)
{
char progress[20];
//snprintf(progress, 20, "downloading %d%%", percent);
ScriptingCore::getInstance()->evalString(
CCString::createWithFormat("cc.onResourcesUpdating && cc.onResourcesUpdating('%d')", percent)
->getCString()
,NULL
);
}
void ResUpdater::onSuccess()
{
//CCLOG("%s", pathToSave.c_str());
//CCFileUtils::sharedFileUtils()->addSearchPath(pathToSave.c_str());
vector<string> searchPaths = CCFileUtils::sharedFileUtils()->getSearchPaths();
searchPaths.insert(searchPaths.begin(), pathToSave.c_str());
CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);
ScriptingCore::getInstance()->evalString("cc.onResourcesUpdateSuccess && cc.onResourcesUpdateSuccess();",NULL);
}
void ResUpdater::createDownloadedDir(const char * storagePath)
{
pathToSave = CCFileUtils::sharedFileUtils()->getWritablePath();
pathToSave += storagePath;
CCLOG("create %s", pathToSave.c_str());
// Create the folder if it doesn't exist
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
DIR *pDir = NULL;
pDir = opendir (pathToSave.c_str());
if (! pDir){
mkdir(pathToSave.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
}
#else
if ((GetFileAttributesA(pathToSave.c_str())) == INVALID_FILE_ATTRIBUTES){
CreateDirectoryA(pathToSave.c_str(), 0);
}
#endif
}
#ifndef KEY_OF_VERSION
#define KEY_OF_VERSION "current-version-code"
#endif
void ResUpdater::reset()
{
// Remove downloaded files
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
string command = "rm -r ";
// Path may include space.
command += "\"" + pathToSave + "\"";
system(command.c_str());
#else
string command = "rd /s /q ";
// Path may include space.
command += "\"" + pathToSave + "\"";
system(command.c_str());
#endif
// Delete recorded version codes.
CCUserDefault::sharedUserDefault()->setStringForKey(KEY_OF_VERSION, "");
//if(NULL != ResUpdater::s_manager){
// ResUpdater::s_manager->deleteVersion();
//}
}
|
f0e178e9ed2b378ab4d039d1965535c0a937a578
|
729f5397fa300c5d50db9ac89c6416a3fcbe65a6
|
/AI/connect4/source/Board.h
|
50b3b53ae52611482f38f08fea4a9b824ee67d09
|
[] |
no_license
|
andrewthenintendrone/AI-Project
|
66c7f43f6c494bf97948851ab929e701352f7c0c
|
b232e2ed7ec21d47fdc8ba616b3bcc520123bebf
|
refs/heads/master
| 2020-12-13T19:57:15.542732
| 2017-08-06T23:56:54
| 2017-08-06T23:56:54
| 95,515,231
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 333
|
h
|
Board.h
|
#pragma once
#include "GridTile.h"
#include "Position.h"
#include "AI.h"
class Board
{
public:
Board();
void playerTurn();
void aiTurn();
void update();
void draw();
private:
Position m_position;
GridTile m_gridTiles[Position::WIDTH][Position::HEIGHT];
sf::Font m_font;
sf::Text m_winText;
};
|
6a52231f77b95997b214b9dbd509479ebedeabf7
|
07ec6b72a5ff9a7c8c42f6f1213a75cb6ef2719a
|
/POJ/1363.cc
|
a2cebcb8111bc9d3acb7841aaf600a1993e6982e
|
[] |
no_license
|
cheuk-fung/Programming-Challenges
|
fbfbf833b19ff1063b0fca4b5d14d1e907264aa1
|
7c055fd2891b7edc865e7da8886d057a93fb41fe
|
refs/heads/master
| 2020-12-24T17:36:21.407367
| 2020-04-26T19:44:42
| 2020-04-27T17:13:09
| 1,443,793
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 939
|
cc
|
1363.cc
|
/*
* SRC: POJ 1363
* PROB: Rails
* ALGO: NULL
* DATE: Jul 19, 2011
* COMP: g++
*
* Created by Leewings Ac
*/
#include <cstdio>
int n, a[1000];
void solve()
{
for (int i = 0; i < n; i++) {
int pre = 0;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[i]) {
if (pre == 0) {
pre = a[j];
continue;
}
if (a[j] < pre) {
pre = a[j];
continue;
}
puts("No");
return ;
}
}
}
puts("Yes");
}
int main()
{
while (scanf("%d", &n) != EOF) {
if (n == 0) break;
scanf("%d", a);
while (a[0] != 0) {
for (int i = 1; i < n; i++)
scanf("%d", a + i);
solve();
scanf("%d", a);
}
putchar(10);
}
return 0;
}
|
dfabf3fe6ccfe09ce28aaa83fb576a58fb43a69e
|
dad517a244d337049f92a76eb1730e9bcdb9de96
|
/c++/codeeval_cpp/src/22.cpp
|
f693ff8873f5de0f0c44c8a4f5f28e4540f1a802
|
[] |
no_license
|
andrewauclair/codeeval
|
87209f1640c98c617ac3cec3999b34679cd26354
|
c101192eac1d4880cb17929715ca2fa43eb2a67d
|
refs/heads/master
| 2021-01-21T12:11:41.107509
| 2016-03-11T03:52:18
| 2016-03-11T03:52:18
| 32,610,536
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 541
|
cpp
|
22.cpp
|
#include <iostream>
#include <fstream>
using namespace std;
#if _EDITOR
#include "22cpp.h"
int C22::fib(int p_nNum)
#else
int fib(int p_nNum)
#endif
{
if (p_nNum < 2)
{
return p_nNum;
}
return fib(p_nNum - 1) + fib(p_nNum - 2);
}
#if _EDITOR
int C22::nRun(int argc, const char * argv[])
#else
int main(int argc, char* argv[])
#endif
{
fstream t_file(argv[1], ios::in);
string t_strInput;
int t_nValue = 0;
while (!t_file.eof())
{
t_file >> t_nValue;
cout << fib(t_nValue) << endl;
}
t_file.close();
return 0;
}
|
6d9730d3e6d3d682953f8b6ce3b1b28de803031e
|
149ba333fe45be7503a5bd95a4c760c0fabd65b7
|
/Project/checkout.h
|
928298f5b6b3009d9fb087719eee322afff9461b
|
[] |
no_license
|
wenshicheng97/Shopping-Cart-Simulator
|
5a6f744cf9f41ca3d1e08c58e9141fec54f553fc
|
6b1af2ac50d9b81331551b2ecb04b737ff19c909
|
refs/heads/main
| 2023-01-27T22:22:56.168879
| 2020-12-01T10:33:44
| 2020-12-01T10:33:44
| 317,505,474
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 285
|
h
|
checkout.h
|
#ifndef CHECKOUT_H
#define CHECKOUT_H
#include <QPushButton>
class CheckOut:public QPushButton
{
Q_OBJECT
public:
CheckOut(QWidget* qw):QPushButton(qw){};
signals:
void iChanged(QObject*);
public slots:
void imClicked(bool);
};
#endif // CHECKOUT_H
|
1da6c3e4c3e77f8bd2fd3fded2682872d1ac0643
|
07ee17f9fb57c0ccc9e4fe2c18410bd3f3eeec34
|
/darkstar/Terrain/Inc/grdEdgeTable.h
|
2213e8dbf2fc6374be97fed36cb90b6e0dbc5fc9
|
[] |
no_license
|
AlexHuck/TribesRebirth
|
1ea6ba27bc2af10527259d4d6cd4561a1793bccd
|
cf52c2e8c63f3da79e38cb3c153288d12003b123
|
refs/heads/master
| 2021-09-11T00:35:45.407177
| 2021-08-29T14:36:56
| 2021-08-29T14:36:56
| 226,741,338
| 0
| 0
| null | 2019-12-08T22:30:13
| 2019-12-08T22:30:12
| null |
UTF-8
|
C++
| false
| false
| 2,012
|
h
|
grdEdgeTable.h
|
//----------------------------------------------------------------------------
// $Workfile: GRDCAM.H $
// $Version$
// $Revision: 1.17 $
// $Date: 12 Jan 1996 10:11:34 $
// VO:timg
//----------------------------------------------------------------------------
#ifndef _GRDCAM_H_
#define _GRDCAM_H_
#include <base.h>
#include <ml.h>
#include <ts.h>
#include <tvector.h>
#include <viewcone.h>
#include "grdrange.h"
//----------------------------------------------------------------------------
struct Raster;
class DLLAPI GridEdgeTable
{
public:
enum Constants {
MaxDetail = 10,
};
typedef GridRange<int> Edge;
typedef Vector<Edge> EdgeVector;
struct Table {
int starty;
EdgeVector edges;
const Edge& getRange(int y) const {
return edges[y - starty];
}
const bool isVisible(const Point2I& p) const {
int yoff = p.y - starty;
return (yoff >= 0 && yoff < edges.size())?
edges[yoff].inside(p.x): false;
}
};
private:
//
struct DetailData {
Table edgeTable; // Rasterized viewcone
Point2I camera;
Box2I boundingBox;
};
DetailData details[MaxDetail];
// Grid File data
int groundScale;
int scanDetailLevel;
float visibleDistance;
GridRange<float> groundHeight;// Height range (used by viewcone)
// Methods
void trapezoid(int count,Raster& lx,Raster& rx);
void rasterize(const Poly3I& poly);
void buildEdgeTables(const Poly3I&);
void setDetailCamera(Point3F& camPos);
public:
GridEdgeTable();
~GridEdgeTable();
void buildTables(const TSCamera& cam);
void buildTablesOrtho(const TSOrthographicCamera& cam);
void setRasterData(int scale,int scanLevel,float visdist,GridRange<float> height);
bool isVisible(int detail,const Point2I& p) const;
const Table& getEdgeTable(int detail);
};
inline bool GridEdgeTable::isVisible(int detail,const Point2I& p) const
{
return details[detail].edgeTable.isVisible(p);
}
inline const GridEdgeTable::Table& GridEdgeTable::getEdgeTable(int detail)
{
return details[detail].edgeTable;
}
#endif
|
7d00e535ec8f4abde8dce9449de4f0e0d9d9cd97
|
eeaf4a8dcd26fa83582a4348e680047e0fbe1b55
|
/leetcode/leetCode/leetCode/sumPathNum.h
|
3b76b1aa13f3413dca3254cf975c7913f7e4a625
|
[] |
no_license
|
sniperswang/dev
|
ba954593639e1fe515eb8e10c54f2f40ba20eb0b
|
a921886fe11b4128b2bd7d8bd632839aa2b20133
|
refs/heads/master
| 2020-04-13T22:11:33.562837
| 2018-07-02T02:13:58
| 2018-07-02T02:13:58
| 53,461,366
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,604
|
h
|
sumPathNum.h
|
//
// sumPathNum.h
// leetCode
//
// Created by Yao Wang on 9/21/13.
//
//
#ifndef leetCode_sumPathNum_h
#define leetCode_sumPathNum_h
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int sumNumbers(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) {
return 0;
}
vector<int> v;
helper(root,0,v);
int val = sum(v);
return val;
}
int sum (vector<int> &v) {
int sum = 0;
for(int i =0; i < v.size(); i++ ){
sum += v[i];
}
return sum;
}
void helper(TreeNode *root, int num, vector<int> & v){
num = num*10 + root->val;
if( root->left == NULL && root->right == NULL) {
v.push_back(num);
return;
}
if (root->left == NULL && root->right != NULL ) {
helper(root->right, num, v);
return;
} else if (root->left != NULL && root->right == NULL ) {
helper(root->left, num, v);
return;
}
helper(root->right, num, v);
helper(root->left, num, v);
}
};
/*
TreeNode a(1);
TreeNode b(2);
TreeNode c(3);
TreeNode c_l(4);
TreeNode c_r(5);
a.right=&b;
a.left=&c;
c.right = &c_r;
c.left = &c_l;
Solution s;
int sum = s.sumNumbers(&a);
cout << "sum:" << sum <<endl;
/*
*/
#endif
|
2bca5d92c7330ce24096d7d7336d6c7a6b8e6eda
|
70a03ed528595815c7323d81824c690426d37a69
|
/Projects/Project 2/Game_V2/main.cpp
|
8928145b4ce3c7c962920b2ef1e4841785c403d7
|
[] |
no_license
|
penaandrew12/PenaAndrew_CIS5_Spring2017
|
fb70e7249080ff0954c4c5fcd044199e793f99a3
|
739d6c9d1c522669f5f1390684746ea0592a4322
|
refs/heads/master
| 2020-05-18T13:06:51.636118
| 2017-06-06T02:44:04
| 2017-06-06T02:44:04
| 84,239,351
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,112
|
cpp
|
main.cpp
|
/*
* File: main.cpp
* Author: Andrew Pena
* Created on March 30, 2017, 5:40 PM
* Purpose: Version 2 of Game
*/
//System Libraries
#include <iostream> //Main Library
#include <cmath> //Power Function
#include <iomanip> //Format
#include <cstdlib> //Random Number Generator
#include <ctime> //Library for time
#include <string> //String Library
using namespace std;
//User Libraries
//Global Constants Only
//Like PI, e, Gravity, or conversions
//Function Prototypes
//Program Execution Begins
int main(int argc, char** argv) {
//Set the random number seed
srand(static_cast<unsigned int>(time(0)));
//Variables Set for Program
string Name;
char Input,
ans; //Answer to play again
int RndmNum=0, //Random Number
i=0, //For loop
MrblsTkn=0; //Marbles Taken By player
float num=0; //Random Number Generator
int Mrbls=0; //Symbols marbles for the materials for game (First Game Starts at 12)
bool a=true,
b=false;
//Display for Programs, States Rules, and allows user to have a winnable chance.
cout<<"Please Enter Name = ";
cin>>Name;
cout<<"Welcome "<<Name<<". You get to play Dr. NIM!"<<endl;
cout<<"The Objective of this game is to try to take the last Marble."<<endl;
cout<<"The Rules are simple. The Computer will go first and it will choose One, Two, or Three Marbles."<<endl;
cout<<"After it picks the Marbles, it will be your turn to choose from One, Two, or Three Marbles."<<endl;
cout<<"It will then repeat and will let you go again until the last Marble is picked."<<endl;
cout<<"Good Luck! Also, if you do not win the first time you may play again."<<endl;
cout<<"Please press Enter to Start Game."<<endl;
//Pause to let user have time to get ready to play game
cin.get();
cin.ignore();
//Loop for the game. If the user wants he/she can play again
do {
//Random Number Generator Formula
num=(rand()% 4)+16;
num=pow(num,2);
//Random Amount of Marbles chosen to play game
Mrbls=num;
//Conversion to turn float Marbles into an Integer
Mrbls=static_cast<int>(Mrbls);
cout<<"The Game will play with "<<Mrbls<<" Marbles"<<endl<<endl;
cout<<"Many have tried but have always failed. There is a secret to the game and if you do not know it the computer will always win."<<endl;
cout<<"You may enter a to make the game fair and winnable or choose b to have it show no mercy."<<endl;
cout<<"what will you decide?"<<endl;
cin>>Input;
if (Input==a){
for (i<=4;i>=Mrbls;i--){
if (Mrbls%3==0)//Statement to take certain Random amount per turn
RndmNum=(rand()% 3)+1;
cout<<"The Computer takes "<<RndmNum<<" Marble(s)."<<endl;
Mrbls=Mrbls-RndmNum;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
}
else if (!(Input==b)){
//If/Else Statements to have computer choose what move to make
if (Mrbls%4==0){ //Statement to take certain Random amount per turn
RndmNum=(rand()% 3)+1;
cout<<"The Computer takes "<<RndmNum<<" Marble(s)."<<endl;
Mrbls=Mrbls-RndmNum;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
else if ((Mrbls-1)%4==0){ //Statement to take 1 Marble per turn
cout<<"The Computer takes 1 Marble."<<endl;
Mrbls=Mrbls-1;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
else if ((Mrbls-2)%4==0){ //Statement to take 2 Marbles per turn
cout<<"The Computer takes 2 Marble."<<endl;
Mrbls=Mrbls-2;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
else if ((Mrbls-3)%4==0){ //Statement to take 3 Marbles per turn
cout<<"The Computer takes 3 Marble."<<endl;
Mrbls=Mrbls-3;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
}
//loop for the program to keep going until only 4 marbles are left
while (Mrbls>4){
//Users Turn to choose the amount of marbles to take
cout<<"Enter The Amount of Marbles you wish to take for Your Turn = ";
cin>>MrblsTkn;
//If user does not take 1, 2, or 3 Marbles error will run and end game
if(!(MrblsTkn==1||MrblsTkn==2||MrblsTkn==3)){
cout<<"Invalid Input. The Computer Follows the Rules of the Game, which "
"if not are not followed, it will not work properly."<<endl;
return 1;
}
//After User chooses it is computer turn
Mrbls=Mrbls-MrblsTkn;
cout<<"You have taken "<<MrblsTkn<<" Marble(s). There are ";
cout<<Mrbls<<" Marble(s) Left."<<endl;
if (Mrbls%4==0){
RndmNum=(rand()% 3)+1;
cout<<"The Computer takes "<<RndmNum<<" Marble(s)."<<endl;
Mrbls=Mrbls-RndmNum;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
else if ((Mrbls-1)%4==0){ //Statement to take 1 Marble per turn
cout<<"The Computer takes 1 Marble."<<endl;
Mrbls=Mrbls-1;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
else if ((Mrbls-2)%4==0){ //Statement to take 2 Marbles per turn
cout<<"The Computer takes 2 Marble."<<endl;
Mrbls=Mrbls-2;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
else if ((Mrbls-3)%4==0){ //Statement to take 3 Marbles per turn
cout<<"The Computer takes 3 Marble."<<endl;
Mrbls=Mrbls-3;
cout<<"There are "<<Mrbls<<" Marbles Left."<<endl<<endl;
}
}
//At the 4th Marble the program will no longer loop and
cout<<"Enter The Amount of Marbles you wish to take for the Next Turn = ";
cin>>MrblsTkn;
//If user does not take 1, 2, or 3 Marbles error will run and end game
if(!(MrblsTkn==1||MrblsTkn==2||MrblsTkn==3)){
cout<<"Invalid Input. The Computer Follows the Rules of the Game, which "
"if not are not followed, it can not work properly."<<endl;
return 1; //Use of DeMorgans law to make clear
}
//The game is at the end and the reaming marbles are left.
Mrbls=Mrbls-MrblsTkn;
cout<<fixed<<setprecision(3)<<showpoint;
cout<<endl<<"During the game there was a total of "<<setw(1)<<num<<" Marbles. There is now "<<Mrbls<<" Left."<<endl;
//If game is run without not cheating and not entering fair the game will win
if (Mrbls=1,Mrbls=2,Mrbls=3){
cout<<"The Computer Takes the Last Marble(s)."<<endl<<endl;
}
//Option to play again
cout<<"Play Again?"<<endl;
cout<<"Yes or No?"<<endl;
cout<<"Type Y for Yes N for No."<<endl;
cin>>ans;
cout<<endl;
}
//If the user types Yes or yes the game will start again asking if you would like a fair match
while (ans=='Y'||ans=='y');
//Exit Stage
return 0;
}
|
429161e2d11fa09490e638af35c5226f9f445fec
|
2b95046bec2c38cbe7fc6f3cccc93747ed0b7cdc
|
/EDA/EDA 2014 Junio FInal eje2/Source.cpp
|
e85d6e5a12c42310772b8a9e93a48525dc7a7547
|
[] |
no_license
|
AndresHG/UCM
|
effe67e845bb466bfac205ad495dce05d129d568
|
1d29df8b7f1eae09ef94a4736ca55486cab91732
|
refs/heads/master
| 2021-04-27T11:08:20.276441
| 2019-02-01T14:14:51
| 2019-02-01T14:14:51
| 122,554,844
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 665
|
cpp
|
Source.cpp
|
#include <iostream>
#include <string>
#include "Arbin.h"
using namespace std;
void encuentraTesoro(const Arbin<string> &a, int dragones, int &mejor, string &puerta) {
if (a.esVacio()) {
return;
}
if (a.raiz()[0] == 'D') {
dragones++;
}
else if (a.raiz()[0] == 'P') {
if (dragones < mejor || mejor == -1) {
mejor = dragones;
puerta = a.raiz();
}
}
encuentraTesoro(a.hijoIz(), dragones, mejor, puerta);
encuentraTesoro(a.hijoDr(), dragones, mejor, puerta);
}
string puertaSalida(const Arbin<string> &a) {
int dragones = 0, mejor = -1;
string puerta = "";
encuentraTesoro(a, dragones, mejor, puerta);
return puerta;
}
int main() {
}
|
fbd2f314c90b0d9158b13eed0a06f553dae8c3a3
|
345b56ebe5bdf174fffb6dce26d0d68ce46089c1
|
/Source/Tools/Editor/SceneOutliner.h
|
12e322e75c16a3beec3e117fddd83dea6972b80c
|
[
"BSD-3-Clause"
] |
permissive
|
HeliumProject/Engine
|
4c010631c3e10655740bf663bf2be1c390008fba
|
32497019f57d5cf7fc231200fac310756ae6cea9
|
refs/heads/master
| 2023-09-05T17:48:31.165233
| 2022-07-01T17:47:42
| 2022-07-01T17:47:42
| 962,121
| 140
| 27
|
NOASSERTION
| 2018-10-31T21:18:14
| 2010-10-04T23:13:39
|
C++
|
UTF-8
|
C++
| false
| false
| 5,307
|
h
|
SceneOutliner.h
|
#pragma once
#include "Platform/Types.h"
#include "EditorScene/Scene.h"
#include "EditorScene/SceneManager.h"
#include "EditorScene/Selection.h"
#include "Reflect/Object.h"
#include "Editor/API.h"
#include "Editor/SceneOutlinerState.h"
#include "Editor/Controls/Tree/SortTreeCtrl.h"
namespace Helium
{
namespace Editor
{
/////////////////////////////////////////////////////////////////////////////
// MetaClass for attaching Objects to items displayed in a tree control.
//
class SceneOutlinerItemData : public wxTreeItemData
{
protected:
Reflect::Object* m_Object;
std::string m_ItemText;
int m_CachedCount;
bool m_Countable;
public:
SceneOutlinerItemData( Reflect::Object* object )
: m_Object( object )
, m_CachedCount( 0 )
{
}
~SceneOutlinerItemData()
{
}
Reflect::Object* GetObject() const
{
return m_Object;
}
void SetObject( Reflect::Object* object )
{
m_Object = object;
}
void SetItemText( const std::string& text )
{
m_ItemText = text;
}
const std::string& GetItemText()
{
return m_ItemText;
}
int GetCachedCount()
{
return m_CachedCount;
}
void SetCachedCount( int count )
{
m_CachedCount = count;
}
bool GetCountable()
{
return m_Countable;
}
void SetCountable( bool countable )
{
m_Countable = countable;
}
};
/////////////////////////////////////////////////////////////////////////////
// Abstract base class for GUIs that display trees of scene nodes.
//
class SceneOutliner : public wxEvtHandler
{
protected:
// Typedefs
typedef std::map< Reflect::Object*, wxTreeItemId > M_TreeItems;
protected:
// Member variables
Editor::SceneManager* m_SceneManager;
Editor::Scene* m_CurrentScene;
SortTreeCtrl* m_TreeCtrl;
M_TreeItems m_Items;
SceneOutlinerState m_StateInfo;
bool m_IgnoreSelectionChange;
bool m_DisplayCounts;
public:
// Functions
SceneOutliner( Editor::SceneManager* sceneManager );
virtual ~SceneOutliner();
SortTreeCtrl* InitTreeCtrl( wxWindow* parent, wxWindowID id );
void SaveState( SceneOutlinerState& state );
void RestoreState( const SceneOutlinerState& state );
void DisableSorting();
void EnableSorting();
virtual void Sort( const wxTreeItemId& root = NULL );
protected:
SceneOutlinerItemData* GetTreeItemData( const wxTreeItemId& item );
void UpdateCurrentScene( Editor::Scene* scene );
void DoRestoreState();
protected:
// Derived classes can optionally override these functions
virtual void Clear();
virtual wxTreeItemId AddItem( const wxTreeItemId& parent, const std::string& name, int32_t image, SceneOutlinerItemData* data, bool isSelected, bool countable = true);
virtual void DeleteItem( Reflect::Object* object );
void UpdateItemCounts( const wxTreeItemId& node, int delta );
void UpdateItemVisibility( const wxTreeItemId& item, bool visible );
virtual void ConnectSceneListeners();
virtual void DisconnectSceneListeners();
virtual void CurrentSceneChanging( Editor::Scene* newScene );
virtual void CurrentSceneChanged( Editor::Scene* oldScene );
protected:
// Application event callbacks
virtual void CurrentSceneChanged( const Editor::SceneChangeArgs& args );
virtual void SelectionChanged( const Editor::SelectionChangeArgs& args );
virtual void SceneNodeNameChanged( const Editor::SceneNodeChangeArgs& args );
void SceneNodeVisibilityChanged( const Editor::SceneNodeChangeArgs& args );
protected:
// Derived classes must override these functions
virtual SortTreeCtrl* CreateTreeCtrl( wxWindow* parent, wxWindowID id ) = 0;
private:
// Tree event callbacks
virtual void OnEndLabelEdit( wxTreeEvent& args );
virtual void OnSelectionChanging( wxTreeEvent& args );
virtual void OnSelectionChanged( wxTreeEvent& args );
virtual void OnExpanded( wxTreeEvent& args );
virtual void OnCollapsed( wxTreeEvent& args );
virtual void OnDeleted( wxTreeEvent& args );
virtual void OnChar( wxKeyEvent& args );
private:
// Connect/disconnect dynamic event table for GUI callbacks
void ConnectDynamicEventTable();
void DisconnectDynamicEventTable();
};
}
}
|
a815c281e48ae3dab9bcf4de1633910591b2ad74
|
25a744639b3d80921bad2073b77c8bd6208efd71
|
/koenig/ch5/6b.cc
|
acc9a9d5ac8da0e78e1ad7abab5e4293e76896aa
|
[] |
no_license
|
samikganguly/cpp_learn
|
97ca465e2c80e165be554f09a7f2833988729708
|
49893882bf3375b6245ef4973e6335b59c3c76a9
|
refs/heads/master
| 2020-12-31T04:28:48.850333
| 2016-04-09T11:56:15
| 2016-04-09T11:56:15
| 55,842,291
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 521
|
cc
|
6b.cc
|
#include <string>
#include "6b.h"
using std::string;
using std::vector;
using std::domain_error;
double median(vector<double>& hw) {
const vector<double>::size_type sz = hw.size();
if(sz > 0)
return (sz % 2 == 0) ? (hw[sz / 2 - 1] + hw[sz / 2]) / 2
: hw[sz / 2];
else
return 0;
}
double grade(double midterm, double final_exam, vector<double>& hw)
throw (domain_error) {
if(hw.size() == 0)
throw domain_error("student has done no homework");
return 0.2 * midterm + 0.4 * final_exam + 0.4 * median(hw);
}
|
c0cd2cce5eddc8e1654281063ec2a89a5452b695
|
8ee127bc4c9e174f2fc5bb8441cde39d8378d721
|
/lib/include/EOUL/Utils.hpp
|
c167fbbbb56610e888af23177fc0fda80db53f2b
|
[] |
no_license
|
timeester3648/AssaultCube-Qt-Menu
|
b1847b420b7226adc245676aefc84d906b123249
|
8515724aaca945e73cf0675a83460fcdcf047736
|
refs/heads/master
| 2020-04-08T08:38:41.004897
| 2019-08-16T14:12:29
| 2019-08-16T14:12:29
| 159,186,852
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,395
|
hpp
|
Utils.hpp
|
#pragma once
#pragma comment(lib, "Psapi")
#include <Windows.h>
#include <Psapi.h>
namespace EOUL::Util {
namespace Private {
inline static MEMORYSTATUSEX memInfo;
inline static bool initialized = false;
}
enum MemoryType {
Physical,
Virtual
};
/* returns how much ram is free */
inline size_t ramFree(MemoryType type = MemoryType::Physical) {
if (!Private::initialized) {
Private::memInfo.dwLength = sizeof(MEMORYSTATUSEX);
Private::initialized = true;
}
GlobalMemoryStatusEx(&Private::memInfo);
if (type == MemoryType::Physical) {
return Private::memInfo.ullAvailPhys;
} else {
return Private::memInfo.ullAvailVirtual;
}
}
/* returns how much ram is used */
inline size_t ramUsed(MemoryType type = MemoryType::Physical) {
if (!Private::initialized) {
Private::memInfo.dwLength = sizeof(MEMORYSTATUSEX);
Private::initialized = true;
}
GlobalMemoryStatusEx(&Private::memInfo);
if (type == MemoryType::Physical) {
return Private::memInfo.ullTotalPhys - Private::memInfo.ullAvailPhys;
} else {
return Private::memInfo.ullTotalVirtual - Private::memInfo.ullAvailVirtual;
}
}
/* returns how much ram is used by current process */
inline size_t ramUsedByCurrent() {
PROCESS_MEMORY_COUNTERS pmc;
GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
return pmc.WorkingSetSize;
}
}
|
61ec9d406b613a48a6876a0ebaff05c6e8eb57d6
|
e9425ff5a7ed5d37ddf67866cc36baa90e062368
|
/ADS/1-й курс/(2) Списки, стеки, очереди, СНМ/(B)Проверка ПСП.cpp
|
b64efcfe54089cc019762be6e08d81ad984698d8
|
[] |
no_license
|
JarikLag/ITMO-Labs
|
4ebdeec4accffa4a7726227e95f0111b7be8f59d
|
e3a02501e81ab7e874a459f88b6eabe97026d7f7
|
refs/heads/master
| 2020-05-09T17:28:57.617814
| 2019-06-22T13:44:29
| 2019-06-22T13:44:29
| 181,310,699
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,381
|
cpp
|
(B)Проверка ПСП.cpp
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <ctime>
using namespace std;
typedef long long LL;
bool open(char c)
{
if (c == '(' || c == '[' || c == '{')
return true;
else
return false;
}
bool sameType(char a, char b)
{
if (a == '(' && b == ')' || a == '[' && b == ']' || a == '{' && b == '}')
return true;
else
return false;
}
int main()
{
freopen("brackets.in", "r", stdin);
freopen("brackets.out", "w", stdout);
stack<char> myStack;
string s;
cin >> s;
for (int i = 0; i < s.length(); i++)
{
if (myStack.empty())
{
if(open(s[i]))
myStack.push(s[i]);
else
{
cout << "NO";
return 0;
}
}
else
{
if (open(s[i]))
myStack.push(s[i]);
else
{
if (sameType(myStack.top(), s[i]))
myStack.pop();
else
{
cout << "NO";
return 0;
}
}
}
}
if (myStack.empty())
cout << "YES";
else
cout << "NO";
return 0;
}
|
db59081e048eb3a16b084aa51b970a5b9bd6c65b
|
0af419e9a0a5d5263a5eac851b53e4c19d7e6f59
|
/Inventory.hpp
|
ec5f66f13085c9cfcf02108b0c208abc1a72bad1
|
[] |
no_license
|
aiman-junaid/Eco-Planet
|
689fc98df937c7d0aa345a06bbebedb7f07ae68e
|
b969f2feec2637c494bc31e94b672340e0be159d
|
refs/heads/main
| 2023-05-07T11:57:46.761190
| 2021-06-08T20:47:10
| 2021-06-08T20:47:10
| 355,972,447
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 302
|
hpp
|
Inventory.hpp
|
#pragma once
#include "string.h"
#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include "RandomObj.hpp"
class Inventory
{
GameObject **lst = NULL;
int stored;
public:
Inventory();
void append(GameObject *);
GameObject *remove();
~Inventory();
};
|
b1223a074afb3bbaabe94e3cb4c528c6de940838
|
45fb39d8e60dae09530f67086bdd6288dfcd5765
|
/Server/include/Networking/UDP_Server.h
|
ca243be49df05d38e5d8c7e368c8945f568bf79f
|
[] |
no_license
|
itcgames/ARGO_2018_19_F
|
ecc984fe111dba9146d69143bf2cad632040a42a
|
85d55b0b86b7893db012d5451e64bf7530d56d5b
|
refs/heads/master
| 2020-04-20T19:54:47.860534
| 2019-03-05T17:10:53
| 2019-03-05T17:10:53
| 169,062,078
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 294
|
h
|
UDP_Server.h
|
#ifndef UDP_SERVER_H
#define UDP_SERVER_H
#include "Networking/Server.h"
class UDPServer : public Server
{
public:
UDPServer();
virtual bool createSocket() override;
virtual bool bindSocket() override;
void sendAndRecv();
virtual void closeSocket() override;
};
#endif // !UDP_SERVER_H
|
f1e87ef819b1f2858e9cd47c5a75f0e99c7b2670
|
9e30fce1a475704054ed75e33eda1ebe4aabc628
|
/Engine/Source/gui/gui_manager.h
|
02d630ea4634fd3ec80858a99bbf8220dc5a201b
|
[] |
no_license
|
stkromm/darkshore
|
c9b6dea426925d4fcae6dbbe87499976c875d19f
|
65f84083423d4be0f7268da27f90b416e1941a16
|
refs/heads/master
| 2022-12-22T00:42:23.236705
| 2020-09-21T15:23:33
| 2020-09-21T15:23:33
| 133,785,449
| 0
| 0
| null | 2020-09-04T19:12:55
| 2018-05-17T08:47:27
|
C++
|
UTF-8
|
C++
| false
| false
| 156
|
h
|
gui_manager.h
|
#pragma once
#include "gui.h"
namespace ds {
namespace gui
{
namespace GuiManager
{
Gui* get_gui();
bool init();
void shutdown();
};
}
}
|
a34c2ff78581a2f28fa3232f64dc9e09d170b544
|
6f874ccb136d411c8ec7f4faf806a108ffc76837
|
/code/Windows-classic-samples/Samples/IdentifyInputSource/cpp/InputSource.cpp
|
b448144bddab19863ed5d490446ca9347565bae8
|
[
"MIT"
] |
permissive
|
JetAr/ZDoc
|
c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435
|
e81a3adc354ec33345e9a3303f381dcb1b02c19d
|
refs/heads/master
| 2022-07-26T23:06:12.021611
| 2021-07-11T13:45:57
| 2021-07-11T13:45:57
| 33,112,803
| 8
| 8
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,832
|
cpp
|
InputSource.cpp
|
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#include "stdafx.h"
/******************************************************************
* *
* Global Variables *
* *
******************************************************************/
HWND g_hwnd = NULL;
INPUT_MESSAGE_SOURCE g_inputSource;
/******************************************************************
* *
* Function Prototypes *
* *
******************************************************************/
HRESULT Initialize(HINSTANCE hInstance);
HRESULT OnRender(HDC hdc, const RECT &rcPaint);
void OnResize(UINT width, UINT height);
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
/******************************************************************
* *
* WinMain *
* *
* Application entrypoint *
* *
******************************************************************/
_Use_decl_annotations_
int
WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
HRESULT hr = E_FAIL;
ZeroMemory(&g_inputSource, sizeof(g_inputSource));
if (SUCCEEDED(hr = Initialize(hInstance)))
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return SUCCEEDED(hr);
}
/******************************************************************
* *
* InputSourceApp::Initialize *
* *
* This method is used to create and display the application *
* window, and provides a convenient place to create any device *
* independent resources that will be required. *
* *
******************************************************************/
HRESULT Initialize(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
ATOM atom;
// Register window class
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = sizeof(LONG_PTR);
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = NULL;
wcex.lpszMenuName = NULL;
wcex.lpszClassName = TEXT("InputSourceApp");
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
atom = RegisterClassEx(&wcex);
SetProcessDPIAware();
// Create window
g_hwnd = CreateWindow(
TEXT("InputSourceApp"),
TEXT("Input Source Identification Sample"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
640,
480,
NULL,
NULL,
hInstance,
NULL
);
if (g_hwnd)
{
ShowWindow(
g_hwnd,
SW_SHOWNORMAL
);
UpdateWindow(
g_hwnd
);
}
return g_hwnd ? S_OK : E_FAIL;
}
HRESULT OnRender(HDC hdc, const RECT &rcPaint)
{
WCHAR wzText[512];
FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
StringCchCopyW(wzText, ARRAYSIZE(wzText), L"Source: ");
switch(g_inputSource.deviceType)
{
case IMDT_UNAVAILABLE:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Unavailable\n");
break;
case IMDT_KEYBOARD:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Keyboard\n");
break;
case IMDT_MOUSE:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Mouse\n");
break;
case IMDT_TOUCH:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Touch\n");
break;
case IMDT_PEN:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Pen\n");
break;
}
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Origin: ");
switch(g_inputSource.originId)
{
case IMO_UNAVAILABLE:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Unavailable\n");
break;
case IMO_HARDWARE:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Hardware\n");
break;
case IMO_INJECTED:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"Injected\n");
break;
case IMO_SYSTEM:
StringCchCatW(wzText, ARRAYSIZE(wzText), L"System\n");
break;
}
DrawText(hdc, wzText, (int)wcslen(wzText), (LPRECT)&rcPaint, DT_TOP | DT_LEFT);
return S_OK;
}
/******************************************************************
* *
* WndProc *
* *
* This static method handles our app's window messages *
* *
******************************************************************/
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if ((message >= WM_MOUSEFIRST && message <= WM_MOUSELAST) ||
(message >= WM_KEYFIRST && message <= WM_KEYLAST) ||
(message >= WM_TOUCH && message <= WM_POINTERWHEEL))
{
GetCurrentInputMessageSource(&g_inputSource);
InvalidateRect(g_hwnd, NULL, FALSE);
}
switch (message)
{
case WM_PAINT:
case WM_DISPLAYCHANGE:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
OnRender(hdc, ps.rcPaint);
EndPaint(hwnd, &ps);
}
return 0;
case WM_DESTROY:
{
PostQuitMessage(0);
}
return 1;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
|
b4ea6e9265e4da6268ab679cfa976a127d3dc5af
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/admin/pchealth/sr/rstrcore/drvtable.cpp
|
1914c36df3d7d2fee77db0e92bfe81bbed6e5477
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 34,429
|
cpp
|
drvtable.cpp
|
/******************************************************************************
Copyright (c) 2000 Microsoft Corporation
Module Name:
drvtable.cpp
Abstract:
This file contains CRstrDriveInfo class and CreateDriveList function.
Revision History:
Seong Kook Khang (SKKhang) 07/20/00
created
******************************************************************************/
#include "stdwin.h"
#include "rstrcore.h"
#include "resource.h"
#include "..\shell\resource.h"
static LPCWSTR s_cszEmpty = L"";
WCHAR s_szSysDrv[MAX_PATH];
/////////////////////////////////////////////////////////////////////////////
//
// CRstrDriveInfo class
//
/////////////////////////////////////////////////////////////////////////////
//
// NOTE - 7/26/00 - skkhang
// CSRStr has one issue -- NULL return in case of memory failure. Even though
// the behavior is just same with regular C language pointer, many codes are
// blindly passing it to some external functions (e.g. strcmp) which does not
// gracefully handle NULL pointer. Ideally and eventually all of code should
// prevent any possible NULL pointers from getting passed to such functions,
// but for now, I'm using an alternative workaround -- GetID, GetMount, and
// GetLabel returns a static empty string instead of NULL pointer.
//
/////////////////////////////////////////////////////////////////////////////
// CRstrDriveInfo construction / destruction
CRstrDriveInfo::CRstrDriveInfo()
{
m_dwFlags = 0;
m_hIcon[0] = NULL;
m_hIcon[1] = NULL;
m_llDSMin = SR_DEFAULT_DSMIN * MEGABYTE;
m_llDSMax = SR_DEFAULT_DSMAX * MEGABYTE;
m_uDSUsage = 0;
m_fCfgExcluded = FALSE;
m_uCfgDSUsage = 0;
m_ulTotalBytes.QuadPart = 0;
}
CRstrDriveInfo::~CRstrDriveInfo()
{
if ( m_hIcon[0] != NULL )
::DestroyIcon( m_hIcon[0] );
if ( m_hIcon[1] != NULL )
::DestroyIcon( m_hIcon[1] );
}
BOOL CRstrDriveInfo::InitUsage (LPCWSTR cszID, INT64 llDSUsage)
{
TraceFunctEnter("CRstrDriveInfo::InitUsage");
//
// calculate max datastore size - max (12% of disk, 400mb)
//
// read % from registry
HKEY hKey = NULL;
DWORD dwPercent = SR_DEFAULT_DISK_PERCENT;
DWORD dwDSMax = SR_DEFAULT_DSMAX;
DWORD dwDSMin = IsSystem() ? SR_DEFAULT_DSMIN : SR_DEFAULT_DSMIN_NONSYSTEM;
ULARGE_INTEGER ulDummy;
DWORD dwRes = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
s_cszSRRegKey, 0, KEY_READ, &hKey);
if (ERROR_SUCCESS == dwRes)
{
RegReadDWORD(hKey, s_cszDiskPercent, &dwPercent);
RegReadDWORD(hKey, s_cszDSMax, &dwDSMax);
if (IsSystem())
RegReadDWORD(hKey, s_cszDSMin, &dwDSMin);
RegCloseKey(hKey);
}
else
{
ErrorTrace(0, "! RegOpenKeyEx : %ld", dwRes);
}
// BUGBUG - this call may not always give total disk space (per-user quota)
ulDummy.QuadPart = 0;
if (FALSE == GetDiskFreeSpaceEx (cszID, &ulDummy, &m_ulTotalBytes, NULL))
{
ErrorTrace(0, "! GetDiskFreeSpaceEx : %ld", GetLastError());
goto done;
}
m_llDSMin = min(m_ulTotalBytes.QuadPart, (INT64) dwDSMin * MEGABYTE);
m_llDSMax = min(m_ulTotalBytes.QuadPart,
max( (INT64) dwDSMax * MEGABYTE,
(INT64) dwPercent * m_ulTotalBytes.QuadPart / 100 ));
if (m_llDSMax < m_llDSMin)
m_llDSMax = m_llDSMin;
//
// take floor of this value
//
m_llDSMax = ((INT64) (m_llDSMax / (INT64) MEGABYTE)) * (INT64) MEGABYTE;
DebugTrace(0, "m_llDSMax: %I64d, Size: %I64d", m_llDSMax, llDSUsage);
if ( ( llDSUsage == 0) || (llDSUsage > m_llDSMax) )
// not initialized, assume maximum
{
llDSUsage = m_llDSMax;
}
if ( ( llDSUsage - m_llDSMin > 0) && ( m_llDSMax - m_llDSMin > 0))
{
// + ((llDSUsage - m_llDSMin)/2) is to ensure that correct
// rounding off happens here
m_uDSUsage =( ((llDSUsage - m_llDSMin) * DSUSAGE_SLIDER_FREQ)
+ ((m_llDSMax - m_llDSMin)/2))/( m_llDSMax - m_llDSMin);
}
else
m_uDSUsage = 0;
m_uCfgDSUsage = m_uDSUsage;
done:
TraceFunctLeave();
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CRstrDriveInfo operations
BOOL
CRstrDriveInfo::Init( LPCWSTR cszID, DWORD dwFlags, INT64 llDSUsage, LPCWSTR cszMount, LPCWSTR cszLabel )
{
TraceFunctEnter("CRstrDriveInfo::Init");
BOOL fRet = FALSE;
LPCWSTR cszErr;
DWORD dwRes;
WCHAR szMount[MAX_PATH];
WCHAR szLabel[MAX_PATH];
m_dwFlags = dwFlags;
m_strID = cszID;
if ( !IsOffline() )
{
// Get Mount Point (drive letter or root directory path) from Unique Volume ID
//
if ( !::GetVolumePathNamesForVolumeName( cszID, szMount, MAX_PATH, &dwRes ) && GetLastError() != ERROR_MORE_DATA)
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "::GetVolumePathNamesForVolumeName failed - %ls", cszErr);
// Instead of fail, use cszMount even if it may not accurate
::lstrcpy( szMount, cszMount );
}
else
{
szMount[MAX_PATH-1] = L'\0';
if (lstrlenW (szMount) > MAX_MOUNTPOINT_PATH)
{
// Instead of fail, use cszMount even if it may not accurate
::lstrcpy( szMount, cszMount );
}
}
// Get Volume Label from Mount Point
//
if ( !::GetVolumeInformation( cszID, szLabel, MAX_PATH, NULL, NULL, NULL, NULL, 0 ) )
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "::GetVolumeInformation failed - %ls", cszErr);
// Instead of fail, use cszLabel even if it may not accurate
::lstrcpy( szLabel, cszLabel );
}
}
if ( ( szMount[1] == L':' ) && ( szMount[2] == L'\\' ) && ( szMount[3] == L'\0' ) )
szMount[2] = L'\0';
m_strMount = szMount;
m_strLabel = szLabel;
InitUsage (cszID, llDSUsage);
m_fCfgExcluded = IsExcluded();
fRet = TRUE;
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::Init( LPCWSTR cszID, CDataStore *pDS, BOOL fOffline )
{
TraceFunctEnter("CRstrDriveInfo::Init");
BOOL fRet = FALSE;
LPCWSTR cszErr;
DWORD dwRes;
WCHAR szMount[MAX_PATH];
WCHAR szLabel[MAX_PATH];
m_strID = cszID;
UpdateStatus( pDS->GetFlags(), fOffline );
if ( !fOffline )
{
// Get Mount Point (drive letter or root directory path) from Unique Volume ID
//
if ( !::GetVolumePathNamesForVolumeName( cszID, szMount, MAX_PATH, &dwRes ) && GetLastError() != ERROR_MORE_DATA )
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "::GetVolumePathNamesForVolumeName failed - %ls", cszErr);
goto Exit;
}
else
{
szMount[MAX_PATH-1] = L'\0';
if (lstrlenW (szMount) > MAX_MOUNTPOINT_PATH)
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "mount point too long %ls", cszErr);
goto Exit;
}
}
// Get Volume Label from Mount Point
//
if ( !::GetVolumeInformation( cszID, szLabel, MAX_PATH, NULL, NULL, NULL, NULL, 0 ) )
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "::GetVolumeInformation failed - %ls", cszErr);
// this is not a fatal error - this can happen if the
// volume is being formatted for example. assume that the
// label is empty
szLabel[0]= L'\0';
}
}
else
{
::lstrcpyW (szMount, pDS->GetDrive());
::lstrcpyW (szLabel, pDS->GetLabel());
}
if ( ( szMount[1] == L':' ) && ( szMount[2] == L'\\' ) && ( szMount[3] == L'\0' ) )
szMount[2] = L'\0';
m_strMount = szMount;
m_strLabel = szLabel;
InitUsage (cszID, pDS->GetSizeLimit());
m_fCfgExcluded = IsExcluded();
fRet = TRUE;
Exit:
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::LoadFromLog( HANDLE hfLog )
{
TraceFunctEnter("CRstrDriveInfo::LoadFromLog");
BOOL fRet = FALSE;
DWORD dwRes;
WCHAR szBuf[MAX_PATH];
// Read m_dwFlags
READFILE_AND_VALIDATE( hfLog, &m_dwFlags, sizeof(DWORD), dwRes, Exit );
// Read m_strID
if ( !::ReadStrAlign4( hfLog, szBuf ) )
{
ErrorTrace(0, "Cannot read drive ID...");
goto Exit;
}
if ( szBuf[0] == L'\0' )
{
ErrorTrace(0, "Drive Guid is empty...");
goto Exit;
}
m_strID = szBuf;
// Read m_strMount
if ( !::ReadStrAlign4( hfLog, szBuf ) )
{
ErrorTrace(0, "Cannot read drive mount point...");
goto Exit;
}
m_strMount = szBuf;
// Read m_strLabel
if ( !::ReadStrAlign4( hfLog, szBuf ) )
{
ErrorTrace(0, "Cannot read drive mount point...");
goto Exit;
}
m_strLabel = szBuf;
m_fCfgExcluded = IsExcluded();
// m_nCfgMaxSize = ...
fRet = TRUE;
Exit:
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
void
CRstrDriveInfo::UpdateStatus( DWORD dwFlags, BOOL fOffline )
{
TraceFunctEnter("CRstrDriveInfo::UpdateStatus");
m_dwFlags = 0;
if ( fOffline )
{
m_dwFlags |= RDIF_OFFLINE;
}
else
{
// check if frozen
if ( ( dwFlags & SR_DRIVE_FROZEN ) != 0 )
m_dwFlags |= RDIF_FROZEN;
// check if system drive
if ( ( dwFlags & SR_DRIVE_SYSTEM ) != 0 )
{
m_dwFlags |= RDIF_SYSTEM;
}
else
{
// if not system drive, simply use MONITORED flag of drive table
if ( ( dwFlags & SR_DRIVE_MONITORED ) == 0 )
m_dwFlags |= RDIF_EXCLUDED;
}
}
DebugTrace(0, "Status has been updated, m_dwFlags=%08X", m_dwFlags);
TraceFunctLeave();
}
/////////////////////////////////////////////////////////////////////////////
// CRstrDriveInfo - methods
DWORD
CRstrDriveInfo::GetFlags()
{
return( m_dwFlags );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::IsExcluded()
{
return( ( m_dwFlags & RDIF_EXCLUDED ) != 0 );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::IsFrozen()
{
return( ( m_dwFlags & RDIF_FROZEN ) != 0 );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::IsOffline()
{
return( ( m_dwFlags & RDIF_OFFLINE ) != 0 );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::IsSystem()
{
return( ( m_dwFlags & RDIF_SYSTEM ) != 0 );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::RefreshStatus()
{
TraceFunctEnter("CRstrDriveInfo::RefreshStatus");
BOOL fRet = FALSE;
LPCWSTR cszErr;
WCHAR szDTFile[MAX_PATH];
DWORD dwRes;
CDriveTable cDrvTable;
CDataStore *pDS;
::MakeRestorePath( szDTFile, s_szSysDrv, NULL );
::PathAppend( szDTFile, s_cszDriveTable );
DebugTrace(0, "Loading drive table - %ls", szDTFile);
dwRes = cDrvTable.LoadDriveTable( szDTFile );
if ( dwRes != ERROR_SUCCESS )
{
cszErr = ::GetSysErrStr( dwRes );
ErrorTrace(0, "Cannot load a drive table - %ls", cszErr);
ErrorTrace(0, " szDTFile: '%ls'", szDTFile);
goto Exit;
}
dwRes = cDrvTable.RemoveDrivesFromTable();
if ( dwRes != ERROR_SUCCESS )
{
cszErr = ::GetSysErrStr( dwRes );
ErrorTrace(0, "CDriveTable::RemoveDrivesFromTable failed - %ls", cszErr);
// ignore error
}
pDS = cDrvTable.FindGuidInTable( (LPWSTR)GetID() );
if ( pDS == NULL )
UpdateStatus( 0, TRUE );
else
UpdateStatus( pDS->GetFlags(), FALSE );
fRet = TRUE;
Exit:
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
LPCWSTR
CRstrDriveInfo::GetID()
{
return( ( m_strID.Length() > 0 ) ? m_strID : s_cszEmpty );
}
/////////////////////////////////////////////////////////////////////////////
LPCWSTR
CRstrDriveInfo::GetMount()
{
return( ( m_strMount.Length() > 0 ) ? m_strMount : s_cszEmpty );
}
/////////////////////////////////////////////////////////////////////////////
LPCWSTR
CRstrDriveInfo::GetLabel()
{
return( ( m_strLabel.Length() > 0 ) ? m_strLabel : s_cszEmpty );
}
/////////////////////////////////////////////////////////////////////////////
void
CRstrDriveInfo::SetMountAndLabel( LPCWSTR cszMount, LPCWSTR cszLabel )
{
TraceFunctEnter("CRstrDriveInfo::SetMountAndLabel");
m_strMount = cszMount;
m_strLabel = cszLabel;
TraceFunctLeave();
}
/////////////////////////////////////////////////////////////////////////////
HICON
CRstrDriveInfo::GetIcon( BOOL fSmall )
{
TraceFunctEnter("CRstrDriveInfo::GetIcon");
LPCWSTR cszErr;
int nIdx = fSmall ? 0 : 1;
int cxIcon, cyIcon;
HICON hIcon;
if ( m_hIcon[nIdx] != NULL )
goto Exit;
cxIcon = ::GetSystemMetrics( fSmall ? SM_CXSMICON : SM_CXICON );
cyIcon = ::GetSystemMetrics( fSmall ? SM_CYSMICON : SM_CYICON );
hIcon = (HICON)::LoadImage( g_hInst, MAKEINTRESOURCE(IDI_DRIVE_FIXED),
IMAGE_ICON, cxIcon, cyIcon, LR_DEFAULTCOLOR );
if ( hIcon == NULL )
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "::LoadImage failed - %ls", cszErr);
goto Exit;
}
m_hIcon[nIdx] = hIcon;
Exit:
TraceFunctLeave();
return( m_hIcon[nIdx] );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::SaveToLog( HANDLE hfLog )
{
TraceFunctEnter("CRstrDriveInfo::SaveToLog");
BOOL fRet = FALSE;
BYTE pbBuf[7*MAX_PATH];
DWORD dwSize = 0;
DWORD dwRes;
*((DWORD*)pbBuf) = m_dwFlags;
dwSize += sizeof(DWORD);
dwSize += ::StrCpyAlign4( pbBuf+dwSize, m_strID );
dwSize += ::StrCpyAlign4( pbBuf+dwSize, m_strMount );
dwSize += ::StrCpyAlign4( pbBuf+dwSize, m_strLabel );
WRITEFILE_AND_VALIDATE( hfLog, pbBuf, dwSize, dwRes, Exit );
fRet = TRUE;
Exit:
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
UINT
CRstrDriveInfo::GetDSUsage()
{
TraceFunctEnter("CRstrDriveInfo::GetDSUsage");
TraceFunctLeave();
return( m_uDSUsage );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::GetUsageText( LPWSTR szUsage )
{
TraceFunctEnter("CRstrDriveInfo::GetUsageText");
INT64 llUsage;
int nPercent;
int nUsage;
if (m_llDSMax - m_llDSMin > 0)
llUsage = m_llDSMin + ( m_llDSMax - m_llDSMin ) * m_uCfgDSUsage / DSUSAGE_SLIDER_FREQ;
else
llUsage = m_llDSMin;
if (m_ulTotalBytes.QuadPart != 0)
{
// the m_ulTotalBytes.QuadPart/200 addition is to ensure that
// the correct round off happens
nPercent = (llUsage + (m_ulTotalBytes.QuadPart/200)) * 100/
m_ulTotalBytes.QuadPart;
}
else nPercent = 0;
nUsage = llUsage / ( 1024 * 1024 );
::wsprintf( szUsage, L"%d%% (%d MB)", nPercent, nUsage );
TraceFunctLeave();
return( TRUE );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::GetCfgExcluded( BOOL *pfExcluded )
{
TraceFunctEnter("CRstrDriveInfo::GetCfgExcluded");
BOOL fRet = FALSE;
if ( m_fCfgExcluded != IsExcluded() )
{
*pfExcluded = m_fCfgExcluded;
fRet = TRUE;
}
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
void
CRstrDriveInfo::SetCfgExcluded( BOOL fExcluded )
{
TraceFunctEnter("CRstrDriveInfo::SetCfgExcluded");
m_fCfgExcluded = fExcluded;
TraceFunctLeave();
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::GetCfgDSUsage( UINT *puPos )
{
TraceFunctEnter("CRstrDriveInfo::GetCfgDSUsage");
BOOL fRet = FALSE;
if ( m_uCfgDSUsage != m_uDSUsage )
{
*puPos = m_uCfgDSUsage;
fRet = TRUE;
}
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
void
CRstrDriveInfo::SetCfgDSUsage( UINT uPos )
{
TraceFunctEnter("CRstrDriveInfo::SetCfgDSUsage");
m_uCfgDSUsage = uPos;
TraceFunctLeave();
}
/////////////////////////////////////////////////////////////////////////////
void
CloseRestoreUI()
{
WCHAR szPath[MAX_PATH], szTitle[MAX_PATH] = L"";
if (ExpandEnvironmentStrings(L"%windir%\\system32\\restore\\rstrui.exe", szPath, MAX_PATH))
{
if (ERROR_SUCCESS == SRLoadString(szPath, IDS_RESTOREUI_TITLE, szTitle, MAX_PATH))
{
HWND hWnd = FindWindow(CLSNAME_RSTRSHELL, szTitle);
if (hWnd != NULL)
PostMessage(hWnd, WM_CLOSE, 0, 0);
}
}
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::ApplyConfig( HWND hWnd )
{
TraceFunctEnter("CRstrDriveInfo::ApplyConfig");
BOOL fRet = FALSE;
LPCWSTR cszErr;
INT64 llUsage;
DWORD dwRes;
if ( m_fCfgExcluded != IsExcluded() )
{
if ( m_fCfgExcluded )
{
WCHAR szTitle[MAX_STR];
WCHAR szMsg[MAX_STR+2*MAX_PATH];
// Confirm if it's ok to turn drive or SR off.
::LoadString( g_hInst, IDS_SYSTEMRESTORE, szTitle,
sizeof(szTitle)/sizeof(WCHAR) );
if ( IsSystem() )
::LoadString( g_hInst, IDS_CONFIRM_TURN_SR_OFF, szMsg,
sizeof(szMsg)/sizeof(WCHAR) );
else
{
::SRFormatMessage( szMsg, IDS_CONFIRM_TURN_DRV_OFF, GetLabel() ? GetLabel() : L"", GetMount() );
}
if ( ::MessageBox( hWnd, szMsg, szTitle, MB_YESNO ) == IDNO )
{
m_fCfgExcluded = IsExcluded();
goto Exit;
}
//
// if disabling all of SR, close the wizard if open
//
if (IsSystem())
{
CloseRestoreUI();
}
dwRes = ::DisableSR( m_strID );
if ( dwRes != ERROR_SUCCESS )
{
ShowSRErrDlg (IDS_ERR_SR_ON_OFF);
cszErr = ::GetSysErrStr( dwRes );
ErrorTrace(0, "::DisableSR failed - %ls", cszErr);
goto Exit;
}
m_dwFlags |= RDIF_EXCLUDED;
}
else
{
//
// make a synchronous call to enable sr
// this will block till the firstrun checkpoint is created
// and the service is fully initialized
//
dwRes = ::EnableSREx( m_strID, TRUE );
if ( dwRes != ERROR_SUCCESS )
{
ShowSRErrDlg (IDS_ERR_SR_ON_OFF);
cszErr = ::GetSysErrStr( dwRes );
ErrorTrace(0, "::EnableSR failed - %ls", cszErr);
goto Exit;
}
m_dwFlags &= ~RDIF_EXCLUDED;
}
}
if ( m_uCfgDSUsage != m_uDSUsage )
{
if (m_llDSMax - m_llDSMin > 0)
llUsage = m_llDSMin + (m_llDSMax - m_llDSMin)* m_uCfgDSUsage /DSUSAGE_SLIDER_FREQ;
else
llUsage = m_llDSMin;
dwRes = ::SRUpdateDSSize( m_strID, llUsage );
if ( dwRes != ERROR_SUCCESS )
{
LPCWSTR cszErr = ::GetSysErrStr( dwRes );
ErrorTrace(0, "::SRUpdateDriveTable failed - %ls", cszErr);
goto Exit;
}
m_uDSUsage = m_uCfgDSUsage;
}
fRet = TRUE;
Exit:
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
CRstrDriveInfo::Release()
{
TraceFunctEnter("CRstrDriveInfo::Release");
delete this;
TraceFunctLeave();
return( TRUE );
}
/////////////////////////////////////////////////////////////////////////////
//
// Helper Function
//
/////////////////////////////////////////////////////////////////////////////
//
// Enumerate Volumes without Drive Table if SR is disabled and DS not exists.
//
BOOL
EnumVolumes( CRDIArray &aryDrv )
{
TraceFunctEnter("EnumVolumes");
BOOL fRet = FALSE;
LPCWSTR cszErr;
HANDLE hEnumVol = INVALID_HANDLE_VALUE;
WCHAR szVolume[MAX_PATH];
WCHAR szMount[MAX_PATH];
DWORD cbMount;
CRstrDriveInfo *pDrv = NULL;
DWORD dwFlags;
hEnumVol = ::FindFirstVolume( szVolume, MAX_PATH );
if ( hEnumVol == INVALID_HANDLE_VALUE )
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "::FindFirstVolume failed - %ls", cszErr);
goto Exit;
}
// dummy space for system drive
if ( !aryDrv.AddItem( NULL ) )
goto Exit;
do
{
HANDLE hfDrv;
DebugTrace(0, "Guid=%ls", szVolume);
if ( !::GetVolumePathNamesForVolumeName( szVolume, szMount, MAX_PATH, &cbMount ) && GetLastError() != ERROR_MORE_DATA)
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "::GetVolumePathNamesForVolumeName failed - %ls", cszErr);
continue;
}
else
{
szMount[MAX_PATH-1] = L'\0';
if (lstrlenW (szMount) > MAX_MOUNTPOINT_PATH)
continue;
}
DebugTrace(0, " Mount=%ls", szMount);
if ( ::GetDriveType( szMount ) != DRIVE_FIXED )
{
DebugTrace(0, "Non-fixed drive");
// includes only the fixed drives.
continue;
}
hfDrv = ::CreateFile( szVolume, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL );
if ( hfDrv == INVALID_HANDLE_VALUE )
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "::CreateFile(volume) failed - %ls", cszErr);
// probably an unformatted drive.
continue;
}
::CloseHandle( hfDrv );
pDrv = new CRstrDriveInfo;
if ( pDrv == NULL )
{
FatalTrace(0, "Insufficient memory...");
goto Exit;
}
dwFlags = RDIF_EXCLUDED;
if ( ::IsSystemDrive( szVolume ) )
{
dwFlags |= RDIF_SYSTEM;
if ( !aryDrv.SetItem( 0, pDrv ) )
goto Exit;
}
else
{
if ( !aryDrv.AddItem( pDrv ) )
goto Exit;
}
if ( !pDrv->Init( szVolume, dwFlags, 0, szMount, NULL ) )
goto Exit;
pDrv = NULL;
}
while ( ::FindNextVolume( hEnumVol, szVolume, MAX_PATH ) );
fRet = TRUE;
Exit:
if ( pDrv != NULL )
if ( hEnumVol != INVALID_HANDLE_VALUE )
::FindVolumeClose( hEnumVol );
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
LoadDriveTable( LPCWSTR cszRPDir, CRDIArray &aryDrv, BOOL fRemoveDrives)
{
TraceFunctEnter("LoadDriveTable");
BOOL fRet = FALSE;
LPCWSTR cszErr;
WCHAR szDTFile[MAX_PATH];
DWORD dwRes;
CDriveTable cDrvTable;
SDriveTableEnumContext sDTEnum = { NULL, 0 };
CDataStore *pDS;
CRstrDriveInfo *pDrv = NULL;
BOOL fOffline;
::MakeRestorePath( szDTFile, s_szSysDrv, cszRPDir );
::PathAppend( szDTFile, s_cszDriveTable );
DebugTrace(0, "Loading drive table - %ls", szDTFile);
dwRes = cDrvTable.LoadDriveTable( szDTFile );
if ( dwRes != ERROR_SUCCESS )
{
cszErr = ::GetSysErrStr( dwRes );
ErrorTrace(0, "Cannot load a drive table - %ls", cszErr);
ErrorTrace(0, " szDTFile: '%ls'", szDTFile);
goto Exit;
}
// If this is for the current drive table, try to update information
// about removed volumes.
if ( cszRPDir == NULL )
{
if (fRemoveDrives)
cDrvTable.RemoveDrivesFromTable();
else
{
sDTEnum.Reset();
pDS = cDrvTable.FindFirstDrive (sDTEnum);
while (pDS != NULL)
{
pDS->IsVolumeDeleted(); // mark deleted volumes as inactive
pDS = cDrvTable.FindNextDrive( sDTEnum );
}
}
}
sDTEnum.Reset();
pDS = cDrvTable.FindFirstDrive( sDTEnum );
while ( pDS != NULL )
{
int i;
LPCWSTR cszGuid = pDS->GetGuid();
DebugTrace(0, "Drive: %ls %ls", pDS->GetDrive(), cszGuid);
if ( cszRPDir != NULL ) // not the current restore point
{
for ( i = aryDrv.GetUpperBound(); i >= 0; i-- )
{
CRstrDriveInfo *pExist = aryDrv.GetItem( i );
if ( ::lstrcmpi( cszGuid, pExist->GetID() ) == 0 )
{
// Match has been found. Check if it's offline, in which
// case mount point and volume label should be updated to the
// latest ones.
if ( pExist->IsOffline() )
pExist->SetMountAndLabel( pDS->GetDrive(), pDS->GetLabel() );
break;
}
pDrv = NULL;
}
if ( i >= 0 )
goto NextDrv;
}
pDrv = new CRstrDriveInfo;
if ( pDrv == NULL )
{
FatalTrace(0, "Insufficient memory...");
goto Exit;
}
//
// mark a drive as offline if it's not in the current restore point
// or it's inactive in the current restore point
//
fOffline = (cszRPDir != NULL) || !(pDS->GetFlags() & SR_DRIVE_ACTIVE);
if ( !pDrv->Init( cszGuid, pDS, fOffline ) )
goto Exit;
if (( pDrv->GetMount() == NULL ) || ( (pDrv->GetMount())[0] == L'\0' ))
{
pDrv->Release();
goto NextDrv;
}
if ( pDrv->IsSystem() )
{
if ( !aryDrv.SetItem( 0, pDrv ) )
goto Exit;
}
else
{
if ( !aryDrv.AddItem( pDrv ) )
goto Exit;
}
pDrv = NULL;
NextDrv:
pDS = cDrvTable.FindNextDrive( sDTEnum );
}
fRet = TRUE;
Exit:
if ( !fRet )
SAFE_RELEASE(pDrv);
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
BOOL
UpdateDriveList( CRDIArray &aryDrv )
{
TraceFunctEnter("UpdateDriveTable");
BOOL fRet = FALSE;
LPCWSTR cszErr;
DWORD dwDisable = 0;
WCHAR szDTFile[MAX_PATH];
DWORD dwRes;
CDriveTable cDrvTable;
CDataStore *pDS;
CRstrDriveInfo *pDrv;
int i;
// Check if SR is disabled
if ( ::SRGetRegDword( HKEY_LOCAL_MACHINE, s_cszSRRegKey, s_cszDisableSR, &dwDisable ) )
if ( dwDisable != 0 )
{
for ( i = aryDrv.GetUpperBound(); i >= 0; i-- )
{
pDrv = (CRstrDriveInfo*)aryDrv[i];
pDrv->UpdateStatus( SR_DRIVE_FROZEN, FALSE );
}
goto Done;
}
::MakeRestorePath( szDTFile, s_szSysDrv, NULL );
::PathAppend( szDTFile, s_cszDriveTable );
DebugTrace(0, "Loading drive table - %ls", szDTFile);
dwRes = cDrvTable.LoadDriveTable( szDTFile );
if ( dwRes != ERROR_SUCCESS )
{
cszErr = ::GetSysErrStr( dwRes );
ErrorTrace(0, "Cannot load a drive table - %ls", cszErr);
ErrorTrace(0, " szDTFile: '%ls'", szDTFile);
goto Exit;
}
dwRes = cDrvTable.RemoveDrivesFromTable();
if ( dwRes != ERROR_SUCCESS )
{
cszErr = ::GetSysErrStr( dwRes );
ErrorTrace(0, "CDriveTable::RemoveDrivesFromTable failed - %ls", cszErr);
// ignore error
}
for ( i = aryDrv.GetUpperBound(); i >= 0; i-- )
{
pDrv = (CRstrDriveInfo*)aryDrv[i];
pDS = cDrvTable.FindGuidInTable( (LPWSTR)pDrv->GetID() );
if ( ( pDS == NULL ) || ( pDS->GetDrive() == NULL ) || ( (pDS->GetDrive())[0] == L'\0' ) )
pDrv->UpdateStatus( 0, TRUE );
else
pDrv->UpdateStatus( pDS->GetFlags(), FALSE );
}
Done:
fRet = TRUE;
Exit:
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
//
// CreateAndLoadDriveInfoInstance
//
// This routine creates a CRstrDriveInfo class instance and load the content
// from a log file.
//
/////////////////////////////////////////////////////////////////////////////
BOOL
CreateAndLoadDriveInfoInstance( HANDLE hfLog, CRstrDriveInfo **ppRDI )
{
TraceFunctEnter("CreateAndLoadDriveInfoInstance");
BOOL fRet = FALSE;
CRstrDriveInfo *pRDI=NULL;
if ( ppRDI == NULL )
{
ErrorTrace(0, "Invalid parameter, ppRDI is NULL.");
goto Exit;
}
*ppRDI = NULL;
pRDI = new CRstrDriveInfo;
if ( pRDI == NULL )
{
ErrorTrace(0, "Insufficient memory...");
goto Exit;
}
if ( !pRDI->LoadFromLog( hfLog ) )
goto Exit;
*ppRDI = pRDI;
fRet = TRUE;
Exit:
if ( !fRet )
SAFE_RELEASE(pRDI);
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
//
// CreateDriveList
//
// This routine creates a drive list consists of CDriveInfo class instances.
//
/////////////////////////////////////////////////////////////////////////////
BOOL
CreateDriveList( int nRP, CRDIArray &aryDrv, BOOL fRemoveDrives )
{
TraceFunctEnter("CreateDriveList");
BOOL fRet = FALSE;
LPCWSTR cszErr;
DWORD fDisable;
if ( !::GetSystemDrive( s_szSysDrv ) )
{
cszErr = ::GetSysErrStr();
ErrorTrace(0, "Cannot get system drive - %ls", cszErr);
goto Exit;
}
DebugTrace(0, "SystemDrive=%ls", s_szSysDrv);
// Check if SR is disabled
if ( !::SRGetRegDword( HKEY_LOCAL_MACHINE, s_cszSRRegKey, s_cszDisableSR, &fDisable ) )
{
DebugTrace(0, "Cannot get disable reg key");
goto Exit;
}
if ( fDisable )
{
DebugTrace(0, "SR is DISABLED!!!");
// Enumerate instead of reading drive table...
if ( !EnumVolumes( aryDrv ) )
goto Exit;
}
else
{
// dummy space for system drive
if ( !aryDrv.AddItem( NULL ) )
goto Exit;
// process the current drive table...
if ( !LoadDriveTable( NULL, aryDrv, fRemoveDrives ) )
{
DebugTrace(0, "Loading current drive table failed");
goto Exit;
}
if ( nRP > 0 )
{
CRestorePointEnum cEnum( s_szSysDrv, FALSE, FALSE );
CRestorePoint cRP;
DWORD dwRes;
dwRes = cEnum.FindFirstRestorePoint( cRP );
if ( dwRes != ERROR_SUCCESS && dwRes != ERROR_FILE_NOT_FOUND )
{
cszErr = ::GetSysErrStr(dwRes);
ErrorTrace(0, "CRestorePointEnum::FindFirstRestorePoint failed - %ls", cszErr);
goto Exit;
}
while ( (dwRes == ERROR_SUCCESS || dwRes == ERROR_FILE_NOT_FOUND) && ( cRP.GetNum() >= nRP ))
{
dwRes = cEnum.FindNextRestorePoint( cRP );
if ( dwRes == ERROR_NO_MORE_ITEMS )
break;
if ( dwRes != ERROR_SUCCESS && dwRes != ERROR_FILE_NOT_FOUND )
{
cszErr = ::GetSysErrStr(dwRes);
ErrorTrace(0, "CRestorePointEnum::FindNextRestorePoint failed - %ls", cszErr);
goto Exit;
}
DebugTrace(0, "RPNum=%d", cRP.GetNum());
if ( cRP.GetNum() >= nRP )
{
// process drive table of each RP...
if ( !LoadDriveTable( cRP.GetDir(), aryDrv, fRemoveDrives))
{
// The last restore point does not have drive table...
// simply ignore it.
}
}
}
}
}
fRet = TRUE;
Exit:
TraceFunctLeave();
return( fRet );
}
// end of file
|
94f7e677a482c2d094040298efca52982e94c3f6
|
f914562ea4f7899684589c04cfdaeb27d9d9cd21
|
/ogsr_engine/xrGame/interactive_motion.h
|
2980a464e57374bb2c0d6b01f71582137da704be
|
[
"Apache-2.0"
] |
permissive
|
Graff46/OGSR-Engine
|
4e9a0ed0380edf1b34264db47a87db94c5fb6fc2
|
acdc51354a7d273bf211ec3cc700253f68252cdb
|
refs/heads/main
| 2023-08-08T11:52:20.252179
| 2023-01-17T10:54:26
| 2023-01-17T19:36:21
| 235,670,325
| 2
| 2
|
Apache-2.0
| 2023-08-19T18:22:37
| 2020-01-22T21:26:28
|
C++
|
UTF-8
|
C++
| false
| false
| 1,434
|
h
|
interactive_motion.h
|
#pragma once
#include "..\Include/xrRender/KinematicsAnimated.h"
class CPhysicsShell;
class interactive_motion
{
MotionID motion;
protected:
Flags8 flags;
enum Flag
{
fl_use_death_motion = 1 << 4,
fl_switch_dm_toragdoll = 1 << 5
};
public:
interactive_motion();
void init();
void setup(LPCSTR m, CPhysicsShell* s);
void setup(MotionID m, CPhysicsShell* s);
void update(CPhysicsShell* s);
IC bool is_enabled() { return !!flags.test(fl_use_death_motion); }
void play(CPhysicsShell* s);
private:
virtual void move_update(CPhysicsShell* s) = 0;
virtual void collide(CPhysicsShell* s) = 0;
protected:
virtual void state_end(CPhysicsShell* s);
virtual void state_start(CPhysicsShell* s);
private:
void switch_to_free(CPhysicsShell* s);
static void anim_callback(CBlend* B);
};
class imotion_velocity : public interactive_motion
{
typedef interactive_motion inherited;
virtual void move_update(CPhysicsShell* s);
virtual void collide(CPhysicsShell* s);
virtual void state_end(CPhysicsShell* s);
virtual void state_start(CPhysicsShell* s);
};
class imotion_position : public interactive_motion
{
typedef interactive_motion inherited;
virtual void move_update(CPhysicsShell* s);
virtual void collide(CPhysicsShell* s);
virtual void state_end(CPhysicsShell* s);
virtual void state_start(CPhysicsShell* s);
};
|
831d19377b9d7ae7b7f68c5dd66c5a318b1e6a46
|
b81caf94710fd45613f1da2f61b1ca2f09d16de6
|
/0121.买卖股票的最佳时机/0121-买卖股票的最佳时机.cpp
|
708e7ee5a9d6c26dd2fbd57f651f41456f253da2
|
[] |
no_license
|
KatePang13/leetcode-pang
|
64c5dcf96f60930ea8d4408f16e8cac327415390
|
ce1fa371f2821cc06169cbb35ef0a251c9f7ea7f
|
refs/heads/master
| 2023-04-14T23:19:12.104426
| 2021-04-27T06:13:49
| 2021-04-27T06:13:49
| 280,997,684
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 369
|
cpp
|
0121-买卖股票的最佳时机.cpp
|
class Solution {
public:
int maxProfit(vector<int>& prices) {
int last = 0;
int profit = 0;
if( prices.size() <2 ){
return 0;
}
for( int i=0; i< prices.size()-1; i++ ){
last = max( 0, last+prices[i+1] - prices[i] );
profit = max( profit, last );
}
return profit;
}
};
|
29bca84e3f4dd433ff0ab35bd123768a4a8a379e
|
d5f7eccd40734676546f7d3692f09074c9088d63
|
/TwistPong/game_state_start.cpp
|
3a19fb7c75793a5f3230f4197bfcedb49ed1b2fd
|
[] |
no_license
|
JDuchniewicz/TwistPong
|
f83fde0830468e51f3695551af53a55b69e113db
|
78f4b96c4e7bd00606d52cc69c99ad225dbfbf80
|
refs/heads/master
| 2021-07-08T22:18:20.424758
| 2017-10-09T13:23:04
| 2017-10-09T13:23:04
| 106,265,527
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,517
|
cpp
|
game_state_start.cpp
|
#include "game_state_start.hpp"
#include <iostream>
#include "game_state_ai.hpp"
void GameStateStart::draw()
{
this->game->window.setView(this->view);
this->game->window.clear(sf::Color::Black);
this->game->window.draw(this->game->background);
}
void GameStateStart::update()
{
}
void GameStateStart::handleInput()
{
sf::Event event;
while(game->window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
game->window.close();
break;
case sf::Event::Resized:
this->view.setSize(event.size.width, event.size.height);
break;
case sf::Event::KeyPressed:
if(event.key.code == sf::Keyboard::Space)
{
std::cout << "space pressed" << std::endl;
}
else if (event.key.code == sf::Keyboard::A)
{
std::cout << "a pressed" << std::endl;
loadGame("AI");
}
else if (event.key.code == sf::Keyboard::Escape) this->game->window.close();
break;
//TODO:: add gui system for the menu and add loading from there not with key
}
}
}
void GameStateStart::checkCollisions()
{
}
GameStateStart::GameStateStart(Game* game)
{
this->game = game;
sf::Vector2f pos = sf::Vector2f(this->game->window.getSize());
this->view.setSize(pos);
pos *= 0.5f;
this->view.setCenter(pos);
if(!music.openFromFile("media/track1.ogg"))
{
std::cout << "cannot open music file" << std::endl;
}
//music.play();
}
void GameStateStart::loadGame(std::string name)
{
if (name == "AI")
{
this->game->pushState(new GameStateAI(this->game));
}
return;
}
|
63fc643a3651e113d6281867b2ab4e16e3a9af80
|
6107c96e068e3df8d65832730fe368600defabca
|
/src/observer.cc
|
08f2598f3e14c8a25b25a440ab497c4e65afba74
|
[] |
no_license
|
i-Zaak/tvb-pdde
|
708b6d440d92c574a3e204993316f74f31a21864
|
5648833b612a7ed0f028e1e3080eecc4c34d8201
|
refs/heads/master
| 2020-12-25T20:21:11.465148
| 2016-02-29T13:29:15
| 2016-02-29T13:29:15
| 47,503,929
| 0
| 0
| null | 2016-02-29T13:29:15
| 2015-12-06T16:15:06
|
C++
|
UTF-8
|
C++
| false
| false
| 551
|
cc
|
observer.cc
|
#include "observer.h"
raw_observer::raw_observer(unsigned long nodes, unsigned long steps)
{
this->observation = global_solution_type(nodes);
if (steps >0){
for( global_solution_type::size_type i=0;
i < this->observation.size();
i++){
this->observation[i].reserve(steps);
}
}
}
void raw_observer::operator()(unsigned long node, local_state_type &state, double time )
{
this->observation[node].push_back( std::make_pair(time, state) );
}
const global_solution_type &raw_observer::get_solution( )
{
return this->observation;
}
|
76b3956212b0f9768e3ff5c4bd340115406dc064
|
df0d7d165d8f83ecafaccfca5c566bc00d01d8af
|
/algo-W10-letter_springs/src/letter.cpp
|
4b8183293227786599a41a2d207cc2926a4a9f1d
|
[] |
no_license
|
esrutledge/Algo_Fall_2011
|
defeeb153db26a8b91528a1a4fe0e7e29e2bca61
|
04c676a6a8dbdd7184a1fb0f57ad9c42846f4f71
|
refs/heads/master
| 2021-01-22T09:48:48.563745
| 2011-12-24T03:17:37
| 2011-12-24T03:17:37
| 2,362,295
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,465
|
cpp
|
letter.cpp
|
//
// letter.cpp
// algo_wk9
//
// Created by Elizabeth Rutledge on 11/15/11.
// Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//
//#include <iostream>
#include "letter.h"
letter::letter() {
startingX = ofGetWidth()/2;
}
void letter::setup() {
myFont.loadFont("GothamHTF-Bold.otf", 150, true,true,true);
testChar = myFont.getCharacterAsPoints(theLetter);
ofPolyline line;
for(int k = 0; k < 1; k++){
//if( k!= 0)ofNextContour(true) ;
for(int i = 0; i < (int)testChar.getOutline()[k].size(); i++){
ofPoint pos;
pos.x = testChar.getOutline()[k].getVertices()[i].x;
pos.y = testChar.getOutline()[k].getVertices()[i].y;
line.addVertex(pos);
}
}
line.addVertex(testChar.getOutline()[0][0]);
ofPolyline lineResampled = line.getResampledBySpacing(10);
ofSetColor(255);
lineResampled.draw();
for (int i = 0; i < lineResampled.getVertices().size(); i++){
float x = startingX + lineResampled.getVertices()[i].x;
float y = 100 + lineResampled.getVertices()[i].y;
particle myParticle;
myParticle.setInitialCondition(x,y,0,0);
particles.push_back(myParticle);
}
for (int i = 0; i < particles.size(); i++){
spring mySpring;
mySpring.distance = 10;
mySpring.springiness = 0.1f;
mySpring.particleA = & (particles[i]);
mySpring.particleB = & (particles[(i+1)%particles.size()]);
springs.push_back(mySpring);
}
for (int i = 0; i < particles.size(); i++){
spring mySpring;
float dist = (particles[i].pos - particles[(i+10)%particles.size()].pos).length();
mySpring.distance = dist;
mySpring.springiness = 0.1f;
mySpring.particleA = & (particles[i]);
mySpring.particleB = & (particles[(i+10)%particles.size()]);
springs.push_back(mySpring);
}
for (int i = 0; i < particles.size(); i++){
spring mySpring;
float dist = (particles[i].pos - particles[(i+20)%particles.size()].pos).length();
mySpring.distance = dist;
mySpring.springiness = 0.1f;
mySpring.particleA = & (particles[i]);
mySpring.particleB = & (particles[(i+20)%particles.size()]);
springs.push_back(mySpring);
}
//particles[particles.size()-1].bFixed = true;
}
void letter::update() {
// on every frame
// we reset the forces
// add in any forces on the particle
// perfom damping and
// then update
for (int i = 0; i < particles.size(); i++){
particles[i].resetForce();
}
for (int i = 0; i < particles.size(); i++){
particles[i].addForce(0,0.3);
particles[i].addRepulsionForce(mouseX, mouseY, 300, 1.5);
}
for (int i = 0; i < springs.size(); i++){
springs[i].update();
}
for (int i = 0; i < particles.size(); i++){
particles[i].bounceOffWalls();
particles[i].addDampingForce();
particles[i].update();
}
}
void letter::draw() {
ofSetColor(255,153,0);
ofFill();
//ofBeginShape();
for (int i = 0; i < particles.size(); i++){
// ofVertex(particles[i].pos.x, particles[i].pos.y);
particles[i].draw();
}
//ofEndShape(true);
for (int i = 0; i < springs.size(); i++){
if(i < springs.size()/3 ){
ofSetColor(255,64,0);
}
else {
ofSetColor(0,0,0,0);
}
springs[i].draw();
}
ofNoFill();
// ofBeginShape();
// for (int i = 0; i < trail.size(); i++){
// ofVertex(trail[i].x, trail[i].y);
// }
// ofEndShape();
}
|
d3220c721854828784d419217a9540ddc9a731c2
|
5e561d21184a0f006892201c10129bbba1795b11
|
/streams/block/ciphers/lightweight/lblock/lblock.cc
|
4c7887f57eef2d08f65da219a713eff3faf481b7
|
[
"MIT"
] |
permissive
|
crocs-muni/CryptoStreams
|
c5bf432a14aa161ff2aa6dbfa38448152293ebb1
|
b92d96ad16679c24a9402b0d33378d1f318db23a
|
refs/heads/master
| 2022-11-13T06:57:04.333740
| 2022-11-11T20:44:47
| 2022-11-11T20:48:36
| 84,541,435
| 9
| 5
|
MIT
| 2022-11-11T20:48:37
| 2017-03-10T09:11:32
|
C
|
UTF-8
|
C++
| false
| false
| 29,060
|
cc
|
lblock.cc
|
//
// Created by mhajas on 7/8/18.
//
#include "lblock.h"
void block::lblock::keysetup(const std::uint8_t *key, const std::uint64_t keysize) {
uint16_t shiftedKey[2];
uint8_t keyCopy[LBLOCK_KEY_SIZE];
uint16_t *Key = (uint16_t *)key;
uint32_t *RoundKeys = (uint32_t *)_key;
uint16_t *KeyCopy = (uint16_t *)keyCopy;
KeyCopy[4] = Key[4];
KeyCopy[3] = Key[3];
KeyCopy[2] = Key[2];
KeyCopy[1] = Key[1];
KeyCopy[0] = Key[0];
/* Set round subkey K(1) */
RoundKeys[0] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(2) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x00;
keyCopy[5] = keyCopy[5] ^ 0x40;
/* (d) Set the round subkey K(i+1) */
RoundKeys[1] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(2) - End */
/* Set round subkey K(3) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x00;
keyCopy[5] = keyCopy[5] ^ 0x80;
/* (d) Set the round subkey K(i+1) */
RoundKeys[2] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(3) - End */
/* Set round subkey K(4) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x00;
keyCopy[5] = keyCopy[5] ^ 0xC0;
/* (d) Set the round subkey K(i+1) */
RoundKeys[3] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(4) - End */
/* Set round subkey K(5) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x01;
keyCopy[5] = keyCopy[5] ^ 0x00;
/* (d) Set the round subkey K(i+1) */
RoundKeys[4] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(5) - End */
/* Set round subkey K(6) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x01;
keyCopy[5] = keyCopy[5] ^ 0x40;
/* (d) Set the round subkey K(i+1) */
RoundKeys[5] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(6) - End */
/* Set round subkey K(7) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x01;
keyCopy[5] = keyCopy[5] ^ 0x80;
/* (d) Set the round subkey K(i+1) */
RoundKeys[6] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(7) - End */
/* Set round subkey K(8) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x01;
keyCopy[5] = keyCopy[5] ^ 0xC0;
/* (d) Set the round subkey K(i+1) */
RoundKeys[7] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(8) - End */
/* Set round subkey K(9) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];;
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x02;
keyCopy[5] = keyCopy[5] ^ 0x00;
/* (d) Set the round subkey K(i+1) */
RoundKeys[8] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(9) - End */
/* Set round subkey K(10) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x02;
keyCopy[5] = keyCopy[5] ^ 0x40;
/* (d) Set the round subkey K(i+1) */
RoundKeys[9] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(10) - End */
/* Set round subkey K(11) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x02;
keyCopy[5] = keyCopy[5] ^ 0x80;
/* (d) Set the round subkey K(i+1) */
RoundKeys[10] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(11) - End */
/* Set round subkey K(12) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x02;
keyCopy[5] = keyCopy[5] ^ 0xC0;
/* (d) Set the round subkey K(i+1) */
RoundKeys[11] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(12) - End */
/* Set round subkey K(13) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x03;
keyCopy[5] = keyCopy[5] ^ 0x00;
/* (d) Set the round subkey K(i+1) */
RoundKeys[12] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(13) - End */
/* Set round subkey K(14) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x03;
keyCopy[5] = keyCopy[5] ^ 0x40;
/* (d) Set the round subkey K(i+1) */
RoundKeys[13] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(14) - End */
/* Set round subkey K(15) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x03;
keyCopy[5] = keyCopy[5] ^ 0x80;
/* (d) Set the round subkey K(i+1) */
RoundKeys[14] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(15) - End */
/* Set round subkey K(16) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x03;
keyCopy[5] = keyCopy[5] ^ 0xC0;
/* (d) Set the round subkey K(i+1) */
RoundKeys[15] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(16) - End */
/* Set round subkey K(17) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x04;
keyCopy[5] = keyCopy[5] ^ 0x00;
/* (d) Set the round subkey K(i+1) */
RoundKeys[16] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(17) - End */
/* Set round subkey K(18) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x04;
keyCopy[5] = keyCopy[5] ^ 0x40;
/* (d) Set the round subkey K(i+1) */
RoundKeys[17] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(18) - End */
/* Set round subkey K(19) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x04;
keyCopy[5] = keyCopy[5] ^ 0x80;
/* (d) Set the round subkey K(i+1) */
RoundKeys[18] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(19) - End */
/* Set round subkey K(20) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x04;
keyCopy[5] = keyCopy[5] ^ 0xC0;
/* (d) Set the round subkey K(i+1) */
RoundKeys[19] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(20) - End */
/* Set round subkey K(21) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x05;
keyCopy[5] = keyCopy[5] ^ 0x00;
/* (d) Set the round subkey K(i+1) */
RoundKeys[20] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(21) - End */
/* Set round subkey K(22) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x05;
keyCopy[5] = keyCopy[5] ^ 0x40;
/* (d) Set the round subkey K(i+1) */
RoundKeys[21] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(22) - End */
/* Set round subkey K(23) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x05;
keyCopy[5] = keyCopy[5] ^ 0x80;
/* (d) Set the round subkey K(i+1) */
RoundKeys[22] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(23) - End */
/* Set round subkey K(24) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x05;
keyCopy[5] = keyCopy[5] ^ 0xC0;
/* (d) Set the round subkey K(i+1) */
RoundKeys[23] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(24) - End */
/* Set round subkey K(25) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x06;
keyCopy[5] = keyCopy[5] ^ 0x00;
/* (d) Set the round subkey K(i+1) */
RoundKeys[24] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(25) - End */
/* Set round subkey K(26) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x06;
keyCopy[5] = keyCopy[5] ^ 0x40;
/* (d) Set the round subkey K(i+1) */
RoundKeys[25] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(26) - End */
/* Set round subkey K(27) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x06;
keyCopy[5] = keyCopy[5] ^ 0x80;
/* (d) Set the round subkey K(i+1) */
RoundKeys[26] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(27) - End */
/* Set round subkey K(28) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x06;
keyCopy[5] = keyCopy[5] ^ 0xC0;
/* (d) Set the round subkey K(i+1) */
RoundKeys[27] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(28) - End */
/* Set round subkey K(29) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x07;
keyCopy[5] = keyCopy[5] ^ 0x00;
/* (d) Set the round subkey K(i+1) */
RoundKeys[28] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(29) - End */
/* Set round subkey K(30) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x07;
keyCopy[5] = keyCopy[5] ^ 0x40;
/* (d) Set the round subkey K(i+1) */
RoundKeys[29] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(30) - End */
/* Set round subkey K(31) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x07;
keyCopy[5] = keyCopy[5] ^ 0x80;
/* (d) Set the round subkey K(i+1) */
RoundKeys[30] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(31) - End */
/* Set round subkey K(32) - Begin */
/* (a) K <<< 29 */
shiftedKey[1] = KeyCopy[4];
shiftedKey[0] = KeyCopy[3];
KeyCopy[4] = (KeyCopy[3] << 13) ^ (KeyCopy[2] >> 3);
KeyCopy[3] = (KeyCopy[2] << 13) ^ (KeyCopy[1] >> 3);
KeyCopy[2] = (KeyCopy[1] << 13) ^ (KeyCopy[0] >> 3);
KeyCopy[1] = (KeyCopy[0] << 13) ^ (shiftedKey[1] >> 3);
KeyCopy[0] = (shiftedKey[1] << 13) ^ (shiftedKey[0] >> 3);
/* (b) S-boxes */
keyCopy[9] = (READ_SBOX_BYTE(S9[keyCopy[9] >> 4]) << 4) ^ READ_SBOX_BYTE(S8[(keyCopy[9] & 0x0F)]);
/* (c) XOR */
keyCopy[6] = keyCopy[6] ^ 0x07;
keyCopy[5] = keyCopy[5] ^ 0xC0;
/* (d) Set the round subkey K(i+1) */
RoundKeys[31] = (((uint32_t)KeyCopy[4]) << 16) ^ (uint32_t)KeyCopy[3];
/* Set round subkey K(32) - End */}
void block::lblock::Encrypt(uint8_t *block) {
uint8_t temp[4];
uint8_t p[4];
uint8_t *x = block;
uint8_t *k = _key;
uint32_t *X = (uint32_t *) x;
uint32_t *K = (uint32_t *) k;
uint32_t *Temp = (uint32_t *) temp;
/* Save a copy of the left half of X */
Temp[0] = X[1];
for (auto i = 1; i <= _rounds; i++) {
if (i % 2 == 0) {
X[0] = Temp[0];
} else {
/* Save a copy of the left half of X */
X[1] = Temp[0];
}
/* XOR X left half with the round key: X XOR K(j) */
Temp[0] = Temp[0] ^ READ_ROUND_KEY_DOUBLE_WORD(K[i - 1]);
/* (2) Confusion function S: S(X XOR K(i)) */
temp[3] = (READ_SBOX_BYTE(S7[temp[3] >> 4]) << 4) ^ READ_SBOX_BYTE(S6[temp[3] & 0x0F]);
temp[2] = (READ_SBOX_BYTE(S5[temp[2] >> 4]) << 4) ^ READ_SBOX_BYTE(S4[temp[2] & 0x0F]);
temp[1] = (READ_SBOX_BYTE(S3[temp[1] >> 4]) << 4) ^ READ_SBOX_BYTE(S2[temp[1] & 0x0F]);
temp[0] = (READ_SBOX_BYTE(S1[temp[0] >> 4]) << 4) ^ READ_SBOX_BYTE(S0[temp[0] & 0x0F]);
/* (3) Diffusion function P: P(S(X XOR K(i))) */
p[3] = (temp[3] << 4) ^ (temp[2] & 0x0F);
p[2] = (temp[3] & 0xF0) ^ (temp[2] >> 4);
p[1] = (temp[1] << 4) ^ (temp[0] & 0x0F);
p[0] = (temp[1] & 0xF0) ^ (temp[0] >> 4);
if (i % 2 == 0) {
/* F(X(i-1), K(i-1)) XOR (X(i-2) <<< 8) */
temp[3] = p[3] ^ x[6];
temp[2] = p[2] ^ x[5];
temp[1] = p[1] ^ x[4];
temp[0] = p[0] ^ x[7];
} else {
/* F(X(i-1), K(i-1)) XOR (X(i-2) <<< 8) */
temp[3] = p[3] ^ x[2];
temp[2] = p[2] ^ x[1];
temp[1] = p[1] ^ x[0];
temp[0] = p[0] ^ x[3];
}
}
X[1] = X[0];
X[0] = Temp[0];
}
void block::lblock::Decrypt(uint8_t *block) {
uint8_t temp[4];
uint8_t p[4];
uint8_t *x = block;
uint8_t *k = _key;
uint32_t *X = (uint32_t *) x;
uint32_t *K = (uint32_t *) k;
uint32_t *Temp = (uint32_t *) temp;
/* Save a copy of the left half of X */
Temp[0] = X[1];
for (auto i = _rounds; i >= 1; i--) {
if (i % 2 != 0) {
X[0] = Temp[0];
} else {
X[1] = Temp[0];
}
/* XOR X left half with the round key: X XOR K(j) */
Temp[0] = Temp[0] ^ READ_ROUND_KEY_DOUBLE_WORD(K[i - 1]);
/* (2) Confusion function S: S(X XOR K(j)) */
temp[3] = (READ_SBOX_BYTE(S7[temp[3] >> 4]) << 4) ^ READ_SBOX_BYTE(S6[temp[3] & 0x0F]);
temp[2] = (READ_SBOX_BYTE(S5[temp[2] >> 4]) << 4) ^ READ_SBOX_BYTE(S4[temp[2] & 0x0F]);
temp[1] = (READ_SBOX_BYTE(S3[temp[1] >> 4]) << 4) ^ READ_SBOX_BYTE(S2[temp[1] & 0x0F]);
temp[0] = (READ_SBOX_BYTE(S1[temp[0] >> 4]) << 4) ^ READ_SBOX_BYTE(S0[temp[0] & 0x0F]);
/* (3) Diffusion function P: P(S(X XOR K(j))) */
p[3] = (temp[3] << 4) ^ (temp[2] & 0x0F);
p[2] = (temp[3] & 0xF0) ^ (temp[2] >> 4);
p[1] = (temp[1] << 4) ^ (temp[0] & 0x0F);
p[0] = (temp[1] & 0xF0) ^ (temp[0] >> 4);
if (i % 2 != 0) {
/* F(X(j+1), K(j+1)) XOR X(j+2)) >>> 8) */
temp[3] = x[4] ^ p[0];
temp[2] = x[7] ^ p[3];
temp[1] = x[6] ^ p[2];
temp[0] = x[5] ^ p[1];
} else {
/* F(X(j+1), K(j+1)) XOR X(j+2)) >>> 8) */
temp[3] = x[0] ^ p[0];
temp[2] = x[3] ^ p[3];
temp[1] = x[2] ^ p[2];
temp[0] = x[1] ^ p[1];
}
}
X[1] = X[0];
X[0] = Temp[0];
}
|
dfc559fac38698a4b24f1aab671404e98ed7021d
|
3e56d690a549585bcc74a6e242a2379cb870e77f
|
/fileio/fileio.cpp
|
fbf094d4a6b11e083514aabead3a7da52b019b8f
|
[] |
no_license
|
FXFY18/Proj_refactor_monolithic_file
|
8c1d3f3619738aa6fe9ea401c071c295dcb79b27
|
1e0aab614e082251e665779ca5940afac6b17d71
|
refs/heads/master
| 2022-12-19T01:58:57.346497
| 2020-09-26T16:12:35
| 2020-09-26T16:12:35
| 297,794,525
| 0
| 0
| null | 2020-09-22T23:12:04
| 2020-09-22T23:12:03
| null |
UTF-8
|
C++
| false
| false
| 575
|
cpp
|
fileio.cpp
|
/*
* fileio.cpp
* Ver: 9/24/2020
* Creator: Felix Phommachanh
*
*/
#include <iostream>
#include "../includes/fileio.h"
using namespace std;
//attempt to open file 'filename' and read in all data
//returns SUCCESS if all goes well or COULD_NOT_OPEN_FILE
int loadData(const std::string filename, vector<process> &myProcesses){
return UNIMPLEMENTED;
}
//attempt to create or open file 'filename' to write all data to
//returns SUCCESS if all goes well or COULD_NOT_OPEN_FILE
int saveData(const std::string filename, vector<process> &myProcesses){
return UNIMPLEMENTED;
}
|
1d9135a5f3c37ad2a3b628cf1f79d6bb072f9936
|
4d3bcc6440ce022d4d0e67dabfef1dadc358fb87
|
/20180221/namespace.cc
|
7e1297f19854cf9f2c5a9ddbe70767704754f445
|
[] |
no_license
|
Westringliu/wangdao_cpp
|
3b03b62fbda2f5ece6d41ff4a49154175683af31
|
e91669142cfa51f075442daf9631a49fe72fc606
|
refs/heads/master
| 2020-03-09T16:22:32.723620
| 2018-04-10T06:20:24
| 2018-04-10T06:20:24
| 128,883,098
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 383
|
cc
|
namespace.cc
|
//
/// @file namespace.cc
/// @author westring(1364643962@qq.com)
/// @date 2018-02-21 10:40:04
///
#include <iostream>
using std::cout;
using std::endl;
namespace B{
void displayB()
{
cout<<"displayB()"<<endl;
}
}
namespace A{
void displayA()
{
cout<<"displayA()"<<endl;
B::displayB();
}
}
int main(void)
{
A::displayA();
B::displayB();
return 0;
}
|
314b76da8e4db7ab609e8ac22b8aa1d834a51be7
|
013caff69e41c36c4efe9359c8ce2ecfb5f659ab
|
/Little Bishops.cpp
|
00f441bf49fe7ea5f8cfe434abacceade4899b3b
|
[] |
no_license
|
iamsile/ACM
|
cbe5754bed56b1abb3cfaed6b25b9bffa1ec04a5
|
d51e43780e33b51c70007ba0702448909f9d0553
|
refs/heads/master
| 2016-08-04T02:31:51.523885
| 2013-09-09T05:36:35
| 2013-09-09T05:36:35
| 12,693,702
| 9
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,805
|
cpp
|
Little Bishops.cpp
|
#include <iostream>
#include <stdio.h>
using namespace std;
const long table[9][65]={{0},{1,1},{1,4,4},{1,9,26,26,8},{1,16,92,232,260,112,16},
{1,25,240,1124,2728,3368,1960,440,32},{1,36,520,3896,16428,39680,53744,38368,12944,1600,64},
{1,49,994,10894,70792,282248,692320,1022320,867328,389312,81184,5792,128},{1,64,1736,26192,
242856,1444928,5599888,14082528,22522960,22057472,12448832,3672448,489536,20224,256}};
int main(){
int n,m;
while (scanf("%d%d",&n,&m)){
if (!n&&!m)
return 0;
printf("%ld\n", table[n][m]);
}
return 0;
}
/*
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstdio>
using namespace std;
int n,m,num;
void construct_candidates(int a[],int k,int c[],int *ncandidates)
{
*ncandidates=0;
int i,j,ans,bns,t,temp;
ans=k;
bns=0;
if(k>n) ans=2*n-k;
for(i=0; i<=ans; i++)
{
temp=1;
for(j=1; j<k&&i!=0; j++)
{
if(k%2!=j%2) continue;
if(a[j]==0) continue;
if(j>n) bns=2*n-j;
else bns=j;
if(k>n&&j>n)
{
t=(abs(j-k)/2);
if(t+i==a[j])
temp=0;
}
else if(k>n&&j<=n)
{
t=(abs(2*n-k-j)/2);
if(2*n-k<j)
{
if(i+t==a[j])
temp=0;
}
else
{
if(i==t+a[j])
temp=0;
}
}
else if(k<=n&&j<=n)
{
t=(abs(k-j)/2);
if(t+a[j]==i)
temp=0;
}
}
if(temp)
{
c[*ncandidates]=i;
*ncandidates=*ncandidates+1;
}
}
}
int is_a_solution(int k,int a[],int count)
{
if(count==m)
{
num++;
return 1;
}
else if(k==2*n-1)
return 1;
else return 0;
}
void backtrack( int a[], int k, int count)
{
int c[500],temp;
int ncandidates;
int i;
if(is_a_solution(k,a,count)==0)
{
k++;
construct_candidates(a,k,c,&ncandidates);
temp=1;
for(i=0; i<ncandidates; i++)
{
a[k]=c[i];
if(c[i]!=0&&temp)
{
count++;
temp=0;
}
if(count+2*n-1-k>=m)
backtrack(a,k,count);
}
}
}
int main()
{
int a[1000];
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0&&m==0) break;
num=0;
backtrack(a,0,0);
printf("%d\n",num);
}
return 0;
}*/
/*#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int n,m,map[10][10];
unsigned num;
void dfs(int x,int y,int k)
{
if (y==n) {
++x;
y=0;
}
if (k==m) {
++num;
return;
}
if (x==n)
return;
if (!map[x][y]) {
int i,j,loc=0,pos[1001][2];
for (i=x,j=y; i<n&&j<n; i++,j++)
if (!map[i][j]) {
map[i][j]=1;
pos[loc][0]=i;
pos[loc][1]=j;
loc++;
}
for (i=x-1,j=y-1; i>=0&&j>=0; i--,j--)
if (!map[i][j]) {
map[i][j]=1;
pos[loc][0]=i;
pos[loc][1]=j;
loc++;
}
for (i=x,j=y; i>=0&&j<n; i--,j++)
if (!map[i][j]) {
map[i][j]=1;
pos[loc][0]=i;
pos[loc][1]=j;
loc++;
}
for (i=x,j=y; i<n&&j>=0; i++,j--)
if (!map[i][j]) {
map[i][j]=1;
pos[loc][0]=i;
pos[loc][1]=j;
loc++;
}
map[x][y]=1;
dfs(x, y+1, k+1);
map[x][y]=0;
for (i=0; i<loc; i++)
map[pos[i][0]][pos[i][1]]=0;
}
dfs(x, y+1, k);
}
int main()
{
while (scanf("%d%d",&n,&m)!=EOF) {
if (!n&&!m)
return 0;
num=0;
memset(map, 0, sizeof(map));
dfs(0,0,0);
printf("%u\n",num);
}
return 0;
}*/
/*
A bishop is a piece used in the game of chess which can only move diagonally from its current position. Two bishops attack each other if one is on the path of the other. In the figure below, the dark squares represent the reachable locations for bishop B1 from its current position. Bishops B1 and B2 are in attacking position, while B1 and B3 are not. Bishops B2 and B3 are also in non-attacking position.
Given two numbers n and k, determine the number of ways one can put k bishops on an n x n chessboard so that no two of them are in attacking positions.
Input
The input file may contain multiple test cases. Each test case occupies a single line in the input file and contains two integers n(1 n 8) and k(0 k n2).
A test case containing two zeros terminates the input.
Output
For each test case, print a line containing the total number of ways one can put the given number of bishops on a chessboard of the given size so that no two of them lie in attacking positions. You may safely assume that this number will be less than 1015.
Sample Input
8 6
4 4
0 0
Sample Output
5599888
260
*/
|
e78c065a9d700faacc74e2b5a898cd13e63119bd
|
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
|
/InnerDetector/InDetEventCnv/InDetEventTPCnv/InDetEventTPCnv/InDetRIO_OnTrack/TRT_DriftCircleOnTrackCnv_p2.h
|
d19671f433980dba764c57f260c5c2771613cc9c
|
[
"Apache-2.0"
] |
permissive
|
strigazi/athena
|
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
|
354f92551294f7be678aebcd7b9d67d2c4448176
|
refs/heads/master
| 2022-12-09T02:05:30.632208
| 2020-09-03T14:03:18
| 2020-09-03T14:03:18
| 292,587,480
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,648
|
h
|
TRT_DriftCircleOnTrackCnv_p2.h
|
/*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#ifndef TRT_DRIFT_CIRCLE_ON_TRACK_CNV_p2_H
#define TRT_DRIFT_CIRCLE_ON_TRACK_CNV_p2_H
#include "InDetRIO_OnTrack/TRT_DriftCircleOnTrack.h"
#include "InDetEventTPCnv/InDetRIO_OnTrack/TRT_DriftCircleOnTrack_p2.h"
#include "DataModelAthenaPool/ElementLinkCnv_p1.h"
#include "AthLinks/ElementLink.h"
#include "InDetPrepRawData/TRT_DriftCircleContainer.h"
#include "TrkEventTPCnv/TrkEventPrimitives/ErrorMatrixCnv_p1.h"
#include "TrkEventTPCnv/TrkEventPrimitives/LocalParametersCnv_p1.h"
#include "GaudiKernel/ToolHandle.h"
#include "TrkEventCnvTools/IEventCnvSuperTool.h"
class MsgStream;
class TRT_DriftCircleOnTrackCnv_p2 : public T_AthenaPoolTPPolyCnvBase< Trk::MeasurementBase, InDet::TRT_DriftCircleOnTrack, InDet::TRT_DriftCircleOnTrack_p2 > {
public:
TRT_DriftCircleOnTrackCnv_p2(): m_eventCnvTool("Trk::EventCnvSuperTool/EventCnvSuperTool"),
m_localParCnv(0), m_errorMxCnv(0) {}
void persToTrans( const InDet :: TRT_DriftCircleOnTrack_p2 *persObj, InDet :: TRT_DriftCircleOnTrack *transObj, MsgStream &log );
void transToPers( const InDet :: TRT_DriftCircleOnTrack *transObj, InDet :: TRT_DriftCircleOnTrack_p2 *persObj, MsgStream &log );
protected:
ToolHandle<Trk::IEventCnvSuperTool> m_eventCnvTool;
ElementLinkCnv_p1< ElementLinkToIDCTRT_DriftCircleContainer > m_elCnv;
LocalParametersCnv_p1* m_localParCnv;
ErrorMatrixCnv_p1* m_errorMxCnv;
};
#endif
|
db70f9e32f37f0f87bfa4a117519d3b5c31c4dce
|
ffff2a4fb72a163e4d42b01cefa1f5566784990f
|
/codeforces/contests/677div3/q3.cpp
|
dab83ab6c973173450c78d4db31b62e03d0e6013
|
[] |
no_license
|
sanyamdtu/competitive_programming
|
d5b4bb6a1b46c56ebe2fe684f4a7129fe5fb8e86
|
5a810bbbd0c2119a172305b16d7d7aab3f0ed95e
|
refs/heads/master
| 2021-10-25T07:11:47.431312
| 2021-10-06T07:37:25
| 2021-10-06T07:37:25
| 238,703,031
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 746
|
cpp
|
q3.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mod 1000000007
#define INF 1e18
typedef long long ll;
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
ll t;
cin >> t;
while (t--)
{
ll n;
cin>>n;
ll arr[n];
for (ll i = 0; i < n; ++i)
{
cin>>arr[i];
}
ll maxi=INT_MIN;
for (ll i = 0; i < n; ++i)
{
maxi=max(maxi,arr[i]);
}
vector<ll> v;
for (ll i = 0; i < n; ++i)
{
if(maxi==arr[i])
v.pb(i);
}
ll ans=-1;
// cout<<maxi;
for(auto i:v){
ll x=INT_MAX;
ll y=INT_MAX;
if(x!=0)
x=arr[i-1];
if(y!=n-1)
y=arr[i+1];
if(x<arr[i]||y<arr[i])
{
ans=i;
break;
}
}
if(ans!=-1)
ans++;
cout<<ans<<endl;
}
return 0;
}
|
8ed4c57f893353559593d81314fc737adf17de36
|
c60331c2fa72988af73c688d2f222c185559c080
|
/demo/parameter/paramdialog.h
|
cf304b55d7d686b5a33799728a6b9a32c5529cfe
|
[] |
no_license
|
heyuyi/qt-gui
|
4610b82f75a69c26d003ef9b2bdcc960a24b48f1
|
3588e859e2beeaae6fdeea7d7e7843e8f1b58743
|
refs/heads/master
| 2020-04-02T20:07:15.553652
| 2016-08-04T04:40:40
| 2016-08-04T04:40:40
| 60,269,964
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,459
|
h
|
paramdialog.h
|
#ifndef PARAMDIALOG_H
#define PARAMDIALOG_H
#include "base/paramdata.h"
#include "numberdialog.h"
#include <QDialog>
#include <QStandardItemModel>
namespace Ui {
class ParamDialog;
}
class ParamDialog : public QDialog
{
Q_OBJECT
public:
explicit ParamDialog(QWidget *parent = 0);
~ParamDialog();
private:
void saveCheck(void);
void displayUpdate(void);
private slots:
void dateTimerSLOT(void);
void nDialogOutValueSLOT();
void on_paramView_clicked(const QModelIndex &index);
void on_enableCheckBox_clicked();
void on_pumpSpeedEdit_released();
void on_delayEdit_released();
void on_quantityEdit_released();
void on_speedEdit_released();
void on_delay1Edit_released();
void on_pumpEdit_released();
void on_delay2Edit_released();
void on_newLabel_pressed();
void on_newLabel_released();
void on_openLabel_pressed();
void on_openLabel_released();
void on_saveLabel_pressed();
void on_saveLabel_released();
void on_saveAsLabel_pressed();
void on_saveAsLabel_released();
void on_confirmLabel_pressed();
void on_confirmLabel_released();
void on_cancelLabel_pressed();
void on_cancelLabel_released();
private:
Ui::ParamDialog *ui;
NumberDialog *nDialog;
ParamData *param;
QStandardItemModel *treeModel;
QString name;
short treeItem;
short editItem;
bool isChanged;
};
#endif // PARAMDIALOG_H
|
63eb94e08b0699563b7c32f96783e0378677aa71
|
3b83616a6d0718f298b5bb6de735ddcd510b3355
|
/Project/Core/Src/stm32f4xx_hal_msp.cpp
|
dc1243eb23a54cc13d95840095958b14b6b9dd41
|
[
"MIT"
] |
permissive
|
steve22184/STM32F4_MQTTdemo
|
506d050b4a77c19b4550fb2d2693879331fce616
|
b03fa8fd25754c14b7c94a35b5bdd61d2d5b4daa
|
refs/heads/master
| 2022-09-01T22:49:47.940085
| 2020-05-31T14:13:25
| 2020-05-31T14:13:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,531
|
cpp
|
stm32f4xx_hal_msp.cpp
|
/* USER CODE BEGIN Header */
/**
******************************************************************************
* File Name : stm32f4xx_hal_msp.c
* Description : This file provides code for the MSP Initialization
* and de-Initialization codes.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include <gui/mainscreen_screen/MainScreenView.hpp>
#include <gui/lightscreen_screen/LightScreenView.hpp>
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
TIM_HandleTypeDef htim1;
TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim3;
DMA_HandleTypeDef hdma_tim1_ch1;
DMA_HandleTypeDef hdma_tim2_ch1;
DMA_HandleTypeDef hdma_tim3_ch1_trig;
TIM_HandleTypeDef htim4;
ADC_HandleTypeDef hadc2;
DMA_HandleTypeDef hdma_adc2;
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN Define */
/* USER CODE END Define */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
/* USER CODE END Macro */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* External functions --------------------------------------------------------*/
/* USER CODE BEGIN ExternalFunctions */
/* USER CODE END ExternalFunctions */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
{
/* USER CODE BEGIN MspInit 0 */
/* USER CODE END MspInit 0 */
__HAL_RCC_SYSCFG_CLK_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
/* System interrupt init*/
/* USER CODE BEGIN MspInit 1 */
/* USER CODE END MspInit 1 */
}
/**
* @brief ADC MSP Initialization
* This function configures the hardware resources used in this example
* @param hadc: ADC handle pointer
* @retval None
*/
void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(hadc->Instance==ADC2)
{
/* USER CODE BEGIN ADC2_MspInit 0 */
/* USER CODE END ADC2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_ADC2_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
/**ADC2 GPIO Configuration
PC5 ------> ADC2_IN15
*/
GPIO_InitStruct.Pin = Light_ADC_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(Light_ADC_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN ADC2_MspInit 1 */
/* USER CODE END ADC2_MspInit 1 */
}
}
/**
* @brief ADC MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hadc: ADC handle pointer
* @retval None
*/
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
{
if(hadc->Instance==ADC2)
{
/* USER CODE BEGIN ADC2_MspDeInit 0 */
/* USER CODE END ADC2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_ADC2_CLK_DISABLE();
/**ADC2 GPIO Configuration
PC5 ------> ADC2_IN15
*/
HAL_GPIO_DeInit(Light_ADC_GPIO_Port, Light_ADC_Pin);
/* USER CODE BEGIN ADC2_MspDeInit 1 */
/* USER CODE END ADC2_MspDeInit 1 */
}
}
/**
* @brief TIM_Base MSP Initialization
* This function configures the hardware resources used in this example
* @param htim_base: TIM_Base handle pointer
* @retval None
*/
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(htim_base->Instance==TIM1)
{
/* USER CODE BEGIN TIM1_MspInit 0 */
/* USER CODE END TIM1_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_TIM1_CLK_ENABLE();
/* TIM1 DMA Init */
/* TIM1_CH1 Init */
hdma_tim1_ch1.Instance = DMA2_Stream1;
hdma_tim1_ch1.Init.Channel = DMA_CHANNEL_6;
hdma_tim1_ch1.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_tim1_ch1.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_tim1_ch1.Init.MemInc = DMA_MINC_ENABLE;
hdma_tim1_ch1.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_tim1_ch1.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_tim1_ch1.Init.Mode = DMA_CIRCULAR;
hdma_tim1_ch1.Init.Priority = DMA_PRIORITY_LOW;
hdma_tim1_ch1.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_tim1_ch1) != HAL_OK)
{
//Error_Handler();
}
__HAL_LINKDMA(htim_base,hdma[TIM_DMA_ID_CC1],hdma_tim1_ch1);
/* USER CODE BEGIN TIM1_MspInit 1 */
/* USER CODE END TIM1_MspInit 1 */
}
else if(htim_base->Instance==TIM4)
{
/* USER CODE BEGIN TIM4_MspInit 0 */
/* USER CODE END TIM4_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_TIM4_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/**TIM4 GPIO Configuration
PD12 ------> TIM4_CH1
*/
GPIO_InitStruct.Pin = GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF2_TIM4;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/* USER CODE BEGIN TIM4_MspInit 1 */
/* USER CODE END TIM4_MspInit 1 */
}
}
/**
* @brief TIM_PWM MSP Initialization
* This function configures the hardware resources used in this example
* @param htim_pwm: TIM_PWM handle pointer
* @retval None
*/
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef* htim_pwm)
{
if(htim_pwm->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspInit 0 */
/* USER CODE END TIM2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_TIM2_CLK_ENABLE();
/* TIM2 DMA Init */
/* TIM2_CH1 Init */
hdma_tim2_ch1.Instance = DMA1_Stream5;
hdma_tim2_ch1.Init.Channel = DMA_CHANNEL_3;
hdma_tim2_ch1.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_tim2_ch1.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_tim2_ch1.Init.MemInc = DMA_MINC_ENABLE;
hdma_tim2_ch1.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_tim2_ch1.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_tim2_ch1.Init.Mode = DMA_CIRCULAR;
hdma_tim2_ch1.Init.Priority = DMA_PRIORITY_LOW;
hdma_tim2_ch1.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_tim2_ch1) != HAL_OK)
{
//Error_Handler();
}
__HAL_LINKDMA(htim_pwm,hdma[TIM_DMA_ID_CC1],hdma_tim2_ch1);
/* USER CODE BEGIN TIM2_MspInit 1 */
/* USER CODE END TIM2_MspInit 1 */
}
else if(htim_pwm->Instance==TIM3)
{
/* USER CODE BEGIN TIM3_MspInit 0 */
/* USER CODE END TIM3_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_TIM3_CLK_ENABLE();
/* TIM3 DMA Init */
/* TIM3_CH1_TRIG Init */
hdma_tim3_ch1_trig.Instance = DMA1_Stream4;
hdma_tim3_ch1_trig.Init.Channel = DMA_CHANNEL_5;
hdma_tim3_ch1_trig.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_tim3_ch1_trig.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_tim3_ch1_trig.Init.MemInc = DMA_MINC_ENABLE;
hdma_tim3_ch1_trig.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_tim3_ch1_trig.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_tim3_ch1_trig.Init.Mode = DMA_CIRCULAR;
hdma_tim3_ch1_trig.Init.Priority = DMA_PRIORITY_LOW;
hdma_tim3_ch1_trig.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_tim3_ch1_trig) != HAL_OK)
{
//Error_Handler();
}
/* Several peripheral DMA handle pointers point to the same DMA handle.
Be aware that there is only one stream to perform all the requested DMAs. */
__HAL_LINKDMA(htim_pwm,hdma[TIM_DMA_ID_CC1],hdma_tim3_ch1_trig);
__HAL_LINKDMA(htim_pwm,hdma[TIM_DMA_ID_TRIGGER],hdma_tim3_ch1_trig);
/* USER CODE BEGIN TIM3_MspInit 1 */
/* USER CODE END TIM3_MspInit 1 */
}
}
void HAL_TIM_MspPostInit(TIM_HandleTypeDef* htim)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(htim->Instance==TIM1)
{
/* USER CODE BEGIN TIM1_MspPostInit 0 */
/* USER CODE END TIM1_MspPostInit 0 */
__HAL_RCC_GPIOE_CLK_ENABLE();
/**TIM1 GPIO Configuration
PE9 ------> TIM1_CH1
*/
GPIO_InitStruct.Pin = Red_PWM_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF1_TIM1;
HAL_GPIO_Init(Red_PWM_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN TIM1_MspPostInit 1 */
/* USER CODE END TIM1_MspPostInit 1 */
}
else if(htim->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspPostInit 0 */
/* USER CODE END TIM2_MspPostInit 0 */
__HAL_RCC_GPIOA_CLK_ENABLE();
/**TIM2 GPIO Configuration
PA5 ------> TIM2_CH1
*/
GPIO_InitStruct.Pin = Green_PWM_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF1_TIM2;
HAL_GPIO_Init(Green_PWM_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN TIM2_MspPostInit 1 */
/* USER CODE END TIM2_MspPostInit 1 */
}
else if(htim->Instance==TIM3)
{
/* USER CODE BEGIN TIM3_MspPostInit 0 */
/* USER CODE END TIM3_MspPostInit 0 */
__HAL_RCC_GPIOA_CLK_ENABLE();
/**TIM3 GPIO Configuration
PA6 ------> TIM3_CH1
*/
GPIO_InitStruct.Pin = Blue_PWM_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF2_TIM3;
HAL_GPIO_Init(Blue_PWM_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN TIM3_MspPostInit 1 */
/* USER CODE END TIM3_MspPostInit 1 */
}
}
/**
* @brief TIM_Base MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param htim_base: TIM_Base handle pointer
* @retval None
*/
void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* htim_base)
{
if(htim_base->Instance==TIM1)
{
/* USER CODE BEGIN TIM1_MspDeInit 0 */
/* USER CODE END TIM1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM1_CLK_DISABLE();
/* TIM1 DMA DeInit */
HAL_DMA_DeInit(htim_base->hdma[TIM_DMA_ID_CC1]);
/* USER CODE BEGIN TIM1_MspDeInit 1 */
/* USER CODE END TIM1_MspDeInit 1 */
}
else if(htim_base->Instance==TIM4)
{
/* USER CODE BEGIN TIM4_MspDeInit 0 */
/* USER CODE END TIM4_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM4_CLK_DISABLE();
/**TIM4 GPIO Configuration
PD12 ------> TIM4_CH1
*/
HAL_GPIO_DeInit(GPIOD, GPIO_PIN_12);
/* USER CODE BEGIN TIM4_MspDeInit 1 */
/* USER CODE END TIM4_MspDeInit 1 */
}
}
/**
* @brief TIM_PWM MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param htim_pwm: TIM_PWM handle pointer
* @retval None
*/
void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef* htim_pwm)
{
if(htim_pwm->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspDeInit 0 */
/* USER CODE END TIM2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM2_CLK_DISABLE();
/* TIM2 DMA DeInit */
HAL_DMA_DeInit(htim_pwm->hdma[TIM_DMA_ID_CC1]);
/* USER CODE BEGIN TIM2_MspDeInit 1 */
/* USER CODE END TIM2_MspDeInit 1 */
}
else if(htim_pwm->Instance==TIM3)
{
/* USER CODE BEGIN TIM3_MspDeInit 0 */
/* USER CODE END TIM3_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM3_CLK_DISABLE();
/* TIM3 DMA DeInit */
HAL_DMA_DeInit(htim_pwm->hdma[TIM_DMA_ID_CC1]);
HAL_DMA_DeInit(htim_pwm->hdma[TIM_DMA_ID_TRIGGER]);
/* USER CODE BEGIN TIM3_MspDeInit 1 */
/* USER CODE END TIM3_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
2d508e2cdbbae07ebc8216c7ad95523a71510760
|
0bedbcd5d9821abaad01e1d32949007a1a3f756b
|
/1600 -Patrol Robot.cpp
|
78685598a6868e820a5579c1759ff42d120aadce
|
[] |
no_license
|
ahqmrf/desktopUva
|
02a17c20f114cd305883ad1c809d6f135a12f816
|
33a6579e0c8bb25f5893d05d9a95de88db5ccc80
|
refs/heads/master
| 2021-01-23T12:16:25.145257
| 2015-03-19T07:02:55
| 2015-03-19T07:02:55
| 32,505,544
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,116
|
cpp
|
1600 -Patrol Robot.cpp
|
#include <bits/stdc++.h>
using namespace std;
int obstacle[32][32];
int moves[32][32][32];
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
int main() {
int cases;
int N, M, K;
scanf("%d", &cases);
while(cases--) {
scanf("%d %d %d", &N, &M, &K);
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
scanf("%d", &obstacle[i][j]);
memset(moves, 63, sizeof moves);
moves[0][0][0] = 0;
queue<int> X, Y, S;
int x, y, s, tx, ty, ts;
X.push(0), Y.push(0), S.push(0);
while(!X.empty()) {
x = X.front(), X.pop();
y = Y.front(), Y.pop();
s = S.front(), S.pop();
for(int i = 0; i < 4; i++) {
tx = x + dx[i], ty = y + dy[i];
if(tx < 0 || ty < 0 || tx >= N || ty >= M) continue;
if(obstacle[tx][ty]) ts = s + 1;
else ts = 0;
if(ts > K) continue;
if(moves[tx][ty][ts] > moves[x][y][s] + 1) {
moves[tx][ty][ts] = moves[x][y][s] + 1;
X.push(tx), Y.push(ty), S.push(ts);
}
}
}
int ret = 0x3f3f3f3f;
for(int i = 0; i <= K; i++)
ret = min(ret, moves[N-1][M-1][i]);
printf("%d\n", ret == 0x3f3f3f3f ? -1 : ret);
}
return 0;
}
|
f880c2e8824177b25a39039d3900534732e7a8f2
|
165ad2af507836c4844389da9f5f214a2c6a1e49
|
/superjxsyxtool/sysex.h
|
c8b2c180fc5c4883f3376f246d4db73d2ef777bd
|
[
"MIT"
] |
permissive
|
10x10sw/SuperJX
|
ca790634fabb12eb28f96d820957e877c68dd1c1
|
b607638a3a166785f8f9e980cab18683f02463fd
|
refs/heads/master
| 2022-01-18T15:36:20.056674
| 2022-01-05T00:10:13
| 2022-01-05T00:10:13
| 84,658,227
| 4
| 3
|
MIT
| 2019-05-01T14:04:36
| 2017-03-11T15:03:32
|
C++
|
UTF-8
|
C++
| false
| false
| 818
|
h
|
sysex.h
|
//
// sysex.h
// superjxsyxtool
//
// Created by Christian E. on 2017/Oct/19.
// Copyright © 2017 Ten by Ten. All rights reserved.
//
#ifndef sysex_h
#define sysex_h
#include <stdint.h>
#include <vector>
typedef std::vector<uint8_t> SyxBuffer;
inline uint8_t CombineBytes(uint8_t top, uint8_t bot)
{
top = top << 4;
if (top > 127) top -= 128;
return top | bot;
}
inline uint8_t Decode2valParameter(uint8_t val)
{
return val>=64;
}
inline uint8_t Decode3valParameter(uint8_t val)
{
if (val<32)
return 0;
if (val<64)
return 1;
return 2;
}
inline uint8_t Decode4valParameter(uint8_t val)
{
if (val<32)
return 0;
if (val<64)
return 1;
if (val<96)
return 2;
return 3;
}
inline uint8_t Decode100valParameter(uint8_t val)
{
return static_cast<uint8_t>(val * .78f);
}
#endif /* sysex_h */
|
8dd0b2c09499ac022f77327f5c2ec665a15d487c
|
571ef575bd69c7dc0d6ac82bf093354f0f1e237a
|
/aten/src/THC/THCCachingHostAllocator.h
|
056caf3dfb0e73340e61b49c281bb96a9f1944f6
|
[
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
TrendingTechnology/nimble
|
0f8240749cac3e04d9489ce514445a79980ba5f1
|
5ac9544dace9630e26df083fb71e9e56e2ee21ea
|
refs/heads/main
| 2023-01-24T01:50:22.972927
| 2020-11-28T22:31:06
| 2020-11-28T22:31:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,307
|
h
|
THCCachingHostAllocator.h
|
#ifndef THC_CACHING_HOST_ALLOCATOR_INC
#define THC_CACHING_HOST_ALLOCATOR_INC
#include <THC/THCGeneral.h>
#include <c10/cuda/CUDAStream.h>
//
// A caching allocator for CUDA host allocations (pinned memory).
//
// This provides a drop-in replacement for THCudaHostAllocator, which re-uses
// freed pinned (page-locked) memory allocations. This avoids device
// synchronizations due to cudaFreeHost calls.
//
// To ensure correct behavior, THCCachingHostAllocator_recordEvent must be
// called anytime a pointer from this allocator is used in a cudaMemcpyAsync
// call between host and device. We implement this for storages and tensors in
// copy_from_cpu_async_ and copy_to_cpu_async_.
//
// Note that this allocator does not split larger allocations into smaller
// blocks, unlike the caching device allocator.
//
THC_API c10::Allocator* getTHCCachingHostAllocator(void);
// Records an event in the specified stream. The allocation 'ptr' will not be
// re-used until the event has occurred.
THC_API cudaError_t THCCachingHostAllocator_recordEvent(void *ptr, at::cuda::CUDAStream stream);
// Releases cached pinned memory allocations via cudaHostFree
THC_API void THCCachingHostAllocator_emptyCache(void);
THC_API std::unique_ptr<std::vector<at::DataPtr>> collectCapturedHostPointers(void);
#endif
|
628eccd021a5f37399d53adcd3f0bdf82fff7413
|
e013ec787e57af5c8c798f5714d9f930b76dfd32
|
/Solutions/Codeforces Solutions/80-B_Depression.cpp
|
43eb73e4bc8daad51e3d00baf0c30d606e3fe7c2
|
[] |
no_license
|
omaryasser/Competitive-Programming
|
da66cb75bf6ed5495454d2f57333b02fe30a5b68
|
ba71b23ae3d0c4ef8bbdeff0cd12c3daca19d809
|
refs/heads/master
| 2021-04-29T00:39:29.663196
| 2019-02-19T04:20:56
| 2019-02-19T04:20:56
| 121,832,844
| 17
| 8
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 53
|
cpp
|
80-B_Depression.cpp
|
https://codeforces.com/contest/80/submission/21831449
|
f746b748ffe97523560b92b477d5f6827bf60958
|
635a31fb5f4fed8f1f630f6f6620e55ce4ae03e6
|
/CPP/Inheritence/hier.cpp
|
3e9ee70ab076af7901f1704f555ec8a09938ba95
|
[] |
no_license
|
iCodeIN/Problem-Solving
|
82cd4eef0e4606baf31d8de34135dd5366d19a1e
|
92f13c2cab5dfe914755dae7790c9cf8c6fb8782
|
refs/heads/master
| 2022-11-27T16:49:30.319955
| 2020-08-08T08:47:24
| 2020-08-08T08:47:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,587
|
cpp
|
hier.cpp
|
#include<bits/stdc++.h>
using namespace std;
class employee{
string name,ID,dob;
int salary;
public:
employee(string n,string i,string d,int s)
{
name=n;
ID=i;
dob=d;
salary=s;
}
int get_salary(){return salary;}
string get_ID(){return ID;}
string get_name(){return name;}
string get_dob(){return dob;}
};
class manager:public employee{
string name;
list<employee*> e;
typedef map<string,manager*> vmap;
vmap work;
public:
manager(string n)
{
name=n;
}
void set_employee_list();
void show_emp_list();
void add_manager();
};
void manager::add_manager(string n,employee* e)
{
vmap::iterator it=work.begin();
it=work.find(n);
if(it==work.end()){
work[n]=new manager(n);
work[n]->set_employee_list(e);
}else{
it->second->set_employee_list(e);
}
}
void manager::set_employee_list(employee* el)
{
e.push_back(el);
}
void manager::show_emp_list()
{
cout<<"MANAGER EMP_NAME SALARY DOB ID"<<endl;
for(vmap::iterator it=work.begin();it!=work.end();it++){
cout<<it->second->name<<"\t";
for(list<employee*>::iterator iter=it->second->e.begin();iter!=it->second->e.end();iter++)
cout<<iter->name<<"\t"<<iter->salary<<"\t"<<iter->dob<<"\t"<<iter->ID<<endl;
}
}
int main()
{
ifstream fin;
fin.open("employee.txt");
manager m;
while(!fin.eof()){
string nam,sal,db,man;
int id;
fin >>nam>>sal>>db>>id>>man;
employee* emp=new employee(nam,id,db,sal);
m.add_manager(man,emp);
}
m.show_emp_list();
return 0;
}
|
06ef502801b98a3810ceaed18607b70e8c9eac1b
|
ba00fcdd10ca8edc1db46d688f85c5baa67cb514
|
/xD-Balls/BallSpawner.hpp
|
ad1d3e9b8d6cffb527e8497e93b4ce44f5d6c0cf
|
[] |
no_license
|
dominikhofman/xD-QuadBalls
|
2082512ef713eb903e30372c5bb085948426b191
|
d53891dd439d5ef96f434e4011beceb2f5dc7d13
|
refs/heads/master
| 2020-03-17T01:36:38.301402
| 2018-05-30T12:07:19
| 2018-05-30T12:07:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 416
|
hpp
|
BallSpawner.hpp
|
#pragma once
#include <cmath>
#include <vector>
#include "Ball.hpp"
#include "Rectangle.hpp"
class BallSpawner
{
public:
std::vector<Ball> balls;
Vector2D position;
size_t texture_max_id;
BallSpawner();
~BallSpawner();
void deployBalls(const Ball source, int n, bool random_velocity = true, bool random_radius = false, bool random_color = true, size_t texture_max_id = 2);
void update(double delta_t);
};
|
4d0a5834cbd8720d6f0b2f17aec67a211ccd92e9
|
42b8c11aef0dcc1d6540029958d85f2e8ce93b08
|
/스터디/Kakao_2020_외벽점검/main.cpp
|
30129ae39086ef495091b34ddc0a3dc8bde35d27
|
[] |
no_license
|
pjs56ww/Algorithm_2021
|
6d0811d54db62d82ce6351c63971955d318c9e34
|
4668f839b7fd839deae6f14699a65162f4fbfae0
|
refs/heads/master
| 2023-08-01T09:06:07.682042
| 2021-09-26T01:43:06
| 2021-09-26T01:43:06
| 409,654,480
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,256
|
cpp
|
main.cpp
|
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int solution(int n, vector<int> weak, vector<int> dist) {
int answer = -1;
sort(dist.begin(), dist.end());
for (int i = 0; i < weak.size(); i++) {
int tmp = weak[0] + n;
for (int j = 1; j < weak.size(); j++) {
weak[j - 1] = weak[j];
}
weak[weak.size() - 1] = tmp;
do {
int i = 0;
int j = 0;
for (j = 0; j < dist.size(); j++) {
int f = weak[i] + dist[j];
while (f >= weak[i]) {
i++;
if (i == weak.size()) {
break;
}
}
if (i == weak.size()) {
break;
}
}
if (i == weak.size()) {
if (answer == -1 || j + 1 < answer) {
answer = j + 1;
}
}
} while (next_permutation(dist.begin(), dist.end()));
}
return answer;
}
int main() {
vector <int> weak = { 1, 5, 6, 10 };
vector <int> dist = { 1, 2, 3, 4 };
cout << solution(12, weak, dist) << endl;
return 0;
}
|
2f90a7e828e79e4055c3a5c7bd22cc548eceff7c
|
830cacca1cbf67435424b48487ba13adc9af6ae5
|
/src/Widget.cpp
|
de65f1e11bdf48667caefcdc92d7ecb15a606028
|
[] |
no_license
|
Xiaodisan/BevProg2_bead3
|
22fb58944ed164085904722b4404072f2e1eaa76
|
ed8d7383bd0dc77ac83c827de5166a2883bbec82
|
refs/heads/master
| 2022-06-16T22:30:18.740893
| 2020-05-11T04:38:06
| 2020-05-11T04:38:06
| 262,751,498
| 0
| 0
| null | 2020-05-11T04:38:07
| 2020-05-10T09:21:42
|
C
|
UTF-8
|
C++
| false
| false
| 413
|
cpp
|
Widget.cpp
|
#include "Widget.h"
Widget::Widget(int a, int b, int c, int d) :
left(a),
top(b),
width(c),
height(d) {}
Widget::~Widget(){}
bool Widget::is_selected(const int& mx, const int& my) {
if(mx > left && mx < left + width && my > top && my < top + height) {
focused = true;
return true;
}
return false;
}
void Widget::update(){}
void Widget::unfocus(){focused = false;}
|
a21cb95569025680b61f8cd8232122cae608270f
|
4b9de44bff59a4938ce209be84fd67e367d5b82b
|
/lib/Sht31d.cpp
|
c3414b38fc997ee61944ddf3e601846f6e2f0050
|
[
"MIT"
] |
permissive
|
laszlofederics/Esp
|
42c89043f436ae57a83cbe1b472bf361d493e114
|
bf41e4d05945bc422bd7a0add65b7f1a3e954300
|
refs/heads/master
| 2020-03-30T05:07:31.997191
| 2018-10-28T21:38:01
| 2018-10-28T21:38:01
| 150,782,191
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,573
|
cpp
|
Sht31d.cpp
|
/* ************************************************************************** */
/* ************* Configuration settings ****************** */
/* ************************************************************************** */
#define ENABLE_DEBUG
#define SHT31D_ADDRESS 0x44
#define SHT31D_READING_DURATION_MS 150
/* ************* End configuration settings ******************* */
#include "debug.h"
#include "I2C.h"
#include "Sht31d.h"
using namespace Esp8266Base;
bool ICACHE_FLASH_ATTR Sht31d::startMeasurement()
{
debug(">>> Sht31d::startMeasurement()\n");
I2C::ErrorCode nError = I2C::writeCommand(SHT31D_ADDRESS, 0x2400);
bool bRet = false;
if (I2C::Succeeded == nError)
{
m_tReading.start(SHT31D_READING_DURATION_MS, false, &measurementReady);
bRet = true;
}
debug("<<< Sht31d::startMeasurement() returns %s\n", bRet ? "true":"false");
return bRet;
}
bool ICACHE_FLASH_ATTR Sht31d::readData(float& temperature, float& humidity)
{
debug(">>> Sht31d::readData()\n");
bool bRet = true;
uint8_t temp1 = 0, temp2 = 0, crc_temp = 0, hum1 = 0, hum2 = 0, crc_hum = 0;
I2C::ErrorCode nError = I2C::readBytes(SHT31D_ADDRESS, temp1, temp2, crc_temp, hum1, hum2, crc_hum);
if (I2C::Succeeded == nError)
{
if (crc_temp == calculateCrc(temp1, temp2))
{
uint16_t temp16 = (temp1 << 8) | temp2;
uint32_t x = 175 * temp16;
float y = x;
temperature = y/65535 - 45;
}
else
{
printError("ERROR: CRC error in temperature in Sht31d::readData()\n");
bRet = false;
}
if (crc_hum == calculateCrc(hum1, hum2))
{
uint16_t hum16 = (hum1 << 8) | hum2;
uint32_t x = 100 * hum16;
float y = x;
humidity = y/65535;
}
else
{
printError("ERROR: CRC error in humidity in Sht31d::readData()\n");
bRet = false;
}
}
else
{
bRet = false;
}
#ifdef ENABLE_DEBUG
// workaround of missing %f format of printf
int a = temperature*100;
int b = humidity;
debug("<<< Sht31d::readData(%d.%d, %d) returns %s\n", a/100, a%100, b, bRet ? "true":"false");
#endif
return bRet;
}
uint8_t Sht31d::calculateCrc(uint8_t byte1, uint8_t byte2) const
{
uint8_t bit;
uint8_t crc = 0xFF;
crc ^= byte1;
for (bit = 8; bit > 0; --bit)
{
if (crc & 0x80)
crc = (crc << 1) ^ 0x131;
else
crc = (crc << 1);
}
crc ^= byte2;
for (bit = 8; bit > 0; --bit)
{
if (crc & 0x80)
crc = (crc << 1) ^ 0x131;
else
crc = (crc << 1);
}
return crc;
}
|
da1644cdef45912573327a599f186505d39755fe
|
1e9bb5826368d34ab202c72440ba656bc0d2ee7d
|
/solutions/85_maximal_rect.cpp
|
b002fea8514123b60d2f36bcf61868a1a6efb3cd
|
[] |
no_license
|
vikas9905/LeetCode_Solutions
|
c5842b08e5716861ec06c14ac6d5aacbb15f93e0
|
84832be2742e3a622380611f01297509cdded6a6
|
refs/heads/master
| 2023-01-04T15:02:24.803882
| 2020-10-29T01:33:00
| 2020-10-29T01:33:00
| 305,785,920
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,601
|
cpp
|
85_maximal_rect.cpp
|
//https://leetcode.com/problems/maximal-rectangle/
class Solution {
public:
int max_hist(vector<int>arr){
int n=arr.size();
stack<int>s;
int area_with_top=0;
int area=0;
int i=0;
while(i<n){
if(s.empty() || arr[s.top()]<=arr[i])
s.push(i++);
else{
int tp=s.top();
s.pop();
area_with_top=arr[tp]*(s.empty()? i:i-s.top()-1);
if(area_with_top>area)
area=area_with_top;
}
}
while(!s.empty()){
int tp=s.top();
s.pop();
area_with_top=arr[tp]*(s.empty()? i:i-s.top()-1);
if(area_with_top>area)
area=area_with_top;
}
return area;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.size()==0)
return 0;
vector<vector<int>>arr;
int n=matrix.size();
int m=matrix[0].size();
for(int i=0;i<n;i++){
vector<int>temp;
for(int j=0;j<m;j++){
if(matrix[i][j]=='0')
temp.push_back(0);
else
temp.push_back(1);
}
arr.push_back(temp);
}
int res=max_hist(arr[0]);
for(int i=1;i<n;i++){
for(int j=0;j<m;j++){
if(arr[i][j])
arr[i][j]+=arr[i-1][j];
}
res=max(res,max_hist(arr[i]));
}
return res;
}
};
|
8b308431519cd039717499839dc797a516c354f1
|
f1430d9ada762c7ec175928a98a3ce2bdd5326b2
|
/include/graphics/texture.h
|
23a8e262caaf9ba9bf1ca838e2731a64dadd0d06
|
[
"MIT"
] |
permissive
|
rededx/xRender
|
1da5fea65c7f1bdde9d08a6bacfba80a13d13960
|
4b4d94a2ef75280e3e30484c20b45571c5f2ec4f
|
refs/heads/main
| 2023-03-19T04:07:28.803853
| 2021-03-09T14:33:07
| 2021-03-09T14:33:07
| 345,322,437
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 371
|
h
|
texture.h
|
#ifndef XRENDER_INCLUDE_GRAPHICS_TEXTURE_H_
#define XRENDER_INCLUDE_GRAPHICS_TEXTURE_H_
#include <string_view>
#include "resource_manager.h"
namespace xrn {
class Texture {
public:
Texture(std::string_view path);
~Texture() = default;
unsigned int get_id();
private:
unsigned int id_;
};
} // namespace xrn
#endif // XRENDER_INCLUDE_GRAPHICS_TEXTURE_H_
|
f3a966ac11047496ab5d0761a6ddafff08d9486d
|
c3ac0f16f812a56bb2c58ce0eef868fef71fccd8
|
/northern19/b.cpp
|
680a8b151bf8a51a31e143c41b69086ba3f445b8
|
[] |
no_license
|
bamboo-hust/icpc-trainings
|
23a853df9a03f2e20a0574c4ad89f459600f69f3
|
edcb2f4e9f2c3dc543a30e77fe636e9f00715238
|
refs/heads/master
| 2020-07-19T00:13:45.734529
| 2019-11-28T14:35:34
| 2019-11-28T14:35:34
| 206,340,416
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,017
|
cpp
|
b.cpp
|
#include <bits/stdc++.h>
using namespace std;
int const NN = 20;
set < string > set_string;
void init(string s) {
int n = s.size();
for (int i = 0; i < n; i++) {
string cur = "";
for (int j = i; j < min(i + NN, n); j++) {
cur = cur + s[j];
set_string.insert(cur);
}
}
}
string convert(int mask, int len) {
string cur = "";
for (int i = 1; i <= len; i++) {
int val = (mask % 2);
cur = cur + (char)('0' + val);
mask /= 2;
}
reverse(cur.begin(), cur.end());
return cur;
}
int main() {
ios_base::sync_with_stdio(0);
string s;
for (int i = 1; i <= 2; i++) {
cin >> s;
init(s);
}
for (int len = 1; len <= NN; len++) {
for (int mask = 0; mask < (1 << len); mask++) {
string cur = convert(mask, len);
if (set_string.find(cur) == set_string.end()) {
cout << cur << endl;
return 0;
}
}
}
}
|
0b5c3675af01e5ad706b13d7059b057b6eec9d6f
|
50fe4c1bdb2f0264a45548719b07112587607a28
|
/RPGMaster/Enemy.h
|
b71074c0737e8932c1c11c1a048fd64e11ddbdf2
|
[] |
no_license
|
stranker/TrabajoPractico3
|
434be85cf2e9dc4c7a11cc6494043141d59feacf
|
c62986e1530d29db918504180a6bc8c61444da45
|
refs/heads/master
| 2020-03-18T09:36:59.287692
| 2018-05-30T12:37:47
| 2018-05-30T12:37:47
| 134,573,017
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 610
|
h
|
Enemy.h
|
#ifndef ENEMY_H
#define ENEMY_H
#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_native_dialog.h>
class Enemy
{
private:
ALLEGRO_BITMAP * sprite = NULL;
float positionX;
float positionY;
float spriteW;
float spriteH;
int directionX;
int directionY;
public:
Enemy(float x, float y);
~Enemy();
void Movimiento(const int SCREEN_W, const int SCREEN_H);
void Update(const int SCREEN_W, const int SCREEN_H);
void Draw();
ALLEGRO_BITMAP* GetSprite();
float GetPosX();
float GetPosY();
float CollisionW();
float CollisionH();
};
#endif
|
e07a0f162e3d8de59e7dcfffb17c093c74e4ef6c
|
df3bad9533e40ad6f5e3c50de74a6a7d118b61bc
|
/BlakesEngine/DataFormat/bePackedData.cpp
|
1d59e8fc04f99e1b54cf8660e91dcbe76a7d369a
|
[] |
no_license
|
BlakeTheAwesome/personal-engine
|
975fb91f216e2dc740deab8680f9640057564ee5
|
3535bfd187bda020083fd399e3c898f782308726
|
refs/heads/master
| 2022-03-21T17:42:07.631845
| 2022-02-27T02:29:15
| 2022-02-27T02:29:15
| 36,546,730
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,844
|
cpp
|
bePackedData.cpp
|
module;
#include "BlakesEngine/bePCH.h"
#include "BlakesEngine/Core/beString.h"
#include "BlakesEngine/Core/beAssert.h"
#include "BlakesEngine/Core/beMacros.h"
#include <filesystem>
module bePackedData;
import beDataBuffer;
import RangeIter;
static int ReadString(char* buffer, int bufferLen, std::FILE* file)
{
int stringLength = std::fgetc(file);
if (stringLength == EOF)
{
BE_ASSERT(false);
return -1;
}
BE_ASSERT(stringLength < bufferLen);
int bytesRead = (int)std::fread(buffer, sizeof(u8), stringLength, file);
if (bytesRead < stringLength)
{
BE_ASSERT(false);
return -1;
}
buffer[stringLength] = '\0';
return stringLength;
}
struct ScopedFile
{
std::FILE* file = nullptr;
~ScopedFile()
{
fclose(file);
}
};
void bePackedData::LoadFromFile(beStringView filePath)
{
std::FILE* file = std::fopen(filePath.c_str(), "rb");
if (!file)
{
BE_ASSERT(false);
return;
}
ScopedFile scope{file};
ReadHeaders(file);
ReadStreams(file);
}
void bePackedData::ReadHeaders(std::FILE* file)
{
int numStreams = std::fgetc(file);
if (numStreams == EOF)
{
BE_ASSERT(false);
return;
}
BE_ASSERT(numStreams < 256);
for (int i : RangeIter(numStreams))
{
Unused(i);
u32 dataLen{};
auto bytesRead = std::fread(&dataLen, sizeof(u8), sizeof(dataLen), file);
if (bytesRead != sizeof(dataLen))
{
BE_ASSERT(false);
return;
}
char stringBuf[256]{};
int stringLength = ReadString(stringBuf, sizeof(stringBuf), file);
if (stringLength < 1)
{
BE_ASSERT(false);
return;
}
DataStream* header = m_streams.AddNew();
header->dataLen = dataLen;
header->name.assign(stringBuf, stringLength);
}
u32 dataOffset = (u32)ftell(file);
for (DataStream& dataStream : m_streams)
{
dataStream.fileOffset = dataOffset;
dataOffset += dataStream.dataLen;
}
}
beDataBuffer bePackedData::GetStream(beStringView name) const
{
DataStream const* stream = m_streams.AddressOf([name](auto&& iter) { return iter.name == name; });
if (!stream)
{
BE_ASSERT(false);
return {};
}
return {stream->data.GetBuffer(), stream->data.GetSize()};
}
void bePackedData::ReadStreams(std::FILE* file)
{
for (DataStream& dataStream : m_streams)
{
ReadStream(file, &dataStream);
}
// Verify we're at end of file
BE_ASSERT_CODE(u32 filePos = (u32)std::ftell(file);)
BE_ASSERT_CODE(std::fseek(file, 0, SEEK_END);)
BE_ASSERT(filePos == (u32)std::ftell(file));
}
void bePackedData::ReadStream(std::FILE* file, DataStream* dataStream)
{
beDataBuffer* dataBuffer = &dataStream->data;
dataBuffer->ResizeBuffer(dataStream->dataLen);
[[maybe_unused]] int ret = std::fseek(file, dataStream->fileOffset, SEEK_SET);
BE_ASSERT(ret == 0);
[[maybe_unused]] auto bytesRead = std::fread(dataBuffer->ModifyBuffer(), sizeof(u8), dataStream->dataLen, file);
BE_ASSERT(bytesRead == dataStream->dataLen);
}
|
7a68f2ab42d0e7172df5c50f31b74ce20a8079fe
|
95f7d3c14fc6180e62317c6e43087aaf0c74cb5b
|
/include/boost/url/bnf/impl/range.hpp
|
e8884fc7b1bf72fa19798be79f63992ea9578dab
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ExternalRepositories/url-1
|
445796d72ec164430eb7a2daed18966f99e537a7
|
9e4531d70c4d3571fe9ad11ba19130ee38291560
|
refs/heads/master
| 2023-08-30T06:06:28.944390
| 2021-10-31T02:35:51
| 2021-11-01T01:23:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,504
|
hpp
|
range.hpp
|
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/url
//
#ifndef BOOST_URL_BNF_IMPL_RANGE_HPP
#define BOOST_URL_BNF_IMPL_RANGE_HPP
#include <boost/url/detail/except.hpp>
namespace boost {
namespace urls {
namespace bnf {
template<class T>
bool
range::
parse_impl(
char const*& it,
char const* end,
error_code& ec,
range& t)
{
typename T::value_type t0;
auto start = it;
std::size_t n = 0;
if(! T::begin(it, end, ec, t0))
{
if(ec == error::end)
goto finish;
if(ec.failed())
return false;
}
for(;;)
{
++n;
if(! T::increment(
it, end, ec, t0))
{
if(ec == error::end)
break;
if(ec.failed())
return false;
}
}
finish:
t.str = string_view(
start, it - start);
t.count = n;
ec = {};
return true;
}
template<class T>
range::
range(T const*) noexcept
: fp_(&range::parse_impl<T>)
{
// Type requirements not met!
BOOST_STATIC_ASSERT(
is_range<T>::value);
}
inline
bool
parse(
char const*& it,
char const* end,
error_code& ec,
range& t)
{
return t.fp_(it, end, ec, t);
}
} // bnf
} // urls
} // boost
#endif
|
f6b2f15601838d85f79710d6b0dcff8a44952011
|
1b363ccfb93ca65052cdeaaf50702bdc37bb3779
|
/google_ai_ c/MyBot.cc
|
a69c4893fce979090aeadd664ba67b461a5d04df
|
[
"Apache-2.0"
] |
permissive
|
wesleyolis/google_plantwars
|
d4cb53ccd4aaa23d70b157680057f9ecf4ba5397
|
e4b832f2a9ce9bfa43cc343bd647ae4432f44166
|
refs/heads/master
| 2021-04-28T20:32:49.659127
| 2018-02-18T07:23:16
| 2018-02-18T07:23:16
| 121,928,363
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,856
|
cc
|
MyBot.cc
|
#include <iostream>
#include "PlanetWars.h"
FILE *fPtr;
// The DoTurn function is where your code goes. The PlanetWars object contains
// the state of the game, including information about all planets and fleets
// that currently exist. Inside this function, you issue orders using the
// pw.IssueOrder() function. For example, to send 10 ships from planet 3 to
// planet 8, you would say pw.IssueOrder(3, 8, 10).
//
// There is already a basic strategy in place here. You can use it as a
// starting point, or you can throw it out entirely and replace it with your
// own. Check out the tutorials and articles on the contest website at
// http://www.ai-contest.com/resources.
void DoTurn(PlanetWars& pw, int diff_ships) {
int num_planets = pw.planets_.size();
int* ptr_pcm_pos;
int* ptr_pcm_end;
int min_move_profit = 99999999;
int min_planet_to_profit = -1;
int c;
auto planet_min_cost = [&]()
{
if( ( diff_ships > 0 && pw.planets_[c].owner_ != 1 || pw.planets_[c].owner_ == 0 )
&& pw.planets_[c].growth_rate_ != 0 && pw.planets_[c].pred_numships <= 0 )
{
int moves = *ptr_pcm_pos -1 * pw.planets_[c].pred_numships/pw.planets_[c].growth_rate_;
if( moves < min_move_profit )
{
min_move_profit = moves;
min_planet_to_profit = c;
}
}
};
for ( int p = 0; p < num_planets; p++ )
{
if( pw.planets_[p].owner_ == 1 )
{
min_move_profit = 99999999;
min_planet_to_profit = -1;
//row base search optermization
ptr_pcm_pos = pw.planet_cost_matrix + p * num_planets;
ptr_pcm_end = ptr_pcm_pos + num_planets;
ptr_pcm_pos += p + 1;
for (c = 0 ; ptr_pcm_pos < ptr_pcm_end; ptr_pcm_pos++, c++ )
{
planet_min_cost();
}
//column Base search
ptr_pcm_pos = pw.planet_cost_matrix + p;
ptr_pcm_end = ptr_pcm_pos + num_planets * p;
for (c = 0 ; ptr_pcm_pos < ptr_pcm_end; ptr_pcm_pos++, c++ )
{
planet_min_cost();
}
/*
//column based search optermizations
for( int r = p; r < num_planets; r++)
{
int* ptr_pcm_end = ptr_pcm_pos + num_planets;
ptr_pcm_pos += r + 1;
for (int c = 0 ; ptr_pcm_pos < ptr_pcm_end; ptr_pcm_pos++, c++ )
{
if(pw.planets_[c].owner_ != 0)
{
int moves = *ptr_pcm_pos + pw.planets_[c].num_ships_/pw.planets_[c].growth_rate_;
if( moves < min_move_profit )
{
min_move_profit = moves;
min_planet_to_profit = c;
}
}
}
}
*/
if ( min_planet_to_profit != -1 )
{
int ships_to_send;
if( -1 * pw.planets_[min_planet_to_profit].pred_numships + 5 > pw.planets_[p].num_ships_ )
return;
else
ships_to_send = -1 * pw.planets_[min_planet_to_profit].pred_numships + 1 ;
pw.planets_[p].num_ships_ -= ships_to_send;
pw.planets_[min_planet_to_profit].num_ships_ += ships_to_send;
pw.planets_[min_planet_to_profit].pred_numships += ships_to_send;
pw.IssueOrder(p, min_planet_to_profit,ships_to_send);
}
}
}
return;
// (1) If we currently have a fleet in flight, just do nothing.
/* if (pw.MyFleets().size() >= 1) {
return;
}*/
// (2) Find my strongest planet.
int source = -1;
double source_score = -999999.0;
int source_num_ships = 0;
std::vector<Planet> my_planets = pw.MyPlanets();
for (int i = 0; i < my_planets.size(); ++i) {
const Planet& p = my_planets[i];
double score = (double)p.NumShips();
if (score > source_score) {
source_score = score;
source = p.PlanetID();
source_num_ships = p.NumShips();
}
}
// (3) Find the weakest enemy or neutral planet.
int dest = -1;
double dest_score = -999999.0;
std::vector<Planet> not_my_planets = pw.NotMyPlanets();
for (int i = 0; i < not_my_planets.size(); ++i) {
const Planet& p = not_my_planets[i];
double score = 1.0 / (1 + p.NumShips());
if (score > dest_score) {
dest_score = score;
dest = p.PlanetID();
}
}
// (4) Send half the ships from my strongest planet to the weakest
// planet that I do not own.
if (source >= 0 && dest >= 0) {
int num_ships = source_num_ships / 2;
pw.IssueOrder(source, dest, num_ships);
}
}
//#define get_char std::cin.get();
#define get_char c = std::cin.get(); putc(c,fPtr);
// This is just the main game loop that takes care of communicating with the
// game engine for you. You don't have to understand or change the code below.
void read_token( char* str, const char stop_token )
{
char c = stop_token;
char p = -1;
do
{
c = (char) get_char
str[++p] = c;
} while ( c != stop_token );
str[p] = '\0';
}
void read_skip_token(const char stop_token, char count)
{
char c;
for( char i = 0; i < count ; i++ )
{
do
{
c = std::cin.get();
putc(c,fPtr);
/*
{
fclose(fPtr);
fPtr = fopen("bot_log.txt","a");
}*/
}
while ( c != stop_token && c != '\n' );
}
}
void fast_pass_game()
{
char token[15];
bool initialize = true;
fPtr = fopen("bot_log.txt","w");
PlanetWars pw("");
double spacial_x_min = 0.0, spacial_y_min = 0.0, spacial_x_max = 0.0, spacial_y_max = 0.0;
int p = 0;
int f = 0;
int c = 0;
int numships;
int owner;
int des;
Planet planet;
Fleet fleet;
int enamy_ships = 0;
int my_ships = 0;
int diff_ships = 0;
bool run = true;
while ( run )
{
c = get_char
switch (c)
{
case '\n':
{
}break;
case '#':
{
read_skip_token('\n', 2);
} break;
case 'P':
{
get_char // read first blank char
if ( initialize )
{
//Read Planet information all on first path on bit on second pass
pw.planets_.push_back( planet );
//p = pw.planets_.size() - 1;
read_token( token, ' ' );
pw.planets_[p].x_ = atoi(token);
if( pw.planets_[p].x_ < spacial_x_min )
spacial_x_min = pw.planets_[p].x_;
if( pw.planets_[p].x_ > spacial_x_max )
spacial_x_max = pw.planets_[p].x_;
read_token( token, ' ' );
pw.planets_[p].y_ = atoi(token);
if( pw.planets_[p].y_ < spacial_y_min )
spacial_y_min = pw.planets_[p].y_;
if( pw.planets_[p].y_ > spacial_y_max )
spacial_y_max = pw.planets_[p].y_;
read_token( token, ' ' );
owner = atoi(token);
pw.planets_[p].owner_ = owner;
if ( owner != 1 )
numships = -numships;
read_token( token, ' ' );
numships = atoi(token);
pw.planets_[p].num_ships_ = numships;
pw.planets_[p].pred_numships = numships;
diff_ships += numships;
read_token( token, '\n' );
pw.planets_[p].growth_rate_ = atoi(token);
pw.planets_[p].planet_id_ = p;
p++;
}
else
{
read_skip_token(' ', 2);
read_token( token, ' ' );
owner = atoi(token);
pw.planets_[p].owner_ = owner;
read_token( token, ' ' );
pw.planets_[p].num_ships_ = atoi(token);
pw.planets_[p].pred_numships = (owner == 1)? numships: -1 * numships;
read_skip_token('\n', 1);
//read_token( fPtr, token, '\n' );
p++;
}
} break;
case 'F':
{
get_char // read first blank char
if ( f >= pw.fleets_.size() )
pw.fleets_.push_back(fleet);
read_token( token, ' ' );
owner = atoi(token);
pw.fleets_[f].owner_ = owner;
read_token( token, ' ' );
numships = atoi(token);
pw.fleets_[f].num_ships_ = numships;
read_token( token, ' ' );
pw.fleets_[f].source_planet_ = atoi(token);
if (owner != 1)
numships = -numships;
read_token( token, ' ' );
des = atoi(token);
pw.fleets_[f].destination_planet_ = des;
pw.planets_[des].pred_numships += numships;
diff_ships += numships;
read_token( token, ' ' );
pw.fleets_[f].total_trip_length_ = atoi(token);
read_token( token, '\n' );
pw.fleets_[f].turns_remaining_ = atoi(token);
f++;
}break;
case 'g':
{
c = get_char
if ( c == 'o' )
{
if ( initialize )
{
fprintf(fPtr,"%f\n", spacial_x_min );
fprintf(fPtr,"%f\n", spacial_x_max );
fprintf(fPtr,"%f\n", spacial_y_min );
fprintf(fPtr,"%f\n", spacial_y_max );
pw.calculate_matrix();
}
initialize = false;
c = get_char
if( c == '\n')
{
DoTurn(pw, diff_ships);
pw.FinishTurn();
pw.fleets_.clear();
p = 0;
f = 0;
enamy_ships = 0;
my_ships = 0;
diff_ships = 0;
}
}
}break;
default:
get_char;
fclose(fPtr);
//run = false;
}
}
delete pw.planet_cost_matrix;
}
int main(int argc, char *argv[]) {
fast_pass_game();
/* std::string current_line;
std::string map_data;
FILE *fPtr;
fPtr = fopen("bot_log.txt","a+");
while (true) {
int c = std::cin.get();
putc(c,fPtr);
current_line += (char)c;
if (c == '\n') {
if (current_line.length() >= 2 && current_line.substr(0, 2) == "go") {
PlanetWars pw(map_data);
map_data = "";
DoTurn(pw);
pw.FinishTurn();
} else {
map_data += current_line;
}
current_line = "";
}
}
fclose(fPtr);
*/
return 0;
}
/*
void read_token( FILE* fPtr, char* str, const char stop_token )
{
char c = stop_token;
char p = -1;
do
{
c = (char) std::cin.get();
putc(c, fPtr);
str[++p] = c;
} while ( c != stop_token );
str[p] = '\0';
}
void read_skip_token(const char stop_token, char count)
{
for( char i = 0; i < count ; i++ )
while ( std::cin.get() != stop_token );
}
void fast_pass_game()
{
std::string current_line;
std::string map_data;
char token[100];
FILE *fPtr = NULL;
fPtr = fopen("bot_log.txt","a+");
bool initialize = true;
PlanetWars pw("");
int p = 0;
int f = 0;
int c = 0;
Planet planet;
Fleet fleet;
while (true)
{
if( fPtr == NULL )
fPtr = fopen("bot_log.txt","a+");
c = std::cin.get();
map_data += (char) c;
switch (c)
{
case '\n':
{
putc('\n',fPtr);
putc('!',fPtr);
putc(c,fPtr);
}break;
case '#':
{
putc('\n',fPtr);
putc('#',fPtr);
do
{
c = std::cin.get();
putc(c,fPtr);
}
while ( c != '\n' );
} break;
case 'P':
{
std::cin.get();
if ( initialize )
{
putc('\n',fPtr);
putc('P',fPtr);
//Read Planet information all on first path on bit on second pass
pw.planets_.push_back( planet );
//p = pw.planets_.size() - 1;
read_token( fPtr, token, ' ' );
pw.planets_[p].x_ = atoi(token);
read_token( fPtr, token, ' ' );
pw.planets_[p].y_ = atoi(token);
read_token( fPtr, token, ' ' );
pw.planets_[p].owner_ = atoi(token);
read_token( fPtr, token, ' ' );
pw.planets_[p].num_ships_ = atoi(token);
read_token( fPtr, token, '\n' );
pw.planets_[p].growth_rate_ = atoi(token);
pw.planets_[p].planet_id_ = p;
p++;
}
else
{
read_skip_token(' ', 2);
read_token( fPtr, token, ' ' );
pw.planets_[p].owner_ = atoi(token);
read_token( fPtr, token, ' ' );
pw.planets_[p].num_ships_ = atoi(token);
read_skip_token('\n', 1);
//read_token( fPtr, token, '\n' );
p++;
}
} break;
case 'F':
{
std::cin.get();
putc('\n',fPtr);
putc('F',fPtr);
if ( f >= pw.fleets_.size() )
pw.fleets_.push_back(fleet);
read_token( fPtr, token, ' ' );
pw.fleets_[f].owner_ = atoi(token);
read_token( fPtr, token, ' ' );
pw.fleets_[f].num_ships_ = atoi(token);
read_token( fPtr, token, ' ' );
pw.fleets_[f].source_planet_ = atoi(token);
read_token( fPtr, token, ' ' );
pw.fleets_[f].destination_planet_ = atoi(token);
read_token( fPtr, token, ' ' );
pw.fleets_[f].total_trip_length_ = atoi(token);
read_token( fPtr, token, '\n' );
pw.fleets_[f].turns_remaining_ = atoi(token);
f++;
}break;
case 'g':
{
putc('\n',fPtr);
putc('g',fPtr);
c = std::cin.get();
putc(c,fPtr);
if ( c == 'o' )
{
c = std::cin.get();
putc(c,fPtr);
if( c == '\n')
{
putc('@',fPtr);
//std::cout << "go" << std::endl;
//std::cout.flush();
putc('%',fPtr);
//PlanetWars pw2(map_data);
//map_data = "";
DoTurn(pw);
pw.FinishTurn();
pw.fleets_.clear();
p = 0;
f = 0;
fclose(fPtr);
if( fPtr == NULL )
fPtr = fopen("bot_log.txt","a+");
// pw.FinishTurn();
}
}
initialize = false;
}break;
default:
{
putc('\n',fPtr);
putc('$',fPtr);
putc(c,fPtr);
}break;
}
}
fclose(fPtr);
}
*/
|
0185987e5799de92ea3310dcfc4dfdc9ffb43c73
|
23a405404b3238e9d7bb24f852f69d3f558183d9
|
/吉田学園情報ビジネス専門学校 竹内亘/01_シューティングゲーム/開発環境/シューティングゲーム/clear.cpp
|
408bc2055deea37208b955faf8ea9c8cec583d0f
|
[] |
no_license
|
takeuchiwataru/TakeuchiWataru_QMAX
|
fa25283aa90bcedb75dd650613d8d828a3f8f81a
|
cd5d6f75ca258f58df934d40a8ea238976e7c69d
|
refs/heads/master
| 2022-02-07T16:33:12.052935
| 2019-06-12T04:32:08
| 2019-06-12T04:32:08
| 191,302,573
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 4,585
|
cpp
|
clear.cpp
|
//=============================================================================
//
// ゲームクリア処理 [clear.cpp]
// Author : 竹内亘
//
//=============================================================================
#include "main.h"
#include "clear.h"
#include "input.h"
#include "fade.h"
#include "sound.h"
#include "boss.h"
//*****************************************************************************
// マクロ定義
//*****************************************************************************
#define CLEAR_TEXTURENAME "data/TEXTURE/CLEAR.jpg" //ゲームオーバーテクスチャ
#define CLEAR_POS_X (0) //背景の左上X座標
#define CLEAR_POS_Y (0) //背景の左上Y座標
#define CLEAR_WIDTH (SCREEN_WIDTH) //背景の幅
#define CLEAR_HEIGHT (SCREEN_HEIGHT) //背景の高さ
//*****************************************************************************
// グローバル変数
//*****************************************************************************
LPDIRECT3DTEXTURE9 g_pTextureClear = NULL; //テクスチャへのポインタ
LPDIRECT3DVERTEXBUFFER9 g_pVtxBuffClear = NULL; //頂点バッファへのポインタ
//=============================================================================
// ゲームクリア初期化処理
//=============================================================================
void InitClear(void)
{
LPDIRECT3DDEVICE9 pDevice; //デバイスへのポインタ
//デバイスの取得
pDevice = GetDevice();
// テクスチャの読み込み
D3DXCreateTextureFromFile(pDevice, CLEAR_TEXTURENAME, &g_pTextureClear);
// 頂点バッファの生成
pDevice->CreateVertexBuffer(sizeof(VERTEX_2D) * 4, // 確保するバッファのサイズ
D3DUSAGE_WRITEONLY,
FVF_VERTEX_2D, // 頂点フォーマット
D3DPOOL_MANAGED,
&g_pVtxBuffClear,
NULL);
VERTEX_2D *pVtx; // 頂点情報へのポインタ
// 頂点バッファをロックし、頂点データへのポインタを取得
g_pVtxBuffClear->Lock(0, 0, (void**)&pVtx, 0);
// 頂点座標の設定
pVtx[0].pos = D3DXVECTOR3(CLEAR_POS_X, CLEAR_POS_Y, 0.0f);
pVtx[1].pos = D3DXVECTOR3(CLEAR_WIDTH, CLEAR_POS_Y, 0.0f);
pVtx[2].pos = D3DXVECTOR3(CLEAR_POS_X, CLEAR_HEIGHT, 0.0f);
pVtx[3].pos = D3DXVECTOR3(CLEAR_WIDTH, CLEAR_HEIGHT, 0.0f);
// rhwの設定
pVtx[0].rhw = 1.0f;
pVtx[1].rhw = 1.0f;
pVtx[2].rhw = 1.0f;
pVtx[3].rhw = 1.0f;
// 頂点カラー
pVtx[0].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[1].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[2].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[3].col = D3DCOLOR_RGBA(255, 255, 255, 255);
// テクスチャ座標の設定
pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f);
pVtx[1].tex = D3DXVECTOR2(1.0f, 0.0f);
pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f);
pVtx[3].tex = D3DXVECTOR2(1.0f, 1.0f);
// 頂点バッファをアンロック
g_pVtxBuffClear->Unlock();
PlaySound(SOUND_LABEL_SE_GAMECLEAR);
}
//=============================================================================
// ゲームクリア終了処理
//=============================================================================
void UninitClear(void)
{
// テクスチャの破棄
if (g_pTextureClear != NULL)
{
g_pTextureClear->Release();
g_pTextureClear = NULL;
}
// 頂点バッファの破棄
if (g_pVtxBuffClear != NULL)
{
g_pVtxBuffClear->Release();
g_pVtxBuffClear = NULL;
}
}
//=============================================================================
// ゲームクリア更新処理
//=============================================================================
void UpdateClear(void)
{
if (GetKeyboardTrigger(DIK_RETURN) == true)
{
FADE *pFade;
pFade = GetFade();
//PlaySound(SOUND_LABEL_SE_DECIDE);
if (*pFade != FADE_OUT)
{
StopSound(SOUND_LABEL_SE_GAMECLEAR);
SetFade(MODE_RANKING);
}
}
}
//=============================================================================
// ゲームクリア描画処理
//=============================================================================
void DrawClear(void)
{
LPDIRECT3DDEVICE9 pDevice; // デバイスへのポインタ
// デバイスを取得する
pDevice = GetDevice();
// 頂点バッファをデバイスのデータストリームに設定
pDevice->SetStreamSource(0, g_pVtxBuffClear, 0, sizeof(VERTEX_2D));
// 頂点フォーマットの設定
pDevice->SetFVF(FVF_VERTEX_2D);
// テクスチャの設定
pDevice->SetTexture(0, g_pTextureClear);
// ポリゴンの描画
pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
}
|
cf20a81ae82bb6e6f8db899332a971e9b62176e9
|
527a7c9af1d8ab969ac3a40f1258e7ebfe37837f
|
/servo.ino
|
a810cda3e46aecfecd7b7d46827367ba13054c77
|
[] |
no_license
|
WSU-RoboticsClub/Door-Automation
|
fecf8dd91930e105c4bc1a151ac6ccda723a3bd0
|
5fef8f090d2eccf2fa3de34e52fccae50f8e605e
|
refs/heads/master
| 2016-09-06T05:59:01.085268
| 2015-05-28T00:22:26
| 2015-05-28T00:22:26
| 34,482,588
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,996
|
ino
|
servo.ino
|
/*
TODO:
- Change servo back to using angular values instead of power levels.
- http://www.instructables.com/id/Cheap-2-Way-Bluetooth-Connection-Between-Arduino-a/?ALLSTEPS
*/
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myServo;
char receivedChar; // User's serial input
char stop_rotate; //Input for reading while spinning
int LED1 = 13; // LED on pin 13
int LED2 = 8; // Second LED on pin 8
SoftwareSerial mySerial(0, 1); // RX, TX
int ccw_count = 0;
// RX on Bluetooth to TCX on Arduino through a voltage divider 50ohm from arduino and 100ohm to ground.
// This is so we can drop the the voltage down to 3.3v (roughly)
// Use blueterm on android to get messages. Does NOT work on IOS.
void setup()
{
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
myServo.attach(8);
myServo.write(0);
// forward(0);
// Open serial communications and wait for port to open:
mySerial.begin(9600);
mySerial.println("DOORBUSTER project using bluetooth communication");
delay(1000);
mySerial.println("Sending a 1 rotates clockwise 180 degrees, then counter clockwise 180 degrees");
mySerial.println("Sending a 0 during the clockwise rotation will reset back to 0...hopefully");
delay(1000);
}
void loop() // Event loop runs forever
{
digitalWrite(8, HIGH);
// stay here so long as COM port is empty
while (!mySerial.available());
receivedChar = mySerial.read();
delay(1000);
if ('0' == receivedChar)
{
//digitalWrite(LED1, HIGH);
myServo.write(0);
}
else if ('1' == receivedChar)
{
receivedChar = 0;
//digitalWrite(LED1, LOW);
CW(5);
//digitalWrite(LED2, HIGH);
delay(3000);
CCW(5);
//digitalWrite(LED2, LOW);
}
else if ('2' == receivedChar)
{
receivedChar = 0;
//digitalWrite(LED1, LOW);
CW(5);
while(receivedChar != '3')
{
receivedChar = mySerial.read();
}
CCW(5);
}
}
void CW(int speed) // aka clockwise
{
for(int pos = 0; pos <= 180; pos++) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myServo.write(pos); // tell servo to go to position in variable 'pos'
delay(speed); // waits 15ms for the servo to reach the position\
ccw_count = pos;
stop_rotate = mySerial.read();
if(stop_rotate == '0')
break;
}
return;
}
void CCW(int speed) // aka counter clockwise
{
for(int pos = ccw_count; pos >= 0 ; pos--) // goes from 180 degrees to 0 degrees
{
myServo.write(pos); // tell servo to go to position in variable 'pos'
delay(speed); // waits 15ms for the servo to reach the position
stop_rotate = mySerial.read();
}
return;
}
/*
void forward(int powerLevel)
{
if (300 < powerLevel)
powerLevel = 300;
myServo.writeMicroseconds(1500 + powerLevel);
}
void backward(int powerLevel)
{
if (300 < powerLevel)
powerLevel = 300;
myServo.writeMicroseconds(1500 - powerLevel);
}
*/
|
f0188b8592f443ea0b689e05f5a1d105c2b3145b
|
bcce017599467b4836b7e71812ec22f0142276e6
|
/fromGerardo/ROS_nodes/rh_calibration/include/rh_calibration/RHcalibration.h
|
ffbd78b3d3cad54a01b8de53cbcb5546e5967d5b
|
[] |
no_license
|
mcdonalda1993/binocular_vision_alg
|
61db3efc74e3820df8eae6ad4b326a955738da61
|
7a3ad9ac074c352ed2b359ff657ac86efd30b373
|
refs/heads/master
| 2020-04-22T10:13:28.697705
| 2014-11-06T22:53:10
| 2014-11-06T22:53:10
| 24,841,447
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,392
|
h
|
RHcalibration.h
|
// main include file
#include <iostream>
#include <sstream>
#include <time.h>
#include <stdlib.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <cvsba/cvsba.h>
#include <vector>
#include <errno.h>
#include <fstream>
#include <math.h>
using namespace cv;
using namespace std;
#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <std_msgs/String.h>
#include <sensor_msgs/JointState.h>
#include <message_filters/synchronizer.h>
#include <image_transport/subscriber_filter.h>
//#include <message_filters/sync_policies/exact_time.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/subscriber.h>
#include <image_transport/image_transport.h>
#include <message_filters/synchronizer.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <ros/package.h>
#include <rh_cameras/CamerasSync.h>
#include <rh_cameras/SetCameraInfo.h>
#include <rh_ptu/GetPtuInfo.h>
#include <rh_ptu/MovePtu.h>
#include <sensor_msgs/CameraInfo.h>
#include <rh_calibration/CameraCalibration.h>
#include <rh_calibration/HandEyeCalibration.h>
#include <cvsba/cvsba.h>
#include <rh_integration/MarkerDetection.h>
namespace enc = sensor_msgs::image_encodings;
#define DEBUG true
|
e76ea2117b425ec6ee685fc3964297e5765a330b
|
7af474a7a1d4ddff3cc84b299d2cf9e3c1fdd6c6
|
/files.cpp
|
9b400d3c4d83f2abd7d43ba42a3c4f1d894ef1c0
|
[] |
no_license
|
ameliameyer/cs16_notes_w20
|
5546e4ce0eb1d6d488d368de6b64d2a6dc1cb6bb
|
59858735266a98ad5399ed183ed1a33853f3ca82
|
refs/heads/master
| 2020-12-22T16:07:06.849878
| 2020-02-06T22:53:54
| 2020-02-06T22:53:54
| 236,853,164
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,501
|
cpp
|
files.cpp
|
// Two ways of providing inputs: cin, command line arguments, read from file
// Ways to output data: cout, cerr, write to file
// Command line arguments go to the main function
// Program and file are both in memory
#include <iostream>
#include <fstream>
using namespace std;
/* Writing to a file
int main(){
ofstream ofs; // Create a ifstream object, making the local variable ofs
// ofstream is a type
ofs.open("animals.txt"); // Open a file to write, will create that file if it doesn't
// already exist and establish a pipe between them
ofs<<"Duck\n"<<"Cat\n"<<"Cow\n"; // The use is similar to cout as you can see
ofs.close();
return 0;
}
*/
int main(){
ifstream ifs; // Create a ifstream object
ifs.open("number.txt"); // Open a file to read
if(!ifs){
// open failed
cerr<<"File does not exist"<<endl;
exit();
}
getline(ifs, line); // Read a line from the file into a string line
// If you attempt to read past the end of file, ifs change to false
// ifs is ifstream and line is a variable of type string
cout<<line;
ifs.close();
// if we want to read until the end of the file
/*
while(ifs){
getline(ifs,line);
cout<<line<<endl;
}
if you attempt to read past the end of the file, only then will ifs become false
so you actually have to do one more read than number of lines
*/
return 0;
}
|
d7318275eb4537f7b575faec1c185a2b8217c720
|
d11dfb3a629b1efca2e7f9ad15a6d134c7d051bc
|
/zlibrary/core/src/network/ZLNetworkXMLParserData.h
|
f629e24f82bd161fe0d8259a4fafb032b8d074b2
|
[] |
no_license
|
stsg/fbreaderosx
|
2bbf5d5d09fd17d998187b528f0fcc4629d66fb8
|
a0971d6a7283a764068814ca8da16316359f57eb
|
refs/heads/master
| 2021-01-18T13:49:16.076718
| 2015-03-28T09:55:06
| 2015-03-28T09:55:06
| 33,026,187
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,211
|
h
|
ZLNetworkXMLParserData.h
|
/*
* Copyright (C) 2008-2009 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#ifndef __ZLNETWORKXMLPARSERDATA_H__
#define __ZLNETWORKXMLPARSERDATA_H__
#include <shared_ptr.h>
#include "ZLNetworkData.h"
class ZLXMLReader;
class ZLNetworkXMLParserData : public ZLNetworkData {
public:
ZLNetworkXMLParserData(const std::string &url, shared_ptr<ZLXMLReader> reader);
~ZLNetworkXMLParserData();
private:
shared_ptr<ZLXMLReader> myReader;
};
#endif /* __ZLNETWORKXMLPARSERDATA_H__ */
|
5cf9b4e8428f874470636a908cc8ea8180cdb370
|
c3c9c1770b18e7476d015186003a555417d8e564
|
/Unit1.cpp
|
2901962df3de803439265a3376f6ac33068bdea3
|
[] |
no_license
|
Kalmykov501/MyRepo
|
5bb87a6fb3a1c13e43ee456465b1035f01de2102
|
6040aba2193335ad544bdc8ae581ff95f30a58d6
|
refs/heads/master
| 2023-04-28T05:53:31.805623
| 2021-05-17T18:51:04
| 2021-05-17T18:51:04
| 368,280,179
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,555
|
cpp
|
Unit1.cpp
|
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include <math.hpp>
#include <jpeg.hpp>
#include <graphics.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
float a, b, c, x, y, imw, imh, imw2, imh2;
int i;
boolean indgrid = false;
TLabel *Lab1[5], *Lab2[5];
AnsiString fname;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
Image1->Canvas->Brush->Color = clWhite;
Image1->Canvas->Pen->Color = clBlack;
imw = Image1->Width;
imh = Image1->Height;
Image1->Canvas->Rectangle(0, 0, imw, imh);
Image2->Canvas->Brush->Color = clWhite;
Image2->Canvas->Pen->Color = clBlack;
imw2 = Image2->Width;
imh2 = Image2->Height;
Image2->Canvas->Rectangle(0, 0, imw2, imh2);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Button2Click(Button2);
Button3Click(Button3);
Image1->Canvas->Pen->Color = (TColor)RGB(255, 0, 0);
Image1->Canvas->Pen->Width = 2;
x = 1e-6;
switch (ComboBox1->ItemIndex) {
case 0:
Image1->Canvas->MoveTo(0, 0);
while (x < imw) {
y = imh / 2 * sin(x / 10) / (x / 10);
Image1->Canvas->LineTo(x, imh / 2 - y);
x++;
}
break;
case 1:
Image1->Canvas->MoveTo(x, -0.03 * imh / 2 * cos(x / 10) * (x / 10) + imh / 2);
while (x < imw) {
y = 0.03 * imh / 2 * cos(x / 10) * (x / 10);
Image1->Canvas->LineTo(x, imh / 2 - y);
x++;
}
break;
default: ;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Image1->Canvas->FillRect(Rect(0, 0, imw, imh));
Image1->Canvas->Pen->Color = clBlack;
Image1->Canvas->Pen->Width = 1;
Image1->Canvas->Rectangle(0, 0, imw, imh);
indgrid = !indgrid;
Button3Click(Button3);
if (Lab1[0] != 0) {
for (i = 0; i < 5; i++) {
Lab1[i]->Caption = "";
Lab2[i]->Caption = "";
}
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
float dx, dy;
dx = imw / 4;
dy = imh / 4;
Image1->Canvas->Pen->Width = 1;
if (indgrid)
Image1->Canvas->Pen->Color = clBlack;
else
Image1->Canvas->Pen->Color = clWhite;
indgrid = !indgrid;
for (i = 1; i < 4; i++) {
x = 0;
y = dy * i;
Image1->Canvas->MoveTo(1, y);
Image1->Canvas->LineTo(imw, y);
}
for (i = 1; i < 4; i++) {
y = 1;
x = dx * i;
Image1->Canvas->MoveTo(x, y);
Image1->Canvas->LineTo(x, imh);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
for(i = 0; i < 5; i++){
Lab1[i] = new TLabel(Form1);
Lab1[i]->Parent = Form1;
Lab1[i]->Top = Image1->Top + imh + 5;
Lab1[i]->Left = Image1->Left + imw / 4 * i -10;
Lab1[i]->Alignment = taCenter;
Lab1[i]->Caption = FloatToStrF(imw / 4 * i / 10, ffFixed, 5, 1);
}
for (i = 0; i < 5; i++) {
Lab2[i] = new TLabel(Form1);
Lab2[i]->Parent = Form1;
Lab2[i]->Top = Image1->Top + imh - 8 - imh / 4 * i;
Lab2[i]->Left = Image1->Left - 25;
Lab2[i]->Caption = FloatToStrF(2. / 4 * i, ffFixed, 5, 1);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button5Click(TObject *Sender)
{
if (OpenPictureDialog1->Execute()) {
fname = OpenPictureDialog1->FileName;
Image2->Picture->LoadFromFile(fname);
Image2->Proportional = true;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button6Click(TObject *Sender)
{
Image2->Picture->Bitmap->FreeImage();
Image2->Canvas->Brush->Color = clWhite;
Image2->Canvas->Pen->Color = clBlack;
Image2->Picture->Graphic->SetSize(imw2, imh2);
Image2->Canvas->Rectangle(0, 0, imw2, imh2);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::N2Click(TObject *Sender){
Button1Click(Button1);
}
void __fastcall TForm1::N3Click(TObject *Sender){
Button2Click(Button2);
}
void __fastcall TForm1::N4Click(TObject *Sender){
Button3Click(Button3);
}
void __fastcall TForm1::N5Click(TObject *Sender){
Button4Click(Button4);
}
void __fastcall TForm1::N7Click(TObject *Sender){
Button5Click(Button5);
}
void __fastcall TForm1::N8Click(TObject *Sender){
Button6Click(Button6);
}
|
76438a12988a77d66227209808e285850afa2a06
|
75148b84e45be73a5119f499167b60387e628f50
|
/kości/exceptions.h
|
2d63ea3e768a02f06529e6645ea81080cea0ba9a
|
[] |
no_license
|
petriczi/diceGame
|
bb95bdccf05215b765f65235cf8fd949c3540ece
|
83ab858bacb3af66e84c066858a0943056966df6
|
refs/heads/master
| 2020-03-11T14:53:59.507981
| 2018-04-18T13:43:43
| 2018-04-18T13:43:43
| 130,068,587
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,259
|
h
|
exceptions.h
|
#ifndef exceptions
#define exceptions
#include<string>
using namespace std;
class exception_generator
{
private:
int error_code;
string message;
public:
exception_generator(int error_code, const string& message)
:error_code(error_code),
message(message)
{}
int err_template()//error template always close programm
const {
cout << this->message;
cout << endl;
system("pause");
exit(this->error_code);
}
string war_template()//warning template only shows info
const {
cout << "Warning: " << this->error_code;
return this->message;
}
};
class err_number_dice : public exception_generator
{
public:
err_number_dice() : exception_generator(1, "Error.Bad random number of dice") {};
};
class err_numbers_to_random : public exception_generator
{
public:
err_numbers_to_random() : exception_generator(3, "You can't change more numbers than 5, because You have only 5 dices.") {};
};
class err_bad_option : public exception_generator
{
public:
err_bad_option() : exception_generator(4, "Select '1' or '2'") {};
};
class err_randomize_changes: public exception_generator
{
public:
err_randomize_changes() : exception_generator(5, "You haven't chances to randomize again in this round.\n\n") {};
};
#endif
|
557246d0a87e383ac34b4523d3447d1f6902afcc
|
97b6b5e0ea8f4de7a762b513a8bd1f4b43500f16
|
/src/include/concore/detail/platform.hpp
|
cbac091410c7ed0befa45693e28bb6eb35360fb5
|
[
"MIT"
] |
permissive
|
lucteo/concore
|
5d73abc9f216e1f48f48194000e8bb56194c68b2
|
ffbc3b8cead7498ddad601dcf357fa72529f81ad
|
refs/heads/master
| 2022-01-14T20:30:23.519658
| 2021-08-15T14:10:52
| 2021-08-15T14:10:52
| 229,525,104
| 62
| 4
|
MIT
| 2021-08-15T14:10:52
| 2019-12-22T05:58:05
|
C++
|
UTF-8
|
C++
| false
| false
| 2,188
|
hpp
|
platform.hpp
|
#pragma once
// User can specify a "platform include" that can override everything that's in here
#ifdef CONCORE_PLATFORM_INCLUDE
#include CONCORE_PLATFORM_INCLUDE
#endif
// Detect the platform (if we were not given one)
#ifndef CONCORE_PLATFORM
#if __APPLE__
#define CONCORE_PLATFORM_APPLE 1
#elif __linux__ || __FreeBSD__ || __NetBSD__ || __OpenBSD__
#define CONCORE_PLATFORM_LINUX 1
#elif _MSC_VER && __MINGW64__ || __MINGW32__
#define CONCORE_PLATFORM_WINDOWS 1
#else
#define CONCORE_PLATFORM_UNKNOWN 1
#endif
#define CONCORE_PLATFORM(X) (CONCORE_PLATFORM_##X)
#endif
// Detect processor type, if not given
#if !defined(CONCORE_CPU_ARCH)
#if defined(_M_ARM) || defined(__arm__) || defined(__aarch64__)
#define CONCORE_CPU_ARCH_arm 1
#elif defined(_M_X64) || defined(__x86_64__)
#define CONCORE_CPU_ARCH_x86_64 1
#elif defined(_M_IX86) || defined(__i386__)
#define CONCORE_CPU_ARCH_x86_32 1
#elif defined(__ia64__) || defined(_M_IA64)
#define CONCORE_CPU_ARCH_ia64 1
#else
#define CONCORE_CPU_ARCH_generic 1
#endif
#define CONCORE_CPU_ARCH(X) (CONCORE_CPU_ARCH_##X)
#endif
// Detect the C++ version
#ifndef CONCORE_CPP_VERSION
#if __cplusplus == 201103L
#define CONCORE_CPP_VERSION 11
#elif __cplusplus == 201402L
#define CONCORE_CPP_VERSION 14
#elif __cplusplus == 201703L
#define CONCORE_CPP_VERSION 17
#else
// Assume C++20
#define CONCORE_CPP_VERSION 20
#endif
// Detect the compiler type
#ifndef CONCORE_CPP_COMPILER
#if defined(__clang__)
#define CONCORE_CPP_COMPILER_clang 1
#elif defined(__GNUC__) || defined(__GNUG__)
#define CONCORE_CPP_COMPILER_gcc 1
#elif defined(_MSC_VER)
#define CONCORE_CPP_COMPILER_msvc 1
#elif defined(__INTEL_COMPILER)
#define CONCORE_CPP_COMPILER_intel 1
#else
#define CONCORE_CPP_COMPILER_UNKNOWN 1
#endif
#define CONCORE_CPP_COMPILER(X) (CONCORE_CPP_COMPILER_##X)
#endif
// Detect use of pthreads; use it on Linux
#if !CONCORE_USE_PTHREADS && CONCORE_PLATFORM_LINUX
#define CONCORE_USE_PTHREADS 1
#else
#define CONCORE_USE_PTHREADS 0
#endif
// Detect the use of libdispatch; use it on Apple
#if !CONCORE_USE_PTHREADS && CONCORE_PLATFORM_APPLE
#define CONCORE_USE_LIBDISPATCH 1
#else
#define CONCORE_USE_LIBDISPATCH 0
#endif
#endif
|
1bef6b6a7da4fb834c5fd216fac8153a0c2ace89
|
1ea0b03c45886ed94523fa21a591bbc041809b5c
|
/Week 1/Problem 1/Problem_1.cpp
|
540a1cfdb6600d3478386b27deee3efbba70635c
|
[] |
no_license
|
Ayush0084/DAA_LAB_ASSIGNMENTS-
|
a041b14356c0fa571415a24fb2706805385a4e18
|
d5c1a50f5baedc51e89435323e30b2dc5c6ec3b8
|
refs/heads/main
| 2023-08-14T13:42:35.286509
| 2021-09-23T13:17:27
| 2021-09-23T13:17:27
| 409,596,410
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 671
|
cpp
|
Problem_1.cpp
|
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
int main()
{
ifstream in("input.txt");
ofstream out("output.txt");
int t;
in >> t;
while (t--)
{
int n,x,count;
in >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
in >> arr[i];
}
in >> x;
count = 0;
for (int i = 0; i < n; i++)
{
count++;
if(x == arr[i])
{
out << "Present " << count << endl;
goto outer;
}
}
out << "Not Present " << count << endl;
outer: continue;
}
return 0;
}
|
539833ad20ec8eed814a93fbc0d31e67d0ef13fd
|
b6607ecc11e389cc56ee4966293de9e2e0aca491
|
/codeforces.com/Contests/423 div 2/C/C.cpp
|
3db03cde7a59bb482ff519a7c4219eb12fb8214b
|
[] |
no_license
|
BekzhanKassenov/olymp
|
ec31cefee36d2afe40eeead5c2c516f9bf92e66d
|
e3013095a4f88fb614abb8ac9ba532c5e955a32e
|
refs/heads/master
| 2022-09-21T10:07:10.232514
| 2021-11-01T16:40:24
| 2021-11-01T16:40:24
| 39,900,971
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,782
|
cpp
|
C.cpp
|
/*****************************************
** Solution by Bekzhan Kassenov **
*****************************************/
#include <bits/stdc++.h>
using namespace std;
#define by(T, x) [](const T& a, const T& b) { return a.x < b.x; }
#define all(x) (x).begin(), (x).end()
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
const double EPS = 1e-9;
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
const int MAXN = 1100000;
template <typename T>
inline T sqr(T n) {
return n * n;
}
char mem[2 * MAXN];
char* memptr = mem;
char* s[MAXN];
int len[MAXN];
void reads(int i) {
scanf("\n%s", memptr);
s[i] = memptr;
len[i] = strlen(s[i]);
memptr = memptr + (len[i] + 1);
}
int n;
char res[2 * MAXN];
vector <char*> open[2 * MAXN];
vector <pair <int, char*> > close[2 * MAXN];
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
scanf("%d", &n);
int total = 0, k, x;
for (int i = 0; i < n; i++) {
reads(i);
scanf("%d", &k);
for (int j = 0; j < k; j++) {
scanf("%d", &x);
x--;
open[x].push_back(s[i]);
close[x + len[i] - 1].push_back(make_pair(x, s[i]));
total = max(total, x + len[i] - 1);
}
}
multiset <pair <int, char*> > cur;
for (int i = 0; i <= total; i++) {
for (char* ptr : open[i]) {
cur.emplace(i, ptr);
}
if (!cur.empty()) {
pair <int, char*> some = *cur.begin();
char c = some.second[i - some.first];
res[i] = c;
} else {
res[i] = 'a';
}
for (auto p : close[i]) {
cur.erase(cur.find(p));
}
}
puts(res);
return 0;
}
|
9b9ce440c847f277a1ae479dcc9fbf0df7aa02a2
|
53d7f089f4714562de0bc8425655a30630ed8ce1
|
/test.cpp
|
f8534f99906fd20c8d5be14a859c64d517b39eb6
|
[] |
no_license
|
smolvik/cpp_motor_model
|
da3ac68df30c5f348c2913c0cf1d4c14781ee262
|
1934f1044e7c9d6fb6503b18b1e4e755a1f8156e
|
refs/heads/master
| 2020-05-09T16:43:36.691239
| 2019-06-28T14:13:54
| 2019-06-28T14:13:54
| 181,280,760
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,793
|
cpp
|
test.cpp
|
#include <iostream>
#include <math.h>
#include <stdint.h>
#include <complex>
#include "tgaimage.h"
#include "geometry.h"
#include "tgaplotter.h"
#include "driver.h"
#include "filter.h"
int32_t antcor(int32_t x, int32_t wdv)
{
static DigFilter2 flt1(-1819, 821, 0, 81919, -81919, 10, 10+7);
static DigFilter2 flt2(-2019, 996, 0, 10240, -10240, 10, 10+10);
static DigFilter1 flt3_1(-1004, 5243, 0, 10, 10+8);
static DigFilter1 flt3_2(-1004, 5243, 0, 10, 10+8);
static DigFilter1 flt4(-996, 7282, 0, 10, 10+8);
static DigFilter1 flt5(-896, 131072, -131072, 10, 10+10);
int32_t num = flt3_1(abs(flt1(x))); //flt3(abs(flt1(x)));
int32_t den = flt3_2(abs(flt2(x))); //flt3(abs(flt2(x)));
//cout << num << ":" << den << endl;
if(den == 0) den = 1;
int32_t zn = flt4(num/den);
int32_t pf = abs(100*flt5(x));
int32_t kw = 0;
if(pf == 0) {
kw = wdv<<1;
}
else {
if(zn < 8) kw = wdv>>2;
else if(zn<12) kw = wdv;
else if(zn<18) kw = wdv + (wdv>>1);
else if(zn<25) kw = wdv + (wdv>>1) + (wdv>>2);
else kw = wdv<<1;
}
//cout << zn << endl;
return zn;
//return kw;
//return pf;
}
/*
int main(int argc, char **argv)
{
double dt = 4e-6;
double tmax = 10;
double klin = 1.57/1000;
double aex = 0.0;
if(argc < 2) return 0;
aex = atof(argv[1]);
Driver driver(dt);
double spdmax = 0.0;
TGAPlotter plot4("curr.tga", tmax,Vec3d(100,100,100));
TGAPlotter plot5("step.tga", tmax,Vec3d(0.05,0.05,0.05));
for( double t=0.0 ; t<tmax ; t+= dt ){
//double v1 = (t<0.2)?10:0;
double v1 = aex;
Vec3d vs = driver(v1);
//cout << vs << endl;
plot5(Vec3d(v1*klin,vs.x,0), t);
plot4(driver.motor->getcurr(), t);
double linspd = vs.y;
if(abs(linspd) > spdmax) spdmax = abs(linspd);
}
std::cout << spdmax*1000 << " mm/s" << std::endl;
return 0;
}
*/
#define NFFT 16
complex<int32_t> wtbl[NFFT];
complex<int32_t> fft(int k, int32_t *x, int n, int is, int d)
{
complex<int32_t> c = 0;
if (n == 1) {
int32_t arg = (k<<(int32_t)log2(NFFT/2)) & (NFFT-1);
c = 10000*x[is] + x[is+d]*wtbl[arg];
}
else {
int32_t arg = (k<<((int32_t)log2(NFFT)-n)) & (NFFT-1);
c = fft(k, x, n-1, is, d<<1) + wtbl[arg]*(fft(k, x, n-1, is+d, d<<1)/10000);
}
return c;
}
complex<double> fft(int k, double *x, int n, int is, int d)
{
complex<double> c = 0;
if (n == 2) {
complex<double> arg = -M_PI*k*1i;
c = x[is] + x[is+d]*exp(arg);
}
else {
complex<double> arg = -(2*M_PI*k/n)*1i;
c = fft(k, x, n/2, is, d*2) + exp(arg)*fft(k, x, n/2, is+d, d*2);
}
return c;
}
union UNI_UARTCWORD
{
uint64_t d64;
struct
{
uint64_t ref1 : 12;
uint64_t ref2 : 12;
uint64_t ref3 : 12;
uint64_t cw_bof3 : 1;
uint64_t cw_bof2 : 1;
uint64_t cw_bof1 : 1;
uint64_t cw_emul : 1;
uint64_t cw_pwon : 1;
uint64_t cw_cal3 : 1;
uint64_t cw_cal2 : 1;
uint64_t cw_cal1 : 1;
uint64_t cw_gmod : 1;
uint64_t cw_res1 : 1;
uint64_t cw_res2 : 1;
uint64_t cw_res3 : 1;
uint64_t crc : 16;
}
b;
};
int main(int argc, char **argv)
{
int32_t x[NFFT];
double xd[NFFT];
double ftst = 32;
double fs = 5.0*NFFT;
//union UNI_UARTCWORD tu;
//printf("%d\n", sizeof(tu));
//return 0;
for(int i = 0; i < NFFT; i++){
complex<double> arg = -(2*M_PI/NFFT)*i*1i;
wtbl[i] = 10000.0*exp(arg);
//wtbl[i] = complex<int32_t>( round(1000.0*cos(-(2*M_PI/NFFT)*i)), round(1000.0*sin(-(2*M_PI/NFFT)*i)) );
x[i] = round(1000*cos(2*M_PI*ftst*i/fs));
xd[i] = 1000*cos(2*M_PI*ftst*i/fs);
}
for(int k = 0; k < NFFT; k++){
complex<int32_t> c = (fft(k, x, log2(NFFT), 0, 1)+500)/1000;
//complex<double> c = fft(k, xd, NFFT, 0, 1);
cout << abs(c) << endl;
//cout << wtbl[k] << endl;
}
return 0;
}
/*
int main(int argc, char **argv)
{
double dt = 4e-6;
double tmax = 1;
double aex = 0;
double fex = 10;
int cnt = 0;
double v1 = 0;
double v2 = 0;
aex = atof(argv[1]);
fex = atof(argv[2]);
//RejFilter flt1(38.4, 0.952, 0.57, 1/320e-6);
//RejFilter flt2(58.7, 0.781, 0.45, 1/320e-6);
RejFilter flt1(35, 0.7, 0.85, 1/320e-6);
RejFilter flt2(35, 0.7, 0.4, 1/320e-6);
TGAPlotter plot5("step.tga", tmax,Vec3d(5000,5000,5000));
for( double t=0.0 ; t<tmax ; t+= dt ){
//v1 = aex;
v1 = (t<0.2)?0:aex;
//v1 = aex*sin(2*M_PI*fex*t);
//v1 = aex*sign(sin(2*M_PI*5*t));
// 3000 Hz
//if(0==(cnt++%80)) v2 = flt2(v1);
if(0==(cnt++%80)) v2 = flt2(flt1(v1));
//if(0==(cnt++%80)) v2 = antcor(v1,1000);
//cout << vs << endl;
plot5(Vec3d(v1, v2, 0), t);
}
return 0;
}
*/
/*
int main(int argc, char **argv)
{
double dt = 4e-6;
double tmax = 1;
int fex = 10;
double aex = 1000;
if(argc < 3) return 0;
aex = atof(argv[1]);
fex = atof(argv[2]);
DigFilter2 flt1(-1819, 821, 0, 81919, -81919, 10, 10+10);
DigFilter2 flt2(-2019, 996, 0, 10240, -10240, 10, 10+13);
DigFilter1 flt3(-1004, 5243, 0, 10, 10+8);
DigFilter1 flt4(-996, 7282, 0, 10, 10+8);
DigFilter1 flt5(-896, 131072, -131072, 10, 10+10);
RejFilter rjflt1(38.4, 0.952, 0.57, 1/320e-6);
RejFilter rjflt2(58.7, 0.781, 0.45, 1/320e-6);
TGAPlotter plot5("sin.tga", tmax,Vec3d(5000,50,5000));
complex<double> arg = 0;
complex<double> c1(0.0, 0.0);
complex<double> c2(0.0, 0.0);
double vs = 0.0;
int cnt = 0;
for( double t=0.0 ; t<tmax ; t+= dt ){
//double v1 = aex*sin(2*M_PI*fex*t) + 100*sin(2*M_PI*20*t);
double v1 = aex*sin(2*M_PI*fex*t);
//if(0==(cnt++%80)) cout << flt3(flt1(v1)) <<":" << flt3(flt2(v1)) << endl;
if(0==(cnt++%80)) vs = antcor(v1,1000);
//if(0==(cnt++%80)) vs = rjflt2(v1);
c1 += v1*exp(arg);
c2 += vs*exp(arg);
complex<double> darg = -(2*M_PI*dt/tmax)*1i*fex;
arg = arg + darg;
//cout << vs << endl;
plot5(Vec3d(v1,vs,0), t);
}
std::cout << fex << " " << 20*log10(std::abs(c2/c1)) << " " << (180/M_PI)*std::arg(c2/c1) << std::endl;
return 0;
}
*/
|
dcf8d84370ea5580c2ffb12af99d16e84979d789
|
054d51d90fc6abb0a6153f5fcf18ecbdacd18407
|
/DataStruct/Code/tempCodeRunnerFile.cc
|
da8d80e6e2cd92857d06bae51526df8ee24ccd08
|
[] |
no_license
|
Stephenhua/CPP
|
c40c4c69bffc37546ed00f16289e0b24293c59f9
|
bbaa84aabf17cf8e9c1eccaa73ba150c8ca20ec4
|
refs/heads/master
| 2020-12-30T03:42:44.502470
| 2020-09-18T14:56:38
| 2020-09-18T14:56:38
| 238,844,457
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 607
|
cc
|
tempCodeRunnerFile.cc
|
void Test1(){
vector<int> arr={72,6,57,8,60,42,83,73,48,85};
vector<int> arr_sort={6,8,42,48,57,60,72,73,83,85};
Test(arr,arr_sort);
}
void Test2(){
vector<int> arr={};
vector<int> arr_sort={};
Test(arr,arr_sort);
}
void Test3(){
vector<int> arr={1};
vector<int> arr_sort={1};
Test(arr,arr_sort);
}
void Test4(){
vector<int> arr={6,72,57,8,60,42,83,73,48,85};
vector<int> arr_sort={6,8,42,48,57,60,72,73,83,85};
Test(arr,arr_sort);
}
int main(int argc, char* argv[]){
Test1();
Test2();
Test3();
Test4();
system("pause");
return 0;
}
|
733a77dcb6cfdd44f37a356514122b5e1c377332
|
653e1872c3f7e1940c41a6f42d2447a05f2e3598
|
/tls/src/internal.cc
|
2ee1346072d241fb9a240258edb37027432e8b65
|
[
"Apache-2.0"
] |
permissive
|
centreon/centreon-broker
|
a04c42bd7a2a7be33a66c0ab403559f2fd10017f
|
4f3ce322120d17edc93d22a0238e7709026da741
|
refs/heads/develop
| 2023-06-07T22:21:06.116565
| 2023-05-26T13:44:42
| 2023-05-26T13:44:42
| 19,499,960
| 40
| 30
|
Apache-2.0
| 2023-05-26T13:44:43
| 2014-05-06T15:37:19
|
C++
|
UTF-8
|
C++
| false
| false
| 5,167
|
cc
|
internal.cc
|
/*
** Copyright 2009-2013,2017 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/
#include <gnutls/gnutls.h>
#include <cstring>
#if GNUTLS_VERSION_NUMBER < 0x030000
#include <gcrypt.h>
#include <pthread.h>
#include <cerrno>
#endif // GNU TLS < 3.0.0
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/io/stream.hh"
#include "com/centreon/broker/log_v2.hh"
#include "com/centreon/broker/tls/internal.hh"
#include "com/centreon/broker/tls/stream.hh"
#include "com/centreon/exceptions/msg_fmt.hh"
using namespace com::centreon::broker;
using namespace com::centreon::exceptions;
/**************************************
* *
* Global Objects *
* *
**************************************/
/**
* Those 2048-bits wide Diffie-Hellman parameters were generated the
* 30/07/2009 on Ubuntu 9.04 x86 using OpenSSL 0.9.8g with generator 2.
*/
unsigned char const tls::dh_params_2048[] =
"-----BEGIN DH PARAMETERS-----\n"
"MIIBCAKCAQEA93F3CN41kJooLbqcOdWHJPb+/zPV+mMs5Svb6PVH/XS3BK/tuuVu\n"
"r9okkOzGr07KLPiKf+3MJSgHs9N91wPG6JcMcRys3fH1Tszh1i1317tE54o+oLPv\n"
"jcs9P13lFlZm4gB7sjkR5If/ZtudoVwv7JS5WHIXrzew7iW+kT/QXCp+jkO1Vusc\n"
"mQHlq4Fqt/p7zxOHVc8GBttE6/vEYipm2pdym1kBy62Z6rZLowkukngI5uzdQvB4\n"
"Pmq5BmeRzGRClSkmRW4pUXiBac8SMAgMBl7cgAEaURR2D8Y4XltyXW51xzO1x1QM\n"
"bOl9nneRY2Y8X3FOR1+Mzt+x44F+cWtqIwIBAg==\n"
"-----END DH PARAMETERS-----\n";
gnutls_dh_params_t tls::dh_params;
#if GNUTLS_VERSION_NUMBER < 0x030000
GCRY_THREAD_OPTION_PTHREAD_IMPL;
#endif // GNU TLS < 3.0.0
/**
* Deinit the TLS library.
*/
void tls::destroy() {
// Unload Diffie-Hellman parameters.
gnutls_dh_params_deinit(dh_params);
// Unload GNU TLS library
gnutls_global_deinit();
}
/**
* @brief TLS initialization function.
*
* Prepare all necessary ressources for TLS use.
*/
void tls::initialize() {
gnutls_datum_t const dhp = {const_cast<unsigned char*>(dh_params_2048),
sizeof(dh_params_2048)};
int ret;
// Eventually initialize libgcrypt.
#if GNUTLS_VERSION_NUMBER < 0x030000
log_v2::tls()->info("TLS: initializing libgcrypt (GNU TLS <= 2.11.0)");
gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
#endif // GNU TLS < 3.0.0
// Initialize GNU TLS library.
if (gnutls_global_init() != GNUTLS_E_SUCCESS) {
log_v2::tls()->error("TLS: GNU TLS library initialization failed");
throw msg_fmt("TLS: GNU TLS library initialization failed");
}
// Log GNU TLS version.
{
log_v2::tls()->info("TLS: compiled with GNU TLS version {}",
GNUTLS_VERSION);
char const* v(gnutls_check_version(GNUTLS_VERSION));
if (!v) {
log_v2::tls()->error(
"TLS: GNU TLS run-time version is incompatible with the compile-time "
"version ({}): please update your GNU TLS library",
GNUTLS_VERSION);
throw msg_fmt(
"TLS: GNU TLS run-time version is incompatible with the compile-time "
"version ({}): please update your GNU TLS library",
GNUTLS_VERSION);
}
log_v2::tls()->info("TLS: loading GNU TLS version {}", v);
// gnutls_global_set_log_function(log_gnutls_message);
// gnutls_global_set_log_level(11);
}
// Load Diffie-Hellman parameters.
ret = gnutls_dh_params_init(&dh_params);
if (ret != GNUTLS_E_SUCCESS) {
log_v2::tls()->error(
"TLS: could not load TLS Diffie-Hellman parameters: {}",
gnutls_strerror(ret));
throw msg_fmt("TLS: could not load TLS Diffie-Hellman parameters: {}",
gnutls_strerror(ret));
}
ret = gnutls_dh_params_import_pkcs3(dh_params, &dhp, GNUTLS_X509_FMT_PEM);
if (ret != GNUTLS_E_SUCCESS) {
log_v2::tls()->error("TLS: could not import PKCS #3 parameters: ",
gnutls_strerror(ret));
throw msg_fmt("TLS: could not import PKCS #3 parameters: {}",
gnutls_strerror(ret));
}
}
/**
* The following static function is used to receive data from the lower
* layer and give it to TLS for decoding.
*/
ssize_t tls::pull_helper(gnutls_transport_ptr_t ptr, void* data, size_t size) {
return static_cast<tls::stream*>(ptr)->read_encrypted(data, size);
}
/**
* The following static function is used to send data from TLS to the lower
* layer.
*/
ssize_t tls::push_helper(gnutls_transport_ptr_t ptr,
void const* data,
size_t size) {
return static_cast<tls::stream*>(ptr)->write_encrypted(data, size);
}
|
2dc3e84c64795a2eeda074c50a51151853372391
|
ebdaaa910fa99ec3a055a375c960cc8b3d6128b7
|
/Applications/Utils/SimpleMeshCreation/createMeshElemPropertiesFromASCRaster.cpp
|
481fa39185fee7a12eca417c45085b50b0f60a50
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
norihiro-w/ogs
|
017d6970ef2a3b37447434a5f3923ba53508d7d3
|
ac990b1aa06a583dba3e32efa3009ef0c6f46ae4
|
refs/heads/master
| 2022-10-29T05:52:14.936998
| 2016-06-14T16:40:51
| 2016-06-14T16:40:51
| 2,612,310
| 3
| 1
|
NOASSERTION
| 2020-08-28T00:55:34
| 2011-10-20T10:16:18
|
C++
|
UTF-8
|
C++
| false
| false
| 9,528
|
cpp
|
createMeshElemPropertiesFromASCRaster.cpp
|
/**
* \brief Implementation of the createMeshElemPropertiesFromASCRaster tool.
*
* \copyright
* Copyright (c) 2012-2016, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include <algorithm>
#include <memory>
#include <numeric>
#include <tclap/CmdLine.h>
#include "Applications/ApplicationsLib/LogogSetup.h"
#include "BaseLib/quicksort.h"
#include "BaseLib/FileTools.h"
#include "MeshLib/IO/readMeshFromFile.h"
#include "MeshLib/IO/writeMeshToFile.h"
#include "GeoLib/IO/AsciiRasterInterface.h"
#include "GeoLib/Raster.h"
#include "MathLib/MathTools.h"
#include "MeshLib/MeshGenerators/RasterToMesh.h"
#include "MeshLib/MeshGenerators/VtkMeshConverter.h"
#include "MeshLib/Elements/Element.h"
#include "MeshLib/Mesh.h"
#include "MeshLib/MeshEditing/Mesh2MeshPropertyInterpolation.h"
#include "MeshLib/MeshEnums.h"
// From wikipedia:
// http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance. The
// original is citing D.E. Knuth. TAOCP, vol 2.
template <typename InputIterator>
auto computeMeanAndVariance(InputIterator first, InputIterator last) ->
std::pair<typename InputIterator::value_type, typename InputIterator::value_type>
{
using T = typename InputIterator::value_type;
std::size_t n = 0;
auto mu = T{0};
auto M2 = T{0};
while (first != last)
{
T const x = *first++;
n++;
auto delta = x - mu;
mu += delta/n;
M2 += delta * (x - mu);
}
if (n < 2)
return std::make_pair(mu, T{0});
return std::make_pair(mu, M2/(n - 1));
}
int main (int argc, char* argv[])
{
ApplicationsLib::LogogSetup logo_setup;
TCLAP::CmdLine cmd(
"Generates properties for mesh elements of an input mesh deploying a ASC raster file",
' ',
"0.1");
TCLAP::ValueArg<std::string> out_mesh_arg("o",
"out-mesh",
"the mesh is stored to a file of this name",
false,
"",
"filename for mesh output");
cmd.add( out_mesh_arg );
TCLAP::ValueArg<bool> refinement_raster_output_arg("",
"output-refined-raster",
"write refined raster to a new ASC file",
false,
false,
"0");
cmd.add( refinement_raster_output_arg );
TCLAP::ValueArg<unsigned> refinement_arg(
"r",
"refine",
"refinement factor that raises the resolution of the raster data",
false,
1,
"factor (default = 1)");
cmd.add( refinement_arg );
TCLAP::ValueArg<std::string> mapping_arg("",
"mapping-name",
"file name of mapping",
true,
"",
"file name");
cmd.add( mapping_arg );
TCLAP::ValueArg<std::string> raster_arg("",
"raster-file",
"the name of the ASC raster file",
true,
"",
"file name");
cmd.add( raster_arg );
TCLAP::ValueArg<std::string> mesh_arg("m",
"mesh",
"the mesh is read from this file",
true,
"test.msh",
"file name");
cmd.add( mesh_arg );
cmd.parse( argc, argv );
// read mesh
std::unique_ptr<MeshLib::Mesh> dest_mesh(MeshLib::IO::readMeshFromFile(mesh_arg.getValue()));
// read raster and if required manipulate it
auto raster = std::unique_ptr<GeoLib::Raster>(
GeoLib::IO::AsciiRasterInterface::getRasterFromASCFile(raster_arg.getValue()));
GeoLib::RasterHeader header (raster->getHeader());
if (refinement_arg.getValue() > 1) {
raster->refineRaster(refinement_arg.getValue());
if (refinement_raster_output_arg.getValue()) {
// write new asc file
std::string new_raster_fname (BaseLib::dropFileExtension(
raster_arg.getValue()));
new_raster_fname += "-" + std::to_string(header.n_rows) + "x" +
std::to_string(header.n_cols) + ".asc";
GeoLib::IO::AsciiRasterInterface::writeRasterAsASC(*raster, new_raster_fname);
}
}
// put raster data in a std::vector
GeoLib::Raster::const_iterator raster_it(raster->begin());
std::size_t size(header.n_cols * header.n_rows);
std::vector<double> src_properties(size);
for (unsigned row(0); row<header.n_rows; row++) {
for (unsigned col(0); col<header.n_cols; col++) {
src_properties[row * header.n_cols + col] = *raster_it;
++raster_it;
}
}
{
double mu, var;
std::tie(mu, var) = computeMeanAndVariance(src_properties.begin(), src_properties.end());
INFO("Mean value of source: %f.", mu);
INFO("Variance of source: %f.", var);
}
std::unique_ptr<MeshLib::Mesh> src_mesh(MeshLib::RasterToMesh::convert(
*raster, MeshLib::MeshElemType::QUAD,MeshLib::UseIntensityAs::DATAVECTOR));
std::vector<std::size_t> src_perm(size);
std::iota(src_perm.begin(), src_perm.end(), 0);
BaseLib::quicksort<double>(src_properties, 0, size, src_perm);
// compress the property data structure
const std::size_t mat_map_size(src_properties.size());
std::vector<std::size_t> mat_map(mat_map_size);
mat_map[0] = 0;
std::size_t n_mat(1);
for (std::size_t k(1); k<mat_map_size; ++k) {
if (std::fabs(src_properties[k] - src_properties[k-1]) > std::numeric_limits<double>::epsilon()) {
mat_map[k] = mat_map[k - 1] + 1;
n_mat++;
} else
mat_map[k] = mat_map[k - 1];
}
std::vector<double> compressed_src_properties(n_mat);
compressed_src_properties[0] = src_properties[0];
for (std::size_t k(1), id(1); k<mat_map_size; ++k) {
if (std::fabs(src_properties[k] - src_properties[k-1]) > std::numeric_limits<double>::epsilon()) {
compressed_src_properties[id] = src_properties[k];
id++;
}
}
compressed_src_properties[n_mat - 1] = src_properties[mat_map_size - 1];
// reset materials in source mesh
const std::size_t n_mesh_elements(src_mesh->getNumberOfElements());
auto materialIds = src_mesh->getProperties().getPropertyVector<int>("MaterialIDs");
if (!materialIds)
{
materialIds = src_mesh->getProperties().createNewPropertyVector<int>
("MaterialIDs", MeshLib::MeshItemType::Cell, 1);
materialIds->resize(n_mesh_elements, 0); // default material id
}
for (std::size_t k(0); k<n_mesh_elements; k++)
(*materialIds)[src_mesh->getElement(src_perm[k])->getID()] = mat_map[k];
// do the interpolation
MeshLib::Mesh2MeshPropertyInterpolation mesh_interpolation(src_mesh.get(),
&compressed_src_properties);
std::vector<double> dest_properties(dest_mesh->getNumberOfElements());
mesh_interpolation.setPropertiesForMesh(dest_mesh.get(),
dest_properties);
const std::size_t n_dest_mesh_elements(dest_mesh->getNumberOfElements());
{ // write property file
std::string property_fname(mapping_arg.getValue());
std::ofstream property_out(property_fname.c_str());
if (!property_out)
{
ERR("Could not open file %s for writing the mapping.", property_fname.c_str());
return EXIT_FAILURE;
}
for (std::size_t k(0); k < n_dest_mesh_elements; k++)
property_out << k << " " << dest_properties[k] << "\n";
property_out.close();
}
{
double mu, var;
std::tie(mu, var) = computeMeanAndVariance(dest_properties.begin(), dest_properties.end());
INFO("Mean value of destination: %f.", mu);
INFO("Variance of destination: %f.", var);
}
if (! out_mesh_arg.getValue().empty()) {
std::vector<std::size_t> dest_perm(n_dest_mesh_elements);
std::iota(dest_perm.begin(), dest_perm.end(), 0);
BaseLib::quicksort<double>(dest_properties, 0, n_dest_mesh_elements, dest_perm);
// reset materials in destination mesh
materialIds = dest_mesh->getProperties().getPropertyVector<int>("MaterialIDs");
for (std::size_t k(0); k<n_dest_mesh_elements; k++) {
(*materialIds)[dest_mesh->getElement(dest_perm[k])->getID()] = k;
}
MeshLib::IO::writeMeshToFile(*dest_mesh, out_mesh_arg.getValue());
}
return EXIT_SUCCESS;
}
|
c802410629c0ae3a7e508981cb64fcd66345feb8
|
e659b9b4f018b5349732b4dbc6c8e70e7c2f1692
|
/BoomFileNoDomino/22_11/src/testApp.cpp
|
4cf8eef9aaeedfa7f8f67618953d6f64d61154ad
|
[] |
no_license
|
lucaswerthein/BoomFile
|
88638966cfba4e5c9d7d1176ea31b58c2f3bc5df
|
68cacb389e05801580ee2465467271d9eda9bffa
|
refs/heads/master
| 2021-01-13T01:55:04.190566
| 2011-04-09T20:52:28
| 2011-04-09T20:52:28
| 1,523,750
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,785
|
cpp
|
testApp.cpp
|
#include "testApp.h"
int testApp::worldCounter = 1;
//--------------------------------------------------------------
vector<b2Body*> collisions;
void MyContactListener::Add(const b2ContactPoint* point){
b2Body* body1 = point->shape1->GetBody();
b2Body* body2 = point->shape2->GetBody();
char *s1 = (char *) body1->GetUserData();
char *s2 = (char *) body2->GetUserData();
///////////////RECT SOUND////////////////////
if (s1 == "imageBall" && s2 == "lineBox") {
soundRect::loadRect();
} else if (s1 == "lineBox" && s2 == "imageBall") {
soundRect::loadRect();
}
///////////////RECT SOUND 2////////////////////
if (s1 == "imageBall" && s2 == "lineBox2") {
soundRect2::loadRect2();
} else if (s1 == "lineBox2" && s2 == "imageBall") {
soundRect2::loadRect2();
}
///////////////BUCKET SOUND////////////////////
if (s1 == "imageBall" && s2 == "bucket") {
soundBucket::loadBucket();
} else if (s1 == "bucket" && s2 == "imageBall") {
soundBucket::loadBucket();
}
///////////////MIRO SOUND////////////////////
if (s1 == "imageBall" && s2 == "swingBall") {
soundBucket::loadBucket();
} else if (s1 == "swingBall" && s2 == "imageBall") {
soundMiro::loadMiro();
}
///////////////BRIDGE SOUND////////////////////
if (s1 == "imageBall" && s2 == "bridgeBall") {
soundBucket::loadBucket();
} else if (s1 == "bridgeBall" && s2 == "imageBall") {
soundBridge::loadBridge();
}
}
//--------------------------------------------------------------
void MyContactListener::Remove(const b2ContactPoint* point){
}
//--------------------------------------------------------------
void testApp::setup(){
ofSetFrameRate(30);
ofBackground(4, 4, 4);
ofSetLogLevel(OF_LOG_NOTICE);
ofEnableSmoothing();
ofSetCircleResolution(100);
ofSetRectMode(OF_RECTMODE_CENTER);
soundStarted = false;
//------------------------COUNTERS------------------------//
width = 1360*3;
height = 384;
counter = 0;
crazyTime = 2;
//--------------------------------------------------------//
//------------------------BOX2D WORLD---------------------//
box2d.init();
box2d.setGravity(0, 20);
box2d.createBounds(0, 0, width, height);
box2d.setFPS(30.0);
box2d.getWorld() -> SetContactListener(&contacts);
//--------------------------------------------------------//
//------------------------LOAD BACKGROUND-----------------//
bkgImage::loadImage();
//--------------------------------------------------------//
//------------------------SKETCH01------------------------//
scenethree.setup(&box2d);
//--------------------------------------------------------//
//------------------------SKETCH02------------------------//
sceneone.setup(&box2d);
//--------------------------------------------------------//
//------------------------SKETCH03------------------------//
scenetwo.setup(&box2d);
//--------------------------------------------------------//
//------------------------IMAGEBALL-----------------------//
pngBall.setupRedBall(&box2d);
//--------------------------------------------------------//
//------------------------LOAD AIMATIONS-----------------//
movies.loadMovie();
//--------------------------------------------------------//
//--------------------------------------------------------//
soundStarted = true;
}
//--------------------------------------------------------------
void testApp::update(){
box2d.update();
if(soundStarted){
testApp::worldCounter++;
}
//-------------------------------------------------------//
if(testApp::worldCounter==crazyTime){
machine.loadSound("motorLong.mp3");
machine.setLoop(true);
machine.play();
//------------------------SKETCH01------------------------//
scenethree.update();
//--------------------------------------------------------//
//------------------------SKETCH02------------------------//
sceneone.update();
//--------------------------------------------------------//
//------------------------SKETCH03------------------------//
scenetwo.update();
//--------------------------------------------------------//
}
//------------------------BALLS------------------------//
if(testApp::worldCounter>=crazyTime){
counter++;
if(counter == 40) pngBall.dropRedball();
if (counter >= 1000){
if(counter %160 == 0) pngBall.dropRedball();
counter = 0;
testApp::worldCounter = 10;
}
pngBall.destroyRedBall();
//--------------------------------------------------------//
}
}
//--------------------------------------------------------------
void testApp::draw(){
box2d.draw();
bkgImage::drawImage();
//-------------------------------------------------------//
if(testApp::worldCounter>=crazyTime){
//------------------------DRAW AIMATIONS-------------//
movies.drawMovie();
//--------------------------------------------------------//
//------------------------SKETCH01------------------------//
scenethree.draw();
pngBall.drawRedBall();
//--------------------------------------------------------//
//------------------------SKETCH02------------------------//
sceneone.draw();
//--------------------------------------------------------//
//------------------------SKETCH03------------------------//
scenetwo.draw();
//--------------------------------------------------------//
//------------------------FRAME RATE------------------------//
string info = "";
info += "FPS: "+ofToString(ofGetFrameRate())+"\n";
info += "Total Bodies: "+ofToString(box2d.getBodyCount())+"\n";
info += "Press b to load ball""\n";
info += "Press c to create BallHolder""\n";
info += "Press d to destroy BallHolder""\n";
ofSetColor(0, 0, 0);
ofDrawBitmapString(info, 900, 30);
//--------------------------------------------------------//
}
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
if(key == 'b'){
pngBall.dropRedball();
}
if(key == 'z'){
pngBall.dropRedball2();
}
if(key == 'c'){
scenetwo.ballHolder();
}
if(key == 'd'){
scenetwo.destroyBallHolder();
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
|
415757e0cdbf43b15aade186bee3fc8f73aba0a1
|
2799f93c2ad2dcb27eb5121299c91fbd4e253fb8
|
/indicview-base/otsu_bin.cpp
|
8d5c1b294616721c3d2ddcf165f6ac5cf6c3d041
|
[] |
no_license
|
krishna95/PilotImage
|
80f6e40e141cfc74c7a731f022d741fa20610dd6
|
d988981abb17d22c68c5e65d08caa6f2d109e7fc
|
refs/heads/master
| 2021-01-15T14:53:51.420124
| 2015-12-19T00:14:51
| 2015-12-19T00:14:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 454
|
cpp
|
otsu_bin.cpp
|
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main ( int argc, char **argv )
{
Mat im_gray = imread(argv[1],0);
Mat blur, binary;
GaussianBlur(im_gray, blur, Size(5,5), 0, 0);
threshold(blur, binary, 0,255, CV_THRESH_BINARY | CV_THRESH_OTSU);
namedWindow("output");
//imshow("output", binary);
imwrite(argv[2], binary);
//waitKey(0);
return 0;
}
|
59f85fb8892fdcd1c828ba29f3a64648006900e7
|
1091356fce98f15e7f78eb1d05db048e12be8a16
|
/parallel/psobel.cpp
|
68d93c927add2fabcb1c516a369dce2a49d7aaa8
|
[] |
no_license
|
vslovik/video
|
0a81bf0d9674e24d3d5fe8144e837bc11d3c2630
|
d509f207759efe870f7a0c0c05fbe6a34e2b7bda
|
refs/heads/master
| 2020-06-03T05:10:42.045480
| 2017-07-05T20:19:56
| 2017-07-05T20:19:56
| 78,033,769
| 0
| 0
| null | 2017-05-06T20:05:02
| 2017-01-04T16:40:55
|
C++
|
UTF-8
|
C++
| false
| false
| 4,548
|
cpp
|
psobel.cpp
|
#include <iostream>
#include <opencv2/core/core.hpp>
#include <ff/parallel_for.hpp>
/* ----- utility function ------- */
#define XY2I(Y,X,COLS) (((Y) * (COLS)) + (X))
/* ------------------------------ */
const float R = 0.3;
const float G = 0.59;
const float B = 0.11;
// returns the gradient in the x direction
static inline long xGradient(uchar * image, long cols, long x, long y) {
return image[XY2I(y-1, x-1, cols)] +
2*image[XY2I(y, x-1, cols)] +
image[XY2I(y+1, x-1, cols)] -
image[XY2I(y-1, x+1, cols)] -
2*image[XY2I(y, x+1, cols)] -
image[XY2I(y+1, x+1, cols)];
}
// returns the gradient in the y direction
static inline long yGradient(uchar * image, long cols, long x, long y) {
return image[XY2I(y-1, x-1, cols)] +
2*image[XY2I(y-1, x, cols)] +
image[XY2I(y-1, x+1, cols)] -
image[XY2I(y+1, x-1, cols)] -
2*image[XY2I(y+1, x, cols)] -
image[XY2I(y+1, x+1, cols)];
}
void sobel(cv::Mat &image, cv::Mat &output, int num_workers) {
int rows = image.rows;
int cols = image.cols;
uchar *src = new uchar[rows * cols];
uchar *dst = new uchar[rows * cols];
// ff::ffTime(ff::START_TIME);
ff::ParallelFor pf(num_workers, true, true);
// ff::ffTime(ff::STOP_TIME);
// std::cout << "cols: " << cols <<" rows: " << rows << std::endl;
// std::cout << "num_workers:::: " << num_workers << " elapsed time =";
// std::cout << ff::ffTime(ff::GET_TIME) << " ms\n";
for (int r = 0; r < rows; r++) {
for (int c = 1; c < cols - 1; c++) {
cv::Vec3b values = image.at<cv::Vec3b>(r, c);
int val = (int) (R * values[0] + G * values[1] + B * values[2]);
if (val > 255)
val = 255;
src[r * cols + c] = (uchar) val;
}
};
ff::ffTime(ff::START_TIME);
pf.parallel_for(1, rows - 1, [src, cols, &dst](const long y) {
for (long x = 1; x < cols - 1; x++) {
const long gx = xGradient(src, cols, x, y);
const long gy = yGradient(src, cols, x, y);
// approximation of sqrt(gx*gx+gy*gy)
int sum = abs((int) gx) + abs((int) gy);
if (sum > 255) sum = 255;
else if (sum < 0) sum = 0;
dst[y * cols + x] = (uchar) sum;
}
}, num_workers);
pf.threadPause();
// ff::ffTime(ff::STOP_TIME);
// std::cout << "num_workers: " << num_workers << " elapsed time =";
// std::cout << ff::ffTime(ff::GET_TIME) << " ms\n";
output = cv::Mat(rows, cols, CV_8U, dst, cv::Mat::AUTO_STEP);
// delete[] dst;
// delete[] src;
}
void sobel_seq(cv::Mat &image, cv::Mat &output) {
int rows = image.rows;
int cols = image.cols;
uchar * src = new uchar[rows * cols];
uchar * dst = new uchar[rows * cols];
for (int r = 0; r < rows; r++) {
for (int c = 1; c < cols - 1; c++) {
cv::Vec3b values = image.at<cv::Vec3b>(r, c);
int val = (int) (R * values[0] + G * values[1] + B * values[2]);
if (val > 255)
val = 255;
src[r * cols + c] = (uchar) val;
}
};
// ff::ffTime(ff::START_TIME);
for (long y = 1; y < rows - 1; y++) {
for (long x = 1; x < cols - 1; x++) {
const long gx = xGradient(src, cols, x, y);
const long gy = yGradient(src, cols, x, y);
// approximation of sqrt(gx*gx+gy*gy)
int sum = abs((int) gx) + abs((int) gy);
if (sum > 255) sum = 255;
else if (sum < 0) sum = 0;
dst[y * cols + x] = (uchar) sum;
}
};
// ff::ffTime(ff::STOP_TIME);
// std::cout << " elapsed time =";
// std::cout << ff::ffTime(ff::GET_TIME) << " ms\n";
output = cv::Mat(rows, cols, CV_8U, dst, cv::Mat::AUTO_STEP);
// delete[] dst;
// delete[] src;
}
void coherence(cv::Mat &image, int* seams, int num_seams) {
int rows = image.rows;
int cols = image.cols;
uchar * dst = new uchar[rows * cols];
uchar * src = new uchar[rows * cols];
int L[cols], R[cols];
int sum, hole, diff;
for (int k = 0; k < num_seams; k++) {
for (unsigned int r = 0; r < rows; r++) {
std::fill_n(L, cols, 0);
std::fill_n(R, cols, 0);
hole = seams[r * num_seams + k];
if (hole > 0) {
for (int c = hole - 1; c >= 0; c--) {
diff = src[r * cols + c] - src[r * cols + c + 1];
L[c] = L[c + 1] + abs(diff);
}
}
if (hole < cols - 1) {
for (int c = hole + 1; c < cols; c++) {
diff = src[r * cols + c] - src[r * cols + c - 1];
R[c] = R[c - 1] + abs(diff);
}
}
for (int c = 0; c < cols; c++) {
sum = (uchar) L[c] + R[c];
dst[r * cols + c] = (uchar) sum;
}
}
if(k < num_seams - 1)
std::swap(dst, src);
}
image = cv::Mat(rows, cols, CV_8U, dst, cv::Mat::AUTO_STEP);
delete[] dst;
delete[] src;
}
|
ec6ff82cfd5bc8499fa10b3de02d63efea5fdc96
|
0a3363c1d3d5867f1340de49b84eab84defa3fb8
|
/od/graphics/ScreenSaver.h
|
d752309fb42d5bfaad14deda3f5cab045f1337ca
|
[
"MIT"
] |
permissive
|
odevices/er-301
|
b09bc53f1b11ff1bba2be8a51220ebfe932dd935
|
3a7b592fe5d223d5a96b2d8e90b578b23bbdabe5
|
refs/heads/develop
| 2023-02-17T16:31:01.764589
| 2023-02-14T06:55:32
| 2023-02-14T06:55:32
| 343,000,824
| 124
| 26
|
MIT
| 2023-02-14T06:55:34
| 2021-02-28T02:06:10
|
C
|
UTF-8
|
C++
| false
| false
| 355
|
h
|
ScreenSaver.h
|
#pragma once
#include <od/graphics/FrameBuffer.h>
#include <od/graphics/SubFrameBuffer.h>
namespace od
{
class ScreenSaver
{
public:
ScreenSaver();
virtual ~ScreenSaver();
virtual void reset() = 0;
virtual void draw(FrameBuffer &mainFrameBuffer,
FrameBuffer &subFrameBuffer) = 0;
};
} /* namespace od */
|
343f5bd0706b5f8308554cfe9a3cbcc17e3e19dc
|
a44e1a9e5ed397fc26a8d30a28685c18437b60fe
|
/Linked_list/linked_list.cpp
|
7cbb49c9198bb01fb9de83be6b0b003dce15a8a2
|
[] |
no_license
|
tranngocson210599/intership
|
a38fdd8959bea1f5e895d5a37c921e2116e0e846
|
46d8f7c07bf07e3cea0695b2f3c559079ccef7f5
|
refs/heads/master
| 2022-12-16T23:01:52.955271
| 2020-09-09T14:21:03
| 2020-09-09T14:21:03
| 297,518,786
| 1
| 0
| null | 2020-09-22T02:54:58
| 2020-09-22T02:54:58
| null |
UTF-8
|
C++
| false
| false
| 4,174
|
cpp
|
linked_list.cpp
|
#include <iostream>
#include "linked_list.h";
using namespace std;
//creat a Node
Node *CreatNode(Data data_in)
{
Node *temp = new Node;
temp->data = data_in;
temp->pnext = NULL;
return temp;
};
void Init (List& lst)
{
lst.phead = lst.pTail = NULL;
};
bool IsEmpty(List& lst)
{
if (lst.phead == NULL)
return true ;
else return false ;
};
void AddHead (List& lst, Node* node)
{
if (IsEmpty(lst)==true)
{
lst.phead = node;
lst.pTail = node;
}
else
{
node->pnext = lst.phead;
lst.phead = node;
}
};
void AddTail(List& lst, Node* node)
{
if (IsEmpty(lst)==true)
{
lst.phead = node;
lst.pTail = node;
}
else
{
lst.pTail->pnext = node;
lst.pTail = node;
}
};
void InsertAfterIndex(List& lst, Node* p, Node* q)
{
if (q != NULL)
{
p->pnext = q->pnext;
q->pnext = p;
if (lst.pTail == q)
{
lst.pTail = p;
}
}
else
AddHead(lst, p);
};
void RemoveHead(List& lst, int&x)
{
if(lst.phead!=NULL)
{
Node* node = lst.phead;
x = node->data.a;
lst.phead = node->pnext;
delete node;
}
};
Node* Getnode(List& lst, int index)
{
Node* node = lst.phead;
int i= 0;
while(node!=NULL && i!=index)
{
i++;
node = node->pnext;
}
if(i!=index)
{
cout <<"gia tri index khong phu hop" <<"\n";
}
else
{
return node;
}
}
void PrintList(List& lst)
{
if(lst.phead!=NULL)
{
Node* node = lst.phead;
while (node!=NULL)
{
cout << node->data.a <<" ";
node = node->pnext;
}
}
}
Node* Search(List& lst, int x)
{
Node* node = lst.phead;
while (node != NULL && node->data.a != x)
node = node->pnext;
if (node != NULL)
return node;
return nullptr;
}
void RemoveAfterIndex(List& list, Node* q, int& x)
{
if(q!=NULL)
{
Node* temp;
if(q->pnext!=NULL)//the last member.
{
temp = q->pnext;
q->pnext = temp->pnext;
x = temp->data.a;
delete temp;
}
else
{
cout <<"day la gia tri cuoi cung cua list" <<"\n";
}
}
else
{
cout << "kiem tra lai chuoi" <<"\n";
}
};
int GetSize(List& lst)
{
Node* temp;
int i = 1;
temp = lst.phead;
while (temp->pnext!= NULL)
{
i++;
temp = temp->pnext;
}
return i;
}
List SortListAsending(List lst)
{
int k = GetSize(lst);
if (k==0)
{
cout << "chieu dai cua chuoi khong hop le" << "\n";
}
else
{
Data a[k];
List ListOut;
int temp = 0;
Node* node = lst.phead;
for(int i=0; i<k; i++)
{
a[i] = node->data;
node = node->pnext;
}
for(int i = 0; i<k; i++)
{
for(int j=0; j<k; j++)
{
if(a[i].a > a[j].a)
{
temp = a[j].a;
a[j].a = a[i].a;
a[i].a = temp;
}
}
}
for(int i = 0; i<k; i++)
{
node = CreatNode(a[i]);
AddTail(ListOut,node);
}
return ListOut;
}
}
List SortListDesending(List lst)
{
int k = GetSize(lst);
if(k==0)
{
cout << "Do dai chuoi khong hop le" <<"\n";
}
else
{
Data a[k];
List ListOut;
int temp = 0;
Node* node = lst.phead;
for(int i=0; i<k; i++)
{
a[i] = node->data;
node = node->pnext;
}
for(int i = 0; i<k; i++)
{
for(int j=0; j<k; j++)
{
if(a[i].a < a[j].a)
{
temp = a[i].a;
a[i].a = a[j].a;
a[j].a = temp;
}
}
}
for(int i = 0; i<k; i++)
{
node = CreatNode(a[i]);
AddTail(ListOut,node);
}
return ListOut;
}
}
void DestructList(List& lst)
{
Node* node;
Node* temp;
node = lst.phead;
while(node->pnext!=NULL)
{
temp = node;
delete(temp);
node = node->pnext;
}
delete(node);
}
|
f3054b382f2d3aa7184c348b4f927d93c9072327
|
6e3c73b11a98d5a33bb621a71405e27c06de7f39
|
/src/Debug.h
|
dc0c81a51f3b8f43616191bf96f8a9d4c92d253b
|
[
"MIT"
] |
permissive
|
BenjaminHinchliff/Tetros
|
192f389d9b390c4b08c3541113ad30383a6528a5
|
256d030007d075f779c5ea6514693e303fecba5f
|
refs/heads/master
| 2022-04-09T11:33:46.413273
| 2020-02-15T05:05:12
| 2020-02-15T05:05:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 377
|
h
|
Debug.h
|
#ifndef DEBUG_H
#define DEBUG_H
#include <iostream>
#include <glad/glad.h>
void APIENTRY glDebugOutput(GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam);
GLenum glCheckError_(const char* file, int line);
#define glCheckError() glCheckError_(__FILE__, __LINE__)
#endif // !DEBUG_H
|
e02bed182472fee98805638421caf6a07d89ec1f
|
6443a53a6586544df1301719634c75ab5b831ee2
|
/src/lib/MSC/Base_Connector.cpp
|
4ac0d90dcc517e0bb282636a3a7e075eb4069e21
|
[] |
no_license
|
marvins/MapServerConnector
|
8c4e44f7be368c5db63eac36e63ab7d9adc6050c
|
f91ff7cd35467c7bfa73923744b19b41faa0a396
|
refs/heads/master
| 2021-01-10T07:18:05.328038
| 2017-03-13T03:48:25
| 2017-03-13T03:48:25
| 50,594,192
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 760
|
cpp
|
Base_Connector.cpp
|
/**
* @file Base_Connector.cpp
* @author Marvin Smith
* @date 1/27/2016
*/
#include "Base_Connector.hpp"
namespace MSC{
/**********************************************/
/* Base Connector Constructor */
/**********************************************/
Base_Connector::Base_Connector( Configuration const& configuration )
: m_class_name("Base_Connector"),
m_is_connected(false),
m_configuration(configuration)
{
}
/********************************************************/
/* Base Connector Generator Constructor */
/********************************************************/
Base_Connector_Generator::Base_Connector_Generator()
: m_class_name("Base_Connector_Generator")
{
}
} // End of MSC Namespace
|
b8f20bcc44db313d09ab2d058942a694cbd739b4
|
94e8e0d10dd993cb08785d1bab6aafc1055f509d
|
/MoreIdioms/MoreIdioms/samples/MI34_FinalClass_Deprecated_C++11.h
|
273264279e663f95e483ee1f35598002bc8c85f6
|
[] |
no_license
|
albertomila/continous-formation
|
1d416170d2ad85ad1e2ea5eef0f2436cd299c716
|
e3a57f0fc22dc16b1e9cce1ed100795ca664359d
|
refs/heads/master
| 2020-06-14T00:46:23.147271
| 2019-07-08T18:38:54
| 2019-07-08T18:38:54
| 194,838,856
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 855
|
h
|
MI34_FinalClass_Deprecated_C++11.h
|
#pragma once
#include "stdafx.h"
/////////////////////////////////////////////////
template<class T>
class MakeFinal
{
private:
MakeFinal()
{
;
} // private by default.
friend T;
};
#define MAKE_FINAL( T ) virtual MakeFinal<T>
#define FINAL_CLASS( T ) class T : virtual MakeFinal<T>
/////////////////////////////////////////////////
class CFinal : MAKE_FINAL( CFinal )
{
public:
CFinal()
{
;
} // private by default.
};
/////////////////////////////////////////////////
FINAL_CLASS( CFinal2 )
{
public:
CFinal2()
{
;
} // private by default.
};
/*
/////////////////////////////////////////////////
class CTest : public CFinal
{
public:
CTest()
{
;
} // private by default.
};
*/
BEGIN_TEST(FinalClass)
CFinal s1;
CFinal2 s2;
//CTest t;
END_TEST()
|
3b8ea9ca2202b083be1dc20a2f20600b178c8c99
|
1dfa90b745a93e5c068643e23c4c802deefa69b5
|
/gollybase/writepattern.cpp
|
e2cd4fb3ab1be84dc6eb7f9858f3734119713432
|
[] |
no_license
|
AlephAlpha/golly
|
81379e8d37debd7fffab2c5cff610db2549897f5
|
86e463d33731bebff26767c676a4c19295ff19d6
|
refs/heads/master
| 2023-08-13T23:58:04.223452
| 2023-07-18T08:48:52
| 2023-07-18T08:48:52
| 140,466,481
| 38
| 12
| null | 2020-09-05T12:01:17
| 2018-07-10T17:29:21
|
C++
|
UTF-8
|
C++
| false
| false
| 10,823
|
cpp
|
writepattern.cpp
|
// This file is part of Golly.
// See docs/License.html for the copyright notice.
#include "writepattern.h"
#include "lifealgo.h"
#include "util.h" // for *progress calls
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#ifdef ZLIB
#include <zlib.h>
#include <streambuf>
#endif
#ifdef __APPLE__
#define BUFFSIZE 4096 // 4K is best for Mac OS X
#else
#define BUFFSIZE 8192 // 8K is best for Windows and other platforms???
#endif
// globals for writing RLE files
static char outbuff[BUFFSIZE];
static size_t outpos; // current write position in outbuff
static bool badwrite; // fwrite failed?
// using buffered putchar instead of fputc is about 20% faster on Mac OS X
static void putchar(char ch, std::ostream &os) {
if (badwrite) return;
if (outpos == BUFFSIZE) {
if (!os.write(outbuff, outpos)) badwrite = true;
outpos = 0;
}
outbuff[outpos] = ch;
outpos++;
}
const int WRLE_NONE = -3 ;
const int WRLE_EOP = -2 ;
const int WRLE_NEWLINE = -1 ;
// output of RLE pattern data is channelled thru here to make it easier to
// ensure all lines have <= 70 characters
void AddRun(std::ostream &f,
int state, // in: state of cell to write
int multistate, // true if #cell states > 2
unsigned int &run, // in and out
unsigned int &linelen) // ditto
{
unsigned int i, numlen;
char numstr[32];
if ( run > 1 ) {
sprintf(numstr, "%u", run);
numlen = (int)strlen(numstr);
} else {
numlen = 0; // no run count shown if 1
}
if ( linelen + numlen + 1 + multistate > 70 ) {
putchar('\n', f);
linelen = 0;
}
i = 0;
while (i < numlen) {
putchar(numstr[i], f);
i++;
}
if (multistate) {
if (state <= 0)
putchar(".$!"[-state], f) ;
else {
if (state > 24) {
int hi = (state - 25) / 24 ;
putchar((char)(hi + 'p'), f) ;
linelen++ ;
state -= (hi + 1) * 24 ;
}
putchar((char)('A' + state - 1), f) ;
}
} else
putchar("!$bo"[state+2], f) ;
linelen += numlen + 1;
run = 0; // reset run count
}
// write current pattern to file using extended RLE format
const char *writerle(std::ostream &os, char *comments, lifealgo &imp,
int top, int left, int bottom, int right,
bool xrle)
{
badwrite = false;
if (xrle) {
// write out #CXRLE line; note that the XRLE indicator is prefixed
// with #C so apps like Life32 and MCell will ignore the line
os << "#CXRLE Pos=" << left << ',' << top;
if (imp.getGeneration() > bigint::zero)
os << " Gen=" << imp.getGeneration().tostring('\0');
os << '\n';
}
char *endcomms = NULL;
if (comments && comments[0]) {
// write given comment line(s) -- can't just do fputs(comments,f)
// because comments might include arbitrary text after the "!"
char *p = comments;
while (*p == '#') {
while (*p != '\n') p++;
p++;
}
if (p != comments) {
char savech = *p;
*p = '\0';
os << comments;
*p = savech;
}
// any comment lines not starting with # will be written after "!"
if (*p != '\0') endcomms = p;
}
if ( imp.isEmpty() || top > bottom || left > right ) {
// empty pattern
os << "x = 0, y = 0, rule = " << imp.getrule() << "\n!\n";
} else {
// do header line
unsigned int wd = right - left + 1;
unsigned int ht = bottom - top + 1;
sprintf(outbuff, "x = %u, y = %u, rule = %s\n", wd, ht, imp.getrule());
outpos = strlen(outbuff);
// do RLE data
unsigned int linelen = 0;
unsigned int brun = 0;
unsigned int orun = 0;
unsigned int dollrun = 0;
int laststate = WRLE_NONE ;
int multistate = imp.NumCellStates() > 2 ;
int cx, cy;
// for showing accurate progress we need to add pattern height to pop count
// in case this is a huge pattern with many blank rows
double maxcount = imp.getPopulation().todouble() + ht;
double accumcount = 0;
int currcount = 0;
int v = 0 ;
for ( cy=top; cy<=bottom; cy++ ) {
// set lastchar to anything except 'o' or 'b'
laststate = WRLE_NONE ;
currcount++;
for ( cx=left; cx<=right; cx++ ) {
int skip = imp.nextcell(cx, cy, v);
if (skip + cx > right)
skip = -1; // pretend we found no more live cells
if (skip > 0) {
// have exactly "skip" dead cells here
if (laststate == 0) {
brun += skip;
} else {
if (orun > 0) {
// output current run of live cells
AddRun(os, laststate, multistate, orun, linelen);
}
laststate = 0 ;
brun = skip;
}
}
if (skip >= 0) {
// found next live cell in this row
cx += skip;
if (laststate == v) {
orun++;
} else {
if (dollrun > 0)
// output current run of $ chars
AddRun(os, WRLE_NEWLINE, multistate, dollrun, linelen);
if (brun > 0)
// output current run of dead cells
AddRun(os, 0, multistate, brun, linelen);
if (orun > 0)
AddRun(os, laststate, multistate, orun, linelen) ;
laststate = v ;
orun = 1;
}
currcount++;
} else {
cx = right + 1; // done this row
}
if (currcount > 1024) {
char msg[128];
accumcount += currcount;
currcount = 0;
sprintf(msg, "File size: %.2f MB", os.tellp() / 1048576.0);
if (lifeabortprogress(accumcount / maxcount, msg)) break;
}
}
// end of current row
if (isaborted()) break;
if (laststate == 0)
// forget dead cells at end of row
brun = 0;
else if (laststate >= 0)
// output current run of live cells
AddRun(os, laststate, multistate, orun, linelen);
dollrun++;
}
// terminate RLE data
dollrun = 1;
AddRun(os, WRLE_EOP, multistate, dollrun, linelen);
putchar('\n', os);
// flush outbuff
if (outpos > 0 && !badwrite && !os.write(outbuff, outpos))
badwrite = true;
}
if (endcomms) os << endcomms;
if (badwrite)
return "Failed to write output buffer!";
else
return 0;
}
const char *writemacrocell(std::ostream &os, char *comments, lifealgo &imp)
{
if (imp.hyperCapable())
return imp.writeNativeFormat(os, comments);
else
return "Not yet implemented.";
}
#ifdef ZLIB
class gzbuf : public std::streambuf
{
public:
gzbuf() : file(NULL) { }
gzbuf(const char *path) : file(NULL) { open(path); }
~gzbuf() { close(); }
gzbuf *open(const char *path)
{
if (file) return NULL;
file = gzopen(path, "wb");
return file ? this : NULL;
}
gzbuf *close()
{
if (!file) return NULL;
int res = gzclose(file);
file = NULL;
return res == Z_OK ? this : NULL;
}
bool is_open() const { return file!=NULL; }
int overflow(int c=EOF)
{
if (c == EOF)
return c ;
return gzputc(file, c) ;
}
std::streamsize xsputn(const char_type *s, std::streamsize n)
{
return gzwrite(file, s, (unsigned int)n);
}
int sync()
{
return gzflush(file, Z_SYNC_FLUSH) == Z_OK ? 0 : -1;
}
pos_type seekoff(off_type off, std::ios_base::seekdir way, std::ios_base::openmode which)
{
if (file && off == 0 && way == std::ios_base::cur && which == std::ios_base::out)
{
#if ZLIB_VERNUM >= 0x1240
// gzoffset is only available in zlib 1.2.4 or later
return pos_type(gzoffset(file));
#else
// return an approximation of file size (only used in progress dialog)
z_off_t offset = gztell(file);
if (offset > 0) offset /= 4;
return pos_type(offset);
#endif
}
return pos_type(off_type(-1));
}
private:
gzFile file;
};
#endif
const char *writepattern(const char *filename, lifealgo &imp,
pattern_format format, output_compression compression,
int top, int left, int bottom, int right)
{
// extract any comments if file exists so we can copy them to new file
char *commptr = NULL;
FILE *f = fopen(filename, "r");
if (f) {
fclose(f);
const char *err = readcomments(filename, &commptr);
if (err) {
if (commptr) free(commptr);
return err;
}
}
// skip past any old #CXRLE lines at start of existing XRLE file
char *comments = commptr;
if (comments) {
while (strncmp(comments, "#CXRLE", 6) == 0) {
while (*comments != '\n') comments++;
comments++;
}
}
// open output stream
std::streambuf *streambuf = NULL;
std::filebuf filebuf;
#ifdef ZLIB
gzbuf gzbuf;
#endif
switch (compression)
{
default: /* no output compression */
streambuf = filebuf.open(filename, std::ios_base::out);
break;
case gzip_compression:
#ifdef ZLIB
streambuf = gzbuf.open(filename);
break;
#else
if (commptr) free(commptr);
return "GZIP compression not supported";
#endif
}
if (!streambuf) {
if (commptr) free(commptr);
return "Can't create pattern file!";
}
std::ostream os(streambuf);
lifebeginprogress("Writing pattern file");
const char *errmsg = NULL;
switch (format) {
case RLE_format:
errmsg = writerle(os, comments, imp, top, left, bottom, right, false);
break;
case XRLE_format:
errmsg = writerle(os, comments, imp, top, left, bottom, right, true);
break;
case MC_format:
// macrocell format ignores given edges
errmsg = writemacrocell(os, comments, imp);
break;
default:
errmsg = "Unsupported pattern format!";
}
if (errmsg == NULL && !os.flush())
errmsg = "Error occurred writing file; maybe disk is full?";
lifeendprogress();
if (commptr) free(commptr);
if (isaborted())
return "File contains truncated pattern.";
else
return errmsg;
}
|
eeb7989b2f6e03ed390b7bbac37ab1152277942e
|
8eb85415285e337f1a7ef621a2f888bc426c5530
|
/ROCm_Libraries/rocALUTION/src/base/hip/hip_sparse.cpp
|
79322050a09b6f1586d2a917ccbe53b0df12b832
|
[] |
no_license
|
Rmalavally/ROCm_Documentation
|
9eebfb0d9f92ec083a3ad97336d73fd3a1751a30
|
b4cfab566ae3fee2502e4bbf2fef1848024a155f
|
refs/heads/master
| 2021-05-19T16:31:51.483435
| 2021-05-11T16:24:37
| 2021-05-11T16:24:37
| 252,028,180
| 2
| 0
| null | 2020-04-01T00:09:34
| 2020-04-01T00:09:33
| null |
UTF-8
|
C++
| false
| false
| 28,038
|
cpp
|
hip_sparse.cpp
|
/* ************************************************************************
* Copyright (c) 2018 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* ************************************************************************ */
#include "../../utils/def.hpp"
#include "../../utils/log.hpp"
#include "hip_sparse.hpp"
#include <rocsparse.h>
#include <complex>
namespace rocalution {
// rocsparse csrmv analysis
template <>
rocsparse_status rocsparseTcsrmv_analysis(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int n,
int nnz,
const rocsparse_mat_descr descr,
const float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info)
{
return rocsparse_scsrmv_analysis(
handle, trans, m, n, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info);
}
template <>
rocsparse_status rocsparseTcsrmv_analysis(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int n,
int nnz,
const rocsparse_mat_descr descr,
const double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info)
{
return rocsparse_dcsrmv_analysis(
handle, trans, m, n, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info);
}
// rocsparse csrmv
template <>
rocsparse_status rocsparseTcsrmv(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int n,
int nnz,
const float* alpha,
const rocsparse_mat_descr descr,
const float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
const float* x,
const float* beta,
float* y)
{
return rocsparse_scsrmv(handle,
trans,
m,
n,
nnz,
alpha,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
info,
x,
beta,
y);
}
template <>
rocsparse_status rocsparseTcsrmv(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int n,
int nnz,
const double* alpha,
const rocsparse_mat_descr descr,
const double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dcsrmv(handle,
trans,
m,
n,
nnz,
alpha,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
info,
x,
beta,
y);
}
// rocsparse csrsv buffer size
template <>
rocsparse_status rocsparseTcsrsv_buffer_size(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int nnz,
const rocsparse_mat_descr descr,
const float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
size_t* buffer_size)
{
return rocsparse_scsrsv_buffer_size(
handle, trans, m, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info, buffer_size);
}
template <>
rocsparse_status rocsparseTcsrsv_buffer_size(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int nnz,
const rocsparse_mat_descr descr,
const double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
size_t* buffer_size)
{
return rocsparse_dcsrsv_buffer_size(
handle, trans, m, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info, buffer_size);
}
// rocsparse csrsv analysis
template <>
rocsparse_status rocsparseTcsrsv_analysis(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int nnz,
const rocsparse_mat_descr descr,
const float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
rocsparse_analysis_policy analysis,
rocsparse_solve_policy solve,
void* temp_buffer)
{
return rocsparse_scsrsv_analysis(handle,
trans,
m,
nnz,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
info,
analysis,
solve,
temp_buffer);
}
template <>
rocsparse_status rocsparseTcsrsv_analysis(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int nnz,
const rocsparse_mat_descr descr,
const double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
rocsparse_analysis_policy analysis,
rocsparse_solve_policy solve,
void* temp_buffer)
{
return rocsparse_dcsrsv_analysis(handle,
trans,
m,
nnz,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
info,
analysis,
solve,
temp_buffer);
}
// rocsparse csrsv
template <>
rocsparse_status rocsparseTcsrsv(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int nnz,
const float* alpha,
const rocsparse_mat_descr descr,
const float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
const float* x,
float* y,
rocsparse_solve_policy policy,
void* temp_buffer)
{
return rocsparse_scsrsv_solve(handle,
trans,
m,
nnz,
alpha,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
info,
x,
y,
policy,
temp_buffer);
}
template <>
rocsparse_status rocsparseTcsrsv(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int nnz,
const double* alpha,
const rocsparse_mat_descr descr,
const double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
const double* x,
double* y,
rocsparse_solve_policy policy,
void* temp_buffer)
{
return rocsparse_dcsrsv_solve(handle,
trans,
m,
nnz,
alpha,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
info,
x,
y,
policy,
temp_buffer);
}
// rocsparse coomv
template <>
rocsparse_status rocsparseTcoomv(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int n,
int nnz,
const float* alpha,
const rocsparse_mat_descr descr,
const float* coo_val,
const int* coo_row_ind,
const int* coo_col_ind,
const float* x,
const float* beta,
float* y)
{
return rocsparse_scoomv(
handle, trans, m, n, nnz, alpha, descr, coo_val, coo_row_ind, coo_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparseTcoomv(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int n,
int nnz,
const double* alpha,
const rocsparse_mat_descr descr,
const double* coo_val,
const int* coo_row_ind,
const int* coo_col_ind,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dcoomv(
handle, trans, m, n, nnz, alpha, descr, coo_val, coo_row_ind, coo_col_ind, x, beta, y);
}
// rocsparse ellmv
template <>
rocsparse_status rocsparseTellmv(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int n,
const float* alpha,
const rocsparse_mat_descr descr,
const float* ell_val,
const int* ell_col_ind,
int ell_width,
const float* x,
const float* beta,
float* y)
{
return rocsparse_sellmv(
handle, trans, m, n, alpha, descr, ell_val, ell_col_ind, ell_width, x, beta, y);
}
template <>
rocsparse_status rocsparseTellmv(rocsparse_handle handle,
rocsparse_operation trans,
int m,
int n,
const double* alpha,
const rocsparse_mat_descr descr,
const double* ell_val,
const int* ell_col_ind,
int ell_width,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dellmv(
handle, trans, m, n, alpha, descr, ell_val, ell_col_ind, ell_width, x, beta, y);
}
// rocsparse csrilu0 buffer size
template <>
rocsparse_status rocsparseTcsrilu0_buffer_size(rocsparse_handle handle,
int m,
int nnz,
const rocsparse_mat_descr descr,
float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
size_t* buffer_size)
{
return rocsparse_scsrilu0_buffer_size(
handle, m, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info, buffer_size);
}
template <>
rocsparse_status rocsparseTcsrilu0_buffer_size(rocsparse_handle handle,
int m,
int nnz,
const rocsparse_mat_descr descr,
double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
size_t* buffer_size)
{
return rocsparse_dcsrilu0_buffer_size(
handle, m, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info, buffer_size);
}
// rocsparse csrilu0 analysis
template <>
rocsparse_status rocsparseTcsrilu0_analysis(rocsparse_handle handle,
int m,
int nnz,
const rocsparse_mat_descr descr,
float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
rocsparse_analysis_policy analysis,
rocsparse_solve_policy solve,
void* temp_buffer)
{
return rocsparse_scsrilu0_analysis(handle,
m,
nnz,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
info,
analysis,
solve,
temp_buffer);
}
template <>
rocsparse_status rocsparseTcsrilu0_analysis(rocsparse_handle handle,
int m,
int nnz,
const rocsparse_mat_descr descr,
double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
rocsparse_analysis_policy analysis,
rocsparse_solve_policy solve,
void* temp_buffer)
{
return rocsparse_dcsrilu0_analysis(handle,
m,
nnz,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
info,
analysis,
solve,
temp_buffer);
}
// rocsparse csrilu0
template <>
rocsparse_status rocsparseTcsrilu0(rocsparse_handle handle,
int m,
int nnz,
const rocsparse_mat_descr descr,
float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
rocsparse_solve_policy policy,
void* temp_buffer)
{
return rocsparse_scsrilu0(
handle, m, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info, policy, temp_buffer);
}
template <>
rocsparse_status rocsparseTcsrilu0(rocsparse_handle handle,
int m,
int nnz,
const rocsparse_mat_descr descr,
double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
rocsparse_mat_info info,
rocsparse_solve_policy policy,
void* temp_buffer)
{
return rocsparse_dcsrilu0(
handle, m, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info, policy, temp_buffer);
}
// rocsparse csr2csc
template <>
rocsparse_status rocsparseTcsr2csc(rocsparse_handle handle,
int m,
int n,
int nnz,
const float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
float* csc_val,
int* csc_row_ind,
int* csc_col_ptr,
rocsparse_action copy_values,
rocsparse_index_base idx_base,
void* temp_buffer)
{
return rocsparse_scsr2csc(handle,
m,
n,
nnz,
csr_val,
csr_row_ptr,
csr_col_ind,
csc_val,
csc_row_ind,
csc_col_ptr,
copy_values,
idx_base,
temp_buffer);
}
template <>
rocsparse_status rocsparseTcsr2csc(rocsparse_handle handle,
int m,
int n,
int nnz,
const double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
double* csc_val,
int* csc_row_ind,
int* csc_col_ptr,
rocsparse_action copy_values,
rocsparse_index_base idx_base,
void* temp_buffer)
{
return rocsparse_dcsr2csc(handle,
m,
n,
nnz,
csr_val,
csr_row_ptr,
csr_col_ind,
csc_val,
csc_row_ind,
csc_col_ptr,
copy_values,
idx_base,
temp_buffer);
}
// rocsparse csr2ell
template <>
rocsparse_status rocsparseTcsr2ell(rocsparse_handle handle,
int m,
const rocsparse_mat_descr csr_descr,
const float* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
const rocsparse_mat_descr ell_descr,
int ell_width,
float* ell_val,
int* ell_col_ind)
{
return rocsparse_scsr2ell(handle,
m,
csr_descr,
csr_val,
csr_row_ptr,
csr_col_ind,
ell_descr,
ell_width,
ell_val,
ell_col_ind);
}
template <>
rocsparse_status rocsparseTcsr2ell(rocsparse_handle handle,
int m,
const rocsparse_mat_descr csr_descr,
const double* csr_val,
const int* csr_row_ptr,
const int* csr_col_ind,
const rocsparse_mat_descr ell_descr,
int ell_width,
double* ell_val,
int* ell_col_ind)
{
return rocsparse_dcsr2ell(handle,
m,
csr_descr,
csr_val,
csr_row_ptr,
csr_col_ind,
ell_descr,
ell_width,
ell_val,
ell_col_ind);
}
// rocsparse ell2csr
template <>
rocsparse_status rocsparseTell2csr(rocsparse_handle handle,
int m,
int n,
const rocsparse_mat_descr ell_descr,
int ell_width,
const float* ell_val,
const int* ell_col_ind,
const rocsparse_mat_descr csr_descr,
float* csr_val,
const int* csr_row_ptr,
int* csr_col_ind)
{
return rocsparse_sell2csr(handle,
m,
n,
ell_descr,
ell_width,
ell_val,
ell_col_ind,
csr_descr,
csr_val,
csr_row_ptr,
csr_col_ind);
}
template <>
rocsparse_status rocsparseTell2csr(rocsparse_handle handle,
int m,
int n,
const rocsparse_mat_descr ell_descr,
int ell_width,
const double* ell_val,
const int* ell_col_ind,
const rocsparse_mat_descr csr_descr,
double* csr_val,
const int* csr_row_ptr,
int* csr_col_ind)
{
return rocsparse_dell2csr(handle,
m,
n,
ell_descr,
ell_width,
ell_val,
ell_col_ind,
csr_descr,
csr_val,
csr_row_ptr,
csr_col_ind);
}
} // namespace rocalution
|
822d03932473804b6840b29fdff55484fee72a5c
|
598688bacee137269adc1852f24b03a3867e9558
|
/TreeQueries2.cpp
|
998612afa144b1f78ca8fce51de33f9be73b0887
|
[] |
no_license
|
amitkr6211/CSES_PROBLEM_SET_TREES
|
28a24ed2ae496b098d52fb8163fac2b0da9b77a9
|
5c74a0448fbd17a2ba25450ee0cc4de1a0ceea07
|
refs/heads/main
| 2023-04-28T05:58:44.005603
| 2021-05-17T07:42:56
| 2021-05-17T07:42:56
| 368,098,109
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,389
|
cpp
|
TreeQueries2.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
//depth of each node
void bfs(vector<int> &depth, vector<int> v[]){
depth[1]=0;
queue<pair<int,int>> q;
q.push({1,0});
while(!q.empty()){
pair<int,int> p=q.front();
depth[p.first]=p.second;
q.pop();
for(int i=0;i<(int)v[p.first].size();i++){
q.push({v[p.first][i],p.second+1});
}
}
}
int LCA(int a, int b, vector<int> &depth , vector<vector<int>> &dp){
int da=depth[a];
int db=depth[b];
// cout<<da<<" "<<db<<endl;
if(db>da){
swap(a,b);
}
int d=abs(da-db);
// dth ancestor of a
while(d>0){
int jump=log2(d);
int new_vert=dp[a][jump];
// cout<<jump<<" "<<new_vert<<endl;
// int t=(int)(pow(2,jump)+0.5);
// cout<<" kk k "<<t<<endl;
d-=(int)(pow(2,jump)+0.5);
a=new_vert;
// cout<<k<<" "<<x<<endl;
}
//now a and b are at the same level
// cout<<a<<" "<<b<<endl;
if(a==b){
return a;
}
if(dp[a][0]==dp[b][0]){
return dp[a][0];
}
int N=depth.size();
int t=log2(N-1);
// cout<<t<<endl;
// int vert=0;
while(t>=0)
{
// cout<<t<<endl;
int ta=dp[a][t];
// vert=ta;
int tb=dp[b][t];
// cout<<ta<<" "<<tb<<endl;
if(ta==-1){
t--;
continue;
}
else if(ta==tb){
t--;
continue;
}
else{
// break;
a=ta;
b=tb;
}
}
return dp[a][0];
}
int main(){
int n,q;
cin>>n>>q;
vector<int> v[n+1];
int t=log2(n)+1;
vector<vector<int>> dp(n+1,vector<int>(t,-1));
vector<int> depth(n+1,0);
vector<int> child(n+1,-1);
for(int i=2;i<=n;i++){
int x;
cin>>x;
dp[i][0]=x; //storing the parents
v[x].push_back(i);
}
bfs(depth,v);
// fill the dp array
for(int j=1;j<t;j++){
for(int i=1;i<=n;i++){
int x=dp[i][j-1];
if(x==-1){
continue;
}
dp[i][j]=dp[x][j-1];
}
}
//table formed
//take queries
for(int i=0;i<q;i++){
int a,b;
cin>>a>>b;
cout<<LCA(a,b,depth,dp)<<" ";
}
return 0;
}
|
b503e07235c7bcbf26eb653d51f382ba7c000bac
|
f8b2ba705d6e360fd2ff0e2dc34a109af0aec781
|
/node.h
|
628ae40ef684a569a00210707d4361dffc238b92
|
[
"MIT"
] |
permissive
|
alekseyl1992/CalcCompiler
|
6371219f71c05685d742408aa571783bf0e57dcb
|
e64894941bb8946a14a657f9c84fe7d0ad0ff197
|
refs/heads/master
| 2020-12-24T13:53:01.633168
| 2016-01-14T12:11:57
| 2016-01-14T12:11:57
| 34,921,515
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,299
|
h
|
node.h
|
#ifndef NODE_H
#define NODE_H
#include <string>
#include <assert.h>
#include "token.h"
struct Node {
enum Type {
NONE, OPERATION, OPERAND
};
Token token = {Token::TOKEN_TYPES_COUNT, L"", 0};
std::vector<Node *> operands;
Type type = NONE;
Node(Token token=Token(), std::vector<Node *> operands={}, Type type=NONE)
: token(token), operands(operands), type(type) {
}
virtual bool isLeaf() {
return operands.size() == 0;
}
};
struct ExpNode : public Node {
ExpNode() : Node() {
operands.resize(2); //left and right children
operands[0] = nullptr;
operands[1] = nullptr;
}
ExpNode *left() {
assert(operands.size() == 2);
return (ExpNode *) operands[0];
}
void left(Node *p) {
assert(operands.size() == 2);
operands[0] = p;
}
ExpNode *right() {
assert(operands.size() == 2);
return (ExpNode *) operands[1];
}
void right(Node *p) {
assert(operands.size() == 2);
operands[1] = p;
}
virtual bool isLeaf() override {
assert(operands.size() == 2);
return operands[0] == nullptr && operands[1] == nullptr;
}
ExpNode *parent = nullptr;
int priority = 0;
double value = 0;
bool isNegative = false;
};
#endif // NODE_H
|
345f86813712567e45f6536723302b3363d50fcb
|
fc833788e798460d3fb153fbb150ea5263daf878
|
/boj/14000~14999/14890.cpp
|
5a73cd5ebb49cbdf6452b3955fcf229f106f6352
|
[] |
no_license
|
ydk1104/PS
|
a50afdc4dd15ad1def892368591d4bd1f84e9658
|
2c791b267777252ff4bf48a8f54c98bcdcd64af9
|
refs/heads/master
| 2021-07-18T08:19:34.671535
| 2020-09-02T17:45:59
| 2020-09-02T17:45:59
| 208,404,564
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 936
|
cpp
|
14890.cpp
|
#include<stdio.h>
int map[101][101];
int road[201][101];
int N, L;
int abs(int x){
if(x>0) return x;
return -x;
}
int check(int now){
int row = 1;
for(int i=0; i<N-1; i++){
int dis = abs(road[now][i] - road[now][i+1]);
if(dis>=2) return 0;
if(dis==0){
if(road[now][i] == road[now][i+1]) row++;
else row=1;
}
else{
if(road[now][i]>road[now][i+1]){
for(int j=i+1; j<=i+L; j++){
if(j>=N) return 0;
if(road[now][j] != road[now][i+1]) return 0;
}
i += L-1;
row = 0;
}
else{
if(row<L) return 0;
row=1;
}
}
}
return 1;
}
int solve(){
int ans = 0;
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
road[i*2][j] = map[i][j];
road[i*2+1][j] = map[j][i];
}
}
for(int i=0; i<2*N; i++) ans+=check(i);
printf("%d", ans);
}
int main(void){
scanf("%d %d", &N, &L);
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
scanf("%d", &map[i][j]);
}
}
solve();
}
|
85b8b87f98ac3cae276d2e9c131878145cfcf34b
|
ef5504db423f7b0258d8bdefacb12236d76f2bb6
|
/src/demo/demo_server/plugin/demo_server_json_service/demo_server_json_service.h
|
0616a390c94ca952af22cdbc4a2f2fb572bb1947
|
[] |
no_license
|
tafchain/vprotocol
|
cc0fc6f7453072a6941af761bb79f1a33dca6127
|
bd2b5b83046d8af7746617a130fb56be230ce4cc
|
refs/heads/master
| 2023-06-02T12:44:19.228025
| 2021-06-17T07:49:42
| 2021-06-17T07:49:42
| 377,747,826
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 831
|
h
|
demo_server_json_service.h
|
#ifndef DEMO_SERVER_JSON_SERVICE_H_4238234089342798435642367234987423972348234168685
#define DEMO_SERVER_JSON_SERVICE_H_4238234089342798435642367234987423972348234168685
#include "dsc/protocol/http_json/server_http_json_service.h"
#include "demo/common/comm_msg_def.h"
class PLUGIN_EXPORT CDemoServerJsonService : public CServerHttpJsonService
{
public:
enum
{
EN_SERVICE_TYPE = NS_DEMO_ID_DEF::DEMO_SERVER_JSON_SERVICE_TYPE
};
public:
CDemoServerJsonService();
public:
virtual ACE_INT32 OnInit(void);
virtual ACE_INT32 OnExit(void);
public:
BEGIN_BIND_SERVER_JSON_MESSAGE
BIND_SERVER_JSON_MESSAGE(DEMO_JSON_REQ_MSG_URL, NS_DEMO_MSG_DEF::CDemoJsonReqMsg)
END_BIND_SERVER_JSON_MESSAGE
public:
ACE_INT32 JsonServiceMessage(NS_DEMO_MSG_DEF::CDemoJsonReqMsg& rDemoJsonReqMsg, const ACE_UINT32 nSessionID);
};
#endif
|
b2e8f9fd016f22cb6138db8cc48a667581ae91f2
|
9607d81d6126b04c75e197440a15c325a69d97a1
|
/TradingSDI/TradingSDI/PosEntryAna.h
|
b0499b62c548f8f6ab26990b919be77183725173
|
[] |
no_license
|
FX-Misc/prasantsingh-trading
|
0f6ef3ddac2fcb65002d6c1031ea0557c1155d9a
|
755670edd6f964915a4f8c3675f2274b70d01c50
|
refs/heads/master
| 2021-05-05T17:18:47.658007
| 2017-01-19T11:06:16
| 2017-01-19T11:06:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,255
|
h
|
PosEntryAna.h
|
#ifndef PosEntryAna_GRID
#define PosEntryAna_GRID
#include "OrderGrid.h"
#include "ugctrl.h"
#include "LogFile.h"
class PosEntryAna :public CUGCtrl
{
public:
PosEntryAna(void);
~PosEntryAna(void);
static int insertFilterFlag;
static int shorting;
CString str[6];
int m_nSpinIndex;
int run_check;
CLogFile m_logfile;
CUGSortArrowType m_sortArrow;
CFont m_font;
int m_iSortCol;
BOOL m_bSortedAscending;
int m_iArrowIndex;
public:
//***** Over-ridable Notify Functions *****
void InitMenu();
void filter();
void gridFilter(int colno,int rows_count,CString col_value);
BOOLEAN CheckvalueInArray(const CStringArray& arr,CString strval) ;
void addItemToCombobox();
//movement and sizing
virtual int OnDropList(long ID,int col,long row,long msg,long param);
virtual void OnSetup();
virtual void OnSheetSetup(int sheetNumber);
void Getdata(_bstr_t m_login);
//mouse and key strokes
virtual int OnCellTypeNotify(long ID,int col,long row,long msg,long param);
//menu notifications
virtual void OnMenuCommand(int col,long row,int section,int item);
virtual void OnTH_LClicked(int col,long row,int updn,RECT *rect,POINT *point,BOOL processed);
virtual int OnSortEvaluate(CUGCell *cell1,CUGCell *cell2,int flags);
};
#endif
|
65bf1f55a91ad0844d3292aeffaacbd4e5912759
|
a13158a23232c771f86230d555a6d01de504bcfe
|
/jiffle/src/jiffle/vm.generate_test.cpp
|
51f2e2106b44e36692af4ccb3672d141cae87995
|
[
"MIT"
] |
permissive
|
ketdev/Jiffle
|
090b1e7b630423299ad35bf69e041458b0e27c58
|
729c8cec77eb0c1510492dcf5ae85c86752a25f7
|
refs/heads/master
| 2021-06-17T03:42:10.160873
| 2017-05-27T06:46:06
| 2017-05-27T06:46:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,336
|
cpp
|
vm.generate_test.cpp
|
#include "vm.h"
#include <assert.h>
namespace jiffle {
namespace vm {
typedef std::vector<uint8_t> bytes;
template<int N>
bytes b(const char str[N]) {
auto v = bytes(N);
memcpy(&v[0], str, N);
return v;
}
void generate_test() {
using namespace syntax;
using namespace expr;
// internal state -------------------------------------------------
std::vector<token> _src;
node _ast;
std::vector<table> _tables;
size_t _index;
// methods --------------------------------------------------------
auto gen = [&](const std::string& input) {
_src = tokenize(input);
_ast = parse(_src, input);
_tables = generate(_ast);
};
auto nextTable = [&]() {
assert(_index < _tables.size());
_index++;
};
auto end = [&]() {
assert(_index >= _tables.size());
};
auto assert_memory = [&](int offset, const bytes& data) {
assert(_index < _tables.size());
auto &mem = _tables[_index].memory;
assert(mem.size() >= offset + data.size());
assert(memcmp(&mem[offset], &data[0], data.size()) == 0);
};
// tests ----------------------------------------------------------
{ // empty
gen("");
end();
}
{ // constant memory
gen("3");
//assert_memory(0, b<4>("\x3\0\0\x1"));
//nextTable();
//end();
}
}
}
}
|
7f945f60461bfdee59a6803cd110b6b91c5d000c
|
986959b15d763745518085bdb5106daeb4e0b41d
|
/Volume - 3 (300 - 375)/303 - Strange Digits.cpp
|
51ad39de8faa8bf5c4da5b8d4f5946571400ec80
|
[] |
no_license
|
Md-Sabbir-Ahmed/Outsbook
|
a19d314b481d5f2e57478c98b0fe50d08781310c
|
e3b2c54517de3badff96f96d99d1592db7286513
|
refs/heads/master
| 2022-11-07T06:43:37.955730
| 2020-06-26T20:32:03
| 2020-06-26T20:32:03
| 267,264,610
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 587
|
cpp
|
303 - Strange Digits.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int m,temp,r,rev=0,maximum=0,minimum=0,temp2,rev2=0,r2;
cin>>m;
temp=m;
while(temp!=0)
{
r=temp%10;
rev=rev*r+r;
temp=temp/10;
}
if(rev>m)
{
maximum=rev;
minimum=m;
}
else{
maximum=m;
minimum=rev;
}
int diff=maximum-minimum;
temp2=diff;
while(temp2!=0)
{
r2=temp2%10;
rev2=rev2+r2;
temp2=temp2/10;
}
cout<<rev2;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.