blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
5e25fec683dec40364ead855789e22371e4302c1
d46c47be43e84569271c1d12ce5140a9b89677c1
/lua/src/loslib.hpp
e60f8624cf2c13461bc60ec791750aee484e2cae
[]
no_license
dragonsn/gv_external
7af56a52336160e9473c3f455450cc5638b5756b
f85971a5dc5b9b596f2f34d00fddc7096bab7402
refs/heads/master
2022-11-09T03:54:28.154202
2022-10-14T04:08:43
2022-10-14T04:08:43
159,042,161
1
0
null
null
null
null
UTF-8
C++
false
false
6,004
hpp
/* ** $Id: loslib.c,v 1.19.1.3 2008/01/18 16:38:18 roberto Exp $ ** Standard Operating System library ** See Copyright Notice in lua.h */ #include <errno.h> #include <locale.h> #include <stdlib.h> #include <string.h> #include <time.h> #define loslib_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" static int os_pushresult (lua_State *L, int i, const char *filename) { int en = errno; /* calls to Lua API may change this value */ if (i) { lua_pushboolean(L, 1); return 1; } else { lua_pushnil(L); lua_pushfstring(L, "%s: %s", filename, strerror(en)); lua_pushinteger(L, en); return 3; } } static int os_execute (lua_State *L) { lua_pushinteger(L, system(luaL_optstring(L, 1, NULL))); return 1; } static int os_remove (lua_State *L) { const char *filename = luaL_checkstring(L, 1); return os_pushresult(L, remove(filename) == 0, filename); } static int os_rename (lua_State *L) { const char *fromname = luaL_checkstring(L, 1); const char *toname = luaL_checkstring(L, 2); return os_pushresult(L, rename(fromname, toname) == 0, fromname); } static int os_tmpname (lua_State *L) { char buff[LUA_TMPNAMBUFSIZE]; int err; lua_tmpnam(buff, err); if (err) return luaL_error(L, "unable to generate a unique filename"); lua_pushstring(L, buff); return 1; } static int os_getenv (lua_State *L) { lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ return 1; } static int os_clock (lua_State *L) { lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); return 1; } /* ** {====================================================== ** Time/Date operations ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, ** wday=%w+1, yday=%j, isdst=? } ** ======================================================= */ static void setfield (lua_State *L, const char *key, int value) { lua_pushinteger(L, value); lua_setfield(L, -2, key); } static void setboolfield (lua_State *L, const char *key, int value) { if (value < 0) /* undefined? */ return; /* does not set field */ lua_pushboolean(L, value); lua_setfield(L, -2, key); } static int getboolfield (lua_State *L, const char *key) { int res; lua_getfield(L, -1, key); res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1); lua_pop(L, 1); return res; } static int getfield (lua_State *L, const char *key, int d) { int res; lua_getfield(L, -1, key); if (lua_isnumber(L, -1)) res = (int)lua_tointeger(L, -1); else { if (d < 0) return luaL_error(L, "field " LUA_QS " missing in date table", key); res = d; } lua_pop(L, 1); return res; } static int os_date (lua_State *L) { const char *s = luaL_optstring(L, 1, "%c"); time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL)); struct tm *stm; if (*s == '!') { /* UTC? */ stm = gmtime(&t); s++; /* skip `!' */ } else stm = localtime(&t); if (stm == NULL) /* invalid date? */ lua_pushnil(L); else if (strcmp(s, "*t") == 0) { lua_createtable(L, 0, 9); /* 9 = number of fields */ setfield(L, "sec", stm->tm_sec); setfield(L, "min", stm->tm_min); setfield(L, "hour", stm->tm_hour); setfield(L, "day", stm->tm_mday); setfield(L, "month", stm->tm_mon+1); setfield(L, "year", stm->tm_year+1900); setfield(L, "wday", stm->tm_wday+1); setfield(L, "yday", stm->tm_yday+1); setboolfield(L, "isdst", stm->tm_isdst); } else { char cc[3]; luaL_Buffer b; cc[0] = '%'; cc[2] = '\0'; luaL_buffinit(L, &b); for (; *s; s++) { if (*s != '%' || *(s + 1) == '\0') /* no conversion specifier? */ luaL_addchar(&b, *s); else { size_t reslen; char buff[200]; /* should be big enough for any conversion result */ cc[1] = *(++s); reslen = strftime(buff, sizeof(buff), cc, stm); luaL_addlstring(&b, buff, reslen); } } luaL_pushresult(&b); } return 1; } static int os_time (lua_State *L) { time_t t; if (lua_isnoneornil(L, 1)) /* called without args? */ t = time(NULL); /* get current time */ else { struct tm ts; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); /* make sure table is at the top */ ts.tm_sec = getfield(L, "sec", 0); ts.tm_min = getfield(L, "min", 0); ts.tm_hour = getfield(L, "hour", 12); ts.tm_mday = getfield(L, "day", -1); ts.tm_mon = getfield(L, "month", -1) - 1; ts.tm_year = getfield(L, "year", -1) - 1900; ts.tm_isdst = getboolfield(L, "isdst"); t = mktime(&ts); } if (t == (time_t)(-1)) lua_pushnil(L); else lua_pushnumber(L, (lua_Number)t); return 1; } static int os_difftime (lua_State *L) { lua_pushnumber(L,(lua_Number) difftime((time_t)(luaL_checknumber(L, 1)), (time_t)(luaL_optnumber(L, 2, 0)))); return 1; } /* }====================================================== */ static int os_setlocale (lua_State *L) { static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME}; static const char *const catnames[] = {"all", "collate", "ctype", "monetary", "numeric", "time", NULL}; const char *l = luaL_optstring(L, 1, NULL); int op = luaL_checkoption(L, 2, "all", catnames); lua_pushstring(L, setlocale(cat[op], l)); return 1; } static int os_exit (lua_State *L) { exit(luaL_optint(L, 1, EXIT_SUCCESS)); } static const luaL_Reg syslib[] = { {"clock", os_clock}, {"date", os_date}, {"difftime", os_difftime}, {"execute", os_execute}, {"exit", os_exit}, {"getenv", os_getenv}, {"remove", os_remove}, {"rename", os_rename}, {"setlocale", os_setlocale}, {"time", os_time}, {"tmpname", os_tmpname}, {NULL, NULL} }; /* }====================================================== */ LUALIB_API int luaopen_os (lua_State *L) { luaL_register(L, LUA_OSLIBNAME, syslib); return 1; }
451fc4b8f108dfc79c88c50f0bcb7363786aac56
544a465731b44638ad61a4afa4f341aecf66f3cd
/src/libivk/computation/StatePartitioning.cpp
93494a5695810dc975898b000366aae41132a2de
[]
no_license
skempken/interverdikom
e13cbe592aa6dc5b67d8b2fbb4182bcb2b8bc15b
dde091ee71dc1d88bbedb5162771623f3ab8a6f4
refs/heads/master
2020-05-29T15:29:18.076702
2014-01-03T10:10:03
2014-01-03T10:10:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,765
cpp
#include "StatePartitioning.h" #include "utility/RealUtils.h" #include "utility/RMatrixUtils.h" #include "utility/Logging.hpp" #include <iostream> namespace ivk{ const char * StatePartitioning::PARAM_NUMCONTRACTIONS = "numContractions"; StatePartitioning::StatePartitioning(const SSMProcess* data, const ComputationParameters &parameters) :AbstractComputation<SSMProcess, SSMProcess>(data, parameters){ this->setParameters( parameters ); this->accErr = cxsc::MaxReal; } StatePartitioning::~StatePartitioning(){ } void StatePartitioning::setParameters(const ComputationParameters &parameters){ this->setNumContractions(parameters.getInt(StatePartitioning::PARAM_NUMCONTRACTIONS)); } void StatePartitioning::setNumContractions(const int value){ this->numContractions = value; } int StatePartitioning::getNumContractions() const{ return this->numContractions; } SSMProcess StatePartitioning::sortByExpectation(){ rvector means = this->m_ptrData->getStateMeans(); vector< pair< int , real > > sorted = RVectorUtils::sortWithIndex( means ); rmatrix newTransition( mid( this->m_ptrData->getTransitionMatrix() ) ); rmatrix newDistribution( mid( this->m_ptrData->getDistributions() ) ); rmatrix transition( mid( this->m_ptrData->getTransitionMatrix() ) ); rmatrix distribution( mid( this->m_ptrData->getDistributions() ) ); int rowcount = 0; int colcount = 0; for( int i = Lb( newTransition , ROW ) ; i <= Ub( newTransition , ROW ) ; i++ ){ for(int j = Lb( newTransition , COL ) ; j <= Ub( newTransition , COL ) ; j++ ){ newTransition[i][j] = transition[ sorted[rowcount].first ][ sorted[colcount].first ]; colcount++; } rowcount ++; colcount = 0; } rowcount = 0; for( int i = Lb( newDistribution , ROW ) ; i <= Ub( newDistribution , ROW ) ; i++ ){ for( int j = Lb( newDistribution , COL ) ; j <= Ub( newDistribution , COL ) ; j++ ){ newDistribution[i][j] = distribution[ sorted[rowcount].first ][j]; } rowcount ++; } SSMProcess ret( newTransition , newDistribution ); return ret; } real StatePartitioning::autocorrelationError( int startIndex , int endIndex ){ SSMProcess sortedProcess = this->sortByExpectation(); rvector statProbs( sortedProcess.getStationaryProbabilities() ); rvector expect( sortedProcess.getStateMeans() ); real e_ = 0.0; for( int i = startIndex ; i <= endIndex ; i++){ e_ += statProbs[i] * expect[i]; } real s_j = 0.0; for( int k = startIndex ; k <= endIndex ; k++ ){ s_j += statProbs[k] * RealUtils::rPow( expect[k] , 2) - RealUtils::rPow( e_ , 2 ); } s_j /= sortedProcess.getVariance(); return s_j; } void StatePartitioning::recursionInit(){ int x = this->m_ptrData->getNumStates() - this->numContractions; this->recursion( 1 , this->m_ptrData->getNumStates() , x-1 ); } void StatePartitioning::recursion( int m , int k , int numParts){ if( numParts == 1 ){ this->ranges.push_back( make_pair( m , k ) ); this->calculateRangeValue(); this->ranges.pop_back(); } else{ for(int i = m+1 ; i <= k-numParts+1 ; i++){ this->ranges.push_back( make_pair( m , i ) ); this->recursion( i , k , numParts-1 ); this->ranges.pop_back(); } } } void StatePartitioning::calculateRangeValue(){ vector< range > tmp = this->ranges; real acerr = 0.0; for( int i = 0 ; i < tmp.size() ; i++ ){ acerr += this->autocorrelationError( tmp[i].first , tmp[i].second ); } if( acerr < this->accErr ){ this->accErr = acerr; this->finalRanges = this->ranges; } //this->ranges.clear(); } SSMProcess StatePartitioning::applyRanges(){ SSMProcess process( *this->m_ptrData ); for( int i = 0 ; i < this->finalRanges.size() ; i++ ){ if( ( this->finalRanges[i].second - this->finalRanges[i].first ) > 1){ int numContractions = this->finalRanges[i].second - this->finalRanges[i].first -1 ; intvector contractions( 1 , numContractions ); for(int c = Lb( contractions ) ; c <= Ub( contractions ) ; c++ ){ contractions[ c ] = this->finalRanges[i].first + c; } process = contractStates( process , this->finalRanges[i].first , contractions ); } } return process; } SSMProcess StatePartitioning::contractStates(const SSMProcess &model , int receivingState, const intvector &states){ int m = receivingState; rmatrix d = mid(model.getDistributions()); rmatrix t = mid(model.getTransitionMatrix()); rvector p = model.getStationaryProbabilities(); rmatrix d_ = RMatrixUtils::zeros( Lb( d,ROW ) , Ub( d,ROW ) - ( VecLen( states ) ) , Lb( d,COL ) , Ub( d,COL ) ); rmatrix t_ = RMatrixUtils::zeros( Lb( t,ROW ) , Ub( t,ROW ) - ( VecLen( states ) ) , Lb( t,ROW ) , Ub( t,ROW ) - ( VecLen( states ) ) ); for( int i = Lb( t,ROW ) ; i <= Ub( t,ROW ) ; i++ ){ int buff = 0; for(int c = Lb( states ) ; c <= Ub(states);c++){ if( states[c] <= i ){ buff -= 1; } } for( int x = Lb( d,COL ) ; x <= Ub( d,COL ) ; x++ ){ bool check = true; for(int c = Lb( states ) ; c <= Ub( states ) ; c++){ if( states[c] == i || receivingState == i ){ check = false; } } if( check ){ assert(i+buff >= Lb(d_, 1)); d_[ i+buff ][x] = d[i][x]; } else if( i == receivingState ){ real numerator = p[receivingState] * d[receivingState][x]; real denominator = p[receivingState]; for( int c = Lb( states ) ; c <= Ub( states ) ; c++ ){ assert(states[c] >= Lb(d, 1)); assert(states[c] <= Ub(d, 1)); numerator += p[states[c]] * d[states[c]][x]; denominator += p[states[c]]; } assert(i+buff >= Lb(d_, 1)); d_[ i+buff ][x] = numerator / denominator; } } } for( int i = Lb( t,ROW ) ; i <= Ub( t,ROW ) ; i++ ){ bool iPull = false; bool iPush = false; int buffI = 0; for( int c = Lb( states ) ; c <= Ub( states ) ; c++ ){ if(states[c] < i){ buffI -= 1; } if(states[c] == i){ iPush = true; } } if( receivingState == i ){ iPull = true; } for( int j = Lb( t,ROW ) ; j <= Ub( t,ROW ) ; j++ ){ bool jPush = false; bool jPull = false; real numerator = 0.0; real denominator = 0.0; int buffJ = 0; for(int c = 0; c <= Ub(states); c++){ if(states[c] < j){ buffJ -= 1; } if(states[c] == j){ jPush = true; } } if(receivingState == j){ jPull = true; } real value = 0.0; if(!iPush && !iPull && !jPush && !jPull){ value = t[i][j]; } else if( !iPush && !iPull && jPull ){ value = t[i][receivingState]; for(int c = Lb( states ) ; c <= Ub( states ) ; c++){ value += t[i][states[c]]; } } else if( iPull && !jPull && !jPush){ numerator = p[receivingState] * t[receivingState][j]; denominator = p[receivingState]; for(int c = Lb( states ) ; c <= Ub( states ) ; c++){ numerator += p[states[c]]*t[states[c]][j]; denominator += p[states[c]]; } value = numerator / denominator; } else if( iPull && jPull){ denominator = p[receivingState]; real tmp = t[receivingState][receivingState]; for(int c = Lb( states ) ; c <= Ub( states ) ; c++ ){ tmp += t[receivingState][states[c]]; numerator += p[states[c]] * (t[states[c]][receivingState] + t[states[c]][states[c]]); denominator += p[states[c]]; } numerator += p[receivingState] * tmp; value = numerator / denominator; } t_[i+buffI][j+buffJ] = value; } } /* Logging::log( Logging::Debug , "d_:" , d_ ); Logging::log( Logging::Debug , "t_:" , t_ ); */ return SSMProcess( t_ , d_ , false ); } SSMProcess* StatePartitioning::compute(){ this->recursionInit(); /*this->applyRanges(); return new SSMProcess(*this->m_ptrData);*/ return new SSMProcess( this->applyRanges() ); } }
[ "sebastian@ivk-virtualbox.(none)" ]
sebastian@ivk-virtualbox.(none)
e5a77ec8853a7179767fa6c309b63fc41603ed46
b5b3d3c24535c135e6186096c8492c9c91b6dd48
/test/test/main.cpp
88e5d0e6fba554c73c187922c9ea4273803b445f
[ "MIT" ]
permissive
yifan-fanyi/Improved-Monocular-ORB-SLAM2
b1ca0eb4301c754a2dd1f0741afd98040ad0b196
27a761e31ab51de6323a290be37565f860213fad
refs/heads/main
2023-05-06T17:34:20.875095
2021-05-31T05:25:14
2021-05-31T05:25:14
334,776,926
11
2
null
null
null
null
UTF-8
C++
false
false
6,787
cpp
// // main.cpp // test // // Created by Alex on 08/03/2018. // Copyright © 2018 Alex. All rights reserved. // /////////////////////////////////////////////////// //LK optical flow #include<opencv2/opencv.hpp> #define ClocksPerSec 1000000; const int MAX_CORNERS = 1000; #include <iostream> #include <sstream> #include <fstream> #include <string> #include <vector> #include <ctime> #include <cstdlib> #include <limits> #include "KMeans.h" using namespace std; int main() { IplImage *imgA = cvLoadImage("1.jpg", CV_LOAD_IMAGE_GRAYSCALE); IplImage *imgB = cvLoadImage("2.jpg", CV_LOAD_IMAGE_GRAYSCALE); if(!imgA){ cout << "could not open photo" << endl; return 0; } if(!imgB){ cout << "could not open photo" << endl; return 0; } CvSize img_sz = cvGetSize(imgA); int win_size = 10; IplImage *imgC = cvLoadImage("1.png", CV_LOAD_IMAGE_UNCHANGED); IplImage *eig_image = cvCreateImage(img_sz, IPL_DEPTH_32F,1); IplImage *tmp_image = cvCreateImage(img_sz, IPL_DEPTH_32F, 1); int corner_count = MAX_CORNERS; CvPoint2D32f *cornersA = new CvPoint2D32f[MAX_CORNERS]; double StartTime,EndTime1,CostTime1,EndTime2,CostTime2; //to calculate the runtime StartTime = clock(); cvGoodFeaturesToTrack( imgA, eig_image, tmp_image, cornersA, &corner_count, 0.01, 5.0, 0, 3, 0, 0.04 ); cvFindCornerSubPix( imgA, cornersA, corner_count, cvSize(win_size, win_size), cvSize(-1, -1), cvTermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03) ); EndTime2 = clock(); CostTime2 = (EndTime2 - StartTime) / ClocksPerSec; //int corner_count = 500; //CvPoint2D32f *cornersA = new CvPoint2D32f[MAX_CORNERS]; char features_found[MAX_CORNERS]; float features_errors[MAX_CORNERS]; CvSize pyr_sz = cvSize(imgA->width + 8, imgB->height / 3); IplImage *pyrA = cvCreateImage(pyr_sz, IPL_DEPTH_32F, 1); IplImage *pyrB = cvCreateImage(pyr_sz, IPL_DEPTH_32F, 1); CvPoint2D32f *cornersB = new CvPoint2D32f[MAX_CORNERS]; cvCalcOpticalFlowPyrLK( imgA, imgB, pyrA, pyrB, cornersA, cornersB, corner_count, cvSize(win_size, win_size), 5, features_found, features_errors, cvTermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.3), 0 ); double vecth[corner_count],veclen[corner_count]; double driftx[corner_count], drifty[corner_count], drift[2*corner_count]; int k=0; for (int i = 0; i < corner_count; ++i) { CvPoint p0 = cvPoint(cvRound(cornersA[i].x), cvRound(cornersA[i].y)); CvPoint p1 = cvPoint(cvRound(cornersB[i].x), cvRound(cornersB[i].y)); veclen[i]=((p0.x-p1.x)*(p0.x-p1.x)+(p0.y-p1.y)*(p0.y-p1.y)); vecth[i]=((p0.y-p1.y)/(p0.x-p1.x+0.0001)); // cout<<vecth[i]<<" "<<veclen[i]<<endl; driftx[i]=cornersA[i].x - cornersB[i].x; drift[k]=cornersA[i].x - cornersB[i].x; k++; drifty[i]=cornersA[i].y - cornersB[i].y; drift[k]=cornersA[i].y - cornersB[i].y; k++; } const int size = corner_count; //Number of samples const int dim = 2; //Dimension of feature const int cluster_num = 5; //Cluster number KMeans* kmeans = new KMeans(dim,cluster_num); int* labels = new int[size]; kmeans->SetInitMode(KMeans::InitUniform); kmeans->Cluster(drift,size,labels); int count[cluster_num]={0}; for(int i=0;i<size;i++){ count[labels[i]]++; // cout<<labels[i]<<endl; } int max=count[0],temp=0; for(int i=1;i<cluster_num;i++){ if(count[i]>max){ max=count[i]; temp=i; } } // cout<<max<<temp<<endl; // for (int i = 0; i < corner_count; ++i) // { // CvPoint p0 = cvPoint(cvRound(cornersA[i].x), cvRound(cornersA[i].y)); // CvPoint p1 = cvPoint(cvRound(cornersB[i].x), cvRound(cornersB[i].y)); //cout<<labels[i]<<" "<<vecth[i]<<" "<<veclen[i]<<endl; // cout<<labels[i]<<" "<<cornersA[i].x<<" "<<cornersA[i].y<<" "<<cornersB[i].x<<" "<<cornersB[i].y<<endl; // if(labels[i]==temp){ // cvLine(imgC, p0, p1, CV_RGB(0, 0, 255),2); // cout<<vecth[i]<<" "<<veclen[i]<<endl; // cout<<driftx[i]<<" "<<drifty[i]<<endl; // } // else{ // cvLine(imgC, p0, p1, CV_RGB(250, 128, 0),2); // } // } // cout<<"/////////////////////////////"<<endl; for (int i = 0; i < corner_count; ++i) { CvPoint p0 = cvPoint(cvRound(cornersA[i].x), cvRound(cornersA[i].y)); CvPoint p1 = cvPoint(cvRound(cornersB[i].x), cvRound(cornersB[i].y)); //cout<<labels[i]<<" "<<vecth[i]<<" "<<veclen[i]<<endl; // cout<<labels[i]<<" "<<cornersA[i].x<<" "<<cornersA[i].y<<" "<<cornersB[i].x<<" "<<cornersB[i].y<<endl; if(labels[i]==temp){ cvLine(imgC, p0, p1, CV_RGB(255, 0, 0),2); // cout<<labels[i]<<" "<<vecth[i]<<" "<<veclen[i]<<endl; } else{ cvLine(imgC, p0, p1, CV_RGB(0, 0, 255),2); // cout<<vecth[i]<<" "<<veclen[i]<<endl; // cout<<driftx[i]<<" "<<drifty[i]<<endl; } } EndTime1 = clock(); CostTime1 = (EndTime1 - StartTime) / ClocksPerSec; //run time //CLOCKS_PER_SEC is 1000 000 while using Xcode cout<<"The during time is: "<< CostTime1 <<" seconds\n"<<endl; cout<<"The during time is: "<< CostTime2 <<" seconds\n"<<endl; cvNamedWindow("ImageA", 0); cvNamedWindow("ImageB", 0); cvNamedWindow("LKpyr_OpticalFlow", 0); cvShowImage("ImageA", imgA); cvShowImage("ImageB", imgB); cvShowImage("LKpyr_OpticalFlow", imgC); cvWaitKey(0); return 0; }
c690df6afe7b4d3b8c3c1977f0a9c1e995dbcdcb
9da899bf6541c6a0514219377fea97df9907f0ae
/Editor/ContentBrowser/Private/ContentBrowserSingleton.h
4633182b9f069fbb5c78919c63daab8ad095f192
[]
no_license
peichangliang123/UE4
1aa4df3418c077dd8f82439ecc808cd2e6de4551
20e38f42edc251ee96905ed8e96e1be667bc14a5
refs/heads/master
2023-08-17T11:31:53.304431
2021-09-15T00:31:03
2021-09-15T00:31:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,730
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "AssetData.h" #include "IContentBrowserSingleton.h" #include "ContentBrowserSingleton.generated.h" class FCollectionAssetRegistryBridge; class FSpawnTabArgs; class FTabManager; class FViewport; class SContentBrowser; class UFactory; #define MAX_CONTENT_BROWSERS 4 USTRUCT() struct FContentBrowserPluginSettings { GENERATED_BODY() UPROPERTY() FName PluginName; /** Used to control the order of plugin root folders in the path view. A higher priority sorts higher in the list. Game and Engine folders are priority 1.0 */ UPROPERTY() float RootFolderSortPriority; FContentBrowserPluginSettings() : RootFolderSortPriority(0.f) {} }; /** * Content browser module singleton implementation class */ class FContentBrowserSingleton : public IContentBrowserSingleton { public: /** Constructor, Destructor */ FContentBrowserSingleton(); virtual ~FContentBrowserSingleton(); // IContentBrowserSingleton interface virtual TSharedRef<class SWidget> CreateContentBrowser( const FName InstanceName, TSharedPtr<SDockTab> ContainingTab, const FContentBrowserConfig* ContentBrowserConfig ) override; virtual TSharedRef<class SWidget> CreateAssetPicker(const FAssetPickerConfig& AssetPickerConfig) override; virtual TSharedRef<class SWidget> CreatePathPicker(const FPathPickerConfig& PathPickerConfig) override; virtual TSharedRef<class SWidget> CreateCollectionPicker(const FCollectionPickerConfig& CollectionPickerConfig) override; virtual TSharedRef<class SWidget> CreateContentBrowserDrawer(const FContentBrowserConfig& ContentBrowserConfig, TFunction<TSharedPtr<SDockTab>()> InOnGetTabForDrawer) override; virtual void CreateOpenAssetDialog(const FOpenAssetDialogConfig& OpenAssetConfig, const FOnAssetsChosenForOpen& OnAssetsChosenForOpen, const FOnAssetDialogCancelled& OnAssetDialogCancelled) override; virtual TArray<FAssetData> CreateModalOpenAssetDialog(const FOpenAssetDialogConfig& InConfig) override; virtual void CreateSaveAssetDialog(const FSaveAssetDialogConfig& SaveAssetConfig, const FOnObjectPathChosenForSave& OnAssetNameChosenForSave, const FOnAssetDialogCancelled& OnAssetDialogCancelled) override; virtual FString CreateModalSaveAssetDialog(const FSaveAssetDialogConfig& SaveAssetConfig) override; virtual bool HasPrimaryContentBrowser() const override; virtual void FocusPrimaryContentBrowser(bool bFocusSearch) override; virtual void FocusContentBrowserSearchField(TSharedPtr<SWidget> ContentBrowserWidget) override; virtual void CreateNewAsset(const FString& DefaultAssetName, const FString& PackagePath, UClass* AssetClass, UFactory* Factory) override; virtual void SyncBrowserToAssets(const TArray<struct FAssetData>& AssetDataList, bool bAllowLockedBrowsers = false, bool bFocusContentBrowser = true, const FName& InstanceName = FName(), bool bNewSpawnBrowser = false) override; virtual void SyncBrowserToAssets(const TArray<UObject*>& AssetList, bool bAllowLockedBrowsers = false, bool bFocusContentBrowser = true, const FName& InstanceName = FName(), bool bNewSpawnBrowser = false) override; virtual void SyncBrowserToFolders(const TArray<FString>& FolderList, bool bAllowLockedBrowsers = false, bool bFocusContentBrowser = true, const FName& InstanceName = FName(), bool bNewSpawnBrowser = false) override; virtual void SyncBrowserToItems(const TArray<FContentBrowserItem>& ItemsToSync, bool bAllowLockedBrowsers = false, bool bFocusContentBrowser = true, const FName& InstanceName = FName(), bool bNewSpawnBrowser = false) override; virtual void SyncBrowserTo(const FContentBrowserSelection& ItemSelection, bool bAllowLockedBrowsers = false, bool bFocusContentBrowser = true, const FName& InstanceName = FName(), bool bNewSpawnBrowser = false) override; virtual void GetSelectedAssets(TArray<FAssetData>& SelectedAssets) override; virtual void GetSelectedFolders(TArray<FString>& SelectedFolders) override; virtual void GetSelectedPathViewFolders(TArray<FString>& SelectedFolders) override; virtual FString GetCurrentPath() override; virtual void CaptureThumbnailFromViewport(FViewport* InViewport, TArray<FAssetData>& SelectedAssets) override; virtual void SetSelectedPaths(const TArray<FString>& FolderPaths, bool bNeedsRefresh = false) override; virtual void ForceShowPluginContent(bool bEnginePlugin) override; virtual void SaveContentBrowserSettings(TSharedPtr<SWidget> ContentBrowserWidget) override; virtual void ExecuteRename(TSharedPtr<SWidget> PickerWidget) override; virtual void ExecuteAddFolder(TSharedPtr<SWidget> PathPickerWidget) override; virtual void RefreshPathView(TSharedPtr<SWidget> PathPickerWidget) override; /** Gets the content browser singleton as a FContentBrowserSingleton */ static FContentBrowserSingleton& Get(); /** Sets the current primary content browser. */ void SetPrimaryContentBrowser(const TSharedRef<SContentBrowser>& NewPrimaryBrowser); /** Notifies the singleton that a browser was closed */ void ContentBrowserClosed(const TSharedRef<SContentBrowser>& ClosedBrowser); /** Gets the settings for the plugin with the specified name */ const FContentBrowserPluginSettings& GetPluginSettings(FName PluginName) const; /** Single storage location for content browser favorites */ TArray<FString> FavoriteFolderPaths; /** Docks the current content browser drawer as a tabbed content browser in a layout */ void DockContentBrowserDrawer(); private: /** Util to get or create the content browser that should be used by the various Sync functions */ TSharedPtr<SContentBrowser> FindContentBrowserToSync(bool bAllowLockedBrowsers, const FName& InstanceName = FName(), bool bNewSpawnBrowser = false); /** Shared code to open an asset dialog window with a config */ void SharedCreateAssetDialogWindow(const TSharedRef<class SAssetDialog>& AssetDialog, const FSharedAssetDialogConfig& InConfig, bool bModal) const; /** * Delegate handlers **/ void OnEditorLoadSelectedAssetsIfNeeded(); /** Sets the primary content browser to the next valid browser in the list of all browsers */ void ChooseNewPrimaryBrowser(); /** Gives focus to the specified content browser */ void FocusContentBrowser(const TSharedPtr<SContentBrowser>& BrowserToFocus); /** Summons a new content browser */ FName SummonNewBrowser(bool bAllowLockedBrowsers = false, TSharedPtr<FTabManager> SpecificTabManager = nullptr); /** Handler for a request to spawn a new content browser tab */ TSharedRef<SDockTab> SpawnContentBrowserTab( const FSpawnTabArgs& SpawnTabArgs, int32 BrowserIdx ); /** Handler for a request to spawn a new content browser tab */ FText GetContentBrowserTabLabel(int32 BrowserIdx); /** Returns true if this content browser is locked (can be used even when closed) */ bool IsLocked(const FName& InstanceName) const; /** Returns a localized name for the tab/menu entry with index */ static FText GetContentBrowserLabelWithIndex( int32 BrowserIdx ); /** Populates properties that come from ini files */ void PopulateConfigValues(); public: /** The tab identifier/instance name for content browser tabs */ FName ContentBrowserTabIDs[MAX_CONTENT_BROWSERS]; private: TArray<TWeakPtr<SContentBrowser>> AllContentBrowsers; TWeakPtr<SContentBrowser> ContentBrowserDrawer; TFunction<TSharedPtr<SDockTab>()> OnGetTabForDrawer; TMap<FName, TWeakPtr<FTabManager>> BrowserToLastKnownTabManagerMap; TWeakPtr<SContentBrowser> PrimaryContentBrowser; TSharedRef<FCollectionAssetRegistryBridge> CollectionAssetRegistryBridge; TArray<FContentBrowserPluginSettings> PluginSettings; /** An incrementing int32 which is used when making unique settings strings */ int32 SettingsStringID; };
9a76013d51e5ca22914b9731dae0ce3198013a6e
ad808d158533435e8cd16f308f454311bb68c369
/src/external/scintilla/src/Editor.h
4903f2909f13a9be553fabda0c06b3413afba244
[ "LicenseRef-scancode-scintilla", "MIT" ]
permissive
mcanthony/ProDBG
088218dd35d2eb988b45617fdbf2a35f9b45f5b2
5da4437c41cd5e63dcd4c6af75fb95052cc74fb8
refs/heads/master
2020-12-27T21:20:24.923146
2015-09-30T21:06:11
2015-09-30T21:06:11
43,863,725
1
0
null
2015-10-08T04:51:42
2015-10-08T04:51:42
null
UTF-8
C++
false
false
20,075
h
// Scintilla source code edit control /** @file Editor.h ** Defines the main editor class. **/ // Copyright 1998-2011 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #ifndef EDITOR_H #define EDITOR_H #ifdef SCI_NAMESPACE namespace Scintilla { #endif /** */ class Timer { public: bool ticking; int ticksToWait; enum {tickSize = 100}; TickerID tickerID; Timer(); }; /** */ class Idler { public: bool state; IdlerID idlerID; Idler(); }; /** * When platform has a way to generate an event before painting, * accumulate needed styling range and other work items in * WorkNeeded to avoid unnecessary work inside paint handler */ class WorkNeeded { public: enum workItems { workNone=0, workStyle=1, workUpdateUI=2 }; bool active; enum workItems items; Position upTo; WorkNeeded() : active(false), items(workNone), upTo(0) {} void Reset() { active = false; items = workNone; upTo = 0; } void Need(workItems items_, Position pos) { if ((items_ & workStyle) && (upTo < pos)) upTo = pos; items = static_cast<workItems>(items | items_); } }; /** * Hold a piece of text selected for copying or dragging, along with encoding and selection format information. */ class SelectionText { std::string s; public: bool rectangular; bool lineCopy; int codePage; int characterSet; SelectionText() : rectangular(false), lineCopy(false), codePage(0), characterSet(0) {} ~SelectionText() { } void Clear() { s.clear(); rectangular = false; lineCopy = false; codePage = 0; characterSet = 0; } void Copy(const std::string &s_, int codePage_, int characterSet_, bool rectangular_, bool lineCopy_) { s = s_; codePage = codePage_; characterSet = characterSet_; rectangular = rectangular_; lineCopy = lineCopy_; FixSelectionForClipboard(); } void Copy(const SelectionText &other) { Copy(other.s, other.codePage, other.characterSet, other.rectangular, other.lineCopy); } const char *Data() const { return s.c_str(); } size_t Length() const { return s.length(); } size_t LengthWithTerminator() const { return s.length() + 1; } bool Empty() const { return s.empty(); } private: void FixSelectionForClipboard() { // To avoid truncating the contents of the clipboard when pasted where the // clipboard contains NUL characters, replace NUL characters by spaces. std::replace(s.begin(), s.end(), '\0', ' '); } }; struct WrapPending { // The range of lines that need to be wrapped enum { lineLarge = 0x7ffffff }; int start; // When there are wraps pending, will be in document range int end; // May be lineLarge to indicate all of document after start WrapPending() { start = lineLarge; end = lineLarge; } void Reset() { start = lineLarge; end = lineLarge; } void Wrapped(int line) { if (start == line) start++; } bool NeedsWrap() const { return start < end; } bool AddRange(int lineStart, int lineEnd) { const bool neededWrap = NeedsWrap(); bool changed = false; if (start > lineStart) { start = lineStart; changed = true; } if ((end < lineEnd) || !neededWrap) { end = lineEnd; changed = true; } return changed; } }; /** */ class Editor : public EditModel, public DocWatcher { // Private so Editor objects can not be copied Editor(const Editor &); Editor &operator=(const Editor &); public: // ScintillaBase subclass needs access to much of Editor /** On GTK+, Scintilla is a container widget holding two scroll bars * whereas on Windows there is just one window with both scroll bars turned on. */ Window wMain; ///< The Scintilla parent window Window wMargin; ///< May be separate when using a scroll view for wMain /** Style resources may be expensive to allocate so are cached between uses. * When a style attribute is changed, this cache is flushed. */ bool stylesValid; ViewStyle vs; int technology; Point sizeRGBAImage; float scaleRGBAImage; MarginView marginView; EditView view; int cursorMode; bool hasFocus; bool mouseDownCaptures; int xCaretMargin; ///< Ensure this many pixels visible on both sides of caret bool horizontalScrollBarVisible; int scrollWidth; bool verticalScrollBarVisible; bool endAtLastLine; int caretSticky; int marginOptions; bool mouseSelectionRectangularSwitch; bool multipleSelection; bool additionalSelectionTyping; int multiPasteMode; int virtualSpaceOptions; KeyMap kmap; Timer timer; Timer autoScrollTimer; enum { autoScrollDelay = 200 }; Idler idler; Point lastClick; unsigned int lastClickTime; Point doubleClickCloseThreshold; int dwellDelay; int ticksToDwell; bool dwelling; enum { selChar, selWord, selSubLine, selWholeLine } selectionType; Point ptMouseLast; enum { ddNone, ddInitial, ddDragging } inDragDrop; bool dropWentOutside; SelectionPosition posDrop; int hotSpotClickPos; int lastXChosen; int lineAnchorPos; int originalAnchorPos; int wordSelectAnchorStartPos; int wordSelectAnchorEndPos; int wordSelectInitialCaretPos; int targetStart; int targetEnd; int searchFlags; int topLine; int posTopLine; int lengthForEncode; int needUpdateUI; enum { notPainting, painting, paintAbandoned } paintState; bool paintAbandonedByStyling; PRectangle rcPaint; bool paintingAllText; bool willRedrawAll; WorkNeeded workNeeded; int modEventMask; SelectionText drag; int caretXPolicy; int caretXSlop; ///< Ensure this many pixels visible on both sides of caret int caretYPolicy; int caretYSlop; ///< Ensure this many lines visible on both sides of caret int visiblePolicy; int visibleSlop; int searchAnchor; bool recordingMacro; int foldAutomatic; // Wrapping support WrapPending wrapPending; bool convertPastes; Editor(); virtual ~Editor(); virtual void Initialise() = 0; virtual void Finalise(); void InvalidateStyleData(); void InvalidateStyleRedraw(); void RefreshStyleData(); void SetRepresentations(); void DropGraphics(bool freeObjects); void AllocateGraphics(); // The top left visible point in main window coordinates. Will be 0,0 except for // scroll views where it will be equivalent to the current scroll position. virtual Point GetVisibleOriginInMain() const; Point DocumentPointFromView(Point ptView) const; // Convert a point from view space to document int TopLineOfMain() const; // Return the line at Main's y coordinate 0 virtual PRectangle GetClientRectangle() const; virtual PRectangle GetClientDrawingRectangle(); PRectangle GetTextRectangle() const; virtual int LinesOnScreen() const; int LinesToScroll() const; int MaxScrollPos() const; SelectionPosition ClampPositionIntoDocument(SelectionPosition sp) const; Point LocationFromPosition(SelectionPosition pos); Point LocationFromPosition(int pos); int XFromPosition(int pos); int XFromPosition(SelectionPosition sp); SelectionPosition SPositionFromLocation(Point pt, bool canReturnInvalid=false, bool charPosition=false, bool virtualSpace=true); int PositionFromLocation(Point pt, bool canReturnInvalid = false, bool charPosition = false); SelectionPosition SPositionFromLineX(int lineDoc, int x); int PositionFromLineX(int line, int x); int LineFromLocation(Point pt) const; void SetTopLine(int topLineNew); virtual bool AbandonPaint(); virtual void RedrawRect(PRectangle rc); virtual void DiscardOverdraw(); virtual void Redraw(); void RedrawSelMargin(int line=-1, bool allAfter=false); PRectangle RectangleFromRange(Range r, int overlap); void InvalidateRange(int start, int end); bool UserVirtualSpace() const { return ((virtualSpaceOptions & SCVS_USERACCESSIBLE) != 0); } int CurrentPosition() const; bool SelectionEmpty() const; SelectionPosition SelectionStart(); SelectionPosition SelectionEnd(); void SetRectangularRange(); void ThinRectangularRange(); void InvalidateSelection(SelectionRange newMain, bool invalidateWholeSelection=false); void SetSelection(SelectionPosition currentPos_, SelectionPosition anchor_); void SetSelection(int currentPos_, int anchor_); void SetSelection(SelectionPosition currentPos_); void SetSelection(int currentPos_); void SetEmptySelection(SelectionPosition currentPos_); void SetEmptySelection(int currentPos_); bool RangeContainsProtected(int start, int end) const; bool SelectionContainsProtected(); int MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd=true) const; SelectionPosition MovePositionOutsideChar(SelectionPosition pos, int moveDir, bool checkLineEnd=true) const; int MovePositionTo(SelectionPosition newPos, Selection::selTypes selt=Selection::noSel, bool ensureVisible=true); int MovePositionTo(int newPos, Selection::selTypes selt=Selection::noSel, bool ensureVisible=true); SelectionPosition MovePositionSoVisible(SelectionPosition pos, int moveDir); SelectionPosition MovePositionSoVisible(int pos, int moveDir); Point PointMainCaret(); void SetLastXChosen(); void ScrollTo(int line, bool moveThumb=true); virtual void ScrollText(int linesToMove); void HorizontalScrollTo(int xPos); void VerticalCentreCaret(); void MoveSelectedLines(int lineDelta); void MoveSelectedLinesUp(); void MoveSelectedLinesDown(); void MoveCaretInsideView(bool ensureVisible=true); int DisplayFromPosition(int pos); struct XYScrollPosition { int xOffset; int topLine; XYScrollPosition(int xOffset_, int topLine_) : xOffset(xOffset_), topLine(topLine_) {} bool operator==(const XYScrollPosition &other) const { return (xOffset == other.xOffset) && (topLine == other.topLine); } }; enum XYScrollOptions { xysUseMargin=0x1, xysVertical=0x2, xysHorizontal=0x4, xysDefault=xysUseMargin|xysVertical|xysHorizontal}; XYScrollPosition XYScrollToMakeVisible(const SelectionRange &range, const XYScrollOptions options); void SetXYScroll(XYScrollPosition newXY); void EnsureCaretVisible(bool useMargin=true, bool vert=true, bool horiz=true); void ScrollRange(SelectionRange range); void ShowCaretAtCurrentPosition(); void DropCaret(); void CaretSetPeriod(int period); void InvalidateCaret(); virtual void UpdateSystemCaret(); bool Wrapping() const; void NeedWrapping(int docLineStart=0, int docLineEnd=WrapPending::lineLarge); bool WrapOneLine(Surface *surface, int lineToWrap); enum wrapScope {wsAll, wsVisible, wsIdle}; bool WrapLines(enum wrapScope ws); void LinesJoin(); void LinesSplit(int pixelWidth); void PaintSelMargin(Surface *surface, PRectangle &rc); void RefreshPixMaps(Surface *surfaceWindow); void Paint(Surface *surfaceWindow, PRectangle rcArea); long FormatRange(bool draw, Sci_RangeToFormat *pfr); int TextWidth(int style, const char *text); virtual void SetVerticalScrollPos() = 0; virtual void SetHorizontalScrollPos() = 0; virtual bool ModifyScrollBars(int nMax, int nPage) = 0; virtual void ReconfigureScrollBars(); void SetScrollBars(); void ChangeSize(); void FilterSelections(); int InsertSpace(int position, unsigned int spaces); void AddChar(char ch); virtual void AddCharUTF(const char *s, unsigned int len, bool treatAsDBCS=false); void FillVirtualSpace(); void InsertPaste(const char *text, int len); enum PasteShape { pasteStream=0, pasteRectangular = 1, pasteLine = 2 }; void InsertPasteShape(const char *text, int len, PasteShape shape); void ClearSelection(bool retainMultipleSelections = false); void ClearAll(); void ClearDocumentStyle(); void Cut(); void PasteRectangular(SelectionPosition pos, const char *ptr, int len); virtual void Copy() = 0; virtual void CopyAllowLine(); virtual bool CanPaste(); virtual void Paste() = 0; void Clear(); void SelectAll(); void Undo(); void Redo(); void DelCharBack(bool allowLineStartDeletion); virtual void ClaimSelection() = 0; static int ModifierFlags(bool shift, bool ctrl, bool alt, bool meta=false); virtual void NotifyChange() = 0; virtual void NotifyFocus(bool focus); virtual void SetCtrlID(int identifier); virtual int GetCtrlID() { return ctrlID; } virtual void NotifyParent(SCNotification scn) = 0; virtual void NotifyStyleToNeeded(int endStyleNeeded); void NotifyChar(int ch); void NotifySavePoint(bool isSavePoint); void NotifyModifyAttempt(); virtual void NotifyDoubleClick(Point pt, int modifiers); virtual void NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt); void NotifyHotSpotClicked(int position, int modifiers); void NotifyHotSpotClicked(int position, bool shift, bool ctrl, bool alt); void NotifyHotSpotDoubleClicked(int position, int modifiers); void NotifyHotSpotDoubleClicked(int position, bool shift, bool ctrl, bool alt); void NotifyHotSpotReleaseClick(int position, int modifiers); void NotifyHotSpotReleaseClick(int position, bool shift, bool ctrl, bool alt); bool NotifyUpdateUI(); void NotifyPainted(); void NotifyIndicatorClick(bool click, int position, int modifiers); void NotifyIndicatorClick(bool click, int position, bool shift, bool ctrl, bool alt); bool NotifyMarginClick(Point pt, int modifiers); bool NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt); void NotifyNeedShown(int pos, int len); void NotifyDwelling(Point pt, bool state); void NotifyZoom(); void NotifyModifyAttempt(Document *document, void *userData); void NotifySavePoint(Document *document, void *userData, bool atSavePoint); void CheckModificationForWrap(DocModification mh); void NotifyModified(Document *document, DocModification mh, void *userData); void NotifyDeleted(Document *document, void *userData); void NotifyStyleNeeded(Document *doc, void *userData, int endPos); void NotifyLexerChanged(Document *doc, void *userData); void NotifyErrorOccurred(Document *doc, void *userData, int status); void NotifyMacroRecord(unsigned int iMessage, uptr_t wParam, sptr_t lParam); void ContainerNeedsUpdate(int flags); void PageMove(int direction, Selection::selTypes selt=Selection::noSel, bool stuttered = false); enum { cmSame, cmUpper, cmLower }; virtual std::string CaseMapString(const std::string &s, int caseMapping); void ChangeCaseOfSelection(int caseMapping); void LineTranspose(); void Duplicate(bool forLine); virtual void CancelModes(); void NewLine(); void CursorUpOrDown(int direction, Selection::selTypes selt=Selection::noSel); void ParaUpOrDown(int direction, Selection::selTypes selt=Selection::noSel); int StartEndDisplayLine(int pos, bool start); virtual int KeyCommand(unsigned int iMessage); virtual int KeyDefault(int /* key */, int /*modifiers*/); int KeyDownWithModifiers(int key, int modifiers, bool *consumed); int KeyDown(int key, bool shift, bool ctrl, bool alt, bool *consumed=0); void Indent(bool forwards); virtual CaseFolder *CaseFolderForEncoding(); long FindText(uptr_t wParam, sptr_t lParam); void SearchAnchor(); long SearchText(unsigned int iMessage, uptr_t wParam, sptr_t lParam); long SearchInTarget(const char *text, int length); void GoToLine(int lineNo); virtual void CopyToClipboard(const SelectionText &selectedText) = 0; std::string RangeText(int start, int end) const; void CopySelectionRange(SelectionText *ss, bool allowLineCopy=false); void CopyRangeToClipboard(int start, int end); void CopyText(int length, const char *text); void SetDragPosition(SelectionPosition newPos); virtual void DisplayCursor(Window::Cursor c); virtual bool DragThreshold(Point ptStart, Point ptNow); virtual void StartDrag(); void DropAt(SelectionPosition position, const char *value, size_t lengthValue, bool moving, bool rectangular); void DropAt(SelectionPosition position, const char *value, bool moving, bool rectangular); /** PositionInSelection returns true if position in selection. */ bool PositionInSelection(int pos); bool PointInSelection(Point pt); bool PointInSelMargin(Point pt) const; Window::Cursor GetMarginCursor(Point pt) const; void TrimAndSetSelection(int currentPos_, int anchor_); void LineSelection(int lineCurrentPos_, int lineAnchorPos_, bool wholeLine); void WordSelection(int pos); void DwellEnd(bool mouseMoved); void MouseLeave(); virtual void ButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers); virtual void ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt); void ButtonMoveWithModifiers(Point pt, int modifiers); void ButtonMove(Point pt); void ButtonUp(Point pt, unsigned int curTime, bool ctrl); void Tick(); bool Idle(); virtual void SetTicking(bool on); enum TickReason { tickCaret, tickScroll, tickWiden, tickDwell, tickPlatform }; virtual void TickFor(TickReason reason); virtual bool FineTickerAvailable(); virtual bool FineTickerRunning(TickReason reason); virtual void FineTickerStart(TickReason reason, int millis, int tolerance); virtual void FineTickerCancel(TickReason reason); virtual bool SetIdle(bool) { return false; } virtual void SetMouseCapture(bool on) = 0; virtual bool HaveMouseCapture() = 0; void SetFocusState(bool focusState); int PositionAfterArea(PRectangle rcArea) const; void StyleToPositionInView(Position pos); virtual void IdleWork(); virtual void QueueIdleWork(WorkNeeded::workItems items, int upTo=0); virtual bool PaintContains(PRectangle rc); bool PaintContainsMargin(); void CheckForChangeOutsidePaint(Range r); void SetBraceHighlight(Position pos0, Position pos1, int matchStyle); void SetAnnotationHeights(int start, int end); virtual void SetDocPointer(Document *document); void SetAnnotationVisible(int visible); int ExpandLine(int line); void SetFoldExpanded(int lineDoc, bool expanded); void FoldLine(int line, int action); void FoldExpand(int line, int action, int level); int ContractedFoldNext(int lineStart) const; void EnsureLineVisible(int lineDoc, bool enforcePolicy); void FoldChanged(int line, int levelNow, int levelPrev); void NeedShown(int pos, int len); void FoldAll(int action); int GetTag(char *tagValue, int tagNumber); int ReplaceTarget(bool replacePatterns, const char *text, int length=-1); bool PositionIsHotspot(int position) const; bool PointIsHotspot(Point pt); void SetHotSpotRange(Point *pt); Range GetHotSpotRange() const; int CodePage() const; virtual bool ValidCodePage(int /* codePage */) const { return true; } int WrapCount(int line); void AddStyledText(char *buffer, int appendLength); virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) = 0; void StyleSetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam); sptr_t StyleGetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam); static const char *StringFromEOLMode(int eolMode); static sptr_t StringResult(sptr_t lParam, const char *val); static sptr_t BytesResult(sptr_t lParam, const unsigned char *val, size_t len); public: // Public so the COM thunks can access it. bool IsUnicodeMode() const; // Public so scintilla_send_message can use it. virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam); // Public so scintilla_set_id can use it. int ctrlID; // Public so COM methods for drag and drop can set it. int errorStatus; friend class AutoSurface; friend class SelectionLineIterator; }; /** * A smart pointer class to ensure Surfaces are set up and deleted correctly. */ class AutoSurface { private: Surface *surf; public: AutoSurface(Editor *ed, int technology = -1) : surf(0) { if (ed->wMain.GetID()) { surf = Surface::Allocate(technology != -1 ? technology : ed->technology); if (surf) { surf->Init(ed->wMain.GetID()); surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage()); surf->SetDBCSMode(ed->CodePage()); } } } AutoSurface(SurfaceID sid, Editor *ed, int technology = -1) : surf(0) { if (ed->wMain.GetID()) { surf = Surface::Allocate(technology != -1 ? technology : ed->technology); if (surf) { surf->Init(sid, ed->wMain.GetID()); surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage()); surf->SetDBCSMode(ed->CodePage()); } } } ~AutoSurface() { delete surf; } Surface *operator->() const { return surf; } operator Surface *() const { return surf; } }; #ifdef SCI_NAMESPACE } #endif #endif
479bb1fcef57f13f3f2885a42f9e41a3b1df2757
fff5ed7a084d26164600d4ea33eb2fb284dd6aa3
/src/vigra_tensors_c.cxx
3582d2f650e89a61476dcb269805ae2b423ff7bb
[ "MIT" ]
permissive
BSeppke/vigra_c
0ea278de8db5dd8ef6fcd634cff17e55c7d2e31d
49f53191a12fe91d4e2fd177d22af167571c71d8
refs/heads/master
2022-02-04T15:21:22.533051
2022-01-23T14:17:07
2022-01-23T14:17:07
19,816,975
2
3
null
null
null
null
UTF-8
C++
false
false
24,439
cxx
/************************************************************************/ /* */ /* Copyright 2008-2017 by Benjamin Seppke */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of VIGRA_C package. For more infos visit: */ /* https://github.com/bseppke/vigra_c */ /* Please direct questions, bug reports, and contributions to */ /* the GitHub page and use the methods provided there. */ /* */ /* 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 "vigra_tensors_c.h" #include "vigra_kernelutils_c.h" #include <vigra/tensorutilities.hxx> #include <vigra/gradient_energy_tensor.hxx> #include <vigra/boundarytensor.hxx> #include <vigra/orientedtensorfilters.hxx> /** * @file * @brief Implementation of Tensor-based algorithms */ /** * Computation of the Structure Tensor of an image band. * This function wraps the * <a href="https://ukoethe.github.io/vigra/doc-release/vigra/group__ConvolutionFilters.html"> * vigra::structureTensor * </a> * function to C to compute the spatially smoothed products * of the first order image derivatives: smooth(I_x^2), smooth(I_x*I_y) and * smooth(I_y^2). The gradient estinmation is performed by convolutions with * derived Gaussian kernels of a given std. dev. The smoothing is also performed * by a convolution with gaussian, but at another scale. * All arrays must have been allocated before the call of this function. * * \param arr_in Flat input array (band) of size width*height. * \param[out] arr_xx_out Flat array (smooth(I_x^2)) of size width*height. * \param[out] arr_xy_out Flat array (smooth(I_x*I_y)) of size width*height. * \param[out] arr_yy_out Flat array (smooth(I_y^2)) of size width*height. * \param width The width of the flat array. * \param height The height of the flat array. * \param inner_scale The scale (gaussian std.dev.) for the derivative computation. * \param outer_scale The scale (gaussian std.dev.) for the smoothing computation. * * \return 0 if the Structure Tensor was computed successfully, 1 else. */ LIBEXPORT int vigra_structuretensor_c(const PixelType * arr_in, const PixelType * arr_xx_out, const PixelType * arr_xy_out, const PixelType * arr_yy_out, const int width, const int height, const float inner_scale, const float outer_scale) { try { //Create gray scale image views for the arrays vigra::Shape2 shape(width,height); ImageView img_in(shape, arr_in); ImageView img_xx(shape, arr_xx_out); ImageView img_xy(shape, arr_xy_out); ImageView img_yy(shape, arr_yy_out); vigra::structureTensor(img_in, img_xx, img_xy, img_yy, inner_scale, outer_scale); } catch (vigra::StdException & e) { return 1; } return 0; } /** * Computation of the Boundary Tensor of an image band. * This function wraps the * <a href="https://ukoethe.github.io/vigra/doc-release/vigra/group__TensorImaging.html"> * vigra::boundaryTensor * </a> * function to C. * All arrays must have been allocated before the call of this function. * * \param arr_in Flat input array (band) of size width*height. * \param[out] arr_xx_out Flat array (Boundary Tensor xx) of size width*height. * \param[out] arr_xy_out Flat array (Boundary Tensor xy) of size width*height. * \param[out] arr_yy_out Flat array (Boundary Tensor yy) of size width*height. * \param width The width of the flat array. * \param height The height of the flat array. * \param scale The scale (gaussian std.dev.) of the boundary tensor. * * \return 0 if the Boundary Tensor was computed successfully, 1 else. */ LIBEXPORT int vigra_boundarytensor_c(const PixelType * arr_in, const PixelType * arr_xx_out, const PixelType * arr_xy_out, const PixelType * arr_yy_out, const int width, const int height, const float scale) { try { //Create gray scale image views for the arrays vigra::Shape2 shape(width,height); ImageView img_in(shape, arr_in); ImageView img_xx(shape, arr_xx_out); ImageView img_xy(shape, arr_xy_out); ImageView img_yy(shape, arr_yy_out); //create the temporary tensor vigra::MultiArray<2, vigra::TinyVector<float, 3> > tensor(width,height); vigra::boundaryTensor(img_in, tensor, scale); auto xx_iter = img_xx.begin(), xy_iter = img_xy.begin(), yy_iter = img_yy.begin(); for(auto t_iter = tensor.begin(); t_iter != tensor.end(); ++t_iter, ++ xx_iter, ++xy_iter, ++yy_iter) { *xx_iter = t_iter->operator[](0); *xy_iter = t_iter->operator[](1); *yy_iter = t_iter->operator[](2); } } catch (vigra::StdException & e) { return 1; } return 0; } /** * Computation of the Boundary Tensor (without the zero order component) of an * image band. * This function wraps the * <a href="https://ukoethe.github.io/vigra/doc-release/vigra/group__TensorImaging.html"> * vigra::boundaryTensor1 * </a> * function to C. * All arrays must have been allocated before the call of this function. * * \param arr_in Flat input array (band) of size width*height. * \param[out] arr_xx_out Flat array (Boundary Tensor xx) of size width*height. * \param[out] arr_xy_out Flat array (Boundary Tensor xy) of size width*height. * \param[out] arr_yy_out Flat array (Boundary Tensor yy) of size width*height. * \param width The width of the flat array. * \param height The height of the flat array. * \param scale The scale (gaussian std.dev.) of the boundary tensor. * * \return 0 if the Boundary Tensor was computed successfully, 1 else. */ LIBEXPORT int vigra_boundarytensor1_c(const PixelType * arr_in, const PixelType * arr_xx_out, const PixelType * arr_xy_out, const PixelType * arr_yy_out, const int width, const int height, const float scale) { try { //Create gray scale image views for the arrays vigra::Shape2 shape(width,height); ImageView img_in(shape, arr_in); ImageView img_xx(shape, arr_xx_out); ImageView img_xy(shape, arr_xy_out); ImageView img_yy(shape, arr_yy_out); //create the temporary tensor vigra::MultiArray<2, vigra::TinyVector<float, 3> > tensor(width,height); vigra::boundaryTensor1(img_in, tensor, scale); auto xx_iter = img_xx.begin(), xy_iter = img_xy.begin(), yy_iter = img_yy.begin(); for(auto t_iter = tensor.begin(); t_iter != tensor.end(); ++t_iter, ++ xx_iter, ++xy_iter, ++yy_iter) { *xx_iter = t_iter->operator[](0); *xy_iter = t_iter->operator[](1); *yy_iter = t_iter->operator[](2); } } catch (vigra::StdException & e) { return 1; } return 0; } /** * Computation of the Gradient Energy Tensor of an image band. * This function wraps the * <a href="https://ukoethe.github.io/vigra/doc-release/vigra/group__TensorImaging.html"> * vigra::gradientEnergyTensor * </a> * function to C. * All arrays must have been allocated before the call of this function. * * \param arr_in Flat input array (band) of size width*height. * \param arr_derivKernel_in Flat input array (derivation kernel) of size derivKernel_size. * \param arr_smoothKernel_in Flat input array (smoothing kernel) of size smoothKernel_size. * \param[out] arr_xx_out Flat array (Boundary Tensor xx) of size width*height. * \param[out] arr_xy_out Flat array (Boundary Tensor xy) of size width*height. * \param[out] arr_yy_out Flat array (Boundary Tensor yy) of size width*height. * \param width The width of the flat array. * \param height The height of the flat array. * \param derivKernel_size The size of the derivative kernel array. * \param smoothKernel_size The size of the smoothing kernel array. * * \return 0 if the Gradient Energy Tensor was computed successfully, * 2 if kernel dimensions are not odd, * 1 else. */ LIBEXPORT int vigra_gradientenergytensor_c(const PixelType * arr_in, const double * arr_derivKernel_in, const double * arr_smoothKernel_in, const PixelType * arr_xx_out, const PixelType * arr_xy_out, const PixelType * arr_yy_out, const int width, const int height, const int derivKernel_size, const int smoothKernel_size) { try { //Create gray scale image views for the arrays vigra::Shape2 shape(width,height); ImageView img_in(shape, arr_in); ImageView img_xx(shape, arr_xx_out); ImageView img_xy(shape, arr_xy_out); ImageView img_yy(shape, arr_yy_out); //check if kernel dimensions are odd if ( (derivKernel_size % 2)==0 || (smoothKernel_size % 2)==0) return 2; //create the temporary tensor vigra::MultiArray<2, vigra::TinyVector<float, 3> > tensor(width,height); vigra::gradientEnergyTensor(img_in, tensor, kernel1dFromArray(arr_derivKernel_in, derivKernel_size), kernel1dFromArray(arr_smoothKernel_in, smoothKernel_size)); auto xx_iter = img_xx.begin(), xy_iter = img_xy.begin(), yy_iter = img_yy.begin(); for(auto t_iter = tensor.begin(); t_iter != tensor.end(); ++t_iter, ++ xx_iter, ++xy_iter, ++yy_iter) { *xx_iter = t_iter->operator[](0); *xy_iter = t_iter->operator[](1); *yy_iter = t_iter->operator[](2); } } catch (vigra::StdException & e) { return 1; } return 0; } /** * Computation of the Eigenvalue/Eigenvector representation of a tensor. * This function wraps the * <a href="https://ukoethe.github.io/vigra/doc-release/vigra/group__TensorImaging.html"> * vigra::tensorEigenRepresentation * </a> * function to C. * All arrays must have been allocated before the call of this function. * * \param arr_xx_in Flat array (Tensor xx) of size width*height. * \param arr_xy_in Flat array (Tensor xy) of size width*height. * \param arr_yy_in Flat array (Tensor yy) of size width*height. * \param[out] arr_lEV_out Flat array (major Eigenvalues) of size width*height. * \param[out] arr_sEV_out Flat array (minor Eigenvalues) of size width*height. * \param[out] arr_ang_out Flat array (angle of largest Eigenvalue) of size width*height. * \param width The width of the flat array. * \param height The height of the flat array. * * \return 0 if the Eigenvalues were computed successfully, 1 else */ LIBEXPORT int vigra_tensoreigenrepresentation_c(const PixelType * arr_xx_in, const PixelType * arr_xy_in, const PixelType * arr_yy_in, const PixelType * arr_lEV_out, const PixelType * arr_sEV_out, const PixelType * arr_ang_out, const int width, const int height) { try { //Create gray scale image views for the arrays vigra::Shape2 shape(width,height); ImageView img_xx(shape, arr_xx_in); ImageView img_xy(shape, arr_xy_in); ImageView img_yy(shape, arr_yy_in); ImageView img_lEV(shape, arr_lEV_out); ImageView img_sEV(shape, arr_sEV_out); ImageView img_ang(shape, arr_ang_out); //create the temporary tensor vigra::MultiArray<2, vigra::TinyVector<float, 3> > tensor(width,height); auto xx_iter = img_xx.begin(), xy_iter = img_xy.begin(), yy_iter = img_yy.begin(); for(auto t_iter = tensor.begin(); t_iter != tensor.end(); ++t_iter, ++ xx_iter, ++xy_iter, ++yy_iter) { t_iter->operator[](0) = *xx_iter; t_iter->operator[](1) = *xy_iter; t_iter->operator[](2) = *yy_iter; } vigra::tensorEigenRepresentation(tensor, tensor); auto lEV_iter = img_lEV.begin(), sEV_iter = img_sEV.begin(), ang_iter = img_ang.begin(); for(auto t_iter = tensor.begin(); t_iter != tensor.end(); ++t_iter, ++ lEV_iter, ++sEV_iter, ++ang_iter) { *lEV_iter = t_iter->operator[](0); *sEV_iter = t_iter->operator[](1); *ang_iter = t_iter->operator[](2); } } catch (vigra::StdException & e) { return 1; } return 0; } /** * Computation of the trace of a tensor. * This function wraps the * <a href="https://ukoethe.github.io/vigra/doc-release/vigra/group__TensorImaging.html"> * vigra::tensorTrace * </a> * function to C. * All arrays must have been allocated before the call of this function. * * \param arr_xx_in Flat array (Tensor xx) of size width*height. * \param arr_xy_in Flat array (Tensor xy) of size width*height. * \param arr_yy_in Flat array (Tensor yy) of size width*height. * \param[out] arr_trace_out Flat array (trace of the tensor) of size width*height. * \param width The width of the flat array. * \param height The height of the flat array. * * \return 0 if the Tensor trace was computed successfully, 1 else */ LIBEXPORT int vigra_tensortrace_c(const PixelType * arr_xx_in, const PixelType * arr_xy_in, const PixelType * arr_yy_in, const PixelType * arr_trace_out, const int width, const int height) { try { //Create gray scale image views for the arrays vigra::Shape2 shape(width,height); ImageView img_xx(shape, arr_xx_in); ImageView img_xy(shape, arr_xy_in); ImageView img_yy(shape, arr_yy_in); ImageView img_trace(shape, arr_trace_out); //create the temporary tensor vigra::MultiArray<2, vigra::TinyVector<float, 3> > tensor(width,height); auto xx_iter = img_xx.begin(), xy_iter = img_xy.begin(), yy_iter = img_yy.begin(); for(auto t_iter = tensor.begin(); t_iter != tensor.end(); ++t_iter, ++ xx_iter, ++xy_iter, ++yy_iter) { t_iter->operator[](0) = *xx_iter; t_iter->operator[](1) = *xy_iter; t_iter->operator[](2) = *yy_iter; } vigra::tensorTrace(tensor, img_trace); } catch (vigra::StdException & e) { return 1; } return 0; } /** * Computation of the Edgeness/Cornerness representation of a tensor. * This function wraps the * <a href="https://ukoethe.github.io/vigra/doc-release/vigra/group__TensorImaging.html"> * vigra::tensorToEdgeCorner * </a> * function to C. * All arrays must have been allocated before the call of this function. * * \param arr_xx_in Flat array (Tensor xx) of size width*height. * \param arr_xy_in Flat array (Tensor xy) of size width*height. * \param arr_yy_in Flat array (Tensor yy) of size width*height. * \param[out] arr_edgeness_out Flat array (edgeness) of size width*height. * \param[out] arr_orientation_out Flat array (orientation of the edge) of size width*height. * \param[out] arr_cornerness_out Flat array (cornerness) of size width*height. * \param width The width of the flat array. * \param height The height of the flat array. * * \return 0 if the Edgeness/Cornerness was computed successfully, 1 else */ LIBEXPORT int vigra_tensortoedgecorner_c(const PixelType * arr_xx_in, const PixelType * arr_xy_in, const PixelType * arr_yy_in, const PixelType * arr_edgeness_out, const PixelType * arr_orientation_out, const PixelType * arr_cornerness_out, const int width, const int height) { try { //Create gray scale image views for the arrays vigra::Shape2 shape(width,height); ImageView img_xx(shape, arr_xx_in); ImageView img_xy(shape, arr_xy_in); ImageView img_yy(shape, arr_yy_in); ImageView img_edgeness(shape, arr_edgeness_out); ImageView img_orientation(shape, arr_orientation_out); ImageView img_cornerness(shape, arr_cornerness_out); //create the temporary tensor vigra::MultiArray<2, vigra::TinyVector<float, 3> > tensor(width,height); vigra::MultiArray<2, vigra::TinyVector<float, 2> > edgePart(width,height); auto xx_iter = img_xx.begin(), xy_iter = img_xy.begin(), yy_iter = img_yy.begin(); for(auto t_iter = tensor.begin(); t_iter != tensor.end(); ++t_iter, ++ xx_iter, ++xy_iter, ++yy_iter) { t_iter->operator[](0) = *xx_iter; t_iter->operator[](1) = *xy_iter; t_iter->operator[](2) = *yy_iter; } vigra::tensorToEdgeCorner(tensor, edgePart, img_cornerness); auto edgeness_iter = img_edgeness.begin(), orientation_iter = img_orientation.begin(); for(auto e_iter = edgePart.begin(); e_iter != edgePart.end(); ++e_iter, ++ edgeness_iter, ++orientation_iter) { *edgeness_iter = e_iter->operator[](0); *orientation_iter = e_iter->operator[](1); } } catch (vigra::StdException & e) { return 1; } return 0; } /** * Filtering of a tensor using the Hourglass filter. * This function wraps the correct application of the * <a href="https://ukoethe.github.io/vigra/doc-release/vigra/group__TensorImaging.html"> * vigra::hourGlassFilter * </a> * function to C. * All arrays must have been allocated before the call of this function. * * \param arr_xx_in Flat array (Tensor xx) of size width*height. * \param arr_xy_in Flat array (Tensor xy) of size width*height. * \param arr_yy_in Flat array (Tensor yy) of size width*height. * \param[out] arr_hgxx_out Flat array (filtered Tensor xx) of size width*height. * \param[out] arr_hgxy_out Flat array (filtered Tensor xy) of size width*height. * \param[out] arr_hgyy_out array (filtered Tensor yy) of size width*height. * \param width The width of the flat array. * \param height The height of the flat array. * \param sigma The std. dev. of the Hourglass Filter. * \param rho The opening angle of the Hourglass Filter. * * \return 0 if the Tensor filtering was successful, 1 else */ LIBEXPORT int vigra_hourglassfilter_c(const PixelType * arr_xx_in, const PixelType * arr_xy_in, const PixelType * arr_yy_in, const PixelType * arr_hgxx_out, const PixelType * arr_hgxy_out, const PixelType * arr_hgyy_out, const int width, const int height, const float sigma, const float rho) { try { //Create gray scale image views for the arrays vigra::Shape2 shape(width,height); ImageView img_xx(shape, arr_xx_in); ImageView img_xy(shape, arr_xy_in); ImageView img_yy(shape, arr_yy_in); ImageView img_hgxx(shape, arr_hgxx_out); ImageView img_hgxy(shape, arr_hgxy_out); ImageView img_hgyy(shape, arr_hgyy_out); //create the temporary tensor vigra::MultiArray<2, vigra::TinyVector<float, 3> > tensor(width,height); vigra::MultiArray<2, vigra::TinyVector<float, 3> > hg_tensor(width,height); auto xx_iter = img_xx.begin(), xy_iter = img_xy.begin(), yy_iter = img_yy.begin(); for(auto t_iter = tensor.begin(); t_iter != tensor.end(); ++t_iter, ++ xx_iter, ++xy_iter, ++yy_iter) { t_iter->operator[](0) = *xx_iter; t_iter->operator[](1) = *xy_iter; t_iter->operator[](2) = *yy_iter; } vigra::tensorEigenRepresentation(tensor, tensor); vigra::hourGlassFilter(tensor, hg_tensor, sigma, rho); auto hgxx_iter = img_hgxx.begin(), hgxy_iter = img_hgxy.begin(), hgyy_iter = img_hgyy.begin(); for(auto hg_iter = hg_tensor.begin(); hg_iter != hg_tensor.end(); ++hg_iter, ++hgxx_iter, ++hgxy_iter, ++hgyy_iter) { *hgxx_iter = hg_iter->operator[](0); *hgxy_iter = hg_iter->operator[](1); *hgyy_iter = hg_iter->operator[](2); } } catch (vigra::StdException & e) { return 1; } return 0; }
45e0eec0a2b28fe44477675c0ccf37ee1f5aa7b2
e2dbb60b0aaf53a9ed4f13807102d06c0a3705ca
/boost/asio-ssl/server_connection.hpp
37c20d499c3a0deba6719f36e656f2c3e9c06f00
[]
no_license
tiagobonetti/refcode
aad6ce55cd08efd345f8018c32e457ae085c7179
98f76a7db680ac6fc0d142746c3e74fb4eeba2c8
refs/heads/master
2021-06-12T20:12:31.438058
2019-09-06T11:43:41
2019-09-06T11:43:41
58,228,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,611
hpp
#pragma once #include "server_connection.hpp" #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <atomic> #include <memory> #include <vector> class server_connection { public: server_connection(boost::asio::io_service &ioService, boost::asio::ssl::context &context, std::size_t messageSize) : m_socket{ioService, context}, m_buffer(messageSize) { ++s_runningConnections; } ~server_connection() { --s_runningConnections; } boost::asio::ssl::stream<boost::asio::ip::tcp::socket>::lowest_layer_type &socket() { return m_socket.lowest_layer(); } void start(std::shared_ptr<server_connection> self, std::size_t messages) { m_socket.async_handshake(boost::asio::ssl::stream_base::server, [=](const boost::system::error_code &) { async_read(self, messages); }); } static std::size_t running_connections() { return s_runningConnections; } private: void async_read(std::shared_ptr<server_connection> self, std::size_t messages) { boost::asio::async_read(m_socket, boost::asio::buffer(m_buffer), [=](const boost::system::error_code &, std::size_t) { if (messages > 1) async_read(self, messages - 1); }); } static std::atomic<std::size_t> s_runningConnections; boost::asio::ssl::stream<boost::asio::ip::tcp::socket> m_socket; std::vector<char> m_buffer; }; std::atomic<std::size_t> server_connection::s_runningConnections{0};
c1279d19011527d1837f1206f469c8d02eff5b00
efc690fe9f8e156e64b24152f1a86069c84f7900
/MayCached/engine/src/RequestController.cpp
af7b2e582d2b9c4e223f2e141ef818f38d9ba6a8
[]
no_license
MayRiv/MayMemCached2
e54c46bc82915239877180b651b4cd75ebb8c72c
beab4927883ed9de3e95910254f088f5c0960cc6
refs/heads/master
2020-03-23T20:08:40.607604
2019-07-25T11:35:28
2019-07-25T11:35:28
142,024,177
1
0
null
null
null
null
UTF-8
C++
false
false
800
cpp
#include <RequestController.hpp> #include <string> #include <memory> #include <RequestParser.hpp> namespace maycached { namespace engine { RequestController::RequestController(gsl::not_null<logic::ILogicController *> lController):m_LogicController(lController) { m_Parser = std::make_unique<RequestParser>(); // has to be created by factory using config } std::string RequestController::handleRequest(const std::string& input) { const auto failed = "Failed to parse&handle the command: " + input; std::string answer{failed}; if (auto&& command = m_Parser->parseCommand(input)) { m_LogicController->handleCommand(*command); answer = command->getAnswer(); } return answer; } void RequestController::start() { } void RequestController::stop() { } } }
66ddda3c415e11f8bfaed100a9d79dd699334639
3cf9e141cc8fee9d490224741297d3eca3f5feff
/C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-5502.cpp
36fa8d573852e27b29fee2f5a85d353dbe39d353
[]
no_license
TeamVault/tauCFI
e0ac60b8106fc1bb9874adc515fc01672b775123
e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10
refs/heads/master
2023-05-30T20:57:13.450360
2021-06-14T09:10:24
2021-06-14T09:10:24
154,563,655
0
1
null
null
null
null
UTF-8
C++
false
false
2,773
cpp
struct c0; void __attribute__ ((noinline)) tester0(c0* p); struct c0 { bool active0; c0() : active0(true) {} virtual ~c0() { tester0(this); active0 = false; } virtual void f0(){} }; void __attribute__ ((noinline)) tester0(c0* p) { p->f0(); } struct c1; void __attribute__ ((noinline)) tester1(c1* p); struct c1 { bool active1; c1() : active1(true) {} virtual ~c1() { tester1(this); active1 = false; } virtual void f1(){} }; void __attribute__ ((noinline)) tester1(c1* p) { p->f1(); } struct c2; void __attribute__ ((noinline)) tester2(c2* p); struct c2 : virtual c0 { bool active2; c2() : active2(true) {} virtual ~c2() { tester2(this); c0 *p0_0 = (c0*)(c2*)(this); tester0(p0_0); active2 = false; } virtual void f2(){} }; void __attribute__ ((noinline)) tester2(c2* p) { p->f2(); if (p->active0) p->f0(); } struct c3; void __attribute__ ((noinline)) tester3(c3* p); struct c3 : c0, virtual c1 { bool active3; c3() : active3(true) {} virtual ~c3() { tester3(this); c0 *p0_0 = (c0*)(c3*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c3*)(this); tester1(p1_0); active3 = false; } virtual void f3(){} }; void __attribute__ ((noinline)) tester3(c3* p) { p->f3(); if (p->active0) p->f0(); if (p->active1) p->f1(); } struct c4; void __attribute__ ((noinline)) tester4(c4* p); struct c4 : virtual c1, c2, virtual c3 { bool active4; c4() : active4(true) {} virtual ~c4() { tester4(this); c0 *p0_0 = (c0*)(c2*)(c4*)(this); tester0(p0_0); c0 *p0_1 = (c0*)(c3*)(c4*)(this); tester0(p0_1); c1 *p1_0 = (c1*)(c4*)(this); tester1(p1_0); c1 *p1_1 = (c1*)(c3*)(c4*)(this); tester1(p1_1); c2 *p2_0 = (c2*)(c4*)(this); tester2(p2_0); c3 *p3_0 = (c3*)(c4*)(this); tester3(p3_0); active4 = false; } virtual void f4(){} }; void __attribute__ ((noinline)) tester4(c4* p) { p->f4(); if (p->active2) p->f2(); if (p->active1) p->f1(); if (p->active3) p->f3(); } int __attribute__ ((noinline)) inc(int v) {return ++v;} int main() { c0* ptrs0[25]; ptrs0[0] = (c0*)(new c0()); ptrs0[1] = (c0*)(c2*)(new c2()); ptrs0[2] = (c0*)(c3*)(new c3()); ptrs0[3] = (c0*)(c2*)(c4*)(new c4()); ptrs0[4] = (c0*)(c3*)(c4*)(new c4()); for (int i=0;i<5;i=inc(i)) { tester0(ptrs0[i]); delete ptrs0[i]; } c1* ptrs1[25]; ptrs1[0] = (c1*)(new c1()); ptrs1[1] = (c1*)(c3*)(new c3()); ptrs1[2] = (c1*)(c4*)(new c4()); ptrs1[3] = (c1*)(c3*)(c4*)(new c4()); for (int i=0;i<4;i=inc(i)) { tester1(ptrs1[i]); delete ptrs1[i]; } c2* ptrs2[25]; ptrs2[0] = (c2*)(new c2()); ptrs2[1] = (c2*)(c4*)(new c4()); for (int i=0;i<2;i=inc(i)) { tester2(ptrs2[i]); delete ptrs2[i]; } c3* ptrs3[25]; ptrs3[0] = (c3*)(new c3()); ptrs3[1] = (c3*)(c4*)(new c4()); for (int i=0;i<2;i=inc(i)) { tester3(ptrs3[i]); delete ptrs3[i]; } c4* ptrs4[25]; ptrs4[0] = (c4*)(new c4()); for (int i=0;i<1;i=inc(i)) { tester4(ptrs4[i]); delete ptrs4[i]; } return 0; }
c7223bcf23a778eb4e09f77dcc92fc6c52aa9c13
65d198c92140ef33e5333d62fab77b89eb60fc58
/Game of amazons/src/Game.cpp
103e4a47ee43c80ee2b1ec33af9806ee549d228f
[]
no_license
OmarKh2000/Game-of-amazons
16d8f124ac0ed96e6c42e2d6c3cd5977e02c2d98
8f7e3f88bd53f6914c48e1b3b607dfb6bf582e9f
refs/heads/master
2023-01-08T19:57:06.851935
2020-11-08T15:08:26
2020-11-08T15:08:26
260,843,164
0
0
null
null
null
null
UTF-8
C++
false
false
7,496
cpp
#include <iostream> #include "Game.h" Game::Game(int size,int time) { this->time = time; board = new int*[size]; for (int i = 0; i < size; ++i) { board[i] = new int[size]; } p1Time = time*1000000*60; p2Time = time*1000000*60; this->size = size; if (size == 10) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { board[i][j] = 0; } board[0][3] = 1; board[0][6] = 1; board[3][0] = 1; board[3][9] = 1; board[9][3] = 2; board[9][6] = 2; board[6][0] = 2; board[6][9] = 2; } else if(size==6) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { board[i][j] = 0; } board[2][1] = 1; board[3][6] = 1; board[0][4] = 2; board[0][6] = 2; } } int Game::getTurn() const { return currentTurn; } int Game::getSize() const { return size; } int Game::getround() { return round; } int Game::getIndex(int i, int j) const { return board[i][j]; } int Game::checkEnd() //chech if someone won. { bool p1Lost = false; bool p2Lost = false; for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { if (!p1Lost && board[i][j] ==1) p1Lost = (p1Lost || checkCanMove(i, j)); if (!p2Lost && board[i][j] == 2) p2Lost = (p2Lost || checkCanMove(i, j)); } if (!p1Lost && !p2Lost) { std::cout << "Player" << ((getTurn() + 1) %2 ) << "has won" <<std::endl; return true; } if (!p1Lost) { std::cout << "Player 2 has won" << std::endl; return true; } if (!p2Lost) { std::cout << "Player 1 has won" << std::endl; return true; } return false; } Game::~Game() { for (int i = 0; i < size; i++) delete[] board[i]; delete board; } int Game::getTime() const { return time; } Game::Game(const Game & game) { this->time = game.getTime(); int size = game.getSize(); if (board == NULL) { board = new int*[size]; for (int i = 0; i < size; ++i) { board[i] = new int[size]; } } for (int i = 0; i < size; i++) { for (int j = 0; j< size; j++) { board[i][j] = game.getIndex(i, j); } } this->currentTurn = game.getTurn(); this->size = game.getSize(); this->round = round; } void Game::applyMove(Move& move, int symbol) { this->round++; if (move.fromX >= 0 && move.fromX < size && move.fromY>=0 && move.fromY < size && move.toX>=0 && move.toY < size && move.shootX>=0 && move.shootY < size) // check if indices are in range. { board[move.fromX][move.fromY] = 0; board[move.toX][move.toX] = symbol; board[move.shootX][move.shootY] = symbol + 2; } } void Game::applyandPrintMove(Move& move, int symbol) { round++; if (move.fromX >= 0 && move.fromX < size && move.fromY>=0 && move.fromY < size && move.toX>=0 && move.toY < size && move.shootX>=0 && move.shootY < size) // check if indices are in range. { board[move.fromX][move.fromY] = 0; board[move.toX][move.toY] = symbol; board[move.shootX][move.shootY] = symbol + 2; } printMove(move); } int Game::updatePlayerTime(int index, int time) //update times { if (index == 1) { p1Time = p1Time - time; return p1Time; } if (index == 2) { p2Time = p2Time - time; return p2Time; } return 0; } void Game::applytemp(Move& move,int symbol) //apply move { board[move.fromX][move.fromY] = 0; board[move.toX][ move.toY] = symbol; } void Game::unapplytemp(Move& move, int symbol) //unapplymove { board[move.fromX][move.fromY] = symbol; board[move.toX][move.toY] = 0; } bool Game::checkCanMove(int i, int j) //check if players can move { int canMove = false; if (i < 0 || i >= size || j < 0 || j >= size) return false; for (int k = i+1; k < size; k++) // Check if player can move right then shoot. { if (board[k][j] == 0 && checkCanShoot(k, j)) return true; else break; } for (int k = i-1; k > 0; k--) // Check if player can move left then shoot. { if (board[k][j] == 0 && checkCanShoot(k, j)) return true; else break; } for (int k = i-1, l = j-1; k > 0 && l > 0; k--, l--) // Check if player can move left-down then shoot. { if (board[k][l] == 0 && checkCanShoot(k, l)) return true; else break; } for (int k = i+1, l = j+1; k < size && l < size; k++, l++) // Check if player can move to the right-up then shoot. { if (board[k][l] == 0 && checkCanShoot(k, l)) return true; else break; } for (int k = j+1; k < size; k++) // Check if player can move to the up then shoot. { if (board[i][k] == 0 && checkCanShoot(i, k)) return true; else break; } for (int k = j-1; k > 0; k--) // Check if player can move to the down then shoot. { if (board[i][k] == 0 && checkCanShoot(i, k)) return true; else break; } for (int k = i-1, l = j+1; k > 0 && l < size; k--, l++) // Check if player can move to the left-up then shoot. { if (board[k][l] == 0 && checkCanShoot(k, l)) return true; else break; } for (int k = i+1, l = j-1; k < size && l >0; k++, l--) // Check if player can move to the right-down then shoot. { if (board[k][l] == 0 && checkCanShoot(k, l)) return true; else break; } return false; } bool Game::checkCanShoot(int i, int j) { if (i < 0 || i >= size || j < 0 || j >= size) return false; for (int k = i; k < size; k++) // Check if player shoot to the right. { if (board[k][j]) return true; else break; } for (int k = i; k > 0; k--) // Check if player can shoot to the left. { if (board[k][j]) return true; else break; } for (int k = i, l = j; k > 0 && l > 0; k--, l--) // Check if player can shoot to left-down. { if (board[k][l] == 0) return true; else break; } for (int k = i, l = j; k < size && l < size; k++, l++) // Check if player can shoot right-up. { if (board[k][l] == 0) return true; else break; } for (int k = j; k < size; k++) // Check if player can shoot up. { if (board[i][k] == 0) return true; else break; } for (int k = j; k > 0; k--) // Check if player can move to the down then shoot. { if (board[i][k] == 0) return true; else break; } for (int k = i, l = j; k > 0 && l < size; k--, l++) // Check if player can move to the left-up then shoot. { if (board[k][l] == 0) return true; else break; } for (int k = i, l = j; k < size && l >0; k++, l--) // Check if player can move to the right-down then shoot. { if (board[k][l] == 0) return true; else break; } return false; } void Game::printMove(Move& move) { //std::cout << char(move.fromX+65) << move.fromY << "-" << char(move.toX+65) << move.toY << "-" << char(move.shootX+65) << move.shootY << std::endl; std::cout << char(move.fromX+65 ) << move.fromY+1 << "-" << char(move.toX +65) << move.toY+1 << "/" << char(move.shootX+65) << move.shootY+1 <<"/"<<move.PV<<"/"<<move.time<< std::endl; std::cout << "Current depth= " << move.depth<<", PV evaluation= "<<move.evaluation <<", number of prunings= "<<move.cuts<<", number of hashs= "<<move.hashCounter<<std::endl<<std::endl; /*for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { std::cout << board[i][j]<< " "; } std::cout << std::endl; } std::cout << std::endl;*/ }
71e942cc63f1e1acdd9df3a67cdfe9e593aa5403
9d8f19c258cc76a6ed6a1071cb1ddf46964e05f1
/moon_raw.h
ba591970783fbf3b48705565fc672c547f6ff27e
[]
no_license
karasova/moon
d11938dc4711b0d64ad608924de17939757fc8ab
c0c80652c7ae9565e0c708c9b3d19eea484a0e40
refs/heads/master
2020-04-11T13:47:44.934031
2018-12-15T04:11:19
2018-12-15T04:11:19
161,829,845
0
0
null
null
null
null
UTF-8
C++
false
false
211
h
#pragma once #include <iostream> #include <fstream> using namespace std; class moon_raw { public: char* data = new char[8]; char* time = new char[6]; double el, az; moon_raw(ifstream& file); };
5209ec2aeca8ad23301f264c84330759d57fc595
4887bfd75770da06a64a39265e6825df6e63df8a
/contest/1203/cf579A.cpp
e91f1127bdf4ef1dfe314d4cd59df8f88df1fd5c
[]
no_license
jayin92/competitive-programming
5ca697d66ca0bd4016f109499ec76b0eba5d1d35
e065a25d26ae78413da934f1081d882461e13d33
refs/heads/master
2022-12-22T13:47:30.776905
2022-12-07T17:28:16
2022-12-07T17:28:26
216,350,027
0
0
null
null
null
null
UTF-8
C++
false
false
1,313
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int q; cin >> q; while(q--){ map <int, int> st; vector <int> area; bool flag = false; int n; cin >> n; int a[n*4]; for(int i=0;i<4*n;i++){ cin >> a[i]; st[a[i]] ++; } for(pair<int, int> i:st){ if(i.second < 2){ st.erase(i.first); } } for(auto i:st){ for(auto j:st){ if(i.first >= j.first){ area.push_back(i.first * j .first); } } } for(int i:area){ cout << i << endl; int temp = 0; for(auto j:st){ for(auto k:st){ if(j.first >= k.first){ if(j.first * k.first == i){ temp ++; j.second -= 2; k.second -= 2; } if(temp == n && !flag){ cout << "YES" << endl; flag = true; } } } } } if(!flag) cout << "NO" << endl; } }
ec45271a572e73e193661d71ef281779404a3fa7
6404f55060041a4e98c6b613c3806767b39bcd18
/Kaynak.cpp
3ad7a6660fd26ad56c464d7cc525215b81828f57
[ "Apache-2.0" ]
permissive
sufasah/Bignumber-Library
7a45566da82c74665608a5324eac3f29d5b72c65
a0e6362a6512573a7aeb8f326946072ec03fc426
refs/heads/master
2023-03-04T22:07:43.600816
2021-02-12T11:05:13
2021-02-12T11:05:13
337,310,754
0
0
null
null
null
null
UTF-8
C++
false
false
469
cpp
#include "bignumber.h" #include <iostream> #include <string> using namespace std; int main() { bigNum n,n2; while(1) { cout << "1. sayi" << endl; string s1; getline(cin, s1); n.set(s1); cout << "2. sayi" << endl; string s2; getline(cin, s2); n2.set(s2); cout << "sonuc" << endl; cout << (n + n2) << endl; cout << "beklenen sonuc" << endl; string s3; getline(cin, s3); cout <<"Esit Mi -> "<<((n+n2).get()==s3?"EVET":"HAYIR")<<endl; } }
86d90b670ac3cfbd10b3dd131c59d3d02db3281c
f9b50a94f492d37bfb2bc20b714ff76ce6055142
/project/terrain.h
b62b6bd015495531210683c925eba25cf994ea63
[]
no_license
bear24rw/CS6060
7d0b2a431f0cddbf3996fc575c784eec3555c8ae
8e4fa6f82013a084b1c897f5483f1362c1a2b13d
refs/heads/master
2021-01-19T18:32:31.754638
2013-12-06T23:02:00
2013-12-06T23:02:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
717
h
#pragma once #include <GL/glew.h> #include <SFML/Graphics.hpp> #include <SFML/OpenGL.hpp> #include <SFML/System.hpp> #include "tile.h" #include "camera.h" #define NUM_TILES_X 11 #define NUM_TILES_Z 11 #define NUM_TILES (NUM_TILES_X*NUM_TILES_Z) class Terrain { public: Terrain(); Terrain(Camera*); void render(void); void update(void); float get_height(int,int); float get_height(float,float); private: //std::vector<Tile*> tiles; Tile *tiles[NUM_TILES]; GLuint shader_id; GLuint mvp_id; GLuint view_id; GLuint model_id; sf::Texture texture; Camera *cam; sf::Thread update_thread; };
faf649e5f8903f171f9d2d27f4ac5e19a69c89b6
d01231b96d6321bbe267365951abe57cd479f80a
/matriz_borrar fila columna.cpp
ed6076440b4e0cec05ffd9fcdf2cafa4e53a9626
[]
no_license
Carlosuca/Proyectos-de-progra
01c1194f79470f9e38265a9ee0355aad142f75db
32d2e54c6f994d1680f2ba2aed1e38da6daee91c
refs/heads/master
2020-07-24T12:04:18.850459
2020-05-02T02:55:07
2020-05-02T02:55:07
207,920,045
0
0
null
null
null
null
UTF-8
C++
false
false
936
cpp
#include <iostream> using namespace std; int main() { int numeros[100][100],filas,columnas; int borar_fila,borrar_columna; cout<<"Digite el numero de filas: "; cin>>filas; cout<<"Digite el numero de columnas: "; cin>>columnas; for(int i=0;i<filas;i++){ for(int j=0;j<columnas;j++){ cout<<"Digite un numero ["<<i<<"]["<<j<<"]: "<<" "; cin>>numeros[i][j]; } } cout<<"\nMostrando matriz\n"; for(int i=0;i<filas;i++){ for(int j=0;j<columnas;j++){ cout<<numeros[i][j]<<" "; } cout<<"\n"; } cout << "Fila y Columna a borrar "; cin >> borar_fila; cin >> borrar_columna; cout << "sub-matriz"; cout << endl; borar_fila = borar_fila - 1; borrar_columna = borrar_columna - 1; for (int i = 0; i <filas; i++) { for (int j = 0; j < columnas; j++) { if (i == borar_fila || j == borrar_columna) { numeros[i][j] = 0; } else { cout << numeros[i][j] << " "; } } cout << endl; } return 0; }
[ "Carlosuca" ]
Carlosuca
7932c837794ed83163f1d74995592d3469958eae
352b2b8dd9a217009d1086097006e36132e6c0de
/whaleyplayer架构和实现分析/软解播放器/decoder_video.cpp
5b3c4f45478e63b16e2d5ee8c0dfd009b8285f99
[]
no_license
sunyuchuan/SunycDocumentation
e95c06fa73308ff837cdc98fdd95cd452cef247a
cd873123750dd6c0250ea34c2ec1356cf1609183
refs/heads/master
2023-01-30T00:38:01.513985
2020-11-25T09:18:40
2020-11-25T09:22:08
293,723,631
1
0
null
null
null
null
UTF-8
C++
false
false
5,476
cpp
#define LOG_TAG "FFVideoDec" #include <utils/Log.h> #include "decoder_video.h" namespace android { static uint64_t global_video_pkt_pts = AV_NOPTS_VALUE; DecoderVideo::DecoderVideo(AVStream* stream, int total_frame): IDecoder(stream), mTotalFrame(total_frame), mClock(NULL) { mVideoClock = 0.0; mSwsFrame = NULL; mVideoPicture = NULL; mConvertCtx = NULL; #if 0 mStream->codec->get_buffer = getBuffer; mStream->codec->release_buffer = releaseBuffer; #endif } DecoderVideo::~DecoderVideo() { if(mFrame) av_frame_free(&mFrame); mFrame = NULL; if(mConvertCtx) sws_freeContext(mConvertCtx); mConvertCtx = NULL; } void DecoderVideo::stop() { if(mClock != NULL) { mClock->stop(); } if(mVideoRender != NULL) { mVideoRender->stop(); } mQueue->abort(); ALOGI("waiting on end of DecoderVideo thread"); int ret = -1; if((ret = wait()) != 0) { ALOGI("Couldn't cancel DecoderVideo: %i", ret); return; } } bool DecoderVideo::prepare() { mFrame = av_frame_alloc(); if (mFrame == NULL) { return false; } mConvertCtx = ff_getContext(mStream->codec); if (mConvertCtx == NULL) { return false; } return true; } double DecoderVideo::synchronize(AVFrame *src_frame, double pts) { double frame_delay; if (pts != 0) { /* if we have pts, set video clock to it */ mVideoClock = pts; } else { /* if we aren't given a pts, set it to the clock */ pts = mVideoClock; } /* update the video clock */ frame_delay = av_q2d(mStream->codec->time_base); /* if we are repeating a frame, adjust clock accordingly */ frame_delay += src_frame->repeat_pict * (frame_delay * 0.5); mVideoClock += frame_delay; return pts; } int DecoderVideo::allocPicture() { int ret = 0; AVCodecContext* codec_ctx = mStream->codec; mSwsFrame = av_frame_alloc(); if (mSwsFrame == NULL) { ALOGE("[HMP]av_frame_alloc fail!\n"); return -1; } ret = avpicture_alloc((AVPicture *)mSwsFrame,AV_PIX_FMT_YUV420P,codec_ctx->width, codec_ctx->height); if (ret < 0) { ALOGE("[HMP]avpicture_alloc fail!\n"); return -1; } mVideoPicture = (AVFrameList *)malloc(sizeof(AVFrameList)); if (mVideoPicture == NULL) { ALOGE("[HMP]av_malloc fail!\n"); return -1; } return 0; } int DecoderVideo::queueVideoFrame(double pts, int64_t pos) { int ret = 0; ret = allocPicture(); if(ret < 0) { ALOGE("allocPicture fail\n"); return -1; } // Convert the image from its native format to RGB ff_scale(mConvertCtx, mFrame, mSwsFrame, 0, mStream->codec->height); mSwsFrame->width = mFrame->width; mSwsFrame->height = mFrame->height; mVideoPicture->frame = mSwsFrame; mVideoPicture->pts = pts; mVideoPicture->pos = pos; mVideoPicture->clk = mVideoClock; mVideoRender->checkQueueFull(); ret = mVideoRender->enqueue(mVideoPicture); return ret; } bool DecoderVideo::process(AVPacket *packet) { int completed = 0; double pts = 0.0; int64_t pos = 0; if(mPause) waitOnNotify(); int len = ff_decode_video(mStream->codec, mFrame, &completed, packet); #if 0 if (packet->dts == AV_NOPTS_VALUE && mFrame->opaque && *(uint64_t*) mFrame->opaque != AV_NOPTS_VALUE) { pts = *(uint64_t *) mFrame->opaque; } else if (packet->dts != AV_NOPTS_VALUE) { pts = packet->dts; } else { pts = 0; } #else int decoder_reorder_pts = -1; if (decoder_reorder_pts == -1) { mFrame->pts = av_frame_get_best_effort_timestamp(mFrame); } else if (mFrame->pkt_pts != AV_NOPTS_VALUE) { mFrame->pts = mFrame->pkt_pts; } else if (mFrame->pkt_dts != AV_NOPTS_VALUE) { mFrame->pts = mFrame->pkt_dts; } else { mFrame->pts = 0; } pos = packet->pos; pts = mFrame->pts*av_q2d(mStream->time_base); #endif if (completed) { pts = synchronize(mFrame, pts); queueVideoFrame(pts, pos); //SLOGD("queueVideoFrame number %d",mVideoRender->getQueueSize()); return true; } return false; } bool DecoderVideo::decode(void* ptr) { AVPacket pPacket; ALOGV("decoding video"); while(mRunning) { mSleeping = mQueue->isEmpty(); if(mQueue->get(&pPacket, true) < 0) { ALOGI("[HMP]mQueue can't get queue & return!"); mRunning = false; return false; } if(!process(&pPacket)) { //mRunning = false; //return false; } // Free the packet that was allocated by av_read_frame ff_free_packet(&pPacket); } ALOGV("decoding video ended"); return true; } /* These are called whenever we allocate a frame * buffer. We use this to store the global_pts in * a frame at the time it is allocated. */ #if 0 int DecoderVideo::getBuffer(struct AVCodecContext *c, AVFrame *pic) { int ret = avcodec_default_get_buffer(c, pic); uint64_t *pts = (uint64_t *)av_malloc(sizeof(uint64_t)); *pts = global_video_pkt_pts; pic->opaque = pts; return ret; } void DecoderVideo::releaseBuffer(struct AVCodecContext *c, AVFrame *pic) { if (pic) av_freep(&pic->opaque); avcodec_default_release_buffer(c, pic); } #endif }
d4efc124809096d64e12df2c0651c72b930c2f37
bea9253e2d2a0d585a421c8ee6b1a033550659c2
/Level 6/4.2b/Exercise 2/numericarray.cpp
caa8f2a186575a0f1a44f9e0c61d875240f10462
[]
no_license
ngaikw/Cplusplus_Financial_Engineering
e82417fb78094ab69179e77457164423a74b7359
fe4fdb45f052ea64c04f7dc7e6b793897adf2e77
refs/heads/master
2021-01-12T17:56:43.159153
2015-12-10T20:53:26
2015-12-10T20:53:26
71,305,638
4
4
null
2016-10-19T01:10:58
2016-10-19T01:10:58
null
UTF-8
C++
false
false
2,335
cpp
#ifndef numericArray_CPP #define numericArray_CPP #include"differentSizeException.hpp" #include"numericarray.hpp" #include<cmath> using namespace std; template <class T> numericArray<T>::numericArray() : Array<T>()//default constructor { } template <class T> numericArray<T>::numericArray(int s) : Array<T>(s) { } template <class T> numericArray<T>::numericArray(const numericArray<T>& nArray) : Array<T>(nArray) //copy constructor { } template <class T> numericArray<T>::~numericArray() //destructor { } template <class T> numericArray<T>& numericArray<T>::operator = (const numericArray<T>& nArray) //assignment operator { Array<T>::operator = (nArray); //call the base class assignment operator return *this; } template <class T> numericArray<T> numericArray<T>::operator * (const T& factor) const //* operator to scale elements by a factor of type T { numericArray<T> nA(size()); //create new nArray object with same size as *this. (have to call size //function because we cannot access private members of base class for (int i = 0; i < nA.size(); i++) { nA[i] = (*this)[i] * factor; //getElement(i) * factor; same //load nArray object with scaled factor cout << "nA" << i << " " << nA[i] << endl; } return nA; } template <class T> numericArray<T> numericArray<T>::operator + (const numericArray<T>& nA) { int iAsize = size(); //store size in variable if (iAsize != nA.size()) { throw differentSizeException(); //throw an exception if the numeric arrays aren't the same size } numericArray<T> nA2(iAsize); //create a new nArray object for (int i = 0; i < size(); i++) { nA2[i] = (*this)[i] + nA[i]; //add elements of both arrays } return nA2; } template <class T> T& numericArray<T>::dot(numericArray<T>& nA) //dot product function { if (size() != nA.size()) { throw differentSizeException(); //throw an exception if the numeric arrays aren't the same size } T temp = 0; //create an object T to store the dot product for(int i = 0; i < size(); i++) { temp = (*this)[i] * nA[i]; //multiply both indices temp += temp; //add to total } return temp; } #endif
7265473c13da1252c402835ee3ac9de5dbb13d15
f839f0c97cfff2791d9d827f244858f31911d478
/AR-36.cpp
a71e53522e7cf371ca8d798bef7f202d6ed16af8
[]
no_license
eric201014/ITSA
c2038fec599d0d28d285e914cb5b2ff1e8103330
57ec8ecd2b584d543e92b90764c495b11b32640a
refs/heads/master
2020-06-09T03:40:00.239467
2020-01-17T02:54:26
2020-01-17T02:54:26
193,363,454
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
#include <iostream> #include <cstdlib> using namespace std; int main() { int n=0,m=0,k=0; cin >> n >> m >> k; int i=0,j=0,a[n][m],b[n][m],c[n][m]; for(i=0;i<n;i++) for(j=0;j<m;j++) cin >> a[i][j]; for(i=0;i<n;i++) for(j=0;j<m;j++) cin >> b[i][j]; for(i=0;i<n;i++) // matrix operate for(j=0;j<m;j++) c[i][j]=k*(a[i][j]+b[i][j]); for(i=0;i<m;i++) { for(j=0;j<n-1;j++) cout << c[j][i] << " "; cout << c[j][i]; cout << endl; } return 0; }
0c2c6ebd18d3b9aa4c85d54f272331cb1dd117bf
9627ea6c2d232c55a949064ff7c7c07c4dd7626a
/FB SDK/CompareState.h
ff1266a78c786e327478f33cb16f5dcbda881cfb
[]
no_license
picco911/Cheat_BF3
e2d42785474348adfdfa44274999aa4d0ea68054
99888a880eed5410308f03258b35a11ce50d927e
refs/heads/master
2020-03-27T21:05:14.875678
2018-09-02T19:13:16
2018-09-02T19:13:16
147,114,166
0
1
null
2018-09-02T19:11:31
2018-09-02T19:11:31
null
UTF-8
C++
false
false
211
h
#ifndef _CompareState_H #define _CompareState_H #include "FB SDK/Frostbite_Classes.h" namespace fb { class CompareState { public: bool asMember; // 0x0 }; // CompareState }; #endif
db66eff324a8fc42b886dfb588994736a5bd2672
cd5e42c91c9018f25b08c6008249297654f5026c
/2009 数列求和.cpp
4cf66cd28b53bd3aba3597ab09ebc4690b2f9aca
[]
no_license
shareone2/HDUOj
518d64b0eae3634b4be6e1d5cc5223a01bbc7a20
d43ff86c2671c44571ed3761f789766f5a85c19e
refs/heads/master
2022-12-10T01:21:07.157972
2020-09-08T10:23:12
2020-09-08T10:23:12
293,774,725
1
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
#include <stdio.h> #include <math.h> int main(){ double n; int m; while (scanf("%lf%d", &n, &m) != EOF && n < 10000 && m < 1000) { double sum = 0; while (m--) { sum = sum + n; n = sqrt(n); } printf("%.2lf\n", sum); } return 0; }
a26ba9a884049a3f1a0b1f0c0ffb93242cd454e4
3e98ac489f3122e86b13a9d9cf565ca79e3b4c72
/HW3/main_char.h
7cfa2c9c1722539220f68eb91670dc607673ff35
[]
no_license
brian220/3DGameProgramming
46e9976595aba4219f6aad3018124096665f6523
d06f54abcd32036dd64ee0f3c9dc31d7d56b4714
refs/heads/master
2020-08-01T01:35:10.568562
2019-12-20T13:29:25
2019-12-20T13:29:25
210,815,177
0
0
null
null
null
null
UTF-8
C++
false
false
1,426
h
#ifndef __MAIN_CHAR_H__ #define __MAIN_CHAR_H__ #include "game_obj.h" #include "weapon_manager.h" #include "WeaponParticleSystemManager.h" class MAIN_CHAR : public GAME_OBJ { protected: Camera *mCamera; Vector3 mEyePosition; WEAPON_MANAGER *mWeaponMgr; unsigned int mFireActionMode; int mCurBulletsNum; virtual void fireWeapon(); double mDistanceOffsetToTerrain; double mSpeedFactor_Modifer; public: MAIN_CHAR(); MAIN_CHAR(SceneManager *a_SceneMgr); virtual void attachCamera(Camera *a_Camera); virtual void walkForward(const Ogre::FrameEvent& evt); virtual void walkBackward(const Ogre::FrameEvent& evt); virtual void setWalkForward(); virtual void setWalkBackward(); void unsetWalkForward(); virtual void unsetWalkBackward(); unsigned int getActionMode() const; virtual void update(const Ogre::FrameEvent& evt); virtual void updateWeapon(const Ogre::FrameEvent& evt); virtual void setFireAction_Normal(); virtual Vector3 getWeaponPosition() const; virtual void updateViewDirection(); virtual void setMaxBulletsNum(int a_Num); virtual void setPosition_to_Environment(const Vector3 &p); virtual void setEyePosition_Y(double y); virtual void setWalkingMaxSpeed_Modifier(double walkingMaxSpeed); WEAPON_MANAGER *getWeaponManager( ); void installWeaponWSManager(WeaponParticleSystemManager *wpsMgr); }; #endif
024f8467ef88e2f30c2bc4e1b6f96407a4d1e49f
fd81ece5b7ac96e4c2456a8633204d95a2ecb980
/MCG03/Obstacle.h
ac93491fa7790c7a5859f63dccb464d6ca58a59d
[]
no_license
PeterZs/MCG03
5607659ea8299edd0012aeb56bc7f41315eee7f2
1620f130852b89bd6f202ba215b608c7520689ea
refs/heads/master
2021-01-12T22:18:52.335411
2015-04-04T02:19:24
2015-04-04T02:19:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
411
h
// // Obstacle.h // MCG03 // // Created by Jing Li on 9/18/14. // Copyright (c) 2014 Jing Li. All rights reserved. // #ifndef __MCG03__Obstacle__ #define __MCG03__Obstacle__ #include <iostream> #include "Particle.h" class Obstacle { public: virtual void draw()const =0; virtual void collide(Particle &particle) const =0; virtual void move(){}; }; #endif /* defined(__MCG03__Obstacle__) */
0135d5a31089d40b202d461d269621ec0fed6624
127e99fbdc4e04f90c0afc6f4d076cc3d7fdce06
/ cpp/플로이드(11404).cpp
35d88c59fc034830282611219912d334de046c03
[]
no_license
holim0/Algo_Study
54a6f10239368c6cf230b9f1273fe42caa97401c
ce734dcde091fa7f29b66dd3fb86d7a6109e8d9c
refs/heads/master
2023-08-25T14:07:56.420288
2021-10-25T12:28:23
2021-10-25T12:28:23
276,076,057
3
1
null
null
null
null
UTF-8
C++
false
false
1,023
cpp
#include<iostream> #include<algorithm> #define MAX 987654321 using namespace std; int n, m; long long list[102][102]; int main(){ cin>>n>>m; long long a, b, w; for (int i = 1; i <=n; i++) { for (int j = 1; j <=n; j++) { list[i][j]=MAX; } } for (int i = 0; i < m; i++) { cin>>a>>b>>w; if(w<list[a][b]){ list[a][b]=w; } } for (int k = 1; k <=n; k++) { for (int s = 1; s <= n; s++) { for (int e = 1; e <= n; e++) { list[s][e]=min(list[s][e], list[s][k]+list[k][e]); } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if(i==j || list[i][j]==MAX){ cout<<0<<" "; }else{ cout<<list[i][j]<<" "; } } cout<<endl; } return 0; }
a60dac0bcfb95436bf179c8e011f19308cb0d3b7
2cf5785bbaeeb10be65348d342269ca735ad10a5
/modules/light.h
42e4540fbfdca1e6470e902615065f92ca62f2b3
[]
no_license
Alfarie/PlantLab-MCU-LIGHT
d334f1e16c4f71fba098acef6cfb322837299535
4b9d22f9c2114d5730ababf23bf88b9c489309b5
refs/heads/master
2020-03-19T15:23:55.677204
2018-06-08T21:54:52
2018-06-08T21:54:52
136,669,025
0
0
null
null
null
null
UTF-8
C++
false
false
794
h
#include <Task.h> extern TaskManager taskManager; #include "TSL2561.h" TSL2561 tsl(TSL2561_ADDR_FLOAT); class Light : public Task { public: static Light *s_instance; Light() : Task(MsToTaskTime(1000)) { value = 0; tsl.setGain(TSL2561_GAIN_0X); tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS); }; static Light *instance() { if (!s_instance) s_instance = new Light; return s_instance; } float GetLight(){ return value; } private: float value; virtual bool OnStart() { value = 0; return true; } virtual void OnUpdate(uint32_t delta_time) { uint32_t lum = tsl.getFullLuminosity(); uint16_t ir, full; ir = lum >> 16; full = lum & 0xFFFF; value = tsl.calculateLux(full, ir); } }; Light *Light::s_instance = 0;
e7f3980fdc12a255be50d30ba516827bc17ead47
db16383db5f7fba2c753f62539010d6529232d42
/task3.cpp
771dbbd14e7de8cdb6fc0b4b59a0c605fd738e4e
[]
no_license
LvovKirill/SR_massiv
ed6d0fa638dd849ef0fdb846f32848fdb62836ec
0823db802a21ddc5843b4d73ded98a376ccc0504
refs/heads/master
2023-01-23T08:58:40.970075
2020-11-30T13:03:58
2020-11-30T13:03:58
317,226,071
0
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
#include <iostream> using namespace std; int main() { int n; cin >> n; int mas[n][n]; // заполняем двумерный массив (i-строки, j-столбцы) for (int i = 0; i<n; i++){ for (int j = 0; j<n; j++){ // если главная диагональ if (i==j) cout << 0 << " "; // если выше главной диагонали if (j>i) cout << 1 << " "; // если ниже главной диагонали if (j<i) cout << -1 << " "; } cout << endl; } }
bf49809a0ffc5451ec3ce86da40ef421899fe8f4
6564776b030d05a959b34f57ad8d9a310859a4c1
/include/window.h
4dbfcf4ed23bad97df1701e170dc8fdd7205c76d
[ "MIT" ]
permissive
ryonagana/shmup2
2fdbd035fe1f57df8bd6337fe996b1c8540f4511
e873402dc82dc148340adc2562dd8eb2353f3915
refs/heads/master
2020-05-02T05:49:43.653850
2019-06-23T23:43:09
2019-06-23T23:43:09
177,781,243
2
1
null
null
null
null
UTF-8
C++
false
false
1,369
h
#ifndef WINDOW_HEADER #define WINDOW_HEADER #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cstdbool> #include <allegro5/allegro.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_font.h> #include <allegro5/allegro_ttf.h> #include <allegro5/allegro_primitives.h> #include <allegro5/allegro_audio.h> #include <allegro5/allegro_acodec.h> #include <allegro5/allegro_opengl.h> #include <allegro5/allegro_physfs.h> #include <allegro5/allegro_native_dialog.h> void window_init(void); void window_close(void); bool window_open(void); void window_exit_loop(void); void window_gracefully_quit(const std::string &msg); bool window_request_gracefully_closing(void); int window_get_width(void); int window_get_height(void); ALLEGRO_DISPLAY* get_window_display(void); ALLEGRO_EVENT_QUEUE* get_window_queue(void); ALLEGRO_TIMER *get_window_timer(void); ALLEGRO_TIMER *get_window_actual_time(void); ALLEGRO_BITMAP *get_window_screen(void); int64_t get_window_time_ms(void); void set_window_time_ms(int64_t time); void set_window_title(const std::string title); #define TICKSPERFRAME 60.0 #define WINDOW_STOP_TIMER() do { al_stop_timer(get_window_timer()); }while(0); #define WINDOW_RESUME_TIMER() do { al_start_timer(get_window_timer());al_set_timer_speed(get_window_timer(), 1.0 / TICKSPERFRAME ); }while(0); #endif
b66ce0e8f081102e6186955b901f3392c2d8a73f
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_5517.cpp
74872789e0474c1d7787589f7c97de6ccb19e72e
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
matchrv = aclMatchUser(data, MatchParam); break; case ACL_PROXY_AUTH_REGEX: matchrv = aclMatchRegex(data, MatchParam); break; default: /* This is a fatal to ensure that aclCacheMatchAcl calls are _only_ * made for supported acl types */ fatal("aclCacheMatchAcl: unknown or unexpected ACL type"); return 0; /* NOTREACHED */ } auth_match = memAllocate(MEM_ACL_PROXY_AUTH_MATCH); auth_match->matchrv = matchrv; auth_match->acl_data = data; dlinkAddTail(auth_match, &auth_match->link, cache);
a5bad939cc8b0a5c5806a39ddde1614b9e807dcf
468716b83d837e2944fe6a3c8078b585560d7d1f
/Players/Cocos2d-x_v4/3rdParty/LLGI/src/DX12/LLGI.TextureDX12.h
eff636267fbf3b42564f3ddd1c9b8561cfad29ed
[ "Zlib", "MIT" ]
permissive
darreney/EffekseerForCocos2d-x
0a1bfea09ec9858081f799cc5b0ce3f42147883a
de9222b28f6f376cfb96f98b7b4dd783a3d66055
refs/heads/master
2020-12-18T20:24:59.103886
2020-06-16T07:21:44
2020-06-16T07:21:44
235,512,027
0
0
MIT
2020-01-22T06:21:45
2020-01-22T06:21:44
null
UTF-8
C++
false
false
1,563
h
#pragma once #include "../LLGI.Texture.h" #include "LLGI.BaseDX12.h" #include "LLGI.GraphicsDX12.h" namespace LLGI { class TextureDX12 : public Texture { private: GraphicsDX12* graphics_ = nullptr; bool hasStrongRef_ = false; ID3D12Device* device_ = nullptr; ID3D12CommandQueue* commandQueue_ = nullptr; ID3D12Resource* texture_ = nullptr; ID3D12Resource* buffer_ = nullptr; D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint_; D3D12_RESOURCE_STATES state_ = D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COMMON; DXGI_FORMAT dxgiFormat_; //! DX12 doesn't have packed buffer std::vector<uint8_t> lockedBuffer_; Vec2I textureSize_; int32_t memorySize_; void CreateBuffer(); public: TextureDX12(GraphicsDX12* graphics, bool hasStrongRef); //! init as screen texture TextureDX12(ID3D12Resource* textureResource, ID3D12Device* device, ID3D12CommandQueue* commandQueue); virtual ~TextureDX12(); //! init as external texture bool Initialize(ID3D12Resource* textureResource); bool Initialize(const Vec2I& size, TextureType type, const TextureFormatType formatType); void* Lock() override; void Unlock() override; Vec2I GetSizeAs2D() const override; ID3D12Resource* Get() const { return texture_; } int32_t GetMemorySize() const { return memorySize_; } TextureFormatType GetFormat() const override { return format_; } DXGI_FORMAT GetDXGIFormat() const { return dxgiFormat_; } //! set a resource barrior and change a state void ResourceBarrior(ID3D12GraphicsCommandList* commandList, D3D12_RESOURCE_STATES state); }; } // namespace LLGI
1148dfaf22725adab805924490e46ee4328b79e9
c14d2822597f87b7fdc1ae3e19f5a0f53ed733d3
/Day03/ex03/ClapTrap.hpp
9a0a7bef185c013611e8572875665a842b2d2b36
[ "MIT" ]
permissive
EnapsTer/StudyCPP
79eef4f5e5fc49cf0f0789e0e2500d22b512dcd8
4bcf2a152fbefebab8ff68574e2b3bc198589f99
refs/heads/main
2023-07-16T05:58:45.689061
2021-08-26T12:52:38
2021-08-26T12:52:38
364,988,775
1
0
null
null
null
null
UTF-8
C++
false
false
975
hpp
// // Created by Arborio Herlinda on 5/14/21. // #ifndef CLAPTRAP_HPP #define CLAPTRAP_HPP #include <string> class ClapTrap { public: ClapTrap(std::string const &name); ClapTrap(ClapTrap const &other); ClapTrap &operator=(ClapTrap const &other); virtual ~ClapTrap(); virtual void RangedAttack(std::string const &target); virtual void MeleeAttack(std::string const &target); virtual void TakeDamage(unsigned int amount); virtual void BeRepaired(unsigned int amount); const std::string &GetName() const; int GetMeleeAttackDamage() const; int GetRangedAttackDamage() const; int GetHitPoints() const; int GetEnergyPoints() const; void SetHitPoints(int hit_points); void SetEnergyPoints(int energy_points); protected: int hit_points_; int max_hit_points_; int energy_points_; int max_energy_points_; int level_; std::string name_; int melee_attack_damage_; int ranged_attack_damage_; int armor_damage_reduction_; }; #endif
aa516b4e5c5f364dc9982f12056551a4ad0181d7
46ebfa8a713fae2f285d4050eb6a429c1757f917
/ui/src/vcpropertieseditor.h
e4f719d9658b03c9f75d8c7b1aba7083a4868b6b
[ "Apache-2.0" ]
permissive
CCLinck21/qlcplus
ae20e333f97e43274c8f2d5f6c13281f4d9061a3
46b09fab78dceb4c27497fb5667451821b07a7aa
refs/heads/master
2021-01-12T20:58:44.853860
2013-12-21T12:26:24
2013-12-21T12:26:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,935
h
/* Q Light Controller vcpropertieseditor.h Copyright (c) Heikki Junnila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef VCPROPERTIESEDITOR_H #define VCPROPERTIESEDITOR_H #include <QDialog> #include "ui_vcproperties.h" #include "vcwidgetproperties.h" #include "universearray.h" #include "vcproperties.h" #define SETTINGS_BUTTON_SIZE "virtualconsole/buttonsize" #define SETTINGS_BUTTON_STATUSLED "virtualconsole/buttonstatusled" #define SETTINGS_SLIDER_SIZE "virtualconsole/slidersize" #define SETTINGS_SPEEDDIAL_SIZE "virtualconsole/speeddialsize" #define SETTINGS_SPEEDDIAL_VALUE "virtualconsole/speeddialvalue" #define SETTINGS_XYPAD_SIZE "virtualconsole/xypadsize" #define SETTINGS_CUELIST_SIZE "virtualconsole/cuelistsize" #define SETTINGS_FRAME_SIZE "virtualconsole/framesize" #define SETTINGS_SOLOFRAME_SIZE "virtualconsole/soloframesize" #define SETTINGS_AUDIOTRIGGERS_SIZE "virtualconsole/audiotriggerssize" class VirtualConsole; class QDomDocument; class QDomElement; class InputMap; class VCFrame; class VCPropertiesEditor : public QDialog, public Ui_VCPropertiesEditor { Q_OBJECT Q_DISABLE_COPY(VCPropertiesEditor) /************************************************************************* * Initialization *************************************************************************/ public: VCPropertiesEditor(QWidget* parent, const VCProperties& properties, InputMap* inputMap); ~VCPropertiesEditor(); VCProperties properties() const; QSize buttonSize(); bool buttonStatusLED(); QSize sliderSize(); QSize speedDialSize(); uint speedDialValue(); QSize xypadSize(); QSize cuelistSize(); QSize frameSize(); QSize soloFrameSize(); QSize audioTriggersSize(); private: VCProperties m_properties; InputMap* m_inputMap; /************************************************************************* * Layout page *************************************************************************/ private: void fillTapModifierCombo(); private slots: void slotSizeXChanged(int value); void slotSizeYChanged(int value); void slotTapModifierActivated(int index); /************************************************************************* * Widgets page *************************************************************************/ protected slots: void slotSpeedDialConfirmed(); /************************************************************************* * Grand Master page *************************************************************************/ private slots: void slotGrandMasterIntensityToggled(bool checked); void slotGrandMasterReduceToggled(bool checked); void slotGrandMasterSliderNormalToggled(bool checked); void slotAutoDetectGrandMasterInputToggled(bool checked); void slotGrandMasterInputValueChanged(quint32 universe, quint32 channel); void slotChooseGrandMasterInputClicked(); private: void updateGrandMasterInputSource(); /************************************************************************* * Input Source helper *************************************************************************/ private: bool inputSourceNames(quint32 universe, quint32 channel, QString& uniName, QString& chName) const; }; #endif
42de1aa58e5f55f34bf464ac275b1d64fcc7c7ef
a80e7ff11efdd689d8ce7c5269df26735899a6e0
/GameAPP/Tests/tst_gametests.cpp
138868d8a5504d87be03ab11ff6df51a575733f7
[]
no_license
fl0rek/ProjektTIN
9ca51dde4d48fdce5d040be76258d1be5f0962f1
606f0047b8868eb282b7df4bf676edf043586d73
refs/heads/master
2021-01-19T22:05:31.043483
2017-06-08T18:01:19
2017-06-08T18:01:19
88,751,702
0
1
null
2017-06-08T17:42:20
2017-04-19T14:00:15
C++
UTF-8
C++
false
false
57
cpp
#include "tst_gametests.h" GameTests::GameTests() { }
146f4b7c73028b17ae0aab6dfde5c66ed4a45b21
f3a316a2f25b37793e1741295d7e932e3d8e7c09
/source/i18n/buddhcal.cpp
082642d5a37775e0501586bd67ddf45f36b83ad9
[ "LicenseRef-scancode-public-domain", "BSD-2-Clause", "NAIST-2003", "BSD-3-Clause", "LicenseRef-scancode-unicode", "ICU", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CdTCzech/ICU
3cb59891b9efcbcfa5fb6e75d394d666561650a3
4c9b8dfefd9a26096f7642c556fa3b4bd887317e
refs/heads/master
2023-03-01T19:23:09.347544
2021-02-09T13:01:11
2021-02-09T13:01:11
257,857,185
0
0
null
null
null
null
UTF-8
C++
false
false
5,493
cpp
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * Copyright (C) 2003-2013, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* * * File BUDDHCAL.CPP * * Modification History: * 05/13/2003 srl copied from gregocal.cpp * */ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "buddhcal.h" #include "unicode/gregocal.h" #include "umutex.h" #include <float.h> U_NAMESPACE_BEGIN UOBJECT_DEFINE_RTTI_IMPLEMENTATION(BuddhistCalendar) //static const int32_t kMaxEra = 0; // only 1 era static const int32_t kBuddhistEraStart = -543; // 544 BC (Gregorian) static const int32_t kGregorianEpoch = 1970; // used as the default value of EXTENDED_YEAR BuddhistCalendar::BuddhistCalendar(const Locale& aLocale, UErrorCode& success) : GregorianCalendar(aLocale, success) { setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly. } BuddhistCalendar::~BuddhistCalendar() { } BuddhistCalendar::BuddhistCalendar(const BuddhistCalendar& source) : GregorianCalendar(source) { } BuddhistCalendar& BuddhistCalendar::operator= ( const BuddhistCalendar& right) { GregorianCalendar::operator=(right); return *this; } BuddhistCalendar* BuddhistCalendar::clone() const { return new BuddhistCalendar(*this); } const char *BuddhistCalendar::getType() const { return "buddhist"; } int32_t BuddhistCalendar::handleGetExtendedYear() { // EXTENDED_YEAR in BuddhistCalendar is a Gregorian year. // The default value of EXTENDED_YEAR is 1970 (Buddhist 2513) int32_t year; if (newerField(UCAL_EXTENDED_YEAR, UCAL_YEAR) == UCAL_EXTENDED_YEAR) { year = internalGet(UCAL_EXTENDED_YEAR, kGregorianEpoch); } else { // extended year is a gregorian year, where 1 = 1AD, 0 = 1BC, -1 = 2BC, etc year = internalGet(UCAL_YEAR, kGregorianEpoch - kBuddhistEraStart) + kBuddhistEraStart; } return year; } int32_t BuddhistCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool useMonth) const { return GregorianCalendar::handleComputeMonthStart(eyear, month, useMonth); } void BuddhistCalendar::handleComputeFields(int32_t julianDay, UErrorCode& status) { GregorianCalendar::handleComputeFields(julianDay, status); int32_t y = internalGet(UCAL_EXTENDED_YEAR) - kBuddhistEraStart; internalSet(UCAL_ERA, 0); internalSet(UCAL_YEAR, y); } int32_t BuddhistCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const { if(field == UCAL_ERA) { return BE; } else { return GregorianCalendar::handleGetLimit(field,limitType); } } #if 0 void BuddhistCalendar::timeToFields(UDate theTime, UBool quick, UErrorCode& status) { //Calendar::timeToFields(theTime, quick, status); int32_t era = internalGet(UCAL_ERA); int32_t year = internalGet(UCAL_YEAR); if(era == GregorianCalendar::BC) { year = 1-year; era = BuddhistCalendar::BE; } else if(era == GregorianCalendar::AD) { era = BuddhistCalendar::BE; } else { status = U_INTERNAL_PROGRAM_ERROR; } year = year - kBuddhistEraStart; internalSet(UCAL_ERA, era); internalSet(UCAL_YEAR, year); } #endif /** * The system maintains a static default century start date. This is initialized * the first time it is used. Once the system default century date and year * are set, they do not change. */ static UDate gSystemDefaultCenturyStart = DBL_MIN; static int32_t gSystemDefaultCenturyStartYear = -1; static icu::UInitOnce gBCInitOnce = U_INITONCE_INITIALIZER; UBool BuddhistCalendar::haveDefaultCentury() const { return TRUE; } static void U_CALLCONV initializeSystemDefaultCentury() { // initialize systemDefaultCentury and systemDefaultCenturyYear based // on the current time. They'll be set to 80 years before // the current time. UErrorCode status = U_ZERO_ERROR; BuddhistCalendar calendar(Locale("@calendar=buddhist"),status); if (U_SUCCESS(status)) { calendar.setTime(Calendar::getNow(), status); calendar.add(UCAL_YEAR, -80, status); UDate newStart = calendar.getTime(status); int32_t newYear = calendar.get(UCAL_YEAR, status); gSystemDefaultCenturyStartYear = newYear; gSystemDefaultCenturyStart = newStart; } // We have no recourse upon failure unless we want to propagate the failure // out. } UDate BuddhistCalendar::defaultCenturyStart() const { // lazy-evaluate systemDefaultCenturyStart and systemDefaultCenturyStartYear umtx_initOnce(gBCInitOnce, &initializeSystemDefaultCentury); return gSystemDefaultCenturyStart; } int32_t BuddhistCalendar::defaultCenturyStartYear() const { // lazy-evaluate systemDefaultCenturyStartYear and systemDefaultCenturyStart umtx_initOnce(gBCInitOnce, &initializeSystemDefaultCentury); return gSystemDefaultCenturyStartYear; } U_NAMESPACE_END #endif
32f0dbc1d0e738616c53804ea86bee3e582c2789
0cff9eb0f1203bb1e969157cdbd8923c18506630
/include_imm/stru_build_inst.h
a91217a75a78e79cdf0d5e93ddc37de182e687d5
[ "MIT" ]
permissive
endrollex/imm_engine
ed93ac0f3860e4c7bd4a5281732dec22878a04c1
034a7a11fc52708b091fe898ab6162d1dcb5c382
refs/heads/main
2023-06-02T19:44:20.612091
2023-06-02T07:54:30
2023-06-02T07:54:30
34,700,114
10
11
null
null
null
null
UTF-8
C++
false
false
3,129
h
//////////////// // stru_build_inst.h // by Huang Yiting //////////////// //////////////// #ifndef STRU_BUILD_INST_H #define STRU_BUILD_INST_H #include "stru_model_mgr.h" namespace imm { //////////////// // inst_build //////////////// //////////////// template <typename T_app> struct inst_build { inst_build(); void init(T_app *app_in); void remove_all(); bool inst_dump(); bool copy_player1(); T_app *app; std::vector<size_t> vindex; std::set<std::string> model; size_t copy_cnt; size_t copy_cnt_max; }; // template <typename T_app> inst_build<T_app>::inst_build(): app(nullptr), vindex(), model(), copy_cnt(0), copy_cnt_max(10000) { ; } // template <typename T_app> void inst_build<T_app>::init(T_app *app_in) { app = app_in; } // template <typename T_app> void inst_build<T_app>::remove_all() { copy_cnt = 0; } // template <typename T_app> bool inst_build<T_app>::inst_dump() { vindex.clear(); model.clear(); std::vector<std::string> csvdata; csvdata.push_back("name,model,scale,rotation,pos_x,pos_y,pos_z\r\n"); size_t index = 0; for (auto &stat: app->m_Inst.m_Stat) { ++index; if (stat.type != MODEL_SIMPLE_P) continue; if (stat.phy.intera_tp & PHY_INTERA_FIXED_INVIS) continue; vindex.push_back(index); if (model.find(*stat.get_ModelName()) == model.end()) model.insert(*stat.get_ModelName()); csvdata.push_back(std::string()); csvdata.back().append(app->m_Inst.m_IndexMap[index-1]); csvdata.back().append(","); csvdata.back().append(*stat.get_ModelName()); csvdata.back().append(","); csvdata.back().append("1"); csvdata.back().append(","); csvdata.back().append("0"); csvdata.back().append(","); csvdata.back().append(std::to_string(stat.get_World()->_41)); csvdata.back().append(","); csvdata.back().append(std::to_string(stat.get_World()->_42)); csvdata.back().append(","); csvdata.back().append(std::to_string(stat.get_World()->_43)); csvdata.back().append("\r\n"); // } std::string file_name = IMM_PATH["dump"]+"dump1.csv"; std::ofstream outfile (file_name, std::ofstream::binary); if (!outfile.is_open()) { outfile.close(); return false; } for (auto &line: csvdata) { outfile.write(line.c_str(), line.size()); } outfile.close(); return true; } // template <typename T_app> bool inst_build<T_app>::copy_player1() { ++copy_cnt; assert(copy_cnt < copy_cnt_max); size_t p1ix = app->m_Control.player1; std::string p1name = app->m_Inst.m_IndexMap[p1ix]; std::string copyname = p1name; if (copyname.size() > 6) copyname.resize(6); std::string namecnt = std::to_string(copy_cnt); for (int ix = 0; ix < 4-namecnt.size(); ++ix) namecnt = "0"+namecnt; copyname = copyname+namecnt; app->m_Inst.copy_instance(p1name, copyname); XMFLOAT3 copypos; copypos.x = app->m_Inst.m_Stat[p1ix].get_World()->_41; copypos.y = app->m_Inst.m_Stat[p1ix].get_World()->_42; copypos.z = app->m_Inst.m_Stat[p1ix].get_World()->_43; copypos.y += app->m_Inst.m_BoundL.extents_y(p1ix)*2.0f; size_t copyix = app->m_Inst.m_NameMap[copyname]; app->m_Inst.m_Stat[copyix].set_WorldPos(copypos); app->m_Control.set_player1(copyix); return true; } // } #endif
7f6224857376d4eeef2b96cbe1f2ecb330540826
c982c1813e4f47cec6913deb960e5082c042eca4
/d.h
3877bc9ed7c188733053ba35d002f0768fc10229
[]
no_license
daniele-mc/lp1-1unidade
c0e86562edaa9154790d6263424bee3da938da71
09dce27497bfba5d3db826cc9d0cc7f60c68518d
refs/heads/master
2020-05-19T08:04:25.114999
2019-05-04T15:43:50
2019-05-04T15:43:50
184,913,047
0
0
null
null
null
null
UTF-8
C++
false
false
231
h
#ifndef D_H #define D_H #include <iostream> #include <cstdlib> #include <ctime> using namespace std; class D{ private: int dado1; int dado2; public: //D(); D(int dado1 = 6, int dado2 = 6); int jogarD(); }; #endif
59fabea8448cfa8487a5822bc784cd80289a8e10
f7113575ad291de87c3a1d358fa64f0886487b40
/etutor_ITSA_16.cpp
7f283f708d969c85424db32d7e00b17ceaefa423
[]
no_license
cys107u/ITSA_C_plus
ba40996b641e6b792ea937a29c6989af2bbe1308
af53dabf32fbde160049c024ede4972164892efc
refs/heads/master
2022-11-14T20:21:55.450430
2020-07-09T05:37:52
2020-07-09T05:37:52
278,272,540
0
0
null
null
null
null
BIG5
C++
false
false
996
cpp
#include<iostream> #include<string.h> using namespace std; int main() { char A[8192],B[8192]; cin>>A>>B; int length_A=strlen(A);//取A的長度 int length_B=strlen(B);//取B的長度 int ans=0; //printf("%d:%s\n%d:%s\n",length_A,A,length_B,B); for(int now_B=0; now_B<length_B; now_B++)//從字串B的第一個字開始搜 { if(now_B+length_A>length_B)//如果B剩下的比A還少 { break; } //printf("!"); int flag=0;//用flag紀錄有幾個相同 for(int now_A=0; now_A<length_A; now_A++) { if(A[now_A]==B[now_B+now_A]) { flag++;//現在到的A跟B如果一樣flag就+ } } if(flag==length_A)//flag跟A的長度一樣,表示從B的這個字開始會跟A一樣 { ans++; } //printf("nowB:%d,f:%d\n",now_B,flag); } cout<<ans<<"\n"; return 0; }
87f7bf0c1cab5bf921c70e2f9b38ad010d1d0000
dd629803899abbb8b6d8b4503b3591bb7eae6e73
/include/forge/imaging/hd/compExtCompInputSource.h
154365ec3663d31921c09be1d3f47aef1e3bd28a
[]
no_license
furby-tm/Winggverse
8d78bb691d2e5eecc5197845e9cbfb98f45c58bd
0dc9db7057f52fca3e52e73491e24f298d108106
refs/heads/main
2023-04-21T17:32:20.350636
2021-04-30T04:24:30
2021-04-30T04:24:30
362,732,238
1
0
null
null
null
null
UTF-8
C++
false
false
2,641
h
#line 1 "C:/Users/tyler/dev/WINGG/forge/imaging/hd/compExtCompInputSource.h" /* * Copyright 2021 Forge. All Rights Reserved. * * The use of this software is subject to the terms of the * Forge license agreement provided at the time of installation * or download, or which otherwise accompanies this software in * either electronic or hard copy form. * * Portions of this file are derived from original work by Pixar * distributed with Universal Scene Description, a project of the * Academy Software Foundation (ASWF). https://www.aswf.io/ * * Original Copyright (C) 2016-2021 Pixar. * Modifications copyright (C) 2020-2021 ForgeXYZ LLC. * * Forge. The Animation Software & Motion Picture Co. */ #ifndef FORGE_IMAGING_HD_COMP_EXT_COMP_INPUT_SOURCE_H #define FORGE_IMAGING_HD_COMP_EXT_COMP_INPUT_SOURCE_H #include "forge/forge.h" #include "forge/imaging/hd/api.h" #include "forge/imaging/hd/version.h" #include "forge/imaging/hd/extCompInputSource.h" #include <memory> FORGE_NAMESPACE_BEGIN class HdExtCompCpuComputation; using HdExtCompCpuComputationSharedPtr = std::shared_ptr<HdExtCompCpuComputation>; /// /// An Hd Buffer Source Computation that is used to bind an ExtComputation input /// to a specific output of another ExtComputation. /// class Hd_CompExtCompInputSource final : public Hd_ExtCompInputSource { public: /// Constructs the computation, binding inputName to sourceOutputName /// on buffer source representation of the source computation. HD_API Hd_CompExtCompInputSource(const TfToken &inputName, const HdExtCompCpuComputationSharedPtr &source, const TfToken &sourceOutputName); HD_API virtual ~Hd_CompExtCompInputSource() = default; /// Returns true once the source computation has been resolved. HD_API virtual bool Resolve() override; /// Obtains the value of the output from the source computation. HD_API virtual const VtValue &GetValue() const override; protected: /// Returns true if the binding is successful. virtual bool _CheckValid() const override; private: HdExtCompCpuComputationSharedPtr _source; size_t _sourceOutputIdx; Hd_CompExtCompInputSource() = delete; Hd_CompExtCompInputSource(const Hd_CompExtCompInputSource &) = delete; Hd_CompExtCompInputSource &operator = (const Hd_CompExtCompInputSource &) = delete; }; FORGE_NAMESPACE_END #endif // FORGE_IMAGING_HD_COMP_EXT_COMP_INPUT_SOURCE_H
5fc3a57069073ee81a7d255f0df32d77e2dce3bd
934b0f30a81e7bdf9d81c4924bcd39a66adf4dc9
/APEX-S/Libraries/drake-v0.9.11-mac/build/include/drake/ValueConstraint.h
793b6107c649dc373da9369aad6b562d9bed1a76
[ "BSD-3-Clause" ]
permissive
mlab-upenn/arch-apex
6d253b418147216997b15b1daa5c835e0bb60afd
2af0fc3d6b61ad738aca2e100e4966ad394a5218
refs/heads/master
2021-01-17T23:38:28.551132
2016-03-18T23:15:37
2016-03-18T23:15:37
49,383,752
6
2
null
null
null
null
UTF-8
C++
false
false
664
h
#ifndef DRAKE_SOLVERS_QPSPLINE_VALUECONSTRAINT_H_ #define DRAKE_SOLVERS_QPSPLINE_VALUECONSTRAINT_H_ #undef DLLEXPORT #if defined(WIN32) || defined(WIN64) #if defined(drakeSplineGeneration_EXPORTS) #define DLLEXPORT __declspec( dllexport ) #else #define DLLEXPORT __declspec( dllimport ) #endif #else #define DLLEXPORT #endif class DLLEXPORT ValueConstraint { private: int derivative_order; double time; double value; public: ValueConstraint(int derivative_order, double time, double value); int getDerivativeOrder() const; double getTime() const; double getValue() const; }; #endif /* DRAKE_SOLVERS_QPSPLINE_VALUECONSTRAINT_H_ */
11f5a08f8d6a03aea169818503a22e08d8f8f666
1dfdc3004bd64b4839d74ed12bcc7eeed1a3e265
/Network Flow/lightoj__1155.cpp
f931da4cdde0293753866e2fcea5716fb0261d94
[]
no_license
JaberHPranto/Programming-
6944f2f213a05404109dacf50889e69b6c14fcce
5ebf17bf011ea51d674e135d345620814da84781
refs/heads/master
2023-02-07T03:48:49.595089
2021-01-02T10:00:05
2021-01-02T10:00:05
298,335,906
0
0
null
null
null
null
UTF-8
C++
false
false
2,361
cpp
#include<bits/stdc++.h> using namespace std; const int maxnodes = 100; int n,pr[210],cap[210][210]; int bfs(int src,int des) { int vis[210]= {0}; vis[src]=1; pr[src]=-1; queue<int>Q; Q.push(src); while(!Q.empty()) { int u=Q.front(); Q.pop(); for(int i=0; i<=2*(n+4); i++) { // cout <<i<<" "<<u<<" "<< vis[i] << " " << cap[u][i] << endl; if(vis[i] or cap[u][i]<=0) continue; Q.push(i); vis[i]=1; pr[i]=u; } } return vis[des]; } int maxFlow(int src,int des) { int f=0; while(bfs(src,des)) { int path=1e9; for(int i=des; i!=src; i=pr[i]) path=min(path,cap[pr[i]][i]); for(int i=des; i!=src; i=pr[i]) { int u=pr[i]; int v=i; // cout << "# " << u << " " << v <<"--"<<cap[u][v]<< endl; cap[u][v] -= path; cap[v][u] += path; } f+=path; } return f; } void clear(){ memset(pr, 0, sizeof(pr)); memset(cap, 0, sizeof(cap)); } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t,case_no=0; cin >> t; while(t--){ int edge, s, t,node_cap,i,val; cin >> n; int source = 0; int sink = 2 * (n + 4); for (i = 1; i <= n;i++){ cin >> val; int u = 2 * i - 1; int v = u + 1; cap[u][v] += val; cap[v][u] += val; } cin >>edge; for (i = 0; i < edge; i++) { int a, b, c; cin >> a >> b >> c; int u = 2 * a; int v = 2 * b - 1; cap[u][v] += c; // cap[v][u] += c; // cout <<u<<"-"<<v<<" "<< cap[u][v] << endl; } int b, d,node; cin >> b >> d; for (i = 1; i <= b;i++){ cin >> node; int u = 2 * node - 1; cap[source][u] = INT16_MAX; // cap[u][source] += INT16_MAX; } for (i = 1; i <= d;i++){ cin >> node; int u = 2 * node; cap[u][sink] = INT16_MAX; // cap[sink][u] += INT16_MAX; } cout << "Case " << ++case_no << ": " << maxFlow(source, sink) << "\n"; clear(); } }
2fb468e9c775c3a7ef3e4872f1ca35dd88f4960c
527739ed800e3234136b3284838c81334b751b44
/include/RED4ext/Types/generated/audio/GroupingCountableMetadata.hpp
93f518d109f7ebaf676b50ef1f60721c8d5de949
[ "MIT" ]
permissive
0xSombra/RED4ext.SDK
79ed912e5b628ef28efbf92d5bb257b195bfc821
218b411991ed0b7cb7acd5efdddd784f31c66f20
refs/heads/master
2023-07-02T11:03:45.732337
2021-04-15T16:38:19
2021-04-15T16:38:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
596
hpp
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Types/generated/audio/EmitterMetadata.hpp> namespace RED4ext { namespace audio { struct GroupingCountableMetadata : audio::EmitterMetadata { static constexpr const char* NAME = "audioGroupingCountableMetadata"; static constexpr const char* ALIAS = NAME; bool void; // 38 uint8_t unk39[0x40 - 0x39]; // 39 }; RED4EXT_ASSERT_SIZE(GroupingCountableMetadata, 0x40); } // namespace audio } // namespace RED4ext
6f4cc3a7891a0fd261599680d0a9e317bf37519b
d88aee6ee4f6c90e68bc27074ebc551da362992b
/SDS/day4/primesum.cpp
e3d2321442f0587e4a19550329488555183bc5e4
[]
no_license
hjy0951/Algorithm
ed04fd92c6c07e275377940435928bd569de5030
a84428254aad376f5cbc57c4dfc1dfc500dbea76
refs/heads/master
2023-06-25T23:44:36.992766
2023-06-12T06:15:23
2023-06-12T06:15:23
232,743,643
0
0
null
null
null
null
UTF-8
C++
false
false
1,027
cpp
// 백준 1644 소수의 연속합 #include <iostream> #include <vector> using namespace std; long long int n; vector<int> prime; int check[4000001]; int cnt; int main(){ cnt = 0; cin >> n; if(n == 1){ cout << 0 << "\n"; return 0; } else if(n == 2 || n == 3){ cout << 1 << "\n"; return 0; } // n보다 작은 소수들을 prime q에 넣음 for(int i = 2 ; i <= n ; i++){ if(check[i] == 0){ int cur = i; prime.push_back(cur); check[i] = 1; cur += i; while(cur <= n){ if(check[cur] == 0) check[cur] = 1; cur += i; } } } // 큐 안에서 투 포인터를 이용하여 수가 만들어지는 합 구간을 찾음 int s = 0, e = 0; int len = prime.size(); long long int sum = 0; while(e <= len){ if(sum < n){ sum += prime[e]; e++; } else if(sum > n){ sum -= prime[s]; s++; } if(sum == n){ cnt++; sum += prime[e]; e++; } } cout << cnt << endl; return 0; }
fd0a6b83e386bda2d794baa3106edcc9308a500a
675ad919b372939fcc4cd2ccffd62817522caaad
/source/core/image/texture/texture_byte_2_unorm.cpp
dff868f3c2384f5cf3f5a82efd25e17ccf8f5080
[]
no_license
lineCode/sprout
2308ff7de515c6499ffb5bf6889bf9ccebc6b2bd
ffaefc1c6ffd5f8fb6da3acbe98d05555586791e
refs/heads/master
2020-04-05T06:15:25.954312
2018-11-07T09:41:57
2018-11-07T09:41:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,840
cpp
#include "texture_byte_2_unorm.hpp" #include "base/math/vector4.inl" #include "image/typed_image.inl" #include "texture_encoding.hpp" namespace image::texture { Byte2_unorm::Byte2_unorm(std::shared_ptr<Image> image) noexcept : Texture(image), image_(*static_cast<const Byte2*>(image.get())) {} float Byte2_unorm::at_1(int32_t i) const noexcept { auto value = image_.load(i); return encoding::cached_unorm_to_float(value[0]); } float3 Byte2_unorm::at_3(int32_t i) const noexcept { auto value = image_.load(i); return float3(encoding::cached_unorm_to_float(value[0]), encoding::cached_unorm_to_float(value[1]), 0.f); } float Byte2_unorm::at_1(int32_t x, int32_t y) const noexcept { auto value = image_.load(x, y); return encoding::cached_unorm_to_float(value[0]); } float2 Byte2_unorm::at_2(int32_t x, int32_t y) const noexcept { auto value = image_.load(x, y); return float2(encoding::cached_unorm_to_float(value[0]), encoding::cached_unorm_to_float(value[1])); } float3 Byte2_unorm::at_3(int32_t x, int32_t y) const noexcept { auto value = image_.load(x, y); return float3(encoding::cached_unorm_to_float(value[0]), encoding::cached_unorm_to_float(value[1]), 0.f); } void Byte2_unorm::gather_1(int4 const& xy_xy1, float c[4]) const noexcept { byte2 v[4]; image_.gather(xy_xy1, v); c[0] = encoding::cached_unorm_to_float(v[0][0]); c[1] = encoding::cached_unorm_to_float(v[1][0]); c[2] = encoding::cached_unorm_to_float(v[2][0]); c[3] = encoding::cached_unorm_to_float(v[3][0]); } void Byte2_unorm::gather_2(int4 const& xy_xy1, float2 c[4]) const noexcept { byte2 v[4]; image_.gather(xy_xy1, v); encoding::cached_unorm_to_float(v, c); } void Byte2_unorm::gather_3(int4 const& xy_xy1, float3 c[4]) const noexcept { byte2 v[4]; image_.gather(xy_xy1, v); c[0] = float3(encoding::cached_unorm_to_float(v[0][0]), encoding::cached_unorm_to_float(v[0][1]), 0.f); c[1] = float3(encoding::cached_unorm_to_float(v[1][0]), encoding::cached_unorm_to_float(v[1][1]), 0.f); c[2] = float3(encoding::cached_unorm_to_float(v[2][0]), encoding::cached_unorm_to_float(v[2][1]), 0.f); c[3] = float3(encoding::cached_unorm_to_float(v[3][0]), encoding::cached_unorm_to_float(v[3][1]), 0.f); } float Byte2_unorm::at_element_1(int32_t x, int32_t y, int32_t element) const noexcept { auto value = image_.load_element(x, y, element); return encoding::cached_unorm_to_float(value[0]); } float2 Byte2_unorm::at_element_2(int32_t x, int32_t y, int32_t element) const noexcept { auto value = image_.load_element(x, y, element); return float2(encoding::cached_unorm_to_float(value[0]), encoding::cached_unorm_to_float(value[1])); } float3 Byte2_unorm::at_element_3(int32_t x, int32_t y, int32_t element) const noexcept { auto value = image_.load_element(x, y, element); return float3(encoding::cached_unorm_to_float(value[0]), encoding::cached_unorm_to_float(value[1]), 0.f); } float Byte2_unorm::at_1(int32_t x, int32_t y, int32_t z) const noexcept { auto value = image_.load(x, y, z); return encoding::cached_unorm_to_float(value[0]); } float2 Byte2_unorm::at_2(int32_t x, int32_t y, int32_t z) const noexcept { auto value = image_.load(x, y, z); return float2(encoding::cached_unorm_to_float(value[0]), encoding::cached_unorm_to_float(value[1])); } float3 Byte2_unorm::at_3(int32_t x, int32_t y, int32_t z) const noexcept { auto value = image_.load(x, y, z); return float3(encoding::cached_unorm_to_float(value[0]), encoding::cached_unorm_to_float(value[1]), 0.f); } } // namespace image::texture
3184050bdb012e63bf802d48c2eeb13a25c4b69f
62bf91e6efbc8762c6ff0097486e1d2a7836def7
/Data Structures/Trie/NoPrefixSet.cpp
c4704c98e3949f7466b5048393bc00cd924c40ac
[]
no_license
Fidanrlee/Hackerrank-solutions
1d7618c565125aff22a470fa3976f30bb8537eb8
91c7d3e1831fc296f2e68e2fa5eca6b8f1b5fd7c
refs/heads/master
2021-02-07T10:09:24.978660
2020-07-08T11:06:16
2020-07-08T11:06:16
244,012,551
0
0
null
null
null
null
UTF-8
C++
false
false
1,139
cpp
#include <iostream> #include <cmath> #include <cstring> #define MAX 100005 #define oo 1000000009 using namespace std; struct node{ int val[10] = {0}; bool A=false; node *link[10]={NULL}; }; node *trie = new node; int Add(string s){ node *tmp = trie; int i; for(i = 0; s[i] != '\0'; i++){ if(tmp->link[s[i] - 'a'] != NULL){ tmp = tmp->link[s[i] - 'a']; tmp->val[s[i] - 'a']++; if (tmp->A==true) return 0; }else{ node *new_node = new node; tmp->link[s[i] - 'a'] = new_node; tmp = new_node; tmp->val[s[i] - 'a']++; if (tmp->A==true) return 0; } } tmp->A=true; if(tmp->val[s[i-1] - 'a']>1) return 0; else return 1; } int main() { int n; cin>>n; string s1; while(n--) { cin>>s1; int a; a=Add(s1); if(a==0){ cout<<"BAD SET"<<endl<<s1<<endl; return 0; } else if(a==1 && n==0){ cout<<"GOOD SET"<<endl; return 0; } } return 0; }
53f1ad8c11e4bb4be03e12dca1124aa28cb1a577
b56a77108435afd8d47943381191096aff75cbff
/MyException.hpp
93bf4e6b78f57dfc501d7090947b2538364b7e06
[]
no_license
louischristner/MessageQueue
47ce602ed964dbecb96723802396a9a76ff160a7
66771b40ccacc70794ca6e0f5c66eb58a5485554
refs/heads/master
2022-04-28T07:41:50.722166
2020-04-30T16:11:03
2020-04-30T16:11:03
260,192,953
0
1
null
null
null
null
UTF-8
C++
false
false
453
hpp
/* ** EPITECH PROJECT, 2020 ** CCP_plazza_2019 ** File description: ** */ #ifndef MYEXCEPTION_HPP_ #define MYEXCEPTION_HPP_ #include <string> #include <exception> class MyException : public std::exception { public: MyException(const std::string &msg) noexcept : Msg("Exception: " + msg) {} const char *what() const noexcept override { return Msg.data(); } private: std::string Msg; }; #endif /* !MYEXCEPTION_HPP_ */
68a07b1a0a825a736e9e7787fa128ff993d10040
6b707de8b6df6e7a0f9e8eafca3bfd2712908575
/src/Day17.cpp
3df9b23e94f98f90d906454b8e08bf6fa5199cbc
[]
no_license
glasnak/aoc2018
0627ec0fefaadec40a2cc79af0db5bdbd397f402
3aed38f4bfd057312df80d5aa585b16546dbcfb7
refs/heads/master
2020-04-09T02:55:31.812496
2019-06-12T20:24:28
2019-06-12T20:24:28
159,960,458
0
0
null
null
null
null
UTF-8
C++
false
false
2,229
cpp
// --- Day 17: Reservoir Research --- #include "Day17.h" /// parse this: // x=495, y=2..7 // y=7, x=495..501 void Day17::parse(const std::vector<std::string> &Lines) { std::vector<Coord> SetBits; char Coord1, Coord2; int CoordStatic, CoordRangeMin, CoordRangeMax; for (const auto &Line : Lines) { sscanf(Line.c_str(), "%c=%d, %c=%d..%d\n", &Coord1, &CoordStatic, &Coord2, &CoordRangeMin, &CoordRangeMax); if (Coord1 == 'x') { for (int i = CoordRangeMin; i <= CoordRangeMax; ++i) { Grid.insert('#', Coord(i, CoordStatic)); } } else { // 'y' assert(Coord1 == 'y'); for (int i = CoordRangeMin; i <= CoordRangeMax; ++i) { Grid.insert('#', Coord(CoordStatic, i)); } } } } /// turn on the faucet and let the water flow down through the grid. void Day17::flow() { // honestly, this was more fun and easier to do in sublime text using regex and multi-cursor. // but here goes a pseudo-code anyway. // TODO: implement this: // while water can flow downwards, add '|' underneath active water block. // if # under |, reach instead left and right - loop until you find a wall. // when wall is found on both left and right, change flowing water '|' into still water '~' in this row. // once we changed the still water, look at the top of the stack for next flowing water, it now has '~' underneath. // for '~', act the same as for '#'. // if no wall is found and instead the empty block underneath exists, go down and continue the main loop. // Honestly, sublime multi-cursor plus regex works well for this kind of problem. } void Day17::solvePart1() { Grid = Matrix<char>(2000,2000); // more like 600x1800 and even first hundreds of columns can be ignored, to optimize later. Grid.fill('.'); Coord Faucet = Coord(0,500); Grid.insert('+', Faucet); FlowingWater.emplace_back(Faucet); std::vector<std::string> Lines = Util::getLines("inputs/input_17.txt"); // std::vector<std::string> Lines = Util::getLines("inputs/input_17.txt"); parse(Lines); std::cout << 36790 << "\n"; } void Day17::solvePart2() { // It was easier to do with regex semi-manually in a proper word processor. std::cout << 30765 << "\n"; }
85d0a78032d07f8c75b1c9ea5e505d1f9d815dbd
2764ca18ed56fdd91b2ecb2c2025f496cb7685f9
/CSCI430/GaryFowlerCSCI430Prog2/GaryFowlerCSCI430Prog2/Source.cpp
6a66f67c8223d8223a5c8ff99eae2ba0264abd27
[]
no_license
IamGary24/CollegeCourseWork
576c0b299124ea1c61c59266e9e15872f4f1184d
801d78042dbe0d3af993a5eff411c39157124b6b
refs/heads/master
2021-05-13T14:06:43.616746
2018-01-08T21:58:05
2018-01-08T21:58:05
116,728,205
0
0
null
null
null
null
UTF-8
C++
false
false
4,930
cpp
/** @file Source.cpp * * @author Gary Fowler III * * @assg Programming Assignment #2 * * @date June 18, 2017 */ #include <stdlib.h> #include "ProcessControlBlock.h" #include <iostream> #include <fstream> #include <string> #include <list> using namespace std; int nextProcessID = 1; int currentSystemTime = 1; bool processRunning = false; list<ProcessControlBlock> processList; //list to hold the ready processes /**The process dispatcher *See if anything in ready queue, make next process run, pop running process from ready queue * */ ProcessControlBlock dispatcher() { if (!processRunning) //if there is no process running, set a new process running { ProcessControlBlock nextProcessToRun = processList.front(); processRunning = true; return nextProcessToRun; } } /**Output the simulation *Output the current timestamp as well as all information about the processes * * */ void simulationOutput(ProcessControlBlock process) { cout << "Time: " << currentSystemTime << endl; cout << "CPU (currently running): " << endl; process.outputProcess(); cout << "Ready Queue: " << endl; //ready queue cout << "Blocked Queue: " << endl; //blocked queue cout << endl; } /** The process simulator. * The main loop for running a simulation. We read simulation * events from a file * * @param simfilename The name of the file (e.g. simulaiton-01.sim) to open * and read simulated event sequence from. * @param timeSliceQuantum The value to be used for system time slicing preemption * for this simulation. */ void runSimulation(char* simfilename, int timeSliceQuantum) { ifstream simeventsfile(simfilename); string command; int eventnum; if (!simeventsfile.is_open()) { cout << "Error: could not open simulator events file: " << simfilename << endl; exit(1); } while (!simeventsfile.eof()) { simeventsfile >> command; // Handle the next simulated event we just read from the // simulation event file if (command == "cpu") { ProcessControlBlock nextProcess = dispatcher(); if (nextProcess.getTimeSliceQuantumsUsed() < timeSliceQuantum) { simulationOutput(nextProcess); } else { processList.push_back(nextProcess); } currentSystemTime++; } else if (command == "new") { ProcessControlBlock newProcess(nextProcessID, currentSystemTime, "NEW", 1); //process is new, timeSliceQuantums used is default 1 nextProcessID++; processList.push_back(newProcess); simulationOutput(newProcess); currentSystemTime++; } else if (command == "done") { cout << " done: simulate termination of currently running process here" << endl; processList.pop_front(); currentSystemTime++; } else if (command == "wait") { simeventsfile >> eventnum; cout << " wait: eventnum: " << eventnum << " simulate event blocked and waiting" << endl; currentSystemTime++; } else if (command == "event") { simeventsfile >> eventnum; cout << " event: eventnum: " << eventnum << " simulate event occurring possibly making some processes ready" << endl; currentSystemTime++; } else if (command == "exit") { // we use an explicit indicator to ensure simulation exits correctly break; } else { cout << " ERROR: unknown command: " << command << endl; exit(0); } } simeventsfile.close(); } /** Main entry point of simulator * The main entry point of the process simulator. We simply set up * and initialize the environment, then call the appropriate function * to begin the simulation. We expect a single command line argument * which is the name of the simulation event file to process. * * @param argc The argument count * @param argv The command line argument values. We expect argv[1] to be the * name of a file in the current directory holding process events * to simulate. */ int main(int argc, char** argv) { int timeSliceQuantum = 0; // validate command line arguments if (argc != 3) { cout << "Error: expecting event file as first command line parameter and time slice quantum as second" << endl; cout << "Usage: " << argv[0] << " simeventfile.sim time_slice" << endl; exit(1); } // Assume second command line argument is the time slice quantum and parse it timeSliceQuantum = atoi(argv[2]); if (timeSliceQuantum <= 0) { cout << "Error: invalid time slice quantum received: " << timeSliceQuantum << endl; exit(1); } // Invoke the function to actually run the simulation runSimulation(argv[1], timeSliceQuantum); // if don't want to use command line do following. // need to recompile by hand since file // name to get simulated events from is hard coded //runSimulation("simulation-01.sim", 5); return 0; }
540a641d7227f7d13f4d5563fb79aeb5e0945382
b5e6a80820d0d13bbaaff83c8125134fd51a02f3
/a4/RayTrace/shademodel.cpp
e579787528f2a941b37acc244a7b4933ab736d80
[]
no_license
jguze/csc305_graphics
22bc774d25acedcddeac38397b439fc831c98537
32523a4a52f971adaa3ced164f5b2d81113b5367
refs/heads/master
2021-01-22T04:34:17.377163
2015-03-02T18:07:20
2015-03-02T18:07:20
31,554,601
0
0
null
null
null
null
UTF-8
C++
false
false
59
cpp
#include "shademodel.h" ShadeModel::ShadeModel() { }
7a15bf3df1c8e3ff2e4ba6811c1f74004899e7b4
09c7b95d714386cfd4ff88f89520f4204aeddcc7
/Windows/FFP/15_Point/GL_point.cpp
ad2fa14e0c7761b7f2a33d1705549e45c9f51dfc
[]
no_license
visonavane8/rtrOneEight
45ca78b5d7fc51b8a141d2008cabe019673d767b
0c38a9df25cc4dbf53ece66b4c19cea1c7b94bf9
refs/heads/master
2020-09-02T14:17:04.135799
2019-11-03T08:44:53
2019-11-03T08:44:53
219,239,286
0
0
null
null
null
null
UTF-8
C++
false
false
6,895
cpp
#include<windows.h> #include<stdio.h> #include<gl/GL.h> #pragma comment(lib,"opengl32.lib") #define WIN_WIDTH 800 #define WIN_HEIGHT 600 #define DEF 0 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); HWND ghwnd; HDC ghdc = NULL; HGLRC ghrc = NULL; //OpenGL Rendering Context FILE *gpfile; DWORD dwstyle; WINDOWPLACEMENT wpPrev = { sizeof(WINDOWPLACEMENT) }; bool bFullScreen = false; bool GbActiveWindow = false; bool GbFullScreen = false; void ToggleFullScreen(void); void resize(int, int); void display(void); void uninitialize(); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int iCmdShow) { //fuction declarations int initialize(void); //variable declarations WNDCLASSEX wndclass; HWND hwnd = NULL; MSG msg; TCHAR szAppName[] = TEXT("MyApp"); //variable declarations 2 bool bDone = false; int iRet = 0; //FullScreen Global void ToggleFullScreen(void); bool bFullScreen = false; WINDOWPLACEMENT wpPrev = { sizeof(WINDOWPLACEMENT) }; //code //initialization of WNDCLASSEX wndclass.cbSize = sizeof(WNDCLASSEX); wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.lpfnWndProc = WndProc; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndclass.lpszClassName = szAppName; wndclass.lpszMenuName = NULL; wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); //register above class RegisterClassEx(&wndclass); //create window hwnd = CreateWindowEx(WS_EX_APPWINDOW, szAppName, TEXT("OpenGL Window by Vinit"), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE, 100, 100, WIN_WIDTH, WIN_HEIGHT, NULL, NULL, hInstance, NULL); ghwnd = hwnd; if (fopen_s(&gpfile, "Log.txt", "w") != 0) { MessageBox(NULL, TEXT("Log File Cannot be Created"), TEXT("Error"), MB_OK); exit(0); } else { fprintf(gpfile, "Log File Successfully Created\n"); } iRet = initialize(); if (iRet == -1) { fprintf(gpfile, "Choose Pixel Format Failed\n"); } else if (iRet == -2) { fprintf(gpfile, "Set Pixel Format Failed\n"); } else if (iRet == -3) { fprintf(gpfile, "wglCreateContext failed\n"); } else if (iRet == -4) { fprintf(gpfile, "wglMakeCurrent failed\n"); DestroyWindow(hwnd); } else { fprintf(gpfile, "Initialization Successful\n"); } ShowWindow(hwnd, iCmdShow); SetForegroundWindow(hwnd); SetFocus(hwnd); //UpdateWindow(hwnd); //Gameloop while (bDone == false) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { bDone = true; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { if (GbActiveWindow == true) { //Here call update } //Here call display display(); } } return((int)msg.wParam); } LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { //code switch (iMsg) { case WM_SETFOCUS: GbActiveWindow = true; break; case WM_KILLFOCUS: GbActiveWindow = false; break; case WM_SIZE: resize(LOWORD(lParam), HIWORD(lParam)); case WM_PAINT: display(); // This should be done only in single buffering break; case WM_KEYDOWN: switch (wParam) { case VK_ESCAPE: MessageBox(hwnd, TEXT("This is Escape"), TEXT("MAIN2"), MB_OK); DestroyWindow(hwnd); break; case 0x46: ToggleFullScreen(); MessageBox(hwnd, TEXT("This is FullScreen"), TEXT("FS"), MB_OK); break; } case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: uninitialize(); PostQuitMessage(0); break; } return(DefWindowProc(hwnd, iMsg, wParam, lParam)); } int initialize(void) { //function declaration //variable declaration PIXELFORMATDESCRIPTOR pfd; int iPixelFormatIndex; //code //initialize pfd structure / Filling Form ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cRedBits = 8; pfd.cGreenBits = 8; pfd.cBlueBits = 8; pfd.cAlphaBits = 8; ghdc = GetDC(ghwnd); iPixelFormatIndex = ChoosePixelFormat(ghdc, &pfd); if (iPixelFormatIndex == 0) return -1; if (SetPixelFormat(ghdc, iPixelFormatIndex, &pfd) == false) return -2; ghrc = wglCreateContext(ghdc); if (ghrc == NULL) return -3; if (wglMakeCurrent(ghdc, ghrc) == false) return -4; glClearColor(0.0f, 0.0f, 0.0f, 1.0f); resize(WIN_WIDTH, WIN_HEIGHT); return 0; } void resize(int width, int height) { glViewport(0,0, (GLsizei)width, (GLsizei)height); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPointSize(5.0f); glBegin(GL_POINTS); //GL_POINTS glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f,0.0f); glEnd(); glFlush(); SwapBuffers(ghdc); } void uninitialize(void) { if (GbFullScreen == true) { SetWindowLong(ghwnd, GWL_STYLE, dwstyle | WS_OVERLAPPEDWINDOW); SetWindowPlacement(ghwnd, &wpPrev); SetWindowPos(ghwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOMOVE | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOOWNERZORDER); ShowCursor(TRUE); } if (wglGetCurrentContext() == ghrc) { wglMakeCurrent(NULL, NULL); } if (ghrc) { wglDeleteContext(ghrc); ghrc = NULL; } if (ghdc) { ReleaseDC(ghwnd, ghdc); ghdc = NULL; } if (gpfile) { fprintf(gpfile, "fclose Successful"); fclose(gpfile); gpfile = NULL; } } void ToggleFullScreen(void) { MONITORINFO mi; if (bFullScreen == false) { dwstyle = GetWindowLong(ghwnd, GWL_STYLE); if (dwstyle && WS_OVERLAPPEDWINDOW) { mi = { sizeof(MONITORINFO) }; if (GetWindowPlacement(ghwnd, &wpPrev) && GetMonitorInfo(MonitorFromWindow(ghwnd, MONITORINFOF_PRIMARY), &mi)) { SetWindowLong(ghwnd, GWL_STYLE, dwstyle & ~WS_OVERLAPPEDWINDOW); SetWindowPos(ghwnd, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right - mi.rcMonitor.left, mi.rcMonitor.bottom - mi.rcMonitor.top, SWP_NOZORDER | SWP_FRAMECHANGED); } } ShowCursor(FALSE); bFullScreen = true; } else { SetWindowLong(ghwnd, GWL_STYLE, dwstyle | WS_OVERLAPPEDWINDOW); SetWindowPlacement(ghwnd, &wpPrev); SetWindowPos(ghwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER); ShowCursor(TRUE); bFullScreen = false; } }
f0d34c785c20e218bb8758805a103aba7ba1d9df
fb59dcedeb1aae73e92afebeb6cb2e51b13d5c22
/middleware/src/porting/LocalPlayer/localplayer_port.cpp
c59252d893fad1f7b1eb9ff9d7557db4dc6109f2
[]
no_license
qrsforever/yxstb
a04a7c7c814b7a5647f9528603bd0c5859406631
78bbbae07aa7513adc66d6f18ab04cd7c3ea30d5
refs/heads/master
2020-06-18T20:13:38.214225
2019-07-11T16:40:14
2019-07-11T16:40:14
196,431,357
0
1
null
2020-03-08T00:54:09
2019-07-11T16:38:29
C
UTF-8
C++
false
false
7,601
cpp
#ifdef INCLUDE_LocalPlayer #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "json/json.h" #include "json/json_public.h" #include "Hippo_api.h" #include "Assertions.h" #include "config/pathConfig.h" #include "DirFileInfo.h" #include "RegularFileInfo.h" #include "FileManager.h" #include "libzebra.h" #include "Assertions.h" #define PlayerRootDir "/mnt" extern"C"{ using namespace Hippo; using namespace std; extern int get_jpeg_info(char *path, int *w, int *h); extern int get_png_info(char *path, int *w, int *h); extern int get_gif_info(char *path, int *w, int *h); extern int get_bmp_info(char *path, int *w, int *h); extern int ygp_pic_shrink(char *path, char *shrink_path, int *w, int *h, u32_t color, void *param); int currentDirId = 0; std::vector<FileInfo*> *pCurrentList = NULL; FileManager * pFileManager = NULL; int ReleseDirInfo(const char *pPath) { if(!pFileManager) { LogUserOperError("pFileManager is NULL\n"); return -1; } if (!pCurrentList) { LogUserOperError("pCurrentList is NULL\n"); return -1; } if (!pPath) { LogUserOperError("LocalPlayerFileManagerReleseDir path is NULL\n"); return -1; } LogUserOperDebug("ReleseDirInfo [%s]\n", pPath); std::string path = pPath; if (pCurrentList->size() > 0) { if (pCurrentList->at(0)->getFullPath().find(path) != std::string::npos) { pCurrentList->clear(); } } std::vector<std::string>* rootNameList = pFileManager->pathParser(PlayerRootDir); if ( !rootNameList || (rootNameList->size() == 0)) { LogUserOperError("ReleseDirInfo parser rootpath error\n"); return -1; } std::vector<std::string>* nameList = pFileManager->pathParser(path); if ( nameList && (nameList->size() > 1)) { if (nameList->at(0).compare(rootNameList->at(0))) { LogUserOperError("path is error 000\n"); goto Err; } pFileManager->releaseFileTree(pFileManager->getFileInfo(path), false); delete rootNameList; delete nameList; return 0; } Err: delete rootNameList; delete nameList; LogUserOperError("path is error\n"); return -1; } void LocalPlayerDiskRefresh(int type, const char *diskName, int position, const char *mountPoint) { extern void HDPlayerDiskRefresh(int type, const char *diskName, int position, const char *mountPoint); HDPlayerDiskRefresh(type, diskName, position, mountPoint); if(!pFileManager) { LogUserOperError("pFileManager is NULL\n"); return; } if (!pCurrentList) { LogUserOperError("pCurrentList is NULL\n"); return; } if (!mountPoint) { LogUserOperError("mountPoint is NULL\n"); return ; } LogUserOperDebug("umount [%s]\n", mountPoint); std::string mPoint = mountPoint; std::string sep = "|"; std::vector<std::string> *nameList = pFileManager->ParserString(mPoint, sep); for(unsigned int i = 0; i < nameList->size(); i++) { ReleseDirInfo(nameList->at(i).c_str()); } delete nameList; } int sortOrder = 0; bool compareName(FileInfo *a, FileInfo *b) { FileInfo *item_1 = NULL; FileInfo *item_2 = NULL; if (sortOrder) { item_1 = a; item_2 = b; } else { item_1 = b; item_2 = a; } if(!item_1 || !item_2) { LogUserOperError("compareName error\n"); return false; } if ((item_1->getFileType() == FileInfo::Dir_file) && (item_2->getFileType() == FileInfo::Dir_file)) { return item_1->getName() < item_2->getName(); } if ((item_1->getFileType() == FileInfo::Regular_file) && (item_2->getFileType() == FileInfo::Regular_file)) { return item_1->getName() < item_2->getName(); } return item_1->getFileType()<item_2->getFileType(); } bool compareSize(FileInfo *a, FileInfo *b) { FileInfo *item_1 = NULL; FileInfo *item_2 = NULL; if (sortOrder) { item_1 = a; item_2 = b; } else { item_1 = b; item_2 = a; } if(!item_1 || !item_2) { LogUserOperError("compareName error\n"); return false; } if ((item_1->getFileType() == FileInfo::Dir_file) && (item_2->getFileType() == FileInfo::Dir_file)) { return item_1->getFileSizeByte() < item_2->getFileSizeByte(); } if ((item_1->getFileType() == FileInfo::Regular_file) && (item_2->getFileType() == FileInfo::Regular_file)) { return item_1->getFileSizeByte() < item_2->getFileSizeByte(); } return item_1->getFileType() > item_2->getFileType(); } bool compareType(FileInfo *a, FileInfo *b) { FileInfo *item_1 = NULL; FileInfo *item_2 = NULL; if (sortOrder) { item_1 = a; item_2 = b; } else { item_1 = b; item_2 = a; } if(!item_1 || !item_2) { LogUserOperError("compareType error\n"); return false; } if ((item_1->getFileType() == FileInfo::Dir_file) && (item_2->getFileType() == FileInfo::Dir_file)) { return item_1->getName() < item_2->getName(); } if ((item_1->getFileType() == FileInfo::Regular_file) && (item_2->getFileType() == FileInfo::Regular_file)) { RegularFileInfo *pInfo_1 = static_cast<RegularFileInfo *>(item_1); RegularFileInfo *pInfo_2 = static_cast<RegularFileInfo *>(item_2); if (pInfo_1->getClassification() == pInfo_2->getClassification()) { std::string suffix_1; std::string suffix_2; std::string name_1; std::string name_2; std::string::size_type s1, s2; s1 = pInfo_1->getName().find_last_of('.'); s2 = pInfo_2->getName().find_last_of('.'); name_1 = pInfo_1->getName().substr(0, s1); name_2 = pInfo_2->getName().substr(0, s2); suffix_1 = pInfo_1->getName().substr(s1 + 1, pInfo_1->getName().length() - s1); suffix_2 = pInfo_2->getName().substr(s2 + 1, pInfo_2->getName().length() - s2); if (suffix_1 == suffix_2) return name_1 < name_2; else return suffix_1 < suffix_2; } else { return pInfo_1->getClassification() < pInfo_2->getClassification(); } } return item_1->getFileType() < item_2->getFileType(); } bool compareCreateTime(FileInfo *a, FileInfo *b) { FileInfo *item_1 = NULL; FileInfo *item_2 = NULL; if (sortOrder) { item_1 = a; item_2 = b; } else { item_1 = b; item_2 = a; } if(!item_1 || !item_2) { LogUserOperError("compareCreateTime error\n"); return false; } if ((item_1->getFileType() == FileInfo::Dir_file) && (item_2->getFileType() == FileInfo::Dir_file)) { return item_1->getFileCreateTime() < item_2->getFileCreateTime(); } if ((item_1->getFileType() == FileInfo::Regular_file) && (item_2->getFileType() == FileInfo::Regular_file)) { return item_1->getFileCreateTime() < item_2->getFileCreateTime(); } return item_1->getFileType() > item_2->getFileType(); } void a_LocalPlayer_JseMapInit() { extern int HDplayer_jseAPI_Register(ioctl_context_type_e type); HDplayer_jseAPI_Register(IoctlContextType_eHWBase); } };//extern"C" #endif//Localplayer
a42c0eaf12f5a85c9168f03ae677db003c08fc70
1022b24a65543c2e041eb6c3db12957d2793c359
/CytronWiFiShield-master/src/CytronWiFiShield.h
32d83f8c962ad65338f316589277d679d241e3f8
[]
no_license
tyrahuda/Temp-datalog
1b5dfe801a491a136e052a8180f2e4741f5e0c14
5c038cffcec862e9dc0e4b504b810241755a8d6f
refs/heads/master
2020-03-23T23:40:52.095884
2018-08-02T01:41:16
2018-08-02T01:41:16
142,248,619
0
1
null
null
null
null
UTF-8
C++
false
false
5,062
h
/****************************************************************************** CytronWiFiShield.h Cytron WiFi Shield Library Main Header File Created by Ng Beng Chet @ Cytron Technologies Sdn Bhd Original Creation Date: Sept 11, 2015 https://github.com/CytronTechnologies/CytronWiFiShield Modified from ESP8266 WiFi Shield Library Main Header File Credit to Jim Lindblom @ SparkFun Electronics Original Creation Date: June 20, 2015 http://github.com/sparkfun/SparkFun_ESP8266_AT_Arduino_Library !!! Description Here !!! Development environment specifics: IDE: Arduino 1.6.5 Hardware Platform: Arduino Uno ESP8266 WiFi Shield Version: 1.0 Distributed as-is; no warranty is given. ******************************************************************************/ #ifndef _CYTRONWIFISHIELD_H_ #define _CYTRONWIFISHIELD_H_ #include <Arduino.h> #include <SoftwareSerial.h> #include <IPAddress.h> /////////////////////////////// // Command Response Timeouts // /////////////////////////////// #define COMMAND_RESPONSE_TIMEOUT 5000 #define COMMAND_PING_TIMEOUT 3000 #define WIFI_CONNECT_TIMEOUT 30000 #define COMMAND_RESET_TIMEOUT 5000 #define CLIENT_CONNECT_TIMEOUT 10000 #define ESP8266_MAX_SOCK_NUM 5 #define ESP8266_SOCK_NOT_AVAIL 255 #define ESP8266_RX_BUFFER_LEN 128 #define AVAILABLE 0 #define TAKEN 1 #define ESP8266_STATUS_GOTIP 2 #define ESP8266_STATUS_CONNECTED 3 #define ESP8266_STATUS_DISCONNECTED 4 #define ESP8266_STATUS_NOWIFI 5 #define ESP8266_CMD_QUERY 0 #define ESP8266_CMD_SETUP 1 #define ESP8266_CMD_EXECUTE 2 #define ESP8266_CMD_BAD -5 #define ESP8266_RSP_MEMORY_ERR -4 #define ESP8266_RSP_FAIL -3 #define ESP8266_RSP_UNKNOWN -2 #define ESP8266_RSP_TIMEOUT -1 #define ESP8266_RSP_SUCCESS 0 #define OPEN 0 #define WPA_PSK 2 #define WPA2_PSK 3 #define WPA_WPA2_PSK 4 typedef enum esp8266_wifi_mode { WIFI_STA = 1, WIFI_AP = 2, WIFI_BOTH = 3 }; class ESP8266Class : public Stream { public: ESP8266Class(); bool begin(uint8_t rx_pin=2, uint8_t tx_pin=3); bool begin(HardwareSerial &hSerial); /////////////////////// // Basic AT Commands // /////////////////////// bool setAutoConn(bool enable); bool showInfo(bool enable); bool test(); bool reset(); String firmwareVersion(); bool echo(bool enable); //////////////////// // WiFi Functions // //////////////////// int8_t getMode(); bool setMode(esp8266_wifi_mode mode); bool connectAP(const char * ssid); bool connectAP(const char * ssid, const char * pwd); bool disconnectAP(); bool softAP(const char * ssid, const char * pwd, uint8_t channel_id = 1, uint8_t enc = 4); String SSID(); int RSSI(); IPAddress localIP(); bool config(IPAddress ip, IPAddress gateway = {192, 168, 1, 1}, IPAddress subnet = {255, 255, 255, 0}); IPAddress softAPIP(); int8_t status(); int8_t updateStatus(); ///////////////////// // TCP/IP Commands // ///////////////////// bool setSslBufferSize(size_t size); bool tcpConnect(uint8_t linkID, const char * destination, uint16_t port, uint16_t keepAlive=0); bool sslConnect(uint8_t linkID, const char * destination, uint16_t port, uint16_t keepAlive=0); int16_t tcpSend(uint8_t linkID, const uint8_t *buf, size_t buf_size); bool close(uint8_t linkID); //int16_t setTransferMode(uint8_t mode); bool setMux(bool enable); bool configureTCPServer(uint8_t create = 1, uint16_t port = 80); bool setServerTimeout(uint16_t time); //int16_t ping(IPAddress ip); //int16_t ping(char * server); ////////////////////////// // Custom GPIO Commands // ////////////////////////// //int16_t pinMode(uint8_t pin, uint8_t mode); bool digitalWrite(uint8_t pin, uint8_t state); int8_t digitalRead(uint8_t pin); /////////////////////////////////// // Virtual Functions from Stream // /////////////////////////////////// size_t write(uint8_t); int available(); int read(); int peek(); void flush(); //bool find(char *); //bool find(uint8_t *); friend class ESP8266Client; friend class ESP8266Server; bool _state[ESP8266_MAX_SOCK_NUM]; IPAddress _client[ESP8266_MAX_SOCK_NUM]; protected: Stream* _serial; SoftwareSerial* swSerial; private: bool init(); ////////////////////////// // Command Send/Receive // ////////////////////////// void sendCommand(const char * cmd, uint8_t type = ESP8266_CMD_EXECUTE, const char * params = NULL); int16_t readForResponse(const char * rsp, unsigned int timeout); int16_t readForResponses(const char * pass, const char * fail, unsigned int timeout); ////////////////// // Buffer Stuff // ////////////////// /// clearBuffer() - Reset buffer pointer, set all values to 0 void clearBuffer(); /// readByteToBuffer() - Read first byte from UART receive buffer /// and store it in rxBuffer. unsigned int readByteToBuffer(); /// searchBuffer([test]) - Search buffer for string [test] /// Success: Returns pointer to beginning of string /// Fail: returns NULL //! TODO: Fix this function so it searches circularly char * searchBuffer(const char * test); int8_t _status; bool isHardwareSerial; }; extern ESP8266Class wifi; #endif
ca5fc6db4bce0bc018d187c0996b176065d19427
db84bf6382c21920c3649b184f20ea48f54c3048
/gerdageometry/gerdageometry/GEGeometryLArInstTest.hh
d2a0fd4c5ceb4ef29cd4b6e6e595db9f914fbf13
[]
no_license
liebercanis/MaGeLAr
85c540e3b4c5a48edea9bc0520c9d1a1dcbae73c
aa30b01f3c9c0f5de0f040d05681d358860a31b3
refs/heads/master
2020-09-20T12:48:38.106634
2020-03-06T18:43:19
2020-03-06T18:43:19
224,483,424
2
0
null
null
null
null
UTF-8
C++
false
false
3,590
hh
//---------------------------------------------------------------------------// //bb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nu// // // // // // MaGe Simulation // // // // This code implementation is the intellectual property of the // // MAJORANA and Gerda Collaborations. It is based on Geant4, an // // intellectual property of the RD44 GEANT4 collaboration. // // // // ********************* // // // // 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. // // By copying, distributing or modifying the Program (or any work based // // on on the Program) you indicate your acceptance of this statement, // // and all its terms. // // // //bb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nu// //---------------------------------------------------------------------------// /** * CLASS DECLARATION: GEGeometryLArInstTest.hh * * AUTHOR: Nuno Barros * * CONTACT: nuno *dot* barros *at* tu-dresden *dot* de * ** DESCRIPTION: * * Declaration of a test LAr geometry composed simply of a cylinder collecting the incident photons. * The optical parameters do not represent any physical meaning for the moment. * * FIRST SUBMISSION: 02-11-2011 * * REVISION: MM-DD-YYYY * * */ #ifndef GEGEOMETRYLARINSTTEST_HH_ #define GEGEOMETRYLARINSTTEST_HH_ #include "gerdageometry/GEGeometryLArDesignBase.hh" class G4LogicalVolume; class G4VSolid; class G4VPhysicalVolume; class G4Material; class G4VisAttributes; class GEGeometryLArInstTest: public GEGeometryLArDesignBase { public: GEGeometryLArInstTest(GEGeometryDetectorDB* theGeometryDB); virtual ~GEGeometryLArInstTest(); void ConstructDesign(); // virtual G4LogicalVolume *GetLArInstrSDLogical(G4int index = 0); virtual G4LogicalVolume *GetLArInstrSDLogical(G4int index = 0); virtual G4int GetNumSDLogicVols(); virtual G4String GetLogicalSDName(G4int index = 0); virtual G4int GetNLogicalInstances(G4int index = 0); static const G4int npoints = 250; protected: // NB: These were shamelessly taken from MPIKLArGe G4double CalculateWLSmfp(G4double yield); G4double VM2000EmissionSpectrum(G4double energy); void InitializeVM2000Spectrum(); G4double CalculateRefractiveIndexGe(G4double lambda); private: G4VSolid* fFiberSolid; G4LogicalVolume* fFiberLogical; G4VPhysicalVolume* fFiberPhysical; G4LogicalVolume* fMotherLogical; // mother volume for the instrumentation GEGeometryDetectorDB* fDetectorDB; G4Material* fMaterialFiber; G4VisAttributes* fFiberVisAtt; G4bool fInitDone; // Some more aux tables: G4double frequencyV[npoints]; G4double efficiencyV[npoints]; }; #endif /* GEGEOMETRYLARINSTDUMMY_HH_ */
3555d47efb9f17d0f7ace4329a166e9a6788f4f6
2bfddaf9c0ceb7bf46931f80ce84a829672b0343
/src/xtd.drawing/include/xtd/drawing/imaging/color_palette.h
84fe0dac8162de3df39567f68132deb7ad54c3c6
[ "MIT" ]
permissive
gammasoft71/xtd
c6790170d770e3f581b0f1b628c4a09fea913730
ecd52f0519996b96025b196060280b602b41acac
refs/heads/master
2023-08-19T09:48:09.581246
2023-08-16T20:52:11
2023-08-16T20:52:11
170,525,609
609
53
MIT
2023-05-06T03:49:33
2019-02-13T14:54:22
C++
UTF-8
C++
false
false
3,760
h
/// @file /// @brief Contains xtd::drawing::imaging::color_palette class. /// @copyright Copyright (c) 2023 Gammasoft. All rights reserved. #pragma once #include <cstdint> #include <vector> #include <xtd/iequatable.h> #include <xtd/object.h> #include "../color.h" /// @brief The xtd namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace xtd { /// @brief The xtd::drawing namespace provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the xtd::drawing::drawing_2d, xtd::drawing::imaging, and xtd::drawing::text namespaces. namespace drawing { /// @cond class image; /// @endcond /// @brief The xtd.drawing.imaging namespace provides advanced GDI+ imaging functionality. Basic graphics functionality is provided by the xtd.drawing namespace. /// @remarks The metafile class provides methods for recording and saving metafiles. The encoder class enables users to extend GDI+ to support any image format. The property_item class provides methods for storing and retrieving metadata in image files. namespace imaging { /// @brief Defines an array of colors that make up a color palette. The colors are 32-bit ARGB colors. Not inheritable. /// @par Namespace /// xtd::drawing::imaging /// @par Library /// xtd.drawing /// @ingroup xtd_drawing /// @remarks You are not allowed to construct a color_palette object directly. If you created a color_palette object, you could then manipulate the palette size for a particular image, which is not allowed. Use the image.palette property to obtain a color_palette object. /// @remarks The colors in the palette are limited to 32-bit ARGB colors. A 32-bit ARGB color has 8 bits each for alpha, red, green, and blue values. The lowest 8 bits make up the blue bit, the next 8 bits are green, the next 8 bits are red, and the most significant 8 bits are alpha. This means each component can vary from 0 to 255. Fully on is 255 and fully off is 0. Alpha is used to make the color value transparent (alpha = 0) or opaque (alpha = 255). The number of intensity levels in the image can be increased without increasing the number of colors used. This process creates what is called a halftone, and it offers increased contrast at a cost of decreased resolution. class color_palette final : public object, public xtd::iequatable<color_palette> { public: /// @cond color_palette(const color_palette&) = default; color_palette& operator =(const color_palette&) = default; /// @endcond /// @name Properties /// @{ /// @brief Gets an array of color structures. /// @return The array of color structure that make up this color_palette. const std::vector<color>& entries() const noexcept {return entries_;} /// @brief Gets a value that specifies how to interpret the color information in the array of colors. /// @remarks The following flag values are valid: /// * 0x00000001 The color values in the array contain alpha information. /// * 0x00000002 The colors in the array are grayscale values. /// * 0x00000004 The colors in the array are halftone values. int32 flags() const noexcept {return flags_;} /// @} /// @name Methods /// @{ bool equals(const color_palette& value) const noexcept override {return entries_ == value.entries_ && flags_ == value.flags_;} /// @} private: friend class xtd::drawing::image; color_palette() = default; std::vector<color> entries_; int32 flags_ = 0; }; } } }
a81c2ef23c2a275fd641e17df07811308637666d
cd726912664cea9c458ac8b609dd98bf33e3b9a0
/snippets/cpp/VS_Snippets_CLR_System/system.Int16.Parse/cpp/parse3.cpp
e17d9457ac6c96aa7cf1447bcbecae806ce6cc98
[ "MIT", "CC-BY-4.0" ]
permissive
dotnet/dotnet-api-docs
b41fc7fa07aa4d54205df81284bae4f491286ec2
70e7abc4bcd692cb4fb6b4cbcb34bb517261dbaf
refs/heads/main
2023-09-04T07:16:44.908599
2023-09-01T21:46:11
2023-09-01T21:46:11
111,510,915
630
1,856
NOASSERTION
2023-09-14T21:45:33
2017-11-21T06:52:13
C#
UTF-8
C++
false
false
1,963
cpp
// Parse3.cpp : main project file. using namespace System; using namespace System::Globalization; int main(array<System::String ^> ^args) { // <Snippet3> String^ value; Int16 number; NumberStyles style; // Parse string using "." as the thousands separator // and " " as the decimal separator. value = "19 694,00"; style = NumberStyles::AllowDecimalPoint | NumberStyles::AllowThousands; CultureInfo^ provider = gcnew CultureInfo("fr-FR"); number = Int16::Parse(value, style, provider); Console::WriteLine("'{0}' converted to {1}.", value, number); // Displays: // '19 694,00' converted to 19694. try { number = Int16::Parse(value, style, CultureInfo::InvariantCulture); Console::WriteLine("'{0}' converted to {1}.", value, number); } catch (FormatException ^e) { Console::WriteLine("Unable to parse '{0}'.", value); } // Displays: // Unable to parse '19 694,00'. // Parse string using "$" as the currency symbol for en_GB and // en-US cultures. value = "$6,032.00"; style = NumberStyles::Number | NumberStyles::AllowCurrencySymbol; provider = gcnew CultureInfo("en-GB"); try { number = Int16::Parse(value, style, CultureInfo::InvariantCulture); Console::WriteLine("'{0}' converted to {1}.", value, number); } catch (FormatException ^e) { Console::WriteLine("Unable to parse '{0}'.", value); } // Displays: // Unable to parse '$6,032.00'. provider = gcnew CultureInfo("en-US"); number = Int16::Parse(value, style, provider); Console::WriteLine("'{0}' converted to {1}.", value, number); // Displays: // '$6,032.00' converted to 6032. // </Snippet3> Console::ReadLine(); return 0; }
69394f201c6b02e1dbee41faecd3262a02892115
6923ef5f30a47f3a8daeba1fc4853bfb853ccf2b
/Include/Imagics/GteHistogram.h
888ba3d8a4294a39ce78c9d9f758a361118a45a3
[]
no_license
0000duck/GTEngine
61ea1f42115de89f609d2e689ccf772740bb9df6
dd6a813d39a2ee6a3d816065ae59bed52c427f70
refs/heads/master
2022-03-01T05:22:07.143977
2019-11-05T06:02:22
2019-11-05T06:02:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,154
h
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) #pragma once #include <GTEngineDEF.h> #include <vector> namespace gte { class GTE_IMPEXP Histogram { public: // In the constructor with input 'int const* samples', set noRescaling to // 'true' when you want the sample values mapped directly to the buckets. // Typically, you know that the sample values are in the set of numbers // {0,1,...,numBuckets-1}, but in the event of out-of-range values, the // histogram stores a count for those numbers smaller than 0 and those // numbers larger or equal to numBuckets. Histogram(int numBuckets, int numSamples, int const* samples, bool noRescaling); Histogram(int numBuckets, int numSamples, float const* samples); Histogram(int numBuckets, int numSamples, double const* samples); // Construction where you plan on updating the histogram incrementally. // The incremental update is implemented only for integer samples and // no rescaling. Histogram(int numBuckets); // This function is called when you have used the Histogram(int) // constructor. No bounds checking is used; you must ensure that the // input value is in {0,...,numBuckets-1}. inline void Insert(int value); // This function is called when you have used the Histogram(int) // constructor. Bounds checking is used. void InsertCheck(int value); // Member access. inline std::vector<int> const& GetBuckets() const; inline int GetExcessLess() const; inline int GetExcessGreater() const; // In the following, define cdf(V) = sum_{i=0}^{V} bucket[i], where // 0 <= V < B and B is the number of buckets. Define N = cdf(B-1), // which must be the number of pixels in the image. // Get the lower tail of the histogram. The returned index L has the // properties: cdf(L-1)/N < tailAmount and cdf(L)/N >= tailAmount. int GetLowerTail(double tailAmount); // Get the upper tail of the histogram. The returned index U has the // properties: cdf(U)/N >= 1-tailAmount and cdf(U+1) < 1-tailAmount. int GetUpperTail(double tailAmount); // Get the lower and upper tails of the histogram. The returned indices // are L and U and have the properties: // cdf(L-1)/N < tailAmount/2, cdf(L)/N >= tailAmount/2, // cdf(U)/N >= 1-tailAmount/2, and cdf(U+1) < 1-tailAmount/2. void GetTails(double tailAmount, int& lower, int& upper); private: std::vector<int> mBuckets; int mExcessLess, mExcessGreater; }; inline void Histogram::Insert(int value) { ++mBuckets[value]; } inline std::vector<int> const& Histogram::GetBuckets() const { return mBuckets; } inline int Histogram::GetExcessLess() const { return mExcessLess; } inline int Histogram::GetExcessGreater() const { return mExcessGreater; } }
107092f8aec70c5aaba69390f9dbc0d0e9ef9d62
220227c1cae2bd4892351c7f1f185892672bd673
/NexaSelfLearningConstants.inc
cfc1fa8776b0ad14be67ba4e377af28a77f15508
[ "BSD-2-Clause" ]
permissive
dcollin/NexaControl
51e2ea484f4ab779e743261fe60084ff12e644ed
5fd5429375b3fffbf0bdd041d493d5c6ff0c156a
refs/heads/master
2021-01-17T10:45:17.958959
2016-01-22T16:34:58
2016-01-22T16:34:58
30,599,493
4
1
null
2016-06-17T18:08:21
2015-02-10T15:45:43
C++
UTF-8
C++
false
false
1,626
inc
#ifndef NEXA_SELF_LEARNING_CONSTANTS #define NEXA_SELF_LEARNING_CONSTANTS //timings (in microseconds) for preamble pulses over air. #define PREAMBLE_HIGH 250 #define PREAMBLE_LOW 2500 #define PREAMBLE_LOW_MIN 2200 //allowed lower variation when detecting the low pulse length #define PREAMBLE_LOW_MAX 2800 //allowed higher variation when detecting the low pulse length //timings (in microseconds) for binary one pulses over air. #define ONE_HIGH 250 #define ONE_LOW 1250 #define ONE_LOW_MIN 1100 //allowed lower variation when detecting the low pulse length #define ONE_LOW_MAX 1550 //allowed higher variation when detecting the low pulse length //timings (in microseconds) for binary zero pulses over air. #define ZERO_HIGH 250 #define ZERO_LOW 250 #define ZERO_LOW_MIN 200 //allowed lower variation when detecting the low pulse length #define ZERO_LOW_MAX 400 //allowed higher variation when detecting the low pulse length //timings (in microseconds) for end pulses over air. #define END_HIGH 250 #define END_LOW 10000 #define END_LOW_MIN 8000 //allowed lower variation when detecting the low pulse length #define END_LOW_MAX 12000 //allowed higher variation when detecting the low pulse length //the time (in ms) during which a duplicate signal is ignored. #define DUPLICATE_SIGNAL_DELAY 250 //value boundaries for valid transmitter IDs. #define TRANSMITTER_ID_MIN 1 #define TRANSMITTER_ID_MAX 67108863 //((2^26)-1) #endif //NEXA_SELF_LEARNING_CONSTANTS
94d1d3968794405cb07d0239aa07b7ffedd1887e
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/contest/1542581317.cpp
4ebdc229cb13f0c39b379b60c67a25f1acdf4df6
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
1,433
cpp
//#include "stdafx.h" #include <cstdio> #include <cstdlib> #include <iostream> #include <algorithm> #include <iostream> using namespace std; // //char str[5]; //bool fr(false), ls(false); //int main() //{ // cin >> str; // int n; // cin >> n; // for (int i(0); i != n; ++i) // { // char s[5]; // cin >> s; // if (s[1] == str[0]) // { // fr = true; // } // if (s[0] == str[1]) // { // ls = true; // } // } // if (fr && ls) // { // printf("YES\n"); // } // else // { // printf("NO\n"); // } // return 0; //} int main() { double tm[5]; double perh = 360 / 12, perm = 360 / 60, pers = 360 / 60; cin >> tm[0] >> tm[1] >> tm[2] >> tm[3] >> tm[4]; tm[0] = tm[0] * perh + tm[1] / 60 * perh + tm[2] / 60 / 60 * perh; tm[1] = tm[1] * perm + tm[2] / 60 * perm; tm[2] = tm[2] * pers; tm[3] *= perh; tm[4] *= perh; //for (int i = 0; i < 5; i++) //{ // cout << tm[i] << endl; //} double beg(tm[3]), end(tm[4]); sort(tm, tm + 5); //for (int i = 0; i < 5; i++) //{ // cout << tm[i] << endl; //} int b, e; for (int i(0); i < 5; ++i) { if (beg == tm[i]) b = i; if (end == tm[i]) e = i; } //printf("%d %d\n", b, e); if (abs(b - e) == 1 || abs(b - e) == 4) { printf("YES\n"); } else { printf("NO\n"); } //system("pause"); return 0; }
bc82c4f15fd5e0cd2f6dac7536831bcb65e4566a
db84bf6382c21920c3649b184f20ea48f54c3048
/validation/AlphaInteractions/AlphaInteractionAnalysis.cxx
62b38549e2407567047f237816ad5ed549f696c8
[]
no_license
liebercanis/MaGeLAr
85c540e3b4c5a48edea9bc0520c9d1a1dcbae73c
aa30b01f3c9c0f5de0f040d05681d358860a31b3
refs/heads/master
2020-09-20T12:48:38.106634
2020-03-06T18:43:19
2020-03-06T18:43:19
224,483,424
2
0
null
null
null
null
UTF-8
C++
false
false
8,143
cxx
// C++ headers #include <iostream> #include <fstream> #include <sstream> #include <math.h> #include <vector> // CERN ROOT headers #include <TROOT.h> #include <TSystem.h> #include <TCanvas.h> #include <TLatex.h> #include <TStyle.h> #include <TF1.h> #include <TH1F.h> #include <TApplication.h> #include <TFile.h> #include <TTree.h> #include <TGraph.h> #include <TGraphErrors.h> #include <TAxis.h> #include <TLegend.h> //#include <TLegend.h> // MaGe Validation headers #include "../VaLi/ParticleTrack.h" #include "MaterialInteraction.h" #include "../VaLi/RComp.h" #include "../../io/io/MGOutputG4StepsData.hh" using namespace std; int main(int argc, char* argv[]) { string compfile = ""; string compfile_new = ""; int relcomp = 0; if (argc < 2) { std::cout << "Usage: AlphaInteractionAnalysis <element name> \n"; return 0; } if(argc == 3){ relcomp = 1; compfile = argv[2]; } if(argc == 4){ relcomp = 1; compfile = argv[2]; compfile_new = argv[3]; } string elementName(argv[1]); TCanvas* can; TApplication theApp("App", &argc, argv); TFile *runfile; stringstream label; ifstream inputfile; ofstream outputfile; // Relative Comparison RComp *rcomp = new RComp(); RComp *rcomp_new = new RComp(); // Adjusting ROOT style gROOT->SetBatch(true); gROOT->SetStyle("Plain"); gStyle->SetOptStat(0); UInt_t runID, eventID, trackID, parentID; Int_t PID; Double_t positionX, positionY, positionZ, energyKinetic, energyDeposit; can = new TCanvas("can","InteractionAnalysis",1100,500); can->SetGrid(); can->SetLogy(); can->Connect("Closed()", "TApplication", &theApp, "Terminate()"); string s; string* ps; vector<double> energy_literature; vector<double> attenuation_literature; vector<double> energy_simulation; vector<double> attenuation_simulation; vector<string> token; double density,temp; int dataType; size_t endposition; istringstream conv; string filename = "dat/" + elementName + ".dat"; inputfile.open(filename.c_str()); if (inputfile.fail()) { cout << "ERROR! Can't open file \"" << filename << "\"\n"; } while (getline(inputfile, s)) { ps = new string[2]; endposition = s.find(":XX", 0); if(s[0]=='#') continue; if(endposition==string::npos) continue; ps[0] = s.substr(0, endposition + 3); ps[1] = s.substr(endposition + 3); conv.str(ps[1]); conv >> dataType; switch(dataType){ case 10: conv >> density; cout << "density:\t" << density << "\n"; break; case 13: conv >> temp; energy_literature.push_back(temp); conv >> temp; attenuation_literature.push_back(temp / density); token.push_back(ps[0]); break; } conv.str(""); conv.clear(); } inputfile.close(); s = elementName + "parameter.txt"; cout << "generating file " << s << "\n"; outputfile.open(s.c_str()); inputfile.open("dat/alphaEnergies.txt"); if (inputfile.fail()) { cout << "ERROR! File alphaEnergies.txt is missing. AlphaInteractionAnalysis terminated\n"; return 0; } while (getline(inputfile, s)) { conv.str(s); conv >> temp; conv.str(""); conv.clear(); energy_simulation.push_back(temp); filename = "dat/" + elementName + "_" + s + "MeV.root"; cout << filename << "\n"; runfile = new TFile(filename.c_str()); if(runfile->IsZombie()){ cout << "trouble!\n"; return 0; } MaterialInteraction *newInteraction = new MaterialInteraction(); newInteraction->SetToken("XX:" + elementName + "_CSDA_alpha" + s + "MeV:XX"); newInteraction->SetEnergy(temp); for(int i=0;i<energy_literature.size();i++){ if(temp == energy_literature[i]){ newInteraction->SetAttenuationLiterature(attenuation_literature[i]); break; } } MGOutputG4StepsData *dat = new MGOutputG4StepsData(); TTree *tree = (TTree*) runfile->Get("fTree"); TBranch *branch = tree->GetBranch("RawMC"); branch->SetAddress(&dat); cout << "number of entries: " << tree->GetEntries() << "\n"; for(int i=0;i<tree->GetEntries();i++){ tree->GetEntry(i); newInteraction->AddInteractionNode(i, 0.0, 0.0, 0.0, temp, 0.0); for(int j=0;j<dat->fTotalNumberOfSteps;j++){ if(dat->fTrackID[j]==1){ //cout << dat->fX[j] << "\t" << dat->fY[j] << "\t" << dat->fZ[j] << "\n"; newInteraction->AddInteractionNode(i,dat->fX[j], dat->fY[j], dat->fZ[j],0.0,dat->fEdep[j]); } } } outputfile << newInteraction->GetEnergyToken() << "\n"; outputfile << newInteraction->GetAttenuationLiteratureToken() << "\n"; outputfile << newInteraction->GetAverageTotalRangeToken() << "\n"; outputfile << newInteraction->GetAttenuationDifferenceToken(); if(newInteraction->GetEnergy() == 2.0){ newInteraction->PlotHistogramEndZ(); std::stringstream label; label.str(""); label.clear(); label << "pics/" << elementName << "_alpha" << newInteraction->GetEnergy() << "MeV.pdf"; can->SaveAs(label.str().c_str()); outputfile << "XX:" << elementName << "_alpha" << newInteraction->GetEnergy() << "MeV_plot:XX\t"; outputfile << "AlphaInteractions/" << label.str() << "\n"; gSystem->ProcessEvents(); } attenuation_simulation.push_back(newInteraction->GetAverageTotalRange()); runfile->Close(); delete runfile; delete dat; delete newInteraction; } inputfile.close(); if (relcomp == 1) { label.str(""); label.clear(); label << "dat/" << elementName << "_" << compfile << ".root"; if (gSystem->AccessPathName(label.str().c_str(), kFileExists) == 0) rcomp->OpenCompFile(label.str(), "READ"); if (compfile_new.size() > 0) { label.str(""); label.clear(); label << "dat/" << elementName << "_" << compfile_new << ".root"; rcomp_new->CreateNewCompFile(label.str()); rcomp_new->OpenCompFile(label.str(), "UPDATE"); cout << "opening file " << label.str() << "\n"; } } TLegend *leg = new TLegend(0.75,0.99,0.99,0.86); TGraphErrors *gr_sim = new TGraphErrors(attenuation_simulation.size()); TGraphErrors *gr_comp = new TGraphErrors(attenuation_simulation.size()); for(int i=0;i<attenuation_simulation.size();i++){ gr_sim->SetPoint(i,energy_simulation[i],attenuation_simulation[i]); gr_sim->SetPointError(i,0.0,0.0); if(relcomp){ s = token[i]; outputfile << s.substr(0,s.size()-3) << "_attenuation_simulation_old:XX\t"; outputfile << rcomp->GetEntryValue(s.substr(0,s.size()-3) + "_attenuation_simulation:XX") << "\n"; outputfile << s.substr(0,s.size()-3) << "_attenuation_reldiff:XX\t"; outputfile << rcomp->GetAgreementColourString(attenuation_simulation[i],0.0,rcomp->GetEntryValue(s.substr(0,s.size()-3) + "_attenuation_simulation:XX"),rcomp->GetEntryValue(s.substr(0,s.size()-3) + "_attenuation_simulation_sigma:XX"),1.0 ); rcomp_new->WriteEntry(s.substr(0,s.size()-3) + "_attenuation_simulation:XX",attenuation_simulation[i],0.0); gr_comp->SetPoint(i,energy_simulation[i], rcomp->GetEntryValue(s.substr(0,s.size()-3) + "_attenuation_simulation:XX")); gr_comp->SetPointError(i,0.0,rcomp->GetEntrySigma(s.substr(0,s.size()-3) + "_attenuation_simulation:XX")); } } can->SetLogx(); gr_sim->SetMarkerColor(kRed); gr_sim->SetTitle(elementName.c_str()); gr_sim->SetMarkerStyle(21); gr_sim->GetXaxis()->SetTitle("alpha energy [MeV]"); gr_sim->GetYaxis()->SetTitle("range [cm]"); leg->AddEntry(gr_sim,"simulated values","p"); can->Update(); gr_sim->Draw("AP"); if(relcomp){ gr_comp->SetMarkerStyle(23); gr_comp->SetMarkerColor(kGray + 1); s = "previous values (" + compfile + ")"; leg->AddEntry(gr_comp,s.c_str(),"p"); gr_comp->Draw("P"); } TGraph *gr_lit = new TGraph(energy_literature.size()); for(int i=0;i<energy_literature.size();i++) gr_lit->SetPoint(i,energy_literature[i],attenuation_literature[i]); gr_lit->SetMarkerColor(kBlack); gr_lit->SetMarkerStyle(24); leg->AddEntry(gr_lit,"literature values","p"); gr_lit->Draw("P"); leg->Draw(); s = "pics/" + elementName + "_plot.pdf"; can->SaveAs(s.c_str()); outputfile << "XX:" << elementName << "_plot:XX\t"; outputfile << "AlphaInteractions/pics/" << elementName << "_plot.pdf"; outputfile.close(); //theApp.Run(); if(relcomp == 1){ rcomp_new->CloseCompFile(); rcomp->CloseCompFile(); } return 0; }
cca67078a98d5f6aabe6b419d67997261c06fa4c
e05b9a88b1fabe2b76139154f027bdffebb88763
/src/render/Shader.cpp
700a51017b3229a108baee789f03f991e1e3f3a1
[]
no_license
JaronOrchard/idsc
ab188ae816fc05cdb557bfbd048000f7c17cf8de
3a5df91fc07ba62fa563211bdaa3bde004f3dfea
refs/heads/master
2021-01-22T18:18:23.999013
2015-02-11T21:03:19
2015-02-11T21:03:19
24,157,400
1
0
null
null
null
null
UTF-8
C++
false
false
2,739
cpp
#include "Shader.h" #include <string.h> #include <iostream> #include <fstream> #include <streambuf> Shader::Shader(int id) { this->id = id; } int Shader::get_id() { return id; } Shader * Shader::compile_from(char * v_file, char * f_file) { int id = load_shaders(v_file, NULL, f_file); return new Shader(id); } Shader * Shader::compile_from(char * v_file, char * g_file, char * f_file) { int id = load_shaders(v_file, g_file, f_file); return new Shader(id); } GLuint Shader::load_shader(char * file_name, GLenum shader_type) { GLuint id = glCreateShader(shader_type); std::string shader_code; std::ifstream file_stream(file_name); if (file_stream.fail()) { fprintf(stderr, "could not find shader file %s\n", file_name); throw 1; } file_stream.seekg(0, std::ios::end); shader_code.reserve(file_stream.tellg()); file_stream.seekg(0, std::ios::beg); shader_code.assign((std::istreambuf_iterator<char>(file_stream)), std::istreambuf_iterator<char>()); char const * source_pointer = shader_code.c_str(); glShaderSource(id, 1, &source_pointer , NULL); glCompileShader(id); int log_length; GLint result = GL_FALSE; glGetShaderiv(id, GL_COMPILE_STATUS, &result); glGetShaderiv(id, GL_INFO_LOG_LENGTH, &log_length); if (log_length > 1) { char * error_message = (char *) calloc(log_length + 1, sizeof(char)); glGetShaderInfoLog(id, log_length, NULL, error_message); fprintf(stderr, "error when compiling shader file %s\n", file_name); fprintf(stderr, "%s\n", error_message); free(error_message); throw 1; } return id; } GLuint Shader::load_shaders(char * v_file, char * g_file, char * f_file) { GLuint program_id = glCreateProgram(); GLuint v_id = load_shader(v_file, GL_VERTEX_SHADER); glAttachShader(program_id, v_id); GLuint g_id; if (g_file != NULL) { g_id = load_shader(g_file, GL_GEOMETRY_SHADER); glAttachShader(program_id, g_id); } GLuint f_id = load_shader(f_file, GL_FRAGMENT_SHADER); glAttachShader(program_id, f_id); glLinkProgram(program_id); int log_length; GLint result = GL_FALSE; glGetProgramiv(program_id, GL_LINK_STATUS, &result); glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &log_length); if (log_length > 1){ char * error_message = (char *) calloc(log_length + 1, sizeof(char)); glGetProgramInfoLog(program_id, log_length, NULL, error_message); printf("%s\n", error_message); free(error_message); } glDeleteShader(v_id); if (g_file != NULL) { glDeleteShader(g_id); } glDeleteShader(f_id); return program_id; }
67742ad0b07114cc08fc99168cec297907240fa0
88061c078a687620e53f413d9cee0645891e1d40
/fitsGen/src/MeritFile2.cxx
d0331c21de017bcc8c4c6d0e1ece602a1c3f746b
[]
no_license
fermi-lat/ScienceTools-scons-old
2b80b24220433fc951c7e12cb2935a3b6d5690aa
1bc4e2dc8db28e87c4b97afb998ff1ce2fd770b8
refs/heads/master
2021-06-29T02:10:35.524126
2017-08-23T23:40:25
2017-08-23T23:40:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,922
cxx
/** * @file MeritFile2.cxx * @brief Interface to merit files that uses ROOT directly. * @author J. Chiang * * $Header$ */ #include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <stdexcept> #include "TChain.h" #include "TError.h" #include "TEventList.h" #include "TFile.h" #include "TFormula.h" #include "TLeaf.h" #include "TObjArray.h" #include "TSystem.h" #include "TTree.h" #include "fitsGen/MeritFile2.h" namespace fitsGen { MeritFile2::MeritFile2(const std::string & meritfile, const std::string & tree, const std::string & filter) : m_file(0), m_tree(0), m_index(0) { /// Vain effort to suppress uninformative error messages from ROOT. /// This is borrowed from tip::RootTable.cxx. long root_err_level = gErrorIgnoreLevel; m_file = TFile::Open(meritfile.c_str()); gErrorIgnoreLevel = root_err_level; TFormula::SetMaxima(2000, 2000, 2000); if (m_file == 0) { throw std::runtime_error("Failed to load " + meritfile); } m_tree = dynamic_cast<TTree *>(m_file->Get(tree.c_str())); if (m_tree == 0) { throw std::runtime_error("Failed to load tree '" + tree + "' from file " + meritfile); } // Use TTree::Draw function to apply the filter string and get a // TEventList. Long64_t first(0); Long64_t nmax(m_tree->GetEntries()); Long64_t retcode = m_tree->Draw(">>merit_event_list", filter.c_str(), "", nmax, first); if (retcode == -1) { throw std::runtime_error("ROOT failed to create a TEventList from " + meritfile + " using the TTree::Draw function."); } m_eventList = (TEventList *)gDirectory->Get("merit_event_list"); m_nrows = m_eventList->GetN(); m_tstart = operator[]("EvtElapsedTime"); setEntry(m_nrows - 1); m_tstop = operator[]("EvtElapsedTime"); rewind(); } MeritFile2::MeritFile2(const std::vector<std::string> & meritFiles, const std::string & tree, const std::string & filter) : m_file(0), m_tree(new TChain(tree.c_str())), m_index(0) { /// Vain effort to suppress uninformative error messages from ROOT. /// This is borrowed from tip::RootTable.cxx. long root_err_level = gErrorIgnoreLevel; gErrorIgnoreLevel = root_err_level; for (size_t i(0); i < meritFiles.size(); i++) { dynamic_cast<TChain *>(m_tree)->Add(meritFiles[i].c_str()); } m_tree->SetBranchStatus("*", 1); // Use TTree::Draw function to apply the filter string and get a // TEventList. m_tree->Draw(">>merit_event_list", filter.c_str(), ""); m_eventList = (TEventList *)gDirectory->Get("merit_event_list"); m_nrows = m_eventList->GetN(); m_tstart = operator[]("EvtElapsedTime"); setEntry(m_nrows - 1); m_tstop = operator[]("EvtElapsedTime"); rewind(); } MeritFile2::~MeritFile2() { BranchMap_t::iterator it = m_branches.begin(); for ( ; it != m_branches.end(); ++it) { delete_branch_pointer(it->second); } if (dynamic_cast<TChain *>(m_tree)) { delete m_tree; } delete m_file; } Long64_t MeritFile2::next() { if (m_index < m_nrows) { m_index++; } if (m_index < m_nrows) { setEntry(); } return m_index; } Long64_t MeritFile2::prev() { if (m_index > 0) { m_index--; } if (m_index >= 0) { setEntry(); } return m_index; } Long64_t MeritFile2::rewind() { m_index = 0; setEntry(); return m_index; } void MeritFile2::setEntry() { setEntry(m_index); } void MeritFile2::setEntry(Long64_t index) { Long64_t entry_value = m_eventList->GetEntry(index); if (entry_value == -1) { std::cout << "Missing index error from TEventList::GetEntry " << "for index " << index << std::endl; } Int_t status = m_tree->GetEvent(entry_value); if (status == -1) { std::ostringstream message; message << "MeritFile2::setEntry: " << "TTree::GetEvent == -1 for index " << index << "\n"; throw std::runtime_error(message.str()); } } double MeritFile2::operator[](const std::string & fieldname) { std::string branch_name(fieldname); std::string::size_type pos; int offset(0); if ((pos=fieldname.find_first_of("[")) != std::string::npos) { // Array is being accessed, so cast the substring in the square // brackets to get the element number desired. std::string my_substr(fieldname.substr(pos)); std::string::size_type end_pos(my_substr.find_first_of("]")); if (end_pos == std::string::npos) { throw std::runtime_error("Badly formed column name for merit access: " + fieldname); } offset = std::atoi(my_substr.substr(1, end_pos).c_str()); // Get the recognized branch name for arrays from the leaf name. branch_name = branchName(fieldname.substr(0, pos)); } BranchMap_t::iterator it = m_branches.find(branch_name); if (it == m_branches.end()) { BranchData_t branch_data(get_branch_pointer(branch_name)); m_tree->SetBranchAddress(branch_name.c_str(), branch_data.first); m_branches[branch_name] = branch_data; setEntry(); return recast_as_double(branch_data, offset); } return recast_as_double(it->second, offset); } const std::string & MeritFile2:: branchName(const std::string & truncated_fieldname) { std::map<std::string, std::string>::const_iterator it(m_branchNames.find(truncated_fieldname)); if (it != m_branchNames.end()) { return it->second; } // Find the desired branch name from the TTree and save it. TObjArray * branch_list = m_tree->GetListOfBranches(); Long64_t nbranches = branch_list->GetEntries(); std::string branchname; for (Long64_t i(0); i < nbranches; i++) { branchname = branch_list->At(i)->GetName(); if (branchname.substr(0, truncated_fieldname.size()) == truncated_fieldname) { m_branchNames[truncated_fieldname] = branchname; break; } } return m_branchNames.find(truncated_fieldname)->second; } short int MeritFile2::conversionType() const { double layer(const_cast<MeritFile2 *>(this)->operator[]("Tkr1FirstLayer")); if (17 - layer < 11.5) { return 0; } return 1; } //BranchData_t MeritFile2:: std::pair<void *, std::string> MeritFile2:: get_branch_pointer(const std::string & fieldname) const { std::string leaf_name(fieldname); std::string::size_type pos; if ((pos=fieldname.find_first_of('[')) != std::string::npos) { leaf_name = fieldname.substr(0, pos); } TLeaf * leaf = m_tree->GetLeaf(leaf_name.c_str()); if (!leaf) { throw std::runtime_error("leaf " + leaf_name + " not found."); } void * pointer(0); std::string type(leaf->GetTypeName()); if (type == "Double_t") { pointer = new Double_t; } else if (type == "Float_t") { pointer = new Float_t; } else if (type == "Int_t") { pointer = new Int_t; } else if (type == "UInt_t") { pointer = new UInt_t; } else if (type == "Long_t") { pointer = new Long_t; } else if (type == "ULong_t") { pointer = new ULong_t; } return std::make_pair(pointer, type); } double MeritFile2:: recast_as_double(const BranchData_t & branch_data, int offset) const { if (branch_data.second == "Double_t") { return static_cast<double>(*(reinterpret_cast<Double_t *> (branch_data.first) + offset)); } else if (branch_data.second == "Float_t") { return static_cast<double>(*(reinterpret_cast<Float_t *> (branch_data.first) + offset)); } else if (branch_data.second == "Int_t") { return static_cast<double>(*(reinterpret_cast<Int_t *> (branch_data.first) + offset)); } else if (branch_data.second == "UInt_t") { return static_cast<double>(*(reinterpret_cast<UInt_t *> (branch_data.first) + offset)); } else if (branch_data.second == "Long_t") { return static_cast<double>(*(reinterpret_cast<Long_t *> (branch_data.first) + offset)); } else if (branch_data.second == "ULong_t") { return static_cast<double>(*(reinterpret_cast<ULong_t *> (branch_data.first) + offset)); } } void MeritFile2::delete_branch_pointer(const BranchData_t & branch_data) const { if (branch_data.second == "Double_t") { delete reinterpret_cast<Double_t *>(branch_data.first); } else if (branch_data.second == "Float_t") { delete reinterpret_cast<Float_t *>(branch_data.first); } else if (branch_data.second == "Int_t") { delete reinterpret_cast<Int_t *>(branch_data.first); } else if (branch_data.second == "UInt_t") { delete reinterpret_cast<UInt_t *>(branch_data.first); } else if (branch_data.second == "Long_t") { delete reinterpret_cast<Long_t *>(branch_data.first); } else if (branch_data.second == "ULong_t") { delete reinterpret_cast<ULong_t *>(branch_data.first); } } bool MeritFile2::resetSigHandlers() { if (0 == gSystem) { return false; } gSystem->ResetSignal(kSigBus); gSystem->ResetSignal(kSigSegmentationViolation); gSystem->ResetSignal(kSigSystem); gSystem->ResetSignal(kSigPipe); gSystem->ResetSignal(kSigIllegalInstruction); gSystem->ResetSignal(kSigQuit); gSystem->ResetSignal(kSigInterrupt); gSystem->ResetSignal(kSigWindowChanged); gSystem->ResetSignal(kSigAlarm); gSystem->ResetSignal(kSigChild); gSystem->ResetSignal(kSigUrgent); gSystem->ResetSignal(kSigFloatingException); gSystem->ResetSignal(kSigTermination); gSystem->ResetSignal(kSigUser1); gSystem->ResetSignal(kSigUser2); return true; } } //namespace fitsGen
[ "" ]
e32f91ded45c0eb3f430f03062fae54a857e36a5
d10b69c7ad20400c761053b178a30175d4161332
/Render/RenderMaterial.cpp
8dd460f28c0d105c85e1fabc4b58d31b0bc82488
[]
no_license
epicabsol/aobaker
ceb78a8c1684a1fab9a35afcebdacd68529fb22d
27ee061ff433e2a1956ba3646c1110b7b189186e
refs/heads/master
2020-04-01T05:42:57.015964
2019-10-25T04:29:14
2019-10-25T04:29:14
152,916,648
1
1
null
2018-10-19T23:11:25
2018-10-13T21:38:46
C++
UTF-8
C++
false
false
765
cpp
#include "RenderMaterial.h" RenderTexture** RenderMaterial::GetTextures() const { return this->Textures; } int RenderMaterial::GetTextureCount() const { return this->TextureCount; } RenderShader* RenderMaterial::GetShader() const { return this->Shader; } void RenderMaterial::SetTexture(RenderTexture* const texture, const int& slot) { this->Textures[slot] = texture; } RenderMaterial::RenderMaterial(RenderShader* const shader, RenderTexture** const textures, const int& textureCount) { this->Shader = shader; this->TextureCount = textureCount; this->Textures = new RenderTexture*[this->TextureCount]; for (size_t i = 0; i < this->TextureCount; i++) this->Textures[i] = textures[i]; } RenderMaterial::~RenderMaterial() { delete[] this->Textures; }
f5f64315746d47ba225f10b9e52b26ee2be559ee
fc51258b6b967133a4d419840ac1cd22d0819dfc
/src/edit.cc
064ea7ade91d012469f176b973f9d51b2cfa3f85
[]
no_license
iochoa/GeneComp
414bb0ce0bdcca943f7d0171b78dcecca1bc6eaa
7fbc027207fc49c9983e1c2c29188be3e181f1d0
refs/heads/master
2021-05-08T04:51:05.857214
2017-10-31T20:50:56
2017-10-31T20:50:56
108,455,867
1
0
null
null
null
null
UTF-8
C++
false
false
8,356
cc
#include "edit.h" #include <iostream> #include <vector> #include <iomanip> #include "sam_block.h" #define UINT32_MAX ((uint32_t) - 1) #define INT32_MIN (-0x7fffffff - 1) #define INT32_MAX (0x7fffffffL) #define DEBUG false #define VERIFY false #define STATS false using namespace std; static uint32_t const EDITS = 3; struct entry { int16_t value; int8_t direction; }; vector<vector<uint32_t> > matrix_edits(200, vector<uint32_t>(200)); template <typename T> void print_matrix(vector<vector<T> > matrix) { for (size_t i = 0; i < matrix.size(); i++) { for (size_t j = 0; j < matrix[i].size(); j++) { cout << setw(5) << setfill(' ') << matrix[i][j]; } cout << '\n'; } } static uint32_t min_index(uint32_t *array, uint32_t size) { uint32_t min = UINT32_MAX; uint32_t index = 0; for (uint32_t i = 0; i < size; i++) { if (array[i] < min) { min = array[i]; index = i; } } return index; } static inline uint32_t max_index(vector<int32_t> &array) { int32_t max = INT32_MIN; uint32_t index = 0; for (uint32_t i = 0; i < array.size(); i++) { if (array[i] > max) { max = array[i]; index = i; } } return index; } void init_sequence(struct sequence *seq, uint32_t *Dels, struct ins *Insers, struct snp *SNPs) { seq->n_dels = 0, seq->n_ins = 0, seq->n_snps = 0; seq->Dels = Dels; seq->Insers = Insers; seq->SNPs = SNPs; } static uint32_t edit_dist_helper(char *str1, char *str2, uint32_t s1, uint32_t s2) { for (uint32_t i = 0; i <= s1; i++) { matrix_edits[i][0] = i; } for (uint32_t j = 0; j <= s2; j++) { matrix_edits[0][j] = j; } matrix_edits[0][0] = 0; for (uint32_t i = 1; i <= s1; i++) { for (uint32_t j = 1; j <= s2; j++) { if (str1[i-1] == str2[j-1]) { matrix_edits[i][j] = matrix_edits[i-1][j-1]; } else { matrix_edits[i][j] = min(matrix_edits[i-1][j-1] + 1, min(matrix_edits[i-1][j] + 1, matrix_edits[i][j-1] + 1)); } } } return s2; } // returns the index of the min in the last row static uint32_t asymmetric_edit_dist_helper(char *str1, char *str2, uint32_t s1, uint32_t s2) { uint32_t sub = 1; uint32_t del = 1; uint32_t ins = 1; for (uint32_t i = 0; i <= s1; i++) { matrix_edits[i][0] = i; } for (uint32_t j = 0; j <= s2; j++) { matrix_edits[0][j] = j; } matrix_edits[0][0] = 0; uint32_t index = 0; uint32_t min_value = UINT32_MAX; for (uint32_t i = 1; i <= s1; i++) { for (uint32_t j = 1; j <= s2; j++) { if (str1[i-1] == str2[j-1]) { matrix_edits[i][j] = matrix_edits[i-1][j-1]; } else { matrix_edits[i][j] = min(matrix_edits[i-1][j-1] + sub, min(matrix_edits[i-1][j] + ins, matrix_edits[i][j-1] + del)); } if (i == s1 && matrix_edits[i][j] < min_value) { min_value = matrix_edits[i][j]; index = j; } } } return index; } uint32_t edit_dist(char *str1, char *str2, uint32_t s1, uint32_t s2) { uint32_t dist = edit_dist_helper(str1, str2, s1, s2); return dist; } static void fill_target(char *ref, char *target, int prev_pos, int cur_pos, uint32_t *ref_pos, uint32_t *Dels, uint32_t *dels_pos, uint32_t numDels) { uint32_t ref_start = *ref_pos; if (prev_pos == cur_pos) { return; } while (*dels_pos < numDels && *ref_pos >= Dels[*dels_pos]) { if (DEBUG) printf("DELETE %d\n", Dels[*dels_pos]); (*ref_pos)++; (*dels_pos)++; } for (int i = prev_pos; i < cur_pos; i++) { target[i] = ref[*ref_pos]; (*ref_pos)++; while (*dels_pos < numDels && *ref_pos >= Dels[*dels_pos]) { if (DEBUG) printf("DELETE %d\n", Dels[*dels_pos]); (*ref_pos)++; (*dels_pos)++; } } if (VERIFY) assert(*dels_pos <= numDels); if (DEBUG) printf("MATCH [%d, %d), ref [%d, %d)\n", prev_pos, cur_pos, ref_start, *ref_pos); } void reconstruct_read_from_ops(struct sequence *seq, char *ref, char *target, uint32_t len) { uint32_t start_copy = 0, ref_pos = 0; uint32_t ins_pos = 0, snps_pos = 0, dels_pos = 0; uint32_t numIns = seq->n_ins, numSnps = seq->n_snps, numDels = seq->n_dels; //printf("snps %d, dels %d, ins %d\n", numSnps, numDels, numIns); struct ins *Insers = seq->Insers; struct snp *SNPs = seq->SNPs; uint32_t *Dels = seq->Dels; uint32_t buf[2]; while (numDels > 0 && dels_pos < numDels && ref_pos >= Dels[dels_pos]) { if (DEBUG) printf("DELETE %d\n", Dels[dels_pos]); ref_pos++; dels_pos++; } for (uint32_t i = 0; i < numIns + numSnps; i++) { buf[0] = (ins_pos < numIns) ? Insers[ins_pos].pos : UINT32_MAX; buf[1] = (snps_pos < numSnps) ? SNPs[snps_pos].pos : UINT32_MAX; uint32_t index = min_index(buf, 2); if (index == 0) { fill_target(ref, target, start_copy, Insers[ins_pos].pos, &ref_pos, Dels, &dels_pos, numDels); if (DEBUG) printf("Insert %c at %d\n", basepair2char(Insers[ins_pos].targetChar), Insers[ins_pos].pos); target[Insers[ins_pos].pos] = basepair2char(Insers[ins_pos].targetChar); start_copy = Insers[ins_pos].pos + 1; ins_pos++; } else { fill_target(ref, target, start_copy, SNPs[snps_pos].pos, &ref_pos, Dels, &dels_pos, numDels); if (DEBUG) printf("Replace %c with %c at %d\n", basepair2char(SNPs[snps_pos].refChar), basepair2char(SNPs[snps_pos].targetChar), SNPs[snps_pos].pos); target[SNPs[snps_pos].pos] = basepair2char(SNPs[snps_pos].targetChar); start_copy = SNPs[snps_pos].pos + 1; snps_pos++; ref_pos++; } } fill_target(ref, target, start_copy, len, &ref_pos, Dels, &dels_pos, numDels); if (VERIFY) assert(snps_pos == numSnps); } // sequence transforms str2 into str1 // callee allocates a large enough array (>= sizeof(operation) * max(s1, 22)) // returns number of operations used uint32_t edit_sequence(char *str1, char *str2, uint32_t s1, uint32_t s2, struct sequence &seq) { uint32_t i = s1; uint32_t j = asymmetric_edit_dist_helper(str1, str2, s1, s2); if (DEBUG) cout << "min index: " << j << endl; uint32_t n_dels_tmp = 0, n_ins_tmp = 0, n_snps_tmp = 0; uint32_t Dels_tmp[max(s1,s2)]; struct ins Insers_tmp[max(s1, s2)]; struct snp SNPs_tmp[max(s1, s2)]; uint32_t dist = matrix_edits[i][j]; while (i != 0 || j != 0) { uint32_t edits[EDITS]; edits[0] = (i > 0 && j > 0) ? matrix_edits[i-1][j-1] : UINT32_MAX; // REPLACE edits[1] = (j > 0) ? matrix_edits[i][j-1] : UINT32_MAX; // DELETE edits[2] = (i > 0) ? matrix_edits[i-1][j] : UINT32_MAX; // INSERT uint32_t index = min_index(edits, EDITS); switch (index) { case 0: { if (str1[i-1] != str2[j-1]) { SNPs_tmp[n_snps_tmp].targetChar = char2basepair(str1[i-1]); SNPs_tmp[n_snps_tmp].refChar = char2basepair(str2[j-1]); //printf("Replace %c with %c, Reference: %d, targetPos: %d\n", str2[j-1], str1[i-1], (j-1), (i-1)); SNPs_tmp[n_snps_tmp].pos = i - 1; n_snps_tmp++; } i--; j--; break; } case 1: { Dels_tmp[n_dels_tmp] = j - 1; n_dels_tmp++; j--; break; } case 2: { Insers_tmp[n_ins_tmp].targetChar = char2basepair(str1[i-1]); Insers_tmp[n_ins_tmp].pos = i - 1; n_ins_tmp++; if (VERIFY) assert(isalpha(str1[i-1])); i--; break; } } } seq.n_dels = n_dels_tmp; seq.n_ins = n_ins_tmp; seq.n_snps = n_snps_tmp; for (uint32_t i = 0; i < n_dels_tmp; i++) { seq.Dels[i] = Dels_tmp[n_dels_tmp - i - 1]; } for (uint32_t i = 0; i < n_ins_tmp; i++) { seq.Insers[i] = Insers_tmp[n_ins_tmp - i - 1]; } for (uint32_t i = 0; i < n_snps_tmp; i++) { seq.SNPs[i] = SNPs_tmp[n_snps_tmp - i - 1]; } if (DEBUG || STATS) { printf("%d %d %d\n", n_snps_tmp, n_dels_tmp, n_ins_tmp); } if (VERIFY || DEBUG) { char buf[1024]; reconstruct_read_from_ops(&seq, str2, buf, s1); //assert(edit_dist(str1, buf, s1, s1) == 0); if (DEBUG) printf("Ref: %.100s\nTar: %.100s\nAtt: %.100s\n", str2, str1, buf); //if (DEBUG) printf("Computed dist: %d\n", (int) dist); } return dist; }
91eb1856bee6dcea0216cdfb06fccd4024013959
c3e4456f1b473378d94031239cf7e925760dd346
/src/live_wallpapers/include/live_wallpapers/live_wallpapers.hpp
f7a15c77078835f5e618894398a78a892e030b9a
[]
no_license
winmord/live_wallpaper
5516461d95d58b75783117f17ee3919d7ba678ce
d21bb052a76bce8d2d0ac4d9c822b1639297dfef
refs/heads/master
2022-09-18T03:27:31.063129
2020-06-02T22:15:43
2020-06-02T22:15:43
267,045,771
0
0
null
null
null
null
UTF-8
C++
false
false
732
hpp
#pragma once #include <string> #include <filesystem> namespace live_wallpapers { enum class wallpaper_style { WPSTYLE_CENTER, WPSTYLE_TILE, WPSTYLE_STRETCH, WPSTYLE_KEEPASPECT, WPSTYLE_CROPTOFIT, WPSTYLE_SPAN, WPSTYLE_MAX }; class live_wallpapers { public: live_wallpapers() = default; std::string https_get(std::string const& uri); std::string get_image_from_html(std::string const& html_body); std::string get_image_from_cache(std::string const& wp); void set_wallpapers(std::string const& path); void write_file(std::string const& info); void slide_show(std::string const& path = ".cache", int const& delay = 0); void get_image(std::string const& host, std::string const& path); }; }
9ae08f7db27e988a9ff9843087bc47169a4cdd1c
825395ff6d32cc81ad30ce48253a8601aaaec01d
/src/tests/moveonly.hpp
1802795ab5a4211cb1fcdf40899f304ce48ced89
[ "MIT" ]
permissive
degarashi/spine
4fdd1a00c1561cd81c6c1dc4ec840cdd7e60a1d9
c4de65cfbc6fd27c368b11d2b91153185ac5ba77
refs/heads/master
2020-04-09T20:08:45.867751
2019-09-07T11:41:24
2019-09-07T11:41:26
68,188,948
0
0
null
null
null
null
UTF-8
C++
false
false
2,530
hpp
#pragma once #include "util.hpp" #include <utility> #include <algorithm> #include <cereal/access.hpp> namespace spi { namespace test { //! non-copyableな値 template <class T> class MoveOnly { public: using value_t = T; private: value_t _value; // MoveOnlyがネストされていた場合にget()で一括除去 template <class T2> static const T2& _getValue(const T2& t, ...) { return t; } template <class T3> static decltype(auto) _getValue(const MoveOnly<T3>& t, ...) { return t.getValue(); } public: MoveOnly() = default; MoveOnly(const value_t& v): _value(v) {} MoveOnly(value_t&& v) noexcept: _value(std::move(v)) {} MoveOnly(const MoveOnly&) = delete; MoveOnly(MoveOnly&&) = default; void operator = (const MoveOnly&) = delete; MoveOnly& operator = (MoveOnly&&) = default; decltype(auto) getValue() const { return _getValue(_value, nullptr); } bool operator == (const MoveOnly& m) const noexcept { return getValue() == m.getValue(); } bool operator != (const MoveOnly& m) const noexcept { return !(this->operator == (m)); } bool operator < (const MoveOnly& m) const noexcept { return getValue() < m.getValue(); } bool operator > (const MoveOnly& m) const noexcept { return getValue() > m.getValue(); } bool operator <= (const MoveOnly& m) const noexcept { return getValue() <= m.getValue(); } bool operator >= (const MoveOnly& m) const noexcept { return getValue() >= m.getValue(); } value_t& get() noexcept { return _value; } const value_t& get() const noexcept { return _value; } template <class Ar> void serialize(Ar& ar) { ar(_value); } template <class Ar> static void load_and_construct(Ar& ar, cereal::construct<MoveOnly>& cs) { value_t val; ar(val); cs(val); } }; template <class T> std::ostream& operator << (std::ostream& os, const MoveOnly<T>& m) { return os << m.get(); } template <class T> decltype(auto) Deref_MoveOnly(const MoveOnly<T>& m) { return m.get(); } template <class T> decltype(auto) Deref_MoveOnly(const T& t) { return t; } template <class T> void ModifyValue(MoveOnly<T>& t) { ModifyValue(t.get()); } } } namespace std { template <class T> struct hash<spi::test::MoveOnly<T>> { std::size_t operator()(const spi::test::MoveOnly<T>& m) const noexcept { return std::hash<T>()(m.get()); } }; }
2821dc5ac43c862f7038731089feb9a8f377139e
d630eee8e231aa9d06cae22d0ff8095eb66895ef
/vendor/samsung/packages/apps/SBrowser/src/content/browser/loader/resource_loader.cc
d942879343cc1cedc115788b82145421ca6040d8
[ "BSD-3-Clause" ]
permissive
wangyx0055/gh_note4_platform-4.4.4
f3941560ea0ad737b3ef11b572c00c4ff866eab5
4b5584881021fb80158162288c1ad99f2b8c5134
refs/heads/master
2023-08-31T19:15:20.313492
2017-01-24T08:52:56
2017-01-24T08:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,437
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/loader/resource_loader.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "base/time/time.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/loader/cross_site_resource_handler.h" #include "content/browser/loader/detachable_resource_handler.h" #include "content/browser/loader/resource_loader_delegate.h" #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/ssl/ssl_client_auth_handler.h" #include "content/browser/ssl/ssl_manager.h" #include "content/common/ssl_status_serialization.h" #include "content/public/browser/cert_store.h" #include "content/public/browser/resource_context.h" #include "content/public/browser/resource_dispatcher_host_login_delegate.h" #include "content/public/browser/signed_certificate_timestamp_store.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/resource_response.h" #include "net/base/io_buffer.h" #include "net/base/load_flags.h" #include "net/http/http_response_headers.h" #include "net/ssl/client_cert_store.h" #include "net/url_request/url_request_status.h" #include "webkit/browser/appcache/appcache_interceptor.h" #if !defined(S_UNITTEST_SUPPORT) // SAMSUNG CHANGE: idle connection closing immediately after loading finished. #include "net/url_request/url_request_context.h" #include "net/http/http_network_session.h" #include "net/http/http_transaction_factory.h" // SAMSUNG CHANGE #endif using base::TimeDelta; using base::TimeTicks; namespace content { namespace { void PopulateResourceResponse(net::URLRequest* request, ResourceResponse* response) { response->head.error_code = request->status().error(); response->head.request_time = request->request_time(); response->head.response_time = request->response_time(); response->head.headers = request->response_headers(); request->GetCharset(&response->head.charset); response->head.content_length = request->GetExpectedContentSize(); request->GetMimeType(&response->head.mime_type); net::HttpResponseInfo response_info = request->response_info(); response->head.was_fetched_via_spdy = response_info.was_fetched_via_spdy; response->head.was_npn_negotiated = response_info.was_npn_negotiated; response->head.npn_negotiated_protocol = response_info.npn_negotiated_protocol; response->head.connection_info = response_info.connection_info; response->head.was_fetched_via_proxy = request->was_fetched_via_proxy(); response->head.socket_address = request->GetSocketAddress(); appcache::AppCacheInterceptor::GetExtraResponseInfo( request, &response->head.appcache_id, &response->head.appcache_manifest_url); // TODO(mmenke): Figure out if LOAD_ENABLE_LOAD_TIMING is safe to remove. if (request->load_flags() & net::LOAD_ENABLE_LOAD_TIMING) request->GetLoadTimingInfo(&response->head.load_timing); } } // namespace ResourceLoader::ResourceLoader(scoped_ptr<net::URLRequest> request, scoped_ptr<ResourceHandler> handler, ResourceLoaderDelegate* delegate) : deferred_stage_(DEFERRED_NONE), request_(request.Pass()), handler_(handler.Pass()), delegate_(delegate), last_upload_position_(0), waiting_for_upload_progress_ack_(false), is_transferring_(false), weak_ptr_factory_(this) { request_->set_delegate(this); handler_->SetController(this); } ResourceLoader::~ResourceLoader() { if (login_delegate_.get()) login_delegate_->OnRequestCancelled(); if (ssl_client_auth_handler_.get()) ssl_client_auth_handler_->OnRequestCancelled(); // Run ResourceHandler destructor before we tear-down the rest of our state // as the ResourceHandler may want to inspect the URLRequest and other state. handler_.reset(); } void ResourceLoader::StartRequest() { if (delegate_->HandleExternalProtocol(this, request_->url())) { CancelAndIgnore(); return; } // Give the handler a chance to delay the URLRequest from being started. bool defer_start = false; if (!handler_->OnWillStart(GetRequestInfo()->GetRequestID(), request_->url(), &defer_start)) { Cancel(); return; } #if !defined(S_UNITTEST_SUPPORT) // SAMSUNG CHANGE: logging pending request(timeout: 10s) request_start_time_ = TimeTicks::Now(); // SAMSUNG CHANGE #endif if (defer_start) { deferred_stage_ = DEFERRED_START; } else { StartRequestInternal(); } } void ResourceLoader::CancelRequest(bool from_renderer) { CancelRequestInternal(net::ERR_ABORTED, from_renderer); } void ResourceLoader::CancelAndIgnore() { ResourceRequestInfoImpl* info = GetRequestInfo(); info->set_was_ignored_by_handler(true); CancelRequest(false); } void ResourceLoader::CancelWithError(int error_code) { CancelRequestInternal(error_code, false); } void ResourceLoader::ReportUploadProgress() { ResourceRequestInfoImpl* info = GetRequestInfo(); if (waiting_for_upload_progress_ack_) return; // Send one progress event at a time. net::UploadProgress progress = request_->GetUploadProgress(); if (!progress.size()) return; // Nothing to upload. if (progress.position() == last_upload_position_) return; // No progress made since last time. const uint64 kHalfPercentIncrements = 200; const TimeDelta kOneSecond = TimeDelta::FromMilliseconds(1000); uint64 amt_since_last = progress.position() - last_upload_position_; TimeDelta time_since_last = TimeTicks::Now() - last_upload_ticks_; bool is_finished = (progress.size() == progress.position()); bool enough_new_progress = (amt_since_last > (progress.size() / kHalfPercentIncrements)); bool too_much_time_passed = time_since_last > kOneSecond; if (is_finished || enough_new_progress || too_much_time_passed) { if (request_->load_flags() & net::LOAD_ENABLE_UPLOAD_PROGRESS) { handler_->OnUploadProgress( info->GetRequestID(), progress.position(), progress.size()); waiting_for_upload_progress_ack_ = true; } last_upload_ticks_ = TimeTicks::Now(); last_upload_position_ = progress.position(); } } void ResourceLoader::MarkAsTransferring() { CHECK(ResourceType::IsFrame(GetRequestInfo()->GetResourceType())) << "Can only transfer for navigations"; is_transferring_ = true; } void ResourceLoader::CompleteTransfer() { DCHECK_EQ(DEFERRED_READ, deferred_stage_); is_transferring_ = false; GetRequestInfo()->cross_site_handler()->ResumeResponse(); } ResourceRequestInfoImpl* ResourceLoader::GetRequestInfo() { return ResourceRequestInfoImpl::ForRequest(request_.get()); } void ResourceLoader::ClearLoginDelegate() { login_delegate_ = NULL; } void ResourceLoader::ClearSSLClientAuthHandler() { ssl_client_auth_handler_ = NULL; } void ResourceLoader::OnUploadProgressACK() { waiting_for_upload_progress_ack_ = false; } void ResourceLoader::OnReceivedRedirect(net::URLRequest* unused, const GURL& new_url, bool* defer) { DCHECK_EQ(request_.get(), unused); VLOG(1) << "OnReceivedRedirect: " << request_->url().spec(); DCHECK(request_->status().is_success()); ResourceRequestInfoImpl* info = GetRequestInfo(); if (info->GetProcessType() != PROCESS_TYPE_PLUGIN && !ChildProcessSecurityPolicyImpl::GetInstance()-> CanRequestURL(info->GetChildID(), new_url)) { VLOG(1) << "Denied unauthorized request for " << new_url.possibly_invalid_spec(); // Tell the renderer that this request was disallowed. Cancel(); return; } delegate_->DidReceiveRedirect(this, new_url); if (delegate_->HandleExternalProtocol(this, new_url)) { // The request is complete so we can remove it. CancelAndIgnore(); return; } scoped_refptr<ResourceResponse> response(new ResourceResponse()); PopulateResourceResponse(request_.get(), response.get()); if (!handler_->OnRequestRedirected( info->GetRequestID(), new_url, response.get(), defer)) { Cancel(); } else if (*defer) { deferred_stage_ = DEFERRED_REDIRECT; // Follow redirect when resumed. } } void ResourceLoader::OnAuthRequired(net::URLRequest* unused, net::AuthChallengeInfo* auth_info) { DCHECK_EQ(request_.get(), unused); if (request_->load_flags() & net::LOAD_DO_NOT_PROMPT_FOR_LOGIN) { request_->CancelAuth(); return; } // Create a login dialog on the UI thread to get authentication data, or pull // from cache and continue on the IO thread. DCHECK(!login_delegate_.get()) << "OnAuthRequired called with login_delegate pending"; login_delegate_ = delegate_->CreateLoginDelegate(this, auth_info); if (!login_delegate_.get()) request_->CancelAuth(); } void ResourceLoader::OnCertificateRequested( net::URLRequest* unused, net::SSLCertRequestInfo* cert_info) { DCHECK_EQ(request_.get(), unused); if (request_->load_flags() & net::LOAD_PREFETCH) { request_->Cancel(); return; } DCHECK(!ssl_client_auth_handler_.get()) << "OnCertificateRequested called with ssl_client_auth_handler pending"; ssl_client_auth_handler_ = new SSLClientAuthHandler( GetRequestInfo()->GetContext()->CreateClientCertStore(), request_.get(), cert_info); ssl_client_auth_handler_->SelectCertificate(); } void ResourceLoader::OnSSLCertificateError(net::URLRequest* request, const net::SSLInfo& ssl_info, bool fatal) { ResourceRequestInfoImpl* info = GetRequestInfo(); int render_process_id; int render_frame_id; if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_id)) NOTREACHED(); SSLManager::OnSSLCertificateError( weak_ptr_factory_.GetWeakPtr(), info->GetGlobalRequestID(), info->GetResourceType(), request_->url(), render_process_id, render_frame_id, ssl_info, fatal); } void ResourceLoader::OnBeforeNetworkStart(net::URLRequest* unused, bool* defer) { DCHECK_EQ(request_.get(), unused); // Give the handler a chance to delay the URLRequest from using the network. if (!handler_->OnBeforeNetworkStart( GetRequestInfo()->GetRequestID(), request_->url(), defer)) { Cancel(); return; } else if (*defer) { deferred_stage_ = DEFERRED_NETWORK_START; } } void ResourceLoader::OnResponseStarted(net::URLRequest* unused) { DCHECK_EQ(request_.get(), unused); VLOG(1) << "OnResponseStarted: " << request_->url().spec(); // The CanLoadPage check should take place after any server redirects have // finished, at the point in time that we know a page will commit in the // renderer process. ResourceRequestInfoImpl* info = GetRequestInfo(); ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); if (!policy->CanLoadPage(info->GetChildID(), request_->url(), info->GetResourceType())) { Cancel(); return; } if (!request_->status().is_success()) { ResponseCompleted(); return; } // We want to send a final upload progress message prior to sending the // response complete message even if we're waiting for an ack to to a // previous upload progress message. waiting_for_upload_progress_ack_ = false; ReportUploadProgress(); CompleteResponseStarted(); if (is_deferred()) return; if (request_->status().is_success()) { StartReading(false); // Read the first chunk. } else { ResponseCompleted(); } } void ResourceLoader::OnReadCompleted(net::URLRequest* unused, int bytes_read) { DCHECK_EQ(request_.get(), unused); VLOG(1) << "OnReadCompleted: \"" << request_->url().spec() << "\"" << " bytes_read = " << bytes_read; // bytes_read == -1 always implies an error. if (bytes_read == -1 || !request_->status().is_success()) { ResponseCompleted(); return; } CompleteRead(bytes_read); if (is_deferred()) return; if (request_->status().is_success() && bytes_read > 0) { StartReading(true); // Read the next chunk. } else { ResponseCompleted(); } } void ResourceLoader::CancelSSLRequest(const GlobalRequestID& id, int error, const net::SSLInfo* ssl_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // The request can be NULL if it was cancelled by the renderer (as the // request of the user navigating to a new page from the location bar). if (!request_->is_pending()) return; DVLOG(1) << "CancelSSLRequest() url: " << request_->url().spec(); if (ssl_info) { request_->CancelWithSSLError(error, *ssl_info); } else { request_->CancelWithError(error); } } void ResourceLoader::ContinueSSLRequest(const GlobalRequestID& id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << "ContinueSSLRequest() url: " << request_->url().spec(); request_->ContinueDespiteLastError(); } void ResourceLoader::Resume() { DCHECK(!is_transferring_); DeferredStage stage = deferred_stage_; deferred_stage_ = DEFERRED_NONE; switch (stage) { case DEFERRED_NONE: NOTREACHED(); break; case DEFERRED_START: StartRequestInternal(); break; case DEFERRED_NETWORK_START: request_->ResumeNetworkStart(); break; case DEFERRED_REDIRECT: request_->FollowDeferredRedirect(); break; case DEFERRED_READ: base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceLoader::ResumeReading, weak_ptr_factory_.GetWeakPtr())); break; case DEFERRED_FINISH: // Delay self-destruction since we don't know how we were reached. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceLoader::CallDidFinishLoading, weak_ptr_factory_.GetWeakPtr())); break; } } void ResourceLoader::Cancel() { CancelRequest(false); } void ResourceLoader::StartRequestInternal() { DCHECK(!request_->is_pending()); request_->Start(); delegate_->DidStartRequest(this); } void ResourceLoader::CancelRequestInternal(int error, bool from_renderer) { VLOG(1) << "CancelRequestInternal: " << request_->url().spec(); ResourceRequestInfoImpl* info = GetRequestInfo(); // WebKit will send us a cancel for downloads since it no longer handles // them. In this case, ignore the cancel since we handle downloads in the // browser. if (from_renderer && (info->IsDownload() || info->is_stream())) return; if (from_renderer && info->detachable_handler()) { // TODO(davidben): Fix Blink handling of prefetches so they are not // cancelled on navigate away and end up in the local cache. info->detachable_handler()->Detach(); return; } // TODO(darin): Perhaps we should really be looking to see if the status is // IO_PENDING? bool was_pending = request_->is_pending(); if (login_delegate_.get()) { login_delegate_->OnRequestCancelled(); login_delegate_ = NULL; } if (ssl_client_auth_handler_.get()) { ssl_client_auth_handler_->OnRequestCancelled(); ssl_client_auth_handler_ = NULL; } request_->CancelWithError(error); if (!was_pending) { // If the request isn't in flight, then we won't get an asynchronous // notification from the request, so we have to signal ourselves to finish // this request. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceLoader::ResponseCompleted, weak_ptr_factory_.GetWeakPtr())); } } void ResourceLoader::StoreSignedCertificateTimestamps( const net::SignedCertificateTimestampAndStatusList& sct_list, int process_id, SignedCertificateTimestampIDStatusList* sct_ids) { SignedCertificateTimestampStore* sct_store( SignedCertificateTimestampStore::GetInstance()); for (net::SignedCertificateTimestampAndStatusList::const_iterator iter = sct_list.begin(); iter != sct_list.end(); ++iter) { const int sct_id(sct_store->Store(iter->sct, process_id)); sct_ids->push_back( SignedCertificateTimestampIDAndStatus(sct_id, iter->status)); } } void ResourceLoader::CompleteResponseStarted() { ResourceRequestInfoImpl* info = GetRequestInfo(); scoped_refptr<ResourceResponse> response(new ResourceResponse()); PopulateResourceResponse(request_.get(), response.get()); if (request_->ssl_info().cert.get()) { int cert_id = CertStore::GetInstance()->StoreCert( request_->ssl_info().cert.get(), info->GetChildID()); SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids; StoreSignedCertificateTimestamps( request_->ssl_info().signed_certificate_timestamps, info->GetChildID(), &signed_certificate_timestamp_ids); response->head.security_info = SerializeSecurityInfo( cert_id, request_->ssl_info().cert_status, request_->ssl_info().security_bits, request_->ssl_info().connection_status, signed_certificate_timestamp_ids); } else { // We should not have any SSL state. DCHECK(!request_->ssl_info().cert_status && request_->ssl_info().security_bits == -1 && !request_->ssl_info().connection_status); } delegate_->DidReceiveResponse(this); bool defer = false; if (!handler_->OnResponseStarted( info->GetRequestID(), response.get(), &defer)) { Cancel(); } else if (defer) { read_deferral_start_time_ = base::TimeTicks::Now(); deferred_stage_ = DEFERRED_READ; // Read first chunk when resumed. } } void ResourceLoader::StartReading(bool is_continuation) { int bytes_read = 0; ReadMore(&bytes_read); // If IO is pending, wait for the URLRequest to call OnReadCompleted. if (request_->status().is_io_pending()) return; if (!is_continuation || bytes_read <= 0) { OnReadCompleted(request_.get(), bytes_read); } else { // Else, trigger OnReadCompleted asynchronously to avoid starving the IO // thread in case the URLRequest can provide data synchronously. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceLoader::OnReadCompleted, weak_ptr_factory_.GetWeakPtr(), request_.get(), bytes_read)); } } void ResourceLoader::ResumeReading() { DCHECK(!is_deferred()); if (!read_deferral_start_time_.is_null()) { UMA_HISTOGRAM_TIMES("Net.ResourceLoader.ReadDeferral", base::TimeTicks::Now() - read_deferral_start_time_); read_deferral_start_time_ = base::TimeTicks(); } if (request_->status().is_success()) { StartReading(false); // Read the next chunk (OK to complete synchronously). } else { ResponseCompleted(); } } void ResourceLoader::ReadMore(int* bytes_read) { ResourceRequestInfoImpl* info = GetRequestInfo(); DCHECK(!is_deferred()); // Make sure we track the buffer in at least one place. This ensures it gets // deleted even in the case the request has already finished its job and // doesn't use the buffer. scoped_refptr<net::IOBuffer> buf; int buf_size; if (!handler_->OnWillRead(info->GetRequestID(), &buf, &buf_size, -1)) { Cancel(); return; } DCHECK(buf); DCHECK(buf_size > 0); request_->Read(buf.get(), buf_size, bytes_read); // No need to check the return value here as we'll detect errors by // inspecting the URLRequest's status. } void ResourceLoader::CompleteRead(int bytes_read) { DCHECK(bytes_read >= 0); DCHECK(request_->status().is_success()); ResourceRequestInfoImpl* info = GetRequestInfo(); bool defer = false; if (!handler_->OnReadCompleted(info->GetRequestID(), bytes_read, &defer)) { Cancel(); } else if (defer) { deferred_stage_ = DEFERRED_READ; // Read next chunk when resumed. } } void ResourceLoader::ResponseCompleted() { VLOG(1) << "ResponseCompleted: " << request_->url().spec(); RecordHistograms(); ResourceRequestInfoImpl* info = GetRequestInfo(); std::string security_info; const net::SSLInfo& ssl_info = request_->ssl_info(); if (ssl_info.cert.get() != NULL) { int cert_id = CertStore::GetInstance()->StoreCert(ssl_info.cert.get(), info->GetChildID()); SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids; StoreSignedCertificateTimestamps(ssl_info.signed_certificate_timestamps, info->GetChildID(), &signed_certificate_timestamp_ids); security_info = SerializeSecurityInfo( cert_id, ssl_info.cert_status, ssl_info.security_bits, ssl_info.connection_status, signed_certificate_timestamp_ids); } bool defer = false; handler_->OnResponseCompleted(info->GetRequestID(), request_->status(), security_info, &defer); if (defer) { // The handler is not ready to die yet. We will call DidFinishLoading when // we resume. deferred_stage_ = DEFERRED_FINISH; } else { // This will result in our destruction. CallDidFinishLoading(); } } void ResourceLoader::CallDidFinishLoading() { #if !defined(S_UNITTEST_SUPPORT) // SAMSUNG CHANGE: idle connection closing immediately after loading finished. if(request_->context()->main_frame_load_finished()) { net::HttpNetworkSession* session = request_->context()->http_transaction_factory()->GetSession(); if (session) session ->CloseIdleConnections(); } // SAMSUNG CHANGE #endif delegate_->DidFinishLoading(this); } void ResourceLoader::RecordHistograms() { ResourceRequestInfoImpl* info = GetRequestInfo(); if (info->GetResourceType() == ResourceType::PREFETCH) { PrefetchStatus status = STATUS_UNDEFINED; TimeDelta total_time = base::TimeTicks::Now() - request_->creation_time(); switch (request_->status().status()) { case net::URLRequestStatus::SUCCESS: if (request_->was_cached()) { status = STATUS_SUCCESS_FROM_CACHE; UMA_HISTOGRAM_TIMES("Net.Prefetch.TimeSpentPrefetchingFromCache", total_time); } else { status = STATUS_SUCCESS_FROM_NETWORK; UMA_HISTOGRAM_TIMES("Net.Prefetch.TimeSpentPrefetchingFromNetwork", total_time); } break; case net::URLRequestStatus::CANCELED: status = STATUS_CANCELED; UMA_HISTOGRAM_TIMES("Net.Prefetch.TimeBeforeCancel", total_time); break; case net::URLRequestStatus::IO_PENDING: case net::URLRequestStatus::FAILED: status = STATUS_UNDEFINED; break; } UMA_HISTOGRAM_ENUMERATION("Net.Prefetch.Pattern", status, STATUS_MAX); } } } // namespace content
632051db38be94fe6e2a036c6766a694fd35a563
a01eeb40fc673490f1efb579dc620a9c9caa65b7
/M5Stack-MLX90640-Thermal-Camera.ino
190ea4a1edc1fad105d7c54815b63d71e12a3f9b
[]
no_license
kidkid168/M5Stack-MLX90640-Thermal-Camera
6c09e23ee746cea4ae48f5d0e6c551224cd54c2e
5a5114f86c7b7a58a7397102a124cb75341a9005
refs/heads/master
2020-03-24T18:36:02.649743
2018-06-24T09:30:47
2018-06-24T09:30:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,103
ino
// update 3 :mirror image // reverseScreen=true/false, turn=front camera, false=Selfie /* Read the temperature pixels from the MLX90640 IR array By: Nathan Seidle SparkFun Electronics Date: May 22nd, 2018 License: MIT. See license file for more information but you can basically do whatever you want with this code. Feel like supporting open source hardware? Buy a board from SparkFun! https://www.sparkfun.com/products/14769 This example initializes the MLX90640 and outputs the 768 temperature values from the 768 pixels. This example will work with a Teensy 3.1 and above. The MLX90640 requires some hefty calculations and larger arrays. You will need a microcontroller with 20,000 bytes or more of RAM. This relies on the driver written by Melexis and can be found at: https://github.com/melexis/mlx90640-library Hardware Connections: Connect the SparkFun Qwiic Breadboard Jumper (https://www.sparkfun.com/products/14425) to the Qwiic board Connect the male pins to the Teensy. The pinouts can be found here: https://www.pjrc.com/teensy/pinout.html Open the serial monitor at 9600 baud to see the output */ #include <M5Stack.h> #include <Wire.h> //#include "M5StackUpdater.h" #include "MLX90640_API.h" #include "MLX90640_I2C_Driver.h" const byte MLX90640_address = 0x33; //Default 7-bit unshifted address of the MLX90640 #define TA_SHIFT 8 //Default shift for MLX90640 in open air #define AMG_COLS 32 #define AMG_ROWS 24 float pixelsArraySize = AMG_COLS * AMG_ROWS; //count 1 once float pixels[AMG_COLS * AMG_ROWS]; //# define reversePixels [pixelsArraySize]; float reversePixels[AMG_COLS * AMG_ROWS]; //bool reverseScreen=false; bool reverseScreen=true; #define INTERPOLATED_COLS 16 #define INTERPOLATED_ROWS 16 static float mlx90640To[AMG_COLS * AMG_ROWS]; paramsMLX90640 mlx90640; float signedMag12ToFloat(uint16_t val); //low range of the sensor (this will be blue on the screen) int MINTEMP = 22; int Default_MINTEMP = 20; //high range of the sensor (this will be red on the screen) int MAXTEMP = 32; int Default_MAXTEMP = 32; //the colors we will be using const uint16_t camColors[] = {0x480F, 0x400F, 0x400F, 0x400F, 0x4010, 0x3810, 0x3810, 0x3810, 0x3810, 0x3010, 0x3010, 0x3010, 0x2810, 0x2810, 0x2810, 0x2810, 0x2010, 0x2010, 0x2010, 0x1810, 0x1810, 0x1811, 0x1811, 0x1011, 0x1011, 0x1011, 0x0811, 0x0811, 0x0811, 0x0011, 0x0011, 0x0011, 0x0011, 0x0011, 0x0031, 0x0031, 0x0051, 0x0072, 0x0072, 0x0092, 0x00B2, 0x00B2, 0x00D2, 0x00F2, 0x00F2, 0x0112, 0x0132, 0x0152, 0x0152, 0x0172, 0x0192, 0x0192, 0x01B2, 0x01D2, 0x01F3, 0x01F3, 0x0213, 0x0233, 0x0253, 0x0253, 0x0273, 0x0293, 0x02B3, 0x02D3, 0x02D3, 0x02F3, 0x0313, 0x0333, 0x0333, 0x0353, 0x0373, 0x0394, 0x03B4, 0x03D4, 0x03D4, 0x03F4, 0x0414, 0x0434, 0x0454, 0x0474, 0x0474, 0x0494, 0x04B4, 0x04D4, 0x04F4, 0x0514, 0x0534, 0x0534, 0x0554, 0x0554, 0x0574, 0x0574, 0x0573, 0x0573, 0x0573, 0x0572, 0x0572, 0x0572, 0x0571, 0x0591, 0x0591, 0x0590, 0x0590, 0x058F, 0x058F, 0x058F, 0x058E, 0x05AE, 0x05AE, 0x05AD, 0x05AD, 0x05AD, 0x05AC, 0x05AC, 0x05AB, 0x05CB, 0x05CB, 0x05CA, 0x05CA, 0x05CA, 0x05C9, 0x05C9, 0x05C8, 0x05E8, 0x05E8, 0x05E7, 0x05E7, 0x05E6, 0x05E6, 0x05E6, 0x05E5, 0x05E5, 0x0604, 0x0604, 0x0604, 0x0603, 0x0603, 0x0602, 0x0602, 0x0601, 0x0621, 0x0621, 0x0620, 0x0620, 0x0620, 0x0620, 0x0E20, 0x0E20, 0x0E40, 0x1640, 0x1640, 0x1E40, 0x1E40, 0x2640, 0x2640, 0x2E40, 0x2E60, 0x3660, 0x3660, 0x3E60, 0x3E60, 0x3E60, 0x4660, 0x4660, 0x4E60, 0x4E80, 0x5680, 0x5680, 0x5E80, 0x5E80, 0x6680, 0x6680, 0x6E80, 0x6EA0, 0x76A0, 0x76A0, 0x7EA0, 0x7EA0, 0x86A0, 0x86A0, 0x8EA0, 0x8EC0, 0x96C0, 0x96C0, 0x9EC0, 0x9EC0, 0xA6C0, 0xAEC0, 0xAEC0, 0xB6E0, 0xB6E0, 0xBEE0, 0xBEE0, 0xC6E0, 0xC6E0, 0xCEE0, 0xCEE0, 0xD6E0, 0xD700, 0xDF00, 0xDEE0, 0xDEC0, 0xDEA0, 0xDE80, 0xDE80, 0xE660, 0xE640, 0xE620, 0xE600, 0xE5E0, 0xE5C0, 0xE5A0, 0xE580, 0xE560, 0xE540, 0xE520, 0xE500, 0xE4E0, 0xE4C0, 0xE4A0, 0xE480, 0xE460, 0xEC40, 0xEC20, 0xEC00, 0xEBE0, 0xEBC0, 0xEBA0, 0xEB80, 0xEB60, 0xEB40, 0xEB20, 0xEB00, 0xEAE0, 0xEAC0, 0xEAA0, 0xEA80, 0xEA60, 0xEA40, 0xF220, 0xF200, 0xF1E0, 0xF1C0, 0xF1A0, 0xF180, 0xF160, 0xF140, 0xF100, 0xF0E0, 0xF0C0, 0xF0A0, 0xF080, 0xF060, 0xF040, 0xF020, 0xF800, }; int min_v = -40; int min_cam_v = min_v; int resetMinTemp = min_cam_v +10; int max_v = 300; int max_cam_v = max_v; int resetMaxTemp = max_cam_v -10; float get_point(float *p, uint8_t rows, uint8_t cols, int8_t x, int8_t y); void set_point(float *p, uint8_t rows, uint8_t cols, int8_t x, int8_t y, float f); void get_adjacents_1d(float *src, float *dest, uint8_t rows, uint8_t cols, int8_t x, int8_t y); void get_adjacents_2d(float *src, float *dest, uint8_t rows, uint8_t cols, int8_t x, int8_t y); float cubicInterpolate(float p[], float x); float bicubicInterpolate(float p[], float x, float y); void interpolate_image(float *src, uint8_t src_rows, uint8_t src_cols, float *dest, uint8_t dest_rows, uint8_t dest_cols); int size = sizeof(reversePixels); long loopTime,startTime,endTime,fps; void setup() { M5.begin(); Wire.begin(); /* * //M5StackUpdater if(digitalRead(BUTTON_A_PIN) == 0) { Serial.println("Will Load menu binary"); updateFromFS(SD); ESP.restart(); } */ // Wire.setClock(400000); //Increase I2C clock speed to 400kHz Wire.setClock(600000); //Increase I2C clock speed to 600kHz //Wire.setClock(800000); //Increase I2C clock speed to 800kHz //Serial.begin(9600); Serial.begin(115200); M5.Lcd.begin(); M5.Lcd.setRotation(0); M5.Lcd.fillScreen(TFT_BLACK); M5.Lcd.setTextColor(YELLOW, BLACK); while (!Serial); //Wait for user to open terminal Serial.println("MLX90640 IR Array Example"); M5.Lcd.setTextSize(2); M5.Lcd.drawCentreString("MLX90640 IR Array Example", 60, 4, 1); //Get device parameters - We only have to do this once int status; uint16_t eeMLX90640[832]; status = MLX90640_DumpEE(MLX90640_address, eeMLX90640); if (status != 0) Serial.println("Failed to load system parameters"); status = MLX90640_ExtractParameters(eeMLX90640, &mlx90640); if (status != 0) Serial.println("Parameter extraction failed"); int SetRefreshRate; //Setting MLX90640 device at slave address 0x33 to work with 16Hz refresh rate: // 0x00 – 0.5Hz // 0x01 – 1Hz // 0x02 – 2Hz // 0x03 – 4Hz // 0x04 – 8Hz // OK @ I2C clock speed to 600kHz ~3fps // 0x05 – 16Hz // OK // 0x06 – 32Hz // Fail // 0x07 – 64Hz SetRefreshRate = MLX90640_SetRefreshRate (0x33,0x05); //Once params are extracted, we can release eeMLX90640 array //Display left side colorList and info // M5.Lcd.fillScreen(TFT_BLACK); // int icolor = 255; // for (int irow = 16; irow <= 223; irow++) // { // M5.Lcd.drawRect(0, 0, 35, irow, camColors[icolor]); // icolor--; // } //Display bottom side colorList and info M5.Lcd.fillScreen(TFT_BLACK); int icolor = 0; for (int icol = 0; icol <= 248; icol++) { M5.Lcd.drawRect(36, 208, icol, 284 , camColors[icolor]); icolor++; } infodisplay(); } void loop() { loopTime = millis(); startTime = loopTime; // Serial.print("Loop Start Time: "); // Serial.print(loopTime); /////////////////////////////// // Set Min Value - LongPress // /////////////////////////////// if (M5.BtnA.pressedFor(1000)) { if (MINTEMP <= min_v +10) { MINTEMP = MAXTEMP - 10; } else { MINTEMP = MINTEMP - 10; } infodisplay(); } /////////////////////////////// // Set Min Value - SortPress // /////////////////////////////// if (M5.BtnA.wasPressed()) { if (MINTEMP <= min_cam_v) { MINTEMP = MAXTEMP - 1; } else { MINTEMP--; } infodisplay(); } ///////////////////// // Reset settings // ///////////////////// if (M5.BtnB.wasPressed()) { MINTEMP = max_v - 12; MAXTEMP = max_v - 2; infodisplay(); } //////////////// // Power Off // //////////////// if (M5.BtnB.pressedFor(1000)) { M5.Lcd.fillScreen(TFT_BLACK); M5.Lcd.setTextColor(YELLOW, BLACK); M5.Lcd.drawCentreString("Power Off...", 160, 80, 4); delay(1000); M5.powerOFF(); } /////////////////////////////// // Set Max Value - LongPress // /////////////////////////////// if (M5.BtnC.pressedFor(1000)) { if (MAXTEMP >= resetMaxTemp) { MAXTEMP = MINTEMP + 1; } else { MAXTEMP = MAXTEMP + 10; } infodisplay(); } /////////////////////////////// // Set Max Value - SortPress // /////////////////////////////// if (M5.BtnC.wasPressed()) { if (MAXTEMP >= max_cam_v ) { MAXTEMP = MINTEMP + 1; } else { MAXTEMP++; } infodisplay(); } M5.update(); for (byte x = 0 ; x < 2 ; x++) //Read both subpages { uint16_t mlx90640Frame[834]; int status = MLX90640_GetFrameData(MLX90640_address, mlx90640Frame); if (status < 0) { Serial.print("GetFrame Error: "); Serial.println(status); } float vdd = MLX90640_GetVdd(mlx90640Frame, &mlx90640); float Ta = MLX90640_GetTa(mlx90640Frame, &mlx90640); float tr = Ta - TA_SHIFT; //Reflected temperature based on the sensor ambient temperature float emissivity = 0.95; //MLX90640_CalculateTo(mlx90640Frame, &mlx90640, emissivity, tr, mlx90640To); MLX90640_CalculateTo(mlx90640Frame, &mlx90640, emissivity, tr, pixels); //save pixels temp to array (pixels) } /* for (int x = 0 ; x < 768 ; x++) { if(x % 32 == 0) Serial.println(); //32 values wide Serial.print(pixels[x], 0); //no fractions Serial.print(" "); //space instead of comma // M5.Lcd.fillScreen(TFT_BLACK); // M5.Lcd.setTextColor(YELLOW, BLACK); // M5.Lcd.setCursor(0, 0); // M5.Lcd.setTextSize(1); // M5.Lcd.print(mlx90640To[x], 1); } Serial.println(""); Serial.println(""); //extra line */ //Reverse image (order of Integer array) if (reverseScreen == 1) { for (int x = 0 ; x < pixelsArraySize ; x++) { // Serial.print(String(pixels[x])); // Serial.print(" "); if(x % AMG_COLS == 0) //32 values wide { // Serial.println(": pixels"); //space instead of comma for (int j = 0+x, k = AMG_COLS+x; j < AMG_COLS+x ; j++, k--) { reversePixels[j]=pixels[k]; // Serial.print("j:" + String(j)); //no fractions // Serial.print(" k:" + String(k) + ", "); // if ( j >= AMG_COLS+x ) Serial.println(": reversePixels"); //space instead of comma } } } } //Serial.println("loop done."); float dest_2d[INTERPOLATED_ROWS * INTERPOLATED_COLS]; // * temp stop display image if (reverseScreen == 1) { // ** reversePixels interpolate_image(reversePixels, AMG_ROWS, AMG_COLS, dest_2d, INTERPOLATED_ROWS, INTERPOLATED_COLS); } else { //interpolate_image(float *src, src_rows, src_cols, *dest, dest_rows, dest_cols); interpolate_image(pixels, AMG_ROWS, AMG_COLS, dest_2d, INTERPOLATED_ROWS, INTERPOLATED_COLS); } // uint16_t boxsize = min(M5.Lcd.width() / INTERPOLATED_COLS, M5.Lcd.height() / INTERPOLATED_COLS); uint16_t boxsize = min(M5.Lcd.width() / INTERPOLATED_ROWS, M5.Lcd.height() / INTERPOLATED_COLS); //drawpixels( *p, rows, cols, boxWidth, boxHeight, showVal) // drawpixels(dest_2d, INTERPOLATED_ROWS, INTERPOLATED_COLS, boxsize, boxsize, false); uint16_t boxWidth = M5.Lcd.width() / INTERPOLATED_ROWS; uint16_t boxHeight = (M5.Lcd.height()-31) / INTERPOLATED_COLS; // 31 for bottom info drawpixels(dest_2d, INTERPOLATED_ROWS, INTERPOLATED_COLS, boxWidth, boxHeight, false); max_v = INT_MIN; int spot_v = pixels[28]; // int spot_v = pixels[32*12+6]; for ( int itemp = 0; itemp < sizeof(pixels) / sizeof(pixels[0]); itemp++ ) // for ( int itemp = 0; itemp < (32*24) / sizeof(pixels[0]); itemp++ ) { if ( pixels[itemp] > max_v ) { max_v = pixels[itemp]; //max_i = itemp; } if ( pixels[itemp] < min_v ) { min_v = pixels[itemp]; //max_i = itemp; } } M5.Lcd.setTextSize(2); // M5.Lcd.fillRect(284, 18, 36, 16, TFT_BLACK); // clear max temp text M5.Lcd.fillRect(164, 220, 75, 18, TFT_BLACK); // clear max temp text // M5.Lcd.fillRect(284, 130, 36, 16, TFT_BLACK); // clear spot temp text M5.Lcd.fillRect(85, 220, 90, 18, TFT_BLACK); // clear spot temp text // M5.Lcd.setCursor(284, 18); // update max temp text // M5.Lcd.setCursor(200, 224); // update max temp text M5.Lcd.setCursor(163, 222); // update max temp text with "Max" M5.Lcd.setTextColor(TFT_WHITE); if (max_v > max_cam_v | max_v < min_cam_v) { M5.Lcd.setTextColor(TFT_RED); M5.Lcd.printf("Err", 1); } else { // M5.Lcd.setCursor(284, 0); M5.Lcd.printf("Max", 1); M5.Lcd.print(max_v, 1); M5.Lcd.printf("C" , 1); // M5.Lcd.setCursor(284, 130); // update spot temp text M5.Lcd.drawCircle(95, 230, 6, TFT_WHITE); // update spot icon M5.Lcd.drawLine(95, 221, 95, 239, TFT_WHITE); // vertical line M5.Lcd.drawLine(86, 230, 104, 230, TFT_WHITE); // horizontal line M5.Lcd.setCursor(106, 222); // update spot temp text M5.Lcd.print(spot_v, 1); M5.Lcd.printf("C" , 1); M5.Lcd.drawCircle(160, 120, 6, TFT_WHITE); // update center spot icon M5.Lcd.drawLine(160, 110, 160, 130, TFT_WHITE); M5.Lcd.drawLine(150, 120, 170, 120, TFT_WHITE); } //delay(1000); // Serial.print(", Loop End Time: "); loopTime = millis(); endTime = loopTime; // Serial.print(loopTime); // Serial.print(", "); fps=1000 / (endTime - startTime); M5.Lcd.fillRect(300, 209, 20, 12, TFT_BLACK); //Clear fps text area // Serial.println( String( fps ) +"/fps"); M5.Lcd.setTextSize(1); M5.Lcd.setCursor(284, 210); M5.Lcd.print("fps:"+ String( fps )); M5.Lcd.setTextSize(1); } /***infodisplay()*****/ void infodisplay(void) { M5.Lcd.setTextColor(TFT_WHITE); // M5.Lcd.setCursor(288, 230); // M5.Lcd.printf("Power" , 1); //M5.Lcd.fillRect(0, 0, 36, 16, TFT_BLACK); M5.Lcd.fillRect(284, 223, 320, 240, TFT_BLACK); //Clear MaxTemp area M5.Lcd.setTextSize(2); // M5.Lcd.setCursor(0, 1); // M5.Lcd.fillRect(284, 208, 36, 16, TFT_BLACK); // M5.Lcd.setCursor(284, 208); //show max_cam_v // M5.Lcd.print(max_cam_v , 1); M5.Lcd.setCursor(284, 222); //move to bottom right M5.Lcd.print(MAXTEMP , 1); // update MAXTEMP M5.Lcd.printf("C" , 1); // M5.Lcd.fillRect(0, 208, 36, 16, TFT_BLACK); M5.Lcd.setCursor(0, 208); //show min_cam_v // M5.Lcd.print(min_cam_v , 1); M5.Lcd.print(size , 1); M5.Lcd.setCursor(0, 222); // update MINTEMP text M5.Lcd.fillRect(0, 222, 36, 16, TFT_BLACK); M5.Lcd.print(MINTEMP , 1); M5.Lcd.printf("C" , 1); // M5.Lcd.setCursor(284, 100); M5.Lcd.setCursor(106, 224); // M5.Lcd.printf("Spot", 1); // M5.Lcd.drawCircle(300, 120, 6, TFT_WHITE); // M5.Lcd.drawLine(300, 110, 300, 130, TFT_WHITE); // M5.Lcd.drawLine(290, 120, 310, 120, TFT_WHITE); M5.Lcd.drawCircle(95, 231, 6, TFT_WHITE); // update spot icon M5.Lcd.drawLine(95, 223, 95, 239, TFT_WHITE); M5.Lcd.drawLine(85, 231, 105, 231, TFT_WHITE); } void drawpixels(float *p, uint8_t rows, uint8_t cols, uint8_t boxWidth, uint8_t boxHeight, boolean showVal) { int colorTemp; for (int y = 0; y < rows; y++) { for (int x = 0; x < cols; x++) { float val = get_point(p, rows, cols, x, y); if (val >= MAXTEMP) colorTemp = MAXTEMP; else if (val <= MINTEMP) colorTemp = MINTEMP; else colorTemp = val; uint8_t colorIndex = map(colorTemp, MINTEMP, MAXTEMP, 0, 255); colorIndex = constrain(colorIndex, 0, 255); //draw the pixels! uint16_t color; color = val * 2; // M5.Lcd.fillRect(40 + boxWidth * x, boxHeight * y, boxWidth, boxHeight, camColors[colorIndex]); M5.Lcd.fillRect(boxWidth * x, boxHeight * y, boxWidth, boxHeight, camColors[colorIndex]); } } } //Returns true if the MLX90640 is detected on the I2C bus boolean isConnected() { Wire.beginTransmission((uint8_t)MLX90640_address); if (Wire.endTransmission() != 0) return (false); //Sensor did not ACK return (true); }
1032a24fc0a4e6d026949eb1c6b3bd09950511b7
bf6f17c788522bf51ba6f3317e83b05aeff61e29
/leet61-80/70.ClimbingStairs.cpp
9bd44291f8101f4834225660dc0ef8168d44a4bc
[]
no_license
wshwbluebird/LC16
e73616f8352d0375adc92f2a7dc2b801e994f70c
c099aa90e8c361fdb243e07c630d298edf8f870e
refs/heads/master
2020-04-06T06:55:27.237668
2016-09-03T07:54:28
2016-09-03T07:54:28
65,088,470
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
//// //// Created by wshwbluebird on 16/8/18. //// // //#include <iostream> //using namespace std; // //class Solution { //public: // int climbStairs(int n) { // int dp[n+1]; // dp[0] = 1; // dp[1] = 1; // for (int i = 2; i <= n ; ++i) { // dp[i] = dp[i-1]+dp[i-2]; // } // return dp[n]; // } //}; // // //int main(){ // Solution s; // cout<<s.climbStairs(5); // return 0; //}
e552c2c5d76fc6e1555f2eb68caf7b5c9f6caa6f
be3d301bf8c502bb94149c76cc09f053c532d87a
/include/GafferSceneBindings/SceneAlgoBinding.h
8c12bf8b40eb8b6fa0f4af00065e8d96e4e534d2
[ "BSD-3-Clause" ]
permissive
ljkart/gaffer
28be401d04e05a3c973ef42d29a571aba6407665
d2ce0eb7134a33ceee375d0a3676129a9bdcfbc6
refs/heads/master
2021-01-18T08:30:19.763744
2014-08-10T13:48:10
2014-08-10T13:48:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,086
h
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #ifndef GAFFERSCENEBINDINGS_SCENEALGOBINDING_H #define GAFFERSCENEBINDINGS_SCENEALGOBINDING_H namespace GafferSceneBindings { void bindSceneAlgo(); } // namespace GafferSceneBindings #endif // GAFFERSCENEBINDINGS_SCENEALGOBINDING_H
9e586f61928244f27ed3a76f99cf0ecde85a05f6
488fec9ae3eaeb8c6e2f20a77928fcd510185e98
/matrix.h
ca90854eb53de2597bc7c6a778f055534c0ead83
[]
no_license
Cheetos/CIMAT-RRT
07cb75b9f8c503a463becff292e27f91031d8282
2ba5a92f858fd87b8caa0a686c39ab1d4853ccbe
refs/heads/master
2020-04-01T00:24:21.869794
2018-10-12T04:50:26
2018-10-12T04:50:26
152,695,386
0
0
null
null
null
null
UTF-8
C++
false
false
11,397
h
#ifndef MATRIX_H #define MATRIX_H #include <iostream> #include <iomanip> #include <fstream> #include <cmath> using namespace std; template <class T> class CArray { private: T *data; int size; public: CArray() { data = NULL; size = 0; } CArray(int n) { data = new T[n]; size = n; } T &operator [] (int n) { if(n < 0 || n >= size) throw 1; return data[n]; } }; template <class T> class CMatrix { private: int nRows; int nColumns; CArray<T> *data; public: /****************************************************** * Constructors * *******************************************************/ CMatrix() { data = NULL; nRows = 0; nColumns = 0; } CMatrix(int r, int c) { nRows = r; nColumns = c; data = new CArray<T> [r]; for(int i=0; i<r; i++) data[i] = CArray<T>(c); } /****************************************************** * Constructor by Copy * *******************************************************/ CMatrix(const CMatrix<T> &b) { if(b.nRows > 0 && b.nColumns > 0) { nRows = b.nRows; nColumns = b.nColumns; data = new CArray<T> [b.nRows]; for(int i=0; i<b.nRows; i++) data[i] = CArray<T>(b.nColumns); for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) data[i][j] = b.data[i][j]; } else { data = NULL; nRows = 0; nColumns = 0; } } /****************************************************** * Destructor Definition * *******************************************************/ ~CMatrix() { if(nRows > 0) delete [] data; } /****************************************************** * Operators Definition [] * *******************************************************/ CArray<T> &operator [] (int n) { if(n < 0 || n >= nRows) throw 1; return data[n]; } /****************************************************** * Operators Definition = * *******************************************************/ CMatrix<T> &operator = (const CMatrix<T> &b) { if(nRows > 0) delete [] data; if(b.nRows > 0 && b.nColumns > 0) { nRows = b.nRows; nColumns = b.nColumns; data = new CArray<T> [nRows]; for(int i=0; i<nRows; i++) data[i] = CArray<T>(nColumns); for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) data[i][j] = b.data[i][j]; } else { data = NULL; nRows = 0; nColumns = 0; } return *this; } CMatrix<T> &operator = (const T val) { for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) data[i][j] = val; return *this; } /****************************************************** * Operators Definition +,-,* * *******************************************************/ CMatrix<T> operator + (const CMatrix<T> &b) { if(nRows != b.nRows || nColumns != b.nColumns) return *this; CMatrix<T> temp(nRows,nColumns); for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) temp.data[i][j] = data[i][j] + b.data[i][j]; return temp; } CMatrix<T> operator - (const CMatrix<T> &b) { if(nRows != b.nRows || nColumns != b.nColumns) return *this; CMatrix<T> temp(nRows,nColumns); for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) temp.data[i][j] = data[i][j] - b.data[i][j]; return temp; } CMatrix<T> operator * (const CMatrix<T> &b) { if(nColumns != b.nRows) return *this; CMatrix<T> temp(nRows,b.nColumns); temp = 0; for(int i=0; i<nRows; i++) for(int j=0; j<b.nColumns; j++) for(int k=0; k<nColumns; k++) temp.data[i][j] = temp.data[i][j] + data[i][k] * b.data[k][j]; return temp; } CMatrix<T> operator * (const T val) { CMatrix<T> temp(nRows,nColumns); for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) temp.data[i][j] = data[i][j]*val; return temp; } /****************************************************** * Operators Definition +=,-= * *******************************************************/ CMatrix<T> &operator += (const CMatrix<T> &b) { if(nRows != b.nRows || nColumns != b.nColumns) return *this; for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) data[i][j] = data[i][j] + b.data[i][j]; return *this; } CMatrix<T> &operator -= (const CMatrix<T> &b) { if(nRows != b.nRows || nColumns != b.nColumns) return *this; for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) data[i][j] = data[i][j] - b.data[i][j]; return *this; } /****************************************************** * Operators Definition << * *******************************************************/ friend ostream &operator << (ostream &os, const CMatrix<T> &b) { for(int i=0; i<b.nRows; i++) { for(int j=0; j<b.nColumns; j++) os << setiosflags(ios::fixed) << setw(10) << setprecision(8) << b.data[i][j] << " "; os << endl; } os << endl; return os; } /****************************************************** * Methods Definition * *******************************************************/ void Resize(int r, int c) { if(nRows > 0) delete [] data; nRows = r; nColumns = c; data = new CArray<T> [r]; for(int i=0; i<r; i++) data[i] = CArray<T>(c); } CMatrix<T> Transpose() { CMatrix<T> temp(nColumns,nRows); for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) temp.data[j][i] = data[i][j]; return temp; } CMatrix<T> Inverse() { int r; T max, p; CMatrix<T> B = *this; CMatrix<T> A(nRows,2*nColumns); if(nRows != nColumns) return B; A = 0; for(int i=0; i<nRows; i++) { A.data[i][i+nColumns] = 1; for(int j=0; j<nColumns; j++) A.data[i][j] = data[i][j]; } for(int i=0; i<nRows; i++) { max = A.data[i][i]; r = i; for(int j=i; j<nRows; j++) { if(fabs(A.data[j][i]) > max) { max = fabs(A.data[j][i]); r = j; } } A.Swap_Rows(i,r); for(int j=i; j<2*nColumns; j++) A.data[i][j] = A.data[i][j]/max; for(int j=0; j<nRows; j++) { p = A.data[j][i]; if(i != j) { for(int k=i; k<2*nColumns; k++) { A.data[j][k] = A.data[j][k] - p*A.data[i][k]/A.data[i][i]; if(fabs(A.data[j][k]) < 0.000000001) A.data[j][k] = 0.0; } } } } for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) B.data[i][j] = A.data[i][j+nColumns]; return B; } void Identity() { if(nRows == nColumns) { for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) if(i == j) data[i][j] = 1; else data[i][j] = 0; } } double Infinite_Norm(int &r, int &c) { double max = 0.0; for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) if(fabs(double(data[i][j])) > max) { max = fabs(double(data[i][j])); r = i; c = j; } return max; } double Norm2() { double max = 0.0; for(int i=0; i<nRows; i++) for(int j=0; j<nColumns; j++) max = max + double(data[i][j]) * double(data[i][j]); return sqrt(max); } void Delete_Row(int r) { if(r <= nRows && nRows > 0) { CMatrix<T> temp = *this; delete [] data; data = new CArray<T> [nRows-1]; for(int i=0; i<nRows-1; i++) data[i] = CArray<T>(nColumns); int k = 0; for(int i=0; i<nRows; i++) { if(i == r) continue; for(int j=0; j<nColumns; j++) data[k][j] = temp.data[i][j]; k++; } nRows--; } } void Delete_Column(int c) { if(c <= nColumns && nColumns > 0) { CMatrix<T> temp = *this; delete [] data; data = new CArray<T> [nRows]; for(int i=0; i<nRows; i++) data[i] = CArray<T>(nColumns-1); for(int i=0; i<nRows; i++) { int k = 0; for(int j=0; j<nColumns; j++) { if(j == c) continue; data[i][k++] = temp.data[i][j]; } } nColumns--; } } void Swap_Rows(int r1, int r2) { T temp; if(r1 >= 0 && r1 < nRows && r2 >= 0 && r2 < nRows) { for(int i=0; i<nColumns; i++) { temp = data[r1][i]; data[r1][i] = data[r2][i]; data[r2][i] = temp; } } } int columns() {return nColumns;} int rows() {return nRows;} }; #endif
459295ba4571020a197819cebc65d5005a7e59a7
1e757caafb1bb6a741c78f4973c7293f6ae9e3a3
/CallBackTest.cpp
f63cf91bd76bf4cf6deebe795afd126f15c3f775
[]
no_license
aaa782544811/aaatest
3658b915354e205f09a30042153ff51a59ed1a07
67f6b4021d3307e6148df14645425fe1bb040871
refs/heads/master
2022-09-23T18:25:43.071936
2020-06-05T00:57:19
2020-06-05T00:57:19
269,497,124
0
0
null
null
null
null
GB18030
C++
false
false
2,418
cpp
// CallBackTest.cpp : 定义应用程序的类行为。 // #include "stdafx.h" #include "CallBackTest.h" #include "CallBackTestDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CCallBackTestApp BEGIN_MESSAGE_MAP(CCallBackTestApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CCallBackTestApp 构造 CCallBackTestApp::CCallBackTestApp() { // 支持重新启动管理器 m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: 在此处添加构造代码, // 将所有重要的初始化放置在 InitInstance 中 } // 唯一的一个 CCallBackTestApp 对象 CCallBackTestApp theApp; // CCallBackTestApp 初始化 BOOL CCallBackTestApp::InitInstance() { // 如果一个运行在 Windows XP 上的应用程序清单指定要 // 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式, //则需要 InitCommonControlsEx()。否则,将无法创建窗口。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 将它设置为包括所有要在应用程序中使用的 // 公共控件类。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // 创建 shell 管理器,以防对话框包含 // 任何 shell 树视图控件或 shell 列表视图控件。 CShellManager *pShellManager = new CShellManager; // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("应用程序向导生成的本地应用程序")); CCallBackTestDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: 在此放置处理何时用 // “确定”来关闭对话框的代码 } else if (nResponse == IDCANCEL) { // TODO: 在此放置处理何时用 // “取消”来关闭对话框的代码 } // 删除上面创建的 shell 管理器。 if (pShellManager != NULL) { delete pShellManager; } // 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序, // 而不是启动应用程序的消息泵。 return FALSE; }
27fd038cd39adf30712b6f430f15341ac1c10e97
728e57a80995d7be98d46295b780d0b433c9e62a
/src/dictionary/user_dictionary_util.h
09215eacecccd0b07182e57fb21124607201e6c9
[ "Apache-2.0", "MIT", "BSD-3-Clause", "GPL-1.0-or-later" ]
permissive
SNQ-2001/Mozc-for-iOS
7936bfd9ff024faacfd2d96af3ec15a2000378a1
45b0856ed8a22d5fa6b4471548389cbde4abcf10
refs/heads/master
2023-03-17T22:19:15.843107
2014-10-04T05:48:29
2014-10-04T05:48:42
574,371,060
0
0
Apache-2.0
2022-12-05T06:48:07
2022-12-05T06:48:06
null
UTF-8
C++
false
false
7,688
h
// Copyright 2010-2014, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // UserDicUtil provides various utility functions related to the user // dictionary. #ifndef MOZC_DICTIONARY_USER_DICTIONARY_UTIL_H_ #define MOZC_DICTIONARY_USER_DICTIONARY_UTIL_H_ #include <string> #include <vector> #include "base/port.h" #include "dictionary/user_dictionary_storage.pb.h" namespace mozc { class UserPOSInterface; // TODO(hidehiko): Move this class into user_dictionary namespace. class UserDictionaryUtil { public: // Following methods return limits of dictionary/entry size. static size_t max_dictionary_size(); static size_t max_entry_size(); // Returns true if all characters in the given string is a legitimate // character for reading. static bool IsValidReading(const string &reading); // Performs varirous kinds of character normalization such as // katakana-> hiragana and full-width ascii -> half width // ascii. Identity of reading of a word should be defined by the // output of this function. static void NormalizeReading(const string &input, string *output); // Returns true if all fields of the given data is properly set and // have a legitimate value. It checks for an empty string, an // invalid character and so on. If the function returns false, we // shouldn't accept the data being passed into the dictionary. // TODO(hidehikoo): Replace this method by the following ValidateEntry. static bool IsValidEntry( const UserPOSInterface &user_pos, const user_dictionary::UserDictionary::Entry &entry); // Returns the error status of the validity for the given entry. // The validation process is as follows: // - Checks the reading // - if it isn't empty // - if it doesn't exceed the max length // - if it doesn't contain invalid character // - Checks the word // - if it isn't empty // - if it doesn't exceed the max length // - if it doesn't contain invalid character // - Checks the comment // - if it isn't exceed the max length // - if it doesn't contain invalid character // - Checks if a valid pos type is set. static user_dictionary::UserDictionaryCommandStatus::Status ValidateEntry( const user_dictionary::UserDictionary::Entry &entry); // Sanitizes a dictionary entry so that it's acceptable to the // class. A user of the class may want this function to make sure an // error want happen before calling AddEntry() and other // methods. Return true if the entry is changed. static bool SanitizeEntry(user_dictionary::UserDictionary::Entry *entry); // Helper function for SanitizeEntry // "max_size" is the maximum allowed size of str. If str size exceeds // "max_size", remaining part is truncated by this function. static bool Sanitize(string *str, size_t max_size); // Returns the error status of the validity for the given dictionary name. static user_dictionary::UserDictionaryCommandStatus::Status ValidateDictionaryName(const user_dictionary::UserDictionaryStorage &storage, const string &dictionary_name); // Returns true if the given storage hits the limit for the number of // dictionaries. static bool IsStorageFull( const user_dictionary::UserDictionaryStorage &storage); // Returns true if the given dictionary hits the limit for the number of // entries. static bool IsDictionaryFull( const user_dictionary::UserDictionary &dictionary); // Returns UserDictionary with the given id, or NULL if not found. static const user_dictionary::UserDictionary *GetUserDictionaryById( const user_dictionary::UserDictionaryStorage &storage, uint64 dictionary_id); static user_dictionary::UserDictionary *GetMutableUserDictionaryById( user_dictionary::UserDictionaryStorage *storage, uint64 dictionary_id); // Returns the index of the dictionary with the given dictionary_id // in the storage, or -1 if not found. static int GetUserDictionaryIndexById( const user_dictionary::UserDictionaryStorage &storage, uint64 dictionary_id); // Returns the file name of UserDictionary. static string GetUserDictionaryFileName(); // Returns the string representation of PosType, or NULL if the given // pos is invalid. // For historicall reason, the pos was represented in Japanese characters. static const char* GetStringPosType( user_dictionary::UserDictionary::PosType pos_type); // Returns the string representation of PosType, or NULL if the given // pos is invalid. static user_dictionary::UserDictionary::PosType ToPosType( const char *string_pos_type); // Tries to resolve the unknown fields in UserDictionary. // This is introduced for the change of protobuf refactoring. static bool ResolveUnknownFieldSet( user_dictionary::UserDictionaryStorage *storage); // To keep a way to re-install old stable version (1.5 or earlier), // we temporarily fill the legacy (deprecated) pos field in string format // on desktop version. static void FillDesktopDeprecatedPosField( user_dictionary::UserDictionaryStorage *storage); // Generates a new dictionary id, i.e. id which is not in the storage. static uint64 CreateNewDictionaryId( const user_dictionary::UserDictionaryStorage &storage); // Creates dictionary with the given name. static user_dictionary::UserDictionaryCommandStatus::Status CreateDictionary( user_dictionary::UserDictionaryStorage *storage, const string &dictionary_name, uint64 *new_dictionary_id); // Deletes dictionary specified by the given dictionary_id. // If the deleted_dictionary is not NULL, the pointer to the // delete dictionary is stored into it. In other words, // caller has responsibility to actual deletion of the instance. // Returns true if succeeded, otherwise false. static bool DeleteDictionary( user_dictionary::UserDictionaryStorage *storage, uint64 dictionary_id, int *original_index, user_dictionary::UserDictionary **deleted_dictionary); private: DISALLOW_IMPLICIT_CONSTRUCTORS(UserDictionaryUtil); }; } // namespace mozc #endif // MOZC_DICTIONARY_USER_DICTIONARY_UTIL_H_
fd2f98f69fcef88e50cdab12e607138cafe6a642
7c9842e9cbd879d4d06d64c17eb1a62167673504
/GLFWtest/LightSpot.cpp
340200b625e0d643709352e5e383f7a875523609
[]
no_license
hkzhch/GLFWtest
928b4b2a4e47a8466fce92119632894e4ab93e71
0dc86f060b7e8a076b325f42c0d1eec45af1cd78
refs/heads/master
2022-12-15T10:08:10.447279
2020-09-09T04:14:53
2020-09-09T04:14:53
294,000,426
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
#include "LightSpot.h" LightSpot::LightSpot(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color) : position(_position), angles(_angles), color(_color) { UpdateDirection(); } void LightSpot::UpdateDirection() { direction = glm::vec3(0.0f, 0.0f, 1.0f); direction = glm::rotateZ(direction, angles.z); direction = glm::rotateY(direction, angles.y); direction = glm::rotateX(direction, angles.x); direction = -1.0f * direction; }
[ "c-zhang@GLASGOW" ]
c-zhang@GLASGOW
a5dbb66f575f7b0d68c8c9fcf93204f246decefa
1f3019ccf04713f4c0be87a883d38e5720225525
/mp5/quadtree.h
7d0b03818c4b9817f1f3cb5ced1247616617de3e
[]
no_license
liuruoqian/CS225
8aabdc199e0e95ff7410ded1e43fa701eb4bcb86
f4df5ad4c7808d4ebce604d7eb48484318abd081
refs/heads/master
2021-01-09T05:46:33.096739
2017-02-12T22:29:04
2017-02-12T22:29:04
80,801,209
0
1
null
2017-02-12T20:33:20
2017-02-03T05:49:21
null
UTF-8
C++
false
false
2,608
h
/** * @file quadtree.h * Quadtree class definition. * @date Spring 2008 */ #ifndef QUADTREE_H #define QUADTREE_H #include "png.h" /** * A tree structure that is used to compress PNG images. */ class Quadtree { public: Quadtree(); /**< The Quadtree default constructor */ /**<The Quadtree constructor given source image, and resolution */ Quadtree(PNG const & source, int resolution); ~Quadtree(); Quadtree const & operator=(Quadtree const & other); Quadtree(Quadtree const & other); void buildTree(PNG const & source, int resolution); /**< A function to build QuadTree*/ RGBAPixel getPixel(int x, int y) const; PNG decompress() const; // mp5.2 functions: void clockwiseRotate(); void prune(int tolerance); int pruneSize(int tolerance)const; int idealPrune(int numLeaves)const; private: /** * A simple class representing a single node of a Quadtree. * You may want to add to this class; in particular, it could * probably use a constructor or two... */ class QuadtreeNode { public: QuadtreeNode* nwChild; /**< pointer to northwest child */ QuadtreeNode* neChild; /**< pointer to northeast child */ QuadtreeNode* swChild; /**< pointer to southwest child */ QuadtreeNode* seChild; /**< pointer to southeast child */ RGBAPixel element; /**< the pixel stored as this node's "data" */ }; QuadtreeNode* root; /**< pointer to root of quadtree */ int resol; /**< remember the resolution */ /** * A helper function of buildTree. */ QuadtreeNode * buildTree_helper(PNG const & source, int d, int upleftX, int upleftY); void clearSub(QuadtreeNode * &subRoot); /**< clear subtree given a pointer to the subroot */ void clear(); /**< helper function for destructor */ QuadtreeNode * copy(QuadtreeNode * const & subRoot); //RGBAPixel getpixel(QuadtreeNode* temp, int x, int y, int i) const; QuadtreeNode * help_getPixel(int x, int y, int d, QuadtreeNode * subRoot) const; void Rotate_helper(QuadtreeNode * subRoot); void prune_helper(int tolerance, QuadtreeNode * subRoot); bool Prunable(QuadtreeNode * rootN, QuadtreeNode * leaf, int tolerance) const; int pruneSize_helper(QuadtreeNode * subRoot, int tolerance, int count) const; int idealPrune_helper(int numLeaves, int maxTol, int minTol) const; /**** Functions for testing/grading ****/ /**** Do not remove this line or copy its contents here! ****/ #include "quadtree_given.h" }; #endif
fbcc86b111512fa2b068ad1128f4af6ba990427b
6c7cfedb2a354d0da1118ee1660503f6827c9193
/HalfAdder.cpp
284c6ed80ae0b7f50a55ad24451160e52aad7cab
[]
no_license
Akhil423/GreenBits
2fa242f1ab18346d5c499f6105cd3de69dfe128d
5b1bb9a4a944412231b4b5bff154e1f1e4ab833f
refs/heads/master
2021-01-21T16:32:12.673347
2017-10-13T10:27:30
2017-10-13T10:27:30
95,407,811
0
0
null
null
null
null
UTF-8
C++
false
false
302
cpp
#include<iostream> using namespace std; int fun(int c,int d){ int sum,ca; while(d!=0){ sum=c^d; ca=c&d; c=sum; d=ca<<1; cout<<d; } return sum; } int main(){ int a,b; cin>>a>>b; int sum=fun(a,b); cout<<sum; return 0; }
b60132fbac7b0cad2fadfcf7615b3da91ffe88ba
4eaeb089f4ce242217618be337cf6272ee9ddaf5
/PatCodeRepo/PatBasic/Basic1090.cpp
be2b5ff21b2fb03955853d1e7ebab8f6f8ad9117
[]
no_license
luyiming112233/PatCodeRepo
dc45d57659fdfed4bf230e3a13dd731ccbe2bf20
2b8c4363b363563738bd9c63171ed51c9af32f84
refs/heads/master
2020-06-27T16:53:27.702734
2019-09-09T00:57:26
2019-09-09T00:57:26
200,001,771
1
0
null
null
null
null
GB18030
C++
false
false
795
cpp
#include<cstdio> #include<vector> using namespace std; #define ssize 100010 #define gsize 1010 int main() { vector<vector<int> > v(ssize); int N, M, K,a,b,thing[ssize],G[gsize]; bool OK; scanf("%d %d", &N, &M); for (int i = 0; i < N; i++) { scanf("%d %d", &a, &b); v[a].push_back(b); v[b].push_back(a); } for (int i = 0; i < M; i++) { scanf("%d", &K); for (int k = 0; k < K; k++) scanf("%d", &G[k]); //初始化thing数组 for (int t = 0; t < ssize; t++) thing[t] = 0; OK = true; for(int k=0;k<K&&OK;k++){ //说明该物品不冲突 if (thing[G[k]] == 0) { //新增冲突编号 for (int c = 0; c < v[G[k]].size(); c++) thing[v[G[k]][c]] = 1; } else { OK = false; } } if (OK) printf("Yes\n"); else printf("No\n"); } }
962a1615ed539ded89efdcbb04cc5b22e17a6385
12bde528e9fdae91a3eb29048761946afdd9c393
/Chapter 09/CAPTCHA/main.cpp
0630887b633053ea37a01c76d3d31322aaaf5f0e
[]
no_license
alvarohenriquecz/Algorithms_C-Plus-Plus_Part1
9b58aa497b63c65d9be55d0a6642c109f86c32d9
4f0db1fb8dd4cef8c800952bcad862f0bc53a802
refs/heads/master
2022-11-14T08:39:41.954377
2020-07-04T03:25:21
2020-07-04T03:25:21
274,179,658
0
0
null
null
null
null
UTF-8
C++
false
false
559
cpp
#include <iostream> #include <ctime> using namespace std; string GenerateCaptcha(int n) { time_t t; srand((unsigned) time(&t)); //all characters char * chrs = "аbсdеfghіjklmnорԛrѕtuvwxуzABCDEFGHI" "JKLMNOPQRSTUVWXYZ0123456789"; // Generate n characters from above set and // add these characters to captch. string captcha = ""; while(n--) captcha.push_back(chrs[rand() % 62]); return captcha; } int main() { cout << "CAPTCHA" << endl; cout << GenerateCaptcha(10) << endl; return 0; }
e3eead3333d97a0c3eb09f0542131cc3f8dc761c
9d0c1da53da9e60d4a891d7edb7a02c31c8d26b9
/kdgantt/KDGanttXMLTools.h
f375c4d0765b4a0a1d327bddfadac1a4935bc9bd
[]
no_license
serghei/kde3-kdepim
7e6d4a0188c35a2c9c17babd317bfe3c0f1377d2
a1980f1560de118f19f54a5eff5bae87a6aa4784
refs/heads/master
2021-01-17T10:03:14.624954
2018-11-04T21:31:00
2018-11-04T21:31:00
3,688,187
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,725
h
/* -*- Mode: C++ -*- $Id: KDGanttXMLTools.h 367698 2004-12-01 19:34:06Z mueller $ KDGantt - a multi-platform charting engine */ /**************************************************************************** ** Copyright (C) 2002-2004 Klarälvdalens Datakonsult AB. All rights reserved. ** ** This file is part of the KDGantt library. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid commercial KDGantt licenses may use this file in ** accordance with the KDGantt Commercial License Agreement provided with ** the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.klaralvdalens-datakonsult.se/Public/products/ for ** information about KDGantt Commercial License Agreements. ** ** Contact [email protected] if any conditions of this ** licensing are not clear to you. ** ** As a special exception, permission is given to link this program ** with any edition of Qt, and distribute the resulting executable, ** without including the source code for Qt in the source distribution. ** **********************************************************************/ #ifndef __KDGANTTXMLTOOLS_H__ #define __KDGANTTXMLTOOLS_H__ #include <qpen.h> #include <qdom.h> #include <qstring.h> #include <qcolor.h> #include <qrect.h> #include <qfont.h> #include <qstringlist.h> #include <qdatetime.h> namespace KDGanttXML { QString penStyleToString(Qt::PenStyle style); Qt::PenStyle stringToPenStyle(const QString &style); QString brushStyleToString(Qt::BrushStyle style); Qt::BrushStyle stringToBrushStyle(const QString &style); void createBoolNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, bool value); void createSizeNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QSize &value); void createIntNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, int value); void createDoubleNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, double value); void createStringNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QString &text); void createColorNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QColor &color); void createBrushNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QBrush &brush); void createPixmapNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QPixmap &pixmap); void createRectNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QRect &rect); void createStringListNodes(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QStringList *list); void createFontNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QFont &font); void createPenNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QPen &pen); void createDateTimeNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QDateTime &datetime); void createDateNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QDate &date); void createTimeNode(QDomDocument &doc, QDomNode &parent, const QString &elementName, const QTime &time); bool readIntNode(const QDomElement &element, int &value); bool readStringNode(const QDomElement &element, QString &value); bool readDoubleNode(const QDomElement &element, double &value); bool readBoolNode(const QDomElement &element, bool &value); bool readColorNode(const QDomElement &element, QColor &value); bool readBrushNode(const QDomElement &element, QBrush &brush); bool readPixmapNode(const QDomElement &element, QPixmap &pixmap); bool readRectNode(const QDomElement &element, QRect &value); bool readFontNode(const QDomElement &element, QFont &font); bool readPenNode(const QDomElement &element, QPen &pen); bool readDateTimeNode(const QDomElement &element, QDateTime &datetime); bool readDateNode(const QDomElement &element, QDate &date); bool readTimeNode(const QDomElement &element, QTime &time); } #endif
4c07ec1884c38760d7d7db3e38df11040c1797f2
557f5a9d48392ef804705aad3edc8e170064ac0c
/support.cpp
a5128a23b1caa032d9fbc5aac3fded8266a9700c
[]
no_license
yknnnnft/cppstudy
bdf9097e22ca5210f1c54ff76003b47d1993102c
d8e58e1da7be56e6983c1e65109f4f7c625a963a
refs/heads/master
2021-01-19T10:56:20.788297
2017-04-19T09:19:25
2017-04-19T09:19:25
87,917,605
0
0
null
null
null
null
UTF-8
C++
false
false
129
cpp
#include <iostream> extern int count; void write_extern(void) { std::cout << "count is: " << count << std::endl; }
53627ac92de15e0b595108aef92fe7afd6bff7df
845e3e104ec4af1476f082f070e5aee7e55f53ee
/ChiaVaTri/SoFibonaciThuN.cpp
74396c6854b209518a6bab9a4abb3cc12bbd9e0e
[]
no_license
hoangnv2810/Algorithm
96000ede09269adb0ac8d8fa598b158997fd4286
cdc5c7708e63f12ed01a84b3de4fec7585b5070a
refs/heads/main
2023-08-23T08:44:07.510186
2021-09-28T13:19:35
2021-09-28T13:19:35
411,252,789
0
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
#include<bits/stdc++.h> using namespace std; const long long mod = 1e9+7; void Mul(long long x[2][2], long long y[2][2], long long a[2][2]){ long long temp[2][2]; for(int i = 0; i < 2; i++){ for(int j = 0; j < 2; j++){ long long res = 0; for(int k = 0; k < 2; k++){ res += (x[i][k]*y[k][j])%mod; res %= mod; } temp[i][j] = res; } } for(int i = 0; i < 2; i++){ for(int j = 0; j < 2; j++){ a[i][j] = temp[i][j]; } } } void Pow(long long a[2][2], long long b[2][2], int k){ if(k <= 1) return; Pow(a, b, k/2); Mul(a, a, a); if(k%2 != 0) Mul(a, b, a); } int main(){ int t; cin >> t; while(t--){ int n; cin >> n; long long a[2][2] = {{1,1},{1,0}}, b[2][2] = {{1,1},{1,0}}; Pow(a, b, n-1); cout << a[0][0] << endl; } }
15e6290733f53a48038fef467274692959497b44
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/CEF3/cef_source/libcef_dll/ctocpp/zip_reader_ctocpp.h
42ddcd8e092a5c12287c443f868963d881a1c0eb
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
1,677
h
// Copyright (c) 2017 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // #ifndef CEF_LIBCEF_DLL_CTOCPP_ZIP_READER_CTOCPP_H_ #define CEF_LIBCEF_DLL_CTOCPP_ZIP_READER_CTOCPP_H_ #pragma once #if !defined(WRAPPING_CEF_SHARED) #error This file can be included wrapper-side only #endif #include "include/cef_zip_reader.h" #include "include/capi/cef_zip_reader_capi.h" #include "libcef_dll/ctocpp/ctocpp_ref_counted.h" // Wrap a C structure with a C++ class. // This class may be instantiated and accessed wrapper-side only. class CefZipReaderCToCpp : public CefCToCppRefCounted<CefZipReaderCToCpp, CefZipReader, cef_zip_reader_t> { public: CefZipReaderCToCpp(); // CefZipReader methods. bool MoveToFirstFile() OVERRIDE; bool MoveToNextFile() OVERRIDE; bool MoveToFile(const CefString& fileName, bool caseSensitive) OVERRIDE; bool Close() OVERRIDE; CefString GetFileName() OVERRIDE; int64 GetFileSize() OVERRIDE; CefTime GetFileLastModified() OVERRIDE; bool OpenFile(const CefString& password) OVERRIDE; bool CloseFile() OVERRIDE; int ReadFile(void* buffer, size_t bufferSize) OVERRIDE; int64 Tell() OVERRIDE; bool Eof() OVERRIDE; }; #endif // CEF_LIBCEF_DLL_CTOCPP_ZIP_READER_CTOCPP_H_
b0a0d13cfddbc3fd234c99cf2e4752d6ca7ded05
0d0e78c6262417fb1dff53901c6087b29fe260a0
/live/src/v20180801/model/DeleteLiveWatermarkRequest.cpp
98c89d3c4baeadc71804d23ac67f015331a7dc1f
[ "Apache-2.0" ]
permissive
li5ch/tencentcloud-sdk-cpp
ae35ffb0c36773fd28e1b1a58d11755682ade2ee
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
refs/heads/master
2022-12-04T15:33:08.729850
2020-07-20T00:52:24
2020-07-20T00:52:24
281,135,686
1
0
Apache-2.0
2020-07-20T14:14:47
2020-07-20T14:14:46
null
UTF-8
C++
false
false
1,937
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/live/v20180801/model/DeleteLiveWatermarkRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Live::V20180801::Model; using namespace rapidjson; using namespace std; DeleteLiveWatermarkRequest::DeleteLiveWatermarkRequest() : m_watermarkIdHasBeenSet(false) { } string DeleteLiveWatermarkRequest::ToJsonString() const { Document d; d.SetObject(); Document::AllocatorType& allocator = d.GetAllocator(); if (m_watermarkIdHasBeenSet) { Value iKey(kStringType); string key = "WatermarkId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_watermarkId, allocator); } StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } int64_t DeleteLiveWatermarkRequest::GetWatermarkId() const { return m_watermarkId; } void DeleteLiveWatermarkRequest::SetWatermarkId(const int64_t& _watermarkId) { m_watermarkId = _watermarkId; m_watermarkIdHasBeenSet = true; } bool DeleteLiveWatermarkRequest::WatermarkIdHasBeenSet() const { return m_watermarkIdHasBeenSet; }
39cdc14cd274e8dc8abb0bbbc5a66741848b405b
faeca7997c9bae0ee9c3597e42b27a96f37f5dbe
/Chapter10/Ch10_Exc08/Ch10_Exc08.cpp
596d907c6c67beeb192fdfab5f16af7401ba11d8
[]
no_license
dimpellos/Cplusplus_Primer_-
c726898c5699a349eb3158c724d2734fe4a3ae2b
756cb1684ea62d9217f769e8e49984da1db37972
refs/heads/master
2020-07-25T21:49:03.229883
2019-10-18T12:35:36
2019-10-18T12:35:36
208,430,960
1
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include <iostream> #include "list.h" void addage(Item& item); int main() { List l; Item i = { "shaolinngjiang", 24 }; l.additem(i); int n; n = l.itemcount(); std::cout << n << " items in list" << std::endl; l.visit(addage); std::cout << "Chapter 10 Excercise 8.\n"; return 0; } void addage(Item& item) { item.age += 1; return; }
975d505738bba091bb865c30db3a96ab09e6da58
982f80970ddfd1ad2b9aa94eef5b065c00984e30
/DirectionalLight.h
631f6a0534a4a7fbdd9010ed1e2563424bea9b58
[]
no_license
AbuBakr62/TheLabyrinth
bf5b4420bee02ffa944a0fb4b1f82ecbbcb5411e
045cc06c11d1d954bf6c1990ca2e2a076068436d
refs/heads/main
2023-03-01T16:45:53.201494
2021-02-08T12:07:04
2021-02-08T12:07:04
337,063,381
1
0
null
null
null
null
UTF-8
C++
false
false
612
h
#pragma once #include "Common.h" #include "Light.h" namespace Library { class DirectionalLight : public Light { RTTI_DECLARATIONS(DirectionalLight, Light) public: DirectionalLight(Game& game); virtual ~DirectionalLight(); const XMFLOAT3& Direction() const; const XMFLOAT3& Up() const; const XMFLOAT3& Right() const; XMVECTOR DirectionVector() const; XMVECTOR UpVector() const; XMVECTOR RightVector() const; void ApplyRotation(CXMMATRIX transform); void ApplyRotation(const XMFLOAT4X4& transform); protected: XMFLOAT3 mDirection; XMFLOAT3 mUp; XMFLOAT3 mRight; }; }
d00290d606343d2a95fd9d55a904de18a6a44c57
ee6603006365082c68dd7c58c0cd441577b09c87
/firmware/src/train.h
bcac9099dc9706652f993be5dc5b9704ad65998f
[]
no_license
pete-j-turnbull/anpr-gate-cam
2595b1e0d579eb7183242b4938ef50ce2c4379ba
6c7e731c0eff25dc4af226a6a645e38c31c74d41
refs/heads/master
2022-11-09T13:13:24.748088
2020-06-26T01:39:00
2020-06-26T01:39:00
258,886,441
0
0
null
null
null
null
UTF-8
C++
false
false
2,728
h
#ifndef TRAIN_H #define TRAIN_H #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/core.hpp> #include <opencv2/ml.hpp> #include "feature.h" #include "utils.h" #include <iostream> using namespace cv; using namespace std; using namespace cv::ml; bool train(string save_path, string train_path) { const int number_of_class = 35; const int number_of_sample = 1; const int number_of_feature = 32; Ptr<SVM> svm = SVM::create(); svm->setType(SVM::C_SVC); svm->setKernel(SVM::LINEAR); svm->setGamma(0.5); svm->setC(16); svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6)); vector<string> folders = list_folder(train_path); if (folders.size() <= 0) { return false; } if (number_of_class != folders.size() || number_of_sample <= 0 || number_of_class <= 0) { return false; } Mat src; Mat data = Mat(number_of_sample * number_of_class * 6, number_of_feature, CV_32FC1); Mat label = Mat(number_of_sample * number_of_class * 6, 1, CV_32SC1); int index = 0; sort(folders.begin(), folders.end()); for (size_t i = 0; i < folders.size(); ++i) { vector<string> files = list_file(folders.at(i)); if (files.size() <= 0 || files.size() != number_of_sample) return false; string folder_path = folders.at(i); cout << "list folder" << folders.at(i) << endl; string label_folder = folder_path.substr(folder_path.length() - 1); for (size_t j = 0; j < files.size(); ++j) { src = imread(files.at(j)); if (src.empty()) { return false; } vector<float> feature = calculate_feature(src); for (size_t t = 0; t < feature.size(); ++t) { data.at<float>(index * 6, t) = feature.at(t); data.at<float>(index * 6 + 1, t) = feature.at(t); data.at<float>(index * 6 + 2, t) = feature.at(t); data.at<float>(index * 6 + 3, t) = feature.at(t); data.at<float>(index * 6 + 4, t) = feature.at(t); data.at<float>(index * 6 + 5, t) = feature.at(t); } label.at<int>(index * 6, 0) = i; label.at<int>(index * 6 + 1, 0) = i; label.at<int>(index * 6 + 2, 0) = i; label.at<int>(index * 6 + 3, 0) = i; label.at<int>(index * 6 + 4, 0) = i; label.at<int>(index * 6 + 5, 0) = i; index++; } } // SVM Train OpenCV 3.1 svm->trainAuto(ml::TrainData::create(data, ml::ROW_SAMPLE, label)); svm->save(save_path); return true; } #endif
689c3f3fa0adacc05b9df8421270ebf24c22f86a
90aa2c05707787660b3fc69d5f3fd36dfea5dde4
/C++98/idioms/sfinae.cpp
bfa8c468a31d44d3d1a7e9963c6647b5b06a4433
[]
no_license
Olvv/Cpp
36fad81746f0adc9eb968ac1925de52ca9a65bd8
53d8f6831216b59d82f34c68eb82e509708ce31c
refs/heads/master
2023-01-09T19:05:15.446745
2020-11-12T17:41:08
2020-11-12T17:41:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,410
cpp
/* * References: * * [wikipedia] Substitution failure is not an error * http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error * * [20191104alhadi] Substitution Failure is Error and Not An Error * https://medium.com/@MKahsari/sfinae-step-by-step-67e6ef6154da * * [20180518boccara] How to Make SFINAE Pretty – Part 2: the Hidden Beauty of SFINAE * https://www.fluentcpp.com/2018/05/18/make-sfinae-pretty-2-hidden-beauty-sfinae/ * * [20180515boccara] How to Make SFINAE Pretty - Part 1: What SFINAE Brings to Code * https://www.fluentcpp.com/2018/05/15/make-sfinae-pretty-1-what-value-sfinae-brings-to-code/ * * [warzecha20171110] An inspiring introduction to Templatemetaprogramming. * https://youtu.be/UnIc_qJ0DRc?t=19m43s * * [filipek20160225] SFINAE Followup * http://www.bfilipek.com/2016/02/sfinae-followup.html * * [filipek20160218] Notes on C++ SFINAE * http://www.bfilipek.com/2016/02/notes-on-c-sfinae.html * * [mueller20151130] Controlling overload resolution #4: SFINAE * https://foonathan.github.io/blog/2015/11/30/overload-resolution-4.html * * [guegant20151031] An introduction to C++'s SFINAE concept: compile-time introspection of a class member * http://jguegant.github.io/blogs/tech/sfinae-introduction.html * * [watt20150127] C++: SFINAE * http://codeofthedamned.com/index.php/sfinae */
3716c52ff0b9975779e67eb24f9ad9a76fcd9c2b
033e1e353d1ff07c8680e0be7c83081906f4fcdb
/RideTheFlow/src/math/Vector3.cpp
ea15981a10777449ddc6b4b70715041a08d4d732
[]
no_license
KataSin/KozinKataoka
572d897cdb777b241a2848ff18c691c7f10d7d31
1b15b3a12364e34561c042f3b97b99d9a4482852
refs/heads/master
2021-01-11T18:21:41.396200
2017-07-06T15:00:10
2017-07-06T15:00:10
69,627,602
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
7,164
cpp
#include "Vector3.h" #include "Math.h" #include <cmath> #include <sstream> Vector3 Vector3::Zero = Vector3(0, 0, 0); Vector3 Vector3::One = Vector3(1, 1, 1); Vector3 Vector3::Up = Vector3(0, 1, 0); Vector3 Vector3::Down = Vector3(0, -1, 0); Vector3 Vector3::Right = Vector3(1, 0, 0); Vector3 Vector3::Left = Vector3(-1, 0, 0); Vector3 Vector3::Forward = Vector3(0, 0, -1); Vector3 Vector3::Backward = Vector3(0, 0, 1); Vector3 Vector3::White = Vector3(255, 255, 255); Vector3 Vector3::Black = Vector3(0, 0, 0); Vector3 Vector3::Blue = Vector3(0, 0, 255); Vector3 Vector3::Red = Vector3(255, 0, 0); Vector3 Vector3::Green = Vector3(0, 255, 0); Vector3::Vector3() : x(0), y(0), z(0) { } Vector3::Vector3(float s) : x(s), y(s), z(s) { } Vector3::Vector3(float x, float y) : x(x), y(y), z(0) { } Vector3::Vector3(float x, float y, float z) : x(x), y(y), z(z) { } Vector3::Vector3(int s) : x((float)s), y((float)s), z((float)s) { } Vector3::Vector3(int x, int y) : x((float)x), y((float)y), z((float)0) { } Vector3::Vector3(int x, int y, int z) : x((float)x), y((float)y), z((float)z) { } Vector3::Vector3(const Vector3& vector) : x(vector.x), y(vector.y), z(vector.z) { } Vector3::Vector3(const VECTOR& vector) : x(vector.x), y(vector.y), z(vector.z) { } float Vector3::Length() const { return sqrt(x * x + y * y + z * z); } void Vector3::Normalize() { float result = Length(); if (result != 0.0f) { (*this) /= result; } } Vector3 Vector3::Normalized() const { return Vector3::Normalize(Vector3(x, y, z)); } float Vector3::Length(const Vector3& v) { return sqrt(v.x * v.x + v.y * v.y + v.z * v.z); } float Vector3::Distance(const Vector3& v1, const Vector3& v2) { return (v2 - v1).Length(); } Vector3 Vector3::Normalize(const Vector3& v) { Vector3 result = v; result.Normalize(); return result; } float Vector3::Dot(const Vector3& v1, const Vector3& v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } Vector3 Vector3::Cross(const Vector3& v1, const Vector3& v2) { return Vector3(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x); } float Vector3::Inner(const Vector3& v1, const Vector3& v2) { return Math::Degree(acosf(Dot(Normalize(v1), Normalize(v2)))); } Vector3 Vector3::FrontVec(Vector3& position, Vector3& rotate) { // 原点を設定 Vector3 origin = position; // オブジェクトの位置を設定 Vector3 point = position + Forward; // 中心を原点に移動 Vector3 center = point - origin; // キャラクターの回転量からcossinを割り出す float rotate_cos = cos(-Math::Radian(rotate.y)); float rotate_sin = sin(-Math::Radian(rotate.y)); // 原点を中心に回転 Vector3 front = Vector3( center.x * rotate_cos - center.z * rotate_sin, 0.0f, center.x * rotate_sin + center.z * rotate_cos ); // 原点から戻す front += origin; return front - position; } // 二つのベクトル間の線形補間をする Vector3 Vector3::Lerp(const Vector3& start, const Vector3& end, float amount) { if (amount < 0.0f) { amount = 0.0f; } else if (amount > 1.0f) { amount = 1.0f; } return start * (1.0f - amount) + end * amount; } // バネの力を加える void Vector3::Spring( Vector3& position, Vector3& velocity, const Vector3& restPosition, float stiffness, float friction, float mass ) { // バネの伸び具合を計算 Vector3 stretch = (position - restPosition); // バネの力を計算 Vector3 force = -stiffness * stretch; // 加速度を追加 Vector3 acceleration = force / mass; // 移動速度を計算 velocity = friction * (velocity + acceleration); // 座標の更新 position += velocity; } float Vector3::Pitch(const Vector3& front) { float l = Length(front); if (l == 0) return 0.0f; float y = front.y / l; return Math::Asin(Math::Degree(-y)); } float Vector3::Yaw(const Vector3& front) { if (Length(front) == 0){ return 0.0f; } return Math::Atan(front.x, front.z); } Vector3 Vector3::Direction(const Vector3& start, const Vector3& end) { return Normalize(end - start); } float Vector3::GetAngle2D(const Vector3 & pos1, const Vector3 & pos2) { return Math::Degree(Math::Atan2(pos2.z - pos1.z, pos2.x - pos1.x)); } VECTOR Vector3::ToVECTOR(const Vector3& v) { VECTOR result; result.x = v.x; result.y = v.y; result.z = v.z; return result; } VECTOR Vector3::ToVECTOR() const { return ToVECTOR(*this); } DWORD Vector3::ToColor(const Vector3& v) { DWORD result; result = GetColor((int)v.x, (int)v.y, (int)v.z); return result; } DWORD Vector3::ToColor() const { return ToColor(*this); } Vector3& Vector3::operator = (const VECTOR& v){ x = v.x; y = v.y; z = v.z; return *this; } Vector3& Vector3::operator = (const Vector3& v) { x = v.x; y = v.y; z = v.z; return *this; } Vector3::operator std::string() const { std::stringstream ss; ss << "(" << x << " , " << y << " , " << z << ")"; return ss.str(); } Vector3::operator VECTOR() const{ return VGet((float)x, (float)y, (float)z); } Vector3 operator + (const Vector3& v1, const Vector3& v2) { Vector3 result; result.x = v1.x + v2.x; result.y = v1.y + v2.y; result.z = v1.z + v2.z; return result; } Vector3& operator += (Vector3& v1, const Vector3& v2) { v1.x += v2.x; v1.y += v2.y; v1.z += v2.z; return v1; } Vector3 operator - (const Vector3& v1, const Vector3& v2) { Vector3 result; result.x = v1.x - v2.x; result.y = v1.y - v2.y; result.z = v1.z - v2.z; return result; } Vector3& operator -= (Vector3& v1, const Vector3& v2) { v1.x -= v2.x; v1.y -= v2.y; v1.z -= v2.z; return v1; } Vector3 operator * (const Vector3& v, const float f) { Vector3 result; result.x = v.x * f; result.y = v.y * f; result.z = v.z * f; return result; } Vector3 operator * (const float f, const Vector3& v) { Vector3 result; result.x = v.x * f; result.y = v.y * f; result.z = v.z * f; return result; } Vector3 operator * (const Vector3& v1, const Vector3& v2) { Vector3 result; result.x = v1.x * v2.x; result.y = v1.y * v2.y; result.z = v1.z * v2.z; return result; } Vector3& operator *= (Vector3& v, const float f) { v.x = v.x * f; v.y = v.y * f; v.z = v.z * f; return v; } Vector3& operator *= (const float f, Vector3& v) { v.x = v.x * f; v.y = v.y * f; v.z = v.z * f; return v; } Vector3 operator / (const Vector3& v, const float f) { Vector3 result; result.x = v.x / f; result.y = v.y / f; result.z = v.z / f; return result; } Vector3 operator / (const float f, const Vector3& v) { Vector3 result; result.x = v.x / f; result.y = v.y / f; result.z = v.z / f; return result; } Vector3 operator / (const Vector3& v1, const Vector3& v2) { Vector3 result; result.x = v1.x / v2.x; result.y = v1.y / v2.y; result.z = v1.z / v2.z; return result; } Vector3& operator /= (Vector3& v, const float f) { v.x = v.x / f; v.y = v.y / f; v.z = v.z / f; return v; } Vector3 operator - (const Vector3& v) { Vector3 result = v; result.x = -v.x; result.y = -v.y; result.z = -v.z; return result; } bool operator != (const Vector3& v1, const Vector3& v2) { return ((int)v1.x == (int)v2.x) && ((int)v1.y == (int)v2.y) && ((int)v1.z == (int)v2.z); }
415a2fa28d2da569e6fa440a468d55261c1be308
b61c99eb76422623fdfff5d5cfb01b1d95afc4bf
/mini-server v2.0/EventLoop.cpp
aed197d6abe0fe7f634c580554a64dfface6f902
[]
no_license
Jaiss123/Myserver-mini
0b943d84573985da6452355002280f8b424bd031
d3296d22cf63095b73ff9b70227af5894d0348b6
refs/heads/master
2020-06-08T06:48:36.526359
2019-07-08T09:34:24
2019-07-08T09:34:24
193,180,269
1
0
null
null
null
null
UTF-8
C++
false
false
3,009
cpp
#include <sys/eventfd.h> #include "EventLoop.h" #include "Channel.h" #include "Epoll.h" #include "TimerQueue.h" #include "Timestamp.h" #include "Task.h" #include "CurrentThread.h" #include <iostream> using namespace std; EventLoop::EventLoop() :_quit(false) ,_callingPendingFunctors(false) ,_pPoller(new Epoll()) // Memory Leak !!! ,_threadId(CurrentThread::tid()) ,_pTimerQueue(new TimerQueue(this)) // Memory Leak!!! { _eventfd = createEventfd(); _pEventfdChannel = new Channel(this, _eventfd); // Memory Leak !!! _pEventfdChannel->setCallback(this); _pEventfdChannel->enableReading(); } EventLoop::~EventLoop() {} void EventLoop::loop() { while(!_quit) { vector<Channel*> channels; _pPoller->poll(&channels); vector<Channel*>::iterator it; for(it = channels.begin(); it != channels.end(); ++it) { (*it)->handleEvent(); } doPendingFunctors(); } } void EventLoop::update(Channel* pChannel) { _pPoller->update(pChannel); } void EventLoop::queueInLoop(Task& task) { { MutexLockGuard guard(_mutex); _pendingFunctors.push_back(task); } if(!isInLoopThread() || _callingPendingFunctors) { wakeup(); } } void EventLoop::runInLoop(Task& task) { if(isInLoopThread()) { task.doTask(); } else { queueInLoop(task); } } void EventLoop::wakeup() { uint64_t one = 1; ssize_t n = ::write(_eventfd, &one, sizeof one); if (n != sizeof one) { cout << "EventLoop::wakeup() writes " << n << " bytes instead of 8" << endl; } } int EventLoop::createEventfd() { int evtfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if (evtfd < 0) { cout << "Failed in eventfd" << endl; } return evtfd; } void EventLoop::handleRead() { uint64_t one = 1; ssize_t n = ::read(_eventfd, &one, sizeof one); if (n != sizeof one) { cout << "EventEventLoop::handleRead() reads " << n << " bytes instead of 8" << endl; } } void EventLoop::handleWrite() {} void EventLoop::doPendingFunctors() { vector<Task> tempRuns; _callingPendingFunctors = true; { MutexLockGuard guard(_mutex); tempRuns.swap(_pendingFunctors); } vector<Task>::iterator it; for(it = tempRuns.begin(); it != tempRuns.end(); ++it) { it->doTask(); } _callingPendingFunctors = false; } int EventLoop::runAt(Timestamp when, IRun0* pRun) { return _pTimerQueue->addTimer(pRun, when, 0.0); } int EventLoop::runAfter(double delay, IRun0* pRun) { return _pTimerQueue->addTimer(pRun, Timestamp::nowAfter(delay), 0.0); } int EventLoop::runEvery(double interval, IRun0* pRun) { return _pTimerQueue->addTimer(pRun, Timestamp::nowAfter(interval), interval); } void EventLoop::cancelTimer(int timerId) { _pTimerQueue->cancelTimer(timerId); } bool EventLoop::isInLoopThread() { return _threadId == CurrentThread::tid(); }
f4e378bd654999398471096dcce40f2bff5b7389
dcc0edb1da8ce822da2a43aa7ba5de7743e8c75c
/CapaLogica/FachadaLogica.cpp
e1d612e2c576c37c1d1000686fa5640136bbfc82
[]
no_license
mtorresdemello/ObligatorioP4
72a6ae48398cbf06e78569444f7d1116c9fca5fb
abbe22521ec61aa4e5b331978aa02a023f7b248a
refs/heads/master
2020-05-18T03:46:15.632907
2019-04-29T22:44:59
2019-04-29T22:44:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,892
cpp
#include "FachadaLogica.h" FachadaLogica::FachadaLogica() { Brujas DiccioBrujasDelSistema = Brujas(); } void FachadaLogica::R1_AltaBruSup(Bruja * nuevaSuprema, bool &hayError1){ //hayError1 = La bruja (suprema) a ingresar ya existe? hayError1 = false; if (DiccioBrujasDelSistema.Member(nuevaSuprema->getIdentificador())) hayError1 = true; else DiccioBrujasDelSistema.Insert(nuevaSuprema); } //precondicion: los id deben ser distintos void FachadaLogica::R2_AltaBruCom(String idBrujaSuprema, Comun * nuevaComun, bool &hayError1, bool &hayError2){ //hayError1 = La bruja suprema no existe (y es suprema) //hayError2 = La bruja (comun) a ingresar ya existe hayError1 = false; hayError2 = false; if (!DiccioBrujasDelSistema.EstaRegistradaEstaBrujaSuprema(idBrujaSuprema)) hayError1 = true; else { if (DiccioBrujasDelSistema.Member(nuevaComun->getIdentificador())) hayError2 = true; else { nuevaComun->setSuprema((Suprema *)DiccioBrujasDelSistema.Find(idBrujaSuprema)); DiccioBrujasDelSistema.Insert(nuevaComun); } } } void FachadaLogica::R3_ListTodasLasBrujas(IteradorBrujas &iB, bool &hayError1){ //hayError1 = No Hay alguna bruja hayError1 = false; if (!DiccioBrujasDelSistema.HayAlgunaBruja()) hayError1 = true; else { DiccioBrujasDelSistema.GetAllBrujas(iB); } } void FachadaLogica::R4_ListUnaBru(String idBrujaAretornar, Bruja * &brujaARetornar, IteradorHechizos &iH, bool &hayError1){ //hayError1 = La bruja no existe hayError1 = false; if (!DiccioBrujasDelSistema.Member(idBrujaAretornar) ) { hayError1 = true; } else { brujaARetornar = DiccioBrujasDelSistema.Find(idBrujaAretornar); bool tieneAlgunHechizo = brujaARetornar->TieneAlgunHechizo(); if (tieneAlgunHechizo == true) { iH = IteradorHechizos(); iH = brujaARetornar->getHechizos().CargarIteradorH(); } } } void FachadaLogica::R5_ListBrujasSupsMay(IteradorBrujas &iB, bool &hayError1){ //hayError1 = No Hay alguna bruja suprema hayError1 = false; if (!DiccioBrujasDelSistema.HayAlgunaBrujaSuprema()) hayError1 = true; else { iB = IteradorBrujas(); ////// iB = DiccioBrujasDelSistema.GetBrujasMayores(); iB.Insertar(DiccioBrujasDelSistema.GetBrujaSupremaMayor()); } } void FachadaLogica::R6_AltaHechi(String idBrujaACargarle, Hechizo * hACargarle, bool &hayError1, bool &hayError2){ //hayError1 = La bruja no existe //hayError2 = No Se le puede cargar un hechizo a esta bruja hayError1 = false; hayError2 = false; if (!DiccioBrujasDelSistema.Member(idBrujaACargarle)) hayError1 = true; else { if (DiccioBrujasDelSistema.Find(idBrujaACargarle)->getHechizos().Largo() == 20) hayError2 = true; else { int nextID = DiccioBrujasDelSistema.Find(idBrujaACargarle)->getHechizos().Largo(); // nextID++; hACargarle->setNumero(nextID); DiccioBrujasDelSistema.Find(idBrujaACargarle)->setNewHechizo(hACargarle); // DiccioBrujasDelSistema.Find(idBrujaACargarle)->getHechizos().Insertar(hACargarle); } } } void FachadaLogica::R7_ListHechi(String idBrujaABuscarle, int idHechizoEncontradoARetornar, Hechizo * &hARetornar, bool &hayError1, bool &hayError2){ //hayError1 = La bruja no existe //hayError2 = La bruja no tiene ese hechizo hayError1 = false; hayError2 = false; if (!DiccioBrujasDelSistema.Member(idBrujaABuscarle)) hayError1 = true; else { // if (!DiccioBrujasDelSistema.Find(idBrujaABuscarle)->getHechizos().ExisteEsteHechizo(idHechizoEncontradoARetornar) ) // fflush(stdin); if (!DiccioBrujasDelSistema.Find(idBrujaABuscarle)->TieneEsteHechizo(idHechizoEncontradoARetornar-1)) hayError2 = true; else hARetornar = DiccioBrujasDelSistema.Find(idBrujaABuscarle)->getHechizos().K_esimo(idHechizoEncontradoARetornar-1); } } void FachadaLogica::R8_CantHechiComYEspe(String idBrujaAContarle, int &cantHComunes, int &cantHEspeciales, bool &hayError1, bool &hayError2){ //hayError1 = La bruja no existe //hayError2 = La bruja no tiene algun hechizo hayError1 = false; hayError2 = false; if (!DiccioBrujasDelSistema.Member(idBrujaAContarle)) hayError1 = true; else { if ( DiccioBrujasDelSistema.Find(idBrujaAContarle)->getHechizos().EsVacia() ) hayError2 = true; else DiccioBrujasDelSistema.Find(idBrujaAContarle)->getHechizos().CantidadHechizosByTipo(cantHComunes, cantHEspeciales); } }
d3832d90c6bf934e7ddd7d01c4961436eb6883c7
5fef0c812a535c1a7597bb6e1f976a36f92a5484
/138. 复制带随机指针的链表.cpp
9bfec187747719f4e8f476db84ae26af0a6285b4
[]
no_license
hzh0/LeetCode
c18ca70782365f21eccc1914f3c96d78ec7a0709
884b1e1412999819e5280f3008fe10a9ebc12bca
refs/heads/master
2023-03-12T03:15:03.302125
2021-02-25T11:12:43
2021-02-25T11:12:43
306,652,491
2
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
/* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { public: Node* copyRandomList(Node* head) { if (head == nullptr) return nullptr; auto p = head; while (p != nullptr) { auto q = new Node(p->val); q->next = p->next; p->next = q; p = p->next->next; } p = head; while (p != nullptr) { if (p->random != nullptr) p->next->random = p->random->next; else p->next->random = nullptr; p = p->next->next; } p = head; auto q = head->next; auto ans = q; while (p != nullptr) { p->next = p->next->next; if (q->next != nullptr) q->next = q->next->next; else q->next = nullptr; p = p->next; q = q->next; } return ans; } };
ca89cba60c45fd52df4e6bb8df7b51945b4624fb
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/public/internal/com/inc/ilgwrta.h
2ba12129521177b3b19814e0eae7a8c52a2b0437
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
2,117
h
// Copyright (C) 1995-1999 Microsoft Corporation. All rights reserved. // ----------------------------------------------------------------------- // Microsoft Distributed Transaction Coordinator (Microsoft Confidential) // @doc // @module ILOGWRTA.H | Header for interface <i ILogWriteAsynch>.<nl><nl> // Usage:<nl> // Clients of this DLL require this file. // @rev 0 | 06/02/95 | rbarnes | Cloned: For LOGMGR.DLL // ----------------------------------------------------------------------- #ifndef _ILGWRTA_H # define _ILGWRTA_H // =============================== // INCLUDES: // =============================== #include <objbase.h> #include "logrec.h" // logmgr general types class CAsynchSupport; //forward class declaration // =============================== // INTERFACE: ILogWriteAsynch // =============================== // TODO: In the interface comments, update the description. // TODO: In the interface comments, update the usage. // ----------------------------------------------------------------------- // @interface ILogWriteAsynch | See also <c CILogWriteAsynch>.<nl><nl> // Description:<nl> // Provide append functionality<nl><nl> // Usage:<nl> // Useless, but for an example. // ----------------------------------------------------------------------- DECLARE_INTERFACE_ (ILogWriteAsynch, IUnknown) { // @comm IUnknown methods: See <c CILogWriteAsynch>. STDMETHOD (QueryInterface) (THIS_ REFIID i_riid, LPVOID FAR* o_ppv) PURE; STDMETHOD_ (ULONG, AddRef) (THIS) PURE; STDMETHOD_ (ULONG, Release) (THIS) PURE; // @comm ILogWriteAsynch methods: See <c CILogWriteAsynch>. STDMETHOD (Init) (ULONG cbMaxOutstandingWrites) PURE; STDMETHOD (AppendAsynch) (LOGREC* lgrLogRecord, LRP* plrpLRP, CAsynchSupport* pCAsynchSupport,BOOL fFlushHint,ULONG* pulAvailableSpace) PURE; STDMETHOD (SetCheckpoint) (LRP lrpLatestCheckpoint,CAsynchSupport* pCAsynchSupport, LRP* plrpCheckpointLogged) PURE; }; #endif _ILGWRTA_H
32562ec1a13bc7801868f7f916de202908f44c99
0852bf2f1357f4d8fd5bcdef15b0f6b60b8a31aa
/src/compat/glibc_compat.cpp
db96e0758eefff42c9b38e2d035ee15e2d442fd9
[ "MIT" ]
permissive
CoinBuild/gdc
cd59e47febdd477653acca75dda9458337420ca1
dc294039205746cf66aaef6655bc032a3bda1bfd
refs/heads/master
2020-03-18T16:38:08.463099
2018-04-24T16:29:35
2018-04-24T16:29:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
828
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/gdc-config.h" #endif #include <cstddef> #if defined(HAVE_SYS_SELECT_H) #include <sys/select.h> #endif // Prior to GLIBC_2.14, memcpy was aliased to memmove. extern "C" void* memmove(void* a, const void* b, size_t c); extern "C" void* memcpy(void* a, const void* b, size_t c) { return memmove(a, b, c); } extern "C" void __chk_fail(void) __attribute__((__noreturn__)); extern "C" FDELT_TYPE __fdelt_warn(FDELT_TYPE a) { if (a >= FD_SETSIZE) __chk_fail(); return a / __NFDBITS; } extern "C" FDELT_TYPE __fdelt_chk(FDELT_TYPE) __attribute__((weak, alias("__fdelt_warn")));
d297c943a222245107fd42132c2506b9c6385f2e
ae31ef39206bb73f700448119bacb690601b6ad6
/Algo/2020-10/1007/jiyoung_homework.cpp
624afa2690d80393a18c7905879cb6fceca312a8
[]
no_license
LIKESEAL/LikeSeal-Algorithm-Study
a52eaa629d435a6103e4a30fe378a95634111ff2
8c18d3966f9a880b316c3c02c6653b9328a900bb
refs/heads/master
2023-04-09T10:35:51.468376
2021-04-04T16:02:56
2021-04-04T16:02:56
335,230,396
0
0
null
null
null
null
UTF-8
C++
false
false
3,561
cpp
/* baekjoon 2151 : 거울 설치 solved by JY DATE : 2020.10.09 bfs를 이용하여 풀이 */ #include <algorithm> #include <cstdio> #include <iostream> #include <queue> #include <vector> #define min(a, b) a > b ? b : a #define INF 1e9 using namespace std; int N; char H[52][52] = {0,}; int mirror[52][52][4] = {0,}; // mirror[A][B][C] = D : (A,B)에서 빛이 C방향으로 진행 시 지금까지 설치한 문의 갯수는 D개 int dx[4] = {0, 0, -1, 1}; // 상,하,좌,우 int dy[4] = {-1, 1, 0, 0}; int s_x, s_y, e_x, e_y; int ans = INF; int change_dir(int dir, int shape) { if (shape == 0) { // / 거울일 경우 방향 전환 if (dir == 0) return 3; if (dir == 1) return 2; if (dir == 2) return 1; if (dir == 3) return 0; } if (shape == 1) { // \ 거울일 경우 방향 전환 if (dir == 0) return 2; if (dir == 1) return 3; if (dir == 2) return 0; if (dir == 3) return 1; } } int main(void) { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); bool flag = true; cin >> N; for (int i = 0; i < N; i++) { // 입력 for (int j = 0; j < N; j++) { cin >> H[i][j]; if (H[i][j] == '#' && flag) { s_x = j; s_y = i; flag = false; } else if (H[i][j] == '#' && !flag) { e_x = j; e_y = i; } } } fill(mirror[0][0], mirror[52][0], INF); // mirror 배열 INF로 초기화 queue<vector<int> > q; for (int i = 0; i < 4; i++) { // 시작문 상,하,좌,우 q.push({s_y, s_x, i}); mirror[s_y][s_x][i] = 0; } while (!q.empty()) { // bfs int y = q.front().at(0); // 현재칸 int x = q.front().at(1); int dir = q.front().at(2); q.pop(); int c_y = y + dy[dir]; // 다음칸 int c_x = x + dx[dir]; int c_dir = 0; if (c_x < 0 || c_x >= N || c_y < 0 || c_y >= N) continue; if (H[c_y][c_x] == '*') continue; if (H[c_y][c_x] == '.') { if (mirror[c_y][c_x][dir] > mirror[y][x][dir]) { mirror[c_y][c_x][dir] = mirror[y][x][dir]; q.push({c_y, c_x, dir}); } } else if (H[c_y][c_x] == '!') { if (mirror[c_y][c_x][dir] > mirror[y][x][dir]) { // 거울 없음 if (mirror[c_y][c_x][dir] > mirror[y][x][dir]) { mirror[c_y][c_x][dir] = mirror[y][x][dir]; q.push({c_y, c_x, dir}); } c_dir = change_dir(dir, 0); // / 거울일 경우 전환된 방향 if (mirror[c_y][c_x][c_dir] > mirror[y][x][dir] + 1) { mirror[c_y][c_x][c_dir] = mirror[y][x][dir] + 1; q.push({c_y, c_x, c_dir}); } c_dir = change_dir(dir, 1); // \ 거울일 경우 전환된 방향 if (mirror[c_y][c_x][c_dir] > mirror[y][x][dir] + 1) { mirror[c_y][c_x][c_dir] = mirror[y][x][dir] + 1; q.push({c_y, c_x, c_dir}); } } } else if (H[c_y][c_x] == '#' && c_y == e_y && c_x == e_x) { // 도착 문일 경우 if (mirror[c_y][c_x][dir] > mirror[y][x][dir]) { mirror[c_y][c_x][dir] = mirror[y][x][dir]; ans = min(ans, mirror[c_y][c_x][dir]); // 설치할 거울 최소 개수 확인 } } } cout << ans << '\n'; return 0; }
74238fd1efff05c9396b64c1681ac6191920dd20
bfc0a74a378d3692d5b033c21c29cf223d2668da
/unittests/libtests/faults/TestFault.cc
054dcc62a95b5956af85d7ba2eee62ada8293f05
[ "MIT" ]
permissive
rishabhdutta/pylith
b2ed9cd8039de33e337c5bc989e6d76d85fd4df1
cb07c51b1942f7c6d60ceca595193c59a0faf3a5
refs/heads/master
2020-12-29T01:53:49.828328
2016-07-15T20:34:58
2016-07-15T20:34:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,995
cc
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2016 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "TestFault.hh" // Implementation of class methods #include "pylith/faults/FaultCohesiveKin.hh" // USES FaultCohesiveKin #include "pylith/utils/error.h" // USES PYLITH_METHOD_BEGIN/END #include <string> // USES std::string // ---------------------------------------------------------------------- CPPUNIT_TEST_SUITE_REGISTRATION( pylith::faults::TestFault ); // ---------------------------------------------------------------------- // Test id() void pylith::faults::TestFault::testID(void) { // testID PYLITH_METHOD_BEGIN; const int id = 346; FaultCohesiveKin fault; fault.id(id); CPPUNIT_ASSERT_EQUAL(id, fault.id()); PYLITH_METHOD_END; } // testID // ---------------------------------------------------------------------- // Test label() void pylith::faults::TestFault::testLabel(void) { // testLabel PYLITH_METHOD_BEGIN; const std::string label = "the_database"; FaultCohesiveKin fault; fault.label(label.c_str()); CPPUNIT_ASSERT_EQUAL(label, std::string(fault.label())); PYLITH_METHOD_END; } // testLabel // ---------------------------------------------------------------------- // Test edge() void pylith::faults::TestFault::testEdge(void) { // testLabel PYLITH_METHOD_BEGIN; const std::string edge = "the_edge"; FaultCohesiveKin fault; fault.edge(edge.c_str()); CPPUNIT_ASSERT_EQUAL(edge, std::string(fault.edge())); PYLITH_METHOD_END; } // testEdge // End of file
2b92d6286a34aef82e2932e24546db6e780a2080
9c95d0c7d909af6c48b2614dbf5b4e46b406c594
/shockwave/tools.h
6c12739f764edbae324c66507880e345a5fda137
[]
no_license
haipengyu1013/ShockWaveDemo
b97b05a13a4ce5e80b1fa9cdbe7fda20257f4f5f
cacc96ec50eaab5b8b583addd7be09de4d1351c0
refs/heads/master
2020-03-17T09:20:33.057969
2018-05-15T06:41:12
2018-05-15T06:41:12
133,470,706
0
0
null
null
null
null
UTF-8
C++
false
false
251
h
#ifndef TOOLS_H #define TOOLS_H #include <QObject> class Tools : public QObject { Q_OBJECT public: Tools(QObject *parent = 0); public: Q_INVOKABLE QString readFile(const QString &fileName) const; }; #endif // TOOLS_H
38d40542337ce2f9e1c0ef185f3c32249b05f38d
4ed5b25a3015e5a13ca1ff3992c00146ffccd213
/abc/abc126/a.cpp
6fc9a3dbf50d1daf91bcc0efa3b31728150a47e3
[]
no_license
Stealthmate/atcoder
32284557eca524aafa312098132f583753e3d05c
6659dbde59d90f322f04751aaddc4ecb79e98eb8
refs/heads/master
2023-02-11T10:48:51.194510
2023-01-29T04:47:32
2023-01-29T04:47:32
192,467,091
0
0
null
null
null
null
UTF-8
C++
false
false
154
cpp
#include<bits/stdc++.h> using namespace std; int main() { int n, k; string s; cin >> n >> k >> s; s[k - 1] += 'a' - 'A'; cout << s << endl; }
c135e0340752fb0ffb2694a8c174a75c3326c7be
d01911c430c472e85ad8e9ece26ab008ed1f8160
/include/gcontainer.H
2145b0b823610ccc5633bd4d66037080e7786b30
[]
no_license
andresarcia/binder
1de95a95f29a85f0a77d1c7c8431191d398cf862
809c726947254da7383fa7b01cc62b8d82d1f069
refs/heads/master
2021-01-09T05:42:20.425502
2017-02-03T09:40:35
2017-02-03T09:40:35
80,815,842
0
0
null
null
null
null
UTF-8
C++
false
false
3,990
h
# ifndef GCONTAINER_H # define GCONTAINER_H # include <stdlib.h> # include "locator_calls.H" # include <pthread.h> # include <fstream> # include <base_message_header.H> # include <remote_multiserver_point.H> # include <useMutex.H> # define PRINT_PORT(the_port, type) {\ FILE * port_log = fopen("port_log","a");\ char port_str[Port::stringSize];\ the_port.getStringPort(port_str, Port::stringSize);\ fprintf(port_log, "%s:line %i: file %s:type %s\n",\ port_str, __LINE__, __FILE__, type);\ fclose(port_log);\ } // usage: container <number of iterations> <number of objects> <Site_Id_1> // <Object_Id_1> <number of iter> Site_Id this_site(INVALID_SITE_ID); Container_Id this_container; Dlink objs_list; Dlink cnt_list; Locator * array_of_refs; int n_objs, n_refs, n_tries=0, total_tries, n_cnts = 0; FILE * objs_file, * cnt_file; class Migration_Service; Remote_Multiserver_Point<Migration_Service> * migration_thread; pthread_mutex_t mutex_for_migration = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait_for_unregistration = PTHREAD_COND_INITIALIZER; bool object_migrating = false; int reinvocations = 0; int invocations = 0; template<class Node_Type> Node_Type * get_ith_elem(Dlink & centinel_node, unsigned i) { ASSERT(i > 0); Dlink * cursor = centinel_node.getNext(); for (unsigned pos = 1; (pos < i) && (cursor != &centinel_node); pos ++) cursor = cursor->getNext(); if (cursor == &centinel_node) return NULL; return static_cast<Node_Type *>(cursor); } template<class Node_Type, class Key_Type> Node_Type * search_elem(Dlink & centinel_node, const Key_Type & key) { Dlink * cursor = & centinel_node; for (cursor = cursor->getNext(); cursor != &centinel_node; cursor = cursor->getNext()) { char * key_inside_node = reinterpret_cast<char *>(cursor) + sizeof(Dlink); if (key == *reinterpret_cast<Key_Type*>(key_inside_node)) return static_cast<Node_Type*>(cursor); } return NULL; } int get_rand(int min_number, int max_number, bool with_randomize = false) { ASSERT((max_number - min_number) >= 0); if (max_number == min_number) return max_number; max_number = max_number - min_number + 1; int ret_val = min_number; float value = static_cast<float>(max_number)*rand()/(RAND_MAX+1.0); ret_val += static_cast<int>(value); ASSERT(ret_val >= min_number && ret_val <= (min_number + max_number - 1)); return ret_val; } class Locator_Node : public Dlink { Locator locator; public: Locator_Node(const Locator & _locator) : locator(_locator) { // empty } const Locator & get_locator() const { return locator; } }; class Container_Node : public Dlink { Container_Id container_id; Port container_port; public: Container_Node(const Container_Id & _container_id, const Port & _container_port) : container_id(_container_id), container_port(_container_port) { // empty } const Container_Id & get_container_id() const { return container_id; } const Port & get_container_port() const { return container_port; } }; class Object_Node : public Dlink { Object_Id object_id; Logical_Timestamp logical_timestamp; bool allowed_to_migrate; public: Object_Node(const Object_Id & _obj_id, Logical_Timestamp _timestamp = 0, const bool _allowed = true) : object_id(_obj_id), logical_timestamp(_timestamp), allowed_to_migrate(_allowed) { // empty } const Object_Id & get_object_id() const { return object_id; } const bool get_allowed_to_migrate() const { return allowed_to_migrate; } const Logical_Timestamp get_logical_timestamp() const { return logical_timestamp; } void set_allowed_to_migrate(bool _allowed) { allowed_to_migrate = _allowed; } }; # endif
00e0211d93f6be5a7f30996ae5be8c5e1df95c80
ebe7339ee948c4647951057bb19e62acccd3d0dc
/inline/inline.cpp
985ad55987293d41937824b8a83287820a467bc7
[ "Apache-2.0" ]
permissive
en6yu/src
1c8904958556dab863f2b68bc15078e4834cb253
715756a521df8ce700d4ba3f2df42bdeb9bed945
refs/heads/main
2023-06-30T03:36:29.323700
2021-07-25T14:52:26
2021-07-25T14:52:26
388,852,032
0
0
null
null
null
null
UTF-8
C++
false
false
1,333
cpp
#include<sstream> #include<iostream> #include<string> using namespace std; /** * @brief inline use * @author * @param * @return * @note * 1.inline 必须和函数定义在一起,只在声明中是不行的。 * 2.类成员函数有两种内联方式 隐式内联和显示内联 * 3.代码冗长和有循环时不宜用内联 * 4.虚函数和内联函数 只有知道特定调用才能用虚函数+内联 多态时就不能用内联+虚函数 */ class CInline { private: int m_value; public: CInline(); ~CInline(); public: void display()// 2.隐式内联 { cout<<m_value<<endl; } void show(); public: inline virtual void run(); }; class CSon :public CInline { public: void run() { cout<<"Cson"<<endl; } }; CInline::CInline() { } CInline::~CInline() { } void CInline::run() { cout<<"CInline"<<endl; } inline void CInline::show()//2.显示内联 { cout<<m_value<<endl; } inline void print() //1. inline 必须和定义在一起 { cout<<"inline"<<endl; } int main() { cout<<"CInline"<<endl; print(); CSon son; son.run();//4.run 可以内联 CInline * prun=new CSon(); prun->run();//4.run 阻止内联 编译器决定的 return 0; }
78f05a9c4cc3d71a3c2d8f6807cddf9432e7c6ce
5a49b5da44fa9c3a585febcf3d975197d872efc9
/Tools/SGP_WorldEditor/NewMapConfigDlg.cpp
168a140dfa34125fec52f1bf271bde7be41af8f0
[ "MIT" ]
permissive
phoenixzz/SGPEngine
1ab3de99fdf6dd791baaf57e029a09e8db3580f7
593b4313abdb881d60e82750b36ddda2d7c73c49
refs/heads/master
2021-01-24T03:42:44.683083
2017-01-24T04:39:43
2017-01-24T04:39:43
53,315,434
4
2
null
null
null
null
GB18030
C++
false
false
3,763
cpp
// NewMapConfigDlg.cpp : 实现文件 // #include "stdafx.h" #include "WorldEditor.h" #include "NewMapConfigDlg.h" #include "afxdialogex.h" #include "HelpFunction.h" #include "WorldEditorConfig.h" #include ".\Render Interface\WorldEditorRenderInterface.h" #include "..\SGPLibraryCode\SGPHeader.h" #include "NewMapLoadingDlg.h" #include "FolderDialog.h" // CNewMapConfigDlg 对话框 IMPLEMENT_DYNAMIC(CNewMapConfigDlg, CDialogEx) CNewMapConfigDlg::CNewMapConfigDlg(CNewMapLoadingDlg* loadingDlg,CWnd* pParent /*=NULL*/) : CDialogEx(CNewMapConfigDlg::IDD, pParent) { m_loadingDlg = loadingDlg; } CNewMapConfigDlg::~CNewMapConfigDlg() { } void CNewMapConfigDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CNewMapConfigDlg, CDialogEx) ON_BN_CLICKED(IDB_BROWSE_LAYER0_TEXTURE,OnBrowseLayer0Texture) ON_BN_CLICKED(IDB_BROWSE_MAP_FOLDER,OnBrowseMapFolder) END_MESSAGE_MAP() // CNewMapConfigDlg 消息处理程序 BOOL CNewMapConfigDlg::OnInitDialog() { CDialogEx::OnInitDialog(); CComboBox* pComboBox=(CComboBox*)GetDlgItem(IDC_WORLD_SIZE); pComboBox->AddString("Small (16X16)"); pComboBox->AddString("Middle (32X32)"); pComboBox->AddString("Large (64X64)"); pComboBox->SetCurSel(0); SetDlgItemText(IDE_MAX_TERRAIN_HEIGHT,"128"); m_Layer0TexturePath="Texture\\terrain\\slope.dds"; SetDlgItemText(IDE_LAYER0_TEXTURE_PATH,m_Layer0TexturePath); CheckDlgButton(IDC_USE_PERLIN_NOISE,BST_CHECKED); GetDlgItem(IDE_MAP_FOLDER)->SetWindowText(WorldEditorConfig::GetInstance()->GetWorldMapDir()); return TRUE; } BOOL CNewMapConfigDlg::PreTranslateMessage(MSG* pMsg) { //avoid ESC/OK to exit dialog if(pMsg->message==WM_KEYDOWN&&pMsg->wParam==VK_ESCAPE) return TRUE; UINT nID = ::GetDlgCtrlID(pMsg->hwnd); if(nID==IDE_LAYER0_TEXTURE_PATH||nID==IDE_MAP_FOLDER) { if(pMsg->message == WM_CHAR) return TRUE; if(pMsg->message>=WM_KEYFIRST&&pMsg->message<=WM_KEYLAST) return TRUE; } return CDialogEx::PreTranslateMessage(pMsg); } void CNewMapConfigDlg::OnBrowseLayer0Texture() { TCHAR szFilter[] = _T("DDS Files (*.dds)|*.dds|TGA Files (*.tga)|*.tga||"); CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,szFilter); dlg.m_ofn.lpstrInitialDir = (char*)(LPCTSTR)WorldEditorConfig::GetInstance()->GetDataFileDir(); if(dlg.DoModal()==IDOK) { if(!FileInFolder(dlg.GetPathName(),WorldEditorConfig::GetInstance()->GetDataFileDir())) { MessageBox("The texture must be in Data directory!","WorldEditor",MB_OK|MB_ICONERROR); return ; } m_Layer0TexturePath = GetRelativePath(dlg.GetPathName(),WorldEditorConfig::GetInstance()->GetDataFileDir()); SetDlgItemText(IDE_LAYER0_TEXTURE_PATH,m_Layer0TexturePath); } } void CNewMapConfigDlg::OnBrowseMapFolder() { CFolderDialog dlg(m_hWnd,"Choose folder to save map:",WorldEditorConfig::GetInstance()->GetWorldMapDir()); if(dlg.DoModal()==IDOK) { GetDlgItem(IDE_MAP_FOLDER)->SetWindowText(dlg.GetPath()); } } void CNewMapConfigDlg::CreateMap() { GetDlgItemText(IDE_WORLD_NAME,m_loadingDlg->m_MapName); GetDlgItemText(IDE_MAP_FOLDER,m_loadingDlg->m_MapFolder); CComboBox* pMapSize=(CComboBox*)GetDlgItem(IDC_WORLD_SIZE); SGP_TERRAIN_SIZE terrainSize; switch(pMapSize->GetCurSel()) { case 0: terrainSize = SGPTS_SMALL; break; case 1: terrainSize = SGPTS_MEDIUM; break; case 2: terrainSize = SGPTS_LARGE; break; } m_loadingDlg->m_TerrainSize = terrainSize; m_loadingDlg->m_TerrainMaxHeight = GetDlgItemInt(IDE_MAX_TERRAIN_HEIGHT); if(IsDlgButtonChecked(IDC_USE_PERLIN_NOISE)) m_loadingDlg->m_bUsePerlinNoise = true; else m_loadingDlg->m_bUsePerlinNoise = false; m_loadingDlg->m_Layer0TexPath = m_Layer0TexturePath; } void CNewMapConfigDlg::OnOK() { CreateMap(); CDialogEx::OnOK(); }
2924c68cc5ee7692b262adc9da37520f2804c276
0c4bd1b977cc714a8a6b2839f51c4247ecfd32b1
/C++/nnForge/nnforge/cuda/sparse_fully_connected_1x1_layer_tester_cuda.h
58ec7a2155caf652dfb505fd11c359cc1a41cb4f
[ "Apache-2.0" ]
permissive
ishine/neuralLOGIC
281d498b40159308815cee6327e6cf79c9426b16
3eb3b9980e7f7a7d87a77ef40b1794fb5137c459
refs/heads/master
2020-08-14T14:11:54.487922
2019-10-14T05:32:53
2019-10-14T05:32:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,859
h
/* * Copyright 2011-2016 Maxim Milakov * * 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. */ #pragma once #include "layer_tester_cuda.h" #include <cudnn.h> namespace nnforge { namespace cuda { class sparse_fully_connected_1x1_layer_tester_cuda : public layer_tester_cuda { public: sparse_fully_connected_1x1_layer_tester_cuda(); virtual ~sparse_fully_connected_1x1_layer_tester_cuda(); virtual void enqueue_forward_propagation( cudaStream_t stream_id, cuda_linear_buffer_device::ptr output_buffer, const std::vector<cuda_linear_buffer_device::const_ptr>& schema_data, const std::vector<cuda_linear_buffer_device::const_ptr>& data, const std::vector<cuda_linear_buffer_device::const_ptr>& data_custom, const std::vector<cuda_linear_buffer_device::const_ptr>& input_buffers, const std::vector<cuda_linear_buffer_device::const_ptr>& persistent_working_data, cuda_linear_buffer_device::ptr temporary_working_fixed_buffer, cuda_linear_buffer_device::ptr temporary_working_per_entry_buffer, unsigned int entry_count); protected: virtual void tester_configured(); private: int feature_map_connection_count; bool bias; cudnnTensorDescriptor_t output_data_desc; cudnnTensorDescriptor_t bias_desc; }; } }
8c59953d09d8977d52af8398f95aeb175665312e
342fa565a78e3a935d9ac643c749a05357a3fc9c
/src/tcp/socket.cpp
1b6748a1019932ab0b2f9cc81a7dc9562fe6dcff
[]
no_license
xxyyboy/php-flame
071dd698677c527066e9323c935962d869b5de03
220e3e8daf10c5b65c66c3b948417ce2e9868bdc
refs/heads/master
2020-04-20T10:37:35.865346
2019-01-18T12:57:21
2019-01-18T12:57:21
168,794,338
0
0
null
2019-02-02T04:33:59
2019-02-02T04:33:59
null
UTF-8
C++
false
false
3,533
cpp
#include "../controller.h" #include "../coroutine.h" #include "socket.h" namespace flame::tcp { void socket::declare(php::extension_entry& ext) { php::class_entry<socket> class_socket("flame\\tcp\\socket"); class_socket .property({"local_address", ""}) .property({"remote_address", ""}) .method<&socket::read>("read", { {"completion", php::TYPE::UNDEFINED, false, true} }) .method<&socket::write>("write", { {"data", php::TYPE::STRING} }) .method<&socket::close>("close"); ext.add(std::move(class_socket)); } socket::socket() : socket_(gcontroller->context_x) { } php::value socket::read(php::parameters& params) { coroutine_handler ch{coroutine::current}; // 使用下面锁保证不会同时进行读取 coroutine_guard guard(rmutex_, ch); boost::system::error_code err; std::size_t len; if (params.size() == 0) // 1. 随意读取一段数据 { len = socket_.async_read_some(boost::asio::buffer(buffer_.prepare(8192), 8192), ch[err]); buffer_.commit(len); } else if (params[0].typeof(php::TYPE::STRING)) // 2. 读取到指定的结束符 { std::string delim = params[0]; len = boost::asio::async_read_until(socket_, buffer_, delim, ch[err]); } else if (params[0].typeof(php::TYPE::INTEGER)) // 3. 读取指定长度 { std::size_t want = params[0].to_integer(); if(buffer_.size() >= want) { len = want; goto RETURN_DATA; } // 读取指定长度 (剩余的缓存数据也算在长度中) len = boost::asio::async_read(socket_, buffer_, boost::asio::transfer_exactly(want - buffer_.size()), ch[err]); len = want; } else // 未知读取方式 { throw php::exception(zend_ce_error, "failed to read tcp socket: unknown completion"); } RETURN_DATA: // 数据返回 if (err == boost::asio::error::operation_aborted || err == boost::asio::error::eof) { return nullptr; } else if (err) { throw php::exception(zend_ce_exception, (boost::format("failed to read tcp socket: (%1%) %2%") % err.value() % err.message()).str(), err.value()); } else { php::string data(len); boost::asio::buffer_copy(boost::asio::buffer(data.data(), len), buffer_.data(), len); buffer_.consume(len); return std::move(data); } } php::value socket::write(php::parameters& params) { coroutine_handler ch{coroutine::current}; // 使用下面锁保证不会同时写入 coroutine_guard guard(wmutex_, ch); boost::system::error_code err; std::string data = params[0]; boost::asio::async_write(socket_, boost::asio::buffer(data), ch); if (!err || err == boost::asio::error::operation_aborted) { return nullptr; } else { throw php::exception(zend_ce_exception, (boost::format("failed to write tcp socket: (%1%) %2%") % err.value() % err.message()).str(), err.value()); } } php::value socket::close(php::parameters& params) { socket_.shutdown(boost::asio::socket_base::shutdown_both); return nullptr; } }
f043ba63680be1077d93ea03f0fb1d9a006443a1
e2b305de68d93f078b5b0fdb03d3e39537691895
/Trees/SumRootToLeafNumbers.cpp
1bfe763131804e9c681e2a958fe03d41c2aae829
[]
no_license
Rishabh-Thapliyal/interviewbit
ceb6f0d1544515ea587a0b678052ff87c34059bc
ff4acd962524f76eaa14238efe686c6b65abc59a
refs/heads/master
2022-11-07T06:38:24.524588
2020-06-20T12:49:50
2020-06-20T12:49:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ const int MOD = 1003; void helper(TreeNode* A, vector<string> &v1, string s1){ if (!A->left && !A->right) { s1+=to_string(A->val); v1.push_back(s1); return; } s1+=to_string(A->val); s1 = to_string(stoll(s1, nullptr, 10)%1003); if (A->left) { helper(A->left, v1, s1); } if (A->right) { helper(A->right, v1, s1); } return; } int Solution::sumNumbers(TreeNode* A) { if (!A) { return 0; } string s1 = ""; vector<string> v1; helper(A, v1, s1); long long sum = 0; for (int i = 0; i < v1.size(); ++i) { sum=(sum + stoll(v1[i], nullptr, 10)%MOD)%MOD; } sum = sum%MOD; return (int)sum; }
6647b00290a043bba70b84bd3539ad32e47d1a31
9a2da4c236b3306315cb5896aaa300fa95dca566
/mainwindow.h
884828db573a9b11f8adf2767693aa4185d3c3cf
[]
no_license
Dacaar94/Wycenator
304359eb785fe6a1255bdca144639b2f365496e2
084af8f276484ffd6de5be96fe046af9193292aa
refs/heads/master
2022-12-09T13:52:24.831310
2020-09-14T11:53:27
2020-09-14T11:53:27
287,329,398
0
0
null
null
null
null
UTF-8
C++
false
false
1,133
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QtSql> #include <QDebug> #include <QFileInfo> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_4_clicked(); void on_pushButton_3_clicked(); void on_pushButton_6_clicked(); void on_pushButton_7_clicked(); void on_actionKopiuj_triggered(); void on_actionWklej_triggered(); void on_actionWytnij_triggered(); void on_actionWstecz_triggered(); void on_actionNaprz_d_triggered(); void on_actionNowy_triggered(); void on_actionOtw_rz_triggered(); void on_actionZapisz_triggered(); void on_actionZapisz_jako_triggered(); void on_actionInstrukcja_triggered(); void on_actionO_programie_triggered(); void on_actionO_tw_rcy_triggered(); void on_actionZako_cz_triggered(); void on_resetbutton_clicked(); private: Ui::MainWindow *ui; QSqlDatabase mydb; }; #endif // MAINWINDOW_H