blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
9f2d595c99b4f7421bbe1f15a5733e1c8c143f41
5c77807c8a39658e995c00adecb5f9e3bde0884d
/opengl/Source/Shader/main.cpp
5e7a3f06f7f2a08402b1346318ab9a04409a5fe2
[]
no_license
starlitnext/practice
6a39b116213caaf014875b32d048ff5f2d6ca190
3d1be394c7c7cc444a10cfd878caacb2f592b653
refs/heads/master
2021-01-18T21:33:09.692397
2018-01-24T15:23:25
2018-01-24T15:23:25
40,886,119
1
0
null
null
null
null
UTF-8
C++
false
false
3,571
cpp
#include <iostream> #include "Common.hpp" #include "Shader.hpp" // Function prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); // Window dimensions const GLuint WIDTH = 800, HEIGHT = 600; int main() { // ---------------------------------------------------------------- // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); // ---------------------------------------------------------------- // Build and compile our shader program Shader ourShader("F:\\workspace\\c++\\demos\\HelloWorld\\OpenGL\\Source\\Shader\\shader.vs", "F:\\workspace\\c++\\demos\\HelloWorld\\OpenGL\\Source\\Shader\\shader.frag"); // ---------------------------------------------------------------- // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Colors 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // Bottom Left 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // Top }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); // Unbind VAO // ---------------------------------------------------------------- // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Draw the triangle ourShader.Use(); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); }
[ "gzxuxiaoqiang@game.ntes" ]
gzxuxiaoqiang@game.ntes
323d48a232dc170bdb3dca6a29cc27247a164709
b41532e333eb839abd35c788fbdc54eadb93263b
/src/RMeCabMx.cpp
a739e7ccb566356a691bb563b5c7855ec480ca3e
[]
no_license
halka9000stg/RMeCab
8dd1b94aa717bc6d9d1d10c798b4422e884b29ca
72775047fe9f88346963512157dcab965440b9b6
refs/heads/master
2022-07-07T20:57:28.035193
2020-05-13T05:29:28
2020-05-13T05:29:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,907
cpp
/* ver 0.99995 2016 12 27 全ての関数を使われる前に消し去りたい         |\           /|         |\\       //|        :  ,> `´ ̄`´ <  ′ .       V            V .       i{ ●      ● }i        八    、_,_,     八    わけがわからないよ .       / 个 . _  _ . 个 ',    _/   il   ,'    '.  li  ',__ docDF関数で全てをまかなえるから */ #include "RMeCab.h" ////////////////////////////////////////////////////// /* データフレームから指定された列の文字列を読む */ extern "C" { SEXP RMeCabMx(SEXP filename, SEXP pos, SEXP posN, SEXP minFreq, SEXP kigo , SEXP mydic ){ // SEXP sym, SEXP kigo // Rprintf("in RMeCabMX\n"); const char* input = CHAR(STRING_ELT(filename,0)); const char* dic = CHAR(STRING_ELT(mydic, 0));//指定辞書 char KIGO[BUF1]; // = CHAR(STRING_ELT(kigo,0)); strcpy(KIGO, kigoCode()); //strcpy(KIGO, "記号"); // Rprintf("before minFreq\n"); int mFreq = INTEGER_VALUE( minFreq );// 最小頻度の数 int mSym = INTEGER_VALUE( kigo );// INTEGER_VALUE( sym ) 記号を含めるか 0 含めない;1 含める int mF = 0;// map オブジェクト内の最小頻度以下の個数を記憶 int pos_n = INTEGER_VALUE( posN );// pos の数 bool flag = 1; if(pos_n < 1 ){ pos_n = 2;// = 1 flag = 0; } // char *Ppos[pos_n]; // 2011 03 10 vector<string> Ppos2; int totalM = 0; char input2[BUF4];//char input2[5120];char input2[5120]; mecab_t *mecab; mecab_node_t *node; int i, j, n, z, zz = 0; int posC = 0; int pc = 0; // int console = 0; char buf1[BUF1];// [512];//入力された語形を記憶 char buf2[BUF3]; char buf3[BUF2];// [128];記号チェック用 char buf4[BUF2];// [128]; 記号チェック用 char *p; // SEXP mydf, tmp, varlables, row_names; SEXP vecInt, vecName, myPos; map<string, int> m1; map<string, int>::iterator pa; //Rprintf("before MeCab\n"); string str;// 2009 04 03 FILE *fp; // 2009 04 03 mecab = mecab_new2 (dic);// mecab = mecab_new2 ("MeCab");// mecab_new2 (" -u user.dic"); CHECK(mecab); //Rprintf("before Pos set\n"); if(pos_n > 0 && flag){ PROTECT(myPos = AS_CHARACTER(pos));pc++; // 2011 03 10 for( i = 0; i < pos_n; i++){ // Ppos[i] = R_alloc( (unsigned int ) strlen (CHAR(STRING_ELT(myPos, i))), sizeof(char)); // } // Rprintf("end myPos = AS_CHARACTER(pos) \n"); for( i = 0; i < pos_n; i++){ // 2011 03 10 strcpy(Ppos[i], CHAR(STRING_ELT(myPos, i))); Ppos2.push_back(CHAR(STRING_ELT(myPos, i))); // 2011 03 10 // Rprintf("Pos[%d] = %s\n", i, Ppos[i]); if(strcmp(Ppos2[i].c_str() , KIGO) == 0){// if(strcmp(Ppos[i], KIGO) == 0){ mSym = 1; } } }else{ PROTECT(myPos = AS_CHARACTER(pos));pc++; // Ppos[0] = R_alloc(strlen(CHAR(STRING_ELT(myPos, 0))), sizeof(char)); // strcpy(Ppos[0], meisiCode()); // 2011 03 10 // Ppos[0] = R_alloc( (unsigned int ) strlen( meisiCode()), sizeof(char)); // 2011 03 10 // strcpy(Ppos[0], meisiCode() ); Ppos2.push_back( meisiCode() ); // 2011 03 10 // 2011 03 10 // Ppos[1] = R_alloc( (unsigned int ) strlen( keiyouCode() ), sizeof(char)); // 2011 03 10 // strcpy(Ppos[1], keiyouCode() ); Ppos2.push_back( keiyouCode() ); // 2011 03 10 // char * tmp; // strcpy(tmp, (const char*) meisiCode()); // strcpy(Ppos[0], tmp ); // strcpy(tmp, (const char*) keiyouCode()); // strcpy(Ppos[0], tmp ); } //Rprintf("before file to open\n"); if((fp = fopen(input, "r")) == NULL){ Rprintf("no file found\n"); return(R_NilValue); }else{ Rprintf("file = %s\n",input ); while(!feof(fp)){ if(fgets(input2, FILEINPUT, fp) != NULL){// 2011 03 11 if(fgets(input2, 5120, fp) != NULL){ node = ( mecab_node_t * ) mecab_sparse_tonode(mecab, input2); CHECK(node); /// 解析結果のノードをなめる for (; node; node = node->next) { // printf("%d ", node->id); if (node->stat == MECAB_BOS_NODE) //printf("BOS"); continue; else if (node->stat == MECAB_EOS_NODE) //printf("EOS"); continue; else { // 2010 buf1 = (char *)malloc( node->length * MB_CUR_MAX+ 1); strncpy(buf1, node->surface, node->length) ;//元の語形 buf1[node->length] = '\0';// 末尾にNULLを加える// 2006 06 移動 if(strlen(buf1) < 1){ continue;// 2006 06 移動 } //< 2005 11 07> //Rprintf("%s\n", buf1); //if( atoi(buf1) > 0x00 && atoi(buf1) < 0x0e ){//if( atoi(buf1) == 0x0e){//エスケープ記号類 if( buf1[0] > 0x00 && buf1[0] < 0x21 ){//エスケープ記号類 continue; }// </ 2005 11 07> // buf1[node->length] = '\0';// 末尾にNULLを加える// 2006 06 移動 // if(strlen(buf1) < 1){// 2006 06 移動 // continue; // } strcpy(buf2, node->feature);//ノードごとに解析情報の取得.要素数は 9 if(strlen(buf2) < 1){ continue; } p = strtok(buf2, "," );//取得情報の分割 if( p != NULL){ sprintf(buf3, "%s", p); //Rprintf("%s\n", buf3); //if(mSym < 1 && strcmp(buf3, "記号") == 0){ if(mSym < 1 && strcmp(buf3, KIGO) == 0){ continue; } totalM++; for( i = 0; i < pos_n; i++){ sprintf(buf4, "%s", Ppos2[i].c_str());// 2011 03 10 // sprintf(buf4, "%s", Ppos[i]); // Rprintf("buf4 %s\n", buf4); if(strcmp(buf3, buf4) == 0){ posC = 1; } } if(posC != 1){ // mFreq++; // mF++; p = NULL; posC = 0; continue; } } j = 1; while ( p != NULL ) { if( j == 1){//品詞情報1 str = p; // str.append(","); } else if( j == 7){ if(p == NULL || strcmp(p, "*") == 0){ str = buf1;//元の語形 // str.append(buf1);//元の語形 } else{ // str.append(p); str = p; } pa = m1.find(str);//出てきた形態素原型は既にマップにあるか? if(pa != m1.end()){ pa->second = pa->second + 1; //二つ目の数値を加算 } else{// マップにないなら,新規にマップに追加 m1.insert(make_pair(str, 1));// 1 は 1個目と言う意味 } } p = strtok( NULL,"," ); posC = 0; j++; } } //memset(buf1,'\0',strlen(buf1)); memset(buf1,0,strlen(buf1));// 2017 08 04 memset(buf2,0,strlen(buf2)); // 2017 08 04 }// for }//if }// while(!feof(fp));//while UNPROTECT(pc);//この段階では PC は 1のはず pc--;// ゼロにする fclose(fp); mecab_destroy(mecab); // return(R_NilValue); sprintf(buf3, "[[LESS-THAN-%d]]",mFreq); n = (int)m1.size(); if(n < 1){ Rprintf("empty results\n"); UNPROTECT(pc); return (R_NilValue); } PROTECT(vecName = allocVector(STRSXP, n)); pc++; PROTECT(vecInt = allocVector(INTSXP, n)); pc++; // Rprintf("morphem numbers = %d \n", m1.size()); if(n < 1){ // Rprintf("(000) map length =0\n"); UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, 2)); PROTECT(vecName = lengthgets(vecName, 2)); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_UTF8)); // #endif // // SET_STRING_ELT(vecName, 0, mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, 0, mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[0] = 0; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // // SET_STRING_ELT(vecName, 1, mkChar( "[[TOTAL-TOKENS]]" )); // // </ 2005 11 08> SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); // テキスト総トークン数をセット INTEGER(vecInt)[1] = totalM; SET_NAMES(vecInt, vecName);// UNPROTECT(pc); // Rprintf("(000) OUT \n"); return (vecInt); } pa = m1.begin(); // // PROTECT(mydf = allocVector(VECSXP, 2));//2 列のdata.frame // // pc++; // // SET_VECTOR_ELT(mydf, 0, allocVector(STRSXP, n));//形態素原型 // // SET_VECTOR_ELT(mydf, 1, allocVector(INTSXP, n));// 頻度 // // PROTECT(tmp = mkString("data.frame")); // // pc++; // // //df 内ベクトルの名前を用意 // // PROTECT(varlabels = allocVector(STRSXP, 2)); // // pc++; // // // その単純な初期化 // // SET_STRING_ELT(varlabels, 0, mkChar("Term")); // // SET_STRING_ELT(varlabels, 1, mkChar("Freq")); // Rprintf("(start) length(vecInt) = %d \n",length(vecInt) ); zz = 0;// 実際にベクトルに収納された要素数 // map の内容を vector にして返す for ( z = 0; z < n; z++) { // Rprintf("mFreq - %d ; pa->second = %d \n", mFreq, pa->second ); // // char s [256]; // // strcpy(s, (pa->first).c_str()); // // SET_VECTOR_ELT(VECTOR_ELT(mydf, 0), z, mkChar((pa->first).c_str())); // // INTEGER(VECTOR_ELT(mydf,1))[z] = pa->second;// 最後に頻度情報 if( (pa->second) < mFreq){ mF = mF + (pa->second); } else{ // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz, mkCharCE((pa->first).c_str(), CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz, mkCharCE((pa->first).c_str() , CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz, mkCharCE((pa->first).c_str() , CE_UTF8)); // #endif // //SET_STRING_ELT(vecName, zz, mkChar((pa->first).c_str() )); // 形態素情報をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz, mkCharCE((pa->first).c_str(), (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz] = (pa->second); zz++; } pa++; }//_end_for ///// sprintf(buf3, "[[LESS-THAN-%d]]",mFreq); // Rprintf("n = %d : zz = %d\n",n ,zz ); if(zz < 1 ){ // Rprintf("(0) zz = %d \n",zz ); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_UTF8)); // #endif // //SET_STRING_ELT(vecName, 0, mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, 0, mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[0] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // //SET_STRING_ELT(vecName, 1, mkChar( "[[TOTAL-TOKENS]]" )); // // </ 2005 11 08> SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); // テキスト総トークン数をセット INTEGER(vecInt)[1] = totalM; UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, 2)); PROTECT(vecName = lengthgets(vecName, 2)); // UNPROTECT(pc); // return(R_NilValue); }else if(zz == n){// 二つ足す // Rprintf("(1) zz = %d \n",zz ); UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, zz+2)); PROTECT(vecName = lengthgets(vecName, zz+2)); // Rprintf("(2) zz = %d \n", zz ); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_UTF8)); // #endif // //SET_STRING_ELT(vecName, zz , mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, zz , mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[zz] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // // SET_STRING_ELT(vecName, zz+1 , mkChar( "[[TOTAL-TOKENS]]" )); //// テキスト総トークン数をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz+1] = totalM; }else if(zz+1 == n){// 二つ足す // Rprintf("(3) zz = %d \n", zz ); UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, zz+2)); PROTECT(vecName = lengthgets(vecName, zz+2)); // Rprintf("(2) zz = %d \n", zz ); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz-1 , mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz-1 , mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz-1 , mkCharCE(buf3, CE_UTF8)); // #endif // //SET_STRING_ELT(vecName, zz-1 , mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, zz-1 , mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[zz-1] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, zz , mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // //SET_STRING_ELT(vecName, zz , mkChar( "[[TOTAL-TOKENS]]" )); //// テキスト総トークン数をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz , mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz] = totalM; }else if(zz+2 == n){// 一つ足す // Rprintf("(4) zz = %d \n", zz ); UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, zz+2)); PROTECT(vecName = lengthgets(vecName, zz+2)); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_UTF8)); // #endif // // SET_STRING_ELT(vecName, zz , mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, zz , mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[zz] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // //SET_STRING_ELT(vecName, zz+1 , mkChar( "[[TOTAL-TOKENS]]" )); //// テキスト総トークン数をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz+1] = totalM; }else if(zz +2 < n){ // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz, mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz, mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz, mkCharCE(buf3, CE_UTF8)); // #endif // // SET_STRING_ELT(vecName, zz, mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, zz, mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[zz] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz+1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz+1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, zz+1, mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // // SET_STRING_ELT(vecName, zz+1, mkChar( "[[TOTAL-TOKENS]]" )); // テキスト総トークン数をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz+1, mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz+1] = totalM; UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, zz+2)); PROTECT(vecName = lengthgets(vecName, zz+2)); } zz = 0; mF = 0; totalM = 0; // Rprintf("* "); // // データフレームオブジェクト mydf の属性設定 // // setAttrib(mydf, R_ClassSymbol, tmp); // // setAttrib(mydf, R_NamesSymbol, varlabels); // // // 行名を指定.必須 // // PROTECT(row_names = allocVector(STRSXP, n)); // // pc++; // // char labelbuff[n]; // // for (int z = 0; z < n; z++) { // // sprintf(labelbuff, "%d", z+1); // // SET_STRING_ELT(row_names, z, mkChar(labelbuff)); // // } // // setAttrib(mydf, R_RowNamesSymbol, row_names); SET_NAMES(vecInt, vecName);// UNPROTECT(pc); return (vecInt); } return(R_NilValue); } }// end_extern ///////////////////////////////////////////////
[ "ishida.motohiro@tokushima-u.ac.jp" ]
ishida.motohiro@tokushima-u.ac.jp
593dcabd1348a48eea41a4e863d7d0595a9a030b
90d39aa2f36783b89a17e0687980b1139b6c71ce
/SPOJ/BOOKS1.cpp
aa3a89f41208fd13f4b286a710faee88262e8004
[]
no_license
nims11/coding
634983b21ad98694ef9badf56ec8dfc950f33539
390d64aff1f0149e740629c64e1d00cd5fb59042
refs/heads/master
2021-03-22T08:15:29.770903
2018-05-28T23:27:37
2018-05-28T23:27:37
247,346,971
4
0
null
null
null
null
UTF-8
C++
false
false
1,717
cpp
/* Nimesh Ghelani (nims11) */ #include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<map> #include<string> #include<vector> #include<queue> #include<cmath> #include<stack> #include<utility> #define in_T int t;for(scanf("%d",&t);t--;) #define in_I(a) scanf("%d",&a) #define in_F(a) scanf("%lf",&a) #define in_L(a) scanf("%lld",&a) #define in_S(a) scanf("%s",a) #define newline printf("\n") #define MAX(a,b) a>b?a:b #define MIN(a,b) a<b?a:b #define SWAP(a,b) {int tmp=a;a=b;b=tmp;} #define P_I(a) printf("%d",a) using namespace std; int m,k; int p[500]; vector<int>ans; bool possible(int size, bool print = false) { if(print)ans.clear(); int curr=0; for(int i=0;i<k-1;i++) { int sum=0; while(curr<m-k+i+1 && sum+p[curr]<=size) { if(print)ans.push_back(p[curr]); sum+=p[curr]; curr++; } if(print)ans.push_back(-1); } int sum2=0; while(curr<m) { if(print)ans.push_back(p[curr]); sum2+=p[curr++]; } if(print) for(int i=ans.size()-1;i>=0;i--) { if(ans[i]!=-1)printf("%d ",ans[i]); else printf("/ "); } if(print) newline; if(sum2>size)return false; return true; } int main() { in_T { in_I(m);in_I(k); int start=0,end=0; for(int i=m-1;i>=0;i--) { in_I(p[i]); start = max(start,p[i]); end +=p[i]; } while(start<end) { int mid = (start+end)/2; if(possible(mid)) { end = mid; }else start = mid+1; } possible(start,true); } }
[ "nimeshghelani@gmail.com" ]
nimeshghelani@gmail.com
747609b8c6187b661b33e0dca0d1d28edc801e7f
693d9feddd6d151173b7bb6753681f2bab6e3dd0
/src/servidor/modelo/fisicas/transformaciones/Reubicar.cpp
9a0c8e876cd78ecda32ad2e0f44697ee3f6677b5
[]
no_license
mateoicalvo/micromachines_cpp
e2e02971f0c170ec1054bf6642b263ef0fe5ebf6
06e6f608ff7ca00435a605aba2f6d0072079b913
refs/heads/main
2023-02-15T23:48:08.912214
2021-01-14T10:19:46
2021-01-14T10:19:46
329,439,942
0
0
null
null
null
null
UTF-8
C++
false
false
651
cpp
#include "includes/servidor/modelo/fisicas/transformaciones/Reubicar.h" #include "includes/3rd-party/Box2D/Box2D.h" #include "includes/servidor/modelo/movimiento/Posicion.h" #ifndef DEGTORAD #define DEGTORAD 0.0174532925199432957f #define RADTODEG 57.295779513082320876f #endif Reubicar::Reubicar(Fisicas& fisicas, b2Body* cuerpo, Posicion& posicion) : Transformacion(fisicas), cuerpo_(cuerpo), posicion_(posicion) { } void Reubicar::aplicar() { cuerpo_->SetTransform(b2Vec2(posicion_.x_, posicion_.y_), (float)posicion_.anguloDeg_*DEGTORAD); cuerpo_->SetLinearVelocity(b2Vec2(0, 0)); cuerpo_->SetAngularVelocity(0.0f); }
[ "macalvo@fi.uba.ar" ]
macalvo@fi.uba.ar
4647cfcf4d3761b0c0da56b8afd29e5e4d5c72ad
ca6ad207254acd23b8cb56aec2bb30951c52a949
/src/core/framework/ui/portable/SpriteBatcher.cpp
cef0a591ecd408092192c361e38cbffee67d727e
[]
no_license
sgowen/GGJ17
30c049f2faa491f232835d3410458f35206d15cc
eee3863538754b3cfdba95827afcce09b58c937a
refs/heads/master
2022-05-02T08:40:34.973728
2022-04-26T21:16:43
2022-04-26T21:16:43
79,612,785
1
0
null
null
null
null
UTF-8
C++
false
false
252
cpp
// // SpriteBatcher.cpp // noctisgames-framework // // Created by Stephen Gowen on 9/25/14. // Copyright (c) 2017 Noctis Games. All rights reserved. // #include "SpriteBatcher.h" SpriteBatcher::SpriteBatcher() : m_iNumSprites(0) { // Empty }
[ "dev.sgowen@gmail.com" ]
dev.sgowen@gmail.com
7b10f8e4433e74622d38f2cf902843613cf92da1
375a52f863fd4d3fbd5c993edb22185c26fd9c84
/Build3DProject/GLWidget.cpp
eb0c542b13ad23db7802eb395528dd0c7ac4c398
[]
no_license
anguszhou/Build3D
5c5bf07994fd74f397a85e7274d08d0d01feab1b
4867851513320c2ae1e017e0d24e9f832884160f
refs/heads/master
2021-01-10T19:03:37.311235
2014-02-18T01:52:04
2014-02-18T01:52:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,787
cpp
#include "glwidget.h" #include <QtCore> #include <QtOpenGL> #include <time.h> #ifndef GL_MULTISAMPLE #define GL_MULTISAMPLE 0x809D #endif #define GL_PI 3.1415926 #define GL_RADIUX 0.2f #define glGUI ((QSplatWin32GUI *) theQSplatGUI) GLWidget::GLWidget(QGLWidget *parent) : QGLWidget(parent) { makeCurrent(); fullscreen = false; int whichDriver; theQSplatGUI = new QSplatWin32GUI(); bool a = strncmp((char *)glGetString(GL_VENDOR), "Microsoft", 9); theQSplatGUI->whichDriver = strncmp((char *)glGetString(GL_VENDOR), "Microsoft", 9) ? OPENGL_POINTS : SOFTWARE_BEST ; float framerate = ((int)whichDriver >= (int)SOFTWARE_GLDRAWPIXELS) ? 4.0f : 8.0f; theQSplatGUI->set_desiredrate(framerate); } void GLWidget::initializeGL() { makeCurrent(); } /* double GLWidget::CalFrameRate(){ static int count; static double save; static clock_t last, current; double timegap; ++count; if(count <= 50){ return save; } count = 0 ; current = clock(); timegap = (current - last) / (double)CLK_TCK; qDebug()<<"current - last : "<<current - last<<" , CLK_TCK"<<CLK_TCK; save = 50.0 / timegap; return save; } */ double GLWidget::CalFrameRate(){ static float framePerSecond = 0.0f; static float lastTime = 0.0f; float returndata ; float currentTime = GetTickCount()* 0.001f; ++framePerSecond; if(currentTime - lastTime > 1.0f){ lastTime = currentTime; qDebug()<<"frame rate is : "<<framePerSecond; returndata = framePerSecond; framePerSecond = 0 ; } return returndata; } void GLWidget::paintGL() { GUI->windowPosX=this->geometry().x(); GUI->windowPosY=this->geometry().y(); GUI->windowHeight = this->height(); GUI->windowWidth = this->width(); GUI->windowBorderY = 0; glReadBuffer(GL_BACK); theQSplatGUI->framePerSecond = CalFrameRate(); theQSplatGUI->redraw(); /* double frameRate = CalFrameRate(); qDebug()<<"frame rate is : "<<frameRate; QPainter painter(this); QPen pen = painter.pen(); pen.setColor(Qt::red); QFont font = painter.font(); font.setPixelSize(50); painter.setPen(pen); painter.setFont(font); painter.drawText(100,100 ,"123123"); */ } void GLWidget::resizeGL(int width, int height) { } void GLWidget::mouseMoveEvent(QMouseEvent *e) { static QSplatGUI::mousebutton this_button = QSplatGUI::NO_BUTTON; //L/M/R button + Ctrl/Shift if(((e->buttons() & Qt::LeftButton)||(e->buttons() & Qt::MidButton)||(e->buttons() & Qt::RightButton)) && ((e->modifiers()==Qt::Key_Control) || (e->modifiers()==Qt::Key_Shift))) { qDebug()<<"L/M/R button + Ctrl/Shift"; this_button = QSplatGUI::LIGHT_BUTTON; }// L + R button else if((e->buttons() & Qt::LeftButton) && (e->buttons() & Qt::RightButton)) { this_button = QSplatGUI::TRANSZ_BUTTON; }//M + R button else if((e->buttons() & Qt::MidButton) && (e->buttons() & Qt::RightButton)) { this_button = QSplatGUI::LIGHT_BUTTON; }//L button else if((e->buttons() & Qt::LeftButton)) { this_button = QSplatGUI::ROT_BUTTON; }//M button else if((e->buttons() & Qt::MidButton)) { this_button = QSplatGUI::TRANSZ_BUTTON; }//R button else if((e->buttons() & Qt::RightButton)) { this_button = QSplatGUI::TRANSXY_BUTTON; }//no button else { this_button = QSplatGUI::NO_BUTTON; } GUI->mouse(e->globalX() - GUI->windowPosX, (GUI->windowHeight - GUI->windowBorderY) - (e->globalY() - GUI->windowPosY ), this_button); updateGL(); } void GLWidget::wheelEvent(QWheelEvent * e) { static QSplatGUI::mousebutton this_button = QSplatGUI::NO_BUTTON; this_button = e->delta() > 0 ? QSplatGUI::UP_WHEEL : QSplatGUI::DOWN_WHEEL; GUI->mouse(e->globalX() - GUI->windowPosX, (GUI->windowHeight - GUI->windowBorderY) - (e->globalY() - GUI->windowPosY ), this_button); updateGL(); } void GLWidget::keyPressEvent(QKeyEvent *e) { }
[ "zhoucong07@gmail.com" ]
zhoucong07@gmail.com
49253809c76f108e98b2afcee193135537c64487
aab7eafab5efae62cb06c3a2b6c26fe08eea0137
/preparetuplesforBDTfinalallvartrigger/MCSigpreparetupleNewL0/src/mainincludebreak.cc
55d5836a79b1b3b9c54a914a419ced08349480db
[]
no_license
Sally27/B23MuNu_backup
397737f58722d40e2a1007649d508834c1acf501
bad208492559f5820ed8c1899320136406b78037
refs/heads/master
2020-04-09T18:12:43.308589
2018-12-09T14:16:25
2018-12-09T14:16:25
160,504,958
0
1
null
null
null
null
UTF-8
C++
false
false
9,477
cc
#include <iostream> #include<sstream> #include<string> #include<vector> #include<fstream> #include "TH1F.h" #include "TH3F.h" #include "TCanvas.h" #include "TFile.h" #include "TTree.h" #include "TLorentzVector.h" #include "TVector3.h" #include "TBranch.h" #include "TRandom.h" #include "TBranch.h" #include "TString.h" #include<algorithm> #include "TTreeFormula.h" #include "alltogetherMC.hpp" #include<iostream> using namespace std; int main(){ ofstream out; out.open("EfficienciesBreakNT.tex"); out<<"\\documentclass[a4paper,11pt]{article}"<<endl; out<<"\\usepackage[pdftex]{graphicx}"<<endl; out<<"\\usepackage{url}"<<endl; out<<"\\usepackage{mathtools}"<<endl; out<<"\\usepackage{amsmath}"<<endl; out<<"\\usepackage{graphicx}"<<endl; out<<"\\usepackage[table]{xcolor}"<<endl; out<<"\\usepackage{amsmath,amssymb}"<<endl; out<<"\\usepackage[top=25mm,bottom=25mm,left=25mm,right=25mm]{geometry}"<<endl; out<<"\\usepackage{colortbl}"<<endl; out<<"\\begin{document}"<<endl; out<<"\\begin{table}[ht]"<<endl; out<<"\\begin{center}"<<endl; out<<"\\begin{tabular}{| l | l | l | l |}"<<endl; out<<"\\hline"<<endl; out<<"Cut & $\\epsilon$ & N & error \\\\ "<<endl; out<<"\\hline"<<endl; double toteff(0); string pathname = "/vols/lhcb/ss4314/tuplesallvar/B23MuNuMCL0/"; string filename = "B23MuMC2012L0data"; string decaytreename = "B23MuNu_Tuple/DecayTree"; string ext = ".root"; string cuttag = "_MCtruth"; string filename2 = (filename+cuttag).c_str(); double decprodcut2 =0.185; double effrecostrip2= 0.111; out << "$\\epsilon_{decprodcut}$ &" << decprodcut2 << " & " << "(3544)10000" << " & "<< (sqrt(double(3544)*(1.0-((double(3544)/double(10000))))))*(1/double(10000))<<" \\\\ "<<endl; out << "$\\epsilon_{reco}$ &" << effrecostrip2 << " & "<<"(124051)1114130" << " & "<< (sqrt(double(124051)*(1.0-((double(124051)/double(1114130))))))*(1/double(1114130)) <<" \\\\ "<<endl; double mctrutheff; mctrutheff=mctruth((pathname+filename).c_str(), decaytreename, (filename2).c_str()); out << "$\\epsilon_{MC}$ &" << mctrutheff <<" - & "<< " - & " << " \\\\ "<<endl; convertbranchname(filename2, "DecayTree", filename2); addqsqinf(filename2, "DecayTree", filename2); addcostheta(filename2, "DecayTree", filename2); double L0eff(0); L0eff=calculateL0effMC(filename2, "DecayTree", "miau"); toteff = L0eff; cutTree((filename2+ext).c_str(),"DecayTree",(filename2+"_L0MuonDecisionTOS"+ext).c_str(),"Bplus_L0MuonDecision_TOS==1.0"); string filenameclean=(filename2+"_L0MuonDecisionTOS").c_str(); string file=(filename2+"_L0MuonDecisionTOS").c_str(); out << "$\\epsilon_{L0}$ &" << L0eff <<"&"<< getmyentries((filenameclean+ext).c_str(),"DecayTree") << " & " << " \\\\ "<<endl; vector<string> varia; varia.push_back("trigger"); varia.push_back("qmincut"); vector<string> vals; vals.push_back("(Bplus_Hlt1TrackMuonDecision_TOS==1.0) && ((Bplus_Hlt2TopoMu2BodyBBDTDecision_TOS==1.0) || (Bplus_Hlt2TopoMu3BodyBBDTDecision_TOS==1.0) || (Bplus_Hlt2DiMuonDetachedDecision_TOS==1.0) || (Bplus_Hlt2DiMuonDetachedHeavyDecision_TOS==1.0))"); vals.push_back("minq2 < 960400"); for(int i(0);i<1;i++) { double eff; double error; int numofentriesbefore; int numofentriesafter; eff=cutTree((filenameclean+ext).c_str(), "DecayTree", (filenameclean+"_"+varia.at(i)+ext).c_str(), (vals.at(i)).c_str()); numofentriesbefore= getmyentries((filenameclean+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filenameclean+"_"+varia.at(i)+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out<<"$\\epsilon_{"+varia.at(i)+"}$ & "<<eff<<" & "<<numofentriesafter<<" & "<<error<<" \\\\ "<<endl; filenameclean=(filenameclean+"_"+varia.at(i)).c_str(); toteff=toteff*eff; } double jpsieff; jpsieff=Jpsi((filenameclean).c_str(), "DecayTree", (filenameclean+"_Jpsi").c_str()); double error; int numofentriesbefore; int numofentriesafter; numofentriesbefore= getmyentries((filenameclean+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filenameclean+"_Jpsi"+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out << "$\\epsilon_{Jpsi}$ &" << jpsieff<<" & "<<numofentriesafter<<" & "<<error << " \\\\ "<<endl; toteff=toteff*jpsieff; filenameclean=(filenameclean+"_Jpsi").c_str(); for(int i(1);i<2;i++) { double eff; double error; int numofentriesbefore; int numofentriesafter; eff=cutTree((filenameclean+ext).c_str(), "DecayTree", (filenameclean+"_"+varia.at(i)+ext).c_str(), (vals.at(i)).c_str()); numofentriesbefore= getmyentries((filenameclean+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filenameclean+"_"+varia.at(i)+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out<<"$\\epsilon_{"+varia.at(i)+"}$ & "<<eff<<" & "<<numofentriesafter<<" & "<<error<<" \\\\ "<<endl; filenameclean=(filenameclean+"_"+varia.at(i)).c_str(); toteff=toteff*eff; } out<<"\\hline"<<endl; out<<"$\\epsilon_{totaleff}$ & "<<toteff<<" \\\\ "<<endl; out<<"\\hline"<<endl; addKFoldandW(filenameclean, "DecayTree", filenameclean); vals.push_back("Bplus_Hlt1TrackMuonDecision_TOS==1.0"); vals.push_back("(Bplus_Hlt2TopoMu2BodyBBDTDecision_TOS==1.0) || (Bplus_Hlt2TopoMu3BodyBBDTDecision_TOS==1.0) || (Bplus_Hlt2DiMuonDetachedDecision_TOS==1.0) || (Bplus_Hlt2DiMuonDetachedHeavyDecision_TOS==1.0)"); varia.push_back("Hlt1TrackMuonDecisionTOS"); varia.push_back("Hlt2orofDecisions"); string filename3=(file).c_str(); for(int i(2);i<4;i++) { double error; int numofentriesbefore; int numofentriesafter; double eff; eff=cutTree((filename3+ext).c_str(), "DecayTree", (filename3+"_"+varia.at(i)+ext).c_str(), (vals.at(i)).c_str()); numofentriesbefore= getmyentries((filename3+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filename3+"_"+varia.at(i)+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out<<vals.at(i)+" & "<<eff<<" & "<<numofentriesafter<<" & "<<error<<" \\\\ "<<endl; filename3=(filename3+"_"+varia.at(i)).c_str(); } out<<"\\hline"<<endl; vals.push_back("Bplus_Hlt2TopoMu2BodyBBDTDecision_TOS==1.0"); vals.push_back("Bplus_Hlt2TopoMu3BodyBBDTDecision_TOS==1.0"); vals.push_back("Bplus_Hlt2DiMuonDetachedDecision_TOS==1.0"); vals.push_back("Bplus_Hlt2DiMuonDetachedHeavyDecision_TOS==1.0"); varia.push_back("Hlt2TopoMu2BodyBBDTDecision"); varia.push_back("Hlt2TopoMu3BodyBBDTDecision"); varia.push_back("Hlt2DiMuonDetachedDecision"); varia.push_back("Hlt2DiMuonDetachedHeavyDecision"); string filename4=(file+"_Hlt1TrackMuonDecisionTOS").c_str(); for(int i(4);i<8;i++) { double error; int numofentriesbefore; int numofentriesafter; double eff; eff=cutTree((filename4+ext).c_str(), "DecayTree", (filename4+"_"+varia.at(i)+ext).c_str(), (vals.at(i)).c_str()); numofentriesbefore= getmyentries((filename4+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filename4+"_"+varia.at(i)+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out<<vals.at(i)+" & "<<eff<<" & "<<numofentriesafter<<" & "<<error<<" \\\\ "<<endl; } out<<"\\hline"<<endl; double brfr=1e-8; double ppbbX=284e-6; double bBplus= 2*0.4; double datacoll=3e15; double decprodcut =0.185; double effrecostrip= 0.111; double finalnum; finalnum=ppbbX*bBplus*brfr*datacoll*decprodcut*effrecostrip*toteff; out<<"TotSig asuming 10$^-8$ & "<<finalnum<<" \\\\ "<<endl; out<<" \\\\ "<<endl; out<<"\\hline"<<endl; out<<"\\end{tabular}"<<endl; out<<"\\end{center}"<<endl; out<<"\\caption{EFFICIENCIESMCSIG.txt}"<<endl; out<<"\\end{table}"<<endl; out<<"\\end{document}"<<endl; out.close(); // cout<<mctrutheff*jpsieff*nSharedeff*qmineff<<endl; // double brfr=1e-8; // double ppbbX=284e-6; // double bBplus= 2*0.4; // double datacoll=3e15; // double decprodcut =0.185; // double effrecostrip= 0.111; // // double finaleff; // finaleff=ppbbX*bBplus*brfr*datacoll*decprodcut*effrecostrip*jpsieff*nSharedeff*qmineff*triggereff; // cout<<"Final Num Of Events: "<<finaleff<<endl; return(0); }
[ "ss4314@ss4314-laptop.hep.ph.ic.ac.uk" ]
ss4314@ss4314-laptop.hep.ph.ic.ac.uk
3711faf1f6c02f323de756c2e0452ed7bbe95aec
21f553e7941c9e2154ff82aaef5e960942f89387
/include/algorithms/neural_networks/layers/fullyconnected/fullyconnected_layer_backward.h
94f96c7047aab261a07873b287a9ab157a3c88de
[ "Apache-2.0", "Intel" ]
permissive
tonythomascn/daal
7e6fe4285c7bb640cc58deb3359d4758a9f5eaf5
3e5071f662b561f448e8b20e994b5cb53af8e914
refs/heads/daal_2017_update2
2021-01-19T23:05:41.968161
2017-04-19T16:18:44
2017-04-19T16:18:44
88,920,723
1
0
null
2017-04-20T23:54:18
2017-04-20T23:54:18
null
UTF-8
C++
false
false
8,487
h
/* file: fullyconnected_layer_backward.h */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * * 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. *******************************************************************************/ /* //++ // Implementation of the interface for the backward fully-connected layer // in the batch processing mode //-- */ #ifndef __FULLYCONNECTED_LAYER_BACKWARD_H__ #define __FULLYCONNECTED_LAYER_BACKWARD_H__ #include "algorithms/algorithm.h" #include "data_management/data/tensor.h" #include "services/daal_defines.h" #include "algorithms/neural_networks/layers/layer.h" #include "algorithms/neural_networks/layers/fullyconnected/fullyconnected_layer_types.h" #include "algorithms/neural_networks/layers/fullyconnected/fullyconnected_layer_backward_types.h" namespace daal { namespace algorithms { namespace neural_networks { namespace layers { namespace fullyconnected { namespace backward { namespace interface1 { /** * @defgroup fullyconnected_backward_batch Batch * @ingroup fullyconnected_backward * @{ */ /** * <a name="DAAL-CLASS-ALGORITHMS__NEURAL_NETWORKS__LAYERS__FULLYCONNECTED__BACKWARD__BATCHCONTAINER"></a> * \brief Provides methods to run implementations of the of the backward fully-connected layer * This class is associated with the daal::algorithms::neural_networks::layers::fullyconnected::backward::Batch class * and supports the method of backward fully-connected layer computation in the batch processing mode * * \tparam algorithmFPType Data type to use in intermediate computations of backward fully-connected layer, double or float * \tparam method Computation method of the layer, \ref daal::algorithms::neural_networks::layers::fullyconnected::Method * \tparam cpu Version of the cpu-specific implementation of the layer, \ref daal::CpuType */ template<typename algorithmFPType, Method method, CpuType cpu> class DAAL_EXPORT BatchContainer : public AnalysisContainerIface<batch> { public: /** * Constructs a container for the backward fully-connected layer with a specified environment * in the batch processing mode * \param[in] daalEnv Environment object */ BatchContainer(daal::services::Environment::env *daalEnv); /** Default destructor */ ~BatchContainer(); /** * Computes the result of the backward fully-connected layer in the batch processing mode */ void compute() DAAL_C11_OVERRIDE; }; /** * <a name="DAAL-CLASS-ALGORITHMS__NEURAL_NETWORKS__LAYERS__FULLYCONNECTED__BACKWARD__BATCH"></a> * \brief Provides methods for backward fully-connected layer computations in the batch processing mode * \n<a href="DAAL-REF-FULLYCONNECTEDBACKWARD-ALGORITHM">Backward fully-connected layer description and usage models</a> * * \tparam algorithmFPType Data type to use in intermediate computations of backward fully-connected layer, double or float * \tparam method Computation method of the layer, \ref Method * * \par Enumerations * - \ref Method Computation methods for the backward fully-connected layer * - \ref LayerDataId Identifiers of input objects for the backward fully-connected layer * * \par References * - forward::interface1::Batch class */ template<typename algorithmFPType = float, Method method = defaultDense> class Batch : public layers::backward::LayerIface { public: Parameter &parameter; /*!< \ref interface1::Parameter "Parameters" of the layer */ Input input; /*!< %Input objects of the layer */ /** * Constructs backward fully-connected layer * \param[in] nOutputs A number of layer outputs */ Batch(const size_t nOutputs) : _defaultParameter(nOutputs), parameter(_defaultParameter) { initialize(); }; /** * Constructs a backward fully-connected layer in the batch processing mode * and initializes its parameter with the provided parameter * \param[in] parameter Parameter to initialize the parameter of the layer */ Batch(Parameter& parameter) : parameter(parameter), _defaultParameter(parameter) { initialize(); } /** * Constructs backward fully-connected layer by copying input objects and parameters of another fully-connected layer * \param[in] other A layer to be used as the source to initialize the input objects * and parameters of this layer */ Batch(const Batch<algorithmFPType, method> &other): _defaultParameter(other.parameter), parameter(_defaultParameter) { initialize(); input.set(layers::backward::inputGradient, other.input.get(layers::backward::inputGradient)); input.set(layers::backward::inputFromForward, other.input.get(layers::backward::inputFromForward)); } /** * Returns computation method of the layer * \return Computation method of the layer */ virtual int getMethod() const DAAL_C11_OVERRIDE { return(int) method; } /** * Returns the structure that contains input objects of fully-connected layer * \return Structure that contains input objects of fully-connected layer */ virtual Input *getLayerInput() DAAL_C11_OVERRIDE { return &input; } /** * Returns the structure that contains parameters of the backward fully-connected layer * \return Structure that contains parameters of the backward fully-connected layer */ virtual Parameter *getLayerParameter() DAAL_C11_OVERRIDE { return &parameter; }; /** * Returns the structure that contains results of fully-connected layer * \return Structure that contains results of fully-connected layer */ services::SharedPtr<layers::backward::Result> getLayerResult() DAAL_C11_OVERRIDE { return getResult(); } /** * Returns the structure that contains results of fully-connected layer * \return Structure that contains results of fully-connected layer */ services::SharedPtr<Result> getResult() { return _result; } /** * Registers user-allocated memory to store results of fully-connected layer * \param[in] result Structure to store results of fully-connected layer */ void setResult(const services::SharedPtr<Result>& result) { DAAL_CHECK(result, ErrorNullResult) _result = result; _res = _result.get(); } /** * Returns a pointer to the newly allocated fully-connected layer * with a copy of input objects and parameters of this fully-connected layer * \return Pointer to the newly allocated layer */ services::SharedPtr<Batch<algorithmFPType, method> > clone() const { return services::SharedPtr<Batch<algorithmFPType, method> >(cloneImpl()); } /** * Allocates memory to store the result of the backward fully-connected layer */ virtual void allocateResult() DAAL_C11_OVERRIDE { this->_result->template allocate<algorithmFPType>(&(this->input), &parameter, (int) method); this->_res = this->_result.get(); } protected: virtual Batch<algorithmFPType, method> *cloneImpl() const DAAL_C11_OVERRIDE { return new Batch<algorithmFPType, method>(*this); } void initialize() { Analysis<batch>::_ac = new __DAAL_ALGORITHM_CONTAINER(batch, BatchContainer, algorithmFPType, method)(&_env); input = fullyconnected::backward::Input(); _in = &input; _par = &parameter; _result = services::SharedPtr<Result>(new Result()); } private: services::SharedPtr<Result> _result; Parameter _defaultParameter; }; /** @} */ } // namespace interface1 using interface1::BatchContainer; using interface1::Batch; } // namespace backward } // namespace fullyconnected } // namespace layers } // namespace neural_networks } // namespace algorithms } // namespace daal #endif
[ "vasily.rubtsov@intel.com" ]
vasily.rubtsov@intel.com
5ac62918490a8a0d8ddd5477426003aaa55f1da6
16db2176f14d67f7e270c8ccfb263c2cc4bd90fa
/Linked List/Doubly Linked list/del_end.cpp
8ad8d8f9d98f3227d0bfa8fd26858c551de3eb54
[]
no_license
Anantm007/Ds-Algo-Programs
7416348a3a3d6f7df1761db6319ab425ea7d4431
fb2ae5b2b5fa89837c653e08e196c53db647b04d
refs/heads/master
2023-02-18T04:21:10.039700
2021-01-21T08:35:43
2021-01-21T08:35:43
330,117,532
0
0
null
null
null
null
UTF-8
C++
false
false
1,564
cpp
#include <iostream> using namespace std; struct node { int n; node *next; node *prev; node (int d) { n = d; next = NULL; prev = NULL; } }; // O (n) node *ins_end (node *head, int data) { node *temp = new node (data); if (head == NULL) { return temp; } node *cur = head; while (cur -> next != NULL) { cur = cur -> next; } cur -> next = temp; temp -> prev = cur; return head; } // O (1) node *del_head (node *head) { if (head == NULL || head -> next == NULL) { return NULL; } node *temp = head; head = head -> next; head ->prev = NULL; delete temp; return head; } // O (n) node *del_end (node *head) { if (head == NULL || head -> next == NULL) { return NULL; } node *cur = head; while (cur -> next -> next != NULL) { cur = cur -> next; } node *temp = cur -> next; cur -> next = NULL; delete temp; return head; } void print (node *head) { while (head != NULL) { cout << head -> n << " "; head = head -> next; } } int main() { node *head = NULL; head = ins_end (head, 10); head = ins_end (head, 20); head = ins_end (head, 30); head = ins_end (head, 40); print (head); head = del_end (head); cout << "\n"; print (head); head = ins_end (head, 50); head = ins_end (head, 60); cout << "\n"; print (head); head = del_end (head); cout << "\n"; print (head); return 0; }
[ "anant.mathur007@gmail.com" ]
anant.mathur007@gmail.com
c0e5b8853a72fb102664c29f6996d7bef2b4caae
47c1438e4eabe800987865b8bdaad3a9a70ab172
/utils/utils.hpp
a56c6915da9fcd7e9bc37b5481269f5ec4554961
[]
no_license
gongcm/Server
323bf8c1a6938bc5e5734440bbf25eb8fcaffb5b
07b4d6a519135a6fb4f418064839ae51cf951614
refs/heads/master
2020-03-15T15:30:00.767247
2018-05-05T11:31:42
2018-05-05T11:31:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
375
hpp
#include <iostream> #include <sys/stat.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/shm.h> #include <sys/utsname.h> #include <dirent.h> class utils{ public: static int getSystemVersion(); static int getFilelist(char * path,list_t &list); };
[ "gcm1994g@163.com" ]
gcm1994g@163.com
d95c7fd09908b17bf398d12ef6c445a1da98dfca
94eefa5c297a427cf52d2cdd9852fbc74605a76d
/Exercise4.h
d4b7d1d4f5f16a8e4647a956f095578adac71130
[]
no_license
calderona/ZAnalyisis
f78f62ec19794f043da721ba33a2d0702364fc5a
2ca9fb15b61a87ff3c60618a7e963414d07cdd90
refs/heads/master
2021-01-22T11:37:16.942535
2014-10-17T10:42:11
2014-10-17T10:42:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,621
h
////////////////////////////////////////////////////////// // Universidad de Cantabria // Ciencias Físicas - Partículas // Curso 2014 - 2015 // EXERCISE NUMBER 4 :: Analysis de datos del detector de partículas CMS // Author: Alicia Calderon // 07 October 2014 - Version v1.2 // Root version 5.30.06 ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // // ================= NOMBRE ALUMNO: // ////////////////////////////////////////////////////////// #ifndef EXERCISE4_H #define EXERCISE4_H #include <TH2.h> #include <TH1.h> #include <TROOT.h> #include <TBranch.h> class Exercise4 { public: Exercise4(TTree *tree, bool save, string sample); ~Exercise4(); //--- INITIALIZE FUNCTIONS Bool_t IsInitialized() const { return fIsInitialized; } void Initialize(TTree *tree, bool save, string sample); void FillHistograms(Long64_t jentry); bool isGoodMuonISO (int iMu); void SaveHistrograms(bool save, string sample); bool isGoodGLBMuonID (int iMu); //--- DEFINE VARIABLES Int_t Run; Int_t Event; Int_t Lumi; Int_t nPU; vector<bool> *Muon_IsGlobalMuon; vector<bool> *Muon_IsAllTrackerMuons; vector<bool> *Muon_IsAllStandAloneMuons; vector<bool> *Muon_IsTMLastStationAngTight; vector<float> *Muon_Px; vector<float> *Muon_Py; vector<float> *Muon_Pz; vector<float> *Muon_Pt; vector<float> *Muon_deltaPt; vector<float> *Muon_Energy; vector<int> *Muon_Charge; vector<float> *Muon_NormChi2GTrk; vector<int> *Muon_NValidHitsSATrk; vector<int> *Muon_NumOfMatches; vector<float> *Muon_Chi2InTrk; vector<float> *Muon_dofInTrk; vector<int> *Muon_NValidHitsInTrk; vector<int> *Muon_NValidPixelHitsInTrk; vector<float> *Muon_SumIsoCalo; vector<float> *Muon_SumIsoTrack; vector<float> *Muon_dzPV; vector<float> *Muon_IPPV; // List of branches TBranch *b_Run; //! TBranch *b_Event; //! TBranch *b_Lumi; //! TBranch *b_nPU; //! TBranch *b_Muon_IsGlobalMuon; //! TBranch *b_Muon_IsAllTrackerMuons; //! TBranch *b_Muon_IsAllStandAloneMuons; //! TBranch *b_Muon_IsTMLastStationAngTight; //! TBranch *b_Muon_Px; //! TBranch *b_Muon_Py; //! TBranch *b_Muon_Pz; //! TBranch *b_Muon_Pt; //! TBranch *b_Muon_deltaPt; //! TBranch *b_Muon_Energy; //! TBranch *b_Muon_Charge; //! TBranch *b_Muon_NormChi2GTrk; //! TBranch *b_Muon_NValidHitsSATrk; //! TBranch *b_Muon_NumOfMatches; //! TBranch *b_Muon_Chi2InTrk; //! TBranch *b_Muon_dofInTrk; //! TBranch *b_Muon_NValidHitsInTrk; //! TBranch *b_Muon_NValidPixelHitsInTrk; //! TBranch *b_Muon_SumIsoCalo; //! TBranch *b_Muon_SumIsoTrack; //! TBranch *b_Muon_dzPV; //! TBranch *b_Muon_IPPV; //! //--- DEFINE HISTOGRAMS //--- 1D H TH1F *test; TH1F *h_Mu_cutWorkflow; TH1F *h_Mu_pt_all; TH1F *h_Mu_pt_GoodMu; TH1F *h_Mu_eta_all; TH1F *h_Mu_eta_GoodMu; TH1F *h_Mu_InvMass_all; TH1F *h_Mu_InvMass_GoodMu; TH1F *h_Mu_ZInvMass_GlbGlb; TH1F *h_Mu_ZInvMass_StaSta; TH1F *h_Mu_ZInvMass_TkTk; TH1F *h_Mu_ZInvMass_GoodMu; //--- 2D H //--- DEFINE FILES TFile *outputFile; protected: Bool_t fIsInitialized; }; #endif
[ "calderon@cern.ch" ]
calderon@cern.ch
c0313fba7a58c8d1d378ce149c30fe2bc8687822
4a13e4b7dd038ed801cc41e47bbd49b44c23692a
/Cat/Pie.h
9eaff543780efca692580ae1425737188d11af03
[]
no_license
SchemIng/Cat
90fc90f6a56f06bf998159beb2dfd3d822997411
79aea3d2cd283953d6347dc8b591014bb41d9b30
refs/heads/master
2021-01-10T15:34:26.469746
2016-01-04T03:07:57
2016-01-04T03:07:57
48,970,740
0
0
null
null
null
null
UTF-8
C++
false
false
226
h
#pragma once #include "Bill.h" class CPie { public: CPie(CPaintDC* dc, CPoint o, int r); ~CPie(); void Draw(vector<CBill> bills); private: CPoint o; int r; CPaintDC dc; void count(vector<CBill> bills, double* a); };
[ "1055062460@qq.com" ]
1055062460@qq.com
aa4d7853d94585a56c6818a1e0479301c126b674
025c78a4ed41519b08238afb2e6389d29a955893
/ch02/ex202.cpp
9eb1e625923322f398d1d77534a5a552dc6b8682
[]
no_license
ArtemNikolaev/opp-in-cpp
09a92282c56337b994160be66db5f323ee029640
b13373bdbd3b33b1c2953e88c626046f3ca635e7
refs/heads/master
2023-04-01T11:31:43.262127
2021-03-28T13:30:33
2021-03-28T13:30:33
334,686,841
0
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
#include <iostream> #include <iomanip> int main() { std::cout << std::setw(4) << 1990 << std::setw(9) << 135 << std::endl; std::cout << std::setw(4) << 1991 << std::setw(9) << 7290 << std::endl; std::cout << std::setw(4) << 1992 << std::setw(9) << 11300 << std::endl; std::cout << std::setw(4) << 1993 << std::setw(9) << 16200 << std::endl; return 0; }
[ "artem@nikolaev.by" ]
artem@nikolaev.by
4907aa6f867afa7d180a1305084e3f805802e238
768c55006dea03b485c4f6435b7e4888f489f719
/include/AutomappingNode.h
dc60013a25d2d106ffa194123448359e68344406
[]
no_license
red-itmo/box_finder
94288448ce7d7aa7ebffcd99af12442f367a3b4f
9e9503dab38f5eb7de03099d4c51143c5bb23208
refs/heads/master
2021-01-20T20:14:48.359548
2016-07-22T15:50:43
2016-07-22T15:50:43
63,970,233
1
0
null
null
null
null
UTF-8
C++
false
false
858
h
#ifndef _AUTOMAPPINGNODE_ #define _AUTOMAPPINGNODE_ #include <RobotClass.hpp> #include <nav_msgs/GetPlan.h> #include <box_finder/GetGoal.h> #include <cstdlib> #include <vector> #include <fstream> #define EQUAL(A, B) A.x == B.x && A.y == B.y #define ISNULL(A) A.x == 0.0 && A.y == 0.0 && A.z == 0.0 && A.w == 0.0 class AutomappingNode{ ros::NodeHandle nh, nh_for_params; RobotClass robot; ros::ServiceClient goal_requester, pathfinder; double safe_distance, tolerance, rotational_speed; std::string map_name, pose_params_file_name; geometry_msgs::PoseStamped safeGoalInPlan(const nav_msgs::Path &plan); double distanceBetweenPoses(const geometry_msgs::PoseStamped &pose1, const geometry_msgs::PoseStamped &pose2); public: AutomappingNode(); ~AutomappingNode(); void doYourWork(); }; #endif //_AUTOMAPPINGNODE_
[ "antonovspostbox@gmail.com" ]
antonovspostbox@gmail.com
14aa1ddfc8beba4bec0a50896b65f2703c446c11
5d2343977bd25cae2c43addf2e19dd027a7ae198
/Codeforces/CR630/c.cpp
c3b7dd2d77ead4093108900a255e0b966681a831
[]
no_license
ayushgupta2959/CodeReview
5ea844d180992ee80ba1f189af2ab3b0be90f5ce
7d8a5a6610c9227e458c6fda0bbc5885301788d8
refs/heads/master
2021-08-22T13:07:59.314076
2020-04-26T14:30:08
2020-04-26T14:30:08
173,270,707
1
0
null
null
null
null
UTF-8
C++
false
false
720
cpp
#include <bits/stdc++.h> using namespace std; #define sp ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) #define v(t) vector<t> #define vv(t) vector<vector<t>> #define vn(t,n,val) vector<t>(n,val) #define vvn(t,r,c,val) vector<vector<t>>(r, vector<t>(c,val)) #define vvv(t) vector<vector<vector<t>>> #define vvvn(t,l,b,h,val) vector<vector<vector<t>>>(l,vector<vector<t>>(b,vector<t>(h))) void solve(){ int n,k; string s; cin>>n>>k>>s; } int main() { sp; ////////////////To Remove////////////// freopen("../../input.txt", "r", stdin); freopen("../../output.txt", "w", stdout); /////////////////////////////////////// int t; cin>>t; while(t--){ solve(); cout<<"\n"; } return 0; }
[ "37008291+ayushgupta2959@users.noreply.github.com" ]
37008291+ayushgupta2959@users.noreply.github.com
16134ee8a40bb7c4bcbddb21ae296c2b61773ec6
38c10c01007624cd2056884f25e0d6ab85442194
/extensions/common/manifest_test.cc
37034b5927e2c313389bc3889ad80d35a0d61e00
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
9,032
cc
// Copyright (c) 2012 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 "extensions/common/manifest_test.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/path_service.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/values.h" #include "extensions/common/extension_l10n_util.h" #include "extensions/common/extension_paths.h" #include "extensions/common/test_util.h" #include "ui/base/l10n/l10n_util.h" namespace extensions { namespace { // |manifest_path| is an absolute path to a manifest file. base::DictionaryValue* LoadManifestFile(const base::FilePath& manifest_path, std::string* error) { base::FilePath extension_path = manifest_path.DirName(); EXPECT_TRUE(base::PathExists(manifest_path)) << "Couldn't find " << manifest_path.value(); JSONFileValueDeserializer deserializer(manifest_path); base::DictionaryValue* manifest = static_cast<base::DictionaryValue*>( deserializer.Deserialize(NULL, error).release()); // Most unit tests don't need localization, and they'll fail if we try to // localize them, since their manifests don't have a default_locale key. // Only localize manifests that indicate they want to be localized. // Calling LocalizeExtension at this point mirrors file_util::LoadExtension. if (manifest && manifest_path.value().find(FILE_PATH_LITERAL("localized")) != std::string::npos) extension_l10n_util::LocalizeExtension(extension_path, manifest, error); return manifest; } } // namespace ManifestTest::ManifestTest() : enable_apps_(true) { } ManifestTest::~ManifestTest() { } // Helper class that simplifies creating methods that take either a filename // to a manifest or the manifest itself. ManifestTest::ManifestData::ManifestData(const char* name) : name_(name), manifest_(NULL) { } ManifestTest::ManifestData::ManifestData(base::DictionaryValue* manifest, const char* name) : name_(name), manifest_(manifest) { CHECK(manifest_) << "Manifest NULL"; } ManifestTest::ManifestData::ManifestData( scoped_ptr<base::DictionaryValue> manifest) : manifest_(manifest.get()), manifest_holder_(manifest.Pass()) { CHECK(manifest_) << "Manifest NULL"; } ManifestTest::ManifestData::ManifestData(const ManifestData& m) { NOTREACHED(); } ManifestTest::ManifestData::~ManifestData() { } base::DictionaryValue* ManifestTest::ManifestData::GetManifest( base::FilePath test_data_dir, std::string* error) const { if (manifest_) return manifest_; base::FilePath manifest_path = test_data_dir.AppendASCII(name_); manifest_ = LoadManifestFile(manifest_path, error); manifest_holder_.reset(manifest_); return manifest_; } std::string ManifestTest::GetTestExtensionID() const { return std::string(); } base::FilePath ManifestTest::GetTestDataDir() { base::FilePath path; PathService::Get(DIR_TEST_DATA, &path); return path.AppendASCII("manifest_tests"); } scoped_ptr<base::DictionaryValue> ManifestTest::LoadManifest( char const* manifest_name, std::string* error) { base::FilePath manifest_path = GetTestDataDir().AppendASCII(manifest_name); return make_scoped_ptr(LoadManifestFile(manifest_path, error)); } scoped_refptr<Extension> ManifestTest::LoadExtension( const ManifestData& manifest, std::string* error, extensions::Manifest::Location location, int flags) { base::FilePath test_data_dir = GetTestDataDir(); base::DictionaryValue* value = manifest.GetManifest(test_data_dir, error); if (!value) return NULL; return Extension::Create(test_data_dir.DirName(), location, *value, flags, GetTestExtensionID(), error); } scoped_refptr<Extension> ManifestTest::LoadAndExpectSuccess( const ManifestData& manifest, extensions::Manifest::Location location, int flags) { std::string error; scoped_refptr<Extension> extension = LoadExtension(manifest, &error, location, flags); EXPECT_TRUE(extension.get()) << manifest.name(); EXPECT_EQ("", error) << manifest.name(); return extension; } scoped_refptr<Extension> ManifestTest::LoadAndExpectSuccess( char const* manifest_name, extensions::Manifest::Location location, int flags) { return LoadAndExpectSuccess(ManifestData(manifest_name), location, flags); } scoped_refptr<Extension> ManifestTest::LoadAndExpectWarning( const ManifestData& manifest, const std::string& expected_warning, extensions::Manifest::Location location, int flags) { std::string error; scoped_refptr<Extension> extension = LoadExtension(manifest, &error, location, flags); EXPECT_TRUE(extension.get()) << manifest.name(); EXPECT_EQ("", error) << manifest.name(); EXPECT_EQ(1u, extension->install_warnings().size()); EXPECT_EQ(expected_warning, extension->install_warnings()[0].message); return extension; } scoped_refptr<Extension> ManifestTest::LoadAndExpectWarning( char const* manifest_name, const std::string& expected_warning, extensions::Manifest::Location location, int flags) { return LoadAndExpectWarning( ManifestData(manifest_name), expected_warning, location, flags); } void ManifestTest::VerifyExpectedError( Extension* extension, const std::string& name, const std::string& error, const std::string& expected_error) { EXPECT_FALSE(extension) << "Expected failure loading extension '" << name << "', but didn't get one."; EXPECT_TRUE(base::MatchPattern(error, expected_error)) << name << " expected '" << expected_error << "' but got '" << error << "'"; } void ManifestTest::LoadAndExpectError( const ManifestData& manifest, const std::string& expected_error, extensions::Manifest::Location location, int flags) { std::string error; scoped_refptr<Extension> extension( LoadExtension(manifest, &error, location, flags)); VerifyExpectedError(extension.get(), manifest.name(), error, expected_error); } void ManifestTest::LoadAndExpectError( char const* manifest_name, const std::string& expected_error, extensions::Manifest::Location location, int flags) { return LoadAndExpectError( ManifestData(manifest_name), expected_error, location, flags); } void ManifestTest::AddPattern(extensions::URLPatternSet* extent, const std::string& pattern) { int schemes = URLPattern::SCHEME_ALL; extent->AddPattern(URLPattern(schemes, pattern)); } ManifestTest::Testcase::Testcase(const std::string& manifest_filename, const std::string& expected_error, extensions::Manifest::Location location, int flags) : manifest_filename_(manifest_filename), expected_error_(expected_error), location_(location), flags_(flags) {} ManifestTest::Testcase::Testcase(const std::string& manifest_filename, const std::string& expected_error) : manifest_filename_(manifest_filename), expected_error_(expected_error), location_(extensions::Manifest::INTERNAL), flags_(Extension::NO_FLAGS) {} ManifestTest::Testcase::Testcase(const std::string& manifest_filename) : manifest_filename_(manifest_filename), location_(extensions::Manifest::INTERNAL), flags_(Extension::NO_FLAGS) {} ManifestTest::Testcase::Testcase(const std::string& manifest_filename, extensions::Manifest::Location location, int flags) : manifest_filename_(manifest_filename), location_(location), flags_(flags) {} void ManifestTest::RunTestcases(const Testcase* testcases, size_t num_testcases, ExpectType type) { for (size_t i = 0; i < num_testcases; ++i) RunTestcase(testcases[i], type); } void ManifestTest::RunTestcase(const Testcase& testcase, ExpectType type) { switch (type) { case EXPECT_TYPE_ERROR: LoadAndExpectError(testcase.manifest_filename_.c_str(), testcase.expected_error_, testcase.location_, testcase.flags_); break; case EXPECT_TYPE_WARNING: LoadAndExpectWarning(testcase.manifest_filename_.c_str(), testcase.expected_error_, testcase.location_, testcase.flags_); break; case EXPECT_TYPE_SUCCESS: LoadAndExpectSuccess(testcase.manifest_filename_.c_str(), testcase.location_, testcase.flags_); break; } } } // namespace extensions
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
efe4916240e5925eba0b0f9e5aaccb13a9af6107
c485cb363d29d81212427d3268df1ddcda64d952
/dependencies/boost/libs/spirit/example/scheme/qi/parse_qiexpr.hpp
a9696f673e98768e60d7a1d38984b5c910845717
[ "BSL-1.0" ]
permissive
peplopez/El-Rayo-de-Zeus
66e4ed24d7d1d14a036a144d9414ca160f65fb9c
dc6f0a98f65381e8280d837062a28dc5c9b3662a
refs/heads/master
2021-01-22T04:40:57.358138
2013-10-04T01:19:18
2013-10-04T01:19:18
7,038,026
2
1
null
null
null
null
UTF-8
C++
false
false
654
hpp
// Copyright (c) 2001-2010 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(BOOST_SPIRIT_PARSE_QIEXPR) #define BOOST_SPIRIT_PARSE_QIEXPR #include <input/sexpr.hpp> namespace scheme { namespace input { template <typename String> bool parse_qi_expr(String const& str, utree& result); template <typename String> bool parse_qi_rule(String const& str, utree& result); template <typename String> bool parse_qi_grammar(String const& str, utree& result); }} #endif
[ "fibrizo.raziel@gmail.com" ]
fibrizo.raziel@gmail.com
7c4ec5d05ece56568c574ecfe218f98652907a3c
c1ff870879152fba2b54eddfb7591ec322eb3061
/plugins/render/ogreRender/3rdParty/ogre/Components/Overlay/include/OgreOverlayElement.h
d0871d967b376d8a962a7df3c2b2efe04bd7b0e6
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
MTASZTAKI/ApertusVR
1a9809fb7af81c3cd7fb732ed481ebe4ce66fefa
424ec5515ae08780542f33cc4841a8f9a96337b3
refs/heads/0.9
2022-12-11T20:03:42.926813
2019-10-11T09:29:45
2019-10-11T09:29:45
73,708,854
188
55
MIT
2022-12-11T08:53:21
2016-11-14T13:48:00
C++
UTF-8
C++
false
false
21,590
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2016 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __OverlayElement_H__ #define __OverlayElement_H__ #include "OgreOverlayPrerequisites.h" #include "OgreRenderable.h" #include "OgreUTFString.h" #include "OgreStringInterface.h" #include "OgreOverlayElementCommands.h" #include "OgreColourValue.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Overlays * @{ */ #if OGRE_UNICODE_SUPPORT typedef UTFString DisplayString; # define OGRE_DEREF_DISPLAYSTRING_ITERATOR(it) it.getCharacter() #else typedef String DisplayString; # define OGRE_DEREF_DISPLAYSTRING_ITERATOR(it) *it #endif /** Enum describing how the position / size of an element is to be recorded. */ enum GuiMetricsMode { /// 'left', 'top', 'height' and 'width' are parametrics from 0.0 to 1.0 GMM_RELATIVE, /// Positions & sizes are in absolute pixels GMM_PIXELS, /// Positions & sizes are in virtual pixels GMM_RELATIVE_ASPECT_ADJUSTED }; /** Enum describing where '0' is in relation to the parent in the horizontal dimension. @remarks Affects how 'left' is interpreted. */ enum GuiHorizontalAlignment { GHA_LEFT, GHA_CENTER, GHA_RIGHT }; /** Enum describing where '0' is in relation to the parent in the vertical dimension. @remarks Affects how 'top' is interpreted. */ enum GuiVerticalAlignment { GVA_TOP, GVA_CENTER, GVA_BOTTOM }; /** Abstract definition of a 2D element to be displayed in an Overlay. @remarks This class abstracts all the details of a 2D element which will appear in an overlay. In fact, not all OverlayElement instances can be directly added to an Overlay, only those which are OverlayContainer instances (a subclass of this class). OverlayContainer objects can contain any OverlayElement however. This is just to enforce some level of grouping on widgets. @par OverlayElements should be managed using OverlayManager. This class is responsible for instantiating / deleting elements, and also for accepting new types of element from plugins etc. @par Note that positions / dimensions of 2D screen elements are expressed as parametric values (0.0 - 1.0) because this makes them resolution-independent. However, most screen resolutions have an aspect ratio of 1.3333:1 (width : height) so note that in physical pixels 0.5 is wider than it is tall, so a 0.5x0.5 panel will not be square on the screen (but it will take up exactly half the screen in both dimensions). @par Because this class is designed to be extensible, it subclasses from StringInterface so its parameters can be set in a generic way. */ class _OgreOverlayExport OverlayElement : public StringInterface, public Renderable, public OverlayAlloc { public: protected: // Command object for setting / getting parameters static OverlayElementCommands::CmdLeft msLeftCmd; static OverlayElementCommands::CmdTop msTopCmd; static OverlayElementCommands::CmdWidth msWidthCmd; static OverlayElementCommands::CmdHeight msHeightCmd; static OverlayElementCommands::CmdMaterial msMaterialCmd; static OverlayElementCommands::CmdCaption msCaptionCmd; static OverlayElementCommands::CmdMetricsMode msMetricsModeCmd; static OverlayElementCommands::CmdHorizontalAlign msHorizontalAlignCmd; static OverlayElementCommands::CmdVerticalAlign msVerticalAlignCmd; static OverlayElementCommands::CmdVisible msVisibleCmd; String mName; bool mVisible; bool mCloneable; Real mLeft; Real mTop; Real mWidth; Real mHeight; String mMaterialName; MaterialPtr mMaterial; DisplayString mCaption; ColourValue mColour; RealRect mClippingRegion; GuiMetricsMode mMetricsMode; GuiHorizontalAlignment mHorzAlign; GuiVerticalAlignment mVertAlign; // metric-mode positions, used in GMM_PIXELS & GMM_RELATIVE_ASPECT_ADJUSTED mode. Real mPixelTop; Real mPixelLeft; Real mPixelWidth; Real mPixelHeight; Real mPixelScaleX; Real mPixelScaleY; /// Parent pointer OverlayContainer* mParent; /// Overlay attached to Overlay* mOverlay; // Derived positions from parent Real mDerivedLeft; Real mDerivedTop; bool mDerivedOutOfDate; /// Flag indicating if the vertex positions need recalculating bool mGeomPositionsOutOfDate; /// Flag indicating if the vertex uvs need recalculating bool mGeomUVsOutOfDate; /** Zorder for when sending to render queue. Derived from parent */ ushort mZOrder; /// World transforms Matrix4 mXForm; /// Is element enabled? bool mEnabled; /// Is element initialised? bool mInitialised; /// Used to see if this element is created from a Template OverlayElement* mSourceTemplate ; /** Internal method which is triggered when the positions of the element get updated, meaning the element should be rebuilding it's mesh positions. Abstract since subclasses must implement this. */ virtual void updatePositionGeometry(void) = 0; /** Internal method which is triggered when the UVs of the element get updated, meaning the element should be rebuilding it's mesh UVs. Abstract since subclasses must implement this. */ virtual void updateTextureGeometry(void) = 0; /** Internal method for setting up the basic parameter definitions for a subclass. @remarks Because StringInterface holds a dictionary of parameters per class, subclasses need to call this to ask the base class to add it's parameters to their dictionary as well. Can't do this in the constructor because that runs in a non-virtual context. @par The subclass must have called it's own createParamDictionary before calling this method. */ virtual void addBaseParameters(void); public: /// Constructor: do not call direct, use OverlayManager::createElement OverlayElement(const String& name); virtual ~OverlayElement(); /** Initialise gui element */ virtual void initialise(void) = 0; /** Notifies that hardware resources were lost */ virtual void _releaseManualHardwareResources() {} /** Notifies that hardware resources should be restored */ virtual void _restoreManualHardwareResources() {} /** Gets the name of this overlay. */ const String& getName(void) const; /** Shows this element if it was hidden. */ virtual void show(void); /** Hides this element if it was visible. */ virtual void hide(void); /** Returns whether or not the element is visible. */ bool isVisible(void) const; bool isEnabled() const; virtual void setEnabled(bool b); /** Sets the dimensions of this element in relation to the screen (1.0 = screen width/height). */ void setDimensions(Real width, Real height); /** Sets the position of the top-left corner of the element, relative to the screen size (1.0 = screen width / height) */ void setPosition(Real left, Real top); /** Sets the width of this element in relation to the screen (where 1.0 = screen width) */ void setWidth(Real width); /** Gets the width of this element in relation to the screen (where 1.0 = screen width) */ Real getWidth(void) const; /** Sets the height of this element in relation to the screen (where 1.0 = screen height) */ void setHeight(Real height); /** Gets the height of this element in relation to the screen (where 1.0 = screen height) */ Real getHeight(void) const; /** Sets the left of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ void setLeft(Real left); /** Gets the left of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ Real getLeft(void) const; /** Sets the top of this element in relation to the screen (where 0 = top, 1.0 = bottom) */ void setTop(Real Top); /** Gets the top of this element in relation to the screen (where 0 = top, 1.0 = bottom) */ Real getTop(void) const; /** Gets the left of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ Real _getLeft(void) const { return mLeft; } /** Gets the top of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ Real _getTop(void) const { return mTop; } /** Gets the width of this element in relation to the screen (where 1.0 = screen width) */ Real _getWidth(void) const { return mWidth; } /** Gets the height of this element in relation to the screen (where 1.0 = screen height) */ Real _getHeight(void) const { return mHeight; } /** Sets the left of this element in relation to the screen (where 1.0 = screen width) */ void _setLeft(Real left); /** Sets the top of this element in relation to the screen (where 1.0 = screen width) */ void _setTop(Real top); /** Sets the width of this element in relation to the screen (where 1.0 = screen width) */ void _setWidth(Real width); /** Sets the height of this element in relation to the screen (where 1.0 = screen width) */ void _setHeight(Real height); /** Sets the left and top of this element in relation to the screen (where 1.0 = screen width) */ void _setPosition(Real left, Real top); /** Sets the width and height of this element in relation to the screen (where 1.0 = screen width) */ void _setDimensions(Real width, Real height); /** Gets the name of the material this element uses. */ virtual const String& getMaterialName(void) const; /** Sets the name of the material this element will use. @remarks Different elements will use different materials. One constant about them all though is that a Material used for a OverlayElement must have it's depth checking set to 'off', which means it always gets rendered on top. OGRE will set this flag for you if necessary. What it does mean though is that you should not use the same Material for rendering OverlayElements as standard scene objects. It's fine to use the same textures, just not the same Material. */ virtual void setMaterialName(const String& matName); // --- Renderable Overrides --- /** See Renderable */ const MaterialPtr& getMaterial(void) const; // NB getRenderOperation not implemented, still abstract here /** See Renderable */ void getWorldTransforms(Matrix4* xform) const; /** Tell the object to recalculate */ virtual void _positionsOutOfDate(void); /** Internal method to update the element based on transforms applied. */ virtual void _update(void); /** Updates this elements transform based on it's parent. */ virtual void _updateFromParent(void); /** Internal method for notifying the GUI element of it's parent and ultimate overlay. */ virtual void _notifyParent(OverlayContainer* parent, Overlay* overlay); /** Gets the 'left' position as derived from own left and that of parents. */ virtual Real _getDerivedLeft(void); /** Gets the 'top' position as derived from own left and that of parents. */ virtual Real _getDerivedTop(void); /** Gets the 'width' as derived from own width and metrics mode. */ virtual Real _getRelativeWidth(void); /** Gets the 'height' as derived from own height and metrics mode. */ virtual Real _getRelativeHeight(void); /** Gets the clipping region of the element */ virtual void _getClippingRegion(RealRect &clippingRegion); /** Internal method to notify the element when Z-order of parent overlay has changed. @remarks Overlays have explicit Z-orders. OverlayElements do not, they inherit the Z-order of the overlay, and the Z-order is incremented for every container nested within this to ensure that containers are displayed behind contained items. This method is used internally to notify the element of a change in final Z-order which is used to render the element. @return Return the next Z-ordering number available. For single elements, this is simply 'newZOrder + 1', except for containers. They increment it once for each child (or even more if those children are also containers with their own elements). */ virtual ushort _notifyZOrder(ushort newZOrder); /** Internal method to notify the element when it's world transform of parent overlay has changed. */ virtual void _notifyWorldTransforms(const Matrix4& xform); /** Internal method to notify the element when the viewport of parent overlay has changed. */ virtual void _notifyViewport(); /** Internal method to put the contents onto the render queue. */ virtual void _updateRenderQueue(RenderQueue* queue); /// @copydoc MovableObject::visitRenderables void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables = false); /** Gets the type name of the element. All concrete subclasses must implement this. */ virtual const String& getTypeName(void) const = 0; /** Sets the caption on elements that support it. @remarks This property doesn't do something on all elements, just those that support it. However, being a common requirement it is in the top-level interface to avoid having to set it via the StringInterface all the time. */ virtual void setCaption(const DisplayString& text); /** Gets the caption for this element. */ virtual const DisplayString& getCaption(void) const; /** Sets the colour on elements that support it. @remarks This property doesn't do something on all elements, just those that support it. However, being a common requirement it is in the top-level interface to avoid having to set it via the StringInterface all the time. */ virtual void setColour(const ColourValue& col); /** Gets the colour for this element. */ virtual const ColourValue& getColour(void) const; /** Tells this element how to interpret the position and dimension values it is given. @remarks By default, OverlayElements are positioned and sized according to relative dimensions of the screen. This is to ensure portability between different resolutions when you want things to be positioned and sized the same way across all resolutions. However, sometimes you want things to be sized according to fixed pixels. In order to do this, you can call this method with the parameter GMM_PIXELS. Note that if you then want to place your element relative to the center, right or bottom of it's parent, you will need to use the setHorizontalAlignment and setVerticalAlignment methods. */ virtual void setMetricsMode(GuiMetricsMode gmm); /** Retrieves the current settings of how the element metrics are interpreted. */ virtual GuiMetricsMode getMetricsMode(void) const; /** Sets the horizontal origin for this element. @remarks By default, the horizontal origin for a OverlayElement is the left edge of the parent container (or the screen if this is a root element). You can alter this by calling this method, which is especially useful when you want to use pixel-based metrics (see setMetricsMode) since in this mode you can't use relative positioning. @par For example, if you were using GMM_PIXELS metrics mode, and you wanted to place a 30x30 pixel crosshair in the center of the screen, you would use GHA_CENTER with a 'left' property of -15. @par Note that neither GHA_CENTER or GHA_RIGHT alter the position of the element based on it's width, you have to alter the 'left' to a negative number to do that; all this does is establish the origin. This is because this way you can align multiple things in the center and right with different 'left' offsets for maximum flexibility. */ virtual void setHorizontalAlignment(GuiHorizontalAlignment gha); /** Gets the horizontal alignment for this element. */ virtual GuiHorizontalAlignment getHorizontalAlignment(void) const; /** Sets the vertical origin for this element. @remarks By default, the vertical origin for a OverlayElement is the top edge of the parent container (or the screen if this is a root element). You can alter this by calling this method, which is especially useful when you want to use pixel-based metrics (see setMetricsMode) since in this mode you can't use relative positioning. @par For example, if you were using GMM_PIXELS metrics mode, and you wanted to place a 30x30 pixel crosshair in the center of the screen, you would use GHA_CENTER with a 'top' property of -15. @par Note that neither GVA_CENTER or GVA_BOTTOM alter the position of the element based on it's height, you have to alter the 'top' to a negative number to do that; all this does is establish the origin. This is because this way you can align multiple things in the center and bottom with different 'top' offsets for maximum flexibility. */ virtual void setVerticalAlignment(GuiVerticalAlignment gva); /** Gets the vertical alignment for this element. */ virtual GuiVerticalAlignment getVerticalAlignment(void) const; /** Returns true if xy is within the constraints of the component */ virtual bool contains(Real x, Real y) const; /** Returns true if xy is within the constraints of the component */ virtual OverlayElement* findElementAt(Real x, Real y); // relative to parent /** * returns false as this class is not a container type */ inline virtual bool isContainer() const { return false; } inline virtual bool isKeyEnabled() const { return false; } inline virtual bool isCloneable() const { return mCloneable; } inline virtual void setCloneable(bool c) { mCloneable = c; } /** * Returns the parent container. */ OverlayContainer* getParent() ; void _setParent(OverlayContainer* parent) { mParent = parent; } /** * Returns the zOrder of the element */ inline ushort getZOrder() const { return mZOrder; } /** Overridden from Renderable */ Real getSquaredViewDepth(const Camera* cam) const { (void)cam; return 10000.0f - (Real)getZOrder(); } /** @copydoc Renderable::getLights */ const LightList& getLights(void) const { // Overlayelements should not be lit by the scene, this will not get called static LightList ll; return ll; } virtual void copyFromTemplate(OverlayElement* templateOverlay); virtual OverlayElement* clone(const String& instanceName); /// Returns the SourceTemplate for this element const OverlayElement* getSourceTemplate () const { return mSourceTemplate ; } }; /** @} */ /** @} */ } #endif
[ "peter.kovacs@sztaki.mta.hu" ]
peter.kovacs@sztaki.mta.hu
f26c23ade804a84c4a6986f04d7355b64315a0f0
aef50deb115eac52e29dce51eb9f5f8221e9ed16
/gpu/command_buffer/service/shared_image_representation.h
da832e81a6348e35014ebf6e5ed2f264f9b12826
[ "BSD-3-Clause" ]
permissive
coolsabya/chromium
2a1557937943086e7d2245b9c28d614633ff6ffc
65f89d72ed17c5c23f3c93d5b575ec51e86e1d82
refs/heads/master
2022-11-25T00:28:15.370458
2020-01-03T21:25:55
2020-01-03T21:25:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,946
h
// Copyright 2018 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. #ifndef GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_REPRESENTATION_H_ #define GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_REPRESENTATION_H_ #include <dawn/dawn_proc_table.h> #include <dawn/webgpu.h> #include "base/callback_helpers.h" #include "base/util/type_safety/pass_key.h" #include "build/build_config.h" #include "components/viz/common/resources/resource_format.h" #include "gpu/command_buffer/service/shared_image_backing.h" #include "gpu/command_buffer/service/shared_image_manager.h" #include "gpu/gpu_gles2_export.h" #include "third_party/skia/include/core/SkSurface.h" #include "ui/gfx/color_space.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/gpu_fence.h" typedef unsigned int GLenum; class SkPromiseImageTexture; namespace gl { class GLImage; } namespace gpu { namespace gles2 { class Texture; class TexturePassthrough; } // namespace gles2 enum class RepresentationAccessMode { kNone, kRead, kWrite, }; // A representation of a SharedImageBacking for use with a specific use case / // api. class GPU_GLES2_EXPORT SharedImageRepresentation { public: // Used by derived classes. enum class AllowUnclearedAccess { kYes, kNo }; SharedImageRepresentation(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker); virtual ~SharedImageRepresentation(); viz::ResourceFormat format() const { return backing_->format(); } const gfx::Size& size() const { return backing_->size(); } const gfx::ColorSpace& color_space() const { return backing_->color_space(); } uint32_t usage() const { return backing_->usage(); } MemoryTypeTracker* tracker() { return tracker_; } bool IsCleared() const { return backing_->IsCleared(); } void SetCleared() { backing_->SetCleared(); } gfx::Rect ClearedRect() const { return backing_->ClearedRect(); } void SetClearedRect(const gfx::Rect& cleared_rect) { backing_->SetClearedRect(cleared_rect); } // Indicates that the underlying graphics context has been lost, and the // backing should be treated as destroyed. void OnContextLost() { has_context_ = false; backing_->OnContextLost(); } protected: SharedImageManager* manager() const { return manager_; } SharedImageBacking* backing() const { return backing_; } bool has_context() const { return has_context_; } private: SharedImageManager* const manager_; SharedImageBacking* const backing_; MemoryTypeTracker* const tracker_; bool has_context_ = true; }; class SharedImageRepresentationFactoryRef : public SharedImageRepresentation { public: SharedImageRepresentationFactoryRef(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} const Mailbox& mailbox() const { return backing()->mailbox(); } void Update(std::unique_ptr<gfx::GpuFence> in_fence) { backing()->Update(std::move(in_fence)); backing()->OnWriteSucceeded(); } bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) { return backing()->ProduceLegacyMailbox(mailbox_manager); } bool PresentSwapChain() { return backing()->PresentSwapChain(); } }; class GPU_GLES2_EXPORT SharedImageRepresentationGLTextureBase : public SharedImageRepresentation { public: class ScopedAccess { public: ScopedAccess(util::PassKey<SharedImageRepresentationGLTextureBase> pass_key, SharedImageRepresentationGLTextureBase* representation) : representation_(representation) {} ~ScopedAccess() { representation_->UpdateClearedStateOnEndAccess(); representation_->EndAccess(); } private: SharedImageRepresentationGLTextureBase* representation_ = nullptr; DISALLOW_COPY_AND_ASSIGN(ScopedAccess); }; SharedImageRepresentationGLTextureBase(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} std::unique_ptr<ScopedAccess> BeginScopedAccess( GLenum mode, AllowUnclearedAccess allow_uncleared); protected: friend class SharedImageRepresentationSkiaGL; // Can be overridden to handle clear state tracking when GL access ends. virtual void UpdateClearedStateOnEndAccess() {} // TODO(ericrk): Make these pure virtual and ensure real implementations // exist. virtual bool BeginAccess(GLenum mode); virtual void EndAccess() {} }; class GPU_GLES2_EXPORT SharedImageRepresentationGLTexture : public SharedImageRepresentationGLTextureBase { public: SharedImageRepresentationGLTexture(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentationGLTextureBase(manager, backing, tracker) {} // TODO(ericrk): Move this to the ScopedAccess object. crbug.com/1003686 virtual gles2::Texture* GetTexture() = 0; protected: void UpdateClearedStateOnEndAccess() override; }; class GPU_GLES2_EXPORT SharedImageRepresentationGLTexturePassthrough : public SharedImageRepresentationGLTextureBase { public: SharedImageRepresentationGLTexturePassthrough(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentationGLTextureBase(manager, backing, tracker) {} // TODO(ericrk): Move this to the ScopedAccess object. crbug.com/1003686 virtual const scoped_refptr<gles2::TexturePassthrough>& GetTexturePassthrough() = 0; }; class GPU_GLES2_EXPORT SharedImageRepresentationSkia : public SharedImageRepresentation { public: class GPU_GLES2_EXPORT ScopedWriteAccess { public: ScopedWriteAccess(util::PassKey<SharedImageRepresentationSkia> pass_key, SharedImageRepresentationSkia* representation, sk_sp<SkSurface> surface); ~ScopedWriteAccess(); SkSurface* surface() const { return surface_.get(); } private: SharedImageRepresentationSkia* const representation_; sk_sp<SkSurface> surface_; DISALLOW_COPY_AND_ASSIGN(ScopedWriteAccess); }; class GPU_GLES2_EXPORT ScopedReadAccess { public: ScopedReadAccess(util::PassKey<SharedImageRepresentationSkia> pass_key, SharedImageRepresentationSkia* representation, sk_sp<SkPromiseImageTexture> promise_image_texture); ~ScopedReadAccess(); SkPromiseImageTexture* promise_image_texture() const { return promise_image_texture_.get(); } private: SharedImageRepresentationSkia* const representation_; sk_sp<SkPromiseImageTexture> promise_image_texture_; DISALLOW_COPY_AND_ASSIGN(ScopedReadAccess); }; SharedImageRepresentationSkia(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} // Note: See BeginWriteAccess below for a description of the semaphore // parameters. std::unique_ptr<ScopedWriteAccess> BeginScopedWriteAccess( int final_msaa_count, const SkSurfaceProps& surface_props, std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores, AllowUnclearedAccess allow_uncleared); std::unique_ptr<ScopedWriteAccess> BeginScopedWriteAccess( std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores, AllowUnclearedAccess allow_uncleared); // Note: See BeginReadAccess below for a description of the semaphore // parameters. std::unique_ptr<ScopedReadAccess> BeginScopedReadAccess( std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores); virtual bool SupportsMultipleConcurrentReadAccess(); protected: // Begin the write access. The implementations should insert semaphores into // begin_semaphores vector which client will wait on before writing the // backing. The ownership of begin_semaphores will be passed to client. // The implementations should also insert semaphores into end_semaphores, // client must submit them with drawing operations which use the backing. // The ownership of end_semaphores are not passed to client. And client must // submit the end_semaphores before calling EndWriteAccess(). virtual sk_sp<SkSurface> BeginWriteAccess( int final_msaa_count, const SkSurfaceProps& surface_props, std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores) = 0; virtual void EndWriteAccess(sk_sp<SkSurface> surface) = 0; // Begin the read access. The implementations should insert semaphores into // begin_semaphores vector which client will wait on before reading the // backing. The ownership of begin_semaphores will be passed to client. // The implementations should also insert semaphores into end_semaphores, // client must submit them with drawing operations which use the backing. // The ownership of end_semaphores are not passed to client. And client must // submit the end_semaphores before calling EndReadAccess(). virtual sk_sp<SkPromiseImageTexture> BeginReadAccess( std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores) = 0; virtual void EndReadAccess() = 0; }; class GPU_GLES2_EXPORT SharedImageRepresentationDawn : public SharedImageRepresentation { public: SharedImageRepresentationDawn(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} class GPU_GLES2_EXPORT ScopedAccess { public: ScopedAccess(util::PassKey<SharedImageRepresentationDawn> pass_key, SharedImageRepresentationDawn* representation, WGPUTexture texture); ~ScopedAccess(); WGPUTexture texture() const { return texture_; } private: SharedImageRepresentationDawn* representation_ = nullptr; WGPUTexture texture_ = 0; DISALLOW_COPY_AND_ASSIGN(ScopedAccess); }; // Calls BeginAccess and returns a ScopedAccess object which will EndAccess // when it goes out of scope. The Representation must outlive the returned // ScopedAccess. std::unique_ptr<ScopedAccess> BeginScopedAccess( WGPUTextureUsage usage, AllowUnclearedAccess allow_uncleared); private: // This can return null in case of a Dawn validation error, for example if // usage is invalid. virtual WGPUTexture BeginAccess(WGPUTextureUsage usage) = 0; virtual void EndAccess() = 0; }; class GPU_GLES2_EXPORT SharedImageRepresentationOverlay : public SharedImageRepresentation { public: SharedImageRepresentationOverlay(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} class ScopedReadAccess { public: ScopedReadAccess(util::PassKey<SharedImageRepresentationOverlay> pass_key, SharedImageRepresentationOverlay* representation, gl::GLImage* gl_image) : representation_(representation), gl_image_(gl_image) {} ~ScopedReadAccess() { if (representation_) representation_->EndReadAccess(); } gl::GLImage* gl_image() const { DCHECK(representation_); return gl_image_; } private: SharedImageRepresentationOverlay* representation_; gl::GLImage* gl_image_; }; #if defined(OS_ANDROID) virtual void NotifyOverlayPromotion(bool promotion, const gfx::Rect& bounds) = 0; #endif std::unique_ptr<ScopedReadAccess> BeginScopedReadAccess(bool needs_gl_image); protected: // TODO(weiliangc): Currently this only handles Android pre-SurfaceControl // case. Add appropriate fence later. virtual void BeginReadAccess() = 0; virtual void EndReadAccess() = 0; // TODO(weiliangc): Add API to backing AHardwareBuffer. // TODO(penghuang): Refactor it to not depend on GL. // Get the backing as GLImage for GLSurface::ScheduleOverlayPlane. virtual gl::GLImage* GetGLImage() = 0; }; } // namespace gpu #endif // GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_REPRESENTATION_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
30e8970bf412022ee788b617fb02408e3e9aa50b
b67a780af96a1b70569f81def205f2adbe328292
/Demo/Graph/DirectedGraph/Connected/DirectedCycle.hpp
545fdad1a8bfad451974630397cfc90e0497b853
[]
no_license
doquanghuy/Algorithm
8c27933c5c42b4324b39e061c43542adf4a6372b
4dd63edd823bd0a158034e281c37ef1f6704ec9c
refs/heads/master
2020-04-13T18:52:44.872226
2019-01-16T15:04:48
2019-01-16T15:04:48
163,387,254
0
0
null
2019-01-16T14:21:06
2018-12-28T08:36:31
null
UTF-8
C++
false
false
578
hpp
// // DirectedCycle.hpp // Demo // // Created by Quang Huy on 12/22/18. // Copyright © 2018 Techmaster. All rights reserved. // #ifndef DirectedCycle_hpp #define DirectedCycle_hpp #include <stdio.h> #include "Stack+LinkedList.hpp" class Digraph; class DirectedCycle { public: DirectedCycle(Digraph g); bool hasCycle(); Iterable<int>** cycles(); int numberCycles(); private: int _numberCycles; bool* markedVertices; Iterable<int>** _cycles; int* edges; bool* onStack; void dfs(Digraph g, int s); }; #endif /* DirectedCycle_hpp */
[ "sin.do@mobiclixgroup.com" ]
sin.do@mobiclixgroup.com
eaaddffc571e5ad5b1aa953164019055033d2410
d0fb46aecc3b69983e7f6244331a81dff42d9595
/alikafka/src/model/UpdateConsumerOffsetResult.cc
1ace5b4b7cf904781ffdfcb26ac559122fbf0a2c
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,722
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/alikafka/model/UpdateConsumerOffsetResult.h> #include <json/json.h> using namespace AlibabaCloud::Alikafka; using namespace AlibabaCloud::Alikafka::Model; UpdateConsumerOffsetResult::UpdateConsumerOffsetResult() : ServiceResult() {} UpdateConsumerOffsetResult::UpdateConsumerOffsetResult(const std::string &payload) : ServiceResult() { parse(payload); } UpdateConsumerOffsetResult::~UpdateConsumerOffsetResult() {} void UpdateConsumerOffsetResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = std::stoi(value["Code"].asString()); if(!value["Message"].isNull()) message_ = value["Message"].asString(); } std::string UpdateConsumerOffsetResult::getMessage()const { return message_; } int UpdateConsumerOffsetResult::getCode()const { return code_; } bool UpdateConsumerOffsetResult::getSuccess()const { return success_; }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
0c07d94815348de12a9b5fb15764917aa707d913
72530b12990dc28da37e3aad3d32bf8768af630b
/CPP/cpp_pool/day04/ex02/AssaultTerminator.cpp
a65151f34cc1c8f995b9720d510b0a0d94d39338
[]
no_license
lacretelle/42_cursus
baa805415819a74535d94a9a2f2ca058080d70c0
3333da966109c1e378545137b5530148ecd7d972
refs/heads/master
2023-03-17T16:19:31.627724
2021-03-05T15:25:57
2021-03-05T15:25:57
317,812,905
0
0
null
null
null
null
UTF-8
C++
false
false
940
cpp
#include "AssaultTerminator.hpp" AssaultTerminator::AssaultTerminator() { std::cout << "* teleports from space *" << std::endl; } AssaultTerminator::AssaultTerminator(AssaultTerminator const &src) { std::cout << "copy" << std::endl; *this = src; } AssaultTerminator & AssaultTerminator::operator=(AssaultTerminator const &src) { std::cout << "ENTER in operstor =" << std::endl; (void)src; return *this; } AssaultTerminator::~AssaultTerminator() { std::cout << "I’ll be back ..." << std::endl; } ISpaceMarine *AssaultTerminator::clone() const { return new AssaultTerminator(*this); } void AssaultTerminator::battleCry() const { std::cout << "This code is unclean. Purify it !" << std::endl; } void AssaultTerminator::rangedAttack() const { std::cout << "* does nothing *" << std::endl; } void AssaultTerminator::meleeAttack() const { std::cout << "** attaque with chainfists *" << std::endl; }
[ "marie@MacBook-Air-de-Marie.local" ]
marie@MacBook-Air-de-Marie.local
ebc6fb20e89828f29706f62aee1b4cffece75874
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/CHotkeyHandler.cpp
15febe39e79e820d09d62728a8f847983dbeed2d
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
18,886
cpp
#include "env.h" #include "pragma.h" #include "macro.h" #include "window.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT //#define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE /* History ---------- Monday, April 21, 2003 * Initial version Tuesday, April 22, 2003 * Added list entries recycling into RemoveHandler(). Now removing works correctly. * Added utility functions: HotkeyFlagsToModifiers() and HotkeyModifiersToFlags() Wednesday, April 23, 2003 * Added checks on Start() to prevent starting if already started. Thursday, April 24, 2003 * Fixed CreateThread() in Start() calling so that it works on Win9x. Thursday, May 01, 2003 * Fixed code in MakeWindow() and now CHotkeyHandler works under Win9x very well. Monday, Oct 20, 2003 * Removed 'using std::vector' from header file * Fixed a minor bug in RemoveHandler() */ /* ----------------------------------------------------------------------------- * Copyright (c) 2003 Lallous <lallousx86@yahoo.com> * All rights reserved. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * ----------------------------------------------------------------------------- */ /* CHotkeyHandler() is a class that wrappes the RegisterHotkey() and its UnregisterHotkey() Windows APIs. This class provides a simple method to implement and handle multiple hotkeys at the same time. * Debug Flag: -------------- bool bDebug; This flag is used to turn debugging on/off. Useful when you're developing. * Constructor --------------- CHotkeyHandler(bool Debug = false); This constructor initializes internal variables and sets debug info on/off If you call Start() and do not call Stop() the destructor will automatically Stop() for you. * Start() ----------- int Start(LPVOID Param=NULL); This method is asynchronous; It starts the hotkey listener. You must have at least one handler inserted before calling this method, otherwise hkheNoEntry would be returned. It returns an hkhe error code. 'Param' is a user supplied pointer used when calling the hotkey callbacks. * Stop() ----------- int Stop(); After you've started the hotkey listener, you can stop it w/ Stop(). Stop() will return success if it was stopped successfully or if it was not started at all. * InsertHandler() -------------------- int InsertHandler(WORD mod, WORD virt, tHotkeyCB cb, int &index); This function will return an error code. 'index' will be filled by the index of where the hotkey is stored (1 based). If you attempt to insert a hotkey that already exists then 'index' will be the index value of that previously inserted hotkey. 'mod' is any of the MOD_XXXX constants. 'virt' is the virtual key code. 'cb' is the handler that will be called. The prototype is: void Callback(void *param) The 'param' of 'cb' will be the one that you passed when you called Start() * RemoveHandler() -------------------- int RemoveHandler(const int index); Removes a hotkey definition. This function has effects only when called before Start() or after Stop(). * HotkeyModifiersToFlags() ---------------------------- WORD HotkeyModifiersToFlags(WORD modf); Converts from MOD_XXX modifiers into HOTKEYF_XXXX to be used by HOTKEYFLAGS. This method is static. * HotkeyFlagsToModifiers() ----------------------------- WORD HotkeyFlagsToModifiers(WORD hkf); Converts HOTKEYFLAGS used by CHotKeyCtrl into MOD_XXX used by windows API This method is static. Error codes ------------- CHotkeyHandler::hkheXXXXX hkheOk - Success hkheClassError - Window class registration error hkheWindowError - Window creation error hkheNoEntry - No entry found at given index hkheRegHotkeyError - Could not register hotkey hkheMessageLoop - Could not create message loop thread hkheInternal - Internal error */ #include "chotkeyhandler.h" //------------------------------------------------------------------------------------- // Initializes internal variables CHotkeyHandler::CHotkeyHandler(bool Debug) { bDebug = Debug; m_bStarted = false; m_hWnd = NULL; m_hMessageLoopThread = m_hPollingError = m_hRaceProtection = NULL; } //------------------------------------------------------------------------------------- // Initializes internal variables CHotkeyHandler::~CHotkeyHandler() { if (m_bStarted) Stop(); } //------------------------------------------------------------------------------------- // Releases and deletes the protection mutex void CHotkeyHandler::EndRaceProtection() { if (m_hRaceProtection) { ::ReleaseMutex(m_hRaceProtection); ::CloseHandle(m_hRaceProtection); // invalidate handle m_hRaceProtection = NULL; } } //------------------------------------------------------------------------------------- // Creates and acquires protection mutex bool CHotkeyHandler::BeginRaceProtection() { LPCTSTR szMutex = _T("{97B7C451-2467-4C3C-BB91-25AC918C2430}"); // failed to create a mutex ? to open ? if ( // failed to create and the object does not exist? ( !(m_hRaceProtection = ::CreateMutex(NULL, FALSE, szMutex)) && (::GetLastError() != ERROR_ALREADY_EXISTS) ) || !(m_hRaceProtection = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, szMutex)) ) return false; ::WaitForSingleObject(m_hRaceProtection, INFINITE); return true; } //------------------------------------------------------------------------------------- // removes a disabled hotkey from the internal list // If this function is of use only before a Start() call or after a Stop() int CHotkeyHandler::RemoveHandler(const int index) { // index out of range ? if (m_listHk.size() <= index) return hkheNoEntry; // mark handler as deleted m_listHk.at(index).deleted = true; return hkheOk; } //------------------------------------------------------------------------------------- // Generates a unique atom and then registers a hotkey // int CHotkeyHandler::EnableHotkey(const int index) { TCHAR atomname[MAX_PATH]; ATOM a; // get hotkey definition tHotkeyDef *def = &m_listHk.at(index); // If entry does not exist then return Ok if (def->deleted) return hkheOk; // compose atom name wsprintf(atomname, _T("ED7D65EB-B139-44BB-B455-7BB83FE361DE-%08lX"), MAKELONG(def->virt, def->mod)); // Try to create an atom a = ::GlobalAddAtom(atomname); // could not create? probably already there if (!a) a = ::GlobalFindAtom(atomname); // try to locate atom if (!a || !::RegisterHotKey(m_hWnd, a, def->mod, def->virt)) { if (a) ::GlobalDeleteAtom(a); return hkheRegHotkeyError; } // store atom into definition too def->id = a; return hkheOk; } //------------------------------------------------------------------------------------- // Unregisters a hotkey and deletes the atom int CHotkeyHandler::DisableHotkey(const int index) { // get hotkey definition tHotkeyDef *def = &m_listHk.at(index); // skip deleted entry if (def->deleted) return hkheOk; // already registered if (def->id) { UnregisterHotKey(m_hWnd, def->id); GlobalDeleteAtom(def->id); return hkheOk; } else return hkheNoEntry; } //------------------------------------------------------------------------------------- // Locates a hotkey definition given its ID int CHotkeyHandler::FindHandlerById(const ATOM id, tHotkeyDef *&def) { tHotkeyList::iterator i; for (i=m_listHk.begin(); i != m_listHk.end(); i++) { def = &*i; if ((def->id == id) && !def->deleted) return hkheOk; } return hkheNoEntry; } //------------------------------------------------------------------------------------- // Finds a deleted entry int CHotkeyHandler::FindDeletedHandler(int &idx) { tHotkeyDef *def; int i, c = m_listHk.size(); for (i=0; i< c; i++) { def = &m_listHk[i]; if (def->deleted) { idx = i; return hkheOk; } } return hkheNoEntry; } //------------------------------------------------------------------------------------- // Finds a hotkeydef given it's modifier 'mod' and virtuak key 'virt' // If return value is hkheOk then 'idx' is filled with the found index // Otherwise 'idx' is left untouched. int CHotkeyHandler::FindHandler(WORD mod, WORD virt, int &idx) { tHotkeyDef *def; int i, c = m_listHk.size(); for (i=0; i < c; i++) { def = &m_listHk[i]; // found anything in the list ? if ( (def->mod == mod) && (def->virt == virt) && !def->deleted) { // return its id idx = i; return hkheOk; } } return hkheNoEntry; } //------------------------------------------------------------------------------------- // Inserts a hotkey into the list // Returns into 'idx' the index of where the definition is added // You may use the returned idx to modify/delete this definition int CHotkeyHandler::InsertHandler(WORD mod, WORD virt, tHotkeyCB cb, int &idx) { tHotkeyDef def; // Try to find a deleted entry and use it if (FindDeletedHandler(idx) == hkheOk) { tHotkeyDef *d = &m_listHk.at(idx); d->deleted = false; d->id = NULL; d->callback = cb; d->virt = virt; d->mod = mod; } // Add a new entry else if (FindHandler(mod, virt, idx) == hkheNoEntry) { def.mod = mod; def.virt = virt; def.callback = cb; def.id = NULL; def.deleted = false; idx = m_listHk.size(); m_listHk.push_back(def); } return hkheOk; } //------------------------------------------------------------------------------------- // Window Procedure // Almost empty; it responds to the WM_DESTROY message only LRESULT CALLBACK CHotkeyHandler::WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { case WM_DESTROY: ::PostQuitMessage(0); break; default: return ::DefWindowProc(hWnd, Msg, wParam, lParam); } return 0; } //------------------------------------------------------------------------------------- // This function is run from a new thread, it: // 1) Create our hidden window to process hotkeys // 2) Enables (registers) all defined hotkeys // 3) Starts the message loop DWORD WINAPI CHotkeyHandler::MessageLoop(LPVOID Param) { int rc; CHotkeyHandler *_this = reinterpret_cast<CHotkeyHandler *>(Param); // create window if ((rc = _this->MakeWindow()) != hkheOk) { _this->m_PollingError = rc; ::SetEvent(_this->m_hPollingError); return rc; } // register all hotkeys for (int i=0; i<_this->m_listHk.size(); i++) { // try to register if ((rc = _this->EnableHotkey(i)) != hkheOk) { // disable hotkeys enabled so far for (int j=0;j<i;j++) _this->DisableHotkey(j); // uninit window _this->MakeWindow(true); // signal that error is ready _this->m_PollingError = rc; ::SetEvent(_this->m_hPollingError); return rc; } } _this->m_PollingError = hkheOk; ::SetEvent(_this->m_hPollingError); MSG msg; BOOL bRet; while ( ((bRet = ::GetMessage(&msg, _this->m_hWnd, 0, 0)) != 0) ) { if (bRet == -1) break; // hotkey received ? if (msg.message == WM_HOTKEY) { tHotkeyDef *def; // try to find handler (wParam == id (ATOM) if (_this->FindHandlerById( (ATOM) msg.wParam, def) == hkheOk) { // call the registered handler if (def->callback) def->callback(_this->m_lpCallbackParam); } } ::TranslateMessage(&msg); ::DispatchMessage(&msg); } return hkheOk; } //------------------------------------------------------------------------------------- // This asynchronous function will register all hotkeys and starts the window message // loop into its own thread. You would have to call Stop() to unroll everything // int CHotkeyHandler::Start(LPVOID cbParam) { int rc; // avoid starting again if already started if (m_bStarted) return hkheOk; // Do not start if no entries are there! if (m_listHk.empty()) return hkheNoEntry; if (!BeginRaceProtection()) return hkheInternal; if (!(m_hPollingError = ::CreateEvent(NULL, FALSE, FALSE, NULL))) { rc = hkheMessageLoop; goto cleanup; } m_lpCallbackParam = cbParam; // create message loop thread DWORD dwThreadId; m_hMessageLoopThread = ::CreateThread(NULL, NULL, MessageLoop, static_cast<LPVOID>(this), NULL, &dwThreadId); if (!m_hMessageLoopThread) { rc = hkheMessageLoop; goto cleanup; } // wait until we get an error code from the message loop thread ::WaitForSingleObject(m_hPollingError, INFINITE); if (m_PollingError != hkheOk) { ::CloseHandle(m_hMessageLoopThread); m_hMessageLoopThread = NULL; } rc = m_PollingError; m_bStarted = true; cleanup: EndRaceProtection(); return rc; } //------------------------------------------------------------------------------------- // Disables all hotkeys then kills the hidden window that processed the hotkeys // The return code is the one returned from the MessageLoop() // int CHotkeyHandler::Stop() { // not started? return Success if (!m_bStarted || !m_hMessageLoopThread) return hkheOk; if (!BeginRaceProtection()) return hkheInternal; // disable all hotkeys for (int i=0;i<m_listHk.size();i++) DisableHotkey(i); // tell message loop to terminate ::SendMessage(m_hWnd, WM_DESTROY, 0, 0); // wait for the thread to exit by itself if (::WaitForSingleObject(m_hMessageLoopThread, 3000) == WAIT_TIMEOUT) ::TerminateThread(m_hMessageLoopThread, 0); // kill thread DWORD exitCode; ::GetExitCodeThread(m_hMessageLoopThread, &exitCode); // close handle of thread ::CloseHandle(m_hMessageLoopThread); // reset this variable m_hMessageLoopThread = NULL; // unregister window class MakeWindow(true); // kill error polling event ::CloseHandle(m_hPollingError); m_bStarted = false; EndRaceProtection(); return exitCode; } //------------------------------------------------------------------------------------- // Creates the hidden window that will receive hotkeys notification // When bUnmake, it will Unregister the window class int CHotkeyHandler::MakeWindow(bool bUnmake) { HWND hwnd; WNDCLASSEX wcl; HINSTANCE hInstance = ::GetModuleHandle(NULL); // Our hotkey processing window class LPTSTR szClassName = _T("HKWND-CLS-BC090410-3872-49E5-BDF7-1BB8056BF696"); if (bUnmake) { UnregisterClass(szClassName, hInstance); m_hWnd = NULL; return hkheOk; } // Set the window class wcl.cbSize = sizeof(WNDCLASSEX); wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.hbrBackground = NULL;//(HBRUSH) GetStockObject(WHITE_BRUSH); wcl.lpszClassName = szClassName; wcl.lpszMenuName = NULL; wcl.hCursor = NULL;//LoadCursor(NULL, IDC_ARROW); wcl.hIcon = NULL;//LoadIcon(NULL, IDI_APPLICATION); wcl.hIconSm = NULL;//LoadIcon(NULL, IDI_WINLOGO); wcl.hInstance = hInstance; wcl.lpfnWndProc = WindowProc; wcl.style = 0; // Failed to register class other than that the class already exists? if (!::RegisterClassEx(&wcl) && (::GetLastError() != ERROR_CLASS_ALREADY_EXISTS)) return hkheClassError; // Create the window hwnd = ::CreateWindowEx( 0, szClassName, _T("CHotkeyHandlerWindow"), WS_OVERLAPPEDWINDOW, 0, 0, 100, 100, HWND_DESKTOP, NULL, hInstance, NULL); // Window creation failed ? if (!hwnd) return hkheWindowError; // hide window ::ShowWindow(hwnd, bDebug ? SW_SHOW : SW_HIDE); m_hWnd = hwnd; return hkheOk; } //--------------------------------------------------------------------------------- // Converts HOTKEYFLAGS used by CHotKeyCtrl into MOD_XXX used by windows API // WORD CHotkeyHandler::HotkeyFlagsToModifiers(WORD hkf) { WORD r; r = ((hkf & HOTKEYF_CONTROL) ? MOD_CONTROL : 0) | ((hkf & HOTKEYF_ALT) ? MOD_ALT : 0) | ((hkf & HOTKEYF_SHIFT) ? MOD_SHIFT : 0); return r; } //--------------------------------------------------------------------------------- // Converts from MOD_XXX modifiers into HOTKEYF_XXXX // WORD CHotkeyHandler::HotkeyModifiersToFlags(WORD modf) { WORD r; r = ((modf & MOD_CONTROL) ? HOTKEYF_CONTROL : 0) | ((modf & MOD_ALT) ? HOTKEYF_ALT : 0) | ((modf & MOD_SHIFT) ? HOTKEYF_SHIFT : 0); return r; }
[ "luca.pierge@gmail.com" ]
luca.pierge@gmail.com
3ec88323905a8f206541cc8a3936763e80e03678
05d8a212d29c310157dbf6b3fbb1379055468309
/chrome/browser/ui/views/tabs/tab_icon.cc
2916aaaeb06f0da288e03dea73ff5c5e0b748e71
[ "BSD-3-Clause" ]
permissive
zjj6029/chromium
1e9743a8a4698831d0b9cf094c67216e7e4df27a
80b54fd5b182936eab1fc1ac5c247857e66d5cbe
refs/heads/master
2023-03-18T13:33:54.559462
2019-08-21T15:54:01
2019-08-21T15:54:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,266
cc
// Copyright 2017 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/views/tabs/tab_icon.h" #include "base/metrics/histogram_macros.h" #include "base/time/default_tick_clock.h" #include "base/timer/elapsed_timer.h" #include "base/trace_event/trace_event.h" #include "cc/paint/paint_flags.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/views/tabs/tab_renderer_data.h" #include "chrome/common/webui_url_constants.h" #include "components/grit/components_scaled_resources.h" #include "content/public/common/url_constants.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/theme_provider.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/animation/linear_animation.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/favicon_size.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/scoped_canvas.h" #include "ui/native_theme/native_theme.h" #include "ui/resources/grit/ui_resources.h" #include "ui/views/border.h" #include "url/gurl.h" namespace { constexpr int kAttentionIndicatorRadius = 3; constexpr int kLoadingAnimationStrokeWidthDp = 2; // Returns whether the favicon for the given URL should be colored according to // the browser theme. bool ShouldThemifyFaviconForUrl(const GURL& url) { return url.SchemeIs(content::kChromeUIScheme) && url.host_piece() != chrome::kChromeUIHelpHost && url.host_piece() != chrome::kChromeUIUberHost && url.host_piece() != chrome::kChromeUIAppLauncherPageHost; } bool NetworkStateIsAnimated(TabNetworkState network_state) { return network_state != TabNetworkState::kNone && network_state != TabNetworkState::kError; } } // namespace // Helper class that manages the favicon crash animation. class TabIcon::CrashAnimation : public gfx::LinearAnimation, public gfx::AnimationDelegate { public: explicit CrashAnimation(TabIcon* target) : gfx::LinearAnimation(base::TimeDelta::FromSeconds(1), 25, this), target_(target) {} ~CrashAnimation() override = default; // gfx::Animation overrides: void AnimateToState(double state) override { if (state < .5) { // Animate the normal icon down. target_->hiding_fraction_ = state * 2.0; } else { // Animate the crashed icon up. target_->should_display_crashed_favicon_ = true; target_->hiding_fraction_ = 1.0 - (state - 0.5) * 2.0; } target_->SchedulePaint(); } private: TabIcon* target_; DISALLOW_COPY_AND_ASSIGN(CrashAnimation); }; TabIcon::TabIcon() : AnimationDelegateViews(this), clock_(base::DefaultTickClock::GetInstance()), favicon_fade_in_animation_(base::TimeDelta::FromMilliseconds(250), gfx::LinearAnimation::kDefaultFrameRate, this) { set_can_process_events_within_subtree(false); // The minimum size to avoid clipping the attention indicator. const int preferred_width = gfx::kFaviconSize + kAttentionIndicatorRadius + GetInsets().width(); SetPreferredSize(gfx::Size(preferred_width, preferred_width)); // Initial state (before any data) should not be animating. DCHECK(!ShowingLoadingAnimation()); } TabIcon::~TabIcon() = default; void TabIcon::SetData(const TabRendererData& data) { const bool was_showing_load = ShowingLoadingAnimation(); inhibit_loading_animation_ = data.should_hide_throbber; SetIcon(data.visible_url, data.favicon); SetNetworkState(data.network_state); SetIsCrashed(data.IsCrashed()); has_tab_renderer_data_ = true; const bool showing_load = ShowingLoadingAnimation(); RefreshLayer(); if (was_showing_load && !showing_load) { // Loading animation transitioning from on to off. loading_animation_start_time_ = base::TimeTicks(); waiting_state_ = gfx::ThrobberWaitingState(); SchedulePaint(); } else if (!was_showing_load && showing_load) { // Loading animation transitioning from off to on. The animation painting // function will lazily initialize the data. SchedulePaint(); } } void TabIcon::SetAttention(AttentionType type, bool enabled) { int previous_attention_type = attention_types_; if (enabled) attention_types_ |= static_cast<int>(type); else attention_types_ &= ~static_cast<int>(type); if (attention_types_ != previous_attention_type) SchedulePaint(); } bool TabIcon::ShowingLoadingAnimation() const { if (inhibit_loading_animation_) return false; return NetworkStateIsAnimated(network_state_); } bool TabIcon::ShowingAttentionIndicator() const { return attention_types_ > 0; } void TabIcon::SetCanPaintToLayer(bool can_paint_to_layer) { if (can_paint_to_layer == can_paint_to_layer_) return; can_paint_to_layer_ = can_paint_to_layer; RefreshLayer(); } void TabIcon::StepLoadingAnimation(const base::TimeDelta& elapsed_time) { // Only update elapsed time in the kWaiting state. This is later used as a // starting point for PaintThrobberSpinningAfterWaiting(). if (network_state_ == TabNetworkState::kWaiting) waiting_state_.elapsed_time = elapsed_time; if (ShowingLoadingAnimation()) SchedulePaint(); } void TabIcon::OnPaint(gfx::Canvas* canvas) { // This is used to log to UMA. NO EARLY RETURNS! base::ElapsedTimer paint_timer; // Compute the bounds adjusted for the hiding fraction. gfx::Rect contents_bounds = GetContentsBounds(); if (contents_bounds.IsEmpty()) return; gfx::Rect icon_bounds( GetMirroredXWithWidthInView(contents_bounds.x(), gfx::kFaviconSize), contents_bounds.y() + static_cast<int>(contents_bounds.height() * hiding_fraction_), std::min(gfx::kFaviconSize, contents_bounds.width()), std::min(gfx::kFaviconSize, contents_bounds.height())); // Don't paint the attention indicator during the loading animation. if (!ShowingLoadingAnimation() && ShowingAttentionIndicator() && !should_display_crashed_favicon_) { PaintAttentionIndicatorAndIcon(canvas, GetIconToPaint(), icon_bounds); } else { MaybePaintFavicon(canvas, GetIconToPaint(), icon_bounds); } if (ShowingLoadingAnimation()) PaintLoadingAnimation(canvas, icon_bounds); UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES( "TabStrip.Tab.Icon.PaintDuration", paint_timer.Elapsed(), base::TimeDelta::FromMicroseconds(1), base::TimeDelta::FromMicroseconds(10000), 50); } void TabIcon::OnThemeChanged() { crashed_icon_ = gfx::ImageSkia(); // Force recomputation if crashed. if (!themed_favicon_.isNull()) themed_favicon_ = ThemeImage(favicon_); } void TabIcon::AnimationProgressed(const gfx::Animation* animation) { SchedulePaint(); } void TabIcon::AnimationEnded(const gfx::Animation* animation) { RefreshLayer(); SchedulePaint(); } void TabIcon::PaintAttentionIndicatorAndIcon(gfx::Canvas* canvas, const gfx::ImageSkia& icon, const gfx::Rect& bounds) { TRACE_EVENT0("views", "TabIcon::PaintAttentionIndicatorAndIcon"); gfx::Point circle_center( bounds.x() + (base::i18n::IsRTL() ? 0 : gfx::kFaviconSize), bounds.y() + gfx::kFaviconSize); // The attention indicator consists of two parts: // . a clear (totally transparent) part over the bottom right (or left in rtl) // of the favicon. This is done by drawing the favicon to a layer, then // drawing the clear part on top of the favicon. // . a circle in the bottom right (or left in rtl) of the favicon. if (!icon.isNull()) { canvas->SaveLayerAlpha(0xff); canvas->DrawImageInt(icon, 0, 0, bounds.width(), bounds.height(), bounds.x(), bounds.y(), bounds.width(), bounds.height(), false); cc::PaintFlags clear_flags; clear_flags.setAntiAlias(true); clear_flags.setBlendMode(SkBlendMode::kClear); const float kIndicatorCropRadius = 4.5f; canvas->DrawCircle(circle_center, kIndicatorCropRadius, clear_flags); canvas->Restore(); } // Draws the actual attention indicator. cc::PaintFlags indicator_flags; indicator_flags.setColor(GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_ProminentButtonColor)); indicator_flags.setAntiAlias(true); canvas->DrawCircle(circle_center, kAttentionIndicatorRadius, indicator_flags); } void TabIcon::PaintLoadingAnimation(gfx::Canvas* canvas, gfx::Rect bounds) { TRACE_EVENT0("views", "TabIcon::PaintLoadingAnimation"); const ui::ThemeProvider* tp = GetThemeProvider(); if (network_state_ == TabNetworkState::kWaiting) { gfx::PaintThrobberWaiting( canvas, bounds, tp->GetColor(ThemeProperties::COLOR_TAB_THROBBER_WAITING), waiting_state_.elapsed_time, kLoadingAnimationStrokeWidthDp); } else { const base::TimeTicks current_time = clock_->NowTicks(); if (loading_animation_start_time_.is_null()) loading_animation_start_time_ = current_time; waiting_state_.color = tp->GetColor(ThemeProperties::COLOR_TAB_THROBBER_WAITING); gfx::PaintThrobberSpinningAfterWaiting( canvas, bounds, tp->GetColor(ThemeProperties::COLOR_TAB_THROBBER_SPINNING), current_time - loading_animation_start_time_, &waiting_state_, kLoadingAnimationStrokeWidthDp); } } const gfx::ImageSkia& TabIcon::GetIconToPaint() { if (should_display_crashed_favicon_) { if (crashed_icon_.isNull()) { // Lazily create a themed sad tab icon. ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); crashed_icon_ = ThemeImage(*rb.GetImageSkiaNamed(IDR_CRASH_SAD_FAVICON)); } return crashed_icon_; } return themed_favicon_.isNull() ? favicon_ : themed_favicon_; } void TabIcon::MaybePaintFavicon(gfx::Canvas* canvas, const gfx::ImageSkia& icon, const gfx::Rect& bounds) { TRACE_EVENT0("views", "TabIcon::MaybePaintFavicon"); if (icon.isNull()) return; if (ShowingLoadingAnimation()) { // Never paint the favicon during the waiting animation. if (network_state_ == TabNetworkState::kWaiting) return; // Don't paint the default favicon while we're still loading. if (!HasNonDefaultFavicon()) return; } std::unique_ptr<gfx::ScopedCanvas> scoped_canvas; bool use_scale_filter = false; if (ShowingLoadingAnimation() || favicon_fade_in_animation_.is_animating()) { scoped_canvas = std::make_unique<gfx::ScopedCanvas>(canvas); use_scale_filter = true; // The favicon is initially inset with the width of the loading-animation // stroke + an additional dp to create some visual separation. const float kInitialFaviconInsetDp = 1 + kLoadingAnimationStrokeWidthDp; const float kInitialFaviconDiameterDp = gfx::kFaviconSize - 2 * kInitialFaviconInsetDp; // This a full outset circle of the favicon square. The animation ends with // the entire favicon shown. const float kFinalFaviconDiameterDp = sqrt(2) * gfx::kFaviconSize; SkScalar diameter = kInitialFaviconDiameterDp; if (favicon_fade_in_animation_.is_animating()) { diameter += gfx::Tween::CalculateValue( gfx::Tween::EASE_OUT, favicon_fade_in_animation_.GetCurrentValue()) * (kFinalFaviconDiameterDp - kInitialFaviconDiameterDp); } SkPath path; gfx::PointF center = gfx::RectF(bounds).CenterPoint(); path.addCircle(center.x(), center.y(), diameter / 2); canvas->ClipPath(path, true); // This scales and offsets painting so that the drawn favicon is downscaled // to fit in the cropping area. const float offset = (gfx::kFaviconSize - std::min(diameter, SkFloatToScalar(gfx::kFaviconSize))) / 2; const float scale = std::min(diameter, SkFloatToScalar(gfx::kFaviconSize)) / gfx::kFaviconSize; canvas->Translate(gfx::Vector2d(offset, offset)); canvas->Scale(scale, scale); } canvas->DrawImageInt(icon, 0, 0, bounds.width(), bounds.height(), bounds.x(), bounds.y(), bounds.width(), bounds.height(), use_scale_filter); } bool TabIcon::HasNonDefaultFavicon() const { return !favicon_.isNull() && !favicon_.BackedBySameObjectAs( favicon::GetDefaultFavicon().AsImageSkia()); } void TabIcon::SetIcon(const GURL& url, const gfx::ImageSkia& icon) { // Detect when updating to the same icon. This avoids re-theming and // re-painting. if (favicon_.BackedBySameObjectAs(icon)) return; favicon_ = icon; if (!HasNonDefaultFavicon() || ShouldThemifyFaviconForUrl(url)) { themed_favicon_ = ThemeImage(icon); } else { themed_favicon_ = gfx::ImageSkia(); } SchedulePaint(); } void TabIcon::SetNetworkState(TabNetworkState network_state) { const bool was_animated = NetworkStateIsAnimated(network_state_); network_state_ = network_state; const bool is_animated = NetworkStateIsAnimated(network_state_); if (was_animated != is_animated) { if (was_animated && HasNonDefaultFavicon()) { favicon_fade_in_animation_.Start(); } else { favicon_fade_in_animation_.Stop(); favicon_fade_in_animation_.SetCurrentValue(0.0); } } } void TabIcon::SetIsCrashed(bool is_crashed) { if (is_crashed == is_crashed_) return; is_crashed_ = is_crashed; if (!is_crashed_) { // Transitioned from crashed to non-crashed. if (crash_animation_) crash_animation_->Stop(); should_display_crashed_favicon_ = false; hiding_fraction_ = 0.0; } else { // Transitioned from non-crashed to crashed. if (!has_tab_renderer_data_) { // This is the initial SetData(), so show the crashed icon directly // without animating. should_display_crashed_favicon_ = true; } else { if (!crash_animation_) crash_animation_ = std::make_unique<CrashAnimation>(this); if (!crash_animation_->is_animating()) crash_animation_->Start(); } } SchedulePaint(); } void TabIcon::RefreshLayer() { // Since the loading animation can run for a long time, paint animation to a // separate layer when possible to reduce repaint overhead. bool should_paint_to_layer = can_paint_to_layer_ && (ShowingLoadingAnimation() || favicon_fade_in_animation_.is_animating()); if (should_paint_to_layer == !!layer()) return; // Change layer mode. if (should_paint_to_layer) { SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); } else { DestroyLayer(); } } gfx::ImageSkia TabIcon::ThemeImage(const gfx::ImageSkia& source) { if (!GetThemeProvider()->HasCustomColor( ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON)) return source; return gfx::ImageSkiaOperations::CreateColorMask( source, GetThemeProvider()->GetColor(ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON)); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d672de6dff7d0f640a73931604a38f86ee73bcb1
1f2ba15e21a80b939cfe8b44851370ed5728b171
/Chapter 3/3.1.5 (1).cpp
a20af25c38489b658ffe50700549088ffe10bffc
[]
no_license
AWoLf98/CPP-Advanced-Programing
bc8d9fc50731ccd22d433c2c7842bb7c5b68fc6d
1cccb906dc8a3d3ea07b4d55d6fd47284e2fd5be
refs/heads/master
2021-08-31T04:38:12.021413
2017-12-20T10:16:48
2017-12-20T10:16:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; //your_code int main() { vector<int> values = { 1, 1, 5, 3, 4, 4, 3, 2, 2, 4, 4, 5, 3, 8, 8, 1 }; //your_code // pattern 1: { 0, 1, -1 } // pattern 2: { -1, 1, 0 } return 0; }
[ "andresistuk@ukr.net" ]
andresistuk@ukr.net
897cab253c90b9ff94274363bd7767a992fca802
21f082941cce3824ba96366e576308de135c08a7
/src/rpcblockchain.cpp
75ede93db5c20ab574c7bb7bfe3d3f935ea5d7b8
[ "MIT" ]
permissive
chain123-team/litecoins
f1f582ec0f85e0b13c18781a4d8720cd35e32909
0409e805314b5e200a065c676d674e92840094a1
refs/heads/main
2023-09-02T23:04:20.061668
2021-11-12T07:55:47
2021-11-12T07:55:47
290,706,290
0
0
null
null
null
null
UTF-8
C++
false
false
34,678
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "checkpoints.h" #include "clientversion.h" #include "core_io.h" #include "main.h" #include "rpcserver.h" #include "sync.h" #include "txdb.h" #include "util.h" #include "utilmoneystr.h" #include <stdint.h> #include <univalue.h> using namespace std; double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == nullptr) { if (chainActive.Tip() == nullptr) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (txDetails) { UniValue objTx(UniValue::VOBJ); TxToUniv(tx, uint256(0), objTx); txs.push_back(objTx); } else txs.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex* pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); result.push_back(Pair("modifier", strprintf("%016x", blockindex->nStakeModifier))); result.push_back(Pair("moneysupply",ValueFromAmount(blockindex->nMoneySupply))); return result; } UniValue getblockcount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest block chain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "")); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest block chain.\n" "\nResult\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "")); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } UniValue getdifficulty(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "")); LOCK(cs_main); return GetDifficulty(); } UniValue mempoolToJSON(bool fVerbose = false) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); BOOST_FOREACH (const PAIRTYPE(uint256, CTxMemPoolEntry) & entry, mempool.mapTx) { const uint256& hash = entry.first; const CTxMemPoolEntry& e = entry.second; UniValue info(UniValue::VOBJ); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); const CTransaction& tx = e.GetTx(); set<string> setDepends; BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); BOOST_FOREACH(const string& dep, setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); o.push_back(Pair(hash.ToString(), info)); } return o; } else { vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); BOOST_FOREACH (const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" " \"size\" : n, (numeric) transaction size in bytes\n" " \"fee\" : n, (numeric) transaction fee in lts\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) transaction priority now\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n" " }, ...\n" "]\n" "\nExamples\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true")); LOCK(cs_main); bool fVerbose = false; if (params.size() > 0) fVerbose = params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash index\n" "\nReturns hash of block in best-block-chain at index provided.\n" "\nArguments:\n" "1. index (numeric, required) The block index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000")); LOCK(cs_main); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" " \"moneysupply\" : \"supply\" (numeric) The money supply when this block was added to the blockchain\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") + HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")); LOCK(cs_main); uint256 hash(ParseHashV(params[0].get_str(), "blockhash")); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!ReadBlockFromDisk(block, pblockindex)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex); } UniValue getblockheader(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash' header.\n" "If verbose is true, returns an Object with information about block <hash> header.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"version\" : n, (numeric) The block version\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash' header.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") + HelpExampleRpc("getblockheader", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")); uint256 hash(ParseHashV(params[0].get_str(), "hash")); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) the best block hash hex\n" " \"transactions\": n, (numeric) The number of transactions\n" " \"txouts\": n, (numeric) The number of output transactions\n" " \"bytes_serialized\": n, (numeric) The serialized size\n" " \"hash_serialized\": \"hash\", (string) The serialized hash\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "")); LOCK(cs_main); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } return ret; } UniValue gettxout(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "gettxout \"txid\" n ( includemempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. n (numeric, required) vout value\n" "3. includemempool (boolean, optional) Whether to included the mem pool\n" "\nResult:\n" "{\n" " \"bestblock\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in lts\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of lts addresses\n" " \"ltsaddress\" (string) lts address\n" " ,...\n" " ]\n" " },\n" " \"version\" : n, (numeric) The version\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1")); LOCK(cs_main); UniValue ret(UniValue::VOBJ); uint256 hash(ParseHashV(params[0].get_str(), "txid")); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return NullUniValue; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return NullUniValue; } if (n < 0 || (unsigned int)n >= coins.vout.size() || coins.vout[n].IsNull()) return NullUniValue; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex* pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } UniValue verifychain(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "verifychain ( checklevel numblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=3) How thorough the block verification is.\n" "2. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "")); LOCK(cs_main); int nCheckLevel = GetArg("-checklevel", 3); int nCheckDepth = GetArg("-checkblocks", 288); if (params.size() > 0) nCheckLevel = params[0].get_int(); if (params.size() > 1) nCheckDepth = params[1].get_int(); return CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth); } UniValue getblockchaininfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding block chain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "")); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(chainActive.Tip()))); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "")); LOCK(cs_main); /* Build up a list of chain tips. We start with the list of all known blocks, and successively remove blocks that appear as pprev of another block. */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex) setTips.insert(item.second); BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex) { const CBlockIndex* pprev = item.second->pprev; if (pprev) setTips.erase(pprev); } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); BOOST_FOREACH (const CBlockIndex* block, setTips) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } UniValue getfeeinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getfeeinfo blocks\n" "\nReturns details of transaction fees over the last n blocks.\n" "\nArguments:\n" "1. blocks (int, required) the number of blocks to get transaction data from\n" "\nResult:\n" "{\n" " \"txcount\": xxxxx (numeric) Current tx count\n" " \"txbytes\": xxxxx (numeric) Sum of all tx sizes\n" " \"ttlfee\": xxxxx (numeric) Sum of all fees\n" " \"feeperkb\": xxxxx (numeric) Average fee per kb over the block range\n" " \"rec_highpriorityfee_perkb\": xxxxx (numeric) Recommended fee per kb to use for a high priority tx\n" "}\n" "\nExamples:\n" + HelpExampleCli("getfeeinfo", "5") + HelpExampleRpc("getfeeinfo", "5")); LOCK(cs_main); int nBlocks = params[0].get_int(); int nBestHeight = chainActive.Height(); int nStartHeight = nBestHeight - nBlocks; if (nBlocks < 0 || nStartHeight <= 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid start height"); CAmount nFees = 0; int64_t nBytes = 0; int64_t nTotal = 0; for (int i = nStartHeight; i <= nBestHeight; i++) { CBlockIndex* pindex = chainActive[i]; CBlock block; if (!ReadBlockFromDisk(block, pindex)) throw JSONRPCError(RPC_DATABASE_ERROR, "failed to read block from disk"); CAmount nValueIn = 0; CAmount nValueOut = 0; for (const CTransaction& tx : block.vtx) { if (tx.IsCoinBase() || tx.IsCoinStake()) continue; for (unsigned int j = 0; j < tx.vin.size(); j++) { COutPoint prevout = tx.vin[j].prevout; CTransaction txPrev; uint256 hashBlock; if(!GetTransaction(prevout.hash, txPrev, hashBlock, true)) throw JSONRPCError(RPC_DATABASE_ERROR, "failed to read tx from disk"); nValueIn += txPrev.vout[prevout.n].nValue; } for (unsigned int j = 0; j < tx.vout.size(); j++) { nValueOut += tx.vout[j].nValue; } nFees += nValueIn - nValueOut; nBytes += tx.GetSerializeSize(SER_NETWORK, CLIENT_VERSION); nTotal++; } pindex = chainActive.Next(pindex); if (!pindex) break; } UniValue ret(UniValue::VOBJ); CFeeRate nFeeRate = CFeeRate(nFees, nBytes); ret.push_back(Pair("txcount", (int64_t)nTotal)); ret.push_back(Pair("txbytes", (int64_t)nBytes)); ret.push_back(Pair("ttlfee", FormatMoney(nFees))); ret.push_back(Pair("feeperkb", FormatMoney(nFeeRate.GetFeePerK()))); ret.push_back(Pair("rec_highpriorityfee_perkb", FormatMoney(nFeeRate.GetFeePerK() + 1000))); return ret; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); //ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage())); return ret; } UniValue getmempoolinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx (numeric) Current tx count\n" " \"bytes\": xxxxx (numeric) Sum of all tx sizes\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "")); return mempoolInfoToJSON(); } UniValue invalidateblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "invalidateblock \"hash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to mark as invalid\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"")); uint256 hash(ParseHashV(params[0].get_str(), "blockhash")); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, pblockindex); } if (state.IsValid()) { ActivateBestChain(state); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "reconsiderblock \"hash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to reconsider\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"")); uint256 hash(ParseHashV(params[0].get_str(), "blockhash")); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ReconsiderBlock(state, pblockindex); } if (state.IsValid()) { ActivateBestChain(state); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; }
[ "123chain.team@gmail.com" ]
123chain.team@gmail.com
f91309ec1463d73994907e0d9d98999d87ff8da2
1a4d186d84b819da76c0ba6e1ebb3af87307a8f3
/2257.cpp
f7f363ebc7d8865bb5cfc8d5a9553ca58d740919
[]
no_license
JungHam/algorithm
b5e986c9e6c70e9092394417c53eaabebe0b8bf1
ead08c8abe19a232651993ea5d52212b9262a4b7
refs/heads/master
2020-03-19T07:19:13.010706
2018-10-28T12:31:25
2018-10-28T12:31:25
136,104,591
0
0
null
null
null
null
UTF-8
C++
false
false
1,637
cpp
#include <iostream> #include <string> #include <ctype.h> using namespace std; string chemical; long long global_count = 0; long long calcChemical(string part_c){ long long local_count= 0; long long previous_count = 0; int i = 0; while(global_count < part_c.size()){ //전역변수로 index 체크하는 경우에는 for문은 괜히 한바퀴 돌고 계속 index를 증감해야 되서 계산하기 헷갈리니까 while문을 쓰자. if(part_c.at(global_count) == ')'){ local_count += previous_count; global_count++; return local_count; } if(part_c.at(global_count) == '(') { local_count += previous_count; global_count++; previous_count = calcChemical(part_c); continue; } else if(isdigit(part_c.at(global_count))){ local_count += previous_count * (int)(part_c.at(global_count) - '0'); previous_count = 0; global_count++; } else{ local_count += previous_count; previous_count = 0; if(part_c.at(global_count) == 'H') previous_count = 1; else if(part_c.at(global_count) == 'C') previous_count = 12; else if(part_c.at(global_count) == 'O') previous_count = 16; global_count++; } } local_count += previous_count; return local_count; } int main() { while(cin >> chemical){ long long cost = calcChemical(chemical); cout << cost << endl; global_count = 0; } return 0; }
[ "wjdgpal7@gmail.com" ]
wjdgpal7@gmail.com
9a42a6a8494e88ca07433ce1dcc5d9be358ece6b
0fa86e5ba6e6723ec1c2f72dc2812af566a61581
/src/Camera.cpp
025074473800480f4c6b54acf698fdf264dcf6ba
[ "MIT" ]
permissive
janisz/gk3d
3814a1189f4eda29836f0ad5c616672e4f855673
9bda743a956f646867c527c4505543d4047d5ba3
refs/heads/master
2021-01-22T01:04:35.025942
2014-12-08T18:49:17
2014-12-08T18:49:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,891
cpp
#include <stdio.h> #include <math.h> #include <GL/glut.h> #include "Camera.h" void Camera::Init() { m_yaw = 0.0; m_pitch = 0.0; SetPos(0, 0, 0); } void Camera::Refresh() { // Camera parameter according to Riegl's co-ordinate system // x/y for flat, z for height m_lx = cos(m_yaw) * cos(m_pitch); m_ly = sin(m_pitch); m_lz = sin(m_yaw) * cos(m_pitch); m_strafe_lx = cos(m_yaw - M_PI_2); m_strafe_lz = sin(m_yaw - M_PI_2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_x, m_y, m_z, m_x + m_lx, m_y + m_ly, m_z + m_lz, 0.0,1.0,0.0); //printf("Camera: %f %f %f Direction vector: %f %f %f\n", m_x, m_y, m_z, m_lx, m_ly, m_lz); } void Camera::SetPos(float x, float y, float z) { m_x = x; m_y = y; m_z =z; Refresh(); } void Camera::GetPos(float &x, float &y, float &z) { x = m_x; y = m_y; z = m_z; } void Camera::GetDirectionVector(float &x, float &y, float &z) { x = m_lx; y = m_ly; z = m_lz; } void Camera::Move(float incr) { float lx = cos(m_yaw)*cos(m_pitch); float ly = sin(m_pitch); float lz = sin(m_yaw)*cos(m_pitch); m_x = m_x + incr*lx; m_y = m_y + incr*ly; m_z = m_z + incr*lz; Refresh(); } void Camera::Strafe(float incr) { m_x = m_x + incr*m_strafe_lx; m_z = m_z + incr*m_strafe_lz; Refresh(); } void Camera::Fly(float incr) { m_y = m_y + incr; Refresh(); } void Camera::RotateYaw(float angle) { m_yaw += angle; Refresh(); } void Camera::RotatePitch(float angle) { const float limit = 89.0 * M_PI / 180.0; m_pitch += angle; if(m_pitch < -limit) m_pitch = -limit; if(m_pitch > limit) m_pitch = limit; Refresh(); } void Camera::SetYaw(float angle) { m_yaw = angle; Refresh(); } void Camera::SetPitch(float angle) { m_pitch = angle; Refresh(); }
[ "janiszt@gmail.com" ]
janiszt@gmail.com
9b3058d03ff2b7fc2ad16cb089d2a4c75f371b85
3f21c24ff10cba14ca4ab16ee62e8c1213b60bd0
/src/gestures/SystemGesture.cpp
03d4e8db2d65cba5171cd68042440ba4b06391d7
[]
no_license
watson-intu/self
273833269f5bf1027d823896e085ac675d1eb733
150dc55e193a1df01e7acfbc47610c29b279c2e7
refs/heads/develop
2021-01-20T03:15:02.118963
2018-04-16T08:19:31
2018-04-16T08:19:31
89,515,657
34
31
null
2018-04-16T08:15:51
2017-04-26T18:50:00
C++
UTF-8
C++
false
false
1,446
cpp
/** * Copyright 2017 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "SystemGesture.h" #include "utils/ThreadPool.h" REG_SERIALIZABLE( SystemGesture ); RTTI_IMPL( SystemGesture, IGesture ); void SystemGesture::Serialize(Json::Value & json) { IGesture::Serialize( json ); json["m_SystemId"] = m_SystemId; } void SystemGesture::Deserialize(const Json::Value & json) { IGesture::Deserialize( json ); if ( json.isMember( "m_SystemId" ) ) m_SystemId = json["m_SystemId"].asString(); } bool SystemGesture::Execute( GestureDelegate a_Callback, const ParamsMap & a_Params ) { if ( m_SystemId == "reboot" ) ThreadPool::Instance()->StopMainThread(1); else if ( m_SystemId == "shutdown" ) ThreadPool::Instance()->StopMainThread(0); else Log::Warning( "SystemGesture", "Unsupported system gesture %s", m_SystemId.c_str() ); if ( a_Callback.IsValid() ) a_Callback( this ); return true; }
[ "rolyle@us.ibm.com" ]
rolyle@us.ibm.com
e6b2340e49f0a04fd8c583d433974d25dd44984a
25765941341ff304a3c7faf0ddee437f3bea8310
/src/WinMain.cxx
94a00033fdd67b18162d53c80d8f55e8a1dcb597
[ "BSD-3-Clause" ]
permissive
fermi-lat/gui
797cdf0dfb9a0905e2bebbe618dc8a4701c0ffc0
d2387b2d9f2bbde3a9310ff8f2cca038a339ebf6
refs/heads/master
2021-05-05T16:14:43.636293
2019-08-27T17:29:51
2019-08-27T17:29:51
103,186,998
0
0
null
null
null
null
UTF-8
C++
false
false
5,859
cxx
#ifdef WIN32 // only used for the windows app // $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/gui/src/WinMain.cxx,v 1.2 2002/11/01 22:57:05 burnett Exp $ #include "WinGui.h" #include "WinScene.h" #include "WinGUIostream.h" #include "gui/Menu.h" #include "gui/SubMenu.h" #include "resource.h" extern "C" { int main(int argn, char *argc[] );} static char *szAppName = "WinGUI"; //======================================================================== // Windows routines //======================================================================== LRESULT CALLBACK WndProc (HWND hWnd, unsigned Message, WPARAM wParam, LONG lParam) { // decide which window this is, set appropriate scene to message WinScene* display = ( hWnd==WinGUI::s_hwnd || WinGUI::s_hwnd==0)? WinGUI::s_graphics_window : WinGUI::s_2d_window; switch(Message) { case WM_COMMAND: WinGUI::s_gui->execute(wParam); break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc= BeginPaint( hWnd, &ps); if(display) display->redisplay(hdc); EndPaint(hWnd, &ps); } break; case WM_CHAR: { // single non-special key char c = static_cast<char>(wParam); // check if is is registered with the Menu if( Menu::instance()->strike(c)) break; // no, just pass it to the display char cmd[2] = {c,0}; if( display->do_command(cmd)>0 ) display->redisplay(); } break; case WM_KEYDOWN: { char cmd[2] = {0,0}; switch (wParam){ case VK_LEFT: cmd[1]=75; break; case VK_RIGHT:cmd[1]=77; break; case VK_HOME: cmd[1]=71; break; case VK_UP: cmd[1]=72; break; case VK_DOWN: cmd[1]=80; break; case VK_PRIOR:cmd[1]=73; break; case VK_NEXT: cmd[1]=81; break; } if (!cmd[1] )break; if( display->do_command(cmd)>0 ) display->redisplay(); } break; case WM_LBUTTONDOWN: { int xPos = LOWORD(lParam); // horizontal position of cursor int yPos = HIWORD(lParam); // vertical position of cursor display->mouseDown(xPos,yPos); } break; case WM_LBUTTONUP: { int xPos = LOWORD(lParam); // horizontal position of cursor int yPos = HIWORD(lParam); // vertical position of cursor display->mouseUp(xPos,yPos); } break; case WM_RBUTTONUP : { RECT winpos; ::GetWindowRect(hWnd, &winpos); ::TrackPopupMenu( (HMENU)(display->menu()->tag()), // handle to shortcut menu TPM_LEFTALIGN | TPM_TOPALIGN, // screen-position and mouse-button flags winpos.left+LOWORD(lParam), // horizontal position, in screen coordinates winpos.top+HIWORD(lParam), // vertical position, in screen coordinates 0, // reserved, must be zero hWnd, // handle to owner window 0); } break; case WM_ACTIVATEAPP: { int fActive = LOWORD(wParam); // activation flag if( fActive) ::SetCursor(::LoadCursor(NULL, IDC_ARROW)); break; } case WM_DESTROY: Menu::instance()->quit(); #if 0 ::PostQuitMessage(0); WinGUI::s_quitting=true; GUI::running=false; #endif break; case WM_SETCURSOR: // mouse comes over window--make it the normal arrow { ::SetCursor(::LoadCursor(NULL, IDC_ARROW)); break; } default: return ::DefWindowProc(hWnd, Message, wParam, lParam); } return 0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { WinGUI::s_instance = hThisInstance; //need the instance // declare, and create a windows class for the main window WNDCLASS wndClass; if (!hPrevInstance) { wndClass.style = CS_HREDRAW | CS_VREDRAW ; wndClass.lpfnWndProc = WndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hThisInstance; wndClass.hIcon = wndClass.hIcon= LoadIcon(hThisInstance,MAKEINTRESOURCE(IDI_ICON1));; wndClass.hCursor = NULL; wndClass.hbrBackground = (HBRUSH)GetStockObject (LTGRAY_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = szAppName; if( !RegisterClass(&wndClass) ) return FALSE; } // create the main window to be used later WinGUI::s_hwnd = CreateWindow(szAppName, "", (WS_OVERLAPPED | WS_CAPTION | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_SYSMENU),//WS_OVERLAPPEDWINDOW, 20, 20, //CW_USEDEFAULT, 0, 500, 500, //CW_USEDEFAULT, 0, NULL, NULL, WinGUI::s_instance, NULL); // setup the console window here WinGUI::s_text_window = new WinGUIostream( "wingui", WinGUI::s_hwnd, WinGUI::s_instance); // parse command line by hand const unsigned MAX_TOKENS=20; char * _argv[MAX_TOKENS]; _argv[0] = szAppName; int argc = 1; char seps[] = " \t\n"; /* Establish string and get the first token: */ char * token = strtok( lpszCmdLine, seps ); while(token != NULL && argc < MAX_TOKENS) { /* While there are tokens in "string" */ _argv[argc++] = token; /* Get next token: */ token = strtok( NULL, seps ); } // ::UserMain(argc, _argv); ::main(argc, _argv); return 0; } #endif
[ "" ]
48b037c14f1bbf610eb0e00e1730d52c6b18eca2
ef59aae67e896e78723b719415068aa93a685854
/others/sketch_oct09b/sketch_oct09b.ino
a453680e748b2c1ead3059f6cad0f87b4689f14f
[]
no_license
tokujin/Arduino
fe99fffa7c66dd0386fef1a4caee63ee509f7614
282de130362bd1e7aa8c74bd8bf55f37c70631e7
refs/heads/master
2016-09-06T05:12:09.744414
2013-05-08T16:52:43
2013-05-08T16:52:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
544
ino
int sensorPin = A0; //select the input pin for the potentiometer int ledPin = 13; //select the pin for the LED int sensorValue = 0; //variable to store the value coming from the int newSensorValue; void setup(){ //declare the ledPIN as an OUTPUT: pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop(){ //read the value from the sensor: sensorValue = analogRead(sensorPin); //turn the ledPIN on newSensorValue = map(sensorValue, 0, 1023, 0, 255); analogWrite(ledPin, newSensorValue); Serial.print(newSensorValue); }
[ "norihito.yuki@me.com" ]
norihito.yuki@me.com
97384d59742e4a539b01df4e008c02a55ae3f9a8
815aaa29871c1f4de330669ca692294c1c7baccb
/testscripts/indexgen2d_templated.cpp
c81be28cc3e49673017cb86cfc4140286ca51813
[]
no_license
khokhlov/solvergen
44a4aea8aaf6edebca2945560e6c539727cb2121
9bf580eeed1d263e83ca754417bd8365dcde7d30
refs/heads/master
2020-08-11T01:10:18.886710
2019-05-30T07:32:55
2019-05-30T07:39:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,147
cpp
#include <iostream> #include <vector> #include <bitset> #include <cmath> #include <array> #include <cassert> using namespace std; class Checker { public: Checker(int nx, int ny) : nx(nx), ny(ny), data(nx * ny, -1) { } bool check(int i, int j, int t) { int& val = data.at(i + nx * j); auto is = {-1, 0, 1}; auto js = {-1, 0, 1}; for (int iss : is) { for (int jss : js) { int ii = i + iss; int jj = j + jss; if (ii < 0 || jj < 0 || ii >= nx || jj >= ny) continue; int vval = data.at(ii + nx * jj); if (vval < t - 1) { return false; } } } if (val == t - 1) { val = t; return true; } else { return false; } } private: int nx, ny; std::vector<int> data; }; template <typename T> inline T pow2(T k) { return 1ll << k; } template <typename F> void tiledLoops(int nx, int ny, int nt, F func) { std::array<int8_t,24> lut_ii{ 0, 1,-1, 0, 0, 1, 1,-1,-1, 1,-1, 0, 0, 0, 1,-1, 0, 0, 0, 0, 0, 0, 1,-1 }; std::array<int8_t,24> lut_jj{ 0, 0, 0, 1,-1, 1,-1, 1,-1, 0, 0, 1,-1, 0, 0, 0, 0, 1,-1, 1,-1, 0, 0, 0 }; std::array<int8_t,24> lut_tt{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1 }; std::array<int8_t,24> lut_mode { 0,19,19,14,14, 0, 0, 0, 0,14,14,19,19, 0,14,14, 0,14,14,19,19, 0,19,19 }; int base = max(nx, ny); base = base | 1; // round up to the nearest odd number int height = nt; int32_t tileParam = 1; while (pow2(tileParam+1) < base + height - 1) { tileParam++; } assert(pow2(tileParam+1) >= base + height - 1); //cerr << "tileParam: " << tileParam << endl; int32_t sx = - base / 2; //cerr << "sx: " << sx << endl; int32_t ex = sx + nx - 1; //cerr << "ex: " << ex << endl; int32_t sy = - base / 2; //cerr << "sy: " << sy << endl; int32_t ey = sy + ny - 1; //cerr << "ey: " << ey << endl; int32_t st = + base / 2; //cerr << "st: " << st << endl; int32_t et = st + nt - 1; //cerr << "et: " << et << endl; // size of array is the logarithm of desired tile size std::vector<int8_t> state(tileParam); // height of the tile depends on the number of iterations: // num of iterations: 2^{3i+1}-2^i // i from 1 to inf // height big: 2^{i+1} ( range: [0;2^{i+1}-1] ) // height small: 2^i ( range: [0;2^i-1] ) // width: 2^{i+1} - 1 ( range: [-(2^i - 1); +(2^i - 1)] ) int64_t iterations = pow2(3ll * tileParam + 1ll) - pow2(tileParam); //iterations = 20; //cerr << "iterations: " << iterations << endl; std::vector<int32_t> tts(tileParam + 1); std::vector<int32_t> iis(tileParam + 1); std::vector<int32_t> jjs(tileParam + 1); size_t K = state.size() - 1; bool finished = false; while (1) { //cerr << "=====" << endl; // step //for (int i = 0; i < state.size(); i++) { // cerr << int(state[i]) << " "; //} //cerr << endl; bool skipTile = false; while (1) { int32_t ss = state[K]; int32_t tt = lut_tt[ss]; int32_t ii = lut_ii[ss]; int32_t jj = lut_jj[ss]; tts[K] = tts[K+1] + (tt << K); iis[K] = iis[K+1] + (ii << K); jjs[K] = jjs[K+1] + (jj << K); int32_t min_t = tts[K] + 0; int32_t min_x = iis[K] - (pow2(K + 1) - 1); int32_t min_y = jjs[K] - (pow2(K + 1) - 1); int32_t mode = lut_mode[ss]; int32_t height = pow2(K + (mode == 0 ? 2 : 1)) - 1; int32_t max_t = tts[K] + height - 1; int32_t max_x = iis[K] + (pow2(K + 1) - 1); int32_t max_y = jjs[K] + (pow2(K + 1) - 1); //cerr // << min_x << " " // << max_x << " " // << min_y << " " // << max_y << " " // << min_t << " " // << max_t << " " // << endl; if (max_t < st || min_t > et || max_x < sx || min_x > ex || max_y < sy || min_y > ey) { skipTile = true; break; } if (K == 0) break; state[K-1] = lut_mode[state[K]]; K--; }; //cerr << "skipTile: " << skipTile << endl; //cerr << "ijt: " << iis[0] << " " << jjs[0] << " " << tts[0] << endl; if (!skipTile) { // print if (sx <= iis[0] && iis[0] <= ex && sy <= jjs[0] && jjs[0] <= ey) { if (st <= tts[0] && tts[0] <= et) { func(iis[0] - sx, jjs[0] - sy, tts[0] - st); } if (lut_mode[state[0]] == 0) { if(st <= tts[0] + 1 && tts[0] + 1 <= et) { func(iis[0] - sx, jjs[0] - sy, tts[0] + 1 - st); } } } } while (state[K] == 13 || state[K] == 18 || state[K] == 23) { K++; if (K == state.size()) { finished = true; break; } } if (finished == true) break; state[K]++; } } template <int Level, typename F> struct SmallTileX { static void run(int i, int j, int t, int nx, int ny, int nt, F func); }; template <int Level, typename F> struct SmallTileY { static void run(int i, int j, int t, int nx, int ny, int nt, F func); }; template <int Level, typename F> struct LargeTile { static void run(int i, int j, int t, int nx, int ny, int nt, F func); }; template <int Level, typename F> void SmallTileX<Level, F>::run(int i, int j, int t, int nx, int ny, int nt, F func) { constexpr int tileSize = 1 << (Level - 1); constexpr int tileWidth = tileSize * 2 - 1; constexpr int tileHeight = tileSize * 2 - 1; if (i + tileWidth < 0 || i - tileWidth >= nx || j + tileWidth < 0 || j - tileWidth >= ny || t + tileHeight < 0 || t >= nt) return; SmallTileX<Level - 1, F>::run(i - tileSize, j, t, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i + tileSize, j, t, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i, j, t, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i, j - tileSize, t + tileSize, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i, j + tileSize, t + tileSize, nx, ny, nt, func); } template <int Level, typename F> void SmallTileY<Level, F>::run(int i, int j, int t, int nx, int ny, int nt, F func) { constexpr int tileSize = 1 << (Level - 1); constexpr int tileWidth = tileSize * 2 - 1; constexpr int tileHeight = tileSize * 2 - 1; if (i + tileWidth < 0 || i - tileWidth >= nx || j + tileWidth < 0 || j - tileWidth >= ny || t + tileHeight < 0 || t >= nt) return; SmallTileY<Level - 1, F>::run(i, j - tileSize, t, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i, j + tileSize, t, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i, j, t, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i - tileSize, j, t + tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i + tileSize, j, t + tileSize, nx, ny, nt, func); } template <int Level, typename F> void LargeTile<Level, F>::run(int i, int j, int t, int nx, int ny, int nt, F func) { constexpr int tileSize = 1 << (Level - 1); constexpr int tileWidth = tileSize * 2 - 1; constexpr int tileHeight = tileSize * 4 - 1; if (i + tileWidth < 0 || i - tileWidth >= nx || j + tileWidth < 0 || j - tileWidth >= ny || t + tileHeight < 0 || t >= nt) return; LargeTile<Level - 1, F>::run(i, j, t, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i, j - tileSize, t + tileSize, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i, j + tileSize, t + tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i - tileSize, j, t + tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i + tileSize, j, t + tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i - tileSize, j - tileSize, t + tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i + tileSize, j - tileSize, t + tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i - tileSize, j + tileSize, t + tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i + tileSize, j + tileSize, t + tileSize, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i - tileSize, j, t + 2 * tileSize, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i + tileSize, j, t + 2 * tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i, j - tileSize, t + 2 * tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i, j + tileSize, t + 2 * tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i, j, t + 2 * tileSize, nx, ny, nt, func); } template <typename F> struct SmallTileX<0, F> { static void run(int i, int j, int t, int nx, int ny, int nt, F func) { if (0 <= i && i < nx && 0 <= j && j < ny && 0 <= t && t < nt) { func(i, j, t); } } }; template <typename F> struct SmallTileY<0, F> { static void run(int i, int j, int t, int nx, int ny, int nt, F func) { if (0 <= i && i < nx && 0 <= j && j < ny && 0 <= t && t < nt) { func(i, j, t); } } }; template <typename F> struct LargeTile<0, F> { static void run(int i, int j, int t, int nx, int ny, int nt, F func) { if (0 <= i && i < nx && 0 <= j && j < ny) { if (0 <= t && t < nt) func(i, j, t); if (0 <= t + 1 && t + 1 < nt) func(i, j, t + 1); } } }; template <typename F> void tiledLoopsTemplated(int nx, int ny, int nt, F f) { constexpr int tileSize = 15; int nodesWidth = std::max(nx, std::max(ny, nt)); int requiredTileSize = 0; while ((1 << requiredTileSize) < nodesWidth) requiredTileSize++; assert(requiredTileSize <= tileSize); LargeTile<tileSize, decltype(f)>::run(0, 0, -(1 << tileSize), nx, ny, nt, f); } int main() { int nx = 2000; int ny = 2000; int nt = 100; Checker checker(nx, ny); int unused = 0; //auto f = [&unused,&checker](int i, int j, int t) { // std::cout << i << " " << j << " " << t << endl; // //cerr << "ijt: " << i << " " << j << " " << t << endl; // assert(checker.check(i, j, t)); // unused += i + j + t; //}; //tiledLoops(nx, ny, nt, f); //templatedTiledLoops(); auto f = [&](int i, int j, int t) { //std::cerr << i << " " << j << " " << t << endl; //std::cout << i << " " << j << " " << t << endl; //assert(checker.check(i, j, t)); unused += i + j + t; }; tiledLoopsTemplated(nx, ny, nt, f); cerr << "unused: " << unused << endl; }
[ "furgailo@phystech.edu" ]
furgailo@phystech.edu
d6e3e45aa5dc3fb224dfdc730466e1a003ab94c9
663ab089cf6b940fa8245a897b5cc3887dfa089f
/src/gpplib.cpp
9daeba0357660425e3e1f10bd481a3827faf3519
[]
no_license
alfaki/gppk
eef55e803229cd27ca681e79d9448e8a7f6e2f9c
1baf8f0edd722028081986ba748c32ea5bc33b34
refs/heads/main
2022-12-29T19:05:17.447179
2020-10-08T19:08:11
2020-10-08T19:08:11
302,432,462
0
0
null
null
null
null
UTF-8
C++
false
false
5,750
cpp
/* gpplib.cpp (miscellaneous library routines) */ /****************************************************************************** * This code is part of GPPK (The Generalized Pooling Problem Kit). * * Copyright (C) 2009, 2010 Mohammed Alfaki, Department of Informatics, * University of Bergen, Bergen, Norway. All rights reserved. E-mail: * <mohammeda@ii.uib.no>. * * GPPK 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. ******************************************************************************/ #include "gppk.h" /* Write formatted output to char string */ string get_str(const char *fmt, ...) { char *cstr; va_list arg; va_start(arg, fmt); int val = vasprintf(&cstr, fmt, arg); va_end(arg); string str(cstr); free(cstr); return str; } /* print error message and terminate processing */ void xerror(const char *fmt, ...) { va_list arg; va_start(arg, fmt); vprintf(fmt, arg); va_end(arg); printf("\n"); longjmp(buf, 1); /* no return */ } /* return file name for a full path of file */ string file_name(const char *file) { string str = file, fname, fpath; size_t size = str.find_last_of("/\\"); fpath = str.substr(0,size); fname = str.substr(size+1); size = str.substr(size+1).find_last_of("."); fname = fname.substr(0, size); return fname; } /* return the current date and time char string */ char *cdate() { time_t rawtime; struct tm *timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); return asctime(timeinfo); } /* convert time in seconds to hh:mm:ss */ string clocktime(double ttime) { char *ctime; ctime = new char[STRING_LENGTH]; int time, hr, mn, sc, ms; time = (int)ttime; hr = time/3600; time = time%3600; mn = time/60; sc = time%60; ms = (int)(100*(ttime-(double)time)); sprintf(ctime, "%02d:%02d:%02d:%02d", hr, mn, sc, ms); string str(ctime); delete[] ctime; return str; } /* compute n choose k */ int n_choose_k(int n, int k) { if (k <= 0 || k >= n) return 1; else return n_choose_k(n-1, k-1)+n_choose_k(n-1, k); } /****************************************************************************** * NAME * str2int - convert character string to value of int type * * SYNOPSIS * #include "gppk.h" * int str2int(const char *str, int *val); * * DESCRIPTION * The routine str2int converts the character string str to a value of * integer type and stores the value into location, which the parameter * val points to (in the case of error content of this location is not * changed). * * RETURNS * The routine returns one of the following error codes: * 0 - no error; * 1 - value out of range; * 2 - character string is syntactically incorrect. ******************************************************************************/ int str2int(const char *str, int *_val) { int d, k, s, val = 0; /* scan optional sign */ if (str[0] == '+') s = +1, k = 1; else if (str[0] == '-') s = -1, k = 1; else s = +1, k = 0; /* check for the first digit */ if (!isdigit((unsigned char)str[k])) return 2; /* scan digits */ while (isdigit((unsigned char)str[k])) { d = str[k++] - '0'; if (s > 0) { if (val > INT_MAX / 10) return 1; val *= 10; if (val > INT_MAX - d) return 1; val += d; } else { if (val < INT_MIN / 10) return 1; val *= 10; if (val < INT_MIN + d) return 1; val -= d; } } /* check for terminator */ if (str[k] != '\0') return 2; /* conversion has been done */ *_val = val; return 0; } /****************************************************************************** * NAME * str2num - convert character string to value of double type * * SYNOPSIS * #include ".h" * int str2num(const char *str, double *val); * * DESCRIPTION * The routine str2num converts the character string str to a value of * double type and stores the value into location, which the parameter * val points to (in the case of error content of this location is not * changed). * * RETURNS * The routine returns one of the following error codes: * 0 - no error; * 1 - value out of range; * 2 - character string is syntactically incorrect. ******************************************************************************/ int str2num(const char *str, double *_val) { int k; double val; /* scan optional sign */ k = (str[0] == '+' || str[0] == '-' ? 1 : 0); /* check for decimal point */ if (str[k] == '.') { k++; /* a digit should follow it */ if (!isdigit((unsigned char)str[k])) return 2; k++; goto frac; } /* integer part should start with a digit */ if (!isdigit((unsigned char)str[k])) return 2; /* scan integer part */ while (isdigit((unsigned char)str[k])) k++; /* check for decimal point */ if (str[k] == '.') k++; frac: /* scan optional fraction part */ while (isdigit((unsigned char)str[k])) k++; /* check for decimal exponent */ if (str[k] == 'E' || str[k] == 'e') { k++; /* scan optional sign */ if (str[k] == '+' || str[k] == '-') k++; /* a digit should follow E, E+ or E- */ if (!isdigit((unsigned char)str[k])) return 2; } /* scan optional exponent part */ while (isdigit((unsigned char)str[k])) k++; /* check for terminator */ if (str[k] != '\0') return 2; /* perform conversion */ { char *endptr; val = strtod(str, &endptr); if (*endptr != '\0') return 2; } /* check for overflow */ if (!(-DBL_MAX <= val && val <= +DBL_MAX)) return 1; /* check for underflow */ if (-DBL_MIN < val && val < +DBL_MIN) val = 0.0; /* conversion has been done */ *_val = val; return 0; } /* eof */
[ "moh_alfaki@hotmail.com" ]
moh_alfaki@hotmail.com
b4fb2210a8be6a954abc1a796044da981b41c1a0
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/third_party/blink/renderer/core/layout/ng/mathml/ng_math_radical_layout_algorithm.cc
eda8c7b094f7dd09b2182023358314d5f55cbd49
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
10,177
cc
// Copyright 2020 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 "third_party/blink/renderer/core/layout/ng/mathml/ng_math_radical_layout_algorithm.h" #include "third_party/blink/renderer/core/layout/ng/mathml/ng_math_layout_utils.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h" #include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h" #include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h" #include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" #include "third_party/blink/renderer/platform/fonts/shaping/stretchy_operator_shaper.h" namespace blink { namespace { bool HasBaseGlyphForRadical(const ComputedStyle& style) { return style.GetFont().PrimaryFont() && style.GetFont().PrimaryFont()->GlyphForCharacter(kSquareRootCharacter); } } // namespace NGMathRadicalLayoutAlgorithm::NGMathRadicalLayoutAlgorithm( const NGLayoutAlgorithmParams& params) : NGLayoutAlgorithm(params) { DCHECK(params.space.IsNewFormattingContext()); container_builder_.SetIsNewFormattingContext( params.space.IsNewFormattingContext()); } void NGMathRadicalLayoutAlgorithm::GatherChildren( NGBlockNode* base, NGBlockNode* index, NGBoxFragmentBuilder* container_builder) const { for (NGLayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { NGBlockNode block_child = To<NGBlockNode>(child); if (child.IsOutOfFlowPositioned()) { if (container_builder) { container_builder->AddOutOfFlowChildCandidate( block_child, BorderScrollbarPadding().StartOffset()); } continue; } if (!*base) { *base = block_child; continue; } if (!*index) { *index = block_child; continue; } NOTREACHED(); } if (Node().HasIndex()) { DCHECK(*base); DCHECK(*index); } } scoped_refptr<const NGLayoutResult> NGMathRadicalLayoutAlgorithm::Layout() { DCHECK(!BreakToken()); DCHECK(IsValidMathMLRadical(Node())); auto vertical = GetRadicalVerticalParameters(Style(), Node().HasIndex()); scoped_refptr<const NGPhysicalBoxFragment> index_fragment, base_fragment; LayoutUnit index_inline_size, index_ascent, index_descent, base_ascent, base_descent; RadicalHorizontalParameters horizontal; NGBoxStrut index_margins, base_margins; NGBlockNode base = nullptr; NGBlockNode index = nullptr; GatherChildren(&base, &index, &container_builder_); if (base) { // Handle layout of base child. For <msqrt> the base is anonymous and uses // the row layout algorithm. NGConstraintSpace constraint_space = CreateConstraintSpaceForMathChild( Node(), ChildAvailableSize(), ConstraintSpace(), base); scoped_refptr<const NGLayoutResult> base_layout_result = base.Layout(constraint_space); base_fragment = &To<NGPhysicalBoxFragment>(base_layout_result->PhysicalFragment()); base_margins = ComputeMarginsFor(constraint_space, base.Style(), ConstraintSpace()); NGBoxFragment fragment(ConstraintSpace().GetWritingMode(), ConstraintSpace().Direction(), *base_fragment); base_ascent = base_margins.block_start + fragment.Baseline().value_or(fragment.BlockSize()); base_descent = fragment.BlockSize() + base_margins.BlockSum() - base_ascent; } if (index) { // Handle layout of index child. // (https://mathml-refresh.github.io/mathml-core/#root-with-index). NGConstraintSpace constraint_space = CreateConstraintSpaceForMathChild( Node(), ChildAvailableSize(), ConstraintSpace(), index); scoped_refptr<const NGLayoutResult> index_layout_result = index.Layout(constraint_space); index_fragment = &To<NGPhysicalBoxFragment>(index_layout_result->PhysicalFragment()); index_margins = ComputeMarginsFor(constraint_space, index.Style(), ConstraintSpace()); NGBoxFragment fragment(ConstraintSpace().GetWritingMode(), ConstraintSpace().Direction(), *index_fragment); index_inline_size = fragment.InlineSize() + index_margins.InlineSum(); index_ascent = index_margins.block_start + fragment.Baseline().value_or(fragment.BlockSize()); index_descent = fragment.BlockSize() + index_margins.BlockSum() - index_ascent; horizontal = GetRadicalHorizontalParameters(Style()); horizontal.kern_before_degree = std::max(horizontal.kern_before_degree, LayoutUnit()); horizontal.kern_after_degree = std::max(horizontal.kern_after_degree, -index_inline_size); } StretchyOperatorShaper::Metrics surd_metrics; if (HasBaseGlyphForRadical(Style())) { // Stretch the radical operator to cover the base height. StretchyOperatorShaper shaper(kSquareRootCharacter, OpenTypeMathStretchData::Vertical); float target_size = base_ascent + base_descent + vertical.vertical_gap + vertical.rule_thickness; scoped_refptr<ShapeResult> shape_result = shaper.Shape(&Style().GetFont(), target_size, &surd_metrics); scoped_refptr<ShapeResultView> shape_result_view = ShapeResultView::Create(shape_result.get()); LayoutUnit operator_inline_offset = index_inline_size + horizontal.kern_before_degree + horizontal.kern_after_degree; container_builder_.SetMathMLPaintInfo( kSquareRootCharacter, std::move(shape_result_view), LayoutUnit(surd_metrics.advance), LayoutUnit(surd_metrics.ascent), LayoutUnit(surd_metrics.descent), &operator_inline_offset, &base_margins); } // Determine the metrics of the radical operator + the base. LayoutUnit radical_operator_block_size = LayoutUnit(surd_metrics.ascent + surd_metrics.descent); LayoutUnit index_bottom_raise = LayoutUnit(vertical.degree_bottom_raise_percent) * radical_operator_block_size; LayoutUnit radical_ascent = base_ascent + vertical.vertical_gap + vertical.rule_thickness + vertical.extra_ascender; LayoutUnit ascent = radical_ascent; LayoutUnit descent = std::max(base_descent, radical_operator_block_size + vertical.extra_ascender - ascent); if (index) { ascent = std::max( ascent, -descent + index_bottom_raise + index_descent + index_ascent); descent = std::max( descent, descent - index_bottom_raise + index_descent + index_ascent); } ascent += BorderScrollbarPadding().block_start; if (base) { LogicalOffset base_offset = { BorderScrollbarPadding().inline_start + LayoutUnit(surd_metrics.advance) + index_inline_size + horizontal.kern_before_degree + horizontal.kern_after_degree + base_margins.inline_start, base_margins.block_start - base_ascent + ascent}; container_builder_.AddChild(To<NGPhysicalContainerFragment>(*base_fragment), base_offset); base.StoreMargins(ConstraintSpace(), base_margins); } if (index) { LogicalOffset index_offset = { BorderScrollbarPadding().inline_start + index_margins.inline_start + horizontal.kern_before_degree, index_margins.block_start + ascent + descent - index_bottom_raise - index_descent - index_ascent}; container_builder_.AddChild( To<NGPhysicalContainerFragment>(*index_fragment), index_offset); index.StoreMargins(ConstraintSpace(), index_margins); } container_builder_.SetBaseline(ascent); auto total_block_size = ascent + descent + BorderScrollbarPadding().block_end; LayoutUnit block_size = ComputeBlockSizeForFragment( ConstraintSpace(), Style(), BorderPadding(), total_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetIntrinsicBlockSize(total_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); NGOutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } MinMaxSizesResult NGMathRadicalLayoutAlgorithm::ComputeMinMaxSizes( const MinMaxSizesInput& input) const { DCHECK(IsValidMathMLRadical(Node())); NGBlockNode base = nullptr; NGBlockNode index = nullptr; GatherChildren(&base, &index); MinMaxSizes sizes; bool depends_on_percentage_block_size = false; if (index) { auto horizontal = GetRadicalHorizontalParameters(Style()); sizes += horizontal.kern_before_degree.ClampNegativeToZero(); MinMaxSizesResult index_result = ComputeMinAndMaxContentContribution(Style(), index, input); NGBoxStrut index_margins = ComputeMinMaxMargins(Style(), index); index_result.sizes += index_margins.InlineSum(); depends_on_percentage_block_size |= index_result.depends_on_percentage_block_size; sizes += index_result.sizes; // kern_after_degree decreases the inline size, but is capped by the index // content inline size. sizes.min_size += std::max(-index_result.sizes.min_size, horizontal.kern_after_degree); sizes.max_size += std::max(index_result.sizes.max_size, horizontal.kern_after_degree); } if (base) { if (HasBaseGlyphForRadical(Style())) { sizes += GetMinMaxSizesForVerticalStretchyOperator(Style(), kSquareRootCharacter); } MinMaxSizesResult base_result = ComputeMinAndMaxContentContribution(Style(), base, input); NGBoxStrut base_margins = ComputeMinMaxMargins(Style(), base); base_result.sizes += base_margins.InlineSum(); depends_on_percentage_block_size |= base_result.depends_on_percentage_block_size; sizes += base_result.sizes; } sizes += BorderScrollbarPadding().InlineSum(); return {sizes, depends_on_percentage_block_size}; } } // namespace blink
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
79cf562e9c03a4d758dc342b509b48998be8c660
792e697ba0f9c11ef10b7de81edb1161a5580cfb
/tools/clang/test/CXX/drs/dr17xx.cpp
c8648908ebda9882785d1484d273006bee092ef5
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
opencor/llvmclang
9eb76cb6529b6a3aab2e6cd266ef9751b644f753
63b45a7928f2a8ff823db51648102ea4822b74a6
refs/heads/master
2023-08-26T04:52:56.472505
2022-11-02T04:35:46
2022-11-03T03:55:06
115,094,625
0
1
Apache-2.0
2021-08-12T22:29:21
2017-12-22T08:29:14
LLVM
UTF-8
C++
false
false
3,720
cpp
// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++1z %s -verify -fexceptions -fcxx-exceptions -pedantic-errors namespace dr1715 { // dr1715: 3.9 #if __cplusplus >= 201103L struct B { template<class T> B(T, typename T::Q); }; class S { using Q = int; template<class T> friend B::B(T, typename T::Q); }; struct D : B { using B::B; }; struct E : B { // expected-note 2{{candidate}} template<class T> E(T t, typename T::Q q) : B(t, q) {} // expected-note {{'Q' is a private member}} }; B b(S(), 1); D d(S(), 2); E e(S(), 3); // expected-error {{no match}} #endif } namespace dr1736 { // dr1736: 3.9 #if __cplusplus >= 201103L struct S { template <class T> S(T t) { struct L : S { using S::S; }; typename T::type value; // expected-error {{no member}} L l(value); // expected-note {{instantiation of}} } }; struct Q { typedef int type; } q; S s(q); // expected-note {{instantiation of}} #endif } namespace dr1753 { // dr1753: 11 typedef int T; struct A { typedef int T; }; namespace B { typedef int T; } void f(T n) { n.~T(); n.T::~T(); n.dr1753::~T(); // expected-error {{'dr1753' does not refer to a type name in pseudo-destructor}} n.dr1753::T::~T(); n.A::~T(); // expected-error {{the type of object expression ('dr1753::T' (aka 'int')) does not match the type being destroyed ('dr1753::A') in pseudo-destructor expression}} n.A::T::~T(); n.B::~T(); // expected-error {{'B' does not refer to a type name in pseudo-destructor expression}} n.B::T::~T(); #if __cplusplus >= 201103L n.decltype(n)::~T(); // expected-error {{not a class, namespace, or enumeration}} n.T::~decltype(n)(); // expected-error {{expected a class name after '~'}} n.~decltype(n)(); // OK #endif } } namespace dr1756 { // dr1756: 3.7 #if __cplusplus >= 201103L // Direct-list-initialization of a non-class object int a{0}; struct X { operator int(); } x; int b{x}; #endif } namespace dr1758 { // dr1758: 3.7 #if __cplusplus >= 201103L // Explicit conversion in copy/move list initialization struct X { X(); }; struct Y { explicit operator X(); } y; X x{y}; struct A { A() {} A(const A &) {} }; struct B { operator A() { return A(); } } b; A a{b}; #endif } namespace dr1722 { // dr1722: 9 #if __cplusplus >= 201103L void f() { const auto lambda = [](int x) { return x + 1; }; // Without the DR applied, this static_assert would fail. static_assert( noexcept((int (*)(int))(lambda)), "Lambda-to-function-pointer conversion is expected to be noexcept"); } #endif } // namespace dr1722 namespace dr1778 { // dr1778: 9 // Superseded by P1286R2. #if __cplusplus >= 201103L struct A { A() noexcept(true) = default; }; struct B { B() noexcept(false) = default; }; static_assert(noexcept(A()), ""); static_assert(!noexcept(B()), ""); struct C { A a; C() noexcept(false) = default; }; struct D { B b; D() noexcept(true) = default; }; static_assert(!noexcept(C()), ""); static_assert(noexcept(D()), ""); #endif } namespace dr1762 { // dr1762: 14 #if __cplusplus >= 201103L float operator ""_E(const char *); // expected-error@+2 {{invalid suffix on literal; C++11 requires a space between literal and identifier}} // expected-warning@+1 {{user-defined literal suffixes not starting with '_' are reserved; no literal will invoke this operator}} float operator ""E(const char *); #endif }
[ "agarny@hellix.com" ]
agarny@hellix.com
185f0ea6883490059c56bf02d212e1be05ad187d
07c856e147c6b3f0fa607ecb632a573c02165f4f
/Ch08_Algorithm/ex32_next_permutation.cpp
ccfd00a371adeafd5a210c7435965b448b6c9ca8
[]
no_license
choisb/Study-Cpp-STL
46359db3783767b1ef6099761f67164ab637e579
e5b12b6da744f37713983ef6f61d4f0e10a4eb13
refs/heads/master
2023-06-25T04:13:40.960447
2021-07-19T01:38:59
2021-07-19T01:38:59
329,786,891
0
0
null
null
null
null
UHC
C++
false
false
1,767
cpp
// next_permutation() 알고리즘 예제 // 원소의 순서를 순열처럼 변경할 때 next_permutation()과 prev_permutation()알고리즘을 사용 // next_permutation(b,e)는 구간 [b,e)의 순차열을 다음 순열의 순차열이 되게 한다. // 마지막 순열이라면 false를 반환하며, 아니면 true를 반환한다. // 이전 순열의 순차열이 되도록 하기 위해서는 prev_premutation(b,e)를 사용한다. // 기본적으로 순열의 기준은 사전순이며, 사용자가 조건자를 사용하여 기준을 만들 수도 있다. #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> vec1; vec1.push_back(10); vec1.push_back(20); vec1.push_back(30); cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; while (next_permutation(vec1.begin(), vec1.end())) { cout << "next> "; cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; } cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; prev_permutation(vec1.begin(), vec1.end()); cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; while (prev_permutation(vec1.begin(), vec1.end())) { cout << "prev> "; cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; } cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; return 0; } // [출력 결과] // vec1: 10 20 30 // next > vec1: 10 30 20 // next > vec1: 20 10 30 // next > vec1: 20 30 10 // next > vec1: 30 10 20 // next > vec1: 30 20 10 // vec1 : 10 20 30 // vec1 : 30 20 10 // prev > vec1: 30 10 20 // prev > vec1: 20 30 10 // prev > vec1: 20 10 30 // prev > vec1: 10 30 20 // prev > vec1: 10 20 30 // vec1 : 30 20 10
[ "s004402@gmail.com" ]
s004402@gmail.com
f8474078f305094f8bc3346045fe8a8b1fd9dbdb
9d374d182bfb7990ccc6fdffb05f824abc08300d
/DFS/removeLeavesBinaryTree.cpp
c6c7ddb2e7c7a332b117868aa56f3a9a525d1b8f
[ "MIT" ]
permissive
jkerkela/best-algorithm-collection
cf96e7d790fa5ce82c4411b7ea60940ee5adbaef
6b22536a9f8ebdf3ae134031d41becf30066a5ef
refs/heads/master
2023-08-29T18:30:28.692332
2021-11-14T10:23:56
2021-11-14T10:23:56
246,857,441
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void deleteLeavesFromTreeRecursivelyPostOrder(TreeNode* parentNode, TreeNode* node, bool isLeftLeave, int target) { if(node == NULL) return; deleteLeavesFromTreeRecursivelyPostOrder(node, node->left, true, target); deleteLeavesFromTreeRecursivelyPostOrder(node, node->right, false, target); if (node->val == target && node->left == NULL && node->right == NULL && parentNode != node) { isLeftLeave ? parentNode->left = NULL : parentNode->right = NULL; delete (node); } } bool isRootNodeRemovable(TreeNode* root, int target) { return (!root->left && !root->right && root->val == target); } TreeNode* removeLeafNodes(TreeNode* root, int target) { deleteLeavesFromTreeRecursivelyPostOrder(root, root, false, target); if(isRootNodeRemovable(root, target)){ return NULL; } return root; } };
[ "jonikerkela@hotmail.com" ]
jonikerkela@hotmail.com
31c1981515ef889205eaf9e2eb831bdbc19b9aba
72527c36295e67ff9092a03a101ade79fa23f532
/non-linear-ds/AVLdeletion.cpp
c1eaa1dc57dadf93d57a2d07615f2dc71b2b0ddd
[]
no_license
Divij-berry14/data-structures-and-algorithms
66e5e6d1e3c559e872ac4c8b2db06483288b58f7
4b37d400dade439f15db662685acbea46cb77305
refs/heads/master
2020-06-19T05:49:46.418126
2019-06-19T01:18:45
2019-06-19T01:18:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,622
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: Priyanka * * Created on June 10, 2019, 8:14 PM */ // C++ program to insert a node in AVL tree #include<iostream> using namespace std; // An AVL tree node class Node { public: int key; Node *left; Node *right; int height; }; int height(Node *root) { if (root == NULL) return 0; return root->height; } int max(int a, int b) { return (a > b) ? a : b; } Node* getNewNode(int x) { Node* newNode = new Node(); newNode->key = x; newNode->height = 1; newNode->left = NULL; newNode->right = NULL; return newNode; } int getBalance(Node *root) { if (root == NULL) return 0; return (height(root->left) - height(root->right)); } Node* rightRotate(Node *y) { Node *x = y->left; Node *t = x->right; //Perform rotation x->right = y; y->left = t; //Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; return x; } Node* leftRotate(Node *x) { Node *y = x->right; Node *t = y->left; //ROtate y->left = x; x->right = t; //Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; return y; } Node* insert(Node* head, int a) { if (head == NULL) return (getNewNode(a)); else if (a < head->key) head->left = insert(head->left, a); else if (a > head->key) head->right = insert(head->right, a); //equal values not allowed in BST else return head; //2. Updating the height of the ancestor head->height = max((height(head->left)), (height(head->right))) + 1; //3. Get the balance factor int balance = getBalance(head); //4. Check for any unbalances //Left left case if (balance > 1 && a < head->left->key) { //Right rotate; return rightRotate(head); } //right right case else if (balance<-1 && a > head->right->key) { //Left rotate return leftRotate(head); } //left right case else if (balance > 1 && a > head->left->key) { //Left right rotate head->left = leftRotate(head->left); return rightRotate(head); } //right left case else if (balance <-1 && a < head->right->key) { //Right left rotate head->right = rightRotate(head->right); return leftRotate(head); } //Return the unchanged node return head; } int findMin(Node *root) { Node *temp=root; while(temp->left!=NULL) { temp=temp->left; } return temp->key; } Node* deleteNode(Node *root,int x) { // STep 1. Insert normally as in BST if(root==NULL) return NULL; else if(root->key < x) { root->right = deleteNode(root->right,x); } else if(root->key >x) { root->left = deleteNode(root->left,x); } else { if(root->left==NULL && root->right == NULL) { delete root; root=NULL; } else if(root->left==NULL) { Node *temp=root; root=root->right; delete temp; } else if(root->right==NULL) { Node *temp=root; root=root->left; delete temp; } else{ int min=findMin(root->right); root->key=min; root->right=deleteNode(root->right,min); } } // If the tree had only one node // then return if (root == NULL) return root; root->height = max((height(root->left)), (height(root->right))) + 1; //3. Get the balance factor int balance = getBalance(root); //4. Check for any unbalances //Left left case // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } void preOrder(Node *root) { if (root != NULL) { cout << root->key << " "; preOrder(root->left); preOrder(root->right); } } int main() { Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); /* The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50 */ cout << "preorder traversal of the " "constructed AVL tree is \n"; preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \ 0 9 / / \ -1 5 11 / \ 2 6 */ cout << "\nPreorder traversal after" << " deletion of 10 \n"; preOrder(root); return 0; }
[ "500060668@stu.upes.ac.in" ]
500060668@stu.upes.ac.in
f7d4b1cd1f2f50808caa626693e2ff3a898fbbee
9d579a0ddba661ff9e3e29ec11fde5360bc433f1
/Juego Dados/Jugador.h
c0237ffb6302f04a792641f59d7c577c4c787938
[]
no_license
Agusdel/Programacion2
0eba3e3213b6fb28e1f9239af3ce16c01565bbfd
d1393fb8fc61cf23d4baa69a62f72b568a863f67
refs/heads/master
2021-01-17T18:17:10.621465
2016-11-21T04:04:32
2016-11-21T04:04:32
69,419,363
0
0
null
null
null
null
UTF-8
C++
false
false
443
h
#ifndef JUGADOR_H_INCLUDED #define JUGADOR_H_INCLUDED #include "Dado.h" #include "TablaDeResultados.h" class Jugador{ private: Dado* dadoAzul; Dado* dadoVerde; Dado* dadoRojo; public: Jugador(int cantCarasAzul = 6, int cantCarasVerde = 8, int cantCarasRojo = 12); ~Jugador(); TablaDeResultados LanzarDados(); int getCarasAzul(); int getCarasVerde(); int getCarasRojo(); }; #endif // JUGADOR_H_INCLUDED
[ "agusdel_94@hotmail.com" ]
agusdel_94@hotmail.com
1c5e802f2a2a1fa4c8b63a9d8d3684d9f709158f
429c7c9911d1d474085610a4a9623c116ab0b50e
/NeuArch/Thread.cpp
6fc86a314980d6375fcf8884935f748ea8930a7a
[]
no_license
evlad/nnacs
932f575056da33e8d8b8a3b3f98b60b9713a575f
fea3f054b695c97b08b2e2584f2b56bc45b17e0b
refs/heads/master
2023-04-27T00:38:55.261142
2019-10-06T16:20:55
2019-10-06T16:20:55
13,727,160
2
3
null
null
null
null
UTF-8
C++
false
false
257
cpp
/* Thread.cpp */ static char rcsid[] = "$Id$"; //--------------------------------------------------------------------------- #include "Thread.h" //--------------------------------------------------------------------------- #pragma package(smart_init)
[ "ev1ad@yandex.ru" ]
ev1ad@yandex.ru
b25fef9a4b12d686e1d8bc18ebbd090130d557c9
858d413add89d4afae69e13e2deb4572f8e5f34e
/test/arbitrary_fanin.cpp
8d2e426b31f269d37c9d80ce4afa8dab444ac7b3
[ "MIT" ]
permissive
msoeken/percy
2958200e6af4bd857fd5b55e32cc73841c6e686a
42cd65b490849d5cdc4b8142db03e78cc67f1be6
refs/heads/master
2020-03-19T18:11:35.569292
2018-06-08T13:55:00
2018-06-08T13:55:00
124,677,384
0
0
MIT
2018-04-25T13:04:40
2018-03-10T17:02:07
C++
UTF-8
C++
false
false
1,443
cpp
#include <cstdio> #include <percy/percy.hpp> using namespace percy; /******************************************************************************* Tests support for exact synthesis of arbitrary fanin chains. Specifically, tests if the functions that are used to map selection variable indices to fanin assignments work correctly. *******************************************************************************/ int main(void) { std::array<int, 2> init_test; fanin_init(init_test, 1); assert(init_test[0] == 0); assert(init_test[1] == 1); std::array<int, 2> fanin2 = { 0, 1 }; assert(fanin_inc(fanin2, 1) == false); assert(fanin_inc(fanin2, 2) == true); assert(fanin2[0] == 0); assert(fanin2[1] == 2); assert(fanin_inc(fanin2, 2) == true); assert(fanin2[0] == 1); assert(fanin2[1] == 2); assert(fanin_inc(fanin2, 2) == false); std::array<int, 3> fanin3 = { 0, 1, 2 }; assert(fanin_inc(fanin3, 2) == false); assert(fanin_inc(fanin3, 3) == true); assert(fanin3[0] == 0); assert(fanin3[1] == 1); assert(fanin3[2] == 3); assert(fanin_inc(fanin3, 3) == true); assert(fanin3[0] == 0); assert(fanin3[1] == 2); assert(fanin3[2] == 3); assert(fanin_inc(fanin3, 3) == true); assert(fanin3[0] == 1); assert(fanin3[1] == 2); assert(fanin3[2] == 3); assert(fanin_inc(fanin3, 3) == false); return 0; }
[ "winston.haaswijk@gmail.com" ]
winston.haaswijk@gmail.com
8a51ef8e58067fbdb6416a63746c2dc47dafeac9
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-tizen/generated/src/ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties.h
d1104d828590097092a34bd708c21f5d9cd79c54
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
1,551
h
/* * ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties.h * * */ #ifndef _ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties_H_ #define _ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties_H_ #include <string> #include "ConfigNodePropertyBoolean.h" #include "Object.h" /** \defgroup Models Data Structures for API * Classes containing all the Data Structures needed for calling/returned by API endpoints * */ namespace Tizen { namespace ArtikCloud { /*! \brief * * \ingroup Models * */ class ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties : public Object { public: /*! \brief Constructor. */ ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties(); ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties(char* str); /*! \brief Destructor. */ virtual ~ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties(); /*! \brief Retrieve a string JSON representation of this class. */ char* toJson(); /*! \brief Fills in members of this class from JSON string representing it. */ void fromJson(char* jsonStr); /*! \brief Get */ ConfigNodePropertyBoolean getIsMemberCheck(); /*! \brief Set */ void setIsMemberCheck(ConfigNodePropertyBoolean isMemberCheck); private: ConfigNodePropertyBoolean isMemberCheck; void __init(); void __cleanup(); }; } } #endif /* _ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties_H_ */
[ "cliffano@gmail.com" ]
cliffano@gmail.com
bf9e1719a140ccc62272e781f28b92a9e597bbba
93f635bbef282f8dcfbbfa682aec2c206e68f7b7
/beginner_level_and_uva/memset 1.cpp
5ba1226cf3208c18cf8d87af1d93c1608ecb1578
[]
no_license
Alimurrazi/Programming
6ba828ea15e640f70311fab33cce1a6e9190db45
cd4354616596d6c7865f4ccd835b1c0712f41c45
refs/heads/master
2023-08-01T14:23:31.342302
2021-09-14T03:53:50
2021-09-14T03:53:50
107,748,091
0
0
null
null
null
null
UTF-8
C++
false
false
160
cpp
#include<stdio.h> #include<string.h> int main() { int ara[100]; int i,j,k,l; memset(ara,('1'-'0'),sizeof(ara)); for(i=0;i<=50;i++) printf("%d\n",ara[i]); }
[ "alimurrazi570@gmail.com" ]
alimurrazi570@gmail.com
fd8ba1248793b71c9bef40a3ce4c149241f91039
e6dfe602a69230fb4f2548afefd9faf85848d1d1
/0027.cpp
2122c4d645de333d3d972d14bd430d786b604465
[]
no_license
chenjiahui0131/LeetCode_cpp
0d6cb758c638bd2dd8b592a932529e39841e08f7
aca79506326f0e1c2088f90437e7a17367e62879
refs/heads/master
2021-01-04T19:27:17.957312
2020-04-02T14:16:48
2020-04-02T14:16:48
240,728,567
0
0
null
null
null
null
UTF-8
C++
false
false
543
cpp
#include<iostream> #include<vector> using namespace std; class Solution { public: int removeElement(vector<int>& nums, int val) { int idx = -1; for (int i = 0; i < nums.size(); i++) { if (nums[i] != val) { idx++; nums[idx] = nums[i]; } } return idx + 1; } }; int main() { vector<int> nums = {0,1,2,2,3,0,4,2}; Solution s; int length = s.removeElement(nums, 2); for (int i = 0; i < length; i++) cout << nums[i] << endl; }
[ "coffee@email.com" ]
coffee@email.com
b030a566adfc03502cba6b087bbd5cd20f249c05
a9fc0a713d0817160dc18a3fae1fbe8b804f7044
/rc-switch-jni-wrapper/src/com_opitz_jni_NativeRCSwitchAdapter.cpp
79fea898553b15a97256e96c31805509721bc07a
[]
no_license
magicgis/Pi-jAutomation433
ced27758fce529f9b9e187cdfbd98e99844d5dd4
7ceec94dd7b1c89376db70fccbbe8d99e2b3964a
refs/heads/master
2020-08-29T04:06:15.378274
2014-09-16T11:43:01
2014-09-16T11:43:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,015
cpp
#include "com_opitz_jni_NativeRCSwitchAdapter.h" #include "RCSwitch.h" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <wiringPi.h> using namespace std; RCSwitch mySwitch = RCSwitch(); JNIEXPORT void JNICALL Java_com_opitz_jni_NativeRCSwitchAdapter_switchOn(JNIEnv * env, jobject obj, jstring jsGroup, jstring jsChannel ){ if (wiringPiSetup () == -1) { printf("noWiringPiSetup"); } const char *csGroup = env->GetStringUTFChars(jsGroup, 0); const char *csChannel = env->GetStringUTFChars(jsChannel, 0); char sGroup[6]; char sChannel[6]; for (int i = 0; i<5; i++) { sGroup[i] = csGroup[i]; sChannel[i] = csChannel[i]; } sGroup[5] = '\0'; sChannel[5] = '\0'; cout<<"ON with"<<sGroup<<"and "<< sChannel <<endl; piHiPri(20); //for testing purposes set to the ELRO Power Plugs mySwitch.setPulseLength(300); mySwitch.enableTransmit(0); mySwitch.setRepeatTransmit(3); mySwitch.switchOn(sGroup, sChannel); } JNIEXPORT void JNICALL Java_com_opitz_jni_NativeRCSwitchAdapter_switchOff(JNIEnv * env, jobject obj, jstring jsGroup, jstring jsChannel ){ if (wiringPiSetup () == -1) { printf("noWiringPiSetup"); } const char *csGroup = env->GetStringUTFChars(jsGroup, 0); const char *csChannel = env->GetStringUTFChars(jsChannel, 0); char sGroup[6]; char sChannel[6]; for (int i = 0; i<5; i++) { sGroup[i] = csGroup[i]; sChannel[i] = csChannel[i]; } sGroup[5] = '\0'; sChannel[5] = '\0'; cout<<"OFF with "<<sGroup<<" and "<< sChannel <<endl; piHiPri(20); //for testing purposes set to the ELRO Power Plugs mySwitch.setPulseLength(300); mySwitch.enableTransmit(0); mySwitch.setRepeatTransmit(3); mySwitch.switchOff(sGroup, sChannel); } JNIEXPORT void JNICALL Java_NativeRCSwitchAdapter_setPulseLength(JNIEnv * env, jobject obj , jint pulseLength){ //int = env->GetStringUTFChars(jsGroup, 0); }
[ "satspeedy@users.noreply.github.com" ]
satspeedy@users.noreply.github.com
953545cb89deb409ff63aedc8e976b058438bfc1
4fa1e0711c3023a94035b58f6a66c9acd4a7f424
/Microsoft/SAMPLES/CPPtoCOM/DB_Vtbl/Interface/Dbsrv.h
b1d29aad31a79d42cf391a6c279a1d59666ac97e
[ "MIT" ]
permissive
tig/Tigger
4d1f5a2088468c75a7c21b103705445a93ec571c
8e06d117a5b520c5fc9e37a710bf17aa51a9958c
refs/heads/master
2023-06-09T01:59:43.167371
2020-08-19T15:21:53
2020-08-19T15:21:53
3,426,737
1
2
null
2023-05-31T18:56:36
2012-02-13T03:05:18
C
UTF-8
C++
false
false
724
h
#ifndef _DBSERVER_INCLUDE #define _DBSERVER_INCLUDE typedef long HRESULT; class IDB { // Interfaces public: // Interface for data access virtual HRESULT Read(short nTable, short nRow, LPTSTR lpszData) =0; virtual HRESULT Write(short nTable, short nRow, LPCTSTR lpszData) =0; // Interface for database management virtual HRESULT Create(short &nTable, LPCTSTR lpszName) =0; virtual HRESULT Delete(short nTable) =0; // Interface for database information virtual HRESULT GetNumTables(short &nNumTables) =0; virtual HRESULT GetTableName(short nTable, LPTSTR lpszName) =0; virtual HRESULT GetNumRows(short nTable, short &nRows) =0; }; HRESULT CreateDB(IDB** ppObj); #endif
[ "charlie@kindel.com" ]
charlie@kindel.com
9c855778a2888a3d40da21c56810803fa7c43bf4
72d8bd35b3be639a4be081de1786d031c9e9a1a9
/PXFXMQery.cpp
8f94641b40f9c54948f81faeaa786ac9950d51c6
[]
no_license
bravesoftdz/IC-Info
69bb6d30c130dc29da2b51262b542f95079fcf53
e07e745a69ea2181d2fa05ad5fc2cc7b07711827
refs/heads/master
2020-03-08T06:40:20.549679
2014-11-20T11:51:14
2014-11-20T11:51:14
null
0
0
null
null
null
null
GB18030
C++
false
false
8,013
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "PXFXMQery.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "cxButtons" #pragma link "cxCalendar" #pragma link "cxContainer" #pragma link "cxControls" #pragma link "cxDropDownEdit" #pragma link "cxEdit" #pragma link "cxGraphics" #pragma link "cxGroupBox" #pragma link "cxLabel" #pragma link "cxLookAndFeelPainters" #pragma link "cxLookAndFeels" #pragma link "cxMaskEdit" #pragma link "cxTextEdit" #pragma link "dxSkinBlack" #pragma link "dxSkinBlue" #pragma link "dxSkinCaramel" #pragma link "dxSkinCoffee" #pragma link "dxSkinDarkRoom" #pragma link "dxSkinDarkSide" #pragma link "dxSkinFoggy" #pragma link "dxSkinGlassOceans" #pragma link "dxSkiniMaginary" #pragma link "dxSkinLilian" #pragma link "dxSkinLiquidSky" #pragma link "dxSkinLondonLiquidSky" #pragma link "dxSkinMcSkin" #pragma link "dxSkinMoneyTwins" #pragma link "dxSkinOffice2007Black" #pragma link "dxSkinOffice2007Blue" #pragma link "dxSkinOffice2007Green" #pragma link "dxSkinOffice2007Pink" #pragma link "dxSkinOffice2007Silver" #pragma link "dxSkinPumpkin" #pragma link "dxSkinsCore" #pragma link "dxSkinsDefaultPainters" #pragma link "dxSkinSeven" #pragma link "dxSkinSharp" #pragma link "dxSkinSilver" #pragma link "dxSkinSpringTime" #pragma link "dxSkinStardust" #pragma link "dxSkinSummer2008" #pragma link "dxSkinValentine" #pragma link "dxSkinXmas2008Blue" #pragma resource "*.dfm" TPXFXMForm *PXFXMForm; //--------------------------------------------------------------------------- __fastcall TPXFXMForm::TPXFXMForm(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TPXFXMForm::ReadCardInfoBTNClick(TObject *Sender) { WORD status; int tmpbalance; int tmpkh,tmpsycs; double tmpintye; double tmpye; unsigned char keymode,secnum,Delayms,mode; unsigned char key[6]; unsigned char dwmm[6]; unsigned char daytime[4]; unsigned char kh[4]; unsigned char balance[4]; unsigned char cardtype[1]; unsigned char czmm[3]; unsigned char synum[3]; // unsigned char readcomno[5] = ""; Delayms = 0x00; keymode = CARDPasswordEdition;//0x03; secnum = UsingSecNUM;//0x01; key[0] = CARDPassword[0]; key[1] = CARDPassword[1]; key[2] = CARDPassword[2]; key[3] = CARDPassword[3]; key[4] = CARDPassword[4]; key[5] = CARDPassword[5]; if(LoadHModule) { beepofreaddll(readcomno, '10'); if(readcardinfo) { status = readcardinfo(readcomno,keymode,secnum,key,kh,balance, dwmm,synum,daytime,cardtype,czmm,Delayms); if(status > 99) { ShowMessage("通讯错误!"); } else if (1 == status) { ShowMessage("请把卡片放好!"); } else if (2 == status) { ShowMessage("卡号大于192000或等于0!"); } else if (4 == status) { ShowMessage("卡片密码不对!"); } else if (5 == status) { ShowMessage("读写卡不稳定!"); } else if (6 == status) { ShowMessage("卡结构不对!"); } else if (10 == status) { ShowMessage("卡结构不对!"); } else if (0 != status) { ShowMessage("该卡未发行或已退卡!"); } else { String tmpstr; tmpkh = (int)kh[1]*256*256+(int)kh[2]*256+(int)kh[3]; tmpsycs = (int)synum[0]*256+(int)synum[1]; tmpintye = (double)balance[1]*256*256+(double)balance[2]*256+(double)balance[3]; tmpye = tmpintye/100; XFADOQ->Close(); XFADOQ->SQL->Clear(); tmpstr = "select * from KZT where kh="; tmpstr += tmpkh; XFADOQ->SQL->Add(tmpstr); XFADOQ->Open(); if(!XFADOQ->IsEmpty()) { if(0 != XFADOQ->FieldByName("GS")->AsInteger) { ShowMessage("此卡已挂失,请没收此卡!"); XFADOQ->Close(); } } else { ShowMessage("此卡不是本系统发出的卡!"); XFADOQ->Close(); } XFADOQ->Close(); XFADOQ->SQL->Clear(); tmpstr = "select * from CARD where kh="; tmpstr += tmpkh; XFADOQ->SQL->Add(tmpstr); XFADOQ->Open(); if(!XFADOQ->IsEmpty()) { XFXMTextEdit->Text = ""; XFKHTextEdit->Text = tmpkh; } else { ShowMessage("此卡不是本系统发出的卡!"); XFADOQ->Close(); } } } else { ShowMessage("读卡函数加载失败!"); } } else ShowMessage("加载读写卡动态链接库失败!"); } //--------------------------------------------------------------------------- void __fastcall TPXFXMForm::QueryBTNClick(TObject *Sender) { if(XFKHTextEdit->Text.IsEmpty()&&XFXMTextEdit->Text.IsEmpty()) { ShowMessage("请至少填写姓名与卡号中的一项!"); return; } if(!XFBeginDateEdit->Text.IsEmpty()&&!XFEndDateEdit->Text.IsEmpty()) { String sumsqlstr = "select SUM(case when SFLX='X' then MXBAK.SFJE else 0 end) as XFZE,SUM(case when SFLX='X' then 1 else 0 end) as XFZCS,SUM(case when (SFLX='I' or SFLX='A') then MXBAK.SFJE when SFLX='K' then MXBAK.SF_YE else 0 end) as CZZE,SUM(case when (SFLX='I' or SFLX='A') then 1 when SFLX='K' then 1 else 0 end) as CZZCS,SUM(case when (SFLX='D' or SFLX='Q' or SFLX='R') then MXBAK.SFJE else 0 end) as QKZE,SUM(case when (SFLX='D' or SFLX='Q' or SFLX='R') then 1 else 0 end) as QKZCS from MXBAK join CARD_F on CARD_F.BH=MXBAK.BH where "; String mxsqlstr = "select MXBAK.KH,MXBAK.BH,CARD_F.XM,CARD_F.BM,CARD_F.ZW,MXBAK.SF_YE,MXBAK.SFJE,MXBAK.SYCS,MXBAK.JYNO,MXBAK.SFLX,MXBAK.SFRQ from MXBAK join CARD_F on CARD_F.BH=MXBAK.BH where SFLX in ('X','I','A','K','D','Q', 'R') and "; String addsqlstr = ""; if(!XFKHTextEdit->Text.IsEmpty()) { addsqlstr = "MXBAK.KH='"; addsqlstr += XFKHTextEdit->Text; addsqlstr += "' and "; } if(!XFXMTextEdit->Text.IsEmpty()) { if(addsqlstr.IsEmpty()) { addsqlstr = "CARD_F.XM='"; addsqlstr += XFXMTextEdit->Text; addsqlstr += "' and "; } else { addsqlstr += "CARD_F.XM='"; addsqlstr += XFXMTextEdit->Text; addsqlstr += "' and "; } } addsqlstr += "SFRQ>'"; addsqlstr += XFBeginDateEdit->Text; addsqlstr += " 00:00:00' and SFRQ<'"; addsqlstr += XFEndDateEdit->Text; addsqlstr += " 23:59:59'"; sumsqlstr += addsqlstr; mxsqlstr += addsqlstr; XFADOQ->Close(); XFADOQ->SQL->Clear(); XFADOQ->SQL->Add(mxsqlstr); XFADOQ->Open(); if(!XFADOQ->IsEmpty()) { XFADOQ->Close(); XFADOQ->SQL->Clear(); XFADOQ->SQL->Add(sumsqlstr); XFADOQ->Open(); PXFMXShowFrm->AllXFTextEdit->Text = XFADOQ->FieldByName("XFZE")->AsString; PXFMXShowFrm->AllCSTextEdit->Text = XFADOQ->FieldByName("XFZCS")->AsString; PXFMXShowFrm->cxTextEdit2->Text = XFADOQ->FieldByName("CZZE")->AsString; PXFMXShowFrm->cxTextEdit1->Text = XFADOQ->FieldByName("CZZCS")->AsString; PXFMXShowFrm->cxTextEdit4->Text = XFADOQ->FieldByName("QKZE")->AsString; PXFMXShowFrm->cxTextEdit3->Text = XFADOQ->FieldByName("QKZCS")->AsString; XFADOQ->Close(); PXFMXShowFrm->BeginDateTimeStr = XFBeginDateEdit->Text + " 00:00:00"; PXFMXShowFrm->EndDateTimeStr = XFEndDateEdit->Text + " 23:59:59"; PXFMXShowFrm->KHStr = XFKHTextEdit->Text; PXFMXShowFrm->XMStr = XFXMTextEdit->Text; PXFMXShowFrm->CZYStr = OperatorName; PXFMXShowFrm->XFMXExportProgressBar->Position = 0; PXFMXShowFrm->allsqlstr = mxsqlstr; PXFMXShowFrm->XFMXADOQuery->Close(); PXFMXShowFrm->XFMXADOQuery->SQL->Clear(); PXFMXShowFrm->XFMXADOQuery->SQL->Add(mxsqlstr); PXFMXShowFrm->ShowModal(); } else ShowMessage("符合该查询条件的记录条数为0!"); } else { ShowMessage("必须填写查询起止日期!"); } } //--------------------------------------------------------------------------- void __fastcall TPXFXMForm::FormShow(TObject *Sender) { XFBeginDateEdit->Date = Date(); XFEndDateEdit->Date = Date(); } //---------------------------------------------------------------------------
[ "47157860@qq.com" ]
47157860@qq.com
45e2a325dab8ec5d056af37af42b6a058938a849
02b361a4c1267e8f9e7e2008bf0d82fb9cef8cd2
/src/txdb.cpp
b6379fbb2f9c1a7d68026403ef33287d4621ae40
[ "MIT" ]
permissive
team-exor/exor
abaf938ee24cc66c6b86ee76a93aa501dbbd32ac
da9a2145d834e45db2fd8637ec984e249bfbd5d9
refs/heads/master
2020-05-28T05:50:04.600841
2019-06-24T20:26:46
2019-06-24T20:26:46
188,899,679
1
3
null
null
null
null
UTF-8
C++
false
false
14,719
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "main.h" #include "pow.h" #include "uint256.h" #include "accumulators.h" #include <stdint.h> #include <boost/thread.hpp> using namespace std; using namespace libzerocoin; void static BatchWriteCoins(CLevelDBBatch& batch, const uint256& hash, const CCoins& coins) { if (coins.IsPruned()) batch.Erase(make_pair('c', hash)); else batch.Write(make_pair('c', hash), coins); } void static BatchWriteHashBestChain(CLevelDBBatch& batch, const uint256& hash) { batch.Write('B', hash); } CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) { } bool CCoinsViewDB::GetCoins(const uint256& txid, CCoins& coins) const { return db.Read(make_pair('c', txid), coins); } bool CCoinsViewDB::HaveCoins(const uint256& txid) const { return db.Exists(make_pair('c', txid)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!db.Read('B', hashBestChain)) return uint256(0); return hashBestChain; } bool CCoinsViewDB::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) { CLevelDBBatch batch; size_t count = 0; size_t changed = 0; for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { BatchWriteCoins(batch, it->first, it->second.coins); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } if (hashBlock != uint256(0)) BatchWriteHashBestChain(batch, hashBlock); LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex) { return Write(make_pair('b', blockindex.GetBlockHash()), blockindex); } bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo& info) { return Write(make_pair('f', nFile), info); } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo& info) { return Read(make_pair('f', nFile), info); } bool CBlockTreeDB::WriteLastBlockFile(int nFile) { return Write('l', nFile); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write('R', '1'); else return Erase('R'); } bool CBlockTreeDB::ReadReindexing(bool& fReindexing) { fReindexing = Exists('R'); return true; } bool CBlockTreeDB::ReadLastBlockFile(int& nFile) { return Read('l', nFile); } bool CCoinsViewDB::GetStats(CCoinsStats& stats) const { /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator()); pcursor->SeekToFirst(); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = GetBestBlock(); ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'c') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); CCoins coins; ssValue >> coins; uint256 txhash; ssKey >> txhash; ss << txhash; ss << VARINT(coins.nVersion); ss << (coins.fCoinBase ? 'c' : 'n'); ss << VARINT(coins.nHeight); stats.nTransactions++; for (unsigned int i = 0; i < coins.vout.size(); i++) { const CTxOut& out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i + 1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + slValue.size(); ss << VARINT(0); } pcursor->Next(); } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight; stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } bool CBlockTreeDB::ReadTxIndex(const uint256& txid, CDiskTxPos& pos) { return Read(make_pair('t', txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >& vect) { CLevelDBBatch batch; for (std::vector<std::pair<uint256, CDiskTxPos> >::const_iterator it = vect.begin(); it != vect.end(); it++) batch.Write(make_pair('t', it->first), it->second); return WriteBatch(batch); } bool CBlockTreeDB::WriteFlag(const std::string& name, bool fValue) { return Write(std::make_pair('F', name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string& name, bool& fValue) { char ch; if (!Read(std::make_pair('F', name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::WriteInt(const std::string& name, int nValue) { return Write(std::make_pair('I', name), nValue); } bool CBlockTreeDB::ReadInt(const std::string& name, int& nValue) { return Read(std::make_pair('I', name), nValue); } bool CBlockTreeDB::LoadBlockIndexGuts() { boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator()); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); ssKeySet << make_pair('b', uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex uint256 nPreviousCheckpoint; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'b') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); CDiskBlockIndex diskindex; ssValue >> diskindex; // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev); pindexNew->pnext = InsertBlockIndex(diskindex.hashNext); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; //zerocoin pindexNew->nAccumulatorCheckpoint = diskindex.nAccumulatorCheckpoint; pindexNew->mapZerocoinSupply = diskindex.mapZerocoinSupply; pindexNew->vMintDenominationsInBlock = diskindex.vMintDenominationsInBlock; //Proof Of Stake pindexNew->nMint = diskindex.nMint; pindexNew->nMoneySupply = diskindex.nMoneySupply; pindexNew->nFlags = diskindex.nFlags; pindexNew->nStakeModifier = diskindex.nStakeModifier; pindexNew->prevoutStake = diskindex.prevoutStake; pindexNew->nStakeTime = diskindex.nStakeTime; pindexNew->hashProofOfStake = diskindex.hashProofOfStake; if (pindexNew->nHeight <= Params().LAST_POW_BLOCK()) { if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits)) return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString()); } // ppcoin: build setStakeSeen if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); //populate accumulator checksum map in memory if(pindexNew->nAccumulatorCheckpoint != 0 && pindexNew->nAccumulatorCheckpoint != nPreviousCheckpoint) { //Don't load any checkpoints that exist before v2 zexor. The accumulator is invalid for v1 and not used. if (pindexNew->nHeight >= Params().Zerocoin_Block_V2_Start()) LoadAccumulatorValuesFromDB(pindexNew->nAccumulatorCheckpoint); nPreviousCheckpoint = pindexNew->nAccumulatorCheckpoint; } pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } return true; } CZerocoinDB::CZerocoinDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "zerocoin", nCacheSize, fMemory, fWipe) { } bool CZerocoinDB::WriteCoinMintBatch(const std::vector<std::pair<libzerocoin::PublicCoin, uint256> >& mintInfo) { CLevelDBBatch batch; size_t count = 0; for (std::vector<std::pair<libzerocoin::PublicCoin, uint256> >::const_iterator it=mintInfo.begin(); it != mintInfo.end(); it++) { PublicCoin pubCoin = it->first; uint256 hash = GetPubCoinHash(pubCoin.getValue()); batch.Write(make_pair('m', hash), it->second); ++count; } LogPrint("zero", "Writing %u coin mints to db.\n", (unsigned int)count); return WriteBatch(batch, true); } bool CZerocoinDB::ReadCoinMint(const CBigNum& bnPubcoin, uint256& hashTx) { return ReadCoinMint(GetPubCoinHash(bnPubcoin), hashTx); } bool CZerocoinDB::ReadCoinMint(const uint256& hashPubcoin, uint256& hashTx) { return Read(make_pair('m', hashPubcoin), hashTx); } bool CZerocoinDB::EraseCoinMint(const CBigNum& bnPubcoin) { uint256 hash = GetPubCoinHash(bnPubcoin); return Erase(make_pair('m', hash)); } bool CZerocoinDB::WriteCoinSpendBatch(const std::vector<std::pair<libzerocoin::CoinSpend, uint256> >& spendInfo) { CLevelDBBatch batch; size_t count = 0; for (std::vector<std::pair<libzerocoin::CoinSpend, uint256> >::const_iterator it=spendInfo.begin(); it != spendInfo.end(); it++) { CBigNum bnSerial = it->first.getCoinSerialNumber(); CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); batch.Write(make_pair('s', hash), it->second); ++count; } LogPrint("zero", "Writing %u coin spends to db.\n", (unsigned int)count); return WriteBatch(batch, true); } bool CZerocoinDB::ReadCoinSpend(const CBigNum& bnSerial, uint256& txHash) { CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); return Read(make_pair('s', hash), txHash); } bool CZerocoinDB::ReadCoinSpend(const uint256& hashSerial, uint256 &txHash) { return Read(make_pair('s', hashSerial), txHash); } bool CZerocoinDB::EraseCoinSpend(const CBigNum& bnSerial) { CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); return Erase(make_pair('s', hash)); } bool CZerocoinDB::WipeCoins(std::string strType) { if (strType != "spends" && strType != "mints") return error("%s: did not recognize type %s", __func__, strType); boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator()); char type = (strType == "spends" ? 's' : 'm'); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); ssKeySet << make_pair(type, uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex std::set<uint256> setDelete; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == type) { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); uint256 hash; ssValue >> hash; setDelete.insert(hash); pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } for (auto& hash : setDelete) { if (!Erase(make_pair(type, hash))) LogPrintf("%s: error failed to delete %s\n", __func__, hash.GetHex()); } return true; } bool CZerocoinDB::WriteAccumulatorValue(const uint32_t& nChecksum, const CBigNum& bnValue) { LogPrint("zero","%s : checksum:%d val:%s\n", __func__, nChecksum, bnValue.GetHex()); return Write(make_pair('2', nChecksum), bnValue); } bool CZerocoinDB::ReadAccumulatorValue(const uint32_t& nChecksum, CBigNum& bnValue) { return Read(make_pair('2', nChecksum), bnValue); } bool CZerocoinDB::EraseAccumulatorValue(const uint32_t& nChecksum) { LogPrint("zero", "%s : checksum:%d\n", __func__, nChecksum); return Erase(make_pair('2', nChecksum)); }
[ "joeuhren@protonmail.com" ]
joeuhren@protonmail.com
d7cf5aa00a7af9379a0d212235c08c584227a53a
9d05e9312f35377b46269ce00d5720338743e260
/MashView.h
fe511b4134a617c0e99f36418570d7d97db04e7e
[]
no_license
dbratell/Mash
b18b83f0c9c10366cee29da0f1f9ce1a0eceb9c6
73ddb1405272725ca2b9406cd1e00b7d7f30da51
refs/heads/master
2020-05-09T15:06:49.671860
2000-04-24T20:29:24
2000-04-24T20:29:24
181,221,694
0
0
null
null
null
null
UTF-8
C++
false
false
1,792
h
// MashView.h : interface of the CMashView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MASHVIEW_H__278C1BB6_A133_4BD7_A3CA_34646DB9DB75__INCLUDED_) #define AFX_MASHVIEW_H__278C1BB6_A133_4BD7_A3CA_34646DB9DB75__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMashView : public CView { protected: // create from serialization only CMashView(); DECLARE_DYNCREATE(CMashView) // Attributes public: CMashDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMashView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); //}}AFX_VIRTUAL // Implementation public: virtual ~CMashView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CMashView) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in MashView.cpp inline CMashDoc* CMashView::GetDocument() { return (CMashDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MASHVIEW_H__278C1BB6_A133_4BD7_A3CA_34646DB9DB75__INCLUDED_)
[ "bratell@lysator.liu.se" ]
bratell@lysator.liu.se
05a3fa4e764da6e7c9614bb002a9d5babcb94615
a89bd048287b91f8fe958809b6c958bc45c1aec8
/include/rtl/PerspectiveCamera.h
6358baf3ffd7fb1df1aec107412cb67952e76f5b
[ "MIT" ]
permissive
potato3d/rtrt
8b739300bed61a5336fe3a230e6384f897d74c61
cac9f2f80d94bf60adf0bbd009f5076973ee10c6
refs/heads/main
2023-03-02T11:23:52.096304
2021-02-13T03:36:56
2021-02-13T03:36:56
338,484,429
2
0
null
null
null
null
UTF-8
C++
false
false
1,500
h
#pragma once #ifndef _RTL_PERSPECTIVECAMERA_H_ #define _RTL_PERSPECTIVECAMERA_H_ #include <rts/ICamera.h> #include <rtu/float3.h> #include <rtu/quat.h> #include <rtu/sse.h> namespace rtl { class PerspectiveCamera : public rts::ICamera { public: virtual void init(); virtual void newFrame(); virtual void receiveParameter( int paramId, void* paramValue ); virtual void lookAt( float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ ); virtual void setPerspective( float fovY, float zNear, float zFar ); virtual void setViewport( unsigned int width, unsigned int height ); virtual void getViewport( unsigned int& width, unsigned int& height ); virtual void getRay( rts::RTstate& state, float x, float y ); virtual void getRayPacket( rts::RTstate& state, float* rayXYCoords ); private: // Has changed since the last update? bool _dirty; // Input parameters rtu::float3 _position; rtu::quatf _orientation; float _fovy; float _zNear; float _zFar; unsigned int _screenWidth; unsigned int _screenHeight; // Derived values rtu::float3 _axisX; // camera axes rtu::float3 _axisY; rtu::float3 _axisZ; rtu::float3 _nearOrigin; // near plane origin rtu::float3 _nearU; // near plane U vector rtu::float3 _nearV; // near plane V vector // Pre-computation float _invWidth; float _invHeight; rtu::float3 _baseDir; }; } // namespace rts #endif // _RTL_PERSPECTIVECAMERA_H_
[ "" ]
4c33aa8c2265575cf636f324549baa51f05c6940
e642f1e4cc822114c8a3651cbe51dabb95c85716
/ift-demo/demo/watershed/kernels/dijk.cpp
13f18dd6b7d5748192c3654c3bde9e7ea275fa28
[ "BSD-3-Clause" ]
permissive
gagallo7/OpenCLStudy
e80cd8d0339d1fafaa8860f2d2e6a161418a243e
d054115addb7831725f816eb7f4d54b81f1f14bc
refs/heads/master
2021-01-19T10:59:10.373979
2014-04-01T01:11:19
2014-04-01T01:11:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,572
cpp
#include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <string> #include <string.h> #include <vector> #include <list> #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif #if !defined(CL_CALLBACK) #define CL_CALLBACK #endif #define INF 1 << 30 using namespace std; void log (vector < unsigned int > v, char *argv[]) { FILE* fp; char local[50] = "logs/"; strcat(local, argv[2]); //cout << local << endl; fp = fopen(local,"w"); for (int i=0; i<v.size(); i++) { fprintf(fp, "%d\n", v[i]); } fclose(fp); } bool vazio (vector < unsigned int > M) { for (int i = 0; i < M.size(); i++) { if (M[i] == true) return false; } return true; } class grafo { public: int numV; // Numero de vertices vector < cl_uint > vert; // Vetor de vertices vector < cl_uint > arestas; // Vetor de arestas vector < cl_uint > pesos; // Vetor de pesos void make_graph (FILE *); void make_graph9 (FILE *); void make_graph558 (FILE *, int* ); void printInfo (void); void prepare (vector < cl_uint >&, vector < cl_uint >&, vector < cl_uint >&); }; // Cria grafo no modelo da disciplina de MC558 // Primeira linha tem o numero de vertices seguido do numero total // de arestas do grafo. void grafo::make_graph558 ( FILE* fp, int* raiz ) { char linha[2000]; vector < unsigned int > a_tmp, p_tmp, v_tmp; vector < list < vector < unsigned int > > > la; if (fp==NULL) { cout << "Erro ao abrir arquivo!" << endl; return; } // Primeiro vertice comeca sua lista de adjacencias em 0 //vert.push_back(0); // Cada linha tem a representacao de cada vertice // fgets limita-se a capturar uma linha int i, o, peso; int numA; // Coletando a primeira linha, a qual armazena o numero // de vertices do grafo if (fgets (linha, 2000, fp) != NULL) { sscanf(linha, " %d %d", &numV, &numA); } la.resize(numV+1); //cout << numV << endl; int nLinha = 0; // Coletando as arestas while (fgets (linha, 2000, fp) != NULL) { //int ant = -1; // Capturando o vertice if (nLinha < numA) { // Se o vertice tiver arestas sscanf(linha," %d %d %d", &i, &o, &peso); // Caso de fim de linha, pois nao ha arestas iguais // Logo o destino nao pode ser o mesmo // cout << i << " " << o << " " << peso; // ant = i; vector < unsigned int > novo; novo.push_back(o); novo.push_back(peso); la[i].push_back(novo); } else { sscanf(linha," %d", raiz); break; } nLinha++; /* */ // Apontando para a proxima lista de adjacencias //vert.push_back(arestas.size()); } fclose(fp); list < vector < unsigned int > >::iterator ll; int j = 0; for (int i = 0; i < numV; i++) { vert.push_back(j); for (ll = la[i].begin(); ll != la[i].end(); ll++) { j++; arestas.push_back((*ll)[0]); pesos.push_back((*ll)[1]); } } vert.push_back(j); // Arestas do ultimo vertice } // Cria grafo baseado no modelo do DIMACS9 // DIMACS usa o seguinte modelo: // Cada linha tem o vertice de origem e saida e também o peso de // cada aresta // void grafo::make_graph9 ( FILE* fp ) { char linha[2000]; vector < unsigned int > a_tmp, p_tmp, v_tmp; vector < list < vector < unsigned int > > > la; if (fp==NULL) { cout << "Erro ao abrir arquivo!" << endl; return; } // Primeiro vertice comeca sua lista de adjacencias em 0 //vert.push_back(0); // Cada linha tem a representacao de cada vertice // fgets limita-se a capturar uma linha int i, o, peso; // Coletando a primeira linha, a qual armazena o numero // de vertices do grafo if (fgets (linha, 2000, fp) != NULL) { sscanf(linha, " %d", &numV); } la.resize(numV+1); cout << numV << endl; // Coletando as arestas while (fgets (linha, 2000, fp) != NULL) { //int ant = -1; // Capturando o vertice if (*linha != '-') { // Se o vertice tiver arestas sscanf(linha," %d %d %d", &i, &o, &peso); // Caso de fim de linha, pois nao ha arestas iguais // Logo o destino nao pode ser o mesmo cout << i << " " << o << " " << peso; // ant = i; vector < unsigned int > novo; novo.push_back(o); novo.push_back(peso); la[i].push_back(novo); } /* */ // Apontando para a proxima lista de adjacencias //vert.push_back(arestas.size()); } fclose(fp); list < vector < unsigned int > >::iterator ll; int j = 0; for (int i = 0; i < numV; i++) { vert.push_back(j); for (ll = la[i].begin(); ll != la[i].end(); ll++) { j++; arestas.push_back((*ll)[0]); pesos.push_back((*ll)[1]); } } vert.push_back(j); // Arestas do ultimo vertice } // Cria grafo baseado no modelo do DIMACS // DIMACS usa o seguinte modelo: // Cada linha tem o vertice de origem e o resto da linha sao // as arestas do mesmo vertice void grafo::make_graph(FILE *fp) { char linha[2000]; if (fp==NULL) { cout << "Erro ao abrir arquivo!" << endl; return; } // Primeiro vertice comeca sua lista de adjacencias em 0 vert.push_back(0); // Cada linha tem a representacao de cada vertice // fgets limita-se a capturar uma linha int i, peso; while (fgets (linha, 2000, fp) != NULL) { int ant = -1; // Capturando o vertice if (*linha != '\n') // Se o vertice tiver arestas while(1) { sscanf(linha," %d %d %[0-9 ]", &i, &peso, linha); // Caso de fim de linha, pois nao ha arestas iguais // Logo o destino nao pode ser o mesmo if (ant == i) { break; } cout << i << " "; ant = i; arestas.push_back(i); pesos.push_back(peso); } /* */ // Apontando para a proxima lista de adjacencias vert.push_back(arestas.size()); } fclose(fp); numV = vert.size() - 1; // A representacao faz com que tenha mais um elemento no vetor de vertices } void grafo::printInfo () { cout << "Vetor de vertices:" << endl; vector < cl_uint >::iterator it, it2; for (it=vert.begin();it!=vert.end();it++) { cout << *it << " "; } cout << endl; cout << "Vetor de arestas:" << endl; it2 = pesos.begin(); for (it=arestas.begin();it!=arestas.end();it++) { cout << *it << ":" << *it2 << " "; it2++; } cout << endl; } // Retorna a proxima potencia de 2 baseado numa entrada cl_uint nextPow2 (int n) { cl_uint p = 2; while (p < n && 2*p) p *= 2; return p; } void prepare (vector < cl_uint >& M, vector < cl_uint >& C, vector < cl_uint >& U, int numV, int s) { cl_uint inf = 1 << 30; // Infinito M.resize(numV,0); C.resize(numV, inf); U.resize(numV, inf); M[s] = true; C[s] = 0; U[s] = 0; } void infoPlataforma (cl_platform_id * listaPlataformaID, cl_uint i) { cl_int err; size_t size; err = clGetPlatformInfo(listaPlataformaID[i], CL_PLATFORM_NAME, 0, NULL, &size); char * name = (char *)alloca(sizeof(char) * size); err = clGetPlatformInfo(listaPlataformaID[i], CL_PLATFORM_NAME, size, name, NULL); err = clGetPlatformInfo(listaPlataformaID[i], CL_PLATFORM_VENDOR, 0, NULL, &size); char * vname = (char *)alloca(sizeof(char) * size); err = clGetPlatformInfo(listaPlataformaID[i], CL_PLATFORM_VENDOR, size, vname, NULL); std::cout << "Platform name: " << name << std::endl << "Vendor name : " << vname << std::endl; } // Checagem de erros inline void checkErr(cl_int err, const char *name) { if(err!=CL_SUCCESS) { std::cerr << "ERRO: " << name << " (" << err << ")" << std::endl; exit(EXIT_FAILURE); } } void CL_CALLBACK contextCallback ( const char *errInfo, const void *private_info, size_t cb, void *user_data ) { std::cout << "Ocorreu um erro durante o uso do context: " << errInfo << std::endl; // Ignorando limpeza de memória e saindo diretamente exit(1); } int main(int argc, char *argv[]) { cl_int errNum; cl_uint nPlataformas; cl_uint nDispositivos; cl_platform_id *listaPlataformaID; cl_device_id *listaDispositivoID; cl_context contexto = NULL; cl_command_queue fila; cl_program programa, programa2; cl_kernel kernel, kernel2; cl_mem Vbuffer; cl_mem Abuffer; cl_mem Pbuffer; cl_mem Mbuffer; cl_mem Cbuffer; cl_mem Ubuffer; cl_mem SEMbuffer; cl_mem numVbuffer; cl_event evento; int raiz; cout << "Abrindo arquivo... " << endl; // Abrindo arquivo de entrada FILE *fp = fopen(argv[1], "r"); if (argc > 2) raiz = atoi(argv[2]); grafo g; // Criando vetores auxiliares vector < cl_uint > C, U, M; // Criando Grafo cout << "Montando grafo... " << endl; //g.make_graph9(fp); g.make_graph558(fp, &raiz); // Preparando vetores auxiliares para o Dijkstra cout << endl << "Preparando... raiz em: " << raiz << endl; prepare(M, C, U, g.numV, raiz); //g.printInfo(); cout << "Vetores prontos. " << endl; cout << "Numero de workitems: " << nextPow2(g.arestas.size()) << endl; ///// Selecionando uma plataforma OpenCL para rodar // Atribuindo a nPlataformas o número de plataformas disponíveis errNum = clGetPlatformIDs(0, NULL, &nPlataformas); checkErr( (errNum != CL_SUCCESS) ? errNum : (nPlataformas <= 0 ? -1 : CL_SUCCESS), "clGetPlataformsIDs"); // Se não houve erro, alocar memória para cl_platform_id listaPlataformaID = (cl_platform_id *)alloca(sizeof(cl_platform_id)*nPlataformas); // Atribuindo uma plataforma ao listaPlataformaID errNum = clGetPlatformIDs(nPlataformas, listaPlataformaID, NULL); std::cout << "#Plataformas: " << nPlataformas << std::endl; checkErr( (errNum != CL_SUCCESS) ? errNum : (nPlataformas <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); // Iterando na lista de plataformas até achar uma que suporta um dispositivo de CPU. Se isso não ocorrer, acusar erro. cl_uint i; for (i=0; i < nPlataformas; i++) { // Atribuindo o número de dispositivos de GPU a nDispositivos errNum = clGetDeviceIDs ( listaPlataformaID[i], // CL_DEVICE_TYPE_ALL, //CL_DEVICE_TYPE_CPU, CL_DEVICE_TYPE_GPU, 0, NULL, &nDispositivos ); if (errNum != CL_SUCCESS && errNum != CL_DEVICE_NOT_FOUND) { infoPlataforma(listaPlataformaID, i); checkErr (errNum, "clGetDeviceIDs"); } // Conferindo se há dispositivos de CPU else if (nDispositivos > 0) { // Atribuindo um dispositivo a uma listaDispositivoID listaDispositivoID = (cl_device_id *)alloca(sizeof(cl_device_id)*nDispositivos); errNum = clGetDeviceIDs ( listaPlataformaID[i], // CL_DEVICE_TYPE_ALL, // CL_DEVICE_TYPE_CPU, CL_DEVICE_TYPE_GPU, nDispositivos, &listaDispositivoID[0], NULL); checkErr(errNum, "clGetPlatformIDs"); break; } } // Crindo um contexto no dispositivo/plataforma selecionada std::cout << "Adicionando dispositivos OpenCL de numero " << i << std::endl; infoPlataforma(listaPlataformaID, i); cl_context_properties propContexto[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)listaPlataformaID[i], 0 }; contexto = clCreateContext( propContexto, nDispositivos, listaDispositivoID, &contextCallback, NULL, &errNum ); checkErr(errNum, "clCreateContext"); // Carregando o arquivo-fonte cl para póstuma compilação feita em runtime std::ifstream srcFile("dijkstra.cl"); // Conferindo se ele foi aberto checkErr(srcFile.is_open() ? CL_SUCCESS : -1, "lendo dijkstra.cl"); std::string srcProg ( std::istreambuf_iterator<char>(srcFile), (std::istreambuf_iterator<char>())); const char *fonte = srcProg.c_str(); size_t tamanho = srcProg.length(); // Criando programa da fonte programa = clCreateProgramWithSource ( contexto, 1, &fonte, &tamanho, &errNum); checkErr(errNum, "clCreateProgramWithSource"); // Criando programa da fonte do kernel2 // Carregando o arquivo-fonte cl para póstuma compilação feita em runtime std::ifstream srcFile2("kernel2.cl"); // Conferindo se ele foi aberto checkErr(srcFile2.is_open() ? CL_SUCCESS : -1, "lendo kernel2.cl"); std::string srcProg2 ( std::istreambuf_iterator<char>(srcFile2), (std::istreambuf_iterator<char>())); const char *fonte2 = srcProg2.c_str(); tamanho = srcProg2.length(); programa2 = clCreateProgramWithSource ( contexto, 1, &fonte2, &tamanho, &errNum); checkErr(errNum, "clCreateProgramWithSource"); /* */ // Compilando programa errNum = clBuildProgram ( programa, nDispositivos, listaDispositivoID, NULL, NULL, NULL); errNum = clBuildProgram ( programa2, nDispositivos, listaDispositivoID, NULL, NULL, NULL); if (errNum != CL_SUCCESS) { // Verificando se houve erro // Determinando o motivo do erro char logCompilacao[16384]; clGetProgramBuildInfo ( programa, listaDispositivoID[0], CL_PROGRAM_BUILD_LOG, sizeof(logCompilacao), logCompilacao, NULL); std::cerr << "Erro no kernel: " << std::endl; std::cerr << logCompilacao; checkErr(errNum, "clBuildProgram"); } // Criando o objeto do Kernel kernel = clCreateKernel ( programa, "dijkstra", &errNum); checkErr(errNum, "clCreateKernel"); // Criando o objeto do Kernel2 kernel2 = clCreateKernel ( programa2, "dijkstra2", &errNum); checkErr(errNum, "clCreateKernel2"); // Alocando Buffers Vbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int) * g.vert.size(), g.vert.data(), &errNum); checkErr(errNum, "clCreateBuffer(V)"); Abuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int) * g.arestas.size(), g.arestas.data(), &errNum); checkErr(errNum, "clCreateBuffer(A)"); Pbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int) * g.pesos.size(), g.pesos.data(), &errNum); checkErr(errNum, "clCreateBuffer(P)"); Ubuffer = clCreateBuffer ( contexto, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int) * U.size(), U.data(), &errNum); checkErr(errNum, "clCreateBuffer(U)"); Mbuffer = clCreateBuffer ( contexto, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int) * M.size(), M.data(), &errNum); checkErr(errNum, "clCreateBuffer(M)"); Cbuffer = clCreateBuffer ( contexto, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int) * C.size(), C.data(), &errNum); checkErr(errNum, "clCreateBuffer(C)"); int semaforo = 0; SEMbuffer = clCreateBuffer ( contexto, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int), &semaforo, &errNum); checkErr(errNum, "clCreateBuffer(semaforo)"); int numV = g.vert.size(); numVbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int), &numV, &errNum); checkErr(errNum, "clCreateBuffer(numero_de_vertices)"); /* Bbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint)*m*n, (B), &errNum); checkErr(errNum, "clCreateBuffer(B)"); Cbuffer = clCreateBuffer ( contexto, CL_MEM_WRITE_ONLY, sizeof(cl_uint)*l*n, NULL, &errNum); checkErr(errNum, "clCreateBuffer(C)"); */ // Escolhendo o primeiro dispositivo e criando a fila de comando fila = clCreateCommandQueue ( contexto, listaDispositivoID[0], CL_QUEUE_PROFILING_ENABLE, &errNum); checkErr(errNum, "clCreateCommandQueue"); // Setando os argumentos da função do Kernel errNum = clSetKernelArg(kernel, 0, sizeof(cl_mem), &Vbuffer); errNum |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &Abuffer); errNum |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &Pbuffer); errNum |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &Mbuffer); errNum |= clSetKernelArg(kernel, 4, sizeof(cl_mem), &Cbuffer); errNum |= clSetKernelArg(kernel, 5, sizeof(cl_mem), &Ubuffer); errNum |= clSetKernelArg(kernel, 6, sizeof(cl_mem), &SEMbuffer); errNum |= clSetKernelArg(kernel, 7, sizeof(cl_mem), &numVbuffer); /* */ // Setando os argumentos da função do Kernel2 errNum = clSetKernelArg(kernel2, 0, sizeof(cl_mem), &Vbuffer); errNum |= clSetKernelArg(kernel2, 1, sizeof(cl_mem), &Abuffer); errNum |= clSetKernelArg(kernel2, 2, sizeof(cl_mem), &Pbuffer); errNum |= clSetKernelArg(kernel2, 3, sizeof(cl_mem), &Mbuffer); errNum |= clSetKernelArg(kernel2, 4, sizeof(cl_mem), &Cbuffer); errNum |= clSetKernelArg(kernel2, 5, sizeof(cl_mem), &Ubuffer); errNum |= clSetKernelArg(kernel2, 6, sizeof(cl_mem), &SEMbuffer); errNum |= clSetKernelArg(kernel2, 7, sizeof(cl_mem), &numVbuffer); checkErr(errNum, "clSetKernelArg"); // Definindo o número de work-items globais e locais const size_t globalWorkSize[1] = { g.numV }; const size_t localWorkSize[1] = { 1 }; // releituraFeita e um evento que sincroniza a atualizacao feita // por cada chamada aos kernels cl_event releituraFeita; errNum = clEnqueueReadBuffer(fila, Mbuffer, CL_FALSE, 0, sizeof(int) * M.size(), M.data(), 0, NULL, &releituraFeita); checkErr(errNum, CL_SUCCESS); clWaitForEvents(1, &releituraFeita); while(!vazio(M)) { /* std::cout << endl << "Mask: " << std::endl; for(int i=0; i<M.size(); i++) { cout << M[i] << " "; } */ // Enfileirando o Kernel para execução através da matriz errNum = clEnqueueNDRangeKernel ( fila, kernel, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, &evento); checkErr(errNum, "clEnqueueNDRangeKernel"); // Enfileirando o Kernel2 para execução através da matriz errNum = clEnqueueNDRangeKernel ( fila, kernel2, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, &evento); checkErr(errNum, "clEnqueueNDRangeKernel2"); errNum = clEnqueueReadBuffer(fila, Mbuffer, CL_FALSE, 0, sizeof(int) * M.size(), M.data(), 0, NULL, &releituraFeita); checkErr(errNum, CL_SUCCESS); clWaitForEvents(1, &releituraFeita); } cl_ulong ev_start_time=(cl_ulong)0; cl_ulong ev_end_time=(cl_ulong)0; clFinish(fila); errNum = clWaitForEvents(1, &evento); errNum |= clGetEventProfilingInfo(evento, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &ev_start_time, NULL); errNum |= clGetEventProfilingInfo(evento, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &ev_end_time, NULL); double run_time_gpu = (double)(ev_end_time - ev_start_time); // in usec errNum = clEnqueueReadBuffer ( fila, Mbuffer, CL_TRUE, 0, sizeof(cl_uint) * M.size(), M.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); /* errNum = clEnqueueReadBuffer ( fila, Vbuffer, CL_TRUE, 0, sizeof(cl_uint) * g.vert.size(), g.vert.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); errNum = clEnqueueReadBuffer ( fila, Abuffer, CL_TRUE, 0, sizeof(cl_uint) * g.arestas.size(), g.arestas.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); errNum = clEnqueueReadBuffer ( fila, Pbuffer, CL_TRUE, 0, sizeof(cl_uint) * g.pesos.size(), g.pesos.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); */ errNum = clEnqueueReadBuffer ( fila, Cbuffer, CL_TRUE, 0, sizeof(cl_uint) * C.size(), C.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); errNum = clEnqueueReadBuffer ( fila, Ubuffer, CL_TRUE, 0, sizeof(cl_uint) * U.size(), U.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); /* std::cout << endl << "Vertices: " << std::endl; for(int i=0; i<g.vert.size(); i++) { cout << g.vert[i] << " "; } std::cout << endl << "Arestas: " << std::endl; for(int i=0; i<g.arestas.size(); i++) { cout << g.arestas[i] << " "; } std::cout << endl << "Mask: " << std::endl; for(int i=0; i<g.vert.size() - 1; i++) { cout << M[i] << " "; } std::cout << endl << "Pesos: " << std::endl; for(int i=0; i<g.arestas.size(); i++) { cout << g.pesos[i] << " "; } std::cout << std::endl; cout << setw(6) << setfill('0'); std::cout << "Update: " << std::endl; for(int i=0; i<g.numV; i++) { if (i%8==0) cout << std::endl; if (U[i] < INF) { cout << setw(6) << setfill(' ') << i << ":" << U[i] << " "; } else { cout << setw(6) << setfill(' ') << i << ":" << "INF " << " "; } } std::cout << std::endl; std::cout << "Cost: " << std::endl; for(int i=0; i<g.numV; i++) { if (i%8==0) cout << std::endl; if (C[i] < INF) { cout << setw(6) << setfill(' ')<< i << ":" << C[i] << " "; } else { cout << setw(6) << setfill(' ') << i << ":" << "INF " << " "; } } std::cout << std::endl; */ std::cout << std::endl << std::fixed; std::cout << "Tempo de execução: " << std::setprecision(6) << run_time_gpu/1000000 << " ms"; std::cout << std::endl; std::cout << run_time_gpu*1.0e-6; std::cout << std::endl; log(U, argv); return 0; }
[ "gagallo7@gmail.com" ]
gagallo7@gmail.com
16398a9e08fc3db5480d05882c1bf8450c397e62
1665a6d1f918076d4c5e29059eeedb344e8df28b
/src/reporters/reporter_particle.cpp
141802427cf8609019036ae50e7e65f682e0b812
[ "MIT" ]
permissive
suda/SensorReporter
8ae50ef01c357d6e9774c95a66d418bee7587d32
efd89334fc778f5adde91650899a0ba8f77fa5eb
refs/heads/master
2020-04-01T07:40:54.027722
2018-10-16T17:58:10
2018-10-16T17:58:10
152,999,111
1
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
#include "reporter_particle.h" void ReporterParticle::report(Sample _sample) { String name = this->prefix; name.concat(_sample.name); Particle.publish(name, _sample.value); } void ReporterParticle::setPrefix(String _prefix) { this->prefix = _prefix; };
[ "admin@suda.pl" ]
admin@suda.pl
b804810e42ce1e17cd78f8cbd0738e37a55a37f0
186bb5a81666d27b7576732a35bf5a412b33224b
/exceptions/main.cpp
bc29ebeff5b0ba4e0f4141067b4c0b9731bda83f
[ "MIT" ]
permissive
VgTajdd/cpp_playground
9de305821ecb53539a676097693f5f9039e9ccc9
7d91940f2404ae96a8f66cc6aac4334efca7b245
refs/heads/master
2023-06-07T18:12:38.826641
2023-09-17T19:19:19
2023-06-06T17:29:33
213,281,912
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,076
cpp
#include <iostream> /* An exception is an error condition. */ double division( int a, int b ) { if ( b == 0 ) { throw std::exception( "Division by zero condition!" ); } return ( a / b ); } class Entity { public: Entity() { std::cout << "Entity created!" << std::endl; } ~Entity() { std::cout << "Entity destroyed!" << std::endl; } }; class A { public: A() {}; ~A() noexcept( false ) // Destructors are by defualt noexecpt, so this ('noexcept(false)') will turn-off the compiler warning. { throw std::exception{}; // AVOID THROW EXCEPTIONS OUT OF DESTRUCTORS because destructors are called // during stack unwinding when an exception is thrown, // and we are not allowed to throw another exception while the previous one is // not caught – in such a case std::terminate will be called. // http://www.vishalchovatiya.com/7-best-practices-for-exception-handling-in-cpp-with-example/ } }; struct base { ~base() noexcept( false ) { throw 1; } }; struct derive : base { ~derive() noexcept( false ) { throw 2; } }; // Custom exception. struct MyException : public std::exception { const char* what() const throw ( ) { return "Custom exception"; } }; int main() { // Simple example. { try { throw 20; } catch ( int e ) { std::cout << "An exception occurred! Exception: " << e << std::endl; } } // https://en.cppreference.com/w/cpp/language/try_catch { try { division( 10, 0 ); } catch ( const std::overflow_error& /*e*/ ) { // this executes if division() throws std::overflow_error (same type rule) } catch ( const std::runtime_error& /*e*/ ) { // this executes if division() throws std::underflow_error (base class rule) } catch ( const std::exception& e ) { std::cout << e.what() << std::endl; // this executes if division() throws std::exception (same type rule) // this executes if division() throws std::logic_error (base class rule) } catch ( ... ) { std::cout << "An exception occurred!" << std::endl; // this executes if division() throws std::string or int or any other unrelated type } } // Exceptions in destructors. { try { A a; } catch ( ... ) {} } #if 0 // An exception will be thrown when the object d will be destroyed as a result of RAII. // But at the same time destructor of base will also be called as it is sub - object of derive // which will again throw an exception.Now we have two exceptions at the same time which // is invalid scenario & std::terminate will be called. { try { derive a; } catch ( ... ) {} } #endif std::cout << "----------------" << std::endl; std::cout << "Exception safety" << std::endl; std::cout << "----------------" << std::endl; // This code is exception safe. { try { std::unique_ptr< Entity > entity = std::make_unique< Entity >(); throw std::exception( "Custom exception!" ); // The destructor of Entity is called when scope ends. } catch ( ... ) { // Code to handle the exception. } } std::cout << "----------------" << std::endl; // This code is no exception safe. { try { Entity* entity = new Entity; throw std::exception( "Custom exception!" ); delete entity; // This won't be called! } catch ( ... ) { // Code to handle the exception. } } std::cin.get(); return 0; }
[ "aduranddiaz@gmail.com" ]
aduranddiaz@gmail.com
ebcba5075897623ba1eba0f5fe41ad9e399fc2fc
ab97a8915347c76d05d6690dbdbcaf23d7f0d1fd
/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc
2b44420412ced64b9d0d251c95a8b7e510c8cac3
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
laien529/chromium
c9eb243957faabf1b477939e3b681df77f083a9a
3f767cdd5c82e9c78b910b022ffacddcb04d775a
refs/heads/master
2022-11-28T00:28:58.669067
2020-08-20T08:37:31
2020-08-20T08:37:31
288,961,699
1
0
BSD-3-Clause
2020-08-20T09:21:57
2020-08-20T09:21:56
null
UTF-8
C++
false
false
12,113
cc
// Copyright 2019 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 "third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_blend_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_color_state_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_depth_stencil_state_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_rasterization_state_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_render_pipeline_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_stencil_state_face_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_attribute_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_buffer_layout_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_state_descriptor.h" #include "third_party/blink/renderer/modules/webgpu/dawn_conversions.h" #include "third_party/blink/renderer/modules/webgpu/gpu_bind_group_layout.h" #include "third_party/blink/renderer/modules/webgpu/gpu_device.h" #include "third_party/blink/renderer/modules/webgpu/gpu_pipeline_layout.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" namespace blink { namespace { WGPUBlendDescriptor AsDawnType(const GPUBlendDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPUBlendDescriptor dawn_desc = {}; dawn_desc.dstFactor = AsDawnEnum<WGPUBlendFactor>(webgpu_desc->dstFactor()); dawn_desc.srcFactor = AsDawnEnum<WGPUBlendFactor>(webgpu_desc->srcFactor()); dawn_desc.operation = AsDawnEnum<WGPUBlendOperation>(webgpu_desc->operation()); return dawn_desc; } } // anonymous namespace WGPUColorStateDescriptor AsDawnType( const GPUColorStateDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPUColorStateDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; dawn_desc.alphaBlend = AsDawnType(webgpu_desc->alphaBlend()); dawn_desc.colorBlend = AsDawnType(webgpu_desc->colorBlend()); dawn_desc.writeMask = AsDawnEnum<WGPUColorWriteMask>(webgpu_desc->writeMask()); dawn_desc.format = AsDawnEnum<WGPUTextureFormat>(webgpu_desc->format()); return dawn_desc; } namespace { WGPUStencilStateFaceDescriptor AsDawnType( const GPUStencilStateFaceDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPUStencilStateFaceDescriptor dawn_desc = {}; dawn_desc.compare = AsDawnEnum<WGPUCompareFunction>(webgpu_desc->compare()); dawn_desc.depthFailOp = AsDawnEnum<WGPUStencilOperation>(webgpu_desc->depthFailOp()); dawn_desc.failOp = AsDawnEnum<WGPUStencilOperation>(webgpu_desc->failOp()); dawn_desc.passOp = AsDawnEnum<WGPUStencilOperation>(webgpu_desc->passOp()); return dawn_desc; } WGPUDepthStencilStateDescriptor AsDawnType( const GPUDepthStencilStateDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPUDepthStencilStateDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; dawn_desc.depthCompare = AsDawnEnum<WGPUCompareFunction>(webgpu_desc->depthCompare()); dawn_desc.depthWriteEnabled = webgpu_desc->depthWriteEnabled(); dawn_desc.format = AsDawnEnum<WGPUTextureFormat>(webgpu_desc->format()); dawn_desc.stencilBack = AsDawnType(webgpu_desc->stencilBack()); dawn_desc.stencilFront = AsDawnType(webgpu_desc->stencilFront()); dawn_desc.stencilReadMask = webgpu_desc->stencilReadMask(); dawn_desc.stencilWriteMask = webgpu_desc->stencilWriteMask(); return dawn_desc; } using WGPUVertexStateInfo = std::tuple<WGPUVertexStateDescriptor, Vector<WGPUVertexBufferLayoutDescriptor>, Vector<WGPUVertexAttributeDescriptor>>; WGPUVertexStateInfo GPUVertexStateAsWGPUVertexState( v8::Isolate* isolate, const GPUVertexStateDescriptor* descriptor, ExceptionState& exception_state) { WGPUVertexStateDescriptor dawn_desc = {}; dawn_desc.indexFormat = AsDawnEnum<WGPUIndexFormat>(descriptor->indexFormat()); dawn_desc.vertexBufferCount = 0; dawn_desc.vertexBuffers = nullptr; Vector<WGPUVertexBufferLayoutDescriptor> dawn_vertex_buffers; Vector<WGPUVertexAttributeDescriptor> dawn_vertex_attributes; if (descriptor->hasVertexBuffers()) { // TODO(crbug.com/951629): Use a sequence of nullable descriptors. v8::Local<v8::Value> vertex_buffers_value = descriptor->vertexBuffers().V8Value(); if (!vertex_buffers_value->IsArray()) { exception_state.ThrowTypeError("vertexBuffers must be an array"); return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), std::move(dawn_vertex_attributes)); } v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> vertex_buffers = vertex_buffers_value.As<v8::Array>(); // First we collect all the descriptors but we don't set // WGPUVertexBufferLayoutDescriptor::attributes // TODO(cwallez@chromium.org): Should we validate the Length() first so we // don't risk creating HUGE vectors of WGPUVertexBufferLayoutDescriptor from // the sparse array? for (uint32_t i = 0; i < vertex_buffers->Length(); ++i) { // This array can be sparse. Skip empty slots. v8::MaybeLocal<v8::Value> maybe_value = vertex_buffers->Get(context, i); v8::Local<v8::Value> value; if (!maybe_value.ToLocal(&value) || value.IsEmpty() || value->IsNullOrUndefined()) { WGPUVertexBufferLayoutDescriptor dawn_vertex_buffer = {}; dawn_vertex_buffer.arrayStride = 0; dawn_vertex_buffer.stepMode = WGPUInputStepMode_Vertex; dawn_vertex_buffer.attributeCount = 0; dawn_vertex_buffer.attributes = nullptr; dawn_vertex_buffers.push_back(dawn_vertex_buffer); continue; } GPUVertexBufferLayoutDescriptor* vertex_buffer = NativeValueTraits<GPUVertexBufferLayoutDescriptor>::NativeValue( isolate, value, exception_state); if (exception_state.HadException()) { return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), std::move(dawn_vertex_attributes)); } WGPUVertexBufferLayoutDescriptor dawn_vertex_buffer = {}; dawn_vertex_buffer.arrayStride = vertex_buffer->arrayStride(); dawn_vertex_buffer.stepMode = AsDawnEnum<WGPUInputStepMode>(vertex_buffer->stepMode()); dawn_vertex_buffer.attributeCount = static_cast<uint32_t>(vertex_buffer->attributes().size()); dawn_vertex_buffer.attributes = nullptr; dawn_vertex_buffers.push_back(dawn_vertex_buffer); for (wtf_size_t j = 0; j < vertex_buffer->attributes().size(); ++j) { const GPUVertexAttributeDescriptor* attribute = vertex_buffer->attributes()[j]; WGPUVertexAttributeDescriptor dawn_vertex_attribute = {}; dawn_vertex_attribute.shaderLocation = attribute->shaderLocation(); dawn_vertex_attribute.offset = attribute->offset(); dawn_vertex_attribute.format = AsDawnEnum<WGPUVertexFormat>(attribute->format()); dawn_vertex_attributes.push_back(dawn_vertex_attribute); } } // Set up pointers in DawnVertexBufferLayoutDescriptor::attributes only // after we stopped appending to the vector so the pointers aren't // invalidated. uint32_t attributeIndex = 0; for (WGPUVertexBufferLayoutDescriptor& buffer : dawn_vertex_buffers) { if (buffer.attributeCount == 0) { continue; } buffer.attributes = &dawn_vertex_attributes[attributeIndex]; attributeIndex += buffer.attributeCount; } } dawn_desc.vertexBufferCount = static_cast<uint32_t>(dawn_vertex_buffers.size()); dawn_desc.vertexBuffers = dawn_vertex_buffers.data(); return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), std::move(dawn_vertex_attributes)); } WGPURasterizationStateDescriptor AsDawnType( const GPURasterizationStateDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPURasterizationStateDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; dawn_desc.frontFace = AsDawnEnum<WGPUFrontFace>(webgpu_desc->frontFace()); dawn_desc.cullMode = AsDawnEnum<WGPUCullMode>(webgpu_desc->cullMode()); dawn_desc.depthBias = webgpu_desc->depthBias(); dawn_desc.depthBiasSlopeScale = webgpu_desc->depthBiasSlopeScale(); dawn_desc.depthBiasClamp = webgpu_desc->depthBiasClamp(); return dawn_desc; } } // anonymous namespace // static GPURenderPipeline* GPURenderPipeline::Create( ScriptState* script_state, GPUDevice* device, const GPURenderPipelineDescriptor* webgpu_desc) { DCHECK(device); DCHECK(webgpu_desc); std::string label; WGPURenderPipelineDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; if (webgpu_desc->hasLayout()) { dawn_desc.layout = AsDawnType(webgpu_desc->layout()); } if (webgpu_desc->hasLabel()) { label = webgpu_desc->label().Utf8(); dawn_desc.label = label.c_str(); } OwnedProgrammableStageDescriptor vertex_stage_info = AsDawnType(webgpu_desc->vertexStage()); dawn_desc.vertexStage = std::get<0>(vertex_stage_info); OwnedProgrammableStageDescriptor fragment_stage_info; if (webgpu_desc->hasFragmentStage()) { fragment_stage_info = AsDawnType(webgpu_desc->fragmentStage()); dawn_desc.fragmentStage = &std::get<0>(fragment_stage_info); } else { dawn_desc.fragmentStage = nullptr; } v8::Isolate* isolate = script_state->GetIsolate(); ExceptionState exception_state(isolate, ExceptionState::kConstructionContext, "GPUVertexStateDescriptor"); WGPUVertexStateInfo vertex_state_info = GPUVertexStateAsWGPUVertexState( isolate, webgpu_desc->vertexState(), exception_state); dawn_desc.vertexState = &std::get<0>(vertex_state_info); if (exception_state.HadException()) { return nullptr; } dawn_desc.primitiveTopology = AsDawnEnum<WGPUPrimitiveTopology>(webgpu_desc->primitiveTopology()); WGPURasterizationStateDescriptor rasterization_state; rasterization_state = AsDawnType(webgpu_desc->rasterizationState()); dawn_desc.rasterizationState = &rasterization_state; dawn_desc.sampleCount = webgpu_desc->sampleCount(); WGPUDepthStencilStateDescriptor depth_stencil_state = {}; if (webgpu_desc->hasDepthStencilState()) { depth_stencil_state = AsDawnType(webgpu_desc->depthStencilState()); dawn_desc.depthStencilState = &depth_stencil_state; } else { dawn_desc.depthStencilState = nullptr; } std::unique_ptr<WGPUColorStateDescriptor[]> color_states = AsDawnType(webgpu_desc->colorStates()); dawn_desc.colorStateCount = static_cast<uint32_t>(webgpu_desc->colorStates().size()); dawn_desc.colorStates = color_states.get(); dawn_desc.sampleMask = webgpu_desc->sampleMask(); dawn_desc.alphaToCoverageEnabled = webgpu_desc->alphaToCoverageEnabled(); return MakeGarbageCollected<GPURenderPipeline>( device, device->GetProcs().deviceCreateRenderPipeline(device->GetHandle(), &dawn_desc)); } GPURenderPipeline::GPURenderPipeline(GPUDevice* device, WGPURenderPipeline render_pipeline) : DawnObject<WGPURenderPipeline>(device, render_pipeline) {} GPURenderPipeline::~GPURenderPipeline() { if (IsDawnControlClientDestroyed()) { return; } GetProcs().renderPipelineRelease(GetHandle()); } GPUBindGroupLayout* GPURenderPipeline::getBindGroupLayout(uint32_t index) { return MakeGarbageCollected<GPUBindGroupLayout>( device_, GetProcs().renderPipelineGetBindGroupLayout(GetHandle(), index)); } } // namespace blink
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
080c0d35d2195ed26a02e5465739e970461ae3a0
839515ab21cf09f00321c1a33f8d890060429213
/NFServer/NFGameServerNet_ServerPlugin/NFGameServerNet_ServerModule.h
e0a78d7f02c0a908b487ace0f42181b92c051e50
[ "Apache-2.0" ]
permissive
lemospring/NoahGameFrame
61aea980fc0ef44a60b5c110cba59d75ef7ebc34
c4f049f235e779cd21f9cf3f0c8719c1ae825854
refs/heads/master
2021-03-21T16:22:03.320378
2020-03-14T05:45:36
2020-03-14T05:45:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,541
h
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2020 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 NF_GAMESERVER_SERVER_MODULE_H #define NF_GAMESERVER_SERVER_MODULE_H #include <memory> #include "NFComm/NFMessageDefine/NFMsgDefine.h" #include "NFComm/NFPluginModule/NFINetModule.h" #include "NFComm/NFPluginModule/NFILogModule.h" #include "NFComm/NFPluginModule/NFIKernelModule.h" #include "NFComm/NFPluginModule/NFIClassModule.h" #include "NFComm/NFPluginModule/NFISceneProcessModule.h" #include "NFComm/NFPluginModule/NFIElementModule.h" #include "NFComm/NFPluginModule/NFIEventModule.h" #include "NFComm/NFPluginModule/NFISceneModule.h" #include "NFComm/NFPluginModule/NFIGameServerToWorldModule.h" #include "NFComm/NFPluginModule/NFIGameServerNet_ServerModule.h" #include "NFComm/NFPluginModule/NFIGameServerNet_ServerModule.h" #include "NFComm/NFPluginModule/NFIScheduleModule.h" //////////////////////////////////////////////////////////////////////////// class NFGameServerNet_ServerModule : public NFIGameServerNet_ServerModule { public: NFGameServerNet_ServerModule(NFIPluginManager* p) { pPluginManager = p; } virtual bool Init(); virtual bool Shut(); virtual bool Execute(); virtual bool AfterInit(); virtual void SendMsgPBToGate(const uint16_t nMsgID, google::protobuf::Message& xMsg, const NFGUID& self); virtual void SendGroupMsgPBToGate(const uint16_t nMsgID, google::protobuf::Message& xMsg, const int nSceneID, const int nGroupID); virtual void SendGroupMsgPBToGate(const uint16_t nMsgID, google::protobuf::Message& xMsg, const int nSceneID, const int nGroupID, const NFGUID exceptID); virtual void SendMsgToGate(const uint16_t nMsgID, const std::string& strMsg, const NFGUID& self); virtual void SendGroupMsgPBToGate(const uint16_t nMsgID, const std::string& strMsg, const int nSceneID, const int nGroupID); virtual void SendGroupMsgPBToGate(const uint16_t nMsgID, const std::string& strMsg, const int nSceneID, const int nGroupID, const NFGUID exceptID); virtual bool AddPlayerGateInfo(const NFGUID& nRoleID, const NFGUID& nClientID, const int nGateID); virtual bool RemovePlayerGateInfo(const NFGUID& nRoleID); virtual NF_SHARE_PTR<GateBaseInfo> GetPlayerGateInfo(const NFGUID& nRoleID); virtual NF_SHARE_PTR<GateServerInfo> GetGateServerInfo(const int nGateID); virtual NF_SHARE_PTR<GateServerInfo> GetGateServerInfoBySockIndex(const NFSOCK nSockIndex); protected: void OnSocketPSEvent(const NFSOCK nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet); void OnClientDisconnect(const NFSOCK nSockIndex); void OnClientConnected(const NFSOCK nSockIndex); protected: void OnProxyServerRegisteredProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnProxyServerUnRegisteredProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnRefreshProxyServerInfoProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); protected: void OnClientEnterGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientLeaveGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientSwapSceneProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientReqMoveProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientReqMoveImmuneProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientReqStateSyncProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientReqPosSyncProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientEnterGameFinishProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnLagTestProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); ///////////WORLD_START/////////////////////////////////////////////////////////////// void OnTransWorld(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); protected: void OnClientPropertyIntProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyFloatProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyStringProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyObjectProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyVector2Process(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyVector3Process(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientAddRowProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRemoveRowProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientSwapRowProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordIntProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordFloatProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordStringProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordObjectProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordVector2Process(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordVector3Process(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); protected: ////////////////////////////////////////// private: NFMapEx<NFGUID, GateBaseInfo> mRoleBaseData; //gateid,data NFMapEx<int, GateServerInfo> mProxyMap; ////////////////////////////////////////////////////////////////////////// NFIKernelModule* m_pKernelModule; NFIClassModule* m_pClassModule; NFILogModule* m_pLogModule; NFISceneProcessModule* m_pSceneProcessModule; NFIElementModule* m_pElementModule; NFINetModule* m_pNetModule; NFIEventModule* m_pEventModule; NFISceneModule* m_pSceneModule; NFINetClientModule* m_pNetClientModule; NFIScheduleModule* m_pScheduleModule; }; #endif
[ "342006@qq.com" ]
342006@qq.com
1ec8b8e4d9ed980f9e1e2af57163eb3ec27af8e6
d20876df1308f1eaf3c280f6d3dd78c47633a2d8
/src/Corrade/PluginManager/Test/generated-metadata/GeneratedMetadataDynamic.cpp
ca30521c89c656d9f9cc585d72c5f90cd032af29
[ "MIT", "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
mosra/corrade
729ff71a9c8ceb7d27507b635be6433114b963bf
183b375b73fa3e819a6b41dbcc0cf2f06773d2b4
refs/heads/master
2023-08-24T21:56:12.599589
2023-08-23T14:07:19
2023-08-24T09:43:55
2,863,909
470
143
NOASSERTION
2023-09-12T02:52:28
2011-11-28T00:51:12
C++
UTF-8
C++
false
false
1,865
cpp
/* This file is part of Corrade. Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "../AbstractGeneratedMetadata.h" #include "Corrade/PluginManager/AbstractManager.h" namespace Corrade { namespace PluginManager { namespace Test { struct GeneratedMetadataDynamic: AbstractGeneratedMetadata { explicit GeneratedMetadataDynamic(AbstractManager& manager, const Containers::StringView& plugin): AbstractGeneratedMetadata{manager, plugin} {} }; }}} CORRADE_PLUGIN_REGISTER(GeneratedMetadataDynamic, Corrade::PluginManager::Test::GeneratedMetadataDynamic, "cz.mosra.corrade.PluginManager.Test.AbstractGeneratedMetadata/1.0")
[ "mosra@centrum.cz" ]
mosra@centrum.cz
a9ddf2117cffb017e1cb9c93f63941d572605006
4296ad62fc2d1c0111af5e9c9ef5b8336256674e
/src/arc36/c.cpp
55b1142cc1134fbd358aaffca76214d2436c098c
[]
no_license
emakryo/cmpro
8aa50db1d84fb85e515546f37e675121be9de5c2
81db478cc7da06a9b99a7888e39952ddb82cdbe5
refs/heads/master
2023-02-09T12:36:47.893287
2023-01-23T12:07:03
2023-01-23T12:07:03
79,899,196
0
0
null
null
null
null
UTF-8
C++
false
false
2,768
cpp
#include<bits/stdc++.h> #include<boost/variant.hpp> using namespace std; typedef long long ll; typedef vector<boost::variant<bool, ll, int, string, double, char*, const char*>> any; template<typename T> inline void pr(const vector<T> &xs){ for(int i=0; i<xs.size()-1; i++) cout<<xs[i]<<" "; (xs.empty()?cout:(cout<<xs[xs.size()-1]))<<endl; } #ifdef DEBUG #define debug(...) pr(any{__VA_ARGS__}) #define debugv(x) pr((x)) #else #define debug(...) #define debugv(x) #endif struct mint { typedef long long ll; ll x, m; mint(ll x=0, ll m=1e9+7): x(x%m), m(m) {} mint operator-() const { return mint(m-x, m); } mint operator+(const mint o) const { return mint(x+o.x, m); } mint operator-(const mint o) const { return mint(x-o.x+m, m); } mint operator*(const mint o) const { return mint(x*o.x, m); } mint& operator+=(const mint o) { x = (x+o.x)%m; return *this; } mint& operator-=(const mint o) { x = (x-o.x+m)%m; return *this; } mint& operator*=(const mint o) { x = x*o.x%m; return *this; } bool operator==(const mint o) const { return x==o.x; } bool operator!=(const mint o) const { return x!=o.x; } template<typename T> mint& operator=(const T o) { x = o%m; return *this; } template<typename T> mint operator+(const T o) const { return mint(x+o, m); } template<typename T> mint operator-(const T o) const { return mint(x-((ll)o)%m+m, m); } template<typename T> mint operator*(const T o) const { return mint(x*o, m); } template<typename T> mint& operator+=(const T o) { x = (x+(ll)o%m)%m; return *this; } template<typename T> mint& operator-=(const T o) { x = (x-((ll)o)%m+m)%m; return *this; } template<typename T> mint& operator*=(const T o) { x = x*((ll)o%m)%m; return *this; } template<typename T> bool operator==(const T o) const { return x==o%m; } template<typename T> bool operator!=(const T o) const { return x!=o%m; } mint pow(ll k) const { if(k==0) return mint(1, m); if(k%2) return pow(k-1)*x; mint z = pow(k/2); return z*z; } mint inv() const { return pow(m-2); } }; mint dp[2][305][305]; int main(){ int N, K; cin >> N >> K; string S; cin >> S; dp[0][0][0] = 1; for(int i=0; i<N; i++){ for(int p=0; p<=K; p++) for(int q=0; q<=K; q++) dp[(i+1)%2][p][q] = 0; int n_pos = 0; for(int p=0; p<=K; p++) for(int q=0; q<=K; q++) { debug(i, p, q, dp[i%2][p][q].x); if(dp[i%2][p][q] != 0) n_pos++; if(S[i]=='?' || S[i]=='0'){ if(q>0) dp[(i+1)%2][p+1][q-1] += dp[i%2][p][q]; else dp[(i+1)%2][p+1][q] += dp[i%2][p][q]; } if(S[i]=='?' || S[i]=='1'){ if(p>0) dp[(i+1)%2][p-1][q+1] += dp[i%2][p][q]; else dp[(i+1)%2][p][q+1] += dp[i%2][p][q]; } } debug(n_pos); } mint ans; for(int p=0; p<=K; p++) for(int q=0; q<=K; q++) ans += dp[N%2][p][q]; cout << ans.x << endl; return 0; }
[ "ryosuke.kamesawa@dena.jp" ]
ryosuke.kamesawa@dena.jp
a82f1f5ae16cacdc5b315dd3ca012a691e12fb0e
9e9267611371cdff143e7a9b286a9fffc2641e78
/about.cpp
2f19cfdae4ea8cd13cc09e765a17fb1c62037efa
[]
no_license
wucan/csv2sql
736473e357c73acf40fa4ca96c05af3b52a572fc
20c9630bd323d7787eb5a1982f8c98c0fd1a9ecc
refs/heads/master
2021-01-22T23:57:52.712701
2012-03-30T13:49:14
2012-03-30T13:49:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
cpp
#include <QPushButton> #include "about.h" AboutDialog::AboutDialog() { /* build ui */ ui.setupUi(this); ui.closeButtonBox->addButton(new QPushButton("&Close", this), QDialogButtonBox::RejectRole); setWindowRole("csv2sql-about"); setMinimumSize(400, 300); resize(400, 300); setWindowModality(Qt::WindowModal); connect(ui.closeButtonBox, SIGNAL(rejected()), this, SLOT(close())); ui.closeButtonBox->setFocus(); ui.introduction->setText("CSV2SQL " APP_VERSION); ui.iconApp->setPixmap(QPixmap(":/images/logo")); /* Main Introduction */ ui.infoLabel->setText( "CSV2SQL is CSV -> SQL inject, " "for Adidas system.\n" "This version of csv2sql was compiled at: " __DATE__" " __TIME__"\n" "Copyright (C) 2012 AAA"); /* License */ ui.licenseEdit->setText("AAA"); /* People who helped */ ui.thanksEdit->setText(""); /* People who wrote the software */ ui.authorsEdit->setText(""); } void AboutDialog::close() { done(0); }
[ "wu.canus@gmail.com" ]
wu.canus@gmail.com
bfe76ae9c060dec1266a80d5c27c80e019148545
a3ec7ce8ea7d973645a514b1b61870ae8fc20d81
/Codeforces/A/404.cc
f978cf5c38a0d91457842b3f31fea7221820d6d7
[]
no_license
userr2232/PC
226ab07e3f2c341cbb087eecc2c8373fff1b340f
528314b608f67ff8d321ef90437b366f031e5445
refs/heads/master
2022-05-29T09:13:54.188308
2022-05-25T23:24:48
2022-05-25T23:24:48
130,185,439
1
0
null
null
null
null
UTF-8
C++
false
false
1,515
cc
#include <iostream> #include <vector> #include <set> using namespace std; int main() { int n; cin >> n; bool out = false; vector<string> sq; set<char> all_set; for(int i = 0; i < n && !out; ++i) { string tmp; cin >> tmp; sq.push_back(tmp); set<char> tmp_set; for(auto c : tmp) { tmp_set.insert(c); all_set.insert(c); if(all_set.size() > 2) { cout << "NO" << endl; out = true; break; } } } char main_char = sq[0][0]; for(int i = 0; i < n && !out; ++i) { int sum = 0; for(int j = 0; j < n && !out; ++j) { if(i == n / 2) { if(sq[i][j] == main_char) { if(j != n / 2) { cout << "NO" << endl; out = true; break; } } else { if(j == n / 2) { cout << "NO" << endl; out = true; break; } } } else { if(sq[i][j] == main_char) { sum += j + 1; } } } if(i != n/2 && !out && sum != n + 1) { cout << "NO" << endl; out = true; break; } } if(!out) cout << "YES" << endl; }
[ "reynaldo.rz.26@gmail.com" ]
reynaldo.rz.26@gmail.com
f06585d106b12a765e5f0e62c54cc0f9436209cd
e6ae6070d3053ca1e4ff958c719a8cf5dfcd6b9b
/sum_to_prime_spoj.cpp
f7883717e6b737c7893878b4eeb3553bcbe5faa1
[]
no_license
Arti14/Competitive-Programming
31d246d34581599219ffb7e23a3372f02fc6dfa6
de42977b6cce39bb480d3cf90c1781d806be3b56
refs/heads/master
2021-01-25T07:34:29.240567
2015-05-08T07:07:10
2015-05-08T07:07:10
35,263,950
0
0
null
null
null
null
UTF-8
C++
false
false
1,260
cpp
#include <iostream> #include <cmath> #include <vector> using namespace std; vector < int > arr; int dp[4][8000]; int cnt(int m, int n) { if(n==0) { return 1; } if(n<0) { return 0; } if (m <=0 && n >= 1) { return 0; } if (dp[m][n] == 0) { dp[m][n] = cnt(m - 1, n) + cnt(m, n - m); } return dp[m][n]; } int main() { int T; int Sp2n[501]; int count=1; for (int i = 0; i < 8000; ++i) { for (int j = 0; j < 4; ++j) { dp[j][i] = 0; } } cnt(3, 7994); for(int i=2;i<7994;i++) { int j; if(count==1) { Sp2n[count]=2; count++; continue; } for(j=2;j<=sqrt(i);j++) { if(i%j==0) { break; } } if(j>sqrt(i)&&(i-1)%4==0) { Sp2n[count]=i; count++; } } cin>>T; while(T--) { int n, k; cin>>n>>k; int p=cnt(k,Sp2n[n]); cout<<p<<endl; } }
[ "rt@rt-VGN-CS14G-B.(none)" ]
rt@rt-VGN-CS14G-B.(none)
f9b5ca0cc955310239e328ec62576564519c0b0d
5cf7bb9a74875cd2a110fa3e1243b7c3f2e54753
/EXTERNAL/MMPS_245/MMPS_245/cpp/fsurf_tools/randsurfsmooth.cpp
b620f5bf9e6199f921d8eeb7db457832a4c73dcd
[]
no_license
ekaestner/MMIL
5c7dd8045550fe9cee41b1477f7c188916f29a5e
ce9d5bd01a38fd622719a787f28eb10dd66dff15
refs/heads/master
2023-04-27T20:36:30.815437
2023-04-23T17:49:53
2023-04-23T17:49:53
155,797,098
6
1
null
null
null
null
UTF-8
C++
false
false
15,918
cpp
/* randsurfsmooth.cpp: generate value at random vertex, smooth, calculate fwhm created: 02/11/05 DH last mod: 04/16/13 DH purpose: calculating fwhm for different smoothing steps input: options only output: stdout only acknowledgements: */ #include "surflib.h" #include "clustlib.h" using namespace std; #define MINARGC 3 #define INITVALUE 1000 #define RATIO(X,Y) ((float)X/(float)Y) #ifdef Darwin # define RAND_FLOAT(L,H) ((L)+RATIO(random(),INT_MAX)*((H)-(L))) #else # define RAND_FLOAT(L,H) ((L)+RATIO(random(),MAXINT)*((H)-(L))) #endif #define RAND_INT(H) (int)RAND_FLOAT(0,H) #define SMALLFLOAT 1e-10 // todo: optional pdf (probability distribution function) output /* global variables */ static char *progname = NULL; /* parameter defaults */ char subj[STRLEN]=UNDEFSTR; char instem[STRLEN]=UNDEFSTR; char maskstem[STRLEN]=UNDEFSTR; char outstem[STRLEN]=UNDEFSTR; char indir[STRLEN]="."; char maskdir[STRLEN]="."; char outdir[STRLEN]="."; char hemi[STRLEN]="rh"; char real_infix[STRLEN]="_r"; char imag_infix[STRLEN]="_i"; char surf[STRLEN]="white"; int niter = 1; int minsmooth = 0; int maxsmooth = 100; int smoothinc = 10; int growclusterflag = 0; int heatflag = 0; int complexflag = 0; int dataflag = 0; int maskflag = 0; int outflag = 0; float stdev = 1.0; float heatsigma = 0; /* functions */ void usage() { printf("\n"); printf("Usage: %s -subj subjname [options]\n",progname); printf("\n"); printf(" Required parameters:\n"); printf(" -subj subjname subject name (can be ico)\n"); printf("\n"); printf(" Optional parameters:\n"); printf(" -instem instem omit extension, infixes, hemi:\n"); printf(" <instem>_{r,i}-{rh,lh}.w\n"); printf(" If instem not specified, will generate\n"); printf(" Gaussian noise instead\n"); printf(" -indir [.] input dir\n"); printf(" -maskstem maskstem stem for w file defining ROI\n"); printf(" -maskdir [.] dir containing mask file\n"); printf(" -outstem [randsmooth] text output file stem\n"); printf(" -outdir [.] output dir\n"); printf(" -growcluster grow cluster from non-zero seed\n"); printf(" -hemi [rh] hemisphere (rh or lh)\n"); printf(" -niter [1] number of iterations\n"); printf(" -minsmooth [0] minimum number of smoothing steps\n"); printf(" -maxsmooth [100] maximum number of smoothing steps\n"); printf(" -smoothinc [10] incremental increase in smooth steps\n"); printf(" -surf [white] surface used for area calculations\n"); printf(" -stdev [1.0] standard deviation of random values\n"); printf(" -heatsigma [0.0] sigma of heat keernel smoothing\n"); printf(" -avgdist use average distance for noise fwhm\n"); printf(" -complex complex (phase-encoded) data\n"); printf(" -quiet suppress messages\n"); printf("\n"); } void parse_args(int argc, char **argv) { int i; char tempstr[STRLEN]; char *pch; progname = argv[0]; /* strip off path */ pch = strtok(progname,"/"); while (pch!=NULL) { strcpy(tempstr,pch); pch = strtok (NULL,"/"); } strcpy(progname,tempstr); if (argc<MINARGC) {usage(); exit(0);} /* parse arguments */ for (i=1;i<argc;i++) { if (argv[i][0]=='-') { if ((MATCH(argv[i],"-subj") || MATCH(argv[i],"-name")) && i+1<argc){ strcpy(subj,argv[i+1]); i++; } else if (MATCH(argv[i],"-instem") && i+1<argc) { strcpy(instem,argv[i+1]); i++; dataflag=1; } else if (MATCH(argv[i],"-maskstem") && i+1<argc){ strcpy(maskstem,argv[i+1]); i++; maskflag=1; } else if (MATCH(argv[i],"-outstem") && i+1<argc){ strcpy(outstem,argv[i+1]); i++; } else if (MATCH(argv[i],"-indir") && i+1<argc) { strcpy(indir,argv[i+1]); i++; } else if (MATCH(argv[i],"-outdir") && i+1<argc) { strcpy(outdir,argv[i+1]); i++; } else if (MATCH(argv[i],"-maskdir") && i+1<argc) { strcpy(maskdir,argv[i+1]); i++; } else if (MATCH(argv[i],"-hemi") && i+1<argc) { strcpy(hemi,argv[i+1]); i++; } else if (MATCH(argv[i],"-niter") && i+1<argc){ niter = atoi(argv[i+1]); i++; } else if (MATCH(argv[i],"-minsmooth") && i+1<argc){ minsmooth = atoi(argv[i+1]); i++; } else if (MATCH(argv[i],"-maxsmooth") && i+1<argc){ maxsmooth = atoi(argv[i+1]); i++; } else if (MATCH(argv[i],"-smoothinc") && i+1<argc){ smoothinc = atoi(argv[i+1]); i++; } else if (MATCH(argv[i],"-growcluster")){ growclusterflag = 1; } else if (MATCH(argv[i],"-heatsigma")){ heatsigma = atof(argv[i+1]); i++; heatflag = 1; } else if (MATCH(argv[i],"-complex")){ complexflag = 1; } else if (MATCH(argv[i],"-surf") && i+1<argc) { strcpy(surf,argv[i+1]); i++; } else if (MATCH(argv[i],"-stdev") && i+1<argc) { stdev = atof(argv[i+1]); i++; } else if (MATCH(argv[i],"-quiet")){ setQuiet(1); } else ErrorExit(ERROR_BADPARM,"%s: ### parse error opt: %s\n",progname,argv[i]); } else ErrorExit(ERROR_BADPARM,"%s: ### parse error opt: %s\n",progname,argv[i]); } MsgPrintf("%s: starting to check arguments\n",progname); /* check arguments */ if (MATCH(subj,UNDEFSTR)) ErrorExit(ERROR_BADPARM,"%s: ### subject name not specified ...quitting\n", progname); if (!FileExists(indir)) { ErrorExit(ERROR_BADPARM,"%s: ### indir %s not found ...quitting\n", progname,indir); } if(!isadir(indir)) { ErrorExit(ERROR_BADPARM,"%s: ### %s exists, but not a dir ...quitting\n", progname,indir); } if (!FileExists(maskdir)) { ErrorExit(ERROR_BADPARM,"%s: ### maskdir %s not found ...quitting\n", progname,maskdir); } if(!isadir(maskdir)) { ErrorExit(ERROR_BADPARM,"%s: ### %s exists, but not a dir ...quitting\n", progname,maskdir); } if (!MATCH(outstem,UNDEFSTR)) outflag=1; if (!FileExists(outdir)) { ErrorExit(ERROR_BADPARM,"%s: ### outdir %s not found ...quitting\n", progname,outdir); } if(!isadir(outdir)) { ErrorExit(ERROR_BADPARM,"%s: ### %s exists, but not a dir ...quitting\n", progname,outdir); } if (!MATCH(hemi,"rh") && !MATCH(hemi,"lh")) ErrorExit(ERROR_BADPARM,"%s: ### %s: hemi must be rh or lh\n", progname,hemi); if (maxsmooth < 0) ErrorExit(ERROR_BADPARM,"%s: ### %s: maximum smooth steps (%d) must be >0\n", progname,maxsmooth); if (minsmooth > maxsmooth) minsmooth = maxsmooth; if (minsmooth < 0) minsmooth = 0; if (smoothinc <= 0) ErrorExit(ERROR_BADPARM,"%s: ### %s: smooth increment (%d) must be >0\n", progname,smoothinc); if (niter < 0) ErrorExit(ERROR_BADPARM,"%s: ### %s: number of iterations (%d) must be >0\n", progname,niter); if (heatflag && heatsigma <= 0) ErrorExit(ERROR_BADPARM,"%s: ### %s: heat kernel sigma (%0.3f) must be >0\n", progname,heatsigma); MsgPrintf("%s: finished parsing arguments\n",progname); } float uniform () { return ( (float)drand48() ); } void normal (float * n1, float * n2) { float u1, u2; float r; u1 = 0.0; while (u1 <= 0.0) {u1 = uniform();} u2 = uniform(); #if 0 r = sqrt(-2.0*log(u1)); #else r = stdev * sqrt(-2.0*log(u1)); #endif *n1 = r * cos(2.0*M_PI*u2); *n2 = r * sin(2.0*M_PI*u2); } void genRandSurf(MRIS *mris) { int k, nverts, nvertsdiv2; float n1, n2; nverts = mris->nvertices; nvertsdiv2 = nverts/2; for (k=0;k<nvertsdiv2;k++) { normal(&n1,&n2); mris->vertices[k].val = n1; mris->vertices[k+nvertsdiv2].val = n2; } normal(&n1,&n2); mris->vertices[nverts-1].val = n1; } void genRandSurf(MRIS *mris, int *maskverts, int nmaskverts) { int j,k, nvertsdiv2; float n1, n2; nvertsdiv2 = nmaskverts/2; for (j=0;j<nvertsdiv2;j++) { normal(&n1,&n2); k=maskverts[j]; mris->vertices[k].val = n1; k=maskverts[j+nvertsdiv2]; mris->vertices[k].val = n2; } normal(&n1,&n2); k=maskverts[nmaskverts-1]; mris->vertices[k].val = n1; } void genCxRandSurf(MRIS *mris) { int k; float n1, n2; for (k=0;k<mris->nvertices;k++) { normal(&n1,&n2); mris->vertices[k].val = n1; mris->vertices[k].imag_val = n2; } } void genCxRandSurf(MRIS *mris, int *maskverts, int nmaskverts) { int j,k; float n1, n2; for (j=0;j<nmaskverts;j++) { normal(&n1,&n2); k=maskverts[j]; mris->vertices[k].val = n1; mris->vertices[k].imag_val = n2; } } int main(int argc, char **argv) { int i,j,k,nverts,nmaskverts=0,seedvert=0,s; float *avgdiam, *stdevdiam; MRIS *mris; ClusterList clustlist; Cluster clust; int threshabsflag = 0; float halfmax=0,diam,area; float *maskvals=NULL; int *maskverts=NULL; float *vals=NULL, *imag_vals=NULL; FILE *fp=NULL; char tempstr[STRLEN]; int ecode=NO_ERROR; parse_args(argc,argv); randseed(); if(outflag) { // open output file sprintf(tempstr,"%s/%s.txt",outdir,outstem); fp = fopen(tempstr,"w"); if(fp==NULL) ErrorExit(ERROR_NOFILE,"%s: ### can't create file %s\n",progname,tempstr); } // load surface MsgPrintf("%s: loading surface files\n",progname); mris = openSurface(subj,hemi,surf); nverts = mris->nvertices; MsgPrintf("%s: nverts = %d\n",progname,nverts); // load data if(dataflag && !growclusterflag) { if(complexflag) { // read complex input files MsgPrintf("%s: reading input files\n",progname); vals = new float[nverts]; MTEST(vals); sprintf(tempstr,"%s/%s%s-%s.w",indir,instem,real_infix,hemi); ecode = readSurfVals(tempstr,vals,nverts); if(ecode) ErrorExit(ecode,"%s: ### error reading value file %s\n", progname,tempstr); imag_vals = new float[nverts]; MTEST(imag_vals); sprintf(tempstr,"%s/%s%s-%s.w",indir,instem,imag_infix,hemi); ecode = readSurfVals(tempstr,imag_vals,nverts); if(ecode!=NO_ERROR) ErrorExit(ecode,"%s: ### error reading value file %s\n", progname,tempstr); } else { // read input file MsgPrintf("%s: reading input file\n",progname); vals = new float[nverts]; MTEST(vals); sprintf(tempstr,"%s/%s-%s.w",indir,instem,hemi); ecode = readSurfVals(tempstr,vals,nverts); if(ecode) ErrorExit(ecode,"%s: ### error reading value file %s\n", progname,tempstr); } } if(maskflag) { MsgPrintf("%s: reading mask file\n",progname); maskvals = new float[nverts]; MTEST(maskvals); sprintf(tempstr,"%s/%s-%s.w",maskdir,maskstem,hemi); ecode = readSurfVals(tempstr,maskvals,nverts); if(ecode!=NO_ERROR) ErrorExit(ecode,"%s: ### error reading mask file %s\n", progname,tempstr); MsgPrintf("%s: finished reading input files\n",progname); for (k=0;k<nverts;k++) { if(maskvals[k]>0) { nmaskverts++; mris->vertices[k].undefval=0; } else { mris->vertices[k].undefval=1; } } MsgPrintf("%s: nmaskverts = %d\n",progname,nmaskverts); maskverts = new int[nmaskverts]; MTEST(maskverts); for (k=0,j=0;k<nverts;k++) { if(maskvals[k]>0) maskverts[j++]=k; } } else { nmaskverts = nverts; maskverts = new int[nverts]; MTEST(maskverts); for (k=0;k<nverts;k++) { maskverts[k]=k; mris->vertices[k].undefval=0; } } // initialize arrays avgdiam = new float[maxsmooth+1]; stdevdiam = new float[maxsmooth+1]; for (s=minsmooth;s<=maxsmooth;s++) { avgdiam[s]=0; stdevdiam[s]=0; } for (i=0;i<niter;i++) { MsgPrintf("%s: ## iteration %d ##\n",progname,i); MRISclearValues(mris); if(growclusterflag) { MsgPrintf("%s: generating value at random vertex\n",progname); j = RAND_INT(nmaskverts); seedvert = maskverts[j]; mris->vertices[seedvert].val = INITVALUE; } else { if(dataflag) { MsgPrintf("%s: restoring original data values at each vertex\n",progname); for (j=0;j<nmaskverts;j++) { k=maskverts[j]; mris->vertices[k].val=vals[k]; if(complexflag) mris->vertices[k].imag_val=imag_vals[k]; } } else { MsgPrintf("%s: generating random values at each vertex\n",progname); if(maskflag) if(complexflag) genCxRandSurf(mris,maskverts,nmaskverts); else genRandSurf(mris,maskverts,nmaskverts); else if(complexflag) genCxRandSurf(mris); else genRandSurf(mris); } } // ROI smoothing to skip vertices outside of mask if(minsmooth>0) { if(complexflag) MRISsmoothComplexValuesROI(mris,minsmooth); // todo: heat kernel smoothing for complex values -- why bother? else if(heatflag) MRISsmoothValuesHeatROI(mris,minsmooth,heatsigma); else MRISsmoothValuesROI(mris,minsmooth); } for (s=minsmooth;s<=maxsmooth;s+=smoothinc) { if(s>minsmooth) { if(complexflag) MRISsmoothComplexValuesROI(mris,smoothinc); else if(heatflag) MRISsmoothValuesHeatROI(mris,smoothinc,heatsigma); else MRISsmoothValuesROI(mris,smoothinc); } if(growclusterflag) { initSurfClustIndices(mris); halfmax = mris->vertices[seedvert].val/2; clust.clear(); clust.addVertex(seedvert); clust.growCluster(seedvert,mris,halfmax,threshabsflag); clust.calcStats(mris); area = clust.Area(); diam = 2*sqrt(area/M_PI); MsgPrintf("%s: smooth=%d, clustverts=%d, area=%0.4f, diam=%0.4f\n", progname,s,clust.size(),clust.Area(),diam); } else { if(complexflag) diam=MRISgaussCxFWHM(mris,1); else diam=MRISgaussFWHM(mris,1); MsgPrintf("%s: smooth=%d, fwhm=%0.4f\n", progname,s,diam); } avgdiam[s]+=diam; stdevdiam[s]+=diam*diam; } } MsgPrintf("%s: iterations completed = %d\n",progname,niter); MsgPrintf("%s: min smooth steps = %d\n",progname,minsmooth); MsgPrintf("%s: max smooth steps = %d\n",progname,maxsmooth); if(outflag) MsgPrintf("%s: saving results to %s/%s.txt:\n",progname,outdir,outstem); if(niter>1) { if(outflag) fprintf(fp,"smooth steps ; avg diam (mm) ; stdev\n"); printf("smooth steps ; avg diam (mm) ; stdev\n"); } else { if(outflag) fprintf(fp,"smooth steps ; avg diam (mm)\n"); printf("smooth steps ; avg diam (mm)\n"); } for (s=minsmooth;s<=maxsmooth;s+=smoothinc) { if(niter<=1) { stdevdiam[s] = 0; if(outflag) fprintf(fp,"%d ; %0.10f\n",s,avgdiam[s]); printf("%d ; %0.10f\n",s,avgdiam[s]); } else { stdevdiam[s] = (stdevdiam[s] - (avgdiam[s]*avgdiam[s])/niter)/(niter-1); if(stdevdiam[s]<0) stdevdiam[s]=0; else stdevdiam[s]=sqrt(stdevdiam[s]); avgdiam[s]/=niter; if(outflag) fprintf(fp,"%d ; %0.10f ; %0.10f\n",s,avgdiam[s],stdevdiam[s]); printf("%d ; %0.10f ; %0.10f\n",s,avgdiam[s],stdevdiam[s]); } } // cleanup if(dataflag) { delete [] vals; if(complexflag) delete [] imag_vals; } if(maskflag) { delete [] maskvals; } delete [] maskverts; delete [] avgdiam; delete [] stdevdiam; if(outflag) fclose(fp); MsgPrintf("\n%s: finished\n",progname); }
[ "erik.kaestner@gmail.com" ]
erik.kaestner@gmail.com
51e96cec613372a1c8a36fdf984d3091e7c2967d
b116bebaea28d233092a76abc683d274675989ad
/forumCode/forumCode.ino
2927a9c14a9e9f6f416289c8f0abc366c6c3feec
[]
no_license
nrtyc4/picospritzer
762345983840c3fa53c273658ca190f173fd832d
071b3888a1ee91f30774148dfaba6e914d431d28
refs/heads/master
2016-09-06T08:39:19.038829
2013-08-09T23:34:16
2013-08-09T23:34:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,777
ino
#include <Wire.h> //I2C library const byte LCDa = 40; //LCD address on I2C bus const byte LCD_CLEAR[2] = {0xFE, 0x51}; const byte LCD_CLEAR_COUNT = 2; const byte LCD_SET_CURSOR[2] = {0xFE, 0x45}; const byte LCD_SET_CURSOR_COUNT = 2; //const byte LCD_UNDERLINE_CURSOR_ON[2] = {0xFE, 0x47}; //const byte LCD_UNDERLINE_CURSOR_ON_COUNT = 2; //const byte LCD_UNDERLINE_CURSOR_OFF[2] = {0xFE, 0x48}; //const byte LCD_UNDERLINE_CURSOR_OFF_COUNT = 2; void setup() { delay(200); Wire.begin(); // join i2c bus (address optional for master) Wire.beginTransmission(LCDa); Wire.write(LCD_CLEAR, LCD_CLEAR_COUNT); //Clear screen every time the program begins Wire.endTransmission(); delayMicroseconds(1500); //Set cursor to 1st line Wire.beginTransmission(LCDa); Wire.write(LCD_SET_CURSOR, LCD_SET_CURSOR_COUNT); Wire.write(0x00); Wire.endTransmission(); delayMicroseconds(100); //Create first char string Wire.beginTransmission(LCDa); for (byte i=47; i<66; i++) { Wire.write(i); } Wire.endTransmission(); //Set cursor to 2nd line Wire.beginTransmission(LCDa); Wire.write(LCD_SET_CURSOR, LCD_SET_CURSOR_COUNT); Wire.write(0x40); Wire.endTransmission(); delayMicroseconds(100); Wire.beginTransmission(LCDa); for (byte i=48; i<67; i++) { Wire.write(i); } Wire.endTransmission(); //Set cursor to 3rd line Wire.beginTransmission(LCDa); Wire.write(LCD_SET_CURSOR, LCD_SET_CURSOR_COUNT); Wire.write(0x14); Wire.endTransmission(); delayMicroseconds(100); //Write 3rd char string on 3rd line Wire.beginTransmission(LCDa); for (byte i=47; i<66; i++) { Wire.write(i); } Wire.endTransmission(); } void loop() { }
[ "natthompson72@gmail.com" ]
natthompson72@gmail.com
a06d0b2ba7c1970c1ab270f7844b496f44c787cc
726030bc5951dfb65fd823cc11d39e2f145f85c1
/Source/SnakeGame2/PlayerPawnBase.cpp
c92c7aab628764411e9d2722911cd1f843f709ad
[]
no_license
anchello2810/SnakeGame2
061877ffb4bd111ebe8e1d11a1f0ff31cc888542
b732b682ab2466bd47d6691d0a5bb0af18a5da2b
refs/heads/master
2023-07-10T15:37:21.344179
2021-08-09T14:43:27
2021-08-09T14:43:27
391,105,607
0
0
null
null
null
null
UTF-8
C++
false
false
2,163
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "PlayerPawnBase.h" #include "Engine/Classes/Camera/CameraComponent.h" #include "SnakeBase.h" #include "Components/InputComponent.h" #include "Food.h" // Sets default values APlayerPawnBase::APlayerPawnBase() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; PawnCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("PawnCamera")); RootComponent = PawnCamera; } // Called when the game starts or when spawned void APlayerPawnBase::BeginPlay() { Super::BeginPlay(); SetActorRotation(FRotator(-90, 0, 0)); CreateSnakeActor(); } // Called every frame void APlayerPawnBase::Tick(float DeltaTime) { Super::Tick(DeltaTime); //AddRandomApple(); } // Called to bind functionality to input void APlayerPawnBase::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("Vertical", this, &APlayerPawnBase::HandlePlayerVerticalImput); PlayerInputComponent->BindAxis("Horizontal", this, &APlayerPawnBase::HandlePlayerHorizontalImput); } void APlayerPawnBase::CreateSnakeActor() { SnakeActor = GetWorld()->SpawnActor<ASnakeBase>(SnakeActorClass, FTransform()); } void APlayerPawnBase::HandlePlayerVerticalImput(float value) { if (IsValid(SnakeActor)) { if (value > 0 && SnakeActor->LastMoveDirection != EMovementDirection::DOWN) { SnakeActor->LastMoveDirection = EMovementDirection::UP; } else if (value < 0 && SnakeActor->LastMoveDirection != EMovementDirection::UP) { SnakeActor->LastMoveDirection = EMovementDirection::DOWN; } } } void APlayerPawnBase::HandlePlayerHorizontalImput(float value) { if (IsValid(SnakeActor)) { if (value > 0 && SnakeActor->LastMoveDirection != EMovementDirection::LEFT) { SnakeActor->LastMoveDirection = EMovementDirection::RIGHT; } else if (value < 0 && SnakeActor->LastMoveDirection != EMovementDirection::RIGHT) { SnakeActor->LastMoveDirection = EMovementDirection::LEFT; } } }
[ "anchello@yandex.ru" ]
anchello@yandex.ru
447c0c59a9bd4a00639a1ba66d68e548d1c94105
6de7f1f0d9be7d0659902dc60c77dcaf332e927e
/src/libtsduck/dtv/descriptors/tsTargetSmartcardDescriptor.h
595c17ab8eeffd5a2d25efcbdb455c30ba8488ca
[ "BSD-2-Clause" ]
permissive
ConnectionMaster/tsduck
ed41cd625c894dca96f9b64f7e18cc265ef7f394
32732db5fed5f663dfe68ffb6213a469addc9342
refs/heads/master
2023-08-31T20:01:00.538543
2022-09-30T05:25:02
2022-09-30T08:14:43
183,097,216
1
0
BSD-2-Clause
2023-04-03T23:24:45
2019-04-23T21:15:45
C++
UTF-8
C++
false
false
3,314
h
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2022, Thierry Lelegard // All rights reserved. // // 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. // // 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 OWNER 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. // //---------------------------------------------------------------------------- //! //! @file //! Representation of a target_smartcard_descriptor (INT/UNT specific). //! //---------------------------------------------------------------------------- #pragma once #include "tsAbstractDescriptor.h" #include "tsIPv4Address.h" #include "tsIPUtils.h" namespace ts { //! //! Representation of a target_smartcard_descriptor (INT/UNT specific). //! //! This descriptor cannot be present in other tables than an INT or UNT //! because its tag reuses an MPEG-defined one. //! //! @see ETSI EN 301 192, 8.4.5.5 //! @see ETSI TS 102 006, 9.5.2.1 //! @ingroup descriptor //! class TSDUCKDLL TargetSmartcardDescriptor : public AbstractDescriptor { public: // TargetSmartcardDescriptor public members: uint32_t super_CA_system_id; //!< Super CAS Id, as in DVB SimulCrypt. ByteBlock private_data; //!< Private data bytes. //! //! Default constructor. //! TargetSmartcardDescriptor(); //! //! Constructor from a binary descriptor. //! @param [in,out] duck TSDuck execution context. //! @param [in] bin A binary descriptor to deserialize. //! TargetSmartcardDescriptor(DuckContext& duck, const Descriptor& bin); // Inherited methods DeclareDisplayDescriptor(); protected: // Inherited methods virtual void clearContent() override; virtual void serializePayload(PSIBuffer&) const override; virtual void deserializePayload(PSIBuffer&) override; virtual void buildXML(DuckContext&, xml::Element*) const override; virtual bool analyzeXML(DuckContext&, const xml::Element*) override; }; }
[ "thierry@lelegard.fr" ]
thierry@lelegard.fr
50b81048e62a4bb2f08b91c59a40f47efae62e61
f442f639a567cde56ae5126dce18b944a510ce90
/player_db.cpp
c7628238468decca568d1e3703ff66532261ec46
[]
no_license
TieJu/swtorla
a22b4715933e9c690782e43c809e1acded6ed9b8
dcf2cbd8af6891676640549b430351cd78e8fa36
refs/heads/master
2016-08-02T22:15:58.741909
2013-12-13T11:22:49
2013-12-13T11:22:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include "app.h" void player_db::set_player_name( const std::wstring& name_, string_id id_ ) { ensure_index_is_present( id_ ); if ( is_player_in_db( name_ ) ) { auto old = get_player_id( name_ ); if ( old != id_ ) { _app->remap_player_name( old, id_ ); remove_player_name( old ); } } _players[id_] = name_; }
[ "tiemo.jung@thm.de" ]
tiemo.jung@thm.de
af8b2e49ad29d538bc91a0d9770c331c2588c9d4
7ab3757bde602ebe0b2f9e49d7e1d5f672ee150a
/easyrespacker/src/librespacker/ShapeBuilder.h
8369e261ca4bdb9bb823faced1a538f5d45107e4
[ "MIT" ]
permissive
brucelevis/easyeditor
310dc05084b06de48067acd7ef5d6882fd5b7bba
d0bb660a491c7d990b0dae5b6fa4188d793444d9
refs/heads/master
2021-01-16T18:36:37.012604
2016-08-11T11:25:20
2016-08-11T11:25:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
697
h
#ifndef _EASYRESPACKER_SHAPE_BUILDER_H_ #define _EASYRESPACKER_SHAPE_BUILDER_H_ #include "INodeBuilder.h" #include <map> namespace etexture { class Symbol; } namespace erespacker { class IPackNode; class PackShape; class ShapeBuilder : public INodeBuilder { public: ShapeBuilder(); virtual ~ShapeBuilder(); virtual void Traverse(ee::Visitor& visitor) const; bool CanHandle(const etexture::Symbol* symbol) const; const IPackNode* Create(const etexture::Symbol* symbol); private: void Load(const etexture::Symbol* symbol, PackShape* shape); private: std::map<const etexture::Symbol*, const PackShape*> m_map_data; }; // ShapeBuilder } #endif // _EASYRESPACKER_SHAPE_BUILDER_H_
[ "zhuguang@ejoy.com" ]
zhuguang@ejoy.com
36c23c73350218373751b7eacc1d3f11b46517e2
89ba283b2d655e569f945974c21e12440fb623df
/source/core/event_translators/axis/axis2btns.h
4a781d8fc48bd0c2c9fd83c456c10e9a2ea8b54b
[ "MIT" ]
permissive
swipi-retro/MoltenGamepad
20b35e8e50e2f9400708d278cf11c8bccf02a7fb
b5aebecd3112a65394841e45a27cda4dd9f4a1e8
refs/heads/master
2020-03-22T06:09:06.657599
2018-07-03T17:19:01
2018-07-03T17:19:01
139,614,620
0
0
MIT
2018-07-03T17:10:10
2018-07-03T17:10:09
null
UTF-8
C++
false
false
495
h
#pragma once #include "../event_change.h" class axis2btns : public event_translator { public: int neg_btn; int pos_btn; int neg_cache = 0; int pos_cache = 0; axis2btns(int neg_btn, int pos_btn) : neg_btn(neg_btn), pos_btn(pos_btn) { } virtual void process(struct mg_ev ev, output_slot* out); virtual axis2btns* clone() { return new axis2btns(*this); } static const char* decl; axis2btns(std::vector<MGField>& fields); virtual void fill_def(MGTransDef& def); };
[ "josephgeumlek@gmail.com" ]
josephgeumlek@gmail.com
462b4953ebc6cf88a2acd8e21f98c179dc95dae6
fe5db3014317f062330a6c9fab3e9d941a84689c
/cube2.cpp
30b4b9177e90163dc91cf8738f169c7ff694f381
[]
no_license
mkutlu/ShaderBasedDraws
932b410bbf0771725b9d268bc3c091f1f499d0e1
7898fb33974dee349bc3a25c723d292ee3029e8d
refs/heads/master
2020-12-25T18:53:03.751103
2017-06-12T18:36:57
2017-06-12T18:36:57
94,010,272
0
0
null
null
null
null
UTF-8
C++
false
false
5,382
cpp
// // Display a color cube // // Colors are assigned to each vertex and then the rasterizer interpolates // those colors across the triangles. We us an orthographic projection // as the default projetion. #include "Angel.h" typedef Angel::vec4 color4; typedef Angel::vec4 point4; const int NumVertices = 36; //(6 faces)(2 triangles/face)(3 vertices/triangle) point4 points[NumVertices]; color4 colors[NumVertices]; // Vertices of a unit cube centered at origin, sides aligned with axes point4 vertices[8] = { point4(-0.07, 0.3, 0.5, 1.0), point4( -0.07, -0.3, 0.5, 1.0 ), point4(0.07, -0.3, 0.5, 1.0), point4( 0.07, 0.3, 0.5, 1.0 ), point4(0.07, -0.2, 0.5, 1.0), point4(0.07, -0.3, 0.5, 1.0), point4(0.3, -0.3, 0.5, 1.0), point4(0.3, -0.2, 0.5, 1.0), }; // RGBA olors color4 vertex_colors[1] = { color4( 0.75, 0.75, 0.75, 0.75 ), }; // Array of rotation angles (in degrees) for each coordinate axis enum { Xaxis = 0, Yaxis = 1, Zaxis = 2, NumAxes = 3 }; int Axis = Xaxis; GLfloat Theta[NumAxes] = { 0.0, 0.0, 0.0 }; //---------------------------------------------------------------------------- // quad generates two triangles for each face and assigns colors // to the vertices int Index = 0; void quad( int a, int b, int c, int d ) { colors[Index] = vertex_colors[0]; points[Index] = vertices[a]; Index++; colors[Index] = vertex_colors[0]; points[Index] = vertices[b]; Index++; colors[Index] = vertex_colors[0]; points[Index] = vertices[c]; Index++; colors[Index] = vertex_colors[0]; points[Index] = vertices[a]; Index++; colors[Index] = vertex_colors[0]; points[Index] = vertices[c]; Index++; colors[Index] = vertex_colors[0]; points[Index] = vertices[d]; Index++; } //---------------------------------------------------------------------------- // generate 12 triangles: 36 vertices and 36 colors void colorcube() { quad(0,1,2,3 ); quad(4, 5, 6, 7); } //---------------------------------------------------------------------------- // OpenGL initialization void init() { colorcube(); // Create a vertex array object GLuint vao; glGenVertexArrays( 1, &vao ); glBindVertexArray( vao ); // Create and initialize a buffer object GLuint buffer; glGenBuffers( 1, &buffer ); glBindBuffer( GL_ARRAY_BUFFER, buffer ); glBufferData( GL_ARRAY_BUFFER, sizeof(points) + sizeof(colors), NULL, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(points), points ); glBufferSubData( GL_ARRAY_BUFFER, sizeof(points), sizeof(colors), colors ); // Load shaders and use the resulting shader program GLuint program = InitShader( "vs.glsl", "fs.glsl" ); glUseProgram( program ); // set up vertex arrays GLuint vPosition = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) ); GLuint vColor = glGetAttribLocation( program, "vColor" ); glEnableVertexAttribArray( vColor ); glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(points)) ); glEnable( GL_DEPTH_TEST ); glClearColor( 1.0, 1.0, 1.0, 1.0 ); } //---------------------------------------------------------------------------- void drawL() { mat4 transform = (RotateX(Theta[Xaxis]) * RotateY(Theta[Yaxis]) * RotateZ(Theta[Zaxis])); point4 transformed_points[NumVertices]; for (int i = 0; i < NumVertices; ++i) { transformed_points[i] = points[i]; } glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(transformed_points), transformed_points); glDrawArrays(GL_TRIANGLES, 0, NumVertices); } void display( void ) { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); drawL(); glutSwapBuffers(); } //---------------------------------------------------------------------------- void keyboard( unsigned char key, int x, int y ) { switch( key ) { case 033: // Escape Key case 'q': case 'Q': exit( EXIT_SUCCESS ); break; } } //---------------------------------------------------------------------------- void mouse( int button, int state, int x, int y ) { if ( state == GLUT_DOWN ) { switch( button ) { case GLUT_LEFT_BUTTON: Axis = Xaxis; break; case GLUT_MIDDLE_BUTTON: Axis = Yaxis; break; case GLUT_RIGHT_BUTTON: Axis = Zaxis; break; } } } //---------------------------------------------------------------------------- void timer( int id ) { Theta[Axis] += 0.5; if ( Theta[Axis] > 360.0 ) { Theta[Axis] -= 360.0; } glutTimerFunc(10, timer, 0); glutPostRedisplay(); } //---------------------------------------------------------------------------- int main( int argc, char **argv ) { glutInit( &argc, argv ); #ifdef __APPLE__ glutInitDisplayMode( GLUT_3_2_CORE_PROFILE | GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); #else glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); #endif glutInitWindowSize( 512, 512 ); // glutInitContextVersion( 3, 2 ); // glutInitContextProfile( GLUT_CORE_PROFILE ); glutCreateWindow( "Color Cube" ); glewExperimental = GL_TRUE; glewInit(); init(); glutDisplayFunc( display ); glutKeyboardFunc( keyboard ); glutMouseFunc( mouse ); glutTimerFunc(10, timer, 0); glutMainLoop(); return 0; }
[ "mkutlu13@gmail.com" ]
mkutlu13@gmail.com
2e4bee36b192d11b3a4515b4d9311c5606678953
86ec1329a33c7071267fc973023d988603b74387
/include/Redis.h
68e171e5aad24f226f62266dc2a712d8cbd14f71
[]
no_license
xuaokun/spellCorrect
0a0da9d64c9ed1caf0fb8df311054d960e15c3cd
e29a388d182aa1dffe349b569d78e73486b4807d
refs/heads/master
2020-07-23T08:13:50.058184
2019-09-10T08:56:53
2019-09-10T08:56:53
203,904,051
0
0
null
null
null
null
UTF-8
C++
false
false
1,411
h
#ifndef _REDIS_H_ #define _REDIS_H_ #include <iostream> #include <string.h> #include <string> #include <stdio.h> #include <hiredis/hiredis.h> using std::string; class Redis{ public: Redis() :_connect(nullptr) ,_reply(nullptr) {} ~Redis(){ if(_connect){ redisFree(_connect); } this->_connect=nullptr; this->_reply=nullptr; } bool connect(string host,int port){ this->_connect=redisConnect(host.c_str(),port); if(this->_connect!=NULL && this->_connect->err){ printf("connect error:%s\n",this->_connect->errstr); return 0; } printf("Connect to redisServer Success\n"); return 1; } string get(string key){ this->_reply =(redisReply *)redisCommand(this->_connect,"GET %s",key.c_str()); printf("Succeed to execute command:get %s\n",key.c_str()); if(_reply->type == REDIS_REPLY_NIL){//没有收到任何查询结果 return string("-1"); } string str = this->_reply->str; freeReplyObject(this->_reply); return str; } void set(string key,string value){ redisCommand(this->_connect,"SET %s %s",key.c_str(),value.c_str()); printf("Succeed to execute command:set %s val\n",key.c_str()); } private: redisContext* _connect; redisReply* _reply; }; #endif
[ "xuaokun1997@163.com" ]
xuaokun1997@163.com
23c8ddc8bf56f1d0381e2669faa7cb8f50acf99a
da0513732e6f512975be831bc4ee820ba04b3c19
/chap_2/include/Rifle.h
cce9076b836bf9c4ae64704fcb9e5d7241e08be2
[]
no_license
yepeichu123/design_patterns
6cea819fccc536b2da9a0a28dd8ec75bb96c976c
32bdd014040f08202dee68152e2703ffd348a029
refs/heads/master
2022-12-18T13:32:15.538354
2020-07-30T06:54:13
2020-07-30T06:54:13
282,859,735
0
0
null
null
null
null
UTF-8
C++
false
false
192
h
#ifndef RIFLE_H #define RIFLE_H #include "AbstractGun.h" class CRifle: public CAbstractGun { public: CRifle(); ~CRifle(); void shoot(); }; #endif /* RIFLE_H */
[ "peichu.ye@gmail.com" ]
peichu.ye@gmail.com
621676212529cfc00440025d1a550f09fccf67a8
e11d62362decf103d16b5469a09f0d575bb5ccce
/ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h
7e426b43b21844c7df85202a1e008da6e6426d6b
[ "BSD-3-Clause" ]
permissive
nhiroki/chromium
1e35fd8511c52e66f62e810c2f0aee54a20215c9
e65402bb161a854e42c0140ac1ab3217f39c134e
refs/heads/master
2023-03-13T18:09:40.765227
2019-09-10T06:06:31
2019-09-10T06:06:31
207,478,927
0
0
BSD-3-Clause
2019-09-10T06:12:21
2019-09-10T06:12:20
null
UTF-8
C++
false
false
6,551
h
// Copyright 2018 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. #ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_ #define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_ #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "ui/aura/window_tree_host_platform.h" #include "ui/views/views_export.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host.h" namespace views { class WindowEventFilter; class VIEWS_EXPORT DesktopWindowTreeHostPlatform : public aura::WindowTreeHostPlatform, public DesktopWindowTreeHost { public: DesktopWindowTreeHostPlatform( internal::NativeWidgetDelegate* native_widget_delegate, DesktopNativeWidgetAura* desktop_native_widget_aura); ~DesktopWindowTreeHostPlatform() override; // DesktopWindowTreeHost: void Init(const Widget::InitParams& params) override; void OnNativeWidgetCreated(const Widget::InitParams& params) override; void OnWidgetInitDone() override; void OnActiveWindowChanged(bool active) override; std::unique_ptr<corewm::Tooltip> CreateTooltip() override; std::unique_ptr<aura::client::DragDropClient> CreateDragDropClient( DesktopNativeCursorManager* cursor_manager) override; void Close() override; void CloseNow() override; aura::WindowTreeHost* AsWindowTreeHost() override; void Show(ui::WindowShowState show_state, const gfx::Rect& restore_bounds) override; bool IsVisible() const override; void SetSize(const gfx::Size& size) override; void StackAbove(aura::Window* window) override; void StackAtTop() override; void CenterWindow(const gfx::Size& size) override; void GetWindowPlacement(gfx::Rect* bounds, ui::WindowShowState* show_state) const override; gfx::Rect GetWindowBoundsInScreen() const override; gfx::Rect GetClientAreaBoundsInScreen() const override; gfx::Rect GetRestoredBounds() const override; std::string GetWorkspace() const override; gfx::Rect GetWorkAreaBoundsInScreen() const override; void SetShape(std::unique_ptr<Widget::ShapeRects> native_shape) override; void Activate() override; void Deactivate() override; bool IsActive() const override; void Maximize() override; void Minimize() override; void Restore() override; bool IsMaximized() const override; bool IsMinimized() const override; bool HasCapture() const override; void SetZOrderLevel(ui::ZOrderLevel order) override; ui::ZOrderLevel GetZOrderLevel() const override; void SetVisibleOnAllWorkspaces(bool always_visible) override; bool IsVisibleOnAllWorkspaces() const override; bool SetWindowTitle(const base::string16& title) override; void ClearNativeFocus() override; Widget::MoveLoopResult RunMoveLoop( const gfx::Vector2d& drag_offset, Widget::MoveLoopSource source, Widget::MoveLoopEscapeBehavior escape_behavior) override; void EndMoveLoop() override; void SetVisibilityChangedAnimationsEnabled(bool value) override; NonClientFrameView* CreateNonClientFrameView() override; bool ShouldUseNativeFrame() const override; bool ShouldWindowContentsBeTransparent() const override; void FrameTypeChanged() override; void SetFullscreen(bool fullscreen) override; bool IsFullscreen() const override; void SetOpacity(float opacity) override; void SetAspectRatio(const gfx::SizeF& aspect_ratio) override; void SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) override; void InitModalType(ui::ModalType modal_type) override; void FlashFrame(bool flash_frame) override; bool IsAnimatingClosed() const override; bool IsTranslucentWindowOpacitySupported() const override; void SizeConstraintsChanged() override; bool ShouldUpdateWindowTransparency() const override; bool ShouldUseDesktopNativeCursorManager() const override; bool ShouldCreateVisibilityController() const override; // WindowTreeHost: gfx::Transform GetRootTransform() const override; // PlatformWindowDelegateBase: void DispatchEvent(ui::Event* event) override; void OnClosed() override; void OnWindowStateChanged(ui::PlatformWindowState new_state) override; void OnCloseRequest() override; void OnActivationChanged(bool active) override; base::Optional<gfx::Size> GetMinimumSizeForWindow() override; base::Optional<gfx::Size> GetMaximumSizeForWindow() override; protected: // TODO(https://crbug.com/990756): move these methods back to private // once DWTHX11 stops using them. internal::NativeWidgetDelegate* native_widget_delegate() { return native_widget_delegate_; } DesktopNativeWidgetAura* desktop_native_widget_aura() { return desktop_native_widget_aura_; } // Accessor for DesktopNativeWidgetAura::content_window(). aura::Window* content_window(); // These are not general purpose methods and must be used with care. Please // make sure you understand the rounding direction before using. gfx::Rect ToDIPRect(const gfx::Rect& rect_in_pixels) const; gfx::Rect ToPixelRect(const gfx::Rect& rect_in_dip) const; private: FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformTest, HitTest); void Relayout(); void RemoveNonClientEventFilter(); Widget* GetWidget(); const Widget* GetWidget() const; // There are platform specific properties that Linux may want to add. virtual void AddAdditionalInitProperties( const Widget::InitParams& params, ui::PlatformWindowInitProperties* properties); internal::NativeWidgetDelegate* const native_widget_delegate_; DesktopNativeWidgetAura* const desktop_native_widget_aura_; bool is_active_ = false; base::string16 window_title_; // We can optionally have a parent which can order us to close, or own // children who we're responsible for closing when we CloseNow(). DesktopWindowTreeHostPlatform* window_parent_ = nullptr; std::set<DesktopWindowTreeHostPlatform*> window_children_; #if defined(OS_LINUX) // A handler for events intended for non client area. std::unique_ptr<WindowEventFilter> non_client_window_event_filter_; #endif base::WeakPtrFactory<DesktopWindowTreeHostPlatform> close_widget_factory_{ this}; base::WeakPtrFactory<DesktopWindowTreeHostPlatform> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DesktopWindowTreeHostPlatform); }; } // namespace views #endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
5bb5b2f90e8a4eed3dfc8c788fbad3bdb9a37c11
d065109ae84eeda9ad64bd8fb1c4176c85730954
/magician.cpp
0a4fdb10563fba8270aa880d9a22444b3262396f
[]
no_license
liuke0002/BasicAlgorithm
31e79209a948ece98e7e54aaa6af3c0a60730331
df62d9954486ae0f25ff425435840817bd86f0ac
refs/heads/master
2021-01-10T08:12:19.121080
2017-09-27T15:05:10
2017-09-27T15:05:10
54,707,237
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
862
cpp
#include<stdio.h> #include<stdlib.h> #define CardNumber 13 typedef struct node{ int data; struct node *next; }node; node *createLinkList(){ node *head,*p; node *s; int i; head=(node*)malloc(sizeof(node)); p=head; for(i=0;i<CardNumber;i++){ s=(node*)malloc(sizeof(node)); s->data=0; p->next=s; p=s; } s->next=head->next; free(head); return s->next; } void margician(node *head){ node *p; int j; int countNumber=2; p=head; p->data=1; while(1){ for(j=0;j<countNumber;j++){ p=p->next; if(p->data!=0){//¸ÃλÖÃÓÐÅÆ p->next; j--; } } if(p->data==0){ p->data=countNumber; countNumber++; if(countNumber==14){ break; } } } } int main(){ node *p=createLinkList(); margician(p); int i; for(i=1;i<CardNumber;i++){ printf("%d->",p->data); p=p->next; } printf("%d\n",p->data); return 0; }
[ "1395674569@qq.com" ]
1395674569@qq.com
1e7eef25e1e50dbf48594241a544445bf203aa1c
d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3
/Modules/Core/Common/include/itkTreeIteratorClone.h
47bcafc6a92a3271a6c4791048fbb4003e1833b4
[ "SMLNJ", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NTP", "IJG", "GPL-1.0-or-later", "libtiff", "BSD-4.3TAHOE", "...
permissive
nalinimsingh/ITK_4D
18e8929672df64df58a6446f047e6ec04d3c2616
95a2eacaeaffe572889832ef0894239f89e3f303
refs/heads/master
2020-03-17T18:58:50.953317
2018-10-01T20:46:43
2018-10-01T21:21:01
133,841,430
0
0
Apache-2.0
2018-05-17T16:34:54
2018-05-17T16:34:53
null
UTF-8
C++
false
false
4,725
h
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkTreeIteratorClone_h #define itkTreeIteratorClone_h #include "itkMacro.h" #include <iostream> namespace itk { /** \class itkTreeIteratorClone * \brief itkTreeIteratorClone class * \ingroup DataRepresentation * \ingroup ITKCommon */ template< typename TObjectType > class TreeIteratorClone { public: /** Typedefs */ typedef TreeIteratorClone< TObjectType > Self; typedef TObjectType ObjectType; /** Constructor */ TreeIteratorClone () { m_Pointer = 0; } /** Copy constructor */ TreeIteratorClone (const TreeIteratorClone< ObjectType > & p) { m_Pointer = ITK_NULLPTR; if ( p.m_Pointer != ITK_NULLPTR ) { m_Pointer = p.m_Pointer->Clone(); } } /** Constructor to pointer p */ TreeIteratorClone (ObjectType *p) { m_Pointer = 0; if ( p != ITK_NULLPTR ) { m_Pointer = p->Clone(); } } /** Constructor to reference p */ TreeIteratorClone (const ObjectType & p) { m_Pointer = ITK_NULLPTR; m_Pointer = const_cast< ObjectType * >( &p )->Clone(); } /** Destructor */ ~TreeIteratorClone () { delete m_Pointer; m_Pointer = ITK_NULLPTR; } /** Overload operator -> */ ObjectType * operator->() const { return m_Pointer; } /** Test if the pointer has been initialized */ bool IsNotNull() const { return m_Pointer != 0; } bool IsNull() const { return m_Pointer == 0; } /** Template comparison operators. */ template< typename TR > bool operator==(TR r) const { return ( m_Pointer == (ObjectType *)( r ) ); } template< typename TR > bool operator!=(TR r) const { return ( m_Pointer != (ObjectType *)( r ) ); } /** Access function to pointer. */ ObjectType * GetPointer() const { return m_Pointer; } /** Comparison of pointers. Less than comparison. */ bool operator<(const TreeIteratorClone & r) const { return (void *)m_Pointer < (void *)r.m_Pointer; } /** Comparison of pointers. Greater than comparison. */ bool operator>(const TreeIteratorClone & r) const { return (void *)m_Pointer > (void *)r.m_Pointer; } /** Comparison of pointers. Less than or equal to comparison. */ bool operator<=(const TreeIteratorClone & r) const { return (void *)m_Pointer <= (void *)r.m_Pointer; } /** Comparison of pointers. Greater than or equal to comparison. */ bool operator>=(const TreeIteratorClone & r) const { return (void *)m_Pointer >= (void *)r.m_Pointer; } /** Overload operator assignment. */ TreeIteratorClone & operator=(const TreeIteratorClone & r) { return this->operator=( r.GetPointer() ); } /** Overload operator assignment. */ TreeIteratorClone & operator=(const ObjectType *r) { if ( m_Pointer != r ) { delete m_Pointer; m_Pointer = ITK_NULLPTR; if ( r != ITK_NULLPTR ) { m_Pointer = const_cast< ObjectType * >( r )->Clone(); } } return *this; } Self & operator++() { if ( m_Pointer ) { ++( *m_Pointer ); } return *this; } const Self operator++(int) { if ( m_Pointer ) { const Self oldValue(m_Pointer); // create a copy of the iterator behind // the pointer (Clone()) ++( *m_Pointer ); return oldValue; } } /** Function to print object pointed to */ ObjectType * Print(std::ostream & os) const { // This prints the object pointed to by the pointer ( *m_Pointer ).Print(os); return m_Pointer; } private: /** The pointer to the object referred to by this smart pointer. */ ObjectType *m_Pointer; }; template< typename T > std::ostream & operator<<(std::ostream & os, TreeIteratorClone< T > p) { p.Print(os); return os; } } // end namespace itk #endif
[ "ruizhi@csail.mit.edu" ]
ruizhi@csail.mit.edu
67678978cd39ab2bbe4e1508900be073fb0a6f8d
dbddebd6eb0ed34104acb254da81fc643c01a4ca
/ros/devel/include/styx_msgs/TrafficLight.h
06c45173a2543ba0a7550b4f51346694c3ced9d7
[ "MIT" ]
permissive
arpitsri3/CarND_Capstone_Code
4eba922f7c8ccc3a01aff520934b39d1736520e6
2824a14c6fc3992123d5189187c5c8c85f58c9fd
refs/heads/master
2020-03-19T05:57:27.860271
2018-06-06T09:32:41
2018-06-06T09:32:41
135,978,409
0
1
null
null
null
null
UTF-8
C++
false
false
7,513
h
// Generated by gencpp from file styx_msgs/TrafficLight.msg // DO NOT EDIT! #ifndef STYX_MSGS_MESSAGE_TRAFFICLIGHT_H #define STYX_MSGS_MESSAGE_TRAFFICLIGHT_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> #include <geometry_msgs/PoseStamped.h> namespace styx_msgs { template <class ContainerAllocator> struct TrafficLight_ { typedef TrafficLight_<ContainerAllocator> Type; TrafficLight_() : header() , pose() , state(0) { } TrafficLight_(const ContainerAllocator& _alloc) : header(_alloc) , pose(_alloc) , state(0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef ::geometry_msgs::PoseStamped_<ContainerAllocator> _pose_type; _pose_type pose; typedef uint8_t _state_type; _state_type state; enum { UNKNOWN = 4u, GREEN = 2u, YELLOW = 1u, RED = 0u, }; typedef boost::shared_ptr< ::styx_msgs::TrafficLight_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::styx_msgs::TrafficLight_<ContainerAllocator> const> ConstPtr; }; // struct TrafficLight_ typedef ::styx_msgs::TrafficLight_<std::allocator<void> > TrafficLight; typedef boost::shared_ptr< ::styx_msgs::TrafficLight > TrafficLightPtr; typedef boost::shared_ptr< ::styx_msgs::TrafficLight const> TrafficLightConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::styx_msgs::TrafficLight_<ContainerAllocator> & v) { ros::message_operations::Printer< ::styx_msgs::TrafficLight_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace styx_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'styx_msgs': ['/home/workspace/CarND_Capstone_Code/ros/src/styx_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::styx_msgs::TrafficLight_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::styx_msgs::TrafficLight_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::styx_msgs::TrafficLight_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::styx_msgs::TrafficLight_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::styx_msgs::TrafficLight_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::styx_msgs::TrafficLight_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::styx_msgs::TrafficLight_<ContainerAllocator> > { static const char* value() { return "444a7e648c334df4cc0678bcfbd971da"; } static const char* value(const ::styx_msgs::TrafficLight_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x444a7e648c334df4ULL; static const uint64_t static_value2 = 0xcc0678bcfbd971daULL; }; template<class ContainerAllocator> struct DataType< ::styx_msgs::TrafficLight_<ContainerAllocator> > { static const char* value() { return "styx_msgs/TrafficLight"; } static const char* value(const ::styx_msgs::TrafficLight_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::styx_msgs::TrafficLight_<ContainerAllocator> > { static const char* value() { return "Header header\n\ geometry_msgs/PoseStamped pose\n\ uint8 state\n\ \n\ uint8 UNKNOWN=4\n\ uint8 GREEN=2\n\ uint8 YELLOW=1\n\ uint8 RED=0\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/PoseStamped\n\ # A Pose with reference coordinate frame and timestamp\n\ Header header\n\ Pose pose\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Pose\n\ # A representation of pose in free space, composed of position and orientation. \n\ Point position\n\ Quaternion orientation\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Quaternion\n\ # This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w\n\ "; } static const char* value(const ::styx_msgs::TrafficLight_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::styx_msgs::TrafficLight_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.pose); stream.next(m.state); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct TrafficLight_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::styx_msgs::TrafficLight_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::styx_msgs::TrafficLight_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "pose: "; s << std::endl; Printer< ::geometry_msgs::PoseStamped_<ContainerAllocator> >::stream(s, indent + " ", v.pose); s << indent << "state: "; Printer<uint8_t>::stream(s, indent + " ", v.state); } }; } // namespace message_operations } // namespace ros #endif // STYX_MSGS_MESSAGE_TRAFFICLIGHT_H
[ "i.arpitsri@gmail.com" ]
i.arpitsri@gmail.com
f6bd926660705a781e82078ade25abaa29e6e3e4
f8b56b711317fcaeb0fb606fb716f6e1fe5e75df
/Internal/SDK/BP_FishingFish_AncientScale_05_Colour_02_Sapphire_classes.h
0936daf43fc17391e41695cf0caa46b123fb6db3
[]
no_license
zanzo420/SoT-SDK-CG
a5bba7c49a98fee71f35ce69a92b6966742106b4
2284b0680dcb86207d197e0fab6a76e9db573a48
refs/heads/main
2023-06-18T09:20:47.505777
2021-07-13T12:35:51
2021-07-13T12:35:51
385,600,112
0
0
null
2021-07-13T12:42:45
2021-07-13T12:42:44
null
UTF-8
C++
false
false
949
h
#pragma once // Name: Sea of Thieves, Version: 2.2.0.2 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_FishingFish_AncientScale_05_Colour_02_Sapphire.BP_FishingFish_AncientScale_05_Colour_02_Sapphire_C // 0x0000 (FullSize[0x0910] - InheritedSize[0x0910]) class ABP_FishingFish_AncientScale_05_Colour_02_Sapphire_C : public ABP_FishingFish_AncientScale_05_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_FishingFish_AncientScale_05_Colour_02_Sapphire.BP_FishingFish_AncientScale_05_Colour_02_Sapphire_C"); return ptr; } void UserConstructionScript(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
b0d49f17931cf066425441ef6e2b0fce63233454
bdaa8f6fa3627232dd8129499b7603f1e30647e9
/Login_ConnectDataBase/Login_ConnectDataBase/ChangeCode.h
f14687ca42b716af2839cbe1d7d8fb58dc9fb437
[]
no_license
tianyunzqs/C_C_plus_plus_algorithm
3e5b8258af86c8b8b95e3c6a1a879f70478f68e8
d4e95e33129865f1baf4eefdbc996ac59882141e
refs/heads/master
2020-12-02T05:24:43.977114
2017-07-11T13:41:46
2017-07-11T13:41:46
96,889,940
2
0
null
null
null
null
GB18030
C++
false
false
479
h
#pragma once // CChangeCode 对话框 class CChangeCode : public CDialog { DECLARE_DYNAMIC(CChangeCode) public: CChangeCode(CWnd* pParent = NULL); // 标准构造函数 virtual ~CChangeCode(); // 对话框数据 enum { IDD = IDD_CHANGECODE }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedFinishchange(); afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); };
[ "tianyunzqs@sina.com" ]
tianyunzqs@sina.com
290b63702b731ec513028e85b9913ab623bd0a27
1810a26cd8db1da2263889067d93a48750dcb50a
/any.cpp
6955aa688b94aa9b7e93fa39dd147df49964d093
[]
no_license
spurnaye/cpp_algorithms
4f63e559c94b1b3b30c32105a3cb17cac85f598f
87fe47a24a7e80d31cb55a30dd0dcf0c91d3bc1a
refs/heads/master
2020-03-08T02:04:49.650375
2018-10-22T04:22:03
2018-10-22T04:22:03
127,849,116
1
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
#include <any> #include <iostream> #include <vector> int main(){ std::any a = 1; std::vector<std::any> v{1,2,3,4.5,6.7,"some string"}; auto x = std::any_cast<float>(v[0]); }
[ "spurnaye@gmail.com" ]
spurnaye@gmail.com
67c9d453adb00745905766ae9048094df455c4bc
5db5ddf10fb0b71f1fd19cb93f874f7e539e33eb
/Tech/src/foundation/modules/event/peventmanager.cpp
ac97e0670c7582a5917c4e54de6751964da99777
[]
no_license
softwarekid/FutureInterface
13b290435c552a3feca0f97ecd930aa05fa2fb25
55583a58297a5e265953c36c72f41ccb8bac3015
refs/heads/master
2020-04-08T04:42:21.041081
2014-07-25T01:14:34
2014-07-25T01:14:34
22,280,531
0
1
null
null
null
null
UTF-8
C++
false
false
2,741
cpp
// peventmanager.cpp // The event manager // // Copyright 2012 - 2014 by Future Interface. // This software is licensed under the terms of the MIT license. // // Hongwei Li lihw81@gmail.com // // #include "peventmanager.h" #include <PFoundation/pevent.h> #include <PFoundation/pcontext.h> #include <PFoundation//pobject.h> #include <PFoundation/pclock.h> PEventManager::PEventManager(PContext *context) : PModule("event-manager", context) { } PEventManager::~PEventManager() { PList<PEvent *>::iterator it; PList<PEvent *>::iterator ib = m_queue.begin(); PList<PEvent *>::iterator ie = m_queue.end(); for (it = ib; it != ie; ++it) { PDELETE(*it); } m_queue.clear(); } void PEventManager::update() { puint32 deltaTime = (puint32)m_context->clock().systemDeltaTime(); // The deltaTime is the elapsed time from last frame, so each event should // update its timer in this function so that it approaches the firing stage // gradually. The correct logic should be // // Step 1. update times of all queued events PList<PEvent *>::iterator it; PList<PEvent *>::iterator ib = m_queue.begin(); PList<PEvent *>::iterator ie = m_queue.end(); for (it = ib; it != ie; ++it) { if ((*it)->m_fireTime < deltaTime) { (*it)->m_fireTime = 0; } else { (*it)->m_fireTime -= pMin((*it)->m_fireTime, deltaTime); } } // Step 2. fire those events on due in the order of the fire time. it = ib; while (it != ie) { if ((*it)->canFire()) { PEvent *event = *it; fire(event); m_queue.erase(it); // FIXME: it can't be right to reset the iterator // to the head of list. Those nodes already visited // will be checked again. It seems to me we need to have a dedicated // event queue data structure instead of using qlist. it = m_queue.begin(); recycelEvent(event); } else { ++it; } } } void PEventManager::queueEvent(PEvent *event) { m_queue.append(event); } void PEventManager::fire(PEvent *event) { event->m_handled = true; if (event->m_receiver == P_NULL) { m_context->dispatch(event); } else { event->m_receiver->onEvent(event); } } PEvent * PEventManager::createEvent(PEventTypeEnum type, PObject *sender) { // TODO: a memory pool. PEvent *ret = PNEW(PEvent(type, sender, m_context->clock().timestamp(), this)); return ret; } void PEventManager::recycelEvent(PEvent *event) { // TODO: recycle the event memory. PDELETE(event); }
[ "lihw81@gmail.com" ]
lihw81@gmail.com
52f7f33ba90ecb9be6b17eb32350559ce7acfaeb
50ada458f964ade9515b8405fc75ac0ed42ca3cd
/Level 1/Section 1.5/Exercise 1/Exercise 1/Exercise 1.cpp
8e0a7e8741f7a20779c994dec9b384b8468a85de
[]
no_license
CPP-Muggle/C_Github
f7a224ee61cd98c5b3ae1142bc4956f44334622e
e860fe3c189c1821f93c7c6d6bea2d82ec60a089
refs/heads/master
2021-01-01T19:37:44.414099
2015-11-28T16:30:56
2015-11-28T16:30:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
276
cpp
#include <stdio.h> float minus(float a, float b){ return a - b; } void main(){ float a, b; printf("Enter the first number "); scanf_s("%f", &a); printf("Enter the second number "); scanf_s("%f", &b); printf("The difference between two numbers is %.4f", minus(a, b)); }
[ "jz2631@columbia.edu" ]
jz2631@columbia.edu
76c7f0199fe875a62ecfc0d1f5263b5d5bfb92af
2348000ede440b3513010c29a154ca70b22eb88e
/src/CPP/src/pratice/ReverseWordsInAString.cpp
ea103cf7c69443a4b5fc68e39dde58502fd01294
[]
no_license
ZhenyingZhu/ClassicAlgorithms
76438e02ecc813b75646df87f56d9588ffa256df
86c90c23ea7ed91e8ce5278f334f0ce6e034a38c
refs/heads/master
2023-08-27T20:34:18.427614
2023-08-25T06:08:00
2023-08-25T06:08:00
24,016,875
2
1
null
null
null
null
UTF-8
C++
false
false
1,496
cpp
#include <iostream> using namespace std; // [Source]: https://leetcode.com/problems/reverse-words-in-a-string/ // http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=212481 class Solution { public: void reverseWords(string &s) { if (s.empty()) return; removeTrailingSpaces(s); int st = 0; for (int i = 0; i < (int)s.length(); ++i) { if (s[i] == ' ') { reverse(s, st, i - 1); st = i + 1; } } reverse(s, st, s.length() - 1); reverse(s, 0, s.length() - 1); } void removeTrailingSpaces(string &s) { int len = s.length(); // move pointer to first non space char int run = 0; while (run < len && s[run] == ' ') ++run; // copy characters to previous slots int cur = 0; while (run < len) { if (s[run] != ' ') s[cur++] = s[run++]; else if (s[cur - 1] != ' ') // first char must not space s[cur++] = s[run++]; else ++run; } // the last char might be a space if (cur > 0 && s[cur - 1] == ' ') --cur; s.erase(cur); } void reverse(string &s, int st, int ed) { while (st < ed) { swap(s[st++], s[ed--]); } } }; int main() { Solution sol; string s = " "; sol.reverseWords(s); cout << s << "|" << endl; }
[ "zz2283@columbia.edu" ]
zz2283@columbia.edu
7d0439776dfbc40b8079872a3030ee1ae91f9b0b
55c81da8a1d0e98fe426b7b5c3ce7a9646ffdbe8
/samples/Test/Classes/CDNewsViewController.cpp
58cce061bc006658ab286accd2c85e63b901b5e3
[]
no_license
babyliynfg/nano-CrossApp
e40c1b209e30b47bea588b981f4f15aedc638266
e0c0e45c500d2647d330131b68474b67f0dfaae2
refs/heads/master
2021-01-18T03:04:08.540737
2017-03-14T03:47:06
2017-03-14T03:47:06
68,501,961
38
23
null
null
null
null
UTF-8
C++
false
false
18,542
cpp
// // CDNewsViewController.cpp // Test // // Created by renhongguang on 15/4/16. // // #include "CDNewsViewController.h" #include "CDWebViewController.h" extern int page_index; float temp_time = 0; CDNewsTableCell::CDNewsTableCell() :theTitle(NULL), theDesc(NULL), theImage(NULL) { this->setAllowsSelected(false); } CDNewsTableCell::~CDNewsTableCell() { } CDNewsTableCell* CDNewsTableCell::create(const std::string& identifier) { CCLog("CDNewsTableCell"); CDNewsTableCell* tableViewCell = new CDNewsTableCell(); if(tableViewCell&&tableViewCell->initWithReuseIdentifier(identifier)) { tableViewCell->autorelease(); return tableViewCell; } CC_SAFE_DELETE(tableViewCell); return NULL; } void CDNewsTableCell::highlightedTableViewCell() { this->setBackgroundView(CAView::createWithColor(ccc4(0, 0, 0, 64))); } void CDNewsTableCell::selectedTableViewCell() { this->setBackgroundView(CAView::createWithColor(ccc4(0, 0, 0, 64))); } bool CDNewsTableCell::initWithReuseIdentifier(const std::string& reuseIdentifier) { if (!CATableViewCell::initWithReuseIdentifier(reuseIdentifier)) { return false; } theImage = CommonUrlImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(20, 200), DVerticalLayout_T_B(20, 20))); theImage->setTag(101); theImage->setImageViewScaleType(CAImageViewScaleTypeFitImageCrop); theImage->setImage(CAImage::create("image/HelloWorld.png")); this->getContentView()->addSubview(theImage); theTitle = CALabel::createWithLayout(DLayout(DHorizontalLayout_L_R(240, 150), DVerticalLayout_T_H(20, 40))); theTitle->setColor(CAColor_black); theTitle->setTextAlignment(CATextAlignmentLeft); theTitle->setVerticalTextAlignmet(CAVerticalTextAlignmentTop); theTitle->setFontSize(32); theTitle->setTag(100); this->getContentView()->addSubview(theTitle); theDesc = CALabel::createWithLayout(DLayout(DHorizontalLayout_L_R(240, 150), DVerticalLayout_T_H(65, 40))); theDesc->setColor(CAColor_black); theDesc->setTextAlignment(CATextAlignmentLeft); theDesc->setVerticalTextAlignmet(CAVerticalTextAlignmentTop); theDesc->setFontSize(24); theDesc->setTag(102); theDesc->setColor(CAColor_gray); theDesc->setLineSpacing(10); this->getContentView()->addSubview(theDesc); return true; } void CDNewsTableCell::setModel(const newsMsg &cellmodel) { theImage->setImage(CAImage::create("image/HelloWorld.png")); theImage->setUrl(cellmodel.m_imageUrl); theTitle->setText(cellmodel.m_title); theDesc->setText(cellmodel.m_desc); } CDNewsViewController::CDNewsViewController(int index) :p_PageView(NULL) ,p_TableView(NULL) ,p_pLoading(NULL) ,p_section(1) { urlID = index; m_msg.clear(); } CDNewsViewController::~CDNewsViewController() { } string CDNewsViewController::getSign(std::map<std::string,std::string> key_value) { string appsecret = "c174cb1fda3491285be953998bb867a0"; string tempStr = ""; std::map<std::string,std::string>::iterator itr; for (itr=key_value.begin(); itr!=key_value.end(); itr++) { tempStr = tempStr+itr->first+itr->second; } tempStr = appsecret+tempStr+appsecret; CCLog("tempStr===%s",tempStr.c_str()); string sign = MD5(tempStr).md5(); for(int i=0;i<sign.length();i++) { if(sign[i]>='a'&&sign[i]<='z') sign[i]-=32; else if (sign[i]>='A'&&sign[i]<='Z')sign[i]+=32; } return sign; } void CDNewsViewController::viewDidLoad() { if (m_msg.empty()) { std::map<std::string, std::string> key_value; key_value["tag"] = menuTag[urlID]; key_value["page"]= "1"; key_value["limit"]= "20"; key_value["appid"]="10000"; key_value["sign_method"]="md5"; string tempSign = getSign(key_value); CCLog("sign===%s",tempSign.c_str()); key_value["sign"] = tempSign; string tempUrl = "http://api.9miao.com/news/"; CommonHttpManager::getInstance()->send_post(tempUrl, key_value, this, CommonHttpJson_selector(CDNewsViewController::onRequestFinished)); p_pLoading = CAActivityIndicatorView::createWithLayout(DLayoutFill); this->getView()->insertSubview(p_pLoading, CAWindowZOrderTop); p_pLoading->setLoadingMinTime(0.5f); p_pLoading->setTargetOnCancel(this, callfunc_selector(CDNewsViewController::initNewsTableView)); } else { this->initNewsTableView(); } } void CDNewsViewController::showAlert() { if (p_alertView) { this->getView()->removeSubview(p_alertView); p_alertView= NULL; } p_alertView = CAView::createWithFrame(this->getView()->getBounds()); this->getView()->addSubview(p_alertView); CAImageView* bg = CAImageView::createWithLayout(DLayoutFill); bg->setImageViewScaleType(CAImageViewScaleTypeFitImageCrop); bg->setImage(CAImage::create("image/HelloWorld.png")); CAButton* btn5 = CAButton::create(CAButtonTypeSquareRect); btn5->setTag(100); btn5->setLayout(DLayoutFill); btn5->setTitleColorForState(CAControlStateNormal,CAColor_white); btn5->setBackgroundViewForState(CAControlStateNormal, bg); btn5->setBackgroundViewForState(CAControlStateHighlighted, bg); btn5->addTarget(this, CAControl_selector(CDNewsViewController::buttonCallBack), CAControlEventTouchUpInSide); p_alertView->addSubview(btn5); CALabel* test = CALabel::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(100, 40))); test->setColor(CAColor_gray); test->setTextAlignment(CATextAlignmentCenter); test->setVerticalTextAlignmet(CAVerticalTextAlignmentTop); test->setFontSize(24); test->setText("网络不给力,请点击屏幕重新加载~"); p_alertView->addSubview(test); } void CDNewsViewController::buttonCallBack(CAControl* btn,DPoint point) { this->getView()->removeSubview(p_alertView); p_alertView = NULL; std::map<std::string, std::string> key_value; key_value["tag"] = menuTag[urlID]; key_value["page"]= "1"; key_value["limit"]= "20"; key_value["appid"]="10000"; key_value["sign_method"]="md5"; string tempSign = getSign(key_value); CCLog("sign===%s",tempSign.c_str()); key_value["sign"] = tempSign; string tempUrl = "http://api.9miao.com/news/"; CommonHttpManager::getInstance()->send_post(tempUrl, key_value, this, CommonHttpJson_selector(CDNewsViewController::onRequestFinished)); { p_pLoading = CAActivityIndicatorView::createWithLayout(DLayoutFill); this->getView()->insertSubview(p_pLoading, CAWindowZOrderTop); p_pLoading->setLoadingMinTime(0.5f); p_pLoading->setTargetOnCancel(this, callfunc_selector(CDNewsViewController::initNewsTableView)); } } void CDNewsViewController::onRequestFinished(const HttpResponseStatus& status, const CSJson::Value& json) { if (status == HttpResponseSucceed) { const CSJson::Value& value = json["result"]; int length = value.size(); m_msg.clear(); m_page.clear(); for (int i=0; i<3; i++) { newsPage temp_page; temp_page.m_title = value[i]["title"].asString(); temp_page.m_pic = value[i]["image"].asString(); temp_page.m_url = value[i]["url"].asString(); m_page.push_back(temp_page); } for (int index = 3; index < length; index++) { newsMsg temp_msg; temp_msg.m_title = value[index]["title"].asString(); temp_msg.m_desc = value[index]["desc"].asString(); temp_msg.m_url = value[index]["url"].asString(); temp_msg.m_imageUrl = value[index]["image"].asString(); m_msg.push_back(temp_msg); } } CATabBarController* tabBarController = this->getTabBarController(); for (int i=0; i<5; i++) { CDNewsViewController* catalog = dynamic_cast<CDNewsViewController*>(tabBarController->getViewControllerAtIndex(i)); if (catalog && catalog->p_pLoading) { catalog->p_pLoading->stopAnimating(); } } if (p_TableView) { p_TableView->reloadData(); } } void CDNewsViewController::onRefreshRequestFinished(const HttpResponseStatus& status, const CSJson::Value& json) { if (status == HttpResponseSucceed) { const CSJson::Value& value = json["result"]; int length = value.size(); for (int index = 0; index < length; index++) { newsMsg temp_msg; temp_msg.m_title = value[index]["title"].asString(); temp_msg.m_desc = value[index]["desc"].asString(); temp_msg.m_url = value[index]["url"].asString(); temp_msg.m_imageUrl = value[index]["image"].asString(); m_msg.push_back(temp_msg); } } do { CC_BREAK_IF(p_pLoading == NULL); if (p_pLoading->isAnimating()) { p_pLoading->stopAnimating(); } else { p_TableView->reloadData(); } } while (0); } void CDNewsViewController::initNewsTableView() { if (m_page.empty()) { showAlert(); return; } if (p_TableView!=NULL) { this->getView()->removeSubview(p_TableView); p_TableView = NULL; } p_TableView= CATableView::createWithLayout(DLayoutFill); p_TableView->setTableViewDataSource(this); p_TableView->setTableViewDelegate(this); p_TableView->setScrollViewDelegate(this); p_TableView->setAllowsSelection(true); this->getView()->addSubview(p_TableView); CAPullToRefreshView *refreshDiscount = CAPullToRefreshView::create(CAPullToRefreshView::CAPullToRefreshTypeFooter); refreshDiscount->setLabelColor(CAColor_black); CAPullToRefreshView *refreshDiscount1 = CAPullToRefreshView::create(CAPullToRefreshView::CAPullToRefreshTypeHeader); refreshDiscount1->setLabelColor(CAColor_black); p_TableView->setFooterRefreshView(refreshDiscount); p_TableView->setHeaderRefreshView(refreshDiscount1); initNewsPageView(); } void CDNewsViewController::initNewsPageView() { //初始化pageView CAView* tempview = CAView::create(); p_TableView->setTableHeaderView(tempview); p_TableView->setTableHeaderHeight(360); CAVector<CAView* > viewList; CommonUrlImageView* temImage0 = CommonUrlImageView::createWithImage(CAImage::create("image/HelloWorld.png")); temImage0->setImageViewScaleType(CAImageViewScaleTypeFitImageCrop); temImage0->setUrl(m_page[m_page.size()-1].m_pic); viewList.pushBack(temImage0); for (int i=0; i<m_page.size(); i++) { //初始化viewList CommonUrlImageView* temImage = CommonUrlImageView::createWithImage(CAImage::create("image/HelloWorld.png")); temImage->setImageViewScaleType(CAImageViewScaleTypeFitImageCrop); temImage->setUrl(m_page[i].m_pic); viewList.pushBack(temImage); } CommonUrlImageView* temImage1 = CommonUrlImageView::createWithImage(CAImage::create("image/HelloWorld.png")); temImage1->setImageViewScaleType(CAImageViewScaleTypeFitImageCrop); temImage1->setUrl(m_page[0].m_pic); viewList.pushBack(temImage1); p_PageView = CAPageView::createWithLayout(DLayoutFill, CAPageViewDirectionHorizontal); p_PageView->setViews(viewList); p_PageView->setPageViewDelegate(this); p_PageView->setTouchEnabled(true); tempview->addSubview(p_PageView); p_PageView->setCurrPage(1, false); CAView* bg = CAView::createWithColor(ccc4(0, 0, 0, 128)); bg->setLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(0, 50))); tempview->addSubview(bg); pageControl = CAPageControl::createWithLayout(DLayout(DHorizontalLayout_R_W(40, 100), DVerticalLayoutFill)); pageControl->setNumberOfPages((int)m_page.size()); pageControl->setPageIndicatorImage(CAImage::create("image/pagecontrol_selected.png")); pageControl->setCurrIndicatorImage(CAImage::create("image/pagecontrol_bg.png")); pageControl->setPageIndicatorTintColor(CAColor_gray); //pageControl->setCurrentPageIndicatorTintColor(CAColor_clear); pageControl->addTarget(this, CAControl_selector(CDNewsViewController::pageControlCallBack)); bg->addSubview(pageControl); if (m_page.size()>0) { pageViewTitle = CALabel::createWithLayout(DLayout(DHorizontalLayout_L_R(20, 160), DVerticalLayoutFill)); pageViewTitle->setVerticalTextAlignmet(CAVerticalTextAlignmentCenter); pageViewTitle->setText(m_page[0].m_title); pageViewTitle->setColor(CAColor_white); pageViewTitle->setFontSize(28); bg->addSubview(pageViewTitle); } } void CDNewsViewController::viewDidUnload() { } void CDNewsViewController::tableViewDidSelectRowAtIndexPath(CATableView* table, unsigned int section, unsigned int row) { CDWebViewController* _webController = new CDWebViewController(); _webController->init(); _webController->setTitle(" "); _webController->autorelease(); RootWindow::getInstance()->getDrawerController()->hideLeftViewController(true); RootWindow::getInstance()->getRootNavigationController()->pushViewController(_webController, true); _webController->initWebView(m_msg[row].m_url); } void CDNewsViewController::tableViewDidDeselectRowAtIndexPath(CATableView* table, unsigned int section, unsigned int row) { } CATableViewCell* CDNewsViewController::tableCellAtIndex(CATableView* table, const DSize& cellSize, unsigned int section, unsigned int row) { CDNewsTableCell* cell = dynamic_cast<CDNewsTableCell*>(table->dequeueReusableCellWithIdentifier("CrossApp")); if (cell == NULL) { cell = CDNewsTableCell::create("CrossApp"); } cell->setModel(m_msg[row]); return cell; } void CDNewsViewController::tableViewWillDisplayCellAtIndex(CATableView* table, CATableViewCell* cell, unsigned int section, unsigned int row) { /* if (cell != NULL) { temp_time+=0.02f; CAViewAnimation::beginAnimations("", NULL); CAViewAnimation::setAnimationDuration(temp_time); CAViewAnimation::setAnimationDidStopSelector(this,CAViewAnimation0_selector(CDNewsViewController::tempCallBack)); CAViewAnimation::commitAnimations(); cell->getContentView()->setScale(0.8f); cell->getContentView()->setRotationY(-180); CAViewAnimation::beginAnimations("", NULL); CAViewAnimation::setAnimationDuration(0.3f); CAViewAnimation::setAnimationDelay(temp_time); cell->getContentView()->setScale(1.0f); cell->getContentView()->setRotationY(0); //执行动画 CAViewAnimation::commitAnimations(); } */ } void CDNewsViewController::tempCallBack() { temp_time-=0.02f; } unsigned int CDNewsViewController::numberOfSections(CATableView *table) { return 1; } unsigned int CDNewsViewController::numberOfRowsInSection(CATableView *table, unsigned int section) { return (unsigned int)m_msg.size(); } unsigned int CDNewsViewController::tableViewHeightForRowAtIndexPath(CATableView* table, unsigned int section, unsigned int row) { return 170; } void CDNewsViewController::scrollViewHeaderBeginRefreshing(CrossApp::CAScrollView *view) { std::map<std::string, std::string> key_value; key_value["tag"] = menuTag[urlID]; key_value["page"]= "1"; key_value["limit"]= "20"; key_value["appid"]="10000"; key_value["sign_method"]="md5"; string tempSign = getSign(key_value); CCLog("sign===%s",tempSign.c_str()); key_value["sign"] = tempSign; string tempUrl = "http://api.9miao.com/news/"; CommonHttpManager::getInstance()->send_post(tempUrl, key_value, this, CommonHttpJson_selector(CDNewsViewController::onRequestFinished)); CATabBarItem* item = this->getTabBarItem(); CCLog("BadgeValue====%s",item->getBadgeValue().c_str()); if (!item->getBadgeValue().empty()) { item->setBadgeValue(""); this->setTabBarItem(item); } } void CDNewsViewController::scrollViewFooterBeginRefreshing(CAScrollView* view) { p_section++; std::map<std::string, std::string> key_value; key_value["tag"] = menuTag[urlID]; key_value["page"]= crossapp_format_string("%d",p_section); key_value["limit"]= "20"; key_value["appid"]="10000"; key_value["sign_method"]="md5"; string tempSign = getSign(key_value); CCLog("sign===%s",tempSign.c_str()); key_value["sign"] = tempSign; string tempUrl = "http://api.9miao.com/news/"; CommonHttpManager::getInstance()->send_post(tempUrl, key_value, this, CommonHttpJson_selector(CDNewsViewController::onRefreshRequestFinished)); } void CDNewsViewController::pageViewDidSelectPageAtIndex(CAPageView* pageView, unsigned int index, const DPoint& point) { CDWebViewController* _webController = new CDWebViewController(); _webController->init(); _webController->setTitle(" "); _webController->autorelease(); RootWindow::getInstance()->getDrawerController()->hideLeftViewController(true); RootWindow::getInstance()->getRootNavigationController()->pushViewController(_webController, true); _webController->initWebView(m_page[index-1].m_url); } void CDNewsViewController::pageViewDidBeginTurning(CAPageView* pageView) { } void CDNewsViewController::pageViewDidEndTurning(CAPageView* pageView) { if (pageView->getCurrPage()==0) { pageView->setCurrPage((int)m_page.size(), false); } else if(pageView->getCurrPage()==m_page.size()+1) { pageView->setCurrPage(1, false); } pageControl->setCurrentPage(pageView->getCurrPage()-1); pageControl->updateCurrentPageDisplay(); if (m_page.size()>0) { pageViewTitle->setText(m_page[pageView->getCurrPage()-1].m_title); } } void CDNewsViewController::pageControlCallBack(CrossApp::CAControl *btn, CrossApp::DPoint point){ CAPageControl* button = (CAPageControl*)btn; p_PageView->setCurrPage(button->getCurrentPage()+1, true); if (m_page.size()>0) { pageViewTitle->setText(m_page[button->getCurrentPage()].m_title); } }
[ "278688386@qq.com" ]
278688386@qq.com
f26812631cd687e678cb07125d646b93724896a7
8a1d056a516831d99ccb4eb52053d1cffd97c9e9
/src/gamed/gs/player/subsys/player_prop_reinforce.h
bf05a5ebb6126b9d9f03bdf36830d57707a4c113
[]
no_license
289/a
b964481d2552f11f300b1199062ca62b71edf76e
43d28da99387ba225b476fe51bd7a13245f49d5e
refs/heads/master
2020-04-17T04:22:23.226951
2018-03-21T14:17:08
2018-03-21T14:17:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,275
h
#ifndef GAMED_GS_SUBSYS_PLAYER_PROP_REINFORCE_H_ #define GAMED_GS_SUBSYS_PLAYER_PROP_REINFORCE_H_ #include "gs/player/player_subsys.h" namespace gamed { /** * @brief:player属性强化子系统(初阶属性强化等) */ class PlayerPropReinforce : public PlayerSubSystem { public: PlayerPropReinforce(Player& player); virtual ~PlayerPropReinforce(); virtual void RegisterCmdHandler(); bool SaveToDB(common::PlayerPropRFData* pdata); bool LoadFromDB(const common::PlayerPropRFData& data); void PlayerGetPropReinforce(); void ResetPrimaryPropRF(); void AddPrimaryPropRFCurEnergy(); public: enum PrimaryPropRFIndex { PPRFI_HP = 0, // 生命值 PPRFI_P_ATK, // 物理攻击 PPRFI_M_ATK, // 魔法攻击 PPRFI_P_DEF, // 物理防御 PPRFI_M_DEF, // 魔法防御 PPRFI_P_PIE, // 物理穿透 PPRFI_M_PIE, // 魔法穿透 PPRFI_MAX }; protected: void CMDHandler_QueryPrimaryPropRF(const C2G::QueryPrimaryPropRF&); void CMDHandler_BuyPrimaryPropRFEnergy(const C2G::BuyPrimaryPropRFEnergy&); void CMDHandler_PrimaryPropReinforce(const C2G::PrimaryPropReinforce&); private: class PrimaryPropRF { public: struct Detail { Detail() : cur_add_energy(0), cur_level(0) { } void clear() { cur_add_energy = 0; cur_level = 0; } int32_t cur_add_energy; // 当前已经充了多少能量 int32_t cur_level; // 当前等级 }; PrimaryPropRF() : last_recover_time(0), cur_energy(0) { } void clear() { last_recover_time = 0; cur_energy = 0; for (size_t i = 0; i < detail.size(); ++i) { detail[i].clear(); } } int32_t last_recover_time; // 上次恢复能量的时间点,绝对时间,0表示上次恢复已经大于等于能量上限 int32_t cur_energy; // 当前能量值 FixedArray<Detail, PPRFI_MAX> detail; // 下标对应枚举PrimaryPropRFIndex }; private: void PlayerGetPrimaryPropRF(); void RecalculatePPRFEnergy(int32_t add_energy = 0, bool is_reset = false, bool sync_to_client = true); // 重新计算当前能量值 void AttachPrimaryPropRFPoints() const; void DetachPrimaryPropRFPoints() const; void CalcPrimaryPropRF(int32_t calc_energy, bool reset_cur_energy, bool sync_levelup); void CalcPrimaryPropRFLevelUp(const int32_t* option, size_t size, bool sync_to_client); void refresh_pprf_points(bool is_attach) const; float get_pprf_average_level() const; int32_t get_pprf_add_points(PrimaryPropRFIndex index) const; // 计算初阶属性强化最终加点 int32_t calc_pprf_weight(PrimaryPropRFIndex index, float average_level) const; // 计算初阶属性强化权重 bool check_pprf_levelup() const; // 检查是否还有可以升级的初阶属性 private: PrimaryPropRF primary_prop_rf_; }; } // namespace gamed #endif // GAMED_GS_SUBSYS_PLAYER_PROP_REINFORCE_H_
[ "18842636481@qq.com" ]
18842636481@qq.com
3bfdde37d9a152ea31bcedb241d9976ee1b84030
de70d532402c2c419a2057cd10df5405a81989d8
/prac10/src/ofApp.cpp
cf9cca5ee7b481bd8757f8089e624fe0940f9a25
[]
no_license
Lacty/of_practice
083fdc0c6b5c776348e4b429f4fb69cb4584e122
adcf0cbc89616e13eda7889c673318d155fbc2dd
refs/heads/master
2021-01-12T16:16:14.045576
2016-11-19T10:09:41
2016-11-19T10:09:41
71,971,117
0
0
null
null
null
null
UTF-8
C++
false
false
2,007
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetCircleResolution(32); } //-------------------------------------------------------------- void ofApp::update() { for (auto& part : particles) { part.update(true, 0, 460, 0, 300); } } //-------------------------------------------------------------- void ofApp::draw() { for (auto& part : particles) { part.draw(); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) {} //-------------------------------------------------------------- void ofApp::keyReleased(int key) {} //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ) {} //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { create(x, y); } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) {} //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) {} //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y) {} //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y) {} //-------------------------------------------------------------- void ofApp::windowResized(int w, int h) {} //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg) {} //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo) {} void ofApp::create(int x, int y) { Particle part; part.setPosition(ofVec3f(x, y, 0)) ->setSize(2 + ofRandom(5)) ->setColor(ofColor(100 + ofRandom(155), 100 + ofRandom(155), 100 + ofRandom(155))) ->setGravity(true, 0.08f) ->setVelocity(ofVec3f(ofRandom(-5, 5), ofRandom(-5, 5), 0)); particles.push_back(part); }
[ "akira206@gmail.com" ]
akira206@gmail.com
6a59f0dd5bb54d2b26d30ed38650291eb59e3bec
d14b5d78b72711e4614808051c0364b7bd5d6d98
/third_party/llvm-10.0/llvm/lib/Target/ARM/Thumb2InstrInfo.h
7d8dff14e1e72de01db5f990b13d4ff6beb01ab6
[ "Apache-2.0" ]
permissive
google/swiftshader
76659addb1c12eb1477050fded1e7d067f2ed25b
5be49d4aef266ae6dcc95085e1e3011dad0e7eb7
refs/heads/master
2023-07-21T23:19:29.415159
2023-07-21T19:58:29
2023-07-21T20:50:19
62,297,898
1,981
306
Apache-2.0
2023-07-05T21:29:34
2016-06-30T09:25:24
C++
UTF-8
C++
false
false
3,284
h
//===-- Thumb2InstrInfo.h - Thumb-2 Instruction Information -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the Thumb-2 implementation of the TargetInstrInfo class. // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_ARM_THUMB2INSTRINFO_H #define LLVM_LIB_TARGET_ARM_THUMB2INSTRINFO_H #include "ARMBaseInstrInfo.h" #include "ThumbRegisterInfo.h" namespace llvm { class ARMSubtarget; class ScheduleHazardRecognizer; class Thumb2InstrInfo : public ARMBaseInstrInfo { ThumbRegisterInfo RI; public: explicit Thumb2InstrInfo(const ARMSubtarget &STI); /// Return the noop instruction to use for a noop. void getNoop(MCInst &NopInst) const override; // Return the non-pre/post incrementing version of 'Opc'. Return 0 // if there is not such an opcode. unsigned getUnindexedOpcode(unsigned Opc) const override; void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail, MachineBasicBlock *NewDest) const override; bool isLegalToSplitMBBAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const override; void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc) const override; void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override; void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override; /// getRegisterInfo - TargetInstrInfo is a superset of MRegister info. As /// such, whenever a client has an instance of instruction info, it should /// always be able to get register info as well (through this method). /// const ThumbRegisterInfo &getRegisterInfo() const override { return RI; } private: void expandLoadStackGuard(MachineBasicBlock::iterator MI) const override; }; /// getITInstrPredicate - Valid only in Thumb2 mode. This function is identical /// to llvm::getInstrPredicate except it returns AL for conditional branch /// instructions which are "predicated", but are not in IT blocks. ARMCC::CondCodes getITInstrPredicate(const MachineInstr &MI, unsigned &PredReg); // getVPTInstrPredicate: VPT analogue of that, plus a helper function // corresponding to MachineInstr::findFirstPredOperandIdx. int findFirstVPTPredOperandIdx(const MachineInstr &MI); ARMVCC::VPTCodes getVPTInstrPredicate(const MachineInstr &MI, unsigned &PredReg); } #endif
[ "bclayton@google.com" ]
bclayton@google.com
1fdbbbdb7b020f222da85fccd1e4da8b7a336e27
2485ffe62134cd39d4c5cf12f8e73ca9ef781dd1
/contrib/boost/iterator/test/function_input_iterator_test.cpp
f64e9f59d6111b1aabc22365483b734d20daa66d
[ "MIT", "BSL-1.0" ]
permissive
alesapin/XMorphy
1aed0c8e0f8e74efac9523f4d6e585e5223105ee
aaf1d5561cc9227691331a515ca3bc94ed6cc0f1
refs/heads/master
2023-04-16T09:27:58.731844
2023-04-08T17:15:26
2023-04-08T17:15:26
97,373,549
37
5
MIT
2023-04-08T17:15:27
2017-07-16T09:35:41
C++
UTF-8
C++
false
false
3,974
cpp
// Copyright 2010 (c) Dean Michael Berris // Distributed under the Boost Software License Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <cstddef> #include <algorithm> #include <iterator> #include <vector> #include <boost/config.hpp> #if !defined(BOOST_NO_CXX11_DECLTYPE) // Force boost::result_of use decltype, even on compilers that don't support N3276. // This enables this test to also verify if the iterator works with lambdas // on such compilers with this config macro. Note that without the macro result_of // (and consequently the iterator) is guaranteed to _not_ work, so this case is not // worth testing anyway. #define BOOST_RESULT_OF_USE_DECLTYPE #endif #include <boost/core/lightweight_test.hpp> #include <boost/iterator/function_input_iterator.hpp> namespace { struct ones { typedef int result_type; result_type operator() () { return 1; } }; int ones_function () { return 1; } struct counter { typedef int result_type; int n; explicit counter(int n_) : n(n_) { } result_type operator() () { return n++; } }; } // namespace using namespace std; int main() { // test the iterator with function objects ones ones_generator; vector<int> values(10); generate(values.begin(), values.end(), ones()); vector<int> generated; copy( boost::make_function_input_iterator(ones_generator, 0), boost::make_function_input_iterator(ones_generator, 10), back_inserter(generated) ); BOOST_TEST_ALL_EQ(values.begin(), values.end(), generated.begin(), generated.end()); // test the iterator with normal functions vector<int>().swap(generated); copy( boost::make_function_input_iterator(&ones_function, 0), boost::make_function_input_iterator(&ones_function, 10), back_inserter(generated) ); BOOST_TEST_ALL_EQ(values.begin(), values.end(), generated.begin(), generated.end()); // test the iterator with a reference to a function vector<int>().swap(generated); copy( boost::make_function_input_iterator(ones_function, 0), boost::make_function_input_iterator(ones_function, 10), back_inserter(generated) ); BOOST_TEST_ALL_EQ(values.begin(), values.end(), generated.begin(), generated.end()); // test the iterator with a stateful function object counter counter_generator(42); vector<int>().swap(generated); copy( boost::make_function_input_iterator(counter_generator, 0), boost::make_function_input_iterator(counter_generator, 10), back_inserter(generated) ); BOOST_TEST_EQ(generated.size(), 10u); BOOST_TEST_EQ(counter_generator.n, 42 + 10); for(std::size_t i = 0; i != 10; ++i) BOOST_TEST_EQ(generated[i], static_cast<int>(42 + i)); // Test that incrementing the iterator returns a reference to the iterator type { typedef boost::iterators::function_input_iterator<counter, int> function_counter_iterator_t; function_counter_iterator_t it1(counter_generator, 0); function_counter_iterator_t it2(++it1); function_counter_iterator_t it3(it2++); BOOST_TEST_EQ(*it3, 54); } #if !defined(BOOST_NO_CXX11_LAMBDAS) && !defined(BOOST_NO_CXX11_AUTO_DECLARATIONS) \ && defined(BOOST_RESULT_OF_USE_DECLTYPE) // test the iterator with lambda expressions int num = 42; auto lambda_generator = [&num] { return num++; }; vector<int>().swap(generated); copy( boost::make_function_input_iterator(lambda_generator, 0), boost::make_function_input_iterator(lambda_generator, 10), back_inserter(generated) ); BOOST_TEST_EQ(generated.size(), 10u); for(std::size_t i = 0; i != 10; ++i) BOOST_TEST_EQ(generated[i], static_cast<int>(42 + i)); #endif // BOOST_NO_CXX11_LAMBDAS return boost::report_errors(); }
[ "alesapin@gmail.com" ]
alesapin@gmail.com
1771468770fd2b916cc3faeda3c3fac137591d68
7add42e3fffa26c8aea222eca87791c89c7d84bd
/scenario/grid/GridSpectrum.cpp
bae10d12643975534f40a4f21df4935ebbcb804c
[]
no_license
mr-oroboto/Waveguide
1f15417f43551dded241be66505a73900c075fd1
d2921b065386a9f79830d6094b944f1b93b515ad
refs/heads/master
2022-10-20T02:45:03.016262
2022-10-09T05:10:10
2022-10-09T05:10:10
235,275,433
0
0
null
null
null
null
UTF-8
C++
false
false
4,188
cpp
#include "GridSpectrum.h" #include <iostream> GridSpectrum::GridSpectrum(insight::WindowManager* window_manager, sdr::SpectrumSampler* sampler, uint32_t bin_coalesce_factor) : SimpleSpectrum(window_manager, sampler, bin_coalesce_factor) { } void GridSpectrum::run() { resetState(); display_manager_->resetCamera(); display_manager_->setCameraPointingVector(glm::vec3(1, 0, -1.0)); display_manager_->setCameraCoords(glm::vec3(-55, 20, 25)); display_manager_->setPerspective(0.1, 100.0, 90); std::unique_ptr<insight::FrameQueue> frame_queue = std::make_unique<insight::FrameQueue>(display_manager_, true); frame_queue->setFrameRate(1); frame_ = frame_queue->newFrame(); uint64_t raw_bin_count = samples_->getBinCount(); uint64_t coalesced_bin_count = (raw_bin_count + bin_coalesce_factor_ - 1) / bin_coalesce_factor_; // integer ceiling std::cout << "Coalescing " << raw_bin_count << " frequency bins into " << coalesced_bin_count << " visual bins" << std::endl; uint32_t grid_width = 80; glm::vec3 start_coords = glm::vec3(-1.0f * (grid_width / 2.0f), 0, 0); for (uint64_t bin_id = 0; bin_id < coalesced_bin_count; bin_id++) { // Coalesce the frequency bins std::vector<sdr::FrequencyBin const*> frequency_bins; uint64_t start_frequency_bin = bin_id * bin_coalesce_factor_; for (uint64_t j = start_frequency_bin; j < (start_frequency_bin + bin_coalesce_factor_) && j < raw_bin_count; j++) { frequency_bins.push_back(samples_->getFrequencyBin(j)); } glm::vec3 world_coords = start_coords; world_coords.x += (bin_id % grid_width); SimpleSpectrumRange* bin = new SimpleSpectrumRange(display_manager_, insight::primitive::Primitive::Type::RECTANGLE, 0, bin_id, world_coords, glm::vec3(1, 1, 1), frequency_bins); coalesced_bins_.push_back(bin); frame_->addObject(bin); if (bin_id != 0 && (bin_id % grid_width) == 0) { char msg[64]; snprintf(msg, sizeof(msg), "%.2fMHz", const_cast<sdr::FrequencyBin*>(frequency_bins[0])->getFrequency() / 1000000.0f); frame_->addText(msg, world_coords.x - 5.0f, 0.0f, world_coords.z, false, 0.02, glm::vec3(1.0, 1.0, 1.0)); start_coords.z -= 1.0f; } } char msg[128]; snprintf(msg, sizeof(msg), "Grid Perspective (%.3fMhz - %.3fMhz)", sampler_->getStartFrequency() / 1000000.0f, sampler_->getEndFrequency() / 1000000.0f); frame_->addText(msg, 10, 10, 0, true, 1.0, glm::vec3(1.0, 1.0, 1.0)); frame_queue->enqueueFrame(frame_); display_manager_->setUpdateSceneCallback(std::bind(&GridSpectrum::updateSceneCallback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); frame_queue->setReady(); if (frame_queue->setActive()) { display_manager_->setFrameQueue(std::move(frame_queue)); } } void GridSpectrum::updateSceneCallback(GLfloat secs_since_rendering_started, GLfloat secs_since_framequeue_started, GLfloat secs_since_last_renderloop, GLfloat secs_since_last_frame) { uint16_t current_slice = 0; if (samples_->getSweepCount() && current_interest_markers_ < max_interest_markers_) { markLocalMaxima(); } frame_->updateObjects(secs_since_rendering_started, secs_since_framequeue_started, secs_since_last_renderloop, secs_since_last_frame, static_cast<void*>(&current_slice)); } void GridSpectrum::addInterestMarkerToBin(SimpleSpectrumRange *bin) { char msg[64]; snprintf(msg, sizeof(msg), "%.3fMHz", bin->getFrequency() / 1000000.0f); unsigned long text_id = frame_->addText(msg, bin->getPosition().x, bin->getAmplitude() + 0.2f, bin->getPosition().z, false, 0.02, glm::vec3(1.0, 1.0, 1.0)); marked_bin_text_ids_.push_back(text_id); SimpleSpectrum::addInterestMarkerToBin(bin); } void GridSpectrum::clearInterestMarkers() { if (frame_ == nullptr) { return; } for (unsigned long i : marked_bin_text_ids_) { frame_->deleteText(i); } marked_bin_text_ids_.clear(); SimpleSpectrum::clearInterestMarkers(); }
[ "jsmtp@protonmail.com" ]
jsmtp@protonmail.com
23dce32bae5ecd77a4eb93240c163b8759e6bbd0
992f1b4fef76853e256e7c54280139753c5a6192
/leet/test/leet0013_test.cpp
ac08bc0f348f343bdc2ee208127fa34e5c39553e
[]
no_license
lcllkzdzq/leet
ce19526a5a4c2f94403a7e3c3dcdd4fffd912d2f
7ea46a37e365c0d55435dfbb5a167a33c8c3e7a2
refs/heads/master
2021-04-06T13:32:08.580309
2018-07-19T15:31:11
2018-07-19T15:31:11
124,920,999
0
0
null
null
null
null
UTF-8
C++
false
false
457
cpp
#include <gtest/gtest.h> #include "leet0013.hpp" TEST(Leet0013, less_than_10) { Leet0013Solution s; EXPECT_EQ(s.romanToInt("IV"), 4); } TEST(Leet0013, 10_to_100) { Leet0013Solution s; EXPECT_EQ(s.romanToInt("XLIII"), 43); } TEST(Leet0013, 100_to_1000) { Leet0013Solution s; EXPECT_EQ(s.romanToInt("DCCCXCIII"), 893); } TEST(Leet0013, 1000_than_3999) { Leet0013Solution s; EXPECT_EQ(s.romanToInt("MMCLXXXV"), 2185); }
[ "lunarwaterfox@gmail.com" ]
lunarwaterfox@gmail.com
3a794bc08ae9ccdb3cba751b38e514ad047a8f58
bb9b83b2526d3ff8a932a1992885a3fac7ee064d
/src/modules/osg/generated_code/Projection.pypp.hpp
1d2fcfebffa4444825eb24c23f299906cbee207f
[]
no_license
JaneliaSciComp/osgpyplusplus
4ceb65237772fe6686ddc0805b8c77d7b4b61b40
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
refs/heads/master
2021-01-10T19:12:31.756663
2015-09-09T19:10:16
2015-09-09T19:10:16
23,578,052
20
7
null
null
null
null
UTF-8
C++
false
false
207
hpp
// This file has been generated by Py++. #ifndef Projection_hpp__pyplusplus_wrapper #define Projection_hpp__pyplusplus_wrapper void register_Projection_class(); #endif//Projection_hpp__pyplusplus_wrapper
[ "brunsc@janelia.hhmi.org" ]
brunsc@janelia.hhmi.org
a9dfd063e51f04e7c148083bad9f3b955ed54d65
09a8696421a8edc1fbb33aca63f42eb70a6b43b5
/Class(III)/7-1-1.cpp
52b67eca845c216f48b83122d3ca03f5880f3dd8
[]
no_license
chris0765/CppPrograming
be35e6f7be37566d74ef3bafcbc01f8ef017772a
726536c3c9cb18d281535b2a32256db1e8cf5f2b
refs/heads/main
2023-05-13T23:26:55.650267
2021-06-03T14:43:54
2021-06-03T14:43:54
348,203,097
0
0
null
null
null
null
UTF-8
C++
false
false
785
cpp
#include <iostream> using namespace std; class Complex{ double re, im; public: Complex(double r = 0, double i = 0): re(r), im(i){} ~Complex(){} double real() {return re;} double imag() {return im;} Complex add(const Complex& c) const; friend Complex operator+(const Complex& c, const Complex& d); void print() const{ cout << re << " + " << im << "i" << endl; } }; Complex operator+(const Complex& c, const Complex& d){ Complex result(c.re+d.re, c.im+d.im); return result; } Complex Complex::add(const Complex& c) const{ Complex result(re + c.re, im + c.im); return result; } int main() { Complex x(2, 3); Complex y(-1, -3); Complex z; x.print(); y.print(); z = x+y; z.print(); return 0; }
[ "chris0765@kookmin.ac.kr" ]
chris0765@kookmin.ac.kr
bb06ab64b895169d467557df06c044aa519c0824
fd8bb910d54c981157bfc2748ed5078760bd8be6
/tensorflow_impl/applications/Garfield_legacy/native/so_threadpool/threadpool.cpp
e7a6c25049e594705e749d288b0b00ce38ee25dd
[ "MIT" ]
permissive
yanlili1995/Garfield
7ac5941ebb78807e4ef53a24f0327f80599fb83c
f784cfd4cc2f34879abb287ef32c586243ee5b0c
refs/heads/master
2023-08-05T18:20:04.547095
2021-09-24T08:27:55
2021-09-24T08:27:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,760
cpp
/** * @file threadpool.cpp * @author Sébastien Rouault <sebastien.rouault@alumni.epfl.ch> * * @section LICENSE * * Copyright © 2018-2019 École Polytechnique Fédérale de Lausanne (EPFL). * See LICENSE file. * * @section DESCRIPTION * * Another thread pool management class, with parallel for-loop helper. **/ // Compiler version check #if __cplusplus < 201103L #error This translation unit requires at least a C++11 compiler #endif #ifndef __GNUC__ #error This translation unit requires a GNU C++ compiler #endif // External headers #include <algorithm> #include <condition_variable> #include <cmath> #include <cstddef> #include <cstdio> #include <future> #include <iterator> #include <limits> #include <memory> #include <mutex> #include <queue> #include <thread> #include <tuple> #include <type_traits> #include <utility> #include <vector> extern "C" { #include <unistd.h> } // Internal headers #include <common.hpp> #include <threadpool.hpp> // -------------------------------------------------------------------------- // /** Lock guard class. **/ template<class Lock> using Guard = ::std::unique_lock<Lock>; /** Lock "reverse" guard class. **/ template<class Lock> class Forsake { private: Lock& lock; // Bound lock public: /** Deleted copy constructor/assignment. **/ Forsake(Forsake const&) = delete; Forsake& operator=(Forsake const&) = delete; /** Lock release constructor. * @param lock Lock to bind **/ Forsake(Lock& lock): lock{lock} { lock.unlock(); } /** Lock acquire destructor. **/ ~Forsake() { lock.lock(); } }; /** Worker thread entry point. * @param self Bound thread pool **/ void ThreadPool::entry_point(ThreadPool& self) { Guard<Mutex> guard{self.lock}; while (true) { // Main loop if (self.status == Status::detached) // Must terminate return; if (!self.jobs.empty()) { // Pick and run job auto& job = *self.jobs.front(); // Get job info self.jobs.pop(); // Remove job { // Run job Forsake<Mutex> forsake{self.lock}; job(); } continue; } self.cv.wait(guard); // Wait for event } } /** Get the default number of worker threads to use. * @return Default number of worker threads **/ size_t ThreadPool::get_default_nbworker() noexcept { auto res = ::sysconf(_SC_NPROCESSORS_ONLN); if (unlikely(res <= 0)) return 8; // Arbitrary default return res; } // -------------------------------------------------------------------------- // /** Thread pool begin constructor. * @param nbworkers Number of worker threads to use (optional, 0 for auto) **/ ThreadPool::ThreadPool(size_t nbworkers): size{nbworkers}, status{Status::running}, lock{}, cv{}, jobs{}, threads{} { if (nbworkers == 0) size = get_default_nbworker(); { // Worker threads creation threads.reserve(size); for (decltype(size) i = 0; i < size; ++i) threads.emplace_back(entry_point, ::std::ref(*this)); } } /** Notify then detach worker threads destructor. **/ ThreadPool::~ThreadPool() { { // Mark ending Guard<Mutex> guard{lock}; status = Status::detached; } cv.notify_all(); for (auto&& thread: threads) // Detach workers thread.detach(); } /** Submit a new job. * @param job Job to submit **/ void ThreadPool::submit(AbstractJob& job) { { // Submit one job Guard<Mutex> guard{lock}; jobs.push(::std::addressof(job)); } cv.notify_one(); // Notify one worker } // -------------------------------------------------------------------------- // // Shared thread pool ThreadPool pool;
[ "sebastien.rouault@alumni.epfl.ch" ]
sebastien.rouault@alumni.epfl.ch
27c3e8b068c3e05231ef3f1fbd203ae19a3a897e
5aecd1098bf6941216e19825059babf35306b0ea
/cvs/objects/util/base/include/data_definition_util.h
5d22a5fe3cf98cff9d7273c60fcd919c0dd120fc
[ "ECL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Silviameteoro/gcam-core
151f3f8a850918a3ad74c1d95fd3ec52273a17eb
cc0ed1f976fb625ce34ef23b92e917922f4c0bd4
refs/heads/master
2023-08-09T14:39:38.278457
2021-09-13T14:35:12
2021-09-13T14:35:12
285,346,443
0
0
NOASSERTION
2020-08-05T16:29:50
2020-08-05T16:29:49
null
UTF-8
C++
false
false
17,678
h
#ifndef _DATA_DEFINITION_UTIL_H_ #define _DATA_DEFINITION_UTIL_H_ #if defined(_MSC_VER) #pragma once #endif /* * LEGAL NOTICE * This computer software was prepared by Battelle Memorial Institute, * hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830 * with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE * CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY * LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this * sentence must appear on any copies of this computer software. * * EXPORT CONTROL * User agrees that the Software will not be shipped, transferred or * exported into any country or used in any manner prohibited by the * United States Export Administration Act or any other applicable * export laws, restrictions or regulations (collectively the "Export Laws"). * Export of the Software may require some form of license or other * authority from the U.S. Government, and failure to obtain such * export control license may result in criminal liability under * U.S. laws. In addition, if the Software is identified as export controlled * items under the Export Laws, User represents and warrants that User * is not a citizen, or otherwise located within, an embargoed nation * (including without limitation Iran, Syria, Sudan, Cuba, and North Korea) * and that User is not otherwise prohibited * under the Export Laws from receiving the Software. * * Copyright 2011 Battelle Memorial Institute. All Rights Reserved. * Distributed as open-source under the terms of the Educational Community * License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php * * For further details, see: http://www.globalchange.umd.edu/models/gcam/ * */ /*! * \file data_definition_util.h * \ingroup util * \brief Header file for that provide Macros and other utilities to generate member * variable definitions which can be manipulated at compile time and accessed * in a generic way. * \author Pralit Patel */ #include <string> #include <boost/mpl/vector.hpp> #include <boost/fusion/include/vector.hpp> #include <boost/fusion/include/at.hpp> #include <boost/fusion/include/mpl.hpp> #include <boost/preprocessor/seq.hpp> #include <boost/preprocessor/variadic/to_seq.hpp> #include <boost/preprocessor/variadic/elem.hpp> #include <boost/preprocessor/variadic/size.hpp> #include <boost/preprocessor/facilities/empty.hpp> #include <boost/preprocessor/control/iif.hpp> #include <boost/preprocessor/punctuation/is_begin_parens.hpp> #include "util/base/include/expand_data_vector.h" /*! * \brief An enumeration of flags that could be useful as tags on the various Data * definitions. * \details All Data definitions will have a flag of SIMPLE, ARRAY, or CONTAINER * however even more flags may be added to give even more context about * the definition such as SIMPLE | STATE which could then also be used to * for instance search by in GCAMFusion. */ enum DataFlags { /*! * \brief A flag to indicate this Data definition is a simple member variable. * \details A SIMPLE data would be something such as an int or std::string. * Basically a kind of data that would not contain any further Data * definitions (of interest during introspection) and would not make * sense to be indexed into such as with ARRAY definitions. */ SIMPLE = 1 << 0, /*! * \brief A flag to indicate this Data definition is a simple array member variable. * \details A ARRAY data would be something such as PeriodVector<double>. * Basically a kind of data that would not contain any further Data * definitions (of interest during introspection) however can be * indexed, for instance to only get the double in 10th position. */ ARRAY = 1 << 1, /*! * \brief A flag to indicate this Data definition which contains a GCAM class * that itself would have futher data definitions within it. * \details A CONTAINER data would be something such as IDiscreteChoice* or * std::vector<Subsector*> where by the choice function and subsector * each have further Data member variables themselves. As implied * earlier both "single containers" or "arrays of containers" can be * tagged with just this flag (i.e. no need to add the ARRAY flag too). */ CONTAINER = 1 << 2, /*! * \brief A flag to indicate this Data is a "state" variable or in other words * it's value changes during World.calc. * \details This flag would generally be used in conjunction with a SIMPLE or * ARRAY who's data type is Value or an array of Values. Data marked * with this flag can be searched for and re-organized so that "state" * can be managed centrally stored/restored for instance during partial * derivative calculations. */ STATE = 1 << 3 // potentially more flags here such as to tag "non-parsable" Data etc }; /*! * \brief Basic structure for holding data members for GCAM classes. * \details The idea behind this structure is that every data member * has two important properties: the data itself and a name * used to refer to it (e.g., in XML inputs). In addition * there may be some additional compile time meta data that * would be useful to generate code or search by in GCAM * Fusion such as the data type or some combination from the * enumeration DataFlags. * This structure makes all of those available for inspection * by other objects and functions. */ template<typename T, int DataFlagsDefinition> struct Data { Data( T& aData, const char* aDataName ):mDataName( aDataName ), mData( aData ){} Data( T& aData, const std::string& aDataName ):mDataName( aDataName.c_str() ), mData( aData ){} /*! \note The Data struct does not manage any of it's member variables and * instead simply holds reference to some original source. */ virtual ~Data() { } /*! * \brief The human readable name for this data. */ const char* mDataName; /*! * \brief A reference to the actual data stored. */ T& mData; /*! * \brief Type for this data item */ typedef T value_type; /*! * \brief A constexpr (compile time) function that checks if a given aDataFlag * matches any of the flags set set in DataFlagsDefinition. * \param aDataFlag A Flag that may be some combination of the flags declared * in the enumeration DataFlags. * \return True if aTypeFlag was set in the data definition flags used to * define this data structure. */ static constexpr bool hasDataFlag( const int aDataFlag ) { return ( ( aDataFlag & ~DataFlagsDefinition ) == 0 ); } /*! * \pre All Data definitions must at the very least be tagged as SIMPLE, * ARRAY, or CONTAINER. */ static_assert( hasDataFlag( SIMPLE ) || hasDataFlag( ARRAY ) || hasDataFlag( CONTAINER ), "Invalid Data definition: failed to declare the kind of data." ); }; /*! * \brief Macro to add to a class a method to accept the ExpandDataVector visitor * \details The ExpandDataVector visitor works with this method to * produce a vector of all of the data elements for an object * (including those inherited from base classes). Each class * needs to have such a method, and this macro produces it. */ #define ACCEPT_EXPAND_DATA_VECTOR_METHOD( aTypeDef ) \ friend class ExpandDataVector<aTypeDef>; \ virtual void doDataExpansion( ExpandDataVector<aTypeDef>& aVisitor ) { \ aVisitor.setSubClass( this ); \ } /*! * \brief This Macro is how GCAM member variables definitions that should be * available for introspection should be made. * \details Note that while this is how all Data definitions should be generated * the result of this Macro will not make sense unless called from within * DEFINE_DATA_INTERNAL (through it proxy Macro calls DEFINE_DATA or * DEFINE_DATA_WITH_PARENT). The purpose of this Macro then is simply to * collect all of the required pieces of a Data definition, reorganize them, * and put them into a sequence of tokens so that then can be safely processed * and stiched together in DEFINE_DATA_INTERNAL. Thus a call such as * ``` * DEFINE_VARIABLE( CONTAINER, "period", mVintages, std::map<int, ITechnology*> ) * ``` * will expand to: * ``` * ( "period", mVintages, (Data<std::map<int)(ITechnology*>)(CONTAINER>) ) * ``` * Note the special consideration given to ensure type definitions with * commas in them get handled properly. This sequence will be used by * DEFINE_DATA_INTERNAL to generate the declarations needed by the class declaration. * \param aDataTypeFlags DataFlags used to determine properties about this data. Note this flag * must at least contain one of SIMPLE, ARRAY, or CONTAINER. * \param aDataName The human readable name. * \param aVarName The variable the user of the class will use for direct access to this Data. * \param aTypeDef (... / __VA_ARGS__) The type definition of the member variable. */ #define DEFINE_VARIABLE( aDataTypeFlags, aDataName, aVarName, ... ) \ ( aDataName, aVarName, BOOST_PP_VARIADIC_TO_SEQ( Data<__VA_ARGS__, aDataTypeFlags> ) ) /*! * \brief Identity transformation. To be used with FOR_EACH metafunction to Flatten the nesting of sequences one level. * \details Example. Starting with a sequence like this * ``` * (a) (b) (c) * ``` * will become: * ``` * a b c * ``` * \param s The next available BOOST_PP_FOR repetition. * \param data A base token to be always passed in (not used). * \param elem The sequence of tokens represetning the current data definition. */ #define FLATTEN( r, data, elem ) \ elem /*! * \brief Creates the direct access variable definition. * \details This Macro will be called by BOOST_PP_SEQ_FOR_EACH_I as it loops * over all the requested Data definitions. Each time it is called * it will create the acutal member variable definition although the * type is pointing to the corresponding element in the Boost::Fusion * vector such as: * boost::mpl::at_c< DataVectorType, 0 >::type::value_type mName; * \param r The next available BOOST_PP_FOR repetition. * \param data A base token to be always passed in (not used). * \param i The current iteration of the data definitions. * \param elem The variable name to define for direct access to the current Data. */ #define MAKE_VAR_REF( r, data, i, elem ) \ boost::mpl::at_c< DataVectorType, i >::type::value_type elem; /*! * \brief Creates data vector initialization syntax. * \details This Macro will be called by BOOST_PP_SEQ_FOR_EACH_I as it loops * over all the requested Data definitions. Each time it is called * it will create the call to the constructor to the corresponding * element in the Boost::Fusion Data vector such as: * Data<std::string, SIMPLE>( mName, "name" ) * To create this definition all elements of each DATA DEFINITION will * need to be used. * \param r The next available BOOST_PP_FOR repetition. * \param data A base token to be always passed in (not used). * \param i The current iteration of the data definitions. * \param elem The full definition for a single data as generated by DEFINE_VARIABLE. */ #define MAKE_DATA_STRUCT_INIT( r, data, i, elem ) \ ( ( BOOST_PP_SEQ_ENUM( BOOST_PP_TUPLE_ELEM( 2, elem ) )( BOOST_PP_TUPLE_ELEM( 1, elem ), BOOST_PP_TUPLE_ELEM( 0, elem ) ) ) ) /*! * \brief Cut accross sequences of Data declarations to organize as * sequences of variable names, Data type definitions, and data names. * \details Implementation from: http://stackoverflow.com/questions/26475453/how-to-use-boostpreprocessor-to-unzip-a-sequence * The "unzipped" sequences can be accessed by index. For data definitions * given like: * ``` * #define DECLS \ * ( NAME_1, VAR_1, TYPE_1 ), \ * ( NAME_2, VAR_2, TYPE_2 ) * ``` * The macro calls: * ``` * UNZIP(0, DECLS) * UNZIP(1, DECLS) * UNZIP(2, DECLS) * ``` * Would then be transformed to: * ``` * (NAME_1) (NAME_2) * (VAR_1) (VAR_2) * (TYPE_1) (TYPE_2) * ``` */ #define UNZIP_MACRO(s, data, elem) BOOST_PP_TUPLE_ELEM(data, elem) #define UNZIP(i, ...) \ BOOST_PP_SEQ_TRANSFORM( \ UNZIP_MACRO, \ i, \ BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__) \ ) /*! * \brief Collects each DEFINE_VARIABLE definition and generates the full set of Data definitions. * Note that for perforamance reasons the data vector is only generated upon * request through the function generateDataVector(). * \details The collected data generates the following definitions: * 1) A boost::fusion::vector typedef that contains all of the Data definitions types in a * vector. * 2) A member function generateDataVector() which will generate a boost::fusion::vector that contains all of the Data structs which * contains reference to actual member variable data and data names, etc. * 3) The actual member varible definitions such as mName, mYear so that * users can continue to use the member variables as normal. * * For instance a call such as: * ``` * DEFINE_DATA_INTERNAL( DEFINE_VARIABLE( SIMPLE, "name", mName, std::string ) ) * ``` * Would then be transformed to (although perhaps not so well formatted): * ``` * typedef boost::fusion::vector<Data<std::string, SIMPLE> > DataVectorType; * DataVectorType generateDataVector() { * return DataVectorType>(Data<std::string, SIMPLE>( mName, "name" ) ); * } * boost::mpl::at_c< DataVectorType, 0 >::type::value_type mName; * ``` */ #define DEFINE_DATA_INTERNAL( ... ) \ typedef boost::fusion::vector<BOOST_PP_SEQ_ENUM( BOOST_PP_SEQ_FOR_EACH( FLATTEN, BOOST_PP_EMPTY, UNZIP( 2, __VA_ARGS__ ) ) )> DataVectorType; \ DataVectorType generateDataVector() { \ return DataVectorType( BOOST_PP_SEQ_ENUM( BOOST_PP_SEQ_FOR_EACH_I( MAKE_DATA_STRUCT_INIT, BOOST_PP_EMPTY, BOOST_PP_VARIADIC_TO_SEQ( __VA_ARGS__ ) ) ) ); \ } \ BOOST_PP_SEQ_FOR_EACH_I( MAKE_VAR_REF, BOOST_PP_EMPTY, UNZIP( 1, __VA_ARGS__ ) ) /*! * \brief A Macro to handle the special case where there are no Data definitions * to be made. This will correctly make the data definitions in a way that * won't result in compiler error. */ #define DEFINE_DATA_INTERNAL_EMPTY() \ typedef boost::fusion::vector<> DataVectorType; \ DataVectorType generateDataVector() { return DataVectorType(); } /*! * \brief A helper Macro to detect if we do or do not actually have any DEFINE_VARIABLE * definitions. We need to check explicitly since DEFINE_DATA_INTERNAL would * generate invalid syntax if it's argument was infact empty. */ #define DEFINE_DATA_INTERNAL_CHECK_ARGS( ... ) \ BOOST_PP_IIF( BOOST_PP_IS_BEGIN_PARENS( __VA_ARGS__ ), DEFINE_DATA_INTERNAL, DEFINE_DATA_INTERNAL_EMPTY ) ( __VA_ARGS__ ) /*! * \brief Define data entry point. In this definition a user must give a sequence * of all of the possible members of the inheritance heirarchy this class * belongs to starting with itself. This is necessary in order to get the * full data vector from sub-classes at runtime. * \details The first argument is used to typedef the SubClassFamilyVector, and the * rest is given to DEFINE_DATA_INTERNAL to process the actual data definitions. * The DEFINE_SUBCLASS_FAMILY macro can be used to create the SubClassFamilySeq * argument. */ #define DEFINE_DATA( aSubClassFamilySeq, ... ) \ public: typedef boost::mpl::vector<BOOST_PP_SEQ_ENUM( aSubClassFamilySeq )> SubClassFamilyVector; \ ACCEPT_EXPAND_DATA_VECTOR_METHOD( SubClassFamilyVector ) protected: \ DEFINE_DATA_INTERNAL_CHECK_ARGS( __VA_ARGS__ ) /*! * \brief Define data entry point which adds a typdef to give reference to the direct * parent class. This is necessary since each definition of generateDataVector() is * independent from it's parent classes. * \details The first argument is used to typeef the reference to the direct parent class, * and the rest is given to DEFINE_DATA_INTERNAL to process the actual data definitions. */ #define DEFINE_DATA_WITH_PARENT( aParentClass, ... ) \ public: typedef aParentClass ParentClass; \ ACCEPT_EXPAND_DATA_VECTOR_METHOD( get_base_class<ParentClass>::type::SubClassFamilyVector ) protected: \ DEFINE_DATA_INTERNAL_CHECK_ARGS( __VA_ARGS__ ) /*! * \brief A helper to organize the subclass family members into a sequence. */ #define DEFINE_SUBCLASS_FAMILY( ... ) \ BOOST_PP_VARIADIC_TO_SEQ( __VA_ARGS__ ) #endif // _DATA_DEFINITION_UTIL_H_
[ "pralit.patel@pnnl.gov" ]
pralit.patel@pnnl.gov
e58bc7c45ef7ad0488f5d5a644e4d6710bfc9649
fc7d9bbe049114ad5a94a6107321bdc09d3ccf53
/.history/Maze_20210919224931.cpp
573be8375c565b4a0b90910a5f0b7c42d540c2e3
[]
no_license
xich4932/3010_maze
2dbf7bb0f2be75d014a384cbefc4095779d525b5
72be8a7d9911efed5bc78be681486b2532c08ad8
refs/heads/main
2023-08-11T00:42:18.085853
2021-09-22T03:29:40
2021-09-22T03:29:40
408,272,071
0
0
null
null
null
null
UTF-8
C++
false
false
3,434
cpp
#include<iostream> #include<vector> #include<cstdlib> #include<array> #include"Maze.h" #include<time.h> //using namespace std; //return true when the path is not in the vector bool checkInPath(const int num, const std::vector<int> &vec){ for(int d =0; d < vec.size(); d++){ if(vec[d] == num) return true; } return false; } Board::Board(){ rows_ = 4; cols_ = 4; generate(); } Board::Board(int r, int c){ rows_ = r; cols_ = c; generate(); } void Board::displayUpdated(){ for(int i = 0; i < rows_; i++){ for(int d = 0; d < cols_; d++){ if(checkInPath(4*i +d, path)){ std::cout<< "*"; }else{ std::cout << "+" ; } } std::cout << std::endl; } } Maze::Maze(int r, int c){ //generate (board_); Board *new_board = new Board(r, c); } std::vector<int> getDirection(int point, int r, int c, int max_r, int max_c){ //{col,row} up left down right //int direction[4][2] ={{1,0},{0,1},{-1,0},{0,-1}}; std::vector< int > ret; ret.push_back(point - max_r); //up ret.push_back(point + 1); //right ret.push_back(point + max_r); //down ret.push_back(point - 1); //left if(r == 0){ ret.erase(ret.begin()+3); }else if(r == max_r - 1){ ret.erase(ret.begin()+1); } if(c == 0){ ret.erase(ret.begin()); }else if(c == max_c - 1){ ret.erase(ret.begin()+2); } return ret; } void printer(std::vector<int> pri){ for(int i =0 ; i< pri.size(); i++){ std::cout << pri[i] <<" "; } std::cout << std::endl; } void printer1(std::vector<std::array<int, 2>> pri){ for(int d =0; d < pri.size(); d++){ std::cout<<pri[d][0] <<" " << pri[d][1] <<std::endl; } } bool Board::generate(){ int max_step = 1; //max step to reach exit is 8 int visited[cols_][rows_]; //vector<int> path; path.push_back(0); srand((unsigned ) time(NULL)); int max = rows_ * cols_; visited[0][0] = 1; int start_r = 0; int start_c = 0; int end_c = cols_ - 1; int end_r = rows_ - 1; while(start_r != end_r && start_c != end_c && path.size() < 13 && max_step < 16){ std::vector<int> direction = getDirection(path[path.size()-1], start_r, start_c, rows_, cols_); //printer1(direction); int curr = rand()%direction.size(); std::cout << curr << std::endl; int temp_r = curr % rows_; int temp_c = curr / rows_; for(int t =0; t < cols_; t++){ for(int y =0; y < rows_; y++){ if(t == temp_c && y == temp_r){ std::cout << "2" << " "; }else{ std::cout << visited[t][y] << " "; } } std::cout << std::endl; } //std::cout << direction[curr][0] << " " << direction[curr][1] << std::endl; if(visited[curr / rows_][ curr % cols_]) continue; path.push_back(direction[curr]); max_step ++; //start_c += direction[curr][0]; //start_r += direction[curr][1]; visited[curr / rows_][curr % rows_] = 1; max_step ++; direction.clear(); displayUpdated(); } printer(path); if(start_r == end_r && start_c == end_c) return true; return false; }
[ "xich4932@colorado.edu" ]
xich4932@colorado.edu
338c31bdc9a9460a90248dc30619602322741e6d
9214736766cce5399cf0d178b1398438fc40357d
/libs/tgp/src/temper.cc
b27343406597fe57db91773a300c681a916f1019
[]
no_license
CustomComputingGroup/MLO
daaa391984a7b795354e518563733c98692b460c
3af52321da6a5bfb3b3cc04df714eb04250e157c
refs/heads/master
2021-01-01T19:34:15.891410
2013-05-21T16:23:26
2013-05-21T16:23:26
7,650,010
0
1
null
2019-01-21T19:53:47
2013-01-16T17:12:56
Python
UTF-8
C++
false
false
21,432
cc
/******************************************************************************** * * Bayesian Regression and Adaptive Sampling with Gaussian Process Trees * Copyright (C) 2005, University of California * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Questions? Contact Robert B. Gramacy (rbgramacy@ams.ucsc.edu) * ********************************************************************************/ extern "C" { #include "rand_draws.h" #include "matrix.h" #include "rhelp.h" } #include "temper.h" #include <stdlib.h> #include <assert.h> #include <math.h> /* * Temper: (constructor) * * create a new temperature structure from the temperature * array provided, of length n (duplicating the array) */ Temper::Temper(double *itemps, double *tprobs, unsigned int numit, double c0, double n0, IT_LAMBDA it_lambda) { /* copy the inv-temperature vector */ this->itemps = new_dup_vector(itemps, numit); this->numit = numit; /* stochastic approximation parameters */ this->c0 = c0; this->n0 = n0; this->doSA = false; /* must turn on in Model:: */ /* combination method */ this->it_lambda = it_lambda; /* either assign uniform probs if tprobs is NULL */ if(tprobs == NULL) { this->tprobs = ones(numit, 1.0/numit); } else { /* or copy them and make sure they're positive and normalized */ this->tprobs = new_dup_vector(tprobs, numit); Normalize(); } /* init itemp-location pointer -- find closest to 1.0 */ this->k = 0; double mindist = fabs(this->itemps[0] - 1.0); for(unsigned int i=1; i<this->numit; i++) { double dist = fabs(this->itemps[i] - 1.0); if(dist < mindist) { mindist = dist; this->k = i; } } /* set new (proposed) temperature to "null" */ this->knew = -1; /* set iteration number for stoch_approx to zero */ this->cnt = 1; /* zero-out a new counter for each temperature */ this->tcounts = new_ones_uivector(this->numit, 0); this->cum_tcounts = new_ones_uivector(this->numit, 0); } /* * Temper: (constructor) * * create a new temperature structure from the temperature * array provided, the first entry of the array is n. If n * is not zero, then c0 and n0 follow, and then n inverse * temperatures and n (possibly unnormalized) probabilities. */ Temper::Temper(double *ditemps) { /* read the number of inverse temperatures */ assert(ditemps[0] >= 0); numit = (unsigned int) ditemps[0]; /* copy c0 and n0 */ c0 = ditemps[1]; n0 = ditemps[2]; assert(c0 >= 0 && n0 >= 0); doSA = false; /* must turn on in Model:: */ /* copy the inv-temperature vector and probs */ itemps = new_dup_vector(&(ditemps[3]), numit); tprobs = new_dup_vector(&(ditemps[3+numit]), numit); /* normalize the probs and then check that they're positive */ Normalize(); /* combination method */ int dlambda = (unsigned int) ditemps[3+3*numit]; switch((unsigned int) dlambda) { case 1: it_lambda = OPT; break; case 2: it_lambda = NAIVE; break; case 3: it_lambda = ST; break; default: error("IT lambda = %d unknown\n", dlambda); } /* init itemp-location pointer -- find closest to 1.0 */ k = 0; double mindist = fabs(itemps[0] - 1.0); for(unsigned int i=1; i<numit; i++) { double dist = fabs(itemps[i] - 1.0); if(dist < mindist) { mindist = dist; k = i; } } /* set new (proposed) temperature to "null" */ knew = -1; /* set iteration number for stoch_approx to zero */ cnt = 1; /* initialize the cumulative counter for each temperature */ cum_tcounts = new_ones_uivector(numit, 0); for(unsigned int i=0; i<numit; i++) cum_tcounts[i] = (unsigned int) ditemps[3+2*numit+i]; /* initialize the frequencies in each temperature to a a constant determined by the acerave cum_tcounts */ tcounts = new_ones_uivector(numit, meanuiv(cum_tcounts, numit)); } /* * Temper: (duplicator/constructor) * * create a new temperature structure from the temperature * array provided, of length n (duplicating the array) */ Temper::Temper(Temper *temp) { assert(temp); itemps = new_dup_vector(temp->itemps, temp->numit); tprobs = new_dup_vector(temp->tprobs, temp->numit); tcounts = new_dup_uivector(temp->tcounts, temp->numit); cum_tcounts = new_dup_uivector(temp->cum_tcounts, temp->numit); numit = temp->numit; k = temp->k; knew = temp->knew; c0 = temp->c0; n0 = temp->n0; doSA = false; cnt = temp->cnt; } /* * Temper: (assignment operator) * * copy new temperature structure from the temperature * array provided, of length n (duplicating the array) */ Temper& Temper::operator=(const Temper &t) { Temper *temp = (Temper*) &t; assert(numit == temp->numit); dupv(itemps, temp->itemps, numit); dupv(tprobs, temp->tprobs, numit); dupuiv(tcounts, temp->tcounts, numit); dupuiv(cum_tcounts, temp->cum_tcounts, numit); numit = temp->numit; k = temp->k; knew = temp->knew; c0 = temp->c0; n0 = temp->n0; cnt = temp->cnt; doSA = temp->doSA; return *this; } /* * ~Temper: (destructor) * * free the memory and contents of an itemp * structure */ Temper::~Temper(void) { free(itemps); free(tprobs); free(tcounts); free(cum_tcounts); } /* * Itemp: * * return the actual inv-temperature currently * being used */ double Temper::Itemp(void) { return itemps[k]; } /* * Prob: * * return the probability inv-temperature currently * being used */ double Temper::Prob(void) { return tprobs[k]; } /* * ProposedProb: * * return the probability inv-temperature proposed */ double Temper::ProposedProb(void) { return tprobs[knew]; } /* * Propose: * * Uniform Random-walk proposal for annealed importance sampling * temperature in the continuous interval (0,1) with bandwidth * of 2*0.1. Returns proposal, and passes back forward and * backward probs */ double Temper::Propose(double *q_fwd, double *q_bak, void *state) { /* sanity check */ if(knew != -1) warning("did not accept or reject last proposed itemp"); if(k == 0) { if(numit == 1) { /* only one temp avail */ knew = k; *q_fwd = *q_bak = 1.0; } else { /* knew should be k+1 */ knew = k + 1; *q_fwd = 1.0; if(knew == (int) (numit - 1)) *q_bak = 1.0; else *q_bak = 0.5; } } else { /* k > 0 */ /* k == numit; means k_new = k-1 */ if(k == (int) (numit - 1)) { assert(numit > 1); knew = k - 1; *q_fwd = 1.0; if(knew == 0) *q_bak = 1.0; else *q_bak = 0.5; } else { /* most general case */ if(runi(state) < 0.5) { knew = k - 1; *q_fwd = 0.5; if(knew == (int) (numit - 1)) *q_bak = 1.0; else *q_bak = 0.5; } else { knew = k + 1; *q_fwd = 0.5; if(knew == 0) *q_bak = 1.0; else *q_bak = 0.5; } } } return itemps[knew]; } /* * Keep: * * keep a proposed itemp, double-checking that the itemp_new * argument actually was the last proposed inv-temperature */ void Temper::Keep(double itemp_new, bool burnin) { assert(knew >= 0); assert(itemp_new == itemps[knew]); k = knew; knew = -1; /* update the observation counts only whilest not doing SA and not doing burn in rounds */ if(!(doSA || burnin)) { (tcounts[k])++; (cum_tcounts[k])++; } } /* * Reject: * * reject a proposed itemp, double-checking that the itemp_new * argument actually was the last proposed inv-temperature -- * this actually amounts to simply updating the count of the * kept (old) temperature */ void Temper::Reject(double itemp_new, bool burnin) { assert(itemp_new == itemps[knew]); /* do not update itemps->k, but do update the counter for the old (kept) temperature */ knew = -1; /* update the observation counts only whilest not doing SA and not doing burn in rounds */ if(!(doSA || burnin)) { (tcounts[k])++; (cum_tcounts[k])++; } } /* * UpdatePrior: * * re-create the prior distribution of the temperature * ladder by dividing by the normalization constant, i.e., * adjust by the "observation counts" -- returns a pointer * to the probabilities */ double* Temper::UpdatePrior(void) { /* do nothing if there is only one temperature */ if(numit == 1) return tprobs; /* first find the min (non-zero) tcounts */ unsigned int min = tcounts[0]; for(unsigned int i=1; i<numit; i++) { if(min == 0 || (tcounts[i] != 0 && tcounts[i] < min)) min = tcounts[i]; } assert(min != 0); /* now adjust the probabilities */ double sum = 0.0; for(unsigned int i=0; i<numit; i++) { if(tcounts[i] == 0) tcounts[i] = min; tprobs[i] /= tcounts[i]; sum += tprobs[i]; } /* now normalize the probabilities */ Normalize(); /* mean-out the tcounts (observation counts) vector */ uiones(tcounts, numit, meanuiv(cum_tcounts, numit)); /* return a pointer to the (new) prior probs */ return tprobs; } /* * UpdateTprobs: * * copy the passed in tprobs vector, no questions asked. */ void Temper::UpdatePrior(double *tprobs, unsigned int numit) { assert(this->numit == numit); dupv(this->tprobs, tprobs, numit); } /* * CopyPrior: * * write the tprior into the double vector provided, in the * same format as the double-input vector to the * Temper::Temper(double*) constructor */ void Temper::CopyPrior(double *dparams) { assert(this->numit == (unsigned int) dparams[0]); /* copy the pseudoprior */ dupv(&(dparams[3+numit]), tprobs, numit); /* copy the integer counts in each temperature */ for(unsigned int i=0; i<numit; i++) dparams[3+2*numit+i] = (double) cum_tcounts[i]; } /* * StochApprox: * * update the pseudo-prior via the stochastic approximation * suggested by Geyer & Thompson */ void Temper::StochApprox(void) { /* check if stochastic approximation is currently turned on */ if(doSA == false) return; /* adjust each of the probs in the pseudo-prior */ assert(cnt >= 1); for(unsigned int i=0; i<numit; i++) { if((int)i == k) { tprobs[i] = exp(log(tprobs[i]) - c0 / ((double)(cnt) + n0)); } else { tprobs[i] = exp(log(tprobs[i])+ c0 / (((double)numit)*((double)(cnt) + n0))); } } /* update the count of the number of SA rounds */ cnt++; } /* * LambdaOpt: * * adjust the weight distribution w[n] using richard's * principled method of minimization by lagrange multipliers * thus producing a lambda--adjusted weight distribution */ double Temper::LambdaOpt(double *w, double *itemp, unsigned int wlen, double *essd, unsigned int verb) { unsigned int len; unsigned int tlen = 0; double tess = 0.0; double eisum = 0.0; /* allocate space for the lambdas, etc */ double *lambda = new_zero_vector(numit); double *W = new_zero_vector(numit); double *w2sum = new_zero_vector(numit); /* for pretty printing */ if(verb >= 1) myprintf(mystdout, "\neffective sample sizes:\n"); /* for each temperature */ for(unsigned int i=0; i<numit; i++) { /* get the weights at the i-th temperature */ int *p = find(itemp, wlen, EQ, itemps[i], &len); /* nothing to do if no samples were taken at this tempereature -- but this is bad! */ double ei = 0; if(len == 0) { essd[i] = essd[numit + i] = 0; continue; } /* collect the weights at the i-th temperature */ double *wi = new_sub_vector(p, w, len); /* calculate Wi=sum(wi) */ W[i] = sumv(wi, len); w2sum[i] = sum_fv(wi, len, sq); /* calculate the ess of the weights of the i-th temperature */ if(W[i] > 0 && w2sum[i] > 0) { /* compute ess and max weight for this temp */ lambda[i] = sq(W[i]) / w2sum[i]; /* check for numerical problems and (if none) calculate the within temperature ESS */ if(!R_FINITE(lambda[i])) { lambda[i] = 0; ei = 0; } else ei = calc_ess(wi, len); /* sum up the within temperature ESS's */ eisum += ei*len; } else { W[i] = 1; } /* doesn't matter since ei=0 */ /* keep track of sum of lengths and ess so far */ tlen += len; tess += len * ei; /* save individual ess to the (double) output essd vector */ essd[i] = len; essd[numit + i] = ei*len; /* print individual ess */ if(verb >= 1) myprintf(mystdout, "%d: itemp=%g, len=%d, ess=%g\n", //, sw=%g\n", i, itemps[i], len, ei*len); //, sumv(wi, len)); /* clean up */ free(wi); free(p); } /* normalize the lambdas */ double gamma_sum = sumv(lambda, numit); scalev(lambda, numit, 1.0/gamma_sum); /* for each temperature, calculate the adjusted weights */ for(unsigned int i=0; i<numit; i++) { /* get the weights at the i-th temperature */ int *p = find(itemp, wlen, EQ, itemps[i], &len); /* nothing to do if no samples were taken at this tempereature -- but this is bad! */ if(len == 0) continue; /* collect the weights at the i-th temperature */ double *wi = new_sub_vector(p, w, len); /* multiply by numerator of lambda-star */ scalev(wi, len, lambda[i]/W[i]); /* copy the mofified weights into the big weight vector */ copy_p_vector(w, p, wi, len); /* clean up */ free(p); free(wi); } /* print totals */ if(verb >= 1) { myprintf(mystdout, "total: len=%d, ess.sum=%g, ess(w)=%g\n", tlen, tess, ((double)wlen)*calc_ess(w,wlen)); double lce = wlen*(wlen-1.0)*gamma_sum/(sq(wlen)-gamma_sum); if(ISNAN(lce)) lce = 1; myprintf(mystdout, "lambda-combined ess=%g\n", lce); } /* clean up */ free(lambda); free(W); free(w2sum); /* return the overall effective sample size */ return(((double)wlen)*calc_ess(w, wlen)); } /* * EachESS: * * calculate the effective sample size at each temperature */ void Temper::EachESS(double *w, double *itemp, unsigned int wlen, double *essd) { /* for each temperature */ for(unsigned int i=0; i<numit; i++) { /* get the weights at the i-th temperature */ unsigned int len; int *p = find(itemp, wlen, EQ, itemps[i], &len); /* nothing to do if no samples were taken at this tempereature -- but this is bad! */ if(len == 0) { essd[i] = essd[numit + i] = 0; continue; } /* collect the weights at the i-th temperature */ double *wi = new_sub_vector(p, w, len); /* calculate the ith ess */ double ei = calc_ess(wi, len); /* save individual ess to the (double) output essd vector */ essd[i] = len; essd[numit + i] = ei*len; /* clean up */ free(wi); free(p); } } /* * LambdaST: * * adjust the weight distribution w[n] to implement Simulated Tempering -- * that is, find the w corresponding to itemps == 1, and set the rest to * zero, thus producing a lambda--adjusted weight distribution */ double Temper::LambdaST(double *w, double *itemp, unsigned int wlen, unsigned int verb) { /* ST not doable */ if(itemps[0] != 1.0) warning("itemps[0]=%d != 1.0", itemps[0]); /* get the weights at the i-th temperature */ unsigned int len; int *p = find(itemp, wlen, EQ, itemps[0], &len); /* nothing to do if no samples were taken at this tempereature -- but this is bad! */ if(len == 0) { zerov(w, wlen); return 0.0; } /* collect the weights at the i-th temperature */ double *wi = new_sub_vector(p, w, len); /* calculate Wi=sum(wi) */ double Wi = sumv(wi, len); /* multiply by numerator of lambda-star */ scalev(wi, len, 1.0/Wi); /* zero-out the weight vector */ zerov(w, wlen); /* copy the mofified weights into the big weight vector */ copy_p_vector(w, p, wi, len); /* print totals */ if(verb >= 1) myprintf(mystdout, "\nST sample size=%d\n", len); /* return the overall effective sample size */ return((double) len); } /* * LambdaNaive: * * adjust the weight distribution w[n] via Naive Importance Tempering; * that is, disregard demperature, and just normalize the weight vector */ double Temper::LambdaNaive(double *w, unsigned int wlen, unsigned int verb) { /* calculate Wi=sum(wi) */ double W = sumv(w, wlen); if(W == 0) return 0.0; /* multiply by numerator of lambda-star */ scalev(w, wlen, 1.0/W); /* calculate ESS */ double ess = ((double)wlen)*calc_ess(w, wlen); /* print totals */ if(verb >= 1) myprintf(mystdout, "\nnaive IT ess=%g\n", ess); /* return the overall effective sample size */ return(ess); } /* * N: * * get number of temperatures n: */ unsigned int Temper::Numit(void) { return numit; } /* * DoStochApprox: * * true if both c0 and n0 are non-zero, then we * are doing StochApprox */ bool Temper::DoStochApprox(void) { if(c0 > 0 && n0 > 0 && numit > 1) return true; else return false; } /* * IS_ST_or_IS: * * return true importance tempering, simulated tempering, * or importance sampling is supported by the current * Tempering distribution */ bool Temper::IT_ST_or_IS(void) { if(numit > 1 || itemps[0] != 1.0) return true; else return false; } /* * IT_or_ST: * * return true importance tempering or simulated tempering, * is supported by the current Tempering distribution */ bool Temper::IT_or_ST(void) { if(numit > 1) return true; else return false; } /* * IS: * * return true if importance sampling (only) is supported * by the current Tempering distribution */ bool Temper::IS(void) { if(numit == 1 && itemps[0] != 1.0) return true; else return false; } /* * Itemps: * * return the temperature ladder */ double* Temper::Itemps(void) { return itemps; } /* * C0: * * return the c0 (SA) paramete */ double Temper::C0(void) { return c0; } /* * N0: * * return the n0 (SA) paramete */ double Temper::N0(void) { return n0; } /* * ResetSA: * * reset the stochastic approximation by setting * the counter to 1, and turn SA on */ void Temper::ResetSA(void) { doSA = true; cnt = 1; } /* * StopSA: * * turn off stochastic approximation */ void Temper::StopSA(void) { doSA = false; } /* * ITLambda: * * choose a method for importance tempering based on the it_lambda * variable, call that method, passing back the lambda-adjusted * weights w, and returning a calculation of ESSw */ double Temper::LambdaIT(double *w, double *itemp, unsigned int R, double *essd, unsigned int verb) { /* sanity check that it makes sense to adjust weights */ assert(IT_ST_or_IS()); double ess = 0; switch(it_lambda) { case OPT: ess = LambdaOpt(w, itemp, R, essd, verb); break; case NAIVE: ess = LambdaNaive(w, R, verb); EachESS(w, itemp, R, essd); break; case ST: ess = LambdaST(w, itemp, R, verb); EachESS(w, itemp, R, essd); break; default: error("bad it_lambda\n"); } return ess; } /* * Print: * * write information about the IT configuration * out to the supplied file */ void Temper::Print(FILE *outfile) { /* print the importance tempring information */ if(IS()) myprintf(outfile, "IS with inv-temp %g\n", itemps[0]); else if(IT_or_ST()) { switch(it_lambda) { case OPT: myprintf(outfile, "IT: optimal"); break; case NAIVE: myprintf(outfile, "IT: naive"); break; case ST: myprintf(outfile, "IT: implementing ST"); break; } myprintf(outfile, " on %d-rung ladder\n", numit); if(DoStochApprox()) myprintf(outfile, " with stoch approx\n"); else myprintf(outfile, "\n"); } } /* * AppendLadder: * * append tprobs and tcounts to a file with the name * provided */ void Temper::AppendLadder(const char* file_str) { FILE *LOUT = fopen(file_str, "a"); printVector(tprobs, numit, LOUT, MACHINE); printUIVector(tcounts, numit, LOUT); fclose(LOUT); } /* * Normalize: * * normalize the pseudo-prior (tprobs) and * check that all probs are positive */ void Temper::Normalize(void) { scalev(tprobs, numit, 1.0/sumv(tprobs, numit)); for(unsigned int i=0; i<numit; i++) assert(tprobs[i] > 0); } /* * ess: * * effective sample size calculation for imporancnce * sampling -- per unit sample. To get the full sample * size, just multiply by n */ double calc_ess(double *w, unsigned int n) { if(n == 0) return 0; else { double cv2 = calc_cv2(w,n); if(ISNAN(cv2) || !R_FINITE(cv2)) { // warning("nan or inf found in cv2, probably due to zero weights"); return 0.0; } else return(1.0/(1.0+cv2)); } } /* * cv2: * * calculate the coefficient of variation, used here * to find the variance of a sample of unnormalized * importance sampling weights */ double calc_cv2(double *w, unsigned int n) { double mw; wmean_of_rows(&mw, &w, 1, n, NULL); double sum = 0; if(n == 1) return 0.0; for(unsigned int i=0; i<n; i++) sum += sq(w[i] - mw); return sum/((((double)n) - 1.0)*sq(mw)); }
[ "liutianchi@yahoo.com" ]
liutianchi@yahoo.com
66159bc3e47a4ff4502f507ed98fe086fb59c68f
ca978c8ad2a77677635df5042aa9139a727172dc
/src/backend/src/generated/follow_me/follow_me.pb.h
f7641d02ea4dfbf7381a190baf59b6514bc2443a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hrnbot/MAVSDK
e5541d60be3b32bf12bf0ea5afefc91a27b810a9
68ab0c5d50bb2e7e8f1e7ce565603f9e3f2c772f
refs/heads/master
2023-01-05T17:58:22.994430
2020-10-12T10:59:14
2020-10-12T10:59:14
287,504,011
0
0
BSD-3-Clause
2020-10-07T10:06:05
2020-08-14T10:11:29
C++
UTF-8
C++
false
true
131,215
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: follow_me/follow_me.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_follow_5fme_2ffollow_5fme_2eproto #define GOOGLE_PROTOBUF_INCLUDED_follow_5fme_2ffollow_5fme_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3011000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3011002 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> #include "mavsdk_options.pb.h" // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_follow_5fme_2ffollow_5fme_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_follow_5fme_2ffollow_5fme_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[17] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_follow_5fme_2ffollow_5fme_2eproto; namespace mavsdk { namespace rpc { namespace follow_me { class Config; class ConfigDefaultTypeInternal; extern ConfigDefaultTypeInternal _Config_default_instance_; class FollowMeResult; class FollowMeResultDefaultTypeInternal; extern FollowMeResultDefaultTypeInternal _FollowMeResult_default_instance_; class GetConfigRequest; class GetConfigRequestDefaultTypeInternal; extern GetConfigRequestDefaultTypeInternal _GetConfigRequest_default_instance_; class GetConfigResponse; class GetConfigResponseDefaultTypeInternal; extern GetConfigResponseDefaultTypeInternal _GetConfigResponse_default_instance_; class GetLastLocationRequest; class GetLastLocationRequestDefaultTypeInternal; extern GetLastLocationRequestDefaultTypeInternal _GetLastLocationRequest_default_instance_; class GetLastLocationResponse; class GetLastLocationResponseDefaultTypeInternal; extern GetLastLocationResponseDefaultTypeInternal _GetLastLocationResponse_default_instance_; class IsActiveRequest; class IsActiveRequestDefaultTypeInternal; extern IsActiveRequestDefaultTypeInternal _IsActiveRequest_default_instance_; class IsActiveResponse; class IsActiveResponseDefaultTypeInternal; extern IsActiveResponseDefaultTypeInternal _IsActiveResponse_default_instance_; class SetConfigRequest; class SetConfigRequestDefaultTypeInternal; extern SetConfigRequestDefaultTypeInternal _SetConfigRequest_default_instance_; class SetConfigResponse; class SetConfigResponseDefaultTypeInternal; extern SetConfigResponseDefaultTypeInternal _SetConfigResponse_default_instance_; class SetTargetLocationRequest; class SetTargetLocationRequestDefaultTypeInternal; extern SetTargetLocationRequestDefaultTypeInternal _SetTargetLocationRequest_default_instance_; class SetTargetLocationResponse; class SetTargetLocationResponseDefaultTypeInternal; extern SetTargetLocationResponseDefaultTypeInternal _SetTargetLocationResponse_default_instance_; class StartRequest; class StartRequestDefaultTypeInternal; extern StartRequestDefaultTypeInternal _StartRequest_default_instance_; class StartResponse; class StartResponseDefaultTypeInternal; extern StartResponseDefaultTypeInternal _StartResponse_default_instance_; class StopRequest; class StopRequestDefaultTypeInternal; extern StopRequestDefaultTypeInternal _StopRequest_default_instance_; class StopResponse; class StopResponseDefaultTypeInternal; extern StopResponseDefaultTypeInternal _StopResponse_default_instance_; class TargetLocation; class TargetLocationDefaultTypeInternal; extern TargetLocationDefaultTypeInternal _TargetLocation_default_instance_; } // namespace follow_me } // namespace rpc } // namespace mavsdk PROTOBUF_NAMESPACE_OPEN template<> ::mavsdk::rpc::follow_me::Config* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::Config>(Arena*); template<> ::mavsdk::rpc::follow_me::FollowMeResult* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::FollowMeResult>(Arena*); template<> ::mavsdk::rpc::follow_me::GetConfigRequest* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::GetConfigRequest>(Arena*); template<> ::mavsdk::rpc::follow_me::GetConfigResponse* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::GetConfigResponse>(Arena*); template<> ::mavsdk::rpc::follow_me::GetLastLocationRequest* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::GetLastLocationRequest>(Arena*); template<> ::mavsdk::rpc::follow_me::GetLastLocationResponse* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::GetLastLocationResponse>(Arena*); template<> ::mavsdk::rpc::follow_me::IsActiveRequest* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::IsActiveRequest>(Arena*); template<> ::mavsdk::rpc::follow_me::IsActiveResponse* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::IsActiveResponse>(Arena*); template<> ::mavsdk::rpc::follow_me::SetConfigRequest* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::SetConfigRequest>(Arena*); template<> ::mavsdk::rpc::follow_me::SetConfigResponse* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::SetConfigResponse>(Arena*); template<> ::mavsdk::rpc::follow_me::SetTargetLocationRequest* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::SetTargetLocationRequest>(Arena*); template<> ::mavsdk::rpc::follow_me::SetTargetLocationResponse* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::SetTargetLocationResponse>(Arena*); template<> ::mavsdk::rpc::follow_me::StartRequest* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::StartRequest>(Arena*); template<> ::mavsdk::rpc::follow_me::StartResponse* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::StartResponse>(Arena*); template<> ::mavsdk::rpc::follow_me::StopRequest* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::StopRequest>(Arena*); template<> ::mavsdk::rpc::follow_me::StopResponse* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::StopResponse>(Arena*); template<> ::mavsdk::rpc::follow_me::TargetLocation* Arena::CreateMaybeMessage<::mavsdk::rpc::follow_me::TargetLocation>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace mavsdk { namespace rpc { namespace follow_me { enum Config_FollowDirection : int { Config_FollowDirection_FOLLOW_DIRECTION_NONE = 0, Config_FollowDirection_FOLLOW_DIRECTION_BEHIND = 1, Config_FollowDirection_FOLLOW_DIRECTION_FRONT = 2, Config_FollowDirection_FOLLOW_DIRECTION_FRONT_RIGHT = 3, Config_FollowDirection_FOLLOW_DIRECTION_FRONT_LEFT = 4, Config_FollowDirection_Config_FollowDirection_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::min(), Config_FollowDirection_Config_FollowDirection_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::max() }; bool Config_FollowDirection_IsValid(int value); constexpr Config_FollowDirection Config_FollowDirection_FollowDirection_MIN = Config_FollowDirection_FOLLOW_DIRECTION_NONE; constexpr Config_FollowDirection Config_FollowDirection_FollowDirection_MAX = Config_FollowDirection_FOLLOW_DIRECTION_FRONT_LEFT; constexpr int Config_FollowDirection_FollowDirection_ARRAYSIZE = Config_FollowDirection_FollowDirection_MAX + 1; const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Config_FollowDirection_descriptor(); template<typename T> inline const std::string& Config_FollowDirection_Name(T enum_t_value) { static_assert(::std::is_same<T, Config_FollowDirection>::value || ::std::is_integral<T>::value, "Incorrect type passed to function Config_FollowDirection_Name."); return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( Config_FollowDirection_descriptor(), enum_t_value); } inline bool Config_FollowDirection_Parse( const std::string& name, Config_FollowDirection* value) { return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<Config_FollowDirection>( Config_FollowDirection_descriptor(), name, value); } enum FollowMeResult_Result : int { FollowMeResult_Result_RESULT_UNKNOWN = 0, FollowMeResult_Result_RESULT_SUCCESS = 1, FollowMeResult_Result_RESULT_NO_SYSTEM = 2, FollowMeResult_Result_RESULT_CONNECTION_ERROR = 3, FollowMeResult_Result_RESULT_BUSY = 4, FollowMeResult_Result_RESULT_COMMAND_DENIED = 5, FollowMeResult_Result_RESULT_TIMEOUT = 6, FollowMeResult_Result_RESULT_NOT_ACTIVE = 7, FollowMeResult_Result_RESULT_SET_CONFIG_FAILED = 8, FollowMeResult_Result_FollowMeResult_Result_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::min(), FollowMeResult_Result_FollowMeResult_Result_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::max() }; bool FollowMeResult_Result_IsValid(int value); constexpr FollowMeResult_Result FollowMeResult_Result_Result_MIN = FollowMeResult_Result_RESULT_UNKNOWN; constexpr FollowMeResult_Result FollowMeResult_Result_Result_MAX = FollowMeResult_Result_RESULT_SET_CONFIG_FAILED; constexpr int FollowMeResult_Result_Result_ARRAYSIZE = FollowMeResult_Result_Result_MAX + 1; const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FollowMeResult_Result_descriptor(); template<typename T> inline const std::string& FollowMeResult_Result_Name(T enum_t_value) { static_assert(::std::is_same<T, FollowMeResult_Result>::value || ::std::is_integral<T>::value, "Incorrect type passed to function FollowMeResult_Result_Name."); return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( FollowMeResult_Result_descriptor(), enum_t_value); } inline bool FollowMeResult_Result_Parse( const std::string& name, FollowMeResult_Result* value) { return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<FollowMeResult_Result>( FollowMeResult_Result_descriptor(), name, value); } // =================================================================== class Config : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.Config) */ { public: Config(); virtual ~Config(); Config(const Config& from); Config(Config&& from) noexcept : Config() { *this = ::std::move(from); } inline Config& operator=(const Config& from) { CopyFrom(from); return *this; } inline Config& operator=(Config&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const Config& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const Config* internal_default_instance() { return reinterpret_cast<const Config*>( &_Config_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(Config& a, Config& b) { a.Swap(&b); } inline void Swap(Config* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline Config* New() const final { return CreateMaybeMessage<Config>(nullptr); } Config* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<Config>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Config& from); void MergeFrom(const Config& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Config* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.Config"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- typedef Config_FollowDirection FollowDirection; static constexpr FollowDirection FOLLOW_DIRECTION_NONE = Config_FollowDirection_FOLLOW_DIRECTION_NONE; static constexpr FollowDirection FOLLOW_DIRECTION_BEHIND = Config_FollowDirection_FOLLOW_DIRECTION_BEHIND; static constexpr FollowDirection FOLLOW_DIRECTION_FRONT = Config_FollowDirection_FOLLOW_DIRECTION_FRONT; static constexpr FollowDirection FOLLOW_DIRECTION_FRONT_RIGHT = Config_FollowDirection_FOLLOW_DIRECTION_FRONT_RIGHT; static constexpr FollowDirection FOLLOW_DIRECTION_FRONT_LEFT = Config_FollowDirection_FOLLOW_DIRECTION_FRONT_LEFT; static inline bool FollowDirection_IsValid(int value) { return Config_FollowDirection_IsValid(value); } static constexpr FollowDirection FollowDirection_MIN = Config_FollowDirection_FollowDirection_MIN; static constexpr FollowDirection FollowDirection_MAX = Config_FollowDirection_FollowDirection_MAX; static constexpr int FollowDirection_ARRAYSIZE = Config_FollowDirection_FollowDirection_ARRAYSIZE; static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FollowDirection_descriptor() { return Config_FollowDirection_descriptor(); } template<typename T> static inline const std::string& FollowDirection_Name(T enum_t_value) { static_assert(::std::is_same<T, FollowDirection>::value || ::std::is_integral<T>::value, "Incorrect type passed to function FollowDirection_Name."); return Config_FollowDirection_Name(enum_t_value); } static inline bool FollowDirection_Parse(const std::string& name, FollowDirection* value) { return Config_FollowDirection_Parse(name, value); } // accessors ------------------------------------------------------- enum : int { kMinHeightMFieldNumber = 1, kFollowDistanceMFieldNumber = 2, kFollowDirectionFieldNumber = 3, kResponsivenessFieldNumber = 4, }; // float min_height_m = 1 [(.mavsdk.options.default_value) = "8.0"]; void clear_min_height_m(); float min_height_m() const; void set_min_height_m(float value); private: float _internal_min_height_m() const; void _internal_set_min_height_m(float value); public: // float follow_distance_m = 2 [(.mavsdk.options.default_value) = "8.0"]; void clear_follow_distance_m(); float follow_distance_m() const; void set_follow_distance_m(float value); private: float _internal_follow_distance_m() const; void _internal_set_follow_distance_m(float value); public: // .mavsdk.rpc.follow_me.Config.FollowDirection follow_direction = 3; void clear_follow_direction(); ::mavsdk::rpc::follow_me::Config_FollowDirection follow_direction() const; void set_follow_direction(::mavsdk::rpc::follow_me::Config_FollowDirection value); private: ::mavsdk::rpc::follow_me::Config_FollowDirection _internal_follow_direction() const; void _internal_set_follow_direction(::mavsdk::rpc::follow_me::Config_FollowDirection value); public: // float responsiveness = 4 [(.mavsdk.options.default_value) = "0.5"]; void clear_responsiveness(); float responsiveness() const; void set_responsiveness(float value); private: float _internal_responsiveness() const; void _internal_set_responsiveness(float value); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.Config) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; float min_height_m_; float follow_distance_m_; int follow_direction_; float responsiveness_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class TargetLocation : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.TargetLocation) */ { public: TargetLocation(); virtual ~TargetLocation(); TargetLocation(const TargetLocation& from); TargetLocation(TargetLocation&& from) noexcept : TargetLocation() { *this = ::std::move(from); } inline TargetLocation& operator=(const TargetLocation& from) { CopyFrom(from); return *this; } inline TargetLocation& operator=(TargetLocation&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const TargetLocation& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const TargetLocation* internal_default_instance() { return reinterpret_cast<const TargetLocation*>( &_TargetLocation_default_instance_); } static constexpr int kIndexInFileMessages = 1; friend void swap(TargetLocation& a, TargetLocation& b) { a.Swap(&b); } inline void Swap(TargetLocation* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline TargetLocation* New() const final { return CreateMaybeMessage<TargetLocation>(nullptr); } TargetLocation* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<TargetLocation>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const TargetLocation& from); void MergeFrom(const TargetLocation& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TargetLocation* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.TargetLocation"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kLatitudeDegFieldNumber = 1, kLongitudeDegFieldNumber = 2, kAbsoluteAltitudeMFieldNumber = 3, kVelocityXMSFieldNumber = 4, kVelocityYMSFieldNumber = 5, kVelocityZMSFieldNumber = 6, }; // double latitude_deg = 1 [(.mavsdk.options.default_value) = "NaN"]; void clear_latitude_deg(); double latitude_deg() const; void set_latitude_deg(double value); private: double _internal_latitude_deg() const; void _internal_set_latitude_deg(double value); public: // double longitude_deg = 2 [(.mavsdk.options.default_value) = "NaN"]; void clear_longitude_deg(); double longitude_deg() const; void set_longitude_deg(double value); private: double _internal_longitude_deg() const; void _internal_set_longitude_deg(double value); public: // float absolute_altitude_m = 3 [(.mavsdk.options.default_value) = "NaN"]; void clear_absolute_altitude_m(); float absolute_altitude_m() const; void set_absolute_altitude_m(float value); private: float _internal_absolute_altitude_m() const; void _internal_set_absolute_altitude_m(float value); public: // float velocity_x_m_s = 4 [(.mavsdk.options.default_value) = "NaN"]; void clear_velocity_x_m_s(); float velocity_x_m_s() const; void set_velocity_x_m_s(float value); private: float _internal_velocity_x_m_s() const; void _internal_set_velocity_x_m_s(float value); public: // float velocity_y_m_s = 5 [(.mavsdk.options.default_value) = "NaN"]; void clear_velocity_y_m_s(); float velocity_y_m_s() const; void set_velocity_y_m_s(float value); private: float _internal_velocity_y_m_s() const; void _internal_set_velocity_y_m_s(float value); public: // float velocity_z_m_s = 6 [(.mavsdk.options.default_value) = "NaN"]; void clear_velocity_z_m_s(); float velocity_z_m_s() const; void set_velocity_z_m_s(float value); private: float _internal_velocity_z_m_s() const; void _internal_set_velocity_z_m_s(float value); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.TargetLocation) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; double latitude_deg_; double longitude_deg_; float absolute_altitude_m_; float velocity_x_m_s_; float velocity_y_m_s_; float velocity_z_m_s_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class GetConfigRequest : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.GetConfigRequest) */ { public: GetConfigRequest(); virtual ~GetConfigRequest(); GetConfigRequest(const GetConfigRequest& from); GetConfigRequest(GetConfigRequest&& from) noexcept : GetConfigRequest() { *this = ::std::move(from); } inline GetConfigRequest& operator=(const GetConfigRequest& from) { CopyFrom(from); return *this; } inline GetConfigRequest& operator=(GetConfigRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const GetConfigRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const GetConfigRequest* internal_default_instance() { return reinterpret_cast<const GetConfigRequest*>( &_GetConfigRequest_default_instance_); } static constexpr int kIndexInFileMessages = 2; friend void swap(GetConfigRequest& a, GetConfigRequest& b) { a.Swap(&b); } inline void Swap(GetConfigRequest* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline GetConfigRequest* New() const final { return CreateMaybeMessage<GetConfigRequest>(nullptr); } GetConfigRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<GetConfigRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const GetConfigRequest& from); void MergeFrom(const GetConfigRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GetConfigRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.GetConfigRequest"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.GetConfigRequest) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class GetConfigResponse : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.GetConfigResponse) */ { public: GetConfigResponse(); virtual ~GetConfigResponse(); GetConfigResponse(const GetConfigResponse& from); GetConfigResponse(GetConfigResponse&& from) noexcept : GetConfigResponse() { *this = ::std::move(from); } inline GetConfigResponse& operator=(const GetConfigResponse& from) { CopyFrom(from); return *this; } inline GetConfigResponse& operator=(GetConfigResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const GetConfigResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const GetConfigResponse* internal_default_instance() { return reinterpret_cast<const GetConfigResponse*>( &_GetConfigResponse_default_instance_); } static constexpr int kIndexInFileMessages = 3; friend void swap(GetConfigResponse& a, GetConfigResponse& b) { a.Swap(&b); } inline void Swap(GetConfigResponse* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline GetConfigResponse* New() const final { return CreateMaybeMessage<GetConfigResponse>(nullptr); } GetConfigResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<GetConfigResponse>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const GetConfigResponse& from); void MergeFrom(const GetConfigResponse& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GetConfigResponse* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.GetConfigResponse"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kConfigFieldNumber = 1, }; // .mavsdk.rpc.follow_me.Config config = 1; bool has_config() const; private: bool _internal_has_config() const; public: void clear_config(); const ::mavsdk::rpc::follow_me::Config& config() const; ::mavsdk::rpc::follow_me::Config* release_config(); ::mavsdk::rpc::follow_me::Config* mutable_config(); void set_allocated_config(::mavsdk::rpc::follow_me::Config* config); private: const ::mavsdk::rpc::follow_me::Config& _internal_config() const; ::mavsdk::rpc::follow_me::Config* _internal_mutable_config(); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.GetConfigResponse) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::mavsdk::rpc::follow_me::Config* config_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class SetConfigRequest : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.SetConfigRequest) */ { public: SetConfigRequest(); virtual ~SetConfigRequest(); SetConfigRequest(const SetConfigRequest& from); SetConfigRequest(SetConfigRequest&& from) noexcept : SetConfigRequest() { *this = ::std::move(from); } inline SetConfigRequest& operator=(const SetConfigRequest& from) { CopyFrom(from); return *this; } inline SetConfigRequest& operator=(SetConfigRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const SetConfigRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const SetConfigRequest* internal_default_instance() { return reinterpret_cast<const SetConfigRequest*>( &_SetConfigRequest_default_instance_); } static constexpr int kIndexInFileMessages = 4; friend void swap(SetConfigRequest& a, SetConfigRequest& b) { a.Swap(&b); } inline void Swap(SetConfigRequest* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline SetConfigRequest* New() const final { return CreateMaybeMessage<SetConfigRequest>(nullptr); } SetConfigRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<SetConfigRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const SetConfigRequest& from); void MergeFrom(const SetConfigRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SetConfigRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.SetConfigRequest"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kConfigFieldNumber = 1, }; // .mavsdk.rpc.follow_me.Config config = 1; bool has_config() const; private: bool _internal_has_config() const; public: void clear_config(); const ::mavsdk::rpc::follow_me::Config& config() const; ::mavsdk::rpc::follow_me::Config* release_config(); ::mavsdk::rpc::follow_me::Config* mutable_config(); void set_allocated_config(::mavsdk::rpc::follow_me::Config* config); private: const ::mavsdk::rpc::follow_me::Config& _internal_config() const; ::mavsdk::rpc::follow_me::Config* _internal_mutable_config(); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.SetConfigRequest) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::mavsdk::rpc::follow_me::Config* config_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class SetConfigResponse : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.SetConfigResponse) */ { public: SetConfigResponse(); virtual ~SetConfigResponse(); SetConfigResponse(const SetConfigResponse& from); SetConfigResponse(SetConfigResponse&& from) noexcept : SetConfigResponse() { *this = ::std::move(from); } inline SetConfigResponse& operator=(const SetConfigResponse& from) { CopyFrom(from); return *this; } inline SetConfigResponse& operator=(SetConfigResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const SetConfigResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const SetConfigResponse* internal_default_instance() { return reinterpret_cast<const SetConfigResponse*>( &_SetConfigResponse_default_instance_); } static constexpr int kIndexInFileMessages = 5; friend void swap(SetConfigResponse& a, SetConfigResponse& b) { a.Swap(&b); } inline void Swap(SetConfigResponse* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline SetConfigResponse* New() const final { return CreateMaybeMessage<SetConfigResponse>(nullptr); } SetConfigResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<SetConfigResponse>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const SetConfigResponse& from); void MergeFrom(const SetConfigResponse& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SetConfigResponse* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.SetConfigResponse"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kFollowMeResultFieldNumber = 1, }; // .mavsdk.rpc.follow_me.FollowMeResult follow_me_result = 1; bool has_follow_me_result() const; private: bool _internal_has_follow_me_result() const; public: void clear_follow_me_result(); const ::mavsdk::rpc::follow_me::FollowMeResult& follow_me_result() const; ::mavsdk::rpc::follow_me::FollowMeResult* release_follow_me_result(); ::mavsdk::rpc::follow_me::FollowMeResult* mutable_follow_me_result(); void set_allocated_follow_me_result(::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result); private: const ::mavsdk::rpc::follow_me::FollowMeResult& _internal_follow_me_result() const; ::mavsdk::rpc::follow_me::FollowMeResult* _internal_mutable_follow_me_result(); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.SetConfigResponse) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class IsActiveRequest : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.IsActiveRequest) */ { public: IsActiveRequest(); virtual ~IsActiveRequest(); IsActiveRequest(const IsActiveRequest& from); IsActiveRequest(IsActiveRequest&& from) noexcept : IsActiveRequest() { *this = ::std::move(from); } inline IsActiveRequest& operator=(const IsActiveRequest& from) { CopyFrom(from); return *this; } inline IsActiveRequest& operator=(IsActiveRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const IsActiveRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const IsActiveRequest* internal_default_instance() { return reinterpret_cast<const IsActiveRequest*>( &_IsActiveRequest_default_instance_); } static constexpr int kIndexInFileMessages = 6; friend void swap(IsActiveRequest& a, IsActiveRequest& b) { a.Swap(&b); } inline void Swap(IsActiveRequest* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline IsActiveRequest* New() const final { return CreateMaybeMessage<IsActiveRequest>(nullptr); } IsActiveRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<IsActiveRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const IsActiveRequest& from); void MergeFrom(const IsActiveRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(IsActiveRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.IsActiveRequest"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.IsActiveRequest) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class IsActiveResponse : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.IsActiveResponse) */ { public: IsActiveResponse(); virtual ~IsActiveResponse(); IsActiveResponse(const IsActiveResponse& from); IsActiveResponse(IsActiveResponse&& from) noexcept : IsActiveResponse() { *this = ::std::move(from); } inline IsActiveResponse& operator=(const IsActiveResponse& from) { CopyFrom(from); return *this; } inline IsActiveResponse& operator=(IsActiveResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const IsActiveResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const IsActiveResponse* internal_default_instance() { return reinterpret_cast<const IsActiveResponse*>( &_IsActiveResponse_default_instance_); } static constexpr int kIndexInFileMessages = 7; friend void swap(IsActiveResponse& a, IsActiveResponse& b) { a.Swap(&b); } inline void Swap(IsActiveResponse* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline IsActiveResponse* New() const final { return CreateMaybeMessage<IsActiveResponse>(nullptr); } IsActiveResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<IsActiveResponse>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const IsActiveResponse& from); void MergeFrom(const IsActiveResponse& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(IsActiveResponse* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.IsActiveResponse"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kIsActiveFieldNumber = 1, }; // bool is_active = 1; void clear_is_active(); bool is_active() const; void set_is_active(bool value); private: bool _internal_is_active() const; void _internal_set_is_active(bool value); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.IsActiveResponse) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; bool is_active_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class SetTargetLocationRequest : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.SetTargetLocationRequest) */ { public: SetTargetLocationRequest(); virtual ~SetTargetLocationRequest(); SetTargetLocationRequest(const SetTargetLocationRequest& from); SetTargetLocationRequest(SetTargetLocationRequest&& from) noexcept : SetTargetLocationRequest() { *this = ::std::move(from); } inline SetTargetLocationRequest& operator=(const SetTargetLocationRequest& from) { CopyFrom(from); return *this; } inline SetTargetLocationRequest& operator=(SetTargetLocationRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const SetTargetLocationRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const SetTargetLocationRequest* internal_default_instance() { return reinterpret_cast<const SetTargetLocationRequest*>( &_SetTargetLocationRequest_default_instance_); } static constexpr int kIndexInFileMessages = 8; friend void swap(SetTargetLocationRequest& a, SetTargetLocationRequest& b) { a.Swap(&b); } inline void Swap(SetTargetLocationRequest* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline SetTargetLocationRequest* New() const final { return CreateMaybeMessage<SetTargetLocationRequest>(nullptr); } SetTargetLocationRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<SetTargetLocationRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const SetTargetLocationRequest& from); void MergeFrom(const SetTargetLocationRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SetTargetLocationRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.SetTargetLocationRequest"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kLocationFieldNumber = 1, }; // .mavsdk.rpc.follow_me.TargetLocation location = 1; bool has_location() const; private: bool _internal_has_location() const; public: void clear_location(); const ::mavsdk::rpc::follow_me::TargetLocation& location() const; ::mavsdk::rpc::follow_me::TargetLocation* release_location(); ::mavsdk::rpc::follow_me::TargetLocation* mutable_location(); void set_allocated_location(::mavsdk::rpc::follow_me::TargetLocation* location); private: const ::mavsdk::rpc::follow_me::TargetLocation& _internal_location() const; ::mavsdk::rpc::follow_me::TargetLocation* _internal_mutable_location(); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.SetTargetLocationRequest) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::mavsdk::rpc::follow_me::TargetLocation* location_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class SetTargetLocationResponse : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.SetTargetLocationResponse) */ { public: SetTargetLocationResponse(); virtual ~SetTargetLocationResponse(); SetTargetLocationResponse(const SetTargetLocationResponse& from); SetTargetLocationResponse(SetTargetLocationResponse&& from) noexcept : SetTargetLocationResponse() { *this = ::std::move(from); } inline SetTargetLocationResponse& operator=(const SetTargetLocationResponse& from) { CopyFrom(from); return *this; } inline SetTargetLocationResponse& operator=(SetTargetLocationResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const SetTargetLocationResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const SetTargetLocationResponse* internal_default_instance() { return reinterpret_cast<const SetTargetLocationResponse*>( &_SetTargetLocationResponse_default_instance_); } static constexpr int kIndexInFileMessages = 9; friend void swap(SetTargetLocationResponse& a, SetTargetLocationResponse& b) { a.Swap(&b); } inline void Swap(SetTargetLocationResponse* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline SetTargetLocationResponse* New() const final { return CreateMaybeMessage<SetTargetLocationResponse>(nullptr); } SetTargetLocationResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<SetTargetLocationResponse>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const SetTargetLocationResponse& from); void MergeFrom(const SetTargetLocationResponse& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SetTargetLocationResponse* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.SetTargetLocationResponse"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kFollowMeResultFieldNumber = 1, }; // .mavsdk.rpc.follow_me.FollowMeResult follow_me_result = 1; bool has_follow_me_result() const; private: bool _internal_has_follow_me_result() const; public: void clear_follow_me_result(); const ::mavsdk::rpc::follow_me::FollowMeResult& follow_me_result() const; ::mavsdk::rpc::follow_me::FollowMeResult* release_follow_me_result(); ::mavsdk::rpc::follow_me::FollowMeResult* mutable_follow_me_result(); void set_allocated_follow_me_result(::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result); private: const ::mavsdk::rpc::follow_me::FollowMeResult& _internal_follow_me_result() const; ::mavsdk::rpc::follow_me::FollowMeResult* _internal_mutable_follow_me_result(); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.SetTargetLocationResponse) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class GetLastLocationRequest : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.GetLastLocationRequest) */ { public: GetLastLocationRequest(); virtual ~GetLastLocationRequest(); GetLastLocationRequest(const GetLastLocationRequest& from); GetLastLocationRequest(GetLastLocationRequest&& from) noexcept : GetLastLocationRequest() { *this = ::std::move(from); } inline GetLastLocationRequest& operator=(const GetLastLocationRequest& from) { CopyFrom(from); return *this; } inline GetLastLocationRequest& operator=(GetLastLocationRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const GetLastLocationRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const GetLastLocationRequest* internal_default_instance() { return reinterpret_cast<const GetLastLocationRequest*>( &_GetLastLocationRequest_default_instance_); } static constexpr int kIndexInFileMessages = 10; friend void swap(GetLastLocationRequest& a, GetLastLocationRequest& b) { a.Swap(&b); } inline void Swap(GetLastLocationRequest* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline GetLastLocationRequest* New() const final { return CreateMaybeMessage<GetLastLocationRequest>(nullptr); } GetLastLocationRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<GetLastLocationRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const GetLastLocationRequest& from); void MergeFrom(const GetLastLocationRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GetLastLocationRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.GetLastLocationRequest"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.GetLastLocationRequest) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class GetLastLocationResponse : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.GetLastLocationResponse) */ { public: GetLastLocationResponse(); virtual ~GetLastLocationResponse(); GetLastLocationResponse(const GetLastLocationResponse& from); GetLastLocationResponse(GetLastLocationResponse&& from) noexcept : GetLastLocationResponse() { *this = ::std::move(from); } inline GetLastLocationResponse& operator=(const GetLastLocationResponse& from) { CopyFrom(from); return *this; } inline GetLastLocationResponse& operator=(GetLastLocationResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const GetLastLocationResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const GetLastLocationResponse* internal_default_instance() { return reinterpret_cast<const GetLastLocationResponse*>( &_GetLastLocationResponse_default_instance_); } static constexpr int kIndexInFileMessages = 11; friend void swap(GetLastLocationResponse& a, GetLastLocationResponse& b) { a.Swap(&b); } inline void Swap(GetLastLocationResponse* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline GetLastLocationResponse* New() const final { return CreateMaybeMessage<GetLastLocationResponse>(nullptr); } GetLastLocationResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<GetLastLocationResponse>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const GetLastLocationResponse& from); void MergeFrom(const GetLastLocationResponse& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GetLastLocationResponse* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.GetLastLocationResponse"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kLocationFieldNumber = 1, }; // .mavsdk.rpc.follow_me.TargetLocation location = 1; bool has_location() const; private: bool _internal_has_location() const; public: void clear_location(); const ::mavsdk::rpc::follow_me::TargetLocation& location() const; ::mavsdk::rpc::follow_me::TargetLocation* release_location(); ::mavsdk::rpc::follow_me::TargetLocation* mutable_location(); void set_allocated_location(::mavsdk::rpc::follow_me::TargetLocation* location); private: const ::mavsdk::rpc::follow_me::TargetLocation& _internal_location() const; ::mavsdk::rpc::follow_me::TargetLocation* _internal_mutable_location(); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.GetLastLocationResponse) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::mavsdk::rpc::follow_me::TargetLocation* location_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class StartRequest : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.StartRequest) */ { public: StartRequest(); virtual ~StartRequest(); StartRequest(const StartRequest& from); StartRequest(StartRequest&& from) noexcept : StartRequest() { *this = ::std::move(from); } inline StartRequest& operator=(const StartRequest& from) { CopyFrom(from); return *this; } inline StartRequest& operator=(StartRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const StartRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const StartRequest* internal_default_instance() { return reinterpret_cast<const StartRequest*>( &_StartRequest_default_instance_); } static constexpr int kIndexInFileMessages = 12; friend void swap(StartRequest& a, StartRequest& b) { a.Swap(&b); } inline void Swap(StartRequest* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline StartRequest* New() const final { return CreateMaybeMessage<StartRequest>(nullptr); } StartRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<StartRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const StartRequest& from); void MergeFrom(const StartRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StartRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.StartRequest"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.StartRequest) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class StartResponse : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.StartResponse) */ { public: StartResponse(); virtual ~StartResponse(); StartResponse(const StartResponse& from); StartResponse(StartResponse&& from) noexcept : StartResponse() { *this = ::std::move(from); } inline StartResponse& operator=(const StartResponse& from) { CopyFrom(from); return *this; } inline StartResponse& operator=(StartResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const StartResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const StartResponse* internal_default_instance() { return reinterpret_cast<const StartResponse*>( &_StartResponse_default_instance_); } static constexpr int kIndexInFileMessages = 13; friend void swap(StartResponse& a, StartResponse& b) { a.Swap(&b); } inline void Swap(StartResponse* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline StartResponse* New() const final { return CreateMaybeMessage<StartResponse>(nullptr); } StartResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<StartResponse>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const StartResponse& from); void MergeFrom(const StartResponse& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StartResponse* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.StartResponse"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kFollowMeResultFieldNumber = 1, }; // .mavsdk.rpc.follow_me.FollowMeResult follow_me_result = 1; bool has_follow_me_result() const; private: bool _internal_has_follow_me_result() const; public: void clear_follow_me_result(); const ::mavsdk::rpc::follow_me::FollowMeResult& follow_me_result() const; ::mavsdk::rpc::follow_me::FollowMeResult* release_follow_me_result(); ::mavsdk::rpc::follow_me::FollowMeResult* mutable_follow_me_result(); void set_allocated_follow_me_result(::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result); private: const ::mavsdk::rpc::follow_me::FollowMeResult& _internal_follow_me_result() const; ::mavsdk::rpc::follow_me::FollowMeResult* _internal_mutable_follow_me_result(); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.StartResponse) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class StopRequest : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.StopRequest) */ { public: StopRequest(); virtual ~StopRequest(); StopRequest(const StopRequest& from); StopRequest(StopRequest&& from) noexcept : StopRequest() { *this = ::std::move(from); } inline StopRequest& operator=(const StopRequest& from) { CopyFrom(from); return *this; } inline StopRequest& operator=(StopRequest&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const StopRequest& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const StopRequest* internal_default_instance() { return reinterpret_cast<const StopRequest*>( &_StopRequest_default_instance_); } static constexpr int kIndexInFileMessages = 14; friend void swap(StopRequest& a, StopRequest& b) { a.Swap(&b); } inline void Swap(StopRequest* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline StopRequest* New() const final { return CreateMaybeMessage<StopRequest>(nullptr); } StopRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<StopRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const StopRequest& from); void MergeFrom(const StopRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StopRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.StopRequest"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.StopRequest) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class StopResponse : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.StopResponse) */ { public: StopResponse(); virtual ~StopResponse(); StopResponse(const StopResponse& from); StopResponse(StopResponse&& from) noexcept : StopResponse() { *this = ::std::move(from); } inline StopResponse& operator=(const StopResponse& from) { CopyFrom(from); return *this; } inline StopResponse& operator=(StopResponse&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const StopResponse& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const StopResponse* internal_default_instance() { return reinterpret_cast<const StopResponse*>( &_StopResponse_default_instance_); } static constexpr int kIndexInFileMessages = 15; friend void swap(StopResponse& a, StopResponse& b) { a.Swap(&b); } inline void Swap(StopResponse* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline StopResponse* New() const final { return CreateMaybeMessage<StopResponse>(nullptr); } StopResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<StopResponse>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const StopResponse& from); void MergeFrom(const StopResponse& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StopResponse* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.StopResponse"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kFollowMeResultFieldNumber = 1, }; // .mavsdk.rpc.follow_me.FollowMeResult follow_me_result = 1; bool has_follow_me_result() const; private: bool _internal_has_follow_me_result() const; public: void clear_follow_me_result(); const ::mavsdk::rpc::follow_me::FollowMeResult& follow_me_result() const; ::mavsdk::rpc::follow_me::FollowMeResult* release_follow_me_result(); ::mavsdk::rpc::follow_me::FollowMeResult* mutable_follow_me_result(); void set_allocated_follow_me_result(::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result); private: const ::mavsdk::rpc::follow_me::FollowMeResult& _internal_follow_me_result() const; ::mavsdk::rpc::follow_me::FollowMeResult* _internal_mutable_follow_me_result(); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.StopResponse) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // ------------------------------------------------------------------- class FollowMeResult : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:mavsdk.rpc.follow_me.FollowMeResult) */ { public: FollowMeResult(); virtual ~FollowMeResult(); FollowMeResult(const FollowMeResult& from); FollowMeResult(FollowMeResult&& from) noexcept : FollowMeResult() { *this = ::std::move(from); } inline FollowMeResult& operator=(const FollowMeResult& from) { CopyFrom(from); return *this; } inline FollowMeResult& operator=(FollowMeResult&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const FollowMeResult& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const FollowMeResult* internal_default_instance() { return reinterpret_cast<const FollowMeResult*>( &_FollowMeResult_default_instance_); } static constexpr int kIndexInFileMessages = 16; friend void swap(FollowMeResult& a, FollowMeResult& b) { a.Swap(&b); } inline void Swap(FollowMeResult* other) { if (other == this) return; InternalSwap(other); } // implements Message ---------------------------------------------- inline FollowMeResult* New() const final { return CreateMaybeMessage<FollowMeResult>(nullptr); } FollowMeResult* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<FollowMeResult>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const FollowMeResult& from); void MergeFrom(const FollowMeResult& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FollowMeResult* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "mavsdk.rpc.follow_me.FollowMeResult"; } private: inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_follow_5fme_2ffollow_5fme_2eproto); return ::descriptor_table_follow_5fme_2ffollow_5fme_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- typedef FollowMeResult_Result Result; static constexpr Result RESULT_UNKNOWN = FollowMeResult_Result_RESULT_UNKNOWN; static constexpr Result RESULT_SUCCESS = FollowMeResult_Result_RESULT_SUCCESS; static constexpr Result RESULT_NO_SYSTEM = FollowMeResult_Result_RESULT_NO_SYSTEM; static constexpr Result RESULT_CONNECTION_ERROR = FollowMeResult_Result_RESULT_CONNECTION_ERROR; static constexpr Result RESULT_BUSY = FollowMeResult_Result_RESULT_BUSY; static constexpr Result RESULT_COMMAND_DENIED = FollowMeResult_Result_RESULT_COMMAND_DENIED; static constexpr Result RESULT_TIMEOUT = FollowMeResult_Result_RESULT_TIMEOUT; static constexpr Result RESULT_NOT_ACTIVE = FollowMeResult_Result_RESULT_NOT_ACTIVE; static constexpr Result RESULT_SET_CONFIG_FAILED = FollowMeResult_Result_RESULT_SET_CONFIG_FAILED; static inline bool Result_IsValid(int value) { return FollowMeResult_Result_IsValid(value); } static constexpr Result Result_MIN = FollowMeResult_Result_Result_MIN; static constexpr Result Result_MAX = FollowMeResult_Result_Result_MAX; static constexpr int Result_ARRAYSIZE = FollowMeResult_Result_Result_ARRAYSIZE; static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Result_descriptor() { return FollowMeResult_Result_descriptor(); } template<typename T> static inline const std::string& Result_Name(T enum_t_value) { static_assert(::std::is_same<T, Result>::value || ::std::is_integral<T>::value, "Incorrect type passed to function Result_Name."); return FollowMeResult_Result_Name(enum_t_value); } static inline bool Result_Parse(const std::string& name, Result* value) { return FollowMeResult_Result_Parse(name, value); } // accessors ------------------------------------------------------- enum : int { kResultStrFieldNumber = 2, kResultFieldNumber = 1, }; // string result_str = 2; void clear_result_str(); const std::string& result_str() const; void set_result_str(const std::string& value); void set_result_str(std::string&& value); void set_result_str(const char* value); void set_result_str(const char* value, size_t size); std::string* mutable_result_str(); std::string* release_result_str(); void set_allocated_result_str(std::string* result_str); private: const std::string& _internal_result_str() const; void _internal_set_result_str(const std::string& value); std::string* _internal_mutable_result_str(); public: // .mavsdk.rpc.follow_me.FollowMeResult.Result result = 1; void clear_result(); ::mavsdk::rpc::follow_me::FollowMeResult_Result result() const; void set_result(::mavsdk::rpc::follow_me::FollowMeResult_Result value); private: ::mavsdk::rpc::follow_me::FollowMeResult_Result _internal_result() const; void _internal_set_result(::mavsdk::rpc::follow_me::FollowMeResult_Result value); public: // @@protoc_insertion_point(class_scope:mavsdk.rpc.follow_me.FollowMeResult) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr result_str_; int result_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_follow_5fme_2ffollow_5fme_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // Config // float min_height_m = 1 [(.mavsdk.options.default_value) = "8.0"]; inline void Config::clear_min_height_m() { min_height_m_ = 0; } inline float Config::_internal_min_height_m() const { return min_height_m_; } inline float Config::min_height_m() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.Config.min_height_m) return _internal_min_height_m(); } inline void Config::_internal_set_min_height_m(float value) { min_height_m_ = value; } inline void Config::set_min_height_m(float value) { _internal_set_min_height_m(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.Config.min_height_m) } // float follow_distance_m = 2 [(.mavsdk.options.default_value) = "8.0"]; inline void Config::clear_follow_distance_m() { follow_distance_m_ = 0; } inline float Config::_internal_follow_distance_m() const { return follow_distance_m_; } inline float Config::follow_distance_m() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.Config.follow_distance_m) return _internal_follow_distance_m(); } inline void Config::_internal_set_follow_distance_m(float value) { follow_distance_m_ = value; } inline void Config::set_follow_distance_m(float value) { _internal_set_follow_distance_m(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.Config.follow_distance_m) } // .mavsdk.rpc.follow_me.Config.FollowDirection follow_direction = 3; inline void Config::clear_follow_direction() { follow_direction_ = 0; } inline ::mavsdk::rpc::follow_me::Config_FollowDirection Config::_internal_follow_direction() const { return static_cast< ::mavsdk::rpc::follow_me::Config_FollowDirection >(follow_direction_); } inline ::mavsdk::rpc::follow_me::Config_FollowDirection Config::follow_direction() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.Config.follow_direction) return _internal_follow_direction(); } inline void Config::_internal_set_follow_direction(::mavsdk::rpc::follow_me::Config_FollowDirection value) { follow_direction_ = value; } inline void Config::set_follow_direction(::mavsdk::rpc::follow_me::Config_FollowDirection value) { _internal_set_follow_direction(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.Config.follow_direction) } // float responsiveness = 4 [(.mavsdk.options.default_value) = "0.5"]; inline void Config::clear_responsiveness() { responsiveness_ = 0; } inline float Config::_internal_responsiveness() const { return responsiveness_; } inline float Config::responsiveness() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.Config.responsiveness) return _internal_responsiveness(); } inline void Config::_internal_set_responsiveness(float value) { responsiveness_ = value; } inline void Config::set_responsiveness(float value) { _internal_set_responsiveness(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.Config.responsiveness) } // ------------------------------------------------------------------- // TargetLocation // double latitude_deg = 1 [(.mavsdk.options.default_value) = "NaN"]; inline void TargetLocation::clear_latitude_deg() { latitude_deg_ = 0; } inline double TargetLocation::_internal_latitude_deg() const { return latitude_deg_; } inline double TargetLocation::latitude_deg() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.TargetLocation.latitude_deg) return _internal_latitude_deg(); } inline void TargetLocation::_internal_set_latitude_deg(double value) { latitude_deg_ = value; } inline void TargetLocation::set_latitude_deg(double value) { _internal_set_latitude_deg(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.TargetLocation.latitude_deg) } // double longitude_deg = 2 [(.mavsdk.options.default_value) = "NaN"]; inline void TargetLocation::clear_longitude_deg() { longitude_deg_ = 0; } inline double TargetLocation::_internal_longitude_deg() const { return longitude_deg_; } inline double TargetLocation::longitude_deg() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.TargetLocation.longitude_deg) return _internal_longitude_deg(); } inline void TargetLocation::_internal_set_longitude_deg(double value) { longitude_deg_ = value; } inline void TargetLocation::set_longitude_deg(double value) { _internal_set_longitude_deg(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.TargetLocation.longitude_deg) } // float absolute_altitude_m = 3 [(.mavsdk.options.default_value) = "NaN"]; inline void TargetLocation::clear_absolute_altitude_m() { absolute_altitude_m_ = 0; } inline float TargetLocation::_internal_absolute_altitude_m() const { return absolute_altitude_m_; } inline float TargetLocation::absolute_altitude_m() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.TargetLocation.absolute_altitude_m) return _internal_absolute_altitude_m(); } inline void TargetLocation::_internal_set_absolute_altitude_m(float value) { absolute_altitude_m_ = value; } inline void TargetLocation::set_absolute_altitude_m(float value) { _internal_set_absolute_altitude_m(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.TargetLocation.absolute_altitude_m) } // float velocity_x_m_s = 4 [(.mavsdk.options.default_value) = "NaN"]; inline void TargetLocation::clear_velocity_x_m_s() { velocity_x_m_s_ = 0; } inline float TargetLocation::_internal_velocity_x_m_s() const { return velocity_x_m_s_; } inline float TargetLocation::velocity_x_m_s() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.TargetLocation.velocity_x_m_s) return _internal_velocity_x_m_s(); } inline void TargetLocation::_internal_set_velocity_x_m_s(float value) { velocity_x_m_s_ = value; } inline void TargetLocation::set_velocity_x_m_s(float value) { _internal_set_velocity_x_m_s(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.TargetLocation.velocity_x_m_s) } // float velocity_y_m_s = 5 [(.mavsdk.options.default_value) = "NaN"]; inline void TargetLocation::clear_velocity_y_m_s() { velocity_y_m_s_ = 0; } inline float TargetLocation::_internal_velocity_y_m_s() const { return velocity_y_m_s_; } inline float TargetLocation::velocity_y_m_s() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.TargetLocation.velocity_y_m_s) return _internal_velocity_y_m_s(); } inline void TargetLocation::_internal_set_velocity_y_m_s(float value) { velocity_y_m_s_ = value; } inline void TargetLocation::set_velocity_y_m_s(float value) { _internal_set_velocity_y_m_s(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.TargetLocation.velocity_y_m_s) } // float velocity_z_m_s = 6 [(.mavsdk.options.default_value) = "NaN"]; inline void TargetLocation::clear_velocity_z_m_s() { velocity_z_m_s_ = 0; } inline float TargetLocation::_internal_velocity_z_m_s() const { return velocity_z_m_s_; } inline float TargetLocation::velocity_z_m_s() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.TargetLocation.velocity_z_m_s) return _internal_velocity_z_m_s(); } inline void TargetLocation::_internal_set_velocity_z_m_s(float value) { velocity_z_m_s_ = value; } inline void TargetLocation::set_velocity_z_m_s(float value) { _internal_set_velocity_z_m_s(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.TargetLocation.velocity_z_m_s) } // ------------------------------------------------------------------- // GetConfigRequest // ------------------------------------------------------------------- // GetConfigResponse // .mavsdk.rpc.follow_me.Config config = 1; inline bool GetConfigResponse::_internal_has_config() const { return this != internal_default_instance() && config_ != nullptr; } inline bool GetConfigResponse::has_config() const { return _internal_has_config(); } inline void GetConfigResponse::clear_config() { if (GetArenaNoVirtual() == nullptr && config_ != nullptr) { delete config_; } config_ = nullptr; } inline const ::mavsdk::rpc::follow_me::Config& GetConfigResponse::_internal_config() const { const ::mavsdk::rpc::follow_me::Config* p = config_; return p != nullptr ? *p : *reinterpret_cast<const ::mavsdk::rpc::follow_me::Config*>( &::mavsdk::rpc::follow_me::_Config_default_instance_); } inline const ::mavsdk::rpc::follow_me::Config& GetConfigResponse::config() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.GetConfigResponse.config) return _internal_config(); } inline ::mavsdk::rpc::follow_me::Config* GetConfigResponse::release_config() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.GetConfigResponse.config) ::mavsdk::rpc::follow_me::Config* temp = config_; config_ = nullptr; return temp; } inline ::mavsdk::rpc::follow_me::Config* GetConfigResponse::_internal_mutable_config() { if (config_ == nullptr) { auto* p = CreateMaybeMessage<::mavsdk::rpc::follow_me::Config>(GetArenaNoVirtual()); config_ = p; } return config_; } inline ::mavsdk::rpc::follow_me::Config* GetConfigResponse::mutable_config() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.GetConfigResponse.config) return _internal_mutable_config(); } inline void GetConfigResponse::set_allocated_config(::mavsdk::rpc::follow_me::Config* config) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete config_; } if (config) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, config, submessage_arena); } } else { } config_ = config; // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.GetConfigResponse.config) } // ------------------------------------------------------------------- // SetConfigRequest // .mavsdk.rpc.follow_me.Config config = 1; inline bool SetConfigRequest::_internal_has_config() const { return this != internal_default_instance() && config_ != nullptr; } inline bool SetConfigRequest::has_config() const { return _internal_has_config(); } inline void SetConfigRequest::clear_config() { if (GetArenaNoVirtual() == nullptr && config_ != nullptr) { delete config_; } config_ = nullptr; } inline const ::mavsdk::rpc::follow_me::Config& SetConfigRequest::_internal_config() const { const ::mavsdk::rpc::follow_me::Config* p = config_; return p != nullptr ? *p : *reinterpret_cast<const ::mavsdk::rpc::follow_me::Config*>( &::mavsdk::rpc::follow_me::_Config_default_instance_); } inline const ::mavsdk::rpc::follow_me::Config& SetConfigRequest::config() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.SetConfigRequest.config) return _internal_config(); } inline ::mavsdk::rpc::follow_me::Config* SetConfigRequest::release_config() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.SetConfigRequest.config) ::mavsdk::rpc::follow_me::Config* temp = config_; config_ = nullptr; return temp; } inline ::mavsdk::rpc::follow_me::Config* SetConfigRequest::_internal_mutable_config() { if (config_ == nullptr) { auto* p = CreateMaybeMessage<::mavsdk::rpc::follow_me::Config>(GetArenaNoVirtual()); config_ = p; } return config_; } inline ::mavsdk::rpc::follow_me::Config* SetConfigRequest::mutable_config() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.SetConfigRequest.config) return _internal_mutable_config(); } inline void SetConfigRequest::set_allocated_config(::mavsdk::rpc::follow_me::Config* config) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete config_; } if (config) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, config, submessage_arena); } } else { } config_ = config; // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.SetConfigRequest.config) } // ------------------------------------------------------------------- // SetConfigResponse // .mavsdk.rpc.follow_me.FollowMeResult follow_me_result = 1; inline bool SetConfigResponse::_internal_has_follow_me_result() const { return this != internal_default_instance() && follow_me_result_ != nullptr; } inline bool SetConfigResponse::has_follow_me_result() const { return _internal_has_follow_me_result(); } inline void SetConfigResponse::clear_follow_me_result() { if (GetArenaNoVirtual() == nullptr && follow_me_result_ != nullptr) { delete follow_me_result_; } follow_me_result_ = nullptr; } inline const ::mavsdk::rpc::follow_me::FollowMeResult& SetConfigResponse::_internal_follow_me_result() const { const ::mavsdk::rpc::follow_me::FollowMeResult* p = follow_me_result_; return p != nullptr ? *p : *reinterpret_cast<const ::mavsdk::rpc::follow_me::FollowMeResult*>( &::mavsdk::rpc::follow_me::_FollowMeResult_default_instance_); } inline const ::mavsdk::rpc::follow_me::FollowMeResult& SetConfigResponse::follow_me_result() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.SetConfigResponse.follow_me_result) return _internal_follow_me_result(); } inline ::mavsdk::rpc::follow_me::FollowMeResult* SetConfigResponse::release_follow_me_result() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.SetConfigResponse.follow_me_result) ::mavsdk::rpc::follow_me::FollowMeResult* temp = follow_me_result_; follow_me_result_ = nullptr; return temp; } inline ::mavsdk::rpc::follow_me::FollowMeResult* SetConfigResponse::_internal_mutable_follow_me_result() { if (follow_me_result_ == nullptr) { auto* p = CreateMaybeMessage<::mavsdk::rpc::follow_me::FollowMeResult>(GetArenaNoVirtual()); follow_me_result_ = p; } return follow_me_result_; } inline ::mavsdk::rpc::follow_me::FollowMeResult* SetConfigResponse::mutable_follow_me_result() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.SetConfigResponse.follow_me_result) return _internal_mutable_follow_me_result(); } inline void SetConfigResponse::set_allocated_follow_me_result(::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete follow_me_result_; } if (follow_me_result) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { follow_me_result = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, follow_me_result, submessage_arena); } } else { } follow_me_result_ = follow_me_result; // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.SetConfigResponse.follow_me_result) } // ------------------------------------------------------------------- // IsActiveRequest // ------------------------------------------------------------------- // IsActiveResponse // bool is_active = 1; inline void IsActiveResponse::clear_is_active() { is_active_ = false; } inline bool IsActiveResponse::_internal_is_active() const { return is_active_; } inline bool IsActiveResponse::is_active() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.IsActiveResponse.is_active) return _internal_is_active(); } inline void IsActiveResponse::_internal_set_is_active(bool value) { is_active_ = value; } inline void IsActiveResponse::set_is_active(bool value) { _internal_set_is_active(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.IsActiveResponse.is_active) } // ------------------------------------------------------------------- // SetTargetLocationRequest // .mavsdk.rpc.follow_me.TargetLocation location = 1; inline bool SetTargetLocationRequest::_internal_has_location() const { return this != internal_default_instance() && location_ != nullptr; } inline bool SetTargetLocationRequest::has_location() const { return _internal_has_location(); } inline void SetTargetLocationRequest::clear_location() { if (GetArenaNoVirtual() == nullptr && location_ != nullptr) { delete location_; } location_ = nullptr; } inline const ::mavsdk::rpc::follow_me::TargetLocation& SetTargetLocationRequest::_internal_location() const { const ::mavsdk::rpc::follow_me::TargetLocation* p = location_; return p != nullptr ? *p : *reinterpret_cast<const ::mavsdk::rpc::follow_me::TargetLocation*>( &::mavsdk::rpc::follow_me::_TargetLocation_default_instance_); } inline const ::mavsdk::rpc::follow_me::TargetLocation& SetTargetLocationRequest::location() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.SetTargetLocationRequest.location) return _internal_location(); } inline ::mavsdk::rpc::follow_me::TargetLocation* SetTargetLocationRequest::release_location() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.SetTargetLocationRequest.location) ::mavsdk::rpc::follow_me::TargetLocation* temp = location_; location_ = nullptr; return temp; } inline ::mavsdk::rpc::follow_me::TargetLocation* SetTargetLocationRequest::_internal_mutable_location() { if (location_ == nullptr) { auto* p = CreateMaybeMessage<::mavsdk::rpc::follow_me::TargetLocation>(GetArenaNoVirtual()); location_ = p; } return location_; } inline ::mavsdk::rpc::follow_me::TargetLocation* SetTargetLocationRequest::mutable_location() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.SetTargetLocationRequest.location) return _internal_mutable_location(); } inline void SetTargetLocationRequest::set_allocated_location(::mavsdk::rpc::follow_me::TargetLocation* location) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete location_; } if (location) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { location = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, location, submessage_arena); } } else { } location_ = location; // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.SetTargetLocationRequest.location) } // ------------------------------------------------------------------- // SetTargetLocationResponse // .mavsdk.rpc.follow_me.FollowMeResult follow_me_result = 1; inline bool SetTargetLocationResponse::_internal_has_follow_me_result() const { return this != internal_default_instance() && follow_me_result_ != nullptr; } inline bool SetTargetLocationResponse::has_follow_me_result() const { return _internal_has_follow_me_result(); } inline void SetTargetLocationResponse::clear_follow_me_result() { if (GetArenaNoVirtual() == nullptr && follow_me_result_ != nullptr) { delete follow_me_result_; } follow_me_result_ = nullptr; } inline const ::mavsdk::rpc::follow_me::FollowMeResult& SetTargetLocationResponse::_internal_follow_me_result() const { const ::mavsdk::rpc::follow_me::FollowMeResult* p = follow_me_result_; return p != nullptr ? *p : *reinterpret_cast<const ::mavsdk::rpc::follow_me::FollowMeResult*>( &::mavsdk::rpc::follow_me::_FollowMeResult_default_instance_); } inline const ::mavsdk::rpc::follow_me::FollowMeResult& SetTargetLocationResponse::follow_me_result() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.SetTargetLocationResponse.follow_me_result) return _internal_follow_me_result(); } inline ::mavsdk::rpc::follow_me::FollowMeResult* SetTargetLocationResponse::release_follow_me_result() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.SetTargetLocationResponse.follow_me_result) ::mavsdk::rpc::follow_me::FollowMeResult* temp = follow_me_result_; follow_me_result_ = nullptr; return temp; } inline ::mavsdk::rpc::follow_me::FollowMeResult* SetTargetLocationResponse::_internal_mutable_follow_me_result() { if (follow_me_result_ == nullptr) { auto* p = CreateMaybeMessage<::mavsdk::rpc::follow_me::FollowMeResult>(GetArenaNoVirtual()); follow_me_result_ = p; } return follow_me_result_; } inline ::mavsdk::rpc::follow_me::FollowMeResult* SetTargetLocationResponse::mutable_follow_me_result() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.SetTargetLocationResponse.follow_me_result) return _internal_mutable_follow_me_result(); } inline void SetTargetLocationResponse::set_allocated_follow_me_result(::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete follow_me_result_; } if (follow_me_result) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { follow_me_result = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, follow_me_result, submessage_arena); } } else { } follow_me_result_ = follow_me_result; // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.SetTargetLocationResponse.follow_me_result) } // ------------------------------------------------------------------- // GetLastLocationRequest // ------------------------------------------------------------------- // GetLastLocationResponse // .mavsdk.rpc.follow_me.TargetLocation location = 1; inline bool GetLastLocationResponse::_internal_has_location() const { return this != internal_default_instance() && location_ != nullptr; } inline bool GetLastLocationResponse::has_location() const { return _internal_has_location(); } inline void GetLastLocationResponse::clear_location() { if (GetArenaNoVirtual() == nullptr && location_ != nullptr) { delete location_; } location_ = nullptr; } inline const ::mavsdk::rpc::follow_me::TargetLocation& GetLastLocationResponse::_internal_location() const { const ::mavsdk::rpc::follow_me::TargetLocation* p = location_; return p != nullptr ? *p : *reinterpret_cast<const ::mavsdk::rpc::follow_me::TargetLocation*>( &::mavsdk::rpc::follow_me::_TargetLocation_default_instance_); } inline const ::mavsdk::rpc::follow_me::TargetLocation& GetLastLocationResponse::location() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.GetLastLocationResponse.location) return _internal_location(); } inline ::mavsdk::rpc::follow_me::TargetLocation* GetLastLocationResponse::release_location() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.GetLastLocationResponse.location) ::mavsdk::rpc::follow_me::TargetLocation* temp = location_; location_ = nullptr; return temp; } inline ::mavsdk::rpc::follow_me::TargetLocation* GetLastLocationResponse::_internal_mutable_location() { if (location_ == nullptr) { auto* p = CreateMaybeMessage<::mavsdk::rpc::follow_me::TargetLocation>(GetArenaNoVirtual()); location_ = p; } return location_; } inline ::mavsdk::rpc::follow_me::TargetLocation* GetLastLocationResponse::mutable_location() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.GetLastLocationResponse.location) return _internal_mutable_location(); } inline void GetLastLocationResponse::set_allocated_location(::mavsdk::rpc::follow_me::TargetLocation* location) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete location_; } if (location) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { location = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, location, submessage_arena); } } else { } location_ = location; // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.GetLastLocationResponse.location) } // ------------------------------------------------------------------- // StartRequest // ------------------------------------------------------------------- // StartResponse // .mavsdk.rpc.follow_me.FollowMeResult follow_me_result = 1; inline bool StartResponse::_internal_has_follow_me_result() const { return this != internal_default_instance() && follow_me_result_ != nullptr; } inline bool StartResponse::has_follow_me_result() const { return _internal_has_follow_me_result(); } inline void StartResponse::clear_follow_me_result() { if (GetArenaNoVirtual() == nullptr && follow_me_result_ != nullptr) { delete follow_me_result_; } follow_me_result_ = nullptr; } inline const ::mavsdk::rpc::follow_me::FollowMeResult& StartResponse::_internal_follow_me_result() const { const ::mavsdk::rpc::follow_me::FollowMeResult* p = follow_me_result_; return p != nullptr ? *p : *reinterpret_cast<const ::mavsdk::rpc::follow_me::FollowMeResult*>( &::mavsdk::rpc::follow_me::_FollowMeResult_default_instance_); } inline const ::mavsdk::rpc::follow_me::FollowMeResult& StartResponse::follow_me_result() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.StartResponse.follow_me_result) return _internal_follow_me_result(); } inline ::mavsdk::rpc::follow_me::FollowMeResult* StartResponse::release_follow_me_result() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.StartResponse.follow_me_result) ::mavsdk::rpc::follow_me::FollowMeResult* temp = follow_me_result_; follow_me_result_ = nullptr; return temp; } inline ::mavsdk::rpc::follow_me::FollowMeResult* StartResponse::_internal_mutable_follow_me_result() { if (follow_me_result_ == nullptr) { auto* p = CreateMaybeMessage<::mavsdk::rpc::follow_me::FollowMeResult>(GetArenaNoVirtual()); follow_me_result_ = p; } return follow_me_result_; } inline ::mavsdk::rpc::follow_me::FollowMeResult* StartResponse::mutable_follow_me_result() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.StartResponse.follow_me_result) return _internal_mutable_follow_me_result(); } inline void StartResponse::set_allocated_follow_me_result(::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete follow_me_result_; } if (follow_me_result) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { follow_me_result = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, follow_me_result, submessage_arena); } } else { } follow_me_result_ = follow_me_result; // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.StartResponse.follow_me_result) } // ------------------------------------------------------------------- // StopRequest // ------------------------------------------------------------------- // StopResponse // .mavsdk.rpc.follow_me.FollowMeResult follow_me_result = 1; inline bool StopResponse::_internal_has_follow_me_result() const { return this != internal_default_instance() && follow_me_result_ != nullptr; } inline bool StopResponse::has_follow_me_result() const { return _internal_has_follow_me_result(); } inline void StopResponse::clear_follow_me_result() { if (GetArenaNoVirtual() == nullptr && follow_me_result_ != nullptr) { delete follow_me_result_; } follow_me_result_ = nullptr; } inline const ::mavsdk::rpc::follow_me::FollowMeResult& StopResponse::_internal_follow_me_result() const { const ::mavsdk::rpc::follow_me::FollowMeResult* p = follow_me_result_; return p != nullptr ? *p : *reinterpret_cast<const ::mavsdk::rpc::follow_me::FollowMeResult*>( &::mavsdk::rpc::follow_me::_FollowMeResult_default_instance_); } inline const ::mavsdk::rpc::follow_me::FollowMeResult& StopResponse::follow_me_result() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.StopResponse.follow_me_result) return _internal_follow_me_result(); } inline ::mavsdk::rpc::follow_me::FollowMeResult* StopResponse::release_follow_me_result() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.StopResponse.follow_me_result) ::mavsdk::rpc::follow_me::FollowMeResult* temp = follow_me_result_; follow_me_result_ = nullptr; return temp; } inline ::mavsdk::rpc::follow_me::FollowMeResult* StopResponse::_internal_mutable_follow_me_result() { if (follow_me_result_ == nullptr) { auto* p = CreateMaybeMessage<::mavsdk::rpc::follow_me::FollowMeResult>(GetArenaNoVirtual()); follow_me_result_ = p; } return follow_me_result_; } inline ::mavsdk::rpc::follow_me::FollowMeResult* StopResponse::mutable_follow_me_result() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.StopResponse.follow_me_result) return _internal_mutable_follow_me_result(); } inline void StopResponse::set_allocated_follow_me_result(::mavsdk::rpc::follow_me::FollowMeResult* follow_me_result) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete follow_me_result_; } if (follow_me_result) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { follow_me_result = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, follow_me_result, submessage_arena); } } else { } follow_me_result_ = follow_me_result; // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.StopResponse.follow_me_result) } // ------------------------------------------------------------------- // FollowMeResult // .mavsdk.rpc.follow_me.FollowMeResult.Result result = 1; inline void FollowMeResult::clear_result() { result_ = 0; } inline ::mavsdk::rpc::follow_me::FollowMeResult_Result FollowMeResult::_internal_result() const { return static_cast< ::mavsdk::rpc::follow_me::FollowMeResult_Result >(result_); } inline ::mavsdk::rpc::follow_me::FollowMeResult_Result FollowMeResult::result() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.FollowMeResult.result) return _internal_result(); } inline void FollowMeResult::_internal_set_result(::mavsdk::rpc::follow_me::FollowMeResult_Result value) { result_ = value; } inline void FollowMeResult::set_result(::mavsdk::rpc::follow_me::FollowMeResult_Result value) { _internal_set_result(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.FollowMeResult.result) } // string result_str = 2; inline void FollowMeResult::clear_result_str() { result_str_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline const std::string& FollowMeResult::result_str() const { // @@protoc_insertion_point(field_get:mavsdk.rpc.follow_me.FollowMeResult.result_str) return _internal_result_str(); } inline void FollowMeResult::set_result_str(const std::string& value) { _internal_set_result_str(value); // @@protoc_insertion_point(field_set:mavsdk.rpc.follow_me.FollowMeResult.result_str) } inline std::string* FollowMeResult::mutable_result_str() { // @@protoc_insertion_point(field_mutable:mavsdk.rpc.follow_me.FollowMeResult.result_str) return _internal_mutable_result_str(); } inline const std::string& FollowMeResult::_internal_result_str() const { return result_str_.GetNoArena(); } inline void FollowMeResult::_internal_set_result_str(const std::string& value) { result_str_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value); } inline void FollowMeResult::set_result_str(std::string&& value) { result_str_.SetNoArena( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:mavsdk.rpc.follow_me.FollowMeResult.result_str) } inline void FollowMeResult::set_result_str(const char* value) { GOOGLE_DCHECK(value != nullptr); result_str_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:mavsdk.rpc.follow_me.FollowMeResult.result_str) } inline void FollowMeResult::set_result_str(const char* value, size_t size) { result_str_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:mavsdk.rpc.follow_me.FollowMeResult.result_str) } inline std::string* FollowMeResult::_internal_mutable_result_str() { return result_str_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline std::string* FollowMeResult::release_result_str() { // @@protoc_insertion_point(field_release:mavsdk.rpc.follow_me.FollowMeResult.result_str) return result_str_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } inline void FollowMeResult::set_allocated_result_str(std::string* result_str) { if (result_str != nullptr) { } else { } result_str_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), result_str); // @@protoc_insertion_point(field_set_allocated:mavsdk.rpc.follow_me.FollowMeResult.result_str) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace follow_me } // namespace rpc } // namespace mavsdk PROTOBUF_NAMESPACE_OPEN template <> struct is_proto_enum< ::mavsdk::rpc::follow_me::Config_FollowDirection> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::mavsdk::rpc::follow_me::Config_FollowDirection>() { return ::mavsdk::rpc::follow_me::Config_FollowDirection_descriptor(); } template <> struct is_proto_enum< ::mavsdk::rpc::follow_me::FollowMeResult_Result> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::mavsdk::rpc::follow_me::FollowMeResult_Result>() { return ::mavsdk::rpc::follow_me::FollowMeResult_Result_descriptor(); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_follow_5fme_2ffollow_5fme_2eproto
[ "julian@oes.ch" ]
julian@oes.ch
f1df8ce8fefa15ecf47a8c45b38a61bbf7c86415
a0f8610bcb61463ef9982007dfb877408c3b1a78
/Microwaving Lunch Boxes/Microwaving Lunch Boxes/main.cpp
53c54e5610c068c9a3188ecfe75f13f32b1cac0b
[]
no_license
kiswiss777/Algorithm-SourceCode
75669371f5e9a9a6895543c398bf4a9bfe76c99d
08f01aa3bb1a524e687677a2c8723f1682516dd5
refs/heads/master
2020-04-30T20:50:29.569344
2019-06-14T07:11:15
2019-06-14T07:11:15
177,079,486
0
0
null
null
null
null
UTF-8
C++
false
false
881
cpp
#include<vector> #include<iostream> #include<algorithm> #include<functional> using namespace std; const int MAX = 10000; int boxNum; vector<int> eat_t, micro_t; int microwave(void) { vector<pair<int, int>> order; for (int i = 0; i < boxNum; i++) order.push_back(make_pair(-eat_t[i], i)); sort(order.begin(), order.end()); int answer = 0, start_e= 0; for (int i = 0; i < boxNum; i++) { int box = order[i].second; start_e += micro_t[box]; answer = max(answer, start_e + eat_t[box]); } return answer; } int main(void) { int test_case, input; cin >> test_case; while(test_case--) { cin >> boxNum; for (int j = 0; j < boxNum; j++) { cin >> input; micro_t.push_back(input); } for (int j = 0; j < boxNum; j++) { cin >> input; eat_t.push_back(input); } cout << microwave() << endl; micro_t.clear(); eat_t.clear(); } return 0; }
[ "kiswiss77477@naver.com" ]
kiswiss77477@naver.com
19826386c9b011a4d9a57c3eea4b84e641f96f1a
43acc519d1eb85c654776f28ef8ec06ca11fc7d0
/robo/robo.ino
243f4078262057914267f20f675c15208c9bc246
[]
no_license
Rphmelo/robo-explorador
2701888b85713235a6571563e3fe31649bc24c76
636d00f3876a70614d6e5e264a9379b0dc8975d8
refs/heads/master
2021-07-10T14:05:33.598034
2017-10-10T17:56:58
2017-10-10T17:56:58
105,097,405
0
0
null
null
null
null
UTF-8
C++
false
false
6,349
ino
#include <AFMotor.h> #include <DHT.h> #define DHTPIN 24 #define DHTTYPE DHT11 #define LED 22 DHT dht(DHTPIN, DHTTYPE); float umidade; float temperatura; int ldrValue; class Robo { char comando; int velocidade; AF_DCMotor *rodaDD; //Dianteira Direita AF_DCMotor *rodaDE; //Dianteira Esquerda AF_DCMotor *rodaTD; //Traseira Direita AF_DCMotor *rodaTE; //Traseira Esquerda public: Robo(char, int, int, int, int, int); void setComando(char _comando){ this->comando = toupper(_comando); }; char getComando(){ return comando; }; void setVelocidade(int _velocidade){ this->velocidade = _velocidade; }; int getVelocidade(){ return velocidade; }; void definirVelocidade(){ //rodaDD->setSpeed(this->velocidade); //rodaDE->setSpeed(this->velocidade > 50 ? this->velocidade - 50: this->velocidade); //rodaTD->setSpeed(this->velocidade > 50 ? this->velocidade - 50: this->velocidade); //rodaTE->setSpeed(this->velocidade > 50 ? this->velocidade - 50: this->velocidade); rodaDD->setSpeed(this->velocidade); rodaDE->setSpeed(this->velocidade ); rodaTD->setSpeed(this->velocidade ); rodaTE->setSpeed(this->velocidade ); }; void virarAEsquerda(){ definirVelocidade(); // rodas esquerdas param rodaDD->run(FORWARD); rodaDE->run(BACKWARD); rodaTD->run(FORWARD); rodaTE->run(BACKWARD); Serial.write("Virando a esquerda"); } void virarADireita(){ definirVelocidade(); // rodas direitas param rodaDD->run(BACKWARD); rodaDE->run(FORWARD); rodaTD->run(BACKWARD); rodaTE->run(FORWARD); Serial.write("Virando a direita"); } void pararRobo(){ // para todas as rodas rodaDD->run(RELEASE); rodaDE->run(RELEASE); rodaTD->run(RELEASE); rodaTE->run(RELEASE); definirVelocidade(); Serial.write("Parando robo"); } void moverParaFrente(){ // aciona todas as rodas definirVelocidade(); rodaDD->run(FORWARD); rodaDE->run(FORWARD); rodaTD->run(FORWARD); rodaTE->run(FORWARD); Serial.write("Andando para frente"); } void moverParaTras(){ // aciona todas as rodas definirVelocidade(); rodaDD->run(BACKWARD); rodaDE->run(BACKWARD); rodaTD->run(BACKWARD); rodaTE->run(BACKWARD); Serial.write("Andando para tras"); } }; Robo::Robo(char _comando, int _velocidade, int _rodaDD, int _rodaDE, int _rodaTD, int _rodaTE) { comando = _comando; velocidade = _velocidade; rodaDD = new AF_DCMotor(_rodaDD); rodaDE = new AF_DCMotor(_rodaDE); rodaTD = new AF_DCMotor(_rodaTD); rodaTE = new AF_DCMotor(_rodaTE); } Robo *curtoCircuito = new Robo('z', 255, 1, 2, 3, 4); long previousMillis = 0; long interval = 1000; void setup() { //Inicia a serial do bluetooth Serial1.begin(9600); //Inicia a serial Serial.begin(9600); //Inicia o dht dht.begin(); //Definindo pinMode do LED pinMode(LED, OUTPUT); } void lerDht(){ // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) umidade = dht.readHumidity(); // Read temperature as Celsius (the default) temperatura = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) // Check if any reads failed and exit early (to try again). if (isnan(umidade) || isnan(temperatura)) { Serial.println("Failed to read from DHT sensor!"); return; } Serial.print("Umidade: "); Serial.print(umidade); Serial.print(" %\t"); Serial.print("Temperatura: "); Serial.print(temperatura); Serial.print(" *C "); } void acionarLed(){ digitalWrite(LED, HIGH); } void lerLdr(){ // read the input on analog pin 0: ldrValue = analogRead(A10); // print out the value you read: Serial.println("LDR:"); Serial.println(ldrValue); } void enviarDadosDhtLdr(){ } String receberDadosBluetooth(){ char caractere = ' '; String retornoCompleto = ""; while(Serial1.available()){ caractere = (char) Serial1.read(); retornoCompleto.concat(caractere); } return retornoCompleto; } int extrairVelocidade(String comando){ int velocidade = (comando.substring(1)).toInt(); return velocidade; } void iniciarControleRobo(){ unsigned long currentMillis = millis(); if(Serial1.available()){ String comando = receberDadosBluetooth(); int velocidade = extrairVelocidade(comando); curtoCircuito->setComando(comando.charAt(0)); curtoCircuito->setVelocidade(velocidade); switch(curtoCircuito->getComando()){ case 'A': if(currentMillis - previousMillis > interval) { curtoCircuito->virarAEsquerda(); previousMillis = currentMillis; } break; case 'B': if(currentMillis - previousMillis > interval) { curtoCircuito->virarADireita(); previousMillis = currentMillis; } break; case 'C': if(currentMillis - previousMillis > interval) { curtoCircuito->moverParaFrente(); previousMillis = currentMillis; } break; case 'D': if(currentMillis - previousMillis > interval) { curtoCircuito->moverParaTras(); previousMillis = currentMillis; } break; case 'E': if(currentMillis - previousMillis > interval) { curtoCircuito->pararRobo(); previousMillis = currentMillis; } break; } } } void loop() { //Inicia o controle do robô iniciarControleRobo(); //Lendo umidade, temperatura e luminosidade lerDht(); //Acionando led acionarLed(); //Lendo Ldr lerLdr(); //Enviando dados ao aplicativo Serial.println("Teste"); String dado = ""; dado.concat("T"); dado.concat(temperatura); dado.concat("U"); dado.concat(umidade); dado.concat("L"); dado.concat(ldrValue); for(int indice = 0; dado.length() < indice; indice++){ if(Serial1.available()){ Serial1.write(dado.charAt(indice)); } if(Serial.available()){ Serial.write(dado.charAt(indice)); } } }
[ "r.de.melo.silva@accenture.com" ]
r.de.melo.silva@accenture.com
4df8d2385ab5ea180d37426faed849bfea0bee9a
d8e7a11322f6d1b514c85b0c713bacca8f743ff5
/7.6.00.32/V76_00_32/MaxDB_ORG/sys/src/SAPDB/SystemViews/SysView_OMSLocks.cpp
817f46524a67b44085c06a57de6aad1db8889f95
[]
no_license
zhaonaiy/MaxDB_GPL_Releases
a224f86c0edf76e935d8951d1dd32f5376c04153
15821507c20bd1cd251cf4e7c60610ac9cabc06d
refs/heads/master
2022-11-08T21:14:22.774394
2020-07-07T00:52:44
2020-07-07T00:52:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,236
cpp
/****************************************************************************/ /*! @file SysView_OMSLocks.cpp ------------------------------------------------------------------------- @author ElkeZ @ingroup SystemViews @brief This module implements the "OMSLocks" view class. @see */ /*------------------------------------------------------------------------- copyright: Copyright (c) 2002-2005 SAP AG ========== licence begin GPL Copyright (c) 2002-2005 SAP AG This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ========== licence end *****************************************************************************/ /*===========================================================================* * INCLUDES * *===========================================================================*/ #include "ggg00.h" #include "gsp00.h" #include "vak001.h" #include "liveCache/LVC_LibOmsInterface.hpp" #include "SystemViews/SysView_Defines.hpp" #include "SystemViews/SysView_ITableObj.hpp" #include "SystemViews/SysView_OMSLocks.hpp" #include "SQLManager/SQLMan_Context.hpp" /*===========================================================================* * DEFINES * *===========================================================================*/ /*===========================================================================* * MACROS * *===========================================================================*/ /*===========================================================================* * LOCAL CLASSES, STRUCTURES, TYPES, UNIONS ... * *===========================================================================*/ /*===========================================================================* * STATIC/INLINE FUNCTIONS (PROTOTYPES) * *===========================================================================*/ /*===========================================================================* * METHODS * *===========================================================================*/ void SysView_OMSLocks::Create() { m_Table->AppendCol (ITOCT_CHARBYTE, SV_ID, 8); m_Table->AppendCol (ITOCT_FIXED, SV_TASKID, 10); m_Table->AppendCol (ITOCT_FIXED, SV_LOCKREQUESTTIMEOUT, 10); m_Table->AppendCol (ITOCT_CHAR, SV_LOCKMODE, 18); m_Table->AppendCol (ITOCT_CHAR, SV_REQUESTMODE, 18); } /*---------------------------------------------------------------------------*/ SAPDB_Int SysView_OMSLocks::GetColCount() { return SV_CC_OMSLOCKS; } /*---------------------------------------------------------------------------*/ SAPDB_Int SysView_OMSLocks::EstimateRows() { return SV_ER_OMSLOCKS; } /*---------------------------------------------------------------------------*/ void SysView_OMSLocks::Execute() { //OMS_LibOmsInterface *pLibOmsInterface; void *pHandle; tgg01_OmsLockInfo LockInfo; SAPDB_Bool bExit; m_Table->GetCatalogTable(); if (m_Context.IsOk() && (m_Context.a_ex_kind != only_parsing)) { pHandle = NULL; bExit = false; while ((!bExit) && (LVC_LibOmsInterface::Instance()->NextOmsLockObjInfo(&pHandle, LockInfo))) { m_Table->MoveToCol (ITOVT_CHARPTR, LockInfo.oli_handle.asCharp(), sizeof(LockInfo.oli_handle)); m_Table->MoveToCol (ITOVT_INT4, &LockInfo.oli_taskid, 0); if (LockInfo.oli_timeout < 0) { m_Table->MoveToCol (ITOVT_NULL, NULL, 0); } else { m_Table->MoveToCol (ITOVT_INT4, &LockInfo.oli_timeout, 0); } m_Table->MoveToCol (ITOVT_CHARPTR, LockInfo.oli_lockmode.asCharp(), LockInfo.oli_lockmode.length()); m_Table->MoveToCol (ITOVT_CHARPTR, LockInfo.oli_requestmode.asCharp(), LockInfo.oli_requestmode.length()); if (!pHandle) { bExit = true; } } } } /*===========================================================================* * END OF CODE * *===========================================================================*/
[ "gunter.mueller@gmail.com" ]
gunter.mueller@gmail.com
ff13b6eec7e704e653491ac29d62ee37b71c27ef
d38c0e1b1fa45e3dd9ed101db047831ac740f085
/src/BinaryHelper.cpp
d4f91bb8bdefea3e9611535f7a3d12b6c0c19751
[]
no_license
igornfaustino/Huffman_algoritmo
b39df1cf078794df45eee949e1c77aa32c6e8ab1
5c3d8eb5e4e22387019eda8209e319daf648709e
refs/heads/master
2021-11-08T16:46:52.761091
2021-10-26T16:29:40
2021-10-26T16:29:40
92,450,075
0
0
null
null
null
null
UTF-8
C++
false
false
836
cpp
#include "BinaryHelper.h" unsigned int BinaryHelper::setBitToOne(unsigned int num) { return ((num & mask) | mask_one); } unsigned int BinaryHelper::setBitToZero(unsigned int num) { return ((num & mask) | mask_zero); } unsigned int BinaryHelper::getCurrentBit(unsigned int num) { return (num & mask_one); } unsigned int BinaryHelper::parse_int(string str) { unsigned int num = 0x00000000; for (int i = 0; i < str.size(); i++) { if (str[i] == '1') { num = setBitToOne(num); } else { num = setBitToZero(num); } if (i < str.size() - 1) num = num << 1; } return num; } string BinaryHelper::parse_str(unsigned int num) { string str; unsigned int aux; for (int i = 0; i < 32; i++) { aux = getCurrentBit(num); stringstream ss; ss << aux; str = ss.str() + str; num = num >> 1; } return str; }
[ "igor@nfaustino.com" ]
igor@nfaustino.com
a69c194e832d0e67183b7d72487be01c9ec5a830
3f5179150584730cc0ee2ddc8f232b5e372d84aa
/Source/ProjectR/Private/UI/RacePlayerUI.cpp
6a5a2d52c1c5da7aefe0a8ef63178e03449ccdd7
[]
no_license
poettlr/ProjectR
4e8963c006bc0e5a2f7ffe72b89e5f65355d5dde
1b92b4c034c36f0cbb0ef8c2e02972dd86a3e1e1
refs/heads/master
2023-06-16T02:37:39.782708
2021-06-29T00:07:41
2021-06-29T00:07:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,546
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "UI/RacePlayerUI.h" #include "Components/TextBlock.h" int URacePlayerUI::currentLap() { return FCString::Atoi(*currentLapText->GetText().ToString()); } int URacePlayerUI::totalLaps() { return FCString::Atoi(*totalLapsText->GetText().ToString()); } int URacePlayerUI::currentPosition() { return FCString::Atoi(*currentPositionText->GetText().ToString()); } void URacePlayerUI::setTotalLapsTo(int aDesiredValue) { if(totalLapsText->GetText().ToString().Contains("(Total Laps)")) { changeIntegerTextOf(totalLapsText, aDesiredValue); } } void URacePlayerUI::changeIntegerTextOf(UTextBlock* aTextBlock, int aNewValue) { aTextBlock->SetText(FText::FromString(FString::FromInt(aNewValue))); } bool URacePlayerUI::Initialize() { bool initializeResult = Super::Initialize(); if(currentLapText) { currentLapText->SetText(FText::FromString(FString("(Current Lap)"))); } if(totalLapsText) { totalLapsText->SetText(FText::FromString(FString("(Total Laps)"))); } if(currentPositionText) { currentPositionText->SetText(FText::FromString(FString("(Current Position)"))); } return initializeResult; } void URacePlayerUI::updateLapTo(int aNewLap) { changeIntegerTextOf(currentLapText, aNewLap); } void URacePlayerUI::updatePositionTo(int aNewPosition) { changeIntegerTextOf(currentPositionText, aNewPosition); } void URacePlayerUI::modifyTotalLapsTo(int aNewTotalLapsValue) { changeIntegerTextOf(totalLapsText, aNewTotalLapsValue); }
[ "betomiku@gmail.com" ]
betomiku@gmail.com
5dcfc142474bcde5cf20a4cc9e99cdc523250bf3
6fbf5d53f59b8c9de18f91effb8d223eaf9dbc45
/copy_elision/main.cpp
b2c03cb04462dcb6fbc91ad061179036566fe9db
[]
no_license
yajnas07/cppmunchies
9f50da6ce751e32d43324e8de83eb4cbcd67478b
6e2f532fc5f4fe6187c88320fa0ce823ae96b492
refs/heads/master
2021-12-23T21:09:51.146283
2021-08-05T19:31:36
2021-08-05T19:31:36
91,421,906
2
0
null
null
null
null
UTF-8
C++
false
false
946
cpp
#include<iostream> using namespace std; class copiable_class { public: copiable_class() { cout << "Inside constructor" << endl; } copiable_class(const copiable_class & other){ cout << "Copying.." << endl; } }; //Invokes copy constructor, Named return value optimization copiable_class creator_nrvo() { copiable_class instance; return instance; } //Invokes copy constructor, return value optimization copiable_class creator_rvo() { return copiable_class(); } void pass_byvalue_func(copiable_class ob) { } int main(int argc,char * argv[]) { //Copying should have been printed two times //But compiler optimizes out call to copy constructor for temporary objects copiable_class instance1 = creator_rvo(); copiable_class instance2 = creator_nrvo(); cout << "Calling function" << endl; pass_byvalue_func(copiable_class()); cout << "Returned from function" << endl; }
[ "email.yajnas@gmail.com" ]
email.yajnas@gmail.com