blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
46fa4a1d269f85acb530719ed13d181e8ed6a12e
a9103f6db80d8a593b2b588c18b4dfb56824e16f
/11/DorababuArigi.cpp
eb0b54036feea14341d708433248d9e09746d668
[]
no_license
Coding-Club-NIT-Meghalaya/Leetcode-January-Challenge
937910c22f696b5cbbe19b5a5829dc3988295e80
349928f9b418b74e65007ecba78d7ac27bdfe1ed
refs/heads/main
2023-02-26T07:04:35.938774
2021-01-31T14:47:15
2021-01-31T14:47:15
326,126,590
1
19
null
2021-01-31T14:47:16
2021-01-02T06:50:05
C++
UTF-8
C++
false
false
313
cpp
/* B19CS039 Dorababu Arigi DorababuArigi */ class Solution { public: vector<int> merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { for(int i=m,j=0;i<nums1.size()&&j<n;++i,++j){ nums1[i]=nums2[j]; } sort(nums1.begin(),nums1.end()); return nums1; } };
[ "noreply@github.com" ]
Coding-Club-NIT-Meghalaya.noreply@github.com
ef99789da9553c6ef0ea5ec8814e5ee566ee890c
a85bcd9a3332c6ae187453e32a9d234ae8532dc5
/application/HTTPDownloader.hpp
802cc741241a4ef99daee1835a293c5c0c24c0cb
[]
no_license
vinnoplexus/Crawler_Test
f3ba9298fd94a40b17ce2d3d7c48b1b7b8590cdf
1ef1449bff2efd313d7ce80a492337dd3c2ac301
refs/heads/master
2021-01-20T14:22:35.428550
2017-05-11T13:18:36
2017-05-11T13:18:36
90,595,164
0
0
null
null
null
null
UTF-8
C++
false
false
399
hpp
#include <string> /** * A non-threadsafe simple libcURL-easy based HTTP downloader */ class HTTPDownloader { public: HTTPDownloader(); ~HTTPDownloader(); /** * Download a file using HTTP GET and store in in a std::string * @param url The URL to download * @return The download result */ std::string download(const std::string& url); private: void* curl; };
[ "vinay.sable@innoplexus.com" ]
vinay.sable@innoplexus.com
834bb6e62e11f31ed489977231e17b6cff199969
040ae0bfa0218a30383ee5a24b2ba4d2e5fefbb5
/AntiyMonitor-MFC/EventSink.cpp
8ccef81f1d4db9cca62e4662cd59bd1424bb4386
[]
no_license
fengjixuchui/NetMon-2
f6df5d794992f2ed85fbaf046a03fdfc62768b62
1a2f22e1e8ab65d2062f10455b91550cb6838b39
refs/heads/main
2023-02-05T03:56:41.900497
2020-12-22T15:48:26
2020-12-22T15:48:26
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
9,208
cpp
#include <stdio.h> #include <iostream> #include <comutil.h> #include <string.h> #include <stdlib.h> #include "AntiyEtw.h" #include "AntiyWmi.h" using namespace std; EventSink::EventSink() { InitListEntry(&m_ListHeader); InitializeCriticalSection(&m_WmiEventLock); } EventSink::~EventSink() { } ULONG EventSink::AddRef() { return InterlockedIncrement(&m_lRef); } ULONG EventSink::Release() { LONG lRef = InterlockedDecrement(&m_lRef); if (lRef == 0) delete this; return lRef; } HRESULT EventSink::QueryInterface(REFIID riid, void** ppv) { if (riid == IID_IUnknown || riid == IID_IWbemObjectSink) { *ppv = (IWbemObjectSink *)this; AddRef(); return WBEM_S_NO_ERROR; } else return E_NOINTERFACE; } void CopyUnicodeString(PUNICODE_STRING *Desc, WCHAR *Source) { *Desc = (PUNICODE_STRING)malloc(sizeof(UNICODE_STRING)); ULONG dwLen = wcslen(Source) + 1; (*Desc)->Buffer = (WCHAR *)malloc(dwLen * sizeof(WCHAR)); memset((*Desc)->Buffer, 0, dwLen); (*Desc)->Length = dwLen; wcsncpy_s((*Desc)->Buffer, dwLen,Source, dwLen); } LARGE_INTEGER EventSink::GetTimeStampValue(WCHAR *szTime) { LARGE_INTEGER llValue; WCHAR *p = NULL; llValue.QuadPart = 0; p = szTime; while (*p != '\0') { llValue.QuadPart *= 10; llValue.QuadPart += (*p); llValue.QuadPart -= '0'; ++p; } return llValue; } void EventSink::SetWmiEventData(WMI_EVENT_DATA *pWmiEventData ,WCHAR *pKey, WCHAR *pValue) { if (_wcsicmp(pKey, L"__CLASS") == 0) { CopyUnicodeString(&pWmiEventData->szClassName, pValue); } else if (_wcsicmp(pKey, L"__SUPERCLASS") == 0) { CopyUnicodeString(&pWmiEventData->szSuperClassName, pValue); } else if (_wcsicmp(pKey, L"__SERVER") == 0) { CopyUnicodeString(&pWmiEventData->szServerName, pValue); } else if (_wcsicmp(pKey, L"__NAMESPACE") == 0) { CopyUnicodeString(&pWmiEventData->szNameSpace, pValue); } else if (_wcsicmp(pKey, L"TIME_CREATED") == 0) { pWmiEventData->llTimeCreate = GetTimeStampValue(pValue); } } WMI_EVENT_DATA *EventSink::EnumClassData(IWbemClassObject *pClass) { VARIANT varWmiDatas; LONG Ubound = 0; LONG Lbound = 0; SAFEARRAY *pSafeArray = NULL; BSTR bWmiString = NULL; LONG rgIndices = 0; CIMTYPE CimType; IWbemQualifierSet *pQualifierSet = NULL; HRESULT hr; VARIANT varIant; VARIANT varValue; LIST_ENTRY *pList = NULL; WMI_EVENT_DATA *pWmiEventData = NULL; BOOL bSuccess = FALSE; if (!pClass) return pWmiEventData; pWmiEventData = (WMI_EVENT_DATA *)malloc(sizeof(WMI_EVENT_DATA)); memset(pWmiEventData, 0, sizeof(WMI_EVENT_DATA)); while (pClass->GetNames(NULL, WBEM_FLAG_ALWAYS, &varWmiDatas, &pSafeArray) == S_OK) { if(SafeArrayGetLBound(pSafeArray,1u,&Lbound) || SafeArrayGetUBound(pSafeArray, 1u, &Ubound) || Ubound < 0) break; if (Lbound <= Ubound) { rgIndices = Lbound; } do { if(SafeArrayGetElement(pSafeArray,&rgIndices,&bWmiString) || pClass->Get(bWmiString,0,0,&CimType,NULL)) break; VariantInit(&varIant); hr = pClass->Get(bWmiString,0,&varIant,NULL,NULL); do { if(FAILED(hr)) break; bSuccess = TRUE; VariantInit(&varValue); switch (varIant.vt) { case CIM_STRING: { //printf("%ws=%ws\n",bWmiString,varIant.bstrVal); hr = pClass->GetQualifierSet(&pQualifierSet); if (hr == S_OK) { SetWmiEventData(pWmiEventData,bWmiString, varIant.bstrVal); } } break; case CIM_UINT64: { printf("%ws=%d\n", bWmiString,varIant.llVal); } } VariantClear(&varIant); VariantClear(&varValue); } while (0); ++rgIndices; } while (rgIndices <= Ubound); VariantClear(&varWmiDatas); SafeArrayDestroy(pSafeArray); pSafeArray = NULL; varWmiDatas.lVal++; break; } if (!bSuccess) { free(pWmiEventData); return NULL; } EnterCriticalSection(&m_WmiEventLock); InsertHeaderList(&m_ListHeader, &pWmiEventData->List); LeaveCriticalSection(&m_WmiEventLock); return pWmiEventData; } BOOL GetWmiQueryInfo(PWMI_EVENT_DATA pWmiEventData, OLECHAR *szObjectText) { BOOL bResult = FALSE; ULONG dwNameOffset = 0; ULONG dwNameLen; ULONG i = 0; ULONG dwEnd; OLECHAR *rp = NULL;//read pointer const OLECHAR *cps[4] = {L"Name = ",L"Query = ",L"QueryLanguage = ",L"TargetInstance = "};//compare pointer ULONG cpcount; const OLECHAR *cp = NULL; const OLECHAR *p = NULL; WCHAR *tmpstr = NULL; const OLECHAR *pName = NULL; do { rp = szObjectText; for (cpcount = 0; cpcount < 4; ++cpcount) { cp = cps[cpcount]; dwNameLen = wcslen(cp); dwEnd = 0; //while (rp[i] != '\0') { p = wcsstr(rp, cp); if (p) { pName = p + dwNameLen; while (pName[dwEnd] != '\0') { if (pName[dwEnd] == ';') { break; } ++dwEnd; } if(dwEnd == 0) break; tmpstr = (WCHAR *)malloc((dwEnd + 1) * sizeof(WCHAR)); memset(tmpstr, 0, (dwEnd + 1) * sizeof(WCHAR)); CopyMemory(tmpstr, pName,dwEnd * sizeof(WCHAR)); if (_wcsicmp(cp, L"Name = ") == 0) { pWmiEventData->szName = (UNICODE_STRING *)malloc(sizeof(UNICODE_STRING)); CopyUnicodeString(&pWmiEventData->szName, tmpstr); } else if (_wcsicmp(cp, L"Query = ") == 0) { pWmiEventData->szQuery = (UNICODE_STRING *)malloc(sizeof(UNICODE_STRING)); CopyUnicodeString(&pWmiEventData->szQuery, tmpstr); } else if (_wcsicmp(cp, L"QueryLanguage = ") == 0) { pWmiEventData->szQueryLanguage = (UNICODE_STRING *)malloc(sizeof(UNICODE_STRING)); CopyUnicodeString(&pWmiEventData->szQueryLanguage, tmpstr); } else if (_wcsicmp(cp, L"TargetInstance = ") == 0) { WCHAR *startstr = tmpstr; WCHAR *endstr = NULL; while (*startstr && *(startstr + 1)) { //if (*startstr == '_' && *(startstr + 1) == '_') { startstr += wcslen(L"instance of "); endstr = startstr; while (*endstr) { if (*endstr == '{') { break; } ++endstr; } break; } ++startstr; } if (endstr) { WCHAR tmpBuffer[0x30] = { 0 }; CopyMemory(tmpBuffer, startstr, (endstr - startstr) * sizeof(WCHAR)); CopyUnicodeString(&pWmiEventData->szEventName, tmpBuffer); } } if (tmpstr) { free(tmpstr); tmpstr = NULL; } } ++i; } } } while (0); return bResult; } HRESULT EventSink::Indicate(long lObjectCount, IWbemClassObject **apObjArray) { ULONG dwResult = 0; IWbemClassObject *pClassObj = NULL; IWbemQualifierSet *pQualifierSet = NULL; SAFEARRAY *pNames = NULL; HRESULT hr; char pByteBuffer[0x1fe] = { 0 }; void *pVBuffer_1; ULONG dwCurrentIndex = 0; VARIANT varClass; OLECHAR *bstr; OLECHAR **pBstr = NULL; void **pPAddress = NULL; ULONG ProcessId = 0; PWMI_EVENT_DATA pWmiEventData = NULL; if (lObjectCount <= 0) return WBEM_S_FALSE; do { pBstr = &bstr; bstr = NULL; pVBuffer_1 = NULL; pClassObj = *(apObjArray + dwCurrentIndex); do { if ( (hr = pClassObj->GetObjectText(0, &bstr)) < 0 || !bstr) break; pVBuffer_1 = NULL; pPAddress = (void **)&varClass; //printf("ÊÕµ½Wmiʼþ:%ws\n", bstr); pWmiEventData = EnumClassData(pClassObj); if(!pWmiEventData) break; GetWmiQueryInfo(pWmiEventData, bstr); }while (0); if (bstr) SysFreeString(bstr); ++dwCurrentIndex; } while (FALSE); return WBEM_S_NO_ERROR; } HRESULT EventSink::SetStatus( /* [in] */ LONG lFlags, /* [in] */ HRESULT hResult, /* [in] */ BSTR strParam, /* [in] */ IWbemClassObject __RPC_FAR *pObjParam ) { if (lFlags == WBEM_STATUS_COMPLETE) { printf("Call complete. hResult = 0x%X\n", hResult); } else if (lFlags == WBEM_STATUS_PROGRESS) { printf("Call in progress.\n"); } return WBEM_S_NO_ERROR; } // end of EventSink.cpp void FreeUnicodeString(PUNICODE_STRING *uString) { if (*uString == NULL || (*uString)->Buffer == NULL || (*uString)->Length == 0) return; free((*uString)->Buffer); (*uString)->Buffer = NULL; (*uString)->Length = 0; free(*uString); *uString = NULL; } void EventSink::FreeWmiData(void) { LIST_ENTRY *pList = NULL; LIST_ENTRY *pFreeList = NULL; PWMI_EVENT_DATA pWmiEventData = NULL; if (IsEmptyList(&m_ListHeader)) return; EnterCriticalSection(&m_WmiEventLock); pList = m_ListHeader.Flink; pFreeList = &m_ListHeader; while (pList != &m_ListHeader) { do { pWmiEventData = CONTAINING_RECORD(pList,WMI_EVENT_DATA,List); if (!pWmiEventData) { pList = pList->Flink; break; } FreeUnicodeString(&pWmiEventData->szClassName); FreeUnicodeString(&pWmiEventData->szSuperClassName); FreeUnicodeString(&pWmiEventData->szNameSpace); FreeUnicodeString(&pWmiEventData->szServerName); FreeUnicodeString(&pWmiEventData->szName); FreeUnicodeString(&pWmiEventData->szQuery); FreeUnicodeString(&pWmiEventData->szQueryLanguage); FreeUnicodeString(&pWmiEventData->szEventName); pFreeList = pList; pList = pList->Flink; RemoveHeaderList(pFreeList); free(pWmiEventData); pWmiEventData = NULL; } while (0); } LeaveCriticalSection(&m_WmiEventLock); }
[ "p0sixb1ackcat@gmail.com" ]
p0sixb1ackcat@gmail.com
825082dbdbd7093d6ec04614651c4baca2a2ed65
0c848a59f3feb3bcef685d889224630ba674a04d
/Connect 4/src/Program/State.h
11e7a2a0a1dce30bc9c4fc84280b50ec27b9c886
[]
no_license
josephcwalker/NEA-Coursework
168ea06ad85f90f739ec6acb3c1814a22d044653
bfdb7175c44b238d8f759d7d86014ee6a945c355
refs/heads/master
2023-04-02T03:32:39.010745
2021-04-15T14:06:32
2021-04-15T14:06:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
h
#pragma once #include <SFML/Graphics.hpp> namespace Connect { class Button; // Abstract State class used to allow for polymorphism // to store all states in a single data structure easily class State { public: State() {}; virtual ~State() {}; public: // Used to initialize any values that need to be created a single time // Cannot take parameters so the construcutor of the base class must be used virtual void Initialize() = 0; // Used to update any values that may need to change based on the user // Perhaps an optimization can be made to only run this when something has actually changed virtual void Execute() = 0; // Used to draw all the objects in the state will be run every frame // Unless there is an optimization but this will be hard to communicate with main.cpp virtual void Draw() = 0; // Used to give this state the handle to the window to draw stuff inline void SetWindow(sf::RenderWindow* window) { m_Window = window; } // Common Button Functions protected: void PopState(); void RemoveAllStates(); void PushConfirmExitState(); protected: static sf::RenderWindow* m_Window; public: Button* recentButton = nullptr; }; }
[ "josephwalker2010@hotmail.co.uk" ]
josephwalker2010@hotmail.co.uk
87a2717b06352054d1e196774fc1458a6777143d
0b5ca79064d0f6049c943704b9066d18cf0dfb70
/src/Controls.h
6bdc9e164621cf034978cc8f51600056b5727b70
[]
no_license
aspirkin/Andrumeda
9cef4723204bc032fae73826e0a5cf1712fac161
0f2c3b86a5dac3c04d0ddf2dbbec82809cf2836b
refs/heads/master
2023-01-19T15:27:41.558937
2020-11-30T11:57:32
2020-11-30T11:57:32
218,037,134
0
0
null
null
null
null
UTF-8
C++
false
false
1,918
h
#ifndef Controls_h_ #define Controls_h_ #include <EncoderHandler.h> #include <SensorHandler.h> #include <vector> #include <menus/MenuBranch.h> #include <menus/MenuLeaf.h> #include <parameters/AbstractParameter.h> #include <parameters/StatefulParameter.h> #include <parameters/StatelessParameter.h> #include <EncoderHandler.h> #include <displays/ST7735_DisplayHandler.h> class Controls { protected: int _numberOfMusicNodes; int _numberOfEncoders; std::vector <SensorHandler*> _ptrMusicSensorHandlers; std::vector <EncoderHandler*> _ptrEncoderHandlers; MenuBranch* _rootMenu; MenuBranch* _currentMenu; AbstractDisplayHandler* _displayHandler; AbstractParameter* _parameterMock = new AbstractParameter(); AbstractParameter* _configurableParameter; StatelessParameter* _navigationParameter = new StatelessParameter( std::bind(&Controls::selectNextChild, this), std::bind(&Controls::selectPreviousChild, this) ); StatelessParameter* _configurationParameter = new StatelessParameter( std::bind(&Controls::increaseParameter, this), std::bind(&Controls::decreaseParameter, this) ); EncoderHandler* _configurationEncoderHandler; EncoderHandler* _navigationEncoderHandler; void setConfigurableParameter(MenuItem* item); public: Controls(int numberOfMusicNodes, int numberOfEncoders, MenuBranch* rootMenu, AbstractDisplayHandler* displayHandler); SensorHandler* getMusicSensorHandler(int index); EncoderHandler* getEncoderHandler(int index); void addMusicSensor(int pin); void addNavigationEncoder(int pinA, int pinB, int pinS); void addConfigurationEncoder(int pinA, int pinB, int pinS); EncoderHandler* addCommonEncoder(int pinA, int pinB, int pinS); void update(); void enterCurrentChild(); void escapeToParent(); void selectNextChild(); void selectPreviousChild(); void increaseParameter(); void decreaseParameter(); }; #endif //Controls_h_
[ "aleksey.spirkin@gmail.com" ]
aleksey.spirkin@gmail.com
9d765ced88134e529d5f6196b68ba4eda6e0820c
6d7eae0eda05945f2d95448b647cdc9217b592a7
/RC/Projeto/shared/src/error.cpp
fd66a10052c5f5045f4524942d781660c4b7b8f9
[]
no_license
oitgg/EC-UFPB
dcac2c7349e30d78cb04f042d2cd742306f9b033
972a2cb2233ac03ded577bb5a6ff47f94e8944d8
refs/heads/master
2020-05-21T01:16:09.884537
2019-05-20T22:00:39
2019-05-20T22:00:39
185,852,791
0
0
null
null
null
null
UTF-8
C++
false
false
677
cpp
#include "error.h" void socket_error() { perror("Erro ao criar um socket"); exit(1); } void connect_error() { perror("Erro ao solicitar uma conexão"); exit(1); } void recv_error() { perror("Erro ao receber uma mensagem"); exit(1); } void send_error() { perror("Erro ao enviar uma mensagem"); exit(1); } void bind_error() { perror("Erro ao associar uma porta ao socket (bind)"); exit(1); } void listen_error() { perror("Erro ao abrir a escuta"); exit(1); } void gethostbyname_error() { perror("gethostbyname"); exit(1); } void reuse_address_error() { perror("setsockopt(SO_REUSEADDR) failed"); exit(1); }
[ "37004066+oitgg@users.noreply.github.com" ]
37004066+oitgg@users.noreply.github.com
190a7cd719ab64812936aa144e9579b45b6de7c1
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/62/6fd89b84cf582b/main.cpp
5a2058f961e3926fa90025c5967f9c302c999ee3
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
#include <iostream> #include <string.h> void copyString(char stringToCopyTo[], char stringToCopy[]); int main(){ char string1[] = "Hello World!"; char string2[80]; copyString(string2, string1); std::cout << "String1: " << string1 << "\n"; std::cout << "String2: " << string2 << "\n"; return 0; } void copyString(char stringToCopyTo[], char stringToCopy[]){ stringToCopyTo = stringToCopy; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
054855fd222da0ca5bf35f2a29b64067de553e60
7248fece394bb45defc21b18fd7aaa18bba73cad
/Problem 10/Problem 10/main.cpp
af249730666b0c6928a2e9cf2110306fcb2380fe
[]
no_license
drsoxen/Project-Euler
eff25fb15eba322b19a2a5f8b669d695799ea67a
1676d680ce66ad56e44362ba81b95d3fa3c84c50
refs/heads/master
2016-09-03T06:31:25.504019
2012-09-27T02:54:55
2012-09-27T02:54:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
760
cpp
#include <iostream> #include <vector> using namespace std; void PrimeNumbers(unsigned long long numberOfPrimeNumbers); vector<unsigned long long>PrimeNumberVec; unsigned long long sum = 0; int main() { PrimeNumbers(2000000); for(int i =0;i<PrimeNumberVec.size();i++) sum += PrimeNumberVec[i]; cout<<sum<<endl; system("PAUSE"); return 0; } void PrimeNumbers(unsigned long long numberOfPrimeNumbers) { unsigned long long j; for (unsigned long long i = 2; i< numberOfPrimeNumbers; i++ ) { for ( j = 2; j <= i/2; j++ ) { if ( ! ( i % j ) ) break; } if ( j > i / 2 ) { PrimeNumberVec.push_back(i); //cout<<i<<endl; } } }
[ "stargateno1fan@Chriss-MacBook.local" ]
stargateno1fan@Chriss-MacBook.local
838948498508aace143eeeacd8a312dad133135d
8def94d70dff30617a7644b2dff534fef7dc8281
/IntXLib.Test/src/LessOpTest.h
16db0987365d5b661e7d42bc9a42827af4cede03
[ "MIT" ]
permissive
dendisuhubdy/IntXLib4CPP
e2a295d033a3a10155fdb68ea73082c7dd9a92ec
ba9869269bee5a25f8d9ab9bc84da6380e2eb315
refs/heads/master
2020-05-17T04:24:30.121236
2017-09-08T11:26:06
2017-09-08T11:26:06
183,508,780
1
0
null
2019-04-25T20:58:18
2019-04-25T20:58:17
null
UTF-8
C++
false
false
1,048
h
#define BOOST_TEST_MODULE LessOpTest #include "../IntX.h" #include <vector> #include <boost/test/included/unit_test.hpp> BOOST_AUTO_TEST_SUITE(LessOpTest) BOOST_AUTO_TEST_CASE(Simple) { IntX int1 = IntX(7); IntX int2 = IntX(8); BOOST_CHECK(int1 < int2); BOOST_CHECK(int1 < 8); BOOST_CHECK(7 < int2); } BOOST_AUTO_TEST_CASE(SimpleFail) { IntX int1 = IntX(8); BOOST_CHECK(!(int1 < 7)); } BOOST_AUTO_TEST_CASE(Big) { IntX int1 = IntX(vector<UInt32>({ 1, 2 }), false); IntX int2 = IntX(vector<UInt32>({ 1, 2, 3 }), true); BOOST_CHECK(int2 < int1); } BOOST_AUTO_TEST_CASE(BigFail) { IntX int1 = IntX(vector<UInt32>({ 1, 2 }), false); IntX int2 = IntX(vector<UInt32>({ 1, 2, 3 }), true); BOOST_CHECK(!(int1 < int2)); } BOOST_AUTO_TEST_CASE(EqualValues) { IntX int1 = IntX(vector<UInt32>({ 1, 2, 3 }), true); IntX int2 = IntX(vector<UInt32>({ 1, 2, 3 }), true); BOOST_CHECK(!(int1 < int2)); } BOOST_AUTO_TEST_CASE(Neg) { IntX int1 = IntX(-10); IntX int2 = IntX(-2); BOOST_CHECK(int1 < int2); } BOOST_AUTO_TEST_SUITE_END()
[ "ron2tele@gmail.com" ]
ron2tele@gmail.com
ecaec957f7973768feba2ca4f272120e0322a494
7975dc9f1c3550719c0f8f841ef5c533091ebbe8
/src/sensorsbank.cpp
f4fe5625a51741e2dc488c5f8a6a692a8c8e8d01
[ "Apache-2.0" ]
permissive
marc-despland/alarm
edb00a8b44c3905ddd0f10a475eb1b7ff1f0e140
06fa62a490b57e012402c2f3dfd9c4c54e624070
refs/heads/master
2021-03-19T14:50:07.513833
2017-07-30T13:52:32
2017-07-30T13:52:32
97,235,283
0
0
null
null
null
null
UTF-8
C++
false
false
2,193
cpp
#include "sensorsbank.h" #include <ctime> #include <curl/curl.h> #include <sstream> #include "log.h" string SensorsBank::ApiKey=""; string SensorsBank::ApiUrl=""; string SensorsBank::toJson(std::map<string,double> sensors) { time_t rawtime; struct tm * timeinfo; char responsedate [80]; time (&rawtime); timeinfo = gmtime (&rawtime); //2017-07-28T10:35:55.912Z strftime (responsedate,80,"\"date\": \"%Y-%m-%dT%H:%M:%S.000Z\"",timeinfo); std::stringstream json; json << "{" <<endl; json << " "<< responsedate<<","<<endl; json << " \"sensors\": [" << endl; for (std::map<string, double>::iterator it=sensors.begin();it!=sensors.end(); it++) { if (it!=sensors.begin()) { json << ","<<endl; } json << " {" <<endl; json << " \"name\": \"" << it->first<< "\"," <<endl; json << " \"value\": " << it->second <<endl; json << " }"; } json << endl << " ]" << endl; json << "}" <<endl; Log::logger->log("SENSORSBANK",DEBUG) << "Sensors data : " <<endl<< json.str() <<endl; return json.str(); } void SensorsBank::sendData(std::map<string,double> sensors) throw (CurlInitException, PostException) { CURL *curl; CURLcode res; struct curl_slist *list = NULL; curl = curl_easy_init(); if(curl) { string apikey="ApiKey: "+SensorsBank::ApiKey; list = curl_slist_append(list, apikey.c_str()); list = curl_slist_append(list, "Content-Type: application/json"); list = curl_slist_append(list, "Expect:"); string url=SensorsBank::ApiUrl+"/sensors"; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); string data=SensorsBank::toJson(sensors); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.length()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); res = curl_easy_perform(curl); if(res != CURLE_OK) { Log::logger->log("SENSORSBANK",ERROR) << "Failed to send sensors data " << curl_easy_strerror(res) <<endl; curl_easy_cleanup(curl); throw PostException(); } Log::logger->log("SENSORSBANK",DEBUG) << "Success" <<endl; curl_easy_cleanup(curl); } else { Log::logger->log("SENSORSBANK",ERROR) << "Failed to init curl library " <<endl; throw CurlInitException(); } }
[ "marc.despland@art122-5.net" ]
marc.despland@art122-5.net
2cc8437d950d93f0ab4bf920ba65f05c8cb127a2
d01196c421b8e99b1140c2814e8ae899ecae903e
/TestCOMServer/dllmain.cpp
0d2d2ef8e2b264c8a0b688045f108b0e197aa4fc
[ "BSD-3-Clause" ]
permissive
0x01-tools/COMProxy
69638d220ba160dbf29d9591b114bf319a61c542
73fdcc08e1cc584cb780c8f19680e0deb8d0cec2
refs/heads/master
2020-07-22T08:48:57.111054
2019-08-30T13:33:31
2019-08-30T13:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,783
cpp
#include <Windows.h> #include <comutil.h> // #include for _bstr_t #include <string> BOOL FindOriginalCOMServer(wchar_t* GUID, wchar_t** DLLName); DWORD MyThread(); typedef HRESULT(__stdcall *_DllGetClassObject)(REFCLSID rclsid, REFIID riid, LPVOID* ppv); UINT g_uThreadFinished; extern UINT g_uThreadFinished; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { AllocConsole(); FILE *stream; freopen_s(&stream, "CONOUT$", "w+", stdout); g_uThreadFinished = 0; printf("[*] DLL_PROCESS_ATTACH\n"); break; } case DLL_PROCESS_DETACH: printf("[*] DLL_PROCESS_DETACH\n"); break; } return TRUE; } STDAPI DllCanUnloadNow(void) { wprintf(L"[+] DllCanUnloadNow\n"); // Ensure our thread can finish before we're unloaded do { Sleep(1); } while (g_uThreadFinished == 0); wprintf(L"[+] All done, exiting.\n"); return S_OK; } STDAPI DllRegisterServer(void) { wprintf(L"[+] DllRegisterServer\n"); return S_OK; } STDAPI DllUnregisterServer(void) { wprintf(L"[+] DllUnregisterServer\n"); return S_OK; } STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { wprintf(L"[+] DllGetClassObject\n"); CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread, NULL, 0, NULL); HMODULE hDLL; _DllGetClassObject lpGetClassObject; LPOLESTR lplpsz; HRESULT hResult = StringFromCLSID(rclsid, &lplpsz); wchar_t* DLLName = new wchar_t[MAX_PATH]; if (!FindOriginalCOMServer((wchar_t*)lplpsz, &DLLName)) { wprintf(L"[-] Couldn't find original COM server\n"); return S_FALSE; } wprintf(L"[+] Found original COM server: %s\n", DLLName); // Load up the original COM server hDLL = LoadLibrary(DLLName); if (hDLL == NULL) { wprintf(L"[-] hDLL was NULL\n"); return S_FALSE; } // Find the DllGetClassObject for original COM server lpGetClassObject = (_DllGetClassObject)GetProcAddress(hDLL, "DllGetClassObject"); if (lpGetClassObject == NULL) { wprintf(L"[-] lpGetClassObject is null\n"); return S_FALSE; } // Call the intended DllGetClassObject from original COM server // This will get all the necessary pointers and should be all set if successful HRESULT hr = lpGetClassObject(rclsid, riid, ppv); if FAILED(hr) { wprintf(L"[-] lpGetClassObject got hr 0x%08lx\n", hr); } wprintf(L"[+] Done!\n"); return S_OK; } BOOL FindOriginalCOMServer(wchar_t* GUID, wchar_t** DLLName) { HKEY hKey; HKEY hCLSIDKey; wchar_t name[MAX_PATH]; DWORD nameLength = MAX_PATH; wprintf(L"[*] Beginning search for GUID %s\n", GUID); LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)L"SOFTWARE\\Classes\\CLSID", 0, KEY_READ, &hKey); if (lResult != ERROR_SUCCESS) { wprintf(L"[-] Error getting CLSID path\n"); return FALSE; } // Make sure HKLM\Software\Classes\CLSID\{GUID} exists lResult = RegOpenKeyExW(hKey, GUID, 0, KEY_READ, &hCLSIDKey); if (lResult != ERROR_SUCCESS) { wprintf(L"[-] Error getting GUID path\n"); RegCloseKey(hKey); return FALSE; } // Read the value of HKLM's InProcServer32 lResult = RegGetValueW(hCLSIDKey, (LPCWSTR)L"InProcServer32", NULL, RRF_RT_ANY, NULL, (PVOID)&name, &nameLength); if (lResult != ERROR_SUCCESS) { wprintf(L"[-] Error getting InProcServer32 value: %d\n", lResult); RegCloseKey(hKey); RegCloseKey(hCLSIDKey); return FALSE; } *DLLName = name; return TRUE; } DWORD MyThread() { printf("[+] MyThread\n\n"); for (int i = 0; i < 30; i++) { printf("[*] %d\n", i); Sleep(1000); } g_uThreadFinished = 1; return 0; }
[ "noreply@github.com" ]
0x01-tools.noreply@github.com
c3d24abc36a85169270116fccc158fc79e0bf3b3
2c74e4ad6c5dd8258fe4e061b784add7099f099d
/Civ4 Reimagined/Source/CyPlayer.cpp
9c7872973d7446b6e9f979ee0773770ab44a6f06
[ "CC-BY-3.0" ]
permissive
nalyc/MCiv4Reimagined
73bb0e925cf915111e78973bf3cf4dda1ba9aa63
dc1d66420493892c4572a15b80f70528813f1592
refs/heads/master
2021-04-27T05:16:38.572025
2018-02-23T08:59:01
2018-02-23T08:59:01
122,595,106
0
0
null
null
null
null
UTF-8
C++
false
false
60,018
cpp
// // Python wrapper class for CvPlayer // #include "CvGameCoreDLL.h" #include "CyPlayer.h" #include "CyUnit.h" #include "CyCity.h" #include "CyArea.h" #include "CyPlot.h" #include "CvPlayerAI.h" //#include "CvEnums.h" #include "CvCity.h" #include "CvMap.h" #include "CvPlot.h" #include "CySelectionGroup.h" #include "CvDLLPythonIFaceBase.h" #include "CvGlobals.h" CyPlayer::CyPlayer() : m_pPlayer(NULL) { } CyPlayer::CyPlayer(CvPlayer* pPlayer) : m_pPlayer(pPlayer) { } /************************************************************************************************/ /* CHANGE_PLAYER 08/27/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ void CyPlayer::changeLeader( int /*LeaderHeadTypes*/ eNewLeader ) { if( m_pPlayer ) m_pPlayer->changeLeader( (LeaderHeadTypes)eNewLeader ); } void CyPlayer::changeCiv( int /*CivilizationTypes*/ eNewCiv ) { if( m_pPlayer ) m_pPlayer->changeCiv( (CivilizationTypes)eNewCiv ); } void CyPlayer::setIsHuman( bool bNewValue ) { if( m_pPlayer ) m_pPlayer->setIsHuman( bNewValue ); } /************************************************************************************************/ /* CHANGE_PLAYER END */ /************************************************************************************************/ int CyPlayer::startingPlotRange() { return m_pPlayer ? m_pPlayer->startingPlotRange() : -1; } bool CyPlayer::startingPlotWithinRange(CyPlot *pPlot, int /*PlayerTypes*/ ePlayer, int iRange, int iPass) { if (m_pPlayer && pPlot != NULL && !pPlot->isNone()) { CvPlot *pcvPlot = pPlot->getPlot(); if (pPlot) { return m_pPlayer->startingPlotWithinRange(pcvPlot, (PlayerTypes)ePlayer, iRange, iPass); } } return NULL; } CyPlot* CyPlayer::findStartingPlot(bool bRandomize) { return m_pPlayer ? new CyPlot(m_pPlayer->findStartingPlot(bRandomize)) : NULL; } CyCity* CyPlayer::initCity(int x, int y) { return m_pPlayer ? new CyCity(m_pPlayer->initCity(x, y, true, true)) : NULL; } void CyPlayer::acquireCity(CyCity* pCity, bool bConquest, bool bTrade) { if (m_pPlayer) m_pPlayer->acquireCity(pCity->getCity(), bConquest, bTrade, true); } void CyPlayer::killCities() { if (m_pPlayer) m_pPlayer->killCities(); } std::wstring CyPlayer::getNewCityName() { return m_pPlayer ? m_pPlayer->getNewCityName() : std::wstring(); } CyUnit* CyPlayer::initUnit(int /*UnitTypes*/ iIndex, int iX, int iY, UnitAITypes eUnitAI, DirectionTypes eFacingDirection) { return m_pPlayer ? new CyUnit(m_pPlayer->initUnit((UnitTypes) iIndex, iX, iY, eUnitAI, eFacingDirection)) : NULL; } void CyPlayer::disbandUnit(bool bAnnounce) { return m_pPlayer ? m_pPlayer->disbandUnit(bAnnounce) : NULL; } void CyPlayer::killUnits() { if (m_pPlayer) m_pPlayer->killUnits(); } bool CyPlayer::hasTrait(int /*TraitTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->hasTrait((TraitTypes) iIndex) : false; } bool CyPlayer::isHuman() { return m_pPlayer ? m_pPlayer->isHuman() : false; } bool CyPlayer::isBarbarian() { return m_pPlayer ? m_pPlayer->isBarbarian() : false; } std::wstring CyPlayer::getName() { return m_pPlayer ? m_pPlayer->getName() : std::wstring(); } std::wstring CyPlayer::getNameForm(int iForm) { return m_pPlayer ? m_pPlayer->getName((uint)iForm) : std::wstring(); } std::wstring CyPlayer::getNameKey() { return m_pPlayer ? m_pPlayer->getNameKey() : std::wstring(); } std::wstring CyPlayer::getCivilizationDescription(int iForm) { return m_pPlayer ? m_pPlayer->getCivilizationDescription((uint)iForm) : std::wstring(); } std::wstring CyPlayer::getCivilizationDescriptionKey() { return m_pPlayer ? m_pPlayer->getCivilizationDescriptionKey() : std::wstring(); } std::wstring CyPlayer::getCivilizationShortDescription(int iForm) { return m_pPlayer ? m_pPlayer->getCivilizationShortDescription((uint)iForm) : std::wstring(); } std::wstring CyPlayer::getCivilizationShortDescriptionKey() { return m_pPlayer ? m_pPlayer->getCivilizationShortDescriptionKey() : std::wstring(); } std::wstring CyPlayer::getCivilizationAdjective(int iForm) { return m_pPlayer ? m_pPlayer->getCivilizationAdjective((uint)iForm) : std::wstring(); } std::wstring CyPlayer::getCivilizationAdjectiveKey( ) { return m_pPlayer ? m_pPlayer->getCivilizationAdjectiveKey() : std::wstring(); } std::wstring CyPlayer::getFlagDecal( ) { return m_pPlayer ? m_pPlayer->getFlagDecal() : std::wstring(); } bool CyPlayer::isWhiteFlag() { return m_pPlayer ? m_pPlayer->isWhiteFlag() : false; } std::wstring CyPlayer::getStateReligionName(int iForm) { return m_pPlayer ? m_pPlayer->getStateReligionName((int)iForm) : std::wstring(); } std::wstring CyPlayer::getStateReligionKey( ) { return m_pPlayer ? m_pPlayer->getStateReligionKey() : std::wstring(); } std::wstring CyPlayer::getBestAttackUnitName(int iForm) { return m_pPlayer ? m_pPlayer->getBestAttackUnitName((uint)iForm) : std::wstring(); } std::wstring CyPlayer::getWorstEnemyName() { return m_pPlayer ? m_pPlayer->getWorstEnemyName() : std::wstring(); } std::wstring CyPlayer::getBestAttackUnitKey() { return m_pPlayer ? m_pPlayer->getBestAttackUnitKey() : std::wstring(); } int /*ArtStyleTypes*/ CyPlayer::getArtStyleType() { return m_pPlayer ? (int) m_pPlayer->getArtStyleType() : -1; } std::string CyPlayer::getUnitButton(int eUnit) { return m_pPlayer ? m_pPlayer->getUnitButton((UnitTypes)eUnit) : ""; } int CyPlayer::findBestFoundValue( ) { return m_pPlayer ? m_pPlayer->findBestFoundValue() : -1; } int CyPlayer::countReligionSpreadUnits(CyArea* pArea, int /*ReligionTypes*/ eReligion) { return m_pPlayer ? m_pPlayer->countReligionSpreadUnits(pArea->getArea(), (ReligionTypes) eReligion) : -1; } int CyPlayer::countNumCoastalCities() { return m_pPlayer ? m_pPlayer->countNumCoastalCities() : -1; } int CyPlayer::countNumCoastalCitiesByArea(CyArea* pArea) { return m_pPlayer ? m_pPlayer->countNumCoastalCitiesByArea(pArea->getArea()) : -1; } int CyPlayer::countTotalCulture() { return m_pPlayer ? m_pPlayer->countTotalCulture() : -1; } int CyPlayer::countOwnedBonuses(int /*BonusTypes*/ eBonus) { return m_pPlayer ? m_pPlayer->countOwnedBonuses((BonusTypes)eBonus) : NO_BONUS; } int CyPlayer::countUnimprovedBonuses(CyArea* pArea, CyPlot* pFromPlot) { return m_pPlayer ? m_pPlayer->countUnimprovedBonuses(pArea->getArea(), pFromPlot->getPlot()) : -1; } int CyPlayer::countCityFeatures(int /*FeatureTypes*/ eFeature) { return m_pPlayer ? m_pPlayer->countCityFeatures((FeatureTypes) eFeature) : -1; } int CyPlayer::countNumBuildings(int /*BuildingTypes*/ eBuilding) { return m_pPlayer ? m_pPlayer->countNumBuildings((BuildingTypes) eBuilding) : -1; } int CyPlayer::countNumCitiesConnectedToCapital() { return m_pPlayer ? m_pPlayer->countNumCitiesConnectedToCapital() : -1; } bool CyPlayer::canContact(int /*PlayerTypes*/ ePlayer) { return m_pPlayer ? m_pPlayer->canContact((PlayerTypes)ePlayer) : false; } void CyPlayer::contact(int /*PlayerTypes*/ ePlayer) { if (m_pPlayer) m_pPlayer->contact((PlayerTypes)ePlayer); } bool CyPlayer::canTradeWith(int /*PlayerTypes*/ eWhoTo) { return m_pPlayer ? m_pPlayer->canTradeWith((PlayerTypes)eWhoTo) : false; } bool CyPlayer::canTradeItem(int /*PlayerTypes*/ eWhoTo, TradeData item, bool bTestDenial) { return m_pPlayer ? m_pPlayer->canTradeItem((PlayerTypes)eWhoTo, item, bTestDenial) : false; } DenialTypes CyPlayer::getTradeDenial(int /*PlayerTypes*/ eWhoTo, TradeData item) { return m_pPlayer ? m_pPlayer->getTradeDenial((PlayerTypes)eWhoTo, item) : NO_DENIAL; } bool CyPlayer::canTradeNetworkWith(int /*PlayerTypes*/ iPlayer) { return m_pPlayer ? m_pPlayer->canTradeNetworkWith((PlayerTypes)iPlayer) : false; } int CyPlayer::getNumAvailableBonuses(int /*BonusTypes*/ eBonus) { return m_pPlayer ? m_pPlayer->getNumAvailableBonuses((BonusTypes)eBonus) : NO_BONUS; } int CyPlayer::getNumTradeableBonuses(int /*BonusTypes*/ eBonus) { return m_pPlayer ? m_pPlayer->getNumTradeableBonuses((BonusTypes)eBonus) : NO_BONUS; } int CyPlayer::getNumTradeBonusImports(int /*PlayerTypes*/ ePlayer) { return m_pPlayer ? m_pPlayer->getNumTradeBonusImports((PlayerTypes) ePlayer) : -1; } bool CyPlayer::hasBonus(int /*BonusTypes*/ eBonus) { return m_pPlayer ? m_pPlayer->hasBonus((BonusTypes)eBonus) : NO_BONUS; } bool CyPlayer::canStopTradingWithTeam(int /*TeamTypes*/ eTeam) { return m_pPlayer ? m_pPlayer->canStopTradingWithTeam((TeamTypes) eTeam) : false; } void CyPlayer::stopTradingWithTeam(int /*TeamTypes*/ eTeam) { if (m_pPlayer) m_pPlayer->stopTradingWithTeam((TeamTypes) eTeam); } void CyPlayer::killAllDeals() { if (m_pPlayer) m_pPlayer->killAllDeals(); } bool CyPlayer::isTurnActive() { return m_pPlayer ? m_pPlayer->isTurnActive() : false; } void CyPlayer::findNewCapital() { if (m_pPlayer) m_pPlayer->findNewCapital(); } int CyPlayer::getNumGovernmentCenters() { return m_pPlayer ? m_pPlayer->getNumGovernmentCenters() : -1; } bool CyPlayer::canRaze(CyCity* pCity) { return m_pPlayer ? m_pPlayer->canRaze(pCity->getCity()) : false; } void CyPlayer::raze(CyCity* pCity) { if (m_pPlayer) m_pPlayer->raze(pCity->getCity()); } void CyPlayer::disband(CyCity* pCity) { if (m_pPlayer) m_pPlayer->disband(pCity->getCity()); } bool CyPlayer::canReceiveGoody(CyPlot* pPlot, int /*GoodyTypes*/ iIndex, CyUnit* pUnit) { return m_pPlayer ? m_pPlayer->canReceiveGoody(pPlot->getPlot(), (GoodyTypes) iIndex, pUnit->getUnit()) : false; } void CyPlayer::receiveGoody(CyPlot* pPlot, int /*GoodyTypes*/ iIndex, CyUnit* pUnit) { if (m_pPlayer) m_pPlayer->receiveGoody(pPlot->getPlot(), (GoodyTypes) iIndex, pUnit->getUnit()); } void CyPlayer::doGoody(CyPlot* pPlot, CyUnit* pUnit) { if (m_pPlayer) m_pPlayer->doGoody(pPlot->getPlot(), pUnit->getUnit()); } bool CyPlayer::canFound(int iX, int iY) { return m_pPlayer ? m_pPlayer->canFound(iX, iY) : false; } void CyPlayer::found(int x, int y) { if (m_pPlayer) m_pPlayer->found(x,y); } bool CyPlayer::canTrain(int /*UnitTypes*/ eUnit, bool bContinue, bool bTestVisible) { return m_pPlayer ? m_pPlayer->canTrain((UnitTypes)eUnit, bContinue, bTestVisible) : false; } bool CyPlayer::canConstruct(int /*BuildingTypes*/eBuilding, bool bContinue, bool bTestVisible, bool bIgnoreCost) { return m_pPlayer ? m_pPlayer->canConstruct((BuildingTypes)eBuilding, bContinue, bTestVisible, bIgnoreCost) : false; } bool CyPlayer::canCreate(int /*ProjectTypes*/ eProject, bool bContinue, bool bTestVisible) { return m_pPlayer ? m_pPlayer->canCreate((ProjectTypes)eProject, bContinue, bTestVisible) : false; } bool CyPlayer::canMaintain(int /*ProcessTypes*/ eProcess, bool bContinue) { return m_pPlayer ? m_pPlayer->canMaintain((ProcessTypes)eProcess, bContinue) : false; } bool CyPlayer::isProductionMaxedUnitClass(int /*UnitClassTypes*/ eUnitClass) { return m_pPlayer ? m_pPlayer->isProductionMaxedUnitClass((UnitClassTypes) eUnitClass) : false; } bool CyPlayer::isProductionMaxedBuildingClass(int /*BuildingClassTypes*/ eBuildingClass, bool bAcquireCity) { return m_pPlayer ? m_pPlayer->isProductionMaxedBuildingClass((BuildingClassTypes) eBuildingClass, bAcquireCity) : false; } bool CyPlayer::isProductionMaxedProject(int /*ProjectTypes*/ eProject) { return m_pPlayer ? m_pPlayer->isProductionMaxedProject((ProjectTypes) eProject) : false; } int CyPlayer::getUnitProductionNeeded(int /*UnitTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getProductionNeeded((UnitTypes) iIndex) : -1; } int CyPlayer::getBuildingProductionNeeded(int /*BuildingTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getProductionNeeded((BuildingTypes) iIndex) : -1; } int CyPlayer::getProjectProductionNeeded(int /*ProjectTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getProductionNeeded((ProjectTypes)iIndex) : -1; } int CyPlayer::getBuildingClassPrereqBuilding(int /*BuildingTypes*/ eBuilding, int /*BuildingClassTypes*/ ePrereqBuildingClass, int iExtra) { return m_pPlayer ? m_pPlayer->getBuildingClassPrereqBuilding((BuildingTypes) eBuilding, (BuildingClassTypes) ePrereqBuildingClass, iExtra) : -1; } void CyPlayer::removeBuildingClass(int /*BuildingClassTypes*/ eBuildingClass) { if (m_pPlayer) m_pPlayer->removeBuildingClass((BuildingClassTypes)eBuildingClass); } bool CyPlayer::canBuild(CyPlot* pPlot, int /*BuildTypes*/ eBuild, bool bTestEra, bool bTestVisible) { return m_pPlayer ? m_pPlayer->canBuild(pPlot->getPlot(), (BuildTypes)eBuild, bTestEra, bTestVisible) : false; } int /*RouteTypes*/ CyPlayer::getBestRoute(CyPlot* pPlot) const { return m_pPlayer ? (int) m_pPlayer->getBestRoute(NULL != pPlot ? pPlot->getPlot() : NULL) : -1; } int CyPlayer::getImprovementUpgradeRate() const { return m_pPlayer ? m_pPlayer->getImprovementUpgradeRate() : -1; } int CyPlayer::calculateTotalYield(int /*YieldTypes*/ eYield) { return m_pPlayer ? m_pPlayer->calculateTotalYield((YieldTypes)eYield) : -1; } int CyPlayer::calculateTotalExports(int /*YieldTypes*/ eYield) { return m_pPlayer ? m_pPlayer->calculateTotalExports((YieldTypes)eYield) : -1; } int CyPlayer::calculateTotalImports(int /*YieldTypes*/ eYield) { return m_pPlayer ? m_pPlayer->calculateTotalImports((YieldTypes)eYield) : -1; } int CyPlayer::calculateTotalCityHappiness() { return m_pPlayer ? m_pPlayer->calculateTotalCityHappiness() : -1; } int CyPlayer::calculateTotalCityUnhappiness() { return m_pPlayer ? m_pPlayer->calculateTotalCityUnhappiness() : -1; } int CyPlayer::calculateTotalCityHealthiness() { return m_pPlayer ? m_pPlayer->calculateTotalCityHealthiness() : -1; } int CyPlayer::calculateTotalCityUnhealthiness() { return m_pPlayer ? m_pPlayer->calculateTotalCityUnhealthiness() : -1; } int CyPlayer::calculateUnitCost() { return m_pPlayer ? m_pPlayer->calculateUnitCost() : -1; } int CyPlayer::calculateUnitSupply() { return m_pPlayer ? m_pPlayer->calculateUnitSupply() : -1; } int CyPlayer::calculatePreInflatedCosts() { return m_pPlayer ? m_pPlayer->calculatePreInflatedCosts() : -1; } //int CyPlayer::calculateInflationRate() int CyPlayer::getInflationRate() { return m_pPlayer ? m_pPlayer->getInflationRate() : -1; } int CyPlayer::calculateInflatedCosts() { return m_pPlayer ? m_pPlayer->calculateInflatedCosts() : -1; } int CyPlayer::calculateGoldRate() { return m_pPlayer ? m_pPlayer->calculateGoldRate() : -1; } int CyPlayer::calculateTotalCommerce() { return m_pPlayer ? m_pPlayer->calculateTotalCommerce() : -1; } int CyPlayer::calculateResearchRate(int /*TechTypes*/ eTech) { return m_pPlayer ? m_pPlayer->calculateResearchRate((TechTypes)eTech) : -1; } int CyPlayer::calculateResearchModifier(int /*TechTypes*/ eTech) { return m_pPlayer ? m_pPlayer->calculateResearchModifier((TechTypes)eTech) : -1; } /* ** K-Mod, 18/dec/10, karadoc */ int CyPlayer::calculatePollution(int iTypes) const { return m_pPlayer ? m_pPlayer->calculatePollution(iTypes) : 0; } int CyPlayer::getGwPercentAnger() const { return m_pPlayer ? m_pPlayer->getGwPercentAnger() : 0; } /* ** K-Mod end */ /* int CyPlayer::calculateBaseNetResearch() { return m_pPlayer ? m_pPlayer->calculateBaseNetResearch() : -1; } */ bool CyPlayer::isResearch() { return m_pPlayer ? m_pPlayer->isResearch() : false; } bool CyPlayer::canEverResearch(int /*TechTypes*/ eTech) { return m_pPlayer ? m_pPlayer->canEverResearch((TechTypes)eTech) : false; } bool CyPlayer::canResearch(int /*TechTypes*/ eTech, bool bTrade) { return m_pPlayer ? m_pPlayer->canResearch((TechTypes)eTech, bTrade) : false; } int /* TechTypes */ CyPlayer::getCurrentResearch() { return m_pPlayer ? (int) m_pPlayer->getCurrentResearch() : (int) NO_TECH; } bool CyPlayer::isCurrentResearchRepeat() { return m_pPlayer ? m_pPlayer->isCurrentResearchRepeat() : false; } bool CyPlayer::isNoResearchAvailable() { return m_pPlayer ? m_pPlayer->isNoResearchAvailable() : false; } int CyPlayer::getResearchTurnsLeft(int /*TechTypes*/ eTech, bool bOverflow) { return m_pPlayer ? m_pPlayer->getResearchTurnsLeft((TechTypes)eTech, bOverflow) : -1; } // K-Mod bool CyPlayer::canSeeResearch(int /*PlayerTypes*/ ePlayer) const { return m_pPlayer ? m_pPlayer->canSeeResearch((PlayerTypes)ePlayer) : false; } bool CyPlayer::canSeeDemographics(int /*PlayerTypes*/ ePlayer) const { return m_pPlayer ? m_pPlayer->canSeeDemographics((PlayerTypes)ePlayer) : false; } // K-Mod end bool CyPlayer::isCivic(int /*CivicTypes*/ eCivic) { return m_pPlayer ? m_pPlayer->isCivic((CivicTypes)eCivic) : false; } bool CyPlayer::canDoCivics(int /*CivicTypes*/ eCivic) { return m_pPlayer ? m_pPlayer->canDoCivics((CivicTypes)eCivic) : false; } bool CyPlayer::canRevolution(int /*CivicTypes**/ paeNewCivics) { return m_pPlayer ? m_pPlayer->canRevolution((CivicTypes*)paeNewCivics) : false; } void CyPlayer::revolution(int /*CivicTypes**/ paeNewCivics, bool bForce) { if (m_pPlayer) m_pPlayer->revolution((CivicTypes*)paeNewCivics, bForce); } int CyPlayer::getCivicPercentAnger(int /*CivicTypes*/ eCivic) { return m_pPlayer ? m_pPlayer->getCivicPercentAnger((CivicTypes) eCivic) : -1; } bool CyPlayer::canDoReligion(int /*ReligionTypes*/ eReligion) { return m_pPlayer ? m_pPlayer->canDoReligion((ReligionTypes) eReligion) : false; } bool CyPlayer::canChangeReligion() { return m_pPlayer ? m_pPlayer->canChangeReligion() : false; } bool CyPlayer::canConvert(int /*ReligionTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->canConvert((ReligionTypes)iIndex) : false; } void CyPlayer::convert(int /*ReligionTypes*/ iIndex) { if (m_pPlayer) m_pPlayer->convert((ReligionTypes)iIndex); } bool CyPlayer::hasHolyCity(int /*ReligionTypes*/ eReligion) { return m_pPlayer ? m_pPlayer->hasHolyCity((ReligionTypes)eReligion) : false; } int CyPlayer::countHolyCities() { return m_pPlayer ? m_pPlayer->countHolyCities() : -1; } void CyPlayer::foundReligion(int /*ReligionTypes*/ iIndex, int /*ReligionTypes*/ iSlotReligion, bool bAward) { if (m_pPlayer) m_pPlayer->foundReligion((ReligionTypes)iIndex, (ReligionTypes)iSlotReligion, bAward); } bool CyPlayer::hasHeadquarters(int /*CorporationTypes*/ eCorporation) { return m_pPlayer ? m_pPlayer->hasHeadquarters((CorporationTypes)eCorporation) : false; } int CyPlayer::countHeadquarters() { return m_pPlayer ? m_pPlayer->countHeadquarters() : -1; } int CyPlayer::countCorporations(int /*CorporationTypes*/ eCorporation) { return m_pPlayer ? m_pPlayer->countCorporations((CorporationTypes)eCorporation) : -1; } void CyPlayer::foundCorporation(int /*CorporationTypes*/ iIndex) { if (m_pPlayer) m_pPlayer->foundCorporation((CorporationTypes)iIndex); } int CyPlayer::getCivicAnarchyLength(boost::python::list& /*CivicTypes**/ paeNewCivics) { int* pCivics = NULL; gDLL->getPythonIFace()->putSeqInArray(paeNewCivics.ptr() /*src*/, &pCivics /*dst*/); int iRet = m_pPlayer ? m_pPlayer->getCivicAnarchyLength((CivicTypes*)pCivics) : -1; delete [] pCivics; return iRet; } int CyPlayer::getReligionAnarchyLength() { return m_pPlayer ? m_pPlayer->getReligionAnarchyLength() : -1; } int CyPlayer::unitsRequiredForGoldenAge() { return m_pPlayer ? m_pPlayer->unitsRequiredForGoldenAge() : -1; } int CyPlayer::unitsGoldenAgeCapable() { return m_pPlayer ? m_pPlayer->unitsGoldenAgeCapable() : -1; } int CyPlayer::unitsGoldenAgeReady() { return m_pPlayer ? m_pPlayer->unitsGoldenAgeReady() : -1; } int CyPlayer::greatPeopleThreshold(bool bMilitary) { return m_pPlayer ? m_pPlayer->greatPeopleThreshold(bMilitary) : -1; } int CyPlayer::specialistYield(int /*SpecialistTypes*/ eSpecialist, int /*YieldTypes*/ eCommerce) { return m_pPlayer ? m_pPlayer->specialistYield((SpecialistTypes)eSpecialist, (YieldTypes)eCommerce) : -1; } int CyPlayer::specialistCommerce(int /*SpecialistTypes*/ eSpecialist, int /*CommerceTypes*/ eCommerce) { return m_pPlayer ? m_pPlayer->specialistCommerce((SpecialistTypes)eSpecialist, (CommerceTypes)eCommerce) : -1; } CyPlot* CyPlayer::getStartingPlot() { if (!m_pPlayer) { return NULL; } return new CyPlot(m_pPlayer->getStartingPlot()); } void CyPlayer::setStartingPlot(CyPlot* pPlot, bool bUpdateStartDist) { if (!m_pPlayer) { return; } m_pPlayer->setStartingPlot(NULL != pPlot ? pPlot->getPlot() : NULL, bUpdateStartDist); } int CyPlayer::getTotalPopulation() { return m_pPlayer ? m_pPlayer->getTotalPopulation() : -1; } int CyPlayer::getAveragePopulation() { return m_pPlayer ? m_pPlayer->getAveragePopulation() : -1; } long CyPlayer::getRealPopulation() { return m_pPlayer ? m_pPlayer->getRealPopulation() : -1; } int CyPlayer::getTotalLand() { return m_pPlayer ? m_pPlayer->getTotalLand() : -1; } int CyPlayer::getTotalLandScored() { return m_pPlayer ? m_pPlayer->getTotalLandScored() : -1; } int CyPlayer::getGold() { return m_pPlayer ? m_pPlayer->getGold() : -1; } void CyPlayer::setGold(int iNewValue) { if (m_pPlayer) m_pPlayer->setGold(iNewValue); } void CyPlayer::changeGold(int iChange) { if (m_pPlayer) m_pPlayer->changeGold(iChange); } int CyPlayer::getGoldPerTurn() { return m_pPlayer ? m_pPlayer->getGoldPerTurn() : -1; } int CyPlayer::getAdvancedStartPoints() { return m_pPlayer ? m_pPlayer->getAdvancedStartPoints() : -1; } void CyPlayer::setAdvancedStartPoints(int iNewValue) { if (m_pPlayer) m_pPlayer->setAdvancedStartPoints(iNewValue); } void CyPlayer::changeAdvancedStartPoints(int iChange) { if (m_pPlayer) m_pPlayer->changeAdvancedStartPoints(iChange); } int CyPlayer::getAdvancedStartUnitCost(int /*UnitTypes*/ eUnit, bool bAdd, CyPlot* pPlot) { return m_pPlayer ? m_pPlayer->getAdvancedStartUnitCost((UnitTypes) eUnit, bAdd, NULL != pPlot ? pPlot->getPlot() : NULL) : -1; } int CyPlayer::getAdvancedStartCityCost(bool bAdd, CyPlot* pPlot) { return m_pPlayer ? m_pPlayer->getAdvancedStartCityCost(bAdd, NULL != pPlot ? pPlot->getPlot() : NULL) : -1; } int CyPlayer::getAdvancedStartPopCost(bool bAdd, CyCity* pCity) { return m_pPlayer ? m_pPlayer->getAdvancedStartPopCost(bAdd, pCity->getCity()) : -1; } int CyPlayer::getAdvancedStartCultureCost(bool bAdd, CyCity* pCity) { return m_pPlayer ? m_pPlayer->getAdvancedStartCultureCost(bAdd, pCity->getCity()) : -1; } int CyPlayer::getAdvancedStartBuildingCost(int /*BuildingTypes*/ eBuilding, bool bAdd, CyCity* pCity) { return m_pPlayer ? m_pPlayer->getAdvancedStartBuildingCost((BuildingTypes) eBuilding, bAdd, pCity->getCity()) : -1; } int CyPlayer::getAdvancedStartImprovementCost(int /*ImprovementTypes*/ eImprovement, bool bAdd, CyPlot* pPlot) { return m_pPlayer ? m_pPlayer->getAdvancedStartImprovementCost((ImprovementTypes) eImprovement, bAdd, NULL != pPlot ? pPlot->getPlot() : NULL) : -1; } int CyPlayer::getAdvancedStartRouteCost(int /*RouteTypes*/ eRoute, bool bAdd, CyPlot* pPlot) { return m_pPlayer ? m_pPlayer->getAdvancedStartRouteCost((RouteTypes) eRoute, bAdd, NULL != pPlot ? pPlot->getPlot() : NULL) : -1; } int CyPlayer::getAdvancedStartTechCost(int /*TechTypes*/ eTech, bool bAdd) { return m_pPlayer ? m_pPlayer->getAdvancedStartTechCost((TechTypes) eTech, bAdd) : -1; } int CyPlayer::getAdvancedStartVisibilityCost(bool bAdd, CyPlot* pPlot) { return m_pPlayer ? m_pPlayer->getAdvancedStartVisibilityCost(bAdd, NULL != pPlot ? pPlot->getPlot() : NULL) : -1; } int CyPlayer::getEspionageSpending(int /*TeamTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getEspionageSpending((TeamTypes) eIndex) : -1; } bool CyPlayer::canDoEspionageMission(int /*EspionageMissionTypes*/ eMission, int /*PlayerTypes*/ eTargetPlayer, CyPlot* pPlot, int iExtraData) { return m_pPlayer ? m_pPlayer->canDoEspionageMission((EspionageMissionTypes) eMission, (PlayerTypes) eTargetPlayer, NULL != pPlot ? pPlot->getPlot() : NULL, iExtraData, NULL) : false; } int CyPlayer::getEspionageMissionCost(int /*EspionageMissionTypes*/ eMission, int /*PlayerTypes*/ eTargetPlayer, CyPlot* pPlot, int iExtraData) { return m_pPlayer ? m_pPlayer->getEspionageMissionCost((EspionageMissionTypes) eMission, (PlayerTypes) eTargetPlayer, NULL != pPlot ? pPlot->getPlot() : NULL, iExtraData) : -1; } void CyPlayer::doEspionageMission(int /*EspionageMissionTypes*/ eMission, int /*PlayerTypes*/ eTargetPlayer, CyPlot* pPlot, int iExtraData, CyUnit* pUnit) { if (m_pPlayer) m_pPlayer->doEspionageMission((EspionageMissionTypes) eMission, (PlayerTypes) eTargetPlayer, NULL != pPlot ? pPlot->getPlot() : NULL, iExtraData, pUnit->getUnit()); } int CyPlayer::getEspionageSpendingWeightAgainstTeam(int /*TeamTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getEspionageSpendingWeightAgainstTeam((TeamTypes) eIndex) : -1; } void CyPlayer::setEspionageSpendingWeightAgainstTeam(int /*TeamTypes*/ eIndex, int iValue) { if (m_pPlayer) m_pPlayer->setEspionageSpendingWeightAgainstTeam((TeamTypes) eIndex, iValue); } void CyPlayer::changeEspionageSpendingWeightAgainstTeam(int /*TeamTypes*/ eIndex, int iChange) { if (m_pPlayer) m_pPlayer->changeEspionageSpendingWeightAgainstTeam((TeamTypes) eIndex, iChange); } int CyPlayer::getGoldenAgeTurns() { return m_pPlayer ? m_pPlayer->getGoldenAgeTurns() : -1; } int CyPlayer::getGoldenAgeLength() { return m_pPlayer ? m_pPlayer->getGoldenAgeLength() : -1; } bool CyPlayer::isGoldenAge() { return m_pPlayer ? m_pPlayer->isGoldenAge() : false; } void CyPlayer::changeGoldenAgeTurns(int iChange) { if (m_pPlayer) m_pPlayer->changeGoldenAgeTurns(iChange); } int CyPlayer::getNumUnitGoldenAges() { return m_pPlayer ? m_pPlayer->getNumUnitGoldenAges() : -1; } void CyPlayer::changeNumUnitGoldenAges(int iChange) { if (m_pPlayer) m_pPlayer->changeNumUnitGoldenAges(iChange); } int CyPlayer::getAnarchyTurns() { return m_pPlayer ? m_pPlayer->getAnarchyTurns() : -1; } bool CyPlayer::isAnarchy() { return m_pPlayer ? m_pPlayer->isAnarchy() : false; } void CyPlayer::changeAnarchyTurns(int iChange) { if (m_pPlayer) m_pPlayer->changeAnarchyTurns(iChange); } int CyPlayer::getStrikeTurns() { return m_pPlayer ? m_pPlayer->getStrikeTurns() : -1; } int CyPlayer::getMaxAnarchyTurns() { return m_pPlayer ? m_pPlayer->getMaxAnarchyTurns() : -1; } int CyPlayer::getAnarchyModifier() { return m_pPlayer ? m_pPlayer->getAnarchyModifier() : -1; } int CyPlayer::getGoldenAgeModifier() { return m_pPlayer ? m_pPlayer->getGoldenAgeModifier() : -1; } int CyPlayer::getHurryModifier() { return m_pPlayer ? m_pPlayer->getHurryModifier() : -1; } void CyPlayer::createGreatPeople(int eGreatPersonUnit, bool bIncrementThreshold, bool bIncrementExperience, int iX, int iY) { if (m_pPlayer) { m_pPlayer->createGreatPeople((UnitTypes)eGreatPersonUnit, bIncrementThreshold, bIncrementExperience, iX, iY); } } int CyPlayer::getGreatPeopleCreated() { return m_pPlayer ? m_pPlayer->getGreatPeopleCreated() : -1; } int CyPlayer::getGreatGeneralsCreated() { return m_pPlayer ? m_pPlayer->getGreatGeneralsCreated() : -1; } int CyPlayer::getGreatPeopleThresholdModifier() { return m_pPlayer ? m_pPlayer->getGreatPeopleThresholdModifier() : -1; } int CyPlayer::getGreatGeneralsThresholdModifier() { return m_pPlayer ? m_pPlayer->getGreatGeneralsThresholdModifier() : -1; } int CyPlayer::getGreatPeopleRateModifier() { return m_pPlayer ? m_pPlayer->getGreatPeopleRateModifier() : -1; } int CyPlayer::getGreatGeneralRateModifier() { return m_pPlayer ? m_pPlayer->getGreatGeneralRateModifier() : -1; } int CyPlayer::getDomesticGreatGeneralRateModifier() { return m_pPlayer ? m_pPlayer->getDomesticGreatGeneralRateModifier() : -1; } int CyPlayer::getStateReligionGreatPeopleRateModifier() { return m_pPlayer ? m_pPlayer->getStateReligionGreatPeopleRateModifier() : -1; } int CyPlayer::getMaxGlobalBuildingProductionModifier() { return m_pPlayer ? m_pPlayer->getMaxGlobalBuildingProductionModifier() : -1; } int CyPlayer::getMaxTeamBuildingProductionModifier() { return m_pPlayer ? m_pPlayer->getMaxTeamBuildingProductionModifier() : -1; } int CyPlayer::getMaxPlayerBuildingProductionModifier() { return m_pPlayer ? m_pPlayer->getMaxPlayerBuildingProductionModifier() : -1; } int CyPlayer::getFreeExperience() { return m_pPlayer ? m_pPlayer->getFreeExperience() : -1; } int CyPlayer::getFeatureProductionModifier() { return m_pPlayer ? m_pPlayer->getFeatureProductionModifier() : -1; } int CyPlayer::getWorkerSpeedModifier() { return m_pPlayer ? m_pPlayer->getWorkerSpeedModifier() : -1; } int CyPlayer::getImprovementUpgradeRateModifier() { return m_pPlayer ? m_pPlayer->getImprovementUpgradeRateModifier() : -1; } int CyPlayer::getMilitaryProductionModifier() { return m_pPlayer ? m_pPlayer->getMilitaryProductionModifier() : -1; } int CyPlayer::getSpaceProductionModifier() { return m_pPlayer ? m_pPlayer->getSpaceProductionModifier() : -1; } int CyPlayer::getCityDefenseModifier() { return m_pPlayer ? m_pPlayer->getCityDefenseModifier() : -1; } int CyPlayer::getNumNukeUnits() { return m_pPlayer ? m_pPlayer->getNumNukeUnits() : -1; } int CyPlayer::getNumOutsideUnits() { return m_pPlayer ? m_pPlayer->getNumOutsideUnits() : -1; } int CyPlayer::getBaseFreeUnits() { return m_pPlayer ? m_pPlayer->getBaseFreeUnits() : -1; } int CyPlayer::getBaseFreeMilitaryUnits() { return m_pPlayer ? m_pPlayer->getBaseFreeMilitaryUnits() : -1; } int CyPlayer::getFreeUnitsPopulationPercent() { return m_pPlayer ? m_pPlayer->getFreeUnitsPopulationPercent() : -1; } int CyPlayer::getFreeMilitaryUnitsPopulationPercent() { return m_pPlayer ? m_pPlayer->getFreeMilitaryUnitsPopulationPercent() : -1; } int CyPlayer::getGoldPerUnit() { return m_pPlayer ? m_pPlayer->getGoldPerUnit() : -1; } int CyPlayer::getGoldPerMilitaryUnit() { return m_pPlayer ? m_pPlayer->getGoldPerMilitaryUnit() : -1; } int CyPlayer::getExtraUnitCost() { return m_pPlayer ? m_pPlayer->getExtraUnitCost() : -1; } int CyPlayer::getNumMilitaryUnits() { return m_pPlayer ? m_pPlayer->getNumMilitaryUnits() : -1; } int CyPlayer::getHappyPerMilitaryUnit() { return m_pPlayer ? m_pPlayer->getHappyPerMilitaryUnit() : -1; } bool CyPlayer::isMilitaryFoodProduction() { return m_pPlayer ? m_pPlayer->isMilitaryFoodProduction() : false; } int CyPlayer::getHighestUnitLevel() { return m_pPlayer ? m_pPlayer->getHighestUnitLevel() : -1; } int CyPlayer::getConscriptCount() { return m_pPlayer ? m_pPlayer->getConscriptCount() : -1; } void CyPlayer::setConscriptCount(int iNewValue) { if (m_pPlayer) m_pPlayer->setConscriptCount(iNewValue); } void CyPlayer::changeConscriptCount(int iChange) { if (m_pPlayer) m_pPlayer->changeConscriptCount(iChange); } int CyPlayer::getMaxConscript() { return m_pPlayer ? m_pPlayer->getMaxConscript() : -1; } int CyPlayer::getOverflowResearch() { return m_pPlayer ? m_pPlayer->getOverflowResearch() : 0; } /* ** K-Mod, 27/dec/10, karadoc ** replaced NoUnhealthyPopulation with UnhealthyPopulationModifier */ /* original bts code bool CyPlayer::isNoUnhealthyPopulation() { return m_pPlayer ? m_pPlayer->isNoUnhealthyPopulation() : false; }*/ int CyPlayer::getUnhealthyPopulationModifier() { return m_pPlayer ? m_pPlayer->getUnhealthyPopulationModifier() : 0; } /* ** K-Mod end */ bool CyPlayer::getExpInBorderModifier() { return m_pPlayer ? m_pPlayer->getExpInBorderModifier() : false; } bool CyPlayer::isBuildingOnlyHealthy() { return m_pPlayer ? m_pPlayer->isBuildingOnlyHealthy() : false; } int CyPlayer::getDistanceMaintenanceModifier() { return m_pPlayer ? m_pPlayer->getDistanceMaintenanceModifier() : -1; } int CyPlayer::getNumCitiesMaintenanceModifier() { return m_pPlayer ? m_pPlayer->getNumCitiesMaintenanceModifier() : -1; } int CyPlayer::getCorporationMaintenanceModifier() { return m_pPlayer ? m_pPlayer->getCorporationMaintenanceModifier() : -1; } int CyPlayer::getTotalMaintenance() { return m_pPlayer ? m_pPlayer->getTotalMaintenance() : -1; } int CyPlayer::getUpkeepModifier() { return m_pPlayer ? m_pPlayer->getUpkeepModifier() : -1; } int CyPlayer::getLevelExperienceModifier() const { return m_pPlayer ? m_pPlayer->getLevelExperienceModifier() : -1; } int CyPlayer::getExtraHealth() { return m_pPlayer ? m_pPlayer->getExtraHealth() : -1; } int CyPlayer::getBuildingGoodHealth() { return m_pPlayer ? m_pPlayer->getBuildingGoodHealth() : -1; } int CyPlayer::getBuildingBadHealth() { return m_pPlayer ? m_pPlayer->getBuildingBadHealth() : -1; } int CyPlayer::getExtraHappiness() { return m_pPlayer ? m_pPlayer->getExtraHappiness() : -1; } void CyPlayer::changeExtraHappiness(int iChange) { if (m_pPlayer) m_pPlayer->changeExtraHappiness(iChange); } int CyPlayer::getBuildingHappiness() { return m_pPlayer ? m_pPlayer->getBuildingHappiness() : -1; } int CyPlayer::getLargestCityHappiness() { return m_pPlayer ? m_pPlayer->getLargestCityHappiness() : -1; } int CyPlayer::getWarWearinessPercentAnger() { return m_pPlayer ? m_pPlayer->getWarWearinessPercentAnger() : -1; } int CyPlayer::getWarWearinessModifier() { return m_pPlayer ? m_pPlayer->getWarWearinessModifier() : -1; } int CyPlayer::getFreeSpecialist() { return m_pPlayer ? m_pPlayer->getFreeSpecialist() : -1; } bool CyPlayer::isNoForeignTrade() { return m_pPlayer ? m_pPlayer->isNoForeignTrade() : false; } bool CyPlayer::isNoCorporations() { return m_pPlayer ? m_pPlayer->isNoCorporations() : false; } bool CyPlayer::isNoForeignCorporations() { return m_pPlayer ? m_pPlayer->isNoForeignCorporations() : false; } int CyPlayer::getCoastalTradeRoutes() { return m_pPlayer ? m_pPlayer->getCoastalTradeRoutes() : -1; } void CyPlayer::changeCoastalTradeRoutes(int iChange) { if (m_pPlayer) m_pPlayer->changeCoastalTradeRoutes(iChange); } int CyPlayer::getTradeRoutes() { return m_pPlayer ? m_pPlayer->getTradeRoutes() : -1; } int CyPlayer::getConversionTimer() { return m_pPlayer ? m_pPlayer->getConversionTimer() : -1; } int CyPlayer::getRevolutionTimer() { return m_pPlayer ? m_pPlayer->getRevolutionTimer() : -1; } bool CyPlayer::isStateReligion() { return m_pPlayer ? m_pPlayer->isStateReligion() : false; } bool CyPlayer::isNoNonStateReligionSpread() { return m_pPlayer ? m_pPlayer->isNoNonStateReligionSpread() : false; } int CyPlayer::getStateReligionHappiness() { return m_pPlayer ? m_pPlayer->getStateReligionHappiness() : -1; } int CyPlayer::getNonStateReligionHappiness() { return m_pPlayer ? m_pPlayer->getNonStateReligionHappiness() : -1; } int CyPlayer::getStateReligionUnitProductionModifier() { return m_pPlayer ? m_pPlayer->getStateReligionUnitProductionModifier() : -1; } void CyPlayer::changeStateReligionUnitProductionModifier(int iChange) { if (m_pPlayer) m_pPlayer->changeStateReligionUnitProductionModifier(iChange); } int CyPlayer::getStateReligionBuildingProductionModifier() { return m_pPlayer ? m_pPlayer->getStateReligionBuildingProductionModifier() : -1; } void CyPlayer::changeStateReligionBuildingProductionModifier(int iChange) { if (m_pPlayer) m_pPlayer->changeStateReligionBuildingProductionModifier(iChange); } int CyPlayer::getStateReligionFreeExperience() { return m_pPlayer ? m_pPlayer->getStateReligionFreeExperience() : -1; } CyCity* CyPlayer::getCapitalCity() { return m_pPlayer ? new CyCity(m_pPlayer->getCapitalCity()) : NULL; } int CyPlayer::getCitiesLost() { return m_pPlayer ? m_pPlayer->getCitiesLost() : -1; } int CyPlayer::getWinsVsBarbs() { return m_pPlayer ? m_pPlayer->getWinsVsBarbs() : -1; } int CyPlayer::getAssets() { return m_pPlayer ? m_pPlayer->getAssets() : -1; } void CyPlayer::changeAssets(int iChange) { if (m_pPlayer) m_pPlayer->changeAssets(iChange); } int CyPlayer::getPower() { return m_pPlayer ? m_pPlayer->getPower() : -1; } int CyPlayer::getPopScore() { return m_pPlayer ? m_pPlayer->getPopScore() : -1; } int CyPlayer::getLandScore() { return m_pPlayer ? m_pPlayer->getLandScore() : -1; } int CyPlayer::getWondersScore() { return m_pPlayer ? m_pPlayer->getWondersScore() : -1; } int CyPlayer::getTechScore() { return m_pPlayer ? m_pPlayer->getTechScore() : -1; } int CyPlayer::getTotalTimePlayed() { return m_pPlayer ? m_pPlayer->getTotalTimePlayed() : -1; } bool CyPlayer::isMinorCiv() { return m_pPlayer ? m_pPlayer->isMinorCiv() : false; } bool CyPlayer::isAlive() { return m_pPlayer ? m_pPlayer->isAlive() : false; } bool CyPlayer::isEverAlive() { return m_pPlayer ? m_pPlayer->isEverAlive() : false; } bool CyPlayer::isExtendedGame() { return m_pPlayer ? m_pPlayer->isExtendedGame() : false; } bool CyPlayer::isFoundedFirstCity() { return m_pPlayer ? m_pPlayer->isFoundedFirstCity() : false; } bool CyPlayer::isStrike() { return m_pPlayer ? m_pPlayer->isStrike() : false; } int CyPlayer::getID() { return m_pPlayer ? m_pPlayer->getID() : -1; } int /* HandicapTypes */ CyPlayer::getHandicapType() { return m_pPlayer ? (int) m_pPlayer->getHandicapType() : -1; } int /* CivilizationTypes */ CyPlayer::getCivilizationType() { return m_pPlayer ? (int) m_pPlayer->getCivilizationType() : NO_CIVILIZATION; } int /*LeaderHeadTypes*/ CyPlayer::getLeaderType() { return m_pPlayer ? (int) m_pPlayer->getLeaderType() : -1; } int /*LeaderHeadTypes*/ CyPlayer::getPersonalityType() { return m_pPlayer ? (int) m_pPlayer->getPersonalityType() : -1; } void CyPlayer::setPersonalityType(int /*LeaderHeadTypes*/ eNewValue) { if (m_pPlayer) m_pPlayer->setPersonalityType((LeaderHeadTypes) eNewValue); } int /*ErasTypes*/ CyPlayer::getCurrentEra() { return m_pPlayer ? (int) m_pPlayer->getCurrentEra() : NO_ERA; } void CyPlayer::setCurrentEra(int /*EraTypes*/ iNewValue) { if (m_pPlayer) m_pPlayer->setCurrentEra((EraTypes) iNewValue); } int /*ReligonTypes*/ CyPlayer::getStateReligion() { return m_pPlayer ? (int) m_pPlayer->getStateReligion() : NO_RELIGION; } void CyPlayer::setLastStateReligion(int /*ReligionTypes*/ iNewReligion) { if (m_pPlayer) m_pPlayer->setLastStateReligion((ReligionTypes) iNewReligion); } int CyPlayer::getTeam() { return m_pPlayer ? m_pPlayer->getTeam() : -1; } int /*PlayerColorTypes*/ CyPlayer::getPlayerColor() { return m_pPlayer ? (int) m_pPlayer->getPlayerColor() : NO_COLOR; } int CyPlayer::getPlayerTextColorR() { return m_pPlayer ? m_pPlayer->getPlayerTextColorR() : -1; } int CyPlayer::getPlayerTextColorG() { return m_pPlayer ? m_pPlayer->getPlayerTextColorG() : -1; } int CyPlayer::getPlayerTextColorB() { return m_pPlayer ? m_pPlayer->getPlayerTextColorB() : -1; } int CyPlayer::getPlayerTextColorA() { return m_pPlayer ? m_pPlayer->getPlayerTextColorA() : -1; } int CyPlayer::getSeaPlotYield(YieldTypes eIndex) { return m_pPlayer ? (int) m_pPlayer->getSeaPlotYield(eIndex) : NO_YIELD; } int CyPlayer::getYieldRateModifier(YieldTypes eIndex) { return m_pPlayer ? m_pPlayer->getYieldRateModifier(eIndex) : NO_YIELD; } int CyPlayer::getCapitalYieldRateModifier(YieldTypes eIndex) { return m_pPlayer ? m_pPlayer->getCapitalYieldRateModifier(eIndex) : NO_YIELD; } int CyPlayer::getExtraYieldThreshold(YieldTypes eIndex) { return m_pPlayer ? m_pPlayer->getExtraYieldThreshold(eIndex) : NO_YIELD; } int CyPlayer::getTradeYieldModifier(YieldTypes eIndex) { return m_pPlayer ? m_pPlayer->getTradeYieldModifier(eIndex) : NO_YIELD; } int CyPlayer::getFreeCityCommerce(CommerceTypes eIndex) { return m_pPlayer ? m_pPlayer->getFreeCityCommerce(eIndex) : NO_COMMERCE; } int CyPlayer::getCommercePercent(int /*CommerceTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getCommercePercent((CommerceTypes)eIndex) : NO_COMMERCE; } void CyPlayer::setCommercePercent(CommerceTypes eIndex, int iNewValue) { if (m_pPlayer) m_pPlayer->setCommercePercent(eIndex, iNewValue); } void CyPlayer::changeCommercePercent(CommerceTypes eIndex, int iChange) { if (m_pPlayer) m_pPlayer->changeCommercePercent(eIndex, iChange); } int CyPlayer::getCommerceRate(CommerceTypes eIndex) { return m_pPlayer ? m_pPlayer->getCommerceRate(eIndex) : -1; } int CyPlayer::getCommerceRateModifier(CommerceTypes eIndex) { return m_pPlayer ? m_pPlayer->getCommerceRateModifier(eIndex) : NO_COMMERCE; } int CyPlayer::getCapitalCommerceRateModifier(CommerceTypes eIndex) { return m_pPlayer ? m_pPlayer->getCapitalCommerceRateModifier(eIndex) : NO_COMMERCE; } int CyPlayer::getStateReligionBuildingCommerce(CommerceTypes eIndex) { return m_pPlayer ? m_pPlayer->getStateReligionBuildingCommerce(eIndex) : NO_COMMERCE; } int CyPlayer::getSpecialistExtraCommerce(CommerceTypes eIndex) { return m_pPlayer ? m_pPlayer->getSpecialistExtraCommerce(eIndex) : NO_COMMERCE; } bool CyPlayer::isCommerceFlexible(int /*CommerceTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->isCommerceFlexible((CommerceTypes)eIndex) : false; } int CyPlayer::getGoldPerTurnByPlayer(int /*PlayerTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getGoldPerTurnByPlayer((PlayerTypes) eIndex) : -1; } bool CyPlayer::isFeatAccomplished(int /*FeatTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->isFeatAccomplished((FeatTypes)eIndex) : false; } void CyPlayer::setFeatAccomplished(int /*FeatTypes*/ eIndex, bool bNewValue) { if (m_pPlayer) m_pPlayer->setFeatAccomplished((FeatTypes)eIndex, bNewValue); } bool CyPlayer::isOption(int /*PlayerOptionTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->isOption((PlayerOptionTypes)eIndex) : false; } void CyPlayer::setOption(int /*PlayerOptionTypes*/ eIndex, bool bNewValue) { if (m_pPlayer) m_pPlayer->setOption((PlayerOptionTypes)eIndex, bNewValue); } bool CyPlayer::isLoyalMember(int /*VoteSourceTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->isLoyalMember((VoteSourceTypes)eIndex) : false; } void CyPlayer::setLoyalMember(int /*VoteSourceTypes*/ eIndex, bool bNewValue) { if (m_pPlayer) m_pPlayer->setLoyalMember((VoteSourceTypes)eIndex, bNewValue); } int CyPlayer::getVotes(int /*VoteTypes*/ eVote, int /*VoteSourceTypes*/ eVoteSource) { return m_pPlayer ? m_pPlayer->getVotes((VoteTypes)eVote, (VoteSourceTypes)eVoteSource) : -1; } bool CyPlayer::isFullMember(int /*VoteSourceTypes*/ eVoteSource) const { return m_pPlayer ? m_pPlayer->isFullMember((VoteSourceTypes)eVoteSource) : false; } bool CyPlayer::isVotingMember(int /*VoteSourceTypes*/ eVoteSource) const { return m_pPlayer ? m_pPlayer->isVotingMember((VoteSourceTypes)eVoteSource) : false; } bool CyPlayer::isPlayable() { return m_pPlayer ? m_pPlayer->isPlayable() : false; } void CyPlayer::setPlayable(bool bNewValue) { if (m_pPlayer) m_pPlayer->setPlayable(bNewValue); } int CyPlayer::getBonusExport(int /*BonusTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getBonusExport((BonusTypes)iIndex) : -1; } int CyPlayer::getBonusImport(int /*BonusTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getBonusImport((BonusTypes)iIndex) : -1; } int CyPlayer::getImprovementCount(int /*ImprovementTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getImprovementCount((ImprovementTypes)iIndex) : -1; } bool CyPlayer::isBuildingFree(int /*BuildingTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->isBuildingFree((BuildingTypes)iIndex) : false; } int CyPlayer::getExtraBuildingHappiness(int /*BuildingTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getExtraBuildingHappiness((BuildingTypes)iIndex) : -1; } int CyPlayer::getExtraBuildingHealth(int /*BuildingTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getExtraBuildingHealth((BuildingTypes)iIndex) : -1; } int CyPlayer::getFeatureHappiness(int /*FeatureTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getFeatureHappiness((FeatureTypes)iIndex) : -1; } int CyPlayer::getUnitClassCount(int /*UnitClassTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getUnitClassCount((UnitClassTypes) eIndex) : NO_UNITCLASS; } bool CyPlayer::isUnitClassMaxedOut(int /*UnitClassTypes*/ eIndex, int iExtra) { return m_pPlayer ? m_pPlayer->isUnitClassMaxedOut((UnitClassTypes) eIndex, iExtra) : false; } int CyPlayer::getUnitClassMaking(int /*UnitClassTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getUnitClassMaking((UnitClassTypes) eIndex) : -1; } int CyPlayer::getUnitClassCountPlusMaking(int /*UnitClassTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getUnitClassCountPlusMaking((UnitClassTypes) eIndex) : -1; } int CyPlayer::getBuildingClassCount(int /*BuildingClassTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getBuildingClassCount((BuildingClassTypes)iIndex) : -1; } bool CyPlayer::isBuildingClassMaxedOut(int /*BuildingClassTypes*/ iIndex, int iExtra) { return m_pPlayer ? m_pPlayer->isBuildingClassMaxedOut((BuildingClassTypes)iIndex, iExtra) : false; } int CyPlayer::getBuildingClassMaking(int /*BuildingClassTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getBuildingClassMaking((BuildingClassTypes)iIndex) : -1; } int CyPlayer::getBuildingClassCountPlusMaking(int /*BuildingClassTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getBuildingClassCountPlusMaking((BuildingClassTypes)iIndex) : -1; } int CyPlayer::getHurryCount(int /*HurryTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getHurryCount((HurryTypes)eIndex) : (int) NO_HURRY; } bool CyPlayer::canHurry(int /*HurryTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->canHurry((HurryTypes)eIndex) : (int) NO_HURRY; } int CyPlayer::getSpecialBuildingNotRequiredCount(int /*SpecialBuildingTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getSpecialBuildingNotRequiredCount((SpecialBuildingTypes)eIndex) : -1; } bool CyPlayer::isSpecialBuildingNotRequired(int /*SpecialBuildingTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->isSpecialBuildingNotRequired((SpecialBuildingTypes)eIndex) : -1; } bool CyPlayer::isHasCivicOption(int /*CivicOptionTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->isHasCivicOption((CivicOptionTypes) eIndex) : false; } bool CyPlayer::isNoCivicUpkeep(int /*CivicOptionTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->isNoCivicUpkeep((CivicOptionTypes)iIndex) : false; } int CyPlayer::getHasReligionCount(int /*ReligionTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getHasReligionCount((ReligionTypes)iIndex) : -1; } int CyPlayer::countTotalHasReligion() { return m_pPlayer ? m_pPlayer->countTotalHasReligion() : -1; } int CyPlayer::getHasCorporationCount(int /*CorporationTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getHasCorporationCount((CorporationTypes)iIndex) : -1; } int CyPlayer::countTotalHasCorporation() { return m_pPlayer ? m_pPlayer->countTotalHasCorporation() : -1; } int CyPlayer::findHighestHasReligionCount() { return m_pPlayer ? m_pPlayer->findHighestHasReligionCount() : -1; } int CyPlayer::getUpkeepCount(int /*UpkeepTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->getUpkeepCount((UpkeepTypes) eIndex) : -1; } bool CyPlayer::isSpecialistValid(int /*SpecialistTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->isSpecialistValid((SpecialistTypes)iIndex) : false; } bool CyPlayer::isResearchingTech(int /*TechTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->isResearchingTech((TechTypes)iIndex) : false; } int /* CivicTypes */ CyPlayer::getCivics(int /*CivicOptionTypes*/ iIndex) { return m_pPlayer ? m_pPlayer->getCivics((CivicOptionTypes)iIndex) : -1; } int CyPlayer::getSingleCivicUpkeep(int /*CivicTypes*/ eCivic, bool bIgnoreAnarchy) { return m_pPlayer ? m_pPlayer->getSingleCivicUpkeep((CivicTypes) eCivic, bIgnoreAnarchy) : -1; } int CyPlayer::getCivicUpkeep(boost::python::list& /*CivicTypes*/ paiCivics, bool bIgnoreAnarchy) { int* pCivics = NULL; gDLL->getPythonIFace()->putSeqInArray(paiCivics.ptr() /*src*/, &pCivics /*dst*/); int iRet = m_pPlayer ? m_pPlayer->getCivicUpkeep((CivicTypes*)pCivics, bIgnoreAnarchy) : -1; delete [] pCivics; return iRet; } void CyPlayer::setCivics(int /*CivicOptionTypes*/ eIndex, int /*CivicTypes*/ eNewValue) { if (m_pPlayer) m_pPlayer->setCivics((CivicOptionTypes) eIndex, (CivicTypes) eNewValue); } // Civ4 Reimagined int CyPlayer::getBonusValueModifier() { return m_pPlayer ? m_pPlayer->getBonusValueModifier() : -1; } // Civ4 Reimagined int CyPlayer::getTechValue() { return m_pPlayer ? m_pPlayer->getTechValue() : -1; } // Civ4 Reimagined int CyPlayer::getBonusRatio() { return m_pPlayer ? m_pPlayer->getBonusRatio() : -1; } // Civ4 Reimagined int CyPlayer::getUniquePowerLevel() { return m_pPlayer ? m_pPlayer->getUniquePowerLevel() : -1; } // Civ4 Reimagined long CyPlayer::getUniquePowerRequirement(int iLevel) { return m_pPlayer ? m_pPlayer->getUniquePowerRequirement(iLevel) : -1; } // Civ4 Reimagined long CyPlayer::getAccumulatedCulture() { return m_pPlayer ? m_pPlayer->getAccumulatedCulture() : -1; } // Civ4 Reimagined long CyPlayer::getUniquePowerRate() { return m_pPlayer ? m_pPlayer->getUniquePowerRate() : -1; } // Civ4 Reimagined int CyPlayer::getMayaCalendar() { return m_pPlayer ? m_pPlayer->getMayaCalendar() : -1; } int CyPlayer::getCombatExperience() const { if (m_pPlayer) { return m_pPlayer->getCombatExperience(); } return -1; } void CyPlayer::changeCombatExperience(int iChange) { if (m_pPlayer) { m_pPlayer->changeCombatExperience(iChange); } } void CyPlayer::setCombatExperience(int iExperience) { if (m_pPlayer) { m_pPlayer->setCombatExperience(iExperience); } } int CyPlayer::getSpecialistExtraYield(int /*SpecialistTypes*/ eIndex1, int /*YieldTypes*/ eIndex2) { return m_pPlayer ? m_pPlayer->getSpecialistExtraYield((SpecialistTypes) eIndex1, (YieldTypes) eIndex2) : -1; } int CyPlayer::findPathLength(int /*TechTypes*/ eTech, bool bCost) { return m_pPlayer ? m_pPlayer->findPathLength((TechTypes)eTech, bCost) : -1; } int CyPlayer::getQueuePosition( int /* TechTypes */ eTech ) { if (m_pPlayer) { return m_pPlayer->getQueuePosition((TechTypes)eTech); } return -1; } void CyPlayer::clearResearchQueue() { if (m_pPlayer) m_pPlayer->clearResearchQueue(); } bool CyPlayer::pushResearch(int /*TechTypes*/ iIndex, bool bClear) { return m_pPlayer ? m_pPlayer->pushResearch((TechTypes)iIndex, bClear) : false; } void CyPlayer::popResearch(int /*TechTypes*/ eTech) { if (m_pPlayer) m_pPlayer->popResearch((TechTypes) eTech); } int CyPlayer::getLengthResearchQueue() { return m_pPlayer ? m_pPlayer->getLengthResearchQueue() : -1; } void CyPlayer::addCityName(std::wstring szName) { if (m_pPlayer) m_pPlayer->addCityName(szName); } int CyPlayer::getNumCityNames() { return m_pPlayer ? m_pPlayer->getNumCityNames() : -1; } std::wstring CyPlayer::getCityName(int iIndex) { return m_pPlayer ? m_pPlayer->getCityName(iIndex) : std::wstring(); } // returns tuple of (CyCity, iterOut) python::tuple CyPlayer::firstCity(bool bRev) { int iterIn = 0; CvCity* pvObj = m_pPlayer ? m_pPlayer->firstCity(&iterIn, bRev) : NULL; CyCity* pyObj = pvObj ? new CyCity(pvObj) : NULL; python::tuple tup=python::make_tuple(pyObj, iterIn); delete pyObj; return tup; } // returns tuple of (CyCity, iterOut) python::tuple CyPlayer::nextCity(int iterIn, bool bRev) { CvCity* pvObj = m_pPlayer ? m_pPlayer->nextCity(&iterIn, bRev) : NULL; CyCity* pyObj = pvObj ? new CyCity(pvObj) : NULL; python::tuple tup=python::make_tuple(pyObj, iterIn); delete pyObj; return tup; } int CyPlayer::getNumCities() { return m_pPlayer ? m_pPlayer->getNumCities() : -1; } CyCity* CyPlayer::getCity(int iID) { return m_pPlayer ? new CyCity(m_pPlayer->getCity(iID)) : NULL; } // returns tuple of (CyUnit, iterOut) python::tuple CyPlayer::firstUnit(bool bRev) { int iterIn = 0; CvUnit* pvUnit = m_pPlayer ? m_pPlayer->firstUnit(&iterIn, bRev) : NULL; CyUnit* pyUnit = pvUnit ? new CyUnit(pvUnit) : NULL; python::tuple tup=python::make_tuple(pyUnit, iterIn); delete pyUnit; return tup; } // returns tuple of (CyUnit, iterOut) python::tuple CyPlayer::nextUnit(int iterIn, bool bRev) { CvUnit* pvObj = m_pPlayer ? m_pPlayer->nextUnit(&iterIn, bRev) : NULL; CyUnit* pyObj = pvObj ? new CyUnit(pvObj) : NULL; python::tuple tup=python::make_tuple(pyObj, iterIn); delete pyObj; return tup; } int CyPlayer::getNumUnits() { return m_pPlayer ? m_pPlayer->getNumUnits() : -1; } CyUnit* CyPlayer::getUnit(int iID) { return m_pPlayer ? new CyUnit(m_pPlayer->getUnit(iID)) : NULL; } // returns tuple of (CySelectionGroup, iterOut) python::tuple CyPlayer::firstSelectionGroup(bool bRev) { int iterIn = 0; CvSelectionGroup* pvObj = m_pPlayer ? m_pPlayer->firstSelectionGroup(&iterIn, bRev) : NULL; CySelectionGroup* pyObj = pvObj ? new CySelectionGroup(pvObj) : NULL; python::tuple tup=python::make_tuple(pyObj, iterIn); delete pyObj; return tup; } // returns tuple of (CySelectionGroup, iterOut) python::tuple CyPlayer::nextSelectionGroup(int iterIn, bool bRev) { CvSelectionGroup* pvObj = m_pPlayer ? m_pPlayer->nextSelectionGroup(&iterIn, bRev) : NULL; CySelectionGroup* pyObj = pvObj ? new CySelectionGroup(pvObj) : NULL; python::tuple tup=python::make_tuple(pyObj, iterIn); delete pyObj; return tup; } int CyPlayer::getNumSelectionGroups() { return m_pPlayer ? m_pPlayer->getNumSelectionGroups() : -1; } CySelectionGroup* CyPlayer::getSelectionGroup(int iID) { return m_pPlayer ? new CySelectionGroup(m_pPlayer->getSelectionGroup(iID)) : NULL; } void CyPlayer::trigger(/*EventTriggerTypes*/int eEventTrigger) { if (m_pPlayer) { m_pPlayer->trigger((EventTriggerTypes)eEventTrigger); } } const EventTriggeredData* CyPlayer::getEventOccured(int /*EventTypes*/ eEvent) const { return m_pPlayer ? m_pPlayer->getEventOccured((EventTypes)eEvent) : NULL; } void CyPlayer::resetEventOccured(int /*EventTypes*/ eEvent) { if (m_pPlayer) { m_pPlayer->resetEventOccured((EventTypes)eEvent); } } EventTriggeredData* CyPlayer::getEventTriggered(int iID) const { return m_pPlayer ? m_pPlayer->getEventTriggered(iID) : NULL; } EventTriggeredData* CyPlayer::initTriggeredData(int /*EventTriggerTypes*/ eEventTrigger, bool bFire, int iCityId, int iPlotX, int iPlotY, int /*PlayerTypes*/ eOtherPlayer, int iOtherPlayerCityId, int /*ReligionTypes*/ eReligion, int /*CorporationTypes*/ eCorporation, int iUnitId, int /*BuildingTypes*/ eBuilding) { return m_pPlayer ? m_pPlayer->initTriggeredData((EventTriggerTypes)eEventTrigger, bFire, iCityId, iPlotX, iPlotY, (PlayerTypes)eOtherPlayer, iOtherPlayerCityId, (ReligionTypes)eReligion, (CorporationTypes)eCorporation, iUnitId, (BuildingTypes)eBuilding) : NULL; } int CyPlayer::getEventTriggerWeight(int /*EventTriggerTypes*/ eTrigger) { return m_pPlayer ? m_pPlayer->getEventTriggerWeight((EventTriggerTypes)eTrigger) : NULL; } void CyPlayer::AI_updateFoundValues(bool bStartingLoc) { if (m_pPlayer) m_pPlayer->AI_updateFoundValues(bStartingLoc); } int CyPlayer::AI_foundValue(int iX, int iY, int iMinUnitRange/* = -1*/, bool bStartingLoc/* = false*/) { return m_pPlayer ? m_pPlayer->AI_foundValue(iX, iY, iMinUnitRange, bStartingLoc) : -1; } bool CyPlayer::AI_isFinancialTrouble() { return m_pPlayer ? m_pPlayer->AI_isFinancialTrouble() : false; } bool CyPlayer::AI_demandRebukedWar(int /*PlayerTypes*/ ePlayer) { return m_pPlayer ? m_pPlayer->AI_demandRebukedWar((PlayerTypes)ePlayer) : false; } AttitudeTypes CyPlayer::AI_getAttitude(int /*PlayerTypes*/ ePlayer) { return m_pPlayer ? m_pPlayer->AI_getAttitude((PlayerTypes)ePlayer) : NO_ATTITUDE; } int CyPlayer::AI_unitValue(int /*UnitTypes*/ eUnit, int /*UnitAITypes*/ eUnitAI, CyArea* pArea) { return m_pPlayer ? m_pPlayer->AI_unitValue((UnitTypes)eUnit, (UnitAITypes)eUnitAI, pArea->getArea()) : -1; } int CyPlayer::AI_civicValue(int /*CivicTypes*/ eCivic) { return m_pPlayer ? m_pPlayer->AI_civicValue((CivicTypes)eCivic) : -1; } int CyPlayer::AI_totalUnitAIs(int /*UnitAITypes*/ eUnitAI) { return m_pPlayer ? m_pPlayer->AI_totalUnitAIs((UnitAITypes)eUnitAI) : -1; } int CyPlayer::AI_totalAreaUnitAIs(CyArea* pArea, int /*UnitAITypes*/ eUnitAI) { return m_pPlayer ? m_pPlayer->AI_totalAreaUnitAIs(pArea->getArea(), (UnitAITypes)eUnitAI) : -1; } int CyPlayer::AI_totalWaterAreaUnitAIs(CyArea* pArea, int /*UnitAITypes*/ eUnitAI) { return m_pPlayer ? m_pPlayer->AI_totalWaterAreaUnitAIs(pArea->getArea(), (UnitAITypes)eUnitAI) : -1; } int CyPlayer::AI_getNumAIUnits(int /*UnitAITypes*/ eIndex) { return m_pPlayer ? m_pPlayer->AI_getNumAIUnits((UnitAITypes)eIndex) : NO_UNITAI; } int CyPlayer::AI_getAttitudeExtra(int /*PlayerTypes*/ eIndex) { return m_pPlayer ? m_pPlayer->AI_getAttitudeExtra((PlayerTypes)eIndex) : -1; } void CyPlayer::AI_setAttitudeExtra(int /*PlayerTypes*/ eIndex, int iNewValue) { if (m_pPlayer) m_pPlayer->AI_setAttitudeExtra((PlayerTypes)eIndex, iNewValue); } void CyPlayer::AI_changeAttitudeExtra(int /*PlayerTypes*/ eIndex, int iChange) { if (m_pPlayer) m_pPlayer->AI_changeAttitudeExtra((PlayerTypes)eIndex, iChange); } int CyPlayer::AI_getMemoryCount(int /*PlayerTypes*/ eIndex1, int /*MemoryTypes*/ eIndex2) { return m_pPlayer ? m_pPlayer->AI_getMemoryCount((PlayerTypes)eIndex1, (MemoryTypes)eIndex2) : -1; } void CyPlayer::AI_changeMemoryCount(int /*PlayerTypes*/ eIndex1, int /*MemoryTypes*/ eIndex2, int iChange) { if (m_pPlayer) m_pPlayer->AI_changeMemoryCount((PlayerTypes)eIndex1, (MemoryTypes)eIndex2, iChange); } int CyPlayer::AI_getExtraGoldTarget() const { return m_pPlayer ? m_pPlayer->AI_getExtraGoldTarget() : -1; } void CyPlayer::AI_setExtraGoldTarget(int iNewValue) { if (m_pPlayer) { m_pPlayer->AI_setExtraGoldTarget(iNewValue); } } int CyPlayer::getScoreHistory(int iTurn) const { return (NULL != m_pPlayer ? m_pPlayer->getScoreHistory(iTurn) : 0); } int CyPlayer::getEconomyHistory(int iTurn) const { return (NULL != m_pPlayer ? m_pPlayer->getEconomyHistory(iTurn) : 0); } int CyPlayer::getIndustryHistory(int iTurn) const { return (NULL != m_pPlayer ? m_pPlayer->getIndustryHistory(iTurn) : 0); } int CyPlayer::getAgricultureHistory(int iTurn) const { return (NULL != m_pPlayer ? m_pPlayer->getAgricultureHistory(iTurn) : 0); } int CyPlayer::getPowerHistory(int iTurn) const { return (NULL != m_pPlayer ? m_pPlayer->getPowerHistory(iTurn) : 0); } int CyPlayer::getCultureHistory(int iTurn) const { return (NULL != m_pPlayer ? m_pPlayer->getCultureHistory(iTurn) : 0); } int CyPlayer::getEspionageHistory(int iTurn) const { return (NULL != m_pPlayer ? m_pPlayer->getEspionageHistory(iTurn) : 0); } std::string CyPlayer::getScriptData() const { return m_pPlayer ? m_pPlayer->getScriptData() : ""; } void CyPlayer::setScriptData(std::string szNewValue) { if (m_pPlayer) m_pPlayer->setScriptData(szNewValue); } void CyPlayer::chooseTech(int iDiscover, std::wstring szText, bool bFront) { if ( m_pPlayer ) { m_pPlayer->chooseTech(iDiscover, szText.c_str(), bFront); } } int CyPlayer::AI_maxGoldTrade(int iPlayer) { CvPlayerAI* pPlayer = dynamic_cast<CvPlayerAI*>(m_pPlayer); if (pPlayer) { return (pPlayer->AI_maxGoldTrade((PlayerTypes)iPlayer)); } return 0; } int CyPlayer::AI_maxGoldPerTurnTrade(int iPlayer) { CvPlayerAI* pPlayer = dynamic_cast<CvPlayerAI*>(m_pPlayer); if (pPlayer) { return (pPlayer->AI_maxGoldPerTurnTrade((PlayerTypes)iPlayer)); } return 0; } bool CyPlayer::splitEmpire(int iAreaId) { if (m_pPlayer) { return m_pPlayer->splitEmpire(iAreaId); } return false; } bool CyPlayer::canSplitEmpire() const { if (m_pPlayer) { return m_pPlayer->canSplitEmpire(); } return false; } bool CyPlayer::canSplitArea(int iAreaId) const { if (m_pPlayer) { return m_pPlayer->canSplitArea(iAreaId); } return false; } bool CyPlayer::canHaveTradeRoutesWith(int iPlayer) { return m_pPlayer ? m_pPlayer->canHaveTradeRoutesWith((PlayerTypes)iPlayer) : false; } void CyPlayer::forcePeace(int iPlayer) { if (m_pPlayer) m_pPlayer->forcePeace((PlayerTypes)iPlayer); } // Civ4 Reimagined int CyPlayer::getBuildingYieldChange(int /*BuildingClassTypes*/ eIndex1, int /*YieldTypes*/ eIndex2) const { FAssertMsg(eIndex1 >= 0, "eIndex1 is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex1 < GC.getNumBuildingClassInfos(), "eIndex1 is expected to be within maximum bounds (invalid Index)"); FAssertMsg(eIndex2 >= 0, "eIndex2 is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex2 < NUM_YIELD_TYPES, "eIndex2 is expected to be within maximum bounds (invalid Index)"); return m_pPlayer ? m_pPlayer->getBuildingYieldChange((BuildingClassTypes)eIndex1, (YieldTypes)eIndex2) : 0; }
[ "pierre@tupito.de" ]
pierre@tupito.de
d4a42fa5fb0c30fbae0b22f2c71628d6ab7b00ff
5d49a7a63fe13383911c64f26623038e4abcd0c2
/mapreduce-mapper.h
894785341fbdcae1c8a29d70142b39ee1a37916f
[]
no_license
sfgorky/Map-Reduce
b34049bf678799d345de8c838433d1cb9bb2f81a
0f33b2885fcdc002fc0ff043c49c85002c9812c0
refs/heads/master
2021-09-18T04:45:51.507696
2018-07-09T21:13:46
2018-07-09T21:13:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,364
h
/** * File: mapreduce-mapper.h * ------------------------ * Defines the interface for the MapReduceMapper class, * which knows how to configure itself (via its constructor) and * feed input files to the supplied executable. Input files received * from the map-reduce server should be .input files (that is, the file * extension is expected to be ".input"), and the output files are of * the form "<name>-00000.mapped", "<name>-00001.mapped","<name>-00002.mapped", * and so forth. The 00000, 00001, etc, are five-digit numbers ranging from * 0 up through but not including the split value. * * You'll need to extend the MapReduceMapper constructor to accept one more parameter * (the size_t split value), add state to the MapReduceMapper, and extend the implementation * of map to distribute the mapper executable's output across many, many files. * * See mapreduce-worker.h for more documentation on how the constructor * should behave. */ #pragma once #include "mapreduce-worker.h" class MapReduceMapper: protected MapReduceWorker { public: MapReduceMapper(const std::string& serverHost, unsigned short serverPort, const std::string& cwd, const std::string& executable, const std::string& outputPath, const size_t numHashCodes); void map() const; private: size_t nHashCodes; };
[ "melmuhta@gmail.com" ]
melmuhta@gmail.com
0d06efb22d1832b9e52fd5c0093a05efb83a806a
170ab6daedec4a8f107203b6eb5cd8bed1f4ed81
/Beginning-Algorithm-Contests-Rujia-Liu-Second-Edition/Chapter-6.Data-Structures/Examples/12-UVA 572 Oil Deposits.cpp
279379fdece906fa7058a70ec52958a37585c6d4
[]
no_license
sfailsthy/ACM-ICPC
4a15930c06c5ba35ca54a5ecb0acd7de63ebe7f7
7e32bfc49010c55d24b68c074c800a2d492abbfd
refs/heads/master
2021-01-11T06:07:58.598819
2017-01-18T13:04:23
2017-01-18T13:04:23
71,685,224
3
2
null
null
null
null
UTF-8
C++
false
false
955
cpp
//created by sfailsthy 2016/10/29 2:21 #include <iostream> #include<cstdio> #include<set> #include<queue> #include<vector> #include<cstring> using namespace std; typedef long long ll; const int maxn =100+10; char grid[maxn][maxn]; int m,n; int res; void dfs(int x,int y) { grid[x][y]='*'; for(int dr=-1;dr<=1;dr++){ for(int dc=-1;dc<=1;dc++){ int nx=x+dr,ny=y+dc; if(dr==0&&dc==0) continue; if(nx<0||nx>=m||ny<0||ny>=n) continue; if(grid[nx][ny]=='@'){ dfs(nx,ny); } } } } int main() { while(cin>>m>>n&&m&&n){ for(int i=0;i<m;i++){ scanf("%s",grid[i]); } res=0; for(int x=0;x<m;x++){ for(int y=0;y<n;y++){ if(grid[x][y]=='@'){ dfs(x,y); res++; } } } cout<<res<<endl; } return 0; }
[ "noreply@github.com" ]
sfailsthy.noreply@github.com
16e0d5029094b90ef481fbce50faa89e5ea480b9
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1485488_1/C++/xreborner/B.cpp
7541b58d8f6b0ed44a016aaf5e3cda62176f0442
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,550
cpp
#define _CRT_SECURE_NO_DEPRECATE #pragma warning(disable: 4018) #ifdef NDEBUG #define _SECURE_SCL 0 #endif #include <iostream> #include <memory> #include <vector> #include <algorithm> #include <string> #include <map> #include <set> #include <sstream> #include <utility> #include <functional> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <cassert> using namespace std; const int Inf = 999999999; const int XXs[4] = {0, 1, 0, -1}; const int YYs[4] = {1, 0, -1, 0}; struct item { int Time; int X, Y; item() {}; item(int Time, int X, int Y) : Time(Time), X(X), Y(Y) {} }; bool operator<(const item& A, const item& B) { return A.Time > B.Time; } int NN, TT; int N, M, InitLev; int Ceils[100][100], Floors[100][100]; int EnableTimes[100][100]; bool Marks[100][100]; int P[100][100]; vector<item> Queue; int main() { cin >> NN; for (TT = 1; TT <= NN; TT++) { cin >> InitLev >> N >> M; for (int X = 0; X < N; X++) for (int Y = 0; Y < M; Y++) cin >> Ceils[X][Y]; for (int X = 0; X < N; X++) for (int Y = 0; Y < M; Y++) cin >> Floors[X][Y]; for (int X = 0; X < N; X++) for (int Y = 0; Y < M; Y++) { if (Ceils[X][Y] - Floors[X][Y] < 50) EnableTimes[X][Y] = Inf; else if (Ceils[X][Y] - InitLev >= 50) EnableTimes[X][Y] = 0; else EnableTimes[X][Y] = (InitLev - (Ceils[X][Y] - 50)); } for (int X = 0; X < N; X++) for (int Y = 0; Y < M; Y++) P[X][Y] = Inf, Marks[X][Y] = false; P[0][0] = 0; Queue.clear(); Queue.push_back(item(0, 0, 0)); while (!Queue.empty()) { item Me = Queue[0]; pop_heap(Queue.begin(), Queue.end()); Queue.pop_back(); if (Marks[Me.X][Me.Y]) continue; Marks[Me.X][Me.Y] = true; for (int Dir = 0; Dir < 4; Dir++) { int X = Me.X + XXs[Dir]; int Y = Me.Y + YYs[Dir]; if (X < 0 || X >= N || Y < 0 || Y >= M) continue; if (Ceils[Me.X][Me.Y] - Floors[X][Y] < 50) continue; if (Ceils[X][Y] - Floors[Me.X][Me.Y] < 50) continue; if (Ceils[X][Y] - Floors[X][Y] < 50) continue; int Time = max(Me.Time, EnableTimes[X][Y]); if (Time >= Inf) continue; if (Time > 0) { if (InitLev - Time >= Floors[Me.X][Me.Y] + 20) Time += 10; else Time += 100; } if (Time < P[X][Y]) { P[X][Y] = Time; Queue.push_back(item(Time, X, Y)); push_heap(Queue.begin(), Queue.end()); } } } printf("Case #%d: %.1f\n", TT, (double)P[N - 1][M - 1] / 10); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
24799be3d8ce2a87bf314cc2f02039d37e40e6bb
7e3397302123a1b12d30250f837ed0d2b004962a
/milestone1/GameOfLifeCode/matrix.h
25b59c5b3f116144795b47d007b6660325d7b63c
[]
no_license
yuliahn/PRG_Praktikum
5f291739a82a082ca248d7015be4f6758dbe4e67
989c76325a56cd33d846a399f0e40425be7dc5a2
refs/heads/master
2020-04-04T19:12:51.313233
2019-01-29T20:07:25
2019-01-29T20:07:25
156,196,661
1
2
null
null
null
null
UTF-8
C++
false
false
837
h
#ifndef MATRIX_H #define MATRIX_H #include <cstdlib> #include <stdlib.h> #include <vector> #include <string> using namespace std; class matrix //creates the class matrix { public: typedef std::vector<double> Vector; public: size_t getRows() const; size_t getCols() const; double getElement(size_t, size_t) const; void createString(); matrix importData(string source); void exportData(string source); matrix evolution(); void setElement(size_t, size_t, double); matrix(); matrix(size_t, size_t); matrix(const matrix &); matrix(const char *); ~matrix() = default; private: std::vector<Vector> data; void initilizer(size_t, size_t); string str_matrix; protected: size_t rows; size_t cols; }; #endif // MATRIX_H
[ "noreply@github.com" ]
yuliahn.noreply@github.com
00d580ed13b9609a6e985f72f4b3b8730e0cf31e
942bfe7fbc326daa2f8a2701480758cee0854f5d
/Source/Wave/UI/HammerCountBarUI.cpp
538aeeae04d8369a7136980386df66a64f919265
[]
no_license
naryuu8/GameTaisyou2020
074930623a8b4367e4f40c8a64ec53b2f6ea117f
880ec8552bb3f3f39a293291628aaf4d5e3121fd
refs/heads/master
2023-01-31T11:08:03.539366
2020-06-14T14:30:46
2020-06-14T14:30:46
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
881
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "HammerCountBarUI.h" #define GAUGE_SPEED (0.03f)//ゲージ徐々に減らすスピード float UHammerCountBarUI::DownGauge(const float DamageX, const float HpX) { if (!IsDamageDown) {//ゲージが初めて下がる時の差分を得る NowHp = DamageX - HpX; IsDamageDown = true; } //1フレームで減らす量を計算 //今は割合だが固定値にすれば一定の速さになる float AddBar = NowHp * GAUGE_SPEED; return DamageX - AddBar; } float UHammerCountBarUI::DownGaugeTime(const float DamageX, const float HpX, const float Speed) { if (!IsDamageDown) {//ゲージが初めて下がる時の差分を得る NowHp = DamageX - HpX; IsDamageDown = true; } //1フレームで減らす量を計算 //float AddBar = NowHp * Speed; return DamageX - Speed; }
[ "orengi93@yahoo.co.jp" ]
orengi93@yahoo.co.jp
905696cc0b60d3e56ef883fdbd7903c947165ebe
563b013cfa9027136e2e1d0e3ac7c2879a04e2b2
/Common/Ccpp/Common.h
5c867a42cf248234afeb55eb8682a32c088cbca5
[]
no_license
aloe-all/NPP_HexEdit
8cb6263bb7fa00a70bdfc3781eefe8db80b39e96
edf1d755d790b31ffac781493d0001106b8e0b0b
refs/heads/master
2023-09-02T03:07:56.487088
2021-11-01T09:23:05
2021-11-01T09:23:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,467
h
// This file is part of Notepad++ project // Copyright (C)2021 Don HO <don.h@free.fr> // 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 <https://www.gnu.org/licenses/>. #pragma once #include <vector> #include <string> #include <sstream> #include <windows.h> #include <iso646.h> #include <cstdint> #include <unordered_set> #include <algorithm> const bool dirUp = true; const bool dirDown = false; #define NPP_CP_WIN_1252 1252 #define NPP_CP_DOS_437 437 #define NPP_CP_BIG5 950 #define LINKTRIGGERED WM_USER+555 #define BCKGRD_COLOR (RGB(255,102,102)) #define TXT_COLOR (RGB(255,255,255)) #define generic_strtol wcstol #define generic_strncpy wcsncpy #define generic_stricmp _wcsicmp //MODIFIED by HEXEDIT #define generic_strncmp wcsncmp #define generic_strnicmp wcsnicmp #define generic_strncat wcsncat #define generic_strchr wcschr #define generic_atoi _wtoi #define generic_itoa _itow #define generic_atof _wtof #define generic_strtok wcstok #define generic_strftime wcsftime #define generic_fprintf fwprintf #define generic_sprintf swprintf #define generic_sscanf swscanf #define generic_fopen _wfopen #define generic_fgets fgetws #define COPYDATA_FILENAMES COPYDATA_FILENAMESW #define NPP_INTERNAL_FUCTION_STR TEXT("Notepad++::InternalFunction") typedef std::basic_string<TCHAR> generic_string; typedef std::basic_stringstream<TCHAR> generic_stringstream; //NOT USED by HEXEDIT generic_string folderBrowser(HWND parent, const generic_string & title = TEXT(""), int outputCtrlID = 0, const TCHAR *defaultStr = NULL); //NOT USED by HEXEDIT generic_string getFolderName(HWND parent, const TCHAR *defaultDir = NULL); void printInt(int int2print); void printStr(const TCHAR *str2print); generic_string commafyInt(size_t n); void writeLog(const TCHAR *logFileName, const char *log2write); int filter(unsigned int code, struct _EXCEPTION_POINTERS *ep); generic_string purgeMenuItemString(const TCHAR * menuItemStr, bool keepAmpersand = false); std::vector<generic_string> tokenizeString(const generic_string & tokenString, const char delim); void ClientRectToScreenRect(HWND hWnd, RECT* rect); void ScreenRectToClientRect(HWND hWnd, RECT* rect); std::wstring string2wstring(const std::string & rString, UINT codepage); std::string wstring2string(const std::wstring & rwString, UINT codepage); bool isInList(const TCHAR *token, const TCHAR *list); generic_string BuildMenuFileName(int filenameLen, unsigned int pos, const generic_string &filename); std::string getFileContent(const TCHAR *file2read); generic_string relativeFilePathToFullFilePath(const TCHAR *relativeFilePath); void writeFileContent(const TCHAR *file2write, const char *content2write); bool matchInList(const TCHAR *fileName, const std::vector<generic_string> & patterns); bool allPatternsAreExclusion(const std::vector<generic_string> patterns); class WcharMbcsConvertor final { public: static WcharMbcsConvertor& getInstance() { static WcharMbcsConvertor instance; return instance; } const wchar_t * char2wchar(const char *mbStr, UINT codepage, int lenIn=-1, int *pLenOut=NULL, int *pBytesNotProcessed=NULL); const wchar_t * char2wchar(const char *mbcs2Convert, UINT codepage, int *mstart, int *mend); const char * wchar2char(const wchar_t *wcStr, UINT codepage, int lenIn = -1, int *pLenOut = NULL); const char * wchar2char(const wchar_t *wcStr, UINT codepage, long *mstart, long *mend); const char * encode(UINT fromCodepage, UINT toCodepage, const char *txt2Encode, int lenIn=-1, int *pLenOut=NULL, int *pBytesNotProcessed=NULL) { int lenWc = 0; const wchar_t * strW = char2wchar(txt2Encode, fromCodepage, lenIn, &lenWc, pBytesNotProcessed); return wchar2char(strW, toCodepage, lenWc, pLenOut); } protected: WcharMbcsConvertor() = default; ~WcharMbcsConvertor() = default; // Since there's no public ctor, we need to void the default assignment operator and copy ctor. // Since these are marked as deleted does not matter under which access specifier are kept WcharMbcsConvertor(const WcharMbcsConvertor&) = delete; WcharMbcsConvertor& operator= (const WcharMbcsConvertor&) = delete; // No move ctor and assignment WcharMbcsConvertor(WcharMbcsConvertor&&) = delete; WcharMbcsConvertor& operator= (WcharMbcsConvertor&&) = delete; template <class T> class StringBuffer final { public: ~StringBuffer() { if (_allocLen) delete[] _str; } void sizeTo(size_t size) { if (_allocLen < size) { if (_allocLen) delete[] _str; _allocLen = max(size, initSize); _str = new T[_allocLen]; } } void empty() { static T nullStr = 0; // routines may return an empty string, with null terminator, without allocating memory; a pointer to this null character will be returned in that case if (_allocLen == 0) _str = &nullStr; else _str[0] = 0; } operator T* () { return _str; } operator const T* () const { return _str; } protected: static const int initSize = 1024; size_t _allocLen = 0; T* _str = nullptr; }; StringBuffer<char> _multiByteStr; StringBuffer<wchar_t> _wideCharStr; }; #define MACRO_RECORDING_IN_PROGRESS 1 #define MACRO_RECORDING_HAS_STOPPED 2 #define REBARBAND_SIZE sizeof(REBARBANDINFO) generic_string PathRemoveFileSpec(generic_string & path); generic_string PathAppend(generic_string &strDest, const generic_string & str2append); COLORREF getCtrlBgColor(HWND hWnd); generic_string stringToUpper(generic_string strToConvert); generic_string stringToLower(generic_string strToConvert); generic_string stringReplace(generic_string subject, const generic_string& search, const generic_string& replace); std::vector<generic_string> stringSplit(const generic_string& input, const generic_string& delimiter); bool str2numberVector(generic_string str2convert, std::vector<size_t>& numVect); generic_string stringJoin(const std::vector<generic_string>& strings, const generic_string& separator); generic_string stringTakeWhileAdmissable(const generic_string& input, const generic_string& admissable); double stodLocale(const generic_string& str, _locale_t loc, size_t* idx = NULL); int OrdinalIgnoreCaseCompareStrings(LPCTSTR sz1, LPCTSTR sz2); bool str2Clipboard(const generic_string &str2cpy, HWND hwnd); generic_string GetLastErrorAsString(DWORD errorCode = 0); generic_string intToString(int val); generic_string uintToString(unsigned int val); HWND CreateToolTip(int toolID, HWND hDlg, HINSTANCE hInst, const PTSTR pszText, bool isRTL); HWND CreateToolTipRect(int toolID, HWND hWnd, HINSTANCE hInst, const PTSTR pszText, const RECT rc); //NOT USED by HEXEDIT bool isCertificateValidated(const generic_string & fullFilePath, const generic_string & subjectName2check); bool isAssoCommandExisting(LPCTSTR FullPathName); std::wstring s2ws(const std::string& str); std::string ws2s(const std::wstring& wstr); bool deleteFileOrFolder(const generic_string& f2delete); void getFilesInFolder(std::vector<generic_string>& files, const generic_string& extTypeFilter, const generic_string& inFolder); template<typename T> size_t vecRemoveDuplicates(std::vector<T>& vec, bool isSorted = false, bool canSort = false) { if (!isSorted && canSort) { std::sort(vec.begin(), vec.end()); isSorted = true; } if (isSorted) { typename std::vector<T>::iterator it; it = std::unique(vec.begin(), vec.end()); vec.resize(distance(vec.begin(), it)); // unique() does not shrink the vector } else { std::unordered_set<T> seen; auto newEnd = std::remove_if(vec.begin(), vec.end(), [&seen](const T& value) { return !seen.insert(value).second; }); vec.erase(newEnd, vec.end()); } return vec.size(); } void trim(generic_string& str); bool endsWith(const generic_string& s, const generic_string& suffix); int nbDigitsFromNbLines(size_t nbLines); generic_string getDateTimeStrFrom(const generic_string& dateTimeFormat, const SYSTEMTIME& st);
[ "christian.grasser@live.de" ]
christian.grasser@live.de
771a47c8ac7af2eb4ca5b159995adda7c8a43ef5
f556d0c63551f3e3cd138f01b081dfd299c57225
/IPlugExamples/filtertest/LinkwitzRiley.h
051cb084457aa650a63cd5098524ad907fafa8c9
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive" ]
permissive
michaeldonovan/wdl-md
78e0a2f59b32e8b0d7547bec7ca5815e5893a16c
2148c1ef7a327dabcf9c6281c3bb425e0e064503
refs/heads/master
2021-01-15T16:14:47.438742
2016-04-20T00:01:00
2016-04-20T00:01:00
49,093,121
1
0
null
null
null
null
UTF-8
C++
false
false
2,334
h
// // LinkwitzRiley.h // MultibandDistortion // // Created by Michael on 3/9/16. // Original from T. Lossius - ttblue project // #ifndef LinkwitzRiley_h #define LinkwitzRiley_h enum FilterType { Lowpass = 0, Highpass, }; class LinkwitzRiley{ public: LinkwitzRiley(float sampleRate, const int& type, double cutoffFreq){ sr = sampleRate; filterType = type; fc = cutoffFreq; for (int i=0; i<4; i++) { buffX[i]=0; buffY[i]=0; } calcFilter(); }; // Process sample of audio double process(double sample){ double tempx = sample; double tempy = a0*tempx+a1*buffX[0]+a2*buffX[1]+a3*buffX[2]+a4*buffX[3]-b1*buffY[0]-b2*buffY[1]-b3*buffY[2]-b4*buffY[3]; buffX[3]=buffX[2]; buffX[2]=buffX[1]; buffX[1]=buffX[0]; buffX[0]=tempx; buffY[3]=buffY[2]; buffY[2]=buffY[1]; buffY[1]=buffY[0]; buffY[0]=tempy; return tempy; } // Set cutoff frequency (Hz) void setCutoff(double freq){ fc = freq; calcFilter(); } private: void calcFilter(){ double wc, wc2, wc3, wc4, k, k2, k3, k4, sqrt2, sq_tmp1, sq_tmp2, a_tmp; wc=2*pi*fc; wc2=wc*wc; wc3=wc2*wc; wc4=wc2*wc2; k=wc/tan(pi*fc/sr); k2=k*k; k3=k2*k; k4=k2*k2; sqrt2=sqrt(2); sq_tmp1=sqrt2*wc3*k; sq_tmp2=sqrt2*wc*k3; a_tmp=4*wc2*k2+2*sq_tmp1+k4+2*sq_tmp2+wc4; b1=(4*(wc4+sq_tmp1-k4-sq_tmp2))/a_tmp; b2=(6*wc4-8*wc2*k2+6*k4)/a_tmp; b3=(4*(wc4-sq_tmp1+sq_tmp2-k4))/a_tmp; b4=(k4-2*sq_tmp1+wc4-2*sq_tmp2+4*wc2*k2)/a_tmp; if (filterType==Lowpass) { a0=wc4/a_tmp; a1=4*wc4/a_tmp; a2=6*wc4/a_tmp; a3=a1; a4=a0; } else{ a0=k4/a_tmp; a1=-4*k4/a_tmp; a2=6*k4/a_tmp; a3=a1; a4=a0; } }; // Params int filterType; double fc; double sr; // Coefficients double a0, a1, a2, a3, a4, b1, b2, b3, b4; // Buffer double buffX[4]; double buffY[4]; }; #endif /* LinkwitzRiley_h */
[ "michael.donovan.audio@gmail.com" ]
michael.donovan.audio@gmail.com
1bd175b6f12add3061ac5fbd54d99dbd4409cc28
3603495adfdc6b76236d6e3eb6f1ecf3f70835f8
/Automatic_infantry_robot/ROS_original_notes/catkin_ws/src/robot_bringup/include/robot_bringup/robot.h
8a9e6f0902250af6dd7c5f380baf28e30dba81b7
[]
no_license
wf-hahaha/Robomaster-skyteam
a1e70eaa8e31fc5481858173f4f208f2535b56da
0a82bbfc0da3ad3b5fe3dcb8ed83d7e6adfdb312
refs/heads/main
2023-05-06T17:47:09.452301
2021-04-19T12:14:20
2021-04-19T12:14:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
h
#ifndef __ROBOT_H__ #define __ROBOT_H__ #include <ros/ros.h> #include <ros/time.h> #include <geometry_msgs/TransformStamped.h> #include <tf/transform_broadcaster.h> #include <nav_msgs/Odometry.h> #include <boost/asio.hpp> #include <geometry_msgs/Twist.h> namespace robot { class robot { public: robot(); ~robot(); bool init(); bool deal(double RobotV, double RobotYawRate); private: void calcOdom(); //里程计计算 void pubOdomAndTf(); //发布Odom和tf private: ros::Time current_time_, last_time_; //时间 double x_; //机器人位姿 double y_; double th_; double vx_; //机器人x方向速度 double vy_; //机器人y方向速度 double vth_; //机器人角速度 unsigned char sensFlag_; //通信预留发送和接收标志位,可进行信号控制使用 unsigned char receFlag_; ros::NodeHandle nh; ros::Publisher pub_; tf::TransformBroadcaster odom_broadcaster_; }; } #endif
[ "noreply@github.com" ]
wf-hahaha.noreply@github.com
5fcdc97c637a66f03bd5df745cb2df9f11c51c9d
e1656b466e2c23bfa83a07c122543498112e7045
/main.cpp
25fdd2f72603fe08182a87a8342f26e76a3af0cb
[]
no_license
blueshen111/connect_four
5b89136054f6993f4e98aa30634c543f47ef9469
7da3308e501ffb940c064643fb219255c3108621
refs/heads/master
2020-07-25T17:03:17.096166
2019-09-13T23:52:44
2019-09-13T23:52:44
208,364,436
0
0
null
null
null
null
UTF-8
C++
false
false
5,717
cpp
// Jordan Steer-Furderer // CIS 25 // CONNECT FOUR #include <iostream> using namespace std; int main() { int columnChoice; 0 <= columnChoice <= 6; char x; char o; cout << "Welcome to Connect Four" << endl; cout << "=============" << endl; char board[6][7] = { {'-', '-', '-', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-'}, {'-', '-', '-', '-', '-', '-', '-'}, }; ////THIS IS THE GAME BOARD//// for (int r = 0; r < 6; r++){ for (int c = 0; c < 7; c++){ cout << board[r][c] << " "; } cout << endl; } cout << "=============" << endl; ////////////////////////////// int index = 0; while (index < 21) { //int index = 0; //while(index <= 0) { cout << "Player 1 pick column 0 - 6" << endl; cin >> columnChoice; if (board[5][columnChoice] != 'x' && board[5][columnChoice] != 'o'){ (board[5][columnChoice] = 'x');} else { if (board[4][columnChoice] != 'x' && board[4][columnChoice] != 'o'){ (board[4][columnChoice] = 'x'); } else {if (board[3][columnChoice] != 'x' && board[3][columnChoice] != 'o'){ (board[3][columnChoice] = 'x'); } else {if (board[2][columnChoice] != 'x' && board[2][columnChoice] != 'o'){ (board[2][columnChoice] = 'x'); } else {if (board[1][columnChoice] != 'x' && board[1][columnChoice] != 'o'){ (board[1][columnChoice] = 'x'); } else {if (board[0][columnChoice] != 'x' && board[0][columnChoice] != 'o'){ (board[0][columnChoice] = 'x'); } else {if (board[0][columnChoice] != '-'){ cout << "Try again"<< endl; cout << "Player 1 pick column 0 - 6" << endl; cin >> columnChoice; if (board[5][columnChoice] != 'x' && board[5][columnChoice] != 'o'){ (board[5][columnChoice] = 'x');} else { if (board[4][columnChoice] != 'x' && board[4][columnChoice] != 'o'){ (board[4][columnChoice] = 'x'); } else {if (board[3][columnChoice] != 'x' && board[3][columnChoice] != 'o'){ (board[3][columnChoice] = 'x'); } else {if (board[2][columnChoice] != 'x' && board[2][columnChoice] != 'o'){ (board[2][columnChoice] = 'x'); } else {if (board[1][columnChoice] != 'x' && board[1][columnChoice] != 'o'){ (board[1][columnChoice] = 'x'); } else {if (board[0][columnChoice] != 'x' && board[0][columnChoice] != 'o'){ (board[0][columnChoice] = 'x'); } } } } } } } } } } } } } cout << "=============" << endl; for (int r = 0; r < 6; r++){ for (int c = 0; c < 7; c++){ cout << board[r][c] << " "; } cout << endl; } cout << "=============" << endl; cout << "Player 2 pick column 0 - 6" << endl; cin >> columnChoice; if (board[5][columnChoice] != 'x' && board[5][columnChoice] != 'o'){ (board[5][columnChoice] = 'o');} else { if (board[4][columnChoice] != 'x' && board[4][columnChoice] != 'o'){ (board[4][columnChoice] = 'o'); } else {if (board[3][columnChoice] != 'x' && board[3][columnChoice] != 'o'){ (board[3][columnChoice] = 'o'); } else {if (board[2][columnChoice] != 'x' && board[2][columnChoice] != 'o'){ (board[2][columnChoice] = 'o'); } else {if (board[1][columnChoice] != 'x' && board[1][columnChoice] != 'o'){ (board[1][columnChoice] = 'o'); } else {if (board[0][columnChoice] != 'x' && board[0][columnChoice] != 'o'){ (board[0][columnChoice] = 'o'); } else {if (board[0][columnChoice] != 'x'){ cout << "Try again" << endl; cout << "Player 2 pick column 0 - 6" << endl; cin >> columnChoice; if (board[5][columnChoice] != 'x' && board[5][columnChoice] != 'o'){ (board[5][columnChoice] = 'o');} else { if (board[4][columnChoice] != 'x' && board[4][columnChoice] != 'o'){ (board[4][columnChoice] = 'o'); } else {if (board[3][columnChoice] != 'x' && board[3][columnChoice] != 'o'){ (board[3][columnChoice] = 'o'); } else {if (board[2][columnChoice] != 'x' && board[2][columnChoice] != 'o'){ (board[2][columnChoice] = 'o'); } else {if (board[1][columnChoice] != 'x' && board[1][columnChoice] != 'o'){ (board[1][columnChoice] = 'o'); } else {if (board[0][columnChoice] != 'x' && board[0][columnChoice] != 'o'){ (board[0][columnChoice] = 'o'); } } } } } } } } } } } } } cout << "=============" << endl; for (int r = 0; r < 6; r++){ for (int c = 0; c < 7; c++){ cout << board[r][c] << " "; } cout << endl; } cout << "=============" << endl; // index++; //} index++; } cout << "BOARD FULL" << endl; return 0; }
[ "noreply@github.com" ]
blueshen111.noreply@github.com
528710aec7b101e17daa85088ea4027250982a0e
76261a91107cdacb6046c1fdc106ffcb4368ad92
/DragonBones/DragonBonesExample/DragonBones/objects/SkeletonData.h
581763e1d4b9245fdddf7a662d5a79cffdabd421
[]
no_license
KingNormac/CPlusPlus-Opengl-Dragonbones
f33c903682efd43497bca78c1548f4baa19f4534
305a11d68143ac9d15ddd9a0c767a3b00439e120
refs/heads/master
2020-04-10T07:56:08.589533
2013-08-10T18:39:53
2013-08-10T18:39:53
12,017,983
4
2
null
null
null
null
UTF-8
C++
false
false
911
h
#ifndef SKELETONDATA_H #define SKELETONDATA_H #include "ArmatureData.h" #include <string> #include <vector> #include <map> #include "../as3/Vector2D.h" namespace DragonBones { class SkeletonData { private: std::map<std::string, Vector2D*> _subTexturePivots; std::vector<ArmatureData*> _armatureDataList; public: std::string name; std::vector<std::string> getArmatureNames(); std::vector<ArmatureData*> getArmatureDataList(); SkeletonData(); ~SkeletonData(); ArmatureData* getArmatureData(std::string armatureName); void addArmatureData(ArmatureData* armatureData); void removeArmatureData(ArmatureData* armatureData); void removeArmatureDataByName(std::string armatureName); Vector2D* getSubTexturePivot(std::string subTextureName); Vector2D* addSubTexturePivot(float x, float y, std::string name); void removeSubTexturePivot(std::string subTextureName); }; }; #endif
[ "thedreamteamorganization@gmail.com" ]
thedreamteamorganization@gmail.com
c44d259fa285d95aa20f441dafc997b46e802257
84a9cf5fd65066cd6c32b4fc885925985231ecde
/Plugins2/ElementalEngine/LightMapObject/PhotonMap.h
b9395a5f584497b4c526251109f58a95734049e9
[]
no_license
acemon33/ElementalEngine2
f3239a608e8eb3f0ffb53a74a33fa5e2a38e4891
e30d691ed95e3811c68e748c703734688a801891
refs/heads/master
2020-09-22T06:17:42.037960
2013-02-11T21:08:07
2013-02-11T21:08:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,595
h
///============================================================================ /// \note Elemental Engine /// Copyright (c) 2005-2008 Signature Devices, Inc. /// /// This code is redistributable under the terms of the EE License. /// /// This code is distributed without warranty or implied warranty of /// merchantability or fitness for a particular purpose. See the /// EE License for more details. /// /// You should have received a copy of the EE License along with this /// code; If not, write to Signature Devices, Inc., /// 3200 Bridge Parkway Suite 102, Redwood City, CA 94086 USA. ///============================================================================ #ifndef PHOTONMAP_H #define PHOTONMAP_H // Macros to pack/unpack directions #define dirToPhoton(theta__,phi__,D__) { \ int t__,p__; \ t__ = (int) (acos(D__.z)*(256.0 / PI)); \ p__ = (int) (atan2(D__.y,D__.x)*(256.0 / (2.0*PI))); \ if (t__ > 255) \ theta__ = (unsigned char) 255; \ else \ theta__ = (unsigned char) t__; \ \ if (p__ > 255) \ phi__ = (unsigned char) 255; \ else if (p__ < 0) \ phi__ = (unsigned char) (p__ + 256); \ else \ phi__ = (unsigned char) p__; \ } #define photonToDir(D__,theta__,phi__) { \ D__.x = sintheta[theta__]*cosphi[phi__]; \ D__.y = sintheta[theta__]*sinphi[phi__]; \ D__.z = costheta[theta__]; \ } // Debug and build options //#define PHOTON_DEBUG //#define PHOTON_LOOKUP_CACHE /////////////////////////////////////////////////////////////////////// // Class : CPhoton // Description : A Photon // Comments : class CPhoton : public CTon { public: Vec3 C; // The intensity unsigned char theta,phi; // Photon direction }; /////////////////////////////////////////////////////////////////////// // Class : CPhotonRay // Description : A Photon // Comments : class CPhotonRay { public: CPhotonRay( Ray &ray ) { m_Ray = ray; } Ray m_Ray; Vec3 intensity; // The intensity float factor; // The product of all the factors (used for routian roulette) }; /////////////////////////////////////////////////////////////////////// // Class : CPhotonMap // Description : A Photon map // Comments : class CPhotonMap : public CMap<CPhoton> { #ifdef PHOTON_LOOKUP_CACHE class CPhotonSample { public: Vec3 C,P,N; float dP; CPhotonSample *next; }; class CPhotonNode { public: Vec3 center; float side; CPhotonSample *samples; CPhotonNode *children[8]; }; #endif public: CPhotonMap(); ~CPhotonMap(); void attach() { refCount++; } void detach() { refCount--; if (refCount == 0) delete this; } void check() { if (refCount == 0) delete this; } void reset(); void lookup(Vec3 &,const Vec3 &,int); void lookup(Vec3 &,const Vec3 &,const Vec3 &,int); void balance(); void store(const Vec3 &,const Vec3 &,const Vec3 &,const Vec3 &); void bound(Vec3 &bmin,Vec3 &bmax); #ifdef PHOTON_LOOKUP_CACHE int probe(Vec3 &,const Vec3 &,const Vec3 &); void insert(const Vec3 &,const Vec3 &,const Vec3 &,float); CPhotonNode *root; int maxDepth; // The maximum depth of the hierarchy #endif int refCount; int modifying; Matrix4x4 from,to; float maxPower; // The maximum photon power float searchRadius; }; #endif // PHOTONMAP_H
[ "klhurley@yahoo.com" ]
klhurley@yahoo.com
99a1788b62cff717a1ad975a215cc2c4ee2bc7aa
e7dcf1b8325270e9ca908723a86e417e40d75614
/chapter2/소스37.cpp
f97b8954e5103198345ecb90e16d51108ff9758e
[]
no_license
jojarim/cprog
73f7b4ca733293b32baee3dcee982c2132e36521
f3d1f9447919003a0a4550f244c65a297a48770a
refs/heads/master
2020-07-28T16:50:48.407148
2019-12-12T05:15:13
2019-12-12T05:15:13
209,471,178
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
211
cpp
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { int a = 10; int *p = &a; int b = *p; *p = 20; int **pp = &p; int c = **pp; **pp = 30; printf("%dÀÌ´Ù", a); return 0; }
[ "whwo2142@naver.com" ]
whwo2142@naver.com
35793a6075f9168ae11ef40c90daa8e61dae9557
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_3288_httpd-2.2.34.cpp
e1542935750a5753e96b65d55e72e75da96158d5
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
121
cpp
static int PTRCALL big2_charMatches(const ENCODING *enc, const char *p, int c) { return BIG2_CHAR_MATCHES(enc, p, c); }
[ "993273596@qq.com" ]
993273596@qq.com
c9464dcf08ea2bb98fd7e7465ada19ee4ad4cc9e
13c599a48f0b596c314c7c570f47756fd97a2b92
/device/geolocation/geolocation_service_context.cc
ffd69ff01be24ab609b9777b35bb47fe4bae89a2
[ "BSD-3-Clause" ]
permissive
qichanna/chromium
a5e3d44bda4bd6511e090e25263f5de94dbfe492
458d956db161377610486b7c82a95fc485f60b9b
refs/heads/master
2022-11-13T00:50:48.147260
2016-08-01T23:23:16
2016-08-01T23:28:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,790
cc
// 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. #include "device/geolocation/geolocation_service_context.h" #include <utility> #include "device/geolocation/geolocation_service_impl.h" namespace device { GeolocationServiceContext::GeolocationServiceContext() : paused_(false) {} GeolocationServiceContext::~GeolocationServiceContext() {} void GeolocationServiceContext::CreateService( const base::Closure& update_callback, mojo::InterfaceRequest<blink::mojom::GeolocationService> request) { GeolocationServiceImpl* service = new GeolocationServiceImpl(std::move(request), this, update_callback); services_.push_back(service); if (geoposition_override_) service->SetOverride(*geoposition_override_.get()); else service->StartListeningForUpdates(); } void GeolocationServiceContext::ServiceHadConnectionError( GeolocationServiceImpl* service) { auto it = std::find(services_.begin(), services_.end(), service); DCHECK(it != services_.end()); services_.erase(it); } void GeolocationServiceContext::PauseUpdates() { paused_ = true; for (auto* service : services_) { service->PauseUpdates(); } } void GeolocationServiceContext::ResumeUpdates() { paused_ = false; for (auto* service : services_) { service->ResumeUpdates(); } } void GeolocationServiceContext::SetOverride( std::unique_ptr<Geoposition> geoposition) { geoposition_override_.swap(geoposition); for (auto* service : services_) { service->SetOverride(*geoposition_override_.get()); } } void GeolocationServiceContext::ClearOverride() { for (auto* service : services_) { service->ClearOverride(); } } } // namespace device
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f60a861644cbbd5ac09e0febd4db3cad5e6df811
c11f601574b36c77674a6aecbe64fca6333ef2f8
/MT/MT_Robot/robot/SteeredRobot.h
dcf3b3850ff4dea0831144eecb23369196ddad8b
[ "MIT" ]
permissive
leonard-lab/MADTraC
736afe84c51993d21864669aa4d9a42a3f76c723
f1830c377a075aa5ddff9342c4851d0715cdd6a4
refs/heads/master
2020-05-19T17:39:43.278238
2013-02-17T01:05:05
2013-02-17T01:05:05
3,463,121
5
1
null
null
null
null
UTF-8
C++
false
false
4,151
h
#ifndef STEEREDROBOT_H #define STEEREDROBOT_H /************************************************************ * SteeredRobot.h * * Defines the MT_SteeredRobot class. This is a MT_MiaBotPro with * only speed and turning rate controls (not direct wheel * rate controls). This should suffice as a basic class * to use for most MT_MiaBotPro applications while still guarding * the low-level functionality of MT_MiaBotPro. * * - Modified from FishBot.h DTS 8/10/09 * ************************************************************/ // Inherits from the (more basic) MT_MiaBotPro class. #include "MiaBotPro.h" #include "RobotBase.h" // Default length of the buffers static const int MT_DEFAULT_TAIL_LENGTH_ROBOT = 500; // Header for the MT_R3 class #include "MT/MT_Core/primitives/R3.h" // Header for the MT_ringbuffer class #include "MT/MT_Core/primitives/ringbuffer.h" const double SR_DEFAULT_MAX_SPEED = 0.35; // speeds in meters/sec const double SR_DEFAULT_MAX_TURNING_RATE = 8.0; // turning rates in rad/sec (based on 7 cm wheelbase) const double SR_MAX_ALLOWED_SPEED = 4.0; // max rates: see DTS notebook #2, 1/2-1/5 2009 const double SR_MAX_ALLOWED_TURNING_RATE = 114.3; const double SR_DEFAULT_DEADBAND = 0.05; class MT_SteeredRobot : public MT_MiaBotPro, public MT_RobotBase { protected: MT_R3 position; float theta; void init_buffers(const int length); MT_ringbuffer<float>* xbuffer; MT_ringbuffer<float>* ybuffer; //! scaling factor: [world meters] = world_scale*[internal units] double world_scale; //! comega: control omega double comega; double cdtheta; //! cspeed: control speed double cspeed; unsigned char Autonomous; double m_dMaxTurningRate; double m_dMaxSpeed; double m_dSpeedDeadBand; double m_dTurningRateDeadBand; void init(); public: // NOTE: there is no MT_SteeredRobot(comport, speed, omega) constructor // as this seems like a bad idea (wait for the program to // be in control of things to start the robot moving) //! default constructor (use stdout) MT_SteeredRobot(); //! constructor to specify com port MT_SteeredRobot(const char* onComPort, const char* name); //! constructor to specify com port and scaling factor MT_SteeredRobot(const char* onComPort, double inscale, const char* name); // dtor virtual ~MT_SteeredRobot(); // function to display the name of this robot (and its port) void spitup(const char* name) const; //! Set kinematic speed void SetSpeed(double inspd); //! Set kinematic turning rate void SetOmega(double inomega); //! Set kinematic speed and turning rate void SetSpeedOmega(double inspd, double inomega); // flag autonomous mode on void SetAutonomousOn(){ Autonomous = 1; }; // flag autonomous mode off void SetAutonomousOff(){ Autonomous = 0; }; void Go(); //! Provide access to the go command void Pause(); //! Provide access to the pause command //! Do a donut and wow the audience :) void Donut(double spd, double radius); // functions to get counter values void QueryCounters(); void QueryCounters(int* Left, int* Right); // accessor functions double GetX() const; double GetY() const; double GetTheta() const; // Safe functions we can pass-through to MiaBot (or MT_ComIO) virtual const char* getComPort() const {return MT_MiaBotPro::getComPort();}; virtual unsigned char IsConnected() const { return MT_MiaBotPro::IsConnected(); }; //! Calculation of Control virtual void Update(){ Control(); }; virtual void Update(float inx, float iny, float intheta); void Update(std::vector<double> state){Update(state[0], state[1], state[2]);}; //! Apply Control virtual void Control(); void SafeStop(){SetSpeedOmega(0,0);}; void AutoIDResponse(){SetSpeedOmega(0.1, 0);}; void JoyStickControl(std::vector<double> js_axes, unsigned int js_buttons); }; #endif // STEEREDROBOT_H
[ "dan.t.swain@gmail.com" ]
dan.t.swain@gmail.com
25b6cb76f1d3a71f993a5b53f089a41af22fb16f
b42facd15642a20b40ea668e36201784a2995a7d
/src/stan_files/AugBin2T1A.hpp
60064694da5456f391e9ccf90581578cf5a6d575
[]
no_license
studentmicky/trialr
3e7cb46e690387c2c7462a5bde27e43599b617e9
83dad6f5c255d7f66a5bf87512e212e57c0feb8a
refs/heads/master
2020-12-10T02:41:30.710821
2019-06-25T16:27:04
2019-06-25T16:27:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
49,347
hpp
/* trialr 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. trialr 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 trialr. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MODELS_HPP #define MODELS_HPP #define STAN__SERVICES__COMMAND_HPP #include <rstan/rstaninc.hpp> // Code generated by Stan version 2.18.0 #include <stan/model/model_header.hpp> namespace model_AugBin2T1A_namespace { using std::istream; using std::string; using std::stringstream; using std::vector; using stan::io::dump; using stan::math::lgamma; using stan::model::prob_grad; using namespace stan::math; static int current_statement_begin__; stan::io::program_reader prog_reader__() { stan::io::program_reader reader; reader.add_event(0, 0, "start", "model_AugBin2T1A"); reader.add_event(104, 102, "end", "model_AugBin2T1A"); return reader; } #include <meta_header.hpp> class model_AugBin2T1A : public prob_grad { private: int N; vector_d z0; vector_d z1; vector_d z2; vector<int> d1; vector<int> d2; double alpha_mean; double alpha_sd; double beta_mean; double beta_sd; double gamma_mean; double gamma_sd; double sigma_mean; double sigma_sd; double omega_lkj_eta; double alpha_d1_mean; double alpha_d1_sd; double gamma_d1_mean; double gamma_d1_sd; double alpha_d2_mean; double alpha_d2_sd; double gamma_d2_mean; double gamma_d2_sd; vector<vector_d> y; public: model_AugBin2T1A(stan::io::var_context& context__, std::ostream* pstream__ = 0) : prob_grad(0) { ctor_body(context__, 0, pstream__); } model_AugBin2T1A(stan::io::var_context& context__, unsigned int random_seed__, std::ostream* pstream__ = 0) : prob_grad(0) { ctor_body(context__, random_seed__, pstream__); } void ctor_body(stan::io::var_context& context__, unsigned int random_seed__, std::ostream* pstream__) { typedef double local_scalar_t__; boost::ecuyer1988 base_rng__ = stan::services::util::create_rng(random_seed__, 0); (void) base_rng__; // suppress unused var warning current_statement_begin__ = -1; static const char* function__ = "model_AugBin2T1A_namespace::model_AugBin2T1A"; (void) function__; // dummy to suppress unused var warning size_t pos__; (void) pos__; // dummy to suppress unused var warning std::vector<int> vals_i__; std::vector<double> vals_r__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning // initialize member variables try { current_statement_begin__ = 3; context__.validate_dims("data initialization", "N", "int", context__.to_vec()); N = int(0); vals_i__ = context__.vals_i("N"); pos__ = 0; N = vals_i__[pos__++]; current_statement_begin__ = 5; validate_non_negative_index("z0", "N", N); context__.validate_dims("data initialization", "z0", "vector_d", context__.to_vec(N)); validate_non_negative_index("z0", "N", N); z0 = vector_d(static_cast<Eigen::VectorXd::Index>(N)); vals_r__ = context__.vals_r("z0"); pos__ = 0; size_t z0_i_vec_lim__ = N; for (size_t i_vec__ = 0; i_vec__ < z0_i_vec_lim__; ++i_vec__) { z0[i_vec__] = vals_r__[pos__++]; } current_statement_begin__ = 6; validate_non_negative_index("z1", "N", N); context__.validate_dims("data initialization", "z1", "vector_d", context__.to_vec(N)); validate_non_negative_index("z1", "N", N); z1 = vector_d(static_cast<Eigen::VectorXd::Index>(N)); vals_r__ = context__.vals_r("z1"); pos__ = 0; size_t z1_i_vec_lim__ = N; for (size_t i_vec__ = 0; i_vec__ < z1_i_vec_lim__; ++i_vec__) { z1[i_vec__] = vals_r__[pos__++]; } current_statement_begin__ = 7; validate_non_negative_index("z2", "N", N); context__.validate_dims("data initialization", "z2", "vector_d", context__.to_vec(N)); validate_non_negative_index("z2", "N", N); z2 = vector_d(static_cast<Eigen::VectorXd::Index>(N)); vals_r__ = context__.vals_r("z2"); pos__ = 0; size_t z2_i_vec_lim__ = N; for (size_t i_vec__ = 0; i_vec__ < z2_i_vec_lim__; ++i_vec__) { z2[i_vec__] = vals_r__[pos__++]; } current_statement_begin__ = 9; validate_non_negative_index("d1", "N", N); context__.validate_dims("data initialization", "d1", "int", context__.to_vec(N)); validate_non_negative_index("d1", "N", N); d1 = std::vector<int>(N,int(0)); vals_i__ = context__.vals_i("d1"); pos__ = 0; size_t d1_limit_0__ = N; for (size_t i_0__ = 0; i_0__ < d1_limit_0__; ++i_0__) { d1[i_0__] = vals_i__[pos__++]; } current_statement_begin__ = 10; validate_non_negative_index("d2", "N", N); context__.validate_dims("data initialization", "d2", "int", context__.to_vec(N)); validate_non_negative_index("d2", "N", N); d2 = std::vector<int>(N,int(0)); vals_i__ = context__.vals_i("d2"); pos__ = 0; size_t d2_limit_0__ = N; for (size_t i_0__ = 0; i_0__ < d2_limit_0__; ++i_0__) { d2[i_0__] = vals_i__[pos__++]; } current_statement_begin__ = 14; context__.validate_dims("data initialization", "alpha_mean", "double", context__.to_vec()); alpha_mean = double(0); vals_r__ = context__.vals_r("alpha_mean"); pos__ = 0; alpha_mean = vals_r__[pos__++]; current_statement_begin__ = 15; context__.validate_dims("data initialization", "alpha_sd", "double", context__.to_vec()); alpha_sd = double(0); vals_r__ = context__.vals_r("alpha_sd"); pos__ = 0; alpha_sd = vals_r__[pos__++]; current_statement_begin__ = 16; context__.validate_dims("data initialization", "beta_mean", "double", context__.to_vec()); beta_mean = double(0); vals_r__ = context__.vals_r("beta_mean"); pos__ = 0; beta_mean = vals_r__[pos__++]; current_statement_begin__ = 17; context__.validate_dims("data initialization", "beta_sd", "double", context__.to_vec()); beta_sd = double(0); vals_r__ = context__.vals_r("beta_sd"); pos__ = 0; beta_sd = vals_r__[pos__++]; current_statement_begin__ = 18; context__.validate_dims("data initialization", "gamma_mean", "double", context__.to_vec()); gamma_mean = double(0); vals_r__ = context__.vals_r("gamma_mean"); pos__ = 0; gamma_mean = vals_r__[pos__++]; current_statement_begin__ = 19; context__.validate_dims("data initialization", "gamma_sd", "double", context__.to_vec()); gamma_sd = double(0); vals_r__ = context__.vals_r("gamma_sd"); pos__ = 0; gamma_sd = vals_r__[pos__++]; current_statement_begin__ = 20; context__.validate_dims("data initialization", "sigma_mean", "double", context__.to_vec()); sigma_mean = double(0); vals_r__ = context__.vals_r("sigma_mean"); pos__ = 0; sigma_mean = vals_r__[pos__++]; current_statement_begin__ = 21; context__.validate_dims("data initialization", "sigma_sd", "double", context__.to_vec()); sigma_sd = double(0); vals_r__ = context__.vals_r("sigma_sd"); pos__ = 0; sigma_sd = vals_r__[pos__++]; current_statement_begin__ = 23; context__.validate_dims("data initialization", "omega_lkj_eta", "double", context__.to_vec()); omega_lkj_eta = double(0); vals_r__ = context__.vals_r("omega_lkj_eta"); pos__ = 0; omega_lkj_eta = vals_r__[pos__++]; current_statement_begin__ = 25; context__.validate_dims("data initialization", "alpha_d1_mean", "double", context__.to_vec()); alpha_d1_mean = double(0); vals_r__ = context__.vals_r("alpha_d1_mean"); pos__ = 0; alpha_d1_mean = vals_r__[pos__++]; current_statement_begin__ = 26; context__.validate_dims("data initialization", "alpha_d1_sd", "double", context__.to_vec()); alpha_d1_sd = double(0); vals_r__ = context__.vals_r("alpha_d1_sd"); pos__ = 0; alpha_d1_sd = vals_r__[pos__++]; current_statement_begin__ = 27; context__.validate_dims("data initialization", "gamma_d1_mean", "double", context__.to_vec()); gamma_d1_mean = double(0); vals_r__ = context__.vals_r("gamma_d1_mean"); pos__ = 0; gamma_d1_mean = vals_r__[pos__++]; current_statement_begin__ = 28; context__.validate_dims("data initialization", "gamma_d1_sd", "double", context__.to_vec()); gamma_d1_sd = double(0); vals_r__ = context__.vals_r("gamma_d1_sd"); pos__ = 0; gamma_d1_sd = vals_r__[pos__++]; current_statement_begin__ = 29; context__.validate_dims("data initialization", "alpha_d2_mean", "double", context__.to_vec()); alpha_d2_mean = double(0); vals_r__ = context__.vals_r("alpha_d2_mean"); pos__ = 0; alpha_d2_mean = vals_r__[pos__++]; current_statement_begin__ = 30; context__.validate_dims("data initialization", "alpha_d2_sd", "double", context__.to_vec()); alpha_d2_sd = double(0); vals_r__ = context__.vals_r("alpha_d2_sd"); pos__ = 0; alpha_d2_sd = vals_r__[pos__++]; current_statement_begin__ = 31; context__.validate_dims("data initialization", "gamma_d2_mean", "double", context__.to_vec()); gamma_d2_mean = double(0); vals_r__ = context__.vals_r("gamma_d2_mean"); pos__ = 0; gamma_d2_mean = vals_r__[pos__++]; current_statement_begin__ = 32; context__.validate_dims("data initialization", "gamma_d2_sd", "double", context__.to_vec()); gamma_d2_sd = double(0); vals_r__ = context__.vals_r("gamma_d2_sd"); pos__ = 0; gamma_d2_sd = vals_r__[pos__++]; // validate, data variables current_statement_begin__ = 3; check_greater_or_equal(function__,"N",N,1); current_statement_begin__ = 5; current_statement_begin__ = 6; current_statement_begin__ = 7; current_statement_begin__ = 9; for (int k0__ = 0; k0__ < N; ++k0__) { check_greater_or_equal(function__,"d1[k0__]",d1[k0__],0); check_less_or_equal(function__,"d1[k0__]",d1[k0__],1); } current_statement_begin__ = 10; for (int k0__ = 0; k0__ < N; ++k0__) { check_greater_or_equal(function__,"d2[k0__]",d2[k0__],0); check_less_or_equal(function__,"d2[k0__]",d2[k0__],1); } current_statement_begin__ = 14; current_statement_begin__ = 15; check_greater_or_equal(function__,"alpha_sd",alpha_sd,0); current_statement_begin__ = 16; current_statement_begin__ = 17; check_greater_or_equal(function__,"beta_sd",beta_sd,0); current_statement_begin__ = 18; current_statement_begin__ = 19; check_greater_or_equal(function__,"gamma_sd",gamma_sd,0); current_statement_begin__ = 20; current_statement_begin__ = 21; check_greater_or_equal(function__,"sigma_sd",sigma_sd,0); current_statement_begin__ = 23; current_statement_begin__ = 25; current_statement_begin__ = 26; check_greater_or_equal(function__,"alpha_d1_sd",alpha_d1_sd,0); current_statement_begin__ = 27; current_statement_begin__ = 28; check_greater_or_equal(function__,"gamma_d1_sd",gamma_d1_sd,0); current_statement_begin__ = 29; current_statement_begin__ = 30; check_greater_or_equal(function__,"alpha_d2_sd",alpha_d2_sd,0); current_statement_begin__ = 31; current_statement_begin__ = 32; check_greater_or_equal(function__,"gamma_d2_sd",gamma_d2_sd,0); // initialize data variables current_statement_begin__ = 36; validate_non_negative_index("y", "N", N); validate_non_negative_index("y", "2", 2); y = std::vector<vector_d>(N,vector_d(static_cast<Eigen::VectorXd::Index>(2))); stan::math::fill(y,DUMMY_VAR__); current_statement_begin__ = 37; for (int i = 1; i <= N; ++i) { current_statement_begin__ = 38; stan::model::assign(y, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(1), stan::model::nil_index_list())), stan::math::log((get_base1(z1,i,"z1",1) / get_base1(z0,i,"z0",1))), "assigning variable y"); current_statement_begin__ = 39; stan::model::assign(y, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(2), stan::model::nil_index_list())), stan::math::log((get_base1(z2,i,"z2",1) / get_base1(z0,i,"z0",1))), "assigning variable y"); } // validate transformed data current_statement_begin__ = 36; // validate, set parameter ranges num_params_r__ = 0U; param_ranges_i__.clear(); current_statement_begin__ = 44; ++num_params_r__; current_statement_begin__ = 45; ++num_params_r__; current_statement_begin__ = 46; ++num_params_r__; current_statement_begin__ = 47; validate_non_negative_index("Omega", "2", 2); num_params_r__ += ((2 * (2 - 1)) / 2); current_statement_begin__ = 48; validate_non_negative_index("sigma", "2", 2); num_params_r__ += 2; current_statement_begin__ = 49; ++num_params_r__; current_statement_begin__ = 50; ++num_params_r__; current_statement_begin__ = 51; ++num_params_r__; current_statement_begin__ = 52; ++num_params_r__; } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } ~model_AugBin2T1A() { } void transform_inits(const stan::io::var_context& context__, std::vector<int>& params_i__, std::vector<double>& params_r__, std::ostream* pstream__) const { stan::io::writer<double> writer__(params_r__,params_i__); size_t pos__; (void) pos__; // dummy call to supress warning std::vector<double> vals_r__; std::vector<int> vals_i__; if (!(context__.contains_r("alpha"))) throw std::runtime_error("variable alpha missing"); vals_r__ = context__.vals_r("alpha"); pos__ = 0U; context__.validate_dims("initialization", "alpha", "double", context__.to_vec()); double alpha(0); alpha = vals_r__[pos__++]; try { writer__.scalar_unconstrain(alpha); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable alpha: ") + e.what()); } if (!(context__.contains_r("beta"))) throw std::runtime_error("variable beta missing"); vals_r__ = context__.vals_r("beta"); pos__ = 0U; context__.validate_dims("initialization", "beta", "double", context__.to_vec()); double beta(0); beta = vals_r__[pos__++]; try { writer__.scalar_unconstrain(beta); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable beta: ") + e.what()); } if (!(context__.contains_r("gamma"))) throw std::runtime_error("variable gamma missing"); vals_r__ = context__.vals_r("gamma"); pos__ = 0U; context__.validate_dims("initialization", "gamma", "double", context__.to_vec()); double gamma(0); gamma = vals_r__[pos__++]; try { writer__.scalar_unconstrain(gamma); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable gamma: ") + e.what()); } if (!(context__.contains_r("Omega"))) throw std::runtime_error("variable Omega missing"); vals_r__ = context__.vals_r("Omega"); pos__ = 0U; validate_non_negative_index("Omega", "2", 2); validate_non_negative_index("Omega", "2", 2); context__.validate_dims("initialization", "Omega", "matrix_d", context__.to_vec(2,2)); matrix_d Omega(static_cast<Eigen::VectorXd::Index>(2),static_cast<Eigen::VectorXd::Index>(2)); for (int j2__ = 0U; j2__ < 2; ++j2__) for (int j1__ = 0U; j1__ < 2; ++j1__) Omega(j1__,j2__) = vals_r__[pos__++]; try { writer__.corr_matrix_unconstrain(Omega); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable Omega: ") + e.what()); } if (!(context__.contains_r("sigma"))) throw std::runtime_error("variable sigma missing"); vals_r__ = context__.vals_r("sigma"); pos__ = 0U; validate_non_negative_index("sigma", "2", 2); context__.validate_dims("initialization", "sigma", "vector_d", context__.to_vec(2)); vector_d sigma(static_cast<Eigen::VectorXd::Index>(2)); for (int j1__ = 0U; j1__ < 2; ++j1__) sigma(j1__) = vals_r__[pos__++]; try { writer__.vector_lb_unconstrain(0,sigma); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable sigma: ") + e.what()); } if (!(context__.contains_r("alphaD1"))) throw std::runtime_error("variable alphaD1 missing"); vals_r__ = context__.vals_r("alphaD1"); pos__ = 0U; context__.validate_dims("initialization", "alphaD1", "double", context__.to_vec()); double alphaD1(0); alphaD1 = vals_r__[pos__++]; try { writer__.scalar_unconstrain(alphaD1); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable alphaD1: ") + e.what()); } if (!(context__.contains_r("gammaD1"))) throw std::runtime_error("variable gammaD1 missing"); vals_r__ = context__.vals_r("gammaD1"); pos__ = 0U; context__.validate_dims("initialization", "gammaD1", "double", context__.to_vec()); double gammaD1(0); gammaD1 = vals_r__[pos__++]; try { writer__.scalar_unconstrain(gammaD1); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable gammaD1: ") + e.what()); } if (!(context__.contains_r("alphaD2"))) throw std::runtime_error("variable alphaD2 missing"); vals_r__ = context__.vals_r("alphaD2"); pos__ = 0U; context__.validate_dims("initialization", "alphaD2", "double", context__.to_vec()); double alphaD2(0); alphaD2 = vals_r__[pos__++]; try { writer__.scalar_unconstrain(alphaD2); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable alphaD2: ") + e.what()); } if (!(context__.contains_r("gammaD2"))) throw std::runtime_error("variable gammaD2 missing"); vals_r__ = context__.vals_r("gammaD2"); pos__ = 0U; context__.validate_dims("initialization", "gammaD2", "double", context__.to_vec()); double gammaD2(0); gammaD2 = vals_r__[pos__++]; try { writer__.scalar_unconstrain(gammaD2); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable gammaD2: ") + e.what()); } params_r__ = writer__.data_r(); params_i__ = writer__.data_i(); } void transform_inits(const stan::io::var_context& context, Eigen::Matrix<double,Eigen::Dynamic,1>& params_r, std::ostream* pstream__) const { std::vector<double> params_r_vec; std::vector<int> params_i_vec; transform_inits(context, params_i_vec, params_r_vec, pstream__); params_r.resize(params_r_vec.size()); for (int i = 0; i < params_r.size(); ++i) params_r(i) = params_r_vec[i]; } template <bool propto__, bool jacobian__, typename T__> T__ log_prob(vector<T__>& params_r__, vector<int>& params_i__, std::ostream* pstream__ = 0) const { typedef T__ local_scalar_t__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning T__ lp__(0.0); stan::math::accumulator<T__> lp_accum__; try { // model parameters stan::io::reader<local_scalar_t__> in__(params_r__,params_i__); local_scalar_t__ alpha; (void) alpha; // dummy to suppress unused var warning if (jacobian__) alpha = in__.scalar_constrain(lp__); else alpha = in__.scalar_constrain(); local_scalar_t__ beta; (void) beta; // dummy to suppress unused var warning if (jacobian__) beta = in__.scalar_constrain(lp__); else beta = in__.scalar_constrain(); local_scalar_t__ gamma; (void) gamma; // dummy to suppress unused var warning if (jacobian__) gamma = in__.scalar_constrain(lp__); else gamma = in__.scalar_constrain(); Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,Eigen::Dynamic> Omega; (void) Omega; // dummy to suppress unused var warning if (jacobian__) Omega = in__.corr_matrix_constrain(2,lp__); else Omega = in__.corr_matrix_constrain(2); Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> sigma; (void) sigma; // dummy to suppress unused var warning if (jacobian__) sigma = in__.vector_lb_constrain(0,2,lp__); else sigma = in__.vector_lb_constrain(0,2); local_scalar_t__ alphaD1; (void) alphaD1; // dummy to suppress unused var warning if (jacobian__) alphaD1 = in__.scalar_constrain(lp__); else alphaD1 = in__.scalar_constrain(); local_scalar_t__ gammaD1; (void) gammaD1; // dummy to suppress unused var warning if (jacobian__) gammaD1 = in__.scalar_constrain(lp__); else gammaD1 = in__.scalar_constrain(); local_scalar_t__ alphaD2; (void) alphaD2; // dummy to suppress unused var warning if (jacobian__) alphaD2 = in__.scalar_constrain(lp__); else alphaD2 = in__.scalar_constrain(); local_scalar_t__ gammaD2; (void) gammaD2; // dummy to suppress unused var warning if (jacobian__) gammaD2 = in__.scalar_constrain(lp__); else gammaD2 = in__.scalar_constrain(); // transformed parameters current_statement_begin__ = 56; validate_non_negative_index("Mu", "2", 2); validate_non_negative_index("Mu", "N", N); vector<Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> > Mu(N, (Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> (static_cast<Eigen::VectorXd::Index>(2)))); stan::math::initialize(Mu, DUMMY_VAR__); stan::math::fill(Mu,DUMMY_VAR__); current_statement_begin__ = 57; validate_non_negative_index("Sigma", "2", 2); Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,Eigen::Dynamic> Sigma(static_cast<Eigen::VectorXd::Index>(2),static_cast<Eigen::VectorXd::Index>(2)); (void) Sigma; // dummy to suppress unused var warning stan::math::initialize(Sigma, DUMMY_VAR__); stan::math::fill(Sigma,DUMMY_VAR__); current_statement_begin__ = 58; validate_non_negative_index("ProbD", "2", 2); validate_non_negative_index("ProbD", "N", N); vector<Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> > ProbD(N, (Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> (static_cast<Eigen::VectorXd::Index>(2)))); stan::math::initialize(ProbD, DUMMY_VAR__); stan::math::fill(ProbD,DUMMY_VAR__); current_statement_begin__ = 60; for (int i = 1; i <= N; ++i) { current_statement_begin__ = 61; stan::model::assign(Mu, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(1), stan::model::nil_index_list())), (alpha + (gamma * get_base1(z0,i,"z0",1))), "assigning variable Mu"); current_statement_begin__ = 62; stan::model::assign(Mu, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(2), stan::model::nil_index_list())), (beta + (gamma * get_base1(z0,i,"z0",1))), "assigning variable Mu"); current_statement_begin__ = 63; stan::model::assign(ProbD, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(1), stan::model::nil_index_list())), inv_logit((alphaD1 + (gammaD1 * get_base1(z0,i,"z0",1)))), "assigning variable ProbD"); current_statement_begin__ = 64; stan::model::assign(ProbD, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(2), stan::model::nil_index_list())), inv_logit((alphaD2 + (gammaD2 * get_base1(z1,i,"z1",1)))), "assigning variable ProbD"); } current_statement_begin__ = 67; stan::math::assign(Sigma, quad_form_diag(Omega,sigma)); // validate transformed parameters for (int i0__ = 0; i0__ < N; ++i0__) { for (int i1__ = 0; i1__ < 2; ++i1__) { if (stan::math::is_uninitialized(Mu[i0__](i1__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: Mu" << '[' << i0__ << ']' << '[' << i1__ << ']'; throw std::runtime_error(msg__.str()); } } } for (int i0__ = 0; i0__ < 2; ++i0__) { for (int i1__ = 0; i1__ < 2; ++i1__) { if (stan::math::is_uninitialized(Sigma(i0__,i1__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: Sigma" << '[' << i0__ << ']' << '[' << i1__ << ']'; throw std::runtime_error(msg__.str()); } } } for (int i0__ = 0; i0__ < N; ++i0__) { for (int i1__ = 0; i1__ < 2; ++i1__) { if (stan::math::is_uninitialized(ProbD[i0__](i1__))) { std::stringstream msg__; msg__ << "Undefined transformed parameter: ProbD" << '[' << i0__ << ']' << '[' << i1__ << ']'; throw std::runtime_error(msg__.str()); } } } const char* function__ = "validate transformed params"; (void) function__; // dummy to suppress unused var warning current_statement_begin__ = 56; current_statement_begin__ = 57; stan::math::check_cov_matrix(function__,"Sigma",Sigma); current_statement_begin__ = 58; // model body { current_statement_begin__ = 72; validate_non_negative_index("d", "N", N); Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> d(static_cast<Eigen::VectorXd::Index>(N)); (void) d; // dummy to suppress unused var warning stan::math::initialize(d, DUMMY_VAR__); stan::math::fill(d,DUMMY_VAR__); current_statement_begin__ = 75; lp_accum__.add(normal_log<propto__>(alpha, alpha_mean, alpha_sd)); current_statement_begin__ = 76; lp_accum__.add(normal_log<propto__>(beta, beta_mean, beta_sd)); current_statement_begin__ = 77; lp_accum__.add(normal_log<propto__>(gamma, gamma_mean, gamma_sd)); current_statement_begin__ = 81; lp_accum__.add(normal_log<propto__>(sigma, sigma_mean, sigma_sd)); current_statement_begin__ = 84; lp_accum__.add(lkj_corr_log<propto__>(Omega, omega_lkj_eta)); current_statement_begin__ = 87; lp_accum__.add(normal_log<propto__>(alphaD1, alpha_d1_mean, alpha_d1_sd)); current_statement_begin__ = 88; lp_accum__.add(normal_log<propto__>(gammaD1, gamma_d1_mean, gamma_d1_sd)); current_statement_begin__ = 89; lp_accum__.add(normal_log<propto__>(alphaD2, alpha_d2_mean, alpha_d2_sd)); current_statement_begin__ = 90; lp_accum__.add(normal_log<propto__>(gammaD2, gamma_d2_mean, gamma_d2_sd)); current_statement_begin__ = 93; lp_accum__.add(multi_normal_log<propto__>(y, Mu, Sigma)); current_statement_begin__ = 96; stan::math::assign(d, rep_vector(0,N)); current_statement_begin__ = 97; for (int i = 1; i <= N; ++i) { current_statement_begin__ = 98; lp_accum__.add(bernoulli_log<propto__>(get_base1(d1,i,"d1",1), get_base1(get_base1(ProbD,i,"ProbD",1),1,"ProbD",2))); current_statement_begin__ = 99; if (as_bool(logical_eq(get_base1(d1,i,"d1",1),1))) { current_statement_begin__ = 99; stan::model::assign(d, stan::model::cons_list(stan::model::index_uni(i), stan::model::nil_index_list()), 1, "assigning variable d"); } current_statement_begin__ = 100; if (as_bool(logical_eq(get_base1(d,i,"d",1),0))) { current_statement_begin__ = 100; lp_accum__.add(bernoulli_log<propto__>(get_base1(d2,i,"d2",1), get_base1(get_base1(ProbD,i,"ProbD",1),2,"ProbD",2))); } } } } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } lp_accum__.add(lp__); return lp_accum__.sum(); } // log_prob() template <bool propto, bool jacobian, typename T_> T_ log_prob(Eigen::Matrix<T_,Eigen::Dynamic,1>& params_r, std::ostream* pstream = 0) const { std::vector<T_> vec_params_r; vec_params_r.reserve(params_r.size()); for (int i = 0; i < params_r.size(); ++i) vec_params_r.push_back(params_r(i)); std::vector<int> vec_params_i; return log_prob<propto,jacobian,T_>(vec_params_r, vec_params_i, pstream); } void get_param_names(std::vector<std::string>& names__) const { names__.resize(0); names__.push_back("alpha"); names__.push_back("beta"); names__.push_back("gamma"); names__.push_back("Omega"); names__.push_back("sigma"); names__.push_back("alphaD1"); names__.push_back("gammaD1"); names__.push_back("alphaD2"); names__.push_back("gammaD2"); names__.push_back("Mu"); names__.push_back("Sigma"); names__.push_back("ProbD"); } void get_dims(std::vector<std::vector<size_t> >& dimss__) const { dimss__.resize(0); std::vector<size_t> dims__; dims__.resize(0); dimss__.push_back(dims__); dims__.resize(0); dimss__.push_back(dims__); dims__.resize(0); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(2); dims__.push_back(2); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(2); dimss__.push_back(dims__); dims__.resize(0); dimss__.push_back(dims__); dims__.resize(0); dimss__.push_back(dims__); dims__.resize(0); dimss__.push_back(dims__); dims__.resize(0); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(N); dims__.push_back(2); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(2); dims__.push_back(2); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(N); dims__.push_back(2); dimss__.push_back(dims__); } template <typename RNG> void write_array(RNG& base_rng__, std::vector<double>& params_r__, std::vector<int>& params_i__, std::vector<double>& vars__, bool include_tparams__ = true, bool include_gqs__ = true, std::ostream* pstream__ = 0) const { typedef double local_scalar_t__; vars__.resize(0); stan::io::reader<local_scalar_t__> in__(params_r__,params_i__); static const char* function__ = "model_AugBin2T1A_namespace::write_array"; (void) function__; // dummy to suppress unused var warning // read-transform, write parameters double alpha = in__.scalar_constrain(); double beta = in__.scalar_constrain(); double gamma = in__.scalar_constrain(); matrix_d Omega = in__.corr_matrix_constrain(2); vector_d sigma = in__.vector_lb_constrain(0,2); double alphaD1 = in__.scalar_constrain(); double gammaD1 = in__.scalar_constrain(); double alphaD2 = in__.scalar_constrain(); double gammaD2 = in__.scalar_constrain(); vars__.push_back(alpha); vars__.push_back(beta); vars__.push_back(gamma); for (int k_1__ = 0; k_1__ < 2; ++k_1__) { for (int k_0__ = 0; k_0__ < 2; ++k_0__) { vars__.push_back(Omega(k_0__, k_1__)); } } for (int k_0__ = 0; k_0__ < 2; ++k_0__) { vars__.push_back(sigma[k_0__]); } vars__.push_back(alphaD1); vars__.push_back(gammaD1); vars__.push_back(alphaD2); vars__.push_back(gammaD2); // declare and define transformed parameters double lp__ = 0.0; (void) lp__; // dummy to suppress unused var warning stan::math::accumulator<double> lp_accum__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning try { current_statement_begin__ = 56; validate_non_negative_index("Mu", "2", 2); validate_non_negative_index("Mu", "N", N); vector<Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> > Mu(N, (Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> (static_cast<Eigen::VectorXd::Index>(2)))); stan::math::initialize(Mu, DUMMY_VAR__); stan::math::fill(Mu,DUMMY_VAR__); current_statement_begin__ = 57; validate_non_negative_index("Sigma", "2", 2); Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,Eigen::Dynamic> Sigma(static_cast<Eigen::VectorXd::Index>(2),static_cast<Eigen::VectorXd::Index>(2)); (void) Sigma; // dummy to suppress unused var warning stan::math::initialize(Sigma, DUMMY_VAR__); stan::math::fill(Sigma,DUMMY_VAR__); current_statement_begin__ = 58; validate_non_negative_index("ProbD", "2", 2); validate_non_negative_index("ProbD", "N", N); vector<Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> > ProbD(N, (Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> (static_cast<Eigen::VectorXd::Index>(2)))); stan::math::initialize(ProbD, DUMMY_VAR__); stan::math::fill(ProbD,DUMMY_VAR__); current_statement_begin__ = 60; for (int i = 1; i <= N; ++i) { current_statement_begin__ = 61; stan::model::assign(Mu, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(1), stan::model::nil_index_list())), (alpha + (gamma * get_base1(z0,i,"z0",1))), "assigning variable Mu"); current_statement_begin__ = 62; stan::model::assign(Mu, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(2), stan::model::nil_index_list())), (beta + (gamma * get_base1(z0,i,"z0",1))), "assigning variable Mu"); current_statement_begin__ = 63; stan::model::assign(ProbD, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(1), stan::model::nil_index_list())), inv_logit((alphaD1 + (gammaD1 * get_base1(z0,i,"z0",1)))), "assigning variable ProbD"); current_statement_begin__ = 64; stan::model::assign(ProbD, stan::model::cons_list(stan::model::index_uni(i), stan::model::cons_list(stan::model::index_uni(2), stan::model::nil_index_list())), inv_logit((alphaD2 + (gammaD2 * get_base1(z1,i,"z1",1)))), "assigning variable ProbD"); } current_statement_begin__ = 67; stan::math::assign(Sigma, quad_form_diag(Omega,sigma)); // validate transformed parameters current_statement_begin__ = 56; current_statement_begin__ = 57; stan::math::check_cov_matrix(function__,"Sigma",Sigma); current_statement_begin__ = 58; // write transformed parameters if (include_tparams__) { for (int k_1__ = 0; k_1__ < 2; ++k_1__) { for (int k_0__ = 0; k_0__ < N; ++k_0__) { vars__.push_back(Mu[k_0__][k_1__]); } } for (int k_1__ = 0; k_1__ < 2; ++k_1__) { for (int k_0__ = 0; k_0__ < 2; ++k_0__) { vars__.push_back(Sigma(k_0__, k_1__)); } } for (int k_1__ = 0; k_1__ < 2; ++k_1__) { for (int k_0__ = 0; k_0__ < N; ++k_0__) { vars__.push_back(ProbD[k_0__][k_1__]); } } } if (!include_gqs__) return; // declare and define generated quantities // validate generated quantities // write generated quantities } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } template <typename RNG> void write_array(RNG& base_rng, Eigen::Matrix<double,Eigen::Dynamic,1>& params_r, Eigen::Matrix<double,Eigen::Dynamic,1>& vars, bool include_tparams = true, bool include_gqs = true, std::ostream* pstream = 0) const { std::vector<double> params_r_vec(params_r.size()); for (int i = 0; i < params_r.size(); ++i) params_r_vec[i] = params_r(i); std::vector<double> vars_vec; std::vector<int> params_i_vec; write_array(base_rng,params_r_vec,params_i_vec,vars_vec,include_tparams,include_gqs,pstream); vars.resize(vars_vec.size()); for (int i = 0; i < vars.size(); ++i) vars(i) = vars_vec[i]; } static std::string model_name() { return "model_AugBin2T1A"; } void constrained_param_names(std::vector<std::string>& param_names__, bool include_tparams__ = true, bool include_gqs__ = true) const { std::stringstream param_name_stream__; param_name_stream__.str(std::string()); param_name_stream__ << "alpha"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "beta"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "gamma"; param_names__.push_back(param_name_stream__.str()); for (int k_1__ = 1; k_1__ <= 2; ++k_1__) { for (int k_0__ = 1; k_0__ <= 2; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "Omega" << '.' << k_0__ << '.' << k_1__; param_names__.push_back(param_name_stream__.str()); } } for (int k_0__ = 1; k_0__ <= 2; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "sigma" << '.' << k_0__; param_names__.push_back(param_name_stream__.str()); } param_name_stream__.str(std::string()); param_name_stream__ << "alphaD1"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "gammaD1"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "alphaD2"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "gammaD2"; param_names__.push_back(param_name_stream__.str()); if (!include_gqs__ && !include_tparams__) return; if (include_tparams__) { for (int k_1__ = 1; k_1__ <= 2; ++k_1__) { for (int k_0__ = 1; k_0__ <= N; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "Mu" << '.' << k_0__ << '.' << k_1__; param_names__.push_back(param_name_stream__.str()); } } for (int k_1__ = 1; k_1__ <= 2; ++k_1__) { for (int k_0__ = 1; k_0__ <= 2; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "Sigma" << '.' << k_0__ << '.' << k_1__; param_names__.push_back(param_name_stream__.str()); } } for (int k_1__ = 1; k_1__ <= 2; ++k_1__) { for (int k_0__ = 1; k_0__ <= N; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "ProbD" << '.' << k_0__ << '.' << k_1__; param_names__.push_back(param_name_stream__.str()); } } } if (!include_gqs__) return; } void unconstrained_param_names(std::vector<std::string>& param_names__, bool include_tparams__ = true, bool include_gqs__ = true) const { std::stringstream param_name_stream__; param_name_stream__.str(std::string()); param_name_stream__ << "alpha"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "beta"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "gamma"; param_names__.push_back(param_name_stream__.str()); for (int k_0__ = 1; k_0__ <= ((2 * (2 - 1)) / 2); ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "Omega" << '.' << k_0__; param_names__.push_back(param_name_stream__.str()); } for (int k_0__ = 1; k_0__ <= 2; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "sigma" << '.' << k_0__; param_names__.push_back(param_name_stream__.str()); } param_name_stream__.str(std::string()); param_name_stream__ << "alphaD1"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "gammaD1"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "alphaD2"; param_names__.push_back(param_name_stream__.str()); param_name_stream__.str(std::string()); param_name_stream__ << "gammaD2"; param_names__.push_back(param_name_stream__.str()); if (!include_gqs__ && !include_tparams__) return; if (include_tparams__) { for (int k_1__ = 1; k_1__ <= 2; ++k_1__) { for (int k_0__ = 1; k_0__ <= N; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "Mu" << '.' << k_0__ << '.' << k_1__; param_names__.push_back(param_name_stream__.str()); } } for (int k_0__ = 1; k_0__ <= (2 + ((2 * (2 - 1)) / 2)); ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "Sigma" << '.' << k_0__; param_names__.push_back(param_name_stream__.str()); } for (int k_1__ = 1; k_1__ <= 2; ++k_1__) { for (int k_0__ = 1; k_0__ <= N; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "ProbD" << '.' << k_0__ << '.' << k_1__; param_names__.push_back(param_name_stream__.str()); } } } if (!include_gqs__) return; } }; // model } typedef model_AugBin2T1A_namespace::model_AugBin2T1A stan_model; #endif
[ "kristian.brock@gmail.com" ]
kristian.brock@gmail.com
f4a62bf2941d984dd3f508164ff95b5962426fe8
d2faaf968199d35d9df9b2c85e669294334e425f
/Classes/module/gamePlayingScene/Controller/archerController/archerController.h
2f80757ea2f13f1974c07978691207c22c1b7f57
[]
no_license
lifestory/CatapultGame
374abd3937577998766d864870a7f2e8961712ec
2e4235d7e0a2b0bcf92704638c248769b0dcca84
refs/heads/master
2021-01-20T18:01:50.216264
2016-06-28T08:48:55
2016-06-28T08:48:55
62,115,939
1
0
null
null
null
null
UTF-8
C++
false
false
1,435
h
#ifndef __ARCHER_CONTROLLER_H__ #define __ARCHER_CONTROLLER_H__ #include "cocos2d.h" USING_NS_CC; #include"../../Model/archer/archer.h" #include"../../../../public/Constant/Constant.h" #include"../../../../public/ParameterManager/ParameterManager.h" #include"../../Model/archer/arrow.h" #include"../../Model/archer/progressTime.h" #include"../cameraController/CameraController.h" #include"../../Model/Enemy/Enemy.h" class ArcherController : public cocos2d::Layer{ public: static ArcherController* getInstance(); virtual bool init(); CREATE_FUNC(ArcherController); archer* getArcher(); progressTime* getProgressTime(); static void touchBegan(Vec2); static void touchEnded(Vec2); void updateTimeForProgressBar(float dt); void updateTimeForAddExp(float dt); void onKeyPressed(EventKeyboard::KeyCode keyCode, Event*event); void onKeyReleased(EventKeyboard::KeyCode keyCode, Event*event); void landGround(); void leaveGround(); void attacked(Node* aNode, int); void setWeapon(int); void gameEndedAndRemove(); void touchRope(); void leaveRope(); void createArrowRainTouch(Node* arrowRainNode); private: ArcherController(); ~ArcherController(); static ArcherController* archerController; static archer* archer_; static progressTime* progressTime_; static float totalTimeForProgressBar; static bool moveLeftAngRightLock; static bool moveUpAndDownLock; static bool onAir; static bool climbing; }; #endif
[ "496756287@qq.com" ]
496756287@qq.com
66b23b642a6d3a775c0822288c0d218c6ee9bf93
da07d22c338f1c046b24eb9dfb4d2cc3a02c3a36
/Atcoder/ARC/099/099-C.cpp
8fdd340cc452d57e38e869594365b4c7a396a8d8
[]
no_license
Umi-def/Atcoder
7fa402baf8de3ca846a8e43289d34baecc9d40ab
dd354894097890b4ce40c3eb679bd04b78aae810
refs/heads/main
2023-08-19T06:33:19.716933
2021-10-14T04:47:34
2021-10-14T04:47:34
302,190,503
0
0
null
null
null
null
UTF-8
C++
false
false
5,218
cpp
#include <iostream> #include <cstdint> #include <cstdio> #include <algorithm> #include <cmath> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <stack> #include <cctype> #include <cassert> #include <climits> #include <string> #include <bitset> #include <cfloat> #include <unordered_set> #include <limits> #include <math.h> #include <utility> #include <tuple> #include <deque> #include <unordered_map> #pragma GCC optimize("Ofast") #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> #include <iomanip> using namespace boost::multiprecision; typedef cpp_int BigNum; typedef cpp_dec_float_100 PreciseFloat; using namespace std; typedef long double ld; typedef long long int ll; typedef unsigned long long int ull; typedef vector<int> vi; typedef vector<char> vc; typedef vector<bool> vb; typedef vector<double> vd; typedef vector<string> vs; typedef vector<ll> vll; typedef vector<pair<int, int>> vpii; typedef vector<vector<int>> vvi; typedef vector<vector<char>> vvc; typedef vector<vector<string>> vvs; typedef vector<vector<ll>> vvll; #define rep(i, n) for (int i = 0; i < (ll)(n); ++i) #define rrep(i, n) for (int i = 1; i <= (ll)(n); ++i) #define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++) #define drep(i, n) for (int i = (n)-1; i >= 0; --i) #define CHOOSE3(a) CHOOSE4 a #define CHOOSE4(a0, a1, a2, x, ...) x #define mes_1(a) cout << (a) << endl #define mes_2(a, b) cout << (a) << " " << (b) << endl #define mes_3(a, b, c) cout << (a) << " " << (b) << " " << (c) << endl #define mes(...) \ CHOOSE3((__VA_ARGS__, mes_3, mes_2, mes_1, ~)) \ (__VA_ARGS__) #define CHOOSE(a) CHOOSE2 a #define CHOOSE2(a0, a1, a2, a3, a4, x, ...) x #define debug_1(x1) cout << #x1 << ": " << x1 << endl #define debug_2(x1, x2) cout << #x1 << ": " << x1 << ", " #x2 << ": " << x2 << endl #define debug_3(x1, x2, x3) cout << #x1 << ": " << x1 << ", " #x2 << ": " << x2 << ", " #x3 << ": " << x3 << endl #define debug_4(x1, x2, x3, x4) cout << #x1 << ": " << x1 << ", " #x2 << ": " << x2 << ", " #x3 << ": " << x3 << ", " #x4 << ": " << x4 << endl #define debug_5(x1, x2, x3, x4, x5) cout << #x1 << ": " << x1 << ", " #x2 << ": " << x2 << ", " #x3 << ": " << x3 << ", " #x4 << ": " << x4 << ", " #x5 << ": " << x5 << endl #define debug(...) \ CHOOSE((__VA_ARGS__, debug_5, debug_4, debug_3, debug_2, debug_1, ~)) \ (__VA_ARGS__) #define Ynmes(a) (a) ? mes("Yes") : mes("No") #define YNmes(a) (a) ? mes("YES") : mes("NO") #define ynmes(a) (a) ? mes("yes") : mes("no") #define re0 return 0 #define mp(p, q) make_pair(p, q) #define pb(n) push_back(n) #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define Sort(a) sort(a.begin(), a.end()) #define rSort(a) sort(a.rbegin(), a.rend()) #define Rev(a) reverse(a.begin(), a.end()) #define MATHPI acos(-1) #define itn int; int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1}; template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } struct io { io() { ios::sync_with_stdio(false); cin.tie(0); } }; const int INF = INT_MAX; const ll LLINF = 1LL << 60; const ll MOD = 1000000007; const double EPS = 1e-9; ll fact_mod(ll n, ll mod) { ll f = 1; for (ll i = 2; i <= n; i++) f = f * (i % mod) % mod; return f; } ll modpow(ll x, ll n, ll mod) { if (n == 0) return 1; ll res = modpow((x * x) % mod, n / 2, mod); if (n & 1) res = (res * x) % mod; return res; } ll modncr(ll n, ll r, ll mod) { if (r > n - r) r = n - r; if (r == 0) return 1; ll a = 1; rep(i, r) a = a * ((n - i) % mod) % mod; ll b = modpow(fact_mod(r, mod), mod - 2, mod); return (a % mod) * (b % mod) % mod; } ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } ll lcm(ll a, ll b) { return a / gcd(a, b) * b; } ll nlcm(vector<ll> numbers) { ll res; res = numbers[0]; for (ll i = 1; i < (ll)numbers.size(); i++) { res = lcm(res, numbers[i]); } return res; } uintmax_t ncr(unsigned int n, unsigned int r) { if (r * 2 > n) r = n - r; uintmax_t dividend = 1; uintmax_t divisor = 1; for (unsigned int i = 1; i <= r; ++i) { dividend *= (n - i + 1); divisor *= i; } return dividend / divisor; } signed main(void) { ll n, k, ans = 0; cin >> n >> k; vll a(n); rep(i, n) cin >> a[i]; if (n == k) { mes(1); re0; } if (k == 2) { mes(n - 1); re0; } if (n % (k - 1) == 0 || (n - 1) % (k - 1) == 0) { mes(n / (k - 1)); } else { mes(n / (k - 1) + 1); } }
[ "yumi901ririi@icloud.com" ]
yumi901ririi@icloud.com
2b1d665ea8991195a81560ea9f24ea3bff74826c
0e6a0119fa18a550c0e26a5b1b288e1d3951cfcc
/speed_leds.cpp
794fc8535203d2fefd7ece81fce640126c86d381
[]
no_license
jamesfowkes/asap-watercraft-user-board
441f801dc498634bbc533d32923fb93d4f9e1229
f74f91ab75cc439de6e7bfc705cd214fe2a42e19
refs/heads/master
2021-09-07T07:24:19.749089
2018-02-19T15:10:12
2018-02-19T15:10:12
85,165,502
0
0
null
null
null
null
UTF-8
C++
false
false
2,779
cpp
/* * switches.cpp * * James Fowkes (jamesfowkes@gmail.com) * for ASAP Watercrafts * * Created March 2017 * * Modified from original file RTD-ASAP_Controller.c * by Rapid Technology Development ltd. */ /* * AVR Includes */ #include <avr/io.h> /* * C standard library Includes */ #include <stdint.h> /* * Application Includes */ #include "speed_leds.h" #include "util.h" /* * Defines, Typedefs, Constants */ #define SPEED_LEDS_DDR DDRC #define SPEED_LEDS_PORT PORTC static const int BLINK_PERIOD = 250; static const int SPEED_LED_ROW0 = (1<<0); static const int SPEED_LED_ROW1 = (1<<1); static const int SPEED_LED_ROW2 = (1<<2); static const int SPEED_LED_ROW3 = (1<<3); static const int SPEED_LED_MASK = 0x0F; #define SPEED_LED_PWM_DDR DDRD #define SPEED_LED_PWM_PORT PORTD #define SPEED_LED_PWM_PIN (4) /* * Private Variables */ static uint32_t s_blink_timer = BLINK_PERIOD; static bool s_blink = false; static bool s_blink_state = false; /* * Public Functions */ void speed_leds_setup() { SPEED_LEDS_DDR |= ( SPEED_LED_ROW0 | SPEED_LED_ROW1 | SPEED_LED_ROW2 | SPEED_LED_ROW3 ); SPEED_LED_PWM_DDR |= (1 << SPEED_LED_PWM_PIN); // Timer/Counter 1 initialization. TCCR1A = ( (0 << COM1A1) | (0 << COM1A0) // Channel A not used | (1 << COM1B1) | (1 << COM1B0) // Channel B in set-on-compare-match, clear at TOP mode | (0 << FOC1A) | (0 << FOC1B) // Clear force output compare bits | (0 << WGM11) | (1 << WGM10) // 8-bit PWM node (lower 2 bits) ); TCCR1B = ( (1<<WGM12) // 8-bit PWM mode (upper bit) | (0 << CS12) | (1 << CS11) | (1 << CS10) // (Fcpu/64 = 125kHz clock = ~490Hz PWM frequency) ); TCNT1=0x00; speed_leds_set_brightness(0); speed_leds_set_level(0); } void speed_leds_set_brightness(uint8_t brightness) { uint16_t linearised_brightness = brightness * brightness; linearised_brightness = (linearised_brightness & 0xFF00) >> 8; OCR1B = 255-linearised_brightness; } void speed_leds_set_level(uint8_t level) { SPEED_LEDS_PORT &= ~SPEED_LED_MASK; switch(level) { case 0: break; case 1: SPEED_LEDS_PORT |= SPEED_LED_ROW0; break; case 2: SPEED_LEDS_PORT |= SPEED_LED_ROW0 | SPEED_LED_ROW1; break; case 3: SPEED_LEDS_PORT |= SPEED_LED_ROW0 | SPEED_LED_ROW1 | SPEED_LED_ROW2; break; case 4: default: SPEED_LEDS_PORT |= SPEED_LED_ROW0 | SPEED_LED_ROW1 | SPEED_LED_ROW2 | SPEED_LED_ROW3; break; } } void speed_leds_blink(bool blink) { s_blink = blink; } void speed_leds_tick(uint32_t tick_ms) { if (s_blink) { s_blink_timer = subtract_not_below_zero(s_blink_timer, tick_ms); if (s_blink_timer == 0) { speed_leds_set_level(s_blink_state ? 4 : 0); s_blink_state = !s_blink_state; s_blink_timer = BLINK_PERIOD; } } }
[ "jamesfowkes@gmail.com" ]
jamesfowkes@gmail.com
cebd30dd44a9dfb5cc5970ca4971d28436f3c148
6b980d21531cabbaf6b718227b023aa233352d6d
/menu/rendermenu.hpp
9eb18641f16943287b3f7fd441122e3b4608af53
[]
no_license
younasiqw/affluence
217a26eb45777e4822ddac91920c4eaaa5e317e1
1977307d865825a7c13540a20da01b5045f69a05
refs/heads/master
2020-03-18T14:30:18.150307
2018-05-25T09:18:49
2018-05-25T09:18:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
400
hpp
#pragma once #include "../main/interfaces.hpp" struct render_struct { const char* title; float* value; float min; float max; float step; bool isTab; }; class render_definitions { public: int index = 0; int items = 0; float tab, tab2, tab3, tab4; }; class render_menu { public: render_struct frame[150]; }; extern render_menu g_rendermenu; extern render_definitions g_renderdefinitions;
[ "headaimclub2@gmail.com" ]
headaimclub2@gmail.com
44ef367a83bea28de67506e19b35c8bb47b95080
03c6d91afa813b32aa0c0f5710c8ccc68e5d7c05
/codeforces 1393 C. Pinkie Pie Eats Patty-cakes.cpp
18afdaae442b7f88f2a442e46bd40f60ccd42c4d
[]
no_license
DorianBajorek/Codeforces-solutions
96fe6c54b55681fe030f3e9015367d2176d10daf
d8e936de286342fef7230da2afbc50dd13164c93
refs/heads/master
2023-05-29T00:52:16.680588
2020-10-05T16:33:52
2020-10-05T16:33:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,683
cpp
// Problem : C. Pinkie Pie Eats Patty-cakes // Contest : Codeforces - Codeforces Round #662 (Div. 2) // URL : https://codeforces.com/contest/1393/problem/C // Memory Limit : 256.000000 MB // Time Limit : 2000.000000 milisec #include<bits/stdc++.h> #define ll long long int #define pb push_back #define F first #define S second #define mp make_pair #define MOD 1000000007 #define vi vector<int> #define vll vector<ll> #define pll pair<ll,ll> #define pii pair<int,int> #define all(p) p.begin(),p.end() #define mid(s,e) (s+(e-s)/2) #define eb emplace_back #define ull unsigned long long #define bug(x) cout<<" [ "#x<<" = "<<x<<" ]"<<endl; #define KAMEHAMEHA ios_base::sync_with_stdio(0); #define RASENGAN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; void solve() { int n; cin>>n; unordered_map<int,int> cnt; int mx=0,mxcnt=0; for(int i=0,temp;i<n;i++) { cin>>temp; cnt[temp]++; mx=max(mx,cnt[temp]); } for(auto i : cnt) { if(i.S==mx) mxcnt++; } ll low=0,high=n-1,mid,ans=0; while(low<=high) { mid=low+((high-low)>>1); ll req=mxcnt+((mx-1)*(mid+1)); if(req>n) { high=mid-1; } else { low=mid+1; ans=max(ans,mid); } } cout<<ans<<endl; } int main() { KAMEHAMEHA int t=1; cin>>t; for(int cn=1;cn<=t;cn++) { solve(); } return 0; }
[ "noreply@github.com" ]
DorianBajorek.noreply@github.com
edab26a13467e30a0df5c4142fc9bf57a4247abd
50b452728fcc521cd8e82ca1377bd1f6a7fa60ec
/CavemanNinja/GUILabel.cpp
0afe6c8c694599281aaa07930f1ae69be361cad2
[]
no_license
DorianHawkmoon/Caveman-Ninja
a7c6e8f38363278127a8c3a4af6e0e79265fa7e6
c39dbd8be2234722bad3f2e5e53981d83ec3022c
refs/heads/master
2021-01-10T17:10:45.342359
2016-04-11T00:41:40
2016-04-11T00:41:40
49,627,241
0
0
null
null
null
null
UTF-8
C++
false
false
1,899
cpp
#include "GUILabel.h" #include "Application.h" #include "ModuleRender.h" #include "ModuleFonts.h" namespace GUI { GUILabel::GUILabel(const std::string& text, const SDL_Color& color, const std::string& font, const GUILocation& location, int size) : GUI::GUITexture(), nameFont(font), text(text), size(size+1), color(color) { transform.location = location; setSize(size); } bool GUILabel::isSelectable() const { return false; } void GUILabel::handleEvent(const SDL_Event&) {} SDL_Color GUILabel::getColor() const { return color; } void GUILabel::setColor(const SDL_Color & color) { this->color = color; createTexture(); } std::string GUILabel::getText() const { return text; } void GUILabel::setText(const std::string & text) { this->text = text; createTexture(); } void GUILabel::setSize(unsigned int size) { if (this->size != size) { if (font != nullptr) { App->fonts->unload(font, size); } this->size = size; font = App->fonts->load(nameFont.c_str(), size); createTexture(); } } unsigned int GUILabel::getSize() { return size; } void GUILabel::createTexture() { //Render text surface SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), color); if (textSurface == nullptr) { LOG("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError()); } else { //Create texture from surface pixels texture = SDL_CreateTextureFromSurface(App->renderer->renderer, textSurface); if (texture == nullptr) { LOG("Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError()); } //Get rid of old surface SDL_FreeSurface(textSurface); } // Establece el offset de acuerdo al alineamiento if (transform.location == GUILocation::ABSOLUTE) { return; } } GUILabel::~GUILabel() { if (font != nullptr) { App->fonts->unload(font, size); } } }
[ "dorian.cadenas@gmail.com" ]
dorian.cadenas@gmail.com
7c2a4cae19275d82c6dc3dcce1844cc9f826cc84
723638405a3a0fa9bf4fcef914420c58f3daeb2d
/src/object/object_engine.h
dc901660735357023494ddf664ec77e898c4d468
[ "MIT" ]
permissive
xuguozhi/mnn_example
c02b6a522236c8eec69b4fbf70b3f5519aa6a583
324f5ebc15c677270a614766dd9bb891b76c9505
refs/heads/master
2021-05-20T21:05:31.931058
2020-04-09T15:32:36
2020-04-09T15:32:36
252,416,589
0
1
MIT
2020-04-02T09:52:44
2020-04-02T09:52:44
null
UTF-8
C++
false
false
424
h
#ifndef _OBJECTER_H_ #define _OBJECTER_H_ #include "../../common/common.h" #include "./mobilenetssd/mobilenetssd.h" namespace mirror { class ObjectEngine { public: ObjectEngine(); ~ObjectEngine(); int Init(const char* root_path); int DetectObject(const cv::Mat& img_src, std::vector<ObjectInfo>* objects); private: bool initialized_; MobilenetSSD* mobilenetssd_; }; } #endif // !_OBJECTER_H_
[ "15671640320@163.com" ]
15671640320@163.com
976cc2295379f84b02a059a5efea47d1452874cd
751bddd2cd3152c0f40165cd004ce450fe69e087
/Source/Engine/Physics/Constraint.h
3a47dd488a317c493565cafc916894ef4eeac05f
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Zlib", "LicenseRef-scancode-khronos", "Apache-2.0", "BSD-2-Clause" ]
permissive
sabotage3d/UrhoSSAO
a9ec4bd2dfe24b73d0e13a3a609a3feabbab070b
66cd902dc96b41c10afd5b00e9e8c238d74978f5
refs/heads/master
2021-01-10T21:20:31.364517
2015-01-03T13:02:21
2015-01-03T13:02:21
28,743,920
13
2
null
null
null
null
UTF-8
C++
false
false
7,644
h
// // Copyright (c) 2008-2014 the Urho3D project. // // 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. // #pragma once #include "Component.h" #include "Vector3.h" class btTypedConstraint; namespace Urho3D { /// Supported constraint types. enum ConstraintType { CONSTRAINT_POINT = 0, CONSTRAINT_HINGE, CONSTRAINT_SLIDER, CONSTRAINT_CONETWIST }; class PhysicsWorld; class RigidBody; /// Physics constraint component. Connects two rigid bodies together, or one rigid body to a static point. class URHO3D_API Constraint : public Component { OBJECT(Constraint); friend class RigidBody; public: /// Construct. Constraint(Context* context); /// Destruct. ~Constraint(); /// Register object factory. static void RegisterObject(Context* context); /// Handle attribute write access. virtual void OnSetAttribute(const AttributeInfo& attr, const Variant& src); /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update. virtual void ApplyAttributes(); /// Handle enabled/disabled state change. virtual void OnSetEnabled(); /// Return the depended on nodes to order network updates. virtual void GetDependencyNodes(PODVector<Node*>& dest); /// Visualize the component as debug geometry. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest); /// Set constraint type and recreate the constraint. void SetConstraintType(ConstraintType type); /// Set other body to connect to. Set to null to connect to the static world. void SetOtherBody(RigidBody* body); /// Set constraint position relative to own body. void SetPosition(const Vector3& position); /// Set constraint rotation relative to own body. void SetRotation(const Quaternion& rotation); /// Set constraint rotation relative to own body by specifying the axis. void SetAxis(const Vector3& axis); /// Set constraint position relative to the other body. If connected to the static world, is a world space position. void SetOtherPosition(const Vector3& position); /// Set constraint rotation relative to the other body. If connected to the static world, is a world space rotation. void SetOtherRotation(const Quaternion& rotation); /// Set constraint rotation relative to the other body by specifying the axis. void SetOtherAxis(const Vector3& axis); /// Set constraint world space position. Resets both own and other body relative position, ie. zeroes the constraint error. void SetWorldPosition(const Vector3& position); /// Set high limit. Interpretation is constraint type specific. void SetHighLimit(const Vector2& limit); /// Set low limit. Interpretation is constraint type specific. void SetLowLimit(const Vector2& limit); /// Set constraint error reduction parameter. Zero = leave to default. void SetERP(float erp); /// Set constraint force mixing parameter. Zero = leave to default. void SetCFM(float cfm); /// Set whether to disable collisions between connected bodies. void SetDisableCollision(bool disable); /// Return physics world. PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; } /// Return Bullet constraint. btTypedConstraint* GetConstraint() const { return constraint_; } /// Return constraint type. ConstraintType GetConstraintType() const { return constraintType_; } /// Return rigid body in own scene node. RigidBody* GetOwnBody() const { return ownBody_; } /// Return the other rigid body. May be null if connected to the static world. RigidBody* GetOtherBody() const { return otherBody_; } /// Return constraint position relative to own body. const Vector3& GetPosition() const { return position_; } /// Return constraint rotation relative to own body. const Quaternion& GetRotation() const { return rotation_; } /// Return constraint position relative to other body. const Vector3& GetOtherPosition() const { return otherPosition_; } /// Return constraint rotation relative to other body. const Quaternion& GetOtherRotation() const { return otherRotation_; } /// Return constraint world position, calculated from own body. Vector3 GetWorldPosition() const; /// Return high limit. const Vector2& GetHighLimit() const { return highLimit_; } /// Return low limit. const Vector2& GetLowLimit() const { return lowLimit_; } /// Return constraint error reduction parameter. float GetERP() const { return erp_; } /// Return constraint force mixing parameter. float GetCFM() const { return cfm_; } /// Return whether collisions between connected bodies are disabled. bool GetDisableCollision() const { return disableCollision_; } /// Release the constraint. void ReleaseConstraint(); /// Apply constraint frames. void ApplyFrames(); protected: /// Handle node being assigned. virtual void OnNodeSet(Node* node); /// Handle node transform being dirtied. virtual void OnMarkedDirty(Node* node); private: /// Create the constraint. void CreateConstraint(); /// Apply high and low constraint limits. void ApplyLimits(); /// Physics world. WeakPtr<PhysicsWorld> physicsWorld_; /// Own rigid body. WeakPtr<RigidBody> ownBody_; /// Other rigid body. WeakPtr<RigidBody> otherBody_; /// Bullet constraint. btTypedConstraint* constraint_; /// Constraint type. ConstraintType constraintType_; /// Constraint position. Vector3 position_; /// Constraint rotation. Quaternion rotation_; /// Constraint other body position. Vector3 otherPosition_; /// Constraint other body axis. Quaternion otherRotation_; /// Cached world scale for determining if the constraint position needs update. Vector3 cachedWorldScale_; /// High limit. Vector2 highLimit_; /// Low limit. Vector2 lowLimit_; /// Error reduction parameter. float erp_; /// Constraint force mixing parameter. float cfm_; /// Other body node ID for pending constraint recreation. int otherBodyNodeID_; /// Disable collision between connected bodies flag. bool disableCollision_; /// Recreate constraint flag. bool recreateConstraint_; /// Coordinate frames dirty flag. bool framesDirty_; }; }
[ "sabotage3d@gmail.com" ]
sabotage3d@gmail.com
9d40f5fec97fa61271abac741a07df0282bd4c5b
8607bda716336606ea63a0d7f68ea114b9dc4ae2
/project1/sectE/unused/RIS_model.h
3360c1fb715f47423aa6f0469f2c7cdfb1e2d814
[ "BSD-3-Clause" ]
permissive
wood-b/CompBook
6a7c7f606c0a1b89a69f2ffa8974e6a262b00da3
5a0d5764d1d9ed97b54b7ce91048471b70dadb7d
refs/heads/master
2021-01-17T12:10:58.853498
2016-06-03T21:22:20
2016-06-03T21:22:20
38,138,422
2
0
null
null
null
null
UTF-8
C++
false
false
549
h
#ifndef RIS_MODEL_H #define RIS_MODEL_H #include <vector> #include "matrix.h" class RIS_params { private: matrix m_statWt; //U is stat weight matrix matrix m_eigenvec; //A is eigenvector matrix double m_eigenval; //lamda is the largest eigenvalue public: RIS_params (/*const*/ std::vector<double>& U, /*const*/ std::vector<double>& A, /*const*/ double& lamda); matrix& statWtMatrix(); matrix& eigenvectors(); double& eigenvalue(); }; #endif
[ "b.wood@berkeley.edu" ]
b.wood@berkeley.edu
00b7884bca0eac926de97bc2ac5c026bdee59119
4e5603d18ddb236ea2b7cb7bf55b1020bb20c9c2
/vijos/p1549.cpp
ddf566df7c6d58b4dd56dc2647f8131bb6348a77
[ "Unlicense" ]
permissive
huanghongxun/ACM
0c6526ea8e4aeab44d906444cada2870e4dfb137
b7595bbe6c0d82ceb271e81fca3e787dc4060a55
refs/heads/master
2021-01-20T05:41:23.163401
2017-12-14T07:50:59
2017-12-14T07:50:59
101,464,800
3
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
#include <iostream> #include <cstring> #define N 100005 using namespace std; typedef long long ll; ll a[N]; ll cnt[2*N]; ll n, k, i, ki, sum, ans; int main() { memset(cnt, 0, sizeof(cnt)); cin>>n>>k; for(i = 0; i < n; i++) { cin>>a[i]; if(a[i] > k) a[i] = 1; else if(a[i] == k) { a[i] = 0; ki = i; } else a[i] = -1; } ans = 1; sum = 0; for(i = ki - 1; i >= 0; i--) { sum += a[i]; cnt[sum + N]++; if(sum == 0) ans++; } sum = 0; for(i = ki + 1; i < n; i++) { sum += a[i]; ans += cnt[-sum + N]; if(sum == 0) ans++; } cout<<ans; return 0; }
[ "huanghongxun2008@126.com" ]
huanghongxun2008@126.com
6ed2c424cfc6178e2835bcc4412dd6ac48595b5e
4cb0e906aefbfcbf7ab492551f90cae089fcdac5
/Assignment 2/deleteMiddle.cpp
cb553e1e7189eaa1ee9dd2fe95f75bd6ca87e3af
[]
no_license
bhumesh1505/IOOM
a021af284ebd78a8e6cb50d400c35b4b9211a4d3
01dc10857ea7410c6ab6bbad0ca0d0726c96f6b8
refs/heads/master
2020-03-29T19:42:08.895324
2018-11-17T06:32:14
2018-11-17T06:32:14
150,276,719
0
0
null
null
null
null
UTF-8
C++
false
false
785
cpp
#include "item.h" #include "Stack.h" void Stack::deleteMiddle() { try { if(!isEmpty()) { Stack temp(MAX_SIZE); item x; int siz = Size / 2; for(int i = 0 ; i < siz ; i++) { x = pop(); temp.push( x.getId() , x.getQuantity() , x.getLabel() ); } pop(); for(int i = 0 ; i < siz ; i++) { x = temp.pop(); push( x.getId() , x.getQuantity() , x.getLabel() ); } cout << "deleted successfully" << endl; } else { cout << "Stack already Empty" << endl; } } catch(exception e) { cout << e.what() << endl; } }
[ "bhumesh1505@gmail.com" ]
bhumesh1505@gmail.com
42ddaa16d0039bb086a622c60d4c0194be68820c
c8958958e5802f3e04ce88bd4064eacb98ce2f97
/图像渲染.cpp
d58225dfed6559616382cef3f559368fd19564c9
[]
no_license
Kiids/OJ_Practice
08e5ea99066421bfaf5b71e59eea24e282e39a24
e7d36ddb1664635d27db3c37bec952970b77dcb0
refs/heads/master
2023-09-01T11:38:28.834187
2023-06-30T17:12:18
2023-06-30T17:12:18
217,068,695
0
0
null
null
null
null
GB18030
C++
false
false
1,903
cpp
/* 有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。 给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。 为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。 最后返回经过上色渲染后的图像。 示例 1: 输入: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 输出: [[2,2,2],[2,2,0],[2,0,1]] 解析: 在图像的正中间,(坐标(sr,sc)=(1,1)), 在路径上所有符合条件的像素点的颜色都被更改成2。 注意,右下角的像素没有更改为2, 因为它不是在上下左右四个方向上与初始点相连的像素点。 注意: image 和 image[0] 的长度在范围 [1, 50] 内。 给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length。 image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。 */ class Solution { public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int oldColor = image[sr][sc]; if (image[sr][sc] == newColor) return image; image[sr][sc] = newColor; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; for (int i = 0; i < 4; i++) { int x = sr + dx[i], y = sc + dy[i]; if (x >= 0 && y >= 0 && x < image.size() && y < image[0].size() && image[x][y] == oldColor) floodFill(image, x, y, newColor); } return image; } };
[ "1980774293@qq.com" ]
1980774293@qq.com
e88cd7ba1e58d352671df76c981e28ee5ba175c3
ea90486b2c0174818e02ef7ba17e2c67c2eaaa00
/motion/controllers/sweetie_bot_controller_cartesian/src/cartesian_trajectory_cache.hpp
58863e66aecaa6dab57f4f4e8a36145b4db331d5
[]
no_license
sweetie-bot-project/sweetie_bot_rt_control
f760df3e991c10cbeacb7f656e8825cf381a6fcc
ee523681773327ab7b1328e646779e828473e919
refs/heads/master
2021-06-14T19:48:26.210352
2020-01-04T16:47:09
2020-01-04T16:47:09
190,021,034
0
1
null
null
null
null
UTF-8
C++
false
false
5,158
hpp
#ifndef JOINT_TRAJECTORY_CACHE_HPP #define JOINT_TRAJECTORY_CACHE_HPP #include <sensor_msgs/typekit/JointState.h> #include <sweetie_bot_kinematics_msgs/typekit/SupportState.h> #include <sweetie_bot_kinematics_msgs/typekit/RigidBodyState.h> #include <sweetie_bot_control_msgs/typekit/FollowStepSequenceAction.h> namespace sweetie_bot { namespace motion { class RobotModel; namespace controller { /** * @brief CartesianRobotState cache. * Store supplied messages "as is" using shared pointer. Object includes time marker. * * TODO In future versions should also support: * * messages appending * * hermite interpolation if period does not match * * restore velocity by spline * * TODO base link processing, cahin index access, limb name vector bufferizaion **/ class CartesianTrajectoryCache { public: typedef sweetie_bot_kinematics_msgs::RigidBodyState RigidBodyState; typedef sweetie_bot_control_msgs::FollowStepSequenceGoal FollowStepSequenceGoal; typedef sweetie_bot_kinematics_msgs::SupportState SupportState; typedef boost::shared_ptr<const FollowStepSequenceGoal> FollowStepSequenceGoal_const_shared_ptr; typedef std::list<FollowStepSequenceGoal_const_shared_ptr> StepSequenceList; protected: StepSequenceList step_sequence_list; /**< Contains trajectory chunks. */ int time_step; /**< Contains number of point in step_sequence_list.front(). Always valid. */ std::vector<int> limb_index_fullpose; /**< index of coresponding chain in fullpose */ std::vector<std::string> contact_name; /**< buffers default contact names from robot model */ public: /** * @brief Create new trajectory from sweetie_bot_control_msgs::FollowStepSequenceGoal message. * Check message consistency and throw std::invalid_argument if check failed. * @param trajectory Pointer to goal message. Shared pointer is used to minimize number of copy operations. * @param robot_model Pointer to RobotModel. * @param period Discretizaion period of trajectory. **/ CartesianTrajectoryCache(FollowStepSequenceGoal_const_shared_ptr trajectory, RobotModel * robot_model, double period); /** * @brief Move time marker one period in future. * Move time marker one period ahead. * @return false if trajectory is finished **/ bool step(); /** * @brief Prepare message buffers. * Set names, resize arrays. * @param limbs Buffer to be prepared. **/ void prepareEndEffectorStateBuffer(RigidBodyState& limbs) const; /** * @brief Return lists of required kinematics chains (according to RobotModel). * @return List of kinematics chains. **/ std::vector<std::string> getRequiredChains() const; /** * @brief Return lists of required kinematics chains (according to RobotModel). * @return List of kinematics chains. **/ double getTime() const { return step_sequence_list.front()->time_from_start[time_step]; } /** * @brief Copy desired base state in buffer of proper size. * Method does not check buffer size. * @param base RigidBodyState buffer receiving new base. It size must be at least one. * @return true if trajectory contains information about base position, false is returned otherwise. **/ bool getBaseState(RigidBodyState& base) const; /** * @brief Copy desired end effector locations in buffer of proper size. * Method does not check buffer size. * @param limbs RigidBodyState buffer receiving new state represented in base link frame. **/ void getEndEffectorState(RigidBodyState& limbs) const; /* * @brief Simplifies check of start conditions: check path tolerance at current time. * @param joints_real_sorted Full pose in joint space sorted according to RobotModel. * @return index of kinematic chain which violates tolerance, -1 otherwise **/ int checkPathToleranceFullpose(const RigidBodyState& limbs_real_sorted) const; /* * @brief Check if given pose is within defined path tolerance. * Check path_tolerance. Both poses must have the same layout as trajectory. * @return index of kinematic chain which violates tolerance, -1 otherwise **/ int checkPathTolerance(const RigidBodyState& joints_real, const RigidBodyState& joints_desired) const; /* * @brief Select kinematic chains from full robot pose. * Method does not perform size checks and does not set kinematic chains' names. Use @c prepareEndEffectorStateBuffer() to prepare it. * @param in_sorted Full pose sorted according to RobotModel. * @param out Selected kinematic chains. **/ void selectEndEffector(const RigidBodyState& in_sorted, RigidBodyState& out) const; /** * @brief Prepare SupportState message. * Resize arrays, set names. * @param support message buffer, **/ void prepareSupportStateBuffer(SupportState& support) const; /** * @brief Get supports' state to buffer of proper size. * Method does not check message * @param supports Support state buffer receiving new state **/ void getSupportState(SupportState& support) const; }; } // namespace controller } // namespace motion } // namespace sweetie_bot #endif /*JOINT_TRAJECTORY_CACHE_HPP*/
[ "goncharovoi@yandex.ru" ]
goncharovoi@yandex.ru
c6b39db6d88e75a558aa9c0a2be56f9d4df2d5fa
303c22dd001c3634bd2c80fe22b5468b82ae641f
/data_structures/graph/grid/bfs.cpp
e8878d27d2a9960cb10de4bfd9749293bf57b8d2
[]
no_license
VaibhavSaraf/Algorithms
8551b35f1fe7c0af1a67df43e532b6f481f5a2d7
72acf2e84267d4e6696e955bf0527e37a0063619
refs/heads/master
2023-06-05T23:09:41.735584
2021-07-05T08:21:27
2021-07-05T08:21:27
261,447,982
3
1
null
null
null
null
UTF-8
C++
false
false
1,313
cpp
#include <bits/stdc++.h> using namespace std; #define OJ \ freopen("input.txt", "r", stdin); \ freopen("output.txt", "w", stdout); bool visited[1001][1001]; int dist[1001][1001]; int n, m; bool isValid(int x, int y) { if (x < 1 || x > n || y < 1 || y > m) return false; if (visited[x][y] == true) return false; return true; } int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; void bfs(int srcX, int srcY) { queue<pair<int, int>> q; q.push({srcX, srcY}); visited[srcX][srcY] = true; dist[srcX][srcY] = 0; while (!q.empty()) { int currX = q.front().first; int currY = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { if (isValid(currX + dx[i], currY + dy[i])) { int newX = currX + dx[i]; int newY = currY + dy[i]; dist[newX][newY] = dist[currX][currY] + 1; visited[newX][newY] = 1; q.push({newX, newY}); } } } } int main() { OJ; cin >> n >> m; // n=rows, m=cols bfs(4, 2); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) cout << dist[i][j] << " "; cout << endl; } return 0; }
[ "vaibhavgsaraf@gmail.com" ]
vaibhavgsaraf@gmail.com
214e312b5fddc0c09482b257691853d363234c29
7d92c91d6ceae5e55d897f34f84a31b08b5d288c
/abc/117/A.cpp
90dc1e440fb91696994f398d36c92b0b16a626a2
[]
no_license
umaumax/atcoder
68cd9f5dc10bf54a2b670522e5327051e8148043
bf506ef04ad0592108ce231c379221c529ba88cc
refs/heads/master
2020-05-03T04:46:03.061324
2019-04-15T14:07:21
2019-04-15T14:07:21
178,431,089
0
0
null
null
null
null
UTF-8
C++
false
false
317
cpp
#include <algorithm> #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <set> #include <string> #include <unordered_map> #include <vector> int main(int argc, char* argv[]) { int T, X; std::cin >> T >> X; std::cout << (double)T / X << std::endl; return 0; }
[ "umauma7083@gmail.com" ]
umauma7083@gmail.com
3d838de244e82d2997322c6c0385eee018c1ce17
997b0ac548c08f8ea3c57be423c946f946ecff40
/Nutcracker/src/Nutcracker/Renderer/Texture.h
a5d701fdc76301793d8a43db40cde7ca1ffb13fc
[ "Apache-2.0" ]
permissive
DevShag/Nutcracker
883e4158bcba847c8ef88f486e127d92dd1825ee
a5d90233b4b308db58872288a7d1637bf22e3050
refs/heads/main
2023-07-15T05:48:37.533974
2021-08-23T06:40:50
2021-08-23T06:40:50
318,091,266
0
0
null
null
null
null
UTF-8
C++
false
false
520
h
#pragma once #include <string> #include "Nutcracker/Core/Core.h" namespace Nutcracker { class Texture { public: virtual ~Texture() = default; virtual uint32_t GetWidth() const = 0; virtual uint32_t GetHeight() const = 0; virtual void SetData(void* data, uint32_t size) = 0; virtual void Bind(uint32_t slot=0) const = 0; }; class Texture2D : public Texture { public: static Ref<Texture2D> Create(uint32_t width, uint32_t height); static Ref<Texture2D> Create(const std::string& path); }; }
[ "alishaguftadev@gmail.com" ]
alishaguftadev@gmail.com
83ad6f621a61beb8e8688cb56b81f4496caccb47
488effd96f778ac24ec956a611b41282cfb6672d
/install/include/hpp/constraints/hybrid-solver.hh
18a6bd0056e344f6210de61aed2db6628cffa754
[]
no_license
0000duck/hpp_source_code
c9f92ad813df2ae7d6ebfcd6331c2128b2b73d16
e155580ba6a0dcfa0d552bd998fc4b7df97bfb3f
refs/heads/master
2022-02-24T09:09:22.725116
2019-09-03T07:48:42
2019-09-03T07:48:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,083
hh
// Copyright (c) 2017, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-constraints. // hpp-constraints is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-constraints 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-constraints. If not, see <http://www.gnu.org/licenses/>. #ifndef HPP_CONSTRAINTS_HYBRID_SOLVER_HH # define HPP_CONSTRAINTS_HYBRID_SOLVER_HH # warning "This file is deprecated include <hpp/constraints/solver/by-substitution> instead" # include <hpp/constraints/solver/by-substitution.hh> #endif // HPP_CONSTRAINTS_HYBRID_SOLVER_HH
[ "352376886@qq.com" ]
352376886@qq.com
33cba41ce619abf4736995d078113bd309c63920
7a78522a78f7082f9517e0aa6af75db3f9de2357
/Engine/source/EtPipeline/Assets/EditableAudioAsset.h
8469ebc3c01cfb9d65c6d52b59e2a51563bfb811
[ "MIT" ]
permissive
avpdiver/ETEngine
86a511d5d1ca8f03d47579d0ce0b367180e9b55e
8a51e77a59cdeef216d4b6c41e4b882677db9596
refs/heads/master
2023-03-21T21:57:22.190835
2022-07-14T01:09:49
2022-07-14T01:09:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
526
h
#pragma once #include <EtFramework/Audio/AudioData.h> #include <EtPipeline/Content/EditorAsset.h> namespace et { namespace pl { //--------------------------------- // EditableAudioAsset // class EditableAudioAsset final : public EditorAsset<fw::AudioData> { DECLARE_FORCED_LINKING() RTTR_ENABLE(EditorAsset<fw::AudioData>) public: // Construct destruct //--------------------- EditableAudioAsset() : EditorAsset<fw::AudioData>() {} virtual ~EditableAudioAsset() = default; }; } // namespace pl } // namespace et
[ "illeahtion@gmail.com" ]
illeahtion@gmail.com
62ea6ffdcf5728ac378b46f6dfb84cac43ebf77b
e18c44e6c2d33e4ed02fc12f17b4e6305bca6a28
/Source/LD37/LooseWeapon.cpp
25b200057b36c653cf0f9dda35f5b659449fa6ea
[]
no_license
Quadtree/LD37
dbc68c74a090b35528180b6198d3758a25334322
4c43b3ebe1af0db64ac3469f9c89c6b1664300f3
refs/heads/master
2021-04-30T16:00:02.979074
2016-12-12T06:28:10
2016-12-12T06:28:10
76,097,648
0
0
null
null
null
null
UTF-8
C++
false
false
1,868
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "LD37.h" #include "LD37Character.h" #include "LooseWeapon.h" // Sets default values ALooseWeapon::ALooseWeapon() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; Root = CreateDefaultSubobject<USceneComponent>("Root"); Root->SetRelativeScale3D(FVector(0.056642f)); Mesh = CreateDefaultSubobject<UStaticMeshComponent>("Mesh"); Mesh->SetupAttachment(Root); Mesh->SetNotifyRigidBodyCollision(true); Mesh->OnComponentHit.AddDynamic(this, &ALooseWeapon::OnHit); Mesh->SetSimulatePhysics(true); RootComponent = Root; LifeSpan = 99999; } // Called when the game starts or when spawned void ALooseWeapon::BeginPlay() { Super::BeginPlay(); } // Called every frame void ALooseWeapon::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); LifeSpan -= DeltaTime; if (LifeSpan <= 0) Destroy(); } void ALooseWeapon::SetWeaponType(ALD37Character* chrRef, int32 weaponType) { WeaponType = weaponType; Mesh->SetStaticMesh(chrRef->WeaponDescriptions[weaponType].GunModel); if (chrRef->WeaponDescriptions[weaponType].GunInheritMaterial) Mesh->SetMaterial(0, chrRef->WeaponMaterials[weaponType]); } void ALooseWeapon::OnHit(UPrimitiveComponent * HitComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, FVector NormalImpulse, const FHitResult & Hit) { if (auto act = Cast<ALD37Character>(OtherActor)) { if (act->Health > 0) { act->AmmoCounts[act->WeaponDescriptions[WeaponType].AmmoType] += Ammo; if (!act->HasWeapon[WeaponType]) { act->HasWeapon[WeaponType] = true; act->WeaponMaterials[WeaponType] = Mesh->GetMaterial(0); } Destroy(); } } }
[ "quadtree@gmail.com" ]
quadtree@gmail.com
da1ecd209804e24782dd737c679f4adfc8f4f979
7d3ab1dd6e193bfba3eb23ac26159b7b1d5a95b8
/sources/srm_c_cpp_sdk_4.1/src/include/Planetodetic.h
81115aa272d25891c71712038544c1ed43f784d2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Geo4Win/sedris
2aef810d56aff38bbd68835bc13e16b6392ed909
f35768630212b22a5c2912fe2beb640c0511faa7
refs/heads/master
2021-07-07T10:40:40.583077
2017-10-03T19:14:13
2017-10-03T19:14:13
105,591,021
6
0
null
null
null
null
UTF-8
C++
false
false
15,305
h
/** @file Planetodetic.h @author David Shen @brief Planetodetic SRF. */ // SRM SDK Release 4.1.4 - July 1, 2011 // - SRM spec. 4.1 /* * NOTICE * * This software is provided openly and freely for use in representing and * interchanging environmental data & databases. * * This software was developed for use by the United States Government with * unlimited rights. The software was developed under contract * DASG60-02-D-0006 TO-193 by Science Applications International Corporation. * The software is unclassified and is deemed as Distribution A, approved * for Public Release. * * Use by others is permitted only upon the ACCEPTANCE OF THE TERMS AND * CONDITIONS, AS STIPULATED UNDER THE FOLLOWING PROVISIONS: * * 1. Recipient may make unlimited copies of this software and give * copies to other persons or entities as long as the copies contain * this NOTICE, and as long as the same copyright notices that * appear on, or in, this software remain. * * 2. Trademarks. All trademarks belong to their respective trademark * holders. Third-Party applications/software/information are * copyrighted by their respective owners. * * 3. Recipient agrees to forfeit all intellectual property and * ownership rights for any version created from the modification * or adaptation of this software, including versions created from * the translation and/or reverse engineering of the software design. * * 4. Transfer. Recipient may not sell, rent, lease, or sublicense * this software. Recipient may, however enable another person * or entity the rights to use this software, provided that this * AGREEMENT and NOTICE is furnished along with the software and * /or software system utilizing this software. * * All revisions, modifications, created by the Recipient, to this * software and/or related technical data shall be forwarded by the * Recipient to the Government at the following address: * * SMDC * Attention SEDRIS (TO193) TPOC * P.O. Box 1500 * Huntsville, AL 35807-3801 * * or via electronic mail to: se-mgmt@sedris.org * * 5. No Warranty. This software is being delivered to you AS IS * and there is no warranty, EXPRESS or IMPLIED, as to its use * or performance. * * The RECIPIENT ASSUMES ALL RISKS, KNOWN AND UNKNOWN, OF USING * THIS SOFTWARE. The DEVELOPER EXPRESSLY DISCLAIMS, and the * RECIPIENT WAIVES, ANY and ALL PERFORMANCE OR RESULTS YOU MAY * OBTAIN BY USING THIS SOFTWARE OR DOCUMENTATION. THERE IS * NO WARRANTY, EXPRESS OR, IMPLIED, AS TO NON-INFRINGEMENT OF * THIRD PARTY RIGHTS, MERCHANTABILITY, OR FITNESS FOR ANY * PARTICULAR PURPOSE. IN NO EVENT WILL THE DEVELOPER, THE * UNITED STATES GOVERNMENT OR ANYONE ELSE ASSOCIATED WITH THE * DEVELOPMENT OF THIS SOFTWARE BE HELD LIABLE FOR ANY CONSEQUENTIAL, * INCIDENTAL OR SPECIAL DAMAGES, INCLUDING ANY LOST PROFITS * OR LOST SAVINGS WHATSOEVER. */ // $Id: Planetodetic.h,v 1.6.1.4 2009-08-24 15:57:08-04 worleym Exp $ #ifndef _Planetodetic_h #define _Planetodetic_h #include "BaseSRF.h" #include "Coord.h" #include "Exception.h" namespace srm { /** SRF_Planetodetic class declaration. SRFs are allocated by the API, and when no longer needed they should be released by calling the release() method. @author David Shen @see BaseSRF_WithEllipsoidalHeight */ class EXPORT_SRM_CPP_DLL SRF_Planetodetic: public BaseSRF_WithEllipsoidalHeight { public: /** SRF_Planetodetic only constructor by ORM code @exception This method throws srm::Exception */ static SRF_Planetodetic* create( SRM_ORM_Code orm, SRM_RT_Code rt ); /** SRF_Planetodetic constructor by ORM parameters @exception This method throws srm::Exception */ static SRF_Planetodetic* create( SRM_SRF_Parameters_Info srf_params ) { return create( srf_params.value.srf_template.orm_code, srf_params.rt_code ); } /** Returns a 3D coordinate object */ Coord3D* createCoordinate3D(SRM_Long_Float coord_comp1, SRM_Long_Float coord_comp2, SRM_Long_Float coord_comp3 ); /** Returns a surface coordinate object */ CoordSurf* createSurfaceCoordinate(SRM_Long_Float coord_surf_comp1, SRM_Long_Float coord_surf_comp2 ); /** Returns true if this SRF is of the given class type */ virtual bool isA( SRF_ClassType type ) const; /** Returns the class type of this SRF instance */ virtual SRF_ClassType getClassType() const { return BaseSRF::SRF_TYP_PD; } /** Returns true if the SRF parameters are equal @note This method is deprecated. Use the equality operator instead. */ bool isEqual( const SRF_Planetodetic &srf ) const; /** The equality operator @note This operator returns true if the SRFs have identical parameter values. */ bool operator==( const SRF_Planetodetic &rhs ) const; /** Returns a copy of this SRF object @exception This method throws srm::Exception */ SRF_Planetodetic* makeCopy() const; /** Returns char* of parameter names and their values @exception This method throws srm::Exception */ const char* toString(); protected: friend class BaseSRF; SRF_Planetodetic( void *impl ) : BaseSRF_WithEllipsoidalHeight(impl) {} ///< No stack allocation SRF_Planetodetic &operator =( const SRF_Planetodetic & ) { return *this; } ///< No copy constructor virtual ~SRF_Planetodetic() {} ///< Use release() }; inline bool SRF_Planetodetic::isA( SRF_ClassType type ) const { if (type == BaseSRF::SRF_TYP_PD) return true; else return BaseSRF_WithEllipsoidalHeight::isA(type); }; /// Shorthand version for SRF_Planetodetic typedef SRF_Planetodetic SRF_PD; /** A Coord3D for SRF_Planetodetic. @author David Shen @see SRF_Planetodetic */ class EXPORT_SRM_CPP_DLL Coord3D_Planetodetic: public Coord3D { public: /** Constructor */ Coord3D_Planetodetic(SRF_Planetodetic *srf, SRM_Long_Float longitude = 0.0, SRM_Long_Float latitude = 0.0, SRM_Long_Float ellipsoidal_height = 0.0 ) : Coord3D(srf) { setComponentValues(longitude, latitude, ellipsoidal_height); } /** Copy constructor */ Coord3D_Planetodetic( const Coord3D_Planetodetic &coord ) : Coord3D(coord._srf) { setComponentValues( coord._values[0], coord._values[1], coord._values[2] ); } /** Copies component values to the coordinate @note The coordinates must be associated with the same SRF instance. @note This method is deprecated. Use the assignment operator. @exception This method throws srm::Exception */ void copyTo( Coord3D_Planetodetic &coord ) const { if (coord._srf != _srf) throw Exception( SRM_STATCOD_INVALID_SOURCE_COORDINATE, "copyTo: Coordinate associated with a difference SRF" ); coord._values[0] = _values[0]; coord._values[1] = _values[1]; coord._values[2] = _values[2]; } /** Returns true if the coordinate component values are identical @note This method is deprecated. Use the equality operator. */ bool isEqual( const Coord3D_Planetodetic &coord ) const { return (_srf == coord._srf && _values[0] == coord._values[0] && _values[1] == coord._values[1] && _values[2] == coord._values[2] ); } /** Sets all coordinate component values */ void setComponentValues( SRM_Long_Float longitude, SRM_Long_Float latitude, SRM_Long_Float ellipsoidal_height ) { _values[0] = longitude; _values[1] = latitude; _values[2] = ellipsoidal_height; } /** Returns the latitude value */ SRM_Long_Float get_latitude() const { return _values[1]; } /** Returns the longitude value */ SRM_Long_Float get_longitude() const { return _values[0]; } /** Returns the ellipsoidal_height value */ SRM_Long_Float get_ellipsoidal_height() const { return _values[2]; } /** Sets the latitude value */ void set_latitude( SRM_Long_Float value ) { _values[1] = value; } /** Sets the longitude value */ void set_longitude( SRM_Long_Float value ) { _values[0] = value; } /** Sets the ellipsoidal_height value */ void set_ellipsoidal_height( SRM_Long_Float value ) { _values[2] = value; } /** Returns true if this coordinate is of the given class type */ virtual bool isA( Coord_ClassType type ) const; /** Returns true if this SRF is of the given class type */ virtual Coord_ClassType getClassType() const { return Coord::COORD_TYP_PD; } /** The equality operator */ bool operator==( const Coord3D_Planetodetic &rhs ) const; /** Returns true if the coordinates are associated with SRFs with identical parameters. @note This method should be used to evaluate coordinate compatibility before calling the coordinate assignment operator to avoid raising runtime exception when operating on incompatible coordinates. */ bool isCompatibleWith( const Coord3D_Planetodetic &rhs ) const { return ((*(SRF_Planetodetic*)(this->_srf)) == (*(SRF_Planetodetic*)(rhs._srf))); } /** The assignment operator @note This operator will check whether the coordinates are compatible. @exception This method throws srm::Exception */ Coord3D_Planetodetic &operator= ( const Coord3D_Planetodetic &rhs ) { if((*(SRF_Planetodetic*)(this->_srf)) == (*(SRF_Planetodetic*)(rhs._srf))) { _values[0] = rhs._values[0]; _values[1] = rhs._values[1]; _values[2] = rhs._values[2]; } else throw Exception(SRM_STATCOD_INVALID_TARGET_COORDINATE, "Coord3D_Planetodetic op=: incompatible rhs coordinate"); return *this; } }; inline bool Coord3D_Planetodetic::isA( Coord_ClassType type ) const { if (type == Coord::COORD_TYP_PD) return true; else return Coord3D::isA(type); }; /// Shorthand version for Coord3D_Planetodetic typedef Coord3D_Planetodetic Coord3D_PD; /** A CoordSurf for SRF_Planetodetic. @author David Shen @see SRF_Planetodetic */ class EXPORT_SRM_CPP_DLL CoordSurf_Planetodetic: public CoordSurf { public: /** Constructor */ CoordSurf_Planetodetic(SRF_Planetodetic *srf, SRM_Long_Float longitude = 0.0, SRM_Long_Float latitude = 0.0 ) : CoordSurf(srf) { setComponentValues(longitude, latitude); } /** Copy constructor */ CoordSurf_Planetodetic( const CoordSurf_Planetodetic &coord ) : CoordSurf(coord._srf) { setComponentValues( coord._values[0], coord._values[1] ); } /** Copies component values to the coordinate @note The coordinates must be associated with the same SRF instance. @note This method is deprecated. Use the assignment operator. @exception This method throws srm::Exception */ void copyTo( CoordSurf_Planetodetic &coord ) const { if (coord._srf != _srf) throw Exception( SRM_STATCOD_INVALID_SOURCE_COORDINATE, "copyTo: Coordinate associated with a difference SRF" ); coord._values[0] = _values[0]; coord._values[1] = _values[1]; } /** Returns true if the coordinate component values are identical @note This method is deprecated. Use the equality operator. */ bool isEqual( const CoordSurf_Planetodetic &coord ) const { return (_srf == coord._srf && _values[0] == coord._values[0] && _values[1] == coord._values[1] ); } /** Sets all coordinate component values */ void setComponentValues( SRM_Long_Float longitude, SRM_Long_Float latitude ) { _values[0] = longitude; _values[1] = latitude; } /** Returns the latitude value */ SRM_Long_Float get_latitude() const { return _values[1]; } /** Returns the longitude value */ SRM_Long_Float get_longitude() const { return _values[0]; } /** Sets the latitude value */ void set_latitude( SRM_Long_Float value ) { _values[1] = value; } /** Sets the longitude value */ void set_longitude( SRM_Long_Float value ) { _values[0] = value; } /** Returns true if this coordinate is of the given class type */ virtual bool isA( Coord_ClassType type ) const; /** Returns true if this SRF is of the given class type */ virtual Coord_ClassType getClassType() const { return Coord::COORD_TYP_SURF_PD; } /** The equality operator */ bool operator==( const CoordSurf_Planetodetic &rhs ) const; /** Returns true if the coordinates are associated with SRFs with identical parameters. @note This method should be used to evaluate coordinate compatibility before calling the coordinate assignment operator to avoid raising runtime exception when operating on incompatible coordinates. */ bool isCompatibleWith( const CoordSurf_Planetodetic &rhs ) const { return ((*(SRF_Planetodetic*)(this->_srf)) == (*(SRF_Planetodetic*)(rhs._srf))); } /** The assignment operator @note This operator will check whether the coordinates are compatible. @exception This method throws srm::Exception */ CoordSurf_Planetodetic &operator= ( const CoordSurf_Planetodetic &rhs ) { if((*(SRF_Planetodetic*)(this->_srf)) == (*(SRF_Planetodetic*)(rhs._srf))) { _values[0] = rhs._values[0]; _values[1] = rhs._values[1]; } else throw Exception(SRM_STATCOD_INVALID_TARGET_COORDINATE, "CoordSurf_Planetodetic op=: incompatible rhs coordinate"); return *this; } }; inline bool CoordSurf_Planetodetic::isA( Coord_ClassType type ) const { if (type == Coord::COORD_TYP_SURF_PD) return true; else return CoordSurf::isA(type); }; /// Shorthand version for CoordSurf_Planetodetic typedef CoordSurf_Planetodetic CoordSurf_PD; } // namespace srm #endif // _Planetodetic_h
[ "sysbender@gmail.com" ]
sysbender@gmail.com
a74605e6cb5132d3d5a09516616aafbc45402db4
dfe1f796a54143e5eb8661f3328ad29dbfa072d6
/psx/_dump_/23/_dump_c_src_/diabpsx/source/lighting.cpp
394f829720bb799182612df5d02a2e3cc7728022
[ "Unlicense" ]
permissive
diasurgical/scalpel
0f73ad9be0750ce08eb747edc27aeff7931800cd
8c631dff3236a70e6952b1f564d0dca8d2f4730f
refs/heads/master
2021-06-10T18:07:03.533074
2020-04-16T04:08:35
2020-04-16T04:08:35
138,939,330
15
7
Unlicense
2019-08-27T08:45:36
2018-06-27T22:30:04
C
UTF-8
C++
false
false
5,311
cpp
// C:\diabpsx\SOURCE\LIGHTING.CPP #include "types.h" // address: 0x800453FC // line start: 319 // line end: 334 int veclen2__Fii(int ix, int iy) { // register: 4 register int t; } // address: 0x80045464 // line start: 380 // line end: 399 void set_light_bands__Fv() { // register: 2 register int v; // register: 5 register int y; // register: 4 register int c; } // address: 0x800454D8 // line start: 404 // line end: 411 void SetLightFX__FiisssUcUcUc(int x, int y, short s_r, short s_g, int s_b, int d_r, int d_g, int d_b) { } // address: 0x80045544 // line start: 415 // line end: 765 void DoLighting__Fiiii(int nXPos, int nYPos, int nRadius, int Lnum) { // register: 9 register int xoff; // register: 10 register int yoff; // register: 20 register int x; // register: 30 register int y; // register: 4 register int v; // register: 22 register int colour_mask; // register: 17 register int shift_mask; // register: 12 register int shake; // address: 0xFFFFFFA8 auto int light_x; // address: 0xFFFFFFB0 auto int light_y; // address: 0xFFFFFFB8 auto int block_x; // register: 9 register int block_y; // register: 23 register int dist_y; // register: 11 register int max_x; // register: 6 register int mult; // register: 7 register int mult_st; // register: 21 register int radius_block; // register: 7 register int scr_x; // register: 8 register int scr_y; // register: 6 register int temp_x; // register: 5 register int temp_y; // register: 19 register int weirdy; // register: 11 register int cont; } // address: 0x800461F4 // line start: 771 // line end: 819 void DoUnLight__Fv() { // register: 6 register int x; // register: 7 register int y; // register: 11 register int max_x; // register: 16 register int max_y; // register: 14 register int radius_block; // register: 13 register int nXPos; // register: 12 register int nYPos; } // address: 0x80046438 // line start: 826 // line end: 841 void DoUnVision__Fiii(int nXPos, int nYPos, int nRadius) { // register: 4 register int i; // register: 6 register int j; // register: 3 register int x1; // register: 9 register int y1; // register: 8 register int x2; // register: 5 register int y2; } // address: 0x800464FC // line start: 848 // line end: 952 void DoVision__FiiiUcUc(int nXPos, int nYPos, int nRadius, unsigned char doautomap, int visible) { // register: 16 register int nCrawlX; // register: 19 register int nCrawlY; // register: 9 register int nLineLen; // register: 21 register int nBlockerFlag; // register: 8 register int j; // register: 20 register int k; // register: 2 register int v; // register: 5 register int x1adj; // register: 7 register int x2adj; // register: 4 register int y1adj; // register: 6 register int y2adj; } // address: 0x80046A0C // line start: 957 // line end: 958 void FreeLightTable__Fv() { } // address: 0x80046A14 // line start: 964 // line end: 965 void InitLightTable__Fv() { } // address: 0x80046A1C // line start: 970 // line end: 971 void MakeLightTable__Fv() { } // address: 0x80046A24 // line start: 1062 // line end: 1065 void InitLightMax__Fv() { } // address: 0x80046A48 // line start: 1072 // line end: 1083 void InitLighting__Fv() { // register: 2 register int i; } // address: 0x80046A8C // line start: 1089 // line end: 1105 int AddLight__Fiii(int x, int y, int r) { // register: 7 register int lid; } // address: 0x80046B20 // line start: 1110 // line end: 1116 void AddUnLight__Fi(int i) { } // address: 0x80046B50 // line start: 1121 // line end: 1131 void ChangeLightRadius__Fii(int i, int r) { } // address: 0x80046B7C // line start: 1136 // line end: 1147 void ChangeLightXY__Fiii(int i, int x, int y) { } // address: 0x80046BB4 // line start: 1150 // line end: 1156 void light_fix__Fi(int i) { } // address: 0x80046BBC // line start: 1166 // line end: 1178 void ChangeLightOff__Fiii(int i, int x, int y) { } // address: 0x80046BF4 // line start: 1183 // line end: 1195 void ChangeLight__Fiiii(int i, int x, int y, int r) { } // address: 0x80046C38 // line start: 1198 // line end: 1199 void ChangeLightColour__Fii(int i, int c) { } // address: 0x80046C68 // line start: 1205 // line end: 1266 void ProcessLightList__Fv() { // register: 7 register int i; // register: 16 register int j; // register: 4 register unsigned char temp; } // address: 0x80046D94 // line start: 1271 // line end: 1298 void SavePreLighting__Fv() { } // address: 0x80046D9C // line start: 1303 // line end: 1310 void InitVision__Fv() { // register: 4 register int i; } // address: 0x80046DEC // line start: 1317 // line end: 1333 int AddVision__FiiiUc(int x, int y, int r, unsigned char mine) { // register: 8 register int vid; } // address: 0x80046EF0 // line start: 1356 // line end: 1369 void ChangeVisionRadius__Fii(int id, int r) { // register: 8 register int i; } // address: 0x80046FA4 // line start: 1374 // line end: 1388 void ChangeVisionXY__Fiii(int id, int x, int y) { // register: 10 register int i; } // address: 0x8004705C // line start: 1417 // line end: 1446 void ProcessVisionList__Fv() { // register: 17 register int i; // register: 4 register unsigned char delflag; }
[ "rnd0x00@gmail.com" ]
rnd0x00@gmail.com
453a0286d1a608e138d38a42dc63156c739687b4
fd8bfa1ddc32ad1ee24b2f9ecc7ec860f5690443
/Bcore/src/main/jni/Hook/UnixFileSystemHook.cpp
e7d70da1610c449be5468034107dc51c19f0001c
[ "Apache-2.0" ]
permissive
YunShiTiger/BlackDex
247ee95c33426ab0b0270dadd674b83b0f19e18d
095ad946e253b4fbdd182483d80cf594a796fbb8
refs/heads/main
2023-05-14T12:33:05.019390
2021-06-05T18:41:32
2021-06-05T18:41:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,263
cpp
// // Created by Milk on 4/9/21. // #include <IO.h> #include "UnixFileSystemHook.h" #import "JniHook/JniHook.h" #include "BaseHook.h" /* * Class: java_io_UnixFileSystem * Method: canonicalize0 * Signature: (Ljava/lang/String;)Ljava/lang/String; */ HOOK_JNI(jstring, canonicalize0, JNIEnv *env, jobject obj, jstring path) { jstring redirect = IO::redirectPath(env, path); return orig_canonicalize0(env, obj, redirect); } /* * Class: java_io_UnixFileSystem * Method: getBooleanAttributes0 * Signature: (Ljava/lang/String;)I */ HOOK_JNI(jint, getBooleanAttributes0, JNIEnv *env, jobject obj, jstring abspath) { jstring redirect = IO::redirectPath(env, abspath); return orig_getBooleanAttributes0(env, obj, redirect); } /* * Class: java_io_UnixFileSystem * Method: getLastModifiedTime0 * Signature: (Ljava/io/File;)J */ HOOK_JNI(jlong, getLastModifiedTime0, JNIEnv *env, jobject obj, jobject path) { jobject redirect = IO::redirectPath(env, path); return orig_getLastModifiedTime0(env, obj, redirect); } /* * Class: java_io_UnixFileSystem * Method: setPermission0 * Signature: (Ljava/io/File;IZZ)Z */ HOOK_JNI(jboolean, setPermission0, JNIEnv *env, jobject obj, jobject file, jint access, jboolean enable, jboolean owneronly) { jobject redirect = IO::redirectPath(env, file); return orig_setPermission0(env, obj, redirect, access, enable, owneronly); } /* * Class: java_io_UnixFileSystem * Method: createFileExclusively0 * Signature: (Ljava/lang/String;)Z */ HOOK_JNI(jboolean, createFileExclusively0, JNIEnv *env, jobject obj, jstring path) { jstring redirect = IO::redirectPath(env, path); return orig_createFileExclusively0(env, obj, redirect); } /* * Class: java_io_UnixFileSystem * Method: list0 * Signature: (Ljava/io/File;)[Ljava/lang/String; */ HOOK_JNI(jobjectArray, list0, JNIEnv *env, jobject obj, jobject file) { jobject redirect = IO::redirectPath(env, file); return orig_list0(env, obj, redirect); } /* * Class: java_io_UnixFileSystem * Method: createDirectory0 * Signature: (Ljava/io/File;)Z */ HOOK_JNI(jboolean, createDirectory0, JNIEnv *env, jobject obj, jobject path) { jobject redirect = IO::redirectPath(env, path); return orig_createDirectory0(env, obj, redirect); } /* * Class: java_io_UnixFileSystem * Method: setLastModifiedTime0 * Signature: (Ljava/io/File;J)Z */ HOOK_JNI(jboolean, setLastModifiedTime0, JNIEnv *env, jobject obj, jobject file, jobject time) { jobject redirect = IO::redirectPath(env, file); return orig_setLastModifiedTime0(env, obj, redirect, time); } /* * Class: java_io_UnixFileSystem * Method: setReadOnly0 * Signature: (Ljava/io/File;)Z */ HOOK_JNI(jboolean, setReadOnly0, JNIEnv *env, jobject obj, jobject file) { jobject redirect = IO::redirectPath(env, file); return orig_setReadOnly0(env, obj, redirect); } /* * Class: java_io_UnixFileSystem * Method: getSpace0 * Signature: (Ljava/io/File;I)J */ HOOK_JNI(jboolean, getSpace0, JNIEnv *env, jobject obj, jobject file, jint t) { jobject redirect = IO::redirectPath(env, file); return orig_getSpace0(env, obj, redirect, t); } void UnixFileSystemHook::init(JNIEnv *env) { const char *className = "java/io/UnixFileSystem"; JniHook::HookJniFun(env, className, "canonicalize0", "(Ljava/lang/String;)Ljava/lang/String;", (void *) new_canonicalize0, (void **) (&orig_canonicalize0), false); // JniHook::HookJniFun(env, className, "getBooleanAttributes0", "(Ljava/lang/String;)I", // (void *) new_getBooleanAttributes0, // (void **) (&orig_getBooleanAttributes0), false); JniHook::HookJniFun(env, className, "getLastModifiedTime0", "(Ljava/io/File;)J", (void *) new_getLastModifiedTime0, (void **) (&orig_getLastModifiedTime0), false); JniHook::HookJniFun(env, className, "setPermission0", "(Ljava/io/File;IZZ)Z", (void *) new_setPermission0, (void **) (&orig_setPermission0), false); JniHook::HookJniFun(env, className, "createFileExclusively0", "(Ljava/lang/String;)Z", (void *) new_createFileExclusively0, (void **) (&orig_createFileExclusively0), false); JniHook::HookJniFun(env, className, "list0", "(Ljava/io/File;)[Ljava/lang/String;", (void *) new_list0, (void **) (&orig_list0), false); JniHook::HookJniFun(env, className, "createDirectory0", "(Ljava/io/File;)Z", (void *) new_createDirectory0, (void **) (&orig_createDirectory0), false); JniHook::HookJniFun(env, className, "setLastModifiedTime0", "(Ljava/io/File;J)Z", (void *) new_setLastModifiedTime0, (void **) (&orig_setLastModifiedTime0), false); JniHook::HookJniFun(env, className, "setReadOnly0", "(Ljava/io/File;)Z", (void *) new_setReadOnly0, (void **) (&orig_setReadOnly0), false); JniHook::HookJniFun(env, className, "getSpace0", "(Ljava/io/File;I)J", (void *) new_getSpace0, (void **) (&orig_getSpace0), false); }
[ "1871357815@qq.com" ]
1871357815@qq.com
daaffa4eb12a15fdf84694bea161200b160c6965
05e7a96c4390e9cc51c22ecc25229836a0f2c960
/graphicsview-1/main.cpp
e912f67abd8b0c882e5b53fa6be2384fbe2fff17
[]
no_license
chgans/leda-playground
cafe51fc9bb3f0e6652e63c57ef2e11736b994e5
61c1bde60b527978330e3855f7647245e729a603
refs/heads/master
2020-12-24T15:49:50.339734
2016-03-09T04:50:13
2016-03-09T04:50:13
30,560,286
1
0
null
null
null
null
UTF-8
C++
false
false
8,233
cpp
#include "mainwindow.h" #include "mainview.h" #include "scene.h" #include <QApplication> #include <QDebug> #include <QGraphicsScene> #include <QGraphicsRectItem> #include <QGraphicsPolygonItem> #include <QGraphicsSimpleTextItem> #include <QGraphicsItemGroup> #include <QFile> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QColor> #include <QRgb> #include <QPen> #include <QBrush> #include <QFont> #include <QtMath> #include <QVector> QVector<double> readPosition(const QJsonArray a) { double x = 0.0, y = 0.0, z = 0.0; switch (a.size()) { case 3: z = a[2].toDouble(); case 2: x = a[0].toDouble(); y = a[1].toDouble(); break; default: qDebug() << "Invalid position"; break; } QVector<double> pos; pos << x << y << z; return pos; } QPen readPen(const QJsonObject &obj) { QPen pen; pen.setWidth(obj["width"].toDouble()); pen.setColor(QColor(obj["color"].toString())); return pen; } QBrush readBrush(const QJsonObject &obj) { QBrush brush; brush.setColor(obj["color"].toString()); brush.setStyle(Qt::SolidPattern); return brush; } QFont readFont(const QJsonObject &obj) { QFont font; font.setFamily(obj["family"].toString()); font.setPointSizeF(obj["size"].toDouble()); font.setWeight(QFont::Bold); font.setBold(false); font.setItalic(false); font.setUnderline(false); font.setStrikeOut(false); return font; } QVector<QPointF> readPointList(const QJsonArray a) { QVector<QPointF> points; foreach (QJsonValue val, a) { points << QPointF(val.toArray()[0].toDouble(), val.toArray()[1].toDouble()); } return points; } // Apply a radial symetry to path using the mid-point of the segment [p0,pn] and return the result. QPainterPath radialSymetricPath(const QPainterPath &path) { QPainterPath result; int n = path.elementCount(); result = path.toReversed(); result.setElementPositionAt(0, path.elementAt(0).x, path.elementAt(0).y); for (int i=1; i<(n-1); ++i) { int to = i, ref = to - 1, from1 = n - i, from2 = from1 - 1; qreal dx = path.elementAt(from2).x - path.elementAt(from1).x; qreal dy = path.elementAt(from2).y - path.elementAt(from1).y; result.setElementPositionAt(to, result.elementAt(ref).x - dx, result.elementAt(ref).y - dy); } result.setElementPositionAt(n-1, path.elementAt(n-1).x, path.elementAt(n-1).y); return result; } // Apply an axial symetry to path using the axis (p0,pn) and return the result QPainterPath axialSymetricPath(const QPainterPath &path) { QPainterPath result = path; int n = result.elementCount(); QLineF axis(result.elementAt(0).x, result.elementAt(0).y, result.elementAt(n-1).x, result.elementAt(n-1).y); for (int i=1; i<(n-1); ++i) { QLineF line(result.elementAt(0).x, result.elementAt(0).y, result.elementAt(i).x, result.elementAt(i).y); line.setAngle(axis.angle() + line.angleTo(axis)); result.setElementPositionAt(i, line.p2().x(), line.p2().y()); } return result; } #include "pcbpalettesettingsdialog.h" #include "pcbpalettemanager.h" #include "pcbpalettemanagerdialog.h" #include "designlayermanager.h" #include <QDir> int main(int argc, char *argv[]) { QApplication app(argc, argv); QCoreApplication::setOrganizationName("Libre EDA"); QCoreApplication::setOrganizationDomain("libreeda.org"); QCoreApplication::setApplicationName("graphicsview-1"); PcbPaletteManager *paletteManager = PcbPaletteManager::instance(); paletteManager->setPalettesPath(QDir::currentPath() + "/../graphicsview-1/"); paletteManager->loadPalettes(); DesignLayerManager *layerManager = DesignLayerManager::instance(); // layerManager->setProfilePath(); // layerManager->loadProfiles(); layerManager->loadFromDefaults(); PcbPalette *palette = paletteManager->activePalette(); foreach (DesignLayer *layer, layerManager->allLayers()) { QColor color = palette->color(PcbPalette::ColorRole(layer->index() + 1)); layer->setColor(color); } Scene scene(-5000, -5000, 10000, 10000); // um { QString filename("../graphicsview-1/test.json"); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { qDebug() << "Couldn't open" << filename; return 1; } QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error); if (doc.isNull()) { qDebug() << "Doc is null"; qDebug() << error.errorString() << error.offset; return 1; } if (!doc.isObject()) { qDebug() << "Doc is not an object!"; return 1; } // Header QJsonObject obj = doc.object(); qDebug() << obj["producer"].toString() << obj["version"].toString() << obj["author"].toString() << obj["license"].toString(); // Graphical items if (!obj.keys().contains("items")) { qDebug() << "Document has no items"; return 1; } QJsonArray items = obj["items"].toArray(); foreach (QJsonValue val, items) { if (!val.isObject()) { qDebug() << "Item is not an object"; continue; } obj = val.toObject(); QString type = obj["type"].toString(); if (type.isNull()) { qDebug() << "Item has no type"; continue; } QGraphicsItem *item; QVector<double> pos = readPosition(obj["position"].toArray()); QVector<QPointF> points = readPointList(obj["points"].toArray()); int layerIndex = obj["layer"].toInt(); DesignLayer *layer = layerManager->layerAt(layerIndex); QColor color = layer->color(); qDebug() << layer->defaultName() << layer->index() << layer->color(); if (type.toLower() == "rectangle") { QGraphicsRectItem *ritem = new QGraphicsRectItem(); ritem->setRect(QRectF(points[0], points[1])); QPen pen; pen.setWidth(0); QBrush brush(color); ritem->setPen(pen); ritem->setBrush(brush); item = ritem; } else if (type.toLower() == "polyline") { QGraphicsPolygonItem *pitem = new QGraphicsPolygonItem(); pitem->setPolygon(QPolygonF(points)); QPen pen; pen.setWidth(obj["width"].toInt()); pen.setColor(color); pen.setCapStyle(Qt::RoundCap); pen.setJoinStyle(Qt::RoundJoin); pitem->setPen(pen); item = pitem; } else { continue; } item->setPos(pos[0], pos[1]); item->setZValue(pos[2]); item->setOpacity(0.75); item->setFlag(QGraphicsItem::ItemIsMovable, true); item->setFlag(QGraphicsItem::ItemIsSelectable, true); item->setParentItem(layer); } layerManager->enableOnlyUsedLayers(); } MainWindow *w = new MainWindow; w->setGraphicsScene(&scene); w->show(); app.exec(); delete w; return 0; } /* QPainterPath: Element count=5 -> MoveTo(x=0, y=0) -> CurveTo(x=40, y=50) -> CurveToData(x=80, y=100) -> CurveToData(x=130, y=100) -> LineTo(x=180, y=30) QPainterPath: Element count=5 -> MoveTo(x=180, y=30) -> LineTo(x=130, y=100) -> CurveTo(x=80, y=100) -> CurveToData(x=40, y=50) -> CurveToData(x=0, y=0) QPainterPath: Element count=5 -> MoveTo(x=0, y=0) -> LineTo(x=-40, y=-50) -> CurveTo(x=-80, y=-100) -> CurveToData(x=-130, y=-100) -> CurveToData(x=-180, y=-30) */
[ "chgans@gna.org" ]
chgans@gna.org
ec1d202fe3bd9ece445a473a12725f2c0cc58838
cd70f8f1349310bfea59967d46373fac2ba4a65b
/course 1/Programming/semestr 1/lab2/8_bez_samoperetiniv/8.cpp
ee06ecaaa4747f6605cef353d2fe4b82699f8e79
[]
no_license
SymphonyOfTranquility/Univ
0a0ad37d4ff4b2d42c3ff6eb9785964f232f8ad7
c1f9d7f7537547ca8f96fc422adee6b7bc9cacc8
refs/heads/master
2023-02-06T18:12:26.556651
2020-12-29T20:12:58
2020-12-29T20:12:58
325,336,012
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,215
cpp
#include <iostream> #include <vector> #include <cmath> using namespace std; struct pt{ double x,y; }; double formula(pt a, pt b, pt p) { return (p.x - a.x)*(b.y - a.y) - (p.y - a.y)*(b.x - a.x); } bool proverka(vector<pt> m, long i, long n) { double a = formula(m[i], m[(i-2+n)%n], m[(i-1+n)%n]); double b = formula(m[i], m[(i-2+n)%n], m[(i-3+n)%n]); if (a == 0 || b == 0 || (a < 0 && b < 0) || (a > 0 && b > 0)) return false; return true; } bool global_prov(vector<pt> m, long i, long n) { if (i == n-1){ if (m[0].x == m[n-1].x && m[0].y == m[n-1].y) return false; if (i > 2 && (!proverka(m,i,n) || !proverka(m,0,n) || !proverka(m,1,n))) return false; } if (i > 0 && m[i].x == m[i-1].x && m[i].y == m[i-1].y) return false; if (i == 2 && formula(m[2], m[0], m[1]) == 0) return false; if (i >= 3 && !proverka(m,i,n)) return false; return true; } long double sum_next(pt a, pt b){ return ((a.x + b.x)*(a.y - b.y)/2.0); } long double plosh(vector<pt> a) { long n = a.size(); long double s = 0; for (long i = 0;i < n; ++i) s += sum_next(a[(i+1)%n],a[i]); return abs(s); } long double len(pt a, pt b){ return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)); } long double perimetr(vector<pt> a) { long double p = 0; long n = a.size(); for (long i = 0; i < n; ++i) p += len(a[i],a[(i+1)%n]); return p; } int main() { // принято что многоугольник выпуклый long n; bool err = false; vector<pt> mas; do{ if (err) cout << "n less than 3\n"; err = true; cin >> n; } while (n <= 2); mas.resize(n); for (long i = 0;i < mas.size(); ++i){ cin >> mas[i].x >> mas[i].y; if (!global_prov(mas,i,n)){ --i; cout << "mistake\nanother point, please:\n"; } } bool flag = true; long double s = plosh(mas); long double p = perimetr(mas); cout << s << ' ' << p; return 0; }
[ "mysechko01@gmail.com" ]
mysechko01@gmail.com
58a3fe98e0500b1ddb038817e11df6f8b02f09f4
9eac48c3beb78b984c918d86ae72954a73253e0c
/ROHIT KUMAR SINGH (Hacktober Contribution)/HackerRank/Counting_Sort_1.cpp
5f677990ff37340cc3c1ddcaf7608dfcf89e452f
[ "MIT" ]
permissive
herambchaudhari4121/Hacktoberfest-KIIT-2021
2986f8c82bd795c606a880b0f68f17c68816b11f
dd62a26c519abb786c7116c8ad6bf891451246e8
refs/heads/master
2023-08-19T19:16:34.123637
2021-10-31T05:46:00
2021-10-31T05:46:00
423,064,440
0
0
MIT
2021-10-31T05:49:11
2021-10-31T05:46:20
null
UTF-8
C++
false
false
684
cpp
#include<bits/stdc++.h> using namespace std; vector<int> countingSort(vector<int> arr) { map<int,int> mp; int no = *max_element(arr.begin(),arr.end()); vector<int> result; for(int &it:arr) { mp[it]++; } for(int i=0; i<no+1; i++) { if(mp[i]==0) { result.push_back(0); } else { result.push_back(mp[i]); } } return result; } int main() { int n; cin>>n; vector<int> v(n); for(int &it:v) cin>>it; vector<int> result = countingSort(v); for(int &it:result) cout<<it<<" "; //countingSort(v); return 0; }
[ "noreply@github.com" ]
herambchaudhari4121.noreply@github.com
0926be3c2d29a23c40f2149860a378d68d5d76a2
5fc03cffb8e7c0d83ec0feab7be675dc530b3396
/src/engine/physics/particle_generator.h
546b11322d9f21a97edab3ec1fd267f4fdf808f6
[]
no_license
simplejeff/liquidSim
205f6fdce4db280dbe7dd0bbb7673efca7690828
c0468d54374667b3b8e0733693d86e4246a28db6
refs/heads/master
2020-03-10T03:24:25.757580
2018-04-27T13:31:07
2018-04-27T13:31:07
129,163,891
0
0
null
null
null
null
UTF-8
C++
false
false
257
h
#ifndef PARTICLE_GENERATOR_H #define PARTICLE_GENERATOR_H #include <Eigen/Dense> using namespace Eigen; void InitRandom(); float Random(); VectorXf GenParticleInCube(size_t,float); VectorXf GenRandomVelocities(size_t); #endif // PARTICLE_GENERATOR_H
[ "jeffrey_hao@brown.edu" ]
jeffrey_hao@brown.edu
236741d68b3ba05de79b872aaecda117efa339cb
37cca16f12e7b1d4d01d6f234da6d568c318abee
/src/rice/pastry/socket/nat/connectivityverifiier/ConnectivityVerifierImpl_findExternalNodesHelper_3_receiveResult_3_1.hpp
c54da7f810897c6ed9fbe0155645beec41c6778f
[]
no_license
subhash1-0/thirstyCrow
e48155ce68fc886f2ee8e7802567c1149bc54206
78b7e4e3d2b9a9530ad7d66b44eacfe73ceea582
refs/heads/master
2016-09-06T21:25:54.075724
2015-09-21T17:21:15
2015-09-21T17:21:15
42,881,521
0
0
null
null
null
null
UTF-8
C++
false
false
2,412
hpp
// Generated from /pastry-2.1/src/rice/pastry/socket/nat/connectivityverifiier/ConnectivityVerifierImpl.java #pragma once #include <java/util/fwd-pastry-2.1.hpp> #include <rice/fwd-pastry-2.1.hpp> #include <rice/pastry/socket/nat/connectivityverifiier/fwd-pastry-2.1.hpp> #include <java/lang/Object.hpp> #include <java/lang/Runnable.hpp> struct default_init_tag; class rice::pastry::socket::nat::connectivityverifiier::ConnectivityVerifierImpl_findExternalNodesHelper_3_receiveResult_3_1 : public virtual ::java::lang::Object , public virtual ::java::lang::Runnable { public: typedef ::java::lang::Object super; void run() override; // Generated ConnectivityVerifierImpl_findExternalNodesHelper_3_receiveResult_3_1(ConnectivityVerifierImpl_findExternalNodesHelper_3 *ConnectivityVerifierImpl_findExternalNodesHelper_3_this, ::rice::Continuation* deliverResultToMe, ::java::util::Collection* result); static ::java::lang::Class *class_(); ConnectivityVerifierImpl_findExternalNodesHelper_3 *ConnectivityVerifierImpl_findExternalNodesHelper_3_this; ::rice::Continuation* deliverResultToMe; ::java::util::Collection* result; private: virtual ::java::lang::Class* getClass0(); friend class ConnectivityVerifierImpl; friend class ConnectivityVerifierImpl_getInetSocketAddressLookup_1; friend class ConnectivityVerifierImpl_findExternalNodes_2; friend class ConnectivityVerifierImpl_findExternalNodesHelper_3; friend class ConnectivityVerifierImpl_findExternalNodesHelper_3_receiveException_3_2; friend class ConnectivityVerifierImpl_findExternalAddress_4; friend class ConnectivityVerifierImpl_findExternalAddressHelper_5; friend class ConnectivityVerifierImpl_findExternalAddressHelper_5_receiveResult_5_1; friend class ConnectivityVerifierImpl_findExternalAddressHelper_5_receiveException_5_2; friend class ConnectivityVerifierImpl_verifyConnectivity_6; friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_1; friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_2; friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_2_udpSuccess_6_2_1; friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_2_tcpSuccess_6_2_2; friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_2_receiveException_6_2_3; };
[ "sgurjar@adobe.com" ]
sgurjar@adobe.com
098607574dba40af93cac4f5e38cffd90c00d1f7
d8f854a479641a793b775fa6b573543e32694a37
/src/sender.hpp
79b57cc6ab393e9946d493063362e6cc7dd27b63
[]
no_license
dudelka/file_streamer
e8d3def168160d2ca05e863cff449a39f767bde5
f2813fd960b700036208504ca209b71cc4f6aa0a
refs/heads/main
2023-08-01T00:34:49.133633
2021-09-12T18:19:17
2021-09-12T18:19:17
395,458,547
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
hpp
#pragma once #include "socket.hpp" #include "packet.hpp" #include <string> #ifdef CLIENT_MODE #include "utils.hpp" #include <cstdint> #include <atomic> #include <queue> #include <list> class Sender : public Multithreaded { public: Sender(const std::string& send_address, uint32_t resend_timeout); void Connect(); void Shutdown(); void PushPacket(Packet packet); virtual void Run() override; void AckPacket(uint32_t id, uint32_t packet_num); private: Socket sock_; uint32_t resend_timeout_; std::queue<Packet> fifo_; std::list<Packet> not_ack_packets_; std::atomic<bool> has_packets_ {false}; std::atomic<bool> has_not_ack_packets_ {false}; LockPrimitives fifo_lock_; LockPrimitives ack_lock_; void SendControlPacket(const PacketType packet_type); void ResendPackets(); }; #elif SERVER_MODE class Sender { public: explicit Sender(const std::string& send_address); void ProcessPacket(Packet packet); private: Socket sock_; }; #endif
[ "nbazargarmaev@gmail.com" ]
nbazargarmaev@gmail.com
dc2ee6da048b725083e1de425dcda1c33b830294
9b26f861f7ceb50c55b93ff115dbdabf3fe77b52
/PB14210043/hw2.cpp
1a64306ad45b3bc2a68aa85f47fae49fef245eba
[]
no_license
dyh127/homework2
3840f2271533908b82dce86a5c33e9c032cc6cc4
5bb51d7d4b6bcf1b1a92a2af09ceaf7970e25ea0
refs/heads/master
2021-07-12T00:00:37.257474
2017-10-16T03:39:35
2017-10-16T03:39:35
106,658,948
0
0
null
2017-10-12T07:22:32
2017-10-12T07:22:32
null
UTF-8
C++
false
false
18,712
cpp
#define _CRT_NONSTDC_NO_WARNINGS #define PI 3.1415926f #include "opencv.hpp" #include "math.h" #include <cv.h> #include <iostream> using namespace cv; using namespace std; #define IN #define OUT #define MY_OK 1 #define MY_FAIL -1 // the threshold of converting gradient map into a binary map; #define g2b_threshold 225 //#define test_guan // this is the value when the gradient map pixels beyond the g2b_threshold will be assigned. #define G_binaryvalue 1 //cos sin list float cos_list[360] = { 1,0.999848,0.999391,0.99863,0.997564,0.996195,0.994522,0.992546,0.990268,0.987688,0.984808,0.981627,0.978148,0.97437,0.970296,0.965926,0.961262,0.956305,0.951057,0.945519,0.939693,0.93358,0.927184,0.920505,0.913545,0.906308,0.898794,0.891007,0.882948,0.87462,0.866025,0.857167,0.848048,0.838671,0.829038,0.819152,0.809017,0.798636,0.788011,0.777146,0.766044,0.75471,0.743145,0.731354,0.71934,0.707107,0.694658,0.681998,0.669131,0.656059,0.642788,0.62932,0.615662,0.601815,0.587785,0.573577,0.559193,0.544639,0.529919,0.515038,0.5,0.48481,0.469472,0.453991,0.438371,0.422618,0.406737,0.390731,0.374607,0.358368,0.34202,0.325568,0.309017,0.292372,0.275637,0.258819,0.241922,0.224951,0.207912,0.190809,0.173648,0.156435,0.139173,0.121869,0.104529,0.0871558,0.0697565,0.0523361,0.0348996,0.0174525,7.54979e-08,-0.0174524,-0.0348995,-0.0523358,-0.0697564,-0.0871556,-0.104529,-0.121869,-0.139173,-0.156434,-0.173648,-0.190809,-0.207912,-0.224951,-0.241922,-0.258819,-0.275637,-0.292372,-0.309017,-0.325568,-0.34202,-0.358368,-0.374607,-0.390731,-0.406737,-0.422618,-0.438371,-0.45399,-0.469471,-0.48481,-0.5,-0.515038,-0.529919,-0.544639,-0.559193,-0.573576,-0.587785,-0.601815,-0.615661,-0.62932,-0.642787,-0.656059,-0.669131,-0.681998,-0.694658,-0.707107,-0.71934,-0.731354,-0.743145,-0.754709,-0.766044,-0.777146,-0.788011,-0.798635,-0.809017,-0.819152,-0.829037,-0.83867,-0.848048,-0.857167,-0.866025,-0.87462,-0.882948,-0.891006,-0.898794,-0.906308,-0.913545,-0.920505,-0.927184,-0.93358,-0.939693,-0.945518,-0.951056,-0.956305,-0.961262,-0.965926,-0.970296,-0.97437,-0.978148,-0.981627,-0.984808,-0.987688,-0.990268,-0.992546,-0.994522,-0.996195,-0.997564,-0.99863,-0.999391,-0.999848,-1,-0.999848,-0.999391,-0.99863,-0.997564,-0.996195,-0.994522,-0.992546,-0.990268,-0.987688,-0.984808,-0.981627,-0.978148,-0.97437,-0.970296,-0.965926,-0.961262,-0.956305,-0.951057,-0.945519,-0.939693,-0.93358,-0.927184,-0.920505,-0.913545,-0.906308,-0.898794,-0.891007,-0.882948,-0.87462,-0.866026,-0.857167,-0.848048,-0.838671,-0.829038,-0.819152,-0.809017,-0.798636,-0.788011,-0.777146,-0.766045,-0.75471,-0.743145,-0.731354,-0.71934,-0.707107,-0.694659,-0.681998,-0.669131,-0.656059,-0.642788,-0.629321,-0.615662,-0.601815,-0.587785,-0.573577,-0.559193,-0.544639,-0.529919,-0.515038,-0.5,-0.48481,-0.469472,-0.453991,-0.438371,-0.422618,-0.406737,-0.390731,-0.374607,-0.358368,-0.342021,-0.325568,-0.309017,-0.292372,-0.275638,-0.258819,-0.241922,-0.224951,-0.207912,-0.190809,-0.173649,-0.156435,-0.139173,-0.12187,-0.104529,-0.0871562,-0.069757,-0.0523361,-0.0348998,-0.0174523,1.19249e-08,0.0174518,0.0348993,0.0523357,0.0697566,0.0871557,0.104528,0.121869,0.139173,0.156434,0.173648,0.190809,0.207911,0.224951,0.241921,0.258819,0.275637,0.292371,0.309017,0.325568,0.34202,0.358368,0.374606,0.390731,0.406736,0.422618,0.438371,0.45399,0.469472,0.484809,0.499999,0.515038,0.529919,0.544639,0.559193,0.573576,0.587785,0.601815,0.615661,0.62932,0.642788,0.656059,0.66913,0.681998,0.694658,0.707107,0.71934,0.731353,0.743145,0.75471,0.766044,0.777146,0.788011,0.798635,0.809017,0.819152,0.829037,0.838671,0.848048,0.857167,0.866025,0.87462,0.882947,0.891007,0.898794,0.906308,0.913545,0.920505,0.927184,0.93358,0.939693,0.945518,0.951056,0.956305,0.961262,0.965926,0.970296,0.97437,0.978148,0.981627,0.984808,0.987688,0.990268,0.992546,0.994522,0.996195,0.997564,0.99863,0.999391,0.999848 }; float sin_list[360] = { 0,0.0174524,0.0348995,0.052336,0.0697565,0.0871557,0.104528,0.121869,0.139173,0.156434,0.173648,0.190809,0.207912,0.224951,0.241922,0.258819,0.275637,0.292372,0.309017,0.325568,0.34202,0.358368,0.374607,0.390731,0.406737,0.422618,0.438371,0.453991,0.469472,0.48481,0.5,0.515038,0.529919,0.544639,0.559193,0.573576,0.587785,0.601815,0.615662,0.62932,0.642788,0.656059,0.669131,0.681998,0.694658,0.707107,0.71934,0.731354,0.743145,0.75471,0.766044,0.777146,0.788011,0.798635,0.809017,0.819152,0.829038,0.838671,0.848048,0.857167,0.866025,0.87462,0.882948,0.891007,0.898794,0.906308,0.913545,0.920505,0.927184,0.93358,0.939693,0.945519,0.951057,0.956305,0.961262,0.965926,0.970296,0.97437,0.978148,0.981627,0.984808,0.987688,0.990268,0.992546,0.994522,0.996195,0.997564,0.99863,0.999391,0.999848,1,0.999848,0.999391,0.99863,0.997564,0.996195,0.994522,0.992546,0.990268,0.987688,0.984808,0.981627,0.978148,0.97437,0.970296,0.965926,0.961262,0.956305,0.951056,0.945519,0.939693,0.93358,0.927184,0.920505,0.913545,0.906308,0.898794,0.891007,0.882948,0.87462,0.866025,0.857167,0.848048,0.838671,0.829038,0.819152,0.809017,0.798636,0.788011,0.777146,0.766044,0.75471,0.743145,0.731354,0.71934,0.707107,0.694658,0.681998,0.669131,0.656059,0.642788,0.62932,0.615662,0.601815,0.587785,0.573576,0.559193,0.544639,0.529919,0.515038,0.5,0.48481,0.469472,0.45399,0.438371,0.422618,0.406737,0.390731,0.374607,0.358368,0.34202,0.325568,0.309017,0.292372,0.275637,0.258819,0.241922,0.224951,0.207912,0.190809,0.173648,0.156435,0.139173,0.121869,0.104529,0.0871558,0.0697565,0.052336,0.0348996,0.0174525,5.35898e-08,-0.0174522,-0.0348995,-0.0523359,-0.0697566,-0.0871557,-0.104528,-0.121869,-0.139173,-0.156434,-0.173648,-0.190809,-0.207912,-0.224951,-0.241922,-0.258819,-0.275637,-0.292372,-0.309017,-0.325568,-0.34202,-0.358368,-0.374606,-0.390731,-0.406737,-0.422618,-0.438371,-0.45399,-0.469472,-0.48481,-0.5,-0.515038,-0.529919,-0.544639,-0.559193,-0.573576,-0.587785,-0.601815,-0.615661,-0.62932,-0.642788,-0.656059,-0.669131,-0.681998,-0.694658,-0.707107,-0.71934,-0.731354,-0.743145,-0.75471,-0.766044,-0.777146,-0.788011,-0.798635,-0.809017,-0.819152,-0.829037,-0.838671,-0.848048,-0.857167,-0.866025,-0.87462,-0.882948,-0.891007,-0.898794,-0.906308,-0.913545,-0.920505,-0.927184,-0.93358,-0.939693,-0.945519,-0.951056,-0.956305,-0.961262,-0.965926,-0.970296,-0.97437,-0.978148,-0.981627,-0.984808,-0.987688,-0.990268,-0.992546,-0.994522,-0.996195,-0.997564,-0.99863,-0.999391,-0.999848,-1,-0.999848,-0.999391,-0.99863,-0.997564,-0.996195,-0.994522,-0.992546,-0.990268,-0.987688,-0.984808,-0.981627,-0.978148,-0.97437,-0.970296,-0.965926,-0.961262,-0.956305,-0.951057,-0.945519,-0.939693,-0.93358,-0.927184,-0.920505,-0.913545,-0.906308,-0.898794,-0.891007,-0.882948,-0.87462,-0.866026,-0.857167,-0.848048,-0.838671,-0.829038,-0.819152,-0.809017,-0.798636,-0.788011,-0.777146,-0.766045,-0.75471,-0.743145,-0.731354,-0.71934,-0.707107,-0.694659,-0.681998,-0.669131,-0.656059,-0.642788,-0.629321,-0.615661,-0.601815,-0.587785,-0.573576,-0.559193,-0.544639,-0.529919,-0.515038,-0.5,-0.48481,-0.469472,-0.453991,-0.438371,-0.422618,-0.406737,-0.390731,-0.374607,-0.358368,-0.34202,-0.325568,-0.309017,-0.292372,-0.275637,-0.258819,-0.241922,-0.224951,-0.207912,-0.190809,-0.173648,-0.156434,-0.139173,-0.12187,-0.104528,-0.0871559,-0.0697568,-0.052336,-0.0348997,-0.0174524 }; /* int cos_sin_list() { for (int i = 0;i < 360;i++) { if (abs(float(cos(float(i) / 180 * PI)) - cos_list[i] )> 0.01) { cout << float(cos(float(i) / 180 * PI))<<" "<<cos_list[i] << " cos "<<endl; } } for (int i = 0;i < 360;i++) { if (abs((float)(sin(float(i)/ 180 * PI)) - sin_list[i])> 0.01) { cout << (float)(sin(float(i)) / 180 * PI) <<" "<<sin_list[i]<<" sin " <<i<<endl; } } cout << "end" << endl; return 0; } int is_near(//判断是否需要跳过这次圆心-半径对 IN int min_radius_dist, IN int min_center_dist, IN int *x, IN int *y, IN int *radius, IN int row_i, IN int col_j, IN int r, IN int len ) { int tresh = min_center_dist*min_center_dist; for (int i = len-1;i >=0; i--) { if (x[i] == row_i && y[i] == col_j) { if (r - radius[i] < min_radius_dist) return 1; } int a = x[i] - row_i; int b = y[i] - col_j; if (a*a + b*b < min_radius_dist) return 1; } return 0; } */ struct circle_centre { int x; int y; int radius; float value; struct circle_centre *next; }; int ustc_ConvertBgr2Gray(Mat bgrImg, Mat& grayImg) { if (NULL == bgrImg.data) { cout << "image input failed" << '\n'; return -1; } int width = bgrImg.cols; int height = bgrImg.rows; int k1, k2, k3, t; for (int row_i = 0; row_i < height; row_i++) { k1 = row_i*width; for (int col_j = 0; col_j < width; col_j++) { k2 = k1 + col_j; k3 = k2 * 3; t = bgrImg.data[k3] * 114 + bgrImg.data[k3 + 1] * 587 + bgrImg.data[k3 + 2] * 299; grayImg.data[k2] = t / 1000; } } return 1; } //功能说明:找到图像中所有圆心在图像内的圆,得到中心点和半径 //colorImg:用来搜索圆形目标的彩色图像 //min_radius:需要搜索的圆的最小半径 //max_radius:需要搜索的圆的最大半径 //min_center_dist:找到的圆心之间的最小距离 //min_radius_dist:同心圆半径之间的最小差距 //max_circle_diff:阈值,圆周差分值低于此阈值,不是圆 //x:数组,存储所有的圆的中心点x坐标 //y:数组,存储所有的圆的中心点y坐标 //radius:数组,存储所有的圆的半径值 //circle_cnt:图像中找到的圆的数目 //max_circle:外部传入参数,圆的数目上限。如果图像中圆的数目超过此参数,根据差分值由大到小进行排序 //返回值:MY_OK或者MY_FAIL int ustc_Find_Circles_By_Difference( Mat colorImg, int min_radius, int max_radius, int min_center_dist, int min_radius_dist, int max_circle_diff, int* x, int* y, int* radius, int* circle_cnt, int max_circle) { int height = colorImg.rows; int width = colorImg.cols; *circle_cnt = 0; int thresh; struct circle_centre head_circ; Mat grayImg(height, width, CV_8UC1); int dx_in, dx_out, dy_in, dy_out; int indx_in, indx_out, idx; uchar *p_img = grayImg.data; int sum_in, sum_out; float average; *circle_cnt = 0; ustc_ConvertBgr2Gray(colorImg, grayImg); head_circ.next = NULL; for (int row_i = 0;row_i < height;row_i++) { for (int col_j = 0;col_j < width;col_j++) { for (int r = min_radius;r <= max_radius;r++) { if (r > row_i || row_i + r > height || r > col_j || col_j + r > width) { continue; } int r_in = r - 5; int r_out = r + 5; sum_in = 0; sum_out = 0; for (int theta = 0;theta < 360;theta++) { dx_in = r_in * cos_list[theta]; dx_out = r_out * cos_list[theta]; dy_in = r_in * sin_list[theta]; dy_out = r_out * sin_list[theta]; sum_in += p_img[(row_i + dx_in)*width + col_j + dy_in]; sum_out += p_img[(row_i + dx_out)*width + col_j + dy_out]; } average = fabs(sum_in - sum_out) / 360; if (average>max_circle_diff) { struct circle_centre * circle = &head_circ; int flag = 1; while (circle->next != NULL) { //半径差小于要求 以及 距离小于要求的只允许有一个圆 if (abs(circle->next->radius - r) < min_radius && abs(circle->next->x - row_i) + abs(circle->next->y - col_j) < min_center_dist) { //现存已有更大差值者 if (circle->next->value > average) { flag = 0; break; } else { struct circle_centre * delete_circle = circle->next; circle->next = circle->next->next; free(delete_circle); *circle_cnt -= 1; continue; } } circle = circle->next; } if (flag) { if (*circle_cnt >= max_circle) { continue; } *circle_cnt += 1; struct circle_centre * new_circle = new circle_centre; circle = &head_circ; while (circle->next != NULL && circle->next->value > average) { circle = circle->next; } new_circle->x = row_i; new_circle->y = col_j; new_circle->radius = r; new_circle->value = average; new_circle->next = circle->next; circle->next = new_circle; } } } } } /*//create a Mat array to store the total sum of a circle Mat sum_in(height, width, CV_32SC3); Mat sum_out(height, width, CV_32SC3); Mat gradient(height, width, CV_8UC3); Mat anglecalc(height, width, CV_8UC3); int total_siz = height*width * sizeof(int)*3; int total_length = height*width * 3; head_circ.next = NULL; ustc_CalcGrad(colorImg, gradient, g2b_threshold); // basic algorithm is to each certain r,theta , to each circle center // add the pixel's value of the inner circle and of outer circle to the average array. // after theta loops from 0-359, the whole picture's circle's average have already been calculated // then we can calculate the thresh hold and decide whether there is circle centre with the certain radius r. int dx_in, dx_out, dy_in, dy_out,xdx_in,xdx_out,idx_x; int indx_in, indx_out, idx; for (int r = min_radius;r <= max_radius;r++) { int r_in = r - 5; int r_out = r + 5; memset(sum_in.data, 0, total_siz); memset(sum_out.data, 0, total_siz); memset(anglecalc.data , 0, total_length); for (int theta = 0;theta < 360;theta++) { dx_in = r_in * cos_list[theta]; dx_out = r_out * cos_list[theta]; dy_in = r_in * sin_list[theta]; dy_out = r_out * sin_list[theta]; uchar *p_img=colorImg.data; int *p_sum_in = (int *)sum_in.data; int *p_sum_out = (int *)sum_out.data; uchar *p_grad = gradient.data; uchar *p_calc = anglecalc.data; for (int row_i = 0;row_i < height;row_i++) { if (row_i + dx_out < 0 || row_i + dx_out >= height) { continue; } // inner circle's x-coordinate index xdx_in = (row_i + dx_in)*width; //outer circle's y-coordinate index xdx_out = (row_i + dx_out)*width; // the circle's centre point x_index idx_x = row_i*width; for (int col_j = 0;col_j < width;col_j++) { if (col_j + dy_out < 0 || col_j + dy_out >= width) { continue; } indx_in = xdx_in + col_j + dy_in; indx_out = xdx_out + col_j + dy_out; idx = idx_x + col_j; // 3 channel indx_in = indx_in+ indx_in+ indx_in; indx_out = indx_out+ indx_out+ indx_out; idx = idx+ idx+ idx; // if the outer cirle's pixel overstep the ranges of array then continue; p_sum_in[idx] += (p_img[indx_in])* (p_grad[idx]); p_sum_in[idx+1] += (p_img[indx_in+1])* (p_grad[idx+1]); p_sum_in[idx+2] += (p_img[indx_in+2])* (p_grad[idx+2]); p_sum_out[idx] += (p_img[indx_out]) * (p_grad[idx]); p_sum_out[idx + 1] += (p_img[indx_out + 1]) * (p_grad[idx+1]); p_sum_out[idx + 2] += (p_img[indx_out + 2]) * (p_grad[idx+2]); p_calc[idx] += p_grad[idx]; idx++; p_calc[idx] += p_grad[idx]; idx++; p_calc[idx] += p_grad[idx]; } } } int *p_sum_in = (int *)sum_in.data; int *p_sum_out = (int *)sum_out.data; uchar *p_anglecalc = anglecalc.data; for (int row_i = 0;row_i < height;row_i++) { int k0 = row_i*width; for (int col_j = 0;col_j < width;col_j++) { int k1 = k0 +col_j; //3 channel k1 = k1 + k1 + k1; // if the proportion of circle less than one fouth then continue; if (p_anglecalc[k1] < 90) { continue; } float average = abs(p_sum_in[k1] - p_sum_out[k1])*1.0f / p_anglecalc[k1]; struct circle_centre * circle = &head_circ; #ifdef test_guan cout << average << '\t'; #endif if (average > max_circle_diff) { while (circle->next != NULL) { //半径差小于要求 以及 距离小于要求的只允许有一个圆 if (abs(circle->next->radius - r) < min_radius && abs(circle->next->x - row_i) + abs(circle->next->y - col_j) < min_center_dist) { //现存已有更大差值者 if (circle->next->value > average) { break; } else { struct circle_centre * delete_circle = circle->next; circle->next = circle->next->next; free(delete_circle); continue; } } circle = circle->next; //头插法插入合格元素 } if (NULL == circle) { int cnt = 0; struct circle_centre * new_circle = (struct circle_centre *) malloc(sizeof(struct circle_centre)); circle = &head_circ; while (circle->next != NULL && circle->next->value > average) { cnt++; circle = circle->next; } if (cnt >= max_circle) continue; new_circle->x = row_i; new_circle->y = col_j; new_circle->radius = r; new_circle->value = average; new_circle->next = circle->next; circle->next = new_circle; } } else { ; } k1 += 1; if (p_anglecalc[k1] < 90) { continue; } average = abs(p_sum_in[k1] - p_sum_out[k1])*1.0f / p_anglecalc[k1]; circle = &head_circ; if (average > max_circle_diff) { while (circle->next != NULL) { if (abs(circle->next->radius - r) < min_radius && abs(circle->next->x - row_i) + abs(circle->next->y - col_j) < min_center_dist) { if (circle->next->value > average) { break; } else { struct circle_centre * delete_circle = circle->next; circle->next = circle->next->next; free(delete_circle); continue; } } circle = circle->next; } if (NULL == circle) { int cnt = 0; struct circle_centre * new_circle = (struct circle_centre *) malloc(sizeof(struct circle_centre)); circle = &head_circ; while (circle->next != NULL && circle->next->value > average) { cnt++; circle = circle->next; } if (cnt >= max_circle) continue; new_circle->x = row_i; new_circle->y = col_j; new_circle->radius = r; new_circle->value = average; new_circle->next = circle->next; circle->next = new_circle; } } else { ; } k1 += 1; if (p_anglecalc[k1] < 90) { continue; } average = abs(p_sum_in[k1] - p_sum_out[k1])*1.0f / p_anglecalc[k1]; circle = &head_circ; if (average > max_circle_diff) { while (circle->next != NULL) { if (abs(circle->next->radius - r) < min_radius && abs(circle->next->x - row_i) + abs(circle->next->y - col_j) < min_center_dist) { if (circle->next->value > average) { break; } else { struct circle_centre * delete_circle = circle->next; circle->next = circle->next->next; free(delete_circle); continue; } } circle = circle->next; } if (NULL == circle) { int cnt = 0; struct circle_centre * new_circle = (struct circle_centre *) malloc(sizeof(struct circle_centre)); circle = &head_circ; while (circle->next != NULL && circle->next->value > average) { cnt++; circle = circle->next; } if (cnt >= max_circle) continue; new_circle->x = row_i; new_circle->y = col_j; new_circle->radius = r; new_circle->value = average; new_circle->next = circle->next; circle->next = new_circle; } } else { ; } } } }*/ *circle_cnt = 0; struct circle_centre *circle = head_circ.next; while (circle != NULL) { x[*circle_cnt] = circle->x; y[*circle_cnt] = circle->y; radius[*circle_cnt] = circle->radius; *circle_cnt += 1; circle = circle->next; } return MY_OK; }
[ "noreply@github.com" ]
dyh127.noreply@github.com
599c82acea40477281e2a0e2e79cb2e2e65d1c9e
eead3440d191939b0288b33599a1a9bdb72e4280
/Arrays & Strings/spiral_anti.cpp
161b419e1046022a912f7b20c79ed48bcf2f66a5
[]
no_license
Akp6528/DS-Algo
f1cd1d2624be6747e237055e8c1bced7ca499e00
63e38c9263e46332f62011ce053555fc9cdf7021
refs/heads/main
2023-04-18T12:08:09.078473
2021-05-04T08:28:04
2021-05-04T08:28:04
300,832,214
1
1
null
2020-10-14T13:24:57
2020-10-03T08:23:58
C++
UTF-8
C++
false
false
939
cpp
#include<iostream> using namespace std; void spiral(int a[][100], int m, int n) { int startRow = 0; int startCol = 0; int endRow = m-1; int endCol = n-1; while(startRow <= endRow and startCol <= endCol){ // 1 for(int i=startRow; i<=endRow; i++) cout<<a[i][startCol]<<", "; startCol++; //2 for(int i=startCol; i<=endCol; i++) cout<<a[endRow][i] <<", "; endRow--; //3 if(endRow > startRow){ for(int i=endRow; i>=startRow; i--) cout<<a[i][endCol]<<", "; endCol--; } //4 if(endCol > startCol) { for(int i=endCol; i>=startCol; i--) cout<<a[startRow][i]<<", "; startRow++; } } } int main(){ int a[100][100] ; int m,n; cin>>m>>n; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ cin>>a[i][j]; } } spiral(a,m,n); cout<<"END"; return 0; }
[ "pandeyashwani999@gmail.com" ]
pandeyashwani999@gmail.com
92f8b43d068c2e82a3228cdccdb6a114df9b7212
ee22fa7476a52f3fe2f9bc88d6c8f43f614cdba6
/Codeforces/D2-256A.cpp
a640fad785667bb2bf692f9c83e95e850a733b4f
[]
no_license
Sillyplus/Solution
704bff07a29709f64e3e1634946618170d426b72
48dcaa075852f8cda1db22ec1733600edea59422
refs/heads/master
2020-12-17T04:53:07.089633
2016-07-02T10:01:28
2016-07-02T10:01:28
21,733,756
0
0
null
null
null
null
UTF-8
C++
false
false
511
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> using namespace std; const int MN = 10010; int a1, a2, a3; int b1, b2, b3; int n, a, b, ans; int main() { cin >> a1 >> a2 >> a3; cin >> b1 >> b2 >> b3; cin >> n; a = a1 + a2 + a3; b = b1 + b2 + b3; ans = 0; ans = ans + (a % 5 == 0 ? (a/5): (a/5)+1); ans = ans + (b % 10 == 0 ? (b/10): (b/10)+1); if (ans <= n) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
[ "oi_boy@sina.cn" ]
oi_boy@sina.cn
2456f9c26d8c92f9cbdb4fc19f2abbdfdec5250d
5470644b5f0834b9646649da365c96101a2f9b2a
/Sources/Elastos/Frameworks/Droid/Base/Core/inc/text/method/DigitsKeyListener.h
792dd387ebee09cbe44de8e8a1cc67d50537801e
[]
no_license
dothithuy/ElastosRDK5_0
42372da3c749170581b5ee9b3884f4a27ae81608
2cf231e9f09f8b3b8bcacb11080b4a87d047833f
refs/heads/master
2021-05-13T15:02:22.363934
2015-05-25T01:54:38
2015-05-25T01:54:38
116,755,452
1
0
null
2018-01-09T02:33:06
2018-01-09T02:33:06
null
UTF-8
C++
false
false
2,485
h
#ifndef __DigitsKeyListener_H__ #define __DigitsKeyListener_H__ #include "text/method/NumberKeyListener.h" namespace Elastos { namespace Droid { namespace Text { namespace Method { extern "C" const InterfaceID EIID_DigitsKeyListener; /** * For digits-only text entry * <p></p> * As for all implementations of {@link KeyListener}, this class is only concerned * with hardware keyboards. Software input methods have no obligation to trigger * the methods in this class. */ class DigitsKeyListener : public NumberKeyListener { public: /** * Allocates a DigitsKeyListener that accepts the digits 0 through 9. */ DigitsKeyListener(); /** * Allocates a DigitsKeyListener that accepts the digits 0 through 9, * plus the minus sign (only at the beginning) and/or decimal point * (only one per field) if specified. */ DigitsKeyListener( /* [in] */ Boolean sign, /* [in] */ Boolean decimal); static CARAPI_(AutoPtr<IDigitsKeyListener>) GetInstance(); static CARAPI_(AutoPtr<IDigitsKeyListener>) GetInstance( /* [in] */ Boolean sign, /* [in] */ Boolean decimal); static CARAPI_(AutoPtr<IDigitsKeyListener>) GetInstance( /* [in] */ const String& accepted); CARAPI_(void) Init(); CARAPI_(void) Init( /* [in] */ Boolean sign, /* [in] */ Boolean decimal); CARAPI_(Int32) GetInputType(); //@Override CARAPI_(AutoPtr<ICharSequence>) Filter( /* [in] */ ICharSequence* source, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ ISpanned* dest, /* [in] */ Int32 dstart, /* [in] */ Int32 dend); protected: //@Override CARAPI_(AutoPtr< ArrayOf<Char32> >) GetAcceptedChars(); protected: static const Int32 SIGN;// = 1; static const Int32 DECIMAL;// = 2; /** * The characters that are used. * * @see KeyEvent#getMatch * @see #getAcceptedChars */ AutoPtr< ArrayOf<Char32> > mAccepted; private: Boolean mSign; Boolean mDecimal; static const Char32* CHARACTERS[]; static const Char32 CHARACTERS0[]; static const Char32 CHARACTERS1[]; static const Char32 CHARACTERS2[]; static const Char32 CHARACTERS3[]; static AutoPtr< ArrayOf< IDigitsKeyListener* > > sInstance;// = new DigitsKeyListener[4]; }; } // namespace Method } // namespace Text } // namepsace Droid } // namespace Elastos #endif // __DigitsKeyListener_H__
[ "chen.yunzhi@kortide.com" ]
chen.yunzhi@kortide.com
3996cb3362930a148e14eb83392721e72822f187
eb2402919a6cd96eef93473c14cb946b2eaa5f7a
/source/d3d9/d3d9_runtime.cpp
466132ad29e0cfe00b7b8dd4aa1d31a2399d1b89
[ "BSD-3-Clause" ]
permissive
acourreges/reshade
f860f92b3432afd52557421afff9ea67115482ea
f2560b05b9cac0ea355fd63451f594d7e424fb11
refs/heads/master
2020-03-17T09:23:02.832200
2018-05-14T17:38:15
2018-05-14T17:38:15
133,472,624
18
4
null
2018-05-15T06:56:10
2018-05-15T06:56:10
null
UTF-8
C++
false
false
28,196
cpp
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "log.hpp" #include "d3d9_runtime.hpp" #include "d3d9_effect_compiler.hpp" #include "effect_lexer.hpp" #include "input.hpp" #include <imgui.h> #include <algorithm> const auto D3DFMT_INTZ = static_cast<D3DFORMAT>(MAKEFOURCC('I', 'N', 'T', 'Z')); const auto D3DFMT_DF16 = static_cast<D3DFORMAT>(MAKEFOURCC('D', 'F', '1', '6')); const auto D3DFMT_DF24 = static_cast<D3DFORMAT>(MAKEFOURCC('D', 'F', '2', '4')); namespace reshade::d3d9 { d3d9_runtime::d3d9_runtime(IDirect3DDevice9 *device, IDirect3DSwapChain9 *swapchain) : runtime(0x9300), _device(device), _swapchain(swapchain) { assert(device != nullptr); assert(swapchain != nullptr); _device->GetDirect3D(&_d3d); assert(_d3d != nullptr); D3DCAPS9 caps; D3DADAPTER_IDENTIFIER9 adapter_desc; D3DDEVICE_CREATION_PARAMETERS creation_params; _device->GetDeviceCaps(&caps); _device->GetCreationParameters(&creation_params); _d3d->GetAdapterIdentifier(creation_params.AdapterOrdinal, 0, &adapter_desc); _vendor_id = adapter_desc.VendorId; _device_id = adapter_desc.DeviceId; _behavior_flags = creation_params.BehaviorFlags; _num_samplers = caps.MaxSimultaneousTextures; _num_simultaneous_rendertargets = std::min(caps.NumSimultaneousRTs, DWORD(8)); } bool d3d9_runtime::init_backbuffer_texture() { // Get back buffer surface HRESULT hr = _swapchain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &_backbuffer); assert(SUCCEEDED(hr)); if (_is_multisampling_enabled || (_backbuffer_format == D3DFMT_X8R8G8B8 || _backbuffer_format == D3DFMT_X8B8G8R8)) { switch (_backbuffer_format) { case D3DFMT_X8R8G8B8: _backbuffer_format = D3DFMT_A8R8G8B8; break; case D3DFMT_X8B8G8R8: _backbuffer_format = D3DFMT_A8B8G8R8; break; } hr = _device->CreateRenderTarget(_width, _height, _backbuffer_format, D3DMULTISAMPLE_NONE, 0, FALSE, &_backbuffer_resolved, nullptr); if (FAILED(hr)) { LOG(ERROR) << "Failed to create back buffer resolve texture! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } } else { _backbuffer_resolved = _backbuffer; } // Create back buffer shader texture hr = _device->CreateTexture(_width, _height, 1, D3DUSAGE_RENDERTARGET, _backbuffer_format, D3DPOOL_DEFAULT, &_backbuffer_texture, nullptr); if (SUCCEEDED(hr)) { _backbuffer_texture->GetSurfaceLevel(0, &_backbuffer_texture_surface); } else { LOG(ERROR) << "Failed to create back buffer texture! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } return true; } bool d3d9_runtime::init_default_depth_stencil() { // Create default depth stencil surface HRESULT hr = _device->CreateDepthStencilSurface(_width, _height, D3DFMT_D24S8, D3DMULTISAMPLE_NONE, 0, FALSE, &_default_depthstencil, nullptr); if (FAILED(hr)) { LOG(ERROR) << "Failed to create default depth stencil! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } return true; } bool d3d9_runtime::init_fx_resources() { HRESULT hr = _device->CreateVertexBuffer(3 * sizeof(float), D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &_effect_triangle_buffer, nullptr); if (SUCCEEDED(hr)) { float *data = nullptr; hr = _effect_triangle_buffer->Lock(0, 3 * sizeof(float), reinterpret_cast<void **>(&data), 0); assert(SUCCEEDED(hr)); for (unsigned int i = 0; i < 3; i++) { data[i] = static_cast<float>(i); } _effect_triangle_buffer->Unlock(); } else { LOG(ERROR) << "Failed to create effect vertex buffer! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } const D3DVERTEXELEMENT9 declaration[] = { { 0, 0, D3DDECLTYPE_FLOAT1, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; hr = _device->CreateVertexDeclaration(declaration, &_effect_triangle_layout); if (FAILED(hr)) { LOG(ERROR) << "Failed to create effect vertex declaration! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } return true; } bool d3d9_runtime::init_imgui_font_atlas() { int width, height, bits_per_pixel; unsigned char *pixels; ImGui::SetCurrentContext(_imgui_context); ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bits_per_pixel); D3DLOCKED_RECT font_atlas_rect; com_ptr<IDirect3DTexture9> font_atlas; HRESULT hr = _device->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &font_atlas, nullptr); if (FAILED(hr) || FAILED(font_atlas->LockRect(0, &font_atlas_rect, nullptr, 0))) { LOG(ERROR) << "Failed to create font atlas texture! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } for (int y = 0; y < height; y++) { std::memcpy(static_cast<BYTE *>(font_atlas_rect.pBits) + font_atlas_rect.Pitch * y, pixels + (width * bits_per_pixel) * y, width * bits_per_pixel); } font_atlas->UnlockRect(0); d3d9_tex_data obj = { }; obj.texture = font_atlas; _imgui_font_atlas_texture = std::make_unique<d3d9_tex_data>(obj); if (hr = _device->BeginStateBlock(); SUCCEEDED(hr)) { _device->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); _device->SetPixelShader(nullptr); _device->SetVertexShader(nullptr); _device->SetRenderState(D3DRS_ZENABLE, false); _device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); _device->SetRenderState(D3DRS_ALPHATESTENABLE, false); _device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); _device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); _device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); _device->SetRenderState(D3DRS_ALPHABLENDENABLE, true); _device->SetRenderState(D3DRS_FOGENABLE, false); _device->SetRenderState(D3DRS_STENCILENABLE, false); _device->SetRenderState(D3DRS_CLIPPING, false); _device->SetRenderState(D3DRS_LIGHTING, false); _device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA); _device->SetRenderState(D3DRS_SCISSORTESTENABLE, true); _device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); _device->SetRenderState(D3DRS_SRGBWRITEENABLE, false); _device->SetRenderState(D3DRS_BLENDOPALPHA, D3DBLENDOP_ADD); _device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); _device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); _device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); _device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); _device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); _device->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); _device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); _device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); const D3DMATRIX identity_mat = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; const D3DMATRIX ortho_projection = { 2.0f / _width, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f / _height, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, -(_width + 1.0f) / _width, (_height + 1.0f) / _height, 0.5f, 1.0f }; _device->SetTransform(D3DTS_WORLD, &identity_mat); _device->SetTransform(D3DTS_VIEW, &identity_mat); _device->SetTransform(D3DTS_PROJECTION, &ortho_projection); hr = _device->EndStateBlock(&_imgui_state); } if (FAILED(hr)) { LOG(ERROR) << "Failed to create state block! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } return true; } bool d3d9_runtime::on_init(const D3DPRESENT_PARAMETERS &pp) { _width = pp.BackBufferWidth; _height = pp.BackBufferHeight; _backbuffer_format = pp.BackBufferFormat; _is_multisampling_enabled = pp.MultiSampleType != D3DMULTISAMPLE_NONE; _input = input::register_window(pp.hDeviceWindow); if (FAILED(_device->CreateStateBlock(D3DSBT_ALL, &_stateblock))) { return false; } if (!init_backbuffer_texture() || !init_default_depth_stencil() || !init_fx_resources() || !init_imgui_font_atlas()) { return false; } return runtime::on_init(); } void d3d9_runtime::on_reset() { if (!is_initialized()) { return; } runtime::on_reset(); // Destroy resources _stateblock.reset(); _backbuffer.reset(); _backbuffer_resolved.reset(); _backbuffer_texture.reset(); _backbuffer_texture_surface.reset(); _depthstencil.reset(); _depthstencil_replacement.reset(); _depthstencil_texture.reset(); _default_depthstencil.reset(); _effect_triangle_buffer.reset(); _effect_triangle_layout.reset(); _imgui_vertex_buffer.reset(); _imgui_index_buffer.reset(); _imgui_vertex_buffer_size = 0; _imgui_index_buffer_size = 0; _imgui_state.reset(); // Clear depth source table for (auto &it : _depth_source_table) { it.first->Release(); } _depth_source_table.clear(); } void d3d9_runtime::on_present() { if (!is_initialized()) return; // Begin post processing if (FAILED(_device->BeginScene())) return; runtime::on_frame(); detect_depth_source(); // Capture device state _stateblock->Capture(); BOOL software_rendering_enabled; D3DVIEWPORT9 viewport; com_ptr<IDirect3DSurface9> stateblock_rendertargets[8], stateblock_depthstencil; _device->GetViewport(&viewport); for (DWORD target = 0; target < _num_simultaneous_rendertargets; target++) { _device->GetRenderTarget(target, &stateblock_rendertargets[target]); } _device->GetDepthStencilSurface(&stateblock_depthstencil); if ((_behavior_flags & D3DCREATE_MIXED_VERTEXPROCESSING) != 0) { software_rendering_enabled = _device->GetSoftwareVertexProcessing(); _device->SetSoftwareVertexProcessing(FALSE); } // Resolve back buffer if (_backbuffer_resolved != _backbuffer) { _device->StretchRect(_backbuffer.get(), nullptr, _backbuffer_resolved.get(), nullptr, D3DTEXF_NONE); } // Apply post processing if (is_effect_loaded()) { _device->SetRenderTarget(0, _backbuffer_resolved.get()); _device->SetDepthStencilSurface(nullptr); // Setup vertex input _device->SetStreamSource(0, _effect_triangle_buffer.get(), 0, sizeof(float)); _device->SetVertexDeclaration(_effect_triangle_layout.get()); on_present_effect(); } // Apply presenting runtime::on_present(); // Copy to back buffer if (_backbuffer_resolved != _backbuffer) { _device->StretchRect(_backbuffer_resolved.get(), nullptr, _backbuffer.get(), nullptr, D3DTEXF_NONE); } // Apply previous device state _stateblock->Apply(); for (DWORD target = 0; target < _num_simultaneous_rendertargets; target++) { _device->SetRenderTarget(target, stateblock_rendertargets[target].get()); } _device->SetDepthStencilSurface(stateblock_depthstencil.get()); _device->SetViewport(&viewport); if ((_behavior_flags & D3DCREATE_MIXED_VERTEXPROCESSING) != 0) { _device->SetSoftwareVertexProcessing(software_rendering_enabled); } // End post processing _device->EndScene(); } void d3d9_runtime::on_draw_call(D3DPRIMITIVETYPE type, UINT vertices) { switch (type) { case D3DPT_LINELIST: vertices *= 2; break; case D3DPT_LINESTRIP: vertices += 1; break; case D3DPT_TRIANGLELIST: vertices *= 3; break; case D3DPT_TRIANGLESTRIP: case D3DPT_TRIANGLEFAN: vertices += 2; break; } _vertices += vertices; _drawcalls += 1; com_ptr<IDirect3DSurface9> depthstencil; _device->GetDepthStencilSurface(&depthstencil); if (depthstencil != nullptr) { if (depthstencil == _depthstencil_replacement) { depthstencil = _depthstencil; } const auto it = _depth_source_table.find(depthstencil.get()); if (it != _depth_source_table.end()) { it->second.drawcall_count = _drawcalls; it->second.vertices_count += vertices; } } } void d3d9_runtime::on_set_depthstencil_surface(IDirect3DSurface9 *&depthstencil) { if (_depth_source_table.find(depthstencil) == _depth_source_table.end()) { D3DSURFACE_DESC desc; depthstencil->GetDesc(&desc); // Early rejection if ( desc.MultiSampleType != D3DMULTISAMPLE_NONE || (desc.Width < _width * 0.95 || desc.Width > _width * 1.05) || (desc.Height < _height * 0.95 || desc.Height > _height * 1.05)) { return; } depthstencil->AddRef(); // Begin tracking const depth_source_info info = { desc.Width, desc.Height }; _depth_source_table.emplace(depthstencil, info); } if (_depthstencil_replacement != nullptr && depthstencil == _depthstencil) { depthstencil = _depthstencil_replacement.get(); } } void d3d9_runtime::on_get_depthstencil_surface(IDirect3DSurface9 *&depthstencil) { if (_depthstencil_replacement != nullptr && depthstencil == _depthstencil_replacement) { depthstencil->Release(); depthstencil = _depthstencil.get(); depthstencil->AddRef(); } } void d3d9_runtime::capture_frame(uint8_t *buffer) const { if (_backbuffer_format != D3DFMT_X8R8G8B8 && _backbuffer_format != D3DFMT_X8B8G8R8 && _backbuffer_format != D3DFMT_A8R8G8B8 && _backbuffer_format != D3DFMT_A8B8G8R8) { LOG(WARNING) << "Screenshots are not supported for back buffer format " << _backbuffer_format << "."; return; } HRESULT hr; com_ptr<IDirect3DSurface9> screenshot_surface; hr = _device->CreateOffscreenPlainSurface(_width, _height, _backbuffer_format, D3DPOOL_SYSTEMMEM, &screenshot_surface, nullptr); if (FAILED(hr)) { return; } hr = _device->GetRenderTargetData(_backbuffer_resolved.get(), screenshot_surface.get()); if (FAILED(hr)) { return; } D3DLOCKED_RECT mapped_rect; hr = screenshot_surface->LockRect(&mapped_rect, nullptr, D3DLOCK_READONLY); if (FAILED(hr)) { return; } auto mapped_data = static_cast<BYTE *>(mapped_rect.pBits); const UINT pitch = _width * 4; for (UINT y = 0; y < _height; y++) { std::memcpy(buffer, mapped_data, std::min(pitch, static_cast<UINT>(mapped_rect.Pitch))); for (UINT x = 0; x < pitch; x += 4) { buffer[x + 3] = 0xFF; if (_backbuffer_format == D3DFMT_A8R8G8B8 || _backbuffer_format == D3DFMT_X8R8G8B8) { std::swap(buffer[x + 0], buffer[x + 2]); } } buffer += pitch; mapped_data += mapped_rect.Pitch; } screenshot_surface->UnlockRect(); } bool d3d9_runtime::load_effect(const reshadefx::syntax_tree &ast, std::string &errors) { return d3d9_effect_compiler(this, ast, errors, false).run(); } bool d3d9_runtime::update_texture(texture &texture, const uint8_t *data) { if (texture.impl_reference != texture_reference::none) { return false; } const auto texture_impl = texture.impl->as<d3d9_tex_data>(); assert(data != nullptr); assert(texture_impl != nullptr); D3DSURFACE_DESC desc; texture_impl->texture->GetLevelDesc(0, &desc); HRESULT hr; com_ptr<IDirect3DTexture9> mem_texture; hr = _device->CreateTexture(desc.Width, desc.Height, 1, 0, desc.Format, D3DPOOL_SYSTEMMEM, &mem_texture, nullptr); if (FAILED(hr)) { LOG(ERROR) << "Failed to create memory texture for texture updating! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } D3DLOCKED_RECT mapped_rect; hr = mem_texture->LockRect(0, &mapped_rect, nullptr, 0); if (FAILED(hr)) { LOG(ERROR) << "Failed to lock memory texture for texture updating! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } const UINT size = std::min(texture.width * 4, static_cast<UINT>(mapped_rect.Pitch)) * texture.height; auto mapped_data = static_cast<BYTE *>(mapped_rect.pBits); switch (texture.format) { case texture_format::r8: for (UINT i = 0; i < size; i += 4, mapped_data += 4) mapped_data[0] = 0, mapped_data[1] = 0, mapped_data[2] = data[i], mapped_data[3] = 0; break; case texture_format::rg8: for (UINT i = 0; i < size; i += 4, mapped_data += 4) mapped_data[0] = 0, mapped_data[1] = data[i + 1], mapped_data[2] = data[i], mapped_data[3] = 0; break; case texture_format::rgba8: for (UINT i = 0; i < size; i += 4, mapped_data += 4) mapped_data[0] = data[i + 2], mapped_data[1] = data[i + 1], mapped_data[2] = data[i], mapped_data[3] = data[i + 3]; break; default: std::memcpy(mapped_data, data, size); break; } mem_texture->UnlockRect(0); hr = _device->UpdateTexture(mem_texture.get(), texture_impl->texture.get()); if (FAILED(hr)) { LOG(ERROR) << "Failed to update texture from memory texture! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } return true; } bool d3d9_runtime::update_texture_reference(texture &texture, texture_reference id) { com_ptr<IDirect3DTexture9> new_reference; switch (id) { case texture_reference::back_buffer: new_reference = _backbuffer_texture; break; case texture_reference::depth_buffer: new_reference = _depthstencil_texture; break; default: return false; } texture.impl_reference = id; const auto texture_impl = texture.impl->as<d3d9_tex_data>(); assert(texture_impl != nullptr); if (new_reference == texture_impl->texture) { return true; } texture_impl->surface.reset(); if (new_reference == nullptr) { texture_impl->texture.reset(); texture.width = texture.height = texture.levels = 0; texture.format = texture_format::unknown; } else { texture_impl->texture = new_reference; new_reference->GetSurfaceLevel(0, &texture_impl->surface); D3DSURFACE_DESC desc; texture_impl->surface->GetDesc(&desc); texture.width = desc.Width; texture.height = desc.Height; texture.format = texture_format::unknown; texture.levels = new_reference->GetLevelCount(); } return true; } void d3d9_runtime::render_technique(const technique &technique) { bool is_default_depthstencil_cleared = false; // Setup shader constants if (technique.uniform_storage_index >= 0) { const auto uniform_storage_data = reinterpret_cast<const float *>(get_uniform_value_storage().data() + technique.uniform_storage_offset); _device->SetVertexShaderConstantF(0, uniform_storage_data, static_cast<UINT>(technique.uniform_storage_index)); _device->SetPixelShaderConstantF(0, uniform_storage_data, static_cast<UINT>(technique.uniform_storage_index)); } for (const auto &pass_object : technique.passes) { const d3d9_pass_data &pass = *pass_object->as<d3d9_pass_data>(); // Setup states pass.stateblock->Apply(); // Save back buffer of previous pass _device->StretchRect(_backbuffer_resolved.get(), nullptr, _backbuffer_texture_surface.get(), nullptr, D3DTEXF_NONE); // Setup shader resources for (DWORD sampler = 0; sampler < pass.sampler_count; sampler++) { _device->SetTexture(sampler, pass.samplers[sampler].texture->texture.get()); for (DWORD state = D3DSAMP_ADDRESSU; state <= D3DSAMP_SRGBTEXTURE; state++) { _device->SetSamplerState(sampler, static_cast<D3DSAMPLERSTATETYPE>(state), pass.samplers[sampler].states[state]); } } // Setup render targets for (DWORD target = 0; target < _num_simultaneous_rendertargets; target++) { _device->SetRenderTarget(target, pass.render_targets[target]); } D3DVIEWPORT9 viewport; _device->GetViewport(&viewport); const float texelsize[4] = { -1.0f / viewport.Width, 1.0f / viewport.Height }; _device->SetVertexShaderConstantF(255, texelsize, 1); const bool is_viewport_sized = viewport.Width == _width && viewport.Height == _height; _device->SetDepthStencilSurface(is_viewport_sized ? _default_depthstencil.get() : nullptr); if (is_viewport_sized && !is_default_depthstencil_cleared) { is_default_depthstencil_cleared = true; _device->Clear(0, nullptr, (pass.clear_render_targets ? D3DCLEAR_TARGET : 0) | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, 0, 1.0f, 0); } else if (pass.clear_render_targets) { _device->Clear(0, nullptr, D3DCLEAR_TARGET, 0, 0.0f, 0); } // Draw triangle _device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1); _vertices += 3; _drawcalls += 1; // Update shader resources for (const auto target : pass.render_targets) { if (target == nullptr || target == _backbuffer_resolved) { continue; } com_ptr<IDirect3DBaseTexture9> texture; if (SUCCEEDED(target->GetContainer(IID_PPV_ARGS(&texture))) && texture->GetLevelCount() > 1) { texture->SetAutoGenFilterType(D3DTEXF_LINEAR); texture->GenerateMipSubLevels(); } } } } void d3d9_runtime::render_imgui_draw_data(ImDrawData *draw_data) { // Fixed-function vertex layout struct vertex { float x, y, z; D3DCOLOR col; float u, v; }; // Create and grow buffers if needed if (_imgui_vertex_buffer == nullptr || _imgui_vertex_buffer_size < draw_data->TotalVtxCount) { _imgui_vertex_buffer.reset(); _imgui_vertex_buffer_size = draw_data->TotalVtxCount + 5000; if (FAILED(_device->CreateVertexBuffer(_imgui_vertex_buffer_size * sizeof(vertex), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1, D3DPOOL_DEFAULT, &_imgui_vertex_buffer, nullptr))) { return; } } if (_imgui_index_buffer == nullptr || _imgui_index_buffer_size < draw_data->TotalIdxCount) { _imgui_index_buffer.reset(); _imgui_index_buffer_size = draw_data->TotalIdxCount + 10000; if (FAILED(_device->CreateIndexBuffer(_imgui_index_buffer_size * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &_imgui_index_buffer, nullptr))) { return; } } vertex *vtx_dst; ImDrawIdx *idx_dst; if (FAILED(_imgui_vertex_buffer->Lock(0, draw_data->TotalVtxCount * sizeof(vertex), reinterpret_cast<void **>(&vtx_dst), D3DLOCK_DISCARD)) || FAILED(_imgui_index_buffer->Lock(0, draw_data->TotalIdxCount * sizeof(ImDrawIdx), reinterpret_cast<void **>(&idx_dst), D3DLOCK_DISCARD))) { return; } for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList *const cmd_list = draw_data->CmdLists[n]; for (auto vtx_src = cmd_list->VtxBuffer.begin(); vtx_src != cmd_list->VtxBuffer.end(); vtx_src++, vtx_dst++) { vtx_dst->x = vtx_src->pos.x; vtx_dst->y = vtx_src->pos.y; vtx_dst->z = 0.0f; // RGBA --> ARGB for Direct3D 9 vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000) >> 16) | ((vtx_src->col & 0xFF) << 16); vtx_dst->u = vtx_src->uv.x; vtx_dst->v = vtx_src->uv.y; } std::memcpy(idx_dst, &cmd_list->IdxBuffer.front(), cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx)); idx_dst += cmd_list->IdxBuffer.size(); } _imgui_vertex_buffer->Unlock(); _imgui_index_buffer->Unlock(); // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing _device->SetRenderTarget(0, _backbuffer_resolved.get()); for (DWORD target = 1; target < _num_simultaneous_rendertargets; target++) { _device->SetRenderTarget(target, nullptr); } _device->SetDepthStencilSurface(nullptr); _device->SetStreamSource(0, _imgui_vertex_buffer.get(), 0, sizeof(vertex)); _device->SetIndices(_imgui_index_buffer.get()); _imgui_state->Apply(); // Render command lists UINT vtx_offset = 0, idx_offset = 0; for (UINT i = 0; i < _num_samplers; i++) _device->SetTexture(i, nullptr); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList *const cmd_list = draw_data->CmdLists[n]; for (const ImDrawCmd *cmd = cmd_list->CmdBuffer.begin(); cmd != cmd_list->CmdBuffer.end(); idx_offset += cmd->ElemCount, cmd++) { const RECT scissor_rect = { static_cast<LONG>(cmd->ClipRect.x), static_cast<LONG>(cmd->ClipRect.y), static_cast<LONG>(cmd->ClipRect.z), static_cast<LONG>(cmd->ClipRect.w) }; _device->SetTexture(0, static_cast<const d3d9_tex_data *>(cmd->TextureId)->texture.get()); _device->SetScissorRect(&scissor_rect); _device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, vtx_offset, 0, cmd_list->VtxBuffer.size(), idx_offset, cmd->ElemCount / 3); } vtx_offset += cmd_list->VtxBuffer.size(); } } void d3d9_runtime::detect_depth_source() { static int cooldown = 0, traffic = 0; if (cooldown-- > 0) { traffic += g_network_traffic > 0; return; } else { cooldown = 30; if (traffic > 10) { traffic = 0; create_depthstencil_replacement(nullptr); return; } else { traffic = 0; } } if (_is_multisampling_enabled || _depth_source_table.empty()) { return; } depth_source_info best_info = { 0 }; IDirect3DSurface9 *best_match = nullptr; for (auto it = _depth_source_table.begin(); it != _depth_source_table.end();) { const auto depthstencil = it->first; auto &depthstencil_info = it->second; if ((depthstencil->AddRef(), depthstencil->Release()) == 1) { depthstencil->Release(); it = _depth_source_table.erase(it); continue; } else { ++it; } if (depthstencil_info.drawcall_count == 0) { continue; } if ((depthstencil_info.vertices_count * (1.2f - float(depthstencil_info.drawcall_count) / _drawcalls)) >= (best_info.vertices_count * (1.2f - float(best_info.drawcall_count) / _drawcalls))) { best_match = depthstencil; best_info = depthstencil_info; } depthstencil_info.drawcall_count = depthstencil_info.vertices_count = 0; } if (best_match != nullptr && _depthstencil != best_match) { create_depthstencil_replacement(best_match); } } bool d3d9_runtime::create_depthstencil_replacement(IDirect3DSurface9 *depthstencil) { _depthstencil.reset(); _depthstencil_replacement.reset(); _depthstencil_texture.reset(); if (depthstencil != nullptr) { _depthstencil = depthstencil; D3DSURFACE_DESC desc; _depthstencil->GetDesc(&desc); if (desc.Format != D3DFMT_INTZ && desc.Format != D3DFMT_DF16 && desc.Format != D3DFMT_DF24) { D3DDISPLAYMODE displaymode; _swapchain->GetDisplayMode(&displaymode); D3DDEVICE_CREATION_PARAMETERS creation_params; _device->GetCreationParameters(&creation_params); desc.Format = D3DFMT_UNKNOWN; const D3DFORMAT formats[] = { D3DFMT_INTZ, D3DFMT_DF24, D3DFMT_DF16 }; for (const auto format : formats) { if (SUCCEEDED(_d3d->CheckDeviceFormat(creation_params.AdapterOrdinal, creation_params.DeviceType, displaymode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, format))) { desc.Format = format; break; } } if (desc.Format == D3DFMT_UNKNOWN) { LOG(ERROR) << "Your graphics card is missing support for at least one of the 'INTZ', 'DF24' or 'DF16' texture formats. Cannot create depth replacement texture."; return false; } const HRESULT hr = _device->CreateTexture(desc.Width, desc.Height, 1, D3DUSAGE_DEPTHSTENCIL, desc.Format, D3DPOOL_DEFAULT, &_depthstencil_texture, nullptr); if (SUCCEEDED(hr)) { _depthstencil_texture->GetSurfaceLevel(0, &_depthstencil_replacement); // Update auto depth stencil com_ptr<IDirect3DSurface9> current_depthstencil; _device->GetDepthStencilSurface(&current_depthstencil); if (current_depthstencil != nullptr) { if (current_depthstencil == _depthstencil) { _device->SetDepthStencilSurface(_depthstencil_replacement.get()); } } } else { LOG(ERROR) << "Failed to create depth replacement texture! HRESULT is '" << std::hex << hr << std::dec << "'."; return false; } } else { _depthstencil_replacement = _depthstencil; _depthstencil_replacement->GetContainer(IID_PPV_ARGS(&_depthstencil_texture)); } } // Update effect textures for (auto &texture : _textures) { if (texture.impl_reference == texture_reference::depth_buffer) { update_texture_reference(texture, texture_reference::depth_buffer); } } return true; } }
[ "crosiredev@gmail.com" ]
crosiredev@gmail.com
23a1f70bb567882962fcd8275c76416fb371ac5e
8d1ff170385e7b556ac7b8fdf67a00701a6b8a73
/latentred/firmware/UART.h
47ead4013f5381d48fd3c551b1cb21b1fce44ee6
[ "BSD-3-Clause" ]
permissive
azonenberg/latentpacket
92db28e3e61ff6e94cdbc90bdb58a87b55f484d2
9de75f116f3d6734547fea574ad9deece2825625
refs/heads/master
2023-08-17T03:33:40.458469
2023-08-14T08:06:28
2023-08-14T08:06:28
129,678,427
25
4
null
null
null
null
UTF-8
C++
false
false
4,116
h
/*********************************************************************************************************************** * * * LATENTPACKET v0.1 * * * * Copyright (c) 2019 Andrew D. Zonenberg * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 uart_h #define uart_h /** @file @author Andrew D. Zonenberg @brief UART driver */ /** @brief Driver for a UART */ class UART : public CharacterDevice { public: UART(volatile usart_t* lane, uint32_t baud_div = 181) : UART(lane, lane, baud_div) {} //we calculate 217 for 115.2 Kbps but experimentally we need 181, why?? //This is suggestive of APB1 being 20.8 MHz instead of 25. UART(volatile usart_t* txlane, volatile usart_t* rxlane, uint32_t baud_div = 181); //TX side virtual void PrintBinary(char ch); void Printf(const char* format, ...); void WritePadded(const char* str, int minlen, char padding, int prepad); protected: volatile usart_t* m_txlane; volatile usart_t* m_rxlane; }; #endif
[ "azonenberg@drawersteak.com" ]
azonenberg@drawersteak.com
f8626aa4ca99069d35abb224ea6c70549d4c9004
551bf7d1180a6d54449eb7f60c5120d7bd8a953d
/include/rpoly/rpoly_ak1.hpp
3e218b1f1f90789773153cf744eb160b6ed4a1e9
[]
no_license
swgmone/trajectory_server
76d40212c8f70ab6141e918888f7e770f44ffc09
e2dea16266cea8b7b7f4b35af5dccb14f80129aa
refs/heads/main
2023-09-01T10:24:17.174801
2021-10-12T08:58:20
2021-10-12T08:58:20
406,545,939
7
2
null
null
null
null
UTF-8
C++
false
false
587
hpp
/* Polynomial Handler */ /* Author: Lorenzo Gentilini */ /* E-Mail: lorenzo.gentilini6@unibo.it */ /* Date: August 2020 */ /* File: rpoly_ak1.hpp */ #ifndef _RPOLY_H #define _RPOLY_H #include <Eigen/Eigen> #include <iostream> #include <fstream> #include <cctype> #include <cmath> #include <cfloat> int findLastNonZeroCoeff(Eigen::VectorXd coefficients); bool findRootsJenkinsTraub(Eigen::VectorXd coefficients_increasing, Eigen::VectorXcd& roots); #endif
[ "lorenzo.gentilini6@unibo.it" ]
lorenzo.gentilini6@unibo.it
0553178a51410ac56d2588fecaaabe1cbb1817d8
c76796ac315152b9c701c120be2562bded1ac584
/ObjectInserter.h
35ed93878a5d44ea61575a6e60c59bd9cb5fff93
[]
no_license
shocklateboy92/conemaker2
6983ea8f5410ffb791422eaf6e177c0615e139cc
0e5ddda7d8b154bae8313f6f4898e3fed7ea2400
refs/heads/master
2016-09-15T22:24:49.176141
2014-05-13T23:41:49
2014-05-13T23:41:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
#ifndef CONEMAKER_OBJECTINSERTER_H #define CONEMAKER_OBJECTINSERTER_H #include "Tool.h" #include <Ogre.h> namespace ConeMaker { class ObjectInserter : public Tool { public: ObjectInserter(Ogre::SceneNode *cursor); // MouseListener interface public: virtual bool mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id); // Tool interface public: virtual void setup(); private: Ogre::SceneNode *m_cursorNode; }; } // namespace ConeMaker #endif // CONEMAKER_OBJECTINSERTER_H
[ "kde@lasath.org" ]
kde@lasath.org
f90a5fb6203ff252c3aa3371018b448b9b15fedf
be0204c1b95839adee1ad204be022be38e32e2d6
/BOJ/1003.cpp
5d7c948297e279a1d5391ac594f7a700c9942836
[]
no_license
tlsdorye/Problem-Solving
507bc8d3cf1865c10067ef2e8eb7cb2ee42e16dd
5c112d2238bfb1fc092612a76f10c7785ba86c78
refs/heads/master
2021-06-12T19:19:19.337092
2021-04-23T06:39:43
2021-04-23T06:39:43
179,432,390
4
0
null
null
null
null
UTF-8
C++
false
false
409
cpp
#include <iostream> using namespace std; int fibo[41][2]; void makeFibo() { fibo[0][0] = 1; fibo[0][1] = 0; fibo[1][0] = 0; fibo[1][1] = 1; for (int i = 2; i <= 40; i++) { fibo[i][0] = fibo[i - 1][1]; fibo[i][1] = fibo[i - 1][0] + fibo[i - 1][1]; } } int main() { makeFibo(); int n; cin >> n; while (n--) { int tmp; cin >> tmp; cout << fibo[tmp][0] << " " << fibo[tmp][1] << endl; } }
[ "tlsdorye@gmail.com" ]
tlsdorye@gmail.com
e1a4b0203c949dcfe478c1b29e0c3ae4779792f3
cfdab33825bb160dea64f0aab79b7206bf82e6d7
/10828/10828.cc
0955cac890a3052709ddc19e1858b118c29f557a
[]
no_license
wjdwithyou/BOJ
299e0efaf3e5173addc55709fed5c19a458a0900
a8ab50a14f2059905be4093b1f889c02f568126c
refs/heads/master
2021-01-11T20:18:13.462615
2018-01-24T14:28:25
2018-01-24T14:28:25
81,535,224
0
1
null
null
null
null
UTF-8
C++
false
false
734
cc
#include <iostream> int stack[10000]; int main() { char buf[16]; int n, num; int stack_idx = 0; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%s", buf); switch (buf[0]) { case 'p': if (buf[1] == 'u') { scanf("%d", &num); stack[stack_idx++] = num; } else { if (stack_idx == 0) { puts("-1"); } else { printf("%d\n", stack[--stack_idx]); } } break; case 's': printf("%d\n", stack_idx); break; case 'e': if (stack_idx == 0) { puts("1"); } else { puts("0"); } break; case 't': if (stack_idx == 0) { puts("-1"); } else { printf("%d\n", stack[stack_idx - 1]); } break; default: break; } } return 0; }
[ "administrator@mail.tastewiki.xyz" ]
administrator@mail.tastewiki.xyz
07d6728a9182ed1a39c77d9ce33b8be446490452
0e6c9a7187fd0d3ff3e6419c3041fa04e50e192e
/deimos/llvm/c/bitwriter.d
727e33e80e07db370d2dc0339f2d260b48cfccd6
[]
no_license
jkm/deimos-llvm
45511e009a6982493bda7d2f8567d545a3299a0b
25b58cec1c5a053e44a7ad8e1167d1515032ae2f
refs/heads/master
2020-06-08T14:17:30.833067
2014-02-15T21:33:48
2014-02-15T21:33:48
5,119,416
1
1
null
2017-02-18T19:40:25
2012-07-20T05:16:18
D
UTF-8
C++
false
false
2,145
d
/*===-- llvm-c/BitWriter.h - BitWriter Library C Interface ------*- C++ -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This header declares the C interface to libLLVMBitWriter.a, which *| |* implements output of the LLVM bitcode format. *| |* *| |* Many exotic languages can interoperate with C code but have a harder time *| |* with C++ due to name mangling. So in addition to C, this interface enables *| |* tools written in such languages. *| |* *| \*===----------------------------------------------------------------------===*/ module deimos.llvm.c.bitwriter; import deimos.llvm.c.core; extern(C) nothrow: /** * @defgroup LLVMCBitWriter Bit Writer * @ingroup LLVMC * * @{ */ /*===-- Operations on modules ---------------------------------------------===*/ /** Writes a module to the specified path. Returns 0 on success. */ int LLVMWriteBitcodeToFile(LLVMModuleRef M, const(char) *Path); /** Writes a module to an open file descriptor. Returns 0 on success. */ int LLVMWriteBitcodeToFD(LLVMModuleRef M, int FD, int ShouldClose, int Unbuffered); /** Deprecated for LLVMWriteBitcodeToFD. Writes a module to an open file descriptor. Returns 0 on success. Closes the Handle. */ int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int Handle); /** * @} */
[ "jkm@gluey.org" ]
jkm@gluey.org
0e67e467f3c4fb6aabeeb1789b6b3fe9d0bc726e
e09a7d5e9c8a2a2a2dc7b6d972d6d62e7db284e3
/Dynamic Programming/number_of_balanced_binary_tree.cpp
b7f833d551e5b917984a45db2b527bc35feef425
[]
no_license
yuktajuneja/Data-Structure-Coding-ninjas
5254ef0e2d4d1bc02c22c1aebe746bcbe6eba2e6
200891531364aca9b4baa650a035d4db7a415600
refs/heads/main
2023-08-16T10:39:47.996011
2021-09-28T08:22:14
2021-09-28T08:22:14
405,596,181
0
0
null
null
null
null
UTF-8
C++
false
false
1,199
cpp
/* Given an integer h, find the possible number of balanced binary trees of height h. You just need to return the count of possible binary trees which are balanced. This number can be huge, so return output modulus 10^9 + 7. */ #include<iostream> using namespace std; #include<cmath> int count_of_bt1(int n){ if(n<=1){ return 1; } int mod=(int) (pow(10,9)) +7; int x=count_of_bt1(n-1); int y=count_of_bt1(n-2); int x1=(int) ( ( (long)(x) *x) % mod); int y1=(int) ( (2* (long)(x) *y) % mod); int ans= ((x1+y1)%mod); return ans; } int helper(int n,int* ans){ if(n<=1){ return 1; } if(ans[n]!=-1){ return ans[n]; } int x=helper(n-1,ans); int y=helper(n-2,ans); ans[n]=(x*x)+(2*(x*y)); return ans[n]; } int count_of_bt2(int n){ int*ans=new int[n+1]; for(int i=0;i<n+1;i++){ ans[i]=-1; } return helper(n,ans); } int count_of_bt3(int n){ int ans[n+1]; ans[0]=ans[1]=1; for(int i=2;i<=n;i++){ int x=ans[i-1]; int y=ans[i-2]; ans[i]= (x*x)+(2*(x*y)); } return ans[n]; } int main(int argc, char const *argv[]) { int n; cin>>n; cout<<count_of_bt1(n)<<" "<<count_of_bt2(n)<<" "<<count_of_bt3(n)<<endl; return 0; }
[ "yukta.juneja1582@gmail.com" ]
yukta.juneja1582@gmail.com
690384a8dc25e76b0c4115a91527ec013668a1c0
69bdd4914ac1a014a089325d468bf0c0ab2fd458
/PHONELST.cpp
f5e5c9974f00eff2c3d939cd2754b4999814b14c
[]
no_license
ab1hi2shek/SPOJ-Solutions
f0185f8758fca2e4daa633e66739a17fc68d8f9d
d80da26241f19bf75f77c369d520b19e2520cd91
refs/heads/master
2021-07-04T01:37:56.219641
2017-09-26T17:23:50
2017-09-26T17:23:50
103,300,870
0
0
null
null
null
null
UTF-8
C++
false
false
1,374
cpp
#include <bits/stdc++.h> using namespace std; //data types #define ll long long int //stl typedef vector<ll> vi; typedef vector<vi> vvi; typedef pair<ll,ll> pii; typedef map<ll,ll> mpll; //loops #define loop(i,a,b) for(ll i=a;i<=b;i++) #define loopr(i,a,b) for(ll i=a;i>=b;i--) #define SIZE 10 struct trie{ trie *child[SIZE]; bool isLeaf; }; trie* getNode() { trie* root = new trie; root->isLeaf = false; for(int i=0;i<SIZE;i++) root->child[i] = NULL; return root; } int insert(trie *root, string s) { trie *temp = root; ll flag = 0; for(ll i=0;i<s.size();i++) { ll index = s[i]-'0'; //cout<<" index = "<<index<<endl; if(!temp->child[index]) { temp->child[index] = getNode(); flag = 1; } else { if(temp->child[index]->isLeaf) return 0; } temp = temp->child[index]; } temp->isLeaf = true; return flag; } int main() { std::ios::sync_with_stdio(false); ll t; cin>>t; while(t--) { trie *root = getNode(); ll n; cin>>n; bool ans = true; for(ll i=0;i<n;i++) { string s; cin>>s; //cout<<s<<endl; if(ans && !insert(root,s)) ans = false; // cout<<insert(root,s)<<endl; // if(insert(root,s) == false) // break; } if(!ans) cout<<"NO"<<endl; else cout<<"YES"<<endl; } }
[ "ab1hi2shek@DESKTOP-FC3M4GT.localdomain" ]
ab1hi2shek@DESKTOP-FC3M4GT.localdomain
03fc0ef2fa87babe7dd145f194bf2877f802bb23
f426375bc339ae8f5c6244dc47bd453c6dce1371
/Classes/HelloWorldScene.h
77807375ec36b3988f3f8fb1ddc9445432c54c2c
[]
no_license
TunerRed/HeroRun
dc21caea374d1acff6131095ccdd4766806962a2
c3a3ac3b8fe7b98c596a9a040887403323767dbe
refs/heads/master
2020-03-25T13:51:22.138757
2018-09-17T04:08:06
2018-09-17T04:08:06
143,846,317
0
0
null
null
null
null
UTF-8
C++
false
false
310
h
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" USING_NS_CC; class HelloWorld : public cocos2d::Layer { public: ActionInterval *action[5]; static cocos2d::Scene* createScene(); virtual bool init(); CREATE_FUNC(HelloWorld); }; #endif // __HELLOWORLD_SCENE_H__
[ "12877111966@qq.com" ]
12877111966@qq.com
a5bc5ae5202a6e8f63dd3cef85326031d7752a5c
f163486ed0a7e38c15c51e5d55dbf1443a7e637c
/HomeAlertTest/HomeAlertTest.ino
cae0fdf6b3748b4ec5b4465d05b456b20d2a2fc5
[]
no_license
khawajamechatronics/Arduino
31c58145cd0632664026030160a45d6f64c34dad
721855f0d1f965399a6200e7018d195ae7902c58
refs/heads/master
2020-03-18T18:35:42.125924
2017-02-08T14:40:59
2017-02-08T14:40:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,710
ino
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <DNSServer.h> #include <TimeLib.h> #include <Timezone.h> #include "ModuleSettings.h" #include "ESP8266WebServerEx.h" #include "SendEmailSms.h" #include "NTPClient.h" #include "TimeSettings.h" #include "SerialDebug.h" #include "General.h" #include "EmailSms.h" #include "InputPinMgmt.h" #include "HttpSession.h" #include "InfoExchg.h" #include "MyWiFi.h" #include "ArmLogic.h" //#include <ESP8266mDNS.h> #include "admin.html.h" #ifndef PHASE2_CODE #include "email.html.h" #else #include "email.html.h" //#include "email_p2.html.h" #endif #include "favicon.png.h" #include "general.html.h" #include "gpio.html.h" #include "login.html.h" #include "time.html.h" #include "device.html.h" #include "network.html.h" #include "skeleton.css.h" #include "normalize.css.h" #include "main.css.h" #include "main.js.h" #include "jquery-3.1.0.min.js.gz.h" #include "md5.min.js.gz.h" ///////////////////////////////////////////////////////////////////////// 12 13 int g_inputPins[INPUT_PIN_COUNT]={5}; int g_outputPins[OUTPUT_PIN_COUNT]={ 15, 2, 0, 4, 16, 14, 12, 13}; int g_buttonPins[BUTTON_PIN_COUNT]={}; int g_ARM_INPUT_PIN = 5; int g_ARM_OFF_PIN = 99; // virtual pin for toggle off ARM int g_BELL_PIN = 16; char* g_WifiApPassword = NULL; IPAddress g_ApIp(192,168,3,1); ///////////////////////////////////////////////////////////////////////// const int ANALOG_PIN = A0; // Analog input. Need to seed the random generator #define BROWSER_CACHE_DAYS 864000 // cache for 10 days static const char MimeTypeJS[] = "application/javascript"; static const char MimeCss[] = "text/css"; static const char MimeHtml[] = "text/html"; static const char MimeJson[] = "application/json"; static const char MimePNG[] = "image/png"; static const char StatusJsonTrue[] = "{\"status\":true}"; static const char StatusJsonFalse[] = "{\"status\":false}"; InfoExchg udpServer; CNTPClient NTP; ModuleSettings g_ModuleSettings; General g_General; InputPinMagement g_InputPinMgmt; ArmLogic g_ArmLogic(g_ARM_INPUT_PIN, g_BELL_PIN); MyWiFi g_WifiList; ESP8266WebServerEx *g_pServer = NULL; DNSServer *g_pDnsServer = NULL; void SetupGPIO(); void handleRoot(); void handleIoPinMaps(); void handleNotFound(); void handleGetTimeSettings(); void handleSetTimeSettings(); void handleGetGeneral(); void handleSetGeneral(); void handleGetEmailSms(); void handleSetEmailSms(); void handleGetDeviceInfo(); void handleGetGpio(); void handleGetDeviceList(); void handleScanWiFi(); void handleGetNetworkSettings(bool bHead=true); void handleSetNetworkSettings(); void handleRebootEsp(); bool StartAsWifiSTA(); bool StartAsWifiAP(); bool g_IsAPMode = false; bool g_FirstAPMode = false; unsigned long g_lastSave = 0; unsigned long g_lastimeCheckConn; String inputString; bool stringComplete=false; ////////////////////////////////////////////////////////////////////////////////////////////////// // global setup void setup ( void ) { delay(1000); INIT_SERIAL_DEBUG(); g_IsAPMode = false; g_ModuleSettings.LoadSettings(); g_ModuleSettings.data.ending=9; g_ModuleSettings.SaveSettings(); // seed the random generator sources randomSeed(analogRead(ANALOG_PIN) ^ millis()); SetupGPIO(); g_WifiList.Scan(); if ( StartAsWifiSTA() ) { g_pServer = new ESP8266WebServerEx(g_ModuleSettings.data.port); TRACE2("HTTP server port: ",g_ModuleSettings.data.port); TRACE2("IP address: ",WiFi.localIP()); } else { if ( StartAsWifiAP() ) { g_FirstAPMode = true; g_IsAPMode = true; g_pServer = new ESP8266WebServerEx(80); TRACE2("IP address: ",WiFi.softAPIP()); g_pServer->ForceLogin(false); } else { TRACE("Starting as WIFI AP failed.\nRebooting..."); delay(2000); ESP.restart(); return; } } //here the list of headers to be recorded const char * headerkeys[] = {"Cookie","Host"}; size_t headerkeyssize = sizeof(headerkeys)/sizeof(char*); //ask server to track these headers g_pServer->collectHeaders(headerkeys, headerkeyssize ); // send jquery and related CSS files g_pServer->on ( "/js/jquery-3.1.0.min.js.gz", []() { g_pServer->sendEx(200, MimeTypeJS, jquery_3_1_0_min_js_gz, sizeof(jquery_3_1_0_min_js_gz),true,BROWSER_CACHE_DAYS); }); g_pServer->on ( "/js/md5.min.js.gz", []() { g_pServer->sendEx(200, MimeTypeJS, md5_min_js_gz, sizeof(md5_min_js_gz),true,BROWSER_CACHE_DAYS); }); g_pServer->on("/js/main.js", []() { g_pServer->sendEx(200, MimeTypeJS, main_js, sizeof(main_js),false,BROWSER_CACHE_DAYS); }); g_pServer->on("/css/skeleton.css", []() { g_pServer->sendEx(200, MimeCss, skeleton_css, sizeof(skeleton_css),false,BROWSER_CACHE_DAYS); }); g_pServer->on("/css/normalize.css", []() { g_pServer->sendEx(200, MimeCss, normalize_css, sizeof(normalize_css),false,BROWSER_CACHE_DAYS); }); g_pServer->on("/css/main.css", []() { g_pServer->sendEx(200, MimeCss, main_css, sizeof(main_css),false,BROWSER_CACHE_DAYS); }); g_pServer->onNotFound ( handleNotFound ); g_pServer->on("/favicon.png", []() { g_pServer->sendEx(200, MimePNG, favicon_png, sizeof(favicon_png),false,BROWSER_CACHE_DAYS); }); g_pServer->on("/js/ioPinMaps.js", handleIoPinMaps); g_pServer->on("/getdeviceinfo", handleGetDeviceInfo); g_pServer->on("/getgpio", handleGetGpio); g_pServer->on("/setgpio", []() { g_pServer->handleSetGpio(); }); g_pServer->on("/gettimesettings", handleGetTimeSettings); g_pServer->on("/settimesettings", handleSetTimeSettings); g_pServer->on("/getgeneral", handleGetGeneral); g_pServer->on("/setgeneral", handleSetGeneral); g_pServer->on("/getemailsms", handleGetEmailSms); g_pServer->on("/setemailsms", handleSetEmailSms); g_pServer->on("/getdevicelist", handleGetDeviceList); g_pServer->on("/scanwifi", handleScanWiFi); g_pServer->on("/setnetworksettings", handleSetNetworkSettings); g_pServer->on("/reboot", handleRebootEsp); if ( g_IsAPMode ) { g_pServer->on("/getnetworksettings", []() { handleGetNetworkSettings(false); }); g_pServer->on("/network.html", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); }); g_pServer->on("/", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); }); g_pServer->on("/hotspot-detect.html", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); }); g_pServer->on("/ search", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); }); g_pServer->on("/search", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); }); g_pServer->begin(); return; } g_pServer->on("/getnetworksettings", []() { handleGetNetworkSettings(); }); g_pServer->on("/", handleRoot); g_pServer->on("/admin.html", []() { g_pServer->sendEx(200, MimeHtml, admin_html, sizeof(admin_html)); }); g_pServer->on("/gpio.html", []() { g_pServer->sendEx(200, MimeHtml, gpio_html, sizeof(gpio_html)); }); g_pServer->on("/general.html", []() { g_pServer->sendEx(200, MimeHtml, general_html, sizeof(general_html)); }); g_pServer->on("/network.html", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); }); g_pServer->on("/time.html", []() { g_pServer->sendEx(200, MimeHtml, time_html, sizeof(time_html)); }); #ifndef PHASE2_CODE g_pServer->on("/email.html", []() { g_pServer->sendEx(200, MimeHtml, email_html, sizeof(email_html)); }); #else g_pServer->on("/email.html", []() { g_pServer->sendEx(200, MimeHtml, email_p2_html, sizeof(email_p2_html)); }); #endif g_pServer->on("/device.html", []() { g_pServer->sendEx(200, MimeHtml, device_html, sizeof(device_html)); }); g_pServer->on("/logout.html", []() { g_pServer->handleLogout(); }); g_pServer->on("/login.html", handleRoot); g_pServer->begin(); udpServer.begin(); } #ifdef _DEBUG_ unsigned long heapChk = 0; #endif ////////////////////////////////////////////////////////////////////////////////////////////////// // main loop ////////////////////////////////////////////////////////////////////////////////////////////////// void loop ( void ) { while(!g_FirstAPMode&&(WiFi.status()==WL_CONNECTION_LOST||WiFi.status()==WL_DISCONNECTED)){ g_WifiList.Scan(); delay(1000); StartAsWifiSTA(); } if(g_FirstAPMode&&g_ModuleSettings.data.ssid[0]){ if((millis()-g_lastimeCheckConn)>5000){ g_lastimeCheckConn = millis(); int numSsid = WiFi.scanNetworks(); if (numSsid == -1) { TRACE("Couldn't get a wifi connection"); } for (int thisNet = 0; thisNet < numSsid; thisNet++) { if(String(WiFi.SSID(thisNet))==String(g_ModuleSettings.data.ssid)){ TRACE2("ssid :", WiFi.SSID(thisNet)); g_FirstAPMode = false; if(StartAsWifiSTA()){ ESP.restart(); } } } } } if (g_pServer) g_pServer->handleClient(); if ( g_IsAPMode ) { if ( g_pDnsServer ) g_pDnsServer->processNextRequest(); return; } g_InputPinMgmt.checkInputPinStatus(); g_ArmLogic.runLogic(); NTP.AutoSync(); g_General.CheckPinSetOnOff(); udpServer.Update(); unsigned long curMillis = millis(); if ( curMillis>g_lastSave ) { if ( curMillis-g_lastSave>3600000 ) { g_ModuleSettings.SaveSettings(); g_lastSave = curMillis; } } else g_lastSave = curMillis; serialEvent(); if (stringComplete) { Serial.println(inputString); if(inputString.indexOf("restore")>=0){ g_ModuleSettings.CleanSettings(); ESP.restart(); }else if(inputString.indexOf("restart")>=0){ ESP.restart(); } // clear the string: inputString = ""; stringComplete = false; } } ////////////////////////////////////////////////////////////////////////////////////////////////// // void handleRoot() { g_pServer->handleLogin(login_html,sizeof(login_html),"/gpio.html"); } ////////////////////////////////////////////////////////////////////////////////////////////////// // return a JavaScript mapping of inputs and output pins ////////////////////////////////////////////////////////////////////////////////////////////////// void handleIoPinMaps() { int i; char buf[16]; String data = "var outputPins = {"; for (i=0; i<OUTPUT_PIN_COUNT; i++) { delay(0); if ( i ) data += ","; sprintf(buf,"\"GPIO-%d\":%d",g_outputPins[i],g_outputPins[i]); data += buf; } data += "};\nvar inputPins = {"; for (i=0; i<INPUT_PIN_COUNT; i++) { delay(0); if ( i ) data += ","; sprintf(buf,"\"GPIO-%d\":%d",g_inputPins[i],g_inputPins[i]); data += buf; } data += "};\nvar buttonPins = {"; for (i=0; i<BUTTON_PIN_COUNT; i++) { delay(0); if ( i ) data += ","; sprintf(buf,"\"GPIO-%d\":%d",g_buttonPins[i],g_buttonPins[i]); data += buf; } data += "};"; g_pServer->send(200,MimeTypeJS,data); } ////////////////////////////////////////////////////////////////////////////////////////////////// // process not found case ////////////////////////////////////////////////////////////////////////////////////////////////// void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += g_pServer->uri(); message += "\nMethod: "; message += ( g_pServer->method() == HTTP_GET ) ? "GET" : "POST"; message += "\nArguments: "; message += g_pServer->args(); message += "\n"; for ( uint8_t i = 0; i < g_pServer->args(); i++ ) { delay(0); message += " " + g_pServer->argName ( i ) + ": " + g_pServer->arg ( i ) + "\n"; } g_pServer->send ( 404, "text/plain", message ); } ////////////////////////////////////////////////////////////////////////////////////////////////// // void SetupGPIO() { int i; for (i=0; i<INPUT_PIN_COUNT; i++) { delay(0); pinMode(g_inputPins[i], INPUT_PULLUP); } for (i=0; i<OUTPUT_PIN_COUNT; i++) { delay(0); pinMode(g_outputPins[i], OUTPUT); } for (i=0; i<BUTTON_PIN_COUNT; i++) { delay(0); pinMode(g_buttonPins[i], OUTPUT); } } ////////////////////////////////////////////////////////////////////////////////////////////////// // return JSON {server: "timeg_pServer->com",time:12345648,zone:4} // time is UNIX epoch and zone is the zone index ////////////////////////////////////////////////////////////////////////////////////////////////// void handleGetTimeSettings() { String result; TimeSettings::GetTimeSettingsData(result); g_pServer->send(200, MimeJson, result); } ////////////////////////////////////////////////////////////////////////////////////////////////// // client call this to set the time zone index {zone: 4, server: "pool.ntp.org"} // return status OK if success or failed ////////////////////////////////////////////////////////////////////////////////////////////////// void handleSetTimeSettings() { if ( TimeSettings::ParseData(g_pServer) ) { NTP.SetNTPServer(g_ModuleSettings.data.TimeServer); g_pServer->send(200, MimeJson, StatusJsonTrue); g_ModuleSettings.SaveSettings(); } else { g_pServer->send(200, MimeJson, StatusJsonFalse); } } ////////////////////////////////////////////////////////////////////////////////////////////////// // return settings to client ////////////////////////////////////////////////////////////////////////////////////////////////// void handleGetGeneral() { String result; General::GetGeneralData(g_pServer,result); g_pServer->send(200, MimeJson, result); } ////////////////////////////////////////////////////////////////////////////////////////////////// // Parse client data and save to the settings ////////////////////////////////////////////////////////////////////////////////////////////////// void handleSetGeneral() { if ( General::ParseData(g_pServer) ) { g_pServer->send(200, MimeJson, StatusJsonTrue); g_ModuleSettings.SaveSettings(); } else { g_pServer->send(200, MimeJson, StatusJsonFalse); } } ////////////////////////////////////////////////////////////////////////////////////////////////// // return email and sms settings to client ////////////////////////////////////////////////////////////////////////////////////////////////// void handleGetEmailSms() { String result; EmailSmsSettings::GetEmailSmsSettings(g_pServer,result); g_pServer->send(200, MimeJson, result); } ////////////////////////////////////////////////////////////////////////////////////////////////// // Parse client data and save to the settings for email and sms ////////////////////////////////////////////////////////////////////////////////////////////////// void handleSetEmailSms() { if ( EmailSmsSettings::ParseData(g_pServer) ) { g_pServer->send(200, MimeJson, StatusJsonTrue); g_ModuleSettings.SaveSettings(); } else { g_pServer->send(200, MimeJson, StatusJsonFalse); } } ////////////////////////////////////////////////////////////////////////////////////////////////// // return device information: {"name":"My Bedroom","cat:":"0","ip":"192.168.1.100","port":8080} ////////////////////////////////////////////////////////////////////////////////////////////////// void handleGetDeviceInfo() { String buffer; buffer.reserve(80); buffer = "{\"name\":\""; buffer += g_ModuleSettings.data.ModuleName; buffer += "\",\"cat\":\""; buffer += g_ModuleSettings.data.Category; buffer += "\",\"ip\":\""; buffer += WiFi.localIP().toString(); buffer += "\",\"port\":"; buffer += (int)g_ModuleSettings.data.port; buffer +="}"; g_pServer->send(200, MimeJson, buffer); } ////////////////////////////////////////////////////////////////////////////////////////////////// // return a json of all inputs and output pin status // {"gpi12":1,"gpo13":0} ////////////////////////////////////////////////////////////////////////////////////////////////// void handleGetGpio() { String buffer; int i; buffer.reserve(64); buffer = "{"; for (i=0; i<INPUT_PIN_COUNT; i++) { delay(0); if ( i>0 ) buffer += ","; buffer += "\"gpi"; buffer += g_inputPins[i]; buffer += "\":"; buffer += g_InputPinMgmt.GetInputPinStatus(i); } for (i=0; i<OUTPUT_PIN_COUNT; i++) { delay(0); buffer += ",\"gpo"; buffer += g_outputPins[i]; buffer += "\":"; buffer += (int)(digitalRead(g_outputPins[i])==HIGH); } // for virtual pin arm/disarm buffer += ",\"gpo"; buffer += g_ARM_OFF_PIN; buffer += "\":"; buffer += (int)g_ArmLogic.getOutputActive(); for (i=0; i<BUTTON_PIN_COUNT; i++) { delay(0); buffer += ",\"gpo"; buffer += g_buttonPins[i]; buffer += "\":"; buffer += (int)(digitalRead(g_buttonPins[i])==HIGH); } buffer += "}"; g_pServer->send(200, MimeJson, buffer); } ////////////////////////////////////////////////////////////////////////////////////////////////// // receive: {cat: 1} // return: [{"name":"Living Room","ip":"192.168.1.1","port":8080},{name:"Bed Room",ip:"192.168.1.2",port:8080}] ////////////////////////////////////////////////////////////////////////////////////////////////// void handleGetDeviceList() { String buffer; buffer.reserve(256); udpServer.ParseData(g_pServer,buffer); g_pServer->send(200, MimeJson, buffer); } ////////////////////////////////////////////////////////////////////////////////////////////////// void handleScanWiFi() { String buffer; buffer.reserve(256); g_WifiList.GetWifiList(buffer); g_pServer->send(200, MimeJson, buffer); } ////////////////////////////////////////////////////////////////////////////////////////////////// void handleGetNetworkSettings(bool bHead) { String buffer; buffer.reserve(256); MyWiFi::GetWifiData(buffer,bHead); g_pServer->send(200, MimeJson, buffer); } ////////////////////////////////////////////////////////////////////////////////////////////////// void handleSetNetworkSettings() { if ( MyWiFi::ParseData(g_pServer) ) { g_pServer->send(200, MimeJson, StatusJsonTrue); g_ModuleSettings.SaveSettings(); } else { g_pServer->send(200, MimeJson, StatusJsonFalse); } } ////////////////////////////////////////////////////////////////////////////////////////////////// bool StartAsWifiSTA() { WiFi.softAPdisconnect(); WiFi.disconnect(); WiFi.mode(WIFI_STA); TRACE("Trying to connect to WIFI"); // ip, gw, subnet, dns1, dns2 if ( !g_ModuleSettings.data.dhcp ) { IPAddress ip; IPAddress gw; IPAddress mask; TRACE("Using static IP"); if ( ip.fromString(g_ModuleSettings.data.ip) && gw.fromString(g_ModuleSettings.data.gw) && mask.fromString(g_ModuleSettings.data.mask) ) { WiFi.config(ip, gw, mask, IPAddress(8,8,8,8), IPAddress(208,67,222,222)); } else { TRACE("Error: Invalid IP format"); } } else { TRACE("Using DHCP"); } WiFi.setAutoConnect(true); WiFi.setAutoReconnect(true); TRACE("Connecting to WIFI."); TRACE2("SSID:",g_ModuleSettings.data.ssid); TRACE2("PW:",g_ModuleSettings.data.pw); if ( g_ModuleSettings.data.pw[0] ) WiFi.begin(g_ModuleSettings.data.ssid, g_ModuleSettings.data.pw); else WiFi.begin(g_ModuleSettings.data.ssid); for (int i=0; i<20; i++) { if ( WiFi.isConnected() ) { TRACE("CONNECTED!"); return true; } delay(500); } TRACE("Failed to connect to WIFI.\nStarting in AP Mode"); return false; } ////////////////////////////////////////////////////////////////////////////////////////////////// bool StartAsWifiAP() { WiFi.disconnect(); WiFi.mode(WIFI_AP_STA); WiFi.softAPConfig(g_ApIp,g_ApIp,IPAddress(255,255,255,0)); g_pDnsServer = new DNSServer(); String ssid = "ESP" + String(ESP.getChipId()); bool bRvl = WiFi.softAP(ssid.c_str(),g_WifiApPassword); if ( bRvl && g_pDnsServer ) { // Setup the DNS server redirecting all the domains to the apIP g_pDnsServer->setErrorReplyCode(DNSReplyCode::NoError); g_pDnsServer->start(53, "*", g_ApIp); } return bRvl; } ////////////////////////////////////////////////////////////////////////////////////////////////// void handleRebootEsp() { g_pServer->send(200, MimeJson, StatusJsonTrue); delay(100); g_pServer->close(); ESP.restart(); } /////////////////////////////// void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag // so the main loop can do something about it: if (inChar == '\n') { stringComplete = true; } } }
[ "binhpham1909@gmail.com" ]
binhpham1909@gmail.com
c583c58cd155c70d0f13223d477c5ad24f44e2ae
47de9c88b957dc66c46769f40103d5147b00b7c9
/codeforces/609/C.cpp
835488ef50d68d9863bd9709a67dfb32c6b45bd7
[]
no_license
autul2017831021/Codeforces_Atcoder_Solved_Problems
1027a606b3cb5be80e57fcfbcfa0327ebd47bd95
b95e432718c9393f8a781fa56c2ed65f082274f5
refs/heads/master
2023-07-02T02:23:58.307782
2021-03-01T13:00:00
2021-07-31T15:40:28
329,067,317
1
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
using namespace std; #include<bits/stdc++.h> typedef long long int ll; typedef double dl; #define pb push_back #define bg begin() #define en end() #define rbg rbegin() #define ren rend() #define sz size() #define r0 return 0 #define F first #define S second #define inf 9999999999 #define its (*it).S #define itf (*it).F #define nl cout<<endl; main() { ll n,c=0,s=0; cin>>n; vector<ll>v,w; for(int i=0;i<n;i++) { ll x; cin>>x; v.pb(x); s+=x; } sort(v.rbg,v.ren); if(v[0]-v[n-1]==1 || n==1) { cout<<c;nl r0; } ll av,m; av=s/n; m=s%n; for(int i=0;i<n;i++) w.pb(av); for(int i=0;i<m;i++) w[i]+=1; for(int i=0;i<n;i++) { if(w[i]<v[i]) c=c+(v[i]-w[i]); } cout<<c<<endl; }
[ "alexiautul@gmail.com" ]
alexiautul@gmail.com
7f19c5914a7d362a0588c417b5cd049da28d79ee
793f4aa2dbc58397d29eb14cd8f521cdcfd4dab8
/opencv_read_display_image/src/main.cpp
653d917b74e7c394d26401fb52d800bc62ff6cbf
[]
no_license
TEJASWI-TEJASWI/UpliftProject-AppDevelopment
b1c298ac467c7eade9e71756604bd8d1260d2f83
f9fa4d1a049e3ec877440136c9272692d5cded96
refs/heads/master
2022-10-22T09:09:25.391775
2020-06-15T13:51:17
2020-06-15T13:51:17
273,899,731
2
0
null
2020-06-21T12:28:20
2020-06-21T12:28:19
null
UTF-8
C++
false
false
987
cpp
/* * File: main.cpp * Last Modified: February 19, 2000 * Topic: Writing Make Files * ---------------------------------------------------------------- */ #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace cv; using namespace std; int main( int argc, char** argv ) { if( argc != 2) { cout <<" Usage: display_image ImageToLoadAndDisplay" << endl; return -1; } Mat image; image = imread(argv[1]); // Read the file if(! image.data ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; return -1; } namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display. imshow( "Display window", image ); // Show our image inside it. waitKey(0); // Wait for a keystroke in the window return 0; }
[ "noreply@github.com" ]
TEJASWI-TEJASWI.noreply@github.com
0c53c175bd922525d6a151a3c88982e4d8e01332
cfd33821398cede8c2aadd847d59b89d72d7e0a6
/msnp24/src/msn.cpp
e4252711ccfdaf41ab8dd97ffa7792ebe636647c
[]
no_license
miranda-ng/deprecated
1c922e502d7ec35371a454131b9e5fa019e241fd
137526f743d2e8237845b7faea992989a7e8fbd7
refs/heads/master
2023-01-28T20:57:12.499530
2023-01-13T23:32:54
2023-01-13T23:32:54
71,989,840
3
3
null
2017-08-22T18:52:34
2016-10-26T09:53:01
C++
UTF-8
C++
false
false
4,275
cpp
/* Plugin of Miranda IM for communicating with users of the MSN Messenger protocol. Copyright (c) 2012-2014 Miranda NG Team Copyright (c) 2006-2012 Boris Krasnovskiy. Copyright (c) 2003-2005 George Hazan. Copyright (c) 2002-2003 Richard Hughes (original version). This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "msn_global.h" #include "msn_proto.h" #include "version.h" HINSTANCE hInst; int hLangpack; TIME_API tmi; ///////////////////////////////////////////////////////////////////////////////////////// // Initialization routines void MsnLinks_Init(void); void MsnLinks_Destroy(void); ///////////////////////////////////////////////////////////////////////////////////////// // Global variables int avsPresent = -1; static const PLUGININFOEX pluginInfo = { sizeof(PLUGININFOEX), __PLUGIN_NAME, PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM), __DESCRIPTION, __AUTHOR, __AUTHOREMAIL, __COPYRIGHT, __AUTHORWEB, UNICODE_AWARE, // {97724AF9-F3FB-47d3-A3BF-EAA935C74E6D} {0x97724af9, 0xf3fb, 0x47d3, {0xa3, 0xbf, 0xea, 0xa9, 0x35, 0xc7, 0x4e, 0x6d}} }; int MSN_GCEventHook(WPARAM wParam, LPARAM lParam); int MSN_GCMenuHook(WPARAM wParam, LPARAM lParam); ///////////////////////////////////////////////////////////////////////////// // Protocol instances static int sttCompareProtocols(const CMsnProto *p1, const CMsnProto *p2) { return _tcscmp(p1->m_tszUserName, p2->m_tszUserName); } OBJLIST<CMsnProto> g_Instances(1, sttCompareProtocols); ///////////////////////////////////////////////////////////////////////////////////////// // Main DLL function extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID) { if (fdwReason == DLL_PROCESS_ATTACH) { hInst = hinstDLL; DisableThreadLibraryCalls(hinstDLL); } return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // OnModulesLoaded - finalizes plugin's configuration on load static int OnModulesLoaded(WPARAM, LPARAM) { avsPresent = ServiceExists(MS_AV_SETMYAVATART) != 0; MsnLinks_Init(); return 0; } static CMsnProto* msnProtoInit(const char* pszProtoName, const TCHAR* tszUserName) { CMsnProto *ppro = new CMsnProto(pszProtoName, tszUserName); g_Instances.insert(ppro); return ppro; } static int msnProtoUninit(CMsnProto* ppro) { g_Instances.remove(ppro); return 0; } ///////////////////////////////////////////////////////////////////////////////////////// // Performs a primary set of actions upon plugin loading extern "C" int __declspec(dllexport) Load(void) { mir_getTMI(&tmi); mir_getLP(&pluginInfo); HookEvent(ME_SYSTEM_MODULESLOADED, OnModulesLoaded); PROTOCOLDESCRIPTOR pd = { sizeof(pd) }; pd.szName = "MSN"; pd.fnInit = (pfnInitProto)msnProtoInit; pd.fnUninit = (pfnUninitProto)msnProtoUninit; pd.type = PROTOTYPE_PROTOCOL; CallService(MS_PROTO_REGISTERMODULE, 0, (LPARAM)&pd); MsnInitIcons(); MSN_InitContactMenu(); return 0; } ///////////////////////////////////////////////////////////////////////////////////////// // Unload a plugin extern "C" int __declspec(dllexport) Unload(void) { MSN_RemoveContactMenus(); MsnLinks_Destroy(); return 0; } ///////////////////////////////////////////////////////////////////////////////////////// // MirandaPluginInfoEx - returns an information about a plugin extern "C" __declspec(dllexport) const PLUGININFOEX* MirandaPluginInfoEx(DWORD) { return &pluginInfo; } ///////////////////////////////////////////////////////////////////////////////////////// // MirandaInterfaces - returns the protocol interface to the core extern "C" __declspec(dllexport) const MUUID MirandaInterfaces[] = { MIID_PROTOCOL, MIID_LAST };
[ "watcherhd@gmail.com" ]
watcherhd@gmail.com
d9c68afd6c6836c865f5b05206068ee5daf0bd89
51635684d03e47ebad12b8872ff469b83f36aa52
/external/gcc-12.1.0/libstdc++-v3/testsuite/experimental/filesystem/path/compare/strings.cc
19d22664226152615e03b366d224653b4c18c68c
[ "Zlib", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "GPL-3.0-only", "GCC-exception-3.1", "GPL-2.0-only", "LGPL-3.0-only", "LGPL-2.0-or-later" ]
permissive
zhmu/ananas
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
30850c1639f03bccbfb2f2b03361792cc8fae52e
refs/heads/master
2022-06-25T10:44:46.256604
2022-06-12T17:04:40
2022-06-12T17:04:40
30,108,381
59
8
Zlib
2021-09-26T17:30:30
2015-01-31T09:44:33
C
UTF-8
C++
false
false
1,414
cc
// { dg-options "-DUSE_FILESYSTEM_TS -lstdc++fs" } // { dg-do run { target c++11 } } // { dg-require-filesystem-ts "" } // Copyright (C) 2014-2022 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 8.4.8 path compare [path.compare] #include <experimental/filesystem> #include <testsuite_hooks.h> #include <testsuite_fs.h> using std::experimental::filesystem::path; void test01() { const std::string s0 = "/a/a/b/b"; const path p0 = s0; for (const std::string& s : __gnu_test::test_paths) { path p(s); VERIFY( p.compare(s) == 0 ); VERIFY( p.compare(s.c_str()) == 0 ); VERIFY( p.compare(p0) == p.compare(s0) ); VERIFY( p.compare(p0) == p.compare(s0.c_str()) ); } } int main() { test01(); }
[ "rink@rink.nu" ]
rink@rink.nu
1d1ebd38358b891198e20b3e68f562603c5c7539
0466f22155da48d446f27a7de2c3023c85284f14
/src/hdchain.h
fc72c5e98531703bca139f99b365d57cfa447760
[ "MIT" ]
permissive
jesusleon1995/dashdiff
fe660564ccf31a32cfd2851abb527a1fb7eb314f
83347b555ab7f6212bc40bb47f9afee7823be090
refs/heads/master
2020-03-21T16:58:34.574472
2018-06-27T00:45:18
2018-06-27T00:45:18
138,805,516
0
0
null
null
null
null
UTF-8
C++
false
false
4,467
h
// Copyright (c) 2014-2017 The Dashdiff Core developers // Distributed under the MIT software license, see the accompanying #ifndef DASH_HDCHAIN_H #define DASH_HDCHAIN_H #include "key.h" #include "sync.h" /* hd account data model */ class CHDAccount { public: uint32_t nExternalChainCounter; uint32_t nInternalChainCounter; CHDAccount() : nExternalChainCounter(0), nInternalChainCounter(0) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(nExternalChainCounter); READWRITE(nInternalChainCounter); } }; /* simple HD chain data model */ class CHDChain { private: static const int CURRENT_VERSION = 1; int nVersion; uint256 id; bool fCrypted; SecureVector vchSeed; SecureVector vchMnemonic; SecureVector vchMnemonicPassphrase; std::map<uint32_t, CHDAccount> mapAccounts; // critical section to protect mapAccounts mutable CCriticalSection cs_accounts; public: CHDChain() : nVersion(CHDChain::CURRENT_VERSION) { SetNull(); } CHDChain(const CHDChain& other) : nVersion(other.nVersion), id(other.id), fCrypted(other.fCrypted), vchSeed(other.vchSeed), vchMnemonic(other.vchMnemonic), vchMnemonicPassphrase(other.vchMnemonicPassphrase), mapAccounts(other.mapAccounts) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { LOCK(cs_accounts); READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(id); READWRITE(fCrypted); READWRITE(vchSeed); READWRITE(vchMnemonic); READWRITE(vchMnemonicPassphrase); READWRITE(mapAccounts); } void swap(CHDChain& first, CHDChain& second) // nothrow { // enable ADL (not necessary in our case, but good practice) using std::swap; // by swapping the members of two classes, // the two classes are effectively swapped swap(first.nVersion, second.nVersion); swap(first.id, second.id); swap(first.fCrypted, second.fCrypted); swap(first.vchSeed, second.vchSeed); swap(first.vchMnemonic, second.vchMnemonic); swap(first.vchMnemonicPassphrase, second.vchMnemonicPassphrase); swap(first.mapAccounts, second.mapAccounts); } CHDChain& operator=(CHDChain from) { swap(*this, from); return *this; } bool SetNull(); bool IsNull() const; void SetCrypted(bool fCryptedIn); bool IsCrypted() const; void Debug(std::string strName) const; bool SetMnemonic(const SecureVector& vchMnemonic, const SecureVector& vchMnemonicPassphrase, bool fUpdateID); bool SetMnemonic(const SecureString& ssMnemonic, const SecureString& ssMnemonicPassphrase, bool fUpdateID); bool GetMnemonic(SecureVector& vchMnemonicRet, SecureVector& vchMnemonicPassphraseRet) const; bool GetMnemonic(SecureString& ssMnemonicRet, SecureString& ssMnemonicPassphraseRet) const; bool SetSeed(const SecureVector& vchSeedIn, bool fUpdateID); SecureVector GetSeed() const; uint256 GetID() const { return id; } uint256 GetSeedHash(); void DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_t nChildIndex, CExtKey& extKeyRet); void AddAccount(); bool GetAccount(uint32_t nAccountIndex, CHDAccount& hdAccountRet); bool SetAccount(uint32_t nAccountIndex, const CHDAccount& hdAccount); size_t CountAccounts(); }; /* hd pubkey data model */ class CHDPubKey { private: static const int CURRENT_VERSION = 1; int nVersion; public: CExtPubKey extPubKey; uint256 hdchainID; uint32_t nAccountIndex; uint32_t nChangeIndex; CHDPubKey() : nVersion(CHDPubKey::CURRENT_VERSION), nAccountIndex(0), nChangeIndex(0) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(extPubKey); READWRITE(hdchainID); READWRITE(nAccountIndex); READWRITE(nChangeIndex); } std::string GetKeyPath() const; }; #endif // DASH_HDCHAIN_H
[ "jjuansan9@alumnes.ub.edu" ]
jjuansan9@alumnes.ub.edu
c080bfc93864a58c321390627a1c6a9ef9b94a6f
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qttools/src/designer/src/components/formeditor/formwindow.h
802b27f707a671c8a0c75e20556ed2ba641ed215
[ "Qt-LGPL-exception-1.1", "LGPL-2.1-only", "LGPL-2.0-or-later", "LGPL-3.0-only", "GPL-3.0-only", "LGPL-2.1-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GFDL-1.3-only", "LicenseRef-scancode-digia-qt-preview", "LicenseRef-scancode-warranty-discl...
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
12,172
h
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** 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 The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef FORMWINDOW_H #define FORMWINDOW_H #include "formeditor_global.h" #include "qdesignerundostack.h" #include <formwindowbase_p.h> // Qt #include <QtCore/QHash> #include <QtCore/QList> #include <QtCore/QMap> #include <QtCore/QSet> #include <QtCore/QPointer> QT_BEGIN_NAMESPACE class QDesignerDnDItemInterface; class QDesignerTaskMenuExtension; class DomConnections; class DomUI; class QWidget; class QAction; class QLabel; class QTimer; class QAction; class QMenu; class QRubberBand; namespace qdesigner_internal { class FormEditor; class FormWindowCursor; class WidgetEditorTool; class FormWindowWidgetStack; class FormWindowManager; class FormWindowDnDItem; class SetPropertyCommand; class QT_FORMEDITOR_EXPORT FormWindow: public FormWindowBase { Q_OBJECT public: explicit FormWindow(FormEditor *core, QWidget *parent = 0, Qt::WindowFlags flags = 0); virtual ~FormWindow(); QDesignerFormEditorInterface *core() const Q_DECL_OVERRIDE; QDesignerFormWindowCursorInterface *cursor() const Q_DECL_OVERRIDE; // Overwritten: FormWindowBase QWidget *formContainer() const Q_DECL_OVERRIDE; int toolCount() const Q_DECL_OVERRIDE; int currentTool() const Q_DECL_OVERRIDE; void setCurrentTool(int index) Q_DECL_OVERRIDE; QDesignerFormWindowToolInterface *tool(int index) const Q_DECL_OVERRIDE; void registerTool(QDesignerFormWindowToolInterface *tool) Q_DECL_OVERRIDE; QString author() const Q_DECL_OVERRIDE; void setAuthor(const QString &author) Q_DECL_OVERRIDE; QString comment() const Q_DECL_OVERRIDE; void setComment(const QString &comment) Q_DECL_OVERRIDE; void layoutDefault(int *margin, int *spacing) Q_DECL_OVERRIDE; void setLayoutDefault(int margin, int spacing) Q_DECL_OVERRIDE; void layoutFunction(QString *margin, QString *spacing) Q_DECL_OVERRIDE; void setLayoutFunction(const QString &margin, const QString &spacing) Q_DECL_OVERRIDE; QString pixmapFunction() const Q_DECL_OVERRIDE; void setPixmapFunction(const QString &pixmapFunction) Q_DECL_OVERRIDE; QString exportMacro() const Q_DECL_OVERRIDE; void setExportMacro(const QString &exportMacro) Q_DECL_OVERRIDE; QStringList includeHints() const Q_DECL_OVERRIDE; void setIncludeHints(const QStringList &includeHints) Q_DECL_OVERRIDE; QString fileName() const Q_DECL_OVERRIDE; void setFileName(const QString &fileName) Q_DECL_OVERRIDE; QString contents() const Q_DECL_OVERRIDE; bool setContents(QIODevice *dev, QString *errorMessage = 0) Q_DECL_OVERRIDE; bool setContents(const QString &) Q_DECL_OVERRIDE; QDir absoluteDir() const Q_DECL_OVERRIDE; void simplifySelection(QWidgetList *sel) const Q_DECL_OVERRIDE; void ensureUniqueObjectName(QObject *object) Q_DECL_OVERRIDE; QWidget *mainContainer() const Q_DECL_OVERRIDE; void setMainContainer(QWidget *mainContainer) Q_DECL_OVERRIDE; bool isMainContainer(const QWidget *w) const; QWidget *currentWidget() const; bool hasInsertedChildren(QWidget *w) const; QList<QWidget *> selectedWidgets() const; void clearSelection(bool changePropertyDisplay = true) Q_DECL_OVERRIDE; bool isWidgetSelected(QWidget *w) const; void selectWidget(QWidget *w, bool select = true) Q_DECL_OVERRIDE; void selectWidgets(); void repaintSelection(); void updateSelection(QWidget *w); void updateChildSelections(QWidget *w); void raiseChildSelections(QWidget *w); void raiseSelection(QWidget *w); inline const QList<QWidget *>& widgets() const { return m_widgets; } inline int widgetCount() const { return m_widgets.count(); } inline QWidget *widgetAt(int index) const { return m_widgets.at(index); } QList<QWidget *> widgets(QWidget *widget) const; QWidget *createWidget(DomUI *ui, const QRect &rect, QWidget *target); bool isManaged(QWidget *w) const Q_DECL_OVERRIDE; void manageWidget(QWidget *w) Q_DECL_OVERRIDE; void unmanageWidget(QWidget *w) Q_DECL_OVERRIDE; QUndoStack *commandHistory() const Q_DECL_OVERRIDE; void beginCommand(const QString &description) Q_DECL_OVERRIDE; void endCommand() Q_DECL_OVERRIDE; bool blockSelectionChanged(bool blocked) Q_DECL_OVERRIDE; void emitSelectionChanged() Q_DECL_OVERRIDE; bool unify(QObject *w, QString &s, bool changeIt); bool isDirty() const Q_DECL_OVERRIDE; void setDirty(bool dirty) Q_DECL_OVERRIDE; static FormWindow *findFormWindow(QWidget *w); virtual QWidget *containerAt(const QPoint &pos); QWidget *widgetAt(const QPoint &pos) Q_DECL_OVERRIDE; void highlightWidget(QWidget *w, const QPoint &pos, HighlightMode mode = Highlight) Q_DECL_OVERRIDE; void updateOrderIndicators(); bool handleEvent(QWidget *widget, QWidget *managedWidget, QEvent *event); QStringList resourceFiles() const Q_DECL_OVERRIDE; void addResourceFile(const QString &path) Q_DECL_OVERRIDE; void removeResourceFile(const QString &path) Q_DECL_OVERRIDE; void resizeWidget(QWidget *widget, const QRect &geometry); bool dropDockWidget(QDesignerDnDItemInterface *item, const QPoint &global_mouse_pos); bool dropWidgets(const QList<QDesignerDnDItemInterface*> &item_list, QWidget *target, const QPoint &global_mouse_pos) Q_DECL_OVERRIDE; QWidget *findContainer(QWidget *w, bool excludeLayout) const Q_DECL_OVERRIDE; // for WidgetSelection only. QWidget *designerWidget(QWidget *w) const; // Initialize and return a popup menu for a managed widget QMenu *initializePopupMenu(QWidget *managedWidget) Q_DECL_OVERRIDE; #ifndef QT_NO_CLIPBOARD void paste(PasteMode pasteMode) Q_DECL_OVERRIDE; #endif virtual QEditorFormBuilder *createFormBuilder() Q_DECL_OVERRIDE; bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE; signals: void contextMenuRequested(QMenu *menu, QWidget *widget); public slots: void deleteWidgets(); void raiseWidgets(); void lowerWidgets(); #ifndef QT_NO_CLIPBOARD void copy(); void cut(); void paste(); #endif void selectAll(); void createLayout(int type, QWidget *container = 0); void morphLayout(QWidget *container, int newType); void breakLayout(QWidget *w); void editContents(); protected: virtual QMenu *createPopupMenu(QWidget *w); void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE; void insertWidget(QWidget *w, const QRect &rect, QWidget *target, bool already_in_form = false); private slots: void selectionChangedTimerDone(); void checkSelection(); void checkSelectionNow(); void slotSelectWidget(QAction *); private: enum MouseState { NoMouseState, // Double click received MouseDoubleClicked, // Drawing selection rubber band rectangle MouseDrawRubber, // Started a move operation MouseMoveDrag, // Click on a widget whose parent is selected. Defer selection to release MouseDeferredSelection }; MouseState m_mouseState; QPointer<QWidget> m_lastClickedWidget; void init(); void initializeCoreTools(); int getValue(const QRect &rect, int key, bool size) const; int calcValue(int val, bool forward, bool snap, int snapOffset) const; void handleClickSelection(QWidget *managedWidget, unsigned mouseFlags); bool frameNeeded(QWidget *w) const; enum RectType { Insert, Rubber }; void startRectDraw(const QPoint &global, QWidget *, RectType t); void continueRectDraw(const QPoint &global, QWidget *, RectType t); void endRectDraw(); QWidget *containerAt(const QPoint &pos, QWidget *notParentOf); void checkPreviewGeometry(QRect &r); bool handleContextMenu(QWidget *widget, QWidget *managedWidget, QContextMenuEvent *e); bool handleMouseButtonDblClickEvent(QWidget *widget, QWidget *managedWidget, QMouseEvent *e); bool handleMousePressEvent(QWidget *widget, QWidget *managedWidget, QMouseEvent *e); bool handleMouseMoveEvent(QWidget *widget, QWidget *managedWidget, QMouseEvent *e); bool handleMouseReleaseEvent(QWidget *widget, QWidget *managedWidget, QMouseEvent *e); bool handleKeyPressEvent(QWidget *widget, QWidget *managedWidget, QKeyEvent *e); bool handleKeyReleaseEvent(QWidget *widget, QWidget *managedWidget, QKeyEvent *e); bool isCentralWidget(QWidget *w) const; bool setCurrentWidget(QWidget *currentWidget); bool trySelectWidget(QWidget *w, bool select); void dragWidgetWithinForm(QWidget *widget, const QRect &targetGeometry, QWidget *targetContainer); void setCursorToAll(const QCursor &c, QWidget *start); QPoint mapToForm(const QWidget *w, const QPoint &pos) const; bool canBeBuddy(QWidget *w) const; QWidget *findTargetContainer(QWidget *widget) const; void clearMainContainer(); static int widgetDepth(const QWidget *w); static bool isChildOf(const QWidget *c, const QWidget *p); void editWidgets() Q_DECL_OVERRIDE; void updateWidgets(); void handleArrowKeyEvent(int key, Qt::KeyboardModifiers modifiers); void layoutSelection(int type); void layoutContainer(QWidget *w, int type); private: QWidget *innerContainer(QWidget *outerContainer) const; QWidget *containerForPaste() const; QAction *createSelectAncestorSubMenu(QWidget *w); void selectSingleWidget(QWidget *w); FormEditor *m_core; FormWindowCursor *m_cursor; QWidget *m_mainContainer; QWidget *m_currentWidget; bool m_blockSelectionChanged; QPoint m_rectAnchor; QRect m_currRect; QWidgetList m_widgets; QSet<QWidget*> m_insertedWidgets; class Selection; Selection *m_selection; QPoint m_startPos; QDesignerUndoStack m_undoStack; QString m_fileName; typedef QPair<QPalette ,bool> PaletteAndFill; typedef QMap<QWidget*, PaletteAndFill> WidgetPaletteMap; WidgetPaletteMap m_palettesBeforeHighlight; QRubberBand *m_rubberBand; QTimer *m_selectionChangedTimer; QTimer *m_checkSelectionTimer; QTimer *m_geometryChangedTimer; FormWindowWidgetStack *m_widgetStack; WidgetEditorTool *m_widgetEditor; QStringList m_resourceFiles; QString m_comment; QString m_author; QString m_pixmapFunction; int m_defaultMargin, m_defaultSpacing; QString m_marginFunction, m_spacingFunction; QString m_exportMacro; QStringList m_includeHints; QPoint m_contextMenuPosition; private: friend class WidgetEditorTool; }; } // namespace qdesigner_internal QT_END_NAMESPACE #endif // FORMWINDOW_H
[ "p_pavlov@wargaming.net" ]
p_pavlov@wargaming.net
15cbaf7134a07afc078d2cde5c2920895e6b9f10
7274d5a3f1c78c2412205db504119487522e3dda
/CocoaEngine/include/cocoa/renderer/CameraStruct.h
aae127b84759d27a7342be9c6574bd53cca17e74
[ "MIT" ]
permissive
ambrosiogabe/Cocoa
a7101ce7de24b5e0ac50239200bd60304ed834cd
c66539149c9963e354daba9dfd4ec444ca135b48
refs/heads/master
2023-09-04T06:50:56.325751
2023-08-19T21:09:44
2023-08-19T21:09:44
268,167,311
50
8
MIT
2023-08-19T21:09:45
2020-05-30T22:06:33
C++
UTF-8
C++
false
false
573
h
#ifndef COCOA_ENGINE_CAMERA_STRUCT_H #define COCOA_ENGINE_CAMERA_STRUCT_H #include "externalLibs.h" #include "cocoa/renderer/Framebuffer.h" namespace Cocoa { struct Camera { // Projection/View matrices for ortho and perspective glm::mat4 viewMatrix; glm::mat4 inverseView; glm::mat4 projectionMatrix; glm::mat4 inverseProjection; glm::vec3 clearColor; glm::vec2 projectionSize; float projectionNearPlane; float projectionFarPlane; Framebuffer framebuffer; float fov = 45.0f; float aspect = 1920.0f / 1080.0f; float zoom = 1.0f; }; } #endif
[ "ambrosiogabe@gmail.com" ]
ambrosiogabe@gmail.com
43121abe4cc63532158f72d199d613cdaa271d06
a1eab6f939f8e1622cf2d6a5bc344762a660a3cf
/algorithm/code/minimal_number.cpp
9028f9dc13373213b3e7ba722a0fdfc335b8305d
[]
no_license
T-tssxuan/data_structure_algorithm
02b21f20adae864ac55857d58c68d6fb806719a4
3a19ac19bd4b56c6971b95fa1adb9d7c857f94fe
refs/heads/master
2021-01-12T16:26:14.980768
2017-08-16T14:06:43
2017-08-16T14:06:43
69,272,305
4
1
null
null
null
null
UTF-8
C++
false
false
1,764
cpp
#include <string> #include <iostream> #include <vector> #include <queue> using namespace std; /** * Describe: Give a series of number, find the minimal number they can find. */ // The order decide compare bool compare(const string &str1, const string &str2){ size_t idx1 = 0; size_t idx2 = 0; while (idx1 < str1.length() && idx2 < str2.length()) { if (str1[idx1] > str2[idx2]) { return true; } else if (str1[idx1] < str2[idx2]) { return false; } ++idx1; ++idx2; } if (idx1 < str1.length()) { string tmp = str1.substr(idx1); return compare(tmp, str2); } if (idx2 < str2.length()) { string tmp = str2.substr(idx2); return compare(str1, tmp); } return false; }; class Solution { public: using PQ = priority_queue<string, vector<string>, function<bool(const string &, const string &)>>; string minNumber(vector<int>& nums) { vector<string> strs(nums.size()); auto trans = [](int a){ return to_string(a); }; transform(nums.begin(), nums.end(), strs.begin(), trans); PQ pq(strs.begin(), strs.end(), compare); string rst; while (!pq.empty()) { rst += pq.top(); pq.pop(); } size_t idx = 0; while (idx < rst.length() && rst[idx] == '0') { ++idx; } rst = rst.substr(idx); return rst == ""? "0" : rst; } }; int main() { Solution so; int n; vector<int> test; while (cin >> n) { test = vector<int>(n); for (auto& ele : test) { cin >> ele; } auto re = so.minNumber(test); cout << "result: " << re << endl; } return 0; }
[ "2270360114@qq.com" ]
2270360114@qq.com
4cf65fe9b3e6a052d442b84a81f8d9247b52083c
db2b7b36ae7eced337d50d31d3917900c4578e59
/ProjectBarnabus/src/GameEngine/Transform.cpp
28781b3717a77e0532cf93069e76a2fc8ca05dae
[]
no_license
conzo096/ProjectBarnabus
6b355efbef61d10599947fc10ff3649513cb6a78
3cf276fd667cba4b429202d7faebb2062da1f601
refs/heads/master
2021-08-03T00:09:05.154905
2020-12-27T17:44:45
2020-12-27T17:44:45
188,912,820
1
0
null
null
null
null
UTF-8
C++
false
false
1,918
cpp
#include "Transform.h" #include <glm/gtc/quaternion.hpp> #include <glm/gtx/euler_angles.hpp> #include <glm/gtx/transform.hpp> Transform::Transform() : scale(glm::vec3(1.0)), rotation(glm::quat()), position(glm::vec3(0)), previousPosition(glm::vec3(0)), transform(glm::mat4(1)), changed(true) { } Transform::Transform(glm::vec3 pos, glm::vec3 rot, glm::vec3 scale) : Transform() { SetPosition(pos); SetRotation(rot); SetScale(scale); changed = true; } Transform::~Transform() { } void Transform::UpdateTransforms() { if (changed) { transform = glm::translate(position) * mat4_cast(rotation) * glm::scale(scale); changed = false; } } const bool Transform::GetChanged() const { return changed; } const glm::vec3 Transform::GetPosition() const { return position; } void Transform::SetPosition(const glm::vec3 v3) { position = v3; changed = true; } void Transform::Move(const glm::vec3 v3) { previousPosition = position; SetPosition(position + v3); changed = true; } const glm::quat Transform::GetRotation() const { return rotation; } void Transform::SetRotation(const glm::quat q) { rotation = q; changed = true; } void Transform::SetRotation(const glm::vec3 v3) { rotation = glm::quat(v3); changed = true; } void Transform::Rotate(const glm::quat q) { SetRotation(rotation * q); changed = true; } void Transform::Rotate(const glm::vec3 v3) { SetRotation(rotation * glm::quat(glm::radians(v3))); changed = true; } const glm::vec3 Transform::GetScale() const { return scale; } void Transform::SetScale(const glm::vec3 v3) { scale = v3; changed = true; } void Transform::Scale(const glm::vec3 v3) { scale *= v3; changed = true; } const glm::mat4 Transform::GetTransform() const { return transform; } void Transform::SetTransform(const glm::mat4 m4) { transform = m4; changed = true; } const glm::vec3 Transform::GetPreviousPosition() const { return previousPosition; }
[ "connerweatherston@hotmail.co.uk" ]
connerweatherston@hotmail.co.uk
9f25ab7aab811e48b4f23afcde2854306404691b
50f8c138da0165fa140c3241291aa2b0a8a14f99
/sequence with digits.cpp
72ec3f360dcda2a3a95adc149073d422a2424842
[]
no_license
Priybhanu99/My-Codes
c5da0821348939d75498e2751bc6c63d5e572294
4dc2e93fb941c4166b3b687a76358a1f309cc976
refs/heads/master
2021-05-19T12:22:09.830851
2021-01-17T15:22:23
2021-01-17T15:22:23
251,694,773
2
0
null
null
null
null
UTF-8
C++
false
false
735
cpp
#include <bits/stdc++.h> using namespace std; #define int long long int int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int t; cin>>t; while(t--){ int n,k; cin>>n>>k; int mnm = INT_MAX; int mxm = INT_MIN; int count = 0; while(mnm!=0 && count<k-1){ int temp = n; mnm = INT_MAX; mxm = INT_MIN; while(temp){ int rem = temp%10; if(rem<mnm){ mnm = rem; } if(rem>mxm){ mxm = rem; } temp /= 10; } n += mnm*mxm; count++; //cout<<n<<" "; } cout<<n<<"\n"; } } // 42 // 487 // 519 // 528 // 544 // 564 // 588 // 628
[ "bhanuyadav1999.by@gmail.com" ]
bhanuyadav1999.by@gmail.com
236ffad97c075df64f0db31f90cedd6a397268d8
2252d70a654948b5aadb06a1158d97e646b8097f
/Competitive Programming/Codeforces/edu87(2)/4.cpp
4da97da8438191d55f9278ecfd2423feb51def0a
[]
no_license
spashal/Competitive-Programming
1b02aea6496f82920924b714eb857189c1542d63
f68e7bdf05dad9eab41bee0c2d9558f92068c244
refs/heads/master
2023-07-26T16:26:36.633063
2021-09-09T04:15:21
2021-09-09T04:15:21
267,501,288
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
cpp
#include <bits/stdc++.h> using namespace std; typedef long double ll; ll mpi = 3.14159265; ll t; int n; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; while( t-- > 0 ){ cin >> n; if( n == 2 ) cout << "1.0000000" << endl; else{ ll ans = 0; if( (n-1)%2==0 ){ ll angler = (ll)(mpi*(n-1))/(n); ll angle = angler/2; for( int i = 0 ; i < (n-1)/2 ; i++ ){ ans += (ll)cos(angle); cout << ans << " "; angle = angler - (mpi/2) - ((mpi)/2 - angle); } } else{ ll angler = (ll)(mpi*(n-1))/(n); ll angle = angler - (mpi/2); for( int i = 0 ; i < (n-1)/2 ; i++ ){ ans += (ll)cos(angle); // cout << ans << " "; angle = angler - (mpi/2) - ((mpi)/2 - angle); } ans += 0.500000000; } ans *= 2; ans += 1; cout << fixed << setprecision(6) << ans << endl; // cout << fixed << setprecision(6) << 2 * ( ( ll)cos((ll)((n-1)*mpi)/( 2*n )) / ( 1 - cos( (ll)(mpi/n)))) << endl; } } return(0); }
[ "palash.sharma@students.iiit.ac.in" ]
palash.sharma@students.iiit.ac.in
3f61433dd1f3eac10d91e1e2b8afb324d5684fe2
0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd
/ash/app_launch_unittest.cc
88deea07253f42a9ae7497d445e8e14a2ab67260
[ "BSD-3-Clause" ]
permissive
yachtcaptain23/browser-android-tabs
e5144cee9141890590d6d6faeb1bdc5d58a6cbf1
a016aade8f8333c822d00d62738a922671a52b85
refs/heads/master
2021-04-28T17:07:06.955483
2018-09-26T06:22:11
2018-09-26T06:22:11
122,005,560
0
0
NOASSERTION
2019-05-17T19:37:59
2018-02-19T01:00:10
null
UTF-8
C++
false
false
1,781
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/components/quick_launch/public/mojom/constants.mojom.h" #include "ash/public/interfaces/constants.mojom.h" #include "base/bind.h" #include "base/command_line.h" #include "base/run_loop.h" #include "services/service_manager/public/cpp/service_test.h" #include "services/ui/public/interfaces/constants.mojom.h" #include "services/ui/public/interfaces/window_server_test.mojom.h" #include "ui/views/layout/layout_provider.h" namespace ash { void RunCallback(bool* success, base::RepeatingClosure callback, bool result) { *success = result; std::move(callback).Run(); } class AppLaunchTest : public service_manager::test::ServiceTest { public: AppLaunchTest() : ServiceTest("ash_unittests") {} ~AppLaunchTest() override = default; private: void SetUp() override { base::CommandLine::ForCurrentProcess()->AppendSwitch("use-test-config"); ServiceTest::SetUp(); } views::LayoutProvider layout_provider_; DISALLOW_COPY_AND_ASSIGN(AppLaunchTest); }; // TODO(sky): reenable this once it is actually uses ash with ws2. TEST_F(AppLaunchTest, DISABLED_TestQuickLaunch) { connector()->StartService(mojom::kServiceName); connector()->StartService(quick_launch::mojom::kServiceName); ui::mojom::WindowServerTestPtr test_interface; connector()->BindInterface(ui::mojom::kServiceName, &test_interface); base::RunLoop run_loop; bool success = false; test_interface->EnsureClientHasDrawnWindow( quick_launch::mojom::kServiceName, base::BindOnce(&RunCallback, &success, run_loop.QuitClosure())); run_loop.Run(); EXPECT_TRUE(success); } } // namespace ash
[ "artem@brave.com" ]
artem@brave.com
f1d159ad1b4676abeaaa9377d3e32ba7f3f0e890
6f6f5f3e2ca4f87415ce308edaa8374833f1f148
/app/src/main/cpp/game_client.cpp
1e7d88bef9ab14e85079dd4e8617964acc6a7f5a
[]
no_license
iplaycloud/xctx_project_p51_ModeSwitch
1fe8462a42c09a3c179ef274d7282300a6ed9e0d
8e5ef09176c12517a6709db59825a40c28a5f924
refs/heads/master
2020-06-18T23:40:26.205667
2016-12-05T02:51:07
2016-12-05T02:51:07
74,934,614
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
cpp
#include <fcntl.h> #include <sys/prctl.h> #include <sys/wait.h> #include <binder/IPCThreadState.h> #include <binder/ProcessState.h> #include <binder/IServiceManager.h> #include <cutils/properties.h> #include <utils/Log.h> #include "IGameEventService.h" using namespace android; /* ./test_client <startService|stopService> */ int main(int argc, char **argv) { int cnt; if (argc < 2){ ALOGI("Usage:\n"); ALOGI("%s <startService|stopService>\n", argv[0]); return -1; } /* getService */ /* 打开驱动, mmap */ sp<ProcessState> proc(ProcessState::self()); /* 获得BpServiceManager */ sp<IServiceManager> sm = defaultServiceManager(); if (strcmp(argv[1], "startService") == 0) { sp<IBinder> binder = sm->getService(String16("GameEvent")); if (binder == 0) { ALOGI("can't get GameEvent service\n"); return -1; } /* service肯定是BpHelloServie指针 */ sp<IGameEventService> service = interface_cast<IGameEventService>(binder); /* 调用Service的函数 */ service->startService(); ALOGI("client call startService"); } else { sp<IBinder> binder = sm->getService(String16("GameEvent")); if (binder == 0) { ALOGI("can't get GameEvent service\n"); return -1; } /* service肯定是BpGoodbyeServie指针 */ sp<IGameEventService> service = interface_cast<IGameEventService>(binder); /* 调用Service的函数 */ service->stopService(); ALOGI("client call stopService"); } return 0; }
[ "iplaycloud@gmail.com" ]
iplaycloud@gmail.com
25549284cebfa914dc4dd0204d8e719d9356ebfd
f90b03c3cb72d6d066e984e8a91004cd9565e2c6
/Arduino/libraries/IRremote/irRecv.cpp
937372297ce843704a44b52990ff708d8c12fcd3
[]
no_license
acid8x/RCRACING
3af6612e2e00bc404e37127a0851de65d8a16bd9
0dbd9e6c4d7944d6c91c2828ff4f6a56508cd0c6
refs/heads/master
2021-01-11T20:26:30.027382
2018-04-24T04:46:09
2018-04-24T04:46:09
79,114,838
0
0
null
null
null
null
UTF-8
C++
false
false
5,788
cpp
#include "IRremote.h" #include "IRremoteInt.h" //+============================================================================= // Decodes the received IR message // Returns 0 if no data ready, 1 if data ready. // Results of decoding are stored in results // int IRrecv::decode (decode_results *results) { results->rawbuf = irparams.rawbuf; results->rawlen = irparams.rawlen; results->overflow = irparams.overflow; if (irparams.rcvstate != STATE_STOP) return false ; #if DECODE_NEC DBG_PRINTLN("Attempting NEC decode"); if (decodeNEC(results)) return true ; #endif #if DECODE_SONY DBG_PRINTLN("Attempting Sony decode"); if (decodeSony(results)) return true ; #endif #if DECODE_SANYO DBG_PRINTLN("Attempting Sanyo decode"); if (decodeSanyo(results)) return true ; #endif #if DECODE_MITSUBISHI DBG_PRINTLN("Attempting Mitsubishi decode"); if (decodeMitsubishi(results)) return true ; #endif #if DECODE_RC5 DBG_PRINTLN("Attempting RC5 decode"); if (decodeRC5(results)) return true ; #endif #if DECODE_RC6 DBG_PRINTLN("Attempting RC6 decode"); if (decodeRC6(results)) return true ; #endif #if DECODE_PANASONIC DBG_PRINTLN("Attempting Panasonic decode"); if (decodePanasonic(results)) return true ; #endif #if DECODE_LG DBG_PRINTLN("Attempting LG decode"); if (decodeLG(results)) return true ; #endif #if DECODE_JVC DBG_PRINTLN("Attempting JVC decode"); if (decodeJVC(results)) return true ; #endif #if DECODE_SAMSUNG DBG_PRINTLN("Attempting SAMSUNG decode"); if (decodeSAMSUNG(results)) return true ; #endif #if DECODE_WHYNTER DBG_PRINTLN("Attempting Whynter decode"); if (decodeWhynter(results)) return true ; #endif #if DECODE_AIWA_RC_T501 DBG_PRINTLN("Attempting Aiwa RC-T501 decode"); if (decodeAiwaRCT501(results)) return true ; #endif #if DECODE_DENON DBG_PRINTLN("Attempting Denon decode"); if (decodeDenon(results)) return true ; #endif // decodeHash returns a hash on any input. // Thus, it needs to be last in the list. // If you add any decodes, add them before this. if (decodeHash(results)) return true ; // Throw away and start over resume(); return false; } //+============================================================================= IRrecv::IRrecv (int recvpin) : irparams() { irparams.recvpin = recvpin; irparams.blinkflag = 0; irparamslist[irparams_used] = &irparams; irparams_used++; } IRrecv::IRrecv (int recvpin, int blinkpin) { irparams.recvpin = recvpin; irparams.blinkpin = blinkpin; pinMode(blinkpin, OUTPUT); irparams.blinkflag = 0; } //+============================================================================= // initialization // void IRrecv::enableIRIn ( ) { cli(); // Setup pulse clock timer interrupt // Prescale /8 (16M/8 = 0.5 microseconds per tick) // Therefore, the timer interval can range from 0.5 to 128 microseconds // Depending on the reset value (255 to 0) TIMER_CONFIG_NORMAL(); // Timer2 Overflow Interrupt Enable TIMER_ENABLE_INTR; TIMER_RESET; sei(); // enable interrupts // Initialize state machine variables irparams.rcvstate = STATE_IDLE; irparams.rawlen = 0; // Set pin modes pinMode(irparams.recvpin, INPUT); } //+============================================================================= // Enable/disable blinking of pin 13 on IR processing // void IRrecv::blink13 (int blinkflag) { irparams.blinkflag = blinkflag; if (blinkflag) pinMode(BLINKLED, OUTPUT) ; } //+============================================================================= // Return if receiving new IR signals // bool IRrecv::isIdle ( ) { return (irparams.rcvstate == STATE_IDLE || irparams.rcvstate == STATE_STOP) ? true : false; } //+============================================================================= // Restart the ISR state machine // void IRrecv::resume ( ) { irparams.rcvstate = STATE_IDLE; irparams.rawlen = 0; } //+============================================================================= // hashdecode - decode an arbitrary IR code. // Instead of decoding using a standard encoding scheme // (e.g. Sony, NEC, RC5), the code is hashed to a 32-bit value. // // The algorithm: look at the sequence of MARK signals, and see if each one // is shorter (0), the same length (1), or longer (2) than the previous. // Do the same with the SPACE signals. Hash the resulting sequence of 0's, // 1's, and 2's to a 32-bit value. This will give a unique value for each // different code (probably), for most code systems. // // http://arcfn.com/2010/01/using-arbitrary-remotes-with-arduino.html // // Compare two tick values, returning 0 if newval is shorter, // 1 if newval is equal, and 2 if newval is longer // Use a tolerance of 20% // int IRrecv::compare (unsigned int oldval, unsigned int newval) { if (newval < oldval * .7) return 0 ; else if (oldval < newval * .7) return 2 ; else return 1 ; } //+============================================================================= // Use FNV hash algorithm: http://isthe.com/chongo/tech/comp/fnv/#FNV-param // Converts the raw code values into a 32-bit hash code. // Hopefully this code is unique for each button. // This isn't a "real" decoding, just an arbitrary value. // #define FNV_PRIME_32 16777619 #define FNV_BASIS_32 2166136261 long IRrecv::decodeHash (decode_results *results) { long hash = FNV_BASIS_32; // Require at least 6 samples to prevent triggering on noise if (results->rawlen < 6) return false ; for (int i = 1; (i + 2) < results->rawlen; i++) { int value = compare(results->rawbuf[i], results->rawbuf[i+2]); // Add value into the hash hash = (hash * FNV_PRIME_32) ^ value; } results->value = hash; results->bits = 32; results->decode_type = UNKNOWN; return true; }
[ "acid8x@gmail.com" ]
acid8x@gmail.com
288901475252d80a65f8fab91d3a2961ca72d925
a1b93fd969fa04db05f01a3783f7e9ff77c0c9df
/Random/random.hh
5755cd869ae5d6d4304bf84a5296cf791555e7e1
[]
no_license
mvdsanden/mvds
a31176d423203abf4e5b16a5effdebd7e2c054d8
c95c1b4706dc718cb7dcee6dee01c922691d7968
refs/heads/master
2021-01-19T14:04:54.389200
2009-10-27T20:14:14
2009-10-27T20:14:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,796
hh
#ifndef __INC_MVDS_RANDOM_HH__ #define __INC_MVDS_RANDOM_HH__ #include <algorithm> #include <gsl/gsl_rng.h> #include <cmath> namespace mvds { class Random { static Random *s_instance; Random(); public: ~Random(); static void initialize(); static void finish(); static Random &instance(); /** * Seed the random number generator. */ void seed(unsigned seed); /** * @returns a uniform distributed random value in the range [0,1). */ double uniform(); /** * @returns a uniform distributed random value in the range [r0,r1). */ double uniform(double r0, double r1); /** * @param sigma the standard deviation. * @param mu the means. * * @returns a normal (gaussian) distributed random value (N(mu,sigma)). */ double normal(double sigma); double normal(double mu, double sigma); /** * @returns a uniform distributed random value in the range [r0,r1). */ size_t inRange(size_t r0, size_t r1); /** * @returns true with a probability of pHeads. */ bool coinToss(double pHeads = 0.5); /** * This operator can be used with random_shuffle. */ ptrdiff_t operator()(ptrdiff_t scale); private: gsl_rng *d_random; }; inline double Random::uniform(double r0, double r1) { return r0 + uniform() / (r1 - r0); } inline double Random::normal(double mu, double sigma) { return mu + normal(sigma); } inline size_t Random::inRange(size_t r0, size_t r1) { return std::min(r0,r1) + (1.0/labs(r0 - r1)) * uniform(); } inline bool Random::coinToss(double pHeads) { return uniform() < pHeads; } inline ptrdiff_t Random::operator()(ptrdiff_t scale) { return std::floor(inRange(0,scale)); } }; #endif // __INC_MVDS_RANDOM_HH__
[ "mart.vd.sanden@gmail.com" ]
mart.vd.sanden@gmail.com
ac36cdc32d03e8e2cb0828aa040afa92fec280c5
92adab7f98dc2e694739558e925dc4a408aa7da8
/cpp/CSC2104/labtest5/binary_search_tree.cpp
fbf5ea308559eb4f4bdc8af6a3571bc6a9ebaff2
[]
no_license
wzulfikar/lab
a5c29d54baa111526032741a7850ebf9457148a3
2ef21c16150a88a15bfb7bf4ef0014fbee262ed3
refs/heads/master
2023-07-23T21:37:46.047237
2022-10-14T20:31:15
2022-10-14T20:31:15
83,702,755
3
2
null
2023-07-12T00:14:00
2017-03-02T16:56:58
Jupyter Notebook
UTF-8
C++
false
false
2,421
cpp
#include <iostream> #include <list> using namespace std; // template template<class T> class Node { public: T value; Node<T>* left; Node<T>* right; Node(T value) { this->value = value; this->left = NULL; this->right = NULL; } }; template<class F> class BST { private: Node<F> *root; void prefix (Node<F>* current) { if (current != NULL) { cout << current->value << ' '; prefix(current->left); prefix(current->right); } } void infix (Node<F>* current) { if (current != NULL) { infix(current->left); cout << current->value << ' '; infix(current->right); } } void reverseInfix (Node<F>* current) { if (current != NULL) { reverseInfix(current->right); cout << current->value << ' '; reverseInfix(current->left); } } void postfix (Node<F>* current) { if (current != NULL) { postfix(current->left); postfix(current->right); cout << current->value << ' '; } } public: BST(){ root = NULL; } void insert (F value) { if (root == NULL) { root = new Node<F>(value); } else { Node<F>* temp = root; while (temp != NULL) { if (value > temp->value) { if (temp->right == NULL) { temp->right = new Node<F>(value); break; } temp = temp->right; } else { if (temp->left == NULL) { temp->left = new Node<F>(value); break; } temp = temp->left; } } } } bool find (F value) { Node<F>* temp = root; while (temp != NULL) { if (value == temp->value) { return true; } temp = value > temp->value ? temp->right : temp->left; } return false; } void display (int order = 0) { switch (order) { case 0: cout << "Displaying tree in PREFIX mode:\n"; prefix(root); break; case 1: cout << "Displaying tree in INFIX mode:\n"; infix(root); break; case 2: cout << "Displaying tree in POSTFIX mode:\n"; postfix(root); break; case 3: cout << "Displaying tree in REVERSE-INVIX mode:\n"; reverseInfix(root); break; default: prefix(root); } } }; int main() { BST<int> tree; tree.insert(5); tree.insert(10); tree.insert(3); tree.insert(7); tree.insert(10); tree.insert(7); tree.display(3); string findNode = tree.find(11) ? "Found" : "Not found"; cout << "\nNode 11 is " << findNode; string findNode2 = tree.find(10) ? "Found" : "Not found"; cout << "\nNode 10 is " << findNode2; return 0; }
[ "me@wzulfikar.com" ]
me@wzulfikar.com
8ea6b9ebedb383a93a4f77342f6d13eaabeab8d4
33a5e1bf4e09b84c2d895cd739ed732066d0486a
/hlesgx_test/App/App.cpp
59e3ab70bdc51f3827d4f360e3dfb49dfaa1e0d9
[]
no_license
StanPlatinum/tsx-in-sgx
d3bcde61bb881e16fff74c7809c4496bea4fef1f
285e6b0b9d8c1a52faea8f19f80e5f4ccc1a4e66
refs/heads/master
2020-05-24T13:33:03.364075
2020-03-22T19:25:21
2020-03-22T19:25:21
187,291,426
0
0
null
null
null
null
UTF-8
C++
false
false
7,435
cpp
/* * Copyright (C) 2011-2017 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <stdio.h> #include <string.h> #include <assert.h> # include <unistd.h> # include <pwd.h> # define MAX_PATH FILENAME_MAX #include "sgx_urts.h" #include "App.h" #include "Enclave_u.h" /* Global EID shared by multiple threads */ sgx_enclave_id_t global_eid = 0; typedef struct _sgx_errlist_t { sgx_status_t err; const char *msg; const char *sug; /* Suggestion */ } sgx_errlist_t; /* Error code returned by sgx_create_enclave */ static sgx_errlist_t sgx_errlist[] = { { SGX_ERROR_UNEXPECTED, "Unexpected error occurred.", NULL }, { SGX_ERROR_INVALID_PARAMETER, "Invalid parameter.", NULL }, { SGX_ERROR_OUT_OF_MEMORY, "Out of memory.", NULL }, { SGX_ERROR_ENCLAVE_LOST, "Power transition occurred.", "Please refer to the sample \"PowerTransition\" for details." }, { SGX_ERROR_INVALID_ENCLAVE, "Invalid enclave image.", NULL }, { SGX_ERROR_INVALID_ENCLAVE_ID, "Invalid enclave identification.", NULL }, { SGX_ERROR_INVALID_SIGNATURE, "Invalid enclave signature.", NULL }, { SGX_ERROR_OUT_OF_EPC, "Out of EPC memory.", NULL }, { SGX_ERROR_NO_DEVICE, "Invalid SGX device.", "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards." }, { SGX_ERROR_MEMORY_MAP_CONFLICT, "Memory map conflicted.", NULL }, { SGX_ERROR_INVALID_METADATA, "Invalid enclave metadata.", NULL }, { SGX_ERROR_DEVICE_BUSY, "SGX device was busy.", NULL }, { SGX_ERROR_INVALID_VERSION, "Enclave version was invalid.", NULL }, { SGX_ERROR_INVALID_ATTRIBUTE, "Enclave was not authorized.", NULL }, { SGX_ERROR_ENCLAVE_FILE_ACCESS, "Can't open enclave file.", NULL }, }; /* Check error conditions for loading enclave */ void print_error_message(sgx_status_t ret) { size_t idx = 0; size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0]; for (idx = 0; idx < ttl; idx++) { if(ret == sgx_errlist[idx].err) { if(NULL != sgx_errlist[idx].sug) printf("Info: %s\n", sgx_errlist[idx].sug); printf("Error: %s\n", sgx_errlist[idx].msg); break; } } if (idx == ttl) printf("Error: Unexpected error occurred.\n"); } /* Initialize the enclave: * Step 1: try to retrieve the launch token saved by last transaction * Step 2: call sgx_create_enclave to initialize an enclave instance * Step 3: save the launch token if it is updated */ int initialize_enclave(void) { char token_path[MAX_PATH] = {'\0'}; sgx_launch_token_t token = {0}; sgx_status_t ret = SGX_ERROR_UNEXPECTED; int updated = 0; /* Step 1: try to retrieve the launch token saved by last transaction * if there is no token, then create a new one. */ /* try to get the token saved in $HOME */ const char *home_dir = getpwuid(getuid())->pw_dir; if (home_dir != NULL && (strlen(home_dir)+strlen("/")+sizeof(TOKEN_FILENAME)+1) <= MAX_PATH) { /* compose the token path */ strncpy(token_path, home_dir, strlen(home_dir)); strncat(token_path, "/", strlen("/")); strncat(token_path, TOKEN_FILENAME, sizeof(TOKEN_FILENAME)+1); } else { /* if token path is too long or $HOME is NULL */ strncpy(token_path, TOKEN_FILENAME, sizeof(TOKEN_FILENAME)); } FILE *fp = fopen(token_path, "rb"); if (fp == NULL && (fp = fopen(token_path, "wb")) == NULL) { printf("Warning: Failed to create/open the launch token file \"%s\".\n", token_path); } if (fp != NULL) { /* read the token from saved file */ size_t read_num = fread(token, 1, sizeof(sgx_launch_token_t), fp); if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) { /* if token is invalid, clear the buffer */ memset(&token, 0x0, sizeof(sgx_launch_token_t)); printf("Warning: Invalid launch token read from \"%s\".\n", token_path); } } /* Step 2: call sgx_create_enclave to initialize an enclave instance */ /* Debug Support: set 2nd parameter to 1 */ ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, &token, &updated, &global_eid, NULL); if (ret != SGX_SUCCESS) { print_error_message(ret); if (fp != NULL) fclose(fp); return -1; } /* Step 3: save the launch token if it is updated */ if (updated == FALSE || fp == NULL) { /* if the token is not updated, or file handler is invalid, do not perform saving */ if (fp != NULL) fclose(fp); return 0; } /* reopen the file with write capablity */ fp = freopen(token_path, "wb", fp); if (fp == NULL) return 0; size_t write_num = fwrite(token, 1, sizeof(sgx_launch_token_t), fp); if (write_num != sizeof(sgx_launch_token_t)) printf("Warning: Failed to save launch token to \"%s\".\n", token_path); fclose(fp); return 0; } /* OCall functions */ void Ocall_PrintString(const char *str){ printf("%s", str); } /* Application entry */ int SGX_CDECL main(int argc, char *argv[]) { (void)(argc); (void)(argv); /* Initialize the enclave */ if(initialize_enclave() < 0){ printf("Please enter a character before exit ...\n"); getchar(); return -1; } /* * to-do */ hle_test(global_eid); /* Destroy the enclave */ sgx_destroy_enclave(global_eid); return 0; }
[ "weijliu@bio-sgx.soic.indiana.edu" ]
weijliu@bio-sgx.soic.indiana.edu
827314b59cde13e29647b53545413e0146d1a823
9547c22035266bf5fb414090bbe0e5bfb454cdbb
/src/main.cpp
409f309dfb303483f984e917c1e3dd26d5dffb1f
[]
no_license
haohaoh4/my-compiler
42f9c4e310fce7d82a0fc1b74709e152800f5489
67605df8dd2889716b96fb44663b88d3ac197e94
refs/heads/master
2020-12-03T00:17:49.567470
2017-07-02T09:32:02
2017-07-02T09:32:02
96,010,765
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,316
cpp
#include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; enum { EOS, //end of setence TYPE, EXP, //±í´ïʽ NAME, OP, ERR }; string types[]= { "int", "char" }; bool is_a_var(string); int get(); void pass(); bool com_exp(); int point=0; string source; int get() { char *p = const_cast<char*>(source.c_str()); p+=point; string s; int times=0; if(point>=source.length()) return EOF; while(p[point+times]!=' ' && point+times<s.length()) { s+=p[point+times]; times++; } if(s=="") return EOF; if(s==";") return EOS; for(int i=0;i<sizeof(types)/sizeof(string);i++) { if(s==types[i]) return TYPE; } if(is_a_var(s)) return NAME; for(int i=0;i<10;i++) { if(s[0]==i+'0') return EXP; } return ERR; } string get_string() { char *p = const_cast<char*>(source.c_str()); string s; int times=0; while(p[point+times]!=' ' && point+times<source.length()) { s+=p[point+times]; times++; } return s; } struct var { string name; string type; }; vector<var> vars; bool is_a_var(string str) { for(vector<var>::iterator i=vars.begin();i!=vars.end();i++) { if((*i).name==str) return true; } return false; } bool def_var() { var n; n.type=get_string(); pass(); n.name=get_string(); pass(); vars.push_back(n); cout<<"Define a var:"<<n.type<<" "<<n.name<<endl; return true; } void pass() { if(point>=source.length()) return; while(source[point]!=' ' && source[point+1]!=';') point++; int times=0; while(source[point]) { point++,times++; } return; } int main() { char file[255]; cout<<"enter the file name:[test.c]"; cin.getline(file,254); cout<<endl; ifstream fin(file); if(!fin) { cout<<"failed"; return -1; } istreambuf_iterator<char> beg(fin), end; string sour(beg, end); source=sour; while(get()!=EOF) { while(1) { int status=get(); switch (status) { case EOS: pass(); cout<<"EOS"<<endl; break; case TYPE: if(get()==OP) com_exp(); else if(!def_var())goto error; break; case NAME: if(get()==OP) if(!com_exp())goto error; if(get()==EOS) pass(); break; case ERR: error: cout<<"ERROR "<<point<<endl; pass(); } } } return 0; } bool com_exp() { return true; }
[ "handahao@163.com" ]
handahao@163.com
769a329727ea67d9f9889d5d6be46c569c92580d
a453f5e6a44bf39e52335b2f4b4e7aae3baad8ff
/THREAD_STORE.cpp
2510e48450c385671ab79889b0476b55711b69e5
[ "MIT" ]
permissive
iliya-dehsarvi/Advanced-CPP
b594b41c2c67d7880cc6387dc46745c0d052c4fe
36d26fd147ccf29f8f8a19b3f524cff672f40ad7
refs/heads/main
2023-06-25T05:17:20.233448
2021-07-26T18:06:25
2021-07-26T18:06:25
389,724,987
0
0
null
null
null
null
UTF-8
C++
false
false
13,008
cpp
#include <iostream> #include <vector> #include <string> #include <exception> #include <fstream> #include <regex> #include <bitset> #include <math.h> #include <map> #include <sstream> #include <algorithm> #include <queue> #include <thread> #include <mutex> std::mutex GLOBAL_MUTEX; /* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ g++ --std=c++11 THREAD_STORE.cpp -o THREAD_STORE && ./THREAD_STORE ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ */ class BARCODES { std::vector<std::pair<std::string, std::string>> _CONTAINER; public: BARCODES() { _CONTAINER.push_back(std::pair<std::string, std::string>(" ", "nwwnnnwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("-", "nwnnnnwnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("+", "nwnnnwnwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("$", "nwnwnwnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("%", "nnnwnwnwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("*", "nwnnwnwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>(".", "wwnnnnwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("/", "nwnwnnnwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("0", "nnnwwnwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("1", "wnnwnnnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("2", "nnwwnnnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("3", "wnwwnnnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("4", "nnnwwnnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("5", "wnnwwnnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("6", "nnwwwnnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("7", "nnnwnnwnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("8", "wnnwnnwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("9", "nnwwnnwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("A", "wnnnnwnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("B", "nnwnnwnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("C", "wnwnnwnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("D", "nnnnwwnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("E", "wnnnwwnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("F", "nnwnwwnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("G", "nnnnnwwnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("H", "wnnnnwwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("I", "nnwnnwwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("J", "nnnnwwwnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("K", "wnnnnnnww")); _CONTAINER.push_back(std::pair<std::string, std::string>("L", "nnwnnnnww")); _CONTAINER.push_back(std::pair<std::string, std::string>("M", "wnwnnnnwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("N", "nnnnwnnww")); _CONTAINER.push_back(std::pair<std::string, std::string>("O", "wnnnwnnwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("P", "nnwnwnnwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("Q", "nnnnnnwww")); _CONTAINER.push_back(std::pair<std::string, std::string>("R", "wnnnnnwwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("S", "nnwnnnwwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("T", "nnnnwnwwn")); _CONTAINER.push_back(std::pair<std::string, std::string>("U", "wwnnnnnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("V", "nwwnnnnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("W", "wwwnnnnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("X", "nwnnwnnnw")); _CONTAINER.push_back(std::pair<std::string, std::string>("Y", "wwnnwnnnn")); _CONTAINER.push_back(std::pair<std::string, std::string>("Z", "nwwnwnnnn")); } std::string operator [] (std::string KEY) { std::string NEW_KEY = ""; for (auto CHAR: KEY) { if (CHAR=='0') { NEW_KEY+='n'; } else { NEW_KEY+='w'; } } for (auto CHAR: _CONTAINER) { if (CHAR.second==NEW_KEY) { return CHAR.first; } } return ""; } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ class PRODUCT_INFO { BARCODES _CODES; std::string _PRODUCT_NAME(std::string PASSED_BARCODE) { int CHAR_COUNT=0; std::string CHAR_HOLDER=""; std::string NEW_NAME=""; for (char CHAR: PASSED_BARCODE) { CHAR_HOLDER+=CHAR; CHAR_COUNT++; if (CHAR_COUNT==9) { NEW_NAME+=_CODES[CHAR_HOLDER]; CHAR_HOLDER=""; CHAR_COUNT=0; } } return NEW_NAME; } public: std::string _BARCODE; std::string _NAME; double _PRICE; PRODUCT_INFO(std::string PASSED_BARCODE, double PASSED_PRICE) { _NAME = _PRODUCT_NAME(PASSED_BARCODE); _BARCODE = PASSED_BARCODE; _PRICE = PASSED_PRICE; } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ class PRODUCT_DATABASE { std::vector<PRODUCT_INFO> _DATABASE; public: void INSERT(PRODUCT_INFO NEW_PRODUCT) { _DATABASE.push_back(NEW_PRODUCT); } std::unique_ptr<PRODUCT_INFO> operator [] (std::string PASSED_HEX_CODE) { for (auto OBJECT: _DATABASE) { if (OBJECT._BARCODE == PASSED_HEX_CODE) { std::unique_ptr<PRODUCT_INFO> OBJECT_PTR(new PRODUCT_INFO(OBJECT)); return OBJECT_PTR; } } return nullptr; } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ class XML_PROCESSOR { PRODUCT_DATABASE _DB; public: XML_PROCESSOR(std::string FILENAME="ProductPrice.xml") { std::ifstream DATABASE_FILE; std::regex REGEX("<.*>(.*)</.*>"); std::string BUFFER; std::string NEW_BARCODE; int MODULE = 0; DATABASE_FILE.open(FILENAME); if (!DATABASE_FILE) { std::cout << "UNABLE TO OPEN THE FILE, '"+FILENAME+"'.\n"; exit(1); } while (DATABASE_FILE >> BUFFER) { std::smatch MATCHES; std::regex_match(BUFFER, MATCHES, REGEX); if (MATCHES.size()) { if (MODULE%2) { NEW_BARCODE=MATCHES[1].str(); } else { PRODUCT_INFO PRODUCT(NEW_BARCODE, std::stod(MATCHES[1].str())); _DB.INSERT(PRODUCT); } } MODULE++; } DATABASE_FILE.close(); } PRODUCT_DATABASE DB() { return _DB; } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ struct ORDER_INFO { std::string ID; std::vector<std::string> PRODUCTS; ORDER_INFO(std::string PASSED_ID, std::vector<std::string> PASSED_PRODUCTS) { ID = PASSED_ID; PRODUCTS = PASSED_PRODUCTS; } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ class CUSTOMER_ORDERS { std::vector<ORDER_INFO> _ORDERS; std::string _CHECK_REGEX(std::string TO_BE_CHECKED) { std::regex REGEX("([A-Z0-9]+)"); std::smatch MATCHES; if (std::regex_match(TO_BE_CHECKED, MATCHES, REGEX)) { return MATCHES[0]; } return ""; } public: CUSTOMER_ORDERS(std::string FILENAME="Carts.csv") { std::ifstream ORDERS_FILE; std::string CART_NAME; std::string HEX_ORDERS; std::string PARSER; ORDERS_FILE.open(FILENAME); if (!ORDERS_FILE) { std::cout << "UNABLE TO OPEN THE FILE, '"+FILENAME+"'.\n"; exit(1); } while (ORDERS_FILE >> CART_NAME) { ORDERS_FILE >> HEX_ORDERS; PARSER=""; std::vector<std::string> ITEM_LIST; std::smatch MATCHES; for (auto CHAR: HEX_ORDERS) { if (CHAR==',' && _CHECK_REGEX(PARSER)!="") { ITEM_LIST.push_back(PARSER); PARSER=""; } else if (CHAR!=',') { PARSER+=CHAR; } } if (_CHECK_REGEX(PARSER)!="") { ITEM_LIST.push_back(PARSER); } ORDER_INFO NEW_ORDER(CART_NAME,ITEM_LIST); _ORDERS.push_back(NEW_ORDER); } ORDERS_FILE.close(); } std::vector<std::deque<ORDER_INFO>> ORDERS() { std::vector<std::deque<ORDER_INFO>> _LANES; for (int _INDEX=0; _INDEX<12; _INDEX++) { _LANES.push_back(std::deque<ORDER_INFO>()); } for (int _INDEX=0; _INDEX<_ORDERS.size(); _INDEX++) { _LANES[_INDEX%12].push_back(_ORDERS[_INDEX]); } return _LANES; } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ struct HASH_NODE { std::string CART_ID; std::vector<PRODUCT_INFO> ITEMS; HASH_NODE(std::string PASSED_CART_ID, std::vector<PRODUCT_INFO> PASSED_ITEMS) { CART_ID=PASSED_CART_ID; ITEMS=PASSED_ITEMS; } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ class HASH { XML_PROCESSOR _STORE_DATABASE; std::deque<std::thread> _LANE_THREADS; PRODUCT_DATABASE _DATABASE = _STORE_DATABASE.DB(); std::vector<HASH_NODE> _TABLE; std::string _CONEVRT(std::string HEX_CODE) { std::string BARCODE = ""; std::for_each(HEX_CODE.begin(), HEX_CODE.end(), [&BARCODE](char& CHAR) { if (CHAR >= 'A' && CHAR <= 'Z') { char NEW_CHAR = CHAR - 55; std::bitset<4> BITS(NEW_CHAR); BARCODE += BITS.to_string(); } else { std::bitset<4> BITS(CHAR); BARCODE += BITS.to_string(); } }); return BARCODE; } void _PUSH_BACK(ORDER_INFO ORDER) { std::vector<PRODUCT_INFO> CONVERTED_ORDERS; for (auto DATA: ORDER.PRODUCTS) { auto RETURNED = _DATABASE[_CONEVRT(DATA)]; if (RETURNED) { CONVERTED_ORDERS.push_back(*RETURNED); } } if (CONVERTED_ORDERS.size()==0) { return; } for (auto DATA: _TABLE) { if (DATA.CART_ID == ORDER.ID) { DATA.ITEMS.insert(DATA.ITEMS.end(), CONVERTED_ORDERS.begin(), CONVERTED_ORDERS.end()); return; } } HASH_NODE NEW_NODE(ORDER.ID, CONVERTED_ORDERS); _TABLE.push_back(NEW_NODE); } void _LANE_THREAD_CALLBACK(std::deque<ORDER_INFO> LANE) { GLOBAL_MUTEX.lock(); for (auto CART: LANE) { _PUSH_BACK(CART); } GLOBAL_MUTEX.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } public: std::vector<HASH_NODE> PROCESS(std::vector<std::deque<ORDER_INFO>> LANES) { for (auto LANE: LANES) { _LANE_THREADS.emplace_back(std::thread (&HASH::_LANE_THREAD_CALLBACK, this, LANE)); } for_each(_LANE_THREADS.begin(), _LANE_THREADS.end(), [](std::thread& LANE_THREAD) { LANE_THREAD.join(); }); return _TABLE; } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ class THREADING { std::vector<std::deque<HASH_NODE>> _LANES; std::deque<std::thread> _LANE_THREADS; void _DISPLAY_CART(HASH_NODE CART, int INDEX) { double TOTAL=0; std::cout << "\nLANE " << INDEX+1 << ": " << CART.CART_ID << "\n- - - - - - - - - - - - - - - --\n"; for (auto _DATA: CART.ITEMS) { TOTAL+=_DATA._PRICE; std::cout << _DATA._NAME << ":\t\t\t$" << _DATA._PRICE << "\n"; } std::cout << "- - - - - - - - - - - - - - - --\nTOTAL:\t\t\t$" << TOTAL << "\n--------------------------------\n"; } void _LANE_THREAD_CALLBACK(std::deque<HASH_NODE> LANE, int INDEX) { GLOBAL_MUTEX.lock(); for (auto CART: LANE) { _DISPLAY_CART(CART, INDEX); } GLOBAL_MUTEX.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } public: THREADING(std::vector<HASH_NODE> PASSED_TABLE) { int INDEX=0; for (int _INDEX=0; _INDEX<12; _INDEX++) { _LANES.push_back(std::deque<HASH_NODE>()); } for (int _INDEX=0; _INDEX<PASSED_TABLE.size(); _INDEX++) { _LANES[_INDEX%12].push_back(PASSED_TABLE[_INDEX]); } for (auto LANE: _LANES) { _LANE_THREADS.emplace_back(std::thread (&THREADING::_LANE_THREAD_CALLBACK, this, LANE, INDEX)); INDEX++; } for_each(_LANE_THREADS.begin(), _LANE_THREADS.end(), [](std::thread& LANE_THREAD) { LANE_THREAD.join(); }); } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ class STORE { XML_PROCESSOR _STORE_DATABASE; CUSTOMER_ORDERS _STORE_ORDERS; HASH _HASHED_ORDERS; public: STORE() { THREADING LANES(_HASHED_ORDERS.PROCESS(_STORE_ORDERS.ORDERS())); } }; /*~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~*/ int main() { STORE LOCAL_STORE; return 0; }
[ "noreply@github.com" ]
iliya-dehsarvi.noreply@github.com
2b1da003432d6141acd8b867ca04e2709974f15d
eb20d54d53268637fd3ec43575f30a06f0f02f79
/antigos/1856.cpp
3ab2176bc45180d1ec56d2b8fd3c7e6c631659a2
[]
no_license
biessek/maratona
f934033d8d85eef35fd9e1b19107d850caa25191
b4b7dcc49ed221203df24c1934ef09b26671c837
refs/heads/master
2021-07-04T22:50:22.870648
2017-09-28T03:14:29
2017-09-28T03:14:29
105,094,465
0
0
null
null
null
null
UTF-8
C++
false
false
3,930
cpp
#include<cstdio> #include<cmath> #include<algorithm> #include<map> #include<vector> #include<list> using namespace std; typedef pair<int, list<int>::iterator> tupla; const int MAXTAM = 318; int N, Q; map<int, tupla > P; struct setor { int q; list<int>::iterator l,r; setor() { q=0; } } QTR[MAXTAM]; list<int> A; void remove(int p) { tupla q = P[p]; // setor. QTR[q.first].q--; int setor = q.first; if(q.second == QTR[setor].l) { QTR[setor].l++; } else if(q.second == QTR[setor].r) { QTR[setor].r--; } else { list<int>::iterator it = QTR[setor].l; it++; while(it!=QTR[setor].r){ if(*it == p) break; it++; } } A.erase(q.second); while(setor+1<MAXTAM && QTR[setor+1].q > 0) { QTR[setor+1].q--; QTR[setor].r = QTR[setor+1].l; P[*QTR[setor].r].first = setor; QTR[setor+1].l++; QTR[setor].q++; if(QTR[setor].q==1) { QTR[setor].l = QTR[setor].r; } setor++; } } void insere(int p, int e) { int setor = e? P[e].first:0; list<int>::iterator posicao = e? P[e].second : A.end(); posicao++; P[p].first = setor; P[p].second = A.insert(posicao,p); QTR[setor].q++; if(QTR[setor].q==1) { QTR[setor].r = QTR[setor].l = P[p].second; } else if(e == *QTR[setor].r) { QTR[setor].r = P[p].second; } while(setor+1<MAXTAM && QTR[setor].q >MAXTAM ) { QTR[setor+1].q++; QTR[setor+1].l = QTR[setor].r; P[*QTR[setor].r].first = setor+1; QTR[setor].r--; QTR[setor].q--; if(QTR[setor+1].q==1) { QTR[setor+1].r = QTR[setor+1].l; } setor++; } } int query(int p, int e) { if(e==p) return 0; int set1, set2; set1 = P[p].first; set2 = P[e].first; list<int>::iterator l1, l2; if(set1==set2) { bool contando = false; int res=0; for(l1 = QTR[set1].l;l1!=QTR[set1].r;l1++) { if(*l1 == p || *l1 == e) { if(contando) break; else contando = true; } else if(contando) res++; } return res; } else { if(set2 < set1) { swap(p,e); swap(set2,set1);} int res=0; if(QTR[set1].r != P[p].second) { l1=P[p].second; l1++; l2 = QTR[set1].r; l2++; while(l1!=l2) { res++; l1++; } } if(QTR[set2].l != P[e].second) { l1=QTR[set2].l; l2 = P[e].second; while(l1!=l2) { res++; l1++; } } set1++; set2; while(set1<set2) { res+=QTR[set1++].q; } return res; } } // void printsetores() { // for(int q=0;q<MAXTAM;q++) { // if(QTR[q].q > 0) { // printf("setor %d|%d %d = %d\n", q, QTR[q].q, *QTR[q].l,*QTR[q].r); // } // } // puts("ini"); // for(map<int,pair<int,list<int>::iterator> >::iterator it = P.begin();it!=P.end();it++) // printf("p %d = %d\n", (*it).first, (*it).second.first); // } int main() { int i, p, e; char op; fill(QTR,QTR+MAXTAM,setor()); A.clear(); P.clear(); scanf("%d", &N); for(i=0;i<N;i++) { scanf("%d", &p); insere(p, !A.empty()? A.back(): 0); } scanf("%d", &Q); while(Q--) { scanf(" %c", &op); if(op == 'I') { scanf(" %d %d", &p, &e); insere(p,e); } else if(op == 'Q') { scanf(" %d %d", &p, &e); // printsetores(); puts("res"); printf("%d\n", query(p,e)); } else { scanf(" %d", &p); remove(p); } // printsetores(); } // printf("%d\n", P[99999].first); return 0; }
[ "root@DESKTOP-V5LA2IB.localdomain" ]
root@DESKTOP-V5LA2IB.localdomain
a3e1325f206592e6fdd3f04b15c9c85940370042
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/net/proxy/proxy_config.cc
87e17d8eb487d39f66c2c51a8dd1588bc493114c
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
9,150
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/proxy_config.h" #include <memory> #include <utility> #include "base/logging.h" #include "base/strings/string_tokenizer.h" #include "base/strings/string_util.h" #include "base/values.h" #include "net/proxy/proxy_info.h" namespace net { namespace { // If |proxies| is non-empty, sets it in |dict| under the key |name|. void AddProxyListToValue(const char* name, const ProxyList& proxies, base::DictionaryValue* dict) { if (!proxies.IsEmpty()) dict->Set(name, proxies.ToValue()); } // Split the |uri_list| on commas and add each entry to |proxy_list| in turn. void AddProxyURIListToProxyList(std::string uri_list, ProxyList* proxy_list, ProxyServer::Scheme default_scheme) { base::StringTokenizer proxy_uri_list(uri_list, ","); while (proxy_uri_list.GetNext()) { proxy_list->AddProxyServer( ProxyServer::FromURI(proxy_uri_list.token(), default_scheme)); } } } // namespace ProxyConfig::ProxyRules::ProxyRules() : reverse_bypass(false), type(TYPE_NO_RULES) { } ProxyConfig::ProxyRules::ProxyRules(const ProxyRules& other) = default; ProxyConfig::ProxyRules::~ProxyRules() { } void ProxyConfig::ProxyRules::Apply(const GURL& url, ProxyInfo* result) const { if (empty()) { result->UseDirect(); return; } bool bypass_proxy = bypass_rules.Matches(url); if (reverse_bypass) bypass_proxy = !bypass_proxy; if (bypass_proxy) { result->UseDirectWithBypassedProxy(); return; } switch (type) { case ProxyRules::TYPE_SINGLE_PROXY: { result->UseProxyList(single_proxies); return; } case ProxyRules::TYPE_PROXY_PER_SCHEME: { const ProxyList* entry = MapUrlSchemeToProxyList(url.scheme()); if (entry) { result->UseProxyList(*entry); } else { // We failed to find a matching proxy server for the current URL // scheme. Default to direct. result->UseDirect(); } return; } default: { result->UseDirect(); NOTREACHED(); return; } } } void ProxyConfig::ProxyRules::ParseFromString(const std::string& proxy_rules) { // Reset. type = TYPE_NO_RULES; single_proxies = ProxyList(); proxies_for_http = ProxyList(); proxies_for_https = ProxyList(); proxies_for_ftp = ProxyList(); fallback_proxies = ProxyList(); base::StringTokenizer proxy_server_list(proxy_rules, ";"); while (proxy_server_list.GetNext()) { base::StringTokenizer proxy_server_for_scheme( proxy_server_list.token_begin(), proxy_server_list.token_end(), "="); while (proxy_server_for_scheme.GetNext()) { std::string url_scheme = proxy_server_for_scheme.token(); // If we fail to get the proxy server here, it means that // this is a regular proxy server configuration, i.e. proxies // are not configured per protocol. if (!proxy_server_for_scheme.GetNext()) { if (type == TYPE_PROXY_PER_SCHEME) continue; // Unexpected. AddProxyURIListToProxyList(url_scheme, &single_proxies, ProxyServer::SCHEME_HTTP); type = TYPE_SINGLE_PROXY; return; } // Trim whitespace off the url scheme. base::TrimWhitespaceASCII(url_scheme, base::TRIM_ALL, &url_scheme); // Add it to the per-scheme mappings (if supported scheme). type = TYPE_PROXY_PER_SCHEME; ProxyList* entry = MapUrlSchemeToProxyListNoFallback(url_scheme); ProxyServer::Scheme default_scheme = ProxyServer::SCHEME_HTTP; // socks=XXX is inconsistent with the other formats, since "socks" // is not a URL scheme. Rather this means "for everything else, send // it to the SOCKS proxy server XXX". if (url_scheme == "socks") { DCHECK(!entry); entry = &fallback_proxies; // Note that here 'socks' is understood to be SOCKS4, even though // 'socks' maps to SOCKS5 in ProxyServer::GetSchemeFromURIInternal. default_scheme = ProxyServer::SCHEME_SOCKS4; } if (entry) { AddProxyURIListToProxyList(proxy_server_for_scheme.token(), entry, default_scheme); } } } } const ProxyList* ProxyConfig::ProxyRules::MapUrlSchemeToProxyList( const std::string& url_scheme) const { const ProxyList* proxy_server_list = const_cast<ProxyRules*>(this)-> MapUrlSchemeToProxyListNoFallback(url_scheme); if (proxy_server_list && !proxy_server_list->IsEmpty()) return proxy_server_list; if (url_scheme == "ws" || url_scheme == "wss") return GetProxyListForWebSocketScheme(); if (!fallback_proxies.IsEmpty()) return &fallback_proxies; return NULL; // No mapping for this scheme. Use direct. } bool ProxyConfig::ProxyRules::Equals(const ProxyRules& other) const { return type == other.type && single_proxies.Equals(other.single_proxies) && proxies_for_http.Equals(other.proxies_for_http) && proxies_for_https.Equals(other.proxies_for_https) && proxies_for_ftp.Equals(other.proxies_for_ftp) && fallback_proxies.Equals(other.fallback_proxies) && bypass_rules.Equals(other.bypass_rules) && reverse_bypass == other.reverse_bypass; } ProxyList* ProxyConfig::ProxyRules::MapUrlSchemeToProxyListNoFallback( const std::string& scheme) { DCHECK_EQ(TYPE_PROXY_PER_SCHEME, type); if (scheme == "http") return &proxies_for_http; if (scheme == "https") return &proxies_for_https; if (scheme == "ftp") return &proxies_for_ftp; return NULL; // No mapping for this scheme. } const ProxyList* ProxyConfig::ProxyRules::GetProxyListForWebSocketScheme() const { if (!fallback_proxies.IsEmpty()) return &fallback_proxies; if (!proxies_for_https.IsEmpty()) return &proxies_for_https; if (!proxies_for_http.IsEmpty()) return &proxies_for_http; return NULL; } ProxyConfig::ProxyConfig() : auto_detect_(false), pac_mandatory_(false), source_(PROXY_CONFIG_SOURCE_UNKNOWN), id_(kInvalidConfigID) { } ProxyConfig::ProxyConfig(const ProxyConfig& config) = default; ProxyConfig::~ProxyConfig() { } ProxyConfig& ProxyConfig::operator=(const ProxyConfig& config) = default; bool ProxyConfig::Equals(const ProxyConfig& other) const { // The two configs can have different IDs and sources. We are just interested // in if they have the same settings. return auto_detect_ == other.auto_detect_ && pac_url_ == other.pac_url_ && pac_mandatory_ == other.pac_mandatory_ && proxy_rules_.Equals(other.proxy_rules()); } bool ProxyConfig::HasAutomaticSettings() const { return auto_detect_ || has_pac_url(); } void ProxyConfig::ClearAutomaticSettings() { auto_detect_ = false; pac_url_ = GURL(); } std::unique_ptr<base::DictionaryValue> ProxyConfig::ToValue() const { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); // Output the automatic settings. if (auto_detect_) dict->SetBoolean("auto_detect", auto_detect_); if (has_pac_url()) { dict->SetString("pac_url", pac_url_.possibly_invalid_spec()); if (pac_mandatory_) dict->SetBoolean("pac_mandatory", pac_mandatory_); } // Output the manual settings. if (proxy_rules_.type != ProxyRules::TYPE_NO_RULES) { switch (proxy_rules_.type) { case ProxyRules::TYPE_SINGLE_PROXY: AddProxyListToValue("single_proxy", proxy_rules_.single_proxies, dict.get()); break; case ProxyRules::TYPE_PROXY_PER_SCHEME: { std::unique_ptr<base::DictionaryValue> dict2( new base::DictionaryValue()); AddProxyListToValue("http", proxy_rules_.proxies_for_http, dict2.get()); AddProxyListToValue("https", proxy_rules_.proxies_for_https, dict2.get()); AddProxyListToValue("ftp", proxy_rules_.proxies_for_ftp, dict2.get()); AddProxyListToValue("fallback", proxy_rules_.fallback_proxies, dict2.get()); dict->Set("proxy_per_scheme", std::move(dict2)); break; } default: NOTREACHED(); } // Output the bypass rules. const ProxyBypassRules& bypass = proxy_rules_.bypass_rules; if (!bypass.rules().empty()) { if (proxy_rules_.reverse_bypass) dict->SetBoolean("reverse_bypass", true); auto list = std::make_unique<base::ListValue>(); for (ProxyBypassRules::RuleList::const_iterator it = bypass.rules().begin(); it != bypass.rules().end(); ++it) { list->AppendString((*it)->ToString()); } dict->Set("bypass_list", std::move(list)); } } // Output the source. dict->SetString("source", ProxyConfigSourceToString(source_)); return dict; } } // namespace net
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
31f23e1166d0dee42f32ad83d4107e2b362cdfca
260e5dec446d12a7dd3f32e331c1fde8157e5cea
/Indi/SDK/Indi_Food_Rizzo_KnockYouOutBar_functions.cpp
eb07ee8753f1aeb92b104eabcf410c76e6c342a4
[]
no_license
jfmherokiller/TheOuterWorldsSdkDump
6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0
18a8c6b1f5d87bb1ad4334be4a9f22c52897f640
refs/heads/main
2023-08-30T09:27:17.723265
2021-09-17T00:24:52
2021-09-17T00:24:52
407,437,218
0
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
// TheOuterWorlds SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "Indi_Food_Rizzo_KnockYouOutBar_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "peterpan0413@live.com" ]
peterpan0413@live.com
64a7d1305dacf856ca1d874e0c957779688299be
3b6ee14ff27aa37882cee98f16de21daf60f48aa
/DesignWorldApp/MainFrm.h
4f5390341dfeb93c67d1d165d18066d3208cf88f
[]
no_license
seenunit/DesignWorld
410aa01c274d9eac04b6ef52222d0273420f960b
40d311b2ddf4dcc5c555689b3b4bf4a0c97f2c39
refs/heads/client
2021-01-18T21:21:03.688005
2017-07-01T07:57:19
2017-07-01T07:57:19
34,983,157
3
1
null
2016-04-04T12:35:26
2015-05-03T11:09:04
C++
UTF-8
C++
false
false
1,537
h
// MainFrm.h : interface of the CMainFrame class // #pragma once #include "FileView.h" #include "ClassView.h" #include "OutputWnd.h" #include "PropertiesWnd.h" class CMainFrame : public CMDIFrameWndEx { DECLARE_DYNAMIC(CMainFrame) public: CMainFrame(); // Attributes public: // Operations public: // Overrides public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL LoadFrame(UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL); // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CMFCMenuBar m_wndMenuBar; CMFCToolBar m_wndToolBar; CMFCStatusBar m_wndStatusBar; CMFCToolBarImages m_UserImages; CFileView m_wndFileView; CClassView m_wndClassView; COutputWnd m_wndOutput; CPropertiesWnd m_wndProperties; CMFCToolBar m_ViewToolBar; // Generated message map functions protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnWindowManager(); afx_msg void OnViewCustomize(); afx_msg LRESULT OnToolbarCreateNew(WPARAM wp, LPARAM lp); afx_msg void OnApplicationLook(UINT id); afx_msg void OnUpdateApplicationLook(CCmdUI* pCmdUI); afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection); DECLARE_MESSAGE_MAP() BOOL CreateDockingWindows(); void SetDockingWindowIcons(BOOL bHiColorIcons); };
[ "seenunit@gmail.com" ]
seenunit@gmail.com
b11716018f39a8f16761d6e1785d3c6d73b11e40
b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1
/tensorflow/compiler/xla/service/hlo_instruction.cc
afe4680ed9ade4dcfb190ed3f05a41c0058992f2
[ "Apache-2.0" ]
permissive
uve/tensorflow
e48cb29f39ed24ee27e81afd1687960682e1fbef
e08079463bf43e5963acc41da1f57e95603f8080
refs/heads/master
2020-11-29T11:30:40.391232
2020-01-11T13:43:10
2020-01-11T13:43:10
230,088,347
0
0
Apache-2.0
2019-12-25T10:49:15
2019-12-25T10:49:14
null
UTF-8
C++
false
false
144,979
cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include <algorithm> #include <ostream> #include <set> #include <unordered_set> #include <utility> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/container/inlined_vector.h" #include "absl/memory/memory.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/types/span.h" #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/protobuf_util.h" #include "tensorflow/compiler/xla/service/dfs_hlo_visitor.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instructions.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_sharding_metadata.h" #include "tensorflow/compiler/xla/service/name_uniquer.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/platform/human_readable_json.h" #include "tensorflow/core/platform/logging.h" namespace xla { using absl::CEscape; using absl::StrAppend; using absl::StrCat; using absl::StrJoin; /* static */ StatusOr<std::unique_ptr<HloInstruction>> HloInstruction::CreateFromProto( const HloInstructionProto& proto, const absl::flat_hash_map<int64, HloInstruction*>& instruction_map, const absl::flat_hash_map<int64, HloComputation*>& computation_map) { TF_RET_CHECK(!proto.opcode().empty()); HloOpcode opcode; auto opcode_or = StringToHloOpcode(proto.opcode()); absl::optional<ComparisonDirection> comparison_direction; if (opcode_or.ok()) { opcode = opcode_or.ConsumeValueOrDie(); } else { // Unknown opcode. Try auto-upgrading deprecated "less-than", // "greater-than", etc opcodes, which are now rolled into the kCompare // opcode. if (proto.opcode() == "equal-to") { comparison_direction = ComparisonDirection::kEq; } else if (proto.opcode() == "not-equal-to") { comparison_direction = ComparisonDirection::kNe; } else if (proto.opcode() == "greater-than-or-equal-to") { comparison_direction = ComparisonDirection::kGe; } else if (proto.opcode() == "greater-than") { comparison_direction = ComparisonDirection::kGt; } else if (proto.opcode() == "less-than-or-equal-to") { comparison_direction = ComparisonDirection::kLe; } else if (proto.opcode() == "less-than") { comparison_direction = ComparisonDirection::kLt; } if (comparison_direction) { opcode = HloOpcode::kCompare; } else { return InvalidArgument("Unknown opcode: %s", proto.opcode()); } } TF_RET_CHECK(proto.has_shape()); std::unique_ptr<HloInstruction> instruction; const auto operands = [&instruction_map, &proto](int index) { return instruction_map.at(proto.operand_ids(index)); }; const auto all_operands = [&instruction_map, &proto]() { std::vector<HloInstruction*> result(proto.operand_ids_size()); std::transform(proto.operand_ids().begin(), proto.operand_ids().end(), result.begin(), [&instruction_map](int64 operand_id) { return instruction_map.at(operand_id); }); return result; }; const auto computations = [&computation_map, &proto](int index) { return computation_map.at(proto.called_computation_ids(index)); }; const auto all_computations = [&computation_map, &proto]() { std::vector<HloComputation*> result(proto.called_computation_ids_size()); std::transform(proto.called_computation_ids().begin(), proto.called_computation_ids().end(), result.begin(), [&computation_map](int64 computation_id) { return computation_map.at(computation_id); }); return result; }; TF_RET_CHECK( absl::c_all_of(proto.operand_ids(), [&](int64 id) { return instruction_map.contains(id); })) << proto.name() << " instruction contains invalid operand id(s)"; TF_RET_CHECK( absl::c_all_of(proto.called_computation_ids(), [&](int64 id) { return computation_map.contains(id); })) << proto.name() << " instruction references invalid computation id(s)"; Shape shape(proto.shape()); TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); absl::optional<int> arity = HloOpcodeArity(opcode); if (arity) { TF_RET_CHECK(proto.operand_ids_size() == *arity) << proto.opcode() << " instruction should have " << *arity << " operands but sees " << proto.operand_ids_size(); } switch (opcode) { // Ops migrated to subclasses. case HloOpcode::kBatchNormTraining: instruction = CreateBatchNormTraining(shape, operands(0), operands(1), operands(2), proto.epsilon(), proto.feature_index()); break; case HloOpcode::kBatchNormInference: instruction = CreateBatchNormInference( shape, operands(0), operands(1), operands(2), operands(3), operands(4), proto.epsilon(), proto.feature_index()); break; case HloOpcode::kBatchNormGrad: instruction = CreateBatchNormGrad(shape, operands(0), operands(1), operands(2), operands(3), operands(4), proto.epsilon(), proto.feature_index()); break; case HloOpcode::kFft: { std::vector<int64> fft_length(proto.fft_length().begin(), proto.fft_length().end()); instruction = CreateFft(shape, operands(0), proto.fft_type(), absl::Span<const int64>(fft_length)); break; } case HloOpcode::kCompare: { // Auto-upgraded from deprecated opcode skips the following. if (!comparison_direction) { TF_ASSIGN_OR_RETURN( comparison_direction, StringToComparisonDirection(proto.comparison_direction())); } instruction = CreateCompare(shape, operands(0), operands(1), *comparison_direction); break; } case HloOpcode::kTriangularSolve: { instruction = CreateTriangularSolve(shape, operands(0), operands(1), proto.triangular_solve_options()); break; } case HloOpcode::kCholesky: { instruction = CreateCholesky(shape, operands(0), proto.cholesky_options()); break; } case HloOpcode::kSend: instruction = CreateSend(operands(0), operands(1), proto.channel_id(), proto.is_host_transfer()); break; case HloOpcode::kSendDone: instruction = CreateSendDone(operands(0), proto.is_host_transfer()); break; case HloOpcode::kRecv: instruction = CreateRecv(shape.tuple_shapes(0), operands(0), proto.channel_id(), proto.is_host_transfer()); break; case HloOpcode::kRecvDone: instruction = CreateRecvDone(operands(0), proto.is_host_transfer()); break; case HloOpcode::kReverse: instruction = CreateReverse(shape, operands(0), std::vector<int64>(proto.dimensions().begin(), proto.dimensions().end())); break; case HloOpcode::kConcatenate: TF_RET_CHECK(proto.dimensions_size() == 1) << "Concatenate instruction should have 1 dimension but sees " << proto.dimensions_size(); instruction = CreateConcatenate(shape, all_operands(), proto.dimensions(0)); break; case HloOpcode::kConditional: { TF_RET_CHECK(proto.called_computation_ids_size() > 0) << "conditional should have at least 1 called computation"; if (operands(0)->shape().element_type() == PRED) { TF_RET_CHECK(proto.called_computation_ids_size() == 2) << "conditional should have exactly 2 called computations but got " << proto.called_computation_ids_size(); } TF_RET_CHECK(proto.operand_ids_size() == proto.called_computation_ids_size() + 1) << "conditional should have one branch_index operand plus one " "operand per called computation but got " << proto.operand_ids_size() << " operands for " << proto.called_computation_ids_size() << " branch computations"; auto cond_operands = all_operands(); instruction = CreateConditional(shape, cond_operands[0], all_computations(), absl::MakeSpan(cond_operands).subspan(1)); break; } case HloOpcode::kReduce: TF_RET_CHECK(proto.operand_ids_size() % 2 == 0) << "Reduce instruction should have an even number of operands but " "sees " << proto.operand_ids_size(); TF_RET_CHECK(proto.called_computation_ids_size() == 1) << "Reduce instruction should have 1 called computation but sees " << proto.called_computation_ids_size(); { const auto reduce_operands = all_operands(); auto inputs = absl::MakeSpan(reduce_operands) .subspan(0, reduce_operands.size() / 2); auto init_values = absl::MakeSpan(reduce_operands) .subspan(reduce_operands.size() / 2, reduce_operands.size()); instruction = CreateReduce(shape, inputs, init_values, std::vector<int64>(proto.dimensions().begin(), proto.dimensions().end()), computations(0)); } break; case HloOpcode::kSort: { TF_RET_CHECK(proto.operand_ids_size() >= 1) << "Sort instruction should have at least 1 operand but has " << proto.operand_ids_size(); TF_RET_CHECK(proto.dimensions().size() == 1) << "Sort instruction should have 1 dimension"; TF_RET_CHECK(proto.called_computation_ids_size() == 1) << "Sort instruction should one called computation but sees " << proto.called_computation_ids_size(); auto sort_operands = all_operands(); instruction = CreateSort(shape, proto.dimensions(0), all_operands(), computations(0), proto.is_stable()); break; } case HloOpcode::kTranspose: instruction = CreateTranspose(shape, operands(0), std::vector<int64>(proto.dimensions().begin(), proto.dimensions().end())); break; case HloOpcode::kBroadcast: instruction = CreateBroadcast(shape, operands(0), std::vector<int64>(proto.dimensions().begin(), proto.dimensions().end())); break; case HloOpcode::kMap: TF_RET_CHECK(proto.called_computation_ids_size() == 1) << "Map instruction should have 1 called computation but sees " << proto.called_computation_ids_size(); instruction = CreateMap(shape, all_operands(), computations(0)); break; case HloOpcode::kSlice: { std::vector<int64> slice_starts, slice_limits, slice_strides; for (const HloInstructionProto::SliceDimensions& slice_dimensions : proto.slice_dimensions()) { slice_starts.push_back(slice_dimensions.start()); slice_limits.push_back(slice_dimensions.limit()); slice_strides.push_back(slice_dimensions.stride()); } instruction = CreateSlice(shape, operands(0), slice_starts, slice_limits, slice_strides); break; } case HloOpcode::kConstant: { // TODO(b/110214922): Revert this to CHECK(proto.has_literal()). if (proto.has_literal()) { TF_ASSIGN_OR_RETURN(auto literal, Literal::CreateFromProto(proto.literal())); instruction = CreateConstant(std::move(literal)); // Literal's shape may have no/different tiling info. TF_RET_CHECK(Shape::Equal().MinorToMajorOnlyInLayout()( instruction->shape(), shape)); *instruction->mutable_shape() = shape; } else { instruction = absl::make_unique<HloConstantInstruction>(shape); } break; } case HloOpcode::kTrace: { TF_RET_CHECK(proto.has_literal()); TF_ASSIGN_OR_RETURN(auto literal, Literal::CreateFromProto(proto.literal())); instruction = CreateTrace(literal.GetR1U8AsString(), operands(0)); break; } case HloOpcode::kFusion: { // In the proto, fused computations are held exclusively within the // HloInstructionProto and do not appear as an HloComputationProto within // the HloModuleProto. TF_RET_CHECK(!proto.fusion_kind().empty()); TF_ASSIGN_OR_RETURN(FusionKind fusion_kind, StringToFusionKind(proto.fusion_kind())); // Find the fused computation and set its fusion instruction. TF_RET_CHECK(proto.called_computation_ids_size() == 1) << "Expect 1 called computation for fusion instruction but sees " << proto.called_computation_ids_size(); const int64 fusion_id = proto.called_computation_ids(0); auto* fused_computation = tensorflow::gtl::FindPtrOrNull(computation_map, fusion_id); TF_RET_CHECK(fused_computation != nullptr) << "No fusion computation with id " << fusion_id; instruction = CreateFusion(shape, fusion_kind, all_operands(), fused_computation); break; } case HloOpcode::kRng: instruction = CreateRng(shape, proto.distribution(), all_operands()); break; case HloOpcode::kRngGetAndUpdateState: instruction = CreateRngGetAndUpdateState(shape, proto.delta()); break; case HloOpcode::kParameter: instruction = CreateParameter(proto.parameter_number(), shape, proto.name()); if (!proto.parameter_replication().replicated_at_leaf_buffers().empty()) { instruction->set_parameter_replicated_at_leaf_buffers( proto.parameter_replication().replicated_at_leaf_buffers()); } break; case HloOpcode::kGetTupleElement: instruction = CreateGetTupleElement(shape, operands(0), proto.tuple_index()); break; case HloOpcode::kReducePrecision: instruction = CreateReducePrecision( shape, operands(0), proto.exponent_bits(), proto.mantissa_bits()); break; case HloOpcode::kInfeed: { TF_RET_CHECK(shape.IsTuple() && (ShapeUtil::TupleElementCount(shape) == 2)) << "Infeed should have a tuple shape with 2 operands, but has: " << shape; const Shape& data_shape = ShapeUtil::GetTupleElementShape(shape, 0); instruction = CreateInfeed(data_shape, operands(0), proto.infeed_config()); } break; case HloOpcode::kOutfeed: { Shape outfeed_shape(proto.outfeed_shape()); TF_RETURN_IF_ERROR( ShapeUtil::ValidateShapeWithOptionalLayout(outfeed_shape)); instruction = CreateOutfeed(outfeed_shape, operands(0), operands(1), proto.outfeed_config()); break; } case HloOpcode::kAllReduce: { TF_RET_CHECK(proto.called_computation_ids_size() == 1) << "AllReduce should have 1 called computation but sees " << proto.called_computation_ids_size(); TF_RET_CHECK(proto.channel_id() <= 0 || proto.all_reduce_id() <= 0) << "AllReduce cannot have both channel_id() and all_reduce_id()"; absl::optional<int64> channel_id; if (proto.channel_id() > 0) { channel_id = proto.channel_id(); } if (proto.all_reduce_id() > 0) { channel_id = proto.all_reduce_id(); } instruction = CreateAllReduce( shape, all_operands(), computations(0), /*replica_groups=*/ std::vector<ReplicaGroup>(proto.replica_groups().begin(), proto.replica_groups().end()), /*channel_id=*/channel_id); break; } case HloOpcode::kAllToAll: { instruction = CreateAllToAll( shape, all_operands(), /*replica_groups=*/ std::vector<ReplicaGroup>(proto.replica_groups().begin(), proto.replica_groups().end())); break; } case HloOpcode::kCollectivePermute: { std::vector<std::pair<int64, int64>> source_target_pairs( proto.source_target_pairs_size()); absl::optional<int64> channel_id; if (proto.channel_id() > 0) { channel_id = proto.channel_id(); } for (int i = 0; i < source_target_pairs.size(); i++) { source_target_pairs[i].first = proto.source_target_pairs(i).source(); source_target_pairs[i].second = proto.source_target_pairs(i).target(); } instruction = CreateCollectivePermute(shape, operands(0), source_target_pairs, channel_id); break; } case HloOpcode::kReplicaId: { instruction = CreateReplicaId(); break; } case HloOpcode::kPartitionId: { instruction = CreatePartitionId(); break; } case HloOpcode::kConvolution: { TF_RET_CHECK(proto.has_window()); TF_RET_CHECK(proto.has_convolution_dimension_numbers()); PrecisionConfig precision_config = proto.precision_config(); precision_config.mutable_operand_precision()->Resize( proto.operand_ids_size(), PrecisionConfig::DEFAULT); instruction = CreateConvolve( shape, operands(0), operands(1), std::max<int64>(proto.feature_group_count(), 1), std::max<int64>(proto.batch_group_count(), 1), proto.window(), proto.convolution_dimension_numbers(), precision_config); break; } case HloOpcode::kReduceWindow: TF_RET_CHECK(proto.called_computation_ids_size() == 1) << "ReduceWindow should have 1 called computation but sees " << proto.called_computation_ids_size(); instruction = CreateReduceWindow(shape, operands(0), operands(1), proto.window(), computations(0)); break; case HloOpcode::kSelectAndScatter: TF_RET_CHECK(proto.called_computation_ids_size() == 2) << "SelectAndScatter should have 2 called computations but sees " << proto.called_computation_ids_size(); instruction = CreateSelectAndScatter(shape, operands(0), computations(0), proto.window(), operands(1), operands(2), computations(1)); break; case HloOpcode::kCustomCall: { if (proto.constrain_layout()) { // A proto RepeatedPtrField cannot be converted to a Span (it is a // vector of pointers essentially) so create a vector of shapes to pass // in. std::vector<Shape> operand_shapes; for (const ShapeProto& shape_proto : proto.operand_shapes_with_layout()) { operand_shapes.emplace_back(shape_proto); } instruction = CreateCustomCall(shape, all_operands(), proto.custom_call_target(), operand_shapes, proto.backend_config()); } else { instruction = CreateCustomCall(shape, all_operands(), proto.custom_call_target(), proto.backend_config()); } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction.get()); if (proto.has_window()) { custom_call_instr->set_window(proto.window()); } if (proto.has_convolution_dimension_numbers()) { custom_call_instr->set_convolution_dimension_numbers( proto.convolution_dimension_numbers()); } custom_call_instr->set_feature_group_count( std::max(static_cast<int64>(proto.feature_group_count()), 1LL)); custom_call_instr->set_batch_group_count( std::max(static_cast<int64>(proto.batch_group_count()), 1LL)); custom_call_instr->set_custom_call_has_side_effect( proto.custom_call_has_side_effect()); break; } case HloOpcode::kPad: TF_RET_CHECK(proto.has_padding_config()); instruction = CreatePad(shape, operands(0), operands(1), proto.padding_config()); break; case HloOpcode::kDynamicSlice: { std::vector<int64> slice_sizes(proto.dynamic_slice_sizes_size()); absl::c_copy(proto.dynamic_slice_sizes(), slice_sizes.begin()); TF_RET_CHECK(proto.operand_ids_size() >= 1) << "DynamicSlice instruction should have at least 1 operands but " "sees " << proto.operand_ids_size(); // TODO(b/118437727): Old form, make the check unconditional. if (proto.operand_ids_size() != 2 || operands(1)->shape().rank() != 1) { auto expected_operands = 1 + operands(0)->shape().rank(); TF_RET_CHECK(proto.operand_ids_size() == expected_operands) << "DynamicSlice instruction should have " << expected_operands << " operands, but has " << proto.operand_ids_size(); } const auto& operand_vector = all_operands(); instruction = CreateDynamicSlice( shape, operands(0), absl::MakeSpan(operand_vector).subspan(1), slice_sizes); break; } case HloOpcode::kDynamicUpdateSlice: { TF_RET_CHECK(proto.operand_ids_size() >= 2) << "DynamicUpdateSlice instruction should have at least 2 operands " "but sees " << proto.operand_ids_size(); // TODO(b/118437727): Old form, make the check unconditional. if (proto.operand_ids_size() != 3 || operands(2)->shape().rank() != 1) { auto expected_operands = 2 + operands(0)->shape().rank(); TF_RET_CHECK(proto.operand_ids_size() == expected_operands) << "DynamicUpdateSlice instruction should have " << expected_operands << " operands, but has " << proto.operand_ids_size(); } const auto& operand_vector = all_operands(); instruction = CreateDynamicUpdateSlice(shape, operands(0), operands(1), absl::MakeSpan(operand_vector).subspan(2)); break; } case HloOpcode::kGather: { TF_RET_CHECK(proto.has_gather_dimension_numbers()) << "Gather instruction should have GatherDimensionNumbers set."; std::unique_ptr<GatherDimensionNumbers> gather_dimension_numbers = absl::make_unique<GatherDimensionNumbers>( proto.gather_dimension_numbers()); std::vector<int64> gather_slice_sizes; for (int64 bound : proto.gather_slice_sizes()) { gather_slice_sizes.push_back(bound); } instruction = CreateGather(shape, operands(0), operands(1), *gather_dimension_numbers, gather_slice_sizes); break; } case HloOpcode::kScatter: { TF_RET_CHECK(proto.has_scatter_dimension_numbers()) << "Scatter instruction should have ScatterDimensionNumbers set."; TF_RET_CHECK(proto.called_computation_ids_size() == 1) << "Scatter instruction should have 1 called computation but sees " << proto.called_computation_ids_size(); auto scatter_dimension_numbers = absl::make_unique<ScatterDimensionNumbers>( proto.scatter_dimension_numbers()); instruction = CreateScatter(shape, operands(0), operands(1), operands(2), computations(0), *scatter_dimension_numbers); break; } case HloOpcode::kIota: TF_RET_CHECK(proto.dimensions_size() == 1) << "Iota instruction should have 1 dimension but sees " << proto.dimensions_size(); instruction = CreateIota(shape, proto.dimensions(0)); break; case HloOpcode::kDot: { TF_RET_CHECK(proto.has_dot_dimension_numbers()) << "Dot instruction should have dot_dimension_numbers."; PrecisionConfig precision_config = proto.precision_config(); precision_config.mutable_operand_precision()->Resize( proto.operand_ids_size(), PrecisionConfig::DEFAULT); instruction = absl::make_unique<HloDotInstruction>( shape, operands(0), operands(1), proto.dot_dimension_numbers(), precision_config); break; } case HloOpcode::kDomain: { std::shared_ptr<const HloSharding> entry_hlo_sharding; std::shared_ptr<const HloSharding> exit_hlo_sharding; if (proto.has_domain_entry_sharding()) { TF_ASSIGN_OR_RETURN( HloSharding sharding, HloSharding::FromProto(proto.domain_entry_sharding())); entry_hlo_sharding = std::make_shared<const HloSharding>(sharding); } if (proto.has_domain_exit_sharding()) { TF_ASSIGN_OR_RETURN( HloSharding sharding, HloSharding::FromProto(proto.domain_exit_sharding())); exit_hlo_sharding = std::make_shared<const HloSharding>(sharding); } instruction = absl::make_unique<HloDomainInstruction>( shape, operands(0), absl::make_unique<ShardingMetadata>(entry_hlo_sharding), absl::make_unique<ShardingMetadata>(exit_hlo_sharding)); break; } case HloOpcode::kGetDimensionSize: TF_RET_CHECK(proto.dimensions_size() == 1); instruction = CreateGetDimensionSize(shape, operands(0), proto.dimensions(0)); break; case HloOpcode::kReshape: { int64 inferred_dimension = -1; if (!proto.dimensions().empty()) { inferred_dimension = proto.dimensions()[0]; } TF_RET_CHECK(shape.IsArray() && operands(0)->shape().IsArray() && ShapeUtil::ElementsIn(shape) == ShapeUtil::ElementsIn(operands(0)->shape())) << "shape: " << ShapeUtil::HumanString(shape) << " operand: " << ShapeUtil::HumanString(operands(0)->shape()); instruction = CreateReshape(shape, operands(0), inferred_dimension); break; } default: { instruction = absl::WrapUnique(new HloInstruction(opcode, shape)); for (const int64 operand_id : proto.operand_ids()) { instruction->AppendOperand(instruction_map.at(operand_id)); } if (instruction->opcode() != HloOpcode::kFusion) { if (instruction->opcode() == HloOpcode::kCall) { TF_RET_CHECK(proto.called_computation_ids_size() == 1) << "Call should have 1 called computation but has " << proto.called_computation_ids_size(); } for (const int64 computation_id : proto.called_computation_ids()) { instruction->called_computations_.push_back( computation_map.at(computation_id)); } } TF_RET_CHECK(!proto.has_precision_config()) << instruction->opcode() << proto.DebugString(); TF_RET_CHECK(!proto.has_dot_dimension_numbers()) << instruction->opcode(); break; } } for (const int64 predecessor_id : proto.control_predecessor_ids()) { TF_RET_CHECK(ContainsKey(instruction_map, predecessor_id)) << "No instruction with id " << predecessor_id; TF_RETURN_IF_ERROR(instruction_map.at(predecessor_id) ->AddControlDependencyTo(instruction.get())); } TF_RET_CHECK(!proto.name().empty()); instruction->SetAndSanitizeName(proto.name()); instruction->metadata_ = proto.metadata(); instruction->backend_config_ = proto.backend_config(); instruction->outer_dimension_partitions_.assign( proto.outer_dimension_partitions().begin(), proto.outer_dimension_partitions().end()); TF_RET_CHECK(proto.id() >= 0) << "Instruction with negative id: " << proto.id(); TF_RET_CHECK(proto.id() <= INT_MAX) << "Instruction with id > INT_MAX: " << proto.id(); instruction->unique_id_ = proto.id(); if (proto.has_sharding()) { TF_ASSIGN_OR_RETURN(const auto& sharding, HloSharding::FromProto(proto.sharding())); instruction->set_sharding(sharding); } return std::move(instruction); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateParameter( int64 parameter_number, const Shape& shape, const string& name) { return absl::make_unique<HloParameterInstruction>(parameter_number, shape, name); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTrace( const string& tag, HloInstruction* operand) { return absl::make_unique<HloTraceInstruction>(tag, operand); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConstant( Literal literal) { return absl::make_unique<HloConstantInstruction>(std::move(literal)); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateIota( const Shape& shape, int64 iota_dimension) { return absl::make_unique<HloIotaInstruction>(shape, iota_dimension); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateGetTupleElement(const Shape& shape, HloInstruction* operand, int64 index) { return absl::make_unique<HloGetTupleElementInstruction>(shape, operand, index); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRng( const Shape& shape, RandomDistribution distribution, absl::Span<HloInstruction* const> parameters) { return absl::make_unique<HloRngInstruction>(shape, distribution, parameters); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRngGetAndUpdateState(const Shape& shape, int64 delta) { return absl::make_unique<HloRngGetAndUpdateStateInstruction>(shape, delta); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateNary( const Shape& shape, HloOpcode opcode, absl::Span<HloInstruction* const> operands) { if (opcode == HloOpcode::kCopy) { // It is impossible to copy an opaque shape, we don't know how big it is. CHECK(!shape.IsOpaque()); } auto instruction = absl::WrapUnique(new HloInstruction(opcode, shape)); for (auto operand : operands) { instruction->AppendOperand(operand); } return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateUnary( const Shape& shape, HloOpcode opcode, HloInstruction* operand) { // Only certain opcodes are supported with CreateUnary: opcodes of unary // instructions with no auxiliary fields. switch (opcode) { case HloOpcode::kAbs: case HloOpcode::kRoundNearestAfz: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kCopy: case HloOpcode::kCopyStart: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kClz: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kTanh: break; default: LOG(FATAL) << "Invalid unary instruction opcode " << HloOpcodeString(opcode); } return CreateNary(shape, opcode, {operand}); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBinary( const Shape& shape, HloOpcode opcode, HloInstruction* lhs, HloInstruction* rhs) { // Only certain opcodes are supported with CreateBinary: opcodes of binary // instructions with no auxiliary fields. switch (opcode) { case HloOpcode::kAdd: case HloOpcode::kAtan2: case HloOpcode::kDivide: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kSubtract: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: break; default: LOG(FATAL) << "Invalid binary instruction opcode " << HloOpcodeString(opcode); } return CreateNary(shape, opcode, {lhs, rhs}); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTernary( const Shape& shape, HloOpcode opcode, HloInstruction* lhs, HloInstruction* rhs, HloInstruction* ehs) { // Only certain opcodes are supported with CreateTernary: opcodes of ternary // instructions with no auxiliary fields. switch (opcode) { case HloOpcode::kClamp: case HloOpcode::kSelect: case HloOpcode::kTupleSelect: break; default: LOG(FATAL) << "Invalid ternary instruction opcode " << HloOpcodeString(opcode); } return CreateNary(shape, opcode, {lhs, rhs, ehs}); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateVariadic( const Shape& shape, HloOpcode opcode, absl::Span<HloInstruction* const> operands) { CHECK_EQ(HloOpcode::kTuple, opcode); return CreateNary(shape, opcode, operands); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateMap( const Shape& shape, absl::Span<HloInstruction* const> operands, HloComputation* map_computation) { return absl::make_unique<HloMapInstruction>(shape, operands, map_computation); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConvolve( const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, int64 feature_group_count, int64 batch_group_count, const Window& window, const ConvolutionDimensionNumbers& dimension_numbers, const PrecisionConfig& precision_config) { return absl::make_unique<HloConvolutionInstruction>( shape, lhs, rhs, feature_group_count, batch_group_count, window, dimension_numbers, precision_config); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFft( const Shape& shape, HloInstruction* operand, FftType fft_type, absl::Span<const int64> fft_length) { return absl::make_unique<HloFftInstruction>(shape, operand, fft_type, fft_length); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCompare( const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, ComparisonDirection direction) { return absl::make_unique<HloCompareInstruction>(shape, lhs, rhs, direction); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTriangularSolve(const Shape& shape, HloInstruction* a, HloInstruction* b, const TriangularSolveOptions& options) { return absl::make_unique<HloTriangularSolveInstruction>(shape, a, b, options); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCholesky( const Shape& shape, HloInstruction* a, const CholeskyOptions& options) { return absl::make_unique<HloCholeskyInstruction>(shape, a, options); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDot( const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, const DotDimensionNumbers& dimension_numbers, const PrecisionConfig& precision_config) { return absl::make_unique<HloDotInstruction>( shape, lhs, rhs, dimension_numbers, precision_config); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReducePrecision(const Shape& shape, HloInstruction* operand, const int exponent_bits, const int mantissa_bits) { return absl::make_unique<HloReducePrecisionInstruction>( shape, operand, exponent_bits, mantissa_bits); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateAllReduce( const Shape& shape, absl::Span<HloInstruction* const> operands, HloComputation* reduce_computation, const std::vector<ReplicaGroup>& replica_groups, const absl::optional<int64>& channel_id) { return absl::make_unique<HloAllReduceInstruction>( shape, operands, reduce_computation, replica_groups, channel_id); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateAllToAll( const Shape& shape, absl::Span<HloInstruction* const> operands, const std::vector<ReplicaGroup>& replica_groups) { return absl::make_unique<HloAllToAllInstruction>(shape, operands, replica_groups); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCollectivePermute( const Shape& shape, HloInstruction* operand, const std::vector<std::pair<int64, int64>>& source_target_pairs, const absl::optional<int64>& channel_id) { return absl::make_unique<HloCollectivePermuteInstruction>( shape, operand, source_target_pairs, channel_id); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReplicaId() { return absl::WrapUnique( new HloInstruction(HloOpcode::kReplicaId, ShapeUtil::MakeShape(U32, {}))); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreatePartitionId() { return absl::WrapUnique(new HloInstruction(HloOpcode::kPartitionId, ShapeUtil::MakeShape(U32, {}))); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateInfeed( const Shape& infeed_shape, HloInstruction* token_operand, const string& config) { return absl::make_unique<HloInfeedInstruction>(infeed_shape, token_operand, config); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateOutfeed( const Shape& outfeed_shape, HloInstruction* operand, HloInstruction* token_operand, absl::string_view outfeed_config) { return absl::make_unique<HloOutfeedInstruction>( outfeed_shape, operand, token_operand, outfeed_config); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSend( HloInstruction* operand, HloInstruction* token, int64 channel_id, bool is_host_transfer) { return absl::make_unique<HloSendInstruction>(operand, token, channel_id, is_host_transfer); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSendDone( HloInstruction* operand, bool is_host_transfer) { auto send_operand = DynCast<HloSendInstruction>(operand); CHECK(send_operand != nullptr) << "SendDone must take the context operand from Send"; return absl::make_unique<HloSendDoneInstruction>(send_operand, is_host_transfer); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRecv( const Shape& shape, HloInstruction* token, int64 channel_id, bool is_host_transfer) { return absl::make_unique<HloRecvInstruction>(shape, token, channel_id, is_host_transfer); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRecvDone( HloInstruction* operand, bool is_host_transfer) { auto recv_operand = DynCast<HloRecvInstruction>(operand); CHECK(recv_operand != nullptr) << "RecvDone must take the context operand from Recv"; return absl::make_unique<HloRecvDoneInstruction>(recv_operand, is_host_transfer); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReverse( const Shape& shape, HloInstruction* operand, absl::Span<const int64> dimensions) { return absl::make_unique<HloReverseInstruction>(shape, operand, dimensions); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateAfterAll( absl::Span<HloInstruction* const> operands) { CHECK(!operands.empty()); auto instruction = absl::WrapUnique( new HloInstruction(HloOpcode::kAfterAll, ShapeUtil::MakeTokenShape())); for (auto operand : operands) { instruction->AppendOperand(operand); } return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateToken() { return absl::WrapUnique( new HloInstruction(HloOpcode::kAfterAll, ShapeUtil::MakeTokenShape())); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateAddDependency(HloInstruction* data_operand, HloInstruction* token_operand) { auto instruction = absl::WrapUnique( new HloInstruction(HloOpcode::kAddDependency, data_operand->shape())); instruction->AppendOperand(data_operand); instruction->AppendOperand(token_operand); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateWhile( const Shape& shape, HloComputation* condition, HloComputation* body, HloInstruction* init) { auto instruction = absl::WrapUnique(new HloInstruction(HloOpcode::kWhile, shape)); instruction->AppendOperand(init); // Body comes before condition computation in the vector. instruction->called_computations_.push_back(body); instruction->called_computations_.push_back(condition); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConditional( const Shape& shape, HloInstruction* pred, HloInstruction* true_computation_arg, HloComputation* true_computation, HloInstruction* false_computation_arg, HloComputation* false_computation) { auto instruction = absl::WrapUnique(new HloInstruction(HloOpcode::kConditional, shape)); instruction->AppendOperand(pred); instruction->AppendOperand(true_computation_arg); instruction->AppendOperand(false_computation_arg); // In called_computations_, the index of true_computation must be 0 and that // of false computation must be 1, as defined by kTrueComputationIndex and // kFalseComputationIndex. instruction->called_computations_.push_back(true_computation); instruction->called_computations_.push_back(false_computation); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConditional( const Shape& shape, HloInstruction* branch_index, absl::Span<HloComputation* const> branch_computations, absl::Span<HloInstruction* const> branch_computation_args) { auto instruction = absl::WrapUnique(new HloInstruction(HloOpcode::kConditional, shape)); instruction->AppendOperand(branch_index); CHECK_EQ(branch_computations.size(), branch_computation_args.size()); for (int i = 0; i < branch_computations.size(); ++i) { instruction->called_computations_.push_back(branch_computations[i]); instruction->AppendOperand(branch_computation_args[i]); } return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSlice( const Shape& shape, HloInstruction* operand, absl::Span<const int64> start_indices, absl::Span<const int64> limit_indices, absl::Span<const int64> strides) { return absl::make_unique<HloSliceInstruction>(shape, operand, start_indices, limit_indices, strides); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDynamicSlice( const Shape& shape, HloInstruction* operand, absl::Span<HloInstruction* const> start_indices, absl::Span<const int64> slice_sizes) { return absl::make_unique<HloDynamicSliceInstruction>( shape, operand, start_indices, slice_sizes); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDynamicUpdateSlice( const Shape& shape, HloInstruction* operand, HloInstruction* update, absl::Span<HloInstruction* const> start_indices) { return absl::make_unique<HloDynamicUpdateSliceInstruction>( shape, operand, update, start_indices); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConcatenate( const Shape& shape, absl::Span<HloInstruction* const> operands, int64 dimension) { return absl::make_unique<HloConcatenateInstruction>(shape, operands, dimension); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConvert( const Shape& shape, HloInstruction* operand) { auto instruction = absl::WrapUnique(new HloInstruction(HloOpcode::kConvert, shape)); instruction->AppendOperand(operand); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBitcastConvert(const Shape& shape, HloInstruction* operand) { auto instruction = absl::WrapUnique(new HloInstruction(HloOpcode::kBitcastConvert, shape)); instruction->AppendOperand(operand); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBitcast( const Shape& shape, HloInstruction* operand) { auto instruction = absl::WrapUnique(new HloInstruction(HloOpcode::kBitcast, shape)); instruction->AppendOperand(operand); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReduce( const Shape& shape, HloInstruction* operand, HloInstruction* init_value, absl::Span<const int64> dimensions_to_reduce, HloComputation* reduce_computation) { auto instruction = absl::WrapUnique(new HloReduceInstruction( shape, {operand, init_value}, dimensions_to_reduce, reduce_computation)); return std::move(instruction); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReduce( const Shape& shape, absl::Span<HloInstruction* const> operands, absl::Span<HloInstruction* const> init_values, absl::Span<const int64> dimensions_to_reduce, HloComputation* reduce_computation) { std::vector<HloInstruction*> all_args; all_args.reserve(operands.size() * 2); all_args.insert(all_args.end(), operands.begin(), operands.end()); all_args.insert(all_args.end(), init_values.begin(), init_values.end()); return absl::make_unique<HloReduceInstruction>( shape, all_args, dimensions_to_reduce, reduce_computation); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReduceWindow( const Shape& shape, HloInstruction* operand, HloInstruction* init_value, const Window& window, HloComputation* reduce_computation) { return absl::make_unique<HloReduceWindowInstruction>( shape, operand, init_value, window, reduce_computation); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBatchNormTraining(const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* offset, float epsilon, int64 feature_index) { return absl::make_unique<HloBatchNormTrainingInstruction>( shape, operand, scale, offset, epsilon, feature_index); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBatchNormInference( const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* offset, HloInstruction* mean, HloInstruction* variance, float epsilon, int64 feature_index) { return absl::make_unique<HloBatchNormInferenceInstruction>( shape, operand, scale, offset, mean, variance, epsilon, feature_index); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBatchNormGrad(const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* mean, HloInstruction* variance, HloInstruction* grad_output, float epsilon, int64 feature_index) { return absl::make_unique<HloBatchNormGradInstruction>( shape, operand, scale, mean, variance, grad_output, epsilon, feature_index); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSelectAndScatter( const Shape& shape, HloInstruction* operand, HloComputation* select, const Window& window, HloInstruction* source, HloInstruction* init_value, HloComputation* scatter) { return absl::make_unique<HloSelectAndScatterInstruction>( shape, operand, select, window, source, init_value, scatter); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBroadcast( const Shape& shape, HloInstruction* operand, absl::Span<const int64> broadcast_dimensions) { return absl::make_unique<HloBroadcastInstruction>(shape, operand, broadcast_dimensions); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateGetDimensionSize(const Shape& shape, HloInstruction* operand, int64 dimension) { return absl::make_unique<HloGetDimensionSizeInstruction>(shape, operand, dimension); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBroadcastSequence( const Shape& output_shape, HloInstruction* operand, const std::function<HloInstruction*(std::unique_ptr<HloInstruction>)>& adder) { CHECK(ShapeUtil::IsScalar(operand->shape()) || operand->shape().rank() == output_shape.rank()); Shape broadcast_shape = ShapeUtil::ChangeElementType( output_shape, operand->shape().element_type()); // Do explicit broadcast for scalar. if (ShapeUtil::IsScalar(operand->shape())) { auto broadcast = HloInstruction::CreateBroadcast(broadcast_shape, operand, {}); broadcast->set_metadata(operand->metadata()); if (operand->has_sharding()) { broadcast->set_sharding(operand->sharding()); } return broadcast; } // Do explicit broadcast for degenerate broadcast. std::vector<int64> broadcast_dimensions; std::vector<int64> reshaped_dimensions; for (int i = 0; i < operand->shape().rank(); i++) { if (operand->shape().dimensions(i) == output_shape.dimensions(i)) { broadcast_dimensions.push_back(i); reshaped_dimensions.push_back(operand->shape().dimensions(i)); } else { CHECK_EQ(operand->shape().dimensions(i), 1) << "An explicit broadcast sequence requires the broadcasted " "dimensions to be trivial; operand: " << operand->ToString() << "; output_shape: " << output_shape; } } // Eliminate the size one dimensions. HloInstruction* reshaped_operand = adder(HloInstruction::CreateReshape( ShapeUtil::MakeShape(operand->shape().element_type(), reshaped_dimensions), operand)); reshaped_operand->set_metadata(operand->metadata()); if (operand->has_sharding()) { reshaped_operand->set_sharding(operand->sharding()); } // Broadcast 'reshape' up to the larger size. auto broadcast = HloInstruction::CreateBroadcast( broadcast_shape, reshaped_operand, broadcast_dimensions); broadcast->set_metadata(operand->metadata()); if (operand->has_sharding()) { broadcast->set_sharding(operand->sharding()); } return broadcast; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreatePad( const Shape& shape, HloInstruction* operand, HloInstruction* padding_value, const PaddingConfig& padding_config) { return absl::make_unique<HloPadInstruction>(shape, operand, padding_value, padding_config); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReshape( const Shape& shape, HloInstruction* operand, int64 inferred_dimension) { CHECK_EQ(ShapeUtil::ElementsIn(shape), ShapeUtil::ElementsIn(operand->shape())) << "shape: " << ShapeUtil::HumanString(shape) << " operand: " << ShapeUtil::HumanString(operand->shape()); return absl::make_unique<HloReshapeInstruction>(shape, operand, inferred_dimension); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTranspose( const Shape& shape, HloInstruction* operand, absl::Span<const int64> dimensions) { return absl::make_unique<HloTransposeInstruction>(shape, operand, dimensions); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSort( const Shape& shape, int64 dimension, absl::Span<HloInstruction* const> operands, HloComputation* compare, bool is_stable) { return absl::make_unique<HloSortInstruction>(shape, dimension, operands, compare, is_stable); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFusion( const Shape& shape, FusionKind fusion_kind, HloInstruction* fused_root) { return absl::make_unique<HloFusionInstruction>(shape, fusion_kind, fused_root); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFusion( const Shape& shape, FusionKind fusion_kind, absl::Span<HloInstruction* const> operands, HloComputation* fusion_computation) { return absl::make_unique<HloFusionInstruction>(shape, fusion_kind, operands, fusion_computation); } void HloInstruction::set_single_sharding(const HloSharding& sharding) { CHECK(!sharding.IsTuple()) << sharding; if (shape().IsTuple()) { set_sharding(HloSharding::Tuple(sharding.GetAsShapeTree(shape()))); } else { set_sharding(sharding); } } void HloInstruction::SetupDerivedInstruction( HloInstruction* derived_instruction) const { if (sharding_ != nullptr && ShapeUtil::CompatibleIgnoringElementType( shape_, derived_instruction->shape())) { // Only copy sharding if the shape of the two instruction is compatible // because copying it between differently shaped instructions can produce // invalid shardings. derived_instruction->set_sharding(*sharding_); } else { derived_instruction->clear_sharding(); } derived_instruction->set_metadata(metadata_); } bool HloInstruction::HasSideEffectNoRecurse() const { switch (opcode_) { case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kInfeed: case HloOpcode::kOutfeed: case HloOpcode::kTrace: return true; case HloOpcode::kAllReduce: return channel_id().has_value(); case HloOpcode::kCustomCall: return Cast<HloCustomCallInstruction>(this) ->custom_call_has_side_effect(); default: return false; } } bool HloInstruction::HasSideEffect() const { if (HasSideEffectNoRecurse()) { return true; } // Check if any of the called computations has a side effect. for (const auto& computation : called_computations()) { if (computation->HasSideEffect()) { return true; } } return false; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCall( const Shape& shape, absl::Span<HloInstruction* const> operands, HloComputation* computation) { std::unique_ptr<HloInstruction> instruction = absl::WrapUnique(new HloInstruction(HloOpcode::kCall, shape)); for (auto operand : operands) { instruction->AppendOperand(operand); } instruction->called_computations_.push_back(computation); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCustomCall( const Shape& shape, absl::Span<HloInstruction* const> operands, absl::string_view custom_call_target, string opaque) { return absl::make_unique<HloCustomCallInstruction>( shape, operands, custom_call_target, std::move(opaque)); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCustomCall( const Shape& shape, absl::Span<HloInstruction* const> operands, absl::string_view custom_call_target, absl::Span<const Shape> operand_shapes_with_layout, string opaque) { return absl::make_unique<HloCustomCallInstruction>( shape, operands, custom_call_target, std::move(opaque), operand_shapes_with_layout); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTuple( absl::Span<HloInstruction* const> elements) { std::vector<Shape> element_shapes; for (auto element : elements) { element_shapes.push_back(element->shape()); } Shape tuple_shape = ShapeUtil::MakeTupleShape(element_shapes); return CreateVariadic(tuple_shape, HloOpcode::kTuple, elements); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateGather( const Shape& shape, HloInstruction* operand, HloInstruction* start_indices, const GatherDimensionNumbers& gather_dim_numbers, absl::Span<const int64> slice_sizes) { return absl::make_unique<HloGatherInstruction>( shape, operand, start_indices, gather_dim_numbers, slice_sizes); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateScatter( const Shape& shape, HloInstruction* operand, HloInstruction* scatter_indices, HloInstruction* updates, HloComputation* update_computation, const ScatterDimensionNumbers& scatter_dim_numbers) { return absl::make_unique<HloScatterInstruction>( shape, operand, scatter_indices, updates, update_computation, scatter_dim_numbers); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDomain( const Shape& shape, HloInstruction* operand, std::unique_ptr<DomainMetadata> operand_side_metadata, std::unique_ptr<DomainMetadata> user_side_metadata) { return absl::make_unique<HloDomainInstruction>( shape, operand, std::move(operand_side_metadata), std::move(user_side_metadata)); } std::unique_ptr<HloInstruction> HloInstruction::CloneWithNewOperands( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const { VLOG(3) << "CloneWithNewOperands:\n " << ToString(); VLOG(3) << " new operands:"; for (const HloInstruction* new_operand : new_operands) { VLOG(3) << " %" << new_operand->name(); } std::unique_ptr<HloInstruction> clone; // Explicitly call the factory for the instruction type. This is more robust // in the face of code changes than copying fields explicitly. This also // properly sets the user fields of the operands. switch (opcode_) { // Ops migrated to subclasses. // TODO(b/80131774): Remove this switch when migration is complete. case HloOpcode::kBatchNormTraining: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormGrad: case HloOpcode::kFft: case HloOpcode::kCompare: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReverse: case HloOpcode::kConcatenate: case HloOpcode::kReduce: case HloOpcode::kTranspose: case HloOpcode::kBroadcast: case HloOpcode::kReshape: case HloOpcode::kMap: case HloOpcode::kSlice: case HloOpcode::kConstant: case HloOpcode::kTrace: case HloOpcode::kFusion: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kParameter: case HloOpcode::kGetTupleElement: case HloOpcode::kReducePrecision: case HloOpcode::kAllReduce: case HloOpcode::kAllToAll: case HloOpcode::kCollectivePermute: case HloOpcode::kInfeed: case HloOpcode::kOutfeed: case HloOpcode::kConvolution: case HloOpcode::kCustomCall: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kPad: case HloOpcode::kDynamicSlice: case HloOpcode::kSort: case HloOpcode::kGather: case HloOpcode::kScatter: case HloOpcode::kIota: case HloOpcode::kDot: case HloOpcode::kDomain: case HloOpcode::kGetDimensionSize: case HloOpcode::kTriangularSolve: case HloOpcode::kCholesky: clone = CloneWithNewOperandsImpl(shape, new_operands, context); break; // Unary ops. case HloOpcode::kAbs: case HloOpcode::kRoundNearestAfz: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCopy: case HloOpcode::kCopyStart: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kTanh: CHECK_EQ(new_operands.size(), 1); clone = CreateUnary(shape, opcode_, new_operands[0]); break; // Binary ops. case HloOpcode::kAdd: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: CHECK_EQ(new_operands.size(), 2); clone = CreateBinary(shape, opcode_, new_operands[0], new_operands[1]); break; // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: case HloOpcode::kTupleSelect: CHECK_EQ(new_operands.size(), 3); clone = CreateTernary(shape, opcode_, new_operands[0], new_operands[1], new_operands[2]); break; // Other supported ops. case HloOpcode::kCall: clone = CreateCall(shape, new_operands, to_apply()); break; case HloOpcode::kConvert: CHECK_EQ(new_operands.size(), 1); clone = CreateConvert(shape, new_operands[0]); break; case HloOpcode::kBitcastConvert: CHECK_EQ(new_operands.size(), 1); clone = CreateBitcastConvert(shape, new_operands[0]); break; case HloOpcode::kDynamicUpdateSlice: clone = CreateDynamicUpdateSlice(shape, new_operands[0], new_operands[1], new_operands.subspan(2)); break; case HloOpcode::kTuple: clone = CreateTuple(new_operands); *clone->mutable_shape() = shape; break; case HloOpcode::kWhile: CHECK_EQ(new_operands.size(), 1); clone = CreateWhile(shape, while_condition(), while_body(), new_operands[0]); break; case HloOpcode::kConditional: CHECK_EQ(new_operands.size(), branch_count() + 1); clone = CreateConditional(shape, new_operands[0], absl::MakeSpan(branch_computations()), new_operands.subspan(1)); break; case HloOpcode::kAfterAll: if (new_operands.empty()) { clone = CreateToken(); } else { clone = CreateAfterAll(new_operands); } break; case HloOpcode::kAddDependency: CHECK_EQ(new_operands.size(), 2); clone = CreateAddDependency(new_operands[0], new_operands[1]); break; case HloOpcode::kReplicaId: CHECK_EQ(new_operands.size(), 0); clone = CreateReplicaId(); break; case HloOpcode::kPartitionId: CHECK_EQ(new_operands.size(), 0); clone = CreatePartitionId(); break; } // SetupDerivedInstruction will setup the precision_config_ field. SetupDerivedInstruction(clone.get()); clone->set_parent(parent_); clone->set_outer_dimension_partitions(outer_dimension_partitions_); clone->set_raw_backend_config_string(backend_config_); if (context != nullptr) { context->MapInstruction(this, clone.get()); clone->ReplaceCalledComputations([&](HloComputation* callee) { return callee->parent() != context->module() ? context->module()->DeepCloneComputation(callee, context) : callee; }); } return clone; } HloInstruction::~HloInstruction() { // Detach from operands. An instruction may be repeated as an operand. To // avoid calling RemoveUser twice on the same operand, check before remove. for (int64 operand_num = 0; operand_num < operand_count(); ++operand_num) { HloInstruction* operand = operands_[operand_num]; if (operand == nullptr) { continue; } if (operand->user_set_.find(this) != operand->user_set_.end()) { operand->RemoveUser(this); } operands_[operand_num] = nullptr; } // Update users. Set `nullptr` to the correpsonding operand slot for users. for (auto& user : this->users()) { for (int i = 0; i < user->operand_count(); ++i) { if (user->operands_[i] == this) { user->operands_[i] = nullptr; } } } } std::unique_ptr<HloInstruction> HloInstruction::Clone( const string& suffix, HloCloneContext* context) const { std::unique_ptr<HloInstruction> clone = CloneWithNewOperands(shape_, operands_, context); if (suffix.empty()) { clone->name_ = name(); } else { // If an instruction is cloned multiple times avoid names like // foo.suffix.suffix.suffix. Instead of repeating the suffix add a numeric // suffix. Specifically, the clone of foo.suffix is named foo.suffix2, the // clone of foo.suffix2 is named foo.suffix3 and so on. const string dot_suffix = "." + suffix; size_t index = name().rfind(dot_suffix); if (index == string::npos) { // Existing name does not include ".suffix". clone->name_ = name() + dot_suffix; } else { // Existing name includes ".suffix". Determine if substring after // ".suffix" is numeric and should be replaced with an incremented number. string after_suffix = name().substr(index + dot_suffix.size()); if (after_suffix.empty()) { // Existing name ends in ".suffix". New name should end in ".suffix2". clone->name_ = name() + "2"; } else { // If names ends with .suffix[0-9]+ then replace with a suffix with the // numeric value incremented. int64 numeric_suffix; if (absl::SimpleAtoi(after_suffix, &numeric_suffix)) { clone->name_ = StrCat(name().substr(0, index), dot_suffix, numeric_suffix + 1); } else { // Substring after ".suffix" is non-numeric. clone->name_ = name() + dot_suffix; } } } } return clone; } std::pair<const HloInstruction*, ShapeIndex> HloInstruction::LatestNonGteAncestorAndIndex() const { const HloInstruction* hlo = this; ShapeIndex index; while (hlo->opcode() == HloOpcode::kGetTupleElement) { index.push_back(hlo->tuple_index()); hlo = hlo->operand(0); } // We built up index in the reverse order from what we want. std::reverse(index.begin(), index.end()); return {hlo, index}; } const HloInstruction* HloInstruction::LatestNonGteAncestor() const { const HloInstruction* hlo = this; while (hlo->opcode() == HloOpcode::kGetTupleElement) { hlo = hlo->operand(0); } return hlo; } const HloInstruction* HloInstruction::operand(int64 i) const { return operands_.at(i); } HloInstruction* HloInstruction::mutable_operand(int64 i) { CHECK(operands_[i] != nullptr); return operands_.at(i); } int64 HloInstruction::operand_index(const HloInstruction* target) const { for (int64 i = 0; i < operand_count(); ++i) { if (target == operand(i)) { return i; } } LOG(FATAL) << "target was not an operand: " << target->ToString(); } HloInstruction::InstructionVector HloInstruction::unique_operands() const { InstructionVector unique; absl::flat_hash_set<const HloInstruction*> seen; for (HloInstruction* operand : operands()) { if (seen.insert(operand).second) { unique.push_back(operand); } } return unique; } Status HloInstruction::AddControlDependencyTo(HloInstruction* instruction) { TF_RET_CHECK(instruction->parent() == parent()); if (!absl::c_linear_search(control_successors_, instruction)) { control_successors_.push_back(instruction); TF_RET_CHECK( !absl::c_linear_search(instruction->control_predecessors_, this)); instruction->control_predecessors_.push_back(this); } return Status::OK(); } Status HloInstruction::RemoveControlDependencyTo(HloInstruction* instruction) { TF_RET_CHECK(instruction->parent() == parent()); TF_RETURN_IF_ERROR(EraseElementFromVector(&control_successors_, instruction)); TF_RETURN_IF_ERROR( EraseElementFromVector(&instruction->control_predecessors_, this)); return Status::OK(); } Status HloInstruction::DropAllControlDeps() { for (auto* ctrl_succ : control_successors_) { TF_RETURN_IF_ERROR( EraseElementFromVector(&ctrl_succ->control_predecessors_, this)); } for (auto* ctrl_pred : control_predecessors_) { TF_RETURN_IF_ERROR( EraseElementFromVector(&ctrl_pred->control_successors_, this)); } control_successors_.clear(); control_predecessors_.clear(); return Status::OK(); } Status HloInstruction::CopyAllControlDepsFrom(const HloInstruction* inst) { for (auto* ctrl_pred : inst->control_predecessors()) { TF_RETURN_IF_ERROR(ctrl_pred->AddControlDependencyTo(this)); } for (auto* ctrl_succ : inst->control_successors()) { TF_RETURN_IF_ERROR(this->AddControlDependencyTo(ctrl_succ)); } return Status::OK(); } void HloInstruction::AppendOperand(HloInstruction* operand) { operands_.push_back(operand); operand->AddUser(this); } void HloInstruction::RemoveOperandsAtAscendingIndices( absl::Span<const int> ascending_indices) { if (ascending_indices.empty()) { return; } int next_index = 0; int removed_count = 0; for (int to_remove : ascending_indices) { while (next_index < to_remove) { operands_[next_index - removed_count] = operands_[next_index]; ++next_index; } CHECK_LT(to_remove, operands_.size()); ++removed_count; ++next_index; } while (next_index < operands_.size()) { operands_[next_index - removed_count] = operands_[next_index]; ++next_index; } CHECK_EQ(removed_count, ascending_indices.size()); operands_.resize(operands_.size() - removed_count); } void HloInstruction::AddUser(HloInstruction* user) { if (!ContainsKey(user_set_, user)) { user_set_.insert(user); users_.push_back(user); } } bool HloInstruction::HasConstantOperand() const { for (const HloInstruction* operand : operands_) { if (operand->IsConstant()) { return true; } } return false; } bool HloInstruction::IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const { // Perform opcode specific checks. switch (opcode()) { // The result of these instructions only depend upon their opcode and // operands. case HloOpcode::kAbs: case HloOpcode::kAtan2: case HloOpcode::kAdd: case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kCeil: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kComplex: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kCopyStart: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kDivide: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kRemainder: case HloOpcode::kReshape: case HloOpcode::kReplicaId: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRsqrt: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kSubtract: case HloOpcode::kTanh: case HloOpcode::kTuple: case HloOpcode::kTupleSelect: return true; // This opcode has complex or special behavior so just return false. case HloOpcode::kAfterAll: case HloOpcode::kAddDependency: return false; // Remaining instructions with special values. case HloOpcode::kCall: return eq_computations(to_apply(), other.to_apply()); case HloOpcode::kConditional: for (int j = 0; j < branch_count(); ++j) { if (!eq_computations(branch_computation(j), other.branch_computation(j))) { return false; } } return true; case HloOpcode::kWhile: return (eq_computations(while_body(), other.while_body()) && eq_computations(while_condition(), other.while_condition())); // Ops migrated to subclasses should never come to this line. // TODO(b/80131774): Remove this switch when migration is complete. case HloOpcode::kBatchNormTraining: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormGrad: case HloOpcode::kFft: case HloOpcode::kCompare: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReverse: case HloOpcode::kConcatenate: case HloOpcode::kReduce: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kBroadcast: case HloOpcode::kMap: case HloOpcode::kSlice: case HloOpcode::kConstant: case HloOpcode::kIota: case HloOpcode::kTrace: case HloOpcode::kFusion: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kParameter: case HloOpcode::kGetTupleElement: case HloOpcode::kReducePrecision: case HloOpcode::kInfeed: case HloOpcode::kOutfeed: case HloOpcode::kAllReduce: case HloOpcode::kAllToAll: case HloOpcode::kCollectivePermute: case HloOpcode::kConvolution: case HloOpcode::kCustomCall: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kPad: case HloOpcode::kDynamicSlice: case HloOpcode::kGather: case HloOpcode::kScatter: case HloOpcode::kDot: case HloOpcode::kDomain: case HloOpcode::kGetDimensionSize: case HloOpcode::kTriangularSolve: case HloOpcode::kCholesky: LOG(FATAL) << "Base class impl called for opcode with subclass: " << opcode(); } return false; } static uint64 HashOperand(const HloInstruction* hlo) { return ShapeUtil::Hash(hlo->shape()); } uint64 HloInstruction::Hash( const std::function<uint64(const HloInstruction*)>& hash_operand) const { using tensorflow::Hash64Combine; uint64 hash_value = Hash64Combine(0, static_cast<uint64>(opcode())); hash_value = Hash64Combine(hash_value, ShapeUtil::Hash(shape())); if (!IsCrossModuleAllReduce()) { if (!operands().empty()) { for (size_t i = 0; i < operands().size(); ++i) { hash_value = Hash64Combine(hash_value, hash_operand(operand(i))); } } } hash_value = Hash64Combine(hash_value, InnerHash()); return hash_value; } uint64 HloInstruction::Hash() const { // Use HashOperand as an argument to prevent non-termination. return Hash(HashOperand); } uint64 HloInstruction::InnerHash() const { return 13; } void HloInstruction::RemoveUser(HloInstruction* user) { auto set_it = user_set_.find(user); CHECK(set_it != user_set_.end()); user_set_.erase(set_it); // This is linear in the number of the users, but a vector provides a stable // iteration order and much faster traversal. auto vec_it = absl::c_find(users_, user); CHECK(vec_it != users_.end()); users_.erase(vec_it); } Status HloInstruction::ReplaceUseWith(HloInstruction* user, HloInstruction* new_producer) { TF_RET_CHECK( ShapeUtil::CompatibleIgnoringFpPrecision(shape(), new_producer->shape())) << "this shape: " << ShapeUtil::HumanString(shape()) << ", replacement shape: " << ShapeUtil::HumanString(new_producer->shape()); return ReplaceUseWithDifferentShape(user, new_producer); } Status HloInstruction::ReplaceUseWithDifferentShape( HloInstruction* user, HloInstruction* new_producer) { VLOG(3) << "Replacing uses of " << name() << " in " << user->name() << " with " << new_producer->name(); RemoveUser(user); TF_RET_CHECK(absl::c_count(user->operands_, this) >= 0); std::replace(user->operands_.begin(), user->operands_.end(), this, new_producer); new_producer->AddUser(user); // Custom fusions may not be able to handle deduplicated operands. if (user->opcode() == HloOpcode::kFusion) { TF_RETURN_IF_ERROR( Cast<HloFusionInstruction>(user)->DeduplicateFusionOperands()); } return Status::OK(); } Status HloInstruction::ReplaceOperandWith(int64 operand_num, HloInstruction* new_operand) { auto old_operand = operand(operand_num); TF_RET_CHECK(ShapeUtil::CompatibleIgnoringFpPrecision(old_operand->shape(), new_operand->shape())) << old_operand->shape() << " is not compatible with " << new_operand->shape(); return ReplaceOperandWithDifferentShape(operand_num, new_operand); } Status HloInstruction::ReplaceOperandWithDifferentShape( int64 operand_num, HloInstruction* new_operand) { TF_RET_CHECK(operand_num >= 0); TF_RET_CHECK(operand_num < operand_count()); HloInstruction* old_operand = mutable_operand(operand_num); if (old_operand == new_operand) { return Status::OK(); } operands_[operand_num] = new_operand; VLOG(3) << "Replacing operand " << operand_num << " of " << name() << " with " << new_operand->name() << ", was " << old_operand->name(); if (!absl::c_linear_search(operands_, old_operand)) { old_operand->RemoveUser(this); } new_operand->AddUser(this); return Status::OK(); } Status HloInstruction::ReplaceAllUsesWith(HloInstruction* new_producer) { TF_RET_CHECK( ShapeUtil::CompatibleIgnoringFpPrecision(shape(), new_producer->shape())) << shape() << " is not compatible with " << new_producer->shape(); return ReplaceAllUsesWithDifferentShape(new_producer); } Status HloInstruction::ReplaceAllUsesWithDifferentShape( HloInstruction* new_producer) { bool new_producer_is_user = false; for (HloInstruction* user : users()) { if (user == new_producer) { // It's possible that new_producer is a user of this instruction as might // be the case when replacing an instruction with a kCopy of itself. In // this case, don't do the replacement to avoid creating a cycle in the // graph. new_producer remains the only user of this instruction. new_producer_is_user = true; } else { std::replace(user->operands_.begin(), user->operands_.end(), this, new_producer); new_producer->AddUser(user); if (user->opcode() == HloOpcode::kFusion) { TF_RETURN_IF_ERROR( Cast<HloFusionInstruction>(user)->DeduplicateFusionOperands()); } } } users_.clear(); user_set_.clear(); if (new_producer_is_user) { AddUser(new_producer); } if (parent_ && parent_->root_instruction() == this) { parent_->set_root_instruction(new_producer, /*accept_different_shape=*/true); } return Status::OK(); } HloComputation* HloInstruction::to_apply() const { switch (opcode_) { case HloOpcode::kCall: case HloOpcode::kMap: case HloOpcode::kReduceWindow: case HloOpcode::kReduce: case HloOpcode::kAllReduce: case HloOpcode::kScatter: case HloOpcode::kSort: CHECK_EQ(called_computations_.size(), 1); return called_computations_[0]; default: LOG(FATAL) << "Invalid opcode for to_apply(): " << HloOpcodeString(opcode()); } } void HloInstruction::set_to_apply(HloComputation* computation) { // Don't allow changing the computation for fused instructions so we don't // have to recompute called_instructions for the entire fusion instruction. CHECK(!IsFused()); switch (opcode_) { case HloOpcode::kCall: case HloOpcode::kMap: case HloOpcode::kReduceWindow: case HloOpcode::kReduce: case HloOpcode::kAllReduce: case HloOpcode::kScatter: case HloOpcode::kSort: CHECK_EQ(called_computations_.size(), 1); called_computations_[0] = computation; break; default: LOG(FATAL) << "Invalid opcode for to_apply(): " << HloOpcodeString(opcode()); } } HloComputation* HloInstruction::while_condition() const { CHECK_EQ(HloOpcode::kWhile, opcode_); return called_computations_[kConditionComputationIndex]; } HloComputation* HloInstruction::while_body() const { CHECK_EQ(HloOpcode::kWhile, opcode_); return called_computations_[kBodyComputationIndex]; } void HloInstruction::set_while_condition(HloComputation* computation) { // Don't allow changing the computation for fused instructions so we don't // have to recompute called_instructions for the entire fusion instruction. CHECK(!IsFused()); CHECK_EQ(HloOpcode::kWhile, opcode_); called_computations_[kConditionComputationIndex] = computation; } void HloInstruction::set_while_body(HloComputation* computation) { // Don't allow changing the computation for fused instructions so we don't // have to recompute called_instructions for the entire fusion instruction. CHECK(!IsFused()); CHECK_EQ(HloOpcode::kWhile, opcode_); called_computations_[kBodyComputationIndex] = computation; } HloInstruction* HloInstruction::while_init() const { CHECK_EQ(HloOpcode::kWhile, opcode_); return operands_[0]; } HloComputation* HloInstruction::true_computation() const { CHECK_EQ(HloOpcode::kConditional, opcode_); CHECK_EQ(PRED, operand(0)->shape().element_type()); return called_computations_[kTrueComputationIndex]; } HloComputation* HloInstruction::false_computation() const { CHECK_EQ(HloOpcode::kConditional, opcode_); CHECK_EQ(PRED, operand(0)->shape().element_type()); return called_computations_[kFalseComputationIndex]; } const std::vector<HloComputation*>& HloInstruction::branch_computations() const { CHECK(HloOpcode::kConditional == opcode_); return called_computations_; } int HloInstruction::branch_count() const { CHECK(HloOpcode::kConditional == opcode_); return called_computations_.size(); } HloComputation* HloInstruction::branch_computation(int b) const { CHECK(HloOpcode::kConditional == opcode_); CHECK_GE(b, 0); CHECK_LT(b, called_computations_.size()); return called_computations_[b]; } void HloInstruction::set_branch_computation(int b, HloComputation* computation) { // Don't allow changing the computation for fused instructions so we don't // have to recompute called_instructions for the entire fusion instruction. CHECK(!IsFused()); CHECK_EQ(HloOpcode::kConditional, opcode_); called_computations_[b] = computation; } string HloInstruction::SignatureString() const { string operands = StrJoin(operands_, ", ", [](string* out, HloInstruction* operand) { StrAppend(out, ShapeUtil::HumanString(operand->shape())); }); return StrCat("(", operands, ") -> ", ShapeUtil::HumanString(shape())); } string PrintName(const string& name, bool print_ids) { if (print_ids) { return name; } else { auto dot_position = name.find_first_of("."); return name.substr(0, dot_position); } } namespace { string PrintNameInternal(const string& name, const HloPrintOptions& options) { return StrCat(options.print_percent() ? "%" : "", PrintName(name, options.print_ids())); } } // namespace string HloInstruction::ToString(const HloPrintOptions& options) const { CanonicalNameMap new_map; return ToStringWithCanonicalNameMap(options, &new_map); } bool HloInstruction::IsElementwiseImpl( const absl::optional<int64>& operand_idx) const { switch (opcode_) { // Unary elementwise operations. case HloOpcode::kAbs: case HloOpcode::kRoundNearestAfz: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kConvert: case HloOpcode::kBitcastConvert: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kReducePrecision: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kTanh: CHECK_EQ(1, operand_count()); return true; // Binary elementwise operations, the same as in IsElementwiseBinary(). case HloOpcode::kAdd: case HloOpcode::kAtan2: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kDivide: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kSubtract: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: CHECK_EQ(2, operand_count()); return true; // Ternary elementwise operations. case HloOpcode::kSelect: case HloOpcode::kClamp: return true; case HloOpcode::kDynamicUpdateSlice: return operand_idx.has_value() && operand_idx.value() == 0; default: return false; } } bool HloInstruction::IsCrossModuleAllReduce() const { return opcode() == HloOpcode::kAllReduce && channel_id(); } bool HloInstruction::IsCrossReplicaAllReduce() const { return opcode() == HloOpcode::kAllReduce && !channel_id(); } string HloInstruction::ToStringWithCanonicalNameMap( const HloPrintOptions& options, CanonicalNameMap* canonical_name_map) const { string result = ""; // Logic to print the instruction name (e.g. "%foo = "). if (options.canonicalize_instruction_names()) { if (options.is_in_nested_computation()) { // If we are canonicalizing instruction names and this is a top-level // HloInstruction::ToString() call, don't print an instruction name. StrAppend(&result, PrintNameInternal(canonical_name_map->LookupOrInsert(name()), options), " = "); } } else { StrAppend(&result, PrintNameInternal(name(), options), " = "); } // Print shape. if (options.include_layout_in_shapes()) { StrAppend(&result, ShapeUtil::HumanStringWithLayout(shape())); } else { StrAppend(&result, ShapeUtil::HumanString(shape())); } // Print opcode, operand(s). StrAppend(&result, " ", HloOpcodeString(opcode()), "(", OperandsToStringWithCanonicalNameMap(options, canonical_name_map), ")"); // Print additional attributes. If an instruction contains a subcomputation, // the subcomputation is also printed here. for (const string& extra : ExtraAttributesToString(options)) { StrAppend(&result, ", ", extra); } if (options.print_metadata() && (!metadata_.op_type().empty() || !metadata_.op_name().empty() || !metadata_.source_file().empty())) { StrAppend(&result, ", metadata={", xla::OpMetadataToString(metadata_), "}"); } if (options.print_backend_config() && !backend_config_.empty()) { StrAppend(&result, ", backend_config=\"", CEscape(backend_config_), "\""); } return result; } string HloInstruction::OperandsToString(const HloPrintOptions& options) const { CanonicalNameMap new_map; return OperandsToStringWithCanonicalNameMap(options, &new_map); } string HloInstruction::OperandsToStringWithCanonicalNameMap( const HloPrintOptions& options, CanonicalNameMap* canonical_name_map) const { string operands; absl::Span<HloInstruction* const> slice(operands_); const int64 kMaxOperandsToShowIfCompact = 4; if (options.compact_operands() && slice.size() > kMaxOperandsToShowIfCompact) { slice.remove_suffix(slice.size() - kMaxOperandsToShowIfCompact); } operands = StrJoin(slice, ", ", [&](string* out, HloInstruction* operand) { // If operand is already been deleted, put `null` to the string output. if (operand == nullptr) { StrAppend(out, "null "); return; } std::vector<string> str; if (options.print_operand_shape()) { if (options.include_layout_in_shapes()) { str.push_back(ShapeUtil::HumanStringWithLayout(operand->shape())); } else { str.push_back(ShapeUtil::HumanString(operand->shape())); } } // In a top-level HloInstruction::ToString() call, the operand name is not // part of the canonical string. if (options.canonicalize_instruction_names() && options.is_in_nested_computation()) { str.push_back(PrintNameInternal( canonical_name_map->LookupOrInsert(operand->name()), options)); } else if (options.print_operand_names()) { str.push_back(PrintNameInternal(operand->name(), options)); } StrAppend(out, StrJoin(str, " ")); }); const int64 remaining = operands_.size() - slice.size(); if (slice.size() != operands_.size()) { StrAppend(&operands, ", ...(+", remaining, ")"); } return operands; } std::vector<string> HloInstruction::ExtraAttributesToString( const HloPrintOptions& options) const { std::vector<string> extra = ExtraAttributesToStringImpl(options); if (options.print_subcomputation_mode() == HloPrintOptions::PrintSubcomputationMode::kNameOnly) { if (opcode() == HloOpcode::kWhile) { extra.push_back(StrCat( "condition=", PrintNameInternal(while_condition()->name(), options))); extra.push_back( StrCat("body=", PrintNameInternal(while_body()->name(), options))); } else if (opcode() == HloOpcode::kSelectAndScatter) { extra.push_back( StrCat("select=", PrintNameInternal(select()->name(), options))); extra.push_back( StrCat("scatter=", PrintNameInternal(scatter()->name(), options))); } else if (opcode() == HloOpcode::kConditional) { if (operand(0)->shape().element_type() == PRED) { extra.push_back( StrCat("true_computation=", PrintNameInternal(true_computation()->name(), options))); extra.push_back( StrCat("false_computation=", PrintNameInternal(false_computation()->name(), options))); } else { extra.push_back(StrCat( "branch_computations={", StrJoin(branch_computations(), ", ", [&](string* out, const HloComputation* computation) { StrAppend( out, PrintNameInternal(computation->name(), options)); }), "}")); } } else if (opcode() == HloOpcode::kCall || opcode() == HloOpcode::kMap || opcode() == HloOpcode::kReduceWindow || opcode() == HloOpcode::kReduce || opcode() == HloOpcode::kAllReduce || opcode() == HloOpcode::kScatter || opcode() == HloOpcode::kSort) { extra.push_back( StrCat("to_apply=", PrintNameInternal(to_apply()->name(), options))); } else if (!called_computations().empty()) { extra.push_back(StrCat( "calls=", StrJoin(called_computations(), ", ", [&](string* out, const HloComputation* computation) { StrAppend(out, PrintNameInternal(computation->name(), options)); }))); } } else if (options.print_subcomputation_mode() == HloPrintOptions::PrintSubcomputationMode::kFullBodies) { HloPrintOptions new_options = options; new_options.set_is_in_nested_computation(true); switch (opcode()) { case HloOpcode::kWhile: extra.push_back( StrCat("condition=\n", while_condition()->ToString(new_options))); extra.push_back(StrCat("body=\n", while_body()->ToString(new_options))); break; case HloOpcode::kSelectAndScatter: extra.push_back(StrCat("select=\n", select()->ToString(new_options))); extra.push_back(StrCat("scatter=\n", scatter()->ToString(new_options))); break; case HloOpcode::kConditional: if (operand(0)->shape().element_type() == PRED) { extra.push_back(StrCat("true_computation=\n", true_computation()->ToString(new_options))); extra.push_back(StrCat("false_computation=\n", false_computation()->ToString(new_options))); } else { extra.push_back(StrCat( "branch_computations={\n", StrJoin(branch_computations(), ",\n", [&](string* out, const HloComputation* computation) { StrAppend(out, computation->ToString(new_options)); }), "\n}")); } break; case HloOpcode::kCall: case HloOpcode::kMap: case HloOpcode::kReduceWindow: case HloOpcode::kReduce: case HloOpcode::kAllReduce: case HloOpcode::kScatter: case HloOpcode::kSort: extra.push_back( StrCat("to_apply=\n", to_apply()->ToString(new_options))); break; default: if (!called_computations().empty()) { extra.push_back(StrCat( "calls=\n", StrJoin(called_computations(), ", ", [&](string* out, const HloComputation* computation) { StrAppend(out, computation->ToString(new_options)); }))); } break; } } if (has_sharding()) { extra.push_back(StrCat("sharding=", sharding().ToString())); } if (!outer_dimension_partitions_.empty()) { extra.push_back(absl::StrFormat("outer_dimension_partitions={%s}", StrJoin(outer_dimension_partitions_, ","))); } if (options.print_control_dependencies() && !control_predecessors_.empty()) { extra.push_back(StrCat("control-predecessors={", StrJoin(control_predecessors_, ", ", [&](string* out, HloInstruction* pre) { StrAppend(out, PrintNameInternal( pre->name(), options)); }), "}")); } return extra; } string HloInstruction::ToShortString() const { return StrCat("%", name(), " = ", HloOpcodeString(opcode()), "(", StrJoin(operands_, ", ", [](string* out, HloInstruction* operand) { StrAppend(out, "%", operand->name()); }), ")"); } HloInstructionProto HloInstruction::ToProto() const { HloInstructionProto proto; CHECK(unique_id_ != -1) << "This instruction does not have a valid id. Please make sure the " "instruction is inside a module before dumping it."; proto.set_id(unique_id_); proto.set_name(name_); proto.set_opcode(HloOpcodeString(opcode_)); *proto.mutable_shape() = shape_.ToProto(); for (const HloInstruction* operand : operands_) { proto.add_operand_ids(operand->unique_id()); } for (const HloInstruction* control : control_predecessors_) { proto.add_control_predecessor_ids(control->unique_id()); } *proto.mutable_metadata() = metadata_; proto.set_backend_config(backend_config_); if (opcode() != HloOpcode::kFusion) { for (const HloComputation* computation : called_computations_) { proto.add_called_computation_ids(computation->unique_id()); } } if (has_sharding()) { *proto.mutable_sharding() = sharding().ToProto(); } if (!outer_dimension_partitions_.empty()) { for (const auto& idx : outer_dimension_partitions_) { proto.mutable_outer_dimension_partitions()->Add(idx); } } return proto; } string HloInstruction::ToCategory() const { if (opcode() == HloOpcode::kTranspose || opcode() == HloOpcode::kCopy || opcode() == HloOpcode::kReshape) { return "data formatting"; } if (IsElementwise()) { return "non-fusion elementwise"; } return HloOpcodeString(opcode()); } HloInstruction* HloInstruction::tracing() const { return trace_instruction_; } void HloInstruction::set_tracing(HloInstruction* trace_instruction) { trace_instruction_ = trace_instruction; } bool HloInstruction::IsFused() const { return parent_->IsFusionComputation(); } bool HloInstruction::IsInputFusion() const { return opcode() == HloOpcode::kFusion && fusion_kind() == FusionKind::kInput; } bool HloInstruction::IsLoopFusion() const { return opcode() == HloOpcode::kFusion && fusion_kind() == FusionKind::kLoop; } bool HloInstruction::IsOutputFusion() const { return opcode() == HloOpcode::kFusion && fusion_kind() == FusionKind::kOutput; } bool HloInstruction::IsCustomFusion() const { return opcode() == HloOpcode::kFusion && fusion_kind() == FusionKind::kCustom; } bool HloInstruction::IsFusible() const { // Instructions which are traced should not be fused. if (tracing()) { return false; } // Some kinds of instructions don't make sense to fuse. switch (opcode_) { case HloOpcode::kDomain: case HloOpcode::kParameter: return false; // Side effecting instrutions cannot be fused. default: return !HasSideEffect(); } } HloInstruction::HloInstruction(HloOpcode opcode, const Shape& shape) : unique_id_(-1), opcode_(opcode), shape_(shape), name_(HloOpcodeString(opcode)) { TF_DCHECK_OK(ShapeUtil::ValidateShapeWithOptionalLayout(shape_)); } template <typename HloInstructionPtr> Status HloInstruction::Visit(DfsHloVisitorBase<HloInstructionPtr>* visitor) { switch (opcode_) { case HloOpcode::kAbs: return visitor->HandleAbs(this); case HloOpcode::kAtan2: return visitor->HandleAtan2(this); case HloOpcode::kRoundNearestAfz: return visitor->HandleRound(this); case HloOpcode::kBatchNormTraining: return visitor->HandleBatchNormTraining(this); case HloOpcode::kBatchNormInference: return visitor->HandleBatchNormInference(this); case HloOpcode::kBatchNormGrad: return visitor->HandleBatchNormGrad(this); case HloOpcode::kSign: return visitor->HandleSign(this); case HloOpcode::kConstant: return visitor->HandleConstant(this); case HloOpcode::kGetTupleElement: return visitor->HandleGetTupleElement(this); case HloOpcode::kParameter: return visitor->HandleParameter(this); case HloOpcode::kCompare: return visitor->HandleCompare(this); case HloOpcode::kComplex: return visitor->HandleComplex(this); case HloOpcode::kAdd: return visitor->HandleAdd(this); case HloOpcode::kDivide: return visitor->HandleDivide(this); case HloOpcode::kSubtract: return visitor->HandleSubtract(this); case HloOpcode::kMaximum: return visitor->HandleMaximum(this); case HloOpcode::kMinimum: return visitor->HandleMinimum(this); case HloOpcode::kAnd: return visitor->HandleAnd(this); case HloOpcode::kOr: return visitor->HandleOr(this); case HloOpcode::kXor: return visitor->HandleXor(this); case HloOpcode::kShiftLeft: return visitor->HandleShiftLeft(this); case HloOpcode::kShiftRightArithmetic: return visitor->HandleShiftRightArithmetic(this); case HloOpcode::kShiftRightLogical: return visitor->HandleShiftRightLogical(this); case HloOpcode::kConcatenate: return visitor->HandleConcatenate(this); case HloOpcode::kConvert: return visitor->HandleConvert(this); case HloOpcode::kBitcastConvert: return visitor->HandleBitcastConvert(this); case HloOpcode::kCopy: return visitor->HandleCopy(this); case HloOpcode::kMultiply: return visitor->HandleMultiply(this); case HloOpcode::kDot: return visitor->HandleDot(this); case HloOpcode::kPower: return visitor->HandlePower(this); case HloOpcode::kRemainder: return visitor->HandleRemainder(this); case HloOpcode::kSelect: return visitor->HandleSelect(this); case HloOpcode::kTupleSelect: return visitor->HandleTupleSelect(this); case HloOpcode::kConvolution: return visitor->HandleConvolution(this); case HloOpcode::kFft: return visitor->HandleFft(this); case HloOpcode::kAllReduce: return visitor->HandleAllReduce(this); case HloOpcode::kAllToAll: return visitor->HandleAllToAll(this); case HloOpcode::kCollectivePermute: return visitor->HandleCollectivePermute(this); case HloOpcode::kReplicaId: return visitor->HandleReplicaId(this); case HloOpcode::kPartitionId: return visitor->HandlePartitionId(this); case HloOpcode::kTuple: return visitor->HandleTuple(this); case HloOpcode::kMap: return visitor->HandleMap(this); case HloOpcode::kClamp: return visitor->HandleClamp(this); case HloOpcode::kReduce: return visitor->HandleReduce(this); case HloOpcode::kReduceWindow: return visitor->HandleReduceWindow(this); case HloOpcode::kSelectAndScatter: return visitor->HandleSelectAndScatter(this); case HloOpcode::kNegate: return visitor->HandleNegate(this); case HloOpcode::kExp: return visitor->HandleExp(this); case HloOpcode::kExpm1: return visitor->HandleExpm1(this); case HloOpcode::kFloor: return visitor->HandleFloor(this); case HloOpcode::kCeil: return visitor->HandleCeil(this); case HloOpcode::kClz: return visitor->HandleClz(this); case HloOpcode::kLog: return visitor->HandleLog(this); case HloOpcode::kLog1p: return visitor->HandleLog1p(this); case HloOpcode::kTanh: return visitor->HandleTanh(this); case HloOpcode::kCos: return visitor->HandleCos(this); case HloOpcode::kSin: return visitor->HandleSin(this); case HloOpcode::kSqrt: return visitor->HandleSqrt(this); case HloOpcode::kRsqrt: return visitor->HandleRsqrt(this); case HloOpcode::kReal: return visitor->HandleReal(this); case HloOpcode::kImag: return visitor->HandleImag(this); case HloOpcode::kIsFinite: return visitor->HandleIsFinite(this); case HloOpcode::kNot: return visitor->HandleNot(this); case HloOpcode::kPopulationCount: return visitor->HandlePopulationCount(this); case HloOpcode::kBitcast: return visitor->HandleBitcast(this); case HloOpcode::kBroadcast: return visitor->HandleBroadcast(this); case HloOpcode::kPad: return visitor->HandlePad(this); case HloOpcode::kReshape: return visitor->HandleReshape(this); case HloOpcode::kTranspose: return visitor->HandleTranspose(this); case HloOpcode::kReverse: return visitor->HandleReverse(this); case HloOpcode::kReducePrecision: return visitor->HandleReducePrecision(this); case HloOpcode::kSlice: return visitor->HandleSlice(this); case HloOpcode::kDynamicSlice: return visitor->HandleDynamicSlice(this); case HloOpcode::kDynamicUpdateSlice: return visitor->HandleDynamicUpdateSlice(this); case HloOpcode::kSort: return visitor->HandleSort(this); case HloOpcode::kInfeed: return visitor->HandleInfeed(this); case HloOpcode::kOutfeed: return visitor->HandleOutfeed(this); case HloOpcode::kRng: return visitor->HandleRng(this); case HloOpcode::kRngGetAndUpdateState: return visitor->HandleRngGetAndUpdateState(this); case HloOpcode::kWhile: return visitor->HandleWhile(this); case HloOpcode::kFusion: return visitor->HandleFusion(this); case HloOpcode::kCall: return visitor->HandleCall(this); case HloOpcode::kConditional: return visitor->HandleConditional(this); case HloOpcode::kCustomCall: return visitor->HandleCustomCall(this); case HloOpcode::kCopyStart: return visitor->HandleCopyStart(this); case HloOpcode::kCopyDone: return visitor->HandleCopyDone(this); case HloOpcode::kRecv: return visitor->HandleRecv(this); case HloOpcode::kRecvDone: return visitor->HandleRecvDone(this); case HloOpcode::kSend: return visitor->HandleSend(this); case HloOpcode::kSendDone: return visitor->HandleSendDone(this); case HloOpcode::kGather: return visitor->HandleGather(this); case HloOpcode::kScatter: return visitor->HandleScatter(this); case HloOpcode::kDomain: return visitor->HandleDomain(this); case HloOpcode::kAfterAll: return visitor->HandleAfterAll(this); case HloOpcode::kAddDependency: return visitor->HandleAddDependency(this); case HloOpcode::kIota: return visitor->HandleIota(this); case HloOpcode::kGetDimensionSize: return visitor->HandleGetDimensionSize(this); case HloOpcode::kTriangularSolve: return visitor->HandleTriangularSolve(this); case HloOpcode::kCholesky: return visitor->HandleCholesky(this); // These opcodes are not handled here. case HloOpcode::kTrace: break; } return InternalError( "Unhandled HloOpcode for DfsHloVisitor: %s. This should not happen - " "please file a bug for XLA.", HloOpcodeString(opcode_)); } // Explicit instantiations. template Status HloInstruction::Visit(DfsHloVisitor* visitor); template Status HloInstruction::Visit(ConstDfsHloVisitor* visitor); using DFSStack = absl::InlinedVector<std::pair<int, HloInstruction*>, 16>; // Push "child" onto the dfs_stack if not already visited. Returns false if a // cycle was detected, and true otherwise. template <typename Visitor> inline bool PushDFSChild(Visitor* visitor, DFSStack* dfs_stack, HloInstruction* child) { CHECK(child != nullptr); const int id = child->unique_id(); CHECK_GE(id, 0) << "instruction may not have a parent computation"; switch (visitor->GetVisitState(id)) { case Visitor::kVisiting: return false; case Visitor::kVisited: // Nothing to do return true; case Visitor::kNotVisited: dfs_stack->push_back(std::make_pair(id, child)); return true; } } using InternalCompareFunction = std::function<bool(std::pair<int, const HloInstruction*>, std::pair<int, const HloInstruction*>)>; template <typename Visitor> static Status PostOrderDFS(HloInstruction* root, Visitor* visitor, const InternalCompareFunction* operand_order, bool ignore_control_predecessors) { // Calculating the instruction count within a module can be expensive on large // models so only do it if the visit state is empty. This will help when the // same visitor is reused across many computations of a single module. if (visitor->VisitStateCapacity() == 0) { visitor->ReserveVisitStates(root->GetModule()->instruction_count()); } // dfs_stack holds pairs of <HloInstruction*->unique_id(), HloInstruction*>. // // We need to keep track of both the id and the instruction because // instructions can get deleted while they are on the stack, so we // can't always use the (potentially dead) instruction object to grab // its id. DFSStack dfs_stack; dfs_stack.emplace_back(root->unique_id(), root); do { DCHECK(!dfs_stack.empty()); int current_id = dfs_stack.back().first; HloInstruction* current_node = dfs_stack.back().second; CHECK_GE(current_id, 0) << current_id << ": " << current_node << ": instruction may not have parent computation"; typename Visitor::VisitState visit_state = visitor->GetVisitState(current_id); if (visit_state == Visitor::kVisited) { dfs_stack.pop_back(); VLOG(3) << "Not visiting HLO %" << current_node->name() << " as it was already visited."; continue; } if (visit_state == Visitor::kVisiting) { dfs_stack.pop_back(); TF_RETURN_IF_ERROR(visitor->Preprocess(current_node)); VLOG(2) << "Visiting HLO %" << current_node->name(); TF_RETURN_IF_ERROR(current_node->Visit(visitor)); visitor->SetVisitState(current_id, Visitor::kVisited); TF_RETURN_IF_ERROR(visitor->Postprocess(current_node)); continue; } visitor->SetVisitState(current_id, Visitor::kVisiting); const size_t old_dfs_stack_size = dfs_stack.size(); for (HloInstruction* child : current_node->operands()) { if (!TF_PREDICT_TRUE(PushDFSChild(visitor, &dfs_stack, child))) { return FailedPrecondition( "A cycle is detected while visiting instruction %s", current_node->ToString()); } } if (!ignore_control_predecessors) { for (HloInstruction* child : current_node->control_predecessors()) { if (!TF_PREDICT_TRUE(PushDFSChild(visitor, &dfs_stack, child))) { return FailedPrecondition( "A cycle is detected while visiting instruction %s", current_node->ToString()); } } } if (operand_order != nullptr) { std::sort(dfs_stack.begin() + old_dfs_stack_size, dfs_stack.end(), *operand_order); } // This makes the traversal order the same as what you'd expect // out of a recursive algorithm. std::reverse(dfs_stack.begin() + old_dfs_stack_size, dfs_stack.end()); } while (!dfs_stack.empty()); return Status::OK(); } template <typename HloInstructionPtr> Status HloInstruction::Accept(DfsHloVisitorBase<HloInstructionPtr>* visitor, bool call_finish_visit, bool ignore_control_predecessors) { VLOG(3) << "HloInstruction::Accept(%" << name() << ")"; TF_RETURN_IF_ERROR( PostOrderDFS(this, visitor, nullptr, ignore_control_predecessors)); if (call_finish_visit) { TF_RETURN_IF_ERROR(visitor->FinishVisit(this)); } return Status::OK(); } // Explicit instantiations. template Status HloInstruction::Accept(DfsHloVisitor*, bool, bool); template Status HloInstruction::Accept(ConstDfsHloVisitor*, bool, bool); Status HloInstruction::AcceptWithOperandOrder( DfsHloVisitor* visitor, const CompareFunction& operand_order, bool call_finish_visit) { VLOG(2) << "HloInstruction::AcceptWithOperandOrder(%" << name() << ")"; InternalCompareFunction func = [&operand_order]( std::pair<int, const HloInstruction*> a, std::pair<int, const HloInstruction*> b) { // Call the client's comparison function on the actual HloInstruction* // objects (ignoring the internal ids we also have in our stack entries) return operand_order(a.second, b.second); }; TF_RETURN_IF_ERROR(PostOrderDFS(this, visitor, &func, /*ignore_control_predecessors=*/false)); if (call_finish_visit) { VLOG(3) << "HloInstruction::AcceptWithOperandOrder BEFORE FINISH VISIT"; TF_RETURN_IF_ERROR(visitor->FinishVisit(this)); VLOG(3) << "HloInstruction::AcceptWithOperandOrder AFTER FINISH VISIT"; } VLOG(2) << "HloInstruction::AcceptWithOperandOrder EXIT"; return Status::OK(); } const Shape& HloInstruction::shape() const { return shape_; } std::vector<int64> HloInstruction::OperandIndices( const HloInstruction* operand) const { std::vector<int64> result; for (int64 i = 0; i < operand_count(); ++i) { if (this->operand(i) == operand) { result.push_back(i); } } return result; } bool HloInstruction::IsElementwiseBinary() const { return IsElementwise() && operand_count() == 2; } bool HloInstruction::IsElementwise() const { return IsElementwiseImpl(absl::nullopt); } bool HloInstruction::IsElementwiseOnOperand(int64 operand_idx) const { return IsElementwiseImpl(operand_idx); } // A helper class for memoized, recursive computation of HloOpcode::kFusion // in HloInstruction::OperandElementUse below. class HloInstruction::FusionReusesParamElements { public: using UseKind = HloInstruction::UseKind; // We could rather iterate backwards through fused_instructions_ here, as it // is in reverse postorder, and compute whether each fused instruction reuses // the value of this parameter, which would save stack space but not allow us // to finish early if we find a reuse. static UseKind Compute(int64 i, const HloInstruction& hlo) { absl::flat_hash_map<const HloInstruction*, UseKind> memoization_cache; return ComputeInternal(i, hlo, &memoization_cache); } private: static UseKind ComputeInternal( int64 i, const HloInstruction& hlo, absl::flat_hash_map<const HloInstruction*, UseKind>* cache) { if (auto hlo_param = DynCast<HloParameterInstruction>(&hlo)) { if (hlo_param->parameter_number() == i) { return UseKind::kUse; } } auto p = cache->emplace(&hlo, UseKind::kNoUse); auto value_it = p.first; const bool key_is_new = p.second; if (key_is_new) { for (int64 j = 0; j < hlo.operands_.size(); ++j) { UseKind old_val = value_it->second; // The next operation invalidates iterators. UseKind new_val = Fold(old_val, FoldUseMandatory(hlo.OperandElementUse(j), ComputeInternal(i, *hlo.operand(j), cache))); // Re-acquire the iterator. We could work harder to do this only if // absolutely necessary, but this code is not hot enough to warrant // that. value_it = cache->find(&hlo); value_it->second = new_val; } } return value_it->second; } // Combines two UseKinds. // // This is the min operation on the lattice // // kReuse < kUse < kNoUse. // // Two kUses uses which have different permutations count as kReuse. static UseKind Fold(UseKind a, UseKind b) { // Without loss of generality, let `b` be the operation with the larger use // kind. if (b.kind < a.kind) { std::swap(a, b); } // If the kinds are different, return the smaller one, namely `a`. if (a.kind != b.kind) { return a; } // If the kinds are both kUse, check that they're the same permutation. if (a.kind == UseKind::kUse && b.kind == UseKind::kUse && a.permutation_instr != b.permutation_instr) { return UseKind::kReuse; } return a; // They're the same. } // Combines two UseKinds differently than Fold(). // // This is the min operation on the lattice // // kNoUse < kReuse < kUse. // // If `a` and `b` are both kUse and one has a non-null permutation // instruction, returns kUse with that permutation. OTOH if both have // different, non-null permutation instructions, returns kReuse. // // You can think of this sort of as a conjunction, whereas Fold is sort of a // disjunction. FoldUseMandatory() says "no use" if either input isn't used, // whereas Fold() would say "use". static UseKind FoldUseMandatory(UseKind a, UseKind b) { if (a.kind == UseKind::kNoUse || b.kind == UseKind::kNoUse) { return UseKind::kNoUse; } if (a.kind == UseKind::kReuse || b.kind == UseKind::kReuse) { return UseKind::kReuse; } if (a.permutation_instr == b.permutation_instr) { return a; // They're the same. } if (b.permutation_instr == nullptr) { return a; } if (a.permutation_instr == nullptr) { return b; } return UseKind::kReuse; } }; HloInstruction::UseKind HloInstruction::OperandElementUse( int64 operand_num) const { switch (opcode_) { case HloOpcode::kBitcast: // A bitcast that only adds or removes degenerate (i.e. size 1) dimensions // doesn't permute its elements, so it counts as a plain, non-permuting // use. return ShapeUtil::DropDegenerateDimensions(shape()) == ShapeUtil::DropDegenerateDimensions(operand(0)->shape()) ? UseKind::kUse : UseKind::Permuting(this); case HloOpcode::kConcatenate: case HloOpcode::kReshape: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kTranspose: return UseKind::Permuting(this); case HloOpcode::kPad: // Pad reuses the padding value but not the padded array elements. return operand_num > 0 ? UseKind::kReuse : UseKind::Permuting(this); case HloOpcode::kReduce: // Reduce reuses the init values but not the operand array elements. return operand_num >= Cast<HloReduceInstruction>(this)->input_count() ? UseKind::kReuse : UseKind::Permuting(this); case HloOpcode::kFusion: // Uses the memoizing, recursive computation defined above. return FusionReusesParamElements::Compute(operand_num, *fused_expression_root()); case HloOpcode::kDot: // Matrix-vector dots do not reuse the matrix operand. if (shape().dimensions_size() <= 1) { if ((operand_num == 0 && operand(1)->shape().rank() <= 1) || (operand_num == 1 && operand(0)->shape().rank() <= 1)) { return UseKind::kUse; } } return UseKind::kReuse; case HloOpcode::kDynamicUpdateSlice: // Dynamic-update-slice reuses only start_indices. if (operand_num == 0 || operand_num == 1) { return UseKind::kUse; } return UseKind::kReuse; case HloOpcode::kGather: // Gather reads its indices in a linear fashion, and it permutes the // vector it's gathering from. return operand_num == 0 ? UseKind::kUse : UseKind::Permuting(this); default: return IsElementwise() ? UseKind::kUse : UseKind::kReuse; } } std::tuple<bool, std::vector<int64>, std::vector<int64>> HloInstruction::ReshapeMerelyInsertsOrDeletes1SizedDimensions() const { if (HloOpcode::kReshape != opcode_) { return std::make_tuple(false, std::vector<int64>(), std::vector<int64>()); } return ShapeUtil::InsertedOrDeleted1SizedDimensions(operand(0)->shape_, shape_); } string ToString(HloInstruction::FusionKind kind) { switch (kind) { case HloInstruction::FusionKind::kLoop: return "kLoop"; case HloInstruction::FusionKind::kInput: return "kInput"; case HloInstruction::FusionKind::kOutput: return "kOutput"; case HloInstruction::FusionKind::kCustom: return "kCustom"; } } StatusOr<HloInstruction::FusionKind> StringToFusionKind( const string& kind_name) { if (kind_name == "kLoop") { return HloInstruction::FusionKind::kLoop; } if (kind_name == "kInput") { return HloInstruction::FusionKind::kInput; } if (kind_name == "kOutput") { return HloInstruction::FusionKind::kOutput; } if (kind_name == "kCustom") { return HloInstruction::FusionKind::kCustom; } return InvalidArgument("Unknown fusion kind: %s", kind_name); } string PaddingConfigToString(const PaddingConfig& padding) { bool has_interior_padding = absl::c_any_of(padding.dimensions(), [](const PaddingConfig::PaddingConfigDimension& dim) { return dim.interior_padding() != 0; }); return StrJoin( padding.dimensions(), "x", [&](string* out, const PaddingConfig::PaddingConfigDimension& dim) { StrAppend( out, dim.edge_padding_low(), "_", dim.edge_padding_high(), has_interior_padding ? StrCat("_", dim.interior_padding()) : ""); }); } string OpMetadataToString(const OpMetadata& metadata) { std::vector<string> result; if (!metadata.op_type().empty()) { result.push_back(StrCat("op_type=\"", CEscape(metadata.op_type()), "\"")); } if (!metadata.op_name().empty()) { result.push_back(StrCat("op_name=\"", CEscape(metadata.op_name()), "\"")); } if (!metadata.source_file().empty()) { result.push_back( StrCat("source_file=\"", CEscape(metadata.source_file()), "\"")); } if (metadata.source_line() != 0) { result.push_back(StrCat("source_line=", metadata.source_line())); } return StrJoin(result, " "); } string RandomDistributionToString(const RandomDistribution& distribution) { return absl::AsciiStrToLower(RandomDistribution_Name(distribution)); } string PrecisionToString(const PrecisionConfig::Precision& precision) { return absl::AsciiStrToLower(PrecisionConfig::Precision_Name(precision)); } string ConvolutionDimensionNumbersToString( const ConvolutionDimensionNumbers& dnums) { // lhs_dims[i] is the symbol of the logical dimension i for the lhs // operand. E.g. if batch has dimension number 2, then lhs_dims[2] == "b". std::vector<string> lhs_dims(2 + dnums.input_spatial_dimensions().size()); lhs_dims[dnums.input_batch_dimension()] = 'b'; lhs_dims[dnums.input_feature_dimension()] = 'f'; for (int64 i = 0; i < dnums.input_spatial_dimensions().size(); ++i) { lhs_dims[dnums.input_spatial_dimensions(i)] = StrCat(i); } std::vector<string> rhs_dims(2 + dnums.kernel_spatial_dimensions().size()); rhs_dims[dnums.kernel_input_feature_dimension()] = "i"; rhs_dims[dnums.kernel_output_feature_dimension()] = "o"; for (int64 i = 0; i < dnums.kernel_spatial_dimensions().size(); ++i) { rhs_dims[dnums.kernel_spatial_dimensions(i)] = StrCat(i); } std::vector<string> output_dims(2 + dnums.output_spatial_dimensions().size()); output_dims[dnums.output_batch_dimension()] = 'b'; output_dims[dnums.output_feature_dimension()] = 'f'; for (int64 i = 0; i < dnums.output_spatial_dimensions().size(); ++i) { output_dims[dnums.output_spatial_dimensions(i)] = StrCat(i); } return StrCat(StrJoin(lhs_dims, ""), "_", StrJoin(rhs_dims, ""), "->", StrJoin(output_dims, "")); } string ReplicaGroupsToString(const std::vector<ReplicaGroup>& replica_groups) { std::vector<string> replica_group_str; replica_group_str.reserve(replica_groups.size()); for (const ReplicaGroup& group : replica_groups) { replica_group_str.push_back( StrCat("{", StrJoin(group.replica_ids(), ","), "}")); } return StrCat("{", StrJoin(replica_group_str, ","), "}"); } StatusOr<RandomDistribution> StringToRandomDistribution(const string& name) { static std::unordered_map<string, RandomDistribution>* map = [] { static auto* map = new std::unordered_map<string, RandomDistribution>; for (int i = 0; i < RandomDistribution_ARRAYSIZE; i++) { if (RandomDistribution_IsValid(i)) { auto value = static_cast<RandomDistribution>(i); (*map)[RandomDistributionToString(value)] = value; } } return map; }(); auto found = map->find(absl::AsciiStrToLower(name)); if (found == map->end()) { return InvalidArgument("Unknown distribution"); } return found->second; } StatusOr<PrecisionConfig::Precision> StringToPrecision(const string& name) { static std::unordered_map<string, PrecisionConfig::Precision>* map = [] { static auto* map = new std::unordered_map<string, PrecisionConfig::Precision>; for (int i = 0; i < PrecisionConfig::Precision_ARRAYSIZE; i++) { if (PrecisionConfig::Precision_IsValid(i)) { auto value = static_cast<PrecisionConfig::Precision>(i); (*map)[PrecisionToString(value)] = value; } } return map; }(); auto found = map->find(absl::AsciiStrToLower(name)); if (found == map->end()) { return InvalidArgument("Unknown distribution"); } return found->second; } std::ostream& operator<<(std::ostream& os, HloInstruction::FusionKind kind) { return os << ToString(kind); } bool HloPtrComparator::operator()(const HloInstruction* const& lhs, const HloInstruction* const& rhs) const { if (rhs == nullptr) { // Nothing compares less than nullptr. return false; } if (lhs == nullptr) { return true; } auto lhs_module = lhs->GetModule(); auto rhs_module = rhs->GetModule(); CHECK((lhs_module == nullptr && rhs_module == nullptr) || (lhs_module != nullptr && rhs_module != nullptr)); if (lhs_module != nullptr && lhs_module->unique_id() != rhs_module->unique_id()) { return lhs_module->unique_id() < rhs_module->unique_id(); } return lhs->unique_id() < rhs->unique_id(); } bool HloInstruction::CouldBeBitcast() const { switch (opcode_) { case HloOpcode::kTranspose: return true; case HloOpcode::kReshape: return std::get<0>(ReshapeMerelyInsertsOrDeletes1SizedDimensions()); default: return false; } } Status HloInstruction::GetBackendConfigInternal( tensorflow::protobuf::Message* proto) const { proto->Clear(); // Empty string does not parse as valid JSON, but it's a valid backend config, // corresponding to the empty proto. if (backend_config_.empty()) { return Status::OK(); } return tensorflow::HumanReadableJsonToProto(backend_config_, proto); } Status HloInstruction::set_backend_config( const tensorflow::protobuf::Message& proto) { TF_ASSIGN_OR_RETURN(backend_config_, BackendConfigToRawString(proto)); return Status::OK(); } /* static */ StatusOr<string> HloInstruction::BackendConfigToRawString( const tensorflow::protobuf::Message& proto) { string ret; // Pass ignore_accuracy_loss = true because estimated_cycles field can be // INT64_MAX. If ignore_accuracy_loss = false and estimated_cycles = // INT64_MAX, JsonFormat will return an error status, although there is no // accuracy loss for int64. TF_RETURN_IF_ERROR(tensorflow::ProtoToHumanReadableJson( proto, &ret, /*ignore_accuracy_loss=*/true)); return ret; } const PrecisionConfig& HloInstruction::precision_config() const { if (auto* convolution = DynCast<HloConvolutionInstruction>(this)) { return convolution->precision_config(); } if (auto* dot = DynCast<HloDotInstruction>(this)) { return dot->precision_config(); } LOG(FATAL) << "Unimplemented method."; } PrecisionConfig* HloInstruction::mutable_precision_config() { if (auto* convolution = DynCast<HloConvolutionInstruction>(this)) { return convolution->mutable_precision_config(); } if (auto* dot = DynCast<HloDotInstruction>(this)) { return dot->mutable_precision_config(); } LOG(FATAL) << "Unimplemented method."; } HloModule* HloInstruction::GetModule() const { if (parent_) { return parent_->parent(); } return nullptr; } void HloInstruction::UniquifyName(NameUniquer* name_uniquer) { string parent_str = parent() == nullptr ? "noparent" : parent()->name(); name_ = name_uniquer->GetUniqueName(name_); } void HloInstruction::set_outer_dimension_partitions( const std::vector<int64>& outer_dimension_partitions) { outer_dimension_partitions_ = outer_dimension_partitions; } // TODO(b/80131774): Remove these temporary methods after transition. int64 HloInstruction::feature_index() const { return Cast<HloBatchNormInstruction>(this)->feature_index(); } float HloInstruction::epsilon() const { return Cast<HloBatchNormInstruction>(this)->epsilon(); } FftType HloInstruction::fft_type() const { return Cast<HloFftInstruction>(this)->fft_type(); } const std::vector<int64>& HloInstruction::fft_length() const { return Cast<HloFftInstruction>(this)->fft_length(); } int64 HloInstruction::concatenate_dimension() const { return Cast<HloConcatenateInstruction>(this)->concatenate_dimension(); } int64 HloInstruction::dimension() const { return Cast<HloGetDimensionSizeInstruction>(this)->dimension(); } int64 HloInstruction::inferred_dimension() const { return Cast<HloReshapeInstruction>(this)->inferred_dimension(); } bool HloInstruction::IsRank2Transpose() const { auto transpose = DynCast<HloTransposeInstruction>(this); return transpose != nullptr && transpose->IsRank2Transpose(); } int64 HloInstruction::slice_starts(int64 dimension) const { return Cast<HloSliceInstruction>(this)->slice_starts(dimension); } const std::vector<int64>& HloInstruction::slice_starts() const { return Cast<HloSliceInstruction>(this)->slice_starts(); } int64 HloInstruction::slice_limits(int64 dimension) const { return Cast<HloSliceInstruction>(this)->slice_limits(dimension); } const std::vector<int64>& HloInstruction::slice_limits() const { return Cast<HloSliceInstruction>(this)->slice_limits(); } int64 HloInstruction::slice_strides(int64 dimension) const { return Cast<HloSliceInstruction>(this)->slice_strides(dimension); } const std::vector<int64>& HloInstruction::slice_strides() const { return Cast<HloSliceInstruction>(this)->slice_strides(); } const Literal& HloInstruction::literal() const { return Cast<HloConstantInstruction>(this)->literal(); } bool HloInstruction::IsConstant() const { return DynCast<HloConstantInstruction>(this) != nullptr; } void HloInstruction::RelayoutConstant(const Layout& new_layout, const ShapeIndex& shape_index) { Cast<HloConstantInstruction>(this)->RelayoutConstant(new_layout, shape_index); } string HloInstruction::TracingTag() const { return Cast<HloTraceInstruction>(this)->TracingTag(); } HloInstruction* HloInstruction::AddFusionOperand(HloInstruction* new_operand) { return Cast<HloFusionInstruction>(this)->AddFusionOperand(new_operand); } // Delegates to HloFusionInstruction::MergeFusionInstruction. void HloInstruction::MergeFusionInstruction( HloInstruction* instruction_to_merge) { return Cast<HloFusionInstruction>(this)->MergeFusionInstruction( Cast<HloFusionInstruction>(instruction_to_merge)); } // Delegates to HloFusionInstruction::MergeFusionInstructionIntoMultiOutput. void HloInstruction::MergeFusionInstructionIntoMultiOutput( HloInstruction* instruction_to_merge) { return Cast<HloFusionInstruction>(this) ->MergeFusionInstructionIntoMultiOutput( Cast<HloFusionInstruction>(instruction_to_merge)); } HloInstruction* HloInstruction::FuseInstruction( HloInstruction* instruction_to_fuse) { return Cast<HloFusionInstruction>(this)->FuseInstruction(instruction_to_fuse); } HloInstruction* HloInstruction::FuseInstructionIntoMultiOutput( HloInstruction* instruction_to_fuse) { return Cast<HloFusionInstruction>(this)->FuseInstructionIntoMultiOutput( instruction_to_fuse); } HloComputation* HloInstruction::fused_instructions_computation() const { return Cast<HloFusionInstruction>(this)->fused_instructions_computation(); } HloInstruction* HloInstruction::fused_expression_root() const { return Cast<HloFusionInstruction>(this)->fused_expression_root(); } const tensorflow::gtl::iterator_range<UnwrappingIterator< std::list<std::unique_ptr<HloInstruction>>::const_iterator>> HloInstruction::fused_instructions() const { return Cast<HloFusionInstruction>(this)->fused_instructions(); } const tensorflow::gtl::iterator_range< UnwrappingIterator<std::list<std::unique_ptr<HloInstruction>>::iterator>> HloInstruction::fused_instructions() { return Cast<HloFusionInstruction>(this)->fused_instructions(); } int64 HloInstruction::fused_instruction_count() const { return Cast<HloFusionInstruction>(this)->fused_instruction_count(); } HloInstruction* HloInstruction::fused_parameter(int64 parameter_number) const { return Cast<HloFusionInstruction>(this)->fused_parameter(parameter_number); } const std::vector<HloInstruction*>& HloInstruction::fused_parameters() const { return Cast<HloFusionInstruction>(this)->fused_parameters(); } const bool HloInstruction::IsMultiOutputFusion() const { const HloFusionInstruction* fusion = DynCast<HloFusionInstruction>(this); return fusion != nullptr && fusion->IsMultiOutputFusion(); } HloInstruction::FusionKind HloInstruction::fusion_kind() const { return Cast<HloFusionInstruction>(this)->fusion_kind(); } void HloInstruction::set_fusion_kind(FusionKind kind) { return Cast<HloFusionInstruction>(this)->set_fusion_kind(kind); } RandomDistribution HloInstruction::random_distribution() const { return Cast<HloRngInstruction>(this)->random_distribution(); } int64 HloInstruction::parameter_number() const { return Cast<HloParameterInstruction>(this)->parameter_number(); } void HloInstruction::set_parameter_replicated_at_leaf_buffers( absl::Span<const bool> parameter_replicated_at_leaf_buffers) { return Cast<HloParameterInstruction>(this) ->set_parameter_replicated_at_leaf_buffers( parameter_replicated_at_leaf_buffers); } void HloInstruction::set_parameter_replicated_at_leaf_buffers( const std::vector<bool>& parameter_replicated_at_leaf_buffers) { return Cast<HloParameterInstruction>(this) ->set_parameter_replicated_at_leaf_buffers( parameter_replicated_at_leaf_buffers); } const absl::optional<std::vector<bool>>& HloInstruction::parameter_replicated_at_leaf_buffers() const { return Cast<HloParameterInstruction>(this) ->parameter_replicated_at_leaf_buffers(); } int64 HloInstruction::tuple_index() const { return Cast<HloGetTupleElementInstruction>(this)->tuple_index(); } void HloInstruction::set_tuple_index(int64 new_tuple_index) { return Cast<HloGetTupleElementInstruction>(this)->set_tuple_index( new_tuple_index); } int32 HloInstruction::exponent_bits() const { return Cast<HloReducePrecisionInstruction>(this)->exponent_bits(); } int32 HloInstruction::mantissa_bits() const { return Cast<HloReducePrecisionInstruction>(this)->mantissa_bits(); } string HloInstruction::infeed_config() const { return Cast<HloInfeedInstruction>(this)->infeed_config(); } void HloInstruction::set_infeed_config(const string& config) { return Cast<HloInfeedInstruction>(this)->set_infeed_config(config); } const Shape& HloInstruction::outfeed_shape() const { return Cast<HloOutfeedInstruction>(this)->outfeed_shape(); } const string& HloInstruction::outfeed_config() const { return Cast<HloOutfeedInstruction>(this)->outfeed_config(); } const std::vector<ReplicaGroup>& HloInstruction::replica_groups() const { return Cast<HloCollectiveInstruction>(this)->replica_groups(); } const std::vector<std::pair<int64, int64>>& HloInstruction::source_target_pairs() const { return Cast<HloCollectivePermuteInstruction>(this)->source_target_pairs(); } absl::optional<int64> HloInstruction::channel_id() const { return Cast<HloChannelInstruction>(this)->channel_id(); } void HloInstruction::set_channel_id(const absl::optional<int64>& channel_id) { return Cast<HloChannelInstruction>(this)->set_channel_id(channel_id); } const ConvolutionDimensionNumbers& HloInstruction::convolution_dimension_numbers() const { if (auto convolution = DynCast<HloConvolutionInstruction>(this)) { return convolution->convolution_dimension_numbers(); } if (auto custom_call = DynCast<HloCustomCallInstruction>(this)) { return custom_call->convolution_dimension_numbers(); } LOG(FATAL) << "Unimplemented method."; } void HloInstruction::set_convolution_dimension_numbers( const ConvolutionDimensionNumbers& dnums) { if (auto convolution = DynCast<HloConvolutionInstruction>(this)) { convolution->set_convolution_dimension_numbers(dnums); } else if (auto custom_call = DynCast<HloCustomCallInstruction>(this)) { custom_call->set_convolution_dimension_numbers(dnums); } else { LOG(FATAL) << "Unimplemented method."; } } int64 HloInstruction::feature_group_count() const { if (auto convolution = DynCast<HloConvolutionInstruction>(this)) { return convolution->feature_group_count(); } return Cast<HloCustomCallInstruction>(this)->feature_group_count(); } void HloInstruction::set_feature_group_count(int64 feature_group_count) { Cast<HloCustomCallInstruction>(this)->set_feature_group_count( feature_group_count); } int64 HloInstruction::batch_group_count() const { if (auto convolution = DynCast<HloConvolutionInstruction>(this)) { return convolution->batch_group_count(); } return Cast<HloCustomCallInstruction>(this)->batch_group_count(); } void HloInstruction::set_batch_group_count(int64 batch_group_count) { Cast<HloCustomCallInstruction>(this)->set_batch_group_count( batch_group_count); } HloComputation* HloInstruction::select() const { return Cast<HloSelectAndScatterInstruction>(this)->select(); } HloComputation* HloInstruction::scatter() const { return Cast<HloSelectAndScatterInstruction>(this)->scatter(); } void HloInstruction::set_select(HloComputation* computation) { return Cast<HloSelectAndScatterInstruction>(this)->set_select(computation); } void HloInstruction::set_scatter(HloComputation* computation) { return Cast<HloSelectAndScatterInstruction>(this)->set_scatter(computation); } const string& HloInstruction::custom_call_target() const { return Cast<HloCustomCallInstruction>(this)->custom_call_target(); } const PaddingConfig& HloInstruction::padding_config() const { return Cast<HloPadInstruction>(this)->padding_config(); } int64 HloInstruction::slice_sizes(int64 dimension) const { return Cast<HloDynamicSliceInstruction>(this)->slice_sizes(dimension); } const std::vector<int64>& HloInstruction::dynamic_slice_sizes() const { return Cast<HloDynamicSliceInstruction>(this)->dynamic_slice_sizes(); } const GatherDimensionNumbers& HloInstruction::gather_dimension_numbers() const { return Cast<HloGatherInstruction>(this)->gather_dimension_numbers(); } absl::Span<const int64> HloInstruction::gather_slice_sizes() const { return Cast<HloGatherInstruction>(this)->gather_slice_sizes(); } const ScatterDimensionNumbers& HloInstruction::scatter_dimension_numbers() const { return Cast<HloScatterInstruction>(this)->scatter_dimension_numbers(); } const DotDimensionNumbers& HloInstruction::dot_dimension_numbers() const { return Cast<HloDotInstruction>(this)->dot_dimension_numbers(); } const DomainMetadata& HloInstruction::operand_side_metadata() const { return Cast<HloDomainInstruction>(this)->operand_side_metadata(); } const DomainMetadata& HloInstruction::user_side_metadata() const { return Cast<HloDomainInstruction>(this)->user_side_metadata(); } ComparisonDirection HloInstruction::comparison_direction() const { return Cast<HloCompareInstruction>(this)->direction(); } const TriangularSolveOptions& HloInstruction::triangular_solve_options() const { return Cast<HloTriangularSolveInstruction>(this)->triangular_solve_options(); } const CholeskyOptions& HloInstruction::cholesky_options() const { return Cast<HloCholeskyInstruction>(this)->cholesky_options(); } } // namespace xla
[ "v-grniki@microsoft.com" ]
v-grniki@microsoft.com
c0815807a8e63c60bf6d54da7a462ba7c892dff6
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/net/http/http_proxy_client_socket_wrapper.h
3d0c27f741f6ee1a92a12708414c79eefa9e30c2
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
7,281
h
// Copyright 2015 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 NET_HTTP_HTTP_PROXY_CLIENT_SOCKET_WRAPPER_H_ #define NET_HTTP_HTTP_PROXY_CLIENT_SOCKET_WRAPPER_H_ #include <stdint.h> #include <memory> #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "net/base/completion_callback.h" #include "net/base/host_port_pair.h" #include "net/base/load_timing_info.h" #include "net/http/http_auth_controller.h" #include "net/http/proxy_client_socket.h" #include "net/log/net_log_with_source.h" #include "net/socket/next_proto.h" #include "net/socket/ssl_client_socket.h" #include "net/socket/ssl_client_socket_pool.h" #include "net/socket/transport_client_socket_pool.h" #include "net/spdy/chromium/spdy_session.h" namespace net { class ClientSocketHandle; class IOBuffer; class HttpAuthCache; class HttpResponseInfo; class HttpStream; class IOBuffer; class ProxyDelegate; class SpdySessionPool; class SSLClientSocketPool; class TransportClientSocketPool; // Class that establishes connections by calling into the lower layer socket // pools, creates a HttpProxyClientSocket / SpdyProxyClientSocket, and then // wraps the resulting socket. // // This class is needed to handle auth state across multiple connection. On // auth challenge, this class retains auth state in its AuthController, and can // either send the auth response to the old connection, or establish a new // connection and send the response there. // // TODO(mmenke): Ideally, we'd have a central location store auth state across // multiple connections to the same server instead. class HttpProxyClientSocketWrapper : public ProxyClientSocket { public: HttpProxyClientSocketWrapper( const std::string& group_name, RequestPriority priority, ClientSocketPool::RespectLimits respect_limits, base::TimeDelta connect_timeout_duration, base::TimeDelta proxy_negotiation_timeout_duration, TransportClientSocketPool* transport_pool, SSLClientSocketPool* ssl_pool, const scoped_refptr<TransportSocketParams>& transport_params, const scoped_refptr<SSLSocketParams>& ssl_params, const std::string& user_agent, const HostPortPair& endpoint, HttpAuthCache* http_auth_cache, HttpAuthHandlerFactory* http_auth_handler_factory, SpdySessionPool* spdy_session_pool, bool tunnel, ProxyDelegate* proxy_delegate, const NetLogWithSource& net_log); // On destruction Disconnect() is called. ~HttpProxyClientSocketWrapper() override; // Returns load state while establishing a connection. Returns // LOAD_STATE_IDLE at other times. LoadState GetConnectLoadState() const; std::unique_ptr<HttpResponseInfo> GetAdditionalErrorState(); // ProxyClientSocket implementation. const HttpResponseInfo* GetConnectResponseInfo() const override; std::unique_ptr<HttpStream> CreateConnectResponseStream() override; int RestartWithAuth(const CompletionCallback& callback) override; const scoped_refptr<HttpAuthController>& GetAuthController() const override; bool IsUsingSpdy() const override; NextProto GetProxyNegotiatedProtocol() const override; // StreamSocket implementation. int Connect(const CompletionCallback& callback) override; void Disconnect() override; bool IsConnected() const override; bool IsConnectedAndIdle() const override; const NetLogWithSource& NetLog() const override; void SetSubresourceSpeculation() override; void SetOmniboxSpeculation() override; bool WasEverUsed() const override; bool WasAlpnNegotiated() const override; NextProto GetNegotiatedProtocol() const override; bool GetSSLInfo(SSLInfo* ssl_info) override; void GetConnectionAttempts(ConnectionAttempts* out) const override; void ClearConnectionAttempts() override; void AddConnectionAttempts(const ConnectionAttempts& attempts) override; int64_t GetTotalReceivedBytes() const override; // Socket implementation. int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback) override; int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback) override; int SetReceiveBufferSize(int32_t size) override; int SetSendBufferSize(int32_t size) override; int GetPeerAddress(IPEndPoint* address) const override; int GetLocalAddress(IPEndPoint* address) const override; private: enum State { STATE_BEGIN_CONNECT, STATE_TCP_CONNECT, STATE_TCP_CONNECT_COMPLETE, STATE_SSL_CONNECT, STATE_SSL_CONNECT_COMPLETE, STATE_HTTP_PROXY_CONNECT, STATE_HTTP_PROXY_CONNECT_COMPLETE, STATE_SPDY_PROXY_CREATE_STREAM, STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE, STATE_SPDY_PROXY_CONNECT_COMPLETE, STATE_RESTART_WITH_AUTH, STATE_RESTART_WITH_AUTH_COMPLETE, STATE_NONE, }; void OnIOComplete(int result); // Runs the state transition loop. int DoLoop(int result); // Determine if need to go through TCP or SSL path. int DoBeginConnect(); // Connecting to HTTP Proxy int DoTransportConnect(); int DoTransportConnectComplete(int result); // Connecting to HTTPS Proxy int DoSSLConnect(); int DoSSLConnectComplete(int result); int DoHttpProxyConnect(); int DoHttpProxyConnectComplete(int result); int DoSpdyProxyCreateStream(); int DoSpdyProxyCreateStreamComplete(int result); int DoRestartWithAuth(); int DoRestartWithAuthComplete(int result); void NotifyProxyDelegateOfCompletion(int result); void SetConnectTimer(base::TimeDelta duration); void ConnectTimeout(); const HostResolver::RequestInfo& GetDestination(); State next_state_; const std::string group_name_; RequestPriority priority_; ClientSocketPool::RespectLimits respect_limits_; const base::TimeDelta connect_timeout_duration_; const base::TimeDelta proxy_negotiation_timeout_duration_; TransportClientSocketPool* const transport_pool_; SSLClientSocketPool* const ssl_pool_; const scoped_refptr<TransportSocketParams> transport_params_; const scoped_refptr<SSLSocketParams> ssl_params_; const std::string user_agent_; const HostPortPair endpoint_; SpdySessionPool* const spdy_session_pool_; bool has_restarted_; const bool tunnel_; ProxyDelegate* const proxy_delegate_; bool using_spdy_; NextProto negotiated_protocol_; std::unique_ptr<HttpResponseInfo> error_response_info_; std::unique_ptr<ClientSocketHandle> transport_socket_handle_; std::unique_ptr<ProxyClientSocket> transport_socket_; // Called when a connection is established. Also used when restarting with // AUTH, which will invoke this when ready to restart, after reconnecting // if necessary. CompletionCallback connect_callback_; SpdyStreamRequest spdy_stream_request_; scoped_refptr<HttpAuthController> http_auth_controller_; NetLogWithSource net_log_; base::OneShotTimer connect_timer_; // Time when the connection to the proxy was started. base::TimeTicks connect_start_time_; DISALLOW_COPY_AND_ASSIGN(HttpProxyClientSocketWrapper); }; } // namespace net #endif // NET_HTTP_HTTP_PROXY_CLIENT_SOCKET_WRAPPER_H_
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
69e6b5607df8ab04cb5284e04d098cdb4a7bc1d5
96ab18b237681c5c01bf3d0fce187740e5038bb8
/ asdk/Source2/ATPManager/include/AlgoEngine/AbstractAlgo.h
8a68a7580ed0028b5c604cf2bee797f9a45c30b8
[]
no_license
radtek/asdk
43fd7bfeb31028ef6392be4117e5de4c908af8e5
4f9a3bd80f6cc58db02a4ed0f67bc5ee03cedb01
refs/heads/master
2020-06-09T04:28:16.485493
2012-05-10T10:30:00
2012-05-10T10:30:00
null
0
0
null
null
null
null
GB18030
C++
false
false
3,070
h
/** * @copyright 深圳市创真科技有限公司 * @system 宏汇算法交易平台(ATP) * @brief 算法执行类 * @author 李伟 * @histroy ------------------------------------------------------------- 日期 作者 修改说明 2010-6-2 李伟 创建 ------------------------------------------------------------- */ #pragma once #ifndef __ABSTRACTALGO_H_ #define __ABSTRACTALGO_H_ #include "..\\include\\ATSvr\\OpenTDProtocol.h" #include "..\\include\\ATPSetting\\ATPLogger.h" class CTradingHandler_Futures; class CTradingHandler_Security; #include "AlgoSession.h" /** 算法执行的接象类 写义了两个接口 #See Begin #See End 算法需实现上述函数,以完成实际算法的执行. */ class AFX_EXT_CLASS CAbstractAlgo : public CObject { DECLARE_DYNCREATE(CAbstractAlgo); public: /** 任务总数 */ virtual UINT GetTotal(){ return m_nTotal;} /** 己任务总数 */ virtual UINT GetFinish(){return m_nFinish;} /** 取状态 */ virtual CString GetStatus(){return m_szStatus;} /** 取标识名 */ virtual CString GetRunningAlgoName(){return m_szName;} public: /** 算法名称 */ char m_szName[64]; /** 开始时间 */ UINT m_nBeginTime; /** 下单次数 */ UINT m_nMakeOrderTimes; /** 己完成数. */ UINT m_nFinish; /** 总数 */ UINT m_nTotal; /** 状态说明 */ char m_szStatus[64]; public: CAbstractAlgo(); virtual ~CAbstractAlgo(); /** 算法初始化. @param pParamters 算法参数值首地址. @param nParams 参数个数 @param strReason 如果初始化失败时,或者参数不正确时,返时出错原因。 @return 返回是否初始化成功,如果初始化成功,算法交易引擎将进一步调用Run函数. */ virtual bool Init(ATP_ALGOPARAM_VALUE* pParamters,int nParams,CString& strReason); /** 具体执行算法,该函数返回后,表示算法退出。算法操作引擎会执行资源的回收工作。 @return 返回退出代码。 */ virtual int Run(){return 0;} /** * 强行终止算法下单. * 算法应重写此函数,以实现算法的终止运行.结束算法运算,并退出Run函数。 * @return 返回退出代码. @See Run */ virtual int Kill(){return 0;} protected: CAlgoSession* m_pAlgoSession; /* 交易私有日志. */ CATPLogger* m_pPrivateLog; /** 框架在,算法Run之前调用, 如果是股同时将其值传递到成员变量. */ virtual void BeforRun(CAlgoSession* pSession, CATPLogger* pPrivateLog, CTradingHandler_Security* pHandlerSec, CTradingHandler_Futures* pHandlerFut); /** 证券交易指针. */ CTradingHandler_Security* m_pTradingHeandleSec; /** 期货交易指针. */ CTradingHandler_Futures* m_pTradingHeandleFut; friend class CAlgoManager; friend class CWinThread_ExecAlgo; }; #endif //__ABSTRACTALGO_H_
[ "He.Reyter@gmail.com@195b811d-50ba-3ccd-8b31-a51a91d0a79c" ]
He.Reyter@gmail.com@195b811d-50ba-3ccd-8b31-a51a91d0a79c
c3c44080ecac01ae1a6931b50bff95dc281bd140
3762eafb1544217ca71081ec7215d71d6e1cc9e2
/Dynamic Programming/Dynamic Programming/1937.cpp
9acd9d11b71a0f923092d0b3060fbfa983073e01
[]
no_license
challenger71498/Algorithm
710f4a75d5adadb6bd555ae02c0c7974c3e77a77
09db61e56f7e657210dde91061ea218d4d09e41f
refs/heads/master
2020-12-20T02:43:33.965776
2020-02-03T17:03:09
2020-02-03T17:03:09
235,936,579
0
0
null
null
null
null
UTF-8
C++
false
false
1,187
cpp
#include <iostream> #include <deque> #include <algorithm> #include <climits> using namespace std; typedef pair<int, int> ii; int arr[502][502]; deque<ii> st; int len[502][502]; int n; void chk(int x, int y) { int v = arr[x][y]; int* l = &len[x][y]; if (v != arr[x + 1][y]) { *l = max(*l, len[x + 1][y]); } if (v != arr[x - 1][y]) { *l = max(*l, len[x - 1][y]); } if (v != arr[x][y + 1]) { *l = max(*l, len[x][y + 1]); } if (v != arr[x][y - 1]) { *l = max(*l, len[x][y - 1]); } *l += 1; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cin >> n; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { cin >> arr[i][j]; st.push_back({ i, j }); } } sort(st.begin(), st.end(), [](ii a, ii b) { return arr[a.first][a.second] > arr[b.first][b.second]; }); for (int i = 0; i < st.size(); ++i) { chk(st[i].first, st[i].second); /*for (int j = 1; j <= n; ++j) { for (int k = 1; k <= n; ++k) { cout << len[j][k] << ' '; } cout << '\n'; } cout << '\n';*/ } int maxi = INT_MIN; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { maxi = max(maxi, len[i][j]); } } cout << maxi << '\n'; }
[ "challenger71498@gmail.com" ]
challenger71498@gmail.com
60cffa182c05651c2455580d86d29d7afa6aaad6
f851cf2ca7644d8ad1c6690e167124c17d087f5e
/Personagem.cpp
ef9d6546c9902376b14663d14ead68822f8bd6df
[]
no_license
MateusMat/Elemantal_VS_Mal
a077de4aca8dc69ba966a5d1d74bb6d889bf85ac
0d161e8170b98550f1f3218fb561c6d3be1968de
refs/heads/master
2020-06-12T16:27:17.018211
2019-06-29T03:20:07
2019-06-29T03:20:07
194,358,782
0
0
null
null
null
null
UTF-8
C++
false
false
2,531
cpp
#include "Personagem.h" using namespace Personagens; Personagem::Personagem() { velocidadeX = 0.0; velocidadeY = 0.0; aceleracaoX = 0.0; aceleracaoY = 0.0; velMax = 0.0; inercia = 0.0; forcaPulo = 0.0; gravidade = 0.0; maxPulo = 0; contPulo = 0; contAnimacao = 0; olhandoDireita = true; } Personagem::~Personagem() { } void Personagem::movimentar() { } void Personagem::calcMovimentar() { velocidadeY += gravidade; velocidadeX += (aceleracaoX / inercia); velocidadeY += (aceleracaoY / inercia); if (velocidadeX > 0 && aceleracaoX == 0) velocidadeX -= 1 / inercia; else if (velocidadeX < 0 && aceleracaoX == 0) velocidadeX += 1 / inercia; if(velocidadeX > velMax) velocidadeX = velMax; else if (velocidadeX < -velMax) velocidadeX = - velMax; setPosX(getPosX() + velocidadeX); setPosY(getPosY() + velocidadeY); } void Personagem::setVelocidadeX (float vX) {velocidadeX = vX;} float Personagem::getVelocidadeX () {return velocidadeX;} void Personagem::setVelocidadeY (float vY) {velocidadeY = vY;} float Personagem::getVelocidadeY () {return velocidadeY;} void Personagem::setAceleracaoX (float aX) {aceleracaoX = aX;} float Personagem::getAceleracaoX () {return aceleracaoX;} void Personagem::setAceleracaoY (float aY) {aceleracaoY = aY;} float Personagem::getAceleracaoY () {return aceleracaoY;} void Personagem::setVelMax (float vm) {velMax = vm;} float Personagem::getVelMax () {return velMax;} void Personagem::setInercia (float in) {inercia = in;} float Personagem::getInercia () {return inercia;} void Personagem::setForcaPulo (float fp) {forcaPulo = fp;} float Personagem::getForcaPulo () {return forcaPulo;} void Personagem::setGravidade (float g) {gravidade = g;} float Personagem::getGravidade () {return gravidade;} void Personagem::setMaxPulo (int mP) {maxPulo = mP;} int Personagem::getMaxPulo () {return maxPulo;} void Personagem::setContPulo (int cP) {contPulo = cP;} int Personagem::getContPulo () {return contPulo;} void Personagem::setContAnimacao (int cA){contAnimacao = cA;} int Personagem::getContAnimacao () {return contAnimacao;} void Personagem::setOlhandoDireita (bool oD){olhandoDireita = oD;} bool Personagem::getOlhandoDireita () {return olhandoDireita;}
[ "noreply@github.com" ]
MateusMat.noreply@github.com
ab109e9dfe68883c5f8f7c36015e65a79171791d
7b6f2cf2b00f21e148662a2d7e2992aaad570bc6
/Planets.cpp
fbc224653ce52770d7062fd04bfc511202cb7325
[]
no_license
ScarGarak/cg15
794bd92c980c0e7f13897dff8b2ca100259e979a
d57abf67e6fcc29238d5e07053d14c34f9a85154
refs/heads/master
2020-04-06T04:48:10.104975
2015-07-16T19:53:56
2015-07-16T19:55:23
37,919,371
0
0
null
null
null
null
UTF-8
C++
false
false
2,370
cpp
/* * Planets.cpp * * Created on: 29.06.2015 * Author: Oliver Thummerer */ #include "Planets.hpp" #include <GLFW/glfw3.h> #include <stdlib.h> #include <stdio.h> #include <math.h> // constructor Planet::Planet() { } // deconstructor Planet::~Planet() { } // getter float Planet::getXPos() { return this->xPos; } float Planet::getYPos() { return this->yPos; } float Planet::getZPos() { return this->zPos; } double Planet::getSize() { return this->size; } // setter void Planet::setXPos(float xPos){ this->xPos = xPos; } void Planet::setYPos(float yPos){ this->yPos = yPos; } void Planet::setZPos(float zPos){ this->zPos = zPos; } // set the sphere color void Planet::setMaterialColor(int side, double r, double g, double b) { float amb[4], dif[4], spe[4]; int mat; dif[0] = r; dif[1] = g; dif[2] = b; for(int i = 0; i < 3; i++) { amb[i] = .1 * dif[i]; spe[i] = .5; } amb[3] = dif[3] = spe[3] = 1.0; switch(side){ case 1: mat = GL_FRONT; break; case 2: mat = GL_BACK; break; default: mat = GL_FRONT_AND_BACK; } glMaterialfv(mat, GL_AMBIENT, amb); glMaterialfv(mat, GL_DIFFUSE, dif); glMaterialfv(mat, GL_SPECULAR, spe); glMaterialf( mat, GL_SHININESS, 20); } // draw a sphere composed of triangles void Planet::draw(const Vec3& ctr, double r){ this->setMaterialColor(1,0,155,0); int i, j, n1 = 6, n2 = 12; Vec3 normal, v1; double a1, a1d = M_PI / n1, a2, a2d = M_PI / n2, s1, s2, c1, c2; glShadeModel(GL_SMOOTH); for(i = 0; i < n1; i++){ a1 = i * a1d; glBegin(GL_TRIANGLE_STRIP); for(j = 0; j <= n2; j++){ a2 = (j + .5 * (i % 2)) * 2 * a2d; s1 = sin(a1); c1 = cos(a1); s2 = sin(a2); c2 = cos(a2); normal = c1 * XVec3 + s1 * (c2 * YVec3 + s2 * ZVec3); v1 = ctr + r * normal; glNormal3dv(normal.p); glVertex3dv(v1.p); s1 = sin(a1 + a1d); c1 = cos(a1 + a1d); s2 = sin(a2 + a2d); c2 = cos(a2 + a2d); normal = c1 * XVec3 + s1 * (c2 * YVec3 + s2 * ZVec3); v1 = ctr + r * normal; glNormal3dv(normal.p); glVertex3dv(v1.p); } glEnd(); } }
[ "othummerer@gmx.de" ]
othummerer@gmx.de