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
b51d479f20b4ce582993f4c493474051dcabdc8d
3fe58516d32f8ab121ff17435c35b948e4b39e1a
/Sort/InsertSort.cpp
0bc9fdda4af7f30b8dff63028ffc93a176867b79
[]
no_license
Eli-yp/Data_structure
57a35bcb7117a970e38a7a09c3434d6780a0c88d
14224d943ee72cee51c5376ada43803493f86328
refs/heads/master
2020-03-18T16:16:10.978687
2018-06-08T11:13:19
2018-06-08T11:13:19
134,956,589
0
0
null
null
null
null
UTF-8
C++
false
false
555
cpp
#include<iostream> #include "sort.h" using namespace std; void InsertSort(SqList *L) { int j; for(int i = 2; i < L->length; ++i) { if(L->r[i] < L->r[i-1]) //需将L->r[i]插入有序字表 { L->r[0] = L->r[i]; //设置哨兵 for(j = i-1; L->r[j] > L->r[0]; --j) L->r[j+1] = L->r[j]; //记录后移 L->r[j+1] = L->r[0]; //插入到正确位置 } } } int main(int argc, char *argv[]) { SqList L = {{0,5,3,4,6,2}, 6}; InsertSort(&L); for(int i = 1; i < L.length; ++i) cout << L.r[i] << " "; cout << endl; return 0; }
[ "1094870599@qq.com" ]
1094870599@qq.com
37d80371c32bb430a2d07ab401f87f4b92038287
192fd8f3017356222af0b86682b64435a8e69e90
/lab5/ConsoleTextEditorLib/DocumentResources.cpp
bed16723d029dceb5876304f205184f9fc22d3f2
[]
no_license
Tandyru/ood-labs
d5ecfe9a0169e8607f3cad8b4bea54a88c1b9ff8
7c9fc19599eb37014d997e5a9a0dd5439acaf4e6
refs/heads/master
2021-07-15T18:21:25.802606
2019-02-07T18:24:49
2019-02-07T18:24:49
147,715,235
0
0
null
null
null
null
UTF-8
C++
false
false
1,075
cpp
#include "stdafx.h" #include "DocumentResources.h" #include <stdio.h> #include "StringUtils.h" #include "FileUtils.h" using namespace std; using namespace filesystem; namespace resources { CDocumentResources::CDocumentResources(const string& saveFolderName) : m_saveFolderName(saveFolderName) { m_tempDirectoryPath = temp_directory_path() / GetUniqueFileName(); create_directory(m_tempDirectoryPath); } CDocumentResources::~CDocumentResources() { remove_all(m_tempDirectoryPath); } unique_ptr<IResource> CDocumentResources::AddResource(const Path & originalPath, const string& saveNamePrefix) { const string extension = w2s(originalPath.extension().c_str()); Path filePath = m_tempDirectoryPath / GetUniqueFileName(extension); copy(originalPath, filePath); //const string extension = w2s(originalPath.extension().native().c_str()); return make_unique<CResource>(filePath/*, Path(m_saveFolderName) / (saveNamePrefix + to_string(m_nextResourceNameSuffix++) + extension)*/); } Path CDocumentResources::GetDirectoryPath() const { return m_tempDirectoryPath; } }
[ "43044294+Tandyru@users.noreply.github.com" ]
43044294+Tandyru@users.noreply.github.com
008b4f3a7b33f9efd1e9e2d7033165ead5b2d6f9
d7621ca29e6333ae104d66d4b046d2eb782cbf1c
/emoncms_2pinzas_localyremoto/emoncms_2pinzas_localyremoto.ino
4f5a7c787d2d7ddfff574bf0f68a56bf529fcaed
[]
no_license
asecashugo/ArduinoSketches
2e1241880ff59ae48749c0ee2f01a09d6a2bd2a8
acd5ff75b68421084950df9e2615b4b971dbaf37
refs/heads/master
2020-03-12T15:56:23.893361
2019-05-19T10:03:10
2019-05-19T10:03:10
130,703,302
0
0
null
null
null
null
UTF-8
C++
false
false
3,680
ino
/* Emoncms sensor client with Strings This sketch connects an analog sensor to Emoncms, using a ms14 with Yún + Lenonard. created 15 March 2010 updated 27 May 2013 by Tom Igoe updated 6, Oct, 2013 to support Emoncms by Edwin Chen */ // include all Libraries needed: #include <Process.h> #include <Bridge.h> #include "EmonLib.h" EnergyMonitor cons; EnergyMonitor gen; // set up net client info: const unsigned long postingInterval = 1000; //delay between updates to emoncms.com unsigned long lastRequest = 0; // when you last made a request String dataString = ""; void setup() { // start serial port: Bridge.begin(); Console.begin(); //while(!Console); // wait for Network Console to open Console.println("Emoncms client"); cons.current(1, 60.6); gen.current(2, 60.6); // Do a first update immediately updateData(); sendDataRemoto(); sendDataLocal(); lastRequest = millis(); } void loop() { // get a timestamp so you can calculate reading and sending intervals: long now = millis(); // if the sending interval has passed since your // last connection, then connect again and send data: if (now - lastRequest >= postingInterval) { updateData(); sendDataRemoto(); sendDataLocal(); lastRequest = now; } } void updateData() { // convert the readings to a String to send it: double consumo = 240.0 * cons.calcIrms(1480) - 54; double generacion = 240.0 * gen.calcIrms(1480) - 54; double contador = consumo - generacion; dataString = "Consumo_w:"; dataString += consumo; // add generacion: dataString += ",Generacion_w:"; dataString += generacion; // add contador: dataString += ",Contador_w:"; dataString += contador; } // this method makes a HTTP connection to the server: void sendDataRemoto() { // form the string for the API header parameter: String apiString = "a6724324477c9f5e07bb8390392cc71c"; // apiString += APIKEY; // form the string for the URL parameter: String url = "http://emoncms.org/api/post?"; url += "json={"; url += dataString; url += "}&"; url += "apikey="; url += apiString; // Send the HTTP PUT request // Is better to declare the Process here, so when the // sendData function finishes the resources are immediately // released. Declaring it global works too, BTW. Process emoncms; Console.print("\n\nSending data CURL... "); Console.println(url); emoncms.begin("curl"); emoncms.addParameter("-g"); emoncms.addParameter(url); emoncms.run(); // If there's incoming data from the net connection, // send it out the Console: while (emoncms.available() > 0) { char c = emoncms.read(); Console.write(c); } } void sendDataLocal() { // form the string for the API header parameter: String apiString = "e22ff0cae49b72a2901811989be7eba0"; // apiString += APIKEY; // form the string for the URL parameter: String url = "http://rpihugo.ddns.net/emoncms/input/post?"; url += "node=Yun_Entrada&"; url += "json={"; url += dataString; url += "}&"; url += "apikey="; url += apiString; // Send the HTTP PUT request // Is better to declare the Process here, so when the // sendData function finishes the resources are immediately // released. Declaring it global works too, BTW. Process emoncms; Console.print("\n\nSending data local CURL... "); Console.println(url); emoncms.begin("curl"); emoncms.addParameter("-g"); emoncms.addParameter(url); emoncms.run(); // If there's incoming data from the net connection, // send it out the Console: while (emoncms.available() > 0) { char c = emoncms.read(); Console.write(c); } }
[ "asecashugo@gmail.com" ]
asecashugo@gmail.com
eb1b7c5c1a2836509d042a9fda2f3d386ff7ccd4
67bad951ef286875e983dd6c9584696ff18e8c6e
/projecteuler3/main.cpp
646318971f2dd44f61dac8dcb2d4d278edbdd207
[]
no_license
irajankumar/ProjectEuler
2522af9a1f92a5ffab8d8bc58db46cc7e9ce6747
3b0047ab0db129023703bb44081caaf77aa07480
refs/heads/master
2021-05-30T03:10:01.464610
2015-12-14T11:22:42
2015-12-14T11:22:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
591
cpp
#include <iostream> #include<vector> //This program finds out the largest prime factor of given input using namespace std; int main() { long int n,big; cin>>n; vector<long int>primes; for(long int l=2; l<n; l++) { int ct=0; for(int m=2;m<l;m++) { if(l%m==0) { ct++; break; } if(ct>0) break; } if(ct==0) primes.push_back(l); } for(int i=0; i<primes.size();i++) { if(n%primes[i]==0) big=primes[i]; } cout<<big; return 0; }
[ "rkking@live.com" ]
rkking@live.com
5b2349da2fbcfd150f71c7e1c81b55a28a3cdd58
73d8f126460d2b8ab0cb18c475b8ee9fb28925e0
/src/easing_functions/Cubic.cpp
4e17295f388fa7b4ed090d4fd521089a9e771cef
[ "MIT" ]
permissive
morphogencc/ofxAnimation
001b8a9b6d21b87aa7fc3a2ae46a5a6e67321a49
82bbfd533b1d49d2298a2ed1ae17cbbcf4de9280
refs/heads/master
2020-02-26T15:21:03.099053
2016-06-13T12:02:19
2016-06-13T12:02:19
60,379,071
0
0
null
null
null
null
UTF-8
C++
false
false
500
cpp
#include "Cubic.h" using namespace ofxAnimation; float Cubic::easeIn (float t, EasingParameters parameters) { return parameters.c*(t/=parameters.d)*t*t + parameters.b; } float Cubic::easeOut(float t, EasingParameters parameters) { return parameters.c*((t=t/parameters.d-1)*t*t + 1) + parameters.b; } float Cubic::easeInOut(float t, EasingParameters parameters) { if ((t/=parameters.d/2) < 1) return parameters.c/2*t*t*t + parameters.b; return parameters.c/2*((t-=2)*t*t + 2) + parameters.b; }
[ "info@morphogen.cc" ]
info@morphogen.cc
f321beea9070f8411afe35411c98c183b531b07c
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/admin/services/sched/svc_core/sch_wkr.cxx
4ccdb59fa940f388e3a4156e1b8059dfa53ebb5d
[]
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
69,581
cxx
//+---------------------------------------------------------------------------- // // Scheduling Agent Service // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1996. // // File: sch_wkr.cxx // // Contents: job scheduler service worker class impementation // // Classes: CSchedWorker // // History: 15-Sep-95 EricB created // 25-Jun-99 AnirudhS Extensive fixes to close windows in // MainServiceLoop algorithms. // 15-Feb-01 Jbenton Bug 315821 - NULL pJob pointer being // dereferenced when ActivateJob failed with OUT_OF_MEMORY. // //----------------------------------------------------------------------------- #include "..\pch\headers.hxx" #pragma hdrstop #include "globals.hxx" #include "svc_core.hxx" #include "..\inc\resource.h" #include <sddl.h> #define CONTROL_WINDOWS_KEY TEXT("System\\CurrentControlSet\\Control\\Windows") #define NOBOOTPOPUPS_VALUENAME TEXT("NoPopupsOnBoot") extern HANDLE g_WndEvent; DWORD CalcWait(LPFILETIME pftNow, LPFILETIME pftJob); void ReportMissedRuns(const SYSTEMTIME * pstLastRun, const SYSTEMTIME * pstNow); DWORD WINAPI PopupThread(LPVOID lpParameter); #if DBG LPSTR SystemTimeString(const SYSTEMTIME& st, CHAR * szBuf, size_t cchBuf) { StringCchPrintfA(szBuf, cchBuf, "%2d/%02d/%d %2d:%02d:%02d.%03d", st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); return szBuf; } LPSTR FileTimeString(FILETIME ft, CHAR * szBuf, size_t cchBuf) { SYSTEMTIME st; FileTimeToSystemTime(&ft, &st); return (SystemTimeString(st, szBuf, cchBuf)); } #endif LONG g_fPopupDisplaying; // = FALSE //+---------------------------------------------------------------------------- // // Member: CSchedWorker::Init // // Synopsis: Two phase constrution - do class init that could fail here. // // Returns: hresults // //----------------------------------------------------------------------------- HRESULT CSchedWorker::Init() { m_pSch = new CSchedule; if (m_pSch == NULL) { return E_OUTOFMEMORY; } HRESULT hr = m_pSch->Init(); if (FAILED(hr)) { ERR_OUT("CSchedWorker::Init, m_pSch->Init", hr); delete m_pSch; return hr; } hr = m_pSch->InitAtID(); if (FAILED(hr)) { ERR_OUT("CSchedWorker::Init, m_pSch->Init", hr); delete m_pSch; return hr; } // // Compose the job search string. It will be composed of the following: // g_TasksFolderInfo.ptszPath\*.TSZ_JOB // UINT cch = lstrlen(g_TasksFolderInfo.ptszPath) + 3 + ARRAY_LEN(TSZ_JOB); m_ptszSearchPath = new TCHAR[cch]; if (!m_ptszSearchPath) { ERR_OUT("CSchedWorker::Init", E_OUTOFMEMORY); return E_OUTOFMEMORY; } StringCchCopy(m_ptszSearchPath, cch, g_TasksFolderInfo.ptszPath); StringCchCat(m_ptszSearchPath, cch, TEXT("\\*.") TSZ_JOB); // // Create the service control event. // m_hServiceControlEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (m_hServiceControlEvent == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); ERR_OUT("CreateEvent", hr); return hr; } // // Create the on idle event. // m_hOnIdleEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (m_hOnIdleEvent == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); ERR_OUT("CreateEvent", hr); return hr; } // // Create the idle loss event. // m_hIdleLossEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (m_hIdleLossEvent == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); ERR_OUT("CreateEvent", hr); return hr; } // // Create the event used for synchronization with processor threads. // m_hMiscBlockEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (m_hMiscBlockEvent == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); ERR_OUT("CreateEvent", hr); return hr; } // // Create the timer that will wake the system when it's time to run // a job with TASK_FLAG_SYSTEM_REQUIRED. // HINSTANCE hKernel32Dll = GetModuleHandle(TEXT("KERNEL32.DLL")); if (hKernel32Dll == NULL) { DWORD dwErr = GetLastError(); ERR_OUT("Load of kernel32.dll", dwErr); return HRESULT_FROM_WIN32(dwErr); } pfnSetThreadExecutionState = (PFNSetThreadExecutionState) GetProcAddress(hKernel32Dll, "SetThreadExecutionState"); if (pfnSetThreadExecutionState == NULL) { ERR_OUT("GetProcAddress for SetThreadExecutionState", GetLastError()); } m_hSystemWakeupTimer = CreateWaitableTimer(NULL, FALSE, NULL); if (m_hSystemWakeupTimer == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); ERR_OUT("CreateWaitableTimer", hr); return hr; } // // Save the service's working directory. // cch = GetCurrentDirectory(0, m_ptszSvcDir); if (cch == 0) { hr = HRESULT_FROM_WIN32(GetLastError()); ERR_OUT("CSchedWorker::Init, GetCurrentDirectory", hr); return hr; } m_ptszSvcDir = new TCHAR[cch + 1]; if (m_ptszSvcDir == NULL) { ERR_OUT("CSchedWorker::Init, service directory", E_OUTOFMEMORY); return E_OUTOFMEMORY; } if (GetCurrentDirectory(cch + 1, m_ptszSvcDir) == 0) { hr = HRESULT_FROM_WIN32(GetLastError()); ERR_OUT("CSchedWorker::Init, GetCurrentDirectory", hr); return hr; } // // Tell the queue of service controls which event to signal when a // control is in the queue. // m_ControlQueue.Init(m_hServiceControlEvent); // // Record the start up time as the directory-last-checked-time. // GetSystemTimeAsFileTime(&m_ftLastChecked); // // Also use this as the beginning of the wait list period. // FileTimeToLocalFileTime(&m_ftLastChecked, &m_ftBeginWaitList); // // Set the initial end-of-wait-list-period. // SYSTEMTIME st; FileTimeToSystemTime(&m_ftBeginWaitList, &st); schDebugOut((DEB_ITRACE, "Init: time now is %u/%u/%u %u:%02u:%02u\n", st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond)); SetEndOfWaitListPeriod(&st); return S_OK; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::BuildWaitList // // Synopsis: Examines the job objects in the scheduler folder and builds // a run time list. // // Arguments: [fStartup] - if true, then being called at initial service // start up. If this is the case, then verify and fix // job state consistency and run any jobs with // startup triggers. // [fReportMisses] - whether to detect and report task runs that // were missed (because the service was not running // or the machine was asleep). This is TRUE when // called on machine wakeup and service start or // continue, FALSE otherwise. // [fSignAtJobs] - whether to trust and sign all At jobs that // an owner of Admin or LocalSystem (the pre-NT5 // check). This is TRUE the first time the service // runs on NT5. // // Returns: hresults // // Notes: Currently gets all runs from now until midnight. A later // enhancement will be to allow a different period to be // specified. // //----------------------------------------------------------------------------- HRESULT CSchedWorker::BuildWaitList( BOOL fStartup, BOOL fReportMisses, BOOL fSignAtJobs ) { TRACE(CSchedWorker, BuildWaitList); HRESULT hr = S_OK; DWORD dwRet; HANDLE hFind; WIN32_FIND_DATA fd; BOOL fMisses = FALSE; // Whether runs were missed m_WaitList.FreeList(); m_IdleList.FreeExpiredOrRegenerated(); m_ftFutureWakeup = MAX_FILETIME; fReportMisses = (fReportMisses && g_fNotifyMiss); // // The start of the wait list period was picked elsewhere. // SYSTEMTIME stBegin; FileTimeToSystemTime(&m_ftBeginWaitList, &stBegin); FILETIME ftSTBegin; LocalFileTimeToFileTime(&m_ftBeginWaitList, &ftSTBegin); // // Set the end of the wait list period. // SYSTEMTIME stEnd = stBegin; SetEndOfWaitListPeriod(&stEnd); schDebugOut((DEB_TRACE, "BuildWaitList %s to %s\n", CSystemTimeString(stBegin).sz(), CSystemTimeString(stEnd).sz())); // // Save the time of last (starting to) scan the folder. // GetSystemTimeAsFileTime(&m_ftLastChecked); m_cJobs = 0; hFind = FindFirstFile(m_ptszSearchPath, &fd); if (hFind == INVALID_HANDLE_VALUE) { dwRet = GetLastError(); if (dwRet == ERROR_FILE_NOT_FOUND) { // // No job files. // schDebugOut((DEB_ITRACE, "No jobs found!\n")); return S_OK; } else { return HRESULT_FROM_WIN32(dwRet); } } // // Read the last task run time from the registry. If it's absent, // as it will be the first time the service runs, use stBegin (so no // misses will be reported). // SYSTEMTIME stLastRun; if (fReportMisses) { if (!ReadLastTaskRun(&stLastRun)) { stLastRun = stBegin; } } CJob * pJob = NULL; CRunList * pStartupList = new CRunList; if (pStartupList == NULL) { ERR_OUT("BuildWaitList list allocation", E_OUTOFMEMORY); return E_OUTOFMEMORY; } do { DWORD dwSavePFlags = 0; // // Check if the service is shutting down. We check the event rather // than simply checking GetCurrentServiceState because this method is // called by the main loop which won't be able to react to the shut // down event while in this method. // DWORD dwWaitResult = WaitForSingleObject(m_hServiceControlEvent, 0); if (dwWaitResult == WAIT_OBJECT_0) { // // Reset the event so that the main loop will react properly. // EnterCriticalSection(&m_SvcCriticalSection); if (!SetEvent(m_hServiceControlEvent)) { LogServiceError(IDS_NON_FATAL_ERROR, GetLastError()); ERR_OUT("BuildWaitList: SetEvent", HRESULT_FROM_WIN32(GetLastError())); // // If this call fails, we are in a heap of trouble, so it // really doesn't matter what we do. So, continue. // } LeaveCriticalSection(&m_SvcCriticalSection); if (GetCurrentServiceState() == SERVICE_STOP_PENDING) { DBG_OUT("BuildWaitList: Service shutting down"); // // The service is shutting down. Free job info objects. // delete pStartupList; m_WaitList.FreeList(); return S_OK; } } m_cJobs++; // // Activate the job. // If we've been asked to sign At jobs, do a full load (because we // will be writing some variable-length job properties, and we don't // want to lose the others). Otherwise a partial load is enough. // BOOL fTriggersLoaded = fSignAtJobs; hr = m_pSch->ActivateJob(fd.cFileName, &pJob, fSignAtJobs); if (FAILED(hr)) { LogTaskError(fd.cFileName, NULL, IDS_LOG_SEVERITY_WARNING, IDS_LOG_JOB_WARNING_CANNOT_LOAD, NULL, (DWORD)hr); ERR_OUT("BuildWaitList Activate", hr); hr = S_OK; goto CheckNext; } if (pJob->IsFlagSet(JOB_I_FLAG_NET_SCHEDULE) && fSignAtJobs) { // // We're about to sign this At job, because it's the first time // the service is running and At jobs didn't have signatures // before NT5. First verify that the job at least passes the // pre-NT5 test for authenticity. // if (g_TasksFolderInfo.FileSystemType == FILESYSTEM_NTFS && !IsAdminFileOwner(pJob->GetFileName())) { // // Bogus job. Leave it unsigned. // schDebugOut((DEB_ERROR, "BuildWaitList: file not owned by Admin: %ws\n", pJob->GetFileName())); hr = S_OK; goto CheckNext; } // // Sign the job // hr = pJob->Sign(); if (FAILED(hr)) { CHECK_HRESULT(hr); hr = S_OK; goto CheckNext; } // // Force the updated job to be written to disk // dwSavePFlags |= SAVEP_VARIABLE_LENGTH_DATA; } FILETIME ftSTNow; // time just after activating job GetSystemTimeAsFileTime(&ftSTNow); if (fStartup) { // // Let the service controller know we're making progress. // StartupProgressing(); // // Do service startup processing. First load the triggers. // hr = pJob->LoadTriggers(); if (FAILED(hr)) { LogTaskError(fd.cFileName, NULL, IDS_LOG_SEVERITY_WARNING, IDS_LOG_JOB_WARNING_CANNOT_LOAD, NULL, (DWORD)hr); ERR_OUT("BuildWaitList, pJob->LoadTriggers", hr); hr = S_OK; goto CheckNext; } fTriggersLoaded = TRUE; pJob->UpdateJobState(FALSE); // // If this job has no more runs and the delete-when-done flag is // set, then delete the job. // if (pJob->IsFlagSet(JOB_I_FLAG_NO_MORE_RUNS) && pJob->IsFlagSet(TASK_FLAG_DELETE_WHEN_DONE)) { hr = pJob->Delete(); if (FAILED(hr)) { LogTaskError(fd.cFileName, NULL, IDS_LOG_SEVERITY_WARNING, IDS_CANT_DELETE_JOB, NULL, (DWORD)hr); ERR_OUT("JobPostProcessing, delete-when-done", hr); } goto CheckNextNoSave; } // // Make sure that the job object status is in a consistent state. // The state can be left inconsistent if the service is stopped // while jobs are running. // if (pJob->IsStatus(SCHED_S_TASK_RUNNING)) { if (pJob->IsFlagSet(JOB_I_FLAG_NO_MORE_RUNS)) { pJob->SetStatus(SCHED_S_TASK_NO_MORE_RUNS); } pJob->SetFlag(JOB_I_FLAG_PROPERTIES_DIRTY); } if (pJob->IsFlagSet(JOB_I_FLAG_RUN_NOW) || pJob->IsFlagSet(JOB_I_FLAG_ABORT_NOW)) { pJob->ClearFlag(JOB_I_FLAG_RUN_NOW | JOB_I_FLAG_ABORT_NOW); pJob->SetFlag(JOB_I_FLAG_PROPERTIES_DIRTY); } if (pJob->m_cRunningInstances) { pJob->m_cRunningInstances = 0; pJob->SetFlag(JOB_I_FLAG_PROPERTIES_DIRTY); } } // // Check if job can run. // if (!pJob->IsFlagSet(TASK_FLAG_DISABLED) && pJob->IsFlagSet(JOB_I_FLAG_HAS_APPNAME)) { // // LoadTriggers will set or clear the JOB_I_FLAG_HAS_TRIGGERS flag // as appropriate. // if (!fTriggersLoaded) { hr = pJob->LoadTriggers(); if (FAILED(hr)) { LogTaskError(fd.cFileName, NULL, IDS_LOG_SEVERITY_WARNING, IDS_LOG_JOB_WARNING_CANNOT_LOAD, NULL, (DWORD)hr); ERR_OUT("BuildWaitList, pJob->LoadTriggers", hr); hr = S_OK; goto CheckNext; } } if (pJob->IsFlagSet(JOB_I_FLAG_HAS_TRIGGERS)) { // // Add startup-triggered runs to the startup list, if this // is startup // if (fStartup && !g_fUserStarted) { hr = pJob->IfStartupJobAddToList(fd.cFileName, pStartupList, &m_IdleList); if (FAILED(hr)) { ERR_OUT("BuildWaitList IfStartupJobAddToList", hr); goto Cleanup; } } // // See if the job had missed runs (runs scheduled between // stLastRun and stBegin) // if (fReportMisses) { CTimeRunList MissedList; WORD cMissedRuns = 0; hr = pJob->GetRunTimesP(&stLastRun, &stBegin, &cMissedRuns, 1, &MissedList, fd.cFileName); if (FAILED(hr)) { schDebugOut((DEB_ERROR, "BuildWaitList: Get Missed RunTimes for " FMT_TSTR " FAILED, %#lx\n", fd.cFileName, hr)); // BUGBUG Log this? Disable the job? hr = S_OK; } if (cMissedRuns != 0) { fMisses = TRUE; pJob->SetFlag(JOB_I_FLAG_MISSED | JOB_I_FLAG_PROPERTIES_DIRTY); FILETIME ftMissed; schAssert(MissedList.PeekHeadTime(&ftMissed) == S_OK); schDebugOut((DEB_TRACE, FMT_TSTR " missed a run (at %s) between %s and %s\n", fd.cFileName, CFileTimeString(ftMissed).sz(), CSystemTimeString(stLastRun).sz(), CSystemTimeString(stBegin).sz() )); } } // // Add time-triggered runs to the wait list // // If the file has a creation time between stBegin and now, // start its run list from that time, instead of stBegin. // This prevents the most common case of a task being run // even though it was created after its scheduled run time. // We can't use the task write time because that could cause // runs to be skipped if non-schedule changes were made to // the task after it was submitted. // // BUGBUG We will still run a task if it was created at // 5:00:00, and modified at 8:03:20 to run at 8:03:00, and // we haven't yet run an 8:03:00 batch by 8:03:20. // SYSTEMTIME stJobBegin = stBegin; if (CompareFileTime(&ftSTBegin, &fd.ftCreationTime) < 0 // recently created && CompareFileTime(&fd.ftCreationTime, &ftSTNow) < 0 // created "in the future" would mean a time change // or a drag-drop occurred, so forget this adjustment ) { FILETIME ftJobBegin; FileTimeToLocalFileTime(&fd.ftCreationTime, &ftJobBegin); FileTimeToSystemTime(&ftJobBegin, &stJobBegin); schDebugOut((DEB_TRACE, "Using %s for " FMT_TSTR "\n", CSystemTimeString(stJobBegin).sz(), fd.cFileName)); } WORD cRuns = 0; hr = pJob->GetRunTimesP(&stJobBegin, &stEnd, &cRuns, TASK_MAX_RUN_TIMES, &m_WaitList, fd.cFileName); if (FAILED(hr)) { schDebugOut((DEB_ERROR, "BuildWaitList: GetRunTimesP for " FMT_TSTR " FAILED, %#lx\n", fd.cFileName, hr)); // BUGBUG Log this? Disable the job? hr = S_OK; } if (cRuns == 0) { schDebugOut((DEB_TRACE, "There are no runs scheduled for " FMT_TSTR ".\n", fd.cFileName)); } // // If the system must be woken to run this task, also // compute its first run time AFTER the wait list period. // Remember the first of all such run times. // if (pJob->IsFlagSet(TASK_FLAG_SYSTEM_REQUIRED)) { CTimeRunList RunList; WORD cRuns = 0; hr = pJob->GetRunTimesP(&stEnd, NULL, &cRuns, 1, &RunList, NULL); if (hr == S_OK && cRuns != 0) { FILETIME ft; RunList.PeekHeadTime(&ft); m_ftFutureWakeup = minFileTime(m_ftFutureWakeup, ft); } } // // Add idle-triggered runs to the idle list // hr = pJob->IfIdleJobAddToList(fd.cFileName, &m_IdleList); if (FAILED(hr)) { schDebugOut((DEB_ERROR, "BuildWaitList: IfIdleJobAddToList for " FMT_TSTR " FAILED, %#lx\n", fd.cFileName, hr)); // BUGBUG Log this? Disable the job? hr = S_OK; } } } CheckNext: if (pJob != NULL && (pJob->IsFlagSet(JOB_I_FLAG_PROPERTIES_DIRTY) || !pJob->IsFlagSet(JOB_I_FLAG_NO_RUN_PROP_CHANGE))) { // // Mark this job as clean // pJob->SetFlag(JOB_I_FLAG_NO_RUN_PROP_CHANGE); // // Write out the cleaned up state. Be sure not to clear the // AT bit on an AT job just because we're updating its run // state. // dwSavePFlags |= (SAVEP_PRESERVE_NET_SCHEDULE | SAVEP_RUNNING_INSTANCE_COUNT); hr = pJob->SaveWithRetry(NULL, FALSE, dwSavePFlags); if (FAILED(hr)) { ERR_OUT("BuildWaitList, pJob->Save", hr); goto Cleanup; } } CheckNextNoSave: if (!FindNextFile(hFind, &fd)) { dwRet = GetLastError(); if (dwRet == ERROR_NO_MORE_FILES) { break; } else { ERR_OUT("CSchedWorker::BuildWaitList, FindNextFile", dwRet); hr = HRESULT_FROM_WIN32(dwRet); goto Cleanup; } } } while (SUCCEEDED(hr)); Cleanup: if (pJob) { pJob->Release(); } FindClose(hFind); if (FAILED(hr)) { m_WaitList.FreeList(); m_IdleList.FreeList(); delete pStartupList; return hr; } // // Report missed runs // if (fMisses) { ReportMissedRuns(&stLastRun, &stBegin); } if (fStartup) { // // If this is the first time in BuildWaitList, wait until the other // thread has created the window and initialized idle detection. // // This code is executed by the main thread of the service, // which is the state machine thread, not the window thread. // So it must wait for the window thread to initialize. // // Currently waiting for 15 minutes. If the window has not been // created by then, we are in trouble. // #define WINDOW_WAIT_TIMEOUT (15 * 60 * 1000) if (WaitForSingleObject(g_WndEvent, WINDOW_WAIT_TIMEOUT) == WAIT_TIMEOUT) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_WINDOW_HANDLE); ERR_OUT("Waiting for window creation", hr); delete pStartupList; return hr; } } // // If there are any idle-dependent tasks, set the initial idle wait time. // // (Possible optimization: It may be safe to get rid of this crit sec) EnterCriticalSection(&m_SvcCriticalSection); SetNextIdleNotification(m_IdleList.GetFirstWait()); LeaveCriticalSection(&m_SvcCriticalSection); if (!pStartupList->GetFirstJob()->IsNull()) { // // Run all jobs with startup triggers. // schDebugOut((DEB_ITRACE, "Running startup jobs...\n")); hr = RunJobs(pStartupList); // RunJobs *should* handle deleting pStartupList, even in failure cases if (FAILED(hr)) { ERR_OUT("Running startup jobs", hr); return hr; } } else { delete pStartupList; } return (hr == S_FALSE) ? S_OK : hr; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::GetNextListTime // // Synopsis: Returns the time at which the next job needs to run or // the end of the current wait list period. // // Arguments: None. // // Returns: Wait time in milliseconds. // //----------------------------------------------------------------------------- FILETIME CSchedWorker::GetNextListTime() { //TRACE(CSchedWorker, GetNextListTime); FILETIME ftJob; if (m_WaitList.PeekHeadTime(&ftJob) == S_FALSE) { // // No more jobs in list, return the end of the wait list period // instead. // SystemTimeToFileTime(&m_stEndOfWaitListPeriod, &ftJob); } return ftJob; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::GetNextRunWait // // Synopsis: Returns the wait time until the next job needs to run or until // the end of the current wait list period. // // Arguments: None. // // Returns: Wait time in milliseconds. // //----------------------------------------------------------------------------- DWORD CSchedWorker::GetNextRunWait() { //TRACE(CSchedWorker, GetNextRunWait); FILETIME ftJob = GetNextListTime(); FILETIME ftNow = GetLocalTimeAsFileTime(); return (CalcWait(&ftNow, &ftJob)); } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::NextWakeupTime // // Synopsis: Finds the next time at which the machine must be awake. // // Arguments: [ftNow] - the current time. // // Returns: The next time at which the machine must be awake. // // Notes: Finds the first run of a SYSTEM_REQUIRED job that is at least // 5 seconds into the future, and returns its time. // If there's no such run, returns MAX_FILETIME. //----------------------------------------------------------------------------- FILETIME CSchedWorker::NextWakeupTime(FILETIME ftNow) { FILETIME ftWakeup = FTfrom64(FTto64(ftNow) + SCHED_WAKEUP_CALC_MARGIN); for (CRun * pRun = m_WaitList.GetFirstJob(); !pRun->IsNull(); pRun = pRun->Next()) { if (pRun->IsFlagSet(TASK_FLAG_SYSTEM_REQUIRED) && CompareFileTime(pRun->GetTime(), &ftWakeup) > 0 && !(g_fOnBattery && pRun->IsFlagSet(TASK_FLAG_DONT_START_IF_ON_BATTERIES))) { return (* (pRun->GetTime())); } } // // No suitable run time in the list. Use m_ftFutureWakeup, unless // it's MAX_FILETIME. // ftWakeup = m_ftFutureWakeup; if (CompareFileTime(&ftWakeup, &MAX_FILETIME) < 0) { if (CompareFileTime(&ftWakeup, &ftNow) < 0) { // // The "future wakeup time" is in the past. // This can happen if the time is changed and the service hasn't // received the WM_TIMECHANGE message yet. This check avoids an // infinite loop of WAKEUP_TIME_EVENT and NextWakeupTime(). // It could also happen if, e.g., the future wakeup time was // 12:01 am and we passed that time and got here before rebuilding // the wait list. // schDebugOut((DEB_ERROR, "***** WARNING: Wakeup time in past! " "Machine time changed without receiving WM_TIMECHANGE. *****\n")); ftWakeup = MAX_FILETIME; // // When the WM_TIMECHANGE is received, we'll rebuild the wait // list and recalculate m_ftFutureWakeup. // If the WM_TIMECHANGE is never received, the wakeup time won't // be set and the machine could fail to wakeup. (e.g. on NT 4.0 // the "time" command changes the time without sending the // message.) Send ourselves the message to be sure. // schDebugOut((DEB_TRACE, "Sending ourselves a WM_TIMECHANGE message\n")); PostMessage(g_hwndSchedSvc, WM_TIMECHANGE, 0, 0); } } return ftWakeup; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::SetNextWakeupTime // // Synopsis: Sets the wakeup timer to the next time at which the machine // must be awake. // // Arguments: None. // // Returns: The next time at which the machine must be awake. // // Notes: //----------------------------------------------------------------------------- void CSchedWorker::SetNextWakeupTime() { #if DBG CHAR szDbgTime[40], szDbgTime2[40]; #endif // // Remember the time that we set the timer for. It is used on waking // to make sure we don't miss any runs. // m_ftLastWakeupSet = NextWakeupTime(GetLocalTimeAsFileTime()); if (m_hSystemWakeupTimer != NULL) { if (CompareFileTime(&m_ftLastWakeupSet, &MAX_FILETIME) < 0) { schDebugOut((DEB_TRACE, "SetNextWakeupTime: now %s, setting to %s\n", FileTimeString(GetLocalTimeAsFileTime(),szDbgTime2, 40), FileTimeString(m_ftLastWakeupSet, szDbgTime, 40))); // Convert to UTC FILETIME ft; LocalFileTimeToFileTime(&m_ftLastWakeupSet, &ft); LARGE_INTEGER li = { ft.dwLowDateTime, ft.dwHighDateTime }; if (! SetWaitableTimer( m_hSystemWakeupTimer, &li, 0, // not periodic NULL, NULL, TRUE)) // wake up system when signaled { ERR_OUT("SetNextWakeupTime SetWaitableTimer", HRESULT_FROM_WIN32(GetLastError())); } } else { CancelWakeup(); } } } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::CancelWakeup // // Synopsis: Cancels the wakeup timer. (Usually done when going into a // PAUSED state. Also done if there are no more jobs with // TASK_FLAG_SYSTEM_REQUIRED.) // // Arguments: None. // // Returns: // // Notes: //----------------------------------------------------------------------------- void CSchedWorker::CancelWakeup() { schDebugOut((DEB_TRACE, "Canceling wakeup timer\n")); if (m_hSystemWakeupTimer) { if (!CancelWaitableTimer(m_hSystemWakeupTimer)) { ERR_OUT("CancelWaitableTimer", GetLastError()); } } } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::SignalWakeupTimer // // Synopsis: Signals the wakeup timer. // // Arguments: None. // // Returns: // // Notes: //----------------------------------------------------------------------------- void CSchedWorker::SignalWakeupTimer() { schDebugOut((DEB_TRACE, "Signaling wakeup timer\n")); if (m_hSystemWakeupTimer != NULL) { // Signal the timer 1 time unit in the future (i.e. now) LARGE_INTEGER li = { 0xFFFFFFFF, 0xFFFFFFFF }; if (! SetWaitableTimer( m_hSystemWakeupTimer, &li, 0, // not periodic NULL, NULL, TRUE)) // wake up system when signaled { ERR_OUT("SignalWakeupTimer SetWaitableTimer", HRESULT_FROM_WIN32(GetLastError())); } } } //+---------------------------------------------------------------------------- // // Function: CalcWait // // Synopsis: return the time difference between the FILETIME params // // Arguments: [pftNow] // [pftThen] // // Returns: time difference in milliseconds // 0 if pftThen was before pftNow // //----------------------------------------------------------------------------- DWORD CalcWait(LPFILETIME pftNow, LPFILETIME pftThen) { if (CompareFileTime(pftNow, pftThen) >= 0) { // // Job run time is in the past. // return 0; } // // subtract now-time from job-time to get the wait in 100-nano-seconds unit // ULARGE_INTEGER uliNow, uliJob; uliNow.LowPart = pftNow->dwLowDateTime; uliNow.HighPart = pftNow->dwHighDateTime; uliJob.LowPart = pftThen->dwLowDateTime; uliJob.HighPart = pftThen->dwHighDateTime; __int64 n64Wait = uliJob.QuadPart - uliNow.QuadPart; // // convert to milliseconds // DWORD dwWait = (DWORD)(n64Wait / FILETIMES_PER_MILLISECOND); #if DBG == 1 SYSTEMTIME stNow, stRun; FileTimeToSystemTime(pftNow, &stNow); FileTimeToSystemTime(pftThen, &stRun); schDebugOut((DEB_TRACE, "Run time is %u:%02u\n", stRun.wHour, stRun.wMinute)); DWORD dwSeconds = dwWait / 1000; schDebugOut((DEB_TRACE, "*** Wait time to next run is %u:%02u:%02u (h:m:s)\n", dwSeconds / 3600, dwSeconds / 60 % 60, dwSeconds % 60)); #endif return dwWait; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::RunNextJobs // // Synopsis: Run the jobs at the top of the list that have the same run // time. // // Returns: hresults // //----------------------------------------------------------------------------- HRESULT CSchedWorker::RunNextJobs(void) { TRACE(CSchedWorker, RunNextJobs); FILETIME ftCurJob; if (m_WaitList.PeekHeadTime(&ftCurJob) != S_OK) { return S_FALSE; // list is empty } // // Set the beginning of any wait list we build in future to one second // past the scheduled run time of the last scheduled jobs we ran. // m_ftBeginWaitList = FTfrom64(FTto64(ftCurJob) + FILETIMES_PER_SECOND); CRunList * pJobList = new CRunList; if (pJobList == NULL) { LogServiceError(IDS_NON_FATAL_ERROR, ERROR_OUTOFMEMORY, IDS_HELP_HINT_CLOSE_APPS); ERR_OUT("RunNextJobs list allocation", E_OUTOFMEMORY); return E_OUTOFMEMORY; } // // Collect all jobs with the same start time as the first job. // FILETIME ftNextJob; BOOL fIdleWaitChanged = FALSE; while (m_WaitList.PeekHeadTime(&ftNextJob) == S_OK && CompareFileTime(&ftCurJob, &ftNextJob) == 0) { CRun * pRun = m_WaitList.Pop(); schAssert(pRun); if ((pRun->GetFlags() & TASK_FLAG_START_ONLY_IF_IDLE) && pRun->GetWait() > 0) { // // The job has to wait for an idle period before running, so // move it to the idle wait list. // schDebugOut((DEB_IDLE, "Time to run " FMT_TSTR ", but it needs a " "%d-minute idle period - moving to idle list\n", pRun->GetName(), pRun->GetWait())); m_IdleList.AddSortedByIdleWait(pRun); fIdleWaitChanged = TRUE; // Optimization: If idle detection is disabled, we will never get an // idle notification, so the run will stay in the idle list until // its deadline passes. This could cause a big accumulation of // runs in the idle list. It would be more space-efficient to just discard all // runs that are added to the idle list, or never generate runs // for tasks with TASK_FLAG_START_ONLY_IF_IDLE (and log one error // about them). } else { // // Move it to the list of jobs that we are about to run. // schDebugOut((DEB_IDLE, "Time to run " FMT_TSTR ", and it needs " "no idle period\n", pRun->GetName())); pJobList->Add(pRun); } } if (fIdleWaitChanged) { SetNextIdleNotification(m_IdleList.GetFirstWait()); } if (pJobList->GetFirstJob()->IsNull()) { // RunJobs won't accept an empty list delete pJobList; return S_OK; } else { schDebugOut((DEB_TRACE, "RunNextJobs: Running %s jobs\n", CFileTimeString(ftCurJob).sz())); HRESULT hr = RunJobs(pJobList); // RunJobs *should* handle deleting pJobList, even in failure cases schDebugOut((DEB_TRACE, "RunNextJobs: Done running %s jobs\n", CFileTimeString(ftCurJob).sz())); if (SUCCEEDED(hr)) { // // Save the last scheduled run time at which we ran jobs // ftCurJob = FTfrom64(FTto64(ftCurJob) + FILETIMES_PER_SECOND); SYSTEMTIME stCurJob; FileTimeToSystemTime(&ftCurJob, &stCurJob); WriteLastTaskRun(&stCurJob); } return hr; } } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::RunLogonJobs // // Synopsis: Run all jobs with a Logon trigger. // // Returns: hresults // //----------------------------------------------------------------------------- HRESULT CSchedWorker::RunLogonJobs(void) { TRACE(CSchedWorker, RunLogonJobs); HRESULT hr = S_OK; DWORD dwRet; HANDLE hFind; WIN32_FIND_DATA fd; hFind = FindFirstFile(m_ptszSearchPath, &fd); if (hFind == INVALID_HANDLE_VALUE) { dwRet = GetLastError(); if (dwRet == ERROR_FILE_NOT_FOUND) { // // No job files. // return S_OK; } else { return HRESULT_FROM_WIN32(dwRet); } } CJob * pJob = NULL; CRunList * pRunLogonList = new CRunList; if (pRunLogonList == NULL) { LogServiceError(IDS_NON_FATAL_ERROR, ERROR_OUTOFMEMORY, IDS_HELP_HINT_CLOSE_APPS); ERR_OUT("RunLogonJobs list allocation", E_OUTOFMEMORY); return E_OUTOFMEMORY; } do { hr = m_pSch->ActivateJob(fd.cFileName, &pJob, FALSE); if (FAILED(hr)) { LogTaskError(fd.cFileName, NULL, IDS_LOG_SEVERITY_WARNING, IDS_LOG_JOB_WARNING_CANNOT_LOAD, NULL, (DWORD)hr); ERR_OUT("RunLogonJobs Activate", hr); if (pJob) { pJob->Release(); } FindClose(hFind); delete pRunLogonList; return hr; } // // Check if job can run. // TODO: similar checks for account flags. // if (!pJob->IsFlagSet(TASK_FLAG_DISABLED) && pJob->IsFlagSet(JOB_I_FLAG_HAS_APPNAME)) { // // LoadTriggers will set or clear the JOB_I_FLAG_HAS_TRIGGERS flag // as appropriate. // hr = pJob->LoadTriggers(); if (FAILED(hr)) { LogTaskError(fd.cFileName, NULL, IDS_LOG_SEVERITY_WARNING, IDS_LOG_JOB_WARNING_CANNOT_LOAD, NULL, (DWORD)hr); ERR_OUT("RunLogonJobs, pJob->LoadTriggers", hr); pJob->Release(); FindClose(hFind); delete pRunLogonList; return hr; } hr = pJob->IfLogonJobAddToList(fd.cFileName, pRunLogonList, &m_IdleList); if (FAILED(hr)) { LogServiceError(IDS_NON_FATAL_ERROR, (DWORD)hr); ERR_OUT("RunLogonJobs IfLogonJobAddToList", hr); pJob->Release(); FindClose(hFind); delete pRunLogonList; return hr; } } if (!FindNextFile(hFind, &fd)) { dwRet = GetLastError(); if (dwRet == ERROR_NO_MORE_FILES) { break; } else { LogServiceError(IDS_NON_FATAL_ERROR, dwRet); ERR_OUT("RunLogonJobs, FindNextFile", dwRet); pJob->Release(); FindClose(hFind); delete pRunLogonList; return HRESULT_FROM_WIN32(dwRet); } } } while (SUCCEEDED(hr)); pJob->Release(); FindClose(hFind); // // If any jobs with a TASK_EVENT_TRIGGER_AT_LOGON trigger were found, then // run them now. // if (!pRunLogonList->GetFirstJob()->IsNull()) { hr = RunJobs(pRunLogonList); // RunJobs *should* handle deleting pRunLogonList, even in failure cases if (FAILED(hr)) { LogServiceError(IDS_NON_FATAL_ERROR, (DWORD)hr); ERR_OUT("Running idle jobs", hr); } } else { delete pRunLogonList; } return hr; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::RunIdleJobs // // Synopsis: Run all jobs with an OnIdle trigger. // // Returns: hresults // //----------------------------------------------------------------------------- HRESULT CSchedWorker::RunIdleJobs(void) { TRACE(CSchedWorker, RunIdleJobs); HRESULT hr = S_OK; CRun *pRun, *pNext; // // Move pending idle runs, if any, into the idle list. (See SubmitIdleRun.) // if (! m_PendingList.IsEmpty()) { EnterCriticalSection(&m_PendingListCritSec); for (pRun = m_PendingList.GetFirstJob(); !pRun->IsNull(); pRun = pNext) { pNext = pRun->Next(); schDebugOut((DEB_IDLE, "Moving " FMT_TSTR " from pending to idle list\n", pRun->GetName())); pRun->UnLink(); m_IdleList.AddSortedByIdleWait(pRun); } LeaveCriticalSection(&m_PendingListCritSec); } DWORD wCumulativeIdleTime = GetTimeIdle(); CRunList * pRunIdleList = new CRunList; if (pRunIdleList == NULL) { LogServiceError(IDS_NON_FATAL_ERROR, ERROR_OUTOFMEMORY, IDS_HELP_HINT_CLOSE_APPS); ERR_OUT("RunIdleJobs list allocation", E_OUTOFMEMORY); return E_OUTOFMEMORY; } // // Use the critical section to protect the idle struct assignments since // assignments can be made asynchronously from two different threads. This // is called on the main event-loop/state-machine thread. // EnterCriticalSection(&m_SvcCriticalSection); // // Run all unexpired tasks whose idle wait is less than or equal // to the current cumulative idle time. But don't start a task // more than once in any period of idleness. // FILETIME ftNow; SYSTEMTIME stNow; GetLocalTime(&stNow); SystemTimeToFileTime(&stNow, &ftNow); for (pRun = m_IdleList.GetFirstJob(); !pRun->IsNull() && pRun->GetWait() <= wCumulativeIdleTime; pRun = pNext) { pNext = pRun->Next(); if (pRun->m_fStarted) { continue; } if (CompareFileTime(pRun->GetDeadline(), &ftNow) < 0) { // // The run has missed its deadline - delete it. // (This is also done when rebuilding the wait list.) // schDebugOut((DEB_IDLE, "Run of " FMT_TSTR " has missed its deadline - deleting\n", pRun->GetName())); // // Log the reason for not running. // LogTaskError(pRun->GetName(), NULL, IDS_LOG_SEVERITY_WARNING, IDS_LOG_JOB_WARNING_NOT_IDLE, &stNow); pRun->UnLink(); // // If the system needed to stay awake to run this task, decrement // the thread's wake count. (We know that this is always called // by the worker thread.) // if (pRun->IsFlagSet(TASK_FLAG_SYSTEM_REQUIRED)) { WrapSetThreadExecutionState(FALSE, "CSchedWorker::RunIdleJobs 1"); } delete pRun; continue; } if (pRun->IsIdleTriggered()) { // // Run it, and keep it in the idle list // schDebugOut((DEB_IDLE, "COPYING idle-triggered run of " FMT_TSTR " to run list\n", pRun->GetName())); hr = pRunIdleList->AddCopy(pRun); if (FAILED(hr)) { LogServiceError(IDS_NON_FATAL_ERROR, ERROR_OUTOFMEMORY, IDS_HELP_HINT_CLOSE_APPS); ERR_OUT("RunIdleJobs CRun allocation", E_OUTOFMEMORY); LeaveCriticalSection(&m_SvcCriticalSection); delete pRunIdleList; return E_OUTOFMEMORY; } pRun->m_fStarted = TRUE; } else { // // Run it, and remove it from the idle list // schDebugOut((DEB_IDLE, "MOVING run of " FMT_TSTR " to run list\n", pRun->GetName())); pRun->UnLink(); // // If the system needed to stay awake to run this task, decrement // the thread's wake count. (We know that this is always called // by the worker thread.) // if (pRun->IsFlagSet(TASK_FLAG_SYSTEM_REQUIRED)) { WrapSetThreadExecutionState(FALSE, "CSchedWorker::RunIdleJobs 2"); } pRunIdleList->Add(pRun); } } // // Set the next idle wait time. // WORD wIdleWait = m_IdleList.GetFirstWait(); LeaveCriticalSection(&m_SvcCriticalSection); // // If more idle-trigger tasks to run, then set the wait time for // their notification. // SetNextIdleNotification(wIdleWait); // // Run any tasks with a matching idle wait time. // if (!pRunIdleList->GetFirstJob()->IsNull()) { hr = RunJobs(pRunIdleList); // RunJobs *should* handle deleting pRunIdleList, even in failure cases if (FAILED(hr)) { LogServiceError(IDS_NON_FATAL_ERROR, (DWORD)hr); ERR_OUT("Running idle jobs", hr); } } else { delete pRunIdleList; } return hr; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::SubmitIdleRun // // Synopsis: Submits a CRun for insertion in the idle list. // // Notes: This method is called by job processor threads for jobs with // TASK_FLAG_RESTART_ON_IDLE_RESUME set. // //----------------------------------------------------------------------------- void CSchedWorker::SubmitIdleRun(CRun * pRun) { // // Insert the run in the pending list. // We don't insert directly into the idle list because we want to avoid // having a critical section to guard the idle list. // schAssert(pRun->GetWait() != 0); EnterCriticalSection(&m_PendingListCritSec); schDebugOut((DEB_IDLE, "Submitting " FMT_TSTR " to pending idle list\n", pRun->GetName())); m_PendingList.Add(pRun); LeaveCriticalSection(&m_PendingListCritSec); // // Wake up the main thread, which will move the run into the idle list // and register for idle notification if necessary. // SetEvent(m_hOnIdleEvent); } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::CControlQueue methods // // Synopsis: Ensure that controls sent to the service are processed in the // order received // //----------------------------------------------------------------------------- CSchedWorker::CControlQueue::~CControlQueue() { DeleteCriticalSection(&_Lock); while (!IsListEmpty(&_ListHead)) { QueueEntry * pEntry = CONTAINING_RECORD(_ListHead.Flink, QueueEntry, Links); RemoveEntryList(&pEntry->Links); delete pEntry; } } void CSchedWorker::CControlQueue::AddEntry(DWORD dwControl) { QueueEntry * pNew = new QueueEntry; if (pNew == NULL) { LogServiceError(IDS_NON_FATAL_ERROR, GetLastError()); ERR_OUT("new QueueEntry", GetLastError()); return; } pNew->dwControl = dwControl; EnterCriticalSection(&_Lock); InsertTailList(&_ListHead, &pNew->Links); if (!SetEvent(_Event)) { LogServiceError(IDS_NON_FATAL_ERROR, GetLastError()); ERR_OUT("CControlQueue::AddEntry: SetEvent", GetLastError()); } LeaveCriticalSection(&_Lock); } DWORD CSchedWorker::CControlQueue::GetEntry() { DWORD dwControl; EnterCriticalSection(&_Lock); if (IsListEmpty(&_ListHead)) { dwControl = 0; } else { QueueEntry * pEntry = CONTAINING_RECORD(_ListHead.Flink, QueueEntry, Links); dwControl = pEntry->dwControl; RemoveEntryList(&pEntry->Links); delete pEntry; // // If there are still controls in the queue, make sure we get // signaled again. // if (!IsListEmpty(&_ListHead)) { if (!SetEvent(_Event)) { LogServiceError(IDS_NON_FATAL_ERROR, GetLastError()); ERR_OUT("CControlQueue::GetEntry: SetEvent", GetLastError()); } } } LeaveCriticalSection(&_Lock); return dwControl; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::OnIdleEvent // // Synopsis: Called when the machine's idle state changes. // // Arguments: [fIdle] - set to true if receiving an idle time notification, // false if leaving the idle state. // // Returns: S_OK unless there is a SetEvent error. // //----------------------------------------------------------------------------- HRESULT CSchedWorker::OnIdleEvent(BOOL fIdle) { TRACE(CSchedWorker, OnIdleEvent); HRESULT hr = S_OK; if (fIdle) { // // Notify the main service loop that the machine has entered the idle // state. // schDebugOut((DEB_IDLE, "Setting idle event\n")); if (!SetEvent(m_hOnIdleEvent)) { hr = HRESULT_FROM_WIN32(GetLastError()); LogServiceError(IDS_NON_FATAL_ERROR, (DWORD)hr); ERR_OUT("OnIdleChange: SetEvent", hr); } } if (!fIdle) { // // Notify the main service loop that idle has been lost. // schDebugOut((DEB_IDLE, "Setting idle loss event\n")); if (!SetEvent(m_hIdleLossEvent)) { hr = HRESULT_FROM_WIN32(GetLastError()); LogServiceError(IDS_NON_FATAL_ERROR, (DWORD)hr); ERR_OUT("OnIdleChange: SetEvent(IdleLoss)", hr); } // // // Notify the job processor to kill any jobs with the // TASK_FLAG_KILL_ON_IDLE_END flag set. // CJobProcessor * pjp; for (pjp = gpJobProcessorMgr->GetFirstProcessor(); pjp != NULL; ) { pjp->KillIfFlagSet(TASK_FLAG_KILL_ON_IDLE_END); CJobProcessor * pjpNext = pjp->Next(); pjp->Release(); pjp = pjpNext; } } return hr; } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::CSchedWorker // // Synopsis: ctor // //----------------------------------------------------------------------------- CSchedWorker::CSchedWorker(void) : m_pSch(NULL), m_hChangeNotify(INVALID_HANDLE_VALUE), m_hServiceControlEvent(NULL), m_hOnIdleEvent(NULL), m_hIdleLossEvent(NULL), m_hSystemWakeupTimer(NULL), m_hMiscBlockEvent(NULL), m_ptszSearchPath(NULL), m_ptszSvcDir(NULL), m_cJobs(0) { TRACE(CSchedWorker, CSchedWorker); InitializeCriticalSection(&m_SvcCriticalSection); InitializeCriticalSection(&m_PendingListCritSec); } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::~CSchedWorker // // Synopsis: dtor // //----------------------------------------------------------------------------- CSchedWorker::~CSchedWorker(void) { TRACE(CSchedWorker, ~CSchedWorker); // // Free resources and close handles. // if (m_pSch != NULL) { m_pSch->Release(); } if (m_hChangeNotify != INVALID_HANDLE_VALUE) { FindCloseChangeNotification(m_hChangeNotify); m_hChangeNotify = INVALID_HANDLE_VALUE; } if (m_hServiceControlEvent != NULL) { CloseHandle(m_hServiceControlEvent); m_hServiceControlEvent = NULL; } if (m_hOnIdleEvent != NULL) { CloseHandle(m_hOnIdleEvent); m_hOnIdleEvent = NULL; } if (m_hIdleLossEvent != NULL) { CloseHandle(m_hIdleLossEvent); m_hIdleLossEvent = NULL; } if (m_hSystemWakeupTimer != NULL) { CloseHandle(m_hSystemWakeupTimer); m_hSystemWakeupTimer = NULL; } if (m_hMiscBlockEvent != NULL) { CloseHandle(m_hMiscBlockEvent); m_hMiscBlockEvent = NULL; } DeleteCriticalSection(&m_PendingListCritSec); DeleteCriticalSection(&m_SvcCriticalSection); if (m_ptszSearchPath) { delete [] m_ptszSearchPath; } if (m_ptszSvcDir != NULL) { delete [] m_ptszSvcDir; } m_WaitList.FreeList(); } //+---------------------------------------------------------------------------- // // Member: CSchedWorker::SetEndOfWaitListPeriod // // Synopsis: Advance the passed in time to the end of the current run // period. // //----------------------------------------------------------------------------- void CSchedWorker::SetEndOfWaitListPeriod(LPSYSTEMTIME pstEnd) { // // Set pstEnd to a few seconds after midnight so that midnight jobs are // included. Midnight is 0:0:0 of the next day. // pstEnd->wHour = pstEnd->wMinute = 0; pstEnd->wSecond = 10; IncrementDay(pstEnd); // // Save it for use in GetNextRunWait. // m_stEndOfWaitListPeriod = *pstEnd; } //+--------------------------------------------------------------------------- // // Member: CSchedWorker::ActivateWithRetry // // Synopsis: Load the job object from disk with failure retry. // // Arguments: [ptszName] - name of the job to activate. // [pJob] - Job object to activate. // [fFullActivate] - load the entire object? // //---------------------------------------------------------------------------- HRESULT CSchedWorker::ActivateWithRetry(LPTSTR ptszName, CJob ** ppJob, BOOL fFullActivate) { HRESULT hr; // // Load the job object. If there are sharing violations, retry two times. // for (int i = 0; i < 3; i++) { hr = m_pSch->ActivateJob(ptszName, ppJob, fFullActivate); if (SUCCEEDED(hr)) { return S_OK; } if (hr != HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION)) { // // If we have a failure other than sharing violation, we will // retry anyway after reporting the error. // ERR_OUT("ActivateWithRetry, Loading job object", hr); } // // Wait 300 milliseconds before trying again. // Sleep(300); } return hr; } //+--------------------------------------------------------------------------- // // Function: EnsureTasksFolderSecurity // // Synopsis: at this point, we assume the task folder exists // // Arguments: voidness // // Returns: HRESULT // //---------------------------------------------------------------------------- HRESULT EnsureTasksFolderSecurity(void) { HRESULT hr = S_OK; PSECURITY_DESCRIPTOR pSD = NULL; WCHAR* pwszSDDL = NULL; OSVERSIONINFOEX verInfo; verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!GetVersionEx((LPOSVERSIONINFOW)&verInfo)) return E_FAIL; if (verInfo.wProductType == VER_NT_WORKSTATION) pwszSDDL = L"D:P(A;OICIIO;FA;;;CO)(A;;0x1200ab;;;AU)(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)" L"S:(AU;SAFAOICI;FWDCSDWDWO;;;WD)(AU;SAFAOICI;FWDCSDWDWO;;;AN)"; else pwszSDDL = L"D:P(A;OICIIO;FA;;;CO)(A;;0x1200ab;;;BO)(A;;0x1200ab;;;SO)(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)" L"S:(AU;SAFAOICI;FWDCSDWDWO;;;WD)(AU;SAFAOICI;FWDCSDWDWO;;;AN)"; // // generate SD to be used for tasks folder // if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(pwszSDDL, SDDL_REVISION_1, &pSD, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); return hr; } if (SUCCEEDED(hr)) { if (!SetFileSecurity(g_TasksFolderInfo.ptszPath, DACL_SECURITY_INFORMATION, pSD)) hr = HRESULT_FROM_WIN32(GetLastError()); } if (pSD) LocalFree(pSD); return hr; } //+--------------------------------------------------------------------------- // // Member: CSchedWorker::InitialDirScan // // Synopsis: Do the startup BuildWaitList and create the change events. // //---------------------------------------------------------------------------- HRESULT CSchedWorker::InitialDirScan(void) { HRESULT hr; DWORD dwFirstBoot = 0; DWORD dwType; DWORD cb = sizeof(dwFirstBoot); HKEY hSchedKey = NULL; LONG lErr; // // Find out if this is the first boot by checking the FirstBoot // value under the schedule agent key // lErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, SCH_AGENT_KEY, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hSchedKey); if (lErr == ERROR_SUCCESS) { // // Get the first boot value // lErr = RegQueryValueEx(hSchedKey, SCH_FIRSTBOOT_VALUE, NULL, &dwType, (LPBYTE) &dwFirstBoot, &cb); if (lErr == ERROR_SUCCESS && dwFirstBoot != 0) { schDebugOut((DEB_TRACE, "First boot -- will sign At jobs\n")); } } // ensure task folder security is set properly upon first bootup if (dwFirstBoot) { hr = EnsureTasksFolderSecurity(); if (FAILED(hr)) { LogServiceError(IDS_FATAL_ERROR, (DWORD)hr, 0); ERR_OUT("InitialDirScan, EnsureTasksFolderSecurity", hr); RegCloseKey(hSchedKey); return hr; } } // // Do the initial job folder read -- a non-zero dwValue means // this is the first boot of the Task Scheduler on NT5. // hr = BuildWaitList(TRUE, TRUE, dwFirstBoot); if (FAILED(hr)) { LogServiceError(IDS_FATAL_ERROR, (DWORD)hr, 0); ERR_OUT("InitialDirScan, BuildWaitList", hr); RegCloseKey(hSchedKey); return hr; } if (hSchedKey != NULL) { // // No more need for this reg value // RegDeleteValue(hSchedKey, SCH_FIRSTBOOT_VALUE); RegCloseKey(hSchedKey); } // // Set up the folder change notification. // // If a job is created, deleted, renamed, or modified then // m_hChangeNotify will be triggered. // // This is done after the initial call to BuildWaitList since there is no // reason to field change notifications until the main loop is entered. // m_hChangeNotify = FindFirstChangeNotification( g_TasksFolderInfo.ptszPath, FALSE, // no subdirs FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE); if (m_hChangeNotify == INVALID_HANDLE_VALUE) { ULONG ulLastError = GetLastError(); LogServiceError(IDS_FATAL_ERROR, ulLastError, 0); ERR_OUT("InitialDirScan, FindFirstChangeNotification", ulLastError); return HRESULT_FROM_WIN32(ulLastError); } return S_OK; } //+--------------------------------------------------------------------------- // // Function: ReportMissedRuns // // Synopsis: Pops up a message indicating that some runs were missed, and // logs this to the event log and task scheduler log. // // Arguments: [pstLastRun], [pstNow] - times between which runs were missed. // //---------------------------------------------------------------------------- void ReportMissedRuns(const SYSTEMTIME * pstLastRun, const SYSTEMTIME * pstNow) { // // Write to the task scheduler log // LogMissedRuns(pstLastRun, pstNow); // // Spin a thread to popup a message. // Suppress the popup if NoPopupsOnBoot is indicated in the registry. // DWORD PopupStatus; BOOL bPopups = TRUE; // FALSE means suppress popups on boot HKEY WindowsKey=NULL; PopupStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, CONTROL_WINDOWS_KEY, 0, KEY_READ, &WindowsKey); if (PopupStatus == ERROR_SUCCESS) { DWORD Type; DWORD Data; DWORD cbData = sizeof(Data); PopupStatus = RegQueryValueEx(WindowsKey, NOBOOTPOPUPS_VALUENAME, NULL, &Type, (LPBYTE) &Data, &cbData); // // Popups are suppressed if the NOBOOTPOPUPS_VALUENAME value is // present, is a REG_DWORD and is non-zero. // if (PopupStatus == ERROR_SUCCESS && Type == REG_DWORD && Data != 0) { bPopups = FALSE; } RegCloseKey(WindowsKey); } if (bPopups && // // If the message has already been popped up on the screen, and hasn't // been dismissed yet, don't pop up another one. // ! InterlockedExchange(&g_fPopupDisplaying, TRUE)) { DWORD dwThreadId; HANDLE hThread = CreateThread( NULL, 0L, (LPTHREAD_START_ROUTINE) PopupThread, 0, // parameter 0L, &dwThreadId ); if (hThread == NULL) { ERR_OUT("CreateThread PopupThread", GetLastError()); g_fPopupDisplaying = FALSE; } else { CloseHandle(hThread); } } } //+--------------------------------------------------------------------------- // // Function: PopupThread // // Synopsis: Pops up a message indicating that some runs were missed. // // Arguments: [lpParameter] - ignored. // //---------------------------------------------------------------------------- DWORD WINAPI PopupThread(LPVOID lpParameter) { CHAR szTitle[SCH_MEDBUF_LEN]; CHAR szMsg[SCH_BIGBUF_LEN]; if (LoadStringA(g_hInstance, IDS_POPUP_SERVICE_TITLE, szTitle, SCH_MEDBUF_LEN) == 0) { CHECK_HRESULT(HRESULT_FROM_WIN32(GetLastError())); } else if (LoadStringA(g_hInstance, IDS_POPUP_RUNS_MISSED, szMsg, SCH_BIGBUF_LEN) == 0) { CHECK_HRESULT(HRESULT_FROM_WIN32(GetLastError())); } else { MessageBoxA(NULL, szMsg, szTitle, MB_OK | MB_SETFOREGROUND | MB_ICONEXCLAMATION | MB_SERVICE_NOTIFICATION | MB_SYSTEMMODAL); } g_fPopupDisplaying = FALSE; return 0; }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
9c64a0044186ec5ca9ae944f2daa108523354cc2
0d4d18a6132bfe07579cd8f99f05cba6787bd4d3
/include/mockitopp/detail/util/tr1_type_traits.hpp
6e8b3f68df96111708062dac0f51240a48325c67
[ "MIT" ]
permissive
tpounds/mockitopp
a9865b1dcad39533d4bdbfb01a222631f6847069
775b151fa746c81c8762faea2de3429d6f3f46af
refs/heads/master
2021-08-28T12:46:43.967092
2021-08-14T18:45:12
2021-08-14T19:00:37
32,499,033
87
12
MIT
2019-08-31T16:13:10
2015-03-19T03:37:18
C++
UTF-8
C++
false
false
1,490
hpp
#ifndef __MOCKITOPP_TR1_TYPE_TRAITS_HPP__ #define __MOCKITOPP_TR1_TYPE_TRAITS_HPP__ namespace mockitopp { namespace detail { /** * Simple subset adaptation of tr1 type_traits * for internal mockitopp use. * * @author Trevor Pounds * @see http://www.boost.org/doc/libs/release/libs/type_traits/ */ namespace tr1 { #ifdef _MSC_VER // C4181: qualifier applied to reference type #pragma warning(disable:4181) #endif // std::tr1::add_const template <typename T> struct add_const { typedef const T type; }; template <typename T> struct add_const<const T> { typedef const T type; }; #ifdef _MSC_VER #pragma warning(default:4181) #endif // std::tr1::remove_const template <typename T> struct remove_const { typedef T type; }; template <typename T> struct remove_const<const T> { typedef T type; }; // std::tr1::add_reference template <typename T> struct add_reference { typedef T type; }; template <typename T> struct add_reference<T&> { typedef T& type; }; // std::tr1::remove_reference template <typename T> struct remove_reference { typedef T type; }; template <typename T> struct remove_reference<T&> { typedef T type; }; } // namespace tr1 } // namespace detail } // namespace mockitopp #endif //__MOCKITOPP_TR1_TYPE_TRAITS_HPP__
[ "trevor.pounds@gmail.com" ]
trevor.pounds@gmail.com
390880d2d4154c6bc38854486dbaf5111c9f55c6
e5d5933f7445d318bb83012fe7ce391e04f16023
/src/Volterra.h
7f3251137e9f89972daf66fc2ddc0afea5bfa96d
[ "MIT" ]
permissive
epsilonleqzero/Cpp-Runge-Kutta-Fehlberg
e9fb7000888a1251dbfebadc01a14a7b48e79852
4e1aeb1d0231acbb12c94617fb79a33b3f542726
refs/heads/master
2021-06-09T03:12:00.252393
2016-08-15T10:34:58
2016-08-15T10:34:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
450
h
/* * Volterra.h * * Created on: Aug 6, 2016 * Author: Devils */ #include<vector> #include<armadillo> #include "OdeFun.h" #ifndef VOLTERRA_H_ #define VOLTERRA_H_ class Volterra: public OdeFun { public: Volterra(); virtual ~Volterra(); Volterra(std::vector<double> params); arma::vec evalF(double t,arma::vec x); int dim; private: std::vector<double> params; double a; double b; double c; double d; }; #endif /* VOLTERRA_H_ */
[ "tkwan@impulse.net" ]
tkwan@impulse.net
df8b93cf92566bb8d891bca729ed3ebaf3902254
3709ea68d237ef6dc73a649e0f13fdaca9f1f8af
/Related code/AssemblyInfo.cpp
c9e97097c7b9e8eeef1d5a3e6ce58d243bea2f35
[]
no_license
simonyang0701/ENG-2002-Computer-Programming
8b7ae0911a3345591a3dff76bcfdf41fb4232804
8664feb189ca9ac39fe89bca5ef472396756aad4
refs/heads/master
2021-07-03T00:50:14.931685
2020-09-27T00:03:29
2020-09-27T00:03:29
175,833,059
1
0
null
null
null
null
UTF-8
C++
false
false
1,368
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute("miniprojectfirstassignment")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("miniprojectfirstassignment")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2015")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
[ "noreply@github.com" ]
noreply@github.com
2c82d7c8a8e65f7d1c25cee40bf8375a8108e960
a8f69afb2d2ba08513df1a8bd16c165b000d224b
/src/tuple.cpp
a346b181610f065286d441d615d0b451405e9f6b
[]
no_license
nhtranngoc/yart
7b3de558ab407f3f91d9eba0eebafe2d32b74054
45872b235ce53b9b989dff59c687f29efb415719
refs/heads/master
2020-09-25T13:57:58.323525
2020-06-12T03:46:00
2020-06-12T03:46:00
226,017,717
5
0
null
null
null
null
UTF-8
C++
false
false
2,460
cpp
#include "tuple.h" Tuple::Tuple(float x, float y, float z, float w) { this->x = x; this->y = y; this->z = z; this->w = w; } Tuple::Tuple() { this->x = 0; this->y = 0; this->z = 0; this->w = 0; } bool operator == (Tuple const &t1, Tuple const &t2) { return ( equal(t1.x, t2.x) && equal(t1.y, t2.y) && equal(t1.z, t2.z) && equal(t1.w, t2.w)); } Tuple operator + (Tuple const &t1, Tuple const &t2) { return Tuple( t1.x + t2.x, t1.y + t2.y, t1.z + t2.z, t1.w + t2.w); } Tuple operator - (Tuple const &t1, Tuple const &t2) { return Tuple( t1.x - t2.x, t1.y - t2.y, t1.z - t2.z, t1.w - t2.w ); } Tuple operator - (Tuple const &t) { return Tuple( -t.x, -t.y, -t.z, -t.w ); } Tuple operator * (Tuple const &t, float const s) { return Tuple( t.x * s, t.y * s, t.z * s, t.w * s ); } Tuple operator * (Tuple const &t1, Tuple const &t2) { return Tuple( t1.x * t2.x, t1.y * t2.y, t1.z * t2.z, t1.w * t2.z ); } Tuple operator / (Tuple const &t, float const s) { return Tuple( t.x / s, t.y / s, t.z / s, t.w / s ); } bool Tuple::IsPoint() { return equal(this->w, 1.0); } bool Tuple::IsVector() { return equal(this->w, 0.0); } float Tuple::Magnitude() { return (sqrt( this->x * this->x + this->y * this->y + this->z * this->z + this->w * this->w )); } Tuple Tuple::Normalize() { float m = this->Magnitude(); return Tuple( this->x / m, this->y / m, this->z / m, this->w / m ); } float Tuple::Dot(Tuple const &t) { return ( this->x * t.x + this->y * t.y + this->z * t.z + this->w * t.w ); } Tuple Tuple::Cross(Tuple const &t) { return Vector( this->y * t.z - this->z * t.y, this->z * t.x - this->x * t.z, this->x * t.y - this->y * t.x ); } Tuple Tuple::Reflect(Tuple const &n) { return *(this) - n * 2 * this->Dot(n); } Tuple Point(float x, float y, float z) { Tuple tmp(x,y,z,1.0); return tmp; } Tuple Vector(float x, float y, float z) { Tuple tmp(x,y,z,0.0); return tmp; } bool equal(float x, float y) { return (fabs(x -y) < EPSILON); }
[ "nhtranngoc@wpi.edu" ]
nhtranngoc@wpi.edu
e9f4e746524c0e16a59a7f1e98bb3ac1e79a15a1
1711520715cb5e70b4265b8faed13261670db2c5
/8.域名及网络地址/gethostbyaddr.cpp
e9f7f80449c0209948a0b769151220c2b75a2462
[]
no_license
Starry0/TCP-IP
012801946840858c768cc110a5dc37150bd730a6
242b48fb12dc4c4b61e8fb99ab5fa95794cca739
refs/heads/master
2020-04-27T04:40:55.581698
2019-03-25T02:29:10
2019-03-25T02:29:10
174,053,160
0
0
null
null
null
null
UTF-8
C++
false
false
1,113
cpp
// // Created by starry on 19-3-16. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <netdb.h> void error_handling(char *message); int main(int argc, char *argv[]) { int i; struct hostent *host; struct sockaddr_in addr; if(argc != 2) { printf("Usage : %s <IP> \n",argv[0]); exit(1); } memset(&addr, 0, sizeof(addr)); addr.sin_addr.s_addr = inet_addr(argv[1]); host = gethostbyaddr((char*)&addr.sin_addr, 4, AF_INET); if(!host) error_handling("gethost....error"); printf("Official name : %s \n", host->h_name); for(i = 0; host->h_aliases[i]; i ++) printf("Aliases %d: %s \n",i+1,host->h_aliases[i]); printf("Address type: %s \n", (host->h_addrtype == AF_INET)?"AF_INET":"AFINET6"); for(i = 0; host->h_addr_list[i]; i ++) printf("IP addr %d: %s \n", i+1, inet_ntoa(*(struct in_addr*)host->h_addr_list[i])); return 0; } void error_handling(char *message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
[ "1173298382@qq.com" ]
1173298382@qq.com
79bb2b69bb335d7a643c92478619e72360c33863
45d40c30b11d2f4c0e9e59fe4f6381055c0b97bd
/Tempus Fugit/Graph Theory/TreeHash.cpp
f12737c8fff495e8a849e7208585fcb2fab029fa
[]
no_license
volzkzg/Tempus-Fugit-Code-Machine
e585dfa357747b0bb79f9e30a0112f064ff15d47
d209465ab5858b87f3b89e04d33cb78b0b6912ab
refs/heads/master
2021-07-09T23:32:10.256317
2017-01-16T08:07:06
2017-01-16T08:07:06
39,577,162
2
2
null
null
null
null
UTF-8
C++
false
false
3,742
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <map> #include <queue> using namespace std; const int mm = 1051697, p = 1e9 + 9, q = 1e9 + 7; const int N = 100000 + 10; vector<int> vec[N]; int n, size[N], mark[N], deg[N], father[N]; long long f[N], g[N], rtp[N], rtq[N]; map<pair<long long, long long>, int> mp; struct Node { int a, b, v; Node() {} Node(int _a, int _b, int _v) { a = _a, b = _b, v = _v; } bool operator < (const Node &rhs) const { if (a == rhs.a ) return b < rhs.b; return a < rhs.a; } }; struct HashNode { int pos; long long val1, val2; HashNode() {} HashNode(int _pos, long long _val1, long long _val2) { pos = _pos; val1 = _val1; val2 = _val2; } bool operator < (const HashNode &rhs) const { if (val1 == rhs.val1) return val2 < rhs.val2; return val1 < rhs.val1; } }; void hashwork(int u) { vector<Node> data; size[u] = 1; for (int i = 0; i < (int)vec[u].size(); ++i) { int v = vec[u][i]; hashwork(v); data.push_back(Node(f[v], g[v], size[v])); size[u] += size[v]; } data.push_back(Node(1, 1, size[u])); sort(data.begin(), data.end()); int len = 0; f[u] = 1; for (int i = 0; i < (int)data.size(); ++i) { f[u] = ((f[u] * data[i].a) % p * rtp[len]) % p; g[u] = ((g[u] * data[i].b) % q + rtq[len]) % q; len += data[i].v; } } int main() { ios::sync_with_stdio(false); rtp[0] = rtq[0] = 1; for (int i = 1; i < N; ++i) { rtp[i] = (rtp[i - 1] * mm) % p; rtq[i] = (rtq[i - 1] * mm) % q; } queue<int> que; cin >> n; for (int v = 2; v <= n; ++v) { int u; cin >> u; vec[u].push_back(v); father[v] = u; deg[u]++; } memset(size, 0, sizeof(size)); memset(f, 0, sizeof(f)); memset(g, 0, sizeof(g)); for (int i = 1; i <= n; ++i) if (deg[i] == 0) que.push(i); while (!que.empty()) { int u = que.front(); //cout << u << endl; que.pop(); deg[father[u]]--; if (deg[father[u]] == 0) que.push(father[u]); vector<Node> data; size[u] = 1; for (int i = 0; i < (int)vec[u].size(); ++i) { int v = vec[u][i]; //hashwork(v); data.push_back(Node(f[v], g[v], size[v])); size[u] += size[v]; } data.push_back(Node(1, 1, size[u])); sort(data.begin(), data.end()); int len = 0; f[u] = 1; for (int i = 0; i < (int)data.size(); ++i) { f[u] = ((f[u] * data[i].a) % p * rtp[len]) % p; g[u] = ((g[u] * data[i].b) % q + rtq[len]) % q; len += data[i].v; } } //hashwork(1); /* vector<HashNode> ans; for (int i = 1; i <= n; ++i) { ans.push_back(HashNode(i, f[i], g[i])); } sort(ans.begin(), ans.end()); int tot = 0; for (int i = 0, j; i < (int)ans.size(); i = j) { ++tot; for (j = i; j < (int)ans.size() && (ans[j].val1 == ans[i].val1 && ans[j].val2 == ans[i].val2); ++j) mark[ans[j].pos] = tot; } */ int tot = 0; for (int i = 1; i <= n; ++i) { pair<long long, long long> pr = make_pair(f[i], g[i]); if (mp.count(pr) == 0) { mp[pr] = ++tot; mark[i] = tot; } else { mark[i] = mp[pr]; } } for (int i = 1; i <= n; ++i) { cout << mark[i]; if (i == n) cout << endl; else cout << " "; } return 0; }
[ "volz.kz.g@gmail.com" ]
volz.kz.g@gmail.com
cd97d9e2fcee6a061f0d97dfdab7bb28ed97dab5
20537d05b4b90283c17e183367a832422682b548
/stub/stub.cpp
74e37434c508e0eaad68c150cf04e9ed4a7621b1
[]
no_license
catsay217994/15pbpack
25d1ceba3b1292cc3a3f2016bf44fe8c13582c5c
45af94bf280a002741fdc4b25019c7838e92afa6
refs/heads/master
2020-04-08T11:58:15.092632
2018-10-31T13:05:34
2018-10-31T13:05:34
null
0
0
null
null
null
null
GB18030
C++
false
false
2,847
cpp
#include <Windows.h> #pragma comment(linker,"/merge:.data=.text") #pragma comment(linker,"/merge:.rdata=.text") //#pragma comment(linker,"/merge:.tls=.text") #pragma comment(linker, "/section:.text,RWE") #include "Conf.h" int WINAPI DllMain(HMODULE, LPVOID, int) { return TRUE; } //获取DOS头 IMAGE_DOS_HEADER* getDosHeader(_In_ char* pFileData) { return (IMAGE_DOS_HEADER *)pFileData; } // 获取NT头 IMAGE_NT_HEADERS* getNtHeader(_In_ char* pFileData) { return (IMAGE_NT_HEADERS*)(getDosHeader(pFileData)->e_lfanew + (SIZE_T)pFileData); } //获取文件头 IMAGE_FILE_HEADER* getFileHeader(_In_ char* pFileData) { return &getNtHeader(pFileData)->FileHeader; } //获取扩展头 IMAGE_OPTIONAL_HEADER* getOptionHeader(_In_ char* pFileData) { return &getNtHeader(pFileData)->OptionalHeader; } typedef LPVOID* (WINAPI* FnGetProcAddress)(HMODULE, const char*); FnGetProcAddress pfnGetProcAddress; typedef HMODULE(WINAPI* FnLoadLibraryA)(const char*); FnLoadLibraryA pfnLoadLibraryA; typedef DWORD(WINAPI* FnMessageBoxA)(HWND, const char*, const char*, UINT); FnMessageBoxA pfnMessageBoxA; DWORD MyStrcmp(const char* dest, const char* src) { int i = 0; while (dest[i]) { if (dest[i] != src[i]) { return 1; } i++; } return 0; } void getApi() { // 1. 先获取kernel32的加载基址 HMODULE hKernel32=NULL; _asm { mov eax, FS:[0x30]; mov eax, [eax + 0xc]; mov eax, [eax + 0xc]; mov eax, [eax]; mov eax, [eax]; mov eax, [eax + 0x18]; mov hKernel32, eax; } // 2. 再获取LoadLibrayA和GetProcAddress函数的地址 // 2.1 遍历导出表获取函数地址 IMAGE_EXPORT_DIRECTORY* pExp=NULL; pExp = (IMAGE_EXPORT_DIRECTORY*) (getOptionHeader((char*)hKernel32)->DataDirectory[0].VirtualAddress + (DWORD)hKernel32); DWORD* pEAT = NULL, *pENT=NULL; WORD* pEOT = NULL; pEAT = (DWORD*)(pExp->AddressOfFunctions + (DWORD)hKernel32); pENT = (DWORD*)(pExp->AddressOfNames + (DWORD)hKernel32); pEOT = (WORD*)(pExp->AddressOfNameOrdinals+(DWORD)hKernel32); for (size_t i = 0; i < pExp->NumberOfNames; i++) { char* pName = pENT[i] + (char*)hKernel32; if (MyStrcmp(pName, "GetProcAddress") == 0) { int index = pEOT[i]; pfnGetProcAddress = (FnGetProcAddress)(pEAT[index] + (DWORD)hKernel32); break; } } // 3. 通过这两个API获取其它的API pfnLoadLibraryA= (FnLoadLibraryA)pfnGetProcAddress(hKernel32, "LoadLibraryA"); // 4. 弹个消息框测试 HMODULE hUser32=pfnLoadLibraryA("user32.dll"); pfnMessageBoxA = (FnMessageBoxA)pfnGetProcAddress(hUser32, "MessageBoxA"); pfnMessageBoxA(0, "我是一个壳", "提示", 0); } extern"C" { _declspec(dllexport) StubConf g_conf = {0xFFFFFFFF}; _declspec(dllexport) _declspec(naked) void start() { // 1. 先获取必要的API地址. getApi(); g_conf.oep += 0x400000; _asm jmp g_conf.oep; } }
[ "573887402@qq.com" ]
573887402@qq.com
de6e972954c27fb2017adcb7521d242078b4ce6c
ee2b7a0a184d714dac804a023e4e2dd1367e0ddf
/blaze/math/expressions/TSMatDMatMultExpr.h
dc2501f36437de78c4f006faa908774418017f2c
[ "BSD-3-Clause" ]
permissive
fpzh2011/blaze
b51d4c4825bc7cf0f696e852b279efcc92b82484
7bf9ff8dddea687264bd8ce834ec15345f1135f1
refs/heads/master
2020-03-14T20:45:14.626274
2015-10-15T21:39:17
2016-01-17T01:05:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
98,569
h
//================================================================================================= /*! // \file blaze/math/expressions/TSMatDMatMultExpr.h // \brief Header file for the transpose sparse matrix/dense matrix multiplication expression // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZE_MATH_EXPRESSIONS_TSMATDMATMULTEXPR_H_ #define _BLAZE_MATH_EXPRESSIONS_TSMATDMATMULTEXPR_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/math/constraints/ColumnMajorMatrix.h> #include <blaze/math/constraints/DenseMatrix.h> #include <blaze/math/constraints/MatMatMultExpr.h> #include <blaze/math/constraints/RowMajorMatrix.h> #include <blaze/math/constraints/SparseMatrix.h> #include <blaze/math/constraints/StorageOrder.h> #include <blaze/math/expressions/Computation.h> #include <blaze/math/expressions/DenseMatrix.h> #include <blaze/math/expressions/Forward.h> #include <blaze/math/expressions/MatMatMultExpr.h> #include <blaze/math/Functions.h> #include <blaze/math/shims/IsDefault.h> #include <blaze/math/shims/Reset.h> #include <blaze/math/shims/Serial.h> #include <blaze/math/traits/ColumnExprTrait.h> #include <blaze/math/traits/DMatDVecMultExprTrait.h> #include <blaze/math/traits/DMatSVecMultExprTrait.h> #include <blaze/math/traits/MultExprTrait.h> #include <blaze/math/traits/MultTrait.h> #include <blaze/math/traits/RowExprTrait.h> #include <blaze/math/traits/SubmatrixExprTrait.h> #include <blaze/math/traits/TDMatDVecMultExprTrait.h> #include <blaze/math/traits/TDMatSVecMultExprTrait.h> #include <blaze/math/traits/TSMatDVecMultExprTrait.h> #include <blaze/math/traits/TDVecDMatMultExprTrait.h> #include <blaze/math/traits/TDVecTDMatMultExprTrait.h> #include <blaze/math/traits/TDVecTSMatMultExprTrait.h> #include <blaze/math/traits/TSVecDMatMultExprTrait.h> #include <blaze/math/traits/TSVecTDMatMultExprTrait.h> #include <blaze/math/traits/TSVecTSMatMultExprTrait.h> #include <blaze/math/typetraits/Columns.h> #include <blaze/math/typetraits/IsAligned.h> #include <blaze/math/typetraits/IsColumnMajorMatrix.h> #include <blaze/math/typetraits/IsColumnVector.h> #include <blaze/math/typetraits/IsComputation.h> #include <blaze/math/typetraits/IsDenseMatrix.h> #include <blaze/math/typetraits/IsDenseVector.h> #include <blaze/math/typetraits/IsDiagonal.h> #include <blaze/math/typetraits/IsExpression.h> #include <blaze/math/typetraits/IsLower.h> #include <blaze/math/typetraits/IsResizable.h> #include <blaze/math/typetraits/IsRowMajorMatrix.h> #include <blaze/math/typetraits/IsRowVector.h> #include <blaze/math/typetraits/IsSparseMatrix.h> #include <blaze/math/typetraits/IsSparseVector.h> #include <blaze/math/typetraits/IsStrictlyLower.h> #include <blaze/math/typetraits/IsStrictlyUpper.h> #include <blaze/math/typetraits/IsSymmetric.h> #include <blaze/math/typetraits/IsTriangular.h> #include <blaze/math/typetraits/IsUniLower.h> #include <blaze/math/typetraits/IsUniUpper.h> #include <blaze/math/typetraits/IsUpper.h> #include <blaze/math/typetraits/Rows.h> #include <blaze/system/Optimizations.h> #include <blaze/system/Thresholds.h> #include <blaze/util/Assert.h> #include <blaze/util/DisableIf.h> #include <blaze/util/EnableIf.h> #include <blaze/util/Exception.h> #include <blaze/util/InvalidType.h> #include <blaze/util/logging/FunctionTrace.h> #include <blaze/util/mpl/And.h> #include <blaze/util/mpl/Or.h> #include <blaze/util/SelectType.h> #include <blaze/util/Types.h> #include <blaze/util/typetraits/RemoveReference.h> #include <blaze/util/valuetraits/IsTrue.h> namespace blaze { //================================================================================================= // // CLASS SMATDMATMULTEXPR // //================================================================================================= //************************************************************************************************* /*!\brief Expression object for transpose sparse matrix-dense matrix multiplications. // \ingroup dense_matrix_expression // // The TSMatDMatMultExpr class represents the compile time expression for multiplications between // a column-major sparse matrix and a row-major dense matrix. */ template< typename MT1 // Type of the left-hand side dense matrix , typename MT2 > // Type of the right-hand side sparse matrix class TSMatDMatMultExpr : public DenseMatrix< TSMatDMatMultExpr<MT1,MT2>, true > , private MatMatMultExpr , private Computation { private: //**Type definitions**************************************************************************** typedef typename MT1::ResultType RT1; //!< Result type of the left-hand side sparse matrix expression. typedef typename MT2::ResultType RT2; //!< Result type of the right-hand side dense matrix expression. typedef typename RT1::ElementType ET1; //!< Element type of the left-hand side dense matrix expression. typedef typename RT2::ElementType ET2; //!< Element type of the right-hand side sparse matrix expression. typedef typename MT1::CompositeType CT1; //!< Composite type of the left-hand side sparse matrix expression. typedef typename MT2::CompositeType CT2; //!< Composite type of the right-hand side dense matrix expression. //********************************************************************************************** //********************************************************************************************** //! Compilation switch for the composite type of the left-hand side sparse matrix expression. enum { evaluateLeft = IsComputation<MT1>::value || RequiresEvaluation<MT1>::value }; //********************************************************************************************** //********************************************************************************************** //! Compilation switch for the composite type of the right-hand side dense matrix expression. enum { evaluateRight = IsComputation<MT2>::value || RequiresEvaluation<MT2>::value }; //********************************************************************************************** //********************************************************************************************** /*! \cond BLAZE_INTERNAL */ //! Helper structure for the explicit application of the SFINAE principle. /*! The CanExploitSymmetry struct is a helper struct for the selection of the optimal evaluation strategy. In case the right-hand side dense matrix operand is symmetric, \a value is set to 1 and an optimized evaluation strategy is selected. Otherwise \a value is set to 0 and the default strategy is chosen. */ template< typename T1, typename T2, typename T3 > struct CanExploitSymmetry { enum { value = IsSymmetric<T2>::value }; }; /*! \endcond */ //********************************************************************************************** //********************************************************************************************** /*! \cond BLAZE_INTERNAL */ //! Helper structure for the explicit application of the SFINAE principle. /*! The IsEvaluationRequired struct is a helper struct for the selection of the parallel evaluation strategy. In case either of the two matrix operands requires an intermediate evaluation, the nested \value will be set to 1, otherwise it will be 0. */ template< typename T1, typename T2, typename T3 > struct IsEvaluationRequired { enum { value = ( evaluateLeft || evaluateRight ) && !CanExploitSymmetry<T1,T2,T3>::value }; }; /*! \endcond */ //********************************************************************************************** //********************************************************************************************** /*! \cond BLAZE_INTERNAL */ //! Helper structure for the explicit application of the SFINAE principle. /*! In case no SMP assignment is required and the element type of the target matrix has a fixed size (i.e. is not resizable), the nested \value will be set to 1, otherwise it will be 0. */ template< typename T1, typename T2, typename T3 > struct UseOptimizedKernel { enum { value = useOptimizedKernels && !IsDiagonal<T3>::value && !IsResizable<typename T1::ElementType>::value && !IsResizable<ET1>::value }; }; /*! \endcond */ //********************************************************************************************** //********************************************************************************************** /*! \cond BLAZE_INTERNAL */ //! Helper structure for the explicit application of the SFINAE principle. /*! In case no SMP assignment is required and the element type of the target matrix is resizable, the nested \value will be set to 1, otherwise it will be 0. */ template< typename T1, typename T2, typename T3 > struct UseDefaultKernel { enum { value = !UseOptimizedKernel<T1,T2,T3>::value }; }; /*! \endcond */ //********************************************************************************************** public: //**Type definitions**************************************************************************** typedef TSMatDMatMultExpr<MT1,MT2> This; //!< Type of this TSMatDMatMultExpr instance. typedef typename MultTrait<RT1,RT2>::Type ResultType; //!< Result type for expression template evaluations. typedef typename ResultType::OppositeType OppositeType; //!< Result type with opposite storage order for expression template evaluations. typedef typename ResultType::TransposeType TransposeType; //!< Transpose type for expression template evaluations. typedef typename ResultType::ElementType ElementType; //!< Resulting element type. typedef const ElementType ReturnType; //!< Return type for expression template evaluations. typedef const ResultType CompositeType; //!< Data type for composite expression templates. //! Composite type of the left-hand side sparse matrix expression. typedef typename SelectType< IsExpression<MT1>::value, const MT1, const MT1& >::Type LeftOperand; //! Composite type of the right-hand side dense matrix expression. typedef typename SelectType< IsExpression<MT2>::value, const MT2, const MT2& >::Type RightOperand; //! Type for the assignment of the left-hand side sparse matrix operand. typedef typename SelectType< evaluateLeft, const RT1, CT1 >::Type LT; //! Type for the assignment of the right-hand side dense matrix operand. typedef typename SelectType< evaluateRight, const RT2, CT2 >::Type RT; //********************************************************************************************** //**Compilation flags*************************************************************************** //! Compilation switch for the expression template evaluation strategy. enum { vectorizable = 0 }; //! Compilation switch for the expression template assignment strategy. enum { smpAssignable = !evaluateLeft && MT1::smpAssignable && !evaluateRight && MT2::smpAssignable }; //********************************************************************************************** //**Constructor********************************************************************************* /*!\brief Constructor for the TSMatDMatMultExpr class. // // \param lhs The left-hand side sparse matrix operand of the multiplication expression. // \param rhs The right-hand side dense matrix operand of the multiplication expression. */ explicit inline TSMatDMatMultExpr( const MT1& lhs, const MT2& rhs ) : lhs_( lhs ) // Left-hand side sparse matrix of the multiplication expression , rhs_( rhs ) // Right-hand side dense matrix of the multiplication expression { BLAZE_INTERNAL_ASSERT( lhs.columns() == rhs.rows(), "Invalid matrix sizes" ); } //********************************************************************************************** //**Access operator***************************************************************************** /*!\brief 2D-access to the matrix elements. // // \param i Access index for the row. The index has to be in the range \f$[0..M-1]\f$. // \param j Access index for the column. The index has to be in the range \f$[0..N-1]\f$. // \return The resulting value. */ inline ReturnType operator()( size_t i, size_t j ) const { BLAZE_INTERNAL_ASSERT( i < lhs_.rows() , "Invalid row access index" ); BLAZE_INTERNAL_ASSERT( j < rhs_.columns(), "Invalid column access index" ); const size_t kbegin( ( IsUpper<MT1>::value ) ?( ( IsLower<MT2>::value ) ?( max( ( IsStrictlyUpper<MT1>::value ? i+1UL : i ) , ( IsStrictlyLower<MT2>::value ? j+1UL : j ) ) ) :( IsStrictlyUpper<MT1>::value ? i+1UL : i ) ) :( ( IsLower<MT2>::value ) ?( IsStrictlyLower<MT2>::value ? j+1UL : j ) :( 0UL ) ) ); const size_t kend( ( IsLower<MT1>::value ) ?( ( IsUpper<MT2>::value ) ?( min( ( IsStrictlyLower<MT1>::value ? i : i+1UL ) , ( IsStrictlyUpper<MT2>::value ? j : j+1UL ) ) ) :( IsStrictlyLower<MT1>::value ? i : i+1UL ) ) :( ( IsUpper<MT2>::value ) ?( IsStrictlyUpper<MT2>::value ? j : j+1UL ) :( lhs_.columns() ) ) ); if( lhs_.columns() == 0UL || ( ( IsTriangular<MT1>::value || IsTriangular<MT2>::value ) && kbegin >= kend ) ) return ElementType(); ElementType tmp( lhs_(i,kbegin) * rhs_(kbegin,j) ); for( size_t k=kbegin+1UL; k<kend; ++k ) { tmp += lhs_(i,k) * rhs_(k,j); } return tmp; } //********************************************************************************************** //**Rows function******************************************************************************* /*!\brief Returns the current number of rows of the matrix. // // \return The number of rows of the matrix. */ inline size_t rows() const { return lhs_.rows(); } //********************************************************************************************** //**Columns function**************************************************************************** /*!\brief Returns the current number of columns of the matrix. // // \return The number of columns of the matrix. */ inline size_t columns() const { return rhs_.columns(); } //********************************************************************************************** //**Left operand access************************************************************************* /*!\brief Returns the left-hand side transpose sparse matrix operand. // // \return The left-hand side transpose sparse matrix operand. */ inline LeftOperand leftOperand() const { return lhs_; } //********************************************************************************************** //**Right operand access************************************************************************ /*!\brief Returns the right-hand side dense matrix operand. // // \return The right-hand side dense matrix operand. */ inline RightOperand rightOperand() const { return rhs_; } //********************************************************************************************** //********************************************************************************************** /*!\brief Returns whether the expression can alias with the given address \a alias. // // \param alias The alias to be checked. // \return \a true in case the expression can alias, \a false otherwise. */ template< typename T > inline bool canAlias( const T* alias ) const { return ( lhs_.isAliased( alias ) || rhs_.isAliased( alias ) ); } //********************************************************************************************** //********************************************************************************************** /*!\brief Returns whether the expression is aliased with the given address \a alias. // // \param alias The alias to be checked. // \return \a true in case an alias effect is detected, \a false otherwise. */ template< typename T > inline bool isAliased( const T* alias ) const { return ( lhs_.isAliased( alias ) || rhs_.isAliased( alias ) ); } //********************************************************************************************** //********************************************************************************************** /*!\brief Returns whether the operands of the expression are properly aligned in memory. // // \return \a true in case the operands are aligned, \a false if not. */ inline bool isAligned() const { return rhs_.isAligned(); } //********************************************************************************************** //********************************************************************************************** /*!\brief Returns whether the expression can be used in SMP assignments. // // \return \a true in case the expression can be used in SMP assignments, \a false if not. */ inline bool canSMPAssign() const { return ( columns() > SMP_TSMATDMATMULT_THRESHOLD ); } //********************************************************************************************** private: //**Member variables**************************************************************************** LeftOperand lhs_; //!< Left-hand side sparse matrix of the multiplication expression. RightOperand rhs_; //!< Right-hand side dense matrix of the multiplication expression. //********************************************************************************************** //**Assignment to dense matrices**************************************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Assignment of a transpose sparse matrix-dense matrix multiplication to a dense matrix // (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side multiplication expression to be assigned. // \return void // // This function implements the performance optimized assignment of a transpose sparse matrix- // dense matrix multiplication expression to a dense matrix. */ template< typename MT // Type of the target dense matrix , bool SO > // Storage order of the target dense matrix friend inline typename DisableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type assign( DenseMatrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); LT A( serial( rhs.lhs_ ) ); // Evaluation of the right-hand side sparse matrix operand RT B( serial( rhs.rhs_ ) ); // Evaluation of the left-hand side dense matrix operand BLAZE_INTERNAL_ASSERT( A.rows() == rhs.lhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( A.columns() == rhs.lhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( B.rows() == rhs.rhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == rhs.rhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( A.rows() == (~lhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == (~lhs).columns() , "Invalid number of columns" ); TSMatDMatMultExpr::selectAssignKernel( ~lhs, A, B ); } /*! \endcond */ //********************************************************************************************** //**Assignment to dense matrices (kernel selection)********************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Selection of the kernel for an assignment of a transpose sparse matrix-dense matrix // multiplication to a dense matrix (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline void selectAssignKernel( MT3& C, const MT4& A, const MT5& B ) { const size_t size( C.rows() * C.columns() ); if( ( IsRowMajorMatrix<MT3>::value && size < TSMATDMATMULT_THRESHOLD ) || ( IsColumnMajorMatrix<MT3>::value && size < 625UL ) ) selectSmallAssignKernel( C, A, B ); else selectLargeAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Default assignment to dense matrices******************************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default assignment of a transpose sparse matrix-dense matrix multiplication // (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the default assignment of a transpose sparse matrix-dense matrix // multiplication expression to a dense matrix. This assign function is used in case the // element type of the target matrix is resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline void selectDefaultAssignKernel( MT3& C, const MT4& A, const MT5& B ) { typedef typename MT4::ConstIterator ConstIterator; reset( C ); if( IsDiagonal<MT5>::value ) { for( size_t i=0UL; i<A.columns(); ++i ) { const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); for( ; element!=end; ++element ) { C(element->index(),i) = element->value() * B(i,i); } } } else { const size_t block( IsRowMajorMatrix<MT3>::value ? 256UL : 8UL ); for( size_t jj=0UL; jj<B.columns(); jj+=block ) { const size_t jpos( ( jj+block > B.columns() )?( B.columns() ):( jj+block ) ); for( size_t i=0UL; i<A.columns(); ++i ) { const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); const size_t jbegin( ( IsUpper<MT5>::value ) ?( max( IsStrictlyUpper<MT5>::value ? i+1UL : i, jj ) ) :( jj ) ); const size_t jend( ( IsLower<MT5>::value ) ?( min( IsStrictlyLower<MT5>::value ? i : i+1UL, jpos ) ) :( jpos ) ); if( jbegin >= jend ) continue; for( ; element!=end; ++element ) { for( size_t j=jbegin; j<jend; ++j ) { if( isDefault( C(element->index(),j) ) ) C(element->index(),j) = element->value() * B(i,j); else C(element->index(),j) += element->value() * B(i,j); } } } } } } /*! \endcond */ //********************************************************************************************** //**Default assignment to dense matrices (small matrices)*************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default assignment of a small transpose sparse matrix-dense matrix multiplication // (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function relays to the default implementation of the assignment of a transpose sparse // matrix-dense matrix multiplication expression to a dense matrix. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseDefaultKernel<MT3,MT4,MT5> >::Type selectSmallAssignKernel( MT3& C, const MT4& A, const MT5& B ) { selectDefaultAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Optimized assignment to dense matrices (small matrices)************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Optimized assignment of a small transpose sparse matrix-dense matrix multiplication // (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the performance optimized assignment of a transpose sparse matrix- // dense matrix multiplication expression to a dense matrix. This assign function is used in // case the element type of the target matrix is not resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseOptimizedKernel<MT3,MT4,MT5> >::Type selectSmallAssignKernel( MT3& C, const MT4& A, const MT5& B ) { typedef typename MT4::ConstIterator ConstIterator; const size_t block( ( IsRowMajorMatrix<MT3>::value )?( 256UL ):( 8UL ) ); reset( C ); for( size_t jj=0UL; jj<B.columns(); jj+=block ) { const size_t jpos( ( jj+block > B.columns() )?( B.columns() ):( jj+block ) ); for( size_t i=0UL; i<A.columns(); ++i ) { const size_t jbegin( ( IsUpper<MT5>::value ) ?( max( IsStrictlyUpper<MT5>::value ? i+1UL : i, jj ) ) :( jj ) ); const size_t jend( ( IsLower<MT5>::value ) ?( min( IsStrictlyLower<MT5>::value ? i : i+1UL, jpos ) ) :( jpos ) ); if( jbegin >= jend ) continue; const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); const size_t nonzeros( A.nonZeros(i) ); const size_t kpos( nonzeros & size_t(-4) ); BLAZE_INTERNAL_ASSERT( ( nonzeros - ( nonzeros % 4UL ) ) == kpos, "Invalid end calculation" ); for( size_t k=0UL; k<kpos; k+=4UL ) { const size_t i1( element->index() ); const ET1 v1( element->value() ); ++element; const size_t i2( element->index() ); const ET1 v2( element->value() ); ++element; const size_t i3( element->index() ); const ET1 v3( element->value() ); ++element; const size_t i4( element->index() ); const ET1 v4( element->value() ); ++element; BLAZE_INTERNAL_ASSERT( i1 < i2 && i2 < i3 && i3 < i4, "Invalid sparse matrix index detected" ); for( size_t j=jbegin; j<jend; ++j ) { C(i1,j) += v1 * B(i,j); C(i2,j) += v2 * B(i,j); C(i3,j) += v3 * B(i,j); C(i4,j) += v4 * B(i,j); } } for( ; element!=end; ++element ) { for( size_t j=jbegin; j<jend; ++j ) { C(element->index(),j) += element->value() * B(i,j); } } } } } /*! \endcond */ //********************************************************************************************** //**Default assignment to dense matrices (large matrices)*************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default assignment of a large transpose sparse matrix-dense matrix multiplication // (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function relays to the default implementation of the assignment of a transpose sparse // matrix-dense matrix multiplication expression to a dense matrix. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseDefaultKernel<MT3,MT4,MT5> >::Type selectLargeAssignKernel( MT3& C, const MT4& A, const MT5& B ) { selectDefaultAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Optimized assignment to dense matrices (large matrices)************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Default assignment of a large transpose sparse matrix-dense matrix multiplication // (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the performance optimized assignment of a transpose sparse matrix- // dense matrix multiplication expression to a dense matrix. This assign function is used in // case the element type of the target matrix is not resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseOptimizedKernel<MT3,MT4,MT5> >::Type selectLargeAssignKernel( MT3& C, const MT4& A, const MT5& B ) { BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE( typename MT4::OppositeType ); const typename MT4::OppositeType tmp( serial( A ) ); assign( C, tmp * B ); } /*! \endcond */ //********************************************************************************************** //**Assignment to sparse matrices*************************************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Assignment of a transpose sparse matrix-dense matrix multiplication to a sparse matrix // (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side sparse matrix. // \param rhs The right-hand side multiplication expression to be assigned. // \return void // // This function implements the performance optimized assignment of a transpose sparse matrix- // dense matrix multiplication expression to a sparse matrix. */ template< typename MT // Type of the target sparse matrix , bool SO > // Storage order of the target sparse matrix friend inline typename DisableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type assign( SparseMatrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; typedef typename SelectType< SO, ResultType, OppositeType >::Type TmpType; BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( ResultType ); BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( OppositeType ); BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( ResultType ); BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE( OppositeType ); BLAZE_CONSTRAINT_MATRICES_MUST_HAVE_SAME_STORAGE_ORDER( MT, TmpType ); BLAZE_CONSTRAINT_MUST_BE_REFERENCE_TYPE( typename TmpType::CompositeType ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); const TmpType tmp( serial( rhs ) ); assign( ~lhs, tmp ); } /*! \endcond */ //********************************************************************************************** //**Restructuring assignment to row-major matrices********************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Restructuring assignment of a transpose sparse matrix-dense matrix multiplication to // a row-major matrix (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side matrix. // \param rhs The right-hand side multiplication expression to be assigned. // \return void // // This function implements the symmetry-based restructuring assignment of a transpose sparse // matrix-dense matrix multiplication expression to a row-major matrix. Due to the explicit // application of the SFINAE principle this function can only be selected by the compiler in // case the symmetry of either of the two matrix operands can be exploited. */ template< typename MT // Type of the target matrix , bool SO > // Storage order of the target matrix friend inline typename EnableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type assign( Matrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_CONSTRAINT_MUST_NOT_BE_SYMMETRIC_MATRIX_TYPE( MT ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); assign( ~lhs, trans( rhs.lhs_ ) * rhs.rhs_ ); } /*! \endcond */ //********************************************************************************************** //**Addition assignment to dense matrices******************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Addition assignment of a transpose sparse matrix-dense matrix multiplication to a // dense matrix (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side multiplication expression to be added. // \return void // // This function implements the performance optimized addition assignment of a transpose sparse // matrix-dense matrix multiplication expression to a dense matrix. */ template< typename MT // Type of the target dense matrix , bool SO > // Storage order of the target dense matrix friend inline typename DisableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type addAssign( DenseMatrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); LT A( serial( rhs.lhs_ ) ); // Evaluation of the right-hand side sparse matrix operand RT B( serial( rhs.rhs_ ) ); // Evaluation of the left-hand side dense matrix operand BLAZE_INTERNAL_ASSERT( A.rows() == rhs.lhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( A.columns() == rhs.lhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( B.rows() == rhs.rhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == rhs.rhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( A.rows() == (~lhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == (~lhs).columns() , "Invalid number of columns" ); TSMatDMatMultExpr::selectAddAssignKernel( ~lhs, A, B ); } /*! \endcond */ //********************************************************************************************** //**Addition assignment to dense matrices (kernel selection)************************************ /*! \cond BLAZE_INTERNAL */ /*!\brief Selection of the kernel for an addition assignment of a transpose sparse matrix-dense // matrix multiplication to a dense matrix (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline void selectAddAssignKernel( MT3& C, const MT4& A, const MT5& B ) { const size_t size( C.rows() * C.columns() ); if( ( IsRowMajorMatrix<MT3>::value && size < TSMATDMATMULT_THRESHOLD ) || ( IsColumnMajorMatrix<MT3>::value && size < 625UL ) ) selectSmallAddAssignKernel( C, A, B ); else selectLargeAddAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Default addition assignment to dense matrices*********************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default addition assignment of a transpose sparse matrix-dense matrix multiplication // (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the default addition assignment of a transpose sparse matrix-dense // matrix multiplication expression to a dense matrix. This assign function is used in case the // element type of the target matrix is resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline void selectDefaultAddAssignKernel( MT3& C, const MT4& A, const MT5& B ) { typedef typename MT4::ConstIterator ConstIterator; if( IsDiagonal<MT5>::value ) { for( size_t i=0UL; i<A.columns(); ++i ) { const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); for( ; element!=end; ++element ) { C(element->index(),i) += element->value() * B(i,i); } } } else { const size_t block( IsRowMajorMatrix<MT3>::value ? 256UL : 8UL ); for( size_t jj=0UL; jj<B.columns(); jj+=block ) { const size_t jpos( ( jj+block > B.columns() )?( B.columns() ):( jj+block ) ); for( size_t i=0UL; i<A.columns(); ++i ) { const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); const size_t jbegin( ( IsUpper<MT5>::value ) ?( max( IsStrictlyUpper<MT5>::value ? i+1UL : i, jj ) ) :( jj ) ); const size_t jend( ( IsLower<MT5>::value ) ?( min( IsStrictlyLower<MT5>::value ? i : i+1UL, jpos ) ) :( jpos ) ); if( jbegin >= jend ) continue; for( ; element!=end; ++element ) { for( size_t j=jbegin; j<jend; ++j ) { C(element->index(),j) += element->value() * B(i,j); } } } } } } /*! \endcond */ //********************************************************************************************** //**Default addition assignment to dense matrices (small matrices)****************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default addition assignment of a small transpose sparse matrix-dense matrix // multiplication (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function relays to the default implementation of the addition assignment of a transpose // sparse matrix-dense matrix multiplication expression to a dense matrix. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseDefaultKernel<MT3,MT4,MT5> >::Type selectSmallAddAssignKernel( MT3& C, const MT4& A, const MT5& B ) { selectDefaultAddAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Optimized addition assignment to dense matrices (small matrices)**************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Optimized addition assignment of a small transpose sparse matrix-dense matrix // multiplication (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the performance optimized addition assignment of a transpose sparse // matrix-dense matrix multiplication expression to a dense matrix. This assign function is used // in case the element type of the target matrix is not resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseOptimizedKernel<MT3,MT4,MT5> >::Type selectSmallAddAssignKernel( MT3& C, const MT4& A, const MT5& B ) { typedef typename MT4::ConstIterator ConstIterator; const size_t block( ( IsRowMajorMatrix<MT3>::value )?( 256UL ):( 8UL ) ); for( size_t jj=0UL; jj<B.columns(); jj+=block ) { const size_t jpos( ( jj+block > B.columns() )?( B.columns() ):( jj+block ) ); for( size_t i=0UL; i<A.columns(); ++i ) { const size_t jbegin( ( IsUpper<MT5>::value ) ?( max( IsStrictlyUpper<MT5>::value ? i+1UL : i, jj ) ) :( jj ) ); const size_t jend( ( IsLower<MT5>::value ) ?( min( IsStrictlyLower<MT5>::value ? i : i+1UL, jpos ) ) :( jpos ) ); if( jbegin >= jend ) continue; const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); const size_t nonzeros( A.nonZeros(i) ); const size_t kpos( nonzeros & size_t(-4) ); BLAZE_INTERNAL_ASSERT( ( nonzeros - ( nonzeros % 4UL ) ) == kpos, "Invalid end calculation" ); for( size_t k=0UL; k<kpos; k+=4UL ) { const size_t i1( element->index() ); const ET1 v1( element->value() ); ++element; const size_t i2( element->index() ); const ET1 v2( element->value() ); ++element; const size_t i3( element->index() ); const ET1 v3( element->value() ); ++element; const size_t i4( element->index() ); const ET1 v4( element->value() ); ++element; BLAZE_INTERNAL_ASSERT( i1 < i2 && i2 < i3 && i3 < i4, "Invalid sparse matrix index detected" ); for( size_t j=jbegin; j<jend; ++j ) { C(i1,j) += v1 * B(i,j); C(i2,j) += v2 * B(i,j); C(i3,j) += v3 * B(i,j); C(i4,j) += v4 * B(i,j); } } for( ; element!=end; ++element ) { for( size_t j=jbegin; j<jend; ++j ) { C(element->index(),j) += element->value() * B(i,j); } } } } } /*! \endcond */ //********************************************************************************************** //**Default addition assignment to dense matrices (large matrices)****************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default addition assignment of a large transpose sparse matrix-dense matrix // multiplication (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function relays to the default implementation of the addition assignment of a transpose // sparse matrix-dense matrix multiplication expression to a dense matrix. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseDefaultKernel<MT3,MT4,MT5> >::Type selectLargeAddAssignKernel( MT3& C, const MT4& A, const MT5& B ) { selectDefaultAddAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Optimized addition assignment to dense matrices (large matrices)**************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default addition assignment of a large transpose sparse matrix-dense matrix // multiplication (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the performance optimized addition assignment of a transpose sparse // matrix-dense matrix multiplication expression to a dense matrix. This assign function is used // in case the element type of the target matrix is not resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseOptimizedKernel<MT3,MT4,MT5> >::Type selectLargeAddAssignKernel( MT3& C, const MT4& A, const MT5& B ) { BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE( typename MT4::OppositeType ); const typename MT4::OppositeType tmp( serial( A ) ); addAssign( C, tmp * B ); } /*! \endcond */ //********************************************************************************************** //**Restructuring addition assignment to row-major matrices************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Restructuring addition assignment of a transpose sparse matrix-dense matrix // multiplication to a row-major matrix (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side matrix. // \param rhs The right-hand side multiplication expression to be added. // \return void // // This function implements the symmetry-based restructuring addition assignment of a // transpose sparse matrix-dense matrix multiplication expression to a row-major matrix. Due // to the explicit application of the SFINAE principle this function can only be selected by // the compiler in case the symmetry of either of the two matrix operands can be exploited. */ template< typename MT // Type of the target matrix , bool SO > // Storage order of the target matrix friend inline typename EnableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type addAssign( Matrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_CONSTRAINT_MUST_NOT_BE_SYMMETRIC_MATRIX_TYPE( MT ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); addAssign( ~lhs, trans( rhs.lhs_ ) * rhs.rhs_ ); } /*! \endcond */ //********************************************************************************************** //**Addition assignment to sparse matrices****************************************************** // No special implementation for the addition assignment to sparse matrices. //********************************************************************************************** //**Subtraction assignment to dense matrices**************************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Subtraction assignment of a transpose sparse matrix-dense matrix multiplication to a // dense matrix (\f$ A-=B*C \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side multiplication expression to be subtracted. // \return void // // This function implements the performance optimized subtraction assignment of a transpose // sparse matrix-dense matrix multiplication expression to a dense matrix. */ template< typename MT // Type of the target dense matrix , bool SO > // Storage order of the target dense matrix friend inline typename DisableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type subAssign( DenseMatrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); LT A( serial( rhs.lhs_ ) ); // Evaluation of the right-hand side sparse matrix operand RT B( serial( rhs.rhs_ ) ); // Evaluation of the left-hand side dense matrix operand BLAZE_INTERNAL_ASSERT( A.rows() == rhs.lhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( A.columns() == rhs.lhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( B.rows() == rhs.rhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == rhs.rhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( A.rows() == (~lhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == (~lhs).columns() , "Invalid number of columns" ); TSMatDMatMultExpr::selectSubAssignKernel( ~lhs, A, B ); } /*! \endcond */ //********************************************************************************************** //**Subtraction assignment to dense matrices (kernel selection)********************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Selection of the kernel for an subtraction assignment of a transpose sparse matrix- // dense matrix multiplication to a dense matrix (\f$ C-=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline void selectSubAssignKernel( MT3& C, const MT4& A, const MT5& B ) { const size_t size( C.rows() * C.columns() ); if( ( IsRowMajorMatrix<MT3>::value && size < TSMATDMATMULT_THRESHOLD ) || ( IsColumnMajorMatrix<MT3>::value && size < 625UL ) ) selectSmallSubAssignKernel( C, A, B ); else selectLargeSubAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Default subtraction assignment to dense matrices******************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default subtraction assignment of a transpose sparse matrix-dense matrix // multiplication (\f$ C-=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the default subtraction assignment of a transpose sparse matrix- // dense matrix multiplication expression to a dense matrix. This assign function is used in // case the element type of the target matrix is resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline void selectDefaultSubAssignKernel( MT3& C, const MT4& A, const MT5& B ) { typedef typename MT4::ConstIterator ConstIterator; if( IsDiagonal<MT5>::value ) { for( size_t i=0UL; i<A.columns(); ++i ) { const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); for( ; element!=end; ++element ) { C(element->index(),i) -= element->value() * B(i,i); } } } else { const size_t block( IsRowMajorMatrix<MT3>::value ? 256UL : 8UL ); for( size_t jj=0UL; jj<B.columns(); jj+=block ) { const size_t jpos( ( jj+block > B.columns() )?( B.columns() ):( jj+block ) ); for( size_t i=0UL; i<A.columns(); ++i ) { const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); const size_t jbegin( ( IsUpper<MT5>::value ) ?( max( IsStrictlyUpper<MT5>::value ? i+1UL : i, jj ) ) :( jj ) ); const size_t jend( ( IsLower<MT5>::value ) ?( min( IsStrictlyLower<MT5>::value ? i : i+1UL, jpos ) ) :( jpos ) ); if( jbegin >= jend ) continue; for( ; element!=end; ++element ) { for( size_t j=jbegin; j<jend; ++j ) { C(element->index(),j) -= element->value() * B(i,j); } } } } } } /*! \endcond */ //********************************************************************************************** //**Default subtraction assignment to dense matrices (small matrices)*************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default subtraction assignment of a small transpose sparse matrix-dense matrix // multiplication (\f$ C-=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function relays to the default implementation of the subtraction assignment of a // transpose sparse matrix-dense matrix multiplication expression to a dense matrix. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseDefaultKernel<MT3,MT4,MT5> >::Type selectSmallSubAssignKernel( MT3& C, const MT4& A, const MT5& B ) { selectDefaultSubAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Optimized subtraction assignment to dense matrices (small matrices)************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Optimized subtraction assignment of a small transpose sparse matrix-dense matrix // multiplication (\f$ C-=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the performance optimized subtraction assignment of a transpose // sparse matrix-dense matrix multiplication expression to a dense matrix. This assign function // is used in case the element type of the target matrix is not resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseOptimizedKernel<MT3,MT4,MT5> >::Type selectSmallSubAssignKernel( MT3& C, const MT4& A, const MT5& B ) { typedef typename MT4::ConstIterator ConstIterator; const size_t block( ( IsRowMajorMatrix<MT3>::value )?( 256UL ):( 8UL ) ); for( size_t jj=0UL; jj<B.columns(); jj+=block ) { const size_t jpos( ( jj+block > B.columns() )?( B.columns() ):( jj+block ) ); for( size_t i=0UL; i<A.columns(); ++i ) { const size_t jbegin( ( IsUpper<MT5>::value ) ?( max( IsStrictlyUpper<MT5>::value ? i+1UL : i, jj ) ) :( jj ) ); const size_t jend( ( IsLower<MT5>::value ) ?( min( IsStrictlyLower<MT5>::value ? i : i+1UL, jpos ) ) :( jpos ) ); if( jbegin >= jend ) continue; const ConstIterator end( A.end(i) ); ConstIterator element( A.begin(i) ); const size_t nonzeros( A.nonZeros(i) ); const size_t kpos( nonzeros & size_t(-4) ); BLAZE_INTERNAL_ASSERT( ( nonzeros - ( nonzeros % 4UL ) ) == kpos, "Invalid end calculation" ); for( size_t k=0UL; k<kpos; k+=4UL ) { const size_t i1( element->index() ); const ET1 v1( element->value() ); ++element; const size_t i2( element->index() ); const ET1 v2( element->value() ); ++element; const size_t i3( element->index() ); const ET1 v3( element->value() ); ++element; const size_t i4( element->index() ); const ET1 v4( element->value() ); ++element; BLAZE_INTERNAL_ASSERT( i1 < i2 && i2 < i3 && i3 < i4, "Invalid sparse matrix index detected" ); for( size_t j=jbegin; j<jend; ++j ) { C(i1,j) -= v1 * B(i,j); C(i2,j) -= v2 * B(i,j); C(i3,j) -= v3 * B(i,j); C(i4,j) -= v4 * B(i,j); } } for( ; element!=end; ++element ) { for( size_t j=jbegin; j<jend; ++j ) { C(element->index(),j) -= element->value() * B(i,j); } } } } } /*! \endcond */ //********************************************************************************************** //**Default subtraction assignment to dense matrices (large matrices)*************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Default subtraction assignment of a large transpose sparse matrix-dense matrix // multiplication (\f$ C-=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function relays to the default implementation of the subtraction assignment of a // transpose sparse matrix-dense matrix multiplication expression to a dense matrix. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseDefaultKernel<MT3,MT4,MT5> >::Type selectLargeSubAssignKernel( MT3& C, const MT4& A, const MT5& B ) { selectDefaultSubAssignKernel( C, A, B ); } /*! \endcond */ //********************************************************************************************** //**Optimized subtraction assignment to dense matrices (large matrices)************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Default subtraction assignment of a large transpose sparse matrix-dense matrix // multiplication (\f$ C-=A*B \f$). // \ingroup dense_matrix // // \param C The target left-hand side dense matrix. // \param A The left-hand side multiplication operand. // \param B The right-hand side multiplication operand. // \return void // // This function implements the performance optimized subtraction assignment of a transpose // sparse matrix-dense matrix multiplication expression to a dense matrix. This assign function // is used in case the element type of the target matrix is not resizable. */ template< typename MT3 // Type of the left-hand side target matrix , typename MT4 // Type of the left-hand side matrix operand , typename MT5 > // Type of the right-hand side matrix operand static inline typename EnableIf< UseOptimizedKernel<MT3,MT4,MT5> >::Type selectLargeSubAssignKernel( MT3& C, const MT4& A, const MT5& B ) { BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE( typename MT4::OppositeType ); const typename MT4::OppositeType tmp( serial( A ) ); subAssign( C, tmp * B ); } /*! \endcond */ //********************************************************************************************** //**Restructuring subtraction assignment to row-major matrices********************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Restructuring subtraction assignment of a transpose sparse matrix-dense matrix // multiplication to a row-major matrix (\f$ C-=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side matrix. // \param rhs The right-hand side multiplication expression to be subtracted. // \return void // // This function implements the symmetry-based restructuring subtraction assignment of a // transpose sparse matrix-dense matrix multiplication expression to a row-major matrix. Due // to the explicit application of the SFINAE principle this function can only be selected by // the compiler in case the symmetry of either of the two matrix operands can be exploited. */ template< typename MT // Type of the target matrix , bool SO > // Storage order of the target matrix friend inline typename EnableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type subAssign( Matrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_CONSTRAINT_MUST_NOT_BE_SYMMETRIC_MATRIX_TYPE( MT ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); subAssign( ~lhs, trans( rhs.lhs_ ) * rhs.rhs_ ); } /*! \endcond */ //********************************************************************************************** //**Subtraction assignment to sparse matrices*************************************************** // No special implementation for the subtraction assignment to sparse matrices. //********************************************************************************************** //**Multiplication assignment to dense matrices************************************************* // No special implementation for the multiplication assignment to dense matrices. //********************************************************************************************** //**Multiplication assignment to sparse matrices************************************************ // No special implementation for the multiplication assignment to sparse matrices. //********************************************************************************************** //**SMP assignment to dense matrices************************************************************ /*! \cond BLAZE_INTERNAL */ /*!\brief SMP assignment of a transpose sparse matrix-dense matrix multiplication to a dense // matrix (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side multiplication expression to be assigned. // \return void // // This function implements the performance optimized SMP assignment of a transpose sparse // matrix-dense matrix multiplication expression to a dense matrix. Due to the explicit // application of the SFINAE principle this function can only be selected by the compiler // in case either of the two matrix operands requires an intermediate evaluation and no // symmetry can be exploited. */ template< typename MT // Type of the target dense matrix , bool SO > // Storage order of the target dense matrix friend inline typename EnableIf< IsEvaluationRequired<MT,MT1,MT2> >::Type smpAssign( DenseMatrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); LT A( rhs.lhs_ ); // Evaluation of the right-hand side sparse matrix operand RT B( rhs.rhs_ ); // Evaluation of the left-hand side dense matrix operand BLAZE_INTERNAL_ASSERT( A.rows() == rhs.lhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( A.columns() == rhs.lhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( B.rows() == rhs.rhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == rhs.rhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( A.rows() == (~lhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == (~lhs).columns() , "Invalid number of columns" ); smpAssign( ~lhs, A * B ); } /*! \endcond */ //********************************************************************************************** //**SMP assignment to sparse matrices*********************************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief SMP assignment of a transpose sparse matrix-dense matrix multiplication to a sparse // matrix (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side sparse matrix. // \param rhs The right-hand side multiplication expression to be assigned. // \return void // // This function implements the performance optimized SMP assignment of a transpose sparse // matrix-dense matrix multiplication expression to a sparse matrix. Due to the explicit // application of the SFINAE principle this function can only be selected by the compiler // in case either of the two matrix operands requires an intermediate evaluation and no // symmetry can be exploited. */ template< typename MT // Type of the target sparse matrix , bool SO > // Storage order of the target sparse matrix friend inline typename EnableIf< IsEvaluationRequired<MT,MT1,MT2> >::Type smpAssign( SparseMatrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; typedef typename SelectType< SO, ResultType, OppositeType >::Type TmpType; BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( ResultType ); BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( OppositeType ); BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( ResultType ); BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE( OppositeType ); BLAZE_CONSTRAINT_MATRICES_MUST_HAVE_SAME_STORAGE_ORDER( MT, TmpType ); BLAZE_CONSTRAINT_MUST_BE_REFERENCE_TYPE( typename TmpType::CompositeType ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); const TmpType tmp( rhs ); smpAssign( ~lhs, tmp ); } /*! \endcond */ //********************************************************************************************** //**Restructuring SMP assignment to row-major matrices****************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Restructuring SMP assignment of a transpose sparse matrix-dense matrix multiplication // to a row-major matrix (\f$ C=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side matrix. // \param rhs The right-hand side multiplication expression to be assigned. // \return void // // This function implements the symmetry-based restructuring SMP assignment of a transpose // sparse matrix-dense matrix multiplication expression to a row-major matrix. Due to the // explicit application of the SFINAE principle this function can only be selected by the // compiler in case the symmetry of either of the two matrix operands can be exploited. */ template< typename MT // Type of the target matrix , bool SO > // Storage order of the target matrix friend inline typename EnableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type smpAssign( Matrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); smpAssign( ~lhs, trans( rhs.lhs_ ) * rhs.rhs_ ); } /*! \endcond */ //********************************************************************************************** //**SMP addition assignment to dense matrices*************************************************** /*! \cond BLAZE_INTERNAL */ /*!\brief SMP addition assignment of a transpose sparse matrix-dense matrix multiplication // to a dense matrix (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side multiplication expression to be added. // \return void // // This function implements the performance optimized SMP addition assignment of a transpose // sparse matrix-dense matrix multiplication expression to a dense matrix. Due to the explicit // application of the SFINAE principle this function can only be selected by the compiler // in case either of the two matrix operands requires an intermediate evaluation and no // symmetry can be exploited. */ template< typename MT // Type of the target dense matrix , bool SO > // Storage order of the target dense matrix friend inline typename EnableIf< IsEvaluationRequired<MT,MT1,MT2> >::Type smpAddAssign( DenseMatrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); LT A( rhs.lhs_ ); // Evaluation of the right-hand side sparse matrix operand RT B( rhs.rhs_ ); // Evaluation of the left-hand side dense matrix operand BLAZE_INTERNAL_ASSERT( A.rows() == rhs.lhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( A.columns() == rhs.lhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( B.rows() == rhs.rhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == rhs.rhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( A.rows() == (~lhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == (~lhs).columns() , "Invalid number of columns" ); smpAddAssign( ~lhs, A * B ); } /*! \endcond */ //********************************************************************************************** //**Restructuring SMP addition assignment to row-major matrices********************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Restructuring SMP addition assignment of a transpose sparse matrix-dense matrix // multiplication to a row-major matrix (\f$ C+=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side matrix. // \param rhs The right-hand side multiplication expression to be added. // \return void // // This function implements the symmetry-based restructuring SMP addition assignment of a // transpose sparse matrix-dense matrix multiplication expression to a row-major matrix. Due // to the explicit application of the SFINAE principle this function can only be selected by // the compiler in case the symmetry of either of the two matrix operands can be exploited. */ template< typename MT // Type of the target matrix , bool SO > // Storage order of the target matrix friend inline typename EnableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type smpAddAssign( Matrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); smpAddAssign( ~lhs, trans( rhs.lhs_ ) * rhs.rhs_ ); } /*! \endcond */ //********************************************************************************************** //**SMP addition assignment to sparse matrices************************************************** // No special implementation for the SMP addition assignment to sparse matrices. //********************************************************************************************** //**SMP subtraction assignment to dense matrices************************************************ /*! \cond BLAZE_INTERNAL */ /*!\brief SMP subtraction assignment of a transpose sparse matrix-dense matrix multiplication // to a dense matrix (\f$ A-=B*C \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side multiplication expression to be subtracted. // \return void // // This function implements the performance optimized subtraction assignment of a transpose // sparse matrix-dense matrix multiplication expression to a dense matrix. Due to the explicit // application of the SFINAE principle this function can only be selected by the compiler // in case either of the two matrix operands requires an intermediate evaluation and no // symmetry can be exploited. */ template< typename MT // Type of the target dense matrix , bool SO > // Storage order of the target dense matrix friend inline typename EnableIf< IsEvaluationRequired<MT,MT1,MT2> >::Type smpSubAssign( DenseMatrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); LT A( rhs.lhs_ ); // Evaluation of the right-hand side sparse matrix operand RT B( rhs.rhs_ ); // Evaluation of the left-hand side dense matrix operand BLAZE_INTERNAL_ASSERT( A.rows() == rhs.lhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( A.columns() == rhs.lhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( B.rows() == rhs.rhs_.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == rhs.rhs_.columns(), "Invalid number of columns" ); BLAZE_INTERNAL_ASSERT( A.rows() == (~lhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( B.columns() == (~lhs).columns() , "Invalid number of columns" ); smpSubAssign( ~lhs, A * B ); } /*! \endcond */ //********************************************************************************************** //**Restructuring SMP subtraction assignment to row-major matrices****************************** /*! \cond BLAZE_INTERNAL */ /*!\brief Restructuring SMP subtraction assignment of a transpose sparse matrix-dense matrix // multiplication to a row-major matrix (\f$ C-=A*B \f$). // \ingroup dense_matrix // // \param lhs The target left-hand side matrix. // \param rhs The right-hand side multiplication expression to be subtracted. // \return void // // This function implements the symmetry-based restructuring SMP subtraction assignment of a // transpose sparse matrix-dense matrix multiplication expression to a row-major matrix. Due // to the explicit application of the SFINAE principle this function can only be selected by // the compiler in case the symmetry of either of the two matrix operands can be exploited. */ template< typename MT // Type of the target matrix , bool SO > // Storage order of the target matrix friend inline typename EnableIf< CanExploitSymmetry<MT,MT1,MT2> >::Type smpSubAssign( Matrix<MT,SO>& lhs, const TSMatDMatMultExpr& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == rhs.rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == rhs.columns(), "Invalid number of columns" ); smpSubAssign( ~lhs, trans( rhs.lhs_ ) * rhs.rhs_ ); } /*! \endcond */ //********************************************************************************************** //**SMP subtraction assignment to sparse matrices*********************************************** // No special implementation for the SMP subtraction assignment to sparse matrices. //********************************************************************************************** //**SMP multiplication assignment to dense matrices********************************************* // No special implementation for the SMP multiplication assignment to dense matrices. //********************************************************************************************** //**SMP multiplication assignment to sparse matrices******************************************** // No special implementation for the SMP multiplication assignment to sparse matrices. //********************************************************************************************** //**Compile time checks************************************************************************* /*! \cond BLAZE_INTERNAL */ BLAZE_CONSTRAINT_MUST_BE_SPARSE_MATRIX_TYPE( MT1 ); BLAZE_CONSTRAINT_MUST_BE_COLUMN_MAJOR_MATRIX_TYPE( MT1 ); BLAZE_CONSTRAINT_MUST_BE_DENSE_MATRIX_TYPE( MT2 ); BLAZE_CONSTRAINT_MUST_BE_ROW_MAJOR_MATRIX_TYPE( MT2 ); BLAZE_CONSTRAINT_MUST_FORM_VALID_MATMATMULTEXPR( MT1, MT2 ); /*! \endcond */ //********************************************************************************************** }; //************************************************************************************************* //================================================================================================= // // GLOBAL BINARY ARITHMETIC OPERATORS // //================================================================================================= //************************************************************************************************* /*!\brief Multiplication operator for the multiplication of a column-major sparse matrix and // a row-major dense matrix (\f$ A=B*C \f$). // \ingroup dense_matrix // // \param lhs The left-hand side sparse matrix for the multiplication. // \param rhs The right-hand side dense matrix for the multiplication. // \return The resulting matrix. // \exception std::invalid_argument Matrix sizes do not match. // // This operator represents the multiplication of a column-major sparse matrix and a row-major // dense matrix: \code using blaze::rowMajor; using blaze::columnMajor; blaze::CompressedMatrix<double,columnMajor> A; blaze::DynamicMatrix<double,rowMajor> B; blaze::DynamicMatrix<double,columnMajor> C; // ... Resizing and initialization C = A * B; \endcode // The operator returns an expression representing a dense matrix of the higher-order element // type of the two involved matrix element types \a T1::ElementType and \a T2::ElementType. // Both matrix types \a T1 and \a T2 as well as the two element types \a T1::ElementType and // \a T2::ElementType have to be supported by the MultTrait class template.\n // In case the current sizes of the two given matrices don't match, a \a std::invalid_argument // is thrown. */ template< typename T1 // Type of the left-hand side sparse matrix , typename T2 > // Type of the right-hand side dense matrix inline const TSMatDMatMultExpr<T1,T2> operator*( const SparseMatrix<T1,true>& lhs, const DenseMatrix<T2,false>& rhs ) { BLAZE_FUNCTION_TRACE; if( (~lhs).columns() != (~rhs).rows() ) { BLAZE_THROW_INVALID_ARGUMENT( "Matrix sizes do not match" ); } return TSMatDMatMultExpr<T1,T2>( ~lhs, ~rhs ); } //************************************************************************************************* //================================================================================================= // // ROWS SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct Rows< TSMatDMatMultExpr<MT1,MT2> > : public Rows<MT1> {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // COLUMNS SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct Columns< TSMatDMatMultExpr<MT1,MT2> > : public Columns<MT2> {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // ISALIGNED SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct IsAligned< TSMatDMatMultExpr<MT1,MT2> > : public IsTrue< IsAligned<MT2>::value > {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // ISLOWER SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct IsLower< TSMatDMatMultExpr<MT1,MT2> > : public IsTrue< And< IsLower<MT1>, IsLower<MT2> >::value > {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // ISUNILOWER SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct IsUniLower< TSMatDMatMultExpr<MT1,MT2> > : public IsTrue< And< IsUniLower<MT1>, IsUniLower<MT2> >::value > {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // ISSTRICTLYLOWER SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct IsStrictlyLower< TSMatDMatMultExpr<MT1,MT2> > : public IsTrue< Or< And< IsStrictlyLower<MT1>, IsLower<MT2> > , And< IsStrictlyLower<MT2>, IsLower<MT1> > >::value > {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // ISUPPER SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct IsUpper< TSMatDMatMultExpr<MT1,MT2> > : public IsTrue< And< IsUpper<MT1>, IsUpper<MT2> >::value > {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // ISUNIUPPER SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct IsUniUpper< TSMatDMatMultExpr<MT1,MT2> > : public IsTrue< And< IsUniUpper<MT1>, IsUniUpper<MT2> >::value > {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // ISSTRICTLYUPPER SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct IsStrictlyUpper< TSMatDMatMultExpr<MT1,MT2> > : public IsTrue< Or< And< IsStrictlyUpper<MT1>, IsUpper<MT2> > , And< IsStrictlyUpper<MT2>, IsUpper<MT1> > >::value > {}; /*! \endcond */ //************************************************************************************************* //================================================================================================= // // EXPRESSION TRAIT SPECIALIZATIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2, typename VT > struct TDMatDVecMultExprTrait< TSMatDMatMultExpr<MT1,MT2>, VT > { public: //********************************************************************************************** typedef typename SelectType< IsSparseMatrix<MT1>::value && IsColumnMajorMatrix<MT1>::value && IsDenseMatrix<MT2>::value && IsRowMajorMatrix<MT2>::value && IsDenseVector<VT>::value && IsColumnVector<VT>::value , typename TSMatDVecMultExprTrait< MT1, typename DMatDVecMultExprTrait<MT2,VT>::Type >::Type , INVALID_TYPE >::Type Type; //********************************************************************************************** }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2, typename VT > struct TDMatSVecMultExprTrait< TSMatDMatMultExpr<MT1,MT2>, VT > { public: //********************************************************************************************** typedef typename SelectType< IsSparseMatrix<MT1>::value && IsColumnMajorMatrix<MT1>::value && IsDenseMatrix<MT2>::value && IsRowMajorMatrix<MT2>::value && IsSparseVector<VT>::value && IsColumnVector<VT>::value , typename TSMatDVecMultExprTrait< MT1, typename DMatSVecMultExprTrait<MT2,VT>::Type >::Type , INVALID_TYPE >::Type Type; //********************************************************************************************** }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename VT, typename MT1, typename MT2 > struct TDVecTDMatMultExprTrait< VT, TSMatDMatMultExpr<MT1,MT2> > { public: //********************************************************************************************** typedef typename SelectType< IsDenseVector<VT>::value && IsRowVector<VT>::value && IsSparseMatrix<MT1>::value && IsColumnMajorMatrix<MT1>::value && IsDenseMatrix<MT2>::value && IsRowMajorMatrix<MT2>::value , typename TDVecDMatMultExprTrait< typename TDVecTSMatMultExprTrait<VT,MT1>::Type, MT2 >::Type , INVALID_TYPE >::Type Type; //********************************************************************************************** }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename VT, typename MT1, typename MT2 > struct TSVecTDMatMultExprTrait< VT, TSMatDMatMultExpr<MT1,MT2> > { public: //********************************************************************************************** typedef typename SelectType< IsSparseVector<VT>::value && IsRowVector<VT>::value && IsSparseMatrix<MT1>::value && IsColumnMajorMatrix<MT1>::value && IsDenseMatrix<MT2>::value && IsRowMajorMatrix<MT2>::value , typename TDVecDMatMultExprTrait< typename TDVecTSMatMultExprTrait<VT,MT1>::Type, MT2 >::Type , INVALID_TYPE >::Type Type; //********************************************************************************************** }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2, bool AF > struct SubmatrixExprTrait< TSMatDMatMultExpr<MT1,MT2>, AF > { public: //********************************************************************************************** typedef typename MultExprTrait< typename SubmatrixExprTrait<const MT1,AF>::Type , typename SubmatrixExprTrait<const MT2,AF>::Type >::Type Type; //********************************************************************************************** }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct RowExprTrait< TSMatDMatMultExpr<MT1,MT2> > { public: //********************************************************************************************** typedef typename MultExprTrait< typename RowExprTrait<const MT1>::Type, MT2 >::Type Type; //********************************************************************************************** }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename MT1, typename MT2 > struct ColumnExprTrait< TSMatDMatMultExpr<MT1,MT2> > { public: //********************************************************************************************** typedef typename MultExprTrait< MT1, typename ColumnExprTrait<const MT2>::Type >::Type Type; //********************************************************************************************** }; /*! \endcond */ //************************************************************************************************* } // namespace blaze #endif
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
9d56752d4a3d4633dace9948d7b6b1d129ab1053
e570afd5eadc2315c3bf0611b258e52784403833
/acmCoder/构造队列.cpp
60ee916acc78b7872b7576203112486dfdea50f1
[]
no_license
futureCoder/algorithms
dccad33d69125f99cae10eb339d7849116fb8c07
efc73da82122823f571675e6200547a2f5a45247
refs/heads/master
2021-01-16T23:58:20.343282
2020-06-01T16:18:31
2020-06-01T16:18:31
58,052,627
0
0
null
null
null
null
UTF-8
C++
false
false
921
cpp
#include <iostream> #include <vector> #include <string> #include <map> #include <queue> #include <algorithm> #include <cmath> #include <cstdio> #include <iomanip> using namespace std; vector<int> rebuild(vector<int> myvec, int len, int remain) { int curIdx = len; while(remain != 0 && curIdx < myvec.size()) { for(int i = 0; i < len; ++i) { if(myvec[i] != 0) continue; if(myvec[curIdx] != 0) { myvec[i] = myvec[curIdx]; --remain; } ++curIdx; } } return vector<int>(myvec.begin(), myvec.begin() + len); } int main() { int T; while(cin >> T) { while(T--) { int n; cin >> n; vector<int> myvec(2 * n, 0); int val = 0; for(int i = 1; i < myvec.size(); i += 2) myvec[i] = ++val; int remain = 2 * n - val; vector<int> ret = rebuild(myvec, n, remain); for(int i = 0; i < n; ++i) { char c = (i == n - 1) ? '\n' : ' '; cout << ret[i] << c; } } } }
[ "jason-dong@foxmail.com" ]
jason-dong@foxmail.com
10e4244614ee0d93a588533f037bed67aed27caf
203889eca5b44a681071b332b82b09c3f8cd1d56
/acwandroid/app/src/main/cpp/jni/JavaContainers.h
0ef26fa63b41a2ef75b9ec23c913ef7a311c4541
[]
no_license
lakizoli/ACW
0ad1672747a616919f6d14e2052cdb6cd156269c
940fc7eed24b589cf135e474b6c6e73c1b69721d
refs/heads/master
2022-11-04T11:16:44.276563
2022-10-27T05:35:56
2022-10-27T05:35:56
142,253,380
0
0
null
null
null
null
UTF-8
C++
false
false
4,988
h
#ifndef JAVACONTAINERS_H_INCLUDED #define JAVACONTAINERS_H_INCLUDED #include "JavaObject.h" #include "vector" //////////////////////////////////////////////////////////////////////////////////////////////////// // JNI helper for Java Containers //////////////////////////////////////////////////////////////////////////////////////////////////// namespace jni_containers { //Java class signature extern JNI::jClassID jArrayListClass; //Java method and field signatures extern JNI::jCallableID jALInitMethod; extern JNI::jCallableID jALAddMethod; extern JNI::jCallableID jALSizeMethod; extern JNI::jCallableID jALGetMethod; extern JNI::jCallableID jALClearMethod; } //////////////////////////////////////////////////////////////////////////////////////////////////// // C++ implementation of the JavaIterator class //////////////////////////////////////////////////////////////////////////////////////////////////// class JavaIterator : public JavaObject { DECLARE_DEFAULT_JAVAOBJECT (JavaIterator); public: bool hasNext () const; JavaObject next () const; private: JavaIterator () = delete; }; //////////////////////////////////////////////////////////////////////////////////////////////////// // C++ implementation of the JavaSet class //////////////////////////////////////////////////////////////////////////////////////////////////// class JavaSet : public JavaObject { DECLARE_DEFAULT_JAVAOBJECT (JavaSet); public: JavaIterator iterator () const; private: JavaSet () = delete; }; //////////////////////////////////////////////////////////////////////////////////////////////////// // C++ implementation of the JavaEntry class //////////////////////////////////////////////////////////////////////////////////////////////////// class JavaEntry : public JavaObject { DECLARE_DEFAULT_JAVAOBJECT (JavaEntry); public: JavaObject key () const; JavaObject value () const; private: JavaEntry () = delete; }; //////////////////////////////////////////////////////////////////////////////////////////////////// // C++ implementation of the JavaHashMap class //////////////////////////////////////////////////////////////////////////////////////////////////// class JavaHashSet : public JavaObject { DECLARE_DEFAULT_JAVAOBJECT (JavaHashSet); public: JavaHashSet (); public: int size () const; void add (const JavaObject& obj); bool contains (const JavaObject& obj) const; JavaIterator iterator () const; }; //////////////////////////////////////////////////////////////////////////////////////////////////// // C++ implementation of the JavaHashMap class //////////////////////////////////////////////////////////////////////////////////////////////////// class JavaHashMap : public JavaObject { DECLARE_DEFAULT_JAVAOBJECT (JavaHashMap); public: JavaHashMap (); public: int size () const; void put (const JavaObject& key, const JavaObject& value); JavaObject at (const JavaObject& key) const; bool containsKey (const JavaObject& key) const; void iterate (std::function<bool (JavaObject key, JavaObject value)> callback) const; }; //////////////////////////////////////////////////////////////////////////////////////////////////// // C++ implementation of the JavaArrayList class //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T = JavaObject> class JavaArrayList : public JavaObject { DECLARE_DEFAULT_JAVAOBJECT (JavaArrayList); public: JavaArrayList<T> () : JavaObject () { JNI::AutoLocalRef<jobject> jobj (JNI::GetEnv ()->NewObject (JNI::JavaClass (jni_containers::jArrayListClass), JNI::JavaMethod (jni_containers::jALInitMethod))); mObject = JNI::GlobalReferenceObject (jobj.get ()); } template<class N> static JavaArrayList<T> createFromVector (const std::vector<N>& vec) { JavaArrayList<T> jArr; for (const N& item : vec) { jArr.add (T (item).get ()); } return jArr; } template<class N> static JavaArrayList<T> createFromVector (const std::vector<N>& vec, std::function<T (const N& item)> getJavaItem) { JavaArrayList<T> jArr; for (const N& item : vec) { jArr.add (getJavaItem (item)); } return jArr; } public: int size () const { return JNI::GetEnv ()->CallIntMethod (mObject, JNI::JavaMethod (jni_containers::jALSizeMethod)); } bool add (const T& what) { return JNI::GetEnv ()->CallBooleanMethod (mObject, JNI::JavaMethod (jni_containers::jALAddMethod), what.get ()); } T itemAt (int index) const { return JNI::CallObjectMethod<T> (mObject, JNI::JavaMethod (jni_containers::jALGetMethod), index); } void clear () { JNI::GetEnv ()->CallVoidMethod (mObject, JNI::JavaMethod (jni_containers::jALClearMethod)); } template<class N> std::vector<N> toVector (N (T::* getItem) () const) const { std::vector<N> res; if (mObject != nullptr) { for (int i = 0, iEnd = size (); i < iEnd; ++i) { T item = itemAt (i); res.push_back ((item.*getItem) ()); } } return res; } }; #endif //JAVACONTAINERS_H_INCLUDED
[ "lakizoli@yahoo.com" ]
lakizoli@yahoo.com
3249be047bcc43ea2a575ce272d48bceaa0fa87a
1b2a5c6c07814f265471a0c42019bdca2e352433
/动态规划_04/动态规划_04/test.cpp
856dcba755f25101a1a6aab1aeb9ff0c3099fff8
[]
no_license
HotPot-J/algorithms
d83c11a58876830ea44e849c061884449ea3d5c2
ad4e55ca6529108738b72c3c3d49409d9a2b1bcb
refs/heads/master
2021-01-02T00:30:31.216442
2020-09-25T08:39:23
2020-09-25T08:39:23
239,411,304
0
0
null
null
null
null
GB18030
C++
false
false
6,432
cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> #include<vector> #include<algorithm> using namespace std; /* 121. 买卖股票的最佳时机 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。 注意:你不能在买入股票前卖出股票。 示例 1: 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。 示例 2: 输入: [7,6,4,3,1] 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 */ /* 思路: 维护一个最小值(买入点) 维护一个最大值(卖出点) */ class Solution { public: int maxProfit(vector<int>& prices) { int _min = INT_MAX; int res = 0; for (int i = 0; i < prices.size(); ++i){ if (prices[i] < _min){ _min = prices[i]; } else if (prices[i] - _min>res){ res = prices[i] - _min; } } return res; } }; //int main(){ // vector<int> arr = { 7, 1, 5, 3, 6, 4 }; // Solution a; // cout<<a.maxProfit(arr)<<endl; // return 0; //} /* 198. 打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有 相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。给定一个代表每个房屋存放金额的非 负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 示例 1: 输入:[1, 2, 3, 1] 输出:4 解释:偷窃 1 号房屋(金额 = 1) ,然后偷窃 3 号房屋(金额 = 3)。 偷窃到的最高金额 = 1 + 3 = 4 。 示例 2: 输入:[2, 7, 9, 3, 1] 输出:12 解释:偷窃 1 号房屋(金额 = 2), 偷窃 3 号房屋(金额 = 9),接着偷窃 5 号房屋(金额 = 1)。 偷窃到的最高金额 = 2 + 9 + 1 = 12 。*/ /* 1.目标,在不触发报警装置的情况下能偷到的最大金额 2.状态:f(i):偷到第i家时的最大金额 3.f(2):2 (代表第一家) f(3):7 (不能连续偷) f(4):f(1)+arr[3-1] f(i) = max(f(i),f(j)+arr[i-2]) (j<i-1) */ class Solution1 { public: int rob(vector<int>& nums) { if (nums.empty()) return 0; int len = nums.size(); vector<int> dp(len + 2, 0); int res = INT_MIN; for (int i = 2; i <= len + 1; ++i){ for (int j = 0; j < i - 1; ++j){ dp[i] = max(dp[i], dp[j] + nums[i - 2]); } if (dp[i]>res) res = dp[i]; } return res; } }; //int main(){ // vector<int> arr = { 2, 7, 9, 3, 1 }; // Solution1 a; // cout << a.rob(arr) << endl; // return 0; //} /* 303. 区域和检索 - 数组不可变 给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。 示例: 给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 说明: 你可以假设数组不可变。 会多次调用 sumRange 方法。 */ /* 思路一:动态规划(比暴力法能好点,空间换时间) 1.f(i,j):表示从i-j之和 2.由于只有i~j,不会有j~i,所以这是一个上半三角矩阵 3.i=j:f(i,j) = nums[j] i<j:f(i,j) = dp[i][j-1]+nums[j] */ class NumArray { vector<vector<int>> dp; public: NumArray(vector<int>& nums) { int len = nums.size(); dp.resize(len); for (int i = 0; i < len; ++i){ dp[i].resize(len, 0); for (int j = i; j< len; ++j){ if (i == j){ dp[i][j] = nums[j];} else{ dp[i][j] = dp[i][j - 1] + nums[j]; } } } } int sumRange(int i, int j) { return dp[i][j]; } }; //int main(){ // vector<int> arr = { -2, 0, 3, -5, 2, -1 }; // NumArray a(arr); // cout << a.sumRange(0, 2) << endl; // cout << a.sumRange(2, 5) << endl; // cout << a.sumRange(0, 5) << endl; // return 0; //} /* 思路二:动态规划(优化) f(i)表示从第一个数字到第i个数字之和 f(i) = f(i-1)+nums[i] nums:-2, 0, 3, -5, 2, -1 f(i):0,-2,-2,1,-4,-2,-1 (初始状态f(0)=0) F(0,0) = f(1)-f(0) = -2 F(0,5):f(6)-f(0) = -1 那么F(i,j) = f(j+1)-f(i) 初始状态:f(0) = 0; */ class NumArray1 { public: vector<int> dp; NumArray1(vector<int>& nums) { dp.resize(nums.size() + 1, 0); for (int i = 1; i <= nums.size(); ++i){ dp[i] = dp[i - 1] + nums[i - 1]; } } int sumRange(int i, int j) { return dp[j + 1] - dp[i]; } }; /* 746. 使用最小花费爬楼梯 数组的每个索引作为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。 每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。 您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。 示例 1: 输入: cost = [10, 15, 20] 输出: 15 解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。 示例 2: 输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] 输出: 6 解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。 注意: cost 的长度将会在 [2, 1000]。 每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。 */ /* 思路: 目标:到达楼层顶部的最低花费 状态: f(i)表示到达当前楼层的最低花费 初始状态f(0):0 表示一开始在起点位置的花费为0 f(1):cost[0]如果跳上第一阶的花费为cost[0] f(2):cost[1]如果跳上第二阶的花费为cost[1] f(3):min(cost[0],cost[1])+cost[2] 即:f(i) = min(f(i-1),f(i-2))+cost[i-1] int len = cost.size(); 我们可以将数组多开辟两个位置,f(0)=0最为初始状态,而f(i+1)存储结果 */ class Solution3 { public: int minCostClimbingStairs(vector<int>& cost) { if (cost.empty()) return 0; int len = cost.size(); vector<int> dp(len + 2, 0); dp[1] = cost[0]; for (int i = 2; i <= len + 1; ++i){ dp[i] = min(dp[i - 1], dp[i - 2]); if (i <len+1){ dp[i] += cost[i - 1]; } } return dp[len + 1]; } }; //int main(){ // vector<int> arr = { 10, 15, 20 }; // Solution3 a; // a.minCostClimbingStairs(arr); // return 0; //}
[ "807126916@qq.com" ]
807126916@qq.com
7821a952ed891dc3ebcd33e1ae80b9a43264f156
ae33344a3ef74613c440bc5df0c585102d403b3b
/SDK/SOT_Proposal_OOS_Chapters_Rank10Reward_002_classes.hpp
1ef8f0b2e83331c596ca5bc34e29eb4937d7020c
[]
no_license
ThePotato97/SoT-SDK
bd2d253e811359a429bd8cf0f5dfff73b25cecd9
d1ff6182a2d09ca20e9e02476e5cb618e57726d3
refs/heads/master
2020-03-08T00:48:37.178980
2018-03-30T12:23:36
2018-03-30T12:23:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
789
hpp
#pragma once // SOT: Sea of Thieves (1.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x4) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Proposal_OOS_Chapters_Rank10Reward_002.Proposal_OOS_Chapters_Rank10Reward_002_C // 0x0000 (0x00F0 - 0x00F0) class UProposal_OOS_Chapters_Rank10Reward_002_C : public UVoyageProposalDesc { public: static UClass* StaticClass() { static UClass* ptr = 0; if(ptr == 0) { ptr = UObject::FindClass(_xor_("BlueprintGeneratedClass Proposal_OOS_Chapters_Rank10Reward_002.Proposal_OOS_Chapters_Rank10Reward_002_C")); } return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "antoniohermano@gmail.com" ]
antoniohermano@gmail.com
09437c4bf2f9e719ec49189bc9b2056df6cb47d8
70d119732872d95582b273b104f663191e3b11f5
/MinPriorityLinkQueue.cc
607b90f9d4535d093a8a0420ff6bbf68387d7620
[]
no_license
sundongxu/data-structure
9d5033f49a3628a263d13dac7f3fd1847d521629
668454c1c780ad93697c85b92a8026f6a4a8525c
refs/heads/master
2021-09-13T21:16:56.415533
2018-05-04T08:58:23
2018-05-04T08:58:23
92,672,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,690
cc
#include "MinPriorityLinkQueue.h" // 最小优先链队列类的实现部分 template <class ElemType> int MinPriorityLinkQueue<ElemType>::InQueue(const ElemType &e) { // 操作结果:插入元素e为新的队尾,返回SUCCESS Node<ElemType> *curPtr = LinkQueue<ElemType>::front->next; // 指向当前结点 Node<ElemType> *curPrePtr = LinkQueue<ElemType>::front; // 指向当前结点的前驱结点 while (curPtr != nullptr && curPtr->val <= e) { // curPtr与curPrePtr都指向下一元素 curPrePtr = curPtr; curPtr = curPtr->next; } Node<ElemType> *tmpPtr = new Node<ElemType>(e, curPtr); // 生成新结点 curPrePtr->next = tmpPtr; // 将tmpPtr插入在curPrePtr与curPtr之间 if (curPrePtr == LinkQueue<ElemType>::rear) { // 新结点插在rear的后面 LinkQueue<ElemType>::rear = tmpPtr; // rear指向新队尾 } return SUCCESS; } int main() { // 最大优先链队列成员函数测试 // 测试InQueue、GetHead、OutQueue int e; MinPriorityLinkQueue<int> q; q.InQueue(1); q.InQueue(2); q.InQueue(3); q.InQueue(4); q.InQueue(5); q.GetHead(e); cout << "队首元素:" << e << endl; q.Traverse(Print); cout << endl; q.OutQueue(e); q.OutQueue(e); q.Traverse(Print); cout << endl; // 测试拷贝构造 MinPriorityLinkQueue<int> q1(q); q1.Traverse(Print); cout << endl; // 测试赋值运算符 MinPriorityLinkQueue<int> q2; q2.InQueue(6); q2.InQueue(7); q2.Traverse(Print); cout << endl; q2 = q; q2.Traverse(Print); return 0; }
[ "371211947@qq.com" ]
371211947@qq.com
d552ba74c2e7b8bef4f544489a8521e76197f838
fd0353304f33f09da62099f05b68b11bf691fa23
/Informe/_informe/FlujoDeRedes/FordFulkerson.h
2bb156b79d313ada307b411377a8dd921079b098
[]
no_license
addinkevin/TDA
06ccd07c24c53c559e879f46ebe12f859b32563f
7fcf70cdbf315d867db56def451c8406d524765d
refs/heads/master
2021-05-08T06:51:50.670935
2016-12-08T05:01:56
2016-12-08T05:01:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
851
h
#ifndef TRABAJOPRACTICO2_FORDFULKENSON_H #define TRABAJOPRACTICO2_FORDFULKENSON_H #include <vector> #include "Edge.h" #include "Digraph.h" #include "Flow.h" #include "ParserNetworkFlow.h" using namespace std; class FordFulkerson { private: ParserNetworkFlow *parser; Flow* flow; vector<int> setS; vector<int> setT; int bottleneck(vector<Edge*> pathInResidualGraph); void augment(vector<Edge*> pathInResidualGraph); bool isEdgeForward(Edge* edge); Edge *getEdgeInG(Edge *edgeInGResidual); vector<Edge *> getPathST(); void calculateMinCut(); public: FordFulkerson(ParserNetworkFlow* parser); ~FordFulkerson(); void maxFlow(); vector<int> getSetS(); vector<int> getSetT(); vector<int> getProjects(); vector<int> getAreas(); }; #endif //TRABAJOPRACTICO2_FORDFULKENSON_H
[ "addinkevin@gmail.com" ]
addinkevin@gmail.com
b6a5e284879849b7ce6546b6582007e59552fce3
b91c85cc541226f1d8b75205e11ae2ff27085097
/계산기/공준배_계산기(클래스)/공준배_CPP_Calculator/Usplash.cpp
3d32a8e32eb298975dccf3307e0720e43bb9be5a
[]
no_license
devgearedu/DelphiWindow
f88d9621995bb58c5eab4a689fef9ea81e4e9208
745534fe1e8db157309afb45c79f32c87f4ce27b
refs/heads/master
2021-08-30T10:38:21.426254
2021-08-20T10:23:32
2021-08-20T10:23:32
194,223,332
1
1
null
null
null
null
UTF-8
C++
false
false
521
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Usplash.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TSplashForm *SplashForm; //--------------------------------------------------------------------------- __fastcall TSplashForm::TSplashForm(TComponent* Owner) : TForm(Owner) { } //---------------------------------------------------------------------------
[ "kwk@embarcadero.kr" ]
kwk@embarcadero.kr
cc3846e4507a51c6ff7df5a39105ad99588949bf
8c2144d40c9bb8ece222e609f2647879102e685b
/CODING BLOCKS/BEGINNER C++/1/mpn.cpp
32be46c58f90937e4e7017fc7605e41381ac4b0a
[]
no_license
Arpit-Jindal/My-Codes
c09cf5897b72e4c83f78bf01fee9943f30c55f50
c6bc249df93e88dd1e3100cc398f8bdada8e3786
refs/heads/master
2022-11-26T09:59:41.570859
2020-08-05T12:43:26
2020-08-05T12:43:26
285,284,684
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
#include <iostream> using namespace std; int main() { int m, n; cout << "enter m\n"; cin >> m; cout << "enter n\n"; cin >> n; int ans = 1; for (int i = 1; i <= m; i++) { ans = ans * n ; } cout << ans; }
[ "arpitjindaldtu@gmail.com" ]
arpitjindaldtu@gmail.com
b7620b36af2fd985e73a70f9cbb07acffef01d2a
f97f5f15a9d7d146ed7d9dcc8c0e0b40f37d76bb
/test/parser/parsing_bracket_notation_size_test.cc
fa084baf2fcb18fbfebe5f3a893a9d30aca6e37b
[]
no_license
deadoggy/tree-similarity
70394aa3b844401844f5af5be2737ce8d2274353
bb45515366a73d3fcc6318d349c8147dedf5551a
refs/heads/master
2022-12-10T02:02:38.926364
2017-07-05T07:52:38
2017-07-05T07:52:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
998
cc
#include <iostream> #include <string> #include <vector> #include <fstream> #include "string_label.h" #include "node.h" #include "bracket_notation_parser.h" int main() { using Label = label::StringLabel; // Parse test cases from file. std::ifstream test_cases_file("size_test_data.txt"); for (std::string line; std::getline( test_cases_file, line);) { if (line[0] == '#') { std::getline(test_cases_file, line); std::string input_tree = line; std::getline(test_cases_file, line); int correct_result = std::stoi(line); // Parse test tree. parser::BracketNotationParser bnp; node::Node<Label> t = bnp.parse_string(input_tree); int computed_results = t.get_tree_size(); if (correct_result != computed_results) { std::cerr << "Incorrect number of nodes: " << computed_results << " instead of " << correct_result << std::endl; std::cerr << input_tree << std::endl; return -1; } } } return 0; }
[ "mpawlik@cosy.sbg.ac.at" ]
mpawlik@cosy.sbg.ac.at
ae07a222129d756ffd7e5a44c18ab3f02c0a4206
81528f582dd6d727bc0661723f0258e4e6ecc881
/solutions/11078-OpenCreditSystem/11078.cpp
756cfdbf5c56ac84617730c7fff2c1edbc5f0bb7
[]
no_license
remerson/uva
6123e283b0b4762acc6a131df1c5ee5b8cb029a0
d3a288d13657af45229421bfa6f3cbd3e8fa40c2
refs/heads/master
2023-07-22T17:20:27.577541
2023-07-15T21:01:05
2023-07-15T21:01:05
18,739,804
2
1
null
null
null
null
UTF-8
C++
false
false
5,819
cpp
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> #include <set> #include <map> #include <queue> #include <iostream> #include <iterator> #include <bitset> #include <unistd.h> #ifndef ONLINE_JUDGE #define DEBUG(X) { X; } #else #define DEBUG(X) #endif /////////////////////////////////////////////////////////////////////////////// // // Cut and paste everything from below here // #include <unistd.h> #ifndef ONLINE_JUDGE #define DEBUG_READ(X) { X; } #else #define DEBUG_READ(X) #endif namespace { const size_t BLOCK_SIZE_BYTES = 4096; const size_t NUM_BLOCKS = 2; // // Optimised integer (signed/unsigned) only read from stdin. // // This can only read integers. // // Assumes the input file only contains number characters (0-9) // or non-readable characters (< ASCII 47). // // Input containing ASCII values above 57 ('9') will give // unpredictable (bad) results. You have been warned. // // Do not mix using this with scanf/cin. It will not work. // // Copying is also probably a bad idea. // // It is intended to be instantiated once only up front in main() // and then used until termination. // class buffered_read { public: buffered_read() : current_(0), index_(0), size_(0) { #ifdef ONLINE_JUDGE std::ios_base::sync_with_stdio(false); #endif read_block(); } // // Read a signed value into v. // // Returns a flag to indicate whether more input is available (true) // or not (false). // // The type NUM must support operators: =, * and +. // // It must also support signed values and be large enough to hold // the value read. // template<typename NUM> bool read_signed(NUM &v) { bool negative = false; v = 0; // "fast" path - "far" from end of block if(size_ > 16) { char *current = current_; const char *start = current_; while(*current < 48) { if(*current == '-') negative = true; ++current; } do { v = v * 10 + *current - '0'; ++current; } while(*current > 47); if(negative) v *= -1; size_ -= (current - start); current_ = current; DEBUG_READ(printf(" -- (fast) read_signed = %d\n", v)); return true; // must be more to read (although more carefully) } // "slow" path - near end of block while(*current_ < 48 && !end_reached()) { if(*current_ == '-') negative = true; advance(); } while(*current_ > 47 && !end_reached()) { v = v * 10 + *current_ - '0'; advance(); } if(negative) v *= -1; DEBUG_READ(printf(" -- (slow) read_signed = %d\n", v)); return !end_reached(); } // // Read an signed value into v. Optimised to not bother looking // for a leading unary minus. // // Returns a flag to indicate whether more input is available (true) // or not (false). // // The type NUM must support operators: =, * and +. // // It must also support unsigned values and be large enough to hold // the value read. // template<typename NUM> bool read_unsigned(NUM &v) { v = 0; // "fast" path if(size_ > 16) { char *current = current_; const char *start = current_; while(*current < 48) ++current; do { v = v * 10 + *current - '0'; ++current; } while(*current > 47); size_ -= (current - start); current_ = current; DEBUG_READ(printf(" -- (fast) read_unsigned = %u\n", v)); return true; // must be more to read (although more carefully) } // "slow" path while(*current_ < 48 && !end_reached()) advance(); while(*current_ > 47 && !end_reached()) { v = v * 10 + *current_ - '0'; advance(); } DEBUG_READ(printf(" -- (slow) read_unsigned = %u\n", v)); return !end_reached(); } bool end_reached() const { return size_ == 0; } private: void advance() { --size_; if(size_ == 0) { read_block(); } else { ++current_; } } void read_block() { current_ = &blocks_[index_][0]; size_ = read(0, current_, sizeof(char) * BLOCK_SIZE_BYTES); ++index_; index_ = (index_ % NUM_BLOCKS); } // Remaining bytes left in current block char *current_; char blocks_[NUM_BLOCKS][BLOCK_SIZE_BYTES]; size_t index_; size_t size_; }; } // namespace // // End of buffered_read // /////////////////////////////////////////////////////////////////////////////// using namespace std; int main() { // #ifdef ONLINE_JUDGE // std::ios_base::sync_with_stdio(false); // #endif int t; buffered_read input; input.read_unsigned(t); const int MAX_N = 150100; int scores[MAX_N]; for(int s = 0; s < t; ++s) { int n; input.read_signed(n); for(int i = 0; i < n; ++i) { input.read_signed(scores[i]); DEBUG(printf("scores[%d] = %d\n", i, scores[i])); } int global_max = -99999999; int highest = scores[n-1]; DEBUG(printf("start %d highest = %d\n", n-1, highest)); for(int i = n-2; i >= 0; --i) { DEBUG(printf("i = %d highest = %d max = %d\n", i, highest, global_max)); const int value = scores[i] - highest; if(value > global_max) global_max = value; if(scores[i] < highest) highest = scores[i]; } printf("%d\n", global_max); } return 0; }
[ "remerson@fastmail.fm" ]
remerson@fastmail.fm
265d45b26e695e05638025cb513c4f90e463fbcb
3ba610a5e441d6b7062e964d461511ba2ac71d02
/Merge_two_sorted_lists.cpp
72708bb70f100f79fc76cb5ea17b80eec88670b0
[]
no_license
uttam-anand/Interview-Preparation-Kit
996c7c268aa95c7210285a49ade34296f4931de3
b18302b9926532daa104ec5c679818899a59eed8
refs/heads/main
2023-04-06T11:02:17.299295
2021-04-24T13:54:54
2021-04-24T13:54:54
322,326,187
1
0
null
null
null
null
UTF-8
C++
false
false
779
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head=NULL; ListNode** ptr=&head; while(l1 && l2){ if(l1->val>=l2->val){ *ptr=l2; l2=l2->next; } else{ *ptr=l1; l1=l1->next; } ptr=&((*ptr)->next); } if(l1) *ptr=l1; if(l2) *ptr=l2; return head; } };
[ "noreply@github.com" ]
noreply@github.com
c96aa3b05376eaefe12fc58088cd05c4686ee4f1
613bb55365d68e31ec68d3c101d4630681d1c8ee
/source/include/xulrunner-sdk/include/dom/nsIDOMSVGAnimatedAngle.h
7893fc2253ce2942ad64ab358f8ecf8e1bf90376
[]
no_license
changpinggou/NPAPI-ActiveX
db478bc7bfecc7d995a1dd3a380ff6bacf5891e4
805a311f457d64acc34ba818a495792679636205
refs/heads/master
2021-01-10T13:31:30.766738
2015-06-25T02:18:08
2015-06-25T02:18:08
36,733,400
1
0
null
null
null
null
UTF-8
C++
false
false
3,521
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/xr19rel/WINNT_5.2_Depend/mozilla/dom/public/idl/svg/nsIDOMSVGAnimatedAngle.idl */ #ifndef __gen_nsIDOMSVGAnimatedAngle_h__ #define __gen_nsIDOMSVGAnimatedAngle_h__ #ifndef __gen_domstubs_h__ #include "domstubs.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIDOMSVGAngle; /* forward declaration */ /* starting interface: nsIDOMSVGAnimatedAngle */ #define NS_IDOMSVGANIMATEDANGLE_IID_STR "c6ab8b9e-32db-464a-ae33-8691d44bc60a" #define NS_IDOMSVGANIMATEDANGLE_IID \ {0xc6ab8b9e, 0x32db, 0x464a, \ { 0xae, 0x33, 0x86, 0x91, 0xd4, 0x4b, 0xc6, 0x0a }} /** * The nsIDOMSVGAnimatedAngle interface is the interface to an SVG * animated angle. * * For more information on this interface please see * http://www.w3.org/TR/SVG11/types.html#InterfaceSVGAnimatedAngle * */ class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMSVGAnimatedAngle : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSVGANIMATEDANGLE_IID) /* readonly attribute nsIDOMSVGAngle baseVal; */ NS_SCRIPTABLE NS_IMETHOD GetBaseVal(nsIDOMSVGAngle * *aBaseVal) = 0; /* readonly attribute nsIDOMSVGAngle animVal; */ NS_SCRIPTABLE NS_IMETHOD GetAnimVal(nsIDOMSVGAngle * *aAnimVal) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMSVGAnimatedAngle, NS_IDOMSVGANIMATEDANGLE_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMSVGANIMATEDANGLE \ NS_SCRIPTABLE NS_IMETHOD GetBaseVal(nsIDOMSVGAngle * *aBaseVal); \ NS_SCRIPTABLE NS_IMETHOD GetAnimVal(nsIDOMSVGAngle * *aAnimVal); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMSVGANIMATEDANGLE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetBaseVal(nsIDOMSVGAngle * *aBaseVal) { return _to GetBaseVal(aBaseVal); } \ NS_SCRIPTABLE NS_IMETHOD GetAnimVal(nsIDOMSVGAngle * *aAnimVal) { return _to GetAnimVal(aAnimVal); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMSVGANIMATEDANGLE(_to) \ NS_SCRIPTABLE NS_IMETHOD GetBaseVal(nsIDOMSVGAngle * *aBaseVal) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetBaseVal(aBaseVal); } \ NS_SCRIPTABLE NS_IMETHOD GetAnimVal(nsIDOMSVGAngle * *aAnimVal) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAnimVal(aAnimVal); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMSVGAnimatedAngle : public nsIDOMSVGAnimatedAngle { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMSVGANIMATEDANGLE nsDOMSVGAnimatedAngle(); private: ~nsDOMSVGAnimatedAngle(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMSVGAnimatedAngle, nsIDOMSVGAnimatedAngle) nsDOMSVGAnimatedAngle::nsDOMSVGAnimatedAngle() { /* member initializers and constructor code */ } nsDOMSVGAnimatedAngle::~nsDOMSVGAnimatedAngle() { /* destructor code */ } /* readonly attribute nsIDOMSVGAngle baseVal; */ NS_IMETHODIMP nsDOMSVGAnimatedAngle::GetBaseVal(nsIDOMSVGAngle * *aBaseVal) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIDOMSVGAngle animVal; */ NS_IMETHODIMP nsDOMSVGAnimatedAngle::GetAnimVal(nsIDOMSVGAngle * *aAnimVal) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMSVGAnimatedAngle_h__ */
[ "applechang@applechang-PC2.tencent.com" ]
applechang@applechang-PC2.tencent.com
4204b17d2242019ea3dd558adab151744d955774
df7c38f47332dd5318c71f8059b1560576699c70
/Even_Number_LED_Pattern.ino
fb73cd10b53d04310e3ef6bb69b00da82a942ed4
[]
no_license
Dearth96/Arduino
2633a6be47b9e1883663bef3397df3ed0594132a
e7235107891c89d8d05f475a5322b0fe5befc64d
refs/heads/master
2021-01-11T19:10:25.965629
2017-01-18T14:04:34
2017-01-18T14:04:34
79,330,748
0
0
null
null
null
null
UTF-8
C++
false
false
473
ino
const int a = 3; // The number depends on the number of LED's attached// const int k[a] = {11,12,13};// the number should be the pins connected to it// void setup(){ for(int i = 0; i<a;i++){ pinMode(k[i], OUTPUT); } } void loop(){ for(int i =0;i<a;i++){ if(i % 2 == 0){ digitalWrite(k[i], HIGH); delay(1000); } } for(int i = a-1;i>=0;i--){ if( i % 2 == 0){ digitalWrite(k[i], LOW); delay(1000); } } }
[ "noreply@github.com" ]
noreply@github.com
594f8bb1aaf55b6300daf4071a39ebf4b227611c
c4ce8f47a4923054e85d6add96984c8fa70ae3d6
/Tool.cpp
2f3c24fb6d8805d83a94db4e4a94cdfa13e2d972
[]
no_license
MindEater123/Chess
17afd0312ee145eaa5180ee2d179b355af7818ef
01a2aaeb3e1cd6144efddbd208135b0020302c44
refs/heads/master
2021-01-12T05:27:06.214207
2017-01-03T15:29:53
2017-01-03T15:29:53
77,929,106
1
2
null
null
null
null
UTF-8
C++
false
false
726
cpp
#include "Tool.h" Point Tool::_kingLoc[2]; Tool::Tool() { this->_color = WHITE; this->_ifMove = 0; this->_place; } Tool::Tool(bool color,Point& place) { this->_color = color; this->_ifMove = 0; this->_place = place; } int Tool::canMove(Point toMove , Tool* board[BOARD_SIZE][BOARD_SIZE]) { return 0; } Tool::~Tool() {} void Tool::setPlace(Point place) { this->_place = place; } void Tool::setifmove() { this->_ifMove = 1; } bool Tool::getColor() { return this->_color; } Point Tool::getPlace() { return this->_place; } void Tool::setKingLoc() { this->_kingLoc[this->_color] = this->getPlace(); } Point* Tool::getkingLoc() { return this->_kingLoc; }
[ "noreply@github.com" ]
noreply@github.com
ddc9c98e9368a06d21a64dc34ed2ad9a183ae1e1
a815edcd3c7dcbb79d7fc20801c0170f3408b1d6
/chrome/browser/page_load_metrics/observers/page_capping_page_load_metrics_observer.cc
0d8ad92a0472ed3a1b9174b69faefddced9c5da3
[ "BSD-3-Clause" ]
permissive
oguzzkilic/chromium
06be90df9f2e7f218bff6eee94235b6e684e2b40
1de71b638f99c15a3f97ec7b25b0c6dc920fbee0
refs/heads/master
2023-03-04T00:01:27.864257
2018-07-17T10:33:19
2018-07-17T10:33:19
141,275,697
1
0
null
2018-07-17T10:48:53
2018-07-17T10:48:52
null
UTF-8
C++
false
false
12,698
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/page_load_metrics/observers/page_capping_page_load_metrics_observer.h" #include <algorithm> #include <utility> #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" #include "base/optional.h" #include "base/rand_util.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/data_use_measurement/page_load_capping/chrome_page_load_capping_features.h" #include "chrome/browser/data_use_measurement/page_load_capping/page_load_capping_blacklist.h" #include "chrome/browser/data_use_measurement/page_load_capping/page_load_capping_infobar_delegate.h" #include "chrome/browser/data_use_measurement/page_load_capping/page_load_capping_service.h" #include "chrome/browser/data_use_measurement/page_load_capping/page_load_capping_service_factory.h" #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/page_load_metrics/page_load_metrics_util.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" namespace { const char kMediaPageCap[] = "MediaPageCapMiB"; const char kPageCap[] = "PageCapMiB"; const char kMediaPageTypical[] = "MediaPageTypicalLargePageMiB"; const char kPageTypical[] = "PageTypicalLargePageMiB"; const char kPageFuzzing[] = "PageFuzzingKiB"; // The page load capping bytes threshold for the page. There are seperate // thresholds for media and non-media pages. Returns empty optional if the // page should not be capped. base::Optional<int64_t> GetPageLoadCappingBytesThreshold(bool media_page_load) { if (!base::FeatureList::IsEnabled(data_use_measurement::page_load_capping:: features::kDetectingHeavyPages)) { return base::nullopt; } // Defaults are 15 MiB for media and 5 MiB for non-media. int64_t default_cap_mib = media_page_load ? 15 : 5; return base::GetFieldTrialParamByFeatureAsInt( data_use_measurement::page_load_capping::features:: kDetectingHeavyPages, (media_page_load ? kMediaPageCap : kPageCap), default_cap_mib) * 1024 * 1024; } // Provides an estimate of savings based on the typical size of page loads above // the capping thresholds. int64_t GetEstimatedSavings(int64_t network_bytes, int64_t threshold, bool media_page_load) { // These are estimated by the median size page above the capping threshold int64_t typical_size = base::GetFieldTrialParamByFeatureAsInt( data_use_measurement::page_load_capping::features:: kDetectingHeavyPages, (media_page_load ? kMediaPageTypical : kPageTypical), 0) * 1024 * 1024; if (typical_size == 0) { // Defaults are capping thresholds inflated 50 percent. typical_size = threshold * 1.5; } // If this page load already exceeded the typical page load size, report 0 // savings. return std::max<int64_t>((typical_size - network_bytes), 0); } } // namespace PageCappingPageLoadMetricsObserver::PageCappingPageLoadMetricsObserver() : weak_factory_(this) {} PageCappingPageLoadMetricsObserver::~PageCappingPageLoadMetricsObserver() {} page_load_metrics::PageLoadMetricsObserver::ObservePolicy PageCappingPageLoadMetricsObserver::OnCommit( content::NavigationHandle* navigation_handle, ukm::SourceId source_id) { web_contents_ = navigation_handle->GetWebContents(); page_cap_ = GetPageLoadCappingBytesThreshold(false /* media_page_load */); url_host_ = navigation_handle->GetURL().host(); fuzzing_offset_ = GetFuzzingOffset(); MaybeCreate(); // TODO(ryansturm) Check a blacklist of eligible pages. // https://crbug.com/797981 return page_load_metrics::PageLoadMetricsObserver::CONTINUE_OBSERVING; } void PageCappingPageLoadMetricsObserver::OnLoadedResource( const page_load_metrics::ExtraRequestCompleteInfo& extra_request_complete_info) { if (extra_request_complete_info.was_cached) return; network_bytes_ += extra_request_complete_info.raw_body_bytes; MaybeCreate(); } void PageCappingPageLoadMetricsObserver::MaybeCreate() { // If the InfoBar has already been shown for the page, don't show an InfoBar. if (page_capping_state_ != PageCappingState::kInfoBarNotShown) return; // If the page has not committed, don't show an InfoBar. if (!web_contents_) return; // If there is no capping threshold, the threshold or the threshold is not // met, do not show an InfoBar. Use the fuzzing offset to increase the number // of bytes needed. if (!page_cap_ || (network_bytes_ - fuzzing_offset_) < page_cap_.value()) return; if (IsBlacklisted()) return; if (PageLoadCappingInfoBarDelegate::Create( page_cap_.value(), web_contents_, base::BindRepeating( &PageCappingPageLoadMetricsObserver::PauseSubresourceLoading, weak_factory_.GetWeakPtr()))) { page_capping_state_ = PageCappingState::kInfoBarShown; } } void PageCappingPageLoadMetricsObserver::MediaStartedPlaying( const content::WebContentsObserver::MediaPlayerInfo& video_type, bool is_in_main_frame) { media_page_load_ = true; page_cap_ = GetPageLoadCappingBytesThreshold(true /* media_page_load */); } void PageCappingPageLoadMetricsObserver::OnDidFinishSubFrameNavigation( content::NavigationHandle* navigation_handle) { // If the page is not paused, there is no need to pause new frames. if (page_capping_state_ != PageCappingState::kPagePaused) return; // If the navigation is to the same page, is to an error page, the load hasn't // committed or render frame host is null, no need to pause the page. if (navigation_handle->IsSameDocument() || navigation_handle->IsErrorPage() || !navigation_handle->HasCommitted() || !navigation_handle->GetRenderFrameHost()) { return; } // Pause the new frame. handles_.push_back( navigation_handle->GetRenderFrameHost()->PauseSubresourceLoading()); } void PageCappingPageLoadMetricsObserver::PauseSubresourceLoading(bool pause) { DCHECK((pause && page_capping_state_ == PageCappingState::kInfoBarShown) || (!pause && page_capping_state_ == PageCappingState::kPagePaused)); page_capping_state_ = pause ? PageCappingState::kPagePaused : PageCappingState::kPageResumed; if (pause) handles_ = web_contents_->PauseSubresourceLoading(); else handles_.clear(); } page_load_metrics::PageLoadMetricsObserver::ObservePolicy PageCappingPageLoadMetricsObserver::FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { RecordDataSavingsAndUKM(info); return CONTINUE_OBSERVING; } page_load_metrics::PageLoadMetricsObserver::ObservePolicy PageCappingPageLoadMetricsObserver::OnHidden( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { RecordDataSavingsAndUKM(info); return CONTINUE_OBSERVING; } void PageCappingPageLoadMetricsObserver::OnComplete( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { RecordDataSavingsAndUKM(info); ReportOptOut(); if (page_capping_state_ == PageCappingState::kPagePaused) { PAGE_BYTES_HISTOGRAM("HeavyPageCapping.RecordedDataSavings", recorded_savings_); } } void PageCappingPageLoadMetricsObserver::RecordDataSavingsAndUKM( const page_load_metrics::PageLoadExtraInfo& info) { // If the InfoBar was never shown, don't report savings or UKM. if (page_capping_state_ == PageCappingState::kInfoBarNotShown) { DCHECK_EQ(0, recorded_savings_); return; } if (!ukm_recorded_) { ukm::builders::PageLoadCapping builder(info.source_id); builder.SetFinalState(static_cast<int64_t>(page_capping_state_)); builder.Record(ukm::UkmRecorder::Get()); ukm_recorded_ = true; } // If the InfoBar was shown, but not acted upon, don't update savings. if (page_capping_state_ == PageCappingState::kInfoBarShown) { DCHECK_EQ(0, recorded_savings_); return; } // If the user resumed, we may need to update the savings. if (page_capping_state_ == PageCappingState::kPageResumed) { // No need to undo savings if no savings were previously recorded. if (recorded_savings_ == 0) return; // Undo previous savings since the page was resumed. WriteToSavings(-1 * recorded_savings_); recorded_savings_ = 0; return; } DCHECK_EQ(PageCappingState::kPagePaused, page_capping_state_); int64_t estimated_savings = GetEstimatedSavings(network_bytes_, page_cap_.value(), media_page_load_); // Record an update to the savings. |recorded_savings_| is generally larger // than |estimated_savings| when called a second time. WriteToSavings(estimated_savings - recorded_savings_); recorded_savings_ = estimated_savings; } void PageCappingPageLoadMetricsObserver::WriteToSavings(int64_t bytes_saved) { data_reduction_proxy::DataReductionProxySettings* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( web_contents_->GetBrowserContext()); bool data_saver_enabled = data_reduction_proxy_settings->IsDataReductionProxyEnabled(); data_reduction_proxy_settings->data_reduction_proxy_service() ->UpdateDataUseForHost(0, bytes_saved, url_host_); data_reduction_proxy_settings->data_reduction_proxy_service() ->UpdateContentLengths(0, bytes_saved, data_saver_enabled, data_reduction_proxy::HTTPS, "text/html", true, data_use_measurement::DataUseUserData::OTHER, 0); } int64_t PageCappingPageLoadMetricsObserver::GetFuzzingOffset() const { if (!base::FeatureList::IsEnabled(data_use_measurement::page_load_capping:: features::kDetectingHeavyPages)) { return 0; } // Default is is 75 KiB. int cap_kib = 75; cap_kib = base::GetFieldTrialParamByFeatureAsInt( data_use_measurement::page_load_capping::features::kDetectingHeavyPages, kPageFuzzing, cap_kib); int cap_bytes = cap_kib * 1024; return base::RandInt(0, cap_bytes); } bool PageCappingPageLoadMetricsObserver::IsPausedForTesting() const { return page_capping_state_ == PageCappingState::kPagePaused; } void PageCappingPageLoadMetricsObserver::ReportOptOut() { if (page_capping_state_ == PageCappingState::kInfoBarNotShown) return; auto* blacklist = GetPageLoadCappingBlacklist(); // Opt outs are when the InfoBar is shown and either ignored or clicked // through twice to resume the page. Currently, reloads are not treated as opt // outs. blacklist->AddEntry( url_host_, page_capping_state_ != PageCappingState::kPagePaused, static_cast<int>(PageCappingBlacklistType::kPageCappingOnlyType)); } bool PageCappingPageLoadMetricsObserver::IsBlacklisted() { if (blacklisted_) return blacklisted_.value(); auto* blacklist = GetPageLoadCappingBlacklist(); // Treat incognito profiles as blacklisted. if (!blacklist) { blacklisted_ = true; return true; } std::vector<blacklist::BlacklistReason> passed_reasons; auto blacklist_reason = blacklist->IsLoadedAndAllowed( url_host_, static_cast<int>(PageCappingBlacklistType::kPageCappingOnlyType), false, &passed_reasons); UMA_HISTOGRAM_ENUMERATION("HeavyPageCapping.BlacklistReason", blacklist_reason); blacklisted_ = (blacklist_reason != blacklist::BlacklistReason::kAllowed); return blacklisted_.value(); } PageLoadCappingBlacklist* PageCappingPageLoadMetricsObserver::GetPageLoadCappingBlacklist() const { auto* page_capping_service = PageLoadCappingServiceFactory::GetForBrowserContext( web_contents_->GetBrowserContext()); if (!page_capping_service) return nullptr; return page_capping_service->page_load_capping_blacklist(); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
029e8c59157a8c52060013788f1fd938c6e19c50
f9ae4ac25faff56ca67c51e2c9a7998834d48703
/Practica Final/practica_final/src/main.cpp
72188712ad5a8679d5a85a63d39d3ee340ebd05c
[]
no_license
elena97om/ED_UGR
fd5d2220faca249027298cf8c93bb9c230087164
a23a3d064cfa446fb0125442d1d8090f7ef284fa
refs/heads/master
2020-04-02T06:42:28.775290
2018-01-19T10:15:46
2018-01-19T10:15:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,050
cpp
// Julian Arenas Guerrero // Ana Isabel Guerrero Tejada #include <fstream> #include <iostream> #include <string> #include <math.h> #include "../include/quienesquien.h" using namespace std; int main(int argc, char * argv[]){ bool jugar = false; bool limpiar = false; QuienEsQuien quienEsQuien; if(argc == 2){ string parametroAleatorio = "aleatorio"; if(argv[1]== parametroAleatorio){ cout << "Creando un QuienEsQuien aleatorio"<< endl; int numero_de_personajes; int numero_de_atributos; do{ cout << "¿Número de personajes? "; cin >>numero_de_personajes; if (numero_de_personajes <= 0) cout << "El numero de personajes debe ser mayor que 0" << endl; }while(numero_de_personajes<=0); quienEsQuien.tablero_aleatorio(numero_de_personajes); quienEsQuien.mostrar_estructuras_leidas(); string nombreFicheroSalida = string("datos/tablero") + "-num-per="+to_string(numero_de_personajes)+".csv"; cout << "Guardando tablero aleatorio en "<<nombreFicheroSalida<<endl; ofstream archivoDeSalida(nombreFicheroSalida); archivoDeSalida << quienEsQuien; cout << "Guardado"<<endl; return 0; }else{ cout << "Cargando fichero para jugar'"<< argv[1] <<"'"<< endl; ifstream f (argv[1]); if (!f){ cout<<"No puedo abrir el fichero "<<argv[1]<<endl; return 1; } f>> quienEsQuien; jugar = true; } } else if(argc == 3 ){ string parametroLimpiar = "limpiar"; if(parametroLimpiar== argv[2]){ cout << "Cargando fichero para limpiar (sin jugar) '"<< argv[1] <<"'"<< endl; ifstream f (argv[1]); if (!f){ cout<<"No puedo abrir el fichero "<<argv[1]<<endl; return 1; } f>> quienEsQuien; jugar = false; } else{ cout << "Modo '"<<argv[2]<<"' no reconocido"<<endl; return 1; } } else { cout << "No se reconocen los argumentos. Ejemplos de uso:" << endl; cout << "\tJugar: ./bin/quienesquien RUTA_FICHERO"<< endl; cout << "\tLimpiar sin jugar: ./bin/quienesquien RUTA_FICHERO limpiar"<< endl; cout << "\tGenerar aleatorio: ./bin/quienesquien aleatorio"<< endl; return 1; } quienEsQuien.mostrar_estructuras_leidas(); quienEsQuien.usar_arbol(quienEsQuien.crear_arbol()); cout << "=========== Arbol en crudo ===========" << endl; quienEsQuien.escribir_arbol_completo(); cout << "Profundidad promedio de las hojas del arbol: "; cout << quienEsQuien.profundidad_promedio_hojas() << endl; cout << "======================================" << endl << endl << endl; quienEsQuien.eliminar_nodos_redundantes(); cout << "=========== Arbol ===================="<<endl; quienEsQuien.escribir_arbol_completo(); cout << "Profundidad promedio de las hojas del arbol: "; cout << quienEsQuien.profundidad_promedio_hojas()<<endl; cout << "======================================" << endl << endl << endl; if(jugar){ quienEsQuien.iniciar_juego(); } return 0; }
[ "juliquiag@hotmail.com" ]
juliquiag@hotmail.com
0bab4af1e16cf79fd36eba26df709f18ac327980
7e3da1697f3aad20c7d63095d572c43a58797393
/COMPLILE.CPP
6e29a306e6b3da5377c8905f5f78552d2800d2ce
[]
no_license
krishankant10/C-language
5d50eb4df5bfbe3017cbb1dad1f1d6f7280a0ce2
e03e590d7c75e86ceade7a06f52c064db70abe54
refs/heads/master
2020-04-28T03:23:47.174914
2019-11-24T14:44:10
2019-11-24T14:44:10
174,935,501
0
0
null
null
null
null
UTF-8
C++
false
false
318
cpp
#include <iostream.h> #include <conio.h> class base { public: void show(int i) { cout<<"Base class\n"<<i<<endl; } }; class deri: public base { public: void show() { cout<<"Derived calss\n"; } }; void main() { clrscr(); deri d; d.show(); d.base::show(500); getch(); }
[ "noreply@github.com" ]
noreply@github.com
13f9d192f3fae5b354e46090832d4042da5a4f70
fc1d5b98af5f4bce938aa95a844cc3d11abc01f2
/Speech/src/Event/Responders/ISpeechResponder.h
c1ff0f44cce451aeb1e61a923b4ac395007adfb4
[]
no_license
sandsmark/loom
726fa80d1e8e49c43a12e3967d81c1aca59c331c
ff9e9263446261553113fb93d087af454fb160d7
refs/heads/master
2021-01-01T18:34:42.597398
2015-02-26T21:07:42
2015-02-26T21:07:42
35,631,823
3
0
null
null
null
null
UTF-8
C++
false
false
579
h
#pragma once #include <Core/Event/cDispatcherHub.h> #include <Core/Event/IEventDispatcher.h> #include <Speech/Event/ISpeechEvent.h> #include <Core/Singleton/ISingleton.h> using Loom::Core::IEventDispatcher; using Loom::Core::ISingleton; using Loom::Core::cDispatcherHub; BEGIN_NAMESPACE( Speech ) template< class iClass > class ISpeechResponder : public IEventDispatcher<ISpeechEvent>, public cDispatcherHub::IResponder, public ISingleton<iClass> { public: ISpeechResponder( const cString &iEventName ) : IResponder( iEventName ) {} }; END_NAMESPACE()
[ "thorlist@41b1a1b8-9ad1-474a-a649-7d62dcce9156" ]
thorlist@41b1a1b8-9ad1-474a-a649-7d62dcce9156
ecb339ce8a5508074f96a47d2508140249b7d5ab
04b886bcb4eae8b4cd656b2917a82a13067ca2b7
/src/cpp/oclint/oclint-rules/rules/custom2/CompareThisWithNULLShouldBeAvoidRule.cpp
7ca7de812a74e9f56c277655cf86d11e238e0971
[ "BSD-3-Clause" ]
permissive
terryhu08/MachingLearning
4d01ba9c72e931a82db0992ea58ad1bd425f1544
45ccc79ee906e072bb40552c211579e2c677f459
refs/heads/master
2021-09-16T01:38:10.364942
2018-06-14T13:45:39
2018-06-14T13:45:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,919
cpp
#include "oclint/AbstractASTVisitorRule.h" #include "oclint/RuleSet.h" #include "clang/Lex/Lexer.h" using namespace std; using namespace clang; using namespace oclint; class CompareThisWithNULLShouldBeAvoidRule : public AbstractASTVisitorRule<CompareThisWithNULLShouldBeAvoidRule> { public: virtual const string name() const override { return "compare this with n u l l should be avoid"; } virtual int priority() const override { return 3; } virtual const string category() const override { return "custom2"; } #ifdef DOCGEN virtual const std::string since() const override { return "0.12"; } virtual const std::string description() const override { return ""; // TODO: fill in the description of the rule. } virtual const std::string example() const override { return R"rst( .. code-block:: cpp void example() { // TODO: modify the example for this rule. } )rst"; } /* fill in the file name only when it does not match the rule identifier virtual const std::string fileName() const override { return ""; } */ /* add each threshold's key, description, and its default value to the map. virtual const std::map<std::string, std::string> thresholds() const override { std::map<std::string, std::string> thresholdMapping; return thresholdMapping; } */ /* add additional document for the rule, like references, notes, etc. virtual const std::string additionalDocument() const override { return ""; } */ /* uncomment this method when the rule is enabled to be suppressed. virtual bool enableSuppress() const override { return true; } */ #endif virtual void setUp() override { sm = &_carrier->getSourceManager(); } virtual void tearDown() override {} inline Expr* rmICE(Expr* expr){ while(expr){ if(isa<ImplicitCastExpr>(expr)){ ImplicitCastExpr* ice = dyn_cast_or_null<ImplicitCastExpr>(expr); expr = ice->getSubExpr(); }else break; } return expr; } /* Visit IfStmt */ bool VisitIfStmt(IfStmt *is) { Expr* expr = is->getCond(); if(isa<UnaryOperator>(expr)){ UnaryOperator* uo = dyn_cast_or_null<UnaryOperator>(expr); if(uo->getOpcode()==UO_LNot){ expr = uo->getSubExpr(); expr = rmICE(expr); if(isa<CXXThisExpr>(expr)){ string message = "'"+expr2str(is->getCond())+"' comparison should be avoided - this comparison is always false on newer compilers."; addViolation(is->getCond(), this, message); } } }else if(isa<BinaryOperator>(expr)){ BinaryOperator* bo = dyn_cast_or_null<BinaryOperator>(expr); Expr* lhs = bo->getLHS(); if(isa<CXXThisExpr>(lhs)){ Expr* rhs = rmICE(bo->getRHS()); if(isa<IntegerLiteral>(rhs) || isa<GNUNullExpr>(rhs)){ string message = "'"+expr2str(bo)+"' comparison should be avoided - this comparison is always false on newer compilers."; addViolation(bo, this, message); } } } } string expr2str(Expr* expr){ // (T, U) => "T,," string text = clang::Lexer::getSourceText( CharSourceRange::getTokenRange(expr->getSourceRange()), *sm, LangOptions(), 0); if (text.at(text.size()-1) == ',') return clang::Lexer::getSourceText(CharSourceRange::getCharRange(expr->getSourceRange()), *sm, LangOptions(), 0); return text; } private: SourceManager* sm; }; static RuleSet rules(new CompareThisWithNULLShouldBeAvoidRule());
[ "dhfang812@163.com" ]
dhfang812@163.com
4c0305c5e026520c4e9c797fb0343951d858ec7a
c12fba29b0cbb5071dca39ddbe67da9607b77d65
/Engine/Include/Rendering/Translation/Vulkan/VulkanGraphicsPipelineData.h
a975890a45466072fd6179aeb02ea7180d7f95a2
[]
no_license
satellitnorden/Catalyst-Engine
55666b2cd7f61d4e5a311297ccbad754e901133e
c8064856f0be6ed81a5136155ab6b9b3352dca5c
refs/heads/master
2023-08-08T04:59:54.887284
2023-08-07T13:33:08
2023-08-07T13:33:08
116,288,917
21
3
null
null
null
null
UTF-8
C++
false
false
837
h
#if defined(CATALYST_RENDERING_VULKAN) #pragma once //Core. #include <Core/Essential/CatalystEssential.h> //Vulkan. #include <Rendering/Abstraction/Vulkan/VulkanCore.h> #include <Rendering/Abstraction/Vulkan/VulkanGraphicsPipeline.h> #include <Rendering/Translation/Vulkan/VulkanPipelineData.h> class VulkanGraphicsPipelineData final : public VulkanPipelineData { public: //The pipeline associated with the graphics pipeline. VulkanGraphicsPipeline *RESTRICT _Pipeline; //The render pass. VulkanRenderPass *RESTRICT _RenderPass; //The framebuffers. DynamicArray<VulkanFramebuffer *RESTRICT> _FrameBuffers; //The extent. VkExtent2D _Extent; //The number of attachments. uint32 _NumberOfAttachments; //Denotes whether or not this render pass is aimed to be rendered unto the screen. bool _RenderToScreeen; }; #endif
[ "DennisMartenssons@gmail.com" ]
DennisMartenssons@gmail.com
7de291624129494e39c97f2cf39a17644187244a
5b12760333f6ce9f2c818c9406a788bbdde83cb3
/shynet/events/EventBufferSsl.cpp
a6bfb58557d8f802d9a50821d72c85adb421391d
[]
no_license
JoyZou/gameframe
a9476948b86b34d4bb5e8eae47552023c07d7566
a5db12da016b65033cc088ba3c2a464936b2b942
refs/heads/master
2023-08-28T22:18:56.117350
2021-11-10T09:04:30
2021-11-10T09:04:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
942
cpp
#include "shynet/events/eventbufferssl.h" #include "shynet/utils/logger.h" namespace shynet { namespace events { EventBufferSsl::EventBufferSsl(std::shared_ptr<EventBase> base, evutil_socket_t fd, bufferevent_ssl_state state, int options, SSL_CTX* ctx) : EventBuffer(base) { ssl_ = SSL_new(ctx); if (ssl_ == nullptr) { THROW_EXCEPTION("call SSL_new"); } bufferevent* buf = bufferevent_openssl_socket_new(base->base(), fd, ssl_, state, options); if (buf == nullptr) { THROW_EXCEPTION("call bufferevent_openssl_socket_new"); } set_buffer(buf); } EventBufferSsl::~EventBufferSsl() { if (ssl_ != nullptr) { SSL_shutdown(ssl_); SSL_set_shutdown(ssl_, SSL_RECEIVED_SHUTDOWN); //SSL_free(ssl_); } if (buffer() != nullptr) bufferevent_free(buffer()); } } }
[ "54823051@qq.com" ]
54823051@qq.com
1c074c8d26f06a4074d6e2c1867da4ebb97fc82a
ecbd4cd659a10ca18649009e0a320609a19687c4
/Source/ROSIntegration/Private/Conversion/Messages/std_msgs/StdMsgsEmptyConverter.cpp
6278509e324ff1c6ade150834fe1ccc10b1cba9f
[ "MIT" ]
permissive
code-iai/ROSIntegration
5e21317872fea2c2f909133b15e563bcf2e8d745
46dd9668eab4e5624b88681f22b7303af3d38592
refs/heads/master
2023-08-09T04:02:02.653565
2023-08-02T16:40:00
2023-08-02T16:40:00
100,639,520
370
122
MIT
2023-08-02T16:40:02
2017-08-17T19:46:51
C++
UTF-8
C++
false
false
499
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Conversion/Messages/std_msgs/StdMsgsEmptyConverter.h" UStdMsgsEmptyConverter::UStdMsgsEmptyConverter() { _MessageType = "std_msgs/Empty"; } bool UStdMsgsEmptyConverter::ConvertIncomingMessage(const ROSBridgePublishMsg* message, TSharedPtr<FROSBaseMsg> &BaseMsg) { return true; } bool UStdMsgsEmptyConverter::ConvertOutgoingMessage(TSharedPtr<FROSBaseMsg> BaseMsg, bson_t** message) { return true; }
[ "gburroughes1@gmail.com" ]
gburroughes1@gmail.com
f28f5c60e22652355c3854530caa296e1782fac9
7e98b2ff8ec98605ada716fa766831c5d36d992c
/fontys_at_work/map_marker/include/MapMarker/ClickableLabel.hpp
ea63c61ca8fc7c495b20a48269da71548bb33d8a
[ "MIT" ]
permissive
FontysAtWork/ESA-PROJ
2d7f50f5f2fad136bfb7c4129750659ebcb2344b
50d5b397f634db98e2627a764c7731e76a4b3feb
refs/heads/master
2021-09-07T07:20:34.681550
2018-02-19T13:58:34
2018-02-19T13:58:34
101,985,367
2
0
MIT
2018-01-25T10:08:32
2017-08-31T09:41:45
C++
UTF-8
C++
false
false
443
hpp
#ifndef CLICKABLELABEL_H #define CLICKABLELABEL_H #include <QLabel> #include <QWidget> #include <Qt> #include <QObject> #include <QMouseEvent> class ClickableLabel : public QLabel { Q_OBJECT public: explicit ClickableLabel(QWidget* parent = 0, Qt::WindowFlags f = Qt::WindowFlags()); ~ClickableLabel(); Q_SIGNALS: void clicked(QPoint); protected: void mousePressEvent(QMouseEvent *ev); }; #endif // CLICKABLELABEL_H
[ "jdeweger@live.com" ]
jdeweger@live.com
d9c7f1b3d3b58f3219e52ff76a9f4e01e3336580
f0af794e3c1fcbe85229cfb06dced0965322b9be
/mpich2/modules/ucx/test/gtest/ucp/test_ucp_peer_failure.cc
d9693214081076b4997300c1487b7893f9e78fd6
[ "mpich2", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
ParaStation/psmpi
ccf1a67b44faabdfeddeb7d9496e7b7588b65ca2
7d81186a8dda3fac415555466f95db42dc29f2a8
refs/heads/master
2023-08-18T00:45:26.495923
2023-08-14T14:08:46
2023-08-14T14:08:46
17,880,600
10
6
NOASSERTION
2022-10-13T19:06:58
2014-03-18T20:20:23
C
UTF-8
C++
false
false
19,654
cc
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2017. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #include <common/test.h> #include "ucp_test.h" #include "ucp_datatype.h" extern "C" { #include <ucp/core/ucp_ep.inl> /* for testing EP RNDV configuration */ #include <ucp/core/ucp_request.h> /* for debug */ #include <ucp/core/ucp_worker.h> /* for testing memory consumption */ } class test_ucp_peer_failure : public ucp_test { public: test_ucp_peer_failure(); static void get_test_variants(std::vector<ucp_test_variant>& variants); ucp_ep_params_t get_ep_params(); protected: static const int AM_ID = 0; enum { TEST_AM = UCS_BIT(0), TEST_RMA = UCS_BIT(1), FAIL_IMM = UCS_BIT(2), WAKEUP = UCS_BIT(3) }; enum { STABLE_EP_INDEX, FAILING_EP_INDEX }; typedef ucs::handle<ucp_mem_h, ucp_context_h> mem_handle_t; void set_am_handler(entity &e); static ucs_status_t am_callback(void *arg, const void *header, size_t header_length, void *data, size_t length, const ucp_am_recv_param_t *param); static void err_cb(void *arg, ucp_ep_h ep, ucs_status_t status); ucp_ep_h stable_sender(); ucp_ep_h failing_sender(); entity& stable_receiver(); entity& failing_receiver(); void *send_nb(ucp_ep_h ep, ucp_rkey_h rkey); static ucs_log_func_rc_t warn_unreleased_rdesc_handler(const char *file, unsigned line, const char *function, ucs_log_level_t level, const ucs_log_component_config_t *comp_conf, const char *message, va_list ap); void fail_receiver(); void smoke_test(bool stable_pair); static void unmap_memh(ucp_mem_h memh, ucp_context_h context); void get_rkey(ucp_ep_h ep, entity& dst, mem_handle_t& memh, ucs::handle<ucp_rkey_h>& rkey); void set_rkeys(); static void send_cb(void *request, ucs_status_t status, void *user_data); virtual void cleanup(); void do_test(size_t msg_size, int pre_msg_count, bool force_close, bool request_must_fail); size_t m_am_rx_count; size_t m_err_count; ucs_status_t m_err_status; std::string m_sbuf, m_rbuf; mem_handle_t m_stable_memh, m_failing_memh; ucs::handle<ucp_rkey_h> m_stable_rkey, m_failing_rkey; }; UCP_INSTANTIATE_TEST_CASE(test_ucp_peer_failure) // DC without UD auxiliary UCP_INSTANTIATE_TEST_CASE_TLS(test_ucp_peer_failure, dc_mlx5, "dc_mlx5") test_ucp_peer_failure::test_ucp_peer_failure() : m_am_rx_count(0), m_err_count(0), m_err_status(UCS_OK) { ucs::fill_random(m_sbuf); configure_peer_failure_settings(); } void test_ucp_peer_failure::get_test_variants( std::vector<ucp_test_variant> &variants) { add_variant_with_value(variants, UCP_FEATURE_AM, TEST_AM, "am"); add_variant_with_value(variants, UCP_FEATURE_RMA, TEST_RMA, "rma"); add_variant_with_value(variants, UCP_FEATURE_AM, TEST_AM | FAIL_IMM, "am_fail_imm"); add_variant_with_value(variants, UCP_FEATURE_RMA, TEST_RMA | FAIL_IMM, "rma_fail_imm"); } ucp_ep_params_t test_ucp_peer_failure::get_ep_params() { ucp_ep_params_t params; memset(&params, 0, sizeof(params)); params.field_mask = UCP_EP_PARAM_FIELD_ERR_HANDLING_MODE | UCP_EP_PARAM_FIELD_ERR_HANDLER; params.err_mode = UCP_ERR_HANDLING_MODE_PEER; params.err_handler.cb = err_cb; params.err_handler.arg = reinterpret_cast<void*>(this); return params; } void test_ucp_peer_failure::set_am_handler(entity &e) { if (!(get_variant_value() & TEST_AM)) { return; } ucp_am_handler_param_t param; param.field_mask = UCP_AM_HANDLER_PARAM_FIELD_ID | UCP_AM_HANDLER_PARAM_FIELD_CB | UCP_AM_HANDLER_PARAM_FIELD_ARG; param.cb = am_callback; param.arg = this; param.id = AM_ID; ucs_status_t status = ucp_worker_set_am_recv_handler(e.worker(), &param); ASSERT_UCS_OK(status); } ucs_status_t test_ucp_peer_failure::am_callback(void *arg, const void *header, size_t header_length, void *data, size_t length, const ucp_am_recv_param_t *param) { test_ucp_peer_failure *self = reinterpret_cast<test_ucp_peer_failure*>(arg); ++self->m_am_rx_count; return UCS_OK; } void test_ucp_peer_failure::err_cb(void *arg, ucp_ep_h ep, ucs_status_t status) { test_ucp_peer_failure *self = reinterpret_cast<test_ucp_peer_failure*>(arg); EXPECT_TRUE((UCS_ERR_CONNECTION_RESET == status) || (UCS_ERR_ENDPOINT_TIMEOUT == status)); self->m_err_status = status; ++self->m_err_count; } /* stable pair: sender = ep(0), receiver: entity(size - 1) * failing pair: sender = ep(1), receiver: entity(size - 2)*/ ucp_ep_h test_ucp_peer_failure::stable_sender() { return sender().ep(0, STABLE_EP_INDEX); } ucp_ep_h test_ucp_peer_failure::failing_sender() { return sender().ep(0, FAILING_EP_INDEX); } ucp_test::entity& test_ucp_peer_failure::stable_receiver() { return m_entities.at(m_entities.size() - 1 - STABLE_EP_INDEX); } ucp_test::entity& test_ucp_peer_failure::failing_receiver() { return m_entities.at(m_entities.size() - 1 - FAILING_EP_INDEX); } void *test_ucp_peer_failure::send_nb(ucp_ep_h ep, ucp_rkey_h rkey) { ucp_request_param_t param; param.op_attr_mask = UCP_OP_ATTR_FIELD_DATATYPE | UCP_OP_ATTR_FIELD_CALLBACK; param.datatype = DATATYPE; param.cb.send = send_cb; if (get_variant_value() & TEST_AM) { return ucp_am_send_nbx(ep, AM_ID, NULL, 0, &m_sbuf[0], m_sbuf.size(), &param); } else if (get_variant_value() & TEST_RMA) { return ucp_put_nbx(ep, &m_sbuf[0], m_sbuf.size(), (uintptr_t)&m_rbuf[0], rkey, &param); } else { ucs_fatal("invalid test case"); } } ucs_log_func_rc_t test_ucp_peer_failure::warn_unreleased_rdesc_handler(const char *file, unsigned line, const char *function, ucs_log_level_t level, const ucs_log_component_config_t *comp_conf, const char *message, va_list ap) { if (level == UCS_LOG_LEVEL_WARN) { std::string err_str = format_message(message, ap); if (err_str.find("unexpected tag-receive descriptor") != std::string::npos) { return UCS_LOG_FUNC_RC_STOP; } } return UCS_LOG_FUNC_RC_CONTINUE; } void test_ucp_peer_failure::fail_receiver() { /* TODO: need to handle non-empty TX window in UD EP destructor", * see debug message (ud_ep.c:220) * ucs_debug("ep=%p id=%d conn_id=%d has %d unacked packets", * self, self->ep_id, self->conn_id, * (int)ucs_queue_length(&self->tx.window)); */ // TODO use force-close to close connections flush_worker(failing_receiver()); m_failing_memh.reset(); { /* transform warning messages about unreleased TM rdescs to test * message that are expected here, since we closed receiver w/o * reading the messages that were potentially received */ scoped_log_handler slh(warn_unreleased_rdesc_handler); failing_receiver().cleanup(); } } void test_ucp_peer_failure::smoke_test(bool stable_pair) { ucp_ep_h send_ep = stable_pair ? stable_sender() : failing_sender(); size_t am_count = m_am_rx_count; // Send and wait for completion void *sreq = send_nb(send_ep, stable_pair ? m_stable_rkey : m_failing_rkey); request_wait(sreq); if (get_variant_value() & TEST_AM) { // Wait for active message to be received while (m_am_rx_count < am_count) { progress(); } } else if (get_variant_value() & TEST_RMA) { // Flush the sender and expect data to arrive on receiver void *freq = ucp_ep_flush_nb(send_ep, 0, (ucp_send_callback_t)ucs_empty_function); request_wait(freq); EXPECT_EQ(m_sbuf, m_rbuf); } } void test_ucp_peer_failure::unmap_memh(ucp_mem_h memh, ucp_context_h context) { ucs_status_t status = ucp_mem_unmap(context, memh); if (status != UCS_OK) { ucs_warn("failed to unmap memory: %s", ucs_status_string(status)); } } void test_ucp_peer_failure::get_rkey(ucp_ep_h ep, entity& dst, mem_handle_t& memh, ucs::handle<ucp_rkey_h>& rkey) { ucp_mem_map_params_t params; memset(&params, 0, sizeof(params)); params.field_mask = UCP_MEM_MAP_PARAM_FIELD_ADDRESS | UCP_MEM_MAP_PARAM_FIELD_LENGTH; params.address = &m_rbuf[0]; params.length = m_rbuf.size(); ucp_mem_h ucp_memh; ucs_status_t status = ucp_mem_map(dst.ucph(), &params, &ucp_memh); ASSERT_UCS_OK(status); memh.reset(ucp_memh, unmap_memh, dst.ucph()); void *rkey_buffer; size_t rkey_buffer_size; status = ucp_rkey_pack(dst.ucph(), memh, &rkey_buffer, &rkey_buffer_size); ASSERT_UCS_OK(status); ucp_rkey_h ucp_rkey; status = ucp_ep_rkey_unpack(ep, rkey_buffer, &ucp_rkey); ASSERT_UCS_OK(status); rkey.reset(ucp_rkey, ucp_rkey_destroy); ucp_rkey_buffer_release(rkey_buffer); } void test_ucp_peer_failure::set_rkeys() { if (get_variant_value() & TEST_RMA) { get_rkey(failing_sender(), failing_receiver(), m_failing_memh, m_failing_rkey); get_rkey(stable_sender(), stable_receiver(), m_stable_memh, m_stable_rkey); } } void test_ucp_peer_failure::send_cb(void *request, ucs_status_t status, void *user_data) { } void test_ucp_peer_failure::cleanup() { m_failing_rkey.reset(); m_stable_rkey.reset(); m_failing_memh.reset(); m_stable_memh.reset(); ucp_test::cleanup(); } void test_ucp_peer_failure::do_test(size_t msg_size, int pre_msg_count, bool force_close, bool request_must_fail) { skip_loopback(); m_sbuf.resize(msg_size); m_rbuf.resize(msg_size); /* connect 2 ep's from sender() to 2 receiver entities */ create_entity(); sender().connect(&stable_receiver(), get_ep_params(), STABLE_EP_INDEX); sender().connect(&failing_receiver(), get_ep_params(), FAILING_EP_INDEX); set_am_handler(stable_receiver()); set_am_handler(failing_receiver()); set_rkeys(); /* Since we don't want to test peer failure on a stable pair * and don't expect EP timeout error on those EPs, * run traffic on a stable pair to connect it */ smoke_test(true); if (!(get_variant_value() & FAIL_IMM)) { /* if not fail immediately, run traffic on failing pair to connect it */ smoke_test(false); } /* put some sends on the failing pair */ std::vector<void*> sreqs_pre; for (int i = 0; i < pre_msg_count; ++i) { progress(); void *req = send_nb(failing_sender(), m_failing_rkey); ASSERT_FALSE(UCS_PTR_IS_ERR(req)); if (UCS_PTR_IS_PTR(req)) { sreqs_pre.push_back(req); } } flush_ep(sender(), 0, FAILING_EP_INDEX); EXPECT_EQ(UCS_OK, m_err_status); /* Since UCT/UD EP has a SW implementation of reliablity on which peer * failure mechanism is based, we should set small UCT/UD EP timeout * for UCT/UD EPs for sender's UCP EP to reduce testing time */ double prev_ib_ud_peer_timeout = sender().set_ib_ud_peer_timeout(3.); { scoped_log_handler slh(wrap_errors_logger); fail_receiver(); void *sreq = send_nb(failing_sender(), m_failing_rkey); flush_ep(sender(), 0, FAILING_EP_INDEX); while (!m_err_count) { progress(); } EXPECT_NE(UCS_OK, m_err_status); if (UCS_PTR_IS_PTR(sreq)) { ucs_status_t status; /* If rendezvous protocol is used, the m_err_count is increased * on the receiver side, so the send request may not complete * immediately */ status = request_wait(sreq); if (request_must_fail) { EXPECT_TRUE((m_err_status == status) || (UCS_ERR_CANCELED == status)); } else { EXPECT_TRUE((m_err_status == status) || (UCS_OK == status)); } } /* Additional sends must fail */ void *sreq2 = send_nb(failing_sender(), m_failing_rkey); ucs_status_t status = request_wait(sreq2); EXPECT_TRUE(UCS_STATUS_IS_ERR(status)); EXPECT_EQ(m_err_status, status); if (force_close) { unsigned allocd_eps_before = ucs_strided_alloc_inuse_count(&sender().worker()->ep_alloc); ucp_ep_h ep = sender().revoke_ep(0, FAILING_EP_INDEX); m_failing_rkey.reset(); void *creq = ucp_ep_close_nb(ep, UCP_EP_CLOSE_MODE_FORCE); request_wait(creq); short_progress_loop(); /* allow discard lanes & complete destroy EP */ unsigned allocd_eps_after = ucs_strided_alloc_inuse_count(&sender().worker()->ep_alloc); if (!(get_variant_value() & FAIL_IMM)) { EXPECT_LT(allocd_eps_after, allocd_eps_before); } } /* release requests */ while (!sreqs_pre.empty()) { void *req = sreqs_pre.back(); sreqs_pre.pop_back(); EXPECT_NE(UCS_INPROGRESS, ucp_request_test(req, NULL)); ucp_request_release(req); } } /* Since we won't test peer failure anymore, reset UCT/UD EP timeout to the * default value to avoid possible UD EP timeout errors under high load */ sender().set_ib_ud_peer_timeout(prev_ib_ud_peer_timeout); /* Check workability of stable pair */ smoke_test(true); /* Check that TX polling is working well */ while (sender().progress()); /* Destroy rkey for failing pair */ m_failing_rkey.reset(); } UCS_TEST_P(test_ucp_peer_failure, basic) { do_test(UCS_KBYTE, /* msg_size */ 0, /* pre_msg_cnt */ false, /* force_close */ false /* must_fail */); } UCS_TEST_P(test_ucp_peer_failure, zcopy, "ZCOPY_THRESH=1023", /* to catch failure with TCP during progressing multi AM Zcopy, * since `must_fail=true` */ "TCP_SNDBUF?=1k", "TCP_RCVBUF?=128", "TCP_RX_SEG_SIZE?=512", "TCP_TX_SEG_SIZE?=256") { do_test(UCS_KBYTE, /* msg_size */ 0, /* pre_msg_cnt */ false, /* force_close */ true /* must_fail */); } UCS_TEST_P(test_ucp_peer_failure, bcopy_multi, "SEG_SIZE?=512", "RC_TM_ENABLE?=n") { do_test(UCS_KBYTE, /* msg_size */ 0, /* pre_msg_cnt */ false, /* force_close */ false /* must_fail */); } UCS_TEST_P(test_ucp_peer_failure, force_close, "RC_FC_ENABLE?=n", /* To catch unexpected descriptors leak, for multi-fragment protocol with TCP */ "TCP_RX_SEG_SIZE?=1024", "TCP_TX_SEG_SIZE?=1024") { do_test(16000, /* msg_size */ 1000, /* pre_msg_cnt */ true, /* force_close */ false /* must_fail */); } class test_ucp_peer_failure_keepalive : public test_ucp_peer_failure { public: test_ucp_peer_failure_keepalive() { m_sbuf.resize(1 * UCS_MBYTE); m_rbuf.resize(1 * UCS_MBYTE); m_env.push_back(new ucs::scoped_setenv("UCX_TCP_KEEPIDLE", "inf")); m_env.push_back(new ucs::scoped_setenv("UCX_UD_TIMEOUT", "3s")); } void init() { test_ucp_peer_failure::init(); create_entity(); sender().connect(&stable_receiver(), get_ep_params(), STABLE_EP_INDEX); sender().connect(&failing_receiver(), get_ep_params(), FAILING_EP_INDEX); stable_receiver().connect(&sender(), get_ep_params()); failing_receiver().connect(&sender(), get_ep_params()); set_am_handler(failing_receiver()); set_am_handler(stable_receiver()); } static void get_test_variants(std::vector<ucp_test_variant>& variants) { add_variant_with_value(variants, UCP_FEATURE_AM, TEST_AM, "am"); add_variant_with_value(variants, UCP_FEATURE_AM | UCP_FEATURE_WAKEUP, TEST_AM | WAKEUP, "am_wakeup"); } void wakeup_drain_check_no_events(const std::vector<entity*> &entities) { ucs_time_t deadline = ucs::get_deadline(); int ret; /* Read all possible wakeup events to make sure that no more events * arrive */ do { progress(entities); ret = wait_for_wakeup(entities, 0); } while ((ret > 0) && (ucs_get_time() < deadline)); EXPECT_EQ(ret, 0); } }; UCS_TEST_P(test_ucp_peer_failure_keepalive, kill_receiver, "KEEPALIVE_INTERVAL=0.3", "KEEPALIVE_NUM_EPS=inf") { /* TODO: wireup is not tested yet */ scoped_log_handler err_handler(wrap_errors_logger); scoped_log_handler warn_handler(hide_warns_logger); /* initiate p2p pairing */ ucp_ep_resolve_remote_id(failing_sender(), 0); smoke_test(true); /* allow wireup to complete */ smoke_test(false); if (ucp_ep_config(stable_sender())->key.keepalive_lane == UCP_NULL_LANE) { UCS_TEST_SKIP_R("Unsupported"); } /* ensure both pair have ep_check map */ ASSERT_NE(UCP_NULL_LANE, ucp_ep_config(failing_sender())->key.keepalive_lane); /* aux (ud) transport doesn't support keepalive feature and * we are assuming that wireup/connect procedure is done */ EXPECT_EQ(0, m_err_count); /* ensure no errors are detected */ /* flush all outstanding ops to allow keepalive to run */ flush_worker(sender()); if (get_variant_value() & WAKEUP) { check_events({ &sender(), &failing_receiver() }, true); /* make sure no remaining events are returned from poll() */ wakeup_drain_check_no_events({ &sender(), &failing_receiver() }); } /* kill EPs & ifaces */ failing_receiver().close_all_eps(*this, 0, UCP_EP_CLOSE_MODE_FORCE); if (get_variant_value() & WAKEUP) { wakeup_drain_check_no_events({ &sender() }); } wait_for_flag(&m_err_count); /* dump warnings */ int warn_count = m_warnings.size(); for (int i = 0; i < warn_count; ++i) { UCS_TEST_MESSAGE << "< " << m_warnings[i] << " >"; } EXPECT_NE(0, m_err_count); ucp_ep_h ep = sender().revoke_ep(0, FAILING_EP_INDEX); void *creq = ucp_ep_close_nb(ep, UCP_EP_CLOSE_MODE_FORCE); request_wait(creq); /* make sure no remaining events are returned from poll() */ if (get_variant_value() & WAKEUP) { wakeup_drain_check_no_events({ &sender() }); } /* check if stable receiver is still works */ m_err_count = 0; smoke_test(true); EXPECT_EQ(0, m_err_count); /* ensure no errors are detected */ } UCP_INSTANTIATE_TEST_CASE(test_ucp_peer_failure_keepalive)
[ "pickartz@par-tec.com" ]
pickartz@par-tec.com
2dfe717c3ac418228c23dc4a8a4a1c2e415f6a39
8cf32b4cbca07bd39341e1d0a29428e420b492a6
/contracts/libc++/upstream/test/std/numerics/rand/rand.dis/rand.dist.samp/rand.dist.samp.pconst/param_eq.pass.cpp
35c49ff0d7eecdc8b8dabf21d4bde6c29e43d727
[ "NCSA", "MIT" ]
permissive
cubetrain/CubeTrain
e1cd516d5dbca77082258948d3c7fc70ebd50fdc
b930a3e88e941225c2c54219267f743c790e388f
refs/heads/master
2020-04-11T23:00:50.245442
2018-12-17T16:07:16
2018-12-17T16:07:16
156,970,178
0
0
null
null
null
null
UTF-8
C++
false
false
1,105
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <random> // template<class RealType = double> // class piecewise_constant_distribution // { // class param_type; #include <random> #include <limits> #include <cassert> int main() { { typedef std::piecewise_constant_distribution<> D; typedef D::param_type P; double b[] = {10, 14, 16, 17}; double p[] = {25, 62.5, 12.5}; P p1(b, b+4, p); P p2(b, b+4, p); assert(p1 == p2); } { typedef std::piecewise_constant_distribution<> D; typedef D::param_type P; double b[] = {10, 14, 16, 17}; double p[] = {25, 62.5, 12.5}; P p1(b, b+3, p); P p2(b, b+4, p); assert(p1 != p2); } }
[ "1848@shanchain.com" ]
1848@shanchain.com
661b62dd5856d64457497e58c1dc4b6a45f61b19
dcedada900b43e47f7bc7a1f30f4120a662a520f
/Generic_DS/TreeNode.h
a0f1e3330be7bd85b99ac81eec8db8ae7535cce1
[]
no_license
teampheonix2021/Castle_DS_Project
1424e4a843bb2bb21a4a307b41decc9884c37ccf
25b104b33cddae98650b3b6e6550483e19a7bd1f
refs/heads/master
2023-08-28T14:05:21.927412
2021-08-30T17:13:49
2021-08-30T17:13:49
401,120,963
0
0
null
null
null
null
UTF-8
C++
false
false
1,172
h
#pragma once template<class T> class TreeNode { private: T value; int key; public: TreeNode(); TreeNode(T val, int k); int getKey() const; void setKey(int k); T getVal() const; void setVal(T val); bool operator> (const TreeNode<T>& T) const; bool operator< (const TreeNode<T>& T) const; bool operator==(const TreeNode<T>& T) const; }; template<class T> inline TreeNode<T>::TreeNode() { } template<class T> TreeNode<T>::TreeNode(T val, int k) { value = val; key = k; } template<class T> int TreeNode<T>::getKey() const { return key; } template<class T> void TreeNode<T>::setKey(int k) { key = k; } template<class T> T TreeNode<T>::getVal() const { return value; } template<class T> inline void TreeNode<T>::setVal(T val) { value = val; } template<class T> bool TreeNode<T>::operator>(const TreeNode<T>& T) const { if (key > T.key) return true; else return false; } template <class T> bool TreeNode<T>::operator<(const TreeNode<T>& T) const { if (key < T.key) return true; else return false; } template <class T> bool TreeNode<T>::operator==(const TreeNode<T>& T) const { if (key == T.key) return true; else return false; }
[ "75501336+Kirollos-Badr@users.noreply.github.com" ]
75501336+Kirollos-Badr@users.noreply.github.com
3b836129f6a51c332e3ba4ad7464c7c5c5845275
2ae0b8d95d439ccfd55ea7933ad4a2994ad0f6c5
/src/common/snippets/src/lowered/pass/insert_loops.cpp
32d4151cb38b95a0a18c96e1e11ca6181d767d4f
[ "Apache-2.0" ]
permissive
openvinotoolkit/openvino
38ea745a247887a4e14580dbc9fc68005e2149f9
e4bed7a31c9f00d8afbfcabee3f64f55496ae56a
refs/heads/master
2023-08-18T03:47:44.572979
2023-08-17T21:24:59
2023-08-17T21:24:59
153,097,643
3,953
1,492
Apache-2.0
2023-09-14T21:42:24
2018-10-15T10:54:40
C++
UTF-8
C++
false
false
5,754
cpp
// Copyright (C) 2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "snippets/lowered/pass/insert_loops.hpp" #include "snippets/lowered/linear_ir.hpp" #include "snippets/lowered/loop_manager.hpp" #include "snippets/snippets_isa.hpp" #include "snippets/itt.hpp" namespace ov { namespace snippets { namespace lowered { namespace pass { using LoopPort = LinearIR::LoopManager::LoopPort; namespace { std::vector<size_t> get_outer_loop_ids(const ExpressionPtr& expr, size_t loop_id) { const auto loop_ids = expr->get_loop_ids(); const auto it = std::find(loop_ids.cbegin(), loop_ids.cend(), loop_id); OPENVINO_ASSERT(it != loop_ids.cend(), "Loop ID hasn't been found"); return std::vector<size_t>(loop_ids.cbegin(), it); } } // namespace InsertLoops::InsertLoops() : Pass() {} void InsertLoops::filter_ports(std::vector<LoopPort>& loop_entries, std::vector<LoopPort>& loop_exits) { std::vector<LoopPort> new_loop_entries; std::vector<LoopPort> new_loop_exits; new_loop_entries.reserve(loop_entries.size()); new_loop_exits.reserve(loop_exits.size()); for (const auto& loop_entry_point : loop_entries) { const auto& expr = loop_entry_point.expr_port->get_expr(); const auto ma = ov::as_type_ptr<op::MemoryAccess>(expr->get_node()); if (ma && ma->is_memory_access_input_port(loop_entry_point.expr_port->get_index())) { new_loop_entries.push_back(loop_entry_point); } } for (const auto& loop_exit_point : loop_exits) { const auto& expr = loop_exit_point.expr_port->get_expr(); const auto ma = ov::as_type_ptr<op::MemoryAccess>(expr->get_node()); if (ma && ma->is_memory_access_output_port(loop_exit_point.expr_port->get_index())) { new_loop_exits.push_back(loop_exit_point); } } loop_entries = new_loop_entries; loop_exits = new_loop_exits; } void InsertLoops::insertion(LinearIR& linear_ir, const LinearIR::LoopManagerPtr& loop_manager, size_t loop_id, bool has_outer_loop) { const auto loop_info = loop_manager->get_loop_info(loop_id); auto loop_entries = loop_info->entry_points; auto loop_exits = loop_info->exit_points; const auto work_amount = loop_info->work_amount; const auto work_amount_increment = loop_info->increment; LinearIR::constExprIt loop_begin_pos, loop_end_pos; loop_manager->get_loop_bounds(linear_ir, loop_id, loop_begin_pos, loop_end_pos); // Remove non MemoryAccess ports since Loop can have only GPR inputs filter_ports(loop_entries, loop_exits); const auto in_out_num = loop_entries.size() + loop_exits.size(); std::vector<int64_t> ptr_increments, finalization_offsets, io_data_sizes; std::vector<PortConnectorPtr> loop_end_inputs; ptr_increments.reserve(in_out_num); finalization_offsets.reserve(in_out_num); io_data_sizes.reserve(in_out_num); loop_end_inputs.reserve(in_out_num); auto init_params = [&ptr_increments, &finalization_offsets, &io_data_sizes, &loop_end_inputs](const std::vector<LoopPort>& ports) { for (const auto& port : ports) { ptr_increments.push_back(port.ptr_increment); finalization_offsets.push_back(port.finalization_offset); io_data_sizes.push_back(port.data_size); loop_end_inputs.push_back(port.expr_port->get_port_connector_ptr()); } }; init_params(loop_entries); init_params(loop_exits); const auto& loop_begin = std::make_shared<op::LoopBegin>(); const auto& loop_begin_expr = linear_ir.create_expression(loop_begin, std::vector<PortConnectorPtr>{}); linear_ir.insert(loop_begin_pos, loop_begin_expr); const auto& loop_end = std::make_shared<op::LoopEnd>( loop_begin->output(0), work_amount, work_amount_increment, ptr_increments, finalization_offsets, io_data_sizes, loop_entries.size(), loop_exits.size(), loop_id); loop_end->has_outer_loop = has_outer_loop; // Add LoopBegin port connector loop_end_inputs.push_back(loop_begin_expr->get_output_port_connector(0)); const auto& loop_end_expr = linear_ir.create_expression(loop_end, loop_end_inputs); const auto& it = linear_ir.insert(loop_end_pos, loop_end_expr); const auto outer_loop_ids = get_outer_loop_ids(*std::prev(it), loop_id); loop_begin_expr->set_loop_ids(outer_loop_ids); loop_end_expr->set_loop_ids(outer_loop_ids); } bool InsertLoops::run(LinearIR& linear_ir) { OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::InsertLoops") if (linear_ir.empty()) return false; const auto& loop_manager = linear_ir.get_loop_manager(); std::set<size_t> inserted_loops; for (auto expr_it = linear_ir.begin(); expr_it != linear_ir.end(); expr_it++) { const auto expr = *expr_it; const auto& node = expr->get_node(); if (ov::is_type<op::LoopBase>(node) || ov::is_type<ov::op::v0::Parameter>(node) || ov::is_type<ov::op::v0::Result>(node)) continue; // Outer Loop ----> Inner Loop const auto expr_loops = expr->get_loop_ids(); const auto loop_depth = expr_loops.size(); for (size_t i = 0; i < loop_depth; ++i) { const auto loop_id = expr_loops[i]; if (inserted_loops.count(loop_id) == 0) { const bool has_outer_loop = i > 0 && inserted_loops.find(expr_loops[i - 1]) != inserted_loops.end(); insertion(linear_ir, loop_manager, loop_id, has_outer_loop); inserted_loops.insert(loop_id); // save Loop ID } } } return true; } } // namespace pass } // namespace lowered } // namespace snippets } // namespace ov
[ "noreply@github.com" ]
noreply@github.com
effc2d9df0da59e1165c8e37dbcb35a4fb3f4e5d
1cc631c61d85076c192a6946acb35d804f0620e4
/Source/third_party/boost_1_58_0/boost/geometry/algorithms/simplify.hpp
0add9a3354029bb0edd274d35df179fa041ab860
[ "BSL-1.0" ]
permissive
reven86/dreamfarmgdk
f9746e1c0e701f243c7dd2f14394970cc47346d9
4d5c26701bf05e89eef56ddd4553814aa6b0e770
refs/heads/master
2021-01-19T00:58:04.259208
2016-10-04T21:29:28
2016-10-04T21:33:10
906,953
2
5
null
null
null
null
UTF-8
C++
false
false
17,503
hpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2015 Bruno Lalande, Paris, France. // Copyright (c) 2009-2015 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_SIMPLIFY_HPP #define BOOST_GEOMETRY_ALGORITHMS_SIMPLIFY_HPP #include <cstddef> #include <boost/core/ignore_unused.hpp> #include <boost/range.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #include <boost/variant/variant_fwd.hpp> #include <boost/geometry/core/cs.hpp> #include <boost/geometry/core/closure.hpp> #include <boost/geometry/core/exterior_ring.hpp> #include <boost/geometry/core/interior_rings.hpp> #include <boost/geometry/core/mutable_range.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/strategies/agnostic/simplify_douglas_peucker.hpp> #include <boost/geometry/strategies/concepts/simplify_concept.hpp> #include <boost/geometry/strategies/default_strategy.hpp> #include <boost/geometry/strategies/distance.hpp> #include <boost/geometry/algorithms/clear.hpp> #include <boost/geometry/algorithms/convert.hpp> #include <boost/geometry/algorithms/not_implemented.hpp> #include <boost/geometry/algorithms/detail/distance/default_strategies.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace simplify { struct simplify_range_insert { template<typename Range, typename Strategy, typename OutputIterator, typename Distance> static inline void apply(Range const& range, OutputIterator out, Distance const& max_distance, Strategy const& strategy) { boost::ignore_unused(strategy); if (boost::size(range) <= 2 || max_distance < 0) { std::copy(boost::begin(range), boost::end(range), out); } else { strategy.apply(range, out, max_distance); } } }; struct simplify_copy { template <typename Range, typename Strategy, typename Distance> static inline void apply(Range const& range, Range& out, Distance const& , Strategy const& ) { std::copy ( boost::begin(range), boost::end(range), std::back_inserter(out) ); } }; template<std::size_t Minimum> struct simplify_range { template <typename Range, typename Strategy, typename Distance> static inline void apply(Range const& range, Range& out, Distance const& max_distance, Strategy const& strategy) { // Call do_container for a linestring / ring /* For a RING: The first/last point (the closing point of the ring) should maybe be excluded because it lies on a line with second/one but last. Here it is never excluded. Note also that, especially if max_distance is too large, the output ring might be self intersecting while the input ring is not, although chances are low in normal polygons Finally the inputring might have 3 (open) or 4 (closed) points (=correct), the output < 3 or 4(=wrong) */ if (boost::size(range) <= int(Minimum) || max_distance < 0.0) { simplify_copy::apply(range, out, max_distance, strategy); } else { simplify_range_insert::apply ( range, std::back_inserter(out), max_distance, strategy ); } } }; struct simplify_polygon { private: template < std::size_t Minimum, typename IteratorIn, typename IteratorOut, typename Distance, typename Strategy > static inline void iterate(IteratorIn begin, IteratorIn end, IteratorOut it_out, Distance const& max_distance, Strategy const& strategy) { for (IteratorIn it_in = begin; it_in != end; ++it_in, ++it_out) { simplify_range<Minimum>::apply(*it_in, *it_out, max_distance, strategy); } } template < std::size_t Minimum, typename InteriorRingsIn, typename InteriorRingsOut, typename Distance, typename Strategy > static inline void apply_interior_rings( InteriorRingsIn const& interior_rings_in, InteriorRingsOut& interior_rings_out, Distance const& max_distance, Strategy const& strategy) { traits::resize<InteriorRingsOut>::apply(interior_rings_out, boost::size(interior_rings_in)); iterate<Minimum>( boost::begin(interior_rings_in), boost::end(interior_rings_in), boost::begin(interior_rings_out), max_distance, strategy); } public: template <typename Polygon, typename Strategy, typename Distance> static inline void apply(Polygon const& poly_in, Polygon& poly_out, Distance const& max_distance, Strategy const& strategy) { std::size_t const minimum = core_detail::closure::minimum_ring_size < geometry::closure<Polygon>::value >::value; // Note that if there are inner rings, and distance is too large, // they might intersect with the outer ring in the output, // while it didn't in the input. simplify_range<minimum>::apply(exterior_ring(poly_in), exterior_ring(poly_out), max_distance, strategy); apply_interior_rings<minimum>(interior_rings(poly_in), interior_rings(poly_out), max_distance, strategy); } }; template<typename Policy> struct simplify_multi { template <typename MultiGeometry, typename Strategy, typename Distance> static inline void apply(MultiGeometry const& multi, MultiGeometry& out, Distance const& max_distance, Strategy const& strategy) { traits::resize<MultiGeometry>::apply(out, boost::size(multi)); typename boost::range_iterator<MultiGeometry>::type it_out = boost::begin(out); for (typename boost::range_iterator<MultiGeometry const>::type it_in = boost::begin(multi); it_in != boost::end(multi); ++it_in, ++it_out) { Policy::apply(*it_in, *it_out, max_distance, strategy); } } }; }} // namespace detail::simplify #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template < typename Geometry, typename Tag = typename tag<Geometry>::type > struct simplify: not_implemented<Tag> {}; template <typename Point> struct simplify<Point, point_tag> { template <typename Distance, typename Strategy> static inline void apply(Point const& point, Point& out, Distance const& , Strategy const& ) { geometry::convert(point, out); } }; template <typename Linestring> struct simplify<Linestring, linestring_tag> : detail::simplify::simplify_range<2> {}; template <typename Ring> struct simplify<Ring, ring_tag> : detail::simplify::simplify_range < core_detail::closure::minimum_ring_size < geometry::closure<Ring>::value >::value > {}; template <typename Polygon> struct simplify<Polygon, polygon_tag> : detail::simplify::simplify_polygon {}; template < typename Geometry, typename Tag = typename tag<Geometry>::type > struct simplify_insert: not_implemented<Tag> {}; template <typename Linestring> struct simplify_insert<Linestring, linestring_tag> : detail::simplify::simplify_range_insert {}; template <typename Ring> struct simplify_insert<Ring, ring_tag> : detail::simplify::simplify_range_insert {}; template <typename MultiPoint> struct simplify<MultiPoint, multi_point_tag> : detail::simplify::simplify_copy {}; template <typename MultiLinestring> struct simplify<MultiLinestring, multi_linestring_tag> : detail::simplify::simplify_multi<detail::simplify::simplify_range<2> > {}; template <typename MultiPolygon> struct simplify<MultiPolygon, multi_polygon_tag> : detail::simplify::simplify_multi<detail::simplify::simplify_polygon> {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH namespace resolve_strategy { struct simplify { template <typename Geometry, typename Distance, typename Strategy> static inline void apply(Geometry const& geometry, Geometry& out, Distance const& max_distance, Strategy const& strategy) { dispatch::simplify<Geometry>::apply(geometry, out, max_distance, strategy); } template <typename Geometry, typename Distance> static inline void apply(Geometry const& geometry, Geometry& out, Distance const& max_distance, default_strategy) { typedef typename point_type<Geometry>::type point_type; typedef typename strategy::distance::services::default_strategy < point_tag, segment_tag, point_type >::type ds_strategy_type; typedef strategy::simplify::douglas_peucker < point_type, ds_strategy_type > strategy_type; BOOST_CONCEPT_ASSERT( (concept::SimplifyStrategy<strategy_type, point_type>) ); apply(geometry, out, max_distance, strategy_type()); } }; struct simplify_insert { template < typename Geometry, typename OutputIterator, typename Distance, typename Strategy > static inline void apply(Geometry const& geometry, OutputIterator& out, Distance const& max_distance, Strategy const& strategy) { dispatch::simplify_insert<Geometry>::apply(geometry, out, max_distance, strategy); } template <typename Geometry, typename OutputIterator, typename Distance> static inline void apply(Geometry const& geometry, OutputIterator& out, Distance const& max_distance, default_strategy) { typedef typename point_type<Geometry>::type point_type; typedef typename strategy::distance::services::default_strategy < point_tag, segment_tag, point_type >::type ds_strategy_type; typedef strategy::simplify::douglas_peucker < point_type, ds_strategy_type > strategy_type; BOOST_CONCEPT_ASSERT( (concept::SimplifyStrategy<strategy_type, point_type>) ); apply(geometry, out, max_distance, strategy_type()); } }; } // namespace resolve_strategy namespace resolve_variant { template <typename Geometry> struct simplify { template <typename Distance, typename Strategy> static inline void apply(Geometry const& geometry, Geometry& out, Distance const& max_distance, Strategy const& strategy) { resolve_strategy::simplify::apply(geometry, out, max_distance, strategy); } }; template <BOOST_VARIANT_ENUM_PARAMS(typename T)> struct simplify<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> > { template <typename Distance, typename Strategy> struct visitor: boost::static_visitor<void> { Distance const& m_max_distance; Strategy const& m_strategy; visitor(Distance const& max_distance, Strategy const& strategy) : m_max_distance(max_distance) , m_strategy(strategy) {} template <typename Geometry> void operator()(Geometry const& geometry, Geometry& out) const { simplify<Geometry>::apply(geometry, out, m_max_distance, m_strategy); } }; template <typename Distance, typename Strategy> static inline void apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>& out, Distance const& max_distance, Strategy const& strategy) { boost::apply_visitor( visitor<Distance, Strategy>(max_distance, strategy), geometry, out ); } }; } // namespace resolve_variant /*! \brief Simplify a geometry using a specified strategy \ingroup simplify \tparam Geometry \tparam_geometry \tparam Distance A numerical distance measure \tparam Strategy A type fulfilling a SimplifyStrategy concept \param strategy A strategy to calculate simplification \param geometry input geometry, to be simplified \param out output geometry, simplified version of the input geometry \param max_distance distance (in units of input coordinates) of a vertex to other segments to be removed \param strategy simplify strategy to be used for simplification, might include point-distance strategy \image html svg_simplify_country.png "The image below presents the simplified country" \qbk{distinguish,with strategy} */ template<typename Geometry, typename Distance, typename Strategy> inline void simplify(Geometry const& geometry, Geometry& out, Distance const& max_distance, Strategy const& strategy) { concept::check<Geometry>(); geometry::clear(out); resolve_variant::simplify<Geometry>::apply(geometry, out, max_distance, strategy); } /*! \brief Simplify a geometry \ingroup simplify \tparam Geometry \tparam_geometry \tparam Distance \tparam_numeric \note This version of simplify simplifies a geometry using the default strategy (Douglas Peucker), \param geometry input geometry, to be simplified \param out output geometry, simplified version of the input geometry \param max_distance distance (in units of input coordinates) of a vertex to other segments to be removed \qbk{[include reference/algorithms/simplify.qbk]} */ template<typename Geometry, typename Distance> inline void simplify(Geometry const& geometry, Geometry& out, Distance const& max_distance) { concept::check<Geometry>(); simplify(geometry, out, max_distance, default_strategy()); } #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace simplify { /*! \brief Simplify a geometry, using an output iterator and a specified strategy \ingroup simplify \tparam Geometry \tparam_geometry \param geometry input geometry, to be simplified \param out output iterator, outputs all simplified points \param max_distance distance (in units of input coordinates) of a vertex to other segments to be removed \param strategy simplify strategy to be used for simplification, might include point-distance strategy \qbk{distinguish,with strategy} \qbk{[include reference/algorithms/simplify.qbk]} */ template<typename Geometry, typename OutputIterator, typename Distance, typename Strategy> inline void simplify_insert(Geometry const& geometry, OutputIterator out, Distance const& max_distance, Strategy const& strategy) { concept::check<Geometry const>(); resolve_strategy::simplify_insert::apply(geometry, out, max_distance, strategy); } /*! \brief Simplify a geometry, using an output iterator \ingroup simplify \tparam Geometry \tparam_geometry \param geometry input geometry, to be simplified \param out output iterator, outputs all simplified points \param max_distance distance (in units of input coordinates) of a vertex to other segments to be removed \qbk{[include reference/algorithms/simplify_insert.qbk]} */ template<typename Geometry, typename OutputIterator, typename Distance> inline void simplify_insert(Geometry const& geometry, OutputIterator out, Distance const& max_distance) { // Concept: output point type = point type of input geometry concept::check<Geometry const>(); concept::check<typename point_type<Geometry>::type>(); simplify_insert(geometry, out, max_distance, default_strategy()); } }} // namespace detail::simplify #endif // DOXYGEN_NO_DETAIL }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_SIMPLIFY_HPP
[ "reven86@gmail.com" ]
reven86@gmail.com
620eb28ae9f8d6987ef8ebe2022858af8beec1ef
f739df1f252d7c961ed881be3b8babaf62ff4170
/softs/SCADAsoft/5.3.3_P2/ACE_Wrappers/TAO/TAO_IDL/ast/ast_structure_fwd.cpp
dcc393c988ba6c07ecbbfa5013841478a865c307
[]
no_license
billpwchan/SCADA-nsl
739484691c95181b262041daa90669d108c54234
1287edcd38b2685a675f1261884f1035f7f288db
refs/heads/master
2023-04-30T09:15:49.104944
2021-01-10T21:53:10
2021-01-10T21:53:10
328,486,982
0
0
null
2023-04-22T07:10:56
2021-01-10T21:53:19
C++
UTF-8
C++
false
false
2,175
cpp
// $Id: ast_structure_fwd.cpp 935 2008-12-10 21:47:27Z mitza $ // AST_StructureFwd nodes denote forward declarations of IDL structs. // AST_StructureFwd nodes have a field containing the full declaration // of the struct, which is initialized when that declaration is // encountered. #include "ast_structure_fwd.h" #include "ast_structure.h" #include "ast_visitor.h" #include "utl_identifier.h" ACE_RCSID( ast, ast_structure_fwd, "$Id: ast_structure_fwd.cpp 935 2008-12-10 21:47:27Z mitza $") AST_StructureFwd::AST_StructureFwd (void) : COMMON_Base (), AST_Decl (), AST_Type (), pd_full_definition (0), is_defined_ (false) { } AST_StructureFwd::AST_StructureFwd (AST_Structure *full_defn, UTL_ScopedName *n) : COMMON_Base (), AST_Decl (AST_Decl::NT_struct_fwd, n), AST_Type (AST_Decl::NT_struct_fwd, n), pd_full_definition (full_defn), is_defined_ (false) { } AST_StructureFwd::~AST_StructureFwd (void) { } // Redefinition of inherited virtual operations. // Dump this AST_StructureFwd node to the ostream o. void AST_StructureFwd::dump (ACE_OSTREAM_TYPE &o) { this->dump_i (o, "struct "); this->local_name ()->dump (o); } int AST_StructureFwd::ast_accept (ast_visitor *visitor) { return visitor->visit_structure_fwd (this); } // Data accessors. AST_Structure * AST_StructureFwd::full_definition (void) { return this->pd_full_definition; } void AST_StructureFwd::set_full_definition (AST_Structure *nfd) { delete this->pd_full_definition; this->pd_full_definition = 0; this->pd_full_definition = nfd; // In case it's not already set. this->is_defined_ = true; } bool AST_StructureFwd::is_defined (void) { return this->is_defined_; } void AST_StructureFwd::set_as_defined (void) { this->is_defined_ = true; } void AST_StructureFwd::destroy (void) { if (!this->is_defined_ && 0 != this->pd_full_definition) { this->pd_full_definition->destroy (); delete this->pd_full_definition; this->pd_full_definition = 0; } this->AST_Type::destroy (); } IMPL_NARROW_FROM_DECL (AST_StructureFwd)
[ "billpwchan@hotmail.com" ]
billpwchan@hotmail.com
65669b057cf6b9a4396da0510a209677bb2e9d01
63204939ab3b27f184ae0693e7407164f56426e0
/tests/joystick/joystick_test.cpp
42d0f2cf23d648ba44698013a40740b423a62ef2
[ "MIT" ]
permissive
AndruePeters/bescor_mp101_controller
4f0e87e6cdb5319697948d565d19e4e43e666ac4
002810f83dfe532e64448271d8d3fae469b85355
refs/heads/master
2022-07-10T11:56:00.272669
2022-06-25T00:02:08
2022-06-25T00:02:08
179,557,798
4
0
MIT
2021-04-21T00:39:45
2019-04-04T18:52:51
C++
UTF-8
C++
false
false
2,541
cpp
#include <joystick/js.h> #include <joystick/controller_map.h> #include <chrono> #include <iostream> #include <iterator> #include <list> #include <string> #include <sstream> #include <thread> #include <curses.h> using namespace controller; JS_State js(0); std::list<unsigned> testList; auto it = testList.begin(); int printDiagnostic() { std::stringstream stream; js.update(); if (js.isConnected()) { if (js.isBtnPressedRaw(DS4::L1)) { --it; } else if (js.isBtnPressedRaw(DS4::R1)) { ++it; } stream << js.getName() << std::endl << js.getProductID() << std::endl << js.getVendorID() << std::endl; stream << "\nX: " << js.isBtnPressedRaw(DS4::X) << "\nO: " << js.isBtnPressedRaw(DS4::O) << "\nTri: " << js.isBtnPressedRaw(DS4::Tri) << "\nSqr: " << js.isBtnPressedRaw(DS4::Sqr) << "\nL1: " << js.isBtnPressedRaw(DS4::L1) << "\nR1: " << js.isBtnPressedRaw(DS4::R1) << "\nL2 " << js.isBtnPressedRaw(DS4::L2) << "\nR2 " << js.isBtnPressedRaw(DS4::R2) << "\nShare: " << js.isBtnPressedRaw(DS4::Share) << "\nOptions: " << js.isBtnPressedRaw(DS4::Opt) << "\nPS Btn: " << js.isBtnPressedRaw(DS4::PS) << "\nLS: " << js.isBtnPressedRaw(DS4::LS) << "\nRS: " << js.isBtnPressedRaw(DS4::RS) << "\n\nAxes:" << "\nLS_X: " << js.getAxisPos(DS4::LS_X) << "\nLS_Y: " << js.getAxisPos(DS4::LS_Y) << "\nL: " << js.getAxisPos(DS4::L) << "\nR: " << js.getAxisPos(DS4::R) << "\nRS_X: " << js.getAxisPos(DS4::RS_X) << "\nRS_Y: " << js.getAxisPos(DS4::RS_Y) << "\nPovX: " << js.getAxisPos(DS4::PovX) << "\nPovY: " << js.getAxisPos(DS4::PovY) << "\n" << "Current node: " << *it << std::endl; erase(); addstr(stream.str().c_str()); refresh(); } } int main() { initscr(); noecho(); cbreak(); int h, w; getmaxyx(stdscr, h, w); js.update(); WINDOW* win = newwin(h, w, 0, 0); wrefresh(win); printDiagnostic(); refresh(); for (unsigned i = 0; i < 5; ++i) { testList.push_back(i); } it = testList.begin(); while (1) { printDiagnostic(); std::this_thread::sleep_for(std::chrono::milliseconds(15)); } return 0; }
[ "5511409+AndruePeters@users.noreply.github.com" ]
5511409+AndruePeters@users.noreply.github.com
f11be7cf5a4dfbd069803431d8afbfe6981397d0
009dab4e411758ab470be8a1fb060a91ef9e9c9d
/src/rif/nest/pmap/HecatonicosachoronMap.gtest.cpp
ad18d868c3a46e4608c6daac28c99ccc517ccb4c
[]
no_license
willsheffler/rif
c5bd76159b2e05862c486b4b3020f1e809c9368f
d9320d535aa46a99496e662902f5705fd22aef5c
refs/heads/master
2020-05-29T09:51:46.886781
2017-03-09T05:57:31
2017-03-09T05:57:31
69,121,987
11
9
null
2017-03-09T05:50:02
2016-09-24T19:06:01
C++
UTF-8
C++
false
false
24,826
cpp
#include <gtest/gtest.h> #include "HecatonicosachoronMap.hpp" #include "io/dump_pdb_atom.hpp" #include "nest/NEST.hpp" #include "util/str.hpp" #include <Eigen/Geometry> // #include <Eigen/Dense> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <fstream> #include <iostream> #include <random> #include <vector> namespace rif { namespace nest { namespace pmap { namespace hecat_test { using namespace Eigen; using std::cout; using std::endl; using std::setprecision; using std::vector; using std::ofstream; using std::string; // using std::bitset; using std::ostream; double const r = (1.0 + sqrt(5.0)) / 2.0; void softassert(bool b, string s) { if (!b) cout << "WARNING: " << s << endl; } void dumpatom(ostream &out, bool nothet, size_t iatom, string atom, string res, char chain, size_t ires, double x, double y, double z, double o, double b, string elem) { assert(atom.size() < 5); assert(res.size() < 4); softassert(x < 10000 && x > -1000, "x out of bounds"); softassert(y < 10000 && y > -1000, "y out of bounds"); softassert(z < 10000 && z > -1000, "z out of bounds"); // cout << "ATOM 1604 C GLU A 220 5.010 12.933 1.553 1.00 41.10 // C" << endl; char buf[128]; snprintf(buf, 128, "%s%5lu %4s %3s %c%4lu %8.3f%8.3f%8.3f%6.2f%6.2f %11s\n", nothet ? "ATOM " : "HETATM", iatom, atom.c_str(), res.c_str(), chain, ires, x, y, z, o, b, elem.c_str()); out << buf; } ostream &operator<<(ostream &out, Quaterniond const &q) { char buf[128]; snprintf(buf, 128, "Quaterniond( %8.5f, %8.5f, %8.5f, %8.5f )", q.w(), q.x(), q.y(), q.z()); out << buf; return out; } // Matrix4d projmat( Quaterniond q ){ // return Vector4d( q.w(), q.x(), q.y(), q.z() ) * RowVector4d( q.w(), // q.x(), q.y(), q.z() ); // } void dumpquats(string fname, vector<Quaterniond> &quats, Matrix4d proj, Quaterniond dir, double window = 0.1) { dir.normalize(); ofstream out(fname.c_str()); size_t ia = 0, ir = 0; int count = 0; BOOST_FOREACH (Quaterniond q, quats) { // if( dir.dot(q) < mindot ) continue; // if( dir.dot(q) < 0.99 ) continue; Vector4d wxyz = proj * Vector4d(q.w(), q.x(), q.y(), q.z()); if (fabs(wxyz[1]) > window || fabs(wxyz[2]) > window || fabs(wxyz[3]) > window) continue; char chain = 'A'; if (q.x() >= q.w() && q.x() >= q.x() && q.x() >= q.y() && q.x() >= q.z()) chain = 'B'; if (q.y() >= q.w() && q.y() >= q.x() && q.y() >= q.y() && q.y() >= q.z()) chain = 'C'; if (q.z() >= q.w() && q.z() >= q.x() && q.z() >= q.y() && q.z() >= q.z()) chain = 'D'; dumpatom(out, true, ++ia, "QUAT", "QUT", chain, ++ir, 3000 * wxyz[1], 3000 * wxyz[2], 3000 * wxyz[3], 1.0, 1.0, "C"); ++count; } cout << dir << " dumped " << count << endl; out.close(); } template <class M> void dumppoints(string fname, M const &pts) { ofstream out(fname.c_str()); size_t ia = 0, ir = 0; int count = 0; for (int i = 0; i < pts.cols(); ++i) { // if( dir.dot(q) < mindot ) continue; dumpatom(out, true, ++ia, "PNT ", "PNT", 'A', ++ir, 100.0 * pts(0, i), 100.0 * pts(1, i), 100.0 * pts(2, i), 1.0, 1.0, "C"); ++count; } out.close(); } // double sign(double d){ // if( d == 0) return 0; // if( d > 0 ) return 1.0; // else return -1.0; // } template <class T> double min_cube_side(T const &coords, Matrix<typename T::Scalar, 3, 1> &cen) { Matrix<typename T::Scalar, 3, 1> const mn = coords.rowwise().minCoeff(); Matrix<typename T::Scalar, 3, 1> const mx = coords.rowwise().maxCoeff(); Matrix<typename T::Scalar, 3, 1> const side = mx - mn; cen = (mn + mx) / 2.0; double const cube = side.maxCoeff(); return cube; } template <class T> double min_cube_side(T const &coords) { Matrix<typename T::Scalar, 3, 1> cen; return min_cube_side(coords, cen); } // TEST(hecatonicosachoron, sample_dodec_inscribe_cube){ // // dodecahedron // // (±1, ±1, ±1) // // (0, ±1/φ, ±φ) // // (±1/φ, ±φ, 0) // // (±φ, 0, ±1/φ) // Matrix<double,3,20> dodec0; // dodec0 << Vector3d( +1, +1, +1 ).normalized(), // Vector3d( +1, +1, -1 ).normalized(), // Vector3d( +1, -1, +1 ).normalized(), // Vector3d( +1, -1, -1 ).normalized(), // Vector3d( -1, +1, +1 ).normalized(), // Vector3d( -1, +1, -1 ).normalized(), // Vector3d( -1, -1, +1 ).normalized(), // Vector3d( -1, -1, -1 ).normalized(), // Vector3d( 0, +1.0/r, +r ).normalized(), // Vector3d( 0, +1.0/r, -r ).normalized(), // Vector3d( 0, -1.0/r, +r ).normalized(), // Vector3d( 0, -1.0/r, -r ).normalized(), // Vector3d( +1.0/r, +r, 0 ).normalized(), // Vector3d( +1.0/r, -r, 0 ).normalized(), // Vector3d( -1.0/r, +r, 0 ).normalized(), // Vector3d( -1.0/r, -r, 0 ).normalized(), // Vector3d( +r, 0 , +1.0/r ).normalized(), // Vector3d( +r, 0 , -1.0/r ).normalized(), // Vector3d( -r, 0 , +1.0/r ).normalized(), // Vector3d( -r, 0 , -1.0/r ).normalized(); // // dumppoints("dodec0.pdb",dodec0); // std::mt19937 mt((unsigned int)time(0)); // std::normal_distribution<> rnorm; // // 0.90919 // Quaterniond Q0( // -0.18683389537307968, // -0.94619545649322123, // 0.1868233140277023, // -0.18682693324842686 // ); // double const rad = 0.001; // Vector3d cen; // double const side0 = min_cube_side(dodec0,cen); // double const area0 = side0*side0*side0; // cout << "min cube side: " << side0 << endl; // BOOST_VERIFY( cen.isApprox(Vector3d(0,0,0))); // double minside = side0; // Matrix<double,3,20> bestdodec; // Quaterniond bestrot; // for(size_t i = 0; i < 100000; ++i){ // // Quaterniond qrand = Quaterniond( rnorm(mt), rnorm(mt), // rnorm(mt), rnorm(mt) ); // Quaterniond qrand( Q0.w()+rnorm(mt)*rad, Q0.x()+rnorm(mt)*rad, // Q0.y()+rnorm(mt)*rad, Q0.z()+rnorm(mt)*rad ); // qrand.normalize(); // if(!i) qrand = Quaterniond(1,0,0,0); // Matrix<double,3,20> rotdodec = qrand.matrix() * dodec0; // double side = min_cube_side(rotdodec,cen); // assert( cen.isApprox(Vector3d(0,0,0))); // if( minside > side ){ // minside = side; // bestrot = qrand; // bestdodec = rotdodec; // double const area = side*side*side; // cout << "min cube side: " << side << " vol: " << area << // " // dodec vol frac: " << area / area0 << " " << i << endl; // cout << bestrot << endl; // } // } // cout << "BEST ROTATION OF DODEC: " << endl; // cout << std::setprecision(17) << "\t\t\t" << bestrot.w() << ",\n\t\t\t" // << bestrot.x() << ",\n\t\t\t" << bestrot.y() << ",\n\t\t\t" << bestrot.z() << // endl; // // dodec volume as constructed 2.78516386312, from this: // // print Vec(1,1,1).normalized().distance( Vec(1/r, r, 0).normalized() // )**3 * (15+7*sqrt(5)) /4.0 // dumppoints("0_dodec_0.pdb",dodec0/dodec0.block(0,0,3,1).norm()); // dumppoints("0_dodec_best.pdb",bestdodec/bestdodec.block(0,0,3,1).norm()); // // std::exit(0); // } vector<Quaterniond> make_half120cell() { // hexacosichoron (600-cell), 120 virts // (±½,±½,±½,±½), // and 8 vertices obtained from // (0,0,0,±1) // by permuting coordinates. The remaining 96 vertices are obtained by taking // even permutations of // ½(±φ,±1,±1/φ,0). // hecatonicosachoron (120-cell), 600 virts // The 600 vertices of the 120-cell include all permutations of:[1] // (0, 0, ±2, ±2) // (±1, ±1, ±1, ±√5) // (±φ-2, ±φ, ±φ, ±φ) // (±φ-1, ±φ-1, ±φ-1, ±φ2) // and all even permutations of // (0, ±φ-2, ±1, ±φ2) // (0, ±φ-1, ±φ, ±√5) // (±φ-1, ±1, ±φ, ±2) // where φ (also called τ) is the golden ratio, (1+√5)/2. vector<Quaterniond> half120cell; { double const r = (1.0 + sqrt(5.0)) / 2.0; vector<Quaterniond> c120; for (int s1 = 1; s1 > -2; s1 -= 2) { // and 8 vertices obtained from (0,0,0,±1) c120.push_back(Quaterniond(s1, 0, 0, 0)); c120.push_back(Quaterniond(0, s1, 0, 0)); c120.push_back(Quaterniond(0, 0, s1, 0)); c120.push_back(Quaterniond(0, 0, 0, s1)); for (int s2 = 1; s2 > -2; s2 -= 2) { for (int s3 = 1; s3 > -2; s3 -= 2) { // (±½,±½,±½,±½), c120.push_back(Quaterniond(0.5, s1 * 0.5, s2 * 0.5, s3 * 0.5)); c120.push_back(Quaterniond(-0.5, s1 * 0.5, s2 * 0.5, s3 * 0.5)); // The remaining 96 vertices are obtained by taking even permutations // of // ½(±φ,±1,±1/φ,0). double const a = s1 * r / 2.0, b = s2 * 1 / 2.0, c = s3 / r / 2.0, d = 0; c120.push_back(Quaterniond(a, b, c, d)); // 0 // c120.push_back( Quaterniond( a,b,d,c ) ); // 1 // c120.push_back( Quaterniond( a,c,b,d ) ); // 1 c120.push_back(Quaterniond(a, c, d, b)); // 2 c120.push_back(Quaterniond(a, d, b, c)); // 2 // c120.push_back( Quaterniond( a,d,c,b ) ); // 3 // c120.push_back( Quaterniond( b,a,c,d ) ); // 1 c120.push_back(Quaterniond(b, a, d, c)); // 2 c120.push_back(Quaterniond(b, c, a, d)); // 2 // c120.push_back( Quaterniond( b,c,d,a ) ); // 3 // c120.push_back( Quaterniond( b,d,a,c ) ); // 3 c120.push_back(Quaterniond(b, d, c, a)); // 4 c120.push_back(Quaterniond(c, a, b, d)); // 2 // c120.push_back( Quaterniond( c,a,d,b ) ); // 3 // c120.push_back( Quaterniond( c,b,a,d ) ); // 3 c120.push_back(Quaterniond(c, b, d, a)); // 4 c120.push_back(Quaterniond(c, d, a, b)); // 4 // c120.push_back( Quaterniond( c,d,b,a ) ); // 5 // c120.push_back( Quaterniond( d,a,b,c ) ); // 3 c120.push_back(Quaterniond(d, a, c, b)); // 4 c120.push_back(Quaterniond(d, b, a, c)); // 4 // c120.push_back( Quaterniond( d,b,c,a ) ); // 5 // c120.push_back( Quaterniond( d,c,a,b ) ); // 5 c120.push_back(Quaterniond(d, c, b, a)); // 6 } } } /// provieds about 10% decrease to out-of-bounds samples Quaterniond alignq(-0.18683389537307968, -0.94619545649322123, 0.1868233140277023, -0.18682693324842686); Matrix4d alignment; alignment.fill(0); alignment.block(0, 0, 3, 3) = alignq.matrix(); alignment(3, 3) = 1.0; BOOST_VERIFY( Vector4d(0, 0, 0, 1).isApprox(alignment * Vector4d(0, 0, 0, 1))); BOOST_FOREACH (Quaterniond q, c120) { q.coeffs() = alignment * q.coeffs(); if (q.w() > 0 || (q.w() == 0 && q.x() > 0) || (q.w() == 0 && q.x() == 0 && q.y() > 0) || (q.w() == 0 && q.x() == 0 && q.y() == 0 && q.z() > 0)) { half120cell.push_back(q); // } else { // BOOST_VERIFY( false ); } } if (half120cell.size() != 60) { cout << "problem making half-120-cell " << half120cell.size() << endl; // std::exit(-1); } } return half120cell; } Array<uint8_t, 60, 12> make_half120cell_neighbors( vector<Quaterniond> const &half120cell) { Array<uint8_t, 60, 12> nbrs; for (size_t i = 0; i < 60; ++i) { Quaterniond const &p = half120cell[i]; size_t nnbr = 0; for (size_t j = 0; j < 60; ++j) { if (i == j) continue; Quaterniond const &q = half120cell[j]; double ang = acos(2.0 * q.dot(p) * q.dot(p) - 1.0) * 180.0 / M_PI; if (ang < 73.0) { BOOST_VERIFY(nnbr < 12); nbrs(i, nnbr++) = (uint8_t)j; } } BOOST_VERIFY(nnbr == 12); } // for(size_t i = 0; i < 60; ++i){ // cout << "nbrs " << i; // for(size_t j = 0; j < 12; ++j){ // cout << " " << (int)nbrs(i,j); // } // cout << endl; // } return nbrs; } vector<Quaterniond> make_half120cell(); // TEST(hecatonicosachoron, dump_static_data){ // vector<Quaterniond> half120cell = make_half120cell(); // Array<uint8_t,60,12> nbrs = make_half120cell_neighbors(half120cell); // cout << "\t\tstatic T const h120[240] = {" << endl; // BOOST_FOREACH(Quaterniond q,half120cell){ // cout << "\t\t\t" << setprecision(17) << q.x() << "," << q.y() // << // "," << q.z() << "," << q.w() << "," << endl; // } // cout << "\t\t}" << endl; // cout << "\t\tstatic T const h120inv[240] = {" << endl; // BOOST_FOREACH(Quaterniond q,half120cell){ // q = q.inverse(); // cout << "\t\t\t" << setprecision(17) << q.x() << "," << q.y() // << // "," << q.z() << "," << q.w() << "," << endl; // } // cout << "\t\t}" << endl; // cout << "\t\tstatic uint8_t const h120_nbrs[60,12] = {" << endl; // for(int i = 0; i < 60; ++i){ // cout << "\t\t\t"; // for(int j = 0; j < 12; ++j){ // cout << static_cast<int>(nbrs(i,j)) << ","; // } // cout << endl; // } // cout << "\t\t}" << endl; // cout << "\t\tstatic T const cellfaces[36] = {" << endl; // for(int i = 0; i < 12; ++i){ // Vector3d nbr0 = half120cell[nbrs(0,i)].coeffs().block(0,0,3,1); // nbr0 /= nbr0.norm(); // cout << "\t\t\t" << setprecision(17) << nbr0[0] << "," << // nbr0[1] // << "," << nbr0[2] << "," << endl; // } // cout << "\t\t}" << endl; // } // TEST(hecatonicosachoron, cell_alignment){ // ///////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////// // ///////////// this doesn't make sense, must use vertices not centers! // /////////////// // ///////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////// // vector<Quaterniond> half120cell = make_half120cell(); // Array<uint8_t,60,12> nbrs = make_half120cell_neighbors(half120cell); // std::mt19937 mt((unsigned int)time(0)); // std::normal_distribution<> rnorm; // Matrix<double,4,13> dodec0; // for(size_t inbr = 0; inbr < 12; ++inbr){ // dodec0.col(inbr) = half120cell[ nbrs(0,inbr) ].coeffs(); // } // dodec0.col(12) = Vector4d(0,0,0,1); // // cout << dodec0.block(0,0,3,1).norm() << endl; // // // dumppoints("nbr_icos0.pdb",dodec0.block(0,0,3,13)/dodec0.block(0,0,3,1).norm()); // return; // Vector3d cen; // double const side0 = min_cube_side(dodec0.block(0,0,3,12),cen); // BOOST_VERIFY( cen.isApprox(Vector3d(0,0,0)) ); // double const area0 = side0*side0*side0; // cout << "min cube side: " << side0 << endl; // // cout << dodec0.transpose() << endl; // double mincube = side0; // Matrix4d bestm4; // for(size_t i = 0; i < 1; ++i){ // Matrix4d randm4; { // randm4 << 1, 5, 5, 0, // 2, 3, 8, 0, // 3, 4, 7, 0, // 0, 0, 0, 1; // HouseholderQR<Matrix4d> qr(randm4); // randm4 = qr.householderQ(); // // cout << randm4 << endl << endl; // // cout << ( randm4 * Vector4d(0,0,0,1) ).transpose() << // endl; // BOOST_VERIFY( // Vector4d(0,0,0,1).isApprox(randm4*Vector4d(0,0,0,1)) ); // } // Matrix<double,4,13>dodec = randm4 * dodec0; // // cout << dodec.transpose() << endl; // // dumppoints("test.pdb",dodec); // double const side = min_cube_side(dodec.block(0,0,3,12),cen); // BOOST_VERIFY( cen.isApprox(Vector3d(0,0,0)) ); // if( mincube > side ){ // mincube = side; // bestm4 = randm4; // double const area = side*side*side; // cout << "min cube side: " << side << " vol: " << area << // " // dodec vol frac: " << area / area0 << endl; // } // } // } TEST(hecatonicosachoron, neighbor_identity_rots_init) { vector<Quaterniond> half120cell = make_half120cell(); Array<uint8_t, 60, 12> nbrs = make_half120cell_neighbors(half120cell); std::vector<Quaterniond> nbrs0; for (size_t inbr = 0; inbr < 12; ++inbr) nbrs0.push_back(half120cell[nbrs(0, inbr)]); // size_t ir = 0, ia = 0; size_t id = 0; BOOST_FOREACH (Quaterniond d, half120cell) { Quaterniond const dinv = d.inverse(); // Quaterniond const dinvd = dinv*d; // std::cout << d << " | " << dinv << " | " << dinvd << endl; // ofstream out(("120cell_"+str(id)+".pdb").c_str()); for (size_t inbr = 0; inbr < 12; ++inbr) { Quaterniond const q = half120cell[nbrs(id, inbr)]; Quaterniond p = to_half_cell(dinv * q); // double norm = 100.0/p.coeffs().block(0,0,3,1).norm(); // std::cout << d << " | " << q << " | " << p << endl; if (fabs(p.norm() - 1.0) > 0.0000001) std::exit(-1); // if( p.w() < 0.8 ) continue; // dumpatom(out,true,++ia,"QUAT","QUT",'A',++ir,norm*p.x(),norm*p.y(),norm*p.z(),1.0,1.0,"C"); bool in_nbrs0 = false; for (size_t jnbr = 0; jnbr < 12; ++jnbr) { if (p.isApprox(nbrs0[jnbr])) { in_nbrs0 = true; // cout << id << " " << inbr << " " << jnbr << endl; } } ASSERT_TRUE(in_nbrs0); } // out.close(); ++id; // break; } } TEST(hecatonicosachoron, static_inv_check) { typedef Map<Quaterniond const> QM; double const *h120raw = get_h120<double>(); double const *h120invraw = get_h120inv<double>(); Map<Matrix<double, 4, 60> const> h120(h120raw); Map<Matrix<double, 4, 60> const> h120inv(h120invraw); Map<Array<uint8_t, 12, 60> const> nbrs(get_h120_nbrs<uint8_t>()); for (int i = 0; i < 60; ++i) { ASSERT_TRUE( Quaterniond(1, 0, 0, 0) .isApprox(h120_cellcen<double>(i) * h120_cellceninv<double>(i))); } } #ifdef CXX11 TEST(hecatonicosachoron, neighbor_identity_rots) { typedef Map<Quaterniond const> QM; double const *h120raw = get_h120<double>(); vector<Quaterniond> h120ref = make_half120cell(); Array<uint8_t, 60, 12> nbrsref = make_half120cell_neighbors(h120ref); Map<Matrix<double, 4, 60> const> h120(h120raw); Map<Array<uint8_t, 12, 60> const> nbrs(get_h120_nbrs<uint8_t>()); for (int i = 0; i < 60; ++i) { ASSERT_TRUE(h120ref[i].isApprox(QM(4 * i + h120raw))); ASSERT_TRUE(h120ref[i].isApprox(h120_cellcen<double>(i))); for (int j = 0; j < 12; ++j) { ASSERT_EQ(nbrsref(i, j), nbrs(j, i)); } } // cout << Quaterniond(h120.col(0)) << endl; // cout << Quaterniond(h120.col(1)) << endl; // cout << QM( h120raw+0 ) << endl; // cout << QM( h120raw+4 ) << endl; // cout << nbrs.col(0).transpose().cast<int>() << endl; // cout << nbrs.col(1).transpose().cast<int>() << endl; std::vector<QM> nbrs0; for (size_t inbr = 0; inbr < 12; ++inbr) { nbrs0.push_back(QM(h120raw + 4 * nbrs(inbr, 0))); } // BOOST_FOREACH( Quaterniond q , nbrs0 ) cout << q << endl; // size_t ir = 0, ia = 0; for (int id = 0; id < 60; ++id) { // QM d( 4*id + h120raw ); // Quaterniond const dinv = d.inverse(); QM dinv = h120_cellceninv<double>(id); // Quaterniond const dinvd = dinv*d; // std::cout << d << " | " << dinv << " | " << dinvd << endl; // ofstream out(("120cell_"+str(id)+".pdb").c_str()); for (size_t inbr = 0; inbr < 12; ++inbr) { // QM q( h120raw + 4*nbrs(inbr,id) ); Quaterniond p = to_half_cell(dinv * h120_cellnbr<double>(id, inbr)); // double norm = 100.0/p.coeffs().block(0,0,3,1).norm(); // std::cout << d << " | " << q << " | " << p << endl; if (fabs(p.norm() - 1.0) > 0.0000001) std::exit(-1); // if( p.w() < 0.8 ) continue; // dumpatom(out,true,++ia,"QUAT","QUT",'A',++ir,norm*p.x(),norm*p.y(),norm*p.z(),1.0,1.0,"C"); bool in_nbrs0 = false; for (size_t jnbr = 0; jnbr < 12; ++jnbr) { if (p.isApprox(nbrs0[jnbr])) { in_nbrs0 = true; // cout << id << " " << inbr << " " << jnbr << endl; } } ASSERT_TRUE(in_nbrs0); } // out.close(); // break; } } #endif TEST(hecatonicosachoron, cell_bounds) { // cout << h120_cellcen<double>(0) << endl; // cout << cellnbr<double>(0,0) << endl; // cout << // (h120_cellcen<double>(0).coeffs()+cellnbr<double>(0,0).coeffs()).normalized().transpose() // << endl; // cout << std::setprecision(17) << // (h120_cellcen<double>(0).coeffs()-cellnbr<double>(0,0).coeffs()).norm() << // endl; } TEST(hecatonicosachoron, cell_lookup) { // HecatonicosachoronMap<> map; // HecatonicosachoronMap<>::Params p; // for( size_t i = 0; i < 60; ++i){ // size_t cell_index = 999; // map.value_to_params( h120_cellcen<double>(i).matrix(), 0, p, cell_index // ); // // cout << p << endl; // ASSERT_EQ( i, cell_index ); // ASSERT_NEAR( p[0], 0.5, 0.0000001 ); // ASSERT_NEAR( p[1], 0.5, 0.0000001 ); // ASSERT_NEAR( p[2], 0.5, 0.0000001 ); // } NEST<3, Matrix3d, HecatonicosachoronMap> nest; // ASSERT_EQ( 0, nest.get_index( nest.set_and_get(0,2), 2 )); int MAX_RESL = 3; #ifdef SCHEME_BENCHMARK MAX_RESL += 2; #endif for (int r = 0; r <= MAX_RESL; ++r) { for (int i = 0; i < (int)nest.size(r); ++i) { if (nest.set_state(i, r)) { size_t ilookup = nest.get_index(nest.value(), r); size_t ci0 = i >> (3 * r); size_t ciL = ilookup >> (3 * r); if (ci0 == ciL) ASSERT_EQ(i, ilookup); } } } } TEST(hecatonicosachoron, covering) { // cout << "QuaternionMap Covrad" << endl; int NRES = 8; int NITER = 10 * 1000; #ifdef SCHEME_BENCHMARK NITER = 1000 * 1000; #endif std::mt19937 rng((unsigned int)time(0)); std::normal_distribution<> gauss; std::uniform_real_distribution<> uniform; NEST<3, Matrix3d, HecatonicosachoronMap> nest; for (int r = 0; r <= NRES; ++r) { double maxdiff = 0, avgdiff = 0; for (int i = 0; i <= NITER; ++i) { Eigen::Quaterniond q(fabs(gauss(rng)), gauss(rng), gauss(rng), gauss(rng)); q.normalize(); // cout << q << endl; Eigen::Quaterniond qcen( nest.set_and_get(nest.get_index(q.matrix(), r), r)); maxdiff = std::max(maxdiff, q.angularDistance(qcen)); avgdiff += q.angularDistance(qcen); } avgdiff /= NITER; size_t count = 0; for (size_t i = 0; i < nest.size(r) / 60; ++i) if (nest.set_state(i, r)) ++count; count *= 60; // size_t count = nest.size(r); double volfrac = (double)count * (maxdiff * maxdiff * maxdiff) * 4.0 / 3.0 * M_PI / 8.0 / M_PI / M_PI; double avgfrac = (double)count * (avgdiff * avgdiff * avgdiff) * 4.0 / 3.0 * M_PI / 8.0 / M_PI / M_PI; printf("%2i %16lu %10.5f %10.5f %10.5f %10.5f %10.5f\n", r, count, maxdiff * 180.0 / M_PI, avgdiff * 180.0 / M_PI, maxdiff / avgdiff, volfrac, avgfrac); } } // TEST( hecatonicosachoron, visualize ){ // std::mt19937 rng((unsigned int)time(0)); // std::normal_distribution<> gauss; // std::uniform_real_distribution<> uniform; // // Quaterniond qrand( gauss(rng), gauss(rng), gauss(rng), gauss(rng) ); // Quaterniond qrand( 1,0,0,0 ); // qrand.normalize(); // Vector3d X = qrand*Vector3d(1,0 ,0 ); // Vector3d Y = qrand*Vector3d(0,1.2,0 ); // Vector3d Z = qrand*Vector3d(0,0 ,1.4); // NEST<3,Matrix3d,HecatonicosachoronMap> nest; // // size_t beg = 0; // // while(!nest.set_state(beg,10)) beg = // std::max<size_t>(uniform(rng)*(nest.size(10)-1000),0); // for(size_t r = 0; r <= 4; ++r){ // int N = 2 * std::pow(8,r); // int beg = std::max( 0, (int)nest.size(r)/12 - N/2 ); // std::ofstream // out(("h120_"+boost::lexical_cast<std::string>(r)+".pdb").c_str()); // size_t count1 = 0, count2 = 0; // // cout << r << " " << nest.size(r) << " " << (beg>>(4*(10-r))) // << // endl; // // continue; // // for(size_t i = beg>>(4*(10-r)); i < nest.size(r); ++i){ // for(size_t i = beg; i < nest.size(r); ++i){ // ++count1; // if( nest.set_state(i,r) ){ // ++count2; // if( count1 > N) break; // Matrix3d m = nest.value(); // // cout << r << " " << i << " " << // q.coeffs().transpose() // << endl; // Vector3d ximg = m * X; // Vector3d yimg = m * Y; // Vector3d zimg = m * Z;; // // cout << r << " " << nest.cell_index(i,r) << // endl; // io::dump_pdb_atom(out, // nest.cell_index(i,r)<5?"H":"O" // ,60*ximg); // io::dump_pdb_atom(out, // nest.cell_index(i,r)<5?"H":"NI",60*yimg); // io::dump_pdb_atom(out, // nest.cell_index(i,r)<5?"H":"N" // ,60*zimg); // } // } // out.close(); // cout << r << " " << count2 / (double)count1 << endl; // } // } } } } }
[ "willsheffler@gmail.com" ]
willsheffler@gmail.com
149f2e6b2319a0fbff935e5e4846f978cf5d6708
7567a3c4805733fc894cc4e9fe0aaef677cbabb3
/Demos/SSAODemo/Main.cpp
7413280a84d58fff2f01926fcfeff1750e6a3a6e
[]
no_license
A-K/Huurre3D
8230473579d5eec7c31f5fe3bbac9ecee9801aa3
7c99c0e1909f7e7937f10bceba1c628bbdd08a34
refs/heads/master
2016-09-06T09:23:26.908279
2015-02-18T16:58:45
2015-02-18T16:58:45
26,214,972
2
0
null
null
null
null
UTF-8
C++
false
false
1,349
cpp
// // Copyright (c) 2013-2015 Antti Karhu. // // 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 "SSAODemo.h" int main(int argc, const char* argv[]) { Engine engine; SSAODemo SSAODemoApp; assert(engine.init("../../Demos/SSAODemo/SSAODemoConfig.json")); engine.setApp(&SSAODemoApp); engine.run(); }
[ "anttikarh@gmail.com" ]
anttikarh@gmail.com
0918b59fb425e6bdf18e7de61583d92ee2de9fcc
8afb5afd38548c631f6f9536846039ef6cb297b9
/_REPO/MICROSOFT/cocos2d-x/cocos/renderer/ccGLStateCache.h
a9e4001718277e3d1edd8359be8d644068e2cb35
[ "MIT" ]
permissive
bgoonz/UsefulResourceRepo2.0
d87588ffd668bb498f7787b896cc7b20d83ce0ad
2cb4b45dd14a230aa0e800042e893f8dfb23beda
refs/heads/master
2023-03-17T01:22:05.254751
2022-08-11T03:18:22
2022-08-11T03:18:22
382,628,698
10
12
MIT
2022-10-10T14:13:54
2021-07-03T13:58:52
null
UTF-8
C++
false
false
5,806
h
/**************************************************************************** Copyright (c) 2011 Ricardo Quesada Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2011 Zynga Inc. Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __CCGLSTATE_H__ #define __CCGLSTATE_H__ #include <cstdint> #include "platform/CCGL.h" #include "platform/CCPlatformMacros.h" NS_CC_BEGIN /** * @addtogroup renderer * @{ */ class GLProgram; class Texture2D; namespace GL { /** Vertex attrib flags. */ enum { VERTEX_ATTRIB_FLAG_NONE = 0, VERTEX_ATTRIB_FLAG_POSITION = 1 << 0, VERTEX_ATTRIB_FLAG_COLOR = 1 << 1, VERTEX_ATTRIB_FLAG_TEX_COORD = 1 << 2, VERTEX_ATTRIB_FLAG_NORMAL = 1 << 3, VERTEX_ATTRIB_FLAG_BLEND_WEIGHT = 1 << 4, VERTEX_ATTRIB_FLAG_BLEND_INDEX = 1 << 5, VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = (VERTEX_ATTRIB_FLAG_POSITION | VERTEX_ATTRIB_FLAG_COLOR | VERTEX_ATTRIB_FLAG_TEX_COORD), }; /** * Invalidates the GL state cache. * * If CC_ENABLE_GL_STATE_CACHE it will reset the GL state cache. * @since v2.0.0 */ void CC_DLL invalidateStateCache(void); /** * Uses the GL program in case program is different than the current one. * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly. * @since v2.0.0 */ void CC_DLL useProgram(GLuint program); /** * Deletes the GL program. If it is the one that is being used, it invalidates it. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly. * @since v2.0.0 */ void CC_DLL deleteProgram(GLuint program); /** * Uses a blending function in case it not already used. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly. * @since v2.0.0 */ void CC_DLL blendFunc(GLenum sfactor, GLenum dfactor); /** * Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation(). * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will just set the default blending mode using GL_FUNC_ADD. * @since v2.0.0 */ void CC_DLL blendResetToCache(void); /** * Sets the projection matrix as dirty. * @since v2.0.0 */ void CC_DLL setProjectionMatrixDirty(void); /** * Will enable the vertex attribs that are passed as flags. * Possible flags: * * * VERTEX_ATTRIB_FLAG_POSITION * * VERTEX_ATTRIB_FLAG_COLOR * * VERTEX_ATTRIB_FLAG_TEX_COORDS * * These flags can be ORed. The flags that are not present, will be disabled. * * @since v2.0.0 */ void CC_DLL enableVertexAttribs(uint32_t flags); /** * If the texture is not already bound to texture unit 0, it binds it. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. * @since v2.0.0 */ void CC_DLL bindTexture2D(GLuint textureId); /** * If the texture is not already bound to texture unit 0, it binds it. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. * * @remark: It will bind alpha texture to support ETC1 alpha channel. * @since v3.13 */ void CC_DLL bindTexture2D(Texture2D* texture); /** * If the texture is not already bound to a given unit, it binds it. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. * @since v2.1.0 */ void CC_DLL bindTexture2DN(GLuint textureUnit, GLuint textureId); /** If the texture is not already bound to a given unit, it binds it. * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. * @since v3.6 */ void CC_DLL bindTextureN(GLuint textureUnit, GLuint textureId, GLuint textureType = GL_TEXTURE_2D); /** * It will delete a given texture. If the texture was bound, it will invalidate the cached. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. * @since v2.0.0 */ void CC_DLL deleteTexture(GLuint textureId); /** * It will delete a given texture. If the texture was bound, it will invalidate the cached for the given texture unit. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. * @since v2.1.0 */ CC_DEPRECATED_ATTRIBUTE void CC_DLL deleteTextureN(GLuint textureUnit, GLuint textureId); /** * Select active texture unit. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glActiveTexture() directly. * @since v3.0 */ void CC_DLL activeTexture(GLenum texture); /** * If the vertex array is not already bound, it binds it. * * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. * @since v2.0.0 */ void CC_DLL bindVAO(GLuint vaoId); // end of support group /// @} } // Namespace GL NS_CC_END #endif /* __CCGLSTATE_H__ */
[ "bryan.guner@gmail.com" ]
bryan.guner@gmail.com
3d50027ea4c6ff9f7a1bb1397c3660535bddd160
fed18c8d3288e597a9055836bed227a58c28aaa7
/lessons/lesson_20/game.cpp
3badce02bbd4afbe2fce90bd2f073347faf3d4d5
[]
no_license
cCppProsto/SDLLesson
22bc3106e0249416a522c4329de48b599039a504
22d332cf89aeeaef8431a99d9c1a148109e2e3fd
refs/heads/master
2021-06-20T19:10:21.434487
2021-03-06T05:57:42
2021-03-06T05:57:42
189,386,063
1
0
null
null
null
null
UTF-8
C++
false
false
4,860
cpp
#include <SDL.h> #include "sdlengine.hpp" #include "game.hpp" #include "strResources.hpp" //------------------------------------------------------------------------------ game::game() { _load_textures(); float x = (SDLEngine::instance().windowWidth() / 2) - (m_block_a.width() / 2); float y1 = SDLEngine::instance().windowHeight() * 0.10f; float y2 = SDLEngine::instance().windowHeight() * 0.90f; m_block_a.set_position(x, y1); m_block_b.set_position(x, y2); m_ball.add_horizontal_block(m_block_a); m_ball.add_horizontal_block(m_block_b); m_block_c.set_vertical(); m_block_d.set_vertical(); float y = (SDLEngine::instance().windowHeight() / 2) - (m_block_c.height() / 2); float x1 = SDLEngine::instance().windowWidth() * 0.10; float x2 = SDLEngine::instance().windowWidth() * 0.90; m_block_c.set_position(x1, y); m_block_d.set_position(x2, y); m_ball.add_vertical_block(m_block_c); m_ball.add_vertical_block(m_block_d); x = ( SDLEngine::instance().windowWidth() / 2 ) - m_ball.width() / 2; y = ( SDLEngine::instance().windowHeight() / 2 ) - m_ball.height() / 2; m_ball.set_position(x, y); } //------------------------------------------------------------------------------ game::~game() { } //------------------------------------------------------------------------------ void game::_load_textures() { } //------------------------------------------------------------------------------ void game::draw() { if (m_is_run) { _draw_game(); } if (m_is_pause) { _draw_pause(); } } //------------------------------------------------------------------------------ void game::process() { if (m_is_run) { m_ball.move(); _keyboard_state_process_in_game(); return; } if (m_is_pause) { return; } } //------------------------------------------------------------------------------ void game::_keyboard_state_process_in_game() { const Uint8* keystates = SDL_GetKeyboardState(NULL); if (keystates[SDL_SCANCODE_LEFT]) { m_block_a.move_left(); m_block_b.move_right(); } else if (keystates[SDL_SCANCODE_RIGHT]) { m_block_a.move_right(); m_block_b.move_left(); } else if(keystates[SDL_SCANCODE_UP]) { m_block_c.move_up(); m_block_d.move_down(); } else if (keystates[SDL_SCANCODE_DOWN]) { m_block_c.move_down(); m_block_d.move_up(); } } //------------------------------------------------------------------------------ void game::handle_keyboard_event(const SDL_KeyboardEvent &aEvent) { if (m_is_run) { _handle_keyboard_event_run(aEvent); return; } if (m_is_pause) { _handle_keyboard_event_pause(aEvent); return; } } //------------------------------------------------------------------------------ void game::_handle_keyboard_event_run(const SDL_KeyboardEvent &aEvent) { switch (aEvent.state) { case SDL_PRESSED: { switch (aEvent.keysym.sym) { } break; } case SDL_RELEASED: { switch (aEvent.keysym.sym) { case SDLK_ESCAPE: { m_is_pause = true; m_is_run = false; break; } case SDLK_DOWN: case SDLK_UP: case SDLK_RETURN: { break; } } break; } } } //------------------------------------------------------------------------------ void game::_handle_keyboard_event_pause(const SDL_KeyboardEvent &aEvent) { switch (aEvent.state) { case SDL_PRESSED: { break; } case SDL_RELEASED: { switch (aEvent.keysym.sym) { case SDLK_ESCAPE: { m_is_pause = false; m_is_run = false; m_is_exit = true; break; } case SDLK_RETURN: { m_is_pause = false; m_is_run = true; m_is_exit = false; break; } } break; } } } //------------------------------------------------------------------------------ void game::_draw_game() { m_ball.draw(); m_block_a.draw(); m_block_b.draw(); m_block_c.draw(); m_block_d.draw(); } //------------------------------------------------------------------------------ void game::_draw_pause() { m_ball.draw(); m_block_a.draw(); m_block_b.draw(); m_block_c.draw(); m_block_d.draw(); } //------------------------------------------------------------------------------ void game::init() { m_is_exit = false; m_is_pause = false; m_is_run = true; } //------------------------------------------------------------------------------ const bool &game::isExit()const { return m_is_exit; }
[ "yaroslavoleshko@gmail.com" ]
yaroslavoleshko@gmail.com
5f52ba58b17b8f3d7d8bc5d8e6fcd67920b7839d
e98e505de1a1a3542189125ef4bdde147f9c77cd
/components/cronet/android/cronet_url_request_context_adapter.h
664c8f39689fc10a974aafd5083c91cb26c7b420
[ "BSD-3-Clause" ]
permissive
jesonlay/chromium
b98fca219ab71d230df9a758252058a18e075a06
292532fedbb55d68a83b46c106fd04849a47571d
refs/heads/master
2022-12-16T15:25:13.723395
2017-03-20T14:36:34
2017-03-20T15:37:49
158,929,892
0
0
NOASSERTION
2018-11-24T11:32:20
2018-11-24T11:32:19
null
UTF-8
C++
false
false
10,328
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_CRONET_ANDROID_CRONET_URL_REQUEST_CONTEXT_ADAPTER_H_ #define COMPONENTS_CRONET_ANDROID_CRONET_URL_REQUEST_CONTEXT_ADAPTER_H_ #include <jni.h> #include <stdint.h> #include <memory> #include <queue> #include <string> #include "base/android/scoped_java_ref.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/threading/thread.h" #include "components/prefs/json_pref_store.h" #include "net/nqe/effective_connection_type.h" #include "net/nqe/network_quality_estimator.h" #include "net/nqe/network_quality_observation_source.h" class PrefService; namespace base { class SingleThreadTaskRunner; class TimeTicks; } // namespace base namespace net { class HttpServerPropertiesManager; class NetLog; class NetworkQualitiesPrefsManager; class ProxyConfigService; class SdchOwner; class URLRequestContext; class FileNetLogObserver; } // namespace net namespace cronet { class TestUtil; #if defined(DATA_REDUCTION_PROXY_SUPPORT) class CronetDataReductionProxy; #endif struct URLRequestContextConfig; bool CronetUrlRequestContextAdapterRegisterJni(JNIEnv* env); // Adapter between Java CronetUrlRequestContext and net::URLRequestContext. class CronetURLRequestContextAdapter : public net::NetworkQualityEstimator::EffectiveConnectionTypeObserver, public net::NetworkQualityEstimator::RTTAndThroughputEstimatesObserver, public net::NetworkQualityEstimator::RTTObserver, public net::NetworkQualityEstimator::ThroughputObserver { public: explicit CronetURLRequestContextAdapter( std::unique_ptr<URLRequestContextConfig> context_config); ~CronetURLRequestContextAdapter() override; // Called on main Java thread to initialize URLRequestContext. void InitRequestContextOnMainThread( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller); // Releases all resources for the request context and deletes the object. // Blocks until network thread is destroyed after running all pending tasks. void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller); // Posts a task that might depend on the context being initialized // to the network thread. void PostTaskToNetworkThread(const tracked_objects::Location& posted_from, const base::Closure& callback); bool IsOnNetworkThread() const; net::URLRequestContext* GetURLRequestContext(); // TODO(xunjieli): Keep only one version of StartNetLog(). // Starts NetLog logging to file. This can be called on any thread. // Return false if |jfile_name| cannot be opened. bool StartNetLogToFile(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, const base::android::JavaParamRef<jstring>& jfile_name, jboolean jlog_all); // Starts NetLog logging to disk with a bounded amount of disk space. This // can be called on any thread. void StartNetLogToDisk(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, const base::android::JavaParamRef<jstring>& jdir_name, jboolean jlog_all, jint jmax_size); // Stops NetLog logging to file. This can be called on any thread. This will // flush any remaining writes to disk. void StopNetLog(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller); // Posts a task to Network thread to get serialized results of certificate // verifications of |context_|'s |cert_verifier|. void GetCertVerifierData(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller); // Default net::LOAD flags used to create requests. int default_load_flags() const { return default_load_flags_; } // Called on main Java thread to initialize URLRequestContext. void InitRequestContextOnMainThread(); // Configures the network quality estimator to observe requests to localhost, // to use smaller responses when estimating throughput, and to disable the // device offline checks when computing the effective connection type or when // writing the prefs. This should only be used for testing. This can be // called only after the network quality estimator has been enabled. void ConfigureNetworkQualityEstimatorForTesting( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, jboolean use_local_host_requests, jboolean use_smaller_responses, jboolean disable_offline_check); // Request that RTT and/or throughput observations should or should not be // provided by the network quality estimator. void ProvideRTTObservations( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, bool should); void ProvideThroughputObservations( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, bool should); private: friend class TestUtil; // Initializes |context_| on the Network thread. void InitializeOnNetworkThread( std::unique_ptr<URLRequestContextConfig> config, const base::android::ScopedJavaGlobalRef<jobject>& jcronet_url_request_context); // Runs a task that might depend on the context being initialized. // This method should only be run on the network thread. void RunTaskAfterContextInitOnNetworkThread( const base::Closure& task_to_run_after_context_init); scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner() const; // Serializes results of certificate verifications of |context_|'s // |cert_verifier| on the Network thread. void GetCertVerifierDataOnNetworkThread(); // Gets the file thread. Create one if there is none. base::Thread* GetFileThread(); // Configures the network quality estimator to observe requests to localhost, // to use smaller responses when estimating throughput, and to disable the // device offline checks when computing the effective connection type or when // writing the prefs. This should only be used for testing. void ConfigureNetworkQualityEstimatorOnNetworkThreadForTesting( bool use_local_host_requests, bool use_smaller_responses, bool disable_offline_check); void ProvideRTTObservationsOnNetworkThread(bool should); void ProvideThroughputObservationsOnNetworkThread(bool should); // net::NetworkQualityEstimator::EffectiveConnectionTypeObserver // implementation. void OnEffectiveConnectionTypeChanged( net::EffectiveConnectionType effective_connection_type) override; // net::NetworkQualityEstimator::RTTAndThroughputEstimatesObserver // implementation. void OnRTTOrThroughputEstimatesComputed( base::TimeDelta http_rtt, base::TimeDelta transport_rtt, int32_t downstream_throughput_kbps) override; // net::NetworkQualityEstimator::RTTObserver implementation. void OnRTTObservation(int32_t rtt_ms, const base::TimeTicks& timestamp, net::NetworkQualityObservationSource source) override; // net::NetworkQualityEstimator::ThroughputObserver implementation. void OnThroughputObservation( int32_t throughput_kbps, const base::TimeTicks& timestamp, net::NetworkQualityObservationSource source) override; // Same as StartNetLogToDisk, but called only on the network thread. void StartNetLogToBoundedFileOnNetworkThread(const std::string& dir_path, bool include_socket_bytes, int size); // Same as StartNetLogToFile, but called only on the network thread. void StartNetLogOnNetworkThread(const base::FilePath& file_path, bool include_socket_bytes); // Stops NetLog logging on the network thread. void StopNetLogOnNetworkThread(); // Callback for StopObserving() that unblocks the Java ConditionVariable and // signals that it is safe to access the NetLog files. void StopNetLogCompleted(); std::unique_ptr<base::DictionaryValue> GetNetLogInfo() const; // Network thread is owned by |this|, but is destroyed from java thread. base::Thread* network_thread_; // File thread should be destroyed last. std::unique_ptr<base::Thread> file_thread_; std::unique_ptr<net::FileNetLogObserver> net_log_file_observer_; // |pref_service_| should outlive the HttpServerPropertiesManager owned by // |context_|. std::unique_ptr<PrefService> pref_service_; std::unique_ptr<net::URLRequestContext> context_; std::unique_ptr<net::ProxyConfigService> proxy_config_service_; scoped_refptr<JsonPrefStore> json_pref_store_; net::HttpServerPropertiesManager* http_server_properties_manager_; // |sdch_owner_| should be destroyed before |json_pref_store_|, because // tearing down |sdch_owner_| forces |json_pref_store_| to flush pending // writes to the disk. std::unique_ptr<net::SdchOwner> sdch_owner_; // Context config is only valid until context is initialized. std::unique_ptr<URLRequestContextConfig> context_config_; // Effective experimental options. Kept for NetLog. std::unique_ptr<base::DictionaryValue> effective_experimental_options_; // A queue of tasks that need to be run after context has been initialized. std::queue<base::Closure> tasks_waiting_for_context_; bool is_context_initialized_; int default_load_flags_; // A network quality estimator. std::unique_ptr<net::NetworkQualityEstimator> network_quality_estimator_; // Manages the writing and reading of the network quality prefs. std::unique_ptr<net::NetworkQualitiesPrefsManager> network_qualities_prefs_manager_; // Java object that owns this CronetURLRequestContextAdapter. base::android::ScopedJavaGlobalRef<jobject> jcronet_url_request_context_; #if defined(DATA_REDUCTION_PROXY_SUPPORT) std::unique_ptr<CronetDataReductionProxy> data_reduction_proxy_; #endif DISALLOW_COPY_AND_ASSIGN(CronetURLRequestContextAdapter); }; } // namespace cronet #endif // COMPONENTS_CRONET_ANDROID_CRONET_URL_REQUEST_CONTEXT_ADAPTER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
57587f1603e4a9972583af9b7956a783666dccf4
e219d3072e127fa021a085b549d595f1c9d6ee7e
/src/SimpleSHA1.cpp
a1516ed8fe58c247f8ef801cfbd74fd02f7e7df6
[ "MIT" ]
permissive
jlusPrivat/SimpleHOTP
73e629de292e9d9fe3912d48e2882dcfc12af882
9de140894bb6e2c31b53d97aa4eb91bd886494d4
refs/heads/master
2022-01-18T19:05:04.452499
2019-07-01T22:50:25
2019-07-01T22:50:25
192,279,560
21
5
MIT
2022-01-04T04:24:16
2019-06-17T05:19:37
C++
UTF-8
C++
false
false
1,941
cpp
#include "SimpleSHA1.h" #define h0 returner[0] #define h1 returner[1] #define h2 returner[2] #define h3 returner[3] #define h4 returner[4] void SimpleSHA1::generateSHA (uint8_t *message, uint64_t ml, uint32_t *returner) { // initialize variables h0 = 0x67452301; h1 = 0xEFCDAB89; h2 = 0x98BADCFE; h3 = 0x10325476; h4 = 0xC3D2E1F0; // calculate the number of required cycles and create a blocks array uint32_t numCycles = ((ml+65)/512)+1; uint32_t blocks[numCycles*16] = {}; // copy message uint32_t messageBytes = ml/8 + (ml%8!=0 ? 1 : 0); for (uint32_t i = 0; i < messageBytes; i++) { blocks[i/4] |= ((uint32_t) message[i]) << (8*(3-(i%4))); } // append the 1 bit blocks[ml/32] |= ((uint32_t) 0b1) << (31-(ml%32)); // append the 64-bit big endian ml at the end if (ml < 0x80000000) blocks[(numCycles*16)-1] = (uint32_t) ml; else { blocks[(numCycles*16)-2] = (uint32_t) ml; blocks[(numCycles*16)-1] = (uint32_t) (ml >> 32); } for (uint32_t iCycle = 0; iCycle < numCycles; iCycle++) { // initalize locals uint32_t w[80] = {}; uint32_t a = h0, b = h1, c = h2, d = h3, e = h4; for (uint8_t i = 0; i < 80; i++) { // convert words to big-endian and copy to 80-elem array if (i < 16) w[i] = blocks[(iCycle*16)+i]; else w[i] = rotL((w[i-3]^w[i-8]^w[i-14]^w[i-16]), 1); // run defined formulas uint32_t f, k, temp; if (i < 20) { f = (b & c) | ((~b) & d); k = 0x5A827999; } else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; } else { f = b ^ c ^ d; k = 0xCA62C1D6; } temp = rotL(a, 5) + f + e + k + w[i]; e = d; d = c; c = rotL(b, 30); b = a; a = temp; } // write back the results h0 += a; h1 += b; h2 += c; h3 += d; h4 += e; } } uint32_t SimpleSHA1::rotL (uint32_t input, uint8_t n) { return (input << n) | (input >> (32-n)); }
[ "jonathan@jlus.de" ]
jonathan@jlus.de
e5ba028c44d1e308ddd296e2f9523fdfe738b985
34b0ef0b0bd0d5266ef8f18c6dae3e26ced11c52
/sgb/ave_2.14/libao.cpp
6ed6b27164e897d4949ba4b3899acdcd2364f241
[]
no_license
lindianyin/sgbj
bfb429301ed743b75e6c781b48f893ee41e3d097
93e35dbeb3dfdb5a604821e9e232fdef13a457a4
refs/heads/master
2021-01-10T08:09:42.160527
2016-02-24T02:17:17
2016-02-24T02:17:17
52,407,281
0
0
null
null
null
null
GB18030
C++
false
false
37,980
cpp
#include "libao.h" #include <mysql/mysql.h> #include "Database.h" #include "Query.h" #include "data.h" #include "spls_errcode.h" #include "utils_all.h" #include "singleton.h" #include "combat.h" #include "statistics.h" #include "net.h" extern Database& GetDb(); extern void InsertSaveDb(const std::string& sql); extern int giveLoots(CharData* cdata, std::list<Item>& getItems, int mapid, int level, int type, Combat* pCombat, json_spirit::Object* robj, bool isAttacker, int statistics_type); int getSessionChar(net::session_ptr& psession, boost::shared_ptr<CharData>& cdata); extern void ItemToObj(Item* sitem, boost::shared_ptr<json_spirit::Object>& sgetobj); const json_spirit::Object& baseLibao::getObj() const { return m_obj; } void baseLibao::getObj(json_spirit::Object& obj) { obj.push_back( Pair("id", m_libao_id) ); obj.push_back( Pair("name", m_name) ); obj.push_back( Pair("memo", m_memo) ); obj.push_back( Pair("spic", m_spic) ); obj.push_back( Pair("quality", m_quality) ); return; } const json_spirit::Array& baseLibao::getArray() const { return m_item_list; } void baseLibao::getArray(CharData& cdata, json_spirit::Array& list) { for (std::list<Item>::iterator it_i = m_list.begin(); it_i != m_list.end(); ++it_i) { //cout << "updateObj libao_id=" << m_libao_id << ",item_type=" << it_i->type << ",item_id=" << it_i->id << endl; boost::shared_ptr<json_spirit::Object> p_obj; Item item = *it_i; switch (it_i->type) { case item_type_silver_level: item.type = item_type_silver; item.nums = cdata.m_level * item.nums; break; case item_type_treasure_level: item.type = item_type_treasure; item.nums = cdata.m_level * item.nums; break; case item_type_prestige_level: item.type = item_type_prestige; item.nums = cdata.m_level * item.nums; break; } ItemToObj(&item, p_obj); if (p_obj.get()) { list.push_back(*(p_obj.get())); } } } void baseLibao::updateObj() { m_obj.clear(); m_obj.push_back( Pair("id", m_libao_id) ); m_obj.push_back( Pair("name", m_name) ); m_obj.push_back( Pair("memo", m_memo) ); m_obj.push_back( Pair("spic", m_spic) ); m_obj.push_back( Pair("quality", m_quality) ); json_spirit::Array getlist; m_item_list.clear(); need_slot_num = 0; for (std::list<Item>::iterator it_i = m_list.begin(); it_i != m_list.end(); ++it_i) { //cout << "updateObj libao_id=" << m_libao_id << ",item_type=" << it_i->type << ",item_id=" << it_i->id << endl; boost::shared_ptr<json_spirit::Object> p_obj; ItemToObj(&(*it_i), p_obj); if (p_obj.get()) { getlist.push_back(*(p_obj.get())); } json_spirit::Object obj; it_i->toObj(obj); m_item_list.push_back(obj); if (it_i->type == item_type_equipment || it_i->type == item_type_baoshi) { ++need_slot_num; } else if(it_i->type == item_type_libao) { need_slot_num += it_i->nums; } else if(it_i->type == item_type_treasure) { boost::shared_ptr<baseTreasure> tr = GeneralDataMgr::getInstance()->GetBaseTreasure(it_i->id); if (tr.get() && tr->currency == 0) { ++need_slot_num; } } } m_obj.push_back( Pair("get", getlist) ); } libao::libao(int id, baseLibao& base) :iItem(iItem_type_libao, base.m_libao_id, id, 1) ,m_base(base) { m_id = id; } std::string libao::name() const { return m_base.m_name; } std::string libao::memo() const { return m_base.m_memo; } uint16_t libao::getSpic() const { return m_base.m_spic; } int libao::getQuality() const { return m_base.m_quality; } void libao::Save() { if (m_changed) { int32_t c = getCount(); if (c > 0) { CharData* pc = getChar(); InsertSaveDb("replace into char_libao (id,libao_id,cid,slot) values (" +LEX_CAST_STR(getId())+"," +LEX_CAST_STR(m_base.m_libao_id)+"," +LEX_CAST_STR(pc!=NULL ? pc->m_id : 0)+"," +LEX_CAST_STR((int)(getSlot()))+")"); } else { InsertSaveDb("delete from char_libao where id=" + LEX_CAST_STR(getId())); } m_changed = false; } } libao_mgr* libao_mgr::m_handle = NULL; libao_mgr* libao_mgr::getInstance() { if (NULL == m_handle) { m_handle = new libao_mgr(); m_handle->load(); } return m_handle; } baseLibao* libao_mgr::getBaselibao(int id) { return m_base_libaos[id]; } int libao_mgr::getLevelLibao(int level) { if (m_levelLibaos.find(level) != m_levelLibaos.end()) { return m_levelLibaos[level]; } else { return 0; } } std::string libao_mgr::getlibaoMemo(int sid) { std::string memo = ""; baseLibao* p = NULL; p = libao_mgr::getInstance()->getBaselibao(sid); if (p == NULL) { return memo; } return p->m_memo; } void libao_mgr::getLevelLibaoList(CharData& cdata, json_spirit::Array& rlist) { for (std::map<int,int>::iterator it = m_levelLibaos.begin(); it != m_levelLibaos.end(); ++it) { //已经领取 if (cdata.m_newbie_reward[it->first]) { continue; } json_spirit::Object obj; obj.push_back( Pair("id", it->first) ); obj.push_back( Pair("level", it->first) ); baseLibao* p = NULL; p = libao_mgr::getInstance()->getBaselibao(it->second); if (p != NULL) { obj.push_back( Pair("list", p->getArray()) ); } //std::string memo = ""; //memo = libao_mgr::getInstance()->getlibaoMemo(it->second); //obj.push_back( Pair("award", memo) ); if (cdata.m_level >= it->first) { obj.push_back( Pair("enable", 1) ); } else { obj.push_back( Pair("enable", 0) ); } rlist.push_back(obj); } } int libao_mgr::getLevelLibaoState(CharData& cdata) { bool finish = true; //更新新手冲锋号是否可以获得 for (std::map<int,int>::iterator it = m_levelLibaos.begin(); it != m_levelLibaos.end(); ++it) { if (cdata.m_newbie_reward[it->first]) { } else if (cdata.m_level >= it->first) { return 1;//可以领取 } else { finish = false; } } if (finish) return 2;//全部领完 return 0;//无可领取 } void libao_mgr::load() { Query q(GetDb()); q.get_result("select id,type,level,attack,stronghold,name,memo,spic,quality from base_libao where 1"); while (q.fetch_row()) { int libao_id = q.getval(); int libao_type = q.getval(); baseLibao*p = new baseLibao; p->m_libao_id = libao_id; p->m_type = libao_type; p->m_level = q.getval(); p->m_attack = q.getval(); p->m_stronghold = q.getval(); p->m_name = q.getstr(); p->m_memo = q.getstr(); p->m_spic = q.getval(); p->m_quality = q.getval(); p->need_slot_num = 0; //p->updateObj(); m_base_libaos[p->m_libao_id] = p; //等级礼包 if (p->m_type == 1) m_levelLibaos[p->m_level] = p->m_libao_id; else if(p->m_type == 2) m_chengzhang_Libaos.push_back(p->m_libao_id); } q.free_result(); q.get_result("select l.libao_id,l.reward_type,l.reward_id,l.reward_num from base_libao_reward as l where 1 order by l.libao_id"); while (q.fetch_row()) { int libao_id = q.getval(); baseLibao* p = getBaselibao(libao_id); if (p != NULL) { Item it; it.type = q.getval(); it.id = q.getval(); it.nums = q.getval(); p->m_list.push_back(it); } //cout << "push_into libao_id=" << libao_id << " now_size=" << p->m_list.size() << endl; } q.free_result(); for (std::map<int, baseLibao* >::iterator it = m_base_libaos.begin(); it != m_base_libaos.end(); ++it) { it->second->updateObj(); } m_libao_id = 0; q.get_result("select max(id) from char_libao where 1"); CHECK_DB_ERR(q); if (q.fetch_row()) { m_libao_id = q.getval(); } q.free_result(); #ifdef QQ_PLAT //黄钻等级礼包 q.get_result("select level,itemType,itemId,counts from base_qq_level_libao where 1 order by level,id"); CHECK_DB_ERR(q); while (q.fetch_row()) { int level = q.getval(); baseLibao* lb = getQQLevelLibao(level); if (NULL == lb) { boost::shared_ptr<baseLibao> splb(new baseLibao); m_qq_levelLibaos[level] = splb; lb = splb.get(); lb->m_libao_id = 0; lb->m_type = 0; lb->m_level = level; lb->m_name = "qq yellow level"; lb->m_memo = ""; lb->m_spic = 0; lb->m_quality = 0; lb->need_slot_num = 0; } if (lb) { Item it; it.type = q.getval(); it.id = q.getval(); it.nums = q.getval(); lb->m_list.push_back(it); } } q.free_result(); //黄钻新手礼包 q.get_result("select itemType,itemId,counts from base_qq_newbie_libao where 1"); CHECK_DB_ERR(q); while (q.fetch_row()) { //int level = q.getval(); baseLibao* lb = getQQNewbieLibao(); if (NULL == lb) { boost::shared_ptr<baseLibao> splb(new baseLibao); m_qq_newbie_libao = splb; lb = splb.get(); lb->m_libao_id = 0; lb->m_type = 0; lb->m_level = 1; lb->m_name = "qq yellow newbie"; lb->m_memo = ""; lb->m_spic = 0; lb->m_quality = 0; lb->need_slot_num = 0; } if (lb) { Item it; it.type = q.getval(); it.id = q.getval(); it.nums = q.getval(); lb->m_list.push_back(it); } } q.free_result(); //黄钻专属礼包 q.get_result("select level,itemType,itemId,counts from base_qq_yellow_general where 1"); CHECK_DB_ERR(q); while (q.fetch_row()) { int level = q.getval(); baseLibao* lb = getQQSpecialLibao(); if (NULL == lb) { boost::shared_ptr<baseLibao> splb(new baseLibao); m_qq_special_libao = splb; lb = splb.get(); lb->m_libao_id = 0; lb->m_type = 0; lb->m_level = level; lb->m_name = "qq yellow special"; lb->m_memo = ""; lb->m_spic = 0; lb->m_quality = 0; lb->need_slot_num = 0; } else { if (level > lb->m_level) { lb->m_level = level; } } if (lb) { Item it; it.type = q.getval(); it.id = q.getval(); it.nums = q.getval(); lb->m_list.push_back(it); } } q.free_result(); //黄钻每日礼包 q.get_result("select yellow_level,itemType,itemId,counts from base_qq_yellow_daily_libao where 1 order by yellow_level,id"); CHECK_DB_ERR(q); while (q.fetch_row()) { int level = q.getval(); //cout<<"qq yellow daily libao level "<<level<<endl; baseLibao* lb = NULL; if (level == 0) { lb = getQQYearDailyLibao(); if (NULL == lb) { //cout<<"add qq year daily libao"<<endl; boost::shared_ptr<baseLibao> splb(new baseLibao); m_qq_year_daily_libao = splb; lb = splb.get(); lb->m_libao_id = 0; lb->m_type = 0; lb->m_level = level; lb->m_name = "qq year yellow daily"; lb->m_memo = ""; lb->m_spic = 0; lb->m_quality = 0; lb->need_slot_num = 0; } } else { lb = getQQDailyLibao(level); if (NULL == lb) { //cout<<"add qq daily libao"<<endl; boost::shared_ptr<baseLibao> splb(new baseLibao); m_qq_daily_libao[level] = splb; lb = splb.get(); lb->m_libao_id = 0; lb->m_type = 0; lb->m_level = level; lb->m_name = "qq yellow daily"; lb->m_memo = ""; lb->m_spic = 0; lb->m_quality = 0; lb->need_slot_num = 0; } } if (lb) { Item it; it.type = q.getval(); it.id = q.getval(); it.nums = q.getval(); lb->m_list.push_back(it); //cout<<"add qq year daily libao, add item "<<it.type<<","<<it.id<<","<<it.nums<<endl; } } q.free_result(); if (m_qq_newbie_libao.get()) { m_qq_newbie_libao->updateObj(); } if (m_qq_special_libao.get()) { m_qq_special_libao->updateObj(); } if (m_qq_year_daily_libao.get()) { m_qq_year_daily_libao->updateObj(); } for (std::map<int, boost::shared_ptr<baseLibao> >::iterator it = m_qq_levelLibaos.begin(); it != m_qq_levelLibaos.end(); ++it) { if (it->second.get()) { it->second->updateObj(); } } m_qq_daily_list.clear(); for (std::map<int, boost::shared_ptr<baseLibao> >::iterator it = m_qq_daily_libao.begin(); it != m_qq_daily_libao.end(); ++it) { if (it->second.get()) { it->second->updateObj(); //cout<<"update obj ->"<<it->second->m_name<<",level:"<<it->second->m_level<<endl; //cout<<it->second->m_list.size()<<","<<it->second->m_item_list.size()<<endl; json_spirit::Object obj; obj.push_back( Pair("level", it->first) ); obj.push_back( Pair("list", it->second->getArray()) ); m_qq_daily_list.push_back(obj); } } #else //Vip专属礼包 baseLibao* vip_spe = new baseLibao; m_vip_special_libao.reset(vip_spe); vip_spe->m_libao_id = 0; vip_spe->m_type = 0; vip_spe->m_level = 30; vip_spe->m_name = "vip special"; vip_spe->m_memo = ""; vip_spe->m_spic = 0; vip_spe->m_quality = 0; vip_spe->need_slot_num = 0; Item vip_general; vip_general.type = item_type_general; vip_general.id = 999; vip_general.spic = 999; vip_general.nums = 1; vip_spe->m_list.push_back(vip_general); //VIP每日礼包 q.get_result("select vip,itemType,itemId,counts from base_vip_daily_libao where 1 order by vip,id"); CHECK_DB_ERR(q); while (q.fetch_row()) { int level = q.getval(); //cout<<"qq yellow daily libao level "<<level<<endl; baseLibao* lb = NULL; lb = getVipDailyLibao(level); if (NULL == lb) { //cout<<"add qq year daily libao"<<endl; boost::shared_ptr<baseLibao> splb(new baseLibao); m_vip_daily_libao[level] = splb; lb = splb.get(); lb->m_libao_id = 0; lb->m_type = 0; lb->m_level = level; lb->m_name = "vip daily"; lb->m_memo = ""; lb->m_spic = 0; lb->m_quality = 0; lb->need_slot_num = 0; } if (lb) { Item it; it.type = q.getval(); it.id = q.getval(); it.nums = q.getval(); lb->m_list.push_back(it); //cout<<"add qq year daily libao, add item "<<it.type<<","<<it.id<<","<<it.nums<<endl; } } q.free_result(); //VIP周福利 m_vip_week_libao_org_gold = 0; m_vip_week_libao_gold = 0; q.get_result("select vip,type,count,discount from base_vip_week_benefit where 1 order by vip,id"); while (q.fetch_row()) { int vip = q.getval(); if (vip == 0) { Item item; item.type = item_type_treasure; item.id = q.getval(); item.nums = q.getval(); if (item.nums < 0 || item.nums > 10000) { ERR(); continue; } int discount = q.getval(); if (discount <= 0) { ERR(); continue; } baseLibao* lb = NULL; lb = getVipWeekLibao(); if (NULL == lb) { //cout<<"add qq year daily libao"<<endl; boost::shared_ptr<baseLibao> splb(new baseLibao); m_vip_week_libao = splb; lb = splb.get(); lb->m_libao_id = 0; lb->m_type = 0; lb->m_level = 0; lb->m_name = "vip week"; lb->m_memo = ""; lb->m_spic = 0; lb->m_quality = 0; lb->need_slot_num = 0; } if (lb) { lb->m_list.push_back(item); } boost::shared_ptr<baseTreasure> bt = GeneralDataMgr::getInstance()->GetBaseTreasure(item.id); if (bt.get()) { if (bt->gold_to_buy > 0) { m_vip_week_libao_org_gold += (bt->gold_to_buy * item.nums); if (discount < 100) { m_vip_week_libao_gold += (bt->gold_to_buy * item.nums * discount / 100); } else { m_vip_week_libao_gold += (bt->gold_to_buy * item.nums); } } } } } q.free_result(); if (m_vip_special_libao.get()) { m_vip_special_libao->updateObj(); } if (m_vip_week_libao.get()) { m_vip_week_libao->updateObj(); } m_vip_daily_list.clear(); for (std::map<int, boost::shared_ptr<baseLibao> >::iterator it = m_vip_daily_libao.begin(); it != m_vip_daily_libao.end(); ++it) { if (it->second.get()) { it->second->updateObj(); //cout<<"update obj ->"<<it->second->m_name<<",level:"<<it->second->m_level<<endl; //cout<<it->second->m_list.size()<<","<<it->second->m_item_list.size()<<endl; json_spirit::Object obj; obj.push_back( Pair("level", it->first) ); obj.push_back( Pair("list", it->second->getArray()) ); m_vip_daily_list.push_back(obj); } } #endif } //增加礼包 int libao_mgr::addLibao(CharData* pc, int libao_id) { if (!pc) { return HC_ERROR; } if (pc->m_bag.isFull()) { return HC_ERROR_BAG_FULL; } boost::shared_ptr<iItem> bs; baseLibao* pl = getBaselibao(libao_id); if (!pl) { return HC_ERROR; } int id = newLibaoId(); libao* pb = new libao(id, *pl); bs.reset(pb); if (!bs.get()) { return HC_ERROR; } pc->m_bag.addItem(bs); pb->Save(); json_spirit::Object obj; json_spirit::Object item; item.push_back( Pair("type", item_type_libao) ); item.push_back( Pair("spic", pl->m_spic) ); obj.push_back( Pair("item", item) ); obj.push_back( Pair("cmd", "notify") ); obj.push_back( Pair("s", 200) ); obj.push_back( Pair("type", notify_msg_new_get) ); pc->sendObj(obj); return HC_SUCCESS; } #ifdef QQ_PLAT baseLibao* libao_mgr::getQQLevelLibao(int level) { if (m_qq_levelLibaos.find(level) != m_qq_levelLibaos.end()) { return m_qq_levelLibaos[level].get(); } else { return NULL; } } //是否已经领取全部qq成长礼包 bool libao_mgr::allGetQQLevelLibao(CharData* pc) { if (!pc) { return false; } for (std::map<int, boost::shared_ptr<baseLibao> >::iterator it = m_qq_levelLibaos.begin(); it != m_qq_levelLibaos.end(); ++it) { if (pc->queryExtraData(char_data_type_normal, char_data_qq_yellow_level_libao + it->first)) { } else { return false; } } return true; } baseLibao* libao_mgr::getQQDailyLibao(int yellow_level) { if (m_qq_daily_libao.find(yellow_level) != m_qq_daily_libao.end()) { return m_qq_daily_libao[yellow_level].get(); } else { return NULL; } } void libao_mgr::getQQDailyList(CharData& cdata, json_spirit::Array& list, json_spirit::Array& list2) { if (m_qq_year_daily_libao.get()) { m_qq_year_daily_libao->getArray(cdata, list2); } for (std::map<int, boost::shared_ptr<baseLibao> >::iterator it = m_qq_daily_libao.begin(); it != m_qq_daily_libao.end(); ++it) { if (it->second.get()) { json_spirit::Object obj; obj.push_back( Pair("level", it->first) ); json_spirit::Array list1; it->second->getArray(cdata, list1); obj.push_back( Pair("list", list1) ); list.push_back(list1); } } } baseLibao* libao_mgr::getQQYearDailyLibao() { return m_qq_year_daily_libao.get(); } baseLibao* libao_mgr::getQQNewbieLibao() { return m_qq_newbie_libao.get(); } baseLibao* libao_mgr::getQQSpecialLibao() { return m_qq_special_libao.get(); } void libao_mgr::getCharQQLevelLibao(CharData& cdata, json_spirit::Array& list) { for (std::map<int, boost::shared_ptr<baseLibao> >::iterator it = m_qq_levelLibaos.begin(); it != m_qq_levelLibaos.end(); ++it) { if (it->second.get()) { json_spirit::Object obj; if (cdata.m_qq_yellow_level > 0 && cdata.m_level >= it->first) { int get = cdata.queryExtraData(char_data_type_normal, it->first + char_data_qq_yellow_level_libao); if (get == 0) { obj.push_back( Pair("canGet", 1) ); } else { continue; } } obj.push_back( Pair("level", it->first) ); obj.push_back( Pair("list", it->second->getArray()) ); list.push_back(obj); } } } #else baseLibao* libao_mgr::getVipDailyLibao(int vip) { if (m_vip_daily_libao.find(vip) != m_vip_daily_libao.end()) { return m_vip_daily_libao[vip].get(); } else { return NULL; } } baseLibao* libao_mgr::getVipWeekLibao() { return m_vip_week_libao.get(); } baseLibao* libao_mgr::getVipSpecialLibao() { return m_vip_special_libao.get(); } #endif int libao_mgr::getChengzhangLibao(int pos) { if (pos > 0 && pos <= m_chengzhang_Libaos.size()) { return m_chengzhang_Libaos[pos-1]; } else { return 0; } } int libao_mgr::isChengzhangLibao(int id) { for (int i = 0; i <= m_chengzhang_Libaos.size(); ++i) { if (m_chengzhang_Libaos[i] == id) { return i+1; } } return 0; } int libao_mgr::getChengzhangState(CharData& cdata) { while (cdata.m_chengzhang_reward.size() < m_chengzhang_Libaos.size()) cdata.m_chengzhang_reward.push_back(0); for (int i = 0; i <= m_chengzhang_Libaos.size(); ++i) { if (cdata.m_chengzhang_reward[i] == 2) { continue; } else if (cdata.m_chengzhang_reward[i] == 1) { int libao_id = libao_mgr::getInstance()->getChengzhangLibao(i+1); if (cdata.m_bag.getChengzhangLibaoSlot(libao_id) == 0) continue; return i+1; } else if (cdata.m_chengzhang_reward[i] == 0) { int libao_id = libao_mgr::getInstance()->getChengzhangLibao(i+1); if (cdata.m_bag.getChengzhangLibaoSlot(libao_id) == 0) continue; baseLibao* p = NULL; p = libao_mgr::getInstance()->getBaselibao(libao_id); if (p == NULL) { continue; } if (cdata.m_level >= p->m_level && cdata.getAttack() >= p->m_attack && cdata.m_currentStronghold >= p->m_stronghold) { cdata.m_chengzhang_reward[i] = 1; InsertSaveDb("replace into char_chengzhang_event (cid,pos,state) values (" + LEX_CAST_STR(cdata.m_id) + ","+ LEX_CAST_STR(i+1) + "," + LEX_CAST_STR(cdata.m_chengzhang_reward[i]) + ")"); return i+1; } } } return 0; } //打开礼包 int CharData::openLibao(int slot, json_spirit::Object& robj, bool real_get) { boost::shared_ptr<iItem> itm = m_bag.getItem(slot); if (!itm.get()) { return HC_ERROR; } if (itm->getType() != iItem_type_libao) { return HC_ERROR; } libao* pl = dynamic_cast<libao*>(itm.get()); //成长礼包特殊处理,打开界面 int chengzhang_pos = libao_mgr::getInstance()->isChengzhangLibao(pl->m_base.m_libao_id); if (chengzhang_pos > 0 && !real_get) { robj.push_back( Pair("ischengzhang", 1) ); return getChengzhangLibaoInfo(chengzhang_pos,robj); } int need_slot_num = pl->m_base.need_slot_num; std::list<Item>::iterator it = pl->m_base.m_list.begin(); while (it != pl->m_base.m_list.end()) { if (it->type == item_type_baoshi) { if (it->fac == 0) it->fac = 1; newBaoshi* p = m_bag.getBaoshiCanMerge(it->id, it->fac, 1); if (p) { --need_slot_num; } } else if (it->type == item_type_treasure) { boost::shared_ptr<baseTreasure> tr = GeneralDataMgr::getInstance()->GetBaseTreasure(it->id); if (tr.get() && tr->currency == 0) { int32_t max_c = tr->max_size; if (max_c > 1 || 0 == max_c) { for (size_t i = 0; i < m_bag.m_size && it->nums > 0; ++i) { iItem* p = m_bag.m_bagslot[i].get(); if (p && p->getType() == iItem_type_gem && p->getSubtype() == it->id) { int32_t c = p->getCount(); if (0 == max_c || (c + it->nums) <= max_c) { --need_slot_num; break; } } } } } } ++it; } if (need_slot_num > 0 && (m_bag.size()-m_bag.getUsed()) < need_slot_num) { return HC_ERROR_NOT_ENOUGH_BAG_SIZE; } //打开礼包任务 updateTask(task_open_libao, pl->m_base.m_libao_id); std::list<Item> items = pl->m_base.m_list; giveLoots(this, items, 0, m_level, 0, NULL, &robj, true, give_libao_loot); m_bag.removeItem(slot); itm->Clear(); itm->Save(); robj.push_back( Pair("refresh", 1) ); robj.push_back( Pair("ischengzhang", 0) ); return HC_SUCCESS; } //直接奖励礼包 int CharData::rewardLibao(int libao_id, json_spirit::Object& robj) { baseLibao* p = NULL; p = libao_mgr::getInstance()->getBaselibao(libao_id); if (p == NULL) { return HC_ERROR; } if ((m_bag.size()-m_bag.getUsed()) < p->need_slot_num) { return HC_ERROR_NOT_ENOUGH_BAG_SIZE; } //给东西 std::list<Item> items = p->m_list; giveLoots(this, items, 0, m_level, 0, NULL, &robj, true, give_libao_loot); return HC_SUCCESS; } int CharData::getLibaoInfo(int libao_id, json_spirit::Object& robj) { baseLibao* p = NULL; p = libao_mgr::getInstance()->getBaselibao(libao_id); if (p == NULL) { return HC_ERROR; } robj.push_back( Pair("libaoVO", p->getObj()) ); return HC_SUCCESS; } int CharData::getChengzhangLibaoInfo(int pos, json_spirit::Object& robj) { int libao_id = libao_mgr::getInstance()->getChengzhangLibao(pos); baseLibao* p = NULL; p = libao_mgr::getInstance()->getBaselibao(libao_id); if (p == NULL) { return HC_ERROR; } robj.push_back( Pair("state", m_chengzhang_reward[pos-1]) ); p->getObj(robj); robj.push_back( Pair("pos", pos) ); robj.push_back( Pair("list", p->getArray()) ); return HC_SUCCESS; } #ifdef QQ_PLAT //查询黄钻界面:cmd:getYellowEvent int ProcessQueryQQYellowEvent(net::session_ptr& psession, json_spirit::mObject& o, json_spirit::Object& robj) { boost::shared_ptr<CharData> cdata; int ret = getSessionChar(psession, cdata); if (ret != HC_SUCCESS || !cdata.get()) { return ret; } robj.push_back( Pair("vip_is_year_yellow", cdata->m_qq_yellow_year) ); robj.push_back( Pair("vip_yellow_level", cdata->m_qq_yellow_level) ); robj.push_back( Pair("generalGet", cdata->queryExtraData(char_data_type_normal, char_data_qq_yellow_special) ) ); robj.push_back( Pair("newbieGet", cdata->queryExtraData(char_data_type_normal, char_data_qq_yellow_newbie) ) ); robj.push_back( Pair("levelGet", libao_mgr::getInstance()->allGetQQLevelLibao(cdata.get()) ? 1 : 0)); return ret; } //查询黄钻新手礼包 cmd:queryQQnewbieLibao int ProcessQueryQQNewbieLibao(net::session_ptr& psession, json_spirit::mObject& o, json_spirit::Object& robj) { boost::shared_ptr<CharData> cdata; int ret = getSessionChar(psession, cdata); if (ret != HC_SUCCESS || !cdata.get()) { return ret; } robj.push_back( Pair("vip_is_year_yellow", cdata->m_qq_yellow_year) ); robj.push_back( Pair("vip_yellow_level", cdata->m_qq_yellow_level) ); if (cdata->m_qq_yellow_level > 0) { int get = cdata->queryExtraData(char_data_type_normal, char_data_qq_yellow_newbie); robj.push_back( Pair("get", get)); } baseLibao* lb = libao_mgr::getInstance()->getQQNewbieLibao(); if (lb) { robj.push_back( Pair("list", lb->getArray()) ); } return ret; } //查询黄钻每日礼包 cmd:queryQQDailyLibao int ProcessQueryQQDailyLibao(net::session_ptr& psession, json_spirit::mObject& o, json_spirit::Object& robj) { boost::shared_ptr<CharData> cdata; int ret = getSessionChar(psession, cdata); if (ret != HC_SUCCESS || !cdata.get()) { return ret; } robj.push_back( Pair("vip_is_year_yellow", cdata->m_qq_yellow_year) ); robj.push_back( Pair("vip_yellow_level", cdata->m_qq_yellow_level) ); robj.push_back( Pair("get", cdata->queryExtraData(char_data_type_daily, char_data_daily_qq_yellow_libao))); robj.push_back( Pair("yearGet", cdata->queryExtraData(char_data_type_daily, char_data_daily_qq_year_yellow_libao))); //json_spirit::Array list1, list2; //libao_mgr::getInstance()->getQQDailyList(*cdata.get(), list1, list2); robj.push_back( Pair("list", libao_mgr::getInstance()->getQQDailyList()) ); baseLibao* lb = libao_mgr::getInstance()->getQQYearDailyLibao(); if (lb) { robj.push_back( Pair("list2", lb->getArray()) ); } return ret; } //查询黄钻成长礼包 cmd:queryQQLevelLibao int ProcessQueryQQLevelLibao(net::session_ptr& psession, json_spirit::mObject& o, json_spirit::Object& robj) { boost::shared_ptr<CharData> cdata; int ret = getSessionChar(psession, cdata); if (ret != HC_SUCCESS || !cdata.get()) { return ret; } robj.push_back( Pair("vip_is_year_yellow", cdata->m_qq_yellow_year) ); robj.push_back( Pair("vip_yellow_level", cdata->m_qq_yellow_level) ); json_spirit::Array list; libao_mgr::getInstance()->getCharQQLevelLibao(*(cdata.get()), list); robj.push_back( Pair("list", list) ); return ret; } #else //查询VIP每日礼包 cmd:queryVipDailyLibao int ProcessQueryVipDailyLibao(net::session_ptr& psession, json_spirit::mObject& o, json_spirit::Object& robj) { boost::shared_ptr<CharData> cdata; int ret = getSessionChar(psession, cdata); if (ret != HC_SUCCESS || !cdata.get()) { return ret; } robj.push_back( Pair("vip", cdata->m_vip) ); robj.push_back( Pair("get", cdata->queryExtraData(char_data_type_daily, char_data_daily_vip_libao))); robj.push_back( Pair("weekGet", cdata->queryExtraData(char_data_type_week, char_data_week_vip_libao))); //json_spirit::Array list1, list2; //libao_mgr::getInstance()->getQQDailyList(*cdata.get(), list1, list2); robj.push_back( Pair("list", libao_mgr::getInstance()->getVipDailyList()) ); baseLibao* lb = libao_mgr::getInstance()->getVipWeekLibao(); if (lb) { robj.push_back( Pair("list2", lb->getArray()) ); robj.push_back( Pair("orgGold", libao_mgr::getInstance()->vipWeekOrgGold()) ); robj.push_back( Pair("gold", libao_mgr::getInstance()->vipWeekGold()) ); } return ret; } #endif //查询VIP特权界面:cmd:getVipBenefit int ProcessQueryVipEvent(net::session_ptr& psession, json_spirit::mObject& o, json_spirit::Object& robj) { boost::shared_ptr<CharData> cdata; int ret = getSessionChar(psession, cdata); if (ret != HC_SUCCESS || !cdata.get()) { return ret; } robj.push_back( Pair("vip", cdata->m_vip) ); int first_view = cdata->queryExtraData(char_data_type_daily, char_data_daily_view_vip_benefit); if (0 == first_view) { //每日第一次闪亮 cdata->setExtraData(char_data_type_daily, char_data_daily_view_vip_benefit, 1); } int vip8_general_state = cdata->queryExtraData(char_data_type_normal, char_data_vip8_general); int vip10_general_state = cdata->queryExtraData(char_data_type_normal, char_data_vip10_general); robj.push_back( Pair("generalGet2", vip8_general_state ) ); robj.push_back( Pair("generalGet3", vip10_general_state ) ); #ifdef QQ_PLAT int vip_general_state = cdata->queryExtraData(char_data_type_normal, char_data_qq_yellow_special); #else int vip_general_state = cdata->queryExtraData(char_data_type_normal, char_data_vip_special_libao); #endif robj.push_back( Pair("generalGet", vip_general_state ) ); //vipGet:1 VIP礼包已经全部领取 int state = 2; std::map<int,CharVIPPresent>::iterator it = cdata->m_vip_present.begin(); while (it != cdata->m_vip_present.end()) { CharVIPPresent cvp = it->second; if (cvp.present.get()) { if (cvp.state == 1) { state = 1; break; } else if (state == 2) { state = 0; } break; } ++it; } robj.push_back( Pair("vipGet", state == 2 ? 1 : 0) ); int cur = 3; if (vip_general_state == 0 && cdata->m_vip >= 5 && cdata->m_level >= 30) { cur = 1; } else if (vip8_general_state == 0 && cdata->m_vip >= 8 && cdata->m_level >= 40) { cur = 4; } else if (vip10_general_state == 0 && cdata->m_vip >= 10 && cdata->m_level >= 70) { cur = 5; } else if (1 == state) { cur = 2; } #ifndef QQ_PLAT else if (cdata->m_vip > 0) { int vip_daily_get = cdata->queryExtraData(char_data_type_daily, char_data_daily_vip_libao); int vip_week_get = cdata->queryExtraData(char_data_type_week, char_data_week_vip_libao); if (vip_daily_get == 0 || vip_week_get == 0) { cur = 3; } else { cur = 2; } } else { cur = 2; } #else else { cur = 2; } #endif //cur:1武将,2VIP礼包,3VIP每日礼包,4专属橙将,5专属红将 robj.push_back( Pair("cur", cur) ); if (first_view == 0) { int state = cdata->getVipState(); if (0 == state) { cdata->notifyEventState(top_level_event_vip_present, 0, 0); } } return ret; }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
e5cdbe6b63b74c7c8c203383b35d8dff00663e88
42f6627b78e2e0ef7c83fbae91bdb88d64cecf71
/src/rpcdump.cpp
0e9540b7feb8f5480c3f33aed7e4d951a7d54d14
[ "MIT" ]
permissive
bear61/nanucoin
b87715896e60a6cf39842c8bed11a935162844d4
2b47d5274a101b747077912cf9039006f16b0724
refs/heads/master
2020-03-28T16:16:04.421293
2018-08-25T16:38:40
2018-08-25T16:38:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,890
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2017-2018 The NanuCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "init.h" #include "main.h" #include "rpcserver.h" #include "script/script.h" #include "script/standard.h" #include "sync.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "wallet.h" #include <fstream> #include <secp256k1.h> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <openssl/aes.h> #include <openssl/sha.h> #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string& str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string& str) { std::stringstream ret; BOOST_FOREACH (unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string& str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos + 2 < str.length()) { c = (((str[pos + 1] >> 6) * 9 + ((str[pos + 1] - '0') & 15)) << 4) | ((str[pos + 2] >> 6) * 9 + ((str[pos + 2] - '0') & 15)); pos += 2; } ret << c; } return ret.str(); } Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"nanucoinprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"nanucoinprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return Value::null; } Value importaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importaddress \"address\" ( \"label\" rescan )\n" "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nArguments:\n" "1. \"address\" (string, required) The address\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false")); CScript script; CBitcoinAddress address(params[0].get_str()); if (address.IsValid()) { script = GetScriptForDestination(address.Get()); } else if (IsHex(params[0].get_str())) { std::vector<unsigned char> data(ParseHex(params[0].get_str())); script = CScript(data.begin(), data.end()); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NanuCoin address or script"); } string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); { if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); // add to address book or update label if (address.IsValid()) pwalletMain->SetAddressBook(address.Get(), strLabel, "receive"); // Don't throw error in case an address is already there if (pwalletMain->HaveWatchOnly(script)) return Value::null; pwalletMain->MarkDirty(); if (!pwalletMain->AddWatchOnly(script)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"")); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->GetBlockTime(); bool fGood = true; int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI while (file.good()) { pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100)))); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI CBlockIndex* pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"nanucoinaddress\"\n" "\nReveals the private key corresponding to 'nanucoinaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"nanucoinaddress\" (string, required) The nanucoin address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"")); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NanuCoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"")); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by NanuCoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime())); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID& keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } Value bip38encrypt(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38encrypt \"nanucoinaddress\"\n" "\nEncrypts a private key corresponding to 'nanucoinaddress'.\n" "\nArguments:\n" "1. \"nanucoinaddress\" (string, required) The nanucoin address for the private key (you must hold the key already)\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with - Valid special chars: !#$%&'()*+,-./:;<=>?`{|}~ \n" "\nResult:\n" "\"key\" (string) The encrypted private key\n" "\nExamples:\n"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strPassphrase = params[1].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NanuCoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); uint256 privKey = vchSecret.GetPrivKey_256(); string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey); Object result; result.push_back(Pair("Addess", strAddress)); result.push_back(Pair("Encrypted Key", encryptedOut)); return result; } Value bip38decrypt(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38decrypt \"nanucoinaddress\"\n" "\nDecrypts and then imports password protected private key.\n" "\nArguments:\n" "1. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with\n" "2. \"encryptedkey\" (string, required) The encrypted private key\n" "\nResult:\n" "\"key\" (string) The decrypted private key\n" "\nExamples:\n"); EnsureWalletIsUnlocked(); /** Collect private key and passphrase **/ string strPassphrase = params[0].get_str(); string strKey = params[1].get_str(); uint256 privKey; bool fCompressed; if (!BIP38_Decrypt(strPassphrase, strKey, privKey, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Failed To Decrypt"); Object result; result.push_back(Pair("privatekey", HexStr(privKey))); CKey key; key.Set(privKey.begin(), privKey.end(), fCompressed); if (!key.IsValid()) throw JSONRPCError(RPC_WALLET_ERROR, "Private Key Not Valid"); CPubKey pubkey = key.GetPubKey(); pubkey.IsCompressed(); assert(key.VerifyPubKey(pubkey)); result.push_back(Pair("Address", CBitcoinAddress(pubkey.GetID()).ToString())); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, "", "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) throw JSONRPCError(RPC_WALLET_ERROR, "Key already held by wallet"); pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } return result; }
[ "rodrigo@depeder.com.br" ]
rodrigo@depeder.com.br
a17409c46e583c54a70fea7844a70d613f3c5897
e5d42cf7482c2547b86b6f4595de02fb45c1ee65
/PowerControl/CPowerGPIBDev.h
cb0b44dc303b46effb1ad95f7ecb58784b6448ea
[]
no_license
oORogerOo/ControlPower
f212b86240460d15a08ccb979f0a100d368365fa
676548be2b97c4724a2a1412da35daf48e051c45
refs/heads/master
2021-01-19T18:21:30.928279
2017-08-23T03:14:42
2017-08-23T03:14:42
101,126,403
0
0
null
null
null
null
GB18030
C++
false
false
4,915
h
// 从类型库向导中用“添加类”创建的计算机生成的 IDispatch 包装器类 #ifdef _WIN64 #import "C:\\Program Files (x86)\\Common Files\\Huaqin\\Power.dll" no_namespace #else #import "C:\\Program Files\\Common Files\\Huaqin\\Power.dll" no_namespace #endif // CPowerGPIBDev 包装器类 class CPowerGPIBDev : public COleDispatchDriver { public: CPowerGPIBDev(){} // 调用 COleDispatchDriver 默认构造函数 CPowerGPIBDev(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CPowerGPIBDev(const CPowerGPIBDev& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // 特性 public: // 操作 public: // IPowerGPIBDev 方法 public: BOOL PowerOn() { BOOL result; InvokeHelper(0x1, DISPATCH_METHOD, VT_BOOL, (void*)&result, NULL); return result; } BOOL PowerOff() { BOOL result; InvokeHelper(0x2, DISPATCH_METHOD, VT_BOOL, (void*)&result, NULL); return result; } long Open() { long result; InvokeHelper(0x3, DISPATCH_METHOD, VT_I4, (void*)&result, NULL); return result; } BOOL Close() { BOOL result; InvokeHelper(0x4, DISPATCH_METHOD, VT_BOOL, (void*)&result, NULL); return result; } BOOL SetCurr(double fCurrent) { BOOL result; static BYTE parms[] = VTS_R8; InvokeHelper(0x5, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, fCurrent); return result; } double GetCurr() { double result; InvokeHelper(0x6, DISPATCH_METHOD, VT_R8, (void*)&result, NULL); return result; } BOOL SetVolt(double fVolt) { BOOL result; static BYTE parms[] = VTS_R8; InvokeHelper(0x7, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, fVolt); return result; } double GetVolt() { double result; InvokeHelper(0x8, DISPATCH_METHOD, VT_R8, (void*)&result, NULL); return result; } CString GetSupportType() { CString result; InvokeHelper(0x9, DISPATCH_METHOD, VT_BSTR, (void*)&result, NULL); return result; } long GetGPIBLastError() { long result; InvokeHelper(0xe, DISPATCH_METHOD, VT_I4, (void*)&result, NULL); return result; } void SysSleep() { InvokeHelper(0xf, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void ReSet() { InvokeHelper(0x10, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void GPIBWrite(LPCTSTR GPIBCMD) { static BYTE parms[] = VTS_BSTR; InvokeHelper(0x16, DISPATCH_METHOD, VT_EMPTY, NULL, parms, GPIBCMD); } CString GPIBRead(long strLen) { CString result; static BYTE parms[] = VTS_I4; InvokeHelper(0x17, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, strLen); return result; } long SetArrTest(double iInterval, long iPoints) { long result; static BYTE parms[] = VTS_R8 VTS_I4; InvokeHelper(0x18, DISPATCH_METHOD, VT_I4, (void*)&result, parms, iInterval, iPoints); return result; } CString GetArrVolt() { CString result; InvokeHelper(0x19, DISPATCH_METHOD, VT_BSTR, (void*)&result, NULL); return result; } CString GetArrCurr() { CString result; InvokeHelper(0x1a, DISPATCH_METHOD, VT_BSTR, (void*)&result, NULL); return result; } long SetCurrRange(long RangeFlag) { long result; static BYTE parms[] = VTS_I4; InvokeHelper(0x1b, DISPATCH_METHOD, VT_I4, (void*)&result, parms, RangeFlag); return result; } // IPowerGPIBDev 属性 public: CString GetDeviceName() { CString result; GetProperty(0xa, VT_BSTR, (void*)&result); return result; } void SetDeviceName(CString propVal) { SetProperty(0xa, VT_BSTR, propVal); } CString GetDevicePort() { CString result; GetProperty(0xb, VT_BSTR, (void*)&result); return result; } void SetDevicePort(CString propVal) { SetProperty(0xb, VT_BSTR, propVal); } CString GetGPIBBoard() { CString result; GetProperty(0xc, VT_BSTR, (void*)&result); return result; } void SetGPIBBoard(CString propVal) { SetProperty(0xc, VT_BSTR, propVal); } CString GetGPIBAddress() { CString result; GetProperty(0xd, VT_BSTR, (void*)&result); return result; } void SetGPIBAddress(CString propVal) { SetProperty(0xd, VT_BSTR, propVal); } CString GetViRsrcName() { CString result; GetProperty(0x11, VT_BSTR, (void*)&result); return result; } void SetViRsrcName(CString propVal) { SetProperty(0x11, VT_BSTR, propVal); } long GetMAXVolt() { long result; GetProperty(0x12, VT_I4, (void*)&result); return result; } void SetMAXVolt(long propVal) { SetProperty(0x12, VT_I4, propVal); } CString GetVersion() { CString result; GetProperty(0x13, VT_BSTR, (void*)&result); return result; } void SetVersion(CString propVal) { SetProperty(0x13, VT_BSTR, propVal); } long GetErrorCode() { long result; GetProperty(0x14, VT_I4, (void*)&result); return result; } void SetErrorCode(long propVal) { SetProperty(0x14, VT_I4, propVal); } CString GetDeviceIDN() { CString result; GetProperty(0x15, VT_BSTR, (void*)&result); return result; } void SetDeviceIDN(CString propVal) { SetProperty(0x15, VT_BSTR, propVal); } };
[ "30460793+oORogerOo@users.noreply.github.com" ]
30460793+oORogerOo@users.noreply.github.com
21e377bcc869e7646e16df6f4feb420ea56010c0
b7c15957cd665dcf2777b79d8580197d82a944ab
/lib/VM/Callable.cpp
fa428e32652d399543fd4b96995a31fbc48cea8d
[ "MIT" ]
permissive
HiVie/hermes
afc4203c35452b9f578d48d86cee753f7f515a2a
9cf705779d2e65e4dd3a23d2cf572fc08c53bee2
refs/heads/master
2020-12-01T05:51:11.575397
2019-12-27T23:43:41
2019-12-27T23:45:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
56,051
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/VM/Callable.h" #include "hermes/VM/ArrayLike.h" #include "hermes/VM/BuildMetadata.h" #include "hermes/VM/JSNativeFunctions.h" #include "hermes/VM/SmallXString.h" #include "hermes/VM/StackFrame-inline.h" #include "hermes/VM/StringPrimitive.h" #include "hermes/VM/StringView.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Debug.h" #define DEBUG_TYPE "serialize" namespace hermes { namespace vm { //===----------------------------------------------------------------------===// // class Environment VTable Environment::vt{CellKind::EnvironmentKind, 0}; void EnvironmentBuildMeta(const GCCell *cell, Metadata::Builder &mb) { const auto *self = static_cast<const Environment *>(cell); mb.addField("parentEnvironment", &self->parentEnvironment_); mb.addArray<Metadata::ArrayData::ArrayType::HermesValue>( self->getSlots(), &self->size_, sizeof(GCHermesValue)); } #ifdef HERMESVM_SERIALIZE void EnvironmentSerialize(Serializer &s, const GCCell *cell) { auto *self = vmcast<const Environment>(cell); s.writeInt<uint32_t>(self->size_); s.writeRelocation(self->parentEnvironment_.get(s.getRuntime())); // Write Trailing GCHermesValue for (uint32_t i = 0; i < self->size_; i++) { s.writeHermesValue(self->getSlots()[i]); } s.endObject(cell); } void EnvironmentDeserialize(Deserializer &d, CellKind kind) { assert(kind == CellKind::EnvironmentKind && "Expected Environment"); uint32_t size = d.readInt<uint32_t>(); void *mem = d.getRuntime()->alloc</*fixedSize*/ false>( Environment::allocationSize(size)); auto *cell = new (mem) Environment(d.getRuntime(), size); d.readRelocation(&cell->parentEnvironment_, RelocationKind::GCPointer); // Update Traling GCHermesValue for (uint32_t i = 0; i < size; i++) { d.readHermesValue(&cell->slot(i)); } d.endObject(cell); } #endif //===----------------------------------------------------------------------===// // class Callable void CallableBuildMeta(const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<Callable>()); ObjectBuildMeta(cell, mb); const auto *self = static_cast<const Callable *>(cell); mb.addField("environment", &self->environment_); } #ifdef HERMESVM_SERIALIZE Callable::Callable(Deserializer &d, const VTable *vt) : JSObject(d, vt) { // JSObject constructor already reads JSObject fields. d.readRelocation(&environment_, RelocationKind::GCPointer); } void serializeCallableImpl( Serializer &s, const GCCell *cell, unsigned overlapSlots) { JSObject::serializeObjectImpl(s, cell, overlapSlots); auto *self = vmcast<const Callable>(cell); s.writeRelocation(self->environment_.get(s.getRuntime())); } #endif std::string Callable::_snapshotNameImpl(GCCell *cell, GC *gc) { auto *const self = reinterpret_cast<Callable *>(cell); return self->getNameIfExists(gc->getPointerBase()); } CallResult<HermesValue> Callable::_newObjectImpl( Handle<Callable> /*selfHandle*/, Runtime *runtime, Handle<JSObject> parentHandle) { return JSObject::create(runtime, parentHandle).getHermesValue(); } void Callable::defineLazyProperties(Handle<Callable> fn, Runtime *runtime) { // lazy functions can be Bound or JS Functions. if (auto jsFun = Handle<JSFunction>::dyn_vmcast(fn)) { const CodeBlock *codeBlock = jsFun->getCodeBlock(); // Create empty object for prototype. auto prototypeParent = vmisa<JSGeneratorFunction>(*jsFun) ? Handle<JSObject>::vmcast(&runtime->generatorPrototype) : Handle<JSObject>::vmcast(&runtime->objectPrototype); auto prototypeObjectHandle = toHandle(runtime, JSObject::create(runtime, prototypeParent)); auto cr = Callable::defineNameLengthAndPrototype( fn, runtime, codeBlock->getNameMayAllocate(), codeBlock->getParamCount() - 1, prototypeObjectHandle, Callable::WritablePrototype::Yes, codeBlock->isStrictMode()); assert( cr != ExecutionStatus::EXCEPTION && "failed to define length and name"); (void)cr; } else if (vmisa<BoundFunction>(fn.get())) { Handle<BoundFunction> boundfn = Handle<BoundFunction>::vmcast(fn); Handle<Callable> target = runtime->makeHandle(boundfn->getTarget(runtime)); unsigned int argsWithThis = boundfn->getArgCountWithThis(runtime); auto res = BoundFunction::initializeLengthAndName( boundfn, runtime, target, argsWithThis == 0 ? 0 : argsWithThis - 1); assert( res != ExecutionStatus::EXCEPTION && "failed to define length and name of bound function"); (void)res; } else { // no other kind of function can be lazy currently assert(false && "invalid lazy function"); } } ExecutionStatus Callable::defineNameLengthAndPrototype( Handle<Callable> selfHandle, Runtime *runtime, SymbolID name, unsigned paramCount, Handle<JSObject> prototypeObjectHandle, WritablePrototype writablePrototype, bool strictMode) { PropertyFlags pf; pf.clear(); pf.enumerable = 0; pf.writable = 0; pf.configurable = 1; GCScope scope{runtime, "defineNameLengthAndPrototype"}; namespace P = Predefined; /// Adds a property to the object in \p OBJ_HANDLE. \p SYMBOL provides its name /// as a \c Predefined enum value, and its value is rooted in \p HANDLE. If /// property definition fails, the exceptional execution status will be /// propogated to the outer function. #define DEFINE_PROP(OBJ_HANDLE, SYMBOL, HANDLE) \ do { \ auto status = JSObject::defineNewOwnProperty( \ OBJ_HANDLE, runtime, Predefined::getSymbolID(SYMBOL), pf, HANDLE); \ if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { \ return ExecutionStatus::EXCEPTION; \ } \ } while (false) // Define the name. auto nameHandle = name.isValid() ? runtime->makeHandle(runtime->getStringPrimFromSymbolID(name)) : runtime->getPredefinedStringHandle(Predefined::emptyString); DEFINE_PROP(selfHandle, P::name, nameHandle); // Length is the number of formal arguments. auto lengthHandle = runtime->makeHandle(HermesValue::encodeDoubleValue(paramCount)); DEFINE_PROP(selfHandle, P::length, lengthHandle); if (strictMode) { // Define .callee and .arguments properties: throw always in strict mode. auto accessor = Handle<PropertyAccessor>::vmcast(&runtime->throwTypeErrorAccessor); pf.clear(); pf.enumerable = 0; pf.configurable = 0; pf.accessor = 1; DEFINE_PROP(selfHandle, P::caller, accessor); DEFINE_PROP(selfHandle, P::arguments, accessor); } if (prototypeObjectHandle) { // Set its 'prototype' property. pf.clear(); pf.enumerable = 0; /// System constructors have read-only prototypes. pf.writable = (uint8_t)writablePrototype; pf.configurable = 0; DEFINE_PROP(selfHandle, P::prototype, prototypeObjectHandle); if (!vmisa<JSGeneratorFunction>(*selfHandle)) { // Set the 'constructor' property in the prototype object. // This must not be set for GeneratorFunctions, because // prototypes must not point back to their constructors. // See the diagram: ES9.0 25.2 (GeneratorFunction objects). pf.clear(); pf.enumerable = 0; pf.writable = 1; pf.configurable = 1; DEFINE_PROP(prototypeObjectHandle, P::constructor, selfHandle); } } return ExecutionStatus::RETURNED; #undef DEFINE_PROP } /// Execute this function with no arguments. This is just a convenience /// helper method; it actually invokes the interpreter recursively. CallResult<HermesValue> Callable::executeCall0( Handle<Callable> selfHandle, Runtime *runtime, Handle<> thisArgHandle, bool construct) { ScopedNativeCallFrame newFrame{runtime, 0, selfHandle.getHermesValue(), construct ? selfHandle.getHermesValue() : HermesValue::encodeUndefinedValue(), *thisArgHandle}; if (LLVM_UNLIKELY(newFrame.overflowed())) return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); return call(selfHandle, runtime); } /// Execute this function with one argument. This is just a convenience /// helper method; it actually invokes the interpreter recursively. CallResult<HermesValue> Callable::executeCall1( Handle<Callable> selfHandle, Runtime *runtime, Handle<> thisArgHandle, HermesValue param1, bool construct) { ScopedNativeCallFrame newFrame{runtime, 1, selfHandle.getHermesValue(), construct ? selfHandle.getHermesValue() : HermesValue::encodeUndefinedValue(), *thisArgHandle}; if (LLVM_UNLIKELY(newFrame.overflowed())) return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); newFrame->getArgRef(0) = param1; return call(selfHandle, runtime); } /// Execute this function with two arguments. This is just a convenience /// helper method; it actually invokes the interpreter recursively. CallResult<HermesValue> Callable::executeCall2( Handle<Callable> selfHandle, Runtime *runtime, Handle<> thisArgHandle, HermesValue param1, HermesValue param2, bool construct) { ScopedNativeCallFrame newFrame{runtime, 2, selfHandle.getHermesValue(), construct ? selfHandle.getHermesValue() : HermesValue::encodeUndefinedValue(), *thisArgHandle}; if (LLVM_UNLIKELY(newFrame.overflowed())) return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); newFrame->getArgRef(0) = param1; newFrame->getArgRef(1) = param2; return call(selfHandle, runtime); } /// Execute this function with three arguments. This is just a convenience /// helper method; it actually invokes the interpreter recursively. CallResult<HermesValue> Callable::executeCall3( Handle<Callable> selfHandle, Runtime *runtime, Handle<> thisArgHandle, HermesValue param1, HermesValue param2, HermesValue param3, bool construct) { ScopedNativeCallFrame newFrame{runtime, 3, selfHandle.getHermesValue(), construct ? selfHandle.getHermesValue() : HermesValue::encodeUndefinedValue(), *thisArgHandle}; if (LLVM_UNLIKELY(newFrame.overflowed())) return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); newFrame->getArgRef(0) = param1; newFrame->getArgRef(1) = param2; newFrame->getArgRef(2) = param3; return call(selfHandle, runtime); } /// Execute this function with four arguments. This is just a convenience /// helper method; it actually invokes the interpreter recursively. CallResult<HermesValue> Callable::executeCall4( Handle<Callable> selfHandle, Runtime *runtime, Handle<> thisArgHandle, HermesValue param1, HermesValue param2, HermesValue param3, HermesValue param4, bool construct) { ScopedNativeCallFrame newFrame{runtime, 4, selfHandle.getHermesValue(), construct ? selfHandle.getHermesValue() : HermesValue::encodeUndefinedValue(), *thisArgHandle}; if (LLVM_UNLIKELY(newFrame.overflowed())) return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); newFrame->getArgRef(0) = param1; newFrame->getArgRef(1) = param2; newFrame->getArgRef(2) = param3; newFrame->getArgRef(3) = param4; return call(selfHandle, runtime); } CallResult<HermesValue> Callable::executeCall( Handle<Callable> selfHandle, Runtime *runtime, Handle<> newTarget, Handle<> thisArgument, Handle<JSObject> arrayLike) { CallResult<uint64_t> nRes = getArrayLikeLength(arrayLike, runtime); if (LLVM_UNLIKELY(nRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (*nRes > UINT32_MAX) { runtime->raiseRangeError("Too many arguments for apply"); } uint32_t n = static_cast<uint32_t>(*nRes); ScopedNativeCallFrame newFrame{ runtime, n, selfHandle.getHermesValue(), *newTarget, *thisArgument}; if (LLVM_UNLIKELY(newFrame.overflowed())) return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); // Initialize the arguments to undefined because we might allocate and cause // a gc while populating them. // TODO: look into doing this lazily. newFrame.fillArguments(n, HermesValue::encodeUndefinedValue()); if (LLVM_UNLIKELY( createListFromArrayLike( arrayLike, runtime, n, [&newFrame](Runtime *, uint64_t index, PseudoHandle<> value) { newFrame->getArgRef(index) = value.getHermesValue(); return ExecutionStatus::RETURNED; }) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return Callable::call(selfHandle, runtime); } CallResult<HermesValue> Callable::executeConstruct0( Handle<Callable> selfHandle, Runtime *runtime) { auto thisVal = Callable::createThisForConstruct(selfHandle, runtime); if (LLVM_UNLIKELY(thisVal == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto thisValHandle = runtime->makeHandle<JSObject>(*thisVal); auto result = executeCall0(selfHandle, runtime, thisValHandle, true); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return result->isObject() ? result : thisValHandle.getHermesValue(); } CallResult<HermesValue> Callable::executeConstruct1( Handle<Callable> selfHandle, Runtime *runtime, Handle<> param1) { auto thisVal = Callable::createThisForConstruct(selfHandle, runtime); if (LLVM_UNLIKELY(thisVal == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto thisValHandle = runtime->makeHandle<JSObject>(*thisVal); auto result = executeCall1(selfHandle, runtime, thisValHandle, *param1, true); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return result->isObject() ? result : thisValHandle.getHermesValue(); } CallResult<HermesValue> Callable::createThisForConstruct( Handle<Callable> selfHandle, Runtime *runtime) { auto prototypeProp = JSObject::getNamed_RJS( selfHandle, runtime, Predefined::getSymbolID(Predefined::prototype)); if (LLVM_UNLIKELY(prototypeProp == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } Handle<JSObject> prototype = vmisa<JSObject>(*prototypeProp) ? runtime->makeHandle<JSObject>(*prototypeProp) : Handle<JSObject>::vmcast(&runtime->objectPrototype); return Callable::newObject(selfHandle, runtime, prototype); } CallResult<double> Callable::extractOwnLengthProperty_RJS( Handle<Callable> selfHandle, Runtime *runtime) { NamedPropertyDescriptor desc; if (!JSObject::getOwnNamedDescriptor( selfHandle, runtime, Predefined::getSymbolID(Predefined::length), desc)) { return 0.0; } auto propRes = JSObject::getNamedPropertyValue_RJS( selfHandle, runtime, selfHandle, desc); if (propRes == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } if (!propRes->isNumber()) { return 0.0; } auto intRes = toInteger(runtime, runtime->makeHandle(propRes.getValue())); if (intRes == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return intRes->getNumber(); } //===----------------------------------------------------------------------===// // class BoundFunction CallableVTable BoundFunction::vt{ { VTable( CellKind::BoundFunctionKind, cellSize<BoundFunction>(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, // externalMemorySize VTable::HeapSnapshotMetadata{HeapSnapshot::NodeType::Closure, BoundFunction::_snapshotNameImpl, BoundFunction::_snapshotAddEdgesImpl, nullptr, nullptr}), BoundFunction::_getOwnIndexedRangeImpl, BoundFunction::_haveOwnIndexedImpl, BoundFunction::_getOwnIndexedPropertyFlagsImpl, BoundFunction::_getOwnIndexedImpl, BoundFunction::_setOwnIndexedImpl, BoundFunction::_deleteOwnIndexedImpl, BoundFunction::_checkAllOwnIndexedImpl, }, BoundFunction::_newObjectImpl, BoundFunction::_callImpl}; void BoundFunctionBuildMeta(const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<BoundFunction>()); CallableBuildMeta(cell, mb); const auto *self = static_cast<const BoundFunction *>(cell); mb.addField("target", &self->target_); mb.addField("argStorage", &self->argStorage_); } #ifdef HERMESVM_SERIALIZE BoundFunction::BoundFunction(Deserializer &d) : Callable(d, &vt.base.base) { d.readRelocation(&target_, RelocationKind::GCPointer); if (d.readInt<uint8_t>()) { argStorage_.set( d.getRuntime(), ArrayStorage::deserializeArrayStorage(d), &d.getRuntime()->getHeap()); } } void BoundFunctionSerialize(Serializer &s, const GCCell *cell) { auto *self = vmcast<BoundFunction>(cell); serializeCallableImpl(s, cell, JSObject::numOverlapSlots<BoundFunction>()); s.writeRelocation(self->target_.get(s.getRuntime())); bool hasArray = (bool)self->argStorage_; s.writeInt<uint8_t>(hasArray); if (hasArray) { ArrayStorage::serializeArrayStorage( s, self->argStorage_.get(s.getRuntime())); } s.endObject(cell); } void BoundFunctionDeserialize(Deserializer &d, CellKind kind) { assert(kind == CellKind::BoundFunctionKind && "Expected BoundFunction"); void *mem = d.getRuntime()->alloc(cellSize<BoundFunction>()); void *cell = new (mem) BoundFunction(d); d.endObject(cell); } #endif CallResult<HermesValue> BoundFunction::create( Runtime *runtime, Handle<Callable> target, unsigned argCountWithThis, const PinnedHermesValue *argsWithThis) { unsigned argCount = argCountWithThis > 0 ? argCountWithThis - 1 : 0; auto arrRes = ArrayStorage::create(runtime, argCount + 1); if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto argStorageHandle = runtime->makeHandle<ArrayStorage>(*arrRes); void *mem = runtime->alloc(cellSize<BoundFunction>()); auto selfHandle = runtime->makeHandle(allocateSmallPropStorage(new (mem) BoundFunction( runtime, runtime->functionPrototypeRawPtr, runtime->getHiddenClassForPrototypeRaw( runtime->functionPrototypeRawPtr, numOverlapSlots<BoundFunction>() + ANONYMOUS_PROPERTY_SLOTS), target, argStorageHandle))); // Copy the arguments. If we don't have any, we must at least initialize // 'this' to 'undefined'. MutableHandle<ArrayStorage> handle( runtime, selfHandle->argStorage_.get(runtime)); // In case the storage was trimmed, make sure it has enough capacity. ArrayStorage::ensureCapacity(handle, runtime, argCount + 1); if (argCountWithThis) { for (unsigned i = 0; i != argCountWithThis; ++i) { ArrayStorage::push_back(handle, runtime, Handle<>(&argsWithThis[i])); } } else { // Don't need to worry about resizing since it was created with a capacity // of at least 1. ArrayStorage::push_back(handle, runtime, Runtime::getUndefinedValue()); } // Update the storage pointer in case push_back() needed to reallocate. selfHandle->argStorage_.set(runtime, *handle, &runtime->getHeap()); if (target->isLazy()) { // If the target is lazy we can make the bound function lazy. // If the target is NOT lazy, it might have getter/setters on length that // throws and we also need to throw. selfHandle->flags_.lazyObject = 1; } else { if (initializeLengthAndName(selfHandle, runtime, target, argCount) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } } return selfHandle.getHermesValue(); } ExecutionStatus BoundFunction::initializeLengthAndName( Handle<Callable> selfHandle, Runtime *runtime, Handle<Callable> target, unsigned argCount) { if (LLVM_UNLIKELY(target->isLazy())) { Callable::initializeLazyObject(runtime, target); } // Extract target.length. auto targetLength = Callable::extractOwnLengthProperty_RJS(target, runtime); if (targetLength == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; // Define .length PropertyFlags pf{}; pf.enumerable = 0; pf.writable = 0; pf.configurable = 1; // Length is the number of formal arguments. auto length = runtime->makeHandle(HermesValue::encodeNumberValue( argCount >= *targetLength ? 0.0 : *targetLength - argCount)); if (LLVM_UNLIKELY( JSObject::defineNewOwnProperty( selfHandle, runtime, Predefined::getSymbolID(Predefined::length), pf, length) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // Set the name by prepending "bound ". auto propRes = JSObject::getNamed_RJS( target, runtime, Predefined::getSymbolID(Predefined::name)); if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameHandle = propRes->isString() ? runtime->makeHandle<StringPrimitive>(*propRes) : runtime->getPredefinedStringHandle(Predefined::emptyString); auto nameView = StringPrimitive::createStringView(runtime, nameHandle); llvm::SmallU16String<32> boundName{"bound "}; boundName.append(nameView.begin(), nameView.end()); // Share name strings for repeatedly bound functions by using the // identifier table. If a new symbol is created, it will disappear // after the name string dies, since nothing else refers to it. auto &identifierTable = runtime->getIdentifierTable(); auto boundNameSym = identifierTable.getSymbolHandle(runtime, boundName); if (LLVM_UNLIKELY(boundNameSym == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } Handle<StringPrimitive> boundNameHandle( runtime, identifierTable.getStringPrim(runtime, **boundNameSym)); DefinePropertyFlags dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); dpf.writable = 0; dpf.enumerable = 0; if (LLVM_UNLIKELY( JSObject::defineOwnProperty( selfHandle, runtime, Predefined::getSymbolID(Predefined::name), dpf, boundNameHandle) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // Define .callee and .arguments properties: throw always in bound functions. auto accessor = Handle<PropertyAccessor>::vmcast(&runtime->throwTypeErrorAccessor); pf.clear(); pf.enumerable = 0; pf.configurable = 0; pf.accessor = 1; if (LLVM_UNLIKELY( JSObject::defineNewOwnProperty( selfHandle, runtime, Predefined::getSymbolID(Predefined::caller), pf, accessor) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (LLVM_UNLIKELY( JSObject::defineNewOwnProperty( selfHandle, runtime, Predefined::getSymbolID(Predefined::arguments), pf, accessor) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return ExecutionStatus::RETURNED; } CallResult<HermesValue> BoundFunction::_newObjectImpl( Handle<Callable> selfHandle, Runtime *runtime, Handle<JSObject>) { auto *self = vmcast<BoundFunction>(*selfHandle); // If it is a chain of bound functions, skip directly to the end. while (auto *targetAsBound = dyn_vmcast<BoundFunction>(self->getTarget(runtime))) self = targetAsBound; auto targetHandle = runtime->makeHandle(self->getTarget(runtime)); // We must duplicate the [[Construct]] functionality here. // Obtain "target.prototype". auto propRes = JSObject::getNamed_RJS( targetHandle, runtime, Predefined::getSymbolID(Predefined::prototype)); if (propRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; auto prototype = runtime->makeHandle(*propRes); // If target.prototype is an object, use it, otherwise use the standard // object prototype. return targetHandle->getVT()->newObject( targetHandle, runtime, prototype->isObject() ? Handle<JSObject>::vmcast(prototype) : Handle<JSObject>::vmcast(&runtime->objectPrototype)); } CallResult<HermesValue> BoundFunction::_boundCall( BoundFunction *self, const Inst *ip, Runtime *runtime) { ScopedNativeDepthTracker depthTracker{runtime}; if (LLVM_UNLIKELY(depthTracker.overflowed())) { return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); } CallResult<HermesValue> res{ExecutionStatus::EXCEPTION}; StackFramePtr originalCalleeFrame = StackFramePtr(runtime->getStackPointer()); // Save the original newTarget since we will overwrite it. HermesValue originalNewTarget = originalCalleeFrame.getNewTargetRef(); // Save the original arg count since we will lose it. auto originalArgCount = originalCalleeFrame.getArgCount(); // Keep track of the total arg count. auto totalArgCount = originalArgCount; auto callerFrame = runtime->getCurrentFrame(); // We must preserve the "thisArg" passed to us by the caller because it is in // a register that is not supposed to be modified by a call. Copy it to the // scratch register in the caller's frame. // Note that since there is only one scratch reg, we must process all chained // bound calls in one go (which is more efficient anyway). callerFrame.getScratchRef() = originalCalleeFrame.getThisArgRef(); // Pop the stack down to the first argument, erasing the call frame - we don't // need the call frame since we will build a new one. runtime->popToSavedStackPointer(&originalCalleeFrame->getArgRefUnsafe(0)); // Loop, copying the bound arguments of all chained bound functions. for (;;) { auto boundArgCount = self->getArgCountWithThis(runtime) - 1; totalArgCount += boundArgCount; // Check if we have enough stack for the arguments and the frame metadata. if (LLVM_UNLIKELY(!runtime->checkAvailableStack( StackFrameLayout::callerOutgoingRegisters(boundArgCount)))) { // Oops, we ran out of stack in the middle of calling a bound function. // Restore everything and bail. // We can't "pop" the stack pointer to an arbitrary value, which may be // higher than the current pointer. So, first we pop everything that we // may have pushed, then allocate the correct amount to get back to the // initial state. runtime->popToSavedStackPointer(&originalCalleeFrame->getArgRefUnsafe(0)); runtime->allocUninitializedStack(StackFrameLayout::ThisArg + 1); assert( runtime->getStackPointer() == originalCalleeFrame.ptr() && "Stack wasn't restored properly"); runtime->raiseStackOverflow(Runtime::StackOverflowKind::JSRegisterStack); res = ExecutionStatus::EXCEPTION; goto bail; } // Allocate space only for the arguments for now. auto *stack = runtime->allocUninitializedStack(boundArgCount); // Copy the bound arguments (but not the bound "this"). if (StackFrameLayout::StackIncrement == -1) { std::uninitialized_copy_n( self->getArgsWithThis(runtime) + 1, boundArgCount, stack); } else { std::uninitialized_copy_n( self->getArgsWithThis(runtime) + 1, boundArgCount, llvm::make_reverse_iterator(stack + 1)); } // Loop while the target is another bound function. auto *targetAsBound = dyn_vmcast<BoundFunction>(self->getTarget(runtime)); if (!targetAsBound) break; self = targetAsBound; } // Block scope for non-trivial variables to avoid complaints from "goto". { // Allocate space for "thisArg" and the frame metdata following the outgoing // registers. Note that we already checked earlier that we have enough // stack. static_assert( StackFrameLayout::CallerExtraRegistersAtEnd == StackFrameLayout::ThisArg, "Stack frame layout changed without updating _boundCall"); auto *stack = runtime->allocUninitializedStack(StackFrameLayout::ThisArg + 1); // Initialize the new frame metadata. auto newCalleeFrame = StackFramePtr::initFrame( stack, runtime->getCurrentFrame(), ip, nullptr, totalArgCount, HermesValue::encodeObjectValue(self->getTarget(runtime)), originalNewTarget); // Initialize "thisArg". When constructing we must use the original 'this', // not the bound one. newCalleeFrame.getThisArgRef() = !originalNewTarget.isUndefined() ? callerFrame.getScratchRef() : self->getArgsWithThis(runtime)[0]; res = Callable::call(newCalleeFrame.getCalleeClosureHandleUnsafe(), runtime); assert( runtime->getCurrentFrame() == callerFrame && "caller frame not restored"); // Restore the original stack level. runtime->popToSavedStackPointer(originalCalleeFrame.ptr()); } bail: // We must restore the original call frame. There is no need to restore // all the fields to their previous values, just the registers which are not // supposed to be modified by a call. StackFramePtr::initFrame( originalCalleeFrame.ptr(), StackFramePtr{}, ip, nullptr, 0, nullptr, false); // Restore "thisArg" and clear the scratch register to avoid a leak. originalCalleeFrame.getThisArgRef() = callerFrame.getScratchRef(); callerFrame.getScratchRef() = HermesValue::encodeUndefinedValue(); return res; } CallResult<HermesValue> BoundFunction::_callImpl( Handle<Callable> selfHandle, Runtime *runtime) { // Pass `nullptr` as the IP because this function is never called // from the interpreter, which should use `_boundCall` directly. return _boundCall(vmcast<BoundFunction>(selfHandle.get()), nullptr, runtime); } //===----------------------------------------------------------------------===// // class NativeFunction CallableVTable NativeFunction::vt{ { VTable( CellKind::NativeFunctionKind, cellSize<NativeFunction>(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, // externalMemorySize VTable::HeapSnapshotMetadata{HeapSnapshot::NodeType::Closure, NativeFunction::_snapshotNameImpl, NativeFunction::_snapshotAddEdgesImpl, nullptr, nullptr}), NativeFunction::_getOwnIndexedRangeImpl, NativeFunction::_haveOwnIndexedImpl, NativeFunction::_getOwnIndexedPropertyFlagsImpl, NativeFunction::_getOwnIndexedImpl, NativeFunction::_setOwnIndexedImpl, NativeFunction::_deleteOwnIndexedImpl, NativeFunction::_checkAllOwnIndexedImpl, }, NativeFunction::_newObjectImpl, NativeFunction::_callImpl}; void NativeFunctionBuildMeta(const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<NativeFunction>()); CallableBuildMeta(cell, mb); } #ifdef HERMESVM_SERIALIZE NativeFunction::NativeFunction( Deserializer &d, const VTable *vt, void *context, NativeFunctionPtr functionPtr) : Callable(d, vt), context_(context), functionPtr_(functionPtr) {} void NativeFunction::serializeNativeFunctionImpl( Serializer &s, const GCCell *cell, unsigned overlapSlots) { serializeCallableImpl(s, cell, overlapSlots); } void NativeFunctionSerialize(Serializer &s, const GCCell *cell) { auto *self = vmcast<const NativeFunction>(cell); // Write context_ here as a value directly since it is used as a value for // NativeFunctions. // Note: This is only true if we don't have to serialize after user code, // where we don't have FinalizableNativeFunction. Also before this goes into // production we should make sure there is a way to prevent functions from // being added that rely on a non-serializable ctx. s.writeInt<uint64_t>((uint64_t)self->context_); // The relocation is already there as Serializer is constructed and // we map func to an id based on NativeFunc.def. assert( s.objectInTable((void *)self->functionPtr_) && "functionPtr not in relocation map"); s.writeRelocation((const void *)self->functionPtr_); NativeFunction::serializeNativeFunctionImpl( s, cell, JSObject::numOverlapSlots<NativeFunction>()); s.endObject(cell); } void NativeFunctionDeserialize(Deserializer &d, CellKind kind) { assert(kind == CellKind::NativeFunctionKind && "Expected NativeFunction"); void *context = (void *)d.readInt<uint64_t>(); void *functionPtr = d.ptrRelocationOrNull(d.readInt<uint32_t>()); assert(functionPtr && "functionPtr not in relocation map"); void *mem = d.getRuntime()->alloc(cellSize<NativeFunction>()); auto *cell = new (mem) NativeFunction( d, &NativeFunction::vt.base.base, context, (NativeFunctionPtr)functionPtr); d.endObject(cell); } #endif std::string NativeFunction::_snapshotNameImpl(GCCell *cell, GC *gc) { auto *const self = reinterpret_cast<NativeFunction *>(cell); return getFunctionName(self->functionPtr_); } Handle<NativeFunction> NativeFunction::create( Runtime *runtime, Handle<JSObject> parentHandle, void *context, NativeFunctionPtr functionPtr, SymbolID name, unsigned paramCount, Handle<JSObject> prototypeObjectHandle) { void *mem = runtime->alloc(cellSize<NativeFunction>()); auto selfHandle = runtime->makeHandle(allocateSmallPropStorage(new (mem) NativeFunction( runtime, &vt.base.base, *parentHandle, runtime->getHiddenClassForPrototypeRaw( *parentHandle, numOverlapSlots<NativeFunction>() + ANONYMOUS_PROPERTY_SLOTS), context, functionPtr))); auto st = defineNameLengthAndPrototype( selfHandle, runtime, name, paramCount, prototypeObjectHandle, Callable::WritablePrototype::Yes, false); (void)st; assert( st != ExecutionStatus::EXCEPTION && "defineLengthAndPrototype() failed"); return selfHandle; } Handle<NativeFunction> NativeFunction::create( Runtime *runtime, Handle<JSObject> parentHandle, Handle<Environment> parentEnvHandle, void *context, NativeFunctionPtr functionPtr, SymbolID name, unsigned paramCount, Handle<JSObject> prototypeObjectHandle) { void *mem = runtime->alloc(cellSize<NativeFunction>()); auto selfHandle = runtime->makeHandle(allocateSmallPropStorage(new (mem) NativeFunction( runtime, &vt.base.base, *parentHandle, runtime->getHiddenClassForPrototypeRaw( *parentHandle, numOverlapSlots<NativeFunction>() + ANONYMOUS_PROPERTY_SLOTS), parentEnvHandle, context, functionPtr))); auto st = defineNameLengthAndPrototype( selfHandle, runtime, name, paramCount, prototypeObjectHandle, Callable::WritablePrototype::Yes, false); (void)st; assert( st != ExecutionStatus::EXCEPTION && "defineLengthAndPrototype() failed"); return selfHandle; } CallResult<HermesValue> NativeFunction::_callImpl( Handle<Callable> selfHandle, Runtime *runtime) { return _nativeCall(vmcast<NativeFunction>(selfHandle.get()), runtime); } CallResult<HermesValue> NativeFunction::_newObjectImpl( Handle<Callable>, Runtime *runtime, Handle<JSObject>) { return runtime->raiseTypeError( "This function cannot be used as a constructor."); } //===----------------------------------------------------------------------===// // class NativeConstructor const CallableVTable NativeConstructor::vt{ { VTable( CellKind::NativeConstructorKind, cellSize<NativeConstructor>(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, // externalMemorySize VTable::HeapSnapshotMetadata{ HeapSnapshot::NodeType::Closure, NativeConstructor::_snapshotNameImpl, NativeConstructor::_snapshotAddEdgesImpl, nullptr, nullptr}), NativeConstructor::_getOwnIndexedRangeImpl, NativeConstructor::_haveOwnIndexedImpl, NativeConstructor::_getOwnIndexedPropertyFlagsImpl, NativeConstructor::_getOwnIndexedImpl, NativeConstructor::_setOwnIndexedImpl, NativeConstructor::_deleteOwnIndexedImpl, NativeConstructor::_checkAllOwnIndexedImpl, }, NativeConstructor::_newObjectImpl, NativeConstructor::_callImpl}; void NativeConstructorBuildMeta(const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<NativeConstructor>()); NativeFunctionBuildMeta(cell, mb); } #ifdef HERMESVM_SERIALIZE NativeConstructor::NativeConstructor( Deserializer &d, void *context, NativeFunctionPtr functionPtr, CellKind targetKind, CreatorFunction *creatorFunction) : NativeFunction(d, &vt.base.base, context, functionPtr), #ifndef NDEBUG targetKind_(targetKind), #endif creator_(creatorFunction) { } void NativeConstructorSerialize(Serializer &s, const GCCell *cell) { auto *self = vmcast<const NativeConstructor>(cell); // Write context_ here as a value directly since it is used as a value for // NativeFunctions. s.writeInt<uint64_t>((uint64_t)self->context_); assert( s.objectInTable((void *)self->functionPtr_) && "functionPtr_ not in relocation map"); s.writeRelocation((const void *)self->functionPtr_); #ifndef NDEBUG // CellKind is less than 255. 1 Byte is enough. s.writeInt<uint8_t>((uint8_t)self->targetKind_); #endif assert( s.objectInTable((void *)self->creator_) && "creator funtion not in relocation table"); s.writeRelocation((void *)self->creator_); NativeFunction::serializeNativeFunctionImpl( s, cell, JSObject::numOverlapSlots<NativeConstructor>()); s.endObject(cell); } void NativeConstructorDeserialize(Deserializer &d, CellKind kind) { using CreatorFunction = CallResult<HermesValue>(Runtime *, Handle<JSObject>); assert( kind == CellKind::NativeConstructorKind && "Expected NativeConstructor"); void *context = (void *)d.readInt<uint64_t>(); void *functionPtr = d.ptrRelocationOrNull(d.readInt<uint32_t>()); assert(functionPtr && "functionPtr not in relocation map"); CellKind targetKind = CellKind::UninitializedKind; #ifndef NDEBUG // CellKind is less than 255. 1 Byte is enough targetKind = (CellKind)d.readInt<uint8_t>(); #endif void *creatorPtr = d.ptrRelocationOrNull(d.readInt<uint32_t>()); assert(creatorPtr && "funtion pointer must have been mapped already"); void *mem = d.getRuntime()->alloc(cellSize<NativeConstructor>()); auto *cell = new (mem) NativeConstructor( d, context, (NativeFunctionPtr)functionPtr, targetKind, (CreatorFunction *)creatorPtr); d.endObject(cell); } #endif #ifndef NDEBUG CallResult<HermesValue> NativeConstructor::_callImpl( Handle<Callable> selfHandle, Runtime *runtime) { StackFramePtr newFrame{runtime->getStackPointer()}; if (newFrame.isConstructorCall()) { auto consHandle = Handle<NativeConstructor>::vmcast(selfHandle); assert( consHandle->targetKind_ == vmcast<JSObject>(newFrame.getThisArgRef())->getKind() && "call(construct=true) called without the correct 'this' value"); } return NativeFunction::_callImpl(selfHandle, runtime); } #endif //===----------------------------------------------------------------------===// // class JSFunction CallableVTable JSFunction::vt{ { VTable( CellKind::FunctionKind, cellSize<JSFunction>(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, // externalMemorySize VTable::HeapSnapshotMetadata{ HeapSnapshot::NodeType::Closure, JSFunction::_snapshotNameImpl, JSFunction::_snapshotAddEdgesImpl, nullptr, JSFunction::_snapshotAddLocationsImpl}), JSFunction::_getOwnIndexedRangeImpl, JSFunction::_haveOwnIndexedImpl, JSFunction::_getOwnIndexedPropertyFlagsImpl, JSFunction::_getOwnIndexedImpl, JSFunction::_setOwnIndexedImpl, JSFunction::_deleteOwnIndexedImpl, JSFunction::_checkAllOwnIndexedImpl, }, JSFunction::_newObjectImpl, JSFunction::_callImpl}; void FunctionBuildMeta(const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSFunction>()); CallableBuildMeta(cell, mb); const auto *self = static_cast<const JSFunction *>(cell); mb.addField("domain", &self->domain_); } #ifdef HERMESVM_SERIALIZE void serializeFunctionImpl( Serializer &s, const GCCell *cell, unsigned overlapSlots) { auto *self = vmcast<const JSFunction>(cell); serializeCallableImpl(s, cell, overlapSlots); s.writeRelocation(self->codeBlock_); s.writeRelocation(self->domain_.get(s.getRuntime())); } JSFunction::JSFunction(Deserializer &d, const VTable *vt) : Callable(d, vt) { d.readRelocation(&codeBlock_, RelocationKind::NativePointer); d.readRelocation(&domain_, RelocationKind::GCPointer); } void FunctionSerialize(Serializer &s, const GCCell *cell) { serializeFunctionImpl(s, cell, JSObject::numOverlapSlots<JSFunction>()); s.endObject(cell); } void FunctionDeserialize(Deserializer &d, CellKind kind) { assert(kind == CellKind::FunctionKind && "Expected Function"); void *mem = d.getRuntime()->alloc</*fixedSize*/ true, HasFinalizer::No>( cellSize<JSFunction>()); auto *cell = new (mem) JSFunction(d, &JSFunction::vt.base.base); d.endObject(cell); } #endif CallResult<HermesValue> JSFunction::create( Runtime *runtime, Handle<Domain> domain, Handle<JSObject> parentHandle, Handle<Environment> envHandle, CodeBlock *codeBlock) { void *mem = runtime->alloc</*fixedSize*/ true, kHasFinalizer>(cellSize<JSFunction>()); auto *self = allocateSmallPropStorage(new (mem) JSFunction( runtime, *domain, *parentHandle, runtime->getHiddenClassForPrototypeRaw( *parentHandle, numOverlapSlots<JSFunction>() + ANONYMOUS_PROPERTY_SLOTS), envHandle, codeBlock)); self->flags_.lazyObject = 1; return HermesValue::encodeObjectValue(self); } void JSFunction::addLocationToSnapshot( HeapSnapshot &snap, HeapSnapshot::NodeID id) const { if (auto location = codeBlock_->getSourceLocation()) { snap.addLocation( id, codeBlock_->getRuntimeModule()->getScriptID(), location->line, location->column); } } CallResult<HermesValue> JSFunction::_callImpl( Handle<Callable> selfHandle, Runtime *runtime) { auto *self = vmcast<JSFunction>(selfHandle.get()); if (auto *jitPtr = self->getCodeBlock()->getJITCompiled()) return (*jitPtr)(runtime); return runtime->interpretFunction(self->getCodeBlock()); } std::string JSFunction::_snapshotNameImpl(GCCell *cell, GC *gc) { auto *const self = vmcast<JSFunction>(cell); std::string funcName = Callable::_snapshotNameImpl(self, gc); if (!funcName.empty()) { return funcName; } return self->codeBlock_->getNameString(gc->getCallbacks()); } void JSFunction::_snapshotAddLocationsImpl( GCCell *cell, GC *gc, HeapSnapshot &snap) { auto *const self = vmcast<JSFunction>(cell); self->addLocationToSnapshot(snap, gc->getObjectID(self)); } //===----------------------------------------------------------------------===// // class JSGeneratorFunction CallableVTable JSGeneratorFunction::vt{ { VTable( CellKind::GeneratorFunctionKind, cellSize<JSGeneratorFunction>(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, // externalMemorySize VTable::HeapSnapshotMetadata{ HeapSnapshot::NodeType::Closure, JSGeneratorFunction::_snapshotNameImpl, JSGeneratorFunction::_snapshotAddEdgesImpl, nullptr, nullptr}), JSGeneratorFunction::_getOwnIndexedRangeImpl, JSGeneratorFunction::_haveOwnIndexedImpl, JSGeneratorFunction::_getOwnIndexedPropertyFlagsImpl, JSGeneratorFunction::_getOwnIndexedImpl, JSGeneratorFunction::_setOwnIndexedImpl, JSGeneratorFunction::_deleteOwnIndexedImpl, JSGeneratorFunction::_checkAllOwnIndexedImpl, }, JSGeneratorFunction::_newObjectImpl, JSGeneratorFunction::_callImpl}; void GeneratorFunctionBuildMeta(const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSGeneratorFunction>()); FunctionBuildMeta(cell, mb); } #ifdef HERMESVM_SERIALIZE JSGeneratorFunction::JSGeneratorFunction(Deserializer &d) : JSFunction(d, &vt.base.base) {} void GeneratorFunctionSerialize(Serializer &s, const GCCell *cell) { // No additional fields compared to JSFunction. serializeFunctionImpl( s, cell, JSObject::numOverlapSlots<JSGeneratorFunction>()); s.endObject(cell); } void GeneratorFunctionDeserialize(Deserializer &d, CellKind kind) { assert( kind == CellKind::GeneratorFunctionKind && "Expected GeneratorFunction"); void *mem = d.getRuntime()->alloc</*fixedSize*/ true, HasFinalizer::No>( cellSize<JSFunction>()); auto *cell = new (mem) JSGeneratorFunction(d); d.endObject(cell); } #endif CallResult<HermesValue> JSGeneratorFunction::create( Runtime *runtime, Handle<Domain> domain, Handle<JSObject> parentHandle, Handle<Environment> envHandle, CodeBlock *codeBlock) { void *mem = runtime->alloc</*fixedSize*/ true, kHasFinalizer>(cellSize<JSFunction>()); auto *self = allocateSmallPropStorage(new (mem) JSGeneratorFunction( runtime, *domain, *parentHandle, runtime->getHiddenClassForPrototypeRaw( *parentHandle, numOverlapSlots<JSGeneratorFunction>() + ANONYMOUS_PROPERTY_SLOTS), envHandle, codeBlock)); self->flags_.lazyObject = 1; return HermesValue::encodeObjectValue(self); } //===----------------------------------------------------------------------===// // class GeneratorInnerFunction CallableVTable GeneratorInnerFunction::vt{ { VTable( CellKind::GeneratorInnerFunctionKind, cellSize<GeneratorInnerFunction>(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, // externalMemorySize VTable::HeapSnapshotMetadata{ HeapSnapshot::NodeType::Closure, GeneratorInnerFunction::_snapshotNameImpl, GeneratorInnerFunction::_snapshotAddEdgesImpl, nullptr, nullptr}), GeneratorInnerFunction::_getOwnIndexedRangeImpl, GeneratorInnerFunction::_haveOwnIndexedImpl, GeneratorInnerFunction::_getOwnIndexedPropertyFlagsImpl, GeneratorInnerFunction::_getOwnIndexedImpl, GeneratorInnerFunction::_setOwnIndexedImpl, GeneratorInnerFunction::_deleteOwnIndexedImpl, GeneratorInnerFunction::_checkAllOwnIndexedImpl, }, GeneratorInnerFunction::_newObjectImpl, GeneratorInnerFunction::_callImpl}; void GeneratorInnerFunctionBuildMeta( const GCCell *cell, Metadata::Builder &mb) { mb.addJSObjectOverlapSlots( JSObject::numOverlapSlots<GeneratorInnerFunction>()); FunctionBuildMeta(cell, mb); const auto *self = static_cast<const GeneratorInnerFunction *>(cell); mb.addField("savedContext", &self->savedContext_); mb.addField("result", &self->result_); } #ifdef HERMESVM_SERIALIZE GeneratorInnerFunction::GeneratorInnerFunction(Deserializer &d) : JSFunction(d, &vt.base.base) { state_ = (State)d.readInt<uint8_t>(); argCount_ = d.readInt<uint32_t>(); if (d.readInt<uint8_t>()) { savedContext_.set( d.getRuntime(), ArrayStorage::deserializeArrayStorage(d), &d.getRuntime()->getHeap()); } d.readHermesValue(&result_); nextIPOffset_ = d.readInt<uint32_t>(); action_ = (Action)d.readInt<uint8_t>(); } void GeneratorInnerFunctionSerialize(Serializer &s, const GCCell *cell) { auto *self = vmcast<const GeneratorInnerFunction>(cell); serializeFunctionImpl( s, cell, JSObject::numOverlapSlots<GeneratorInnerFunction>()); s.writeInt<uint8_t>((uint8_t)self->state_); s.writeInt<uint32_t>(self->argCount_); bool hasArray = (bool)self->savedContext_; s.writeInt<uint8_t>(hasArray); if (hasArray) { ArrayStorage::serializeArrayStorage( s, self->savedContext_.get(s.getRuntime())); } s.writeHermesValue(self->result_); s.writeInt<uint32_t>(self->nextIPOffset_); s.writeInt<uint8_t>((uint8_t)self->action_); s.endObject(cell); } void GeneratorInnerFunctionDeserialize(Deserializer &d, CellKind kind) { assert( kind == CellKind::GeneratorInnerFunctionKind && "Expected GeneratorInnerFunction"); void *mem = d.getRuntime()->alloc(cellSize<GeneratorInnerFunction>()); auto *cell = new (mem) GeneratorInnerFunction(d); d.endObject(cell); } #endif CallResult<Handle<GeneratorInnerFunction>> GeneratorInnerFunction::create( Runtime *runtime, Handle<Domain> domain, Handle<JSObject> parentHandle, Handle<Environment> envHandle, CodeBlock *codeBlock, NativeArgs args) { void *mem = runtime->alloc(cellSize<GeneratorInnerFunction>()); auto self = runtime->makeHandle( allocateSmallPropStorage(new (mem) GeneratorInnerFunction( runtime, *domain, *parentHandle, runtime->getHiddenClassForPrototypeRaw( *parentHandle, numOverlapSlots<GeneratorInnerFunction>() + ANONYMOUS_PROPERTY_SLOTS), envHandle, codeBlock, args.getArgCount()))); // We must store the entire frame, including the extra registers the callee // had to allocate at the start. const uint32_t frameSize = codeBlock->getFrameSize() + StackFrameLayout::CalleeExtraRegistersAtStart; // Size needed to store the complete context: // - "this" // - actual arguments // - stack frame const uint32_t ctxSize = 1 + args.getArgCount() + frameSize; auto ctxRes = ArrayStorage::create(runtime, ctxSize, ctxSize); if (LLVM_UNLIKELY(ctxRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto ctx = runtime->makeHandle<ArrayStorage>(*ctxRes); // Set "this" as the first element. ctx->at(0).set(args.getThisArg(), &runtime->getHeap()); // Set the rest of the arguments. // Argument i goes in slot i+1 to account for the "this". for (uint32_t i = 0, e = args.getArgCount(); i < e; ++i) { ctx->at(i + 1).set(args.getArg(i), &runtime->getHeap()); } self->savedContext_.set(runtime, ctx.get(), &runtime->getHeap()); return self; } /// Call the callable with arguments already on the stack. CallResult<HermesValue> GeneratorInnerFunction::callInnerFunction( Handle<GeneratorInnerFunction> selfHandle, Runtime *runtime, Handle<> arg, Action action) { auto self = Handle<GeneratorInnerFunction>::vmcast(selfHandle); self->result_.set(arg.getHermesValue(), &runtime->getHeap()); self->action_ = action; auto ctx = runtime->makeHandle(selfHandle->savedContext_); // Account for the `this` argument stored as the first element of ctx. const uint32_t argCount = self->argCount_; // Generators cannot be used as constructors, so newTarget is always // undefined. HermesValue newTarget = HermesValue::encodeUndefinedValue(); ScopedNativeCallFrame frame{runtime, argCount, // Account for `this`. selfHandle.getHermesValue(), newTarget, ctx->at(0)}; if (LLVM_UNLIKELY(frame.overflowed())) return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); for (ArrayStorage::size_type i = 0, e = argCount; i < e; ++i) { frame->getArgRef(i) = ctx->at(i + 1); } return JSFunction::_callImpl(selfHandle, runtime); } void GeneratorInnerFunction::restoreStack(Runtime *runtime) { const uint32_t frameOffset = getFrameOffsetInContext(); const uint32_t frameSize = getFrameSizeInContext(runtime); // Start at the lower end of the range to be copied. PinnedHermesValue *dst = StackFrameLayout::StackIncrement > 0 ? runtime->getCurrentFrame().ptr() : runtime->getCurrentFrame().ptr() - frameSize; assert( ((StackFrameLayout::StackIncrement > 0 && dst + frameSize <= runtime->getStackPointer()) || (StackFrameLayout::StackIncrement < 0 && dst >= runtime->getStackPointer())) && "reading off the end of the stack"); const GCHermesValue *src = &savedContext_.get(runtime)->at(frameOffset); std::memcpy(dst, src, frameSize * sizeof(PinnedHermesValue)); } void GeneratorInnerFunction::saveStack(Runtime *runtime) { const uint32_t frameOffset = getFrameOffsetInContext(); const uint32_t frameSize = getFrameSizeInContext(runtime); // Start at the lower end of the range to be copied. PinnedHermesValue *first = StackFrameLayout::StackIncrement > 0 ? runtime->getCurrentFrame().ptr() : runtime->getCurrentFrame().ptr() - frameSize; assert( ((StackFrameLayout::StackIncrement > 0 && first + frameSize <= runtime->getStackPointer()) || (StackFrameLayout::StackIncrement < 0 && first >= runtime->getStackPointer())) && "reading off the end of the stack"); // Use GCHermesValue::copy to ensure write barriers are executed. GCHermesValue::copy( first, first + frameSize, &savedContext_.get(runtime)->at(frameOffset), &runtime->getHeap()); } } // namespace vm } // namespace hermes
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
ecc5538c7783dc78ba7cc60f601c0a6d94518de9
7c665a1bd40eb0159e5b29685d21c6f2e98958a0
/grafoListAdj/src/Grafo.cpp
295f354a31ae3de0d60cb0c637cebc1a1f1d05dc
[ "MIT" ]
permissive
h4rd1ideveloper/Grafos
ef8c0d29c2475417d19d567e0436cce21a26b041
5ecb320d5f294f308b836ed45669b62b3f77d96e
refs/heads/master
2020-03-27T18:27:07.823972
2018-09-03T13:27:13
2018-09-03T13:27:13
146,923,040
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,414
cpp
#include "Grafo.h" Grafo::Grafo(int V) { this->V = V; // atribui o número de vértices adj = new list<int>[V]; // cria as listas } void Grafo:: removeAresta(int v1, int v2) { adj[v1].remove(v2); } void Grafo::adicionarAresta(int v1, int v2) { // adiciona vértice v2 à lista de vértices adjacentes de v1 adj[v1].push_back(v2); } int Grafo::obterGrauDeSaida(int v) { // basta retornar o tamanho da lista que é a quantidade de vizinhos return adj[v].size(); } bool Grafo::existeVizinho(int v1, int v2) { if(find(adj[v1].begin(), adj[v1].end(), v2) != adj[v1].end()) return true; return false; } void Grafo::dfs(int v) { stack<int> pilha; bool visitados[V]; // vetor de visitados // marca todos como não visitados for(int i = 0; i < V; i++) visitados[i] = false; while(true) { if(!visitados[v]) { cout << "Visitando vertice " << v << " ...\n"; visitados[v] = true; // marca como visitado pilha.push(v); // insere "v" na pilha } bool achou = false; list<int>::iterator it; // busca por um vizinho não visitado for(it = adj[v].begin(); it != adj[v].end(); it++) { if(!visitados[*it]) { achou = true; break; } } if(achou) v = *it; // atualiza o "v" else { // se todos os vizinhos estão visitados ou não existem vizinhos // remove da pilha pilha.pop(); // se a pilha ficar vazia, então terminou a busca if(pilha.empty()) break; // se chegou aqui, é porque pode pegar elemento do topo v = pilha.top(); } } } void Grafo::bfs(int v) { queue<int> fila; bool visitados[V]; // vetor de visitados for(int i = 0; i < V; i++) visitados[i] = false; cout << "Visitando vertice " << v << " ...\n"; visitados[v] = true; // marca como visitado while(true) { list<int>::iterator it; for(it = adj[v].begin(); it != adj[v].end(); it++) { if(!visitados[*it]) { cout << "Visitando vertice " << *it << " ...\n"; visitados[*it] = true; // marca como visitado fila.push(*it); // insere na fila } } // verifica se a fila NÃO está vazia if(!fila.empty()) { v = fila.front(); // obtém o primeiro elemento fila.pop(); // remove da fila } else break; } } bool Grafo::dfsBool(int v) { stack<int> pilha; bool visitados[V], pilha_rec[V]; // inicializa visitados e pilha_rec com false for(int i = 0; i < V; i++) visitados[i] = pilha_rec[i] = false; // faz uma DFS while(true) { bool achou_vizinho = false; list<int>::iterator it; if(!visitados[v]) { pilha.push(v); visitados[v] = pilha_rec[v] = true; } for(it = adj[v].begin(); it != adj[v].end(); it++) { // se o vizinho já está na pilha é porque existe ciclo if(pilha_rec[*it]) return true; else if(!visitados[*it]) { // se não está na pilha e não foi visitado, indica que achou achou_vizinho = true; break; } } if(!achou_vizinho) { pilha_rec[pilha.top()] = false; // marca que saiu da pilha pilha.pop(); // remove da pilha if(pilha.empty()) break; v = pilha.top(); } else v = *it; } return false; } bool Grafo::temCiclo() { for(int i = 0; i < V; i++) { if(dfsBool(i)) return true; } return false; }
[ "noreply@github.com" ]
noreply@github.com
abacb370940fb325ba2b17c66951fce112186c10
04f59610939088c55ce0c5812b89a9e10fd00dda
/Client/DataManager.h
6d2b148e3ce9f53e2c9397260f81ee72fdd25d6a
[]
no_license
ReoRavi/ICETAG
2810c3fb2f25d66dceea8b33537caf850d222858
a1c19b381149106b35a0a1cdd2c037017fad657a
refs/heads/master
2020-12-24T20:42:47.478270
2016-05-17T04:46:23
2016-05-17T04:46:23
58,851,098
0
0
null
null
null
null
UHC
C++
false
false
1,990
h
#pragma once //============================================= // CDataManager : 공용 변수들을 포함하는 객체. class CDataManager : public ISingleton <CDataManager> { public: CDataManager(); virtual ~CDataManager(); public : VOID Initialize(VOID); public : //======================================== // Scene - InGame // // 플레이어가 살아있는가 bool bIsPlayerAlive[8]; // 나간 클라이언트가 있는가 bool bIsClientQuit[8]; // 술래가 결정되고 게임이 시작됨 bool bIsIceTagStart; // 현재 클라이언트의 수 int ClientNum; // 내 클라이언트의 고유 번호 int SerialNum; // 플레이어의 수 int PlayerNum; // 다른 플레이어의 좌표 int PlayerXPos[8], PlayerYPos[8]; // 시간 // 0 - 분 1, 2 - 초 int Time[3]; // 술래 번호 int TaggerNum; // 플레이어들의 상태 eCharacter_State m_PlayerState[8]; // 플레이어들의 방향 eCharacter_Direction PlayerDirection[8]; // 게임중인가 bool bIsGameEnd; // 플레이어 승리 체크 bool bIsPlayerWin; //======================================== // Scene - Room // // 새로운 클라이언트가 들어왔음을 알림. bool bIsNewClient; // 플레이어들의 상태 bool bIsPlayer[8]; // 모든 클라이언트가 준비되었나. bool bIsAllClientReady; // 내가 방장인가 bool bIsMaster; // 준비된 클라이언트가 있다. bool bIsReadyClient; // 게임 시작이 실패되었다. bool bIsGameStartFailed; // bool bIsOhterPlayerQuit; // 플레이어들의 준비 여부 bool PlayerReadyState[8]; // 준비된 클라이언트의 번호 int ReadyClientNum; // 방장의 번호 int MasterNum; // int QuitPlayerNumber; // .플레이어들의 이름 std::string PlayerName[8]; std::string t_PlayerName; //======================================== // Scene - ALL // // 플레이어 종료. bool bIsQuit; // 게임 중 bool bIsGameRun; }; #define DataManager CDataManager::GetInstance()
[ "accounts1237@naver.com" ]
accounts1237@naver.com
737a3fc1c50f5b66920dade336786abe1f02d1b6
dd6fbf5eb0b517e782a6283202a00a24cccba39e
/Plugins/OpenCV/Source/OpenCV/Private/OpenCV.cpp
3009ba5e232fd5d89fa4738f287b72d051ffe6f2
[]
no_license
sht200713/UE4-OpenCV_Dlib_Plugin
77e1cb2e881de462fbfa0a90e47e57b9a4f0253a
7b47cb7dff9e58fc26dfdac32a9644173f0cac62
refs/heads/master
2022-11-24T06:25:52.356011
2020-08-05T06:11:06
2020-08-05T06:11:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,293
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "OpenCV.h" #include "Interfaces/IPluginManager.h" #if PLATFORM_ANDROID #include "AndroidPermissionFunctionLibrary.h" #endif #define LOCTEXT_NAMESPACE "FOpenCVModule" void FOpenCVModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module const FString PluginDir = IPluginManager::Get().FindPlugin(TEXT("OpenCV"))->GetBaseDir(); FString LibraryPath; #if PLATFORM_WINDOWS LibraryPath = FPaths::Combine(*PluginDir, TEXT("Library/Win64/")); UE_LOG(LogTemp, Warning, TEXT("opencv world LibraryPath == %s"), *(LibraryPath + TEXT("opencv_world340.dll"))); OpenCV_World_Handler = FPlatformProcess::GetDllHandle(*(LibraryPath + TEXT("opencv_world340.dll"))); OpenCV_FFmpeg_Handler = FPlatformProcess::GetDllHandle(*(LibraryPath + TEXT("opencv_ffmpeg340_64.dll"))); if (!OpenCV_World_Handler || !OpenCV_FFmpeg_Handler) { UE_LOG(LogTemp, Error, TEXT("Load OpenCV dll failed!")); } #elif PLATFORM_ANDROID //Request Android Permission TArray<FString> AndroidTotalPermissions = { TEXT("android.permission.CAMERA"), TEXT("android.permission.READ_EXTERNAL_STORAGE"), TEXT("android.permission.WRITE_EXTERNAL_STORAGE"), TEXT("android.permission.MOUNT_UNMOUNT_FILESYSTEMS"), }; TArray<FString> AndroidNeedReqPermissions; for(int i = 0; i < AndroidTotalPermissions.Num(); i++) { if(!UAndroidPermissionFunctionLibrary::CheckPermission(AndroidTotalPermissions[i])) { AndroidNeedReqPermissions.Add(AndroidTotalPermissions[i]); } } UAndroidPermissionFunctionLibrary::AcquirePermissions(AndroidNeedReqPermissions); #elif PLATFORM_IOS #endif } void FOpenCVModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. #if PLATFORM_WINDOWS FPlatformProcess::FreeDllHandle(OpenCV_World_Handler); OpenCV_World_Handler = nullptr; FPlatformProcess::FreeDllHandle(OpenCV_FFmpeg_Handler); OpenCV_FFmpeg_Handler = nullptr; #elif PLATFORM_ANDROID #elif PLATFORM_IOS #endif } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FOpenCVModule, OpenCV)
[ "997146918@qq.com" ]
997146918@qq.com
753ff9ed42e997cbaf1cfac553e06db23a3dfd1a
b5167311e01b478675038764c3f4eeead63d3421
/Yuloow/Classes/HelpLayer.cpp
beab79eefa350b86f68fb21be6872a6546520300
[]
no_license
luyifan/Yuloow
18f230bcf88db293617b5006ceec9b74b632c2be
24a1dbf080116f7d5f1ced291f59240cf11f972a
refs/heads/master
2020-04-06T06:24:03.687007
2013-12-25T11:24:36
2013-12-25T11:24:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,062
cpp
// // HelpLayer.cpp // Yuloow // // Created by luyifan on 13-11-17. // // #include "HelpLayer.h" HelpLayer::HelpLayer() { } HelpLayer::~HelpLayer() { } CCScene * HelpLayer::scene() { CCScene * scene = CCScene::create() ; HelpLayer * layer = HelpLayer::create(); scene->addChild( layer ) ; return scene ; } bool HelpLayer::init() { if ( !CCLayer::init()) return false ; _screenSize = CCDirector::sharedDirector()->getWinSize(); createGameScreen ( ) ; return true ; } void HelpLayer::update(float dt) { } void HelpLayer::createGameScreen() { CCSprite * bg = CCSprite::create("bg.png") ; bg->setPosition( ccp ( _screenSize.width * 0.5 , _screenSize.height * 0.5 )) ; this->addChild( bg ) ; CCSprite * rect ; rect = CCSprite::create ( "blank.png" ) ; rect->setTextureRect( CCRectMake( 0, 0, 512 , 512 )); rect->setPosition( ccp( _screenSize.width * 0.5 , _screenSize.height * 0.5 )) ; rect->setOpacity( 50 ) ; this->addChild( rect ) ; }
[ "maxluyifan@gmail.com" ]
maxluyifan@gmail.com
7f585fa3aeb41bcedba4044759e612794a371740
630a68871d4cdcc9dbc1f8ac8b44f579ff994ecf
/myodd/boost/libs/spirit/test/lex/token_iterpair.cpp
4ca9ecf6b15bc5ef9873729e81cfe41c4ebd61a7
[ "MIT", "BSL-1.0" ]
permissive
FFMG/myoddweb.piger
b56b3529346d9a1ed23034098356ea420c04929d
6f5a183940661bd7457e6a497fd39509e186cbf5
refs/heads/master
2023-01-09T12:45:27.156140
2022-12-31T12:40:31
2022-12-31T12:40:31
52,210,495
19
2
MIT
2022-12-31T12:40:32
2016-02-21T14:31:50
C++
UTF-8
C++
false
false
8,382
cpp
// Copyright (c) 2001-2011 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #define BOOST_SPIRIT_LEXERTL_DEBUG #include <boost/config/warning_disable.hpp> #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/include/lex_lexertl.hpp> #include <boost/spirit/include/lex_lexertl_position_token.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/spirit/include/phoenix_stl.hpp> namespace lex = boost::spirit::lex; namespace phoenix = boost::phoenix; namespace mpl = boost::mpl; /////////////////////////////////////////////////////////////////////////////// enum tokenids { ID_INT = 1000, ID_DOUBLE }; template <typename Lexer> struct token_definitions : lex::lexer<Lexer> { token_definitions() { this->self.add_pattern("HEXDIGIT", "[0-9a-fA-F]"); this->self.add_pattern("OCTALDIGIT", "[0-7]"); this->self.add_pattern("DIGIT", "[0-9]"); this->self.add_pattern("OPTSIGN", "[-+]?"); this->self.add_pattern("EXPSTART", "[eE][-+]"); this->self.add_pattern("EXPONENT", "[eE]{OPTSIGN}{DIGIT}+"); // define tokens and associate them with the lexer int_ = "(0x|0X){HEXDIGIT}+|0{OCTALDIGIT}*|{OPTSIGN}[1-9]{DIGIT}*"; int_.id(ID_INT); double_ = "{OPTSIGN}({DIGIT}*\\.{DIGIT}+|{DIGIT}+\\.){EXPONENT}?|{DIGIT}+{EXPONENT}"; double_.id(ID_DOUBLE); whitespace = "[ \t\n]+"; this->self = double_ | int_ | whitespace[ lex::_pass = lex::pass_flags::pass_ignore ] ; } lex::token_def<lex::omit> int_; lex::token_def<lex::omit> double_; lex::token_def<lex::omit> whitespace; }; template <typename Lexer> struct token_definitions_with_state : lex::lexer<Lexer> { token_definitions_with_state() { this->self.add_pattern("HEXDIGIT", "[0-9a-fA-F]"); this->self.add_pattern("OCTALDIGIT", "[0-7]"); this->self.add_pattern("DIGIT", "[0-9]"); this->self.add_pattern("OPTSIGN", "[-+]?"); this->self.add_pattern("EXPSTART", "[eE][-+]"); this->self.add_pattern("EXPONENT", "[eE]{OPTSIGN}{DIGIT}+"); this->self.add_state(); this->self.add_state("INT"); this->self.add_state("DOUBLE"); // define tokens and associate them with the lexer int_ = "(0x|0X){HEXDIGIT}+|0{OCTALDIGIT}*|{OPTSIGN}[1-9]{DIGIT}*"; int_.id(ID_INT); double_ = "{OPTSIGN}({DIGIT}*\\.{DIGIT}+|{DIGIT}+\\.){EXPONENT}?|{DIGIT}+{EXPONENT}"; double_.id(ID_DOUBLE); whitespace = "[ \t\n]+"; this->self("*") = double_ [ lex::_state = "DOUBLE"] | int_ [ lex::_state = "INT" ] | whitespace[ lex::_pass = lex::pass_flags::pass_ignore ] ; } lex::token_def<lex::omit> int_; lex::token_def<lex::omit> double_; lex::token_def<lex::omit> whitespace; }; /////////////////////////////////////////////////////////////////////////////// template <typename Token> inline bool test_token_ids(int const* ids, std::vector<Token> const& tokens) { BOOST_FOREACH(Token const& t, tokens) { if (*ids == -1) return false; // reached end of expected data typename Token::token_value_type const& value (t.value()); if (t.id() != static_cast<std::size_t>(*ids)) // token id must match return false; ++ids; } return (*ids == -1) ? true : false; } template <typename Token> inline bool test_token_states(std::size_t const* states, std::vector<Token> const& tokens) { BOOST_FOREACH(Token const& t, tokens) { if (*states == std::size_t(-1)) return false; // reached end of expected data typename Token::token_value_type const& value (t.value()); if (t.state() != *states) // token state must match return false; ++states; } return (*states == std::size_t(-1)) ? true : false; } /////////////////////////////////////////////////////////////////////////////// struct position_type { std::size_t begin, end; }; template <typename Iterator, typename Token> inline bool test_token_positions(Iterator begin, position_type const* positions, std::vector<Token> const& tokens) { BOOST_FOREACH(Token const& t, tokens) { if (positions->begin == std::size_t(-1) && positions->end == std::size_t(-1)) { return false; // reached end of expected data } boost::iterator_range<Iterator> matched = t.matched(); std::size_t start = std::distance(begin, matched.begin()); std::size_t end = std::distance(begin, matched.end()); // position must match if (start != positions->begin || end != positions->end) return false; ++positions; } return (positions->begin == std::size_t(-1) && positions->end == std::size_t(-1)) ? true : false; } /////////////////////////////////////////////////////////////////////////////// int main() { typedef std::string::iterator base_iterator_type; std::string input(" 01 1.2 -2 0x3 2.3e6 -3.4"); int ids[] = { ID_INT, ID_DOUBLE, ID_INT, ID_INT, ID_DOUBLE, ID_DOUBLE, -1 }; std::size_t states[] = { 0, 1, 2, 1, 1, 2, std::size_t(-1) }; position_type positions[] = { { 1, 3 }, { 4, 7 }, { 8, 10 }, { 11, 14 }, { 15, 20 }, { 21, 25 }, { std::size_t(-1), std::size_t(-1) } }; // token type: token id, iterator_pair as token value, no state { typedef lex::lexertl::token< base_iterator_type, mpl::vector<>, mpl::false_> token_type; typedef lex::lexertl::actor_lexer<token_type> lexer_type; token_definitions<lexer_type> lexer; std::vector<token_type> tokens; base_iterator_type first = input.begin(); using phoenix::arg_names::_1; BOOST_TEST(lex::tokenize(first, input.end(), lexer , phoenix::push_back(phoenix::ref(tokens), _1))); BOOST_TEST(test_token_ids(ids, tokens)); } { typedef lex::lexertl::position_token< base_iterator_type, mpl::vector<>, mpl::false_> token_type; typedef lex::lexertl::actor_lexer<token_type> lexer_type; token_definitions<lexer_type> lexer; std::vector<token_type> tokens; base_iterator_type first = input.begin(); using phoenix::arg_names::_1; BOOST_TEST(lex::tokenize(first, input.end(), lexer , phoenix::push_back(phoenix::ref(tokens), _1))); BOOST_TEST(test_token_ids(ids, tokens)); BOOST_TEST(test_token_positions(input.begin(), positions, tokens)); } // token type: holds token id, state, iterator_pair as token value { typedef lex::lexertl::token< base_iterator_type, mpl::vector<>, mpl::true_> token_type; typedef lex::lexertl::actor_lexer<token_type> lexer_type; token_definitions_with_state<lexer_type> lexer; std::vector<token_type> tokens; base_iterator_type first = input.begin(); using phoenix::arg_names::_1; BOOST_TEST(lex::tokenize(first, input.end(), lexer , phoenix::push_back(phoenix::ref(tokens), _1))); BOOST_TEST(test_token_ids(ids, tokens)); BOOST_TEST(test_token_states(states, tokens)); } { typedef lex::lexertl::position_token< base_iterator_type, mpl::vector<>, mpl::true_> token_type; typedef lex::lexertl::actor_lexer<token_type> lexer_type; token_definitions_with_state<lexer_type> lexer; std::vector<token_type> tokens; base_iterator_type first = input.begin(); using phoenix::arg_names::_1; BOOST_TEST(lex::tokenize(first, input.end(), lexer , phoenix::push_back(phoenix::ref(tokens), _1))); BOOST_TEST(test_token_ids(ids, tokens)); BOOST_TEST(test_token_states(states, tokens)); BOOST_TEST(test_token_positions(input.begin(), positions, tokens)); } return boost::report_errors(); }
[ "github@myoddweb.com" ]
github@myoddweb.com
911c18320a67018b0c27fb66699adbdff68bbdbc
c7b16512ed5b75cc7034c6c89faad9b4a5aed78d
/LISTAENLAZADA/src/lista.cpp
5f066078363510d4460e8583fc3155f17244e5bb
[]
no_license
faar0000/IPOO
7d10b04ee2b95290b96e76675dac42262e1eb1ad
ee4452c9965f8647cf1cccbbc6e27fb26b612304
refs/heads/master
2021-05-13T22:55:49.440099
2018-01-06T17:28:57
2018-01-06T17:28:57
116,501,714
0
0
null
null
null
null
UTF-8
C++
false
false
3,090
cpp
#include "lista.h" #include "nodo.h" #include <iostream> #include <cstdlib> using namespace std ; lista::lista() { tam=0; primero = NULL; actual = NULL; } void lista::insertar(nodo * n){ if(buscar(n->valor)) { cout<<"Ya se inserto: "<<n->valor<<endl; }else{ if (primero == NULL){ primero=n; actual=n; } else { actual->siguiente=n; actual=n; } actual->setPosicion(tam); tam ++; } } void lista::insertarAleatorio(int valor){ int pos=rand()% this->tam; nodo* nodeValue =new nodo(); nodeValue->valor =valor; if(pos==0){ primero = nodeValue; nodeValue->setPosicion(0); } else { nodo* temp = primero; while(temp!=0){ if(temp->siguiente->posicion==pos) { nodeValue->siguiente = temp->siguiente; temp->siguiente = nodeValue; nodeValue->setPosicion(pos); return; } temp = temp->siguiente; } } } void lista::insertar(int valor,int pos) { if(pos>this->tam) { cout<<"No se puede insertar en la posicion: "<<pos<<endl; return; }else{ cout<<"empezo insertar"<<endl; nodo* nodeValue = new nodo(); nodeValue->valor = valor; if(pos==0){ primero = nodeValue; nodeValue->setPosicion(0); }else{ nodo* temp = primero; while(temp!=0) { cout<<"pos_actual "<<temp->siguiente->posicion<<endl; if(temp->siguiente->posicion==pos) { nodeValue->siguiente = temp->siguiente; temp->siguiente = nodeValue; nodeValue->setPosicion(pos); return; } temp = temp->siguiente; } } } } void lista::elimar(int valor){ nodo *temp = primero; nodo *eliminar; while (temp != 0){ if(temp->siguiente->valor==valor) { eliminar=temp->siguiente; temp->siguiente=eliminar->siguiente; delete eliminar; temp->setPosicion(temp->posicion); return; } temp =temp->siguiente; } } bool lista::buscar(int valor) { nodo *temp = primero; while (temp != 0){ if(temp->valor==valor) { return true; } temp =temp->siguiente; } return false; } void lista::insertar(int valor) { nodo* temp = new nodo(); temp->valor=valor; this->insertar(temp); } void lista::mostrar(){ nodo *temp = primero; while (temp != 0){ cout<<temp->valor<<"("<<temp->posicion<<")->"; temp =temp->siguiente; } if(temp==0) cout<<"end"<<endl; delete temp; }
[ "noreply@github.com" ]
noreply@github.com
d65d0b54a48c6f1d9074706f4799df57e710bc02
efbdec654d7e140a49af065cda33365339c3b199
/LeetCode/48-rotate-image.cpp
092b827dac6adfdfd7a1ad90029f3ed48aa707bf
[]
no_license
tarunrajput/Data-Structures-and-Algorithms
f56b0fba7de9f2b21ab3ddf4cd933310dbc17f17
21e1fbf87b36a104e77029a5277e5a4cce196900
refs/heads/master
2023-09-01T10:50:59.979322
2021-10-02T11:42:57
2021-10-02T11:42:57
298,675,895
4
1
null
2021-10-02T11:42:58
2020-09-25T20:44:59
C++
UTF-8
C++
false
false
1,175
cpp
#include <iostream> #include <vector> using namespace std; // An Inplace function to rotate a N x N matrix by 90 degrees in clockwise direction void rotate(vector<vector<int>> &matrix) { int N = matrix.size(), temp; for (int x = 0; x < N / 2; x++) { for (int y = x; y < N - x - 1; y++) { temp = matrix[x][y]; matrix[x][y] = matrix[N - 1 - y][x]; matrix[N - 1 - y][x] = matrix[N - 1 - x][N - 1 - y]; matrix[N - 1 - x][N - 1 - y] = matrix[y][N - 1 - x]; matrix[y][N - 1 - x] = temp; } } } // Function to print the matrix void displayMatrix(vector<vector<int>> &matrix) { int N = matrix.size(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%2d ", matrix[i][j]); printf("\n"); } printf("\n"); } /* Driver program to test above functions */ int main() { vector<vector<int>> matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; rotate(matrix); displayMatrix(matrix); return 0; }
[ "tarunrajput1337@gmail.com" ]
tarunrajput1337@gmail.com
e15099fdbcfabc5dfe9c840f0c30bc5207125173
5ebd5cee801215bc3302fca26dbe534e6992c086
/blazetest/src/mathtest/dmatdvecmult/MDbVUa.cpp
65fc2098dec50965198067996c77fd5975729289
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
4,282
cpp
//================================================================================================= /*! // \file src/mathtest/dmatdvecmult/MDbVUa.cpp // \brief Source file for the MDbVUa dense matrix/dense vector multiplication math test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/UniformVector.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatdvecmult/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MDbVUa'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using MDb = blaze::DynamicMatrix<TypeB>; using VUa = blaze::UniformVector<TypeA>; // Creator type definitions using CMDb = blazetest::Creator<MDb>; using CVUa = blazetest::Creator<VUa>; // Running tests with small matrices and vectors for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=6UL; ++j ) { RUN_DMATDVECMULT_OPERATION_TEST( CMDb( j, i ), CVUa( i ) ); } } // Running tests with large matrices and vectors RUN_DMATDVECMULT_OPERATION_TEST( CMDb( 67UL, 127UL ), CVUa( 127UL ) ); RUN_DMATDVECMULT_OPERATION_TEST( CMDb( 127UL, 67UL ), CVUa( 67UL ) ); RUN_DMATDVECMULT_OPERATION_TEST( CMDb( 64UL, 128UL ), CVUa( 128UL ) ); RUN_DMATDVECMULT_OPERATION_TEST( CMDb( 128UL, 64UL ), CVUa( 64UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense vector multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
13dc47d3a61314e9668b1c5bc76e10f03561e89e
1908d12374c4058a27a54df36936c53588541c6a
/codechef/long-challenge/feb20/cash.cpp
aec98cb2bbc86aeda653e9795cfe1d725f388fa6
[]
no_license
abhisheksaran/Competitive-Programming
98e364ff7dc5091fda7d1d825d5dd200f445b69c
259f19e70699be02bff25459261f28d6dff7551b
refs/heads/master
2021-07-24T18:35:24.204536
2021-07-06T13:52:20
2021-07-06T13:52:20
200,476,249
0
0
null
null
null
null
UTF-8
C++
false
false
301
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; for(int i=0;i<t;i++){ int n; long long k; cin>>n>>k; vector<int> a(n,0); long long sum=0; for(int j=0;j<n;j++) { cin>> a[j]; sum+=a[j]; } // cout<<sum<<"\n"; long long ans=sum%k; cout<<ans<<"\n"; } return 0; }
[ "abhishekbishnoi695@gmail.com" ]
abhishekbishnoi695@gmail.com
f09b2beab16ab44e8d815063bbdc2240374cc92b
efee6c788d4134dc7f31774de8c0dce9f0d9e1a3
/C++_Code/Needs-Fixing/9.cpp
938d3996e84af3bbb9e4b71be807feb5bf1c03cc
[]
no_license
xXxSpicyBoiiixXx/PersonalProjects
0423f48d913ec3ff17b8d6fc0115420f6336be77
36e773a986715edbb7e38ee0a6e315966a23402e
refs/heads/master
2022-12-11T05:03:01.257568
2020-09-13T22:11:34
2020-09-13T22:11:34
288,551,560
1
0
null
null
null
null
UTF-8
C++
false
false
13,856
cpp
/* File: prog5_mha27_str28.cpp Author: Md Ali, Steven Rodda C.S.1428.501 Lab Section: L01 Program: #5 Due Date: --/--/-- This programs reads an unknown number of records from an input file. Each record contains a salesperson's ID#(integer) and the amount of sales(real) for that salesperson. A negative ID# acts as a sentinel to signal the end of processing. Functions are used to read, process and report the data to an output file. Each function is individually and appropriately documented. After all records are processed, a function is called to write an appropriate sentence to the screen letting the user know the name of the data file to which the sales report has been written. Note: An appropriate message is displayed to the screen if either the input file or the output file fails to open. Processing: * A function is called to print personal identifying information to an output file. * A function is called to print to the output file a title and column headers for the sales report displayed in tabular form. * A function is called to read a salesman's record from an input file. * While the salesman's ID# is non-negative, process the current record: * A function is called to calculate commission earned. * A function is called to calculate the bonus earned. * A function is called to calculate the salesman's total earnings. * A function is called to print the salesman's information to the output file. * A function is called to read a salesman's record from the input file. * A function is called to print personal identifying information to the screen. * A function is called to print an appropriate sentence to the screen letting the user know the name of the data file to which the sales report has been written. Notes: Commission earned by each salesperson is based on a percentage of his/her sales that month. A bonus is paid those who exceed this month's sales target. The bonus is calculated at a percentage based on \ the amount by which the target sales are exceeded. Functions Include: * A void function printIdInfo prints the author's personal information (name, class/section number, lab section number, due date) on the first, second, third and fourth lines of the output. printIdInfo prints two blank lines after the due date. The output is directed to a file or to the screen depending on the call. e.g. Sally Iza Student C.S.1428.? Lab Section: L? Due Date <blank line> <blank line> * A void function printColumnHeadings prints to the output file the title & column headings. * A void function readData uses only one read statement to "get" the values on each record from the input file - the employee ID# and monthly sales amount. * A typed function calcCommission calculates the amount of commission earned by each salesperson based on a commission rate of 10% of his/her sales that month. (10% is declared as a named constant in the calling routine.) * A typed function calcBonus calculates the bonus earned by a salesperson. A bonus is paid at a rate of 3% of sales to those who exceed this month's sales target of $30,000. The bonus calculation is based on the amount by which the target sales are exceeded. Note the example calculation below. (3% and $30000 are declared as named constants in the calling routine.) * A typed function calcEarnings calculates the total earnings for a salesperson. * A void function printReport prints to an output file the information for the current record as shown below. * A void function printFileNotification prints a statement to the screen letting the user know the name of the data file to which the sales report has been written. Input (file - prog5_501inp.txt): salesman's ID (integer) monthly sales figure (double) Constants: TARGET SALES AMOUNT = $30,000.00 COMMISSION RATE = 10% (0.10) BONUS RATE = 3% (0.03) Output (screen): Author's Name C.S.1428.? // '?' represents student's lecture section # Lab Section: L? // '?' represents student's lab section # --/--/-- // dashes represent due date, month/day/year <blank line> <blank line> <Appropriate message indicating the name of the output file.> Output (file - prog5_501out.txt): Author's Name C.S.1428.? // '?' represents student's lecture section # Lab Section: L? // '?' represents student's lab section # --/--/-- // dashes represent due date, month/day/year <blank line> <blank line> Monthly Sales Report <blank line> Sales ID# Sales Comments Commission Bonus Earnings ---------------------------------------------------------------- 39808 35000.00 Met Goal 3500.00 150.00 3650.00 45820 28000.00 2800.00 0.00 2800.00 ... ======================================================================= <Output will vary based on input values.> */ #include <iostream> #include <fstream> #include <cstdlib> #include <iomanip> using namespace std; void printIdInfo(ostream &out); void printColumnHeadings(ofstream &fout); void readData(ifstream &fin, int &employee_id, double &monthly_sales); double calcCommission(double monthly_sales, const double COMMISSION_RATE); double calcBonus(double monthly_sales, const double SALES_TARGET, const double BONUS_RATE); double calcEarnings(double commission, double bonus); void printReport(ofstream &fout, int employee_id, double monthly_sales, const double SALES_TARGET, double commission, double bonus, double earnings); void printFileNotification(ostream &cout); int main() { const double SALES_TARGET = 30000.00, COMMISSION_RATE = 0.10, BONUS_RATE = 0.03; double monthly_sales, commission, bonus, earnings; int employee_id = 1; //Setting default number for while loop ifstream fin; fin.open("prog5_501inp.txt"); if (!fin) { cout << endl << endl << "***Program Terminated.***" << endl << endl << "Input file failed to open!" << endl; return 1; } ofstream fout; fout.open("prog5_501out.txt"); if(!fout) { cout << endl << endl << " ***Program Terminated.*** " << endl << endl << "Output file failed to open!" << endl; fin.close(); return 2; } printIdInfo(fout); printColumnHeadings(fout); do { readData(fin, employee_id, monthly_sales); commission = calcCommission(monthly_sales, COMMISSION_RATE); bonus = calcBonus(monthly_sales, SALES_TARGET, BONUS_RATE); earnings = calcEarnings(commission, bonus); if(employee_id > 0) printReport(fout, employee_id, monthly_sales, SALES_TARGET, commission, bonus, earnings); } while(employee_id > 0); printIdInfo(cout); printFileNotification(cout); fin.close(); fout.close(); system("PAUSE>NUL"); return 0; } /* Function: printIdInfo The void function, printIdInfo, prints the author's personal information (name, class/section number, lab section number and due date) on the first, second, third and fourth lines of output. printIdInfo then prints two blank lines after the due date. Output is directed to a file or to the screen depending on the call. e.g. Author(s) C.S.1428.? // '?' replaced with three digit lecture section number Lab Section: L? // '? replaced with two digit lab section numbers --/--/-- // due date in this format <blank line> <blank line> Receives: output stream variable Constants: none Returns: nothing - prints author's personal information */ void printIdInfo(ostream &out) { out << "Md Ali, Steven Rodda" << endl << "C.S.1428.501" << endl << "Lab Section: L01, L01" << endl << "--/--/--" << endl << endl << endl; } /* Function: printColumnHeadings The void function, printColumnHeadings, prints to an output file a title and column headers for the sales report. e.g. Monthly Sales Report Sales ID# Sales Comments Commission Bonus Earnings ___________________________________________________________________ Receives: output file variable Constants: none Returns: nothing - prints a title and column headers */ void printColumnHeadings(ofstream &fout) { fout << " Monthly Sales Report" << endl << endl << "Sales ID# Sales Comments Commission Bonus Earnings" << endl << "----------------------------------------------------------------" << endl; } /* Function: readData The void function, readData, reads from an input file the employees' information: employee ID# and monthly sales amount. Receives: input file variable; employee_id (integer), monthly_sales (double); in this order Constants: none Returns: employee ID# & monthly sales amount read from an input file */ void readData(ifstream &fin, int &employee_id, double &monthly_sales) { fin >> employee_id >> monthly_sales; } /* Function: calcCommission The typed function, calcCommission, calculates the commission earned by the employee being processed. Receives: monthly_sales (double); COMMISSION_RATE (const double); in this order Constants: COMMISSION_RATE Returns: commission (double) */ double calcCommission(double monthly_sales, const double COMMISSION_RATE) { double commission; commission = monthly_sales * COMMISSION_RATE; return commission; } /* Function: calcBonus The typed function, calcBonus, calculates the bonus earned. A bonus is only paid to those who exceed the month's sales target. Bonus calculation is based on the amount by which the target sales are exceeded. Receives: monthly_sales (double); SALES_TARGET, BONUS_RATE (const doubles); in this order Constants: SALES_TARGET, BONUS_RATE Returns: bonus (double) */ double calcBonus(double monthly_sales, const double SALES_TARGET, const double BONUS_RATE) { double bonus; if (monthly_sales > SALES_TARGET) bonus = (monthly_sales - SALES_TARGET) * BONUS_RATE; else bonus = 0.00; return bonus; } /* Function: calcEarnings The typed function, calcEarnings, calculates total earnings. Receives: commission (double), bonus (double); in this order Constants: none Returns: earnings (double) */ double calcEarnings(double commission, double bonus) { double earnings; earnings = commission + bonus; return earnings; } /* Function: printReport The void function, printReport, prints to an output file the employees' ID, monthly sales, comment indicating whether or not sales goal was met, commission earned, bonus earned, and total earnings in tablular form. e.g. Monthly Sales Report Sales ID# Sales Comments Commission Bonus Earnings ___________________________________________________________________ 39808 35000.00 Met Goal 3500.00 150.00 3650.00 45820 28000.00 2800.00 0.00 2800.00 ... Note: printReport ONLY prints each employee record. Report title and column headers are printed in a different function. Receives: output file variable; employee_id (int), monthly_sales (double); SALES_TARGET (const double); commission (double); bonus (double); earnings (double); in this order Constants: SALES_TARGET Returns: nothing - prints monthly sales results for each employee */ void printReport(ofstream &fout, int employee_id, double monthly_sales, const double SALES_TARGET, double commission, double bonus, double earnings) { if(monthly_sales >= SALES_TARGET) fout << fixed << setprecision(2) << setw(8) << employee_id << setw(12) << monthly_sales << setw(10) << "Goal met" << setw(12) << commission << setw(10) << bonus << setw(12) << earnings << endl; else fout << fixed << setprecision(2) << setw(8) << employee_id << setw(12) << monthly_sales << setw(10) << " " << setw(12) << commission << setw(10) << bonus << setw(12) << earnings << endl; } /* Function: printFileNotification The void function, printFileNotification, prints a statement to the screen letting the user know the name of the data file to which the sales report has been written. e.g. "The sales report has been written to prog5_?out.txt." (without quotation marks); Note: question mark is replaced with author's lecture section # Receives: nothing Constants: none Returns: nothing - prints file notice to the console screen */ void printFileNotification(ostream &cout) { cout << "The sales report has been written to prog5_501out.txt." << endl; }
[ "noreply@github.com" ]
noreply@github.com
a10372bcfe95d2ef833f845be4e57974c8eac013
15f0514701a78e12750f68ba09d68095172493ee
/C++/309.cpp
63727a76d27d4512ab889a4a2e81c2135ab16f72
[ "MIT" ]
permissive
strengthen/LeetCode
5e38c8c9d3e8f27109b9124ae17ef8a4139a1518
3ffa6dcbeb787a6128641402081a4ff70093bb61
refs/heads/master
2022-12-04T21:35:17.872212
2022-11-30T06:23:24
2022-11-30T06:23:24
155,958,163
936
365
MIT
2021-11-15T04:02:45
2018-11-03T06:47:38
null
UTF-8
C++
false
false
1,511
cpp
__________________________________________________________________________________________________ sample 4 ms submission class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); int maxp = 0; if (n <= 1) return maxp; if (n <= 2) return maxp = max(maxp, prices[1] - prices[0]); vector<int> dp(n, 0); dp[1] = max(0, prices[1] - prices[0]); int diff = max(0 - prices[0], 0 - prices[1]); for (int i = 2; i < n; ++i) { dp[i] = max(dp[i - 1], prices[i] + diff); diff = max(diff, dp[i - 2] - prices[i]); } return dp[n - 1]; } }; __________________________________________________________________________________________________ sample 8620 kb submission class Solution { public: int maxProfit(vector<int> &p) { if (p.size() < 2) return 0; int result = 0; vector<int> buy(p.size(), 0); vector<int> sell(p.size(), 0); buy[0] = -p[0]; for(int i = 1; i < p.size(); i++){ sell[i] = max(buy[i - 1] + p[i], sell[i - 1] - p[i - 1] + p[i]); if(sell[i] > result) result = sell[i]; if(i == 1) buy[i] = -p[1]; else buy[i] = max(sell[i-2] - p[i], buy[i-1] + p[i-1] - p[i]); } return result; } }; // Fast I/O static bool _foo = ios::sync_with_stdio(false); static ostream* _bar = cin.tie(NULL); __________________________________________________________________________________________________
[ "strengthen@users.noreply.github.com" ]
strengthen@users.noreply.github.com
3ce577e822436119d5e374da2f4b7f80f04b2fb6
0fe06a24100e7010a18afb45c2a0558a979ea2f3
/HW4/hw4.cpp
7a64566504fe8eeb07ecac36f3501c1a390b2d38
[]
no_license
penguin-yeh/Data-Structure
ad7d2d904e8a12e9861e2951c4822113580aefe3
9dedd803da2682b99d32e1561e12c301d9e04ea7
refs/heads/main
2023-07-15T14:06:53.143887
2021-08-15T20:43:08
2021-08-15T20:43:08
396,406,262
0
0
null
null
null
null
UTF-8
C++
false
false
1,758
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <iostream> #include <functional> using namespace std; void init(bool **bits,int m,int r,int **a,int **b,int p) { *bits =(bool*)malloc(sizeof(bool)*m); *a = (int *)malloc(sizeof(int)*r); *b = (int *)malloc(sizeof(int)*r); srand(1); for(int i=0;i<r;i++) { *(*(a)+i) = rand()%(p-1)+1; } srand(2); for(int i=0;i<r;i++) { *(*(b)+i) = rand()%(p-1)+1; } } int myhash(char *str,int count,int m,int r,int p,int *a,int *b) { size_t key; std::hash<string> hasher; key = hasher(str); return (a[count]*key + b[count]) % p % m; } void insert(bool *bits,int m,int r,int p,char *str,int *a,int *b) { for(int i=0;i<r;i++) { bits[myhash(str,i,m,r,p,a,b)] = 1; } } bool query(bool *bits,int m,int p,int r,char *str,int *a,int *b) { for(int i=0;i<r;i++) { if(bits[myhash(str,i,m,r,p,a,b)]==0) { return 0; } } return 1; } int main() { bool *bits; int *a; int *b; int m,r,p; int word_cnt; int test_cnt; char str[1000]; scanf("%d",&m); scanf("%d",&r); scanf("%d",&word_cnt); scanf("%d",&test_cnt); scanf("%d",&p); init(&bits,m,r,&a,&b,p); for(int i=0;i<word_cnt;i++) { scanf("%s",str); insert(bits,m,r,p,str,a,b); } for(int i=0;i<test_cnt;i++) { scanf("%s",str); if(query(bits,m,p,r,str,a,b)==1) { printf("%s: true\n",str); } else { printf("%s: false\n",str); } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
7bd28121628b2baa68619d9fc6ccea0d12f0ffc3
b2fd3ad09b5986a45f4752ac9d2dd38e515b84e4
/MoravaEngine/src/Platform/Vulkan/VulkanCommandPool.h
2639301a4ed0b7069223e5e81c7daa94d392ced1
[ "Apache-2.0" ]
permissive
HoogDooo/MoravaEngine
3778e33e55246e24dcfdd95903e51bc0ddbbb8ba
bddbcd572b600c9be6eaf3a059b81bd770b821ed
refs/heads/master
2023-05-06T00:41:39.075091
2021-05-25T02:34:04
2021-05-25T02:34:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
201
h
#pragma once #include <vulkan/vulkan.h> class VulkanCommandPool { public: VulkanCommandPool(VkDevice device); ~VulkanCommandPool(); private: VkDevice m_Device; VkCommandPool m_CommandPool; };
[ "dtrajko@gmail.com" ]
dtrajko@gmail.com
72a3e2040ba9343104d60736c66330faa49b2f4b
75e4442debe42f416c49aadda5c07157341ed495
/subfiles/Dot.h
9315b355757140f5e985b26560be5a68dcc80b97
[]
no_license
abs718/autocoder
2c011c1a54059295f3e4a4afd908fca53bfc342e
0e3e02189e6e3aa2b6654f220fd7f9623e73bcab
refs/heads/master
2021-01-22T18:50:17.102664
2017-03-29T20:23:48
2017-03-29T20:23:48
85,120,027
1
2
null
null
null
null
UTF-8
C++
false
false
321
h
#pragma once #include "entity.h" class Dot : public Entity { private: float m_Timer; float m_TimerAmount; ALLEGRO_COLOR m_color; public: Dot(void); ~Dot(void); void Draw(); void Update(float Frame); void Activate(int X, int Y, float Angle, float Size); void Deactivate(void); private: float m_Angle; };
[ "noreply@github.com" ]
noreply@github.com
7bcd9d0773ea3d24cfcbbb707473e831a4054f80
7830649f29e87ff553a78f610bafa42f77283749
/jetson-inference-master/c/experimental/depthNet.h
a4d7716c40bce189d1c320c7c65b43f6ddeabe57
[ "MIT" ]
permissive
isoios7/jetson
2b7bde0dabfe32c8562ab9d8cb4ef764e4dd397d
4a8efb95f6137622e5a72b4f194ffdb20376494f
refs/heads/master
2023-06-08T08:22:54.233787
2021-07-02T02:26:50
2021-07-02T02:26:50
382,208,626
1
0
null
null
null
null
UTF-8
C++
false
false
8,620
h
/* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef __DEPTH_NET_H__ #define __DEPTH_NET_H__ #include "tensorNet.h" #include "cudaColormap.h" ////////////////////////////////////////////////////////////////////////////////// /// @name depthNet /// Depth estimation from monocular images. /// @ingroup deepVision ////////////////////////////////////////////////////////////////////////////////// ///@{ /** * Name of default input blob for depthNet model. * @ingroup depthNet */ #define DEPTHNET_DEFAULT_INPUT "input_0" /** * Name of default output blob for depthNet model. * @ingroup depthNet */ #define DEPTHNET_DEFAULT_OUTPUT "output_0" /** * Command-line options able to be passed to depthNet::Create() * @ingroup depthNet */ #define DEPTHNET_USAGE_STRING "depthNet arguments: \n" \ " --network NETWORK pre-trained model to load, one of the following:\n" \ " * TODO\n" \ " --model MODEL path to custom model to load (onnx)\n" \ " --input_blob INPUT name of the input layer (default is '" DEPTHNET_DEFAULT_INPUT "')\n" \ " --output_blob OUTPUT name of the output layer (default is '" DEPTHNET_DEFAULT_OUTPUT "')\n" \ " --batch_size BATCH maximum batch size (default is 1)\n" \ " --profile enable layer profiling in TensorRT\n" /** * Depth estimation from monocular images, using TensorRT. * @ingroup depthNet */ class depthNet : public tensorNet { public: /** * Network choice enumeration. */ enum NetworkType { CUSTOM, /**< Custom model provided by the user */ MOBILENET, /**< MobileNet backbone */ RESNET_18, /**< ResNet-18 backbone */ RESNET_50, /**< ResNet-50 backbone */ FCN_RESNET_50, /**< Fully-convolutional ResNet-50 */ }; /** * Parse a string to one of the built-in pretrained models. * Valid names are "mobilenet", "resnet-18", or "resnet-50", ect. * @returns one of the depthNet::NetworkType enums, or depthNet::CUSTOM on invalid string. */ static NetworkType NetworkTypeFromStr( const char* model_name ); /** * Convert a NetworkType enum to a string. */ static const char* NetworkTypeToStr( NetworkType network ); /** * Load a new network instance */ static depthNet* Create( NetworkType networkType=MOBILENET, uint32_t maxBatchSize=DEFAULT_MAX_BATCH_SIZE, precisionType precision=TYPE_FASTEST, deviceType device=DEVICE_GPU, bool allowGPUFallback=true ); /** * Load a new network instance * @param model_path File path to the caffemodel * @param mean_binary File path to the mean value binary proto (can be NULL) * @param class_labels File path to list of class name labels * @param input Name of the input layer blob. * @param output Name of the output layer blob. * @param maxBatchSize The maximum batch size that the network will support and be optimized for. */ static depthNet* Create( const char* model_path, const char* input=DEPTHNET_DEFAULT_INPUT, const char* output=DEPTHNET_DEFAULT_OUTPUT, uint32_t maxBatchSize=DEFAULT_MAX_BATCH_SIZE, precisionType precision=TYPE_FASTEST, deviceType device=DEVICE_GPU, bool allowGPUFallback=true ); /** * Load a custom network instance of a UFF model * @param model_path File path to the UFF model * @param input Name of the input layer blob. * @param inputDims Dimensions of the input layer blob. * @param output Name of the output layer blob containing the bounding boxes, ect. * @param maxBatchSize The maximum batch size that the network will support and be optimized for. */ static depthNet* Create( const char* model_path, const char* input, const Dims3& inputDims, const char* output, uint32_t maxBatchSize=DEFAULT_MAX_BATCH_SIZE, precisionType precision=TYPE_FASTEST, deviceType device=DEVICE_GPU, bool allowGPUFallback=true ); /** * Load a new network instance by parsing the command line. */ static depthNet* Create( int argc, char** argv ); /** * Usage string for command line arguments to Create() */ static inline const char* Usage() { return DEPTHNET_USAGE_STRING; } /** * Destroy */ virtual ~depthNet(); /** * Compute the depth field from a monocular RGBA image. * @note the raw depth field can be retrieved with GetDepthField(). */ bool Process( float* input, uint32_t width, uint32_t height ); /** * Process an RGBA image and map the depth image with the specified colormap. * @note this function calls Process() followed by Visualize(). */ bool Process( float* input, float* output, uint32_t width, uint32_t height, cudaColormapType colormap=COLORMAP_DEFAULT, cudaFilterMode filter=FILTER_LINEAR ); /** * Process an RGBA image and map the depth image with the specified colormap. * @note this function calls Process() followed by Visualize(). */ bool Process( float* input, uint32_t input_width, uint32_t input_height, float* output, uint32_t output_width, uint32_t output_height, cudaColormapType colormap=COLORMAP_DEFAULT, cudaFilterMode filter=FILTER_LINEAR ); /** * Visualize the raw depth field into a colorized RGBA depth map. * @note Visualize() should only be called after Process() */ bool Visualize( float* depth_map, uint32_t width, uint32_t height, cudaColormapType colormap=COLORMAP_DEFAULT, cudaFilterMode filter=FILTER_LINEAR ); /** * Extract and save the point cloud to a PCD file (depth only). * @note SavePointCloud() should only be called after Process() */ bool SavePointCloud( const char* filename ); /** * Extract and save the point cloud to a PCD file (depth + RGB). * @note SavePointCloud() should only be called after Process() */ bool SavePointCloud( const char* filename, float* rgba, uint32_t width, uint32_t height ); /** * Extract and save the point cloud to a PCD file (depth + RGB). * @note SavePointCloud() should only be called after Process() */ bool SavePointCloud( const char* filename, float* rgba, uint32_t width, uint32_t height, const float2& focalLength, const float2& principalPoint ); /** * Extract and save the point cloud to a PCD file (depth + RGB). * @note SavePointCloud() should only be called after Process() */ bool SavePointCloud( const char* filename, float* rgba, uint32_t width, uint32_t height, const float intrinsicCalibration[3][3] ); /** * Extract and save the point cloud to a PCD file (depth + RGB). * @note SavePointCloud() should only be called after Process() */ bool SavePointCloud( const char* filename, float* rgba, uint32_t width, uint32_t height, const char* intrinsicCalibrationPath ); /** * Return the raw depth field. */ inline float* GetDepthField() const { return mOutputs[0].CUDA; } /** * Return the width of the depth field. */ inline uint32_t GetDepthFieldWidth() const { return DIMS_W(mOutputs[0].dims); } /** * Return the height of the depth field */ inline uint32_t GetDepthFieldHeight() const { return DIMS_H(mOutputs[0].dims); } /** * Retrieve the network type (alexnet or googlenet) */ inline NetworkType GetNetworkType() const { return mNetworkType; } /** * Retrieve a string describing the network name. */ inline const char* GetNetworkName() const { NetworkTypeToStr(mNetworkType); } protected: depthNet(); NetworkType mNetworkType; float2 mDepthRange; }; ///@} #endif
[ "isoios7@naver.com" ]
isoios7@naver.com
e2caed096306e6875b9c605876b1f334905ba17d
5696f7e9bb6cb18e791be3f71e8a72f9a26a0a22
/src/PerformanceTest/PerformanceTest/CpuTask.cpp
11923da5e4d545c192c09cc3dfaf4780c1c5f0b3
[ "MIT" ]
permissive
xylsxyls/xueyelingshuang
0fdde992e430bdee38abb7aaf868b320e48dba64
a646d281c4b2ec3c2b27de29a67860fccce22436
refs/heads/master
2023-08-04T01:02:35.112586
2023-07-17T09:30:27
2023-07-17T09:30:27
61,338,042
4
2
null
null
null
null
UTF-8
C++
false
false
498
cpp
#include "CpuTask.h" #include "PerformanceManager.h" #include "CSystem/CSystemAPI.h" CpuTask::CpuTask(): m_exit(false), m_pid(0) { } void CpuTask::DoTask() { #ifdef _MSC_VER PerformanceManager::instance().addCPUPid(m_pid); #endif while (!m_exit) { PerformanceManager::instance().modifyCpuPerformance(m_pid, PerformanceManager::instance().CPUOccupation(m_pid)); CSystem::Sleep(800); } } void CpuTask::StopTask() { m_exit = true; } void CpuTask::setParam(uint32_t pid) { m_pid = pid; }
[ "yangnan@sensetime.com" ]
yangnan@sensetime.com
9f794a8235c66fb9dbb682fdcbcdaa643ec6029f
ef85c7bb57412c86d9ab28a95fd299e8411c316e
/inference-engine/tests/functional/plugin/gpu/shared_tests_instances/low_precision_transformations/mat_mul_with_constant_transformation.cpp
7a2c8ec2b8f2fe0850fae42bcf61406762032323
[ "Apache-2.0" ]
permissive
SDxKeeper/dldt
63bf19f01d8021c4d9d7b04bec334310b536a06a
a7dff0d0ec930c4c83690d41af6f6302b389f361
refs/heads/master
2023-01-08T19:47:29.937614
2021-10-22T15:56:53
2021-10-22T15:56:53
202,734,386
0
1
Apache-2.0
2022-12-26T13:03:27
2019-08-16T13:41:06
C++
UTF-8
C++
false
false
3,973
cpp
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include <gtest/gtest.h> #include "low_precision_transformations/mat_mul_with_constant_transformation.hpp" using namespace LayerTestsDefinitions; using namespace InferenceEngine::details; namespace { const std::vector<ngraph::element::Type> precisions = { ngraph::element::f32, ngraph::element::f16 }; //transpose_a = false, transpose_b = true std::vector<MatMulWithConstantTransformationTestValues> testValues = { { { 2, 3, 4 }, { 256ul, {{1, 3, 1}, {1, 3, 1}, {1, 3, 1}, {1, 3, 1}}, {0.f, 0.f, 0.f}, {255.f, 25.5f, 2.55f}, {0.f, 0.f, 0.f}, {255.f, 25.5f, 2.55f} }, { std::vector<float>(4 * 2, 2.f), ngraph::element::f32, ngraph::Shape{ 2, 4 } }, { 256ul, {{2, 1}, {2, 1}, {2, 1}, {2, 1}}, {-128.f, -12.8f}, {127.f, 12.7f}, {-128.f, -12.8f}, {127.f, 12.7f} }, { {}, {}, {} }, "FullyConnected", "FP32" }, { { 2, 3, 4 }, { 256ul, {{1, 3, 1}, {1, 3, 1}, {1, 3, 1}, {1, 3, 1}}, {0.f, 0.f, 0.f}, {255.f, 25.5f, 2.f}, {0.f, 0.f, 0.f}, {255.f, 25.5f, 2.f} }, { std::vector<float>(4 * 2, 2.f), ngraph::element::i8, ngraph::Shape{ 2, 4 } }, {}, { ngraph::element::f32, {}, {0.1f} }, "FullyConnected", "FP32" }, { { 1, 3, 4 }, { 256ul, {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}}, {-10.5f}, {4.5f}, {-10.5f}, {4.5f} }, { std::vector<float>(4 * 2, 2.f), ngraph::element::f32, ngraph::Shape{ 2, 4 } }, { 256ul, {{2, 1}, {2, 1}, {2, 1}, {2, 1}}, {-128.f, -12.8f}, {127.f, 12.7f}, {-128.f, -12.8f}, {127.f, 12.7f} }, { {}, {}, {} }, "FullyConnected", "FP32" }, { { 1, 1, 3, 4 }, { 256ul, {{1, 3, 1}, {1, 3, 1}, {1, 3, 1}, {1, 3, 1}}, {0.f, 0.f, 0.f}, {25.f, 24.f, 25.f}, {0.f, 0.f, 0.f}, {25.f, 24.f, 25.f} }, { std::vector<float>(4 * 2, 2.f), ngraph::element::f32, ngraph::Shape{ 2, 4 } }, { 256ul, {{2, 1}, {2, 1}, {2, 1}, {2, 1}}, {-128.f, -12.8f}, {127.f, 12.7f}, {-128.f, -12.8f}, {127.f, 12.7f} }, { {}, {}, {} }, "FullyConnected", "U8" }, { { 1, 1, 3, 4 }, { 256ul, {{1, 3, 1}, {1, 3, 1}, {1, 3, 1}, {1, 3, 1}}, {0.f, 0.f, 0.f}, {25.f, 24.f, 25.f}, {0.f, 0.f, 0.f}, {25.f, 24.f, 25.f} }, { std::vector<float>(4 * 2, 2.f), ngraph::element::i8, ngraph::Shape{ 2, 4 } }, {}, { ngraph::element::f32, {}, {{0.1f, 0.01}, ngraph::element::f32, ngraph::Shape{ 2, 1 }} }, "FullyConnected", "U8" }, { { 1, 3, 4 }, { 256ul, {{1}, {1}, {1}, {1}}, {0.f}, {255.f}, {0.f}, {25.5f} }, { std::vector<float>(4 * 4, 2.f), ngraph::element::f32, ngraph::Shape{ 4, 4 } }, { 256ul, {{1}, {1}, {1}, {1}}, {-128.f}, {127.f}, {-128.f}, {127.f} }, { {}, {}, {} }, "FullyConnected", "FP32" }, { { 2, 3 }, { 256ul, {{2, 1}, {2, 1}, {2, 1}, {2, 1}}, {-10.f, -5.f}, {5.f, 5.f}, {-10.f, -5.f}, {5.f, 5.f} }, { std::vector<float>{1, 2, 3, 4, 5, 6}, ngraph::element::f32, ngraph::Shape{ 2, 3 } }, { 256ul, {{1}, {1}, {1}, {1}}, {-128.f}, {127.f}, {-12.8f}, {12.7f} }, { {}, {}, {} }, "FullyConnected", "U8" }, { { 2, 3 }, { 256ul, {{2, 1}, {2, 1}, {2, 1}, {2, 1}}, {-10.f, -5.f}, {5.f, 5.f}, {-10.f, -5.f}, {5.f, 5.f} }, { std::vector<float>{1, 2, 3, 4, 5, 6}, ngraph::element::i8, ngraph::Shape{ 2, 3 } }, {}, { ngraph::element::f32, {}, {0.1f} }, "FullyConnected", "U8" } }; INSTANTIATE_TEST_SUITE_P(smoke_LPT, MatMulWithConstantTransformation, ::testing::Combine( ::testing::ValuesIn(precisions), ::testing::Values(CommonTestUtils::DEVICE_GPU), ::testing::ValuesIn(testValues)), MatMulWithConstantTransformation::getTestCaseName); } // namespace
[ "noreply@github.com" ]
noreply@github.com
888ebc796406d018106e391421a038dae1618d70
292827a33c60bdba5643a19a58b0add3d8f7bd1e
/RenderModels/Compounded/BezierModel.hpp
f95a100d230f7b83971f34025a714b567b59863b
[]
no_license
artcampo/2012_3D_96k_Procedural_game
143c9a6ca351fca127f8b00d2ebb8a461a002e9c
ae33e17c795457d777a0569762a3d157de4774b1
refs/heads/master
2021-01-12T04:27:50.727862
2016-12-29T14:01:49
2016-12-29T14:01:49
77,615,952
0
0
null
null
null
null
UTF-8
C++
false
false
463
hpp
#ifndef BEZIERMODEL_HPP #define BEZIERMODEL_HPP #include <vector> #include "dx_misc.hpp" #include "RenderModels\Basics\linelistmodel.h" class BezierModel { public: ~BezierModel(); BezierModel( std::vector<D3DXVECTOR3>& aPointsCurve, D3DXCOLOR& aColour); void displayLines(); D3DXCOLOR& getColour(); private: D3DXCOLOR mColour; LineListModel<VertexPos>* mLines; }; #endif // BEZIERMODEL_H
[ "arturocampos82@gmail.com" ]
arturocampos82@gmail.com
84ddef00dd884821396fc782692f5cbffdcbcb4b
25d8f94b6e9698495aa21a849bfa3c42f636c5b3
/Rubik's Cube Solver.cpp
2e09a557695b33f2d6ab981d8ead7fdb172e5951
[]
no_license
harsha14gupta/Rubiks_Cube_Solver_Algorithm
e4b1dbee633967ca8cbd291e3b3d8718877f39e2
25fec8644dda72b4bcb6268bd1ed467507381a19
refs/heads/master
2020-08-07T20:30:03.784179
2019-10-08T08:32:30
2019-10-08T08:32:30
213,578,485
1
0
null
2019-10-08T08:32:32
2019-10-08T07:40:53
null
UTF-8
C++
false
false
23,258
cpp
#include<iostream> using namespace std; //----------------------------------------------- char white[9]; char red[9]; char orange[9]; char blue[9]; char green[9]; char yellow[9]; //---------------------------------- void display(char face[9]) { for(int i=0;i<9;i++) { cout<<face[i]<<" "; } cout<<endl<<endl; } void swap(char &a,char &b) { char t=a; a=b; b=t; } void rotate_clock(char choice) { if (choice=='w') { cout<<"White"<<endl; swap(white[7],white[3]); swap(white[6],white[4]); swap(white[0],white[2]); swap(white[7],white[5]); swap(white[0],white[4]); swap(white[1],white[3]); //------------------------- swap(blue[0],orange[0]); swap(blue[7],orange[7]); swap(blue[6],orange[6]); swap(orange[6],green[6]); swap(orange[7],green[7]); swap(orange[0],green[0]); swap(green[6],red[6]); swap(green[7],red[7]); swap(green[0],red[0]); } //------------------------- else if(choice=='r') { cout<<"Red"<<endl; swap(red[0],red[4]); swap(red[7],red[5]); swap(red[1],red[3]); swap(red[0],red[6]); swap(red[1],red[5]); swap(red[2],red[4]); //------------------------- swap(blue[6],white[3]); swap(blue[5],white[2]); swap(blue[4],white[1]); swap(white[1],green[0]); swap(white[2],green[1]); swap(white[3],green[2]); swap(green[0],yellow[3]); swap(green[1],yellow[2]); swap(green[2],yellow[1]); //-------------------------- } //----------------------------------- else if(choice=='y') { cout<<"Yellow"<<endl; swap(yellow[1],yellow[5]); swap(yellow[2],yellow[4]); swap(yellow[0],yellow[6]); swap(yellow[1],yellow[3]); swap(yellow[0],yellow[4]); swap(yellow[7],yellow[5]); //-------------------------- swap(blue[4],red[4]); swap(blue[3],red[3]); swap(blue[2],red[2]); swap(red[2],green[2]); swap(red[3],green[3]); swap(red[4],green[4]); swap(green[4],orange[4]); swap(green[3],orange[3]); swap(green[2],orange[2]); //-------------------------- } //------------------------------------- else if(choice=='o') { cout<<"Orange"<<endl; swap(orange[4],orange[0]); swap(orange[3],orange[1]); swap(orange[5],orange[7]); swap(orange[4],orange[2]); swap(orange[5],orange[1]); swap(orange[6],orange[0]); //-------------------------- swap(blue[2],yellow[5]); swap(blue[1],yellow[6]); swap(blue[0],yellow[7]); swap(yellow[5],green[6]); swap(yellow[6],green[5]); swap(yellow[7],green[4]); swap(green[6],white[7]); swap(green[5],white[6]); swap(green[4],white[5]); //-------------------------- } //------------------------------------- else if(choice=='g') { cout<<"Green"<<endl; swap(green[6],green[2]); swap(green[5],green[3]); swap(green[7],green[1]); swap(green[4],green[6]); swap(green[7],green[3]); swap(green[0],green[2]); //-------------------------- swap(white[5],orange[2]); swap(white[4],orange[1]); swap(white[3],orange[0]); swap(yellow[3],orange[2]); swap(yellow[4],orange[1]); swap(yellow[5],orange[0]); swap(yellow[3],red[6]); swap(yellow[4],red[5]); swap(yellow[5],red[4]); //-------------------------- } //------------------------------------------- else if(choice=='b') { cout<<"Blue"; swap(blue[1],blue[7]); swap(blue[2],blue[6]); swap(blue[5],blue[3]); swap(blue[2],blue[0]); swap(blue[7],blue[3]); swap(blue[6],blue[4]); //-------------------------- swap(yellow[1],orange[4]); swap(yellow[0],orange[5]); swap(yellow[7],orange[6]); swap(white[7],orange[4]); swap(white[0],orange[5]); swap(white[1],orange[6]); swap(white[7],red[0]); swap(white[0],red[1]); swap(white[1],red[2]); //-------------------------- } } void white_bottom(char q) { if((yellow[0]=='w' && blue[3]==q) || (yellow[2]=='w' && red[3]==q) || (yellow[4]=='w' && green[3]==q) || (yellow[6]=='w' && orange[3]==q)) { if(q=='b') { while(blue[3]!=q || yellow[0]!='w') {rotate_clock('y');} } if(q=='r') { while(red[3]!=q || yellow[2]!='w') {rotate_clock('y');} if(q!='b') { while(white[0]!='w' && blue[7]!='b') {rotate_clock('w');} } } if(q=='g') { while(green[3]!=q || yellow[4]!='w') {rotate_clock('y');} if(q!='b') { while(white[0]!='w' && blue[7]!='b') {rotate_clock('w');} } } if(q=='o') { while(orange[3]!=q || yellow[6]!='w') {rotate_clock('y');} if(q!='b') { while(white[0]!='w' && blue[7]!='b') {rotate_clock('w');} } } rotate_clock(q);rotate_clock(q); } } void right_alg(char a,char c) { rotate_clock(a);rotate_clock(a);rotate_clock(a); rotate_clock('y');rotate_clock(a);white_bottom(c); } void white_right(char q) { if(blue[1]=='w' || red[1]=='w' || green[1]=='w' ||orange[1]=='w') { if(blue[5]==q && red[1]=='w') {right_alg('b',q);} if(red[5]==q && green[1]=='w') {right_alg('r',q);} if(green[5]==q && orange[1]=='w') {right_alg('g',q);} if(orange[5]==q && blue[1]=='w') {right_alg('o',q);} } } void left_alg(char a,char c) { rotate_clock(a);rotate_clock('y');rotate_clock(a); rotate_clock(a);rotate_clock(a);white_bottom(c); } void white_left(char q) { if(blue[5]=='w' || red[5]=='w' || green[5]=='w' ||orange[5]=='w') { if(blue[5]=='w' && red[1]==q) {left_alg('r',q);} if(red[5]=='w' && green[1]==q) {left_alg('g',q);} if(green[5]=='w' && orange[1]==q) {left_alg('o',q);} if(orange[5]=='w' && blue[1]==q) {left_alg('b',q);} } } void top_alg(char a,char b,char c) { rotate_clock(a);rotate_clock(a);rotate_clock(a); rotate_clock('w');rotate_clock(b);rotate_clock('w'); rotate_clock('w');rotate_clock('w');white_bottom(c); } void white_top(char q) { if(blue[7]=='w' && white[0]==q) {top_alg('b','r',q);} if(red[7]=='w' && white[2]==q) {top_alg('r','g',q);} if(green[7]=='w' && white[4]==q) {top_alg('g','o',q);} if(orange[7]=='w' && white[6]==q) {top_alg('o','b',q);} } void inv_alg(char a,char b,char c) { rotate_clock(a);rotate_clock(b);rotate_clock('y'); rotate_clock('y');rotate_clock('y');rotate_clock(b); rotate_clock(b);rotate_clock(b);rotate_clock(a); rotate_clock(a);rotate_clock(a);white_bottom(c); } void white_bottom_inverted(char q) { if(blue[3]=='w' || red[3]=='w' || green[3]=='w' || orange[3]=='w') { if(blue[3]=='w' && yellow[0]==q) {inv_alg('b','r',q);} if(red[3]=='w' && yellow[2]==q) {inv_alg('r','g',q);} if(green[3]=='w' && yellow[4]==q) {inv_alg('g','o',q);} if(orange[3]=='w' && yellow[6]==q) {inv_alg('o','b',q);} } } void solve_white_cross() { char prefer[4]={'b','r','g','o'}; for(int i=0;i<4;i++) { if(white[0]=='w' && blue[7]==prefer[i]){rotate_clock('b');} if(white[2]=='w' && red[7]==prefer[i]){rotate_clock('r');} if(white[4]=='w' && green[7]==prefer[i]){rotate_clock('g');} if(white[6]=='w' && orange[7]==prefer[i]){rotate_clock('o');} white_bottom(prefer[i]);white_bottom_inverted(prefer[i]);white_left(prefer[i]);white_right(prefer[i]);white_top(prefer[i]); if(i!=0) {while(blue[7]!='b'){rotate_clock('w');}} if(white[0]=='w' && white[2]=='w' && white[4]=='w' && white[6]=='w' &&blue[7]=='b' && red[7]=='r' && green[7]=='g' && orange[7]=='o') {break;} } } void white_corners_alg_left() { rotate_clock('b');rotate_clock('b');rotate_clock('b'); rotate_clock('y');rotate_clock('y');rotate_clock('y'); rotate_clock('b'); } void white_corners_alg_right() { rotate_clock('r'); rotate_clock('y'); rotate_clock('r');rotate_clock('r');rotate_clock('r'); } void solve_white_corners() { while(red[0]!='r' || red[6]!='r' || blue[0]!='b' || blue[6]!='b' || orange[0]!='o' || orange[6]!='o' || green[0]!='g' || green[6]!='g') { while(red[7]!='r') { rotate_clock('w'); } if(blue[4]=='w' || red[4]=='w' || green[4]=='w' || orange[4]=='w') { while(blue[4]!='w') { rotate_clock('y'); } while(red[2]!=red[7]) { rotate_clock('w'); } white_corners_alg_left(); while(red[7]!='r') { rotate_clock('w'); } } else if(blue[2]=='w' || red[2]=='w' || green[2]=='w' || orange[2]=='w') { while(red[2]!='w') { rotate_clock('y'); } while(red[7]!=yellow[1]) { rotate_clock('w'); } white_corners_alg_right(); while(red[7]!='r') { rotate_clock('w'); } } else if(yellow[1]=='w' || yellow[3]=='w' || yellow[5]=='w' || yellow[7]=='w') { while(yellow[1]!='w') { rotate_clock('y'); } while(red[2]!=blue[7]) { rotate_clock('w'); } rotate_clock('b');rotate_clock('b');rotate_clock('b'); rotate_clock('y');rotate_clock('y'); rotate_clock('b'); while(blue[4]!='w') { rotate_clock('y'); } while(red[2]!=red[7]) { rotate_clock('w'); } white_corners_alg_left(); while(red[7]!='r') { rotate_clock('w'); } } else { while(red[7]==red[0]) { rotate_clock('w'); } white_corners_alg_left(); while(red[7]!='r') { rotate_clock('w'); } } } } void middle_place_left_alg(char left,char center) { rotate_clock('y');rotate_clock('y');rotate_clock('y'); rotate_clock(left);rotate_clock(left);rotate_clock(left); rotate_clock('y'); rotate_clock(left); rotate_clock('y'); rotate_clock(center); rotate_clock('y');rotate_clock('y');rotate_clock('y'); rotate_clock(center);rotate_clock(center);rotate_clock(center); } void middle_place_right_alg(char center,char right) { rotate_clock('y'); rotate_clock(right); rotate_clock('y');rotate_clock('y');rotate_clock('y'); rotate_clock(right);rotate_clock(right);rotate_clock(right); rotate_clock('y');rotate_clock('y');rotate_clock('y'); rotate_clock(center);rotate_clock(center);rotate_clock(center); rotate_clock('y'); rotate_clock(center); } void solve_middle_layer() { while(red[5]!='r' || red[1]!='r' || blue[1]!='b' || blue[5]!='b' || orange[1]!='o' || orange[5]!='o' || green[1]!='g' || green[5]!='g') { if((orange[1]!='o' && green[5]!='g') && (orange[1]!='y' || green[5]!='y')) { while(green[3]!='y' && yellow[4]!='y') { rotate_clock('y'); } middle_place_right_alg('g','o'); } else if((orange[5]!='o' && blue[1]!='b') && (orange[5]!='y' || blue[1]!='y')) { while(orange[3]!='y' && yellow[6]!='y') { rotate_clock('y'); } middle_place_right_alg('o','b'); } else if((blue[5]!='b' && red[1]!='r') && (blue[5]!='y' || red[1]!='y')) { while(blue[3]!='y' && yellow[0]!='y') { rotate_clock('y'); } middle_place_right_alg('b','r'); } else if((red[5]!='r' && green[1]!='g') && (red[5]!='y' || green[1]!='y')) { while(red[3]!='y' && yellow[2]!='y') { rotate_clock('y'); } middle_place_right_alg('r','g'); } while(red[3]=='y' || yellow[2]=='y') { rotate_clock('y'); } if(red[3]=='r' && yellow[2]!='y') { if(yellow[2]=='g') { middle_place_right_alg('r','g'); } else if(yellow[2]='b') { middle_place_left_alg('b','r'); } } else if(red[3]=='b' && yellow[2]!='y') { rotate_clock('y'); if(yellow[0]=='r') { middle_place_right_alg('b','r'); } else if(yellow[0]='o') { middle_place_left_alg('o','b'); } } else if(red[3]=='o' && yellow[2]!='y') { rotate_clock('y');rotate_clock('y'); if(yellow[6]=='b') { middle_place_right_alg('o','b'); } else if(yellow[6]='g') { middle_place_left_alg('g','o'); } } else if(red[3]=='g' && yellow[2]!='y') { rotate_clock('y');rotate_clock('y');rotate_clock('y'); if(yellow[4]=='o') { middle_place_right_alg('g','o'); } else if(yellow[4]='r') { middle_place_left_alg('r','g'); } } } } void yellow_cross_algorithm() { rotate_clock('r'); rotate_clock('y'); rotate_clock('g'); rotate_clock('y');rotate_clock('y');rotate_clock('y'); rotate_clock('g');rotate_clock('g');rotate_clock('g'); rotate_clock('r');rotate_clock('r');rotate_clock('r'); } void solve_yellow_cross() { while(yellow[0]!='y' || yellow[2]!='y' || yellow[4]!='y' || yellow[6]!='y') { if((yellow[0]=='y' && yellow[6]=='y') || (yellow[4]=='y' && yellow[6]=='y') || (yellow[2]=='y' && yellow[4]=='y') || (yellow[0]=='y' && yellow[2]=='y')) { while(yellow[0]!='y' && yellow[6]!='y') { rotate_clock('y'); } yellow_cross_algorithm(); } if((yellow[2]=='y' && yellow[6]=='y') || (yellow[0]=='y' && yellow[4]=='y')) { while(yellow[0]!='y' && yellow[4]!='y') { rotate_clock('y'); } yellow_cross_algorithm(); yellow_cross_algorithm(); } else if(yellow[8]=='y') { yellow_cross_algorithm(); rotate_clock('y'); yellow_cross_algorithm(); yellow_cross_algorithm(); } } } void yellow_corners_algorithm() { rotate_clock('g'); rotate_clock('y'); rotate_clock('g');rotate_clock('g');rotate_clock('g'); rotate_clock('y'); rotate_clock('g'); rotate_clock('y');rotate_clock('y'); rotate_clock('g');rotate_clock('g');rotate_clock('g'); } void solve_yellow_corners() { while(yellow[1]!='y' || yellow[3]!='y' || yellow[5]!='y' || yellow[7]!='y') { if((yellow[1]=='y' && yellow[3]!='y' && yellow[5]!='y' && yellow[7]!='y') || (yellow[3]=='y' && yellow[1]!='y' && yellow[5]!='y' && yellow[7]!='y') || (yellow[5]=='y' && yellow[1]!='y' && yellow[3]!='y' && yellow[7]!='y') || (yellow[7]=='y' && yellow[1]!='y' && yellow[3]!='y' && yellow[5]!='y')) { while(yellow[1]!='y') { rotate_clock('y'); } yellow_corners_algorithm(); } else if((green[2]=='y' && green[4]=='y' && yellow[1]=='y' && yellow[7]=='y') || (orange[2]=='y' && orange[4]=='y' && yellow[1]=='y' && yellow[3]=='y') || (blue[2]=='y' && blue[4]=='y' && yellow[3]=='y' && yellow[5]=='y') || (red[2]=='y' && red[4]=='y' && yellow[5]=='y' && yellow[7]=='y')) { while(red[2]!='y' && red[4]!='y' && yellow[5]!='y' && yellow[7]!='y') { rotate_clock('y'); } yellow_corners_algorithm(); } else if((red[4]=='y' && orange[2]=='y' && yellow[1]=='y' && yellow[7]=='y') || (blue[2]=='y' && green[4]=='y' && yellow[1]=='y' && yellow[3]=='y') || (red[2]=='y' && orange[4]=='y' && yellow[3]=='y' && yellow[5]=='y') || (blue[4]=='y' && green[2]=='y' && yellow[5]=='y' && yellow[7]=='y')) { while(red[2]!='y' && orange[4]!='y' && yellow[3]!='y' && yellow[5]!='y') { rotate_clock('y'); } yellow_corners_algorithm(); } else if((green[2]=='y' && green[4]=='y' && blue[2]=='y' && blue[4]=='y') || (red[2]=='y' && red[4]=='y' && orange[2]=='y' && orange[4]=='y')) { while(green[2]!='y' && green[4]!='y' && blue[2]!='y' && blue[4]!='y') { rotate_clock('y'); } yellow_corners_algorithm(); } else if((green[2]=='y' && orange[2]=='y' && orange[4]=='y' && blue[4]=='y') || (red[4]=='y' && orange[2]=='y' && blue[2]=='y' && blue[4]=='y') || (red[2]=='y' && red[4]=='y' && green[4]=='y' && blue[2]=='y') || (green[2]=='y' && green[4]=='y' && orange[4]=='y' && red[2]=='y')) { while(green[2]!='y' && orange[2]!='y' && orange[4]!='y' && blue[4]!='y') { rotate_clock('y'); } yellow_corners_algorithm(); } else if((yellow[1]=='y' && yellow[5]=='y' && yellow[3]!='y' && yellow[7]!='y') || (yellow[3]=='y' && yellow[7]=='y' && yellow[1]!='y' && yellow[5]!='y')) { while(red[2]!='y' && green[4]!='y') { rotate_clock('y'); } yellow_corners_algorithm(); } } } void yellow_corner_orientation_algorithm() { rotate_clock('g');rotate_clock('g');rotate_clock('g'); rotate_clock('r'); rotate_clock('g');rotate_clock('g');rotate_clock('g'); rotate_clock('o');rotate_clock('o'); rotate_clock('g'); rotate_clock('r');rotate_clock('r');rotate_clock('r'); rotate_clock('g');rotate_clock('g');rotate_clock('g'); rotate_clock('o');rotate_clock('o'); rotate_clock('g');rotate_clock('g'); rotate_clock('y');rotate_clock('y');rotate_clock('y'); } void yellow_corner_orientation() { while(red[2]!='r' || red[4]!='r' || green[2]!='g' || green[4]!='g' || orange[2]!='o' || orange[4]!='o' || blue[2]!='b' || blue[4]!='b') { if((red[2]==red[4]) || (green[2]==green[4]) || (orange[2]==orange[4]) || (blue[2]==blue[4])) { while(orange[2]!=orange[4]) { rotate_clock('y'); } yellow_corner_orientation_algorithm(); while(blue[2]!='b') { rotate_clock('y'); } } else { while(orange[4]!='o' && red[4]!='r') { rotate_clock('y'); } yellow_corner_orientation_algorithm(); while(orange[2]!=orange[4]) { rotate_clock('y'); } yellow_corner_orientation_algorithm(); while(blue[2]!='b') { rotate_clock('y'); } } } } void yellow_edges_colour_arrangement_right() { rotate_clock('r');rotate_clock('r'); rotate_clock('y');rotate_clock('y');rotate_clock('y'); rotate_clock('g');rotate_clock('g');rotate_clock('g'); rotate_clock('b'); rotate_clock('r');rotate_clock('r'); rotate_clock('b');rotate_clock('b');rotate_clock('b'); rotate_clock('g'); rotate_clock('y');rotate_clock('y');rotate_clock('y'); rotate_clock('r');rotate_clock('r'); } void yellow_edges_colour_arrangement_left() { rotate_clock('r');rotate_clock('r'); rotate_clock('y'); rotate_clock('b'); rotate_clock('g');rotate_clock('g');rotate_clock('g'); rotate_clock('r');rotate_clock('r'); rotate_clock('b');rotate_clock('b');rotate_clock('b'); rotate_clock('g'); rotate_clock('y'); rotate_clock('r');rotate_clock('r'); } void yellow_edges_colour_arrangement() { while(red[2]!='r') { rotate_clock('r'); } if(red[3]=='o' && orange[3]=='r' && blue[3]=='g' && green[3]=='b') { yellow_edges_colour_arrangement_left(); } else if(red[3]=='b' && blue[3]=='r') { yellow_edges_colour_arrangement_left(); } else if(red[3]=='g' && green[3]=='r') { yellow_edges_colour_arrangement_left(); } while(orange[2]!=orange[3]) { rotate_clock('y'); } if(red[3]==green[2]) { yellow_edges_colour_arrangement_right(); } else if(red[3]==blue[2]) { yellow_edges_colour_arrangement_left(); } while(red[3]!='r') { rotate_clock('y'); } } int main() { cout<<"________________________| RUBIK'S CUBE SOLVER |________________________"<<endl<<endl; cout<<"Input :"<<endl<<endl; cout<<"White Side : "; for(int i=0;i<9;++i) {cin>>white[i];} cout<<"Red Side : "; for(int i=0;i<9;++i) {cin>>red[i];} cout<<"Orange Side : "; for(int i=0;i<9;++i) {cin>>orange[i];} cout<<"Blue Side : "; for(int i=0;i<9;++i) {cin>>blue[i];} cout<<"Green Side : "; for(int i=0;i<9;++i) {cin>>green[i];} cout<<"Yellow Side : "; for(int i=0;i<9;++i) {cin>>yellow[i];} //----------------------------------- cout<<"\n-------------------------------------------------\n"<<endl; cout<<"Turn these sides of the Cube in Clockwise Direction by 90 degrees in this exact order..."<<endl<<endl; solve_white_cross(); solve_white_corners(); solve_middle_layer(); solve_yellow_cross(); solve_yellow_corners(); yellow_corner_orientation(); yellow_edges_colour_arrangement(); //------------------------------------ cout<<"\n\n-------------------------------------------------"<<endl<<endl; cout<<"Your Rubik's Cube is now SOLVED!\n\nOutput : "<<endl<<endl; cout<<"White Side : "; display(white); cout<<"Red Side : "; display(red); cout<<"Orange Side : "; display(orange); cout<<"Blue Side : "; display(blue); cout<<"Green Side : "; display(green); cout<<"Yellow Side : "; display(yellow); return 0; }
[ "noreply@github.com" ]
noreply@github.com
b66cad6037bf363429fd7a2b0d37a80666e2491e
8edbf488e95a2f7c2b5e1d679909d2f3967eb515
/src/qt/receiverequestdialog.h
fb08d8bc0ffa9c20fcd703e85d2f783ed783c545
[ "MIT" ]
permissive
danigarcia3k/Sikacoin
34a30f977b629c318eca44b4c387612a4a7b1260
82ef600cfeed1d8f163df6071d8d080fb9dac6b0
refs/heads/master
2020-06-13T02:51:38.216755
2019-06-30T12:00:00
2019-06-30T12:00:00
194,507,821
0
0
null
null
null
null
UTF-8
C++
false
false
1,466
h
// Copyright (c) 2011-2016 The Sikacoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef SIKACOIN_QT_RECEIVEREQUESTDIALOG_H #define SIKACOIN_QT_RECEIVEREQUESTDIALOG_H #include "walletmodel.h" #include <QDialog> #include <QImage> #include <QLabel> #include <QPainter> class OptionsModel; namespace Ui { class ReceiveRequestDialog; } QT_BEGIN_NAMESPACE class QMenu; QT_END_NAMESPACE /* Label widget for QR code. This image can be dragged, dropped, copied and saved * to disk. */ class QRImageWidget : public QLabel { Q_OBJECT public: explicit QRImageWidget(QWidget *parent = 0); QImage exportImage(); public Q_SLOTS: void saveImage(); void copyImage(); protected: virtual void mousePressEvent(QMouseEvent *event); virtual void contextMenuEvent(QContextMenuEvent *event); private: QMenu *contextMenu; }; class ReceiveRequestDialog : public QDialog { Q_OBJECT public: explicit ReceiveRequestDialog(QWidget *parent = 0); ~ReceiveRequestDialog(); void setModel(OptionsModel *model); void setInfo(const SendCoinsRecipient &info); private Q_SLOTS: void on_btnCopyURI_clicked(); void on_btnCopyAddress_clicked(); void update(); private: Ui::ReceiveRequestDialog *ui; OptionsModel *model; SendCoinsRecipient info; }; #endif // SIKACOIN_QT_RECEIVEREQUESTDIALOG_H
[ "danigarcia3k@gmail.com" ]
danigarcia3k@gmail.com
054db4c0b3b032360245f1db1d5e308a955edcf8
5486c8a5695a885152a6ff0278f64bc32bbf64b9
/UVa/579 - Clock Hands.cpp
b1cb1440edee478184ded24a3bc442bd7655bea0
[]
no_license
emrul-chy/Competitive-Programming
3a3c5fd8fb41320d924c309873868a6d81585bf4
b22fddadaec2c40c1ffebaf594ded94434443662
refs/heads/master
2021-01-10T23:37:36.250883
2018-01-18T16:39:09
2018-01-18T16:39:09
70,418,520
2
1
null
null
null
null
UTF-8
C++
false
false
400
cpp
#include<stdio.h> #include<math.h> #include<stdlib.h> int main() { double h,m,t,i,j,k,l,n,a; while(scanf("%lf:%lf", &h, &m)==2) { if(h==0 && m==0) break; i=((h*30)+(m/2)); j=(m*6); t=i-j; if(t<0) t*=-1; if(t>180) t=360-t; printf("%.3lf\n",t); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
f7a40e560b99208c406276be18e9ce9385471eab
0c72ce623d47fb6b64aa565c40d79e1f49a9b1f6
/cpp/pyWrapper/wrapper.cpp
05725476ecb7bc5e391752a9eea40680f9bba133
[]
no_license
prassanna-ravishankar/SherwoodMod
5a30bfcf93d9d31eda28428acb1dedcb0920c11d
e40419ee7383f0d23e85fa3fc402aa03aceb9e97
refs/heads/master
2021-08-27T15:45:49.421234
2016-04-07T13:43:21
2016-04-07T13:43:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,051
cpp
// // Created by prassanna on 4/04/16. // #include <boost/python.hpp> #include <boost/numpy.hpp> #include <stdexcept> #include <stdio.h> #include <string> #include <iostream> #include <fstream> #include "Platform.h" #include "Graphics.h" #include "dibCodec.h" #include "Sherwood.h" #include "CumulativeNormalDistribution.h" #include "DataPointCollection.h" #include "Classification.h" #include "DensityEstimation.h" #include "SemiSupervisedClassification.h" #include "Regression.h" #include <boost/program_options.hpp> #include "NumPyArrayData.h" namespace bp = boost::python; namespace np = boost::numpy; using namespace MicrosoftResearch::Cambridge::Sherwood; #define ASSERT_THROW(a,msg) if (!(a)) throw std::runtime_error(msg); //Defaults std::auto_ptr<DataPointCollection> test_train_data; std::auto_ptr<Forest<LinearFeatureResponseSVM, HistogramAggregator> > forest; TrainingParameters trainingParameters; LinearFeatureSVMFactory featureFactory; np::ndarray divideByTwo(const np::ndarray& arr) { ASSERT_THROW( (arr.get_nd() == 2), "Expected two-dimensional array"); ASSERT_THROW( (arr.get_dtype() == np::dtype::get_builtin<double>()), "Expected array of type double (np.float64)"); np::ndarray result = np::zeros(bp::make_tuple(arr.shape(0),arr.shape(1)), np::dtype::get_builtin<double>()); NumPyArrayData<double> arr_data(arr); NumPyArrayData<double> result_data(result); for (int i=0; i<arr.shape(0); i++) { for (int j=0; j<arr.shape(1); j++) { result_data(i,j) = arr_data(i,j) / 2.0; } } return result; } bool loadData(const np::ndarray& arr, const np::ndarray& lbls) { ASSERT_THROW( (arr.get_nd() == 2), "Expected two-dimensional Data array"); ASSERT_THROW( (arr.get_dtype() == np::dtype::get_builtin<double>()), "Expected array of type double (np.float64)"); ASSERT_THROW( (lbls.get_dtype() == np::dtype::get_builtin<double>()), "Expected array of type double (np.float64)"); ASSERT_THROW( (lbls.get_nd() == 1), "Expected one-dimensional Label array"); NumPyArrayData<double> arr_data(arr); NumPyArrayData<double> lbl_data(lbls); test_train_data = std::auto_ptr<DataPointCollection>(new DataPointCollection()); std::vector<float> row; test_train_data->dimension_ = arr.shape(1); int count = 0; for(int i = 0;i<arr.shape(0);i++) { for(int j=0;j<arr.shape(1);j++) test_train_data->data_.push_back ((float)arr_data(i,j)); count++; } for(int i = 0;i<lbls.shape(0);i++) { test_train_data->labels_.push_back ((int)lbl_data(i)); } return (count == test_train_data->labels_.size ()); } bool setDefaultParams() { //Defaults trainingParameters.MaxDecisionLevels = 10; trainingParameters.NumberOfCandidateFeatures = 10; trainingParameters.NumberOfCandidateThresholdsPerFeature = 10; trainingParameters.NumberOfTrees = 10; trainingParameters.Verbose = true; trainingParameters.svm_c = 0.5; } bool setMaxDecisionLevels(int n) { trainingParameters.MaxDecisionLevels = n; return true; } bool setNumberOfCandidateFeatures(int n) { trainingParameters.NumberOfCandidateFeatures = n; return true; } bool setNumberOfThresholds(int n) { trainingParameters.NumberOfCandidateThresholdsPerFeature = n; return true; } bool setTrees(int n) { trainingParameters.NumberOfTrees = n; return true; } bool setQuiet(bool choice) { trainingParameters.Verbose = !choice; return true; } bool setSVM_C(float c) { trainingParameters.svm_c = c; return true; } bool onlyTrain() { forest = ClassificationDemo<LinearFeatureResponseSVM>::Train(*test_train_data, &featureFactory, trainingParameters); return true; } bool saveModel(std::string filename) { forest->Serialize(filename); return true; } bool loadModel(std::string filename) { forest = Forest<LinearFeatureResponseSVM, HistogramAggregator>::Deserialize(filename); return true; } //For 2 class problems np::ndarray onlyTest() { int nr_classes = 2; std::vector<HistogramAggregator> distbns; ClassificationDemo<LinearFeatureResponseSVM>::Test(*forest.get(), *test_train_data.get(), distbns); np::ndarray result = np::zeros(bp::make_tuple(distbns.size(),nr_classes), np::dtype::get_builtin<double>()); NumPyArrayData<double> result_data(result); for (int i=0; i<result.shape(0); i++) { float sum = distbns[i].bins_[0]+distbns[i].bins_[1]; result_data(i,0) = distbns[i].bins_[0]/(double)sum; result_data(i,1) = distbns[i].bins_[1]/(double)sum; } return result; } bp::tuple createGridArray(int rows, int cols) { np::ndarray xgrid = np::zeros(bp::make_tuple(rows, cols), np::dtype::get_builtin<int>()); np::ndarray ygrid = np::zeros(bp::make_tuple(rows, cols), np::dtype::get_builtin<int>()); NumPyArrayData<int> xgrid_data(xgrid); NumPyArrayData<int> ygrid_data(ygrid); for (int i=0; i<rows; i++) { for (int j=0; j<cols; j++) { xgrid_data(i,j) = i; ygrid_data(i,j) = j; } } return bp::make_tuple(xgrid,ygrid); } BOOST_PYTHON_MODULE(Rfsvm) { np::initialize(); bp::def("loadData", loadData, bp::args("Features", "Labels")); bp::def("onlyTrain", onlyTrain); bp::def("setDefaultParams", setDefaultParams); bp::def("onlyTest", onlyTest); bp::def("saveModel", saveModel); bp::def("loadModel", loadModel); bp::def("setMaxDescionLevels", setMaxDecisionLevels); bp::def("setNumberOfCandidateFeatures",setNumberOfCandidateFeatures); bp::def("setNumberOfThresholds",setNumberOfThresholds); bp::def("setTrees",setTrees); bp::def("setQuiet",setQuiet); bp::def("setSVM_C",setSVM_C); }
[ "prassi89@gmail.com" ]
prassi89@gmail.com
0e93f1430ca567dbeecf8b8fae83e960fe07194d
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/iecp/include/tencentcloud/iecp/v20210914/model/DeleteIotDeviceBatchResponse.h
f296163ca1b01bea3a0ddc2fdca177feecde48c7
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
1,648
h
/* * 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. */ #ifndef TENCENTCLOUD_IECP_V20210914_MODEL_DELETEIOTDEVICEBATCHRESPONSE_H_ #define TENCENTCLOUD_IECP_V20210914_MODEL_DELETEIOTDEVICEBATCHRESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Iecp { namespace V20210914 { namespace Model { /** * DeleteIotDeviceBatch返回参数结构体 */ class DeleteIotDeviceBatchResponse : public AbstractModel { public: DeleteIotDeviceBatchResponse(); ~DeleteIotDeviceBatchResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); std::string ToJsonString() const; private: }; } } } } #endif // !TENCENTCLOUD_IECP_V20210914_MODEL_DELETEIOTDEVICEBATCHRESPONSE_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
f4be28641f28345a3eb5c59ecf5e640ba848dc76
8957253105acc4b83d58f27ec7ff85c77d3543ae
/021 Merge Two Sorted Lists/MergeTwoSortedList/MergeTwoSortedList/MergeTwoSortedList.cpp
682448b52490640e3a3581d939a32070c1aa6380
[]
no_license
XiFanHeNai/Leetcode
3d0514ea20c9a137653150dfe1fd2a918244021d
b444cd70c16159dd14bd4116b87804574d54f440
refs/heads/master
2021-01-10T22:31:36.155046
2019-03-18T12:58:46
2019-03-18T12:58:46
70,398,086
0
0
null
null
null
null
UTF-8
C++
false
false
853
cpp
#include <iostream> #include <cstdlib> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x):val(x),next(NULL){} }; ListNode * CreateList(int* a, int len) { if (len == 0) return NULL; int index=0; ListNode *head = new ListNode(0); if (head == NULL) return NULL; head->val = a[0]; head->next = NULL; ListNode *temp = head; while(index++ < len-1) { ListNode* Node = (ListNode*)malloc(sizeof(struct ListNode)); Node->val = a[index]; Node->next = NULL; temp->next = Node; temp = temp->next; } return head; } class Solution { public: Solution():l1(&ListNode(0)),l2(&ListNode(0)){} ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { } private: ListNode *l1; ListNode *l2; }; int main() { int a[] = {3,5,8,11,13,14,15}; ListNode * list1 = CreateList(a,7); return 0; }
[ "cj1252077975@163.com" ]
cj1252077975@163.com
0c21e845a28497437d74839b4dbbce29e9263dd7
8ae7a23f05805fd71d4be13686cf35d8994762ed
/mame150/src/mame/includes/appoooh.h
886967e254c354daf96f8df93050d26c7029204f
[]
no_license
cyberkni/276in1JAMMA
fb06ccc6656fb4346808a24beed8977996da91b2
d1a68172d4f3490cf7f6e7db25d5dfd4cde3bb22
refs/heads/master
2021-01-18T09:38:36.974037
2013-10-07T18:30:02
2013-10-07T18:30:02
13,152,960
1
0
null
null
null
null
UTF-8
C++
false
false
2,389
h
#include "sound/msm5205.h" class appoooh_state : public driver_device { public: appoooh_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_spriteram(*this, "spriteram"), m_fg_videoram(*this, "fg_videoram"), m_fg_colorram(*this, "fg_colorram"), m_spriteram_2(*this, "spriteram_2"), m_bg_videoram(*this, "bg_videoram"), m_bg_colorram(*this, "bg_colorram"), m_msm(*this, "msm"), m_maincpu(*this, "maincpu") { } /* memory pointers */ required_shared_ptr<UINT8> m_spriteram; required_shared_ptr<UINT8> m_fg_videoram; required_shared_ptr<UINT8> m_fg_colorram; required_shared_ptr<UINT8> m_spriteram_2; required_shared_ptr<UINT8> m_bg_videoram; required_shared_ptr<UINT8> m_bg_colorram; /* video-related */ tilemap_t *m_fg_tilemap; tilemap_t *m_bg_tilemap; int m_scroll_x; int m_priority; /* sound-related */ UINT32 m_adpcm_data; UINT32 m_adpcm_address; /* devices */ required_device<msm5205_device> m_msm; UINT8 m_nmi_mask; DECLARE_WRITE8_MEMBER(appoooh_adpcm_w); DECLARE_WRITE8_MEMBER(appoooh_scroll_w); DECLARE_WRITE8_MEMBER(appoooh_fg_videoram_w); DECLARE_WRITE8_MEMBER(appoooh_fg_colorram_w); DECLARE_WRITE8_MEMBER(appoooh_bg_videoram_w); DECLARE_WRITE8_MEMBER(appoooh_bg_colorram_w); DECLARE_WRITE8_MEMBER(appoooh_out_w); DECLARE_DRIVER_INIT(robowres); DECLARE_DRIVER_INIT(robowresb); TILE_GET_INFO_MEMBER(get_fg_tile_info); TILE_GET_INFO_MEMBER(get_bg_tile_info); virtual void machine_start(); virtual void machine_reset(); DECLARE_VIDEO_START(appoooh); DECLARE_PALETTE_INIT(appoooh); DECLARE_PALETTE_INIT(robowres); UINT32 screen_update_appoooh(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); UINT32 screen_update_robowres(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); INTERRUPT_GEN_MEMBER(vblank_irq); void appoooh_draw_sprites( bitmap_ind16 &dest_bmp, const rectangle &cliprect, gfx_element *gfx, UINT8 *sprite ); void robowres_draw_sprites( bitmap_ind16 &dest_bmp, const rectangle &cliprect, gfx_element *gfx, UINT8 *sprite ); DECLARE_WRITE_LINE_MEMBER(appoooh_adpcm_int); required_device<cpu_device> m_maincpu; }; #define CHR1_OFST 0x00 /* palette page of char set #1 */ #define CHR2_OFST 0x10 /* palette page of char set #2 */
[ "dan@van.derveer.com" ]
dan@van.derveer.com
00d9d5d5a11665e13f9dc0ac8c3de8cf9aa6b13f
6667353c8e55fad1a7e9b27afd40c55118522b60
/dep/gpis/include/gpis/sampler/prior/Mean.h
a576899ad8ad7f9bf31f295925f5b4336b029b90
[]
no_license
Bardo91/grasping_tools
c9a9b37d95a9d28f849e713011eb6da3169d6c47
c93ae54c3c3acc4efd7ad44af012918f1717c5f8
refs/heads/master
2021-03-27T09:51:36.586405
2019-03-27T23:29:04
2019-03-27T23:29:04
97,807,359
3
0
null
null
null
null
UTF-8
C++
false
false
827
h
#ifndef GPIS_SAMPLER_PRIOR_MEAN_H_ #define GPIS_SAMPLER_PRIOR_MEAN_H_ #include <functional> #include <armadillo> namespace gpis{ class Mean{ public: /// Compute the mean of a set of points.. /// \param points: /// \param computeGradients: arma::mat operator()(const arma::mat &_points, const arma::vec &_parameters, bool computeGradients = false) const; /// Abstract method. Given a point and the parameters, it computes the mean value funtion. virtual double meanFun(const arma::vec& _point, const arma::vec &_parameters) const = 0; /// Abstract method. Given a point and the parameters, it computes the derivatives of the mean value funtion. virtual arma::vec meanGradsFun(const arma::vec& _point, const arma::vec &_parameters) const = 0; }; } // namespace gpis #endif // GPIS_SAMPLER_PRIOR_MEAN_H_
[ "19Bardo91@gmail.com" ]
19Bardo91@gmail.com
536024469bb5094374f31eeaf092d3d706c35c77
c6907f3adc9e3a930a124c852604f19efb359165
/src/utilstrencodings.h
c1d7cd0d848f6ef16dec2e3baddee19c6bb050fd
[ "MIT" ]
permissive
omnistoreservice/omnistorecoin
c489a1e323251addbc15971f51ae4edb510ea03a
ca157bbd52d719f2c84e38bf0b4bfe8a4a652270
refs/heads/master
2020-07-12T04:34:17.834882
2019-09-02T10:30:42
2019-09-02T10:30:42
204,719,354
0
0
null
null
null
null
UTF-8
C++
false
false
4,341
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017 The OmniStoreCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Utilities for converting data from/to strings. */ #ifndef BITCOIN_UTILSTRENCODINGS_H #define BITCOIN_UTILSTRENCODINGS_H #include "allocators.h" #include <stdint.h> #include <string> #include <vector> #define BEGIN(a) ((char*)&(a)) #define END(a) ((char*)&((&(a))[1])) #define UBEGIN(a) ((unsigned char*)&(a)) #define UEND(a) ((unsigned char*)&((&(a))[1])) #define ARRAYLEN(array) (sizeof(array) / sizeof((array)[0])) /** This is needed because the foreach macro can't get over the comma in pair<t1, t2> */ #define PAIRTYPE(t1, t2) std::pair<t1, t2> std::string SanitizeString(const std::string& str); std::vector<unsigned char> ParseHex(const char* psz); std::vector<unsigned char> ParseHex(const std::string& str); signed char HexDigit(char c); bool IsHex(const std::string& str); std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL); std::string DecodeBase64(const std::string& str); std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const std::string& str); SecureString DecodeBase64Secure(const SecureString& input); SecureString EncodeBase64Secure(const SecureString& input); std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL); std::string DecodeBase32(const std::string& str); std::string EncodeBase32(const unsigned char* pch, size_t len); std::string EncodeBase32(const std::string& str); std::string i64tostr(int64_t n); std::string itostr(int n); int64_t atoi64(const char* psz); int64_t atoi64(const std::string& str); int atoi(const std::string& str); /** * Convert string to signed 32-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ bool ParseInt32(const std::string& str, int32_t *out); /** * Convert string to signed 64-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ bool ParseInt64(const std::string& str, int64_t *out); /** * Convert string to double with strict parse error feedback. * @returns true if the entire string could be parsed as valid double, * false if not the entire string could be parsed or when overflow or underflow occurred. */ bool ParseDouble(const std::string& str, double *out); template <typename T> std::string HexStr(const T itbegin, const T itend, bool fSpaces = false) { std::string rv; static const char hexmap[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; rv.reserve((itend - itbegin) * 3); for (T it = itbegin; it < itend; ++it) { unsigned char val = (unsigned char)(*it); if (fSpaces && it != itbegin) rv.push_back(' '); rv.push_back(hexmap[val >> 4]); rv.push_back(hexmap[val & 15]); } return rv; } template <typename T> inline std::string HexStr(const T& vch, bool fSpaces = false) { return HexStr(vch.begin(), vch.end(), fSpaces); } /** Reverse the endianess of a string */ inline std::string ReverseEndianString(std::string in) { std::string out = ""; unsigned int s = in.size(); for (unsigned int i = 0; i < s; i += 2) { out += in.substr(s - i - 2, 2); } return out; } /** * Format a paragraph of text to a fixed width, adding spaces for * indentation to any added line. */ std::string FormatParagraph(const std::string in, size_t width = 79, size_t indent = 0); /** * Timing-attack-resistant comparison. * Takes time proportional to length * of first argument. */ template <typename T> bool TimingResistantEqual(const T& a, const T& b) { if (b.size() == 0) return a.size() == 0; size_t accumulator = a.size() ^ b.size(); for (size_t i = 0; i < a.size(); i++) accumulator |= a[i] ^ b[i % b.size()]; return accumulator == 0; } #endif // BITCOIN_UTILSTRENCODINGS_H
[ "debian@debian" ]
debian@debian
f1b6365956d5e1cdcf755745982957e5153b3703
2bec5a52ce1fb3266e72f8fbeb5226b025584a16
/TauStar/src/red_black_tree.cpp
cc85ebc7195b5f38267cd4ec03ee4baa1d224e6b
[]
no_license
akhikolla/InformationHouse
4e45b11df18dee47519e917fcf0a869a77661fce
c0daab1e3f2827fd08aa5c31127fadae3f001948
refs/heads/master
2023-02-12T19:00:20.752555
2020-12-31T20:59:23
2020-12-31T20:59:23
325,589,503
9
2
null
null
null
null
UTF-8
C++
false
false
23,026
cpp
/*** * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that neither the name of Emin * Martinian nor the names of any contributors are 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. */ #include "red_black_tree.h" /***********************************************************************/ /* FUNCTION: RBTreeCreate */ /**/ /* INPUTS: All the inputs are names of functions. CompFunc takes to */ /* void pointers to keys and returns 1 if the first arguement is */ /* "greater than" the second. DestFunc takes a pointer to a key and */ /* destroys it in the appropriate manner when the node containing that */ /* key is deleted. InfoDestFunc is similiar to DestFunc except it */ /* recieves a pointer to the info of a node and destroys it. */ /* PrintFunc recieves a pointer to the key of a node and prints it. */ /* PrintInfo recieves a pointer to the info of a node and prints it. */ /* If RBTreePrint is never called the print functions don't have to be */ /* defined and NullFunction can be used. */ /**/ /* OUTPUT: This function returns a pointer to the newly created */ /* red-black tree. */ /**/ /* Modifies Input: none */ /***********************************************************************/ rb_red_blk_tree* RBTreeCreate( int (*CompFunc) (const void*,const void*), void (*DestFunc) (void*), void (*InfoDestFunc) (void*), void (*PrintFunc) (const void*), void (*PrintInfo)(void*)) { rb_red_blk_tree* newTree; rb_red_blk_node* temp; newTree=(rb_red_blk_tree*) SafeMalloc(sizeof(rb_red_blk_tree)); newTree->Compare= CompFunc; newTree->DestroyKey= DestFunc; newTree->PrintKey= PrintFunc; newTree->PrintInfo= PrintInfo; newTree->DestroyInfo= InfoDestFunc; /* see the comment in the rb_red_blk_tree structure in red_black_tree.h */ /* for information on nil and root */ temp=newTree->nil= (rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node)); temp->parent=temp->left=temp->right=temp; temp->red=0; temp->key=0; temp->leftSize=0; temp->rightSize=0; temp->numInstances=0; temp=newTree->root= (rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node)); temp->parent=temp->left=temp->right=newTree->nil; temp->key=0; temp->red=0; temp->leftSize=0; temp->rightSize=0; temp->numInstances=0; return(newTree); } /***********************************************************************/ /* FUNCTION: LeftRotate */ /**/ /* INPUTS: This takes a tree so that it can access the appropriate */ /* root and nil pointers, and the node to rotate on. */ /**/ /* OUTPUT: None */ /**/ /* Modifies Input: tree, x */ /**/ /* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */ /* Cormen, Leiserson, Rivest (Chapter 14). Basically this */ /* makes the parent of x be to the left of x, x the parent of */ /* its parent before the rotation and fixes other pointers */ /* accordingly. */ /***********************************************************************/ void LeftRotate(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* y; rb_red_blk_node* nil=tree->nil; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ /* very subtle bug because sometimes this function modifies */ /* the parent pointer of nil. This can be a problem if a */ /* function which calls LeftRotate also uses the nil sentinel */ /* and expects the nil sentinel's parent pointer to be unchanged */ /* after calling this function. For example, when RBDeleteFixUP */ /* calls LeftRotate it expects the parent pointer of nil to be */ /* unchanged. */ y=x->right; x->right=y->left; if (y->left != nil) y->left->parent=x; /* used to use sentinel here */ /* and do an unconditional assignment instead of testing for nil */ y->parent=x->parent; /* instead of checking if x->parent is the root as in the book, we */ /* count on the root sentinel to implicitly take care of this case */ if( x == x->parent->left) { x->parent->left=y; } else { x->parent->right=y; } y->left=x; x->parent=y; x->rightSize = y->leftSize; y->leftSize = x->numInstances + x->rightSize + x->leftSize; #ifdef DEBUG_ASSERT Assert(!tree->nil->red, "nil not red in LeftRotate"); #endif } /***********************************************************************/ /* FUNCTION: RighttRotate */ /**/ /* INPUTS: This takes a tree so that it can access the appropriate */ /* root and nil pointers, and the node to rotate on. */ /**/ /* OUTPUT: None */ /**/ /* Modifies Input?: tree, y */ /**/ /* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */ /* Cormen, Leiserson, Rivest (Chapter 14). Basically this */ /* makes the parent of x be to the left of x, x the parent of */ /* its parent before the rotation and fixes other pointers */ /* accordingly. */ /***********************************************************************/ void RightRotate(rb_red_blk_tree* tree, rb_red_blk_node* y) { rb_red_blk_node* x; rb_red_blk_node* nil=tree->nil; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ /* very subtle bug because sometimes this function modifies */ /* the parent pointer of nil. This can be a problem if a */ /* function which calls LeftRotate also uses the nil sentinel */ /* and expects the nil sentinel's parent pointer to be unchanged */ /* after calling this function. For example, when RBDeleteFixUP */ /* calls LeftRotate it expects the parent pointer of nil to be */ /* unchanged. */ x=y->left; y->left=x->right; if (nil != x->right) x->right->parent=y; /*used to use sentinel here */ /* and do an unconditional assignment instead of testing for nil */ /* instead of checking if x->parent is the root as in the book, we */ /* count on the root sentinel to implicitly take care of this case */ x->parent=y->parent; if( y == y->parent->left) { y->parent->left=x; } else { y->parent->right=x; } x->right=y; y->parent=x; y->leftSize = x->rightSize; x->rightSize = y->numInstances + y->leftSize + y->rightSize; #ifdef DEBUG_ASSERT Assert(!tree->nil->red, "nil not red in RightRotate"); #endif } /***********************************************************************/ /* FUNCTION: TreeInsertHelp */ /**/ /* INPUTS: tree is the tree to insert into and z is the node to insert */ /**/ /* OUTPUT: none */ /**/ /* Modifies Input: tree, z */ /**/ /* EFFECTS: Inserts z into the tree as if it were a regular binary tree */ /* using the algorithm described in _Introduction_To_Algorithms_ */ /* by Cormen et al. This funciton is only intended to be called */ /* by the RBTreeInsert function and not by the user */ /***********************************************************************/ void TreeInsertHelp(rb_red_blk_tree* tree, rb_red_blk_node* z) { /* This function should only be called by InsertRBTree (see above) */ rb_red_blk_node* x; rb_red_blk_node* y; rb_red_blk_node* nil=tree->nil; rb_red_blk_node* lastNode; rb_red_blk_node* currentNode; z->left=z->right=nil; y=tree->root; x=tree->root->left; while( x != nil) { y=x; if (1 == tree->Compare(x->key,z->key)) { /* x.key > z.key */ x=x->left; } else { /* x.key <= z.key */ x=x->right; } } z->parent = y; if(!(y == tree->root) && (0 == tree->Compare(y->key,z->key))) { y->numInstances += 1; z->numInstances = -1; lastNode = y; currentNode = y->parent; } else { if ( (y == tree->root) || (1 == tree->Compare(y->key,z->key))) { // y.key > z.key y->left=z; } else { y->right=z; } lastNode = z; currentNode = z->parent; } while(currentNode != nil) { if(currentNode->left == lastNode) { currentNode->leftSize += 1; } else { currentNode->rightSize += 1; } lastNode = currentNode; currentNode = currentNode->parent; } #ifdef DEBUG_ASSERT Assert(!tree->nil->red, "nil not red in TreeInsertHelp"); #endif } /* Before calling Insert RBTree the node x should have its key set */ /***********************************************************************/ /* FUNCTION: RBTreeInsert */ /**/ /* INPUTS: tree is the red-black tree to insert a node which has a key */ /* pointed to by key and info pointed to by info. */ /**/ /* OUTPUT: This function returns a pointer to the newly inserted node */ /* which is guarunteed to be valid until this node is deleted. */ /* What this means is if another data structure stores this */ /* pointer then the tree does not need to be searched when this */ /* is to be deleted. */ /**/ /* Modifies Input: tree */ /**/ /* EFFECTS: Creates a node node which contains the appropriate key and */ /* info pointers and inserts it into the tree. */ /***********************************************************************/ rb_red_blk_node * RBTreeInsert(rb_red_blk_tree* tree, void* key, void* info) { rb_red_blk_node * y; rb_red_blk_node * x; rb_red_blk_node * newNode; x=(rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node)); x->key=key; x->info=info; x->leftSize=0; x->rightSize=0; x->numInstances=1; TreeInsertHelp(tree,x); if(-1 == x->numInstances) { y = x->parent; free(x); return(y); } newNode=x; x->red=1; while(x->parent->red) { /* use sentinel instead of checking for root */ if (x->parent == x->parent->parent->left) { y=x->parent->parent->right; if (y->red) { x->parent->red=0; y->red=0; x->parent->parent->red=1; x=x->parent->parent; } else { if (x == x->parent->right) { x=x->parent; LeftRotate(tree,x); } x->parent->red=0; x->parent->parent->red=1; RightRotate(tree,x->parent->parent); } } else { /* case for x->parent == x->parent->parent->right */ y=x->parent->parent->left; if (y->red) { x->parent->red=0; y->red=0; x->parent->parent->red=1; x=x->parent->parent; } else { if (x == x->parent->left) { x=x->parent; RightRotate(tree,x); } x->parent->red=0; x->parent->parent->red=1; LeftRotate(tree,x->parent->parent); } } } tree->root->left->red=0; return(newNode); #ifdef DEBUG_ASSERT Assert(!tree->nil->red, "nil not red in RBTreeInsert"); Assert(!tree->root->red, "root not red in RBTreeInsert"); #endif } /***********************************************************************/ /* FUNCTION: TreeSuccessor */ /**/ /* INPUTS: tree is the tree in question, and x is the node we want the */ /* the successor of. */ /**/ /* OUTPUT: This function returns the successor of x or NULL if no */ /* successor exists. */ /**/ /* Modifies Input: none */ /**/ /* Note: uses the algorithm in _Introduction_To_Algorithms_ */ /***********************************************************************/ rb_red_blk_node* TreeSuccessor(rb_red_blk_tree* tree,rb_red_blk_node* x) { rb_red_blk_node* y; rb_red_blk_node* nil=tree->nil; rb_red_blk_node* root=tree->root; if (nil != (y = x->right)) { /* assignment to y is intentional */ while(y->left != nil) { /* returns the minium of the right subtree of x */ y=y->left; } return(y); } else { y=x->parent; while(x == y->right) { /* sentinel used instead of checking for nil */ x=y; y=y->parent; } if (y == root) return(nil); return(y); } } /***********************************************************************/ /* FUNCTION: Treepredecessor */ /**/ /* INPUTS: tree is the tree in question, and x is the node we want the */ /* the predecessor of. */ /**/ /* OUTPUT: This function returns the predecessor of x or NULL if no */ /* predecessor exists. */ /**/ /* Modifies Input: none */ /**/ /* Note: uses the algorithm in _Introduction_To_Algorithms_ */ /***********************************************************************/ rb_red_blk_node* TreePredecessor(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* y; rb_red_blk_node* nil=tree->nil; rb_red_blk_node* root=tree->root; if (nil != (y = x->left)) { /* assignment to y is intentional */ while(y->right != nil) { /* returns the maximum of the left subtree of x */ y=y->right; } return(y); } else { y=x->parent; while(x == y->left) { if (y == root) return(nil); x=y; y=y->parent; } return(y); } } /***********************************************************************/ /* FUNCTION: InorderTreePrint */ /**/ /* INPUTS: tree is the tree to print and x is the current inorder node */ /**/ /* OUTPUT: none */ /**/ /* EFFECTS: This function recursively prints the nodes of the tree */ /* inorder using the PrintKey and PrintInfo functions. */ /**/ /* Modifies Input: none */ /**/ /* Note: This function should only be called from RBTreePrint */ /***********************************************************************/ void InorderTreePrint(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* nil=tree->nil; rb_red_blk_node* root=tree->root; if (x != tree->nil) { InorderTreePrint(tree,x->left); Rprintf("info="); tree->PrintInfo(x->info); Rprintf(" key="); tree->PrintKey(x->key); Rprintf(" l->key="); if( x->left == nil) Rprintf("NULL"); else tree->PrintKey(x->left->key); Rprintf(" r->key="); if( x->right == nil) Rprintf("NULL"); else tree->PrintKey(x->right->key); Rprintf(" p->key="); if( x->parent == root) Rprintf("NULL"); else tree->PrintKey(x->parent->key); Rprintf(" red=%i\n",x->red); InorderTreePrint(tree,x->right); } } /***********************************************************************/ /* FUNCTION: TreeDestHelper */ /**/ /* INPUTS: tree is the tree to destroy and x is the current node */ /**/ /* OUTPUT: none */ /**/ /* EFFECTS: This function recursively destroys the nodes of the tree */ /* postorder using the DestroyKey and DestroyInfo functions. */ /**/ /* Modifies Input: tree, x */ /**/ /* Note: This function should only be called by RBTreeDestroy */ /***********************************************************************/ void TreeDestHelper(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* nil=tree->nil; if (x != nil) { TreeDestHelper(tree,x->left); TreeDestHelper(tree,x->right); //tree->DestroyKey(x->key); tree->DestroyInfo(x->info); free(x); } } /***********************************************************************/ /* FUNCTION: RBTreeDestroy */ /**/ /* INPUTS: tree is the tree to destroy */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: Destroys the key and frees memory */ /**/ /* Modifies Input: tree */ /**/ /***********************************************************************/ void RBTreeDestroy(rb_red_blk_tree* tree) { TreeDestHelper(tree,tree->root->left); free(tree->root); free(tree->nil); free(tree); } /***********************************************************************/ /* FUNCTION: RBTreePrint */ /**/ /* INPUTS: tree is the tree to print */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: This function recursively prints the nodes of the tree */ /* inorder using the PrintKey and PrintInfo functions. */ /**/ /* Modifies Input: none */ /**/ /***********************************************************************/ void RBTreePrint(rb_red_blk_tree* tree) { InorderTreePrint(tree,tree->root->left); } /***********************************************************************/ /* FUNCTION: RBExactQuery */ /**/ /* INPUTS: tree is the tree to print and q is a pointer to the key */ /* we are searching for */ /**/ /* OUTPUT: returns the a node with key equal to q. If there are */ /* multiple nodes with key equal to q this function returns */ /* the one highest in the tree */ /**/ /* Modifies Input: none */ /**/ /***********************************************************************/ rb_red_blk_node* RBExactQuery(rb_red_blk_tree* tree, void* q) { rb_red_blk_node* x=tree->root->left; rb_red_blk_node* nil=tree->nil; int compVal; if (x == nil) return(0); compVal=tree->Compare(x->key,(int*) q); while(0 != compVal) {/*assignemnt*/ if (1 == compVal) { /* x->key > q */ x=x->left; } else { x=x->right; } if ( x == nil) return(0); compVal=tree->Compare(x->key,(int*) q); } return(x); } /***********************************************************************/ /* FUNCTION: RBDeleteFixUp */ /**/ /* INPUTS: tree is the tree to fix and x is the child of the spliced */ /* out node in RBTreeDelete. */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: Performs rotations and changes colors to restore red-black */ /* properties after a node is deleted */ /**/ /* Modifies Input: tree, x */ /**/ /* The algorithm from this function is from _Introduction_To_Algorithms_ */ /***********************************************************************/ void RBDeleteFixUp(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* root=tree->root->left; rb_red_blk_node* w; while( (!x->red) && (root != x)) { if (x == x->parent->left) { w=x->parent->right; if (w->red) { w->red=0; x->parent->red=1; LeftRotate(tree,x->parent); w=x->parent->right; } if ( (!w->right->red) && (!w->left->red) ) { w->red=1; x=x->parent; } else { if (!w->right->red) { w->left->red=0; w->red=1; RightRotate(tree,w); w=x->parent->right; } w->red=x->parent->red; x->parent->red=0; w->right->red=0; LeftRotate(tree,x->parent); x=root; /* this is to exit while loop */ } } else { /* the code below is has left and right switched from above */ w=x->parent->left; if (w->red) { w->red=0; x->parent->red=1; RightRotate(tree,x->parent); w=x->parent->left; } if ( (!w->right->red) && (!w->left->red) ) { w->red=1; x=x->parent; } else { if (!w->left->red) { w->right->red=0; w->red=1; LeftRotate(tree,w); w=x->parent->left; } w->red=x->parent->red; x->parent->red=0; w->left->red=0; RightRotate(tree,x->parent); x=root; /* this is to exit while loop */ } } } x->red=0; #ifdef DEBUG_ASSERT Assert(!tree->nil->red, "nil not black in RBDeleteFixUp"); #endif } /***********************************************************************/ /* FUNCTION: RBDelete */ /**/ /* INPUTS: tree is the tree to delete node z from */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: Deletes z from tree and frees the key and info of z */ /* using DestoryKey and DestoryInfo. Then calls */ /* RBDeleteFixUp to restore red-black properties */ /**/ /* Modifies Input: tree, z */ /**/ /* The algorithm from this function is from _Introduction_To_Algorithms_ */ /***********************************************************************/ void RBDelete(rb_red_blk_tree* tree, rb_red_blk_node* z){ rb_red_blk_node* y; rb_red_blk_node* x; rb_red_blk_node* nil=tree->nil; rb_red_blk_node* root=tree->root; y= ((z->left == nil) || (z->right == nil)) ? z : TreeSuccessor(tree,z); x= (y->left == nil) ? y->right : y->left; if (root == (x->parent = y->parent)) { /* assignment of y->p to x->p is intentional */ root->left=x; } else { if (y == y->parent->left) { y->parent->left=x; } else { y->parent->right=x; } } if (y != z) { /* y should not be nil in this case */ #ifdef DEBUG_ASSERT Assert( (y!=tree->nil), "y is nil in RBDelete\n"); #endif /* y is the node to splice out and x is its child */ if (!(y->red)) RBDeleteFixUp(tree,x); tree->DestroyKey(z->key); tree->DestroyInfo(z->info); y->left=z->left; y->right=z->right; y->parent=z->parent; y->red=z->red; z->left->parent=z->right->parent=y; if (z == z->parent->left) { z->parent->left=y; } else { z->parent->right=y; } free(z); } else { tree->DestroyKey(y->key); tree->DestroyInfo(y->info); if (!(y->red)) RBDeleteFixUp(tree,x); free(y); } #ifdef DEBUG_ASSERT Assert(!tree->nil->red, "nil not black in RBDelete"); #endif } /***********************************************************************/ /* FUNCTION: RBNumGreaterThan */ /**/ /* INPUTS: tree is the tree to count keys greater than key */ /* key */ /**/ /* OUTPUT: integer of the number of keys greater than x */ /**/ /* Modifies Input: none */ /***********************************************************************/ int RBNumGreaterThan(rb_red_blk_tree* tree, void* key) { rb_red_blk_node* nil=tree->nil; rb_red_blk_node* current=tree->root->left; int nodeCount = 0; while(nil != current) { if(1 == (tree->Compare(current->key, key))) {/* current->key > key */ nodeCount += current->rightSize + current->numInstances; current = current->left; } else if(-1 == (tree->Compare(current->key, key))) {/* current->key < key */ current = current->right; } else {/* current->key == key */ current = current->right; } } return(nodeCount); } /***********************************************************************/ /* FUNCTION: RBNumLessThan */ /**/ /* INPUTS: tree is the tree to count keys less than key */ /* key */ /**/ /* OUTPUT: integer of the number of keys less than x */ /**/ /* Modifies Input: none */ /***********************************************************************/ int RBNumLessThan(rb_red_blk_tree* tree, void* key) { rb_red_blk_node* nil=tree->nil; rb_red_blk_node* current=tree->root->left; int nodeCount = 0; int tmp = 0; while(nil != current) { if(1 == (tree->Compare(current->key, key))) {/* current->key > key */ current = current->left; } else if(-1 == (tree->Compare(current->key, key))) {/* current->key < key */ nodeCount += current->leftSize + current->numInstances; current = current->right; } else {/* current->key == key */ current = current->left; } } return(nodeCount); }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
c7ddd085d98ff0361fdea32493d29bd4ac786874
230965ad63ce46b2884c2a1652b54bdb19b23679
/NeuralCreature/NeuralCreature/backup/OpenGLTutorial.h
428672bcd21346af175ba27312a3b03d53ef5921
[]
no_license
jonsor/NeuralJetsonCreature
e6b98301606779c9be1006a95bb6afd058136e31
6b503ee096b5150d3b9bc7ea5f9388de7d509112
refs/heads/master
2021-01-19T04:34:18.450584
2018-04-11T05:38:06
2018-04-11T05:38:06
84,433,043
2
0
null
2017-03-22T14:14:55
2017-03-09T11:11:02
C++
UTF-8
C++
false
false
1,216
h
#pragma once //GLEW #define GLEW_STATIC #include <GL/glew.h> //GLFW #include <GLFW/glfw3.h> //GLM Mathematics #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> //Additional includes #include <iostream> #include "Shader.h" #include "Camera.h" #include "Cube.h" class OpenGLTutorial { private: // Shaders const GLchar* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 position;\n" "void main()\n" "{\n" "gl_Position = vec4(position.x, position.y, position.z, 1.0);\n" "}\0"; const GLchar* fragmentShaderSource = "#version 330 core\n" "out vec4 color;\n" "uniform vec4 customColor;\n" "void main()\n" "{\n" "color = customColor;\n" "}\n\0"; const GLuint WIDTH = 1280, HEIGHT = 720; public: OpenGLTutorial(); void init(); void initGLEW(); void initView(GLFWwindow * window); void renderLoop(GLFWwindow * window, GLint shaderProgram, GLint planeVAO, GLint cubeVAO, GLint lightVAO, Shader lightingShader, Cube cube); void renderLoop(GLFWwindow * window, GLint shaderProgram, GLint planeVAO, GLint cubeVAO, GLint lightVAO, Shader lightingShader); GLint initShaders(); void doMovement(); ~OpenGLTutorial(); };
[ "mafia8261jsorsdal@gmail.com" ]
mafia8261jsorsdal@gmail.com
43ca7a65361662d570787fda2973572a4fc54a25
b41f1b91e59dd72ddacdd2134a73b68591826439
/canbus/libcan/RmCANClient_c.cpp
d51246e7b627f5521bcb3e739c1a850a483da97e
[]
no_license
lvdongweia/Can
c4a55b99b622ada4b360a4f818b8aeda8e78bc6a
34c6bba0794e1fbf64af6f2098c246d477faebfa
refs/heads/master
2021-01-11T06:07:54.875005
2016-09-26T00:48:47
2016-09-26T00:48:47
69,199,820
0
0
null
null
null
null
UTF-8
C++
false
false
1,917
cpp
/* */ #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include "RmCANClient.h" #include "rm_can_data_type.h" #include "rm_can_log.h" #include "RmCANClient_c.h" #undef LOG_TAG #define LOG_TAG "CAN_CLIENT_C" using namespace android; class CANPacketReceiver; sp<RmCANClient> g_can_client = NULL; sp<CANPacketReceiver> g_recevier = NULL; struct can_client_callback g_callback; /**************** can msg reciver **************/ class CANPacketReceiver : public RmCANReceiver { public: void RmRecvCANData(int priority, int src_id, const void *pdata, int len) { if (g_callback.RmRecvCANData != NULL) g_callback.RmRecvCANData(priority, src_id, pdata, len); } void RmCANServiceDied() { if (g_callback.RmCANServiceDied != NULL) g_callback.RmCANServiceDied(); LOGE(LOG_TAG, "CAN Service is dead"); } }; int RmInitCANClient(int module_id, struct can_client_callback *callback) { if (callback == NULL || callback->RmRecvCANData == NULL || callback->RmCANServiceDied == NULL) return -1; RmDeinitCANClient(); memcpy(&g_callback, callback, sizeof(struct can_client_callback)); g_can_client = new RmCANClient(); g_recevier = new CANPacketReceiver(); g_can_client->RmSetReceiver(module_id, g_recevier); return 0; } void RmDeinitCANClient(void) { if (g_can_client != NULL) { g_can_client->disconnect(); g_can_client.clear(); g_can_client == NULL; } if (g_recevier != NULL) g_recevier.clear(); memset(&g_callback, 0, sizeof(struct can_client_callback)); } int RmSendCANData(int dest_id, const void *pdata, int len, int priority) { int ret = -1; if (g_can_client != NULL) ret = g_can_client->RmSendCANData(dest_id, pdata, len, priority); return ret; }
[ "dongwei.lv@avatarmind.com" ]
dongwei.lv@avatarmind.com
119dbdba4fb908db88b3c724cac7147c953ce7c1
8bed063ecb795be78a76df0d381092b9d2a08f7b
/TSE/CLanguage.cpp
4c2ba43a7a045a689dc22dc63c2c69b312b5446f
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Arkheias/Mammoth
fe5cae7036ef3235a9211d09e8288890cdc8fe58
7ff27aad68f3c106de893724489b7592b259c7f2
refs/heads/master
2020-03-16T17:06:17.777862
2018-05-09T17:53:18
2018-05-09T17:53:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,771
cpp
// CLanguage.cpp // // CLanguage class // Copyright (c) 2017 Kronosaur Productions, LLC. All Rights Reserved. #include "PreComp.h" #include "LanguageDefs.h" #define CUSTOM_PLURAL_ATTRIB CONSTLIT("customPlural") #define DEFINITE_ARTICLE_ATTRIB CONSTLIT("definiteArticle") #define ES_PLURAL_ATTRIB CONSTLIT("esPlural") #define FIRST_PLURAL_ATTRIB CONSTLIT("firstPlural") #define NO_ARTICLE_ATTRIB CONSTLIT("noArticle") #define PERSONAL_NAME_ATTRIB CONSTLIT("personalName") #define SECOND_PLURAL_ATTRIB CONSTLIT("secondPlural") #define VOWEL_ARTICLE_ATTRIB CONSTLIT("reverseArticle") CString CLanguage::ComposeNounPhrase (const CString &sNoun, int iCount, const CString &sModifier, DWORD dwNounFlags, DWORD dwComposeFlags) // ComposeNounPhrase // // Composes a noun phrase based on the appropriate flags { // Figure out whether we need to pluralize or not bool bPluralize = (dwComposeFlags & nounPlural) || (iCount > 1 && ((dwComposeFlags & nounCount) || (dwComposeFlags & nounCountOnly) || (dwComposeFlags & nounDemonstrative) || (dwComposeFlags & nounCountAlways) || (dwComposeFlags & nounNoDeterminer)) && !(dwComposeFlags & nounArticle)); // Get the proper noun form SNounDesc NounDesc; CString sNounForm = ParseNounForm(sNoun, sModifier, dwNounFlags, bPluralize, (dwComposeFlags & nounShort) != 0, &NounDesc); // If we need to strip quotes, do it now if (NounDesc.bHasQuotes) { if (dwComposeFlags & nounNoQuotes) sNounForm = strProcess(sNounForm, STRPROC_NO_DOUBLE_QUOTES); else if (dwComposeFlags & nounEscapeQuotes) sNounForm = strProcess(sNounForm, STRPROC_ESCAPE_DOUBLE_QUOTES); } // Get the appropriate article CString sArticle; if (dwComposeFlags & nounNoDeterminer) { } else if ((dwComposeFlags & nounArticle) || ((dwComposeFlags & nounCount) && iCount == 1)) { sArticle = NounDesc.sArticle; } else if (dwComposeFlags & nounDemonstrative) { if (NounDesc.sArticle.IsBlank() || *NounDesc.sArticle.GetPointer() == 't') sArticle = NounDesc.sArticle; else { if (iCount > 1) sArticle = CONSTLIT("these "); else sArticle = CONSTLIT("this "); } } else if (iCount > 1 && ((dwComposeFlags & nounCount) || (dwComposeFlags & nounCountOnly))) sArticle = strPatternSubst(CONSTLIT("%d "), iCount); else if (dwComposeFlags & nounCountAlways) sArticle = strPatternSubst(CONSTLIT("%d "), iCount); // Compose CString sNounPhrase = strPatternSubst(CONSTLIT("%s%s%s"), sArticle, sModifier, sNounForm); if (dwComposeFlags & nounTokenize) sNounPhrase = strConvertToToken(sNounPhrase, true); if (dwComposeFlags & nounTitleCapitalize) return strTitleCapitalize(sNounPhrase, TITLE_CAP_EXCEPTIONS, TITLE_CAP_EXCEPTIONS_COUNT); else if (dwComposeFlags & nounCapitalize) return strCapitalize(sNounPhrase); else return sNounPhrase; } CString CLanguage::ComposeNumber (ENumberFormatTypes iFormat, int iNumber) // ComposeNumber // // Converts to a string of the appropriate format. { switch (iFormat) { case numberInteger: return strFormatInteger(iNumber, -1, FORMAT_THOUSAND_SEPARATOR); case numberSpeed: return strPatternSubst(CONSTLIT(".%02dc"), iNumber); // Defaults to double default: return ComposeNumber(iFormat, (Metric)iNumber); } } CString CLanguage::ComposeNumber (ENumberFormatTypes iFormat, Metric rNumber) // ComposeNumber // // Converts to a string of the appropriate format. { switch (iFormat) { // Automagically come up with precission case numberReal: if (rNumber >= 100.0) return strFromInt((int)mathRound(rNumber)); else if (rNumber >= 1.0) return strFromDouble(rNumber, 1); else return strFromDouble(rNumber, 2); break; // For power, we assume the value in in KWs. case numberPower: if (rNumber < 9950.0) return strPatternSubst(CONSTLIT("%s MW"), strFromDouble(rNumber / 1000.0, 1)); else if (rNumber < 999500.0) return strPatternSubst(CONSTLIT("%d MW"), mathRound(rNumber / 1000.0)); else if (rNumber < 9950000.0) return strPatternSubst(CONSTLIT("%s GW"), strFromDouble(rNumber / 1000000.0, 1)); else return strPatternSubst(CONSTLIT("%d GW"), mathRound(rNumber / 1000000.0)); break; case numberRegenRate: if (rNumber <= 0.0) return CONSTLIT("none"); else { int iRate10 = mathRound(g_TicksPerSecond * rNumber / 18.0); if (iRate10 == 0) return CONSTLIT("<0.1 hp/sec"); else if ((iRate10 % 10) == 0) return strPatternSubst(CONSTLIT("%d hp/sec"), iRate10 / 10); else return strPatternSubst(CONSTLIT("%d.%d hp/sec"), iRate10 / 10, iRate10 % 10); } break; case numberSpeed: return ComposeNumber(iFormat, (int)mathRound(100.0 * rNumber / LIGHT_SPEED)); // Defaults to integer default: return strFormatInteger((int)mathRound(rNumber), -1, FORMAT_THOUSAND_SEPARATOR); } } CString CLanguage::ComposeNumber (ENumberFormatTypes iFormat, ICCItem *pNumber) // ComposeNumber // // Converst to a string of the appropriate format. { if (pNumber->IsDouble()) return ComposeNumber(iFormat, pNumber->GetDoubleValue()); else return ComposeNumber(iFormat, pNumber->GetIntegerValue()); } CString CLanguage::ComposeVerb (const CString &sVerb, DWORD dwVerbFlags) // ComposeVerb // // Generates the proper verb form based on the given flags. { const SVerbData *pVerbData = VERB_FORM_TABLE.GetAt(sVerb); if (pVerbData == NULL) return sVerb; if (dwVerbFlags & verbPluralize) return CString(pVerbData->pszPlural, -1, TRUE); return sVerb; } DWORD CLanguage::LoadNameFlags (CXMLElement *pDesc) // LoadNameFlags // // Returns flags word with NounFlags { DWORD dwFlags = 0; if (pDesc->GetAttributeBool(DEFINITE_ARTICLE_ATTRIB)) dwFlags |= nounDefiniteArticle; if (pDesc->GetAttributeBool(FIRST_PLURAL_ATTRIB)) dwFlags |= nounFirstPlural; if (pDesc->GetAttributeBool(ES_PLURAL_ATTRIB)) dwFlags |= nounPluralES; if (pDesc->GetAttributeBool(CUSTOM_PLURAL_ATTRIB)) dwFlags |= nounCustomPlural; if (pDesc->GetAttributeBool(SECOND_PLURAL_ATTRIB)) dwFlags |= nounSecondPlural; if (pDesc->GetAttributeBool(VOWEL_ARTICLE_ATTRIB)) dwFlags |= nounVowelArticle; if (pDesc->GetAttributeBool(NO_ARTICLE_ATTRIB)) dwFlags |= nounNoArticle; if (pDesc->GetAttributeBool(PERSONAL_NAME_ATTRIB)) dwFlags |= nounPersonalName; return dwFlags; } void CLanguage::ParseItemName (const CString &sName, CString *retsRoot, CString *retsModifiers) // ParseItemName // // Parses an item name like: // // light reactive armor // // And splits it into a root name and a modifier: // // root = "reactive armor" // modifier = "light" { char *pPos = sName.GetASCIIZPointer(); char *pPosStart = pPos; char *pPosEnd = pPos + sName.GetLength(); char *pModifierEnd = NULL; char *pStart = pPos; while (pPos < pPosEnd) { // If this is whitespace, then we've reached then end of a word. if (strIsWhitespace(pPos)) { CString sWord(pStart, (int)(pPos - pStart)); // If this word is a known modifier, then we remember the fact that // we've got at least one modifier. if (ITEM_MODIFIER_TABLE.GetAt(sWord)) { pModifierEnd = pPos; // Skip until the beginning of the next word. while (pPos < pPosEnd && strIsWhitespace(pPos)) pPos++; // Continue looping. pStart = pPos; } // Otherwise, we're done. else { break; } } // Otherwise, next char else pPos++; } // If we have a modifier, then add it. if (pModifierEnd && retsModifiers) *retsModifiers = CString(pPosStart, (int)(pModifierEnd - pPosStart)); // The rest is the root if (retsRoot) *retsRoot = CString(pStart, (int)(pPosEnd - pStart)); } void CLanguage::ParseLabelDesc (const CString &sLabelDesc, CString *retsLabel, CString *retsKey, int *retiKey, TArray<ELabelAttribs> *retSpecial) // ParseLabelDesc // // Parses a label descriptor of the following forms: // // Action: This is a normal label // [PageDown] Action: This is a multi-key accelerator // [A]ction: A is the special key // [Enter]: Treated as a normal label because key is > 1 character // *Action: This is the default action // ^Action: This is the cancel action // >Action: This is the next key // <Action: This is the prev key { char *pPos = sLabelDesc.GetASCIIZPointer(); // Parse any special attribute prefixes while (*pPos == '*' || *pPos == '^' || *pPos == '>' || *pPos == '<') { if (retSpecial) { switch (*pPos) { case '*': retSpecial->Insert(specialDefault); break; case '^': retSpecial->Insert(specialCancel); break; case '>': retSpecial->Insert(specialNextKey); break; case '<': retSpecial->Insert(specialPrevKey); break; } } pPos++; } // Parse out the label and any accelerator key CString sLabel; CString sKey; int iKey = -1; // See if we have a multi-key accelerator label char *pStart = NULL; char *pAccelStart = NULL; char *pAccelEnd = NULL; if (*pPos == '[') { pStart = pPos; while (*pStart != '\0' && *pStart != ']') pStart++; if (*pStart == ']' && pStart[1] != '\0') { pAccelEnd = pStart; pStart++; while (*pStart == ' ') pStart++; // Must be more than 1 character long pAccelStart = pPos + 1; if ((int)(pAccelEnd - pAccelStart) <= 1) pStart = NULL; } else pStart = NULL; } // If we found a multi-key accelerator label, use that if (pStart) { sLabel = CString(pStart); // Look up this key by name CString sKeyName = CString(pAccelStart, (int)(pAccelEnd - pAccelStart)); DWORD dwKey = CVirtualKeyData::GetKey(sKeyName); // If this is a valid key, then we use it as an accelerator // and special key. if (dwKey != CVirtualKeyData::INVALID_VIRT_KEY) { sKey = CVirtualKeyData::GetKeyLabel(dwKey); // We only support a limited number of keys switch (dwKey) { case VK_DOWN: case VK_RIGHT: retSpecial->Insert(specialNextKey); break; case VK_ESCAPE: retSpecial->Insert(specialCancel); break; case VK_LEFT: case VK_UP: retSpecial->Insert(specialPrevKey); break; case VK_NEXT: retSpecial->Insert(specialPgDnKey); break; case VK_PRIOR: retSpecial->Insert(specialPgUpKey); break; case VK_RETURN: retSpecial->Insert(specialDefault); break; } } // Otherwise, just an accelerator else sKey = sKeyName; } // Otherwise, parse for an embedded label using the bracket syntax. else { pStart = pPos; while (*pPos != '\0') { if (pPos[0] == '[' && pPos[1] != '\0' && pPos[2] == ']') { if (pStart) sLabel.Append(CString(pStart, (int)(pPos - pStart))); pPos++; if (*pPos == '\0') break; if (*pPos != ']') { iKey = sLabel.GetLength(); sKey = CString(pPos, 1); sLabel.Append(sKey); pPos++; } if (*pPos == ']') pPos++; pStart = pPos; continue; } else pPos++; } if (pStart != pPos) sLabel.Append(CString(pStart, (int)(pPos - pStart))); } // Done if (retsLabel) *retsLabel = sLabel; if (retsKey) *retsKey = sKey; if (retiKey) *retiKey = iKey; } DWORD CLanguage::ParseNounFlags (const CString &sValue) // ParseNounFlags // // Parse the value as a noun flag and returns it. If not found, we return 0. // sValue can also be a set of flags, separated by spaces or commas. { DWORD dwFlags = 0; char *pPos = sValue.GetASCIIZPointer(); while (*pPos != '\0') { // Find the end of this flag char *pStart = pPos; while (*pPos != '\0' && *pPos != ' ' && *pPos != ',' && *pPos != ';') pPos++; // Add the flag const TStaticStringEntry<DWORD> *pEntry = NOUN_FLAG_TABLE.GetAt(pStart, pPos); if (pEntry) dwFlags |= pEntry->Value; // Next while (*pPos == ' ' || *pPos == ',' || *pPos == ';') pPos++; } return dwFlags; } CString CLanguage::ParseNounForm (const CString &sNoun, const CString &sModifier, DWORD dwNounFlags, bool bPluralize, bool bShortName, SNounDesc *retDesc) // ParseNounForm // // Parses a string of the form: // // abc(s) // :an abcdef(s) // : abcdef(s) // [abc]def(s) // [abc]def| [hij]klm // :the [abc]def| [hij]klm // // Using the noun flags and the required result, it parses out the various component // of the noun (plural form, short name) and returns the required noun { char *pPos = sNoun.GetASCIIZPointer(); // Parse the article, if we have one. char *pArticleStart = NULL; char *pArticleEnd = NULL; if (*pPos == ':') { pPos++; pArticleStart = pPos; // Skip to the end of the article while (pPos != '\0' && *pPos != ' ') pPos++; // No article? if (pPos == pArticleStart) { pArticleEnd = pPos; if (*pPos == ' ') pPos++; } // Otherwise, include a trailing space in the article else { if (*pPos == ' ') pPos++; pArticleEnd = pPos; } } // See if we know enough to compute the article now bool bNeedArticle = true; if (retDesc) { // If we have a modifier, then we always use that to calculate the article. // (And we assume it follows regular rules.) if (!sModifier.IsBlank()) { switch (*sModifier.GetASCIIZPointer()) { case 'A': case 'a': case 'E': case 'e': case 'I': case 'i': case 'O': case 'o': case 'U': case 'u': retDesc->sArticle = CONSTLIT("an "); break; default: retDesc->sArticle = CONSTLIT("a "); break; } bNeedArticle = false; } // Otherwise, if we've got the article above, use that. else if (pArticleStart) { retDesc->sArticle = CString(pArticleStart, (int)(pArticleEnd - pArticleStart)); bNeedArticle = false; } } // Parse the noun CString sDest; char *pDest = sDest.GetWritePointer(sNoun.GetLength() + 10); bool bDestIsSingular = true; bool bInPluralSect = false; bool bInLongNameSect = false; bool bSkipWhitespace = true; bool bStartOfWord = true; bool bHasLongForm = false; bool bHasQuotes = false; int iWord = 1; while (*pPos != '\0') { // Skip whitespace until we find non-whitespace if (bSkipWhitespace) { if (*pPos == ' ') { pPos++; continue; } else bSkipWhitespace = false; } // Begin and end plural addition. Everything inside parentheses // is added only if plural if (*pPos == '(' && !bStartOfWord) { bInPluralSect = true; // If we have a paren, then it means that we can form the // plural version. We don't need any additional auto pluralization if (bPluralize) bDestIsSingular = false; } else if (*pPos == ')' && bInPluralSect) bInPluralSect = false; // Begin and end long name section. Everything inside // brackets appears only for long names else if (*pPos == '[') { bInLongNameSect = true; bHasLongForm = true; } else if (*pPos == ']') bInLongNameSect = false; // Escape code else if (*pPos == '\\') { pPos++; if (*pPos == '\0') break; // Deal with escape codes if (*pPos == 'x' || *pPos == 'X') { pPos++; if (*pPos == '\0') break; int iFirstDigit = strGetHexDigit(pPos); pPos++; if (*pPos == '\0') break; int iSecondDigit = strGetHexDigit(pPos); if ((!bInLongNameSect || !bShortName) && (!bInPluralSect || bPluralize)) *pDest++ = (char)(16 * iFirstDigit + iSecondDigit); } // Add, but not if we're in the long names section // and we only want a short name else if ((!bInLongNameSect || !bShortName) && (!bInPluralSect || bPluralize)) *pDest++ = *pPos; } // A semi-colon or vertical-bar means that we have two // name: singular followed by plural else if (*pPos == ';' || *pPos == '|') { // If we don't need the plural form, then we've reached // the end of the singular form, so we're done if (!bPluralize) break; // Reset the destination so we start capturing from // the plural section pDest = sDest.GetASCIIZPointer(); bDestIsSingular = false; bSkipWhitespace = true; } else { // If we've reached the end of a word, see if we need // to add a plural if (*pPos == ' ') { if (bPluralize && bDestIsSingular && !bShortName) { if ((iWord == 1 && (dwNounFlags & nounFirstPlural)) || (iWord == 2 && (dwNounFlags & nounSecondPlural))) { if (dwNounFlags & nounPluralES) { *pDest++ = 'e'; *pDest++ = 's'; } else *pDest++ = 's'; bDestIsSingular = false; } } iWord++; bSkipWhitespace = true; bStartOfWord = true; } else bStartOfWord = false; if ((!bInLongNameSect || !bShortName) && (!bInPluralSect || bPluralize)) { // See if the noun has embedded quotes if (*pPos == '\"') bHasQuotes = true; // Add to the result *pDest++ = *pPos; } } pPos++; } // Add plural if necessary (short name implies plural because // a short name is always a quantifiable item, e.g., a *mass of* concrete) if (bPluralize && bDestIsSingular && (!bHasLongForm || (dwNounFlags & nounPluralizeLongForm))) { if (dwNounFlags & nounPluralES) { *pDest++ = 'e'; *pDest++ = 's'; } else *pDest++ = 's'; } // Done with name *pDest++ = '\0'; sDest.Truncate(pDest - sDest.GetASCIIZPointer() - 1); // Return noun descriptor, if necessary if (retDesc) { // If we still need an article, compute it now if (bNeedArticle) { if (dwNounFlags & nounNoArticle) retDesc->sArticle = NULL_STR; else if (dwNounFlags & nounDefiniteArticle) retDesc->sArticle = CONSTLIT("the "); else { switch (*sDest.GetASCIIZPointer()) { case 'A': case 'a': case 'E': case 'e': case 'I': case 'i': case 'O': case 'o': case 'U': case 'u': { if (dwNounFlags & nounVowelArticle) retDesc->sArticle = CONSTLIT("a "); else retDesc->sArticle = CONSTLIT("an "); break; } default: { if (dwNounFlags & nounVowelArticle) retDesc->sArticle = CONSTLIT("an "); else retDesc->sArticle = CONSTLIT("a "); break; } } } } // Other flags retDesc->bHasQuotes = bHasQuotes; } return sDest; } CLanguage::ENumberFormatTypes CLanguage::ParseNumberFormat (const CString &sValue) // ParseNumberFormat // // Parses a number format string. { if (sValue.IsBlank()) return numberNone; const TStaticStringEntry<ENumberFormatTypes> *pEntry = NUMBER_FORMAT_TABLE.GetAt(sValue); if (pEntry == NULL) return numberError; return pEntry->Value; }
[ "public@neurohack.com" ]
public@neurohack.com
7453eae43dc8e71e58ecf6556e77d1a3a2c693b9
752ac5c3d24a1c54a670b0a40cdc9767684ff797
/controllerFirmware/src/flipscreen.h
f3740f69b9785b12f8ced2a6161d93441283360a
[]
no_license
Newspaperman57/flipdot-mobitec
c04d1a30b003942842d3522b2aa08b38ad086a46
c0b32aaa4eac632503102e06d401ae1972fb4661
refs/heads/master
2020-04-01T03:01:21.516456
2018-08-19T11:38:36
2018-08-19T11:38:36
152,806,156
0
0
null
2018-10-12T20:49:23
2018-10-12T20:49:23
null
UTF-8
C++
false
false
24,835
h
#ifndef __FLIPSCREEN__ #define __FLIPSCREEN__ #include <Arduino.h> // const int rowPins[5] = {13,12,14,27,26}; // const int columnPins[5] = {15,2,4,16,17}; // const int panelPins[4] = {5,18,19,21}; // const int pinColor = 25; #define BLACK 1 #define WHITE 0 #define ON true #define OFF false #define PANEL_WIDTH 112 #define PANEL_HEIGHT 20 // Yellow config // #define PANEL_WIDTH 112 // #define PANEL_HEIGHT 16 class FlipScreen { private: unsigned char index_to_bitpattern_map[28]; unsigned char gpiostate[40]; unsigned char backlight_state = ON; unsigned char screenState[PANEL_WIDTH][PANEL_HEIGHT] PROGMEM; unsigned char screenBuffer[PANEL_WIDTH][PANEL_HEIGHT] PROGMEM; const unsigned char panel_triggers[4] = {5,18,19,21}; const unsigned char row_addr_pins[5] = {13,23,14,27,26}; // const unsigned char row_addr_pins[5] = {13,12,14,27,26}; const unsigned char col_addr_pins[5] = {15,22,4,16,17}; // const unsigned char col_addr_pins[5] = {15,2,4,16,17}; const unsigned char color_pin = 25; const unsigned char backlight_pin = 33; int index_to_bitpattern(int index); void _digitalWrite(unsigned char pin, unsigned char state); public: FlipScreen(); void flip(); void _setDot(unsigned int x, unsigned int y, unsigned char color); void putPixel(unsigned int x, unsigned int y, unsigned char color); void fillRect(unsigned int x1, unsigned int x2, unsigned int y1, unsigned int y2, unsigned char color); void clear(unsigned char color = BLACK); void putChar(unsigned int x, unsigned int y, char c, unsigned char inverted = false); void write(const char* str, unsigned char inverted = false); void setBacklight(bool state); bool getBacklight(); void screenToUart(); }; // fonts - https://github.com/powerline/fonts/tree/master/Terminus/BDF // const unsigned short font[1][18] = { // each char is 10 wide const unsigned short font[127][18] PROGMEM = { // each char is 10 wide {0x0000, // [0] - uni25AE 0x0000, 0x0000, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [1] - blackdiamond 0x0000, 0x0000, 0x0000, 0x0C00, 0x1E00, 0x3F00, 0x7F80, 0xFFC0, 0xFFC0, 0x7F80, 0x3F00, 0x1E00, 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000}, {0xAA80, // [2] - shade 0x5540, 0xAA80, 0x5540, 0xAA80, 0x5540, 0xAA80, 0x5540, 0xAA80, 0x5540, 0xAA80, 0x5540, 0xAA80, 0x5540, 0xAA80, 0x5540, 0xAA80, 0x5540}, {0x0000, // [3] - uni2409 0x0000, 0xCC00, 0xCC00, 0xFC00, 0xCC00, 0xCC00, 0xCC00, 0x0000, 0x1F80, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0000, 0x0000, 0x0000}, {0x0000, // [4] - uni240C 0x0000, 0xFC00, 0xC000, 0xF000, 0xC000, 0xC000, 0xC000, 0x0000, 0x1F80, 0x1800, 0x1E00, 0x1800, 0x1800, 0x1800, 0x0000, 0x0000, 0x0000}, {0x0000, // [5] - uni240D 0x0000, 0x7800, 0xCC00, 0xC000, 0xC000, 0xCC00, 0x7800, 0x0000, 0x1F00, 0x1980, 0x1980, 0x1F00, 0x1B00, 0x1980, 0x0000, 0x0000, 0x0000}, {0x0000, // [6] - uni240A 0x0000, 0xC000, 0xC000, 0xC000, 0xC000, 0xC000, 0xFC00, 0x0000, 0x1F80, 0x1800, 0x1E00, 0x1800, 0x1800, 0x1800, 0x0000, 0x0000, 0x0000}, {0x0000, // [7] - degree 0x1E00, 0x3300, 0x3300, 0x3300, 0x1E00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [8] - plusminus 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0C00, 0x7F80, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [9] - uni2424 0x0000, 0xCC00, 0xEC00, 0xFC00, 0xDC00, 0xCC00, 0xCC00, 0x0000, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [10] - uni240B 0x0000, 0xCC00, 0xCC00, 0xCC00, 0xCC00, 0x7800, 0x3000, 0x0000, 0x0000, 0x1F80, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0000, 0x0000}, {0x0C00, // [11] - SF040000 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [12] - SF030000 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00}, {0x0000, // [13] - SF010000 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0FC0, 0x0FC0, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00}, {0x0C00, // [14] - SF020000 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0FC0, 0x0FC0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0C00, // [15] - SF050000 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0xFFC0, 0xFFC0, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00}, {0xFFC0, // [16] - uni23BA 0xFFC0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [17] - uni23BB 0x0000, 0x0000, 0x0000, 0xFFC0, 0xFFC0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [18] - SF100000 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFFC0, 0xFFC0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [19] - uni23BC 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFFC0, 0xFFC0, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [20] - uni23BD 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFFC0, 0xFFC0}, {0x0C00, // [21] - SF080000 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0FC0, 0x0FC0, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00}, {0x0C00, // [22] - SF090000 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0xFC00, 0xFC00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00}, {0x0C00, // [23] - SF070000 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0xFFC0, 0xFFC0, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [24] - SF060000 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFFC0, 0xFFC0, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00}, {0x0C00, // [25] - SF110000 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00}, {0x0000, // [26] - lessequal 0x0000, 0x0000, 0x0300, 0x0600, 0x0C00, 0x1800, 0x3000, 0x3000, 0x1800, 0x0C00, 0x0600, 0x0300, 0x0000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [27] - greaterequal 0x0000, 0x0000, 0x3000, 0x1800, 0x0C00, 0x0600, 0x0300, 0x0300, 0x0600, 0x0C00, 0x1800, 0x3000, 0x0000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [28] - pi 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7F80, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [29] - notequal 0x0000, 0x0000, 0x0000, 0x0000, 0x0180, 0x7F80, 0x0600, 0x0C00, 0x1800, 0x7F80, 0x6000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [30] - sterling 0x0000, 0x0000, 0x1E00, 0x3300, 0x3000, 0x3000, 0x3000, 0x7E00, 0x3000, 0x3000, 0x3000, 0x3000, 0x3180, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [31] - periodcentered 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [32] - space 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [33] - exclam 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [34] - quotedbl 0x3300, 0x3300, 0x3300, 0x3300, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [35] - numbersign 0x0000, 0x0000, 0x3300, 0x3300, 0x3300, 0x7F80, 0x3300, 0x3300, 0x3300, 0x3300, 0x7F80, 0x3300, 0x3300, 0x3300, 0x0000, 0x0000, 0x0000}, {0x0000, // [36] - dollar 0x0000, 0x0C00, 0x0C00, 0x3F00, 0x6D80, 0x6C00, 0x6C00, 0x6C00, 0x3F00, 0x0D80, 0x0D80, 0x0D80, 0x6D80, 0x3F00, 0x0C00, 0x0C00, 0x0000}, {0x0000, // [37] - percent 0x0000, 0x0000, 0x7300, 0x5300, 0x7600, 0x0600, 0x0C00, 0x0C00, 0x1800, 0x1800, 0x3000, 0x3700, 0x6500, 0x6700, 0x0000, 0x0000, 0x0000}, {0x0000, // [38] - ampersand 0x0000, 0x0000, 0x3C00, 0x6600, 0x6600, 0x6600, 0x3C00, 0x3980, 0x6D80, 0xC700, 0xC300, 0xC300, 0x6780, 0x3D80, 0x0000, 0x0000, 0x0000}, {0x0000, // [39] - quotesingle 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [40] - parenleft 0x0000, 0x0000, 0x0600, 0x0C00, 0x0C00, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x0C00, 0x0C00, 0x0600, 0x0000, 0x0000, 0x0000}, {0x0000, // [41] - parenright 0x0000, 0x0000, 0x1800, 0x0C00, 0x0C00, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0C00, 0x0C00, 0x1800, 0x0000, 0x0000, 0x0000}, {0x0000, // [42] - asterisk 0x0000, 0x0000, 0x0000, 0x0000, 0x6300, 0x3600, 0x1C00, 0xFF80, 0x1C00, 0x3600, 0x6300, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [43] - plus 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0C00, 0x7F80, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [44] - comma 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0C00, 0x1800, 0x0000, 0x0000}, {0x0000, // [45] - hyphen 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7F80, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [46] - period 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [47] - slash 0x0000, 0x0000, 0x0300, 0x0300, 0x0600, 0x0600, 0x0C00, 0x0C00, 0x1800, 0x1800, 0x3000, 0x3000, 0x6000, 0x6000, 0x0000, 0x0000, 0x0000}, {0x0000, // [48] - zero 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6380, 0x6780, 0x6D80, 0x7980, 0x7180, 0x6180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [49] - one 0x0000, 0x0000, 0x0C00, 0x1C00, 0x3C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [50] - two 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6180, 0x0180, 0x0300, 0x0600, 0x0C00, 0x1800, 0x3000, 0x6000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [51] - three 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x0180, 0x0180, 0x1F00, 0x0180, 0x0180, 0x0180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [52] - four 0x0000, 0x0000, 0x0180, 0x0380, 0x0780, 0x0D80, 0x1980, 0x3180, 0x6180, 0x6180, 0x7F80, 0x0180, 0x0180, 0x0180, 0x0000, 0x0000, 0x0000}, {0x0000, // [53] - five 0x0000, 0x0000, 0x7F80, 0x6000, 0x6000, 0x6000, 0x6000, 0x7F00, 0x0180, 0x0180, 0x0180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [54] - six 0x0000, 0x0000, 0x1F00, 0x3000, 0x6000, 0x6000, 0x6000, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [55] - seven 0x0000, 0x0000, 0x7F80, 0x6180, 0x6180, 0x0180, 0x0300, 0x0300, 0x0600, 0x0600, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [56] - eight 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [57] - nine 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F80, 0x0180, 0x0180, 0x0180, 0x0300, 0x3E00, 0x0000, 0x0000, 0x0000}, {0x0000, // [58] - colon 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [59] - semicolon 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0C00, 0x1800, 0x0000, 0x0000}, {0x0000, // [60] - less 0x0000, 0x0000, 0x0300, 0x0600, 0x0C00, 0x1800, 0x3000, 0x6000, 0x6000, 0x3000, 0x1800, 0x0C00, 0x0600, 0x0300, 0x0000, 0x0000, 0x0000}, {0x0000, // [61] - equal 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7F80, 0x0000, 0x0000, 0x0000, 0x7F80, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [62] - greater 0x0000, 0x0000, 0x6000, 0x3000, 0x1800, 0x0C00, 0x0600, 0x0300, 0x0300, 0x0600, 0x0C00, 0x1800, 0x3000, 0x6000, 0x0000, 0x0000, 0x0000}, {0x0000, // [63] - question 0x0000, 0x0000, 0x1E00, 0x3300, 0x6180, 0x6180, 0x0180, 0x0300, 0x0600, 0x0C00, 0x0C00, 0x0000, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [64] - at 0x0000, 0x0000, 0x7F00, 0xC180, 0xC180, 0xCF80, 0xD980, 0xD980, 0xD980, 0xD980, 0xCF80, 0xC000, 0xC000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [65] - A 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x7F80, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [66] - B 0x0000, 0x0000, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x7F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [67] - C 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [68] - D 0x0000, 0x0000, 0x7E00, 0x6300, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6300, 0x7E00, 0x0000, 0x0000, 0x0000}, {0x0000, // [69] - E 0x0000, 0x0000, 0x7F80, 0x6000, 0x6000, 0x6000, 0x6000, 0x7E00, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [70] - F 0x0000, 0x0000, 0x7F80, 0x6000, 0x6000, 0x6000, 0x6000, 0x7E00, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x0000, 0x0000, 0x0000}, {0x0000, // [71] - G 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6000, 0x6000, 0x6000, 0x6780, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [72] - H 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x7F80, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [73] - I 0x0000, 0x0000, 0x1E00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x1E00, 0x0000, 0x0000, 0x0000}, {0x0000, // [74] - J 0x0000, 0x0000, 0x0780, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x6300, 0x6300, 0x6300, 0x3E00, 0x0000, 0x0000, 0x0000}, {0x0000, // [75] - K 0x0000, 0x0000, 0x6180, 0x6180, 0x6300, 0x6600, 0x6C00, 0x7800, 0x7800, 0x6C00, 0x6600, 0x6300, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [76] - L 0x0000, 0x0000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [77] - M 0x0000, 0x0000, 0x8080, 0xC180, 0xE380, 0xF780, 0xDD80, 0xC980, 0xC180, 0xC180, 0xC180, 0xC180, 0xC180, 0xC180, 0x0000, 0x0000, 0x0000}, {0x0000, // [78] - N 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x7180, 0x7980, 0x6D80, 0x6780, 0x6380, 0x6180, 0x6180, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [79] - O 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [80] - P 0x0000, 0x0000, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x7F00, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x0000, 0x0000, 0x0000}, {0x0000, // [81] - Q 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6780, 0x3F00, 0x0300, 0x0180, 0x0000}, {0x0000, // [82] - R 0x0000, 0x0000, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x7F00, 0x7800, 0x6C00, 0x6600, 0x6300, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [83] - S 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6000, 0x6000, 0x3F00, 0x0180, 0x0180, 0x0180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [84] - T 0x0000, 0x0000, 0x7F80, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [85] - U 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [86] - V 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x6180, 0x3300, 0x3300, 0x3300, 0x3300, 0x1E00, 0x1E00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [87] - W 0x0000, 0x0000, 0xC180, 0xC180, 0xC180, 0xC180, 0xC180, 0xC180, 0xC980, 0xDD80, 0xF780, 0xE380, 0xC180, 0x8080, 0x0000, 0x0000, 0x0000}, {0x0000, // [88] - X 0x0000, 0x0000, 0x6180, 0x6180, 0x3300, 0x3300, 0x1E00, 0x0C00, 0x0C00, 0x1E00, 0x3300, 0x3300, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [89] - Y 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x3300, 0x3300, 0x1E00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [90] - Z 0x0000, 0x0000, 0x7F80, 0x0180, 0x0180, 0x0300, 0x0600, 0x0C00, 0x1800, 0x3000, 0x6000, 0x6000, 0x6000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [91] - bracketleft 0x0000, 0x0000, 0x1E00, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1E00, 0x0000, 0x0000, 0x0000}, {0x0000, // [92] - backslash 0x0000, 0x0000, 0x6000, 0x6000, 0x3000, 0x3000, 0x1800, 0x1800, 0x0C00, 0x0C00, 0x0600, 0x0600, 0x0300, 0x0300, 0x0000, 0x0000, 0x0000}, {0x0000, // [93] - bracketright 0x0000, 0x0000, 0x1E00, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x0600, 0x1E00, 0x0000, 0x0000, 0x0000}, {0x0000, // [94] - asciicircum 0x0C00, 0x1E00, 0x3300, 0x6180, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [95] - underscore 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7F80, 0x0000}, {0x1800, // [96] - grave 0x0C00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, // [97] - a 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3F00, 0x0180, 0x0180, 0x3F80, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [98] - b 0x0000, 0x0000, 0x6000, 0x6000, 0x6000, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x7F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [99] - c 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3F00, 0x6180, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [100] - d 0x0000, 0x0000, 0x0180, 0x0180, 0x0180, 0x3F80, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [101] - e 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6180, 0x7F80, 0x6000, 0x6000, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [102] - f 0x0000, 0x0000, 0x0780, 0x0C00, 0x0C00, 0x3F00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [103] - g 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3F80, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F80, 0x0180, 0x0180, 0x3F00}, {0x0000, // [104] - h 0x0000, 0x0000, 0x6000, 0x6000, 0x6000, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [105] - i 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0000, 0x1C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x1E00, 0x0000, 0x0000, 0x0000}, {0x0000, // [106] - j 0x0000, 0x0000, 0x0300, 0x0300, 0x0000, 0x0700, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x0300, 0x3300, 0x3300, 0x1E00}, {0x0000, // [107] - k 0x0000, 0x0000, 0x6000, 0x6000, 0x6000, 0x6180, 0x6300, 0x6600, 0x6C00, 0x7800, 0x6C00, 0x6600, 0x6300, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [108] - l 0x0000, 0x0000, 0x1C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x1E00, 0x0000, 0x0000, 0x0000}, {0x0000, // [109] - m 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7F00, 0x6D80, 0x6D80, 0x6D80, 0x6D80, 0x6D80, 0x6D80, 0x6D80, 0x6D80, 0x0000, 0x0000, 0x0000}, {0x0000, // [110] - n 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [111] - o 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [112] - p 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7F00, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x7F00, 0x6000, 0x6000, 0x6000}, {0x0000, // [113] - q 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3F80, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F80, 0x0180, 0x0180, 0x0180}, {0x0000, // [114] - r 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x6F80, 0x7800, 0x7000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x6000, 0x0000, 0x0000, 0x0000}, {0x0000, // [115] - s 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3F00, 0x6180, 0x6000, 0x6000, 0x3F00, 0x0180, 0x0180, 0x6180, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [116] - t 0x0000, 0x0000, 0x1800, 0x1800, 0x1800, 0x7E00, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x1800, 0x0F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [117] - u 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [118] - v 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x3300, 0x3300, 0x3300, 0x1E00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [119] - w 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x6D80, 0x6D80, 0x6D80, 0x6D80, 0x6D80, 0x3F00, 0x0000, 0x0000, 0x0000}, {0x0000, // [120] - x 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x6180, 0x6180, 0x3300, 0x1E00, 0x0C00, 0x1E00, 0x3300, 0x6180, 0x6180, 0x0000, 0x0000, 0x0000}, {0x0000, // [121] - y 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x6180, 0x3F80, 0x0180, 0x0180, 0x3F00}, {0x0000, // [122] - z 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x7F80, 0x0180, 0x0300, 0x0600, 0x0C00, 0x1800, 0x3000, 0x6000, 0x7F80, 0x0000, 0x0000, 0x0000}, {0x0000, // [123] - braceleft 0x0000, 0x0000, 0x0700, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x3800, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0700, 0x0000, 0x0000, 0x0000}, {0x0000, // [124] - bar 0x0000, 0x0000, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0000, 0x0000, 0x0000}, {0x0000, // [125] - braceright 0x0000, 0x0000, 0x3800, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0700, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x0C00, 0x3800, 0x0000, 0x0000, 0x0000}, {0x0000, // [126] - asciitilde 0x3980, 0x6D80, 0x6D80, 0x6700, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, }; #endif
[ "anton.christensen9700@gmail.com" ]
anton.christensen9700@gmail.com
a601ad712265ce8192975b36bbdaec40d6fc1fa1
a06a9ae73af6690fabb1f7ec99298018dd549bb7
/_Library/_Include/boost/regex/v4/regex_search.hpp
28bdc634c4c4139f097d608895ba7ba5900b5b74
[]
no_license
longstl/mus12
f76de65cca55e675392eac162dcc961531980f9f
9e1be111f505ac23695f7675fb9cefbd6fa876e9
refs/heads/master
2021-05-18T08:20:40.821655
2020-03-29T17:38:13
2020-03-29T17:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,255
hpp
/* * * Copyright (c) 1998-2002 * John Maddock * * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ /* * LOCATION: see http://www.boost.org for most recent version. * FILE regex_search.hpp * VERSION see <boost/version.hpp> * DESCRIPTION: Provides regex_search implementation. */ #ifndef BOOST_REGEX_V4_REGEX_SEARCH_HPP #define BOOST_REGEX_V4_REGEX_SEARCH_HPP namespace boost{ #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable: 4103) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef BOOST_MSVC #pragma warning(pop) #endif template <class BidiIterator, class Allocator, class charT, class traits> bool regex_search(BidiIterator first, BidiIterator last, match_results<BidiIterator, Allocator>& m, const basic_regex<charT, traits>& e, match_flag_type flags = match_default) { return regex_search(first, last, m, e, flags, first); } template <class BidiIterator, class Allocator, class charT, class traits> bool regex_search(BidiIterator first, BidiIterator last, match_results<BidiIterator, Allocator>& m, const basic_regex<charT, traits>& e, match_flag_type flags, BidiIterator base) { if(e.flags() & regex_constants::failbit) return false; re_detail::perl_matcher<BidiIterator, Allocator, traits> matcher(first, last, m, e, flags, base); return matcher.find(); } // // regex_search convenience interfaces: #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING // // this isn't really a partial specialisation, but template function // overloading - if the compiler doesn't support partial specialisation // then it really won't support this either: template <class charT, class Allocator, class traits> inline bool regex_search(const charT* str, match_results<const charT*, Allocator>& m, const basic_regex<charT, traits>& e, match_flag_type flags = match_default) { return regex_search(str, str + traits::length(str), m, e, flags); } template <class ST, class SA, class Allocator, class charT, class traits> inline bool regex_search(const std::basic_string<charT, ST, SA>& s, match_results<typename std::basic_string<charT, ST, SA>::const_iterator, Allocator>& m, const basic_regex<charT, traits>& e, match_flag_type flags = match_default) { return regex_search(s.begin(), s.end(), m, e, flags); } #else // partial overloads: inline bool regex_search(const char* str, cmatch& m, const regex& e, match_flag_type flags = match_default) { return regex_search(str, str + regex::traits_type::length(str), m, e, flags); } inline bool regex_search(const char* first, const char* last, const regex& e, match_flag_type flags = match_default) { cmatch m; return regex_search(first, last, m, e, flags | regex_constants::match_any); } #ifndef BOOST_NO_WREGEX inline bool regex_search(const wchar_t* str, wcmatch& m, const wregex& e, match_flag_type flags = match_default) { return regex_search(str, str + wregex::traits_type::length(str), m, e, flags); } inline bool regex_search(const wchar_t* first, const wchar_t* last, const wregex& e, match_flag_type flags = match_default) { wcmatch m; return regex_search(first, last, m, e, flags | regex_constants::match_any); } #endif inline bool regex_search(const std::string& s, smatch& m, const regex& e, match_flag_type flags = match_default) { return regex_search(s.begin(), s.end(), m, e, flags); } #if !defined(BOOST_NO_WREGEX) inline bool regex_search(const std::basic_string<wchar_t>& s, wsmatch& m, const wregex& e, match_flag_type flags = match_default) { return regex_search(s.begin(), s.end(), m, e, flags); } #endif #endif template <class BidiIterator, class charT, class traits> bool regex_search(BidiIterator first, BidiIterator last, const basic_regex<charT, traits>& e, match_flag_type flags = match_default) { if(e.flags() & regex_constants::failbit) return false; match_results<BidiIterator> m; typedef typename match_results<BidiIterator>::allocator_type match_alloc_type; re_detail::perl_matcher<BidiIterator, match_alloc_type, traits> matcher(first, last, m, e, flags | regex_constants::match_any, first); return matcher.find(); } #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING template <class charT, class traits> inline bool regex_search(const charT* str, const basic_regex<charT, traits>& e, match_flag_type flags = match_default) { return regex_search(str, str + traits::length(str), e, flags); } template <class ST, class SA, class charT, class traits> inline bool regex_search(const std::basic_string<charT, ST, SA>& s, const basic_regex<charT, traits>& e, match_flag_type flags = match_default) { return regex_search(s.begin(), s.end(), e, flags); } #else // non-template function overloads inline bool regex_search(const char* str, const regex& e, match_flag_type flags = match_default) { cmatch m; return regex_search(str, str + regex::traits_type::length(str), m, e, flags | regex_constants::match_any); } #ifndef BOOST_NO_WREGEX inline bool regex_search(const wchar_t* str, const wregex& e, match_flag_type flags = match_default) { wcmatch m; return regex_search(str, str + wregex::traits_type::length(str), m, e, flags | regex_constants::match_any); } #endif inline bool regex_search(const std::string& s, const regex& e, match_flag_type flags = match_default) { smatch m; return regex_search(s.begin(), s.end(), m, e, flags | regex_constants::match_any); } #if !defined(BOOST_NO_WREGEX) inline bool regex_search(const std::basic_string<wchar_t>& s, const wregex& e, match_flag_type flags = match_default) { wsmatch m; return regex_search(s.begin(), s.end(), m, e, flags | regex_constants::match_any); } #endif // BOOST_NO_WREGEX #endif // partial overload #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable: 4103) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #ifdef BOOST_MSVC #pragma warning(pop) #endif } // namespace boost #endif // BOOST_REGEX_V4_REGEX_SEARCH_HPP ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "adm.fael.hs@gmail.com" ]
adm.fael.hs@gmail.com
e10c7e063b0902453de7b60c7e2d1620b063e6c3
cf163b4174022fa0996c6f865963f604ba597302
/firmware/mpcnc-marlin/MPCNC813_GLCD_EB_T8/SdFatUtil.h
46c65edb0ca0c7168314cb6dafb2f400a8f60417
[ "Apache-2.0" ]
permissive
AravinthPanch/araBot
9e6beb81f93b55ef82fb8c4bb8cd3b054b661f4a
1c45a2aeceb3c956a5eba3835b87569046a4df5e
refs/heads/master
2022-02-28T11:46:34.868836
2019-10-12T19:53:00
2019-10-12T19:53:00
108,847,466
9
0
null
null
null
null
UTF-8
C++
false
false
1,585
h
/** * Marlin 3D Printer Firmware * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * Arduino SdFat Library * Copyright (C) 2008 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #ifndef SdFatUtil_h #define SdFatUtil_h #include "Marlin.h" #if ENABLED(SDSUPPORT) /** * \file * \brief Useful utility functions. */ /** Store and print a string in flash memory.*/ #define PgmPrint(x) SerialPrint_P(PSTR(x)) /** Store and print a string in flash memory followed by a CR/LF.*/ #define PgmPrintln(x) SerialPrintln_P(PSTR(x)) namespace SdFatUtil { int FreeRam(); void print_P(PGM_P str); void println_P(PGM_P str); void SerialPrint_P(PGM_P str); void SerialPrintln_P(PGM_P str); } using namespace SdFatUtil; // NOLINT #endif // SDSUPPORT #endif // SdFatUtil_h
[ "panch.aravinth@gmail.com" ]
panch.aravinth@gmail.com
ee408d4c8ed14cbf6b1cc5a148356c01f1151ff6
c72ea3e81a87cb8d7042b87e59ca89c1a80622e4
/zoom1.h
86f5dd61249261682c4cc63143377d11736dfc0c
[]
no_license
liuyl110/test_interpolation
7b0b786d903cf1fec93b1301fa9bea4dace717c2
a8643a3ce8349ee304948a6f05e25a99a5bc75b7
refs/heads/master
2020-03-25T17:45:01.876599
2017-05-27T08:34:52
2017-05-27T08:34:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,653
h
#if !defined(AFX_ZOOM1_H__2EAB50B7_2821_4AFE_A818_3C79396801E3__INCLUDED_) #define AFX_ZOOM1_H__2EAB50B7_2821_4AFE_A818_3C79396801E3__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. // Dispatch interfaces referenced by this interface class CPen1; class CBrush1; ///////////////////////////////////////////////////////////////////////////// // CZoom wrapper class class CZoom : public COleDispatchDriver { public: CZoom() {} // Calls COleDispatchDriver default constructor CZoom(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CZoom(const CZoom& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: BOOL GetEnable(); void SetEnable(BOOL bNewValue); BOOL GetAnimated(); void SetAnimated(BOOL bNewValue); long GetAnimatedSteps(); void SetAnimatedSteps(long nNewValue); void Undo(); void ZoomRect(long Left, long Top, long Right, long Bottom); BOOL GetZoomed(); CPen1 GetPen(); long GetMinimumPixels(); void SetMinimumPixels(long nNewValue); long GetMouseButton(); void SetMouseButton(long nNewValue); long GetDirection(); void SetDirection(long nNewValue); CBrush1 GetBrush(); void ZoomPercent(double PercentZoom); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ZOOM1_H__2EAB50B7_2821_4AFE_A818_3C79396801E3__INCLUDED_)
[ "1398215919@qq.com" ]
1398215919@qq.com
fe56630b3ee07a67d6a333f5b325c2fba8b59416
f31788a859a346683deef13d98c45d0942c58f68
/Camera.cpp
a3295578813fc7f0c24c2efa11cf7a51c1c323e8
[]
no_license
Vendorf/cs6610
1cef20807883f889624b10665f10b9b80c124868
601f2198499773b3c9da55b14c049b675c5edef3
refs/heads/master
2022-01-27T06:11:36.631411
2017-02-08T05:35:13
2017-02-08T05:35:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,457
cpp
#include "Camera.h" #include <glm\gtx\transform.hpp> const float Camera::MOVEMENT_SPEED = 0.1f; Camera::Camera() : viewDirection(-0.06f, -0.63f, -0.76f), position(0.20f, 3.63f, 4.53f), UP(0.0f, 1.0f, 0.0f) { } void Camera::mouseUpdate(const glm::vec2 & newMousePosition) { glm::vec2 mouseDelta = newMousePosition - oldMousePosition; if (glm::length(mouseDelta) > 50.0f) { oldMousePosition = newMousePosition; return; } const float ROTATIONAL_SPEED = 0.3f; viewDirection = glm::mat3(glm::rotate(-mouseDelta.x * ROTATIONAL_SPEED, UP)) * viewDirection; strafeDirection = glm::cross(viewDirection, UP); glm::mat4 rotator = glm::rotate(-mouseDelta.x * ROTATIONAL_SPEED, UP) * glm::rotate(-mouseDelta.y * ROTATIONAL_SPEED, strafeDirection); viewDirection = glm::mat3(rotator) * viewDirection; oldMousePosition = newMousePosition; } glm::mat4 Camera::getWorldToViewMatrix() const { return glm::lookAt(position, position + viewDirection, UP); } void Camera::moveForward() { position += MOVEMENT_SPEED * viewDirection; } void Camera::moveBackward() { position += -MOVEMENT_SPEED * viewDirection; } void Camera::strafeLeft() { position += -MOVEMENT_SPEED * strafeDirection; } void Camera::strafeRight() { position += MOVEMENT_SPEED * strafeDirection; } void Camera::moveUp() { position += MOVEMENT_SPEED * UP; } void Camera::moveDown() { position += -MOVEMENT_SPEED * UP; } glm::vec3 Camera::getPosition() { return position; }
[ "nick.utsav2345" ]
nick.utsav2345
0efd410abf9eae0a9451609558cdaf57117f2c04
d38195c564dc59f0088d259ac887d1ffb9c19279
/Dec2016GameProject/Sound.cpp
6fae632561901fde3463a413e2726b027494fc16
[]
no_license
Sieunguoimay/GameWandering_Dec2016_Win32_VS_Backup
19e1848f610b90c569eff98439054684da8c7068
019182bb9fa1410e3ecec8b83be3e1104ca9148f
refs/heads/master
2020-09-13T06:25:12.749019
2019-11-18T15:19:49
2019-11-18T15:19:49
222,680,742
0
0
null
null
null
null
UTF-8
C++
false
false
631
cpp
#include "Sound.h" Sound::Sound(std::string path) { loadFromFile(path); } Sound::~Sound() { //delete sound; Mix_FreeChunk(sound); sound = NULL;//to be safe } void Sound::play(int channel) { if (Mix_PlayChannel(channel, sound, 0) == -1) { //SDL_Log("Mix_PlayChannel: %s\n", Mix_GetError()); // may be critical error, or maybe just no channels were free. // you could allocated another channel in that case... } } void Sound::loadFromFile(std::string path) { sound = Mix_LoadWAV(path.c_str()); //SDL_Log("Loaded sound: %s\n", path); //if(sound==NULL) //SDL_Log("Error to Load sound: %s\n", Mix_GetError()); }
[ "vuduydu1997@gmail.com" ]
vuduydu1997@gmail.com
053bc4db04779e24b6b841e48d243e44930a7fa8
b8d438bea9a3dd601ca0fd4b3e3d893f8926201d
/C_C++/C++/CPPREA02.cpp
b0d216cdcafdb012914f19987ae72d3c7a8b5763
[]
no_license
lng8212/DSA
dfa43e6ab3cd4f4b81f16dd52820dcaaa3ce410c
affd23596e19cc1595b3a8f339163621e9ceb3b1
refs/heads/main
2023-06-16T09:52:35.363218
2021-07-17T08:44:26
2021-07-17T08:44:26
386,876,462
1
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
#include<bits/stdc++.h> using namespace std; int main (){ int t; cin >>t; while (t--){ int n; cin >>n; long long a[n+1]; for (int i=0;i<n;i++){ cin >>a[i]; } int S=0; for (int i=0;i<n;i++){ if (a[i]==0) S++; } for (int i=0;i<n;i++){ if (a[i]!=0) cout <<a[i]<<' '; } while (S--){ cout <<0<<' '; } cout <<endl; } return 0; }
[ "long05012001@gmail.com" ]
long05012001@gmail.com
7afc606c1a8eea9a00d8ee982857877b5426ce0f
060fe1bb0c27cb214ef41918ac55c2bcdf06e27c
/sample/eLTE_characteristic/OCX/eLTE_Audio/eLTE_Audio/DGNAParam.cpp
1b4c06c4265ccec0bee87ed2d1b59109a9e32d31
[ "Apache-2.0" ]
permissive
cuiwulin/eSDK_eLTE_SDK_Windows
75e132b4e39cbe8a107943c80610a7f488f4a9cc
aad19fa498f4a6de0d775d98ebd90310807b0b23
refs/heads/master
2020-03-17T19:56:16.980033
2017-05-08T02:32:00
2017-05-08T02:32:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,540
cpp
/*Copyright 2015 Huawei Technologies Co., Ltd. All rights reserved. eSDK is 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.*/ // DGNAParam.cpp : implementation file // #include "stdafx.h" #include "eLTE_Audio.h" #include "DGNAParam.h" #include "afxdialogex.h" // CDGNAParam dialog IMPLEMENT_DYNAMIC(CDGNAParam, CDialog) CDGNAParam::CDGNAParam(CWnd* pParent /*=NULL*/) : CDialog(CDGNAParam::IDD, pParent) , m_pDGNAParamInfo(NULL) , m_strDcId(_T("")) , m_bDGNA(false) { } CDGNAParam::~CDGNAParam() { } void CDGNAParam::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CDGNAParam, CDialog) ON_BN_CLICKED(IDC_BUTTON_ADDGROUP, &CDGNAParam::OnBnClickedButtonAddgroup) ON_BN_CLICKED(IDC_BUTTON_DELGROUP, &CDGNAParam::OnBnClickedButtonDelgroup) ON_BN_CLICKED(IDC_BUTTON_ADDUSER, &CDGNAParam::OnBnClickedButtonAdduser) ON_BN_CLICKED(IDC_BUTTON_DELUSER, &CDGNAParam::OnBnClickedButtonDeluser) ON_BN_CLICKED(IDOK, &CDGNAParam::OnBnClickedOk) ON_BN_CLICKED(IDCANCEL, &CDGNAParam::OnBnClickedCancel) END_MESSAGE_MAP() // CDGNAParam message handlers void CDGNAParam::SetDGNAParamInfo(CString strDcId, DGNAParamInfo* pInfo, bool bDGNA) { m_strDcId = strDcId; m_pDGNAParamInfo = pInfo; m_bDGNA = bDGNA; } void CDGNAParam::OnBnClickedButtonAddgroup() { // TODO: Add your control notification handler code here CString strGroupID; GetDlgItemText(IDC_EDIT_GROUP_ID, strGroupID); if (strGroupID.IsEmpty()) return; SetDlgItemText(IDC_EDIT_GROUP_ID, _T("")); CListBox* pList = (CListBox*)GetDlgItem(IDC_LIST_GROUPLIST); if (LB_ERR != pList->FindString(-1, strGroupID)) { return; } pList->AddString(strGroupID); } void CDGNAParam::OnBnClickedButtonDelgroup() { // TODO: Add your control notification handler code here CListBox* pList = (CListBox*)GetDlgItem(IDC_LIST_GROUPLIST); int nMaxItems = pList->GetSelCount(); LPINT rgIndex = new INT[nMaxItems]; memset(rgIndex, 0, sizeof(INT)*nMaxItems); pList->GetSelItems(nMaxItems, rgIndex); for (int i=0; i<nMaxItems; i++) { pList->DeleteString(rgIndex[i]-i); } delete []rgIndex; } void CDGNAParam::OnBnClickedButtonAdduser() { // TODO: Add your control notification handler code here CString strUserID; GetDlgItemText(IDC_EDIT_USER_ID, strUserID); if (strUserID.IsEmpty()) return; SetDlgItemText(IDC_EDIT_USER_ID, _T("")); CListBox* pList = (CListBox*)GetDlgItem(IDC_LIST_USERLIST); if (LB_ERR != pList->FindString(-1, strUserID)) { return; } pList->AddString(strUserID); } void CDGNAParam::OnBnClickedButtonDeluser() { // TODO: Add your control notification handler code here CListBox* pList = (CListBox*)GetDlgItem(IDC_LIST_USERLIST); int nMaxItems = pList->GetSelCount(); LPINT rgIndex = new INT[nMaxItems]; memset(rgIndex, 0, sizeof(INT)*nMaxItems); pList->GetSelItems(nMaxItems, rgIndex); for (int i=0; i<nMaxItems; i++) { pList->DeleteString(rgIndex[i]-i); } delete []rgIndex; } void CDGNAParam::OnBnClickedOk() { // TODO: Add your control notification handler code here CString strGroupID,strDcID,strAlias,strPriority,strMaxPeriod; GetDlgItemText(IDC_EDIT_GROUPID, strGroupID); GetDlgItemText(IDC_EDIT_DCID, strDcID); GetDlgItemText(IDC_EDIT_ALIAS, strAlias); GetDlgItemText(IDC_EDIT_PRIORITY, strPriority); GetDlgItemText(IDC_EDIT_MAXPERIOD, strMaxPeriod); m_pDGNAParamInfo->GroupID = strGroupID; m_pDGNAParamInfo->DcID = strDcID; m_pDGNAParamInfo->Alias = strAlias; m_pDGNAParamInfo->Priority = strPriority; m_pDGNAParamInfo->MaxPeriod = strMaxPeriod; CListBox* pGroupList = (CListBox*)GetDlgItem(IDC_LIST_GROUPLIST); int iMaxCount = pGroupList->GetCount() > 8 ? 8 : pGroupList->GetCount(); for (int i=0; i<iMaxCount; i++) { CString strGroup_ID; pGroupList->GetText(i, strGroup_ID); m_pDGNAParamInfo->GroupList[i] = strGroup_ID; } CListBox* pUserList = (CListBox*)GetDlgItem(IDC_LIST_USERLIST); iMaxCount = pUserList->GetCount() > 200 ? 200 : pUserList->GetCount(); for (int i=0; i<iMaxCount; i++) { CString strUser_ID; pUserList->GetText(i, strUser_ID); m_pDGNAParamInfo->UserList[i] = strUser_ID; } CDialog::OnOK(); } void CDGNAParam::OnBnClickedCancel() { // TODO: Add your control notification handler code here CDialog::OnCancel(); } BOOL CDGNAParam::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT_DCID); pEdit->SetReadOnly(TRUE); SetDlgItemText(IDC_EDIT_DCID, m_strDcId); CEdit* pEditGroupID = (CEdit*)GetDlgItem(IDC_EDIT_GROUPID); pEditGroupID->SetCueBanner(_T("Automatic distribution")); if (m_bDGNA) { SetDlgItemText(IDC_EDIT_PRIORITY, _T("15")); SetDlgItemText(IDC_EDIT_MAXPERIOD,_T("60")); } else { GetDlgItem(IDC_EDIT_GROUPID)->EnableWindow(FALSE); GetDlgItem(IDC_EDIT_ALIAS)->EnableWindow(FALSE); GetDlgItem(IDC_EDIT_PRIORITY)->EnableWindow(FALSE); GetDlgItem(IDC_EDIT_MAXPERIOD)->EnableWindow(FALSE); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
[ "13262212358@163.com" ]
13262212358@163.com
46ab9c10178214d0d0d21eedbd87ca854954f4af
8c2e7b8aad0d4a70178d3a6e3b5cbd9400db37a9
/RecoParticleFlow/PFProducer/plugins/importers/GSFTrackImporter.cc
0d73634eeecd8c372b998632b39515fdf4da509a
[ "Apache-2.0" ]
permissive
cecilecaillol/cmssw
96961b5815d0d6e7127a6f59c882ec5b8e86feb8
3d70b56717b9b8d49aaffcdbef6fb68e3b81fddb
refs/heads/l1t-integration-CMSSW_10_3_1
2023-03-17T06:40:24.755366
2019-04-16T11:06:39
2019-04-16T11:06:39
331,005,975
0
2
Apache-2.0
2023-02-08T14:43:10
2021-01-19T14:25:16
C++
UTF-8
C++
false
false
5,325
cc
#include "RecoParticleFlow/PFProducer/interface/BlockElementImporterBase.h" #include "DataFormats/ParticleFlowReco/interface/PFClusterFwd.h" #include "DataFormats/ParticleFlowReco/interface/PFCluster.h" #include "DataFormats/ParticleFlowReco/interface/PFBlockElementGsfTrack.h" #include "DataFormats/ParticleFlowReco/interface/PFBlockElementBrem.h" #include "DataFormats/ParticleFlowReco/interface/GsfPFRecTrack.h" #include "DataFormats/GsfTrackReco/interface/GsfTrack.h" #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" #include "DataFormats/EgammaReco/interface/ElectronSeedFwd.h" #include "DataFormats/EgammaReco/interface/ElectronSeed.h" #include "RecoParticleFlow/PFProducer/interface/PFBlockElementSCEqual.h" class GSFTrackImporter : public BlockElementImporterBase { public: GSFTrackImporter(const edm::ParameterSet& conf, edm::ConsumesCollector& sumes) : BlockElementImporterBase(conf,sumes), _src(sumes.consumes<reco::GsfPFRecTrackCollection>(conf.getParameter<edm::InputTag>("source"))), _isSecondary(conf.getParameter<bool>("gsfsAreSecondary")), _superClustersArePF(conf.getParameter<bool>("superClustersArePF")){} void importToBlock( const edm::Event& , ElementList& ) const override; private: edm::EDGetTokenT<reco::GsfPFRecTrackCollection> _src; const bool _isSecondary, _superClustersArePF; }; DEFINE_EDM_PLUGIN(BlockElementImporterFactory, GSFTrackImporter, "GSFTrackImporter"); void GSFTrackImporter:: importToBlock( const edm::Event& e, BlockElementImporterBase::ElementList& elems ) const { typedef BlockElementImporterBase::ElementList::value_type ElementType; edm::Handle<reco::GsfPFRecTrackCollection> gsftracks; e.getByToken(_src,gsftracks); elems.reserve(elems.size() + gsftracks->size()); // setup our elements so that all the SCs are grouped together auto SCs_end = std::partition(elems.begin(),elems.end(), [](const ElementType& a){ return a->type() == reco::PFBlockElement::SC; }); size_t SCs_end_position = std::distance(elems.begin(),SCs_end); // insert gsf tracks and SCs, binding pre-existing SCs to ECAL-Driven GSF auto bgsf = gsftracks->cbegin(); auto egsf = gsftracks->cend(); for( auto gsftrack = bgsf; gsftrack != egsf; ++gsftrack ) { reco::GsfPFRecTrackRef gsfref(gsftracks,std::distance(bgsf,gsftrack)); const reco::GsfTrackRef& basegsfref = gsftrack->gsfTrackRef(); const auto& gsfextraref = basegsfref->extra(); // import associated super clusters if( gsfextraref.isAvailable() && gsfextraref->seedRef().isAvailable()) { reco::ElectronSeedRef seedref = gsfextraref->seedRef().castTo<reco::ElectronSeedRef>(); if( seedref.isAvailable() && seedref->isEcalDriven() ) { reco::SuperClusterRef scref = seedref->caloCluster().castTo<reco::SuperClusterRef>(); if( scref.isNonnull() ) { // explicitly veto HGCal super clusters if( scref->seed()->seed().det() == DetId::Forward ) continue; PFBlockElementSCEqual myEqual(scref); auto sc_elem = std::find_if(elems.begin(),SCs_end,myEqual); if( sc_elem != SCs_end ) { reco::PFBlockElementSuperCluster* scbe = static_cast<reco::PFBlockElementSuperCluster*>(sc_elem->get()); scbe->setFromGsfElectron(true); } else { reco::PFBlockElementSuperCluster* scbe = new reco::PFBlockElementSuperCluster(scref); scbe->setFromGsfElectron(true); scbe->setFromPFSuperCluster(_superClustersArePF); SCs_end = elems.insert(SCs_end,ElementType(scbe)); ++SCs_end; // point to element *after* the new one } } } }// gsf extra ref? // cache the SC_end offset SCs_end_position = std::distance(elems.begin(),SCs_end); // get track momentum information const std::vector<reco::PFTrajectoryPoint>& PfGsfPoint = gsftrack->trajectoryPoints(); unsigned int c_gsf=0; bool PassTracker = false; bool GetPout = false; unsigned int IndexPout = 0; for(auto itPfGsfPoint = PfGsfPoint.begin(); itPfGsfPoint!= PfGsfPoint.end();++itPfGsfPoint) { if (itPfGsfPoint->isValid()){ int layGsfP = itPfGsfPoint->layer(); if (layGsfP == -1) PassTracker = true; if (PassTracker && layGsfP > 0 && GetPout == false) { IndexPout = c_gsf-1; GetPout = true; } //const math::XYZTLorentzVector GsfMoment = itPfGsfPoint->momentum(); ++c_gsf; } } const math::XYZTLorentzVector& pin = PfGsfPoint[0].momentum(); const math::XYZTLorentzVector& pout = PfGsfPoint[IndexPout].momentum(); reco::PFBlockElementGsfTrack* temp = new reco::PFBlockElementGsfTrack(gsfref,pin,pout); if( _isSecondary ) { temp->setTrackType(reco::PFBlockElement::T_FROM_GAMMACONV,true); } elems.emplace_back(temp); // import brems from this primary gsf for( const auto& brem : gsfref->PFRecBrem() ) { const unsigned TrajP = brem.indTrajPoint(); if( TrajP != 99 ) { const double DP = brem.DeltaP(); const double sDP = brem.SigmaDeltaP(); elems.emplace_back(new reco::PFBlockElementBrem(gsfref,DP,sDP,TrajP)); } } // protect against reallocations, create a fresh iterator SCs_end = elems.begin() + SCs_end_position; }// loop on gsf tracks elems.shrink_to_fit(); }
[ "lindsey.gray@gmail.com" ]
lindsey.gray@gmail.com
4c65b14ac758772dd10144bbdc5a0dadc757f4cd
7157f5e6ae4f8b2fe999ddb62fd99146ec12c123
/core/test/RawClientTest/ProtocolClient/FpnnClientCenter.cpp
b917836a90ce692fa58e3527d69726f1b0b24f4a
[]
no_license
highras/fpnn
22c42fd8f02077b3362f56614532800682641aae
cbb4c0d6ff9a74b4937710d92f474f2cf9c2607d
refs/heads/master
2022-11-15T00:04:11.304568
2022-10-28T08:43:35
2022-10-28T08:43:35
125,346,359
307
87
null
2018-07-03T03:58:10
2018-03-15T09:52:33
C++
UTF-8
C++
false
false
4,467
cpp
#include "../../../ClientEngine.h" #include "FpnnClientCenter.h" using namespace fpnn; std::mutex ClientCenter::_mutex; static std::atomic<bool> _created(false); static ClientCenterPtr _clientCenter; ClientCenterPtr ClientCenter::instance() { if (!_created) { std::unique_lock<std::mutex> lck(_mutex); if (!_created) { _clientCenter.reset(new ClientCenter); _created = true; } } return _clientCenter; } ClientCenter::ClientCenter(): _running(true), _timeoutQuest(FPNN_DEFAULT_QUEST_TIMEOUT * 1000) { _loopThread = std::thread(&ClientCenter::loopThread, this); } ClientCenter::~ClientCenter() { _running = false; _loopThread.join(); } void ClientCenter::loopThread() { while (_running) { int cyc = 100; int udpSendingCheckSyc = 5; while (_running && cyc--) { udpSendingCheckSyc -= 1; if (udpSendingCheckSyc == 0) { udpSendingCheckSyc = 5; std::unordered_set<UDPFPNNProtocolProcessorPtr> udpProcessors; { std::unique_lock<std::mutex> lck(_mutex); udpProcessors = _udpProcessors; } for (auto processor: udpProcessors) { processor->sendCacheData(); processor->cleanExpiredCallbacks(); } } usleep(10000); } std::list<std::map<uint32_t, BasicAnswerCallback*>> timeouted; int64_t current = slack_real_msec(); { std::unique_lock<std::mutex> lck(_mutex); for (auto& pp: _callbackMap) { std::map<uint32_t, BasicAnswerCallback*> currMap; timeouted.push_back(currMap); for (auto& pp2: pp.second) { if (pp2.second->expiredTime() <= current) currMap[pp2.first] = pp2.second; } if (currMap.size()) { for (auto& pp2: currMap) pp.second.erase(pp2.first); timeouted.back().swap(currMap); } else timeouted.pop_back(); } } for (auto& cbMap: timeouted) for (auto& pp: cbMap) runCallback(nullptr, FPNN_EC_CORE_TIMEOUT, pp.second); } //-- loop thread will exit. std::unordered_map<int, std::unordered_map<uint32_t, BasicAnswerCallback*>> allCallbackMap; { std::unique_lock<std::mutex> lck(_mutex); allCallbackMap.swap(_callbackMap); } for (auto& pp: allCallbackMap) cleanCallbacks(pp.second); //--TODO } void ClientCenter::cleanCallbacks(std::unordered_map<uint32_t, BasicAnswerCallback*>& callbackMap) { for (auto& pp: callbackMap) { runCallback(nullptr, FPNN_EC_CORE_CONNECTION_CLOSED, pp.second); } callbackMap.clear(); } void ClientCenter::runCallback(FPAnswerPtr answer, int errorCode, BasicAnswerCallback* callback) { if (callback->syncedCallback()) callback->fillResult(answer, errorCode); else { callback->fillResult(answer, errorCode); BasicAnswerCallbackPtr task(callback); ClientEngine::wakeUpAnswerCallbackThreadPool(task); } } void ClientCenter::unregisterConnection(int socket) { std::unordered_map<uint32_t, BasicAnswerCallback*> callbackMap; ClientCenterPtr self = instance(); { std::unique_lock<std::mutex> lck(_mutex); auto iter = self->_callbackMap.find(socket); if (iter != self->_callbackMap.end()) { callbackMap.swap(iter->second); self->_callbackMap.erase(socket); } else return; } cleanCallbacks(callbackMap); } BasicAnswerCallback* ClientCenter::takeCallback(int socket, uint32_t seqNum) { ClientCenterPtr self = instance(); std::unique_lock<std::mutex> lck(_mutex); auto iter = self->_callbackMap.find(socket); if (iter != self->_callbackMap.end()) { auto subIter = iter->second.find(seqNum); if (subIter != iter->second.end()) { BasicAnswerCallback* cb = subIter->second; iter->second.erase(seqNum); //-- Don't processing the case for iter->second empty. //-- It can be processed in loopThread, but a perfect implememted //-- must triggered in unregisterConnection() function. return cb; } } return NULL; } void ClientCenter::registerCallback(int socket, uint32_t seqNum, BasicAnswerCallback* callback) { ClientCenterPtr self = instance(); std::unique_lock<std::mutex> lck(_mutex); self->_callbackMap[socket][seqNum] = callback; } void ClientCenter::registerUDPProcessor(UDPFPNNProtocolProcessorPtr processor) { ClientCenterPtr self = instance(); std::unique_lock<std::mutex> lck(_mutex); self->_udpProcessors.insert(processor); } void ClientCenter::unregisterUDPProcessor(UDPFPNNProtocolProcessorPtr processor) { ClientCenterPtr self = instance(); std::unique_lock<std::mutex> lck(_mutex); self->_udpProcessors.erase(processor); }
[ "wangxing.shi@ilivedata.com" ]
wangxing.shi@ilivedata.com
5fc2951b15b9645094926f611521c166f1a7641f
6b0e651bb6dafc98206cc2546ed4358d477120d2
/qtpim/src/contacts/qcontactabstractrequest.h
8dca178d3fe7a760aef7399882d0fb884fee6a43
[]
no_license
mer-packages/qtpim
a44ff46ff233e4bc31a5d60b03e730948fa7e4ba
35d73f52e43862fc398ebb3ae676711f8f922028
refs/heads/master
2021-01-02T09:25:54.013107
2013-07-30T08:21:40
2013-07-30T08:21:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,412
h
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtContacts module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QCONTACTABSTRACTREQUEST_H #define QCONTACTABSTRACTREQUEST_H #include <qcontactmanager.h> #include <QObject> QT_BEGIN_NAMESPACE_CONTACTS class QContactManagerEngine; class QContactAbstractRequestPrivate; class Q_CONTACTS_EXPORT QContactAbstractRequest : public QObject { Q_OBJECT public: ~QContactAbstractRequest(); Q_ENUMS(State) enum State { InactiveState = 0, // operation not yet started ActiveState, // operation started, not yet finished CanceledState, // operation is finished due to cancellation FinishedState // operation either completed successfully or failed. No further results will become available. }; State state() const; // replaces status() bool isInactive() const; bool isActive() const; bool isFinished() const; bool isCanceled() const; QContactManager::Error error() const; Q_ENUMS(RequestType) enum RequestType { InvalidRequest = 0, ContactFetchRequest, ContactIdFetchRequest, ContactRemoveRequest, ContactSaveRequest, RelationshipFetchRequest, RelationshipRemoveRequest, RelationshipSaveRequest, ContactFetchByIdRequest }; RequestType type() const; /* Which manager we want to perform the asynchronous request */ QContactManager* manager() const; void setManager(QContactManager* manager); enum StorageLocation { UserDataStorage = 0x1, SystemStorage = 0x2 }; Q_DECLARE_FLAGS(StorageLocations, StorageLocation) public Q_SLOTS: /* Verbs */ bool start(); bool cancel(); /* waiting for stuff */ bool waitForFinished(int msecs = 0); Q_SIGNALS: void stateChanged(QContactAbstractRequest::State newState); void resultsAvailable(); protected: QContactAbstractRequest(QContactAbstractRequestPrivate* otherd, QObject* parent = 0); QContactAbstractRequestPrivate* d_ptr; private: QContactAbstractRequest(QObject* parent = 0) : QObject(parent), d_ptr(0) {} Q_DISABLE_COPY(QContactAbstractRequest) friend class QContactManagerEngine; friend class QContactAbstractRequestPrivate; #ifndef QT_NO_DEBUG_STREAM Q_CONTACTS_EXPORT friend QDebug operator<<(QDebug dbg, const QContactAbstractRequest& request); #endif }; Q_DECLARE_OPERATORS_FOR_FLAGS(QContactAbstractRequest::StorageLocations) QT_END_NAMESPACE_CONTACTS #endif
[ "carsten.munk@jollamobile.com" ]
carsten.munk@jollamobile.com
6e79f0be1a243d60891b8bcdf87309be43644ba9
53fd6d2e69f6dc06aebccd4c1861f6d31f1d6412
/platform/desktop/mythic_desktop/source/desktop/Desktop_File_Loader.cpp
e93b98367582713d166f88ca411987493514376e
[ "MIT" ]
permissive
silentorb/mythic-cpp
2c36e5e9e341c57d0cd6f3b5a0d8d06aaf52d9b0
97319d158800d77e1a944c47c13523662bc07e08
refs/heads/master
2020-10-01T09:40:58.577920
2019-12-12T04:52:50
2019-12-12T04:52:50
227,509,036
0
0
null
null
null
null
UTF-8
C++
false
false
517
cpp
#include "Desktop_File_Loader.h" #include <fstream> #include <sstream> #include <stdexcept> #include <direct.h> #include <stdlib.h> #include <stdio.h> namespace desktop { const string Desktop_File_Loader(const string &path) { ifstream file; auto full_path = "resources/" + path; file.open(full_path); if (!file.good()) throw std::runtime_error(string("Could not open ") + full_path); stringstream stream; stream << file.rdbuf(); return stream.str(); } }
[ "cj@silentorb.com" ]
cj@silentorb.com
1be2989600ae29a91855b5f55758aab089b386f8
ac4c8e60e07967f41d25c4ee4ef24e3b95b2f678
/CAdapter/CAdapter/NoGravityImpl.h
0b69c1d13506974cd6e291e14dbe6ab7434def6c
[]
no_license
Hydrotoast/CKPlayer-C-Adapter
f887c901169fbe92a13092f7705b6a73134a72b4
843a8ff3f88921fd29be716a59c2e81e286f167c
refs/heads/master
2021-01-22T07:32:31.255725
2012-12-09T07:11:13
2012-12-09T07:11:13
7,076,077
1
0
null
null
null
null
UTF-8
C++
false
false
337
h
#ifndef NO_GRAVITY_IMPL_H #define NO_GRAVITY_IMPL_H #include "GravityImpl.h" class NoGravityImpl : public GravityImpl { public: explicit NoGravityImpl(BoardState& board); virtual NoGravityImpl* clone(BoardState& board) const; virtual std::list<Cell> getAvailable(); virtual bool occupy(size_t row, size_t col, Mark m); }; #endif
[ "gccielo@gmail.com" ]
gccielo@gmail.com
69d035091d8bc7af341da909c0f4b53ad2931891
d584f41e3453e2aa0cd8b591d5b9b55a36d63fc9
/include/particle_system.h
e2683ade958ca3bff4196996f1052c06d85c4a82
[]
no_license
codepictor/particle-system
332a7005dd71d6bbc3506662ed7b392628f2c839
7cca4b267ce70a6877b6f355404326cde629a00d
refs/heads/master
2020-05-05T00:40:57.187638
2019-04-11T16:27:29
2019-04-11T16:27:29
179,582,778
0
0
null
null
null
null
UTF-8
C++
false
false
2,195
h
#pragma once #include <vector> #include <SFML/Graphics.hpp> class Particle { friend class ParticleSystem; public: Particle( const sf::Vector2f position, const sf::Vector2f velocity, const sf::Vector2f acceleration, const float radius, const float mass ); virtual ~Particle() = default; sf::Vector2f GetPosition() const; sf::Vector2f GetVelocity() const; sf::Vector2f GetAcceleration() const; float GetRadius() const; float GetMass() const; void Push(const sf::Vector2f force); void Update(const float dt); void Render(sf::RenderWindow& window); private: sf::Vector2f position_; sf::Vector2f velocity_; sf::Vector2f acceleration_; float radius_; float mass_; sf::CircleShape shape_; }; class ParticleSystem { public: ParticleSystem() = default; virtual ~ParticleSystem() = default; using ParticleID = size_t; ParticleID AddParticle( const sf::Vector2f position, const sf::Vector2f velocity, const sf::Vector2f acceleration, const float radius, const float mass ); void AddLink( const ParticleID particle1_id, const ParticleID particle2_id, const float stiffness ); const Particle& GetParticleByID(const ParticleID particle_id) const; float GetDistance( const ParticleID particle1_id, const ParticleID particle2_id ) const; void Push(const sf::Vector2f force); void Update(const float dt); void Render(sf::RenderWindow& window); private: struct Link { ParticleID particle1_id; ParticleID particle2_id; float intitial_distance; float stiffness; float min_length; }; void SolveLinks(); void ApplyGravity(); void HandleCollisionsBetweenParticles(); void HandleCollisionsWithWalls(); struct SolvedCollisionInfo { sf::Vector2f particle1_new_velocity; sf::Vector2f particle2_new_velocity; }; SolvedCollisionInfo SolveCollisionBetween( const Particle& particle1, const Particle& particle2 ) const; std::vector<Particle> particles_; std::vector<Link> links_; };
[ "grozzmaster@gmail.com" ]
grozzmaster@gmail.com
78296084da026302e1058f993b427cb99c08a787
fd2de23a704ec408f47c9f2263b604cbd204c0a3
/2018_skim/tautauh/skimm_tt_2018.h
887b669acbbf28c056a511ad7e8c1a404b3d096f
[]
no_license
gparida/monoHiggs_postAnalyzer
1a71c3eaa1cb11ce40923eb831077709987bd866
00fb3e37c5fa6bdd75e7426c3a7bf49534c3eec4
refs/heads/master
2023-01-19T15:19:09.487955
2020-12-03T10:15:11
2020-12-03T10:15:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
72,070
h
////////////////////////////////////////////////////////// // This class has been automatically generated on // Thu Jun 14 01:21:53 2018 by ROOT version 6.10/09 // from TTree EventTree/Event data (tag V08_00_26_03) // found on file: /hdfs/store/user/jmadhusu/MonoHiggs_MC2017/DYJetsToLL_M-50_TuneCP5_13TeV-amcatnloFXFX-pythia8/crab_DYJetsToLL_M-50/180603_140815/0000/ggtree_mc_1.root ////////////////////////////////////////////////////////// #ifndef skimm_tt_2018_h #define skimm_tt_2018_h #include <TROOT.h> #include <TChain.h> #include <TFile.h> #include <iostream> #include <fstream> #include <iomanip> #include <cmath> #include <map> #include <list> #include <vector> #include <bitset> #include <TCanvas.h> #include <TSystem.h> #include <TPostScript.h> #include <TH2.h> #include <TH1.h> #include <TH1F.h> #include <TF1.h> #include <TMath.h> #include <TLegend.h> #include <TProfile.h> #include <TGraph.h> #include <TRef.h> #include <TList.h> #include <TSystemFile.h> #include <TSystemDirectory.h> //#include <TDCacheFile.h> #include <TLorentzVector.h> // Header file for the classes stored in the TTree if any. #include "vector" #include "TString.h" #include "vector" #include "vector" #include "vector" #include "vector" #include "vector" #include "vector" using namespace std; class skimm_tt_2018 { public : TTree *fChain; //!pointer to the analyzed TTree or TChain Int_t fCurrent; //!current Tree number in a TChain //TTree *outTree=new TTree("eventTree","eventTree"); TFile *fileName; TTree *tree; TTree *newtree; TH1F* h_nEvents; // Fixed size dimensions of array or collections stored in the TTree if any. // Declaration of leaf types Int_t run; Long64_t event; Int_t lumis; Bool_t isData; Int_t nVtx; Float_t vtxX; Float_t vtxY; Float_t vtxZ; Int_t vtxNtrks; Bool_t vtx_isFake; Int_t vtx_ndof; Float_t vtx_rho; Bool_t isGoodVtx; Int_t nGoodVtx; Float_t rho; Float_t rhoCentral; Double_t prefiringweight; Double_t prefiringweightup; Double_t prefiringweightdown; ULong64_t HLTEleMuX; ULong64_t HLTEleMuXIsPrescaled; ULong64_t HLTEleMuXRejectedByPS; ULong64_t HLTPho; ULong64_t HLTPhoIsPrescaled; ULong64_t HLTPhoRejectedByPS; ULong64_t HLTTau; ULong64_t HLTTauIsPrescaled; ULong64_t HLTTauRejectedByPS; ULong64_t HLTMet; ULong64_t HLTMetIsPrescaled; ULong64_t HLTMetRejectedByPS; ULong64_t HLTJet; ULong64_t HLTJetIsPrescaled; ULong64_t HLTJetRejectedByPS; Int_t nPho; vector<float> *phoE; vector<float> *phoEt; vector<float> *phoEta; vector<float> *phoPhi; vector<float> *phoUnCalibE; vector<float> *phoUnCalibESigma; vector<float> *phoCalibE; vector<float> *phoCalibESigma; vector<float> *phoCalibEt; vector<float> *phoEnergyScale; vector<float> *phoEnergySigma; vector<float> *phoSCE; vector<float> *phoSCRawE; vector<float> *phoSCEta; vector<float> *phoSCPhi; vector<float> *phoSCEtaWidth; vector<float> *phoSCPhiWidth; vector<int> *phohasPixelSeed; vector<int> *phoEleVeto; vector<float> *phoR9Full5x5; vector<float> *phoHoverE; vector<float> *phoSigmaIEtaIEtaFull5x5; vector<float> *phoSigmaIEtaIPhiFull5x5; vector<float> *phoSigmaIPhiIPhiFull5x5; vector<float> *phoPFChIso; vector<float> *phoPFChWorstIso; vector<float> *phoPFPhoIso; vector<float> *phoPFNeuIso; vector<float> *phoIDMVA; vector<unsigned short> *phoIDbit; vector<float> *phoSeedTime; vector<float> *phoSeedEnergy; vector<ULong64_t> *phoFiredSingleTrgs; vector<ULong64_t> *phoFiredDoubleTrgs; vector<ULong64_t> *phoFiredTripleTrgs; vector<ULong64_t> *phoFiredL1Trgs; vector<float> *phoScale_up; vector<float> *phoScale_dn; vector<float> *phoScale_stat_up; vector<float> *phoScale_stat_dn; vector<float> *phoScale_syst_up; vector<float> *phoScale_syst_dn; vector<float> *phoScale_gain_up; vector<float> *phoScale_gain_dn; vector<float> *phoResol_up; vector<float> *phoResol_dn; vector<float> *phoResol_rho_up; vector<float> *phoResol_rho_dn; vector<float> *phoResol_phi_up; vector<float> *phoResol_phi_dn; Int_t nJet; vector<float> *jetPt; vector<float> *jetE; vector<float> *jetEta; vector<float> *jetPhi; vector<float> *jetRawPt; vector<float> *jetRawE; vector<float> *jetMt; vector<float> *jetArea; vector<float> *jetMass; vector<float> *jetMaxDistance; vector<float> *jetPhiPhiMoment; vector<float> *jetConstituentEtaPhiSpread; vector<float> *jetConstituentPtDistribution; vector<float> *jetPileup; vector<unsigned short> *jetID; vector<float> *jetPUID; vector<int> *jetPUFullID; vector<int> *jetPartonID; vector<int> *jetHadFlvr; vector<float> *jetJECUnc; vector<float> *jetCEF; vector<float> *jetNEF; vector<float> *jetCHF; vector<float> *jetNHF; vector<int> *jetPhotonEnF; vector<int> *jetElectronEnF; vector<float> *jetMuonEnF; vector<float> *jetChargedMuonEnF; vector<float> *jetHFHAE; vector<float> *jetHFEME; vector<int> *jetNConst; vector<int> *jetNConstituents; vector<int> *jetNCharged; vector<int> *jetNNeutral; vector<int> *jetNChargedHad; vector<int> *jetNNeutralHad; vector<int> *jetNPhoton; vector<int> *jetNElectron; vector<int> *jetNMuon; vector<float> *jetCSV2BJetTags; vector<float> *jetDeepCSVTags_b; vector<float> *jetDeepCSVTags_bb; vector<float> *jetDeepCSVTags_c; vector<float> *jetDeepCSVTags_udsg; vector<float> *jetDeepFlavour_b; vector<float> *jetDeepFlavour_bb; vector<float> *jetDeepFlavour_lepb; vector<float> *jetDeepFlavour_c; vector<float> *jetDeepFlavour_uds; vector<float> *jetDeepFlavour_g; vector<float> *jetetaWidth; vector<float> *jetphiWidth; vector<vector<float> > *jetConstPt; vector<vector<float> > *jetConstEt; vector<vector<float> > *jetConstEta; vector<vector<float> > *jetConstPhi; vector<vector<int> > *jetConstPdgId; vector<float> *jetGenJetE; vector<float> *jetGenJetPt; vector<float> *jetGenJetEta; vector<float> *jetGenJetPhi; vector<int> *jetGenPartonID; vector<float> *jetGenE; vector<float> *jetGenPt; vector<float> *jetGenEta; vector<float> *jetGenPhi; vector<int> *jetGenPartonMomID; vector<float> *jetP4Smear; vector<float> *jetP4SmearUp; vector<float> *jetP4SmearDo; Int_t nEle; vector<float> *elePt; vector<float> *eleEta; vector<float> *elePhi; vector<float> *eleR9Full5x5; vector<float> *eleE; vector<int> *eleCharge; vector<int> *eleChargeConsistent; vector<float> *eleD0; vector<float> *eleDz; vector<float> *eleSIP; vector<float> *eleUnCalibE; vector<float> *eleUnCalibESigma; vector<float> *eleCalibEecalonly; vector<float> *eleCalibE; vector<float> *eleCalibESigma; vector<float> *eleCalibEt; vector<float> *eleCalibEtSigma; vector<float> *eleEnergyScale; vector<float> *eleEnergySigma; vector<float> *eleSCRawE; vector<float> *eleSCE; vector<float> *eleSCEta; vector<float> *eleSCPhi; vector<float> *eleSCEtaWidth; vector<float> *eleSCPhiWidth; vector<float> *eleHoverE; vector<float> *eleEoverP; vector<float> *eleEoverPout; vector<float> *eleEoverPInv; vector<float> *eleBrem; vector<float> *eledEtaAtVtx; vector<float> *eledPhiAtVtx; vector<float> *eledEtaAtCalo; vector<float> *eledEtaseedAtVtx; vector<float> *eleSigmaIEtaIEtaFull5x5; vector<float> *eleSigmaIPhiIPhiFull5x5; vector<int> *eleConvVeto; vector<int> *eleMissHits; vector<float> *elePFChIso; vector<float> *elePFPhoIso; vector<float> *elePFNeuIso; vector<float> *elePFPUIso; vector<float> *elePFClusEcalIso; vector<float> *elePFClusHcalIso; vector<ULong64_t> *eleFiredSingleTrgs; vector<ULong64_t> *eleFiredDoubleTrgs; vector<ULong64_t> *eleFiredL1Trgs; vector<float> *eleHEEPID; vector<float> *eleMVAIsoID; vector<float> *eleMVAnoIsoID; vector<unsigned short> *eleIDbit; vector<float> *eleTrkdxy; vector<float> *eleKFHits; vector<float> *eleKFChi2; vector<float> *eleGSFChi2; vector<float> *eleScale_up; vector<float> *eleScale_dn; vector<float> *eleScale_stat_up; vector<float> *eleScale_stat_dn; vector<float> *eleScale_syst_up; vector<float> *eleScale_syst_dn; vector<float> *eleScale_gain_up; vector<float> *eleScale_gain_dn; vector<float> *eleResol_up; vector<float> *eleResol_dn; vector<float> *eleResol_rho_up; vector<float> *eleResol_rho_dn; vector<float> *eleResol_phi_up; vector<float> *eleResol_phi_dn; Int_t nMu; vector<float> *muPt; vector<float> *muE; vector<float> *muEta; vector<float> *muPhi; vector<int> *muCharge; vector<int> *muType; vector<unsigned short> *muIDbit; vector<float> *muD0; vector<float> *muDz; vector<float> *muSIP; vector<float> *muChi2NDF; vector<float> *muInnerD0; vector<float> *muInnerDz; vector<int> *muTrkLayers; vector<int> *muPixelLayers; vector<int> *muPixelHits; vector<int> *muMuonHits; vector<int> *muStations; vector<int> *muMatches; vector<int> *muTrkQuality; vector<float> *muInnervalidFraction; vector<float> *muIsoTrk; vector<float> *muPFChIso; vector<float> *muPFPhoIso; vector<float> *muPFNeuIso; vector<float> *muPFPUIso; vector<float> *musegmentCompatibility; vector<float> *muchi2LocalPosition; vector<float> *mutrkKink; vector<float> *muBestTrkPtError; vector<float> *muBestTrkPt; vector<int> *muBestTrkType; vector<ULong64_t> *muFiredTrgs; vector<ULong64_t> *muFiredL1Trgs; Int_t nTau; vector<float> *tau_Pt; vector<float> *tau_Et; vector<float> *tau_Eta; vector<float> *tau_Phi; vector<float> *tau_Charge; vector<int> *tau_DecayMode; vector<int> *tau_decayModeFindingNewDMs; vector<float> *tau_P; vector<float> *tau_Vz; vector<float> *tau_Energy; vector<float> *tau_Mass; vector<float> *tau_Dxy; vector<float> *tau_ZImpact; vector<float> *tau_byCombinedIsolationDeltaBetaCorrRaw3Hits; vector<float> *tau_chargedIsoPtSum; vector<float> *tau_neutralIsoPtSum; vector<float> *tau_neutralIsoPtSumWeight; vector<float> *tau_footprintCorrection; vector<float> *tau_photonPtSumOutsideSignalCone; vector<float> *tau_puCorrPtSum; vector<int> *tau_NumSignalPFChargedHadrCands; vector<int> *tau_NumSignalPFNeutrHadrCands; vector<int> *tau_NumSignalPFGammaCands; vector<int> *tau_NumSignalPFCands; vector<int> *tau_NumIsolationPFChargedHadrCands; vector<int> *tau_NumIsolationPFNeutrHadrCands; vector<int> *tau_NumIsolationPFGammaCands; vector<int> *tau_NumIsolationPFCands; vector<float> *tau_LeadChargedHadronEta; vector<float> *tau_LeadChargedHadronPhi; vector<float> *tau_LeadChargedHadronPt; vector<float> *tau_LeadChargedHadron_dz; vector<float> *tau_LeadChargedHadron_dxy; vector<unsigned int> *tau_IDbits; vector<float> *tau_byIsolationMVArun2017v2DBoldDMwLTraw2017; vector<float> *tau_byVVVLooseDeepTau2017v2p1VSjet; vector<float> *tau_byVVLooseDeepTau2017v2p1VSjet; vector<float> *tau_byVLooseDeepTau2017v2p1VSjet; vector<float> *tau_byLooseDeepTau2017v2p1VSjet; vector<float> *tau_byMediumDeepTau2017v2p1VSjet; vector<float> *tau_byTightDeepTau2017v2p1VSjet; vector<float> *tau_byVTightDeepTau2017v2p1VSjet; vector<float> *tau_byVVTightDeepTau2017v2p1VSjet; vector<float> *tau_byVVVLooseDeepTau2017v2p1VSe; vector<float> *tau_byVVLooseDeepTau2017v2p1VSe; vector<float> *tau_byVLooseDeepTau2017v2p1VSe; vector<float> *tau_byLooseDeepTau2017v2p1VSe; vector<float> *tau_byMediumDeepTau2017v2p1VSe; vector<float> *tau_byTightDeepTau2017v2p1VSe; vector<float> *tau_byVTightDeepTau2017v2p1VSe; vector<float> *tau_byVVTightDeepTau2017v2p1VSe; vector<float> *tau_byVLooseDeepTau2017v2p1VSmu; vector<float> *tau_byLooseDeepTau2017v2p1VSmu; vector<float> *tau_byMediumDeepTau2017v2p1VSmu; vector<float> *tau_byTightDeepTau2017v2p1VSmu; vector<ULong64_t> *tauFiredTrgs; vector<ULong64_t> *tauFiredL1Trgs; Float_t genMET; Float_t genMETPhi; UShort_t metFilters; Float_t caloMET; Float_t caloMETPhi; Float_t caloMETsumEt; Float_t pfMETCorr; Float_t pfMETPhiCorr; Float_t pfMET; Float_t pfMETPhi; Float_t pfMETsumEt; Float_t pfMETmEtSig; Float_t pfMETSig; Float_t pfMET_T1JERUp; Float_t pfMET_T1JERDo; Float_t pfMET_T1JESUp; Float_t pfMET_T1JESDo; Float_t pfMET_T1UESUp; Float_t pfMET_T1UESDo; Float_t pfMETPhi_T1JESUp; Float_t pfMETPhi_T1JESDo; Float_t pfMETPhi_T1UESUp; Float_t pfMETPhi_T1UESDo; vector<float> *pdf; Float_t pthat; Float_t processID; Float_t genWeight; Float_t genHT; Float_t pdfWeight; vector<float> *pdfSystWeight; Int_t nPUInfo; vector<int> *nPU; vector<int> *puBX; vector<float> *puTrue; Int_t nMC; vector<int> *mcPID; vector<float> *mcVtx; vector<float> *mcVty; vector<float> *mcVtz; vector<float> *mcPt; vector<float> *mcMass; vector<float> *mcEta; vector<float> *mcPhi; vector<float> *mcE; vector<float> *mcEt; vector<int> *mcStatus; vector<unsigned short> *mcStatusFlag; vector<int> *mcIndex; vector<int> *mcDaughterPID; vector<float> *mcCharge; vector<int> *mcMotherPID; vector<int> *mcMotherIndex; vector<int> *mcMotherStatus; vector<int> *mcDaughterStatus; vector<int> *mcDaughterList; vector<unsigned short> *mcTauDecayMode; vector<unsigned short> *genMatch2; // List of branches TBranch *b_run; //! TBranch *b_event; //! TBranch *b_lumis; //! TBranch *b_isData; //! TBranch *b_nVtx; //! TBranch *b_vtxX; //! TBranch *b_vtxY; //! TBranch *b_vtxZ; //! TBranch *b_vtxNtrks; //! TBranch *b_vtx_isFake; //! TBranch *b_vtx_ndof; //! TBranch *b_vtx_rho; //! TBranch *b_isGoodVtx; //! TBranch *b_nGoodVtx; //! TBranch *b_rho; //! TBranch *b_rhoCentral; //! TBranch *b_prefiringweight; //! TBranch *b_prefiringweightup; //! TBranch *b_prefiringweightdown; //! TBranch *b_HLTEleMuX; //! TBranch *b_HLTEleMuXIsPrescaled; //! TBranch *b_HLTEleMuXRejectedByPS; //! TBranch *b_HLTPho; //! TBranch *b_HLTPhoIsPrescaled; //! TBranch *b_HLTPhoRejectedByPS; //! TBranch *b_HLTTau; //! TBranch *b_HLTTauIsPrescaled; //! TBranch *b_HLTTauRejectedByPS; //! TBranch *b_HLTMet; //! TBranch *b_HLTMetIsPrescaled; //! TBranch *b_HLTMetRejectedByPS; //! TBranch *b_HLTJet; //! TBranch *b_HLTJetIsPrescaled; //! TBranch *b_HLTJetRejectedByPS; //! TBranch *b_nPho; //! TBranch *b_phoE; //! TBranch *b_phoEt; //! TBranch *b_phoEta; //! TBranch *b_phoPhi; //! TBranch *b_phoUnCalibE; //! TBranch *b_phoUnCalibESigma; //! TBranch *b_phoCalibE; //! TBranch *b_phoCalibESigma; //! TBranch *b_phoCalibEt; //! TBranch *b_phoEnergyScale; //! TBranch *b_phoEnergySigma; //! TBranch *b_phoSCE; //! TBranch *b_phoSCRawE; //! TBranch *b_phoSCEta; //! TBranch *b_phoSCPhi; //! TBranch *b_phoSCEtaWidth; //! TBranch *b_phoSCPhiWidth; //! TBranch *b_phohasPixelSeed; //! TBranch *b_phoEleVeto; //! TBranch *b_phoR9Full5x5; //! TBranch *b_phoHoverE; //! TBranch *b_phoSigmaIEtaIEtaFull5x5; //! TBranch *b_phoSigmaIEtaIPhiFull5x5; //! TBranch *b_phoSigmaIPhiIPhiFull5x5; //! TBranch *b_phoPFChIso; //! TBranch *b_phoPFChWorstIso; //! TBranch *b_phoPFPhoIso; //! TBranch *b_phoPFNeuIso; //! TBranch *b_phoIDMVA; //! TBranch *b_phoIDbit; //! TBranch *b_phoSeedTime; //! TBranch *b_phoSeedEnergy; //! TBranch *b_phoFiredSingleTrgs; //! TBranch *b_phoFiredDoubleTrgs; //! TBranch *b_phoFiredTripleTrgs; //! TBranch *b_phoFiredL1Trgs; //! TBranch *b_phoScale_up; //! TBranch *b_phoScale_dn; //! TBranch *b_phoScale_stat_up; //! TBranch *b_phoScale_stat_dn; //! TBranch *b_phoScale_syst_up; //! TBranch *b_phoScale_syst_dn; //! TBranch *b_phoScale_gain_up; //! TBranch *b_phoScale_gain_dn; //! TBranch *b_phoResol_up; //! TBranch *b_phoResol_dn; //! TBranch *b_phoResol_rho_up; //! TBranch *b_phoResol_rho_dn; //! TBranch *b_phoResol_phi_up; //! TBranch *b_phoResol_phi_dn; //! TBranch *b_nJet; //! TBranch *b_jetPt; //! TBranch *b_jetE; //! TBranch *b_jetEta; //! TBranch *b_jetPhi; //! TBranch *b_jetRawPt; //! TBranch *b_jetRawE; //! TBranch *b_jetMt; //! TBranch *b_jetArea; //! TBranch *b_jetMass; //! TBranch *b_jetMaxDistance; //! TBranch *b_jetPhiPhiMoment; //! TBranch *b_jetConstituentEtaPhiSpread; //! TBranch *b_jetConstituentPtDistribution; //! TBranch *b_jetPileup; //! TBranch *b_jetID; //! TBranch *b_jetPUID; //! TBranch *b_jetPUFullID; //! TBranch *b_jetPartonID; //! TBranch *b_jetHadFlvr; //! TBranch *b_jetJECUnc; //! TBranch *b_jetCEF; //! TBranch *b_jetNEF; //! TBranch *b_jetCHF; //! TBranch *b_jetNHF; //! TBranch *b_jetPhotonEnF; //! TBranch *b_jetElectronEnF; //! TBranch *b_jetMuonEnF; //! TBranch *b_jetChargedMuonEnF; //! TBranch *b_jetHFHAE; //! TBranch *b_jetHFEME; //! TBranch *b_jetNConst; //! TBranch *b_jetNConstituents; //! TBranch *b_jetNCharged; //! TBranch *b_jetNNeutral; //! TBranch *b_jetNChargedHad; //! TBranch *b_jetNNeutralHad; //! TBranch *b_jetNPhoton; //! TBranch *b_jetNElectron; //! TBranch *b_jetNMuon; //! TBranch *b_jetCSV2BJetTags; //! TBranch *b_jetDeepCSVTags_b; //! TBranch *b_jetDeepCSVTags_bb; //! TBranch *b_jetDeepCSVTags_c; //! TBranch *b_jetDeepCSVTags_udsg; //! TBranch *b_jetDeepFlavour_b; //! TBranch *b_jetDeepFlavour_bb; //! TBranch *b_jetDeepFlavour_lepb; //! TBranch *b_jetDeepFlavour_c; //! TBranch *b_jetDeepFlavour_uds; //! TBranch *b_jetDeepFlavour_g; //! TBranch *b_jetetaWidth; //! TBranch *b_jetphiWidth; //! TBranch *b_jetConstPt; //! TBranch *b_jetConstEt; //! TBranch *b_jetConstEta; //! TBranch *b_jetConstPhi; //! TBranch *b_jetConstPdgId; //! TBranch *b_jetGenJetE; //! TBranch *b_jetGenJetPt; //! TBranch *b_jetGenJetEta; //! TBranch *b_jetGenJetPhi; //! TBranch *b_jetGenPartonID; //! TBranch *b_jetGenE; //! TBranch *b_jetGenPt; //! TBranch *b_jetGenEta; //! TBranch *b_jetGenPhi; //! TBranch *b_jetGenPartonMomID; //! TBranch *b_jetP4Smear; //! TBranch *b_jetP4SmearUp; //! TBranch *b_jetP4SmearDo; //! TBranch *b_nEle; //! TBranch *b_elePt; //! TBranch *b_eleEta; //! TBranch *b_elePhi; //! TBranch *b_eleR9Full5x5; //! TBranch *b_eleE; //! TBranch *b_eleCharge; //! TBranch *b_eleChargeConsistent; //! TBranch *b_eleD0; //! TBranch *b_eleDz; //! TBranch *b_eleSIP; //! TBranch *b_eleUnCalibE; //! TBranch *b_eleUnCalibESigma; //! TBranch *b_eleCalibEecalonly; //! TBranch *b_eleCalibE; //! TBranch *b_eleCalibESigma; //! TBranch *b_eleCalibEt; //! TBranch *b_eleCalibEtSigma; //! TBranch *b_eleEnergyScale; //! TBranch *b_eleEnergySigma; //! TBranch *b_eleSCRawE; //! TBranch *b_eleSCE; //! TBranch *b_eleSCEta; //! TBranch *b_eleSCPhi; //! TBranch *b_eleSCEtaWidth; //! TBranch *b_eleSCPhiWidth; //! TBranch *b_eleHoverE; //! TBranch *b_eleEoverP; //! TBranch *b_eleEoverPout; //! TBranch *b_eleEoverPInv; //! TBranch *b_eleBrem; //! TBranch *b_eledEtaAtVtx; //! TBranch *b_eledPhiAtVtx; //! TBranch *b_eledEtaAtCalo; //! TBranch *b_eledEtaseedAtVtx; //! TBranch *b_eleSigmaIEtaIEtaFull5x5; //! TBranch *b_eleSigmaIPhiIPhiFull5x5; //! TBranch *b_eleConvVeto; //! TBranch *b_eleMissHits; //! TBranch *b_elePFChIso; //! TBranch *b_elePFPhoIso; //! TBranch *b_elePFNeuIso; //! TBranch *b_elePFPUIso; //! TBranch *b_elePFClusEcalIso; //! TBranch *b_elePFClusHcalIso; //! TBranch *b_eleFiredSingleTrgs; //! TBranch *b_eleFiredDoubleTrgs; //! TBranch *b_eleFiredL1Trgs; //! TBranch *b_eleHEEPID; //! TBranch *b_eleMVAIsoID; //! TBranch *b_eleMVAnoIsoID; //! TBranch *b_eleIDbit; //! TBranch *b_eleTrkdxy; //! TBranch *b_eleKFHits; //! TBranch *b_eleKFChi2; //! TBranch *b_eleGSFChi2; //! TBranch *b_eleScale_up; //! TBranch *b_eleScale_dn; //! TBranch *b_eleScale_stat_up; //! TBranch *b_eleScale_stat_dn; //! TBranch *b_eleScale_syst_up; //! TBranch *b_eleScale_syst_dn; //! TBranch *b_eleScale_gain_up; //! TBranch *b_eleScale_gain_dn; //! TBranch *b_eleResol_up; //! TBranch *b_eleResol_dn; //! TBranch *b_eleResol_rho_up; //! TBranch *b_eleResol_rho_dn; //! TBranch *b_eleResol_phi_up; //! TBranch *b_eleResol_phi_dn; //! TBranch *b_nMu; //! TBranch *b_muPt; //! TBranch *b_muE; //! TBranch *b_muEta; //! TBranch *b_muPhi; //! TBranch *b_muCharge; //! TBranch *b_muType; //! TBranch *b_muIDbit; //! TBranch *b_muD0; //! TBranch *b_muDz; //! TBranch *b_muSIP; //! TBranch *b_muChi2NDF; //! TBranch *b_muInnerD0; //! TBranch *b_muInnerDz; //! TBranch *b_muTrkLayers; //! TBranch *b_muPixelLayers; //! TBranch *b_muPixelHits; //! TBranch *b_muMuonHits; //! TBranch *b_muStations; //! TBranch *b_muMatches; //! TBranch *b_muTrkQuality; //! TBranch *b_muInnervalidFraction; //! TBranch *b_muIsoTrk; //! TBranch *b_muPFChIso; //! TBranch *b_muPFPhoIso; //! TBranch *b_muPFNeuIso; //! TBranch *b_muPFPUIso; //! TBranch *b_musegmentCompatibility; //! TBranch *b_muchi2LocalPosition; //! TBranch *b_mutrkKink; //! TBranch *b_muBestTrkPtError; //! TBranch *b_muBestTrkPt; //! TBranch *b_muBestTrkType; //! TBranch *b_muFiredTrgs; //! TBranch *b_muFiredL1Trgs; //! TBranch *b_nTau; //! TBranch *b_tau_Pt; //! TBranch *b_tau_Et; //! TBranch *b_tau_Eta; //! TBranch *b_tau_Phi; //! TBranch *b_tau_Charge; //! TBranch *b_tau_DecayMode; //! TBranch *b_tau_decayModeFindingNewDMs; //! TBranch *b_tau_P; //! TBranch *b_tau_Vz; //! TBranch *b_tau_Energy; //! TBranch *b_tau_Mass; //! TBranch *b_tau_Dxy; //! TBranch *b_tau_ZImpact; //! TBranch *b_tau_byCombinedIsolationDeltaBetaCorrRaw3Hits; //! TBranch *b_tau_chargedIsoPtSum; //! TBranch *b_tau_neutralIsoPtSum; //! TBranch *b_tau_neutralIsoPtSumWeight; //! TBranch *b_tau_footprintCorrection; //! TBranch *b_tau_photonPtSumOutsideSignalCone; //! TBranch *b_tau_puCorrPtSum; //! TBranch *b_tau_NumSignalPFChargedHadrCands; //! TBranch *b_tau_NumSignalPFNeutrHadrCands; //! TBranch *b_tau_NumSignalPFGammaCands; //! TBranch *b_tau_NumSignalPFCands; //! TBranch *b_tau_NumIsolationPFChargedHadrCands; //! TBranch *b_tau_NumIsolationPFNeutrHadrCands; //! TBranch *b_tau_NumIsolationPFGammaCands; //! TBranch *b_tau_NumIsolationPFCands; //! TBranch *b_tau_LeadChargedHadronEta; //! TBranch *b_tau_LeadChargedHadronPhi; //! TBranch *b_tau_LeadChargedHadronPt; //! TBranch *b_tau_LeadChargedHadron_dz; //! TBranch *b_tau_LeadChargedHadron_dxy; //! TBranch *b_tau_IDbits; //! TBranch *b_tau_byIsolationMVArun2017v2DBoldDMwLTraw2017; //! TBranch *b_tau_byVVVLooseDeepTau2017v2p1VSjet; //! TBranch *b_tau_byVVLooseDeepTau2017v2p1VSjet; //! TBranch *b_tau_byVLooseDeepTau2017v2p1VSjet; //! TBranch *b_tau_byLooseDeepTau2017v2p1VSjet; //! TBranch *b_tau_byMediumDeepTau2017v2p1VSjet; //! TBranch *b_tau_byTightDeepTau2017v2p1VSjet; //! TBranch *b_tau_byVTightDeepTau2017v2p1VSjet; //! TBranch *b_tau_byVVTightDeepTau2017v2p1VSjet; //! TBranch *b_tau_byVVVLooseDeepTau2017v2p1VSe; //! TBranch *b_tau_byVVLooseDeepTau2017v2p1VSe; //! TBranch *b_tau_byVLooseDeepTau2017v2p1VSe; //! TBranch *b_tau_byLooseDeepTau2017v2p1VSe; //! TBranch *b_tau_byMediumDeepTau2017v2p1VSe; //! TBranch *b_tau_byTightDeepTau2017v2p1VSe; //! TBranch *b_tau_byVTightDeepTau2017v2p1VSe; //! TBranch *b_tau_byVVTightDeepTau2017v2p1VSe; //! TBranch *b_tau_byVLooseDeepTau2017v2p1VSmu; //! TBranch *b_tau_byLooseDeepTau2017v2p1VSmu; //! TBranch *b_tau_byMediumDeepTau2017v2p1VSmu; //! TBranch *b_tau_byTightDeepTau2017v2p1VSmu; //! TBranch *b_tauFiredTrgs; //! TBranch *b_tauFiredL1Trgs; //! TBranch *b_genMET; //! TBranch *b_genMETPhi; //! TBranch *b_metFilters; //! TBranch *b_caloMET; //! TBranch *b_caloMETPhi; //! TBranch *b_caloMETsumEt; //! TBranch *b_pfMETCorr; //! TBranch *b_pfMETPhiCorr; //! TBranch *b_pfMET; //! TBranch *b_pfMETPhi; //! TBranch *b_pfMETsumEt; //! TBranch *b_pfMETmEtSig; //! TBranch *b_pfMETSig; //! TBranch *b_pfMET_T1JERUp; //! TBranch *b_pfMET_T1JERDo; //! TBranch *b_pfMET_T1JESUp; //! TBranch *b_pfMET_T1JESDo; //! TBranch *b_pfMET_T1UESUp; //! TBranch *b_pfMET_T1UESDo; //! TBranch *b_pfMETPhi_T1JESUp; //! TBranch *b_pfMETPhi_T1JESDo; //! TBranch *b_pfMETPhi_T1UESUp; //! TBranch *b_pfMETPhi_T1UESDo; //! TBranch *b_pdf; //! TBranch *b_pthat; //! TBranch *b_processID; //! TBranch *b_genWeight; //! TBranch *b_genHT; //! TBranch *b_pdfWeight; //! TBranch *b_pdfSystWeight; //! TBranch *b_nPUInfo; //! TBranch *b_nPU; //! TBranch *b_puBX; //! TBranch *b_puTrue; //! TBranch *b_nMC; //! TBranch *b_mcPID; //! TBranch *b_mcVtx; //! TBranch *b_mcVty; //! TBranch *b_mcVtz; //! TBranch *b_mcPt; //! TBranch *b_mcMass; //! TBranch *b_mcEta; //! TBranch *b_mcPhi; //! TBranch *b_mcE; //! TBranch *b_mcEt; //! TBranch *b_mcStatus; //! TBranch *b_mcStatusFlag; //! TBranch *b_mcIndex; //! TBranch *b_mcDaughterPID; //! TBranch *b_mcCharge; //! TBranch *b_mcMotherPID; //! TBranch *b_mcMotherIndex; //! TBranch *b_mcMotherStatus; //! TBranch *b_mcDaughterStatus; //! TBranch *b_mcDaughterList; //! TBranch *b_mcTauDecayMode; //! TBranch *b_genMatch2; //! // skimm_tt_2018(TTree *tree=0); skimm_tt_2018(const char* file1, const char* file2, string isMC); virtual ~skimm_tt_2018(); virtual Int_t Cut(Long64_t entry); virtual Int_t GetEntry(Long64_t entry); virtual Long64_t LoadTree(Long64_t entry); virtual void Init(TChain *tree, string isMC); //virtual void Init(TTree *tree); virtual void Loop(Long64_t maxEvents, int reportEvery, string SampleName, string _isMC_); virtual Bool_t Notify(); virtual void Show(Long64_t entry = -1); virtual void BookHistos(const char* file2); virtual void fillHistos(int histoNumber, double event_weight,int higgs_index); virtual bool skimming_Htt(); virtual vector<int> skimmed_Mu(); virtual vector<int> skimmed_Tau(); virtual void fillOutTree(); virtual double DeltaPhi(double phi1, double phi2); virtual double dR(int mu_index, int tau_index); }; #endif #ifdef skimm_tt_2018_cxx skimm_tt_2018::skimm_tt_2018(const char* file1, const char* file2, string isMC) { TChain *chain = new TChain("phoJetNtuplizer/eventTree"); //TH1F *inspected_events = new TH1F("inspected_events","inspected_events", 5, 0, 5); //Run over all files in file1, presumably /hdfs/store/user/<etc>/ (must end with a /) TString path = file1; TSystemDirectory sourceDir("hi",path); TList* fileList = sourceDir.GetListOfFiles(); TIter next(fileList); TSystemFile* filename; int fileNumber = 0; int maxFiles = -1; while ((filename = (TSystemFile*)next()) && fileNumber > maxFiles) { //if(fileNumber > 1) { TString dataset = "Ntuple_"; TString FullPathInputFile = (path+filename->GetName()); TString name = filename->GetName(); if(name.Contains(dataset)) { //TFile *f_ins=new TFile(FullPathInputFile); //TH1F *h_ins=(TH1F*) f_ins->Get("ins_Events"); //std::cout<<"FullPathInputFile:"<<FullPathInputFile<<std::endl; chain->Add(FullPathInputFile); //inspected_events->Add(h_ins); //h_ins->Delete(); //f_ins->Close(); } } fileNumber++; } std::cout<<"********** for MC *********"<<std::endl; std::cout<<"All files added."<<std::endl; std::cout<<"Initializing chain."<<std::endl; Init(chain, isMC); BookHistos(file2); } skimm_tt_2018::~skimm_tt_2018() { if (!fChain) return; delete fChain->GetCurrentFile(); fileName->cd(); fileName->Write(); fileName->Close(); } Int_t skimm_tt_2018::GetEntry(Long64_t entry) { // Read contents of entry. if (!fChain) return 0; return fChain->GetEntry(entry); } Long64_t skimm_tt_2018::LoadTree(Long64_t entry) { // Set the environment to read one entry if (!fChain) return -5; Long64_t centry = fChain->LoadTree(entry); if (centry < 0) return centry; if (fChain->GetTreeNumber() != fCurrent) { fCurrent = fChain->GetTreeNumber(); Notify(); } return centry; } void skimm_tt_2018::Init(TChain *tree, string _isMC_) { // The Init() function is called when the selector needs to initialize // a new tree or chain. Typically here the branch addresses and branch // pointers of the tree will be set. // It is normally not necessary to make changes to the generated // code, but the routine can be extended by the user if needed. // Init() will be called many times when running on PROOF // (once per file to be processed). TString isMC = TString(_isMC_); cout<<"from Init "<<isMC<<endl; // Set object pointer phoE = 0; phoEt = 0; phoEta = 0; phoPhi = 0; phoUnCalibE = 0; phoUnCalibESigma = 0; phoCalibE = 0; phoCalibESigma = 0; phoCalibEt = 0; phoEnergyScale = 0; phoEnergySigma = 0; phoSCE = 0; phoSCRawE = 0; phoSCEta = 0; phoSCPhi = 0; phoSCEtaWidth = 0; phoSCPhiWidth = 0; phohasPixelSeed = 0; phoEleVeto = 0; phoR9Full5x5 = 0; phoHoverE = 0; phoSigmaIEtaIEtaFull5x5 = 0; phoSigmaIEtaIPhiFull5x5 = 0; phoSigmaIPhiIPhiFull5x5 = 0; phoPFChIso = 0; phoPFChWorstIso = 0; phoPFPhoIso = 0; phoPFNeuIso = 0; phoIDMVA = 0; phoIDbit = 0; phoSeedTime = 0; phoSeedEnergy = 0; phoFiredSingleTrgs = 0; phoFiredDoubleTrgs = 0; phoFiredTripleTrgs = 0; phoFiredL1Trgs = 0; phoScale_up = 0; phoScale_dn = 0; phoScale_stat_up = 0; phoScale_stat_dn = 0; phoScale_syst_up = 0; phoScale_syst_dn = 0; phoScale_gain_up = 0; phoScale_gain_dn = 0; phoResol_up = 0; phoResol_dn = 0; phoResol_rho_up = 0; phoResol_rho_dn = 0; phoResol_phi_up = 0; phoResol_phi_dn = 0; jetPt = 0; jetE = 0; jetEta = 0; jetPhi = 0; jetRawPt = 0; jetRawE = 0; jetMt = 0; jetArea = 0; jetMass = 0; jetMaxDistance = 0; jetPhiPhiMoment = 0; jetConstituentEtaPhiSpread = 0; jetConstituentPtDistribution = 0; jetPileup = 0; jetID = 0; jetPUID = 0; jetPUFullID = 0; jetPartonID = 0; jetHadFlvr = 0; jetJECUnc = 0; jetCEF = 0; jetNEF = 0; jetCHF = 0; jetNHF = 0; jetPhotonEnF = 0; jetElectronEnF = 0; jetMuonEnF = 0; jetChargedMuonEnF = 0; jetHFHAE = 0; jetHFEME = 0; jetNConst = 0; jetNConstituents = 0; jetNCharged = 0; jetNNeutral = 0; jetNChargedHad = 0; jetNNeutralHad = 0; jetNPhoton = 0; jetNElectron = 0; jetNMuon = 0; jetCSV2BJetTags = 0; jetDeepCSVTags_b = 0; jetDeepCSVTags_bb = 0; jetDeepCSVTags_c = 0; jetDeepCSVTags_udsg = 0; jetDeepFlavour_b = 0; jetDeepFlavour_bb = 0; jetDeepFlavour_lepb = 0; jetDeepFlavour_c = 0; jetDeepFlavour_uds = 0; jetDeepFlavour_g = 0; jetetaWidth = 0; jetphiWidth = 0; jetConstPt = 0; jetConstEt = 0; jetConstEta = 0; jetConstPhi = 0; jetConstPdgId = 0; jetGenJetE = 0; jetGenJetPt = 0; jetGenJetEta = 0; jetGenJetPhi = 0; jetGenPartonID = 0; jetGenE = 0; jetGenPt = 0; jetGenEta = 0; jetGenPhi = 0; jetGenPartonMomID = 0; jetP4Smear = 0; jetP4SmearUp = 0; jetP4SmearDo = 0; elePt = 0; eleEta = 0; elePhi = 0; eleR9Full5x5 = 0; eleE = 0; eleCharge = 0; eleChargeConsistent = 0; eleD0 = 0; eleDz = 0; eleSIP = 0; eleUnCalibE = 0; eleUnCalibESigma = 0; eleCalibEecalonly = 0; eleCalibE = 0; eleCalibESigma = 0; eleCalibEt = 0; eleCalibEtSigma = 0; eleEnergyScale = 0; eleEnergySigma = 0; eleSCRawE = 0; eleSCE = 0; eleSCEta = 0; eleSCPhi = 0; eleSCEtaWidth = 0; eleSCPhiWidth = 0; eleHoverE = 0; eleEoverP = 0; eleEoverPout = 0; eleEoverPInv = 0; eleBrem = 0; eledEtaAtVtx = 0; eledPhiAtVtx = 0; eledEtaAtCalo = 0; eledEtaseedAtVtx = 0; eleSigmaIEtaIEtaFull5x5 = 0; eleSigmaIPhiIPhiFull5x5 = 0; eleConvVeto = 0; eleMissHits = 0; elePFChIso = 0; elePFPhoIso = 0; elePFNeuIso = 0; elePFPUIso = 0; elePFClusEcalIso = 0; elePFClusHcalIso = 0; eleFiredSingleTrgs = 0; eleFiredDoubleTrgs = 0; eleFiredL1Trgs = 0; eleHEEPID = 0; eleMVAIsoID = 0; eleMVAnoIsoID = 0; eleIDbit = 0; eleTrkdxy = 0; eleKFHits = 0; eleKFChi2 = 0; eleGSFChi2 = 0; eleScale_up = 0; eleScale_dn = 0; eleScale_stat_up = 0; eleScale_stat_dn = 0; eleScale_syst_up = 0; eleScale_syst_dn = 0; eleScale_gain_up = 0; eleScale_gain_dn = 0; eleResol_up = 0; eleResol_dn = 0; eleResol_rho_up = 0; eleResol_rho_dn = 0; eleResol_phi_up = 0; eleResol_phi_dn = 0; muPt = 0; muE = 0; muEta = 0; muPhi = 0; muCharge = 0; muType = 0; muIDbit = 0; muD0 = 0; muDz = 0; muSIP = 0; muChi2NDF = 0; muInnerD0 = 0; muInnerDz = 0; muTrkLayers = 0; muPixelLayers = 0; muPixelHits = 0; muMuonHits = 0; muStations = 0; muMatches = 0; muTrkQuality = 0; muInnervalidFraction = 0; muIsoTrk = 0; muPFChIso = 0; muPFPhoIso = 0; muPFNeuIso = 0; muPFPUIso = 0; musegmentCompatibility = 0; muchi2LocalPosition = 0; mutrkKink = 0; muBestTrkPtError = 0; muBestTrkPt = 0; muBestTrkType = 0; muFiredTrgs = 0; muFiredL1Trgs = 0; tau_Pt = 0; tau_Et = 0; tau_Eta = 0; tau_Phi = 0; tau_Charge = 0; tau_DecayMode = 0; tau_decayModeFindingNewDMs = 0; tau_P = 0; tau_Vz = 0; tau_Energy = 0; tau_Mass = 0; tau_Dxy = 0; tau_ZImpact = 0; tau_byCombinedIsolationDeltaBetaCorrRaw3Hits = 0; tau_chargedIsoPtSum = 0; tau_neutralIsoPtSum = 0; tau_neutralIsoPtSumWeight = 0; tau_footprintCorrection = 0; tau_photonPtSumOutsideSignalCone = 0; tau_puCorrPtSum = 0; tau_NumSignalPFChargedHadrCands = 0; tau_NumSignalPFNeutrHadrCands = 0; tau_NumSignalPFGammaCands = 0; tau_NumSignalPFCands = 0; tau_NumIsolationPFChargedHadrCands = 0; tau_NumIsolationPFNeutrHadrCands = 0; tau_NumIsolationPFGammaCands = 0; tau_NumIsolationPFCands = 0; tau_LeadChargedHadronEta = 0; tau_LeadChargedHadronPhi = 0; tau_LeadChargedHadronPt = 0; tau_LeadChargedHadron_dz = 0; tau_LeadChargedHadron_dxy = 0; tau_IDbits = 0; tau_byIsolationMVArun2017v2DBoldDMwLTraw2017 = 0; tau_byVVVLooseDeepTau2017v2p1VSjet = 0; tau_byVVLooseDeepTau2017v2p1VSjet = 0; tau_byVLooseDeepTau2017v2p1VSjet = 0; tau_byLooseDeepTau2017v2p1VSjet = 0; tau_byMediumDeepTau2017v2p1VSjet = 0; tau_byTightDeepTau2017v2p1VSjet = 0; tau_byVTightDeepTau2017v2p1VSjet = 0; tau_byVVTightDeepTau2017v2p1VSjet = 0; tau_byVVVLooseDeepTau2017v2p1VSe = 0; tau_byVVLooseDeepTau2017v2p1VSe = 0; tau_byVLooseDeepTau2017v2p1VSe = 0; tau_byLooseDeepTau2017v2p1VSe = 0; tau_byMediumDeepTau2017v2p1VSe = 0; tau_byTightDeepTau2017v2p1VSe = 0; tau_byVTightDeepTau2017v2p1VSe = 0; tau_byVVTightDeepTau2017v2p1VSe = 0; tau_byVLooseDeepTau2017v2p1VSmu = 0; tau_byLooseDeepTau2017v2p1VSmu = 0; tau_byMediumDeepTau2017v2p1VSmu = 0; tau_byTightDeepTau2017v2p1VSmu = 0; tauFiredTrgs = 0; tauFiredL1Trgs = 0; pdf = 0; pdfSystWeight = 0; nPU = 0; puBX = 0; puTrue = 0; mcPID = 0; mcVtx = 0; mcVty = 0; mcVtz = 0; mcPt = 0; mcMass = 0; mcEta = 0; mcPhi = 0; mcE = 0; mcEt = 0; mcStatus = 0; mcStatusFlag = 0; mcIndex = 0; mcDaughterPID = 0; mcCharge = 0; mcMotherPID = 0; mcMotherIndex = 0; mcMotherStatus = 0; mcDaughterStatus = 0; mcDaughterList = 0; mcTauDecayMode = 0; genMatch2 = 0; // Set branch addresses and branch pointers if (!tree) return; fChain = tree; fCurrent = -1; fChain->SetMakeClass(1); fChain->SetBranchAddress("run", &run, &b_run); fChain->SetBranchAddress("event", &event, &b_event); fChain->SetBranchAddress("lumis", &lumis, &b_lumis); fChain->SetBranchAddress("isData", &isData, &b_isData); fChain->SetBranchAddress("nVtx", &nVtx, &b_nVtx); fChain->SetBranchAddress("vtxX", &vtxX, &b_vtxX); fChain->SetBranchAddress("vtxY", &vtxY, &b_vtxY); fChain->SetBranchAddress("vtxZ", &vtxZ, &b_vtxZ); fChain->SetBranchAddress("vtxNtrks", &vtxNtrks, &b_vtxNtrks); fChain->SetBranchAddress("vtx_isFake", &vtx_isFake, &b_vtx_isFake); fChain->SetBranchAddress("vtx_ndof", &vtx_ndof, &b_vtx_ndof); fChain->SetBranchAddress("vtx_rho", &vtx_rho, &b_vtx_rho); fChain->SetBranchAddress("isGoodVtx", &isGoodVtx, &b_isGoodVtx); fChain->SetBranchAddress("nGoodVtx", &nGoodVtx, &b_nGoodVtx); fChain->SetBranchAddress("rho", &rho, &b_rho); fChain->SetBranchAddress("rhoCentral", &rhoCentral, &b_rhoCentral); /* fChain->SetBranchAddress("prefiringweight", &prefiringweight, &b_prefiringweight); */ /* fChain->SetBranchAddress("prefiringweightup", &prefiringweightup, &b_prefiringweightup); */ /* fChain->SetBranchAddress("prefiringweightdown", &prefiringweightdown, &b_prefiringweightdown); */ fChain->SetBranchAddress("HLTEleMuX", &HLTEleMuX, &b_HLTEleMuX); fChain->SetBranchAddress("HLTEleMuXIsPrescaled", &HLTEleMuXIsPrescaled, &b_HLTEleMuXIsPrescaled); fChain->SetBranchAddress("HLTEleMuXRejectedByPS", &HLTEleMuXRejectedByPS, &b_HLTEleMuXRejectedByPS); fChain->SetBranchAddress("HLTPho", &HLTPho, &b_HLTPho); fChain->SetBranchAddress("HLTPhoIsPrescaled", &HLTPhoIsPrescaled, &b_HLTPhoIsPrescaled); fChain->SetBranchAddress("HLTPhoRejectedByPS", &HLTPhoRejectedByPS, &b_HLTPhoRejectedByPS); fChain->SetBranchAddress("HLTTau", &HLTTau, &b_HLTTau); fChain->SetBranchAddress("HLTTauIsPrescaled", &HLTTauIsPrescaled, &b_HLTTauIsPrescaled); fChain->SetBranchAddress("HLTTauRejectedByPS", &HLTTauRejectedByPS, &b_HLTTauRejectedByPS); fChain->SetBranchAddress("HLTMet", &HLTMet, &b_HLTMet); fChain->SetBranchAddress("HLTMetIsPrescaled", &HLTMetIsPrescaled, &b_HLTMetIsPrescaled); fChain->SetBranchAddress("HLTMetRejectedByPS", &HLTMetRejectedByPS, &b_HLTMetRejectedByPS); fChain->SetBranchAddress("HLTJet", &HLTJet, &b_HLTJet); fChain->SetBranchAddress("HLTJetIsPrescaled", &HLTJetIsPrescaled, &b_HLTJetIsPrescaled); fChain->SetBranchAddress("HLTJetRejectedByPS", &HLTJetRejectedByPS, &b_HLTJetRejectedByPS); fChain->SetBranchAddress("nPho", &nPho, &b_nPho); fChain->SetBranchAddress("phoE", &phoE, &b_phoE); fChain->SetBranchAddress("phoEt", &phoEt, &b_phoEt); fChain->SetBranchAddress("phoEta", &phoEta, &b_phoEta); fChain->SetBranchAddress("phoPhi", &phoPhi, &b_phoPhi); fChain->SetBranchAddress("phoUnCalibE", &phoUnCalibE, &b_phoUnCalibE); fChain->SetBranchAddress("phoUnCalibESigma", &phoUnCalibESigma, &b_phoUnCalibESigma); fChain->SetBranchAddress("phoCalibE", &phoCalibE, &b_phoCalibE); fChain->SetBranchAddress("phoCalibESigma", &phoCalibESigma, &b_phoCalibESigma); fChain->SetBranchAddress("phoCalibEt", &phoCalibEt, &b_phoCalibEt); fChain->SetBranchAddress("phoEnergyScale", &phoEnergyScale, &b_phoEnergyScale); fChain->SetBranchAddress("phoEnergySigma", &phoEnergySigma, &b_phoEnergySigma); fChain->SetBranchAddress("phoSCE", &phoSCE, &b_phoSCE); fChain->SetBranchAddress("phoSCRawE", &phoSCRawE, &b_phoSCRawE); fChain->SetBranchAddress("phoSCEta", &phoSCEta, &b_phoSCEta); fChain->SetBranchAddress("phoSCPhi", &phoSCPhi, &b_phoSCPhi); fChain->SetBranchAddress("phoSCEtaWidth", &phoSCEtaWidth, &b_phoSCEtaWidth); fChain->SetBranchAddress("phoSCPhiWidth", &phoSCPhiWidth, &b_phoSCPhiWidth); fChain->SetBranchAddress("phohasPixelSeed", &phohasPixelSeed, &b_phohasPixelSeed); fChain->SetBranchAddress("phoEleVeto", &phoEleVeto, &b_phoEleVeto); fChain->SetBranchAddress("phoR9Full5x5", &phoR9Full5x5, &b_phoR9Full5x5); fChain->SetBranchAddress("phoHoverE", &phoHoverE, &b_phoHoverE); fChain->SetBranchAddress("phoSigmaIEtaIEtaFull5x5", &phoSigmaIEtaIEtaFull5x5, &b_phoSigmaIEtaIEtaFull5x5); fChain->SetBranchAddress("phoSigmaIEtaIPhiFull5x5", &phoSigmaIEtaIPhiFull5x5, &b_phoSigmaIEtaIPhiFull5x5); fChain->SetBranchAddress("phoSigmaIPhiIPhiFull5x5", &phoSigmaIPhiIPhiFull5x5, &b_phoSigmaIPhiIPhiFull5x5); fChain->SetBranchAddress("phoPFChIso", &phoPFChIso, &b_phoPFChIso); fChain->SetBranchAddress("phoPFChWorstIso", &phoPFChWorstIso, &b_phoPFChWorstIso); fChain->SetBranchAddress("phoPFPhoIso", &phoPFPhoIso, &b_phoPFPhoIso); fChain->SetBranchAddress("phoPFNeuIso", &phoPFNeuIso, &b_phoPFNeuIso); fChain->SetBranchAddress("phoIDMVA", &phoIDMVA, &b_phoIDMVA); fChain->SetBranchAddress("phoIDbit", &phoIDbit, &b_phoIDbit); fChain->SetBranchAddress("phoSeedTime", &phoSeedTime, &b_phoSeedTime); fChain->SetBranchAddress("phoSeedEnergy", &phoSeedEnergy, &b_phoSeedEnergy); fChain->SetBranchAddress("phoFiredSingleTrgs", &phoFiredSingleTrgs, &b_phoFiredSingleTrgs); fChain->SetBranchAddress("phoFiredDoubleTrgs", &phoFiredDoubleTrgs, &b_phoFiredDoubleTrgs); fChain->SetBranchAddress("phoFiredTripleTrgs", &phoFiredTripleTrgs, &b_phoFiredTripleTrgs); fChain->SetBranchAddress("phoFiredL1Trgs", &phoFiredL1Trgs, &b_phoFiredL1Trgs); fChain->SetBranchAddress("phoScale_up", &phoScale_up, &b_phoScale_up); fChain->SetBranchAddress("phoScale_dn", &phoScale_dn, &b_phoScale_dn); fChain->SetBranchAddress("phoScale_stat_up", &phoScale_stat_up, &b_phoScale_stat_up); fChain->SetBranchAddress("phoScale_stat_dn", &phoScale_stat_dn, &b_phoScale_stat_dn); fChain->SetBranchAddress("phoScale_syst_up", &phoScale_syst_up, &b_phoScale_syst_up); fChain->SetBranchAddress("phoScale_syst_dn", &phoScale_syst_dn, &b_phoScale_syst_dn); fChain->SetBranchAddress("phoScale_gain_up", &phoScale_gain_up, &b_phoScale_gain_up); fChain->SetBranchAddress("phoScale_gain_dn", &phoScale_gain_dn, &b_phoScale_gain_dn); fChain->SetBranchAddress("phoResol_up", &phoResol_up, &b_phoResol_up); fChain->SetBranchAddress("phoResol_dn", &phoResol_dn, &b_phoResol_dn); fChain->SetBranchAddress("phoResol_rho_up", &phoResol_rho_up, &b_phoResol_rho_up); fChain->SetBranchAddress("phoResol_rho_dn", &phoResol_rho_dn, &b_phoResol_rho_dn); fChain->SetBranchAddress("phoResol_phi_up", &phoResol_phi_up, &b_phoResol_phi_up); fChain->SetBranchAddress("phoResol_phi_dn", &phoResol_phi_dn, &b_phoResol_phi_dn); fChain->SetBranchAddress("nJet", &nJet, &b_nJet); fChain->SetBranchAddress("jetPt", &jetPt, &b_jetPt); fChain->SetBranchAddress("jetE", &jetE, &b_jetE); fChain->SetBranchAddress("jetEta", &jetEta, &b_jetEta); fChain->SetBranchAddress("jetPhi", &jetPhi, &b_jetPhi); fChain->SetBranchAddress("jetRawPt", &jetRawPt, &b_jetRawPt); fChain->SetBranchAddress("jetRawE", &jetRawE, &b_jetRawE); fChain->SetBranchAddress("jetMt", &jetMt, &b_jetMt); fChain->SetBranchAddress("jetArea", &jetArea, &b_jetArea); fChain->SetBranchAddress("jetMass", &jetMass, &b_jetMass); fChain->SetBranchAddress("jetMaxDistance", &jetMaxDistance, &b_jetMaxDistance); fChain->SetBranchAddress("jetPhiPhiMoment", &jetPhiPhiMoment, &b_jetPhiPhiMoment); fChain->SetBranchAddress("jetConstituentEtaPhiSpread", &jetConstituentEtaPhiSpread, &b_jetConstituentEtaPhiSpread); fChain->SetBranchAddress("jetConstituentPtDistribution", &jetConstituentPtDistribution, &b_jetConstituentPtDistribution); fChain->SetBranchAddress("jetPileup", &jetPileup, &b_jetPileup); fChain->SetBranchAddress("jetID", &jetID, &b_jetID); fChain->SetBranchAddress("jetPUID", &jetPUID, &b_jetPUID); fChain->SetBranchAddress("jetPUFullID", &jetPUFullID, &b_jetPUFullID); fChain->SetBranchAddress("jetPartonID", &jetPartonID, &b_jetPartonID); fChain->SetBranchAddress("jetHadFlvr", &jetHadFlvr, &b_jetHadFlvr); fChain->SetBranchAddress("jetJECUnc", &jetJECUnc, &b_jetJECUnc); fChain->SetBranchAddress("jetCEF", &jetCEF, &b_jetCEF); fChain->SetBranchAddress("jetNEF", &jetNEF, &b_jetNEF); fChain->SetBranchAddress("jetCHF", &jetCHF, &b_jetCHF); fChain->SetBranchAddress("jetNHF", &jetNHF, &b_jetNHF); fChain->SetBranchAddress("jetPhotonEnF", &jetPhotonEnF, &b_jetPhotonEnF); fChain->SetBranchAddress("jetElectronEnF", &jetElectronEnF, &b_jetElectronEnF); fChain->SetBranchAddress("jetMuonEnF", &jetMuonEnF, &b_jetMuonEnF); fChain->SetBranchAddress("jetChargedMuonEnF", &jetChargedMuonEnF, &b_jetChargedMuonEnF); fChain->SetBranchAddress("jetHFHAE", &jetHFHAE, &b_jetHFHAE); fChain->SetBranchAddress("jetHFEME", &jetHFEME, &b_jetHFEME); fChain->SetBranchAddress("jetNConst", &jetNConst, &b_jetNConst); fChain->SetBranchAddress("jetNConstituents", &jetNConstituents, &b_jetNConstituents); fChain->SetBranchAddress("jetNCharged", &jetNCharged, &b_jetNCharged); fChain->SetBranchAddress("jetNNeutral", &jetNNeutral, &b_jetNNeutral); fChain->SetBranchAddress("jetNChargedHad", &jetNChargedHad, &b_jetNChargedHad); fChain->SetBranchAddress("jetNNeutralHad", &jetNNeutralHad, &b_jetNNeutralHad); fChain->SetBranchAddress("jetNPhoton", &jetNPhoton, &b_jetNPhoton); fChain->SetBranchAddress("jetNElectron", &jetNElectron, &b_jetNElectron); fChain->SetBranchAddress("jetNMuon", &jetNMuon, &b_jetNMuon); fChain->SetBranchAddress("jetCSV2BJetTags", &jetCSV2BJetTags, &b_jetCSV2BJetTags); fChain->SetBranchAddress("jetDeepCSVTags_b", &jetDeepCSVTags_b, &b_jetDeepCSVTags_b); fChain->SetBranchAddress("jetDeepCSVTags_bb", &jetDeepCSVTags_bb, &b_jetDeepCSVTags_bb); fChain->SetBranchAddress("jetDeepCSVTags_c", &jetDeepCSVTags_c, &b_jetDeepCSVTags_c); fChain->SetBranchAddress("jetDeepCSVTags_udsg", &jetDeepCSVTags_udsg, &b_jetDeepCSVTags_udsg); fChain->SetBranchAddress("jetDeepFlavour_b", &jetDeepFlavour_b, &b_jetDeepFlavour_b); fChain->SetBranchAddress("jetDeepFlavour_bb", &jetDeepFlavour_bb, &b_jetDeepFlavour_bb); fChain->SetBranchAddress("jetDeepFlavour_lepb", &jetDeepFlavour_lepb, &b_jetDeepFlavour_lepb); fChain->SetBranchAddress("jetDeepFlavour_c", &jetDeepFlavour_c, &b_jetDeepFlavour_c); fChain->SetBranchAddress("jetDeepFlavour_uds", &jetDeepFlavour_uds, &b_jetDeepFlavour_uds); fChain->SetBranchAddress("jetDeepFlavour_g", &jetDeepFlavour_g, &b_jetDeepFlavour_g); fChain->SetBranchAddress("jetetaWidth", &jetetaWidth, &b_jetetaWidth); fChain->SetBranchAddress("jetphiWidth", &jetphiWidth, &b_jetphiWidth); fChain->SetBranchAddress("jetConstPt", &jetConstPt, &b_jetConstPt); fChain->SetBranchAddress("jetConstEt", &jetConstEt, &b_jetConstEt); fChain->SetBranchAddress("jetConstEta", &jetConstEta, &b_jetConstEta); fChain->SetBranchAddress("jetConstPhi", &jetConstPhi, &b_jetConstPhi); fChain->SetBranchAddress("jetConstPdgId", &jetConstPdgId, &b_jetConstPdgId); if(isMC=="MC"){ fChain->SetBranchAddress("jetGenJetE", &jetGenJetE, &b_jetGenJetE); fChain->SetBranchAddress("jetGenJetPt", &jetGenJetPt, &b_jetGenJetPt); fChain->SetBranchAddress("jetGenJetEta", &jetGenJetEta, &b_jetGenJetEta); fChain->SetBranchAddress("jetGenJetPhi", &jetGenJetPhi, &b_jetGenJetPhi); fChain->SetBranchAddress("jetGenPartonID", &jetGenPartonID, &b_jetGenPartonID); fChain->SetBranchAddress("jetGenE", &jetGenE, &b_jetGenE); fChain->SetBranchAddress("jetGenPt", &jetGenPt, &b_jetGenPt); fChain->SetBranchAddress("jetGenEta", &jetGenEta, &b_jetGenEta); fChain->SetBranchAddress("jetGenPhi", &jetGenPhi, &b_jetGenPhi); fChain->SetBranchAddress("jetGenPartonMomID", &jetGenPartonMomID, &b_jetGenPartonMomID); fChain->SetBranchAddress("jetP4Smear", &jetP4Smear, &b_jetP4Smear); fChain->SetBranchAddress("jetP4SmearUp", &jetP4SmearUp, &b_jetP4SmearUp); fChain->SetBranchAddress("jetP4SmearDo", &jetP4SmearDo, &b_jetP4SmearDo); } fChain->SetBranchAddress("nEle", &nEle, &b_nEle); fChain->SetBranchAddress("elePt", &elePt, &b_elePt); fChain->SetBranchAddress("eleEta", &eleEta, &b_eleEta); fChain->SetBranchAddress("elePhi", &elePhi, &b_elePhi); fChain->SetBranchAddress("eleR9Full5x5", &eleR9Full5x5, &b_eleR9Full5x5); fChain->SetBranchAddress("eleE", &eleE, &b_eleE); fChain->SetBranchAddress("eleCharge", &eleCharge, &b_eleCharge); fChain->SetBranchAddress("eleChargeConsistent", &eleChargeConsistent, &b_eleChargeConsistent); fChain->SetBranchAddress("eleD0", &eleD0, &b_eleD0); fChain->SetBranchAddress("eleDz", &eleDz, &b_eleDz); fChain->SetBranchAddress("eleSIP", &eleSIP, &b_eleSIP); fChain->SetBranchAddress("eleUnCalibE", &eleUnCalibE, &b_eleUnCalibE); fChain->SetBranchAddress("eleUnCalibESigma", &eleUnCalibESigma, &b_eleUnCalibESigma); fChain->SetBranchAddress("eleCalibEecalonly", &eleCalibEecalonly, &b_eleCalibEecalonly); fChain->SetBranchAddress("eleCalibE", &eleCalibE, &b_eleCalibE); fChain->SetBranchAddress("eleCalibESigma", &eleCalibESigma, &b_eleCalibESigma); fChain->SetBranchAddress("eleCalibEt", &eleCalibEt, &b_eleCalibEt); fChain->SetBranchAddress("eleCalibEtSigma", &eleCalibEtSigma, &b_eleCalibEtSigma); fChain->SetBranchAddress("eleEnergyScale", &eleEnergyScale, &b_eleEnergyScale); fChain->SetBranchAddress("eleEnergySigma", &eleEnergySigma, &b_eleEnergySigma); fChain->SetBranchAddress("eleSCRawE", &eleSCRawE, &b_eleSCRawE); fChain->SetBranchAddress("eleSCE", &eleSCE, &b_eleSCE); fChain->SetBranchAddress("eleSCEta", &eleSCEta, &b_eleSCEta); fChain->SetBranchAddress("eleSCPhi", &eleSCPhi, &b_eleSCPhi); fChain->SetBranchAddress("eleSCEtaWidth", &eleSCEtaWidth, &b_eleSCEtaWidth); fChain->SetBranchAddress("eleSCPhiWidth", &eleSCPhiWidth, &b_eleSCPhiWidth); fChain->SetBranchAddress("eleHoverE", &eleHoverE, &b_eleHoverE); fChain->SetBranchAddress("eleEoverP", &eleEoverP, &b_eleEoverP); fChain->SetBranchAddress("eleEoverPout", &eleEoverPout, &b_eleEoverPout); fChain->SetBranchAddress("eleEoverPInv", &eleEoverPInv, &b_eleEoverPInv); fChain->SetBranchAddress("eleBrem", &eleBrem, &b_eleBrem); fChain->SetBranchAddress("eledEtaAtVtx", &eledEtaAtVtx, &b_eledEtaAtVtx); fChain->SetBranchAddress("eledPhiAtVtx", &eledPhiAtVtx, &b_eledPhiAtVtx); fChain->SetBranchAddress("eledEtaAtCalo", &eledEtaAtCalo, &b_eledEtaAtCalo); fChain->SetBranchAddress("eledEtaseedAtVtx", &eledEtaseedAtVtx, &b_eledEtaseedAtVtx); fChain->SetBranchAddress("eleSigmaIEtaIEtaFull5x5", &eleSigmaIEtaIEtaFull5x5, &b_eleSigmaIEtaIEtaFull5x5); fChain->SetBranchAddress("eleSigmaIPhiIPhiFull5x5", &eleSigmaIPhiIPhiFull5x5, &b_eleSigmaIPhiIPhiFull5x5); fChain->SetBranchAddress("eleConvVeto", &eleConvVeto, &b_eleConvVeto); fChain->SetBranchAddress("eleMissHits", &eleMissHits, &b_eleMissHits); fChain->SetBranchAddress("elePFChIso", &elePFChIso, &b_elePFChIso); fChain->SetBranchAddress("elePFPhoIso", &elePFPhoIso, &b_elePFPhoIso); fChain->SetBranchAddress("elePFNeuIso", &elePFNeuIso, &b_elePFNeuIso); fChain->SetBranchAddress("elePFPUIso", &elePFPUIso, &b_elePFPUIso); fChain->SetBranchAddress("elePFClusEcalIso", &elePFClusEcalIso, &b_elePFClusEcalIso); fChain->SetBranchAddress("elePFClusHcalIso", &elePFClusHcalIso, &b_elePFClusHcalIso); fChain->SetBranchAddress("eleFiredSingleTrgs", &eleFiredSingleTrgs, &b_eleFiredSingleTrgs); fChain->SetBranchAddress("eleFiredDoubleTrgs", &eleFiredDoubleTrgs, &b_eleFiredDoubleTrgs); fChain->SetBranchAddress("eleFiredL1Trgs", &eleFiredL1Trgs, &b_eleFiredL1Trgs); fChain->SetBranchAddress("eleHEEPID", &eleHEEPID, &b_eleHEEPID); fChain->SetBranchAddress("eleMVAIsoID", &eleMVAIsoID, &b_eleMVAIsoID); fChain->SetBranchAddress("eleMVAnoIsoID", &eleMVAnoIsoID, &b_eleMVAnoIsoID); fChain->SetBranchAddress("eleIDbit", &eleIDbit, &b_eleIDbit); fChain->SetBranchAddress("eleTrkdxy", &eleTrkdxy, &b_eleTrkdxy); fChain->SetBranchAddress("eleKFHits", &eleKFHits, &b_eleKFHits); fChain->SetBranchAddress("eleKFChi2", &eleKFChi2, &b_eleKFChi2); fChain->SetBranchAddress("eleGSFChi2", &eleGSFChi2, &b_eleGSFChi2); fChain->SetBranchAddress("eleScale_up", &eleScale_up, &b_eleScale_up); fChain->SetBranchAddress("eleScale_dn", &eleScale_dn, &b_eleScale_dn); fChain->SetBranchAddress("eleScale_stat_up", &eleScale_stat_up, &b_eleScale_stat_up); fChain->SetBranchAddress("eleScale_stat_dn", &eleScale_stat_dn, &b_eleScale_stat_dn); fChain->SetBranchAddress("eleScale_syst_up", &eleScale_syst_up, &b_eleScale_syst_up); fChain->SetBranchAddress("eleScale_syst_dn", &eleScale_syst_dn, &b_eleScale_syst_dn); fChain->SetBranchAddress("eleScale_gain_up", &eleScale_gain_up, &b_eleScale_gain_up); fChain->SetBranchAddress("eleScale_gain_dn", &eleScale_gain_dn, &b_eleScale_gain_dn); fChain->SetBranchAddress("eleResol_up", &eleResol_up, &b_eleResol_up); fChain->SetBranchAddress("eleResol_dn", &eleResol_dn, &b_eleResol_dn); fChain->SetBranchAddress("eleResol_rho_up", &eleResol_rho_up, &b_eleResol_rho_up); fChain->SetBranchAddress("eleResol_rho_dn", &eleResol_rho_dn, &b_eleResol_rho_dn); fChain->SetBranchAddress("eleResol_phi_up", &eleResol_phi_up, &b_eleResol_phi_up); fChain->SetBranchAddress("eleResol_phi_dn", &eleResol_phi_dn, &b_eleResol_phi_dn); fChain->SetBranchAddress("nMu", &nMu, &b_nMu); fChain->SetBranchAddress("muPt", &muPt, &b_muPt); fChain->SetBranchAddress("muE", &muE, &b_muE); fChain->SetBranchAddress("muEta", &muEta, &b_muEta); fChain->SetBranchAddress("muPhi", &muPhi, &b_muPhi); fChain->SetBranchAddress("muCharge", &muCharge, &b_muCharge); fChain->SetBranchAddress("muType", &muType, &b_muType); fChain->SetBranchAddress("muIDbit", &muIDbit, &b_muIDbit); fChain->SetBranchAddress("muD0", &muD0, &b_muD0); fChain->SetBranchAddress("muDz", &muDz, &b_muDz); fChain->SetBranchAddress("muSIP", &muSIP, &b_muSIP); fChain->SetBranchAddress("muChi2NDF", &muChi2NDF, &b_muChi2NDF); fChain->SetBranchAddress("muInnerD0", &muInnerD0, &b_muInnerD0); fChain->SetBranchAddress("muInnerDz", &muInnerDz, &b_muInnerDz); fChain->SetBranchAddress("muTrkLayers", &muTrkLayers, &b_muTrkLayers); fChain->SetBranchAddress("muPixelLayers", &muPixelLayers, &b_muPixelLayers); fChain->SetBranchAddress("muPixelHits", &muPixelHits, &b_muPixelHits); fChain->SetBranchAddress("muMuonHits", &muMuonHits, &b_muMuonHits); fChain->SetBranchAddress("muStations", &muStations, &b_muStations); fChain->SetBranchAddress("muMatches", &muMatches, &b_muMatches); fChain->SetBranchAddress("muTrkQuality", &muTrkQuality, &b_muTrkQuality); fChain->SetBranchAddress("muInnervalidFraction", &muInnervalidFraction, &b_muInnervalidFraction); fChain->SetBranchAddress("muIsoTrk", &muIsoTrk, &b_muIsoTrk); fChain->SetBranchAddress("muPFChIso", &muPFChIso, &b_muPFChIso); fChain->SetBranchAddress("muPFPhoIso", &muPFPhoIso, &b_muPFPhoIso); fChain->SetBranchAddress("muPFNeuIso", &muPFNeuIso, &b_muPFNeuIso); fChain->SetBranchAddress("muPFPUIso", &muPFPUIso, &b_muPFPUIso); fChain->SetBranchAddress("musegmentCompatibility", &musegmentCompatibility, &b_musegmentCompatibility); fChain->SetBranchAddress("muchi2LocalPosition", &muchi2LocalPosition, &b_muchi2LocalPosition); fChain->SetBranchAddress("mutrkKink", &mutrkKink, &b_mutrkKink); fChain->SetBranchAddress("muBestTrkPtError", &muBestTrkPtError, &b_muBestTrkPtError); fChain->SetBranchAddress("muBestTrkPt", &muBestTrkPt, &b_muBestTrkPt); fChain->SetBranchAddress("muBestTrkType", &muBestTrkType, &b_muBestTrkType); fChain->SetBranchAddress("muFiredTrgs", &muFiredTrgs, &b_muFiredTrgs); fChain->SetBranchAddress("muFiredL1Trgs", &muFiredL1Trgs, &b_muFiredL1Trgs); fChain->SetBranchAddress("nTau", &nTau, &b_nTau); fChain->SetBranchAddress("tau_Pt", &tau_Pt, &b_tau_Pt); fChain->SetBranchAddress("tau_Et", &tau_Et, &b_tau_Et); fChain->SetBranchAddress("tau_Eta", &tau_Eta, &b_tau_Eta); fChain->SetBranchAddress("tau_Phi", &tau_Phi, &b_tau_Phi); fChain->SetBranchAddress("tau_Charge", &tau_Charge, &b_tau_Charge); fChain->SetBranchAddress("tau_DecayMode", &tau_DecayMode, &b_tau_DecayMode); //fChain->SetBranchAddress("tau_decayModeFindingNewDMs", &tau_decayModeFindingNewDMs, &b_tau_decayModeFindingNewDMs); fChain->SetBranchAddress("tau_P", &tau_P, &b_tau_P); fChain->SetBranchAddress("tau_Vz", &tau_Vz, &b_tau_Vz); fChain->SetBranchAddress("tau_Energy", &tau_Energy, &b_tau_Energy); fChain->SetBranchAddress("tau_Mass", &tau_Mass, &b_tau_Mass); fChain->SetBranchAddress("tau_Dxy", &tau_Dxy, &b_tau_Dxy); fChain->SetBranchAddress("tau_ZImpact", &tau_ZImpact, &b_tau_ZImpact); fChain->SetBranchAddress("tau_byCombinedIsolationDeltaBetaCorrRaw3Hits", &tau_byCombinedIsolationDeltaBetaCorrRaw3Hits, &b_tau_byCombinedIsolationDeltaBetaCorrRaw3Hits); fChain->SetBranchAddress("tau_chargedIsoPtSum", &tau_chargedIsoPtSum, &b_tau_chargedIsoPtSum); fChain->SetBranchAddress("tau_neutralIsoPtSum", &tau_neutralIsoPtSum, &b_tau_neutralIsoPtSum); fChain->SetBranchAddress("tau_neutralIsoPtSumWeight", &tau_neutralIsoPtSumWeight, &b_tau_neutralIsoPtSumWeight); fChain->SetBranchAddress("tau_footprintCorrection", &tau_footprintCorrection, &b_tau_footprintCorrection); fChain->SetBranchAddress("tau_photonPtSumOutsideSignalCone", &tau_photonPtSumOutsideSignalCone, &b_tau_photonPtSumOutsideSignalCone); fChain->SetBranchAddress("tau_puCorrPtSum", &tau_puCorrPtSum, &b_tau_puCorrPtSum); fChain->SetBranchAddress("tau_NumSignalPFChargedHadrCands", &tau_NumSignalPFChargedHadrCands, &b_tau_NumSignalPFChargedHadrCands); fChain->SetBranchAddress("tau_NumSignalPFNeutrHadrCands", &tau_NumSignalPFNeutrHadrCands, &b_tau_NumSignalPFNeutrHadrCands); fChain->SetBranchAddress("tau_NumSignalPFGammaCands", &tau_NumSignalPFGammaCands, &b_tau_NumSignalPFGammaCands); fChain->SetBranchAddress("tau_NumSignalPFCands", &tau_NumSignalPFCands, &b_tau_NumSignalPFCands); fChain->SetBranchAddress("tau_NumIsolationPFChargedHadrCands", &tau_NumIsolationPFChargedHadrCands, &b_tau_NumIsolationPFChargedHadrCands); fChain->SetBranchAddress("tau_NumIsolationPFNeutrHadrCands", &tau_NumIsolationPFNeutrHadrCands, &b_tau_NumIsolationPFNeutrHadrCands); fChain->SetBranchAddress("tau_NumIsolationPFGammaCands", &tau_NumIsolationPFGammaCands, &b_tau_NumIsolationPFGammaCands); fChain->SetBranchAddress("tau_NumIsolationPFCands", &tau_NumIsolationPFCands, &b_tau_NumIsolationPFCands); fChain->SetBranchAddress("tau_LeadChargedHadronEta", &tau_LeadChargedHadronEta, &b_tau_LeadChargedHadronEta); fChain->SetBranchAddress("tau_LeadChargedHadronPhi", &tau_LeadChargedHadronPhi, &b_tau_LeadChargedHadronPhi); fChain->SetBranchAddress("tau_LeadChargedHadronPt", &tau_LeadChargedHadronPt, &b_tau_LeadChargedHadronPt); fChain->SetBranchAddress("tau_LeadChargedHadron_dz", &tau_LeadChargedHadron_dz, &b_tau_LeadChargedHadron_dz); fChain->SetBranchAddress("tau_LeadChargedHadron_dxy", &tau_LeadChargedHadron_dxy, &b_tau_LeadChargedHadron_dxy); fChain->SetBranchAddress("tau_IDbits", &tau_IDbits, &b_tau_IDbits); fChain->SetBranchAddress("tau_byIsolationMVArun2017v2DBoldDMwLTraw2017", &tau_byIsolationMVArun2017v2DBoldDMwLTraw2017, &b_tau_byIsolationMVArun2017v2DBoldDMwLTraw2017); fChain->SetBranchAddress("tau_byVVVLooseDeepTau2017v2p1VSjet", &tau_byVVVLooseDeepTau2017v2p1VSjet, &b_tau_byVVVLooseDeepTau2017v2p1VSjet); fChain->SetBranchAddress("tau_byVVLooseDeepTau2017v2p1VSjet", &tau_byVVLooseDeepTau2017v2p1VSjet, &b_tau_byVVLooseDeepTau2017v2p1VSjet); fChain->SetBranchAddress("tau_byVLooseDeepTau2017v2p1VSjet", &tau_byVLooseDeepTau2017v2p1VSjet, &b_tau_byVLooseDeepTau2017v2p1VSjet); fChain->SetBranchAddress("tau_byLooseDeepTau2017v2p1VSjet", &tau_byLooseDeepTau2017v2p1VSjet, &b_tau_byLooseDeepTau2017v2p1VSjet); fChain->SetBranchAddress("tau_byMediumDeepTau2017v2p1VSjet", &tau_byMediumDeepTau2017v2p1VSjet, &b_tau_byMediumDeepTau2017v2p1VSjet); fChain->SetBranchAddress("tau_byTightDeepTau2017v2p1VSjet", &tau_byTightDeepTau2017v2p1VSjet, &b_tau_byTightDeepTau2017v2p1VSjet); fChain->SetBranchAddress("tau_byVTightDeepTau2017v2p1VSjet", &tau_byVTightDeepTau2017v2p1VSjet, &b_tau_byVTightDeepTau2017v2p1VSjet); fChain->SetBranchAddress("tau_byVVTightDeepTau2017v2p1VSjet", &tau_byVVTightDeepTau2017v2p1VSjet, &b_tau_byVVTightDeepTau2017v2p1VSjet); fChain->SetBranchAddress("tau_byVVVLooseDeepTau2017v2p1VSe", &tau_byVVVLooseDeepTau2017v2p1VSe, &b_tau_byVVVLooseDeepTau2017v2p1VSe); fChain->SetBranchAddress("tau_byVVLooseDeepTau2017v2p1VSe", &tau_byVVLooseDeepTau2017v2p1VSe, &b_tau_byVVLooseDeepTau2017v2p1VSe); fChain->SetBranchAddress("tau_byVLooseDeepTau2017v2p1VSe", &tau_byVLooseDeepTau2017v2p1VSe, &b_tau_byVLooseDeepTau2017v2p1VSe); fChain->SetBranchAddress("tau_byLooseDeepTau2017v2p1VSe", &tau_byLooseDeepTau2017v2p1VSe, &b_tau_byLooseDeepTau2017v2p1VSe); fChain->SetBranchAddress("tau_byMediumDeepTau2017v2p1VSe", &tau_byMediumDeepTau2017v2p1VSe, &b_tau_byMediumDeepTau2017v2p1VSe); fChain->SetBranchAddress("tau_byTightDeepTau2017v2p1VSe", &tau_byTightDeepTau2017v2p1VSe, &b_tau_byTightDeepTau2017v2p1VSe); fChain->SetBranchAddress("tau_byVTightDeepTau2017v2p1VSe", &tau_byVTightDeepTau2017v2p1VSe, &b_tau_byVTightDeepTau2017v2p1VSe); fChain->SetBranchAddress("tau_byVVTightDeepTau2017v2p1VSe", &tau_byVVTightDeepTau2017v2p1VSe, &b_tau_byVVTightDeepTau2017v2p1VSe); fChain->SetBranchAddress("tau_byVLooseDeepTau2017v2p1VSmu", &tau_byVLooseDeepTau2017v2p1VSmu, &b_tau_byVLooseDeepTau2017v2p1VSmu); fChain->SetBranchAddress("tau_byLooseDeepTau2017v2p1VSmu", &tau_byLooseDeepTau2017v2p1VSmu, &b_tau_byLooseDeepTau2017v2p1VSmu); fChain->SetBranchAddress("tau_byMediumDeepTau2017v2p1VSmu", &tau_byMediumDeepTau2017v2p1VSmu, &b_tau_byMediumDeepTau2017v2p1VSmu); fChain->SetBranchAddress("tau_byTightDeepTau2017v2p1VSmu", &tau_byTightDeepTau2017v2p1VSmu, &b_tau_byTightDeepTau2017v2p1VSmu); fChain->SetBranchAddress("tauFiredTrgs", &tauFiredTrgs, &b_tauFiredTrgs); fChain->SetBranchAddress("tauFiredL1Trgs", &tauFiredL1Trgs, &b_tauFiredL1Trgs); fChain->SetBranchAddress("metFilters", &metFilters, &b_metFilters); fChain->SetBranchAddress("caloMET", &caloMET, &b_caloMET); fChain->SetBranchAddress("caloMETPhi", &caloMETPhi, &b_caloMETPhi); fChain->SetBranchAddress("caloMETsumEt", &caloMETsumEt, &b_caloMETsumEt); fChain->SetBranchAddress("pfMETCorr", &pfMETCorr, &b_pfMETCorr); fChain->SetBranchAddress("pfMETPhiCorr", &pfMETPhiCorr, &b_pfMETPhiCorr); fChain->SetBranchAddress("pfMET", &pfMET, &b_pfMET); fChain->SetBranchAddress("pfMETPhi", &pfMETPhi, &b_pfMETPhi); fChain->SetBranchAddress("pfMETsumEt", &pfMETsumEt, &b_pfMETsumEt); fChain->SetBranchAddress("pfMETmEtSig", &pfMETmEtSig, &b_pfMETmEtSig); fChain->SetBranchAddress("pfMETSig", &pfMETSig, &b_pfMETSig); fChain->SetBranchAddress("pfMET_T1JERUp", &pfMET_T1JERUp, &b_pfMET_T1JERUp); fChain->SetBranchAddress("pfMET_T1JERDo", &pfMET_T1JERDo, &b_pfMET_T1JERDo); fChain->SetBranchAddress("pfMET_T1JESUp", &pfMET_T1JESUp, &b_pfMET_T1JESUp); fChain->SetBranchAddress("pfMET_T1JESDo", &pfMET_T1JESDo, &b_pfMET_T1JESDo); fChain->SetBranchAddress("pfMET_T1UESUp", &pfMET_T1UESUp, &b_pfMET_T1UESUp); fChain->SetBranchAddress("pfMET_T1UESDo", &pfMET_T1UESDo, &b_pfMET_T1UESDo); fChain->SetBranchAddress("pfMETPhi_T1JESUp", &pfMETPhi_T1JESUp, &b_pfMETPhi_T1JESUp); fChain->SetBranchAddress("pfMETPhi_T1JESDo", &pfMETPhi_T1JESDo, &b_pfMETPhi_T1JESDo); fChain->SetBranchAddress("pfMETPhi_T1UESUp", &pfMETPhi_T1UESUp, &b_pfMETPhi_T1UESUp); fChain->SetBranchAddress("pfMETPhi_T1UESDo", &pfMETPhi_T1UESDo, &b_pfMETPhi_T1UESDo); if(isMC=="MC"){ fChain->SetBranchAddress("genMET", &genMET, &b_genMET); fChain->SetBranchAddress("genMETPhi", &genMETPhi, &b_genMETPhi); fChain->SetBranchAddress("pdf", &pdf, &b_pdf); fChain->SetBranchAddress("pthat", &pthat, &b_pthat); fChain->SetBranchAddress("processID", &processID, &b_processID); fChain->SetBranchAddress("genWeight", &genWeight, &b_genWeight); fChain->SetBranchAddress("genHT", &genHT, &b_genHT); fChain->SetBranchAddress("pdfWeight", &pdfWeight, &b_pdfWeight); fChain->SetBranchAddress("pdfSystWeight", &pdfSystWeight, &b_pdfSystWeight); fChain->SetBranchAddress("nPUInfo", &nPUInfo, &b_nPUInfo); fChain->SetBranchAddress("nPU", &nPU, &b_nPU); fChain->SetBranchAddress("puBX", &puBX, &b_puBX); fChain->SetBranchAddress("puTrue", &puTrue, &b_puTrue); fChain->SetBranchAddress("nMC", &nMC, &b_nMC); fChain->SetBranchAddress("mcPID", &mcPID, &b_mcPID); fChain->SetBranchAddress("mcVtx", &mcVtx, &b_mcVtx); fChain->SetBranchAddress("mcVty", &mcVty, &b_mcVty); fChain->SetBranchAddress("mcVtz", &mcVtz, &b_mcVtz); fChain->SetBranchAddress("mcPt", &mcPt, &b_mcPt); fChain->SetBranchAddress("mcMass", &mcMass, &b_mcMass); fChain->SetBranchAddress("mcEta", &mcEta, &b_mcEta); fChain->SetBranchAddress("mcPhi", &mcPhi, &b_mcPhi); fChain->SetBranchAddress("mcE", &mcE, &b_mcE); fChain->SetBranchAddress("mcEt", &mcEt, &b_mcEt); fChain->SetBranchAddress("mcStatus", &mcStatus, &b_mcStatus); fChain->SetBranchAddress("mcStatusFlag", &mcStatusFlag, &b_mcStatusFlag); fChain->SetBranchAddress("mcIndex", &mcIndex, &b_mcIndex); fChain->SetBranchAddress("mcDaughterPID", &mcDaughterPID, &b_mcDaughterPID); fChain->SetBranchAddress("mcCharge", &mcCharge, &b_mcCharge); fChain->SetBranchAddress("mcMotherPID", &mcMotherPID, &b_mcMotherPID); fChain->SetBranchAddress("mcMotherIndex", &mcMotherIndex, &b_mcMotherIndex); fChain->SetBranchAddress("mcMotherStatus", &mcMotherStatus, &b_mcMotherStatus); fChain->SetBranchAddress("mcDaughterStatus", &mcDaughterStatus, &b_mcDaughterStatus); fChain->SetBranchAddress("mcDaughterList", &mcDaughterList, &b_mcDaughterList); fChain->SetBranchAddress("mcTauDecayMode", &mcTauDecayMode, &b_mcTauDecayMode); fChain->SetBranchAddress("genMatch2", &genMatch2, &b_genMatch2); } Notify(); } Bool_t skimm_tt_2018::Notify() { // The Notify() function is called when a new file is opened. This // can be either for a new TTree in a TChain or when when a new TTree // is started when using PROOF. It is normally not necessary to make changes // to the generated code, but the routine can be extended by the // user if needed. The return value is currently not used. return kTRUE; } void skimm_tt_2018::Show(Long64_t entry) { // Print contents of entry. // If entry is not specified, print current entry if (!fChain) return; fChain->Show(entry); } Int_t skimm_tt_2018::Cut(Long64_t entry) { // This function may be called from Loop. // returns 1 if entry is accepted. // returns -1 otherwise. return 1; } #endif // #ifdef skimm_tt_2018_cxx
[ "jithin.madhusudanan.sreekala@cern.ch" ]
jithin.madhusudanan.sreekala@cern.ch