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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
23782c97d8c8c099b43da2522d820d52076c019f
6b5c26e017b41b9df802b6865a3842d69778f3b2
/src/other/API_similardetect/v1.0.0_app/API_imagequality.cpp
b4f2d9c0c0ddb431bdeadaae9b4ad8fc78e75f00
[]
no_license
lvchigo/caffe_image_classfication
ae1f5d4e970ffc345affdb6d6db91918fe07c56d
6b9b05323b0c5efe41c368ff22ec8ed05cd07c8b
refs/heads/master
2020-12-29T02:19:51.445761
2017-01-12T07:08:58
2017-01-12T07:08:58
50,634,240
2
2
null
null
null
null
UTF-8
C++
false
false
13,617
cpp
#include <vector> #include <math.h> #include <iostream> #include <string.h> #include "API_imagequality.h" #include "TErrorCode.h" using namespace std; /***********************************Init*************************************/ /// construct function API_IMAGEQUALITY::API_IMAGEQUALITY() { } /// destruct function API_IMAGEQUALITY::~API_IMAGEQUALITY(void) { } /***********************************ExtractFeat*************************************/ //blur //reference No-reference Image Quality Assessment using blur and noisy //write by Min Goo Choi, Jung Hoon Jung and so on int API_IMAGEQUALITY::ExtractFeat_Blur( unsigned char *pSrcImg, int width, int height, int nChannel, vector< float > &fBlur ) //45D=5*9D { if( !pSrcImg || nChannel != 3 ) { printf("ExtractFeat_Blur err!!\n"); return TEC_INVALID_PARAM; } int i,j,k,nRet=0; int Imgwidth = width; int Imgheight = height; int Bl_width = Imgwidth, Bl_height = Imgheight; unsigned char *pGrayImg = api_imageprocess.ImageRGB2Gray(pSrcImg, width, height, nChannel); vector< float > blockBlur; fBlur.clear(); blockBlur.clear(); //nRet = ExtractFeat_Blur_Block( pGrayImg, width, height, 1, blockBlur ); nRet = ExtractFeat_Blur_Block_App( pGrayImg, width, height, 1, blockBlur ); if (nRet != 0) { cout<<"ExtractFeat_Blur_Block err!!" << endl; if (pGrayImg) {delete [] pGrayImg;pGrayImg = NULL;} return TEC_INVALID_PARAM; } /**********************push data*************************************/ for( k=0;k<blockBlur.size();k++ ) fBlur.push_back( blockBlur[k] ); /**********************cvReleaseImage*************************************/ if (pGrayImg) {delete [] pGrayImg;pGrayImg = NULL;} return nRet; } //only for gray image int API_IMAGEQUALITY::ExtractFeat_Blur_Block( unsigned char *pSrcImg, int width, int height, int nChannel, vector< float > &fBlur) //5D { if( (!pSrcImg) || (nChannel!=1) ) return TEC_INVALID_PARAM; //for mean filter unsigned char *pNoisyData = api_imageprocess.ImageMedianFilter( pSrcImg, width, height, nChannel, 3 ); //printf("ImageMedianFilter:0-%d,1-%d,2-%d\n",pNoisyData[0],pNoisyData[1],pNoisyData[2]); int nWid = width; int nHei = height; int total = (nWid)*(nHei); int iLineBytes = nWid*nChannel; int iNoisyBytes = nWid*nChannel; int steps = 0; //result //blur double blur_mean = 0; double blur_ratio = 0; //noisy double nosiy_mean = 0; double nosiy_ratio = 0; //means DhMean and DvMean in paper //for edge // it is global mean in paper i will try local later double ghMean = 0; double gvMean = 0; //for noisy double gNoisyhMean = 0; double gNoisyvMean = 0; //Nccand-mean double gNoisyMean = 0; //tmp color value for h v double ch = 0; double cv = 0; //The Thresh blur value best detected const double blur_th = 0.1; //blur value sum double blurvalue = 0; //blur count int blur_cnt = 0; //edge count int h_edge_cnt = 0; int v_edge_cnt = 0; //noisy count int noisy_cnt = 0; // noisy value double noisy_value = 0; //mean Dh(x,y) in the paper // in code it means Dh(x,y) and Ax(x,y) double* phEdgeMatric = new double[total]; double* pvEdgeMatric = new double[total]; // for noisy //Dh Dv in the paper double* phNoisyMatric = new double[total]; double* pvNoisyMatric = new double[total]; //Ncond in the paper double * NoisyM = new double[total]; //means Ch(x,y) Cv(x,y) in the paper double* tmpH = new double[total]; double* tmpV = new double[total]; //for blur and noisy //loop 1 for(int i = 0; i < nHei; i ++) { unsigned char* pOffset = pSrcImg; unsigned char* pNoisyOff = pNoisyData; steps = i*nWid; for(int j = 0; j < nWid; j ++) { int nSteps = steps + j; if(i == 0 || i == nHei -1) { //for edge phEdgeMatric[nSteps] = 0; pvEdgeMatric[nSteps] = 0; //for noisy phNoisyMatric[nSteps] = 0; pvNoisyMatric[nSteps] = 0; } else if(j == 0 || j == nWid -1) { //for edge phEdgeMatric[nSteps] = 0; pvEdgeMatric[nSteps] = 0; //for noisy phNoisyMatric[nSteps] = 0; pvNoisyMatric[nSteps] = 0; } else { //for edge ch = fabs(*(pOffset-1) - *(pOffset+1)) * 1.0 / 255.0; phEdgeMatric[nSteps] = ch; ghMean += ch; cv = fabs(*(pOffset-nWid) - *(pOffset+nWid)) * 1.0 / 255.0; pvEdgeMatric[nSteps] = cv; gvMean += cv; //for noisy ch = fabs(*(pNoisyOff-1) - *(pNoisyOff+1)) * 1.0 / 255.0; phNoisyMatric[nSteps] = ch; gNoisyhMean += ch; cv = fabs(*(pNoisyOff-nWid) - *(pNoisyOff+nWid)) * 1.0 / 255.0; pvNoisyMatric[nSteps] = cv; gNoisyvMean += cv; } double tmp_blur_value = 0; double tmp_ch = 0; double tmp_cv = 0; ch = (phEdgeMatric[nSteps] / 2); if(ch != 0) tmp_ch = fabs((*pOffset) * 1.0 / 255 - ch) * 1.0 / ch; cv = (pvEdgeMatric[nSteps] / 2); if(cv != 0) tmp_cv = fabs((*pOffset) * 1.0 / 255 - cv) * 1.0 / cv; tmp_blur_value = max(tmp_ch,tmp_cv); // blurvalue += tmp_blur_value; if(tmp_blur_value > blur_th) { blur_cnt ++; blurvalue += tmp_blur_value; } pOffset ++; pNoisyOff ++; } pSrcImg += iLineBytes; pNoisyData += iNoisyBytes; } //for edge and noisy //for edge ghMean /= (total); gvMean /= (total); //noisy gNoisyhMean /= total; gNoisyvMean /= total; //loop 2 for(int i = 0; i < nHei; i ++) { steps = i*nWid; for(int j = 0; j < nWid; j ++) { int nSteps = steps + j; ch = phEdgeMatric[nSteps]; tmpH[nSteps] = ch > ghMean ? ch : 0; cv = pvEdgeMatric[nSteps]; tmpV[nSteps] = cv > gvMean ? cv : 0; ch = phNoisyMatric[nSteps]; cv = pvNoisyMatric[nSteps]; if(ch <= gNoisyhMean && cv <= gNoisyvMean) { NoisyM[nSteps] = max(ch,cv); } else NoisyM[nSteps] = 0; gNoisyMean += NoisyM[nSteps]; } } gNoisyMean /= total; //loop 3 for(int i = 0; i < nHei; i ++) { steps = i*(nWid); for(int j = 0; j < nWid; j ++) { int nSteps = steps + j; //for edge if(i == 0 || i == nHei -1) { // phEdge[steps+j] = 0; // pvEdge[steps+j] = 0; } else if(j == 0 || j == nWid -1) { // phEdge[steps+j] = 0; // pvEdge[steps+j] = 0; } else { //for edge if(tmpH[nSteps] > tmpH[nSteps-1] && tmpH[nSteps] > tmpH[nSteps+1]) { // phEdge[steps+j] = 1; h_edge_cnt ++; } //else phEdge[steps+j] = 0; if(tmpV[nSteps] > tmpV[steps-nWid] && tmpV[nSteps] > tmpV[steps+nWid]) { // pvEdge[steps+j] = 1; v_edge_cnt ++; } // else pvEdge[steps+j] = 0; if(NoisyM[nSteps] > gNoisyMean) { noisy_cnt++; noisy_value += NoisyM[nSteps]; } } } } if(phEdgeMatric){delete []phEdgeMatric; phEdgeMatric = NULL;} if(pvEdgeMatric){delete []pvEdgeMatric; pvEdgeMatric = NULL;} if(phNoisyMatric){delete []phNoisyMatric; phNoisyMatric = NULL;} if(pvNoisyMatric){delete []pvNoisyMatric; pvNoisyMatric = NULL;} if(NoisyM){delete []NoisyM; NoisyM = NULL;} if(tmpH){delete []tmpH; tmpH = NULL;} if(tmpV){delete []tmpV; tmpV = NULL;} if ( blur_cnt == 0 ) blur_mean = 0; else blur_mean = blurvalue * 1.0 / blur_cnt; if ( (h_edge_cnt+v_edge_cnt) == 0 ) blur_ratio = 0; else blur_ratio = blur_cnt * 1.0 / (h_edge_cnt+v_edge_cnt); if ( noisy_cnt == 0 ) nosiy_mean = 0; else nosiy_mean = noisy_value * 1.0 / noisy_cnt; if ( total == 0 ) nosiy_ratio = 0; else nosiy_ratio = noisy_cnt * 1.0 / total; //the para is provided by paper //another para 1.55 0.86 0.24 0.66 double gReulst = 1 -( blur_mean + blur_ratio*0.95 + nosiy_mean*0.3 + nosiy_ratio*0.75 ); fBlur.push_back( blur_mean ); fBlur.push_back( blur_ratio ); fBlur.push_back( nosiy_mean ); fBlur.push_back( nosiy_ratio ); fBlur.push_back( gReulst ); return TOK; } //only for gray image int API_IMAGEQUALITY::ExtractFeat_Blur_Block_App( unsigned char *pSrcImg, int width, int height, int nChannel, vector< float > &fBlur) //5D { if( (!pSrcImg) || (nChannel!=1) ) return TEC_INVALID_PARAM; //for mean filter unsigned char *pNoisyData = api_imageprocess.ImageMedianFilter( pSrcImg, width, height, nChannel, 3 ); //printf("ImageMedianFilter:0-%d,1-%d,2-%d\n",pNoisyData[0],pNoisyData[1],pNoisyData[2]); int nWid = width; int nHei = height; int total = (nWid)*(nHei); int iLineBytes = nWid*nChannel; int iNoisyBytes = nWid*nChannel; int steps = 0; //result //blur double blur_mean = 0; double blur_ratio = 0; //means DhMean and DvMean in paper //for edge // it is global mean in paper i will try local later double ghMean = 0; double gvMean = 0; //tmp color value for h v double ch = 0; double cv = 0; //The Thresh blur value best detected const double blur_th = 0.1; //blur value sum double blurvalue = 0; //blur count int blur_cnt = 0; //edge count int h_edge_cnt = 0; int v_edge_cnt = 0; //noisy count int noisy_cnt = 0; // noisy value double noisy_value = 0; //mean Dh(x,y) in the paper // in code it means Dh(x,y) and Ax(x,y) double* phEdgeMatric = new double[total]; double* pvEdgeMatric = new double[total]; //means Ch(x,y) Cv(x,y) in the paper double* tmpH = new double[total]; double* tmpV = new double[total]; //for blur and noisy //loop 1 for(int i = 0; i < nHei; i ++) { unsigned char* pOffset = pSrcImg; steps = i*nWid; for(int j = 0; j < nWid; j ++) { int nSteps = steps + j; if(i == 0 || i == nHei -1) { //for edge phEdgeMatric[nSteps] = 0; pvEdgeMatric[nSteps] = 0; } else if(j == 0 || j == nWid -1) { //for edge phEdgeMatric[nSteps] = 0; pvEdgeMatric[nSteps] = 0; } else { //for edge ch = fabs(*(pOffset-1) - *(pOffset+1)) * 1.0 / 255.0; phEdgeMatric[nSteps] = ch; ghMean += ch; cv = fabs(*(pOffset-nWid) - *(pOffset+nWid)) * 1.0 / 255.0; pvEdgeMatric[nSteps] = cv; gvMean += cv; } double tmp_blur_value = 0; double tmp_ch = 0; double tmp_cv = 0; ch = (phEdgeMatric[nSteps] / 2); if(ch != 0) tmp_ch = fabs((*pOffset) * 1.0 / 255 - ch) * 1.0 / ch; cv = (pvEdgeMatric[nSteps] / 2); if(cv != 0) tmp_cv = fabs((*pOffset) * 1.0 / 255 - cv) * 1.0 / cv; tmp_blur_value = max(tmp_ch,tmp_cv); // blurvalue += tmp_blur_value; if(tmp_blur_value > blur_th) { blur_cnt ++; blurvalue += tmp_blur_value; } pOffset ++; } pSrcImg += iLineBytes; pNoisyData += iNoisyBytes; } //for edge and noisy //for edge ghMean /= (total); gvMean /= (total); //loop 2 for(int i = 0; i < nHei; i ++) { steps = i*nWid; for(int j = 0; j < nWid; j ++) { int nSteps = steps + j; ch = phEdgeMatric[nSteps]; tmpH[nSteps] = ch > ghMean ? ch : 0; cv = pvEdgeMatric[nSteps]; tmpV[nSteps] = cv > gvMean ? cv : 0; } } //loop 3 for(int i = 0; i < nHei; i ++) { steps = i*(nWid); for(int j = 0; j < nWid; j ++) { int nSteps = steps + j; //for edge if(i == 0 || i == nHei -1) { // phEdge[steps+j] = 0; // pvEdge[steps+j] = 0; } else if(j == 0 || j == nWid -1) { // phEdge[steps+j] = 0; // pvEdge[steps+j] = 0; } else { //for edge if(tmpH[nSteps] > tmpH[nSteps-1] && tmpH[nSteps] > tmpH[nSteps+1]) { // phEdge[steps+j] = 1; h_edge_cnt ++; } //else phEdge[steps+j] = 0; if(tmpV[nSteps] > tmpV[steps-nWid] && tmpV[nSteps] > tmpV[steps+nWid]) { // pvEdge[steps+j] = 1; v_edge_cnt ++; } // else pvEdge[steps+j] = 0; } } } if(phEdgeMatric){delete []phEdgeMatric; phEdgeMatric = NULL;} if(pvEdgeMatric){delete []pvEdgeMatric; pvEdgeMatric = NULL;} if(tmpH){delete []tmpH; tmpH = NULL;} if(tmpV){delete []tmpV; tmpV = NULL;} if ( blur_cnt == 0 ) blur_mean = 0; else blur_mean = blurvalue * 1.0 / blur_cnt; if ( (h_edge_cnt+v_edge_cnt) == 0 ) blur_ratio = 0; else blur_ratio = blur_cnt * 1.0 / (h_edge_cnt+v_edge_cnt); //the para is provided by paper //another para 1.55 0.86 0.24 0.66 double gReulst = 1 -( blur_mean + blur_ratio*0.95 ); fBlur.push_back( blur_mean ); fBlur.push_back( blur_ratio ); fBlur.push_back( gReulst ); return TOK; } int API_IMAGEQUALITY::ExtractFeat_Blur_test( unsigned char *pSrcImg, int width, int height, int nChannel, float &fBlur ) { if( !pSrcImg || nChannel != 3 ) { printf("ExtractFeat_Blur err!!\n"); return TEC_INVALID_PARAM; } int i,j,k,nRet=0; float Entropy,tmp = 0; unsigned char *pGrayImg = api_imageprocess.ImageRGB2Gray(pSrcImg, width, height, nChannel); //unsigned char *pFilterImg = api_imageprocess.ImageMedianFilter( pGrayImg, width, height, 1, 3 ); Entropy = 0; for (i=1; i<(height-1); ++i) { for (j=1; j<(width-1); ++j) { tmp = 0; //tmp = 2*fabs(pGrayImg[i*(width-2)+j]-pFilterImg[i*(width-2)+j]); tmp += fabs(pGrayImg[i*(width-2)+(j+1)]-pGrayImg[i*(width-2)+(j-1)]); tmp += fabs(pGrayImg[(i+1)*(width-2)+j]-pGrayImg[(i-1)*(width-2)+j]); //tmp += fabs(pFilterImg[i*(width-2)+(j+1)]-pFilterImg[i*(width-2)+(j-1)]); //tmp += fabs(pFilterImg[(i+1)*(width-2)+j]-pFilterImg[(i-1)*(width-2)+j]); tmp = (tmp<0)?0:tmp; tmp = (tmp>255)?255:tmp; if(tmp>0) Entropy = Entropy-(tmp*1.0/255)*(log(tmp*1.0/255)/log(2.0)); } } fBlur = Entropy*127.0/20000; fBlur = (fBlur<0)?0:fBlur; fBlur = (fBlur>127)?127:fBlur; /**********************cvReleaseImage*************************************/ if (pGrayImg) {delete [] pGrayImg;pGrayImg = NULL;} //if (pFilterImg) {delete [] pFilterImg;pFilterImg = NULL;} return nRet; }
[ "xiaogao@in66.com" ]
xiaogao@in66.com
e538f7ca695b6a26c43af8ca2a1468d775f72e00
5bad25ebc0daf25864f57752d93c040b30a1d8eb
/src/cell_writer.cpp
6d135b3d17072c8cd06992c19ae1883829411fc8
[]
no_license
katiya-cw/EncLib
c6c201643af4ea3afc91163b5d74ae634af0b20a
ba8547abe7f2fa02132076227fe4b93b37f3de0c
refs/heads/master
2021-12-02T11:17:29.840453
2010-12-13T22:24:27
2010-12-13T22:24:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
994
cpp
//***************************************************************************** //** Copyright (C) 2010 Kai R. Neufeldt, Ahrensburg, Germany //** This file is part of the ENClib //** The ENC lib may be used unter the GPL General Public License Version 2 //** or with a Commercial License granted by Kai R. Neufeldt //** contact Kai R. Neufeldt, Manhagener Allee 65, 22926 Ahrensburg, Germany //***************************************************************************** #include "cell_writer.h" #include <QtCore/QFile> using namespace Enc; void CellWriter::setCell(const CellS57_Base * cell) { cellS57 = cell; } void CellWriter::writeS57Cell(QString cellName) { if (!cellS57) throw QString("ERROR: Cannot write S-57 Cell %1 No Cell Pointer!").arg(cellName); QFile iso8211file(cellName); if (!iso8211file.open(QIODevice::WriteOnly)) throw QString("ERROR: cannot open S-57 File %1 for writing").arg(cellName); writeS57Cell(&iso8211file); iso8211file.close(); }
[ "KaiAbuSir@gmx.de" ]
KaiAbuSir@gmx.de
535e077037176f84ffad44125e457f46f169fbd5
f520fb1d1a66ae8c2837c1d34b2436535596035d
/drone_v0/src/library/tranformVar/transformVar.cpp
700a30ba8e489919ae375e7a759fb5cdca0d5c1f
[]
no_license
danielggc/avrProjec
eccc89ff9aa6fdcb84de7052e4a5ce62f5ca8664
756245c8c83ecdc67cf041eab55a9d1d55cf5a64
refs/heads/master
2023-04-05T00:19:08.210760
2021-01-09T19:55:02
2021-01-09T19:55:02
286,812,545
0
0
null
2020-11-04T17:27:35
2020-08-11T17:55:54
C++
UTF-8
C++
false
false
2,769
cpp
#include "transformVar.hpp" #include "../UART/UART.hpp" int int_to_binario(int8_t numero){ UART pantalla1; pantalla1.uart_init(); for(int i=7;i!=-1;i--){ if(numero & (1<<i)){ pantalla1.USART0SendByte('1'); } else{ pantalla1.USART0SendByte('0'); } } pantalla1.USART0SendByte('\n'); } int char_to_int(char *direccionCaracter){ UART pantalla1; long numero=0; int contador=0; pantalla1.USART0SendByte('\n'); while (*direccionCaracter!=' '){ pantalla1.USART0SendByte(*direccionCaracter); direccionCaracter++; contador++; } pantalla1.USART0SendByte('\n'); direccionCaracter--; int multiplicador=10; for(int a=0;a<contador;a++){ if(a==0){ numero=(*direccionCaracter-'0'); } else { numero=(*direccionCaracter-'0')*multiplicador+numero; multiplicador=multiplicador*10; } direccionCaracter--; } pantalla1.USART0SendByte('\n'); char dato[6]; char *direcciondato=&dato[0]; int largo=numeroUnidades(numero); int_to_char(numero,direcciondato,largo); for(int d=0;d<largo;d++){ pantalla1.USART0SendByte(dato[d]); } pantalla1.USART0SendByte('\n'); return numero; } long numeroUnidades(long _numero){ long numero=_numero; int contador=0; if (numero==0){ return 1; } else{ if(numero<0){ numero=numero*-1; contador++; } while (numero>0){ numero=numero/10; contador++; } return contador++; } } void int_to_char(int _numero ,char* cadenaChar , int largo){ UART pantalla1; pantalla1.uart_init(); int contador=0; long numero=_numero; bool banderaSigno=true; if(numero<0){ numero=numero*-1; banderaSigno=false; } if(largo>0){ long respaldo=numero; respaldo=numero; int d=largo-1; int inicio=largo-1; long divisor=1; for(;d>-1;d--){ for(int i=0;i<d;i++){ divisor=divisor*10; } long respaldoResta=respaldo; respaldo=numero/divisor; if(d==inicio){ cadenaChar[contador]=respaldo+'0'; } else{ long resta=(respaldoResta*10); long numeroSeparado=respaldo-resta; cadenaChar[contador]=numeroSeparado+'0'; _delay_ms(100); } contador++; divisor=1; } } if(banderaSigno==false)cadenaChar[1]='-'; else if(largo==0){ cadenaChar[0]=numero; } }
[ "danielgrecia7@gmail.com" ]
danielgrecia7@gmail.com
46013a7c2101bbeaaddc0f269aaef690e53ce21d
8481f6130c15c7e60329634012a9706f131b8ec0
/code/1009.cpp
d7fc41141ba6667a1d313550cf9f10a76c6df467
[]
no_license
Double-Wen/codeup
d7faa931e8dbaffe7de51456530032ef09537431
71dc8ffefd234102888037ae9085def67ccdfe5a
refs/heads/master
2020-12-04T03:57:24.221901
2020-01-03T14:00:56
2020-01-03T14:00:56
231,600,498
0
0
null
null
null
null
UTF-8
C++
false
false
407
cpp
// // Created by ubuntu on 1/1/20. // #include <iostream> using namespace std; int main(int argc, char *argv[]) { char buffer[100]; double count=0; for(int i=0;i<12;i++) { scanf("%[^\n]%*c", buffer); double temp=strtod(buffer, nullptr); // printf("%.2f\n", temp); count+=temp; // printf("%.2f\n", count); } printf("¥%.2f\n", count/12); }
[ "1047377010@qq.com" ]
1047377010@qq.com
250346fe0d7dbb8e1a8e0d45d2313baac5065ec5
1a2b0004be47ec7572448ca16a04b59eaaf5103c
/src/mp_betting_tree.cpp
b78f865bf7bde69a3332db011be17765d1c73e1b
[ "MIT" ]
permissive
zhanjunxiong/slumbot2019
15e87fc8ebbbc1a022d05980225ce3246c2adad0
a1b65b84c89ab2eff9e2e0c16cedcfcbd479dffd
refs/heads/master
2023-08-21T10:30:51.475541
2021-10-21T23:45:59
2021-10-21T23:45:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,538
cpp
#include <stdio.h> #include <stdlib.h> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "betting_abstraction.h" #include "betting_tree_builder.h" #include "betting_tree.h" #include "fast_hash.h" #include "game.h" using std::shared_ptr; using std::string; using std::unique_ptr; using std::unordered_map; using std::vector; static void AddStringToKey(const string &s, string *key) { *key += s; } static void AddIntToKey(int i, string *key) { char buf[10]; sprintf(buf, "%i", i); *key += buf; } static unsigned long long int HashKey(const string &key) { return fasthash64((void *)key.c_str(), key.size(), 0); } bool BettingTreeBuilder::FindReentrantNode(const string &key, shared_ptr<Node> *node) { unordered_map< unsigned long long int, shared_ptr<Node> >::iterator it; unsigned long long int h = HashKey(key); it = node_map_->find(h); if (it != node_map_->end()) { *node = it->second; return true; } else { return false; } } void BettingTreeBuilder::AddReentrantNode(const string &key, shared_ptr<Node> node) { unsigned long long int h = HashKey(key); (*node_map_)[h] = node; } // Determine the next player to act, taking into account who has folded. // Pass in first candidate for next player to act. static int NextPlayerToAct(int p, bool *folded) { int num_players = Game::NumPlayers(); while (folded[p]) { p = (p + 1) % num_players; } return p; } void BettingTreeBuilder::GetAllowableBetTos(int old_bet_to, int last_bet_size, bool *bet_to_seen) { int stack_size = betting_abstraction_.StackSize(); int min_bet; if (last_bet_size == 0) { min_bet = betting_abstraction_.MinBet(); } else { min_bet = last_bet_size; } for (int bet_to = old_bet_to + min_bet; bet_to <= stack_size; ++bet_to) { if (betting_abstraction_.AllowableBetTo(bet_to)) { bet_to_seen[bet_to] = true; } } } shared_ptr<Node> BettingTreeBuilder::CreateMPFoldSucc(int street, int last_bet_size, int bet_to, int num_street_bets, int num_bets, int player_acting, int num_players_to_act, bool *folded, int target_player, string *key, int *terminal_id) { shared_ptr<Node> fold_succ; int max_street = Game::MaxStreet(); int num_players = Game::NumPlayers(); int num_players_remaining = 0; for (int p = 0; p < num_players; ++p) { if (! folded[p]) ++num_players_remaining; } if (num_players_remaining <= 1) { fprintf(stderr, "CreateMPFoldSucc npr %u?!?\n", num_players_remaining); exit(-1); } string new_key = *key; if (betting_abstraction_.BettingKey(street)) { AddStringToKey("f", &new_key); } if (num_players_remaining == 2) { // This fold completes the hand int p; for (p = 0; p < num_players; ++p) { if (! folded[p] && p != player_acting) break; } if (p == num_players) { fprintf(stderr, "Everyone folded?!?\n"); fprintf(stderr, "street %u\n", street); fprintf(stderr, "num_players_to_act %u\n", num_players_to_act); exit(-1); } // Subtract last_bet_size from bet_to so that we get the last amount // of chips that the last opponent put in. Not sure this is useful // though, for multiplayer. fold_succ.reset(new Node((*terminal_id)++, street, p, nullptr, nullptr, nullptr, 1, bet_to - last_bet_size)); } else if (num_players_to_act == 1 && street == max_street) { // Showdown fold_succ.reset(new Node((*terminal_id)++, street, 255, nullptr, nullptr, nullptr, num_players_remaining - 1, bet_to)); } else { // Hand is not over unique_ptr<bool []> new_folded(new bool[num_players]); for (int p = 0; p < num_players; ++p) { new_folded[p] = folded[p]; } new_folded[player_acting] = true; if (num_players_to_act == 1) { // This fold completes the street fold_succ = CreateMPStreet(street + 1, bet_to, num_bets, new_folded.get(), target_player, &new_key, terminal_id); } else { // This is a fold that does not end the street int next_player_to_act = NextPlayerToAct((player_acting + 1) % num_players, new_folded.get()); fold_succ = CreateMPSubtree(street, last_bet_size, bet_to, num_street_bets, num_bets, next_player_to_act, num_players_to_act - 1, new_folded.get(), target_player, &new_key, terminal_id); } } return fold_succ; } // num_players_to_act is (re)initialized when a player bets. It gets // decremented every time a player calls or folds. When it reaches zero // the action on the current street is complete. shared_ptr<Node> BettingTreeBuilder::CreateMPCallSucc(int street, int last_bet_size, int bet_to, int num_street_bets, int num_bets, int player_acting, int num_players_to_act, bool *folded, int target_player, string *key, int *terminal_id) { bool advance_street = (num_players_to_act == 1); shared_ptr<Node> call_succ; int max_street = Game::MaxStreet(); int num_players = Game::NumPlayers(); int num_players_remaining = 0; for (int p = 0; p < num_players; ++p) { if (! folded[p]) ++num_players_remaining; } if (folded[player_acting]) { fprintf(stderr, "CreateMPCallSucc: Player already folded\n"); exit(-1); } if (num_players_to_act == 0) exit(-1); if (num_players_to_act > 1000000) exit(-1); if (num_players_to_act > num_players_remaining) exit(-1); string new_key = *key; if (betting_abstraction_.BettingKey(street)) { AddStringToKey("c", &new_key); } if (street < max_street && advance_street) { // Call completes action on current street. call_succ = CreateMPStreet(street + 1, bet_to, num_bets, folded, target_player, &new_key, terminal_id); } else if (! advance_street) { // This is a check or call that does not advance the street int next_player_to_act = NextPlayerToAct((player_acting + 1) % num_players, folded); // Shouldn't happen if (next_player_to_act == player_acting) exit(-1); call_succ = CreateMPSubtree(street, 0, bet_to, num_street_bets, num_bets, next_player_to_act, num_players_to_act - 1, folded, target_player, &new_key, terminal_id); } else { // This is a call on the final street call_succ.reset(new Node((*terminal_id)++, street, 255, nullptr, nullptr, nullptr, num_players_remaining, bet_to)); } return call_succ; } // We are contemplating adding a bet. We might or might not be facing a previous bet. void BettingTreeBuilder::MPHandleBet(int street, int last_bet_size, int last_bet_to, int new_bet_to, int num_street_bets, int num_bets, int player_acting, int num_players_to_act, bool *folded, int target_player, string *key, int *terminal_id, vector< shared_ptr<Node> > *bet_succs) { // New bet must be of size greater than zero if (new_bet_to <= last_bet_to) return; int new_bet_size = new_bet_to - last_bet_to; int stack_size = betting_abstraction_.StackSize(); bool all_in_bet = (new_bet_to == stack_size); // Cannot make a bet that is smaller than the min bet (usually the big blind) if (new_bet_size < betting_abstraction_.MinBet() && ! all_in_bet) { return; } // In general, cannot make a bet that is smaller than the previous bet size. Exception is that // you can always raise all-in if (new_bet_size < last_bet_size && ! all_in_bet) { return; } // If CloseToAllInFrac is set, eliminate some bet sizes that are too close to an all-in bet. int new_pot_size = new_bet_to * 2; if (! all_in_bet && betting_abstraction_.CloseToAllInFrac() > 0 && new_pot_size >= 2 * stack_size * betting_abstraction_.CloseToAllInFrac()) { return; } string new_key = *key; if (betting_abstraction_.BettingKey(street)) { AddStringToKey("b", &new_key); AddIntToKey(new_bet_size, &new_key); } int num_players = Game::NumPlayers(); int num_players_remaining = 0; for (int p = 0; p < num_players; ++p) { if (! folded[p]) ++num_players_remaining; } int next_player_to_act = NextPlayerToAct((player_acting + 1) % num_players, folded); // Shouldn't happen if (num_players_remaining == 1) { fprintf(stderr, "Only one player remaining after bet?!?\n"); exit(-1); } // For bets we pass in the pot size without the pending bet included shared_ptr<Node> bet = CreateMPSubtree(street, new_bet_size, new_bet_to, num_street_bets + 1, num_bets + 1, next_player_to_act, num_players_remaining - 1, folded, target_player, &new_key, terminal_id); bet_succs->push_back(bet); } // last_bet_size is the *size* of the last bet. Needed to ensure raises // are legal. bet_to is what the last bet was *to*. void BettingTreeBuilder::CreateMPSuccs(int street, int last_bet_size, int bet_to, int num_street_bets, int num_bets, int player_acting, int num_players_to_act, bool *folded, int target_player, string *key, int *terminal_id, shared_ptr<Node> *call_succ, shared_ptr<Node> *fold_succ, vector< shared_ptr<Node> > *bet_succs) { if (folded[player_acting]) { fprintf(stderr, "CreateMPSuccs: Player already folded\n"); exit(-1); } bet_succs->clear(); *call_succ = CreateMPCallSucc(street, last_bet_size, bet_to, num_street_bets, num_bets, player_acting, num_players_to_act, folded, target_player, key, terminal_id); // Allow fold if num_street_bets > 0 OR this is the very first action of // the hand (i.e., the small blind can open fold). // Preflop you can fold when num_street_bets is zero if bool can_fold = (num_street_bets > 0); if (! can_fold && street == 0) { // Special case for the preflop. When num_street_bets is zero, everyone // except the big blind can still fold. The big blind is the player // prior to the player who is first to act. int fta = Game::FirstToAct(0); int bb; if (fta == 0) bb = Game::NumPlayers() - 1; else bb = fta - 1; can_fold = (player_acting != bb); } if (can_fold) { *fold_succ = CreateMPFoldSucc(street, last_bet_size, bet_to, num_street_bets, num_bets, player_acting, num_players_to_act, folded, target_player, key, terminal_id); } bool our_bet = (target_player == player_acting); int all_in_bet_to = betting_abstraction_.StackSize(); unique_ptr<bool []> bet_to_seen(new bool[all_in_bet_to + 1]); for (int bt = 0; bt <= all_in_bet_to; ++bt) bet_to_seen[bt] = false; if (betting_abstraction_.AllowableBetTosSpecified()) { if (num_street_bets < betting_abstraction_.MaxBets(street, our_bet)) { GetAllowableBetTos(bet_to, last_bet_size, bet_to_seen.get()); } } else { if (num_street_bets < betting_abstraction_.MaxBets(street, our_bet)) { if ((! betting_abstraction_.Asymmetric() && betting_abstraction_.AlwaysAllIn()) || (betting_abstraction_.Asymmetric() && our_bet && betting_abstraction_.OurAlwaysAllIn()) || (betting_abstraction_.Asymmetric() && ! our_bet && betting_abstraction_.OppAlwaysAllIn())) { // Allow an all-in bet bet_to_seen[all_in_bet_to] = true; } } if (num_street_bets < betting_abstraction_.MaxBets(street, our_bet)) { if ((! betting_abstraction_.Asymmetric() && betting_abstraction_.AlwaysMinBet(street, num_street_bets)) || (betting_abstraction_.Asymmetric() && our_bet && betting_abstraction_.OurAlwaysMinBet(street, num_street_bets)) || (betting_abstraction_.Asymmetric() && ! our_bet && betting_abstraction_.OppAlwaysMinBet(street, num_street_bets))) { // Allow a min bet int min_bet; if (num_street_bets == 0) { min_bet = betting_abstraction_.MinBet(); } else { min_bet = last_bet_size; } int new_bet_to = bet_to + min_bet; if (new_bet_to > all_in_bet_to) { bet_to_seen[all_in_bet_to] = true; } else { if (betting_abstraction_.AllowableBetTo(new_bet_to)) { bet_to_seen[new_bet_to] = true; } else { int old_pot_size = 2 * bet_to; int nearest_allowable_bet_to = NearestAllowableBetTo(old_pot_size, new_bet_to, last_bet_size); bet_to_seen[nearest_allowable_bet_to] = true; #if 0 if (nearest_allowable_bet_to != new_bet_to) { fprintf(stderr, "Changed %u to %u\n", new_bet_to - bet_to, nearest_allowable_bet_to - bet_to); } #endif } } } } if (num_street_bets < betting_abstraction_.MaxBets(street, our_bet)) { const vector<double> &pot_fracs = betting_abstraction_.BetSizes(street, num_street_bets, our_bet, player_acting); GetNewBetTos(bet_to, last_bet_size, pot_fracs, player_acting, target_player, bet_to_seen.get()); } } for (int new_bet_to = 0; new_bet_to <= all_in_bet_to; ++new_bet_to) { if (bet_to_seen[new_bet_to]) { MPHandleBet(street, last_bet_size, bet_to, new_bet_to, num_street_bets, num_bets, player_acting, num_players_to_act, folded, target_player, key, terminal_id, bet_succs); } } } shared_ptr<Node> BettingTreeBuilder::CreateMPSubtree(int st, int last_bet_size, int bet_to, int num_street_bets, int num_bets, int player_acting, int num_players_to_act, bool *folded, int target_player, string *key, int *terminal_id) { if (folded[player_acting]) { fprintf(stderr, "CreateMPSubtree: Player already folded\n"); exit(-1); } string final_key; bool merge = false; // As it stands, we don't encode which players have folded. But we do // encode num_players_to_act. int num_players = Game::NumPlayers(); int num_rem = 0; for (int p = 0; p < num_players; ++p) { if (! folded[p]) ++num_rem; } if (betting_abstraction_.ReentrantStreet(st) && 2 * bet_to >= betting_abstraction_.MinReentrantPot() && num_bets >= betting_abstraction_.MinReentrantBets(st, num_rem)) { merge = true; final_key = *key; AddStringToKey(":", &final_key); AddIntToKey(st, &final_key); AddStringToKey(":", &final_key); AddIntToKey(player_acting, &final_key); AddStringToKey(":", &final_key); AddIntToKey(num_street_bets, &final_key); AddStringToKey(":", &final_key); AddIntToKey(bet_to, &final_key); AddStringToKey(":", &final_key); AddIntToKey(last_bet_size, &final_key); AddStringToKey(":", &final_key); AddIntToKey(num_rem, &final_key); AddStringToKey(":", &final_key); AddIntToKey(num_players_to_act, &final_key); // fprintf(stderr, "Key: %s\n", final_key.c_str()); shared_ptr<Node> node; if (FindReentrantNode(final_key, &node)) { return node; } } shared_ptr<Node> call_succ; shared_ptr<Node> fold_succ; vector< shared_ptr<Node> > bet_succs; CreateMPSuccs(st, last_bet_size, bet_to, num_street_bets, num_bets, player_acting, num_players_to_act, folded, target_player, key, terminal_id, &call_succ, &fold_succ, &bet_succs); if (call_succ == nullptr && fold_succ == nullptr && bet_succs.size() == 0) { fprintf(stderr, "Creating nonterminal with zero succs\n"); fprintf(stderr, "This will cause problems\n"); exit(-1); } // Assign nonterminal ID of -1 for now. shared_ptr<Node> node; node.reset(new Node(-1, st, player_acting, call_succ, fold_succ, &bet_succs, num_rem, bet_to)); if (merge) { AddReentrantNode(final_key, node); } return node; } shared_ptr<Node> BettingTreeBuilder::CreateMPStreet(int street, int bet_to, int num_bets, bool *folded, int target_player, string *key, int *terminal_id) { int num_players = Game::NumPlayers(); int num_players_remaining = 0; for (int p = 0; p < num_players; ++p) { if (! folded[p]) ++num_players_remaining; } int next_player_to_act = NextPlayerToAct(Game::FirstToAct(street + 1), folded); shared_ptr<Node> node = CreateMPSubtree(street, 0, bet_to, 0, num_bets, next_player_to_act, num_players_remaining, folded, target_player, key, terminal_id); return node; } shared_ptr<Node> BettingTreeBuilder::CreateMPTree(int target_player, int *terminal_id) { int initial_street = betting_abstraction_.InitialStreet(); int player_acting = Game::FirstToAct(initial_street_); int initial_bet_to = Game::BigBlind(); int last_bet_size = Game::BigBlind() - Game::SmallBlind(); int num_players = Game::NumPlayers(); unique_ptr<bool []> folded(new bool[num_players]); for (int p = 0; p < num_players; ++p) { folded[p] = false; } string key; return CreateMPSubtree(initial_street, last_bet_size, initial_bet_to, 0, 0, player_acting, Game::NumPlayers(), folded.get(), target_player, &key, terminal_id); }
[ "eric.jackson@gmail.com" ]
eric.jackson@gmail.com
a84596bb95953e05e389f2fa3384003246301893
967901498a9cba019f54e2ed62920f976491f8b2
/winapi/CWindow/SetWindowText/src/CWindow/CWindow/MainApplication.cpp
c765d12d0616e1302843ce5426aef0b7145b8ac8
[ "MIT" ]
permissive
bg1bgst333/Test
732e07a92e0fa52f3c364d1a65348f518ec6d849
40291a30a2b344bdbbae677958112e279374411f
refs/heads/master
2023-08-18T04:59:58.947454
2023-08-09T04:28:23
2023-08-09T04:28:23
239,051,674
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,175
cpp
// ヘッダのインクルード // 独自のヘッダ #include "MainApplication.h" // CMainApplication #include "MainWindow.h" // CMainWindow // インスタンス初期化関数InitInstance. BOOL CMainApplication::InitInstance(HINSTANCE hInstance, LPTSTR lpCmdLine, int nShowCmd) { // ウィンドウクラスの登録. CMainWindow::RegisterClass(hInstance, MAKEINTRESOURCE(IDR_MAINMENU)); // CMainWindow::RegisterClassでメニューIDR_MAINMENUを指定してウィンドウクラスを登録. // CMainWindowオブジェクトの作成. m_pMainWnd = new CMainWindow(); // CMainWindowオブジェクトを作成し, m_pMainWndに格納. // ウィンドウの作成. if (!m_pMainWnd->Create(_T("CWindow"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance)) { // m_pMainWnd->Createでウィンドウ作成し, 失敗した場合. // エラー処理 return FALSE; // returnでFALSEを返して異常終了. } // ウィンドウの表示. m_pMainWnd->ShowWindow(SW_SHOW); // m_pMainWnd->ShowWindowで表示. // TRUEを返す. return TRUE; // returnでTRUEを返す. }
[ "bg1bgst333@gmail.com" ]
bg1bgst333@gmail.com
66e17a3aae3c0f57cafdebaacbf14867eab99e30
04b1803adb6653ecb7cb827c4f4aa616afacf629
/media/blink/multibuffer_data_source_unittest.cc
02be5cee8fcc21b3d4bc016b050ca392f8d988c0
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
58,312
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <stdint.h> #include "base/bind.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/test/scoped_feature_list.h" #include "media/base/media_switches.h" #include "media/base/media_util.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/blink/buffered_data_source_host_impl.h" #include "media/blink/mock_resource_fetch_context.h" #include "media/blink/mock_webassociatedurlloader.h" #include "media/blink/multibuffer_data_source.h" #include "media/blink/multibuffer_reader.h" #include "media/blink/resource_multibuffer_data_provider.h" #include "media/blink/test_response_generator.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/platform/web_url_response.h" using ::testing::_; using ::testing::Assign; using ::testing::DoAll; using ::testing::Invoke; using ::testing::InvokeWithoutArgs; using ::testing::InSequence; using ::testing::NiceMock; using ::testing::StrictMock; using blink::WebAssociatedURLLoader; using blink::WebString; using blink::WebURLResponse; namespace media { class TestResourceMultiBuffer; class TestMultiBufferDataProvider; std::set<TestMultiBufferDataProvider*> test_data_providers; class TestMultiBufferDataProvider : public ResourceMultiBufferDataProvider { public: TestMultiBufferDataProvider(UrlData* url_data, MultiBuffer::BlockId pos) : ResourceMultiBufferDataProvider(url_data, pos, false /* is_client_audio_element */) { CHECK(test_data_providers.insert(this).second); } ~TestMultiBufferDataProvider() override { CHECK_EQ(static_cast<size_t>(1), test_data_providers.erase(this)); } // ResourceMultiBufferDataProvider overrides. void Start() override { ResourceMultiBufferDataProvider::Start(); if (!on_start_.is_null()) on_start_.Run(); } void SetDeferred(bool defer) override { deferred_ = defer; ResourceMultiBufferDataProvider::SetDeferred(defer); } bool loading() const { return !!active_loader_; } bool deferred() const { return deferred_; } void RunOnStart(base::Closure cb) { on_start_ = cb; } private: bool deferred_ = false; base::Closure on_start_; }; class TestUrlData; class TestResourceMultiBuffer : public ResourceMultiBuffer { public: explicit TestResourceMultiBuffer(UrlData* url_data, int shift) : ResourceMultiBuffer(url_data, shift) {} std::unique_ptr<MultiBuffer::DataProvider> CreateWriter(const BlockId& pos, bool) override { auto writer = std::make_unique<TestMultiBufferDataProvider>(url_data_, pos); writer->Start(); return writer; } // TODO: Make these global TestMultiBufferDataProvider* GetProvider() { EXPECT_EQ(test_data_providers.size(), 1U); if (test_data_providers.size() != 1) return nullptr; return *test_data_providers.begin(); } TestMultiBufferDataProvider* GetProvider_allownull() { EXPECT_LE(test_data_providers.size(), 1U); if (test_data_providers.size() != 1U) return nullptr; return *test_data_providers.begin(); } bool HasProvider() const { return test_data_providers.size() == 1U; } bool loading() { if (test_data_providers.empty()) return false; return GetProvider()->loading(); } }; class TestUrlData : public UrlData { public: TestUrlData(const GURL& url, CorsMode cors_mode, UrlIndex* url_index) : UrlData(url, cors_mode, url_index), block_shift_(url_index->block_shift()) {} ResourceMultiBuffer* multibuffer() override { if (!test_multibuffer_.get()) { test_multibuffer_.reset(new TestResourceMultiBuffer(this, block_shift_)); } return test_multibuffer_.get(); } TestResourceMultiBuffer* test_multibuffer() { if (!test_multibuffer_.get()) { test_multibuffer_.reset(new TestResourceMultiBuffer(this, block_shift_)); } return test_multibuffer_.get(); } protected: ~TestUrlData() override = default; const int block_shift_; std::unique_ptr<TestResourceMultiBuffer> test_multibuffer_; }; class TestUrlIndex : public UrlIndex { public: explicit TestUrlIndex(ResourceFetchContext* fetch_context) : UrlIndex(fetch_context) {} scoped_refptr<UrlData> NewUrlData(const GURL& url, UrlData::CorsMode cors_mode) override { last_url_data_ = new TestUrlData(url, cors_mode, this); return last_url_data_; } scoped_refptr<TestUrlData> last_url_data() { EXPECT_TRUE(last_url_data_); return last_url_data_; } size_t load_queue_size() { return loading_queue_.size(); } private: scoped_refptr<TestUrlData> last_url_data_; }; class MockBufferedDataSourceHost : public BufferedDataSourceHost { public: MockBufferedDataSourceHost() = default; ~MockBufferedDataSourceHost() override = default; MOCK_METHOD1(SetTotalBytes, void(int64_t total_bytes)); MOCK_METHOD2(AddBufferedByteRange, void(int64_t start, int64_t end)); private: DISALLOW_COPY_AND_ASSIGN(MockBufferedDataSourceHost); }; class MockMultibufferDataSource : public MultibufferDataSource { public: MockMultibufferDataSource( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, scoped_refptr<UrlData> url_data, BufferedDataSourceHost* host) : MultibufferDataSource( task_runner, std::move(url_data), &media_log_, host, base::Bind(&MockMultibufferDataSource::set_downloading, base::Unretained(this))), downloading_(false) {} bool downloading() { return downloading_; } void set_downloading(bool downloading) { downloading_ = downloading; } bool range_supported() { return url_data_->range_supported(); } void CallSeekTask() { SeekTask(); } private: // Whether the resource is downloading or deferred. bool downloading_; NullMediaLog media_log_; DISALLOW_COPY_AND_ASSIGN(MockMultibufferDataSource); }; static const int64_t kFileSize = 5000000; static const int64_t kFarReadPosition = 3997696; static const int kDataSize = 32 << 10; static const char kHttpUrl[] = "http://localhost/foo.webm"; static const char kFileUrl[] = "file:///tmp/bar.webm"; static const char kHttpDifferentPathUrl[] = "http://localhost/bar.webm"; static const char kHttpDifferentOriginUrl[] = "http://127.0.0.1/foo.webm"; class MultibufferDataSourceTest : public testing::Test { public: MultibufferDataSourceTest() : preload_(MultibufferDataSource::AUTO) { ON_CALL(fetch_context_, CreateUrlLoader(_)) .WillByDefault(Invoke([](const blink::WebAssociatedURLLoaderOptions&) { return std::make_unique<NiceMock<MockWebAssociatedURLLoader>>(); })); url_index_ = std::make_unique<TestUrlIndex>(&fetch_context_); } MOCK_METHOD1(OnInitialize, void(bool)); void InitializeWithCors(const char* url, bool expected, UrlData::CorsMode cors_mode, size_t file_size = kFileSize) { GURL gurl(url); data_source_.reset(new MockMultibufferDataSource( base::ThreadTaskRunnerHandle::Get(), url_index_->GetByUrl(gurl, cors_mode), &host_)); data_source_->SetPreload(preload_); response_generator_.reset(new TestResponseGenerator(gurl, file_size)); EXPECT_CALL(*this, OnInitialize(expected)); data_source_->Initialize(base::Bind( &MultibufferDataSourceTest::OnInitialize, base::Unretained(this))); base::RunLoop().RunUntilIdle(); // Not really loading until after OnInitialize is called. EXPECT_EQ(data_source_->downloading(), false); } void Initialize(const char* url, bool expected, size_t file_size = kFileSize) { InitializeWithCors(url, expected, UrlData::CORS_UNSPECIFIED, file_size); } // Helper to initialize tests with a valid 200 response. void InitializeWith200Response() { Initialize(kHttpUrl, true); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate200()); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); } // Helper to initialize tests with a valid 206 response. void InitializeWith206Response(size_t file_size = kFileSize) { Initialize(kHttpUrl, true, file_size); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); } // Helper to initialize tests with a valid file:// response. void InitializeWithFileResponse() { Initialize(kFileUrl, true); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kFileSize)); Respond(response_generator_->GenerateFileResponse(0)); ReceiveData(kDataSize); } // Starts data source. void Start() { EXPECT_TRUE(data_provider()); EXPECT_FALSE(active_loader_allownull()); data_provider()->Start(); } // Stops any active loaders and shuts down the data source. // // This typically happens when the page is closed and for our purposes is // appropriate to do when tearing down a test. void Stop() { if (loading()) { data_provider()->DidFail(response_generator_->GenerateError()); base::RunLoop().RunUntilIdle(); } data_source_->Stop(); base::RunLoop().RunUntilIdle(); } void Respond(const WebURLResponse& response) { EXPECT_TRUE(active_loader()); data_provider()->DidReceiveResponse(response); base::RunLoop().RunUntilIdle(); } void ReceiveDataLow(int size) { EXPECT_TRUE(active_loader()); std::unique_ptr<char[]> data(new char[size]); memset(data.get(), 0xA5, size); // Arbitrary non-zero value. data_provider()->DidReceiveData(data.get(), size); } void ReceiveData(int size) { ReceiveDataLow(size); base::RunLoop().RunUntilIdle(); } void FinishLoading() { EXPECT_TRUE(active_loader()); data_provider()->DidFinishLoading(); base::RunLoop().RunUntilIdle(); } void FailLoading() { data_provider()->DidFail(response_generator_->GenerateError()); base::RunLoop().RunUntilIdle(); } MOCK_METHOD1(ReadCallback, void(int size)); void ReadAt(int64_t position, int64_t howmuch = kDataSize) { data_source_->Read(position, howmuch, buffer_, base::Bind(&MultibufferDataSourceTest::ReadCallback, base::Unretained(this))); base::RunLoop().RunUntilIdle(); } void ExecuteMixedResponseSuccessTest(const WebURLResponse& response1, const WebURLResponse& response2) { EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)).Times(2); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); FinishLoading(); Start(); ReadAt(kDataSize); Respond(response2); ReceiveData(kDataSize); FinishLoading(); Stop(); } void ExecuteMixedResponseFailureTest(const WebURLResponse& response1, const WebURLResponse& response2) { EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); // Stop() will also cause the readback to be called with kReadError, but // we want to make sure it was called before Stop(). bool failed_ = false; EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)) .WillOnce(Assign(&failed_, true)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); FinishLoading(); Start(); ReadAt(kDataSize); Respond(response2); EXPECT_TRUE(failed_); Stop(); } void CheckCapacityDefer() { EXPECT_EQ(2 << 20, preload_low()); EXPECT_EQ(3 << 20, preload_high()); } void CheckReadThenDefer() { EXPECT_EQ(2 << 14, preload_low()); EXPECT_EQ(3 << 14, preload_high()); } void CheckNeverDefer() { EXPECT_EQ(1LL << 40, preload_low()); EXPECT_EQ(1LL << 40, preload_high()); } // Accessors for private variables on |data_source_|. MultiBufferReader* loader() { return data_source_->reader_.get(); } TestResourceMultiBuffer* multibuffer() { return url_index_->last_url_data()->test_multibuffer(); } TestMultiBufferDataProvider* data_provider() { return multibuffer()->GetProvider(); } blink::WebAssociatedURLLoader* active_loader() { EXPECT_TRUE(data_provider()); if (!data_provider()) return nullptr; return data_provider()->active_loader_.get(); } blink::WebAssociatedURLLoader* active_loader_allownull() { TestMultiBufferDataProvider* data_provider = multibuffer()->GetProvider_allownull(); if (!data_provider) return nullptr; return data_provider->active_loader_.get(); } bool loading() { return multibuffer()->loading(); } MultibufferDataSource::Preload preload() { return data_source_->preload_; } void set_preload(MultibufferDataSource::Preload preload) { preload_ = preload; } int64_t preload_high() { CHECK(loader()); return loader()->preload_high(); } int64_t preload_low() { CHECK(loader()); return loader()->preload_low(); } int data_source_bitrate() { return data_source_->bitrate_; } int64_t max_buffer_forward() { return loader()->max_buffer_forward_; } int64_t max_buffer_backward() { return loader()->max_buffer_backward_; } int64_t buffer_size() { return loader()->current_buffer_size_ * 32768 /* block size */; } double data_source_playback_rate() { return data_source_->playback_rate_; } bool is_local_source() { return data_source_->AssumeFullyBuffered(); } scoped_refptr<UrlData> url_data() { return data_source_->url_data_; } void set_might_be_reused_from_cache_in_future(bool value) { url_data()->set_cacheable(value); } protected: MultibufferDataSource::Preload preload_; NiceMock<MockResourceFetchContext> fetch_context_; std::unique_ptr<TestUrlIndex> url_index_; std::unique_ptr<MockMultibufferDataSource> data_source_; std::unique_ptr<TestResponseGenerator> response_generator_; StrictMock<MockBufferedDataSourceHost> host_; // Used for calling MultibufferDataSource::Read(). uint8_t buffer_[kDataSize * 2]; DISALLOW_COPY_AND_ASSIGN(MultibufferDataSourceTest); }; TEST_F(MultibufferDataSourceTest, Range_Supported) { InitializeWith206Response(); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_InstanceSizeUnknown) { Initialize(kHttpUrl, true); Respond(response_generator_->Generate206( 0, TestResponseGenerator::kNoContentRangeInstanceSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); EXPECT_TRUE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_NotFound) { Initialize(kHttpUrl, false); Respond(response_generator_->Generate404()); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_NotSupported) { InitializeWith200Response(); EXPECT_TRUE(loading()); EXPECT_TRUE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_NotSatisfiable) { Initialize(kHttpUrl, true); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); Respond(response_generator_->GenerateResponse(416)); EXPECT_FALSE(loading()); Stop(); } // Special carve-out for Apache versions that choose to return a 200 for // Range:0- ("because it's more efficient" than a 206) TEST_F(MultibufferDataSourceTest, Range_SupportedButReturned200) { Initialize(kHttpUrl, true); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); WebURLResponse response = response_generator_->Generate200(); response.SetHttpHeaderField(WebString::FromUTF8("Accept-Ranges"), WebString::FromUTF8("bytes")); Respond(response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_MissingContentRange) { Initialize(kHttpUrl, false); Respond(response_generator_->Generate206( 0, TestResponseGenerator::kNoContentRange)); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_MissingContentLength) { Initialize(kHttpUrl, true); // It'll manage without a Content-Length response. EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206( 0, TestResponseGenerator::kNoContentLength)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, Range_WrongContentRange) { Initialize(kHttpUrl, false); // Now it's done and will fail. Respond(response_generator_->Generate206(1337)); EXPECT_FALSE(loading()); Stop(); } // Test the case where the initial response from the server indicates that // Range requests are supported, but a later request prove otherwise. TEST_F(MultibufferDataSourceTest, Range_ServerLied) { InitializeWith206Response(); // Read causing a new request to be made, we will discard the data that // was already read in the first request. ReadAt(kFarReadPosition); // Return a 200 in response to a range request. EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); Respond(response_generator_->Generate200()); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_AbortWhileReading) { InitializeWith206Response(); // Make sure there's a pending read -- we'll expect it to error. ReadAt(kFileSize); // Abort!!! EXPECT_CALL(*this, ReadCallback(media::DataSource::kAborted)); data_source_->Abort(); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_AbortWhileReading) { InitializeWithFileResponse(); // Make sure there's a pending read -- we'll expect it to error. ReadAt(kFileSize); // Abort!!! EXPECT_CALL(*this, ReadCallback(media::DataSource::kAborted)); data_source_->Abort(); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_Retry) { InitializeWith206Response(); // Read to advance our position. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Issue a pending read but terminate the connection to force a retry. ReadAt(kDataSize); FinishLoading(); Start(); Respond(response_generator_->Generate206(kDataSize)); // Complete the read. EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_RetryOnError) { InitializeWith206Response(); // Read to advance our position. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Issue a pending read but trigger an error to force a retry. EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReadAt(kDataSize); base::RunLoop run_loop; data_provider()->DidFail(response_generator_->GenerateError()); data_provider()->RunOnStart(run_loop.QuitClosure()); run_loop.Run(); Respond(response_generator_->Generate206(kDataSize)); ReceiveData(kDataSize); FinishLoading(); EXPECT_FALSE(loading()); Stop(); } // Make sure that we prefetch across partial responses. (crbug.com/516589) TEST_F(MultibufferDataSourceTest, Http_PartialResponsePrefetch) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 3 - 1); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); FinishLoading(); Start(); Respond(response2); ReceiveData(kDataSize); ReceiveData(kDataSize); FinishLoading(); Stop(); } TEST_F(MultibufferDataSourceTest, Http_PartialResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are same. So no error should // occur. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_RedirectedToDifferentPathResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); response2.SetCurrentRequestUrl(GURL(kHttpDifferentPathUrl)); // The origin URL of response1 and response2 are same. So no error should // occur. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_RedirectedToDifferentOriginResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); response2.SetCurrentRequestUrl(GURL(kHttpDifferentOriginUrl)); // The origin URL of response1 and response2 are different. So an error should // occur. ExecuteMixedResponseFailureTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerGeneratedResponseAndNormalResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetWasFetchedViaServiceWorker(true); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // response1 is generated in a Service Worker but response2 is from a native // server. So an error should occur. ExecuteMixedResponseFailureTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerProxiedAndSameURLResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetWasFetchedViaServiceWorker(true); std::vector<blink::WebURL> url_list = {GURL(kHttpUrl)}; response1.SetUrlListViaServiceWorker(url_list); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are same. So no error should // occur. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerProxiedAndDifferentPathResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetWasFetchedViaServiceWorker(true); std::vector<blink::WebURL> url_list = {GURL(kHttpDifferentPathUrl)}; response1.SetUrlListViaServiceWorker(url_list); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are same. So no error should // occur. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerProxiedAndDifferentOriginResponse) { Initialize(kHttpUrl, true); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetWasFetchedViaServiceWorker(true); std::vector<blink::WebURL> url_list = {GURL(kHttpDifferentOriginUrl)}; response1.SetUrlListViaServiceWorker(url_list); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are different. So an error should // occur. ExecuteMixedResponseFailureTest(response1, response2); } TEST_F(MultibufferDataSourceTest, Http_MixedResponse_ServiceWorkerProxiedAndDifferentOriginResponseCors) { InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetWasFetchedViaServiceWorker(true); std::vector<blink::WebURL> url_list = {GURL(kHttpDifferentOriginUrl)}; response1.SetUrlListViaServiceWorker(url_list); WebURLResponse response2 = response_generator_->GeneratePartial206(kDataSize, kDataSize * 2 - 1); // The origin URL of response1 and response2 are different, but a CORS check // has been passed for each request, so expect success. ExecuteMixedResponseSuccessTest(response1, response2); } TEST_F(MultibufferDataSourceTest, File_Retry) { InitializeWithFileResponse(); // Read to advance our position. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Issue a pending read but terminate the connection to force a retry. ReadAt(kDataSize); FinishLoading(); Start(); Respond(response_generator_->GenerateFileResponse(kDataSize)); // Complete the read. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReceiveData(kDataSize); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_TooManyRetries) { InitializeWith206Response(); // Make sure there's a pending read -- we'll expect it to error. ReadAt(kDataSize); for (int i = 0; i < ResourceMultiBufferDataProvider::kMaxRetries; i++) { FailLoading(); Start(); Respond(response_generator_->Generate206(kDataSize)); } // Stop() will also cause the readback to be called with kReadError, but // we want to make sure it was called during FailLoading(). bool failed_ = false; EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)) .WillOnce(Assign(&failed_, true)); FailLoading(); EXPECT_TRUE(failed_); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_TooManyRetries) { InitializeWithFileResponse(); // Make sure there's a pending read -- we'll expect it to error. ReadAt(kDataSize); for (int i = 0; i < ResourceMultiBufferDataProvider::kMaxRetries; i++) { FailLoading(); Start(); Respond(response_generator_->Generate206(kDataSize)); } // Stop() will also cause the readback to be called with kReadError, but // we want to make sure it was called during FailLoading(). bool failed_ = false; EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)) .WillOnce(Assign(&failed_, true)); FailLoading(); EXPECT_TRUE(failed_); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_InstanceSizeUnknown) { Initialize(kFileUrl, false); Respond( response_generator_->GenerateFileResponse(media::DataSource::kReadError)); ReceiveData(kDataSize); EXPECT_FALSE(data_source_->downloading()); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_Successful) { InitializeWithFileResponse(); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsStreaming()); Stop(); } TEST_F(MultibufferDataSourceTest, StopDuringRead) { InitializeWith206Response(); uint8_t buffer[256]; data_source_->Read(kDataSize, base::size(buffer), buffer, base::Bind(&MultibufferDataSourceTest::ReadCallback, base::Unretained(this))); // The outstanding read should fail before the stop callback runs. { InSequence s; EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); data_source_->Stop(); } base::RunLoop().RunUntilIdle(); } TEST_F(MultibufferDataSourceTest, DefaultValues) { InitializeWith206Response(); // Ensure we have sane values for default loading scenario. EXPECT_EQ(MultibufferDataSource::AUTO, preload()); EXPECT_EQ(2 << 20, preload_low()); EXPECT_EQ(3 << 20, preload_high()); EXPECT_EQ(0, data_source_bitrate()); EXPECT_EQ(0.0, data_source_playback_rate()); EXPECT_TRUE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, SetBitrate) { InitializeWith206Response(); data_source_->SetBitrate(1234); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1234, data_source_bitrate()); // Read so far ahead to cause the loader to get recreated. TestMultiBufferDataProvider* old_loader = data_provider(); ReadAt(kFarReadPosition); Respond(response_generator_->Generate206(kFarReadPosition)); // Verify loader changed but still has same bitrate. EXPECT_NE(old_loader, data_provider()); EXPECT_TRUE(loading()); EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); Stop(); } TEST_F(MultibufferDataSourceTest, MediaPlaybackRateChanged) { InitializeWith206Response(); data_source_->MediaPlaybackRateChanged(2.0); base::RunLoop().RunUntilIdle(); EXPECT_EQ(2.0, data_source_playback_rate()); // Read so far ahead to cause the loader to get recreated. TestMultiBufferDataProvider* old_loader = data_provider(); ReadAt(kFarReadPosition); Respond(response_generator_->Generate206(kFarReadPosition)); // Verify loader changed but still has same playback rate. EXPECT_NE(old_loader, data_provider()); EXPECT_TRUE(loading()); EXPECT_CALL(*this, ReadCallback(media::DataSource::kReadError)); Stop(); } TEST_F(MultibufferDataSourceTest, Http_Read) { InitializeWith206Response(); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0, kDataSize * 2); ReadAt(kDataSize, kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + kDataSize / 2)); ReceiveData(kDataSize / 2); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize / 2); EXPECT_TRUE(data_source_->downloading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_ShareData) { InitializeWith206Response(); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0, kDataSize * 2); ReadAt(kDataSize, kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + kDataSize / 2)); ReceiveData(kDataSize / 2); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize / 2); EXPECT_TRUE(data_source_->downloading()); StrictMock<MockBufferedDataSourceHost> host2; MockMultibufferDataSource source2( base::ThreadTaskRunnerHandle::Get(), url_index_->GetByUrl(GURL(kHttpUrl), UrlData::CORS_UNSPECIFIED), &host2); source2.SetPreload(preload_); EXPECT_CALL(*this, OnInitialize(true)); // This call would not be expected if we were not sharing data. EXPECT_CALL(host2, SetTotalBytes(response_generator_->content_length())); EXPECT_CALL(host2, AddBufferedByteRange(0, kDataSize * 2)); source2.Initialize(base::Bind(&MultibufferDataSourceTest::OnInitialize, base::Unretained(this))); base::RunLoop().RunUntilIdle(); // Always loading after initialize. EXPECT_EQ(source2.downloading(), true); Stop(); } TEST_F(MultibufferDataSourceTest, Http_Read_Seek) { InitializeWith206Response(); // Read a bit from the beginning. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Simulate a seek by reading a bit beyond kDataSize. ReadAt(kDataSize * 2); // We receive data leading up to but not including our read. // No notification will happen, since it's progress outside // of our current range. ReceiveData(kDataSize); // We now receive the rest of the data for our read. EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); ReceiveData(kDataSize); EXPECT_TRUE(data_source_->downloading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_Read) { InitializeWithFileResponse(); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0, kDataSize * 2); ReadAt(kDataSize, kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReceiveData(kDataSize); Stop(); } TEST_F(MultibufferDataSourceTest, Http_FinishLoading) { InitializeWith206Response(); EXPECT_TRUE(data_source_->downloading()); // premature didFinishLoading() will cause a retry. FinishLoading(); EXPECT_TRUE(data_source_->downloading()); Stop(); } TEST_F(MultibufferDataSourceTest, File_FinishLoading) { InitializeWithFileResponse(); ReceiveData(kDataSize); EXPECT_FALSE(data_source_->downloading()); // premature didFinishLoading() will cause a retry. FinishLoading(); EXPECT_FALSE(data_source_->downloading()); Stop(); } TEST_F(MultibufferDataSourceTest, LocalResource_DeferStrategy) { InitializeWithFileResponse(); EXPECT_EQ(MultibufferDataSource::AUTO, preload()); EXPECT_TRUE(is_local_source()); CheckCapacityDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, LocalResource_PreloadMetadata_DeferStrategy) { set_preload(MultibufferDataSource::METADATA); InitializeWithFileResponse(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_TRUE(is_local_source()); CheckReadThenDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Reponse200_DeferStrategy) { InitializeWith200Response(); EXPECT_EQ(MultibufferDataSource::AUTO, preload()); EXPECT_FALSE(is_local_source()); EXPECT_FALSE(data_source_->range_supported()); CheckCapacityDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response200_PreloadMetadata_DeferStrategy) { set_preload(MultibufferDataSource::METADATA); InitializeWith200Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_FALSE(data_source_->range_supported()); CheckReadThenDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Reponse206_DeferStrategy) { InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::AUTO, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckCapacityDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); set_might_be_reused_from_cache_in_future(true); data_source_->MediaIsPlaying(); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_PreloadMetadata_DeferStrategy) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); data_source_->MediaIsPlaying(); CheckCapacityDefer(); set_might_be_reused_from_cache_in_future(true); data_source_->MediaIsPlaying(); CheckCapacityDefer(); set_might_be_reused_from_cache_in_future(false); CheckCapacityDefer(); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_VerifyDefer) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); // Read a bit from the beginning. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); ASSERT_TRUE(active_loader()); EXPECT_TRUE(data_provider()->deferred()); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_CancelAfterDefer) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); ReadAt(kDataSize); data_source_->OnBufferingHaveEnough(false); ASSERT_TRUE(active_loader()); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); ReceiveData(kDataSize); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 4)); ReceiveData(kDataSize); EXPECT_FALSE(active_loader_allownull()); } // This test tries to trigger an edge case where the read callback // never happens because the reader is deleted before that happens. TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_CancelAfterDefer2) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); ReadAt(kDataSize); data_source_->OnBufferingHaveEnough(false); ASSERT_TRUE(active_loader()); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + 2000)); ReceiveDataLow(2000); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2 + 2000)); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize * 2, kDataSize * 2 + 2000)); ReceiveDataLow(kDataSize); base::RunLoop().RunUntilIdle(); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3 + 2000)); ReceiveData(kDataSize); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 4 + 2000)); ReceiveData(kDataSize); EXPECT_FALSE(active_loader_allownull()); } // This test tries to trigger an edge case where the read callback // never happens because the reader is deleted before that happens. TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_CancelAfterDefer3) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); ReadAt(kDataSize); ASSERT_TRUE(active_loader()); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); ReceiveData(kDataSize); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 4)); ReceiveData(kDataSize); EXPECT_EQ(data_source_->downloading(), false); data_source_->Read(kDataSize * 10, kDataSize, buffer_, base::Bind(&MultibufferDataSourceTest::ReadCallback, base::Unretained(this))); data_source_->OnBufferingHaveEnough(false); EXPECT_TRUE(active_loader_allownull()); EXPECT_CALL(*this, ReadCallback(-1)); Stop(); } TEST_F(MultibufferDataSourceTest, ExternalResource_Response206_CancelAfterPlay) { set_preload(MultibufferDataSource::METADATA); InitializeWith206Response(); EXPECT_EQ(MultibufferDataSource::METADATA, preload()); EXPECT_FALSE(is_local_source()); EXPECT_TRUE(data_source_->range_supported()); CheckReadThenDefer(); ReadAt(kDataSize); // Marking the media as playing should prevent deferral. It also tells the // data source to start buffering beyond the initial load. data_source_->MediaIsPlaying(); data_source_->OnBufferingHaveEnough(false); CheckCapacityDefer(); ASSERT_TRUE(active_loader()); // Read a bit from the beginning and ensure deferral hasn't happened yet. EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); ASSERT_TRUE(active_loader()); data_source_->OnBufferingHaveEnough(true); ASSERT_TRUE(active_loader()); ASSERT_FALSE(data_provider()->deferred()); // Deliver data until capacity is reached and verify deferral. int bytes_received = 0; EXPECT_CALL(host_, AddBufferedByteRange(_, _)).Times(testing::AtLeast(1)); while (active_loader_allownull() && !data_provider()->deferred()) { ReceiveData(kDataSize); bytes_received += kDataSize; } EXPECT_GT(bytes_received, 0); EXPECT_LT(bytes_received + kDataSize, kFileSize); EXPECT_FALSE(active_loader_allownull()); } TEST_F(MultibufferDataSourceTest, SeekPastEOF) { GURL gurl(kHttpUrl); data_source_.reset(new MockMultibufferDataSource( base::ThreadTaskRunnerHandle::Get(), url_index_->GetByUrl(gurl, UrlData::CORS_UNSPECIFIED), &host_)); data_source_->SetPreload(preload_); response_generator_.reset(new TestResponseGenerator(gurl, kDataSize + 1)); EXPECT_CALL(*this, OnInitialize(true)); data_source_->Initialize(base::Bind(&MultibufferDataSourceTest::OnInitialize, base::Unretained(this))); base::RunLoop().RunUntilIdle(); // Not really loading until after OnInitialize is called. EXPECT_EQ(data_source_->downloading(), false); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); // Read a bit from the beginning. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + 1)); ReceiveData(1); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); FinishLoading(); EXPECT_CALL(*this, ReadCallback(0)); ReadAt(kDataSize + 5, kDataSize * 2); Stop(); } TEST_F(MultibufferDataSourceTest, Http_RetryThenRedirect) { InitializeWith206Response(); // Read to advance our position. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); // Issue a pending read but trigger an error to force a retry. EXPECT_CALL(*this, ReadCallback(kDataSize - 10)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReadAt(kDataSize + 10, kDataSize - 10); base::RunLoop run_loop; data_provider()->DidFail(response_generator_->GenerateError()); data_provider()->RunOnStart(run_loop.QuitClosure()); run_loop.Run(); // Server responds with a redirect. blink::WebURL url{GURL(kHttpDifferentPathUrl)}; blink::WebURLResponse response((GURL(kHttpUrl))); response.SetHttpStatusCode(307); data_provider()->WillFollowRedirect(url, response); Respond(response_generator_->Generate206(kDataSize)); ReceiveData(kDataSize); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); FinishLoading(); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_NotStreamingAfterRedirect) { Initialize(kHttpUrl, true); // Server responds with a redirect. blink::WebURL url{GURL(kHttpDifferentPathUrl)}; blink::WebURLResponse response((GURL(kHttpUrl))); response.SetHttpStatusCode(307); data_provider()->WillFollowRedirect(url, response); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_FALSE(data_source_->IsStreaming()); FinishLoading(); EXPECT_FALSE(loading()); Stop(); } TEST_F(MultibufferDataSourceTest, Http_RangeNotSatisfiableAfterRedirect) { Initialize(kHttpUrl, true); // Server responds with a redirect. blink::WebURL url{GURL(kHttpDifferentPathUrl)}; blink::WebURLResponse response((GURL(kHttpUrl))); response.SetHttpStatusCode(307); data_provider()->WillFollowRedirect(url, response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); Respond(response_generator_->GenerateResponse(416)); Stop(); } TEST_F(MultibufferDataSourceTest, Http_404AfterRedirect) { Initialize(kHttpUrl, false); // Server responds with a redirect. blink::WebURL url{GURL(kHttpDifferentPathUrl)}; blink::WebURLResponse response((GURL(kHttpUrl))); response.SetHttpStatusCode(307); data_provider()->WillFollowRedirect(url, response); Respond(response_generator_->Generate404()); Stop(); } TEST_F(MultibufferDataSourceTest, LengthKnownAtEOF) { Initialize(kHttpUrl, true); // Server responds without content-length. WebURLResponse response = response_generator_->Generate200(); response.ClearHttpHeaderField(WebString::FromUTF8("Content-Length")); response.SetExpectedContentLength(kPositionNotSpecified); Respond(response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); int64_t len; EXPECT_FALSE(data_source_->GetSize(&len)); EXPECT_TRUE(data_source_->IsStreaming()); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); ReadAt(kDataSize); EXPECT_CALL(host_, SetTotalBytes(kDataSize)); EXPECT_CALL(*this, ReadCallback(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); FinishLoading(); // Done loading, now we should know the length. EXPECT_TRUE(data_source_->GetSize(&len)); EXPECT_EQ(kDataSize, len); Stop(); } TEST_F(MultibufferDataSourceTest, FileSizeLessThanBlockSize) { Initialize(kHttpUrl, true); GURL gurl(kHttpUrl); blink::WebURLResponse response(gurl); response.SetHttpStatusCode(200); response.SetHttpHeaderField( WebString::FromUTF8("Content-Length"), WebString::FromUTF8(base::NumberToString(kDataSize / 2))); response.SetExpectedContentLength(kDataSize / 2); Respond(response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize / 2)); EXPECT_CALL(host_, SetTotalBytes(kDataSize / 2)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize / 2); FinishLoading(); int64_t len = 0; EXPECT_TRUE(data_source_->GetSize(&len)); EXPECT_EQ(kDataSize / 2, len); Stop(); } TEST_F(MultibufferDataSourceTest, ResponseTypeBasic) { InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS); set_preload(MultibufferDataSource::NONE); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetType(network::mojom::FetchResponseType::kBasic); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsCorsCrossOrigin()); FinishLoading(); } TEST_F(MultibufferDataSourceTest, ResponseTypeCors) { InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS); set_preload(MultibufferDataSource::NONE); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetType(network::mojom::FetchResponseType::kCors); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsCorsCrossOrigin()); FinishLoading(); } TEST_F(MultibufferDataSourceTest, ResponseTypeDefault) { InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS); set_preload(MultibufferDataSource::NONE); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetType(network::mojom::FetchResponseType::kDefault); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); EXPECT_FALSE(data_source_->IsCorsCrossOrigin()); FinishLoading(); } TEST_F(MultibufferDataSourceTest, ResponseTypeOpaque) { InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS); set_preload(MultibufferDataSource::NONE); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetType(network::mojom::FetchResponseType::kOpaque); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); EXPECT_TRUE(data_source_->IsCorsCrossOrigin()); FinishLoading(); } TEST_F(MultibufferDataSourceTest, ResponseTypeOpaqueRedirect) { InitializeWithCors(kHttpUrl, true, UrlData::CORS_ANONYMOUS); set_preload(MultibufferDataSource::NONE); WebURLResponse response1 = response_generator_->GeneratePartial206(0, kDataSize - 1); response1.SetType(network::mojom::FetchResponseType::kOpaqueRedirect); EXPECT_CALL(host_, SetTotalBytes(kFileSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); EXPECT_CALL(*this, ReadCallback(kDataSize)); Respond(response1); ReceiveData(kDataSize); ReadAt(0); EXPECT_TRUE(loading()); EXPECT_TRUE(data_source_->IsCorsCrossOrigin()); FinishLoading(); } TEST_F(MultibufferDataSourceTest, EtagTest) { Initialize(kHttpUrl, true); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); WebURLResponse response = response_generator_->Generate206(0); const std::string etag("\"arglebargle glop-glyf?\""); response.SetHttpHeaderField(WebString::FromUTF8("Etag"), WebString::FromUTF8(etag)); Respond(response); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_EQ(url_data()->etag(), etag); } TEST_F(MultibufferDataSourceTest, CheckBufferSizes) { InitializeWith206Response(1 << 30); // 1 gb data_source_->SetBitrate(1 << 20); // 1 mbit / s base::RunLoop().RunUntilIdle(); EXPECT_EQ(1 << 20, data_source_bitrate()); EXPECT_EQ(2 << 20, preload_low()); EXPECT_EQ(3 << 20, preload_high()); EXPECT_EQ(25 << 20, max_buffer_forward()); EXPECT_EQ(2 << 20, max_buffer_backward()); EXPECT_EQ(1572864 /* 1.5Mb */, buffer_size()); data_source_->SetBitrate(8 << 20); // 8 mbit / s base::RunLoop().RunUntilIdle(); EXPECT_EQ(8 << 20, data_source_bitrate()); EXPECT_EQ(10 << 20, preload_low()); EXPECT_EQ(11 << 20, preload_high()); EXPECT_EQ(25 << 20, max_buffer_forward()); EXPECT_EQ(2 << 20, max_buffer_backward()); EXPECT_EQ(12 << 20, buffer_size()); data_source_->SetBitrate(16 << 20); // 16 mbit / s base::RunLoop().RunUntilIdle(); EXPECT_EQ(16 << 20, data_source_bitrate()); EXPECT_EQ(20 << 20, preload_low()); EXPECT_EQ(21 << 20, preload_high()); EXPECT_EQ(25 << 20, max_buffer_forward()); EXPECT_EQ(4 << 20, max_buffer_backward()); EXPECT_EQ(24 << 20, buffer_size()); data_source_->SetBitrate(32 << 20); // 32 mbit / s base::RunLoop().RunUntilIdle(); EXPECT_EQ(32 << 20, data_source_bitrate()); EXPECT_EQ(40 << 20, preload_low()); EXPECT_EQ(41 << 20, preload_high()); EXPECT_EQ(41 << 20, max_buffer_forward()); EXPECT_EQ(8 << 20, max_buffer_backward()); EXPECT_EQ(48 << 20, buffer_size()); data_source_->SetBitrate(80 << 20); // 80 mbit / s base::RunLoop().RunUntilIdle(); EXPECT_EQ(80 << 20, data_source_bitrate()); EXPECT_EQ(50 << 20, preload_low()); EXPECT_EQ(51 << 20, preload_high()); EXPECT_EQ(51 << 20, max_buffer_forward()); EXPECT_EQ(20 << 20, max_buffer_backward()); EXPECT_EQ(71 << 20, buffer_size()); } TEST_F(MultibufferDataSourceTest, CheckBufferSizeForSmallFiles) { InitializeWith206Response(); data_source_->SetBitrate(1 << 20); // 1 mbit / s base::RunLoop().RunUntilIdle(); EXPECT_EQ(1 << 20, data_source_bitrate()); EXPECT_EQ(2 << 20, preload_low()); EXPECT_EQ(3 << 20, preload_high()); EXPECT_EQ(25 << 20, max_buffer_forward()); EXPECT_EQ(kFileSize * 2, max_buffer_backward()); EXPECT_EQ(5013504 /* file size rounded up to blocks size */, buffer_size()); data_source_->SetBitrate(80 << 20); // 80 mbit / s base::RunLoop().RunUntilIdle(); EXPECT_EQ(80 << 20, data_source_bitrate()); EXPECT_EQ(50 << 20, preload_low()); EXPECT_EQ(51 << 20, preload_high()); EXPECT_EQ(51 << 20, max_buffer_forward()); EXPECT_EQ(20 << 20, max_buffer_backward()); EXPECT_EQ(5013504 /* file size rounded up to blocks size */, buffer_size()); } TEST_F(MultibufferDataSourceTest, CheckBufferSizeAfterReadingALot) { InitializeWith206Response(); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); const int to_read = 40; for (int i = 1; i < to_read; i++) { EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * (i + 1))); ReadAt(i * kDataSize); ReceiveData(kDataSize); } data_source_->SetBitrate(1 << 20); // 1 mbit / s base::RunLoop().RunUntilIdle(); int64_t extra_buffer = to_read / 10 * kDataSize; EXPECT_EQ(1 << 20, data_source_bitrate()); EXPECT_EQ((2 << 20) + extra_buffer, preload_low()); EXPECT_EQ((3 << 20) + extra_buffer, preload_high()); EXPECT_EQ(25 << 20, max_buffer_forward()); EXPECT_EQ(kFileSize * 2, max_buffer_backward()); EXPECT_EQ(5013504 /* file size rounded up to blocks size */, buffer_size()); } // Provoke an edge case where the loading state may not end up transitioning // back to "idle" when we're done loading. TEST_F(MultibufferDataSourceTest, Http_CheckLoadingTransition) { GURL gurl(kHttpUrl); data_source_.reset(new MockMultibufferDataSource( base::ThreadTaskRunnerHandle::Get(), url_index_->GetByUrl(gurl, UrlData::CORS_UNSPECIFIED), &host_)); data_source_->SetPreload(preload_); response_generator_.reset(new TestResponseGenerator(gurl, kDataSize * 1)); EXPECT_CALL(*this, OnInitialize(true)); data_source_->Initialize(base::Bind(&MultibufferDataSourceTest::OnInitialize, base::Unretained(this))); base::RunLoop().RunUntilIdle(); // Not really loading until after OnInitialize is called. EXPECT_EQ(data_source_->downloading(), false); EXPECT_CALL(host_, SetTotalBytes(response_generator_->content_length())); Respond(response_generator_->Generate206(0)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize)); ReceiveData(kDataSize); EXPECT_EQ(data_source_->downloading(), true); EXPECT_CALL(host_, AddBufferedByteRange(kDataSize, kDataSize + 1)); ReceiveDataLow(1); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); data_provider()->DidFinishLoading(); EXPECT_CALL(*this, ReadCallback(1)); data_source_->Read(kDataSize, 2, buffer_, base::Bind(&MultibufferDataSourceTest::ReadCallback, base::Unretained(this))); base::RunLoop().RunUntilIdle(); // Make sure we're not downloading anymore. EXPECT_EQ(data_source_->downloading(), false); Stop(); } TEST_F(MultibufferDataSourceTest, Http_Seek_Back) { InitializeWith206Response(); // Read a bit from the beginning. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); ReadAt(kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 2)); ReceiveData(kDataSize); ReadAt(kDataSize * 2); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(0, kDataSize * 3)); ReceiveData(kDataSize); // Read some data from far ahead. ReadAt(kFarReadPosition); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(kFarReadPosition, kFarReadPosition + kDataSize)); Respond(response_generator_->Generate206(kFarReadPosition)); ReceiveData(kDataSize); // This should not close the current connection, because we have // more data buffered at this location than at kFarReadPosition. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); data_source_->CallSeekTask(); EXPECT_EQ(kFarReadPosition + kDataSize, loader()->Tell()); // Again, no seek. EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(kDataSize); data_source_->CallSeekTask(); EXPECT_EQ(kFarReadPosition + kDataSize, loader()->Tell()); // Still no seek EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(kFarReadPosition); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(kDataSize * 2); data_source_->CallSeekTask(); EXPECT_EQ(kFarReadPosition + kDataSize, loader()->Tell()); // Read some data from far ahead, but right before where we read before. // This time we'll have one block buffered. ReadAt(kFarReadPosition - kDataSize); EXPECT_CALL(*this, ReadCallback(kDataSize)); EXPECT_CALL(host_, AddBufferedByteRange(kFarReadPosition - kDataSize, kFarReadPosition + kDataSize)); Respond(response_generator_->Generate206(kFarReadPosition - kDataSize)); ReceiveData(kDataSize); // No Seek EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(0); data_source_->CallSeekTask(); EXPECT_EQ(kFarReadPosition, loader()->Tell()); // Seek EXPECT_CALL(*this, ReadCallback(kDataSize)); ReadAt(kDataSize * 2); data_source_->CallSeekTask(); EXPECT_EQ(kDataSize * 3, loader()->Tell()); Stop(); } } // namespace media
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
96e94a8b346463092364f768ae3f28ecf734054a
59115bea46bcf235852e1308d79f07bd07406894
/aieBootstrap-physics/2dTest/Sphere.cpp
afe47b27a51dad1cd6aae92196e8aa1cb593dff9
[ "MIT" ]
permissive
AnonUser676/PhysicsAIE
bb4ba3f081fbcac5f85b3385012bd3fc7cdc6297
f21dce33481740270f82ce33c8323d215d97269c
refs/heads/master
2021-05-03T10:26:45.650164
2018-03-07T00:36:28
2018-03-07T00:36:28
120,534,737
0
0
null
null
null
null
UTF-8
C++
false
false
598
cpp
#include "Sphere.h" Sphere::Sphere(vec2 position, vec2 velocity, float mass, float radius, vec4 color):Rigidbody(SPHERE, position,velocity,0,mass) { m_radius = radius; m_color = color; m_position = position; m_velocity = velocity; m_mass = mass; } Sphere::~Sphere() { } void Sphere::makeGizmo() { Gizmos::add2DCircle(m_position, m_radius, 12, m_color); } bool Sphere::checkCollision(PhysicsObject* pOther) { Sphere* other = dynamic_cast<Sphere*>(pOther); if (other) { return ((other->m_radius + this->m_radius) > distance(other->m_position, this->m_position)); } return false; }
[ "rouie.ortega@live.com" ]
rouie.ortega@live.com
f12ed198f5ac8358723ecdae9fde47cd68b150c3
f279c5a1df1dacf422cf7d47fb01a2fb41510838
/8. Parallel programming/OpenMP/critical_section.cpp
eba59009f08318f0a49cc1cebf90e259cf15d0cc
[]
no_license
newmersedez/multithreaded_programming
a939821b4b55383f67e0b309859b46a15f030593
351abd39b422c7c23d9069b1dead22e6983d69bc
refs/heads/main
2023-08-27T04:00:27.156899
2021-10-24T01:15:46
2021-10-24T01:15:46
415,411,020
0
0
null
null
null
null
UTF-8
C++
false
false
166
cpp
#include <iostream> int main(int argc, char *argv[]) { #pragma omp parallel { #pragma omp critical { std::cout << "output" << std::endl; } } return 0; }
[ "trishkk2001@gmail.com" ]
trishkk2001@gmail.com
ee57983d0a23b55dc24fdcb1f7ac03ed21286737
67d9a8912f2e04f341de00c83dcf9a1ebfa13320
/CangJian.cpp
24608afe0e14964c702c79ada810cdecfeca07f1
[]
no_license
thysm008/CardHero
1d98fcc7d730d84fded22562feb4dc1d795b4b35
32b97e168f024b63dda994fd40249885d1ab5a2d
refs/heads/master
2020-05-30T00:34:08.741651
2017-03-08T14:48:36
2017-03-08T14:48:36
82,621,434
0
0
null
null
null
null
UTF-8
C++
false
false
968
cpp
#include "stdafx.h" #include "CangJian.h" #include "Character.h" CCangJian::CCangJian(CString name, CString pro, int char_id_, int pro_id_, int camp_) { char_name = name; pro_name = pro; char_id = char_id_; pro_id = pro_id_; camp = camp_; } void CCangJian::setJianQi(int n) { cur_jianqi = n; } void CCangJian::addJianQi(int n) { cur_jianqi = cur_jianqi + n; if (cur_jianqi > MAX_JIANQI) cur_jianqi = 7; } void CCangJian::subJianQi(int n) { cur_jianqi = cur_jianqi - n; if (cur_jianqi < 0) cur_jianqi = 0; } int CCangJian::getJianQi() { if (cur_jianqi < 0) return 0; else if (cur_jianqi > MAX_JIANQI) return MAX_JIANQI; else return cur_jianqi; } void CCangJian::setStatus(int i) { sword_status = i; } int CCangJian::getStatus() { return sword_status; } void CCangJian::setShield(int i) { shield = i; } void CCangJian::subShield(int i) { shield -= i; if (shield < 0) shield = 0; } int CCangJian::getShield() { return shield; }
[ "thysm008@qq.com" ]
thysm008@qq.com
1a3cc700228ef5ce0fc3a6d59534482b07000476
288281ea9d5c6344706f267731d9798d527d71d3
/taint-tracking/src/ins_clear_op.cpp
84937ff48f851b1a83e1fff9fa06550e99e40d00
[ "MIT" ]
permissive
UzL-ITS/cipherfix
58847e6454a5888c6345d460b9b8242a375d9f9d
0d05fcbe48498acc827ad0373cd7244c590b27c4
refs/heads/master
2023-07-04T12:13:33.801949
2023-04-14T15:22:30
2023-04-14T15:22:30
556,843,329
2
0
null
null
null
null
UTF-8
C++
false
false
4,102
cpp
#include "ins_clear_op.h" #include "ins_helper.h" /* threads context */ extern thread_ctx_t *threads_ctx; static void PIN_FAST_ANALYSIS_CALL r_clrl4(THREADID tid) { for (size_t i = 0; i < 8; i++) { RTAG[DFT_REG_RDX][i] = tag_traits<tag_t>::cleared_val; RTAG[DFT_REG_RCX][i] = tag_traits<tag_t>::cleared_val; RTAG[DFT_REG_RBX][i] = tag_traits<tag_t>::cleared_val; RTAG[DFT_REG_RAX][i] = tag_traits<tag_t>::cleared_val; } } static void PIN_FAST_ANALYSIS_CALL r_clrl2(THREADID tid) { for (size_t i = 0; i < 8; i++) { RTAG[DFT_REG_RDX][i] = tag_traits<tag_t>::cleared_val; RTAG[DFT_REG_RAX][i] = tag_traits<tag_t>::cleared_val; } } static void PIN_FAST_ANALYSIS_CALL r_clrb_l(THREADID tid, uint32_t reg) { RTAG[reg][0] = tag_traits<tag_t>::cleared_val; } static void PIN_FAST_ANALYSIS_CALL r_clrb_u(THREADID tid, uint32_t reg) { RTAG[reg][1] = tag_traits<tag_t>::cleared_val; } static void PIN_FAST_ANALYSIS_CALL r_clrw(THREADID tid, uint32_t reg) { for (size_t i = 0; i < 2; i++) { RTAG[reg][i] = tag_traits<tag_t>::cleared_val; } } static void PIN_FAST_ANALYSIS_CALL r_clrl(THREADID tid, uint32_t reg) { for (size_t i = 0; i < 4; i++) { RTAG[reg][i] = tag_traits<tag_t>::cleared_val; } } static void PIN_FAST_ANALYSIS_CALL r_clrq(THREADID tid, uint32_t reg) { for (size_t i = 0; i < 8; i++) { RTAG[reg][i] = tag_traits<tag_t>::cleared_val; } } static void PIN_FAST_ANALYSIS_CALL r_clrx(THREADID tid, uint32_t reg) { for (size_t i = 0; i < 16; i++) { RTAG[reg][i] = tag_traits<tag_t>::cleared_val; } } static void PIN_FAST_ANALYSIS_CALL r_clry(THREADID tid, uint32_t reg) { for (size_t i = 0; i < 32; i++) { RTAG[reg][i] = tag_traits<tag_t>::cleared_val; } } void ins_clear_op(INS ins) { if (INS_OperandIsMemory(ins, OP_0)) { INT32 n = INS_OperandWidth(ins, OP_0) / 8; M_CLEAR_N(n); } else { REG reg_dst = INS_OperandReg(ins, OP_0); if (REG_is_gr64(reg_dst)) { R_CALL(r_clrq, reg_dst); } else if (REG_is_gr32(reg_dst)) { R_CALL(r_clrl, reg_dst); } else if (REG_is_gr16(reg_dst)) { R_CALL(r_clrw, reg_dst); } else if (REG_is_xmm(reg_dst)) { R_CALL(r_clrx, reg_dst); } else if (REG_is_mm(reg_dst)) { R_CALL(r_clrq, reg_dst); } else if (REG_is_ymm(reg_dst)) { R_CALL(r_clry, reg_dst); } else { if (REG_is_Upper8(reg_dst)) R_CALL(r_clrb_u, reg_dst); else R_CALL(r_clrb_l, reg_dst); } } } void ins_clear_op_predicated(INS ins) { // one byte if (INS_MemoryOperandCount(ins) == 0) { REG reg_dst = INS_OperandReg(ins, OP_0); if (REG_is_Upper8(reg_dst)) INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)r_clrb_u, IARG_FAST_ANALYSIS_CALL, IARG_THREAD_ID, IARG_UINT32, REG_INDX(reg_dst), IARG_END); else INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)r_clrb_l, IARG_FAST_ANALYSIS_CALL, IARG_THREAD_ID, IARG_UINT32, REG_INDX(reg_dst), IARG_END); } else INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)tagmap_clrn, IARG_FAST_ANALYSIS_CALL, IARG_MEMORYWRITE_EA, IARG_UINT32, 1, IARG_END); } void ins_clear_op_l2(INS ins) { INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)r_clrl2, IARG_FAST_ANALYSIS_CALL, IARG_THREAD_ID, IARG_END); } void ins_clear_op_l4(INS ins) { INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)r_clrl4, IARG_FAST_ANALYSIS_CALL, IARG_THREAD_ID, IARG_END); } VOID clear_ymm_upper(THREADID tid) { // YMM upper bytes are from DFT_REGs 19 - 34 (XMM0 - XMM15) // Iterate over all registers and clear the taint of the upper 128 bits for (int i = 19; i < 35; ++i) { for (size_t j = 16; j < 32; ++j) { RTAG[i][j] = tag_traits<tag_t>::cleared_val; } } } void ins_vzeroupper_op(INS ins) { INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)clear_ymm_upper, IARG_THREAD_ID, IARG_END); }
[ "j.wichelmann@uni-luebeck.de" ]
j.wichelmann@uni-luebeck.de
7e37a2f9985af0f94d32de367e12fd6cdd029df5
30b7ffd17845db982883a91ce8d04551281658c4
/Self Marathon/Practice/September 2020 :: Codificador Rojo/Day 9/test-J.cpp
0d43b2a16dded49d0e3dbd1550bf72b75bf91f01
[]
no_license
shas9/codehub
95418765b602b52edb0d48a473ad7e7a798f76e5
bda856bf6ca0f3a1d59980895cfab82f690c75a2
refs/heads/master
2023-06-21T01:09:34.275708
2021-07-26T14:54:03
2021-07-26T14:54:03
389,404,954
0
0
null
null
null
null
UTF-8
C++
false
false
1,164
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false), cin.tie(0); int n, q; cin >> n >> q; vector<int> a(n+1), ans(q), leftBound(q); vector<vector<int>> endHere(n+1); for (int i = 1; i <= n; ++i) { cin >> a[i]; a[i] = i - a[i]; } for (int i = 0; i < q; ++i) { int x, y; cin >> x >> y; int l = 1+x, r = n-y; leftBound[i] = l; endHere[r].push_back(i); } vector<int> BIT(n+1); int global = 0; for (int r = 1; r <= n; ++r) { int target = a[r]; if (target >= 0) { // Find rightmost pos such that s[pos] >= target int pos = 0, cur = global; for (int jump = 1 << __lg(n); jump >= 1; jump /= 2) if (pos+jump <= r && cur - BIT[pos+jump] >= target) pos += jump, cur -= BIT[pos]; // Increment prefix (+1 on whole array, -1 on suffix) ++global; cout << r << ": " << global << " " << pos << " " << target << endl; for (int i = pos+1; i <= n; i += i & -i) ++BIT[i]; } for (int iQuery : endHere[r]) { ans[iQuery] = global; for (int i = leftBound[iQuery]; i > 0; i -= i & -i) ans[iQuery] -= BIT[i]; } } for (int i = 0; i < q; ++i) cout << ans[i] << "\n"; }
[ "shahwathasnaine@gmail.com" ]
shahwathasnaine@gmail.com
90edbad12c809559a87086ba4c0a58f9205fa49b
9fbbf9cda869bc318fe99874ebeb7ca8dd1a3799
/Utils/interface/FitSolution.hh
9041a56ff16520746c30f500b7de7019b49abe9c
[]
no_license
ssevova/ttbarAnaSolver
d92cfdadfa7b482f8850708732f84e82bdabd583
57720f740c84737e25e6ef8028c4f7934444defd
refs/heads/master
2021-01-11T23:02:10.403805
2017-01-18T17:47:14
2017-01-18T17:47:14
78,534,297
0
0
null
null
null
null
UTF-8
C++
false
false
547
hh
#ifndef FIT_SOLUTION #define FIT_SOLUTION class FitSolution { public: FitSolution(): numSol(-1.) {} ~FitSolution(){} std::vector<TLorentzVector> nu1; std::vector<TLorentzVector> nu2; int numSol; std::vector<double> mass1; std::vector<double> mass2; std::vector<double> weight; std::vector<double> cudisc; std::vector<double> mtt; // KH void reset() { mass1.clear(); mass2.clear(); weight.clear(); cudisc.clear(); mtt.clear(); nu1.clear(); nu2.clear(); numSol=0; } }; #endif
[ "ssevova@gmail.com" ]
ssevova@gmail.com
bb9d46fedc5ac569fe67549cc3b64a264c67965a
2019d94fe0d8b32959190d02dd1ee367f524878e
/Practice for C++/Inheritance/05_magic_spells.cpp
202118de7e723dd3e42ffaeaa2324198816b1f08
[]
no_license
yang4978/Hackerrank_for_Cpp
bfd9065bd4924b26b30961d4d734a7bb891fe2e2
4c3dde90bcc72a0a7e14eda545257c128db313f7
refs/heads/master
2020-05-21T06:05:26.451065
2019-08-11T15:19:13
2019-08-11T15:19:13
185,934,553
0
0
null
null
null
null
UTF-8
C++
false
false
3,663
cpp
//https://www.hackerrank.com/challenges/magic-spells/problem #include <iostream> #include <vector> #include <string> using namespace std; class Spell { private: string scrollName; public: Spell(): scrollName("") { } Spell(string name): scrollName(name) { } virtual ~Spell() { } string revealScrollName() { return scrollName; } }; class Fireball : public Spell { private: int power; public: Fireball(int power): power(power) { } void revealFirepower(){ cout << "Fireball: " << power << endl; } }; class Frostbite : public Spell { private: int power; public: Frostbite(int power): power(power) { } void revealFrostpower(){ cout << "Frostbite: " << power << endl; } }; class Thunderstorm : public Spell { private: int power; public: Thunderstorm(int power): power(power) { } void revealThunderpower(){ cout << "Thunderstorm: " << power << endl; } }; class Waterbolt : public Spell { private: int power; public: Waterbolt(int power): power(power) { } void revealWaterpower(){ cout << "Waterbolt: " << power << endl; } }; class SpellJournal { public: static string journal; static string read() { return journal; } }; string SpellJournal::journal = ""; void counterspell(Spell *spell) { if (spell->revealScrollName()!=""){ string s1 = spell->revealScrollName(); string s2 = SpellJournal::journal; int l1 = s1.size(); int l2 = s2.size(); int chess[l1+1][l2+1]; for(int i=0;i<=l1;i++){ for(int j=0;j<=l2;j++){ if(i==0 || j==0){ chess[i][j] = 0; } else if(s1[i-1]==s2[j-1]){ chess[i][j] = chess[i-1][j-1]+1; } else{ chess[i][j] = max(chess[i-1][j],chess[i][j-1]); } } } cout<<chess[l1][l2]<<endl; } else{ if(Fireball *fire_temp = dynamic_cast<Fireball*> (spell)){ fire_temp->revealFirepower(); delete fire_temp; } else if (Frostbite *frost_temp = dynamic_cast<Frostbite *>(spell)) { frost_temp->revealFrostpower(); delete frost_temp; } else if (Waterbolt *water_temp = dynamic_cast<Waterbolt *>(spell)) { water_temp->revealWaterpower(); delete water_temp; } else if(Thunderstorm *thunder_temp = dynamic_cast<Thunderstorm*> (spell)){ thunder_temp->revealThunderpower(); delete thunder_temp; } } } class Wizard { public: Spell *cast() { Spell *spell; string s; cin >> s; int power; cin >> power; if(s == "fire") { spell = new Fireball(power); } else if(s == "frost") { spell = new Frostbite(power); } else if(s == "water") { spell = new Waterbolt(power); } else if(s == "thunder") { spell = new Thunderstorm(power); } else { spell = new Spell(s); cin >> SpellJournal::journal; } return spell; } }; int main() { int T; cin >> T; Wizard Arawn; while(T--) { Spell *spell = Arawn.cast(); counterspell(spell); } return 0; }
[ "yang_4978@foxmail.com" ]
yang_4978@foxmail.com
d4145d7364f4715ba3f4b1c0bdf733bfd9997688
d9254711a4bdade616d2707b3df157b14a4e9750
/multidimension_newton_root.h
b52f47f7b88bce5f483f826997011972ff3d1a59
[ "MIT" ]
permissive
aofenghanyue/numericalAnalysisHomework
b3203fcec09eef205a743858e82c0cb968f4b85e
ed4db5a5d693a3973ca1c3c5f1fc3847b8f5118e
refs/heads/master
2020-11-25T10:18:53.045904
2019-12-18T06:24:07
2019-12-18T06:24:07
228,615,577
4
1
null
null
null
null
UTF-8
C++
false
false
156
h
#pragma once #include "Gauss.h" #include "commons.h" class MultidimensionNewtonRoot { private: int n; public: MatrixD jac_mat(void *jac(VectorD &x)); };
[ "1772155440@qq.com" ]
1772155440@qq.com
1acace2a393a159457a549e245240eb1048b365b
1dd825971ed4ec0193445dc9ed72d10618715106
/examples/extended/electromagnetic/TestEm7/include/PrimaryGeneratorMessenger.hh
63e1ef7324487d4529372a1fa3f0351085964f9c
[]
no_license
gfh16/Geant4
4d442e5946eefc855436f4df444c245af7d3aa81
d4cc6c37106ff519a77df16f8574b2fe4ad9d607
refs/heads/master
2021-06-25T22:32:21.104339
2020-11-02T13:12:01
2020-11-02T13:12:01
158,790,658
0
0
null
null
null
null
UTF-8
C++
false
false
2,718
hh
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // /// \file electromagnetic/TestEm7/include/PrimaryGeneratorMessenger.hh /// \brief Definition of the PrimaryGeneratorMessenger class // // $Id$ // //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #ifndef PrimaryGeneratorMessenger_h #define PrimaryGeneratorMessenger_h 1 #include "G4UImessenger.hh" #include "globals.hh" class PrimaryGeneratorAction; class G4UIdirectory; class G4UIcmdWithADoubleAndUnit; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... class PrimaryGeneratorMessenger: public G4UImessenger { public: PrimaryGeneratorMessenger(PrimaryGeneratorAction*); ~PrimaryGeneratorMessenger(); virtual void SetNewValue(G4UIcommand*, G4String); private: PrimaryGeneratorAction* fAction; G4UIdirectory* fGunDir; G4UIcmdWithADoubleAndUnit* fRndmCmd; }; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #endif
[ "gfh16@mails.tsinghua.edu.cn" ]
gfh16@mails.tsinghua.edu.cn
491efed239743bd0db34996e1a91932ede547540
60ccc97366c43b0f83275c2c7aabd569939f8a43
/lcpfw/net/third_party/quiche/src/quic/core/http/quic_send_control_stream_test.cc
fe849733c8207fffe779641dfdf184f834ebdec9
[ "BSD-3-Clause" ]
permissive
VestasWey/mysite
d89c886c333e5aae31a04584e592bd108ead8dd3
41ea707007b688a3ef27eec55332500e369a191f
refs/heads/master
2022-12-09T10:02:19.268154
2022-10-03T03:14:16
2022-10-03T03:14:16
118,091,757
1
1
null
2022-11-26T14:29:04
2018-01-19T07:22:23
C++
UTF-8
C++
false
false
8,142
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 "quic/core/http/quic_send_control_stream.h" #include <utility> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quic/core/crypto/null_encrypter.h" #include "quic/platform/api/quic_flags.h" #include "quic/test_tools/quic_config_peer.h" #include "quic/test_tools/quic_spdy_session_peer.h" #include "quic/test_tools/quic_test_utils.h" #include "common/platform/api/quiche_text_utils.h" namespace quic { namespace test { namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::Invoke; using ::testing::StrictMock; struct TestParams { TestParams(const ParsedQuicVersion& version, Perspective perspective) : version(version), perspective(perspective) { QUIC_LOG(INFO) << "TestParams: " << *this; } TestParams(const TestParams& other) : version(other.version), perspective(other.perspective) {} friend std::ostream& operator<<(std::ostream& os, const TestParams& tp) { os << "{ version: " << ParsedQuicVersionToString(tp.version) << ", perspective: " << (tp.perspective == Perspective::IS_CLIENT ? "client" : "server") << "}"; return os; } ParsedQuicVersion version; Perspective perspective; }; // Used by ::testing::PrintToStringParamName(). std::string PrintToString(const TestParams& tp) { return absl::StrCat( ParsedQuicVersionToString(tp.version), "_", (tp.perspective == Perspective::IS_CLIENT ? "client" : "server")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (const auto& version : AllSupportedVersions()) { if (!VersionUsesHttp3(version.transport_version)) { continue; } for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) { params.emplace_back(version, p); } } return params; } class QuicSendControlStreamTest : public QuicTestWithParam<TestParams> { public: QuicSendControlStreamTest() : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective(), SupportedVersions(GetParam().version))), session_(connection_) { ON_CALL(session_, WritevData(_, _, _, _, _, _)) .WillByDefault(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); } void Initialize() { EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber()); session_.Initialize(); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); send_control_stream_ = QuicSpdySessionPeer::GetSendControlStream(&session_); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_.config(), 3); session_.OnConfigNegotiated(); } Perspective perspective() const { return GetParam().perspective; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; StrictMock<MockQuicSpdySession> session_; QuicSendControlStream* send_control_stream_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSendControlStreamTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicSendControlStreamTest, WriteSettings) { SetQuicFlag(FLAGS_quic_enable_http3_grease_randomness, false); session_.set_qpack_maximum_dynamic_table_capacity(255); session_.set_qpack_maximum_blocked_streams(16); session_.set_max_inbound_header_list_size(1024); Initialize(); testing::InSequence s; std::string expected_write_data = absl::HexStringToBytes( "00" // stream type: control stream "04" // frame type: SETTINGS frame "0b" // frame length "01" // SETTINGS_QPACK_MAX_TABLE_CAPACITY "40ff" // 255 "06" // SETTINGS_MAX_HEADER_LIST_SIZE "4400" // 1024 "07" // SETTINGS_QPACK_BLOCKED_STREAMS "10" // 16 "4040" // 0x40 as the reserved settings id "14" // 20 "4040" // 0x40 as the reserved frame type "01" // 1 byte frame length "61"); // payload "a" auto buffer = std::make_unique<char[]>(expected_write_data.size()); QuicDataWriter writer(expected_write_data.size(), buffer.get()); // A lambda to save and consume stream data when QuicSession::WritevData() is // called. auto save_write_data = [&writer, this](QuicStreamId /*id*/, size_t write_length, QuicStreamOffset offset, StreamSendingState /*state*/, TransmissionType /*type*/, absl::optional<EncryptionLevel> /*level*/) { send_control_stream_->WriteStreamData(offset, write_length, &writer); return QuicConsumedData(/* bytes_consumed = */ write_length, /* fin_consumed = */ false); }; EXPECT_CALL(session_, WritevData(send_control_stream_->id(), 1, _, _, _, _)) .WillOnce(Invoke(save_write_data)); EXPECT_CALL(session_, WritevData(send_control_stream_->id(), expected_write_data.size() - 5, _, _, _, _)) .WillOnce(Invoke(save_write_data)); EXPECT_CALL(session_, WritevData(send_control_stream_->id(), 4, _, _, _, _)) .WillOnce(Invoke(save_write_data)); send_control_stream_->MaybeSendSettingsFrame(); EXPECT_EQ(expected_write_data, absl::string_view(writer.data(), writer.length())); } TEST_P(QuicSendControlStreamTest, WriteSettingsOnlyOnce) { Initialize(); testing::InSequence s; EXPECT_CALL(session_, WritevData(send_control_stream_->id(), 1, _, _, _, _)); EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)) .Times(2); send_control_stream_->MaybeSendSettingsFrame(); // No data should be written the second time MaybeSendSettingsFrame() is // called. send_control_stream_->MaybeSendSettingsFrame(); } // Send stream type and SETTINGS frame if WritePriorityUpdate() is called first. TEST_P(QuicSendControlStreamTest, WritePriorityBeforeSettings) { Initialize(); testing::InSequence s; // The first write will trigger the control stream to write stream type, a // SETTINGS frame, and a greased frame before the PRIORITY_UPDATE frame. EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)) .Times(4); PriorityUpdateFrame frame; send_control_stream_->WritePriorityUpdate(frame); EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)); send_control_stream_->WritePriorityUpdate(frame); } TEST_P(QuicSendControlStreamTest, CloseControlStream) { Initialize(); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _)); send_control_stream_->OnStopSending(QUIC_STREAM_CANCELLED); } TEST_P(QuicSendControlStreamTest, ReceiveDataOnSendControlStream) { Initialize(); QuicStreamFrame frame(send_control_stream_->id(), false, 0, "test"); EXPECT_CALL( *connection_, CloseConnection(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, _, _)); send_control_stream_->OnStreamFrame(frame); } TEST_P(QuicSendControlStreamTest, SendGoAway) { Initialize(); StrictMock<MockHttp3DebugVisitor> debug_visitor; session_.set_debug_visitor(&debug_visitor); QuicStreamId stream_id = 4; EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(debug_visitor, OnSettingsFrameSent(_)); EXPECT_CALL(debug_visitor, OnGoAwayFrameSent(stream_id)); send_control_stream_->SendGoAway(stream_id); } } // namespace } // namespace test } // namespace quic
[ "Vestas.Wey@qq.com" ]
Vestas.Wey@qq.com
8f50de6868bc5e48af09ee9b5878ef0a50e1c04f
4628e5e79389f7d9a012778c15deaefd9b5a07f1
/modules/task_2/napylov_e_contrast/contrast.cpp
16d61512db3c3c270e7914df2ef9264f90bfab4b
[ "BSD-3-Clause" ]
permissive
BFDestroyeer/pp_2021_spring_informatics
6fdcd299b7860fe0f5f71a4967b63be93b8b59f0
508879cdc00fcf168268f9f4c99f024021719f5e
refs/heads/master
2023-03-28T00:55:23.106817
2021-03-26T06:53:45
2021-03-26T06:53:45
345,943,620
0
0
BSD-3-Clause
2021-03-09T09:00:28
2021-03-09T09:00:27
null
UTF-8
C++
false
false
3,319
cpp
// Copyright 2021 Napylov Evgenii #include <iostream> #include <cassert> #include <random> #include <ctime> #include <algorithm> #include "../../../modules/task_2/napylov_e_contrast/contrast.h" void print_vec(const VecImage& vec) { for (auto val : vec) { std::cout << static_cast<int>(val) << ' '; } std::cout << std::endl; } VecImage image_to_vec(const Image& image, int w, int h) { VecImage res(w * h); int k = 0; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { res[k++] = image[i][j]; } } return res; } Image vec_to_image(const VecImage& vec, int w, int h) { Image res(w); for (int i = 0; i < w; i++) { res[i].resize(h); for (int j = 0; j < h; j++) { res[i][j] = vec[h * i + j]; } } return res; } VecImage RandomVector(int size) { static std::mt19937 gen(time(0)); VecImage result(size); std::uniform_int_distribution<unsigned int> distr(0, 255); for (int i = 0; i < size; i++) { result[i] = static_cast<unsigned char>(distr(gen)); } return result; } VecImage add_contrast(VecImage image, unsigned char down, unsigned char up) { assert(up > down); unsigned char min = *std::min_element(image.begin(), image.end()); unsigned char max = *std::max_element(image.begin(), image.end()); if (max == min) { return image; } else { for (size_t i = 0; i < image.size(); i++) { image[i] = round((static_cast<double>((image[i] - min)) / static_cast<double>((max - min)))* (up - down)); } return image; } } std::pair<unsigned char, unsigned char> minmax_omp(const VecImage& image) { unsigned char min_col = 255; unsigned char max_col = 0; // MSVC19 does not support the min/max reduction :( // -> Each thread searches for a local min max. std::vector<unsigned char> min_vec(omp_get_max_threads()); std::fill(min_vec.begin(), min_vec.end(), 255); std::vector<unsigned char> max_vec(omp_get_max_threads()); std::fill(max_vec.begin(), max_vec.end(), 0); #pragma omp parallel for for (int i = 0; i < static_cast<int>(image.size()); i++) { if (image[i] > max_vec[omp_get_thread_num()]) { max_vec[omp_get_thread_num()] = image[i]; } if (image[i] < min_vec[omp_get_thread_num()]) { min_vec[omp_get_thread_num()] = image[i]; } } // Reduction max_col = *std::max_element(max_vec.begin(), max_vec.end()); min_col = *std::min_element(min_vec.begin(), min_vec.end()); return std::pair<double, double>(min_col, max_col); } VecImage add_contrast_omp(VecImage image, unsigned char down, unsigned char up) { assert(up > down); std::pair<double, double> minmax = minmax_omp(image); unsigned char min_col = minmax.first; unsigned char max_col = minmax.second; if (max_col == min_col) { return image; } else { #pragma omp parallel for for (int i = 0; i < static_cast<int>(image.size()); i++) { image[i] = round((static_cast<double>((image[i] - min_col)) / static_cast<double>((max_col - min_col))) * (up - down)); } return image; } }
[ "vetero4ekcs@mail.ru" ]
vetero4ekcs@mail.ru
b3ac7272ffb47ad427600885fef6c840bc36db3a
63426e63712da8b1f01ae584cd780c660c2969c3
/NineMansMorris/NineMansMorris/BoardFactory.h
b58e3ff3c843d43bf998de9a0ad3710f01b7c1f3
[]
no_license
TinEnglman/NineMansMorris
1b5af909bcef09e39a2f45e14fa288bbc07c199e
2c483ff19900e84e8df1a56c0b69a5b62fea0467
refs/heads/master
2020-05-22T16:04:58.017414
2019-05-27T09:34:28
2019-05-27T09:34:28
186,418,576
0
0
null
null
null
null
UTF-8
C++
false
false
215
h
#pragma once #include "Board.h" #include "CellData.h" class BoardFactory { public: BoardFactory(); ~BoardFactory(); Board* CreateBoard(); private: const unsigned int NUM_SLOTS = 24; CellData* _cellData; };
[ "gonzoglizli@gmail.com" ]
gonzoglizli@gmail.com
199a1bf825f3d2d3a6303a16d9fc8f73ad0a7497
51b69d63e603c010d8955013a3b67bcb567228df
/codeforces/978B.cpp
70e4fe182b331c07b30ca0ef649666fd2d437717
[]
no_license
AugustoCalaca/competitive-programming
abcb8df9b6b741d5e6ae0c9020b58c11ec4fbd2d
96bb034faaf44606970771e8a294bdf45e7a9356
refs/heads/master
2021-04-27T10:57:18.782352
2019-04-13T03:34:59
2019-04-13T03:34:59
122,549,144
6
0
null
null
null
null
UTF-8
C++
false
false
481
cpp
#include <iostream> #include <string> using namespace std; int main() { int n; string s; cin >> n >> s; int c = 0; for(int i = 0; i < n; i++) { if(s[i] == 'x') c++; else c = 0; if(c == 3) break; } if(c != 3) { cout << "0\n"; return 0; } int ans = 0; c = 0; for(int i = 0; i < n; i++) { if(s[i] == 'x') { c++; if(c >= 3) ans++; } else c = 0; } cout << ans << "\n"; return 0; }
[ "augusto@Calaca.Augusto" ]
augusto@Calaca.Augusto
5cec04916076ef0f0cd79ae646b4e289f08d56aa
4fd358a4e26f678077770db11c4f7461123351c5
/mp2/test.cpp
510709b4ec9f59bf7c52b9db4930ebd2373d32a4
[]
no_license
arjanirh/cs425
e89fe45206a5dffb7204c15f39eaa93a67811a35
94761c40633f1af172e58662814f20bfbafe8e41
refs/heads/master
2020-05-19T13:45:44.622065
2012-05-18T23:59:10
2012-05-18T23:59:10
3,635,798
1
0
null
null
null
null
UTF-8
C++
false
false
202
cpp
#include<iostream> #include<string> using namespace std; int main () { string str; cout << "Please enter full name: "; getline (cin,str); cout << "Thank you, " << str << ".\n"; }
[ "nirh1@linux7.ews.illinois.edu" ]
nirh1@linux7.ews.illinois.edu
9227f7155eb70070e1969c7a5440b7547a526d6e
14029a914f030ac5301fdabdc99299f5e322a1a5
/Cryptography_Algorithm/2018_01_DES/My des.cpp
601040a7faacf27b4363220949475b629fee4d0f
[]
no_license
joseoyeon/Cryptography
bc3a7ef8ce4db2d8acdd79bfe35f663222dc9a55
db6691d59b7676a816e3f6f076c40d569f78368b
refs/heads/master
2022-04-09T02:01:43.297934
2020-03-13T09:33:15
2020-03-13T09:33:15
187,388,602
0
1
null
null
null
null
UHC
C++
false
false
12,354
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> unsigned long long KEY; unsigned C , D; void print_binary(const unsigned long long t) { //size 는 원래 없어ok 수정하다 보니 생긴 변수 int i,b = 0; unsigned long long tmp =1LL; for (i=63; i>=0; i--,b++) { printf("%d",(t) & ((tmp << i) )? 1:0); if(b%4 == 3){printf(" ");} if(b%32== 31){printf("\n");}; } printf("\n\n"); } void print_hex(unsigned long long t) { int i=0; for(i = 15; i>=0; i--) { printf("%x", ((t >> (i*4))&0x000000F)); } printf("\n\n"); } void print_char(unsigned long long t) { int i=0; for(i = 7; i>=0; i--) { printf("%c", ((t >> (i*8))&0x000000FF)); } printf("\n\n\n"); } unsigned long long PC1(unsigned long long source) { char i; unsigned long long tmp = (1LL<<55), res = 0LL; static char perm[] = {57,49,41,33,25,17, 9,1,58,50,42,34,26,18, 10, 2,59,51,43,35,27, 19,11, 3,60,52,44,36, 63,55,47,39,31,23,15, 7,62,54,46,38,30,22, 14, 6,61,53,45,37,29, 21,13, 5,28,20,12, 4}; for(i = 0; i < 56; i++, tmp = tmp >> 1LL) if (source & (1LL << (64-perm[i]))) res |= tmp; return res; } unsigned long long PC2() { char i; unsigned long long tmp = (1LL<<47), res = 0LL; static char perm[] = {14,17,11,24, 1, 5, 3,28,15, 6,21,10, 23,19,12, 4,26, 8, 16, 7,27,20,13, 2, 41,52,31,37,47,55, 30,40,51,45,33,48, 44,49,39,56,34,53, 46,42,50,36,29,32}; for(i = 0; i < 48; i++, tmp = tmp >> 1LL) if (KEY & (1LL << (56-perm[i]))) res |= tmp; //전치 /* printf("PC2 후\n"); print_hex(res); */ return res; } unsigned long long IP(unsigned long long source) { char i; unsigned long long tmp = (1LL<<63), res = 0LL; static char perm[] = {58, 50, 42, 34, 26 ,18 ,10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7}; for(i = 0; i < 64; i++, tmp = tmp >> 1LL) if (source & (1LL << (64-perm[i]))) res |= tmp; //전 치 return res; } unsigned long long FP(unsigned long long source) { char i; unsigned long long tmp = (1LL<<63), res = 0LL; static char perm[] = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25}; for(i = 0; i < 64; i++, tmp = tmp >> 1LL) if (source & (1LL << (64-perm[i]))) res |= tmp; //전 치 return res; } unsigned long long EX(unsigned source) { char i; unsigned long long tmp = (1LL<<47), res = 0LL; static char perm[] = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9,10,11,12,13, 12,13,14,15,16,17, 16,17,18,19,20,21, 20,21,22,23,24,25, 24,25,26,27,28,29, 28,29,30,31,32, 1}; for(i = 0; i < 48; i++, tmp = tmp >> 1LL) if (source & (1 << (32-perm[i]))) res |= tmp; return res; } unsigned P(unsigned source) { char i; unsigned tmp = (1<<31), res = 0; static char perm[] = {16, 7,20,21, 29,12,28,17, 1,15,23,26, 5,18,31,10, 2, 8,24,14, 32,27, 3, 9, 19,13,30, 6, 22,11, 4,25}; for(i = 0; i < 32; i++, tmp = tmp >> 1) if (source & (1 << (32-perm[i]))) res |= tmp; /* printf("평문 P\n"); print_binary((unsigned long long)res, 4); */ return res; } unsigned S(unsigned long long source){ //32bit out static char perm[8][64] = { { 14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7, 0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8, 4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0, 15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13 }, { 15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10, 3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5, 0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15, 13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9 }, { 10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1, 13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7, 1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12 }, { 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15, 13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9, 10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4, 3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14 }, { 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9, 14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6, 4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14, 11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3 }, { 12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11, 10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8, 9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6, 4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13 }, { 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1, 13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6, 1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2, 6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12 }, { 13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7, 1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2, 7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8, 2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11 } }; int i; unsigned int z=0; //저장 unsigned res=0; /* printf("평문 S- source \n"); print_binary(source, 8); */ for(i = 0, res = 0; i < 8; i++) { z = ((source >> (((7-i)* 6))) & 0x3F); (res |= (perm[i][((z&0x20)|((z<<4)&0x10)|(z>>1)&0x0F)])); (i!=7)? res <<=4 : 0; } /* printf("평문 S\n"); print_binary((unsigned long long)res, 4); */ return res; } unsigned rotation(unsigned source, char c, char f) { static char rotation_sheet[] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; c = rotation_sheet[c]; if (f) while(c-- > 0) source = (source >> 1) | ((source & 1) << 27); else while(c-- > 0) source = ((source << 1) & 0x0FFFFFFF) | (source >> 27); // 0, 암호화 return source; } unsigned long long EN(unsigned long long source) { int i = -1; unsigned Ln, L, R; source = IP(source); /* printf("평문 IP \n"); print_binary(&source, 8); */ L = (unsigned)((source) >> 32); R = ((unsigned)source); /* printf("평문 L\n"); print_binary((unsigned long long)L);//4 printf("평문 R \n"); print_binary((unsigned long long)R);//4 unsigned long long tmp= EX(L); printf("L EX \n"); print_binary((unsigned long long*)&tmp, 6); */ C = (KEY>>28); D = (KEY&0x0FFFFFFF); /*라운드 함수 실행*/ while(++i < 16) { Ln = R; C = rotation(C, i, 0); D = rotation(D, i, 0); KEY = ((unsigned long long)C <<28| D); /* printf("KEY C \n"); print_binary((unsigned long long*)&C, 4); printf("KEY D \n"); print_binary((unsigned long long*)&D, 4); printf("KEY K \n"); print_binary(&K, 8); unsigned long long PC= PC2(); printf("KEY PC2 \n"); puts_hex(&PC); print_binary(&PC, 8); */ R = (L^P(S(EX(R)^PC2()))); L = Ln; /* unsigned long long tmp = (((unsigned long long)L << 32) | R); printf("[L + R] "); print_binary(&tmp, 8); /*printf("[L] "); print_binary((unsigned long long *)&L, 4); /* unsigned long long tmp = FP(((unsigned long long)R<< 32) | L); printf("[FP] "); print_binary(&tmp, 8); unsigned long long tmp = (((unsigned long long)L << 32) | R); printf("[L + R] "); print_hex(tmp); print_binary(tmp);*/ } return FP(((unsigned long long)R<< 32) | L); } unsigned long long DE(unsigned long long source) { char i = 16; unsigned Ln, L, R; source = IP(source); L = (unsigned)((source) >> 32); R = ((unsigned)source); C = (KEY>>28); D = (KEY&0x0FFFFFFF); while(--i >= 0) { Ln = R; R = L^P(S(EX(R)^PC2())); L = Ln; /* printf("KEY C \n"); print_binary((unsigned long long*)&C, 4); printf("KEY D \n"); print_binary((unsigned long long*)&D, 4); printf("KEY K \n"); print_binary(&K, 8); */ C = rotation(C, i, 1); D = rotation(D, i, 1); KEY = ((unsigned long long)C <<28| D); //printf("%d \n",16-i); /* printf("rotation 후\n"); print_hex(KEY); */} return FP(((unsigned long long)R << 32) | L); } void encryption(unsigned long long src, unsigned long long*encrypted_str, unsigned long long key) { KEY = PC1(key); /* printf("KEY PC1 \n"); print_binary(KEY,8); */ *(encrypted_str) = EN(src); return; } void decryption(unsigned long long src, unsigned long long*decrypted_str, unsigned long long key) { KEY = PC1(key); /* printf("PC1 후\n"); print_hex(KEY); */ *(decrypted_str) = DE(src); return; } int main(){ unsigned long long decrypted_source_str= 0x9d96ce27e370975c; unsigned long long source_key= 0LL; unsigned long long encrypted_str, decrypted_str= 0LL; unsigned int i,j,d=0; printf("[암호] : "); print_hex(decrypted_source_str); print_binary(decrypted_source_str); /* printf("[키] : "); print_hex(source_key); print_binary(source_key);*/ for(i=10000; i>1000; i-=2){ source_key =i; decryption(decrypted_source_str, &decrypted_str, source_key); //printf("[복호] : "); //print_hex(decrypted_str); //print_binary(decrypted_str); // printf("%d. ",i); if( (((i&0xFF000000)>=48)|((i&0xFF000000)<=57)) & (((i&0xFF000000)>=65)|((i&0xFF000000)<=90)) & (((i&0xFF000000)>=97)|(i&0xFF000000)<=122)& (((i&0x00FF0000)>=48)|((i&0x00FF0000)<=57)) & (((i&0x00FF0000)>=65)|((i&0x00FF0000)<=90)) & (((i&0x00FF0000)>=97)|(i&0x00FF0000)<=122)& (((i&0x0000FF00)>=48)|((i&0x0000FF00)<=57)) & (((i&0x0000FF00)>=65)|((i&0x0000FF00)<=90)) & (((i&0x0000FF00)>=97)|(i&0x0000FF00)<=122)& (((i&0x000000FF)>=48)|((i&0x000000FF)<=57)) & (((i&0x000000FF)>=65)|((i&0x000000FF)<=90)) & (((i&0x000000FF)>=97)|(i&0x000000FF)<=122)) { printf("%d ",i); print_char(decrypted_str); }} encryption(decrypted_str, &encrypted_str, source_key); encryption(decrypted_str, &encrypted_str, source_key); printf("[다시 암호] : "); print_hex(encrypted_str); print_binary(encrypted_str); system("pause"); return 0; } /*unsigned long long decrypted_source_str= 0xda02ce3a89ecac3b; unsigned long long source_key= 0x0f1571c947d9e859; unsigned long long encrypted_str, decrypted_str= 0LL;*/ /*unsigned long long decrypted_source_str= 0x9d96ce27e370975c; unsigned long long source_key= 0LL; unsigned long long encrypted_str, decrypted_str= 0LL; unsigned int i=0; */
[ "joseoyeon60@gmail.com" ]
joseoyeon60@gmail.com
a481020995d835dff9b4d9e8bc0d37537958aed2
c04e49371d98c136fb484c541a0fb479c96001ff
/deprecated/include/Graphics/Native/WindowModes.h
fb4cd0481f48eef7970bddaf93daf916e05872b1
[ "MIT" ]
permissive
Arzana/Plutonium
0af59b6ffee010eed7c6c8f6182c87480ef45dc3
5a17c93e5072ac291b96347a4df196e1609fabe2
refs/heads/master
2021-05-09T02:20:42.528906
2020-10-31T20:36:57
2020-10-31T20:36:57
119,201,274
4
0
null
null
null
null
UTF-8
C++
false
false
341
h
#pragma once namespace Plutonium { /* Defines the modes of a window. */ enum class WindowMode { /* A sizeable window with a header. */ Windowed, /* A sizeable window without a header. */ Borderless, /* A sizeable window that takes up the whole display. */ BorderlessFullscreen, /* A fullscreen window. */ Fullscreen }; }
[ "largewowfan@gmail.com" ]
largewowfan@gmail.com
f68f908f6da483c9d3667b60cb52d5f0aa68a59f
51e8260df21001498150dc4dcadd36a364300e24
/src/test/resources/results/armadillo/detectionObjectDetector2/l1/detection_objectDetector2_spectralClusterer_1_.h
0c91a3a67b04422ff37ecfeb1fa1410aab053f71
[]
no_license
Qwertzimus/EMAM2Cpp
f733a19eaf8619df921aaff9ee401d1c4e8314e8
6f5a7ffa880fa223fd5e3d828239b7d3bbd2efa1
refs/heads/master
2020-03-20T22:34:50.299533
2018-05-22T16:51:38
2018-05-22T16:51:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,669
h
#ifndef DETECTION_OBJECTDETECTOR2_SPECTRALCLUSTERER_1_ #define DETECTION_OBJECTDETECTOR2_SPECTRALCLUSTERER_1_ #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #include "armadillo.h" #include "detection_objectDetector2_spectralClusterer_1__similarity.h" #include "detection_objectDetector2_spectralClusterer_1__normalizedLaplacian.h" #include "detection_objectDetector2_spectralClusterer_1__eigenSolver.h" #include "detection_objectDetector2_spectralClusterer_1__kMeansClustering.h" using namespace arma; class detection_objectDetector2_spectralClusterer_1_{ const int n = 50; const int elements = 2500; const int k = 4; const int maximumClusters = 1; public: mat red; mat green; mat blue; mat clusters; detection_objectDetector2_spectralClusterer_1__similarity similarity; detection_objectDetector2_spectralClusterer_1__normalizedLaplacian normalizedLaplacian; detection_objectDetector2_spectralClusterer_1__eigenSolver eigenSolver; detection_objectDetector2_spectralClusterer_1__kMeansClustering kMeansClustering; void init() { red=mat(n,n); green=mat(n,n); blue=mat(n,n); clusters=mat(elements,maximumClusters); similarity.init(); normalizedLaplacian.init(); eigenSolver.init(); kMeansClustering.init(); } void execute() { similarity.red = red; similarity.green = green; similarity.blue = blue; similarity.execute(); normalizedLaplacian.degree = similarity.degree; normalizedLaplacian.similarity = similarity.similarity; normalizedLaplacian.execute(); eigenSolver.matrix = normalizedLaplacian.nLaplacian; eigenSolver.execute(); kMeansClustering.vectors = eigenSolver.eigenvectors; kMeansClustering.execute(); clusters = kMeansClustering.clusters; } }; #endif
[ "sascha.schneiders@rwth-aachen.de" ]
sascha.schneiders@rwth-aachen.de
668d5caa75249dc3a94d500bc45f1ccd01617d13
1739bf1e1512c11f3d096beaed009677d349575d
/Sources/Engine/TRtxPipeline.h
21a89a6c4895ed211a3fd172d9a48cfe7aa9250b
[]
no_license
TiraX/tix2
60eebd345097e80d59c8a1d2887a2413ddc1fa11
ebdab17e400764abfb9ea7a9d4db3fbdada8f293
refs/heads/master
2023-02-18T05:28:38.956220
2023-01-28T14:41:10
2023-01-28T14:41:10
129,262,369
10
2
null
2021-03-30T01:32:13
2018-04-12T14:16:02
C++
UTF-8
C++
false
false
1,334
h
/* TiX Engine v2.0 Copyright (C) 2018~2021 By ZhaoShuai tirax.cn@gmail.com */ #pragma once namespace tix { enum E_HITGROUP { HITGROUP_ANY_HIT, HITGROUP_CLOSEST_HIT, HITGROUP_INTERSECTION, HITGROUP_NUM }; struct TRtxPipelineDesc { uint32 Flags; TShaderPtr ShaderLib; TVector<TString> ExportNames; TString HitGroupName; TString HitGroup[HITGROUP_NUM]; int32 MaxAttributeSizeInBytes; int32 MaxPayloadSizeInBytes; int32 MaxTraceRecursionDepth; TRtxPipelineDesc() : Flags(0) , MaxAttributeSizeInBytes(0) , MaxPayloadSizeInBytes(0) , MaxTraceRecursionDepth(0) { } }; class TRtxPipeline : public TResource { public: TRtxPipeline(); virtual ~TRtxPipeline(); void SetShaderLib(TShaderPtr InShaderLib); void AddExportName(const TString& InName); void SetHitGroupName(const TString& InName); void SetHitGroup(E_HITGROUP HitGroup, const TString& InName); void SetMaxAttributeSizeInBytes(int32 InSize); void SetMaxPayloadSizeInBytes(int32 InSize); void SetMaxTraceRecursionDepth(int32 InDepth); virtual void InitRenderThreadResource() override; virtual void DestroyRenderThreadResource() override; const TRtxPipelineDesc& GetDesc() const { return Desc; } FRtxPipelinePtr PipelineResource; protected: protected: TRtxPipelineDesc Desc; }; }
[ "zhaoshuai2@kingsoft.com" ]
zhaoshuai2@kingsoft.com
ccc5ff6e2cea566c23d70eab3fa42f9354c44dfe
e39b3fad5b4ee23f926509a7e5fc50e84d9ebdc8
/AtCoder/Companies/AISing-Programming-Contest/2019/c.cpp
d5bca632ec2a2584cf7aa0a701cdae7c3c0af3c3
[]
no_license
izumo27/competitive-programming
f755690399c5ad1c58d3db854a0fa21eb8e5f775
e721fc5ede036ec5456da9a394648233b7bfd0b7
refs/heads/master
2021-06-03T05:59:58.460986
2021-05-08T14:39:58
2021-05-08T14:39:58
123,675,037
0
0
null
null
null
null
UTF-8
C++
false
false
1,858
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef vector<ll> vl; typedef pair<int, int> pii; typedef pair<ll, ll> pll; #define REP(i, n) for(int i=0; i<(n); ++i) #define FOR(i, a, b) for(int i=(a); i<(b); ++i) #define FORR(i, a, b) for(int i=(b)-1; i>=(a); --i) #define DEBUG(x) cout<<#x<<": "<<x<<'\n' #define DEBUG_VEC(v) cout<<#v<<":";REP(i, v.size())cout<<' '<<v[i];cout<<'\n' #define ALL(a) (a).begin(), (a).end() #define CHMIN(a, b) a=min((a), (b)) #define CHMAX(a, b) a=max((a), (b)) const ll MOD=1000000007ll; // const ll MOD=998244353ll; #define FIX(a) ((a)%MOD+MOD)%MOD const double EPS=1e-11; #define EQ0(x) (abs((x))<EPS) #define EQ(a, b) (abs((a)-(b))<EPS) bool used[404][404]; int dx[4]={-1, 0, 1, 0}, dy[4]={0, -1, 0, 1}; int h, w; string s[404]; pll bfs(int sx, int sy){ queue<pair<pii, bool>> q; q.push(make_pair(pii(sx, sy), true)); ll cnt1=0, cnt2=0; while(q.size()){ pair<pii, bool> p=q.front(); q.pop(); REP(i, 4){ int nx=p.first.first+dx[i]; int ny=p.first.second+dy[i]; if(nx>=0 && nx<h && ny>=0 && ny<w && !used[nx][ny]){ if(p.second){ if(s[nx][ny]=='.'){ ++cnt2; q.push(make_pair(pii(nx, ny), false)); used[nx][ny]=true; } } else{ if(s[nx][ny]=='#'){ ++cnt1; q.push(make_pair(pii(nx, ny), true)); used[nx][ny]=true; } } } } } return pll(cnt1, cnt2); } int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>h>>w; REP(i, h){ cin>>s[i]; } ll ans=0; REP(i, h){ REP(j, w){ if(s[i][j]!='#'){ continue; } pll cnt=bfs(i, j); ans+=cnt.first*cnt.second; } } cout<<ans<<'\n'; return 0; }
[ "22386882+izumo27@users.noreply.github.com" ]
22386882+izumo27@users.noreply.github.com
53ae6d240054548fe6180e5891a066453db5d113
38b9daafe39f937b39eefc30501939fd47f7e668
/tutorials/2WayCouplingOceanWave3D/EvalResults180628-Eta-W/95.6/uniform/time
91a0a29ea7edd45b72de7dbef11c1668bcc786c5
[]
no_license
rubynuaa/2-way-coupling
3a292840d9f56255f38c5e31c6b30fcb52d9e1cf
a820b57dd2cac1170b937f8411bc861392d8fbaa
refs/heads/master
2020-04-08T18:49:53.047796
2018-08-29T14:22:18
2018-08-29T14:22:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,006
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 3.0.1 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "95.6/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 95.6000000000000085; name "95.6"; index 12870; deltaT 0.00714286; deltaT0 0.00714286; // ************************************************************************* //
[ "abenaz15@etudiant.mines-nantes.fr" ]
abenaz15@etudiant.mines-nantes.fr
b4e505e38b7e7375a9a3cc64761eb9b0d791b862
64684646c96123397d60052d7d04bb370a182b42
/game/dragon3d-core/test/com/dragon3d/util/assets/AssetsManagerTest.cc
05141b1ec3ed4998690f9e02ad7bf849b8da773a
[]
no_license
yubing744/dragon
e6ca32726df8fe8e9e1d0586058b8628245efb55
eca9b4b6823c98ddc56ccedde486099653b13920
refs/heads/master
2020-05-22T09:11:15.052073
2017-01-02T01:30:53
2017-01-02T01:30:53
33,351,592
4
1
null
null
null
null
UTF-8
C++
false
false
1,499
cc
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /********************************************************************** * Author: Owen Wu/wcw/yubing * Email: yubing744@163.com * Created: 2014/04/27 **********************************************************************/ #include <gtest/gtest.h> #include <dragon/lang/System.h> #include <dragon/io/File.h> #include <com/dragon3d/util/assets/AssetsManager.h> Import dragon::io; Import dragon::lang; Import com::dragon3d::util::assets; /* TEST(Com_Dragon3d_Util_Assets_AssetsManagerTest, getResources) { const String* base = System::getProperty("HOME"); String* filePath = new String(L"/dragon_test/model_load_test/"); File* file = new File(base, filePath); //List<Resource>* reses = AssetsManager::getInstance()->getResources("/dragon_test/model_load_test/", true); //ASSERT_TRUE(reses != null); SafeRelease(file); SafeRelease(filePath); } */
[ "yubing744@163.com" ]
yubing744@163.com
a9482c33fb8e07452e0a4797cbbf272d051e185c
a4c8d163888799dbb6efe236b4d3886114d4769b
/cie_sign_sdk/include/UUCTextFileReader.h
012aedf29c9f61c7bb19149ae5d74c210a9a811a
[ "BSD-3-Clause" ]
permissive
bitpdg/cie-middleware-linux
8b5ab036ebbcef29fb18c17c7d1af7421725be3d
d3a794802240a2cda55ecd1d02ff79195689e5ac
refs/heads/master
2023-04-24T02:17:41.952027
2021-05-19T12:49:24
2021-05-19T12:49:24
267,796,262
0
0
BSD-3-Clause
2020-05-29T07:38:35
2020-05-29T07:38:35
null
UTF-8
C++
false
false
753
h
// UUCTextFile.h: interface for the UUCTextFile class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_UUCTEXTFILE_H__CD3660A5_B4C5_4CD4_99AC_69AC96D1460F__INCLUDED_) #define AFX_UUCTEXTFILE_H__CD3660A5_B4C5_4CD4_99AC_69AC96D1460F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <stdio.h> #include "ASN1/UUCByteArray.h" class UUCTextFileReader { public: UUCTextFileReader(const char* szFilePath); virtual ~UUCTextFileReader(); long readLine(char* szLine, unsigned long nLen);// throw (long); long readLine(UUCByteArray& line); private: FILE* m_pf; }; #endif // !defined(AFX_UUCTEXTFILE_H__CD3660A5_B4C5_4CD4_99AC_69AC96D1460F__INCLUDED_)
[ "pdg@bit4id.com" ]
pdg@bit4id.com
6b490e5e6772ed11bb92c37a88cc84d443046655
d9ee3d21555a856326899f3470140ab1694e49a3
/HggRazor/CommonTools/include/TableMakerAux.hh
7525e8517db0d01aad5f933bbbce43204ed8f42d
[]
no_license
cmorgoth/RazorFramework
47f76e17a00a8aee01e416649db3983a25101dee
ca180336bf5498c8731b360bc70fd5c980b41cea
refs/heads/master
2020-04-06T06:59:03.881664
2016-06-28T21:26:18
2016-06-28T21:26:18
35,075,908
1
1
null
2016-05-27T00:43:15
2015-05-05T03:34:23
C++
UTF-8
C++
false
false
51
hh
#ifndef TableMakerAux #define TableMakerAux #endif
[ "cristian.morgoth@gmail.com" ]
cristian.morgoth@gmail.com
ce4a0f0ea26bc34057c2fb79a106fec4b24cc951
791c9de4ec8b5778bb6327da5fe967f5c4e1ed95
/src/PhoneBook.hpp
03c96acd59537574fc9fccac6ee266ffa03f6778
[]
no_license
sv99/sms_gate
528cf0b567046af4a1642ed6400e09bf3fa02fd3
f277aba9739e5952ffd4de1702a90c16a41d89f6
refs/heads/master
2020-04-14T22:41:53.148696
2018-04-05T14:41:59
2018-04-05T14:41:59
68,000,957
3
0
null
null
null
null
UTF-8
C++
false
false
493
hpp
// // Created by Volkov on 09.09.16. // #ifndef SMS_GATE_PHONEBOOK_H #define SMS_GATE_PHONEBOOK_H #include <string> #include <vector> class Number { public: int m_id{0}; std::string m_number{""}; std::string to_string(); }; class Record { public: int m_id{0}; std::string m_FirstName{}; std::string m_SecondName{}; std::vector<Number> numbers{}; std::string to_string(); }; class PhoneBook { public: std::vector<Record> records{}; }; #endif //SMS_GATE_PHONEBOOK_H
[ "sv99@inbox.ru" ]
sv99@inbox.ru
4a51f1d22f9203a68c68126c2f44baf966c74859
da3c59e9e54b5974648828ec76f0333728fa4f0c
/email/pop3andsmtpmtm/clientmtms/inc/cimfinder.h
d3ceb1596c81fa7646cc4ad91cf8447515b1b67a
[]
no_license
finding-out/oss.FCL.sf.app.messaging
552a95b08cbff735d7f347a1e6af69fc427f91e8
7ecf4269c53f5b2c6a47f3596e77e2bb75c1700c
refs/heads/master
2022-01-29T12:14:56.118254
2010-11-03T20:32:03
2010-11-03T20:32:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,710
h
// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // cimfinder.h // /** * @file * @internalComponent * @released */ #if !defined (__CIMFINDER_H__) #define __CIMFINDER_H__ class CImFinder : public CMsgActive /** @internalComponent @released */ { public: IMPORT_C void FindFirstL(TMsvId aRootEntry, TRequestStatus &aStatus); IMPORT_C ~CImFinder(); IMPORT_C virtual void FindNextL(TRequestStatus &aStatus); void FindFirstL(const CMsvEntrySelection& aInitialSelection, TRequestStatus &aStatus); class CImEntryStack : public CBase { public: static CImEntryStack* NewL(); ~CImEntryStack(); inline void PushL(TMsvId aId); inline TMsvId PopL(); inline TBool Empty() const; inline void Reset(); private: void ConstructL(); CMsvEntrySelection* iFolders; }; protected: void ConstructL(); CImFinder(CMsvEntry& aEntry); private: void DoRunL(); virtual void AddChildEntriesL() = 0; virtual TBool IsRequiredEntryType(TUid aEntryType) const = 0; protected: CImEntryStack* iEntryStack; CMsvEntry& iCurrentEntry; private: enum TImmfState { EImmfEntryFound, EImmfFindingEntry, EImmfNothingFound }; TImmfState iState; }; class CImMessageFinder : public CImFinder /** @internalComponent @released */ { public: IMPORT_C static CImMessageFinder* NewL(CMsvEntry& aEntry); IMPORT_C static CImMessageFinder* NewLC(CMsvEntry& aEntry); protected: virtual void AddChildEntriesL(); virtual TBool IsRequiredEntryType(TUid aEntryType) const; CImMessageFinder(CMsvEntry& aEntry); }; class CImEntryFinder : public CImFinder /** @internalComponent @released */ { public: IMPORT_C static CImEntryFinder* NewL(CMsvEntry& aEntry); IMPORT_C static CImEntryFinder* NewLC(CMsvEntry& aEntry); protected: virtual void AddChildEntriesL(); virtual TBool IsRequiredEntryType(TUid aEntryType) const; CImEntryFinder(CMsvEntry& aEntry); }; class CImMessageCounter : public CImFinder /** @internalComponent @released */ { public: IMPORT_C static CImMessageCounter* NewL(CMsvEntry& aEntry); IMPORT_C static CImMessageCounter* NewLC(CMsvEntry& aEntry); IMPORT_C TInt Count(); protected: virtual void AddChildEntriesL(); virtual TBool IsRequiredEntryType(TUid aEntryType) const; CImMessageCounter(CMsvEntry& aEntry); private: TInt iCount; }; #endif //__CIMFINDER_H__
[ "none@none" ]
none@none
0b1f7d4a6c6c51dfcc15480bc8f2caa8470c8302
e4ec5b6cf3cfe2568ef0b5654c019e398b4ecc67
/aws-sdk-cpp/1.2.10/include/aws/budgets/model/DescribeBudgetRequest.h
13843bd583a4a95a49d3811afc8fc1668e17629b
[ "MIT", "Apache-2.0", "JSON" ]
permissive
EnjoyLifeFund/macHighSierra-cellars
59051e496ed0e68d14e0d5d91367a2c92c95e1fb
49a477d42f081e52f4c5bdd39535156a2df52d09
refs/heads/master
2022-12-25T19:28:29.992466
2017-10-10T13:00:08
2017-10-10T13:00:08
96,081,471
3
1
null
2022-12-17T02:26:21
2017-07-03T07:17:34
null
UTF-8
C++
false
false
3,482
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/budgets/Budgets_EXPORTS.h> #include <aws/budgets/BudgetsRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Budgets { namespace Model { /** * Request of DescribeBudget<p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/budgets-2016-10-20/DescribeBudgetRequest">AWS * API Reference</a></p> */ class AWS_BUDGETS_API DescribeBudgetRequest : public BudgetsRequest { public: DescribeBudgetRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DescribeBudget"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; inline const Aws::String& GetAccountId() const{ return m_accountId; } inline void SetAccountId(const Aws::String& value) { m_accountIdHasBeenSet = true; m_accountId = value; } inline void SetAccountId(Aws::String&& value) { m_accountIdHasBeenSet = true; m_accountId = std::move(value); } inline void SetAccountId(const char* value) { m_accountIdHasBeenSet = true; m_accountId.assign(value); } inline DescribeBudgetRequest& WithAccountId(const Aws::String& value) { SetAccountId(value); return *this;} inline DescribeBudgetRequest& WithAccountId(Aws::String&& value) { SetAccountId(std::move(value)); return *this;} inline DescribeBudgetRequest& WithAccountId(const char* value) { SetAccountId(value); return *this;} inline const Aws::String& GetBudgetName() const{ return m_budgetName; } inline void SetBudgetName(const Aws::String& value) { m_budgetNameHasBeenSet = true; m_budgetName = value; } inline void SetBudgetName(Aws::String&& value) { m_budgetNameHasBeenSet = true; m_budgetName = std::move(value); } inline void SetBudgetName(const char* value) { m_budgetNameHasBeenSet = true; m_budgetName.assign(value); } inline DescribeBudgetRequest& WithBudgetName(const Aws::String& value) { SetBudgetName(value); return *this;} inline DescribeBudgetRequest& WithBudgetName(Aws::String&& value) { SetBudgetName(std::move(value)); return *this;} inline DescribeBudgetRequest& WithBudgetName(const char* value) { SetBudgetName(value); return *this;} private: Aws::String m_accountId; bool m_accountIdHasBeenSet; Aws::String m_budgetName; bool m_budgetNameHasBeenSet; }; } // namespace Model } // namespace Budgets } // namespace Aws
[ "Raliclo@gmail.com" ]
Raliclo@gmail.com
d051b5a7739d0e15dc035b6a255072470e5a548e
3a64d611b73e036ad01d0a84986a2ad56f4505d5
/ash/system/holding_space/pinned_files_container.cc
37f8e6b07948625760b61c65693117d4a0988f02
[ "BSD-3-Clause" ]
permissive
ISSuh/chromium
d32d1fccc03d7a78cd2fbebbba6685a3e16274a2
e045f43a583f484cc4a9dfcbae3a639bb531cff1
refs/heads/master
2023-03-17T04:03:11.111290
2020-09-26T11:39:44
2020-09-26T11:39:44
298,805,518
0
0
BSD-3-Clause
2020-09-26T12:04:46
2020-09-26T12:04:46
null
UTF-8
C++
false
false
2,836
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 "ash/system/holding_space/pinned_files_container.h" #include "ash/public/cpp/holding_space/holding_space_constants.h" #include "ash/public/cpp/holding_space/holding_space_controller.h" #include "ash/public/cpp/holding_space/holding_space_item.h" #include "ash/public/cpp/holding_space/holding_space_model.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/holding_space/holding_space_item_chip_view.h" #include "ash/system/holding_space/holding_space_item_chips_container.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/tray/tray_popup_item_style.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/border.h" #include "ui/views/controls/label.h" #include "ui/views/controls/separator.h" #include "ui/views/layout/box_layout.h" namespace ash { PinnedFilesContainer::PinnedFilesContainer( HoldingSpaceItemViewDelegate* delegate) : delegate_(delegate) { SetID(kHoldingSpacePinnedFilesContainerId); SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, kHoldingSpaceContainerPadding, kHoldingSpaceContainerChildSpacing)); auto* title_label = AddChildView(std::make_unique<views::Label>( l10n_util::GetStringUTF16(IDS_ASH_HOLDING_SPACE_PINNED_TITLE))); TrayPopupItemStyle style(TrayPopupItemStyle::FontStyle::HOLDING_SPACE_TITLE, true /* use_unified_theme */); style.SetupLabel(title_label); title_label->SetPaintToLayer(); title_label->layer()->SetFillsBoundsOpaquely(false); item_chips_container_ = AddChildView(std::make_unique<HoldingSpaceItemChipsContainer>()); if (HoldingSpaceController::Get()->model()) OnHoldingSpaceModelAttached(HoldingSpaceController::Get()->model()); } PinnedFilesContainer::~PinnedFilesContainer() = default; void PinnedFilesContainer::AddHoldingSpaceItemView( const HoldingSpaceItem* item) { DCHECK(!base::Contains(views_by_item_id_, item->id())); if (item->type() == HoldingSpaceItem::Type::kPinnedFile) { views_by_item_id_[item->id()] = item_chips_container_->AddChildViewAt( std::make_unique<HoldingSpaceItemChipView>(delegate_, item), /*index=*/0); } } void PinnedFilesContainer::RemoveAllHoldingSpaceItemViews() { views_by_item_id_.clear(); item_chips_container_->RemoveAllChildViews(true); } void PinnedFilesContainer::RemoveHoldingSpaceItemView( const HoldingSpaceItem* item) { auto it = views_by_item_id_.find(item->id()); if (it == views_by_item_id_.end()) return; item_chips_container_->RemoveChildViewT(it->second); views_by_item_id_.erase(it->first); } } // namespace ash
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
0d0eb7de6a48d48b1894abb0e16055230a1bb461
260a59fb9e70d043b4208abd871bf559b4cfa874
/src/frame.cpp
828df7e04482adf8ff8fbdbb8adf7f316d52a2b2
[]
no_license
softwareCxw/signature2
0cf15c84e272637904c5145a4e01e337ba250cd6
8cf33164bc121719bf8f6de7eb2b43aba367e413
refs/heads/master
2020-12-31T04:29:15.346025
2015-11-25T08:58:40
2015-11-25T08:58:40
46,849,268
0
0
null
null
null
null
UTF-8
C++
false
false
1,875
cpp
#include "frame.h" void frame::setup() { i_choose = CHOOSE; _fbo.allocate(1920, 1080); _chooseBack.setup(); _signature.setup(); } void frame::update() { switch(i_choose) { case CHOOSE : _chooseBack.update(); break; case SIGNATURE : _signature.update(); break; default: break; } } void frame::draw() { _fbo.begin(); ofClear(0); switch(i_choose) { case CHOOSE : _chooseBack.draw(); break; case SIGNATURE : _signature.draw(); break; default: break; } _fbo.end(); _fbo.draw(0, 0, ofGetWidth(), ofGetHeight()); } void frame::mouseMoved( int x, int y ) { } void frame::mouseDragged( int x, int y, int button ) { x = _fbo.getWidth() / ofGetWidth() * x; y = _fbo.getHeight() / ofGetHeight() *y; switch(i_choose) { case CHOOSE : _chooseBack.mouseTrigger(MOUSE_DRAGGED, x, y, button); break; case SIGNATURE : _signature.mouseTrigger(MOUSE_DRAGGED, x, y, button); break; default: break; } } void frame::mousePressed( int x, int y, int button ) { x = _fbo.getWidth() / ofGetWidth() * x; y = _fbo.getHeight() / ofGetHeight() *y; switch(i_choose) { case CHOOSE : _chooseBack.mouseTrigger(MOUSE_PRESSED, x, y, button); break; case SIGNATURE : _signature.mouseTrigger(MOUSE_PRESSED, x, y, button); break; default: break; } } void frame::mouseReleased( int x, int y, int button ) { x = _fbo.getWidth() / ofGetWidth() * x; y = _fbo.getHeight() / ofGetHeight() *y; switch(i_choose) { case CHOOSE : _chooseBack.mouseTrigger(MOUSE_RELEASED, x, y, button); if(_chooseBack.is_next()) { i_choose = SIGNATURE; _signature.setSignatureImg(_chooseBack.getSignatureImg()); _chooseBack.revect(); } break; case SIGNATURE : _signature.mouseTrigger(MOUSE_RELEASED, x, y, button); if(_signature.is_next()) { i_choose = CHOOSE; _signature.revect(); } break; default: break; } }
[ "825873709@qq.com" ]
825873709@qq.com
73eb810dba6fa9feb96bd2df35538fb73ab967f7
81e4a14225fdef668aee4a4eb3c0e4bf4f992196
/src/Timer.cpp
1e477af20d33e6baa1135b39d39d52d6bd4d72fa
[]
no_license
LPPOINT/Checkers
dffdad148024e60ff0f03ea2bcfce700e9f8712a
12d5b06d0ab70327c65186cf97d4e6fa798a91fb
refs/heads/master
2021-01-10T19:22:24.115634
2012-08-11T12:37:08
2012-08-11T12:37:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#include "Timer.h" void Timer::Update(float msec) { if((_msec+=msec)>1000) { _sec++; _msec-= 1000; } }
[ "ostrov1762@mail.ru" ]
ostrov1762@mail.ru
e03e4b1ceba6a9616803784840edefa1b0db8ac6
825e64b1cb17aac2a4d5c396d7bbeaca91aaaa10
/src/transport/Messages/Packer.cpp
4626f52164dff26b9fdb253afca694a8263c0e28
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cpshereda/hxhim
7cf7643228f44a7ce336bedf05762ad95d5b72bd
1ef69e33d320e629779df27fb36de102f587c829
refs/heads/master
2023-01-29T12:53:21.008388
2020-12-08T19:50:24
2020-12-08T19:50:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,023
cpp
#include "datastore/constants.hpp" #include "transport/Messages/Packer.hpp" #include "utils/little_endian.hpp" #include "utils/memory.hpp" namespace Transport { static char *pack_addr(char *&dst, void *ptr) { // // skip check // if (!dst) { // return nullptr; // } little_endian::encode(dst, ptr); dst += sizeof(ptr); return dst; } int Packer::pack(const Request::Request *req, void **buf, std::size_t *bufsize) { int ret = TRANSPORT_ERROR; if (!req) { return ret; } // mlog(THALLIUM_DBG, "Packing Request type %d", req->op); switch (req->op) { case hxhim_op_t::HXHIM_PUT: ret = pack(static_cast<const Request::BPut *>(req), buf, bufsize); break; case hxhim_op_t::HXHIM_GET: ret = pack(static_cast<const Request::BGet *>(req), buf, bufsize); break; case hxhim_op_t::HXHIM_GETOP: ret = pack(static_cast<const Request::BGetOp *>(req), buf, bufsize); break; case hxhim_op_t::HXHIM_DELETE: ret = pack(static_cast<const Request::BDelete *>(req), buf, bufsize); break; case hxhim_op_t::HXHIM_HISTOGRAM: ret = pack(static_cast<const Request::BHistogram *>(req), buf, bufsize); break; default: break; } // mlog(THALLIUM_DBG, "Done Packing Request type %d", req->op); return ret; } int Packer::pack(const Request::BPut *bpm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Request::Request *>(bpm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bpm->count; i++) { // subject + len bpm->subjects[i].pack(curr, true); // subject addr pack_addr(curr, bpm->subjects[i].data()); // predicate + len bpm->predicates[i].pack(curr, true); // predicate addr pack_addr(curr, bpm->predicates[i].data()); // object + len bpm->objects[i].pack(curr, true); } return TRANSPORT_SUCCESS; } int Packer::pack(const Request::BGet *bgm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Request::Request *>(bgm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bgm->count; i++) { // subject bgm->subjects[i].pack(curr, true); // subject addr pack_addr(curr, bgm->subjects[i].data()); // predicate bgm->predicates[i].pack(curr, true); // predicate addr pack_addr(curr, bgm->predicates[i].data()); // object type little_endian::encode(curr, bgm->object_types[i], sizeof(bgm->object_types[i])); curr += sizeof(bgm->object_types[i]); } return TRANSPORT_SUCCESS; } int Packer::pack(const Request::BGetOp *bgm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Request::Request *>(bgm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bgm->count; i++) { // operation to run little_endian::encode(curr, bgm->ops[i], sizeof(bgm->ops[i])); curr += sizeof(bgm->ops[i]); if ((bgm->ops[i] != hxhim_getop_t::HXHIM_GETOP_FIRST) && (bgm->ops[i] != hxhim_getop_t::HXHIM_GETOP_LAST)) { // subject bgm->subjects[i].pack(curr, true); // predicate bgm->predicates[i].pack(curr, true); } // object type little_endian::encode(curr, bgm->object_types[i], sizeof(bgm->object_types[i])); curr += sizeof(bgm->object_types[i]); // number of records to get back little_endian::encode(curr, bgm->num_recs[i], sizeof(bgm->num_recs[i])); curr += sizeof(bgm->num_recs[i]); } return TRANSPORT_SUCCESS; } int Packer::pack(const Request::BDelete *bdm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Request::Request *>(bdm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bdm->count; i++) { // subject bdm->subjects[i].pack(curr, true); // subject addr pack_addr(curr, bdm->subjects[i].data()); // predicate bdm->predicates[i].pack(curr, true); // predicate addr pack_addr(curr, bdm->predicates[i].data()); } return TRANSPORT_SUCCESS; } int Packer::pack(const Request::BHistogram *bhm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Request::Request *>(bhm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bhm->count; i++) { // histogram names bhm->names[i].pack(curr, false); } return TRANSPORT_SUCCESS; } int Packer::pack(const Response::Response *res, void **buf, std::size_t *bufsize) { int ret = TRANSPORT_ERROR; if (!res) { return ret; } // mlog(THALLIUM_DBG, "Packing Response type %d", res->op); switch (res->op) { case hxhim_op_t::HXHIM_PUT: ret = pack(static_cast<const Response::BPut *>(res), buf, bufsize); break; case hxhim_op_t::HXHIM_GET: ret = pack(static_cast<const Response::BGet *>(res), buf, bufsize); break; case hxhim_op_t::HXHIM_GETOP: ret = pack(static_cast<const Response::BGetOp *>(res), buf, bufsize); break; case hxhim_op_t::HXHIM_DELETE: ret = pack(static_cast<const Response::BDelete *>(res), buf, bufsize); break; case hxhim_op_t::HXHIM_HISTOGRAM: ret = pack(static_cast<const Response::BHistogram *>(res), buf, bufsize); break; default: break; } // mlog(THALLIUM_DBG, "Done Packing Response type %d", res->op); return ret; } int Packer::pack(const Response::BPut *bpm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Response::Response *>(bpm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bpm->count; i++) { little_endian::encode(curr, bpm->statuses[i], sizeof(bpm->statuses[i])); curr += sizeof(bpm->statuses[i]); // original subject addr + len bpm->orig.subjects[i].pack_ref(curr, true); // original predicate addr + len bpm->orig.predicates[i].pack_ref(curr, true); } return TRANSPORT_SUCCESS; } int Packer::pack(const Response::BGet *bgm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Response::Response *>(bgm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bgm->count; i++) { little_endian::encode(curr, bgm->statuses[i], sizeof(bgm->statuses[i])); curr += sizeof(bgm->statuses[i]); // original subject addr + len bgm->orig.subjects[i].pack_ref(curr, true); // original predicate addr + len bgm->orig.predicates[i].pack_ref(curr, true); // object if (bgm->statuses[i] == DATASTORE_SUCCESS) { bgm->objects[i].pack(curr, true); } } return TRANSPORT_SUCCESS; } int Packer::pack(const Response::BGetOp *bgm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Response::Response *>(bgm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bgm->count; i++) { little_endian::encode(curr, bgm->statuses[i], sizeof(bgm->statuses[i])); curr += sizeof(bgm->statuses[i]); // num_recs little_endian::encode(curr, bgm->num_recs[i], sizeof(bgm->num_recs[i])); curr += sizeof(bgm->num_recs[i]); for(std::size_t j = 0; j < bgm->num_recs[i]; j++) { // subject bgm->subjects[i][j].pack(curr, true); // predicate bgm->predicates[i][j].pack(curr, true); // object if (bgm->statuses[i] == DATASTORE_SUCCESS) { bgm->objects[i][j].pack(curr, true); } } } return TRANSPORT_SUCCESS; } int Packer::pack(const Response::BDelete *bdm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Response::Response *>(bdm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } for(std::size_t i = 0; i < bdm->count; i++) { little_endian::encode(curr, bdm->statuses[i], sizeof(bdm->statuses[i])); curr += sizeof(bdm->statuses[i]); // original subject addr + len bdm->orig.subjects[i].pack_ref(curr, true); // original predicate addr + len bdm->orig.predicates[i].pack_ref(curr, true); } return TRANSPORT_SUCCESS; } int Packer::pack(const Response::BHistogram *bhm, void **buf, std::size_t *bufsize) { char *curr = nullptr; if (pack(static_cast<const Response::Response *>(bhm), buf, bufsize, &curr) != TRANSPORT_SUCCESS) { return TRANSPORT_ERROR; } std::size_t avail = *bufsize - (curr - (char *) *buf); for(std::size_t i = 0; i < bhm->count; i++) { little_endian::encode(curr, bhm->statuses[i], sizeof(bhm->statuses[i])); curr += sizeof(bhm->statuses[i]); // histogram bhm->histograms[i]->pack(curr, avail, nullptr); } return TRANSPORT_SUCCESS; } int Packer::pack(const Message *msg, void **buf, std::size_t *bufsize, char **curr) { if (!msg || !buf || !bufsize || !curr) { return TRANSPORT_ERROR; } *bufsize = msg->size(); // only allocate space if a nullptr is provided; otherwise, assume *buf has enough space if (!*buf) { if (!(*buf = alloc(*bufsize))) { *bufsize = 0; return TRANSPORT_ERROR; } } *curr = (char *) *buf; // copy header into *buf little_endian::encode(*curr, msg->direction); *curr += sizeof(msg->direction); little_endian::encode(*curr, msg->op); *curr += sizeof(msg->op); little_endian::encode(*curr, msg->src); *curr += sizeof(msg->src); little_endian::encode(*curr, msg->dst); *curr += sizeof(msg->dst); little_endian::encode(*curr, msg->count); *curr += sizeof(msg->count); return TRANSPORT_SUCCESS; } int Packer::pack(const Request::Request *req, void **buf, std::size_t *bufsize, char **curr) { return pack(static_cast<const Message *>(req), buf, bufsize, curr); } int Packer::pack(const Response::Response *res, void **buf, std::size_t *bufsize, char **curr) { return pack(static_cast<const Message *>(res), buf, bufsize, curr); } }
[ "jasonlee@lanl.gov" ]
jasonlee@lanl.gov
cdaf0aa25f8fe0c592f216237ff58329df4d1290
88ff0f4227d8f2004df52205cde54f568256597a
/task_1_8_11.cpp
cb19e3a2356604e0c4765eb88a8924d2deb89f46
[]
no_license
AlterFritz88/intro_to_prog_c_plus_plus
6f5322ff6d2ce17ab5252db62cb774fcfb075598
d83b15bbfad2252a041a560487b2dcc5c6b39c16
refs/heads/master
2020-06-13T04:39:24.602066
2019-07-16T10:18:53
2019-07-16T10:18:53
194,537,678
0
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
#include <iostream> using namespace std; int main() { int r, c; cin >> r >> c; int arr[r][c]; int tranc_arr[c][r]; for (int i = 0; i < r; i++){ for (int j = 0; j < c; j++){ cin >> arr[i][j]; } } for (int i = 0; i < r; i++){ for (int j = 0; j < c; j++){ tranc_arr[j][i] = arr[r - i - 1][j]; } } for (int i = 0; i < c; i++){ for (int j = 0; j < r; j++) { cout << tranc_arr[i][j] << " "; } cout << endl; } return 0; }
[ "burdin009@gmail.com" ]
burdin009@gmail.com
aebb9268c3df555dd40407d922e029f361df6a98
5d4da40e0b511a955b418748327ce29565d9c10c
/include/ResourceManager.h
bb2b11cfb8d52c1af59593628002a47c282517a1
[]
no_license
danilodna/arf
eef0c22032813ddafd99d1e28c2c25964074b0b5
9f48264acd7a98a164d130f4c0e51d5f0b9d8f2b
refs/heads/master
2020-03-27T04:44:07.212116
2018-10-31T13:58:07
2018-10-31T13:58:07
145,964,373
0
0
null
null
null
null
UTF-8
C++
false
false
1,573
h
#ifndef RESOURCE_MANAGER_H #define RESOURCE_MANAGER_H #include "../include/Shader.h" #include "../include/Texture.h" #include <glm/gtc/type_ptr.hpp> #include <string> #include <map> class ResourceManager { private: ResourceManager() = default; // Loads and generates a shader from file static Shader loadShaderFromFile(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile = NULL); // Loads a single texture from file static Texture loadTextureFromFile(const GLchar *file, GLboolean alpha); public: // Resource storage static std::map<std::string, Shader> Shaders; static std::map<std::string, Texture> Textures; // Loads (and generates) a shader program from file loading vertex, fragment (and geometry) shader's source code. If gShaderFile is not NULL, it also loads a geometry shader static Shader loadShader(const GLchar* vertexShaderFile, const GLchar* fragmentShaderFile, const GLchar* geometryShaderFile, const std::string& name, GLfloat width, GLfloat height); // static Shader loadShader(const GLchar* vertexShaderFile, const GLchar* fragmentShaderFile, const GLchar* geometryShaderFile, const std::string& name); // Retrieves a stored sader static Shader getShader(const std::string& name); // Loads (and generates) a texture from file static Texture loadTexture(const GLchar *file, GLboolean alpha, const std::string& name); // Retrieves a stored texture static Texture getTexture(const std::string& name); // Properly de-allocates all loaded resources static void clear(); }; #endif // RESOURCE_MANAGER_H
[ "danillodna@gmail.com" ]
danillodna@gmail.com
ec192bc2eda9c23831b53284cc1db991ccdaf4e9
95b9621b5c8b930e780df893dd774fd263171513
/BUGLIFE - A Bug’s Life.cpp
655c899f9bbb04dc3ab25bdce13320220cf0679f
[]
no_license
Perdente/SPOJ
0936aacb9ea76be3b0d9cf8da2a4dee9fa45f74a
0bfe31818a62c532a97e5f3ca96ae3675a1b2169
refs/heads/main
2023-06-11T11:16:18.406075
2021-06-18T04:57:32
2021-06-18T04:57:32
370,556,252
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
cpp
//https://www.spoj.com/problems/BUGLIFE/ #include<bits/stdc++.h> using namespace std; #define int long long int vector<vector<int>>graph; vector<int>color; int c=1; void Malena(){ int n,m;cin>>n>>m; graph.resize(n+1); color.resize(n+1); bool flag=true; function<void(int,int)>dfs=[&](int u,int col)->void{ color[u]=col; for(auto v:graph[u]){ if(color[v]==col)flag=false; if(color[v]==-1){ dfs(v,col^1); } } }; for(int i=1;i<=n;++i){ graph[i].clear(); color[i]=-1; } for(int i=0;i<m;++i){ int u,v;cin>>u>>v; graph[u].push_back(v); graph[v].push_back(u); } for(int i=1;i<=n;++i){ if(graph[i].size() and color[i]==-1){ dfs(i,0); } } cout<<"Scenario #"<<c++<<":\n"; cout<<(flag?"No suspicious bugs found!":"Suspicious bugs found!")<<'\n'; } signed main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; t=1; cin>>t; while(t--){ Malena(); } return 0; }
[ "noreply@github.com" ]
Perdente.noreply@github.com
6a46c3fed10e50d21aac4071a80a618367e743f7
51c8fabe609cc7de64dc1aa8a0c702d1ae4f61fe
/54.ScrollView/Classes/HelloWorldScene.cpp
118c80ca1c34cfdae7db411931b01f1ff8f84621
[]
no_license
Gasbebe/cocos2d_source
5f7720da904ff71a4951bee470b8744aab51c59d
2376f6bdb93a58ae92c0e9cbd06c0d97cd241d14
refs/heads/master
2021-01-18T22:35:30.357253
2016-05-20T08:10:55
2016-05-20T08:10:55
54,854,003
0
0
null
null
null
null
UTF-8
C++
false
false
1,595
cpp
#include "HelloWorldScene.h" USING_NS_CC; using namespace cocos2d; using namespace cocos2d::extension; Scene* HelloWorld::createScene() { auto scene = Scene::create(); auto layer = HelloWorld::create(); scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { if ( !LayerColor::initWithColor(Color4B(255,255,255,255)) ) { return false; } ///////////////////////////// auto sprite1 = Sprite::create("Hello.png"); auto sprite2 = Sprite::create("Hello.png"); sprite1->setScale(0.4f); sprite2->setScale(0.4f); sprite1->setPosition(Vec2(100, 80)); sprite2->setPosition(Vec2(850, 80)); auto layer = LayerColor::create(Color4B::GREEN); layer->setAnchorPoint(Vec2::ZERO); layer->setPosition(Vec2::ZERO); layer->setContentSize(Size(960, 160)); layer->addChild(sprite1); layer->addChild(sprite2); scrollView = ScrollView::create(); scrollView->retain(); scrollView->setDirection(ScrollView::Direction::HORIZONTAL); scrollView->setViewSize(Size(480, 160)); scrollView->setContentSize(layer->getContentSize()); scrollView->setContentOffset(Vec2::ZERO, false); //scrollView->setContentOffset(Vec2(300,0), true); scrollView->setPosition(Vec2(0, 100)); scrollView->setContainer(layer); scrollView->setDelegate(this); this->addChild(scrollView); return true; } void HelloWorld::scrollViewDidScroll(ScrollView* view) { log("scrollViewDidScroll......"); } void HelloWorld::scrollViewDidZoom(ScrollView* view) { log("scrollViewDidZoom"); }
[ "gasbebe@gmail.com" ]
gasbebe@gmail.com
2856107f09e192f4a848ff8336fe456fd85fbc3a
caef7bf5be5bfe5713e192a679c35532d51e7405
/src/tir/schedule/analysis/analysis.cc
3865781c587026fe759571070f966f329bc0edef
[ "Apache-2.0", "Zlib", "MIT", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "Unlicense" ]
permissive
hitcoogle/tvm
9c1055bae803b57ddbd243872a3ae5e09337e7d0
9b034d729f80f6f19106ae435221e4c48df44618
refs/heads/main
2023-07-27T14:29:49.767273
2021-09-06T23:54:15
2021-09-06T23:54:15
403,906,667
1
0
Apache-2.0
2021-09-07T08:48:30
2021-09-07T08:48:29
null
UTF-8
C++
false
false
35,249
cc
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "../utils.h" namespace tvm { namespace tir { /******** IR Module ********/ const PrimFuncNode* GetRootPrimFunc(const IRModule& mod, const StmtNode* root_block, GlobalVar* result_g_var) { for (const auto& kv : mod->functions) { const GlobalVar& g_var = kv.first; const BaseFunc& base_func = kv.second; if (const auto* func = base_func.as<PrimFuncNode>()) { if (const auto* realize = func->body.as<BlockRealizeNode>()) { if (realize->block.get() == root_block) { if (result_g_var != nullptr) { *result_g_var = g_var; } return func; } } } } LOG(FATAL) << "IndexError: Could not get the corresponding function in the schedule state of the " "statement:\n" << GetRef<Stmt>(root_block); throw; } /******** Scope ********/ /*! * \brief Gets the sref to the scope root block, exclusive * \param sref The block or loop sref to be retrieved * \return The sref to the scope root block. NullOpt if `sref` is the root block of the IR */ Optional<StmtSRef> GetScopeRoot(const StmtSRef& sref) { for (const StmtSRefNode* p = sref->parent; p != nullptr; p = p->parent) { if (p->stmt->IsInstance<BlockNode>()) { return GetRef<StmtSRef>(p); } } return NullOpt; } StmtSRef GetScopeRoot(const ScheduleState& self, const StmtSRef& sref, bool require_stage_pipeline) { class RootBlockError : public ScheduleError { public: explicit RootBlockError(IRModule mod) : mod_(mod) {} IRModule mod() const final { return mod_; } String FastErrorString() const final { return "ScheduleError: The primitive does not operate on the root block"; } String DetailRenderTemplate() const final { return "The primitive does not operate on the root block"; } Array<ObjectRef> LocationsOfInterest() const final { return {}; } IRModule mod_; }; class NotStagePipelineError : public ScheduleError { public: explicit NotStagePipelineError(IRModule mod, Block block) : mod_(mod), block_(block) {} IRModule mod() const final { return mod_; } String FastErrorString() const final { return "ScheduleError: The scope root is not a stage pipeline"; } String DetailRenderTemplate() const final { return R"(The scope {0} is not a stage pipeline. Definition of a scope that is a stage pipeline: - The region cover property holds for every of its child blocks - No write-after-read dependency or opaque dependency, - only read-after-write and write-after-write are allowed - All the statements in the scope are schedulable statements, i.e. Block and For )"; } Array<ObjectRef> LocationsOfInterest() const final { return {block_}; } IRModule mod_; Block block_; }; StmtSRef scope_root_sref{nullptr}; if (Optional<StmtSRef> opt_scope_root_sref = GetScopeRoot(sref)) { scope_root_sref = opt_scope_root_sref.value(); } else { throw RootBlockError(self->mod); } bool stage_pipeline = self->GetBlockInfo(scope_root_sref).scope->stage_pipeline; if (require_stage_pipeline && stage_pipeline == false) { const BlockNode* block = TVM_SREF_TO_BLOCK(block, scope_root_sref); throw NotStagePipelineError(self->mod, GetRef<Block>(block)); } return scope_root_sref; } /*! * \brief Check the dominant property of a block: * the block is the only writer of its output, dominating the reader of its output buffers * \param self The schedule state * \param block_sref The block whose dominant property is to be checked * \return A boolean indicating if the block is a dominant block */ bool IsDominantBlock(const BlockScope& self, const StmtSRef& block_sref) { // Check whether the input block is the only writer of its outputs const BlockNode* block = TVM_SREF_TO_BLOCK(block, block_sref); const std::unordered_map<Buffer, Array<StmtSRef>, ObjectPtrHash, ObjectPtrEqual>& buffer_writers = self->buffer_writers; for (const BufferRegion& write_region : block->writes) { ICHECK(buffer_writers.count(write_region->buffer)) << "InternalError: buffer \"" << write_region->buffer->name << "\" does not exist in the current scope, when querying block:\n" << GetRef<Block>(block); if (buffer_writers.at(write_region->buffer).size() != 1) { return false; } } return true; } /*! * \brief A helper function that checks whether a given block is a complete block under the scope, * or return the condition it violates if it is not a complete block * \param self The schedule state * \param block_sref The block to be checked * \param scope_root_sref The sref to the root block of the scope that `block_sref` is in * \return 0 if the block is a complete block, or a positive integer indicating which condition is * first violated */ int CheckCompleteBlockErrorCode(const ScheduleState& self, const StmtSRef& block_sref, const StmtSRef& scope_root_sref) { BlockScope scope = self->GetBlockScope(scope_root_sref); // Cond 1. All block vars are data parallel const BlockNode* block = TVM_SREF_TO_BLOCK(block, block_sref); for (const IterVar& iter_var : block->iter_vars) { if (iter_var->iter_type != kDataPar) { return 1; } } // Cond 2. Dominant: the block is the only writer of its output, // dominating the reader of its output buffers if (!IsDominantBlock(scope, block_sref)) { return 2; } // Cond 3. No overlap between the buffers the block reads and writes std::unordered_set<const BufferNode*> written_buffers; written_buffers.reserve(block->writes.size()); for (const BufferRegion& write : block->writes) { written_buffers.insert(write->buffer.get()); } for (const BufferRegion& read : block->reads) { if (written_buffers.count(read->buffer.get())) { return 3; } } return 0; } bool IsCompleteBlock(const ScheduleState& self, const StmtSRef& block_sref, const StmtSRef& scope_root_sref) { return CheckCompleteBlockErrorCode(self, block_sref, scope_root_sref) == 0; } void CheckCompleteBlock(const ScheduleState& self, const StmtSRef& block_sref, const StmtSRef& scope_root_sref) { class IncompleteBlockError : public ScheduleError { public: explicit IncompleteBlockError(IRModule mod, Block block, int violated_cond) : mod_(std::move(mod)), block_(std::move(block)), violated_cond_(violated_cond) {} String FastErrorString() const final { return "ScheduleError: Incomplete block"; } String DetailRenderTemplate() const final { std::ostringstream os; os << "The block {0} is not a complete block - it violates condition #" << violated_cond_ << ".\n" << R"(Definition of a complete block: 1) All block vars are data parallel 2) Dominant: the block is the only writer of its output, dominating the reader of its output buffers 3) No overlap between the buffers the block reads and writes)"; return os.str(); } IRModule mod() const final { return mod_; } Array<ObjectRef> LocationsOfInterest() const final { return {block_}; } IRModule mod_; Block block_; int violated_cond_; }; int error_code = CheckCompleteBlockErrorCode(self, block_sref, scope_root_sref); if (error_code != 0) { const BlockNode* block = TVM_SREF_TO_BLOCK(block, block_sref); throw IncompleteBlockError(self->mod, GetRef<Block>(block), error_code); } } /*! * \brief A helper function that checks whether a given block is a reduction block under the scope, * or return the condition it violates if it is not a reduction block * \param self The schedule state * \param block_sref The block to be checked * \param scope_root_sref The sref to the root block of the scope that `block_sref` is in * \return 0 if the block is a reduction block, or a positive integer indicating which condition is * first violated */ int CheckReductionBlockErrorCode(const ScheduleState& self, const StmtSRef& block_sref, const StmtSRef& scope_root_sref) { BlockScope scope = self->GetBlockScope(scope_root_sref); const BlockNode* block = TVM_SREF_TO_BLOCK(block, block_sref); // Cond 1. The block has the `init` statement. if (!block->init.defined()) { return 1; } // Cond 2. All the block bindings are quasi-affine expressions. if (!self->IsAffineBlockBinding(block_sref)) { return 2; } // Cond 3. All block vars are either data parallel block vars or reduction block vars. Meanwhile, // we collect all the reduction block vars. std::unordered_set<const VarNode*> reduction_block_vars; reduction_block_vars.reserve(block->iter_vars.size()); for (const IterVar& iter_var : block->iter_vars) { if (iter_var->iter_type != kDataPar && iter_var->iter_type != kCommReduce) { return 3; } else if (iter_var->iter_type == kCommReduce) { reduction_block_vars.insert(iter_var->var.get()); } } // Cond 4. Dominant: the block is the only writer of its output, dominating the reader of its // output buffers. if (!IsDominantBlock(scope, block_sref)) { return 4; } // Cond 5. The reduction block vars are not used to index the output buffers. std::unordered_set<const BufferNode*> buffer_written; buffer_written.reserve(block->writes.size()); for (const BufferRegion& write_region : block->writes) { buffer_written.insert(write_region->buffer.get()); } bool affected = false; PreOrderVisit(block->body, [&](const ObjectRef& obj) { if (affected) { return false; } if (const auto* store = obj.as<BufferStoreNode>()) { ICHECK(buffer_written.count(store->buffer.get())) << "ValueError: The buffer \"" << store->buffer << "\" is written in the block but is not in the block's signature"; for (const PrimExpr& index : store->indices) { if (UsesVar(index, [&reduction_block_vars](const VarNode* var) { return reduction_block_vars.count(var); })) { affected = true; return false; } } return false; } return true; }); return !affected ? 0 : 5; } bool IsReductionBlock(const ScheduleState& self, const StmtSRef& block_sref, const StmtSRef& scope_root_sref) { return CheckReductionBlockErrorCode(self, block_sref, scope_root_sref) == 0; } void CheckReductionBlock(const ScheduleState& self, const StmtSRef& block_sref, const StmtSRef& scope_root_sref) { class NotReductionBlockError : public ScheduleError { public: explicit NotReductionBlockError(IRModule mod, Block block, int violated_cond) : mod_(std::move(mod)), block_(std::move(block)), violated_cond_(violated_cond) {} String FastErrorString() const final { return "ScheduleError: Not a reduction block"; } String DetailRenderTemplate() const final { std::ostringstream os; os << "The block {0} is not a reduction block - it violates condition #" << violated_cond_ << ".\n" << R"(Definition of a reduction block: 1) The block has the `init` statement 2) All the block bindings are quasi-affine expressions 3) All block vars are either data parallel block vars or reduction block vars 4) Dominant: the block is the only writer of its output, dominating the reader of its output buffers 5) The reduction block vars are not used to index the output buffers)"; return os.str(); } IRModule mod() const final { return mod_; } Array<ObjectRef> LocationsOfInterest() const final { return {block_}; } IRModule mod_; Block block_; int violated_cond_; }; int error_code = CheckReductionBlockErrorCode(self, block_sref, scope_root_sref); if (error_code != 0) { const BlockNode* block = TVM_SREF_TO_BLOCK(block, block_sref); throw NotReductionBlockError(self->mod, GetRef<Block>(block), error_code); } } void CheckSRefSubtreeCompactDataFlow(const ScheduleState& self, const StmtSRef& subtree_root_sref) { class NotCompactDataFlowError : public ScheduleError { public: explicit NotCompactDataFlowError(IRModule mod, Stmt subtree_root, Block violate_block) : mod_(std::move(mod)), subtree_root_(std::move(subtree_root)), violate_block_(std::move(violate_block)) { ICHECK(subtree_root_->IsInstance<BlockNode>() || subtree_root_->IsInstance<ForNode>()); } String FastErrorString() const final { return "ScheduleError: The queried subtree root in SRef tree does not have compact data " "flow, because some of its child block on SRef tree is neither a complete block nor a " "reduction block"; } String DetailRenderTemplate() const final { return "The queried subtree root {0} in SRef tree does not have compact data flow, because " "its child block {1} on SRef tree is neither a complete block nor a reduction block"; } IRModule mod() const final { return mod_; } Array<ObjectRef> LocationsOfInterest() const final { return {subtree_root_, violate_block_}; } IRModule mod_; Stmt subtree_root_; Block violate_block_; }; StmtSRef scope_root = GetScopeRoot(self, subtree_root_sref, /*require_stage_pipeline=*/true); Array<StmtSRef> child_blocks = GetChildBlockSRefOnSRefTree(self, scope_root); for (const StmtSRef& block : child_blocks) { if (!IsCompleteBlock(self, block, scope_root) && !IsReductionBlock(self, block, scope_root)) { const BlockNode* violate_block = TVM_SREF_TO_BLOCK(violate_block, block); throw NotCompactDataFlowError(self->mod, GetRef<Stmt>(subtree_root_sref->stmt), GetRef<Block>(violate_block)); } } } /******** Binding ********/ bool IsAffineBinding(const BlockRealize& realize, const Map<Var, Range>& loop_var_ranges, arith::Analyzer* analyzer) { if (loop_var_ranges.empty()) { return true; } Array<arith::IterSumExpr> results = arith::DetectIterMap( /*indices=*/realize->iter_values, /*input_iters=*/loop_var_ranges, /*predicate=*/realize->predicate, /*require_bijective=*/false, /*analyzer=*/analyzer); if (results.empty()) { return false; } for (const arith::IterSumExpr& sum_expr : results) { const Array<arith::IterSplitExpr>& args = sum_expr->args; if (!args.empty() && !is_one(args[0]->scale)) { return false; } } return true; } void CheckAffineBinding(const ScheduleState& self, Block block) { class NotAffineBindingError : public ScheduleError { public: explicit NotAffineBindingError(IRModule mod, Block block) : mod_(std::move(mod)), block_(std::move(block)) {} String FastErrorString() const final { return "ScheduleError: The block is required to have an affine binding"; } String DetailRenderTemplate() const final { return "The block {0} is required to have an affine binding"; } IRModule mod() const final { return mod_; } Array<ObjectRef> LocationsOfInterest() const final { return {block_}; } IRModule mod_; Block block_; }; if (!self->IsAffineBlockBinding(self->stmt2ref.at(block.get()))) { throw NotAffineBindingError(self->mod, std::move(block)); } } Map<Var, Range> LoopDomainOfSRefTreePath(const StmtSRef& low_inclusive, const Optional<StmtSRef>& high_exclusive, const runtime::StorageScope& extra_relax_scope) { Map<Var, Range> result; const StmtSRefNode* p = low_inclusive.get(); const StmtSRefNode* limit = static_cast<const StmtSRefNode*>(high_exclusive.get()); for (; p != limit; p = p->parent) { const ForNode* loop = p->StmtAs<ForNode>(); if (loop == nullptr) { break; } result.Set(loop->loop_var, Range::FromMinExtent(loop->min, loop->extent)); } if (extra_relax_scope.rank != runtime::StorageRank::kGlobal) { for (; p; p = p->parent) { if (const ForNode* loop = p->StmtAs<ForNode>()) { if (loop->kind == ForKind::kThreadBinding) { const String& thread_tag = loop->thread_binding.value()->thread_tag; if (CanRelaxStorageUndereThread(extra_relax_scope, runtime::ThreadScope::Create(thread_tag))) { result.Set(loop->loop_var, Range::FromMinExtent(loop->min, loop->extent)); } } } } } return result; } Map<Var, PrimExpr> GetBindings(const BlockRealize& realize) { const BlockNode* block = realize->block.get(); const Array<IterVar>& all_lhs = block->iter_vars; const Array<PrimExpr>& all_rhs = realize->iter_values; ICHECK_EQ(all_lhs.size(), all_rhs.size()); Map<Var, PrimExpr> result; for (int i = 0, n = all_lhs.size(); i < n; ++i) { const IterVar& lhs = all_lhs[i]; const PrimExpr& rhs = all_rhs[i]; result.Set(lhs->var, rhs); } return result; } bool GetVarsTouchedByBlockIters(const BlockRealize& block_realize, std::unordered_set<const VarNode*>* data_par_vars, std::unordered_set<const VarNode*>* reduce_vars) { Block block = block_realize->block; ICHECK(block_realize->block.same_as(block)) << "ValueError: The input `block_realize` is required to be the exact BlockRealize of the " "input block"; bool has_block_vars_of_other_types = false; ICHECK_EQ(block->iter_vars.size(), block_realize->iter_values.size()); int n = static_cast<int>(block->iter_vars.size()); for (int i = 0; i < n; ++i) { const IterVar& iter_var = block->iter_vars[i]; const PrimExpr& iter_value = block_realize->iter_values[i]; std::unordered_set<const VarNode*>* set = nullptr; if (iter_var->iter_type == IterVarType::kDataPar) { set = data_par_vars; } else if (iter_var->iter_type == IterVarType::kCommReduce) { set = reduce_vars; } else { has_block_vars_of_other_types = true; } Array<Var> vars_in_binding = UndefinedVars(iter_value); for (const Var& var : vars_in_binding) { set->insert(var.get()); } } return has_block_vars_of_other_types; } /******** Block-loop relation ********/ Array<StmtSRef> GetChildBlockSRefOnSRefTree(const ScheduleState& self, const StmtSRef& parent_sref) { Array<BlockRealize> child_block_realize = GetChildBlockRealizeOnSRefTree(parent_sref); Array<StmtSRef> child_block_srefs; child_block_srefs.reserve(child_block_realize.size()); for (BlockRealize realize : child_block_realize) { child_block_srefs.push_back(self->stmt2ref.at(realize->block.get())); } return child_block_srefs; } Array<BlockRealize> GetChildBlockRealizeOnSRefTree(const StmtSRef& parent_sref) { struct Collector : public StmtVisitor { static Array<BlockRealize> Collect(const Stmt& stmt) { Collector collector; collector(stmt); return std::move(collector.result_); } void VisitStmt_(const BlockRealizeNode* block_realize) final { result_.push_back(GetRef<BlockRealize>(block_realize)); } Array<BlockRealize> result_; }; if (parent_sref->stmt->IsInstance<ForNode>()) { const auto* loop = static_cast<const ForNode*>(parent_sref->stmt); return Collector::Collect(loop->body); } else if (parent_sref->stmt->IsInstance<BlockNode>()) { const auto* block = static_cast<const BlockNode*>(parent_sref->stmt); return Collector::Collect(block->body); } ICHECK(false) << "Unreachable"; throw; } BlockRealize CheckGetSingleChildBlockRealizeOnSRefTree(const ScheduleState& self, const StmtSRef& parent_sref) { class NonSingleChildBlockError : public ScheduleError { public: explicit NonSingleChildBlockError(IRModule mod, const StmtSRef& sref) : mod_(std::move(mod)), stmt_(GetRef<Stmt>(sref->stmt)) { sref_type_ = stmt_.as<BlockNode>() != nullptr ? "block" : "loop"; } String FastErrorString() const final { std::ostringstream os; os << "ScheduleError: The " << sref_type_ << " is required to have only one child block"; return os.str(); } String DetailRenderTemplate() const final { std::ostringstream os; os << "The " << sref_type_ << " {0} is required to have only one child block"; return os.str(); } IRModule mod() const final { return mod_; } Array<ObjectRef> LocationsOfInterest() const final { return {stmt_}; } IRModule mod_; Stmt stmt_; String sref_type_; }; Array<BlockRealize> child_block_realize = GetChildBlockRealizeOnSRefTree(parent_sref); if (child_block_realize.size() != 1) { throw NonSingleChildBlockError(self->mod, parent_sref); } return child_block_realize[0]; } BlockRealize GetBlockRealize(const ScheduleState& self, const StmtSRef& block_sref) { struct BlockRealizeFinder : public StmtVisitor { explicit BlockRealizeFinder(const BlockNode* target_block) : target_block(target_block), result(nullptr) {} void VisitStmt(const Stmt& stmt) final { if (result != nullptr) { return; } StmtVisitor::VisitStmt(stmt); } void VisitStmt_(const BlockRealizeNode* block_realize) final { if (block_realize->block.get() == target_block) { result = block_realize; } // No need to visit recursively, since the deeper BlockRealizes must not be the result. } const BlockNode* target_block; const BlockRealizeNode* result; }; const BlockNode* block = TVM_SREF_TO_BLOCK(block, block_sref); if (block_sref->parent == nullptr) { const PrimFuncNode* func = GetRootPrimFunc(self->mod, block, nullptr); return Downcast<BlockRealize>(func->body); } else { BlockRealizeFinder finder(block); finder(GetRef<Stmt>(block_sref->parent->stmt)); ICHECK(finder.result != nullptr) << "InternalError: Cannot find the BlockRealize of block " << GetRef<Block>(block); return GetRef<BlockRealize>(finder.result); } } /******** Block-buffer relation ********/ Buffer GetNthAccessBuffer(const ScheduleState& self, const Block& block, int n, bool is_write) { class BufferIndexOutOfRangeError : public ScheduleError { public: explicit BufferIndexOutOfRangeError(IRModule mod, Block block, int buffer_index, bool is_write) : mod_(std::move(mod)), block_(std::move(block)), buffer_index_(buffer_index), is_write_(is_write) {} String FastErrorString() const final { if (is_write_) { return "ScheduleError: The input `buffer_index` is out of range. It is required to be in " "range " "[0, num_write_regions) where `num_write_regions` is the number of buffer regions " "written by the block."; } else { return "ScheduleError: The input `buffer_index` is out of range. It is required to be in " "range " "[0, num_read_regions) where `num_read_regions` is the number of buffer regions " "read by the block."; } } String DetailRenderTemplate() const final { std::ostringstream os; size_t num = is_write_ ? block_->writes.size() : block_->reads.size(); std::string access_type = is_write_ ? "write" : "read"; os << "The block {0} has " << num << " " << access_type << " regions, so `buffer_index` is required to be in [0, " << num << "). However, the input `buffer_index` is " << buffer_index_ << ", which is out of the expected range."; return os.str(); } IRModule mod() const final { return mod_; } Array<ObjectRef> LocationsOfInterest() const final { return {block_}; } private: IRModule mod_; Block block_; int buffer_index_; bool is_write_; }; const Array<BufferRegion>& access_region = is_write ? block->writes : block->reads; if (n < 0 || static_cast<int>(access_region.size()) <= n) { throw BufferIndexOutOfRangeError(self->mod, block, n, is_write); } return access_region[n]->buffer; } /******** Pattern Matcher ********/ /*! * \brief PrimExpr pattern matcher. * * It is different from the pattern matcher in arith/pattern_match.h, which is dedicated * for compile-time constant patterns. This pattern matcher can work on dynamic user-specific * patterns. * * The code below shows how to use the pattern matcher. * * \code * * Var x("x"), y("y"); * // use PrimExpr to declare patterns, x, y are holes that can be filled with * PatternMatcher pattern_matcher(x + y); * // expr = C[i, j] + A[i, k] * B[k, j], which is the expr we want to match * pattern_matcher.Match(expr); * * if (pattern_matcher.Success()) { * pattern_matcher.Eval(x) // C[i, j] * pattern_matcher.Eval(y) // A[i, k] * B[k, j] * } * * \endcode */ class PatternMatcher : public ExprVisitor { public: explicit PatternMatcher(PrimExpr pattern) : pattern_(std::move(pattern)) {} void VisitExpr_(const VarNode* op) final { auto it = filled_map_.find(op); if (it == filled_map_.end()) { filled_map_[op] = expr_to_match_; } else { ExprDeepEqual equal; if (it->second.same_as(expr_to_match_) || equal(it->second, expr_to_match_)) return; match_success_ = false; } } void VisitExpr_(const LoadNode* op) final { const auto* ptr = expr_to_match_.as<LoadNode>(); if (ptr == nullptr) { match_success_ = false; } else { if (!op->buffer_var.same_as(ptr->buffer_var)) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; expr_to_match_ = ptr->predicate; VisitExpr(op->predicate); expr_to_match_ = ptr->index; VisitExpr(op->index); std::swap(expr_to_match_, tmp); } } } void VisitExpr_(const LetNode* op) final { const auto* ptr = expr_to_match_.as<LetNode>(); if (ptr == nullptr) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; expr_to_match_ = ptr->var; VisitExpr(op->var); expr_to_match_ = ptr->value; VisitExpr(op->value); expr_to_match_ = ptr->body; VisitExpr(op->body); std::swap(expr_to_match_, tmp); } } void VisitExpr_(const CallNode* op) final { const auto* ptr = expr_to_match_.as<CallNode>(); if (ptr == nullptr) { match_success_ = false; } else { if (!op->op.same_as(ptr->op)) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; for (size_t i = 0; i < op->args.size(); ++i) { expr_to_match_ = ptr->args[i]; VisitExpr(op->args[i]); } std::swap(expr_to_match_, tmp); } } } #define TVM_DECLARE_PATTERN_MATCHER_BIN_OP(OpName) \ void VisitExpr_(const OpName* op) { \ const auto* ptr = expr_to_match_.as<OpName>(); \ if (ptr == nullptr) { \ match_success_ = false; \ } else { \ PrimExpr current = expr_to_match_; \ expr_to_match_ = ptr->a; \ VisitExpr(op->a); \ expr_to_match_ = ptr->b; \ VisitExpr(op->b); \ std::swap(expr_to_match_, current); \ } \ } TVM_DECLARE_PATTERN_MATCHER_BIN_OP(AddNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(SubNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(MulNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(DivNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(ModNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(FloorDivNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(FloorModNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(MinNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(MaxNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(EQNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(NENode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(LTNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(LENode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(GTNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(GENode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(AndNode); TVM_DECLARE_PATTERN_MATCHER_BIN_OP(OrNode); void VisitExpr_(const CastNode* op) final { const auto* ptr = expr_to_match_.as<CastNode>(); if (ptr == nullptr) { match_success_ = false; } else { if (!runtime::TypeEqual(op->dtype, ptr->dtype)) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; expr_to_match_ = ptr->value; VisitExpr(op->value); std::swap(expr_to_match_, tmp); } } } void VisitExpr_(const NotNode* op) final { const auto* ptr = expr_to_match_.as<NotNode>(); if (ptr == nullptr) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; expr_to_match_ = ptr->a; VisitExpr(op->a); std::swap(expr_to_match_, tmp); } } void VisitExpr_(const SelectNode* op) final { const auto* ptr = expr_to_match_.as<SelectNode>(); if (ptr == nullptr) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; expr_to_match_ = ptr->condition; VisitExpr(op->condition); expr_to_match_ = ptr->true_value; VisitExpr(op->true_value); expr_to_match_ = ptr->false_value; VisitExpr(op->false_value); std::swap(expr_to_match_, tmp); } } void VisitExpr_(const RampNode* op) final { const auto* ptr = expr_to_match_.as<RampNode>(); if (ptr == nullptr) { match_success_ = false; } else { if (op->lanes != ptr->lanes) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; expr_to_match_ = ptr->base; VisitExpr(op->base); expr_to_match_ = ptr->stride; VisitExpr(op->stride); std::swap(expr_to_match_, tmp); } } } void VisitExpr_(const BroadcastNode* op) final { const auto* ptr = expr_to_match_.as<BroadcastNode>(); if (ptr == nullptr) { match_success_ = false; } else { if (op->lanes != ptr->lanes) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; expr_to_match_ = ptr->value; VisitExpr(op->value); std::swap(expr_to_match_, tmp); } } } void VisitExpr_(const ShuffleNode* op) final { const auto* ptr = expr_to_match_.as<ShuffleNode>(); if (ptr == nullptr) { match_success_ = false; } else { if (op->vectors.size() != ptr->vectors.size() || op->indices.size() != ptr->indices.size()) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; for (size_t i = 0; i < op->indices.size(); ++i) { expr_to_match_ = ptr->indices[i]; VisitExpr(op->indices[i]); } for (size_t i = 0; i < op->vectors.size(); ++i) { expr_to_match_ = ptr->vectors[i]; VisitExpr(op->vectors[i]); } std::swap(expr_to_match_, tmp); } } } void VisitExpr_(const IntImmNode* op) final { const auto* ptr = expr_to_match_.as<IntImmNode>(); match_success_ = ptr != nullptr && op->value == ptr->value; } void VisitExpr_(const FloatImmNode* op) final { const auto* ptr = expr_to_match_.as<FloatImmNode>(); match_success_ = ptr != nullptr && op->value == ptr->value; } void VisitExpr_(const StringImmNode* op) final { const auto* ptr = expr_to_match_.as<StringImmNode>(); match_success_ = ptr != nullptr && op->value == ptr->value; } void VisitExpr_(const BufferLoadNode* op) final { const auto* ptr = expr_to_match_.as<BufferLoadNode>(); if (ptr == nullptr) { match_success_ = false; } else { if (!op->buffer.same_as(ptr->buffer) || op->indices.size() != ptr->indices.size()) { match_success_ = false; } else { PrimExpr tmp = expr_to_match_; for (size_t i = 0; i < op->indices.size(); ++i) { expr_to_match_ = ptr->indices[i]; VisitExpr(op->indices[i]); } std::swap(expr_to_match_, tmp); } } } void Match(const PrimExpr& expr_to_match) { this->match_success_ = true; this->filled_map_.clear(); this->expr_to_match_ = expr_to_match; this->operator()(pattern_); } PrimExpr Eval(const Var& var) { auto it = filled_map_.find(var.operator->()); ICHECK(it != filled_map_.end()) << "Unknown pattern variable"; ICHECK(match_success_) << "Match failed"; return it->second; } bool Success() const { return match_success_; } private: bool match_success_{true}; PrimExpr pattern_, expr_to_match_; std::unordered_map<const VarNode*, PrimExpr> filled_map_; }; /******** Commutative Reducer ********/ bool MatchReducer(const CommReducer& reducer, const PrimExpr& identity, const PrimExpr& combiner, const BufferLoad& load, PrimExpr* lhs, PrimExpr* rhs) { if (!ExprDeepEqual()(reducer->identity_element[0], identity)) { return false; } PatternMatcher pattern_matcher(reducer->result[0]); pattern_matcher.Match(combiner); if (pattern_matcher.Success()) { PrimExpr lhs_tmp = pattern_matcher.Eval(reducer->lhs[0]); PrimExpr rhs_tmp = pattern_matcher.Eval(reducer->rhs[0]); if (ExprDeepEqual()(load, lhs_tmp)) { *lhs = std::move(lhs_tmp); *rhs = std::move(rhs_tmp); } return true; } return false; } bool FromIdentityCombiner(const PrimExpr& identity, const BufferStore& combiner, CommReducer* result_reducer, PrimExpr* lhs, PrimExpr* rhs) { BufferLoad load(combiner->buffer, combiner->indices); // Check reduction patterns. for (const TypedPackedFunc<CommReducer(DataType)>& reducer_getter : GetReducerGetters()) { CommReducer reducer = reducer_getter(identity.dtype()); if (MatchReducer(reducer, identity, combiner->value, load, lhs, rhs)) { *result_reducer = std::move(reducer); return true; } } return false; } /******** SRef Tree Related ********/ StmtSRef GetSRefTreeRoot(const StmtSRef& sref) { const StmtSRefNode* p = sref.get(); for (; p->parent != nullptr; p = p->parent) { } return GetRef<StmtSRef>(p); } } // namespace tir } // namespace tvm
[ "noreply@github.com" ]
hitcoogle.noreply@github.com
2127fc3dc33e9565b5344f468ad66d666da8a3b0
8cfcf7710c2ffe3e6df8dc2d95a90769cc56c779
/ArmFW.ino
8a5d8e8afdbd79054de20e6b602e3125d9fd4348
[]
no_license
AmitSoli/IMU_Glove
eb80adbdc4329fd7d29eadf2c21f2d4a08259dea
da9407e8f0baf91776cbebf93eecf1a75149bb4b
refs/heads/master
2022-11-27T06:41:09.398665
2020-07-31T12:05:52
2020-07-31T12:05:52
284,027,284
0
0
null
null
null
null
UTF-8
C++
false
false
6,232
ino
#include <Wire.h> #include <BMI160Gen.h> #define NUM_GYROS (5) #define TCAADDR 0x70 #define BMI160_RA_GYRO_X_L 0x0C #define interrupt_lock() (0) #define interrupt_unlock(flags) while (0) {} typedef struct BMI_s { BMI160GenClass bmi160; float gyroXangle; float gyroYangle; float gyroZangle; float CFangleX; float CFangleY; float CFangleZ; } BMI; BMI bmi_s_0; BMI bmi_s_1; BMI bmi_s_2; BMI bmi_s_3; BMI bmi_s_4; BMI bmi_s_array[] = {bmi_s_0, bmi_s_1, bmi_s_2, bmi_s_3, bmi_s_4}; int entry_array[] = {2, 3, 5, 6, 7}; byte oppos_num_bit[] = {7, 6, 5, 4, 3, 2, 1, 0}; byte shifted_num_bit[] = {0 << 3, 1 << 3, 2 << 3, 3 << 3, 4 << 3, 5 << 3, 6 << 3, 7 << 3}; byte shifted_oppos_num_bit[] = {7 << 3, 6 << 3, 5 << 3, 4 << 3, 3 << 3, 2 << 3, 1 << 3, 0}; byte end_num_bit[] = {0 << 6, 1 << 6, 0 << 6, 1 << 6, 2 << 6, 3 << 6, 2 << 6, 3 << 6}; byte oppos_end_num_bit[] = {3 << 6, 2 << 6, 3 << 6, 2 << 6, 1 << 6, 0 << 6, 1 << 6, 0}; const int i2c_addr = 0x69; float G_GAIN = 0.0076; float DT = 0.00001; //20ms, baud = 304bits/DT b = 38400, dt = 0.02 float AA = 0.99; int g_curr_bmi160_index = 0; byte g_i = 0; byte float_to_byte(float num) { float abs_num = (num >=0) ? num : -num; byte b_abs_num = round(abs_num*100); byte ret = b_abs_num & 0x7F; if (num < 0) { ret = (ret | 0x80); } return ret; } byte* float_to_ulong(float num, byte* outArray) { float abs_num = (num >=0) ? num : -num; unsigned long b_abs_num = round(abs_num*100000000); unsigned long toSend = b_abs_num & 0x7FFFFFFF; if (num < 0) { toSend = (toSend | 0x80000000); } outArray[0] = (toSend & 0xFF000000) >> 24; outArray[1] = (toSend & 0xFF0000) >> 16; outArray[2] = (toSend & 0xFF00) >> 8; outArray[3] = (toSend & 0xFF); return outArray; } void setup(void) { unsigned long startTime = millis(); Serial.begin(115200); for (int i=0; i<NUM_GYROS; i++) { bmi_s_array[i].bmi160.begin(1 << entry_array[i],TCAADDR,BMI160GenClass::I2C_MODE, i2c_addr); bmi_s_array[i].gyroXangle = 0; bmi_s_array[i].gyroYangle = 0; bmi_s_array[i].gyroZangle = 0; bmi_s_array[i].CFangleX = 0; bmi_s_array[i].CFangleY = 0; bmi_s_array[i].CFangleZ = 0; bmi_s_array[i].bmi160.autoCalibrateGyroOffset(); } while(Serial.available() >0) { Serial.read(); } while(millis() - startTime < 5000) { } } void loop(void) { int ax, ay, az, gx, gy, gz; // raw values unsigned long startTime = millis(); bmi_s_array[g_curr_bmi160_index].bmi160.readMotionSensor(ax, ay, az, gx, gy, gz); // angular velocity float rateX = gx*G_GAIN; float rateY = gy*G_GAIN; float rateZ = gz*G_GAIN; float accXangle = (atan2(ay,az)+PI)*RAD_TO_DEG; float accYangle = (atan2(az,ax)+PI)*RAD_TO_DEG; float accZangle = (atan2(ax,ay)+PI)*RAD_TO_DEG; if(accXangle>180) accXangle-=360; if(accYangle>180) accYangle-=360; if(accZangle>180) accZangle-=360; /* //no acc bmi_s_array[g_curr_bmi160_index].CFangleX = bmi_s_array[g_curr_bmi160_index].CFangleX + rateX*DT*NUM_GYROS; bmi_s_array[g_curr_bmi160_index].CFangleY = bmi_s_array[g_curr_bmi160_index].CFangleY + rateY*DT*NUM_GYROS; bmi_s_array[g_curr_bmi160_index].CFangleZ = bmi_s_array[g_curr_bmi160_index].CFangleZ + rateZ*DT*NUM_GYROS; */ // original bmi_s_array[g_curr_bmi160_index].CFangleX = AA*(bmi_s_array[g_curr_bmi160_index].CFangleX + rateX*DT*NUM_GYROS) + (1-AA)*accXangle; bmi_s_array[g_curr_bmi160_index].CFangleY = AA*(bmi_s_array[g_curr_bmi160_index].CFangleY + rateY*DT*NUM_GYROS) + (1-AA)*accYangle; bmi_s_array[g_curr_bmi160_index].CFangleZ = AA*(bmi_s_array[g_curr_bmi160_index].CFangleZ + rateZ*DT*NUM_GYROS) + (1-AA)*accZangle; /* neg float cos_yaw = cos(bmi_s_array[g_curr_bmi160_index].CFangleZ*DEG_TO_RAD); float sin_yaw = sin(bmi_s_array[g_curr_bmi160_index].CFangleZ*DEG_TO_RAD); float cos_roll = cos(bmi_s_array[g_curr_bmi160_index].CFangleY*DEG_TO_RAD); float sin_roll = sin(bmi_s_array[g_curr_bmi160_index].CFangleY*DEG_TO_RAD); float sin_pitch = sin(bmi_s_array[g_curr_bmi160_index].CFangleX*DEG_TO_RAD); float cos_pitch = cos(bmi_s_array[g_curr_bmi160_index].CFangleX*DEG_TO_RAD); */ byte delta = millis() - startTime; float cos_yaw = cos(bmi_s_array[g_curr_bmi160_index].CFangleZ*DEG_TO_RAD); float cos_roll = cos(bmi_s_array[g_curr_bmi160_index].CFangleY*DEG_TO_RAD); float cos_pitch = cos(bmi_s_array[g_curr_bmi160_index].CFangleX*DEG_TO_RAD); float sin_yaw = sin(bmi_s_array[g_curr_bmi160_index].CFangleZ*DEG_TO_RAD); float sin_roll = sin(bmi_s_array[g_curr_bmi160_index].CFangleY*DEG_TO_RAD); float sin_pitch = sin(bmi_s_array[g_curr_bmi160_index].CFangleX*DEG_TO_RAD); byte arr[4]; byte start_seq = entry_array[g_curr_bmi160_index] | shifted_oppos_num_bit[entry_array[g_curr_bmi160_index]] | end_num_bit[entry_array[g_curr_bmi160_index]]; byte end_seq = oppos_num_bit[entry_array[g_curr_bmi160_index]] | shifted_num_bit[entry_array[g_curr_bmi160_index]] | oppos_end_num_bit[entry_array[g_curr_bmi160_index]]; //Serial.print(start_seq); //Serial.print('\t'); //Serial.println(end_seq); //byte start_seq = g_curr_bmi160_index | shifted_oppos_num_bit[g_curr_bmi160_index] | end_num_bit[g_curr_bmi160_index]; //byte end_seq = oppos_num_bit[g_curr_bmi160_index] | shifted_num_bit[g_curr_bmi160_index] | oppos_end_num_bit[g_curr_bmi160_index]; Serial.flush(); Serial.write(start_seq); Serial.write(float_to_ulong(cos_yaw*cos_pitch,arr), 4); Serial.write(float_to_ulong(cos_yaw*sin_pitch,arr), 4); Serial.write(float_to_ulong(-sin_yaw,arr), 4); Serial.write(float_to_ulong(sin_roll*sin_yaw*cos_pitch-cos_roll*sin_pitch,arr), 4); Serial.write(float_to_ulong(sin_roll*sin_yaw*sin_pitch+cos_roll*cos_pitch,arr), 4); Serial.write(float_to_ulong(sin_roll*cos_yaw,arr), 4); Serial.write(float_to_ulong(cos_roll*sin_yaw*cos_pitch+sin_roll*sin_pitch,arr), 4); Serial.write(float_to_ulong(cos_roll*sin_yaw*sin_pitch-sin_roll*cos_pitch,arr), 4); Serial.write(float_to_ulong(cos_roll*cos_yaw,arr), 4); Serial.write(end_seq); g_curr_bmi160_index = (g_curr_bmi160_index + 1) % NUM_GYROS; while(millis() - startTime < DT*1000) { } }
[ "soliamit@gmail.com" ]
soliamit@gmail.com
b36534a23f34c5027dd17f2cbcc24d4632bdfe2a
beb2c6086d8b24b3129709bfc1042bc7b9e8e4d0
/core/library/mysql/mysql/psi/psi.h
aae1d50526e13d9a329c20a054f7dfd263730f7d
[]
no_license
sige5193/oha_dbmigrator
f9f5f662f2e3c1927f490eed8fd046bd0f85e5bc
7776706e8a1f3ecd3571d94afc95a894c7a49d86
refs/heads/master
2022-09-01T14:52:11.574668
2017-04-28T02:36:20
2017-04-28T02:36:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
85,865
h
/* Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H #define MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H #ifdef EMBEDDED_LIBRARY #define DISABLE_ALL_PSI #endif /* EMBEDDED_LIBRARY */ #ifndef MY_GLOBAL_INCLUDED /* Make sure a .c or .cc file contains an include to my_global.h first. When this include is missing, all the #ifdef HAVE_XXX have no effect, and the resulting binary won't build, or won't link, or will crash at runtime since various structures will have different binary definitions. */ #error "You must include my_global.h in the code for the build to be correct." #endif #include "../../../mysql/mysql/psi/psi_base.h" #include "../../../mysql/mysql/psi/psi_memory.h" /* MAINTAINER: The following pattern: typedef struct XYZ XYZ; is not needed in C++, but required for C. */ C_MODE_START /** @sa MDL_key. */ struct MDL_key; typedef struct MDL_key MDL_key; /** @sa enum_mdl_type. */ typedef int opaque_mdl_type; /** @sa enum_mdl_duration. */ typedef int opaque_mdl_duration; /** @sa MDL_wait::enum_wait_status. */ typedef int opaque_mdl_status; /** @sa enum_vio_type. */ typedef int opaque_vio_type; struct TABLE_SHARE; struct sql_digest_storage; #ifdef __cplusplus class THD; #else /* Phony declaration when compiling C code. This is ok, because the C code will never have a THD anyway. */ struct opaque_THD { int dummy; }; typedef struct opaque_THD THD; #endif /** @file mysql/psi/psi.h Performance schema instrumentation interface. @defgroup Instrumentation_interface Instrumentation Interface @ingroup Performance_schema @{ */ /** Interface for an instrumented mutex. This is an opaque structure. */ struct PSI_mutex; typedef struct PSI_mutex PSI_mutex; /** Interface for an instrumented rwlock. This is an opaque structure. */ struct PSI_rwlock; typedef struct PSI_rwlock PSI_rwlock; /** Interface for an instrumented condition. This is an opaque structure. */ struct PSI_cond; typedef struct PSI_cond PSI_cond; /** Interface for an instrumented table share. This is an opaque structure. */ struct PSI_table_share; typedef struct PSI_table_share PSI_table_share; /** Interface for an instrumented table handle. This is an opaque structure. */ struct PSI_table; typedef struct PSI_table PSI_table; /** Interface for an instrumented thread. This is an opaque structure. */ struct PSI_thread; typedef struct PSI_thread PSI_thread; /** Interface for an instrumented file handle. This is an opaque structure. */ struct PSI_file; typedef struct PSI_file PSI_file; /** Interface for an instrumented socket descriptor. This is an opaque structure. */ struct PSI_socket; typedef struct PSI_socket PSI_socket; /** Interface for an instrumented prepared statement. This is an opaque structure. */ struct PSI_prepared_stmt; typedef struct PSI_prepared_stmt PSI_prepared_stmt; /** Interface for an instrumented table operation. This is an opaque structure. */ struct PSI_table_locker; typedef struct PSI_table_locker PSI_table_locker; /** Interface for an instrumented statement. This is an opaque structure. */ struct PSI_statement_locker; typedef struct PSI_statement_locker PSI_statement_locker; /** Interface for an instrumented transaction. This is an opaque structure. */ struct PSI_transaction_locker; typedef struct PSI_transaction_locker PSI_transaction_locker; /** Interface for an instrumented idle operation. This is an opaque structure. */ struct PSI_idle_locker; typedef struct PSI_idle_locker PSI_idle_locker; /** Interface for an instrumented statement digest operation. This is an opaque structure. */ struct PSI_digest_locker; typedef struct PSI_digest_locker PSI_digest_locker; /** Interface for an instrumented stored procedure share. This is an opaque structure. */ struct PSI_sp_share; typedef struct PSI_sp_share PSI_sp_share; /** Interface for an instrumented stored program. This is an opaque structure. */ struct PSI_sp_locker; typedef struct PSI_sp_locker PSI_sp_locker; /** Interface for an instrumented metadata lock. This is an opaque structure. */ struct PSI_metadata_lock; typedef struct PSI_metadata_lock PSI_metadata_lock; /** Interface for an instrumented stage progress. This is a public structure, for efficiency. */ struct PSI_stage_progress { ulonglong m_work_completed; ulonglong m_work_estimated; }; typedef struct PSI_stage_progress PSI_stage_progress; /** IO operation performed on an instrumented table. */ enum PSI_table_io_operation { /** Row fetch. */ PSI_TABLE_FETCH_ROW= 0, /** Row write. */ PSI_TABLE_WRITE_ROW= 1, /** Row update. */ PSI_TABLE_UPDATE_ROW= 2, /** Row delete. */ PSI_TABLE_DELETE_ROW= 3 }; typedef enum PSI_table_io_operation PSI_table_io_operation; /** State data storage for @c start_table_io_wait_v1_t, @c start_table_lock_wait_v1_t. This structure provide temporary storage to a table locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_table_io_wait_v1_t @sa start_table_lock_wait_v1_t */ struct PSI_table_locker_state { /** Internal state. */ uint m_flags; /** Current io operation. */ enum PSI_table_io_operation m_io_operation; /** Current table handle. */ struct PSI_table *m_table; /** Current table share. */ struct PSI_table_share *m_table_share; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; /** Implementation specific. For table io, the table io index. For table lock, the lock type. */ uint m_index; }; typedef struct PSI_table_locker_state PSI_table_locker_state; /** Entry point for the performance schema interface. */ struct PSI_bootstrap { /** ABI interface finder. Calling this method with an interface version number returns either an instance of the ABI for this version, or NULL. @param version the interface version number to find @return a versioned interface (PSI_v1, PSI_v2 or PSI) @sa PSI_VERSION_1 @sa PSI_v1 @sa PSI_VERSION_2 @sa PSI_v2 @sa PSI_CURRENT_VERSION @sa PSI */ void* (*get_interface)(int version); }; typedef struct PSI_bootstrap PSI_bootstrap; #ifdef HAVE_PSI_INTERFACE #ifdef DISABLE_ALL_PSI #ifndef DISABLE_PSI_THREAD #define DISABLE_PSI_THREAD #endif #ifndef DISABLE_PSI_MUTEX #define DISABLE_PSI_MUTEX #endif #ifndef DISABLE_PSI_RWLOCK #define DISABLE_PSI_RWLOCK #endif #ifndef DISABLE_PSI_COND #define DISABLE_PSI_COND #endif #ifndef DISABLE_PSI_FILE #define DISABLE_PSI_FILE #endif #ifndef DISABLE_PSI_TABLE #define DISABLE_PSI_TABLE #endif #ifndef DISABLE_PSI_SOCKET #define DISABLE_PSI_SOCKET #endif #ifndef DISABLE_PSI_STAGE #define DISABLE_PSI_STAGE #endif #ifndef DISABLE_PSI_STATEMENT #define DISABLE_PSI_STATEMENT #endif #ifndef DISABLE_PSI_SP #define DISABLE_PSI_SP #endif #ifndef DISABLE_PSI_IDLE #define DISABLE_PSI_IDLE #endif #ifndef DISABLE_PSI_STATEMENT_DIGEST #define DISABLE_PSI_STATEMENT_DIGEST #endif #ifndef DISABLE_PSI_METADATA #define DISABLE_PSI_METADATA #endif #ifndef DISABLE_PSI_MEMORY #define DISABLE_PSI_MEMORY #endif #ifndef DISABLE_PSI_TRANSACTION #define DISABLE_PSI_TRANSACTION #endif #ifndef DISABLE_PSI_SP #define DISABLE_PSI_SP #endif #ifndef DISABLE_PSI_PS #define DISABLE_PSI_PS #endif #endif /** @def DISABLE_PSI_MUTEX Compiling option to disable the mutex instrumentation. This option is mostly intended to be used during development, when doing special builds with only a subset of the performance schema instrumentation, for code analysis / profiling / performance tuning of a specific instrumentation alone. @sa DISABLE_PSI_RWLOCK @sa DISABLE_PSI_COND @sa DISABLE_PSI_FILE @sa DISABLE_PSI_THREAD @sa DISABLE_PSI_TABLE @sa DISABLE_PSI_STAGE @sa DISABLE_PSI_STATEMENT @sa DISABLE_PSI_SP @sa DISABLE_PSI_STATEMENT_DIGEST @sa DISABLE_PSI_SOCKET @sa DISABLE_PSI_MEMORY @sa DISABLE_PSI_IDLE @sa DISABLE_PSI_METADATA @sa DISABLE PSI_TRANSACTION */ #ifndef DISABLE_PSI_MUTEX #define HAVE_PSI_MUTEX_INTERFACE #endif /** @def DISABLE_PSI_RWLOCK Compiling option to disable the rwlock instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_RWLOCK #define HAVE_PSI_RWLOCK_INTERFACE #endif /** @def DISABLE_PSI_COND Compiling option to disable the cond instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_COND #define HAVE_PSI_COND_INTERFACE #endif /** @def DISABLE_PSI_FILE Compiling option to disable the file instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_FILE #define HAVE_PSI_FILE_INTERFACE #endif /** @def DISABLE_PSI_THREAD Compiling option to disable the thread instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_THREAD #define HAVE_PSI_THREAD_INTERFACE #endif /** @def DISABLE_PSI_TABLE Compiling option to disable the table instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_TABLE #define HAVE_PSI_TABLE_INTERFACE #endif /** @def DISABLE_PSI_STAGE Compiling option to disable the stage instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_STAGE #define HAVE_PSI_STAGE_INTERFACE #endif /** @def DISABLE_PSI_STATEMENT Compiling option to disable the statement instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_STATEMENT #define HAVE_PSI_STATEMENT_INTERFACE #endif /** @def DISABLE_PSI_SP Compiling option to disable the stored program instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_SP #define HAVE_PSI_SP_INTERFACE #endif /** @def DISABLE_PSI_PS Compiling option to disable the prepared statement instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_STATEMENT #ifndef DISABLE_PSI_PS #define HAVE_PSI_PS_INTERFACE #endif #endif /** @def DISABLE_PSI_STATEMENT_DIGEST Compiling option to disable the statement digest instrumentation. */ #ifndef DISABLE_PSI_STATEMENT #ifndef DISABLE_PSI_STATEMENT_DIGEST #define HAVE_PSI_STATEMENT_DIGEST_INTERFACE #endif #endif /** @def DISABLE_PSI_TRANSACTION Compiling option to disable the transaction instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_TRANSACTION #define HAVE_PSI_TRANSACTION_INTERFACE #endif /** @def DISABLE_PSI_SOCKET Compiling option to disable the statement instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_SOCKET #define HAVE_PSI_SOCKET_INTERFACE #endif /** @def DISABLE_PSI_MEMORY Compiling option to disable the memory instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_MEMORY #define HAVE_PSI_MEMORY_INTERFACE #endif /** @def DISABLE_PSI_IDLE Compiling option to disable the idle instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_IDLE #define HAVE_PSI_IDLE_INTERFACE #endif /** @def DISABLE_PSI_METADATA Compiling option to disable the metadata instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_METADATA #define HAVE_PSI_METADATA_INTERFACE #endif /** @def PSI_VERSION_1 Performance Schema Interface number for version 1. This version is supported. */ #define PSI_VERSION_1 1 /** @def PSI_VERSION_2 Performance Schema Interface number for version 2. This version is not implemented, it's a placeholder. */ #define PSI_VERSION_2 2 /** @def PSI_CURRENT_VERSION Performance Schema Interface number for the most recent version. The most current version is @c PSI_VERSION_1 */ #define PSI_CURRENT_VERSION 1 #ifndef USE_PSI_2 #ifndef USE_PSI_1 #define USE_PSI_1 #endif #endif /** Interface for an instrumented mutex operation. This is an opaque structure. */ struct PSI_mutex_locker; typedef struct PSI_mutex_locker PSI_mutex_locker; /** Interface for an instrumented rwlock operation. This is an opaque structure. */ struct PSI_rwlock_locker; typedef struct PSI_rwlock_locker PSI_rwlock_locker; /** Interface for an instrumented condition operation. This is an opaque structure. */ struct PSI_cond_locker; typedef struct PSI_cond_locker PSI_cond_locker; /** Interface for an instrumented file operation. This is an opaque structure. */ struct PSI_file_locker; typedef struct PSI_file_locker PSI_file_locker; /** Interface for an instrumented socket operation. This is an opaque structure. */ struct PSI_socket_locker; typedef struct PSI_socket_locker PSI_socket_locker; /** Interface for an instrumented MDL operation. This is an opaque structure. */ struct PSI_metadata_locker; typedef struct PSI_metadata_locker PSI_metadata_locker; /** Operation performed on an instrumented mutex. */ enum PSI_mutex_operation { /** Lock. */ PSI_MUTEX_LOCK= 0, /** Lock attempt. */ PSI_MUTEX_TRYLOCK= 1 }; typedef enum PSI_mutex_operation PSI_mutex_operation; /** Operation performed on an instrumented rwlock. For basic READ / WRITE lock, operations are "READ" or "WRITE". For SX-locks, operations are "SHARED", "SHARED-EXCLUSIVE" or "EXCLUSIVE". */ enum PSI_rwlock_operation { /** Read lock. */ PSI_RWLOCK_READLOCK= 0, /** Write lock. */ PSI_RWLOCK_WRITELOCK= 1, /** Read lock attempt. */ PSI_RWLOCK_TRYREADLOCK= 2, /** Write lock attempt. */ PSI_RWLOCK_TRYWRITELOCK= 3, /** Shared lock. */ PSI_RWLOCK_SHAREDLOCK= 4, /** Shared Exclusive lock. */ PSI_RWLOCK_SHAREDEXCLUSIVELOCK= 5, /** Exclusive lock. */ PSI_RWLOCK_EXCLUSIVELOCK= 6, /** Shared lock attempt. */ PSI_RWLOCK_TRYSHAREDLOCK= 7, /** Shared Exclusive lock attempt. */ PSI_RWLOCK_TRYSHAREDEXCLUSIVELOCK= 8, /** Exclusive lock attempt. */ PSI_RWLOCK_TRYEXCLUSIVELOCK= 9 }; typedef enum PSI_rwlock_operation PSI_rwlock_operation; /** Operation performed on an instrumented condition. */ enum PSI_cond_operation { /** Wait. */ PSI_COND_WAIT= 0, /** Wait, with timeout. */ PSI_COND_TIMEDWAIT= 1 }; typedef enum PSI_cond_operation PSI_cond_operation; /** Operation performed on an instrumented file. */ enum PSI_file_operation { /** File creation, as in @c create(). */ PSI_FILE_CREATE= 0, /** Temporary file creation, as in @c create_temp_file(). */ PSI_FILE_CREATE_TMP= 1, /** File open, as in @c open(). */ PSI_FILE_OPEN= 2, /** File open, as in @c fopen(). */ PSI_FILE_STREAM_OPEN= 3, /** File close, as in @c close(). */ PSI_FILE_CLOSE= 4, /** File close, as in @c fclose(). */ PSI_FILE_STREAM_CLOSE= 5, /** Generic file read, such as @c fgets(), @c fgetc(), @c fread(), @c read(), @c pread(). */ PSI_FILE_READ= 6, /** Generic file write, such as @c fputs(), @c fputc(), @c fprintf(), @c vfprintf(), @c fwrite(), @c write(), @c pwrite(). */ PSI_FILE_WRITE= 7, /** Generic file seek, such as @c fseek() or @c seek(). */ PSI_FILE_SEEK= 8, /** Generic file tell, such as @c ftell() or @c tell(). */ PSI_FILE_TELL= 9, /** File flush, as in @c fflush(). */ PSI_FILE_FLUSH= 10, /** File stat, as in @c stat(). */ PSI_FILE_STAT= 11, /** File stat, as in @c fstat(). */ PSI_FILE_FSTAT= 12, /** File chsize, as in @c my_chsize(). */ PSI_FILE_CHSIZE= 13, /** File delete, such as @c my_delete() or @c my_delete_with_symlink(). */ PSI_FILE_DELETE= 14, /** File rename, such as @c my_rename() or @c my_rename_with_symlink(). */ PSI_FILE_RENAME= 15, /** File sync, as in @c fsync() or @c my_sync(). */ PSI_FILE_SYNC= 16 }; typedef enum PSI_file_operation PSI_file_operation; /** Lock operation performed on an instrumented table. */ enum PSI_table_lock_operation { /** Table lock, in the server layer. */ PSI_TABLE_LOCK= 0, /** Table lock, in the storage engine layer. */ PSI_TABLE_EXTERNAL_LOCK= 1 }; typedef enum PSI_table_lock_operation PSI_table_lock_operation; /** State of an instrumented socket. */ enum PSI_socket_state { /** Idle, waiting for the next command. */ PSI_SOCKET_STATE_IDLE= 1, /** Active, executing a command. */ PSI_SOCKET_STATE_ACTIVE= 2 }; typedef enum PSI_socket_state PSI_socket_state; /** Operation performed on an instrumented socket. */ enum PSI_socket_operation { /** Socket creation, as in @c socket() or @c socketpair(). */ PSI_SOCKET_CREATE= 0, /** Socket connection, as in @c connect(), @c listen() and @c accept(). */ PSI_SOCKET_CONNECT= 1, /** Socket bind, as in @c bind(), @c getsockname() and @c getpeername(). */ PSI_SOCKET_BIND= 2, /** Socket close, as in @c shutdown(). */ PSI_SOCKET_CLOSE= 3, /** Socket send, @c send(). */ PSI_SOCKET_SEND= 4, /** Socket receive, @c recv(). */ PSI_SOCKET_RECV= 5, /** Socket send, @c sendto(). */ PSI_SOCKET_SENDTO= 6, /** Socket receive, @c recvfrom). */ PSI_SOCKET_RECVFROM= 7, /** Socket send, @c sendmsg(). */ PSI_SOCKET_SENDMSG= 8, /** Socket receive, @c recvmsg(). */ PSI_SOCKET_RECVMSG= 9, /** Socket seek, such as @c fseek() or @c seek(). */ PSI_SOCKET_SEEK= 10, /** Socket options, as in @c getsockopt() and @c setsockopt(). */ PSI_SOCKET_OPT= 11, /** Socket status, as in @c sockatmark() and @c isfdtype(). */ PSI_SOCKET_STAT= 12, /** Socket shutdown, as in @c shutdown(). */ PSI_SOCKET_SHUTDOWN= 13, /** Socket select, as in @c select() and @c poll(). */ PSI_SOCKET_SELECT= 14 }; typedef enum PSI_socket_operation PSI_socket_operation; /** Instrumented mutex key. To instrument a mutex, a mutex key must be obtained using @c register_mutex. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_mutex_key; /** Instrumented rwlock key. To instrument a rwlock, a rwlock key must be obtained using @c register_rwlock. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_rwlock_key; /** Instrumented cond key. To instrument a condition, a condition key must be obtained using @c register_cond. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_cond_key; /** Instrumented thread key. To instrument a thread, a thread key must be obtained using @c register_thread. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_thread_key; /** Instrumented file key. To instrument a file, a file key must be obtained using @c register_file. Using a zero key always disable the instrumentation. */ #ifndef PSI_FILE_KEY_DEFINED typedef unsigned int PSI_file_key; #define PSI_FILE_KEY_DEFINED #endif /** Instrumented stage key. To instrument a stage, a stage key must be obtained using @c register_stage. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_stage_key; /** Instrumented statement key. To instrument a statement, a statement key must be obtained using @c register_statement. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_statement_key; /** Instrumented socket key. To instrument a socket, a socket key must be obtained using @c register_socket. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_socket_key; #ifdef HAVE_PSI_1 /** @defgroup Group_PSI_v1 Application Binary Interface, version 1 @ingroup Instrumentation_interface @{ */ /** Mutex information. @since PSI_VERSION_1 This structure is used to register an instrumented mutex. */ struct PSI_mutex_info_v1 { /** Pointer to the key assigned to the registered mutex. */ PSI_mutex_key *m_key; /** The name of the mutex to register. */ const char *m_name; /** The flags of the mutex to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_mutex_info_v1 PSI_mutex_info_v1; /** Rwlock information. @since PSI_VERSION_1 This structure is used to register an instrumented rwlock. */ struct PSI_rwlock_info_v1 { /** Pointer to the key assigned to the registered rwlock. */ PSI_rwlock_key *m_key; /** The name of the rwlock to register. */ const char *m_name; /** The flags of the rwlock to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_rwlock_info_v1 PSI_rwlock_info_v1; /** Condition information. @since PSI_VERSION_1 This structure is used to register an instrumented cond. */ struct PSI_cond_info_v1 { /** Pointer to the key assigned to the registered cond. */ PSI_cond_key *m_key; /** The name of the cond to register. */ const char *m_name; /** The flags of the cond to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_cond_info_v1 PSI_cond_info_v1; /** Thread instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented thread. */ struct PSI_thread_info_v1 { /** Pointer to the key assigned to the registered thread. */ PSI_thread_key *m_key; /** The name of the thread instrument to register. */ const char *m_name; /** The flags of the thread to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_thread_info_v1 PSI_thread_info_v1; /** File instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented file. */ struct PSI_file_info_v1 { /** Pointer to the key assigned to the registered file. */ PSI_file_key *m_key; /** The name of the file instrument to register. */ const char *m_name; /** The flags of the file instrument to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_file_info_v1 PSI_file_info_v1; /** Stage instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented stage. */ struct PSI_stage_info_v1 { /** The registered stage key. */ PSI_stage_key m_key; /** The name of the stage instrument to register. */ const char *m_name; /** The flags of the stage instrument to register. */ int m_flags; }; typedef struct PSI_stage_info_v1 PSI_stage_info_v1; /** Statement instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented statement. */ struct PSI_statement_info_v1 { /** The registered statement key. */ PSI_statement_key m_key; /** The name of the statement instrument to register. */ const char *m_name; /** The flags of the statement instrument to register. */ int m_flags; }; typedef struct PSI_statement_info_v1 PSI_statement_info_v1; /** Socket instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented socket. */ struct PSI_socket_info_v1 { /** Pointer to the key assigned to the registered socket. */ PSI_socket_key *m_key; /** The name of the socket instrument to register. */ const char *m_name; /** The flags of the socket instrument to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_socket_info_v1 PSI_socket_info_v1; /** State data storage for @c start_idle_wait_v1_t. This structure provide temporary storage to an idle locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_idle_wait_v1_t. */ struct PSI_idle_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_idle_locker_state_v1 PSI_idle_locker_state_v1; /** State data storage for @c start_mutex_wait_v1_t. This structure provide temporary storage to a mutex locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_mutex_wait_v1_t */ struct PSI_mutex_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current operation. */ enum PSI_mutex_operation m_operation; /** Current mutex. */ struct PSI_mutex *m_mutex; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_mutex_locker_state_v1 PSI_mutex_locker_state_v1; /** State data storage for @c start_rwlock_rdwait_v1_t, @c start_rwlock_wrwait_v1_t. This structure provide temporary storage to a rwlock locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_rwlock_rdwait_v1_t @sa start_rwlock_wrwait_v1_t */ struct PSI_rwlock_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current operation. */ enum PSI_rwlock_operation m_operation; /** Current rwlock. */ struct PSI_rwlock *m_rwlock; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_rwlock_locker_state_v1 PSI_rwlock_locker_state_v1; /** State data storage for @c start_cond_wait_v1_t. This structure provide temporary storage to a condition locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_cond_wait_v1_t */ struct PSI_cond_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current operation. */ enum PSI_cond_operation m_operation; /** Current condition. */ struct PSI_cond *m_cond; /** Current mutex. */ struct PSI_mutex *m_mutex; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_cond_locker_state_v1 PSI_cond_locker_state_v1; /** State data storage for @c get_thread_file_name_locker_v1_t. This structure provide temporary storage to a file locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa get_thread_file_name_locker_v1_t @sa get_thread_file_stream_locker_v1_t @sa get_thread_file_descriptor_locker_v1_t */ struct PSI_file_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current operation. */ enum PSI_file_operation m_operation; /** Current file. */ struct PSI_file *m_file; /** Current file name. */ const char *m_name; /** Current file class. */ void *m_class; /** Current thread. */ struct PSI_thread *m_thread; /** Operation number of bytes. */ size_t m_number_of_bytes; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_file_locker_state_v1 PSI_file_locker_state_v1; /** State data storage for @c start_metadata_wait_v1_t. This structure provide temporary storage to a metadata locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_metadata_wait_v1_t */ struct PSI_metadata_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current metadata lock. */ struct PSI_metadata_lock *m_metadata_lock; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_metadata_locker_state_v1 PSI_metadata_locker_state_v1; /* Duplicate of NAME_LEN, to avoid dependency on mysql_com.h */ #define PSI_SCHEMA_NAME_LEN (64 * 3) /** State data storage for @c get_thread_statement_locker_v1_t, @c get_thread_statement_locker_v1_t. This structure provide temporary storage to a statement locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa get_thread_statement_locker_v1_t */ struct PSI_statement_locker_state_v1 { /** Discarded flag. */ my_bool m_discarded; /** In prepare flag. */ my_bool m_in_prepare; /** Metric, no index used flag. */ uchar m_no_index_used; /** Metric, no good index used flag. */ uchar m_no_good_index_used; /** Internal state. */ uint m_flags; /** Instrumentation class. */ void *m_class; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_statement; /** Locked time. */ ulonglong m_lock_time; /** Rows sent. */ ulonglong m_rows_sent; /** Rows examined. */ ulonglong m_rows_examined; /** Metric, temporary tables created on disk. */ ulong m_created_tmp_disk_tables; /** Metric, temporary tables created. */ ulong m_created_tmp_tables; /** Metric, number of select full join. */ ulong m_select_full_join; /** Metric, number of select full range join. */ ulong m_select_full_range_join; /** Metric, number of select range. */ ulong m_select_range; /** Metric, number of select range check. */ ulong m_select_range_check; /** Metric, number of select scan. */ ulong m_select_scan; /** Metric, number of sort merge passes. */ ulong m_sort_merge_passes; /** Metric, number of sort merge. */ ulong m_sort_range; /** Metric, number of sort rows. */ ulong m_sort_rows; /** Metric, number of sort scans. */ ulong m_sort_scan; /** Statement digest. */ const struct sql_digest_storage *m_digest; /** Current schema name. */ char m_schema_name[PSI_SCHEMA_NAME_LEN]; /** Length in bytes of @c m_schema_name. */ uint m_schema_name_length; /** Statement character set number. */ uint m_cs_number; PSI_sp_share *m_parent_sp_share; PSI_prepared_stmt *m_parent_prepared_stmt; }; typedef struct PSI_statement_locker_state_v1 PSI_statement_locker_state_v1; /** State data storage for @c get_thread_transaction_locker_v1_t, @c get_thread_transaction_locker_v1_t. This structure provide temporary storage to a transaction locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa get_thread_transaction_locker_v1_t */ struct PSI_transaction_locker_state_v1 { /** Internal state. */ uint m_flags; /** Instrumentation class. */ void *m_class; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_transaction; /** True if read-only transaction, false if read-write. */ my_bool m_read_only; /** True if transaction is autocommit. */ my_bool m_autocommit; /** Number of statements. */ ulong m_statement_count; /** Total number of savepoints. */ ulong m_savepoint_count; /** Number of rollback_to_savepoint. */ ulong m_rollback_to_savepoint_count; /** Number of release_savepoint. */ ulong m_release_savepoint_count; }; typedef struct PSI_transaction_locker_state_v1 PSI_transaction_locker_state_v1; /** State data storage for @c start_socket_wait_v1_t. This structure provide temporary storage to a socket locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_socket_wait_v1_t */ struct PSI_socket_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current socket. */ struct PSI_socket *m_socket; /** Current thread. */ struct PSI_thread *m_thread; /** Operation number of bytes. */ size_t m_number_of_bytes; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Current operation. */ enum PSI_socket_operation m_operation; /** Source file. */ const char* m_src_file; /** Source line number. */ int m_src_line; /** Internal data. */ void *m_wait; }; typedef struct PSI_socket_locker_state_v1 PSI_socket_locker_state_v1; struct PSI_sp_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Stored Procedure share. */ PSI_sp_share* m_sp_share; }; typedef struct PSI_sp_locker_state_v1 PSI_sp_locker_state_v1; /* Using typedef to make reuse between PSI_v1 and PSI_v2 easier later. */ /** Mutex registration API. @param category a category name (typically a plugin name) @param info an array of mutex info to register @param count the size of the info array */ typedef void (*register_mutex_v1_t) (const char *category, struct PSI_mutex_info_v1 *info, int count); /** Rwlock registration API. @param category a category name (typically a plugin name) @param info an array of rwlock info to register @param count the size of the info array */ typedef void (*register_rwlock_v1_t) (const char *category, struct PSI_rwlock_info_v1 *info, int count); /** Cond registration API. @param category a category name (typically a plugin name) @param info an array of cond info to register @param count the size of the info array */ typedef void (*register_cond_v1_t) (const char *category, struct PSI_cond_info_v1 *info, int count); /** Thread registration API. @param category a category name (typically a plugin name) @param info an array of thread info to register @param count the size of the info array */ typedef void (*register_thread_v1_t) (const char *category, struct PSI_thread_info_v1 *info, int count); /** File registration API. @param category a category name (typically a plugin name) @param info an array of file info to register @param count the size of the info array */ typedef void (*register_file_v1_t) (const char *category, struct PSI_file_info_v1 *info, int count); /** Stage registration API. @param category a category name @param info an array of stage info to register @param count the size of the info array */ typedef void (*register_stage_v1_t) (const char *category, struct PSI_stage_info_v1 **info, int count); /** Statement registration API. @param category a category name @param info an array of stage info to register @param count the size of the info array */ typedef void (*register_statement_v1_t) (const char *category, struct PSI_statement_info_v1 *info, int count); /** Socket registration API. @param category a category name (typically a plugin name) @param info an array of socket info to register @param count the size of the info array */ typedef void (*register_socket_v1_t) (const char *category, struct PSI_socket_info_v1 *info, int count); /** Mutex instrumentation initialisation API. @param key the registered mutex key @param identity the address of the mutex itself @return an instrumented mutex */ typedef struct PSI_mutex* (*init_mutex_v1_t) (PSI_mutex_key key, const void *identity); /** Mutex instrumentation destruction API. @param mutex the mutex to destroy */ typedef void (*destroy_mutex_v1_t)(struct PSI_mutex *mutex); /** Rwlock instrumentation initialisation API. @param key the registered rwlock key @param identity the address of the rwlock itself @return an instrumented rwlock */ typedef struct PSI_rwlock* (*init_rwlock_v1_t) (PSI_rwlock_key key, const void *identity); /** Rwlock instrumentation destruction API. @param rwlock the rwlock to destroy */ typedef void (*destroy_rwlock_v1_t)(struct PSI_rwlock *rwlock); /** Cond instrumentation initialisation API. @param key the registered key @param identity the address of the rwlock itself @return an instrumented cond */ typedef struct PSI_cond* (*init_cond_v1_t) (PSI_cond_key key, const void *identity); /** Cond instrumentation destruction API. @param cond the rcond to destroy */ typedef void (*destroy_cond_v1_t)(struct PSI_cond *cond); /** Socket instrumentation initialisation API. @param key the registered mutex key @param socket descriptor @param addr the socket ip address @param addr_len length of socket ip address @return an instrumented socket */ typedef struct PSI_socket* (*init_socket_v1_t) (PSI_socket_key key, const my_socket *fd, const struct sockaddr *addr, socklen_t addr_len); /** socket instrumentation destruction API. @param socket the socket to destroy */ typedef void (*destroy_socket_v1_t)(struct PSI_socket *socket); /** Acquire a table share instrumentation. @param temporary True for temporary tables @param share The SQL layer table share @return a table share instrumentation, or NULL */ typedef struct PSI_table_share* (*get_table_share_v1_t) (my_bool temporary, struct TABLE_SHARE *share); /** Release a table share. @param info the table share to release */ typedef void (*release_table_share_v1_t)(struct PSI_table_share *share); /** Drop a table share. @param temporary True for temporary tables @param schema_name the table schema name @param schema_name_length the table schema name length @param table_name the table name @param table_name_length the table name length */ typedef void (*drop_table_share_v1_t) (my_bool temporary, const char *schema_name, int schema_name_length, const char *table_name, int table_name_length); /** Open an instrumentation table handle. @param share the table to open @param identity table handle identity @return a table handle, or NULL */ typedef struct PSI_table* (*open_table_v1_t) (struct PSI_table_share *share, const void *identity); /** Unbind a table handle from the current thread. This operation happens when an opened table is added to the open table cache. @param table the table to unbind */ typedef void (*unbind_table_v1_t) (struct PSI_table *table); /** Rebind a table handle to the current thread. This operation happens when a table from the open table cache is reused for a thread. @param table the table to unbind */ typedef PSI_table* (*rebind_table_v1_t) (PSI_table_share *share, const void *identity, PSI_table *table); /** Close an instrumentation table handle. Note that the table handle is invalid after this call. @param table the table handle to close */ typedef void (*close_table_v1_t)(struct TABLE_SHARE *server_share, struct PSI_table *table); /** Create a file instrumentation for a created file. This method does not create the file itself, but is used to notify the instrumentation interface that a file was just created. @param key the file instrumentation key for this file @param name the file name @param file the file handle */ typedef void (*create_file_v1_t)(PSI_file_key key, const char *name, File file); /** Spawn a thread. This method creates a new thread, with instrumentation. @param key the instrumentation key for this thread @param thread the resulting thread @param attr the thread attributes @param start_routine the thread start routine @param arg the thread start routine argument */ typedef int (*spawn_thread_v1_t)(PSI_thread_key key, my_thread_handle *thread, const my_thread_attr_t *attr, void *(*start_routine)(void*), void *arg); /** Create instrumentation for a thread. @param key the registered key @param identity an address typical of the thread @return an instrumented thread */ typedef struct PSI_thread* (*new_thread_v1_t) (PSI_thread_key key, const void *identity, ulonglong thread_id); /** Assign a THD to an instrumented thread. @param thread the instrumented thread @param THD the sql layer THD to assign */ typedef void (*set_thread_THD_v1_t)(struct PSI_thread *thread, THD *thd); /** Assign an id to an instrumented thread. @param thread the instrumented thread @param id the id to assign */ typedef void (*set_thread_id_v1_t)(struct PSI_thread *thread, ulonglong id); /** Assign the current operating system thread id to an instrumented thread. The operating system task id is obtained from @c gettid() @param thread the instrumented thread */ typedef void (*set_thread_os_id_v1_t)(struct PSI_thread *thread); /** Get the instrumentation for the running thread. For this function to return a result, the thread instrumentation must have been attached to the running thread using @c set_thread() @return the instrumentation for the running thread */ typedef struct PSI_thread* (*get_thread_v1_t)(void); /** Assign a user name to the instrumented thread. @param user the user name @param user_len the user name length */ typedef void (*set_thread_user_v1_t)(const char *user, int user_len); /** Assign a user name and host name to the instrumented thread. @param user the user name @param user_len the user name length @param host the host name @param host_len the host name length */ typedef void (*set_thread_account_v1_t)(const char *user, int user_len, const char *host, int host_len); /** Assign a current database to the instrumented thread. @param db the database name @param db_len the database name length */ typedef void (*set_thread_db_v1_t)(const char* db, int db_len); /** Assign a current command to the instrumented thread. @param command the current command */ typedef void (*set_thread_command_v1_t)(int command); /** Assign a connection type to the instrumented thread. @param conn_type the connection type */ typedef void (*set_connection_type_v1_t)(opaque_vio_type conn_type); /** Assign a start time to the instrumented thread. @param start_time the thread start time */ typedef void (*set_thread_start_time_v1_t)(time_t start_time); /** Assign a state to the instrumented thread. @param state the thread state */ typedef void (*set_thread_state_v1_t)(const char* state); /** Assign a process info to the instrumented thread. @param info the process into string @param info_len the process into string length */ typedef void (*set_thread_info_v1_t)(const char* info, uint info_len); /** Attach a thread instrumentation to the running thread. In case of thread pools, this method should be called when a worker thread picks a work item and runs it. Also, this method should be called if the instrumented code does not keep the pointer returned by @c new_thread() and relies on @c get_thread() instead. @param thread the thread instrumentation */ typedef void (*set_thread_v1_t)(struct PSI_thread *thread); /** Delete the current thread instrumentation. */ typedef void (*delete_current_thread_v1_t)(void); /** Delete a thread instrumentation. */ typedef void (*delete_thread_v1_t)(struct PSI_thread *thread); /** Get a file instrumentation locker, for opening or creating a file. @param state data storage for the locker @param key the file instrumentation key @param op the operation to perform @param name the file name @param identity a pointer representative of this file. @return a file locker, or NULL */ typedef struct PSI_file_locker* (*get_thread_file_name_locker_v1_t) (struct PSI_file_locker_state_v1 *state, PSI_file_key key, enum PSI_file_operation op, const char *name, const void *identity); /** Get a file stream instrumentation locker. @param state data storage for the locker @param file the file stream to access @param op the operation to perform @return a file locker, or NULL */ typedef struct PSI_file_locker* (*get_thread_file_stream_locker_v1_t) (struct PSI_file_locker_state_v1 *state, struct PSI_file *file, enum PSI_file_operation op); /** Get a file instrumentation locker. @param state data storage for the locker @param file the file descriptor to access @param op the operation to perform @return a file locker, or NULL */ typedef struct PSI_file_locker* (*get_thread_file_descriptor_locker_v1_t) (struct PSI_file_locker_state_v1 *state, File file, enum PSI_file_operation op); /** Record a mutex instrumentation unlock event. @param mutex the mutex instrumentation */ typedef void (*unlock_mutex_v1_t) (struct PSI_mutex *mutex); /** Record a rwlock instrumentation unlock event. @param rwlock the rwlock instrumentation */ typedef void (*unlock_rwlock_v1_t) (struct PSI_rwlock *rwlock); /** Record a condition instrumentation signal event. @param cond the cond instrumentation */ typedef void (*signal_cond_v1_t) (struct PSI_cond *cond); /** Record a condition instrumentation broadcast event. @param cond the cond instrumentation */ typedef void (*broadcast_cond_v1_t) (struct PSI_cond *cond); /** Record an idle instrumentation wait start event. @param state data storage for the locker @param file the source file name @param line the source line number @return an idle locker, or NULL */ typedef struct PSI_idle_locker* (*start_idle_wait_v1_t) (struct PSI_idle_locker_state_v1 *state, const char *src_file, uint src_line); /** Record an idle instrumentation wait end event. @param locker a thread locker for the running thread */ typedef void (*end_idle_wait_v1_t) (struct PSI_idle_locker *locker); /** Record a mutex instrumentation wait start event. @param state data storage for the locker @param mutex the instrumented mutex to lock @param op the operation to perform @param file the source file name @param line the source line number @return a mutex locker, or NULL */ typedef struct PSI_mutex_locker* (*start_mutex_wait_v1_t) (struct PSI_mutex_locker_state_v1 *state, struct PSI_mutex *mutex, enum PSI_mutex_operation op, const char *src_file, uint src_line); /** Record a mutex instrumentation wait end event. @param locker a thread locker for the running thread @param rc the wait operation return code */ typedef void (*end_mutex_wait_v1_t) (struct PSI_mutex_locker *locker, int rc); /** Record a rwlock instrumentation read wait start event. @param locker a thread locker for the running thread @param must must block: 1 for lock, 0 for trylock */ typedef struct PSI_rwlock_locker* (*start_rwlock_rdwait_v1_t) (struct PSI_rwlock_locker_state_v1 *state, struct PSI_rwlock *rwlock, enum PSI_rwlock_operation op, const char *src_file, uint src_line); /** Record a rwlock instrumentation read wait end event. @param locker a thread locker for the running thread @param rc the wait operation return code */ typedef void (*end_rwlock_rdwait_v1_t) (struct PSI_rwlock_locker *locker, int rc); /** Record a rwlock instrumentation write wait start event. @param locker a thread locker for the running thread @param must must block: 1 for lock, 0 for trylock */ typedef struct PSI_rwlock_locker* (*start_rwlock_wrwait_v1_t) (struct PSI_rwlock_locker_state_v1 *state, struct PSI_rwlock *rwlock, enum PSI_rwlock_operation op, const char *src_file, uint src_line); /** Record a rwlock instrumentation write wait end event. @param locker a thread locker for the running thread @param rc the wait operation return code */ typedef void (*end_rwlock_wrwait_v1_t) (struct PSI_rwlock_locker *locker, int rc); /** Record a condition instrumentation wait start event. @param locker a thread locker for the running thread @param must must block: 1 for wait, 0 for timedwait */ typedef struct PSI_cond_locker* (*start_cond_wait_v1_t) (struct PSI_cond_locker_state_v1 *state, struct PSI_cond *cond, struct PSI_mutex *mutex, enum PSI_cond_operation op, const char *src_file, uint src_line); /** Record a condition instrumentation wait end event. @param locker a thread locker for the running thread @param rc the wait operation return code */ typedef void (*end_cond_wait_v1_t) (struct PSI_cond_locker *locker, int rc); /** Record a table instrumentation io wait start event. @param locker a table locker for the running thread @param file the source file name @param line the source line number */ typedef struct PSI_table_locker* (*start_table_io_wait_v1_t) (struct PSI_table_locker_state *state, struct PSI_table *table, enum PSI_table_io_operation op, uint index, const char *src_file, uint src_line); /** Record a table instrumentation io wait end event. @param locker a table locker for the running thread @param numrows the number of rows involved in io */ typedef void (*end_table_io_wait_v1_t) (struct PSI_table_locker *locker, ulonglong numrows); /** Record a table instrumentation lock wait start event. @param locker a table locker for the running thread @param file the source file name @param line the source line number */ typedef struct PSI_table_locker* (*start_table_lock_wait_v1_t) (struct PSI_table_locker_state *state, struct PSI_table *table, enum PSI_table_lock_operation op, ulong flags, const char *src_file, uint src_line); /** Record a table instrumentation lock wait end event. @param locker a table locker for the running thread */ typedef void (*end_table_lock_wait_v1_t)(struct PSI_table_locker *locker); typedef void (*unlock_table_v1_t)(struct PSI_table *table); /** Start a file instrumentation open operation. @param locker the file locker @param op the operation to perform @param src_file the source file name @param src_line the source line number */ typedef void (*start_file_open_wait_v1_t) (struct PSI_file_locker *locker, const char *src_file, uint src_line); /** End a file instrumentation open operation, for file streams. @param locker the file locker. @param result the opened file (NULL indicates failure, non NULL success). @return an instrumented file handle */ typedef struct PSI_file* (*end_file_open_wait_v1_t) (struct PSI_file_locker *locker, void *result); /** End a file instrumentation open operation, for non stream files. @param locker the file locker. @param file the file number assigned by open() or create() for this file. */ typedef void (*end_file_open_wait_and_bind_to_descriptor_v1_t) (struct PSI_file_locker *locker, File file); /** End a file instrumentation open operation, for non stream temporary files. @param locker the file locker. @param file the file number assigned by open() or create() for this file. @param filename the file name generated during temporary file creation. */ typedef void (*end_temp_file_open_wait_and_bind_to_descriptor_v1_t) (struct PSI_file_locker *locker, File file, const char *filename); /** Record a file instrumentation start event. @param locker a file locker for the running thread @param op file operation to be performed @param count the number of bytes requested, or 0 if not applicable @param src_file the source file name @param src_line the source line number */ typedef void (*start_file_wait_v1_t) (struct PSI_file_locker *locker, size_t count, const char *src_file, uint src_line); /** Record a file instrumentation end event. Note that for file close operations, the instrumented file handle associated with the file (which was provided to obtain a locker) is invalid after this call. @param locker a file locker for the running thread @param count the number of bytes actually used in the operation, or 0 if not applicable, or -1 if the operation failed @sa get_thread_file_name_locker @sa get_thread_file_stream_locker @sa get_thread_file_descriptor_locker */ typedef void (*end_file_wait_v1_t) (struct PSI_file_locker *locker, size_t count); /** Start a file instrumentation close operation. @param locker the file locker @param op the operation to perform @param src_file the source file name @param src_line the source line number */ typedef void (*start_file_close_wait_v1_t) (struct PSI_file_locker *locker, const char *src_file, uint src_line); /** End a file instrumentation close operation. @param locker the file locker. @param rc the close operation return code (0 for success). @return an instrumented file handle */ typedef void (*end_file_close_wait_v1_t) (struct PSI_file_locker *locker, int rc); /** Start a new stage, and implicitly end the previous stage. @param key the key of the new stage @param src_file the source file name @param src_line the source line number @return the new stage progress */ typedef PSI_stage_progress* (*start_stage_v1_t) (PSI_stage_key key, const char *src_file, int src_line); typedef PSI_stage_progress* (*get_current_stage_progress_v1_t)(void); /** End the current stage. */ typedef void (*end_stage_v1_t) (void); /** Get a statement instrumentation locker. @param state data storage for the locker @param key the statement instrumentation key @param charset client character set @return a statement locker, or NULL */ typedef struct PSI_statement_locker* (*get_thread_statement_locker_v1_t) (struct PSI_statement_locker_state_v1 *state, PSI_statement_key key, const void *charset, PSI_sp_share *sp_share); /** Refine a statement locker to a more specific key. Note that only events declared mutable can be refined. @param the statement locker for the current event @param key the new key for the event @sa PSI_FLAG_MUTABLE */ typedef struct PSI_statement_locker* (*refine_statement_v1_t) (struct PSI_statement_locker *locker, PSI_statement_key key); /** Start a new statement event. @param locker the statement locker for this event @param db the active database name for this statement @param db_length the active database name length for this statement @param src_file source file name @param src_line source line number */ typedef void (*start_statement_v1_t) (struct PSI_statement_locker *locker, const char *db, uint db_length, const char *src_file, uint src_line); /** Set the statement text for a statement event. @param locker the current statement locker @param text the statement text @param text_len the statement text length */ typedef void (*set_statement_text_v1_t) (struct PSI_statement_locker *locker, const char *text, uint text_len); /** Set a statement event lock time. @param locker the statement locker @param lock_time the locked time, in microseconds */ typedef void (*set_statement_lock_time_t) (struct PSI_statement_locker *locker, ulonglong lock_time); /** Set a statement event rows sent metric. @param locker the statement locker @param count the number of rows sent */ typedef void (*set_statement_rows_sent_t) (struct PSI_statement_locker *locker, ulonglong count); /** Set a statement event rows examined metric. @param locker the statement locker @param count the number of rows examined */ typedef void (*set_statement_rows_examined_t) (struct PSI_statement_locker *locker, ulonglong count); /** Increment a statement event "created tmp disk tables" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_created_tmp_disk_tables_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "created tmp tables" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_created_tmp_tables_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select full join" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_full_join_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select full range join" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_full_range_join_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select range join" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_range_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select range check" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_range_check_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select scan" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_scan_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "sort merge passes" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_sort_merge_passes_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "sort range" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_sort_range_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "sort rows" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_sort_rows_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "sort scan" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_sort_scan_t) (struct PSI_statement_locker *locker, ulong count); /** Set a statement event "no index used" metric. @param locker the statement locker @param count the metric value */ typedef void (*set_statement_no_index_used_t) (struct PSI_statement_locker *locker); /** Set a statement event "no good index used" metric. @param locker the statement locker @param count the metric value */ typedef void (*set_statement_no_good_index_used_t) (struct PSI_statement_locker *locker); /** End a statement event. @param locker the statement locker @param stmt_da the statement diagnostics area. @sa Diagnostics_area */ typedef void (*end_statement_v1_t) (struct PSI_statement_locker *locker, void *stmt_da); /** Get a transaction instrumentation locker. @param state data storage for the locker @param xid the xid for this transaction @param trxid the InnoDB transaction id @param iso_level isolation level for this transaction @param read_only true if transaction access mode is read-only @param autocommit true if transaction is autocommit @return a transaction locker, or NULL */ typedef struct PSI_transaction_locker* (*get_thread_transaction_locker_v1_t) (struct PSI_transaction_locker_state_v1 *state, const void *xid, const ulonglong *trxid, int isolation_level, my_bool read_only, my_bool autocommit); /** Start a new transaction event. @param locker the transaction locker for this event @param src_file source file name @param src_line source line number */ typedef void (*start_transaction_v1_t) (struct PSI_transaction_locker *locker, const char *src_file, uint src_line); /** Set the transaction xid. @param locker the transaction locker for this event @param xid the id of the XA transaction #param xa_state is the state of the XA transaction */ typedef void (*set_transaction_xid_v1_t) (struct PSI_transaction_locker *locker, const void *xid, int xa_state); /** Set the state of the XA transaction. @param locker the transaction locker for this event @param xa_state the new state of the xa transaction */ typedef void (*set_transaction_xa_state_v1_t) (struct PSI_transaction_locker *locker, int xa_state); /** Set the transaction gtid. @param locker the transaction locker for this event @param sid the source id for the transaction, mapped from sidno @param gtid_spec the gtid specifier for the transaction */ typedef void (*set_transaction_gtid_v1_t) (struct PSI_transaction_locker *locker, const void *sid, const void *gtid_spec); /** Set the transaction trx_id. @param locker the transaction locker for this event @param trxid the storage engine transaction ID */ typedef void (*set_transaction_trxid_v1_t) (struct PSI_transaction_locker *locker, const ulonglong *trxid); /** Increment a transaction event savepoint count. @param locker the transaction locker @param count the increment value */ typedef void (*inc_transaction_savepoints_v1_t) (struct PSI_transaction_locker *locker, ulong count); /** Increment a transaction event rollback to savepoint count. @param locker the transaction locker @param count the increment value */ typedef void (*inc_transaction_rollback_to_savepoint_v1_t) (struct PSI_transaction_locker *locker, ulong count); /** Increment a transaction event release savepoint count. @param locker the transaction locker @param count the increment value */ typedef void (*inc_transaction_release_savepoint_v1_t) (struct PSI_transaction_locker *locker, ulong count); /** Commit or rollback the transaction. @param locker the transaction locker for this event @param commit true if transaction was committed, false if rolled back */ typedef void (*end_transaction_v1_t) (struct PSI_transaction_locker *locker, my_bool commit); /** Record a socket instrumentation start event. @param locker a socket locker for the running thread @param op socket operation to be performed @param count the number of bytes requested, or 0 if not applicable @param src_file the source file name @param src_line the source line number */ typedef struct PSI_socket_locker* (*start_socket_wait_v1_t) (struct PSI_socket_locker_state_v1 *state, struct PSI_socket *socket, enum PSI_socket_operation op, size_t count, const char *src_file, uint src_line); /** Record a socket instrumentation end event. Note that for socket close operations, the instrumented socket handle associated with the socket (which was provided to obtain a locker) is invalid after this call. @param locker a socket locker for the running thread @param count the number of bytes actually used in the operation, or 0 if not applicable, or -1 if the operation failed @sa get_thread_socket_locker */ typedef void (*end_socket_wait_v1_t) (struct PSI_socket_locker *locker, size_t count); /** Set the socket state for an instrumented socket. @param socket the instrumented socket @param state socket state */ typedef void (*set_socket_state_v1_t)(struct PSI_socket *socket, enum PSI_socket_state state); /** Set the socket info for an instrumented socket. @param socket the instrumented socket @param fd the socket descriptor @param addr the socket ip address @param addr_len length of socket ip address @param thread_id associated thread id */ typedef void (*set_socket_info_v1_t)(struct PSI_socket *socket, const my_socket *fd, const struct sockaddr *addr, socklen_t addr_len); /** Bind a socket to the thread that owns it. @param socket instrumented socket */ typedef void (*set_socket_thread_owner_v1_t)(struct PSI_socket *socket); /** Get a prepare statement. @param locker a statement locker for the running thread. */ typedef PSI_prepared_stmt* (*create_prepared_stmt_v1_t) (void *identity, uint stmt_id, PSI_statement_locker *locker, const char *stmt_name, size_t stmt_name_length, const char *name, size_t length); /** destroy a prepare statement. @param prepared_stmt prepared statement. */ typedef void (*destroy_prepared_stmt_v1_t) (PSI_prepared_stmt *prepared_stmt); /** repreare a prepare statement. @param prepared_stmt prepared statement. */ typedef void (*reprepare_prepared_stmt_v1_t) (PSI_prepared_stmt *prepared_stmt); /** Record a prepare statement instrumentation execute event. @param locker a statement locker for the running thread. @param prepared_stmt prepared statement. */ typedef void (*execute_prepared_stmt_v1_t) (PSI_statement_locker *locker, PSI_prepared_stmt* prepared_stmt); /** Get a digest locker for the current statement. @param locker a statement locker for the running thread */ typedef struct PSI_digest_locker * (*digest_start_v1_t) (struct PSI_statement_locker *locker); /** Add a token to the current digest instrumentation. @param locker a digest locker for the current statement @param token the lexical token to add @param yylval the lexical token attributes */ typedef void (*digest_end_v1_t) (struct PSI_digest_locker *locker, const struct sql_digest_storage *digest); typedef PSI_sp_locker* (*start_sp_v1_t) (struct PSI_sp_locker_state_v1 *state, struct PSI_sp_share* sp_share); typedef void (*end_sp_v1_t) (struct PSI_sp_locker *locker); typedef void (*drop_sp_v1_t) (uint object_type, const char *schema_name, uint schema_name_length, const char *object_name, uint object_name_length); /** Acquire a sp share instrumentation. @param type of stored program @param schema name of stored program @param name of stored program @return a stored program share instrumentation, or NULL */ typedef struct PSI_sp_share* (*get_sp_share_v1_t) (uint object_type, const char *schema_name, uint schema_name_length, const char *object_name, uint object_name_length); /** Release a stored program share. @param info the stored program share to release */ typedef void (*release_sp_share_v1_t)(struct PSI_sp_share *share); typedef PSI_metadata_lock* (*create_metadata_lock_v1_t) (void *identity, const MDL_key *key, opaque_mdl_type mdl_type, opaque_mdl_duration mdl_duration, opaque_mdl_status mdl_status, const char *src_file, uint src_line); typedef void (*set_metadata_lock_status_v1_t)(PSI_metadata_lock *lock, opaque_mdl_status mdl_status); typedef void (*destroy_metadata_lock_v1_t)(PSI_metadata_lock *lock); typedef struct PSI_metadata_locker* (*start_metadata_wait_v1_t) (struct PSI_metadata_locker_state_v1 *state, struct PSI_metadata_lock *mdl, const char *src_file, uint src_line); typedef void (*end_metadata_wait_v1_t) (struct PSI_metadata_locker *locker, int rc); /** Stores an array of connection attributes @param buffer char array of length encoded connection attributes in network format @param length length of the data in buffer @param from_cs charset in which @c buffer is encoded @return state @retval non_0 attributes truncated @retval 0 stored the attribute */ typedef int (*set_thread_connect_attrs_v1_t)(const char *buffer, uint length, const void *from_cs); /** Performance Schema Interface, version 1. @since PSI_VERSION_1 */ struct PSI_v1 { /** @sa register_mutex_v1_t. */ register_mutex_v1_t register_mutex; /** @sa register_rwlock_v1_t. */ register_rwlock_v1_t register_rwlock; /** @sa register_cond_v1_t. */ register_cond_v1_t register_cond; /** @sa register_thread_v1_t. */ register_thread_v1_t register_thread; /** @sa register_file_v1_t. */ register_file_v1_t register_file; /** @sa register_stage_v1_t. */ register_stage_v1_t register_stage; /** @sa register_statement_v1_t. */ register_statement_v1_t register_statement; /** @sa register_socket_v1_t. */ register_socket_v1_t register_socket; /** @sa init_mutex_v1_t. */ init_mutex_v1_t init_mutex; /** @sa destroy_mutex_v1_t. */ destroy_mutex_v1_t destroy_mutex; /** @sa init_rwlock_v1_t. */ init_rwlock_v1_t init_rwlock; /** @sa destroy_rwlock_v1_t. */ destroy_rwlock_v1_t destroy_rwlock; /** @sa init_cond_v1_t. */ init_cond_v1_t init_cond; /** @sa destroy_cond_v1_t. */ destroy_cond_v1_t destroy_cond; /** @sa init_socket_v1_t. */ init_socket_v1_t init_socket; /** @sa destroy_socket_v1_t. */ destroy_socket_v1_t destroy_socket; /** @sa get_table_share_v1_t. */ get_table_share_v1_t get_table_share; /** @sa release_table_share_v1_t. */ release_table_share_v1_t release_table_share; /** @sa drop_table_share_v1_t. */ drop_table_share_v1_t drop_table_share; /** @sa open_table_v1_t. */ open_table_v1_t open_table; /** @sa unbind_table_v1_t. */ unbind_table_v1_t unbind_table; /** @sa rebind_table_v1_t. */ rebind_table_v1_t rebind_table; /** @sa close_table_v1_t. */ close_table_v1_t close_table; /** @sa create_file_v1_t. */ create_file_v1_t create_file; /** @sa spawn_thread_v1_t. */ spawn_thread_v1_t spawn_thread; /** @sa new_thread_v1_t. */ new_thread_v1_t new_thread; /** @sa set_thread_id_v1_t. */ set_thread_id_v1_t set_thread_id; /** @sa set_thread_THD_v1_t. */ set_thread_THD_v1_t set_thread_THD; /** @sa set_thread_os_id_v1_t. */ set_thread_os_id_v1_t set_thread_os_id; /** @sa get_thread_v1_t. */ get_thread_v1_t get_thread; /** @sa set_thread_user_v1_t. */ set_thread_user_v1_t set_thread_user; /** @sa set_thread_account_v1_t. */ set_thread_account_v1_t set_thread_account; /** @sa set_thread_db_v1_t. */ set_thread_db_v1_t set_thread_db; /** @sa set_thread_command_v1_t. */ set_thread_command_v1_t set_thread_command; /** @sa set_connection_type_v1_t. */ set_connection_type_v1_t set_connection_type; /** @sa set_thread_start_time_v1_t. */ set_thread_start_time_v1_t set_thread_start_time; /** @sa set_thread_state_v1_t. */ set_thread_state_v1_t set_thread_state; /** @sa set_thread_info_v1_t. */ set_thread_info_v1_t set_thread_info; /** @sa set_thread_v1_t. */ set_thread_v1_t set_thread; /** @sa delete_current_thread_v1_t. */ delete_current_thread_v1_t delete_current_thread; /** @sa delete_thread_v1_t. */ delete_thread_v1_t delete_thread; /** @sa get_thread_file_name_locker_v1_t. */ get_thread_file_name_locker_v1_t get_thread_file_name_locker; /** @sa get_thread_file_stream_locker_v1_t. */ get_thread_file_stream_locker_v1_t get_thread_file_stream_locker; /** @sa get_thread_file_descriptor_locker_v1_t. */ get_thread_file_descriptor_locker_v1_t get_thread_file_descriptor_locker; /** @sa unlock_mutex_v1_t. */ unlock_mutex_v1_t unlock_mutex; /** @sa unlock_rwlock_v1_t. */ unlock_rwlock_v1_t unlock_rwlock; /** @sa signal_cond_v1_t. */ signal_cond_v1_t signal_cond; /** @sa broadcast_cond_v1_t. */ broadcast_cond_v1_t broadcast_cond; /** @sa start_idle_wait_v1_t. */ start_idle_wait_v1_t start_idle_wait; /** @sa end_idle_wait_v1_t. */ end_idle_wait_v1_t end_idle_wait; /** @sa start_mutex_wait_v1_t. */ start_mutex_wait_v1_t start_mutex_wait; /** @sa end_mutex_wait_v1_t. */ end_mutex_wait_v1_t end_mutex_wait; /** @sa start_rwlock_rdwait_v1_t. */ start_rwlock_rdwait_v1_t start_rwlock_rdwait; /** @sa end_rwlock_rdwait_v1_t. */ end_rwlock_rdwait_v1_t end_rwlock_rdwait; /** @sa start_rwlock_wrwait_v1_t. */ start_rwlock_wrwait_v1_t start_rwlock_wrwait; /** @sa end_rwlock_wrwait_v1_t. */ end_rwlock_wrwait_v1_t end_rwlock_wrwait; /** @sa start_cond_wait_v1_t. */ start_cond_wait_v1_t start_cond_wait; /** @sa end_cond_wait_v1_t. */ end_cond_wait_v1_t end_cond_wait; /** @sa start_table_io_wait_v1_t. */ start_table_io_wait_v1_t start_table_io_wait; /** @sa end_table_io_wait_v1_t. */ end_table_io_wait_v1_t end_table_io_wait; /** @sa start_table_lock_wait_v1_t. */ start_table_lock_wait_v1_t start_table_lock_wait; /** @sa end_table_lock_wait_v1_t. */ end_table_lock_wait_v1_t end_table_lock_wait; /** @sa start_file_open_wait_v1_t. */ start_file_open_wait_v1_t start_file_open_wait; /** @sa end_file_open_wait_v1_t. */ end_file_open_wait_v1_t end_file_open_wait; /** @sa end_file_open_wait_and_bind_to_descriptor_v1_t. */ end_file_open_wait_and_bind_to_descriptor_v1_t end_file_open_wait_and_bind_to_descriptor; /** @sa end_temp_file_open_wait_and_bind_to_descriptor_v1_t. */ end_temp_file_open_wait_and_bind_to_descriptor_v1_t end_temp_file_open_wait_and_bind_to_descriptor; /** @sa start_file_wait_v1_t. */ start_file_wait_v1_t start_file_wait; /** @sa end_file_wait_v1_t. */ end_file_wait_v1_t end_file_wait; /** @sa start_file_close_wait_v1_t. */ start_file_close_wait_v1_t start_file_close_wait; /** @sa end_file_close_wait_v1_t. */ end_file_close_wait_v1_t end_file_close_wait; /** @sa start_stage_v1_t. */ start_stage_v1_t start_stage; /** @sa get_current_stage_progress_v1_t. */ get_current_stage_progress_v1_t get_current_stage_progress; /** @sa end_stage_v1_t. */ end_stage_v1_t end_stage; /** @sa get_thread_statement_locker_v1_t. */ get_thread_statement_locker_v1_t get_thread_statement_locker; /** @sa refine_statement_v1_t. */ refine_statement_v1_t refine_statement; /** @sa start_statement_v1_t. */ start_statement_v1_t start_statement; /** @sa set_statement_text_v1_t. */ set_statement_text_v1_t set_statement_text; /** @sa set_statement_lock_time_t. */ set_statement_lock_time_t set_statement_lock_time; /** @sa set_statement_rows_sent_t. */ set_statement_rows_sent_t set_statement_rows_sent; /** @sa set_statement_rows_examined_t. */ set_statement_rows_examined_t set_statement_rows_examined; /** @sa inc_statement_created_tmp_disk_tables. */ inc_statement_created_tmp_disk_tables_t inc_statement_created_tmp_disk_tables; /** @sa inc_statement_created_tmp_tables. */ inc_statement_created_tmp_tables_t inc_statement_created_tmp_tables; /** @sa inc_statement_select_full_join. */ inc_statement_select_full_join_t inc_statement_select_full_join; /** @sa inc_statement_select_full_range_join. */ inc_statement_select_full_range_join_t inc_statement_select_full_range_join; /** @sa inc_statement_select_range. */ inc_statement_select_range_t inc_statement_select_range; /** @sa inc_statement_select_range_check. */ inc_statement_select_range_check_t inc_statement_select_range_check; /** @sa inc_statement_select_scan. */ inc_statement_select_scan_t inc_statement_select_scan; /** @sa inc_statement_sort_merge_passes. */ inc_statement_sort_merge_passes_t inc_statement_sort_merge_passes; /** @sa inc_statement_sort_range. */ inc_statement_sort_range_t inc_statement_sort_range; /** @sa inc_statement_sort_rows. */ inc_statement_sort_rows_t inc_statement_sort_rows; /** @sa inc_statement_sort_scan. */ inc_statement_sort_scan_t inc_statement_sort_scan; /** @sa set_statement_no_index_used. */ set_statement_no_index_used_t set_statement_no_index_used; /** @sa set_statement_no_good_index_used. */ set_statement_no_good_index_used_t set_statement_no_good_index_used; /** @sa end_statement_v1_t. */ end_statement_v1_t end_statement; /** @sa get_thread_transaction_locker_v1_t. */ get_thread_transaction_locker_v1_t get_thread_transaction_locker; /** @sa start_transaction_v1_t. */ start_transaction_v1_t start_transaction; /** @sa set_transaction_xid_v1_t. */ set_transaction_xid_v1_t set_transaction_xid; /** @sa set_transaction_xa_state_v1_t. */ set_transaction_xa_state_v1_t set_transaction_xa_state; /** @sa set_transaction_gtid_v1_t. */ set_transaction_gtid_v1_t set_transaction_gtid; /** @sa set_transaction_trxid_v1_t. */ set_transaction_trxid_v1_t set_transaction_trxid; /** @sa inc_transaction_savepoints_v1_t. */ inc_transaction_savepoints_v1_t inc_transaction_savepoints; /** @sa inc_transaction_rollback_to_savepoint_v1_t. */ inc_transaction_rollback_to_savepoint_v1_t inc_transaction_rollback_to_savepoint; /** @sa inc_transaction_release_savepoint_v1_t. */ inc_transaction_release_savepoint_v1_t inc_transaction_release_savepoint; /** @sa end_transaction_v1_t. */ end_transaction_v1_t end_transaction; /** @sa start_socket_wait_v1_t. */ start_socket_wait_v1_t start_socket_wait; /** @sa end_socket_wait_v1_t. */ end_socket_wait_v1_t end_socket_wait; /** @sa set_socket_state_v1_t. */ set_socket_state_v1_t set_socket_state; /** @sa set_socket_info_v1_t. */ set_socket_info_v1_t set_socket_info; /** @sa set_socket_thread_owner_v1_t. */ set_socket_thread_owner_v1_t set_socket_thread_owner; /** @sa create_prepared_stmt_v1_t. */ create_prepared_stmt_v1_t create_prepared_stmt; /** @sa destroy_prepared_stmt_v1_t. */ destroy_prepared_stmt_v1_t destroy_prepared_stmt; /** @sa reprepare_prepared_stmt_v1_t. */ reprepare_prepared_stmt_v1_t reprepare_prepared_stmt; /** @sa execute_prepared_stmt_v1_t. */ execute_prepared_stmt_v1_t execute_prepared_stmt; /** @sa digest_start_v1_t. */ digest_start_v1_t digest_start; /** @sa digest_end_v1_t. */ digest_end_v1_t digest_end; /** @sa set_thread_connect_attrs_v1_t. */ set_thread_connect_attrs_v1_t set_thread_connect_attrs; /** @sa start_sp_v1_t. */ start_sp_v1_t start_sp; /** @sa start_sp_v1_t. */ end_sp_v1_t end_sp; /** @sa drop_sp_v1_t. */ drop_sp_v1_t drop_sp; /** @sa get_sp_share_v1_t. */ get_sp_share_v1_t get_sp_share; /** @sa release_sp_share_v1_t. */ release_sp_share_v1_t release_sp_share; /** @sa register_memory_v1_t. */ register_memory_v1_t register_memory; /** @sa memory_alloc_v1_t. */ memory_alloc_v1_t memory_alloc; /** @sa memory_realloc_v1_t. */ memory_realloc_v1_t memory_realloc; /** @sa memory_claim_v1_t. */ memory_claim_v1_t memory_claim; /** @sa memory_free_v1_t. */ memory_free_v1_t memory_free; unlock_table_v1_t unlock_table; create_metadata_lock_v1_t create_metadata_lock; set_metadata_lock_status_v1_t set_metadata_lock_status; destroy_metadata_lock_v1_t destroy_metadata_lock; start_metadata_wait_v1_t start_metadata_wait; end_metadata_wait_v1_t end_metadata_wait; }; /** @} (end of group Group_PSI_v1) */ #endif /* HAVE_PSI_1 */ #ifdef USE_PSI_2 #define HAVE_PSI_2 #endif #ifdef HAVE_PSI_2 /** @defgroup Group_PSI_v2 Application Binary Interface, version 2 @ingroup Instrumentation_interface @{ */ /** Performance Schema Interface, version 2. This is a placeholder, this interface is not defined yet. @since PSI_VERSION_2 */ struct PSI_v2 { /** Placeholder */ int placeholder; /* ... extended interface ... */ }; /** Placeholder */ struct PSI_mutex_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_rwlock_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_cond_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_thread_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_file_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_stage_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_statement_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_transaction_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_idle_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_mutex_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_rwlock_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_cond_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_file_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_statement_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_transaction_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_socket_locker_state_v2 { /** Placeholder */ int placeholder; }; struct PSI_metadata_locker_state_v2 { int placeholder; }; /** @} (end of group Group_PSI_v2) */ #endif /* HAVE_PSI_2 */ /** @typedef PSI The instrumentation interface for the current version. @sa PSI_CURRENT_VERSION */ /** @typedef PSI_mutex_info The mutex information structure for the current version. */ /** @typedef PSI_rwlock_info The rwlock information structure for the current version. */ /** @typedef PSI_cond_info The cond information structure for the current version. */ /** @typedef PSI_thread_info The thread information structure for the current version. */ /** @typedef PSI_file_info The file information structure for the current version. */ /* Export the required version */ #ifdef USE_PSI_1 typedef struct PSI_v1 PSI; typedef struct PSI_mutex_info_v1 PSI_mutex_info; typedef struct PSI_rwlock_info_v1 PSI_rwlock_info; typedef struct PSI_cond_info_v1 PSI_cond_info; typedef struct PSI_thread_info_v1 PSI_thread_info; typedef struct PSI_file_info_v1 PSI_file_info; typedef struct PSI_stage_info_v1 PSI_stage_info; typedef struct PSI_statement_info_v1 PSI_statement_info; typedef struct PSI_transaction_info_v1 PSI_transaction_info; typedef struct PSI_socket_info_v1 PSI_socket_info; typedef struct PSI_idle_locker_state_v1 PSI_idle_locker_state; typedef struct PSI_mutex_locker_state_v1 PSI_mutex_locker_state; typedef struct PSI_rwlock_locker_state_v1 PSI_rwlock_locker_state; typedef struct PSI_cond_locker_state_v1 PSI_cond_locker_state; typedef struct PSI_file_locker_state_v1 PSI_file_locker_state; typedef struct PSI_statement_locker_state_v1 PSI_statement_locker_state; typedef struct PSI_transaction_locker_state_v1 PSI_transaction_locker_state; typedef struct PSI_socket_locker_state_v1 PSI_socket_locker_state; typedef struct PSI_sp_locker_state_v1 PSI_sp_locker_state; typedef struct PSI_metadata_locker_state_v1 PSI_metadata_locker_state; #endif #ifdef USE_PSI_2 typedef struct PSI_v2 PSI; typedef struct PSI_mutex_info_v2 PSI_mutex_info; typedef struct PSI_rwlock_info_v2 PSI_rwlock_info; typedef struct PSI_cond_info_v2 PSI_cond_info; typedef struct PSI_thread_info_v2 PSI_thread_info; typedef struct PSI_file_info_v2 PSI_file_info; typedef struct PSI_stage_info_v2 PSI_stage_info; typedef struct PSI_statement_info_v2 PSI_statement_info; typedef struct PSI_transaction_info_v2 PSI_transaction_info; typedef struct PSI_socket_info_v2 PSI_socket_info; typedef struct PSI_idle_locker_state_v2 PSI_idle_locker_state; typedef struct PSI_mutex_locker_state_v2 PSI_mutex_locker_state; typedef struct PSI_rwlock_locker_state_v2 PSI_rwlock_locker_state; typedef struct PSI_cond_locker_state_v2 PSI_cond_locker_state; typedef struct PSI_file_locker_state_v2 PSI_file_locker_state; typedef struct PSI_statement_locker_state_v2 PSI_statement_locker_state; typedef struct PSI_transaction_locker_state_v2 PSI_transaction_locker_state; typedef struct PSI_socket_locker_state_v2 PSI_socket_locker_state; typedef struct PSI_sp_locker_state_v2 PSI_sp_locker_state; typedef struct PSI_metadata_locker_state_v2 PSI_metadata_locker_state; #endif #else /* HAVE_PSI_INTERFACE */ /** Dummy structure, used to declare PSI_server when no instrumentation is available. The content does not matter, since PSI_server will be NULL. */ struct PSI_none { int opaque; }; typedef struct PSI_none PSI; /** Stage instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented stage. */ struct PSI_stage_info_none { /** Unused stage key. */ unsigned int m_key; /** The name of the stage instrument. */ const char *m_name; /** Unused stage flags. */ int m_flags; }; /** The stage instrumentation has to co exist with the legacy THD::set_proc_info instrumentation. To avoid duplication of the instrumentation in the server, the common PSI_stage_info structure is used, so we export it here, even when not building with HAVE_PSI_INTERFACE. */ typedef struct PSI_stage_info_none PSI_stage_info; #endif /* HAVE_PSI_INTERFACE */ extern MYSQL_PLUGIN_IMPORT PSI *PSI_server; /* Allow to override PSI_XXX_CALL at compile time with more efficient implementations, if available. If nothing better is available, make a dynamic call using the PSI_server function pointer. */ #define PSI_DYNAMIC_CALL(M) PSI_server->M /** @} */ C_MODE_END #endif /* MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H */
[ "micahelluthor@163.com" ]
micahelluthor@163.com
784f01ddd93fef26d2e336012bc8879e097ea2bb
777299f9f20b5c1dc930766809b336f5c1ae38e5
/tests/framework/layer/wrap_objects.cpp
8f617a6d330734672d723ed97e944efe96f666ed
[ "Apache-2.0" ]
permissive
chaoticbob/Vulkan-Loader
3c3b0e0ef2c9fbd865c49abae198e4ab840a684f
d5bb7a92160cf34e81ed39d3454c65024cdf09ea
refs/heads/master
2023-08-30T15:20:54.664460
2021-10-27T16:21:10
2021-11-04T21:01:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,692
cpp
/* * Copyright (c) 2015-2021 Valve Corporation * Copyright (c) 2015-2021 LunarG, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: Jon Ashburn <jon@lunarg.com> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <unordered_map> #include <memory> #include "vulkan/vk_layer.h" #include "loader/generated/vk_dispatch_table_helper.h" #include "loader/vk_loader_layer.h" #if !defined(VK_LAYER_EXPORT) #if defined(__GNUC__) && __GNUC__ >= 4 #define VK_LAYER_EXPORT __attribute__((visibility("default"))) #elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590) #define VK_LAYER_EXPORT __attribute__((visibility("default"))) #else #define VK_LAYER_EXPORT #endif #endif struct wrapped_phys_dev_obj { VkLayerInstanceDispatchTable *loader_disp; struct wrapped_inst_obj *inst; // parent instance object void *obj; }; struct wrapped_inst_obj { VkLayerInstanceDispatchTable *loader_disp; VkLayerInstanceDispatchTable layer_disp; // this layer's dispatch table PFN_vkSetInstanceLoaderData pfn_inst_init; struct wrapped_phys_dev_obj *ptr_phys_devs; // any enumerated phys devs VkInstance obj; }; struct wrapped_dev_obj { VkLayerDispatchTable *disp; VkLayerInstanceDispatchTable *layer_disp; // TODO use this PFN_vkSetDeviceLoaderData pfn_dev_init; // TODO use this void *obj; }; // typedef std::unordered_map<void *, VkLayerDispatchTable *> device_table_map; // typedef std::unordered_map<void *, VkLayerInstanceDispatchTable *> instance_table_map; typedef void *dispatch_key; VkInstance unwrap_instance(const VkInstance instance, wrapped_inst_obj **inst) { *inst = reinterpret_cast<wrapped_inst_obj *>(instance); return (*inst)->obj; } VkPhysicalDevice unwrap_phys_dev(const VkPhysicalDevice physical_device, wrapped_phys_dev_obj **phys_dev) { *phys_dev = reinterpret_cast<wrapped_phys_dev_obj *>(physical_device); return reinterpret_cast<VkPhysicalDevice>((*phys_dev)->obj); } dispatch_key get_dispatch_key(const void *object) { return (dispatch_key) * (VkLayerDispatchTable **)object; } template <typename T> struct TableMap { using map_type = std::unordered_map<void *, std::unique_ptr<T>>; map_type map; template <typename U> T *get_table(U *object) { dispatch_key key = get_dispatch_key(object); typename map_type::const_iterator it = map.find(static_cast<void *>(key)); assert(it != map.end() && "Not able to find dispatch entry"); return it->second.get(); } void destroy_table(dispatch_key key) { typename map_type::const_iterator it = map.find(static_cast<void *>(key)); if (it != map.end()) { map.erase(it); } } VkLayerDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa) { dispatch_key key = get_dispatch_key(device); typename map_type::const_iterator it = map.find((void *)key); if (it == map.end()) { map[(void *)key] = std::unique_ptr<T>(new VkLayerDispatchTable); VkLayerDispatchTable *pTable = map.at((void *)key).get(); layer_init_device_dispatch_table(device, pTable, gpa); return pTable; } else { return it->second.get(); } } }; TableMap<VkLayerDispatchTable> device_map; VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func) { VkLayerInstanceCreateInfo *chain_info = (VkLayerInstanceCreateInfo *)pCreateInfo->pNext; while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && chain_info->function == func)) { chain_info = (VkLayerInstanceCreateInfo *)chain_info->pNext; } assert(chain_info != NULL); return chain_info; } VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func) { VkLayerDeviceCreateInfo *chain_info = (VkLayerDeviceCreateInfo *)pCreateInfo->pNext; while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && chain_info->function == func)) { chain_info = (VkLayerDeviceCreateInfo *)chain_info->pNext; } assert(chain_info != NULL); return chain_info; } namespace wrap_objects { static const VkLayerProperties global_layer = { "VK_LAYER_LUNARG_wrap_objects", VK_HEADER_VERSION_COMPLETE, 1, "LunarG Test Layer", }; uint32_t loader_layer_if_version = CURRENT_LOADER_LAYER_INTERFACE_VERSION; VKAPI_ATTR VkResult VKAPI_CALL wrap_vkCreateInstance(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkInstance *pInstance) { VkLayerInstanceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO); PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; PFN_vkCreateInstance fpCreateInstance = (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance"); if (fpCreateInstance == NULL) { return VK_ERROR_INITIALIZATION_FAILED; } // Advance the link info for the next element on the chain chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance); if (result != VK_SUCCESS) { return result; } auto inst = new wrapped_inst_obj; if (!inst) return VK_ERROR_OUT_OF_HOST_MEMORY; memset(inst, 0, sizeof(*inst)); inst->obj = (*pInstance); *pInstance = reinterpret_cast<VkInstance>(inst); // store the loader callback for initializing created dispatchable objects chain_info = get_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK); if (chain_info) { inst->pfn_inst_init = chain_info->u.pfnSetInstanceLoaderData; result = inst->pfn_inst_init(inst->obj, reinterpret_cast<void *>(inst)); if (VK_SUCCESS != result) return result; } else { inst->pfn_inst_init = NULL; inst->loader_disp = *(reinterpret_cast<VkLayerInstanceDispatchTable **>(*pInstance)); } layer_init_instance_dispatch_table(*pInstance, &inst->layer_disp, fpGetInstanceProcAddr); return result; } VKAPI_ATTR void VKAPI_CALL wrap_vkDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) { wrapped_inst_obj *inst; auto vk_inst = unwrap_instance(instance, &inst); VkLayerInstanceDispatchTable *pDisp = &inst->layer_disp; pDisp->DestroyInstance(vk_inst, pAllocator); if (inst->ptr_phys_devs) delete[] inst->ptr_phys_devs; delete inst; } VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDevices(VkInstance instance, uint32_t *pPhysicalDeviceCount, VkPhysicalDevice *pPhysicalDevices) { wrapped_inst_obj *inst; auto vk_inst = unwrap_instance(instance, &inst); VkResult result = inst->layer_disp.EnumeratePhysicalDevices(vk_inst, pPhysicalDeviceCount, pPhysicalDevices); if (VK_SUCCESS != result) return result; if (pPhysicalDevices != NULL) { assert(pPhysicalDeviceCount); auto phys_devs = new wrapped_phys_dev_obj[*pPhysicalDeviceCount]; if (!phys_devs) return VK_ERROR_OUT_OF_HOST_MEMORY; if (inst->ptr_phys_devs) delete[] inst->ptr_phys_devs; inst->ptr_phys_devs = phys_devs; for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) { if (inst->pfn_inst_init == NULL) { phys_devs[i].loader_disp = *(reinterpret_cast<VkLayerInstanceDispatchTable **>(pPhysicalDevices[i])); } else { result = inst->pfn_inst_init(vk_inst, reinterpret_cast<void *>(&phys_devs[i])); if (VK_SUCCESS != result) return result; } phys_devs[i].obj = reinterpret_cast<void *>(pPhysicalDevices[i]); phys_devs[i].inst = inst; pPhysicalDevices[i] = reinterpret_cast<VkPhysicalDevice>(&phys_devs[i]); } } return result; } VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties *pProperties) { wrapped_phys_dev_obj *phys_dev; auto vk_phys_dev = unwrap_phys_dev(physicalDevice, &phys_dev); phys_dev->inst->layer_disp.GetPhysicalDeviceProperties(vk_phys_dev, pProperties); } VKAPI_ATTR void VKAPI_CALL wrap_vkGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties *pQueueFamilyProperties) { wrapped_phys_dev_obj *phys_dev; auto vk_phys_dev = unwrap_phys_dev(physicalDevice, &phys_dev); phys_dev->inst->layer_disp.GetPhysicalDeviceQueueFamilyProperties(vk_phys_dev, pQueueFamilyPropertyCount, pQueueFamilyProperties); } VKAPI_ATTR VkResult VKAPI_CALL wrap_vkCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) { wrapped_phys_dev_obj *phys_dev; auto vk_phys_dev = unwrap_phys_dev(physicalDevice, &phys_dev); VkLayerDeviceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO); PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr; PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(phys_dev->inst->obj, "vkCreateDevice"); if (fpCreateDevice == NULL) { return VK_ERROR_INITIALIZATION_FAILED; } // Advance the link info for the next element on the chain chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; VkResult result = fpCreateDevice(vk_phys_dev, pCreateInfo, pAllocator, pDevice); if (result != VK_SUCCESS) { return result; } device_map.initDeviceTable(*pDevice, fpGetDeviceProcAddr); #if 0 // TODO add once device is wrapped // store the loader callback for initializing created dispatchable objects chain_info = get_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK); if (chain_info) { dev->pfn_dev_init = chain_info->u.pfnSetDeviceLoaderData; } else { dev->pfn_dev_init = NULL; } #endif return result; } VKAPI_ATTR void VKAPI_CALL wrap_vkDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) { dispatch_key key = get_dispatch_key(device); VkLayerDispatchTable *pDisp = device_map.get_table(device); pDisp->DestroyDevice(device, pAllocator); device_map.destroy_table(key); } VKAPI_ATTR VkResult VKAPI_CALL wrap_vkEnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice, const char *pLayerName, uint32_t *pPropertyCount, VkExtensionProperties *pProperties) { wrapped_phys_dev_obj *phys_dev; auto vk_phys_dev = unwrap_phys_dev(physicalDevice, &phys_dev); if (pLayerName && !strcmp(pLayerName, global_layer.layerName)) { *pPropertyCount = 0; return VK_SUCCESS; } return phys_dev->inst->layer_disp.EnumerateDeviceExtensionProperties(vk_phys_dev, pLayerName, pPropertyCount, pProperties); } PFN_vkVoidFunction layer_intercept_proc(const char *name) { if (!name || name[0] != 'v' || name[1] != 'k') return NULL; name += 2; if (!strcmp(name, "CreateInstance")) return (PFN_vkVoidFunction)wrap_vkCreateInstance; if (!strcmp(name, "DestroyInstance")) return (PFN_vkVoidFunction)wrap_vkDestroyInstance; if (!strcmp(name, "EnumeratePhysicalDevices")) return (PFN_vkVoidFunction)vkEnumeratePhysicalDevices; if (!strcmp(name, "GetPhysicalDeviceQueueFamilyProperties")) return (PFN_vkVoidFunction)wrap_vkGetPhysicalDeviceQueueFamilyProperties; if (!strcmp(name, "CreateDevice")) return (PFN_vkVoidFunction)wrap_vkCreateDevice; if (!strcmp(name, "DestroyDevice")) return (PFN_vkVoidFunction)wrap_vkDestroyDevice; return NULL; } PFN_vkVoidFunction layer_intercept_instance_proc(const char *name) { if (!name || name[0] != 'v' || name[1] != 'k') return NULL; name += 2; if (!strcmp(name, "GetInstanceProcAddr")) return (PFN_vkVoidFunction)wrap_vkCreateInstance; if (!strcmp(name, "DestroyInstance")) return (PFN_vkVoidFunction)wrap_vkDestroyInstance; if (!strcmp(name, "EnumeratePhysicalDevices")) return (PFN_vkVoidFunction)vkEnumeratePhysicalDevices; if (!strcmp(name, "GetPhysicalDeviceProperties")) return (PFN_vkVoidFunction)vkGetPhysicalDeviceProperties; if (!strcmp(name, "GetPhysicalDeviceQueueFamilyProperties")) return (PFN_vkVoidFunction)wrap_vkGetPhysicalDeviceQueueFamilyProperties; if (!strcmp(name, "EnumerateDeviceExtensionProperties")) return (PFN_vkVoidFunction)wrap_vkEnumerateDeviceExtensionProperties; return NULL; } VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL wrap_vkGetDeviceProcAddr(VkDevice device, const char *funcName) { PFN_vkVoidFunction addr; if (!strcmp("vkGetDeviceProcAddr", funcName)) { return (PFN_vkVoidFunction)wrap_vkGetDeviceProcAddr; } addr = layer_intercept_proc(funcName); if (addr) return addr; if (device == VK_NULL_HANDLE) { return NULL; } VkLayerDispatchTable *pDisp = device_map.get_table(device); if (pDisp->GetDeviceProcAddr == NULL) { return NULL; } return pDisp->GetDeviceProcAddr(device, funcName); } VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL wrap_vkGetInstanceProcAddr(VkInstance instance, const char *funcName) { PFN_vkVoidFunction addr; if (!strcmp(funcName, "vkCreateInstance")) return (PFN_vkVoidFunction)wrap_vkCreateInstance; if (!strcmp(funcName, "vkCreateDevice")) return (PFN_vkVoidFunction)wrap_vkCreateDevice; if (instance == VK_NULL_HANDLE) { return NULL; } addr = layer_intercept_instance_proc(funcName); if (addr) return addr; wrapped_inst_obj *inst; (void)unwrap_instance(instance, &inst); VkLayerInstanceDispatchTable *pTable = &inst->layer_disp; if (pTable->GetInstanceProcAddr == NULL) return NULL; return pTable->GetInstanceProcAddr(instance, funcName); } VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetPhysicalDeviceProcAddr(VkInstance instance, const char *funcName) { assert(instance); wrapped_inst_obj *inst; (void)unwrap_instance(instance, &inst); VkLayerInstanceDispatchTable *pTable = &inst->layer_disp; if (pTable->GetPhysicalDeviceProcAddr == NULL) return NULL; return pTable->GetPhysicalDeviceProcAddr(instance, funcName); } } // namespace wrap_objects extern "C" { // loader-layer interface v0, just wrappers since there is only a layer VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *funcName) { return wrap_objects::wrap_vkGetInstanceProcAddr(instance, funcName); } VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device, const char *funcName) { return wrap_objects::wrap_vkGetDeviceProcAddr(device, funcName); } VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pCount, VkExtensionProperties *pProperties) { assert(0); // TODO return wrap_objects::EnumerateInstanceExtensionProperties(pLayerName, pCount, pProperties); return VK_SUCCESS; } VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties(uint32_t *pCount, VkLayerProperties *pProperties) { assert(0); // TODO return wrap_objects::EnumerateInstanceLayerProperties(pCount, pProperties); return VK_SUCCESS; } VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice, const char *pLayerName, uint32_t *pCount, VkExtensionProperties *pProperties) { // the layer command handles VK_NULL_HANDLE just fine internally assert(physicalDevice == VK_NULL_HANDLE); return wrap_objects::wrap_vkEnumerateDeviceExtensionProperties(VK_NULL_HANDLE, pLayerName, pCount, pProperties); } VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_layerGetPhysicalDeviceProcAddr(VkInstance instance, const char *funcName) { return wrap_objects::GetPhysicalDeviceProcAddr(instance, funcName); } VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *pVersionStruct) { assert(pVersionStruct != NULL); assert(pVersionStruct->sType == LAYER_NEGOTIATE_INTERFACE_STRUCT); // Fill in the function pointers if our version is at least capable of having the structure contain them. if (pVersionStruct->loaderLayerInterfaceVersion >= 2) { pVersionStruct->pfnGetInstanceProcAddr = wrap_objects::wrap_vkGetInstanceProcAddr; pVersionStruct->pfnGetDeviceProcAddr = wrap_objects::wrap_vkGetDeviceProcAddr; pVersionStruct->pfnGetPhysicalDeviceProcAddr = vk_layerGetPhysicalDeviceProcAddr; } if (pVersionStruct->loaderLayerInterfaceVersion < CURRENT_LOADER_LAYER_INTERFACE_VERSION) { wrap_objects::loader_layer_if_version = pVersionStruct->loaderLayerInterfaceVersion; } else if (pVersionStruct->loaderLayerInterfaceVersion > CURRENT_LOADER_LAYER_INTERFACE_VERSION) { pVersionStruct->loaderLayerInterfaceVersion = CURRENT_LOADER_LAYER_INTERFACE_VERSION; } return VK_SUCCESS; } }
[ "46324611+charles-lunarg@users.noreply.github.com" ]
46324611+charles-lunarg@users.noreply.github.com
e688bf2595ac96c24261d24c192088650a07ca62
84f7b0f26c5ee871eb83322c2fac9f0de94eb98b
/src/splitting/breadth_first_splitter.cpp
ae14355ebe4ac406b05946f4dfbd53f93b775ebc
[ "BSD-3-Clause" ]
permissive
mfkiwl/srrg2-hipe
8b048729046ff1c3798a440555f4d77fec9d7071
d02bf13f63ffb7a4e35a77c595c921663e962750
refs/heads/main
2023-08-17T18:04:23.302808
2021-10-25T13:44:59
2021-10-25T13:44:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,456
cpp
#include "breadth_first_splitter.h" namespace srrg2_hipe { using namespace srrg2_core; using namespace srrg2_solver; BreadthFirstSplitter::BreadthFirstSplitter() : _init_action(new OdometryPropagation){ } const VariableBase* BreadthFirstSplitter::_computeOuterDegreeMap() { const auto& variables = _graph->variables(); int max_degree_pose = -1; const VariableBase* conditioner = nullptr; for (const auto& id_variable : variables) { VariableBase::Id id = id_variable.first; const VariableBase* v = id_variable.second; auto lower = _graph->lowerFactor(v); auto upper = _graph->upperFactor(v); int degree = std::distance(lower, upper); _variable_outer_degree_map[id] = degree; const VariableSE3Base* anchor_type_3d = dynamic_cast<const VariableSE3Base*>(v); if (!anchor_type_3d) { continue; } if (v->status() == VariableBase::Status::Fixed) { conditioner = v; max_degree_pose = std::numeric_limits<int>::max(); continue; } if (degree > max_degree_pose) { max_degree_pose = degree; conditioner = v; } } return conditioner; } void BreadthFirstSplitter::_determineAnchorAndCreatePartition( const VariablePtrVector& variables_, const FactorPtrVector& factors_, const VariableIdSet& boundary_variables_) { if (variables_.empty() || factors_.empty() || variables_.size() <= boundary_variables_.size()) { return; } int max_degree = -1; VariableBase::Id anchor_id = -1; for (const VariableBase* v : variables_) { if (boundary_variables_.count(v->graphId())) { continue; } auto lower = _graph->lowerFactor(v); auto upper = _graph->upperFactor(v); int degree = std::distance(lower, upper); const VariableSE3Base* anchor_type_3d = dynamic_cast<const VariableSE3Base*>(v); if (!anchor_type_3d) { continue; } if (v->status() == VariableBase::Status::Fixed) { anchor_id = v->graphId(); break; } if (degree > max_degree) { max_degree = degree; anchor_id = v->graphId(); } } if (anchor_id < 0) { return; } _manager->createPartition(variables_, factors_, anchor_id, boundary_variables_); } void BreadthFirstSplitter::_constructPartition(const VariableBase* root_, bool root_is_boundary) { // tg add root to variable deque std::deque<const VariableBase*> variable_deque; variable_deque.push_back(root_); // tg initialize quantity for partition creation VariablePtrVector variables; FactorPtrVector factors; VariableIdSet boundary_variables; if (root_is_boundary) { boundary_variables.insert(root_->graphId()); } // tg extract break conditions const int& min_variables = param_min_partition_variables.value(); const int& min_num_levels = param_min_partition_diameter.value(); int num_levels = 0; // tg while deque is not empty while (!variable_deque.empty()) { // tg take front of the deque and extract all the factors // where the variable is involved const VariableBase* top = variable_deque.front(); VariableBase* v = const_cast<VariableBase*>(top); VariableBase::Id v_id = v->graphId(); auto lower = _graph->lowerFactor(top); auto upper = _graph->upperFactor(top); // add variable to partition and initialize degree variables.push_back(v); // tg add a new level in the diameter counter ++num_levels; // tg for all the factors for (auto it = lower; it != upper; ++it) { auto it_var = _variable_outer_degree_map.find(v_id); assert(it_var != _variable_outer_degree_map.end() && "BreadthFirstSplitter::_constructPartition| bookeeping variables is broken"); it_var->second--; // if its already processed skip const FactorBase* f = it->second; if (_processed_factors.count(f->graphId())) { continue; } // tg add factor to partition and to processed factors FactorBase* factor = const_cast<FactorBase*>(f); factors.push_back(factor); _processed_factors.insert(f->graphId()); if (f->numVariables() < 2) { continue; } // tg determine id of the other pose variable VariableBase::Id other_id = f->variableId(0) == v->graphId() ? f->variableId(1) : f->variableId(0); auto it_other = _variable_outer_degree_map.find(other_id); assert(it_other != _variable_outer_degree_map.end() && "BreadthFirstSplitter::_constructPartition| bookeeping variables is broken"); it_other->second--; // tg check if the variable is an open variable in the graph (variable to be expanded) auto is_open = std::find(_open_variables.begin(), _open_variables.end(), other_id); if (is_open != _open_variables.end()) { boundary_variables.insert(*is_open); variable_deque.push_back(_graph->variable(other_id)); _open_variables.erase(is_open); continue; } // tg initialize other variable from current vertex and factor if (_init_action->compute(v, f, _visited_variables)) { variable_deque.push_back(_graph->variable(other_id)); _visited_variables.insert(other_id); } } variable_deque.pop_front(); // tg check current size and diameter, if sufficient create a partition int current_variables_size = variables.size() + variable_deque.size(); if (current_variables_size > min_variables && num_levels > min_num_levels) { break; } } // tg check which non-expanded variables are eligible to be boundary variables for (const VariableBase* vs : variable_deque) { VariableBase::Id vs_id = vs->graphId(); VariableBase* v = const_cast<VariableBase*>(vs); variables.push_back(v); if (_variable_outer_degree_map.at(vs_id) > 0) { _open_variables.push_back(vs_id); boundary_variables.insert(vs_id); } } this->_determineAnchorAndCreatePartition(variables, factors, boundary_variables); } void BreadthFirstSplitter::compute() { assert(_graph && "BreadthFirstSplitter::compute| no graph, call setPartitionManager"); assert(_manager && "BreadthFirstSplitter::compute| no manager, call setPartitionManager"); // tg connect factors and variables _graph->bindFactors(); // tg determine root of the expansion as the maximum degree variable in the graph const VariableBase* root = _computeOuterDegreeMap(); // tg compute first partition _constructPartition(root, false); _conditioner = root->graphId(); _visited_variables.insert(root->graphId()); // tg while there are variables to be expanded while (!_open_variables.empty()) { // tg extract front variable VariableBase::Id id = _open_variables.front(); const VariableBase* v = _graph->variable(id); _open_variables.pop_front(); // tg expand next partition _constructPartition(v, true); } } } // namespace srrg2_hipe
[ "frevo93@gmail.com" ]
frevo93@gmail.com
d58288ba4f309b079738e0515c25e608a6852fcf
7435dd60a9f79be1ffc86e342a61ca68be6c36da
/CSGO Solution/Features/Visuals/World.hpp
bd21207d3d46ae75aa2b13d0421bcf3c6299e47f
[]
no_license
LucQ12/zeeron.su
a1884384874c533ca80dd0df83bc7fdb4c81617b
7fcc32fc3d693340d2fa0800d4e0a531979905ac
refs/heads/main
2023-08-13T11:33:47.453906
2021-10-05T09:42:36
2021-10-05T09:42:36
419,263,778
3
1
null
null
null
null
UTF-8
C++
false
false
1,135
hpp
#pragma once #include <vector> #include "../SDK/Includes.hpp" struct ClientImpact_t { Vector m_vecPosition; float_t m_flTime; float_t m_flExpirationTime; }; struct C_BulletTrace { bool m_bIsLocalTrace = false; Vector m_vecStartPosition = Vector( 0, 0, 0 ); Vector m_vecEndPosition = Vector( 0, 0, 0 ); }; class C_World { public: virtual void Instance( ClientFrameStage_t Stage ); virtual void SkyboxChanger( ); virtual void DrawClientImpacts( ); virtual void DrawBulletTracers( ); virtual void OnBulletImpact( C_GameEvent* pEvent ); virtual void Clantag( ); virtual void Grenades( ); virtual void DrawScopeLines( ); virtual void PenetrationCrosshair( ); virtual void RemoveShadows( ); virtual void RemoveHandShaking( ); virtual void RemoveSmokeAndPostProcess( ); virtual void PostFrame( ClientFrameStage_t Stage ); virtual void OnRageBotFire( Vector vecStartPosition, Vector vecEndPosition ); virtual void PreserveKillfeed( ); std::vector < C_BulletTrace > m_BulletTracers = { }; private: int32_t m_iLastProcessedImpact = 0; bool m_bDidUnlockConvars = false; }; inline C_World* g_World = new C_World( );
[ "ptichka.denozavra05@mail.ru" ]
ptichka.denozavra05@mail.ru
555ed01e6d846c7b8a0bc71e879f8f0b43b908e2
3dfa2da447272f37da95b866aba154082b3c8ab4
/future.h
ea66f5aaf4425af0fcf2779b96670741edec0216
[]
no_license
cool-colo/future
03d40673aee63b4cdd0ead0cdb88ca6b3834e005
8283e03d95f2cce28830bf0808995605962c76e7
refs/heads/master
2023-05-06T16:29:53.067160
2021-06-03T09:00:12
2021-06-03T09:00:12
352,545,823
2
0
null
null
null
null
UTF-8
C++
false
false
6,618
h
#pragma once #include<cassert> #include "future-pre.h" class FutureException : public std::logic_error { public: using std::logic_error::logic_error; }; class FutureInvalid : public FutureException { public: FutureInvalid() : FutureException("Future invalid") {} }; class FutureAlreadyContinued : public FutureException { public: FutureAlreadyContinued() : FutureException("Future already continued") {} }; class FutureNotReady : public FutureException { public: FutureNotReady() : FutureException("Future not ready") {} }; class FutureCancellation : public FutureException { public: FutureCancellation() : FutureException("Future was cancelled") {} }; class FutureTimeout : public FutureException { public: FutureTimeout() : FutureException("Timed out") {} }; class FuturePredicateDoesNotObtain : public FutureException { public: FuturePredicateDoesNotObtain() : FutureException("Predicate does not obtain") {} }; class FutureNoTimekeeper : public FutureException { public: FutureNoTimekeeper() : FutureException("No timekeeper available") {} }; class FutureNoExecutor : public FutureException { public: FutureNoExecutor() : FutureException("No executor provided to via") {} }; template <class T> class Future; template<typename T> class FutureBase { public: using value_type = T; FutureBase(FutureBase<T> const&) = delete; FutureBase(Future<T>&&) noexcept; // not copyable FutureBase(Future<T> const&) = delete; virtual ~FutureBase(); T& value() &; T const& value() const&; T&& value() &&; T const&& value() const&&; bool isReady() const; bool hasValue() const; std::optional<T> poll(); template <class F> void setCallback_(F&& func); protected: friend class Promise<T>; template <class> friend class Future; Core<T>& getCore() { return getCoreImpl(*this); } Core<T> const& getCore() const { return getCoreImpl(*this); } template <typename Self> static decltype(auto) getCoreImpl(Self& self) { if (!self.core_) { throw FutureInvalid(); } return *self.core_; } T& getCoreValueChecked() { return getCoreValueChecked(*this); } T const& getCoreValueChecked() const { return getCoreValueChecked(*this); } template <typename Self> static decltype(auto) getCoreValueChecked(Self& self) { auto& core = self.getCore(); if (!core.hasResult()) { throw FutureNotReady(); } return core.get(); } std::shared_ptr<Core<T>> core_; explicit FutureBase(std::shared_ptr<Core<T>> obj) : core_(obj) {} void throwIfInvalid() const; void throwIfContinued() const; void assign(FutureBase<T>&& other) noexcept; // Variant: returns a value // e.g. f.thenTry([](Try<T> t){ return t.value(); }); template <typename F, typename R> typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type thenImplementation(F&& func, R); // Variant: returns a Future // e.g. f.thenTry([](Try<T> t){ return makeFuture<T>(t); }); template <typename F, typename R> typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type thenImplementation(F&& func, R); }; template <class T> class Future : private FutureBase<T> { private: using Base = FutureBase<T>; public: /// Type of the value that the producer, when successful, produces. using typename Base::value_type; Future(Future<T> const&) = delete; // movable Future(Future<T>&&) noexcept; using Base::isReady; using Base::poll; using Base::setCallback_; using Base::value; /// Creates/returns an invalid Future, that is, one with no shared state. /// /// Postcondition: /// /// - `RESULT.valid() == false` static Future<T> makeEmpty(); // not copyable Future& operator=(Future const&) = delete; // movable Future& operator=(Future&&) noexcept; /// Unwraps the case of a Future<Future<T>> instance, and returns a simple /// Future<T> instance. /// /// Preconditions: /// /// - `valid() == true` (else throws FutureInvalid) /// /// Postconditions: /// /// - Calling code should act as if `valid() == false`, /// i.e., as if `*this` was moved into RESULT. /// - `RESULT.valid() == true` template <class F = T> typename std:: enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type unwrap() &&; /// When this Future has completed, execute func which is a function that /// can be called with `T&&` (often a lambda with parameter type /// `auto&&` or `auto`). /// /// Func shall return either another Future or a value. /// /// Versions of these functions with Inline in the name will run the /// continuation inline with the execution of the previous callback in the /// chain if the callback attached to the previous future that triggers /// execution of func runs on the same executor that func would be executed /// on. /// /// A Future for the return type of func is returned. /// /// Future<string> f2 = f1.then([](auto&& v) { /// ... /// return string("foo"); /// }); /// /// Preconditions: /// /// - `valid() == true` (else throws FutureInvalid) /// /// Postconditions: /// /// - `valid() == false` /// - `RESULT.valid() == true` template <typename F> Future<typename valueCallableResult<T, F>::value_type> then(F&& func) &&; /// func is like std::function<void()> and is executed unconditionally, and /// the value/exception is passed through to the resulting Future. /// func shouldn't throw, but if it does it will be captured and propagated, /// and discard any value/exception that this Future has obtained. /// /// Preconditions: /// /// - `valid() == true` (else throws FutureInvalid) /// /// Postconditions: /// /// - Calling code should act as if `valid() == false`, /// i.e., as if `*this` was moved into RESULT. /// - `RESULT.valid() == true` template <class F> Future<T> ensure(F&& func) &&; T get() &&; Future<T>& wait() &; Future<T>&& wait() &&; protected: friend class Promise<T>; template <class> friend class FutureBase; template <class T2> friend Future<T2> makeFuture(T2&&); template <class> friend class Future; template <class> friend class FutureSplitter; using Base::throwIfContinued; using Base::throwIfInvalid; explicit Future(std::shared_ptr<Core<T>> obj) : Base(obj) {} }; template <class T> std::pair<Promise<T>, Future<T>> makePromiseContract() { auto p = Promise<T>(); auto f = p.getFuture(); return std::make_pair(std::move(p), std::move(f)); } #include "future-inl.h"
[ "fanglc@wifi.com" ]
fanglc@wifi.com
0700619ec984e56ec470bdb14241a910a61d68bf
c3c6d5e826d2cd231dcab832b457f22bbaaeaaa0
/chrome/browser/ui/web_applications/web_app_browsertest.cc
593c444c53116cff6e3e7c637780f3944659deea
[ "BSD-3-Clause" ]
permissive
boy12371/chromium
698c1218fb60d6cbf985932fab0a84709c0a60a1
c19205e6abcec73ee37140b851c0bb5477998660
refs/heads/master
2022-11-18T17:24:27.789838
2020-07-28T02:01:11
2020-07-28T02:01:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
41,378
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 "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/metrics/user_action_tester.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/sessions/tab_restore_service_factory.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_test.h" #include "chrome/browser/ui/page_info/page_info_dialog.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/app_menu_model.h" #include "chrome/browser/ui/web_applications/app_browser_controller.h" #include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h" #include "chrome/browser/ui/web_applications/web_app_controller_browsertest.h" #include "chrome/browser/ui/web_applications/web_app_launch_manager.h" #include "chrome/browser/ui/web_applications/web_app_launch_utils.h" #include "chrome/browser/ui/web_applications/web_app_menu_model.h" #include "chrome/browser/web_applications/components/app_registrar.h" #include "chrome/browser/web_applications/components/app_registry_controller.h" #include "chrome/browser/web_applications/components/external_install_options.h" #include "chrome/browser/web_applications/components/web_app_constants.h" #include "chrome/browser/web_applications/components/web_app_helpers.h" #include "chrome/browser/web_applications/components/web_app_provider_base.h" #include "chrome/browser/web_applications/test/web_app_install_observer.h" #include "chrome/browser/web_applications/test/web_app_test.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/common/chrome_features.h" #include "chrome/common/web_application_info.h" #include "chrome/test/base/ui_test_utils.h" #include "components/sessions/core/tab_restore_service.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/clipboard_buffer.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #if defined(OS_CHROMEOS) #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" #endif #if defined(OS_MACOSX) #include "ui/base/test/scoped_fake_nswindow_fullscreen.h" #endif namespace { constexpr const char kExampleURL[] = "http://example.org/"; constexpr char kLaunchWebAppDisplayModeHistogram[] = "Launch.WebAppDisplayMode"; // Opens |url| in a new popup window with the dimensions |popup_size|. Browser* OpenPopupAndWait(Browser* browser, const GURL& url, const gfx::Size& popup_size) { content::WebContents* const web_contents = browser->tab_strip_model()->GetActiveWebContents(); content::WebContentsAddedObserver new_contents_observer; std::string open_window_script = base::StringPrintf( "window.open('%s', '_blank', 'toolbar=none,width=%i,height=%i')", url.spec().c_str(), popup_size.width(), popup_size.height()); EXPECT_TRUE(content::ExecJs(web_contents, open_window_script)); content::WebContents* popup_contents = new_contents_observer.GetWebContents(); content::WaitForLoadStop(popup_contents); Browser* popup_browser = chrome::FindBrowserWithWebContents(popup_contents); // The navigation should happen in a new window. EXPECT_NE(browser, popup_browser); return popup_browser; } } // namespace namespace web_app { class WebAppBrowserTest : public WebAppControllerBrowserTest { public: GURL GetSecureAppURL() { return https_server()->GetURL("app.com", "/ssl/google.html"); } GURL GetURLForPath(const std::string& path) { return https_server()->GetURL("app.com", path); } AppId InstallPwaForCurrentUrl() { chrome::SetAutoAcceptPWAInstallConfirmationForTesting(true); WebAppInstallObserver observer(profile()); CHECK(chrome::ExecuteCommand(browser(), IDC_INSTALL_PWA)); AppId app_id = observer.AwaitNextInstall(); chrome::SetAutoAcceptPWAInstallConfirmationForTesting(false); return app_id; } }; // A dedicated test fixture for DisplayOverride, which is supported // only for the new web apps mode, and requires a command line switch // to enable manifest parsing. class WebAppBrowserTest_DisplayOverride : public WebAppBrowserTest { public: void SetUpCommandLine(base::CommandLine* command_line) override { WebAppBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, "DisplayOverride"); } }; using WebAppTabRestoreBrowserTest = WebAppBrowserTest; IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ThemeColor) { { const SkColor theme_color = SkColorSetA(SK_ColorBLUE, 0xF0); blink::Manifest manifest; manifest.start_url = GURL(kExampleURL); manifest.scope = GURL(kExampleURL); manifest.theme_color = theme_color; auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app::UpdateWebAppInfoFromManifest(manifest, web_app_info.get()); AppId app_id = InstallWebApp(std::move(web_app_info)); Browser* app_browser = LaunchWebAppBrowser(app_id); EXPECT_EQ(GetAppIdFromApplicationName(app_browser->app_name()), app_id); EXPECT_EQ(SkColorSetA(theme_color, SK_AlphaOPAQUE), app_browser->app_controller()->GetThemeColor()); } { auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->app_url = GURL("http://example.org/2"); web_app_info->scope = GURL("http://example.org/"); web_app_info->theme_color = base::Optional<SkColor>(); AppId app_id = InstallWebApp(std::move(web_app_info)); Browser* app_browser = LaunchWebAppBrowser(app_id); EXPECT_EQ(GetAppIdFromApplicationName(app_browser->app_name()), app_id); EXPECT_EQ(base::nullopt, app_browser->app_controller()->GetThemeColor()); } } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, BackgroundColor) { // This feature is intentionally not implemented for the obsolete bookmark // apps. if (!base::FeatureList::IsEnabled(features::kDesktopPWAsWithoutExtensions)) return; blink::Manifest manifest; manifest.start_url = GURL(kExampleURL); manifest.scope = GURL(kExampleURL); manifest.background_color = SkColorSetA(SK_ColorBLUE, 0xF0); auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app::UpdateWebAppInfoFromManifest(manifest, web_app_info.get()); AppId app_id = InstallWebApp(std::move(web_app_info)); auto* provider = WebAppProviderBase::GetProviderBase(profile()); EXPECT_EQ(provider->registrar().GetAppBackgroundColor(app_id), SK_ColorBLUE); } // This tests that we don't crash when launching a PWA window with an // autogenerated user theme set. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, AutoGeneratedUserThemeCrash) { ThemeServiceFactory::GetForProfile(browser()->profile()) ->BuildAutogeneratedThemeFromColor(SK_ColorBLUE); auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->app_url = GURL(kExampleURL); AppId app_id = InstallWebApp(std::move(web_app_info)); LaunchWebAppBrowser(app_id); } // Check the 'Open in Chrome' menu button for web app windows. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, OpenInChrome) { const GURL app_url(kExampleURL); const AppId app_id = InstallPWA(app_url); { Browser* const app_browser = LaunchWebAppBrowser(app_id); EXPECT_EQ(1, app_browser->tab_strip_model()->count()); EXPECT_EQ(1, browser()->tab_strip_model()->count()); ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile())); chrome::ExecuteCommand(app_browser, IDC_OPEN_IN_CHROME); // The browser frame is closed next event loop so it's still safe to access // here. EXPECT_EQ(0, app_browser->tab_strip_model()->count()); EXPECT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_EQ(1, browser()->tab_strip_model()->active_index()); EXPECT_EQ( app_url, browser()->tab_strip_model()->GetActiveWebContents()->GetVisibleURL()); } // Wait until the browser actually gets closed. This invalidates // |app_browser|. content::RunAllPendingInMessageLoop(); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); } // Check the 'App info' menu button for web app windows. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, AppInfoOpensPageInfo) { const GURL app_url(kExampleURL); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowser(app_id); bool dialog_created = false; GetPageInfoDialogCreatedCallbackForTesting() = base::BindOnce( [](bool* dialog_created) { *dialog_created = true; }, &dialog_created); chrome::ExecuteCommand(app_browser, IDC_WEB_APP_MENU_APP_INFO); EXPECT_TRUE(dialog_created); // The test closure should have run. But clear the global in case it hasn't. EXPECT_FALSE(GetPageInfoDialogCreatedCallbackForTesting()); GetPageInfoDialogCreatedCallbackForTesting().Reset(); } // Check that last launch time is set after launch. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, AppLastLaunchTime) { const GURL app_url(kExampleURL); const AppId app_id = InstallPWA(app_url); auto* provider = WebAppProviderBase::GetProviderBase(profile()); // last_launch_time is not set before launch EXPECT_TRUE(provider->registrar().GetAppLastLaunchTime(app_id).is_null()); auto before_launch = base::Time::Now(); LaunchWebAppBrowser(app_id); EXPECT_TRUE(provider->registrar().GetAppLastLaunchTime(app_id) >= before_launch); } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, HasMinimalUiButtons) { int index = 0; auto has_buttons = [this, &index](DisplayMode display_mode, bool open_as_window) -> bool { base::HistogramTester tester; const std::string base_url = "https://example.com/path"; auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->app_url = GURL(base_url + base::NumberToString(index++)); web_app_info->scope = web_app_info->app_url; web_app_info->display_mode = display_mode; web_app_info->open_as_window = open_as_window; AppId app_id = InstallWebApp(std::move(web_app_info)); Browser* app_browser = LaunchWebAppBrowser(app_id); DCHECK(app_browser->app_controller()); tester.ExpectUniqueSample(kLaunchWebAppDisplayModeHistogram, display_mode, 1); return app_browser->app_controller()->HasMinimalUiButtons(); }; EXPECT_TRUE(has_buttons(DisplayMode::kBrowser, /*open_as_window=*/true)); EXPECT_TRUE(has_buttons(DisplayMode::kMinimalUi, /*open_as_window=*/true)); EXPECT_FALSE(has_buttons(DisplayMode::kStandalone, /*open_as_window=*/true)); EXPECT_TRUE(has_buttons(DisplayMode::kBrowser, /*open_as_window=*/false)); EXPECT_TRUE(has_buttons(DisplayMode::kMinimalUi, /*open_as_window=*/false)); EXPECT_FALSE(has_buttons(DisplayMode::kStandalone, /*open_as_window=*/false)); } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest_DisplayOverride, DisplayOverride) { GURL test_url = https_server()->GetURL( "/banners/" "manifest_test_page.html?manifest=manifest_display_override.json"); NavigateToURLAndWait(browser(), test_url); const AppId app_id = InstallPwaForCurrentUrl(); auto* provider = WebAppProvider::Get(profile()); std::vector<DisplayMode> app_display_mode_override = provider->registrar().GetAppDisplayModeOverride(app_id); ASSERT_EQ(2u, app_display_mode_override.size()); EXPECT_EQ(DisplayMode::kMinimalUi, app_display_mode_override[0]); EXPECT_EQ(DisplayMode::kStandalone, app_display_mode_override[1]); } // Tests that desktop PWAs open links in the browser. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, DesktopPWAsOpenLinksInApp) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); NavigateToURLAndWait(app_browser, app_url); ASSERT_TRUE(app_browser->app_controller()); NavigateAndCheckForToolbar(app_browser, GURL(kExampleURL), true); } // Tests that desktop PWAs open links in a new tab at the end of the tabstrip of // the last active browser. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, DesktopPWAsOpenLinksInNewTab) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); NavigateToURLAndWait(app_browser, app_url); ASSERT_TRUE(app_browser->app_controller()); EXPECT_EQ(chrome::GetTotalBrowserCount(), 2u); Browser* browser2 = CreateBrowser(app_browser->profile()); EXPECT_EQ(chrome::GetTotalBrowserCount(), 3u); TabStripModel* model2 = browser2->tab_strip_model(); chrome::AddTabAt(browser2, GURL(), -1, true); EXPECT_EQ(model2->count(), 2); model2->SelectPreviousTab(); EXPECT_EQ(model2->active_index(), 0); NavigateParams param(app_browser, GURL("http://www.google.com/"), ui::PAGE_TRANSITION_LINK); param.window_action = NavigateParams::SHOW_WINDOW; param.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; ui_test_utils::NavigateToURL(&param); EXPECT_EQ(chrome::GetTotalBrowserCount(), 3u); EXPECT_EQ(model2->count(), 3); EXPECT_EQ(param.browser, browser2); EXPECT_EQ(model2->active_index(), 2); EXPECT_EQ(param.navigated_or_inserted_contents, model2->GetActiveWebContents()); } // Tests that desktop PWAs are opened at the correct size. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, PWASizeIsCorrectlyRestored) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(app_browser)); NavigateToURLAndWait(app_browser, app_url); const gfx::Rect bounds = gfx::Rect(50, 50, 500, 500); app_browser->window()->SetBounds(bounds); app_browser->window()->Close(); Browser* const new_browser = LaunchWebAppBrowser(app_id); EXPECT_EQ(new_browser->window()->GetBounds(), bounds); } // Tests that desktop PWAs are reopened at the correct size. IN_PROC_BROWSER_TEST_P(WebAppTabRestoreBrowserTest, ReopenedPWASizeIsCorrectlyRestored) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(app_browser)); NavigateToURLAndWait(app_browser, app_url); const gfx::Rect bounds = gfx::Rect(50, 50, 500, 500); app_browser->window()->SetBounds(bounds); app_browser->window()->Close(); content::WebContentsAddedObserver new_contents_observer; sessions::TabRestoreService* const service = TabRestoreServiceFactory::GetForProfile(profile()); ASSERT_GT(service->entries().size(), 0U); service->RestoreMostRecentEntry(nullptr); content::WebContents* const restored_web_contents = new_contents_observer.GetWebContents(); Browser* const restored_browser = chrome::FindBrowserWithWebContents(restored_web_contents); EXPECT_EQ(restored_browser->window()->GetBounds(), bounds); } // Tests that using window.open to create a popup window out of scope results in // a correctly sized window. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, OffScopePWAPopupsHaveCorrectSize) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowser(app_id); EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(app_browser)); const GURL offscope_url("https://example.com"); const gfx::Size size(500, 500); Browser* const popup_browser = OpenPopupAndWait(app_browser, offscope_url, size); // The navigation should have happened in a new window. EXPECT_NE(popup_browser, app_browser); // The popup browser should be a PWA. EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(popup_browser)); // Toolbar should be shown, as the popup is out of scope. EXPECT_TRUE(popup_browser->app_controller()->ShouldShowCustomTabBar()); // Skip animating the toolbar visibility. popup_browser->app_controller()->UpdateCustomTabBarVisibility(false); // The popup window should be the size we specified. EXPECT_EQ(size, popup_browser->window()->GetContentsSize()); } // Tests that using window.open to create a popup window in scope results in // a correctly sized window. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, InScopePWAPopupsHaveCorrectSize) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowser(app_id); EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(app_browser)); const gfx::Size size(500, 500); Browser* const popup_browser = OpenPopupAndWait(app_browser, app_url, size); // The navigation should have happened in a new window. EXPECT_NE(popup_browser, app_browser); // The popup browser should be a PWA. EXPECT_TRUE(AppBrowserController::IsForWebAppBrowser(popup_browser)); // Toolbar should not be shown, as the popup is in scope. EXPECT_FALSE(popup_browser->app_controller()->ShouldShowCustomTabBar()); // Skip animating the toolbar visibility. popup_browser->app_controller()->UpdateCustomTabBarVisibility(false); // The popup window should be the size we specified. EXPECT_EQ(size, popup_browser->window()->GetContentsSize()); } // Tests that app windows are correctly restored. IN_PROC_BROWSER_TEST_P(WebAppTabRestoreBrowserTest, RestoreAppWindow) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); ASSERT_TRUE(app_browser->is_type_app()); app_browser->window()->Close(); content::WebContentsAddedObserver new_contents_observer; sessions::TabRestoreService* const service = TabRestoreServiceFactory::GetForProfile(profile()); service->RestoreMostRecentEntry(nullptr); content::WebContents* const restored_web_contents = new_contents_observer.GetWebContents(); Browser* const restored_browser = chrome::FindBrowserWithWebContents(restored_web_contents); EXPECT_TRUE(restored_browser->is_type_app()); } // Test navigating to an out of scope url on the same origin causes the url // to be shown to the user. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, LocationBarIsVisibleOffScopeOnSameOrigin) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); // Toolbar should not be visible in the app. ASSERT_FALSE(app_browser->app_controller()->ShouldShowCustomTabBar()); // The installed PWA's scope is app.com:{PORT}/ssl, // so app.com:{PORT}/accessibility_fail.html is out of scope. const GURL out_of_scope = GetURLForPath("/accessibility_fail.html"); NavigateToURLAndWait(app_browser, out_of_scope); // Location should be visible off scope. ASSERT_TRUE(app_browser->app_controller()->ShouldShowCustomTabBar()); } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, UpgradeWithoutCustomTabBar) { const GURL secure_app_url = https_server()->GetURL("app.site.com", "/empty.html"); GURL::Replacements rep; rep.SetSchemeStr(url::kHttpScheme); const GURL app_url = secure_app_url.ReplaceComponents(rep); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowser(app_id); NavigateToURLAndWait(app_browser, secure_app_url); EXPECT_FALSE(app_browser->app_controller()->ShouldShowCustomTabBar()); const GURL off_origin_url = https_server()->GetURL("example.org", "/empty.html"); NavigateToURLAndWait(app_browser, off_origin_url); EXPECT_EQ(app_browser->app_controller()->ShouldShowCustomTabBar(), true); } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, OverscrollEnabled) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); // Overscroll is only enabled on Aura platforms currently. #if defined(USE_AURA) EXPECT_TRUE(app_browser->CanOverscrollContent()); #else EXPECT_FALSE(app_browser->CanOverscrollContent()); #endif } // Check the 'Copy URL' menu button for Web App windows. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, CopyURL) { const GURL app_url(kExampleURL); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); content::BrowserTestClipboardScope test_clipboard_scope; chrome::ExecuteCommand(app_browser, IDC_COPY_URL); ui::Clipboard* const clipboard = ui::Clipboard::GetForCurrentThread(); base::string16 result; clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &result); EXPECT_EQ(result, base::UTF8ToUTF16(kExampleURL)); } // Tests that the command for popping a tab out to a PWA window is disabled in // incognito. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, PopOutDisabledInIncognito) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const incognito_browser = OpenURLOffTheRecord(profile(), app_url); auto app_menu_model = std::make_unique<AppMenuModel>(nullptr, incognito_browser); app_menu_model->Init(); ui::MenuModel* model = app_menu_model.get(); int index = -1; ASSERT_TRUE(app_menu_model->GetModelAndIndexForCommandId( IDC_OPEN_IN_PWA_WINDOW, &model, &index)); EXPECT_FALSE(model->IsEnabledAt(index)); } // Tests that web app menus don't crash when no tabs are selected. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, NoTabSelectedMenuCrash) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); app_browser->tab_strip_model()->CloseAllTabs(); auto app_menu_model = std::make_unique<WebAppMenuModel>(nullptr, app_browser); app_menu_model->Init(); } // Tests that PWA menus have an uninstall option. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, UninstallMenuOption) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); auto app_menu_model = std::make_unique<WebAppMenuModel>(nullptr, app_browser); app_menu_model->Init(); ui::MenuModel* model = app_menu_model.get(); int index = -1; const bool found = app_menu_model->GetModelAndIndexForCommandId( WebAppMenuModel::kUninstallAppCommandId, &model, &index); #if defined(OS_CHROMEOS) EXPECT_FALSE(found); #else EXPECT_TRUE(found); EXPECT_TRUE(model->IsEnabledAt(index)); base::HistogramTester tester; app_menu_model->ExecuteCommand(WebAppMenuModel::kUninstallAppCommandId, /*event_flags=*/0); tester.ExpectUniqueSample("HostedAppFrame.WrenchMenu.MenuAction", MENU_ACTION_UNINSTALL_APP, 1); tester.ExpectUniqueSample("WrenchMenu.MenuAction", MENU_ACTION_UNINSTALL_APP, 1); #endif // defined(OS_CHROMEOS) } // Tests that both installing a PWA and creating a shortcut app are disabled for // incognito windows. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ShortcutMenuOptionsInIncognito) { Browser* const incognito_browser = CreateIncognitoBrowser(profile()); EXPECT_FALSE(NavigateAndAwaitInstallabilityCheck(incognito_browser, GetSecureAppURL())); EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, incognito_browser), kDisabled); EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, incognito_browser), kNotPresent); } // Tests that both installing a PWA and creating a shortcut app are disabled for // an error page. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ShortcutMenuOptionsForErrorPage) { EXPECT_FALSE(NavigateAndAwaitInstallabilityCheck( browser(), https_server()->GetURL("/invalid_path.html"))); EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, browser()), kDisabled); EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, browser()), kNotPresent); } // Tests that both installing a PWA and creating a shortcut app are available // for an installable PWA. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ShortcutMenuOptionsForInstallablePWA) { EXPECT_TRUE( NavigateAndAwaitInstallabilityCheck(browser(), GetInstallableAppURL())); EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, browser()), kEnabled); EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, browser()), kEnabled); } // Tests that both installing a PWA and creating a shortcut app are disabled // when page crashes. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ShortcutMenuOptionsForCrashedTab) { EXPECT_TRUE( NavigateAndAwaitInstallabilityCheck(browser(), GetInstallableAppURL())); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); tab_contents->SetIsCrashed(base::TERMINATION_STATUS_PROCESS_CRASHED, -1); ASSERT_TRUE(tab_contents->IsCrashed()); EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, browser()), kDisabled); EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, browser()), kDisabled); } // Tests that an installed PWA is not used when out of scope by one path level. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, MenuOptionsOutsideInstalledPwaScope) { NavigateToURLAndWait( browser(), https_server()->GetURL("/banners/scope_is_start_url/index.html")); InstallPwaForCurrentUrl(); // Open a page that is one directory up from the installed PWA. Browser* const new_browser = NavigateInNewWindowAndAwaitInstallabilityCheck( https_server()->GetURL("/banners/no_manifest_test_page.html")); EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, new_browser), kEnabled); EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, new_browser), kNotPresent); EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, new_browser), kNotPresent); } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, InstallInstallableSite) { base::Time before_install_time = base::Time::Now(); base::UserActionTester user_action_tester; NavigateToURLAndWait(browser(), GetInstallableAppURL()); const AppId app_id = InstallPwaForCurrentUrl(); auto* provider = WebAppProviderBase::GetProviderBase(profile()); EXPECT_EQ(provider->registrar().GetAppShortName(app_id), GetInstallableAppName()); // Installed PWAs should launch in their own window. EXPECT_EQ(provider->registrar().GetAppUserDisplayMode(app_id), blink::mojom::DisplayMode::kStandalone); // Installed PWAs should have install time set. EXPECT_TRUE(provider->registrar().GetAppInstallTime(app_id) >= before_install_time); EXPECT_EQ(1, user_action_tester.GetActionCount("InstallWebAppFromMenu")); EXPECT_EQ(0, user_action_tester.GetActionCount("CreateShortcut")); #if defined(OS_CHROMEOS) // Apps on Chrome OS should not be pinned after install. EXPECT_FALSE(ChromeLauncherController::instance()->IsAppPinned(app_id)); #endif } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, CanInstallOverTabPwa) { NavigateToURLAndWait(browser(), GetInstallableAppURL()); const AppId app_id = InstallPwaForCurrentUrl(); // Change display mode to open in tab. auto* provider = WebAppProviderBase::GetProviderBase(profile()); provider->registry_controller().SetAppUserDisplayMode( app_id, blink::mojom::DisplayMode::kBrowser); Browser* const new_browser = NavigateInNewWindowAndAwaitInstallabilityCheck(GetInstallableAppURL()); EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, new_browser), kEnabled); EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, new_browser), kEnabled); EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, new_browser), kNotPresent); } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, CannotInstallOverWindowPwa) { NavigateToURLAndWait(browser(), GetInstallableAppURL()); InstallPwaForCurrentUrl(); // Avoid any interference if active browser was changed by PWA install. Browser* const new_browser = NavigateInNewWindowAndAwaitInstallabilityCheck(GetInstallableAppURL()); EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, new_browser), kEnabled); EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, new_browser), kNotPresent); EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, new_browser), kEnabled); } IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, CannotInstallOverPolicyPwa) { ExternalInstallOptions options = CreateInstallOptions(GetInstallableAppURL()); options.install_source = ExternalInstallSource::kExternalPolicy; PendingAppManagerInstall(profile(), options); // Avoid any interference if active browser was changed by PWA install. Browser* const new_browser = NavigateInNewWindowAndAwaitInstallabilityCheck(GetInstallableAppURL()); EXPECT_EQ(GetAppMenuCommandState(IDC_CREATE_SHORTCUT, new_browser), kDisabled); EXPECT_EQ(GetAppMenuCommandState(IDC_INSTALL_PWA, new_browser), kNotPresent); EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, new_browser), kEnabled); } // Tests that the command for OpenActiveTabInPwaWindow is available for secure // pages in an app's scope. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ReparentWebAppForSecureActiveTab) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); NavigateToURLAndWait(browser(), app_url); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_EQ(tab_contents->GetLastCommittedURL(), app_url); EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, browser()), kEnabled); Browser* const app_browser = ReparentWebAppForActiveTab(browser()); ASSERT_EQ(app_browser->app_controller()->GetAppId(), app_id); } // Tests that reparenting the last browser tab doesn't close the browser window. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ReparentLastBrowserTab) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); NavigateToURLAndWait(browser(), app_url); Browser* const app_browser = ReparentWebAppForActiveTab(browser()); ASSERT_EQ(app_browser->app_controller()->GetAppId(), app_id); ASSERT_TRUE(IsBrowserOpen(browser())); EXPECT_EQ(browser()->tab_strip_model()->count(), 1); } // Tests that reparenting a shortcut app tab results in a minimal-ui app window. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, ReparentShortcutApp) { const GURL app_url = GetSecureAppURL(); auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->app_url = app_url; web_app_info->scope = app_url.GetWithoutFilename(); web_app_info->display_mode = DisplayMode::kBrowser; web_app_info->open_as_window = false; web_app_info->title = base::ASCIIToUTF16("A Shortcut App"); const AppId app_id = InstallWebApp(std::move(web_app_info)); NavigateToURLAndWait(browser(), app_url); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_EQ(tab_contents->GetLastCommittedURL(), app_url); EXPECT_EQ(GetAppMenuCommandState(IDC_OPEN_IN_PWA_WINDOW, browser()), kEnabled); EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_OPEN_IN_PWA_WINDOW)); Browser* const app_browser = BrowserList::GetInstance()->GetLastActive(); ASSERT_EQ(app_browser->app_controller()->GetAppId(), app_id); EXPECT_TRUE(app_browser->app_controller()->HasMinimalUiButtons()); // User preference remains unchanged. Future instances will open in tabs. auto* provider = WebAppProvider::Get(profile()); EXPECT_EQ(provider->registrar().GetAppUserDisplayMode(app_id), DisplayMode::kBrowser); EXPECT_EQ(provider->registrar().GetAppEffectiveDisplayMode(app_id), DisplayMode::kBrowser); } // Tests that the manifest name of the current installable site is used in the // installation menu text. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, InstallToShelfContainsAppName) { EXPECT_TRUE( NavigateAndAwaitInstallabilityCheck(browser(), GetInstallableAppURL())); auto app_menu_model = std::make_unique<AppMenuModel>(nullptr, browser()); app_menu_model->Init(); ui::MenuModel* model = app_menu_model.get(); int index = -1; EXPECT_TRUE(app_menu_model->GetModelAndIndexForCommandId(IDC_INSTALL_PWA, &model, &index)); EXPECT_EQ(app_menu_model.get(), model); EXPECT_EQ(model->GetLabelAt(index), base::UTF8ToUTF16("Install Manifest test app\xE2\x80\xA6")); } // Check that no assertions are hit when showing a permission request bubble. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, PermissionBubble) { const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowserAndWait(app_id); content::RenderFrameHost* const render_frame_host = app_browser->tab_strip_model()->GetActiveWebContents()->GetMainFrame(); EXPECT_TRUE(content::ExecuteScript( render_frame_host, "navigator.geolocation.getCurrentPosition(function(){});")); } // Ensure that web app windows with blank titles don't display the URL as a // default window title. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, EmptyTitlesDoNotDisplayUrl) { const GURL app_url = https_server()->GetURL("app.site.com", "/empty.html"); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowser(app_id); content::WebContents* const web_contents = app_browser->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(web_contents)); EXPECT_EQ(base::string16(), app_browser->GetWindowTitleForCurrentTab(false)); NavigateToURLAndWait(app_browser, https_server()->GetURL("app.site.com", "/simple.html")); EXPECT_EQ(base::ASCIIToUTF16("OK"), app_browser->GetWindowTitleForCurrentTab(false)); } // Ensure that web app windows display the app title instead of the page // title when off scope. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, OffScopeUrlsDisplayAppTitle) { const GURL app_url = GetSecureAppURL(); const base::string16 app_title = base::ASCIIToUTF16("A Web App"); auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->app_url = app_url; web_app_info->scope = app_url.GetWithoutFilename(); web_app_info->title = app_title; const AppId app_id = InstallWebApp(std::move(web_app_info)); Browser* const app_browser = LaunchWebAppBrowser(app_id); content::WebContents* const web_contents = app_browser->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(web_contents)); // When we are within scope, show the page title. EXPECT_EQ(base::ASCIIToUTF16("Google"), app_browser->GetWindowTitleForCurrentTab(false)); NavigateToURLAndWait(app_browser, https_server()->GetURL("app.site.com", "/simple.html")); // When we are off scope, show the app title. EXPECT_EQ(app_title, app_browser->GetWindowTitleForCurrentTab(false)); } // Ensure that web app windows display the app title instead of the page // title when using http. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, InScopeHttpUrlsDisplayAppTitle) { ASSERT_TRUE(embedded_test_server()->Start()); const GURL app_url = embedded_test_server()->GetURL("app.site.com", "/simple.html"); const base::string16 app_title = base::ASCIIToUTF16("A Web App"); auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->app_url = app_url; web_app_info->title = app_title; const AppId app_id = InstallWebApp(std::move(web_app_info)); Browser* const app_browser = LaunchWebAppBrowser(app_id); content::WebContents* const web_contents = app_browser->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(web_contents)); // The page title is "OK" but the page is being served over HTTP, so the app // title should be used instead. EXPECT_EQ(app_title, app_browser->GetWindowTitleForCurrentTab(false)); } // Check that a subframe on a regular web page can navigate to a URL that // redirects to a web app. https://crbug.com/721949. IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, SubframeRedirectsToWebApp) { ASSERT_TRUE(embedded_test_server()->Start()); // Set up a web app which covers app.com URLs. GURL app_url = embedded_test_server()->GetURL("app.com", "/title1.html"); const AppId app_id = InstallPWA(app_url); // Navigate a regular tab to a page with a subframe. const GURL url = embedded_test_server()->GetURL("foo.com", "/iframe.html"); content::WebContents* const tab = browser()->tab_strip_model()->GetActiveWebContents(); NavigateToURLAndWait(browser(), url); // Navigate the subframe to a URL that redirects to a URL in the web app's // web extent. const GURL redirect_url = embedded_test_server()->GetURL( "bar.com", "/server-redirect?" + app_url.spec()); EXPECT_TRUE(NavigateIframeToURL(tab, "test", redirect_url)); // Ensure that the frame navigated successfully and that it has correct // content. content::RenderFrameHost* const subframe = content::ChildFrameAt(tab->GetMainFrame(), 0); EXPECT_EQ(app_url, subframe->GetLastCommittedURL()); EXPECT_EQ( "This page has no title.", EvalJs(subframe, "document.body.innerText.trim();").ExtractString()); } #if defined(OS_MACOSX) IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, NewAppWindow) { BrowserList* const browser_list = BrowserList::GetInstance(); const GURL app_url = GetSecureAppURL(); const AppId app_id = InstallPWA(app_url); Browser* const app_browser = LaunchWebAppBrowser(app_id); EXPECT_EQ(browser_list->size(), 2U); EXPECT_TRUE(chrome::ExecuteCommand(app_browser, IDC_NEW_WINDOW)); EXPECT_EQ(browser_list->size(), 3U); Browser* const new_browser = browser_list->GetLastActive(); EXPECT_NE(new_browser, browser()); EXPECT_NE(new_browser, app_browser); EXPECT_TRUE(new_browser->is_type_app()); EXPECT_EQ(new_browser->app_controller()->GetAppId(), app_id); WebAppProviderBase::GetProviderBase(profile()) ->registry_controller() .SetAppUserDisplayMode(app_id, DisplayMode::kBrowser); EXPECT_EQ(browser()->tab_strip_model()->count(), 1); EXPECT_TRUE(chrome::ExecuteCommand(app_browser, IDC_NEW_WINDOW)); EXPECT_EQ(browser_list->GetLastActive(), browser()); EXPECT_EQ(browser()->tab_strip_model()->count(), 2); EXPECT_EQ( browser()->tab_strip_model()->GetActiveWebContents()->GetVisibleURL(), app_url); } #endif IN_PROC_BROWSER_TEST_P(WebAppBrowserTest, PopupLocationBar) { #if defined(OS_MACOSX) ui::test::ScopedFakeNSWindowFullscreen fake_fullscreen; #endif const GURL app_url = GetSecureAppURL(); const GURL in_scope = https_server()->GetURL("app.com", "/ssl/page_with_subresource.html"); const AppId app_id = InstallPWA(app_url); Browser* const popup_browser = web_app::CreateWebApplicationWindow( profile(), app_id, WindowOpenDisposition::NEW_POPUP); EXPECT_TRUE( popup_browser->CanSupportWindowFeature(Browser::FEATURE_LOCATIONBAR)); EXPECT_TRUE( popup_browser->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR)); FullscreenNotificationObserver waiter(popup_browser); chrome::ToggleFullscreenMode(popup_browser); waiter.Wait(); EXPECT_TRUE( popup_browser->CanSupportWindowFeature(Browser::FEATURE_LOCATIONBAR)); } INSTANTIATE_TEST_SUITE_P(All, WebAppBrowserTest, ::testing::Values(ProviderType::kBookmarkApps, ProviderType::kWebApps), ProviderTypeParamToString); INSTANTIATE_TEST_SUITE_P(All, WebAppTabRestoreBrowserTest, ::testing::Values(ProviderType::kBookmarkApps, ProviderType::kWebApps), ProviderTypeParamToString); // DisplayOverride is supported only for the new web apps mode INSTANTIATE_TEST_SUITE_P(All, WebAppBrowserTest_DisplayOverride, ::testing::Values(ProviderType::kWebApps), ProviderTypeParamToString); } // namespace web_app
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
c20671998265105cf986067aeb34803888bf596f
e18d3ba753df23d389b6903a7e495bfaaef8b2d4
/labs161/practicestrings.cpp
2642148daebef8f5b8b50bad9318fd0628d892f6
[]
no_license
ErinTanaka/IntroToCS
be4656ae915437f7bccedae2ef52735c1a171fd8
6efc984cee29a73ee29cd056392ff4450ed59178
refs/heads/master
2022-07-15T02:17:11.552524
2020-05-11T22:16:28
2020-05-11T22:16:28
263,171,285
0
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
#include <iostream> #include <string> using namespace std; void dointhings(string &str); int main(){ string mystr; mystr="hello world"; cout << "whole string: " << mystr << endl; cout << "3rd character in string: " << mystr[2] << endl; dointhings(mystr); cout << mystr << endl; cout << "dynamic 1-d array" << endl; int *a; a= new int[3]; a[0]=1; a[1]=2; a[2]=9; cout << "2nd element of a: " << a[1] << endl; cout << "static 2d array" << endl; int 2darray[4][2]; return 0; } void dointhings(string &str){ str[0]='s'; str[1]='t'; str[2]='a'; str[3]='r'; str[4]='t'; }
[ "tanakae@flip3.engr.oregonstate.edu" ]
tanakae@flip3.engr.oregonstate.edu
112f02a6693a53d79db13a46ce5d512af1dcf862
8dba4d5f1d91e777e23df52babfd8d942de9591d
/sys/opt/terminal/terminal.h
13fdb1c3935d566ca571d9ecd9c56ec82a67094f
[ "MIT" ]
permissive
scientiist/BellOS
42c484d51511f5aef667552f3d502a38f640f6ea
1a74bf445f2cd6bb704de7ca173bd87b7d1a23ed
refs/heads/master
2021-06-16T17:15:20.647516
2017-05-13T21:06:15
2017-05-13T21:06:15
76,580,271
1
0
null
null
null
null
UTF-8
C++
false
false
254
h
#ifndef __TERMINAL_INCLUDED__ #define __TERMINAL_INCLUDED__ #include "../../kernel/video/videobuffer.h" class Terminal { VideoBuffer termVB; String lastInp; public: void Initialize(); bool Run(); void Prompt(); String GetInput(); }; #endif
[ "j0sh.oleary11@gmail.com" ]
j0sh.oleary11@gmail.com
8140b9b18a091df34781050d65bf594b7dddb076
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_log_3389.cpp
3680e9c5201d2c703bce1a244710d8b004317184
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
238
cpp
ap_log_rerror(APLOG_MARK, APLOG_WARNING, apr_get_os_error(), r, APLOGNO(02116) "unrecognized result code %d " "from HttpExtensionProc(): %s ", rv, r->filename);
[ "993273596@qq.com" ]
993273596@qq.com
d89953d4b4c438b19a38f385b0aef2151e63283c
79c2d89bbfb0fcea09358e8fbee9187c40443b9b
/source/TonyHawksProSkater3.WidescreenFix/dllmain.cpp
eb0da877e62cf04e267b4060d87d0f0a536985fc
[ "MIT" ]
permissive
Sergeanur/WidescreenFixesPack
0d230f6ca733ac6e73a3e322f07db5b303c04fdf
7e159be860a870476a97c322a0c4dd244e50cee7
refs/heads/master
2020-04-01T04:49:49.295083
2018-10-13T15:54:55
2018-10-13T15:58:33
152,878,656
0
0
MIT
2018-10-13T14:12:39
2018-10-13T14:12:39
null
UTF-8
C++
false
false
5,501
cpp
#include "stdafx.h" #include <random> struct Screen { int32_t Width; int32_t Height; float fWidth; float fHeight; int32_t Width43; float fAspectRatio; float fAspectRatioDiff; int32_t FOV; float fHUDScaleX; float fHudOffset; float fHudOffsetReal; } Screen; void Init() { CIniReader iniReader(""); Screen.Width = iniReader.ReadInteger("MAIN", "ResX", 0); Screen.Height = iniReader.ReadInteger("MAIN", "ResY", 0); bool bFixHUD = iniReader.ReadInteger("MAIN", "FixHUD", 1) != 0; bool bRandomSongOrderFix = iniReader.ReadInteger("MAIN", "RandomSongOrderFix", 1) != 0; if (!Screen.Width || !Screen.Height) std::tie(Screen.Width, Screen.Height) = GetDesktopRes(); Screen.fWidth = static_cast<float>(Screen.Width); Screen.fHeight = static_cast<float>(Screen.Height); Screen.Width43 = static_cast<int32_t>(Screen.fHeight * (4.0f / 3.0f)); Screen.fAspectRatio = (Screen.fWidth / Screen.fHeight); Screen.fAspectRatioDiff = 1.0f / (Screen.fAspectRatio / (4.0f / 3.0f)); Screen.fHUDScaleX = 1.0f / Screen.fWidth * (Screen.fHeight / 480.0f); Screen.fHudOffset = ((480.0f * Screen.fAspectRatio) - 640.0f) / 2.0f; Screen.fHudOffsetReal = (Screen.fWidth - Screen.fHeight * (4.0f / 3.0f)) / 2.0f; //Resolution auto pattern = hook::pattern("C7 05 ? ? ? ? ? ? ? ? C7 05 ? ? ? ? ? ? ? ? B0 01 5F 5E"); //40B349 static int32_t* dword_851084 = *pattern.get_first<int32_t*>(2); static int32_t* dword_851088 = *pattern.get_first<int32_t*>(12); injector::MakeNOP(pattern.get_first(-12), 2, true); struct SetResHook { void operator()(injector::reg_pack& regs) { *dword_851084 = Screen.Width; *dword_851088 = Screen.Height; } }; injector::MakeInline<SetResHook>(pattern.get_first(0), pattern.get_first(20)); pattern = hook::pattern("C7 05 ? ? ? ? ? ? ? ? C7 05 ? ? ? ? ? ? ? ? C7 05 ? ? ? ? ? ? ? ? 89 2D"); //40B5B8 injector::MakeInline<SetResHook>(pattern.get_first(0), pattern.get_first(20)); pattern = hook::pattern("A3 ? ? ? ? 8B 04 AE 85 C0"); //40B835 40B84B injector::MakeInline<SetResHook>(pattern.count(2).get(0).get<void*>(0)); injector::MakeInline<SetResHook>(pattern.count(2).get(1).get<void*>(0)); //Aspect Ratio pattern = hook::pattern("89 4E 68 8B 50 04 89 56 6C 8B 46 04"); //0x5591B1 struct AspectRatioHook { void operator()(injector::reg_pack& regs) { *(float*)(regs.esi + 0x68) = *(float*)&regs.ecx / Screen.fAspectRatioDiff; *(float*)&regs.edx = *(float*)(regs.eax + 0x04); } }; injector::MakeInline<AspectRatioHook>(pattern.get_first(0), pattern.get_first(6)); //HUD if (bFixHUD) { pattern = hook::pattern("D8 0D ? ? ? ? 8B CF 89 5C 24 50 D8"); //0x58DDC8 injector::WriteMemory(*pattern.get_first<float*>(2), Screen.fHUDScaleX, true); pattern = hook::pattern("C1 E6 08 0B F2 89 70 64 A1"); //0x4F65AE struct HUDHook //sub_4F62A0 { void operator()(injector::reg_pack& regs) { if (*(float*)(regs.eax + 0x00) == 0.0f && *(float*)(regs.eax + 0x1C) == 0.0f && (int32_t)(*(float*)(regs.eax + 0x38)) == Screen.Width43 && (int32_t)(*(float*)(regs.eax + 0x54)) == Screen.Width43) { //blood overlay, maybe more //*(float*)(regs.eax + 0x00) += Screen.fHudOffsetReal; //*(float*)(regs.eax + 0x1C) += Screen.fHudOffsetReal; *(float*)(regs.eax + 0x38) += Screen.fHudOffsetReal * 2.0f; *(float*)(regs.eax + 0x54) += Screen.fHudOffsetReal * 2.0f; } else { *(float*)(regs.eax + 0x00) += Screen.fHudOffsetReal; *(float*)(regs.eax + 0x1C) += Screen.fHudOffsetReal; *(float*)(regs.eax + 0x38) += Screen.fHudOffsetReal; *(float*)(regs.eax + 0x54) += Screen.fHudOffsetReal; } regs.esi |= regs.edx; *(uint32_t*)(regs.eax + 0x64) = regs.esi; } }; injector::MakeInline<HUDHook>(pattern.get_first(0)); pattern = hook::pattern("8B 81 A4 00 00 00 89 46"); //0x4F66F0 struct HUDHook2 //sub_4F65E0 { void operator()(injector::reg_pack& regs) { *(float*)(regs.esi - 0x04) += Screen.fHudOffsetReal; regs.eax = *(uint32_t*)(regs.ecx + 0xA4); } }; injector::MakeInline<HUDHook2>(pattern.get_first(0), pattern.get_first(6)); } if (bRandomSongOrderFix) { pattern = hook::pattern("E8 ? ? ? ? 8B 96 E8"); struct RandomHook { void operator()(injector::reg_pack& regs) { std::mt19937 r{ std::random_device{}() }; std::uniform_int_distribution<uint32_t> uid(0, regs.eax); regs.eax = uid(r); } }; injector::MakeInline<RandomHook>(pattern.get_first(0)); } } CEXP void InitializeASI() { std::call_once(CallbackHandler::flag, []() { CallbackHandler::RegisterCallback(Init, hook::pattern("53 55 56 57 52 6A 00")); }); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if (reason == DLL_PROCESS_ATTACH) { } return TRUE; }
[ "thirteenag@gmail.com" ]
thirteenag@gmail.com
f6cd487cb63d36d26a4ed4ade00fbac6f44ad2a5
862a88b144cb7fca22a84d43b65a91f85027cbf0
/extensions/GUI/cocos2dx-better/src/CBGridView.cpp
4415b7b6af4aaf55bdd97da3a5130688aac0e040
[ "MIT" ]
permissive
live106/cocos2d-x-AoB
6edbb263bff9ab023da80f92fd68df49272d2851
11dfdf54d904bb25c963cf0846fdd3d224f07ba3
refs/heads/master
2020-12-25T02:20:43.013687
2014-11-06T08:17:16
2014-11-06T08:17:16
9,067,964
0
0
null
null
null
null
UTF-8
C++
false
false
5,702
cpp
/**************************************************************************** Author: Luma (stubma@gmail.com) https://github.com/stubma/cocos2dx-better 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 "CBGridView.h" #include "CCTableViewCell.h" USING_NS_CC_EXT; NS_CC_BEGIN CBGridView::CBGridView() : m_colCount(1) { } CBGridView* CBGridView::create(CBTableViewDataSource* dataSource, CCSize size) { return CBGridView::create(dataSource, size, NULL); } CBGridView* CBGridView::create(CBTableViewDataSource* dataSource, CCSize size, CCNode* container) { CBGridView* table = new CBGridView(); if(table->initWithViewSize(size, container)) { table->autorelease(); table->setDataSource(dataSource); table->_updateContentSize(); return table; } CC_SAFE_RELEASE(table); return NULL; } void CBGridView::setColCount(unsigned int cols) { m_colCount = cols; _updateContentSize(); } int CBGridView::__indexFromOffset(CCPoint offset) { int index = 0; CCSize cellSize; int col, row; float spaceWidth; cellSize = m_pDataSource->cellSizeForTable(this); switch(getDirection()) { case kCCScrollViewDirectionHorizontal: spaceWidth = getContainer()->getContentSize().height / m_colCount; col = (offset.y - (spaceWidth - cellSize.height) * 0.5) / spaceWidth; row = offset.x / cellSize.width; break; default: spaceWidth = getContainer()->getContentSize().width / m_colCount; col = (offset.x - (spaceWidth - cellSize.width) * 0.5) / spaceWidth; row = MAX(0, offset.y / cellSize.height); break; } index = col + row * m_colCount; return index; } CCPoint CBGridView::__offsetFromIndex(unsigned int index) { CCPoint offset; CCSize cellSize; float spaceWidth; int col, row; cellSize = m_pDataSource->cellSizeForTable(this); switch(getDirection()) { case kCCScrollViewDirectionHorizontal: row = index / m_colCount; col = index % m_colCount; spaceWidth = this->getContainer()->getContentSize().height / m_colCount; offset = ccp(row * cellSize.height, col * spaceWidth + (spaceWidth - cellSize.width) * 0.5); break; default: row = index / m_colCount; col = index % m_colCount; spaceWidth = this->getContainer()->getContentSize().width / m_colCount; offset = ccp(col * spaceWidth + (spaceWidth - cellSize.width) * 0.5, row * cellSize.height); break; } return offset; } void CBGridView::_updateCellPositions() { int cellsCount = m_pDataSource->numberOfCellsInTableView(this); m_vCellsPositions.resize(cellsCount + 1, 0.0); if(cellsCount > 0) { float currentPos = 0; CCSize cellSize; for(int i = 0; i < cellsCount; i++) { if(i > 0 && i % m_colCount == 0) { cellSize = m_pDataSource->tableCellSizeForIndex(this, i); switch(getDirection()) { case kCCScrollViewDirectionHorizontal: currentPos += cellSize.width; break; default: currentPos += cellSize.height; break; } } m_vCellsPositions[i] = currentPos; } // 1 extra value allows us to get right/bottom of the last cell m_vCellsPositions[cellsCount] = currentPos; } } void CBGridView::_updateContentSize() { CCSize size, cellSize, viewSize; unsigned int cellCount, rows; cellSize = m_pDataSource->cellSizeForTable(this); cellCount = m_pDataSource->numberOfCellsInTableView(this); viewSize = CCSizeMake(getViewSize().width/getContainer()->getScaleX(), getViewSize().height / getContainer()->getScaleY()); switch(getDirection()) { case kCCScrollViewDirectionHorizontal: rows = ceilf(cellCount / (float)m_colCount); size = CCSizeMake(MAX(rows * cellSize.width, viewSize.width), m_colCount * cellSize.height); break; default: rows = ceilf(cellCount/((float)m_colCount)); size = CCSizeMake(MAX(cellSize.width * m_colCount, viewSize.width), MAX(rows * cellSize.height, viewSize.height)); break; } setContentSize(size); } NS_CC_END
[ "wangyanan@gpp.com" ]
wangyanan@gpp.com
a95e2caada960ccd1c4730e1d9f4c378aa55da6b
acb84fb8d54724fac008a75711f926126e9a7dcd
/poj/poj2663.cpp
773ae3c7b0aa3e82132b9b6c6a8a03669f6c897e
[]
no_license
zrt/algorithm
ceb48825094642d9704c98a7817aa60c2f3ccdeb
dd56a1ba86270060791deb91532ab12f5028c7c2
refs/heads/master
2020-05-04T23:44:25.347482
2019-04-04T19:48:58
2019-04-04T19:48:58
179,553,878
1
0
null
null
null
null
UTF-8
C++
false
false
1,095
cpp
#include<cstdio> using namespace std; int H[9],P[100],X[100],tot; inline void add(int x,int y){ P[++tot]=y;X[tot]=H[x];H[x]=tot; } //0 有挡板 void find(int p,int x,int now,int t){ if(x==4) add(p,t); if(x>3) return; if((now&1)==0) find(p,x+1,now>>1,t+(1<<(x-1)));// 没挡板 if((now&3)==0) find(p,x+2,now>>2,t); if((now&1)!=0) find(p,x+1,now>>1,t); } int n,m; inline void mul(int a[][8],int b[][8]){ int c[8][8]={0}; for(int i=0;i<8;i++){ for(int j=0;j<8;j++){ for(int k=0;k<8;k++){ c[i][j]+=a[i][k]*b[k][j]; // if(c[i][j]>=m) c[i][j]%=m; } } } for(int i=0;i<8;i++) for(int j=0;j<8;j++) a[i][j]=c[i][j]; } int f[8][8]; int p[8][8]; int main(){ for(int i=0;i<1<<4;i++) find(i,1,i,0); for(int i=0;i<1<<4;i++){ for(int j=H[i];j;j=X[j]){ f[i][P[j]]=1; } } while(scanf("%d",&n)&&(~n)){ int t[8][8]={0}; t[0][0]=1; for(int i=0;i<8;i++){ for(int j=0;j<8;j++){ p[i][j]=f[i][j]; } } while(n){ if(n&1) mul(t,p); mul(p,p); n>>=1; } printf("%d\n",t[0][0]); } return 0; }
[ "zhangruotian@foxmail.com" ]
zhangruotian@foxmail.com
365bf36fb132af686524b42aa362972d8aa2f096
face0d0277b84d67deac5acf9a7a4abe7991762b
/L6/Q1/q1.cpp
368c065885f84703cb3208506da20d315fddc9bb
[]
no_license
anon766/DSL
48b53fd41bd57442181cbb8389c63a0f514a45df
0ee86275dbe5f6e51efd8b3a59a7ac3075356059
refs/heads/master
2022-12-28T15:38:05.764683
2020-02-08T14:03:16
2020-02-08T14:03:16
200,645,625
0
0
null
2020-10-13T19:22:29
2019-08-05T11:50:07
C++
UTF-8
C++
false
false
3,319
cpp
#include<bits/stdc++.h> using namespace std; class Node { public: int val; Node* next; Node(int a) { val=a; next=NULL; } }; Node* adjacencyList[100]; int dp[100][100]; bool used[100]; Node* resultStore; int src; bool isCycle; void insertResult(int ); void searchDFS(int ,int ); void insert(int ,int ); int main() { char v1,v2; string temp; int ch; src=-1; fstream file; file.open("L6_Q1_sample_input.txt"); if(!file.is_open()) cout<<"Unable to open input file."<<endl; do { cout<<"\t\t\tMENU\n\n"; cout<<"1. Insert Edges"<<endl; cout<<"2. BFS traversal"<<endl; cout<<"3. DFS traversal"<<endl; cout<<"4. Cycle finding in the graph"<<endl; cout<<"5. Calculate dmt of the graph"<<endl; cout<<"6. Exit"<<endl; cout<<"Enter choice: "; cin>>ch; switch(ch) { case 1: while(getline(file,temp)) { v1=temp[0]; v2=temp[2]; insert((int)v1-(int)'A',(int)v2-(int)'A'); insert((int)v2-(int)'A',(int)v1-(int)'A'); if(src==-1) src=(int)v1-(int)'A'; } break; case 2: { if(src==-1) break; resultStore=NULL; memset(used,false,sizeof(used)); insertResult(src); used[src]=true; while(resultStore!=NULL) { int v=resultStore->val; cout<<(char)(v+(int)'A')<<" "; Node* x=adjacencyList[v]; while(x!=NULL) { if(!used[x->val]) { insertResult(x->val); used[x->val]=true; } x=x->next; } resultStore=resultStore->next; } cout<<endl; break; } case 3: { if(src==-1) break; resultStore=NULL; memset(used,false,sizeof(used)); searchDFS(src,-1); Node* x=resultStore; while(x!=NULL) { cout<<(char)(x->val+(int)'A')<<" "; x=x->next; } cout<<endl; break; } case 4: { if(src==-1) break; resultStore=NULL; memset(used,false,sizeof(used)); isCycle=false; searchDFS(src,-1); if(isCycle) cout<<"Yes"<<endl; else cout<<"No"<<endl; break; } case 5: { if(src==-1) break; for(int i=0;i<100;i++) for(int j=0;j<100;j++) dp[i][j]=1000; for(int i=0;i<100;i++) { Node* x=adjacencyList[i]; while(x!=NULL) { dp[i][x->val]=1; dp[x->val][i]=1; x=x->next; } dp[i][i]=0; } for(int i=0;i<100;i++) for(int j=0;j<100;j++) for(int k=0;k<100;k++) if(dp[j][i]+dp[i][k]<dp[j][k]) dp[j][k]=dp[j][i]+dp[i][k]; int dmt=0; for(int i=0;i<100;i++) for(int j=0;j<100;j++) if(dp[i][j]!=1000 && dp[i][j]>dmt) dmt=dp[i][j]; cout<<"Diameter: "<<dmt<<endl; break; } default: break; } } while(ch!=6); file.close(); return 0; } void insert(int a,int b) { Node* x=adjacencyList[a]; if(x==NULL) adjacencyList[a]=new Node(b); else { while(x->next!=NULL) x=x->next; x->next=new Node(b); } return; } void insertResult(int a) { Node* x=resultStore; if(x==NULL) resultStore=new Node(a); else { while(x->next!=NULL) x=x->next; x->next=new Node(a); } return; } void searchDFS(int v,int p) { used[v]=true; insertResult(v); Node* x=adjacencyList[v]; while(x!=NULL) { if(!used[x->val]) searchDFS(x->val,v); else if(x->val!=p) isCycle=true; x=x->next; } return; }
[ "masih@omen" ]
masih@omen
03091b2dcc93df77ae435c10e9b1298e4ee20b88
e0f129d30ae2611fe1b78f11573a51df5af0945f
/rt-compact/src/light/distant.cpp
be799a6726211eec3f3b9535eecf469a1e2e08dc
[]
no_license
TianhuaTao/computer-graphics-assignment
1b8034fe72cf481bb352053842d3ef9116786176
4f1bddac59f0ecb6be2a82bd86b709f57a69195f
refs/heads/master
2022-11-10T02:03:55.090071
2020-06-21T06:39:29
2020-06-21T06:39:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,447
cpp
// // Created by Sam on 2020/6/16. // #include <core/prob.h> #include "distant.h" DistantLight::DistantLight(const Transform &LightToWorld, const Color &L, const Vector3f &wLight) : Light((int)LightFlags::DeltaDirection, LightToWorld, MediumInterface()), L(L), wLight(Normalize(LightToWorld(wLight))) {} Color DistantLight::Sample_Li(const Interaction &ref, const Point2f &u, Vector3f *wi, Float *pdf, VisibilityTester *vis) const { *wi = wLight; *pdf = 1; Point3f pOutside = ref.p + wLight * (2 * worldRadius); *vis = VisibilityTester(ref, Interaction(pOutside, ref.time, mediumInterface)); return L; } Color DistantLight::Power() const { return L * Pi * worldRadius * worldRadius; } Float DistantLight::Pdf_Li(const Interaction &, const Vector3f &) const { return 0.f; } std::shared_ptr<DistantLight> CreateDistantLight(const Transform &light2world, const ParamSet &paramSet) { Color L = paramSet.FindOneSpectrum("L", Color(1.0)); Color sc = paramSet.FindOneSpectrum("scale", Color(1.0)); Point3f from = paramSet.FindOnePoint3f("from", Point3f(0, 0, 0)); Point3f to = paramSet.FindOnePoint3f("to", Point3f(0, 0, 1)); Vector3f dir = from - to; return std::make_shared<DistantLight>(light2world, L * sc, dir); }
[ "tth135@126.com" ]
tth135@126.com
18073528c7c6e9612caa5418379206e78db4085b
b7dd7ddf80a2468244bf9479ee0916d3298629ed
/course_work/me537/project/simulation/ros_packages/unsuper_nn/src/evo_unsupervised_learner.h
740ccbe81007b3cb42fb6f404278b3a6e708a1a9
[]
no_license
kckemper/kemper
5550e3a0ce1814bd8963ca97cb4d7bacbb3fdbe8
a1c33d19363fa2a60f61a69d21b3dec6a2bddbad
refs/heads/master
2021-01-10T08:49:26.918463
2012-09-21T18:30:50
2012-09-21T18:30:50
52,307,308
0
0
null
null
null
null
UTF-8
C++
false
false
2,033
h
#include <stdio.h> #include <cv.h> #include <highgui.h> #include <math.h> #include <iostream> #include <fstream> #include "evo.h" #define NF 6 #define N_SLICES 8 // number of slices to make of the image #define N_STEPS 855 // number of images #define SIZE 16 // scaled image size #define N_LEARN 200 // number of images per learing episode #define N_EPISODES 50 // number of learning episodes #define N_TRIALS 10 // number of times to repeat the learning #define N_NETS 20 #define N_HIDDEN 16 #define PIX(img,x,y) ((uchar*)((img)->imageData + (img)->widthStep*(y)))[(x)] static void allocateOnDemand( IplImage **, CvSize, int, int); class EvoUnsupervisedLearner { private: CvPoint p,q; CvScalar line_color; CvScalar out_color; const char* name_orig; const char* name_ave; const char* name_weights; const char* inputCmdFile_name; const char* outputFile_name; FILE* outputFile; FILE* inputCmdFile; char inputName[128]; char outputName[128]; // Picture filenames. char sliced_filename[128]; char weight_filename[128]; CvCapture* capture; CvSize frame_size; CvScalar ave; CvRect slice_rect; CvSize slice_size; IplImage* frame; IplImage* frame_g; IplImage* frame_small; IplImage* frame_weights; IplImage* frame_w_big; IplImage* frame_w_final; IplImage* frame_final; IplImage* ave_image; // static IplImage *scale; IplImage* frame_slices[N_SLICES]; float inputs[(SIZE/N_SLICES)*SIZE]; float outputs[N_SLICES]; int choices[N_SLICES]; // float desired[N_SLICES]; // float desired[] = {0,0,0,1,1,0,0,0}; //XXX dummy test... //Evo (int nNets, int nInputs, int nHidden, int nOuts) Evo* evoSlice; int ep; int trial; int stepCnt; int flag; char c; int i,j,k,s; float tmp; public: EvoUnsupervisedLearner(); EvoUnsupervisedLearner(IplImage*); void initialize(int); char takeImage(IplImage*, int); void penalize(float); void decayPenalties(float); };
[ "kkemper@f5c5be9c-040c-f34b-f993-a0493b5d6c12" ]
kkemper@f5c5be9c-040c-f34b-f993-a0493b5d6c12
888ca9f0d4a48b0fd5b9fc6fd03a72dae4559ecf
7d8d3acacb099341f49bd740c1dc2637a0a7413d
/Code Chef/The Leaking Robot.cpp
bd9431f172dff8d158159dc664347304f1a6fd76
[]
no_license
himanshushukla254/BugFreeCodes
71c57023bac39dc9363321a063e0b398f8e23ae8
cf5bd96d8f67a99f107824a20afb54e0ad85e0b3
refs/heads/master
2020-12-03T10:25:52.635565
2016-05-14T11:53:50
2016-05-14T11:53:50
58,805,309
1
1
null
2016-05-14T11:52:15
2016-05-14T11:52:14
null
UTF-8
C++
false
false
674
cpp
//http://www.codechef.com/AUG14/problems/CRAWA //Ashish Kedia, NITK Surathkal //@ashish1294 #include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<algorithm> #include<vector> #include<queue> #include<utility> using namespace std; int main() { int t,x,y,f; scanf("%d",&t); while(t--) { scanf("%d%d",&x,&y); f=0; if(y>=0 && y%2==0 && x>=-y && x<=(y-1)) printf("YES\n"); else if(y<0 && y%2==0 && x>=y && x<=(1-y)) printf("YES\n"); else if(x>0 && x%2==1 && y>=(1-x) && y<=(x+1)) printf("YES\n"); else if(x<=0 && x%2==0 && y>=x && y<=(-x)) printf("YES\n"); else printf("NO\n"); } return 0; }
[ "ashish1294@gmail.com" ]
ashish1294@gmail.com
aebd755a9eeb9561ecb1b795045c9432cb58b451
84464965f202caa72fa395ddf997f026096524f7
/extra/server.cpp
f07fb29eb5fb1c02f70690bcfb3015f5390c2bb8
[]
no_license
dartuso/VeryStrangeWebProxy
fc9ae32b83018008d24d55fcf01c67fe366d8376
c44046b1b8a0538add9abc6e5e7badee504c1db3
refs/heads/master
2022-12-21T06:59:41.074151
2020-10-01T18:19:02
2020-10-01T18:19:02
238,564,500
0
0
null
null
null
null
UTF-8
C++
false
false
4,371
cpp
/* * A simple TCP server that echos messages back to the client. * This server works with only a single client. With a simple modification, it can take more clients. */ #include <iostream> #include <sys/socket.h> // for socket(), connect(), send(), and recv() #include <arpa/inet.h> // for sockaddr_in and inet_addr() #include <stdlib.h> // for atoi() and exit() #include <string.h> // for memset() #include <unistd.h> // for close() using namespace std; const int BUFFERSIZE = 32; // Size the message buffers const int MAXPENDING = 1; // Maximum pending connections int main(int argc, char *argv[]) { int serverSock; // server socket descriptor int clientSock; // client socket descriptor struct sockaddr_in serverAddr; // address of the server struct sockaddr_in clientAddr; // address of the client char inBuffer[BUFFERSIZE]; // Buffer for the message from the server int bytesRecv, bytes; // Number of bytes received int bytesSent; // Number of bytes sent // Check for input errors if (argc != 2) { cout << "Usage: " << argv[0] << " <Listening Port>" << endl; exit(1); } // Create a TCP socket // * AF_INET: using address family "Internet Protocol address" // * SOCK_STREAM: Provides sequenced, reliable, bidirectional, connection-mode byte streams. // * IPPROTO_TCP: TCP protocol if ((serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { cout << "socket() failed" << endl; exit(1); } // Free up the port before binding // * sock: the socket just created // * SOL_SOCKET: set the protocol level at the socket level // * SO_REUSEADDR: allow reuse of local addresses // * &yes: set SO_REUSEADDR on a socket to true (1) // * sizeof(int): size of the value pointed by "yes" int yes = 1; if (setsockopt(serverSock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) { cout << "setsockopt() failed" << endl; exit(1); } // Initialize the server information // Note that we can't choose a port less than 1023 if we are not privileged users (root) memset(&serverAddr, 0, sizeof(serverAddr)); // Zero out the structure serverAddr.sin_family = AF_INET; // Use Internet address family serverAddr.sin_port = htons(atoi(argv[1])); // Server port number serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface // Bind to the local address if (bind(serverSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { cout << "bind() failed" << endl; exit(1); } // Listen for connection requests if (listen(serverSock, MAXPENDING) < 0) { cout << "listen() failed" << endl; exit(1); } // set the size of the client address structure unsigned int size = sizeof(clientAddr); // Waiting for connection requests if ((clientSock = accept(serverSock, (struct sockaddr *) &clientAddr, &size)) < 0) { cout << "accept() failed" << endl; exit(1); } // The server will be blocked until a client is connected to it. cout << "Accepted a connection from " << inet_ntoa(clientAddr.sin_addr) << endl; // Start communication with the client (terminate when receive a "terminate" command) while (strncmp(inBuffer, "terminate", 9) != 0) { // Clear the buffers memset(&inBuffer, 0, BUFFERSIZE); // Receive the message from client bytesRecv = recv(clientSock, (char *) &inBuffer, BUFFERSIZE, 0); // Check for connection close (0) or errors (< 0) if (bytesRecv <= 0) { cout << "recv() failed, or the connection is closed. " << endl; exit(1); } cout << "Client: " << inBuffer; // Echo the message back to the client bytesSent = send(clientSock, (char *) &inBuffer, bytesRecv, 0); if (bytesSent < 0 || bytesSent != bytesRecv) { cout << "error in sending" << endl; exit(1); } } // Close the connection with the client close(clientSock); // Close the server socket close(serverSock); }
[ "daniel.artuso1@gmail.com" ]
daniel.artuso1@gmail.com
4ea7e418ebc21075e8753e710d576a7c1a4ca2a6
666e70c36b92a97a87de07ddc5c9f9ab1587de66
/str concat functin.cpp
c534ad16d3e161c33f944bd98d90e3c0d5370db6
[]
no_license
Manash-git/C-Programming-Study
f3a4e56a8fa09c974f5a11ac9f64141eeeb9a3cb
26562ab58c08d637cfbf5eeebb1690e2d16d6830
refs/heads/master
2021-07-16T03:25:45.497664
2017-10-23T19:54:45
2017-10-23T19:54:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
195
cpp
//#include<stdio.h> #include<bits/stdc++.h> int main(){ char name[]={"People's republic of "}; strcat(name,"Bangladesh"); puts(name); printf("\nLenght is : %d",strlen(name)); return 0; }
[ "manashmondalcse@gmail.com" ]
manashmondalcse@gmail.com
5f88846079f0df6e0c7be4a78cae069a59f8505a
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_log_6099.cpp
aa0b20086616fe7b8500998968195160da6ce3ce
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
195
cpp
ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, c, APLOGNO(03080) "h2_session(%ld): unknown state %d", session->id, session->state);
[ "993273596@qq.com" ]
993273596@qq.com
7ede46d46b1b8e6bf9b755e5e2f09fd0424c22f2
2b62400eb58ca6a93c66c0025a4c440496698f89
/SDPSeminarHomework(GraphAndTree)/SeminatTreeAndGraphTash/SeminatTreeAndGraphTash/Node.h
2a44e8e51b5d15cb2d6be42d7f0ac368fd0612de
[]
no_license
MPTGits/SDP_Tasks
040bccb2444e00a2d44d8640ce236943ad545944
f3eccdce298934e5414b67026bce7c482d054b3a
refs/heads/master
2020-05-25T19:20:58.269353
2019-05-22T02:33:46
2019-05-22T02:33:46
187,948,246
0
0
null
null
null
null
UTF-8
C++
false
false
159
h
#pragma once template <typename T> struct Node { T data; Node<T> *next; Node(T const& _data, Node<T>* _next = nullptr) : data(_data), next(_next){}; };
[ "mr.greend@abv.bg" ]
mr.greend@abv.bg
238fbf64b556953aa6aeca52a4c7fe8ffc573a4c
66634a99cf626b05174e583e92704903a9e006db
/include/cub/sched/Executor.h
7782a5df8e92d50bf5530ed675789b1046b3f17b
[ "Apache-2.0" ]
permissive
ccup/cub
069ce1f3a3d9ddf66c177e0cb6d29b1ec69cd9cf
41e1c1b44252f00021aa61f5f305488abad7b289
refs/heads/master
2022-06-19T08:12:42.286109
2022-05-20T16:31:36
2022-05-20T16:31:36
298,842,727
14
12
null
null
null
null
UTF-8
C++
false
false
1,237
h
#ifndef H441EB5A0_2E97_4187_AA21_FAB5C70470C0 #define H441EB5A0_2E97_4187_AA21_FAB5C70470C0 #include <cub/base/BaseTypes.h> #include <cub/sched/Synchronization.h> #include <condition_variable> #include <vector> #include <queue> #include <thread> #include <mutex> #include <future> #include <functional> #include <memory> CUB_NS_BEGIN struct Executor { Executor(size_t); ~Executor(); template<class F, class... Args> auto execute(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using ReturnType = typename std::result_of<F(Args...)>::type; auto task = std::make_shared< std::packaged_task<ReturnType()> >( std::bind(std::forward<F>(f), std::forward<Args>(args)...) ); std::future<ReturnType> res = task->get_future(); SYNCHRONIZED(tasksMutex) { tasks.emplace([task](){ (*task)(); }); } condition.notify_one(); return res; } private: void threadRun(); private: std::vector< std::thread > workers; std::queue< std::function<void()> > tasks; std::mutex tasksMutex; std::condition_variable condition; bool stop; }; CUB_NS_END #endif
[ "e.bowen.wang@icloud.com" ]
e.bowen.wang@icloud.com
334b648ecf34d61c1a1b7e28a88d3da82affe3a8
00948a19e63549ddfdea1f6e5ac55ffcfeb7c1b3
/utils/NN.h
031b2b12eb8695044b7b523e3c2ffc85c2972759
[ "MIT" ]
permissive
Voleco/bdexplain
6aa310cc9f4c11025d967e4c89aa9673053a708c
5e610155ad4cc0e9024d73497a8c88e33801e833
refs/heads/master
2021-07-04T09:06:10.217994
2019-04-04T13:04:53
2019-04-04T13:04:53
147,047,793
1
0
null
null
null
null
UTF-8
C++
false
false
1,710
h
#ifndef NN_H #define NN_H #include "FunctionApproximator.h" #include <vector> class NN : public FunctionApproximator { public: NN(int inputs, int hiddens, int outputs, double learnrate); NN(NN *); NN(FunctionApproximator *); NN(char *); ~NN(); void load(const char *); void load(FILE *); void load(const NN *); void load(const FunctionApproximator *fa) { load((NN*)fa); } static bool validSaveFile(char *fname); void save(const char *); void save(FILE *); double train(std::vector<double> &input, std::vector<double> &target); double *test(const std::vector<double> &input); double GetInput(std::vector<double> &input, const std::vector<double> &target); double train(std::vector<unsigned int> &input, std::vector<double> &target); double *test(const std::vector<unsigned int> &input); int getNumInputs() { return inputs; } double getInputWeight(int inp, int outp=0) { return weights[0][outp][inp]; } void Print(); private: void allocateMemory(const NN *nn = 0); void freeMemory(); std::vector< std::vector< std::vector<double> > > weights; std::vector< std::vector< std::vector<double> > > updatedweights; std::vector< std::vector< std::vector<double> > > errors; std::vector<double> hidden; std::vector<double> output; int inputs, hiddens, outputs; double g(double a); double dg(double a); double outputerr(const std::vector<double> &output, const std::vector<double> &expected, int which); double internalerr(const std::vector<double> &output, const std::vector<double> &expected, int which); double internalinputerr(const std::vector<double> &output, const std::vector<double> &expected, int which); double error(const std::vector<double> &outputs); }; #endif
[ "chenjingwei1991@gmail.com" ]
chenjingwei1991@gmail.com
ec84e4ae78fa7470f55e43f5f3c7a7cbd787ea9c
28ef30faa8122b3b68da10f79b047a6e2be32de0
/Modelos/Motor Diesel/simulation_model_motor_diesel_bueno/simulation_model_motor_diesel_bueno.ino
b3c57a381c11a3665712e8285eeae8b93961de55
[]
no_license
carmar14/Simulacion_ugrid
05f0c87248e0616a80571bfa3cc5f2c80b60b3a2
80529f394e1f5bf1a10de1ab0e3a75cd0a201846
refs/heads/master
2021-07-05T11:25:09.124412
2020-11-03T00:16:22
2020-11-03T00:16:22
197,256,159
0
0
null
null
null
null
UTF-8
C++
false
false
1,259
ino
#include <FreeRTOS_ARM.h> double TenK, VelK, KGen; double VelK1, TNK, TNK1; double PLK, PLK1, U[51]; double KGen = 1/2; bool r=false; void setup() { pinMode(52,OUTPUT); analogWriteResolution(12); analogReadResolution(12); Serial.begin(115200); xTaskCreate(motor, NULL,configMINIMAL_STACK_SIZE , NULL, 1, NULL); vTaskStartScheduler(); } static void motor(void* arg){ portTickType xLastWakeTime; xLastWakeTime = xTaskGetTickCount(); while(1){ r=true; digitalWrite(52,r); for (int j=50;j>0;j--) U[j] = U[j-1]; TNK1=TNK; VelK1 = VelK; PLK1=PLK; U[0]=analogRead(A0)*1/4095; // Acción al actuador PLK=analogRead(A1)*1/4095; // Par de carga Serial.print("Acción al Actuador = "); Serial.println(U[0]); Serial.print("Par de carga = "); Serial.println(PLK); TNK = (0.9231*TNK1) + (0.04423*(U[49]+U[50])) - PLK + (0.9231 * PLK1); VelK = (0.9997*VelK1) + (0.00015+(TNK+TNK1)); TenK = VelK * KGen; float Vel=VelK*4095/3.3; float Ten=TenK*4095/3.3; Serial.println("Velocidad = "); Serial.println(Vel); Serial.println("Tensión = "); Serial.println(Ten); r=!r; digitalWrite(52,r); vTaskDelayUntil(&xLastWakeTime, (10/portTICK_RATE_MS)); } } void loop() {}
[ "carmar141414@hotmail.com" ]
carmar141414@hotmail.com
d3e4eeb65b43aa862c38bc92bb620bb95d94cfc8
c7c6b0a5cdaa59fe515f4e1c767746a2c9fd4c5f
/apps/qdemo/MotionModel.hpp
14ec9c8c6cd5a0d9cd99e2865cfa96b4d34ae67c
[]
no_license
peter-popov/cppslam
bfb9236f590d887b077dc16eaedf31371968732c
8ef7abc7989fee833b55cd7cbcd433de7f4dd0df
refs/heads/master
2016-09-10T21:18:46.064541
2015-02-12T20:53:10
2015-02-12T20:53:10
26,655,903
2
0
null
null
null
null
UTF-8
C++
false
false
2,212
hpp
#pragma once #include <QtWidgets> #include <QtQml> #include "SimulationModel.hpp" class MotionSample : public QObject { Q_OBJECT Q_PROPERTY(Pose *startPose READ startPose) Q_PROPERTY(QQmlListProperty<Pose> samples READ samples) Q_PROPERTY(QQmlListProperty<Pose> moves READ moves) public: MotionSample(); MotionSample(QPointF pos, double dir); Pose *startPose() const { return m_startPose.get(); } QQmlListProperty<Pose> samples(); QQmlListProperty<Pose> moves(); void recalculate(Pose end_pose, std::array<double, 4> params); private: std::unique_ptr<Pose> m_startPose; QList<std::shared_ptr<Pose> > m_samples; QList<std::shared_ptr<Pose> > m_moves; }; class MotionModel : public QObject { Q_OBJECT Q_PROPERTY(MotionSample *straightMotion READ straightMotion) Q_PROPERTY(MotionSample *rotationMotion READ rotationMotion) Q_PROPERTY(double a0 READ a0 WRITE setA0 NOTIFY modelChanged) Q_PROPERTY(double a1 READ a1 WRITE setA1 NOTIFY modelChanged) Q_PROPERTY(double a2 READ a2 WRITE setA2 NOTIFY modelChanged) Q_PROPERTY(double a3 READ a3 WRITE setA3 NOTIFY modelChanged) signals: void modelChanged(); public: MotionModel(); MotionSample *straightMotion() { return &m_straightMotion; } MotionSample *rotationMotion() { return &m_rotationMotion; } std::array<double, 4> params(); double a0() const { return m_a0; } double a1() const { return m_a1; } double a2() const { return m_a2; } double a3() const { return m_a3; } void setA0(double v) { if (m_a0 == v) return; m_a0 = v; recalculate(); } void setA1(double v) { if (m_a1 == v) return; m_a1 = v; recalculate(); } void setA2(double v) { if (m_a2 == v) return; m_a2 = v; recalculate(); } void setA3(double v) { if (m_a3 == v) return; m_a3 = v; recalculate(); } private: void recalculate(); private: double m_a0; double m_a1; double m_a2; double m_a3; MotionSample m_straightMotion; MotionSample m_rotationMotion; };
[ "petro.popov@gmail.com" ]
petro.popov@gmail.com
320ea568caa1e69f1d20a299d8ab390a17846772
bbb240f6737d04fddb785b271c3a0852e0dd9c08
/Battle/Mine.h
ff50c58594332f76102062844802b491ff19810b
[]
no_license
pascaldevink/smashbattle
72e3fd34f43e077fd9dba41e0f470144583282b2
994e021b824a06dda405709ed3a9594dd5cedb5d
refs/heads/master
2021-01-15T13:19:45.562883
2013-12-16T01:46:22
2013-12-16T01:46:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
313
h
#ifndef _MINE_H #define _MINE_H #include "Bomb.h" #include "Player.h" #define MINE_W 6 #define MINE_H 4 class Mine : public Bomb { public: Mine(SDL_Surface * surface); int flash_interval; int flash_length; int flash_start; void process(); protected: void set_clips(); }; #endif
[ "bert@demontpx.com" ]
bert@demontpx.com
6e2de082929ed74593cdf69c8c135780a158ad2b
e1a24c5c0d710a20b2575f4ee6bc29ffd2321a82
/CodeChef-Programs/MARCHA1.cpp
5e0791a301156090f34bcd18c80743232f9d0e0e
[]
no_license
Anshu-ros/Cool-Practice-Programs
fc14a4703ea3e0da1b9033fef36f32657aa219fa
e0607d70e99e20359f713d10129ffc36a78460ad
refs/heads/master
2021-01-11T17:10:15.938767
2016-12-17T12:46:38
2016-12-17T12:46:38
79,729,412
1
0
null
null
null
null
UTF-8
C++
false
false
441
cpp
#include<stdio.h> int cc_payup(int *A,int m){ for(;*A!=0;A++){ if(*A==m){ return 1; } else if(*A<m){ return cc_payup(A+1,m-*A)||cc_payup(A+1,m); } } return 0; } int main(){ int A[1000],i,j,t,n,m; scanf("%d",&t); for(i=0;i<t;i++){ scanf("%d %d",&n,&m); for(j=0;j<n;j++){ scanf("%d",&A[j]); } A[n]=0; if(cc_payup(A,m)==1){ printf("Yes\n"); } else{ printf("No\n"); } } return 0; }
[ "faheemzunjani@gmail.com" ]
faheemzunjani@gmail.com
5f1d6668a8655ce3a7ddafd9d2e18e7f5e9ecd9f
c2d320626432c783b5f5090bfcc0ad56eb8d814c
/Backend/Parser/submissions/Assignment 12/68.cpp
dc16ceab9e4075481e66fe29eee1feb337c58c39
[]
no_license
shreysingla11/ssl-project
dbc5569ac2d83b359daa3eda67ab1083949ea160
1a6e7494074f74a61100c1d8d09e7709f7f4931c
refs/heads/master
2023-01-29T07:57:20.968588
2020-12-08T15:34:37
2020-12-08T15:34:37
304,885,246
0
0
null
null
null
null
UTF-8
C++
false
false
2,372
cpp
#include <iostream> #include <vector> #include <stack> using namespace std; struct node { int index; vector<int> successors; vector<int> predecessors; char going; bool visited; int t_i; int n_i; int friendsGoing; int friendsNotGoing; node () { going = '0'; friendsGoing = 0; friendsNotGoing = 0; visited = false; } }; struct graph { vector<node> vertices; }; int main() { graph g; stack <int > definitelyGoing; stack <int > definitelyNotGoing; int num; cin>>num; g.vertices.resize(num); for (int i = 0; i < num; ++i) { g.vertices[i].index=i; int T_i; int N_i; int Friend; cin>>T_i>>N_i; g.vertices[i].t_i=T_i; g.vertices[i].n_i=N_i; if (T_i == 0) { definitelyGoing.push(i); g.vertices[i].visited = true; } else if (T_i > N_i) { definitelyNotGoing.push(i); g.vertices[i].visited = true; } for (int j = 0; j < N_i; ++j) { cin>>Friend; g.vertices[i].successors.push_back(Friend); g.vertices[Friend].index=Friend; g.vertices[Friend].predecessors.push_back(i); } } int min = 0; int max = num; while (!definitelyGoing.empty()) { int temp = definitelyGoing.top(); min++; definitelyGoing.pop(); int size = g.vertices[temp].predecessors.size(); for (int i = 0; i < size; ++i) { g.vertices[g.vertices[temp].predecessors[i]]. friendsGoing++; if (g.vertices[g.vertices[temp].predecessors[i]].visited == false && g.vertices[g.vertices[temp].predecessors[i]].friendsGoing >= g.vertices[g.vertices[temp].predecessors[i]].t_i) { definitelyGoing.push(g.vertices[temp].predecessors[i]); g.vertices[g.vertices[temp].predecessors[i]].visited = true; } } } while (!definitelyNotGoing.empty()) { int temp = definitelyNotGoing.top(); max--; definitelyNotGoing.pop(); int size = g.vertices[temp].predecessors.size(); for (int i = 0; i < size; ++i) { g.vertices[g.vertices[temp].predecessors[i]]. friendsNotGoing++; if (g.vertices[g.vertices[temp].predecessors[i]].visited == false && g.vertices[g.vertices[temp].predecessors[i]].friendsNotGoing > g.vertices[g.vertices[temp].predecessors[i]].n_i - g.vertices[g.vertices[temp].predecessors[i]].t_i) { definitelyNotGoing.push(g.vertices[temp].predecessors[i]); g.vertices[g.vertices[temp].predecessors[i]].visited = true; } } } cout<<min<<" "<<max<<endl; return 0; }
[ "shreysingla2@gmail.com" ]
shreysingla2@gmail.com
7c772ad1efd1c6508cc0d06561d44a9e3b246ed8
6009e3237259cd78970abb6cc9c5654553a8d625
/jwspubctrl/sub_client.cpp
22ecb89f43e68b0b7bfd437c14bbacb1b29e31e8
[]
no_license
jmuncaster/jwspubctrl
70c05afa5c1b25540d132daf28f3ec14abadb158
c1abee0ec72d5618047f41a5ef429ffe6b4ca442
refs/heads/main
2023-05-10T16:42:04.854880
2023-04-27T19:01:11
2023-04-27T19:01:11
127,324,796
0
0
null
2023-04-27T19:01:13
2018-03-29T17:26:10
C++
UTF-8
C++
false
false
1,598
cpp
#include "sub_client.hpp" #include <jws/json_with_schema.hpp> #include <wspubctrl/sub_client.hpp> #include <functional> #include <memory> #include <string> namespace jwspubctrl { struct SubClient::Detail { Detail( const std::string& pub_uri, const jws::json& pub_schema) : _client(pub_uri) { _pub_validator = jws::load_validator(pub_schema); } wspubctrl::SubClient _client; jws::json_validator _pub_validator; }; SubClient::SubClient(const std::string& pub_uri, const jws::json& pub_schema) : _detail(new Detail(pub_uri, pub_schema)) { } SubClient::~SubClient() { } void SubClient::connect() { _detail->_client.connect(); } void SubClient::disconnect() { _detail->_client.disconnect(); } jws::json SubClient::poll_json(int timeout_ms) { auto data = _detail->_client.poll(timeout_ms); auto data_json = jws::json::parse(data); _detail->_pub_validator.validate(data_json); return data_json; } bool SubClient::poll_json(jws::json& data_json, int timeout_ms) { // Grab data, return if timeout std::string data; auto success = _detail->_client.poll(data, timeout_ms); if (!success) { return false; } // Validate json and return data_json = jws::json::parse(data); _detail->_pub_validator.validate(data_json); return true; } std::string SubClient::poll_string(int timeout_ms) { return _detail->_client.poll(timeout_ms); } bool SubClient::poll_string(std::string& data, int timeout_ms) { return _detail->_client.poll(data, timeout_ms); } }
[ "justin@muncaster.io" ]
justin@muncaster.io
b7aa01fed16438a76afe431923688efdf0176652
3701e5410478b44109411f72f522f91493d4525d
/factorial.cpp
d26f44ed50176dc177704d90e267e62407ef1273
[]
no_license
Alam11/metaprogramowanie
3cde320f436209ba6fb272455a54f58f8a893024
37438bd75b47bee365cb3f8b06422c6a74577b6c
refs/heads/master
2016-09-01T14:59:37.976477
2016-01-17T21:21:58
2016-01-17T21:21:58
49,573,945
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
template<int N> struct factorial { enum { val = factorial<N - 1>::val * N }; }; template<> struct factorial<0> { enum { val = 1 }; }; template<> struct factorial<1> { enum { val = 1 }; };
[ "morzydusza@gmail.com" ]
morzydusza@gmail.com
fe5bbfdca56fbafbd439210ecb2842329df90fe9
6bd21780b33b41379537636522deec004a492b51
/incredible_waasa1.ino
2f1e9f0594054acd1a21a3fba2fbaef750cb6e3c
[]
no_license
AnasBawazir/Control-DC-Motors-with-L293D-Motor-Driver-IC-Arduino
02a2f2bfb5e98c2ffcac1dd2ccdad5b44bfc4d66
d545c6444d33e1466229d27b563d8b52bef57cd0
refs/heads/master
2022-11-21T12:54:47.521898
2020-07-28T21:10:40
2020-07-28T21:10:40
283,327,872
0
0
null
null
null
null
UTF-8
C++
false
false
1,290
ino
int enA = 9; int in1 = 8; int in2 = 7; int enB = 3; int in3 = 5; int in4 = 4; void setup() { pinMode(enA, OUTPUT); pinMode(enB, OUTPUT); pinMode(in1, OUTPUT); pinMode(in2, OUTPUT); pinMode(in3, OUTPUT); pinMode(in4, OUTPUT); digitalWrite(in1, LOW); digitalWrite(in2, LOW); digitalWrite(in3, LOW); digitalWrite(in4, LOW); } void loop() { directionControl(); delay(1000); speedControl(); delay(1000); } void directionControl() { analogWrite(enA, 255); analogWrite(enB, 255); digitalWrite(in1, HIGH); digitalWrite(in2, LOW); digitalWrite(in3, HIGH); digitalWrite(in4, LOW); delay(2000); // Now change motor directions digitalWrite(in1, LOW); digitalWrite(in2, HIGH); digitalWrite(in3, LOW); digitalWrite(in4, HIGH); delay(2000); digitalWrite(in1, LOW); digitalWrite(in2, LOW); digitalWrite(in3, LOW); digitalWrite(in4, LOW); } void speedControl() { digitalWrite(in1, LOW); digitalWrite(in2, HIGH); digitalWrite(in3, LOW); digitalWrite(in4, HIGH); for (int i = 0; i < 256; i++) { analogWrite(enA, i); analogWrite(enB, i); delay(20); } for (int i = 255; i >= 0; --i) { analogWrite(enA, i); analogWrite(enB, i); delay(20); } digitalWrite(in1, LOW); digitalWrite(in2, LOW); digitalWrite(in3, LOW); digitalWrite(in4, LOW); }
[ "noreply@github.com" ]
AnasBawazir.noreply@github.com
f37fe918a5e5f9f8e63d18b002682a43b851b309
27e8b7337fa04d4e814b4cf162a561dac9c8b4f9
/linked_list.h
2c21ae9c8429d066bca49e19d5654a646ceea26b
[]
no_license
matt1moore/2020-DataStructures-PA5
9404487a8b97012081883ae1389bb131b6a8f17e
008c8a88499385fcac41e8867f427701619f1f14
refs/heads/main
2023-02-16T12:21:41.476872
2020-12-23T16:39:18
2020-12-23T16:39:18
328,014,668
0
0
null
null
null
null
UTF-8
C++
false
false
13,748
h
//---------------------------------------------------------------------- // FILE: linked_list.h // NAME: Matthew Moore // DATE: September, 2020 // DESC: Implements a linked list version of the list class. Elements // are added by default to the end of the list via a tail pointer. // Implemented sorting algorithms that sort lists in ascending order. //---------------------------------------------------------------------- #ifndef LINKED_LIST_H #define LINKED_LIST_H #include "list.h" #include <iostream> using namespace std; template<typename T> class LinkedList : public List<T> { public: LinkedList(); LinkedList(const List<T>& rhs); ~LinkedList(); LinkedList& operator=(const List<T>& rhs); void add(const T& item); bool add(size_t index, const T& item); bool get(size_t index, T& return_item) const; bool set(size_t index, const T& new_item); bool remove(size_t index); size_t size() const; void selection_sort(); void insertion_sort(); void merge_sort(); void quick_sort(); void sort(); private: struct Node { T value; Node* next; }; Node* head; Node* tail; size_t length; // helper to delete linked list void make_empty(); // helper functions for merge and quick sort Node * merge_sort(Node* left, int len); Node * quick_sort(Node* start, int len); }; template<typename T> LinkedList<T>::LinkedList() : head(nullptr), tail(nullptr), length(0) { } template<typename T> LinkedList<T>::LinkedList(const List<T>& rhs) : head(nullptr), tail(nullptr), length(0) { // defer to assignment operator *this = rhs; } // TODO: Finish the remaining functions below template<typename T> LinkedList<T>::~LinkedList() { Node * currNode = NULL; Node * nextNode = head; while (currNode != NULL) { // Traversal of Nodes in the list nextNode = currNode->next; // Deletes the current Node delete currNode; currNode = nextNode; } // Good practice to set head to NULL when list is empty head = NULL; } template<typename T> LinkedList<T>& LinkedList<T>::operator=(const List<T>& rhs) { int i = 1; if (this != &rhs) { // protects against self-assignment chance if (head != nullptr) { // Clears the lhs if not already clear ~LinkedList(); } Node * copyPtr = nullptr; Node * currPtr = rhs.head; while (currPtr != nullptr) { if (head == NULL) { // Sets the head to point to initial element copyPtr = new Node(currPtr->get(length,0)); head = copyPtr; } else { // Sets all next pointers to point new elements copyPtr->add(new Node(currPtr->get(length,i))); copyPtr = copyPtr->next; ++i; } currPtr = currPtr->next;; } } return *this; } template<typename T> void LinkedList<T>::add(const T& item) { // Assigns value to new node Node * newNode = new Node; newNode->value = item; if (head == NULL) { // List is empty if true head = newNode; tail = newNode; } else { // List contains elements tail->next = newNode; tail = newNode; } newNode->next = NULL; length = length + 1; } template<typename T> bool LinkedList<T>:: add(size_t index, const T& item) { if (index > length || index < 0) { // Invalid index return false; } Node * newNode = new Node; newNode->value = item; if (head == NULL) { // For an empty list head = newNode; tail = newNode; newNode->next = NULL; } else { // New node will be inserted at the index Node * currPtr = head; Node * prevPtr = NULL; size_t i = 0; while (i < index) { // Traverse list to the correct index prevPtr = currPtr; currPtr = currPtr->next; ++i; } if (i == 0) { // The element will be at head of the list head = newNode; newNode->next = currPtr; } else if (index == length) { // Case of adding element to the end newNode->next = NULL; prevPtr->next = newNode; tail = newNode; } else { // Regular case prevPtr->next = newNode; newNode->next = currPtr; } } length = length + 1; return true; } template<typename T> bool LinkedList<T>::get(size_t index, T& return_item) const { if (index >= length || index < 0) { // Invalid index return false; } else if (head == tail) { // One element in the list Node * currPtr = head; return_item = currPtr->value; return true; } else { Node * currPtr = head; for (size_t i = 0; i < index; ++i) { // Traverses until index number is hit currPtr = currPtr->next; } return_item = currPtr->value; return true; } } template<typename T> bool LinkedList<T>::set(size_t index, const T& new_item) { if (index >= length || index < 0) { return false; } else if (head == tail) { // One element in the list head->value = new_item; return true; } else { Node * currPtr = head; for (size_t i = 0; i < index; i++) { //Traversal of list until index is reached currPtr = currPtr->next; } // Set new value to the index value currPtr->value = new_item; return true; } } template<typename T> bool LinkedList<T>::remove(size_t index) { size_t i = 0; if (index >= length || index < 0) { return false; } else if (head == tail) { // Singular element in the list Node * currPtr = head; delete currPtr; head = nullptr; tail = nullptr; length = length - 1; return true; } else { Node * currPtr = head; Node * prevPtr = nullptr; while (i < index) { // Traversal of list until index is reached prevPtr = currPtr; currPtr = currPtr->next; ++i; } // Remove the value at this index and fix the pointers if (index == 0) { // Front of the list head = currPtr->next; } else if (index == length - 1) { // Element is at the end of the list tail = prevPtr; prevPtr->next = nullptr; } else { prevPtr->next = currPtr->next; } delete currPtr; length = length - 1; return true; } } template<typename T> size_t LinkedList<T>::size() const { return length; } template<typename T> void LinkedList<T>::selection_sort() { Node * outerNode = head; Node * innerNode = nullptr; Node * minNode = nullptr; Node * tmpNode = nullptr; Node * prevNode = nullptr; Node * prevMin = nullptr; Node * outerPrev = nullptr; if (head == NULL) { // No elements to sort !!! } else if (head == tail) { // There is only one element, so already sorted !!! } else { while (outerNode->next != NULL) { // Runs through list, finding the minimum in the unsorted section minNode = outerNode; innerNode = outerNode; prevMin = outerPrev; while (innerNode != NULL) { // Searches through unsorted region for smallest element if (innerNode->value < minNode->value) { // New minimum has been found minNode = innerNode; prevMin = prevNode; } prevNode = innerNode; innerNode = innerNode->next; } // Now swap the new min value into the first element of the unsorted portion if (outerNode == minNode) { // Case of equivalence, // Thus nothing happens } else if (outerNode == head) { // Case of outer node equalling head, swap occurs head = minNode; tmpNode = minNode->next; if (outerNode->next == minNode) { // Case of first and second element swapping minNode->next = outerNode; outerNode->next = tmpNode->next; } else { // Normal case minNode->next = outerNode->next; prevMin->next = outerNode; outerNode->next = tmpNode; } } else if (outerNode->next == minNode) { // Case of the outerNode and minimum Node being next to each other tmpNode = minNode->next; minNode->next = outerNode; outerPrev->next = minNode; outerNode->next = tmpNode; } else { // Regular swapping of nodes tmpNode = minNode->next; minNode->next = outerNode->next; outerPrev->next = minNode; prevMin->next = outerNode; outerNode->next = tmpNode; } if (minNode == tail) { // Used only in the first swap of a list of numbers tail = outerNode; outerNode->next = nullptr; } // Resets the outer node to the first element in the unsorted array outerNode = minNode->next; // A prev node must be set to the last element of the sorted region, for swapping outerPrev = minNode; } } length = size(); } template<typename T> void LinkedList<T>::insertion_sort() { Node * outerNode = head; Node * innerNode = nullptr; Node * innerPrev = head; Node * finalSorted = nullptr; // Generally the first sorted element Node * tmpNode = nullptr; Node * outerPrev = nullptr; if (head == NULL) { // No elements in the list } else if (head == tail) { // List is one element long and already sorted } else { // List has at least two elements while (outerNode->next != NULL) { finalSorted = outerNode; outerNode = outerNode->next; innerNode = head; if (outerNode == tail) { // Final element is being sorted tail = finalSorted; } // First element of unsorted portion initially set to head head = outerNode; if (innerNode->next == outerNode) { // Case 1: Inner node and outer node are adjacent tmpNode = outerNode->next; outerNode->next = innerNode; innerNode->next = tmpNode; } else { // Case 2: Normal case finalSorted->next = outerNode->next; outerNode->next = innerNode; if (finalSorted == tail) { // Last element to sort finalSorted->next = nullptr; } } while (outerNode != finalSorted && outerNode->value > innerNode->value) { // Outer prev is the final element in the sorted region here // Swapping of items next to each other if (outerNode == head) { head = innerNode; tmpNode = innerNode; innerNode->next = outerNode; outerNode->next = tmpNode->next; } else { // Normal swapping case tmpNode = innerNode; outerPrev->next = innerNode; innerNode->next = outerNode; outerNode->next = tmpNode->next; } // Shifting inner node to be the element to the right of the outer pointer outerPrev = innerNode; innerNode = outerNode->next; } // Reset the Nodes to their correct possitions outerNode = finalSorted; } } } template<typename T> void LinkedList<T>::merge_sort() { Node * i = head; int k = length - 1; // Value based upon index if (head == NULL) { // Case already sorted, 1 element } else if (head->next == NULL) { // Case already sorted, 1 element } else { // Normal case // head = merge_sort(i, k); } } template<typename T> void LinkedList<T>::quick_sort() { if (length <= 1) { return; } head = quick_sort(head, length); // Traverse list to set tail tail = head; while (tail->next != NULL) { tail = tail->next; } } /* CODE ERROR : SEG fault occurs upon the iteration where the list merges to reach a length of 4 Time Spent: Over 6 hours, unable to decipher how to initialize mergeHead pointer */ template<typename T> typename LinkedList<T>::Node * LinkedList<T>::merge_sort(Node * left, int len) { Node * right = left; size_t mid = 0; Node * mergeHead = left; Node * mergeTail = left; if (len > 1) { // As long as there are two or more elements while ((mid + 1) < (len / 2)) { // Traverses list to set the right Node to the start of right partition right = right->next; ++mid; } Node * leftTail = right; right = right->next; leftTail->next = NULL; ++mid; Node * leftPos = merge_sort(left, mid); Node * rightPos = merge_sort(right, len - mid); // Add smallest element first to the tmp linked list while (leftPos != NULL && rightPos != NULL) { if (leftPos->value <= rightPos->value) { // The value from the left partition is greater, so transfer the right value mergeTail->next = leftPos; mergeTail = leftPos; leftPos = leftPos->next; } else { // The value from the left partition is greater, so transfer the right value mergeTail->next = rightPos; mergeTail = rightPos; rightPos = rightPos->next; } } // Attatch the remaining elements in the partition if the end is not reached if (left != NULL) { mergeTail->next = left; } if (right != NULL) { mergeTail->next = right; } } return mergeHead; } template<typename T> typename LinkedList<T>::Node * LinkedList<T>::quick_sort(Node * left, int len) { Node * pivot = left; Node * smaller = NULL; Node * larger = NULL; Node * tmp = NULL; Node * tmpPivot = NULL; size_t smaller_len = 0; size_t larger_len = 0; // BEST CASE : List is either 1 or no elements if (len <= 1) { return left; } while (pivot->next != NULL) { // Partition elements until pivot is only element tmpPivot = pivot->next->next; if (pivot->next->value > pivot->value) { // Partition to front of larger list if true pivot->next->next = larger; larger = pivot->next; pivot->next = tmpPivot; ++larger_len; } else { // Partition to front of smaller list pivot->next->next = smaller; smaller = pivot->next; pivot->next = tmpPivot; ++smaller_len; } // Adjust remaining element in the pivot list pivot->next = tmpPivot; } smaller = quick_sort(smaller,smaller_len); larger = quick_sort(larger,larger_len); if (smaller == NULL) { // Pivot is the first element left = pivot; } else { // Reattatch all elements to the original list left = smaller; Node * theGluer = smaller; for (int i = 1; i < smaller_len; ++i) { // Traverse smaller list to final element theGluer = theGluer->next; } theGluer->next = pivot; } pivot->next = larger; return left; } template <typename T> void LinkedList<T>::sort() { quick_sort(); } #endif
[ "mmoore11@zagmail.gonzaga.edu" ]
mmoore11@zagmail.gonzaga.edu
09e432d03bb9691e45548ddec07c2917a50344f9
5d2177228b61c95e334491010611797b86552ec5
/psmg-oops/src/context/PValueSym.h
e1de0b3bd8e2537cf32542a974f343420dbf05ca
[]
no_license
fqiang/psmg
02d762cda9c03251d1d0878648e90a99aed0f271
474cd07a3e857e3880aec08dde77dca4830801dd
refs/heads/master
2021-01-10T19:02:59.059533
2015-07-17T02:58:03
2015-07-17T02:58:03
41,818,377
0
0
null
null
null
null
UTF-8
C++
false
false
883
h
/* * SymValue.h * * Created on: 22 Mar 2014 * Author: s0965328 */ #ifndef PVALUESYM_H_ #define PVALUESYM_H_ #include "PValue.h" class PValueSym : public PValue { public: string value; PValueSym(const string&); PValueSym(const PValueSym& other); virtual ~PValueSym(); virtual PValueSym* clone(); virtual PValueSym* plus(PValue* other); virtual PValueSym* accumulate(PValue* other); virtual PValueSym* minus(PValue* other); virtual PValueSym* neg(); virtual PValueSym* times(PValue* other); virtual PValueSym* divid(PValue* other); virtual PValueSym* power(PValue* other); virtual PValueSym* power(double&); virtual bool isGT(PValue* other); virtual bool isEQ(PValue* other); virtual bool isNE(PValue* other); virtual string toString(); virtual void calculateMemoryUsage(unsigned long&); private: PValueSym* error(); }; #endif /* PVALUESYM_H_ */
[ "f.qiang@gmail.com" ]
f.qiang@gmail.com
0ee6f8c1718f44606d2b48f8d3037073ee88f84f
4e971bd8f059f3fdb1cf29ec2f870cfb4e38021e
/Uppgift 3 - QuadTree/Projekt/Source/CommonUtilities/Line/Line.hpp
e864c75328f8aad0c827caca0961c3e2c7ce42a5
[]
no_license
godofnanners/Spelorienterade-datastrukturer-och-algoritmer
b0a810ba4009049705bd4cca740943b6bb7558e2
618054d8a301c82896c364f720403cc84f91aa1b
refs/heads/master
2022-12-29T03:04:15.430220
2020-10-21T00:05:53
2020-10-21T00:05:53
287,136,220
0
0
null
null
null
null
UTF-8
C++
false
false
2,744
hpp
#pragma once #include "Vector/Vector2.h" namespace CommonUtilities { template <class T> class Line { public: // Default constructor: there is no line, the normal is the zero vector. Line(); // Copy constructor. Line(const Line <T>& aLine); // Constructor that takes two points that define the line, the direction is aPoint1 -aPoint0. Line(const Vector2<T>& aPoint0, const Vector2<T>& aPoint1); // Init the line with two points, the same as the constructor above. void InitWith2Points(const Vector2<T>& aPoint0, const Vector2<T>& aPoint1); // Init the line with a point and a direction. void InitWithPointAndDirection(const Vector2<T>& aPoint, const Vector2<T>& aDirection); // Returns whether a point is inside the line: it is inside when the point is on the line or on the side the normal is pointing away from. bool IsInside(const Vector2<T>& aPosition) const; // Returns the direction of the line. const Vector2<T>& GetDirection() const; // Returns the normal of the line, which is (-direction.y, direction.x). const Vector2<T>& GetNormal() const; private: Vector2<T> myDirection; Vector2<T> myPoint; Vector2<T> myNormal; }; template<class T> inline Line<T>::Line() { myDirection = { 0,0 }; myPoint = { 0,0 }; } template<class T> inline Line<T>::Line(const Line<T>& aLine) { myDirection = aLine.myDirection; myPoint = aLine.myPoint; myNormal = aLine.myNormal; } template<class T> inline Line<T>::Line(const Vector2<T>& aPoint0, const Vector2<T>& aPoint1) { Vector2<T>unNormalizedDir = (aPoint1 - aPoint0); myDirection = unNormalizedDir.GetNormalized(); myPoint = aPoint0; myNormal = { -myDirection.y,myDirection.x }; } template<class T> inline void Line<T>::InitWith2Points(const Vector2<T>& aPoint0, const Vector2<T>& aPoint1) { Vector2<T>unNormalizedDir = (aPoint1 - aPoint0); myDirection = unNormalizedDir.GetNormalized(); myPoint = aPoint0; myNormal = { -myDirection.y,myDirection.x }; } template<class T> inline void Line<T>::InitWithPointAndDirection(const Vector2<T>& aPoint, const Vector2<T>& aDirection) { myPoint = aPoint; myDirection = aDirection.GetNormalized(); myNormal = { -myDirection.y,myDirection.x }; } template<class T> inline bool Line<T>::IsInside(const Vector2<T>& aPosition) const { Vector2<T> differenceVector = aPosition - myPoint; if (( differenceVector.Dot(myNormal)) <= 0) { return true; } return false; } template<class T> inline const Vector2<T>& Line<T>::GetDirection() const { return myDirection; // TODO: insert return statement here } template<class T> inline const Vector2<T>& Line<T>::GetNormal() const { return myNormal; // TODO: insert return statement here } }
[ "casper.martensson@telia.com" ]
casper.martensson@telia.com
bdc25bff4912ccea8ccba1cadcd78b4c9e7b2de2
fe22a9e12dd6bf68e5f133f083dd32e6ae989597
/SDL Animation/Event.cpp
6e8d917e7882254705b52d5144b38445123beb5f
[ "MIT" ]
permissive
akshay-vv/SDL-Tutorials
de6c3269d983f69685e3012edf0e5f196b04b74f
0768ef3c9104a7bc2905a79120b103caa72f86bf
refs/heads/master
2022-12-30T14:14:31.403496
2020-09-23T17:30:11
2020-09-23T17:30:11
289,952,906
0
0
null
null
null
null
UTF-8
C++
false
false
6,347
cpp
#include "Event.h" Event::Event() { keyStates.insert({SDLK_UP, false}); keyStates.insert({SDLK_DOWN, false}); keyStates.insert({SDLK_LEFT, false}); keyStates.insert({SDLK_RIGHT, false}); } Event::~Event() { //Do nothing } void Event::OnEvent(SDL_Event* Event) { switch (Event->type) { // case SDL_ACTIVEEVENT: { // switch (Event->active.state) { // case SDL_APPMOUSEFOCUS: { // if (Event->active.gain) // OnMouseFocus(); // else // OnMouseBlur(); // break; // } // case SDL_APPINPUTFOCUS: { // if (Event->active.gain) // OnInputFocus(); // else // OnInputBlur(); // break; // } // case SDL_APPACTIVE: { // if (Event->active.gain) // OnRestore(); // else // OnMinimize(); // break; // } // } // break; // } case SDL_KEYDOWN: { OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod); break; } case SDL_KEYUP: { OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod); break; } case SDL_MOUSEMOTION: { OnMouseMove(Event->motion.x, Event->motion.y, Event->motion.xrel, Event->motion.yrel, (Event->motion.state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0, (Event->motion.state & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0, (Event->motion.state & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0); break; } case SDL_MOUSEBUTTONDOWN: { switch (Event->button.button) { case SDL_BUTTON_LEFT: { OnLButtonDown(Event->button.x, Event->button.y); break; } case SDL_BUTTON_RIGHT: { OnRButtonDown(Event->button.x, Event->button.y); break; } case SDL_BUTTON_MIDDLE: { OnMButtonDown(Event->button.x, Event->button.y); break; } } break; } case SDL_MOUSEBUTTONUP: { switch (Event->button.button) { case SDL_BUTTON_LEFT: { OnLButtonUp(Event->button.x, Event->button.y); break; } case SDL_BUTTON_RIGHT: { OnRButtonUp(Event->button.x, Event->button.y); break; } case SDL_BUTTON_MIDDLE: { OnMButtonUp(Event->button.x, Event->button.y); break; } } break; } case SDL_JOYAXISMOTION: { OnJoyAxis(Event->jaxis.which, Event->jaxis.axis, Event->jaxis.value); break; } case SDL_JOYBALLMOTION: { OnJoyBall(Event->jball.which, Event->jball.ball, Event->jball.xrel, Event->jball.yrel); break; } case SDL_JOYHATMOTION: { OnJoyHat(Event->jhat.which, Event->jhat.hat, Event->jhat.value); break; } case SDL_JOYBUTTONDOWN: { OnJoyButtonDown(Event->jbutton.which, Event->jbutton.button); break; } case SDL_JOYBUTTONUP: { OnJoyButtonUp(Event->jbutton.which, Event->jbutton.button); break; } case SDL_QUIT: { OnExit(); break; } case SDL_SYSWMEVENT: { //Ignore break; } // case SDL_VIDEORESIZE: { // OnResize(Event->resize.w,Event->resize.h); // break; // } // case SDL_VIDEOEXPOSE: { // OnExpose(); // break; // } default: { OnUser(Event->user.type, Event->user.code, Event->user.data1, Event->user.data2); break; } } } void Event::OnInputFocus() { //Pure virtual, do nothing } void Event::OnInputBlur() { //Pure virtual, do nothing } void Event::OnKeyDown(SDL_Keycode sym, Uint16 mod) { //Pure virtual, do nothing } void Event::OnKeyUp(SDL_Keycode sym, Uint16 mod) { //Pure virtual, do nothing } void Event::OnMouseFocus() { //Pure virtual, do nothing } void Event::OnMouseBlur() { //Pure virtual, do nothing } void Event::OnMouseMove(int mX, int mY, int relX, int relY, bool Left, bool Right, bool Middle) { //Pure virtual, do nothing } void Event::OnMouseWheel(bool Up, bool Down) { //Pure virtual, do nothing } void Event::OnLButtonDown(int mX, int mY) { //Pure virtual, do nothing } void Event::OnLButtonUp(int mX, int mY) { //Pure virtual, do nothing } void Event::OnRButtonDown(int mX, int mY) { //Pure virtual, do nothing } void Event::OnRButtonUp(int mX, int mY) { //Pure virtual, do nothing } void Event::OnMButtonDown(int mX, int mY) { //Pure virtual, do nothing } void Event::OnMButtonUp(int mX, int mY) { //Pure virtual, do nothing } void Event::OnJoyAxis(Uint8 which, Uint8 axis, Sint16 value) { //Pure virtual, do nothing } void Event::OnJoyButtonDown(Uint8 which, Uint8 button) { //Pure virtual, do nothing } void Event::OnJoyButtonUp(Uint8 which, Uint8 button) { //Pure virtual, do nothing } void Event::OnJoyHat(Uint8 which, Uint8 hat, Uint8 value) { //Pure virtual, do nothing } void Event::OnJoyBall(Uint8 which, Uint8 ball, Sint16 xrel, Sint16 yrel) { //Pure virtual, do nothing } void Event::OnMinimize() { //Pure virtual, do nothing } void Event::OnRestore() { //Pure virtual, do nothing } void Event::OnResize(int w, int h) { //Pure virtual, do nothing } void Event::OnExpose() { //Pure virtual, do nothing } void Event::OnExit() { //Pure virtual, do nothing } void Event::OnUser(Uint8 type, int code, void* data1, void* data2) { //Pure virtual, do nothing }
[ "akshayvivekverma@gmail.com" ]
akshayvivekverma@gmail.com
da2e51cbed7582161cd0b1c2850e644d3725ae0a
d4388e906098bb45885ad218f655c4c80a40ec21
/src/toolkit/net/BaseSocket.cpp
b29deb3dca93e7b459c2842f3833848a3bb21375
[ "MIT" ]
permissive
jbinkleyj/toolkit
911ca3b10a1047da8ffde52904c39971e282e3b5
8d58e968047538ce83a7fe95fb3f0414875d2796
refs/heads/master
2020-05-16T12:01:57.540743
2019-04-14T21:34:48
2019-04-14T21:34:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
#include <toolkit/net/ipv4/TCPSocket.h> #include <toolkit/net/ipv4/Endpoint.h> namespace TOOLKIT_NS { namespace net { BaseSocket::~BaseSocket() { bsd::Socket::Shutdown(SHUT_RDWR); } ssize_t BaseSocket::Write(ConstBuffer data) { return bsd::Socket::Send(data.data(), data.size(), 0); } }}
[ "vladimir.menshakov@gmail.com" ]
vladimir.menshakov@gmail.com
c20bb8110790048f082bcbdbe67a7a5fc7793fba
d0fb46aecc3b69983e7f6244331a81dff42d9595
/avatar/src/model/QueryTimedResetOperateStatusResult.cc
d6026373b4746e8d520f52c27c19319bf505177e
[ "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
2,311
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/avatar/model/QueryTimedResetOperateStatusResult.h> #include <json/json.h> using namespace AlibabaCloud::Avatar; using namespace AlibabaCloud::Avatar::Model; QueryTimedResetOperateStatusResult::QueryTimedResetOperateStatusResult() : ServiceResult() {} QueryTimedResetOperateStatusResult::QueryTimedResetOperateStatusResult(const std::string &payload) : ServiceResult() { parse(payload); } QueryTimedResetOperateStatusResult::~QueryTimedResetOperateStatusResult() {} void QueryTimedResetOperateStatusResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; if(!dataNode["InstanceId"].isNull()) data_.instanceId = dataNode["InstanceId"].asString(); if(!dataNode["StatusStr"].isNull()) data_.statusStr = dataNode["StatusStr"].asString(); if(!dataNode["TenantId"].isNull()) data_.tenantId = dataNode["TenantId"].asString(); if(!dataNode["Status"].isNull()) data_.status = std::stol(dataNode["Status"].asString()); if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } std::string QueryTimedResetOperateStatusResult::getMessage()const { return message_; } QueryTimedResetOperateStatusResult::Data QueryTimedResetOperateStatusResult::getData()const { return data_; } std::string QueryTimedResetOperateStatusResult::getCode()const { return code_; } bool QueryTimedResetOperateStatusResult::getSuccess()const { return success_; }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
04b0871df3de974c8fcc4a7074f8ab3b99d24582
3d72414df47fe6572b166af5c10b8f4c8f9d35d4
/Minigin/FPSComponent.h
e1dfeeb516503ab48b436fce569b811aa39ae995
[]
no_license
Shadania/Minigin-DigDug
cdf3d11dfcca417a75e118c1c0cc4fb040e15cf4
25e5ee8c72e5da14c8b6012579b343b1447a8e16
refs/heads/master
2020-04-28T01:47:21.718367
2019-06-13T14:24:17
2019-06-13T14:24:17
174,872,049
0
0
null
null
null
null
UTF-8
C++
false
false
508
h
#pragma once #include "BaseComponent.h" #include "TextureComponents.h" namespace dae { class FPSComponent final : public BaseComponent { public: FPSComponent(const std::shared_ptr<Font> font, const Float4& color); virtual void Initialize() override; virtual void Update() override; void SetColor(const Float4& newColor); void SetFont(const std::shared_ptr<Font>& newFont); private: std::shared_ptr<TextComponent> m_spText; const std::shared_ptr<Font> m_spFont; Float4 m_Color; }; }
[ "sarah.druyts@gmail.com" ]
sarah.druyts@gmail.com
0766fa1050c80d364934f905f7932d4947368c85
3a65ed8a0635c498feb66c571daba4448352a8ed
/modules/rt/include/motis/rt/update_constant_graph.h
1c8606c9e5ca1c776e4496acdb149f173861e214
[ "Apache-2.0", "MIT" ]
permissive
julianharbarth/motis
e83e8bccd6b8c2025613d91dea715c0ec3055d5d
d5ded8b519a85809949f084ca7983a22180deb1a
refs/heads/master
2022-07-29T04:40:42.429723
2020-05-17T11:49:15
2020-05-17T11:49:15
264,986,758
0
0
MIT
2020-05-18T16:06:00
2020-05-18T15:47:50
null
UTF-8
C++
false
false
2,333
h
#pragma once #include "motis/core/schedule/schedule.h" namespace motis::rt { inline void constant_graph_add_route_node(schedule& sched, int route_index, station_node const* sn, bool in_allowed, bool out_allowed) { auto const route_offset = static_cast<uint32_t>(sched.station_nodes_.size()); auto const route_lb_node_id = route_offset + static_cast<uint32_t>(route_index); auto const cg_size = route_offset + sched.route_count_; auto const add_edge = [&](uint32_t const from, uint32_t const to, bool const is_exit) { auto& fwd_edges = sched.transfers_lower_bounds_fwd_[to]; if (std::find_if(begin(fwd_edges), end(fwd_edges), [&](auto const& se) { return se.to_ == from; }) == end(fwd_edges)) { fwd_edges.emplace_back(from, is_exit); } auto& bwd_edges = sched.transfers_lower_bounds_bwd_[from]; if (std::find_if(begin(bwd_edges), end(bwd_edges), [&](auto const& se) { return se.to_ == to; }) == end(bwd_edges)) { bwd_edges.emplace_back(to, !is_exit); } }; sched.transfers_lower_bounds_fwd_.resize(cg_size); sched.transfers_lower_bounds_bwd_.resize(cg_size); if (in_allowed) { add_edge(sn->id_, route_lb_node_id, false); } if (out_allowed) { add_edge(route_lb_node_id, sn->id_, true); } } inline void constant_graph_add_route_edge(schedule& sched, trip::route_edge const& route_edge) { auto const min_cost = route_edge->get_minimum_cost(); if (!min_cost.is_valid()) { return; } auto const update_min = [&](constant_graph& cg, uint32_t const from, uint32_t const to) { for (auto& se : cg[from]) { if (se.to_ == to) { se.cost_ = std::min(se.cost_, min_cost.time_); return; } } cg[from].emplace_back(to, min_cost.time_); }; auto const from_station_id = route_edge->from_->get_station()->id_; auto const to_station_id = route_edge->to_->get_station()->id_; update_min(sched.travel_time_lower_bounds_fwd_, to_station_id, from_station_id); update_min(sched.travel_time_lower_bounds_bwd_, from_station_id, to_station_id); } } // namespace motis::rt
[ "felix.guendling@gmail.com" ]
felix.guendling@gmail.com
8eb91ab194dcab357a9a76b41776e37e377fa042
0e0a887164b1e5478261faf0ddd33c694f20bdde
/src/caffe/CTPN/ctpn_layers.hpp
9c6684b89ae8faf1797d21c08774edb6ca034e08
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "LicenseRef-scancode-public-domain" ]
permissive
xyt2008/frcnn
86882aa0ffa376fa527006bdd32dc311161eeab8
32a559e881cceeba09a90ff45ad4aae1dabf92a1
refs/heads/master
2020-03-14T20:56:21.930791
2019-09-22T11:16:32
2019-09-22T11:16:32
131,785,765
0
0
NOASSERTION
2019-09-22T11:16:33
2018-05-02T02:10:55
C++
UTF-8
C++
false
false
4,808
hpp
#ifndef CAFFE_CTPN_LAYERS_HPP_ #define CAFFE_CTPN_LAYERS_HPP_ #include <string> #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layers/base_data_layer.hpp" #include "caffe/layer.hpp" #include "caffe/layers/loss_layer.hpp" //#include "caffe/neuron_layers.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief Long-short term memory layer. * fyk: the implementation is from https://github.com/junhyukoh/caffe-lstm * this code is a little quicker than the master branch of Caffe's implementation * TODO(dox): thorough documentation for Forward, Backward, and proto params. */ template <typename Dtype> class LstmLayer : public Layer<Dtype> { public: explicit LstmLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "Lstm"; } virtual bool IsRecurrent() const { return true; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); int I_; // input dimension int H_; // num of hidden units int T_; // length of sequence int N_; // batch size Dtype clipping_threshold_; // threshold for clipped gradient Blob<Dtype> bias_multiplier_; Blob<Dtype> top_; // output values Blob<Dtype> cell_; // memory cell Blob<Dtype> pre_gate_; // gate values before nonlinearity Blob<Dtype> gate_; // gate values after nonlinearity Blob<Dtype> c_0_; // previous cell state value Blob<Dtype> h_0_; // previous hidden activation value Blob<Dtype> c_T_; // next cell state value Blob<Dtype> h_T_; // next hidden activation value // intermediate values Blob<Dtype> h_to_gate_; Blob<Dtype> h_to_h_; }; template <typename Dtype> class TransposeLayer : public Layer<Dtype> { public: explicit TransposeLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "Transpose"; } virtual inline int ExactNumBottomBlobs() const { return 1; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); private: TransposeParameter transpose_param_; vector<int> permute(const vector<int>& vec); Blob<int> bottom_counts_; Blob<int> top_counts_; Blob<int> forward_map_; Blob<int> backward_map_; Blob<int> buf_; }; template <typename Dtype> class ReverseLayer : public Layer<Dtype> { public: explicit ReverseLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "Reverse"; } virtual inline int ExactNumBottomBlobs() const { return 1; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); private: ReverseParameter reverse_param_; Blob<int> bottom_counts_; int axis_; }; } // namespace caffe #endif // CAFFE_CTPN_LAYERS_HPP_
[ "fymkang@gmail.com" ]
fymkang@gmail.com
0ba2250ec26863b26b081691e156d8bb0c18fd17
bdda98f269400b13dfb277d52da4cb234fd4305c
/CVGCom_async/forms/Unit_Result_1.h
4c19fb8c44e83d28d5dcb4a5e35e7b618c7e6e28
[]
no_license
fangxuetian/sources_old
75883b556c2428142e3323e676bea46a1191c775
7b1b0f585c688cb89bd4a23d46067f1dca2a17b2
refs/heads/master
2021-05-11T01:26:02.180353
2012-09-05T20:20:16
2012-09-05T20:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,439
h
//===========================================================================- #ifndef Unit_Result_1H #define Unit_Result_1H //===========================================================================- #include <Classes.hpp> #include <Controls.hpp> #include <Grids.hpp> #include <ComCtrls.hpp> #include <ExtCtrls.hpp> #include <StdCtrls.hpp> #include <Dialogs.hpp> #include <Buttons.hpp> //===========================================================================- class Tform_Result_1 : public TForm { __published: TTabControl *TabControl1; TStringGrid *StringGrid1; TPanel *Panel1; TButton *Button1; TSaveDialog *SaveDialog1; TPanel *Panel2; TLabel *Label2; TEdit *Edit1; TLabel *Label4; TLabel *Label3; TComboBox *ComboBox1; TLabel *Label1; TComboBox *ComboBox2; TButton *Button4; TEdit *Edit3; TLabel *Label5; TLabel *Label6; TLabel *Label7; TEdit *Edit2; TSpeedButton *SpeedButton1; TSpeedButton *SpeedButton2; TSpeedButton *speedbutton_ConvertToFreq; TButton *Button2; void __fastcall FormShow(TObject *Sender); void __fastcall TabControl1Change(TObject *Sender); void __fastcall Button1Click(TObject *Sender); void __fastcall Button2Click(TObject *Sender); void __fastcall SpeedButton1Click(TObject *Sender); void __fastcall FormActivate(TObject *Sender); void __fastcall Button4Click(TObject *Sender); void __fastcall SpeedButton2Click(TObject *Sender); void __fastcall speedbutton_ConvertToFreqClick(TObject *Sender); void __fastcall Panel1DblClick(TObject *Sender); private: CCollectionStorage<float> *pStorage; TSelectPart *pSelecetStorageParts; bool *pisSelecetStorageParts; int *pCountSelectedStorageParts; double SKOCoef; bool isConvertToFreq; public: void SetupTableValues(int aIndex); void SetupForms( CCollectionStorage<float> *apStorage, TSelectPart *apSelecetStorageParts, bool *apisSelecetStorageParts, int *apCountSelectedStorageParts ); virtual __fastcall Tform_Result_1(TComponent* AOwner); }; //===========================================================================- extern PACKAGE Tform_Result_1 *form_Result_1; //===========================================================================- #endif
[ "pm@pm.(none)" ]
pm@pm.(none)
125aa9580c6b91baccdf14cb9b939630a1c5c6e9
5499e8b91353ef910d2514c8a57a80565ba6f05b
/sdk/lib/sys/cpp/file_descriptor.cc
715c88a78f1d915c74873fd36f9d60ab580f5bdf
[ "BSD-3-Clause" ]
permissive
winksaville/fuchsia
410f451b8dfc671f6372cb3de6ff0165a2ef30ec
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
refs/heads/master
2022-11-01T11:57:38.343655
2019-11-01T17:06:19
2019-11-01T17:06:19
223,695,500
3
2
BSD-3-Clause
2022-10-13T13:47:02
2019-11-24T05:08:59
C++
UTF-8
C++
false
false
704
cc
// Copyright 2019 The Fuchsia 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 <lib/fdio/fd.h> #include <lib/sys/cpp/file_descriptor.h> #include <lib/zx/handle.h> #include <zircon/processargs.h> namespace sys { fuchsia::sys::FileDescriptorPtr CloneFileDescriptor(int fd) { zx::handle handle; zx_status_t status = fdio_fd_clone(fd, handle.reset_and_get_address()); if (status != ZX_OK) return nullptr; fuchsia::sys::FileDescriptorPtr result = fuchsia::sys::FileDescriptor::New(); result->type0 = PA_HND(PA_FD, fd); result->handle0 = std::move(handle); return result; } } // namespace sys
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
27c20abbc140cad67235bb308f4b47da6751ac87
c181ce8b03960ee3bc3ae56680554ecc3a9a9bfc
/Linked List/Linked List/linkedList.h
3a13fa983f1e8c4fffd284fc3c5be95e5fbb6764
[ "MIT" ]
permissive
uhzair/Data-Structures-and-Algorithms
a975c08289b95fd06dddc632e9c75403382464c2
08ab359c0f15f79998e35391852973a78c9e68eb
refs/heads/master
2020-03-09T14:11:52.835371
2019-02-02T12:57:08
2019-02-02T12:57:08
128,828,924
0
0
null
null
null
null
UTF-8
C++
false
false
661
h
#include "node.h" #ifndef _linkedList_H #define _linkedList_H template<class TYPE> class linkedList { public: linkedList(); linkedList(const linkedList &); bool isEmpty() const; bool inList(TYPE) const; void insertFirst(TYPE); void insertLast(TYPE); void insertBefore(TYPE, TYPE); void insertAfter(TYPE, TYPE); void deleteFirst(); void deleteLast(); void deleteNode(TYPE); void print() const; void makeEmpty(); void merge(linkedList<TYPE> &); linkedList<TYPE> split(int); linkedList<TYPE>& operator=(const linkedList<TYPE> &); Node<TYPE>& operator[](int index); ~linkedList(); private: Node<TYPE> *first; }; #endif #include "linkedList.cpp"
[ "hey@illicitr.us" ]
hey@illicitr.us
add9d8623ba8a67850102008796590e09e58cb79
b81c57e5fc621d425d0f34e685b6d566f1b908a9
/include/feedForwardFunctions.hpp
6f784176a9230e0087e06903254c2b2ea34dbf33
[]
no_license
AaronMathankeri/project-basicNN
69acf94d08475ce267cbf7ac44078a65020dda5d
157ff5556a3c98950bd40fed83de8eca3b1a53c0
refs/heads/master
2021-06-15T18:03:45.440804
2017-03-21T13:07:05
2017-03-21T13:07:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
775
hpp
/** * \file feedForwardFunctions.hpp * \brief declare feed forward network functions * * Detailed description * */ #ifndef FEEDFORWARDFUNCTIONS_H #define FEEDFORWARDFUNCTIONS_H #include <iostream> #include "mkl.h" #include "mlpParameters.hpp" #include "networkAgnosticFunctions.hpp" using namespace std; //----------------------------------------------------- // Feed-forward Functions void computeActivations( float* x, float* firstLayerWeightMatrix, float* a); void computeHiddenUnits( float* a, float* z, int length); void computeOutputActivations( float* z, float* secondLayerWeightVector, float* v); //----------------------------------------------------- //void logisticSigmoid( float * a , float *sigma, int length); #endif /* FEEDFORWARDFUNCTIONS_H */
[ "aaron@quantifiedag.com" ]
aaron@quantifiedag.com
ca96460389522ecf52ca4bc58ac7882383d37e46
94dbfcf94dd0a61d7cd197cf996602d5a2acdda7
/weekly_contest/231/leetcode_1785_minimum-elements-to-add-to-form-a-given-sum.cpp
618d2cc0914dc8757ba38c327a25e6c2f688f404
[]
no_license
PengJi/Algorithms
46ac90691cc20b0f769374ac3d848a26766965b1
6aa26240679bc209a6fd69580b9c7994cef51b54
refs/heads/master
2023-07-21T05:57:50.637703
2023-07-07T10:16:48
2023-07-09T10:17:10
243,935,787
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
/** * 1785. 构成特定和需要添加的最少元素 * https://leetcode-cn.com/problems/minimum-elements-to-add-to-form-a-given-sum/ */ class Solution { public: int minElements(vector<int>& nums, int limit, int goal) { long cur_sum=0; for(int i = 0; i < nums.size(); i++) { cur_sum += nums[i]; } long goal_sum = abs(goal - cur_sum); if(goal_sum % limit == 0) { return goal_sum/limit; } else { return goal_sum/limit+1; } } };
[ "jipengpro@gmail.com" ]
jipengpro@gmail.com
06af317d1e026577fa116d9ea88b332fdf437016
12e7bd84511b61bbde2288ae695ee64746d337a7
/Stronger/746.使用最小花费爬楼梯.cpp
e71778f845c2241fb7d1b09aded2d5cc7fcb9d53
[]
no_license
hellozmz/LeetCode
97ec70e9c80e601a7cb8ed0efea9ceca30e6843f
05295f388d5952a408d62ba34f6d4fde177f31c4
refs/heads/master
2023-05-11T10:47:26.792395
2023-04-29T05:27:55
2023-04-29T05:27:55
235,086,823
1
3
null
null
null
null
UTF-8
C++
false
false
1,931
cpp
/* * @lc app=leetcode.cn id=746 lang=cpp * * [746] 使用最小花费爬楼梯 * * https://leetcode.cn/problems/min-cost-climbing-stairs/description/ * * algorithms * Easy (63.24%) * Likes: 1025 * Dislikes: 0 * Total Accepted: 254.3K * Total Submissions: 401.8K * Testcase Example: '[10,15,20]' * * 给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。 * * 你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。 * * 请你计算并返回达到楼梯顶部的最低花费。 * * * * 示例 1: * * * 输入:cost = [10,15,20] * 输出:15 * 解释:你将从下标为 1 的台阶开始。 * - 支付 15 ,向上爬两个台阶,到达楼梯顶部。 * 总花费为 15 。 * * * 示例 2: * * * 输入:cost = [1,100,1,1,1,100,1,1,100,1] * 输出:6 * 解释:你将从下标为 0 的台阶开始。 * - 支付 1 ,向上爬两个台阶,到达下标为 2 的台阶。 * - 支付 1 ,向上爬两个台阶,到达下标为 4 的台阶。 * - 支付 1 ,向上爬两个台阶,到达下标为 6 的台阶。 * - 支付 1 ,向上爬一个台阶,到达下标为 7 的台阶。 * - 支付 1 ,向上爬两个台阶,到达下标为 9 的台阶。 * - 支付 1 ,向上爬一个台阶,到达楼梯顶部。 * 总花费为 6 。 * * * * * 提示: * * * 2 <= cost.length <= 1000 * 0 <= cost[i] <= 999 * * */ // @lc code=start class Solution { public: int minCostClimbingStairs(vector<int>& cost) { int len = cost.size(); vector<int> dp(len + 1); dp[0] = 0; dp[1] = 0; for (int i = 2; i <= len; ++i) { dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } return dp[len]; } }; // @lc code=end
[ "407190054@qq.com" ]
407190054@qq.com
e0a85653a9a10f8f9d689f8a04ebfc1ae1c3a4a1
fb188ae45fe8945ba757599b71e2e34c5d095d8c
/Trash/prueba_abstracta001/src/Proceso.cpp
e0525348acecf32a944cdccdafa49b1dfce3cc31
[]
no_license
patrick03524/Algebra-Abstracta
f8726085ddcb4316d77bc1ac2ecd9c2f5c45de1c
bd92d3bf20234b87daa5c0c8fe808eed0673e1a7
refs/heads/master
2021-04-18T20:22:19.305662
2018-06-02T11:25:07
2018-06-02T11:25:07
126,630,623
0
0
null
null
null
null
UTF-8
C++
false
false
670
cpp
#include "Proceso.h" Proceso::Proceso(unsigned int n_cuadrados, unsigned int n_len_cuadrado, string mensaje1) { n=n_cuadrados; n_len=n_len_cuadrado; mensaje=mensaje1; } string Proceso::encriptacion() { string mensaje_encriptado1; unsigned int cont=0; for(int i = 0; i<n_len; i++){ for(int j = 0; j<n_len; j++){ ///mensaje_encriptado.insert(mensaje_encriptado.begin()+i+n_len-i, mensaje[j*n_len+n_len-i]); mensaje_encriptado1.insert(mensaje_encriptado1.begin()+j*n_len+n_len-i, mensaje[cont]); cont++; } } cout << mensaje_encriptado1<<endl; } void Proceso::desencriptacion(string) { }
[ "patrick03524@hotmail.com" ]
patrick03524@hotmail.com
f6cb00583613ba59ca273fc04efbcd344c107043
1e2908e99ff62132291883e07f55ba41813236cd
/DP_Frog.cpp
5d5f211d3cf73554d661342afdf1b8ea6b1078ae
[]
no_license
dev625/dsacpp
f68b0850a7c22dc51c58512ecbb54df272f8bfa9
1de18d761a6a68eb5b9e8aa19b1a6659a6648ed6
refs/heads/master
2023-09-04T01:00:52.085101
2021-11-07T17:13:47
2021-11-07T17:13:47
281,089,207
0
0
null
null
null
null
UTF-8
C++
false
false
753
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long int; constexpr long long int MOD = 1e9 + 7; #define pb push_back #define ppb pob_back #define pf push_front #define ppf pop_front #define fr first #define sc second #define vi vector<int> #define pii pair<int, int> void solve() { int n; cin >> n; vi V(n); for (int i = 0; i < n; i++) cin >> V[i]; vi dp(n); dp[0] = 0; dp[1] = abs(V[1] - V[0]); for (int i = 2; i < n; i++) { dp[i] = min(dp[i - 1] + abs(V[i] - V[i - 1]), dp[i - 2] + abs(V[i] - V[i - 2])); } cout << dp[n - 1]; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 1; while (t--) { solve(); } }
[ "witdx514@gmail.com" ]
witdx514@gmail.com
dd9669aab3af03f19e09e042e3501313488d2640
f6814ecdd2f2ecd2dd1d08bf33ec86f50ace4c77
/多线程顺序打印ABC.cpp
980b8beb3e2a3635035ab8e9afecec09e23076a4
[]
no_license
hp2362/multi-thread-
ea4bf320aad195b4c0d857b491e23bd0ceeb382e
15fab89ffaf55c65eed878efa75a255a3b2f6664
refs/heads/master
2021-01-16T21:11:58.722779
2017-08-14T10:18:45
2017-08-14T10:18:45
100,220,953
0
0
null
null
null
null
UTF-8
C++
false
false
1,430
cpp
 #include<stdio.h> #include<pthread.h> void *secondFunc(void *); void *thirdFunc(void *); void *firstFunc(void *args) { pthread_t id2; pthread_create(&id2, NULL, &secondFunc, NULL); pthread_join(id2, NULL); printf("C\n"); } void *secondFunc(void *args) { pthread_t id3; pthread_create(&id3, NULL, &thirdFunc, NULL); pthread_join(id3, NULL); printf("B\n"); } void *thirdFunc(void *args) { printf("A\n"); } int main() { pthread_t id1; pthread_create(&id1, NULL, &firstFunc, NULL); pthread_join(id1, NULL); return 0; } /* #include<stdio.h> #include<sys/types.h> #include<semaphore.h> #include<pthread.h> sem_t sem_id1, sem_id2, sem_id3; void* func1(void*);    //声明 void* func2(void*); void* func3(void*); int main(void) { sem_init(&sem_id1, 0, 1);    //活动 sem_init(&sem_id2, 0, 0); sem_init(&sem_id3, 0, 0); pthread_t pthread_id1, pthread_id2, pthread_id3; pthread_create(&pthread_id1, NULL, func1, NULL); pthread_create(&pthread_id2, NULL, func2, NULL); pthread_create(&pthread_id3, NULL, func3, NULL); pthread_join(phread_id1, NULL); pthread_join(phread_id1, NULL); pthread_join(phread_id1, NULL); return 0; } void *func1(void*) { sem_wait(sem_id1); printf("A\n"); sem_post(sem_id2); } void *func2(void*) { sem_wait(sem_id2); printf("B\n"); sem_post(sem_id3); } void *func3(void*) { sem_wait(sem_id3); printf("C\n"); sem_post(sem_id1); } */
[ "964358093@qq.com" ]
964358093@qq.com
76c29ba0504a684f1f951c896930127990f3e627
5582ee978d276fa40669bcf2d0cabc1e93e71246
/HelloWorldBorland/main.cpp
724e489aaaf01cb590274c33fcd83c4465f2ca22
[]
no_license
amovsesy/trainings
9e42c2065deeab6659e9f1b46054b5001a7dbb33
8e08ddfb646f87ed605897c30568ce80ea3896eb
refs/heads/master
2020-04-03T17:39:21.155599
2018-10-30T21:46:19
2018-10-30T21:46:19
155,454,129
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <iostream> // required for 'cout' #include <conio.h> // required for 'getch' using namespace std; // activates the standard namespace int main() { cout << "Hello World!" << endl; cout << endl << "Press any key" << endl; getch(); return 0; }
[ "noreply@github.com" ]
amovsesy.noreply@github.com
f765701410bf67d0526b1f077fba5865683e4af9
4e51cfcb0621b88ea8620f05f49bedae2a2c9978
/Algorithms/0. temp.cpp
5157cca3c7056cd38da454ecf3ffe2a6205b775e
[]
no_license
KaiqiaoTian/LeetCode_practice
d5d43525269a05a0fc9a367bc4dcd3d15dcf3c74
a300d0380a01d0b48c4074718d30056e2b2a6c20
refs/heads/master
2023-05-28T11:17:18.473716
2021-06-11T19:55:52
2021-06-11T19:55:52
375,115,531
0
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
/*Description */ class Solution { public: vector<int> runningSum(vector<int>& nums) { vector<int> result = {nums[0]}; for(int i = 1; i < nums.size(); i++){ result.push_back(result.back()+nums[i]); } return result; } };
[ "kaiqiaotian@gmail.com" ]
kaiqiaotian@gmail.com
c0210268585f22b512d48b7f1ff6a502407367f6
60a532f91b8e51b7e504c0422f47708772b5c205
/algorithm/demo/object_server.cpp
e4ec64ba2e425cce4f9a2b87a84b521f6537f890
[]
no_license
wujcheng/solrex
eca0e62b8d476e01b98d97ac312a0704e2566800
1260039d373dab2147dd27ac74ca49fd534f83e5
refs/heads/master
2021-01-18T16:00:33.803400
2012-01-18T07:21:26
2012-01-18T07:21:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,468
cpp
/* COMPILE: g++ objserver.cpp -o objserver -lpthread */ #include <queue> #include <pthread.h> #include <unistd.h> using namespace std; #define MAX_OBJECTS 5 /* number of objects */ #define MAX_THREADS 10 /* number of threads */ #define TID0_TID 0 /* thread_per_obj thread id */ #define CALL_OID (MAX_OBJECTS) /* pseudo object id of call() thread */ #define TID0_OID 0 /* thread_per_obj thread object id */ typedef int THREAD_POLICY; /* thread usage policy */ #define THREAD_PER_OBJ 0 /* 0: 1 thread per 1 object */ #define THREAD_PER_REQ 1 /* 1: 1 thread per 1 request */ /* Message format, we simplified it in our case. */ struct MESSAGE { int source; int object_id; int thread_id; int data; }; /* Thread information structure. */ struct THREAD { int tid; /* Thread id in our case */ int oid; /* Object id for the thread */ pthread_t posix_tid; /* POSIX thread id(the real Linux thread id) */ }; /* Object structure in our object server. */ class object { public: int oid; void stub(MESSAGE req, MESSAGE &res) { res = req; } }; object objects[MAX_OBJECTS]; /* objects in object server */ THREAD threads[MAX_THREADS]; /* threads for object adapter */ MESSAGE mes_pool[MAX_OBJECTS]; /* message buffers for communication */ queue<int> object_queue; /* object index queue for object assignment */ queue<int> thread_queue; /* thread index queue for thread assignment */ int pipe_call[2], pipe_tid0[2]; /* pipe for communication */ /* Get message function */ void get_msg (THREAD_POLICY policy, int oid, MESSAGE &data) { if (policy == THREAD_PER_OBJ) { if (oid == TID0_OID) { read(pipe_tid0[0], &data, sizeof(data)); } else { read(pipe_call[0], &data, sizeof(data)); } } else { data = mes_pool[oid]; } } /* Put message function */ void put_msg (THREAD_POLICY policy, int oid, MESSAGE &data) { if (policy == THREAD_PER_OBJ) { if (oid == TID0_OID) { write(pipe_tid0[1], &data, sizeof(data)); } else { write(pipe_call[1], &data, sizeof(data)); } } else { mes_pool[oid] = data; } } /* Exit thread, */ void thread_exit(THREAD *thread) { thread_queue.push(thread->tid); object_queue.push(thread->oid); pthread_exit(NULL); } /* Object adapter implemented ONE THREAD PER OBJECT policy. */ void * thread_per_object (void *arg) { THREAD *thread = (THREAD *)arg; MESSAGE req, res; while (true) { get_msg (THREAD_PER_OBJ, TID0_OID, req); req.object_id = thread->oid; req.thread_id = thread->tid; objects[thread->oid].stub(req, res); put_msg (THREAD_PER_OBJ, CALL_OID, res); } thread_exit(thread); } /* Object adapter implemented ONE THREAD PER REQUEST policy. */ void * thread_per_request (void *arg) { THREAD *thread = (THREAD *)arg; MESSAGE req, res; get_msg (THREAD_PER_REQ, thread->oid, req); req.object_id = thread->oid; req.thread_id = thread->tid; objects[thread->oid].stub(req, res); put_msg (THREAD_PER_REQ, thread->oid, res); thread_exit(thread); } /* Helper function to create a thread. */ THREAD * create_thread(THREAD_POLICY policy, MESSAGE *request) { if(policy == THREAD_PER_OBJ) { threads[TID0_TID].oid = TID0_OID; pthread_create(&threads[TID0_TID].posix_tid, NULL, &thread_per_object, &threads[TID0_TID]); return &threads[TID0_TID]; } else { int i, j; i = thread_queue.front(); thread_queue.pop(); j = object_queue.front(); object_queue.pop(); threads[i].oid = j; put_msg(THREAD_PER_REQ, threads[i].oid, *request); pthread_create(&threads[i].posix_tid, NULL, &thread_per_request, &threads[i]); return &threads[i]; } } /* Request demultiplexer: If the source of request is an even number, we use * the ONE THREAD PER OBJECT object adapter; else, we use the ONE THREAD PER * REQUEST object adapter. */ MESSAGE call(MESSAGE &request) { THREAD *thread; MESSAGE result; if (request.source%2 == 0) { put_msg(THREAD_PER_OBJ, TID0_OID, request); get_msg(THREAD_PER_OBJ, CALL_OID, result); } else { thread = create_thread(THREAD_PER_REQ, &request); pthread_join(thread->posix_tid, NULL); get_msg(THREAD_PER_REQ, thread->oid, result); } return result; } /* Initialize object server. */ void init_objserver() { int i; if (pipe(pipe_call) < 0 || pipe(pipe_tid0) < 0) perror("pipe() error"); for (i=1; i<MAX_THREADS; i++) threads[i].tid = i; for (i=1; i<MAX_THREADS; i++) thread_queue.push(i); for (i=1; i<MAX_OBJECTS; i++) objects[i].oid = i; for (i=1; i<MAX_OBJECTS; i++) object_queue.push(i); create_thread(THREAD_PER_OBJ, NULL); } int main() { /* Test object server. */ MESSAGE request, result; init_objserver(); printf("### Our object server has 5 objects, and maximum 10 threads. ###\n"); printf("Request demultiplexing policy is:\n"); printf(" Request from even source will be served by THREAD PER OBJECT.\n"); printf(" Request from odd source will be served by THREAD PER REQUEST.\n"); printf("============= TEST START =============\n"); for (int i=0; i<30; i++) { request.source = i; result = call(request); printf("Request from %2d was served by thread %d and object %d\n", result.source, result.thread_id, result.object_id); } return 0; }
[ "solrex@b8839100-cf4c-0410-a34d-a92c6c0b7f09" ]
solrex@b8839100-cf4c-0410-a34d-a92c6c0b7f09
3a033a48cb739021bd94f037f7bc1f84dc61d8cd
0949d5f41fa9c9eb50610fb424ce9a165a9bee88
/Data Structure/twoStack.cpp
add451dbbfb6bf91f9d1469696aa0c2658b3f4d0
[]
no_license
mdsagor07/Programming-Tools
f560120ffa6f57f4290803da1912a414af89da7d
2a6f34072ec289aad7a1c08f9c1cd5f5066f23b1
refs/heads/main
2023-04-14T03:43:52.925464
2021-04-23T04:43:36
2021-04-23T04:43:36
321,398,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,383
cpp
#include <iostream> #include <stdlib.h> using namespace std; class twoStacks { int* arr; int size; int top1, top2; public: twoStacks(int n) // constructor { size = n; arr = new int[n]; top1 = -1; top2 = size; } // Method to push an element x to stack1 void push1(int x) { // There is at least one empty space for new element if (top1 < top2 - 1) { top1++; arr[top1] = x; } else { cout << "Stack Overflow"; exit(1); } } // Method to push an element x to stack2 void push2(int x) { // There is at least one empty // space for new element if (top1 < top2 - 1) { top2--; arr[top2] = x; } else { cout << "Stack Overflow"; exit(1); } } // Method to pop an element from first stack int pop1() { if (top1 >= 0) { int x = arr[top1]; top1--; return x; } else { cout << "Stack UnderFlow"; exit(1); } } // Method to pop an element from second stack int pop2() { if (top2 < size) { int x = arr[top2]; top2++; return x; } else { cout << "Stack UnderFlow"; exit(1); } } }; /* Driver program to test twStacks class */ int main() { twoStacks ts(5); ts.push1(5); ts.push2(10); ts.push2(15); ts.push1(11); ts.push2(7); cout << "Popped element from stack1 is " << ts.pop1(); ts.push2(40); cout << "\nPopped element from stack2 is " << ts.pop2(); return 0; }
[ "sagor.cse.just@gmail.com" ]
sagor.cse.just@gmail.com
be2e71aef83b88e6334f47429be746ed6c49fa60
c32ee8ade268240a8064e9b8efdbebfbaa46ddfa
/Libraries/m2sdk/game/ai/C_AIMessage_Death.h
a4564c27ee9e426b94c945866dc7266e8e7dcab3
[]
no_license
hopk1nz/maf2mp
6f65bd4f8114fdeb42f9407a4d158ad97f8d1789
814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8
refs/heads/master
2021-03-12T23:56:24.336057
2015-08-22T13:53:10
2015-08-22T13:53:10
41,209,355
19
21
null
2015-08-31T05:28:13
2015-08-22T13:56:04
C++
UTF-8
C++
false
false
407
h
// auto-generated file (rttidump-exporter by h0pk1nz) #pragma once #include <game/ai/C_AIMessage.h> namespace game { namespace ai { /** game::ai::C_AIMessage_Death (VTable=0x01E4D720) */ class C_AIMessage_Death : public C_AIMessage { public: virtual void vfn_0001_1A4039D8() = 0; virtual void vfn_0002_1A4039D8() = 0; virtual void vfn_0003_1A4039D8() = 0; }; } // namespace ai } // namespace game
[ "hopk1nz@gmail.com" ]
hopk1nz@gmail.com
a5f13b7b55a3e5fd367e7582f3424ebfd543dd93
4d108f357f7c3da833911293a5bcda4ebba66526
/chrome/browser/ui/ash/fake_tablet_mode_controller.cc
61a34145538abbc9343891b3d3dc5980ad226d58
[ "BSD-3-Clause" ]
permissive
ycbxklk/chromium
1b57c52a441d38814feb2b5b040d7058b51db974
dbeb94d7208e902c90291ee27e07a636f9d72865
refs/heads/master
2023-02-28T05:04:33.740036
2019-07-10T10:44:35
2019-07-10T10:44:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
680
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/ash/fake_tablet_mode_controller.h" #include <utility> FakeTabletModeController::FakeTabletModeController() = default; FakeTabletModeController::~FakeTabletModeController() = default; void FakeTabletModeController::SetTabletModeToggleObserver( ash::TabletModeToggleObserver* observer) { observer_ = observer; } bool FakeTabletModeController::InTabletMode() const { return enabled_; } void FakeTabletModeController::SetEnabledForTest(bool enabled) { enabled_ = enabled; }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
3f1ae3eba1c9ef9a0bf8111c1dffb3ff7544382e
33b08b3036fe3c5921a5b0068eb09b88286e73f1
/coursework/DSU.h
e27321c5761b1c1865986dba2d2b8f64362078e2
[]
no_license
rex-gentium/graph-theory
f072bd4ccea438b4046e3028e4466bcf730cf232
65ff0e58fdef1a0023769205877d08bb64cf4050
refs/heads/master
2021-01-09T06:50:51.446696
2017-04-15T14:56:29
2017-04-15T14:56:29
81,129,457
1
0
null
2017-04-15T11:47:01
2017-02-06T20:23:30
C++
UTF-8
C++
false
false
2,074
h
#pragma once #include <vector> /* Система непересекающихся множеств. Не является полноценной реализацией: возможно только создать систему из N пронумерованных элементов, каждый из которых образует множество. Добавить новое множество нельзя. */ class DSU { public: /* создаёт систему из setCount непересекающихся множеств, id множества является порядковый номер*/ DSU(int setCount); DSU(const DSU& rhs); ~DSU(); DSU & operator=(const DSU & hrs); /*создаёт новое множество с указанным лидером*/ //void makeSet(int x); // для реализации потребуется заменить массив предков на карту /*объединеняет два множества указанных представителей. Амортизированная O(1)*/ void unite(int x, int y); /*возвращает лидера множества указанного представителя. Амортизированная O(1)*/ int find(int x) const; /* возвращает количество множеств */ int getSetCount() const { return setCount; } /* возвращает массив лидеров множеств размера getSetCount(). Массив должен быть уничтожен после использования */ int * getLeaders() const; private: int * parent = nullptr; // массив: по номеру элемента лежит номер его предка (лидер множества является предком сам себе) int * rank = nullptr; // массив: по номеру элемента лежит высота его поддерева int size; // количество элементов int setCount; // количество множеств / лидеров };
[ "budowniczy.zamyslow@gmail.com" ]
budowniczy.zamyslow@gmail.com
de08a559cfda9b5c00b94c083c258fb8f2ed5f21
1bd8d99894ba1d789031cd75cdfea81b5d59e1f6
/src/general/tick.h
2252e0153ec30ac3a0697af0ac19605133679cb7
[ "MIT" ]
permissive
RJJain/VANS
ab7ef169680685a9d32f3f6c682c7dea0f6415d9
1eb6f3873125e0b24aa66d3634ade350c4f5f13f
refs/heads/master
2023-02-09T03:12:04.429169
2020-12-31T06:31:06
2020-12-31T06:31:06
321,661,640
0
0
MIT
2020-12-31T06:31:07
2020-12-15T12:30:14
null
UTF-8
C++
false
false
246
h
#ifndef VANS_TICK_H #define VANS_TICK_H #include "utils.h" namespace vans { class tick_able { public: /* Use a global clock signal from outside */ virtual void tick(clk_t curr_clk) = 0; }; } // namespace vans #endif // VANS_TICK_H
[ "zxwang42@gmail.com" ]
zxwang42@gmail.com
28be2175b62194b9395bcea3047f812193a89011
e778be8ebc60a2ec915698280f17fafffe55c5fb
/platforms/imx8mm/include/nav_os/transport/shm/segment_factory.h
f8da18e9e424eeaa57fef59e3289ac7037482970
[]
no_license
3JLinux/xag_xhome
30b933e11b40ff3c72c810e49a857caaf49a7247
c2b00f449354cf12b72c8c87246a3b4493b751d8
refs/heads/master
2023-06-14T08:05:29.771649
2021-07-02T02:00:42
2021-07-02T02:00:42
382,225,237
0
0
null
null
null
null
UTF-8
C++
false
false
1,252
h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_TRANSPORT_SHM_SEGMENT_FACTORY_H_ #define CYBER_TRANSPORT_SHM_SEGMENT_FACTORY_H_ #include <memory> #include <string> #include "spdlog/spdlog.h" #include "transport/shm/segment.h" #include "transport/shm/posix_segment.h" #include "transport/shm/xsi_segment.h" namespace xag_nav { namespace os { namespace transport{ class SegmentFactory { public: static SegmentPtr CreateSegment(uint64_t channel_id); }; } } } #endif // CYBER_TRANSPORT_SHM_SEGMENT_FACTORY_H_
[ "421721486@qq.com" ]
421721486@qq.com