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
4a66b8340352f5eca3f0d3e9623b4b5fb5fd0bad
2fba17950598a31cf85dd054bc5c978e5af2e74f
/include/agz-utils/graphics_api/d3d12/commandList.h
857d22446f04c7da827511a8856170f0d71837ab
[]
no_license
AirGuanZ/agz-utils
dfa934a7a278eb9a2b2bf964952977c8a11e49cc
a08e6d39bc6640c3f266cb7483133725d5083206
refs/heads/master
2022-01-24T06:28:09.748409
2022-01-15T07:55:06
2022-01-15T07:55:06
186,757,951
5
3
null
null
null
null
UTF-8
C++
false
false
892
h
commandList.h
#pragma once #include <agz-utils/graphics_api/d3d12/common.h> AGZ_D3D12_BEGIN class CommandList : public misc::uncopyable_t { public: CommandList() = default; CommandList(ID3D12Device *device, D3D12_COMMAND_LIST_TYPE type); CommandList(CommandList &&other) noexcept; CommandList &operator=(CommandList &&other) noexcept; void swap(CommandList &other) noexcept; void initialize(ID3D12Device *device, D3D12_COMMAND_LIST_TYPE type); bool isAvailable() const noexcept; void destroy(); ID3D12GraphicsCommandList4 *operator->() noexcept; ID3D12GraphicsCommandList4 *getRawCommandList() noexcept; void executeOnQueue(ID3D12CommandQueue *queue); void executeOnQueue(const ComPtr<ID3D12CommandQueue> &queue); private: ComPtr<ID3D12CommandAllocator> allocator_; ComPtr<ID3D12GraphicsCommandList4> cmdList_; }; AGZ_D3D12_END
22b5e71899fcd92b941967f4bc7c5dd866db3150
09b95cbd823d274de2a7f9e8ef483cb908cb1ebc
/Assegnamento 1/simple/simple.cpp
75ba7ed50747db0416e50bc651333c5d1d84c58b
[]
no_license
cavallo5/Visione_Artificiale
07454a6b9604e547fc2d61f6c03b99f6a9147063
2693001dbfa5918b95aa3c40e3e8276c3906c1b7
refs/heads/master
2022-12-04T03:45:30.194454
2020-08-12T07:59:41
2020-08-12T07:59:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,010
cpp
simple.cpp
/* Visione Artificiale Assegnamento 1 */ // OpenCV #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <fstream> #include <iostream> #include <string> using namespace std; using namespace cv; struct ArgumentList { std::string image_name; //!< image file name int wait_t; //!< waiting time }; bool ParseInputs(ArgumentList& args, int argc, char **argv) { if(argc<3 || (argc==2 && std::string(argv[1]) == "--help") || (argc==2 && std::string(argv[1]) == "-h") || (argc==2 && std::string(argv[1]) == "-help")) { std::cout<<"usage: simple -i <image_name>"<<std::endl; std::cout<<"exit: type q"<<std::endl<<std::endl; std::cout<<"Allowed options:"<<std::endl<< " -h produce help message"<<std::endl<< " -i arg image name. Use %0xd format for multiple images."<<std::endl<< " -t arg wait before next frame (ms) [default = 0]"<<std::endl<<std::endl<<std::endl; return false; } int i = 1; while(i<argc) { if(std::string(argv[i]) == "-i") { args.image_name = std::string(argv[++i]); } if(std::string(argv[i]) == "-t") { args.wait_t = atoi(argv[++i]); } else args.wait_t = 0; ++i; } return true; } /////////////////////////////////////////////////////////////////////////////////////// /* Esercizio 1 Funzione che effettua la valutazione del kernel Input: -cv::Mat& kernel -int val[2] La funzione salverà: -il padding della riga in val[0] -il padding della colonna in val[1] */ void valutazione_kernel(const cv::Mat& kernel, int val[]) { if (kernel.rows > kernel.cols) //se righe del kernel > colonne del kernel { val[0] = kernel.rows - 1; val[1] = 0; } else if (kernel.cols > kernel.rows) //se colonne del kernel > righe del kernel { val[0] = 0; val[1] = kernel.cols - 1; } else //kernel quadrato { val[0] = kernel.rows - 1; val[1] = kernel.cols - 1; } } /* Esercizio 1 Funzione che effettua il padding Input: cv::Mat& input: immagine su cui fare il padding cv::Mat& output: immagine in cui salvo l'immagine con il padding eseguito int pad_riga: informazioni sul padding delle righe int pad_colonna: informazione sul padding delle colonne */ void padding_immagine (const cv::Mat& input, cv::Mat& output,int pad_riga, int pad_colonna){ output = cv::Mat::zeros(input.rows + pad_riga, input.cols + pad_colonna, CV_8UC1); //creo un output di zeri con le dimensioni e formato richieste for(int i = 0; i < input.rows; i++) { for(int j = 0 ; j < input.cols ; j++ ) { output.data[( j + pad_colonna/2 + (i + pad_riga/2) * output.cols) * output.elemSize()] = input.data[(j + i * input.cols) * input.elemSize()]; //padding } } } /* Esercizio 1 Funzione che effettua la convoluzione float Input: -cv::Mat& image: singolo canale uint8 -cv::Mat& kernel: singolo canale float32 -cv::Mat& out: singolo canale float32 */ void convFloat(const cv::Mat& image, const cv::Mat& kernel, cv::Mat& output) { int pad_riga; //variabile utile per gestire il padding int pad_col; //variabile utile per gestire il padding float somma; //variabile utile per effettuare la convoluzione output = Mat(image.rows, image.cols, CV_32FC1); //definisco dimensione e formato dell'immagine d'uscita //Valuto il kernel int valutation_kernel[2]; //array in cui salverò le informazioni per il padding del kernel valutazione_kernel(kernel,valutation_kernel); //valuto la dimensione del kernel pad_riga=valutation_kernel[0]; //salvo l'informazione riguardanti il padding delle righe in pad_riga pad_col=valutation_kernel[1]; //salvo l'informazione riguardanti il padding delle colonne in pad_col /* Richiamo la funzione per effettuare il padding dell'immagine */ cv::Mat immagine_con_padding; //definisco una cv::Mat in cui salverò l'immagine con il padding eseguito padding_immagine(image, immagine_con_padding, pad_riga, pad_col); //effettuo il padding /* Puntatori a float per serializzare matrice */ float * out = (float *) output.data; //puntatori a float per output.data di cv::Mat output float * ker = (float *) kernel.data; //puntatori a float per kernel.data di cv::Mat kernel for (int righe = pad_riga/2; righe < immagine_con_padding.rows - pad_riga/2 ; righe++) { for (int colonne = pad_col/2 ; colonne < immagine_con_padding.cols - pad_col/2; colonne++) { somma = 0; //inizializzo somma a 0 prima di fare la convoluzione for (int kernel_righe = 0; kernel_righe < kernel.rows; kernel_righe++) { for(int kernel_colonne = 0; kernel_colonne < kernel.cols; kernel_colonne++) { somma = somma + float(immagine_con_padding.data[((righe - pad_riga/2 + kernel_righe ) * immagine_con_padding.cols + ( colonne - pad_col/2 + kernel_colonne)) * immagine_con_padding.elemSize()]) * ker[kernel_righe * kernel.cols + kernel_colonne]; //convoluzione } } out[(righe - pad_riga/2) * output.cols + (colonne - pad_col/2) ] = somma; //salvo in out i valori di somma ottenuti dalla convoluzione } } //Effettuo una conversione di output in float 32 cv::Mat conversione= Mat(image.rows, image.cols, CV_32FC1, out).clone(); //creo matrice di conversione delle dimensioni richieste conversione.convertTo(output, CV_32FC1); //converto output in float 32 } /* Esercizio 1bis Funzione che effettua la convoluzione int Input: -cv::Mat& image: singolo canale uint8 -cv::Mat& kernel: singolo canale float32 -cv::Mat& out: singolo canale uint8 */ void conv(const cv::Mat& image, cv::Mat& kernel, cv::Mat& output){ int pad_riga; //variabile utile per gestire il padding int pad_col; //variabile utile per gestire il padding float somma; //variabile utile per effettuare la convoluzione const float massimo = numeric_limits<float>::max(); const float minimo = numeric_limits<float>::min(); output = Mat(image.rows, image.cols, CV_8UC1); //definisco dimensione e formato dell'immagine d'uscita //Valuto ik kernel int valutation_kernel[2]; //array in cui salverò le informazioni per il padding del kernel valutazione_kernel(kernel,valutation_kernel); //valuto la dimensione del kernel pad_riga=valutation_kernel[0]; //salvo l'informazione riguardanti il padding delle righe in pad_riga pad_col=valutation_kernel[1]; //salvo l'informazione riguardanti il padding delle colonne in pad_col /* Richiamo la funzione per effettuare il padding dell'immagine */ cv::Mat immagine_con_padding; //definisco una cv::Mat in cui salverò l'immagine con il padding eseguito padding_immagine (image, immagine_con_padding, pad_riga, pad_col); //effettuo il padding float max = minimo; float min = massimo; float * out = new float[image.rows * image.cols]; float * ker = (float*) kernel.data; //puntatori a float per kernel.data di cv::Mat kernel for (int righe = pad_riga/2; righe < immagine_con_padding.rows - pad_riga/2 ; righe++) { for (int colonne = pad_col/2 ; colonne < immagine_con_padding.cols - pad_col/2; colonne++) { somma = 0; //inizializzo somma a 0 prima di fare la convoluzione for (int kernel_righe = 0; kernel_righe < kernel.rows; kernel_righe++) { for(int kernel_colonne = 0; kernel_colonne < kernel.cols; kernel_colonne++) { somma = somma + float(immagine_con_padding.data [((righe - pad_riga/2 + kernel_righe ) * immagine_con_padding.cols + ( colonne - pad_col/2 + kernel_colonne)) * immagine_con_padding.elemSize()]) * ker[kernel_righe * kernel.cols + kernel_colonne]; //convoluzione } } //Aggiorno i valori di massimo e minimo per effettuare successivamente la constrast stretching if (somma > max ) max = somma; else if(somma < min) min = somma; out[ (righe - pad_riga/2) * image.cols + (colonne -pad_col/2) ] = somma; //salvo in out i valori di somma ottenuti dalla convoluzione } } // Riscalatura dei valori nel range [0-255] cv::Mat conversione = Mat(image.rows, image.cols, CV_32FC1, out).clone(); //creo matrice di conversione delle dimensioni richieste conversione= conversione- min; float divisore=max - min; conversione = conversione * (255/divisore); //range [0-255] conversione.convertTo(output, CV_8UC1); //converto output in uint8 } /////////////////////////////////////////////////////////////////////////////////////// /* Esercizio 2 Funzione che genera un kernel di blur Gaussiano 1-D orizzontale Input: -float sigma: deviazione standard della gaussiana -int radius: raggio del kernel Output: -cv::Mat Kernel */ cv::Mat gaussianKernel(float sigma, int radius) { float dimensione_kernel=(2*radius)+1; //dimensione del Kernel ottenuta dal radius Mat Kernel = cv::Mat (1, 2*radius + 1 , CV_32FC1); //matrice Kernel singolo canale float 32 float sum = 0; //variabile che conta la somma dei valori assunti dall'esponenziale nel ciclo per poi normalizzare float* ker = (float*) Kernel.data; //puntatore a float per Kernel.data for (int i = 0; i < dimensione_kernel; i++){ float esponenziale= exp(-0.5 * ((i-radius)/sigma) * ((i-radius)/sigma)); //Gaussian blur ker[i]=float(esponenziale); //salvo i valori nel kernel sum = sum+(float)esponenziale; //aggiorno il valore somma } Kernel=Kernel/sum; //normalizzo dividendo per la somma dei pesi return Kernel; //restituisco cv::Mat Kernel } /////////////////////////////////////////////////////////////////////////////////////// /* Esercizio 3 Funzione che permette di ottenere un Gaussian blur verticale trasponendo quello orizzontale Input: -cv::Mat& matrice Output: -cv::Mat& matrice_trasposta */ void trasposta_matrice(const cv::Mat& matrice, cv::Mat& matrice_trasposta) { matrice_trasposta=Mat(matrice.cols,1,CV_32FC1); //matrice trasposta singolo canale float 32 float * mat = (float *) matrice.data; //puntatore a float della matrice iniziale float * mat_tra = (float *) matrice_trasposta.data; //puntatore a float di matrice_trasposta for(int i=0; i < matrice.cols; i++) { for(int j=0; j < matrice.rows; j++) { mat_tra[j + i*matrice_trasposta.cols ] = mat[i + j*matrice.cols]; //traspongo gli elementi della matrice matrice } } } /////////////////////////////////////////////////////////////////////////////////////// /* Esercizio 5 Funzione che permette di calcolare la magnitudo e l'orientazione di Sobel 3x3 Input: -cv::Mat& image: immagine -cv::Mat& magnitude: magnitudo di Sobel -cv::Mat& orientation: orientazione di Sobel */ void sobel(const cv::Mat& image, cv::Mat& magnitude, cv::Mat& orientation){ const float massimo = std::numeric_limits<float>::max(); const float minimo = std::numeric_limits<float>::min(); cv::Mat G_orizzontale = (Mat_<float>(3,3) << 1, 0, -1, +2, 0, -2 , 1, 0, -1); //G_orizzontale=[1,0,-1;2,0,-2;1,0,-1] cv::Mat G_verticale = (Mat_<float>(3,3) << 1, 2, 1, 0, 0, 0 , -1, -2, -1); //G_verticale=[1,2,1;0,0,0;-1,-2,-1] cv::Mat G_orizzontale_x , G_verticale_y; convFloat ( image, G_orizzontale , G_orizzontale_x ); convFloat ( image,G_verticale ,G_verticale_y ); float min = massimo; float max = minimo; float* magnitudo = (float* ) magnitude.data; //puntatore a float di magnitude float* orientazione = (float* ) orientation.data; //puntatore a float di orientation float* D_gx = (float* ) G_orizzontale_x.data; //puntatore a float di G_orizzontale_x float* D_gy = (float* ) G_verticale_y.data; //puntatore a float di G_verticale_y for (int i = 0; i < image.rows; i++){ for (int j = 0; j < image.cols; j++){ //Calcolo l'orientazione orientazione [ (i * orientation.cols + j) ] = atan2 (D_gy [ (i * G_verticale_y.cols + j)] , D_gx [ (i * G_orizzontale_x.cols + j) ] ); //arctg(Gy/Gx) if ( orientazione [ (i * orientation.cols + j) ] < 0) //se ho valori negativi orientazione [ (i * orientation.cols + j) ] = orientazione [ (i * orientation.cols + j) ] + 2*M_PI; //sommo 2*M_PI per rifasare //Calcolo la magnitudo magnitudo[(i * magnitude.cols + j)] = sqrt((pow( D_gx [(i * G_orizzontale_x.cols + j)] ,2) + pow( D_gy [ (i * G_verticale_y.cols+ j) ],2) ) ); //sqrt(Gx^2 + Gy^2) //Aggiorno i valori di max e min per effettuare successivamente la riscalatura if( magnitudo [(i * magnitude.cols + j)]< min) { min = magnitudo [(i * magnitude.cols+j )]; } else if( magnitudo [(i * magnitude.cols + j )] > max ) { max = magnitudo [ (i * magnitude.cols + j)]; } } } // Riscalatura dei valori nel range [0-255] Mat conversione = Mat(image.rows,image.cols,CV_32FC1,magnitudo).clone(); //creo matrice di conversione con le dimensioni e formato richiesti conversione =conversione - min; float divisore=max - min; conversione = conversione * (1.0/divisore); conversione.convertTo(magnitude,CV_32FC1); ////converto output in float32 } /////////////////////////////////////////////////////////////////////////////////////// /* Esercizio 6 Funzione che permette di calcolare l'interpolazione bilineare Input: -cv::Mat& image: immagine uint8 -float r= riga del punto -float c= colonna del punto Output: -float f=valore dell'interpolazione bilineare */ float bilinear(const cv::Mat& image, float r, float c) { float f=0; //variabile in cui salverò il valore della bilinear int x = int(r); //x è la parte intera di r int y = int(c); //y è la parte intera di c float s = r - x; float t = c - y; float f00 =( image.data[(x*image.cols + y)]); //in(y,x) float f10 = (image.data[((x+1) * image.cols + y)]); //in(y,x+1) float f01 = (image.data[(x * image.cols + (y + 1))]); //in(y+1,x) float f11 =( image.data[((x+1) * image.cols + (y+1))]); //in(y+1,x+1) f=(1-s)*(1-t)* f00+ s*(1-t)* f10 + (1-s)*t* f01+ s*t*f11; //formula slide 15 return f; } /////////////////////////////////////////////////////////////////////////////////////// /* Esercizio 7 Funzione che permette di calcolare l'interpolazione bilineare Input: -cv::Mat& image: immagine float 32 -float r= riga del punto -float c= colonna del punto Output: -float f=valore dell'interpolazione bilineare */ float bilinear_float(const Mat& image, float r, float c) { float f=0; int x = floor(r); //x è l'intero arrotondato per difetto int y = floor(c); //y è l'intero arrotondato per difetto float s = r - x; float t = c - y; float* immagine = (float * ) image.data; float f00 =float ( immagine[( x * image.cols + y ) ] ); //in(y,x) float f10 = float (immagine[ ( ( x+1) * image.cols + y )] ); //in(y,x+1) float f01 = float ( immagine[( x * image.cols + (y + 1))] ); //in(y+1,x) float f11 =(immagine[( ( x+1) * image.cols + (y + 1))] ); //in(y+1,x+1) f=(1-s)*(1-t)* f00+ s*(1-t)* f10 + (1-s)*t* f01+ s*t*f11; //formula slide 15 return f; } /* Esercizio 7 Funzione che permette di calcolare trovare i picchi (massimi) del gradiente nella direzione perpendicolare al gradiente stesso Input: -cv::Mat& magnitude: singolo canale float32 -cv::Mat& orientation: singolo canale float32 -cv::Mat& out: singolo canale float 32 -float th */ void findPeaks (const cv::Mat& magnitude, const cv::Mat& orientation, cv::Mat& out ,float th){ out = Mat( magnitude.rows, magnitude.cols, CV_32FC1); //creo un output con le dimensioni e formato richieste (float32) float E_1X,E_1Y,E_1,E_2,E_2X,E_2Y; //variabili utilizzate per calcolare i vicini a distanza 1 lungo la direzione del gradiente float* magnitudo = (float*) magnitude.data; //puntatore a float di magnitude float* uscita = (float*) out.data; //puntatore a float di out float* orientazione = (float*) orientation.data; //puntatore a float di orientation for (int r = 0; r < magnitude.rows; r++){ for (int c = 0; c < magnitude.cols; c++){ E_1X = c + 1 * cos( orientazione[ r * out.cols + c ]); //e1x=c+1*cos(theta) E_1Y = r + 1 * sin( orientazione[ r * out.cols + c ]); //e1y=r+1*sin(theta) E_1 = bilinear_float(magnitude,E_1Y,E_1X); //e1 ottenuta dalla bilinear di E_1X e E_1Y E_2X = c - 1 * cos( orientazione[ r * out.cols + c ]); //e2x=c-1*cos(theta) E_2Y = r - 1 * sin( orientazione[ r * out.cols + c ] ); //e2y=r-1*sin(theta) E_2 = bilinear_float(magnitude,E_2Y, E_2X); //e2 ottenuta dalla bilinear di E_2X e E_2Y //Soppressione dei non massimi if ( magnitudo[ (r * magnitude.cols + c )] >= E_1 && magnitudo[ (r * magnitude.cols + c )] >= E_2 && magnitudo[ (r * magnitude.cols + c )] >= th ) { uscita[ r * out.cols + c ] = magnitudo[ (r * magnitude.cols + c )]; //out(r,c)=in(r,c) } else { uscita[ r * out.cols + c ] = 0.0f; //out(r,c)=0 } } } //Effettuo la conversione in float32 cv::Mat conversione = Mat(magnitude.rows,magnitude.cols,CV_32FC1,uscita).clone(); //creo matrice di conversione con le dimensioni e formato richiesti conversione.convertTo(out,CV_32FC1); } /////////////////////////////////////////////////////////////////////////////////////// /* Esercizio 8 Funzione che realizza la Soglia con isteresi -cv::Mat& magnitude: singolo canale float32 -cv::Mat& out: singolo canale uint8 -float th1 -float th2 */ void doubleTh(Mat& magnitude,Mat& out, float th1, float th2){ out = Mat(magnitude.rows, magnitude.cols, CV_8UC1); //definisco l'output con le dimensioni e il formato richieste (uint8) const float val_massimo=255; const float val_medio=128; const float val_minimo=0; float* magnitudo = (float* ) magnitude.data; //puntatore a float di magnitude for (int riga = 0; riga < magnitude.rows; riga++){ for (int colonna = 0; colonna < magnitude.cols; colonna++){ //Catena di if che realizzano il sistema di slide 19 if ( magnitudo [ riga * magnitude.cols + colonna ] > th1 ) //in(r,c)>th1 { out.data[ ( riga * out.cols + colonna ) * out.elemSize()] = val_massimo; //out(r,c)=255 } else if ( magnitudo [ riga * magnitude.cols + colonna ] <= th1 && magnitudo [ riga * magnitude.cols + colonna ] > th2 ) //th1>=in(r,c)>th2 { out.data[ ( riga * out.cols + colonna ) * out.elemSize()] = val_medio; //out(r,c)=128 } else //in(r,c)<=th2 { out.data[ ( riga * out.cols + colonna ) * out.elemSize()] = val_minimo; //out(r,c)=0 } } } } /////////////////////////////////////////////////////////////////////////////////////// /* Esercizio 9 Funzione che effettua il Canny Edge Detector su lenna.pgm -cv::Mat& image: singolo canale uint8 -cv::Mat& out: singolo canale uint8 -float th -float th1 -float th2 */ void canny(const Mat& image, Mat& out, float th, float th1, float th2) { out = Mat(image.rows,image.cols,CV_8UC1); //definisco l'output con le dimensioni e il formato richieste (uint8) //1. Sobel magnituo e orientazione cv::Mat magnitudo,orientazione; magnitudo = Mat(image.rows, image.cols, CV_32FC1); orientazione = Mat(image.rows, image.cols, CV_32FC1); sobel(image,magnitudo,orientazione); //2. FindPeaks della magnitudo cv::Mat uscita_findPeaks; findPeaks(magnitudo, orientazione, uscita_findPeaks, th); //3. Sogliatura con isteresi doubleTh(uscita_findPeaks,out,th1, th2); } /////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char **argv){ int frame_number = 0; char frame_name[256]; bool exit_loop = false; /* Valori soglia assegnamento a=0.2; b=0.7; c=0.3; */ float a,b,c; cout << "Valore di th: "; cin >> a; cout << "Valore di th_1: "; cin >> b; cout << "Valore di th_2: "; cin >> c; ////////////////////// //parse argument list: ////////////////////// ArgumentList args; if(!ParseInputs(args, argc, argv)) { return 1; } while(!exit_loop) { //generating file name // //multi frame case if(args.image_name.find('%') != std::string::npos) sprintf(frame_name,(const char*)(args.image_name.c_str()),frame_number); else //single frame case sprintf(frame_name,"%s",args.image_name.c_str()); //opening file std::cout<<"Opening "<<frame_name<<std::endl; cv::Mat image = cv::imread(frame_name,IMREAD_GRAYSCALE); if(image.empty()) { std::cout<<"Unable to open "<<frame_name<<std::endl; return 1; } ////////////////////// //processing code here /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 1 //Creo Kernel 3x3 float 32 con elementi pari a 1 cv::Mat kernel(3,3,CV_32FC1); //Creo un kernel singolo canale float32 con tutti gli elementi pari a 1 for(int riga_kernel=0; riga_kernel < kernel.rows; riga_kernel++) { for(int colonna_kernel=0; colonna_kernel < kernel.cols; colonna_kernel++) { *((float *)&kernel.data[(colonna_kernel+riga_kernel*kernel.cols)*kernel.elemSize()])=1.0; } } //Stampa del Kernel cout<<"Il kernel è:"<<endl; cout<<kernel<<endl; cv::Mat uscita_esercizio_1; //Definisco cv::Mat esercizio_1 conv(image,kernel,uscita_esercizio_1); //Mostro i risultati ottenuti namedWindow("Esercizio_1", WINDOW_NORMAL); imshow("Esercizio_1", uscita_esercizio_1); /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 2 cout<<"Creazione kernel di blur Gaussiano 1-D orizzontale"<<endl; float sigma=1.0; //sigma della gaussiana int raggio=3; //raggio del kernel cout<<"Sigma: "<<sigma<<endl; cout<<"Raggio: "<<raggio<<endl; cv::Mat gaus_ker=gaussianKernel(sigma, raggio); //Genero un kernel di blur Gaussiano cout<<"Il kernel di blur Gaussiano 1-D orizzontale è"<<std::endl; cout<<gaus_ker<<endl; /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 3 cout<<"Generazione Gaussian blur orizzontale"<<endl; cv::Mat gaussian_blur_orizzontale; //Gaussian blur orizzontale conv(image, gaus_ker, gaussian_blur_orizzontale); cout<<"Generazione Gaussian blur verticale"<<endl; cv::Mat gaus_ker_trasp; //kernel verticale trasposta_matrice(gaus_ker, gaus_ker_trasp); //ottengo il kernel verticale trasponendo quello orizzontale cv::Mat gaussian_blur_verticale; //Gaussian blur verticale conv(image, gaus_ker_trasp, gaussian_blur_verticale); cout<<"Generazione Gaussian blur bidimensionale"<<endl; cv::Mat gaussian_blur_bid; //Gaussian blur bidimensionale conv(gaussian_blur_orizzontale, gaus_ker_trasp, gaussian_blur_bid); //Mostro i 3 risultati ottenuti imshow("Gaussian blur orizzontale", gaussian_blur_orizzontale); imshow("Gaussian blur verticale",gaussian_blur_verticale); imshow("Gaussian blur bidimensionale", gaussian_blur_bid); /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 4 cv::Mat monodimensionale = (Mat_<float>(1,3) << -1, 0, 1); //derivativo monodimensionale [-1,0,1] cv::Mat laplace= (Mat_<float>(3,3) << 0, 1, 0, 1, -4, 1, 0, 1, 0); //[0,1,0;1,-4,1;0,1,0] cv::Mat gauss_derivativo_orizzontale= gaus_ker_trasp * monodimensionale; //derivativo Gaussiano orizzontale cv::Mat monodimensionale_trasp; //ci salvo il trasposto del derivativo monodimensionale ovvero [-1,0,1]' trasposta_matrice(monodimensionale, monodimensionale_trasp); //effettuo il trasposto del derivativo monodimensionale cv::Mat gauss_derivativo_verticale= monodimensionale_trasp * gaus_ker; //derivativo Gaussiano verticale cout<<"Generazione filtro derivativo Gaussiano orizzontale"<<endl; cv::Mat filtro_derivativo_orizzontale; //ci salvo il filtro derivativo gaussiano orizzontale conv(image,gauss_derivativo_orizzontale,filtro_derivativo_orizzontale); cout<<"Generazione filtro derivativo Gaussiano verticale"<<endl; Mat filtro_derivativo_verticale; //ci salvo il filtro derivativo gaussiano verticale conv(image,gauss_derivativo_verticale,filtro_derivativo_verticale); cout<<"Generazione filtro Laplaciano"<<endl; cv::Mat filtro_laplaciano; //ci salvo il filtro Laplaciano conv(image,laplace,filtro_laplaciano); //Mostro i 3 risultati ottenuti imshow("Derivativo Gaussiano Orizzontale", filtro_derivativo_orizzontale); imshow("Derivativo Gaussiano Verticale", filtro_derivativo_verticale); imshow("Laplaciano",filtro_laplaciano); /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 5 cv::Mat magnitudo, orientazione; //magnitudo e orientazione magnitudo = Mat(image.rows, image.cols, CV_32FC1); //creo magnitudo con le dimensioni e formato richieste (float32) orientazione = Mat(image.rows, image.cols, CV_32FC1); //creo orientazione con le dimensioni e formato richieste (float32) cout<<"Generazione magnitudo e orientazione di Sobel"<<endl; sobel(image,magnitudo,orientazione); //Visualizzazione dell'orientazione di Sobel cv::Mat adjMap; convertScaleAbs(orientazione, adjMap, 255 / (2*M_PI)); cv::Mat falseColorsMap; applyColorMap(adjMap, falseColorsMap,cv::COLORMAP_AUTUMN); imshow("Orientazione (Sobel) ", falseColorsMap); //Visualizzazione della magnitudo di Sobel imshow("Magnitudo (Sobel)", magnitudo); /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 6 float r_ex=27.8; //r dell'esempio float c_ex=11.4; //c dell'esempio float bilinear_interpolation=bilinear(image,r_ex,c_ex); //calcolo dell'interpolazione bilineare cout<<"Valore di interpolazione bilineare:"<<endl; cout<<bilinear_interpolation<<endl; /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 7 cv::Mat findPeaks_uscita; //ci salvo Find Peaks float th=a; //0.2 cout<<"Generazione Find Peaks of Edge Responses"<<endl; findPeaks (magnitudo,orientazione,findPeaks_uscita,th); //Visualizzazione di findPeaks imshow ("Find Peaks", findPeaks_uscita); /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 8 float th1= b; //0.7 float th2=c; //0.3 cv::Mat soglia_isteresi; cout<<"Generazione Soglia con isteresi"<<endl; doubleTh(magnitudo, soglia_isteresi, th1, th2); imshow("Soglia con Isteresi", soglia_isteresi); /////////////////////////////////////////////////////////////////////////////////////// //Esercizio 9 cv::Mat canny_edge; //salvo l'uscita del Canny Edge Detector cout<<"Canny Edge Detector"<<endl; canny(image,canny_edge,th,th1,th2); //Visualizzazione di Canny Edge Detector imshow("Canny Edge Detector", canny_edge); /////////////////////////////////////////////////////////////////////////////////////// //display image cv::namedWindow("image", cv::WINDOW_NORMAL); cv::imshow("image", image); //wait for key or timeout unsigned char key = cv::waitKey(args.wait_t); std::cout<<"key "<<int(key)<<std::endl; //char key='g'; //here you can implement some looping logic using key value: // - pause // - stop // - step back // - step forward // - loop on the same frame if(key == 'g') exit_loop = true; frame_number++; } return 0; }
215463b264babcc50d873a0725cc8deb60578bc1
b6351ef45b35e8b648e0fa9056e23f676b757878
/Client/headers/Interpreter.hpp
0d7c5622a0488f6b3b263789d93fdf351a3a1334
[]
no_license
BGCX261/zprproject-jspw-hg-to-git
921de82731d3df6ba52b8dc3d15d14fce82de02a
ad1bebb1b98f5ec9e7f5f9ce74c22f57273a2aee
refs/heads/master
2021-01-23T13:49:59.320262
2011-09-04T14:25:57
2011-09-04T14:25:57
42,317,508
0
0
null
null
null
null
UTF-8
C++
false
false
1,807
hpp
Interpreter.hpp
/* * File: Interpreter.hpp * Author: Pawel * * Zawiera deklaracje klasy Interpreter * Created on 30 listopad 2010, 15:50 */ #ifndef INTERPRETER_HPP #define INTERPRETER_HPP #include <boost/shared_ptr.hpp> #include "Visitor.hpp" #include "Command.hpp" namespace Client { /* * Odpowiedzialna za interpretowanie komend wprowadzanych z konsoli * Singleton */ class Interpreter : public Visitor { public: typedef boost::shared_ptr<Interpreter> PInterpreter; /* * Pobranie instancji * @return Instancja */ static PInterpreter getInstance(); /* * Destruktor */ virtual ~Interpreter(); /* * Obsluguje komende Auth * @param authCmd Komenda */ void handle(const AuthCommand& authCmd); /* * Obsluguje komende Create * @param createCmd Komenda */ void handle(const CreateCommand& createCmd); /* * Obsluguje komende Disc * @param discCmd Komenda */ void handle(const DiscCommand& discCmd); /* * Obsluguje komende Subs * @param subsCmd Komenda */ void handle(const SubsCommand& subsCmd); /* * Obsluguje komende Usub * @param usubCmd Komenda */ void handle(const UsubCommand& usubCmd); /* * Obsluguje komende NewMsg * @param newCmd Komenda */ void handle(const NewMsgCommand& newCmd); /* * Interpretuje podana komende * @param cmd Komenda */ void interpret(const Command& cmd); private: static PInterpreter _pInstance; Interpreter(); }; } #endif /* INTERPRETER_HPP */
d07e3c48e7684acab7b5a579d026b253ef9fd01f
5b90c88a281ed3299a5eb26125f245bc97a259ba
/source/core/property-slider.cpp
8ed5867eacfd6fd08d01be6cd2900ac288fdd8d6
[ "MIT" ]
permissive
kollya/fluid-simulator
5d3a22635af6e94de07243bc7e3f5a0a17dd2720
629301987fff9e82cf1f1cc99b010b5f8619136b
refs/heads/main
2023-07-25T05:52:38.202414
2021-08-27T06:53:19
2021-08-27T06:53:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,920
cpp
property-slider.cpp
#include "application.hpp" #include <iomanip> using namespace nanogui; Application::PropertySlider::PropertySlider(Widget* window, Config::Property* p, const std::string &name, const std::string &unit, size_t precision) : prop(p), last_value(*p), precision(precision) { Widget* panel = new Widget(window); panel->set_layout(new GridLayout(Orientation::Horizontal, 3, Alignment::Middle)); Label* label = new Label(panel, name, "sans-bold"); label->set_fixed_width(86); slider = new Slider(panel); slider->set_value(prop->getNormalized()); slider->set_fixed_size({ 200, 20 }); slider->set_callback([prop = prop, slider = slider, this](float value) { // Hack to skip first set event. Could be fixed if nanogui didn't trigger the slider set event on mouse button release. if (!initiated) { initiated = true; slider->set_value(prop->getNormalized()); return; } prop->setNormalized(value); } ); slider->set_final_callback([this](float value) { initiated = false; } ); float_box = new FloatBox<float>(panel); float_box->set_alignment(TextBox::Alignment::Right); float_box->set_fixed_size({ 70, 20 }); float_box->number_format("%.0" + std::to_string(precision) + "f"); float_box->set_editable(true); float_box->set_value(prop->getDisplay()); float_box->set_font_size(14); float_box->set_units(unit); float_box->set_callback([float_box = float_box, prop = prop, precision](float value) { prop->setDisplay(value); float_box->set_value(*prop); } ); } void Application::PropertySlider::updateValue() { if (last_value != *prop) { slider->set_value(prop->getNormalized()); float_box->set_value(prop->getDisplay()); last_value = *prop; } }
ac50ec9c3c984a392a38a76d37f3454e5c7ffdb1
6fe3afaf390277ccf0702723d26c27938e816d3c
/strStr2.cpp
67d6f4e73178c0d588a20d12a7eb38314e36a2cf
[]
no_license
coderwyc/hello-world
f93640b592b9d372b6d51651b415cbc34e3b4a8c
552523748f89958ed954fd6e031f0148d7c3c46c
refs/heads/master
2020-05-17T10:46:45.624621
2015-07-23T14:06:53
2015-07-23T14:06:53
28,033,252
0
0
null
null
null
null
UTF-8
C++
false
false
635
cpp
strStr2.cpp
/************* Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. **************/ class Solution { public: int strStr(char *haystack, char *needle) { int len_hay = strlen(haystack); int len_nee = strlen(needle); for(int i=0; ;i++) { for(int j=0; ;j++) { if(j == len_nee) return i; if(i + j == len_hay) return -1; if(*(needle+j) != *(haystack+i+j)) break; } } } };
d8618975dde4c6b2bcd82f56f82f8367d6a30a3b
b703cb4f590af7b5f138f4a383b2f6f31209993b
/mef02-c07/carac01.h
852296604b30dd0073edde2f5c545c315d5305aa
[]
no_license
Beasalman/mef
9d5e28a77d1dd25542174cd2e8a2289ec1167548
cd08c3b3cf7050fb76c38b7cd74c7e553faca025
refs/heads/master
2020-05-29T21:50:22.841664
2019-05-31T12:20:08
2019-05-31T12:20:08
189,392,446
0
0
null
null
null
null
UTF-8
C++
false
false
550
h
carac01.h
#include <iostream> using std::cout; using std::endl; #include <vector> using std::vector; #include <map> using std::map; #ifndef cnodo2d_h_ #include "cnodo2d.h" #endif /* --------------------------------------------------------------------------- */ #ifndef carac01_h_ #define carac01_h_ cnodo2d carac01 (cnodo2d *, double, int, vector <double>); cnodo2d carac01 (cnodo2d *, double, int, vector <double> (*)(double,double)); #endif /* -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- */
8f2d1d45007217f5c4e5563eecc9c114a61b22ea
e2368b4672189a195ba5d31dcd5707b9d711feb2
/Coding Blocks Course/Recursion & backtracking/01Knapsack.cpp
1ae77b6783f9661dcdaf9c228164f95fb694251b
[]
no_license
MdAkdas/My_Codes
bd073b82bc35ac506f6fbe15c5b9f34fa75212a5
8cd202e4f4b31820f59577c9983d7e42b3f5c5e4
refs/heads/master
2022-11-29T08:27:21.454738
2020-07-31T18:02:51
2020-07-31T18:02:51
255,170,541
0
0
null
null
null
null
UTF-8
C++
false
false
622
cpp
01Knapsack.cpp
#include <iostream> using namespace std; int profit(int item,int Capacity,int *weight,int *price) { if(item==0 || Capacity==0) return 0; int inc,exc; inc=exc=0; //including current item if(Capacity>=weight[item-1]) inc = price[item-1] + profit(item-1,Capacity-weight[item-1],weight,price); //excluding current item exc = profit(item-1,Capacity,weight,price); cout<<inc<<" "<<exc<<endl; return max(inc,exc); } int main() { int weight[]={1,2,3,5}; int price[]={40,20,30,100}; int item=4; int Capacity=7; cout<<profit(item,Capacity,weight,price)<<endl; return 0; }
99348755e94fe1db83ce4cd7e38c05962a92b9f6
91a0f6893bfa017c3a17a1c17d24902ef1d72a82
/GuessBoard.cpp
3d1907b4fd295007e33ce907fd5436c26765a638
[]
no_license
glmontuya/Battle_Ship_Game
d1694eac72a4b796a19bedf53948be9c586aa2ca
e2ff0150fbb996915f90331e4f72e61659b2c7e6
refs/heads/master
2020-05-26T04:47:04.339980
2019-02-28T00:40:41
2019-02-28T00:40:41
188,110,348
0
0
null
2019-05-22T20:38:41
2019-05-22T20:38:41
null
UTF-8
C++
false
false
950
cpp
GuessBoard.cpp
// // Created by kerne on 2/27/2019. // #include "GuessBoard.h" using std::vector; using std::ostream; using std::endl; using std::cout; #include <string> using std::string; GuessBoard::GuessBoard(){ for(int i = 0; i < _GuessboardSize; i++){ _guide.push_back(vector<string>()); for(int k = 0; k < _GuessboardSize; k++){ _guide[i].push_back("?"); } } } ostream& operator<<(ostream& os, GuessBoard& board){ cout << endl; int counter = 1; for(auto rowVector : board._guide){ cout << counter << " "; for(auto item : rowVector){ os << " " << item; } os << " " << endl; counter++; } cout << endl << " "; for(int i = 1; i < 6; ++i){ cout << " " << i; } return os; } void GuessBoard::processGuess(int x, int y, string s){ _guide[y-1][x-1] = s; } int GuessBoard::getBoardSize(){ return _GuessboardSize; }
9b37729e428bfd8c8708751b0ed4d6c5fe2e230a
dd6147bf9433298a64bbceb7fdccaa4cc477fba6
/8304/Altukhov_Alexander/lab1/CrossbowmanLvl2.cpp
542ca16dcc907aae5dd527775749a4ece1ee35eb
[]
no_license
moevm/oop
64a89677879341a3e8e91ba6d719ab598dcabb49
faffa7e14003b13c658ccf8853d6189b51ee30e6
refs/heads/master
2023-03-16T15:48:35.226647
2020-06-08T16:16:31
2020-06-08T16:16:31
85,785,460
42
304
null
2023-03-06T23:46:08
2017-03-22T04:37:01
C++
UTF-8
C++
false
false
29
cpp
CrossbowmanLvl2.cpp
#include "CrossbowmanLvl2.h"
fc4e0a202848f9c91e9d098315d1cbfbeb9eea94
1c0ec16578f2951f64442f1577b83a4c78194924
/cpp/OpenGL/Vis_03_Particle/Flowfield.cpp
184b5b4c101d2f73c3c3eaab17b61aaa5836fd49
[]
no_license
sdraeger/lnc
5e8381325caf01667597a0e3ed6d5e9b2df22dc8
dc5762d58449b1b5a98c914fd41bd300190dc2c4
refs/heads/master
2023-03-10T10:14:58.728940
2021-02-22T21:53:43
2021-02-22T21:53:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,106
cpp
Flowfield.cpp
#include <cmath> #include "Flowfield.h" Flowfield Flowfield::genDemo(size_t size, DemoType d) { Flowfield f{size,size,size}; switch (d) { case DemoType::DRAIN : { for (size_t z = 0;z<size;++z) { const float localZ = float(z)/size; for (size_t y = 0;y<size;++y) { const float localY = float(y)/size; for (size_t x = 0;x<size;++x) { const float localX = float(x)/size; f.data[x+y*size+z*size*size] = Vec3{(-localY+0.5f)+(0.5f-localX)/10.0f,(localX-0.5f)+(0.5f-localY)/10.0f,-localZ/10.0f}; } } } } break; case DemoType::SATTLE : { for (size_t z = 0;z<size;++z) { const float localZ = float(z)/size; for (size_t y = 0;y<size;++y) { const float localY = float(y)/size; for (size_t x = 0;x<size;++x) { const float localX = float(x)/size; f.data[x+y*size+z*size*size] = Vec3{0.5f-localX,localY-0.5f,0.5f-localZ}; } } } } break; case DemoType::CRITICAL : { for (size_t z = 0;z<size;++z) { const float localZ = float(z)/size; for (size_t y = 0;y<size;++y) { const float localY = float(y)/size; for (size_t x = 0;x<size;++x) { const float localX = float(x)/size; f.data[x+y*size+z*size*size] = Vec3{(localX-0.1f)*(localY-0.3f)*(localX-0.8f),(localY-0.7f)*(localZ-0.2f)*(localX-0.3f),(localZ-0.9f)*(localZ-0.6f)*(localX-0.5f)}; } } } } break; } return f; } Flowfield::Flowfield(size_t sizeX, size_t sizeY, size_t sizeZ) : sizeX(sizeX), sizeY(sizeY), sizeZ(sizeZ) { data.resize(sizeX*sizeY*sizeZ); } Vec3 Flowfield::getData(size_t x, size_t y, size_t z) { return data[x+y*sizeY+z*sizeX*sizeY]; } Vec3 Flowfield::linear(const Vec3& a, const Vec3& b, float alpha) { return a * (1.0f - alpha) + b * alpha; } Vec3 Flowfield::interpolate(const Vec3& pos) { const size_t fX = size_t(floor(pos.x() * (sizeX-1))); const size_t fY = size_t(floor(pos.y() * (sizeY-1))); const size_t fZ = size_t(floor(pos.z() * (sizeZ-1))); const size_t cX = size_t(ceil(pos.x() * (sizeX-1))); const size_t cY = size_t(ceil(pos.y() * (sizeY-1))); const size_t cZ = size_t(ceil(pos.z() * (sizeZ-1))); const std::array<Vec3, 8> values = { getData(fX,fY,fZ), getData(cX,fY,fZ), getData(fX,cY,fZ), getData(cX,cY,fZ), getData(fX,fY,cZ), getData(cX,fY,cZ), getData(fX,cY,cZ), getData(cX,cY,cZ) }; const float alpha = pos.x() * (sizeX-1) - fX; const float beta = pos.y() * (sizeY-1) - fY; const float gamma = pos.z() * (sizeZ-1) - fZ; return linear(linear(linear(values[0], values[1], alpha), linear(values[2], values[3], alpha), beta), linear(linear(values[4], values[5], alpha), linear(values[6], values[7], alpha), beta), gamma); }
f75fb448ea37958b0babd0f93cf0a7e5f910b0d6
9825dc853f1db04e318118cf8bb7d232a9e8d722
/rmvmath/matrix/matrix2x3/func/TMatrix2x3_func.hpp
4134db47d1ee9be13af644250878dc28e5aaeb45
[ "MIT" ]
permissive
vitali-kurlovich/RMMath
5f862c49847a788d7794f71c7df486a49a19aa63
a982b89e5db08e9cd16cb08e92839a315b6198dc
refs/heads/master
2021-01-17T10:45:10.432565
2016-09-14T19:22:14
2016-09-14T19:22:14
53,895,137
0
0
null
null
null
null
UTF-8
C++
false
false
599
hpp
TMatrix2x3_func.hpp
// // Created by Vitali Kurlovich on 1/7/16. // #ifndef RMVECTORMATH_TMATRIX2X3_FUNC_HPP #define RMVECTORMATH_TMATRIX2X3_FUNC_HPP #include "../TMatrix2x3_def.hpp" #include "../../matrix3x2/TMatrix3x2_def.hpp" namespace rmmath { namespace matrix { template<typename T> inline TMatrix3x2 <T> transpose(const TMatrix2x3 <T> &a) { TMatrix3x2<T> result = { a.m00, a.m10, a.m01, a.m11, a.m02, a.m12 }; return result; } } } #endif //RMVECTORMATH_TMATRIX2X3_FUNC_HPP
26ffa8fc0e496a242b2e75960fe0a7c2782cb4b3
807285158038bf1f9c7b7d1666ce8c8f90ef7581
/examples/tile_integration/PhysicalTileApply.cpp
a428d34902c3e5b2a9ed810e0195f5cfd2aebc2b
[]
no_license
jonghunDB/SciDB19.3
177ccc421175977d45b679bd61841218c8ea8b17
e413d086b715112b37b0ae9a2882e0fff3b4cfe6
refs/heads/master
2020-05-23T11:42:23.435694
2019-07-03T11:12:42
2019-07-03T11:12:42
186,736,377
0
0
null
null
null
null
UTF-8
C++
false
false
3,564
cpp
PhysicalTileApply.cpp
/* ** * BEGIN_COPYRIGHT * * Copyright (C) 2008-2019 SciDB, Inc. * All Rights Reserved. * * SciDB is free software: you can redistribute it and/or modify * it under the terms of the AFFERO GNU General Public License as published by * the Free Software Foundation. * * SciDB is distributed "AS-IS" AND WITHOUT ANY WARRANTY OF ANY KIND, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * NON-INFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. See * the AFFERO GNU General Public License for the complete license terms. * * You should have received a copy of the AFFERO GNU General Public License * along with SciDB. If not, see <http://www.gnu.org/licenses/agpl-3.0.html> * * END_COPYRIGHT */ #include <vector> #include <query/PhysicalOperator.h> #include <query/FunctionLibrary.h> #include <query/FunctionDescription.h> #include <query/TypeSystem.h> #include <system/ErrorsLibrary.h> #include <array/Array.h> #include "TileApplyArray.h" namespace scidb { using namespace std; class PhysicalTileApply: public PhysicalOperator { public: PhysicalTileApply(const string& logicalName, const string& physicalName, const Parameters& parameters, const ArrayDesc& schema) : PhysicalOperator(logicalName, physicalName, parameters, schema) { } virtual PhysicalBoundaries getOutputBoundaries(const std::vector<PhysicalBoundaries> & inputBoundaries, const std::vector< ArrayDesc> & inputSchemas) const { return inputBoundaries[0]; } std::shared_ptr<Array> execute(vector< std::shared_ptr<Array> >& inputArrays, std::shared_ptr<Query> query) { assert(inputArrays.size() == 1); assert(_parameters.size()%2 == 0); size_t numAttrs = _schema.getAttributes().size(); assert(numAttrs >0); std::shared_ptr< vector<std::shared_ptr<Expression> > > expPtr = std::make_shared< vector< std::shared_ptr< Expression> > >(numAttrs); vector<std::shared_ptr<Expression> >& expressions = *expPtr; assert(expressions.size() == numAttrs); size_t currentParam = 0; auto attrIter = _schema.getAttributes().begin(); for(size_t i =0; i<numAttrs; ++i) { assert(_parameters.size() > currentParam+1); assert(_parameters[currentParam]->getParamType() == PARAM_ATTRIBUTE_REF); assert(_parameters[currentParam+1]->getParamType() == PARAM_PHYSICAL_EXPRESSION); string const& schemaAttName = attrIter->getName(); ++attrIter; string const& paramAttName = ((std::shared_ptr<OperatorParamReference>&)_parameters[currentParam])->getObjectName(); if(schemaAttName == paramAttName) { expressions[i] = ((std::shared_ptr<OperatorParamPhysicalExpression>&)_parameters[currentParam+1])->getExpression(); currentParam+=2; } if(currentParam == _parameters.size()) { break; } } assert(currentParam == _parameters.size()); assert(expressions.size() == _schema.getAttributes().size()); assert(!_tileMode); // we dont run in old tile mode std::shared_ptr<Array> input = inputArrays[0]; return std::make_shared<TileApplyArray>(_schema, input, expPtr, query); } }; REGISTER_PHYSICAL_OPERATOR_FACTORY(PhysicalTileApply, "tile_apply", "PhysicalTileApply"); } // namespace scidb
e1a247ccd3a5031cb57129cec00e7ff1df3e4557
0c150d83570afd033a51461ffcbe9169bf0db07a
/workspace/ejecucion/enteros.hpp
3ae39cd35d0b5d4e51291add56e447c7842e9e61
[]
no_license
alu0100819182/aedaprct03
d6902e63aad81c3f16a50951183955a7b209cb8a
ee78ab613f4cc71593e0a25178dea1f3d35609a0
refs/heads/master
2021-01-10T13:45:36.750627
2016-03-30T13:17:36
2016-03-30T13:17:36
55,064,380
0
0
null
null
null
null
UTF-8
C++
false
false
1,432
hpp
enteros.hpp
#include <cstdio> #include <iostream> #include "numero.h" #pragma once using namespace std; class entero_t: public numero{ public: int valor; entero_t(); entero_t(int num); ~entero_t (void); friend entero_t operator+(const entero_t& n1, const entero_t& n2); friend entero_t operator-(const entero_t& n1, const entero_t& n2); friend entero_t operator*(const entero_t& n1, const entero_t& n2); friend entero_t operator/(const entero_t& n1, const entero_t& n2); entero_t& operator=(const entero_t& n2); friend bool operator>(const entero_t& n1, const entero_t& n2); friend bool operator<(const entero_t& n1, const entero_t& n2); friend bool operator==(const entero_t& n1, const entero_t& n2); //const entero_t toEntero() const; //const racional toRacional() const; //const real toReal() const; //const complex_t toComplejo() const; friend ostream& operator << (ostream &os,const entero_t &p); friend istream& operator >> (istream &is, entero_t &p); virtual ostream& toStream(ostream& sout)const{ sout << valor; return sout; } virtual istream& fromStream(istream& sin){ double aux_double, aux; int aux_int; cout << "Introduce número entero: "; try{ sin >> aux_double; aux_int=aux_double; aux=aux_int-aux_double; if(aux<0) throw "El número introducido no es válido"; else valor=aux_double; } catch(const char *str){ cout << str << endl; } return sin; } };
7e17c7aaecc8f6c70561b0ee4582e15e926a7f3e
fe6360bf697243c6c318836a3c64a9c1984b610b
/deprecated/alter/pluginSource/entityHelpers/EntityHelpers.cpp
6c365b190b7be9783b2a747f30ffa0812c91edf6
[]
no_license
davidmueller13/vexx
366cec96f4abac2e814176cd5d2ae75393561c0d
9194877951c78cd3fde3e7fbe6d511e40c24f8eb
refs/heads/master
2021-01-10T11:51:19.124071
2015-09-26T15:30:05
2015-09-26T15:30:05
43,210,604
0
0
null
null
null
null
UTF-8
C++
false
false
441
cpp
EntityHelpers.cpp
#include "APlugin" #include "EntityHelpers.h" #include "propertiesDock.h" #include "explorerDock.h" ALTER_SDK_INITIALISE( Q_DECL_EXPORT ) { sdk->addDockedItem( "Explorer", new explorerDock( ) ); sdk->addDockedItem( "Properties", new propertiesDock( ) ); return APlugin::Success; } ALTER_SDK_UNINITIALISE( Q_DECL_EXPORT ) { sdk->removeDockedItem( "Explorer" ); sdk->removeDockedItem( "Properties" ); }
5b10ed097d166d0d72b4fa9cbb3e8c74abdcf1d0
029462827b95625e0b72f1dada384c49106ac409
/dellve_cudnn_benchmark/include/CuDNN/PoolingMode.hpp
85f1e5caca1d9e42912b643c6a9a8cc5cab23ba3
[ "MIT" ]
permissive
dellve/dellve_cudnn
c05c993bacfe721f6a34e3ec83aaa9d7e09ec11c
61491953f3f3953539e6060ccf18c303e7a3c1fd
refs/heads/master
2021-01-22T23:15:58.258731
2017-05-02T16:45:49
2017-05-02T16:45:49
89,177,551
1
0
null
null
null
null
UTF-8
C++
false
false
194
hpp
PoolingMode.hpp
#ifndef PYCUDNN_POOLING_MODE_HPP #define PYCUDNN_POOLING_MODE_HPP #include <cudnn.h> namespace CuDNN { typedef cudnnPoolingMode_t PoolingMode; } // PyCuDNN #endif // PYCUDNN_POOLING_MODE_HPP
5620a0903bf978c4b44ca57d792e29ef1f5a754c
235f766d0edadf581ff6bec0d8fffa181655207b
/data/maps/NewMap6/scripts.inc
71320e02cfcf531332af3af07d1fa20016bcae36
[]
no_license
lassellie/pokeemeraldexceptglitched
ff0f179048bf11cf653c4567b97c31d748a8102e
39d0bedabe7f4d42dac1b5297c6961ca39a6763a
refs/heads/master
2023-06-07T19:29:46.645077
2021-06-30T04:30:47
2021-06-30T04:30:47
267,154,726
0
0
null
null
null
null
UTF-8
C++
false
false
30
inc
scripts.inc
NewMap6_MapScripts:: .byte 0
4c8643280e3696f366019e8ab595c1b58c2702ae
c11c70fedf6576850a82ddfdb2ccefe857a242d8
/mote/brew/brewmotewrite/brewmotewrite.ino
ec953bb7d208d1a3a17bcd9514104333fdb26b73
[ "Apache-2.0" ]
permissive
iinnovations/iicontrollibs
edf43e7f22d90d5143602a07a545e64c1e071a09
94af26a61405f1ad928d36e36602ebb859a2e44f
refs/heads/master
2021-12-14T12:32:29.698267
2021-12-01T01:09:44
2021-12-01T01:09:44
14,500,841
11
12
null
null
null
null
UTF-8
C++
false
false
17,478
ino
brewmotewrite.ino
#define DEBUG 1 // Colin Reese, CuPID Controls, Interface Innovations // UniMote sketch, based on the great example by lowpowerlab // RFM69 and SPIFlash Library by Felix Rusu - felix@lowpowerlab.com // Get the RFM69 and SPIFlash library at: https://github.com/LowPowerLab/ #include <RFM69.h> //#include <RFM69registers.h> #include <SPI.h> #include <SPIFlash.h> #include <OneWire.h> #include <LowPower.h> #include <EEPROM.h> #include <SPIFlash.h> //#include <LedControl.h> //Match frequency to the hardware version of the radio on your Moteino (uncomment one): #define FREQUENCY RF69_433MHZ //#define FREQUENCY RF69_868MHZ //#define FREQUENCY RF69_915MHZ #define IS_RFM69HW //uncomment only for RFM69HW! Leave out if you have RFM69W! #define REG_SYNCVALUE2 0x30 // Radio stuff byte NODEID = 2; byte NETWORKID = 1; byte GATEWAYID = 1; #define serialrfecho 1 #define RETRIES 2 #define ACK_TIME 300 #define ENCRYPTKEY "sampleEncryptKey" /////////////////////////////////////////////////////////// // Software Serial Stuff #include <SoftwareSerial.h> // Gateway is 16 RX, 15 RX, 17 RTS // Mote is 14,15,16 SoftwareSerial mySerial(15, 16, 0); // RX, TX #define LED 9 // Moteinos have LEDs on D9 #define SENDLED 18 #define FLASH_SS 8 char buff[61]; int i = 0; int cmdlength; uint8_t mbstate; byte RTSPIN = 17; int xmitdelay = 0; unsigned long rxstart; unsigned long rxwait = 1000; float sv; float pv; byte rtuaddress=0; // message : node, FC, register start high byte, low byte, number of registers high byte, low byte, CRC, CRC byte pvsvmessage[] = {0x01, 0x03, 0x47, 0x00, 0x00, 0x02, 0x00, 0x00 }; byte outputmessage[] = {0x01, 0x03, 0x47, 0x14, 0x00, 0x02, 0x00, 0x00 }; byte modemessage[] = {0x01, 0x03, 0x47, 0x18, 0x00, 0x02, 0x00, 0x00 }; // for set message, same except two bytes for number of registers are replaced by the data to program into // the target register byte setmessage[] = {0x01, 0x06, 0x47, 0x01, 0x04, 0x4C, 0x00, 0x00 }; byte nummessages = 3; byte message[] = {0x01, 0x03, 0x47, 0x18, 0x00, 0x02, 0x00, 0x00 }; byte mbmessagetype = 0; long mycrc; byte rtuaddresses[] = {1,2,3}; byte rtuindex; boolean requestACK = false; SPIFlash flash(FLASH_SS, 0xEF30); //EF30 for 4mbit Windbond chip (W25X40CL); RFM69 radio; void setup() { Serial.begin(115200); mbstate = 0; rtuindex = 0; addcrc(pvsvmessage,6); addcrc(outputmessage,6); addcrc(modemessage,6); addcrc(setmessage,6); mySerial.begin(9600); if (DEBUG) { Serial.println("DEBUG IS ON"); } #ifdef IS_RFM69HW radio.setHighPower(); //uncomment only for RFM69HW! #endif if (flash.initialize()) { Serial.println(F("SPI Flash Init OK")); // Serial.print(F("UniqueID (MAC): ")); // flash.readUniqueId(); // for (byte i=0;i<8;i++) // { // Serial.print(flash.UNIQUEID[i], HEX); // Serial.print(' '); // } // Serial.println(); } else { Serial.println(F("SPI Flash Init FAIL)")); } radio.encrypt(ENCRYPTKEY); //sendInitMessage(); } void loop() { if (Serial.available() > 0) { if (DEBUG) { Serial.println("reading characters"); } String cmdstring =Serial.readStringUntil('\n'); if (DEBUG) { Serial.println("Serial cmd buffer is: "); Serial.println(cmdstring); Serial.println("Of length"); Serial.println(cmdstring.length()); } processcmdstring(cmdstring); }// comnand sequence // radio send/receive stuff // RADIO RECEIVE AND PROCESSING // Check for any received packets if (radio.receiveDone()) { Blink(LED,5); Serial.println(F("BEGIN RECEIVED")); Serial.print(F("nodeid:"));Serial.print(radio.SENDERID, DEC);Serial.print(F(",")); cmdlength=0; for (byte i = 0; i < radio.DATALEN; i++) { Serial.print((char)radio.DATA[i]); buff[i] = (char)radio.DATA[i]; cmdlength+=1; } Serial.print(F(",RX_RSSI:")); Serial.println(radio.RSSI); Serial.println(F("END RECEIVED")); byte replynode = radio.SENDERID; if (radio.ACKRequested()) { radio.sendACK(); Blink(LED,5); Serial.println(F(" - ACK sent")); } // ack requested if (cmdlength > 0){ //processcmdstring(buff, cmdlength, replynode); } // Reset sleepdelay timer //millistart = millis(); } // Radio Receive // END RADIO RECEIVE // serial master stuff switch ( mbstate ) { case 0: // This is the transmit stage message[0] = rtuaddresses[rtuindex]; for (byte i=1; i<6; i++) { switch (mbmessagetype) { case 0: message[i] = pvsvmessage[i]; break; case 1: message[i] = outputmessage[i]; break; case 2: message[i] = modemessage[i]; break; case 3: message[i] = setmessage[i]; break; } } addcrc(message,6); if (DEBUG) { Serial.print("MESSAGETYPE: "); Serial.println(mbmessagetype); Serial.print("sending to controller: "); Serial.println(rtuaddresses[rtuindex]); Serial.print(message[0],HEX); Serial.print(" "); Serial.print(message[1],HEX); Serial.print(" "); Serial.print(message[2],HEX); Serial.print(" "); Serial.print(message[3],HEX); Serial.print(" "); Serial.print(message[4],HEX); Serial.print(" "); Serial.print(message[5],HEX); Serial.print(" "); Serial.print(message[6],HEX); Serial.print(" "); Serial.println(message[7],HEX); } pinMode(RTSPIN, OUTPUT); digitalWrite(RTSPIN,HIGH); delay(xmitdelay); mySerial.write(message, sizeof(message)); delay(xmitdelay); digitalWrite(RTSPIN,LOW); mbstate = 1; rxstart = millis(); break; case 1: // wait for response // Serial.println("Waiting"); if (mySerial.available() > 0) { Blink(LED,5); cmdlength = mySerial.readBytes(buff, 60); if (DEBUG) { Serial.print("Received message of length "); Serial.println(cmdlength); for (i=0; i<cmdlength;i++){ Serial.print(buff[i], HEX); Serial.print(" "); } Serial.println(); } if (buff[1]==3) { if (mbmessagetype == 0){ pv = (float(buff[3] & 255) * 256 + float(buff[4] & 255))/10; sv = (float(buff[5] & 255) * 256 + float(buff[6] & 255))/10; if (DEBUG) { Serial.println("values"); // Serial.println((int(buff[3]&255))*256, DEC); // Serial.println(buff[4]&255, DEC); // Serial.println(int(buff[5]&255)*256, DEC); // Serial.println(buff[6]&255, DEC); Serial.print("nodeid:"); Serial.print(NODEID); Serial.print(",controller:"); Serial.print(rtuindex); Serial.print(",pv:"); Serial.print(pv); Serial.print(",sv:"); Serial.println(sv); } } else if (mbmessagetype == 1) { pv = (float(buff[3] & 255) * 256 + float(buff[4] & 255)); sv = (float(buff[5] & 255) * 256 + float(buff[6] & 255)); if (DEBUG) { Serial.print("Proportional offset: "); Serial.println(pv); Serial.print("Regulation value"); Serial.println(sv); } } else if (mbmessagetype == 2) { pv = (float(buff[3] & 255) * 256 + float(buff[4] & 255)); sv = (float(buff[5] & 255) * 256 + float(buff[6] & 255)); if (DEBUG) { Serial.print("Heating/cooling"); Serial.println(pv); Serial.print("Run/Stop"); Serial.println(sv); } } Blink(SENDLED,5); sendControllerMessage(rtuaddresses[rtuindex], pv, sv, mbmessagetype); } else if (buff[1]==6) { sv = (float(buff[4] & 255) * 256 + float(buff[5] & 255))/10; if (DEBUG) { Serial.print("Command acknowledged for node:"); Serial.println(buff[0]); Serial.print("Setpoint: "); Serial.println(sv); } sendCmdResponseMessage(buff[0], sv); } else { if (DEBUG) { Serial.println("bad response"); } } } if (millis() - rxstart > rxwait) { if (mbmessagetype >= (nummessages - 1)) { mbmessagetype = 0; if (rtuindex >= sizeof(rtuaddresses)-1) { rtuindex = 0; } else { rtuindex ++; } } else { mbmessagetype ++; } mbstate=0; } break; } // switch } void sendWithSerialNotify(byte destination, char* sendstring, byte sendlength, byte notify) { if (notify==1) { Serial.print(F("SENDING TO ")); Serial.println(destination); sendstring[sendlength]=0; Serial.println(sendstring); // Serial.println(sendlength); } radio.sendWithRetry(destination, sendstring, sendlength, RETRIES, ACK_TIME); if (notify==1) { Serial.println(F("SEND COMPLETE")); } } void sendCmdResponseMessage(byte controller, float sv) { // Initialize send string int sendlength = 61; // default //int wholesv = sv; int wholesv = sv; long fractsv = ((long)(sv*1000))%1000; //Serial.println(wholesv); //Serial.println(fractsv); if (NODEID == 1) { sendlength = 31; sprintf(buff, "nodeid:1,chan:%02d,svcmd:%03d.%03d", controller, wholesv, fractsv); Serial.println(buff); } else { sendlength = 23; sprintf(buff, "chan:%02d,svcmd:%03d.%03d", controller, wholesv, fractsv); sendWithSerialNotify(GATEWAYID, buff, sendlength, 1); } } void sendControllerMessage(byte controller, float pv, float sv, byte messagetype) { // Initialize send string int sendlength = 61; // default int wholepv = pv; int fractpv = (pv - wholepv) * 1000; int wholesv = sv; int fractsv = (sv - wholesv) * 1000; if (messagetype == 0) { if (NODEID == 1) { sendlength = 39; sprintf(buff, "nodeid:1,chan:%02d,sv:%03d.%03d,pv:%03d.%03d", controller, wholesv, fractsv, wholepv, fractpv); Serial.println(buff); } else { sendlength = 30; sprintf(buff, "chan:%02d,sv:%03d.%03d,pv:%03d.%03d", controller, wholesv, fractsv, wholepv, fractpv); sendWithSerialNotify(GATEWAYID, buff, sendlength, 1); } } else if (messagetype == 1) { if (NODEID == 1) { sendlength = 37; sprintf(buff, "nodeid:1,chan:%02d,prop:%03d,treg:%03d.%01d", controller,wholepv, wholesv, fractpv); Serial.println(buff); } else { sendlength = 28; sprintf(buff, "chan:%02d,prop:%03d,treg:%03d.%01d", controller,wholepv, wholesv, fractsv); sendWithSerialNotify(GATEWAYID, buff, sendlength, 1); } } else if (messagetype == 2) { if (NODEID == 1) { sendlength = 31; sprintf(buff, "nodeid:1,chan:%02d,htcool:%01d,run:%01d", controller,wholepv,wholesv); Serial.println(buff); } else { sendlength = 22; sprintf(buff, "chan:%02d,htcool:%01d,run:%01d", controller,wholepv, wholesv); sendWithSerialNotify(GATEWAYID, buff, sendlength, 1); } } } void Blink(byte PIN, int DELAY_MS) { pinMode(PIN, OUTPUT); digitalWrite(PIN,HIGH); delay(DELAY_MS); digitalWrite(PIN,LOW); } // Compute the MODBUS RTU CRC unsigned int ModRTU_CRC(byte* buf, int len) { unsigned int crc = 0xFFFF; for (int pos = 0; pos < len; pos++) { crc ^= (unsigned int)buf[pos]; // XOR byte into least sig. byte of crc for (int i = 8; i != 0; i--) { // Loop over each bit if ((crc & 0x0001) != 0) { // If the LSB is set crc >>= 1; // Shift right and XOR 0xA001 crc ^= 0xA001; } else // Else LSB is not set crc >>= 1; // Just shift right } } // Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes) return crc; } void sendsvcmd(int node, float sv) { message[0] = node; if (sv > 0 && sv < 250) { for (byte i=1; i<6; i++) { message[i] = setmessage[i]; } Serial.print("received setpoint:"); Serial.println(sv); int highbyte = (sv * 10) / 256; int lowbyte = int(sv * 10) & 255; Serial.print("High byte:"); Serial.println(highbyte); Serial.print("Low byte:"); Serial.println(lowbyte); message[4] = highbyte; message[5] = lowbyte; // pv = (float(buff[3] & 255) * 256 + float(buff[4] & 255))/10; // sv = (float(buff[5] & 255) * 256 + float(buff[6] & 255))/10; addcrc(message,6); if (DEBUG) { Serial.println("SENDING SV CMD"); Serial.print("sending to controller: "); Serial.println(node); Serial.print(message[0],HEX); Serial.print(" "); Serial.print(message[1],HEX); Serial.print(" "); Serial.print(message[2],HEX); Serial.print(" "); Serial.print(message[3],HEX); Serial.print(" "); Serial.print(message[4],HEX); Serial.print(" "); Serial.print(message[5],HEX); Serial.print(" "); Serial.print(message[6],HEX); Serial.print(" "); Serial.println(message[7],HEX); } pinMode(RTSPIN, OUTPUT); digitalWrite(RTSPIN,HIGH); delay(xmitdelay); mySerial.write(message, sizeof(message)); delay(xmitdelay); digitalWrite(RTSPIN,LOW); rxstart = millis(); mbstate = 1; } } void addcrc(byte* message, int len) { mycrc = ModRTU_CRC(message, len); // Serial.println(); // Serial.println(mycrc,HEX); long byte1 = mycrc & 255; long byte2 = (mycrc & long(255*256))>>8; if (DEBUG) { Serial.print(byte1,HEX); Serial.print(","); Serial.println(byte2,HEX); } message[len] = byte1; message[len + 1] = byte2; } void processcmdstring(String cmdstring){ Serial.println(F("processing cmdstring")); Serial.println(cmdstring); int i; String str1=""; String str2=""; String str3=""; String str4=""; if (cmdstring[0] == '~'){ Serial.println(F("Command character received")); int strord=1; for (i=1;i<cmdstring.length();i++){ if (cmdstring[i] != ';' || strord == 4){ if (cmdstring[i] != '\n' && cmdstring[i] != '\0' && cmdstring[i] != '\r'){ if (strord == 1){ str1+=cmdstring[i]; } else if (strord == 2){ str2+=cmdstring[i]; } else if (strord == 3){ str3+=cmdstring[i]; } else if (strord == 4){ str4+=cmdstring[i]; } else { Serial.println(F("Error in argument string parse")); } } } // cmdstring is not ; else { // cmdstring is ; strord ++; } //cmdstring is ; } // for each character if (str1 == "listparams") { //listparams(0,0); } else if (str1 == "rlistparams") { //listparams(1,str2.toInt()); } else if (str1 == "reset") { // resetMote(); } else if (str1 =="sendmsg"){ Serial.println(F("sending message: ")); Serial.print(F("to dest id: ")); Serial.println(str2.toInt()); Serial.print(F("Reserved parameter is: ")); Serial.println(str3); Serial.print(F("Message is: ")); Serial.println(str4); Serial.print(F("Length: ")); Serial.println(str4.length()); str4.toCharArray(buff,str4.length()+1); radio.sendWithRetry(str2.toInt(), buff, str4.length()+1); } else if (str1 =="setsv"){ Serial.println(F("setsv: ")); Serial.print(F("of channel: ")); Serial.println(str2.toInt()); Serial.print(F("To value: ")); Serial.println(str3); Serial.println(F("AND here is where I send the message")); sendsvcmd(str2.toInt(), str3.toFloat()); } else if (str1 == "flashid"){ Serial.println(F("Flash ID: ")); for (i=0;i<8;i++){ Serial.print(flash.UNIQUEID[i],HEX); } } else{ Serial.println(F("unrecognized command")); Serial.println(str1); Serial.print(F("of length: ")); Serial.println(str1.length()); for (i=0;i<str1.length();i++){ Serial.println(str1[i]); } } } // first character indicates command sequence else { // first character is not command if (cmdstring[0] == 'r') //d=dump register values radio.readAllRegs(); //if (input == 'E') //E=enable encryption // radio.encrypt(KEY); //if (input == 'e') //e=disable encryption // radio.encrypt(null); if (cmdstring[0] == 'd') //d=dump flash area { Serial.println("Flash content:"); uint16_t counter = 0; Serial.print("0-256: "); while(counter<=256){ Serial.print(flash.readByte(counter++), HEX); Serial.print('.'); } while(flash.busy()); Serial.println(); } if (cmdstring[0] == 'e') { Serial.print(F("Erasing Flash chip ... ")); flash.chipErase(); while(flash.busy()); Serial.println(F("DONE")); } if (cmdstring[0] == 'i') { Serial.print(F("DeviceID: ")); word jedecid = flash.readDeviceId(); Serial.println(jedecid, HEX); } } }
9f17c0bf84a6fcc3ebdd9dc0aa6bf801f16b1d17
715cf2089f8882c3a5f9ab0cb64bbdbc1466ce02
/cc/stablemarket.cpp
6d4d6aabc2d0ee49901ac3645797cd44fea58032
[]
no_license
ShriBatman/myCodes
def9de8b72b5d406d2fb2a0c07cd8e7294679019
72798e04f8b504ddc7ae2ae2295dea13a94156ff
refs/heads/master
2021-01-17T19:23:15.520349
2019-04-20T12:25:43
2019-04-20T12:25:43
95,568,212
0
0
null
null
null
null
UTF-8
C++
false
false
642
cpp
stablemarket.cpp
//i am vengence i am the night i am Batman //ios_base::sync_with_stdio(false);cin.tie(NULL); #include<bits/stdc++.h> using namespace std; int main() { long long int q,i,j,k,l,m,n,r,t,x,y,z; cin>>t; for(i=0;i<t;i++) { cin>>n>>q; vector< int > a; for(j=0;j<n;j++) { cin>>l; a.push_back(l); } for(j=0;j<q;j++) { cin>>l>>r; cin>>k; vector< int > b(n+1,0); x=1; for(m=l-1;m<r-1;m++) { if(a[m]==a[m+1]) { x++; } else { b[x]++; x=1; } } b[x]++; y=0; for(m=k;m<n+1;m++) { y+=b[m]; } cout<<y<<"\n"; } } return 0; }
7ef81980a234cdf194ce0db7cea14d84708ca2df
5743077502c2ab293905c7533fe9774576773ebe
/src/common/beast/beast/unit_test/reporter.h
e9952058e8579087998659e839c5dd2a97d4b01f
[ "ISC", "BSL-1.0", "MIT" ]
permissive
hawx1993/truechain-testnet-core
3056b07dc1d39dc9277d1d2960c7c23db39bbf9c
a75edfe83562b3764fb3140144bc41943ebb995a
refs/heads/master
2021-01-24T19:08:55.033847
2018-02-28T06:31:48
2018-02-28T06:31:48
123,239,490
1
0
MIT
2018-02-28T06:21:53
2018-02-28T06:21:53
null
UTF-8
C++
false
false
7,552
h
reporter.h
//------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef BEAST_UNIT_TEST_REPORTER_H_INCLUDED #define BEAST_UNIT_TEST_REPORTER_H_INCLUDED #include <beast/unit_test/amount.h> #include <beast/unit_test/recorder.h> #include <beast/streams/abstract_ostream.h> #include <beast/streams/basic_std_ostream.h> #include <boost/optional.hpp> #include <algorithm> #include <chrono> #include <functional> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <utility> namespace beast { namespace unit_test { namespace detail { /** A simple test runner that writes everything to a stream in real time. The totals are output when the object is destroyed. */ template <class = void> class reporter : public runner { private: using clock_type = std::chrono::steady_clock; struct case_results { std::string name; std::size_t total = 0; std::size_t failed = 0; case_results (std::string const& name_ = ""); }; struct suite_results { std::string name; std::size_t cases = 0; std::size_t total = 0; std::size_t failed = 0; typename clock_type::time_point start = clock_type::now(); explicit suite_results (std::string const& name_ = ""); void add (case_results const& r); }; struct results { using run_time = std::pair<std::string, typename clock_type::duration>; enum { max_top = 10 }; std::size_t suites = 0; std::size_t cases = 0; std::size_t total = 0; std::size_t failed = 0; std::vector<run_time> top; typename clock_type::time_point start = clock_type::now(); void add (suite_results const& r); }; boost::optional <std_ostream> std_ostream_; std::reference_wrapper <abstract_ostream> stream_; results results_; suite_results suite_results_; case_results case_results_; public: reporter (reporter const&) = delete; reporter& operator= (reporter const&) = delete; ~reporter(); explicit reporter (std::ostream& stream = std::cout); explicit reporter (abstract_ostream& stream); private: static std::string fmtdur (typename clock_type::duration const& d); virtual void on_suite_begin (suite_info const& info) override; virtual void on_suite_end() override; virtual void on_case_begin (std::string const& name) override; virtual void on_case_end() override; virtual void on_pass() override; virtual void on_fail (std::string const& reason) override; virtual void on_log (std::string const& s) override; }; //------------------------------------------------------------------------------ template <class _> reporter<_>::case_results::case_results ( std::string const& name_) : name (name_) { } template <class _> reporter<_>::suite_results::suite_results ( std::string const& name_) : name (name_) { } template <class _> void reporter<_>::suite_results::add (case_results const& r) { ++cases; total += r.total; failed += r.failed; } template <class _> void reporter<_>::results::add ( suite_results const& r) { ++suites; total += r.total; cases += r.cases; failed += r.failed; auto const elapsed = clock_type::now() - r.start; if (elapsed >= std::chrono::seconds(1)) { auto const iter = std::lower_bound(top.begin(), top.end(), elapsed, [](run_time const& t1, typename clock_type::duration const& t2) { return t1.second > t2; }); if (iter != top.end()) { if (top.size() == max_top) top.resize(top.size() - 1); top.emplace(iter, r.name, elapsed); } else if (top.size() < max_top) { top.emplace_back(r.name, elapsed); } } } //------------------------------------------------------------------------------ template <class _> reporter<_>::reporter ( std::ostream& stream) : std_ostream_ (std::ref (stream)) , stream_ (*std_ostream_) { } template <class _> reporter<_>::~reporter() { if (results_.top.size() > 0) { stream_.get() << "Longest suite times:"; for (auto const& i : results_.top) stream_.get() << std::setw(8) << fmtdur(i.second) << " " << i.first; } auto const elapsed = clock_type::now() - results_.start; stream_.get() << fmtdur(elapsed) << ", " << amount (results_.suites, "suite") << ", " << amount (results_.cases, "case") << ", " << amount (results_.total, "test") << " total, " << amount (results_.failed, "failure"); } template <class _> reporter<_>::reporter ( abstract_ostream& stream) : stream_ (stream) { } template <class _> std::string reporter<_>::fmtdur ( typename clock_type::duration const& d) { using namespace std::chrono; auto const ms = duration_cast<milliseconds>(d); if (ms < seconds(1)) return std::to_string(ms.count()) + "ms"; std::stringstream ss; ss << std::fixed << std::setprecision(1) << (ms.count()/1000.) << "s"; return ss.str(); } template <class _> void reporter<_>::on_suite_begin ( suite_info const& info) { suite_results_ = suite_results (info.full_name()); } template <class _> void reporter<_>::on_suite_end() { results_.add (suite_results_); } template <class _> void reporter<_>::on_case_begin ( std::string const& name) { case_results_ = case_results (name); stream_.get() << suite_results_.name << (case_results_.name.empty() ? "" : (" " + case_results_.name)); } template <class _> void reporter<_>::on_case_end() { suite_results_.add (case_results_); } template <class _> void reporter<_>::on_pass() { ++case_results_.total; } template <class _> void reporter<_>::on_fail ( std::string const& reason) { ++case_results_.failed; ++case_results_.total; stream_.get() << "#" << case_results_.total << " failed" << (reason.empty() ? "" : ": ") << reason; } template <class _> void reporter<_>::on_log ( std::string const& s) { stream_.get() << s; } } // detail using reporter = detail::reporter<>; } // unit_test } // beast #endif
2900667ad37ddd7dae407873f8a59e6e6ccfef25
6e27e7c74c43cd2407024878dffba81a4422e6c9
/source/CIO.cpp
579d6126a90d2be69f789423b77af16a0cafbb13
[]
no_license
mbatc/PiProject
b6aae775fe538f34b181a05bd7be4023d5fa95df
fdafc8dbfc6406c5c4497a8a0e70be9739e8a4d8
refs/heads/master
2021-01-20T00:21:32.274169
2017-05-11T13:14:07
2017-05-11T13:14:07
89,117,260
0
0
null
null
null
null
UTF-8
C++
false
false
1,237
cpp
CIO.cpp
#include "CIO.h" #include "CLog.h" #include <stdarg.h> #include <iostream> #include <fstream> using namespace std; CIO::CIO() {} CIO::~CIO() {} void CIO::Print(string format, ...) { va_list args; va_start(args,format); _out.Print(format, args); va_end(args); } void CIO::PrintF(string file, string format, ...) { va_list args; va_start(args,format); _out.PrintF(file, format, args); va_end(args); } string CIO::GetCMDLine() { return _in.GetCMDLine(); } void CIO::OFStream(string file, string format, ...) { ofstream file_ostream(file.c_str()); if(file_ostream < 0) { _LOG.Log(this,DEBUGLOG_LEVEL_WARNING, "Unable to open file output stream: %s", file.c_str()); return; } file_ostream << format; file_ostream.close(); } std::string CIO::IFStream(string file) { string ret; ifstream file_istream(file.c_str()); if(file_istream < 0) { _LOG.Log(this,DEBUGLOG_LEVEL_WARNING, "Unable to open file input stream: %s", file.c_str()); return ""; } file_istream >> ret; file_istream.close(); return ret; } void CIO::OpenFile(string file, const char* t) { _out.OpenFile(file, t); } void CIO::CloseFile(string file) { _out.CloseFile(file); } void CIO::CloseAllFiles() { _out.CloseAllFiles(); }
7ea258ad9628d9d864cc40ee78a0643de0156912
3045fb40b0eb9124d339f4bf377c7a98a9f25884
/addons/cirkit-addon-reversible/src/reversible/utils/reversible_program_options.hpp
ec94115bd473caa9fd45b2449cb987c405eaf280
[]
no_license
chuzhufei/cirkit
43828a97ab0aec3deaf2234eb087b9794f873e45
907a36ea1c82321b730a62c744f7b5c4ef3e8c61
refs/heads/master
2020-12-28T04:51:39.472139
2016-07-13T07:40:07
2016-07-13T07:40:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,319
hpp
reversible_program_options.hpp
/* CirKit: A circuit toolkit * Copyright (C) 2009-2015 University of Bremen * Copyright (C) 2015-2016 EPFL * * 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 3 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, see <http://www.gnu.org/licenses/>. */ /** * @file reversible_program_options.hpp * * @brief Easier access to program options * * @author Mathias Soeken * @author Nabila Abdessaied * @since 1.0 */ #ifndef REVERSIBLE_PROGRAM_OPTIONS_HPP #define REVERSIBLE_PROGRAM_OPTIONS_HPP #include <core/utils/program_options.hpp> #include <reversible/utils/costs.hpp> namespace cirkit { /** * @brief Class for program options on top of the Boost.Program_Options library * * This class can be used when writing programs for accessing algorithms. * It parses from C argc and argv variables and has some functions for * adding program options for common used parameters like input realization or * specification filename and output realization filename. * * @note It can be useful to check the <a href="http://www.boost.org/doc/libs/1_41_0/doc/html/program_options.html">Boost.Program_Options</a> * documentation for further information. */ class reversible_program_options : public program_options { public: /** * @brief Default constructor * * Calls the constructor of the boost::program_options::options_description * base class and adds a --help option. * * @param line_length Length of the terminal where to output * * @since 1.0 */ explicit reversible_program_options( unsigned line_length = m_default_line_length ); /** * @brief Constructor with setting a caption for usage output * * Calls the constructor of the boost::program_options::options_description * base class and adds a --help option. * * @param caption A caption is primarily useful for output * @param line_length Length of the terminal where to output * * @since 1.0 */ explicit reversible_program_options( const std::string& caption, unsigned line_length = m_default_line_length ); /** * @brief Default deconstructor */ virtual ~reversible_program_options(); /** * @brief Is help needed? Are all properties set properly? * * This method returns true when the --help option is not set * and when the --filename option is set, as far as either * add_read_realization_option() or add_read_specification_option() * was called before. * * @return true, when all properties are set properly. Otherwise false. * * @since 1.0 */ bool good() const; /** * @brief Adds an option for an input as RevLib realization * * This method adds an option called --filename which takes * a RevLib realization (*.real) file as argument. * * After calling this function, add_read_specification_option() * cannot be called anymore. * * @return The program_options object itself for repeatedly function calls * * @since 1.0 */ reversible_program_options& add_read_realization_option(); /** * @brief Adds an option for an input as RevLib specification * * This method adds an option called --filename which takes * a RevLib specification (*.spec) file as argument. * * After calling this function, add_read_realization_option() * cannot be called anymore. * * @return The program_options object itself for repeatedly function calls * * @since 1.0 */ reversible_program_options& add_read_specification_option(); /** * @brief Adds an option for an output as RevLib realization * * This method adds an option called --realname which takes * a RevLib realization (*.real) file as argument. * * To check whether this option was set or not, use * is_write_realization_filename_set(). * * @return The program_options object itself for repeatedly function calls * * @since 1.0 */ reversible_program_options& add_write_realization_option(); /** * @brief Adds an option for selecting a cost function * * This method adds an option called --costs which takes * an integer value as argument representing a cost function, * whereby 0 is gate costs, 1 is line costs, 2 is quantum costs, * and 3 is transistor costs, respectively. * * @return The program_options object itself for repeatedly function calls * * @since 1.0 */ reversible_program_options& add_costs_option(); /** * @brief Returns the RevLib realization input if it was set * * This method can just be called after the option * was added with add_read_realization_option() and * good() evaluated to true. * * @return The filename set via the command line * * @since 1.0 */ const std::string& read_realization_filename() const; /** * @brief Returns the RevLib specification input if it was set * * This method can just be called after the option * was added with add_read_specification_option() and * good() evaluated to true. * * @return The filename set via the command line * * @since 1.0 */ const std::string& read_specification_filename() const; /** * @brief Returns the RevLib realization output if it was set * * This method can just be called after the option * was added with add_write_realization_option() and * is_write_realization_filename_set() evaluated to true. * * @return The filename set via the command line * * @since 1.0 */ const std::string& write_realization_filename() const; /** * @brief Checks whether a filename for RevLib realization output was set * * This method evaluates to true, when add_write_realization_option was * called before and --realname was set via the command line. * * @return True, if a realname was specified, otherwise false. * * @since 1.0 */ bool is_write_realization_filename_set() const; /** * @brief Returns a cost function * * Use this method together with add_costs_option() only. * When adding that method, costs are ensured to be selected (e.g. the default ones). * Then this method can create a corresponding cost function. * * @return A cost function depending on the costs option * * @since 1.0 */ cost_function costs() const; private: class priv; priv* const d; }; } #endif // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
41fe119d41ff6af4442fecc10f9270af5b54e96a
875ac20866cdbb9937ddff7686f2d59c56eb8a94
/include/callable_traits/detail/function_object.hpp
17291a2c216fd832671b4f2704399ce5d7c3de1c
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hersoncr/callable_traits
cb779fe4e73eba5db329d3dd72a307a353726ca7
9e7e288417e2a42710a82b10380eec0c3ac19fcb
refs/heads/master
2020-12-31T02:01:37.717866
2016-04-02T01:58:28
2016-04-02T01:58:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,176
hpp
function_object.hpp
/*! @file @copyright Barrett Adair 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef CALLABLE_TRAITS_DETAIL_FUNCTION_OBJECT_HPP #define CALLABLE_TRAITS_DETAIL_FUNCTION_OBJECT_HPP #include <callable_traits/detail/generalized_class.hpp> #include <callable_traits/detail/pmf.hpp> #include <callable_traits/detail/utility.hpp> #include <tuple> namespace callable_traits { namespace detail { template<typename T> struct has_normal_call_operator { template<typename N, N Value> struct check { check(std::nullptr_t) {} }; template<typename U> static std::int8_t test(check<decltype(&U::operator()), &U::operator()>); template<typename> static std::int16_t test(...); static constexpr bool value = sizeof(test<T>(nullptr)) == sizeof(std::int8_t); }; struct callable_dummy { void operator()() {} }; template<typename T> using default_normal_callable = typename std::conditional< has_normal_call_operator<T>::value, T, callable_dummy >::type; template<typename General> struct ambiguous_function_object { using arg_types = std::tuple<unknown>; using return_type = unknown; using has_varargs = std::false_type; using function_type = unknown(unknown); }; template<typename General> struct function_object : std::conditional< has_normal_call_operator<typename General::type>::value, pmf<decltype(&default_normal_callable<typename General::type>::operator())>, ambiguous_function_object<General> >::type { using base = typename std::conditional< has_normal_call_operator<typename General::type>::value, pmf<decltype(&default_normal_callable<typename General::type>::operator())>, ambiguous_function_object<General> >::type; using type = typename General::original_type; using general_type = typename General::type; static constexpr const bool value = std::is_class<type>::value && !is_integral_constant<type>::value; using is_ambiguous = std::integral_constant<bool, !has_normal_call_operator<general_type>::value>; using traits = function_object; using class_type = invalid_type; using invoke_type = invalid_type; using is_function_object = std::integral_constant<bool, std::is_class<general_type>::value>; using is_member_pointer = std::false_type; using is_member_function_pointer = std::false_type; using is_function_reference = std::false_type; using is_function_pointer = std::false_type; using is_function = std::false_type; using is_function_general = std::false_type; using remove_member_pointer = type; using remove_varargs = invalid_type; using add_varargs = invalid_type; template<typename> using apply_member_pointer = invalid_type; template<typename> using apply_return = invalid_type; using remove_reference = invalid_type; using add_lvalue_reference = invalid_type; using add_rvalue_reference = invalid_type; using add_const = invalid_type; using add_volatile = invalid_type; using add_cv = invalid_type; using remove_const = invalid_type; using remove_volatile = invalid_type; using remove_cv = invalid_type; }; template<typename T, typename U> struct function_object <generalized_class<T U::*> > { static constexpr const bool value = false; using traits = function_object; }; } } #endif
ea7fba9f919766ff90d8de8753d1cdee1b871038
9203098742b294f80bdf45bbfbf5c313e0fdf1f8
/qt-creator-plugin/hemeraprojectnodes.h
25f74aca478b49b7a47b3dee2ff2113400f7b891
[ "Apache-2.0" ]
permissive
hemeraos/hemera-developer-mode-client
44e1faea07d64ba6d706792c0cfaef71610c0494
5f3133c754853a4e1ad3b1d60791c5b38f656e7e
refs/heads/master
2023-03-02T12:00:25.120926
2021-02-11T12:05:30
2021-02-11T12:07:10
338,017,821
2
1
null
null
null
null
UTF-8
C++
false
false
1,351
h
hemeraprojectnodes.h
#ifndef HEMERAPROJECTNODE_H #define HEMERAPROJECTNODE_H #include <projectexplorer/projectnodes.h> namespace Hemera { namespace DeveloperMode { class HaManager; } namespace Internal { class HemeraProjectNode : public ProjectExplorer::ProjectNode { Q_OBJECT friend class HemeraProject; public: HemeraProjectNode(const QString &filename, DeveloperMode::HaManager *manager); virtual bool hasBuildTargets() const; virtual QList<ProjectExplorer::ProjectAction> supportedActions(Node *node) const override; virtual bool canAddSubProject(const QString &proFilePath) const; virtual bool addSubProjects(const QStringList &proFilePaths); virtual bool removeSubProjects(const QStringList &proFilePaths); virtual bool addFiles( const QStringList &filePaths, QStringList *notAdded = 0); virtual bool removeFiles(const QStringList &filePaths, QStringList *notRemoved = 0); virtual bool deleteFiles(const QStringList &filePaths); virtual bool renameFile(const QString &filePath, const QString &newFilePath); virtual QList<ProjectExplorer::RunConfiguration *> runConfigurationsFor(Node *node); private: DeveloperMode::HaManager *m_haManager; }; } // namespace Internal } // namespace Hemera #endif // HEMERAPROJECTNODE_H
0f5b87922063773f3153a83dbaff249301d0e851
89dbd1560f8a5703e7ce2d6ae8dd01cac280172f
/blur_image/main.cpp
73216329e2eb05469678d7b6a9a637a4c8ee0f8b
[]
no_license
caffeine-coder25/blur_image
71ca5630e4d746743313a06c6e9e683473a11d53
4e0ef1357bcd01a7d6ef7f627738b433a0de502a
refs/heads/main
2023-03-01T12:09:53.944337
2021-02-05T12:32:01
2021-02-05T12:32:01
336,264,410
0
0
null
null
null
null
UTF-8
C++
false
false
964
cpp
main.cpp
// // main.cpp // blur_image // // Created by shubham saxena on 05/02/21. // #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat image = imread("/Users/caffeine_coder25/Desktop/just_code_it/coders_packet_internship/blur_image/rose.jpg"); if (image.empty()) { cout << "Could not open or find the image" << endl; cin.get(); return -1; } Mat image_blurred_with_99x99_kernel; blur(image, image_blurred_with_99x99_kernel, Size(99, 99)); String window_name = "The Rose"; String window_name_blurred_with_99x99_kernel = "The Rose Blurred with 99 x 99 Kernel"; namedWindow(window_name); namedWindow(window_name_blurred_with_99x99_kernel); imshow(window_name, image); imshow(window_name_blurred_with_99x99_kernel, image_blurred_with_99x99_kernel); waitKey(0); destroyAllWindows(); return 0; }
d7d1a926e10244c945869444d7c776c9489cb56d
df5c61d5939a32986fd52a04e74f2198761016cf
/biliFansESP/biliFansESP.ino
0b84b9399a7c8394d5b789ca8136ad0232ebd797
[ "Unlicense" ]
permissive
errere/WuLiao_de_Arduino
5eb4ecdd122e478eb08d14ef4cb98348e5d818da
55963e640daffb53e61dbaae2bd9716058ab7f73
refs/heads/master
2022-11-25T10:45:55.759103
2020-08-04T15:50:30
2020-08-04T15:50:30
285,026,525
1
0
null
null
null
null
UTF-8
C++
false
false
2,140
ino
biliFansESP.ino
#include <WiFi.h> #include <HTTPClient.h> #include <ArduinoJson.h> const char *ssid = "HONOR_9X"; const char *password = "1234567890"; const char APIAdress[] = "http://api.bilibili.com/x/relation/stat?vmid=94898339&jsonp=jsonp"; HTTPClient http; void setup() { Serial.begin(115200); // put your setup code here, to run once: Serial.println("Connecting..."); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void loop() { // put your main code here, to run repeatedly: http.begin(APIAdress); //HTTPhttps://www.arduino.cn/thread-86568-1-1.html //http.begin("http://123.56.221.173/index.html"); //HTTPhttps://www.arduino.cn/thread-86568-1-1.html Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error if (httpCode > 0) { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server if (httpCode == HTTP_CODE_OK) { String payload = http.getString(); StaticJsonDocument<300> jsonBuffer; deserializeJson(jsonBuffer, payload); JsonObject object = jsonBuffer.as<JsonObject>(); String DataJson = object["data"].as<String>(); StaticJsonDocument<200> jsonBufferData; deserializeJson(jsonBufferData, DataJson); JsonObject objectData = jsonBufferData.as<JsonObject>(); Serial.println(objectData["follower"].as<long>()); //Serial.println(payload); } } else { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } http.end(); delay(10000); }
0d481046cc63214b812076b803405aa3d5588ba5
7e4b1e0cac67cb1de8ac8b258b7b0a917c816a17
/lobatto.hpp
2380d373dbcf9ba578c95ecdbf298a81f4541108
[]
no_license
eluator/dipvlom
d0009bf3ce60540ed2db4b8f340f187f4d2acf84
39f9eabc500bac30e62bd7dfffd6d5c971d8765d
refs/heads/master
2022-01-06T08:50:09.492504
2019-05-18T15:04:01
2019-05-18T15:04:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,698
hpp
lobatto.hpp
#include<array> #include<algorithm> #include<cmath> #include<limits> #include<type_traits> template<class Vector,int N=4> class Lobatto3a { using vector_t = std::array<long double,N>; using matrix_t = std::array<vector_t,N>; using ks_t = std::array<Vector,N>; vector_t a,sigma; matrix_t b; typename Vector::value_type epsilon; long double diffnorm(const ks_t& k1,ks_t& k2) { vector_t r; for(unsigned int i=0;i<k1.size();i++) { k2[i]+=-1*k1[i]; r[i]=~k2[i]; } long double res=*std::max_element(r.begin(),r.end())/norm(k1); return res; } long double norm(const ks_t& k) { long double r=0,t; for(auto x:k) { t=~x; if(t>r) r=t; } return r; } public: Lobatto3a() { if constexpr (N==2) { a={0.0L, 1.0L}; sigma={1.0L/2.0L, 1.0L/2.0L}; b[0].fill(0.0L); b[1]=sigma; } else if constexpr (N==3) { a={0.0L, 1.0L/2.0L, 1.0L}; sigma={1.0L/6.0L, 2.0L/3.0L, 1.0L/6.0L}; b[0].fill(0.0L); b[1]={5.0L/24.0L, 1.0/3.0L, -1.0L/24.0L}; b[2]=sigma; } else if constexpr (N==4) { a={0.0L, (5.0L-sqrt(5.0L))/10.0L, (5.0L+sqrt(5.0L))/10.0L, 1.0L}; sigma={1.0L/12.0L, 5.0L/12.0L, 5.0L/12.0L, 1.0L/12.0L}; b[0].fill(0.0L); b[1]={(11.0L+sqrt(5.0L))/120.0L, (25.0L-sqrt(5.0L))/120.0L, (25.0L-13.0L*sqrt(5.0L))/120.0L, (-1.0L+sqrt(5.0L))/120.0L}; b[2]={(11.0L-sqrt(5.0L))/120.0L, (25.0L+13.0L*sqrt(5.0L))/120.0L, (25.0L+sqrt(5.0L))/120.0L, (-1.0L-sqrt(5.0L))/120.0L}; b[3]=sigma; } else if constexpr (N==5) { a={0.0L, (7.0L-sqrt(21.0L))/14, 1.0L/2.0L, (7+sqrt(21.0L))/14.0L, 1.0L}; sigma={1.0L/20.0L, 49.0L/180.0L, 16.0L/45.0L, 49.0L/180.0L, 1.0L/20.0L}; b[0].fill(0.0L); b[1]={(119.0L+3.0L*sqrt(21.0L))/1960.0L, (343.0L-9.0L*sqrt(21.0L))/2520.0L, (392.0L-96.0L*sqrt(21.0L))/2205, (343.0L-69.0L*sqrt(21.0L))/2520.0L, (-21.0L+3.0L*sqrt(21.0L))/1960.0L}; b[2]={13.0L/320.0L, (392.0L+105.0L*sqrt(21.0L))/2880.0L, 8.0L/45.0L, (392.0L-105*sqrt(21.0L))/2880.0L, 3.0L/320.0L}; b[3]={(119.0L-3.0L*sqrt(21.0L))/1960.0L, (343.0L+69.0L*sqrt(21.0L))/2520.0L, (392.0L+96.0L*sqrt(21.0L))/2205.0L, (343.0L+9.0L*sqrt(21.0L))/2520.0L, -(21.0L+3.0L*sqrt(21.0L))/1960.0L}; b[4]=sigma; } else if constexpr (N==6) { a={0.0L,1.1747233803526765357449851302033093e-1L,3.5738424175967745184292450297956046e-1L,6.4261575824032254815707549702043954e-1L,8.8252766196473234642550148697966908e-1L,1.0L}; sigma={3.3333333333333333333333333333333333e-2L,1.8923747814892349015830640410601233e-1L,2.7742918851774317650836026256065434e-1L,2.7742918851774317650836026256065434e-1L,1.8923747814892349015830640410601233e-1L,3.3333333333333333333333333333333333e-2L}; b[0].fill(0.0L); b[1]={4.5679805133755038575653446730922972e-2L,8.1867817008970666864969819153683861e-2L,-1.487460578908983676559396150555719e-2L,7.6276761182509598020429585787853333e-3L,-4.4717804405737092705509645159422079e-3L,1.6434260039545343679772145784381566e-3L}; b[2]={2.5908385387879822499353401700632774e-2L,2.1384080863282571965204027280905642e-1L,1.3396073565086083664894428137964585e-1L,-2.4004074733154873937276256033001734e-2L,1.1807696377659694346907243344183639e-2L,-4.1293095563937473670444402209564835e-3L}; b[3]={3.746264288972708070037777355428982e-2L,1.7742978177126379581139916076182869e-1L,3.0143326325089805044563651859365607e-1L,1.4346845286688233985941598118100849e-1L,-2.460333048390222949373386870304409e-2L,7.4249479454535108339799316327005587e-3L}; b[4]={3.1689907329378798965356118754895177e-2L,1.9370925858949719942885736862195453e-1L,2.6980151239949221670631730398186901e-1L,2.9230379430683301327395422406621153e-1L,1.0736966113995282329333658495232847e-1L,-1.2346471800421705242320113397589639e-2L}; b[5]=sigma; } else if constexpr (N==7) { a={0.0L,8.488805186071653506398389301626743e-2L,2.6557560326464289309811405904561684e-1L,5.0e-1L,7.3442439673535710690188594095438317e-1L,9.1511194813928346493601610698373257e-1L,1.0L}; sigma={2.3809523809523809523809523809523809e-2L,1.3841302368078297400535020314503315e-1L,2.1587269060493131170893551114068114e-1L,2.4380952380952380952380952380952381e-1L,2.1587269060493131170893551114068114e-1L,1.3841302368078297400535020314503315e-1L,2.3809523809523809523809523809523809e-2L}; b[0].fill(0.0L); b[1]={3.2846264328292647881547377380331421e-2L,5.9322894027551404504198527596713417e-2L,-1.0768594451189267105573388916275431e-2L,5.5975917805697772306731264515785011e-3L,-3.488929970807462766480046045821455e-3L,2.2170965889145396997313080577989019e-3L,-8.3827044261510438011301150805792508e-4L}; b[2]={1.8002223201815165703973460160284566e-2L,1.5770113064168904204778906247437054e-1L,1.0235481204686191521394666173809335e-1L,-1.8478259273459043983140512247516131e-2L,9.5775801007414059542896765174719021e-3L,-5.6818645662243775729731799680753607e-3L,2.0999811132187857342288903709879644e-3L}; b[3]={2.7529761904761904761904761904761902e-2L,1.2778825555983746958666847435455748e-1L,2.3748565272164544351033623662864482e-1L,1.2190476190476190476190476190476191e-1L,-2.1612962116714131801400725487963681e-2L,1.0624768120945504418681728790475672e-2L,-3.7202380952380952380952380952380952e-3L}; b[4]={2.1709542696305023789580633438535843e-2L,1.4409488824700735157832338311310851e-1L,2.0629511050418990575464583462320924e-1L,2.6228778308298285350695003605703994e-1L,1.1351787855806939649498884940258779e-1L,-1.9288106960906068042438859329337396e-2L,5.8073006077086438198360636492392419e-3L}; b[5]={2.4647794252138913903922535317581733e-2L,1.3619592709186843430561889508723425e-1L,2.1936162057573877447541555718650259e-1L,2.3821193202895403229313639735794531e-1L,2.2664128505612057881450890005695657e-1L,7.909012965323156950115167554831973e-2L,-9.0367405187688383577378535708076123e-3L}; b[6]=sigma; } // else if constexpr (N==8) // { // a={}; // sigma={}; // b[0].fill(0.0L); // b[1]={}; // b[2]={}; // b[3]={}; // b[4]={}; // b[5]={}; // b[6]={}; // b[7]=sigma; // } else static_assert(true,"That N is not allowed."); epsilon=10*std::numeric_limits<typename Vector::value_type>::epsilon(); //1e-18; } template<class RHS> Vector do_step(const Vector& y,RHS rhs,const long double& t,const long double& dt) { ks_t k{}; k.fill(Vector()); ks_t k_prev=k; k_prev[0][0]++; //set initial difference to allow next cycle while(diffnorm(k,k_prev)>epsilon) { k_prev=k; for(unsigned int i=1;i<N;i++) { auto v=b[i][0]*k[0]; for(unsigned int o=1;o<N;o++) v+=b[i][o]*k[o]; v=dt*v; v+=y; rhs(v,k[i],t+a[i]*dt); } } auto v=sigma[0]*k[0]; for(unsigned int i=1;i<N;i++) v+=sigma[i]*k[i]; v=dt*v; v+=y; return v; } };
463aa9d3320e1b020537817749acb81d4d8b5297
47ddd7437347c4853f60863d58779c6b14e3b012
/Proyecto1/Flower.h
298024ab70ecb7be4abb0f47dbb54fe0937c732f
[]
no_license
ndiaz9/CVI_Proyecto1
d84ed6c7de8f4ae9bec4c57b6575e6c46d79e5eb
1b02ca9ed1a2fd792aa257dbb219b03ef13feae1
refs/heads/main
2023-03-11T06:53:04.722104
2021-02-28T02:06:07
2021-02-28T02:06:07
337,946,725
0
0
null
null
null
null
UTF-8
C++
false
false
1,705
h
Flower.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Flower.generated.h" UCLASS() class PROYECTO1_API AFlower : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AFlower(); UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMesh* cylinderMesh; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMesh* sphereMesh; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMesh* coneMesh; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* Flower; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* base1; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* base2; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* stem; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* core; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* petal1; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* petal2; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* petal3; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* petal4; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* petal5; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) UStaticMeshComponent* petal6; class UMaterial* color1; class UMaterial* color2; class UMaterial* color3; class UMaterial* color4; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; };
cee1bccf96b4b4c95b0f3720b645e74fc1184e6a
b602bcfe7629fa0bbd53d7136a71ea115a37eba0
/hittable.hxx
cd5f33ae488b169750e36a2793e622fa9448a7ee
[]
no_license
bunbun205/basicRayTracer
b3043066773f2e000e106344b532c5412fe3fca6
67718ec5c1a68d8aa0e7ef7414e3be33bd36b2c9
refs/heads/master
2023-08-01T14:22:27.523722
2021-09-12T15:05:03
2021-09-12T15:05:03
405,673,114
0
0
null
null
null
null
UTF-8
C++
false
false
484
hxx
hittable.hxx
#pragma once #include "ray.hxx" struct hitRecord { point3 p; vec3 normal; double t; bool frontFace; inline void setFaceNormal(const ray &r, const vec3 &outwardNormal) { frontFace = dot(r.direction(), outwardNormal) < 0; normal = frontFace ? outwardNormal : -outwardNormal; } }; class hittable { public: virtual bool hit(const ray &r, double tMin, double tMax, hitRecord &rec) const = 0; };
b505e3f81377c5d90d50b79e26be4a1a19cc3564
64a59d609c6302d71e89df473798906d1fd9d6a5
/src/FinchI/potential_field/src/potential_field.cpp
5dc4137936adb28713bbeb7cf8b141580e0640b1
[]
no_license
ianwfinch/catkin_ws
48eb62b09a381517a962831308690962b75ddf87
f1c24b2d7d0283943741ef82bca5cfff9adea618
refs/heads/master
2020-03-30T14:10:53.639210
2018-10-30T17:00:19
2018-10-30T17:00:19
151,304,731
0
0
null
null
null
null
UTF-8
C++
false
false
6,856
cpp
potential_field.cpp
#include "ros/ros.h" #include "nav_msgs/Odometry.h" #include "geometry_msgs/Twist.h" #include "sensor_msgs/LaserScan.h" #include <vector> #include <cstdlib> // Needed for rand() #include <ctime> // Needed to seed random number generator with a time value #include <LinearMath/btQuaternion.h> // Needed to convert rotation ... #include <LinearMath/btMatrix3x3.h> // ... quaternion into Euler angles struct Pose { double x; // in simulated Stage units double y; // in simulated Stage units double heading; // in radians ros::Time t; // last received time // Construct a default pose object with the time set to 1970-01-01 Pose() : x(0), y(0), heading(0), t(0.0) {}; // Process incoming pose message for current robot void poseCallback(const nav_msgs::Odometry::ConstPtr& msg) { double roll, pitch; x = msg->pose.pose.position.x; y = msg->pose.pose.position.y; btQuaternion q = btQuaternion(msg->pose.pose.orientation.x, \ msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, \ msg->pose.pose.orientation.w); btMatrix3x3(q).getRPY(roll, pitch, heading); t = msg->header.stamp; }; }; class PotFieldBot { public: // Construst a new Potential Field controller object and hook up // this ROS node to the simulated robot's pose, velocity control, // and laser topics PotFieldBot(ros::NodeHandle& nh, int robotID, int n, \ double gx, double gy) : ID(robotID), numRobots(n), \ goalX(gx), goalY(gy) { // Initialize random time generator srand(time(NULL)); // Advertise a new publisher for the current simulated robot's // velocity command topic (the second argument indicates that // if multiple command messages are in the queue to be sent, // only the last command will be sent) commandPub = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1); // Subscribe to the current simulated robot's laser scan topic and // tell ROS to call this->laserCallback() whenever a new message // is published on that topic laserSub = nh.subscribe("base_scan", 1, \ &PotFieldBot::laserCallback, this); // Subscribe to each robot' ground truth pose topic // and tell ROS to call pose->poseCallback(...) whenever a new // message is published on that topic for (int i = 0; i < numRobots; i++) { pose.push_back(Pose()); } for (int i = 0; i < numRobots; i++) { poseSubs.push_back(nh.subscribe("/robot_" + \ boost::lexical_cast<std::string>(i) + \ "/base_pose_ground_truth", 1, \ &Pose::poseCallback, &pose[i])); } }; // Send a velocity command void move(double linearVelMPS, double angularVelRadPS) { geometry_msgs::Twist msg; // The default constructor will set all commands to 0 msg.linear.x = linearVelMPS; msg.angular.z = angularVelRadPS; commandPub.publish(msg); }; // Process incoming laser scan message void laserCallback(const sensor_msgs::LaserScan::ConstPtr& msg) { // TODO: parse laser data // (see http://www.ros.org/doc/api/sensor_msgs/html/msg/LaserScan.html) //code from //http://wiki.ros.org/laser_pipeline/Tutorials/IntroductionToWorkingWithLaserScannerData laser_geometry::LaserProjection projector; tf:TransformListener listener; sensor_msgs::PointCloud cloud; try { projector.transformLaserScanToPointCloud("base_link",*scan_in, cloud, listener); } catch (tf::TransformException& else) { std::cout << e.hmmm(); return } scan_pub_.publish(cloud); }; // Main FSM loop for ensuring that ROS messages are // processed in a timely manner, and also for sending // velocity controls to the simulated robot based on the FSM state void spin() { ros::Rate rate(30); // Specify the FSM loop rate in Hz while (ros::ok()) { // Keep spinning loop until user presses Ctrl+C // TODO: remove demo code, compute potential function, actuate robot //user defined double myGamma = 1; //user defined all in meters double myAlpha = 1; // double myBeta = 4; // double myEpsilon = 0.05; // double dsafe = 0.5; //minimum distance that is safe //temporary function length until i find out what it is //also change Fattr and Frepuls to arrays double[] Fattr [numRobots]; double[] Frepuls [numRobots]; double[] Ftotal [numRobots]; /* for(int i = 0; i < numRobots; i++) { Fattrx[i] = myGamma*(goalX - pose[i].x) //Fattry[i] = myGamma*(goalY - pose[i].y) if (di < dsafe) Frepuls[i] = myAlpha/((di-dsafe)^2); //di is perceived sensor ping TODO } else if (di > dsafe + myAlpha && di < myBeta) { Frepuls[i] = myAlpha/(myGamma^2); } else { Frepuls[i] = 0; } Ftotal[i] = Fattr[i]; } */ //vector summation Demo code: print each robot's pose for (int i = 0; i < numRobots; i++) { std::cout << std::endl; std::cout << i << " "; std::cout << "Pose: " << pose[i].x << ", " << pose[i].y << ", " << pose[i].heading << std::endl; } ros::spinOnce(); // Need to call this function often to allow ROS to process incoming messages rate.sleep(); // Sleep for the rest of the cycle, to enforce the FSM loop rate } }; // Tunable motion controller parameters const static double FORWARD_SPEED_MPS = 2.0; const static double ROTATE_SPEED_RADPS = M_PI/2; protected: ros::Publisher commandPub; // Publisher to the current robot's velocity command topic ros::Subscriber laserSub; // Subscriber to the current robot's laser scan topic std::vector<ros::Subscriber> poseSubs; // List of subscribers to all robots' pose topics std::vector<Pose> pose; // List of pose objects for all robots int ID; // 0-indexed robot ID int numRobots; // Number of robots, positive value double goalX, goalY; // Coordinates of goal }; int main(int argc, char **argv) { int robotID = -1, numRobots = 0; double goalX, goalY; bool printUsage = false; // Parse and validate input arguments if (argc <= 4) { printUsage = true; } else { try { robotID = boost::lexical_cast<int>(argv[1]); numRobots = boost::lexical_cast<int>(argv[2]); goalX = boost::lexical_cast<double>(argv[3]); goalY = boost::lexical_cast<double>(argv[4]); if (robotID < 0) { printUsage = true; } if (numRobots <= 0) { printUsage = true; } } catch (std::exception err) { printUsage = true; } } if (printUsage) { std::cout << "Usage: " << argv[0] << " [ROBOT_NUM_ID] [NUM_ROBOTS] [GOAL_X] [GOAL_Y]" << std::endl; return EXIT_FAILURE; } ros::init(argc, argv, "potfieldbot_" + std::string(argv[1])); // Initiate ROS node ros::NodeHandle n("robot_" + std::string(argv[1])); // Create named handle "robot_#" PotFieldBot robbie(n, robotID, numRobots, goalX, goalY); // Create new random walk object robbie.spin(); // Execute FSM loop return EXIT_SUCCESS; };
a1ba9650d0b0a4f707a5f03234a3336db4e477b8
2b31b6a58a6677f23422a07b9aebbc0ae89e8cb0
/libvis/src/libvis/render_window_qt_opengl.h
9eff672173ca5613b6102f55ddee44ea9f0bb88e
[ "BSD-3-Clause" ]
permissive
SnowCarter/surfelmeshing
eef27c8d8797432f0706502e8507e45adee7323b
5b1c8d160c1d64f5144b58309b725812d8e6e3ab
refs/heads/master
2020-04-03T06:25:35.202401
2018-10-02T12:31:55
2018-10-02T12:31:55
155,074,298
1
0
BSD-3-Clause
2018-10-28T13:30:43
2018-10-28T13:30:42
null
UTF-8
C++
false
false
2,974
h
render_window_qt_opengl.h
// Copyright 2018 ETH Zürich, Thomas Schöps // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include "libvis/opengl.h" #include <QGLWidget> #include <QInputEvent> #include "libvis/libvis.h" #include "libvis/render_window_qt.h" namespace vis { class RenderWidgetOpenGL : public QGLWidget { Q_OBJECT public: RenderWidgetOpenGL(const QGLFormat& format, const shared_ptr<RenderWindowCallbacks>& callbacks); ~RenderWidgetOpenGL(); protected: virtual void initializeGL() override; virtual void paintEvent(QPaintEvent *event) override; virtual void resizeGL(int width, int height) override; virtual void mousePressEvent(QMouseEvent* event) override; virtual void mouseMoveEvent(QMouseEvent* event) override; virtual void mouseReleaseEvent(QMouseEvent* event) override; virtual void wheelEvent(QWheelEvent* event) override; virtual void keyPressEvent(QKeyEvent* event) override; virtual void keyReleaseEvent(QKeyEvent* event) override; shared_ptr<RenderWindowCallbacks> callbacks_; }; // A Qt and OpenGL based render window implementation. class RenderWindowQtOpenGL : public RenderWindowQt { public: RenderWindowQtOpenGL(const std::string& title, int width, int height, const shared_ptr<RenderWindowCallbacks>& callbacks); virtual void RenderFrame() override; virtual void MakeContextCurrent() override; virtual void ReleaseCurrentContext() override; private: // Pointer is managed by Qt. RenderWidgetOpenGL* render_widget_; }; }
01ae9a26aeba818f72f995b457feaee6c1b47e7c
9b38b6b08084ce2f3b45c9c1248e9bfeeab56221
/FIT2096 - Week 4 Base/FIT2049 - Week 4/Game.cpp
640d7a24cb921f46da91e0cce7fb8857b98c65b8
[]
no_license
Billy-Bricknall/FIT2096-A2b
b544d506b55d63fe13fe3d30408bbc6ed5c4b8de
eacd1b54b0b579fb3244f83f211c7f6a6ef05283
refs/heads/master
2021-09-15T06:15:28.482681
2018-05-27T13:53:13
2018-05-27T13:53:13
131,710,604
0
0
null
null
null
null
UTF-8
C++
false
false
12,601
cpp
Game.cpp
/* FIT2049 - Example Code * Game.cpp * Created by Elliott Wilson & Mike Yeates - 2016 - Monash University */ #include "Game.h" #include "TexturedShader.h" #include <iostream> #include "DirectXTK/CommonStates.h" #include <sstream> Game::Game() { m_renderer = NULL; m_currentCam = NULL; m_input = NULL; m_meshManager = NULL; m_textureManager = NULL; m_unlitTexturedShader = NULL; m_unlitVertexColouredShader = NULL; } Game::~Game() {} bool Game::Initialise(Direct3D* renderer, InputController* input, AudioSystem* audio) { m_renderer = renderer; m_input = input; m_audio = audio; m_meshManager = new MeshManager(); m_textureManager = new TextureManager(); m_gConsts = new GameConstants(); if (!InitShaders()) return false; if (!LoadMeshes()) return false; if (!LoadTextures()) return false; if (!LoadAudio()) return false; LoadFonts(); InitUI(); InitGameWorld(); RefreshUI(); m_collisionManager = new CollisionManager(p1, &m_tiles, p1->getGamestate()); m_currentCam = new FirstPersonCamera(p1); return true; } bool Game::InitShaders() { m_unlitVertexColouredShader = new Shader(); if (!m_unlitVertexColouredShader->Initialise(m_renderer->GetDevice(), L"Assets/Shaders/VertexShader.vs", L"Assets/Shaders/VertexColourPixelShader.ps")) return false; m_unlitTexturedShader = new TexturedShader(); if (!m_unlitTexturedShader->Initialise(m_renderer->GetDevice(), L"Assets/Shaders/VertexShader.vs", L"Assets/Shaders/TexturedPixelShader.ps")) return false; return true; } bool Game::LoadMeshes() { if (!m_meshManager->Load(m_renderer, "Assets/Meshes/player_capsule.obj")) return false; if (!m_meshManager->Load(m_renderer, "Assets/Meshes/floor_tile.obj")) return false; if (!m_meshManager->Load(m_renderer, "Assets/Meshes/wall_tile.obj")) return false; if (!m_meshManager->Load(m_renderer, "Assets/Meshes/enemy.obj")) return false; if (!m_meshManager->Load(m_renderer, "Assets/Meshes/bullet.obj")) return false; return true; } bool Game::LoadTextures() { if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_blue.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_disabled.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_green.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_orange.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_orange1.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_purple.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_red.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_red1.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_red_light.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/tile_white.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/ground.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/block_tiles_red.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/gradient_redDarker.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/sprite_healthBar.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/sprite_healthBar1.png")) return false; if (!m_textureManager->Load(m_renderer, "Assets/Textures/bullet.png")) return false; return true; } bool Game::LoadAudio() { if (!m_audio->Load("Assets/Sounds/Pew1.wav")) return false; if (!m_audio->Load("Assets/Sounds/Pew2.wav")) return false; if (!m_audio->Load("Assets/Sounds/Pew3.wav")) return false; if (!m_audio->Load("Assets/Sounds/Pew4.wav")) return false; if (!m_audio->Load("Assets/Sounds/Pew5.wav")) return false; if (!m_audio->Load("Assets/Sounds/Pew6.wav")) return false; if (!m_audio->Load("Assets/Sounds/Health.wav")) return false; if (!m_audio->Load("Assets/Sounds/Teleport.wav")) return false; if (!m_audio->Load("Assets/Sounds/Wilhelm-Scream.mp3")) return false; if (!m_audio->Load("Assets/Sounds/Tunes.wav")) return false; if (!m_audio->Load("Assets/Sounds/Impact1.wav")) return false; if (!m_audio->Load("Assets/Sounds/Impact2.wav")) return false; if (!m_audio->Load("Assets/Sounds/Impact3.wav")) return false; if (!m_audio->Load("Assets/Sounds/Impact4.wav")) return false; return true; } void Game::LoadFonts() { m_arialFont12 = new SpriteFont(m_renderer->GetDevice(), L"Assets/Fonts/Arial-12pt.spritefont"); } void Game::InitUI() { m_spriteBatch = new SpriteBatch(m_renderer->GetDeviceContext()); m_healthBar = m_textureManager->GetTexture("Assets/Textures/sprite_healthBar.png"); m_healthBar1 = m_textureManager->GetTexture("Assets/Textures/sprite_healthBar1.png"); } void Game::RefreshUI() { if (p1){ std::wstringstream ss; ss << p1->getGamestate()->getMonDef().c_str(); m_monsDefeated = ss.str(); } } void Game::InitGameWorld() { m_backgroundMusic = m_audio->Play("Assets/Sounds/Tunes.wav", false); m_backgroundMusic->SetLoopCount(9999999); m_backgroundMusic->SetVolume(m_gConsts->getMusicVol()); generateBoard(); //randomly generates a gameboard p1 = new Player(Vector3(0.0f, 0.0f, 0.0f), m_input, m_gConsts, m_audio); } void Game::Update(float timestep){ m_input->BeginUpdate(); m_audio->Update(); if (!p1->getGamestate()->getGameLose() && !p1->getGamestate()->getGamewin()) { //if game isnt over for (int i = 0; i < m_gConsts->getBoardWidth(); i++) { for (int j = 0; j < m_gConsts->getBoardHeight(); j++) { m_board[i][j]->update(timestep, m_meshManager, p1->GetPosition(), p1->GetYRotation()); //update all tiles } } p1->update(timestep, m_board, m_textureManager, m_meshManager, m_unlitTexturedShader); //update player m_collisionManager->CheckCollisions(); } else { MessageBox(NULL, p1->getGamestate()->getMonDef().c_str(), "GameOver", MB_OK); //gameover box with all mons defeated PostQuitMessage(0); //quits application } RefreshUI(); m_currentCam->Update(timestep); m_input->EndUpdate(); } void Game::Render() { m_renderer->BeginScene(0.2f, 0.2f, 0.2f, 1.0f); // TODO render all gameobjects for (int i = 0; i < m_gConsts->getBoardWidth(); i++) { for (int j = 0; j < m_gConsts->getBoardHeight(); j++) { m_board[i][j]->Render(m_renderer, m_currentCam); //renders board if (m_board[i][j]->getCharMesh()) { m_board[i][j]->getCharMesh()->Render(m_renderer, m_currentCam); //renders character meshes if (m_board[i][j]->getBullet()) { m_board[i][j]->getBullet()->Render(m_renderer, m_currentCam); } } } } for (int i = 0; i < (m_gConsts->getBoardWidth()+1)/2 * (m_gConsts->getBoardHeight()+1)/2; i++) { m_wall[i]->Render(m_renderer, m_currentCam); //renders walls } for (int i = 0; i < p1->getBullet().size(); i++) { p1->getBullet()[i]->Render(m_renderer, m_currentCam); } DrawUI(); m_renderer->EndScene(); } void Game::DrawUI() { // Sprites don't use a shader m_renderer->SetCurrentShader(NULL); CommonStates states(m_renderer->GetDevice()); m_spriteBatch->Begin(SpriteSortMode_Deferred, states.NonPremultiplied()); std::wstringstream ss1; ss1 << "+"; wstring temp1 = ss1.str(); m_arialFont12->DrawString(m_spriteBatch, temp1.c_str(), Vector2(634, 350), Color(0.0f, 0.0f, 0.0f), 0, Vector2(0, 0));//draws a line at the midpoint of the health bar m_arialFont12->DrawString(m_spriteBatch, m_monsDefeated.c_str(), Vector2(0, 100), Color(0.0f, 0.0f, 0.0f), 0, Vector2(0, 0)); //draws the score as in monsters defeated for (int i = 0; i < 10; i++) { m_spriteBatch->Draw(m_healthBar->GetShaderResourceView(), Vector2(479 + 32 * i, 5), Color(1.0f, 1.0f, 1.0f)); //draws health bar background } int health = p1->getCharacter()->getHealth(); for (int i = 0; i < health; i++) { m_spriteBatch->Draw(m_healthBar1->GetShaderResourceView(), Vector2(639 + 3.18 * i, 5), Color(1.0f, 0.0f, 0.0f));//draws current health level m_spriteBatch->Draw(m_healthBar1->GetShaderResourceView(), Vector2(635 - 3.18 * i, 5), Color(1.0f, 0.0f, 0.0f)); } std::wstringstream ss; ss << "|"; wstring temp = ss.str(); m_arialFont12->DrawString(m_spriteBatch, temp.c_str(), Vector2(636, 10), Color(0.0f, 0.0f, 0.0f), 0, Vector2(0, 0));//draws a line at the midpoint of the health bar m_spriteBatch->End(); } void Game::Shutdown() { // TODO delete all gameobjects if (m_currentCam) { delete m_currentCam; m_currentCam = NULL; } if (m_unlitVertexColouredShader) { m_unlitVertexColouredShader->Release(); delete m_unlitVertexColouredShader; m_unlitVertexColouredShader = NULL; } if (m_meshManager) { m_meshManager->Release(); delete m_meshManager; m_meshManager = NULL; } if (m_textureManager) { m_textureManager->Release(); delete m_textureManager; m_textureManager = NULL; } if (m_audio) { m_audio->Shutdown(); delete m_audio; m_audio = NULL; } } void Game::generateBoard() { int numToLink = m_gConsts->getTeleNum(); //number of tiles to link (1 makes a link between 2 tiles) int monNum = m_gConsts->getMonNum(); //number of monsters int healNum = m_gConsts->getHealNum(); //number of heal tiles int height = m_gConsts->getBoardHeight(); int width = m_gConsts->getBoardWidth(); int x; int y; int temp = 0; for (int i = -(width+1)/2; i < 1+(width+1)/2; i++) { //from here... m_wall[temp] = new GameObject(m_meshManager->GetMesh("Assets/Meshes/wall_tile.obj"), m_unlitTexturedShader, Vector3(i, 0, -(width + 1) / 2), m_textureManager->GetTexture("Assets/Textures/ground.png")); m_wall[temp]->Update(NULL); temp++; m_wall[temp] = new GameObject(m_meshManager->GetMesh("Assets/Meshes/wall_tile.obj"), m_unlitTexturedShader, Vector3(i, 0, (width + 1) / 2), m_textureManager->GetTexture("Assets/Textures/ground.png")); m_wall[temp]->Update(NULL); temp++; } for (int i = -(height-1)/2; i < (height + 1) / 2; i++) { m_wall[temp] = new GameObject(m_meshManager->GetMesh("Assets/Meshes/wall_tile.obj"), m_unlitTexturedShader, Vector3(-(height + 1) / 2, 0, i), m_textureManager->GetTexture("Assets/Textures/ground.png")); m_wall[temp]->Update(NULL); temp++; m_wall[temp] = new GameObject(m_meshManager->GetMesh("Assets/Meshes/wall_tile.obj"), m_unlitTexturedShader, Vector3((height + 1) / 2, 0, i), m_textureManager->GetTexture("Assets/Textures/ground.png")); m_wall[temp]->Update(NULL); temp++; } //...to here spawns walls for (int i = -(width - 1) / 2; i < (width + 1) / 2; i++) { for (int j = -(height - 1) / 2; j < (height + 1) / 2; j++) { //following creates blank slate m_board[i+(width-1)/2][j+(height-1)/2] = new Tile(i, j, m_meshManager->GetMesh("Assets/Meshes/floor_tile.obj"), m_unlitTexturedShader, Vector3(i, 0, j), m_textureManager->GetTexture("Assets/Textures/tile_white.png"), m_gConsts, m_textureManager, m_audio); //string can be blank, mon1-5, tele, heal m_tiles.push_back(m_board[i + (width - 1) / 2][j + (height - 1) / 2]); } } do { // the rest randomly generates which tiles are where do { x = rand() % width; y = rand() % height; } while (m_board[x][y]->getActive() == false || m_board[x][y]->getType() != "blank" || (x == (width-1)/2 && y == (height-1)/2)); // if tile hasnt been selected yet if (numToLink > 0) { int linkX, linkY; m_board[x][y]->setType("tele", NULL); //sets type do { linkX = rand() % width; linkY = rand() % height; } while (m_board[linkX][linkY]->getActive() == false || m_board[linkX][linkY]->getType() != "blank" || (x == (width - 1) / 2 && y == (width - 1) / 2)); //if tile hasnt been selected yet m_board[linkX][linkY]->setType("tele", NULL); //sets type m_board[linkX][linkY]->linkTile(m_board[x][y]); //links tile m_board[x][y]->linkTile(m_board[linkX][linkY]); //links tile numToLink--; } else if (monNum > 0) { Character* tempMon; m_board[x][y]->setType("mon", m_meshManager); //sets type if (monNum == 1) { tempMon = new Character("mon1", 10); } //makes first mon else if (monNum == 2) { tempMon = new Character("mon2", 20); } else if (monNum == 3) { tempMon = new Character("mon3", 30); } else if (monNum == 4) { tempMon = new Character("mon4", 40); } else if (monNum == 5) { tempMon = new Character("mon5", 50); } else { tempMon = NULL; } m_board[x][y]->setEnemy(tempMon); monNum--; } else if (healNum > 0) { m_board[x][y]->setType("heal", m_meshManager); //sets type healNum--; } } while (numToLink > 0 || monNum > 0 || healNum > 0); }
a4ffd8020900244539fc70af17574843c3ab4b5e
6f6f5093effaef2f991ed8fbe087e1680eec7bd2
/src/automaton/core/smartproto/smart_protocol.h
24fff9bed92c7e3cd8be2d229811b7fcfe9593eb
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
sept-en/automaton
1006d35d711315fc304a4bf304284061864bdca9
b7448dfe578cf52df37ec7c86536d1e51017c548
refs/heads/master
2021-04-12T15:18:48.886428
2020-03-22T00:49:28
2020-03-22T00:49:28
249,087,538
0
0
MIT
2020-03-22T00:48:51
2020-03-22T00:48:51
null
UTF-8
C++
false
false
2,100
h
smart_protocol.h
#ifndef AUTOMATON_CORE_SMARTPROTO_SMART_PROTOCOL_H_ #define AUTOMATON_CORE_SMARTPROTO_SMART_PROTOCOL_H_ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "automaton/core/data/factory.h" #include "automaton/core/data/schema.h" namespace automaton { namespace core { namespace smartproto { class smart_protocol { public: struct cmd { std::string name; std::string input_type; std::string output_type; cmd(const std::string& nm, const std::string& input, const std::string& output): name(nm), input_type(input), output_type(output) {} }; static std::shared_ptr<smart_protocol> get_protocol(const std::string& proto_id); static std::vector<std::string> list_protocols(); static bool load(const std::string& id, const std::string& path); ~smart_protocol(); std::shared_ptr<data::factory> get_factory(); std::unordered_map<std::string, std::string> get_msgs_definitions(); std::vector<data::schema*> get_schemas(); std::unordered_map<std::string, std::string> get_files(std::string files_type); std::vector<std::string> get_wire_msgs(); std::vector<std::string> get_commands(); std::string get_configuration_file(); uint32_t get_update_time_slice(); int32_t get_wire_from_factory(int32_t); int32_t get_factory_from_wire(int32_t); private: smart_protocol(); static std::unordered_map<std::string, std::shared_ptr<smart_protocol>> protocols; std::string id; std::shared_ptr<data::factory> factory; uint32_t update_time_slice; // files_type -> [file_name -> file] std::unordered_map<std::string, std::unordered_map<std::string, std::string> > files; std::unordered_map<std::string, std::string> msgs_defs; std::vector<data::schema*> schemas; std::vector<std::string> wire_msgs; std::vector<cmd> commands; std::string config_json; std::unordered_map<int32_t, int32_t> wire_to_factory; std::unordered_map<int32_t, int32_t> factory_to_wire; }; } // namespace smartproto } // namespace core } // namespace automaton #endif // AUTOMATON_CORE_SMARTPROTO_SMART_PROTOCOL_H_
dcbccfe769ec1574c23ca4de639087e7d1276101
a1b67e600f66f8c6c306b2179e5e9b908359c42f
/chapter7/examples/7_1.cpp
d8c36727388d6a62ba7baabbd73d2f6665445fb1
[]
no_license
Shreevathsa99/cpp-programs
56041753ee4236cb8ba896d43da649ee78576912
8ec6b2a7b7ecb7e61c33a08c8b277887ecdef0ea
refs/heads/master
2020-04-17T11:26:18.030415
2019-04-20T15:11:18
2019-04-20T15:11:18
166,540,739
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
7_1.cpp
/* Test for open and close errors. * Written by: Shreevathsa. * Date: 19/01/2019. */ #include<iostream> #include<fstream> #include<cstdlib> using namespace std; int main(){ cout << "Start open/close error test\n"; ifstream fsDailyTemps; fsDailyTemps.open("ch7TEMPS.DAT"); if(!fsDailyTemps){ cout << "\aError 100 opening ch7TEMPS.DAT\n"; exit(100); } fsDailyTemps.close(); if(fsDailyTemps.fail()){ cerr << "\aError 102 closing ch7TEMPS.DAT\n"; exit(102); } cout << "End open/close error test\n"; return 0; }
9c27f9f11eb5678c7ea7b885d55bec11f1bd0a17
ca5d37bfe3a9ed372c6f9b2d0057bc07ee7b79d8
/prio4/Main.cpp
e8956a7ede6751924d583687514461a5e5fa83e5
[]
no_license
chenubal/Scratch1
1f1d07e5b2f405e329a99b6442de5101fda2aaea
7f474bbafd11c990eb72e98e4c8140460d06769b
refs/heads/master
2023-08-07T10:40:40.111700
2023-01-01T14:24:03
2023-01-01T14:24:03
95,187,982
0
0
null
null
null
null
UTF-8
C++
false
false
1,187
cpp
Main.cpp
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <tuple> struct Cmd { Cmd( const char* c) : cmd(c) {} Cmd(std::string const&c) : cmd(c) {} Cmd(std::string &&c) : cmd(std::move(c)) {} std::string cmd; void operator()(int p) const { std::cout << "run " << cmd << "(" << p << ")\n"; } }; bool operator<(Cmd const& pc1, Cmd const& pc2) { return pc1.cmd < pc2.cmd; }; using PrioCmd = std::pair< int, Cmd>; using Commands = std::vector <PrioCmd>; void addCommand(Commands & V, int prio, Cmd const& c) { V.emplace_back(prio, c); std::push_heap(V.begin(), V.end()); } void process(Commands & V) { while (!V.empty()) { auto& p = V.front(); p.second(p.first); std::pop_heap(V.begin(), V.end()); // move front -> back V.pop_back(); } } int main() { std::cout << "Priority(E) with heap: -------------------------------------------\n"; Commands V = { {-100, "A"},{ 200, "B"},{ 200, "C"}}; V.emplace_back(-200, "D"); std::make_heap(V.begin(), V.end()); addCommand (V, 0, "X"); process(V); // + multiple container (with random access iterator) // + multiple keys // + no expensive sort // - no simple add/remove => error prone }
0ac2200840043c377a00f2035d1e820a6a42d495
1334014eaeffdde4886da49ce5f387c46a5cc23a
/2021-1/baekjoon/2644_촌수계산.cpp
d3c41bbead4dcd14c881390686ecaf274364016c
[]
no_license
gusah009/Algorithm
a85b1a4526a885b1f809c23c55565f453a5294c4
5da952e16a6f90f663706675812f042707aa7280
refs/heads/main
2023-07-31T17:28:20.404630
2021-09-05T06:14:00
2021-09-05T06:14:00
357,753,076
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
2644_촌수계산.cpp
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> #include <vector> #define FOR(i, j) for(int i = 0; i < j; i++) using namespace std; int N; int x, y; int M; vector<int> EDGE[101]; int answer = -1; void DFS(int v, int prev_v, int depth) { if (v == y) { answer = depth; return; } FOR(i, EDGE[v].size()) { if (EDGE[v][i] == prev_v) continue; if (answer != -1) return; DFS(EDGE[v][i], v, depth + 1); } return; } int main() { cin >> N; cin >> x >> y; cin >> M; FOR(m, M) { int v1, v2; cin >> v1 >> v2; EDGE[v1].push_back(v2); EDGE[v2].push_back(v1); } FOR(i, EDGE[x].size()) { DFS(EDGE[x][i], x, 1); } // FOR(i, EDGE[y].size()) { // DFS(EDGE[y][i], y, 1); // } cout << answer << '\n'; return 0; }
312db1f00f522b06148c46c912d4915144ef78ed
2a73aed02d013defdaeaccb27b494c4b1e9fa943
/Control_Suhu_Ruangan.ino
462ce8bfc7f03f015e1bb122da46232b0ffe3ab0
[]
no_license
Ulfisri/Proyek-Arduino-Control-Sensor-Suhu-pada-Ruangan-
390bb24524249824734c2ca48e9ea953153bbd1e
24855e448c998c960e0efd14237cfee91d432cf5
refs/heads/main
2023-05-21T21:26:54.155491
2021-06-10T14:28:47
2021-06-10T14:28:47
375,724,549
0
0
null
null
null
null
UTF-8
C++
false
false
1,001
ino
Control_Suhu_Ruangan.ino
#include <DHT.h> #include <DHT_U.h> #include <Adafruit_Sensor.h> #define DHTPIN 2 // pin yang digunakan untuk input data dari sensor dht 11 #define DHTTYPE DHT11 // kalian bisa mengganti DHT11 dengan DHT 22 /DHT 21 tergantung sensor yang kalian gunakan DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); Serial.println("DHTxx test!"); dht.begin(); } void loop() { delay(2000); float h = dht.readHumidity(); float t = dht.readTemperature(); // baca temperatur dalam celcius, jika ingin mengganti fahrenheit kalian bisa menggunakan float f = dht.readTemperature(true); // cek apakah koneksi benar, jika salah print error if (isnan(h) || isnan(t)) { Serial.println("Failed to read from DHT sensor!"); return; } Serial.print("Kelembapan: "); Serial.print(h); // menampilkan kelembapan di serial monitor Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); // menampilkan temperatur di serial monitor Serial.println(" *C "); }
68ac9f2cfee3f45868988ede146ec51ab60d9bf7
e173e8fd6d50f0c3191c9395a8c342516f651ebd
/include/Tools/Algo/PRNG/PRNG_MT19937_simd.hpp
eb94d083f1fea984bb000a49e4be610f1e8cf107
[ "MIT" ]
permissive
aff3ct/aff3ct
e11e0ac440b96849f73348dc6fb4a15611f807ec
8fa65a3ca9b0dcdd3d544363bc692d4f85f6f718
refs/heads/master
2023-07-19T06:59:41.908384
2022-04-21T08:34:08
2022-04-21T08:34:08
60,615,913
417
150
MIT
2022-09-14T11:09:54
2016-06-07T13:37:47
C++
UTF-8
C++
false
false
2,150
hpp
PRNG_MT19937_simd.hpp
/*! * \file * \brief The Mersenne Twister pseudo-random number generator (PRNG) with fast SIMD instructions. * * This is an implementation of fast PRNG called MT19937, * meaning it has a period of 2^19937-1, which is a Mersenne * prime. * * This PRNG is fast and suitable for non-cryptographic code. * For instance, it would be perfect for Monte Carlo simulations, * etc. * * This implementation is inspired by: https://github.com/cslarsen/mersenne-twister. * It takes advantage of the fast SIMD instructions of the modern CPUs. * */ #ifndef PRNG_MT19937_SIMD_HPP #define PRNG_MT19937_SIMD_HPP #include <cstdint> #include <mipp.h> namespace aff3ct { namespace tools { /*! * \class PRNG_MT19937_simd * \brief The Mersenne Twister pseudo-random number generator (PRNG) with fast SIMD instructions. */ class PRNG_MT19937_simd { protected: mipp::vector<mipp::Reg<int32_t>> MT; unsigned index; public: explicit PRNG_MT19937_simd(const mipp::Reg<int32_t> seed); PRNG_MT19937_simd(); virtual ~PRNG_MT19937_simd(); /*! * \brief Initializes Mersenne Twister with given seed value. * * \param seed: a vector register of seeds to initialize the PRNG. */ void seed(const mipp::Reg<int32_t> seed); /*! * \brief Extracts a pseudo-random signed 32-bit integer in the range INT32_MIN ... INT32_MAX. * * \return a vector register of pseudo random numbers. */ mipp::Reg<int32_t> rand_s32(); /*! * \brief Returns a random float in the CLOSED range [0, 1] * Mnemonic: randf_co = random float 0=closed 1=closed. * * \return a vector register of pseudo random numbers. */ mipp::Reg<float> randf_cc(); /*! * \brief Returns a random float in the OPEN range [0, 1> * Mnemonic: randf_co = random float 0=closed 1=open. * * \return a vector register of pseudo random numbers. */ mipp::Reg<float> randf_co(); /*! * \brief Returns a random float in the OPEN range <0, 1> * Mnemonic: randf_oo = random float 0=open 1=open. * * \return a vector register of pseudo random numbers. */ mipp::Reg<float> randf_oo(); private: void generate_numbers(); }; } } #endif // PRNG_MT19937_simd_FAST_HPP
30c750b49ec714233a722b1fd88430c4929498b1
21cab7d193e6d74be36afc052906217443651fac
/Codeforces/A_382.cpp
25b9d05a16fdc9c1072a7af806e483b7954bed0d
[ "MIT" ]
permissive
ahakouz17/Competitive-Programming-Practice
2d3e7887129298b850e5bfd7341b6cd103eb5766
5f4daaf491ab03bb86387e491ecc5634b7f99433
refs/heads/master
2020-09-28T02:59:36.450414
2020-01-01T11:33:07
2020-01-01T11:33:07
226,672,685
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
cpp
A_382.cpp
// solved: 2014-01-17 19:54:58 #include <iostream> #include <string> #include <vector> using namespace std; int main() { int en = 0; string w, re; cin >> w >> re; vector<char> l; vector<char> r; for (int i = 0; i < w.length(); i++) { if (w[i] != '|') l.push_back(w[i]); else { i++; for (i; i < w.length(); i++) r.push_back(w[i]); break; } } int mi = min(r.size(), l.size()), ma = max(l.size(), r.size()); if (mi + re.length() < ma) { cout << "Impossible"; return 0; } while (en != re.length()) { if (r.size() > l.size()) { l.push_back(re[en]); en++; } else if (l.size() >= r.size()) { r.push_back(re[en]); en++; } } if (r.size() != l.size()) { cout << "Impossible"; return 0; } for (int i = 0; i < l.size(); i++) cout << l[i]; cout << '|'; for (int i = 0; i < r.size(); i++) cout << r[i]; return 0; }
28c992aed4387d323f0921401c041d78011a35b7
c785b9f58e3e6ab2998b2923ad0df3ba5e64fbb2
/Classes/Client/Tutorials/TutorialsManager.h
5a2163e49b4973b0086dff5adcd355537660492d
[]
no_license
kylinda/xcode_jifengyongzhezhuan
d4673c4be036b0b79197271d2cca211541f15e0c
d914d59259bc1412f281193aadd6ad1c1f0b4ac0
refs/heads/master
2021-01-21T16:18:43.402867
2014-11-11T05:26:26
2014-11-11T05:26:26
null
0
0
null
null
null
null
GB18030
C++
false
false
2,717
h
TutorialsManager.h
#pragma once #include "cocos2d.h" #include "TutorialsDataCenter.h" #include "TutorialBase.h" #include "vector" #include "TaskData.h" USING_NS_CC; class TutorialsManager { public : TutorialsManager(); ~TutorialsManager(); static TutorialsManager* Get(); static void Destroy(); void LoadData(); /** * Instruction : 重置变量 * @param */ void ResetValue(); /** * Instruction : 启动一个教程 * @param */ bool StartOneTutorial(unsigned int id,unsigned int type = kTutorialUnKnow,bool isPlayBegin = true,const char *attachStartControlName = ""); /** * Instruction : 处理控件事件 * @param type 0 单击 1 双击 */ bool HandleOneEvent(const char* name,unsigned int type); bool HandleDragEventOver(int type = 0,unsigned int pos = 0,bool bInEmptyUI = false); bool IsInDragTutorial(); bool IsInTutorial(); void Update(float dt); void ResetTutorialInstance(){ mTutorialInstance = NULL; mCurTutorialId = 0; } void InsertOneCompelteTutorial(unsigned int id){ m_vecCompelteTutorials.push_back(id); } void RevOneTutorialMessage(unsigned int id); bool IsOneTutorialExistInCompelteVec(unsigned int id); TutorialDataCenter* GetTutorialDataCenter(){return mDataCenter;} /** * Instruction : 发送设置ID * @param */ void sendOnceSetReqMessage(unsigned int id); /** * Instruction : * @param */ void SendTutorialStateRqsMessage(); /** * Instruction : * @param */ bool IsOneTaskWithOneTutorial(unsigned int task_id); /** * Instruction : * @param */ bool IsLeadTaskWithOneTutorial(unsigned int task_id); /** * Instruction : * @param */ void UpdateByTaskState(unsigned int taskId,eTaskState taskState,const char *attachStartControlName = ""); /** * Instruction : * @param */ TutorialDataCenter* GetTutorialData() { return mDataCenter; } void SetConfigDataReGetOrNot(bool bGet); bool IsOneTutorialOver(unsigned int id); protected: /** * Instruction : 启动一个UI教程 * @param */ bool StartOneUiTutorial(unsigned int id,unsigned int type = kTutorialUnKnow,const char *attachStartControlName = ""); /** * Instruction : 启动一个任务教程 * @param */ bool StartOneTaskTutorial(unsigned int taskId,bool isPlayBegin = true,const char *attachStartControlName = ""); /** * Instruction : 启动一个通过副本的UI引导 * @param */ bool StartOneLeadInstaceTaskTutorial(unsigned int taskId,unsigned int when); private: static TutorialsManager* mInstance; TutorialDataCenter* mDataCenter; TutorialBase* mTutorialInstance; unsigned int mCurTutorialId; std::vector<unsigned int> m_vecCompelteTutorials; bool bSendData; std::vector<int> m_vecTutorialIds; unsigned int m_nRecTutorialStateNum; };
c6f8f7aaa3320f637883402229c54a281842861a
ebd585fdafb22d31fcd6d04b209f81e88d1a2083
/modem_proc/modem/datamodem/interface/dssock/inc/ds_Sock_Utils.h
31194579972cf9410c172aa7111c1abec0921250
[ "Apache-2.0" ]
permissive
xusl/android-wilhelm
fd28144253cd9d7de0646f96ff27a1f4a9bec6e3
13c59cb5b0913252fe0b5c672d8dc2bf938bb720
refs/heads/master
2018-04-03T21:46:10.195170
2017-04-20T10:17:49
2017-04-20T10:17:49
88,847,837
11
10
null
null
null
null
UTF-8
C++
false
false
5,276
h
ds_Sock_Utils.h
#ifndef DS_SOCK_UTILS_H #define DS_SOCK_UTILS_H /*==========================================================================*/ /*! @file ds_Sock_Utils.h @brief This files provides common utility functions and macros used by the DSSOCK module. Copyright (c) 2009 Qualcomm Technologies Incorporated. All Rights Reserved. Qualcomm Confidential and Proprietary */ /*=========================================================================*/ /*=========================================================================== EDIT HISTORY FOR MODULE Please notice that the changes are listed in reverse chronological order. $Header: //source/qcom/qct/modem/datamodem/interface/dssock/main/latest/inc/ds_Sock_Utils.h#1 $ $DateTime: 2011/01/12 08:43:04 $$Author: aroras $ when who what, where, why ---------- --- ------------------------------------------------------------ 2009-05-29 hm Created module. ===========================================================================*/ /*=========================================================================== INCLUDE FILES FOR MODULE ===========================================================================*/ #include "comdef.h" #include "ds_Utils_DebugMsg.h" #include "ps_mem_ext.h" #include "ps_mem.h" #include "ds_Sock_MemManager.h" namespace DS { namespace Sock { /** @brief Utility macro for overloading the default new operator of a class. @details All of DSSOCK objects internally allocate memory using the ps_mem module. Hence the default new operator for each object is overloaded to support allocation from PS Mem. Use this macro in the class definition to perform the new operator overloading. @param[in] ps_mem_pool_id: PS Mem pool ID to use for the given class. @see ps_mem.h:ps_mem_get_buf() @see DSSockMemManager::GetBuf() @see DSSOCK_OVERLOAD_OPERATOR_DELETE @return None. */ #define DSSOCK_OVERLOAD_OPERATOR_NEW(ps_mem_pool_id) \ inline void* operator new \ ( \ unsigned int num_bytes \ ) \ throw() \ { \ (void) num_bytes; \ return ps_mem_get_buf (ps_mem_pool_id); \ } \ /** @brief Utility macro for overloading the default delete operator of a class. @details Use this macro inside the class definition (the header file) to overload the default delete operator. @param None. @see ps_mem.h:ps_mem_get_buf() @see DSSockMemManager::GetBuf() @see DSSOCK_OVERLOAD_OPERATOR_NEW @return None. */ #define DSSOCK_OVERLOAD_OPERATOR_DELETE() \ inline void operator delete \ ( \ void* objPtr \ ) \ throw() \ { \ PS_MEM_FREE(objPtr); \ } /** @brief Utility macro to perform overloading for both new and deletes operators. @param[in] ps_mem_pool_id: PS Mem pool ID to use for the given class. @see DSSOCK_OVERLOAD_OPERATOR_NEW @see DSSOCK_OVERLOAD_OPERATOR_DELETE */ #define DSSOCK_OVERLOAD_OPERATORS(ps_mem_pool_id) \ DSSOCK_OVERLOAD_OPERATOR_NEW(ps_mem_pool_id) \ DSSOCK_OVERLOAD_OPERATOR_DELETE() \ /** @brief Utility macro to perform Release() on an interface pointer. @details This macro releases an interface if it is non-NULL. It then sets the pointer to NULL. @param[in] pInterface - Double pointer to the interface to be released. @see IQI::Release() */ #define DSSOCK_RELEASEIF(pInterface) \ do \ { \ if (NULL != pInterface) \ { \ (void) pInterface->Release(); \ pInterface = NULL; \ } \ } while (0) }/* namespace Sock */ }/* namespace DS */ #endif /* DS_SOCK_UTILS_H */
0a52b2a86a1d8c5c9359cb8f6f6ce6d71184e824
56b02c68cd34f553ba276749d8c7a2797586fc01
/carManage/mainwindow.cpp
58713a02ea8590e42299e5c65373d430b1f37af8
[]
no_license
Liao-lin/qt_project
569059259a26194b4fcd3664696176df68b4e695
934aeeb6c342cfd194e64cdd81444f45e3adc487
refs/heads/master
2020-05-24T01:21:50.524215
2019-05-16T13:29:12
2019-05-16T13:29:12
187,033,298
0
0
null
null
null
null
UTF-8
C++
false
false
6,590
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "domxml.h" #include<QSqlDatabase> #include<QSqlError> #include<QMessageBox> #include<QSqlQueryModel> #include<QSqlQuery> #include<QString> #include<QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); on_actioncar_triggered();//显示车辆管理页面 connectDb(); //连接数据库 initDate(); DomXML::createXML("./demo.xml"); //创建xml文件 // QStringList list; // list<<"十年来"<<"毕加索"<<"11"<<"33"<<"11"; // DomXML::appendXML("./demo.xml",list); } //连接数据库 void MainWindow::connectDb() { QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("car.db"); if(!db.open()) { QMessageBox::warning(this,"数据库的错误",db.lastError().text()); return; } } void MainWindow::initDate() //初始数据 { QSqlQueryModel *queryModel = new QSqlQueryModel; ui->toolBox->setCurrentIndex(0); queryModel->setQuery("select name from factory"); //用模型来进行数据存储 ui->comboBoxFactory->setModel(queryModel); //初始化下拉框数据 ui->labelLast->setText("0"); //初始化剩余车辆 ui->lineEditTotal->setEnabled(false); //将总数设置为只读 ui->lineEditPrice->setEnabled(false); ui->pushButtonSure->setEnabled(false); } MainWindow::~MainWindow() { delete ui; } //设置车辆管理的菜单 void MainWindow::on_actioncar_triggered() { ui->stackedWidget->setCurrentIndex(0); ui->label->setText("车辆管理"); } //设置车辆统计的菜单 void MainWindow::on_actioncalc_triggered() { ui->stackedWidget->setCurrentIndex(1); ui->label->setText("销售统计"); } //厂家切换时对应的变换槽函数 void MainWindow::on_comboBoxFactory_currentIndexChanged(const QString &arg1) { if(arg1 =="请选择厂家") { ui->comboBoxBrand->clear(); //品牌下拉框清空 ui->lineEditPrice->clear(); //报价栏清空 ui->labelLast->setText("0"); ui->lineEditTotal->clear(); ui->spinBox->setValue(0); ui->spinBox->setEnabled(false); //微调框禁止使用 } else { ui->comboBoxBrand->clear(); //每次操作前进行清空 不然会叠加的 ui->spinBox->setEnabled(true); QSqlQuery query; QString sql =QString("select name from brand where factory= '%1'").arg(arg1); query.exec(sql); //执行查找语句 while (query.next()) { QString name = query.value(0).toString(); ui->comboBoxBrand->addItem(name); } } } //设置剩余以及价格随下拉框的改变而改变 void MainWindow::on_comboBoxBrand_currentIndexChanged(const QString &arg1) { QSqlQuery query; QString sql =QString("select price,last from brand where name= '%1'").arg(arg1); query.exec(sql); //执行查找语句 while (query.next()) { QString price = query.value(0).toString(); QString last =query.value("last").toString(); ui->lineEditPrice->setText(price); //设置单辆车报价 ui->labelLast->setText(last); //设置剩余车的数目 } } //微调框槽函数 void MainWindow::on_spinBox_valueChanged(int arg1) { ui->pushButtonSure->setEnabled(true); //激活确定按钮 //更新剩余数量 QSqlQuery query; QString sql =QString("select last from brand where name= '%1'"). arg(ui->comboBoxBrand->currentText());//查找当前品牌名 query.exec(sql); //执行查找语句 int last; while (query.next()) { last =query.value("last").toInt(); int tempNum =last-arg1; //qDebug()<<tempNum; if(arg1>last) { ui->spinBox->setValue(last); return; //如果选定数目大于剩余 则终止 } ui->labelLast->setText(QString::number(tempNum)); //绑定设置剩余数和微调框 } //更新车价的总体金额数目 int price =ui->lineEditPrice->text().toInt(); int num = ui->spinBox->text().toInt(); int total = price*num; ui->lineEditTotal->setText(QString::number(total)); } void MainWindow::on_pushButtonCal_clicked() //点击取消按钮,不进行数据库操作 { on_comboBoxFactory_currentIndexChanged("请选择厂家");//进行回退初始化 ui->comboBoxFactory->setCurrentText("请选择厂家"); //初始化选择框 } void MainWindow::on_pushButtonSure_clicked() //点击确定按钮 { int num = ui->spinBox->text().toInt(); //获取销售数量 int last = ui->labelLast->text().toInt(); //获取剩余数量 //获取数据库中的销量 QSqlQuery query; QString sql = QString("select sell from brand where name = '%1'"). arg(ui->comboBoxBrand->currentText()); int sell; //销售的数量 query.exec(sql); while (query.next()) { sell = query.value("sell").toInt(); } //更新数据库中的销售量和剩余量 sell = sell + num; QString sq = QString("update brand set sell = %1,last =%2 where name =" " '%3'").arg(sell).arg(last) .arg(ui->comboBoxBrand->currentText()); query.exec(sq); //把确认后的数据跟新到xml中 QStringList list; list<<ui->comboBoxFactory->currentText() <<ui->comboBoxBrand->currentText() <<ui->lineEditPrice->text() <<QString::number(num) <<ui->lineEditTotal->text(); DomXML::appendXML("./demo.xml",list); QStringList fList; QStringList bList; QStringList pList; QStringList nList; QStringList tList; DomXML::readXML("./demo.xml",fList,bList,pList,nList,tList); int i=fList.size()-1; //for(int i=0;i<fList.size();i++)// //{ QString str = QString("%1:%2:卖出了%3,单价:%4,总价:%5") .arg(fList.at(i)) .arg(bList.at(i)) .arg(nList.at(i)) .arg(pList.at(i)) .arg(tList.at(i)); ui->textEdit->append(str); // } //按完确定后进行界面初始化 on_comboBoxFactory_currentIndexChanged("请选择厂家");//进行回退初始化 ui->comboBoxFactory->setCurrentText("请选择厂家"); //初始化选择框 ui->pushButtonSure->setEnabled(false); //淹没确定按钮 //on_pushButtonCal_clicked() 或者直接调用这个函数 }
321e7cde52a47c23090beb12ef1cd7a8402cc0d2
3dda05a9931cd3da5b125d5db883317649c2a294
/cpp/uniform_experiment.cpp
86128642c367e47de1dec81b91a965e65ad99d20
[]
no_license
npetrenko/curse_dim
50e11af1890a683ed40fa1d409f28336a400352a
188e8899fca52407d49d926e8cc272a5e15411f4
refs/heads/master
2020-05-27T08:45:22.506882
2019-08-09T13:05:01
2019-08-09T13:05:01
188,552,470
0
0
null
null
null
null
UTF-8
C++
false
false
1,882
cpp
uniform_experiment.cpp
#include <curse_dim/pendulum.hpp> #include <curse_dim/experiment.hpp> #include <curse_dim/uniform_experiment.hpp> #include <bellman/bellman_operators/uniform_operator.hpp> #include <glog/logging.h> class UniformExperimentImpl final : public AbstractExperiment { public: UniformExperimentImpl(AbstractExperiment::Builder builder) : AbstractExperiment(std::move(builder).Build()) { } std::string GetName() const override { return "UniformExperiment"; } private: void MakeIterationImpl() override { last_qfunc_est_.reset(nullptr); MaybeInitializeBellmanOp(); bellman_op_->MakeIteration(); } IQFuncEstimate* EstimateQFuncImpl() override { if (!bellman_op_) { throw ExperimentNotRunException(); } if (last_qfunc_est_) { return last_qfunc_est_.get(); } auto importance_function = [=](size_t) { return 1 / pow(2 * M_PI, GetNumPendulums() * 2); }; last_qfunc_est_ = std::unique_ptr<IQFuncEstimate>( new QFuncEstForGreedy(GetEnvParams(), bellman_op_->GetQFunc(), importance_function)); return last_qfunc_est_.get(); } void MaybeInitializeBellmanOp() { if (bellman_op_) { return; } VLOG(3) << "Initializing uniform bellman op"; UniformBellmanOperator::Builder builder; builder.SetInitRadius(M_PI) .SetEnvParams(GetEnvParams()) .SetNumParticles(GetNumParticles()) .SetRandomDevice(GetRandomDevice()); bellman_op_ = std::move(builder).Build(); } UniformBellmanOperatorPtr bellman_op_{nullptr}; std::unique_ptr<IQFuncEstimate> last_qfunc_est_{nullptr}; }; namespace UniformExperiment { std::unique_ptr<AbstractExperiment> Make(AbstractExperiment::Builder builder) { return std::make_unique<UniformExperimentImpl>(std::move(builder)); } } // namespace UniformExperiment
f49cb74f6e7b64af0e50a9447eaf46a05df55d78
5330918e825f8d373d3907962ba28215182389c3
/FWCore/Framework/src/GenericObjectOwner.cc
bb6b3c6743db5162910ffe16c71cc0ad15563e23
[]
no_license
perrozzi/cmg-cmssw
31103a7179222c7aa94f65e83d090a5cf2748e27
1f4cfd936da3a6ca78f25959a41620925c4907ca
refs/heads/CMG_PAT_V5_18_from-CMSSW_5_3_22
2021-01-16T23:15:58.556441
2017-05-11T22:43:15
2017-05-11T22:43:15
13,272,641
1
0
null
2017-05-11T22:43:16
2013-10-02T14:05:21
C++
UTF-8
C++
false
false
3,898
cc
GenericObjectOwner.cc
// -*- C++ -*- // // Package: Framework // Class : GenericObjectOwner // // Implementation: // <Notes on implementation> // // Original Author: Chris Jones // Created: Thu Feb 7 17:21:22 EST 2008 // // system include files // user include files #include "FWCore/Framework/interface/GenericObjectOwner.h" #include "FWCore/Framework/interface/EventPrincipal.h" #include "FWCore/Utilities/interface/WrappedClassName.h" namespace edm { // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // //GenericObjectOwner::GenericObjectOwner() //{ //} // GenericObjectOwner::GenericObjectOwner(const GenericObjectOwner& rhs) // { // // do actual copying here; // } GenericObjectOwner::~GenericObjectOwner() { if(m_ownData) { m_object.Destruct(); } } // // assignment operators // // const GenericObjectOwner& GenericObjectOwner::operator=(const GenericObjectOwner& rhs) // { // //An exception safe implementation is // GenericObjectOwner temp(rhs); // swap(rhs); // // return *this; // } // // member functions // void GenericObjectOwner::swap(GenericObjectOwner& iOther) { Reflex::Object old(m_object); m_object = iOther.m_object; iOther.m_object = m_object; } // // const member functions // Reflex::Object GenericObjectOwner::object() const { return m_object; } // // static member functions // template <> OrphanHandle<GenericObjectOwner> Event::put<GenericObjectOwner>(std::auto_ptr<GenericObjectOwner> product, std::string const& productInstanceName) { if(product.get() == 0) { // null pointer is illegal throw edm::Exception(edm::errors::NullPointerError) << "Event::put: A null auto_ptr was passed to 'put'.\n" << "The pointer is of type " << "GenericObjectOwner" << ".\n" << "The specified productInstanceName was '" << productInstanceName << "'.\n"; } // The following will call post_insert if T has such a function, // and do nothing if T has no such function. /* typename boost::mpl::if_c<detail::has_postinsert<PROD>::value, DoPostInsert<PROD>, DoNotPostInsert<PROD> >::type maybe_inserter; maybe_inserter(product.get()); */ ConstBranchDescription const& desc = provRecorder_.getBranchDescription(TypeID(product->object().TypeOf().TypeInfo()), productInstanceName); Reflex::Type const wrapperType = Reflex::Type::ByName(wrappedClassName(desc.fullClassName())); if(wrapperType == Reflex::Type()) { throw edm::Exception(errors::DictionaryNotFound, "NoWrapperDictionary") << "Event::put: the class type '" << desc.fullClassName() << "' was passed to put but the Reflex dictionary for the required class '" << wrappedClassName(desc.fullClassName()) << "' could not be found./n" << "Please change the C++ package which contains the description of '" << desc.fullClassName() << "' so that the required class also has a dictionary autogenerated."; } std::vector<void*> args; args.reserve(1); args.push_back(product->object().Address()); //generate the signature of the function we want to call std::string s("void("); s += desc.fullClassName(); s += "*)"; Reflex::Type ptrT = Reflex::Type::ByName(s); Reflex::Object oWrapper(wrapperType.Construct(ptrT,args)); //ownership was transfered to the wrapper product.release(); //static Reflex::Type s_edproductType(Reflex::Type::ByTypeInfo(typeid(EDProduct))); WrapperOwningHolder wp(oWrapper.Address(), desc.getInterface()); putProducts().push_back(std::make_pair(wp, &desc)); // product.release(); // The object has been copied into the Wrapper. // The old copy must be deleted, so we cannot release ownership. return(OrphanHandle<GenericObjectOwner>(oWrapper.Get("obj"), eventPrincipal().branchIDToProductID(desc.branchID()))); } }
34f892a6a1a9d96f6672acf2674561b971df2afa
7ba61f38646acb3c5cd0d879b716d36f2bfdcd7b
/BST_IDE/ui/bk/uipageview.cpp
22ad75bafb7fb8d8444cbdbc3cdeba16cff8fda7
[]
no_license
HensonLi/Elevator-BST-V1
3f774303e8ebc67fca1c66c8750fcc44ff229907
2e27edcd0bbe54ef03378f4508bf36937bd80f4c
refs/heads/master
2021-05-11T09:56:11.990511
2018-01-19T07:41:10
2018-01-19T07:41:10
118,089,237
0
0
null
null
null
null
GB18030
C++
false
false
2,586
cpp
uipageview.cpp
#include "uipageview.h" uiPageView::uiPageView(QWidget *parent) : QGraphicsView(parent) { scene = 0; setRenderHint(QPainter::Antialiasing); setBackgroundBrush(QBrush(Qt::gray)); //setBackgroundBrush(QPixmap(":/Page/rc/Page/background.png")); setCacheMode(QGraphicsView::CacheBackground); setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); setAcceptDrops(true); setDragMode(QGraphicsView::RubberBandDrag); setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); setAttribute(Qt::WA_TranslucentBackground, true); setAutoFillBackground(true); scene = new DiagramScene(this); setScene(scene); } uiPageView::~uiPageView() { if(scene) { scene->deleteLater(); scene = 0; } } //>@缩放Scene到View的大小 //fitInView(this->rect(), Qt::KeepAspectRatio); void uiPageView::paintEvent(QPaintEvent *event) { static bool busy = false; if(!busy) busy = true; else return; QGraphicsView::paintEvent(event); busy = false; } void uiPageView::drawBackground(QPainter *painter, const QRectF &rect) { static bool busy = false; if(!busy) busy = true; else return; QGraphicsView::drawBackground(painter, rect); if(scene) { int sceneWidth = scene->width(); if(sceneWidth<=RectPulse*2) sceneWidth = 800+2*StartPosX; int sceneHeight = scene->height(); if(sceneHeight<=RectPulse*2) sceneHeight = 600+2*StartPosX; int w = (int)(sceneWidth-RectPulse*2); int h = (int)(sceneHeight-RectPulse*2); painter->setPen(QPen(Qt::black, 4, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->setBrush(Qt::white); painter->drawRect(QRect(0, 0, sceneWidth, sceneHeight)); painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawRect(QRect(RectPulse, RectPulse, w, h)); } // qreal tmp; // for(tmp = 0; tmp < scene->width()-LineLen; tmp+=LinePulse) // { // painter->drawLine(QPointF(tmp,0), QPointF(tmp,LineLen)); // painter->drawLine(QPointF(tmp,scene->height()-LineLen), QPointF(tmp,scene->height())); // } // for(tmp = 0; tmp < scene->height()-LineLen; tmp+=LinePulse) // { // painter->drawLine(QPointF(0,tmp), QPointF(LineLen,tmp)); // painter->drawLine(QPointF(scene->width()-LineLen,tmp), QPointF(scene->width(),tmp)); // } busy = false; }
f07498484fadd9ddcaeaf56c05eb963b6b59ec6f
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/webrtc/modules/utility/source/jvm_android.cc
ee9930bcaa660ab1652bf47b81810c2a299524e8
[ "BSD-3-Clause", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
9,003
cc
jvm_android.cc
/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/utility/include/jvm_android.h" #include <android/log.h> #include <memory> #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/platform_thread.h" namespace webrtc { JVM* g_jvm; // TODO(henrika): add more clases here if needed. struct { const char* name; jclass clazz; } loaded_classes[] = { {"org/webrtc/voiceengine/BuildInfo", nullptr}, {"org/webrtc/voiceengine/WebRtcAudioManager", nullptr}, {"org/webrtc/voiceengine/WebRtcAudioRecord", nullptr}, {"org/webrtc/voiceengine/WebRtcAudioTrack", nullptr}, }; // Android's FindClass() is trickier than usual because the app-specific // ClassLoader is not consulted when there is no app-specific frame on the // stack. Consequently, we only look up all classes once in native WebRTC. // http://developer.android.com/training/articles/perf-jni.html#faq_FindClass void LoadClasses(JNIEnv* jni) { RTC_LOG(LS_INFO) << "LoadClasses:"; for (auto& c : loaded_classes) { jclass localRef = FindClass(jni, c.name); RTC_LOG(LS_INFO) << "name: " << c.name; CHECK_EXCEPTION(jni) << "Error during FindClass: " << c.name; RTC_CHECK(localRef) << c.name; jclass globalRef = reinterpret_cast<jclass>(jni->NewGlobalRef(localRef)); CHECK_EXCEPTION(jni) << "Error during NewGlobalRef: " << c.name; RTC_CHECK(globalRef) << c.name; c.clazz = globalRef; } } void FreeClassReferences(JNIEnv* jni) { for (auto& c : loaded_classes) { jni->DeleteGlobalRef(c.clazz); c.clazz = nullptr; } } jclass LookUpClass(const char* name) { for (auto& c : loaded_classes) { if (strcmp(c.name, name) == 0) return c.clazz; } RTC_CHECK(false) << "Unable to find class in lookup table"; return 0; } // JvmThreadConnector implementation. JvmThreadConnector::JvmThreadConnector() : attached_(false) { RTC_LOG(LS_INFO) << "JvmThreadConnector::ctor"; JavaVM* jvm = JVM::GetInstance()->jvm(); RTC_CHECK(jvm); JNIEnv* jni = GetEnv(jvm); if (!jni) { RTC_LOG(LS_INFO) << "Attaching thread to JVM"; JNIEnv* env = nullptr; jint ret = jvm->AttachCurrentThread(&env, nullptr); attached_ = (ret == JNI_OK); } } JvmThreadConnector::~JvmThreadConnector() { RTC_LOG(LS_INFO) << "JvmThreadConnector::dtor"; RTC_DCHECK(thread_checker_.IsCurrent()); if (attached_) { RTC_LOG(LS_INFO) << "Detaching thread from JVM"; jint res = JVM::GetInstance()->jvm()->DetachCurrentThread(); RTC_CHECK(res == JNI_OK) << "DetachCurrentThread failed: " << res; } } // GlobalRef implementation. GlobalRef::GlobalRef(JNIEnv* jni, jobject object) : jni_(jni), j_object_(NewGlobalRef(jni, object)) { RTC_LOG(LS_INFO) << "GlobalRef::ctor"; } GlobalRef::~GlobalRef() { RTC_LOG(LS_INFO) << "GlobalRef::dtor"; DeleteGlobalRef(jni_, j_object_); } jboolean GlobalRef::CallBooleanMethod(jmethodID methodID, ...) { va_list args; va_start(args, methodID); jboolean res = jni_->CallBooleanMethodV(j_object_, methodID, args); CHECK_EXCEPTION(jni_) << "Error during CallBooleanMethod"; va_end(args); return res; } jint GlobalRef::CallIntMethod(jmethodID methodID, ...) { va_list args; va_start(args, methodID); jint res = jni_->CallIntMethodV(j_object_, methodID, args); CHECK_EXCEPTION(jni_) << "Error during CallIntMethod"; va_end(args); return res; } void GlobalRef::CallVoidMethod(jmethodID methodID, ...) { va_list args; va_start(args, methodID); jni_->CallVoidMethodV(j_object_, methodID, args); CHECK_EXCEPTION(jni_) << "Error during CallVoidMethod"; va_end(args); } // NativeRegistration implementation. NativeRegistration::NativeRegistration(JNIEnv* jni, jclass clazz) : JavaClass(jni, clazz), jni_(jni) { RTC_LOG(LS_INFO) << "NativeRegistration::ctor"; } NativeRegistration::~NativeRegistration() { RTC_LOG(LS_INFO) << "NativeRegistration::dtor"; jni_->UnregisterNatives(j_class_); CHECK_EXCEPTION(jni_) << "Error during UnregisterNatives"; } std::unique_ptr<GlobalRef> NativeRegistration::NewObject(const char* name, const char* signature, ...) { RTC_LOG(LS_INFO) << "NativeRegistration::NewObject"; va_list args; va_start(args, signature); jobject obj = jni_->NewObjectV( j_class_, GetMethodID(jni_, j_class_, name, signature), args); CHECK_EXCEPTION(jni_) << "Error during NewObjectV"; va_end(args); return std::unique_ptr<GlobalRef>(new GlobalRef(jni_, obj)); } // JavaClass implementation. jmethodID JavaClass::GetMethodId(const char* name, const char* signature) { return GetMethodID(jni_, j_class_, name, signature); } jmethodID JavaClass::GetStaticMethodId(const char* name, const char* signature) { return GetStaticMethodID(jni_, j_class_, name, signature); } jobject JavaClass::CallStaticObjectMethod(jmethodID methodID, ...) { va_list args; va_start(args, methodID); jobject res = jni_->CallStaticObjectMethodV(j_class_, methodID, args); CHECK_EXCEPTION(jni_) << "Error during CallStaticObjectMethod"; return res; } jint JavaClass::CallStaticIntMethod(jmethodID methodID, ...) { va_list args; va_start(args, methodID); jint res = jni_->CallStaticIntMethodV(j_class_, methodID, args); CHECK_EXCEPTION(jni_) << "Error during CallStaticIntMethod"; return res; } // JNIEnvironment implementation. JNIEnvironment::JNIEnvironment(JNIEnv* jni) : jni_(jni) { RTC_LOG(LS_INFO) << "JNIEnvironment::ctor"; } JNIEnvironment::~JNIEnvironment() { RTC_LOG(LS_INFO) << "JNIEnvironment::dtor"; RTC_DCHECK(thread_checker_.IsCurrent()); } std::unique_ptr<NativeRegistration> JNIEnvironment::RegisterNatives( const char* name, const JNINativeMethod* methods, int num_methods) { RTC_LOG(LS_INFO) << "JNIEnvironment::RegisterNatives: " << name; RTC_DCHECK(thread_checker_.IsCurrent()); jclass clazz = LookUpClass(name); jni_->RegisterNatives(clazz, methods, num_methods); CHECK_EXCEPTION(jni_) << "Error during RegisterNatives"; return std::unique_ptr<NativeRegistration>( new NativeRegistration(jni_, clazz)); } std::string JNIEnvironment::JavaToStdString(const jstring& j_string) { RTC_DCHECK(thread_checker_.IsCurrent()); const char* jchars = jni_->GetStringUTFChars(j_string, nullptr); CHECK_EXCEPTION(jni_); const int size = jni_->GetStringUTFLength(j_string); CHECK_EXCEPTION(jni_); std::string ret(jchars, size); jni_->ReleaseStringUTFChars(j_string, jchars); CHECK_EXCEPTION(jni_); return ret; } // static void JVM::Initialize(JavaVM* jvm) { RTC_LOG(LS_INFO) << "JVM::Initialize"; RTC_CHECK(!g_jvm); g_jvm = new JVM(jvm); } void JVM::Initialize(JavaVM* jvm, jobject context) { Initialize(jvm); // Pass in the context to the new ContextUtils class. JNIEnv* jni = g_jvm->jni(); jclass context_utils = FindClass(jni, "org/webrtc/ContextUtils"); jmethodID initialize_method = jni->GetStaticMethodID( context_utils, "initialize", "(Landroid/content/Context;)V"); jni->CallStaticVoidMethod(context_utils, initialize_method, context); } // static void JVM::Uninitialize() { RTC_LOG(LS_INFO) << "JVM::Uninitialize"; RTC_DCHECK(g_jvm); delete g_jvm; g_jvm = nullptr; } // static JVM* JVM::GetInstance() { RTC_DCHECK(g_jvm); return g_jvm; } JVM::JVM(JavaVM* jvm) : jvm_(jvm) { RTC_LOG(LS_INFO) << "JVM::JVM"; RTC_CHECK(jni()) << "AttachCurrentThread() must be called on this thread."; LoadClasses(jni()); } JVM::~JVM() { RTC_LOG(LS_INFO) << "JVM::~JVM"; RTC_DCHECK(thread_checker_.IsCurrent()); FreeClassReferences(jni()); } std::unique_ptr<JNIEnvironment> JVM::environment() { RTC_LOG(LS_INFO) << "JVM::environment"; ; // The JNIEnv is used for thread-local storage. For this reason, we cannot // share a JNIEnv between threads. If a piece of code has no other way to get // its JNIEnv, we should share the JavaVM, and use GetEnv to discover the // thread's JNIEnv. (Assuming it has one, if not, use AttachCurrentThread). // See // http://developer.android.com/training/articles/perf-jni.html. JNIEnv* jni = GetEnv(jvm_); if (!jni) { RTC_LOG(LS_ERROR) << "AttachCurrentThread() has not been called on this thread"; return std::unique_ptr<JNIEnvironment>(); } return std::unique_ptr<JNIEnvironment>(new JNIEnvironment(jni)); } JavaClass JVM::GetClass(const char* name) { RTC_LOG(LS_INFO) << "JVM::GetClass: " << name; RTC_DCHECK(thread_checker_.IsCurrent()); return JavaClass(jni(), LookUpClass(name)); } } // namespace webrtc
0c3a57958ea9176f38357d388d7a05ebf970ae24
ec10d4320fdbad0bab61b5fa00c0bf27e50ce6f1
/code/benchmarker/sources/viinterpolatorbatcher.cpp
a09ca703a721829d7b0a82ea72a4eabab46465e3
[]
no_license
dualword/Visore
d9e97c5a53cdd0c812c41a52ce169bd7c04b765d
db402f0bb69b25fccbca7500f275fac8a629b1f9
refs/heads/master
2023-03-17T12:38:02.901936
2015-01-29T06:06:32
2015-01-29T06:06:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,769
cpp
viinterpolatorbatcher.cpp
#include <viinterpolatorbatcher.h> #include <viaudiodata.h> #include <vinoisecreator.h> #include <QTextStream> #include <QDir> #include <iomanip> #include <vinearestneighbourinterpolator.h> #include <viprimitiveinterpolator.h> #include <vipolynomialinterpolator.h> #include <vifourierinterpolator.h> #include <vilagrangeinterpolator.h> #include <vinewtoninterpolator.h> #include <viarimainterpolator.h> #include <vigarchinterpolator.h> #include <vihermiteinterpolator.h> #include <vineuralinterpolator.h> #define WINDOW_SIZE 4096 #define WRITE false #define SUMMARY true ViInterpolatorBatcher::ViInterpolatorBatcher() { mCurrentObject = ViAudioObject::create(); mMainTime.start(); // *************************** // PRIMITIVE // *************************** // Zero Interpolator //mInterpolator = new ViPrimitiveInterpolator(ViPrimitiveInterpolator::Zero); // Cosine Interpolator //mInterpolator = new ViPrimitiveInterpolator(ViPrimitiveInterpolator::Cosine); // Random Interpolator /*mInterpolator = new ViPrimitiveInterpolator(ViPrimitiveInterpolator::Random); setParam("Window Size", 2);*/ // Mirror Interpolator //mInterpolator = new ViPrimitiveInterpolator(ViPrimitiveInterpolator::Mirror); // Duplicate Interpolator //mInterpolator = new ViPrimitiveInterpolator(ViPrimitiveInterpolator::Duplicate); // Similarity Interpolator /*mInterpolator = new ViPrimitiveInterpolator(ViPrimitiveInterpolator::Similarity); setParam("Window Size", 2); setParam("Samples", 2);*/ // Lanczos Interpolator /*mInterpolator = new ViPrimitiveInterpolator(ViPrimitiveInterpolator::Lanczos); setParam("Window Size", 2);*/ // *************************** // NN // *************************** /*mInterpolator = new ViNearestNeighbourInterpolator(ViNearestNeighbourInterpolator::Traditional); setParam("K", 2);*/ // *************************** // LAGRANGE // *************************** /*mInterpolator = new ViLagrangeInterpolator(); setParam("Window Size", 2);*/ // *************************** // NEWTON // *************************** /*mInterpolator = new ViNewtonInterpolator(); setParam("Window Size", 2);*/ // *************************** // HERMITE // *************************** /*mInterpolator = new ViHermiteInterpolator(); setParam("Window Size", 2);*/ // *************************** // Polynomial // *************************** // Normal /*mInterpolator = new ViPolynomialInterpolator(ViPolynomialInterpolator::Normal); setParam("Window Size", 2); setParam("Degree", 2);*/ // Osculating /*mInterpolator = new ViPolynomialInterpolator(ViPolynomialInterpolator::Osculating); setParam("Window Size", 2); setParam("Degree", 2); setParam("Derivatives", 2);*/ // Splines /*mInterpolator = new ViPolynomialInterpolator(ViPolynomialInterpolator::Splines); setParam("Window Size", 8); setParam("Degree", 1);*/ // *************************** // Fourier // *************************** // Normal /*mInterpolator = new ViFourierInterpolator(ViFourierInterpolator::Normal); setParam("Window Size", 2); setParam("Degree", 2);*/ // Osculating /*mInterpolator = new ViFourierInterpolator(ViFourierInterpolator::Osculating); setParam("Window Size", 2); setParam("Degree", 2); setParam("Derivatives", 2);*/ // Splines /*mInterpolator = new ViFourierInterpolator(ViFourierInterpolator::Splines); setParam("Window Size", 2); setParam("Degree", 2);*/ // *************************** // AR // *************************** /*mInterpolator = new ViArimaInterpolator(); setParam("Window Size", 1024); setParam("AR Degree", 2); setParam("I Degree", 0); setParam("MA Degree", 0);*/ // *************************** // MA // *************************** /*mInterpolator = new ViArimaInterpolator(); setParam("Window Size", 1024); setParam("AR Degree", 0); setParam("I Degree", 0); setParam("MA Degree", 2);*/ // *************************** // ARMA // *************************** /*mInterpolator = new ViArimaInterpolator(ViArimaInterpolator::AR2); setParam("Window Size", 1440); setParam("AR Degree", 9);*/ //setParam("I Degree", 0); //setParam("MA Degree", 2); // *************************** // ARIMA // *************************** /*mInterpolator = new ViArimaInterpolator(); setParam("Window Size", 1024); setParam("AR Degree", 2); setParam("I Degree", 2); setParam("MA Degree", 2);*/ // *************************** // ARCH // *************************** /*mInterpolator = new ViGarchInterpolator(); setParam("Window Size", 1024); setParam("Arch Degree", 2); setParam("Garch Degree", 0);*/ // *************************** // GARCH // *************************** /*mInterpolator = new ViGarchInterpolator(); setParam("Window Size", 1024); setParam("Arch Degree", 2); setParam("Garch Degree", 2);*/ // *************************** // ANN - Incremental Prediction // *************************** /*mInterpolator = new ViNeuralInterpolator(ViNeuralInterpolator::IncrementalPrediction); addParam("Window Size", 928, 928, 1); addParam("Hidden Layer 1", 80, 80, 1); mInterpolator->setDirection(ViInterpolator::Forward);*/ // *************************** // ANN - Bidirectional Incremental Prediction // *************************** /*mInterpolator = new ViNeuralInterpolator(ViNeuralInterpolator::IncrementalPrediction); addParam("Window Size", 928, 928, 1); addParam("Hidden Layer 1", 80, 80, 1); mInterpolator->setDirection(ViInterpolator::Bidirectional);*/ // *************************** // ANN - Recurrent Prediction // *************************** /*mInterpolator = new ViNeuralInterpolator(ViNeuralInterpolator::IncrementalRecurrentPrediction); addParam("Window Size", 832, 832, 1); addParam("Hidden Layer 1", 96, 96, 1); mInterpolator->setDirection(ViInterpolator::Forward);*/ // *************************** // ANN - Bidirectional Recurrent Prediction // *************************** /*mInterpolator = new ViNeuralInterpolator(ViNeuralInterpolator::IncrementalRecurrentPrediction); addParam("Window Size", 832, 832, 1); addParam("Hidden Layer 1", 96, 96, 1); mInterpolator->setDirection(ViInterpolator::Bidirectional);*/ // *************************** // ANN - Set Prediction // *************************** /*mInterpolator = new ViNeuralInterpolator(ViNeuralInterpolator::SetPrediction); addParam("Window Size", 416, 416, 1); mInterpolator->setDirection(ViInterpolator::Forward);*/ // *************************** // ANN - Bidirectional Set Prediction // *************************** /*mInterpolator = new ViNeuralInterpolator(ViNeuralInterpolator::SetPrediction); addParam("Window Size", 416, 416, 1); mInterpolator->setDirection(ViInterpolator::Bidirectional);*/ // *************************** // ANN - Interpolation // *************************** mInterpolator = new ViNeuralInterpolator(ViNeuralInterpolator::Interpolation); addParam("Window Size", 256, 256, 1); mInterpolator->setDirection(ViInterpolator::Forward); //mInterpolator->setDirection(ViInterpolator::Forward); QObject::connect(mInterpolator, SIGNAL(progressed(qreal)), this, SLOT(progress(qreal))); } ViInterpolatorBatcher::~ViInterpolatorBatcher() { } void ViInterpolatorBatcher::progress(qreal percentage) { cout << setprecision(2) << fixed << "\r" << percentage << "%" << flush; } void ViInterpolatorBatcher::addParam(QString name, qreal start, qreal end, qreal increase) { if(start == 0 && end == 0) return; if(mInterpolator->hasParameter(name)) { mParamsNames.append(name); mParamsStart.append(start); mParamsEnd.append(end); mParamsIncrease.append(increase); mParamsCurrent.append(0); } else cout << "This interpolator (" << mInterpolator->name("", true).toLatin1().data() << ") doesn't make use of the given parameter (" << name.toLatin1().data() << ")." << endl; } void ViInterpolatorBatcher::setParam(QString name, qreal value) { addParam(name, value, value, 0); } void ViInterpolatorBatcher::initParams() { mDoneParamIterations = 0; mTotalParamIterations = 1; for(int i = 0; i < mParamsStart.size(); ++i) { mTotalParamIterations *= (mParamsEnd[i] - mParamsStart[i] + mParamsIncrease[i]) / mParamsIncrease[i]; } mTotalParamIterations *= mTotalFiles; } bool ViInterpolatorBatcher::nextParam() { int size = mParamsStart.size(); bool finished = true; for(int i = 0; i < size; ++i) { if(mParamsCurrent[i] < mParamsEnd[i]) { finished = false; break; } } if(finished) return false; //All paramaters were tested for(int i = size - 1; i >= 0; --i) { if(mParamsCurrent[i] < mParamsEnd[i]) { mParamsCurrent[i] += mParamsIncrease[i]; return true; } else if(mParamsCurrent[i] >= mParamsEnd[i]) { mParamsCurrent[i] = mParamsStart[i]; int pre = 1; while(mParamsCurrent[i-pre] >= mParamsEnd[i-pre]) { mParamsCurrent[i-pre] = mParamsStart[i-pre]; ++pre; } mParamsCurrent[i-pre] += mParamsIncrease[i-pre]; return true; } } } void ViInterpolatorBatcher::benchmark(QString folder) { if(folder == "") { QDir dir("/home/visore/Visore Projects/Files/"); QStringList dirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); for(int i = 0; i < dirs.size(); ++i) addDir(dirs[i]); } else { addDir(folder); } mTotalFiles = mFiles.size(); initParams(); nextFile(); } void ViInterpolatorBatcher::addDir(QString dirName) { QDir dirFile("/home/visore/Visore Projects/Files/" + dirName); if(!dirFile.exists()) { cout << "Directory does not exist: " << dirFile.absolutePath().toLatin1().data() << endl; return; } QDir dirResult("/home/visore/Visore Projects/Results/" + dirName); if(!dirResult.exists()) dirResult.mkpath(dirResult.absolutePath()); if(SUMMARY) { QString summary = dirResult.absolutePath() + "/summary.txt"; if(!mSummaryFiles.contains(summary)) { printFileHeader(summary); mSummaryFiles.append(summary); } } QDir dir(dirFile.absolutePath()); QStringList files = dir.entryList(QDir::Files); for(int j = 0; j < files.size(); ++j) { mFiles.enqueue(dir.absoluteFilePath(files[j])); QString id = ViId::generate(); mResults.enqueue(dirResult.absolutePath() + "/" + mInterpolator->name() + "_" + id + "_ALL.txt"); mResults2.enqueue(dirResult.absolutePath() + "/" + mInterpolator->name() + "_" + id + "_MINIFIED.txt"); } } void ViInterpolatorBatcher::nextFile() { if(mFiles.isEmpty()) { quit(); } else { for(int i = 0; i < mParamsStart.size(); ++i) mParamsCurrent[i] = mParamsStart[i]; mCurrentFile = mFiles.dequeue(); mAllFile = mResults.dequeue(); mMiniFile = mResults2.dequeue(); printFileHeader(mAllFile); printFileHeader(mMiniFile); mCurrentObject->clearBuffers(); mCurrentObject.setNull(); mCurrentObject = ViAudioObject::create(); mCurrentObject->setFilePath(ViAudio::Target, mCurrentFile); QObject::connect(mCurrentObject.data(), SIGNAL(decoded()), this, SLOT(process())); mCurrentObject->decode(); } } void ViInterpolatorBatcher::process() { mQuitCount = 0; mBestScore = DBL_MAX; QObject::disconnect(mCurrentObject.data(), SIGNAL(decoded()), this, SLOT(process())); qint64 time; ViErrorCollection interpolationErrors, modelErrors; ViNoiseCreator creator; creator.createNoise(mCurrentObject->buffer(ViAudio::Target), mCurrentObject->buffer(ViAudio::Corrupted), mCurrentObject->buffer(ViAudio::NoiseMask), mCurrentObject->buffer(ViAudio::Custom)); //do //{ mQuitCount = 0; interpolationErrors.clear(); modelErrors.clear(); for(int i = 0; i < mParamsStart.size(); ++i) mInterpolator->setParameter(mParamsNames[i], mParamsCurrent[i]); if(mInterpolator->validParameters()) { mTime.restart(); mInterpolator->interpolate(mCurrentObject->buffer(ViAudio::Corrupted), mCurrentObject->buffer(ViAudio::Corrected), mCurrentObject->buffer(ViAudio::Target), mCurrentObject->buffer(ViAudio::Custom), &interpolationErrors, &modelErrors); time = mTime.elapsed(); cout << "\r \r"; // Clear intermidiate percentage } else { time = 0; } // Write if(WRITE) { QObject::connect(mCurrentObject.data(), SIGNAL(encoded()), this, SLOT(quit())); mCurrentObject->encode(ViAudio::Corrupted); //return; } ++mDoneParamIterations; printFileDataAll(mAllFile, interpolationErrors, modelErrors, time); printFileDataMinified(mMiniFile, interpolationErrors, modelErrors, time); if(SUMMARY) printFileDataSummary(genre(mMiniFile), interpolationErrors, modelErrors, time); printTerminal(interpolationErrors, modelErrors, time); //} //while(nextParam()); nextFile(); } void ViInterpolatorBatcher::printFileHeader(QString filepath) { int i; QFile file(filepath); file.open(QIODevice::WriteOnly); QTextStream stream(&file); stream << mInterpolator->name() << "\n\n"; stream << QFileInfo(mCurrentFile).fileName() << "\n\n"; for(i = 0; i < mParamsStart.size(); ++i) stream << "PARAMETER " << i + 1 << " (" << mInterpolator->parameterName(i) <<")\t"; stream << "NRMSE INTERPOLATION" << "\t" << "NRMSE MODEL" << "\t" << "TIME" << "\t\t"; for(i = ViNoiseCreator::minimumNoiseSize(); i <= ViNoiseCreator::maximumNoiseSize(); ++i) stream << "NOISE SIZE " << i << " (NRMSE INTERPOLATION)\t"; stream << "\t"; for(i = ViNoiseCreator::minimumNoiseSize(); i <= ViNoiseCreator::maximumNoiseSize(); ++i) stream << "NOISE SIZE " << i << " (NRMSE MODEL)\t"; stream << "\n"; stream.flush(); file.close(); } void ViInterpolatorBatcher::printFileDataAll(QString filepath, ViErrorCollection &interpolationErrors, ViErrorCollection &modelErrors, const qint64 &time) { int i; QFile file(filepath); file.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream stream(&file); for(i = 0; i < mParamsStart.size(); ++i) stream << (int) mParamsCurrent[i] << "\t"; stream << interpolationErrors.nrmse() << "\t" << modelErrors.nrmse() << "\t" << time << "\t\t"; for(i = ViNoiseCreator::minimumNoiseSize(); i <= ViNoiseCreator::maximumNoiseSize(); ++i) stream << interpolationErrors[i].nrmse() << "\t"; stream << "\t"; for(i = ViNoiseCreator::minimumNoiseSize(); i <= ViNoiseCreator::maximumNoiseSize(); ++i) stream << modelErrors[i].nrmse() << "\t"; stream << "\n"; stream.flush(); } void ViInterpolatorBatcher::printFileDataMinified(QString filepath, ViErrorCollection &interpolationErrors, ViErrorCollection &modelErrors, const qint64 &time) { int i; if(interpolationErrors.nrmse() >= 0 && time != 0) { QFile file(filepath); file.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream stream(&file); for(i = 0; i < mParamsStart.size(); ++i) stream << (int) mParamsCurrent[i] << "\t"; stream << interpolationErrors.nrmse() << "\t" << modelErrors.nrmse() << "\t" << time << "\t\t"; for(i = ViNoiseCreator::minimumNoiseSize(); i <= ViNoiseCreator::maximumNoiseSize(); ++i) stream << interpolationErrors[i].nrmse() << "\t"; stream << "\t"; for(i = ViNoiseCreator::minimumNoiseSize(); i <= ViNoiseCreator::maximumNoiseSize(); ++i) stream << modelErrors[i].nrmse() << "\t"; stream << "\n"; stream.flush(); } } void ViInterpolatorBatcher::printFileDataSummary(QString genre, ViErrorCollection &interpolationErrors, ViErrorCollection &modelErrors, const qint64 &time) { int i; QString filepath = ""; for(i = 0; i < mSummaryFiles.size(); ++i) { if(mSummaryFiles[i].contains(genre)) { filepath = mSummaryFiles[i]; break; } } if(filepath == "") return; QFile file(filepath); file.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream stream(&file); for(i = 0; i < mParamsStart.size(); ++i) stream << (int) mParamsCurrent[i] << "\t"; stream << interpolationErrors.nrmse() << "\t" << modelErrors.nrmse() << "\t" << time << "\t\t"; for(i = ViNoiseCreator::minimumNoiseSize(); i <= ViNoiseCreator::maximumNoiseSize(); ++i) stream << interpolationErrors[i].nrmse() << "\t"; stream << "\t"; for(i = ViNoiseCreator::minimumNoiseSize(); i <= ViNoiseCreator::maximumNoiseSize(); ++i) stream << modelErrors[i].nrmse() << "\t"; stream << "\n"; stream.flush(); } QString ViInterpolatorBatcher::genre(QString path) { path = path.replace("/home/visore/Visore Projects/Files/", ""); int i = path.indexOf("/"); if(i < 0) return ""; return path.left(i).replace("/", ""); } void ViInterpolatorBatcher::printTerminal(ViErrorCollection &interpolationErrors, ViErrorCollection &modelErrors, const qint64 &time) { qreal percentageDone = mDoneParamIterations / qreal(mTotalParamIterations); qint64 remaining = mMainTime.elapsed(); remaining = ((1.0 / percentageDone) * remaining) - remaining; qreal best = interpolationErrors.nrmse(); if(best >=0 && best < mBestScore) mBestScore = best; cout << int(percentageDone * 100.0) << "%\t(" << timeConversion(remaining).toLatin1().data() << ")\t"; cout << "INTERPOLATION NRMSE: " << setprecision(12) << interpolationErrors.nrmse() << " (" << setprecision(6) << mBestScore << ")\tMODEL NRMSE: " << setprecision(6) << modelErrors.nrmse() << "\tTIME: " << time << endl; } QString ViInterpolatorBatcher::timeConversion(int msecs) { QString formattedTime; int days = msecs / 86400000; int hours = (msecs - (days * 86400000)) / 3600000; int minutes = (msecs - (days * 86400000) - (hours * 3600000)) / 60000; int seconds = (msecs - (days * 86400000) - (minutes * 60000) - (hours * 3600000)) / 1000; formattedTime.append(QString("%1").arg(days, 2, 10, QLatin1Char('0')) + ":" + QString("%1").arg(hours, 2, 10, QLatin1Char('0')) + ":" + QString( "%1" ).arg(minutes, 2, 10, QLatin1Char('0')) + ":" + QString( "%1" ).arg(seconds, 2, 10, QLatin1Char('0'))); return formattedTime; } void ViInterpolatorBatcher::quit() { ++mQuitCount; if(WRITE && mQuitCount < 2) return; cout << "QUIT!" << endl; exit(0); }
8fe432f1a9376fde710ce9c98fb614176a4b2964
564c21649799b8b59f47d6282865f0cf745b1f87
/chrome/browser/ui/search/search_ipc_router.cc
2dcba5b33f323cc35d6a805463fd113e78a82cdc
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
pablosalazar7/WebARonARCore
e41f6277dd321c60084abad635819e0f70f2e9ff
43c5db480e89b59e4ae6349e36d8f375ee12cc0d
refs/heads/webarcore_57.0.2987.5
2023-02-23T04:58:12.756320
2018-01-17T17:40:20
2018-01-24T04:14:02
454,492,900
1
0
NOASSERTION
2022-02-01T17:56:03
2022-02-01T17:56:02
null
UTF-8
C++
false
false
10,158
cc
search_ipc_router.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/search/search_ipc_router.h" #include <utility> #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/search.h" #include "chrome/common/render_messages.h" #include "components/search/search.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/associated_interface_provider.h" #include "content/public/common/child_process_host.h" namespace { bool IsRenderedInInstantProcess(content::WebContents* web_contents) { // TODO(tibell): Instead of rejecting messages check at connection time if we // want to talk to the render frame or not. Later, in an out-of-process iframe // world, the IsRenderedInInstantProcess check will have to be done, as it's // based on the RenderView. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); return search::IsRenderedInInstantProcess(web_contents, profile); } class SearchBoxClientFactoryImpl : public SearchIPCRouter::SearchBoxClientFactory { public: // The |web_contents| must outlive this object. explicit SearchBoxClientFactoryImpl(content::WebContents* web_contents) : web_contents_(web_contents), last_connected_rfh_( std::make_pair(content::ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)) {} chrome::mojom::SearchBox* GetSearchBox() override; private: content::WebContents* web_contents_; chrome::mojom::SearchBoxAssociatedPtr search_box_; // The proccess ID and routing ID of the last connected main frame. May be // (ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE) if we haven't // connected yet. std::pair<int, int> last_connected_rfh_; DISALLOW_COPY_AND_ASSIGN(SearchBoxClientFactoryImpl); }; chrome::mojom::SearchBox* SearchBoxClientFactoryImpl::GetSearchBox() { content::RenderFrameHost* frame = web_contents_->GetMainFrame(); auto id = std::make_pair(frame->GetProcess()->GetID(), frame->GetRoutingID()); // Avoid reconnecting repeatedly to the same RenderFrameHost for performance // reasons. if (id != last_connected_rfh_) { if (IsRenderedInInstantProcess(web_contents_)) { frame->GetRemoteAssociatedInterfaces()->GetInterface(&search_box_); } else { // Renderer is not an instant process. We'll create a connection that // drops all messages. mojo::GetIsolatedProxy(&search_box_); } last_connected_rfh_ = id; } return search_box_.get(); } } // namespace SearchIPCRouter::SearchIPCRouter(content::WebContents* web_contents, Delegate* delegate, std::unique_ptr<Policy> policy) : WebContentsObserver(web_contents), delegate_(delegate), policy_(std::move(policy)), commit_counter_(0), is_active_tab_(false), bindings_(web_contents, this), search_box_client_factory_(new SearchBoxClientFactoryImpl(web_contents)) { DCHECK(web_contents); DCHECK(delegate); DCHECK(policy_.get()); } SearchIPCRouter::~SearchIPCRouter() {} void SearchIPCRouter::OnNavigationEntryCommitted() { ++commit_counter_; search_box()->SetPageSequenceNumber(commit_counter_); } void SearchIPCRouter::DetermineIfPageSupportsInstant() { search_box()->DetermineIfPageSupportsInstant(); } void SearchIPCRouter::SendChromeIdentityCheckResult( const base::string16& identity, bool identity_match) { if (!policy_->ShouldProcessChromeIdentityCheck()) return; search_box()->ChromeIdentityCheckResult(identity, identity_match); } void SearchIPCRouter::SendHistorySyncCheckResult(bool sync_history) { if (!policy_->ShouldProcessHistorySyncCheck()) return; search_box()->HistorySyncCheckResult(sync_history); } void SearchIPCRouter::SetSuggestionToPrefetch( const InstantSuggestion& suggestion) { if (!policy_->ShouldSendSetSuggestionToPrefetch()) return; search_box()->SetSuggestionToPrefetch(suggestion); } void SearchIPCRouter::SetInputInProgress(bool input_in_progress) { if (!policy_->ShouldSendSetInputInProgress(is_active_tab_)) return; search_box()->SetInputInProgress(input_in_progress); } void SearchIPCRouter::OmniboxFocusChanged(OmniboxFocusState state, OmniboxFocusChangeReason reason) { if (!policy_->ShouldSendOmniboxFocusChanged()) return; search_box()->FocusChanged(state, reason); } void SearchIPCRouter::SendMostVisitedItems( const std::vector<InstantMostVisitedItem>& items) { if (!policy_->ShouldSendMostVisitedItems()) return; search_box()->MostVisitedChanged(items); } void SearchIPCRouter::SendThemeBackgroundInfo( const ThemeBackgroundInfo& theme_info) { if (!policy_->ShouldSendThemeBackgroundInfo()) return; search_box()->ThemeChanged(theme_info); } void SearchIPCRouter::Submit(const base::string16& text, const EmbeddedSearchRequestParams& params) { if (!policy_->ShouldSubmitQuery()) return; search_box()->Submit(text, params); } void SearchIPCRouter::OnTabActivated() { is_active_tab_ = true; } void SearchIPCRouter::OnTabDeactivated() { is_active_tab_ = false; } void SearchIPCRouter::InstantSupportDetermined(int page_seq_no, bool instant_support) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(instant_support); } void SearchIPCRouter::FocusOmnibox(int page_seq_no, OmniboxFocusState state) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); if (!policy_->ShouldProcessFocusOmnibox(is_active_tab_)) return; delegate_->FocusOmnibox(state); } void SearchIPCRouter::SearchBoxDeleteMostVisitedItem(int page_seq_no, const GURL& url) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); if (!policy_->ShouldProcessDeleteMostVisitedItem()) return; delegate_->OnDeleteMostVisitedItem(url); } void SearchIPCRouter::SearchBoxUndoMostVisitedDeletion(int page_seq_no, const GURL& url) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); if (!policy_->ShouldProcessUndoMostVisitedDeletion()) return; delegate_->OnUndoMostVisitedDeletion(url); } void SearchIPCRouter::SearchBoxUndoAllMostVisitedDeletions(int page_seq_no) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); if (!policy_->ShouldProcessUndoAllMostVisitedDeletions()) return; delegate_->OnUndoAllMostVisitedDeletions(); } void SearchIPCRouter::LogEvent(int page_seq_no, NTPLoggingEventType event, base::TimeDelta time) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); if (!policy_->ShouldProcessLogEvent()) return; delegate_->OnLogEvent(event, time); } void SearchIPCRouter::LogMostVisitedImpression( int page_seq_no, int position, ntp_tiles::NTPTileSource tile_source) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); // Logging impressions is controlled by the same policy as logging events. if (!policy_->ShouldProcessLogEvent()) return; delegate_->OnLogMostVisitedImpression(position, tile_source); } void SearchIPCRouter::LogMostVisitedNavigation( int page_seq_no, int position, ntp_tiles::NTPTileSource tile_source) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); // Logging navigations is controlled by the same policy as logging events. if (!policy_->ShouldProcessLogEvent()) return; delegate_->OnLogMostVisitedNavigation(position, tile_source); } void SearchIPCRouter::PasteAndOpenDropdown(int page_seq_no, const base::string16& text) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); if (!policy_->ShouldProcessPasteIntoOmnibox(is_active_tab_)) return; delegate_->PasteIntoOmnibox(text); } void SearchIPCRouter::ChromeIdentityCheck(int page_seq_no, const base::string16& identity) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); if (!policy_->ShouldProcessChromeIdentityCheck()) return; delegate_->OnChromeIdentityCheck(identity); } void SearchIPCRouter::HistorySyncCheck(int page_seq_no) { if (!IsRenderedInInstantProcess(web_contents())) return; if (page_seq_no != commit_counter_) return; delegate_->OnInstantSupportDetermined(true); if (!policy_->ShouldProcessHistorySyncCheck()) return; delegate_->OnHistorySyncCheck(); } void SearchIPCRouter::set_delegate_for_testing(Delegate* delegate) { DCHECK(delegate); delegate_ = delegate; } void SearchIPCRouter::set_policy_for_testing(std::unique_ptr<Policy> policy) { DCHECK(policy); policy_ = std::move(policy); }
ba4a6d4a04aef07bd61d6b7833dc19b484152998
31589435071cbff4c5e95b357d8f3fa258f43269
/PPTVForWin8/ppbox_1.2.0/src/p2p/server_mod/supernode/LocalDiskCache/SmallFileMode/SmallFileLocalDisk.h
c9cbec601eef0419662a04a803a1fd29dd4484a5
[]
no_license
huangyt/MyProjects
8d94656f41f6fac9ae30f089230f7c4bfb5448ac
cd17f4b0092d19bc752d949737c6ed3a3ef00a86
refs/heads/master
2021-01-17T20:19:35.691882
2013-05-03T07:19:31
2013-05-03T07:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,545
h
SmallFileLocalDisk.h
#ifndef SUPER_NODE_SMALL_FILE_LOCAL_DISK_H #define SUPER_NODE_SMALL_FILE_LOCAL_DISK_H #include "../LocalDisk.h" #include <boost/thread/mutex.hpp> #include <boost/thread/condition.hpp> #include "../../PriorityTasksQueue.h" // #include "../LocalDiskCache.h" #include "DiskTask.h" #include "../../ServiceHealthMonitor/ServiceComponent.h" namespace super_node { class SmallFileLocalDisk : public ILocalDisk, public IServiceComponentHealthPredicate, public boost::enable_shared_from_this<SmallFileLocalDisk>, public count_object_allocate<SmallFileLocalDisk> { public: SmallFileLocalDisk(const string& file_path); void Start(); void Stop(); void UpdateConfig(); bool AsyncRead(const ResourceIdentifier& resource_identifier, int block_index, int read_priority, ReadResourceBlockCallback callback); bool AsyncWrite(const ResourceIdentifier& resource_identifier, const std::map<size_t, boost::shared_ptr<BlockData> >& blocks, WriteResourceTaskCallback callback); bool AsyncLoadResources(LoadResourcesTaskCallback callback, bool delete_resource_on_error); bool AsyncDeleteResources(const std::vector<ResourceIdentifier>& resources, DeleteResourcesTaskCallback callback); boost::filesystem::path GetResourceBlockFilePath(const ResourceIdentifier& resource_identifier, size_t block_index) const; boost::filesystem::path GetResourceFolderPath(const ResourceIdentifier& resource_identifier) const; boost::filesystem::path GetDiskPath() const { return disk_path_; } //these functions do NOT actually add/remove/update resources, //they are exposed for disk tasks to notify disk statistics to update disk space used as appropriate void UpdateResources(const std::vector<boost::shared_ptr<DiskResource> >& resources); void UpdateResource(const ResourceIdentifier& resource_identifier); void RemoveResource(const ResourceIdentifier& resource_identifier); size_t GetFreeSpacePercentage() const; boost::uint64_t GetDiskSpaceInBytes() const; bool IsComponentHealthy() const; protected: //for unittestability bool EnqueueTask(boost::shared_ptr<DiskTask> task); private: void DiskThread(); void ReportStatus(boost::uint32_t ticks_since_last_report); static string GetBlockFileName(size_t block_index); string DiskComponentName() const; void DropPendingTasks(); private: static const int QueueSize; PriorityTasksQueue<DiskTask> pending_tasks_; boost::filesystem::path disk_path_; bool stopped_; boost::mutex mutex_; boost::condition condition_; boost::shared_ptr<boost::thread> disk_thread_; boost::shared_ptr<DiskStatistics> disk_statistics_; boost::shared_ptr<ComponentStatusItem> disk_read_speed_; boost::shared_ptr<ComponentStatusItem> disk_read_count_; boost::shared_ptr<ComponentStatusItem> disk_read_failure_rate_; boost::shared_ptr<ComponentStatusItem> disk_read_consecutive_failures_; boost::shared_ptr<ComponentStatusItem> disk_write_speed_; boost::shared_ptr<ComponentStatusItem> disk_write_count_; boost::shared_ptr<ComponentStatusItem> disk_write_failure_rate_; boost::shared_ptr<ComponentStatusItem> disk_write_consecutive_failures_; boost::shared_ptr<ComponentStatusItem> max_queue_length_; boost::shared_ptr<ComponentStatusItem> average_queue_length_; boost::shared_ptr<ComponentStatusItem> queue_drop_rate_; boost::uint32_t disk_task_failed_times_; boost::uint32_t disk_task_failed_times_since_last_success_; }; } #endif
ee6795ff6d456dab5f3858ca3fbf6b1321c81c23
538e1bad9045aeb4f6fbf93453d20c2c2a874d2b
/10.iterator/vector_randomiterANDlist_bothiter.cpp
c3ac447c7c7bff3766bd7d0741d878637ca4a99b
[]
no_license
rim0621/Cpp-study
849b7d2719e3d4765b85ed7d503b99d4472e1610
383a1c3845d8066421b96b4d488cf46c9e1b47bb
refs/heads/master
2021-09-19T23:34:35.310590
2018-08-01T11:32:59
2018-08-01T11:32:59
95,458,267
0
0
null
null
null
null
UTF-8
C++
false
false
863
cpp
vector_randomiterANDlist_bothiter.cpp
#include<iostream> #include<vector> #include<list> using namespace std; class Point { int x; int y; public: explicit Point(int _x=0, int _y=0):x(_x),y(_y){} void Print() const { cout<<x<<" , "<<y<<endl;} }; int main() { vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); list<int> lt; lt.push_back(10); lt.push_back(20); lt.push_back(30); vector<int>::iterator viter=v.begin(); list<int>::iterator liter=lt.begin(); cout<<*viter<<endl; cout<<*liter<<endl; viter+=2; //임의 접근 반복자는 가능 //liter+=2 ; //양방향 반복자는 불가능 cout<<*viter<<endl; vector<Point> ptVector; ptVector.push_back(Point(2,5)); list<Point> ptList; ptList.push_back(Point(2,5)); vector<Point>::iterator ptV=ptVector.begin(); list<Point>::iterator ptL=ptList.begin(); ptV->Print(); ptL->Print(); return 0; }
87a0406772544f124efd82c82786fe78f8398377
2b384cad54b5037edd9e4f18b4c67f38148e510d
/Database.cpp
ce958cd2dc0b705b32a7548e36b464e17636bddc
[]
no_license
atripathy86/srn
3801988636fa3098fca010c5ec8f86219085c016
592d56d0d566156f65b198b4507d9a7f282453b5
refs/heads/master
2016-09-06T19:58:54.252263
2013-02-23T03:28:32
2013-02-23T03:28:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,512
cpp
Database.cpp
#include "ForwardDeclaration.hpp" #include "Database.hpp" #include "Input.hpp" //#include <cmath> #include "ForwardDeclaration.hpp" //Got from hpp #include "Input.hpp" //Got from hpp #include "Infrastructure.hpp" //Added , troubleshooot circular hpp depepndency if this one gives problem Database::Database(Infrastructure* passed_If_ptr) //constructor //Database::Database(InputParameters *passed_param_ptr) { If_ptr = passed_If_ptr; param_ptr = If_ptr->param_ptr; //param_ptr = passed_param_ptr; Queries_sent_from_ResourceNode =0; //unique : (query_seq_no + source_node) Queries_sent_from_RouterNode =0 ; //unique Queries_forwarded_by_RouterNode_orgininated_from_ResourceNode =0; Queries_forwarded_by_RouterNode_orgininated_from_RouterNode =0; Responses_sent_from_ResourceNode =0; Responses_sent_from_RouterNode =0; //Num_responses_sent =0;// # unique -- node that generates the respnse + query seq that triggerred this response Num_of_good_responses =0 ;//rx decides whether it is a good response or not, not yet implemented with full meaning, for now any response received from a router node is a good response. Num_duplicate_message_dropped =0; Num_message_dropped_for_TTL =0; Num_queries_dropped_for_TTL=0; Num_responses_dropped_for_TTL=0; Num_total_message_generated = 0; //Suneil-total load on the network, /* DatabaseHistResolution=0; DatabaseMaxHops=0; DatabaseHistResolution=param_ptr->DatabaseHistResolution; //user input param : Default is 5 if (DatabaseHistResolution==0) //catch if defaults didn't come in for whatever reason DatabaseHistResolution=5; //if so, give it the default DatabaseMaxHops=param_ptr->DatabaseMaxHops; //user input param : Default is 100 if (DatabaseMaxHops==0) //catch if defaults didn't come in for whatever reason DatabaseMaxHops=100; //if so, give it the default */ num_buckets = (param_ptr->DatabaseMaxHops/param_ptr->DatabaseHistResolution) ; //rename the counter array -- to be called hops_before_response_ctr //add array -- longevity_of_message_ctr_for_TTL //modify function to calculate for both arrays. as second argument add the type --i.e which array to increment. hops_before_response_ctr= new unsigned int[num_buckets+2]; //the +2 : 1 - catch_all bucket, 1 - 0 hop bucket, just-in-case if (!hops_before_response_ctr) { cout << "Database::Database():Error: memory could not be allocated for hops_before_response_ctr"; exit(1); } memset(hops_before_response_ctr,0,(num_buckets+2)*4); //set all counters to zero longevity_of_message_ctr_for_TTL= new unsigned int[num_buckets+2]; //the +2 : 1 - catch_all bucket, 1 - 0 hop bucket, just-in-case if (!longevity_of_message_ctr_for_TTL) { cout << "Database::Database():Error: memory could not be allocated for longevity_of_message_ctr_for_TTL"; exit(1); } memset(longevity_of_message_ctr_for_TTL,0,(num_buckets+2)*4); //set all counters to zero longevity_of_message_ctr_for_loop = new unsigned int[num_buckets+2]; //the +2 : 1 - catch_all bucket, 1 - 0 hop bucket, just-in-case if (!longevity_of_message_ctr_for_loop) { cout << "Database::Database():Error: memory could not be allocated for longevity_of_message_ctr_for_loop"; exit(1); } memset(longevity_of_message_ctr_for_loop,0,(num_buckets+2)*4); //set all counters to zero //To record how many resoource exist with specific tag (the index), get total num of tags from ontology rep num_resource_with_specific_tag = new unsigned int[ param_ptr->num_words]; //the +2 : 1 - catch_all bucket, 1 - 0 hop bucket, just-in-case num_router_with_specific_tag = new unsigned int[ param_ptr->num_words]; //the +2 : 1 - catch_all bucket, 1 - 0 hop bucket, just-in-case if (!num_resource_with_specific_tag || !num_router_with_specific_tag) { cout << "Database::Database():Error: memory could not be allocated for num_resource_with_specific_tag or num_router_with_specific_tag"; exit(1); } memset(num_resource_with_specific_tag,0, param_ptr->num_words*4); //set all counters to zero memset(num_router_with_specific_tag,0, param_ptr->num_words*4); //set all counters to zero Num_of_good_responses_for_specific_tag = new unsigned int[ param_ptr->num_words]; //the +2 : 1 - catch_all bucket, 1 - 0 hop bucket, just-in-case if (!Num_of_good_responses_for_specific_tag) { cout << "Database::Database():Error: memory could not be allocated for Num_of_good_responses_for_specific_tag"; exit(1); } memset(Num_of_good_responses_for_specific_tag,0, param_ptr->num_words*4 ); //set all counters to zero Num_of_queries_for_specific_tag = new unsigned int[ param_ptr->num_words]; //the +2 : 1 - catch_all bucket, 1 - 0 hop bucket, just-in-case if (!Num_of_queries_for_specific_tag) { cout << "Database::Database():Error: memory could not be allocated for Num_of_queries_for_specific_tag_from_UserNode"; exit(1); } memset(Num_of_queries_for_specific_tag,0, param_ptr->num_words*4 ); //set all counters to zero //UserNode counters Queries_sent_from_UserNode=0; Num_responses_sent_for_UserNode=0; Num_of_good_responses_for_UserNode=0; Num_duplicate_message_dropped_for_UserNode=0; Num_queries_dropped_for_TTL_for_UserNode=0; //Suneil | ctr number_queries dropped for ttl //figure out from where you are updating the above ctr. Num_responses_dropped_for_TTL_for_UserNode=0;// Suneil | ctr number_responses dropped for ttl. Num_reponses_dropped_when_no_active_listeners =0; Num_reponses_dropped_when_no_active_listeners_for_UserNode =0; num_buckets_for_UserNode= (param_ptr->DatabaseMaxHops_for_UserNode/param_ptr->DatabaseHistResolution_for_UserNode); hops_before_response_ctr_for_UserNode = new unsigned int[num_buckets_for_UserNode + 2]; if (!hops_before_response_ctr_for_UserNode) { cout << "Database::Database():Error: memory could not be allocated for hops_before_response_ctr_for_UserNode"; exit(1); } memset(hops_before_response_ctr_for_UserNode,0,(num_buckets_for_UserNode + 2)*4); //set all counters to zero longevity_of_message_ctr_for_TTL_for_UserNode = new unsigned int[num_buckets_for_UserNode + 2]; if (!longevity_of_message_ctr_for_TTL_for_UserNode) { cout << "Database::Database():Error: memory could not be allocated for longevity_of_message_ctr_for_TTL_for_UserNode"; exit(1); } memset(longevity_of_message_ctr_for_TTL_for_UserNode,0,(num_buckets_for_UserNode + 2)*4); //set all counters to zero longevity_of_message_ctr_for_loop_for_UserNode = new unsigned int[num_buckets_for_UserNode + 2]; if (!longevity_of_message_ctr_for_loop_for_UserNode) { cout << "Database::Database():Error: memory could not be allocated for longevity_of_message_ctr_for_loop_for_UserNode"; exit(1); } memset(longevity_of_message_ctr_for_loop_for_UserNode,0,(num_buckets_for_UserNode + 2)*4); //set all counters to zero Num_of_good_responses_for_specific_tag_for_UserNode = new unsigned int[ param_ptr->num_words]; if (!Num_of_good_responses_for_specific_tag_for_UserNode) { cout << "Database::Database():Error: memory could not be allocated for Num_of_good_responses_for_specific_tag_for_UserNode"; exit(1); } memset(Num_of_good_responses_for_specific_tag_for_UserNode,0, param_ptr->num_words*4); //set all counters to zero Num_of_queries_for_specific_tag_from_UserNode = new unsigned int[ param_ptr->num_words]; //the +2 : 1 - catch_all bucket, 1 - 0 hop bucket, just-in-case if (!Num_of_queries_for_specific_tag_from_UserNode) { cout << "Database::Database():Error: memory could not be allocated for Num_of_queries_for_specific_tag_from_UserNode"; exit(1); } memset(Num_of_queries_for_specific_tag_from_UserNode,0, param_ptr->num_words*4); //set all counters to zero //sm24, Amit - 25 Aug Num_total_queries_generated = 0; Num_total_responses_generated = 0; return; }; //close of constructor Database::~Database() //destructor { #ifdef DEBUG printf("Started cleaning up for Database\n"); #endif delete [] num_resource_with_specific_tag; delete[] longevity_of_message_ctr_for_TTL; delete[] hops_before_response_ctr; delete[] Num_of_good_responses_for_specific_tag; delete [] Num_of_queries_for_specific_tag; //UserNode counters delete[] longevity_of_message_ctr_for_TTL_for_UserNode; delete[] hops_before_response_ctr_for_UserNode; delete[] Num_of_good_responses_for_specific_tag_for_UserNode; delete [] Num_of_queries_for_specific_tag_from_UserNode; #ifdef DEBUG printf("Finished cleaning up for Database\n"); #endif return; }//close of destructor /* void Database::take_snapshot() { } //close of take_snapsot */ //Suneil, pls update the method with user node couunters void Database::record_hops(unsigned int hop_count, unsigned int *passed_ctr) { histogram_index = hop_count/ param_ptr->DatabaseHistResolution; /* float temp; int i; if (hop_count==0) //if zero hops, increment that { ++(passed_ctr[0]); return; } else */ if (hop_count > param_ptr->DatabaseMaxHops ) //if a value greater than the permitted number of hops then push to overflow bucket { //++(passed_ctr[DatabaseMaxHops]); (passed_ctr[histogram_index +1])++; return; } else {//all other cases, increment appropriate bucket; //temp=(hop_count/DatabaseHistResolution); //i=(int) ceil(temp); (passed_ctr[histogram_index])++; return; } }//close of hops_at_resposnses /* //Suneil, pls update the method with user node couunters void Database::hops_before_response(unsigned int hop_count, MessageType message_type) { float temp; int i; switch (message_type) { case QUERY: {//1=Query if (hop_count==0) //if zero hops, increment that { ++(longevity_of_message_ctr_for_TTL[0]); return; } else if (hop_count >DatabaseMaxHops ) //if a value greater than the permitted number of hops then push to overflow bucket {++(longevity_of_message_ctr_for_TTL[DatabaseMaxHops]); return; } else {//all other cases, increment appropriate bucket; temp=(hop_count/DatabaseHistResolution); i=(int) ceil(temp); ++(longevity_of_message_ctr_for_TTL[i]); return; } break; } case RESPONSE: { //2=Response if (hop_count==0) //if zero hops, increment that { ++(hops_before_response_ctr[0]); return; } else if (hop_count >DatabaseMaxHops ) //if a value greater than the permitted number of hops then push to overflow bucket {++(hops_before_response_ctr[DatabaseMaxHops]); return; } else {//all other cases, increment appropriate bucket; temp=(hop_count/DatabaseHistResolution); i=(int) ceil(temp); ++(hops_before_response_ctr[i]); return; } break; } default:{ cout<<"ERROR::Bad Type Identifier for type of drop at hops_at_response"; break; } }//close of switch }//close of hops_at_resposnses */
c921cb9a31930e22b5bb7370cc06f3377e377292
80bd05d46731a7e21d5e3ba17d4d86aef8ab2694
/Antario/Hooks.h
57c70ff91f6b9c85e7c963d77cf07e0b55c40c1f
[ "MIT" ]
permissive
qq1091192337/censoredwin
e2943bf9f5bf5223e78325d31eb9df639da70c7c
43544438b0930711d2cf9cd879fbba75ebf6da80
refs/heads/master
2020-04-12T13:56:17.491874
2018-12-19T20:23:27
2018-12-19T20:23:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,921
h
Hooks.h
#pragma once #include "Utils\DrawManager.h" #include "Utils\Interfaces.h" #include "SDK\IClientMode.h" #include "SDK\ISurface.h" #include "EventListener.h" #include "SDK\CInput.h" #include "GUI\GUI.h" #include "SDK/IVModelRender.h" namespace vtable_indexes { constexpr auto reset = 16; constexpr auto present = 17; constexpr auto createMove = 24; constexpr auto lockCursor = 67; constexpr auto sceneend = 9; constexpr auto dme = 21; constexpr auto msh = 42; } class VMTHook; class Hooks { public: // Initialization setup, called on injection static void Init(); static void Restore(); /*---------------------------------------------*/ /*-------------Hooked functions----------------*/ /*---------------------------------------------*/ static bool __fastcall CreateMove( IClientMode*, void*, float, CUserCmd* ); static void __fastcall LockCursor( ISurface*, void* ); static HRESULT __stdcall Reset( IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentationParameters ); static void __fastcall SceneEnd( void* thisptr, void* edx ); static HRESULT __stdcall Present( IDirect3DDevice9* pDevice, const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion ); static LRESULT __stdcall WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); static void __fastcall DME( void*, void*, IMatRenderContext*, const DrawModelState_t&, const ModelRenderInfo_t&, matrix3x4_t* ); static void __fastcall BeginFrame( void *thisptr, void*, float ft ); private: /*---------------------------------------------*/ /*-------------VMT Hook pointers---------------*/ /*---------------------------------------------*/ std::unique_ptr<VMTHook> pD3DDevice9Hook; std::unique_ptr<VMTHook> pClientModeHook; std::unique_ptr<VMTHook> pSurfaceHook; std::unique_ptr<VMTHook> pSceneEndHook; std::unique_ptr<VMTHook> pDMEHook; std::unique_ptr<VMTHook> pMaterialSystemHook; /*---------------------------------------------*/ /*-------------Hook prototypes-----------------*/ /*---------------------------------------------*/ typedef bool( __fastcall* CreateMove_t ) (IClientMode*, void*, float, CUserCmd*); typedef void( __fastcall* LockCursor_t ) (ISurface*, void*); typedef long( __stdcall* Reset_t ) (IDirect3DDevice9*, D3DPRESENT_PARAMETERS*); typedef long( __stdcall* Present_t ) (IDirect3DDevice9*, const RECT*, const RECT*, HWND, const RGNDATA*); typedef void( __thiscall* SceneEnd_t ) (void*); typedef void( __thiscall* DrawModelExecute_t )(void*, IMatRenderContext*, const DrawModelState_t&, const ModelRenderInfo_t&, matrix3x4_t*); typedef void( __thiscall *BeginFrame_t )(void*, float); private: ui::MenuMain nMenu; HWND hCSGOWindow = nullptr; // CSGO window handle bool bInitializedDrawManager = false; // Check if we initialized our draw manager WNDPROC pOriginalWNDProc = nullptr; // Original CSGO window proc std::unique_ptr<EventListener> pEventListener = nullptr; // Listens to csgo events, needs to be created }; extern Hooks g_Hooks; class VMTHook { public: VMTHook( void* ppClass ) { this->ppBaseClass = static_cast<std::uintptr_t**>(ppClass); // loop through all valid class indexes. When it will hit invalid (not existing) it will end the loop while (static_cast<std::uintptr_t*>(*this->ppBaseClass)[this->indexCount]) ++this->indexCount; const std::size_t kSizeTable = this->indexCount * sizeof( std::uintptr_t ); this->pOriginalVMT = *this->ppBaseClass; this->pNewVMT = std::make_unique<std::uintptr_t[]>( this->indexCount ); // copy original vtable to our local copy of it std::memcpy( this->pNewVMT.get(), this->pOriginalVMT, kSizeTable ); // replace original class with our local copy *this->ppBaseClass = this->pNewVMT.get(); }; ~VMTHook() { *this->ppBaseClass = this->pOriginalVMT; }; template<class Type> Type GetOriginal( const std::size_t index ) { return reinterpret_cast<Type>(this->pOriginalVMT[index]); }; HRESULT Hook( const std::size_t index, void* fnNew ) { if (index > this->indexCount) // check if given index is valid return E_INVALIDARG; this->pNewVMT[index] = reinterpret_cast<std::uintptr_t>(fnNew); return S_OK; }; HRESULT Unhook( const std::size_t index ) { if (index > this->indexCount) return E_INVALIDARG; this->pNewVMT[index] = this->pOriginalVMT[index]; return S_OK; }; private: std::unique_ptr<std::uintptr_t[]> pNewVMT = nullptr; // Actual used vtable std::uintptr_t** ppBaseClass = nullptr; // Saved pointer to original class std::uintptr_t* pOriginalVMT = nullptr; // Saved original pointer to the VMT std::size_t indexCount = 0; // Count of indexes inside out f-ction };
39e8fe304e8b5e2a18120263188726e5b5d35a60
f3fc8bb9d386dbda07bd3ef4becd6a91abc8cbf5
/src/nebula/test/NebulaInstanceTest.cpp
333ff17f3a93da0fb6f77bddf7165e25f3dc0eae
[]
no_license
bright-starry-sky/nebula-chaos
abc492e48e25141df50ed4920c39204022cb1fbe
9046fd1afd588e5610828d76f309ec5c4d6acb1d
refs/heads/master
2022-12-14T23:01:28.412872
2020-09-01T07:00:06
2020-09-01T07:00:06
290,383,427
1
0
null
2020-08-26T03:17:37
2020-08-26T03:17:36
null
UTF-8
C++
false
false
1,204
cpp
NebulaInstanceTest.cpp
#include "common/Base.h" #include <gtest/gtest.h> #include <glog/logging.h> #include <folly/init/Init.h> #include "nebula/NebulaInstance.h" namespace nebula_chaos { namespace nebula { TEST(NebulaInstanceTest, DateTest) { auto installPath = folly::stringPrintf("%s/mock/nebula", NEBULA_STRINGIFY(NEBULA_CHAOS_HOME)); NebulaInstance instance("127.0.0.1", installPath, NebulaInstance::Type::STORAGE); CHECK(instance.init()); CHECK_EQ(10086, instance.getPid().value()); CHECK_EQ(44500, instance.getPort().value()); CHECK_EQ(12000, instance.getHttpPort().value()); auto dataDirs = instance.dataDirs(); CHECK(dataDirs.hasValue()); auto dirs = std::move(dataDirs).value(); CHECK_EQ(3, dirs.size()); int i = 0; for (auto& d : dirs) { CHECK_EQ(folly::stringPrintf("%s/data%d", installPath.c_str(), ++i), d); } } } // namespace utils } // namespace nebula_chaos int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); folly::init(&argc, &argv, true); google::SetStderrLogging(google::INFO); return RUN_ALL_TESTS(); }
402929b99d63a2473f5fb6d99053e853f9e90478
6d11dc6099e6679eb35428d6117c4955c1ff8861
/CarBluetooth/CarBluetooth.ino
abd6d8a3666eb8e59d0a49a0b0d925b8d58862e7
[]
no_license
lopdam/Arduino
11453df017625c1079dda97a1706c253e2e8bb1e
ec01ccb1c14e561e5ee392c04483703c010514c3
refs/heads/master
2020-04-21T23:03:18.682735
2019-03-22T16:47:01
2019-03-22T16:47:01
169,933,420
0
0
null
null
null
null
UTF-8
C++
false
false
7,300
ino
CarBluetooth.ino
#include <SoftwareSerial.h> #include <Servo.h> //Declaracion de las variables //Motor 1 Derecho const int M11=8; const int M12=7; //Motor 2 Izquierdo const int M22=4; const int M21=2; //Control de velocidad de los motores const int M1PWM=3; const int M2PWM=5; //Buzzer const int Buzzer=6; //Control del servo const int Serv=9; //Comunicacion con el cell const int RX=10;//Receptor const int TX=11;//Transmisor //Declarion de pines para el ultrasonido const int Echo=12;//Receptor const int Triger=13;//Transmisor //Declarion de variables temporales int vel=175;//velocidad por defecto int pos=20;//posicion minima que el servo puede llegar y 160 para la maxima apertura. int dis; // distancia del objeto char r;// Lectura de datos para saber que accion ejecutar long tiempoEntrada; // Almacena el tiempo de respuesta del sensor de entrada float distanciaEntrada; // Almacena la distancia en cm a la que se encuentra el objeto const int distmin=25;//es la distancia minima a la que puede estar ub objeto para esquivarlo //funcionamiento del sensorymotores //Creacion de Objetos Servo S;//Servo SoftwareSerial BT(RX,TX);//comunicacion con cell void setup() { S.attach(Serv); BT.begin(9600); //Declarion de modo de pines motor 1 pinMode (M11, OUTPUT); pinMode (M12, OUTPUT); //Declarion de modo de pines motor 2 pinMode (M21, OUTPUT); pinMode (M22, OUTPUT); //Declarion de modo de pines motor control de velocidad pinMode (M1PWM, OUTPUT); pinMode (M2PWM, OUTPUT); //Declarion de modo de pin para el Buzzer pinMode(Buzzer,OUTPUT); pinMode(Triger,OUTPUT); // El emisor emite por lo que es configurado como salida pinMode(Echo,INPUT); // El receptor recibe por lo que es configurado como entrada //Declaramos la velocidad inicializal analogWrite(M1PWM,vel); analogWrite(M2PWM,vel); // Accion que realiza el auto al inciarce Buzz();//pitido de encendido ServoInit();//movimiento del servo para comprobar que funcion Buzz();//pitido de inicio del ciclo loop } void loop() { //FunObs(); //Funciomiento por reconocimento de obastaculos FunBT();//Funcionamiento por control BT } void robotAvance() { // Motor Derecho // Al mantener un pin HIGH y el otro LOW el motor gira en un sentido digitalWrite (M11, HIGH); digitalWrite (M12, LOW); // Motor Izquierdo // Al mantener un pin HIGH y el otro LOW el motor gira en un sentido digitalWrite (M21, HIGH); digitalWrite (M22, LOW); } /* Función robotRetroceso: esta función hará que ambos motores se activen a máxima potencia en sentido contrario al anterior por lo que el robot avanzará hacia atrás */ void robotRetroceso() { // Motor Derecho // Al mantener un pin LOW y el otro HIGH el motor gira en sentido contrario al anterior digitalWrite (M11, LOW); digitalWrite (M12, HIGH); // Motor Izquierdo // Al mantener un pin LOW y el otro HIGH el motor gira en sentido contrario al anterior digitalWrite (M21, LOW); digitalWrite (M22, HIGH); } /* Función robotDerecha: esta función acccionará el motor izquierdo y parará el derecho por lo que el coche girará hacia la derecha (sentido horario) */ void robotIzquierda() { // Motor Derecho // Se activa el motor Derecho digitalWrite (M11, HIGH); digitalWrite (M12, LOW); // Motor Izquierdo // Se para el motor Izquierdo digitalWrite (M21, LOW); digitalWrite (M22, LOW); } /* Función robotIzquierda: esta función acccionará el motor derecho y parará el izquierdo por lo que el coche girará hacia la izquierda (sentido antihorario) */ void robotDerecha () { // Motor Derecho // Se para el motor Derecho digitalWrite (M11, LOW); digitalWrite (M12, LOW); // Motor Izquierdo // Se activa el motor Izquierdo digitalWrite (M21, HIGH); digitalWrite (M22, LOW); } /* Función robotParar: esta función parará ambos motores por lo que el robot se parará. */ void robotParar() { // Motor Derecho // Se para el motor Derecho digitalWrite (M11, LOW); digitalWrite (M12, LOW); // Motor Izquierdo // Se para el motor Izquierdo digitalWrite (M21, LOW); digitalWrite (M22, LOW); } //////////////////////////////////////////////////////////////////////////// //Funcionamiento del auto por medio del control Bt void FunBT(){ if(BT.available()) { r=BT.read(); if(r=='W'){ robotAvance(); } else if(r=='S'){ robotRetroceso();} else if(r=='A'){ robotIzquierda();} else if(r=='D'){ robotDerecha();} else if(r=='X'){ Buzz(); //Motor Derecho digitalWrite (M11, LOW); digitalWrite (M12, HIGH); // Motor Izquierdo // Se activa el motor Izquierdo digitalWrite (M21, HIGH); digitalWrite (M22, LOW); delay(1500); robotParar(); Buzz(); } else if(r=='F'){ if(vel<255){ vel+=10; analogWrite(M1PWM,vel); analogWrite(M2PWM,vel); } } else if(r=='f'){ if(vel>75){ vel-=10; analogWrite(M1PWM,vel); analogWrite(M2PWM,vel); } } else { robotParar(); } }} ///////////////////////////////////////////////////////////////////////////// // metodo para el buzzer y el servo void Buzz(){ tone(Buzzer,2200); delay(100); noTone(Buzzer); delay(50); tone(Buzzer,2200); delay(100); noTone(Buzzer); } void ServoInit(){ S.write(20);//mini para que no colisiones y 160 maximo for(int i=20;i <=160;i++){ S.write(i); delay(10); } for(int i=140;i >=40;i--){ S.write(i); delay(10); } for(int i=60;i <=120;i++){ S.write(i); delay(10); } for(int i=100;i >=80;i--){ S.write(i); delay(5); } for(int i=85;i <=95;i++){ S.write(i); delay(5); } S.write(90); } /////////////////////////////////////////////////////////////////////////////////////// //Funcionamiento del auto por medio de reconociminetos de obstaculos por el ultrasonido void FunObs(){ while(pos<=160){ pos++; S.write(pos); dis=sensorUltrasonidos(); if(dis<distmin && pos>=20 && pos<=80 ){ robotIzquierda(); delay(100); } else if(dis<distmin && pos>=80 && pos<=100){ robotRetroceso(); delay(100); } else if(dis<distmin && pos>=100 && pos<=160){ robotDerecha(); delay(100); } else{ robotAvance(); } delay(1); } while(pos>=20){ pos--; S.write(pos); dis=sensorUltrasonidos(); if(dis<distmin && pos>=20 && pos<=80 ){ robotIzquierda(); delay(100); } else if(dis<distmin && pos>=80 && pos<=100){ robotRetroceso(); delay(100); } else if(dis<distmin && pos>=100 && pos<=160){ robotDerecha(); delay(100); } else{ robotAvance(); } delay(1); } } //Funcionamiento del Ultrasonido int sensorUltrasonidos() { // Se inicializa el sensor de infrasonidos digitalWrite(Triger,LOW); // Para estabilizar delayMicroseconds(10); // Comenzamos las mediciones // Se envía una señal activando la salida trigger durante 10 microsegundos digitalWrite(Triger, HIGH); // envío del pulso ultrasónico delayMicroseconds(10); tiempoEntrada=pulseIn(Echo, HIGH); return distanciaEntrada= int(0.017*tiempoEntrada); // Fórmula para calcular la distancia en cm }
8de238f888b1ff4b04a1418437e352b7a368d4ac
a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3
/SDK/include/WildMagic4/SampleGraphics/Refraction/RefractionEffect.inl
bab982a75cdd8fa46ce007c2125c1e523303cd10
[ "BSL-1.0" ]
permissive
NikitaNikson/xray-2_0
00d8e78112d7b3d5ec1cb790c90f614dc732f633
82b049d2d177aac15e1317cbe281e8c167b8f8d1
refs/heads/master
2023-06-25T16:51:26.243019
2020-09-29T15:49:23
2020-09-29T15:49:23
390,966,305
1
0
null
null
null
null
UTF-8
C++
false
false
1,038
inl
RefractionEffect.inl
// Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 4.10.0 (2009/11/18) //---------------------------------------------------------------------------- inline void RefractionEffect::SetFresnelConstant (int i, float fValue) { m_afVConstant[i] = fValue; } //---------------------------------------------------------------------------- inline float RefractionEffect::GetFresnelConstant (int i) const { return m_afVConstant[i]; } //---------------------------------------------------------------------------- inline void RefractionEffect::SetEtaRatio (float fEtaRatio) { m_afVConstant[3] = fEtaRatio; } //---------------------------------------------------------------------------- inline float RefractionEffect::GetEtaRatio () const { return m_afVConstant[3]; } //----------------------------------------------------------------------------
ac6379bbb37b33512dca237190ffc02e5cba35dd
2725cbc61c571e59846fabf309ea331631b00295
/ui_talkw.h
0bb5e976eea0c197922b0a39884885c511fc252a
[]
no_license
bunny1985/detoks
40c21dee66f479625698b5acb8024d4d969c8f38
55fd4b154117d328c8962850a39246f542a02513
refs/heads/master
2018-12-28T09:31:33.763688
2010-07-16T05:48:44
2010-07-16T05:48:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,029
h
ui_talkw.h
/******************************************************************************** ** Form generated from reading UI file 'talkw.ui' ** ** Created: Sat 26. Jun 01:03:24 2010 ** by: Qt User Interface Compiler version 4.6.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_TALKW_H #define UI_TALKW_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QGridLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QPushButton> #include <QtGui/QTextEdit> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_talkw { public: QWidget *gridLayoutWidget; QGridLayout *gridLayout; QTextEdit *textEdit; QPushButton *pushButton; QLineEdit *lineEdit; QLabel *label; void setupUi(QWidget *talkw) { if (talkw->objectName().isEmpty()) talkw->setObjectName(QString::fromUtf8("talkw")); talkw->resize(515, 300); QIcon icon; icon.addFile(QString::fromUtf8(":/icons/zas/icons/konversation.png"), QSize(), QIcon::Normal, QIcon::Off); talkw->setWindowIcon(icon); talkw->setStyleSheet(QString::fromUtf8("\n" "border-color: rgb(126, 126, 126);\n" "\n" "font: 9pt \"Calibri\";\n" "border-style:outset;\n" "border-width: 2px;\n" "border-radius: 7px;\n" "\n" "margin: 3px;\n" "background-color: rgb(0, 0, 0);\n" "color: rgb(245, 245, 245);")); gridLayoutWidget = new QWidget(talkw); gridLayoutWidget->setObjectName(QString::fromUtf8("gridLayoutWidget")); gridLayoutWidget->setGeometry(QRect(0, 0, 521, 301)); gridLayout = new QGridLayout(gridLayoutWidget); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); gridLayout->setContentsMargins(0, 0, 0, 0); textEdit = new QTextEdit(gridLayoutWidget); textEdit->setObjectName(QString::fromUtf8("textEdit")); textEdit->setStyleSheet(QString::fromUtf8("background-color: rgb(208, 203, 236);\n" "color: rgb(0, 0, 0);")); textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); textEdit->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); textEdit->setAutoFormatting(QTextEdit::AutoAll); textEdit->setReadOnly(true); gridLayout->addWidget(textEdit, 1, 0, 1, 2); pushButton = new QPushButton(gridLayoutWidget); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setMaximumSize(QSize(100, 16777215)); gridLayout->addWidget(pushButton, 4, 1, 1, 1); lineEdit = new QLineEdit(gridLayoutWidget); lineEdit->setObjectName(QString::fromUtf8("lineEdit")); gridLayout->addWidget(lineEdit, 4, 0, 1, 1); label = new QLabel(gridLayoutWidget); label->setObjectName(QString::fromUtf8("label")); QFont font; font.setFamily(QString::fromUtf8("Calibri")); font.setPointSize(9); font.setBold(false); font.setItalic(false); font.setWeight(50); label->setFont(font); label->setFrameShape(QFrame::NoFrame); gridLayout->addWidget(label, 0, 0, 1, 2); retranslateUi(talkw); QMetaObject::connectSlotsByName(talkw); } // setupUi void retranslateUi(QWidget *talkw) { talkw->setWindowTitle(QApplication::translate("talkw", "Detoks Conversation box ", 0, QApplication::UnicodeUTF8)); pushButton->setText(QApplication::translate("talkw", "Wy\305\233lij", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("talkw", "Rozmowa z :", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class talkw: public Ui_talkw {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_TALKW_H
08a1e717faac668899c9011b589a50893c5a648a
ae6f83a1c625cd2a4ce164e76b1519d65cdfe8fa
/include/list.hpp
c18120ecefe96b1bc8f5fbbbc3cab766219bde78
[]
no_license
westefns-souza/trabalhoedb
acb8d6bd264c076d909e3d032af2b562e17b4ba5
25cbc643ee6f53c0f1ab2882a482503172affcd6
refs/heads/main
2023-01-24T17:14:11.525447
2020-11-30T02:08:12
2020-11-30T02:08:12
317,086,345
0
0
null
null
null
null
UTF-8
C++
false
false
978
hpp
list.hpp
#pragma once #include <iostream> #include "node.hpp" //Lista duplamente encadeada template<typename T> class List { public: List(); ~List(); size_t size(); void insertAt(T value, size_t position); // insere o elemento value na posição position. Complexidade: O(n). void removeAt(size_t position); // remove o elemento na posição position. Complexidade: O(n). void insertAtFront(T value); // insere o valor value na primeira posição da lista. Complexidade: O(1). void insertAtBack(T value); // insere o valor value na última posição da lista. Complexidade: O(1). void removeAtFront(); // remove o primeiro valor da lista. Complexidade: O(1). void removeAtBack(); // remove o último valor da lista. Complexidade: O(1). void print(); // Imprime todos os elementos da lista. Complexidade: O(N) private: size_t length; Node<T>* first; Node<T>* last; };
a25cc6991c8074fd18d8be5dac27d6bfb5657c2c
635c529d802e2d75073a76c2fe4f861f208d8948
/dsaC++/sorting/tempCodeRunnerFile.cpp
ee390f50585b921ebcb3d52e8a35f051af5a3f2a
[]
no_license
parduman/lovebabbar450
bca6c7c03ffc7c704b84e5c5971a80e16c8e897f
4b7bf64274fe77b3f398a782fb3fd234c138d697
refs/heads/master
2023-08-04T23:38:55.065388
2021-09-09T07:28:29
2021-09-09T07:28:29
369,904,777
0
0
null
null
null
null
UTF-8
C++
false
false
71
cpp
tempCodeRunnerFile.cpp
for(int i=0;i<arr.size();i++){ // cout <<arr[i] <<" "; // }
6417a56d5e0ad19b5b26b358b02d06a16d86d214
f3fa6e988b5f32dec3dcddff4021f992dfa5b908
/CContainer.cpp
dcf9ff30ae495cfed69763cadd43f05304bd6c0b
[]
no_license
stefankloepfer/labDevXGroupElitekh25
68ce57e34101be3dbb98b3a8b6696b0cd76952c3
6fabbfb803930edadeb6d1ba1ad9f4fab3c10fcd
refs/heads/master
2021-01-21T08:01:59.940095
2017-02-27T16:07:35
2017-02-27T16:07:35
83,329,372
0
0
null
2017-02-27T16:06:17
2017-02-27T16:06:17
null
UTF-8
C++
false
false
609
cpp
CContainer.cpp
/* * CContainer.cpp * * Created on: Feb 27, 2017 * Author: vmuser */ #include "CContainer.h" CContainer::CContainer() { id_ = 0; this->container_.empty(); fathymutex_ = new pthread_mutex_t(); } CContainer::~CContainer() { delete fathymutex_; }; CContainer::fillMyContainer(int& para) { container_.push_back(para); std::cout<<"Ich habe reingespeichert"<<para<<std::endl; }; CContainer::emptyMyContainer() { int variable=0; pthread_mutex_lock(&fathymutex_); variable = container_.pop_back(); pthread_mutex_unlock(&fathymutex_); std::cout<<"Ich habe rausgeholt"<<variable<<std::endl; }
5e5c6f8d76851572987559b33c620c07283f6427
b9bc15f1f02f0b83c954dc5576604438d890770d
/Source/S05_TestingGrounds/NPC/PatrolRoute.cpp
3d8dee1f50f7a9c771547339eebd7631573a2a08
[]
no_license
zedhqx4/05_TestingGrounds
48495ba2819bfc35d1e6095dd8564f1f957b31cb
5b1fb73b1fae4c44954d42555f71dff7dafc37b0
refs/heads/master
2021-01-20T15:30:43.889955
2017-06-30T16:53:45
2017-06-30T16:53:45
90,666,229
0
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
PatrolRoute.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "S05_TestingGrounds.h" #include "PatrolRoute.h" TArray<AActor*> UPatrolRoute::GetPatrolPoints() const // This is a Getter (GET): Get Patrol points from TArray OF AActor { return PatrolPoints; }
1b72404d58ab1a72afe2182d124bd18deef94fe0
5a0dc429c8d2dfd7af8e9ab470a583f1145bf84b
/include/Helpers.h
75b7aa35cbb642317110fefb861b9fc4c8926173
[ "Apache-2.0" ]
permissive
calinrc/urtoy
fd9b413aabed48511684120674c98c6c6de12354
71103d4915da870c2e5335e0d9fe1eaece2b47b0
refs/heads/master
2020-09-22T02:38:50.573962
2015-03-06T10:20:25
2015-03-06T10:20:25
21,162,790
0
0
null
null
null
null
UTF-8
C++
false
false
1,058
h
Helpers.h
/* * Helpers.h file written and maintained by Calin Cocan * Created on: Jul 7, 2014 * * This work is free: you can redistribute it and/or modify it under the terms of Apache License Version 2.0 * * 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 License for more details. * You should have received a copy of the License along with this program. If not, see <http://choosealicense.com/licenses/apache-2.0/>. ********************************************************************************************************************* */ #ifndef HELPERS_H_ #define HELPERS_H_ #include "Constants.h" class Helpers { private: Helpers(); virtual ~Helpers(); public: static long bigEndienBytesToInt(byte* bytes); static void intToBigEndienBytes(long val, byte* bytes); static const int MAX_MEM_ALLOC_SIZE = 5 * 1024 * 1024; // max 5MB allocation for this app }; #endif /* HELPERS_H_ */
49608e7ca1549e9e253f0a26314ae63dee2e43eb
e28f2a1e39f48015f5ec62b71c3ec5a93ad5573e
/oj/hdoj/hdoj_4891.cpp
011ce4366f1a62025d0c4d69fe8f4b3849f0459e
[]
no_license
james47/acm
22678d314bcdc3058f235443281a5b4abab2660d
09ad1bfc10cdd0af2d56169a0bdb8e0f22cba1cb
refs/heads/master
2020-12-24T16:07:28.284304
2016-03-13T15:16:48
2016-03-13T15:16:48
38,529,014
0
0
null
null
null
null
UTF-8
C++
false
false
1,223
cpp
hdoj_4891.cpp
#include<cstdio> #include<iostream> #include<cstring> #include<cmath> #include<algorithm> #include<cstdlib> #include<set> #include<map> #include<queue> #include<ctime> #include<string> using namespace std; const long long inf = int(1e5); int n; char ch; int main() { while(scanf("%d", &n) != EOF) { getchar(); long long ans = 1, tmp; int cnt = 0; bool flag = false; while(cnt < n){ ch = getchar(); if (ch == '\n') cnt ++; else {if (ch == '{'){ tmp = 0; ch = getchar(); while(ch != '}'){ if (ch == '\n') cnt++; if (ch == '|') tmp++; ch = getchar(); } if (tmp > inf) flag = true; if (!flag) ans *= (tmp+1); if (ans > inf) flag = true; } else if (ch == '$'){ tmp = 0; ch = getchar(); while(ch != '$'){ if (ch == '\n') cnt ++; else if (ch != ' '){ if (tmp > inf) flag = true; if (!flag) ans *= (tmp+1); if (ans > inf) flag = true; tmp = 0; } else tmp ++; ch = getchar(); } if (tmp > inf) flag = true; if (!flag) ans *= (tmp+1); if (ans > inf) flag = true; } } } if (flag) printf("doge\n"); //else printf("%I64d\n", ans); else printf("%lld\n", ans); } return 0; }
5d6d51bb62842e062a175987844dbd4f08c4dd64
93d9819473a1043f7fbc6712aff55610765fc92c
/frmMain.cpp
bdec1257ba42960ace26b98509b4dc8cea1271a1
[]
no_license
cckui/Borland_C_Lamp
fb9d4a94869722984e23a7dc719816bfbc25cebe
afe29e0808a450118784692e7eee971f3cb67af2
refs/heads/master
2021-01-21T18:18:16.846635
2017-05-22T08:57:56
2017-05-22T08:57:56
92,031,876
0
0
null
null
null
null
UTF-8
C++
false
false
4,331
cpp
frmMain.cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "frmMain.h" #include "Tme.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; int flag=0; int count_Red=0 ; int count_Yellow=0; int count_Green=0; //--------------------------------------------------------------------------- //*************************************************************************** // // Init // //*************************************************************************** __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { FLampRed = new Tme(this); FLampGreen = new Tme(this); FLampYellow = new Tme(this); } //--------------------------------------------------------------------------- void __fastcall TForm1::FormActivate(TObject *Sender) { FLampRed->set_ShapeProperty(PanelThread,stCircle,clBlue,clRed,5,130,130); FLampRed->set_ShapePosition(15,30); FLampYellow->set_ShapeProperty(PanelThread,stCircle,clBlue,clYellow,5,130,130); FLampYellow->set_ShapePosition(15,30+160); FLampGreen->set_ShapeProperty(PanelThread,stCircle,clBlue,clGreen,5,130,130); FLampGreen->set_ShapePosition(15,30+320); } //--------------------------------------------------------------------------- //*************************************************************************** // // Timer // //*************************************************************************** void __fastcall TForm1::Timer1Timer(TObject *Sender) { if (count_Red + count_Yellow + count_Green > 0) { if (flag==1 && count_Green!=0) { count_Green -=1; this->TShapeTimerRed->Brush->Color= clGray; this->TShapeTimerYellow->Brush->Color= clGray; this->TShapeTimerGreen->Brush->Color= clGreen; if (count_Green==0) { flag +=1; } }else if (flag==2 && count_Yellow!=0) { count_Yellow -=1; this->TShapeTimerRed->Brush->Color= clGray; this->TShapeTimerYellow->Brush->Color= clYellow; this->TShapeTimerGreen->Brush->Color= clGray; if (count_Yellow==0) { flag +=1; } }else if(flag==3 && count_Red!=0) { count_Red -=1; this->TShapeTimerRed->Brush->Color= clRed; this->TShapeTimerYellow->Brush->Color= clGray; this->TShapeTimerGreen->Brush->Color= clGray; if (count_Red==0) { flag =0; } } }else{ this->Timer1->Enabled=false; this->TShapeTimerRed->Brush->Color=clGray; this->Btn_Timer_Start->Enabled=true; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Btn_Timer_StartClick(TObject *Sender) { flag=1; count_Red = this->TEditRed->Text.ToInt(); count_Yellow=this->TEditYellow->Text.ToInt(); count_Green=(this->TEditGreen->Text.ToInt())-1; this->Btn_Timer_Start->Enabled=false; this->TShapeTimerRed->Brush->Color= clGray; this->TShapeTimerYellow->Brush->Color= clGray; this->TShapeTimerGreen->Brush->Color= clGreen; this->Timer1->Enabled=true; } //--------------------------------------------------------------------------- void __fastcall TForm1::Btn_Timer_StopClick(TObject *Sender) { this->Timer1->Enabled=false; } //--------------------------------------------------------------------------- //*************************************************************************** // // Thread + Component // //*************************************************************************** //--------------------------------------------------------------------------- void __fastcall TForm1::Btn_Thread_StartClick(TObject *Sender) { FLampRed->lamp_start(clRed,Thread_Edit_Red->Text.ToInt(),Thread_Edit_Yellow->Text.ToInt(),Thread_Edit_Green->Text.ToInt()); FLampGreen ->lamp_start(clGreen,Thread_Edit_Red->Text.ToInt(),Thread_Edit_Yellow->Text.ToInt(),Thread_Edit_Green->Text.ToInt()); FLampYellow ->lamp_start(clYellow,Thread_Edit_Red->Text.ToInt(),Thread_Edit_Yellow->Text.ToInt(),Thread_Edit_Green->Text.ToInt()); } //--------------------------------------------------------------------------- void __fastcall TForm1::Btn_Thread_StopClick(TObject *Sender) { FLampRed->lamp_stop(); FLampGreen->lamp_stop(); FLampYellow->lamp_stop(); } //---------------------------------------------------------------------------
0b735f04a645cc52e402aa45ef7bb7535e6d4490
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/TileCalorimeter/TileG4/TileGeoG4SD/src/components/TileGeoG4SD_entries.cxx
d8c63c5cd42facd000cd6d4e20fb8f7481c0fc3c
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
311
cxx
TileGeoG4SD_entries.cxx
#include "GaudiKernel/DeclareFactoryEntries.h" #include "../TileGeoG4SDTool.h" #include "../TileGeoG4SDCalc.hh" DECLARE_TOOL_FACTORY( TileGeoG4SDTool ) DECLARE_SERVICE_FACTORY( TileGeoG4SDCalc ) DECLARE_FACTORY_ENTRIES( TileGeoG4SD ) { DECLARE_TOOL( TileGeoG4SDTool ) DECLARE_SERVICE( TileGeoG4SDCalc ) }
d88abd72f9d3d30d7a1fd08ab558766af493e0ef
03d8bf96b2aae39be2f0632aab5e63fef651ff84
/swea_3142.cpp
85c9bc1907641aca8321af4f373fe5fd771e9728
[]
no_license
HanB2/SWEA_Prac
6a28ca36ca26d78e7b29a1d990e0822825fd8c02
9a8e58cd8ec5cf28e62d8f401b0eec563b582b15
refs/heads/master
2020-07-20T19:36:16.013356
2019-12-26T01:41:15
2019-12-26T01:41:15
206,699,395
3
0
null
null
null
null
UTF-8
C++
false
false
459
cpp
swea_3142.cpp
#include <iostream> using namespace std; int N,M; int Uni; int twinHorn; // N = Uni + 2 * TwinHorn // M = Uni + TwinHorn // N -M = TwinHorn int HowMany(){ twinHorn = N-M; Uni = M - twinHorn; } int main(){ int T; cin >> T; for (int t_case = 0; t_case < T; t_case++) { Uni =0; twinHorn =0; cin >>N >> M; HowMany(); cout << "#" << t_case+1 << " " << Uni << " " << twinHorn <<'\n'; } }
223e78db0eaf954a0bfdb82bc2c7b8856842f23f
85412c3b43165b8860e6416b5a5f2c013e808f03
/preprocess.h
64649ba3646e55c06a34b3b6d8173edd71274979
[]
no_license
ashraf-kx/Arabic-OCR
038e67bcf8b30e48190d734a9840f240ccf17900
8a64d5affeb6c5beed3b4cec580b0126035fd35c
refs/heads/main
2022-03-04T02:13:20.702698
2022-02-16T23:07:36
2022-02-16T23:07:36
55,866,111
1
3
null
null
null
null
UTF-8
C++
false
false
729
h
preprocess.h
#ifndef PREPROCESS_H #define PREPROCESS_H #include <QObject> #include <QDebug> #include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; class Preprocess : public QObject { Q_OBJECT private: struct pos { int x; int y; }; public: explicit Preprocess(QObject *parent = 0); Mat binarization(const Mat &image, int thresholdValue = 0); Mat contour(const Mat &image); Mat convert2cxx(const Mat &binary); Mat computeSkewAndRotate(Mat image); Mat Thinning(Mat image); Mat copyRect(const Mat &image, int x1, int y1, int x2, int y2); void thinningIteration(Mat &im, int iter); void thinning(Mat &image); }; #endif // PREPROCESS_H
b35db1968009919efc9118e7a2ba70b90c95b59a
ca9770f3afce46c796a21ef4be4950c333375d5a
/test/unit/cyt_unit_event_socket.cpp
101dbd72b0e3e4f623d55d2c601111c9a645b90d
[]
no_license
thejinchao/cyclone
25a57db09c4bcef32a773201acbb367a61816aba
40162e2ecd069ab2769c78ffdc2e0007cc9900dd
refs/heads/master
2023-05-26T09:10:06.152747
2023-05-23T01:31:29
2023-05-23T01:31:29
31,857,199
47
15
null
null
null
null
UTF-8
C++
false
false
9,275
cpp
cyt_unit_event_socket.cpp
#include <cy_event.h> #include <cy_crypt.h> #include "cyt_event_fortest.h" #include <gtest/gtest.h> using namespace cyclone; namespace { //------------------------------------------------------------------------------------- class SocketPair { public: socket_t m_fd[2]; RingBuf rb; Looper::event_id_t event_id; void* param; atomic_uint64_t write_counts; public: SocketPair(void* _param) : param(_param) , write_counts(0){ Pipe::construct_socket_pipe(m_fd); } ~SocketPair() { Pipe::destroy_socket_pipe(m_fd); } }; typedef std::vector< SocketPair* > SocketPairVector; //------------------------------------------------------------------------------------- struct ReadThreadData { EventLooper_ForTest* looper; SocketPairVector socketPairs; sys_api::signal_t ready_signal; uint32_t socket_counts; sys_api::signal_t write_to_full_signal; uint32_t active_counts; atomic_uint32_t actived_counts; sys_api::signal_t read_done_signal; uint32_t close_counts; atomic_uint32_t closed_counts; sys_api::signal_t close_done_signal; }; //------------------------------------------------------------------------------------- static void _onRead(Looper::event_id_t id, socket_t fd, Looper::event_t event, void* param) { (void)event; SocketPair* socketPair = (SocketPair*)param; ReadThreadData* data = (ReadThreadData*)(socketPair->param); ssize_t read_size = socketPair->rb.read_socket(fd); if (read_size > 0) { data->actived_counts += (uint32_t)((uint32_t)read_size / sizeof(uint64_t)); if (data->actived_counts.load() >= data->active_counts) { sys_api::signal_notify(data->read_done_signal); } } else { data->looper->disable_all(id); (data->closed_counts)++; if (data->closed_counts.load() >= data->close_counts) { sys_api::signal_notify(data->close_done_signal); } } } //------------------------------------------------------------------------------------- static void _readThreadFunction(void* param) { ReadThreadData* data = (ReadThreadData*)param; EventLooper_ForTest* looper = new EventLooper_ForTest(); data->looper = looper; for (size_t i = 0; i < data->socketPairs.size(); i++) { SocketPair* sp = data->socketPairs[i]; sp->event_id = looper->register_event(sp->m_fd[0], Looper::kRead, sp, _onRead, 0); } sys_api::signal_notify(data->ready_signal); looper->loop(); delete looper; data->looper = nullptr; } //------------------------------------------------------------------------------------- struct WriteThreadData { EventLooper_ForTest* looper; SocketPairVector socketPairs; sys_api::signal_t ready_signal; uint32_t socket_counts; sys_api::signal_t loop_stoped_signal; sys_api::signal_t quit_signal; }; //------------------------------------------------------------------------------------- static void _onWrite(Looper::event_id_t id, socket_t fd, Looper::event_t event, void* param) { (void)id; (void)fd; (void)event; SocketPair* socketPair = (SocketPair*)param; (socketPair->write_counts)++; } //------------------------------------------------------------------------------------- static void _writeThreadFunction(void* param) { WriteThreadData* data = (WriteThreadData*)param; EventLooper_ForTest* looper = new EventLooper_ForTest(); data->looper = looper; for (size_t i = 0; i < data->socketPairs.size(); i++) { SocketPair* sp = data->socketPairs[i]; sp->event_id = looper->register_event(sp->m_fd[0], Looper::kWrite, sp, 0, _onWrite); } sys_api::signal_notify(data->ready_signal); looper->loop(); sys_api::signal_notify(data->loop_stoped_signal); sys_api::signal_wait(data->quit_signal); delete looper; data->looper = nullptr; } //------------------------------------------------------------------------------------- TEST(EventLooper, ReadAndCloseSocket) { ReadThreadData data; data.ready_signal = sys_api::signal_create(); data.read_done_signal = sys_api::signal_create(); data.close_done_signal = sys_api::signal_create(); //read event { data.socket_counts = 100; data.active_counts = 10; data.actived_counts = 0; data.close_counts = 0; data.closed_counts = 0; XorShift128 rndSend, rndCheck; rndSend.make(); rndCheck = rndSend; for (size_t i = 0; i < data.socket_counts; i++) { SocketPair* sp = new SocketPair(&data); data.socketPairs.push_back(sp); } thread_t thread = sys_api::thread_create(_readThreadFunction, &data, "looper_socket"); sys_api::signal_wait(data.ready_signal); //send to some of socket std::vector< size_t > activeIDs; for (size_t i = 0; i < data.active_counts; i++) { size_t index = (size_t)rand() % data.socket_counts; uint64_t sndData = rndSend.next(); EXPECT_EQ(sizeof(sndData), (size_t)socket_api::write(data.socketPairs[index]->m_fd[1], (const char*)&sndData, sizeof(sndData))); activeIDs.push_back(index); } EXPECT_EQ(data.active_counts, activeIDs.size()); sys_api::signal_wait(data.read_done_signal); //begin check EXPECT_GE(data.actived_counts.load(), data.active_counts); for (size_t i = 0; i < data.active_counts; i++) { size_t index = activeIDs[i]; uint64_t rcvData = 0; EXPECT_EQ(sizeof(rcvData), data.socketPairs[index]->rb.memcpy_out(&rcvData, sizeof(rcvData))); EXPECT_EQ(rcvData, rndCheck.next()); } activeIDs.clear(); for (size_t i = 0; i < data.socket_counts; i++) { EXPECT_TRUE(data.socketPairs[i]->rb.empty()); } EXPECT_GE(data.looper->get_loop_counts(), 1ull); EXPECT_LE(data.looper->get_loop_counts(), data.active_counts + 1); //read event(s) + inner pipe register event //quit... data.looper->push_stop_request(); sys_api::thread_join(thread); for (size_t i = 0; i < data.socketPairs.size(); i++) { delete data.socketPairs[i]; } data.socketPairs.clear(); } //close event { data.socket_counts = 100; data.active_counts = 0; data.actived_counts = 0; data.close_counts = 1; data.closed_counts = 0; for (size_t i = 0; i < data.socket_counts; i++) { SocketPair* sp = new SocketPair(&data); data.socketPairs.push_back(sp); } thread_t thread = sys_api::thread_create(_readThreadFunction, &data, "looper_socket"); sys_api::signal_wait(data.ready_signal); //remember all ids std::set < Looper::event_id_t > allIDs; for (size_t i = 0; i < data.socket_counts; i++) { allIDs.insert(data.socketPairs[i]->event_id); } //close some socket std::set < Looper::event_id_t > closeIDs; for (size_t i = 0; i < data.close_counts; i++) { size_t index = (size_t)rand() % data.socket_counts; while (closeIDs.find(data.socketPairs[index]->event_id) != closeIDs.end()) { index = (size_t)rand() % data.socket_counts; } socket_api::close_socket(data.socketPairs[index]->m_fd[1]); data.socketPairs[index]->m_fd[1] = INVALID_SOCKET; closeIDs.insert(data.socketPairs[index]->event_id); } EXPECT_EQ(data.close_counts, closeIDs.size()); sys_api::signal_wait(data.close_done_signal); //begin check const auto& channel_buf = data.looper->get_channel_buf(); EXPECT_EQ(data.closed_counts.load(), data.close_counts); EXPECT_EQ(data.socket_counts - data.close_counts, (uint32_t)data.looper->get_active_channel_counts() - 1); for (size_t i = 0; i < channel_buf.size(); i++) { const auto& channel = channel_buf[i]; if (closeIDs.end() != closeIDs.find(channel.id)) { EXPECT_FALSE(channel.active); } else { if (allIDs.end() != allIDs.find(channel.id)) { EXPECT_TRUE(channel.active); } } } EXPECT_GE(data.looper->get_loop_counts(), 1ull); EXPECT_LE(data.looper->get_loop_counts(), data.close_counts + 1); //close event(s) + inner pipe register event //quit... data.looper->push_stop_request(); sys_api::thread_join(thread); for (size_t i = 0; i < data.socketPairs.size(); i++) { delete data.socketPairs[i]; } data.socketPairs.clear(); } sys_api::signal_destroy(data.ready_signal); sys_api::signal_destroy(data.read_done_signal); sys_api::signal_destroy(data.close_done_signal); } //------------------------------------------------------------------------------------- TEST(EventLooper, WriteSocket) { WriteThreadData data; data.ready_signal = sys_api::signal_create(); data.loop_stoped_signal = sys_api::signal_create(); data.quit_signal = sys_api::signal_create(); //write test { data.socket_counts = 10; for (size_t i = 0; i < data.socket_counts; i++) { SocketPair* sp = new SocketPair(&data); data.socketPairs.push_back(sp); } thread_t thread = sys_api::thread_create(_writeThreadFunction, &data, "looper_socket"); sys_api::signal_wait(data.ready_signal); sys_api::thread_sleep(100); //fly some time //quit... data.looper->push_stop_request(); sys_api::signal_wait(data.loop_stoped_signal); uint64_t loop_counts = data.looper->get_loop_counts(); sys_api::signal_notify(data.quit_signal); sys_api::thread_join(thread); for (size_t i = 0; i < data.socketPairs.size(); i++) { EXPECT_GE(data.socketPairs[i]->write_counts.load(), loop_counts - 1); EXPECT_LE(data.socketPairs[i]->write_counts.load(), loop_counts); delete data.socketPairs[i]; } data.socketPairs.clear(); } sys_api::signal_destroy(data.ready_signal); sys_api::signal_destroy(data.loop_stoped_signal); sys_api::signal_destroy(data.quit_signal); } }
354977ad308c07cf58bc6e6175d2ad47a25c9cf4
bd96459164b7f3f500d4cf2ad6dc79a8673f4b23
/datatype/main.cpp
342153446f3ab6952284347c2d47bf9735814187
[]
no_license
QQBoxy/2018vc
6c0b28b9aa2230907b280244cbc91b826ebe28c5
c92f76a079c4d2359fa4cd8fcbebd5eb6c2ac70e
refs/heads/master
2020-03-23T19:01:59.078412
2018-08-07T07:03:43
2018-08-07T07:03:43
141,949,591
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
main.cpp
//Example 2 - datatype #include <iostream> using namespace std; int main(void) { cout << "type\tbyte" << endl; //整數 cout << "short\t" << sizeof(short) << endl; //2 cout << "int\t" << sizeof(int) << endl; //4 cout << "long\t" << sizeof(long) << "\n" << endl; //4 //浮點數 cout << "float\t" << sizeof(float) << endl; //4 cout << "double\t" << sizeof(double) << endl; //8 cout << "long double\t" << sizeof(long double) << "\n" << endl; //8 //字元 cout << "char\t" << sizeof(char) << "\n" << endl; //1 //布林 cout << "bool\t" << sizeof(bool) << endl; //1 system("pause"); return 0; }
4c84a6731a52756904f36cb23ed4e5329385fc9f
43d5b851932ca564bd26a4e96212797ae0e2cd21
/Source/Entity/NPC.cpp
ab600477aa1910ef372c4651b23e06f686b9daa9
[]
no_license
HexColors60/GoblinCamp
8c427bd04beba022b0c6df980eccfe93ac5770af
80b2ee98dc20ea10a9f5731338f548f0cb2197a5
refs/heads/main
2023-03-21T05:31:29.831316
2021-03-20T02:41:03
2021-03-20T02:41:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
110,831
cpp
NPC.cpp
/* Copyright 2010-2011 Ilkka Halila This file is part of Goblin Camp. Goblin Camp 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 3 of the License, or (at your option) any later version. Goblin Camp 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 Goblin Camp. If not, see <http://www.gnu.org/licenses/>.*/ #include <cstdlib> #include <string> #include <boost/serialization/split_member.hpp> #include <boost/thread/thread.hpp> #include <boost/multi_array.hpp> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <libtcod.hpp> #ifdef DEBUG #include <iostream> #endif #include <boost/serialization/deque.hpp> #include <boost/serialization/weak_ptr.hpp> #include <boost/serialization/list.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/set.hpp> #include "Goblin/Math/Random.hpp" #include "Goblin/Entity/NPC.hpp" #include "Goblin/Task/JobManager.hpp" #include "Goblin/Util/GCamp.hpp" #include "Goblin/Util/Game.hpp" #include "Goblin/Log/Logger.hpp" #include "Goblin/Eden/Map.hpp" #include "Goblin/Mechanism/StatusEffect.hpp" #include "Goblin/Mechanism/Camp.hpp" #include "Goblin/Mechanism/Stockpile.hpp" #include "Goblin/Mechanism/Faction.hpp" #include "Goblin/Mechanism/Stats.hpp" #include "Goblin/Geometry/Coordinate.hpp" #include "Goblin/User/Interface/Announce.hpp" SkillSet::SkillSet() { for (int i = 0; i < SKILLAMOUNT; ++i) { skills[i] = 0; } } int SkillSet::operator()(Skill skill) { return skills[skill]; } void SkillSet::operator()(Skill skill, int value) { skills[skill] = value; } void SkillSet::save(OutputArchive& ar, const unsigned int version) const { ar & skills; } void SkillSet::load(InputArchive& ar, const unsigned int version) { ar & skills; } std::map<std::string, NPCType> NPC::NPCTypeNames = std::map<std::string, NPCType>(); std::vector<NPCPreset> NPC::Presets = std::vector<NPCPreset>(); NPC::NPC(Coordinate pos, std::function<bool(std::shared_ptr<NPC>)> findJob, std::function<void(std::shared_ptr<NPC>)> react) : Entity(), type(0), timeCount(0), taskIndex(0), orderIndex(0), pathIndex(0), nopath(false), findPathWorking(false), pathIsDangerous(false), timer(0), nextMove(0), lastMoveResult(TASKCONTINUE), run(true), taskBegun(false), jobBegun(false), expert(false), carried(std::shared_ptr<Item>()), mainHand(std::shared_ptr<Item>()), offHand(std::shared_ptr<Item>()), armor(std::shared_ptr<Item>()), thirst(0), hunger(0), weariness(0), thinkSpeed(UPDATES_PER_SECOND / 5), //Think 5 times a second statusEffects(std::list<StatusEffect>()), statusEffectIterator(statusEffects.end()), statusGraphicCounter(0), health(100), maxHealth(100), foundItem(std::shared_ptr<Item>()), inventory(std::shared_ptr<Container>(new Container(pos, 0, 30, -1))), needsNutrition(false), needsSleep(false), hasHands(false), isTunneler(false), isFlying(false), FindJob(findJob), React(react), aggressive(false), coward(false), aggressor(std::weak_ptr<NPC>()), dead(false), squad(std::weak_ptr<Squad>()), attacks(std::list<Attack>()), escaped(false), addedTasksToCurrentJob(0), hasMagicRangedAttacks(false), threatLocation(undefined), seenFire(false), traits(std::set<Trait>()), damageDealt(0), damageReceived(0), statusEffectsChanged(false) { this->pos = pos; inventory->SetInternal(); thirst = thirst - (THIRST_THRESHOLD / 2) + Random::Generate(THIRST_THRESHOLD - 1); hunger = hunger - (HUNGER_THRESHOLD / 2) + Random::Generate(HUNGER_THRESHOLD - 1); weariness = weariness - (WEARY_THRESHOLD / 2) + Random::Generate(WEARY_THRESHOLD - 1); for (int i = 0; i < STAT_COUNT; ++i) {baseStats[i] = 0; effectiveStats[i] = 0;} for (int i = 0; i < RES_COUNT; ++i) {baseResistances[i] = 0; effectiveResistances[i] = 0;} } NPC::~NPC() { pathMutex.lock(); /* In case a pathing thread is active we need to wait until we can lock the pathMutex, because it signals that the thread has finished */ map->NPCList(pos)->erase(uid); if (squad.lock()) squad.lock()->Leave(uid); if (boost::iequals(NPC::NPCTypeToString(type), "orc")) Game::Inst()->OrcCount(-1); else if (boost::iequals(NPC::NPCTypeToString(type), "goblin")) Game::Inst()->GoblinCount(-1); else if (NPC::Presets[type].tags.find("localwildlife") != NPC::Presets[type].tags.end()) Game::Inst()->PeacefulFaunaCount(-1); pathMutex.unlock(); delete path; } void NPC::SetMap(Map* map) { this->map = map; inventory->SetMap(map); while (!map->IsWalkable(pos)) { pos += Random::ChooseInRadius(1); } Position(pos,true); path = new TCODPath(map->Width(), map->Height(), map, static_cast<void*>(this)); } void NPC::Position(const Coordinate& p, bool firstTime) { map->MoveTo(p, uid); if (!firstTime) map->MoveFrom(pos, uid); pos = p; inventory->Position(pos); } void NPC::Position(const Coordinate& pos) { Position(pos, false); } Task* NPC::currentTask() const { return jobs.empty() ? 0 : &(jobs.front()->tasks[taskIndex]); } Task* NPC::nextTask() const { if (!jobs.empty()) { if (static_cast<signed int>(jobs.front()->tasks.size()) > taskIndex+1) { return &jobs.front()->tasks[taskIndex+1]; } } return 0; } std::weak_ptr<Job> NPC::currentJob() const { return jobs.empty() ? std::weak_ptr<Job>() : std::weak_ptr<Job>(jobs.front()); } void NPC::TaskFinished(TaskResult result, std::string msg) { #ifdef DEBUG if (msg.size() > 0) { std::cout<<name<<":"<<msg<<"\n"; } #endif RemoveEffect(EATING); RemoveEffect(DRINKING); RemoveEffect(WORKING); if (jobs.size() > 0) { if (result == TASKSUCCESS) { if (++taskIndex >= (signed int)jobs.front()->tasks.size()) { jobs.front()->Complete(); jobs.pop_front(); taskIndex = 0; foundItem = std::shared_ptr<Item>(); addedTasksToCurrentJob = 0; jobBegun = false; } } else { //Remove any tasks this NPC added onto the front before sending it back to the JobManager for (int i = 0; i < addedTasksToCurrentJob; ++i) { if (!jobs.front()->tasks.empty()) jobs.front()->tasks.erase(jobs.front()->tasks.begin()); } if (!jobs.front()->internal) JobManager::Inst()->CancelJob(jobs.front(), msg, result); jobs.pop_front(); taskIndex = 0; DropItem(carried); carried.reset(); foundItem = std::shared_ptr<Item>(); addedTasksToCurrentJob = 0; jobBegun = false; } } taskBegun = false; run = NPC::Presets[type].tags.find("calm") == NPC::Presets[type].tags.end() ? true : false; if (result != TASKSUCCESS) { //If we're wielding a container (ie. a tool) spill it's contents if (mainHand && std::dynamic_pointer_cast<Container>(mainHand)) { std::shared_ptr<Container> cont(std::static_pointer_cast<Container>(mainHand)); if (cont->ContainsWater() > 0) { Game::Inst()->CreateWater(Position(), cont->ContainsWater()); cont->RemoveWater(cont->ContainsWater()); } else if (cont->ContainsFilth() > 0) { Game::Inst()->CreateFilth(Position(), cont->ContainsFilth()); cont->RemoveFilth(cont->ContainsFilth()); } } } } void NPC::HandleThirst() { bool found = false; for (std::deque<std::shared_ptr<Job> >::iterator jobIter = jobs.begin(); jobIter != jobs.end(); ++jobIter) { if ((*jobIter)->name.find("Drink") != std::string::npos) found = true; } if (!found) { std::shared_ptr<Item> item = Game::Inst()->FindItemByCategoryFromStockpiles(Item::StringToItemCategory("Drink"), Position()); Coordinate waterCoordinate; if (!item) { waterCoordinate = Game::Inst()->FindWater(Position()); } if (item || waterCoordinate != undefined) { //Found something to drink std::shared_ptr<Job> newJob(new Job("Drink", MED, 0, !expert)); newJob->internal = true; if (item) { newJob->ReserveEntity(item); newJob->tasks.push_back(Task(MOVE, item->Position())); newJob->tasks.push_back(Task(TAKE, item->Position(), item)); newJob->tasks.push_back(Task(DRINK)); jobs.push_back(newJob); } else { Coordinate adjacentTile = Game::Inst()->FindClosestAdjacent(Position(), waterCoordinate, faction); if (adjacentTile.X() >= 0) { newJob->tasks.push_back(Task(MOVE, adjacentTile)); newJob->tasks.push_back(Task(DRINK, waterCoordinate)); if (jobs.empty()) JobManager::Inst()->NPCNotWaiting(uid); jobs.push_back(newJob); } } } } } void NPC::HandleHunger() { bool found = false; if (hunger > 48000 && !jobs.empty() && jobs.front()->name.find("Eat") == std::string::npos) { //Starving and doing something else TaskFinished(TASKFAILNONFATAL); } for (std::deque<std::shared_ptr<Job> >::iterator jobIter = jobs.begin(); jobIter != jobs.end(); ++jobIter) { if ((*jobIter)->name.find("Eat") != std::string::npos) found = true; } if (!found) { std::shared_ptr<Item> item = Game::Inst()->FindItemByCategoryFromStockpiles( Item::StringToItemCategory("Prepared food"), Position(), MOSTDECAYED); if (!item) { item = Game::Inst()->FindItemByCategoryFromStockpiles(Item::StringToItemCategory("Food"), Position(), MOSTDECAYED | AVOIDGARBAGE); } if (!item) { //Nothing to eat! if (hunger > 48000) { //Nearing death ScanSurroundings(); std::shared_ptr<NPC> weakest; for (std::list<std::weak_ptr<NPC> >::iterator npci = nearNpcs.begin(); npci != nearNpcs.end(); ++npci) { if (npci->lock() && (!weakest || npci->lock()->health < weakest->health)) { weakest = npci->lock(); } } if (weakest) { //Found a creature nearby, eat it std::shared_ptr<Job> newJob(new Job("Eat", HIGH, 0, !expert)); newJob->internal = true; newJob->tasks.push_back(Task(GETANGRY)); newJob->tasks.push_back(Task(KILL, weakest->Position(), weakest, 0, 1)); newJob->tasks.push_back(Task(EAT)); newJob->tasks.push_back(Task(CALMDOWN)); jobs.push_back(newJob); } } } else { //Something to eat! std::shared_ptr<Job> newJob(new Job("Eat", MED, 0, !expert)); newJob->internal = true; newJob->ReserveEntity(item); newJob->tasks.push_back(Task(MOVE, item->Position())); newJob->tasks.push_back(Task(TAKE, item->Position(), item)); newJob->tasks.push_back(Task(EAT)); if (jobs.empty()) JobManager::Inst()->NPCNotWaiting(uid); jobs.push_back(newJob); } } } void NPC::HandleWeariness() { bool found = false; for (std::deque<std::shared_ptr<Job> >::iterator jobIter = jobs.begin(); jobIter != jobs.end(); ++jobIter) { if ((*jobIter)->name.find("Sleep") != std::string::npos) found = true; else if ((*jobIter)->name.find("Get rid of") != std::string::npos) found = true; } if (!found) { std::weak_ptr<Construction> wbed = Game::Inst()->FindConstructionByTag(BED, Position()); std::shared_ptr<Job> sleepJob(new Job("Sleep")); sleepJob->internal = true; if (!squad.lock() && mainHand) { //Only soldiers go to sleep gripping their weapons sleepJob->tasks.push_back(Task(UNWIELD)); sleepJob->tasks.push_back(Task(TAKE)); sleepJob->tasks.push_back(Task(STOCKPILEITEM)); } if (std::shared_ptr<Construction> bed = wbed.lock()) { if (bed->Built()) { sleepJob->ReserveEntity(bed); sleepJob->tasks.push_back(Task(MOVE, bed->Position())); sleepJob->tasks.push_back(Task(SLEEP, bed->Position(), bed)); jobs.push_back(sleepJob); return; } } sleepJob->tasks.push_back(Task(SLEEP, Position())); if (jobs.empty()) JobManager::Inst()->NPCNotWaiting(uid); jobs.push_back(sleepJob); } } void NPC::Update() { if (map->NPCList(pos)->size() > 1) _bgcolor = TCODColor::darkGrey; else _bgcolor = TCODColor::black; UpdateStatusEffects(); //Apply armor effects if present if (std::shared_ptr<Item> arm = armor) { for (int i = 0; i < RES_COUNT; ++i) { effectiveResistances[i] += arm->Resistance(i); } } if (Random::Generate(UPDATES_PER_SECOND) == 0) { //Recalculate bulk once a second, items may get unexpectedly destroyed bulk = 0; for (std::set<std::shared_ptr<Item> >::iterator itemi = inventory->begin(); itemi != inventory->end(); ++itemi) { if (*itemi) bulk += (*itemi)->GetBulk(); } } if (!HasEffect(FLYING) && effectiveStats[MOVESPEED] > 0) effectiveStats[MOVESPEED] = std::max(1, effectiveStats[MOVESPEED]-map->GetMoveModifier(pos)); if (effectiveStats[MOVESPEED] > 0) effectiveStats[MOVESPEED] = std::max(1, effectiveStats[MOVESPEED]-bulk); if (needsNutrition) { ++thirst; ++hunger; if (thirst >= THIRST_THRESHOLD) AddEffect(THIRST); else RemoveEffect(THIRST); if (hunger >= HUNGER_THRESHOLD) AddEffect(HUNGER); else RemoveEffect(HUNGER); if (thirst > THIRST_THRESHOLD && Random::Generate(UPDATES_PER_SECOND * 5 - 1) == 0) { HandleThirst(); } else if (thirst > THIRST_THRESHOLD * 2) Kill(GetDeathMsgThirst()); if (hunger > HUNGER_THRESHOLD && Random::Generate(UPDATES_PER_SECOND * 5 - 1) == 0) { HandleHunger(); } else if (hunger > 72000) Kill(GetDeathMsgHunger()); } if (needsSleep) { ++weariness; if (weariness >= WEARY_THRESHOLD) { AddEffect(DROWSY); if (weariness > WEARY_THRESHOLD) HandleWeariness(); //Give the npc a chance to find a sleepiness curing item } else RemoveEffect(DROWSY); } if (!HasEffect(FLYING)) { if (std::shared_ptr<WaterNode> water = map->GetWater(pos).lock()) { std::shared_ptr<Construction> construct = Game::Inst()->GetConstruction(map->GetConstruction(pos)).lock(); if (water->Depth() > WALKABLE_WATER_DEPTH && (!construct || !construct->HasTag(BRIDGE) || !construct->Built())) { AddEffect(SWIM); RemoveEffect(BURNING); } else { RemoveEffect(SWIM); } } else { RemoveEffect(SWIM); } if (map->GetNatureObject(pos) >= 0 && Game::Inst()->natureList[map->GetNatureObject(pos)]->IsIce() && Random::Generate(UPDATES_PER_SECOND * 5) == 0) AddEffect(TRIPPED); } for (std::list<Attack>::iterator attacki = attacks.begin(); attacki != attacks.end(); ++attacki) { attacki->Update(); } if (faction == PLAYERFACTION && Random::Generate(MONTH_LENGTH - 1) == 0) Game::Inst()->CreateFilth(Position()); if (carried) { AddEffect(StatusEffect(CARRYING, carried->GetGraphic(), carried->Color())); } else RemoveEffect(CARRYING); if (HasTrait(CRACKEDSKULL) && Random::Generate(MONTH_LENGTH * 6) == 0) GoBerserk(); if (HasEffect(BURNING)) { if (Random::Generate(UPDATES_PER_SECOND * 3) == 0) { std::shared_ptr<Spell> spark = Game::Inst()->CreateSpell(Position(), Spell::StringToSpellType("spark")); spark->CalculateFlightPath(Random::ChooseInRadius(Position(), 1), 50, GetHeight()); } if (effectiveResistances[FIRE_RES] < 90 && !HasEffect(RAGE) && (jobs.empty() || jobs.front()->name != "Jump into water")) { if (Random::Generate(UPDATES_PER_SECOND) == 0) { RemoveEffect(PANIC); while (!jobs.empty()) TaskFinished(TASKFAILFATAL); std::shared_ptr<Job> jumpJob(new Job("Jump into water")); jumpJob->internal = true; Coordinate waterPos = Game::Inst()->FindWater(Position()); if (waterPos != undefined) { jumpJob->tasks.push_back(Task(MOVE, waterPos)); jobs.push_back(jumpJob); } } else if (!coward && boost::iequals(NPC::NPCTypeToString(type), "orc") && Random::Generate(2) == 0) {RemoveEffect(PANIC); GoBerserk();} else {AddEffect(PANIC);} } } UpdateHealth(); } void NPC::UpdateStatusEffects() { //Add job related effects if (!jobs.empty()) { for (std::list<StatusEffectType>::iterator stati = jobs.front()->statusEffects.begin(); stati != jobs.front()->statusEffects.end(); ++stati) { AddEffect(*stati); } } for (int i = 0; i < STAT_COUNT; ++i) { effectiveStats[i] = baseStats[i]; } for (int i = 0; i < RES_COUNT; ++i) { effectiveResistances[i] = baseResistances[i]; } if (factionPtr->IsFriendsWith(PLAYERFACTION)) effectiveResistances[DISEASE_RES] = std::max(0, effectiveResistances[DISEASE_RES] - Camp::Inst()->GetDiseaseModifier()); ++statusGraphicCounter; for (std::list<StatusEffect>::iterator statusEffectI = statusEffects.begin(); statusEffectI != statusEffects.end();) { //Apply effects to stats for (int i = 0; i < STAT_COUNT; ++i) { effectiveStats[i] = (int)(effectiveStats[i] * statusEffectI->statChanges[i]); } for (int i = 0; i < RES_COUNT; ++i) { effectiveResistances[i] = (int)(effectiveResistances[i] * statusEffectI->resistanceChanges[i]); } if (statusEffectI->damage.second != 0 && --statusEffectI->damage.first <= 0) { statusEffectI->damage.first = UPDATES_PER_SECOND; TCOD_dice_t dice; dice.addsub = (float)statusEffectI->damage.second; dice.multiplier = 1; dice.nb_dices = 1; dice.nb_faces = std::max(1, (int)dice.addsub / 5); Attack attack; attack.Amount(dice); attack.Type((DamageType)statusEffectI->damageType); Damage(&attack); } if (factionPtr->IsFriendsWith(PLAYERFACTION) && statusEffectI->negative && !HasEffect(SLEEPING) && (statusEffectsChanged || Random::Generate(MONTH_LENGTH) == 0)) { statusEffectsChanged = false; bool removalJobFound = false; for (std::deque<std::shared_ptr<Job> >::iterator jobi = jobs.begin(); jobi != jobs.end(); ++jobi) { if ((*jobi)->name.find("Get rid of") != std::string::npos) { removalJobFound = true; break; } } if (!removalJobFound && Item::EffectRemovers.find((StatusEffectType)statusEffectI->type) != Item::EffectRemovers.end()) { std::shared_ptr<Item> fixItem; for (std::multimap<StatusEffectType, ItemType>::iterator fixi = Item::EffectRemovers.equal_range( (StatusEffectType)statusEffectI->type).first; fixi != Item::EffectRemovers.equal_range((StatusEffectType)statusEffectI->type).second && !fixItem; ++fixi) { fixItem = Game::Inst()->FindItemByTypeFromStockpiles(fixi->second, Position()); } if (fixItem) { std::shared_ptr<Job> rEffJob(new Job("Get rid of " + statusEffectI->name)); rEffJob->internal = true; rEffJob->ReserveEntity(fixItem); rEffJob->tasks.push_back(Task(MOVE, fixItem->Position())); rEffJob->tasks.push_back(Task(TAKE, fixItem->Position(), fixItem)); if (fixItem->IsCategory(Item::StringToItemCategory("drink"))) rEffJob->tasks.push_back(Task(DRINK)); else rEffJob->tasks.push_back(Task(EAT)); jobs.push_back(rEffJob); } } } if (statusEffectI->contagionChance > 0 && Random::Generate(1000) == 0) { //See if we transmit this effect ScanSurroundings(); if (adjacentNpcs.size() > 0 && Random::Generate(100) < statusEffectI->contagionChance) { for (std::list<std::weak_ptr<NPC> >::iterator npci = adjacentNpcs.begin(); npci != adjacentNpcs.end(); ++npci) { if (std::shared_ptr<NPC> npc = npci->lock()) npc->TransmitEffect(*statusEffectI); } } } //Remove the statuseffect if its cooldown has run out if (statusEffectI->cooldown > 0 && --statusEffectI->cooldown == 0) { if (statusEffectI == statusEffectIterator) { ++statusEffectIterator; statusGraphicCounter = 0; } statusEffectI = statusEffects.erase(statusEffectI); if (statusEffectIterator == statusEffects.end()) statusEffectIterator = statusEffects.begin(); } else ++statusEffectI; } if (statusGraphicCounter > 10) { statusGraphicCounter = 0; if (statusEffectIterator != statusEffects.end()) ++statusEffectIterator; else statusEffectIterator = statusEffects.begin(); if (statusEffectIterator != statusEffects.end() && !statusEffectIterator->visible) { std::list<StatusEffect>::iterator oldIterator = statusEffectIterator; ++statusEffectIterator; while (statusEffectIterator != oldIterator) { if (statusEffectIterator != statusEffects.end()) { if (statusEffectIterator->visible) break; ++statusEffectIterator; } else statusEffectIterator = statusEffects.begin(); } if (statusEffectIterator != statusEffects.end() && !statusEffectIterator->visible) statusEffectIterator = statusEffects.end(); } } } //TODO split that monster into smaller chunks void NPC::Think() { Coordinate tmpCoord; int tmp; UpdateVelocity(); lastMoveResult = Move(lastMoveResult); if (velocity == 0) { timeCount += thinkSpeed; //Can't think while hurtling through the air, sorry } else if (!jobs.empty()) { TaskFinished(TASKFAILFATAL, "Flying through the air"); JobManager::Inst()->NPCNotWaiting(uid); } while (timeCount > UPDATES_PER_SECOND) { if (Random::GenerateBool()) React(std::static_pointer_cast<NPC>(shared_from_this())); { std::shared_ptr<NPC> enemy = aggressor.lock(); for (std::list<std::weak_ptr<NPC> >::iterator npci = adjacentNpcs.begin(); npci != adjacentNpcs.end(); ++npci) { if (std::shared_ptr<NPC> adjacentNpc = npci->lock()) { if ((!coward && !factionPtr->IsFriendsWith(adjacentNpc->GetFaction())) || adjacentNpc == enemy) { if (currentTask() && currentTask()->action == KILL) Hit(adjacentNpc, currentTask()->flags != 0); else Hit(adjacentNpc); } } } if (currentTask() && currentTask()->action == KILL) { if (std::shared_ptr<Entity> target = currentTask()->entity.lock()) { if (Random::Generate(4) == 0 && !map->LineOfSight(pos, target->Position())) { TaskFinished(TASKFAILFATAL, "Target lost"); } } } } timeCount -= UPDATES_PER_SECOND; if (!jobs.empty() && !jobBegun) { jobBegun = true; ValidateCurrentJob(); } if (!jobs.empty()) { switch(currentTask()->action) { case MOVE: if (!map->IsWalkable(currentTarget(), static_cast<void*>(this))) { TaskFinished(TASKFAILFATAL, "(MOVE)Target unwalkable"); break; } if (pos == currentTarget()) { TaskFinished(TASKSUCCESS); break; } if (!taskBegun) { findPath(currentTarget()); taskBegun = true; lastMoveResult = TASKCONTINUE;} if (lastMoveResult == TASKFAILFATAL || lastMoveResult == TASKFAILNONFATAL) { TaskFinished(lastMoveResult, std::string("(MOVE)Could not find path to target")); break; } else if (lastMoveResult == PATHEMPTY) { if (pos != currentTarget()) { TaskFinished(TASKFAILFATAL, std::string("(MOVE)No path to target")); break; } } break; case MOVENEAR: /*MOVENEAR first figures out our "real" target, which is a tile near to our current target. Near means max 5 tiles away, visible and walkable. Once we have our target we can actually switch over to a normal MOVE task. In case we can't find a visible tile, we'll allow a non LOS one*/ {bool checkLOS = true; for (int i = 0; i < 2; ++i) { tmp = 0; while (tmp++ < 10) { Coordinate tar = map->Shrink(Random::ChooseInRadius(currentTarget(), 5)); if (map->IsWalkable(tar, (void *)this) && !map->IsUnbridgedWater(tar) && !map->IsDangerous(tar, faction)) { if (!checkLOS || map->LineOfSight(tar, currentTarget())) { currentJob().lock()->tasks[taskIndex] = Task(MOVE, tar); goto MOVENEARend; } } } checkLOS = !checkLOS; }} //If we got here we couldn't find a near coordinate TaskFinished(TASKFAILFATAL, "(MOVENEAR)Couldn't find NEAR coordinate"); MOVENEARend: break; case MOVEADJACENT: if (currentEntity().lock()) { if (Game::Adjacent(Position(), currentEntity())) { TaskFinished(TASKSUCCESS); break; } } else { if (Game::Adjacent(Position(), currentTarget())) { TaskFinished(TASKSUCCESS); break; } } if (!taskBegun) { if (currentEntity().lock()) tmpCoord = Game::Inst()->FindClosestAdjacent(Position(), currentEntity(), GetFaction()); else tmpCoord = Game::Inst()->FindClosestAdjacent(Position(), currentTarget(), GetFaction()); if (tmpCoord != undefined) { findPath(tmpCoord); } else { TaskFinished(TASKFAILFATAL, std::string("(MOVEADJACENT)No walkable adjacent tiles")); break; } taskBegun = true; lastMoveResult = TASKCONTINUE; } if (lastMoveResult == TASKFAILFATAL || lastMoveResult == TASKFAILNONFATAL) { TaskFinished(lastMoveResult, std::string("Could not find path to target")); break; } else if (lastMoveResult == PATHEMPTY) { TaskFinished(TASKFAILFATAL, "(MOVEADJACENT)PATHEMPTY"); } break; case WAIT: //TODO remove that WAIT hack if (++timer > currentTarget().X()) { timer = 0; TaskFinished(TASKSUCCESS); } break; case BUILD: if (Game::Adjacent(Position(), currentEntity())) { AddEffect(WORKING); tmp = std::static_pointer_cast<Construction>(currentEntity().lock())->Build(); if (tmp > 0) { Announce::Inst()->AddMsg((boost::format("%s completed") % currentEntity().lock()->Name()).str(), TCODColor::white, currentEntity().lock()->Position()); TaskFinished(TASKSUCCESS); break; } else if (tmp == BUILD_NOMATERIAL) { TaskFinished(TASKFAILFATAL, "(BUILD)Missing materials"); break; } } else { TaskFinished(TASKFAILFATAL, "(BUILD)Not adjacent to target"); break; } break; case TAKE: if (!currentEntity().lock()) { TaskFinished(TASKFAILFATAL, "(TAKE)No target entity"); break; } if (Position() == currentEntity().lock()->Position()) { if (std::static_pointer_cast<Item>(currentEntity().lock())->ContainedIn()) { std::weak_ptr<Container> cont(std::static_pointer_cast<Container>( std::static_pointer_cast<Item>(currentEntity().lock())->ContainedIn())); cont.lock()->RemoveItem( std::static_pointer_cast<Item>(currentEntity().lock())); } PickupItem(std::static_pointer_cast<Item>(currentEntity().lock())); TaskFinished(TASKSUCCESS); break; } else { TaskFinished(TASKFAILFATAL, "(TAKE)Item not found"); break; } break; case DROP: DropItem(carried); carried.reset(); TaskFinished(TASKSUCCESS); break; case PUTIN: if (carried) { inventory->RemoveItem(carried); carried->Position(Position()); if (!currentEntity().lock()) { TaskFinished(TASKFAILFATAL, "(PUTIN)Target does not exist"); break; } if (!Game::Adjacent(Position(), currentEntity().lock()->Position())) { TaskFinished(TASKFAILFATAL, "(PUTIN)Not adjacent to container"); break; } if (std::dynamic_pointer_cast<Container>(currentEntity().lock())) { std::shared_ptr<Container> cont = std::static_pointer_cast<Container>(currentEntity().lock()); if (!cont->AddItem(carried)) { TaskFinished(TASKFAILFATAL, "(PUTIN)Container full"); break; } bulk -= carried->GetBulk(); } else { TaskFinished(TASKFAILFATAL, "(PUTIN)Target not a container"); break; } } carried.reset(); TaskFinished(TASKSUCCESS); break; case DRINK: //Either we have an item target to drink, or a water tile if (carried) { //Drink from an item timer = std::static_pointer_cast<OrganicItem>(carried)->Nutrition(); inventory->RemoveItem(carried); bulk -= carried->GetBulk(); ApplyEffects(carried); Game::Inst()->RemoveItem(carried); carried = std::shared_ptr<Item>(); } else if (timer == 0) { //Drink from a water tile if (Game::Adjacent(pos, currentTarget())) { if (std::shared_ptr<WaterNode> water = map->GetWater(currentTarget()).lock()) { if (water->Depth() > DRINKABLE_WATER_DEPTH) { thirst -= (int)(THIRST_THRESHOLD / 10); AddEffect(DRINKING); //Create a temporary water item to give us the right effects std::shared_ptr<Item> waterItem = Game::Inst()->GetItem( Game::Inst()->CreateItem(Position(), Item::StringToItemType("water"), false, -1)); ApplyEffects(waterItem); Game::Inst()->RemoveItem(waterItem); if (thirst < 0) { TaskFinished(TASKSUCCESS); } break; } } } TaskFinished(TASKFAILFATAL, "(DRINK)Not enough water"); } if (timer > 0) { AddEffect(DRINKING); thirst -= std::min((int)(THIRST_THRESHOLD / 5), timer); timer -= (int)(THIRST_THRESHOLD / 5); if (timer <= 0) { timer = 0; TaskFinished(TASKSUCCESS); } } break; case EAT: if (carried) { //Set the nutrition to the timer variable if (std::dynamic_pointer_cast<OrganicItem>(carried)) { timer = std::static_pointer_cast<OrganicItem>(carried)->Nutrition(); } else timer = 100; inventory->RemoveItem(carried); bulk -= carried->GetBulk(); ApplyEffects(carried); for (std::list<ItemType>::iterator fruiti = Item::Presets[carried->Type()].fruits.begin(); fruiti != Item::Presets[carried->Type()].fruits.end(); ++fruiti) { Game::Inst()->CreateItem(Position(), *fruiti, true); } Game::Inst()->RemoveItem(carried); } else if (timer == 0) { //Look in all adjacent tiles for anything edible for (int ix = pos.X() - 1; ix <= pos.X() + 1; ++ix) { for (int iy = pos.Y() - 1; iy <= pos.Y() + 1; ++iy) { Coordinate p(ix,iy); if (map->IsInside(p)) { for (std::set<int>::iterator itemi = map->ItemList(p)->begin(); itemi != map->ItemList(p)->end(); ++itemi) { std::shared_ptr<Item> item = Game::Inst()->GetItem(*itemi); if (item && (item->IsCategory(Item::StringToItemCategory("food")) || item->IsCategory(Item::StringToItemCategory("corpse")))) { jobs.front()->ReserveEntity(item); jobs.front()->tasks.push_back(Task(MOVE, item->Position())); jobs.front()->tasks.push_back(Task(TAKE, item->Position(), item)); jobs.front()->tasks.push_back(Task(EAT)); goto CONTINUEEAT; } } } } } } if (timer > 0) { AddEffect(EATING); hunger -= std::min(5000, timer); timer -= 5000; if (timer <= 0) { timer = 0; TaskFinished(TASKSUCCESS); } break; } CONTINUEEAT: carried = std::shared_ptr<Item>(); TaskFinished(TASKSUCCESS); break; case FIND: foundItem = Game::Inst()->FindItemByCategoryFromStockpiles(currentTask()->item, currentTask()->target, currentTask()->flags); if (!foundItem) { TaskFinished(TASKFAILFATAL, "(FIND)Failed"); break; } else { if (factionPtr->IsFriendsWith(PLAYERFACTION)) currentJob().lock()->ReserveEntity(foundItem); TaskFinished(TASKSUCCESS); break; } case USE: if (currentEntity().lock() && std::dynamic_pointer_cast<Construction>(currentEntity().lock())) { tmp = std::static_pointer_cast<Construction>(currentEntity().lock())->Use(); AddEffect(WORKING); if (tmp >= 100) { TaskFinished(TASKSUCCESS); } else if (tmp < 0) { TaskFinished(TASKFAILFATAL, "(USE)Can not use (tmp<0)"); break; } } else { TaskFinished(TASKFAILFATAL, "(USE)Attempted to use non-construct"); break; } break; case HARVEST: if (carried) { bool stockpile = false; if (nextTask() && nextTask()->action == STOCKPILEITEM) stockpile = true; std::shared_ptr<Item> plant = carried; inventory->RemoveItem(carried); bulk -= plant->GetBulk(); carried = std::shared_ptr<Item>(); for (std::list<ItemType>::iterator fruiti = Item::Presets[plant->Type()].fruits.begin(); fruiti != Item::Presets[plant->Type()].fruits.end(); ++fruiti) { if (stockpile) { int item = Game::Inst()->CreateItem(Position(), *fruiti, false); Stats::Inst()->ItemBuilt(Item::Presets[*fruiti].name); //Harvesting counts as production PickupItem(Game::Inst()->GetItem(item)); stockpile = false; } else { Game::Inst()->CreateItem(Position(), *fruiti, true); } } Game::Inst()->RemoveItem(plant); TaskFinished(TASKSUCCESS); break; } else { inventory->RemoveItem(carried); carried = std::shared_ptr<Item>(); TaskFinished(TASKFAILFATAL, "(HARVEST)Carrying nonexistant item"); break; } case FELL: if (std::shared_ptr<NatureObject> tree = std::static_pointer_cast<NatureObject>(currentEntity().lock())) { tmp = tree->Fell(); //This'll be called about 100-150 times per tree if (mainHand && Random::Generate(300) == 0) DecreaseItemCondition(mainHand); AddEffect(WORKING); if (tmp <= 0) { bool stockpile = false; if (nextTask() && nextTask()->action == STOCKPILEITEM) stockpile = true; for (std::list<ItemType>::iterator iti = NatureObject::Presets[tree->Type()].components.begin(); iti != NatureObject::Presets[tree->Type()].components.end(); ++iti) { if (stockpile) { int item = Game::Inst()->CreateItem(tree->Position(), *iti, false); Stats::Inst()->ItemBuilt( Item::Presets[*iti].name); //Felling trees counts as item production DropItem(carried); PickupItem(Game::Inst()->GetItem(item)); stockpile = false; } else { Game::Inst()->CreateItem(tree->Position(), *iti, true); } } Game::Inst()->RemoveNatureObject(tree); TaskFinished(TASKSUCCESS); break; } //Job underway break; } TaskFinished(TASKFAILFATAL, "(FELL) No NatureObject to fell"); break; case HARVESTWILDPLANT: if (std::shared_ptr<NatureObject> plant = std::static_pointer_cast<NatureObject>( currentEntity().lock())) { tmp = plant->Harvest(); AddEffect(WORKING); if (tmp <= 0) { bool stockpile = false; if (nextTask() && nextTask()->action == STOCKPILEITEM) stockpile = true; for (std::list<ItemType>::iterator iti = NatureObject::Presets[plant->Type()].components.begin(); iti != NatureObject::Presets[plant->Type()].components.end(); ++iti) { if (stockpile) { int item = Game::Inst()->CreateItem(plant->Position(), *iti, false); DropItem(carried); PickupItem(Game::Inst()->GetItem(item)); stockpile = false; } else { Game::Inst()->CreateItem(plant->Position(), *iti, true); } } Game::Inst()->RemoveNatureObject(plant); TaskFinished(TASKSUCCESS); break; } //Job underway break; } TaskFinished(TASKFAILFATAL, "(HARVESTWILDPLANT)Harvest target doesn't exist"); break; case KILL: //The reason KILL isn't a combination of MOVEADJACENT and something else is that the other moving actions //assume their target isn't a moving one if (!currentEntity().lock()) { TaskFinished(TASKSUCCESS); break; } if (Game::Adjacent(Position(), currentEntity())) { Hit(currentEntity(), currentTask()->flags != 0); break; } else if (currentTask()->flags == 0 && WieldingRangedWeapon() && quiver && !quiver->empty()) { FireProjectile(currentEntity()); break; } else if (hasMagicRangedAttacks) { CastOffensiveSpell(currentEntity()); break; } if (!taskBegun || Random::Generate(UPDATES_PER_SECOND * 2 - 1) == 0) { //Repath every ~2 seconds tmpCoord = Game::Inst()->FindClosestAdjacent(Position(), currentEntity(), GetFaction()); if (tmpCoord.X() >= 0) { findPath(tmpCoord); } taskBegun = true; lastMoveResult = TASKCONTINUE; } if (lastMoveResult == TASKFAILFATAL || lastMoveResult == TASKFAILNONFATAL) { TaskFinished(lastMoveResult, std::string("(KILL)Could not find path to target")); break; } else if (lastMoveResult == PATHEMPTY) { tmpCoord = Game::Inst()->FindClosestAdjacent(Position(), currentEntity(), GetFaction()); if (tmpCoord.X() >= 0) { findPath(tmpCoord); } } break; case FLEEMAP: if (pos.onExtentEdges(zero, map->Extent())) { //We are at the edge, escape! Escape(); return; } //Find the closest edge and change into a MOVE task and a new FLEEMAP task //Unfortunately this assumes that FLEEMAP is the last task in a job, //which might not be. { Coordinate target; tmp = std::abs(pos.X() - map->Width() / 2); if (tmp < std::abs(pos.Y() - map->Height() / 2)) { int target_y = (pos.Y() < map->Height() / 2) ? 0 : map->Height()-1; target = Coordinate(pos.X(), target_y); } else { int target_x = (pos.X() < map->Width() / 2) ? 0 : map->Width()-1; target = Coordinate(target_x, pos.Y()); } if (map->IsWalkable(target, static_cast<void*>(this))) currentJob().lock()->tasks[taskIndex] = Task(MOVE, target); else currentJob().lock()->tasks[taskIndex] = Task(MOVENEAR, target); } currentJob().lock()->tasks.push_back(Task(FLEEMAP)); break; case SLEEP: AddEffect(SLEEPING); AddEffect(BADSLEEP); weariness -= 25; if (weariness <= 0) { if (std::shared_ptr<Entity> entity = currentEntity().lock()) { if (std::static_pointer_cast<Construction>(entity)->HasTag(BED)) { RemoveEffect(BADSLEEP); } } TaskFinished(TASKSUCCESS); break; } break; case DISMANTLE: if (std::shared_ptr<Construction> construct = std::static_pointer_cast<Construction>( currentEntity().lock())) { construct->Condition(construct->Condition() - 10); AddEffect(WORKING); if (construct->Condition() <= 0) { Game::Inst()->RemoveConstruction(construct); TaskFinished(TASKSUCCESS); break; } } else { TaskFinished(TASKFAILFATAL, "(DISMANTLE)Construction does not exist!"); } break; case WIELD: if (carried) { if (mainHand) { //Drop currently wielded weapon if such exists DropItem(mainHand); mainHand.reset(); } mainHand = carried; carried.reset(); TaskFinished(TASKSUCCESS); #ifdef DEBUG std::cout<<name<<" wielded "<<mainHand->Name()<<"\n"; #endif break; } TaskFinished(TASKFAILFATAL, "(WIELD)Not carrying an item"); break; case WEAR: if (carried) { if (carried->IsCategory(Item::StringToItemCategory("Armor"))) { if (armor) { //Remove armor and drop if already wearing DropItem(armor); armor.reset(); } armor = carried; #ifdef DEBUG std::cout<<name<<" wearing "<<armor->Name()<<"\n"; #endif } else if (carried->IsCategory(Item::StringToItemCategory("Quiver"))) { if (quiver) { //Remove quiver and drop if already wearing DropItem(quiver); quiver.reset(); } quiver = std::static_pointer_cast<Container>(carried); #ifdef DEBUG std::cout<<name<<" wearing "<<quiver->Name()<<"\n"; #endif } carried.reset(); TaskFinished(TASKSUCCESS); break; } TaskFinished(TASKFAILFATAL, "(WEAR)Not carrying an item"); break; case BOGIRON: if (map->GetType(pos) == TILEBOG) { AddEffect(WORKING); if (Random::Generate(UPDATES_PER_SECOND * 15 - 1) == 0) { bool stockpile = false; if (nextTask() && nextTask()->action == STOCKPILEITEM) stockpile = true; if (stockpile) { int item = Game::Inst()->CreateItem(Position(), Item::StringToItemType("Bog iron"), false); DropItem(carried); PickupItem(Game::Inst()->GetItem(item)); stockpile = false; } else { Game::Inst()->CreateItem(Position(), Item::StringToItemType("Bog iron"), true); } TaskFinished(TASKSUCCESS); break; } else { break; } } TaskFinished(TASKFAILFATAL, "(BOGIRON)Not on a bog tile"); break; case STOCKPILEITEM: if (std::shared_ptr<Item> item = carried) { std::shared_ptr<Job> stockJob = Game::Inst()->StockpileItem(item, true, true, !item->Reserved()); if (stockJob) { stockJob->internal = true; //Add remaining tasks into stockjob for (unsigned int i = 1; taskIndex + i < jobs.front()->tasks.size(); ++i) { stockJob->tasks.push_back(jobs.front()->tasks[taskIndex + i]); } jobs.front()->tasks.clear(); std::deque<std::shared_ptr<Job> >::iterator jobi = jobs.begin(); ++jobi; jobs.insert(jobi, stockJob); DropItem(item); //The stockpiling job will pickup the item carried.reset(); TaskFinished(TASKSUCCESS); break; } } TaskFinished(TASKFAILFATAL, "(STOCKPILEITEM)Not carrying an item"); break; case QUIVER: if (carried) { if (!quiver) { DropItem(carried); carried.reset(); TaskFinished(TASKFAILFATAL, "(QUIVER)No quiver"); break; } inventory->RemoveItem(carried); if (!quiver->AddItem(carried)) { DropItem(carried); carried.reset(); TaskFinished(TASKFAILFATAL, "(QUIVER)Quiver full"); break; } carried.reset(); TaskFinished(TASKSUCCESS); break; } TaskFinished(TASKFAILFATAL, "(QUIVER)Not carrying an item"); break; case FILL: { std::shared_ptr<Container> cont; if (carried && (carried->IsCategory(Item::StringToItemCategory("Container")) || carried->IsCategory(Item::StringToItemCategory("Bucket")))) { cont = std::static_pointer_cast<Container>(carried); } else if (mainHand && (mainHand->IsCategory(Item::StringToItemCategory("Container")) || mainHand->IsCategory(Item::StringToItemCategory("Bucket")))) { cont = std::static_pointer_cast<Container>(mainHand); } if (cont) { if (!cont->empty() && cont->ContainsWater() == 0 && cont->ContainsFilth() == 0) { //Not empty, but doesn't have water/filth, so it has items in it TaskFinished(TASKFAILFATAL, "(FILL)Attempting to fill non-empty container"); break; } std::weak_ptr<WaterNode> wnode = map->GetWater(currentTarget()); if (wnode.lock() && wnode.lock()->Depth() > 0 && cont->ContainsFilth() == 0) { int waterAmount = std::min(50, wnode.lock()->Depth()); wnode.lock()->Depth(wnode.lock()->Depth() - waterAmount); cont->AddWater(waterAmount); TaskFinished(TASKSUCCESS); break; } std::weak_ptr<FilthNode> fnode = map->GetFilth(currentTarget()); if (fnode.lock() && fnode.lock()->Depth() > 0 && cont->ContainsWater() == 0) { int filthAmount = std::min(3, fnode.lock()->Depth()); fnode.lock()->Depth(fnode.lock()->Depth() - filthAmount); cont->AddFilth(filthAmount); TaskFinished(TASKSUCCESS); break; } TaskFinished(TASKFAILFATAL, "(FILL)Nothing to fill container with"); break; } } TaskFinished(TASKFAILFATAL, "(FILL)Not carrying a container"); break; case POUR: { std::shared_ptr<Container> sourceContainer; if (carried && (carried->IsCategory(Item::StringToItemCategory("Container")) || carried->IsCategory(Item::StringToItemCategory("Bucket")))) { sourceContainer = std::static_pointer_cast<Container>(carried); } else if (mainHand && (mainHand->IsCategory(Item::StringToItemCategory("Container")) || mainHand->IsCategory(Item::StringToItemCategory("Bucket")))) { sourceContainer = std::static_pointer_cast<Container>(mainHand); } if (sourceContainer) { if (currentEntity().lock() && std::dynamic_pointer_cast<Container>(currentEntity().lock())) { std::shared_ptr<Container> targetContainer( std::static_pointer_cast<Container>(currentEntity().lock())); if (sourceContainer->ContainsWater() > 0) { targetContainer->AddWater(sourceContainer->ContainsWater()); sourceContainer->RemoveWater(sourceContainer->ContainsWater()); } else { targetContainer->AddFilth(sourceContainer->ContainsFilth()); sourceContainer->RemoveFilth(sourceContainer->ContainsFilth()); } TaskFinished(TASKSUCCESS); break; } else if (map->IsInside(currentTarget())) { if (sourceContainer->ContainsWater() > 0) { Game::Inst()->CreateWater(currentTarget(), sourceContainer->ContainsWater()); sourceContainer->RemoveWater(sourceContainer->ContainsWater()); } else { Game::Inst()->CreateFilth(currentTarget(), sourceContainer->ContainsFilth()); sourceContainer->RemoveFilth(sourceContainer->ContainsFilth()); } TaskFinished(TASKSUCCESS); break; } } else { TaskFinished(TASKFAILFATAL, "(POUR) Not carrying a container!"); break; } } TaskFinished(TASKFAILFATAL, "(POUR)No valid target"); break; case DIG: if (!taskBegun) { timer = 0; taskBegun = true; } else { AddEffect(WORKING); if (mainHand && Random::Generate(300) == 0) DecreaseItemCondition(mainHand); if (++timer >= 50) { map->SetLow(currentTarget(), true); map->ChangeType(currentTarget(), TILEDITCH); int amount = 0; int chance = Random::Generate(9); if (chance < 4) amount = 1; else if (chance < 8) amount = 2; else amount = 3; for (int i = 0; i < amount; ++i) Game::Inst()->CreateItem(Position(), Item::StringToItemType("earth")); TaskFinished(TASKSUCCESS); } } break; case FORGET: foundItem.reset(); TaskFinished(TASKSUCCESS); break; case UNWIELD: if (mainHand) { foundItem = mainHand; DropItem(mainHand); mainHand.reset(); } TaskFinished(TASKSUCCESS); break; case GETANGRY: aggressive = true; TaskFinished(TASKSUCCESS); break; case CALMDOWN: aggressive = false; TaskFinished(TASKSUCCESS); break; case STARTFIRE: if (!taskBegun) { taskBegun = true; timer = 0; } else { AddEffect(WORKING); if (++timer >= 50) { Game::Inst()->CreateFire(currentTarget(), 10); TaskFinished(TASKSUCCESS); } } break; case REPAIR: if (currentEntity().lock() && std::dynamic_pointer_cast<Construction>(currentEntity().lock())) { tmp = std::static_pointer_cast<Construction>(currentEntity().lock())->Repair(); AddEffect(WORKING); if (tmp >= 100) { if (carried) { //Repairjobs usually require some material inventory->RemoveItem(carried); bulk -= carried->GetBulk(); Game::Inst()->RemoveItem(carried); carried.reset(); } TaskFinished(TASKSUCCESS); } else if (tmp < 0) { TaskFinished(TASKFAILFATAL, "(USE)Can not use (tmp<0)"); break; } } else { TaskFinished(TASKFAILFATAL, "(USE)Attempted to use non-construct"); break; } break; case FILLDITCH: if (carried && carried->IsCategory(Item::StringToItemCategory("earth"))) { if (map->GetType(currentTarget()) != TILEDITCH) { TaskFinished(TASKFAILFATAL, "(FILLDITCH)Target not a ditch"); break; } if (!taskBegun) { taskBegun = true; timer = 0; } else { AddEffect(WORKING); if (++timer >= 50) { inventory->RemoveItem(carried); bulk -= carried->GetBulk(); Game::Inst()->RemoveItem(carried); carried.reset(); map->ChangeType(currentTarget(), TILEMUD); TaskFinished(TASKSUCCESS); break; } } } else { TaskFinished(TASKFAILFATAL, "(FILLDITCH)Not carrying earth"); break; } break; default: TaskFinished(TASKFAILFATAL, "*BUG*Unknown task*BUG*"); break; } } else { if (HasEffect(DRUNK)) { JobManager::Inst()->NPCNotWaiting(uid); std::shared_ptr<Job> drunkJob(new Job("Huh?")); drunkJob->internal = true; run = false; drunkJob->tasks.push_back(Task(MOVENEAR, Position())); jobs.push_back(drunkJob); if (Random::Generate(75) == 0) GoBerserk(); } else if (HasEffect(PANIC)) { JobManager::Inst()->NPCNotWaiting(uid); if (jobs.empty() && threatLocation != undefined) { std::shared_ptr<Job> fleeJob(new Job("Flee")); fleeJob->internal = true; int x = pos.X(), y = pos.Y(); int dx = x - threatLocation.X(); int dy = y - threatLocation.Y(); Coordinate t1(x + dx, y + dy), t2(x + dx, y), t3(x, y + dy); if (map->IsWalkable(t1, (void*)this)) { fleeJob->tasks.push_back(Task(MOVE, t1)); jobs.push_back(fleeJob); } else if (map->IsWalkable(t2, (void*)this)) { fleeJob->tasks.push_back(Task(MOVE, t2)); jobs.push_back(fleeJob); } else if (map->IsWalkable(t3, (void*)this)) { fleeJob->tasks.push_back(Task(MOVE, t3)); jobs.push_back(fleeJob); } } } else if (!GetSquadJob(std::static_pointer_cast<NPC>(shared_from_this())) && !FindJob(std::static_pointer_cast<NPC>(shared_from_this()))) { std::shared_ptr<Job> idleJob(new Job("Idle")); idleJob->internal = true; if (faction == PLAYERFACTION) { if (Random::Generate(8) < 7) { idleJob->tasks.push_back(Task(MOVENEAR, Camp::Inst()->Center())); } else { Coordinate randomLocation = Camp::Inst()->GetRandomSpot(); idleJob->tasks.push_back(Task(MOVENEAR, randomLocation != undefined ? randomLocation : Camp::Inst()->Center())); } if (map->IsTerritory(pos)) run = false; } else { idleJob->tasks.push_back(Task(MOVENEAR, Position())); run = false; } idleJob->tasks.push_back(Task(WAIT, Coordinate(Random::Generate(9), 0))); jobs.push_back(idleJob); } } } return; } void NPC::StartJob(std::shared_ptr<Job> job) { TaskFinished(TASKOWNDONE, ""); if (job->RequiresTool() && (!mainHand || !mainHand->IsCategory(job->GetRequiredTool()))) { //We insert each one into the beginning, so these are inserted in reverse order job->tasks.insert(job->tasks.begin(), Task(FORGET)); /*"forget" the item we found, otherwise later tasks might incorrectly refer to it */ job->tasks.insert(job->tasks.begin(), Task(WIELD)); job->tasks.insert(job->tasks.begin(), Task(TAKE)); job->tasks.insert(job->tasks.begin(), Task(MOVE)); job->tasks.insert(job->tasks.begin(), Task(FIND, Position(), std::weak_ptr<Entity>(), job->GetRequiredTool())); addedTasksToCurrentJob = 5; } jobs.push_back(job); } TaskResult NPC::Move(TaskResult oldResult) { if (run) nextMove += effectiveStats[MOVESPEED]; else { if (effectiveStats[MOVESPEED]/3 == 0 && effectiveStats[MOVESPEED] != 0) ++nextMove; else nextMove += effectiveStats[MOVESPEED]/3; } while (nextMove > 100) { nextMove -= 100; boost::mutex::scoped_try_lock pathLock(pathMutex); if (pathLock.owns_lock()) { if (nopath) {nopath = false; return TASKFAILFATAL;} if (pathIndex < path->size() && pathIndex >= 0) { //Get next move Coordinate move; path->get(pathIndex, move.Xptr(), move.Yptr()); if (pathIndex != path->size()-1 && map->NPCList(move)->size() > 0) { //Our next move target has an npc on it, and it isn't our target Coordinate next; path->get(pathIndex+1, next.Xptr(), next.Yptr()); /*Find a new target that is adjacent to our current, next, and the next after targets Effectively this makes the npc try and move around another npc, instead of walking onto the same tile and slowing down*/ map->FindEquivalentMoveTarget(pos, move, next, static_cast<void*>(this)); } //If we're about to step on a dangerous tile that we didn't plan to, repath if (!pathIsDangerous && map->IsDangerous(move, faction)) return TASKFAILNONFATAL; if (map->IsWalkable(move, static_cast<void*>(this))) { //If the tile is walkable, move there Position(move); map->WalkOver(move); ++pathIndex; } else { //Encountered an obstacle. Fail if the npc can't tunnel if (IsTunneler() && map->GetConstruction(move) >= 0) { Hit(Game::Inst()->GetConstruction(map->GetConstruction(move))); return TASKCONTINUE; } return TASKFAILNONFATAL; } return TASKCONTINUE; //Everything is ok } else if (!findPathWorking) return PATHEMPTY; //No path } } //Can't move yet, so the earlier result is still valid return oldResult; } unsigned int NPC::pathingThreadCount = 0; boost::mutex NPC::threadCountMutex; void NPC::findPath(Coordinate target) { pathMutex.lock(); findPathWorking = true; pathIsDangerous = false; pathIndex = 0; delete path; path = new TCODPath(map->Width(), map->Height(), map, static_cast<void*>(this)); threadCountMutex.lock(); if (pathingThreadCount < 12) { ++pathingThreadCount; threadCountMutex.unlock(); pathMutex.unlock(); boost::thread pathThread(boost::bind(tFindPath, path, pos.X(), pos.Y(), target.X(), target.Y(), this, true)); } else { threadCountMutex.unlock(); pathMutex.unlock(); tFindPath(path, pos.X(), pos.Y(), target.X(), target.Y(), this, false); } } bool NPC::IsPathWalkable() { for (int i = 0; i < path->size(); i++) { Coordinate p; path->get(i, p.Xptr(), p.Yptr()); if (!map->IsWalkable(p, static_cast<void*>(this))) return false; } return true; } void NPC::speed(unsigned int value) {baseStats[MOVESPEED]=value;} unsigned int NPC::speed() const {return effectiveStats[MOVESPEED];} void NPC::Draw(Coordinate upleft, TCODConsole *console) { int screenx = (pos - upleft).X(); int screeny = (pos - upleft).Y(); if (screenx >= 0 && screenx < console->getWidth() && screeny >= 0 && screeny < console->getHeight()) { if (statusGraphicCounter < 5 || statusEffectIterator == statusEffects.end()) { console->putCharEx(screenx, screeny, _graphic, _color, _bgcolor); } else { console->putCharEx(screenx, screeny, statusEffectIterator->graphic, statusEffectIterator->color, _bgcolor); } } } void NPC::GetTooltip(int x, int y, Tooltip *tooltip) { Entity::GetTooltip(x, y, tooltip); if(faction == PLAYERFACTION && !jobs.empty()) { std::shared_ptr<Job> job = jobs.front(); if (job->name != "Idle") { tooltip->AddEntry(TooltipEntry((boost::format(" %s") % job->name).str(), TCODColor::grey)); } } } void NPC::color(TCODColor value, TCODColor bvalue) { _color = value; _bgcolor = bvalue; } void NPC::graphic(int value) { _graphic = value; } int NPC::GetGraphicsHint() const { return NPC::Presets[type].graphicsHint; } bool NPC::Expert() const {return expert;} void NPC::Expert(bool value) {expert = value;} Coordinate NPC::Position() const {return pos;} bool NPC::Dead() const { return dead; } void NPC::Kill(std::string deathMessage) { if (!dead) {//You can't be killed if you're already dead! dead = true; health = 0; if (NPC::Presets[type].deathItem >= 0) { int corpsenum = Game::Inst()->CreateItem(Position(), NPC::Presets[type].deathItem, false); std::shared_ptr<Item> corpse = Game::Inst()->GetItem(corpsenum); corpse->Color(_color); corpse->Name(corpse->Name() + "(" + name + ")"); if (velocity > 0) { corpse->CalculateFlightPath(GetVelocityTarget(), velocity, GetHeight()); } } else if (NPC::Presets[type].deathItem == -1) { Game::Inst()->CreateFilth(Position()); } while (!jobs.empty()) TaskFinished(TASKFAILFATAL, std::string("dead")); while (!inventory->empty()) { std::shared_ptr<Item> witem = inventory->GetFirstItem(); if (std::shared_ptr<Item> item = witem) { item->Position(Position()); item->PutInContainer(); item->SetFaction(PLAYERFACTION); } inventory->RemoveItem(witem); } if (deathMessage.length() > 0) Announce::Inst()->AddMsg(deathMessage, (factionPtr->IsFriendsWith(PLAYERFACTION) ? TCODColor::red : TCODColor::brass), Position()); Stats::Inst()->deaths[NPC::NPCTypeToString(type)] += 1; Stats::Inst()->AddPoints(NPC::Presets[type].health); } } void NPC::DropItem(std::shared_ptr<Item> witem) { if (std::shared_ptr<Item> item = witem) { inventory->RemoveItem(item); item->Position(Position()); item->PutInContainer(); bulk -= item->GetBulk(); //If the item is a container with filth in it, spill it on the ground if (std::dynamic_pointer_cast<Container>(item)) { std::shared_ptr<Container> cont(std::static_pointer_cast<Container>(item)); if (cont->ContainsFilth() > 0) { Game::Inst()->CreateFilth(Position(), cont->ContainsFilth()); cont->RemoveFilth(cont->ContainsFilth()); } } } } Coordinate NPC::currentTarget() const { if (currentTask()->target == undefined && foundItem) { return foundItem->Position(); } return currentTask()->target; } std::weak_ptr<Entity> NPC::currentEntity() const { if (currentTask()->entity.lock()) return currentTask()->entity; else if (foundItem) return std::weak_ptr<Entity>(foundItem); return std::weak_ptr<Entity>(); } void tFindPath(TCODPath *path, int x0, int y0, int x1, int y1, NPC* npc, bool threaded) { boost::mutex::scoped_lock pathLock(npc->pathMutex); boost::shared_lock<boost::shared_mutex> readCacheLock(npc->map->cacheMutex); npc->nopath = !path->compute(x0, y0, x1, y1); //TODO factorize with path walkability test for (int i = 0; i < path->size(); ++i) { Coordinate p; path->get(i, p.Xptr(), p.Yptr()); if (npc->map->IsDangerousCache(p, npc->faction)) { npc->pathIsDangerous = true; break;//One dangerous tile = whole path considered dangerous } } npc->findPathWorking = false; if (threaded) { NPC::threadCountMutex.lock(); --NPC::pathingThreadCount; NPC::threadCountMutex.unlock(); } } bool NPC::GetSquadJob(std::shared_ptr<NPC> npc) { if (std::shared_ptr<Squad> squad = npc->MemberOf().lock()) { JobManager::Inst()->NPCNotWaiting(npc->uid); npc->aggressive = true; std::shared_ptr<Job> newJob(new Job("Follow orders")); newJob->internal = true; //Priority #1, if the creature can wield a weapon get one if possible /*TODO: Right now this only makes friendlies take a weapon from a stockpile It should be expanded to allow all npc's to search for nearby weapons lying around. */ if (!npc->mainHand && npc->GetFaction() == PLAYERFACTION && squad->Weapon() >= 0) { for (std::list<Attack>::iterator attacki = npc->attacks.begin(); attacki != npc->attacks.end(); ++attacki) { if (attacki->Type() == DAMAGE_WIELDED) { if (Game::Inst()->FindItemByCategoryFromStockpiles( squad->Weapon(), npc->Position())) { newJob->tasks.push_back(Task(FIND, npc->Position(), std::shared_ptr<Entity>(), squad->Weapon())); newJob->tasks.push_back(Task(MOVE)); newJob->tasks.push_back(Task(TAKE)); newJob->tasks.push_back(Task(WIELD)); npc->jobs.push_back(newJob); return true; } break; } } } if (npc->WieldingRangedWeapon()) { if (!npc->quiver) { if (Game::Inst()->FindItemByCategoryFromStockpiles(Item::StringToItemCategory("Quiver"), npc->Position())) { newJob->tasks.push_back(Task(FIND, npc->Position(), std::shared_ptr<Entity>(), Item::StringToItemCategory("Quiver"))); newJob->tasks.push_back(Task(MOVE)); newJob->tasks.push_back(Task(TAKE)); newJob->tasks.push_back(Task(WEAR)); npc->jobs.push_back(newJob); return true; } } else if (npc->quiver->empty()) { if (Game::Inst()->FindItemByCategoryFromStockpiles( npc->mainHand->GetAttack().Projectile(), npc->Position())) { for (int i = 0; i < 20; ++i) { newJob->tasks.push_back(Task(FIND, npc->Position(), std::shared_ptr<Entity>(), npc->mainHand->GetAttack().Projectile())); newJob->tasks.push_back(Task(MOVE)); newJob->tasks.push_back(Task(TAKE)); newJob->tasks.push_back(Task(QUIVER)); } npc->jobs.push_back(newJob); return true; } } } if (!npc->armor && npc->GetFaction() == PLAYERFACTION && squad->Armor() >= 0) { npc->FindNewArmor(); } switch (squad->GetOrder(npc->orderIndex)) { //GetOrder handles incrementing orderIndex case GUARD: if (squad->TargetCoordinate(npc->orderIndex) != undefined) { if (squad->Weapon() == Item::StringToItemCategory("Ranged weapon")) { Coordinate p = npc->map->FindRangedAdvantage(squad->TargetCoordinate(npc->orderIndex)); if (p != undefined) { newJob->tasks.push_back(Task(MOVE, p)); //TODO remove WAIT hack newJob->tasks.push_back(Task(WAIT, Coordinate(5*15, 0))); } } if (newJob->tasks.empty()) { newJob->tasks.push_back(Task(MOVENEAR, squad->TargetCoordinate(npc->orderIndex))); //WAIT waits Coordinate.x / 5 seconds //TODO remove WAIT hack newJob->tasks.push_back(Task(WAIT, Coordinate(5*5, 0))); } if (!newJob->tasks.empty()) { npc->jobs.push_back(newJob); if (Distance(npc->Position(), squad->TargetCoordinate(npc->orderIndex)) < 10) npc->run = false; return true; } } break; case FOLLOW: if (squad->TargetEntity(npc->orderIndex).lock()) { newJob->tasks.push_back(Task(MOVENEAR, squad->TargetEntity(npc->orderIndex).lock()->Position(), squad->TargetEntity(npc->orderIndex))); npc->jobs.push_back(newJob); return true; } break; default: break; } } return false; } bool NPC::JobManagerFinder(std::shared_ptr<NPC> npc) { if (!npc->MemberOf().lock()) { JobManager::Inst()->NPCWaiting(npc->uid); } return false; } void NPC::PlayerNPCReact(std::shared_ptr<NPC> npc) { bool surroundingsScanned = false; //If carrying a container and adjacent to fire, dump it on it immediately if (std::shared_ptr<Item> carriedItem = npc->Carrying()) { if (carriedItem->IsCategory(Item::StringToItemCategory("bucket")) || carriedItem->IsCategory(Item::StringToItemCategory("container"))) { npc->ScanSurroundings(true); surroundingsScanned = true; if (npc->seenFire && Game::Inst()->Adjacent(npc->threatLocation, npc->Position())) { npc->DumpContainer(npc->threatLocation); npc->TaskFinished(TASKFAILNONFATAL); } } } if (npc->coward) { if (!surroundingsScanned) npc->ScanSurroundings(); surroundingsScanned = true; //NPCs with the CHICKENHEART trait panic more than usual if they see fire if (npc->HasTrait(CHICKENHEART) && npc->seenFire && (npc->jobs.empty() || npc->jobs.front()->name != "Aaaaaaaah!!")) { while (!npc->jobs.empty()) npc->TaskFinished(TASKFAILNONFATAL, "(FAIL)Chickenheart"); std::shared_ptr<Job> runAroundLikeAHeadlessChickenJob(new Job("Aaaaaaaah!!")); for (int i = 0; i < 30; ++i) runAroundLikeAHeadlessChickenJob->tasks.push_back( Task(MOVE, Random::ChooseInRadius(npc->Position(), 2))); runAroundLikeAHeadlessChickenJob->internal = true; npc->jobs.push_back(runAroundLikeAHeadlessChickenJob); npc->AddEffect(PANIC); return; } //Cowards panic if they see aggressive unfriendlies or their attacker for (std::list<std::weak_ptr<NPC> >::iterator npci = npc->nearNpcs.begin(); npci != npc->nearNpcs.end(); ++npci) { std::shared_ptr<NPC> otherNpc = npci->lock(); if ((!npc->factionPtr->IsFriendsWith(otherNpc->GetFaction()) && otherNpc->aggressive) || otherNpc == npc->aggressor.lock()) { JobManager::Inst()->NPCNotWaiting(npc->uid); while (!npc->jobs.empty()) npc->TaskFinished(TASKFAILNONFATAL, "(FAIL)Enemy sighted"); npc->AddEffect(PANIC); npc->threatLocation = otherNpc->Position(); return; } } } else { //Aggressive npcs attack unfriendlies if (npc->aggressive) { if (npc->jobs.empty() || npc->currentTask()->action != KILL) { if (!surroundingsScanned) npc->ScanSurroundings(true); surroundingsScanned = true; for (std::list<std::weak_ptr<NPC> >::iterator npci = npc->nearNpcs.begin(); npci != npc->nearNpcs.end(); ++npci) { if (!npc->factionPtr->IsFriendsWith(npci->lock()->GetFaction())) { JobManager::Inst()->NPCNotWaiting(npc->uid); std::shared_ptr<Job> killJob(new Job("Kill " + npci->lock()->name)); killJob->internal = true; killJob->tasks.push_back(Task(KILL, npci->lock()->Position(), *npci)); while (!npc->jobs.empty()) npc->TaskFinished(TASKFAILNONFATAL, "(FAIL)Kill enemy"); npc->jobs.push_back(killJob); return; } } } } //Npcs without BRAVE panic if they see fire if (!npc->HasEffect(BRAVE)) { if (!surroundingsScanned) npc->ScanSurroundings(); surroundingsScanned = true; if (npc->seenFire) { npc->AddEffect(PANIC); while (!npc->jobs.empty()) npc->TaskFinished(TASKFAILFATAL, "(FAIL)Seen fire"); } } } } void NPC::AnimalReact(std::shared_ptr<NPC> animal) { animal->ScanSurroundings(); //Aggressive animals attack constructions/other creatures depending on faction if (animal->aggressive) { if (animal->factionPtr->GetCurrentGoal() == FACTIONDESTROY && !animal->nearConstructions.empty()) { for (std::list<std::weak_ptr<Construction> >::iterator consi = animal->nearConstructions.begin(); consi != animal->nearConstructions.end(); ++consi) { if (std::shared_ptr<Construction> construct = consi->lock()) { if (!construct->HasTag(PERMANENT) && (construct->HasTag(WORKSHOP) || (construct->HasTag(WALL) && Random::Generate(10) == 0))) { std::shared_ptr<Job> destroyJob(new Job("Destroy " + construct->Name())); destroyJob->internal = true; destroyJob->tasks.push_back(Task(MOVEADJACENT, construct->Position(), construct)); destroyJob->tasks.push_back(Task(KILL, construct->Position(), construct)); while (!animal->jobs.empty()) animal->TaskFinished(TASKFAILNONFATAL); animal->jobs.push_back(destroyJob); return; } } } } else { for (std::list<std::weak_ptr<NPC> >::iterator npci = animal->nearNpcs.begin(); npci != animal->nearNpcs.end(); ++npci) { std::shared_ptr<NPC> otherNPC = npci->lock(); if (otherNPC && !animal->factionPtr->IsFriendsWith(otherNPC->GetFaction())) { std::shared_ptr<Job> killJob(new Job("Kill " + otherNPC->name)); killJob->internal = true; killJob->tasks.push_back(Task(KILL, otherNPC->Position(), *npci)); while (!animal->jobs.empty()) animal->TaskFinished(TASKFAILNONFATAL); animal->jobs.push_back(killJob); return; } } } } //Cowards run away from others if (animal->coward) { for (std::list<std::weak_ptr<NPC> >::iterator npci = animal->nearNpcs.begin(); npci != animal->nearNpcs.end(); ++npci) { if (!animal->factionPtr->IsFriendsWith(npci->lock()->GetFaction())) { animal->AddEffect(PANIC); animal->run = true; } } } //Animals with the 'angers' tag get angry if attacked if (animal->aggressor.lock() && NPC::Presets[animal->type].tags.find("angers") != NPC::Presets[animal->type].tags.end()) { //Turn into a hostile animal if attacked by the player's creatures animal->aggressive = true; animal->RemoveEffect(PANIC); animal->AddEffect(RAGE); } //All animals avoid fire if (animal->seenFire) { animal->AddEffect(PANIC); while (!animal->jobs.empty()) animal->TaskFinished(TASKFAILFATAL); return; } } void NPC::AddEffect(StatusEffectType effect) { AddEffect(StatusEffect(effect)); } void NPC::AddEffect(StatusEffect effect) { if (effect.type == PANIC && HasEffect(BRAVE)) return; //BRAVE prevents PANIC if (effect.type == BRAVE && HasTrait(CHICKENHEART)) return; //CHICKENHEARTs can't be BRAVE if (effect.type == BRAVE && HasEffect(PANIC)) RemoveEffect(PANIC); //Becoming BRAVE stops PANIC if (effect.type == FLYING) isFlying = true; for (std::list<StatusEffect>::iterator statusEffectI = statusEffects.begin(); statusEffectI != statusEffects.end(); ++statusEffectI) { if (statusEffectI->type == effect.type) { statusEffectI->cooldown = statusEffectI->cooldownDefault; return; } } statusEffects.push_back(effect); statusEffectsChanged = true; } void NPC::RemoveEffect(StatusEffectType effect) { if (effect == FLYING) isFlying = false; for (std::list<StatusEffect>::iterator statusEffectI = statusEffects.begin(); statusEffectI != statusEffects.end(); ++statusEffectI) { if (statusEffectI->type == effect) { if (statusEffectIterator == statusEffectI) ++statusEffectIterator; statusEffects.erase(statusEffectI); if (statusEffectIterator == statusEffects.end()) statusEffectIterator = statusEffects.begin(); if (statusEffectIterator != statusEffects.end() && !statusEffectIterator->visible) { std::list<StatusEffect>::iterator oldIterator = statusEffectIterator; ++statusEffectIterator; while (statusEffectIterator != oldIterator) { if (statusEffectIterator != statusEffects.end()) { if (statusEffectIterator->visible) break; ++statusEffectIterator; } else statusEffectIterator = statusEffects.begin(); } if (statusEffectIterator != statusEffects.end() && !statusEffectIterator->visible) statusEffectIterator = statusEffects.end(); } return; } } } bool NPC::HasEffect(StatusEffectType effect) const { for (std::list<StatusEffect>::const_iterator statusEffectI = statusEffects.begin(); statusEffectI != statusEffects.end(); ++statusEffectI) { if (statusEffectI->type == effect) { return true; } } return false; } std::list<StatusEffect>* NPC::StatusEffects() { return &statusEffects; } void NPC::AbortCurrentJob(bool remove_job) { std::shared_ptr<Job> job = jobs.front(); TaskFinished(TASKFAILFATAL, "Job aborted"); if (remove_job) { JobManager::Inst()->RemoveJob(job); } } void NPC::Hit(std::weak_ptr<Entity> target, bool careful) { if (target.lock()) { std::shared_ptr<NPC> npc = std::dynamic_pointer_cast<NPC>(target.lock()); std::shared_ptr<Construction> construction = std::dynamic_pointer_cast<Construction>(target.lock()); for (std::list<Attack>::iterator attacki = attacks.begin(); attacki != attacks.end(); ++attacki) { if (attacki->Cooldown() <= 0) { attacki->ResetCooldown(); if (npc) { //First check if the target dodges the attack if (Random::Generate(99) < npc->effectiveStats[DODGE]) { continue; } } Attack attack = *attacki; if (attack.Type() == DAMAGE_WIELDED) { GetMainHandAttack(attack); if (mainHand && Random::Generate(9) == 0) DecreaseItemCondition(mainHand); } if (npc && !careful && effectiveStats[STRENGTH] >= npc->effectiveStats[NPCSIZE]) { if (attack.Type() == DAMAGE_BLUNT || Random::Generate(4) == 0) { Coordinate tar; tar.X((npc->Position().X() - Position().X()) * std::max((effectiveStats[STRENGTH] - npc->effectiveStats[NPCSIZE])/2, 1)); tar.Y((npc->Position().Y() - Position().Y()) * std::max((effectiveStats[STRENGTH] - npc->effectiveStats[NPCSIZE])/2, 1)); npc->CalculateFlightPath(npc->Position()+tar, Random::Generate(25, 19 + 25)); npc->pathIndex = -1; } } if (npc) { npc->Damage(&attack, std::static_pointer_cast<NPC>(shared_from_this())); Random::Dice dice(attack.Amount()); damageDealt += dice.Roll(); if (HasTrait(FRESH) && damageDealt > 50) RemoveTrait(FRESH); } else if (construction) construction->Damage(&attack); } } } } void NPC::FireProjectile(std::weak_ptr<Entity> target) { if (std::shared_ptr<Entity> targetEntity = target.lock()) { for (std::list<Attack>::iterator attacki = attacks.begin(); attacki != attacks.end(); ++attacki) { if (attacki->Type() == DAMAGE_WIELDED) { if (attacki->Cooldown() <= 0) { attacki->ResetCooldown(); if (!quiver->empty()) { std::shared_ptr<Item> projectile = quiver->GetFirstItem(); quiver->RemoveItem(projectile); projectile->PutInContainer(); projectile->Position(Position()); projectile->CalculateFlightPath(targetEntity->Position(), 100, GetHeight()); projectile->SetFaction(PLAYERFACTION); } } break; } } } } void NPC::CastOffensiveSpell(std::weak_ptr<Entity> target) { if (std::shared_ptr<Entity> targetEntity = target.lock()) { for (std::list<Attack>::iterator attacki = attacks.begin(); attacki != attacks.end(); ++attacki) { if (attacki->IsProjectileMagic()) { if (attacki->Cooldown() <= 0) { attacki->ResetCooldown(); std::shared_ptr<Spell> spell = Game::Inst()->CreateSpell(Position(), attacki->Projectile()); if (spell) { spell->CalculateFlightPath(target.lock()->Position(), Spell::Presets[attacki->Projectile()].speed, GetHeight()); } } break; } } } } void NPC::Damage(Attack* attack, std::weak_ptr<NPC> aggr) { Resistance res; switch (attack->Type()) { case DAMAGE_SLASH: case DAMAGE_PIERCE: case DAMAGE_BLUNT: res = PHYSICAL_RES; break; case DAMAGE_MAGIC: res = MAGIC_RES; break; case DAMAGE_FIRE: res = FIRE_RES; break; case DAMAGE_COLD: res = COLD_RES; break; case DAMAGE_POISON: res = POISON_RES; break; default: res = PHYSICAL_RES; break; } double resistance = (100.0 - (float)effectiveResistances[res]) / 100.0; int damage = (int)(Game::DiceToInt(attack->Amount()) * resistance); health -= damage; for (unsigned int effecti = 0; effecti < attack->StatusEffects()->size(); ++effecti) { if (Random::Generate(99) < attack->StatusEffects()->at(effecti).second) { TransmitEffect(attack->StatusEffects()->at(effecti).first); } } if (health <= 0) Kill(GetDeathMsgCombat(aggr, attack->Type())); if (damage > 0) { damageReceived += damage; if (res == PHYSICAL_RES && Random::Generate(99) > effectiveResistances[BLEEDING_RES]) { Game::Inst()->CreateBlood(Coordinate( Position().X() + Random::Generate(-1, 1), Position().Y() + Random::Generate(-1, 1)), Random::Generate(75, 75+damage*20)); if (Random::Generate(10) == 0 && attack->Type() == DAMAGE_SLASH || attack->Type() == DAMAGE_PIERCE) { int gibId = Game::Inst()->CreateItem(Position(), Item::StringToItemType("Gib"), false, -1); std::shared_ptr<Item> gib = Game::Inst()->GetItem(gibId); if (gib) { Coordinate target = Random::ChooseInRadius(Position(), 3); gib->CalculateFlightPath(target, Random::Generate(10, 35)); } } if (damage >= maxHealth / 3 && attack->Type() == DAMAGE_BLUNT && Random::Generate(10) == 0) { AddTrait(CRACKEDSKULL); } } else if (res == FIRE_RES && Random::Generate(std::max(2, 10-damage)) == 0) { AddEffect(BURNING); } if (aggr.lock()) aggressor = aggr; if (!jobs.empty() && boost::iequals(jobs.front()->name, "Sleep")) { TaskFinished(TASKFAILFATAL); } } } void NPC::MemberOf(std::weak_ptr<Squad> newSquad) { squad = newSquad; if (!squad.lock()) { //NPC was removed from a squad //Drop weapon, quiver and armor std::list<std::shared_ptr<Item> > equipment; if (mainHand) { equipment.push_back(mainHand); mainHand.reset(); } if (armor) { equipment.push_back(armor); armor.reset(); } if (quiver) { equipment.push_back(quiver); quiver.reset(); } for (std::list<std::shared_ptr<Item> >::iterator eqit = equipment.begin(); eqit != equipment.end(); ++eqit) { inventory->RemoveItem(*eqit); (*eqit)->Position(Position()); (*eqit)->PutInContainer(); } aggressive = false; } } std::weak_ptr<Squad> NPC::MemberOf() const { return squad; } void NPC::Escape() { if (carried) { Announce::Inst()->AddMsg((boost::format("%s has escaped with [%s]!") % name % carried->Name()).str(), TCODColor::yellow, Position()); } DestroyAllItems(); escaped = true; } void NPC::DestroyAllItems() { while (!inventory->empty()) { std::shared_ptr<Item> item = inventory->GetFirstItem(); inventory->RemoveItem(item); if (std::shared_ptr<Container> container = std::dynamic_pointer_cast<Container>(item)) { while (!container->empty()) { std::shared_ptr<Item> item = container->GetFirstItem(); container->RemoveItem(item); Game::Inst()->RemoveItem(item); } } Game::Inst()->RemoveItem(item); } } bool NPC::Escaped() const { return escaped; } class NPCListener : public ITCODParserListener { int npcIndex; bool parserNewStruct(TCODParser *parser,const TCODParserStruct *str,const char *name) { if (boost::iequals(str->getName(), "npc_type")) { if (NPC::NPCTypeNames.find(name) != NPC::NPCTypeNames.end()) { npcIndex = NPC::NPCTypeNames[name]; NPC::Presets[npcIndex] = NPCPreset(name); } else { NPC::Presets.push_back(NPCPreset(name)); NPC::NPCTypeNames[name] = NPC::Presets.size()-1; npcIndex = NPC::Presets.size() - 1; } } else if (boost::iequals(str->getName(), "attack")) { NPC::Presets[npcIndex].attacks.push_back(Attack()); } else if (boost::iequals(str->getName(), "resistances")) { } return true; } bool parserFlag(TCODParser *parser,const char *name) { if (boost::iequals(name,"generateName")) { NPC::Presets[npcIndex].generateName = true; } else if (boost::iequals(name,"needsNutrition")) { NPC::Presets[npcIndex].needsNutrition = true; } else if (boost::iequals(name,"needsSleep")) { NPC::Presets[npcIndex].needsSleep = true; } else if (boost::iequals(name,"expert")) { NPC::Presets[npcIndex].expert = true; } return true; } bool parserProperty(TCODParser *parser,const char *name, TCOD_value_type_t type, TCOD_value_t value) { if (boost::iequals(name,"name")) { NPC::Presets[npcIndex].name = value.s; } else if (boost::iequals(name,"plural")) { NPC::Presets[npcIndex].plural = value.s; } else if (boost::iequals(name,"speed")) { NPC::Presets[npcIndex].stats[MOVESPEED] = value.i; } else if (boost::iequals(name,"color")) { NPC::Presets[npcIndex].color = value.col; } else if (boost::iequals(name,"graphic")) { NPC::Presets[npcIndex].graphic = value.c; } else if (boost::iequals(name,"fallbackGraphicsSet")) { NPC::Presets[npcIndex].fallbackGraphicsSet = value.s; } else if (boost::iequals(name,"health")) { NPC::Presets[npcIndex].health = value.i; } else if (boost::iequals(name,"AI")) { NPC::Presets[npcIndex].ai = value.s; } else if (boost::iequals(name,"dodge")) { NPC::Presets[npcIndex].stats[DODGE] = value.i; } else if (boost::iequals(name,"spawnAsGroup")) { NPC::Presets[npcIndex].spawnAsGroup = true; NPC::Presets[npcIndex].group = value.dice; } else if (boost::iequals(name,"type")) { NPC::Presets[npcIndex].attacks.back().Type(Attack::StringToDamageType(value.s)); } else if (boost::iequals(name,"damage")) { NPC::Presets[npcIndex].attacks.back().Amount(value.dice); } else if (boost::iequals(name,"cooldown")) { NPC::Presets[npcIndex].attacks.back().CooldownMax(value.i); } else if (boost::iequals(name,"statusEffects")) { for (int i = 0; i < TCOD_list_size(value.list); ++i) { StatusEffectType type = StatusEffect::StringToStatusEffectType((char*)TCOD_list_get(value.list,i)); if (StatusEffect::IsApplyableStatusEffect(type)) NPC::Presets[npcIndex].attacks.back().StatusEffects()->push_back(std::pair<StatusEffectType, int>(type, 100)); } } else if (boost::iequals(name,"effectChances")) { for (int i = 0; i < TCOD_list_size(value.list); ++i) { NPC::Presets[npcIndex].attacks.back().StatusEffects()->at(i).second = (intptr_t)TCOD_list_get(value.list,i); } } else if (boost::iequals(name,"projectile")) { NPC::Presets[npcIndex].attacks.back().Projectile(Item::StringToItemType(value.s)); if (NPC::Presets[npcIndex].attacks.back().Projectile() == -1) { //No item found, probably a spell then NPC::Presets[npcIndex].attacks.back().Projectile(Spell::StringToSpellType(value.s)); if (NPC::Presets[npcIndex].attacks.back().Projectile() >= 0) NPC::Presets[npcIndex].attacks.back().SetMagicProjectile(); } } else if (boost::iequals(name,"physical")) { NPC::Presets[npcIndex].resistances[PHYSICAL_RES] = value.i; } else if (boost::iequals(name,"magic")) { NPC::Presets[npcIndex].resistances[MAGIC_RES] = value.i; } else if (boost::iequals(name,"cold")) { NPC::Presets[npcIndex].resistances[COLD_RES] = value.i; } else if (boost::iequals(name,"fire")) { NPC::Presets[npcIndex].resistances[FIRE_RES] = value.i; } else if (boost::iequals(name,"poison")) { NPC::Presets[npcIndex].resistances[POISON_RES] = value.i; } else if (boost::iequals(name,"bleeding")) { NPC::Presets[npcIndex].resistances[BLEEDING_RES] = value.i; } else if (boost::iequals(name,"tags")) { for (int i = 0; i < TCOD_list_size(value.list); ++i) { std::string tag = (char*)TCOD_list_get(value.list,i); NPC::Presets[npcIndex].tags.insert(boost::to_lower_copy(tag)); } } else if (boost::iequals(name,"strength")) { NPC::Presets[npcIndex].stats[STRENGTH] = value.i; } else if (boost::iequals(name,"size")) { NPC::Presets[npcIndex].stats[NPCSIZE] = value.i; if (NPC::Presets[npcIndex].stats[STRENGTH] == 1) NPC::Presets[npcIndex].stats[STRENGTH] = value.i; } else if (boost::iequals(name,"tier")) { NPC::Presets[npcIndex].tier = value.i; } else if (boost::iequals(name,"death")) { if (boost::iequals(value.s,"filth")) NPC::Presets[npcIndex].deathItem = -1; else NPC::Presets[npcIndex].deathItem = Item::StringToItemType(value.s); } else if (boost::iequals(name,"equipOneOf")) { NPC::Presets[npcIndex].possibleEquipment.push_back(std::vector<int>()); for (int i = 0; i < TCOD_list_size(value.list); ++i) { std::string item = (char*)TCOD_list_get(value.list,i); NPC::Presets[npcIndex].possibleEquipment.back().push_back(Item::StringToItemType(item)); } } else if (boost::iequals(name,"faction")) { NPC::Presets[npcIndex].faction = Faction::StringToFactionType(value.s); } return true; } bool parserEndStruct(TCODParser *parser,const TCODParserStruct *str,const char *name) { if (NPC::Presets[npcIndex].plural == "") NPC::Presets[npcIndex].plural = NPC::Presets[npcIndex].name + "s"; if (NPC::Presets[npcIndex].faction == -1) { if (NPC::Presets[npcIndex].ai == "PlayerNPC") { NPC::Presets[npcIndex].faction = PLAYERFACTION; } else if (NPC::Presets[npcIndex].ai == "PeacefulAnimal") { NPC::Presets[npcIndex].faction = Faction::StringToFactionType("Peaceful animal"); } else if (NPC::Presets[npcIndex].ai == "HungryAnimal") { NPC::Presets[npcIndex].faction = Faction::StringToFactionType("Hostile monster"); } else if (NPC::Presets[npcIndex].ai == "HostileAnimal") { NPC::Presets[npcIndex].faction = Faction::StringToFactionType("Hostile monster"); } } return true; } void error(const char *msg) { throw std::runtime_error(msg); } }; void NPC::LoadPresets(std::string filename) { TCODParser parser = TCODParser(); TCODParserStruct *npcTypeStruct = parser.newStructure("npc_type"); npcTypeStruct->addProperty("name", TCOD_TYPE_STRING, true); npcTypeStruct->addProperty("plural", TCOD_TYPE_STRING, false); npcTypeStruct->addProperty("color", TCOD_TYPE_COLOR, true); npcTypeStruct->addProperty("graphic", TCOD_TYPE_CHAR, true); npcTypeStruct->addFlag("expert"); const char* aiTypes[] = { "PlayerNPC", "PeacefulAnimal", "HungryAnimal", "HostileAnimal", NULL }; npcTypeStruct->addValueList("AI", aiTypes, true); npcTypeStruct->addFlag("needsNutrition"); npcTypeStruct->addFlag("needsSleep"); npcTypeStruct->addFlag("generateName"); npcTypeStruct->addProperty("spawnAsGroup", TCOD_TYPE_DICE, false); npcTypeStruct->addListProperty("tags", TCOD_TYPE_STRING, false); npcTypeStruct->addProperty("tier", TCOD_TYPE_INT, false); npcTypeStruct->addProperty("death", TCOD_TYPE_STRING, false); npcTypeStruct->addProperty("fallbackGraphicsSet", TCOD_TYPE_STRING, false); npcTypeStruct->addListProperty("equipOneOf", TCOD_TYPE_STRING, false); npcTypeStruct->addProperty("faction", TCOD_TYPE_STRING, false); TCODParserStruct *attackTypeStruct = parser.newStructure("attack"); const char* damageTypes[] = { "slashing", "piercing", "blunt", "magic", "fire", "cold", "poison", "wielded", NULL }; attackTypeStruct->addValueList("type", damageTypes, true); attackTypeStruct->addProperty("damage", TCOD_TYPE_DICE, false); attackTypeStruct->addProperty("cooldown", TCOD_TYPE_INT, false); attackTypeStruct->addListProperty("statusEffects", TCOD_TYPE_STRING, false); attackTypeStruct->addListProperty("effectChances", TCOD_TYPE_INT, false); attackTypeStruct->addFlag("ranged"); attackTypeStruct->addProperty("projectile", TCOD_TYPE_STRING, false); TCODParserStruct *resistancesStruct = parser.newStructure("resistances"); resistancesStruct->addProperty("physical", TCOD_TYPE_INT, false); resistancesStruct->addProperty("magic", TCOD_TYPE_INT, false); resistancesStruct->addProperty("cold", TCOD_TYPE_INT, false); resistancesStruct->addProperty("fire", TCOD_TYPE_INT, false); resistancesStruct->addProperty("poison", TCOD_TYPE_INT, false); resistancesStruct->addProperty("bleeding", TCOD_TYPE_INT, false); TCODParserStruct *statsStruct = parser.newStructure("stats"); statsStruct->addProperty("health", TCOD_TYPE_INT, true); statsStruct->addProperty("speed", TCOD_TYPE_INT, true); statsStruct->addProperty("dodge", TCOD_TYPE_INT, true); statsStruct->addProperty("size", TCOD_TYPE_INT, true); statsStruct->addProperty("strength", TCOD_TYPE_INT, false); npcTypeStruct->addStructure(attackTypeStruct); npcTypeStruct->addStructure(resistancesStruct); npcTypeStruct->addStructure(statsStruct); NPCListener listener = NPCListener(); parser.run(filename.c_str(), &listener); } std::string NPC::NPCTypeToString(NPCType type) { if (type >= 0 && type < static_cast<int>(Presets.size())) return Presets[type].typeName; return "Nobody"; } NPCType NPC::StringToNPCType(std::string typeName) { if (NPCTypeNames.find(typeName) == NPCTypeNames.end()) { return -1; } return NPCTypeNames[typeName]; } int NPC::GetNPCSymbol() const { return Presets[type].graphic; } void NPC::InitializeAIFunctions() { FindJob = boost::bind(&Faction::FindJob, Faction::factions[faction], _1); React = boost::bind(NPC::AnimalReact, _1); if (NPC::Presets[type].ai == "PlayerNPC") { FindJob = boost::bind(NPC::JobManagerFinder, _1); React = boost::bind(NPC::PlayerNPCReact, _1); } } void NPC::GetMainHandAttack(Attack &attack) { attack.Type(DAMAGE_BLUNT); if (std::shared_ptr<Item> weapon = mainHand) { Attack wAttack = weapon->GetAttack(); attack.Type(wAttack.Type()); attack.AddDamage(wAttack.Amount()); attack.Projectile(wAttack.Projectile()); for (std::vector<std::pair<StatusEffectType, int> >::iterator effecti = wAttack.StatusEffects()->begin(); effecti != wAttack.StatusEffects()->end(); ++effecti) { attack.StatusEffects()->push_back(*effecti); } } } bool NPC::WieldingRangedWeapon() { if (std::shared_ptr<Item> weapon = mainHand) { Attack wAttack = weapon->GetAttack(); return wAttack.Type() == DAMAGE_RANGED; } return false; } void NPC::FindNewWeapon() { int weaponValue = 0; if (mainHand && mainHand->IsCategory(squad.lock()->Weapon())) { weaponValue = mainHand->RelativeValue(); } ItemCategory weaponCategory = squad.lock() ? squad.lock()->Weapon() : Item::StringToItemCategory("Weapon"); std::shared_ptr<Item> newWeapon = Game::Inst()->FindItemByCategoryFromStockpiles(weaponCategory, Position(), BETTERTHAN, weaponValue); if (std::shared_ptr<Item> weapon = newWeapon) { std::shared_ptr<Job> weaponJob(new Job("Grab weapon")); weaponJob->internal = true; weaponJob->ReserveEntity(weapon); weaponJob->tasks.push_back(Task(MOVE, weapon->Position())); weaponJob->tasks.push_back(Task(TAKE, weapon->Position(), weapon)); weaponJob->tasks.push_back(Task(WIELD)); jobs.push_back(weaponJob); } } void NPC::FindNewArmor() { int armorValue = 0; if (armor && armor->IsCategory(squad.lock()->Armor())) { armorValue = armor->RelativeValue(); } ItemCategory armorCategory = squad.lock() ? squad.lock()->Armor() : Item::StringToItemCategory("Armor"); std::shared_ptr<Item> newArmor = Game::Inst()->FindItemByCategoryFromStockpiles(armorCategory, Position(), BETTERTHAN, armorValue); if (std::shared_ptr<Item> arm = newArmor) { std::shared_ptr<Job> armorJob(new Job("Grab armor")); armorJob->internal = true; armorJob->ReserveEntity(arm); armorJob->tasks.push_back(Task(MOVE, arm->Position())); armorJob->tasks.push_back(Task(TAKE, arm->Position(), arm)); armorJob->tasks.push_back(Task(WEAR)); jobs.push_back(armorJob); } } std::shared_ptr<Item> NPC::Wielding() const { return mainHand; } std::shared_ptr<Item> NPC::Carrying() const { return carried; } std::shared_ptr<Item> NPC::Wearing() const { return armor; } bool NPC::HasHands() const { return hasHands; } void NPC::UpdateVelocity() { if (velocity > 0) { nextVelocityMove += velocity; while (nextVelocityMove > 100) { nextVelocityMove -= 100; if (flightPath.size() > 0) { if (flightPath.back().height < ENTITYHEIGHT) { //We're flying low enough to hit things Coordinate t = flightPath.back().coord; if (map->BlocksWater(t)) { //We've hit an obstacle health -= velocity/5; AddEffect(CONCUSSION); if (map->GetConstruction(t) > -1) { if (std::shared_ptr<Construction> construct = Game::Inst()->GetConstruction( map->GetConstruction(t)).lock()) { Attack attack; attack.Type(DAMAGE_BLUNT); TCOD_dice_t damage; damage.addsub = (float)velocity / 5; damage.multiplier = 1; damage.nb_dices = 1; damage.nb_faces = 5 + effectiveStats[NPCSIZE]; construct->Damage(&attack); } } SetVelocity(0); flightPath.clear(); return; } if (map->NPCList(t)->size() > 0 && Random::Generate(9) < (signed int)(2 + map->NPCList(t)->size())) { health -= velocity/5; AddEffect(CONCUSSION); SetVelocity(0); flightPath.clear(); return; } } if (flightPath.back().height == 0) { health -= velocity/5; AddEffect(CONCUSSION); SetVelocity(0); } Position(flightPath.back().coord); flightPath.pop_back(); } else SetVelocity(0); } } else { //We're not hurtling through air so let's tumble around if we're stuck on unwalkable terrain if (!map->IsWalkable(pos, static_cast<void*>(this))) { for (int radius = 1; radius < 10; ++radius) { for (int ix = pos.X() - radius; ix <= pos.X() + radius; ++ix) { for (int iy = pos.Y() - radius; iy <= pos.Y() + radius; ++iy) { Coordinate p(ix, iy); if (map->IsWalkable(p, static_cast<void*>(this))) { Position(p); return; } } } } } } } void NPC::PickupItem(std::shared_ptr<Item> item) { if (item) { carried = std::static_pointer_cast<Item>(item); bulk += item->GetBulk(); if (!inventory->AddItem(carried)) Announce::Inst()->AddMsg("No space in inventory"); } } NPCPreset::NPCPreset(std::string typeNameVal) : typeName(typeNameVal), name("AA Club"), plural(""), color(TCODColor::pink), graphic('?'), expert(false), health(10), ai("PeacefulAnimal"), needsNutrition(false), needsSleep(false), generateName(false), spawnAsGroup(false), group(TCOD_dice_t()), attacks(std::list<Attack>()), tags(std::set<std::string>()), tier(0), deathItem(-2), fallbackGraphicsSet(), graphicsHint(-1), faction(-1) { for (int i = 0; i < STAT_COUNT; ++i) { stats[i] = 1; } for (int i = 0; i < RES_COUNT; ++i) { resistances[i] = 0; } resistances[DISEASE_RES] = 75; //Pretty much every creature is somewhat resistant to disease group.addsub = 0; group.multiplier = 1; group.nb_dices = 1; group.nb_faces = 1; } int NPC::GetHealth() const { return health; } int NPC::GetMaxHealth() const { return maxHealth; } void NPC::AbortJob(std::weak_ptr<Job> wjob) { if (std::shared_ptr<Job> job = wjob.lock()) { for (std::deque<std::shared_ptr<Job> >::iterator jobi = jobs.begin(); jobi != jobs.end(); ++jobi) { if (*jobi == job) { if (job == jobs.front()) { TaskFinished(TASKFAILFATAL, "(AbortJob)"); } return; } } } } bool NPC::IsTunneler() const { return isTunneler; } void NPC::ScanSurroundings(bool onlyHostiles) { /* The algorithm performs in the following, slightly wrong, way: - for each point B at the border of the rectangle at LOS_DISTANCE of the current position C - for each point P on a line from C to B (from the inside, outwards) - if there is a non-friend NPC on P, update the threat location This means that, depending on the order of traversal of the rectangle border, the final threatLocation may not be the closest non-friend NPC: on each line, the threat location was set to the farthest non-friend NPC. But that's ok, as 'gencontain' explains: « It's not like it matters that much anyway. What's important is that a cowardly npc runs away from some threat that it sees, not that they prioritize threats accurately. A goblin seeing a threat further away and running blindly into a closer one sounds like something a goblin would do. » If you're not happy with that, just go play chess! */ adjacentNpcs.clear(); nearNpcs.clear(); nearConstructions.clear(); threatLocation = Coordinate(-1,-1); seenFire = false; bool skipPosition = false; //We should skip checking this npc's position after the first time Coordinate low = map->Shrink(pos - LOS_DISTANCE); Coordinate high = map->Shrink(pos + LOS_DISTANCE); for (int endx = low.X(); endx < high.X(); endx += 2) { for (int endy = low.Y(); endy < high.Y(); endy += 2) { Coordinate end(endx, endy); if (end.onRectangleEdges(low, high)) { int adjacent = 2; //We're going outwards, the first two iterations are considered adjacent to the starting point Coordinate p = pos; TCODLine::init(p.X(), p.Y(), end.X(), end.Y()); if (skipPosition) { TCODLine::step(p.Xptr(), p.Yptr()); --adjacent; } skipPosition = true; do { /*Check constructions before checking for lightblockage because we can see a wall even though we can't see through it*/ int constructUid = map->GetConstruction(p); if (constructUid >= 0) { nearConstructions.push_back(Game::Inst()->GetConstruction(constructUid)); } //Stop moving along this line if our view is blocked if (map->BlocksLight(p) && GetHeight() < ENTITYHEIGHT) break; //Add all the npcs on this tile, or only hostiles if that boolean is set for (std::set<int>::iterator npci = map->NPCList(p)->begin(); npci != map->NPCList(p)->end(); ++npci) { if (*npci != uid) { std::shared_ptr<NPC> npc = Game::Inst()->GetNPC(*npci); if (!factionPtr->IsFriendsWith(npc->GetFaction())) threatLocation = Coordinate(p); if (!onlyHostiles || !factionPtr->IsFriendsWith(npc->GetFaction())) { nearNpcs.push_back(npc); if (adjacent > 0) adjacentNpcs.push_back(npc); } } } //Only care about fire if we're not flying and/or not effectively immune if (!HasEffect(FLYING) && map->GetFire(p).lock()) { if (effectiveResistances[FIRE_RES] < 90) { threatLocation = p; seenFire = true; } } /*Stop if we already see many npcs, otherwise this can start to bog down in high traffic places*/ if (adjacent <= 0 && nearNpcs.size() > 16) break; --adjacent; } while (!TCODLine::step(p.Xptr(), p.Yptr())); } } } } void NPC::AddTrait(Trait trait) { traits.insert(trait); switch (trait) { case CRACKEDSKULL: AddEffect(CRACKEDSKULLEFFECT); break; default: break; } } void NPC::RemoveTrait(Trait trait) { traits.erase(trait); switch (trait) { case FRESH: _color.g = std::max(0, _color.g - 100); break; default: break; } } bool NPC::HasTrait(Trait trait) const { return traits.find(trait) != traits.end(); } void NPC::GoBerserk() { ScanSurroundings(); if (std::shared_ptr<Item> carriedItem = carried) { inventory->RemoveItem(carriedItem); carriedItem->PutInContainer(); carriedItem->Position(Position()); Coordinate target = undefined; if (!nearNpcs.empty()) { std::shared_ptr<NPC> creature = boost::next(nearNpcs.begin(), Random::ChooseIndex(nearNpcs))->lock(); if (creature) target = creature->Position(); } if (target == undefined) target = Random::ChooseInRadius(Position(), 7); carriedItem->CalculateFlightPath(target, 50, GetHeight()); } carried.reset(); while (!jobs.empty()) TaskFinished(TASKFAILFATAL, "(FAIL)Gone berserk"); if (!nearNpcs.empty()) { std::shared_ptr<NPC> creature = boost::next(nearNpcs.begin(), Random::ChooseIndex(nearNpcs))->lock(); std::shared_ptr<Job> berserkJob(new Job("Berserk!")); berserkJob->internal = true; berserkJob->tasks.push_back(Task(KILL, creature->Position(), creature)); jobs.push_back(berserkJob); } AddEffect(RAGE); } void NPC::ApplyEffects(std::shared_ptr<Item> item) { if (item) { for (std::vector<std::pair<StatusEffectType, int> >::iterator addEffecti = Item::Presets[item->Type()].addsEffects.begin(); addEffecti != Item::Presets[item->Type()].addsEffects.end(); ++addEffecti) { if (Random::Generate(99) < addEffecti->second) TransmitEffect(addEffecti->first); } for (std::vector<std::pair<StatusEffectType, int> >::iterator remEffecti = Item::Presets[item->Type()].removesEffects.begin(); remEffecti != Item::Presets[item->Type()].removesEffects.end(); ++remEffecti) { if (Random::Generate(99) < remEffecti->second) { RemoveEffect(remEffecti->first); if (remEffecti->first == DROWSY) weariness = 0; //Special case, the effect would come straight back otherwise } } } } void NPC::UpdateHealth() { if (health <= 0) {Kill(GetDeathMsg()); return;} if (effectiveStats[STRENGTH] <= baseStats[STRENGTH]/10) {Kill(GetDeathMsgStrengthLoss()); return;} if (health > maxHealth) health = maxHealth; if (Random::Generate(UPDATES_PER_SECOND*10) == 0 && health < maxHealth) ++health; if (faction == PLAYERFACTION && health < maxHealth / 2 && !HasEffect(HEALING)) { bool healJobFound = false; for (std::deque<std::shared_ptr<Job> >::iterator jobi = jobs.begin(); jobi != jobs.end(); ++jobi) { if ((*jobi)->name.find("Heal") != std::string::npos) { healJobFound = true; break; } } if (!healJobFound && Item::GoodEffectAdders.find(HEALING) != Item::GoodEffectAdders.end()) { std::shared_ptr<Item> healItem; for (std::multimap<StatusEffectType, ItemType>::iterator fixi = Item::GoodEffectAdders.equal_range( HEALING).first; fixi != Item::GoodEffectAdders.equal_range(HEALING).second && !healItem; ++fixi) { healItem = Game::Inst()->FindItemByTypeFromStockpiles(fixi->second, Position()); } if (healItem) { std::shared_ptr<Job> healJob(new Job("Heal")); healJob->internal = true; healJob->ReserveEntity(healItem); healJob->tasks.push_back(Task(MOVE, healItem->Position())); healJob->tasks.push_back(Task(TAKE, healItem->Position(), healItem)); if (healItem->IsCategory(Item::StringToItemCategory("drink"))) healJob->tasks.push_back(Task(DRINK)); else healJob->tasks.push_back(Task(EAT)); jobs.push_back(healJob); } } } } /*I opted to place this in NPC instead of it being a method of Item mainly because Item won't know if it's being wielded, worn or whatever, and that's important information when an axe breaks in an orc's hand, for exmple*/ void NPC::DecreaseItemCondition(std::shared_ptr<Item> witem) { if (std::shared_ptr<Item> item = witem) { int condition = item->DecreaseCondition(); if (condition == 0) { //< 0 == does not break, > 0 == not broken inventory->RemoveItem(item); if (carried == item) carried.reset(); if (mainHand == item) { mainHand.reset(); if (currentJob().lock() && currentJob().lock()->RequiresTool()) { TaskFinished(TASKFAILFATAL, "(FAIL)Wielded item broken"); } } if (offHand == item) offHand.reset(); if (armor == item) armor.reset(); if (quiver == item) quiver.reset(); std::vector<std::shared_ptr<Item> > component(1, item); Game::Inst()->CreateItem(Position(), Item::StringToItemType("debris"), false, -1, component); Game::Inst()->RemoveItem(item); } } } void NPC::DumpContainer(Coordinate p) { std::shared_ptr<Container> sourceContainer; if (carried && (carried->IsCategory(Item::StringToItemCategory("Bucket")) || carried->IsCategory(Item::StringToItemCategory("Container")))) { sourceContainer = std::static_pointer_cast<Container>(carried); } else if (mainHand && (mainHand->IsCategory(Item::StringToItemCategory("Bucket")) || mainHand->IsCategory(Item::StringToItemCategory("Container")))) { sourceContainer = std::static_pointer_cast<Container>(mainHand); } if (sourceContainer) { if (map->IsInside(p)) { if (sourceContainer->ContainsWater() > 0) { Game::Inst()->CreateWater(p, sourceContainer->ContainsWater()); sourceContainer->RemoveWater(sourceContainer->ContainsWater()); } else { Game::Inst()->CreateFilth(p, sourceContainer->ContainsFilth()); sourceContainer->RemoveFilth(sourceContainer->ContainsFilth()); } } } } //Checks all the current job's tasks to see if they are potentially doable void NPC::ValidateCurrentJob() { if (!jobs.empty()) { //Only check tasks from the current one onwards for (size_t i = taskIndex; i < jobs.front()->tasks.size(); ++i) { switch (jobs.front()->tasks[i].action) { case FELL: case HARVESTWILDPLANT: if (!jobs.front()->tasks[i].entity.lock() || !std::dynamic_pointer_cast<NatureObject>(jobs.front()->tasks[i].entity.lock())) { TaskFinished(TASKFAILFATAL, "(FELL/HARVESTWILDPLANT)Target doesn't exist"); return; } else if (!std::static_pointer_cast<NatureObject>(jobs.front()->tasks[i].entity.lock())->Marked()) { TaskFinished(TASKFAILFATAL, "(FELL/HARVESTWILDPLANT)Target not marked"); return; } break; case POUR: if (!boost::iequals(jobs.front()->name, "Dump filth")) { //Filth dumping is the one time we want to pour liquid onto an unmarked tile if (!jobs.front()->tasks[i].entity.lock() && !map->GroundMarked(jobs.front()->tasks[i].target)) { TaskFinished(TASKFAILFATAL, "(POUR)Target does not exist"); return; } } break; case PUTIN: if (!jobs.front()->tasks[i].entity.lock()) { TaskFinished(TASKFAILFATAL, "(PUTIN)Target doesn't exist"); return; } break; case DIG: { Season season = Game::Inst()->CurrentSeason(); if (season == EarlyWinter || season == Winter || season == LateWinter) { TaskFinished(TASKFAILFATAL, "(DIG)Cannot dig in winter"); return; } }break; default: break; //Non-validatable tasks } } } } int NPC::GetHeight() const { if (!flightPath.empty()) return flightPath.back().height; if (HasEffect(FLYING) || HasEffect(HIGHGROUND)) return ENTITYHEIGHT+2; return 0; } bool NPC::IsFlying() const { return isFlying; } void NPC::SetFaction(int newFaction) { if (newFaction >= 0 && newFaction < static_cast<int>(Faction::factions.size())) { faction = newFaction; factionPtr = Faction::factions[newFaction]; } else if (!Faction::factions.empty()) { factionPtr = Faction::factions[0]; } } void NPC::TransmitEffect(StatusEffect effect) { if (Random::Generate(effectiveResistances[effect.applicableResistance]) == 0) { if (effect.type != PANIC || coward) //PANIC can only be transmitted to cowards AddEffect(effect); } } //TODO all those messages should be data-driven std::string NPC::GetDeathMsg() { int choice = Random::Generate(5); switch (choice) { default: case 0: return name + " has died"; case 1: return name + " has left the mortal realm"; case 2: return name + " is no longer among us"; case 3: return name + " is wormfood"; case 4: return name + " lost his will to live"; } } std::string NPC::GetDeathMsgStrengthLoss() { std::string effectName = "Unknown disease"; for (std::list<StatusEffect>::const_iterator statI = statusEffects.begin(); statI != statusEffects.end(); ++statI) { if (statI->statChanges[STRENGTH] < 1) { effectName = statI->name; break; } } int choice = Random::Generate(5); switch (choice) { default: case 0: return name + " has died from " + effectName; case 1: return name + " succumbed to " + effectName; case 2: return effectName + " claims another victim in " + name; case 3: return name + " is overcome by " + effectName; case 4: return effectName + " was too much for " + name; } } std::string NPC::GetDeathMsgThirst() { int choice = Random::Generate(2); switch (choice) { default: case 0: return name + " has died from thirst"; case 1: return name + " died from dehydration"; } } std::string NPC::GetDeathMsgHunger() { int choice = Random::Generate(2); switch (choice) { default: case 0: return name + " has died from hunger"; case 1: return name + " was too weak to live"; } } std::string NPC::GetDeathMsgCombat(std::weak_ptr<NPC> other, DamageType damage) { int choice = Random::Generate(4); if (std::shared_ptr<NPC> attacker = other.lock()) { std::string otherName = attacker->Name(); switch (damage) { case DAMAGE_SLASH: switch (choice) { default: case 0: return otherName + " sliced " + name + " into ribbons"; case 1: return otherName + " slashed " + name + " into pieces"; case 2: return name + " was dissected by " + otherName; case 3: return otherName + " chopped " + name + " up"; } case DAMAGE_BLUNT: switch (choice) { default: case 0: return otherName + " bludgeoned " + name + " to death"; case 1: return otherName + " smashed " + name + " into pulp"; case 2: return name + " was crushed by " + otherName; case 3: return otherName + " hammered " + name + " to death"; } case DAMAGE_PIERCE: switch (choice) { default: case 0: return otherName + " pierced " + name + " straight through"; case 1: return otherName + " punched holes through " + name; case 2: return name + " was made into a pincushion by " + otherName; } case DAMAGE_FIRE: switch (choice) { default: case 0: return otherName + " burnt " + name + " to ashes"; case 1: return otherName + " fried " + name + " to a crisp"; case 2: return name + " was barbecued by" + otherName; } default: switch (choice) { default: case 0: return otherName + " ended " + name + "'s life"; case 1: return otherName + " was too much for " + name + " to handle"; case 2: return otherName + " killed " + name; } } } switch (damage) { case DAMAGE_SLASH: switch (choice) { default: case 0: return name + " was cut into ribbons"; case 1: return name + " got slashed into pieces"; case 2: return name + " was dissected"; case 3: return name + " was chopped up"; } case DAMAGE_BLUNT: switch (choice) { default: case 0: return name + " was bludgeoned to death"; case 1: return name + " was smashed into pulp"; case 2: return name + " was crushed"; case 3: return name + " was hammered to death"; } case DAMAGE_PIERCE: switch (choice) { default: case 0: return name + " got pierced straight through"; case 1: return name + " got too many holes punched through"; case 2: return name + " was made into a pincushion"; } case DAMAGE_FIRE: switch (choice) { default: case 0: return name + " burnt into ashes"; case 1: return name + " fried to a crisp"; case 2: return name + " was barbecued"; } default: return GetDeathMsg(); } } void NPC::save(OutputArchive& ar, const unsigned int version) const { ar.register_type<Container>(); ar.register_type<Item>(); ar.register_type<Entity>(); ar.register_type<SkillSet>(); ar & boost::serialization::base_object<Entity>(*this); std::string npcType(NPC::NPCTypeToString(type)); ar & npcType; ar & timeCount; ar & jobs; ar & taskIndex; ar & orderIndex; ar & nopath; ar & findPathWorking; ar & timer; ar & nextMove; ar & run; ar & _color.r; ar & _color.g; ar & _color.b; ar & _bgcolor.r; ar & _bgcolor.g; ar & _bgcolor.b; ar & _graphic; ar & taskBegun; ar & expert; ar & carried; ar & mainHand; ar & offHand; ar & armor; ar & quiver; ar & thirst; ar & hunger; ar & weariness; ar & thinkSpeed; ar & statusEffects; ar & health; ar & maxHealth; ar & foundItem; ar & inventory; ar & needsNutrition; ar & needsSleep; ar & hasHands; ar & isTunneler; ar & baseStats; ar & effectiveStats; ar & baseResistances; ar & effectiveResistances; ar & aggressive; ar & coward; ar & aggressor; ar & dead; ar & squad; ar & attacks; ar & escaped; ar & addedTasksToCurrentJob; ar & Skills; ar & hasMagicRangedAttacks; ar & traits; ar & damageDealt; ar & damageReceived; ar & jobBegun; } void NPC::load(InputArchive& ar, const unsigned int version) { ar.register_type<Container>(); ar.register_type<Item>(); ar.register_type<Entity>(); ar.register_type<SkillSet>(); ar & boost::serialization::base_object<Entity>(*this); std::string typeName; ar & typeName; type = -1; bool failedToFindType = false; type = NPC::StringToNPCType(typeName); if (type == -1) { //Apparently a creature type that doesn't exist type = 2; //Whatever the first monster happens to be failedToFindType = true; //We'll allow loading, this creature will just immediately die } ar & timeCount; ar & jobs; ar & taskIndex; ar & orderIndex; ar & nopath; ar & findPathWorking; ar & timer; ar & nextMove; ar & run; ar & _color.r; ar & _color.g; ar & _color.b; ar & _bgcolor.r; ar & _bgcolor.g; ar & _bgcolor.b; ar & _graphic; ar & taskBegun; ar & expert; ar & carried; ar & mainHand; ar & offHand; ar & armor; ar & quiver; ar & thirst; ar & hunger; ar & weariness; ar & thinkSpeed; ar & statusEffects; ar & health; if (failedToFindType) health = 0; ar & maxHealth; ar & foundItem; ar & inventory; ar & needsNutrition; ar & needsSleep; ar & hasHands; ar & isTunneler; ar & baseStats; ar & effectiveStats; ar & baseResistances; ar & effectiveResistances; ar & aggressive; ar & coward; ar & aggressor; ar & dead; ar & squad; ar & attacks; ar & escaped; ar & addedTasksToCurrentJob; ar & Skills; ar & hasMagicRangedAttacks; ar & traits; ar & damageDealt; ar & damageReceived; if (version >= 1) { ar & jobBegun; } SetFaction(faction); //Required to initialize factionPtr InitializeAIFunctions(); }
6be1b06056d6f196b6d6859e2accec5a919e2854
79cd409b4b12f8ab76a31130750753e147c5dd4e
/wiselib.testing/algorithms/cluster/modules/chd/prob_chd.h
5e249ef9f5638c7c6668049560b569de25ed500e
[]
no_license
bjoerke/wiselib
d28eb39e9095c9bfcec6b4c635b773f5fcaf87fa
183726cbf744be9d65f12dd01bece0f7fd842541
refs/heads/master
2020-12-28T20:30:40.829538
2014-08-18T14:10:42
2014-08-18T14:10:42
19,933,324
1
0
null
null
null
null
UTF-8
C++
false
false
4,090
h
prob_chd.h
/*************************************************************************** ** This file is part of the generic algorithm library Wiselib. ** ** Copyright (C) 2008,2009 by the Wisebed (www.wisebed.eu) project. ** ** ** ** The Wiselib is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU Lesser General Public License as ** ** published by the Free Software Foundation, either version 3 of the ** ** License, or (at your option) any later version. ** ** ** ** The Wiselib 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 Lesser General Public License for more details. ** ** ** ** You should have received a copy of the GNU Lesser General Public ** ** License along with the Wiselib. ** ** If not, see <http://www.gnu.org/licenses/>. ** ***************************************************************************/ /* * File: prob_chd.h * Author: Amaxilatis */ #ifndef _ALGORITHMS_CLUSTER_MODULES_CHD_PROB_CHD_H #define _ALGORITHMS_CLUSTER_MODULES_CHD_PROB_CHD_H namespace wiselib { /** * \ingroup chd_concept * * Probabilistic cluster head decision module. */ template<typename OsModel_P, typename Radio_P> class ProbabilisticClusterHeadDecision { public: //TYPEDEFS typedef OsModel_P OsModel; typedef Radio_P Radio; typedef typename OsModel::Debug Debug; typedef typename OsModel::Rand Rand; /* * Constructor * */ ProbabilisticClusterHeadDecision() : cluster_head_(false), probability_(30) { } /* * Destructor * */ ~ProbabilisticClusterHeadDecision() { } /* * INIT * initializes the values of radio and debug */ void init(Radio& radio, Debug& debug, Rand& rand) { radio_ = &radio; debug_ = &debug; rand_ = &rand; } /* * SET probability * get an integer [0-100] * this the probability in % to * become a cluster_head */ void set_probability(int prob) { if (prob > 100) { probability_ = 100; } else if (prob < 0) { probability_ = 0; } else { probability_ = prob; } } /* * GET is_cluster_head * Returns if Cluster Head */ bool is_cluster_head(void) { return cluster_head_; } /* * RESET * resets the module * initializes values * */ void reset() { cluster_head_ = false; } /* * CALCULATE_HEAD * defines if the node is a cluster head or not * if a cluster head return true * */ bool calculate_head() { int random_num = rand()(100); // check condition to be a cluster head if (random_num < probability_) { cluster_head_ = true; } else { cluster_head_ = false; } return cluster_head_; } private: bool cluster_head_; // if a cluster head int probability_; // clustering parameter Radio * radio_; Debug * debug_; Rand * rand_; Radio& radio() { return *radio_; } Debug& debug() { return *debug_; } Rand& rand() { return *rand_; } }; } #endif
977346d4f37a9d9fc283f89c20ef3d67cdf22b21
e577d913747e591d38bbbe3d773ce6cde7ebd4b7
/include/Triangle.h
8bb9b6d310d7e157135b18d5a52806f57f205ce1
[]
no_license
rohan166/raytracer
44b0ef6f35874fa05a7f525fbd0424ebc00c2dbc
6a7ddc3afbd0ab94d3f5762cbadb0cdca444f074
refs/heads/master
2020-12-27T01:46:16.146655
2016-03-30T08:04:52
2016-03-30T08:04:52
38,178,320
0
2
null
null
null
null
UTF-8
C++
false
false
387
h
Triangle.h
#ifndef RAYTRACER_TRIANGLE_H #define RAYTRACER_TRIANGLE_H #include "Prop.h" #include "Intersection.h" #include "Plane.h" #include "Vector3.h" #include "Plane.h" class Intersection; class Triangle : public Plane { public: Vector3 a, b; Triangle(Point3 n, Point3 e, Point3 f, Material& m); Intersection intersects(const Ray& ray) const; }; #endif //RAYTRACER_TRIANGLE_H
ba092d6a0df815bbce97f0c524e23020609bf3fb
1ea60c0d3a971ec425fab89d82fd291d3fd4d6a1
/filterfalse.hpp
0f07f0afb7c5e7cbccbc0b779b4913fcb73e543d
[ "MIT" ]
permissive
itamar600/c-assignment-5
35ebf819dd079266c388409ac96d25ee5c4af7d5
e8dac2e42cb868de370a8054c01f378682fc63a2
refs/heads/master
2022-11-07T05:54:24.982128
2020-06-21T09:22:57
2020-06-21T09:22:57
272,504,919
0
0
null
null
null
null
UTF-8
C++
false
false
2,339
hpp
filterfalse.hpp
#include <iostream> #include <vector> namespace itertools{ template<typename FUNCTION, class T> struct filterfalse{ const T& con; const FUNCTION& f; filterfalse(const FUNCTION& f, const T& con): con(con),f(f) { // this->con=&con; // this->f=&f; } struct iterator{ T* con; FUNCTION* f; int countS, countF; iterator(FUNCTION& f, T& con){ countS=0; countF=0; this->con=&con; this->f=&f; for(auto temp: con){ countF++; } // std::cout<<"countf: "<< countF<<"\n"<<std::endl; indForCountS(); } // void operator +(int b ){ // countS+=b; // } void operator ++(){ countS++; indForCountS(); } bool operator !=(struct iterator b ){ return countS!=b.countF; } int operator *(){ int count =0; for(auto temp: *con){ if(count==countS) return temp; count++; } return 0; } void indForCountS(){ for(int i=countS;i<countF; i++){ if(isFalse(i)){ countS=i; // std::cout<<"counts: "<< countS<<"\n"<<std::endl; return; } } countS=countF; } bool isFalse(int i){ int count =0; for(auto temp: *con){ if(count==i){ if(!((*f)(temp))) return true; else return false; } count++; } return false; } }; iterator begin(){ iterator i ((FUNCTION&)f, (T&)con); return i; } auto end(){ iterator i ((FUNCTION&)f, (T&)con); i.countS=i.countF; return i; } }; }
1d571290fcd212359b2f99a8d8aefc3c72f0936c
980a7323eeeaff50fc272c1680af9649acaae305
/Game/CarControllerSystem.cpp
556043d03d2ae8498d37a3b66eb73576b9779b6d
[]
no_license
Mrp1Dev/CookieEngine
29d59e082153bc9d73d9ac4081f567ce8550c62c
548bd7aa4e0e1f0e4737e08d2bb6dd8d3d86395b
refs/heads/main
2023-06-23T02:03:02.008300
2021-07-09T15:29:13
2021-07-09T15:29:13
353,698,357
7
1
null
null
null
null
UTF-8
C++
false
false
3,334
cpp
CarControllerSystem.cpp
#include "CarControllerSystem.h" #include <ckMath.h> #include <Resources.h> #include <PhysicsComponents.h> #include <RenderingComponents.h> #include "CarControllerData.h" using namespace ck; using namespace ck::math; using namespace ck::physics; using namespace physx; void CarControllerSystem::FixedUpdate(World* world) { auto input { world->GetResource<Input>() }; auto time { world->GetResource<Time>() }; auto carQuery { world->QueryEntities<TransformData, RigidBodyDynamicData, CarControllerData, BoxColliderData>() }; carQuery->Foreach([&](TransformData& transform, RigidBodyDynamicData& rb, CarControllerData& car, BoxColliderData& collider) { const auto VC = PxForceMode::eVELOCITY_CHANGE; //input f32 verticalAxis { 0.0f }; verticalAxis += input->keys[KeyCode::UpArrow].pressed; verticalAxis -= input->keys[KeyCode::DownArrow].pressed; f32 horizontalAxis { 0.0f }; horizontalAxis += input->keys[KeyCode::RightArrow].pressed; horizontalAxis -= input->keys[KeyCode::LeftArrow].pressed; std::cout << Vector3(rb.pxRb->getLinearVelocity()).Magnitude() << '\n'; rb.pxRb->setAngularDamping(3.0f); rb.pxRb->setRigidDynamicLockFlags(PxRigidDynamicLockFlag::eLOCK_ANGULAR_X | PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z | PxRigidDynamicLockFlag::eLOCK_LINEAR_Y); //Accel rb.pxRb->addForce(transform.rotation * Vector3::Forward() * car.acceleration * time->fixedDeltaTime * verticalAxis, VC); //Top speed clamp auto forwardVel = Vector3::Project(rb.pxRb->getLinearVelocity(), transform.rotation * Vector3::Forward()); rb.pxRb->addForce(forwardVel.Magnitude() > car.maxSpeed ? -(forwardVel - Vector3::ClampMagnitude(forwardVel, car.maxSpeed)) : Vector3::Zero(), VC); //De-accel auto deaccel = Vector3::Project(-rb.pxRb->getLinearVelocity(), transform.rotation * Vector3::Forward()) * car.slowdown * (Mathf::Approximately(verticalAxis, 0.0f) ? 1.0f : 0.0f) * time->fixedDeltaTime; rb.pxRb->addForce(deaccel, VC); //Sideways 'Drag' rb.pxRb->addForce(Vector3::Project(-rb.pxRb->getLinearVelocity(), transform.rotation * Vector3::Right()) * car.sidewaysDrag * time->fixedDeltaTime, VC); //Braking. if (!Mathf::Approximately(verticalAxis, 0.0f)) { if (Vector3(rb.pxRb->getLinearVelocity()).Magnitude() > 0.0f) { auto dot = Vector3::Dot(Vector3(rb.pxRb->getLinearVelocity()).Normalized(), transform.rotation * Vector3::Forward()); if ((dot > 0.0f && verticalAxis < 0.0f) || (dot < 0.0f && verticalAxis > 0.0f)) rb.pxRb->addForce(-rb.pxRb->getLinearVelocity() * car.brakingStrength * time->fixedDeltaTime * Mathf::Abs(verticalAxis), VC); } } //turning f32 carLength = collider.extents.z * transform.scale.z; auto actualTurnSpeed = car.turnSpeed * Mathf::InverseLerp(0.0f, carLength, forwardVel.Magnitude()); auto td = Mathf::Sign(horizontalAxis) == Mathf::Sign(rb.pxRb->getAngularVelocity().y) ? Mathf::Clamp(actualTurnSpeed * time->fixedDeltaTime, 0.0f, Mathf::Max(car.maxTurnSpeed - Vector3(rb.pxRb->getAngularVelocity()).Magnitude(), 0.0f)) : actualTurnSpeed * time->fixedDeltaTime; rb.pxRb->addTorque(Vector3::Up() * horizontalAxis * td, VC); }); }
655cf8b5a257ca4a87593ad66ea9ba9cd1938c89
5b41e312db8aeb5532ba59498c93e2ec1dccd4ff
/Tools/Simulator/tlggen/CExpInvalidTlg.h
ec5ac9b9b3221fd4206dedaf4b003fdde776873e
[]
no_license
frankilfrancis/KPO_HMI_vs17
10d96c6cb4aebffb83254e6ca38fe6d1033eba79
de49aa55eccd8a7abc165f6057088a28426a1ceb
refs/heads/master
2020-04-15T16:40:14.366351
2019-11-14T15:33:25
2019-11-14T15:33:25
164,845,188
0
1
null
null
null
null
UTF-8
C++
false
false
646
h
CExpInvalidTlg.h
// Copyright 2006 SMS - Demag AG #ifndef _CExpInvalidTlg_H_ #define _CExpInvalidTlg_H_ #include "CBaseExp.h" //------------------------------------------------------ // Name: CExpInvalidTlg.h // Descr: Mit dieser Klasse werden Fehlern, die waehrend // der Bildung eines Telegramms entstehen, behandelt. // Date: // Autor: Emeljanov Anatolij //------------------------------------------------------ class CExpInvalidTlg : public CBaseExp { public: CExpInvalidTlg(const std::string& tlg,const std::string& el,const std::string& err); ~CExpInvalidTlg(); const std::string& getError(); private: std::string ErrorMess; }; #endif
caae59f94622f2ce503476148c3b7b9a226b367e
522a1f8533c93accabe956a36e5daa329feb1d39
/SPOJ/cipo.cpp
cf616e22e129e662a69e744ff491e9588e50761d
[]
no_license
p-freire/CompProg
b69f6e6a6649f8c9bb72fe8027d7a1c917da3a30
5c58a187f776a3ad23dbfbb9a39c810210a191ec
refs/heads/master
2021-07-05T22:34:53.303011
2016-12-05T13:35:44
2016-12-05T13:35:44
58,413,853
0
0
null
null
null
null
UTF-8
C++
false
false
2,167
cpp
cipo.cpp
#include <iostream> #include <queue> #define tamMax 1010 #define BIGINT 9999999 using namespace std; int matAdj[tamMax][tamMax]; int distancias[tamMax]; bool foiVisitado[tamMax]; void Prim(int vInicial, int tamanho) { int i; priority_queue< pair<int, int> > filaVertices; pair<int, int> tmp; distancias[vInicial] = 0; filaVertices.push(pair<int, int> (distancias[vInicial], vInicial)); while(!filaVertices.empty()) { tmp = filaVertices.top(); filaVertices.pop(); i = tmp.second; foiVisitado[i] = true; for(int j = 1; j <= tamanho; j++) if(matAdj[i][j] > 0 && !foiVisitado[j] && distancias[j] > matAdj[i][j]) { distancias[j] = matAdj[i][j]; filaVertices.push(pair<int, int> (-distancias[j], j)); } } } int main() { for(int i = 0; i < tamMax; i++) { for(int j = 0; j < tamMax; j++) matAdj[i][j] = 0; distancias[i] = BIGINT; foiVisitado[i] = false; } int n, m, indice1, indice2, peso, distancia = 0, instancia = 1; while(scanf("%d %d", &n, &m) != EOF) { while(m > 0) { scanf("%d %d %d", &indice1, &indice2, &peso); if(matAdj[indice1][indice2] == 0 || matAdj[indice1][indice2] > peso) { matAdj[indice1][indice2] = peso; matAdj[indice2][indice1] = peso; } m--; } for(int i = 1; i <= n; i++) { if(!foiVisitado[i]) Prim(i, n+1); } for(int i = 1; i <= n; i++) { if(distancias[i] != BIGINT) distancia += distancias[i]; } printf("Instancia %d\n%d\n\n", instancia, distancia); distancia = 0; instancia++; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) matAdj[i][j] = 0; distancias[i] = BIGINT; foiVisitado[i] = false; } } return 0; }
2aee721d440df66a616c4f2e8c016e1befde513c
19cc1ba930e2b391b5c41b6c24fb55fee824ef33
/kyotocabinet-sys/kyotocabinet-1.2.76/kctextdb.h
324af3d8f12f16c072c8981b96198788cb9b1bd0
[ "GPL-3.0-only", "GPL-1.0-or-later", "MIT" ]
permissive
rinatz/casket
a1c1b8588f4c8b9228ac5c5526fdcac59d2ac4ee
3d8f933b0260a4e988bbb956a20a51326ed7d858
refs/heads/master
2021-07-01T21:21:13.738437
2020-10-01T15:19:24
2020-10-01T15:19:24
162,697,524
0
1
MIT
2019-03-28T06:32:58
2018-12-21T09:56:42
Rust
UTF-8
C++
false
false
43,542
h
kctextdb.h
/************************************************************************************************* * Plain text database * Copyright (C) 2009-2012 FAL Labs * This file is part of Kyoto Cabinet. * 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 * 3 of the License, or 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, see <http://www.gnu.org/licenses/>. *************************************************************************************************/ #ifndef _KCTEXTDB_H // duplication check #define _KCTEXTDB_H #include <kccommon.h> #include <kcutil.h> #include <kcthread.h> #include <kcfile.h> #include <kccompress.h> #include <kccompare.h> #include <kcmap.h> #include <kcregex.h> #include <kcdb.h> namespace kyotocabinet { // common namespace /** * Plain text database. * @note Although this class is designed to use a text file as a database file, not all methods * are implemented. Each line in the text is treated as a record. When storing a record, the * key is ignored and the value only is appended at the end of the file. Records can be * retrieved only by the iterator and the cursor mechanisms. No record can be retrieved by * specifying the key. When accessing a record by the iterator, the key is given as the offset * from the beginning of the file for descriptive purposes. Any existing record cannot be * modified and deleted. */ class TextDB : public BasicDB { public: class Cursor; private: class ScopedVisitor; /** An alias of list of cursors. */ typedef std::list<Cursor*> CursorList; /** An alias of a past record. */ typedef std::pair<int64_t, std::string> Record; /** The size of the IO buffer. */ static const size_t IOBUFSIZ = 1024; public: /** * Cursor to indicate a record. */ class Cursor : public BasicDB::Cursor { friend class TextDB; public: /** * Constructor. * @param db the container database object. */ explicit Cursor(TextDB* db) : db_(db), off_(INT64MAX), end_(0), queue_(), line_() { _assert_(db); ScopedRWLock lock(&db_->mlock_, true); db_->curs_.push_back(this); } /** * Destructor. */ virtual ~Cursor() { _assert_(true); if (!db_) return; ScopedRWLock lock(&db_->mlock_, true); db_->curs_.remove(this); } /** * Accept a visitor to the current record. * @param visitor a visitor object. * @param writable true for writable operation, or false for read-only operation. * @param step true to move the cursor to the next record, or false for no move. * @return true on success, or false on failure. * @note The key is generated from the offset of each record. To avoid deadlock, any * explicit database operation must not be performed in this function. */ bool accept(Visitor* visitor, bool writable = true, bool step = false) { _assert_(visitor); ScopedRWLock lock(&db_->mlock_, false); if (db_->omode_ == 0) { db_->set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } if (writable && !db_->writer_) { db_->set_error(_KCCODELINE_, Error::NOPERM, "permission denied"); return false; } bool err = false; if (!accept_impl(visitor, step)) err = true; return !err; } /** * Jump the cursor to the first record for forward scan. * @return true on success, or false on failure. */ bool jump() { _assert_(true); ScopedRWLock lock(&db_->mlock_, false); if (db_->omode_ == 0) { db_->set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } off_ = 0; end_ = db_->file_.size(); queue_.clear(); line_.clear(); if (off_ >= end_) { db_->set_error(_KCCODELINE_, Error::NOREC, "no record"); return false; } return true; } /** * Jump the cursor to a record for forward scan. * @param kbuf the pointer to the key region. * @param ksiz the size of the key region. * @return true on success, or false on failure. */ bool jump(const char* kbuf, size_t ksiz) { _assert_(kbuf && ksiz <= MEMMAXSIZ); ScopedRWLock lock(&db_->mlock_, true); if (db_->omode_ == 0) { db_->set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } off_ = atoin(kbuf, ksiz); end_ = db_->file_.size(); queue_.clear(); line_.clear(); if (off_ >= end_) { db_->set_error(_KCCODELINE_, Error::NOREC, "no record"); return false; } return true; } /** * Jump the cursor to a record for forward scan. * @note Equal to the original Cursor::jump method except that the parameter is std::string. */ bool jump(const std::string& key) { _assert_(true); return jump(key.c_str(), key.size()); } /** * Jump the cursor to the last record for backward scan. * @note This is a dummy implementation for compatibility. */ bool jump_back() { _assert_(true); ScopedRWLock lock(&db_->mlock_, true); if (db_->omode_ == 0) { db_->set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } db_->set_error(_KCCODELINE_, Error::NOIMPL, "not implemented"); return false; } /** * Jump the cursor to a record for backward scan. * @note This is a dummy implementation for compatibility. */ bool jump_back(const char* kbuf, size_t ksiz) { _assert_(kbuf && ksiz <= MEMMAXSIZ); ScopedRWLock lock(&db_->mlock_, true); if (db_->omode_ == 0) { db_->set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } db_->set_error(_KCCODELINE_, Error::NOIMPL, "not implemented"); return false; } /** * Jump the cursor to a record for backward scan. * @note This is a dummy implementation for compatibility. */ bool jump_back(const std::string& key) { _assert_(true); return jump_back(key.c_str(), key.size()); } /** * Step the cursor to the next record. * @return true on success, or false on failure. */ bool step() { _assert_(true); ScopedRWLock lock(&db_->mlock_, false); if (db_->omode_ == 0) { db_->set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } if (queue_.empty() && !read_next()) return false; if (queue_.empty()) { db_->set_error(_KCCODELINE_, Error::NOREC, "no record"); return false; } queue_.pop_front(); return true; } /** * Step the cursor to the previous record. * @note This is a dummy implementation for compatibility. */ bool step_back() { _assert_(true); ScopedRWLock lock(&db_->mlock_, true); if (db_->omode_ == 0) { db_->set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } db_->set_error(_KCCODELINE_, Error::NOIMPL, "not implemented"); return false; } /** * Get the database object. * @return the database object. */ TextDB* db() { _assert_(true); return db_; } private: /** * Accept a visitor to the current record. * @param visitor a visitor object. * @param step true to move the cursor to the next record, or false for no move. * @return true on success, or false on failure. */ bool accept_impl(Visitor* visitor, bool step) { _assert_(visitor); if (queue_.empty() && !read_next()) return false; if (queue_.empty()) { db_->set_error(_KCCODELINE_, Error::NOREC, "no record"); return false; } bool err = false; const Record& rec = queue_.front(); char kbuf[NUMBUFSIZ]; size_t ksiz = db_->write_key(kbuf, rec.first); size_t vsiz; const char* vbuf = visitor->visit_full(kbuf, ksiz, rec.second.data(), rec.second.size(), &vsiz); if (vbuf != Visitor::NOP && vbuf != Visitor::REMOVE) { char stack[IOBUFSIZ]; size_t rsiz = vsiz + 1; char* rbuf = rsiz > sizeof(stack) ? new char[rsiz] : stack; std::memcpy(rbuf, vbuf, vsiz); rbuf[vsiz] = '\n'; if (!db_->file_.append(rbuf, rsiz)) { db_->set_error(_KCCODELINE_, Error::SYSTEM, db_->file_.error()); err = true; } if (rbuf != stack) delete[] rbuf; if (db_->autosync_ && !db_->file_.synchronize(true)) { db_->set_error(_KCCODELINE_, Error::SYSTEM, db_->file_.error()); err = true; } } if (step) queue_.pop_front(); return !err; } /** * Read the next record. * @return true on success, or false on failure. */ bool read_next() { _assert_(true); while (off_ < end_) { char stack[IOBUFSIZ]; int64_t rsiz = end_ - off_; if (rsiz > (int64_t)sizeof(stack)) rsiz = sizeof(stack); if (!db_->file_.read_fast(off_, stack, rsiz)) { db_->set_error(_KCCODELINE_, Error::SYSTEM, db_->file_.error()); return false; } const char* rp = stack; const char* pv = rp; const char* ep = rp + rsiz; while (rp < ep) { if (*rp == '\n') { line_.append(pv, rp - pv); Record rec; rec.first = off_ + pv - stack; rec.second = line_; queue_.push_back(rec); line_.clear(); rp++; pv = rp; } else { rp++; } } line_.append(pv, rp - pv); off_ += rsiz; if (!queue_.empty()) break; } return true; } /** Dummy constructor to forbid the use. */ Cursor(const Cursor&); /** Dummy Operator to forbid the use. */ Cursor& operator =(const Cursor&); /** The inner database. */ TextDB* db_; /** The current offset. */ int64_t off_; /** The end offset. */ int64_t end_; /** The queue of read lines. */ std::deque<Record> queue_; /** The current line. */ std::string line_; }; /** * Default constructor. */ explicit TextDB() : error_(), logger_(NULL), logkinds_(0), mtrigger_(NULL), omode_(0), writer_(false), autotran_(false), autosync_(false), file_(), curs_(), path_("") { _assert_(true); } /** * Destructor. * @note If the database is not closed, it is closed implicitly. */ virtual ~TextDB() { _assert_(true); if (omode_ != 0) close(); if (!curs_.empty()) { CursorList::const_iterator cit = curs_.begin(); CursorList::const_iterator citend = curs_.end(); while (cit != citend) { Cursor* cur = *cit; cur->db_ = NULL; ++cit; } } } /** * Accept a visitor to a record. * @param kbuf the pointer to the key region. * @param ksiz the size of the key region. * @param visitor a visitor object. * @param writable true for writable operation, or false for read-only operation. * @return true on success, or false on failure. * @note No record can be retrieved by specifying the key and the Visitor::visit_empty method * is always called. To avoid deadlock, any explicit database operation must not be performed * in this function. */ bool accept(const char* kbuf, size_t ksiz, Visitor* visitor, bool writable = true) { _assert_(kbuf && ksiz <= MEMMAXSIZ && visitor); ScopedRWLock lock(&mlock_, false); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } if (writable && !writer_) { set_error(_KCCODELINE_, Error::NOPERM, "permission denied"); return false; } bool err = false; if (!accept_impl(kbuf, ksiz, visitor)) err = true; return !err; } /** * Accept a visitor to multiple records at once. * @param keys specifies a string vector of the keys. * @param visitor a visitor object. * @param writable true for writable operation, or false for read-only operation. * @return true on success, or false on failure. * @note No record can be retrieved by specifying the key and the Visitor::visit_empty method * is always called. To avoid deadlock, any explicit database operation must not be performed * in this function. */ bool accept_bulk(const std::vector<std::string>& keys, Visitor* visitor, bool writable = true) { _assert_(visitor); ScopedRWLock lock(&mlock_, true); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } if (writable && !writer_) { set_error(_KCCODELINE_, Error::NOPERM, "permission denied"); return false; } ScopedVisitor svis(visitor); bool err = false; std::vector<std::string>::const_iterator kit = keys.begin(); std::vector<std::string>::const_iterator kitend = keys.end(); while (kit != kitend) { if (!accept_impl(kit->data(), kit->size(), visitor)) err = true; ++kit; } return !err; } /** * Iterate to accept a visitor for each record. * @param visitor a visitor object. * @param writable true for writable operation, or false for read-only operation. * @param checker a progress checker object. If it is NULL, no checking is performed. * @return true on success, or false on failure. * @note The key is generated from the offset of each record. To avoid deadlock, any explicit * database operation must not be performed in this function. */ bool iterate(Visitor *visitor, bool writable = true, ProgressChecker* checker = NULL) { _assert_(visitor); ScopedRWLock lock(&mlock_, true); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } if (writable && !writer_) { set_error(_KCCODELINE_, Error::NOPERM, "permission denied"); return false; } ScopedVisitor svis(visitor); bool err = false; if (!iterate_impl(visitor, checker)) err = true; trigger_meta(MetaTrigger::ITERATE, "iterate"); return !err; } /** * Scan each record in parallel. * @param visitor a visitor object. * @param thnum the number of worker threads. * @param checker a progress checker object. If it is NULL, no checking is performed. * @return true on success, or false on failure. * @note This function is for reading records and not for updating ones. The return value of * the visitor is just ignored. The key is generated from the offset of each record. To * avoid deadlock, any explicit database operation must not be performed in this function. */ bool scan_parallel(Visitor *visitor, size_t thnum, ProgressChecker* checker = NULL) { _assert_(visitor && thnum <= MEMMAXSIZ); ScopedRWLock lock(&mlock_, false); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } if (thnum < 1) thnum = 1; if (thnum > (size_t)INT8MAX) thnum = INT8MAX; ScopedVisitor svis(visitor); bool err = false; if (!scan_parallel_impl(visitor, thnum, checker)) err = true; trigger_meta(MetaTrigger::ITERATE, "scan_parallel"); return !err; } /** * Get the last happened error. * @return the last happened error. */ Error error() const { _assert_(true); return error_; } /** * Set the error information. * @param file the file name of the program source code. * @param line the line number of the program source code. * @param func the function name of the program source code. * @param code an error code. * @param message a supplement message. */ void set_error(const char* file, int32_t line, const char* func, Error::Code code, const char* message) { _assert_(file && line > 0 && func && message); error_->set(code, message); if (logger_) { Logger::Kind kind = code == Error::BROKEN || code == Error::SYSTEM ? Logger::ERROR : Logger::INFO; if (kind & logkinds_) report(file, line, func, kind, "%d: %s: %s", code, Error::codename(code), message); } } /** * Open a database file. * @param path the path of a database file. * @param mode the connection mode. TextDB::OWRITER as a writer, TextDB::OREADER as a * reader. The following may be added to the writer mode by bitwise-or: TextDB::OCREATE, * which means it creates a new database if the file does not exist, TextDB::OTRUNCATE, which * means it creates a new database regardless if the file exists, TextDB::OAUTOTRAN, which * means each updating operation is performed in implicit transaction, TextDB::OAUTOSYNC, * which means each updating operation is followed by implicit synchronization with the file * system. The following may be added to both of the reader mode and the writer mode by * bitwise-or: TextDB::ONOLOCK, which means it opens the database file without file locking, * TextDB::OTRYLOCK, which means locking is performed without blocking, TextDB::ONOREPAIR, * which means the database file is not repaired implicitly even if file destruction is * detected. * @return true on success, or false on failure. * @note Every opened database must be closed by the TextDB::close method when it is no * longer in use. It is not allowed for two or more database objects in the same process to * keep their connections to the same database file at the same time. */ bool open(const std::string& path, uint32_t mode = OWRITER | OCREATE) { _assert_(true); ScopedRWLock lock(&mlock_, true); if (omode_ != 0) { set_error(_KCCODELINE_, Error::INVALID, "already opened"); return false; } report(_KCCODELINE_, Logger::DEBUG, "opening the database (path=%s)", path.c_str()); writer_ = false; autotran_ = false; autosync_ = false; uint32_t fmode = File::OREADER; if (mode & OWRITER) { writer_ = true; fmode = File::OWRITER; if (mode & OCREATE) fmode |= File::OCREATE; if (mode & OTRUNCATE) fmode |= File::OTRUNCATE; if (mode & OAUTOTRAN) autotran_ = true; if (mode & OAUTOSYNC) autosync_ = true; } if (mode & ONOLOCK) fmode |= File::ONOLOCK; if (mode & OTRYLOCK) fmode |= File::OTRYLOCK; if (!file_.open(path, fmode, 0)) { const char* emsg = file_.error(); Error::Code code = Error::SYSTEM; if (std::strstr(emsg, "(permission denied)") || std::strstr(emsg, "(directory)")) { code = Error::NOPERM; } else if (std::strstr(emsg, "(file not found)") || std::strstr(emsg, "(invalid path)")) { code = Error::NOREPOS; } set_error(_KCCODELINE_, code, emsg); return false; } if (autosync_ && !File::synchronize_whole()) { set_error(_KCCODELINE_, Error::SYSTEM, "synchronizing the file system failed"); file_.close(); return false; } path_.append(path); omode_ = mode; trigger_meta(MetaTrigger::OPEN, "open"); return true; } /** * Close the database file. * @return true on success, or false on failure. */ bool close() { _assert_(true); ScopedRWLock lock(&mlock_, true); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } report(_KCCODELINE_, Logger::DEBUG, "closing the database (path=%s)", path_.c_str()); bool err = false; disable_cursors(); if (!file_.close()) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); err = true; } omode_ = 0; path_.clear(); trigger_meta(MetaTrigger::CLOSE, "close"); return !err; } /** * Synchronize updated contents with the file and the device. * @param hard true for physical synchronization with the device, or false for logical * synchronization with the file system. * @param proc a postprocessor object. If it is NULL, no postprocessing is performed. * @param checker a progress checker object. If it is NULL, no checking is performed. * @return true on success, or false on failure. * @note The operation of the postprocessor is performed atomically and other threads accessing * the same record are blocked. To avoid deadlock, any explicit database operation must not * be performed in this function. */ bool synchronize(bool hard = false, FileProcessor* proc = NULL, ProgressChecker* checker = NULL) { _assert_(true); ScopedRWLock lock(&mlock_, false); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } bool err = false; if (!synchronize_impl(hard, proc, checker)) err = true; trigger_meta(MetaTrigger::SYNCHRONIZE, "synchronize"); return !err; } /** * Occupy database by locking and do something meanwhile. * @param writable true to use writer lock, or false to use reader lock. * @param proc a processor object. If it is NULL, no processing is performed. * @return true on success, or false on failure. * @note The operation of the processor is performed atomically and other threads accessing * the same record are blocked. To avoid deadlock, any explicit database operation must not * be performed in this function. */ bool occupy(bool writable = true, FileProcessor* proc = NULL) { _assert_(true); ScopedRWLock lock(&mlock_, writable); bool err = false; if (proc && !proc->process(path_, -1, file_.size())) { set_error(_KCCODELINE_, Error::LOGIC, "processing failed"); err = true; } trigger_meta(MetaTrigger::OCCUPY, "occupy"); return !err; } /** * Begin transaction. * @param hard true for physical synchronization with the device, or false for logical * synchronization with the file system. * @return true on success, or false on failure. */ bool begin_transaction(bool hard = false) { _assert_(true); ScopedRWLock lock(&mlock_, true); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } set_error(_KCCODELINE_, Error::NOIMPL, "not implemented"); return false; } /** * Try to begin transaction. * @param hard true for physical synchronization with the device, or false for logical * synchronization with the file system. * @return true on success, or false on failure. */ bool begin_transaction_try(bool hard = false) { _assert_(true); ScopedRWLock lock(&mlock_, true); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } set_error(_KCCODELINE_, Error::NOIMPL, "not implemented"); return false; } /** * End transaction. * @param commit true to commit the transaction, or false to abort the transaction. * @return true on success, or false on failure. */ bool end_transaction(bool commit = true) { _assert_(true); ScopedRWLock lock(&mlock_, true); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } set_error(_KCCODELINE_, Error::NOIMPL, "not implemented"); return false; } /** * Remove all records. * @return true on success, or false on failure. */ bool clear() { _assert_(true); ScopedRWLock lock(&mlock_, true); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } if (!writer_) { set_error(_KCCODELINE_, Error::NOPERM, "permission denied"); return false; } disable_cursors(); if (!file_.truncate(0)) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); return false; } if (autosync_ && !file_.synchronize(true)) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); return false; } trigger_meta(MetaTrigger::CLEAR, "clear"); return true; } /** * Get the number of records. * @return the number of records, or -1 on failure. */ int64_t count() { _assert_(true); ScopedRWLock lock(&mlock_, false); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return -1; } set_error(_KCCODELINE_, Error::NOIMPL, "not implemented"); return -1; } /** * Get the size of the database file. * @return the size of the database file in bytes, or -1 on failure. */ int64_t size() { _assert_(true); ScopedRWLock lock(&mlock_, false); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return -1; } return file_.size(); } /** * Get the path of the database file. * @return the path of the database file, or an empty string on failure. */ std::string path() { _assert_(true); return path_; } /** * Get the miscellaneous status information. * @param strmap a string map to contain the result. * @return true on success, or false on failure. */ bool status(std::map<std::string, std::string>* strmap) { _assert_(strmap); ScopedRWLock lock(&mlock_, true); if (omode_ == 0) { set_error(_KCCODELINE_, Error::INVALID, "not opened"); return false; } (*strmap)["type"] = strprintf("%u", (unsigned)TYPETEXT); (*strmap)["realtype"] = strprintf("%u", (unsigned)TYPETEXT); (*strmap)["path"] = path_; (*strmap)["size"] = strprintf("%lld", (long long)file_.size()); return true; } /** * Create a cursor object. * @return the return value is the created cursor object. * @note Because the object of the return value is allocated by the constructor, it should be * released with the delete operator when it is no longer in use. */ Cursor* cursor() { _assert_(true); return new Cursor(this); } /** * Write a log message. * @param file the file name of the program source code. * @param line the line number of the program source code. * @param func the function name of the program source code. * @param kind the kind of the event. Logger::DEBUG for debugging, Logger::INFO for normal * information, Logger::WARN for warning, and Logger::ERROR for fatal error. * @param message the supplement message. */ void log(const char* file, int32_t line, const char* func, Logger::Kind kind, const char* message) { _assert_(file && line > 0 && func && message); ScopedRWLock lock(&mlock_, false); if (!logger_) return; logger_->log(file, line, func, kind, message); } /** * Set the internal logger. * @param logger the logger object. * @param kinds kinds of logged messages by bitwise-or: Logger::DEBUG for debugging, * Logger::INFO for normal information, Logger::WARN for warning, and Logger::ERROR for fatal * error. * @return true on success, or false on failure. */ bool tune_logger(Logger* logger, uint32_t kinds = Logger::WARN | Logger::ERROR) { _assert_(logger); ScopedRWLock lock(&mlock_, true); if (omode_ != 0) { set_error(_KCCODELINE_, Error::INVALID, "already opened"); return false; } logger_ = logger; logkinds_ = kinds; return true; } /** * Set the internal meta operation trigger. * @param trigger the trigger object. * @return true on success, or false on failure. */ bool tune_meta_trigger(MetaTrigger* trigger) { _assert_(trigger); ScopedRWLock lock(&mlock_, true); if (omode_ != 0) { set_error(_KCCODELINE_, Error::INVALID, "already opened"); return false; } mtrigger_ = trigger; return true; } protected: /** * Report a message for debugging. * @param file the file name of the program source code. * @param line the line number of the program source code. * @param func the function name of the program source code. * @param kind the kind of the event. Logger::DEBUG for debugging, Logger::INFO for normal * information, Logger::WARN for warning, and Logger::ERROR for fatal error. * @param format the printf-like format string. * @param ... used according to the format string. */ void report(const char* file, int32_t line, const char* func, Logger::Kind kind, const char* format, ...) { _assert_(file && line > 0 && func && format); if (!logger_ || !(kind & logkinds_)) return; std::string message; strprintf(&message, "%s: ", path_.empty() ? "-" : path_.c_str()); va_list ap; va_start(ap, format); vstrprintf(&message, format, ap); va_end(ap); logger_->log(file, line, func, kind, message.c_str()); } /** * Report a message for debugging with variable number of arguments. * @param file the file name of the program source code. * @param line the line number of the program source code. * @param func the function name of the program source code. * @param kind the kind of the event. Logger::DEBUG for debugging, Logger::INFO for normal * information, Logger::WARN for warning, and Logger::ERROR for fatal error. * @param format the printf-like format string. * @param ap used according to the format string. */ void report_valist(const char* file, int32_t line, const char* func, Logger::Kind kind, const char* format, va_list ap) { _assert_(file && line > 0 && func && format); if (!logger_ || !(kind & logkinds_)) return; std::string message; strprintf(&message, "%s: ", path_.empty() ? "-" : path_.c_str()); vstrprintf(&message, format, ap); logger_->log(file, line, func, kind, message.c_str()); } /** * Report the content of a binary buffer for debugging. * @param file the file name of the epicenter. * @param line the line number of the epicenter. * @param func the function name of the program source code. * @param kind the kind of the event. Logger::DEBUG for debugging, Logger::INFO for normal * information, Logger::WARN for warning, and Logger::ERROR for fatal error. * @param name the name of the information. * @param buf the binary buffer. * @param size the size of the binary buffer */ void report_binary(const char* file, int32_t line, const char* func, Logger::Kind kind, const char* name, const char* buf, size_t size) { _assert_(file && line > 0 && func && name && buf && size <= MEMMAXSIZ); if (!logger_) return; char* hex = hexencode(buf, size); report(file, line, func, kind, "%s=%s", name, hex); delete[] hex; } /** * Trigger a meta database operation. * @param kind the kind of the event. MetaTrigger::OPEN for opening, MetaTrigger::CLOSE for * closing, MetaTrigger::CLEAR for clearing, MetaTrigger::ITERATE for iteration, * MetaTrigger::SYNCHRONIZE for synchronization, MetaTrigger::BEGINTRAN for beginning * transaction, MetaTrigger::COMMITTRAN for committing transaction, MetaTrigger::ABORTTRAN * for aborting transaction, and MetaTrigger::MISC for miscellaneous operations. * @param message the supplement message. */ void trigger_meta(MetaTrigger::Kind kind, const char* message) { _assert_(message); if (mtrigger_) mtrigger_->trigger(kind, message); } private: /** * Scoped visitor. */ class ScopedVisitor { public: /** constructor */ explicit ScopedVisitor(Visitor* visitor) : visitor_(visitor) { _assert_(visitor); visitor_->visit_before(); } /** destructor */ ~ScopedVisitor() { _assert_(true); visitor_->visit_after(); } private: Visitor* visitor_; ///< visitor }; /** * Accept a visitor to a record. * @param kbuf the pointer to the key region. * @param ksiz the size of the key region. * @param visitor a visitor object. * @return true on success, or false on failure. */ bool accept_impl(const char* kbuf, size_t ksiz, Visitor* visitor) { _assert_(kbuf && ksiz <= MEMMAXSIZ && visitor); bool err = false; size_t vsiz; const char* vbuf = visitor->visit_empty(kbuf, ksiz, &vsiz); if (vbuf != Visitor::NOP && vbuf != Visitor::REMOVE) { size_t rsiz = vsiz + 1; char stack[IOBUFSIZ]; char* rbuf = rsiz > sizeof(stack) ? new char[rsiz] : stack; std::memcpy(rbuf, vbuf, vsiz); rbuf[vsiz] = '\n'; if (!file_.append(rbuf, rsiz)) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); err = true; } if (rbuf != stack) delete[] rbuf; if (autosync_ && !file_.synchronize(true)) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); err = true; } } return !err; } /** * Iterate to accept a visitor for each record. * @param visitor a visitor object. * @param checker a progress checker object. * @return true on success, or false on failure. */ bool iterate_impl(Visitor* visitor, ProgressChecker* checker) { _assert_(visitor); if (checker && !checker->check("iterate", "beginning", 0, -1)) { set_error(_KCCODELINE_, Error::LOGIC, "checker failed"); return false; } int64_t off = 0; int64_t end = file_.size(); int64_t curcnt = 0; std::string line; char stack[IOBUFSIZ*4]; while (off < end) { int64_t rsiz = end - off; if (rsiz > (int64_t)sizeof(stack)) rsiz = sizeof(stack); if (!file_.read_fast(off, stack, rsiz)) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); return false; } const char* rp = stack; const char* pv = rp; const char* ep = rp + rsiz; while (rp < ep) { if (*rp == '\n') { char kbuf[NUMBUFSIZ]; size_t ksiz = write_key(kbuf, off + pv - stack); const char* vbuf; size_t vsiz; if (line.empty()) { vbuf = visitor->visit_full(kbuf, ksiz, pv, rp - pv, &vsiz); } else { line.append(pv, rp - pv); vbuf = visitor->visit_full(kbuf, ksiz, line.data(), line.size(), &vsiz); line.clear(); } if (vbuf != Visitor::NOP && vbuf != Visitor::REMOVE) { char tstack[IOBUFSIZ]; size_t trsiz = vsiz + 1; char* trbuf = trsiz > sizeof(tstack) ? new char[trsiz] : tstack; std::memcpy(trbuf, vbuf, vsiz); trbuf[vsiz] = '\n'; if (!file_.append(trbuf, trsiz)) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); if (trbuf != stack) delete[] trbuf; return false; } if (trbuf != tstack) delete[] trbuf; } curcnt++; if (checker && !checker->check("iterate", "processing", curcnt, -1)) { set_error(_KCCODELINE_, Error::LOGIC, "checker failed"); return false; } rp++; pv = rp; } else { rp++; } } line.append(pv, rp - pv); off += rsiz; } if (checker && !checker->check("iterate", "ending", -1, -1)) { set_error(_KCCODELINE_, Error::LOGIC, "checker failed"); return false; } return true; } /** * Scan each record in parallel. * @param visitor a visitor object. * @param thnum the number of worker threads. * @param checker a progress checker object. * @return true on success, or false on failure. */ bool scan_parallel_impl(Visitor *visitor, size_t thnum, ProgressChecker* checker) { _assert_(visitor && thnum <= MEMMAXSIZ); if (checker && !checker->check("scan_parallel", "beginning", -1, -1)) { set_error(_KCCODELINE_, Error::LOGIC, "checker failed"); return false; } int64_t off = 0; int64_t end = file_.size(); int64_t gap = (end - off) / thnum; std::vector<int64_t> offs; while (off < end) { offs.push_back(off); int64_t edge = off + gap; while (true) { if (edge >= end) { off = end; break; } char rbuf[IOBUFSIZ]; int64_t rsiz = end - edge; if (rsiz > (int64_t)sizeof(rbuf)) rsiz = sizeof(rbuf); if (!file_.read_fast(edge, rbuf, rsiz)) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); return false; } int64_t noff = -1; const char* rp = rbuf; const char* ep = rp + rsiz; while (rp < ep) { if (*rp == '\n') { noff = edge + (rp - rbuf); break; } rp++; } if (noff >= 0) { off = noff + 1; break; } edge += rsiz; } } bool err = false; size_t onum = offs.size(); if (onum > 0) { class ThreadImpl : public Thread { public: explicit ThreadImpl() : db_(NULL), visitor_(NULL), checker_(NULL), begoff_(0), endoff_(0), error_() {} void init(TextDB* db, Visitor* visitor, ProgressChecker* checker, int64_t begoff, int64_t endoff) { db_ = db; visitor_ = visitor; checker_ = checker; begoff_ = begoff; endoff_ = endoff; } const Error& error() { return error_; } private: void run() { TextDB* db = db_; File* file = &db->file_; Visitor* visitor = visitor_; ProgressChecker* checker = checker_; int64_t off = begoff_; int64_t end = endoff_; std::string line; char stack[IOBUFSIZ*4]; while (off < end) { int64_t rsiz = end - off; if (rsiz > (int64_t)sizeof(stack)) rsiz = sizeof(stack); if (!file->read_fast(off, stack, rsiz)) { db->set_error(_KCCODELINE_, Error::SYSTEM, file->error()); return; } const char* rp = stack; const char* pv = rp; const char* ep = rp + rsiz; while (rp < ep) { if (*rp == '\n') { char kbuf[NUMBUFSIZ]; size_t ksiz = db->write_key(kbuf, off + pv - stack); if (line.empty()) { size_t vsiz; visitor->visit_full(kbuf, ksiz, pv, rp - pv, &vsiz); } else { line.append(pv, rp - pv); size_t vsiz; visitor->visit_full(kbuf, ksiz, line.data(), line.size(), &vsiz); line.clear(); } if (checker && !checker->check("iterate", "processing", -1, -1)) { db->set_error(_KCCODELINE_, Error::LOGIC, "checker failed"); return; } rp++; pv = rp; } else { rp++; } } line.append(pv, rp - pv); off += rsiz; } } TextDB* db_; Visitor* visitor_; ProgressChecker* checker_; int64_t begoff_; int64_t endoff_; Error error_; }; ThreadImpl* threads = new ThreadImpl[onum]; for (size_t i = 0; i < onum; i++) { int64_t begoff = offs[i]; int64_t endoff = i < onum - 1 ? offs[i+1] : end; ThreadImpl* thread = threads + i; thread->init(this, visitor, checker, begoff, endoff); thread->start(); } for (size_t i = 0; i < onum; i++) { ThreadImpl* thread = threads + i; thread->join(); if (thread->error() != Error::SUCCESS) { *error_ = thread->error(); err = true; } } delete[] threads; } if (checker && !checker->check("scan_parallel", "ending", -1, -1)) { set_error(_KCCODELINE_, Error::LOGIC, "checker failed"); err = true; } return !err; } /** * Synchronize updated contents with the file and the device. * @param hard true for physical synchronization with the device, or false for logical * synchronization with the file system. * @param proc a postprocessor object. * @param checker a progress checker object. * @return true on success, or false on failure. */ bool synchronize_impl(bool hard, FileProcessor* proc, ProgressChecker* checker) { _assert_(true); bool err = false; if (writer_) { if (checker && !checker->check("synchronize", "synchronizing the file", -1, -1)) { set_error(_KCCODELINE_, Error::LOGIC, "checker failed"); return false; } if (!file_.synchronize(hard)) { set_error(_KCCODELINE_, Error::SYSTEM, file_.error()); err = true; } } if (proc) { if (checker && !checker->check("synchronize", "running the post processor", -1, -1)) { set_error(_KCCODELINE_, Error::LOGIC, "checker failed"); return false; } if (!proc->process(path_, -1, file_.size())) { set_error(_KCCODELINE_, Error::LOGIC, "postprocessing failed"); err = true; } } return !err; } /** * Disable all cursors. */ void disable_cursors() { _assert_(true); if (curs_.empty()) return; CursorList::const_iterator cit = curs_.begin(); CursorList::const_iterator citend = curs_.end(); while (cit != citend) { Cursor* cur = *cit; cur->off_ = INT64MAX; ++cit; } } /** * Write the key pattern into a buffer. * @param kbuf the destination buffer. * @param off the offset of the record. * @return the size of the key pattern. */ size_t write_key(char* kbuf, int64_t off) { _assert_(kbuf && off >= 0); for (size_t i = 0; i < sizeof(off); i++) { uint8_t c = off >> ((sizeof(off) - 1 - i) * 8); uint8_t h = c >> 4; if (h < 10) { *(kbuf++) = '0' + h; } else { *(kbuf++) = 'A' - 10 + h; } uint8_t l = c & 0xf; if (l < 10) { *(kbuf++) = '0' + l; } else { *(kbuf++) = 'A' - 10 + l; } } return sizeof(off) * 2; } /** Dummy constructor to forbid the use. */ TextDB(const TextDB&); /** Dummy Operator to forbid the use. */ TextDB& operator =(const TextDB&); /** The method lock. */ RWLock mlock_; /** The last happened error. */ TSD<Error> error_; /** The internal logger. */ Logger* logger_; /** The kinds of logged messages. */ uint32_t logkinds_; /** The internal meta operation trigger. */ MetaTrigger* mtrigger_; /** The open mode. */ uint32_t omode_; /** The flag for writer. */ bool writer_; /** The flag for auto transaction. */ bool autotran_; /** The flag for auto synchronization. */ bool autosync_; /** The file for data. */ File file_; /** The cursor objects. */ CursorList curs_; /** The path of the database file. */ std::string path_; }; } // common namespace #endif // duplication check // END OF FILE
bd5c3a189d41228472cc48d1737f750dc3e6827d
f3378277b0b5b9cf9e04c8edef13469e0c70ee74
/Household_Power_Manager/Household_Power_Manager.ino
3e62b85e7aef5d264ac3c062e1ee3ebc64bc91f2
[]
no_license
BRBussy/Household-Power-Manager
05a1fca019bb42fdec353cd89468d5ce9b98a3fe
f4b93c0e5f77c6ff94075f6aa8cbffb5e4f0098e
refs/heads/master
2016-09-01T07:50:05.682846
2016-04-08T06:59:26
2016-04-08T06:59:26
55,757,762
0
0
null
null
null
null
UTF-8
C++
false
false
17,596
ino
Household_Power_Manager.ino
/* Name: Household_Power_Manager.ino Created: 3/23/2016 3:01:35 PM Author: Bernard */ #include <Arduino.h> #include <Wire.h> #include <RtcUtility.h> #include <RtcDS3231.h> #include <RtcDateTime.h> #include "Ticker.h" #include "WiFiServer.h" #include "WiFiClientSecure.h" #include "WiFiClient.h" #include "ESP8266WiFiType.h" #include "ESP8266WiFiSTA.h" #include "ESP8266WiFiScan.h" #include "ESP8266WiFiMulti.h" #include "ESP8266WiFiGeneric.h" #include "ESP8266WiFiAP.h" #include "ESP8266WiFi.h" #include "rebuild_received_anything.h" //Special Data Types //Scheduling Information Structure struct scheduling_information { //Declare scheduling_information struct type int ID; //Device ID bool hours_on_off[12][31][24]; //hours_on_off[Months, Days, Hours] }; //Time and Date Structure struct time_and_date { //Declare time_and_date struct type int month; int day; int hour; int minute; int second; }; //Power Measurement Structure struct power_measurement { //Declare power_measurement struct type float measurement; //Actual Power Measurement time_and_date when_made; //when this reading was taken int ID; //The Major Appliance ID }; //Major Appliance Status Structure struct major_appliance_status { //Declare major_appliance_status struct type bool on_off; //Current on/off Status power_measurement latest_measurement; //Most recent power reading }; //Definitions #define BAUD 115200 //Modes #define Setup_Mode 0 #define Normal_Mode 1 //Pin Definitions #define SetupModeButton 0 #define SDA_pin 2 #define SCL_pin 14 //Statuses #define WifiConnected 0 #define ConnectedtoServer 1 //WiFi Data Recieve Flags #define New_Data_for_Client 0 #define Send_Data_to_Server 1 #define No_Command_in_data_from_Server 2 #define No_Data_Received 3 #define Wait_Until_Recv true //Commands_Received #define No_Command 0 #define Send_Data_To_Server 1 #define Receive_Data_From_Server 2 //RTC Definitions #define countof(a) (sizeof(a) / sizeof(a[0])) //Global Variable Declarations //Network Details --SAVE to EEPROM String NetworkName = "BernysWAP"; String NetworkPassword = "bionicle123#"; //Client Server Details String Host = "10.0.0.9"; int Port = 6950; //Major Appliance Variables //Other Uncategorized Variables int Operating_Mode; bool Statuses[2] = {}; WiFiClient client; RtcDS3231 Rtc; // the setup function runs once when you press reset or power the board void setup() { //Hardware Setup, pin modes etc. pinMode(SetupModeButton, INPUT); RTC_SETUP(); //Software Setup Operating_Mode = Normal_Mode; }//End setup(); // the loop function runs over and over again until power down or reset void loop() { Serial.begin(BAUD); delay(10); //Check if User is Requesting SetupMode if (!digitalRead(SetupModeButton)) { Operating_Mode = Setup_Mode; } switch (Operating_Mode) { case Setup_Mode: { Serial.println("Running Setup Mode:"); //Setup Mode Variables String inputString = ""; String SSID = ""; String Password = ""; //Setup Mode Code Serial.println("Waiting For Input from Serial:"); while (Operating_Mode == Setup_Mode) { //Read Input From Serial while (Serial.available() > 0) { inputString += (char)Serial.read(); } if (inputString == "Scan") //Display Available WiFi Networks to User { int n = WiFi.scanNetworks(); //No of Networks found if (n == 0) Serial.println("No Networks Found"); else { Serial.print(n); Serial.println(" Networks Found:"); for (int i = 0; i < n; ++i) { // Print SSID and RSSI for each network found Serial.print(i + 1); Serial.print(": "); Serial.print(WiFi.SSID(i)); Serial.print(" ("); Serial.print(WiFi.RSSI(i)); Serial.print(")"); Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*"); delay(10); } } } //End case "Scan" else if (inputString == "Connect") //Connect to WiFi Network { Connect_to_WiFi(); } //End case "Connect" else if (inputString == "Status") //Display Status of Connection { Serial.print("Network Name: "); Serial.println(NetworkName); Serial.print("Network Password: "); Serial.println(NetworkPassword); } //End case Status else if (inputString.startsWith("NetDet:") && inputString.endsWith("|")) { String SSID = ""; String Password = ""; Serial.println("Network Details Received:"); int charnum = 7; //Extract NetworkName while (inputString.charAt(charnum) != '|') { SSID += inputString.charAt(charnum); charnum++; } charnum++; //Extract NetworkPassword while (inputString.charAt(charnum) != '|') { Password += inputString.charAt(charnum); charnum++; } NetworkName = SSID; NetworkPassword = Password; Serial.print("Network Name: "); Serial.println(NetworkName); Serial.print("Network Password: "); Serial.println(NetworkPassword); } else if (inputString == "Done") { Serial.println("Starting Normal Mode..."); Operating_Mode = Normal_Mode; } else { Serial.print("."); } inputString = ""; delay(1000); } break; }//End Setup Mode case Normal_Mode: { Send_Receive_Protocol(); time_test(); //scheduling_information firstschedule; //Serial.println(sizeof(firstschedule)); delay(1000); break; }//End Normal Mode }//End Switch(Operating_Mode) }//End loop() //Subroutines void Send_Receive_Protocol(void) { //Send_Receive_Protocol Variables bool Wait_for_Data = false; bool Data_Received = false; bool Timeout_Expired = false; int no_of_Bytes_Received = 0; int Timeout_Counter = 0; byte *Bytes_of_Data_In = NULL; //Will point to array of bytes in String temp = "nothing"; do { //WiFi Connected? if (WiFi.status() == WL_CONNECTED) {//WiFi Connected? -->YES Statuses[WifiConnected] = true; //Connected to Server? if (client.connected()) {//Connected to Server? -->YES Statuses[ConnectedtoServer] = true; Bytes_of_Data_In = receive_Data_From_Server(no_of_Bytes_Received); if (Bytes_of_Data_In != NULL) { Data_Received = true; } //Data From Server Received? if (Data_Received) {//Data From Server Received? --> YES //Pass to Data_Identification_Protocol int Command_Received = Data_Identification_Protocol(Bytes_of_Data_In, no_of_Bytes_Received); //Received What from Server? switch (Command_Received) { case Send_Data_To_Server: { //Received What from Server? -->Send Serial.println("Received Command to Send Data to Server"); Send_New_Data_to_Server(); //Send some Data to Server Wait_for_Data = false; //No Need to Wait for Data break; }//END Case Send_Data_To_Server case Receive_Data_From_Server: { //Received What from Server? -->Receive Serial.println("Received Command to Receive Data from Server"); Data_Received = false; //No Data Received yet... Timeout_Counter = 0; //Reset Timeout_Counter Wait_for_Data = true; //Need to Wait for Data from Server break; } default: { //Received What from Server? -->No_Command Serial.println("No Command Received From Server"); break; }//END default case }//END Switch (Command_Received) } else {//Data From Server Received? --> NO //Do Nothing, Go to while where continuity Check Carried out } } else {//Connected to Server? -->NO Statuses[ConnectedtoServer] = false; Connect_as_Client(); return; //Continue } } else {//WiFi Connected? -->NO Statuses[WifiConnected] = false; Connect_to_WiFi(); return; //Continue } if ((Wait_for_Data)&&((Timeout_Counter++) == 10)) { Serial.println("Timeout Expired"); Timeout_Expired = true; } else { if (Wait_for_Data) { //Serial.print("Waiting for Data From Server. Timeout = "); //Serial.println(Timeout_Counter); delay(1000); Timeout_Expired = false; } } free(Bytes_of_Data_In); }while((!Data_Received) && (Wait_for_Data) && !Timeout_Expired); } //-Attempt Connection to WiFi void Connect_to_WiFi(void) { int attempt_count = 20; bool network_available = false; WiFi.disconnect(); Serial.println("Attempting Connection to: "); Serial.print(NetworkName); //Check If Desired Network is available, Return if unavailable int n = WiFi.scanNetworks(); if (n == 0) { Serial.println("No Networks Found. Cannot Connect!"); return; } else { for (int i = 0; i < n; ++i) { if (WiFi.SSID(i) == NetworkName) network_available = true; delay(10); } if (!network_available) { Serial.print("Network: "); Serial.print(NetworkName); Serial.print(" not available. Unable to Connect!"); return; } } //If Network Available, Attempt Connection, Return if failed WiFi.begin(NetworkName.c_str(), NetworkPassword.c_str()); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); attempt_count--; if (!attempt_count) { Serial.println("Password Incorrect! WiFi Connection Failed!"); return; } } Serial.println("WiFi Connected!!"); Serial.print("IP Address is:"); Serial.print(WiFi.localIP()); Serial.println(""); return; } //-Attempt Connection to Server void Connect_as_Client(void) { Serial.println("Attempting Connection to Server..."); if (client.connect(Host.c_str(), Port)) { Serial.println("Connection Successful!"); client.println("First Communication!"); } else Serial.println("Connection to Server Not Possible."); } //-Pointer to all bytes received is returned byte* receive_Data_From_Server(int &no_of_bytes_received) { //int Received_New_Data = 0; //No New Data Yet int size = 0; byte *ptr_Bytes_of_Data_In = NULL; while (client.available()) //While there is New Data Retreive it { size++; ptr_Bytes_of_Data_In = (byte*)realloc(ptr_Bytes_of_Data_In, size*sizeof(byte)); //grow array byte data_byte = client.read(); //read a byte ptr_Bytes_of_Data_In[size - 1] = data_byte; //assign to byte array no_of_bytes_received = size; //New Data Has been Retreived } return ptr_Bytes_of_Data_In; } //END receive_Data_From_Server /*-Returns Type of Command if a Command is Received, else Returns No_Command -Passes Data to be Processed to Appropriate Processing Routine*/ int Data_Identification_Protocol(byte *Bytes_of_Data_In, int &no_of_Bytes_Received) { //Data_Identification_Protocol Variables String Data_Start = ""; String Data_ID = ""; String Data_End = ""; int Data_Start_Point = 7; int Data_End_Point; int Num_Bytes_in_Payload; byte *Data_Payload = NULL; //Will point array of byes which is Data_Payload //Print out Data to be Identified: /*Serial.println("Data Identification Protocol Dealing with: "); for (int i = 0; i < no_of_Bytes_Received; i++) { Serial.println(Bytes_of_Data_In[i]); }*/ if (no_of_Bytes_Received > 12) //If Frame is Valid, i.e. meets minimum no. of bytes { //Extract Start of Data field: |D| for (int i = 0; i <= 2; i++) { Data_Start += (char)Bytes_of_Data_In[i]; } if (Data_Start != "|D|") { Serial.println("No Start Data field detected |D|"); return No_Command; } //If |D| was found then Extract End of Data field: |ED| for (int i = 0; i <= (no_of_Bytes_Received - 4); i++) { Data_End = ""; //Empty Data_End Data_End += (char)Bytes_of_Data_In[i]; Data_End += (char)Bytes_of_Data_In[i + 1]; Data_End += (char)Bytes_of_Data_In[i + 2]; Data_End += (char)Bytes_of_Data_In[i + 3]; if (Data_End == "|ED|") { Data_End_Point = i-1; break; } } if (Data_End != "|ED|") { Serial.println("No End Data field detected |ED|"); return No_Command; } //If |ED| was found then Extract End of Data ID: |ID| for (int i = 3; i < Data_Start_Point; i++) { Data_ID += (char)Bytes_of_Data_In[i]; } //Extract Data Payload Num_Bytes_in_Payload = ((Data_End_Point - Data_Start_Point) + 1); if (Num_Bytes_in_Payload) //If Num_Bytes_in_Payload > 0 { Data_Payload = (byte*)realloc(Data_Payload, Num_Bytes_in_Payload*sizeof(byte)); int j = 0; for (int i = Data_Start_Point; i <= Data_End_Point; i++) { Data_Payload[j] = Bytes_of_Data_In[i]; j++; } } } else { Serial.println("Incorrect Frame"); return No_Command; } //Data Stats: Serial.println(""); Serial.println("Received Data Stats:"); Serial.print("Data ID: "); Serial.println(Data_ID); Serial.print("Data Start: "); Serial.println(Data_Start_Point); Serial.print("Data End: "); Serial.println(Data_End_Point); Serial.print("Number of Bytes in Payload: "); Serial.println(Num_Bytes_in_Payload); Serial.println("Data Payload:"); Serial.print("|"); for (int i = 0; i < Num_Bytes_in_Payload; i++) { Serial.print(Data_Payload[i]); Serial.print("|"); } Serial.println("\n"); Serial.println(""); //Send Data_Payload to correct Processing Routing according to |ID| if (Data_ID == "|CM|") //If A Command was Received { Serial.println("Passing to Command Processing Fcn"); //Pass to Command Processing Function int command_processing_result = process_received_command(Data_Payload, Num_Bytes_in_Payload); //Interpret Return value of Command Processing Function switch (command_processing_result) { case No_Command: { return No_Command; break; }//END Case No_Command case Send_Data_To_Server: { return Send_Data_To_Server; break; }//END Case Send_Data_To_Server case Receive_Data_From_Server: { return Receive_Data_From_Server; break; }//END Case Receive_Data_From_Server default: { return Receive_Data_From_Server; } }//END switch (command_received) }//END if (Data_ID == "|CM|") else if (Data_ID == "|SI|") //If Scheduling Information was Received { process_received_schedule(Data_Payload, Num_Bytes_in_Payload); }//END else if (Data_ID == "|SI|") else if (Data_ID == "|TI|") //If Time Information was Received { process_received_time(Data_Payload, Num_Bytes_in_Payload); }//END else if (Data_ID == "|TI|") return No_Command; } //Data Processing Subroutines //Data Receive Processing Subroutines //|CM| Command Processing int process_received_command(byte *Data_Payload, int &Num_Bytes_in_Payload) { String Command = ""; for (int i = 0; i < Num_Bytes_in_Payload; i++) { Command += (char)Data_Payload[i]; } Serial.print("Command to Process is: "); Serial.println(Command); if (Command == "Send") return Send_Data_To_Server; else if (Command == "Receive") return Receive_Data_From_Server; else if (Command == "RunSched") { Serial.println("Server says to Run Schedule"); return No_Command; } else if (Command == "OFF") { Serial.println("Server says to Turn OFF Major Appliance"); return No_Command; } else if (Command == "ON") { Serial.println("Server says to Turn ON Major Appliance"); return No_Command; } else return No_Command; } //|SI| Scheduling Processing void process_received_schedule(byte *Data_Payload, int &Num_Bytes_in_Payload) { Serial.println("Processing a Schedule..."); scheduling_information firstschedule; rebuild_received_data(Data_Payload, Num_Bytes_in_Payload, firstschedule); Serial.println(firstschedule.ID); } //|TI| Time Processing void process_received_time(byte *Data_Payload, int &Num_Bytes_in_Payload) { Serial.println("Processing a Time..."); } //Data Send Processing Subroutines void Send_New_Data_to_Server(void) { bool New_Data_to_Send = false; //Check if there is data to Send and Set New_Data Accordingly if (New_Data_to_Send) { //Send New Data } else { client.println("|D|No_New_Data|ED|"); } } //Setup Routines void RTC_SETUP(void) { Rtc.Begin(); Wire.begin(SDA_pin, SCL_pin); RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__); if (!Rtc.IsDateTimeValid()) { // Common Cuases: // 1) first time you ran and the device wasn't running yet // 2) the battery on the device is low or even missing Serial.println("RTC lost confidence in the DateTime!"); // following line sets the RTC to the date & time this sketch was compiled // it will also reset the valid flag internally unless the Rtc device is // having an issue Rtc.SetDateTime(compiled); } if (!Rtc.GetIsRunning()) { Serial.println("RTC was not actively running, starting now"); Rtc.SetIsRunning(true); } RtcDateTime now = Rtc.GetDateTime(); if (now < compiled) { Serial.println("RTC is older than compile time! (Updating DateTime)"); Rtc.SetDateTime(compiled); } else if (now > compiled) { Serial.println("RTC is newer than compile time. (this is expected)"); } else if (now == compiled) { Serial.println("RTC is the same as compile time! (not expected but all is fine)"); } // never assume the Rtc was last configured by you, so // just clear them to your needed state Rtc.Enable32kHzPin(false); Rtc.SetSquareWavePin(DS3231SquareWavePin_ModeNone); } void time_test(void) { if (!Rtc.IsDateTimeValid()) { // Common Cuases: // 1) the battery on the device is low or even missing and the power line was disconnected Serial.println("RTC lost confidence in the DateTime!"); } RtcDateTime now = Rtc.GetDateTime(); printDateTime(now); RtcTemperature temp = Rtc.GetTemperature(); Serial.print(temp.AsFloat()); Serial.println("C"); } void printDateTime(const RtcDateTime& dt) { char datestring[20]; snprintf_P(datestring, countof(datestring), PSTR("%02u/%02u/%04u %02u:%02u:%02u"), dt.Month(), dt.Day(), dt.Year(), dt.Hour(), dt.Minute(), dt.Second()); Serial.print(datestring); }
a23acbb012617abc2d0b5cbbb013e17fe9d60aec
e35dd506083ad5119d035f517f8487bd0d0090bb
/WI/2008/rownanie.cpp
118d1483e539b696525c686569f901bc9a2de184
[]
no_license
Neverous/xivlo08-11
95088ded4aa7aeebc28da7c22b255446e4a43bda
7daa4f5125aece228fc2f067a455e24ff20eb3f4
refs/heads/master
2016-08-12T15:59:21.258466
2016-03-22T14:41:25
2016-03-22T14:41:25
54,478,420
0
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
rownanie.cpp
#include<cstdio> #include<string> float a,b,c; int main(void) { while(scanf("%f %f %f", &a,&b,&c)!=-1) { b*=b; a *= 4*c; if(b>a) printf("2\n"); else if(b<a) printf("0\n"); else printf("1\n"); } return 0; }
cd48f6b4bba209f1ffb08a923781bbdac971d3f6
2deb33c50107a7efc916d38f12c38c88ac61ef19
/video_capture/video_bridge.h
4c595021d2f970db83b4907781aac3e3f00e1dd5
[]
no_license
SoonyangZhang/webrtc-learn
54c3bf4aa9714fc63a2409893615e8c717883c16
2c8b45480403223fdd65e20133450ccf5b1e1628
refs/heads/master
2020-06-29T09:26:46.151698
2019-12-01T07:36:10
2019-12-01T07:36:10
200,498,699
0
0
null
null
null
null
UTF-8
C++
false
false
1,741
h
video_bridge.h
#pragma once #include "video_header.h" #include <list> #include <iostream> namespace zsy{ class VideoCaptureCallback: public rtc::VideoSinkInterface<webrtc::VideoFrame> { public: bool AddSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink){ bool success=false; bool exist=false; for(auto it=sinks_.begin();it!=sinks_.end();it++){ if((*it)==sink){ exist=true; break; } } if(!exist){ sinks_.push_back(sink); success=true; } return success; } bool RemoveSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink){ bool success=false; for(auto it=sinks_.begin();it!=sinks_.end();){ if((*it)==sink){ it=sinks_.erase(it); success=true; break; }else{ it++; } } return success; } void OnFrame(const webrtc::VideoFrame& videoFrame) override { int height = videoFrame.height(); int width = videoFrame.width(); uint32_t size=videoFrame.size(); uint64_t now_ms=rtc::Time(); uint64_t record_ms=0; if(last_time_==0){ record_ms=0; }else { record_ms=now_ms-last_time_; } //std::cout<<frame_num_<<" "<<record_ms<<" "<<size<<" "<<height<<" "<<width<<std::endl; last_time_=now_ms; frame_num_++; for(auto it=sinks_.begin();it!=sinks_.end();it++){ (*it)->OnFrame(videoFrame); } } private: int frame_num_{0}; uint64_t last_time_{0}; std::list<rtc::VideoSinkInterface<webrtc::VideoFrame>*> sinks_; }; }
016d9406ac58a76e847d90b2488438f8d23993a4
d84852c821600c3836952b78108df724f90e1096
/exams/2559/02204111/1/midterm/3_2_712_5920500841.cpp
e331969b360fc7acef36cea367776ff5689a7327
[ "MIT" ]
permissive
btcup/sb-admin
4a16b380bbccd03f51f6cc5751f33acda2a36b43
c2c71dce1cd683f8eff8e3c557f9b5c9cc5e168f
refs/heads/master
2020-03-08T05:17:16.343572
2018-05-07T17:21:22
2018-05-07T17:21:22
127,944,367
0
1
null
null
null
null
UTF-8
C++
false
false
954
cpp
3_2_712_5920500841.cpp
//5920500841 wuttipon butchum #include<iostream> #include<cmath> using namespace std; int main() { float a,b,c,x1,x2,x3; cout<<"Enter coeffcients a, b andc : ";cin>>a>>b>>c; cout<<endl; cout<<"Root are real and different."<<endl; if(pow(b,2)-4*a*c>0) { cout<<"X1 = "<<x1<<endl; cout<<"X2 = "<<x2<<endl; x1= (-b+(sqrt((pow(b,2)-4*a*c))/2*a)); x2=(-b-(sqrt((pow(b,2)-4*a*c))/2*a)); } else if (pow(b,2)-4*a*c==0) { cout<<"X1=X2 = "<<x3<<endl; x3= b+(sqrt((pow(b,2)-4*a*c)))/2*a; } else if(pow(b,2)-4*a*c<0) { cout<<"X1 = "<<x1<<"i"<<endl; cout<<"X2 = "<<x2<<"i"<<endl; x1= ((-b/2*a)+(sqrt(-(pow(b,2)-4*a*c)))/2*a); x2= ((-b/2*a)-(sqrt(-(pow(b,2)-4*a*c)))/2*a); } system("pause"); return 0; }
7381ac3f6c6430a6d809a11c8ba021f91024e502
6e93a043f3cd198cfa37470f06396d8709d98090
/c-plus-plus-fundamentals/module_07/ClassesAndObjects/ClassesAndObjects/Person.h
e52f318b9693d0484f2a8a2a60182b90fc41a539
[ "Apache-2.0" ]
permissive
codearchive/c-plus-plus-path
cc1980b2cf74786fbd07d58c3acd3c53969e2ad7
529283ffc450b73eca53c02b6523819e446fe3ca
refs/heads/master
2020-07-27T05:33:37.482531
2019-09-21T20:49:24
2019-09-21T20:49:24
208,887,060
0
0
null
null
null
null
UTF-8
C++
false
false
373
h
Person.h
#pragma once #include <string> class Person { private: std::string first_name_; std::string last_name_; int arbitrary_number_; public: Person(std::string first, std::string last, int arbitrary); Person(); ~Person(); std::string get_name() const; int get_number() const { return arbitrary_number_; } void set_number(int number) { arbitrary_number_ = number; } };
666d1ffa2fe5a59e4475772493621d8186f3f507
e75c8e1fbffb8d62ab5c7ea22317a8c561385956
/112.h
9679aec7c720d06da72ab7be89f2bc631a2933d0
[]
no_license
fltflt/LeetCode-Solution
aa5a4e5b445e04400d10200d67af5afaee5d5da6
102569885d5d3793fefa1d0f10ebb031707aa1f0
refs/heads/master
2020-09-11T03:43:00.860909
2020-06-19T01:53:08
2020-06-19T01:53:08
221,926,755
0
0
null
null
null
null
GB18030
C++
false
false
1,494
h
112.h
#pragma once #include <iostream> using namespace std; #include <vector> class ListNode { public: int val; ListNode *next; }; class Solution { public: ListNode *vector2lianbiao(vector<int> nums) { ListNode *head, *p,*rear; head = rear = new class ListNode; head->val = nums[0]; rear->next = NULL; for (int i = 1; i < nums.size(); i++) { p = new class ListNode; p->val = nums[i]; rear->next = p; rear = p; } rear->next = NULL; return head; }; //删除重复链表元素 ListNode * deleteDuplicates(ListNode * head) { // write your code here ListNode *p = head; while (p->next != NULL) { if (p->next->val == p->val) { p->next =p->next->next; } else { p = p->next; } } return head; } void print_lianbiao(ListNode *head) { ListNode *p= head; while (p != NULL) { cout << p->val; cout << endl; p = p->next; } cout << endl; }; }; //主函数 //#include "pch.h" //#include <iostream> //using namespace std; // //#include "112.h" //#include <vector> // //class Solution; //Solution function; //int main() //{ // ListNode *result, *result_after; // vector<int> nums = { 1, 2, 2, 3,3, 4 }; // result = function.vector2lianbiao(nums); // cout << "原链表的内容如下:" << endl; // function.print_lianbiao(result); // result_after = function.deleteDuplicates(result); // cout << "删除重复元素后的链表的内容如下:" << endl; // function.print_lianbiao(result_after); // //}
afacb0e097d0de621b608bea17b79c005082fed2
2464c0320c1d9ddaa0a9727a914e1887f9265134
/Data_Structures/Project_3/Graph.hpp
b2947fbd4071c26f6712b1d90072830823a37beb
[]
no_license
josephmoreno/Coursework
7866abbe766fa418193e5869aa334669384e92ad
21ce075c85ad96838a6c7601adb8c3bce52a65d1
refs/heads/master
2022-10-29T07:08:18.576187
2020-10-08T17:31:13
2020-10-08T17:31:13
236,175,028
0
0
null
2022-06-22T16:39:09
2020-01-25T13:40:21
VHDL
UTF-8
C++
false
false
1,831
hpp
Graph.hpp
#include <iostream> #include <algorithm> #include <map> #include "GraphBase.hpp" class Vertex { private: std::string vLabel = "\0"; std::vector<Vertex*> adjacencies; public: // Constructor Vertex() {} Vertex(std::string l) { vLabel = l; } // Getters std::string getLabel() { return vLabel; } std::vector<Vertex*> getAdjacencies() { return adjacencies; } // Used to add and remove an adjacent vertex. void addAdjacent(Vertex *v); void removeAdjacent(std::string l); }; class Edge { private: Vertex *v1; Vertex *v2; unsigned long eWeight; public: // Constructor Edge() : v1(nullptr), v2(nullptr), eWeight(0) {} Edge(Vertex *V1, Vertex *V2, unsigned long edgeWeight) : v1(V1), v2(V2), eWeight(edgeWeight) {} // Getters Vertex *getV1() { return v1; } Vertex *getV2() { return v2; } unsigned long getWeight() { return eWeight; } }; // Used in shortestPath(...) struct leastPathValues { leastPathValues() : prev(""), least(999999999) {} std::string prev; unsigned long least; }; class Graph : public GraphBase { private: std::vector<Vertex*> vertices; std::vector<Edge*> edges; public: // Constructor and destructor. Graph() {} ~Graph(); // Viewing the vertices and edges. void printVertices(); void printEdges(); // Used in shortestPath function. //unsigned long dijkstraAlg(Vertex *current, Vertex *end, std::vector<std::string> &p, std::map<std::string, leastPathValues *> &d); //Edge *findEdge(std::string l1, std::string l2); // Virtual functions from GraphBase.hpp void addVertex(std::string label); void removeVertex(std::string label); void addEdge(std::string label1, std::string label2, unsigned long weight); void removeEdge(std::string label1, std::string label2); unsigned long shortestPath(std::string startLabel, std::string endLabel, std::vector<std::string> &path); };
ed360d5f5e224dcc31304c71e58b144bad00b1d0
5af277b5819d74e61374d1d78c303ac93c831cf5
/automl_zero/memory.h
0858bbaa657d81492f8e352527e329676cc98939
[ "Apache-2.0" ]
permissive
Ayoob7/google-research
a2d215afb31513bd59bc989e09f54667fe45704e
727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7
refs/heads/master
2022-11-11T03:10:53.216693
2020-06-26T17:13:45
2020-06-26T17:13:45
275,205,856
2
0
Apache-2.0
2020-06-26T16:58:19
2020-06-26T16:58:18
null
UTF-8
C++
false
false
1,978
h
memory.h
// Copyright 2020 The Google Research 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. #ifndef MEMORY_H_ #define MEMORY_H_ #include <array> #include "definitions.h" #include "absl/flags/flag.h" namespace automl_zero { // Instantiate only once per worker. Then use Wipe() to wipe clean. Unit tests // may create multiple ones. template<FeatureIndexT F> class Memory { public: // Does NOT serve as a way to initialize the Memory. Memory(); Memory(const Memory&) = delete; Memory& operator=(const Memory&) = delete; // Sets the Scalars, Vectors and Matrices to zero. Serves as a way to // initialize the memory. void Wipe(); // Three typed-memory spaces. ::std::array<Scalar, kMaxScalarAddresses> scalar_; ::std::array<Vector<F>, kMaxVectorAddresses> vector_; ::std::array<Matrix<F>, kMaxMatrixAddresses> matrix_; }; // Does NOT serve as a way to initialize the Memory. // Simply ensures that the potentially dynamic Vector and Matrix objects have // definite shape. template<FeatureIndexT F> Memory<F>::Memory() { for (Vector<F>& value : vector_) { value.resize(F, 1); } for (Matrix<F>& value : matrix_) { value.resize(F, F); } } template<FeatureIndexT F> void Memory<F>::Wipe() { for (Scalar& value : scalar_) { value = 0.0; } for (Vector<F>& value : vector_) { value.setZero(); } for (Matrix<F>& value : matrix_) { value.setZero(); } } } // namespace automl_zero #endif // MEMORY_H_
c89c630e459808112341f8fe78c65fc42184a982
3d74f759ee48d383aa82eeff0a55864a93a001ba
/third_party/tonic/dart_list.h
57c5347a8e2540227a05e3c0f5053ba13e15bfb9
[ "BSD-3-Clause" ]
permissive
flutter/engine
78be5418a9b2f7730dda9ca9fcb25b7055f3da85
902ece7f89d7730cc69f35e098b223cbbf4e25f1
refs/heads/main
2023-09-04T06:12:34.462953
2023-09-04T05:33:32
2023-09-04T05:33:32
39,211,337
7,090
6,862
BSD-3-Clause
2023-09-14T21:58:17
2015-07-16T17:39:56
C++
UTF-8
C++
false
false
1,398
h
dart_list.h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_TONIC_DART_LIST_H_ #define LIB_TONIC_DART_LIST_H_ #include <cstddef> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/converter/dart_converter.h" namespace tonic { class DartList { public: DartList(DartList&& other); void Set(size_t index, Dart_Handle value); Dart_Handle Get(size_t index); template <class T> void Set(size_t index, T value) { Set(index, DartConverter<T>::ToDart(value)); } template <class T> T Get(size_t index) { return DartConverter<T>::FromDart(Get(index)); } Dart_Handle dart_handle() const { return dart_handle_; } size_t size() const { return size_; } bool is_valid() const { return is_valid_; } explicit operator bool() const { return is_valid_; } private: explicit DartList(Dart_Handle list); friend struct DartConverter<DartList>; DartList(); Dart_Handle dart_handle_; size_t size_; bool is_valid_; DartList(const DartList& other) = delete; }; template <> struct DartConverter<DartList> { static DartList FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception); }; } // namespace tonic #endif // LIB_TONIC_DART_LIST_H_
ef080c7162e85549743ad5be89519f9f7e19f277
27a0bed279d4525d42d65d8c11c4416a07f532c1
/TextAdventureEngine/TextAdventureEngine/Codebase/NeuroEngine/Framework/UI/Views/ViewColour.cpp
c7ea02e9467b3911bd307c19921287fdcdcc9f47
[]
no_license
Neuroticcheeze/TAE
2b623b16c798a017b4045696425b5819f00d4a2b
dd032c1e5ca2409c62c2e3843e9b302a1127c4af
refs/heads/master
2020-03-15T19:26:23.556598
2018-12-27T11:35:21
2018-12-27T11:35:21
132,308,665
0
0
null
null
null
null
UTF-8
C++
false
false
1,622
cpp
ViewColour.cpp
#include "ViewColour.hpp" #include <Framework/Input/InputManager.hpp> #include <Framework/Graphics/GraphicsManager.hpp> //===================================================================================== ViewColour::ViewColour( const char * a_Name, Page * a_ContainerPage, View * a_Parent ) : View( a_Name, a_ContainerPage, a_Parent ) { SetEnabled(); SetIsInteractible( true ); } //===================================================================================== void ViewColour::OnTick( float a_DeltaTime ) { GraphicsManager::Instance().SetColour( Colour( 1.0F, 0.0F, 0.0F ), GraphicsManager::COL_PRIMARY ); GraphicsManager::Instance().SetColour( Colour( 0.0F, 1.0F, 0.0F ), GraphicsManager::COL_SECONDARY ); GraphicsManager::Instance().SetColour( Colour( 0.0F, 0.0F, 1.0F ), GraphicsManager::COL_TERTIARY ); GraphicsManager::Instance().TfPush(); GraphicsManager::Instance().TfTranslate( GetPosition() ); GraphicsManager::Instance().TfScale( GetSize() ); GraphicsManager::Instance().GfxDrawTriangle( Vector2::ZERO, Vector2::UP, Vector2::ONE ); GraphicsManager::Instance().TfPop(); } //===================================================================================== void ViewColour::OnMouseEnter( const Vector2 & m_MousePosition ) { } //===================================================================================== void ViewColour::OnMouseLeave( const Vector2 & a_MousePosition ) { } //===================================================================================== void ViewColour::OnMouseClick( const Vector2 & a_MousePosition, InputManager::MouseButton a_MouseButton ) { }
b4c7821d7365cf064c9f5b7f604367d5e3349b3d
c0282037ad9255c5519ebd88b17b141b22efca08
/src/MPC.cpp
3fe870d8fb4cda1cbeb6b9079f925e1e1356a158
[ "MIT" ]
permissive
colinmccormick/CarND-MPC-Project
f093d183fc6121c825936c9bff0bcab69a8cc154
809fcba7fc9b469f07d210828d27f258ef272159
refs/heads/master
2020-04-01T03:07:01.886151
2018-10-13T23:59:43
2018-10-13T23:59:43
152,810,065
0
0
null
null
null
null
UTF-8
C++
false
false
7,596
cpp
MPC.cpp
#include "MPC.h" #include <cppad/cppad.hpp> #include <cppad/ipopt/solve.hpp> #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" using CppAD::AD; // TODO: Set N and dt size_t N = 10; double dt = 0.1; // This is the length from front to CoG that has a similar radius. const double Lf = 2.67; // Set some reference values const double ref_v = 85; const double ref_cte = 0; const double ref_epsi = 0; // Set some convenient indices size_t x_start = 0; size_t y_start = x_start + N; size_t psi_start = y_start + N; size_t v_start = psi_start + N; size_t cte_start = v_start + N; size_t epsi_start = cte_start + N; size_t delta_start = epsi_start + N; size_t a_start = delta_start + N - 1; class FG_eval { public: // Fitted polynomial coefficients Eigen::VectorXd coeffs; FG_eval(Eigen::VectorXd coeffs) { this->coeffs = coeffs; } typedef CPPAD_TESTVECTOR(AD<double>) ADvector; void operator()(ADvector& fg, const ADvector& vars) { // fg[0] is the cost; initialize at 0 fg[0] = 0; // ************************************* // Add up costs // ************************************* // Add cost from state variables for (int t = 0; t < N; t++) { fg[0] += 2500.0 * CppAD::pow(vars[cte_start + t] - ref_cte, 2); fg[0] += 2500.0 * CppAD::pow(vars[epsi_start + t] - ref_epsi, 2); fg[0] += 1.0 * CppAD::pow(vars[v_start + t] - ref_v, 2); } // Add cost from actuators for (int t = 0; t < N - 1; t++) { fg[0] += 10.0 * CppAD::pow(vars[delta_start + t], 2); fg[0] += 10.0 * CppAD::pow(vars[a_start + t], 2); } // Add cost from actuator changes for (int t = 0; t < N - 2; t++) { fg[0] += 1000.0 * CppAD::pow(vars[delta_start + t + 1] - vars[delta_start + t], 2); fg[0] += 100.0 * CppAD::pow(vars[a_start + t + 1] - vars[a_start + t], 2); } // ************************************* // Calculate constraints // ************************************* fg[1 + x_start] = vars[x_start]; fg[1 + y_start] = vars[y_start]; fg[1 + psi_start] = vars[psi_start]; fg[1 + v_start] = vars[v_start]; fg[1 + cte_start] = vars[cte_start]; fg[1 + epsi_start] = vars[epsi_start]; // The rest of the constraints for (int t = 1; t < N; t++) { // state variables at previous timestep AD<double> x0 = vars[x_start + t - 1]; AD<double> y0 = vars[y_start + t - 1]; AD<double> psi0 = vars[psi_start + t - 1]; AD<double> v0 = vars[v_start + t - 1]; AD<double> cte0 = vars[cte_start + t - 1]; AD<double> epsi0 = vars[epsi_start + t - 1]; // state variables at current timestep AD<double> x1 = vars[x_start + t]; AD<double> y1 = vars[y_start + t]; AD<double> psi1 = vars[psi_start + t]; AD<double> v1 = vars[v_start + t]; AD<double> cte1 = vars[cte_start + t]; AD<double> epsi1 = vars[epsi_start + t]; // actuator values at last timestep AD<double> delta0 = vars[delta_start + t - 1]; AD<double> a0 = vars[a_start + t - 1]; AD<double> x02 = x0 * x0; AD<double> lane1 = coeffs[0] + coeffs[1]*x0 + coeffs[2]*x02 + coeffs[3]*x02*x0; AD<double> psides1 = CppAD::atan(coeffs[1] + 2*coeffs[2]*x0 + 3*coeffs[3]*x02); // calculate constraints // difference between t+1 value and model prediction from t value AD<double> vdt = v0 * dt; AD<double> dLf = delta0 / Lf; fg[1 + x_start + t] = x1 - (x0 + CppAD::cos(psi0) * vdt); fg[1 + y_start + t] = y1 - (y0 + CppAD::sin(psi0) * vdt); fg[1 + psi_start + t] = psi1 - (psi0 + dLf * vdt); fg[1 + v_start + t] = v1 - (v0 + a0 * dt); fg[1 + cte_start + t] = cte1 - ( lane1 - (y0 - CppAD::sin(epsi0) * vdt )); fg[1 + epsi_start + t] = epsi1 - ( (psi0 + dLf * vdt) - psides1 ); } } }; // // MPC class definition // MPC::MPC() {} MPC::~MPC() {} vector<double> MPC::Solve(Eigen::VectorXd x0, Eigen::VectorXd coeffs) { typedef CPPAD_TESTVECTOR(double) Dvector; // ************************************* // Set number of variables and constraints // ************************************* size_t n_vars = N * 6 + (N - 1) * 2; size_t n_constraints = N * 6; double x = x0[0]; double y = x0[1]; double psi = x0[2]; double v = x0[3]; double cte = x0[4]; double epsi = x0[5]; // ************************************* // Set upper and lower bounds // ************************************* Dvector vars(n_vars); for (int i = 0; i < n_vars; i++) { vars[i] = 0.0; } vars[x_start] = x; vars[y_start] = y; vars[psi_start] = psi; vars[v_start] = v; vars[cte_start] = cte; vars[epsi_start] = epsi; // Lower and upper limits for x Dvector vars_lowerbound(n_vars); Dvector vars_upperbound(n_vars); // Set all non-actuator values to max and min number for (int i = 0; i < delta_start; i++) { vars_lowerbound[i] = -1.0e19; vars_upperbound[i] = 1.0e19; } // Set steering angle bounds (+/-25 degrees in radians) for (int i = delta_start; i < a_start; i++) { vars_lowerbound[i] = -0.436332 * Lf; vars_upperbound[i] = 0.436332 * Lf; } // Set acceleration max/min for (int i = a_start; i < n_vars; i++) { vars_lowerbound[i] = -1.0; vars_upperbound[i] = 1.0; } // Lower and upper limits for constraints Dvector constraints_lowerbound(n_constraints); Dvector constraints_upperbound(n_constraints); for (int i = 0; i < n_constraints; i++) { constraints_lowerbound[i] = 0; constraints_upperbound[i] = 0; } constraints_lowerbound[x_start] = x; constraints_lowerbound[y_start] = y; constraints_lowerbound[psi_start] = psi; constraints_lowerbound[v_start] = v; constraints_lowerbound[cte_start] = cte; constraints_lowerbound[epsi_start] = epsi; constraints_upperbound[x_start] = x; constraints_upperbound[y_start] = y; constraints_upperbound[psi_start] = psi; constraints_upperbound[v_start] = v; constraints_upperbound[cte_start] = cte; constraints_upperbound[epsi_start] = epsi; // ************************************* // Create object that computes objective and constraints // ************************************* FG_eval fg_eval(coeffs); // options std::string options; options += "Integer print_level 0\n"; options += "Sparse true forward\n"; options += "Sparse true reverse\n"; options += "Numeric max_cpu_time 0.5\n"; // place to return solution CppAD::ipopt::solve_result<Dvector> solution; // ************************************* // Solve! // ************************************* // solve the problem CppAD::ipopt::solve<Dvector, FG_eval>( options, vars, vars_lowerbound, vars_upperbound, constraints_lowerbound, constraints_upperbound, fg_eval, solution); // Check some of the solution values bool ok = true; ok &= solution.status == CppAD::ipopt::solve_result<Dvector>::success; // Print out the cost auto cost = solution.obj_value; std::cout << "Cost " << cost << std::endl; // ************************************* // Assemble the result vector and return // ************************************* vector<double> result; result.push_back(solution.x[delta_start]); result.push_back(solution.x[a_start]); for (int i=0; i < N-1; i++) { result.push_back(solution.x[x_start + i + 1]); result.push_back(solution.x[y_start + i + 1]); } return result; }
56344bd7041bf1fb9ca719392c6615dfd5b3e40f
3ea34c23f90326359c3c64281680a7ee237ff0f2
/Data/3506/E
01c04a87b5f5bcab4d6baa88c6ecc574d42c4e3a
[]
no_license
lcnbr/EM
c6b90c02ba08422809e94882917c87ae81b501a2
aec19cb6e07e6659786e92db0ccbe4f3d0b6c317
refs/heads/master
2023-04-28T20:25:40.955518
2020-02-16T23:14:07
2020-02-16T23:14:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
80,889
E
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | foam-extend: Open Source CFD | | \\ / O peration | Version: 4.0 | | \\ / A nd | Web: http://www.foam-extend.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "Data/3506"; object E; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 4096 ( (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-188760.567599003,100218.998588928,88541.5690100739) (-199721.892835062,96134.9753673595,192128.486477775) (-225083.72175628,87548.8549509483,329663.353283103) (-272862.218918269,74052.9100113413,528472.662190042) (-358923.212425143,55809.6327092357,831586.241905948) (-513259.593836549,34801.4858341802,1310044.34990832) (-792669.812075748,15645.2280043955,2087068.93397969) (-1297625.64248147,3908.87700981,3380785.69945136) (-2140248.19620726,-9.8710797309593,5521043.76673831) (-2982048.82321496,-333.19815638795,8503425.78810975) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-199744.540029957,215569.959769526,84393.5788493574) (-210790.261945271,207830.109193172,183488.706968818) (-236510.060346136,191469.865133913,316077.757131987) (-285397.015454292,165375.970949702,510151.711647917) (-373834.395147828,129297.237079108,810498.50242587) (-531910.247558914,86342.3367122776,1290867.89910668) (-814415.067370204,45583.4216742308,2075344.77280704) (-1317451.10586038,19783.2143708424,3376921.54130634) (-2153476.34637005,9646.33437683069,5520741.68221989) (-2988248.34343454,4925.96593863374,8503730.8615593) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-224760.150700759,363767.853766301,76562.256703984) (-236013.822203038,353343.709177839,167062.478922358) (-262533.870088038,331181.87964272,289884.334501594) (-313842.529591182,295162.521954477,473940.313088001) (-407895.752417133,243725.864836527,767407.437747703) (-575770.258332857,179406.992842972,1250113.03994987) (-868004.380093671,114147.017376529,2049553.82434125) (-1366816.95007512,69334.3619617197,3366819.62682544) (-2185272.94191138,45702.8101677993,5516036.09294591) (-3002653.14577043,24791.8393716487,8498823.36528336) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-271374.923597765,569068.894767229,66073.8825968374) (-282815.591724968,557444.930624441,144788.252875205) (-310316.244614449,532608.949362765,253677.427769601) (-365109.167850176,491674.381760993,422274.735813252) (-468451.814172151,431606.574327324,702845.840494619) (-655133.362654738,352613.96704947,1184772.22894285) (-970575.71955257,264807.917442364,2004687.04842958) (-1462245.76997185,193122.012871266,3343145.16749186) (-2243501.3851541,137269.041797534,5495080.32101615) (-3028055.10053026,73890.94946689,8474036.31145138) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-354874.084888004,869524.914938126,54418.0647171001) (-366210.395608516,858214.285695358,119859.105254697) (-394199.064735555,834075.895114426,212591.224238591) (-451928.9010041,794150.988884194,362043.51811949) (-564893.438866403,734917.954232145,623625.577081071) (-774872.082526704,654334.030620949,1096777.59603628) (-1126787.34632887,555548.016064843,1932824.84374267) (-1607471.1105855,446287.160925757,3287130.80627371) (-2328036.75125629,320867.415004914,5431569.18432273) (-3064733.23046449,170097.278316689,8400096.08593743) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-505447.432271298,1331905.31691292,43067.030296516) (-516177.102986062,1321813.70467703,95644.714300903) (-543212.496328477,1300308.24107417,172624.86466964) (-600355.632814142,1264395.79106034,302735.695307629) (-714506.970588126,1209239.28454258,542921.335585335) (-928468.452594223,1127884.29501733,997839.523783185) (-1281433.19147564,1011418.02951822,1823402.70180544) (-1740287.67287781,848459.65541313,3161517.8801959) (-2419583.2825902,621327.361769417,5280641.21602164) (-3110860.654247,331697.404071304,8229901.74451399) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-781714.34460996,2080654.34148262,32965.320040251) (-791217.323331281,2071941.34258473,74055.0054638361) (-815488.200788233,2053218.38999136,136633.057334877) (-867682.433333664,2021162.87560957,247548.406119303) (-973690.248080904,1968915.14929433,461562.789448451) (-1174703.66303333,1882913.03402752,881237.713471607) (-1505947.23531419,1738340.9305002,1660262.04780384) (-1923182.55325502,1497758.07162357,2934146.18484842) (-2556069.0427958,1120705.65194084,4990836.93747275) (-3186144.39693114,610633.542751802,7898045.19572348) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1286947.71234648,3343386.90176062,24215.1520684606) (-1294575.34033721,3335509.13553111,55222.6994592924) (-1314157.58510425,3318121.89715227,104476.777402657) (-1356598.33366665,3286945.67629863,195292.31038024) (-1443695.72431913,3232255.85890522,375647.325088476) (-1610763.63317466,3132682.56552216,736641.42676848) (-1888151.86573609,2943569.79407945,1419564.42892527) (-2225941.74811734,2586365.27698662,2556898.97167958) (-2803937.36174236,2000961.3029548,4480580.68240798) (-3330167.04680024,1134195.28948182,7287185.98247816) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-2132991.75478771,5460097.88380751,16280.7727408183) (-2138190.87918918,5452253.68736426,37727.1000968469) (-2151518.07665357,5434183.13091011,73183.942992526) (-2180070.63814068,5399639.78855786,140560.468873948) (-2237595.85203959,5334241.94525818,276170.234560592) (-2345685.44646913,5206988.86224824,547549.384303655) (-2527253.76836685,4956018.01885218,1062354.92789778) (-2797078.49681053,4474336.84705728,1971461.85463768) (-3261152.42074852,3619805.14655164,3613770.43178925) (-3581384.56739751,2176458.38947856,6152891.89919003) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-2978746.28863443,8430555.51838963,8288.65405230034) (-2981331.96734825,8422424.55890092,19449.7498638697) (-2987967.18214606,8403178.63503843,38421.42788162) (-3002006.60500374,8365034.48509923,75033.3363440493) (-3029843.95342973,8290190.03878669,148929.196245278) (-3081886.22345506,8141247.17691224,296557.105036281) (-3172727.88306878,7844627.14929643,580675.85766079) (-3325873.43591984,7263920.81353583,1116965.32710206) (-3580534.4413895,6146896.0602209,2170408.85482223) (-3605984.2850535,3976469.18231705,3976382.3470373) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (27967191.6956995,89349.1714277663,77685.5033339089) (27948837.9105163,85143.2165338839,166969.421508997) (27906700.1598869,76134.0306572134,282038.447268714) (27828142.9992721,61516.6276601879,442503.539478277) (27688439.3961398,40888.6245168507,677239.244456622) (27440219.8409305,16172.8986367688,1030573.84911289) (26984917.4811424,-6070.85942255414,1582044.35337735) (26085158.67869,-15893.2716323599,2538140.24189839) (24054898.3994351,-13181.2340532748,4679161.81836956) (18541304.6481696,-6453.12526323964,11485248.4103085) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (27948501.1667848,190678.081743839,73412.3209293516) (27930143.5886837,182716.426441776,157892.198452766) (27887669.7881756,165524.247727131,267309.070921361) (27807636.8655004,136996.784408453,421781.971278659) (27664118.4941988,95272.857183105,652431.787325985) (27408874.8025418,42499.7658382863,1008306.80808399) (26946576.5797777,-7990.07526314934,1572221.31483697) (26050570.9433132,-29553.2155399348,2540846.14763112) (24033395.265636,-22106.774831189,4685887.0144631) (18531869.6690289,-9433.37975133749,11491736.1945478) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (27906215.9953426,317307.255849131,65381.6179114234) (27887779.5553573,306670.18778106,140621.417071938) (27844500.5744295,283464.147062708,238634.011279122) (27761006.9111821,243891.284795275,379877.00817935) (27607597.9010172,183134.82334318,599508.326645157) (27331424.8380242,99978.228092099,957821.706094555) (26842626.3167646,11521.243818164,1550666.62821517) (25955127.234239,-26113.4480362166,2548269.61445758) (23977875.7471057,-12517.7923789876,4698518.88104837) (18508823.303353,-596.001292256815,11501191.9915261) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (27828479.8659679,485757.329668684,54682.0746748892) (27810073.5344261,474157.487080258,117292.58728483) (27765822.1888068,448735.653677978,198869.58530849) (27676954.6375399,404795.779987837,318888.222786066) (27505301.9788217,335128.32273118,516127.868464467) (27181849.7524121,232827.010946865,869282.908603052) (26611711.0701768,108522.641013366,1512981.65973877) (25738006.4184618,47803.6952375482,2561799.26609172) (23865760.5418546,52651.7859874436,4710354.69877666) (18465752.9837936,37177.1704640766,11501760.3807569) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (27691745.8114709,719086.735265378,43037.6361045819) (27673847.2068971,708327.03181417,91797.4269251571) (27629458.7144196,685036.545355296,154825.694152989) (27535982.6008916,645644.751216741,249052.159088512) (27343403.9548927,585250.039862697,413619.986258226) (26949066.1921326,500687.147025413,744808.513580658) (26196610.3410676,400818.840790036,1452101.56446775) (25335576.5980822,313363.876816464,2566480.61228143) (23690156.9271762,229212.074923653,4694713.5829728) (18401761.8754162,123909.367992971,11464473.2176233) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (27448699.0692976,1055675.85633855,32251.3154180023) (27432075.4729702,1046814.93772834,68497.7716077514) (27389845.9564963,1028031.67631893,115431.12587956) (27298112.1076262,997042.160860085,188552.913856207) (27103321.613173,950027.536159427,328933.771858483) (26697739.9414636,881603.929429242,644795.533456998) (25935860.2150525,786836.595383858,1364471.31039537) (25112912.9469459,665487.045710241,2482134.4597381) (23540773.351899,484753.979290621,4589222.85894219) (18328486.5906596,256357.618338462,11340414.3017501) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (26998109.3187237,1575446.24807667,23392.8829884296) (26983634.5630847,1568641.07888673,49701.7934742944) (26946213.6733163,1554618.50159984,84400.0321491152) (26862978.4993675,1532282.27680959,141485.921558609) (26681392.6371807,1498911.79224477,260505.71827185) (26293617.8491823,1446818.10851375,549956.965031873) (25554780.742438,1356070.88614954,1242981.6345741) (24812129.0905586,1194932.62509401,2301211.34943698) (23319455.5260525,872773.546488814,4360654.15145051) (18203381.3042689,466578.498854629,11083894.5077946) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (26097541.7602832,2497364.59642913,16579.1170781303) (26086102.4280586,2491898.98527829,35630.3803509248) (26056277.4374435,2480777.00227721,62023.7951860678) (25989069.5357879,2463473.56832333,108151.572277908) (25839486.4051838,2438332.2948371,208535.878242702) (25510614.19214,2397718.71038651,459244.389115612) (24864017.7551672,2304381.28060614,1081751.31181594) (24379707.2116764,2015144.16228411,1978877.75289214) (22872753.6100216,1543675.58996449,3954271.6757127) (17913640.9594424,882932.489381608,10617096.6170033) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (24062036.8843281,4614263.83695547,11059.0584180481) (24054348.3975733,4608990.72920306,24414.9757910709) (24034415.8779634,4597589.39445192,44655.567059576) (23990454.1926243,4577560.06186427,83031.1808138274) (23896855.2609938,4541841.95067629,168057.350001411) (23706470.2499051,4470625.05251163,365982.249562368) (23363246.6494882,4310327.70262767,792522.347746038) (22880926.4442047,3945310.68193371,1507337.82514146) (21519217.4675043,3300216.41107499,3293414.05383835) (17032224.0469649,2151737.91479238,9733986.95212539) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (18543844.0249603,11408978.3142801,5682.14714073654) (18540043.897191,11403434.1474981,12849.8023665842) (18530258.7675329,11390784.1911986,24415.9940011116) (18509127.6081883,11366649.9092645,47178.8714691879) (18465639.3207433,11319658.4340272,96866.0520055486) (18380117.4753573,11222775.7358382,205698.60792689) (18221723.0376451,11017038.5670426,427523.760858345) (17918207.2321433,10589484.7099129,862256.002876375) (17032914.7744494,9727138.1401259,2144871.99604682) (13849242.3393214,7582228.09912041,7582142.12540411) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-486050.204231101,70817.8899723884,59437.0718980347) (-506317.802382207,66542.8842776964,125062.962458508) (-552044.523910024,57117.1815775781,203703.526617747) (-635123.720323939,41003.4119816176,302979.896172042) (-777108.623538765,16537.1462754092,429003.831515067) (-1013748.02723389,-15161.1061180238,575145.86773739) (-1400661.83767136,-44386.6710050751,682124.919496138) (-2012973.19619438,-50457.1041626599,507726.960483026) (-2890913.62059261,-34645.1597869411,-834802.797762557) (-3543789.37455387,-15827.6447313945,-7056868.06836784) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-507412.363936351,148602.761197231,55141.7214361255) (-527308.646363453,140539.211788495,115610.6909122) (-572549.148648203,122480.864719041,187479.006534292) (-655719.239178521,90444.2190019501,278407.366132628) (-799863.647672906,38740.6489136233,397199.067305927) (-1042976.67239685,-34989.7022970979,545892.200363418) (-1438984.99435216,-111958.485002064,676038.65042999) (-2045354.29101617,-124973.524667712,523493.367204226) (-2907175.18538235,-77575.2711359562,-815993.008488499) (-3549561.58630475,-32419.9436907313,-7040956.39225562) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-555092.524402242,239865.790260175,47058.5526218253) (-574326.328603108,229212.722047254,97503.9882633345) (-618715.922827838,204929.890252612,155284.521926799) (-702650.834282401,159871.947580255,226527.600752674) (-854211.101739292,80766.1902777606,323324.124084805) (-1122402.00431463,-49730.9946186387,468905.320684901) (-1566924.39158758,-219496.985651066,663007.591625886) (-2157381.87493391,-243266.665144591,570822.903215445) (-2956373.28235599,-124598.880442943,-770891.396075944) (-3565360.53799575,-43622.3677269428,-7008492.0687512) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-640317.461511488,349302.406015625,36373.7736638236) (-658515.469483881,338084.047735757,73104.5138250951) (-701556.138161257,312395.623842324,110030.169143257) (-787110.717298066,263778.553203559,147201.980297704) (-955486.360967973,173151.968687517,192617.603617377) (-1297196.4959173,-78.7682032634313,299024.687471236) (-1964223.39023899,-306688.369589728,639163.593765391) (-2523778.85777965,-354697.531492561,689392.798294472) (-3079450.38085296,-122984.404039606,-689997.6934614) (-3599147.46925311,-26825.8171661667,-6964880.72903581) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-783263.850875672,476190.428334114,25134.701967901) (-799921.356853862,466630.273409596,47370.1019849186) (-840505.756387892,445408.259752152,61334.9988222709) (-926016.275873715,407700.806384274,56424.6843467452) (-1114294.26638164,345082.371032825,19205.5652154539) (-1596287.58714792,249259.176850143,-7765.53861770786) (-3171730.32947192,139935.628380601,590964.19589121) (-3762621.71933495,90578.9373662386,920899.106389315) (-3320638.55892955,79750.7232065305,-594027.472811153) (-3654457.72256053,50581.703669109,-6938202.33372982) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1018720.38366768,605080.838073781,15542.1051655489) (-1033268.00571904,598384.503618754,26144.4155854627) (-1069597.15401205,584377.516475945,23631.3313098022) (-1149087.34952333,561823.550924749,-6278.89414147439) (-1332135.66476147,527999.237009399,-76725.4202437053) (-1812876.41514693,477401.84590547,-117238.670748663) (-3311440.57223158,405658.960220529,541351.84663513) (-3852517.65924032,364585.42258846,909789.029538844) (-3432573.25691168,263343.766606238,-623444.343110514) (-3709574.03388894,131198.992229215,-6988987.94518211) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1403425.51505766,674815.835640165,8812.89815474624) (-1415404.80055882,671086.376149935,12163.4512068439) (-1445963.7729135,664649.065038639,1082.41081366233) (-1515229.88389145,658269.638291789,-40142.2313545882) (-1683291.51990043,656882.97211029,-127328.74743453) (-2154015.90525557,663710.623371491,-188990.708522832) (-3716905.62274247,665198.755000505,500168.923817568) (-4216854.09906497,762405.874558788,808344.723410592) (-3602045.28527094,425994.024037951,-755791.660757665) (-3800646.02196628,176807.702478701,-7120359.98283227) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-2017458.53353322,461745.440365638,5083.75103067773) (-2026490.26966226,460026.05289678,5749.833944537) (-2049833.8063252,458783.931674002,-5260.72698239169) (-2104141.87423028,464689.742789451,-41456.35952201) (-2243210.18020418,495506.80983758,-120370.549921359) (-2675008.99430631,593387.398174756,-187411.076338624) (-4381925.11532701,803413.959921801,597329.651174074) (-3571535.56508467,516204.594645985,471786.769787826) (-3737338.14201684,190027.056951123,-1005141.44914702) (-3941802.355655,1450.94195290261,-7297328.31158396) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-2898283.44260518,-904230.006538309,3308.83577703187) (-2904139.36281057,-905616.041879371,4451.75287679548) (-2919088.25986872,-906895.19371457,648.078037308732) (-2952485.77404642,-904126.172102527,-10582.9784601629) (-3029074.35074431,-889768.549711767,-22364.9452328649) (-3212086.54013518,-856117.544907631,22709.8498294802) (-3612141.35792699,-831607.786456274,310132.665562551) (-3743452.6602059,-1017785.58524998,145515.011808851) (-4088008.87748138,-1186378.90107506,-1193839.62323946) (-4152781.29880504,-1031425.87791108,-7298944.39566579) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-3549493.63399793,-7135717.91839444,1838.63275417794) (-3552343.69409757,-7137443.29452091,3066.53862400353) (-3559497.20794674,-7140344.39466717,3284.77699613503) (-3574948.45743458,-7143418.92914883,3666.66160498567) (-3607844.56285665,-7146910.77179939,11305.8292323312) (-3676738.12209113,-7158203.45545036,47260.3991631859) (-3804077.01462057,-7205513.90101545,123979.627927771) (-3945957.80772275,-7329535.15629275,-23092.6992237508) (-4154049.32562859,-7306525.81663852,-1038968.62164254) (-4008873.40942132,-6267603.59497621,-6267662.093895) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-574996.843191647,49610.5043166581,39336.1346438878) (-592201.5497284,45651.0905944912,79568.7913955931) (-630008.472046265,36670.1786845954,120862.560847241) (-695904.138783816,20463.6210340529,161179.358273064) (-802121.92310001,-6173.0859689117,192365.743803222) (-965213.838869347,-44316.1963356116,188147.751774284) (-1199567.54273377,-82629.1872953136,69682.64413201) (-1490114.70580819,-82785.9945992702,-370389.851654907) (-1722426.97684079,-50862.0306050241,-1488014.46480166) (-1496721.53652683,-21568.6114632541,-3513513.69136543) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-594366.589261621,101194.617681319,35370.1119606058) (-610615.604346268,93757.1786396911,70570.9818982242) (-646341.405160716,76474.2299772213,104559.187118114) (-708751.217595894,43603.7451924038,134451.041377131) (-810135.015220407,-15596.0767750041,154145.39973072) (-968580.693363285,-114410.817907568,149844.042269109) (-1201456.90196448,-239863.27992438,69550.0425105006) (-1483164.47307885,-236945.333443508,-338480.436582584) (-1711097.02308225,-126711.621936711,-1458709.00755097) (-1489759.39327663,-48183.0169373486,-3491896.79510509) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-636881.28916712,155049.290257628,27934.0921885725) (-651272.067342241,145360.022599455,53276.9869679406) (-682828.894407958,122288.259770486,71575.9287547944) (-738047.879036223,75460.1830928585,75116.535608161) (-829304.501977547,-20581.8431556264,55195.7022270372) (-981325.471826411,-224639.565392511,24347.9172237476) (-1238031.15807007,-616855.936077091,72447.3398589427) (-1483893.84323102,-609661.086699716,-228324.938587764) (-1683546.11477231,-247651.681685031,-1380212.04642313) (-1472692.2599267,-77401.0947752069,-3443662.24665434) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-710221.031368949,206698.477978991,18254.3821361056) (-721947.750509837,196925.41732716,30121.2684343632) (-747331.42988172,173593.526065513,24591.2938598027) (-790852.074966415,124905.033269329,-21112.1986483178) (-862397.108717169,14282.382338788,-149065.676393533) (-1003600.6427937,-299283.449926018,-368017.644983634) (-1514341.4364141,-1514292.62580578,79537.0909201556) (-1593873.69848521,-1593595.41400256,133566.258928541) (-1619343.06535685,-364198.264588295,-1209994.47366432) (-1438169.49467508,-82151.7888588592,-3366221.75415877) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-826026.205352035,240948.721953477,8512.11050187758) (-834670.096132723,233421.405988189,6764.86111971025) (-852414.648425938,216404.885082705,-24137.6058594249) (-878049.539025692,184642.811620146,-131842.121058264) (-896272.806152365,127206.996868249,-462788.195817011) (-807741.615334093,32589.0359897095,-1583206.65354657) (-5.84259805523808e-05,-1.49800341591882e-05,3.73054491766705e-05) (636.531527305809,504.223554369846,1362663.80782578) (-1361738.1023472,-32278.4438449284,-928156.469499978) (-1375929.96728279,-4599.81271357219,-3284236.20092301) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-999103.411373499,220357.630724465,974.118934834797) (-1004813.49435559,216205.814075442,-10264.8005158706) (-1015549.96244411,207965.477390318,-55872.5843914233) (-1026621.75449071,195594.658225509,-189290.0260294) (-1013522.83546443,176747.163848975,-557443.022307182) (-858070.032237505,136161.273001556,-1615821.64222845) (-5.41061006895799e-05,-2.14523410503311e-05,3.13418893094593e-05) (533.863532596123,52.6859505525011,1329401.32825962) (-1328378.41039163,93759.029939547,-900830.992044899) (-1375125.68102153,40058.532572784,-3279937.69019857) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1240547.78804319,60696.4844705648,-3216.58076054959) (-1243846.45123422,59899.8054119959,-18468.9214217119) (-1248944.97815482,60675.7010485154,-68197.9398385735) (-1248928.86169373,69217.6501073041,-208121.953918083) (-1213483.7861951,96813.9298761921,-597996.453650639) (-1006532.78519624,142556.783957885,-1751875.08466629) (-0.00014689496210965,5.31664115908781e-05,3.99675556609378e-05) (903.673286537645,1407544.29913906,1422808.97228901) (-1421277.2194089,290587.477141315,-954787.540774806) (-1430738.21542249,35596.9519339032,-3320233.76667974) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1533595.30241226,-419173.72154804,-3993.02510236281) (-1535188.45847501,-417751.630722297,-17643.4001553233) (-1536572.6367351,-410641.011007934,-59587.8576889784) (-1530213.0418916,-383858.935653364,-180440.104266995) (-1484111.42314804,-290593.453696804,-552131.477750144) (-1246244.27128449,56038.2356002848,-1894377.65241436) (992.405628230146,1572911.7489049,1407539.49619142) (-1406241.48542044,344042.920801218,305746.794865014) (-1770259.36946156,-160828.283717445,-1209916.21683151) (-1550498.38784359,-209643.156571428,-3355980.07613761) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1759158.37575377,-1555692.97348319,-2605.81491625577) (-1759833.76913951,-1554093.29321367,-10569.7460959329) (-1759907.27400452,-1547609.10156493,-32782.6414031296) (-1755058.03542018,-1526939.73370421,-87129.5819785179) (-1732480.23753967,-1468924.96058269,-205392.188297265) (-1662839.32115849,-1321174.92575203,-377426.245921654) (-1571435.88063877,-1023920.66889011,178700.694585107) (-1800905.54949765,-1220600.06125128,-199203.434070646) (-1936575.0655471,-1252627.31238192,-1258838.21734043) (-1587143.58916058,-887633.102286567,-3146485.98126979) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1517465.08724031,-3586687.29515295,-1034.22508784627) (-1517730.93518171,-3585617.71110976,-4122.56610761576) (-1517678.06741546,-3581389.97979078,-12160.8284130331) (-1515753.59436723,-3569098.74610896,-29196.679075603) (-1508648.44181442,-3539713.46157647,-57604.2991240714) (-1493345.53062013,-3482049.55189996,-80122.2644471472) (-1488234.41959204,-3401943.95203171,-17941.5763340422) (-1569245.24032863,-3384020.74804965,-231233.456929762) (-1591146.24303751,-3152859.67915171,-893904.172751039) (-1272401.65458417,-2259003.68207749,-2259005.34779725) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-627507.156380382,30278.0720296473,22232.2411590903) (-639147.1009153,27274.3985562581,41903.3937897341) (-663638.346129138,20391.8652615746,55141.4026110284) (-703533.640265328,7656.28178780722,55114.6223047339) (-762139.782141707,-14159.75606354,29292.2374099713) (-842054.569969847,-47629.1668322217,-46237.8646573113) (-940421.891961166,-84440.4333150838,-220943.082114833) (-1032356.23808265,-75800.6513838432,-602900.898456539) (-1023290.93898694,-39500.92138027,-1262536.01493014) (-727717.624850936,-14573.9085142786,-2016966.01809173) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-642178.95174388,58862.8605707201,19227.573941186) (-652378.860813627,53260.1387583263,35005.0902064706) (-673395.991533743,40100.8756137333,42350.6662273366) (-706343.100065409,14361.9733321994,33236.8571524652) (-752071.732073136,-34755.2679554531,-4230.91410289492) (-810275.485526637,-127130.878872826,-83034.4098989366) (-880292.555364508,-276388.479206834,-212250.710607157) (-967012.309679962,-237639.830306621,-566563.695083251) (-980446.66567609,-99130.5099525838,-1237584.46391711) (-708428.824731292,-31105.0759182406,-2002383.86505847) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-673701.103588915,82035.6955621038,13646.9794304109) (-681142.176391466,74908.0109126449,21869.2163253222) (-695304.336723405,57886.6026774311,16558.9315770741) (-713798.73846072,22666.0398255963,-15994.2754918231) (-729591.280112365,-53718.0374339599,-96744.7278784995) (-725878.799070317,-246970.266921845,-232352.01258556) (-680089.413005539,-893186.376045435,-173495.86081148) (-747270.175587736,-719654.836471151,-428104.522290236) (-857730.565388766,-183468.397237524,-1169582.18438885) (-659219.700455513,-42904.455833306,-1971255.36394499) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-725882.588022098,91122.3996402209,6574.85257503369) (-729631.805134234,84364.7042638272,4802.21384824105) (-734473.618683855,68621.8034407089,-18790.7981129006) (-732175.514756869,37746.6489487198,-92547.9674455735) (-698867.99031596,-19621.9816296039,-290173.141651146) (-558559.870431131,-103504.123674893,-878680.05726067) (-2.8059064387009e-05,-4.01376514594278e-06,1.35574000155503e-05) (-8.13914905119184,849.605660011025,107940.161030726) (-559154.645977553,-106625.5431142,-1029091.1124719) (-561881.452563874,-19919.650835877,-1928363.95958055) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-802790.407206091,68000.0738655606,-113.472371283143) (-802809.869568701,63343.5786499619,-10952.5733214465) (-798361.314290578,53308.4466742564,-49692.5506903589) (-776111.104708286,36085.5706832483,-149969.906742296) (-701675.017397258,9948.06995394692,-374137.747080944) (-492294.158965958,-17793.7436093351,-775295.583514613) (3.38237021775912e-06,-2.02568938631228e-06,-6.81168589666925e-05) (-6.31570038478477e-05,-7.56644639316633e-06,2.03953805242742e-06) (326.468516311329,925.396640952966,-942659.614790568) (-426003.868559846,-3865.56586107151,-1908639.7984883) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-905294.003136211,-21068.1561885986,-4741.17818313304) (-902377.788903792,-22849.4717013952,-20983.8332835778) (-890882.04038453,-25464.2704360565,-66879.0382328441) (-854592.287379731,-26749.1942485607,-176073.740412017) (-754549.245773079,-23255.1095184498,-401844.150630957) (-507827.182134513,-12375.0584944666,-757505.685848812) (-1.02931128062797e-06,-5.76864340941666e-06,-5.37445764325999e-05) (-4.6800416776415e-05,-1.58412677837178e-05,1.39898188531499e-06) (54.391068472479,676.710535918846,-947921.176592834) (-406145.632020405,-15636.4785750771,-1905130.31287996) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1022691.24868827,-232426.467320521,-6498.22822300512) (-1018109.24902987,-231557.368503245,-23527.5336255023) (-1002735.3269012,-227088.358718305,-68113.096596886) (-959020.549308291,-212228.585507272,-172542.017723611) (-844407.841648381,-174003.045754319,-390870.026034459) (-567345.055711193,-97466.356347232,-744966.457666765) (-8.10640219222716e-06,-8.56156816456179e-05,-6.3417112252576e-05) (-8.16238072218298e-05,1.75015490824716e-06,4.17198119537998e-07) (-220.79341257942,-58573.5415382932,-964570.490661236) (-436914.803514794,-84248.8015828144,-1889781.57956119) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1115575.57983833,-644892.090011836,-5554.09988262366) (-1110737.13261311,-642582.731976616,-18980.0622711626) (-1095271.07929776,-634184.896115017,-53185.0823117826) (-1052448.67595706,-608943.449443569,-134234.58431001) (-938958.999002479,-539242.061956949,-314147.992252934) (-649860.141171745,-360903.710676834,-647094.768036081) (-0.000100267974423436,4.93309394808414e-06,5.27882942336551e-06) (130.930547159124,-50954.8752885473,-58552.5675412444) (-569625.014665344,-327368.997387062,-990391.466488685) (-572966.597608936,-246422.769425595,-1805749.28888058) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-1086601.87547872,-1314188.19950354,-3260.39078333626) (-1082843.96373766,-1312203.36941513,-10629.5587466786) (-1071170.14414215,-1305627.56912797,-27924.0155960973) (-1039517.40756477,-1287917.41695341,-64490.6759416704) (-955092.698792958,-1245412.93226863,-135707.344376697) (-721318.829237276,-1152048.47869693,-286083.068277798) (463.872485724396,-941092.680118545,-50947.8356070069) (-578522.263179476,-989221.109453056,-335064.887760683) (-782056.215878973,-907357.773450093,-909594.961365785) (-610660.890252379,-572949.165418701,-1559551.26428087) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-760896.157235238,-2069475.5722512,-1281.55725742114) (-758945.736078758,-2068198.179105,-4071.94667051139) (-753087.710522562,-2064055.08835355,-10234.7843378394) (-738138.285656402,-2053713.73010937,-22053.7798927143) (-702345.192142215,-2031473.37154388,-42296.590289638) (-623532.526977647,-1989104.17073729,-75053.9018917681) (-491271.005581437,-1914077.50041929,-99032.4956016436) (-589208.221537398,-1815081.79570387,-253208.828142072) (-614520.585187437,-1561932.65211981,-575259.607322447) (-447160.650869008,-986705.763357633,-986744.01309868) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-653782.859987983,15567.1937559115,10708.5098516941) (-660013.032645296,14018.9177098774,17555.5238718128) (-672198.198063054,10635.1860853985,15480.1897203282) (-689639.441464746,4823.88565900824,-3237.89473926367) (-710677.361623136,-4139.71971227042,-50560.5955455673) (-732083.844004593,-15870.40516594,-144660.916344876) (-747832.202029853,-24274.4429195124,-312976.163356688) (-740885.191674131,-10420.321898343,-594026.887866858) (-653537.63365409,3364.11542094145,-967144.308620621) (-410142.710436352,4740.65890390768,-1289459.88193917) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-663138.740777838,27393.146857369,9133.83593250414) (-667917.741487762,24561.2836107151,14130.3507058039) (-676495.191594865,18256.2282472481,9608.50860508393) (-686573.317931648,6935.13195015097,-12272.519819822) (-693846.253593159,-12296.453806356,-62341.2642057108) (-692641.390622421,-42771.3950074845,-153074.369268385) (-682352.698319603,-76202.4857718601,-299086.183460939) (-678460.482951822,-17882.8373787475,-580175.494708677) (-615127.652687325,23600.5021790834,-965730.894455563) (-393392.471171306,18117.0376416916,-1294143.62675334) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-682622.064028062,30012.6628506724,6301.44444584814) (-684643.250207476,26539.3824052576,7824.41946731751) (-686240.04262448,18792.4550145504,-1776.10139890819) (-681332.372677487,4321.09930656487,-31628.434538559) (-657570.266985481,-23008.19781575,-92937.7036560495) (-595333.385106709,-79696.9094552873,-186557.603171865) (-488945.981304811,-213141.826059984,-240761.69458447) (-494800.078809049,27604.1154373613,-538718.744179267) (-516715.290096713,115117.31105577,-971250.82834801) (-354594.287156269,54446.526536819,-1312205.73054237) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-713122.050894958,14383.8516266835,2868.27409684413) (-711592.590799592,11327.5378831416,40.9042843221786) (-704136.728088451,4847.42319695961,-16350.9544934919) (-678997.778778353,-6117.4213363537,-59090.1698290879) (-608829.833334959,-22386.5430212443,-149749.981604593) (-430747.243451433,-37227.904762827,-320031.613276751) (-2.39995917291138e-05,-3.93105397011809e-06,-3.09070156356491e-06) (-63.8085180568787,937.552185527631,-451370.789282627) (-316263.618693194,452899.088015381,-1032043.5935266) (-288819.540876196,116005.795948644,-1366664.77462609) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-753903.73835865,-34373.7432447674,-129.073975982235) (-749057.351448983,-36120.1912390259,-6433.86297353001) (-733497.31942172,-39133.7051039227,-27316.729541509) (-691856.203649666,-42330.5490456725,-75358.5028908114) (-591946.601049738,-42869.0096296195,-164604.452629956) (-378008.167984365,-33302.2083787734,-282816.139995606) (3.18015374020323e-06,-9.75296125862145e-07,-4.32054441441944e-06) (-5.66213645698236e-05,-1.65501354138936e-06,-9.39353157791097e-06) (-81.0995913090248,632.305024724651,-1369244.59123967) (-212370.381705259,15982.6483135971,-1482854.93045921) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-799403.507130804,-138446.907471981,-1817.33177819579) (-792353.38849907,-138550.564682323,-9411.35873962217) (-771647.49854637,-137306.790156146,-30472.8155255641) (-720390.117329993,-131169.598326333,-75835.9362946424) (-605184.770713412,-113120.461127182,-154948.959856746) (-374715.422528171,-71915.0296597056,-249447.898182159) (-5.46944757840808e-07,-2.8811386646657e-06,-2.28867685351589e-11) (-3.96640553081291e-05,-1.58949569232184e-06,-7.20190220412265e-06) (231.386492988042,336.335850004096,-1354328.8927277) (-198846.596478837,-46450.5623046771,-1499194.71765099) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-833878.420773391,-325412.081942963,-1847.65344390577) (-826154.152296965,-324279.004925193,-8074.30993393941) (-804091.833837747,-319739.893182221,-24284.6999713132) (-750947.805359906,-305804.121438779,-57722.920807249) (-632921.513980612,-268727.265506527,-113602.444095675) (-395359.213725901,-180144.928918162,-177358.386822507) (-6.15389590054157e-06,-5.97721791157744e-06,-2.70254974590511e-11) (-6.91615771114852e-05,-3.226472343684e-06,-1.08252804844809e-05) (483.533219380866,-628095.274686293,-1401389.08883326) (-211359.306177712,-220366.190161202,-1453028.95831384) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-824215.58022954,-616120.625648531,-651.455903220686) (-817313.502913803,-614880.706177735,-3473.38434997874) (-797924.823014252,-610262.218220483,-10297.3155952285) (-751747.802456145,-596219.264594998,-20583.0459399291) (-647757.305435625,-555640.784908834,-24871.2201044774) (-425174.529299227,-432698.03553579,2996.27464063429) (-8.85465732122839e-05,-1.37586719878004e-05,-4.12787597311792e-06) (245.445540733127,-629885.160214027,-628420.758832613) (-292309.814081083,-539959.784029637,-993871.450073523) (-270101.860956555,-284180.00587222,-1232922.37101487) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-714697.135153922,-988584.708927893,559.342954562854) (-709819.749552618,-988438.11102635,1092.53361812827) (-696392.613849729,-987718.635242059,3771.42034727925) (-665241.502453391,-986752.012082421,20028.262723341) (-595893.793836646,-992953.399905445,98141.9727636381) (-436956.249069641,-1054626.76132817,435708.118388374) (605.686909023123,-1433212.35314643,-630071.12601318) (-299550.573711784,-1000186.64640327,-538741.329291621) (-382492.313915927,-739953.147950085,-738311.86733422) (-274707.759302045,-409461.159505813,-948983.844650981) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-441477.982507998,-1308705.50995029,702.626295169064) (-439052.681832979,-1309432.56021214,1804.02123517574) (-432526.620894537,-1311204.89375675,4729.190121837) (-418079.330071044,-1315852.67009389,13770.8925479347) (-388556.589118794,-1329484.05655625,36512.946175326) (-332847.970043765,-1365959.15308354,57160.7809968141) (-247108.814817623,-1423145.64941191,-197068.11350151) (-281772.716768544,-1226106.87717609,-278583.387497545) (-277586.091345819,-947530.11097291,-407940.918316335) (-185354.147981475,-539572.85225888,-539635.728450803) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-664408.065362389,6114.12674656357,4511.07862783445) (-666990.330658555,6059.10270714551,5429.27393394576) (-671252.348149004,6324.2909163093,-1840.86689641003) (-675225.697065262,7861.92830418077,-24116.5396000704) (-675520.336014978,12630.7176170036,-71904.2828252323) (-667102.51120089,23513.8347967038,-160399.45042564) (-643300.192627966,41154.8931364248,-306086.352963945) (-592145.813775766,51968.4799830384,-506794.210845347) (-478186.792049501,41755.3490135407,-723900.401463481) (-276003.746544998,21498.5108070568,-879537.876161879) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-669253.82594137,7821.41617760667,4407.79573248811) (-670854.125521938,7789.0213737956,5614.26110001351) (-672689.86559606,8512.22933869773,-379.003321187363) (-671840.464242727,12176.4272240764,-19426.3559300046) (-663495.897561519,23945.5258651983,-61091.520209842) (-641894.74672861,54471.5635796386,-142795.892886595) (-605854.415071178,117121.409746803,-295260.692745409) (-570557.810807232,165758.7280434,-516953.612950374) (-468203.648648562,122007.402445449,-744129.670421049) (-272015.601532947,56911.7429861833,-900919.772238526) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-678712.366672671,-427.61634327425,4339.3351654868) (-678443.127966255,-356.16088677489,6284.39518483006) (-675595.695102947,943.496878262965,3208.78012373049) (-664873.712945355,6701.37634421626,-7774.82872854211) (-636516.709285581,25776.1906286386,-30659.0511918865) (-576231.349308665,84905.8935505704,-80195.4169608604) (-481126.678036616,275763.571502481,-246656.881984741) (-537330.805950345,522392.245324075,-560759.672124123) (-461786.165844159,315621.173698433,-809302.567629644) (-269480.431138553,120248.4084755,-957753.089136678) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-691726.411494761,-26239.0106935871,4415.75495011557) (-689069.179183331,-26010.8771148961,7547.05956197177) (-680146.270151541,-24402.8105921731,8902.90909549765) (-655740.624710946,-18859.1208563277,11206.2522286381) (-594906.205629557,-5356.51473913012,28415.3298910126) (-443806.16424996,15653.848503707,110726.295736404) (-1.59988248859247e-05,5.25572147494181e-06,-1.10824027168739e-05) (-622305.636710646,1102.75524499085,-767669.186226998) (-532671.092771604,769159.148746962,-1004799.68719711) (-287884.985442202,192495.412753424,-1077981.24690902) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-705104.419840783,-79740.6655957795,4702.33638431852) (-700303.79474163,-79259.3118005144,9197.21436259106) (-686073.858019508,-77101.3623338134,14472.3047020233) (-650271.254671939,-70686.313254459,24714.5481224307) (-566147.973548111,-55923.3472785808,49482.7531602476) (-378407.986353213,-29858.0306869702,95394.4507197735) (6.64343045132351e-06,3.80097160292473e-07,2.01326241904296e-06) (-3.77990303883583e-05,2.62293678815328e-06,-1.95977626208196e-05) (-971294.411814277,993.870571666161,-1581701.65865388) (-360487.019356417,29530.796385396,-1270620.40463468) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-711499.943423738,-172899.912951126,5255.68364828189) (-705536.950541801,-172242.689401496,11422.6232920013) (-688678.353266552,-169609.136822995,20961.2525013665) (-648096.387079543,-161596.648562316,39577.857558772) (-556494.866362761,-140747.174838187,75711.7807677302) (-361907.020630648,-92458.8658525506,125504.214035789) (6.99300682281645e-07,-6.51610470489055e-08,1.74323349040725e-12) (-2.7375092684022e-05,4.93974079405917e-06,-1.46057648867795e-05) (-920713.671219613,625.232192691008,-1553605.03731984) (-363514.484029541,-58924.8939416015,-1300481.45944214) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-697001.492923405,-315748.679274127,5971.83847302491) (-691150.06788717,-315401.142189308,14126.2068510372) (-675032.32493065,-313570.032615171,29027.5937361152) (-637388.811155393,-306650.725525296,60522.676494578) (-553734.203161987,-283610.987676184,124199.178513953) (-371899.799721599,-209983.437183422,218264.335840517) (-3.37579499053596e-06,-1.6181192625598e-06,-1.94693950486581e-12) (-3.83717354638795e-05,-6.42616921407864e-06,-1.94239335864068e-05) (-1009782.61013631,-920907.782235308,-1613443.73909543) (-362863.759097946,-279078.218274,-1241785.96184279) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-639594.468242984,-506681.617158571,6311.82589789723) (-634940.352297351,-507441.799224424,15979.3323165677) (-622708.156904088,-508795.273895864,35987.907487095) (-596155.148582847,-509839.985636049,83584.5137245467) (-541761.548531862,-503951.666352043,197929.43549664) (-420943.225916458,-444742.212528629,428456.907459078) (-5.18279958707338e-05,-2.76699955719557e-05,-8.20478402194444e-06) (-743240.922606171,-929900.136296211,-921181.050602235) (-532363.340907675,-630207.453910781,-971827.852100172) (-269319.815741926,-288777.803606805,-962910.311981998) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-511481.847056992,-715412.827328645,5515.92207313788) (-508601.297857204,-717733.876670466,14589.5478237661) (-501650.071573331,-723948.185991302,34999.9176428054) (-489833.971961838,-739748.501452317,89500.9029675177) (-481697.236990623,-785850.022605401,257202.702374853) (-547032.333814927,-950816.991664873,873353.566256372) (-1131906.70840225,-1681289.57893199,-930305.856661587) (-555327.208135668,-982655.710021836,-621773.648512067) (-368685.142412127,-635177.655755624,-630610.618171035) (-199687.066513571,-320123.138989478,-674285.97557683) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-292824.656127213,-867261.295588683,3195.14187925671) (-291512.585570827,-870461.441421185,8382.6103678288) (-288501.266088874,-878820.921463856,19229.9910347198) (-283969.764772432,-897988.517402557,43360.4416863482) (-282055.874830145,-941233.95207636,92243.6568686501) (-300891.373263062,-1033419.47731243,142889.545735513) (-377426.625492483,-1176305.42033795,-231776.802183671) (-277279.832805675,-944517.976038164,-274407.420130218) (-201401.695067071,-670064.675147006,-315704.797017583) (-112653.493745623,-354267.869741847,-354260.720501065) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-667452.32721836,1134.61997832811,1909.64187764854) (-668328.00966777,2087.2988461199,1160.02204074142) (-669140.701641884,4805.04489024203,-5756.66935662622) (-667852.559725336,11186.1072614722,-24315.9139580259) (-660919.958148561,24579.9109877567,-63496.2028121985) (-642579.542350789,48657.0553928696,-136676.227055172) (-603517.801310776,78550.5716085916,-255009.189980957) (-527757.02019372,73526.5514418716,-392924.535004869) (-401062.586709811,51728.4034055579,-521777.143750123) (-219619.92985397,25482.455834765,-603643.41627591) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-669162.005543757,-1803.62535457576,2846.42493528734) (-669814.34107376,74.2045068244377,3819.73482640656) (-670138.556061041,5532.27453536546,541.195646266508) (-668238.006960137,19128.2446591436,-11003.3990339968) (-661325.280150014,50907.0561259604,-39501.1615837017) (-645989.909086305,120092.962486046,-106841.906319178) (-615861.224599457,241779.685280048,-260064.210462359) (-541405.511113486,199005.765982684,-414695.724696901) (-411623.606792728,128447.409033077,-547994.772180258) (-224948.642305941,59424.5606384956,-629003.836210998) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-671676.882210741,-13501.6840419843,4662.57422547831) (-671875.345841632,-11021.955010703,9190.9516183813) (-671266.170187291,-3624.91680782019,14018.6180459171) (-668240.320328533,15865.5469539311,20647.9231343133) (-662016.645465751,67446.3238534909,29608.5915869549) (-658673.613330338,217366.907689567,14776.9104051074) (-678414.674357299,756802.794385345,-302958.202379496) (-593478.782971068,437545.288969684,-485349.748345771) (-446443.219929567,244842.423680775,-617087.708908061) (-240670.231254399,101872.953289609,-688346.301443328) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-672783.099911202,-39532.8042589442,7087.80863340433) (-672383.998502872,-37148.2740228273,16528.9469650788) (-670468.193718382,-30208.0735076965,33434.0272317965) (-665334.88600425,-13238.2188333196,72132.054312345) (-658452.343427826,23618.480822587,179506.035141514) (-682590.297723851,81428.7587502307,554228.317554738) (-1005892.57652206,1236.70272372722,-622329.323518761) (-752784.248425024,623880.52507832,-678185.947913019) (-536555.511846213,330681.682977337,-760140.788134987) (-275909.012138042,119924.977965457,-790168.786114981) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-668116.033138017,-85996.3152029661,9475.12424125912) (-667159.45860372,-84303.6811096477,23486.1951901637) (-663750.973361108,-79454.9634705899,50410.2004946503) (-653827.396152686,-68232.8668449051,108960.989986978) (-624949.094991034,-45979.220194059,237359.812446557) (-520666.484279991,-13088.2064597901,474135.275583351) (-2.60557231692476e-05,1.14934415642627e-05,2.40742979887262e-05) (-996045.312696773,390.820034787696,-971646.799235221) (-692927.802214274,51715.5023214765,-971047.22817936) (-327985.235560381,26554.1898812578,-910178.223891191) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-650417.432214147,-158295.390021719,11216.5636091602) (-649321.633367303,-157685.464075474,28383.0294004879) (-645712.880331835,-155738.858475834,61701.4514710159) (-635305.706314043,-150646.514617849,131324.41847846) (-603823.008948999,-137775.223631048,270448.564501684) (-489922.297451417,-102256.011929706,487631.646792367) (-2.13325884439552e-05,1.96090858846657e-05,1.6947147038114e-05) (-936981.906237687,358.872617168717,-920754.022389646) (-704963.330090996,-88313.4498554157,-996475.411341358) (-338256.923914719,-58204.578789791,-936974.202785132) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-608976.244556364,-258195.785432813,11875.1470440465) (-608261.833788793,-259064.90243832,30366.351308514) (-606072.480352046,-261162.746492106,66830.3947461815) (-600175.269112584,-265345.106575403,144315.444660921) (-581825.482110952,-271570.177353691,306201.677332522) (-499347.290704022,-258965.170584636,590358.326969883) (-3.13576378475927e-05,2.89612119141326e-05,2.2263846030693e-05) (-1032716.09799018,-743079.211735202,-1009777.34338309) (-697903.339423805,-443407.64755652,-966562.41639448) (-323181.292108727,-185501.749196899,-878947.712976592) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-530317.93669102,-378479.266684453,11006.9496996717) (-530276.514106313,-381025.336414619,28303.5454849322) (-530543.719666769,-387713.667976227,62690.0297317306) (-533402.141871773,-403524.659987254,138116.576432507) (-550242.793372522,-443884.319719985,318911.963639467) (-639663.305353702,-570853.814541921,849520.687034005) (-1155973.90963456,-1131821.76874319,-743389.649269716) (-777360.752900524,-741974.634514233,-710374.396196331) (-510765.580794834,-466543.305054328,-708836.498811353) (-250867.477601722,-219170.047385025,-693620.538763437) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-401781.619678567,-496647.914209496,8468.42014662006) (-402214.138267418,-500570.953233801,21626.8773760113) (-403865.634519222,-510794.513615484,46923.2859611649) (-410243.594681357,-533928.450299385,97736.698992821) (-433521.141963077,-586277.569640756,191953.853886044) (-509679.563219744,-704777.644541713,288524.913290658) (-694516.870207508,-926911.758904794,-353774.934742479) (-511218.208081401,-704698.308413691,-435160.260897298) (-340777.069912954,-467970.511130911,-461641.127319884) (-172780.951620935,-233121.233016769,-474596.056580764) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-219730.161043898,-574310.905447093,4568.49615428259) (-220098.165726941,-578861.63478012,11444.7578567156) (-221340.882458745,-590316.444015014,23806.3046261104) (-225337.231394201,-614064.041632474,45309.3625809687) (-237132.614022426,-659292.644051456,73401.1761839594) (-265932.539594593,-732665.45801365,66330.1559874305) (-307340.342314537,-799003.538779448,-131664.34731587) (-247778.19567434,-667339.187460863,-198525.105400031) (-172172.208019402,-468777.484982099,-226947.618596514) (-89411.6869336723,-241704.550939828,-241606.107485412) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-667740.000299514,-690.191048560173,977.864129708253) (-668151.426133371,524.120910623808,277.159684685367) (-668149.839363344,3769.04362439139,-4482.74621823766) (-665771.277449843,10792.917055622,-17356.9455493599) (-657187.334409237,24163.2181090517,-45252.7873977365) (-635278.535837727,45262.3963006075,-97816.1902113972) (-588214.512978923,66235.6635014262,-179355.142044675) (-500633.427387936,59878.2820067046,-266357.01685716) (-368224.312192019,41177.7823689922,-340373.073743945) (-196193.106475757,20183.8076409698,-383983.704763128) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-667609.958718956,-4460.48959756941,2218.25172420787) (-668495.8924335,-2074.73505933006,3498.65905389833) (-669721.680897644,4374.79724349243,2476.03027140089) (-670106.969457322,19167.4513609686,-4029.54153675923) (-667267.199062986,50266.0643112328,-24190.4688259714) (-655526.023073141,107468.218659912,-76860.1771984447) (-620050.738697677,179292.516208613,-185727.515807407) (-529224.445104504,146987.658697761,-285017.958507453) (-387774.089793339,93649.386845014,-361339.079982857) (-205721.160385448,43696.1140771475,-404078.868339535) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-666062.369909428,-14590.0916089839,4515.0897101018) (-667803.551788523,-11475.6878134994,9844.24841116303) (-671448.756427421,-2731.26645341156,17132.898348195) (-677802.545644182,18901.3206530917,26961.2543717164) (-688907.517974452,71142.3462197066,32975.8449719419) (-706747.37048728,193581.905683366,-5064.08489456854) (-715546.534044055,429489.65449004,-218129.363489242) (-604626.057534295,278415.920767824,-338410.35099609) (-434734.576217441,154854.32423759,-411323.932100793) (-227274.04212589,66673.0584457716,-447697.06559792) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-660229.86984139,-34694.3374278076,7551.01574901267) (-663102.962067404,-31743.0821969424,18537.3736969818) (-670069.429635275,-23295.0196708182,38702.3628312799) (-685318.729460853,-1531.91276605796,79119.4397070413) (-720932.094723479,57328.4118820523,155413.125340348) (-808088.528755326,243628.973996421,230864.28805878) (-983869.654209168,1007607.63852113,-369276.618285205) (-762562.137633583,380941.605496844,-462024.413805655) (-518651.564426603,174456.683616941,-499530.720604626) (-262358.776317284,67892.5713875848,-514300.469367199) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-645255.141246739,-68052.037780384,10496.8084612952) (-649190.723277192,-66226.7812763608,27011.772214187) (-659342.530288685,-61154.8890790019,60463.1985499513) (-683419.078096498,-49409.9724399373,137932.940167641) (-746897.457878993,-24522.7051413813,341732.420079035) (-948242.058041112,18064.2627732862,994872.705063283) (-1750023.97344123,840.858760869211,-996055.059731284) (-1002430.56892451,59895.2993591813,-668623.497365877) (-620837.883586498,39904.5199664015,-606161.252343111) (-300472.086314818,16401.8764345572,-582183.706635656) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-614227.424456853,-116635.282683456,12393.2371457821) (-618877.982384995,-116424.385500099,32147.1903872106) (-631094.74608242,-115883.240221686,72257.4072804792) (-660083.401439252,-115265.680800312,162890.810766064) (-734374.736868422,-115517.3836366,384437.217180704) (-953843.819473261,-111307.557273041,977730.559248886) (-1714726.82332041,858.051816520636,-937125.310946557) (-1030422.70932294,-94986.0231970333,-688803.185305066) (-642990.685898737,-81066.9503715096,-629804.359159439) (-309956.950551436,-43021.6987075684,-598680.757380591) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-558917.255922536,-179362.419990634,12668.1486733544) (-563786.942620703,-180952.135505918,32721.0075110831) (-576607.957656294,-185526.816746514,72900.0613401575) (-606844.954141091,-198436.962219214,162741.027787573) (-683506.23305933,-239874.403246884,388778.798346232) (-912726.725076573,-399164.924897966,1090015.60034372) (-1784267.18941543,-1155930.2256681,-1033066.76081241) (-998125.835765611,-487587.929707629,-675055.116526399) (-605947.376779486,-256181.382500577,-591896.647041662) (-289171.434908758,-113135.837283102,-555792.365666091) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-471040.078931755,-249756.337265831,11116.0595159309) (-475485.34681619,-252808.443132413,28181.1998523016) (-486989.711071154,-260919.847508052,60020.2220182262) (-512911.548852751,-280265.543921256,121358.210701244) (-571218.54265461,-327094.643095849,229554.199832301) (-701733.060317587,-440835.626926112,333294.656824328) (-943438.396266858,-670300.383733902,-364870.698477556) (-710245.474445218,-475732.555134065,-443841.351506436) (-465327.499600355,-296462.044874197,-448998.770327302) (-229185.525496894,-141029.420481405,-442787.139233818) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-345362.952237751,-314295.734490556,8120.72978391192) (-348759.117604496,-318225.417184559,20082.6831731356) (-357276.912410089,-328096.77089523,40670.8844511802) (-375459.489502636,-348888.015392915,74509.2507441159) (-412084.21829584,-389821.408214037,115799.092195063) (-477428.927405575,-461016.740956022,103729.570410799) (-550897.987162318,-539711.059226522,-170478.637141784) (-451509.209654964,-441191.679767145,-264728.510935135) (-309005.611156148,-299279.578209364,-293682.436356765) (-155963.751032519,-149689.081076167,-301839.976350421) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-184021.875659397,-354265.251444013,4261.23156895519) (-185824.838815799,-358497.497171951,10259.9846452041) (-190259.724613721,-368786.755904663,19868.8118096132) (-199282.378320605,-388611.351510657,33537.2948537553) (-215840.769400897,-422139.178387403,44563.2204055906) (-240571.06049728,-466732.017509702,24917.0178619515) (-258412.125679237,-491625.326721308,-72096.9312785592) (-218668.412933943,-419492.976472965,-122905.417313136) (-153601.668529238,-296568.206385353,-144187.328627312) (-78764.27682585,-152305.86115346,-152217.95865784) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-667490.151968788,-721.549037629738,471.700706903878) (-667897.582458724,80.616709864879,137.240322400504) (-667930.735927802,2140.10133862379,-2221.96445176817) (-665560.739247546,6401.65745137369,-8834.16010543885) (-656561.857505801,14016.4478806255,-23476.084889496) (-632811.247661915,24980.0057152766,-50923.3787805889) (-581664.636269241,34388.5407947479,-91861.7962850255) (-489697.668270648,31264.8254621914,-134062.38086451) (-355614.206672983,21631.9995931542,-168304.485976695) (-187485.742710085,10659.1351636626,-187670.984906035) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-666499.680530137,-3135.99981992881,1304.17259348349) (-667754.136484153,-1560.03229520995,2203.06564921135) (-669912.825861449,2515.6408424719,2018.6711091688) (-671817.559394365,11358.5706437928,-1227.65214621041) (-670456.36757974,28511.9370407277,-12533.9727895607) (-657720.805643797,56178.3858028421,-41537.5703064662) (-615979.625735126,83786.2532974001,-95006.3957716653) (-520883.808321492,71572.5942041708,-143654.801296659) (-377234.368659964,46673.1464024724,-179235.669239349) (-198133.522414735,22110.9344241858,-198275.106470579) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-663178.275362768,-8825.64857987184,2805.5542132823) (-665970.61964962,-6791.42583069724,6204.01560987111) (-672206.542424374,-1306.04663653091,10783.4890858276) (-682979.790458351,11453.0099167809,15866.2946270115) (-698811.813185607,39172.4649194711,15110.0619594295) (-713834.641431488,92323.6458761604,-13947.927169682) (-699747.600068856,161321.088883665,-107281.696731146) (-592403.235447081,120626.210103979,-168558.134718161) (-423874.689188748,71037.5604543424,-203782.435798733) (-220218.466087396,31602.5211376918,-220329.598550732) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-654232.671705997,-19598.6981469644,4775.85143170003) (-659068.29954717,-17699.2778138956,11649.040894666) (-670827.067162212,-12403.5093467774,23504.1411318533) (-694417.505080018,531.939043147646,43523.9876246474) (-737989.87767239,31504.3165524072,68249.9189406199) (-806236.637317502,103669.003800262,55052.6695786904) (-861224.769731645,241747.706200036,-148018.832215193) (-713143.725144517,141331.589836334,-218142.624436609) (-494990.305897706,72432.9344434159,-243199.25695459) (-251863.328375042,29817.0558296927,-251909.239588832) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-634658.94830947,-36876.2497611725,6681.35867694229) (-641401.357877131,-35774.6380830257,16967.3535460107) (-658498.046909457,-32721.4804634927,36440.8412835038) (-695071.902146451,-25839.6478349808,74465.2522115836) (-769623.611284884,-11723.5371085788,140419.259278457) (-910078.578151653,12790.9448596208,193133.838329644) (-1103233.66420843,36568.9099970395,-248477.674700184) (-854742.460779502,32233.412774686,-287067.605783516) (-567615.400568955,17964.6805388773,-285821.834896519) (-281766.348407086,7017.92781153262,-281728.444786083) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-597776.681326073,-61182.7890868056,7855.79619485279) (-605673.778830031,-61187.5600861379,20064.5146430002) (-625889.481974066,-61218.4804601845,43356.2505313335) (-669390.419728373,-61809.9218226497,88633.5428081232) (-758113.858310837,-64360.6799236902,165009.807065651) (-923135.07896022,-69838.1428815336,216930.15429376) (-1140105.65157915,-68267.2287203533,-252854.878730108) (-887243.97729706,-62396.9134044874,-301403.284576813) (-585766.781008702,-43843.2866682165,-296819.222259761) (-288856.149011779,-22139.4623437386,-288762.633644153) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-536615.153796929,-91378.6219782165,7893.73076580071) (-544585.396554343,-92532.802587236,20037.4272005415) (-564797.875222263,-95767.0495930255,42775.9138993521) (-607700.814346364,-104327.120786097,86148.9730680724) (-693948.006534419,-127380.700236472,159610.766855941) (-853553.501223504,-187948.416042514,218547.816163843) (-1072088.81921889,-314895.725253885,-247002.057499136) (-825063.293277595,-199539.630806932,-282921.88258471) (-542068.302123928,-115446.473636196,-275197.770272286) (-266757.266577096,-53071.0164405223,-266680.384507167) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-445261.958079186,-123932.557099116,6775.81426833057) (-452151.982262856,-125907.280280864,16816.9274086286) (-469143.415048385,-131025.989093268,34229.570886105) (-503487.835345533,-142658.563297829,63137.2998906192) (-566727.194245652,-167818.380423926,99083.631669121) (-665819.076549641,-216394.139746891,91615.3716055502) (-757392.719386632,-277622.569876578,-131703.460651978) (-625679.991472817,-216871.923989158,-198936.650442135) (-426745.303082009,-140043.95424202,-212921.366354672) (-213757.099975463,-67749.4273362545,-213671.380980367) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-321536.516087814,-152615.145619269,4856.15237021228) (-326509.097145892,-155002.349055419,11701.2006861637) (-338354.781461683,-160825.738197835,22578.8188423249) (-361010.050864456,-172486.587322867,37957.4042291823) (-399057.593865339,-193389.513260959,50501.9126357156) (-449628.080632459,-224026.846381662,30333.7724973713) (-479986.517616918,-247159.716610322,-71040.5503142825) (-408936.068007052,-208295.418637338,-122190.197314017) (-286749.059274102,-143810.049193641,-140680.654244444) (-146014.121044696,-72441.883215425,-145937.828353097) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (-169344.422997773,-169814.328166507,2521.72988561432) (-171900.891021567,-172305.94461616,5901.37765212462) (-177860.276104494,-178226.453256476,10902.6442015358) (-188800.801804831,-189107.542208727,17042.0225716212) (-205907.721958696,-206143.19275648,19862.6546249418) (-225826.940818741,-226039.817116346,7131.50568109082) (-232998.262777374,-233146.539633117,-32295.5341979764) (-200709.86787973,-200765.528052691,-57783.9698368379) (-142937.888721245,-142910.683222305,-69347.1156161661) (-73550.5303685152,-73518.492669987,-73484.25261894) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) (0,0,0) ) ; boundaryField { fuel { type fixedValue; value uniform (0.1 0 0); } air { type fixedValue; value uniform (-0.1 0 0); } outlet { type zeroGradient; } frontAndBack { type empty; } } // ************************************************************************* //
6b7b4eb3772ccb4e77a703687ca3358b92adc06b
e6543fadda0b18b7c0418766dfbbbdf424a7c259
/NetComm/db/DbOperate.cpp
ba321f965d3532eaabfdaa19dda3cbbe48581ac2
[]
no_license
katiya-cw/NetCommon
7de8cf1dad259d080eb09d519647041ff8947aed
27c3f98329dd2e7b696238fd9a384db2ba380a67
refs/heads/master
2020-06-22T09:51:24.235578
2019-04-16T14:27:46
2019-04-16T14:27:46
null
0
0
null
null
null
null
GB18030
C++
false
false
34,499
cpp
DbOperate.cpp
#include "stdafx.h" #include "afxdb.h" #include "DbOperate.h" #include "../../MyDefine.h" int MyEmpID = 0; CDbOperate::CDbOperate() { //用IP=127.0.0.1链接有时候连接不上 //m_sqlAddr = "Provider=SQLOLEDB.1;Server=127.0.0.1;DATABASE=WXData;UID=sa;PWD=123;";//自己测试电脑上的配置 // m_sqlAddr = "Provider=SQLOLEDB.1;Server=127.0.0.1;DATABASE=wxdata;UID=wxdata;PWD=3239508152;"; //云平台上的密码 118.190.86.76 m_sqlAddr = "Provider=SQLOLEDB.1;Server=127.0.0.1;DATABASE=WXData;UID=sa;PWD=xh6565911;"; //云平台上的密码 115.28.78.161上面的 //m_sqlAddr = "Provider=SQLOLEDB.1;Server=iZm5e727lmif5mZ;DATABASE==WXData;UID=sa;PWD=xh6565911;"; //云平台上的密码 // m_sqlAddr = "Provider=SQLOLEDB.1;Server=101.200.204.188;DATABASE=WXData;UID=sa;PWD=xh6565911;"; //云平台上的密码 // m_sqlAddr = "Provider=SQLOLEDB.1;Server=127.0.0.1;DATABASE=WXData;UID=sa;PWD=xh6565911;"; //云平台上的密码 118.190.86.76 //需要打开远程数据库上的对外连接 // m_sqlAddr = "Provider=SQLOLEDB.1;Server=localhost;DATABASE=wxdata;UID=sa;PWD=xh6565911;"; //云平台上的密码 118.190.86.76 //需要打开远程数据库上的对外连接 // m_sqlAddr = "Provider=SQLOLEDB.1;Server=47.104.168.94;DATABASE=wxdata;UID=sa;PWD=xh6565911;"; m_pSqlCon = &m_db; m_accAddr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = MonitorData.mdb"; m_sqlUser.user_name = ""; m_sqlUser.user_pass = ""; m_accUser.user_name = ""; m_accUser.user_pass = ""; } CDbOperate::~CDbOperate() { } //打开SQL数据库 bool CDbOperate::OpenSql() { HRESULT hr; OutputDebug("myTEST CDbOperate::OpenSql() start.."); try { m_pSqlCon->Open(_T("mengHX"), FALSE, FALSE, _T("ODBC;UID=sa;PWD=xh6565911")); OutputDebug("myTEST CDbOperate::OpenSql() end.."); return true; } catch (_com_error e) { CString errorMsg; errorMsg.Format("连接数据库失败!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); return false; } } //关闭SQL数据库 bool CDbOperate::CloseSql() { try { m_pSqlCon->Close(); ///如果已经打开了连接则关闭它 return true; } catch (_com_error e) { CString errorMsg; return false; } } bool CDbOperate::OpenAccess() { return true; } bool CDbOperate::CloseAccess() { return true; } //插入数据 bool CDbOperate::InsertSQLPayRecord(int deviceID, int EmpIDNUM) { OutputDebug("myTEST InsertSQLPayRecord() start.."); try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); // strSQL.Format("INSERT INTO stuTable(birth) VALUES('%s')", dt.Format("%Y-%m-%d %H:%M:%S")); //自己修改字段名即可 // strTemp.Format("insert into dbo.Dev_NetState(SetID,EmpID) values(%d,%d)", deviceID, EmpIDNUM); strTemp.Format("insert into dbo.Dev_NetState(SetID,EmpID,ConnectDate) values(%d,%d,'%s')", deviceID, EmpIDNUM, (dt.Format("%Y-%m-%d %H:%M:%S"))); _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST InsertSQLPayRecord() end.."); return true; } catch (_com_error e) { CString errorMsg; } OutputDebug("myTEST InsertSQLPayRecord() end.."); return false; } //插入数据 bool CDbOperate::nnInsertSQLPayRecord(int deviceID, int EmpIDNUM, unsigned char mt) { OutputDebug("myTEST InsertSQLPayRecord() start.."); try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); // strSQL.Format("INSERT INTO stuTable(birth) VALUES('%s')", dt.Format("%Y-%m-%d %H:%M:%S")); //自己修改字段名即可 // strTemp.Format("insert into dbo.Dev_NetState(SetID,EmpID) values(%d,%d)", deviceID, EmpIDNUM); if (mt == 0) { strTemp.Format("insert into dbo.Dev_NetState(SetID,EmpID,OpType,ConnectDate) values(%d,%d,%s,'%s')", deviceID, EmpIDNUM, NULL, (dt.Format("%Y-%m-%d %H:%M:%S"))); } else { strTemp.Format("insert into dbo.Dev_NetState(SetID,EmpID,OpType,ConnectDate) values(%d,%d,%d,'%s')", deviceID, EmpIDNUM, mt, (dt.Format("%Y-%m-%d %H:%M:%S"))); } _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST InsertSQLPayRecord() end.."); return true; } catch (_com_error e) { CString errorMsg; } OutputDebug("myTEST InsertSQLPayRecord() end.."); return false; } //插入数据 bool CDbOperate::InsertSQLPayRecordCCC(int deviceID, int EmpIDNUM) { try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); // strSQL.Format("INSERT INTO stuTable(birth) VALUES('%s')", dt.Format("%Y-%m-%d %H:%M:%S")); //自己修改字段名即可 // strTemp.Format("insert into dbo.Dev_NetState(SetID,EmpID) values(%d,%d)", deviceID, EmpIDNUM); strTemp.Format("insert into dbo.Dev_UseState(SetID,status) values(%d,%d)", deviceID, EmpIDNUM); _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); // OutputDebug("myTEST InsertSQLPayRecord() end.."); return true; } catch (_com_error e) { } // OutputDebug("myTEST InsertSQLPayRecord() end.."); return false; } bool CDbOperate::InsertSQLPayRecord2(int deviceID) { OutputDebug("myTEST InsertSQLPayRecord2() start.."); try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); // strSQL.Format("INSERT INTO stuTable(birth) VALUES('%s')", dt.Format("%Y-%m-%d %H:%M:%S")); //自己修改字段名即可 // strTemp.Format("insert into dbo.Dev_NetState(SetID,EmpID) values(%d,%d)", deviceID, EmpIDNUM); strTemp.Format("insert into Dbo.WK_SetState(SetID) values(%d)", deviceID); // strTemp.Format("Update Dbo.WK_SetState set state_1=%d,state_2=%d,state_3=%d,state_4=%d,state_5=%d,state_6=%d,BuildDate='%s' where SetID=%d", mdata[0], mdata[1], mdata[2], mdata[3], mdata[4], mdata[5], dt.Format("%Y-%m-%d %H:%M:%S"), DevID);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST InsertSQLPayRecord2() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } OutputDebug("myTEST InsertSQLPayRecord2() end.."); return false; } #ifdef DaoShenFlowmeter //插入数据 bool CDbOperate::InsertSQLPayRecord_CANSHU(int deviceID, unsigned long tep1, unsigned long tep2, unsigned long tep3, unsigned long tep4, unsigned long tep5, unsigned long tep6) { try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); // strSQL.Format("INSERT INTO stuTable(birth) VALUES('%s')", dt.Format("%Y-%m-%d %H:%M:%S")); //自己修改字段名即可 // strTemp.Format("insert into dbo.Dev_NetState(SetID,EmpID) values(%d,%d)", deviceID, EmpIDNUM); //strTemp.Format("insert into Dbo.WK_SetState(SetID) values(%d)", deviceID); strTemp.Format("Update Dbo.WK_SetState set state_1=%d,state_2=%d,state_3=%d,state_4=%d,state_5=%d,state_6=%d,BuildDate='%s' where SetID=%d", tep1, tep2, tep3, tep4, tep5, tep6, dt.Format("%Y-%m-%d %H:%M:%S"), deviceID);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST InsertSQLPayRecord2() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } return false; } #endif //更新数据 bool CDbOperate::UpdateSQL(int devID, int EmpIDNUM) { OutputDebug("myTEST myOUTerr() start.."); try { CString strTemp; //自己修改字段名即可 //strTemp.Format("Update dbo.Dev_NetState set DevIP=%d,EmpID='%s' )", deviceID, id); //strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d,EmpID=%d ", id,deviceID); strTemp.Format("Update dbo.Dev_NetState set EmpID=%d where SetID=%d ", EmpIDNUM, devID);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST UpdateSQL() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } OutputDebug("myTEST UpdateSQL() end.."); return false; } //更新数据 bool CDbOperate::nnUpdateSQL(int devID, int EmpIDNUM, unsigned char mt) { //OutputDebug("myTEST myOUTerr() start.."); try { CString strTemp; //自己修改字段名即可 //strTemp.Format("Update dbo.Dev_NetState set DevIP=%d,EmpID='%s' )", deviceID, id); //strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d,EmpID=%d ", id,deviceID); if (mt == 0) { strTemp.Format("Update dbo.Dev_NetState set EmpID=%d, OpType=%s where SetID=%d ", EmpIDNUM, NULL, devID);//注意字符串就用'%s',数字用%d } else { strTemp.Format("Update dbo.Dev_NetState set EmpID=%d, OpType=%d where SetID=%d ", EmpIDNUM, mt, devID);//注意字符串就用'%s',数字用%d } _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST UpdateSQL() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } //OutputDebug("myTEST UpdateSQL() end.."); return false; } //更新数据 bool CDbOperate::UpdateSQLCCC(int devID, int EmpIDNUM) { //OutputDebug("myTEST myOUTerr() start.."); try { CString strTemp; //自己修改字段名即可 //strTemp.Format("Update dbo.Dev_NetState set DevIP=%d,EmpID='%s' )", deviceID, id); //strTemp.Format("Update dbo.Dev_UseState set setid=%d,EmpID=%d ", id,deviceID); strTemp.Format("Update dbo.Dev_UseState set status=%d where SetID=%d ", EmpIDNUM, devID);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST UpdateSQL() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } // OutputDebug("myTEST UpdateSQL() end.."); return false; } //临时先假定设备都上线,把链接状态都改为上线状态 bool CDbOperate::myUpdateSQL(int ConOK) { OutputDebug("myTEST myUpdateSQL() start.."); try { CString strTemp; //自己修改字段名即可 //strTemp.Format("Update dbo.Dev_NetState set DevIP=%d,EmpID='%s' )", deviceID, id); //strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d,EmpID=%d ", id,deviceID); strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d ", ConOK);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST myUpdateSQL() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } OutputDebug("myTEST myUpdateSQL() end.."); return false; } bool CDbOperate::my2UpdateSQL(int DevID, int ConOK) { OutputDebug("myTEST my2UpdateSQL() start.."); try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); //自己修改字段名即可 //strTemp.Format("Update dbo.Dev_NetState set DevIP=%d,EmpID='%s' )", deviceID, id); //strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d,EmpID=%d ", id,deviceID); strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d,ConnectDate='%s' where SetID=%d", ConOK, dt.Format("%Y-%m-%d %H:%M:%S"), DevID);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST my2UpdateSQL() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } OutputDebug("myTEST my2UpdateSQL() end.."); return false; } bool CDbOperate::my3UpdateSQL(int DevID, unsigned int *mdata) { OutputDebug("myTEST my3UpdateSQL() start.."); try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); //自己修改字段名即可 //strTemp.Format("Update dbo.Dev_NetState set DevIP=%d,EmpID='%s' )", deviceID, id); //strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d,EmpID=%d ", id,deviceID); strTemp.Format("Update Dbo.WK_SetState set state_1=%d,state_2=%d,state_3=%d,state_4=%d,state_5=%d,state_6=%d,BuildDate='%s' where SetID=%d", mdata[0], mdata[1], mdata[2], mdata[3], mdata[4], mdata[5], dt.Format("%Y-%m-%d %H:%M:%S"), DevID);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST my3UpdateSQL() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } OutputDebug("myTEST my3UpdateSQL() end.."); return false; } bool CDbOperate::myUpdateDown_DataSQL(int deviceID, unsigned int*Down_Data, unsigned int*CheckBox) //是可从入函数 { unsigned int bigDown_Data[15]; unsigned int bigCheckBox; OutputDebug("myTEST myUpdateDown_DataSQL() start.."); bigDown_Data[0] = Down_Data[0]; bigDown_Data[0] = bigDown_Data[0] << 16; bigDown_Data[0] |= Down_Data[1]; bigDown_Data[1] = Down_Data[2]; bigDown_Data[1] = bigDown_Data[1] << 16; bigDown_Data[1] |= Down_Data[3]; bigDown_Data[2] = Down_Data[4]; bigDown_Data[2] = bigDown_Data[2] << 16; bigDown_Data[2] |= Down_Data[5]; bigDown_Data[3] = Down_Data[6]; bigDown_Data[3] = bigDown_Data[3] << 16; bigDown_Data[3] |= Down_Data[7]; bigDown_Data[4] = Down_Data[8]; bigDown_Data[4] = bigDown_Data[4] << 16; bigDown_Data[4] |= Down_Data[9]; bigDown_Data[5] = Down_Data[10]; bigDown_Data[5] = bigDown_Data[5] << 16; bigDown_Data[5] |= Down_Data[11]; bigDown_Data[6] = Down_Data[12]; bigDown_Data[6] = bigDown_Data[6] << 16; bigDown_Data[6] |= Down_Data[13]; bigDown_Data[7] = Down_Data[14]; bigDown_Data[7] = bigDown_Data[7] << 16; bigDown_Data[7] |= Down_Data[15]; bigDown_Data[8] = Down_Data[16]; bigDown_Data[8] = bigDown_Data[8] << 16; bigDown_Data[8] |= Down_Data[17]; bigDown_Data[9] = Down_Data[18]; bigDown_Data[9] = bigDown_Data[9] << 16; bigDown_Data[9] |= Down_Data[19]; bigDown_Data[10] = Down_Data[20]; bigDown_Data[10] = bigDown_Data[10] << 16; bigDown_Data[10] |= Down_Data[21]; bigDown_Data[11] = Down_Data[22]; bigDown_Data[11] = bigDown_Data[11] << 16; bigDown_Data[11] |= Down_Data[23]; bigDown_Data[12] = Down_Data[24]; bigDown_Data[12] = bigDown_Data[12] << 16; bigDown_Data[12] |= Down_Data[25]; bigDown_Data[13] = Down_Data[26]; bigDown_Data[13] = bigDown_Data[13] << 16; bigDown_Data[13] |= Down_Data[27]; bigDown_Data[14] = Down_Data[28]; bigDown_Data[14] = bigDown_Data[14] << 16; bigDown_Data[14] |= Down_Data[29]; bigCheckBox = CheckBox[0]; bigCheckBox = bigCheckBox << 16; bigCheckBox |= CheckBox[1]; try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); //自己修改字段名即可 // strTemp.Format("Update Dbo.WK_SetDownData set Down_Data1=%d,Down_Data2=%d,Down_Data3=%d,Down_Data4=%d,Down_Data5=%d,Down_Data6=%d, Down_Data7=%d, Down_Data8=%d, Down_Data9=%d, Down_Data10=%d, Down_Data11=%d, Down_Data12=%d, Down_Data13=%d, Down_Data14=%d, Down_Data15=%d where SetID=%d ", bigDown_Data[0], bigDown_Data[1], bigDown_Data[2], bigDown_Data[3], bigDown_Data[4], bigDown_Data[5], bigDown_Data[6], bigDown_Data[7], bigDown_Data[8], bigDown_Data[9], bigDown_Data[10], bigDown_Data[11], bigDown_Data[12], bigDown_Data[13], bigDown_Data[14], deviceID);//注意字符串就用'%s',数字用%d strTemp.Format("Update Dbo.WK_SetDownData set Down_Data1=%d,Down_Data2=%d,Down_Data3=%d,Down_Data4=%d,Down_Data5=%d,Down_Data6=%d, Down_Data7=%d, Down_Data8=%d, Down_Data9=%d, Down_Data10=%d, Down_Data11=%d, Down_Data12=%d, Down_Data13=%d, Down_Data14=%d, Down_Data15=%d,Down_CheckBox=%d where SetID=%d ", bigDown_Data[0], bigDown_Data[1], bigDown_Data[2], bigDown_Data[3], bigDown_Data[4], bigDown_Data[5], bigDown_Data[6], bigDown_Data[7], bigDown_Data[8], bigDown_Data[9], bigDown_Data[10], bigDown_Data[11], bigDown_Data[12], bigDown_Data[13], bigDown_Data[14], bigCheckBox, deviceID);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST myUpdateDown_DataSQL() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } OutputDebug("myTEST myUpdateDown_DataSQL() end.."); return false; } //查询示例 void CDbOperate::QuerySQL() { //_RecordsetPtr pRecordset; OutputDebug("myTEST QuerySQL() start.."); //pRecordset.CreateInstance(__uuidof(Recordset)); CString strData; strData.Format("select SetID,EmpID from dbo.Dev_NetState"); _bstr_t sql = strData.GetBuffer(0); CRecordset pRecordset(&m_db); try { pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } if (pRecordset.IsBOF()) { return; } else { pRecordset.MoveFirst(); } while (!pRecordset.IsEOF()) { //循环读取每条记录 CString TEMP; pRecordset.GetFieldValue("EmpID", TEMP); DWORD dtu_id = atoi(TEMP); //atoi()字符串转数据类型 pRecordset.GetFieldValue("SetID", TEMP); DWORD id = atoi(TEMP); //atoi()字符串转数据类型 pRecordset.MoveNext(); } pRecordset.Close(); OutputDebug("myTEST QuerySQL() end.."); } //查询示例---强烈注意里面有全局变量MyEmpID,本函数是非可重入函数。 unsigned char CDbOperate::MyQuerySQL(int deviceID)//强烈注意里面有全局变量MyEmpID,本函数是非可重入函数。 { unsigned long ii; _variant_t var; OutputDebug("myTEST 1CDbOperate:: MyQuerySQL() start.."); ii = 0; CRecordset pRecordset(&m_db); try { CString strData; strData.Format("select * from dbo.Dev_NetState where SetID = %d", deviceID); _bstr_t sql = strData.GetBuffer(0); pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } try { if (!(pRecordset.IsBOF())) { pRecordset.MoveFirst(); } else { // AfxMessageBox("表内数据为空"); goto sttt2; } while (!(pRecordset.IsEOF())) { //循环读取每条记录 // DWORD dtu_id = pRecordset->GetCollect("EmpID"); CString TEMP; //pRecordset.GetFieldValue("SetID", TEMP); // DWORD id = atoi(TEMP); //CString TEMP; pRecordset.GetFieldValue("EmpID", TEMP); MyEmpID = atoi(TEMP); ii++; pRecordset.MoveNext(); } // pRecordset->Close(); } catch (_com_error *e) { AfxMessageBox(e->ErrorMessage()); } OutputDebug("myTEST 2CDbOperate:: 2MyQuerySQL() end.."); sttt2: if (ii > 0) { return 1; } else { return 0; } } #ifdef updataOnOffDTU //查询示例---强烈注意里面有全局变量 int CDbOperate::MyQuerySQLconnectTime(void)// { unsigned long ii; _variant_t var; CString olgTime; CString TEMP; OutputDebug("myTEST 1CDbOperate:: MyQuerySQL() start.."); olgTime = ""; ii = 0; CRecordset pRecordset(&m_db); try { CString strData; strData.Format("select * from dbo.Dev_NetState "); _bstr_t sql = strData.GetBuffer(0); pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } try { if (!(pRecordset.IsBOF())) { pRecordset.MoveFirst(); } else { // AfxMessageBox("表内数据为空"); goto sttt2; } while (!(pRecordset.IsEOF())) { //循环读取每条记录 // DWORD dtu_id = pRecordset->GetCollect("EmpID"); pRecordset.GetFieldValue("ID", TEMP); pRecordset.GetFieldValue("ConnectDate", olgTime); DWORD devNo = atoi(TEMP); //CString TEMP; //pRecordset.GetFieldValue("EmpID", TEMP); //MyEmpID = atoi(TEMP); CDbOperate::devTimeMap[devNo] = olgTime; //CDbOperate::devTimeMap.insert((devNo, olgTime)); ii++; pRecordset.MoveNext(); } // pRecordset->Close(); } catch (_com_error *e) { AfxMessageBox(e->ErrorMessage()); } //OutputDebug("myTEST 2CDbOperate:: 2MyQuerySQL() end.."); sttt2: if (ii > 0) { return 1; } else { return 0; } } bool CDbOperate::UpdateSQLconnectTime(long id, int ConOK) //更新设备的联网状态 { OutputDebug("myTEST my2UpdateSQL() start.."); try { CString strTemp; CString strSQL; COleDateTime dt = COleDateTime::GetCurrentTime(); //自己修改字段名即可 //strTemp.Format("Update dbo.Dev_NetState set DevIP=%d,EmpID='%s' )", deviceID, id); //strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d,EmpID=%d ", id,deviceID); strTemp.Format("Update dbo.Dev_NetState set ConnectOK=%d where ID=%d", ConOK, id);//注意字符串就用'%s',数字用%d _bstr_t sql = strTemp.GetBuffer(0); m_pSqlCon->ExecuteSQL(sql); OutputDebug("myTEST my2UpdateSQL() end.."); return true; } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 // errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); // MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } OutputDebug("myTEST my2UpdateSQL() end.."); return false; } #endif //查询示例---强烈注意里面有全局变量MyEmpID,本函数是可重入函数。 unsigned char CDbOperate::nnMyQuerySQL(int deviceID, int * PnnMyEmpID, unsigned char *OpType)//强烈注意里面有全局变量MyEmpID,本函数是可重入函数。 { unsigned long ii; _variant_t var; OutputDebug("myTEST 1CDbOperate:: MyQuerySQL() start.."); ii = 0; CRecordset pRecordset(&m_db); try { CString strData; strData.Format("select * from dbo.Dev_NetState where SetID = %d", deviceID); _bstr_t sql = strData.GetBuffer(0); pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } try { if (!(pRecordset.IsBOF())) { pRecordset.MoveFirst(); } else { // AfxMessageBox("表内数据为空"); goto sttt2; } while (!(pRecordset.IsEOF())) { //循环读取每条记录 // DWORD dtu_id = pRecordset->GetCollect("EmpID"); CString TEMP; //pRecordset.GetFieldValue("SetID", TEMP); // DWORD id = atoi(TEMP); //CString TEMP; pRecordset.GetFieldValue("EmpID", TEMP); *PnnMyEmpID = atoi(TEMP); pRecordset.GetFieldValue("OpType", TEMP); *OpType = atoi(TEMP); ii++; pRecordset.MoveNext(); } } catch (_com_error *e) { AfxMessageBox(e->ErrorMessage()); } OutputDebug("myTEST 2CDbOperate:: 2MyQuerySQL() end.."); sttt2: if (ii > 0) { return 1; } else { return 0; } } //---查询一下设备是否有人再使用,也就是流水EmpID是否不为0,为0就是没人使用。 unsigned char CDbOperate::MyQuerySQL3(int deviceID)//---查询一下设备是否有人再使用,也就是流水EmpID是否不为0,为0就是没人使用。 { unsigned long ii; _variant_t var; int jj = 0; OutputDebug("myTEST CDbOperate:: MyQuerySQL3() start.."); ii = 0; jj = 0; CRecordset pRecordset(&m_db); try { CString strData; strData.Format("select * from dbo.Dev_NetState where SetID = %d", deviceID); _bstr_t sql = strData.GetBuffer(0); pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } try { if (!(pRecordset.IsBOF())) { pRecordset.MoveFirst(); } else { // AfxMessageBox("表内数据为空"); goto sttt2; } while (!(pRecordset.IsEOF())) { //循环读取每条记录 CString TEMP; pRecordset.GetFieldValue("EmpID", TEMP); jj = atoi(TEMP); ii++; pRecordset.MoveNext(); } // pRecordset->Close(); } catch (_com_error *e) { AfxMessageBox(e->ErrorMessage()); } OutputDebug("myTEST CDbOperate:: MyQuerySQL3() end.."); sttt2: if (jj > 0) { return 1; } else { return 0; } } //查询示例BB unsigned char CDbOperate::MyQuerySQLBB(int deviceID) { unsigned long ii; _variant_t var; OutputDebug("myTEST 3CDbOperate:: MyQuerySQL() start.."); ii = 0; CRecordset pRecordset(&m_db); try { CString strData; strData.Format("select * from dbo.Dev_NetState where SetID = %d", deviceID); _bstr_t sql = strData.GetBuffer(0); pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } try { if (!(pRecordset.IsBOF())) { pRecordset.MoveFirst(); } else { // AfxMessageBox("表内数据为空"); goto sttt2; } while (!(pRecordset.IsEOF())) { //循环读取每条记录 ii++; pRecordset.MoveNext(); } // pRecordset->Close(); } catch (_com_error *e) { AfxMessageBox(e->ErrorMessage()); } OutputDebug("myTEST 4CDbOperate:: MyQuerySQL() end.."); sttt2: if (ii > 0) { return 1; } else { return 0; } } unsigned char CDbOperate::MyQuerySQLCC(int deviceID) { unsigned long ii; _variant_t var; OutputDebug("myTEST 5CDbOperate:: MyQuerySQL() start.."); ii = 0; CRecordset pRecordset(&m_db); try { CString strData; strData.Format("select * from dbo.Dev_UseState where SetID = %d", deviceID); _bstr_t sql = strData.GetBuffer(0); pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } try { if (!(pRecordset.IsBOF())) { pRecordset.MoveFirst(); } else { // AfxMessageBox("表内数据为空"); goto sttt2; } while (!(pRecordset.IsEOF())) { //循环读取每条记录 ii++; pRecordset.MoveNext(); } // pRecordset->Close(); } catch (_com_error *e) { AfxMessageBox(e->ErrorMessage()); } OutputDebug("myTEST 6CDbOperate:: MyQuerySQL() end.."); sttt2: if (ii > 0) { return 1; } else { return 0; } } unsigned char CDbOperate::MyQuerySQL2(int deviceID) { unsigned long ii; _variant_t var; OutputDebug("myTEST MyQuerySQL2() start.."); ii = 0; CRecordset pRecordset(&m_db); try { CString strData; strData.Format("select * from Dbo.WK_SetState where SetID = %d", deviceID);//注意字符串就用'%s',数字用%d _bstr_t sql = strData.GetBuffer(0); pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } try { if (!(pRecordset.IsBOF())) { pRecordset.MoveFirst(); } else { // AfxMessageBox("表内数据为空"); goto sttt2; } while (!(pRecordset.IsEOF())) { //循环读取每条记录 ii++; pRecordset.MoveNext(); } // pRecordset->Close(); } catch (_com_error *e) { AfxMessageBox(e->ErrorMessage()); } OutputDebug("myTEST MyQuerySQL2() end.."); sttt2: if (ii > 0) { return 1; } else { return 0; } } //查询设置的参数是哪些,-本函数是可重入函数。 unsigned char CDbOperate::MyQueryDown_DataSQL(int deviceID, unsigned int*Down_Data, unsigned int*CheckBox) { unsigned long ii; _variant_t var; unsigned long tempDD; OutputDebug("myTEST CDbOperate:: MyQueryDown_DataSQL() start.."); ii = 0; CRecordset pRecordset(&m_db); try { CString strData; strData.Format("select * from dbo.WK_SetDownData where SetID = %d", deviceID); _bstr_t sql = strData.GetBuffer(0); pRecordset.Open(CRecordset::dynamic, sql); } catch (_com_error e) { CString errorMsg; //下面的错误提示,在调试时可以打开,观察错误点 errorMsg.Format("MyQuerySQL数据库!\r\n错误信息:%s", e.ErrorMessage()); MessageBox(NULL, errorMsg, "错误", MB_OK); // return false; } try { if (!(pRecordset.IsBOF())) { pRecordset.MoveFirst(); } else { // AfxMessageBox("表内数据为空"); goto sttt2; } while (!(pRecordset.IsEOF())) { //循环读取每条记录 CString TEMP; pRecordset.GetFieldValue("Down_Data1", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data2", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data3", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data4", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data5", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data6", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data7", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data8", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data9", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data10", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data11", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data12", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data13", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data14", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_Data15", TEMP); #ifdef downLoadPam TEMP.Replace(",", ""); #endif tempDD = atoi(TEMP); Down_Data[ii] = tempDD >> 16; ii++; Down_Data[ii] = tempDD & 0xFFFF; ii++; pRecordset.GetFieldValue("Down_CheckBox", TEMP); tempDD = atoi(TEMP); CheckBox[0] = tempDD >> 16; CheckBox[1] = tempDD & 0xFFFF; pRecordset.MoveNext(); } // pRecordset->Close(); } catch (_com_error *e) { AfxMessageBox(e->ErrorMessage()); } OutputDebug("myTEST CDbOperate:: MyQueryDown_DataSQL() end.."); sttt2: if (ii > 0) { return 1; } else { return 0; } } bool CDbOperate::InsertAccessState(int dtu_id, bool online) { return true; } //更新数据 bool CDbOperate::UpdateAccess(int deviceID, CString str) { //和SQL的一样 return false; } //查询示例 void CDbOperate::QueryAccess() { //和SQL的一样 }
fcfc6ada121862fa684a2f49c2ee1dadd03407e3
267b8fd21e612aa17109110deb799456e2189ca2
/SwordingForOffer/32_NumberOf1.cpp
a4b39908873d12701caa09a31e935671de082d2a
[]
no_license
abumaster/CplusplusCode
abc48292ba0ef8125a89e5cf94336304ce7c4018
c546e44a597b7c096e6a44292098b3070d1c508e
refs/heads/master
2021-01-19T22:02:12.337869
2018-03-28T09:00:49
2018-03-28T09:00:49
88,744,141
0
0
null
2019-03-06T14:36:34
2017-04-19T12:46:11
C++
UTF-8
C++
false
false
1,006
cpp
32_NumberOf1.cpp
#include <iostream> #include <string.h> using namespace std; int PowerBase10(int n) { int result = 1; for(int i=0; i<n; ++i) result *= 10; return result; } int NumberOf1(const char* strN) { if(!strN || *strN < '0' || *strN > '9' || *strN == '\0') return 0; int first = *strN - '0'; int length = strlen(strN); if(length == 1 && first == 0) return 0; if(length == 1 && first > 0) return 1; //位于最高位的1的数目 int numFistDigit = 0; if(first > 1) numFistDigit = PowerBase10(length-1); else if(first == 1) numFistDigit = atoi(strN+1) + 1; //除了第一位之外的1的数目 int numOtherDigits = first*(length-1)*PowerBase10(length-2); //递归求剩下的数字 int numRecursive = NumberOf1(strN+1); return (numFistDigit+numOtherDigits+numRecursive); } int NumOf1andN(int n) { if(n<=0) return 0; char strN[50]; sprintf(strN, "%d", n); return NumberOf1(strN); } int main() { int num; while(cin >> num){ cout << NumOf1andN(num) << endl; } return 0; }
9aaca10beb6b359ede18848f71fac08e4a286f23
63a926588ed0e5decc2633d88c01e30b96c884d3
/cppersist/mongo.hpp
3c7ff520e337e51fbb8089976218d9c73d223930
[]
no_license
tallalnparis4ev/cppersist
e3b774bedf627be0536481fad823b1a35d46c5c4
6801cbeab3057fe79aefebb42b3336783b43a6ae
refs/heads/master
2023-04-02T00:39:49.682010
2021-04-18T17:40:54
2021-04-18T17:40:54
298,915,201
11
0
null
null
null
null
UTF-8
C++
false
false
5,141
hpp
mongo.hpp
#ifndef MONGO_H_FILE #define MONGO_H_FILE #include "crypto/sha256.h" #include "memoization/persistent/memoizer.hpp" namespace cpst { /** * \defgroup PersistMongo Persist MongoDB * @{ */ /** * Creates an object that has persistent memoization applied * to T's solve function. Here, the storage medium for persistent memoization * is mongoDB. * @tparam T - the class which the user wants to instantiate an object of, * with a memoized version of the solve function. * @param key - this function should return a string representation for a * given argument to the solve function. * @param pickle - this function should return a string representation * for any return of the solve function. * @param unpickle - this function is the inverse of pickle. * @param dbURL - this corresponds to the URL of the mongoDB server. * @param hash - this is applied to the key produced by the key function, the * string it returns will be used as the final key for cache entries. Default = * sha256. */ template <typename T, typename Ret, typename... Args> PersistentMemoized<T, Ret, Args...> getMongoMemoizedObj( string (*key)(Args...), string (*pickle)(Ret), Ret (*unpickle)(string), string dbURL, string (*hash)(string) = sha256); /** * Creates an object that has persistent memoization applied * to T's solve function. Here, the storage medium for persistent memoization * is mongoDB. * @tparam T - the class which the user wants to instantiate an object of, * with a memoized version of the solve function. * @param key - this function should return a string representation for a * given argument to the solve function. * @param pickle - this function should return a string representation * for any return of the solve function. * @param unpickle - this function is the inverse of pickle. * @param dbURL - this corresponds to the URL of the mongoDB server. * @param funcName - this corresponds to which collection in the 'cppersist' * database results should be persisted. If this is not passed in, the name * typeid(T).name() is used instead. * @param hash - this is applied to the key produced by the key function, the * string it returns will be used as the final key for cache entries. Default = * sha256. */ template <typename T, typename Ret, typename... Args> PersistentMemoized<T, Ret, Args...> getMongoMemoizedObj( string (*key)(Args...), string (*pickle)(Ret), Ret (*unpickle)(string), string dbURL, string funcName, string (*hash)(string) = sha256); /** * Creates an object that has persistent memoization applied * to T's solve function. Here, the storage medium for persistent memoization * is mongoDB. * @tparam T - the class which the user wants to instantiate an object of, * with a memoized version of the solve function. * @param primaryCache - this will initialise the specified memory cache and use * it as the primary cache. * @param key - this function should return a string representation for a * given argument to the solve function. * @param pickle - this function should return a string representation * for any return of the solve function. * @param unpickle - this function is the inverse of pickle. * @param dbURL - this corresponds to the URL of the mongoDB server. * @param hash - this is applied to the key produced by the key function, the * string it returns will be used as the final key for cache entries. Default = * sha256. */ template <typename T, typename Ret, typename... Args> PersistentMemoized<T, Ret, Args...> getMongoMemoizedObj( MemCacheType primaryCache, string (*key)(Args...), string (*pickle)(Ret), Ret (*unpickle)(string), string dbURL, string (*hash)(string) = sha256); /** * Creates an object that has persistent memoization applied * to T's solve function. Here, the storage medium for persistent memoization * is mongoDB. * @tparam T - the class which the user wants to instantiate an object of, * with a memoized version of the solve function. * @param primaryCache - this will initialise the specified memory cache and use * it as the primary cache. * @param key - this function should return a string representation for a * given argument to the solve function. * @param pickle - this function should return a string representation * for any return of the solve function. * @param unpickle - this function is the inverse of pickle. * @param dbURL - this corresponds to the URL of the mongoDB server. * @param funcName - this corresponds to which collection in the 'cppersist' * database results should be persisted. If this is not passed in, * typeid(T).name() is used instead. * @param hash - this is applied to the key produced by the key function, the * string it returns will be used as the final key for cache entries. Default = * sha256. */ template <typename T, typename Ret, typename... Args> PersistentMemoized<T, Ret, Args...> getMongoMemoizedObj( MemCacheType primaryCache, string (*key)(Args...), string (*pickle)(Ret), Ret (*unpickle)(string), string dbURL, string funcName, string (*hash)(string) = sha256); /**@}*/ } // namespace cpst #include "mongo.cpp" #endif
6a0b2dea75809a56b5b6ddcc420d4b2599967e2e
232dc3461e2244a139fb59a0e2063cb35c7d6235
/src/Frame.h
d467cd96512eeb7fa709ea449e7bbfca0ef563e7
[ "MIT" ]
permissive
VictorQueiroz/ffmpegcpp
96cda6b82fd8e7c8f9c85799a1e7d4fc9ed956a7
56719d097b09f573bf695a392b13f4919b4c81f0
refs/heads/master
2020-04-09T00:53:49.526820
2018-11-30T23:45:38
2018-11-30T23:45:38
159,885,106
0
1
null
null
null
null
UTF-8
C++
false
false
338
h
Frame.h
#ifndef FFMPEG_CPP_FRAME_H #define FFMPEG_CPP_FRAME_H #include "av.h" extern "C" { #include <libavcodec/avcodec.h> } namespace av { class Frame { private: AVFrame* frame; public: Frame(); ~Frame(); AVFrame* c_frame(); void getBuffer(int align); }; } #endif //FFMPEG_CPP_FRAME_H
f4ac8291dccda55d55d827e3df7ac1b3e7746962
71700213aa9121306b7a4ed4b391e3a49df6ddc4
/src/mcv/camshift.cpp
1821e0027a47bfdc7ea53a9687d5d94fcf772fa0
[ "MIT" ]
permissive
mmalicki2/QOczko
9f394dc04eb9cf2f045b3a364f111d119446a32d
838a6cd39d30de07ec972045650e3527a2b18ae6
refs/heads/master
2020-04-08T08:00:01.195835
2015-07-16T19:51:56
2015-07-16T19:51:56
39,217,049
0
0
null
null
null
null
UTF-8
C++
false
false
900
cpp
camshift.cpp
#include "camshift.h" #include <cv.h> #include <QtGui/QTransform> using namespace mcv; CamShift::CamShift(QObject* parent) : QObject(parent) { m_criteria = cv::TermCriteria(cv::TermCriteria::MAX_ITER , 10, 1); } CamShift::~CamShift() { } void CamShift::imageRecived(const cv::Mat& image) { cv::Rect l_rect = (m_rect.height > 0) ? m_rect : cv::Rect(0, 0, image.cols, image.rows); cv::RotatedRect rrect = cv::CamShift(image, l_rect, m_criteria); emit detectedHotPoint(QPoint(rrect.center.x, rrect.center.y)); const QRect rect(-rrect.size.height/2, -rrect.size.width/2, rrect.size.height, rrect.size.width); QTransform transform; transform.rotate(rrect.angle, Qt::ZAxis); QVector<QPolygon> ret; QPolygon polygon = transform.map(QPolygon(rect, true)); polygon.translate(rrect.center.x , rrect.center.y); ret.append(polygon); emit detected(ret); } #include "camshift.moc"
d942a6cfc98748d05524db947e2dd74e28fa57ea
b20d1ec3751dd85bd9238a997080758f08048863
/ukTests/compMagSen/compensatedMagSense2/compensatedMagSense2.ino
842faf2e74fffd466de1527fa238091eb7fb4dfe
[]
no_license
ajayvarghese2000/Maze-Solver
b15bf11185fb0c9496cfdd75bfa289bdcd633162
f1d06e713fdbe1afda72b8bc0b762bc0d55c7a49
refs/heads/main
2023-04-23T11:11:06.532424
2021-04-28T13:18:30
2021-04-28T13:18:30
338,583,756
0
0
null
null
null
null
UTF-8
C++
false
false
3,663
ino
compensatedMagSense2.ino
#include <Adafruit_LSM303_Accel.h> #include <Adafruit_LSM303DLH_Mag.h> #include <Adafruit_Sensor.h> #include <Wire.h> #include <math.h> Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(51234); Adafruit_LSM303DLH_Mag_Unified mag = Adafruit_LSM303DLH_Mag_Unified(12345); const float alpha = 0.4; float fXa = 0; float fYa = 0; float fZa = 0; float fXm = 0; float fYm = 0; float fZm = 0; void setup() { Serial.begin(9600); Wire.begin(); accel.begin(); mag.begin(); mag.setMagRate(LSM303_MAGRATE_220); //Matlab Handshake // Serial.println('a'); char a = 'b'; while(a != 'a') { a=Serial.read(); } //*/ mag.setMagRate(LSM303_MAGRATE_75); accel.setRange(LSM303_RANGE_4G); accel.setMode(LSM303_MODE_HIGH_RESOLUTION); } void loop(){ float Xa_off, Ya_off, Za_off, Xa_cal, Ya_cal, Za_cal; float Xm_off, Ym_off, Zm_off, Xm_cal, Ym_cal, Zm_cal, Xm2_off, Ym2_off, Zm2_off, Xm2_cal, Ym2_cal, Zm2_cal; float pitch, pitch_print, roll, roll_print, Heading, fXm_comp, fYm_comp; sensors_event_t event; accel.getEvent(&event); sensors_event_t event2; mag.getEvent(&event2); if((event2.magnetic.x!=0)&&(event2.magnetic.y!=0)&&(event2.magnetic.z!=0)){ //Accel Xa_off = event.acceleration.x + 0.09936010; //X-axis combined bias (Non calibrated data - bias) Ya_off = event.acceleration.y + -0.20228716; //Y-axis combined bias (Default: substracting bias) Za_off = event.acceleration.z + 0.13047152; //Z-axis combined bias Xa_cal = 1.02674657*Xa_off + -0.00200062*Ya_off + 0.00374363*Za_off; //X-axis correction for combined scale factors (Default: positive factors) Ya_cal = -0.00200062*Xa_off + 1.00162291*Ya_off + -0.00285011*Za_off; //Y-axis correction for combined scale factors Za_cal = 0.00374363*Xa_off + -0.00285011*Ya_off + 0.98308850*Za_off; //Z-axis correction for combined scale factors //Mag (double filter) Xm2_off = event2.magnetic.x*(1000.0) + 15457.78386802; Ym2_off = event2.magnetic.y*(1000.0) + 25151.00289933; Zm2_off = event2.magnetic.z*(1000.0) - 1962.50002183; Xm2_cal = 0.86289497*Xm2_off + 0.00465130*Ym2_off + 0.02390530*Zm2_off; Ym2_cal = 0.00465130*Xm2_off + 0.80913161*Ym2_off + 0.01086330*Zm2_off; Zm2_cal = 0.02390530*Xm2_off + 0.01086330*Ym2_off + 0.83280781*Zm2_off; // Low-Pass filter accelerometer fXa = Xa_cal * alpha + (fXa * (1.0 - alpha)); fYa = Ya_cal * alpha + (fYa * (1.0 - alpha)); fZa = Za_cal * alpha + (fZa * (1.0 - alpha)); // Low-Pass filter magnetometer fXm = Xm2_cal * alpha + (fXm * (1.0 - alpha)); fYm = Ym2_cal * alpha + (fYm * (1.0 - alpha)); fZm = Zm2_cal * alpha + (fZm * (1.0 - alpha)); // Pitch and roll //roll = atan2(fYa, sqrt(fXa*fXa + fZa*fZa)); //pitch = atan2(fXa, sqrt(fYa*fYa + fZa*fZa)); //roll_print = roll*180.0/M_PI; //pitch_print = pitch*180.0/M_PI; pitch = atan2(Xa_cal, Za_cal); roll = atan2(Ya_cal, Za_cal); // Tilt compensated magnetic sensor measurements //fXm_comp = fXm*cos(pitch)+fZm*sin(pitch); //fYm_comp = fXm*sin(roll)*sin(pitch)+fYm*cos(roll)-fZm*sin(roll)*cos(pitch); fXm_comp = fXm*cos(pitch)+fYm*sin(pitch)*sin(roll)-fZm*sin(pitch)*cos(roll); //fYm_comp = fYm*cos(roll)+fZm*sin(roll); fYm_comp = fXm*sin(roll)*sin(pitch)+fYm*cos(roll)-fZm*sin(roll)*cos(pitch); Serial.println(fXm_comp,7); Serial.println(fYm_comp,7); //Serial.println(event2.magnetic.x*1000,7); //Serial.println(event2.magnetic.y*1000,7); Serial.println(Xm2_cal,7); Serial.println(Ym2_cal,7); delay(60); } }
a877b9d225c5277152265eb3616b685b4bca3cfb
7d5593b9bbaf6bb8eaacca88449d90c9c305c36e
/problems/1005-maximize-sum-of-array-after-k-negations/1005.hh
65dca59fc370baab667580949c9ac856a4dd95fb
[]
no_license
yottacto/leetcode
fc98052ed9d643be8a79116d28540596bcc7c26b
9a41e41c0982c1a313803d1d8288d086fbdbd5b6
refs/heads/master
2021-04-25T12:05:55.671066
2019-12-15T03:07:31
2019-12-15T03:07:31
111,814,868
2
0
null
null
null
null
UTF-8
C++
false
false
501
hh
1005.hh
#pragma once #include <vector> #include <algorithm> struct Solution { int largestSumAfterKNegations(std::vector<int>& a, int k) { std::sort(a.begin(), a.end()); for (auto& i : a) if (i < 0 && k) { i = -i; k--; } if (k > 0 && k & 1) { std::sort(a.begin(), a.end()); a[0] = -a[0]; } auto sum = 0; for (auto i : a) sum += i; return sum; } };
51a884dd08c4a1ecee877138162a2474a2e8d88b
7d64e03e403eca85248677d8dc72751c93940e48
/test/db/MojDbWatchTest.h
a5ed4e678b80d8e114d026a7592181e30b381e2d
[ "Apache-2.0" ]
permissive
webosce/db8
a6f6ec64d3cb8653dc522ee7a3e8fad78fcc0203
994da8732319c6cafc59778eec5f82186f73b6ab
refs/heads/webosce
2023-05-13T15:18:39.562208
2018-08-23T08:51:14
2018-09-14T13:30:43
145,513,369
0
1
Apache-2.0
2023-04-26T02:43:57
2018-08-21T05:52:45
C++
UTF-8
C++
false
false
1,296
h
MojDbWatchTest.h
// Copyright (c) 2009-2018 LG Electronics, Inc. // // 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef MOJDBWATCHTEST_H_ #define MOJDBWATCHTEST_H_ #include "MojDbTestRunner.h" class MojDbWatchTest : public MojTestCase { public: MojDbWatchTest(); virtual MojErr run(); virtual void cleanup(); private: MojErr eqTest(MojDb& db); MojErr gtTest(MojDb& db); MojErr ltTest(MojDb& db); MojErr cancelTest(MojDb& db); MojErr rangeTest(MojDb& db); MojErr pageTest(MojDb& db); MojErr limitTest(MojDb& db); MojErr put(MojDb& db, const MojObject& fooVal, const MojObject& barVal, MojObject& idOut, MojInt64& revOut); MojErr merge(MojDb& db, const MojObject& id, const MojObject& barVal); MojInt64 m_rev; }; #endif /* MOJDBWATCHTEST_H_ */
8094aec910a716b020e983535463c91558e854f1
6663fe683509c3211d821f702522447df099fcc5
/main.cpp
cf44cd06a61fdb82ac730807445b7cfd35b2ae41
[]
no_license
Damiankk-dev/new-XML-adventure
c9ca13d71ecf93618cf9b32737ba88fa25ea1ca0
ee8321dd34a351002e5c43ea2e28101498b8175e
refs/heads/master
2023-03-28T22:28:19.056727
2021-04-06T19:00:21
2021-04-06T19:00:21
353,412,623
0
0
null
null
null
null
UTF-8
C++
false
false
5,073
cpp
main.cpp
#include <iostream> #include<vector> #include <sstream> #include "Markup.h" using namespace std; struct User { int id = 0; string username = ""; string password = ""; }; struct UsersIncome { int userId = 0; int incomeId = 0; string incomeLabel = ""; float incomeValue = 0.0; }; string convertFloat2String( float ); int main() { // User users[3]; // users[0].id = 1; // users[0].username = "ziomek"; // users[0].password = "asdf"; // users[1].id = 2; // users[1].username = "2ziomek"; // users[1].password = "2asdf"; // users[2].id = 3; // users[2].username = "3ziomek"; // users[2].password = "3asdf"; // // CMarkup xml; // xml.SetDoc("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); // xml.AddElem( "root" ); // xml.IntoElem(); // // for (int i = 0; i < 3; i++) // { // xml.AddElem( "USER" ); // xml.IntoElem(); // xml.AddElem( "ID", users[i].id ); // xml.AddElem( "USERNAME", users[i].username); // xml.AddElem( "PASSWORD", users[i].password ); // xml.OutOfElem(); // } // // xml.Save("users.xml"); // string xmlStr = xml.GetDoc(); // cout << "First xml File created!" << endl; // cout << "What include string generated from object: \n" << xmlStr << endl; // // float incomeValue = 2450.7827; // ostringstream ss; // ss << incomeValue; // string s(ss.str()); // xml.SetDoc("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); // xml.AddElem( "root" ); // xml.IntoElem(); // xml.AddElem( "INCOME" ); // xml.IntoElem(); // xml.AddElem( "USER_ID", 1 ); // xml.AddElem( "INCOME_ID", 1 ); // xml.AddElem( "INCOME_LABEL", "Pensja" ); // xml.AddElem( "INCOME_VALUE", convertFloat2String( incomeValue ) ); // xml.Save("incomes.xml"); CMarkup xml; xml.Load( "users.xml" ); // string xmlStr = xml.GetDoc(); // cout << "What include string generated from object: \n" << xmlStr << endl; xml.FindElem(); xml.IntoElem(); User user; vector<User> users; while ( xml.FindElem( "USER" ) ) { xml.IntoElem(); xml.FindElem( "ID" ); user.id = stoi( xml.GetData() ); xml.FindElem( "USERNAME" ); user.username = xml.GetData(); xml.FindElem( "PASSWORD" ); user.password = xml.GetData(); users.push_back(user); xml.OutOfElem(); } for (vector<User>::iterator itr = users.begin(), finish = users.end(); itr != finish; itr++) { cout << "User:\n"; cout << "ID: " << itr->id; cout << "\nUsername: " << itr->username; cout << "\nPassword: " << itr->password; cout << "\n\n"; } int loggedUserId = users[1].id; cout << "Signed user's id: " << loggedUserId << endl; xml.Load( "incomes - Kopia.xml" ); xml.FindElem(); xml.IntoElem(); UsersIncome income; vector<UsersIncome> user2incomeArray; while ( xml.FindElem( "INCOME" ) ) { xml.IntoElem(); xml.FindElem( "USER_ID" ); int loadedId; loadedId = stoi( xml.GetData() ); if ( loadedId == 2 ) { xml.FindElem( "INCOME_ID" ); income.incomeId = stoi( xml.GetData() ); xml.FindElem( "INCOME_LABEL" ); income.incomeLabel = xml.GetData(); xml.FindElem( "INCOME_VALUE" ); income.incomeValue = stof( xml.GetData() ); user2incomeArray.push_back(income); } xml.OutOfElem(); } cout << "User 2 incomes:\n"; for (vector<UsersIncome>::iterator itr = user2incomeArray.begin(), finish = user2incomeArray.end(); itr != finish; itr++) { cout << "\nID: " << itr->incomeId; cout << "\t| : " << itr->incomeLabel; cout << "\t| : " << itr->incomeValue; cout << "\n"; } xml.ResetPos(); loggedUserId = users[2].id; cout << "Signed user's id: " << loggedUserId << endl; xml.FindElem(); xml.IntoElem(); vector<UsersIncome> user3incomeArray; while ( xml.FindElem( "INCOME" ) ) { xml.IntoElem(); xml.FindElem( "USER_ID" ); int loadedId; loadedId = stoi( xml.GetData() ); if ( loadedId == 3 ) { xml.FindElem( "INCOME_ID" ); income.incomeId = stoi( xml.GetData() ); xml.FindElem( "INCOME_LABEL" ); income.incomeLabel = xml.GetData(); xml.FindElem( "INCOME_VALUE" ); income.incomeValue = stof( xml.GetData() ); user3incomeArray.push_back(income); } xml.OutOfElem(); } cout << "User 3 incomes:\n"; for (vector<UsersIncome>::iterator itr = user3incomeArray.begin(), finish = user3incomeArray.end(); itr != finish; itr++) { cout << "\nID: " << itr->incomeId; cout << "\t| : " << itr->incomeLabel; cout << "\t| : " << itr->incomeValue; cout << "\n"; } return 0; } string convertFloat2String( float number ) { ostringstream ss; ss << number; return ss.str(); }
cca9d446d4bf0cbb2e503f7ec66572158eb0a56e
092655ae75ce99f4a01815d669086b1359a4b9cf
/C++/Persiapan Gemastik 10/ganjilgenap.cpp
2aeb06a0dc9e1b5f1daa6feef320b65b4c0293a8
[]
no_license
vitorizkiimanda/CodingMixed
f9bf6e078b9e4b9da07106dfe076f4419b027293
d312bac862c098508e170c2e46b24a86d713d26d
refs/heads/master
2020-04-18T21:35:23.201217
2019-01-27T05:05:53
2019-01-27T05:05:53
167,768,951
0
0
null
null
null
null
UTF-8
C++
false
false
224
cpp
ganjilgenap.cpp
#include<bits/stdc++.h> using namespace std; int main(){ int genap,ganjil; scanf("%d %d", &genap,&ganjil); if(genap==ganjil || abs(genap-ganjil)==1) printf("YES\n"); else printf("NO\n"); return 0; }
732066adfd5b2ae13c549edf4eb07e5669c0ea38
ee243a638c7a3923cd874dbdeba5a9fa68e4947b
/Classes/MidiReader.h
ec22593e1a3ce0768d09db2716f7899780412f02
[]
no_license
Allegro-Learning/Allegro-Learning
1f9f65419050703fa97cb5d7e22be41928672b1f
0dd3ff9df62360d8fe654f529e88b782b64b22e2
refs/heads/develop
2021-01-03T03:02:24.732069
2020-03-03T06:48:57
2020-03-03T06:48:57
239,893,472
2
0
null
2020-07-21T22:14:38
2020-02-12T00:27:00
C++
UTF-8
C++
false
false
193
h
MidiReader.h
#ifndef __MIDIREADER_H__ #define __MIDIREADER_H__ #include "cocos2d.h" #include "MidiStream.h" class MidiReader : public MidiStream { private: public: virtual bool init(); } #endif
03912264f5a3151649188231df11bab26791301f
b0b8168720256f01baf5f843da6e8d07c49e7744
/WebMonitor/GeneratedFiles/qrc_window.cpp
fc06fdac9f804886efbb607a2603a5b4009973b0
[]
no_license
treejames/WebMonitor
d4bb8997d2f82fecb9848f7c602707a0e4d59014
1ab84df1260b432d2f6215d7822c4204365633cd
refs/heads/master
2018-03-23T15:14:13.076626
2014-06-11T15:44:58
2014-06-11T15:44:58
21,890,592
1
0
null
null
null
null
UTF-8
C++
false
false
680
cpp
qrc_window.cpp
/**************************************************************************** ** Resource object code ** ** Created: Sat May 3 08:47:29 2014 ** by: The Resource Compiler for Qt version 4.7.1 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <QtCore/qglobal.h> QT_BEGIN_NAMESPACE QT_END_NAMESPACE int QT_MANGLE_NAMESPACE(qInitResources_window)() { return 1; } Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_window)) int QT_MANGLE_NAMESPACE(qCleanupResources_window)() { return 1; } Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_window))
d71c76de1b97b41f10596dd537a455dd71a45df7
e63c918268d0365ed40868694da7402d42780010
/LinkedList.cpp
d074f568184b7a4b44efc95ba48d501ce8b62b52
[]
no_license
sourabhKondal/LinkedListImplementation
28bcdb413bb4d9cf724891f13a0847bf34721c67
8da48046a47d88dde8ec1cccb2d8b6a0ca4b8a29
refs/heads/master
2020-03-22T09:39:06.544386
2018-06-25T12:13:36
2018-06-25T12:13:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,772
cpp
LinkedList.cpp
#include<iostream> using namespace std; class Node { public: int data; class Node *next; }; class Node *start=NULL; class Node* createNode() { int element; class Node *temp=new Node; cout<<"Enter an integer\n"; cin>>element; temp->data=element; temp->next=NULL; return temp; } void insertNodeFirst() { class Node *temp; if(start==NULL) { start=createNode(); } else { temp=createNode(); temp->next=start; start=temp; } } void insertNodeLast() { class Node *temp; temp=start; if(start==NULL) { start=createNode(); } else { while(temp->next!=NULL) { temp=temp->next; } temp->next=createNode(); } } void insertNodePos(int position) { class Node *temp=start; class Node *t; if(start==NULL) { start=createNode(); } else { for(int i=0;i<position-1;i++) { temp=temp->next; } t=createNode(); t->next=temp->next; temp->next=t; } } void deleteFirstNode() { class Node *temp; if(start==NULL) { cout<<"List is already empty. Nothing to delete.\n"; } else { temp=start; start=start->next; delete temp; } } void deleteLastNode() { class Node *temp=start; class Node *t; if(start==NULL) { cout<<"List is already empty. Nothing to delete.\n"; } else { while(temp->next!=NULL) { t=temp; temp=temp->next; } t->next=NULL; delete temp; } } void deleteNodePos(int position) { class Node *temp=start; class Node *t; if(start==NULL) { cout<<"List is already empty. Nothing to delete.\n"; } else { for(int i=0;i<position-2;i++) { temp=temp->next; } t=temp->next; temp->next=temp->next->next; delete t; } } void traverse() { class Node *temp; temp=start; if(start==NULL) { cout<<"List is empty\n"; } else { while(temp!=NULL) { cout<<temp->data<<endl; temp=temp->next; } } } int main() { int choice,position; cout<<"1 Insert a node at first.\n"; cout<<"2 Insert a node at last.\n"; cout<<"3 Insert a node at a specific position.\n"; cout<<"4 Delete a node at first.\n"; cout<<"5 Delete a node at last.\n"; cout<<"6 Delete a node at specific position.\n"; cout<<"7 Print all the values of the list.\n"; cout<<"8 Press to exit.\n"; while(true) { cout<<"Enter your choice.\n"; cin>>choice; switch(choice) { case 1: insertNodeFirst(); break; case 2: insertNodeLast(); break; case 3: cout<<"Enter position\n"; cin>>position; insertNodePos(position); break; case 4: deleteFirstNode(); break; case 5: deleteLastNode(); break; case 6: cout<<"Enter position\n"; cin>>position; deleteNodePos(position); break; case 7: traverse(); break; case 8: exit(false); break; default: cout<<"Invalid Choice\n"; break; } } }