blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ef9778e241885be5272027583fcfac02028b7ccc | 1f465d0e9082b92115d1d65f4f27ee03850b05f9 | /ReadFile/Store.h | 8fc97c0b336cf27f053307d623eea7a09949bc04 | [] | no_license | kjblkblt/ReadFile | 25c8a7b2225f6627d6fd0c5dbb9dc3960a0f60fa | c75309d1dd0b89177ae930cfe5e0ad6e42c5a27e | refs/heads/master | 2021-01-25T00:22:22.862937 | 2015-05-07T17:05:31 | 2015-05-07T17:05:31 | 34,702,589 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,823 | h | #include <string>
#ifndef STORE_H_
#define STORE_H_
using namespace std;
class Store
{
public:
static bool RevenueComparator(const Store& c1, const Store& c2);
static bool NPSComparator(const Store& c1, const Store& c2);
static bool StoreComparator(const Store& c1, const Store& c2);
Store();
~Store();
int storeNumber();
void setStoreNumber(int s);
void setFiscalMonth(string month);
string getFiscalMonth();
void setTotalPoints(int t);
int getTotalPoints();
void setTotalRank(int rank);
int getTotalRank();
void setTotServ2Trgt(double val);
double getTotServ2Trgt();
void setTotServ2TrgtRank(int rank);
double getTotServ2TrgtRank();
void setRenewRev(double renew);
double getRenewRev();
void setRevRank(int revRank);
int getRevRank();
void setNPS(double NPS);
double getNPS();
void setNPSRank(int NPSRank);
int getNPSRank();
void setUtilization(double P_Util);
double getUtilization();
void setATUtilization(double AT_Util);
double getATUtilization();
void setTT(double TT);
double getTT();
void set_TTRank(int TTRank);
int get_TTRank();
void setCertified(double cert);
double getCertified();
void setNPSKeepClient(double NPS_Keep) { _NPSKeepClient = NPS_Keep; };
double getNPSKeepClient() { return _NPSKeepClient; }
void setNPSFollowUP(double NPS_Follow) { _NPSFollowUp = NPS_Follow; };
double getNPSFollowUp() { return _NPSFollowUp; }
void setAJUAppl(int AJU_Appl) { _AJUAppl = AJU_Appl; };
int getAJUAppl() { return _AJUAppl; }
void setAJUAttach(int AJU_Attach) { _AJUAttach = AJU_Attach; };
int getAJUAttach() { return _AJUAttach; }
void setAJUPercent(double AJUcent) { _AJUPercent = AJUcent; };
double getAJUPercent() { return _AJUPercent; }
void setAJUTT(double AJU_TT) { _AJUTT = AJU_TT; };
double getAJUTT(){ return _AJUTT; }
void setAJUCost(double AJUCost) { _AJUCost = AJUCost; };
double getAJUCost() { return _AJUCost; }
void setOverallC2S(double C2S) { _Create2Ship = C2S; };
double getOverallC2S(){ return _Create2Ship; }
void setServiceC2S(double ServiceC2S) { _ServiceC2S = ServiceC2S; };
double getServiceC2S() { return _ServiceC2S; }
void setDTVC2S(double DTVC2S) { _DTVC2S = DTVC2S; };
double getDTVC2S() { return _DTVC2S; }
void setUPSC2S(double USPC2S) { _UPSC2S = USPC2S; };
double getUPSC2S() { return _UPSC2S; }
void setRec2PU(double Rec2PU) { _Rec2PU = Rec2PU; };
double getRec2PU() { return _Rec2PU; }
void setStoreComp2PU(double StoreComp2PU) { _StoreComp2PU = StoreComp2PU; };
double getStoreComp2PU() { return _StoreComp2PU; }
void setSWTags(int SWTags) { _SWTags = SWTags; };
int getSWTags() { return _SWTags; }
void setSWPercent(double SWPercent) { _SWPercent = SWPercent; };
double getSWPercent() { return _SWPercent; }
void setJOTags(int JOTags) { _JOTags = JOTags; };
int getJOTags(){ return _JOTags; }
void setJOPercent(double JOPercent) { _JOPercent = JOPercent; };
double getJOPercent() { return _JOPercent; }
void setNPSTrouble(double NPSTrouble) { _NPSTrouble = NPSTrouble; };
double getNPSTrouble() { return _NPSTrouble; }
void setNPSDemo(double NPSDemo) { _NPSDemo = NPSDemo; };
double getNPSDemo() { return _NPSDemo; }
void setNPSKnow(double NPSKnow) { _NPSKnow = NPSKnow; };
double getNPSKnow(){ return _NPSKnow; }
void setNOVAUse(double NOVAUse) { _NOVAUse = NOVAUse; };
double getNOVAUse(){ return _NOVAUse; }
void setTotRenew(double TotRenew) { _TotRenew = TotRenew; };
double getTotRenew() { return _TotRenew; }
void setTotRenewGoal(double TotRenewGoal) { _TotRenewGoal = TotRenewGoal; };
double getTotRenewGoal() { return _TotRenewGoal; }
void setTotRenewPercent(double TotRenewPercent) { _TotRenewPercent = TotRenewPercent; };
double getTotRenewPercent() { return _TotRenewPercent; }
void setRenew81Mix(double Renew81Mix) { _Renew81Mix = Renew81Mix; };
double getRenew81Mix() { return _Renew81Mix; }
void setRenew404Mix(double Renew404Mix) { _Renew404Mix = Renew404Mix; };
double getRenew404Mix() { return _Renew404Mix; }
void setShip2CTake(double Ship2CTake) { _Ship2CTake = Ship2CTake; };
double getShip2CTake() { return _Ship2CTake; }
void setShip2CElig(int Ship2CElig) { _Ship2CElig = Ship2CElig; };
int getShip2CElig(){ return _Ship2CElig; }
void setDBU2GSTS(double DBU2GSTS) { _DBU2GSTS = DBU2GSTS; };
double getDBU2GSTS(){ return _DBU2GSTS; }
void setNewPCAttach(double NewPCAttach) { _NewPCAttach = NewPCAttach; };
double getNewPCAttach() { return _NewPCAttach; }
void setGSTSAttach(double GSTSAttach) { _GSTSAttach = GSTSAttach; };
double getGSTSAttach(){ return _GSTSAttach; }
void setSetupAttach(double SetupAttach) { _SetupAttach = SetupAttach; };
double getSetupAttach(){ return _SetupAttach; }
void setRestoreAttach(double RestoreAttach){ _RestoreAttach = RestoreAttach; };
double getRestoreAttach(){ return _RestoreAttach; }
void setTotServAttach(double TotServAttach) { _TotServAttach = TotServAttach; };
double getTotServAttach(){ return _TotServAttach; }
void setNPSTT(double NPSTT){ _NPSTT = NPSTT; };
double getNPSTT(){ return _NPSTT; }
void setNPSServQual(double NPSServQual){ _NPSServQual = NPSServQual; };
double getNPSServQual() { return _NPSServQual; }
void setRenewTT(double RenewTT){ _RenewTT = RenewTT; };
double getRenewTT() { _RenewTT; }
void setInstoreTT(double InstoreTT) { _InstoreTT = InstoreTT; };
double getInstoreTT() { _InstoreTT; }
void setNewTT(double NewTT){ _NewTT = NewTT; };
double getNewTT() { return _NewTT; }
void setSOOlder2(int SOOlder2){ _SOOlder2 = SOOlder2; };
int getSOOlder2() { return _SOOlder2; }
void setSOOlder7(int SOOlder7){ _SOOlder7 = SOOlder7; };
int getSOOlder7() { return _SOOlder7; }
void setHP2StoreTT(double HP2StoreTT){ _HP2StoreTT = HP2StoreTT; };
double getHP2StoreTT() { return _HP2StoreTT; }
void setHP2StoreCmplt(int HP2StoreCmplt){ _HP2StoreCmplt = HP2StoreCmplt; };
int getHP2StoreCmplt() { return _HP2StoreCmplt; }
void setHP2StoreServ(int HP2StoreServ){ _HP2StoreServ = HP2StoreServ; };
int getHP2StoreServ(){ return _HP2StoreServ; }
void setHP2StoreSucc(double HP2StoreSucc){ _HP2StoreSucc = HP2StoreSucc; };
double getHP2StoreSucc(){ return _HP2StoreSucc; }
void setGSPPhone(double GSPPhone){ _GSPPhoneScreen = GSPPhone; };
double getGSPPhone(){ return _GSPPhoneScreen; }
void setTotalTags(int TotalTags){ _TotalTags = TotalTags; };
int getTotalTags(){ _TotalTags; }
void setCmpltsPerDay(double CmpltsPerDay){ _CmpltsPerDay = CmpltsPerDay; };
double getCmpltsPerDay(){ return _CmpltsPerDay; }
void setGSPSO(double GSPSO){ _GSPSO = GSPSO; };
double getGSPSO() { return _GSPSO; }
void setCODSO(double CODSO){ _CODSO = CODSO; };
double getCODSO(){ return _CODSO; }
void setGSTSSO(double GSTSSO){ _GSTSSO = GSTSSO; };
double getGSTSSO(){ return _GSTSSO; }
void setStoreRedo(double StoreRedo){ _StoreRedo = StoreRedo; };
double getStoreRedo(){ return _StoreRedo; }
void setRedo(int Redo){ _Redo = Redo; };
int getRedo(){ return _Redo; }
void setGSTSRedo(double GSTSRedo){ _GSTSRedo = GSTSRedo; };
double getGSTSRedo(){ return _GSTSRedo; }
void setOtherRedo(double OtherRedo){ _OtherRedo = OtherRedo; };
double getOtherRedo(){ return _OtherRedo; }
void setClientRedo(double CllientRedo){ _ClientRedo = CllientRedo; };
double getClientRedo(){ _ClientRedo; }
void setAgentRedo(double AgentRedo){ _AgentRedo = AgentRedo; };
double getAgentRedo(){ return _AgentRedo; }
void printSBG();
void printOA();
void printARA();
void printCA();
private:
int _storeNum;
string _fiscalMonth;
int _totalPoints;
int _totalRank;
double _totServ2Trgt;
int _totServ2TrgtRank;
double _renewRev;
int _renewRevRank;
double _nps;
int _npsRank;
double _utilization;
double _atUtilization;
double _tt;
int _ttRank;
double _certified;
double _NPSKeepClient;
double _NPSFollowUp;
int _AJUAppl;
int _AJUAttach;
double _AJUPercent;
double _AJUTT;
double _AJUCost;
double _Create2Ship;
double _ServiceC2S;
double _DTVC2S;
double _UPSC2S;
double _Rec2PU;
double _StoreComp2PU;
int _SWTags;
double _SWPercent;
int _JOTags;
double _JOPercent;
double _NPSTrouble;
double _NPSDemo;
double _NPSKnow;
double _NOVAUse;
double _TotRenew;
double _TotRenewGoal;
double _TotRenewPercent;
double _Renew81Mix;
double _Renew404Mix;
double _Ship2CTake;
int _Ship2CElig;
double _DBU2GSTS;
double _NewPCAttach;
double _GSTSAttach;
double _SetupAttach;
double _RestoreAttach;
double _TotServAttach;
double _NPSTT;
double _NPSServQual;
double _RenewTT;
double _InstoreTT;
double _NewTT;
int _SOOlder2;
int _SOOlder7;
double _HP2StoreTT;
int _HP2StoreCmplt;
int _HP2StoreServ;
double _HP2StoreSucc;
double _GSPPhoneScreen;
int _TotalTags;
double _CmpltsPerDay;
double _GSPSO;
double _CODSO;
double _GSTSSO;
double _StoreRedo;
int _Redo;
double _GSTSRedo;
double _OtherRedo;
double _ClientRedo;
double _AgentRedo;
};
#endif | [
"kim.x.johnson@gmail.com"
] | kim.x.johnson@gmail.com |
6411c0a5dc9202061a2b7a1a7d246eb39933c93a | 38702e29534e03742dedd1cc752990113059509c | /FrontEnd/front/windows/front/MainPage.h | 2756305093e34c45c91c8735e4d932576a1a3d5e | [] | no_license | kandabior/Queries | 6b9a2cb0aa20cea4dfcbd40b828b19dab2399f7c | 6e94dab1e3141dedf613cee503289a873c0dccc1 | refs/heads/master | 2023-03-19T10:44:31.557522 | 2021-03-02T15:48:48 | 2021-03-02T15:48:48 | 337,340,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | h | #pragma once
#include "MainPage.g.h"
#include <winrt/Microsoft.ReactNative.h>
namespace winrt::front::implementation
{
struct MainPage : MainPageT<MainPage>
{
MainPage();
};
}
namespace winrt::front::factory_implementation
{
struct MainPage : MainPageT<MainPage, implementation::MainPage>
{
};
}
| [
"MJFC37@motorolasolutions.com"
] | MJFC37@motorolasolutions.com |
3b899af5d815f9b22371cc1977a7f604e8bc4d85 | 21f5356e9fd0b3ab9ee7a5c54e30fd94bb660ee4 | /com/win32comext/adsi/src/PyADSIUtil.cpp | 069877b6e2c4aace1e8b10f3b7a9c7cbd9a4ffca | [] | no_license | chevah/pywin32 | 90850232a557ecf054bc316e324aaf60188f2cca | d4ff0b440147ab65f1945991e81163fb1cf1ceaf | refs/heads/master | 2020-03-29T09:46:04.465546 | 2014-10-24T09:11:17 | 2014-10-24T09:11:17 | 25,680,336 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,345 | cpp | // @doc
#include "Python.h"
#include "pyerrors.h" // for PyErr_Warn in 2.5...
#include "Windows.h"
#include "PyWinTypes.h"
#include "PythonCOM.h"
#include "PyADSIUtil.h"
#include "structmember.h"
#include "wchar.h"
BOOL GetADSIErrorString( HRESULT hr, WCHAR *buf, int nchars );
PyObject *OleSetADSIError(HRESULT hr, IUnknown *pUnk, REFIID iid)
{
// If the HRESULT is an ADSI one, we do things differently!
if (hr & 0x00005000) {
WCHAR szErrorBuf[MAX_PATH] = {0};
WCHAR szNameBuf[MAX_PATH] = {0};
DWORD dwErrCode = 0;
ADsGetLastError( &dwErrCode,
szErrorBuf,
MAX_PATH-1,
szNameBuf,
MAX_PATH-1);
if (dwErrCode == 0) dwErrCode = hr;
if (!szErrorBuf[0])
GetADSIErrorString( hr, szErrorBuf, MAX_PATH-1);
// Trim trailing /r/n
WCHAR *szEnd = szErrorBuf + wcslen(szErrorBuf) - 1;
while (szEnd > szErrorBuf && (*szEnd == L'\r' || *szEnd == L'\n'))
*szEnd-- = L'\0';
// Only do this if we have a useful message - otherwise
// let the default handling do the best it can.
if (szErrorBuf[0]) {
EXCEPINFO info;
memset(&info, 0, sizeof(info));
info.scode = dwErrCode;
info.bstrSource = SysAllocString(szNameBuf);
info.bstrDescription = SysAllocString(szErrorBuf);
// Technically, we probably should return DISP_E_EXCEPTION so we
// appear to follow COM's rules - however, we really dont
// _need_ to (as only Python sees this result), and having the native
// HRESULT is preferable.
return PyCom_BuildPyExceptionFromEXCEPINFO(dwErrCode, &info);
}
}
if (HRESULT_FACILITY(hr)==FACILITY_WIN32) {
//Get extended error value.
WCHAR szErrorBuf[MAX_PATH] = {0};
WCHAR szNameBuf[MAX_PATH] = {0};
DWORD dwErrCode = 0;
ADsGetLastError( &dwErrCode,
szErrorBuf,
MAX_PATH-1,
szNameBuf,
MAX_PATH-1);
// Only do this if we have a useful message - otherwise
// let the default handling do the best it can.
if (dwErrCode == 0) dwErrCode = hr;
if (szErrorBuf[0]) {
EXCEPINFO info;
memset(&info, 0, sizeof(info));
info.scode = dwErrCode;
info.bstrSource = SysAllocString(szNameBuf);
info.bstrDescription = SysAllocString(szErrorBuf);
// Technically, we probably should return DISP_E_EXCEPTION so we
// appear to follow COM's rules - however, we really dont
// _need_ to (as only Python sees this result), and having the native
// HRESULT is preferable.
return PyCom_BuildPyExceptionFromEXCEPINFO(dwErrCode, &info);
}
}
// Do the normal thing.
return PyCom_BuildPyException(hr, pUnk, iid);
}
// @object PyADSVALUE|A tuple:
// @tupleitem 0|object|value|The value as a Python object.
// @tupleitem 1|int|type|The AD type of the value.
PyObject *PyADSIObject_FromADSVALUE(ADSVALUE &v)
{
PyObject *ob = NULL;
switch (v.dwType) {
case ADSTYPE_DN_STRING:
ob = PyWinObject_FromWCHAR(v.DNString);
break;
case ADSTYPE_CASE_EXACT_STRING:
ob = PyWinObject_FromWCHAR(v.CaseExactString);
break;
case ADSTYPE_CASE_IGNORE_STRING:
ob = PyWinObject_FromWCHAR(v.CaseIgnoreString);
break;
case ADSTYPE_PRINTABLE_STRING:
ob = PyWinObject_FromWCHAR(v.PrintableString);
break;
case ADSTYPE_NUMERIC_STRING:
ob = PyWinObject_FromWCHAR(v.NumericString);
break;
case ADSTYPE_BOOLEAN:
ob = v.Boolean ? Py_True : Py_False;
Py_INCREF(ob);
break;
case ADSTYPE_INTEGER:
ob = PyInt_FromLong(v.Integer);
break;
case ADSTYPE_OCTET_STRING:
{
void *buf;
DWORD bufSize = v.OctetString.dwLength;
if (!(ob=PyBuffer_New(bufSize)))
return NULL;
if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){
Py_DECREF(ob);
return NULL;
}
memcpy(buf, v.OctetString.lpValue, bufSize);
}
break;
case ADSTYPE_UTC_TIME:
ob = PyWinObject_FromSYSTEMTIME(v.UTCTime);
break;
case ADSTYPE_LARGE_INTEGER:
ob = PyWinObject_FromLARGE_INTEGER(v.LargeInteger);
break;
case ADSTYPE_OBJECT_CLASS:
ob = PyWinObject_FromWCHAR(v.ClassName);
break;
case ADSTYPE_PROV_SPECIFIC:
{
void *buf;
DWORD bufSize = v.ProviderSpecific.dwLength;
if (!(ob=PyBuffer_New(bufSize)))
return NULL;
if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){
Py_DECREF(ob);
return NULL;
}
memcpy(buf, v.ProviderSpecific.lpValue, bufSize);
break;
}
case ADSTYPE_NT_SECURITY_DESCRIPTOR:
{
// Get a pointer to the security descriptor.
PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)(v.SecurityDescriptor.lpValue);
DWORD SDSize = v.SecurityDescriptor.dwLength;
// eeek - we don't pass the length - pywintypes relies on
// GetSecurityDescriptorLength - make noise if this may bite us.
if (SDSize != GetSecurityDescriptorLength(pSD))
PyErr_Warn(PyExc_RuntimeWarning, "Security-descriptor size mis-match");
ob = PyWinObject_FromSECURITY_DESCRIPTOR(pSD);
break;
}
default:
{
char msg[100];
sprintf(msg, "Unknown ADS type code 0x%x - None will be returned", v.dwType);
PyErr_Warn(PyExc_RuntimeWarning, msg);
ob = Py_None;
Py_INCREF(ob);
}
}
if (ob==NULL)
return NULL;
PyObject *ret = Py_BuildValue("Oi", ob, (int)v.dwType);
Py_DECREF(ob);
return ret;
}
BOOL PyADSIObject_AsTypedValue(PyObject *val, ADSVALUE &v)
{
BOOL ok = TRUE;
switch (v.dwType) {
// OK - get lazy - we know its a union!
case ADSTYPE_DN_STRING:
case ADSTYPE_CASE_EXACT_STRING:
case ADSTYPE_CASE_IGNORE_STRING:
case ADSTYPE_PRINTABLE_STRING:
case ADSTYPE_NUMERIC_STRING:
case ADSTYPE_OBJECT_CLASS:
ok = PyWinObject_AsWCHAR(val, &v.DNString, FALSE);
break;
case ADSTYPE_BOOLEAN:
v.Boolean = PyInt_AsLong(val);
break;
case ADSTYPE_INTEGER:
v.Integer = PyInt_AsLong(val);
break;
case ADSTYPE_UTC_TIME:
ok = PyWinObject_AsSYSTEMTIME(val, &v.UTCTime);
break;
case ADSTYPE_LARGE_INTEGER:
ok = PyWinObject_AsLARGE_INTEGER(val, &v.LargeInteger);
break;
default:
PyErr_SetString(PyExc_TypeError, "Cant convert to this type");
return FALSE;
}
return ok;
}
BOOL PyADSIObject_AsADSVALUE(PyObject *ob, ADSVALUE &v)
{
if (!PyTuple_Check(ob) || PyTuple_Size(ob) < 1 || PyTuple_Size(ob)>2) {
PyErr_SetString(PyExc_ValueError, "ADSVALUE must be a tuple of (value, type) (but type may be None or omitted)");
return FALSE;
}
PyObject *val = PyTuple_GET_ITEM(ob, 0);
PyObject *obtype = NULL;
DWORD dwType;
if (PyTuple_Size(ob)>1)
obtype = PyTuple_GET_ITEM(ob, 1);
if (obtype==NULL || obtype == Py_None) {
if (PyString_Check(val) || PyUnicode_Check(val))
dwType = ADSTYPE_PRINTABLE_STRING;
else if (val==Py_True || val==Py_False)
dwType = ADSTYPE_BOOLEAN;
else if (PyInt_Check(val))
dwType = ADSTYPE_INTEGER;
else if (PyWinTime_Check(val))
dwType = ADSTYPE_UTC_TIME;
else {
PyErr_SetString(PyExc_ValueError, "No type given, and can't deduce it!");
return FALSE;
}
} else if (PyInt_Check(obtype))
dwType = PyInt_AsLong(obtype);
else {
PyErr_SetString(PyExc_TypeError, "The type specified must be None or a string");
return FALSE;
}
v.dwType = (ADSTYPE)dwType;
return PyADSIObject_AsTypedValue(val, v);
}
void PyADSIObject_FreeADSVALUE(ADSVALUE &v)
{
switch (v.dwType) {
case ADSTYPE_DN_STRING:
case ADSTYPE_CASE_EXACT_STRING:
case ADSTYPE_CASE_IGNORE_STRING:
case ADSTYPE_PRINTABLE_STRING:
case ADSTYPE_NUMERIC_STRING:
case ADSTYPE_OBJECT_CLASS:
PyWinObject_FreeWCHAR(v.DNString);
default:
;
}
// force 'null' reset if called again.
v.dwType = ADSTYPE_INTEGER;
v.Integer = 0;
}
// Helpers for passing arrays of Unicode around.
BOOL PyADSI_MakeNames(PyObject *obNames, WCHAR ***names, DWORD *pcnames)
{
if (!PySequence_Check(obNames)) {
PyErr_SetString(PyExc_TypeError, "names must be a sequence of strings");
return FALSE;
}
*names = NULL;
int cnames = PySequence_Length(obNames);
WCHAR **buf = (WCHAR **)malloc(cnames * sizeof(WCHAR *));
if (buf==NULL) {
PyErr_NoMemory();
return FALSE;
}
memset(buf, 0, cnames * sizeof(WCHAR *));
int i=0;
for (i=0;i<cnames;i++) {
PyObject *ob = PySequence_GetItem(obNames, i);
if (ob==NULL)
goto done;
BOOL ok = PyWinObject_AsWCHAR(ob, &buf[i], FALSE);
Py_DECREF(ob);
if (!ok) goto done;
}
*names = buf;
*pcnames = cnames;
done:
if (*names==NULL) {
PyADSI_FreeNames(buf, cnames);
}
return (*names != NULL);
}
void PyADSI_FreeNames(WCHAR **names, DWORD cnames)
{
for (int i=0;i<(int)cnames;i++)
if (names[i] != NULL)
PyWinObject_FreeWCHAR(names[i]);
free(names);
}
// @object PyADS_OBJECT_INFO|Represents a ADS_OBJECT_INFO structure.
class PyADS_OBJECT_INFO : public PyObject
{
public:
PyADS_OBJECT_INFO(void) {
ob_type = &Type;
_Py_NewReference(this);
obRDN = obObjectDN = obParentDN = obClassName = NULL;
}
PyADS_OBJECT_INFO(const ADS_OBJECT_INFO *pInfo) {
ob_type = &Type;
_Py_NewReference(this);
obRDN = PyWinObject_FromWCHAR(pInfo->pszRDN);
obObjectDN = PyWinObject_FromWCHAR(pInfo->pszObjectDN);
obParentDN = PyWinObject_FromWCHAR(pInfo->pszParentDN);
obClassName = PyWinObject_FromWCHAR(pInfo->pszClassName);
}
~PyADS_OBJECT_INFO() {
Py_XDECREF(obRDN);
Py_XDECREF(obObjectDN);
Py_XDECREF(obParentDN);
Py_XDECREF(obClassName);
}
/* Python support */
static void deallocFunc(PyObject *ob) {
delete (PyADS_OBJECT_INFO *)ob;
}
static struct PyMemberDef memberlist[];
static PyTypeObject PyADS_OBJECT_INFO::Type;
protected:
PyObject *obRDN, *obObjectDN, *obParentDN, *obClassName;
};
PyTypeObject PyADS_OBJECT_INFO::Type =
{
PYWIN_OBJECT_HEAD
"PyADS_OBJECT_INFO",
sizeof(PyADS_OBJECT_INFO),
0,
PyADS_OBJECT_INFO::deallocFunc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0,
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
};
#define OFF(e) offsetof(PyADS_OBJECT_INFO, e)
/*static*/ struct PyMemberDef PyADS_OBJECT_INFO::memberlist[] = {
{"RDN", T_OBJECT, OFF(obRDN)}, // @prop unicode|RDN|The name
{"ObjectDN", T_OBJECT, OFF(obObjectDN)}, // @prop unicode|ObjectDN|
{"ParentDN", T_OBJECT, OFF(obParentDN)}, // @prop unicode|ParentDN|
{"ClassName", T_OBJECT, OFF(obClassName)}, // @prop unicode|ClassName|
{NULL}
};
PyObject *PyADSIObject_FromADS_OBJECT_INFO(ADS_OBJECT_INFO *info)
{
return new PyADS_OBJECT_INFO(info);
}
// @object PyADS_ATTR_INFO|Represents a ADS_ATTR_INFO structure.
class PyADS_ATTR_INFO : public PyObject
{
public:
PyADS_ATTR_INFO(void) {
ob_type = &Type;
_Py_NewReference(this);
dwControlCode = 0;
dwADsType = ADSTYPE_INVALID;
obValues = PyList_New(0);
obName = Py_None;
Py_INCREF(obName);
bufName = NULL;
bufValues = NULL;
}
PyADS_ATTR_INFO(const ADS_ATTR_INFO *pInfo) {
ob_type = &Type;
_Py_NewReference(this);
bufName = NULL;
bufValues = NULL;
obName = PyWinObject_FromWCHAR(pInfo->pszAttrName);
dwControlCode = pInfo->dwControlCode;
dwADsType = pInfo->dwADsType;
obValues = PyList_New(pInfo->dwNumValues);
if (obValues) {
for (DWORD i=0;i<pInfo->dwNumValues;i++) {
PyList_SET_ITEM(obValues, i, PyADSIObject_FromADSVALUE(pInfo->pADsValues[i]));
}
}
}
~PyADS_ATTR_INFO() {
InvalidateName();
InvalidateValues();
Py_XDECREF(obName);
Py_XDECREF(obValues);
}
void InvalidateName(void) {
if (bufName) {
PyWinObject_FreeWCHAR(bufName);
bufName = NULL;
}
}
void InvalidateValues(void) {
if (bufValues) {
for (int i=0;i<bufValuesNum;i++) {
PyADSIObject_FreeADSVALUE(bufValues[i]);
}
free(bufValues);
bufValues = NULL;
}
}
BOOL FillADS_ATTR_INFO( ADS_ATTR_INFO *pInfo) {
pInfo->dwControlCode = dwControlCode;
pInfo->dwADsType = dwADsType;
if (bufName == NULL) {
if (!PyWinObject_AsWCHAR(obName, &bufName, FALSE))
return FALSE;
}
pInfo->pszAttrName = bufName;
if (bufValues == NULL) {
if (!PySequence_Check(obValues)) {
PyErr_SetString(PyExc_TypeError, "Values attribute must be a sequence!");
return FALSE;
}
int n = bufValuesNum = PySequence_Length(obValues);
bufValues = (ADSVALUE *)malloc(n * sizeof(ADSVALUE));
memset(bufValues, 0, n * sizeof(ADSVALUE));
if (bufValues==NULL) {
PyErr_NoMemory();
return FALSE;
}
for (int i=0;i<n;i++) {
PyObject *ob = PySequence_GetItem(obValues, i);
if (ob==NULL)
return FALSE;
BOOL ok = PyADSIObject_AsADSVALUE(ob, bufValues[i]);
Py_DECREF(ob);
if (!ok)
return FALSE;
}
}
pInfo->pADsValues = bufValues;
pInfo->dwNumValues = bufValuesNum;
return TRUE;
}
/* Python support */
static void deallocFunc(PyObject *ob) {
delete (PyADS_ATTR_INFO *)ob;
}
static PyObject *getattro(PyObject *self, PyObject *obname) {
char *name=PYWIN_ATTR_CONVERT(obname);
if (name==NULL)
return NULL;
if (strcmp(name, "__members__")==0) {
PyObject *ret = PyList_New(4);
if (ret) {
PyList_SET_ITEM(ret, 0, PyString_FromString("AttrName"));
PyList_SET_ITEM(ret, 1, PyString_FromString("ControlCode"));
PyList_SET_ITEM(ret, 2, PyString_FromString("ADsType"));
PyList_SET_ITEM(ret, 3, PyString_FromString("Values"));
}
return ret;
}
if (strcmp(name, "Values")==0) {
PyObject *ret = ((PyADS_ATTR_INFO *)self)->obValues ?
((PyADS_ATTR_INFO *)self)->obValues :
Py_None;
Py_INCREF(ret);
return ret;
}
return PyObject_GenericGetAttr(self, obname);
}
//#pragma warning( disable : 4251 )
static struct PyMemberDef memberlist[];
//#pragma warning( default : 4251 )
static PyTypeObject PyADS_ATTR_INFO::Type;
protected:
DWORD dwControlCode;
ADSTYPE dwADsType;
PyObject *obName;
PyObject *obValues;
WCHAR *bufName;
ADSVALUE *bufValues;
int bufValuesNum;
};
PyTypeObject PyADS_ATTR_INFO::Type =
{
PYWIN_OBJECT_HEAD
"PyADS_ATTR_INFO",
sizeof(PyADS_ATTR_INFO),
0,
PyADS_ATTR_INFO::deallocFunc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0,
0, /* tp_call */
0, /* tp_str */
PyADS_ATTR_INFO::getattro, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
};
#undef OFF
#define OFF(e) offsetof(PyADS_ATTR_INFO, e)
/*static*/ struct PyMemberDef PyADS_ATTR_INFO::memberlist[] = {
{"AttrName", T_OBJECT, OFF(obName)}, // @prop unicode|AttrName|The name
{"ControlCode", T_INT, OFF(dwControlCode)}, // @prop integer|ControlCode|
{"ADsType", T_INT, OFF(dwADsType)}, // @prop integer|ADsType|
{NULL}
};
// @prop [<o PyADSVALUE>, ...]|Values|
PyObject *PyADSIObject_FromADS_ATTR_INFOs(ADS_ATTR_INFO *infos, DWORD cinfos)
{
PyObject *ret = PyTuple_New(cinfos);
for (DWORD i=0;ret != NULL && i<cinfos;i++) {
PyObject *n = new PyADS_ATTR_INFO(infos+i);
if (n==NULL) {
Py_DECREF(ret);
ret = NULL;
break;
}
PyTuple_SET_ITEM(ret, (int)i, n);
}
return ret;
}
BOOL _Make_ATTR_INFO(PyObject *ob, ADS_ATTR_INFO *pBase, DWORD index)
{
PyObject *obName, *obValues;
ADS_ATTR_INFO *pThis = pBase + index;
PyObject *sub = PySequence_GetItem(ob, index);
if (!sub)
return FALSE;
if (!PyArg_ParseTuple(sub, "OllO:ADS_ATTR_INFO tuple",
&obName, &pThis->dwControlCode,
&pThis->dwADsType, &obValues))
return FALSE;
if (!PyWinObject_AsWCHAR(obName, &pThis->pszAttrName, FALSE))
return FALSE;
if (!PySequence_Check(obValues)) {
PyErr_Format(PyExc_TypeError,
"4th item in an ATTR_INFO structure must be a sequence (got %s)",
obValues->ob_type->tp_name);
return FALSE;
}
DWORD nValues = PySequence_Length(obValues);
pThis->pADsValues = (PADSVALUE)malloc(nValues * sizeof(ADSVALUE));
if (!pThis->pADsValues) {
PyErr_NoMemory();
return FALSE;
}
memset(pThis->pADsValues, 0, nValues * sizeof(ADSVALUE));
pThis->dwNumValues = nValues;
DWORD i;
BOOL ok;
for (i=0;i<nValues;i++) {
PyObject *val = PySequence_GetItem(obValues, i);
if (!val)
return FALSE;
pThis->pADsValues[i].dwType = pThis->dwADsType;
ok = PyADSIObject_AsTypedValue(val, pThis->pADsValues[i]);
Py_DECREF(val);
}
return TRUE;
}
void PyADSIObject_FreeADS_ATTR_INFOs(ADS_ATTR_INFO *pval, DWORD cinfos)
{
if (!pval) return;
DWORD i;
for (i=0;i<cinfos;i++) {
ADS_ATTR_INFO *pThis = pval + i;
PyWinObject_FreeWCHAR(pThis->pszAttrName);
if (pThis->pADsValues) {
DWORD valnum;
for (valnum=0;valnum<pThis->dwNumValues;valnum++)
PyADSIObject_FreeADSVALUE(pThis->pADsValues[valnum]);
free(pThis->pADsValues);
}
}
free(pval);
}
BOOL PyADSIObject_AsADS_ATTR_INFOs(PyObject *ob, ADS_ATTR_INFO **ppret, DWORD *pcinfos)
{
if (!PySequence_Check(ob)) {
PyErr_SetString(PyExc_TypeError, "ADS_ATTR_INFOs must be a sequence");
return FALSE;
}
DWORD i;
// Use C++ reference to make working with ppret more convenient.
ADS_ATTR_INFO *&pret = *ppret;
DWORD &nitems = *pcinfos;
nitems = PySequence_Length(ob);
pret = (PADS_ATTR_INFO)malloc(nitems * sizeof(ADS_ATTR_INFO));
if (!pret) {
PyErr_NoMemory();
return FALSE;
}
memset(pret, 0, nitems * sizeof(ADS_ATTR_INFO));
BOOL ok = TRUE;
for (i=0;ok && i<nitems;i++) {
ok = _Make_ATTR_INFO(ob, pret, i);
}
if (!ok && pret) {
PyADSIObject_FreeADS_ATTR_INFOs(pret, nitems);
pret = 0;
nitems = 0;
}
return ok;
}
// @object PyADS_SEARCHPREF_INFO|A tuple of:
// @tupleitem 0|int|attr_id|
// @tupleitem 1|<o PyADSVALUE>|value|
void PyADSIObject_FreeADS_SEARCHPREF_INFOs(ADS_SEARCHPREF_INFO *pattr, DWORD cattr)
{
if (!pattr) return;
DWORD i;
for (i=0;i<cattr;i++)
PyADSIObject_FreeADSVALUE(pattr[i].vValue);
free(pattr);
}
BOOL PyADSIObject_AsADS_SEARCHPREF_INFOs(PyObject *ob, ADS_SEARCHPREF_INFO **ppret, DWORD *pcinfos)
{
BOOL ret = FALSE;
if (!PySequence_Check(ob)) {
PyErr_SetString(PyExc_TypeError, "ADS_SEARCHPREF_INFOs must be a sequence");
return FALSE;
}
// Use C++ reference to make working with ppret more convenient.
ADS_SEARCHPREF_INFO *&pret = *ppret;
DWORD &nitems = *pcinfos;
nitems = PySequence_Length(ob);
pret = (ADS_SEARCHPREF_INFO *)malloc(sizeof(ADS_SEARCHPREF_INFO) * nitems);
if (!pret) {
PyErr_NoMemory();
return NULL;
}
memset(pret, 0, sizeof(ADS_SEARCHPREF_INFO) * nitems);
PyObject *sub = NULL;
PyObject *obValue; // no reference
DWORD i;
for (i=0;i<nitems;i++) {
PyObject *sub = PySequence_GetItem(ob, i);
if (!sub) goto done;
if (!PyArg_ParseTuple(sub, "iO:ADS_SEARCHPREF_INFO tuple", &pret[i].dwSearchPref, &obValue))
goto done;
if (!PyADSIObject_AsADSVALUE(obValue, pret[i].vValue))
goto done;
Py_DECREF(sub);
sub = NULL;
}
ret = TRUE;
done:
Py_XDECREF(sub);
if (!ret && pret)
PyADSIObject_FreeADS_SEARCHPREF_INFOs(pret, nitems);
return ret;
}
///////////////////////////////////////////////////////
//
// Error string utility.
//
// ADSERR.h is built from a message file.
// Therefore, there _must_ be a DLL around we can call
// FormatMessage with.
// However, its not obvious, and this code was cut directly from MSDN.
#include "adserr.h"
typedef struct tagADSERRMSG
{
HRESULT hr;
LPCWSTR pszError;
}ADSERRMSG;
#define ADDADSERROR(x) x, L ## #x
const ADSERRMSG adsErr[] =
{
ADDADSERROR(E_ADS_BAD_PATHNAME),
ADDADSERROR(E_ADS_INVALID_DOMAIN_OBJECT),
ADDADSERROR(E_ADS_INVALID_USER_OBJECT),
ADDADSERROR(E_ADS_INVALID_COMPUTER_OBJECT),
ADDADSERROR(E_ADS_UNKNOWN_OBJECT),
ADDADSERROR(E_ADS_PROPERTY_NOT_SET),
ADDADSERROR(E_ADS_PROPERTY_NOT_SUPPORTED),
ADDADSERROR(E_ADS_PROPERTY_INVALID),
ADDADSERROR(E_ADS_BAD_PARAMETER),
ADDADSERROR(E_ADS_OBJECT_UNBOUND),
ADDADSERROR(E_ADS_PROPERTY_NOT_MODIFIED),
ADDADSERROR(E_ADS_PROPERTY_MODIFIED),
ADDADSERROR(E_ADS_CANT_CONVERT_DATATYPE),
ADDADSERROR(E_ADS_PROPERTY_NOT_FOUND),
ADDADSERROR(E_ADS_OBJECT_EXISTS),
ADDADSERROR(E_ADS_SCHEMA_VIOLATION),
ADDADSERROR(E_ADS_COLUMN_NOT_SET),
ADDADSERROR(E_ADS_INVALID_FILTER),
ADDADSERROR(0),
};
/////////////////////////////////////////////
//
// Error message specific to ADSI
//
////////////////////////////////////////////
BOOL GetADSIErrorString( HRESULT hr, WCHAR *buf, int nchars )
{
if ( hr & 0x00005000 )
{
int idx=0;
while (adsErr[idx].hr != 0 )
{
if ( adsErr[idx].hr == hr )
{
wcsncpy(buf, adsErr[idx].pszError, nchars);
return TRUE;
}
idx++;
}
}
buf[0] = L'\0';
return FALSE;
}
| [
"adi.roiban@chevah.com"
] | adi.roiban@chevah.com |
f3033af10cbf5ec1bb20718be6f63168eced9cb8 | f05155d1c9c41fcc6e31686505f856fd2fbc06de | /2019/octobor 2019/atl bangla 18 part 2.cpp | d820369f2af9ec4c15cb8e41c62c0d55975b267b | [] | no_license | T-tasir/Competetive-Programming | 22308db58c827a8dfa9d2f879f7a1c135f3ab96a | b56ab712fd2147a69b90b7300e281b9b6ed85852 | refs/heads/main | 2023-08-18T07:35:22.656508 | 2021-10-14T13:20:33 | 2021-10-14T13:20:33 | 368,572,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | cpp | //#include<bits/stdc++.h>
#include<iostream>
#include<set>
#include<map>
#include<iterator>
using namespace std;
int main()
{
multiset<int>s;
multiset<int>::iterator it;
s.insert(100);
s.insert(100);
s.insert(100);
s.insert(1);
for(it=s.begin();it!=s.end();it++){
cout<< *it <<endl;
}
return 0;
}
| [
"allmoontasir256@gmail.com"
] | allmoontasir256@gmail.com |
bc60de19394bbef643f40ec3f01b587950df6859 | 059be4fd38c56117816d2541731e031325cab43b | /meshlib/algorithm/FindLoop.cpp | e3572b3b60ee58bedd983840c34702f809a6797c | [
"MIT"
] | permissive | seanchas116/meshlib | aeacfc03820b8352a52f7ec3cc044d65628adfa4 | f2b48717667adaff9d70f0e927d1bdd44633beed | refs/heads/master | 2020-11-24T06:37:06.947687 | 2019-12-14T16:08:15 | 2019-12-14T16:08:15 | 228,012,025 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,771 | cpp | #include "FindLoop.hpp"
#include <range/v3/algorithm/find.hpp>
namespace meshlib {
std::vector<EdgeHandle> findLoop(const Mesh &mesh, EdgeHandle edge) {
std::vector<EdgeHandle> edges;
auto vertex = mesh.vertices(edge)[0];
edges.push_back(edge);
if (ranges::distance(mesh.faces(edge)) != 2) {
// non-manifold edge
return {};
}
while (true) {
auto nextVertex = mesh.vertices(edge)[0] == vertex ? mesh.vertices(edge)[1] : mesh.vertices(edge)[0];
if (ranges::distance(mesh.faces(nextVertex)) != 4) {
// extraordinary vertex
return {};
}
EdgeHandle nextEdge;
bool nextEdgeFound = false;
std::vector<FaceHandle> nextEdgeFaces;
for (auto e : mesh.edges(nextVertex)) {
if (ranges::distance(mesh.faces(e)) != 2) {
// non-manifold edge
continue;
}
bool allFacesDifferent = true;
for (auto face : mesh.faces(e)) {
for (auto edgeFace : mesh.faces(edge)) {
if (edgeFace == face) {
allFacesDifferent = false;
}
}
}
if (allFacesDifferent) {
nextEdge = e;
nextEdgeFound = true;
break;
}
}
if (!nextEdgeFound) {
return {};
}
if (nextEdge == edges[0]) {
// loop found
return edges;
}
if (ranges::find(edges, nextEdge) != edges.end()) {
// 9 loop
return {};
}
edges.push_back(nextEdge);
edge = nextEdge;
vertex = nextVertex;
}
}
} // namespace meshlib
| [
"iofg2100@gmail.com"
] | iofg2100@gmail.com |
df549bd23ed9cb01fe14515520c3e6bae78bf49c | f3a879985834f8528baf132eee8b8e0c4813b683 | /src/RequestHandlerFactory.cpp | 20df298937851a945600afcc8dda191bdb119aee | [
"Apache-2.0"
] | permissive | feniksa/tinyhttpd | c92a60971241ff810317d12401ed0110c3eaf4e6 | ba90ddf8dd36eac2ac3f755c01f4e5458d5d533e | refs/heads/master | 2021-04-29T00:00:39.479299 | 2020-03-27T13:23:15 | 2020-03-27T13:23:15 | 77,691,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,872 | cpp | #include "RequestHandlerFactory.h"
#include <Poco/Net/HTTPRequestHandler.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Util/Application.h>
#include <Poco/URI.h>
#include "api/DirectoryHandler.h"
#include "HandleStaticFile.h"
#include "cpsp/DirectoryHandler.h"
#include "HandleNotFound.h"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>
RequestHandlerFactory::RequestHandlerFactory(const WebDirectories& webDirectories)
: m_webDirectories(webDirectories)
{
}
bool RequestHandlerFactory::processUrlSufix(const std::string& prefix, const std::string& path, std::string& sufix)
{
std::string::const_iterator prefi = prefix.begin();
std::string::const_iterator pathi = path.begin();
while (prefi != prefix.end() && pathi != path.end() && *prefi == *pathi) {
++prefi;
++pathi;
}
if (prefi != prefix.end())
return false;
sufix.clear();
sufix.reserve(std::distance(pathi, path.end()));
while (pathi != path.end()) {
sufix += *pathi;
++pathi;
}
return true;
}
Poco::Net::HTTPRequestHandler *RequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &request)
{
Poco::Util::Application &app = Poco::Util::Application::instance();
app.logger().information("Request URI " + request.getURI());
//Poco::URI uri(request.getURI());
/*using callback_t = std::function<Poco::Net::HTTPRequestHandler*()>;
using callmap_t = std::map<std::string, callback_t>;*/
//static callmap_t callmap {
//std::make_pair("/api/dir", [&]() { return new api::DirectoryHandler(_docroot); })
//};
std::string path;
std::string sufixPath;
bool result;
for (WebDirectories::const_iterator i = m_webDirectories.begin(); i != m_webDirectories.end(); ++i) {
const WebDirectory& webDirectory = *i;
Poco::URI uri(request.getURI());
result = processUrlSufix(webDirectory.m_alias, uri.getPath(), sufixPath);
if (!result) continue;
if (!webDirectory.m_alias.empty()) {
path = webDirectory.m_path + boost::filesystem::path::preferred_separator + sufixPath;
} else {
path = sufixPath;
}
//const std::string path = request.getURI(); /*webDirectory.m_path + boost::filesystem::path::preferred_separator + request.getURI()*/;
if (!boost::filesystem::exists(path))
continue;
if (boost::filesystem::is_directory(path)) {
if (webDirectory.m_showContent)
return new DirectoryHandler(path);
else
return new HandleNotFound();
} else if (boost::filesystem::is_symlink(path)) {
if (webDirectory.m_followSymLink) {
return new HandleStaticFile(path);
} else {
return new HandleNotFound();
}
} else if (boost::filesystem::is_regular_file(path)) {
return new HandleStaticFile(path);
}
}
/*callmap_t::const_iterator iter = callmap.find(uri.getPath());
if (iter != callmap.end()) {
return iter->second();
}*/
return new HandleNotFound();
}
| [
"msditanov@200volts.com"
] | msditanov@200volts.com |
d77d40327ab44d7a33742b5ff6f8a1e2e7cb3b16 | f6ef1f50a476c3ed58b4f268feb6fb438996f06a | /有OJ/刷题指南(包含leetcode, POJ, PAT等)/POJ-1/problems/3020.cpp | f1d0d18308fe77a0b88bb5ce26d65a93be763c57 | [] | no_license | February13/OJ_Guide | f9d6c72fc2863f5b6f3ad80b0d6c68b51f9a07db | a190942fae29a0dbee306adc81ee245be7fda44a | refs/heads/master | 2020-04-25T09:01:48.458939 | 2018-01-18T08:31:30 | 2018-01-18T08:31:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,454 | cpp | #include<iostream>
#define MN 401
bool GE[MN][MN],check[MN];
int h,w,q,point[MN][2],map[40][10];
int match[MN],min,x,y;
bool DFS(int p);
void construct();
int main()
{
int i,j,k,n,s;
scanf("%d",&n);
for (i=0;i<n;i++)
{
q=1;
scanf("%d%d",&h,&w);
for (j=0;j<h;j++)
{
getchar();
for (k=0;k<w;k++)
{
if (getchar()=='*')
map[j][k]=q++;
else map[j][k]=0;
}
}
memset(GE,false,sizeof(GE));
x=1;
y=q-1;
for (j=0;j<h;j++)
{
for (k=0;k<w;k++)
{
if (map[j][k]>0)
{
if ((j+k)%2==0)
{
point[x][0]=j;
point[x][1]=k;
map[j][k]=x++;
}
else{
point[y][0]=j;
point[y][1]=k;
map[j][k]=y--;
}
}
}
}
construct();
memset(match,-1,sizeof(match));
s=0;
for(k=1;k<x;k++)
{
memset(check,false,sizeof(check));
if (DFS(k))
s++;
}
min=q-1-s;
printf("%d\n",min);
}
return 0;
}
bool DFS(int p)
{
int i,t,a,b;
if (p<x)
a=x,b=q;
else a=1,b=x;
for(i=a;i<b;i++)
{
if (GE[i][p] && !check[i])
{
check[i]=true;
t=match[i];
match[i]=p;
if (t==-1 || DFS(t))
return true;
match[i]=t;
}
}
return false;
}
void construct()
{
int i,p,a,b;
for (i=1;i<q;i++)
{
a=point[i][0];
b=point[i][1];
if (a>0 && (p=map[a-1][b])>0)
GE[i][p]=true;
if (a<h-1 && (p=map[a+1][b])>0)
GE[i][p]=true;
if (b>0 && (p=map[a][b-1])>0)
GE[i][p]=true;
if (b<w-1 && (p=map[a][b+1])>0)
GE[i][p]=true;
}
}
| [
"zhaoqijie@pku.edu.cn"
] | zhaoqijie@pku.edu.cn |
d39faf6cdac13ccaf766daf5ff1b7d62d7b73202 | 099c2076771c1fd5bba80e5f1465410dfa70375a | /PE050_Consecutive_prime_sum/pe050.cpp | af8dfcf5e878fb87b09f3674d5c8726cc05fbb73 | [] | no_license | Jul-Le/project-euler | 73595411effa3c150c9bae04ae8f155b4c69aae6 | 17fc9e0ad252931ba0dbaeb033a139727eb99e45 | refs/heads/master | 2021-10-07T23:45:29.106429 | 2018-12-05T18:24:00 | 2018-12-05T18:24:00 | 159,533,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,604 | cpp | #include <iostream>
#include "isprime.h"
int main()
{
// The final answer
int answer = 0;
// Temp answer
int num = 0;
// Number of consecutive primes
int consecutivePrimes = 0;
// ^^Temp
int temp = 0;
// Count how many consecutive primes
int counter = 0;
// How many to find before test the answer
int terms = 21;
int i;
int a = 2;
while (a < 10)
{
terms = 21;
// 547 of smallest consecutive primes add up to over a million
while (terms < 547)
{
num = 0;
temp = 0;
counter = 0;
for (i = a; i < 500000; i++)
{
if (isPrime(i))
{
num += i;
counter++;
temp++;
if (counter >= terms)
{
if (isPrime(num))
{
if (temp > consecutivePrimes && num < 1000000)
{
consecutivePrimes = temp;
answer = num;
}
}
else
{
terms++;
std::cout << answer << " is a sum of " << consecutivePrimes
<< " consecutive primes." << std::endl;
break;
}
}
}
}
}
a++;
}
}
| [
"unconfigured@null.spigotmc.org"
] | unconfigured@null.spigotmc.org |
485d67885c492eead74c16cc842bf57297cff38b | 694d42f8e426ee1e7849688d9a332d9fafa99960 | /SnowmanSTG/Memento.h | c366a2db78d8208f293ab237de62fa5ee8bb4132 | [] | no_license | hazama-yuinyan/SnowmanSTG | 23fcfbdc99f03bfd98c920c6e6af1bd7f8cb8848 | 0d59fc481701d99e64fdf13327c54239a7cf4a84 | refs/heads/master | 2016-09-05T13:23:08.161705 | 2011-06-25T18:08:29 | 2011-06-25T18:08:29 | 1,854,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | h | #pragma once
#include "stdafx.h"
class MementoKey
{
friend class InputDeviceKeyBoard;
private:
MementoKey(void);
boost::array<char, 256> key_state;
void SetData(char In[]);
boost::array<char, 256> &GetData(void);
public:
~MementoKey(void){};
};
| [
"Ryouta@.(none)"
] | Ryouta@.(none) |
fbeb76d32c37017fe31321e4545cdb0df18c90f9 | 99f4b183c575d0a476a99a6a851bc7ba5660bdb0 | /755529/20200912.cpp | e3bbce2caec9b5a1cc794af0be22ad169aad2d74 | [] | no_license | XWJWPIY/20200910-homework-basic | 041ec01e0774266a2299bce424ccabd7c9c6e765 | 9541056bcd43ba0fb15b9b3b7b2c61f3430c1a32 | refs/heads/master | 2022-12-10T19:01:40.156838 | 2020-09-12T08:58:14 | 2020-09-12T08:58:14 | 294,898,988 | 0 | 0 | null | 2020-09-12T08:04:12 | 2020-09-12T08:04:11 | null | UTF-8 | C++ | false | false | 178 | cpp | #include <iostream>
using namespace std;
int main() {
string str;
std::cout << "請輸入你的名字:";
std::cin >> str;
std::cout << "你的名字是" + str;
} | [
"piy.angrybirds.minecraft@gmail.com"
] | piy.angrybirds.minecraft@gmail.com |
82627bb8ed682a284db14df4a533e5813953b1a6 | 1ee1f217f14aec3fe1bfe5fab6b9f11f78e2e937 | /CHEDAN_Universe/database.h | 0add48669a5171589ca1634bdd5f9d3fd855550c | [
"Apache-2.0"
] | permissive | Kwongrf/CHEDAN_Universe_v2 | 31ac72dc6c53a2540ed86d73ff50b411e4de035c | 6d001ce08def738c4a145b4c4752e6b63298ed76 | refs/heads/master | 2022-07-08T02:54:00.872522 | 2020-05-12T04:55:57 | 2020-05-12T04:55:57 | 104,554,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,722 | h | <<<<<<< HEAD
#ifndef DATABASE_H
#define DATABASE_H
#include "user.h"
#include "question.h"
#include "answer.h"
#include "notification.h"
#include <QTextCodec>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QTime>
#include <QSqlError>
#include <QtDebug>
#include <QSqlDriver>
#include <QSqlRecord>
class Database
{
public:
bool createConnection(); //创建一个连接
bool createTable(); //创建4张数据库表
bool insert(User user); //插入数据
bool insert(Question ques); //出入数据
bool insert(Answer ans); //出入数据
bool insert(Notification notif);
bool queryById(const int id,User& user); //查询用户信息
bool queryById(const int id,Question& ques); //查询问题信息
bool queryById(const int id,Answer& ans); //查询问题信息
vector<User> queryAllUser();
vector<Question> queryAllQues();
vector<Answer> queryAllAns();
vector<Answer> queryAllAns(vector<int> ids);
vector<Notification> queryAllNotif();
bool update(User user); //更新
bool update(Question ques); //更新
bool update(Answer ans); //更新
//bool deleteById(int id); //删除
//bool sortById(); //排序
};
#endif // DATABASE_H
=======
#ifndef DATABASE_H
#define DATABASE_H
#include "user.h"
#include "question.h"
#include "answer.h"
#include "notification.h"
#include <QTextCodec>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QTime>
#include <QSqlError>
#include <QtDebug>
#include <QSqlDriver>
#include <QSqlRecord>
class Database
{
public:
bool createConnection(); //创建一个连接
bool createTable(); //创建4张数据库表
bool insert(User user); //插入数据
bool insert(Question ques); //出入数据
bool insert(Answer ans); //出入数据
bool insert(Notification notif);
bool queryById(const int id,User& user); //查询用户信息
bool queryById(const int id,Question& ques); //查询问题信息
bool queryById(const int id,Answer& ans); //查询问题信息
vector<User> queryAllUser();
vector<Question> queryAllQues();
vector<Answer> queryAllAns();
vector<Answer> queryAllAns(vector<int> ids);
vector<Notification> queryAllNotif();
bool update(User user); //更新
bool update(Question ques); //更新
bool update(Answer ans); //更新
//bool deleteById(int id); //删除
//bool sortById(); //排序
};
#endif // DATABASE_H
>>>>>>> cfdf638c3bdfa8efdbbb0c911ad54fe243c63989
| [
"kuangruifeng@bupt.edu.cn"
] | kuangruifeng@bupt.edu.cn |
6d593282f13b69af8e64f415bd10d754ec71d582 | 971574c9d61071b8de016ca98b8579885143af82 | /src/hypotheses/hypothesis_with_points.cpp | f124aa4ecf58da26fcd72fa8eb0874b24631aa49 | [
"BSD-3-Clause"
] | permissive | AIS-Bonn/multi_hypothesis_tracking | 6066982e998a69db849ee71f83ba35d2347629da | e9854feee98001a1ea5190fcab4930d1880574f4 | refs/heads/master | 2023-07-01T01:27:36.727692 | 2021-07-27T15:05:43 | 2021-07-27T15:05:43 | 389,998,243 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,719 | cpp | /** @file
*
* Implementation of a hypothesis extended with point measurements on detected objects.
*
* @author Jan Razlaw
*/
#include "multi_hypothesis_tracking/hypotheses/hypothesis_with_points.h"
namespace MultiHypothesisTracker
{
HypothesisWithPoints::HypothesisWithPoints(const Detection& detection,
unsigned int id,
double time_stamp,
bool accumulate_detection_points_in_hypothesis)
: HypothesisBase(detection, id, time_stamp)
, m_accumulate_detection_points_in_hypothesis(accumulate_detection_points_in_hypothesis)
{
m_points = detection.points;
}
void HypothesisWithPoints::predict(float time_difference)
{
HypothesisBase::predict(time_difference);
HypothesisWithPoints::updatePointsAfterPrediction();
}
void HypothesisWithPoints::updatePointsAfterPrediction()
{
const auto& current_position = m_history.position_history.end()[-2];
const auto& predicted_position = m_history.position_history.end()[-1];
const auto& translation_from_current_to_predicted_position = (predicted_position - current_position).eval();
transformPoints(m_points, translation_from_current_to_predicted_position);
}
void HypothesisWithPoints::transformPoints(std::vector<Eigen::Vector3f>& points,
const Eigen::Vector3f& translation)
{
for(auto& point : points)
point += translation;
}
void HypothesisWithPoints::correct(const Detection& detection)
{
const auto predicted_position = m_history.position_history.back();
HypothesisBase::correct(detection);
if(m_accumulate_detection_points_in_hypothesis)
{
updatePointsAfterCorrection(predicted_position);
appendDetectionPoints(detection);
}
else
m_points = detection.points;
}
void HypothesisWithPoints::updatePointsAfterCorrection(const Eigen::Vector3f& predicted_position)
{
const auto& corrected_position = m_history.position_history.back();
auto translation_from_predicted_to_corrected_position = (corrected_position - predicted_position).eval();
transformPoints(m_points, translation_from_predicted_to_corrected_position);
}
void HypothesisWithPoints::appendDetectionPoints(const Detection& detection)
{
const auto transform_detection_to_corrected = (getPosition() - detection.position).eval();
std::vector<Eigen::Vector3f> corrected_detection_points = detection.points;
transformPoints(corrected_detection_points, transform_detection_to_corrected);
m_points.reserve(m_points.size() + corrected_detection_points.size());
m_points.insert(m_points.end(), corrected_detection_points.begin(), corrected_detection_points.end());
}
};
| [
"s6jarazl@uni-bonn.de"
] | s6jarazl@uni-bonn.de |
f2bf1d6e67e0119a78c795e6830b798cd77d0f5d | d669ad659f7f91a3f00ee677c5d5866433adaf41 | /do_best_holdem_hands.cpp | 3c55d90256e77f198ee630c46fc07ac29d337f4b | [] | no_license | neostreet/poker_odds_calculators | 8db5921dd0dbd025c895d8f8b9c714ab2c527cd9 | 5c6a3b68802e99a25800e4a7a077ac13c2e8aaab | refs/heads/master | 2022-10-24T16:34:17.450169 | 2022-09-29T20:42:20 | 2022-09-29T20:42:20 | 1,309,216 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,774 | cpp | #include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define MAIN_MODULE
#include "poker_hand.h"
static char usage[] =
"usage: best_holdem_hand (-unevaluate) (-verbose) (-plain) (-no_stream)";
static char couldnt_open[] = "couldn't open %s\n";
static char parse_error[] = "couldn't parse line %d, card %d: %d\n";
int main(int argc,char **argv)
{
int curr_arg;
bool bUnEvaluate;
bool bVerbose;
bool bPlain;
bool bNoStream;
int n;
int cards[NUM_CARDS_IN_DECK];
HoldemPokerHand board_poker_hand;
PokerHand best_poker_hand;
if ((argc < 1) || (argc > 5)) {
cout << usage << endl;
return 1;
}
bUnEvaluate = false;
bVerbose = false;
bPlain = false;
bNoStream = false;
for (curr_arg = 1; curr_arg < argc; curr_arg++) {
if (!strcmp(argv[curr_arg],"-unevaluate"))
bUnEvaluate = true;
else if (!strcmp(argv[curr_arg],"-verbose"))
bVerbose = true;
else if (!strcmp(argv[curr_arg],"-plain"))
bPlain = true;
else if (!strcmp(argv[curr_arg],"-no_stream"))
bNoStream = true;
else
break;
}
if (argc != curr_arg) {
cout << usage << endl;
return 2;
}
for (n = 0; n < NUM_CARDS_IN_DECK; n++)
cards[n] = n;
for (n = 0; n < NUM_CARDS_IN_DECK - 7 + 1; n++) {
board_poker_hand.NewCards(cards[n],cards[n+1],cards[n+2],
cards[n+3],cards[n+4],cards[n+5],cards[n+6]);
best_poker_hand = board_poker_hand.BestPokerHand();
if (bUnEvaluate)
best_poker_hand.UnEvaluate();
else {
if (bVerbose)
best_poker_hand.Verbose();
if (bPlain)
best_poker_hand.Plain();
}
if (!bNoStream)
cout << best_poker_hand << endl;
else
cout << best_poker_hand.GetHand() << endl;
}
return 0;
}
| [
"lloyd.aidan@gmail.com"
] | lloyd.aidan@gmail.com |
0893d92971311ed0274713d310284408f4295504 | 82770c7bc5e2f27a48b8c370b0bab2ee41f24d86 | /graph-tool/src/graph/search/graph_search_bind.cc | 97d3a28910c3ce68f5104858e8d71101593aa8fc | [
"Apache-2.0",
"GPL-3.0-only",
"LicenseRef-scancode-philippe-de-muyter",
"GPL-3.0-or-later"
] | permissive | johankaito/fufuka | 77ddb841f27f6ce8036d7b38cb51dc62e85b2679 | 32a96ecf98ce305c2206c38443e58fdec88c788d | refs/heads/master | 2022-07-20T00:51:55.922063 | 2015-08-21T20:56:48 | 2015-08-21T20:56:48 | 39,845,849 | 2 | 0 | Apache-2.0 | 2022-06-29T23:30:11 | 2015-07-28T16:39:54 | Python | UTF-8 | C++ | false | false | 1,166 | cc | // graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <boost/python.hpp>
using namespace boost;
void export_bfs();
void export_dfs();
void export_dijkstra();
void export_bellman_ford();
void export_astar();
void export_astar_implicit();
BOOST_PYTHON_MODULE(libgraph_tool_search)
{
export_bfs();
export_dfs();
export_dijkstra();
export_bellman_ford();
export_astar();
export_astar_implicit();
}
| [
"john.g.keto@gmail.com"
] | john.g.keto@gmail.com |
913c1f1457f5c78be61214878d65c5d729111bfe | b056b8adad52ca1ceb994a811be4da8498c8cdde | /tests/cpp/include/test_legacy_op.h | 30bdf07b8b51f5cb4a7283769b42e44eb358bdf8 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-2-Clause-Views",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | SidHard/mxnet | 1a5cc8e958f5cb454ce5bf75f56b66ec8cb7a032 | f95832d73cf3f1413ce1c77fbef0f295a7fbc57f | refs/heads/master | 2022-11-09T00:22:36.043583 | 2017-12-21T05:10:40 | 2017-12-21T05:10:40 | 114,964,884 | 1 | 1 | Apache-2.0 | 2022-10-22T09:57:52 | 2017-12-21T05:06:17 | C++ | UTF-8 | C++ | false | false | 20,560 | h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file test_op.h
* \brief operator unit test utility functions
* \author Chris Olivier
*
* These classes offer a framework for developing, testing and debugging operators
* in C++. They work for both CPU and GPU modes, as well as offer a timing
* infrastructure in order to test inidividual operator performance.
*
* Operator data can be validated against general logic,
* stored scalar values (which can be generated by this code from an existing operator via
* BasicOperatorData::dumpC(), as well as against each other (ie check that
* GPU, CPU, MKL, and CUDNN operators produce the same output given the same input.
*
* test_util.h: General testing utility functionality
* test_perf.h: Performance-related classes
* test_op.h: Operator-specific testing classes
*/
#ifndef TEST_LEGACY_OP_H_
#define TEST_LEGACY_OP_H_
#include <list>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
#include <list>
#include "../../../include/mxnet/operator.h"
#include "./test_op.h"
#include "./test_op_runner.h"
namespace mxnet {
namespace test {
namespace op {
/*!
* \brief Manage test blobs and context, and universal logic
* Create an operator from its "Prop" class and sets up the operator
* and resources for both forward and backward passes
* \tparam DType
*/
template <typename DType, typename AccReal>
class LegacyOperatorExecutor : public OperatorDataInitializer<DType>
, public OperatorExecutorTiming {
public:
typedef DType DataType;
typedef AccReal AccRealType;
/*! \brief Manage test blobs and context */
LegacyOperatorExecutor(const bool isGPU, const std::vector<TShape>& topShapes)
#if !MXNET_USE_CUDA
: isGPU_(false)
#else
: isGPU_(isGPU)
#endif
, initializeForward_(0) // unit testing may call inits in any order based
, initializeBackward_(0) // upon its use-case (ie may not want to run forward pass first)
, initializeCallback_(0) {
opContext_.is_train = true;
opContext_.run_ctx.stream = nullptr;
CHECK(!topShapes.empty());
shape_input_vec_ = topShapes;
}
inline mxnet::Context getContext() {
return isGPU_ ? mxnet::Context::GPU(0) : mxnet::Context{};
}
/*! \brief Initialize forward blob data values */
virtual void resetForward() {}
/*! \brief Initialize backward blob data values */
virtual void resetBackward() {}
/*! \brief Initialize auxiliary and output blobs */
template<typename OperatorPropertyType>
bool initForward(const OperatorPropertyType &opProp, std::vector<int> *in_type) {
if (!initializeForward_++) {
shape_input_vec_.resize(opProp.ListArguments().size());
op_.reset(opProp.CreateOperatorEx(getContext(), &shape_input_vec_, in_type));
if (op_) {
const size_t output_count = opProp.ListOutputs().size();
const size_t aux_count = opProp.ListAuxiliaryStates().size();
// Figure out what sort of blobs we need to allocate
std::vector<TShape> out_shape, aux_shape;
out_shape.resize(output_count);
aux_shape.resize(aux_count);
opProp.InferShape(&shape_input_vec_, &out_shape, &aux_shape);
std::vector<int> out_type(output_count, -1), aux_type(aux_count, -1);
opProp.InferType(in_type, &out_type, &aux_type);
// Allocate top blobs (input)
for (size_t x = 0, n = shape_input_vec_.size(); x < n; ++x) {
int type;
if (x < in_type->size()) {
type = (*in_type)[x];
} else {
type = x ? mshadow::DataType<AccReal>::kFlag : mshadow::DataType<DType>::kFlag;
}
allocateBlob(&c_.blob_input_vec_, shape_input_vec_[x], false, type);
}
// Allocate aux blobs (scratch, hidden, etc.)
for (size_t x = 0, n = aux_shape.size(); x < n; ++x) {
CHECK(x < aux_type.size());
allocateBlob(&c_.blob_aux_states_, aux_shape[x], false, aux_type[x]);
}
// Allocate bottom blobs (output)
for (size_t x = 0, n = out_shape.size(); x < n; ++x) {
CHECK(x < out_type.size());
allocateBlob(&c_.blob_output_vec_, out_shape[x], false, out_type[x]);
}
// Get the resource of temporal space
std::vector<TShape> inputShapes;
for (size_t x = 0, n = shape_input_vec_.size(); x < n; ++x) {
inputShapes.push_back(shape_input_vec_[x]);
}
allocateResources(opProp.ForwardResource(inputShapes));
resetForward();
return true;
}
return false;
} else {
return true;
}
}
/*! \brief Initialize auxiliary and output blobs */
template<typename OperatorPropertyType>
bool initBackward(const OperatorPropertyType &opProp, std::vector<int> *in_type) {
initForward(opProp, in_type);
if (!initializeBackward_++) {
for (size_t x = 0, n = static_cast<size_t>(opProp.NumVisibleOutputs()); x < n; ++x) {
CHECK_LT(x, c_.blob_output_vec_.size());
allocateBlob(&c_.blob_out_grad_, c_.blob_output_vec_[x].shape_,
false, c_.blob_output_vec_[x].type_flag_);
}
for (size_t x = 0, n = c_.blob_input_vec_.size(); x < n; ++x) {
allocateBlob(&c_.blob_in_grad_, c_.blob_input_vec_[x].shape_,
false, c_.blob_input_vec_[x].type_flag_);
}
// Get the resource of temporal space
std::vector<TShape> ishapes;
allocateResources(opProp.BackwardResource(ishapes));
resetBackward();
return false;
} else {
return true;
}
}
/*! \brief Run operator forward */
void forward(const size_t count = 1) {
const std::vector<OpReqType> req(c_.blob_output_vec_.size(), kWriteTo);
// Possibly move data to/from CPU and GPU (outside of timing scope)
MXNET_CUDA_ONLY(std::unique_ptr<GPUOpData> gpuData(isGPU_ ?
new GPUOpData(c_, &opContext_) : nullptr));
perf::TimingItem timeF(&OperatorExecutorTiming::GetTiming(), Forward,
"Forward", count);
if (!isGPU_) {
VTuneResume profile; // VTune sample only this scope
for (size_t x = 0; x < count; ++x) {
op()->Forward(opContext_,
c_.blob_input_vec_,
req,
c_.blob_output_vec_,
c_.blob_aux_states_);
}
} else {
for (size_t x = 0; x < count; ++x) {
MXNET_CUDA_ONLY(op()->Forward(opContext_,
gpuData->blob_input_vec_,
req,
gpuData->blob_output_vec_,
gpuData->blob_aux_states_));
}
}
}
/*! \brief Run operator backwards */
void backward(const size_t count = 1) {
const std::vector<OpReqType> req(c_.blob_in_grad_.size(), kWriteTo);
// Possibly move data to/from CPU and GPU (outside of timing scope)
MXNET_CUDA_ONLY(std::unique_ptr<GPUOpData> gpuData(isGPU_ ?
new GPUOpData(c_, &opContext_) : nullptr));
perf::TimingItem timeB(&OperatorExecutorTiming::GetTiming(), Backward,
"Backward", count);
if (!isGPU_) {
VTuneResume profile; // VTune sample only this scope
for (size_t x = 0; x < count; ++x) {
op()->Backward(opContext_,
c_.blob_out_grad_,
c_.blob_input_vec_,
c_.blob_output_vec_,
req,
c_.blob_in_grad_,
c_.blob_aux_states_);
}
} else {
for (size_t x = 0; x < count; ++x) {
MXNET_CUDA_ONLY(op()->Backward(opContext_,
gpuData->blob_out_grad_,
gpuData->blob_input_vec_,
gpuData->blob_output_vec_,
req,
gpuData->blob_in_grad_,
gpuData->blob_aux_states_));
}
}
}
/*!
* \brief Test if operator has a backward pass
* \return true if this operator has a backward pass
*/
MSHADOW_CINLINE bool HasBackward() const { return true; }
/*! \brief Getter functions for the operator */
inline Operator *op() { return op_.get(); }
inline const Operator *op() const { return op_.get(); }
enum BlobVectorType {
kInput,
kOutput,
kAux,
kInGrad,
kOutGrad,
kBlobVectorTypeCount
};
#define CASE_STR(__v$) case (__v$): return #__v$
/*! \brief Convert BlobVectorType enum into a string */
static inline const char *bvt2String(const BlobVectorType bvt) {
switch (bvt) {
CASE_STR(kInput);
CASE_STR(kOutput);
CASE_STR(kAux);
CASE_STR(kInGrad);
CASE_STR(kOutGrad);
default:
CHECK(false);
return "";
}
}
#undef CASE_STR
/*! \brief Return a particular blob in a test data set */
inline const std::vector<TBlob>& getBlobVect(const BlobVectorType bvt) const {
switch (bvt) {
case kInput:
return c_.blob_input_vec_;
case kOutput:
return c_.blob_output_vec_;
case kAux:
return c_.blob_aux_states_;
case kInGrad:
return c_.blob_in_grad_;
case kOutGrad:
return c_.blob_out_grad_;
default:
CHECK(false);
return c_.blob_input_vec_;
}
}
/*! \brief Dump an operator's data set into compilable C++ data code for runtime validation
* When writing an operator test, you can generate a "known good operator data state" in C++
* code with this function, and then use load() to load the blob states into this
* class (BasicOperatorData).
* After that, you can compare with the "actual" operator state (BasicOperatorData) of
* the operator that you are testing.
*/
template<typename Stream>
inline void dumpC(Stream *_os, const std::string& label) {
Stream& os = *_os;
os << "static const std::vector< std::vector< std::vector<float> > > ___"
<< label << "_data_shape_";
const TShape& shape = shape_input_vec_[0];
for (size_t i = 0, n = shape.ndim(); i < n; ++i) {
os << shape[i] << "_";
}
os << "__ =" << std::endl << "{" << std::endl;
for (size_t x = 0; x < kBlobVectorTypeCount; ++x) {
os << " { /* " << bvt2String(BlobVectorType(x)) << " */" << std::endl;
const std::vector<TBlob>& blobVect = getBlobVect(BlobVectorType(x));
for (size_t i = 0, n = blobVect.size(); i < n; ++i) {
os << " { ";
test::dump<DType>(&os, blobVect[i]);
os << " }";
if (i < n - 1) {
os << ",";
}
os << std::endl;
}
os << " }";
if (x < kBlobVectorTypeCount - 1) {
os << ",";
}
os << std::endl;
}
os << "};" << std::endl;
}
static inline void copy(const TBlob& blob, const DType array[],
const size_t start, const size_t end) {
const size_t blobSize = blob.Size();
DType *p = blob.dptr<DType>();
for (size_t i = 0, n = end - start; i < n; ++i) {
CHECK_LT(i, blobSize);
p[i] = array[i + start];
}
}
/*! \brief Runtime load of the C++ data code generated by dumpC() */
void load(const std::vector<std::vector<std::vector<DType>>>& cData) {
for (size_t i = 0, ni = cData.size(); i < ni; ++i) {
for (size_t j = 0, nj = cData[i].size(); j < nj; ++j) {
const TBlob& blob = getBlobVect(BlobVectorType(i))[j];
const size_t sourceDataSize = cData[i][j].size();
CHECK_EQ(sourceDataSize, blob.Size());
const DType *sourceData = &cData[i][j][0];
copy(blob, sourceData, 0, sourceDataSize);
}
}
}
/*! \brief Runtime load of the C++ data code generated by dumpC() */
void load(const std::vector<std::vector<std::vector<DType>>>& cData,
const BlobVectorType type) {
CHECK_LT(type, cData.size());
for (size_t j = 0, nj = cData[type].size(); j < nj; ++j) {
const TBlob& blob = getBlobVect(type)[j];
const size_t sourceDataSize = cData[type][j].size();
CHECK_EQ(sourceDataSize, blob.Size());
const DType *sourceData = &cData[type][j][0];
copy(blob, sourceData, 0, sourceDataSize);
}
}
/*! \brief Runtime load of the C++ data code generated by dumpC() */
void load(const std::vector<std::vector<std::vector<DType>>>& cData,
const BlobVectorType type, const int idx) {
CHECK_LT(type, cData.size());
CHECK_LT(idx, cData[type].size());
const TBlob& blob = getBlobVect(type)[idx];
const size_t sourceDataSize = cData[type][idx].size();
CHECK_EQ(sourceDataSize, blob.Size());
const DType *sourceData = &cData[type][idx][0];
copy(blob, sourceData, 0, sourceDataSize);
}
void FillRandom() {
for (size_t j = 0, jn = this->c_.all_blob_vects_.size(); j < jn; ++j) {
std::vector<TBlob> *data_vect = this->c_.all_blob_vects_[j];
if (data_vect) {
for (size_t i = 0, n = data_vect->size(); i < n; ++i) {
OperatorDataInitializer<DType>::FillRandom((*data_vect)[i]);
}
}
}
}
std::vector<TBlob>& inputs() { return c_.blob_input_vec_; }
const std::vector<TBlob>& inputs() const { return c_.blob_input_vec_; }
std::vector<TBlob>& outputs() { return c_.blob_output_vec_; }
const std::vector<TBlob>& outputs() const { return c_.blob_output_vec_; }
std::vector<TBlob>& bwd_inputs() { return c_.blob_out_grad_; }
std::vector<TBlob>& bwd_outputs() { return c_.blob_in_grad_; }
/*! \brief Input and output blobs */
OpContext opContext_;
std::vector<TShape> shape_input_vec_;
struct OpData {
std::vector<TBlob> blob_input_vec_;
std::vector<TBlob> blob_output_vec_;
std::vector<TBlob> blob_aux_states_;
std::vector<TBlob> blob_in_grad_;
std::vector<TBlob> blob_out_grad_; // Remaining err (loss) pushing back upstream
std::vector<std::vector<TBlob> *> all_blob_vects_;
inline OpData() {
all_blob_vects_.push_back(&blob_input_vec_);
all_blob_vects_.push_back(&blob_output_vec_);
all_blob_vects_.push_back(&blob_aux_states_);
all_blob_vects_.push_back(&blob_in_grad_);
all_blob_vects_.push_back(&blob_out_grad_); // Remaining err (loss) pushing back upstream
}
virtual ~OpData() {}
};
#if MXNET_USE_CUDA
class GPUOpData : public OpData {
GPUOpData() = delete;
GPUOpData(const GPUOpData& o) = delete;
public:
inline GPUOpData(const OpData& cpuData, OpContext *opContext)
: cpuData_(cpuData)
, allocGPUStream_(opContext) {
// Copy CPU->GPU
CHECK_EQ(gpuBlobs_.size(), 0U);
CHECK_EQ(cpuData_.all_blob_vects_.size(), this->all_blob_vects_.size());
for (size_t bvt = 0, nbvt = cpuData_.all_blob_vects_.size(); bvt < nbvt; ++bvt) {
std::vector<TBlob>& bv_src = *cpuData_.all_blob_vects_[bvt];
std::vector<TBlob>& bvt_dest = *this->all_blob_vects_[bvt];
for (size_t i = 0, n = bv_src.size(); i < n; ++i) {
const TBlob& srcBlob = bv_src[i];
TBlob *destBlob = allocateBlob(&gpuBlobs_, &bvt_dest, srcBlob.shape_,
true, srcBlob.type_flag_);
Context cpu_ctx, gpu_ctx;
cpu_ctx.dev_type = Context::kCPU;
gpu_ctx.dev_type = Context::kGPU;
cpu_ctx.dev_id = gpu_ctx.dev_id = 0;
mxnet::ndarray::Copy<cpu, gpu>(srcBlob, destBlob, cpu_ctx,
gpu_ctx, allocGPUStream_.opContext_.run_ctx);
}
}
cudaDeviceSynchronize();
}
inline ~GPUOpData() {
// Copy GPU->CPU
cudaDeviceSynchronize();
for (size_t bvt = 0, nbvt = this->all_blob_vects_.size(); bvt < nbvt; ++bvt) {
std::vector<TBlob>& bv_src = *this->all_blob_vects_[bvt];
std::vector<TBlob>& bvt_dest = *cpuData_.all_blob_vects_[bvt];
for (size_t i = 0, n = bv_src.size(); i < n; ++i) {
const TBlob& srcBlob = bv_src[i];
TBlob *destBlob = &bvt_dest[i];
Context cpu_ctx, gpu_ctx;
cpu_ctx.dev_type = Context::kCPU;
gpu_ctx.dev_type = Context::kGPU;
cpu_ctx.dev_id = gpu_ctx.dev_id = 0;
mxnet::ndarray::Copy<gpu, cpu>(srcBlob, destBlob, gpu_ctx,
cpu_ctx, allocGPUStream_.opContext_.run_ctx);
}
}
gpuBlobs_.clear(); // Force deallocation of the GPU blob data
cudaDeviceSynchronize();
}
private:
/*! \brief Reference to the src/dest CPU data */
const OpData& cpuData_;
/*! \brief The GPU-allocated blobs */
std::list<std::unique_ptr<test::StandaloneBlob>> gpuBlobs_;
/*! \brief Scoped GPU stream */
GPUStreamScope allocGPUStream_;
};
#endif // MXNET_USE_CUDA
protected:
OpData c_;
/*! \brief Allocate the operator's resource requests */
void allocateResources(const std::vector<ResourceRequest>& reqs) {
std::map<Context, Resource> cached_temp;
Context ctx;
ctx.dev_type = isGPU_ ? Context::kGPU : Context::kCPU;
ctx.dev_id = 0;
for (const ResourceRequest& req : reqs) {
if (req.type == ResourceRequest::kTempSpace) {
if (cached_temp.count(ctx) != 0) {
opContext_.requested.push_back(cached_temp.at(ctx));
} else {
Resource r = ResourceManager::Get()->Request(ctx, req);
opContext_.requested.push_back(r);
cached_temp[ctx] = r;
}
} else if (req.type == ResourceRequest::kRandom) {
opContext_.requested.push_back(ResourceManager::Get()->Request(ctx, req));
} else {
LOG(FATAL) << "resource type not yet supported";
}
}
}
/*! \brief Locally allocate a managed TBlob and insert into the supplied vector */
static TBlob *allocateBlob(std::list<std::unique_ptr<test::StandaloneBlob>> *standalone_blobs,
std::vector<TBlob> *dest,
const TShape& shape,
const bool isGPU,
const int dtype) {
test::StandaloneBlob *blob = new test::StandaloneBlob(shape, isGPU, dtype);
CHECK_NE(blob, static_cast<TBlob *>(nullptr));
standalone_blobs->push_back(std::unique_ptr<test::StandaloneBlob>(blob));
(*dest).push_back(*blob);
return blob;
}
/*! \brief Locally allocate a managed TBlob and insert into the supplied vector */
inline TBlob *allocateBlob(std::vector<TBlob> *dest, const TShape& shape,
const bool isGPU, const int dtype) {
return allocateBlob(&standalone_blobs_, dest, shape, isGPU, dtype);
}
/*! \brief Performance timing categories */
enum TimingId {
Forward,
Backward
};
/*! \brief The operator */
std::unique_ptr<Operator> op_;
/*! \brief Is this for a GPU? */
const bool isGPU_;
/*! \brief Assure that the Forward initialized only once */
std::atomic<int> initializeForward_;
/*! \brief Assure that the Forward initialized only once */
std::atomic<int> initializeBackward_;
/*! \brief Assure that the callback is initialized only once */
std::atomic<int> initializeCallback_;
/*! \brief scoped lifecycle management of allocated blobs */
std::list<std::unique_ptr<test::StandaloneBlob>> standalone_blobs_;
};
template<typename OperatorProp, typename DType, typename AccReal>
using LegacyOpRunner =
mxnet::test::OperatorRunner<OperatorProp, LegacyOperatorExecutor<DType, AccReal>>;
} // namespace op
} // namespace test
} // namespace mxnet
#endif // TEST_LEGACY_OP_H_
| [
"wangxb-1986@163.com"
] | wangxb-1986@163.com |
4a833c031131726463a1a5a5d4c5856d3def3ddd | 95025210b9131d8bbddfe2f4b85e0cf683596c1f | /Src/GeneralInput/DeckBMOptionDlg.cpp | 650be7aeda809367227c11f01e7cd92225f31cd8 | [] | no_license | SamuelBacaner1112/APlate | ece78b86f4cda173c7e1c3d3776d3aaf0ef1d341 | 0d89bd5beadc811d9d33c75f3110903f8b4f256e | refs/heads/master | 2023-01-24T07:50:59.851986 | 2020-12-09T00:19:05 | 2020-12-09T00:19:05 | 319,794,441 | 0 | 2 | null | null | null | null | UHC | C++ | false | false | 120,856 | cpp | // DeckBMOptionDlg.cpp : implementation file
//
#include "stdafx.h"
#include "GeneralInput.h"
#include "../APlateCalc/APlateCalc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDeckBMOptionDlg dialog
CDeckBMOptionDlg::CDeckBMOptionDlg(CWnd* pParent /*=NULL*/)
: CGeneralBaseDlg(CDeckBMOptionDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CDeckBMOptionDlg)
//}}AFX_DATA_INIT
AfxInitRichEdit();
}
void CDeckBMOptionDlg::DoDataExchange(CDataExchange* pDX)
{
CGeneralBaseDlg::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDeckBMOptionDlg)
DDX_Control(pDX, IDC_CHECK_ELECWIREHOLE, m_ElecWireHole);
DDX_Control(pDX, IDC_CHECK_TIMBER, m_Timber);
DDX_Control(pDX, IDC_CHECK_WING_WALL, m_WingWall);
// DDX_Control(pDX, IDC_BUTTON_ALL_CANCEL, m_AllCancel);
// DDX_Control(pDX, IDC_BUTTON_ALL_CHECK, m_AllCheck);
DDX_Control(pDX, IDC_CHECK_DRAIN_BRIDGESURFACE, m_DrainBridgeSurface);
DDX_Control(pDX, IDC_CHECK_SHADE, m_Shade);
DDX_Control(pDX, IDC_CHECK_PAVE, m_Pave);
DDX_Control(pDX, IDC_CHECK_NOTCH, m_Notch);
DDX_Control(pDX, IDC_CHECK_WATER_DRAW, m_WaterDraw);
DDX_Control(pDX, IDC_CHECK_TACK_COATING, m_TackCoating);
DDX_Control(pDX, IDC_CHECK_STYROFOAM, m_Styrofoam);
DDX_Control(pDX, IDC_CHECK_STEEL_QUANTITY, m_SteelQuantity);
DDX_Control(pDX, IDC_CHECK_SPACER, m_Spacer);
DDX_Control(pDX, IDC_CHECK_SOUND_PROOF, m_SoundProof);
DDX_Control(pDX, IDC_CHECK_SHRINKAGE_CONCRETE, m_ShrinkageConcrete);
DDX_Control(pDX, IDC_CHECK_REBAR_MANUFACTURE, m_RebarManufacture);
DDX_Control(pDX, IDC_CHECK_PARAPET, m_Parapet);
DDX_Control(pDX, IDC_CHECK_PAINT, m_Paint);
DDX_Control(pDX, IDC_CHECK_MOLD, m_Mold);
DDX_Control(pDX, IDC_CHECK_GUARD_FENCE, m_GuardFence);
DDX_Control(pDX, IDC_CHECK_EXPLAIN_PLATE, m_ExplainPlate);
DDX_Control(pDX, IDC_CHECK_EXPANSIONJOINT_COVER, m_ExpansionJointCover);
DDX_Control(pDX, IDC_CHECK_EXPANSIONJOINT, m_ExpansionJoint);
DDX_Control(pDX, IDC_CHECK_ESTABLISH_TBM, m_EstablishTBM);
DDX_Control(pDX, IDC_CHECK_DROPPING_PREVENT, m_DroppingPreVent);
DDX_Control(pDX, IDC_CHECK_DRAIN_ESTABLISH, m_DrainEstablish);
DDX_Control(pDX, IDC_CHECK_CONCRETE_PLACING, m_ConcretePlacing);
DDX_Control(pDX, IDC_CHECK_CONCRETE_BUY, m_ConcreteBuy);
DDX_Control(pDX, IDC_CHECK_BRIDGE_NAMEPLATE, m_BridgeNamePlate);
DDX_Control(pDX, IDC_CHECK_BRIDGE_NAME, m_BridgeName);
DDX_Control(pDX, IDC_RICHEDIT_CONTENTS, m_OptContents);
//}}AFX_DATA_MAP
DDX_GridControl(pDX, IDC_GRID, m_Grid); // 반드시 IDC_GRID 로 정의
DDX_Control(pDX, IDC_BUTTON_OPTION_SAVE, m_btnOptSave);
DDX_Control(pDX, IDC_BUTTON_OPTION_LOAD, m_btnOptLoad);
DDX_Control(pDX, IDC_BUTTON_ALL_CHECK, m_AllCheck);
DDX_Control(pDX, IDC_BUTTON_ALL_CANCEL, m_AllCancel);
}
BEGIN_MESSAGE_MAP(CDeckBMOptionDlg, CGeneralBaseDlg)
//{{AFX_MSG_MAP(CDeckBMOptionDlg)
ON_BN_CLICKED(IDC_CHECK_CONCRETE_BUY, OnCheckConcreteBuy)
ON_BN_CLICKED(IDC_CHECK_CONCRETE_PLACING, OnCheckConcretePlacing)
ON_BN_CLICKED(IDC_CHECK_MOLD, OnCheckMold)
ON_BN_CLICKED(IDC_CHECK_SPACER, OnCheckSpacer)
ON_BN_CLICKED(IDC_CHECK_REBAR_MANUFACTURE, OnCheckRebarManufacture)
ON_BN_CLICKED(IDC_CHECK_PAVE, OnCheckPave)
ON_BN_CLICKED(IDC_CHECK_TACK_COATING, OnCheckTackCoating)
ON_BN_CLICKED(IDC_CHECK_DRAIN_BRIDGESURFACE, OnCheckDrainBridgesurface)
ON_BN_CLICKED(IDC_CHECK_BRIDGE_NAME, OnCheckBridgeName)
ON_BN_CLICKED(IDC_CHECK_BRIDGE_NAMEPLATE, OnCheckBridgeNameplate)
ON_BN_CLICKED(IDC_CHECK_EXPLAIN_PLATE, OnCheckExplainPlate)
ON_BN_CLICKED(IDC_CHECK_ESTABLISH_TBM, OnCheckEstablishTbm)
ON_BN_CLICKED(IDC_CHECK_STYROFOAM, OnCheckStyrofoam)
ON_BN_CLICKED(IDC_CHECK_EXPANSIONJOINT, OnCheckExpansionjoint)
ON_BN_CLICKED(IDC_CHECK_EXPANSIONJOINT_COVER, OnCheckExpansionjointCover)
ON_BN_CLICKED(IDC_CHECK_SHRINKAGE_CONCRETE, OnCheckShrinkageConcrete)
ON_BN_CLICKED(IDC_CHECK_WATER_DRAW, OnCheckWaterDraw)
ON_BN_CLICKED(IDC_CHECK_NOTCH, OnCheckNotch)
ON_BN_CLICKED(IDC_CHECK_GUARD_FENCE, OnCheckGuardFence)
ON_BN_CLICKED(IDC_CHECK_SOUND_PROOF, OnCheckSoundProof)
ON_BN_CLICKED(IDC_CHECK_PARAPET, OnCheckParapet)
ON_BN_CLICKED(IDC_CHECK_SHADE, OnCheckShade)
ON_BN_CLICKED(IDC_CHECK_DROPPING_PREVENT, OnCheckDroppingPrevent)
ON_BN_CLICKED(IDC_CHECK_STEEL_QUANTITY, OnCheckSteelQuantity)
ON_BN_CLICKED(IDC_CHECK_PAINT, OnCheckPaint)
ON_BN_CLICKED(IDC_CHECK_DRAIN_ESTABLISH, OnCheckDrainEstablish)
ON_BN_CLICKED(IDC_BUTTON_ALL_CHECK, OnButtonAllCheck)
ON_BN_CLICKED(IDC_BUTTON_ALL_CANCEL, OnButtonAllCancel)
ON_BN_CLICKED(IDC_CHECK_WING_WALL, OnCheckWingWall)
ON_BN_CLICKED(IDC_CHECK_TIMBER, OnCheckTimber)
ON_BN_CLICKED(IDC_CHECK_ELECWIREHOLE, OnCheckElecWireHole)
ON_BN_CLICKED(IDC_BUTTON_OPTION_SAVE, OnButtonOptionSave)
ON_BN_CLICKED(IDC_BUTTON_OPTION_LOAD, OnButtonOptionLoad)
//}}AFX_MSG_MAP
ON_MESSAGE(WM_USER_BUTTON_PUSH, OnReceive)
ON_NOTIFY(GVN_CELL_CHANGED_DATA, IDC_GRID, OnCellChangedData)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDeckBMOptionDlg message handlers
void CDeckBMOptionDlg::OnPreInitDialog()
{
CSteelUWeight *pUWeight = m_pStd->m_pDataManage->GetSteelUWeight();
m_nSelectedOpt = 0;
m_nCols = 2;
m_nRows = 1;
m_Grid.SetColumnCount(m_nCols);
m_Grid.SetRowCount(m_nRows);
m_Grid.SetFiexedRows(1);
m_Grid.SetFixedCols(1);
m_Grid.SetTextMatrix(0, 0, _T("구 분"));
m_Grid.SetTextMatrix(0, 1, _T("적용 여부"));
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 140);
m_OptContents.SetReadOnly();
m_OptContents.SetBackgroundColor(FALSE, RGB(230, 255, 255));
CString sText = _T("");
sText.Format("%s포장", pUWeight->GetTypePave());
m_Pave.SetWindowText(sText);
SetResize(IDC_RICHEDIT_CONTENTS, SZ_TOP_LEFT, SZ_BOTTOM_CENTER);
SetResize(IDC_STATIC_OPT_DETAIL, SZ_MIDDLE_CENTER, SZ_MIDDLE_RIGHT);
SetResize(IDC_GRID, SZ_MIDDLE_CENTER, SZ_BOTTOM_RIGHT);
SetResize(IDC_CHECK_CONCRETE_BUY, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_CONCRETE_PLACING, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_MOLD, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_SPACER, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_REBAR_MANUFACTURE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_PAVE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_TACK_COATING, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_DRAIN_BRIDGESURFACE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_BRIDGE_NAME, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_BRIDGE_NAMEPLATE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_EXPLAIN_PLATE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_ESTABLISH_TBM, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_STYROFOAM, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_EXPANSIONJOINT, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_EXPANSIONJOINT_COVER, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_SHRINKAGE_CONCRETE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_WATER_DRAW, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_NOTCH, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_GUARD_FENCE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_SOUND_PROOF, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_PARAPET, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_SHADE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_DROPPING_PREVENT, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_STEEL_QUANTITY, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_PAINT, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_DRAIN_ESTABLISH, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_WING_WALL, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_TIMBER, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_CHECK_ELECWIREHOLE, SZ_TOP_CENTER, SZ_TOP_CENTER);
SetResize(IDC_BUTTON_ALL_CHECK, SZ_BOTTOM_RIGHT, SZ_BOTTOM_RIGHT);
SetResize(IDC_BUTTON_ALL_CANCEL, SZ_BOTTOM_RIGHT, SZ_BOTTOM_RIGHT);
SetResize(IDC_BUTTON_OPTION_LOAD, SZ_BOTTOM_LEFT, SZ_BOTTOM_LEFT);
SetResize(IDC_BUTTON_OPTION_SAVE, SZ_BOTTOM_LEFT, SZ_BOTTOM_LEFT);
}
void CDeckBMOptionDlg::SetGridTitle()
{
long nRow = 0;
long nCol = 0;
for(nRow=0; nRow<m_Grid.GetRowCount(); nRow++)
{
for(nCol=0; nCol<m_Grid.GetColumnCount(); nCol++)
{
m_Grid.SetItemState(nRow,nCol,0);
m_Grid.SetCellType(nRow,nCol,CT_EDIT);
m_Grid.SetTextBkColor(RGBEDITABLE);
if(nRow != 0 && nCol != 0)
m_Grid.SetItemBkColour(nRow, nCol, RGBEDITABLE);
}
}
m_Grid.SetColumnCount(m_nCols);
m_Grid.SetRowCount(m_nRows);
m_Grid.SetRowHeightAll(20);
m_Grid.SetFiexedRows(1);
m_Grid.SetFixedCols(1);
m_Grid.SetTextMatrix(0, 0, _T("구 분"));
m_Grid.SetTextMatrix(0, 1, _T("적용 여부"));
for(nRow=1; nRow<m_nRows; nRow++)
{
for(nCol=1; nCol<m_nCols; nCol++)
m_Grid.SetItemBkColour(nRow, nCol, RGB(230, 255, 255));
}
}
void CDeckBMOptionDlg::SetDataInit()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CStringArray szArray;
GetBMOptionContents(szArray);
m_OptContents.SetSel(0, -1);
m_OptContents.Clear();
for(long n = 0; n < szArray.GetSize(); n++)
m_OptContents.ReplaceSel(szArray.GetAt(n));
m_ConcreteBuy.SetCheck(pBMOpt->m_bConcreteBuy);
m_ConcreteBuy.Invalidate();
m_ConcretePlacing.SetCheck(pBMOpt->m_bConcretePlacing);
m_Mold.SetCheck(pBMOpt->m_bMold);
m_Spacer.SetCheck(pBMOpt->m_bSpacer);
m_RebarManufacture.SetCheck(pBMOpt->m_structRebarManufacture.m_bApply);
m_Pave.SetCheck(pBMOpt->m_structPave.m_bApply);
m_TackCoating.SetCheck(pBMOpt->m_structTackCoating.m_bApply);
m_DrainBridgeSurface.SetCheck(pBMOpt->m_bDrainBridgeSurface);
m_BridgeName.SetCheck(pBMOpt->m_structBridgeName.m_bApply);
m_BridgeNamePlate.SetCheck(pBMOpt->m_structBridgeNamePlate.m_bApply);
m_ExplainPlate.SetCheck(pBMOpt->m_structExplainPlate.m_bApply);
m_EstablishTBM.SetCheck(pBMOpt->m_structEstablishTBM.m_bApply);
m_Styrofoam.SetCheck(pBMOpt->m_structStyrofoam.m_bApply);
m_ExpansionJoint.SetCheck(pBMOpt->m_structExpansionJoint.m_bApply);
m_ExpansionJointCover.SetCheck(pBMOpt->m_structExpansionJointCover.m_bApply);
m_ShrinkageConcrete.SetCheck(pBMOpt->m_structShrinkageConcrete.m_bApply);
m_WaterDraw.SetCheck(pBMOpt->m_bWaterDraw);
m_Notch.SetCheck(pBMOpt->m_structNotch.m_bApply);
m_GuardFence.SetCheck(pBMOpt->m_structGuardFence.m_bApply);
m_SoundProof.SetCheck(pBMOpt->m_structSoundProof.m_bApply);
m_Parapet.SetCheck(pBMOpt->m_structParapet.m_bApply);
m_Shade.SetCheck(pBMOpt->m_bShade);
m_DroppingPreVent.SetCheck(pBMOpt->m_structDroppingPrevent.m_bApply);
m_SteelQuantity.SetCheck(pBMOpt->m_bSteelQuantity);
m_Paint.SetCheck(pBMOpt->m_bPaint);
m_DrainEstablish.SetCheck(pBMOpt->m_bDrainEstablish);
m_WingWall.SetCheck(pBMOpt->m_structWingWall.m_bApply);
m_Timber.SetCheck(pBMOpt->m_structTimber.m_bApply);
m_ElecWireHole.SetCheck(pBMOpt->m_structElecWireHole.m_bApply);
UpdateData(FALSE);
}
void CDeckBMOptionDlg::SetDataSave()
{
}
BOOL CDeckBMOptionDlg::IsLeft(CString szApply)
{
if(szApply == _T("좌측적용")) return TRUE;
else if(szApply == _T("우측적용")) return FALSE;
else return FALSE;
return FALSE;
}
BOOL CDeckBMOptionDlg::IsApply(CString szApply)
{
if(szApply == _T("적용") || szApply == _T("좌측적용") || szApply == _T("우측적용") || szApply == _T("시점적용") || szApply == _T("종점적용") || szApply == _T("편측적용") || szApply == _T("단위 m당 수량"))
return TRUE;
if(szApply == _T("미적용") || szApply == _T("좌측미적용") || szApply == _T("우측미적용") || szApply == _T("시점미적용") || szApply == _T("종점미적용") || szApply == _T("양측적용") || szApply == _T("지점별 수량"))
return FALSE;
ASSERT(FALSE);
return FALSE;
}
CString CDeckBMOptionDlg::IsApply(BOOL bApply)
{
CString szApply = _T("");
if(bApply) szApply = _T("적용");
else szApply = _T("미적용");
return szApply;
}
CString CDeckBMOptionDlg::IsApplyStt(BOOL bApply)
{
CString szApply = _T("");
if(bApply) szApply = _T("시점적용");
else szApply = _T("시점미적용");
return szApply;
}
CString CDeckBMOptionDlg::IsApplyEnd(BOOL bApply)
{
CString szApply = _T("");
if(bApply) szApply = _T("종점적용");
else szApply = _T("종점미적용");
return szApply;
}
CString CDeckBMOptionDlg::IsApplyLeft(BOOL bApply)
{
CString szApply = _T("");
if(bApply) szApply = _T("좌측적용");
else szApply = _T("좌측미적용");
return szApply;
}
CString CDeckBMOptionDlg::IsApplyRight(BOOL bApply)
{
CString szApply = _T("");
if(bApply) szApply = _T("우측적용");
else szApply = _T("우측미적용");
return szApply;
}
void CDeckBMOptionDlg::OnGridRedraw()
{
switch(m_nSelectedOpt)
{
case BMOPT_CONCRETE_BYE :
OnCheckConcreteBuy();
break;
case BMOPT_CONCRETE_PLACING :
OnCheckConcretePlacing();
break;
case BMOPT_MOLD :
OnCheckMold();
break;
case BMOPT_SPACER :
OnCheckSpacer();
break;
case BMOPT_REBAR_MANUFACTURE :
OnCheckRebarManufacture();
break;
case BMOPT_PAVE :
OnCheckPave();
break;
case BMOPT_TACKCOATING :
OnCheckTackCoating();
break;
case BMOPT_DRAINBRIDGESURFACE :
OnCheckDrainBridgesurface();
break;
case BMOPT_BRIDGENAME :
OnCheckBridgeName();
break;
case BMOPT_BRIDGENAME_PLATE :
OnCheckBridgeNameplate();
break;
case BMOPT_EXPLAIN_PLATE :
OnCheckExplainPlate();
break;
case BMOPT_ESTABLISH_TBM :
OnCheckEstablishTbm();
break;
case BMOPT_STYROFOAM :
OnCheckStyrofoam();
break;
case BMOPT_EXPANSIONJOINT :
OnCheckExpansionjoint();
break;
case BMOPT_EXPANSIONJOINT_COVER :
OnCheckExpansionjointCover();
break;
case BMOPT_SHRINKAGE_CONCRETE :
OnCheckShrinkageConcrete();
break;
case BMOPT_WATER_DRAW :
OnCheckWaterDraw();
break;
case BMOPT_NOTCH :
OnCheckNotch();
break;
case BMOPT_GUARD_FENCE :
OnCheckGuardFence();
break;
case BMOPT_SOUND_PROOF :
OnCheckSoundProof();
break;
case BMOPT_PARAPET :
OnCheckParapet();
break;
case BMOPT_SHADE :
OnCheckShade();
break;
case BMOPT_DROPPING_PREVENT :
OnCheckDroppingPrevent();
break;
case BMOPT_STEEL_QUANTITY :
OnCheckSteelQuantity();
break;
case BMOPT_PAINT :
OnCheckPaint();
break;
case BMOPT_DRAIN_ESTABLISH :
OnCheckDrainEstablish();
break;
case BMOPT_WING_WALL :
OnCheckWingWall();
break;
case BMOPT_TIMBER :
OnCheckTimber();
break;
case BMOPT_ELECWIREHOLE :
OnCheckElecWireHole();
break;
}
}
void CDeckBMOptionDlg::SetDataDefault()
{
CPlateBridgeApp *pDB = m_pStd->m_pDataManage->GetBridge();
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CCalcData *pData = m_pStd->m_pDataManage->GetCalcData();
CCalcFloor CalcFloor(m_pStd->m_pDataManage);
CCentSeparation *pLCen = NULL;
CCentSeparation *pRCen = NULL;
double dGuardHeightL = 0, dGuardHeightR = 0;
if(pDB->GetGuardFencesu() > 0)
{
pLCen = pDB->GetGuardFence(0);
pRCen = pDB->GetGuardFence(pDB->GetGuardWallSu()-1);
dGuardHeightL = pLCen->GetHeight();
dGuardHeightR = pRCen->GetHeight();
}
pBMOpt->SetDataDefault();
double dWingLeftStt = pBMOpt->m_structWingWall.m_dLengthLeftStt;
double dWingLeftEnd = pBMOpt->m_structWingWall.m_dLengthLeftEnd;
double dWingRighStt = pBMOpt->m_structWingWall.m_dLengthRighStt;
double dWingRighEnd = pBMOpt->m_structWingWall.m_dLengthRighEnd;
pBMOpt->m_structParapet.m_dGuardLength[0] = pADeckData->GetLengthSlabTotal(JONGBASEPOS_SLABLEFT) + dWingLeftStt + dWingLeftEnd;
pBMOpt->m_structParapet.m_dGuardLength[1] = pADeckData->GetLengthSlabTotal(JONGBASEPOS_SLABRIGHT) + dWingRighStt + dWingRighEnd;
pBMOpt->m_structParapet.m_dCurbLength = (pBMOpt->m_structParapet.m_dGuardLength[0] + pBMOpt->m_structParapet.m_dGuardLength[1])/2;
double dLHeight = pData->DESIGN_FLOOR_DATA[FLOOR_LEFT].m_dBangEmHeight;
double dRHeight = pData->DESIGN_FLOOR_DATA[FLOOR_RIGHT].m_dBangEmHeight;
long nGuardTypeL = CalcFloor.GetGuardWallType(FLOOR_LEFT);
long nGuardTypeR = CalcFloor.GetGuardWallType(FLOOR_RIGHT);
BOOL bBangEmExistL = (pData->DESIGN_FLOOR_DATA[FLOOR_LEFT].m_bBangEm && nGuardTypeL<=8) ? TRUE : FALSE;
BOOL bBangEmExistR = (pData->DESIGN_FLOOR_DATA[FLOOR_RIGHT].m_bBangEm && nGuardTypeR<=8) ? TRUE : FALSE;
if(bBangEmExistL)
pBMOpt->m_structSoundProof.m_dLHeight = frM(dLHeight - toM(dGuardHeightL));
if(bBangEmExistR)
pBMOpt->m_structSoundProof.m_dRHeight = frM(dRHeight - toM(dGuardHeightR));
OnGridRedraw();
}
void CDeckBMOptionDlg::DrawInputDomyunView(BOOL bZoomAll)
{
CDomyun *pDom = m_pView->GetDomyun();
pDom->ClearEtt(TRUE);
CGeneralBaseDlg::DrawInputDomyunView(bZoomAll);
}
BOOL CDeckBMOptionDlg::PreTranslateMessage(MSG* pMsg)
{
if(m_Grid.TranslateMsg(pMsg))
return m_Grid.PreTranslateMessage(pMsg);
BOOL bReturn = CGeneralBaseDlg::PreTranslateMessage(pMsg);
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CStringArray strCombo;
if(pMsg->message == WM_LBUTTONDOWN || pMsg->message == WM_LBUTTONDBLCLK)
{
CCellID next = m_Grid.GetFocusCell();
switch(m_nSelectedOpt)
{
case BMOPT_CONCRETE_BYE :
case BMOPT_CONCRETE_PLACING :
case BMOPT_MOLD :
case BMOPT_SPACER :
case BMOPT_PAVE :
case BMOPT_TACKCOATING :
case BMOPT_DRAINBRIDGESURFACE :
case BMOPT_SHRINKAGE_CONCRETE :
case BMOPT_WATER_DRAW :
case BMOPT_GUARD_FENCE :
case BMOPT_SOUND_PROOF :
case BMOPT_SHADE :
case BMOPT_STEEL_QUANTITY :
case BMOPT_PAINT :
case BMOPT_BRIDGENAME :
case BMOPT_BRIDGENAME_PLATE :
case BMOPT_EXPLAIN_PLATE :
case BMOPT_ESTABLISH_TBM :
case BMOPT_EXPANSIONJOINT_COVER :
case BMOPT_PARAPET :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
break;
case BMOPT_STYROFOAM :
if(next.col == 1)
{
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 2 && next.col == 1)
{
strCombo.Add("좌측적용");
strCombo.Add("우측적용");
m_Grid.SetComboString(strCombo);
}
else if(next.row ==3 && next.col == 1)
{
strCombo.Add("10");
strCombo.Add("20");
m_Grid.SetComboString(strCombo);
}
}
break;
case BMOPT_EXPANSIONJOINT :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 2 && next.col == 1)
{
// strCombo.Add("단위 m당 수량");
strCombo.Add("지점별 수량");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 4 || next.row == 5 || next.row == 6 || next.row == 8)
{
if(next.col == 1)
GetComboRebarDia(strCombo);
m_Grid.SetComboString(strCombo);
}
break;
case BMOPT_NOTCH :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 2 && next.col == 1)
{
strCombo.Add("좌측적용");
strCombo.Add("우측적용");
strCombo.Add("양측적용");
m_Grid.SetComboString(strCombo);
}
break;
case BMOPT_WING_WALL :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
break;
case BMOPT_DRAIN_ESTABLISH :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 2 && next.col == 1)
{
strCombo.Add("하천용");
strCombo.Add("육교용");
strCombo.Add("하천및육교용");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 3 && next.col == 1)
{
if(pBMOpt->m_nDrainEstablishType == WALKWAY || pBMOpt->m_nDrainEstablishType == RIVERWALKWAY)
{
strCombo.Add("TYPE 1 (건교부)");
strCombo.Add("TYPE 2");
m_Grid.SetComboString(strCombo);
}
}
break;
case BMOPT_TIMBER :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 2 && next.col == 1)
{
strCombo.Add("목재");
strCombo.Add("강관");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 3 && next.col == 1)
{
strCombo.Add("미적용");
strCombo.Add("좌측적용");
strCombo.Add("우측적용");
strCombo.Add("양측적용");
m_Grid.SetComboString(strCombo);
}
break;
case BMOPT_REBAR_MANUFACTURE :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
else if((next.row == 2 || next.row == 3 || next.row == 4) && next.col == 1)
{
strCombo.Add("매우복잡");
strCombo.Add("복잡");
strCombo.Add("보통");
strCombo.Add("간단");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
break;
case BMOPT_DROPPING_PREVENT :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
else if(next.row == 2 && next.col == 1)
{
strCombo.Add("수평적용");
strCombo.Add("수평수직적용");
m_Grid.SetComboString(strCombo);
}
break;
case BMOPT_ELECWIREHOLE :
if(next.row == 1 && next.col == 1)
{
strCombo.Add("적용");
strCombo.Add("미적용");
m_Grid.SetComboString(strCombo);
}
break;
}
}
return bReturn;
}
void CDeckBMOptionDlg::GetComboRebarDia(CStringArray &strComboArr)
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
double dSigmaY = toKgPCm2(pADeckData->m_SigmaY);
CString szFy;
szFy = GetCharRebarMark(dSigmaY);
strComboArr.Add(szFy+"13");
strComboArr.Add(szFy+"16");
strComboArr.Add(szFy+"19");
strComboArr.Add(szFy+"22");
strComboArr.Add(szFy+"25");
strComboArr.Add(szFy+"29");
strComboArr.Add(szFy+"32");
strComboArr.Add(szFy+"35");
}
void CDeckBMOptionDlg::GetBMOptionContents(CStringArray &Arr)
{
CPlateBridgeApp *pDB = m_pStd->m_pDataManage->GetBridge();
CGlobarOption *pGlopt = m_pStd->m_pDataManage->GetGlobalOption();
CSteelUWeight *pUWeight = m_pStd->m_pDataManage->GetSteelUWeight();
CADeckData *pADeckData = m_pStd->m_pDeckData;
CCalcData *pData = m_pStd->m_pDataManage->GetCalcData();
CCalcFloor CalcFloor(m_pStd->m_pDataManage);
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CString sText = _T("");
double dSigmaY = toKgPCm2(pADeckData->m_SigmaY);
sText.Format("\n"); Arr.Add(sText);
sText.Format(" ☞ 수량 출력 옵션 설정 내용 ☜ \n\n"); Arr.Add(sText);
sText.Format(" 1. 콘크리트 구입 : %s\n", IsApply(pBMOpt->m_bConcreteBuy)); Arr.Add(sText);
sText.Format(" 2. 콘크리트 타설 : %s\n", IsApply(pBMOpt->m_bConcretePlacing)); Arr.Add(sText);
sText.Format(" 3. 거 푸 집 : %s\n", IsApply(pBMOpt->m_bMold)); Arr.Add(sText);
sText.Format(" 4. 스페이셔 : %s\n", IsApply(pBMOpt->m_bSpacer)); Arr.Add(sText);
sText.Format(" 5. 철근가공 조립 : %s\n", IsApply(pBMOpt->m_structRebarManufacture.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structRebarManufacture.m_bApply)
{
CString szSpace = pDB->IsTUGir() ? _T(" ") : _T("");
sText.Format(" - 슬 래 브%s : %s \n", szSpace, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nSlabType));
Arr.Add(sText);
if(pDB->GetGuardWallSu() > 0)
{
sText.Format(" - 방 호 벽%s : %s \n", szSpace, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nGuardFenceType));
Arr.Add(sText);
}
if(pBMOpt->m_structExpansionJoint.m_bApply)
{
sText.Format(" - 신축이음%s : %s \n", szSpace, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nExpansionJointType));
Arr.Add(sText);
}
if(pDB->IsTUGir())
{
sText.Format(" - 구속콘크리트 : %s \n", pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nBindConcType));
Arr.Add(sText);
}
}
// 포장
if(pBMOpt->m_structPave.m_bApply) sText.Format(" 6. %s 포장 : %.0f mm\n", pUWeight->GetTypePave(), pBMOpt->m_structPave.m_dPaveThick);
else sText.Format(" 6. %s 포장 : %s\n", pUWeight->GetTypePave(), IsApply(pBMOpt->m_structPave.m_bApply));
Arr.Add(sText);
if(pBMOpt->m_structTackCoating.m_bApply) sText.Format(" 7. 택 코 팅 : %.1f 배\n", pBMOpt->m_structTackCoating.m_dTackCoating);
else sText.Format(" 7. 택 코 팅 : %s\n", IsApply(pBMOpt->m_structTackCoating.m_bApply));
Arr.Add(sText);
sText.Format(" 8. 교면방수 : %s\n", IsApply(pBMOpt->m_bDrainBridgeSurface)); Arr.Add(sText);
sText.Format(" 9. 교 명 주 : %s\n", IsApply(pBMOpt->m_structBridgeName.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structBridgeName.m_bApply)
{
sText.Format(" - 설치갯수 : %d EA\n", pBMOpt->m_structBridgeName.m_nQty); Arr.Add(sText);
}
sText.Format(" 10. 교 명 판 : %s\n", IsApply(pBMOpt->m_structBridgeNamePlate.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structBridgeNamePlate.m_bApply)
{
sText.Format(" - 설치갯수 : %d EA\n", pBMOpt->m_structBridgeNamePlate.m_nQty); Arr.Add(sText);
}
sText.Format(" 11. 설 명 판 : %s\n", IsApply(pBMOpt->m_structExplainPlate.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structExplainPlate.m_bApply)
{
sText.Format(" - 설치갯수 : %d EA\n", pBMOpt->m_structExplainPlate.m_nQty); Arr.Add(sText);
}
sText.Format(" 12. TBM 설치 : %s\n", IsApply(pBMOpt->m_structEstablishTBM.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structEstablishTBM.m_bApply)
{
sText.Format(" - 설치갯수 : %d EA\n", pBMOpt->m_structEstablishTBM.m_nQty); Arr.Add(sText);
}
if(pBMOpt->m_structStyrofoam.m_bApply)
{
if(pBMOpt->m_structStyrofoam.m_bLeft)
sText.Format(" 13. 스티로폼 : 좌측적용 %.0f mm\n", pBMOpt->m_structStyrofoam.m_dThick);
else
sText.Format(" 13. 스티로폼 : 우측적용 %.0f mm\n", pBMOpt->m_structStyrofoam.m_dThick);
}
else
sText.Format(" 13. 스티로폼 : %s\n", IsApply(pBMOpt->m_structStyrofoam.m_bApply));
Arr.Add(sText);
sText.Format(" 14. 신축이음 : %s\n", IsApply(pBMOpt->m_structExpansionJoint.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structExpansionJoint.m_bApply)
{
if(pBMOpt->m_structExpansionJoint.m_bUnitLength)
{
sText.Format(" - 수량기준 : 단위 m당 수량 (Kgf/m)\n");
Arr.Add(sText);
sText.Format(" - 시점 : %s - 종점 : %s\n", pBMOpt->m_structExpansionJoint.m_szSttName, pBMOpt->m_structExpansionJoint.m_szEndName);
Arr.Add(sText);
sText.Format(" %s %.3f Kgf/m %s %.3f Kgf/m\n",
pBMOpt->GetExpansionJointDia(TRUE, 0, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[0]),
pBMOpt->GetExpansionJointDia(FALSE, 0, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[0])); Arr.Add(sText);
sText.Format(" %s %.3f Kgf/m %s %.3f Kgf/m\n",
pBMOpt->GetExpansionJointDia(TRUE, 1, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[1]),
pBMOpt->GetExpansionJointDia(FALSE, 1, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[1])); Arr.Add(sText);
}
else
{
sText.Format(" - 수량기준 : 지점별 수량 (tonf)\n");
Arr.Add(sText);
sText.Format(" - 시점 : %s - 종점 : %s\n", pBMOpt->m_structExpansionJoint.m_szSttName, pBMOpt->m_structExpansionJoint.m_szEndName);
Arr.Add(sText);
sText.Format(" %s %.3f tonf %s %.3f tonf\n",
pBMOpt->GetExpansionJointDia(TRUE, 0, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[0]),
pBMOpt->GetExpansionJointDia(FALSE, 0, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[0])); Arr.Add(sText);
sText.Format(" %s %.3f tonf %s %.3f tonf\n",
pBMOpt->GetExpansionJointDia(TRUE, 1, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[1]),
pBMOpt->GetExpansionJointDia(FALSE, 1, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[1])); Arr.Add(sText);
}
sText.Format(" - 여유치수 : %.0f mm\n", pBMOpt->m_structExpansionJoint.m_dMargin); Arr.Add(sText);
sText.Format(" - 여유치적용 개수 : %d EA\n", pBMOpt->m_structExpansionJoint.m_nMarginsu); Arr.Add(sText);
}
sText.Format(" 15. 신축이음덮개 : %s\n", IsApply(pBMOpt->m_structExpansionJointCover.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structExpansionJointCover.m_bApply)
{
for(long n=0; n<7; n++)
{
sText.Format(" - %s 높이 : %.3f m %d EA\n", pBMOpt->GetExpansionJointCoverPos(n),
toM(pBMOpt->m_structExpansionJointCover.m_dHeight[n]), pBMOpt->m_structExpansionJointCover.m_nQty[n]);
Arr.Add(sText);
}
}
double dExpJointSttHeight = pGlopt->GetSttExpansionJointHeight();
double dExpJointSttWidth = pGlopt->GetSttExpansionJointWidth();
double dExpJointEndHeight = pGlopt->GetEndExpansionJointHeight();
double dExpJointEndWidth = pGlopt->GetEndExpansionJointWidth();
sText.Format(" 16. 무수축 콘크리트 : %s\n", IsApply(pBMOpt->m_structShrinkageConcrete.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structShrinkageConcrete.m_bApply)
{
sText.Format(" - 시점적용 갯수 : %.0f × %.0f %d EA\n", dExpJointSttWidth, dExpJointSttHeight, pBMOpt->m_structShrinkageConcrete.m_nSttQty); Arr.Add(sText);
sText.Format(" - 종점적용 갯수 : %.0f × %.0f %d EA\n", dExpJointEndWidth, dExpJointEndHeight, pBMOpt->m_structShrinkageConcrete.m_nEndQty); Arr.Add(sText);
}
sText.Format(" 17. 교면 물빼기 : %s\n", IsApply(pBMOpt->m_bWaterDraw)); Arr.Add(sText);
sText.Format(" 18. NOTCH : %s\n", IsApply(pBMOpt->m_structNotch.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structNotch.m_bApply)
{
sText.Format(" - 적용위치 : %s\n", pBMOpt->GetNotchPos(pBMOpt->m_structNotch.m_nApplyPos)); Arr.Add(sText);
sText.Format(" - NOTCH 종류 : %s\n", pBMOpt->m_structNotch.m_szNotchType); Arr.Add(sText);
}
if(pBMOpt->m_structGuardFence.m_bApply) sText.Format(" 19. 가드펜스 : %.3f m\n", toM(pBMOpt->m_structGuardFence.m_dHeight));
else sText.Format(" 19. 가드펜스 : %s\n", IsApply(pBMOpt->m_structGuardFence.m_bApply));
Arr.Add(sText);
if(pBMOpt->m_structSoundProof.m_bApply)
{
//방음벽 있나 없나 체크....070111....KB...
long nGuardTypeL = CalcFloor.GetGuardWallType(FLOOR_LEFT);
long nGuardTypeR = CalcFloor.GetGuardWallType(FLOOR_RIGHT);
BOOL bBangEmExistL = (pData->DESIGN_FLOOR_DATA[FLOOR_LEFT].m_bBangEm && nGuardTypeL<=8) ? TRUE : FALSE;
BOOL bBangEmExistR = (pData->DESIGN_FLOOR_DATA[FLOOR_RIGHT].m_bBangEm && nGuardTypeR<=8) ? TRUE : FALSE;
if(bBangEmExistL && bBangEmExistR)
sText.Format(" 20. 방음판넬 : %.3f m (좌) %.3f m (우)\n", toM(pBMOpt->m_structSoundProof.m_dLHeight), toM(pBMOpt->m_structSoundProof.m_dRHeight));
else if(bBangEmExistL && !bBangEmExistR)
sText.Format(" 20. 방음판넬 : %.3f m (좌)\n", toM(pBMOpt->m_structSoundProof.m_dLHeight));
else if(!bBangEmExistL && bBangEmExistR)
sText.Format(" 20. 방음판넬 : %.3f m (우)\n", toM(pBMOpt->m_structSoundProof.m_dRHeight));
}
else sText.Format(" 20. 방음판넬 : %s\n", IsApply(pBMOpt->m_structSoundProof.m_bApply));
Arr.Add(sText);
sText.Format(" 21. 난 간 : %s\n", IsApply(pBMOpt->m_structParapet.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structParapet.m_bApply)
{
sText.Format(" - %s : %s %s %.3f m\n",
pBMOpt->GetParapetType(DRIVEWAY), IsApplyLeft(pBMOpt->m_structParapet.m_bLeft[DRIVEWAY]),
IsApplyRight(pBMOpt->m_structParapet.m_bRight[DRIVEWAY]), toM(pBMOpt->m_structParapet.m_dHeight[DRIVEWAY])); Arr.Add(sText);
sText.Format(" - %s : %s %s %.3f m\n",
pBMOpt->GetParapetType(FOOTWAY), IsApplyLeft(pBMOpt->m_structParapet.m_bLeft[FOOTWAY]),
IsApplyRight(pBMOpt->m_structParapet.m_bRight[FOOTWAY]), toM(pBMOpt->m_structParapet.m_dHeight[FOOTWAY])); Arr.Add(sText);
sText.Format(" - %s : %s %s %.3f m\n",
pBMOpt->GetParapetType(DRIVE_FOOT_BOUNDARY), IsApplyLeft(pBMOpt->m_structParapet.m_bLeft[DRIVE_FOOT_BOUNDARY]),
IsApplyRight(pBMOpt->m_structParapet.m_bRight[DRIVE_FOOT_BOUNDARY]), toM(pBMOpt->m_structParapet.m_dHeight[DRIVE_FOOT_BOUNDARY]));Arr.Add(sText);
}
sText.Format(" 22. 차광망 : %s\n", IsApply(pBMOpt->m_bShade)); Arr.Add(sText);
sText.Format(" 23. 낙하물 방지공 : %s\n", IsApply(pBMOpt->m_structDroppingPrevent.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structDroppingPrevent.m_bApply)
{
sText.Format(" - 적 용 위 치 : %s", pBMOpt->GetDroppingPrevent(pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal));Arr.Add(sText);
sText.Format(" - 수평여유높이 : %.3f m\n", toM(pBMOpt->m_structDroppingPrevent.m_dHorSpaceHeight));Arr.Add(sText);
if(!pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal)
{
sText.Format(" - 수직여유높이 : %.3f m\n", toM(pBMOpt->m_structDroppingPrevent.m_dVerSpaceHeight));
Arr.Add(sText);
}
}
sText.Format(" 24. 강재수량 : %s\n", IsApply(pBMOpt->m_bSteelQuantity)); Arr.Add(sText);
sText.Format(" 25. 강교도장 : %s\n", IsApply(pBMOpt->m_bPaint)); Arr.Add(sText);
sText.Format(" 26. 배수시설 : %s\n", IsApply(pBMOpt->m_bDrainEstablish)); Arr.Add(sText);
if(pBMOpt->m_bDrainEstablish && (pBMOpt->m_nDrainEstablishType == RIVER || pBMOpt->m_nDrainEstablishType == RIVERWALKWAY))
{
sText.Format(" ⊙ 하 천 용\n"); Arr.Add(sText);
sText.Format(" - 집 수 구 (스테인레스 Plate) : %d EA\n", pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect); Arr.Add(sText);
sText.Format(" - 배 수 구 (스테인레스 강관) : %.3f m\n", toM(pBMOpt->m_structRiverDrainEstablish.m_dDrain)); Arr.Add(sText);
}
if(pBMOpt->m_bDrainEstablish && (pBMOpt->m_nDrainEstablishType == WALKWAY || pBMOpt->m_nDrainEstablishType == RIVERWALKWAY))
{
if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0)
{
sText.Format(" ⊙ 육 교 용 TYPE 1 (건교부)\n"); Arr.Add(sText);
sText.Format(" - 집 수 구 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect); Arr.Add(sText);
sText.Format(" - 연결집수거 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect); Arr.Add(sText);
sText.Format(" - 직 관 : %.3f m\n", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0])); Arr.Add(sText);
sText.Format(" - 곡 관 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]); Arr.Add(sText);
sText.Format(" - 연 결 부 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nJoint); Arr.Add(sText);
}
else
{
sText.Format(" ⊙ 육 교 용 TYPE 2\n"); Arr.Add(sText);
sText.Format(" - 집 수 구 (스테인레스 강관) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect); Arr.Add(sText);
sText.Format(" - 배 수 구 (스테인레스 강관) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nDrain); Arr.Add(sText);
sText.Format(" - 연결배수구 (8"" × 10"") : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain); Arr.Add(sText);
sText.Format(" - 직 관 (150A) : %.3f m\n", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0])); Arr.Add(sText);
sText.Format(" - 직 관 (200A) : %.3f m\n", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1])); Arr.Add(sText);
sText.Format(" - 곡 관 (150A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]); Arr.Add(sText);
sText.Format(" - 곡 관 (200A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1]); Arr.Add(sText);
sText.Format(" - 청 소 구 (150A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0]); Arr.Add(sText);
sText.Format(" - 청 소 구 (200A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1]); Arr.Add(sText);
sText.Format(" - 상부고정대 (150A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0]); Arr.Add(sText);
sText.Format(" - 상부고정대 (200A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1]); Arr.Add(sText);
sText.Format(" - 침 전 조 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting); Arr.Add(sText);
}
}
sText.Format(" 27. 날 개 벽 : %s\n", IsApply(pBMOpt->m_structWingWall.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structWingWall.m_bApply)
{
sText.Format(" - 좌측 => 시점 : %.3f m 종점 : %.3f m\n", toM(pBMOpt->m_structWingWall.m_dLengthLeftStt), toM(pBMOpt->m_structWingWall.m_dLengthLeftEnd));Arr.Add(sText);
sText.Format(" - 우측 => 시점 : %.3f m 종점 : %.3f m\n", toM(pBMOpt->m_structWingWall.m_dLengthRighStt), toM(pBMOpt->m_structWingWall.m_dLengthRighEnd));Arr.Add(sText);
}
sText.Format(" 28. 동 바 리 : %s\n", IsApply(pBMOpt->m_structTimber.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structTimber.m_bApply)
{
sText.Format(" - 동 바 리 재질 : %s\n", pBMOpt->GetTimberQuality(pBMOpt->m_structTimber.m_nQuality));Arr.Add(sText);
sText.Format(" - 데크피니셔 위치 : %s\n", pBMOpt->GetPosDeckFinisher(pBMOpt->m_structTimber.m_nPosDeckFinisher));Arr.Add(sText);
sText.Format(" - 데크피니셔 작업폭 : %.3f m\n", toM(pBMOpt->m_structTimber.m_dDeckFinisherWorkWidth));Arr.Add(sText);
}
sText.Format(" 29. 전 선 관 : %s\n", IsApply(pBMOpt->m_structElecWireHole.m_bApply)); Arr.Add(sText);
if(pBMOpt->m_structElecWireHole.m_bApply)
{
sText.Format(" - φ100 => 좌측 : %d EA 우측 : %d EA\n", pBMOpt->m_structElecWireHole.m_nEA100[0], pBMOpt->m_structElecWireHole.m_nEA100[1]);Arr.Add(sText);
sText.Format(" - φ125 => 좌측 : %d EA 우측 : %d EA\n", pBMOpt->m_structElecWireHole.m_nEA125[0], pBMOpt->m_structElecWireHole.m_nEA125[1]);Arr.Add(sText);
sText.Format(" - φ150 => 좌측 : %d EA 우측 : %d EA\n", pBMOpt->m_structElecWireHole.m_nEA150[0], pBMOpt->m_structElecWireHole.m_nEA150[1]);Arr.Add(sText);
}
}
void CDeckBMOptionDlg::OnCellChangedData(NMHDR* nmgv, LRESULT*)
{
CPlateBridgeApp *pDB = m_pStd->m_pDataManage->GetBridge();
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
if(m_nSelectedOpt == BMOPT_CONCRETE_BYE) pBMOpt->m_bConcreteBuy = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_CONCRETE_PLACING) pBMOpt->m_bConcretePlacing = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_MOLD) pBMOpt->m_bMold = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_SPACER) pBMOpt->m_bSpacer = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_REBAR_MANUFACTURE)
{
pBMOpt->m_structRebarManufacture.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structRebarManufacture.m_nSlabType = pBMOpt->GetIdxRebarManufactureType(m_Grid.GetTextMatrix(2, 1));
long nRow = 3;
if(pDB->GetGuardWallSu() > 0)
pBMOpt->m_structRebarManufacture.m_nGuardFenceType = pBMOpt->GetIdxRebarManufactureType(m_Grid.GetTextMatrix(nRow++, 1));
if(pBMOpt->m_structExpansionJoint.m_bApply)
pBMOpt->m_structRebarManufacture.m_nExpansionJointType = pBMOpt->GetIdxRebarManufactureType(m_Grid.GetTextMatrix(nRow++, 1));
if(pDB->IsTUGir())
pBMOpt->m_structRebarManufacture.m_nBindConcType = pBMOpt->GetIdxRebarManufactureType(m_Grid.GetTextMatrix(nRow++, 1));
OnCheckRebarManufacture();
}
if(m_nSelectedOpt == BMOPT_PAVE)
{
pBMOpt->m_structPave.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structPave.m_dPaveThick = m_Grid.GetTextMatrixDouble(1, 2);
OnCheckPave();
}
if(m_nSelectedOpt == BMOPT_TACKCOATING)
{
pBMOpt->m_structTackCoating.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structTackCoating.m_dTackCoating = m_Grid.GetTextMatrixDouble(1, 2);
OnCheckTackCoating();
}
if(m_nSelectedOpt == BMOPT_DRAINBRIDGESURFACE)
pBMOpt->m_bDrainBridgeSurface = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_BRIDGENAME)
{
pBMOpt->m_structBridgeName.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structBridgeName.m_nQty = m_Grid.GetTextMatrixLong(2, 1);
OnCheckBridgeName();
}
if(m_nSelectedOpt == BMOPT_BRIDGENAME_PLATE)
{
pBMOpt->m_structBridgeNamePlate.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structBridgeNamePlate.m_nQty = m_Grid.GetTextMatrixLong(2, 1);
OnCheckBridgeNameplate();
}
if(m_nSelectedOpt == BMOPT_EXPLAIN_PLATE)
{
pBMOpt->m_structExplainPlate.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structExplainPlate.m_nQty = m_Grid.GetTextMatrixLong(2, 1);
OnCheckExplainPlate();
}
if(m_nSelectedOpt == BMOPT_ESTABLISH_TBM)
{
pBMOpt->m_structEstablishTBM.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structEstablishTBM.m_nQty = m_Grid.GetTextMatrixLong(2, 1);
OnCheckEstablishTbm();
}
if(m_nSelectedOpt == BMOPT_STYROFOAM)
{
pBMOpt->m_structStyrofoam.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structStyrofoam.m_bLeft = IsLeft(m_Grid.GetTextMatrix(2, 1));
pBMOpt->m_structStyrofoam.m_dThick = m_Grid.GetTextMatrixDouble(3, 1);
OnCheckStyrofoam();
}
if(m_nSelectedOpt == BMOPT_EXPANSIONJOINT)
{
pBMOpt->m_structExpansionJoint.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structExpansionJoint.m_bUnitLength = IsApply(m_Grid.GetTextMatrix(2, 1));
pBMOpt->m_structExpansionJoint.m_szSttName = m_Grid.GetTextMatrix(3, 1);
pBMOpt->m_structExpansionJoint.m_nSttDiaIdx[0] = pBMOpt->GetRebarDiaIndex(m_Grid.GetTextMatrix(4, 1));
pBMOpt->m_structExpansionJoint.m_dSttWeight[0] = pBMOpt->m_structExpansionJoint.m_bUnitLength ? m_Grid.GetTextMatrixDouble(4, 2) : frTon(m_Grid.GetTextMatrixDouble(4, 2));
pBMOpt->m_structExpansionJoint.m_nSttDiaIdx[1] = pBMOpt->GetRebarDiaIndex(m_Grid.GetTextMatrix(5, 1));
pBMOpt->m_structExpansionJoint.m_dSttWeight[1] = pBMOpt->m_structExpansionJoint.m_bUnitLength ? m_Grid.GetTextMatrixDouble(5, 2) : frTon(m_Grid.GetTextMatrixDouble(5, 2));
pBMOpt->m_structExpansionJoint.m_szEndName = m_Grid.GetTextMatrix(6, 1);
pBMOpt->m_structExpansionJoint.m_nEndDiaIdx[0] = pBMOpt->GetRebarDiaIndex(m_Grid.GetTextMatrix(7, 1));
pBMOpt->m_structExpansionJoint.m_dEndWeight[0] = pBMOpt->m_structExpansionJoint.m_bUnitLength ? m_Grid.GetTextMatrixDouble(7, 2) : frTon(m_Grid.GetTextMatrixDouble(7, 2));
pBMOpt->m_structExpansionJoint.m_nEndDiaIdx[1] = pBMOpt->GetRebarDiaIndex(m_Grid.GetTextMatrix(8, 1));
pBMOpt->m_structExpansionJoint.m_dEndWeight[1] = pBMOpt->m_structExpansionJoint.m_bUnitLength ? m_Grid.GetTextMatrixDouble(8, 2) : frTon(m_Grid.GetTextMatrixDouble(8, 2));
pBMOpt->m_structExpansionJoint.m_dMargin = m_Grid.GetTextMatrixDouble(9, 1);
pBMOpt->m_structExpansionJoint.m_nMarginsu = m_Grid.GetTextMatrixLong(10, 1);
OnCheckExpansionjoint();
}
if(m_nSelectedOpt == BMOPT_EXPANSIONJOINT_COVER)
{
pBMOpt->m_structExpansionJointCover.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
for(long nRow = 2; nRow < 9; nRow++)
{
pBMOpt->m_structExpansionJointCover.m_dHeight[nRow-2] = frM(m_Grid.GetTextMatrixDouble(nRow, 1));
pBMOpt->m_structExpansionJointCover.m_nQty[nRow-2] = m_Grid.GetTextMatrixLong(nRow, 3);
}
OnCheckExpansionjointCover();
}
if(m_nSelectedOpt == BMOPT_SHRINKAGE_CONCRETE)
{
pBMOpt->m_structShrinkageConcrete.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structShrinkageConcrete.m_nSttQty = m_Grid.GetTextMatrixLong(2, 2);
pBMOpt->m_structShrinkageConcrete.m_nEndQty = m_Grid.GetTextMatrixLong(3, 2);
OnCheckShrinkageConcrete();
}
if(m_nSelectedOpt == BMOPT_WATER_DRAW) pBMOpt->m_bWaterDraw = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_NOTCH)
{
pBMOpt->m_structNotch.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structNotch.m_nApplyPos = pBMOpt->GetNotchPos(m_Grid.GetTextMatrix(2, 1));
pBMOpt->m_structNotch.m_szNotchType = m_Grid.GetTextMatrix(3, 1);
OnCheckNotch();
}
if(m_nSelectedOpt == BMOPT_GUARD_FENCE)
{
pBMOpt->m_structGuardFence.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structGuardFence.m_dHeight = frM(m_Grid.GetTextMatrixDouble(1, 2));
OnCheckGuardFence();
}
if(m_nSelectedOpt == BMOPT_SOUND_PROOF)
{
pBMOpt->m_structSoundProof.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structSoundProof.m_dLHeight = frM(m_Grid.GetTextMatrixDouble(2, 1));
pBMOpt->m_structSoundProof.m_dRHeight = frM(m_Grid.GetTextMatrixDouble(3, 1));
OnCheckSoundProof();
}
if(m_nSelectedOpt == BMOPT_PARAPET)
{
pBMOpt->m_structParapet.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structParapet.m_dGuardLength[0] = frM(m_Grid.GetTextMatrixDouble(2, 2));
pBMOpt->m_structParapet.m_dGuardLength[1] = frM(m_Grid.GetTextMatrixDouble(3, 2));
pBMOpt->m_structParapet.m_dCurbLength = frM(m_Grid.GetTextMatrixDouble(4, 2));
pBMOpt->m_structParapet.m_nCurbQty = m_Grid.GetTextMatrixLong(5, 2);
OnCheckParapet();
}
if(m_nSelectedOpt == BMOPT_SHADE) pBMOpt->m_bShade = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_DROPPING_PREVENT)
{
pBMOpt->m_structDroppingPrevent.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal = pBMOpt->GetDroppingPrevent(m_Grid.GetTextMatrix(2, 1));
pBMOpt->m_structDroppingPrevent.m_dHorSpaceHeight = frM(m_Grid.GetTextMatrixDouble(3, 1));
if(!pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal)
pBMOpt->m_structDroppingPrevent.m_dVerSpaceHeight = frM(m_Grid.GetTextMatrixDouble(4, 1));
OnCheckDroppingPrevent();
}
if(m_nSelectedOpt == BMOPT_STEEL_QUANTITY) pBMOpt->m_bSteelQuantity = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_PAINT) pBMOpt->m_bPaint = IsApply(m_Grid.GetTextMatrix(1, 1));
if(m_nSelectedOpt == BMOPT_DRAIN_ESTABLISH)
{
pBMOpt->m_bDrainEstablish = IsApply(m_Grid.GetTextMatrix(1, 1));
if(pBMOpt->m_nDrainEstablishType == RIVER)
{
pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(3, 2); // 집수구
pBMOpt->m_structRiverDrainEstablish.m_dDrain = frM(m_Grid.GetTextMatrixDouble(4, 2)); // 배수구
}
else if(pBMOpt->m_nDrainEstablishType == WALKWAY || pBMOpt->m_nDrainEstablishType == RIVERWALKWAY)
{
if(m_Grid.GetTextMatrix(3, 1) == _T("TYPE 1 (건교부)"))
pBMOpt->m_structWalkWayDrainEstablish.m_nType = 0;
else
pBMOpt->m_structWalkWayDrainEstablish.m_nType = 1;
if(pBMOpt->m_nDrainEstablishType == WALKWAY && pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0)
{
pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(4, 2); // 집수구
pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect = m_Grid.GetTextMatrixLong(5, 2); // 연결집수거
pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0] = frM(m_Grid.GetTextMatrixDouble(6, 2)); // 직관
pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0] = m_Grid.GetTextMatrixLong(7, 2); // 곡관
pBMOpt->m_structWalkWayDrainEstablish.m_nJoint = m_Grid.GetTextMatrixLong(8, 2); // 연결부
}
else if(pBMOpt->m_nDrainEstablishType == WALKWAY && pBMOpt->m_structWalkWayDrainEstablish.m_nType == 1)
{
pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(4, 2); // 집수구
pBMOpt->m_structWalkWayDrainEstablish.m_nDrain = m_Grid.GetTextMatrixLong(5, 2); // 배수구
pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain = m_Grid.GetTextMatrixLong(6, 2); // 연결배수구
pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0] = frM(m_Grid.GetTextMatrixDouble(7, 2)); // 직관
pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1] = frM(m_Grid.GetTextMatrixDouble(8, 2)); // 직관
pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0] = m_Grid.GetTextMatrixLong(9, 2); // 곡관
pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1] = m_Grid.GetTextMatrixLong(10, 2); // 곡관
pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0] = m_Grid.GetTextMatrixLong(11, 2); // 청소구
pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1] = m_Grid.GetTextMatrixLong(12, 2); // 청소구
pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0] = m_Grid.GetTextMatrixLong(13, 2); // 상부고정대
pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1] = m_Grid.GetTextMatrixLong(14, 2); // 상부고정대
pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting = m_Grid.GetTextMatrixLong(15, 2); // 침전조
}
else if(pBMOpt->m_nDrainEstablishType == RIVERWALKWAY)
{
pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(4, 2); // 집수구
pBMOpt->m_structRiverDrainEstablish.m_dDrain = frM(m_Grid.GetTextMatrixDouble(5, 2)); // 배수구
if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0)
{
pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(6, 2); // 집수구
pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect = m_Grid.GetTextMatrixLong(7, 2); // 연결집수거
pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0] = frM(m_Grid.GetTextMatrixDouble(8, 2));// 직관
pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0] = m_Grid.GetTextMatrixLong(9, 2); // 곡관
pBMOpt->m_structWalkWayDrainEstablish.m_nJoint = m_Grid.GetTextMatrixLong(10, 2); // 연결부
}
else
{
pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(6, 2); // 집수구
pBMOpt->m_structWalkWayDrainEstablish.m_nDrain = m_Grid.GetTextMatrixLong(7, 2); // 배수구
pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain = m_Grid.GetTextMatrixLong(8, 2); // 연결배수구
pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0] = frM(m_Grid.GetTextMatrixDouble(9, 2));// 직관
pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1] = frM(m_Grid.GetTextMatrixDouble(10, 2));// 직관
pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0] = m_Grid.GetTextMatrixLong(11, 2); // 곡관
pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1] = m_Grid.GetTextMatrixLong(12, 2); // 곡관
pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0] = m_Grid.GetTextMatrixLong(13, 2); // 청소구
pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1] = m_Grid.GetTextMatrixLong(14, 2); // 청소구
pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0] = m_Grid.GetTextMatrixLong(15, 2); // 상부고정대
pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1] = m_Grid.GetTextMatrixLong(16, 2); // 상부고정대
pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting = m_Grid.GetTextMatrixLong(17, 2); // 침전조
}
}
}
pBMOpt->m_nDrainEstablishType = pBMOpt->GetIdxDrainEstablishType(m_Grid.GetTextMatrix(2, 1));
OnCheckDrainEstablish();
}
if(m_nSelectedOpt == BMOPT_WING_WALL)
{
pBMOpt->m_structWingWall.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structWingWall.m_dLengthLeftStt = frM(m_Grid.GetTextMatrixDouble(2, 2));
pBMOpt->m_structWingWall.m_dLengthLeftEnd = frM(m_Grid.GetTextMatrixDouble(3, 2));
pBMOpt->m_structWingWall.m_dLengthRighStt = frM(m_Grid.GetTextMatrixDouble(4, 2));
pBMOpt->m_structWingWall.m_dLengthRighEnd = frM(m_Grid.GetTextMatrixDouble(5, 2));
OnCheckWingWall();
}
if(m_nSelectedOpt == BMOPT_TIMBER)
{
pBMOpt->m_structTimber.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structTimber.m_nQuality = pBMOpt->GetIdxTimberQuality(m_Grid.GetTextMatrix(2, 1));
pBMOpt->m_structTimber.m_nPosDeckFinisher = pBMOpt->GetIdxDeckFinisher(m_Grid.GetTextMatrix(3, 1));
pBMOpt->m_structTimber.m_dDeckFinisherWorkWidth = frM(m_Grid.GetTextMatrixDouble(4, 1));
OnCheckTimber();
}
if(m_nSelectedOpt == BMOPT_ELECWIREHOLE)
{
pBMOpt->m_structElecWireHole.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1));
pBMOpt->m_structElecWireHole.m_nEA100[0] = m_Grid.GetTextMatrixLong(2, 2);
pBMOpt->m_structElecWireHole.m_nEA100[1] = m_Grid.GetTextMatrixLong(3, 2);
pBMOpt->m_structElecWireHole.m_nEA125[0] = m_Grid.GetTextMatrixLong(4, 2);
pBMOpt->m_structElecWireHole.m_nEA125[1] = m_Grid.GetTextMatrixLong(5, 2);
pBMOpt->m_structElecWireHole.m_nEA150[0] = m_Grid.GetTextMatrixLong(6, 2);
pBMOpt->m_structElecWireHole.m_nEA150[1] = m_Grid.GetTextMatrixLong(7, 2);
OnCheckElecWireHole();
}
SetDataInit();
}
// 콘크리트 구입
void CDeckBMOptionDlg::OnCheckConcreteBuy()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_CONCRETE_BYE;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bConcreteBuy));
m_ConcreteBuy.SetCheck(pBMOpt->m_bConcreteBuy);
m_ConcreteBuy.Invalidate();
m_Grid.SetRedraw(TRUE,TRUE);
}
// 콘크리트 타설
void CDeckBMOptionDlg::OnCheckConcretePlacing()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_CONCRETE_PLACING;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bConcretePlacing));
m_ConcretePlacing.SetCheck(pBMOpt->m_bConcretePlacing);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 거푸집
void CDeckBMOptionDlg::OnCheckMold()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_MOLD;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bMold));
m_Mold.SetCheck(pBMOpt->m_bMold);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 스페이셔
void CDeckBMOptionDlg::OnCheckSpacer()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_SPACER;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bSpacer));
m_Spacer.SetCheck(pBMOpt->m_bSpacer);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 철근가공조립
void CDeckBMOptionDlg::OnCheckRebarManufacture()
{
CPlateBridgeApp *pDB = m_pStd->m_pDataManage->GetBridge();
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_REBAR_MANUFACTURE;
m_nCols = 2;
m_nRows = 3;
BOOL bGuard = FALSE;
BOOL bExp = FALSE;
BOOL bTUGir = pDB->IsTUGir();
if(pDB->GetGuardWallSu()>0) bGuard = TRUE;
if(pBMOpt->m_structExpansionJoint.m_bApply) bExp = TRUE;
if(bGuard) m_nRows++;
if(bExp) m_nRows++;
if(bTUGir) m_nRows++;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
long nRow = 3;
if(bGuard) m_Grid.SetCellType(nRow++, 1, CT_COMBO);
if(bExp) m_Grid.SetCellType(nRow++, 1, CT_COMBO);
if(bTUGir) m_Grid.SetCellType(nRow++, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structRebarManufacture.m_bApply));
m_Grid.SetTextMatrix(2, 0, "슬 래 브");
nRow = 3;
if(bGuard) m_Grid.SetTextMatrix(nRow++, 0, "방 호 벽");
if(bExp) m_Grid.SetTextMatrix(nRow++, 0, "신축이음");
if(bTUGir) m_Grid.SetTextMatrix(nRow++, 0, "구속콘크리트");
m_Grid.SetTextMatrix(2, 1, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nSlabType));
nRow = 3;
if(bGuard)
m_Grid.SetTextMatrix(nRow++, 1, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nGuardFenceType));
if(bExp)
m_Grid.SetTextMatrix(nRow++, 1, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nExpansionJointType));
if(bTUGir)
m_Grid.SetTextMatrix(nRow++, 1, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nBindConcType));
if(!pBMOpt->m_structRebarManufacture.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY);
m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
nRow = 3;
if(bGuard)
{
m_Grid.SetItemState(nRow, 1, m_Grid.GetItemState(nRow, 1) | GVIS_READONLY);
m_Grid.SetItemBkColour(nRow++, 1, RGBREADONLY);
}
if(bExp)
{
m_Grid.SetItemState(nRow, 1, m_Grid.GetItemState(nRow, 1) | GVIS_READONLY);
m_Grid.SetItemBkColour(nRow++, 1, RGBREADONLY);
}
if(bTUGir)
{
m_Grid.SetItemState(nRow, 1, m_Grid.GetItemState(nRow, 1) | GVIS_READONLY);
m_Grid.SetItemBkColour(nRow++, 1, RGBREADONLY);
}
}
m_RebarManufacture.SetCheck(pBMOpt->m_structRebarManufacture.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 포장
void CDeckBMOptionDlg::OnCheckPave()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_PAVE;
m_nCols = 4;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 70);
m_Grid.SetColumnWidth(2, 70);
m_Grid.SetColumnWidth(3, 70);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(0, 2, "두께");
m_Grid.SetTextMatrix(0, 3, "단위");
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structPave.m_bApply));
m_Grid.SetTextMatrix(1, 2, "%.0f", pBMOpt->m_structPave.m_dPaveThick);
m_Grid.SetTextMatrix(1, 3, "mm");
if(!pBMOpt->m_structPave.m_bApply)
{
m_Grid.SetItemState(1, 2, m_Grid.GetItemState(1, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 2, RGBREADONLY);
m_Grid.SetItemState(1, 3, m_Grid.GetItemState(1, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 3, RGBREADONLY);
}
m_Pave.SetCheck(pBMOpt->m_structPave.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 택코팅
void CDeckBMOptionDlg::OnCheckTackCoating()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_TACKCOATING;
m_nCols = 4;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 70);
m_Grid.SetColumnWidth(2, 70);
m_Grid.SetColumnWidth(3, 70);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(0, 2, "도포");
m_Grid.SetTextMatrix(0, 3, "단위");
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structTackCoating.m_bApply));
m_Grid.SetTextMatrix(1, 2, "%.1f", pBMOpt->m_structTackCoating.m_dTackCoating);
m_Grid.SetTextMatrix(1, 3, "배");
if(!pBMOpt->m_structTackCoating.m_bApply)
{
m_Grid.SetItemState(1, 2, m_Grid.GetItemState(1, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 2, RGBREADONLY);
m_Grid.SetItemState(1, 3, m_Grid.GetItemState(1, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 3, RGBREADONLY);
}
m_TackCoating.SetCheck(pBMOpt->m_structTackCoating.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 교면방수
void CDeckBMOptionDlg::OnCheckDrainBridgesurface()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_DRAINBRIDGESURFACE;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainBridgeSurface));
m_DrainBridgeSurface.SetCheck(pBMOpt->m_bDrainBridgeSurface);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 교명주
void CDeckBMOptionDlg::OnCheckBridgeName()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CString sText = _T("");
m_nSelectedOpt = BMOPT_BRIDGENAME;
m_nCols = 3;
m_nRows = 3;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 180);
m_Grid.SetColumnWidth(2, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 2);
m_Grid.SetMergeCol(1, 1, 2);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structBridgeName.m_bApply));
m_Grid.SetTextMatrix(2, 0, "설치갯수");
sText.Format("%d", pBMOpt->m_structBridgeName.m_nQty);
m_Grid.SetTextMatrix(2, 1, sText);
m_Grid.SetTextMatrix(2, 2, "EA");
if(!pBMOpt->m_structBridgeName.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY);
}
m_BridgeName.SetCheck(pBMOpt->m_structBridgeName.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 교명판
void CDeckBMOptionDlg::OnCheckBridgeNameplate()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CString sText = _T("");
m_nSelectedOpt = BMOPT_BRIDGENAME_PLATE;
m_nCols = 3;
m_nRows = 3;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 180);
m_Grid.SetColumnWidth(2, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 2);
m_Grid.SetMergeCol(1, 1, 2);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structBridgeNamePlate.m_bApply));
m_Grid.SetTextMatrix(2, 0, "설치갯수");
sText.Format("%d", pBMOpt->m_structBridgeNamePlate.m_nQty);
m_Grid.SetTextMatrix(2, 1, sText);
m_Grid.SetTextMatrix(2, 2, "EA");
if(!pBMOpt->m_structBridgeNamePlate.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY);
}
m_BridgeNamePlate.SetCheck(pBMOpt->m_structBridgeNamePlate.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 설명판
void CDeckBMOptionDlg::OnCheckExplainPlate()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CString sText = _T("");
m_nSelectedOpt = BMOPT_EXPLAIN_PLATE;
m_nCols = 3;
m_nRows = 3;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 180);
m_Grid.SetColumnWidth(2, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 2);
m_Grid.SetMergeCol(1, 1, 2);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structExplainPlate.m_bApply));
m_Grid.SetTextMatrix(2, 0, "설치갯수");
sText.Format("%d", pBMOpt->m_structExplainPlate.m_nQty);
m_Grid.SetTextMatrix(2, 1, sText);
m_Grid.SetTextMatrix(2, 2, "EA");
if(!pBMOpt->m_structExplainPlate.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY);
}
m_ExplainPlate.SetCheck(pBMOpt->m_structExplainPlate.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// TBM 설치
void CDeckBMOptionDlg::OnCheckEstablishTbm()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CString sText = _T("");
m_nSelectedOpt = BMOPT_ESTABLISH_TBM;
m_nCols = 3;
m_nRows = 3;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 180);
m_Grid.SetColumnWidth(2, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 2);
m_Grid.SetMergeCol(1, 1, 2);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structEstablishTBM.m_bApply));
m_Grid.SetTextMatrix(2, 0, "설치갯수");
sText.Format("%d", pBMOpt->m_structEstablishTBM.m_nQty);
m_Grid.SetTextMatrix(2, 1, sText);
m_Grid.SetTextMatrix(2, 2, "EA");
if(!pBMOpt->m_structEstablishTBM.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY);
}
m_EstablishTBM.SetCheck(pBMOpt->m_structEstablishTBM.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 스티로폼
void CDeckBMOptionDlg::OnCheckStyrofoam()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_STYROFOAM;
m_nCols = 3;
m_nRows = 4;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 100);
m_Grid.SetColumnWidth(1, 140);
m_Grid.SetColumnWidth(2, 70);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetCellType(3, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 2);
m_Grid.SetMergeCol(1, 1, 2);
m_Grid.SetMergeCol(2, 1, 2);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(2, 0, "위 치");
m_Grid.SetTextMatrix(3, 0, "두 께");
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structStyrofoam.m_bApply));
if(pBMOpt->m_structStyrofoam.m_bLeft) m_Grid.SetTextMatrix(2, 1, "좌측적용");
else m_Grid.SetTextMatrix(2, 1, "우측적용");
m_Grid.SetTextMatrix(3, 1, "%.0f", pBMOpt->m_structStyrofoam.m_dThick);
m_Grid.SetTextMatrix(3, 2, "mm");
if(!pBMOpt->m_structStyrofoam.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 2, RGBREADONLY);
}
m_Styrofoam.SetCheck(pBMOpt->m_structStyrofoam.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 신축이음
void CDeckBMOptionDlg::OnCheckExpansionjoint()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CPlateBridgeApp *pDB = m_pStd->GetBridge();
CBMOption *pBMOpt = &pADeckData->m_BMOption;
BOOL bWalkRoad = FALSE;
for(long nHDan=0; nHDan<pDB->GetQtyHDanNode(); nHDan++)
{
if(pDB->GetValueTypeHDan(nHDan, 1)==3) bWalkRoad = TRUE;
}
m_nSelectedOpt = BMOPT_EXPANSIONJOINT;
m_nCols = 4;
m_nRows = 12;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 100);
m_Grid.SetColumnWidth(1, 85);
m_Grid.SetColumnWidth(2, 85);
m_Grid.SetColumnWidth(3, 85);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetMergeCol(2, 1, 3);
m_Grid.SetMergeCol(3, 1, 3);
m_Grid.SetMergeRow(4, 6, 0);
m_Grid.SetMergeRow(7, 9, 0);
m_Grid.SetMergeCol(4, 1, 3);
m_Grid.SetMergeCol(7, 1, 3);
m_Grid.SetMergeCol(10, 1, 2);
m_Grid.SetMergeCol(11, 1, 2);
m_Grid.SetCellType(1, 1, CT_COMBO);
// m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetCellType(3, 1, CT_COMBO);
m_Grid.SetCellType(5, 1, CT_COMBO);
m_Grid.SetCellType(6, 1, CT_COMBO);
m_Grid.SetCellType(8, 1, CT_COMBO);
m_Grid.SetCellType(9, 1, CT_COMBO);
m_Grid.SetTextMatrix(2, 0, "수량기준");
m_Grid.SetTextMatrix(3, 0, "보도구간포함");
m_Grid.SetTextMatrix(4, 0, "시점");
m_Grid.SetTextMatrix(7, 0, "종점");
m_Grid.SetTextMatrix(10, 0, "여유치수");
m_Grid.SetTextMatrix(11, 0, "여유치수개수");
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structExpansionJoint.m_bApply));
if(pBMOpt->m_structExpansionJoint.m_bUnitLength) m_Grid.SetTextMatrix(2, 1, "단위 m당 수량");
else m_Grid.SetTextMatrix(2, 1, "지점별 수량");
if(!bWalkRoad)
{
pBMOpt->m_structExpansionJoint.m_bIncludeWalkLoad = FALSE;
m_Grid.SetRowHeight(3, 0);
}
m_Grid.SetTextMatrix(3, 1, IsApply(pBMOpt->m_structExpansionJoint.m_bIncludeWalkLoad));
m_Grid.SetTextMatrix(4, 1, pBMOpt->m_structExpansionJoint.m_szSttName);
m_Grid.SetTextMatrix(5, 1, pBMOpt->GetRebarDia(pBMOpt->m_structExpansionJoint.m_nSttDiaIdx[0], toKgPCm2(pADeckData->m_SigmaY)));
if(pBMOpt->m_structExpansionJoint.m_bUnitLength)
{
m_Grid.SetTextMatrix(5, 2, "%.3f", pBMOpt->m_structExpansionJoint.m_dSttWeight[0]);
m_Grid.SetTextMatrix(5, 3, "Kgf/m");
}
else
{
m_Grid.SetTextMatrix(5, 2, "%.3f", toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[0]));
m_Grid.SetTextMatrix(5, 3, "tonf");
}
m_Grid.SetTextMatrix(6, 1, pBMOpt->GetRebarDia(pBMOpt->m_structExpansionJoint.m_nSttDiaIdx[1], toKgPCm2(pADeckData->m_SigmaY)));
if(pBMOpt->m_structExpansionJoint.m_bUnitLength)
{
m_Grid.SetTextMatrix(6, 2, "%.3f", pBMOpt->m_structExpansionJoint.m_dSttWeight[1]);
m_Grid.SetTextMatrix(6, 3, "Kgf/m");
}
else
{
m_Grid.SetTextMatrix(6, 2, "%.3f", toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[1]));
m_Grid.SetTextMatrix(6, 3, "tonf");
}
m_Grid.SetTextMatrix(7, 1, pBMOpt->m_structExpansionJoint.m_szEndName);
m_Grid.SetTextMatrix(8, 1, pBMOpt->GetRebarDia(pBMOpt->m_structExpansionJoint.m_nEndDiaIdx[0], toKgPCm2(pADeckData->m_SigmaY)));
if(pBMOpt->m_structExpansionJoint.m_bUnitLength)
{
m_Grid.SetTextMatrix(8, 2, "%.3f", pBMOpt->m_structExpansionJoint.m_dEndWeight[0]);
m_Grid.SetTextMatrix(8, 3, "Kgf/m");
}
else
{
m_Grid.SetTextMatrix(8, 2, "%.3f", toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[0]));
m_Grid.SetTextMatrix(8, 3, "tonf");
}
m_Grid.SetTextMatrix(9, 1, pBMOpt->GetRebarDia(pBMOpt->m_structExpansionJoint.m_nEndDiaIdx[1], toKgPCm2(pADeckData->m_SigmaY)));
if(pBMOpt->m_structExpansionJoint.m_bUnitLength)
{
m_Grid.SetTextMatrix(9, 2, "%.3f", pBMOpt->m_structExpansionJoint.m_dEndWeight[1]);
m_Grid.SetTextMatrix(9, 3, "Kgf/m");
}
else
{
m_Grid.SetTextMatrix(9, 2, "%.3f", toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[1]));
m_Grid.SetTextMatrix(9, 3, "tonf");
}
m_Grid.SetTextMatrix(10, 1, "%.0f", pBMOpt->m_structExpansionJoint.m_dMargin);
m_Grid.SetTextMatrix(10, 3, "mm");
CString sText;
sText.Format("%d", pBMOpt->m_structExpansionJoint.m_nMarginsu);
m_Grid.SetTextMatrix(11, 1, sText);
m_Grid.SetTextMatrix(11, 3, "EA");
if(!pBMOpt->m_structExpansionJoint.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(4, 1, RGBREADONLY);
m_Grid.SetItemState(5, 1, m_Grid.GetItemState(5, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(5, 1, RGBREADONLY);
m_Grid.SetItemState(5, 2, m_Grid.GetItemState(5, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(5, 2, RGBREADONLY);
m_Grid.SetItemState(6, 1, m_Grid.GetItemState(6, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(6, 1, RGBREADONLY);
m_Grid.SetItemState(6, 2, m_Grid.GetItemState(6, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(6, 2, RGBREADONLY);
m_Grid.SetItemState(7, 1, m_Grid.GetItemState(7, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(7, 1, RGBREADONLY);
m_Grid.SetItemState(8, 1, m_Grid.GetItemState(8, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(8, 1, RGBREADONLY);
m_Grid.SetItemState(8, 2, m_Grid.GetItemState(8, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(8, 2, RGBREADONLY);
m_Grid.SetItemState(9, 1, m_Grid.GetItemState(9, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(9, 1, RGBREADONLY);
m_Grid.SetItemState(9, 2, m_Grid.GetItemState(9, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(9, 2, RGBREADONLY);
m_Grid.SetItemState(5, 3, m_Grid.GetItemState(5, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(5, 3, RGBREADONLY);
m_Grid.SetItemState(6, 3, m_Grid.GetItemState(6, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(6, 3, RGBREADONLY);
m_Grid.SetItemState(8, 3, m_Grid.GetItemState(8, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(8, 3, RGBREADONLY);
m_Grid.SetItemState(9, 3, m_Grid.GetItemState(9, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(9, 3, RGBREADONLY);
m_Grid.SetItemState(10, 1, m_Grid.GetItemState(10, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(10, 1, RGBREADONLY);
m_Grid.SetItemState(10, 3, m_Grid.GetItemState(10, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(10, 3, RGBREADONLY);
m_Grid.SetItemState(11, 1, m_Grid.GetItemState(11, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(11, 1, RGBREADONLY);
m_Grid.SetItemState(11, 3, m_Grid.GetItemState(11, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(11, 3, RGBREADONLY);
}
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY);
m_ExpansionJoint.SetCheck(pBMOpt->m_structExpansionJoint.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 신축이음 덮개
void CDeckBMOptionDlg::OnCheckExpansionjointCover()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CString sText = _T("");
m_nSelectedOpt = BMOPT_EXPANSIONJOINT_COVER;
m_nCols = 5;
m_nRows = 9;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 90);
m_Grid.SetColumnWidth(1, 80);
m_Grid.SetColumnWidth(2, 80);
m_Grid.SetColumnWidth(3, 50);
m_Grid.SetColumnWidth(4, 50);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 4);
m_Grid.SetMergeCol(1, 1, 4);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structExpansionJointCover.m_bApply));
m_Grid.SetTextMatrix(2, 0, pBMOpt->GetExpansionJointCoverPos(GENERAL_GUARDFENCE));
m_Grid.SetTextMatrix(3, 0, pBMOpt->GetExpansionJointCoverPos(ABSOLUTE_GUARDFENCE));
m_Grid.SetTextMatrix(4, 0, pBMOpt->GetExpansionJointCoverPos(GENERAL_SOUNDPROOF));
m_Grid.SetTextMatrix(5, 0, pBMOpt->GetExpansionJointCoverPos(ABSOLUTE_SOUNDPROOF));
m_Grid.SetTextMatrix(6, 0, pBMOpt->GetExpansionJointCoverPos(CENTER_GUARDFENCE));
m_Grid.SetTextMatrix(7, 0, pBMOpt->GetExpansionJointCoverPos(PARAPET));
m_Grid.SetTextMatrix(8, 0, pBMOpt->GetExpansionJointCoverPos(CURB));
for(long nRow = 2; nRow < 9; nRow++)
{
m_Grid.SetTextMatrix(nRow, 1, "%.3f", toM(pBMOpt->m_structExpansionJointCover.m_dHeight[nRow-2]));
m_Grid.SetTextMatrix(nRow, 2, "m");
sText.Format("%d", pBMOpt->m_structExpansionJointCover.m_nQty[nRow-2]);
m_Grid.SetTextMatrix(nRow, 3, sText);
m_Grid.SetTextMatrix(nRow, 4, "EA");
}
if(!pBMOpt->m_structExpansionJointCover.m_bApply)
{
for(long nRow = 2; nRow < 9; nRow++)
{
for(long nCol = 1; nCol < 5; nCol++)
{
m_Grid.SetItemState(nRow, nCol, m_Grid.GetItemState(nRow, nCol) | GVIS_READONLY);
m_Grid.SetItemBkColour(nRow, nCol, RGBREADONLY);
}
}
}
m_ExpansionJointCover.SetCheck(pBMOpt->m_structExpansionJointCover.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 무수축 콘크리트
void CDeckBMOptionDlg::OnCheckShrinkageConcrete()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CGlobarOption *pGlopt = m_pStd->m_pDataManage->GetGlobalOption();
CString sText = _T("");
double dExpJointSttHeight = pGlopt->GetSttExpansionJointHeight();
double dExpJointSttWidth = pGlopt->GetSttExpansionJointWidth();
double dExpJointEndHeight = pGlopt->GetEndExpansionJointHeight();
double dExpJointEndWidth = pGlopt->GetEndExpansionJointWidth();
m_nSelectedOpt = BMOPT_SHRINKAGE_CONCRETE;
m_nCols = 4;
m_nRows = 4;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 100);
m_Grid.SetColumnWidth(2, 80);
m_Grid.SetColumnWidth(3, 80);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetTextMatrix(2, 0, "시점적용 갯수");
m_Grid.SetTextMatrix(3, 0, "종점적용 갯수");
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structShrinkageConcrete.m_bApply));
sText.Format("%.0f × %.0f", dExpJointSttWidth, dExpJointSttHeight);
m_Grid.SetTextMatrix(2, 1, sText);
sText.Format("%d", pBMOpt->m_structShrinkageConcrete.m_nSttQty);
m_Grid.SetTextMatrix(2, 2, sText);
m_Grid.SetTextMatrix(2, 3, "EA");
sText.Format("%.0f × %.0f", dExpJointEndWidth, dExpJointEndHeight);
m_Grid.SetTextMatrix(3, 1, sText);
sText.Format("%d", pBMOpt->m_structShrinkageConcrete.m_nSttQty);
m_Grid.SetTextMatrix(3, 2, sText);
m_Grid.SetTextMatrix(3, 3, "EA");
if(!pBMOpt->m_structShrinkageConcrete.m_bApply)
{
}
m_ShrinkageConcrete.SetCheck(pBMOpt->m_structShrinkageConcrete.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 교면 물빼기
void CDeckBMOptionDlg::OnCheckWaterDraw()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_WATER_DRAW;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bWaterDraw));
m_WaterDraw.SetCheck(pBMOpt->m_bWaterDraw);
m_Grid.SetRedraw(TRUE,TRUE);
}
// NOTCH
void CDeckBMOptionDlg::OnCheckNotch()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_NOTCH;
m_nCols = 2;
m_nRows = 4;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetMergeRow(1, 2, 0);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structNotch.m_bApply));
m_Grid.SetTextMatrix(2, 1, pBMOpt->GetNotchPos(pBMOpt->m_structNotch.m_nApplyPos));
m_Grid.SetTextMatrix(3, 0, "NOTCH 종류");
m_Grid.SetTextMatrix(3, 1, pBMOpt->m_structNotch.m_szNotchType);
if(!pBMOpt->m_structNotch.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
}
m_Notch.SetCheck(pBMOpt->m_structNotch.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 가드펜스
void CDeckBMOptionDlg::OnCheckGuardFence()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_GUARD_FENCE;
m_nCols = 4;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 70);
m_Grid.SetColumnWidth(2, 70);
m_Grid.SetColumnWidth(3, 70);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(0, 2, "높이");
m_Grid.SetTextMatrix(0, 3, "단위");
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structGuardFence.m_bApply));
m_Grid.SetTextMatrix(1, 2, "%.1f", toM(pBMOpt->m_structGuardFence.m_dHeight));
m_Grid.SetTextMatrix(1, 3, "m");
if(!pBMOpt->m_structGuardFence.m_bApply)
{
m_Grid.SetItemState(1, 2, m_Grid.GetItemState(1, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 2, RGBREADONLY);
m_Grid.SetItemState(1, 3, m_Grid.GetItemState(1, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 3, RGBREADONLY);
}
m_GuardFence.SetCheck(pBMOpt->m_structGuardFence.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 방음판넬
void CDeckBMOptionDlg::OnCheckSoundProof()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CCalcData *pData = m_pStd->m_pDataManage->GetCalcData();
CCalcFloor CalcFloor(m_pStd->m_pDataManage);
m_nSelectedOpt = BMOPT_SOUND_PROOF;
m_nCols = 3;
m_nRows = 4;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 180);
m_Grid.SetColumnWidth(2, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structSoundProof.m_bApply));
m_Grid.SetMergeCol(0, 1, 2, TRUE);
m_Grid.SetMergeCol(1, 1, 2, TRUE);
long nGuardTypeL = CalcFloor.GetGuardWallType(FLOOR_LEFT);
long nGuardTypeR = CalcFloor.GetGuardWallType(FLOOR_RIGHT);
BOOL bBangEmExistL = (pData->DESIGN_FLOOR_DATA[FLOOR_LEFT].m_bBangEm && nGuardTypeL<=8) ? TRUE : FALSE;
BOOL bBangEmExistR = (pData->DESIGN_FLOOR_DATA[FLOOR_RIGHT].m_bBangEm && nGuardTypeR<=8) ? TRUE : FALSE;
if(bBangEmExistL)
{
m_Grid.SetTextMatrix(2, 0, "높이(좌)");
m_Grid.SetTextMatrix(2, 1, "%.3f", toM(pBMOpt->m_structSoundProof.m_dLHeight));
m_Grid.SetTextMatrix(2, 2, "m");
if(!pBMOpt->m_structSoundProof.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY);
}
}
else
m_Grid.SetRowHeight(2, 0);
if(bBangEmExistR)
{
m_Grid.SetTextMatrix(3, 0, "높이(우)");
m_Grid.SetTextMatrix(3, 1, "%.3f", toM(pBMOpt->m_structSoundProof.m_dRHeight));
m_Grid.SetTextMatrix(3, 2, "m");
if(!pBMOpt->m_structSoundProof.m_bApply)
{
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 2, RGBREADONLY);
}
}
else
m_Grid.SetRowHeight(3, 0);
m_SoundProof.SetCheck(pBMOpt->m_structSoundProof.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 난간
void CDeckBMOptionDlg::OnCheckParapet()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
CCalcData *pData = m_pStd->m_pDataManage->GetCalcData();
CCalcFloor CalcFloor(m_pStd->m_pDataManage);
CString sText = _T("");
m_nSelectedOpt = BMOPT_PARAPET;
m_nCols = 4;
m_nRows = 6;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 100);
m_Grid.SetColumnWidth(1, 120);
m_Grid.SetColumnWidth(2, 120);
m_Grid.SetColumnWidth(3, 70);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetMergeRow(2, 3, 0);
m_Grid.SetMergeRow(4, 5, 0);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structParapet.m_bApply));
m_Grid.SetTextMatrix(2, 0, "방호벽용");
m_Grid.SetTextMatrix(2, 1, "좌측길이");
m_Grid.SetTextMatrix(3, 1, "우측길이");
m_Grid.SetTextMatrix(4, 0, "연석용");
m_Grid.SetTextMatrix(4, 1, "난간길이");
m_Grid.SetTextMatrix(5, 1, "적용갯수");
m_Grid.SetTextMatrix(2, 2, "%.3f", toM(pBMOpt->m_structParapet.m_dGuardLength[0]));
m_Grid.SetTextMatrix(2, 3, "m");
m_Grid.SetTextMatrix(3, 2, "%.3f", toM(pBMOpt->m_structParapet.m_dGuardLength[1]));
m_Grid.SetTextMatrix(3, 3, "m");
m_Grid.SetTextMatrix(4, 2, "%.3f", toM(pBMOpt->m_structParapet.m_dCurbLength));
m_Grid.SetTextMatrix(4, 3, "m");
sText.Format("%d", pBMOpt->m_structParapet.m_nCurbQty);
m_Grid.SetTextMatrix(5, 2, sText);
m_Grid.SetTextMatrix(5, 3, "EA");
long nGuardTypeL = CalcFloor.GetGuardWallType(FLOOR_LEFT);
long nGuardTypeR = CalcFloor.GetGuardWallType(FLOOR_RIGHT);
if(!pBMOpt->m_structParapet.m_bApply)
{
for(long nRow = 2; nRow < 6; nRow++)
{
for(long nCol = 1; nCol < 4; nCol++)
{
m_Grid.SetItemState(nRow, nCol, m_Grid.GetItemState(nRow, nCol) | GVIS_READONLY);
m_Grid.SetItemBkColour(nRow, nCol, RGBREADONLY);
}
}
}
m_Parapet.SetCheck(pBMOpt->m_structParapet.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 차광망
void CDeckBMOptionDlg::OnCheckShade()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_SHADE;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bShade));
m_Shade.SetCheck(pBMOpt->m_bShade);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 낙하물 방지공
void CDeckBMOptionDlg::OnCheckDroppingPrevent()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_DROPPING_PREVENT;
m_nCols = 3;
m_nRows = 5;
if(pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal) m_nRows = 4;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 180);
m_Grid.SetColumnWidth(2, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 2);
m_Grid.SetMergeCol(1, 1, 2);
m_Grid.SetMergeCol(2, 1, 2);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structDroppingPrevent.m_bApply));
m_Grid.SetTextMatrix(2, 0, "적용 방향");
m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDroppingPrevent(pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal));
m_Grid.SetTextMatrix(3, 0, "수평 여유폭");
m_Grid.SetTextMatrix(3, 1, "%.3f", toM(pBMOpt->m_structDroppingPrevent.m_dHorSpaceHeight));
m_Grid.SetTextMatrix(3, 2, "m");
if(!pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal)
{
m_Grid.SetTextMatrix(4, 0, "수직 여유폭");
m_Grid.SetTextMatrix(4, 1, "%.3f", toM(pBMOpt->m_structDroppingPrevent.m_dVerSpaceHeight));
m_Grid.SetTextMatrix(4, 2, "m");
}
if(!pBMOpt->m_structDroppingPrevent.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 2, RGBREADONLY);
if(!pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal)
{
m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(4, 1, RGBREADONLY);
m_Grid.SetItemState(4, 2, m_Grid.GetItemState(4, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(4, 2, RGBREADONLY);
}
}
m_DroppingPreVent.SetCheck(pBMOpt->m_structDroppingPrevent.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 강재수량
void CDeckBMOptionDlg::OnCheckSteelQuantity()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_STEEL_QUANTITY;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bSteelQuantity));
m_SteelQuantity.SetCheck(pBMOpt->m_bSteelQuantity);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 강교도장
void CDeckBMOptionDlg::OnCheckPaint()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_PAINT;
m_nCols = 2;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 235);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bPaint));
m_Paint.SetCheck(pBMOpt->m_bPaint);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 배수시설
void CDeckBMOptionDlg::OnCheckDrainEstablish()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_DRAIN_ESTABLISH;
CString sText = _T("");
if(!pBMOpt->m_bDrainEstablish)
{
m_nCols = 4;
m_nRows = 2;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 90);
m_Grid.SetColumnWidth(1, 120);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish));
m_DrainEstablish.SetCheck(pBMOpt->m_bDrainEstablish);
m_Grid.SetRedraw(TRUE,TRUE);
return;
}
if(pBMOpt->m_nDrainEstablishType == RIVER)
{
m_nCols = 4;
m_nRows = 5;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 90);
m_Grid.SetColumnWidth(1, 110);
m_Grid.SetColumnWidth(2, 90);
m_Grid.SetColumnWidth(3, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetMergeCol(2, 1, 3);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish));
m_Grid.SetTextMatrix(2, 0, "타입 설정");
m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDrainEstablishType());
m_Grid.SetTextMatrix(3, 0, "집 수 구");
m_Grid.SetTextMatrix(3, 1, "스테인레스 Plate");
sText.Format("%d", pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect);
m_Grid.SetTextMatrix(3, 2, sText);
m_Grid.SetTextMatrix(3, 3, "EA");
m_Grid.SetTextMatrix(4, 0, "배 수 구");
m_Grid.SetTextMatrix(4, 1, "스테인레스 강관");
m_Grid.SetTextMatrix(4, 2, "%.3f", toM(pBMOpt->m_structRiverDrainEstablish.m_dDrain));
m_Grid.SetTextMatrix(4, 3, "m");
}
else if(pBMOpt->m_nDrainEstablishType == WALKWAY)
{
if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0)
{
m_nCols = 4;
m_nRows = 9;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 90);
m_Grid.SetColumnWidth(1, 110);
m_Grid.SetColumnWidth(2, 90);
m_Grid.SetColumnWidth(3, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetCellType(3, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetMergeCol(2, 1, 3);
m_Grid.SetMergeCol(3, 1, 3);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish));
m_Grid.SetTextMatrix(2, 0, "타입 설정");
m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDrainEstablishType());
m_Grid.SetTextMatrix(3, 0, "형 식");
if(pBMOpt->m_structWalkWayDrainEstablish.m_nType==0)
sText.Format("TYPE 1 (건교부)");
else
sText.Format("TYPE 2");
m_Grid.SetTextMatrix(3, 1, sText);
m_Grid.SetTextMatrix(4, 0, "집 수 구");
m_Grid.SetTextMatrix(4, 1, "-");
m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect);
m_Grid.SetTextMatrix(4, 2, sText);
m_Grid.SetTextMatrix(4, 3, "EA");
m_Grid.SetTextMatrix(5, 0, "연결집수거");
m_Grid.SetTextMatrix(5, 1, "-");
m_Grid.SetItemState(5, 1, m_Grid.GetItemState(5, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect);
m_Grid.SetTextMatrix(5, 2, sText);
m_Grid.SetTextMatrix(5, 3, "EA");
m_Grid.SetTextMatrix(6, 0, "직 관");
m_Grid.SetTextMatrix(6, 1, "-");
m_Grid.SetItemState(6, 1, m_Grid.GetItemState(6, 1) | GVIS_READONLY);
m_Grid.SetTextMatrix(6, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0]));
m_Grid.SetTextMatrix(6, 3, "m");
m_Grid.SetTextMatrix(7, 0, "곡 관");
m_Grid.SetTextMatrix(7, 1, "-");
m_Grid.SetItemState(7, 1, m_Grid.GetItemState(7, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]);
m_Grid.SetTextMatrix(7, 2, sText);
m_Grid.SetTextMatrix(7, 3, "EA");
m_Grid.SetTextMatrix(8, 0, "연 결 부");
m_Grid.SetTextMatrix(8, 1, "-");
m_Grid.SetItemState(8, 1, m_Grid.GetItemState(8, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoint);
m_Grid.SetTextMatrix(8, 2, sText);
m_Grid.SetTextMatrix(8, 3, "EA");
}
else if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 1)
{
m_nCols = 4;
m_nRows = 16;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 90);
m_Grid.SetColumnWidth(1, 110);
m_Grid.SetColumnWidth(2, 90);
m_Grid.SetColumnWidth(3, 60);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetCellType(3, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetMergeCol(2, 1, 3);
m_Grid.SetMergeCol(3, 1, 3);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish));
m_Grid.SetTextMatrix(2, 0, "타입 설정");
m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDrainEstablishType());
m_Grid.SetTextMatrix(3, 0, "형 식");
if(pBMOpt->m_structWalkWayDrainEstablish.m_nType==0)
sText.Format("TYPE 1 (건교부)");
else
sText.Format("TYPE 2");
m_Grid.SetTextMatrix(3, 1, sText);
m_Grid.SetTextMatrix(4, 0, "집 수 구");
m_Grid.SetTextMatrix(4, 1, "스테인레스 강관");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect);
m_Grid.SetTextMatrix(4, 2, sText);
m_Grid.SetTextMatrix(4, 3, "EA");
m_Grid.SetTextMatrix(5, 0, "배 수 구");
m_Grid.SetTextMatrix(5, 1, "스테인레스강관");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nDrain);
m_Grid.SetTextMatrix(5, 2, sText);
m_Grid.SetTextMatrix(5, 3, "EA");
m_Grid.SetTextMatrix(6, 0, "연결배수구");
m_Grid.SetTextMatrix(6, 1, "8""×10""");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain);
m_Grid.SetTextMatrix(6, 2, sText);
m_Grid.SetTextMatrix(6, 3, "EA");
m_Grid.SetTextMatrix(7, 0, "직 관");
m_Grid.SetTextMatrix(7, 1, "150A");
m_Grid.SetTextMatrix(7, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0]));
m_Grid.SetTextMatrix(7, 3, "m");
m_Grid.SetTextMatrix(8, 0, "직 관");
m_Grid.SetTextMatrix(8, 1, "200A");
m_Grid.SetTextMatrix(8, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1]));
m_Grid.SetTextMatrix(8, 3, "m");
m_Grid.SetTextMatrix(9, 0, "곡 관");
m_Grid.SetTextMatrix(9, 1, "150A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]);
m_Grid.SetTextMatrix(9, 2, sText);
m_Grid.SetTextMatrix(9, 3, "EA");
m_Grid.SetTextMatrix(10, 0, "곡 관");
m_Grid.SetTextMatrix(10, 1, "200A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1]);
m_Grid.SetTextMatrix(10, 2, sText);
m_Grid.SetTextMatrix(10, 3, "EA");
m_Grid.SetTextMatrix(11, 0, "청 소 구");
m_Grid.SetTextMatrix(11, 1, "150A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0]);
m_Grid.SetTextMatrix(11, 2, sText);
m_Grid.SetTextMatrix(11, 3, "EA");
m_Grid.SetTextMatrix(12, 0, "청 소 구");
m_Grid.SetTextMatrix(12, 1, "200A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1]);
m_Grid.SetTextMatrix(12, 2, sText);
m_Grid.SetTextMatrix(12, 3, "EA");
m_Grid.SetTextMatrix(13, 0, "상부고정대");
m_Grid.SetTextMatrix(13, 1, "150A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0]);
m_Grid.SetTextMatrix(13, 2, sText);
m_Grid.SetTextMatrix(13, 3, "EA");
m_Grid.SetTextMatrix(14, 0, "상부고정대");
m_Grid.SetTextMatrix(14, 1, "200A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1]);
m_Grid.SetTextMatrix(14, 2, sText);
m_Grid.SetTextMatrix(14, 3, "EA");
m_Grid.SetTextMatrix(15, 0, "침 전 조");
m_Grid.SetTextMatrix(15, 1, "-");
m_Grid.SetItemState(15, 1, m_Grid.GetItemState(15, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting);
m_Grid.SetTextMatrix(15, 2, sText);
m_Grid.SetTextMatrix(15, 3, "EA");
}
else
return;
}
else if(pBMOpt->m_nDrainEstablishType == RIVERWALKWAY)
{
if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0)
{
m_nCols = 4;
m_nRows = 11;
}
else
{
m_nCols = 4;
m_nRows = 18;
}
SetGridTitle();
m_Grid.SetColumnWidth(0, 90);
m_Grid.SetColumnWidth(1, 110);
m_Grid.SetColumnWidth(2, 90);
m_Grid.SetColumnWidth(3, 60);
m_Grid.SetRowHeightAll(20);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetCellType(3, 1, CT_COMBO);
m_Grid.SetMergeCol(0, 1, m_nCols-1);
m_Grid.SetMergeCol(1, 1, m_nCols-1);
m_Grid.SetMergeCol(2, 1, m_nCols-1);
m_Grid.SetMergeCol(3, 1, m_nCols-1);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish));
m_Grid.SetTextMatrix(2, 0, "타입 설정");
m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDrainEstablishType());
if(pBMOpt->m_structWalkWayDrainEstablish.m_nType==0) sText.Format("TYPE 1 (건교부)");
else sText.Format("TYPE 2");
m_Grid.SetTextMatrix(3, 1, sText);
m_Grid.SetTextMatrix(4, 0, "집 수 구");
m_Grid.SetTextMatrix(4, 1, "스테인레스 Plate");
sText.Format("%d", pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect);
m_Grid.SetTextMatrix(4, 2, sText);
m_Grid.SetTextMatrix(4, 3, "EA");
m_Grid.SetTextMatrix(5, 0, "배 수 구");
m_Grid.SetTextMatrix(5, 1, "스테인레스 강관");
m_Grid.SetTextMatrix(5, 2, "%.3f", toM(pBMOpt->m_structRiverDrainEstablish.m_dDrain));
m_Grid.SetTextMatrix(5, 3, "m");
if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0)
{
m_Grid.SetTextMatrix(6, 0, "집 수 구");
m_Grid.SetTextMatrix(6, 1, "-");
m_Grid.SetItemState(6, 1, m_Grid.GetItemState(6, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect);
m_Grid.SetTextMatrix(6, 2, sText);
m_Grid.SetTextMatrix(6, 3, "EA");
m_Grid.SetTextMatrix(7, 0, "연결집수거");
m_Grid.SetTextMatrix(7, 1, "-");
m_Grid.SetItemState(7, 1, m_Grid.GetItemState(7, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect);
m_Grid.SetTextMatrix(7, 2, sText);
m_Grid.SetTextMatrix(7, 3, "EA");
m_Grid.SetTextMatrix(8, 0, "직 관");
m_Grid.SetTextMatrix(8, 1, "-");
m_Grid.SetItemState(8, 1, m_Grid.GetItemState(8, 1) | GVIS_READONLY);
m_Grid.SetTextMatrix(8, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0]));
m_Grid.SetTextMatrix(8, 3, "m");
m_Grid.SetTextMatrix(9, 0, "곡 관");
m_Grid.SetTextMatrix(9, 1, "-");
m_Grid.SetItemState(9, 1, m_Grid.GetItemState(9, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]);
m_Grid.SetTextMatrix(9, 2, sText);
m_Grid.SetTextMatrix(9, 3, "EA");
m_Grid.SetTextMatrix(10, 0, "연 결 부");
m_Grid.SetTextMatrix(10, 1, "-");
m_Grid.SetItemState(10, 1, m_Grid.GetItemState(10, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoint);
m_Grid.SetTextMatrix(10, 2, sText);
m_Grid.SetTextMatrix(10, 3, "EA");
}
else
{
m_Grid.SetTextMatrix(6, 0, "집 수 구");
m_Grid.SetTextMatrix(6, 1, "스테인레스 강관");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect);
m_Grid.SetTextMatrix(6, 2, sText);
m_Grid.SetTextMatrix(6, 3, "EA");
m_Grid.SetTextMatrix(7, 0, "배 수 구");
m_Grid.SetTextMatrix(7, 1, "스테인레스강관");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nDrain);
m_Grid.SetTextMatrix(7, 2, sText);
m_Grid.SetTextMatrix(7, 3, "EA");
m_Grid.SetTextMatrix(8, 0, "연결배수구");
m_Grid.SetTextMatrix(8, 1, "8""×10""");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain);
m_Grid.SetTextMatrix(8, 2, sText);
m_Grid.SetTextMatrix(8, 3, "EA");
m_Grid.SetTextMatrix(9, 0, "직 관");
m_Grid.SetTextMatrix(9, 1, "150A");
m_Grid.SetTextMatrix(9, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0]));
m_Grid.SetTextMatrix(9, 3, "m");
m_Grid.SetTextMatrix(10, 0, "직 관");
m_Grid.SetTextMatrix(10, 1, "200A");
m_Grid.SetTextMatrix(10, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1]));
m_Grid.SetTextMatrix(10, 3, "m");
m_Grid.SetTextMatrix(11, 0, "곡 관");
m_Grid.SetTextMatrix(11, 1, "150A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]);
m_Grid.SetTextMatrix(11, 2, sText);
m_Grid.SetTextMatrix(11, 3, "EA");
m_Grid.SetTextMatrix(12, 0, "곡 관");
m_Grid.SetTextMatrix(12, 1, "200A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1]);
m_Grid.SetTextMatrix(12, 2, sText);
m_Grid.SetTextMatrix(12, 3, "EA");
m_Grid.SetTextMatrix(13, 0, "청 소 구");
m_Grid.SetTextMatrix(13, 1, "150A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0]);
m_Grid.SetTextMatrix(13, 2, sText);
m_Grid.SetTextMatrix(13, 3, "EA");
m_Grid.SetTextMatrix(14, 0, "청 소 구");
m_Grid.SetTextMatrix(14, 1, "200A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1]);
m_Grid.SetTextMatrix(14, 2, sText);
m_Grid.SetTextMatrix(14, 3, "EA");
m_Grid.SetTextMatrix(15, 0, "상부고정대");
m_Grid.SetTextMatrix(15, 1, "150A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0]);
m_Grid.SetTextMatrix(15, 2, sText);
m_Grid.SetTextMatrix(15, 3, "EA");
m_Grid.SetTextMatrix(16, 0, "상부고정대");
m_Grid.SetTextMatrix(16, 1, "200A");
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1]);
m_Grid.SetTextMatrix(16, 2, sText);
m_Grid.SetTextMatrix(16, 3, "EA");
m_Grid.SetTextMatrix(17, 0, "침 전 조");
m_Grid.SetTextMatrix(17, 1, "-");
m_Grid.SetItemState(17, 1, m_Grid.GetItemState(17, 1) | GVIS_READONLY);
sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting);
m_Grid.SetTextMatrix(17, 2, sText);
m_Grid.SetTextMatrix(17, 3, "EA");
}
long nRow = 0;
for(nRow = 4; nRow < 6; nRow++)
{
for(long nCol = 1; nCol < m_nCols; nCol++)
m_Grid.SetItemBkColour(nRow, nCol, RGB(255, 255, 200));
}
for(nRow = 6; nRow < m_nRows; nRow++)
{
for(long nCol = 1; nCol < m_nCols; nCol++)
m_Grid.SetItemBkColour(nRow, nCol, RGB(200, 255, 255));
}
}
else
return;
m_DrainEstablish.SetCheck(pBMOpt->m_bDrainEstablish);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 날개벽
void CDeckBMOptionDlg::OnCheckWingWall()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_WING_WALL;
m_nCols = 4;
m_nRows = 6;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 70);
m_Grid.SetColumnWidth(2, 70);
m_Grid.SetColumnWidth(3, 70);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(2, 0, "좌측");
m_Grid.SetTextMatrix(2, 1, "시점");
m_Grid.SetTextMatrix(3, 1, "종점");
m_Grid.SetTextMatrix(4, 0, "우측");
m_Grid.SetTextMatrix(4, 1, "시점");
m_Grid.SetTextMatrix(5, 1, "종점");
m_Grid.SetMergeRow(2, 3, 0);
m_Grid.SetMergeRow(4, 5, 0);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structWingWall.m_bApply));
m_Grid.SetTextMatrix(2, 2, "%.1f", toM(pBMOpt->m_structWingWall.m_dLengthLeftStt));
m_Grid.SetTextMatrix(2, 3, "m");
m_Grid.SetTextMatrix(3, 2, "%.1f", toM(pBMOpt->m_structWingWall.m_dLengthLeftEnd));
m_Grid.SetTextMatrix(3, 3, "m");
m_Grid.SetTextMatrix(4, 2, "%.1f", toM(pBMOpt->m_structWingWall.m_dLengthRighStt));
m_Grid.SetTextMatrix(4, 3, "m");
m_Grid.SetTextMatrix(5, 2, "%.1f", toM(pBMOpt->m_structWingWall.m_dLengthRighEnd));
m_Grid.SetTextMatrix(5, 3, "m");
if(!pBMOpt->m_structWingWall.m_bApply)
{
m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemBkColour(4, 1, RGBREADONLY);
m_Grid.SetItemBkColour(5, 1, RGBREADONLY);
m_Grid.SetItemBkColour(2, 3, RGBREADONLY);
m_Grid.SetItemBkColour(3, 3, RGBREADONLY);
m_Grid.SetItemBkColour(4, 3, RGBREADONLY);
m_Grid.SetItemBkColour(5, 3, RGBREADONLY);
m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(2, 2, RGBREADONLY);
m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(3, 2, RGBREADONLY);
m_Grid.SetItemState(4, 2, m_Grid.GetItemState(4, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(4, 2, RGBREADONLY);
m_Grid.SetItemState(5, 2, m_Grid.GetItemState(5, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(5, 2, RGBREADONLY);
}
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(1, 2) | GVIS_READONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(1, 3) | GVIS_READONLY);
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY);
m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY);
m_Grid.SetItemState(5, 1, m_Grid.GetItemState(5, 1) | GVIS_READONLY);
m_Grid.SetItemState(2, 3, m_Grid.GetItemState(2, 1) | GVIS_READONLY);
m_Grid.SetItemState(3, 3, m_Grid.GetItemState(3, 1) | GVIS_READONLY);
m_Grid.SetItemState(4, 3, m_Grid.GetItemState(4, 1) | GVIS_READONLY);
m_Grid.SetItemState(5, 3, m_Grid.GetItemState(5, 1) | GVIS_READONLY);
m_GuardFence.SetCheck(pBMOpt->m_structWingWall.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
// 동바리
void CDeckBMOptionDlg::OnCheckTimber()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_TIMBER;
m_nCols = 3;
m_nRows = 5;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 140);
m_Grid.SetColumnWidth(2, 80);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetCellType(2, 1, CT_COMBO);
m_Grid.SetCellType(3, 1, CT_COMBO);
m_Grid.SetTextMatrix(1, 0, "동바리종류");
m_Grid.SetTextMatrix(2, 0, "동바리재질");
m_Grid.SetTextMatrix(3, 0, "데크피니셔 위치");
m_Grid.SetTextMatrix(4, 0, "데크피니셔 작업폭");
m_Grid.SetMergeCol(0, 1, 2);
m_Grid.SetMergeCol(1, 1, 2);
m_Grid.SetMergeCol(2, 1, 2);
m_Grid.SetMergeCol(3, 1, 2);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structTimber.m_bApply));
m_Grid.SetTextMatrix(2, 1, pBMOpt->GetTimberQuality(pBMOpt->m_structTimber.m_nQuality));
m_Grid.SetTextMatrix(3, 1, pBMOpt->GetPosDeckFinisher(pBMOpt->m_structTimber.m_nPosDeckFinisher));
m_Grid.SetTextMatrix(4, 1, "%.3f", toM(pBMOpt->m_structTimber.m_dDeckFinisherWorkWidth));
m_Grid.SetTextMatrix(4, 2, "m");
if(!pBMOpt->m_structTimber.m_bApply)
{
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY);m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY);m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY);m_Grid.SetItemBkColour(4, 1, RGBREADONLY);
m_Grid.SetItemBkColour(4, 2, RGBREADONLY);
}
m_Grid.SetItemState(4, 2, m_Grid.GetItemState(4, 2) | GVIS_READONLY);
m_GuardFence.SetCheck(pBMOpt->m_structTimber.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
void CDeckBMOptionDlg::OnButtonAllCheck()
{
SetOptionAll(TRUE);
OnGridRedraw();
SetDataInit();
}
void CDeckBMOptionDlg::OnButtonAllCancel()
{
SetOptionAll(FALSE);
OnGridRedraw();
SetDataInit();
}
void CDeckBMOptionDlg::SetOptionAll(BOOL bApply)
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
pBMOpt->m_bConcreteBuy = bApply;
pBMOpt->m_bConcretePlacing = bApply;
pBMOpt->m_bMold = bApply;
pBMOpt->m_bSpacer = bApply;
pBMOpt->m_structRebarManufacture.m_bApply = bApply;
pBMOpt->m_structPave.m_bApply = bApply;
pBMOpt->m_structTackCoating.m_bApply = bApply;
pBMOpt->m_bDrainBridgeSurface = bApply;
pBMOpt->m_structBridgeName.m_bApply = bApply;
pBMOpt->m_structBridgeNamePlate.m_bApply = bApply;
pBMOpt->m_structExplainPlate.m_bApply = bApply;
pBMOpt->m_structEstablishTBM.m_bApply = bApply;
pBMOpt->m_structStyrofoam.m_bApply = bApply;
pBMOpt->m_structExpansionJoint.m_bApply = bApply;
pBMOpt->m_structExpansionJointCover.m_bApply = bApply;
pBMOpt->m_structShrinkageConcrete.m_bApply = bApply;
pBMOpt->m_bWaterDraw = bApply;
pBMOpt->m_structNotch.m_bApply = bApply;
pBMOpt->m_structGuardFence.m_bApply = bApply;
pBMOpt->m_structSoundProof.m_bApply = bApply;
pBMOpt->m_structParapet.m_bApply = bApply;
pBMOpt->m_bShade = bApply;
pBMOpt->m_structDroppingPrevent.m_bApply = bApply;
pBMOpt->m_bSteelQuantity = bApply;
pBMOpt->m_bPaint = bApply;
pBMOpt->m_bDrainEstablish = bApply;
pBMOpt->m_structWingWall.m_bApply = bApply;
pBMOpt->m_structTimber.m_bApply = bApply;
pBMOpt->m_structElecWireHole.m_bApply = bApply;
}
LRESULT CDeckBMOptionDlg::OnReceive(WPARAM wp,LPARAM lp)
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
switch(wp)
{
case IDC_CHECK_CONCRETE_BUY :
pBMOpt->m_bConcreteBuy = m_ConcreteBuy.GetCheck();
OnCheckConcreteBuy();
break;
case IDC_CHECK_CONCRETE_PLACING :
pBMOpt->m_bConcretePlacing = m_ConcretePlacing.GetCheck();
OnCheckConcretePlacing();
break;
case IDC_CHECK_MOLD :
pBMOpt->m_bMold = m_Mold.GetCheck();
OnCheckMold();
break;
case IDC_CHECK_SPACER :
pBMOpt->m_bSpacer= m_Spacer.GetCheck();
OnCheckSpacer();
break;
case IDC_CHECK_REBAR_MANUFACTURE :
pBMOpt->m_structRebarManufacture.m_bApply = m_RebarManufacture.GetCheck();
OnCheckRebarManufacture();
break;
case IDC_CHECK_PAVE :
pBMOpt->m_structPave.m_bApply = m_Pave.GetCheck();
OnCheckPave();
break;
case IDC_CHECK_TACK_COATING :
pBMOpt->m_structTackCoating.m_bApply = m_TackCoating.GetCheck();
OnCheckTackCoating();
break;
case IDC_CHECK_DRAIN_BRIDGESURFACE :
pBMOpt->m_bDrainBridgeSurface = m_DrainBridgeSurface.GetCheck();
OnCheckDrainBridgesurface();
break;
case IDC_CHECK_BRIDGE_NAME :
pBMOpt->m_structBridgeName.m_bApply = m_BridgeName.GetCheck();
OnCheckBridgeName();
break;
case IDC_CHECK_BRIDGE_NAMEPLATE :
pBMOpt->m_structBridgeNamePlate.m_bApply = m_BridgeNamePlate.GetCheck();
OnCheckBridgeNameplate();
break;
case IDC_CHECK_EXPLAIN_PLATE :
pBMOpt->m_structExplainPlate.m_bApply = m_ExplainPlate.GetCheck();
OnCheckExplainPlate();
break;
case IDC_CHECK_ESTABLISH_TBM :
pBMOpt->m_structEstablishTBM.m_bApply = m_EstablishTBM.GetCheck();
OnCheckEstablishTbm();
break;
case IDC_CHECK_STYROFOAM :
pBMOpt->m_structStyrofoam.m_bApply = m_Styrofoam.GetCheck();
OnCheckStyrofoam();
break;
case IDC_CHECK_EXPANSIONJOINT :
pBMOpt->m_structExpansionJoint.m_bApply = m_ExpansionJoint.GetCheck();
OnCheckExpansionjoint();
break;
case IDC_CHECK_EXPANSIONJOINT_COVER :
pBMOpt->m_structExpansionJointCover.m_bApply = m_ExpansionJointCover.GetCheck();
OnCheckExpansionjointCover();
break;
case IDC_CHECK_SHRINKAGE_CONCRETE :
pBMOpt->m_structShrinkageConcrete.m_bApply = m_ShrinkageConcrete.GetCheck();
OnCheckShrinkageConcrete();
break;
case IDC_CHECK_WATER_DRAW :
pBMOpt->m_bWaterDraw = m_WaterDraw.GetCheck();
OnCheckWaterDraw();
break;
case IDC_CHECK_NOTCH :
pBMOpt->m_structNotch.m_bApply = m_Notch.GetCheck();
OnCheckNotch();
break;
case IDC_CHECK_GUARD_FENCE :
pBMOpt->m_structGuardFence.m_bApply = m_GuardFence.GetCheck();
OnCheckGuardFence();
break;
case IDC_CHECK_SOUND_PROOF :
pBMOpt->m_structSoundProof.m_bApply = m_SoundProof.GetCheck();
OnCheckSoundProof();
break;
case IDC_CHECK_PARAPET :
pBMOpt->m_structParapet.m_bApply = m_Parapet.GetCheck();
OnCheckParapet();
break;
case IDC_CHECK_SHADE :
pBMOpt->m_bShade = m_Shade.GetCheck();
OnCheckShade();
break;
case IDC_CHECK_DROPPING_PREVENT :
pBMOpt->m_structDroppingPrevent.m_bApply = m_DroppingPreVent.GetCheck();
OnCheckDroppingPrevent();
break;
case IDC_CHECK_STEEL_QUANTITY :
pBMOpt->m_bSteelQuantity = m_SteelQuantity.GetCheck();
OnCheckSteelQuantity();
break;
case IDC_CHECK_PAINT :
pBMOpt->m_bPaint = m_Paint.GetCheck();
OnCheckPaint();
break;
case IDC_CHECK_DRAIN_ESTABLISH :
pBMOpt->m_bDrainEstablish = m_DrainEstablish.GetCheck();
OnCheckDrainEstablish();
break;
case IDC_CHECK_WING_WALL :
pBMOpt->m_structWingWall.m_bApply = m_WingWall.GetCheck();
OnCheckWingWall();
break;
case IDC_CHECK_TIMBER :
pBMOpt->m_structTimber.m_bApply = m_Timber.GetCheck();
OnCheckTimber();
case IDC_CHECK_ELECWIREHOLE :
pBMOpt->m_structElecWireHole.m_bApply = m_ElecWireHole.GetCheck();
OnCheckElecWireHole();
}
SetDataInit();
return 0;
}
BOOL CDeckBMOptionDlg::IsValid()
{
return m_pStd->m_bInclude_Module_Deck;
}
void CDeckBMOptionDlg::OnCheckElecWireHole()
{
CADeckData *pADeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pADeckData->m_BMOption;
m_nSelectedOpt = BMOPT_ELECWIREHOLE;
m_nCols = 4;
m_nRows = 8;
SetGridTitle();
m_Grid.SetRowHeightAll(20);
m_Grid.SetColumnWidth(0, 140);
m_Grid.SetColumnWidth(1, 70);
m_Grid.SetColumnWidth(2, 70);
m_Grid.SetColumnWidth(3, 70);
m_Grid.SetCellType(1, 1, CT_COMBO);
m_Grid.SetTextMatrix(2, 0, "φ100");
m_Grid.SetTextMatrix(2, 1, "좌측");
m_Grid.SetTextMatrix(3, 1, "우측");
m_Grid.SetTextMatrix(4, 0, "φ125");
m_Grid.SetTextMatrix(4, 1, "좌측");
m_Grid.SetTextMatrix(5, 1, "우측");
m_Grid.SetTextMatrix(6, 0, "φ150");
m_Grid.SetTextMatrix(6, 1, "좌측");
m_Grid.SetTextMatrix(7, 1, "우측");
m_Grid.SetMergeRow(2, 3, 0);
m_Grid.SetMergeRow(4, 5, 0);
m_Grid.SetMergeRow(6, 7, 0);
m_Grid.SetMergeCol(0, 1, 3);
m_Grid.SetMergeCol(1, 1, 3);
m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt));
m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structElecWireHole.m_bApply));
m_Grid.SetTextMatrix(2, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA100[0]));
m_Grid.SetTextMatrix(2, 3, "EA");
m_Grid.SetTextMatrix(3, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA100[1]));
m_Grid.SetTextMatrix(3, 3, "EA");
m_Grid.SetTextMatrix(4, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA125[0]));
m_Grid.SetTextMatrix(4, 3, "EA");
m_Grid.SetTextMatrix(5, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA125[1]));
m_Grid.SetTextMatrix(5, 3, "EA");
m_Grid.SetTextMatrix(6, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA150[0]));
m_Grid.SetTextMatrix(6, 3, "EA");
m_Grid.SetTextMatrix(7, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA150[1]));
m_Grid.SetTextMatrix(7, 3, "EA");
if(!pBMOpt->m_structElecWireHole.m_bApply)
{
m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemBkColour(2, 1, RGBREADONLY);
m_Grid.SetItemBkColour(3, 1, RGBREADONLY);
m_Grid.SetItemBkColour(4, 1, RGBREADONLY);
m_Grid.SetItemBkColour(5, 1, RGBREADONLY);
m_Grid.SetItemBkColour(6, 1, RGBREADONLY);
m_Grid.SetItemBkColour(7, 1, RGBREADONLY);
m_Grid.SetItemBkColour(2, 3, RGBREADONLY);
m_Grid.SetItemBkColour(3, 3, RGBREADONLY);
m_Grid.SetItemBkColour(4, 3, RGBREADONLY);
m_Grid.SetItemBkColour(5, 3, RGBREADONLY);
m_Grid.SetItemBkColour(6, 3, RGBREADONLY);
m_Grid.SetItemBkColour(7, 3, RGBREADONLY);
m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(2, 2, RGBREADONLY);
m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(3, 2, RGBREADONLY);
m_Grid.SetItemState(4, 2, m_Grid.GetItemState(4, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(4, 2, RGBREADONLY);
m_Grid.SetItemState(5, 2, m_Grid.GetItemState(5, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(5, 2, RGBREADONLY);
m_Grid.SetItemState(6, 2, m_Grid.GetItemState(6, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(6, 2, RGBREADONLY);
m_Grid.SetItemState(7, 2, m_Grid.GetItemState(7, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(7, 2, RGBREADONLY);
}
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(1, 2) | GVIS_READONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(1, 3) | GVIS_READONLY);
m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY);
m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY);
m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY);
m_Grid.SetItemState(5, 1, m_Grid.GetItemState(5, 1) | GVIS_READONLY);
m_Grid.SetItemState(6, 1, m_Grid.GetItemState(6, 1) | GVIS_READONLY);
m_Grid.SetItemState(7, 1, m_Grid.GetItemState(7, 1) | GVIS_READONLY);
m_Grid.SetItemState(2, 3, m_Grid.GetItemState(2, 1) | GVIS_READONLY);
m_Grid.SetItemState(3, 3, m_Grid.GetItemState(3, 1) | GVIS_READONLY);
m_Grid.SetItemState(4, 3, m_Grid.GetItemState(4, 1) | GVIS_READONLY);
m_Grid.SetItemState(5, 3, m_Grid.GetItemState(5, 1) | GVIS_READONLY);
m_Grid.SetItemState(6, 3, m_Grid.GetItemState(6, 1) | GVIS_READONLY);
m_Grid.SetItemState(7, 3, m_Grid.GetItemState(7, 1) | GVIS_READONLY);
m_ElecWireHole.SetCheck(pBMOpt->m_structElecWireHole.m_bApply);
m_Grid.SetRedraw(TRUE,TRUE);
}
void CDeckBMOptionDlg::OnButtonOptionSave()
{
CADeckData *pDeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pDeckData->m_BMOption;
CFileDialog dlg(FALSE, "*.abm",NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
"ARoad 수량 옵션파일(*.abm)|*.abm||",NULL);
dlg.m_ofn.lpstrTitle = "수량옵션 저장";
if(dlg.DoModal()==IDOK)
{
UpdateData();
CFile file;
if(!file.Open(dlg.GetPathName(),CFile::modeWrite | CFile::modeCreate)) return;
CArchive ar(&file,CArchive::store);
pBMOpt->Serialize(ar);
ar.Close();
file.Close();
}
}
void CDeckBMOptionDlg::OnButtonOptionLoad()
{
CADeckData *pDeckData = m_pStd->m_pDeckData;
CBMOption *pBMOpt = &pDeckData->m_BMOption;
CFileDialog dlg(TRUE, "*.abm",NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
"APlate 수량 옵션파일(*.abm)|*.abm||",NULL);
dlg.m_ofn.lpstrTitle = "수량옵션 불러오기";
if(dlg.DoModal()==IDOK)
{
CFile file;
if(!file.Open(dlg.GetPathName(),CFile::modeRead)) return;
CArchive ar(&file,CArchive::load);
pBMOpt->Serialize(ar);
ar.Close();
file.Close();
SetDataInit();
}
}
| [
"75705234+SamuelBacaner1112@users.noreply.github.com"
] | 75705234+SamuelBacaner1112@users.noreply.github.com |
2fb86e128bbe2cf6b6a1951019e86f179e8dd808 | b2119eea95c182c183913cc3574e75e8689d3130 | /SOURCES/sim/digi/wvrengage.cpp | 4e4d25b1ad11d3a33a23dd25d10602433ea0862d | [
"Unlicense"
] | permissive | 1059444127/Negev-Storm | 11233b1b3741f643ff14b5aa7b6ee08de40ab69f | 86de63e195577339f6e4a94198bedd31833a8be8 | refs/heads/master | 2021-05-28T10:48:53.536896 | 2015-02-08T10:42:15 | 2015-02-08T10:42:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,006 | cpp | #include "stdhdr.h"
#include "digi.h"
#include "simveh.h"
#include "object.h"
#include "aircrft.h"
#include "airframe.h"
#include "simdrive.h"
#include "classtbl.h"
#include "entity.h"
#include "fakerand.h"
#include "flight.h"
#include "wingorder.h"
#include "playerop.h"
#include "radar.h" // 2002-02-09 S.G.
// #define DEBUG_WVR_ENGAGE
#define MANEUVER_DEBUG
#ifdef MANEUVER_DEBUG
#include "Graphics\include\drawbsp.h"
extern int g_nShowDebugLabels;
#endif
extern bool g_bUseNewCanEnage; // 2002-03-11 S.G.
#ifdef DEBUG_WVR_ENGAGE
#define PrintWVRMode(a) MonoPrint(a)
#else
#define PrintWVRMode(a)
#endif
int CanEngage (AircraftClass *self, int combatClass, SimObjectType* targetPtr, int type); // 2002-03-11 MODIFIED BY S.G. Added the 'type' parameter
FalconEntity* SpikeCheck (AircraftClass* self, FalconEntity *byHim = NULL, int *data = NULL);// 2002-02-10 S.G.
/* Check for Entry/Exit condition into WVR */
void DigitalBrain::WvrEngageCheck(void)
{
float engageRange;
engageRange = 3.0F * NM_TO_FT;
/*---------------------*/
/* return if no target */
/*---------------------*/
if (targetPtr == NULL || (mpActionFlags[AI_ENGAGE_TARGET] != AI_AIR_TARGET && missionClass != AAMission && !missionComplete) || curMode == RTBMode) // 2002-03-04 MODIFIED BY S.G. Use new enum type
{
//me123 ClearTarget();
engagementTimer = 0;
}
/*-------*/
/* entry */
/*-------*/
else if (curMode != WVREngageMode && targetData->range < engageRange &&
(targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter()) && // 2002-03-05 MODIFIED BY S.G. airplane, choppers and fligth are ok in here (choppers only makes it here if it passed the SensorFusion test first)
SimLibElapsedTime > engagementTimer &&
CanEngage (self, self->CombatClass(), targetPtr, WVRManeuver)) // 2002-03-11 MODIFIED BY S.G. Added parameter WVRManeuver
{
AddMode(WVREngageMode);
}
else if (curMode == WVREngageMode &&
targetPtr->localData->range < 1.5F * engageRange &&
CanEngage(self, self->CombatClass(), targetPtr, WVRManeuver)) // 2002-03-11 MODIFIED BY S.G. Added parameter WVRManeuver
{
AddMode(WVREngageMode);
}
else
{
engagementTimer = 0;
}
}
/*
** Name: WVREngage
** Description:
** Main function for within visual range engagement.
** Basically this function just checks the tactics timer to determiine
** when we next need to eval our BFM stuff. It then runs the current
** tactic.
*/
void DigitalBrain::WvrEngage(void)
{
int lastTactic = wvrCurrTactic;
float left=0.0F, right=0.0F, cur=0.0F;
int myCombatClass = self->CombatClass();
int hisCombatClass=0;
ManeuverChoiceTable *theIntercept=NULL;
int numChoices=0, myChoice=0;
#ifdef MANEUVER_DEBUG
char tmpchr[40];
strcpy(tmpchr, "WvrEngage");
#endif
radModeSelect = 3;//default
// 2002-01-27 MN No need to go through all the stuff if we need to avoid the ground
if(groundAvoidNeeded)
return;
int mergeTime = -1 * (int)(SimLibElapsedTime + 2);
/*-------------------*/
/* bail if no target */
/*-------------------*/
if (targetPtr == NULL)
{
wvrCurrTactic = WVR_NONE;
#ifdef MANEUVER_DEBUG
strcpy(tmpchr,"Wvr NoTarget");
if (g_nShowDebugLabels & 0x10)
{
if (g_nShowDebugLabels & 0x8000)
{
if (((AircraftClass*) self)->af->GetSimpleMode())
strcat(tmpchr, " SIMP");
else
strcat(tmpchr, " COMP");
}
if ( self->drawPointer )
((DrawableBSP*)self->drawPointer)->SetLabel (tmpchr, ((DrawableBSP*)self->drawPointer)->LabelColor());
}
#endif
return;
}
// do we need to evaluate our position?
if ( SimLibElapsedTime > wvrTacticTimer || wvrCurrTactic == WVR_NONE )
{
// 2002-02-09 ADDED BY S.G. Change our radarMode to digiSTT if we have been detected and we have a radar to start with
// Look up intercept type for all A/C
if (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter())
{
// Find the data table for these two types of A/C
hisCombatClass = targetPtr->BaseData()->CombatClass(); // 2002-02-26 MODIFIED BY S.G. Removed the AircraftClass cast
// 2002-03-27 MN CTD fix - hisCombatClass is 999 in case of a FalcEnt. Need to add CombatClass() return call to helo.h
F4Assert(hisCombatClass < NumMnvrClasses);
if (hisCombatClass >= NumMnvrClasses)
hisCombatClass = NumMnvrClasses - 1;
theIntercept = &(maneuverData[myCombatClass][hisCombatClass]);
numChoices = theIntercept->numMerges;
if (numChoices)
{
myChoice = rand() % numChoices;// changed back WvrMergeUnlimited;// me123 status test. lets do smart merge for now.
switch (theIntercept->merge[myChoice])
{
case WvrMergeHitAndRun:
mergeTime = 15 * SEC_TO_MSEC;
break;
case WvrMergeLimited:
mergeTime = 60 * SEC_TO_MSEC;
break;
case WvrMergeUnlimited:
mergeTime = -1 * (int)(SimLibElapsedTime + 2);
break;
}
}
}
// run logic for next tactic
WvrChooseTactic();
// When do we get out of the fight
if (SimLibElapsedTime > engagementTimer)
{
engagementTimer = SimLibElapsedTime + mergeTime;
}
// chooose next time to check
// based on current tactic
switch( wvrCurrTactic )
{
case WVR_RANDP:
PrintWVRMode( "DIGI WVR RANDP\n" );
wvrTacticTimer = SimLibElapsedTime + 1000;//me123 status test chenged from 10
break;
case WVR_ROOP:
PrintWVRMode( "DIGI WVR ROOP\n" );
wvrTacticTimer = SimLibElapsedTime + 250;//me123 from 5000
break;
case WVR_OVERB:
PrintWVRMode( "DIGI WVR OVERB\n" );
wvrTacticTimer = SimLibElapsedTime + 3000;//me123 from 5000
break;
case WVR_GUNJINK:
PrintWVRMode( "DIGI WVR GUN JINK\n" );
wvrTacticTimer = SimLibElapsedTime + 500;//me123 status test chenged from 6
break;
case WVR_STRAIGHT:
// note: we'll likely want to set how long we go straight
// for by pilot skill level
PrintWVRMode( "DIGI WVR STRAIGHT\n" );
wvrTacticTimer = SimLibElapsedTime + 1500;
if (lastTactic != wvrCurrTactic)
{
if (af->theta > 0.0F)
holdAlt = max (5000.0F, -self->ZPos());
else
holdAlt = 0.0F;
}
break;
case WVR_AVOID:
PrintWVRMode( "DIGI WVR AVOID\n" );
wvrTacticTimer = SimLibElapsedTime + 1500;
if (lastTactic != wvrCurrTactic)
{
holdAlt = max (5000.0F, -self->ZPos());
}
holdPsi = targetPtr->BaseData()->Yaw() + 180.0F * DTR;
if (holdPsi > 180.0F * DTR)
holdPsi -= 360.0F * DTR;
break;
case WVR_BEAM_RETURN:
if (lastTactic != wvrCurrTactic)
{
PrintWVRMode( "DIGI WVR BEAM RETURN\n" );
wvrTacticTimer = SimLibElapsedTime + 10000;
holdAlt = max (5000.0F, -self->ZPos());
// Find left and right beam angles
// Note: Yaw is 0 - 359.9999
left = targetPtr->BaseData()->Yaw() - 90.0F * DTR;
right = targetPtr->BaseData()->Yaw() + 90.0F * DTR;
// Normalize
if (right > 180.0F * DTR)
right -= 360.0F * DTR;
if (left > 180.0F * DTR)
left -= 360.0F * DTR;
cur = self->Yaw();
if (cur > 180.0F * DTR)
cur -= 360.0F * DTR;
// Go to the closer
if (fabs (left - cur) < fabs (right - cur))
{
holdPsi = left;
}
else
{
holdPsi = right;
}
}
break;
case WVR_BEAM:
PrintWVRMode( "DIGI WVR BEAM\n" );
wvrTacticTimer = SimLibElapsedTime + 1500;
if (lastTactic != wvrCurrTactic)
{
holdAlt = max (5000.0F, -self->ZPos());
}
// Find left and right beam angles
// Note: Yaw is 0 - 359.9999
left = targetPtr->BaseData()->Yaw() - 90.0F * DTR;
right = targetPtr->BaseData()->Yaw() + 90.0F * DTR;
// Normalize
if (right > 180.0F * DTR)
right -= 360.0F * DTR;
if (left > 180.0F * DTR)
left -= 360.0F * DTR;
cur = self->Yaw();
if (cur > 180.0F * DTR)
cur -= 360.0F * DTR;
// Go to the closer
if (fabs (left - cur) < fabs (right - cur))
{
holdPsi = left;
}
else
{
holdPsi = right;
}
break;
case WVR_BUGOUT:
PrintWVRMode( "DIGI WVR BUGOUT\n" );
wvrTacticTimer = SimLibElapsedTime + 5000;
if (lastTactic != wvrCurrTactic)
{
holdAlt = max (5000.0F, -self->ZPos());
}
// Find a heading directly away from the target
cur = TargetAz (self, targetPtr);
if (cur > 0.0F)
cur = self->Yaw() - (180.0F*DTR - cur);
else
cur = self->Yaw() - (-180.0F*DTR - cur);
// Normalize
if (cur > 180.0F * DTR)
cur -= 360.0F * DTR;
holdPsi = cur;
break;
default:
PrintWVRMode( "DIGI NO MODE\n" );
wvrTacticTimer = SimLibElapsedTime + 500;//me123 from 5000
}
}
// run the tactic
switch( wvrCurrTactic )
{
case WVR_RANDP:
RollAndPull();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr Roll&Pull");
#endif
break;
case WVR_ROOP:
WvrRollOutOfPlane();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr RollOutOfPlane");
#endif
break;
case WVR_BUGOUT:
WvrBugOut();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr Bugout");
#endif
break;
case WVR_STRAIGHT:
WvrStraight();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr straight");
#endif
break;
case WVR_GUNJINK:
WvrGunJink();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr Gunjink");
#endif
break;
case WVR_OVERB:
WvrOverBank( 45.0f * DTR );
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr overbank");
#endif
break;
case WVR_AVOID:
WvrAvoid();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr avoid");
#endif
break;
case WVR_BEAM:
WvrBeam();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr beam");
#endif
break;
case WVR_BEAM_RETURN:
if (SimLibElapsedTime > wvrTacticTimer)
{
RollAndPull();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr RandP");
#endif
}
else
{
WvrBeam();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr Beam");
#endif
}
break;
default:
RollAndPull();
#ifdef MANEUVER_DEBUG
sprintf(tmpchr,"Wvr Roll&Pull");
#endif
break;
}
// last tactic executed
wvrPrevTactic = wvrCurrTactic;
#ifdef MANEUVER_DEBUG
if (g_nShowDebugLabels & 0x10)
{
if (g_nShowDebugLabels & 0x50) // add radar mode
{
RadarClass* theRadar = (RadarClass*)FindSensor(self, SensorClass::Radar);
if (theRadar) {
if (theRadar->digiRadarMode = RadarClass::DigiSTT)
strcat(tmpchr, " STT");
else if (theRadar->digiRadarMode = RadarClass::DigiSAM)
strcat(tmpchr, " SAM");
else if (theRadar->digiRadarMode = RadarClass::DigiTWS)
strcat(tmpchr, " TWS");
else if (theRadar->digiRadarMode = RadarClass::DigiRWS)
strcat(tmpchr, " RWS");
else if (theRadar->digiRadarMode = RadarClass::DigiOFF)
strcat(tmpchr, " OFF");
else strcat(tmpchr, " UNKNOWN");
}
}
if (g_nShowDebugLabels & 0x8000)
{
if (((AircraftClass*) self)->af->GetSimpleMode())
strcat(tmpchr, " SIMP");
else
strcat(tmpchr, " COMP");
}
if ( self->drawPointer )
((DrawableBSP*)self->drawPointer)->SetLabel (tmpchr, ((DrawableBSP*)self->drawPointer)->LabelColor());
}
#endif
}
/*
** Name: WvrChooseTactic
** Description:
** Try and make some not completely idiotic decisions....
*/
void DigitalBrain::WvrChooseTactic(void)
{
int myCombatClass = self->CombatClass();
int hisCombatClass;
ManeuverChoiceTable *theIntercept;
int aceAvoid = FALSE;
if (!IsSetATC(AceGunsEngage) && SkillLevel() >= 3)
{
if (maxAAWpnRange > 0 && maxAAWpnRange < 1.0F * NM_TO_FT)
aceAvoid = TRUE;
}
//TJL 12/06/03 Change to targetPtr
//if (threatPtr)
if (targetPtr)
{
// Look up intercept type for all A/C
// if (targetPtr->BaseData()->IsSim() && targetPtr->BaseData()->IsAirplane())
if (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter()) // 2002-03-05 MODIFIED BY S.G. airplane, choppers and fligth are ok in here (choppers only makes it here if it passed the SensorFusion test first)
{
// Find the data table for these two types of A/C
hisCombatClass = targetPtr->BaseData()->CombatClass(); // 2002-02-26 MODIFIED BY S.G. Removed the AircraftClass cast
theIntercept = &(maneuverData[myCombatClass][hisCombatClass]);
// No intercepts or Choose not to, or no weapons, or Guns only and ACE in campaign
if (theIntercept->numIntercepts == 0 ||
theIntercept->intercept[0] == BvrNoIntercept ||
maxAAWpnRange == 0 || aceAvoid)
{
// Can't go offensive, should we be defensive, or just keep running?
if (targetData->range > 1.5F * NM_TO_FT || targetData->ataFrom > 25.0F * DTR)
wvrCurrTactic = WVR_BUGOUT;
else
wvrCurrTactic = WVR_GUNJINK;
// Check for reload
WeaponSelection();
}
else
{// hmm this beaming stuff should be bwr tactics, we dont' do that when at visual range
// it takes place outside 10nm which is not within this rutine's paremeters so it's kinda disregarded
if (targetData->range > 25.0F * NM_TO_FT)
wvrCurrTactic = WVR_AVOID;
else if (targetData->range > 15.0F * NM_TO_FT)
wvrCurrTactic = WVR_BEAM ;//me123 status test chenged from WVR_BEAM_RETURN
else if (targetData->range > 10.0F * NM_TO_FT && wvrCurrTactic != WVR_BEAM_RETURN)//me123 status test chenged from >3
{
wvrCurrTactic = WVR_BEAM_RETURN;
}
else
{
wvrCurrTactic = WVR_RANDP;
}
}
}
else
{
wvrCurrTactic = WVR_AVOID;
}
}
else
/*-----------------------------*/
/* logic is geometry dependent */
/*-----------------------------*/
//ME123 WE DEFINATLY NEED TO THINK ABOUT NOSE TO NOSE OR NOSE TO TAIL FIGHT HERE !
// AT THE MOMENT WE JUST ROLL AND PULL NOMATTER WHAT :-(
// we are pointing at him and him at us and we are too slow
// so let's exploit that we are not emidiatly threatened and get some energy
//TJL 12/06/03 Appears someone forgot a * DTR
//if (targetData->ata <= 90.0F * DTR && targetData->ataFrom <= 90.0F)
if (targetData->ata <= 90.0F * DTR && targetData->ataFrom <= 90.0F * DTR)
{
// how stupid are we?
// MODIFIED BY S.G. af->vt is in feet/second. cornerSpeed is in knot/hour!
// NEEDS TO BE DONE IN THE 1.08 EXE FIRST TO BE CONSISTANT
if ( af->vt < cornerSpeed * 0.3F )
// if ( self->GetKias() < cornerSpeed * 0.3F )
{
wvrCurrTactic = WVR_STRAIGHT;
}
/*--------------*/
/* me -> <- him */
/*--------------*/
else if (targetData->ataFrom <= 90.0F * DTR)
{
wvrCurrTactic = WVR_RANDP;
}
/*--------------*/
/* me -> him -> */
/*--------------*/
else if (targetData->ataFrom >= 90.0F * DTR)
{
wvrCurrTactic = WVR_RANDP;
}
}
/*--------------*/
/* him -> me -> */
/*--------------*/
else if (targetData->ata > 90.0F * DTR)
{
if ( self->GetKias() < cornerSpeed * 0.6f )//me123 status test. accelerate if we are below 210cas changed from 0.3
{
wvrCurrTactic = WVR_RANDP;//me123 WVR_STRAIGHT;
}
else
{
wvrCurrTactic = WVR_RANDP;
}
}
}
void DigitalBrain::WvrRollOutOfPlane(void)
{
float eroll;
/*-----------------------*/
/* first pass, save roll */
/*-----------------------*/
if ( wvrPrevTactic != WVR_ROOP )
{
/*----------------------------------------------------*/
/* want to roll toward the vertical but limit to keep */
/* droll < 45 degrees. */
/*----------------------------------------------------*/
if (self->Roll() >= 0.0)
{
newroll = self->Roll() - 45.0F*DTR;//me123 from 45. smaller repossition
}
else
{
newroll = self->Roll() + 45.0F*DTR;//me123 from 45. smaller repossition
}
}
/*------------*/
/* roll error */
/*------------*/
eroll = newroll - self->Roll();
/*-----------------------------*/
/* roll the shortest direction */
/*-----------------------------*/
/*
if (eroll < -180.0F*DTR)
eroll += 360.0F*DTR;
else if (eroll > 180.0F*DTR)
eroll -= 360.0F*DTR;
*/
// me123 hmm nonono we are too fast that's why we need to do this MachHold(cornerSpeed, self->GetKias(), TRUE);
MachHold(150.0f, self->GetKias(), TRUE);
SetPstick(af->GsAvail(), maxGs, AirframeClass::GCommand);
SetRstick(eroll * RTD);
}
void DigitalBrain::WvrOverBank (float delta)
{
float eroll;
//-----------------------*/
// Find a new roll angle */
// relative to target
//-----------------------*/
if ( wvrPrevTactic != WVR_OVERB )
{
if (self->Roll() > 0.0F)
newroll = targetData->droll + delta;
else
newroll = targetData->droll - delta;
if (newroll > 180.0F * DTR)
newroll -= 360.0F * DTR;
else if (newroll < -180.0F * DTR)
newroll += 360.0F * DTR;
}
eroll = newroll - self->Roll();
MachHold(cornerSpeed, self->GetKias(), TRUE);
SetRstick(eroll * RTD);
SetPstick(af->GsAvail(), maxGs, AirframeClass::GCommand);
}
/*
** Name: WvrStraight
** Description:
** Level out and fly straight at high speed.
*/
void DigitalBrain::WvrStraight ( void )
{
if (holdAlt < 0.0F)
AltitudeHold (holdAlt);
else
pStick = 0.0F;
MachHold(2.0F*cornerSpeed, self->GetKias(), TRUE);
// If alpha > alphamax/2 unload to accel
if (af->alpha > 15.0F)
SetPstick (-1.0F, maxGs, AirframeClass::GCommand);
}
/*
** Name: WvrAvoid
** Description:
** Try to fly around the threat
*/
void DigitalBrain::WvrAvoid ( void )
{
HeadingAndAltitudeHold (holdPsi, holdAlt);
MachHold(2.0F*cornerSpeed, self->GetKias(), TRUE);
}
/*
** Name: WvrBeam
** Description:
** Keep aspect at 90
*/
void DigitalBrain::WvrBeam ( void )
{
HeadingAndAltitudeHold (holdPsi, holdAlt);
MachHold(2.0F*cornerSpeed, self->GetKias(), TRUE);
// We be chaff'n and flare'n
if (((AircraftClass*)self)->HasPilot())
{
if (SimLibElapsedTime > self->ChaffExpireTime() + 500)
{
((AircraftClass*)self)->dropChaffCmd = TRUE;
}
if (SimLibElapsedTime > self->FlareExpireTime() + 500)
{
((AircraftClass*)self)->dropFlareCmd = TRUE;
}
}
}
/*
** Name: WvrBugOut
** Description:
** Level out and fly straight at high speed.
** Head for the hills
*/
void DigitalBrain::WvrBugOut ( void )
{
HeadingAndAltitudeHold (holdPsi, holdAlt);
MachHold(2.0F*cornerSpeed, self->GetKias(), TRUE);
}
/*
** Name: Guns Jink
** Description:
** Jink around
*/
void DigitalBrain::WvrGunJink ( void )
{
GunsJink();
}
/*
** Name: SetThreat
** Description:
** Creates a SimObjectType struct for the entity, sets the threatPtr,
** References the target. Any pre-existing target is dereferenced.
*/
void DigitalBrain::SetThreat( FalconEntity *obj )
{
short edata[6];
int randNum, response;
// don't pre-empt current threat with a new threat until we've been
// dealing with the threat for a while unless the threat is NULL
if ( obj != NULL && threatTimer > 0.0f )
return;
F4Assert (!obj || !obj->IsSim() || !obj->IsHelicopter());
if (obj && obj->OnGround())//Cobra We want to nail those targeting us!
{
SetGroundTarget(obj);
return;
}
if ( obj && !obj->OnGround() )
{
// if the threat is the same as our target, we don't
// need to do anything since we're already dealing
// with it
if ( targetPtr && targetPtr->BaseData() == obj )
{
return;
}
// create new target data and reference it
#ifdef DEBUG
//threatPtr = new SimObjectType( OBJ_TAG, self, obj );
#else
threatPtr = new SimObjectType( obj );
#endif
threatTimer = 10.0f;
SetTarget (threatPtr);
// Occasionally send a radio call stating defensive or ask for help
randNum = rand() % 100;
if (randNum < 5)
{
// Yell for help
edata[0] = ((FlightClass*)self->GetCampaignObject())->callsign_id;
edata[1] = (((FlightClass*)self->GetCampaignObject())->callsign_num - 1) * 4 + self->GetCampaignObject()->GetComponentIndex(self) + 1;
AiMakeRadioResponse( self, rcHELPNOW, edata );
}
else if (randNum < 40)
{
//Inform flight
if(threatPtr->localData->range > 2.0F * NM_TO_FT)
{
if(PlayerOptions.BullseyeOn())
{
response = rcENGDEFENSIVEA;
}
else
{
response = rcENGDEFENSIVEB;
}
edata[0] = ((FlightClass*)self->GetCampaignObject())->callsign_id;
edata[1] = (((FlightClass*)self->GetCampaignObject())->callsign_num - 1) * 4 + isWing;
edata[2] = (short) SimToGrid(threatPtr->BaseData()->YPos());
edata[3] = (short) SimToGrid(threatPtr->BaseData()->XPos());
edata[4] = (short) threatPtr->BaseData()->ZPos();
}
else
{
edata[0] = isWing;
response = rcENGDEFENSIVEC;
}
// Send the message
AiMakeRadioResponse( self, response, edata );
}
threatPtr = NULL;
}
}
// 2002-03-11 MODIFIED BY S.G. Too many changes to track them all, rewrite it...
#if 1
int CanEngage (AircraftClass *self, int combatClass, SimObjectType* targetPtr, int type)
{
int hisCombatClass;
DigitalBrain::ManeuverChoiceTable *theIntercept;
int retBvr = TRUE;
int retWvr = TRUE;
// Check for aircraft, choppers or flights
if (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter())
{
// If asked to use the new code, then honor the request
if (g_bUseNewCanEnage) {
// Find the data table for these two types of flying objects
// But don't assume you know it, see if id'ed first...
CampBaseClass *campBaseObj;
if (targetPtr->BaseData()->IsSim())
campBaseObj = ((SimBaseClass*)targetPtr->BaseData())->GetCampaignObject();
else
campBaseObj = ((CampBaseClass *)targetPtr->BaseData());
// If it doesn't have a campaign object or it's identified... END OF ADDED SECTION plus the use of campBaseObj below
if (!campBaseObj || campBaseObj->GetIdentified(self->GetTeam())) {
// Yes, now you can get its combat class!
hisCombatClass = targetPtr->BaseData()->CombatClass();
}
else {
//TJL Combatclass numbers are kinda hosed, assume the worst at all times if you can't determine
// No :-( Then guestimate it... (from RIK's BVR code)
hisCombatClass = 4;
/*if ((targetPtr->BaseData()->GetVt() * FTPSEC_TO_KNOTS > 300.0f || targetPtr->BaseData()->ZPos() < -10000.0f)) {
//this might be a combat jet.. asume the worst
hisCombatClass = 4;
}
else if (targetPtr->BaseData()->GetVt() * FTPSEC_TO_KNOTS > 250.0f) {
// this could be a a-a capable thingy, but if it's is it's low level so it's a-a long range shoot capabilitys are not great
hisCombatClass = 1;
}
else {
// this must be something unthreatening...it's below 250 knots but it's still unidentified so...
hisCombatClass = 0;
}*/
}
}
else
hisCombatClass = targetPtr->BaseData()->CombatClass();
theIntercept = &(DigitalBrain::maneuverData[combatClass][hisCombatClass]);
if (type & DigitalBrain::WVRManeuver) {
// If no capability, don't go say you can engage!!!
if (theIntercept->numMerges == 0)
retWvr = FALSE;
else if (theIntercept->numMerges == 1)
{
// Need to be real close for a hit and run
if (theIntercept->merge[0] == DigitalBrain::WvrMergeHitAndRun &&
targetPtr->localData->ata > 45.0F * DTR)
{
retWvr = FALSE;
}
// Can't be behind you for limited
else if (theIntercept->merge[0] == DigitalBrain::WvrMergeLimited &&
targetPtr->localData->ata > 90.0F * DTR)
{
retWvr = FALSE;
}
}
}
else
retWvr = FALSE;
// Check for intercepts if in BVR...
if (type & DigitalBrain::BVRManeuver) {
if (theIntercept->numIntercepts == 0)
retBvr = FALSE;
}
else
retBvr = FALSE;
// Fail safe
if (type == 0) {
retWvr = FALSE;
retBvr = FALSE;
}
}
// 2002-03-11 ADDED BY S.G. If it's not even an air thingy, why do you say you can engage it???
else {
retWvr = FALSE;
retBvr = FALSE;
}
return retBvr | retWvr;
}
#else
int CanEngage (int combatClass, SimObjectType* targetPtr)
{
int hisCombatClass;
DigitalBrain::ManeuverChoiceTable *theIntercept;
int retval = TRUE; // Assume you can engage
// Only check for A/C
// if (targetPtr->BaseData()->IsSim() && targetPtr->BaseData()->IsAirplane())
if (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter()) // 2002-03-05 MODIFIED BY S.G. airplane, choppers and fligth are ok in here (choppers only makes it here if it passed the SensorFusion test first)
{
// Find the data table for these two types of A/C
hisCombatClass = targetPtr->BaseData()->CombatClass(); // 2002-02-26 MODIFIED BY S.G. Removed the AircraftClass cast
theIntercept = &(DigitalBrain::maneuverData[combatClass][hisCombatClass]);
if (theIntercept->numMerges == 1)
{
// Need to be real close for a hit and run
if (theIntercept->merge[0] == DigitalBrain::WvrMergeHitAndRun &&
targetPtr->localData->ata > 45.0F * DTR)
{
retval = FALSE;
}
// Can't be behind you for limited
else if (theIntercept->merge[0] == DigitalBrain::WvrMergeLimited &&
targetPtr->localData->ata > 90.0F * DTR)
{
retval = FALSE;
}
}
}
return retval;
}
#endif | [
"israelyflightsimulator@gmail.com"
] | israelyflightsimulator@gmail.com |
3d395af9d17064c76e703b2b7c46530b25cb4749 | ec93acb118d5db08c2ac97b667648db2161d2f6d | /android/cpp/src/objects/asmediacontainer.cpp | b778eb8137a5abf8813ce5df895a1fbadc4c9176 | [] | no_license | ActivLearning/flipchartparser | cb315e698fbd3c3869b978a099c2dbbae93536e2 | dfbe159f4680a0396d3761490376884878cef6e3 | refs/heads/master | 2022-12-07T12:18:28.258572 | 2020-09-04T03:42:48 | 2020-09-04T03:42:48 | 290,667,276 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,463 | cpp |
#include <QMutexLocker>
#include <QObject>
#include <QObjectList>
#include "asmediacontainer.h"
#include "../resources/asimageres.h"
#include "../resources/asmediafileres.h"
#include "../asfactory.h"
#include "../resources/asresourcemanager.h"
#include "../util/asutil.h"
#include "asflipchart.h"
#include "../util/commonlog.h"
#ifdef Q_OS_WIN32
#include "asaxwidget.h"
#endif
AsMediaContainer::AsMediaContainer( AsFactory *pFactory )
: AsWidgetContainer( pFactory ), m_creationMutex( QMutex::Recursive ),
m_bSelected(false),
m_autoTakePlaceHolderImage( false )
{
this->asClear();
}
AsMediaContainer::AsMediaContainer( const AsMediaContainer & container )
: AsWidgetContainer( container ), m_creationMutex( QMutex::Recursive )
{
this->asClear();
this->asCopy( container );
}
AsMediaContainer::~AsMediaContainer()
{
this->asDestroyMediaObjectAndSurface();
}
void AsMediaContainer::asDestroyMediaObjectAndSurface()
{
}
void AsMediaContainer::asSetVisible( bool bVisible )
{
if( asIsVisible() == bVisible )
{
// do nothing.
return;
}
AsRenderable::asSetVisible( bVisible );
// restart the media, well start
this->asRestartMediaObject();
}
void AsMediaContainer::asResetPropertyIndex( void )
{
AsObject::asSetPropertyIterator( &m_lProperties );
}
void AsMediaContainer::asClear()
{
this->asSetType( AsObject::AS_OBJECT_MEDIACONTAINER );
this->m_isContextCreated = false;
this->m_pTheSurfaceWidget = NULL;
this->m_pMediaFileRes = NULL;
this->m_pMultiMediaObject = NULL;
this->m_autoPlay = false;
this->m_loop = false;
this->m_hideControls = false;
this->m_forceAspect = false;
this->m_mediaFileResource = 0;
this->m_transparentBackground = false;
this->m_unableToCreateMultiMediaObject = false;
this->m_unableToCreateController = false;
this->m_unableToCreateSurfaceWidget = false;
this->m_unableToCreateSurface = false;
this->m_creationState = AsMediaContainer::NotCreated;
this->m_giveFocusOnCreate = false;
this->m_firstRenderDone = false;
this->m_currentRenderMode = AsWidgetContainer::AS_PAINTER_RENDER_IMAGE;
this->m_knownDeviceSpaceRectChange = false;
this->m_cachedForceOverlay = true;
this->m_cachedAutoPlay = false;
this->m_cachedLoop = false;
this->m_cachedHideControls = true;
this->m_cachedForceAspect = true;
this->m_cachedTransparentBackground = false;
this->m_cahcedRestartWasPlaying = false;
this->m_needToDoMainSignalsAndSlotsConnection = true;
}
void AsMediaContainer::asCopy( const AsMediaContainer & container )
{
AsWidgetContainer::operator = ( container );
this->m_autoPlay = container.m_autoPlay;
this->m_loop = container.m_loop;
this->m_hideControls = container.m_hideControls;
this->m_forceAspect = container.m_forceAspect;
this->m_transparentBackground = container.m_transparentBackground;
}
void AsMediaContainer::operator = ( const AsMediaContainer & container )
{
this->asCopy( container );
}
bool AsMediaContainer::operator == ( const AsMediaContainer & )
{
return false;
}
void AsMediaContainer::asOnObjectEditing( AsNode *, AsNode *pObjectNode )
{
}
void AsMediaContainer::asOnObjectEdited( AsNode *, AsNode *pObjectNode )
{
}
bool AsMediaContainer::asGetAutoPlay() const
{
return this->m_autoPlay;
}
bool AsMediaContainer::asGetLoop() const
{
return this->m_loop;
}
bool AsMediaContainer::asGetHideControls() const
{
return this->m_hideControls;
}
bool AsMediaContainer::asGetForceAspect() const
{
return this->m_forceAspect;
}
unsigned int AsMediaContainer::asGetMediaFileResource() const
{
return this->m_mediaFileResource;
}
bool AsMediaContainer::asGetTransparentBackground() const
{
return this->m_transparentBackground;
}
void AsMediaContainer::asSetAutoPlay( bool & v )
{
this->m_autoPlay = v;
}
void AsMediaContainer::asSetLoop( bool & v )
{
this->m_loop = v;
}
void AsMediaContainer::asSetHideControls( bool & v )
{
this->m_hideControls = v;
}
void AsMediaContainer::asSetForceAspect( bool & v )
{
this->m_forceAspect = v;
}
void AsMediaContainer::asSetMediaFileResource( unsigned int & id )
{
this->m_pMediaFileRes = NULL;
this->m_mediaFileResource = id;
}
void AsMediaContainer::asSetTransparentBackground( bool & value )
{
this->m_transparentBackground = value;
}
QHash<QString, quint16> & AsMediaContainer::m_lProperties( void )
{
static QHash<QString, quint16> HashProperties;
if ( HashProperties.isEmpty() )
{
// From AsObject...
// HashProperties.insert( "asDateTimeCreated", ( quint16 )AsMediaContainer::AS_PROPERTY_DATETIMECREATED );
// From AsRenderable...
HashProperties.insert( "transform", ( quint16 )AsMediaContainer::AS_PROPERTY_TRANSFORM );
// HashProperties.insert( "asTwips", ( quint16 )AsMediaContainer::AS_PROPERTY_TWIPS );
HashProperties.insert( "name", ( quint16 )AsMediaContainer::AS_PROPERTY_NAME );
// HashProperties.insert( "asKeywords", ( quint16 )AsMediaContainer::AS_PROPERTY_KEYWORDS );
// HashProperties.insert( "asVisible", ( quint16 )AsMediaContainer::AS_PROPERTY_VISIBLE );
HashProperties.insert( "boundingRect", ( quint16 )AsMediaContainer::AS_PROPERTY_BOUNDINGRECT );
HashProperties.insert( "layer", ( quint16 )AsMediaContainer::AS_PROPERTY_LAYER );
HashProperties.insert( "zOrder", ( quint16 )AsMediaContainer::AS_PROPERTY_Z );
HashProperties.insert( "ink", ( quint16 )AsMediaContainer::AS_PROPERTY_INK );
HashProperties.insert( "scaleOrigin", ( quint16 )AsMediaContainer::AS_PROPERTY_SCALEORIGIN );
HashProperties.insert( "rotateOrigin", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATEORIGIN );
HashProperties.insert( "moveType", ( quint16 )AsMediaContainer::AS_PROPERTY_CANMOVE );
// HashProperties.insert( "asCanSize", ( quint16 )AsMediaContainer::AS_PROPERTY_CANSIZE );
// HashProperties.insert( "asCanRotate", ( quint16 )AsMediaContainer::AS_PROPERTY_CANROTATE );
// HashProperties.insert( "asCanBlock", ( quint16 )AsMediaContainer::AS_PROPERTY_CANBLOCK );
// HashProperties.insert( "asCanSnap", ( quint16 )AsMediaContainer::AS_PROPERTY_CANSNAP );
HashProperties.insert( "locked", ( quint16 )AsMediaContainer::AS_PROPERTY_LOCKED );
// HashProperties.insert( "asSnapback", ( quint16 )AsMediaContainer::AS_PROPERTY_SNAPBACK );
// HashProperties.insert( "asPathPointer", ( quint16 )AsMediaContainer::AS_PROPERTY_PATHPOINTER );
// HashProperties.insert( "asRotateAboutPointer", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATEABOUTPOINTER );
// HashProperties.insert( "asRotatePoint", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATEPOINT );
// HashProperties.insert( "asRotateAbout", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATEABOUT );
// HashProperties.insert( "asRotateStep", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATESTEP );
// HashProperties.insert( "asSnapToPointer", ( quint16 )AsMediaContainer::AS_PROPERTY_SNAPTOPOINTER );
// HashProperties.insert( "asSnapPoint", ( quint16 )AsMediaContainer::AS_PROPERTY_SNAPPOINT );
// HashProperties.insert( "asSnapTo", ( quint16 )AsMediaContainer::AS_PROPERTY_SNAPTO );
// HashProperties.insert( "asCanContain", ( quint16 )AsMediaContainer::AS_PROPERTY_CANCONTAIN );
// HashProperties.insert( "asContainPointer", ( quint16 )AsMediaContainer::AS_PROPERTY_CONTAINPOINTER );
// HashProperties.insert( "asContainWords", ( quint16 )AsMediaContainer::AS_PROPERTY_CONTAINWORDS );
// HashProperties.insert( "asContainRule", ( quint16 )AsMediaContainer::AS_PROPERTY_CONTAINRULE );
// HashProperties.insert( "asV2Type", ( quint16 )AsMediaContainer::AS_PROPERTY_V2TYPE );
// HashProperties.insert( "asConnectorList", ( quint16 )AsMediaContainer::AS_PROPERTY_CONNECTORLIST );
// HashProperties.insert( "asLabel", ( quint16 )AsMediaContainer::AS_PROPERTY_LABEL );
// HashProperties.insert( "asQuestionItem", ( quint16 )AsMediaContainer::AS_PROPERTY_QUESTIONITEM );
// HashProperties.insert( "asQuestionItemID", ( quint16 )AsMediaContainer::AS_PROPERTY_QUESTIONITEMID );
// HashProperties.insert( "asQuestionTag", ( quint16 )AsMediaContainer::AS_PROPERTY_QUESTIONTAG );
// HashProperties.insert( "asAllowSnapback", ( quint16 )AsMediaContainer::AS_PROPERTY_ALLOWSNAPBACK );
// HashProperties.insert( "asDragACopy", ( quint16 )AsMediaContainer::AS_PROPERTY_DRAGACOPY );
// HashProperties.insert( "asAsyncTestTag", ( quint16 )AsMediaContainer::AS_PROPERTY_ASYNCTESTTAG );
// HashProperties.insert( "asInteractMode", ( quint16 )AsMediaContainer::AS_PROPERTY_INTERACTMODE );
// From AsWidgetContainer
HashProperties.insert( "placeHolderResource", ( quint16 )AsMediaContainer::AS_PROPERTY_RESOURCE );
// HashProperties.insert( "asForceOverLay", ( quint16 )AsMediaContainer::AS_PROPERTY_FORCEOVERLAY );
// From AsMediaContainer
HashProperties.insert( "autoPlay", ( quint16 )AsMediaContainer::AS_PROPERTY_AUTOPLAY );
HashProperties.insert( "loop", ( quint16 )AsMediaContainer::AS_PROPERTY_LOOP );
// HashProperties.insert( "asHideControls", ( quint16 )AsMediaContainer::AS_PORPERTY_HIDECONTROLS );
// HashProperties.insert( "asForceAspect", ( quint16 )AsMediaContainer::AS_PROPERTY_FORCEASPECT );
HashProperties.insert( "resource", ( quint16 )AsMediaContainer::AS_PROPERTY_MEDIAFILERESOURCE );
HashProperties.insert( "transparentBackground", ( quint16 )AsMediaContainer::AS_PROPERTY_TRANSPARENTBACKGROUND );
}
return HashProperties;
}
void AsMediaContainer::asSetMediaFileResource( AsMediaFileRes *pMediaFileResource )
{
}
AsMediaFileRes* AsMediaContainer::asGetMediaFileResourcePointer()
{
if( this->m_pMediaFileRes == NULL )
{
if( m_mediaFileResource != 0 )
{
this->m_pMediaFileRes = ( AsMediaFileRes* )this->m_pAsFactory->getResourceManager()->asLoadResource( AsObject::AS_OBJECT_MEDIAFILERES, asGetResource() );
if( m_pMediaFileRes && m_mediaFileResource != m_pMediaFileRes->asGetID() )
{
QString sDataFilename = this->m_pAsFactory->getResourceManager()->asGetResourceDataFilename( m_pMediaFileRes );
QString sWorkingPath = this->m_pAsFactory->getResourceManager()->asGetWorkingPath();
m_sResFilePath = sWorkingPath + "/" + sDataFilename;
//this can happen when duplicating multiple pages where a page which is not the current page ( so its resources are not loaded ) has content that has a storage of
//AsInternalPathLink. AsInternalPathLink storage does not use a data file so the duplicated page uses the same resource as the existing page. The resource has a
//reference in the resource manager with the id as per the existing page. The resource created above has a new id due to the duplication being classed as import in the
//factory. The resource id needs to match the reference id so the resource is not unloaded when it should not be and can be found in the resource manager when needed.
m_pMediaFileRes->asSetID( m_mediaFileResource );
}
}
}
return this->m_pMediaFileRes;
}
bool AsMediaContainer::asCreateWidgetSurface()
{
return true;
}
bool AsMediaContainer::asCreateSurface()
{
return true;
}
bool AsMediaContainer::asCreateController()
{
return true;
}
bool AsMediaContainer::asDoDelayedInitMultiMedia()
{
return true;
}
QRect AsMediaContainer::asGetSurfaceRect()
{
return QRect();
}
void AsMediaContainer::asOnLoseKeyboardFocus()
{
}
void AsMediaContainer::asOnGainKeyboardFocus()
{
}
void AsMediaContainer::asOnLoseHoverFocus()
{
}
void AsMediaContainer::asOnGainHoverFocus()
{
}
void AsMediaContainer::asOnActiveItem()
{
}
void AsMediaContainer::asOnDeactiveItem()
{
}
QPoint AsMediaContainer::asGetOrigin()
{
return QPoint();
}
void AsMediaContainer::asMediaObjectStarted()
{
}
void AsMediaContainer::asMediaObjectFinished( QObject* )
{
}
QString AsMediaContainer::asGetNewObjectName(quint32 nIndex)
{
QString strNextName;
return strNextName;
}
enum AsWidgetContainer::AsPainterCanvasPaintBufferType AsMediaContainer::asCanvasPaintSourceType()
{
enum AsWidgetContainer::AsPainterCanvasPaintBufferType ret = AsWidgetContainer::AS_PAINTER_CANVAS_BUFFER_NULL;
return ret;
}
QMutex* AsMediaContainer::asGetCanvasModeBufferProtection()
{
return NULL;
}
QPixmap *AsMediaContainer::asCanvasModeGetQPixmap()
{
QPixmap *pPixmap = NULL;
return pPixmap;
}
void AsMediaContainer::asDoForceUpdate()
{
}
enum AsWidgetContainer::AsPainterRenderMode AsMediaContainer::asPainterToRender()
{
return this->m_currentRenderMode;
}
void AsMediaContainer::asUpdateSurfacePosition()
{
}
void AsMediaContainer::asDoPosForceDraw()
{
}
void AsMediaContainer::asUpdateControllerPosition( const QRect & devicePositionOfSurface )
{
}
void AsMediaContainer::asGuiPluginUnloaded()
{
// we are just about to lose the GUI so destroy all media.
this->asDestroyMediaObjectAndSurface();
}
void AsMediaContainer::asGuiPluginLoaded()
{
}
#include <QDebug>
QPixmap* AsMediaContainer::asCaptureCurrentSurface()
{
QPixmap *pRet = NULL;
return pRet;
}
void AsMediaContainer::asVideoCaptureInsertIntoFlipchart()
{
}
void AsMediaContainer::asVideoCapturePlaceHolderImage()
{
this->asCapturePlaceHolderImage();
}
bool AsMediaContainer::asIsControllerVisable()
{
return false;
}
void AsMediaContainer::asControllerShow()
{
// we don't show the controller if we have nothing active.
}
void AsMediaContainer::asControllerHide()
{
}
void AsMediaContainer::asDoSurfaceDeviceSpaceRectChange( const QRect & newDeviceSpaceRect )
{
}
bool AsMediaContainer::event( QEvent *pEvent )
{
return false;
}
bool AsMediaContainer::asInitMultiMedia()
{
return true;
}
void AsMediaContainer::asSetPlaceHolderOnFirstPaint( bool doIt )
{
qDebug() << "AsMediaContainer::asSetPlaceHolderOnFirstPaint : " << this << ", doit : " << doIt;
this->m_autoTakePlaceHolderImage = doIt;
this->m_autoTakePlaceHolderFrameNumber = 1;
this->m_surfacePaintCount = 0;
}
void AsMediaContainer::asOnFirstFrame()
{
}
void AsMediaContainer::asOnDragAndDropFinished()
{
this->m_firstRenderDone = true;
}
void AsMediaContainer::asMediaObjectReleased()
{
if( this->m_pMultiMediaObject != NULL )
{
this->m_firstRenderDone = false;
this->m_currentRenderMode = AsWidgetContainer::AS_PAINTER_RENDER_IMAGE;
this->m_pMultiMediaObject = NULL;
this->asDestroyMediaObjectAndSurface();
}
}
bool AsMediaContainer::asIsActive() const
{
return false;
}
void AsMediaContainer::asOnSelected()
{
if( AsWidgetContainer::asIsActive() == false )
{
}
}
void AsMediaContainer::asOnDeselected()
{
if( AsWidgetContainer::asIsActive() == false )
{
}
}
void AsMediaContainer::asPushMediaSettingsToCache()
{
this->m_cachedForceOverlay = this->asGetForceOverlay();
this->m_cachedAutoPlay = this->m_autoPlay;
this->m_cachedLoop = this->m_loop;
this->m_cachedHideControls = this->m_hideControls;
this->m_cachedForceAspect = this->m_forceAspect;
this->m_cachedTransparentBackground = this->m_transparentBackground;
}
bool AsMediaContainer::asMediaSettingsDifferantThanCached()
{
if( this->m_cachedForceOverlay != this->asGetForceOverlay() )
{
return true;
}
if( this->m_cachedAutoPlay != this->m_autoPlay )
{
return true;
}
if( this->m_cachedLoop != this->m_loop )
{
return true;
}
if( this->m_cachedHideControls != this->m_hideControls )
{
return true;
}
if( this->m_cachedForceAspect != this->m_forceAspect )
{
return true;
}
if( this->m_cachedTransparentBackground != this->m_transparentBackground )
{
return true;
}
return false;
}
void AsMediaContainer::asRestartMediaObject()
{
if( this->m_pMultiMediaObject != NULL )
{
// cache the current play/capture state so when we to the restart we know what to do.
this->asDestroyMediaObjectAndSurface();
}
if( this->asIsVisible() )
{
this->asInitMultiMedia();
}
}
bool AsMediaContainer::asDoesSupportZReOrderingCommands() const
{
if (m_pMultiMediaObject)
{
}
return true;
}
void AsMediaContainer::asMediaContainerProxyForMouseEvents( int , int , int )
{
}
bool AsMediaContainer::asGetPlaceholderRequired()
{
return m_autoTakePlaceHolderImage;
}
QString AsMediaContainer::getPropertyNameById(int nID)
{
return m_lProperties().key(nID);
}
int AsMediaContainer::getPropertyIdByName(QString name) const
{
return m_lProperties().value(name);
}
const Json::Value &AsMediaContainer::asResourceSerialized()
{
asGetMediaResourcePointer();
asGetResourcePointer();
if(m_pMediaFileRes){
m_resourceJsonObject["mediaUrl"] = m_sResFilePath.toStdString();
}
if(m_pImageRes){
m_resourceJsonObject["tumbFileUrl"] = m_sTumbFilePath.toStdString();
}
return m_resourceJsonObject;
}
AsResource *AsMediaContainer::asGetMediaResourcePointer(void)
{
if( this->m_pMediaFileRes == NULL )
{
Variant var = property(AsMediaContainer::AS_PROPERTY_MEDIAFILERESOURCE);
this->m_pMediaFileRes = ( AsMediaFileRes* )this->m_pAsFactory->getResourceManager()->asLoadResource( AsObject::AS_OBJECT_MEDIAFILERES,
*static_cast<int*>(var.value));
if( m_pMediaFileRes && m_mediaFileResource != m_pMediaFileRes->asGetID() )
{
QString sDataFilename = this->m_pAsFactory->getResourceManager()->asGetResourceDataFilename( m_pMediaFileRes );
QString sWorkingPath = this->m_pAsFactory->getResourceManager()->asGetWorkingPath();
m_sResFilePath = sWorkingPath + "/" + sDataFilename;
//this can happen when duplicating multiple pages where a page which is not the current page ( so its resources are not loaded ) has content that has a storage of
//AsInternalPathLink. AsInternalPathLink storage does not use a data file so the duplicated page uses the same resource as the existing page. The resource has a
//reference in the resource manager with the id as per the existing page. The resource created above has a new id due to the duplication being classed as import in the
//factory. The resource id needs to match the reference id so the resource is not unloaded when it should not be and can be found in the resource manager when needed.
m_pMediaFileRes->asSetID( m_mediaFileResource );
}
}
return this->m_pMediaFileRes;
}
bool AsMediaContainer::isPropertyNeededSerialized(int nID)
{
if(getPropertyNameById(nID) == "ink"){
return false;
}
return true;
}
QString AsMediaContainer::typeName()
{
return "mediaContainer";
}
| [
"zhangyi.sina@gmail.com"
] | zhangyi.sina@gmail.com |
95a8c077432fb9699d7a8b142d5af3ed6f6b0578 | a0bdedcc814dfcbf6f1742c398b64a31619af4df | /ideccmbd/CrdIdecNav/PnlIdecNavPre_blks.cpp | a7856813874a260a40b4296d61833d58366e4101 | [
"BSD-2-Clause"
] | permissive | mpsitech/idec_public | ec7231939b8987fd66482d99276609e16d4ad3f7 | a74cf1c7095e08ee61b237fddc1642f83dbb852d | refs/heads/master | 2021-05-13T20:43:55.046131 | 2018-06-09T16:11:30 | 2018-06-09T16:11:30 | 116,916,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,558 | cpp | /**
* \file PnlIdecNavPre_blks.cpp
* job handler for job PnlIdecNavPre (implementation of blocks)
* \author Alexander Wirthmueller
* \date created: 30 Dec 2017
* \date modified: 30 Dec 2017
*/
/******************************************************************************
class PnlIdecNavPre::VecVDo
******************************************************************************/
uint PnlIdecNavPre::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "butmisremoveclick") return BUTMISREMOVECLICK;
else if (s == "buttouremoveclick") return BUTTOUREMOVECLICK;
return(0);
};
string PnlIdecNavPre::VecVDo::getSref(
const uint ix
) {
if (ix == BUTMISREMOVECLICK) return("ButMisRemoveClick");
else if (ix == BUTTOUREMOVECLICK) return("ButTouRemoveClick");
return("");
};
/******************************************************************************
class PnlIdecNavPre::ContInf
******************************************************************************/
PnlIdecNavPre::ContInf::ContInf(
const string& TxtMis
, const string& TxtTou
) : Block() {
this->TxtMis = TxtMis;
this->TxtTou = TxtTou;
mask = {TXTMIS, TXTTOU};
};
void PnlIdecNavPre::ContInf::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContInfIdecNavPre";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemInfIdecNavPre";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeStringAttr(wr, itemtag, "sref", "TxtMis", TxtMis);
writeStringAttr(wr, itemtag, "sref", "TxtTou", TxtTou);
xmlTextWriterEndElement(wr);
};
set<uint> PnlIdecNavPre::ContInf::comm(
const ContInf* comp
) {
set<uint> items;
if (TxtMis == comp->TxtMis) insert(items, TXTMIS);
if (TxtTou == comp->TxtTou) insert(items, TXTTOU);
return(items);
};
set<uint> PnlIdecNavPre::ContInf::diff(
const ContInf* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {TXTMIS, TXTTOU};
for (auto it=commitems.begin();it!=commitems.end();it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlIdecNavPre::StatShr
******************************************************************************/
PnlIdecNavPre::StatShr::StatShr(
const bool TxtMisAvail
, const bool TxtTouAvail
) : Block() {
this->TxtMisAvail = TxtMisAvail;
this->TxtTouAvail = TxtTouAvail;
mask = {TXTMISAVAIL, TXTTOUAVAIL};
};
void PnlIdecNavPre::StatShr::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "StatShrIdecNavPre";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StatitemShrIdecNavPre";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeBoolAttr(wr, itemtag, "sref", "TxtMisAvail", TxtMisAvail);
writeBoolAttr(wr, itemtag, "sref", "TxtTouAvail", TxtTouAvail);
xmlTextWriterEndElement(wr);
};
set<uint> PnlIdecNavPre::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (TxtMisAvail == comp->TxtMisAvail) insert(items, TXTMISAVAIL);
if (TxtTouAvail == comp->TxtTouAvail) insert(items, TXTTOUAVAIL);
return(items);
};
set<uint> PnlIdecNavPre::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {TXTMISAVAIL, TXTTOUAVAIL};
for (auto it=commitems.begin();it!=commitems.end();it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlIdecNavPre::Tag
******************************************************************************/
void PnlIdecNavPre::Tag::writeXML(
const uint ixIdecVLocale
, xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "TagIdecNavPre";
string itemtag;
if (shorttags) itemtag = "Ti";
else itemtag = "TagitemIdecNavPre";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
if (ixIdecVLocale == VecIdecVLocale::ENUS) {
writeStringAttr(wr, itemtag, "sref", "CptMis", "mission");
writeStringAttr(wr, itemtag, "sref", "CptTou", "tour");
} else if (ixIdecVLocale == VecIdecVLocale::DECH) {
writeStringAttr(wr, itemtag, "sref", "CptMis", "Mission");
writeStringAttr(wr, itemtag, "sref", "CptTou", "Tour");
};
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlIdecNavPre::DpchAppDo
******************************************************************************/
PnlIdecNavPre::DpchAppDo::DpchAppDo() : DpchAppIdec(VecIdecVDpch::DPCHAPPIDECNAVPREDO) {
ixVDo = 0;
};
string PnlIdecNavPre::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlIdecNavPre::DpchAppDo::readXML(
pthread_mutex_t* mScr
, map<string,ubigint>& descr
, xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string scrJref;
string srefIxVDo;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppIdecNavPreDo");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) {
jref = Scr::descramble(mScr, descr, scrJref);
add(JREF);
};
if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) {
ixVDo = VecVDo::getIx(srefIxVDo);
add(IXVDO);
};
} else {
};
};
/******************************************************************************
class PnlIdecNavPre::DpchEngData
******************************************************************************/
PnlIdecNavPre::DpchEngData::DpchEngData(
const ubigint jref
, ContInf* continf
, StatShr* statshr
, const set<uint>& mask
) : DpchEngIdec(VecIdecVDpch::DPCHENGIDECNAVPREDATA, jref) {
if (find(mask, ALL)) this->mask = {JREF, CONTINF, STATSHR, TAG};
else this->mask = mask;
if (find(this->mask, CONTINF) && continf) this->continf = *continf;
if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr;
};
string PnlIdecNavPre::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(CONTINF)) ss.push_back("continf");
if (has(STATSHR)) ss.push_back("statshr");
if (has(TAG)) ss.push_back("tag");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlIdecNavPre::DpchEngData::merge(
DpchEngIdec* dpcheng
) {
DpchEngData* src = (DpchEngData*) dpcheng;
if (src->has(JREF)) {jref = src->jref; add(JREF);};
if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);};
if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);};
if (src->has(TAG)) add(TAG);
};
void PnlIdecNavPre::DpchEngData::writeXML(
const uint ixIdecVLocale
, pthread_mutex_t* mScr
, map<ubigint,string>& scr
, map<string,ubigint>& descr
, xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchEngIdecNavPreData");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/idec");
if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(mScr, scr, descr, jref));
if (has(CONTINF)) continf.writeXML(wr);
if (has(STATSHR)) statshr.writeXML(wr);
if (has(TAG)) Tag::writeXML(ixIdecVLocale, wr);
xmlTextWriterEndElement(wr);
};
| [
"mpsitech@ungenio.local"
] | mpsitech@ungenio.local |
ab86e3926a4ddb7825b3674fc79a98e3bb9d7e29 | 8b5db3bc9f2afe52fce03a843e79454319f3c950 | /hardware/invensense/65xx/libsensors_iio/SensorBase.cpp | c01d394dc76648d808f4232ee58a6008cc28bbf7 | [
"Apache-2.0"
] | permissive | 10114395/android-5.0.0_r5 | 619a6ea78ebcbb6d2c44a31ed0c3f9d5b64455b2 | d023f08717af9bb61c2a273a040d3986a87422e1 | refs/heads/master | 2021-01-21T19:57:16.122808 | 2015-04-02T04:39:50 | 2015-04-02T04:39:50 | 33,306,407 | 2 | 2 | null | 2020-03-09T00:07:10 | 2015-04-02T11:58:28 | C | UTF-8 | C++ | false | false | 5,020 | cpp | /*
* Copyright (C) 2012 Invensense, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/select.h>
#include <cutils/log.h>
#include <linux/input.h>
#include <cutils/properties.h>
#include "SensorBase.h"
/*****************************************************************************/
// static vars
bool SensorBase::PROCESS_VERBOSE = false;
bool SensorBase::EXTRA_VERBOSE = false;
bool SensorBase::SYSFS_VERBOSE = false;
bool SensorBase::FUNC_ENTRY = false;
bool SensorBase::HANDLER_ENTRY = false;
bool SensorBase::ENG_VERBOSE = false;
bool SensorBase::INPUT_DATA = false;
bool SensorBase::HANDLER_DATA = false;
SensorBase::SensorBase(const char* dev_name,
const char* data_name)
: dev_name(dev_name),
data_name(data_name),
dev_fd(-1),
data_fd(-1)
{
if (data_name) {
data_fd = openInput(data_name);
}
char value[PROPERTY_VALUE_MAX];
property_get("invn.hal.verbose.basic", value, "0");
if (atoi(value)) {
PROCESS_VERBOSE = true;
}
property_get("invn.hal.verbose.extra", value, "0");
if (atoi(value)) {
EXTRA_VERBOSE = true;
}
property_get("invn.hal.verbose.sysfs", value, "0");
if (atoi(value)) {
SYSFS_VERBOSE = true;
}
property_get("invn.hal.verbose.engineering", value, "0");
if (atoi(value)) {
ENG_VERBOSE = true;
}
property_get("invn.hal.entry.function", value, "0");
if (atoi(value)) {
FUNC_ENTRY = true;
}
property_get("invn.hal.entry.handler", value, "0");
if (atoi(value)) {
HANDLER_ENTRY = true;
}
property_get("invn.hal.data.input", value, "0");
if (atoi(value)) {
INPUT_DATA = true;
}
property_get("invn.hal.data.handler", value, "0");
if (atoi(value)) {
HANDLER_DATA = true;
}
}
SensorBase::~SensorBase()
{
if (data_fd >= 0) {
close(data_fd);
}
if (dev_fd >= 0) {
close(dev_fd);
}
}
int SensorBase::open_device()
{
if (dev_fd<0 && dev_name) {
dev_fd = open(dev_name, O_RDONLY);
LOGE_IF(dev_fd<0, "Couldn't open %s (%s)", dev_name, strerror(errno));
}
return 0;
}
int SensorBase::close_device()
{
if (dev_fd >= 0) {
close(dev_fd);
dev_fd = -1;
}
return 0;
}
int SensorBase::getFd() const
{
if (!data_name) {
return dev_fd;
}
return data_fd;
}
int SensorBase::setDelay(int32_t handle, int64_t ns)
{
return 0;
}
bool SensorBase::hasPendingEvents() const
{
return false;
}
int64_t SensorBase::getTimestamp()
{
struct timespec t;
t.tv_sec = t.tv_nsec = 0;
clock_gettime(CLOCK_MONOTONIC, &t);
return int64_t(t.tv_sec) * 1000000000LL + t.tv_nsec;
}
int SensorBase::openInput(const char *inputName)
{
int fd = -1;
const char *dirname = "/dev/input";
char devname[PATH_MAX];
char *filename;
DIR *dir;
struct dirent *de;
dir = opendir(dirname);
if(dir == NULL)
return -1;
strcpy(devname, dirname);
filename = devname + strlen(devname);
*filename++ = '/';
while((de = readdir(dir))) {
if(de->d_name[0] == '.' &&
(de->d_name[1] == '\0' ||
(de->d_name[1] == '.' && de->d_name[2] == '\0')))
continue;
strcpy(filename, de->d_name);
fd = open(devname, O_RDONLY);
LOGV_IF(EXTRA_VERBOSE, "path open %s", devname);
LOGI("path open %s", devname);
if (fd >= 0) {
char name[80];
if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) {
name[0] = '\0';
}
LOGV_IF(EXTRA_VERBOSE, "name read %s", name);
if (!strcmp(name, inputName)) {
strcpy(input_name, filename);
break;
} else {
close(fd);
fd = -1;
}
}
}
closedir(dir);
LOGE_IF(fd < 0, "couldn't find '%s' input device", inputName);
return fd;
}
int SensorBase::enable(int32_t handle, int enabled)
{
return 0;
}
int SensorBase::query(int what, int* value)
{
return 0;
}
int SensorBase::batch(int handle, int flags, int64_t period_ns, int64_t timeout)
{
return 0;
}
int SensorBase::flush(int handle)
{
return 0;
}
| [
"xdtianyu@gmail.com"
] | xdtianyu@gmail.com |
ff1bc68ac1c1bcb6f6909fee8a169c5298998a4c | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/k_anonymity_service/k_anonymity_trust_token_getter.cc | 488cfc357870df6582cba5bdc9fdb1883376ecd4 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 19,155 | cc | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/k_anonymity_service/k_anonymity_trust_token_getter.h"
#include "base/json/json_writer.h"
#include "base/json/values_util.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/k_anonymity_service/k_anonymity_service_metrics.h"
#include "chrome/browser/k_anonymity_service/k_anonymity_service_urls.h"
#include "chrome/common/chrome_features.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/gaia/gaia_constants.h"
#include "google_apis/google_api_keys.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "net/base/load_flags.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
namespace {
constexpr base::TimeDelta kRequestMargin = base::Minutes(5);
constexpr base::TimeDelta kRequestTimeout = base::Minutes(1);
constexpr net::NetworkTrafficAnnotationTag
kKAnonymityServiceGetTokenTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("k_anonymity_service_get_token",
R"(
semantics {
sender: "Chrome k-Anonymity Service Client"
description:
"Request to the Chrome k-Anonymity Auth server to obtain a trust token"
trigger:
"The Chrome k-Anonymity Service Client is out of trust tokens"
data:
"Chrome sign-in OAuth Token"
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Disable features using k-anonymity, such as FLEDGE and Attribution "
"Reporting."
chrome_policy {
}
}
comments:
""
)");
} // namespace
KAnonymityTrustTokenGetter::PendingRequest::PendingRequest(
KAnonymityTrustTokenGetter::TryGetTrustTokenAndKeyCallback callback)
: request_start(base::TimeTicks::Now()), callback(std::move(callback)) {}
KAnonymityTrustTokenGetter::PendingRequest::~PendingRequest() = default;
KAnonymityTrustTokenGetter::PendingRequest::PendingRequest(
KAnonymityTrustTokenGetter::PendingRequest&&) noexcept = default;
KAnonymityTrustTokenGetter::PendingRequest&
KAnonymityTrustTokenGetter::PendingRequest::operator=(
KAnonymityTrustTokenGetter::PendingRequest&&) noexcept = default;
KAnonymityTrustTokenGetter::KAnonymityTrustTokenGetter(
signin::IdentityManager* identity_manager,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
network::mojom::TrustTokenQueryAnswerer* answerer,
KAnonymityServiceStorage* storage)
: identity_manager_(identity_manager),
url_loader_factory_(std::move(url_loader_factory)),
trust_token_query_answerer_(answerer),
storage_(storage) {
auth_origin_ =
url::Origin::Create(GURL(features::kKAnonymityServiceAuthServer.Get()));
isolation_info_ = net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kOther, auth_origin_, auth_origin_,
net::SiteForCookies());
}
KAnonymityTrustTokenGetter::~KAnonymityTrustTokenGetter() = default;
void KAnonymityTrustTokenGetter::TryGetTrustTokenAndKey(
TryGetTrustTokenAndKeyCallback callback) {
if ((!base::FeatureList::IsEnabled(network::features::kPrivateStateTokens) &&
!base::FeatureList::IsEnabled(network::features::kFledgePst)) ||
!identity_manager_ ||
!identity_manager_->HasPrimaryAccount(signin::ConsentLevel::kSignin)) {
std::move(callback).Run(absl::nullopt);
return;
}
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kTryGetTrustTokenAndKey);
bool currently_fetching = pending_callbacks_.size() > 0;
pending_callbacks_.emplace_back(std::move(callback));
if (currently_fetching)
return;
TryGetTrustTokenAndKeyInternal();
}
// This function is where we start for each queued request.
void KAnonymityTrustTokenGetter::TryGetTrustTokenAndKeyInternal() {
CheckAccessToken();
}
void KAnonymityTrustTokenGetter::CheckAccessToken() {
if (access_token_.expiration_time <= base::Time::Now() + kRequestMargin) {
RequestAccessToken();
return;
}
CheckTrustTokenKeyCommitment();
}
void KAnonymityTrustTokenGetter::RequestAccessToken() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kRequestAccessToken);
// Choose scopes to obtain for the access token.
signin::ScopeSet scopes;
scopes.insert(GaiaConstants::kKAnonymityServiceOAuth2Scope);
// Choose the mode in which to fetch the access token:
// see AccessTokenFetcher::Mode below for definitions.
auto mode =
signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable;
// Create the fetcher.
access_token_fetcher_ =
std::make_unique<signin::PrimaryAccountAccessTokenFetcher>(
/*consumer_name=*/"KAnonymityService", identity_manager_, scopes,
base::BindOnce(
&KAnonymityTrustTokenGetter::OnAccessTokenRequestCompleted,
weak_ptr_factory_.GetWeakPtr()),
mode, signin::ConsentLevel::kSignin);
}
void KAnonymityTrustTokenGetter::OnAccessTokenRequestCompleted(
GoogleServiceAuthError error,
signin::AccessTokenInfo access_token_info) {
access_token_fetcher_.reset();
if (error.state() != GoogleServiceAuthError::NONE) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kAccessTokenRequestFailed);
FailAllCallbacks();
return;
}
access_token_ = access_token_info;
CheckTrustTokenKeyCommitment();
}
void KAnonymityTrustTokenGetter::CheckTrustTokenKeyCommitment() {
absl::optional<KeyAndNonUniqueUserIdWithExpiration> key_commitment =
storage_->GetKeyAndNonUniqueUserId();
if (!key_commitment ||
key_commitment->expiration <= base::Time::Now() + kRequestMargin) {
FetchNonUniqueUserId();
return;
}
CheckTrustTokens();
}
void KAnonymityTrustTokenGetter::FetchNonUniqueUserId() {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientID);
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url =
auth_origin_.GetURL().Resolve(kGenNonUniqueUserIdPath);
resource_request->headers.SetHeader(
net::HttpRequestHeaders::kAuthorization,
base::StrCat({"Bearer ", access_token_.token}));
resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
resource_request->trusted_params.emplace();
resource_request->trusted_params->isolation_info = isolation_info_;
url_loader_ = network::SimpleURLLoader::Create(
std::move(resource_request), kKAnonymityServiceGetTokenTrafficAnnotation);
url_loader_->SetTimeoutDuration(kRequestTimeout);
// The response should just contain a JSON message containing a uint32.
url_loader_->DownloadToString(
url_loader_factory_.get(),
base::BindOnce(&KAnonymityTrustTokenGetter::OnFetchedNonUniqueUserId,
weak_ptr_factory_.GetWeakPtr()),
/*max_body_size=*/1024);
}
void KAnonymityTrustTokenGetter::OnFetchedNonUniqueUserId(
std::unique_ptr<std::string> response) {
url_loader_.reset();
if (!response) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientIDFailed);
FailAllCallbacks();
return;
}
data_decoder::DataDecoder::ParseJsonIsolated(
*response,
base::BindOnce(&KAnonymityTrustTokenGetter::OnParsedNonUniqueUserId,
weak_ptr_factory_.GetWeakPtr()));
}
void KAnonymityTrustTokenGetter::OnParsedNonUniqueUserId(
data_decoder::DataDecoder::ValueOrError result) {
if (!result.has_value()) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientIDParseError);
FailAllCallbacks();
return;
}
base::Value::Dict* response_dict = result->GetIfDict();
if (!response_dict) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientIDParseError);
FailAllCallbacks();
return;
}
absl::optional<int> maybe_non_unique_user_id =
response_dict->FindInt("shortClientIdentifier");
if (!maybe_non_unique_user_id) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientIDParseError);
FailAllCallbacks();
return;
}
FetchTrustTokenKeyCommitment(*maybe_non_unique_user_id);
}
void KAnonymityTrustTokenGetter::FetchTrustTokenKeyCommitment(
int non_unique_user_id) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKey);
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = auth_origin_.GetURL().Resolve(base::StringPrintf(
kFetchKeysPathFmt, non_unique_user_id, google_apis::GetAPIKey().c_str()));
resource_request->credentials_mode =
network::mojom::CredentialsMode::kOmit; // No credentials required for
// key fetch.
resource_request->trusted_params.emplace();
resource_request->trusted_params->isolation_info = isolation_info_;
url_loader_ = network::SimpleURLLoader::Create(
std::move(resource_request), kKAnonymityServiceGetTokenTrafficAnnotation);
url_loader_->SetTimeoutDuration(kRequestTimeout);
url_loader_->DownloadToString(
url_loader_factory_.get(),
base::BindOnce(
&KAnonymityTrustTokenGetter::OnFetchedTrustTokenKeyCommitment,
weak_ptr_factory_.GetWeakPtr(), non_unique_user_id),
/*max_body_size=*/4096);
}
void KAnonymityTrustTokenGetter::OnFetchedTrustTokenKeyCommitment(
int non_unique_user_id,
std::unique_ptr<std::string> response) {
if (url_loader_->NetError() != net::OK) {
url_loader_.reset();
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyFailed);
FailAllCallbacks();
return;
}
url_loader_.reset();
data_decoder::DataDecoder::ParseJsonIsolated(
*response,
base::BindOnce(
&KAnonymityTrustTokenGetter::OnParsedTrustTokenKeyCommitment,
weak_ptr_factory_.GetWeakPtr(), non_unique_user_id));
}
// The server sends the key commitment in a custom message format. We have to
// reformat the response from the server into a format the browser understands
// (V3 trust token key commitment). See the explainer here:
// https://github.com/WICG/trust-token-api/blob/main/ISSUER_PROTOCOL.md
void KAnonymityTrustTokenGetter::OnParsedTrustTokenKeyCommitment(
int non_unique_user_id,
data_decoder::DataDecoder::ValueOrError result) {
if (!result.has_value()) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
base::Value::Dict* response_dict = result->GetIfDict();
if (!response_dict) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
std::string* maybe_version = response_dict->FindString("protocolVersion");
if (!maybe_version) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
const absl::optional<int> maybe_id = response_dict->FindInt("id");
if (!maybe_id) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
const absl::optional<int> maybe_batchsize =
response_dict->FindInt("batchSize");
if (!maybe_batchsize) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
base::Value::List* maybe_keys = response_dict->FindList("keys");
if (!maybe_keys) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
if (maybe_keys->empty()) {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
int64_t max_expiry = 0;
base::Value::Dict keys_out;
for (base::Value& key_commitment : *maybe_keys) {
base::Value::Dict* key_commit_dict = key_commitment.GetIfDict();
if (!key_commit_dict) {
DLOG(ERROR) << "Key commitment not a dict: "
<< key_commitment.DebugString();
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
const std::string* maybe_key = key_commit_dict->FindString("keyMaterial");
absl::optional<int> maybe_key_id =
key_commit_dict->FindInt("keyIdentifier");
const std::string* maybe_expiry =
key_commit_dict->FindString("expirationTimestampUsec");
int64_t expiry;
if (!maybe_key || !maybe_key_id || !maybe_expiry) {
DLOG(ERROR) << "Key commitment missing required field: "
<< key_commitment.DebugString();
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
if (!base::StringToInt64(*maybe_expiry, &expiry)) {
DLOG(ERROR) << "Key commitment expiry has invalid format: "
<< *maybe_expiry;
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError);
FailAllCallbacks();
return;
}
max_expiry = std::max(max_expiry, expiry);
base::Value::Dict key_out;
key_out.Set("Y", *maybe_key);
key_out.Set("expiry", *maybe_expiry);
keys_out.Set(base::NumberToString(*maybe_key_id), std::move(key_out));
}
base::Value::Dict key_commitment_value;
key_commitment_value.Set("protocol_version", *maybe_version);
key_commitment_value.Set("id", *maybe_id);
key_commitment_value.Set("batchsize", *maybe_batchsize);
key_commitment_value.Set("keys", std::move(keys_out));
base::Value::Dict outer_commitment;
outer_commitment.Set(*maybe_version, std::move(key_commitment_value));
std::string key_commitment_str;
base::JSONWriter::Write(outer_commitment, &key_commitment_str);
KeyAndNonUniqueUserIdWithExpiration key_commitment{
KeyAndNonUniqueUserId{key_commitment_str, non_unique_user_id},
base::Time::UnixEpoch() + base::Microseconds(max_expiry)};
storage_->UpdateKeyAndNonUniqueUserId(key_commitment);
CheckTrustTokens();
}
void KAnonymityTrustTokenGetter::CheckTrustTokens() {
trust_token_query_answerer_->HasTrustTokens(
auth_origin_,
base::BindOnce(&KAnonymityTrustTokenGetter::OnHasTrustTokensComplete,
weak_ptr_factory_.GetWeakPtr()));
}
void KAnonymityTrustTokenGetter::OnHasTrustTokensComplete(
network::mojom::HasTrustTokensResultPtr result) {
if (!result ||
result->status != network::mojom::TrustTokenOperationStatus::kOk) {
DLOG(ERROR) << "Failed checking trust tokens " << result->status;
FailAllCallbacks();
return;
}
if (!result->has_trust_tokens) {
FetchTrustToken();
return;
}
CompleteOneRequest();
}
void KAnonymityTrustTokenGetter::FetchTrustToken() {
auto key_commitment = storage_->GetKeyAndNonUniqueUserId();
DCHECK(key_commitment);
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustToken);
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = auth_origin_.GetURL().Resolve(base::StringPrintf(
kIssueTrustTokenPathFmt, key_commitment->key_and_id.non_unique_user_id));
resource_request->method = net::HttpRequestHeaders::kPostMethod;
resource_request->headers.SetHeader(
net::HttpRequestHeaders::kAuthorization,
base::StrCat({"Bearer ", access_token_.token}));
resource_request->credentials_mode =
network::mojom::CredentialsMode::kOmit; // No cache read, always download
// from the network.
resource_request->load_flags =
net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_CACHE;
resource_request->trusted_params.emplace();
resource_request->trusted_params->isolation_info = isolation_info_;
network::mojom::TrustTokenParamsPtr params =
network::mojom::TrustTokenParams::New();
params->version =
network::mojom::TrustTokenMajorVersion::kPrivateStateTokenV1;
params->operation = network::mojom::TrustTokenOperationType::kIssuance;
params->custom_key_commitment = key_commitment->key_and_id.key_commitment;
resource_request->trust_token_params = *params;
url_loader_ = network::SimpleURLLoader::Create(
std::move(resource_request), kKAnonymityServiceGetTokenTrafficAnnotation);
url_loader_->SetTimeoutDuration(kRequestTimeout);
url_loader_->DownloadHeadersOnly(
url_loader_factory_.get(),
base::BindOnce(&KAnonymityTrustTokenGetter::OnFetchedTrustToken,
weak_ptr_factory_.GetWeakPtr()));
}
void KAnonymityTrustTokenGetter::OnFetchedTrustToken(
scoped_refptr<net::HttpResponseHeaders> headers) {
if (url_loader_->NetError() != net::OK) {
DLOG(ERROR) << "Couldn't get trust token: " << url_loader_->NetError();
url_loader_.reset();
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kFetchTrustTokenFailed);
FailAllCallbacks();
return;
}
url_loader_.reset();
// If the fetch succeeded, that means that the response included the trust
// tokens we requested. They are stored in the network service so we can
// redeem them later.
CompleteOneRequest();
}
void KAnonymityTrustTokenGetter::FailAllCallbacks() {
while (!pending_callbacks_.empty())
DoCallback(false);
}
void KAnonymityTrustTokenGetter::CompleteOneRequest() {
RecordTrustTokenGetterAction(
KAnonymityTrustTokenGetterAction::kGetTrustTokenSuccess);
// Only record timing UMA when we actually fetched a token.
RecordTrustTokenGet(pending_callbacks_.front().request_start,
base::TimeTicks::Now());
DoCallback(true);
if (!pending_callbacks_.empty())
TryGetTrustTokenAndKeyInternal();
}
void KAnonymityTrustTokenGetter::DoCallback(bool status) {
DCHECK(!pending_callbacks_.empty());
absl::optional<KeyAndNonUniqueUserId> result;
if (status) {
auto key_commitment = storage_->GetKeyAndNonUniqueUserId();
DCHECK(key_commitment);
result = key_commitment->key_and_id;
}
// We call the callback *before* removing the current request from the list.
// It is possible that the callback may synchronously enqueue another request.
// If we remove the current request first then enqueuing the request would
// start another thread of execution since there was an empty queue.
std::move(pending_callbacks_.front().callback).Run(result);
pending_callbacks_.pop_front();
}
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
60b04fe2ec36ad5f0fe2c1463dadc9fd8fdb9f9c | 96825cf87690c768a60b0fbc7138a43ca22edaa9 | /Source/BlueprintRetarget/Public/BlueprintRetarget.h | 6e963f4623464174b676580c9c90aa0a9e23a74d | [
"Apache-2.0"
] | permissive | Hengle/BlueprintRetarget | 1ff639ff1866af73676af04f4f9e348f88f315e6 | a7e3cb959dd4a8902d29d3a6947dfbb21b575524 | refs/heads/master | 2022-11-09T01:57:07.599744 | 2020-06-20T07:42:48 | 2020-06-20T07:42:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | // Copyright 2015-2020 Piperift. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
DECLARE_LOG_CATEGORY_EXTERN(LogBlueprintReparent, All, All);
class FToolBarBuilder;
class FMenuBuilder;
class FBlueprintRetargetModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};
| [
"muit@piperift.com"
] | muit@piperift.com |
4efd3c8c0e8ff0f2749316a0e8d8990a4c5d4ff0 | 7b48fcad9a50b8fe2315e20efc7bc2ddefdafea3 | /longest_palindromic_substring/lsp_extend.cpp | e32abb78b25450de4064fb75e28a78f3d18ac725 | [] | no_license | TheWaySoFar/LeetCode_Solution | c96ea26f30c310ae4cc917d21d69809a98eb7b28 | 1ae152d9e261a3587100ccfcadc5097dc1d1ea08 | refs/heads/master | 2020-03-10T00:57:45.025959 | 2018-08-01T14:04:22 | 2018-08-01T14:04:22 | 129,096,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | cpp | #include<iostream>
#include<string>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int len = s.size();
int ans = 1, ansl = 0;
for(int i=0; i<len; i++){
extend(i, i, s, ans, ansl);
extend(i, i+1, s, ans, ansl);
}
//return string(s.begin()+ansl, s.begin()+ansl+ans);
return s.substr(ansl, ans);
}
void extend(int l, int r, string s,int & ans, int & ansl){
int len = s.size();
while(l>=0&&r<len&&s[l]==s[r]){
l--,r++;
}
if(ans < r-l-1){
ans = r-l-1;
ansl = l+1;
}
}
};
int main(){
Solution s;
cout<<s.longestPalindrome("babad")<<endl;
cout<<s.longestPalindrome("cbbd")<<endl;
cout<<s.longestPalindrome("abcddcba")<<endl;
return 0;
} | [
"103664210@qq.com"
] | 103664210@qq.com |
6495bab4408baf0e3f71f8ddfe1c626d27ceac87 | b80b82c336e2d59b0573f4515a26d4684aff9f1a | /projekt/Options.h | 07f7dd7cda864fc9d0be73211754d9d631f2e9cc | [] | no_license | ancf/sfml-2d-game | 3127a3412915ca5af7194ee747584b82bf76c441 | b408d59d20d38610342b7fb3b44fff691d713611 | refs/heads/master | 2023-05-02T10:12:25.204459 | 2021-05-26T11:04:07 | 2021-05-26T11:04:07 | 371,001,376 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 582 | h | #pragma once
#include "SFML/Graphics.hpp"
class Options
{
public:
Options(float width, float height);
~Options();
enum DifficultyLevel { Easy, Medium, Hard };
int SelectedVolume;
std::string SelectedName;
// void draw(sf::RenderWindow &menu_window);
// void draw_test(sf::RenderWindow &menu_window);
// void upwards();
// void downwards();
// int GetPressedIndex() { return SelectedIndex; }
private:
// int ButtonWidth = 300;
// int ButtonHeight = 50;
// sf::Font def;
// sf::Text MenuText[POSITIONS_NUMBER];
// sf::RectangleShape MenuButton[POSITIONS_NUMBER];
};
| [
"krystian1998k@gmail.com"
] | krystian1998k@gmail.com |
9f6fdb582f429d3eb9c06b3638fdc09a9fad06fd | a3947da58918e8508178e75c05d38ea1bef6d5ae | /DataHeaders/mission.h | 8fc3aae804caa90826513cc00339d228a43c2fab | [] | no_license | oygx210/cute42 | a4f59a716cd8d7f647823458d99210849a4aade5 | 6150275f082d01dde3fe12630d669fd7f14998c2 | refs/heads/main | 2023-03-17T22:14:33.807296 | 2021-03-04T09:07:08 | 2021-03-04T09:07:08 | 384,966,099 | 0 | 1 | null | 2021-07-11T14:16:52 | 2021-07-11T14:16:52 | null | UTF-8 | C++ | false | false | 3,550 | h | #ifndef MISSION_H
#define MISSION_H
#include <QString>
#include <QVector>
#include <QVariant>
#include <QDataStream>
#include <QDebug>
#include "qt42baseclass.h"
#include "qt42_headers.h"
class SpacecraftHeader;
class OrbitHeader;
class MissionHolder;
class Spacecraft;
class Orbit;
class Mission : public Qt42BaseClass
{
public:
Mission(MissionHolder* MH = nullptr);
Mission(const Mission& otherMission);
~Mission() override;
Mission& operator=(const Mission& otherMission);
bool operator==(const Mission& otherMission) const;
objectType type() const override { return m_type;}
QString name() const override {return m_name;}
int index() const override {return m_index;}
void updateIndex();
int numberOfSpacecraft() const;
int numberOfOrbit() const;
bool hasName(const QString& name);
bool createSpacecraft();
bool removeSpacecraft(Spacecraft* SC);
Spacecraft* spacecraft(const int& index);
bool createOrbit();
bool removeOrbit(Orbit* SC);
Orbit* orbit(const int& index);
int numberOfHeaders() const {return m_numberOfHeaders;}
const QString defaultName = "Default Mission";
void rename(const QString& newName);
void setDirectroy(const QString& dir) {m_directory = dir;}
QString directory() const {return m_directory;}
SpacecraftHeader* spacecraftheader() const {return m_SpacecraftHeader;}
OrbitHeader* orbitheader() const {return m_OrbitHeader;}
InpSimHeader* inpsimheader() const {return m_InpSimHeader;}
FOVHeader* fOVHeader() {return m_FOVHeader;}
InpIPCHeader* inpIpcHeader() const {return m_InpIPCHeader;}
GraphicsHeader* graphisHeader() const {return m_graphisHeader;}
InpTDRs* inpTDRs() const {return m_inpTDRs;}
RegionHeader* regionHeader() const {return m_regionHeader;}
/** void "setMissionHolder(MissionHolder* mh)" and "void setIndex(const int& index)" are
* for data seriaization (operator << and operator >>) **/
void setMissionHolder(MissionHolder* mh) {m_MissionHolder = mh;}
void setIndex(const int& index) {m_index = index;}
SpacecraftHeader m_SpacecraftHeaderObject = SpacecraftHeader();
OrbitHeader m_OrbitHeaderObejct = OrbitHeader();
InpSimHeader m_InpSimHeaderObject = InpSimHeader();
FOVHeader m_FOVHeaderObject = FOVHeader();
InpIPCHeader m_InpIPCHeaderObject = InpIPCHeader();
GraphicsHeader m_GraphisHeaderObject = GraphicsHeader();
InpTDRs m_inpTDRsObject = InpTDRs();
RegionHeader m_regionHeaderObject = RegionHeader();
/** end **/
friend QDataStream& operator<< (QDataStream& dataStream, const Mission& m);
friend QDataStream& operator>> (QDataStream& dataStream, Mission& m);
friend QDebug operator<< (QDebug dataStream, const Mission& m);
private:
void changeType(const objectType& type) override
{Qt42BaseClass::changeType(type);}
const objectType m_type = MISSION;
QString m_name = "Mission"; // the name of the mission;
QString m_directory = QString();
int m_index = -1; // the index of the mission;
MissionHolder* m_MissionHolder = nullptr;
SpacecraftHeader* m_SpacecraftHeader = nullptr;
OrbitHeader* m_OrbitHeader = nullptr;
InpSimHeader* m_InpSimHeader = nullptr;
FOVHeader* m_FOVHeader = nullptr;
InpIPCHeader* m_InpIPCHeader = nullptr;
GraphicsHeader* m_graphisHeader = nullptr;
InpTDRs* m_inpTDRs = nullptr;
RegionHeader* m_regionHeader = nullptr;
int m_numberOfHeaders = 5;
};
Q_DECLARE_METATYPE(Mission);
#endif // MISSION_H
| [
"ytsoroy@gmail.com"
] | ytsoroy@gmail.com |
17f67977d81a8ea145ea22c3826460f7752b9678 | 15419e6b114d5b89e78648dbae52a0aae276b673 | /Contests/Weekly Team Practice Contests/Week 22 - 13th Iran Internet ACM ICPC 2015 - Shiraz/D - AC.cpp | 1779f05d8bccd578645df1309f8eff03f04e589d | [] | no_license | ImnIrdst/ICPC-Practice-2015-TiZii | 7cde07617d8ebf90dc8a4baec4d9faec49f79d13 | 73bb0f84e7a003e154d685fa598002f8b9498878 | refs/heads/master | 2021-01-10T16:29:34.490848 | 2016-04-08T04:13:37 | 2016-04-08T04:13:37 | 55,749,815 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | cpp | #include<iostream>
#include<algorithm>
#include<vector>
#include<functional>
#include<sstream>
#include<string>
#include<set>
#include<map>
using namespace std;
int main()
{
int tc;
cin >> tc;
while (tc--) {
int n, m;
cin >> n >> m;
vector<int> vote_hist(n + 1, 0);
map<int, vector<int> > votes;
int today = 0;
cin.ignore();
string line;
//read & save input
for (int i = 1; i <= m; ++i) {
getline(cin, line);
stringstream sstr(line);
int day_id, free_day;
sstr >> day_id;
if (!votes.count(day_id)) {
votes[day_id] = vector<int>(n + 1, 0);
}
while (sstr >> free_day) {
votes[day_id][free_day]++;
}
}
bool cond = true;
int last_day = -1;
while(today <= n - 1 && cond){
//add vote of today
int tommorow = today + 1;
if (votes.count(today)) {
last_day = today;//????????????????
//add next day votes to histogram
for (int i = tommorow; i <= n; ++i) {
vote_hist[i] += votes[today][i];
}
}
//check if there is someday better that next day exist
cond = false;
for (int i = tommorow + 1; i <= n; ++i) {
if (vote_hist[i] >= vote_hist[tommorow]) {
cond = true;
break;
}
}
today++;
}
if (today <= n - 1 || last_day == -1) {
cout << today << endl;
}
else {
int m = vote_hist[last_day+1];
int index = last_day+1;
for (int i = index + 1; i <= n; ++i) {
if (vote_hist[i] >= m) {
m = vote_hist[i];
index = i;
}
}
cout << index << endl;
}
}
return 0;
} | [
"imn.irdst@gmail.com"
] | imn.irdst@gmail.com |
1d88fb9b79d7ac1b965e3969ba0457f15e975f47 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/admin/activec/designer/vb98ctls/mssnapr/mssnapr/ppgwrap.cpp | ab676430d1bbf99deec8fb943fc7749fe3bae6d2 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,359 | cpp | //=--------------------------------------------------------------------------=
// ppgwrap.cpp
//=--------------------------------------------------------------------------=
// Copyright (c) 1999, Microsoft Corp.
// All Rights Reserved
// Information Contained Herein Is Proprietary and Confidential.
//=--------------------------------------------------------------------------=
//
// CPropertyPageWrapper class implementation
//
//=--------------------------------------------------------------------------=
#include "pch.h"
#include "common.h"
#include "ppgwrap.h"
#include "tls.h"
// for ASSERT and FAIL
//
SZTHISFILE
const UINT CPropertyPageWrapper::m_RedrawMsg = ::RegisterWindowMessage("Microsoft Visual Basic Snap-in Designer Property Page Redraw Message");
const UINT CPropertyPageWrapper::m_InitMsg = ::RegisterWindowMessage("Microsoft Visual Basic Snap-in Designer Property Page Init Message");
DLGTEMPLATE CPropertyPageWrapper::m_BaseDlgTemplate =
{
WS_TABSTOP | WS_CHILD | DS_CONTROL, // DWORD style;
WS_EX_CONTROLPARENT, // DWORD dwExtendedStyle;
0, // WORD cdit; - no controls in this dialog box
0, // short x; dimensions are set per IPropertyPage::GetPageInfo()
0, // short y;
0, // short cx;
0 // short cy;
};
#define MAX_DLGS 128
// Definition of data stored in TLS for each thread that displays property pages
typedef struct
{
HHOOK hHook; // HHOOK for this thread
UINT cPages; // number of existing property pages
CPropertyPageWrapper *ppgActive; // ptr to the currently active page
} TLSDATA;
// These resource IDs are taken from \nt\private\shell\comctl32\rcids.h.
// We need to know the IDs of the Back, Next and Finish buttons on a wizard
// or else we can't make tabbing work. This is a nasty dependency but there is
// no other way to handle this.
#define IDD_BACK 0x3023
#define IDD_NEXT 0x3024
#define IDD_FINISH 0x3025
#pragma warning(disable:4355) // using 'this' in constructor
CPropertyPageWrapper::CPropertyPageWrapper(IUnknown *punkOuter) :
CSnapInAutomationObject(punkOuter,
OBJECT_TYPE_PROPERTYPAGEWRAPPER,
static_cast<IPropertyPageSite *>(this),
static_cast<CPropertyPageWrapper *>(this),
0, // no property pages
NULL, // no property pages
NULL) // no persistence
{
InitMemberVariables();
}
#pragma warning(default:4355) // using 'this' in constructor
IUnknown *CPropertyPageWrapper::Create(IUnknown *punkOuter)
{
HRESULT hr = S_OK;
CPropertyPageWrapper *pPropertyPage = New CPropertyPageWrapper(punkOuter);
if (NULL == pPropertyPage)
{
hr = SID_E_OUTOFMEMORY;
GLOBAL_EXCEPTION_CHECK_GO(hr);
}
if ( (0 == m_RedrawMsg) || (0 == m_InitMsg) )
{
hr = SID_E_SYSTEM_ERROR;
GLOBAL_EXCEPTION_CHECK_GO(hr);
}
Error:
if (FAILEDHR(hr))
{
if (NULL != pPropertyPage)
{
delete pPropertyPage;
}
return NULL;
}
else
{
return pPropertyPage->PrivateUnknown();
}
}
CPropertyPageWrapper::~CPropertyPageWrapper()
{
ULONG i = 0;
IUnknown *punkObject = NULL; // Don't Release
// Remove this dialog from the message hook TLS data. If there are
// no more dialogs remaining then remove the hook. This should have happened
// in OnDestroy during WM_DESTROY processing but just in case we double
// check here.
(void)RemoveMsgFilterHook();
if (NULL != m_pPropertySheet)
{
m_pPropertySheet->Release();
}
if (NULL != m_pTemplate)
{
::CtlFree(m_pTemplate);
}
// If the marshaling streams are still alive then we need to release
// the marshal data. The easiest way to do this is to simply unmarshal
// the interface pointer. We do this before releasing the held pointers
// below. This case is actually not that rare because it can easily occur
// if the user displays a multi-page property sheet and doesn't click
// on all the tabs. In that case, the streams were created before the
// pages were created but as no WM_INITDIALOG was received, they were
// never unmarshaled. This can also occur in a wizard where the user
// clicks cancel before visiting all of the pages in the wizard.
if (NULL != m_apiObjectStreams)
{
for (i = 0; i < m_cObjects; i++)
{
if (NULL != m_apiObjectStreams[i])
{
(void)::CoGetInterfaceAndReleaseStream(
m_apiObjectStreams[i],
IID_IUnknown,
reinterpret_cast<void **>(&punkObject));
m_apiObjectStreams[i] = NULL;
RELEASE(punkObject);
}
}
CtlFree(m_apiObjectStreams);
}
if (NULL != m_piSnapInStream)
{
(void)::CoGetInterfaceAndReleaseStream(m_piSnapInStream,
IID_ISnapIn,
reinterpret_cast<void **>(&m_piSnapIn));
m_piSnapInStream = NULL;
}
if ( ISPRESENT(m_varInitData) && (NULL != m_piInitDataStream) )
{
if (VT_UNKNOWN == m_varInitData.vt)
{
m_varInitData.punkVal = NULL;
(void)::CoGetInterfaceAndReleaseStream(m_piInitDataStream,
IID_IUnknown,
reinterpret_cast<void **>(&m_varInitData.punkVal));
}
else if (VT_DISPATCH == m_varInitData.vt)
{
m_varInitData.pdispVal = NULL;
(void)::CoGetInterfaceAndReleaseStream(m_piInitDataStream,
IID_IDispatch,
reinterpret_cast<void **>(&m_varInitData.pdispVal));
}
m_piInitDataStream = NULL;
}
if (NULL != m_piMMCPropertySheetStream)
{
(void)::CoGetInterfaceAndReleaseStream(m_piMMCPropertySheetStream,
IID_IMMCPropertySheet,
reinterpret_cast<void **>(&m_piMMCPropertySheet));
m_piMMCPropertySheetStream = NULL;
}
RELEASE(m_piSnapIn);
RELEASE(m_pdispConfigObject);
RELEASE(m_piPropertyPage);
RELEASE(m_piMMCPropertyPage);
RELEASE(m_piMMCPropertySheet);
RELEASE(m_piWizardPage);
(void)::VariantClear(&m_varInitData);
InitMemberVariables();
}
void CPropertyPageWrapper::InitMemberVariables()
{
m_pPropertySheet = NULL;
m_piPropertyPage = NULL;
m_piMMCPropertyPage = NULL;
m_piMMCPropertySheet = NULL;
m_piWizardPage = NULL;
m_fWizard = FALSE;
m_cObjects = 0;
m_apiObjectStreams = NULL;
m_piSnapInStream = NULL;
m_piInitDataStream = NULL;
m_piMMCPropertySheetStream = NULL;
m_piSnapIn = NULL;
m_pdispConfigObject = NULL;
m_pTemplate = NULL;
m_hwndDlg = NULL;
m_hwndSheet = NULL;
m_clsidPage = CLSID_NULL;
::VariantInit(&m_varInitData);
m_fIsRemote = FALSE;
m_fNeedToRemoveHook = FALSE;
}
HRESULT CPropertyPageWrapper::CreatePage
(
CPropertySheet *pPropertySheet,
CLSID clsidPage,
BOOL fWizard,
BOOL fConfigWizard,
ULONG cObjects,
IUnknown **apunkObjects,
ISnapIn *piSnapIn,
short cxPage,
short cyPage,
VARIANT varInitData,
BOOL fIsRemote,
DLGTEMPLATE **ppTemplate
)
{
HRESULT hr = S_OK;
ULONG i = 0;
// AddRef and store the owning property sheet pointer
if (NULL != m_pPropertySheet)
{
m_pPropertySheet->Release();
}
if (NULL == pPropertySheet)
{
hr = SID_E_INTERNAL;
EXCEPTION_CHECK_GO(hr);
}
pPropertySheet->AddRef();
m_pPropertySheet = pPropertySheet;
m_fWizard = fWizard;
m_fConfigWizard = fConfigWizard;
m_fIsRemote = fIsRemote;
// Store the page's CLSID so that OnInitDialog() will have access to it
// to create the real instance of the page. We cannot create the real
// instance here because we are not running in the thread that will be used
// for the property sheet. MMC will run the property sheet in a new thread
// that it will create in order to keep it modeless and so that it will not
// affect the console.
m_clsidPage = clsidPage;
// Create the dialog template and initialize it with common values
m_pTemplate = (DLGTEMPLATE *)::CtlAllocZero(sizeof(m_BaseDlgTemplate) +
(3 * sizeof(int))); // for menu, class, title
if (NULL == m_pTemplate)
{
hr = SID_E_OUTOFMEMORY;
EXCEPTION_CHECK_GO(hr);
}
::memcpy(m_pTemplate, &m_BaseDlgTemplate, sizeof(*m_pTemplate));
m_pTemplate->cx = cxPage;
m_pTemplate->cy = cyPage;
// If this is a wizard then we have the ISnapIn so we can fire
// ConfigurationComplete. Marshal the interface into a stream
// and save the stream so that we can unmarshal it when the page is
// created in MMC's property sheet thread. The returned IStream is free
// threaded and can be kept in a member variable.
if (NULL != piSnapIn)
{
hr = ::CoMarshalInterThreadInterfaceInStream(IID_ISnapIn,
piSnapIn,
&m_piSnapInStream);
EXCEPTION_CHECK_GO(hr);
}
// Also need to marhshal the IMMCPropertySheet pointer that will be
// passed to IMMCPropertyPage::Initialize as that call will occur during
// WM_INITDIALOG which happens in MMC's property sheet thread.
if (NULL != pPropertySheet)
{
hr = ::CoMarshalInterThreadInterfaceInStream(IID_IMMCPropertySheet,
static_cast<IMMCPropertySheet *>(pPropertySheet),
&m_piMMCPropertySheetStream);
EXCEPTION_CHECK_GO(hr);
}
// Add a ref to ourselves. We need to do this because otherwise no one
// else can be depended on to keep this object alive until the Win32
// property page is created by MMC's PropertSheet() call.
ExternalAddRef();
// Marshal the objects' IUnknown pointers into streams. The returned
// IStreams are free threaded and can be kept in a member variable.
//
// When the dialog is created, each IUnknown will be unmarshalled and passed
// to the property page in IPropertyPage::SetObjects().
//
// We check for NULL because the object may have come from an
// IPropertySheet:AddWizardPage() which allows the VB dev to specify the
// object.
IfFalseGo(NULL != apunkObjects, S_OK);
m_apiObjectStreams = (IStream **)CtlAllocZero(cObjects * sizeof(IStream *));
if (NULL == m_apiObjectStreams)
{
hr = SID_E_OUTOFMEMORY;
EXCEPTION_CHECK_GO(hr);
}
m_cObjects = cObjects;
for (i = 0; i < cObjects; i++)
{
hr = ::CoMarshalInterThreadInterfaceInStream(IID_IUnknown,
apunkObjects[i],
&m_apiObjectStreams[i]);
EXCEPTION_CHECK_GO(hr);
}
// If there is an object in InitData then it also needs to be marshaled.
if (VT_UNKNOWN == varInitData.vt)
{
m_varInitData.vt = VT_UNKNOWN;
m_varInitData.punkVal = NULL;
hr = ::CoMarshalInterThreadInterfaceInStream(IID_IUnknown,
varInitData.punkVal,
&m_piInitDataStream);
EXCEPTION_CHECK_GO(hr);
}
else if (VT_DISPATCH == varInitData.vt)
{
m_varInitData.vt = VT_DISPATCH;
m_varInitData.punkVal = NULL;
hr = ::CoMarshalInterThreadInterfaceInStream(IID_IDispatch,
varInitData.pdispVal,
&m_piInitDataStream);
EXCEPTION_CHECK_GO(hr);
}
else
{
hr = ::VariantCopy(&m_varInitData, &varInitData);
EXCEPTION_CHECK_GO(hr);
}
Error:
// We return the DLGTEMPLATE pointer to the caller even though we own it.
// The caller must only use it as long as we are alive.
*ppTemplate = m_pTemplate;
RRETURN(hr);
}
BOOL CALLBACK CPropertyPageWrapper::DialogProc
(
HWND hwndDlg,
UINT uiMsg,
WPARAM wParam,
LPARAM lParam
)
{
HRESULT hr = S_OK;
BOOL fDlgProcRet = FALSE;
CPropertyPageWrapper *pPropertyPageWrapper = NULL;
NMHDR *pnmhdr = NULL;
LRESULT lresult = 0;
if (WM_INITDIALOG == uiMsg)
{
if (NULL != hwndDlg)
{
fDlgProcRet = FALSE; // System should not set focus to any control
// Get this pointer of CPropertyPageWrapper instance managing this
// dialog. For property pages, lParam is a pointer to the
// PROPSHEETPAGE used to define this page. The code in
// CPropertySheet::AddPage put our this pointer into
// PROPSHEETPAGE.lParam.
PROPSHEETPAGE *pPropSheetPage =
reinterpret_cast<PROPSHEETPAGE *>(lParam);
pPropertyPageWrapper =
reinterpret_cast<CPropertyPageWrapper *>(pPropSheetPage->lParam);
IfFailGo(pPropertyPageWrapper->OnInitDialog(hwndDlg));
// Post ourselves a message so that we can initialize the page
// after the dialog creation has completed.
(void)::PostMessage(hwndDlg, m_InitMsg, 0, 0);
}
}
else if (m_RedrawMsg == uiMsg)
{
// See comment for WM_ERASEBKGND below. We don't really have access to
// the property page's HWND because IPropertyPage does not allow that.
// We do know that our dialog window contains no controls and we set it
// as the parent of the property page so it must be our only child.
// Generate an immediate redraw for the entire area of our child and all
// of its children. Cancel any pending WM_ERASEBKGND messages by
// specifying RDW_NOERASE.
fDlgProcRet = TRUE;
::RedrawWindow(::GetWindow(hwndDlg, GW_CHILD), NULL, NULL,
RDW_INVALIDATE | RDW_NOERASE | RDW_UPDATENOW | RDW_ALLCHILDREN);
}
else
{
pPropertyPageWrapper = reinterpret_cast<CPropertyPageWrapper *>(
::GetWindowLong(hwndDlg, DWL_USER));
IfFalseGo(NULL != pPropertyPageWrapper, SID_E_INTERNAL);
if (m_InitMsg == uiMsg)
{
IfFailGo(pPropertyPageWrapper->OnInitMsg());
goto Cleanup;
}
switch (uiMsg)
{
case WM_ERASEBKGND:
{
// Under a debug session property pages are erased and never
// redrawn for some unknown reason. After much hair-pulling it
// was determined that the work-around is to post ourselves a
// message and force a redraw when that message is processed.
(void)::PostMessage(hwndDlg, m_RedrawMsg, 0, 0);
}
break;
case WM_SIZE:
{
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnSize());
}
break;
case WM_DESTROY:
{
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnDestroy());
}
break;
// Pass all CTLCOLOR messages to parent. This is what
// OLE property frame does.
case WM_CTLCOLORMSGBOX:
case WM_CTLCOLOREDIT:
case WM_CTLCOLORLISTBOX:
case WM_CTLCOLORBTN:
case WM_CTLCOLORDLG:
case WM_CTLCOLORSCROLLBAR:
case WM_CTLCOLORSTATIC:
{
fDlgProcRet = TRUE;
::SendMessage(::GetParent(hwndDlg), uiMsg, wParam, lParam);
}
break;
case WM_NOTIFY:
{
pnmhdr = reinterpret_cast<NMHDR *>(lParam);
IfFalseGo(NULL != pnmhdr, SID_E_SYSTEM_ERROR);
// Check that the message is from the property sheet
IfFalseGo(pnmhdr->hwndFrom == pPropertyPageWrapper->m_hwndSheet, S_OK);
// Branch out to the appropriate handler
switch (pnmhdr->code)
{
case PSN_APPLY:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnApply(&lresult));
break;
case PSN_SETACTIVE:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnSetActive(
((PSHNOTIFY *)lParam)->hdr.hwndFrom, &lresult));
break;
case PSN_KILLACTIVE:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnKillActive(&lresult));
break;
case PSN_WIZBACK:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnWizBack(&lresult));
break;
case PSN_WIZNEXT:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnWizNext(&lresult));
break;
case PSN_WIZFINISH:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnWizFinish(&lresult));
break;
case PSN_QUERYCANCEL:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnQueryCancel(&lresult));
break;
case PSN_RESET:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnReset((BOOL)(((PSHNOTIFY *)lParam)->lParam)));
break;
case PSN_HELP:
fDlgProcRet = TRUE;
IfFailGo(pPropertyPageWrapper->OnHelp());
break;
} // switch (pnmhdr->code)
} // WM_NOTIFY
break;
} // switch(uiMsg)
} // not WM_INITDIALOG
Cleanup:
Error:
(void)::SetWindowLong(hwndDlg, DWL_MSGRESULT, static_cast<LONG>(lresult));
return fDlgProcRet;
}
UINT CALLBACK CPropertyPageWrapper::PropSheetPageProc
(
HWND hwnd,
UINT uMsg,
PROPSHEETPAGE *pPropSheetPage
)
{
UINT uiRc = 0;
if (PSPCB_CREATE == uMsg)
{
uiRc = 1; // allow the page to be created
}
else if (PSPCB_RELEASE == uMsg)
{
CPropertyPageWrapper *pPropertyPageWrapper =
reinterpret_cast<CPropertyPageWrapper *>(pPropSheetPage->lParam);
if (NULL != pPropertyPageWrapper)
{
// Release the ref on ourselves. This should result in this object
// being destrotyed so do not reference any member variables after
// this call
pPropertyPageWrapper->ExternalRelease();
}
}
return uiRc;
}
HRESULT CPropertyPageWrapper::OnInitDialog(HWND hwndDlg)
{
HRESULT hr = S_OK;
IUnknown **apunkObjects = NULL;
ULONG i = 0;
IDispatch *pdisp = NULL;
m_pPropertySheet->SetOKToAlterPageCount(FALSE);
// Store the hwnd and store our this pointer in the window words
m_hwndDlg = hwndDlg;
::SetWindowLong(hwndDlg, DWL_USER, reinterpret_cast<LONG>(this));
// Store the property sheet HWND. For now assume it is the parent of
// the dialog. When we get PSN_SETACTIVE we'll update it with that value.
// Technically we should not make this assumption but there is a ton of
// Win32 code that does and we have no choice because we need the HWND
// before PSN_SETACTIVE
m_hwndSheet = ::GetParent(hwndDlg);
// Give it to our owning CPropertySheet
m_pPropertySheet->SetHWNDSheet(m_hwndSheet);
// Create the page
RELEASE(m_piPropertyPage); // should never be necessary, but just in case
hr = ::CoCreateInstance(m_clsidPage,
NULL, // no aggregation,
CLSCTX_INPROC_SERVER,
IID_IPropertyPage,
reinterpret_cast<void **>(&m_piPropertyPage));
EXCEPTION_CHECK_GO(hr);
// Unmarshall the IMMCPropertySheet so we can pass it to
// IMMCPropertyPage::Initialize
if (NULL != m_piMMCPropertySheetStream)
{
hr = ::CoGetInterfaceAndReleaseStream(m_piMMCPropertySheetStream,
IID_IMMCPropertySheet,
reinterpret_cast<void **>(&m_piMMCPropertySheet));
m_piMMCPropertySheetStream = NULL;
EXCEPTION_CHECK_GO(hr);
}
// Set this CPropertyPageWrapper object as the page site
IfFailGo(m_piPropertyPage->SetPageSite(static_cast<IPropertyPageSite *>(this)));
// Unmarshal the IUnknowns on the objects for which the page will be
// displaying properties. This will also release the streams regardless of
// whether it succeeds.
if (NULL != m_apiObjectStreams)
{
apunkObjects = (IUnknown **)CtlAllocZero(m_cObjects * sizeof(IUnknown *));
if (NULL == apunkObjects)
{
hr = SID_E_OUTOFMEMORY;
EXCEPTION_CHECK_GO(hr);
}
for (i = 0; i < m_cObjects; i++)
{
if (NULL == m_apiObjectStreams[i])
{
continue;
}
hr = ::CoGetInterfaceAndReleaseStream(
m_apiObjectStreams[i],
IID_IUnknown,
reinterpret_cast<void **>(&apunkObjects[i]));
m_apiObjectStreams[i] = NULL;
EXCEPTION_CHECK_GO(hr);
}
}
// If this is a wizard then unmarshal the ISnapIn so we can fire
// ConfigurationComplete.
if (NULL != m_piSnapInStream)
{
hr = ::CoGetInterfaceAndReleaseStream(m_piSnapInStream,
IID_ISnapIn,
reinterpret_cast<void **>(&m_piSnapIn));
m_piSnapInStream = NULL;
EXCEPTION_CHECK_GO(hr);
}
// Give the object to the page. Check for NULL because the snap-in
// could have called PropertySheet.AddWizardPage passing Nothing
// for its configuration object.
if (NULL != apunkObjects)
{
IfFailGo(m_piPropertyPage->SetObjects(m_cObjects, apunkObjects));
}
// If this is a wizard then check whether the page supports our IWizardPage
// interface. If it does not, that is not considered an error and it simply
// won't get the next/back/finish etc. notifications.
hr = m_piPropertyPage->QueryInterface(IID_IWizardPage,
reinterpret_cast<void **>(&m_piWizardPage));
if (FAILED(hr))
{
// Just to be extra sure, NULL our IWizardPage pointer
m_piWizardPage = NULL;
// If the error was anything other than E_NOINTERFACE then consider it
// a real error.
if (E_NOINTERFACE == hr)
{
hr = S_OK;
}
IfFailGo(hr);
}
else
{
// It should be a wizard. Store the object so we can pass it to the
// snap-in when the Finish button is pressed (see OnWizFinish).
if (NULL != apunkObjects)
{
if (NULL != apunkObjects[0])
{
IfFailGo(apunkObjects[0]->QueryInterface(IID_IDispatch,
reinterpret_cast<void **>(&m_pdispConfigObject)));
}
}
else
{
m_pdispConfigObject = NULL;
}
}
// Add the MSGFILTER hook so that we can call
// IPropertyPage::TranslateAccelerator when the user hits a key in a control
// on the page.
IfFailGo(AddMsgFilterHook());
// Activate the page and show it
IfFailGo(ActivatePage());
m_pPropertySheet->SetOKToAlterPageCount(TRUE);
Error:
if (NULL != apunkObjects)
{
for (i = 0; i < m_cObjects; i++)
{
if (NULL != apunkObjects[i])
{
apunkObjects[i]->Release();
}
}
CtlFree(apunkObjects);
}
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnInitMsg()
{
HRESULT hr = S_OK;
// If the snap-in supports IMMCPropertyPage then call Initialize
if (SUCCEEDED(m_piPropertyPage->QueryInterface(IID_IMMCPropertyPage,
reinterpret_cast<void **>(&m_piMMCPropertyPage))))
{
IfFailGo(InitPage());
}
Error:
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::InitPage()
{
HRESULT hr = S_OK;
VARIANT varProvider;
::VariantInit(&varProvider);
// If the snap-in passed an object in the InitData parameter of
// MMCPropertySheet.AddPage then unmarshal it.
if (ISPRESENT(m_varInitData))
{
// If there is an object in InitData then it needs to be unmarshaled.
if (VT_UNKNOWN == m_varInitData.vt)
{
m_varInitData.punkVal = NULL;
hr = ::CoGetInterfaceAndReleaseStream(m_piInitDataStream,
IID_IUnknown,
reinterpret_cast<void **>(&m_varInitData.punkVal));
m_piInitDataStream = NULL;
EXCEPTION_CHECK_GO(hr);
}
else if (VT_DISPATCH == m_varInitData.vt)
{
m_varInitData.pdispVal = NULL;
hr = ::CoGetInterfaceAndReleaseStream(m_piInitDataStream,
IID_IDispatch,
reinterpret_cast<void **>(&m_varInitData.pdispVal));
m_piInitDataStream = NULL;
EXCEPTION_CHECK_GO(hr);
}
}
// Call IMMCPropertyPage::Initialize
IfFailGo(m_piMMCPropertyPage->Initialize(m_varInitData,
reinterpret_cast<MMCPropertySheet *>(m_piMMCPropertySheet)));
Error:
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::AddMsgFilterHook()
{
HRESULT hr = S_OK;
TLSDATA *pTlsData = NULL;
// If we are remote then don't install the hook. It doesn't work correctly
// and there is no need to handle tabbing under the debugger.
IfFalseGo(!m_fIsRemote, S_OK);
// Check if TLS data is already there for this thread. If not there
// then create it, add the hook, and set the TLS data. If it is there
// then increment the ref count on the HHOOK.
IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData)));
if (NULL == pTlsData)
{
pTlsData = (TLSDATA *)CtlAllocZero(sizeof(TLSDATA));
if (NULL == pTlsData)
{
hr = SID_E_OUTOFMEMORY;
EXCEPTION_CHECK_GO(hr);
}
pTlsData->hHook = ::SetWindowsHookEx(WH_MSGFILTER,
&MessageProc,
GetResourceHandle(),
::GetCurrentThreadId());
if (NULL == pTlsData->hHook)
{
CtlFree(pTlsData);
hr = HRESULT_FROM_WIN32(::GetLastError());
EXCEPTION_CHECK_GO(hr);
}
if (FAILED(CTls::Set(TLS_SLOT_PPGWRAP, pTlsData)))
{
(void)::UnhookWindowsHookEx(pTlsData->hHook);
CtlFree(pTlsData);
}
}
// Increment the existing page count
pTlsData->cPages++;
m_fNeedToRemoveHook = TRUE;
Error:
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::RemoveMsgFilterHook()
{
HRESULT hr = S_OK;
TLSDATA *pTlsData = NULL;
UINT i = 0;
// If we already removed the hook then nothing to do
IfFalseGo(m_fNeedToRemoveHook, S_OK);
// Check if TLS data is already there for this thread. If it is,
// then remove this dialog's hwnd from the TLS.
IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData)));
IfFalseGo(NULL != pTlsData, S_OK);
pTlsData->cPages--;
m_fNeedToRemoveHook = FALSE;
// If there are no more existing pages then remove the hook and free the TLS
if (0 == pTlsData->cPages)
{
if (NULL != pTlsData->hHook)
{
(void)::UnhookWindowsHookEx(pTlsData->hHook);
pTlsData->hHook = NULL;
}
IfFailGo(CTls::Set(TLS_SLOT_PPGWRAP, NULL));
CtlFree(pTlsData);
}
Error:
RRETURN(hr);
}
LRESULT CALLBACK CPropertyPageWrapper::MessageProc
(
int code, // hook code
WPARAM wParam, // not used
LPARAM lParam // message data
)
{
HRESULT hr = S_OK;
LRESULT lResult = 0; // default ret value is pass msg to wndproc
MSG *pMsg = reinterpret_cast<MSG *>(lParam);
TLSDATA *pTlsData = NULL;
HWND hwndTab = NULL;
HWND hwndSheet = NULL;
HWND hwndBack = NULL;
HWND hwndNext = NULL;
HWND hwndFinish = NULL;
HWND hwndCancel = NULL;
HWND hwndHelp = NULL;
BOOL fTargetIsOnPage = FALSE;
BOOL fPassToPropertyPage = FALSE;
// Get the TLS data in all cases because the HHOOK is in there and we need
// that for CallNextHookEx.
IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData)));
// If input event did not occur in a dialog box then pass to CallNextHookEx
IfFalseGo(code >= 0, S_OK);
// If this is not a key down message then just pass to CallNextHookEx
IfFalseGo( ((WM_KEYFIRST <= pMsg->message) && (WM_KEYLAST >= pMsg->message)), S_OK);
// If there is no pointer to the active page in TLS then just pass to
// CallNextHookeEx
IfFalseGo(NULL != pTlsData, S_OK);
IfFalseGo(NULL != pTlsData->ppgActive, S_OK);
// Get the HWND of the tab control
hwndSheet = pTlsData->ppgActive->m_hwndSheet;
if (NULL != hwndSheet)
{
hwndTab = (HWND)::SendMessage(hwndSheet, PSM_GETTABCONTROL, 0, 0);
}
// Check if the target of the message is a decendant of the wrapper dialog
// window. If so then it is a control on the VB property page.
fTargetIsOnPage = ::IsChild(pTlsData->ppgActive->m_hwndDlg, pMsg->hwnd);
// If a tab was hit outside of the page then in some cases we need to
// let the page handle it.
if ( (VK_TAB == pMsg->wParam) && (!fTargetIsOnPage) )
{
// If this is a back-tab
if (::GetKeyState(VK_SHIFT) < 0)
{
// If the focus is on the OK button, let page handle shift-tab
if (pMsg->hwnd == ::GetDlgItem(hwndSheet, IDOK))
{
fPassToPropertyPage = TRUE;
}
else if (pTlsData->ppgActive->m_fWizard)
{
// Determine which wizard buttons are enabled and handle
// back tabs from the left-most enabled button.
// Wizard buttons can be:
// Back | Next | Finish | Cancel | Help
// The left-most enabled button could be Back, Next, Finish, or
// Cancel
// TODO: does this work on RTL locales such as Hebrew and Arabic?
hwndBack = ::GetDlgItem(hwndSheet, IDD_BACK);
hwndNext = ::GetDlgItem(hwndSheet, IDD_NEXT);
hwndFinish = ::GetDlgItem(hwndSheet, IDD_FINISH);
hwndCancel = ::GetDlgItem(hwndSheet, IDCANCEL);
if (pMsg->hwnd == hwndBack)
{
fPassToPropertyPage = TRUE;
}
else if ( (pMsg->hwnd == hwndNext) &&
(!::IsWindowEnabled(hwndBack)) )
{
// Back-tab is for Next button and Back button is disabled
fPassToPropertyPage = TRUE;
}
else if ( (pMsg->hwnd == hwndFinish) &&
(!::IsWindowEnabled(hwndBack)) &&
(!::IsWindowEnabled(hwndNext)) )
{
// Back-tab is for Finish button and Next and Back buttons
// are disabled
fPassToPropertyPage = TRUE;
}
else if ( (pMsg->hwnd == hwndFinish) &&
(!::IsWindowEnabled(hwndBack)) &&
(!::IsWindowEnabled(hwndNext)) )
{
// Back-tab is for Finish button and Next and Back buttons
// are disabled
fPassToPropertyPage = TRUE;
}
}
}
else // forward tab
{
// If the focus is on the tab control, let page handle tab
if (hwndTab == pMsg->hwnd)
{
fPassToPropertyPage = TRUE;
}
else if (pTlsData->ppgActive->m_fWizard)
{
// Determine which wizard buttons are enabled and handle
// back tabs from the right-most enabled button.
// Wizard buttons can be:
// Back | Next | Finish | Cancel | Help
// The right-most enabled button could be Cancel or Help
// TODO: does this work on RTL locales such as Hebrew and Arabic?
hwndCancel = ::GetDlgItem(hwndSheet, IDCANCEL);
hwndHelp = ::GetDlgItem(hwndSheet, IDHELP);
if (pMsg->hwnd == hwndHelp)
{
fPassToPropertyPage = TRUE;
}
else if ( (pMsg->hwnd == hwndCancel) &&
( (!::IsWindowEnabled(hwndHelp)) ||
(!::IsWindowVisible(hwndHelp)) )
)
{
// Tab is for Cancel button and Help button is disabled
fPassToPropertyPage = TRUE;
}
}
}
}
else if ( ( (VK_LEFT == pMsg->wParam) || (VK_RIGHT == pMsg->wParam) ||
(VK_UP == pMsg->wParam) || (VK_DOWN == pMsg->wParam)
) &&
(!fTargetIsOnPage)
)
{
fPassToPropertyPage = FALSE;
}
else // Not a tab, back-tab, or arrow key. Pass it to the page.
{
fPassToPropertyPage = TRUE;
}
if (fPassToPropertyPage)
{
if (S_OK == pTlsData->ppgActive->m_piPropertyPage->TranslateAccelerator(pMsg))
{
// Property page handled the key. Don't pass msg to wndproc
// and to other hooks.
lResult = (LRESULT)1;
}
}
Error:
if ( (0 == lResult) && (NULL != pTlsData) )
{
// Pass the message to other hooks
if (NULL != pTlsData->hHook)
{
lResult = ::CallNextHookEx(pTlsData->hHook, code, wParam, lParam);
}
}
return lResult;
}
HRESULT CPropertyPageWrapper::ActivatePage()
{
HRESULT hr = S_OK;
HWND hwndPage = NULL;
TLSDATA *pTlsData = NULL;
HWND hwndTab = NULL;
HWND hwndSheet = NULL;
MSG msg;
::ZeroMemory(&msg, sizeof(msg));
RECT rect;
::ZeroMemory(&rect, sizeof(rect));
BYTE rgbKeys[256];
::ZeroMemory(rgbKeys, sizeof(rgbKeys));
// Activate the property page.
//
// Use the dialog's hwnd as the parent.
//
// Set the rect to the dialog window's size
//
// Pass TRUE to indicate that the dialog box frame is modal. This is the
// same way OleCreatePropertyFrame() and and OleCreatePropertyFrameIndirect()
// work.
GetClientRect(m_hwndDlg, &rect);
IfFailGo(m_piPropertyPage->Activate(m_hwndDlg, &rect, TRUE));
hwndPage = ::GetTopWindow(m_hwndDlg);
if (NULL != hwndPage)
{
::SetWindowLong(hwndPage, GWL_STYLE,
::GetWindowLong(hwndPage, GWL_STYLE) & ~(DS_CONTROL | WS_TABSTOP));
::SetWindowLong(hwndPage, GWL_EXSTYLE,
::GetWindowLong(hwndPage, GWL_EXSTYLE) & ~WS_EX_CONTROLPARENT);
}
// Tell the page to show itself and set focus to the first property in its
// tab order.
IfFailGo(m_piPropertyPage->Show(SW_SHOW));
IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData)));
IfFalseGo(NULL != pTlsData, S_OK);
pTlsData->ppgActive = this;
// Fake a tab key to the property page so that the focus will move to
// the first control in the page's tabbing order.
// Ignore all return codes because if this doesn't work then it is not a
// show-stopper. The user would simply have to tab to or click on the first
// control.
hwndTab = (HWND)::SendMessage(m_hwndSheet, PSM_GETTABCONTROL, 0, 0);
IfFalseGo(NULL != hwndTab, S_OK);
msg.hwnd = hwndTab; // message intended for focused control
msg.message = WM_KEYDOWN; // key pressed
msg.wParam = VK_TAB; // tab key
msg.lParam = 0x000F0001; // tab key scan code with repeat count=1
msg.time = ::GetTickCount(); // use current time
(void)::GetCursorPos(&msg.pt); // use current cursor position
// Make sure shift/ctrl/alt keys are not set, since property
// pages will interpret the key wrong.
(void)::GetKeyboardState(rgbKeys);
rgbKeys[VK_SHIFT] &= 0x7F; // remove hi bit (key down)
rgbKeys[VK_CONTROL] &= 0x7F; // remove hi bit (key down)
rgbKeys[VK_MENU] &= 0x7F; // remove hi bit (key down)
(void)::SetKeyboardState(rgbKeys);
(void)m_piPropertyPage->TranslateAccelerator(&msg);
Error:
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnSize()
{
HRESULT hr = S_OK;
RECT rect;
::ZeroMemory(&rect, sizeof(rect));
GetClientRect(m_hwndDlg, &rect);
IfFailGo(m_piPropertyPage->Move(&rect));
Error:
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnDestroy()
{
HRESULT hr = S_OK;
IUnknown *punkThisObject = PrivateUnknown();
m_pPropertySheet->SetOKToAlterPageCount(FALSE);
// Remove the selected objects. We should pass NULL here but in a debugging
// session the proxy will return an error if we do. To get around this we
// pass a pointer to our own IUnknown. VB will not do anything with it
// because the object count is zero.
IfFailGo(m_piPropertyPage->SetObjects(0, &punkThisObject));
// Deactivate the property page.
IfFailGo(m_piPropertyPage->Deactivate());
// Set the site to NULL so it will remove its ref on us.
IfFailGo(m_piPropertyPage->SetPageSite(NULL));
// Release the property page
RELEASE(m_piPropertyPage);
// Remove this dialog from the message hook TLS data. If there are
// no more dialogs remaining then remove the hook.
IfFailGo(RemoveMsgFilterHook());
m_pPropertySheet->SetOKToAlterPageCount(TRUE);
Error:
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnApply(LRESULT *plresult)
{
HRESULT hr = S_OK;
m_pPropertySheet->SetOKToAlterPageCount(FALSE);
// Tell the property page to apply its current values to the underlying
// object.
IfFailGo(m_piPropertyPage->Apply());
m_pPropertySheet->SetOKToAlterPageCount(TRUE);
Error:
if (FAILED(hr))
{
*plresult = PSNRET_INVALID_NOCHANGEPAGE;
}
else
{
*plresult = PSNRET_NOERROR;
}
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnSetActive(HWND hwndSheet, LRESULT *plresult)
{
HRESULT hr = S_OK;
long lNextPage = 0;
WizardPageButtonConstants NextOrFinish = EnabledNextButton;
VARIANT_BOOL fvarEnableBack = VARIANT_TRUE;
BSTR bstrFinishText = NULL;
DWORD dwFlags = 0;
m_pPropertySheet->SetOKToAlterPageCount(FALSE);
// Store the property sheet's HWND and give it to our owning CPropertySheet
m_hwndSheet = hwndSheet;
m_pPropertySheet->SetHWNDSheet(m_hwndSheet);
// If the page is in a wizard then set the wizard buttons
if (m_fWizard && (NULL != m_piWizardPage))
{
IfFailGo(m_piWizardPage->Activate(&fvarEnableBack,
&NextOrFinish,
&bstrFinishText));
IfFailGo(m_pPropertySheet->SetWizardButtons(fvarEnableBack,
NextOrFinish));
if (NULL != bstrFinishText)
{
IfFailGo(m_pPropertySheet->SetFinishButtonText(bstrFinishText));
}
}
// Activate the page and show it
IfFailGo(ActivatePage());
m_pPropertySheet->SetOKToAlterPageCount(TRUE);
Error:
FREESTRING(bstrFinishText);
if (FAILED(hr))
{
// If anything failed then don't allow the operation.
lNextPage = -1L;
}
*plresult = static_cast<LRESULT>(lNextPage);
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnKillActive(LRESULT *plresult)
{
HRESULT hr = S_OK;
TLSDATA *pTlsData = NULL;
m_pPropertySheet->SetOKToAlterPageCount(FALSE);
IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData)));
if (NULL != pTlsData)
{
pTlsData->ppgActive = NULL;
}
// Tell the property page to apply its current values to the underlying
// object.
IfFailGo(m_piPropertyPage->Apply());
m_pPropertySheet->SetOKToAlterPageCount(TRUE);
Error:
if (FAILED(hr))
{
// Apply failed. Tell the property sheet to keep the page active
*plresult = static_cast<LRESULT>(TRUE);
}
else
{
// Apply succeeded. Tell the property sheet it is OK to leave the page
*plresult = static_cast<LRESULT>(FALSE);
}
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnWizBack(LRESULT *plresult)
{
HRESULT hr = S_OK;
long lNextPage = 0;
// If the page doesn't support IWizardPage then allow the Back operation.
IfFalseGo(NULL != m_piWizardPage, S_OK);
IfFailGo(m_piWizardPage->Back(&lNextPage));
if (0 < lNextPage)
{
// Page requested to move to another page. Get its DLGTEMPLATE pointer.
IfFailGo(GetNextPage(&lNextPage));
}
Error:
if (FAILED(hr))
{
// If anything failed then don't allow the Back operation.
lNextPage = -1L;
}
*plresult = static_cast<LRESULT>(lNextPage);
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnWizNext(LRESULT *plresult)
{
HRESULT hr = S_OK;
long lNextPage = 0;
// If the page doesn't support IWizardPage then allow the Next operation.
IfFalseGo(NULL != m_piWizardPage, S_OK);
IfFailGo(m_piWizardPage->Next(&lNextPage));
if (0 < lNextPage)
{
// Page requested to move to another page. Get its DLGTEMPLATE pointer.
IfFailGo(GetNextPage(&lNextPage));
}
Error:
if (FAILED(hr))
{
// If anything failed then don't allow the Next operation.
lNextPage = -1L;
}
*plresult = static_cast<LRESULT>(lNextPage);
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnWizFinish(LRESULT *plresult)
{
HRESULT hr = S_OK;
VARIANT_BOOL fvarAllow = VARIANT_TRUE;
// If the page doesn't support IWizardPage then allow the Finish operation.
IfFalseGo(NULL != m_piWizardPage, S_OK);
IfFailGo(m_piWizardPage->Finish(&fvarAllow));
// If the finish is allowed and this is a configuration wizard then fire
// SnapIn_ConfigurationComplete
if ( (VARIANT_TRUE == fvarAllow) && (NULL != m_piSnapIn) && m_fConfigWizard)
{
IfFailGo(m_piSnapIn->FireConfigComplete(m_pdispConfigObject));
}
Error:
if (FAILED(hr))
{
// If anything failed then don't allow the Finish operation.
fvarAllow = VARIANT_FALSE;
}
else
{
if (VARIANT_TRUE == fvarAllow)
{
*plresult = 0; // Allow the property sheet to be destroyed
}
else
{
// Do not allow the property sheet to be destroyed
*plresult = static_cast<LRESULT>(1);
}
}
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnQueryCancel(LRESULT *plresult)
{
HRESULT hr = S_OK;
VARIANT_BOOL fvarAllow = VARIANT_TRUE;
// If the page doesn't support IMMCPropertyPage then allow the Cancel
// operation.
IfFalseGo(NULL != m_piMMCPropertyPage, S_OK);
IfFailGo(m_piMMCPropertyPage->QueryCancel(&fvarAllow));
Error:
if (FAILED(hr))
{
// If anything failed then don't allow the Cancel operation.
fvarAllow = VARIANT_FALSE;
}
else
{
if (VARIANT_TRUE == fvarAllow)
{
// Allow the cancel operation
*plresult = static_cast<LRESULT>(FALSE);
}
else
{
// Do not allow the cancel operation
*plresult = static_cast<LRESULT>(TRUE);
}
}
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnReset(BOOL fClickedXButton)
{
HRESULT hr = S_OK;
m_pPropertySheet->SetOKToAlterPageCount(FALSE);
// If the page doesn't support IMMCPropertyPage then ignore this notification
IfFalseGo(NULL != m_piMMCPropertyPage, S_OK);
if (fClickedXButton)
{
IfFailGo(m_piMMCPropertyPage->Close());
}
else
{
IfFailGo(m_piMMCPropertyPage->Cancel());
}
m_pPropertySheet->SetOKToAlterPageCount(TRUE);
Error:
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::OnHelp()
{
HRESULT hr = S_OK;
// If the property page implements IMMCPropertyPage then call the Help
// method otherwise call IPropertyPage::Help()
if (NULL != m_piMMCPropertyPage)
{
hr = m_piMMCPropertyPage->Help();
}
else
{
// Call IPropertyPage::Help() on the page. We don't pass the help dir
// because VB doesn't register it and it doesn't use it. See the VB
// source in vbdev\ruby\deskpage.cpp, DESKPAGE::Help().
hr = m_piPropertyPage->Help(NULL);
}
RRETURN(hr);
}
HRESULT CPropertyPageWrapper::GetNextPage(long *lNextPage)
{
HRESULT hr = S_OK;
DLGTEMPLATE *pDlgTemplate = NULL;
IfFalseGo(NULL != m_pPropertySheet, SID_E_INTERNAL);
// The property sheet has the array of DLGTEMPLATE pointers. Ask it
// for the one corresponding to the requested page.
IfFailGo(m_pPropertySheet->GetTemplate(*lNextPage, &pDlgTemplate));
*lNextPage = reinterpret_cast<long>(pDlgTemplate);
Error:
RRETURN(hr);
}
//=--------------------------------------------------------------------------=
// IPropertyPageSite Methods
//=--------------------------------------------------------------------------=
STDMETHODIMP CPropertyPageWrapper::OnStatusChange(DWORD dwFlags)
{
if ( PROPPAGESTATUS_DIRTY == (dwFlags & PROPPAGESTATUS_DIRTY) )
{
// Enables the apply button
::SendMessage(m_hwndSheet, PSM_CHANGED, (WPARAM)m_hwndDlg, 0);
}
else
{
// Disables the apply button. Occurs when page has returned to original
// state. In a VB page, would set Changed = False.
::SendMessage(m_hwndSheet, PSM_UNCHANGED, (WPARAM)m_hwndDlg, 0);
}
return S_OK;
}
STDMETHODIMP CPropertyPageWrapper::GetLocaleID(LCID *pLocaleID)
{
*pLocaleID = GetSystemDefaultLCID();
RRETURN((0 == *pLocaleID) ? E_FAIL : S_OK);
}
STDMETHODIMP CPropertyPageWrapper::GetPageContainer(IUnknown **ppunkContainer)
{
return E_NOTIMPL;
}
STDMETHODIMP CPropertyPageWrapper::TranslateAccelerator(MSG *pMsg)
{
return S_FALSE;
}
//=--------------------------------------------------------------------------=
// CUnknownObject Methods
//=--------------------------------------------------------------------------=
HRESULT CPropertyPageWrapper::InternalQueryInterface(REFIID riid, void **ppvObjOut)
{
if (IID_IPropertyPageSite == riid)
{
*ppvObjOut = static_cast<IPropertyPageSite *>(this);
ExternalAddRef();
return S_OK;
}
else
return CSnapInAutomationObject::InternalQueryInterface(riid, ppvObjOut);
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
24f474e4b694f16c8e54d0878ae215a8e83425df | 9c0af3a75a7ca3250ff6bebcb17e76af5315a31a | /loam_velodyne/include/loam_velodyne/BasicScanRegistration.h | 7693be710cc894c7c27410232230c81dc82313d6 | [
"BSD-3-Clause"
] | permissive | arjo129/darpa_ugv_highlevel | 7fa45fb070803b9f99a2bfe6e91f745908454b76 | 806ff902616ca3252b0099c21e0a07a09c65b4e5 | refs/heads/master | 2023-06-20T18:06:26.023670 | 2020-08-21T07:21:32 | 2020-08-21T07:21:32 | 210,164,633 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,391 | h | #pragma once
#include <utility>
#include <vector>
#include <pcl/point_cloud.h>
#include "Angle.h"
#include "Vector3.h"
#include "CircularBuffer.h"
#include "time_utils.h"
namespace loam
{
/** \brief A pair describing the start end end index of a range. */
typedef std::pair<size_t, size_t> IndexRange;
/** Point label options. */
enum PointLabel
{
CORNER_SHARP = 2, ///< sharp corner point
CORNER_LESS_SHARP = 1, ///< less sharp corner point
SURFACE_LESS_FLAT = 0, ///< less flat surface point
SURFACE_FLAT = -1 ///< flat surface point
};
/** Scan Registration configuration parameters. */
class RegistrationParams
{
public:
RegistrationParams(const float& scanPeriod_ = 0.1,
const int& imuHistorySize_ = 200,
const int& nFeatureRegions_ = 6,
const int& curvatureRegion_ = 5,
const int& maxCornerSharp_ = 2,
const int& maxSurfaceFlat_ = 4,
const float& lessFlatFilterSize_ = 0.2,
const float& surfaceCurvatureThreshold_ = 0.1);
/** The time per scan. */
float scanPeriod;
/** The size of the IMU history state buffer. */
int imuHistorySize;
/** The number of (equally sized) regions used to distribute the feature extraction within a scan. */
int nFeatureRegions;
/** The number of surrounding points (+/- region around a point) used to calculate a point curvature. */
int curvatureRegion;
/** The maximum number of sharp corner points per feature region. */
int maxCornerSharp;
/** The maximum number of less sharp corner points per feature region. */
int maxCornerLessSharp;
/** The maximum number of flat surface points per feature region. */
int maxSurfaceFlat;
/** The voxel size used for down sizing the remaining less flat surface points. */
float lessFlatFilterSize;
/** The curvature threshold below / above a point is considered a flat / corner point. */
float surfaceCurvatureThreshold;
};
/** IMU state data. */
typedef struct IMUState
{
/** The time of the measurement leading to this state (in seconds). */
Time stamp;
/** The current roll angle. */
Angle roll;
/** The current pitch angle. */
Angle pitch;
/** The current yaw angle. */
Angle yaw;
/** The accumulated global IMU position in 3D space. */
Vector3 position;
/** The accumulated global IMU velocity in 3D space. */
Vector3 velocity;
/** The current (local) IMU acceleration in 3D space. */
Vector3 acceleration;
/** \brief Interpolate between two IMU states.
*
* @param start the first IMUState
* @param end the second IMUState
* @param ratio the interpolation ratio
* @param result the target IMUState for storing the interpolation result
*/
static void interpolate(const IMUState& start,
const IMUState& end,
const float& ratio,
IMUState& result)
{
float invRatio = 1 - ratio;
result.roll = start.roll.rad() * invRatio + end.roll.rad() * ratio;
result.pitch = start.pitch.rad() * invRatio + end.pitch.rad() * ratio;
if (start.yaw.rad() - end.yaw.rad() > M_PI)
{
result.yaw = start.yaw.rad() * invRatio + (end.yaw.rad() + 2 * M_PI) * ratio;
}
else if (start.yaw.rad() - end.yaw.rad() < -M_PI)
{
result.yaw = start.yaw.rad() * invRatio + (end.yaw.rad() - 2 * M_PI) * ratio;
}
else
{
result.yaw = start.yaw.rad() * invRatio + end.yaw.rad() * ratio;
}
result.velocity = start.velocity * invRatio + end.velocity * ratio;
result.position = start.position * invRatio + end.position * ratio;
};
} IMUState;
class BasicScanRegistration
{
public:
/** \brief Process a new cloud as a set of scanlines.
*
* @param relTime the time relative to the scan time
*/
void processScanlines(const Time& scanTime, std::vector<pcl::PointCloud<pcl::PointXYZI>> const& laserCloudScans);
bool configure(const RegistrationParams& config = RegistrationParams());
/** \brief Update new IMU state. NOTE: MUTATES ARGS! */
void updateIMUData(Vector3& acc, IMUState& newState);
/** \brief Project a point to the start of the sweep using corresponding IMU data
*
* @param point The point to modify
* @param relTime The time to project by
*/
void projectPointToStartOfSweep(pcl::PointXYZI& point, float relTime);
auto const& imuTransform () { return _imuTrans ; }
auto const& sweepStart () { return _sweepStart ; }
auto const& laserCloud () { return _laserCloud ; }
auto const& cornerPointsSharp () { return _cornerPointsSharp ; }
auto const& cornerPointsLessSharp () { return _cornerPointsLessSharp; }
auto const& surfacePointsFlat () { return _surfacePointsFlat ; }
auto const& surfacePointsLessFlat () { return _surfacePointsLessFlat; }
auto const& config () { return _config ; }
// auto const& laserCloudGroundScansDeep () { return _laserCloudGroundScansDeep ; }
private:
/** \brief Check is IMU data is available. */
inline bool hasIMUData() { return _imuHistory.size() > 0; };
/** \brief Set up the current IMU transformation for the specified relative time.
*
* @param relTime the time relative to the scan time
*/
void setIMUTransformFor(const float& relTime);
/** \brief Project the given point to the start of the sweep, using the current IMU state and position shift.
*
* @param point the point to project
*/
void transformToStartIMU(pcl::PointXYZI& point);
/** \brief Prepare for next scan / sweep.
*
* @param scanTime the current scan time
* @param newSweep indicator if a new sweep has started
*/
void reset(const Time& scanTime);
/** \brief Extract features from current laser cloud.
*
* @param beginIdx the index of the first scan to extract features from
*/
void extractFeatures(const uint16_t& beginIdx = 0);
/** \brief Set up region buffers for the specified point range.
*
* @param startIdx the region start index
* @param endIdx the region end index
*/
void setRegionBuffersFor(const size_t& startIdx,
const size_t& endIdx);
/** \brief Set up scan buffers for the specified point range.
*
* @param startIdx the scan start index
* @param endIdx the scan start index
*/
void setScanBuffersFor(const size_t& startIdx,
const size_t& endIdx);
/** \brief Mark a point and its neighbors as picked.
*
* This method will mark neighboring points within the curvature region as picked,
* as long as they remain within close distance to each other.
*
* @param cloudIdx the index of the picked point in the full resolution cloud
* @param scanIdx the index of the picked point relative to the current scan
*/
void markAsPicked(const size_t& cloudIdx,
const size_t& scanIdx);
/** \brief Try to interpolate the IMU state for the given time.
*
* @param relTime the time relative to the scan time
* @param outputState the output state instance
*/
void interpolateIMUStateFor(const float& relTime, IMUState& outputState);
void updateIMUTransform();
private:
RegistrationParams _config; ///< registration parameter
pcl::PointCloud<pcl::PointXYZI> _laserCloud; ///< full resolution input cloud
std::vector<IndexRange> _scanIndices; ///< start and end indices of the individual scans withing the full resolution cloud
pcl::PointCloud<pcl::PointXYZI> _cornerPointsSharp; ///< sharp corner points cloud
pcl::PointCloud<pcl::PointXYZI> _cornerPointsLessSharp; ///< less sharp corner points cloud
pcl::PointCloud<pcl::PointXYZI> _surfacePointsFlat; ///< flat surface points cloud
pcl::PointCloud<pcl::PointXYZI> _surfacePointsLessFlat; ///< less flat surface points cloud
// pcl::PointCloud<pcl::PointXYZI> _laserCloudGroundScansDeep; ///Ground scan data points
Time _sweepStart; ///< time stamp of beginning of current sweep
Time _scanTime; ///< time stamp of most recent scan
IMUState _imuStart; ///< the interpolated IMU state corresponding to the start time of the currently processed laser scan
IMUState _imuCur; ///< the interpolated IMU state corresponding to the time of the currently processed laser scan point
Vector3 _imuPositionShift; ///< position shift between accumulated IMU position and interpolated IMU position
size_t _imuIdx = 0; ///< the current index in the IMU history
CircularBuffer<IMUState> _imuHistory; ///< history of IMU states for cloud registration
pcl::PointCloud<pcl::PointXYZ> _imuTrans = { 4,1 }; ///< IMU transformation information
std::vector<float> _regionCurvature; ///< point curvature buffer
std::vector<PointLabel> _regionLabel; ///< point label buffer
std::vector<size_t> _regionSortIndices; ///< sorted region indices based on point curvature
std::vector<int> _scanNeighborPicked; ///< flag if neighboring point was already picked
};
}
| [
"paulroopson.pradeep@gmail.com"
] | paulroopson.pradeep@gmail.com |
43e4872221012b3ce2525be93ab85cdc3b181491 | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /media/base/video_util.h | b40331c0293b2f6957b0f89197b92736b6725254 | [
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 7,923 | h | // 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.
#ifndef MEDIA_BASE_VIDEO_UTIL_H_
#define MEDIA_BASE_VIDEO_UTIL_H_
#include <stdint.h>
#include "base/memory/ref_counted.h"
#include "media/base/media_export.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
namespace media {
class VideoFrame;
// Computes the pixel aspect ratio of a given |visible_rect| from its
// |natural_size|.
//
// See https://en.wikipedia.org/wiki/Pixel_aspect_ratio for a detailed
// definition.
//
// Returns NaN or Infinity if |visible_rect| or |natural_size| are empty.
//
// Note: Something has probably gone wrong if you need to call this function;
// pixel aspect ratios should be the source of truth.
//
// TODO(crbug.com/837337): Decide how to encode 'not provided' for pixel aspect
// ratios, and return that if one of the inputs is empty.
MEDIA_EXPORT double GetPixelAspectRatio(const gfx::Rect& visible_rect,
const gfx::Size& natural_size);
// Increases (at most) one of the dimensions of |visible_rect| to produce
// a |natural_size| with the given pixel aspect ratio.
//
// Returns gfx::Size() if |pixel_aspect_ratio| is not finite and positive.
MEDIA_EXPORT gfx::Size GetNaturalSize(const gfx::Rect& visible_rect,
double pixel_aspect_ratio);
// Overload that takes the pixel aspect ratio as an integer fraction (and
// |visible_size| instead of |visible_rect|).
//
// Returns gfx::Size() if numerator or denominator are not positive.
MEDIA_EXPORT gfx::Size GetNaturalSize(const gfx::Size& visible_size,
int aspect_ratio_numerator,
int aspect_ratio_denominator);
// Fills |frame| containing YUV data to the given color values.
MEDIA_EXPORT void FillYUV(VideoFrame* frame, uint8_t y, uint8_t u, uint8_t v);
// Fills |frame| containing YUVA data with the given color values.
MEDIA_EXPORT void FillYUVA(VideoFrame* frame,
uint8_t y,
uint8_t u,
uint8_t v,
uint8_t a);
// Creates a border in |frame| such that all pixels outside of |view_area| are
// black. Only YV12 and ARGB format video frames are currently supported. If
// format is YV12, the size and position of |view_area| must be even to align
// correctly with the color planes.
MEDIA_EXPORT void LetterboxVideoFrame(VideoFrame* frame,
const gfx::Rect& view_area);
// Rotates |src| plane by |rotation| degree with possible flipping vertically
// and horizontally.
// |rotation| is limited to {0, 90, 180, 270}.
// |width| and |height| are expected to be even numbers.
// Both |src| and |dest| planes are packed and have same |width| and |height|.
// When |width| != |height| and rotated by 90/270, only the maximum square
// portion located in the center is rotated. For example, for width=640 and
// height=480, the rotated area is 480x480 located from row 0 through 479 and
// from column 80 through 559. The leftmost and rightmost 80 columns are
// ignored for both |src| and |dest|.
// The caller is responsible for blanking out the margin area.
MEDIA_EXPORT void RotatePlaneByPixels(const uint8_t* src,
uint8_t* dest,
int width,
int height,
int rotation, // Clockwise.
bool flip_vert,
bool flip_horiz);
// Return the largest centered rectangle with the same aspect ratio of |content|
// that fits entirely inside of |bounds|. If |content| is empty, its aspect
// ratio would be undefined; and in this case an empty Rect would be returned.
MEDIA_EXPORT gfx::Rect ComputeLetterboxRegion(const gfx::Rect& bounds,
const gfx::Size& content);
// Same as ComputeLetterboxRegion(), except ensure the result has even-numbered
// x, y, width, and height. |bounds| must already have even-numbered
// coordinates, but the |content| size can be anything.
//
// This is useful for ensuring content scaled and converted to I420 does not
// have color distortions around the edges in a letterboxed video frame. Note
// that, in cases where ComputeLetterboxRegion() would return a 1x1-sized Rect,
// this function could return either a 0x0-sized Rect or a 2x2-sized Rect.
MEDIA_EXPORT gfx::Rect ComputeLetterboxRegionForI420(const gfx::Rect& bounds,
const gfx::Size& content);
// Return a scaled |size| whose area is less than or equal to |target|, where
// one of its dimensions is equal to |target|'s. The aspect ratio of |size| is
// preserved as closely as possible. If |size| is empty, the result will be
// empty.
MEDIA_EXPORT gfx::Size ScaleSizeToFitWithinTarget(const gfx::Size& size,
const gfx::Size& target);
// Return a scaled |size| whose area is greater than or equal to |target|, where
// one of its dimensions is equal to |target|'s. The aspect ratio of |size| is
// preserved as closely as possible. If |size| is empty, the result will be
// empty.
MEDIA_EXPORT gfx::Size ScaleSizeToEncompassTarget(const gfx::Size& size,
const gfx::Size& target);
// Returns |size| with only one of its dimensions increased such that the result
// matches the aspect ratio of |target|. This is different from
// ScaleSizeToEncompassTarget() in two ways: 1) The goal is to match the aspect
// ratio of |target| rather than that of |size|. 2) Only one of the dimensions
// of |size| may change, and it may only be increased (padded). If either
// |size| or |target| is empty, the result will be empty.
MEDIA_EXPORT gfx::Size PadToMatchAspectRatio(const gfx::Size& size,
const gfx::Size& target);
// Copy an RGB bitmap into the specified |region_in_frame| of a YUV video frame.
// Fills the regions outside |region_in_frame| with black.
MEDIA_EXPORT void CopyRGBToVideoFrame(const uint8_t* source,
int stride,
const gfx::Rect& region_in_frame,
VideoFrame* frame);
// Converts a frame with YV12A format into I420 by dropping alpha channel.
MEDIA_EXPORT scoped_refptr<VideoFrame> WrapAsI420VideoFrame(
scoped_refptr<VideoFrame> frame);
// Copy I420 video frame to match the required coded size and pad the region
// outside the visible rect repeatly with the last column / row up to the coded
// size of |dst_frame|. Return false when |dst_frame| is empty or visible rect
// is empty.
// One application is content mirroring using HW encoder. As the required coded
// size for encoder is unknown before capturing, memory copy is needed when the
// coded size does not match the requirement. Padding can improve the encoding
// efficiency in this case, as the encoder will encode the whole coded region.
// Performance-wise, this function could be expensive as it does memory copy of
// the whole visible rect.
// Note:
// 1. |src_frame| and |dst_frame| should have same size of visible rect.
// 2. The visible rect's origin of |dst_frame| should be (0,0).
// 3. |dst_frame|'s coded size (both width and height) should be larger than or
// equal to the visible size, since the visible region in both frames should be
// identical.
MEDIA_EXPORT bool I420CopyWithPadding(const VideoFrame& src_frame,
VideoFrame* dst_frame) WARN_UNUSED_RESULT;
} // namespace media
#endif // MEDIA_BASE_VIDEO_UTIL_H_
| [
"pcding@ucdavis.edu"
] | pcding@ucdavis.edu |
5739ae036b5019955b259653a89a32c8411223a3 | 5fe209e8fb8891f0fa0981be60b724961a8ebf41 | /day6.cpp | 07636bbb323ec4cca3416226991ce5febc2449af | [] | no_license | Jluxcs/CPP_learning | b7d87fe1e1c98ea5f3f203d8db8c706a82d208bb | 9ec057ca6fc5000e3b126bcd49e269043dfcab17 | refs/heads/master | 2020-06-17T02:23:47.588776 | 2019-07-08T08:20:59 | 2019-07-08T08:20:59 | 195,767,170 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | //c++传递指针给函数
#include <iostream>
#include <ctime>
using namespace std;
void gerSeconds(unsigned long *par);
int main(){
unsigned long sec;
gerSeconds(&sec);
cout<<"当前的秒数:"<<sec<<endl;
}
void gerSeconds(unsigned long *par){
*par = time(NULL);
return;
} | [
"852306873@qq.com"
] | 852306873@qq.com |
a819f06d17146b82f70650b918cd1ad1cc722da9 | 4a5f47f4da5356b87c789d15dd83188929791cbc | /src/rpc/rawtransaction.cpp | a422b1c57a65e4a5e7259190b576c8d8bc0e5d4e | [
"MIT"
] | permissive | TMRO2020/UkkeyCoin | e7a5cad8c530311364c47b9aaa0a1f3f0e9db005 | 77aa24be0831b5350d6892d32ff679d9459046a6 | refs/heads/master | 2022-01-12T03:39:55.812200 | 2019-03-19T21:41:00 | 2019-03-19T21:41:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,178 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "chain.h"
#include "coins.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "validation.h"
#include "merkleblock.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "txmempool.h"
#include "uint256.h"
#include "utilstrencodings.h"
#include "instantx.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include "evo/specialtx.h"
#include "evo/providertx.h"
#include "evo/cbtx.h"
#include "llmq/quorums_commitment.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
std::vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey)));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
UniValue a(UniValue::VARR);
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
{
uint256 txid = tx.GetHash();
entry.push_back(Pair("txid", txid.GetHex()));
entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("type", tx.nType));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
UniValue vin(UniValue::VARR);
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
UniValue o(UniValue::VOBJ);
o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true)));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
// Add address and value info if spentindex enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n);
if (GetSpentIndex(spentKey, spentInfo)) {
in.push_back(Pair("value", ValueFromAmount(spentInfo.satoshis)));
in.push_back(Pair("valueSat", spentInfo.satoshis));
if (spentInfo.addressType == 1) {
in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString()));
} else if (spentInfo.addressType == 2) {
in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString()));
}
}
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("valueSat", txout.nValue));
out.push_back(Pair("n", (int64_t)i));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
// Add spent information if spentindex is enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txid, i);
if (GetSpentIndex(spentKey, spentInfo)) {
out.push_back(Pair("spentTxId", spentInfo.txid.GetHex()));
out.push_back(Pair("spentIndex", (int)spentInfo.inputIndex));
out.push_back(Pair("spentHeight", spentInfo.blockHeight));
}
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (!tx.vExtraPayload.empty()) {
entry.push_back(Pair("extraPayloadSize", (int)tx.vExtraPayload.size()));
entry.push_back(Pair("extraPayload", HexStr(tx.vExtraPayload)));
}
if (tx.nType == TRANSACTION_PROVIDER_REGISTER) {
CProRegTx proTx;
if (GetTxPayload(tx, proTx)) {
UniValue obj;
proTx.ToJson(obj);
entry.push_back(Pair("proRegTx", obj));
}
} else if (tx.nType == TRANSACTION_PROVIDER_UPDATE_SERVICE) {
CProUpServTx proTx;
if (GetTxPayload(tx, proTx)) {
UniValue obj;
proTx.ToJson(obj);
entry.push_back(Pair("proUpServTx", obj));
}
} else if (tx.nType == TRANSACTION_PROVIDER_UPDATE_REGISTRAR) {
CProUpRegTx proTx;
if (GetTxPayload(tx, proTx)) {
UniValue obj;
proTx.ToJson(obj);
entry.push_back(Pair("proUpRegTx", obj));
}
} else if (tx.nType == TRANSACTION_PROVIDER_UPDATE_REVOKE) {
CProUpRevTx proTx;
if (GetTxPayload(tx, proTx)) {
UniValue obj;
proTx.ToJson(obj);
entry.push_back(Pair("proUpRevTx", obj));
}
} else if (tx.nType == TRANSACTION_COINBASE) {
CCbTx cbTx;
if (GetTxPayload(tx, cbTx)) {
UniValue obj;
cbTx.ToJson(obj);
entry.push_back(Pair("cbTx", obj));
}
} else if (tx.nType == TRANSACTION_QUORUM_COMMITMENT) {
llmq::CFinalCommitmentTxPayload qcTx;
if (GetTxPayload(tx, qcTx)) {
UniValue obj;
qcTx.ToJson(obj);
entry.push_back(Pair("qcTx", obj));
}
}
if (!hashBlock.IsNull()) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("height", pindex->nHeight));
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
} else {
entry.push_back(Pair("height", -1));
entry.push_back(Pair("confirmations", 0));
}
}
}
bool fLocked = instantsend.IsLockedInstantSendTransaction(txid);
entry.push_back(Pair("instantlock", fLocked));
}
UniValue getrawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n"
"enabled, it also works for blockchain transactions.\n"
"DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
"If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
"\nResult (if verbose is not set or set to false):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose is set to true):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"address\" (string) ukkey address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"extraPayloadSize\" : n (numeric) Size of DIP2 extra payload. Only present if it's a special TX\n"
" \"extraPayload\" : \"hex\" (string) Hex encoded DIP2 extra payload data. Only present if it's a special TX\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"instantlock\" : true|false, (bool) Current transaction lock state\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" true")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
);
LOCK(cs_main);
uint256 hash = ParseHashV(request.params[0], "parameter 1");
// Accept either a bool (true) or a num (>=1) to indicate verbose output.
bool fVerbose = false;
if (request.params.size() > 1) {
if (request.params[1].isNum()) {
if (request.params[1].get_int() != 0) {
fVerbose = true;
}
}
else if(request.params[1].isBool()) {
if(request.params[1].isTrue()) {
fVerbose = true;
}
}
else {
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid type provided. Verbose parameter must be a boolean.");
}
}
CTransactionRef tx;
uint256 hashBlock;
if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string(fTxIndex ? "No such mempool or blockchain transaction"
: "No such mempool transaction. Use -txindex to enable blockchain transaction queries") +
". Use gettransaction for wallet transactions.");
std::string strHex = EncodeHexTx(*tx);
if (!fVerbose)
return strHex;
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", strHex));
TxToJSON(*tx, hashBlock, result);
return result;
}
UniValue gettxoutproof(const JSONRPCRequest& request)
{
if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2))
throw std::runtime_error(
"gettxoutproof [\"txid\",...] ( blockhash )\n"
"\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
"\nNOTE: By default this function only works sometimes. This is when there is an\n"
"unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option or\n"
"specify the block in which the transaction is included manually (by blockhash).\n"
"\nArguments:\n"
"1. \"txids\" (string) A json array of txids to filter\n"
" [\n"
" \"txid\" (string) A transaction hash\n"
" ,...\n"
" ]\n"
"2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n"
"\nResult:\n"
"\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
"\nExamples:\n"
+ HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]'")
+ HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]' \"blockhash\"")
+ HelpExampleRpc("gettxoutproof", "[\"mytxid\",...], \"blockhash\"")
);
std::set<uint256> setTxids;
uint256 oneTxid;
UniValue txids = request.params[0].get_array();
for (unsigned int idx = 0; idx < txids.size(); idx++) {
const UniValue& txid = txids[idx];
if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid txid ")+txid.get_str());
uint256 hash(uint256S(txid.get_str()));
if (setTxids.count(hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str());
setTxids.insert(hash);
oneTxid = hash;
}
LOCK(cs_main);
CBlockIndex* pblockindex = NULL;
uint256 hashBlock;
if (request.params.size() > 1)
{
hashBlock = uint256S(request.params[1].get_str());
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hashBlock];
} else {
const Coin& coin = AccessByTxid(*pcoinsTip, oneTxid);
if (!coin.IsSpent() && coin.nHeight > 0 && coin.nHeight <= chainActive.Height()) {
pblockindex = chainActive[coin.nHeight];
}
}
if (pblockindex == NULL)
{
CTransactionRef tx;
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
pblockindex = mapBlockIndex[hashBlock];
}
CBlock block;
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
unsigned int ntxFound = 0;
for (const auto& tx : block.vtx)
if (setTxids.count(tx->GetHash()))
ntxFound++;
if (ntxFound != setTxids.size())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block");
CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock mb(block, setTxids);
ssMB << mb;
std::string strHex = HexStr(ssMB.begin(), ssMB.end());
return strHex;
}
UniValue verifytxoutproof(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"verifytxoutproof \"proof\"\n"
"\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
"and throwing an RPC error if the block is not in our best chain\n"
"\nArguments:\n"
"1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
"\nResult:\n"
"[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
"\nExamples:\n"
+ HelpExampleCli("verifytxoutproof", "\"proof\"")
+ HelpExampleRpc("gettxoutproof", "\"proof\"")
);
CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
UniValue res(UniValue::VARR);
std::vector<uint256> vMatch;
std::vector<unsigned int> vIndex;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
return res;
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
BOOST_FOREACH(const uint256& hash, vMatch)
res.push_back(hash.GetHex());
return res;
}
UniValue createrawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
throw std::runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"inputs\" (array, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"sequence\":n (numeric, optional) The sequence number\n"
" } \n"
" ,...\n"
" ]\n"
"2. \"outputs\" (object, required) a json object with outputs\n"
" {\n"
" \"address\": x.xxx, (numeric or string, required) The key is the ukkey address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
" \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n"
" ,...\n"
" }\n"
"3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples:\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM), true);
if (request.params[0].isNull() || request.params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = request.params[0].get_array();
UniValue sendTo = request.params[1].get_obj();
CMutableTransaction rawTx;
if (request.params.size() > 2 && !request.params[2].isNull()) {
int64_t nLockTime = request.params[2].get_int64();
if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
}
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
// set the sequence number if passed in the parameters object
const UniValue& sequenceObj = find_value(o, "sequence");
if (sequenceObj.isNum()) {
int64_t seqNr64 = sequenceObj.get_int64();
if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
else
nSequence = (uint32_t)seqNr64;
}
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
std::set<CBitcoinAddress> setAddress;
std::vector<std::string> addrList = sendTo.getKeys();
BOOST_FOREACH(const std::string& name_, addrList) {
if (name_ == "data") {
std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
} else {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Ukkey address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
return EncodeHexTx(rawTx);
}
UniValue decoderawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"type\" : n, (numeric) The type\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwG\" (string) Ukkey address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"extraPayloadSize\" : n (numeric) Size of DIP2 extra payload. Only present if it's a special TX\n"
" \"extraPayload\" : \"hex\" (string) Hex encoded DIP2 extra payload data. Only present if it's a special TX\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
LOCK(cs_main);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR));
CMutableTransaction mtx;
if (!DecodeHexTx(mtx, request.params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
UniValue result(UniValue::VOBJ);
TxToJSON(CTransaction(std::move(mtx)), uint256(), result);
return result;
}
UniValue decodescript(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"decodescript \"hexstring\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hexstring\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) ukkey address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR));
UniValue r(UniValue::VOBJ);
CScript script;
if (request.params[0].get_str().size() > 0){
std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
UniValue type;
type = find_value(r, "type");
if (type.isStr() && type.get_str() != "scripthash") {
// P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
// don't return the address for a P2SH of the P2SH.
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
}
return r;
}
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
entry.push_back(Pair("error", strMessage));
vErrorsRet.push_back(entry);
}
UniValue signrawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
" \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
" \"sequence\" : n, (numeric) Script sequence number\n"
" \"error\" : \"text\" (string) Verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
LOCK(cs_main);
#endif
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
std::vector<unsigned char> txData(ParseHexV(request.params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
std::vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (request.params.size() > 2 && !request.params[2].isNull()) {
fGivenKeys = true;
UniValue keys = request.params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwalletMain)
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (request.params.size() > 1 && !request.params[1].isNull()) {
UniValue prevTxs = request.params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
{"scriptPubKey", UniValueType(UniValue::VSTR)},
});
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
COutPoint out(txid, nOut);
std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
const Coin& coin = view.AccessCoin(out);
if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
std::string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
Coin newcoin;
newcoin.out.scriptPubKey = scriptPubKey;
newcoin.out.nValue = 0;
newcoin.nHeight = 1;
view.AddCoin(out, std::move(newcoin), true);
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheckObj(prevOut,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
{"scriptPubKey", UniValueType(UniValue::VSTR)},
{"redeemScript", UniValueType(UniValue::VSTR)},
});
UniValue v = find_value(prevOut, "redeemScript");
if (!v.isNull()) {
std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (request.params.size() > 3 && !request.params[3].isNull()) {
static std::map<std::string, int> mapSigHashValues =
boost::assign::map_list_of
(std::string("ALL"), int(SIGHASH_ALL))
(std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(std::string("NONE"), int(SIGHASH_NONE))
(std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(std::string("SINGLE"), int(SIGHASH_SINGLE))
(std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
std::string strHashType = request.params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Script verification errors
UniValue vErrors(UniValue::VARR);
// Use CTransaction for the constant parts of the
// transaction to avoid rehashing.
const CTransaction txConst(mergedTx);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
continue;
}
const CScript& prevPubKey = coin.out.scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
if (txv.vin.size() > i) {
txin.scriptSig = CombineSignatures(prevPubKey, txConst, i, txin.scriptSig, txv.vin[i].scriptSig);
}
}
ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i), &serror)) {
TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
}
}
bool fComplete = vErrors.empty();
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
if (!vErrors.empty()) {
result.push_back(Pair("errors", vErrors));
}
return result;
}
UniValue sendrawtransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees instantsend bypasslimits)\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"3. instantsend (boolean, optional, default=false) Use InstantSend to send this transaction\n"
"4. bypasslimits (boolean, optional, default=false) Bypass transaction policy limits\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
LOCK(cs_main);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL));
// parse hex string from parameter
CMutableTransaction mtx;
if (!DecodeHexTx(mtx, request.params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
const uint256& hashTx = tx->GetHash();
CAmount nMaxRawTxFee = maxTxFee;
if (request.params.size() > 1 && request.params[1].get_bool())
nMaxRawTxFee = 0;
bool fInstantSend = false;
if (request.params.size() > 2)
fInstantSend = request.params[2].get_bool();
bool fBypassLimits = false;
if (request.params.size() > 3)
fBypassLimits = request.params[3].get_bool();
CCoinsViewCache &view = *pcoinsTip;
bool fHaveChain = false;
for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {
const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
fHaveChain = !existingCoin.IsSpent();
}
bool fHaveMempool = mempool.exists(hashTx);
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
if (fInstantSend && !instantsend.ProcessTxLockRequest(*tx, *g_connman)) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Not a valid InstantSend transaction, see debug.log for more info");
}
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, std::move(tx), !fBypassLimits, &fMissingInputs, false, nMaxRawTxFee)) {
if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
}
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
g_connman->RelayTransaction(*tx);
return hashTx.GetHex();
}
static const CRPCCommand commands[] =
{ // category name actor (function) okSafeMode
// --------------------- ------------------------ ----------------------- ----------
{ "rawtransactions", "getrawtransaction", &getrawtransaction, true, {"txid","verbose"} },
{ "rawtransactions", "createrawtransaction", &createrawtransaction, true, {"inputs","outputs","locktime"} },
{ "rawtransactions", "decoderawtransaction", &decoderawtransaction, true, {"hexstring"} },
{ "rawtransactions", "decodescript", &decodescript, true, {"hexstring"} },
{ "rawtransactions", "sendrawtransaction", &sendrawtransaction, false, {"hexstring","allowhighfees","instantsend","bypasslimits"} },
{ "rawtransactions", "signrawtransaction", &signrawtransaction, false, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
{ "blockchain", "gettxoutproof", &gettxoutproof, true, {"txids", "blockhash"} },
{ "blockchain", "verifytxoutproof", &verifytxoutproof, true, {"proof"} },
};
void RegisterRawTransactionRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| [
"osaru3@saruyamax.com"
] | osaru3@saruyamax.com |
9d630978e4625bf2d710321d51cd4a17fd676938 | 31651f58f0fc7ab6cd5174eb406463531c563926 | /datasets/ptb/simple-examples/rnnlm-0.2b/rnnlm.cpp | 018f3ce196f38598f354af6df58b16b516e6f97c | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | CavHack/pipeline | 76ee26f016a9503b4ea62bb631930d7c452a1cfd | b397e283d22843d9e05e2f5625affacf9bede741 | refs/heads/master | 2021-07-03T20:00:39.734917 | 2016-09-24T01:59:59 | 2016-09-24T01:59:59 | 69,131,791 | 1 | 0 | Apache-2.0 | 2021-06-04T02:48:48 | 2016-09-24T22:54:23 | Jupyter Notebook | UTF-8 | C++ | false | false | 14,551 | cpp | ///////////////////////////////////////////////////////////////////////
//
// Recurrent neural network based statistical language modeling toolkit
// Version 0.2b
// (c) 2010 Tomas Mikolov (tmikolov@gmail.com)
//
///////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include "rnnlmlib.h"
using namespace std;
#define MAX_STRING 100
int argPos(char *str, int argc, char **argv)
{
int a;
for (a=1; a<argc; a++) if (!strcmp(str, argv[a])) return a;
return -1;
}
int main(int argc, char **argv)
{
int i;
int debug_mode=1;
int train_mode=0;
int valid_data_set=0;
int test_data_set=0;
int rnnlm_file_set=0;
int alpha_set=0, train_file_set=0;
int class_size=100;
float lambda=0.75;
float dynamic=0;
float starting_alpha=0.1;
float regularization=0.0000001;
float min_improvement=1.003;
int hidden_size=30;
int direct=0;
int bptt=0;
int bptt_block=10;
int gen=0;
int rnnlm_exist=0;
int use_lmprob=0;
int rand_seed=1;
int nbest=0;
int one_iter=0;
int anti_k=0;
char train_file[MAX_STRING];
char valid_file[MAX_STRING];
char test_file[MAX_STRING];
char rnnlm_file[MAX_STRING];
char lmprob_file[MAX_STRING];
FILE *f;
if (argc==1) {
//printf("Help\n");
printf("Recurrent neural network based language modeling toolkit v 0.2b\n\n");
printf("Options:\n");
//
printf("Parameters for training phase:\n");
printf("\t-train <file>\n");
printf("\t\tUse text data from <file> to train rnnlm model\n");
printf("\t-class <int>\n");
printf("\t\tWill use specified amount of classes to decompose vocabulary; default is 100\n");
printf("\t-rnnlm <file>\n");
printf("\t\tUse <file> to store rnnlm model\n");
printf("\t-valid <file>\n");
printf("\t\tUse <file> as validation data\n");
printf("\t-alpha <float>\n");
printf("\t\tSet starting learning rate; default is 0.1\n");
printf("\t-beta <float>\n");
printf("\t\tSet L2 regularization parameter; default is 1e-7\n");
printf("\t-hidden <int>\n");
printf("\t\tSet size of hidden layer; default is 30\n");
printf("\t-direct <int>\n");
printf("\t\tWill use direct connections between input and output layers for most frequent <int> words; default is 0\n");
printf("\t-bptt <int>\n");
printf("\t\tSet amount of steps to propagate error back in time; default is 0 (equal to simple RNN)\n");
printf("\t-bptt-block <int>\n");
printf("\t\tSpecifies amount of time steps after which the error is backpropagated through time in block mode (default 10, update at each time step = 1)\n");
printf("\t-one-iter\n");
printf("\t\tWill cause training to perform exactly one iteration over training data (useful for adapting final models on different data etc.)\n");
printf("\t-anti-kasparek <int>\n");
printf("\t\tModel will be saved during training after processing specified amount of words\n");
printf("\t-min-improvement <float>\n");
printf("\t\tSet minimal relative entropy improvement for training convergence; default is 1.003\n");
//
printf("Parameters for testing phase:\n");
printf("\t-rnnlm <file>\n");
printf("\t\tRead rnnlm model from <file>\n");
printf("\t-test <file>\n");
printf("\t\tUse <file> as test data to report perplexity\n");
printf("\t-lm-prob\n");
printf("\t\tUse other LM probabilities for linear interpolation with rnnlm model; see examples/*** \n"); //***
printf("\t-lambda <float>\n");
printf("\t\tSet parameter for linear interpolation of rnnlm and other lm; default weight of rnnlm is 0.75\n");
printf("\t-dynamic <float>\n");
printf("\t\tSet learning rate for dynamic model updates during testing phase; default is 0 (static model)\n");
//
printf("Parameters for data generation:\n");
printf("\t-gen <int>\n");
printf("\t\tGenerate specified amount of words given distribution from current model\n");
printf("\nExamples:\n");
printf("rnnlm -train train -rnnlm model -valid valid -hidden 50\n");
printf("rnnlm -rnnlm model -test test\n");
printf("\n");
return 0; //***
}
//set debug mode
i=argPos((char *)"-debug", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: debug mode not specified!\n");
return 0;
}
debug_mode=atoi(argv[i+1]);
if (debug_mode>0)
printf("debug mode: %d\n", debug_mode);
}
//search for train file
i=argPos((char *)"-train", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: training data file not specified!\n");
return 0;
}
strcpy(train_file, argv[i+1]);
if (debug_mode>0)
printf("train file: %s\n", train_file);
f=fopen(train_file, "rb");
if (f==NULL) {
printf("ERROR: training data file not found!\n");
return 0;
}
train_mode=1;
train_file_set=1;
}
//set one-iter
i=argPos((char *)"-one-iter", argc, argv);
if (i>0) {
one_iter=1;
if (debug_mode>0)
printf("Training for one iteration\n");
}
//search for validation file
i=argPos((char *)"-valid", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: validation data file not specified!\n");
return 0;
}
strcpy(valid_file, argv[i+1]);
if (debug_mode>0)
printf("valid file: %s\n", valid_file);
f=fopen(valid_file, "rb");
if (f==NULL) {
printf("ERROR: validation data file not found!\n");
return 0;
}
valid_data_set=1;
}
if (train_mode && !valid_data_set) {
if (one_iter==0) {
printf("ERROR: validation data file must be specified for training!\n");
return 0;
}
}
//search for test file
i=argPos((char *)"-test", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: test data file not specified!\n");
return 0;
}
strcpy(test_file, argv[i+1]);
if (debug_mode>0)
printf("test file: %s\n", test_file);
f=fopen(test_file, "rb");
if (f==NULL) {
printf("ERROR: test data file not found!\n");
return 0;
}
test_data_set=1;
}
//set class size parameter
i=argPos((char *)"-class", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: amount of classes not specified!\n");
return 0;
}
class_size=atoi(argv[i+1]);
if (debug_mode>0)
printf("class size: %d\n", class_size);
}
//set lambda
i=argPos((char *)"-lambda", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: lambda not specified!\n");
return 0;
}
lambda=atof(argv[i+1]);
if (debug_mode>0)
printf("Lambda (interpolation coefficient between rnnlm and other lm): %f\n", lambda);
}
//set dynamic
i=argPos((char *)"-dynamic", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: dynamic learning rate not specified!\n");
return 0;
}
dynamic=atof(argv[i+1]);
if (debug_mode>0)
printf("Dynamic learning rate: %f\n", dynamic);
}
//set gen
i=argPos((char *)"-gen", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: gen parameter not specified!\n");
return 0;
}
gen=atoi(argv[i+1]);
if (debug_mode>0)
printf("Generating # words: %d\n", gen);
}
//set learning rate
i=argPos((char *)"-alpha", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: alpha not specified!\n");
return 0;
}
starting_alpha=atof(argv[i+1]);
if (debug_mode>0)
printf("Starting learning rate: %f\n", starting_alpha);
alpha_set=1;
}
//set regularization
i=argPos((char *)"-beta", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: beta not specified!\n");
return 0;
}
regularization=atof(argv[i+1]);
if (debug_mode>0)
printf("Regularization: %f\n", regularization);
}
//set min improvement
i=argPos((char *)"-min-improvement", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: minimal improvement value not specified!\n");
return 0;
}
min_improvement=atof(argv[i+1]);
if (debug_mode>0)
printf("Min improvement: %f\n", min_improvement);
}
//set anti kasparek
i=argPos((char *)"-anti-kasparek", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: anti-kasparek parameter not set!\n");
return 0;
}
anti_k=atoi(argv[i+1]);
if ((anti_k!=0) && (anti_k<10000)) anti_k=10000;
if (debug_mode>0)
printf("Model will be saved after each # words: %d\n", anti_k);
}
//set hidden layer size
i=argPos((char *)"-hidden", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: hidden layer size not specified!\n");
return 0;
}
hidden_size=atoi(argv[i+1]);
if (debug_mode>0)
printf("Hidden layer size: %d\n", hidden_size);
}
//set direct connections
i=argPos((char *)"-direct", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: direct connections not specified!\n");
return 0;
}
direct=atoi(argv[i+1]);
if (debug_mode>0)
printf("Direct connections: %d\n", direct);
}
//set bptt
i=argPos((char *)"-bptt", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: bptt value not specified!\n");
return 0;
}
bptt=atoi(argv[i+1]);
bptt++;
if (bptt<1) bptt=0;
if (debug_mode>0)
printf("BPTT: %d\n", bptt-1);
}
//set bptt block
i=argPos((char *)"-bptt-block", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: bptt block value not specified!\n");
return 0;
}
bptt_block=atoi(argv[i+1]);
if (bptt_block<1) bptt_block=1;
if (debug_mode>0)
printf("BPTT block: %d\n", bptt_block);
}
//set random seed
i=argPos((char *)"-rand-seed", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: Random seed variable not specified!\n");
return 0;
}
rand_seed=atoi(argv[i+1]);
if (debug_mode>0)
printf("Rand seed: %d\n", rand_seed);
}
//set nbest rescoring mode
i=argPos((char *)"-nbest", argc, argv);
if (i>0) {
nbest=1;
if (debug_mode>0)
printf("Processing test data as list of nbests\n");
}
//use other lm
i=argPos((char *)"-lm-prob", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: other lm file not specified!\n");
return 0;
}
strcpy(lmprob_file, argv[i+1]);
if (debug_mode>0)
printf("other lm probabilities specified in: %s\n", lmprob_file);
f=fopen(lmprob_file, "rb");
if (f==NULL) {
printf("ERROR: other lm file not found!\n");
return 0;
}
use_lmprob=1;
}
//search for rnnlm file
i=argPos((char *)"-rnnlm", argc, argv);
if (i>0) {
if (i+1==argc) {
printf("ERROR: model file not specified!\n");
return 0;
}
strcpy(rnnlm_file, argv[i+1]);
if (debug_mode>0)
printf("rnnlm file: %s\n", rnnlm_file);
f=fopen(rnnlm_file, "rb");
if (f!=NULL) {
rnnlm_exist=1;
}
rnnlm_file_set=1;
}
if (train_mode && !rnnlm_file_set) {
printf("ERROR: rnnlm file must be specified for training!\n");
return 0;
}
if (test_data_set && !rnnlm_file_set) {
printf("ERROR: rnnlm file must be specified for testing!\n");
return 0;
}
if (!test_data_set && !train_mode && gen==0) {
printf("ERROR: training or testing must be specified!\n");
return 0;
}
if ((gen>0) && !rnnlm_file_set) {
printf("ERROR: rnnlm file must be specified to generate words!\n");
return 0;
}
srand(1);
if (train_mode) {
CRnnLM model1;
model1.setTrainFile(train_file);
model1.setRnnLMFile(rnnlm_file);
model1.setOneIter(one_iter);
if (one_iter==0) model1.setValidFile(valid_file);
model1.setClassSize(class_size);
model1.setLearningRate(starting_alpha);
model1.setRegularization(regularization);
model1.setMinImprovement(min_improvement);
model1.setHiddenLayerSize(hidden_size);
model1.setDirectSize(direct);
model1.setBPTT(bptt);
model1.setBPTTBlock(bptt_block);
model1.setRandSeed(rand_seed);
model1.setDebugMode(debug_mode);
model1.setAntiKasparek(anti_k);
model1.alpha_set=alpha_set;
model1.train_file_set=train_file_set;
model1.trainNet();
}
if (test_data_set && rnnlm_file_set) {
CRnnLM model1;
model1.setLambda(lambda);
model1.setRegularization(regularization);
model1.setDynamic(dynamic);
model1.setTestFile(test_file);
model1.setRnnLMFile(rnnlm_file);
model1.setRandSeed(rand_seed);
model1.useLMProb(use_lmprob);
if (use_lmprob) model1.setLMProbFile(lmprob_file);
model1.setDebugMode(debug_mode);
if (nbest==0) model1.testNet();
else model1.testNbest();
}
if (gen>0) {
CRnnLM model1;
model1.setRnnLMFile(rnnlm_file);
model1.setDebugMode(debug_mode);
model1.setRandSeed(rand_seed);
model1.setGen(gen);
model1.testGen();
}
return 0;
}
| [
"chris@fregly.com"
] | chris@fregly.com |
e3a3fefd05f18e0fa221f3dc444500e79b07d275 | 4c81d5546aa29fb33d8b8d9a7470a4fd69284cc0 | /protocolBuffer/protocolBuffer_org/protobuf-2.6.1/out/BuyClubList_Request.pb.cc | 3c132648b81d88cefbcc15d2f2ab0a13055edea4 | [
"LicenseRef-scancode-protobuf"
] | permissive | zzfeed/tools | 6836c81579a4d02055b12735aa6bde185ecab930 | f43215105e71802afa95b78423011ebaf6c532e8 | refs/heads/master | 2021-09-21T09:56:15.773978 | 2018-08-24T06:09:40 | 2018-08-24T06:09:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 16,365 | cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: BuyClubList_Request.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "BuyClubList_Request.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
// @@protoc_insertion_point(includes)
namespace quote {
void protobuf_ShutdownFile_BuyClubList_5fRequest_2eproto() {
delete BuyClubList_Request::default_instance_;
}
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
void protobuf_AddDesc_BuyClubList_5fRequest_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#else
void protobuf_AddDesc_BuyClubList_5fRequest_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
#endif
BuyClubList_Request::default_instance_ = new BuyClubList_Request();
BuyClubList_Request::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_BuyClubList_5fRequest_2eproto);
}
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_BuyClubList_5fRequest_2eproto_once_);
void protobuf_AddDesc_BuyClubList_5fRequest_2eproto() {
::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_BuyClubList_5fRequest_2eproto_once_,
&protobuf_AddDesc_BuyClubList_5fRequest_2eproto_impl);
}
#else
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_BuyClubList_5fRequest_2eproto {
StaticDescriptorInitializer_BuyClubList_5fRequest_2eproto() {
protobuf_AddDesc_BuyClubList_5fRequest_2eproto();
}
} static_descriptor_initializer_BuyClubList_5fRequest_2eproto_;
#endif
// ===================================================================
#ifndef _MSC_VER
const int BuyClubList_Request::kClassTypeFieldNumber;
const int BuyClubList_Request::kReqFieldsFieldNumber;
const int BuyClubList_Request::kSortFieldFieldNumber;
const int BuyClubList_Request::kSortOrderFieldNumber;
const int BuyClubList_Request::kReqBeginFieldNumber;
const int BuyClubList_Request::kReqSizeFieldNumber;
const int BuyClubList_Request::kReqFlagFieldNumber;
const int BuyClubList_Request::kUserIdFieldNumber;
#endif // !_MSC_VER
BuyClubList_Request::BuyClubList_Request()
: ::google::protobuf::MessageLite() {
SharedCtor();
// @@protoc_insertion_point(constructor:quote.BuyClubList_Request)
}
void BuyClubList_Request::InitAsDefaultInstance() {
}
BuyClubList_Request::BuyClubList_Request(const BuyClubList_Request& from)
: ::google::protobuf::MessageLite() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:quote.BuyClubList_Request)
}
void BuyClubList_Request::SharedCtor() {
_cached_size_ = 0;
class_type_ = 0;
sort_field_ = 0;
sort_order_ = false;
req_begin_ = 0u;
req_size_ = 0u;
req_flag_ = 0u;
user_id_ = GOOGLE_ULONGLONG(0);
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
BuyClubList_Request::~BuyClubList_Request() {
// @@protoc_insertion_point(destructor:quote.BuyClubList_Request)
SharedDtor();
}
void BuyClubList_Request::SharedDtor() {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
if (this != &default_instance()) {
#else
if (this != default_instance_) {
#endif
}
}
void BuyClubList_Request::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const BuyClubList_Request& BuyClubList_Request::default_instance() {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_AddDesc_BuyClubList_5fRequest_2eproto();
#else
if (default_instance_ == NULL) protobuf_AddDesc_BuyClubList_5fRequest_2eproto();
#endif
return *default_instance_;
}
BuyClubList_Request* BuyClubList_Request::default_instance_ = NULL;
BuyClubList_Request* BuyClubList_Request::New() const {
return new BuyClubList_Request;
}
void BuyClubList_Request::Clear() {
#define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \
&reinterpret_cast<BuyClubList_Request*>(16)->f) - \
reinterpret_cast<char*>(16))
#define ZR_(first, last) do { \
size_t f = OFFSET_OF_FIELD_(first); \
size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
::memset(&first, 0, n); \
} while (0)
if (_has_bits_[0 / 32] & 253) {
ZR_(class_type_, user_id_);
}
#undef OFFSET_OF_FIELD_
#undef ZR_
req_fields_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->clear();
}
bool BuyClubList_Request::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
::google::protobuf::io::StringOutputStream unknown_fields_string(
mutable_unknown_fields());
::google::protobuf::io::CodedOutputStream unknown_fields_stream(
&unknown_fields_string);
// @@protoc_insertion_point(parse_start:quote.BuyClubList_Request)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 class_type = 1;
case 1: {
if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &class_type_)));
set_has_class_type();
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_req_fields;
break;
}
// repeated int32 req_fields = 2 [packed = true];
case 2: {
if (tag == 18) {
parse_req_fields:
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_req_fields())));
} else if (tag == 16) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 18, input, this->mutable_req_fields())));
} else {
goto handle_unusual;
}
if (input->ExpectTag(24)) goto parse_sort_field;
break;
}
// required int32 sort_field = 3;
case 3: {
if (tag == 24) {
parse_sort_field:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &sort_field_)));
set_has_sort_field();
} else {
goto handle_unusual;
}
if (input->ExpectTag(32)) goto parse_sort_order;
break;
}
// required bool sort_order = 4;
case 4: {
if (tag == 32) {
parse_sort_order:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &sort_order_)));
set_has_sort_order();
} else {
goto handle_unusual;
}
if (input->ExpectTag(40)) goto parse_req_begin;
break;
}
// required uint32 req_begin = 5;
case 5: {
if (tag == 40) {
parse_req_begin:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &req_begin_)));
set_has_req_begin();
} else {
goto handle_unusual;
}
if (input->ExpectTag(48)) goto parse_req_size;
break;
}
// required uint32 req_size = 6;
case 6: {
if (tag == 48) {
parse_req_size:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &req_size_)));
set_has_req_size();
} else {
goto handle_unusual;
}
if (input->ExpectTag(56)) goto parse_req_flag;
break;
}
// optional uint32 req_flag = 7;
case 7: {
if (tag == 56) {
parse_req_flag:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &req_flag_)));
set_has_req_flag();
} else {
goto handle_unusual;
}
if (input->ExpectTag(64)) goto parse_user_id;
break;
}
// optional uint64 user_id = 8 [default = 0];
case 8: {
if (tag == 64) {
parse_user_id:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &user_id_)));
set_has_user_id();
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(
input, tag, &unknown_fields_stream));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:quote.BuyClubList_Request)
return true;
failure:
// @@protoc_insertion_point(parse_failure:quote.BuyClubList_Request)
return false;
#undef DO_
}
void BuyClubList_Request::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:quote.BuyClubList_Request)
// required int32 class_type = 1;
if (has_class_type()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->class_type(), output);
}
// repeated int32 req_fields = 2 [packed = true];
if (this->req_fields_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_req_fields_cached_byte_size_);
}
for (int i = 0; i < this->req_fields_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32NoTag(
this->req_fields(i), output);
}
// required int32 sort_field = 3;
if (has_sort_field()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->sort_field(), output);
}
// required bool sort_order = 4;
if (has_sort_order()) {
::google::protobuf::internal::WireFormatLite::WriteBool(4, this->sort_order(), output);
}
// required uint32 req_begin = 5;
if (has_req_begin()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->req_begin(), output);
}
// required uint32 req_size = 6;
if (has_req_size()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(6, this->req_size(), output);
}
// optional uint32 req_flag = 7;
if (has_req_flag()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(7, this->req_flag(), output);
}
// optional uint64 user_id = 8 [default = 0];
if (has_user_id()) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(8, this->user_id(), output);
}
output->WriteRaw(unknown_fields().data(),
unknown_fields().size());
// @@protoc_insertion_point(serialize_end:quote.BuyClubList_Request)
}
int BuyClubList_Request::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// required int32 class_type = 1;
if (has_class_type()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->class_type());
}
// required int32 sort_field = 3;
if (has_sort_field()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->sort_field());
}
// required bool sort_order = 4;
if (has_sort_order()) {
total_size += 1 + 1;
}
// required uint32 req_begin = 5;
if (has_req_begin()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->req_begin());
}
// required uint32 req_size = 6;
if (has_req_size()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->req_size());
}
// optional uint32 req_flag = 7;
if (has_req_flag()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->req_flag());
}
// optional uint64 user_id = 8 [default = 0];
if (has_user_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->user_id());
}
}
// repeated int32 req_fields = 2 [packed = true];
{
int data_size = 0;
for (int i = 0; i < this->req_fields_size(); i++) {
data_size += ::google::protobuf::internal::WireFormatLite::
Int32Size(this->req_fields(i));
}
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_req_fields_cached_byte_size_ = data_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
total_size += unknown_fields().size();
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void BuyClubList_Request::CheckTypeAndMergeFrom(
const ::google::protobuf::MessageLite& from) {
MergeFrom(*::google::protobuf::down_cast<const BuyClubList_Request*>(&from));
}
void BuyClubList_Request::MergeFrom(const BuyClubList_Request& from) {
GOOGLE_CHECK_NE(&from, this);
req_fields_.MergeFrom(from.req_fields_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_class_type()) {
set_class_type(from.class_type());
}
if (from.has_sort_field()) {
set_sort_field(from.sort_field());
}
if (from.has_sort_order()) {
set_sort_order(from.sort_order());
}
if (from.has_req_begin()) {
set_req_begin(from.req_begin());
}
if (from.has_req_size()) {
set_req_size(from.req_size());
}
if (from.has_req_flag()) {
set_req_flag(from.req_flag());
}
if (from.has_user_id()) {
set_user_id(from.user_id());
}
}
mutable_unknown_fields()->append(from.unknown_fields());
}
void BuyClubList_Request::CopyFrom(const BuyClubList_Request& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool BuyClubList_Request::IsInitialized() const {
if ((_has_bits_[0] & 0x0000003d) != 0x0000003d) return false;
return true;
}
void BuyClubList_Request::Swap(BuyClubList_Request* other) {
if (other != this) {
std::swap(class_type_, other->class_type_);
req_fields_.Swap(&other->req_fields_);
std::swap(sort_field_, other->sort_field_);
std::swap(sort_order_, other->sort_order_);
std::swap(req_begin_, other->req_begin_);
std::swap(req_size_, other->req_size_);
std::swap(req_flag_, other->req_flag_);
std::swap(user_id_, other->user_id_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.swap(other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::std::string BuyClubList_Request::GetTypeName() const {
return "quote.BuyClubList_Request";
}
// @@protoc_insertion_point(namespace_scope)
} // namespace quote
// @@protoc_insertion_point(global_scope)
| [
"xie123888"
] | xie123888 |
29f282accb576680779b0e44c7832430e6edc6ad | c8b596ba5f07009b646665916a1084d985ef34bc | /mpi_inputfield.h | 2afa953c71acd8720281429a99d073510db2ee0b | [] | no_license | jmerten82/my_first | f5a3c416cf2731b75b0c0863555bcafab0d2eebf | daa7c077903cdcf83b27f89949ed68b250eade86 | refs/heads/master | 2021-06-13T21:28:56.557312 | 2015-03-10T11:24:10 | 2015-03-10T11:24:10 | 254,449,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,724 | h | #ifndef INPUTFIELD_H_
# define INPUTFIELD_H_
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_statistics.h>
#include <cmath>
#include <ctime>
#include "rw_fits.h"
#include "util.h"
#include "soph_math.h"
#include "options.h"
#include "masked_fin_dif.h"
#include "mpi.h"
#include "mpi_comm.h"
using namespace std;
//auxilliary functions
string parametercut2(string);
// cuts out substring between two kinds of given string
int countsymbol2(string, const char&);
// counts the given char in a string
void cutints2(string, string, gsl_vector_int*,int);
//gives all integers separated by string in a string to gsl_vector_int
void cutdoubles2(string, string, gsl_vector*,int);
//same for doubles
class DataGrid
{
/**
Central class of the field preparation process which contains and
calculates all relevant quantities which are written to a FITS file later.
**/
private:
double fieldx;
/*
physical x-dimension of the DataGrid.
*/
double fieldy;
/*
physcial y-dimension of the DataGrid.
*/
double fieldsize;
/*
physical area of the DataGrid, fieldy*fieldy
*/
int x_dim;
/*
pixel x-dimension of the DataGrid
*/
int y_dim;
/*
pixel y-dimension of the DataGrid
*/
double xcentre;
/*
physical x-coordinate of the centre of the bottom left pixel of the DataGrid
*/
double ycentre;
/*
physical y-coordinate of the centre of the bottom left pixel of the DataGrid
*/
double pixelsize;
/*
physical sidelength of one pixel of the DataGrid
*/
int fieldpixels;
/*
Number of non-masked pixels in the DataGrid
*/
gsl_matrix_int *maskcheck;
/*
Identifier for masked pixels in the DataGrid
*/
bool desshear;
/*
For memory deallocation reasons. States if the DataGrid calculates shear.
*/
bool desflexion;
/*
For memory deallocation reasons. States if the DataGrid calculates flexion.
*/
bool desccurve;
/*
For memory deallocation reasons. States if the DataGrid calculates a
critical curve estimator.
*/
bool desmsystems;
/*
For memory deallocation reasons. States if the DataGrid calculates mutliple
image systems.
*/
bool smallindex;
/*
Again for deallocation
*/
bool medindex;
/*
see above
*/
bool root;
/*
Am I the root process?
*/
int numgalshear;
/*
Number of galaxies used for shear estimation in the DataGrid.
*/
double galaxydensityshear;
/*
Number density of the galaxies used for shear estimation in the DataGrid.
numgalshear/fieldsize
*/
gsl_vector *rec;
/*
Contains the RA coordinates of the shear catalogue.
*/
gsl_vector *dec;
/*
Contains the declination coordinates of the shear catalogue.
*/
gsl_vector *ellip1;
/*
Contains the first reduced shear component of the shear catalogue.
*/
gsl_vector *ellip2;
/*
Contains the second reduced shear component of the shear catalogue.
*/
gsl_vector *shearweight;
/*
Contains the weighting function for the reduced shear in the
shear catalogue.
*/
gsl_matrix *meanellip1;
/* Contains the averaged first reduced shear component for each pixel
of the DataGrid.
*/
gsl_matrix *finalmeanellip1;
/*
The full matrix, patched together with all the MPI pieces.
*/
gsl_matrix *meanellip2;
/* Contains the averaged second reduced shear component for each pixel
of the DataGrid.
*/
gsl_matrix *finalmeanellip2;
/*
The full matrix, patched together with all the MPI pieces.
*/
gsl_matrix *ellip1sd;
/* Contains the standard deviation of the first reduced shear component for
each pixel of the DataGrid.
*/
gsl_matrix *finalellip1sd;
/*
The full matrix, patched together with all the MPI pieces.
*/
gsl_matrix *ellip2sd;
/* Contains the standard deviation of the second reduced shear component for
each pixel of the DataGrid.
*/
gsl_matrix *finalellip2sd;
/*
The full matrix, patched together with all the MPI pieces.
*/
gsl_vector *internalellip1;
/* Contains the averaged first reduced shear component for each non-masked
pixel of the DataGrid.
*/
gsl_vector *internalellip2;
/* Contains the averaged second reduced shear component for each non-masked
pixel of the DataGrid.
*/
gsl_vector *internalellip1sd;
/* Contains the standard deviation of the first reduced shear component for
each non-masked pixel of the DataGrid.
*/
gsl_vector *internalellip2sd;
/* Contains the standard deviation of the second reduced shear component for
each non-masked pixel of the DataGrid.
*/
gsl_matrix_uchar *galaxyownersellip;
/*
Matrix which indicates which galaxy in the original catalogue is used
for each pixel in the DataGrid. This is needed to perform covariances.
*/
gsl_matrix_uchar *finalgalaxyownersellip;
/*
The gathering matrix which collects from all processes.
*/
gsl_matrix_int *galaxyshareellip;
/*
Matrix which visualises the galaxy overlap in each pixel. This is used
to calculate the covariances.
*/
gsl_matrix_int *finalgalaxyshareellip;
/*
The full matrix, patched together with all the MPI pieces.
*/
gsl_matrix *ellip1covariance;
/*
Covariance matrix for thr first shear component.
*/
gsl_matrix *finalellip1covariance;
/*
The full matrix, patched together with all the MPI pieces.
*/
gsl_matrix *ellip2covariance;
/*
Covariance matrix for thr second shear component.
*/
gsl_matrix *finalellip2covariance;
/*
The full matrix, patched together with all the MPI pieces.
*/
int numgalflexion;
/*
Number of galaxies used for flexion estimation in the DataGrid.
*/
double galaxydensityflexion;
/*
Number density of the galaxies used for flexion estimation in the DataGrid.
numgalflexion/fieldsize
*/
gsl_vector *recflexion;
/*
Contains the RA coordinates of the flexion catalogue.
*/
gsl_vector *decflexion;
/*
Contains the Declination coordinates of the flexion catalogue.
*/
gsl_vector *f1;
/*
Contains the first F component of the flexion catalogue.
*/
gsl_vector *f2;
/*
Contains the second F component of the flexion catalogue.
*/
gsl_vector *g1;
/*
Contains the first G component of the flexion catalogue.
*/
gsl_vector *g2;
/*
Contains the second G component of the flexion catalogue.
*/
gsl_vector *flexionweight;
/*
Contains the weighting function for the flexion in the
flexion catalogue.
*/
gsl_matrix *meanf1;
/* Contains the averaged first F component for each pixel
of the DataGrid.
*/
gsl_matrix *finalmeanf1;
gsl_matrix *meanf2;
/* Contains the averaged second F component for each pixel
of the DataGrid.
*/
gsl_matrix *finalmeanf2;
gsl_matrix *f1sd;
/* Contains the standard deviation of the first F component for
each pixel of the DataGrid.
*/
gsl_matrix *finalf1sd;
gsl_matrix *f2sd;
/* Contains the standard deviation of the second Fcomponent for
each pixel of the DataGrid.
*/
gsl_matrix *finalf2sd;
gsl_matrix *meang1;
/* Contains the averaged first G component for each pixel
of the DataGrid.
*/
gsl_matrix *finalmeang1;
gsl_matrix *meang2;
/* Contains the averaged second G component for each pixel
of the DataGrid.
*/
gsl_matrix *finalmeang2;
gsl_matrix *g1sd;
/* Contains the standard deviation of the first G component for
each pixel of the DataGrid.
*/
gsl_matrix *finalg1sd;
gsl_matrix *g2sd;
/* Contains the standard deviation of the second G component for
each pixel of the DataGrid.
*/
gsl_matrix *finalg2sd;
gsl_vector *internalf1;
/* Contains the averaged first F component for each non-masked
pixel of the DataGrid.
*/
gsl_vector *internalf2;
/* Contains the averaged second F component for each non-masked
pixel of the DataGrid.
*/
gsl_vector *internalf1sd;
/* Contains the standard deviation of the first F component for
each non-masked pixel of the DataGrid.
*/
gsl_vector *internalf2sd;
/* Contains the standard deviation of the second F component for
each non-masked pixel of the DataGrid.
*/
gsl_vector *internalg1;
/* Contains the averaged first G component for each non-masked
pixel of the DataGrid.
*/
gsl_vector *internalg2;
/* Contains the averaged second G component for each non-masked
pixel of the DataGrid.
*/
gsl_vector *internalg1sd;
/* Contains the standard deviation of the first G component for
each non-masked pixel of the DataGrid.
*/
gsl_vector *internalg2sd;
/* Contains the standard deviation of the second G component for
each non-masked pixel of the DataGrid.
*/
gsl_matrix_uchar *galaxyownersflexion;
/*
Matrix which indicates which galaxy in the original catalogue is used
for each pixel in the DataGrid. This is needed to perform covariances.
*/
gsl_matrix_uchar *finalgalaxyownersflexion;
/*
Gathering matrix for galaxyowners.
*/
gsl_matrix_int *galaxyshareflexion;
/*
Matrix which visualises the galaxy overlap in each pixel. This is used
to calculate the covariances.
*/
gsl_matrix_int *finalgalaxyshareflexion;
gsl_matrix *f1covariance;
/*
Covariance matrix for the first F component.
*/
gsl_matrix *finalf1covariance;
gsl_matrix *f2covariance;
/*
Covariance matrix for the second F component.
*/
gsl_matrix *finalf2covariance;
gsl_matrix *g1covariance;
/*
Covariance matrix for the first G component.
*/
gsl_matrix *finalg1covariance;
gsl_matrix *g2covariance;
/*
Covariance matrix for the second G component.
*/
gsl_matrix *finalg2covariance;
int numccurvepts;
/*
Number of points in the DataGrid, indicated as part of the critical
curve estimate.
*/
gsl_vector *ccurverec;
/*
RA coordinates of the crtical curve estimators.
*/
gsl_vector *ccurvedec;
/*
Declination coordinates of the crtical curve estimators.
*/
gsl_vector *ccurvered;
/*
Redshift information on the critical curve estimators.
*/
gsl_matrix_int *ccurve;
/*
Indicator for the actual critical curve estimate position in the
final DataGrid.
*/
gsl_matrix *ccurveerror;
/*
Error on the critical curve estimation.
*/
gsl_matrix *ccurveredshift;
/*
Redshift information on the critical curve estimator in the actual
DataGrid.
*/
int nummsystems;
/*
Number of multiple image systems.
*/
gsl_matrix *msysteminfo;
/*
Abstract data matrix containing information about position, gridposition
and redshift of multiple image systems.
*/
/*
Insert for an issue in Charles' project! NOT MEMORY EFFICIENT!
*/
gsl_matrix *pure_covariance1;
gsl_matrix *pure_covariance2;
public:
DataGrid(FieldOptions&,int,int my_rank,int p);
/*
Constructor, which needs an options class and an iterationindex.
Reads the catalogues and allocates memory, the rank makes sure
that only the leading process reads data.
*/
~DataGrid();
/*
Standard destructor, free (a lot of) memory.
*/
void analyse(FieldOptions&,int my_rank, int p);
/*
Performs averaging pixel associations and covariances.
The time consuming part.
*/
void write(FieldOptions&,int,int my_rank);
/*
Write the results to FITS resp. ASCII, depending on the options
class and the iterationindex which contain the right filenames.
*/
};
#endif /* !INPUTFIELD_H_ */
| [
"julian.merten@physics.ox.ac.uk"
] | julian.merten@physics.ox.ac.uk |
95c6dd3e3c8fcdae7ad418c1c16b51d404afc663 | 6dcb5aca877030e9d3367ab45abb9611192ca13e | /src/libs/sound/ISoundPlaylistObserver.h | 000a0382e741c0bc978aacd16e0597dec5994ef5 | [
"MIT"
] | permissive | moneytech/dhas | d510dedfd26499093f8a26bf43f260c5c95f2e87 | 424212d4766c02f5df9e363ddb8ad2c295ed49d8 | refs/heads/master | 2021-09-03T18:24:07.451825 | 2018-01-10T23:23:59 | 2018-01-10T23:23:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | h | #pragma once
namespace Dumais{
namespace Sound{
class ISoundPlaylistObserver
{
public:
~ISoundPlaylistObserver(){}
virtual void onSoundQueueEmpty()=0;
};
}
}
| [
"git@dumaisnet.ca"
] | git@dumaisnet.ca |
ea64730e77e81c0c0ff3ff2be219ea4cbcecf882 | e1661d124821ea15d09eec04e2d214a4d6bdbcd2 | /files/djinni/shared-data/generated-src/jni/com/ezored/data/EZRSharedDataPlatformService.cpp | 099576bb0ea9551ba0bb07fe01d6d9b4f38a80bb | [
"MIT"
] | permissive | uilianries/ezored | b6ff656bdecbde830e37066ea154d0326fa823d8 | 8c45a6753ddffce1fe406e6e062ff2b455dbb5a1 | refs/heads/master | 2020-04-29T03:32:12.886679 | 2019-03-15T02:46:28 | 2019-03-15T02:46:28 | 175,813,572 | 0 | 0 | MIT | 2019-03-15T12:10:24 | 2019-03-15T12:10:23 | null | UTF-8 | C++ | false | false | 15,332 | cpp | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from proj.djinni
#include "com/ezored/data/EZRSharedDataPlatformService.hpp" // my header
#include "Marshal.hpp"
namespace djinni_generated {
EZRSharedDataPlatformService::EZRSharedDataPlatformService() : ::djinni::JniInterface<::ezored::data::SharedDataPlatformService, EZRSharedDataPlatformService>() {}
EZRSharedDataPlatformService::~EZRSharedDataPlatformService() = default;
EZRSharedDataPlatformService::JavaProxy::JavaProxy(JniType j) : Handle(::djinni::jniGetThreadEnv(), j) { }
EZRSharedDataPlatformService::JavaProxy::~JavaProxy() = default;
void EZRSharedDataPlatformService::JavaProxy::setString(const std::string & c_key, const std::string & c_value) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_setString,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::String::fromCpp(jniEnv, c_value)));
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::setInteger(const std::string & c_key, int32_t c_value) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_setInteger,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::I32::fromCpp(jniEnv, c_value)));
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::setLong(const std::string & c_key, int64_t c_value) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_setLong,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::I64::fromCpp(jniEnv, c_value)));
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::setBool(const std::string & c_key, bool c_value) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_setBool,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::Bool::fromCpp(jniEnv, c_value)));
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::setFloat(const std::string & c_key, float c_value) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_setFloat,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::F32::fromCpp(jniEnv, c_value)));
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::setDouble(const std::string & c_key, double c_value) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_setDouble,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::F64::fromCpp(jniEnv, c_value)));
::djinni::jniExceptionCheck(jniEnv);
}
std::string EZRSharedDataPlatformService::JavaProxy::getString(const std::string & c_key) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = (jstring)jniEnv->CallObjectMethod(Handle::get().get(), data.method_getString,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::String::toCpp(jniEnv, jret);
}
int32_t EZRSharedDataPlatformService::JavaProxy::getInteger(const std::string & c_key) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallIntMethod(Handle::get().get(), data.method_getInteger,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::I32::toCpp(jniEnv, jret);
}
int64_t EZRSharedDataPlatformService::JavaProxy::getLong(const std::string & c_key) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallLongMethod(Handle::get().get(), data.method_getLong,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::I64::toCpp(jniEnv, jret);
}
bool EZRSharedDataPlatformService::JavaProxy::getBool(const std::string & c_key) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallBooleanMethod(Handle::get().get(), data.method_getBool,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::Bool::toCpp(jniEnv, jret);
}
float EZRSharedDataPlatformService::JavaProxy::getFloat(const std::string & c_key) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallFloatMethod(Handle::get().get(), data.method_getFloat,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::F32::toCpp(jniEnv, jret);
}
double EZRSharedDataPlatformService::JavaProxy::getDouble(const std::string & c_key) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallDoubleMethod(Handle::get().get(), data.method_getDouble,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::F64::toCpp(jniEnv, jret);
}
std::string EZRSharedDataPlatformService::JavaProxy::getStringWithDefaultValue(const std::string & c_key, const std::string & c_defaultValue) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = (jstring)jniEnv->CallObjectMethod(Handle::get().get(), data.method_getStringWithDefaultValue,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::String::fromCpp(jniEnv, c_defaultValue)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::String::toCpp(jniEnv, jret);
}
int32_t EZRSharedDataPlatformService::JavaProxy::getIntegerWithDefaultValue(const std::string & c_key, int32_t c_defaultValue) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallIntMethod(Handle::get().get(), data.method_getIntegerWithDefaultValue,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::I32::fromCpp(jniEnv, c_defaultValue)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::I32::toCpp(jniEnv, jret);
}
int64_t EZRSharedDataPlatformService::JavaProxy::getLongWithDefaultValue(const std::string & c_key, int64_t c_defaultValue) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallLongMethod(Handle::get().get(), data.method_getLongWithDefaultValue,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::I64::fromCpp(jniEnv, c_defaultValue)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::I64::toCpp(jniEnv, jret);
}
bool EZRSharedDataPlatformService::JavaProxy::getBoolWithDefaultValue(const std::string & c_key, bool c_defaultValue) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallBooleanMethod(Handle::get().get(), data.method_getBoolWithDefaultValue,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::Bool::fromCpp(jniEnv, c_defaultValue)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::Bool::toCpp(jniEnv, jret);
}
float EZRSharedDataPlatformService::JavaProxy::getFloatWithDefaultValue(const std::string & c_key, float c_defaultValue) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallFloatMethod(Handle::get().get(), data.method_getFloatWithDefaultValue,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::F32::fromCpp(jniEnv, c_defaultValue)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::F32::toCpp(jniEnv, jret);
}
double EZRSharedDataPlatformService::JavaProxy::getDoubleWithDefaultValue(const std::string & c_key, double c_defaultValue) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallDoubleMethod(Handle::get().get(), data.method_getDoubleWithDefaultValue,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)),
::djinni::get(::djinni::F64::fromCpp(jniEnv, c_defaultValue)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::F64::toCpp(jniEnv, jret);
}
bool EZRSharedDataPlatformService::JavaProxy::has(const std::string & c_key) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
auto jret = jniEnv->CallBooleanMethod(Handle::get().get(), data.method_has,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)));
::djinni::jniExceptionCheck(jniEnv);
return ::djinni::Bool::toCpp(jniEnv, jret);
}
void EZRSharedDataPlatformService::JavaProxy::remove(const std::string & c_key) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_remove,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)));
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::clear() {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_clear);
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::save(bool c_async, bool c_autoFinish) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_save,
::djinni::get(::djinni::Bool::fromCpp(jniEnv, c_async)),
::djinni::get(::djinni::Bool::fromCpp(jniEnv, c_autoFinish)));
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::saveAsync() {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_saveAsync);
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::saveSync() {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_saveSync);
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::start(const std::string & c_groupName) {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_start,
::djinni::get(::djinni::String::fromCpp(jniEnv, c_groupName)));
::djinni::jniExceptionCheck(jniEnv);
}
void EZRSharedDataPlatformService::JavaProxy::finish() {
auto jniEnv = ::djinni::jniGetThreadEnv();
::djinni::JniLocalScope jscope(jniEnv, 10);
const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get();
jniEnv->CallVoidMethod(Handle::get().get(), data.method_finish);
::djinni::jniExceptionCheck(jniEnv);
}
} // namespace djinni_generated
| [
"paulo@prsolucoes.com"
] | paulo@prsolucoes.com |
3a44f2cdf257768de2add16bff061e58650d061b | 250a85858a7f74ce26a200d3e5292ba3bb81624e | /Classes/Stone/Stone_Crab.h | 5d39a96f1f3f76b1afa85f84fe84a4b6c839de83 | [] | no_license | EEEEMAN/cocosOmok | 459944b4e6c770ed101e6f6d710d00d72dac4aba | 5492e11fec5f91177d3915a3e1edca5e1d95e9d3 | refs/heads/master | 2021-07-11T08:13:08.158375 | 2021-03-11T15:04:13 | 2021-03-11T15:04:13 | 31,811,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | h | #ifndef __STONE_CRAB_H__
#define __STONE_CRAB_H__
#include "Stone.h"
class Stone_Crab : public Stone
{
public:
Stone_Crab();
};
#endif | [
"skrnfn2@gmail.com"
] | skrnfn2@gmail.com |
09d78e7bbd0bdc09242aabb50b6577aa26fc6f60 | 9aab638297189a859e0a19420cc2697afe03b1ef | /13_chap_inherit/text/brass/usebrass2.cpp | 7a6735209f79553aa3b0b1579e2d42b1e566bf26 | [] | no_license | inpeterfomax/cplusplus | 3e92657544e80c93aeb45de6323e86821a93175d | 3d01c361157dc1a6d4d9b315cfcb2f8f89acc7d0 | refs/heads/master | 2022-12-08T03:16:24.059550 | 2022-11-26T13:49:03 | 2022-11-26T13:49:03 | 14,574,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,568 | cpp | #include <iostream>
#include "brass.h"
const int CLIENTS = 4;
const int LEN = 40;
int main()
{
using std::cin;
using std::cout;
using std::endl;
Brass * p_clients[CLIENTS];
int i;
char temp[LEN];
long tempnum;
double tempbal;
char kind;
for(i = 0; i < CLIENTS; i ++)
{
char temp[LEN];
long tempnum;
double tempbal;
char kind;
cout << "Enter client's name: ";
cin.getline (temp,LEN);
cout << "Enter client's account number: ";
cin >> tempnum;
cout << "Enter openning balance: $";
cin >> tempbal;
cout << "Enter 1 for Bras Account or 2 for BrassPlus Account: ";
while (cin >> kind && (kind !='1' && kind != '2'))
{
cout << "Enter either 1 or 2: ";
}
if (kind == '1')
{
p_clients[i] = new Brass (temp, tempnum, tempbal);
}
else
{
double tmax, trate;
cout << "Enter the overdraft limit: $";
cin >> tmax;
cout << "Enter the interest rate as a decimal fraction: ";
cin >> trate;
p_clients[i] = new BrassPlus (temp, tempnum, tempbal,tmax,trate);
}
while (cin.get()!='\n')
{
continue;
}
}
cout << endl;
for (i = 0; i < CLIENTS; i ++)
{
p_clients[i]->ViewAcct();
cout << endl;
}
for (i = 0; i < CLIENTS; i ++)
{
delete p_clients[i];
}
cout << "Done. \n";
return 0;
}
| [
"gupingchang@126.com"
] | gupingchang@126.com |
722706dc1714c5d85f184c2cbb7047db93f140bb | d92e9933b8a4ed840d1d87d95727243c1626d747 | /src/Bonus.cpp | cb0e2456e29551b5abef5507c8074d9d13bdb19c | [] | no_license | EricGadbin/Bomberman | dc97197b3709c62e775d67f453e5be4a4d085ec6 | e1567be5ae1fcbbd913f51eb49fcaa0c9faa8225 | refs/heads/master | 2020-07-31T09:24:19.670503 | 2019-09-25T14:34:07 | 2019-09-25T14:34:07 | 210,558,930 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,808 | cpp | /*
** EPITECH PROJECT, 2019
** INDIE_STUDIO
** File description:
** Bonus
*/
#include "../include/Bonus.hpp"
using namespace Indie;
std::string assets[] = {
"../assets/wallbonus.png",
"../assets/speedbonus.png",
"../assets/bombbonus.png",
"../assets/firebonus.png"
};
Bonus::Bonus(btype_t type, irr::core::vector3df pos, irr::scene::ISceneManager* sceneManager, irr::video::IVideoDriver* driver) : _btype(type), _pos(pos), _sound(new sf::Music)
{
_block = Indie::Block(pos, sceneManager, driver);
_block.getCube()->setMaterialTexture(0, driver->getTexture(assets[type].c_str()));
_block.getCube()->setScale(irr::core::vector3df(0.8,0.8,0.8));
_sound->openFromFile("../powerUP.wav");
}
void powerUpSound()
{
sf::Music sound;
sound.openFromFile("../powerUP.wav");
sound.play();
while (sound.getStatus() == sf::SoundSource::Playing);
}
void Bonus::applyBonus(IPlayer *player) const
{
switch (_btype) {
case wUP:
player->setWallpass(true);
break;
case sUP:
player->setSpeed(player->getSpeed() * 1.25);
if (player->getSpeed() > 15 && player->getSpeed() < 16)
player->setSanic(true);
break;
case bUP:
player->setBombNb(player->getBombNb() + 1);
break;
case fUP:
player->setRange(player->getRange() + 1);
if (player->getRange() == 10)
player->setMeg(true);
break;
default:
return;
}
_sound->play();
//std::thread pow(&powerUpSound);
//pow.detach();
}
bool Bonus::checkCollision(irr::core::vector3df nodePosition, IPlayer *player)
{
if (nodePosition.X + 0.2 > _pos.X && nodePosition.X + 0.2 < _pos.X + 1 && nodePosition.Z > _pos.Z && nodePosition.Z < _pos.Z + 1 ||
nodePosition.X + 0.9 > _pos.X && nodePosition.X + 0.9 < _pos.X + 1 && nodePosition.Z > _pos.Z && nodePosition.Z < _pos.Z + 1 ||
nodePosition.X + 0.2 > _pos.X && nodePosition.X + 0.2 < _pos.X + 1 && nodePosition.Z + 0.7 > _pos.Z && nodePosition.Z + 0.7 < _pos.Z + 1 ||
nodePosition.X + 0.9 > _pos.X && nodePosition.X + 0.9 < _pos.X + 1 && nodePosition.Z + 0.7 > _pos.Z && nodePosition.Z + 0.7 < _pos.Z + 1) {
applyBonus(player);
return (true);
}
return (false);
}
bool Bonus::get_time() const
{
return ((std::clock() - _clock) / static_cast<double>(CLOCKS_PER_SEC) >= _iFrames);
}
Bonus::btype_t Bonus::getBonusType() const
{
return _btype;
}
void Bonus::setBonusType(Bonus::btype_t btype)
{
_btype = btype;
}
irr::core::vector3df Bonus::getPos() const
{
return _pos;
}
void Bonus::setPos(irr::core::vector3df pos)
{
_pos = pos;
}
IObject::type_t Bonus::getType() const
{
return _type;
}
| [
"benjamin.renaud@epitech.eu"
] | benjamin.renaud@epitech.eu |
868c9408a0627877f97e325c75688396bf3b6b3d | e398e90159a51b850b9b82540369e98b582468fe | /bioStation/src/main.cpp | f826f4e6b362fc2147bf71376a909f9d1e5ba75a | [] | no_license | unloquer/TalleresESP | f23529b375f494872d2e449d8a040e38960ee031 | a5901fc568285bb9ac925714bd3e4a68976341a5 | refs/heads/master | 2021-01-23T05:44:45.201473 | 2018-03-17T03:09:30 | 2018-03-17T03:09:30 | 92,982,414 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,010 | cpp | /*
This a simple example of the aREST UI Library for the ESP8266.
See the README file for more details.
Written in 2014-2016 by Marco Schwartz under a GPL license.
*/
// Import required libraries
#include <ESP8266WiFi.h>
#include <aREST.h>
#include <aREST_UI.h>
#include <DHT.h>
#define DHTPIN 12 // what pin we're connected to
// Uncomment whatever type you're using!
#define DHTTYPE DHT11 // DHT 11
// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// Create aREST instance
aREST_UI rest = aREST_UI();
// WiFi parameters
const char* ssid = "K5";
const char* password = "seracambiar9";
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Create an instance of the server
WiFiServer server(LISTEN_PORT);
// Variables to be exposed to the API
float temperature;
float humidity;
void setup(void) {
// Start Serial
Serial.begin(115200);
// Set the title
rest.title("aREST UI Demo");
// Init variables and expose them to REST API
temperature = 0;
humidity = 0;
rest.variable("temperature", &temperature);
rest.variable("humidity", &humidity);
// Labels
rest.label("temperature");
rest.label("humidity");
// Give name and ID to device
rest.set_id("1");
rest.set_name("esp8266");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Handle REST calls
WiFiClient client = server.available();
temperature = dht.readTemperature();
humidity = dht.readHumidity();
//Serial.print("temperature ");Serial.println(temperature);
//Serial.print("humidity ");Serial.println(humidity);
if (!client) {
return;
}
while (!client.available()) {
delay(1);
}
rest.handle(client);
}
| [
"brolin108@gmail.com"
] | brolin108@gmail.com |
1b950d20260ecdb1d7cdf745f0c2eb72dd3e8818 | af0b2d96ba888f591b67dc69b3814af6a3573d42 | /blue_shield/blue_shield.ino | d901c7d369d8f1aed091e08cef5e9f508c718faa | [] | no_license | Ketupat-Development-Studios/lumos-switch | e1474525b563156d31f509fdf2374250445e7cae | 6af7ddfa040cf9ef5d8c02627f9191203b25635e | refs/heads/master | 2021-06-28T15:39:05.434570 | 2020-08-15T12:11:26 | 2020-08-15T12:11:26 | 123,659,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,191 | ino | #include<SoftwareSerial.h>
#include<Servo.h>
SoftwareSerial BTserial(3, 2);
Servo actuator;
char c = ' ';
char blueIn = ' ';
boolean readingData = false;
boolean open_state = true;
//int upPin = 4;
//int downPin = 2;
int upVal, downVal;
int upArm = 0;
int downArm = 120;
int restArm = 50;
int state = 999;
int moving = 0;
int move_delay = 150;
int indicator = 0;
int indicator_delay = 100;
int touch_switch = 0;
int touch_switch_delay = 50;
int pairing = 0;
int pairing_delay = 50;
//PINS declaration INPUT
int blueRX = 3;
//PINS declaration OUTPUT
int blueTX = 2;
int blueEN = 5;
int servoCtl = 8;
int touchSensor = 10;
int ind2 = 11;
int ind1 = 12;
void setup() {
Serial.begin(9600);
Serial.println("Arduino is ready");
BTserial.begin(38400);
pinMode(blueRX, INPUT);
pinMode(blueTX, OUTPUT);
pinMode(blueEN, OUTPUT);
pinMode(touchSensor, OUTPUT);
pinMode(ind2, OUTPUT);
pinMode(ind1, OUTPUT);
pinMode(9, INPUT_PULLUP);
actuator.attach(servoCtl);
//Base States
digitalWrite(ind1, LOW);
digitalWrite(ind2, HIGH);
digitalWrite(touchSensor, HIGH);
digitalWrite(blueTX, LOW);
digitalWrite(blueEN, LOW);
}
void loop() {
if (readingData && indicator <= 0) {
indicator = 0;
readingData = false;
}
else if (indicator > 0) {
indicator--;
}
else {
readingData = false;
}
//Keep reading from HC-05 and send to arduino serial monitor
if (BTserial.available()) {
c = BTserial.read();
blueIn = c;
Serial.write(c);
readingData = true;
indicator = indicator_delay;
}
//Keep reading from arduino serial monitor and send to HC-05
if (Serial.available()) {
c = Serial.read();
BTserial.write(c);
}
upVal = HIGH;
downVal = HIGH;
int tmp = digitalRead(9);
// Serial.write("GATE: ");
// Serial.write(tmp==LOW?"LOW":"HIGH");
// Serial.write("\n");
if (touch_switch <= 0) {
if (tmp==LOW) {
if (open_state == true) {
BTserial.write("C\n");
BTserial.flush();
Serial.write("Circuit Closed\n");
touch_switch = touch_switch_delay;
}
open_state = false;
}
else {
if (open_state == false) {
BTserial.write("O\n");
BTserial.flush();
Serial.write("Circuit Open\n");
touch_switch = touch_switch_delay;
}
open_state = true;
}
}
else {
touch_switch--;
if (touch_switch%25 == 0) {
Serial.write("--> Cooldown: ");
Serial.print(touch_switch);
Serial.write("\n");
}
}
if (pairing > 0) pairing--;
if (readingData) digitalWrite(ind1, HIGH);
else digitalWrite(ind1, LOW);
//Hook on bluetooth control --> U (up) D (down)
if (blueIn == 'U') upVal = LOW;
else if (blueIn == 'D') downVal = LOW;
else if (blueIn == 'T') {
if (pairing <= 0) {
digitalWrite(ind1, LOW);
digitalWrite(ind2, LOW);
delay(120);
for (int i=0;i<5;i++) {
digitalWrite(ind2, HIGH);
delay(120);
digitalWrite(ind2, LOW);
delay(120);
}
for (int i=0;i<3;i++) {
digitalWrite(ind1, HIGH);
delay(250);
digitalWrite(ind1, LOW);
delay(250);
}
delay(1000);
pairing = pairing_delay;
}
}
// Serial.write("UP: ");
// Serial.write(upVal==LOW?"LOW":"HIGH");
// Serial.write(" | DOWN: ");
// Serial.write(downVal==LOW?"LOW":"HIGH");
// Serial.write("\n");
if (moving > 0) {
moving--;
digitalWrite(ind2, LOW);
}
else {
if (upVal == HIGH && downVal == HIGH) {
//Resting
if (state != 0) {
actuator.write(restArm);
state = 0;
moving = move_delay;
}
else digitalWrite(ind2, HIGH);
}
else {
if (downVal == LOW) {
if (state != -1) {
actuator.write(downArm);
Serial.write("DOWN\n");
state = -1;
moving = move_delay;
}
else digitalWrite(ind2, HIGH);
}
else if (upVal == LOW) {
if (state != 1) {
actuator.write(upArm);
Serial.write("UP\n");
state = 1;
moving = move_delay;
}
else digitalWrite(ind2, HIGH);
}
}
}
delay(5);
}
| [
"devyaoyh@gmail.com"
] | devyaoyh@gmail.com |
c7443a72fb684d60064a22afe970a823fb316bf7 | 7dd05848e173a624177427f66a1ef7786e94db58 | /extern/lua-5.4.2/src/linit.cc | 3dd960b5b2efc64d4368769dd07d8857af7e33fb | [
"MIT"
] | permissive | stjordanis/rd-eztraits | 6606ca7b63e088b4b045da4ac040125c39a43763 | 5e549edef7a4a39e03747b375a85d8262d0d8431 | refs/heads/master | 2023-07-13T12:24:03.974345 | 2021-08-18T10:53:10 | 2021-08-18T10:53:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,705 | cc | /*
** $Id: linit.c $
** Initialization of libraries for lua.c and other clients
** See Copyright Notice in lua.h
*/
#define linit_c
#define LUA_LIB
/*
** If you embed Lua in your program and need to open the standard
** libraries, call luaL_openlibs in your program. If you need a
** different set of libraries, copy this file to your project and edit
** it to suit your needs.
**
** You can also *preload* libraries, so that a later 'require' can
** open the library, which is already linked to the application.
** For that, do the following code:
**
** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
** lua_pushcfunction(L, luaopen_modname);
** lua_setfield(L, -2, modname);
** lua_pop(L, 1); // remove PRELOAD table
*/
#include "extern/lua-5.4.2/src/lprefix.h"
#include <stddef.h>
#include "extern/lua-5.4.2/src/lua.h"
#include "extern/lua-5.4.2/src/lualib.h"
#include "extern/lua-5.4.2/src/lauxlib.h"
/*
** these libs are loaded by lua.c and are readily available to any Lua
** program
*/
static const luaL_Reg loadedlibs[] = {
{LUA_GNAME, luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_COLIBNAME, luaopen_coroutine},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_UTF8LIBNAME, luaopen_utf8},
{LUA_DBLIBNAME, luaopen_debug},
{NULL, NULL}
};
LUALIB_API void luaL_openlibs (lua_State *L) {
const luaL_Reg *lib;
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
}
}
| [
"manfred.grabherr@imbim.uu.se"
] | manfred.grabherr@imbim.uu.se |
28379d3c2bfb8ad80babf8ad0c30f944a5ab42ac | 460455e7990de7257aa223a58e73069f3ef7ff43 | /src/server/scripts/Kalimdor/CavernsOfTime/DarkPortal/instance_dark_portal.cpp | 6a131594483f1bef460cc1a3df9e373f8063d751 | [] | no_license | Shkipper/wmane | 2ce69adea1eedf866921c857cbc5bd1bc6d037f0 | 2da37e1e758f17b61efb6aae8fa7343b234f3dcd | refs/heads/master | 2020-04-24T19:51:51.897587 | 2019-02-25T06:14:18 | 2019-02-25T06:14:18 | 172,225,859 | 0 | 0 | null | 2019-02-23T14:49:31 | 2019-02-23T14:49:31 | null | UTF-8 | C++ | false | false | 11,104 | cpp | /*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* 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/>.
*/
/* ScriptData
SDName: Instance_Dark_Portal
SD%Complete: 50
SDComment: Quest support: 9836, 10297. Currently in progress.
SDCategory: Caverns of Time, The Dark Portal
EndScriptData */
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "dark_portal.h"
#define MAX_ENCOUNTER 2
#define C_MEDIVH 15608
#define C_TIME_RIFT 17838
#define SPELL_RIFT_CHANNEL 31387
#define RIFT_BOSS 1
inline uint32 RandRiftBoss() { return ((rand()%2) ? C_RKEEP : C_RLORD); }
float PortalLocation[4][4]=
{
{-2041.06f, 7042.08f, 29.99f, 1.30f},
{-1968.18f, 7042.11f, 21.93f, 2.12f},
{-1885.82f, 7107.36f, 22.32f, 3.07f},
{-1928.11f, 7175.95f, 22.11f, 3.44f}
};
struct Wave
{
uint32 PortalBoss; //protector of current portal
uint32 NextPortalTime; //time to next portal, or 0 if portal boss need to be killed
};
static Wave RiftWaves[]=
{
{RIFT_BOSS, 0},
{C_DEJA, 120000},
{RIFT_BOSS, 0},
{C_TEMPO, 140000},
{RIFT_BOSS, 0},
{C_AEONUS, 0}
};
class instance_dark_portal : public InstanceMapScript
{
public:
instance_dark_portal() : InstanceMapScript("instance_dark_portal", 269) { }
InstanceScript* GetInstanceScript(InstanceMap* map) const
{
return new instance_dark_portal_InstanceMapScript(map);
}
struct instance_dark_portal_InstanceMapScript : public InstanceScript
{
instance_dark_portal_InstanceMapScript(Map* map) : InstanceScript(map)
{
}
uint32 m_auiEncounter[MAX_ENCOUNTER];
uint32 mRiftPortalCount;
uint32 mShieldPercent;
uint8 mRiftWaveCount;
uint8 mRiftWaveId;
uint32 NextPortal_Timer;
uint64 MedivhGUID;
uint8 CurrentRiftId;
void Initialize()
{
MedivhGUID = 0;
Clear();
}
void Clear()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
mRiftPortalCount = 0;
mShieldPercent = 100;
mRiftWaveCount = 0;
mRiftWaveId = 0;
CurrentRiftId = 0;
NextPortal_Timer = 0;
}
void InitWorldState(bool Enable = true)
{
DoUpdateWorldState(WORLD_STATE_BM, Enable ? 1 : 0);
DoUpdateWorldState(WORLD_STATE_BM_SHIELD, 100);
DoUpdateWorldState(WORLD_STATE_BM_RIFT, 0);
}
bool IsEncounterInProgress() const
{
if (const_cast<instance_dark_portal_InstanceMapScript*>(this)->GetData(TYPE_MEDIVH) == IN_PROGRESS)
return true;
return false;
}
void OnPlayerEnter(Player* player)
{
if (GetData(TYPE_MEDIVH) == IN_PROGRESS)
return;
player->SendUpdateWorldState(WORLD_STATE_BM, 0);
}
void OnCreatureCreate(Creature* creature)
{
if (creature->GetEntry() == C_MEDIVH)
MedivhGUID = creature->GetGUID();
}
//what other conditions to check?
bool CanProgressEvent()
{
if (instance->GetPlayers().isEmpty())
return false;
return true;
}
uint8 GetRiftWaveId()
{
switch (mRiftPortalCount)
{
case 6:
mRiftWaveId = 2;
return 1;
case 12:
mRiftWaveId = 4;
return 3;
case 18:
return 5;
default:
return mRiftWaveId;
}
}
void SetData(uint32 type, uint32 data)
{
switch (type)
{
case TYPE_MEDIVH:
if (data == SPECIAL && m_auiEncounter[0] == IN_PROGRESS)
{
--mShieldPercent;
DoUpdateWorldState(WORLD_STATE_BM_SHIELD, mShieldPercent);
if (!mShieldPercent)
{
if (Creature* pMedivh = instance->GetCreature(MedivhGUID))
{
if (pMedivh->IsAlive())
{
pMedivh->DealDamage(pMedivh, pMedivh->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
m_auiEncounter[0] = FAIL;
m_auiEncounter[1] = NOT_STARTED;
}
}
}
}
else
{
if (data == IN_PROGRESS)
{
TC_LOG_DEBUG("scripts", "Instance Dark Portal: Starting event.");
InitWorldState();
m_auiEncounter[1] = IN_PROGRESS;
NextPortal_Timer = 15000;
}
if (data == DONE)
{
//this may be completed further out in the post-event
TC_LOG_DEBUG("scripts", "Instance Dark Portal: Event completed.");
Map::PlayerList const& players = instance->GetPlayers();
if (!players.isEmpty())
{
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
{
if (Player* player = itr->GetSource())
{
if (player->GetQuestStatus(QUEST_OPENING_PORTAL) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(QUEST_OPENING_PORTAL);
if (player->GetQuestStatus(QUEST_MASTER_TOUCH) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(QUEST_MASTER_TOUCH);
}
}
}
}
m_auiEncounter[0] = data;
}
break;
case TYPE_RIFT:
if (data == SPECIAL)
{
if (mRiftPortalCount != 6 && mRiftPortalCount != 12 && mRiftPortalCount != 18)
NextPortal_Timer = 5000;
}
else
m_auiEncounter[1] = data;
break;
}
}
uint32 GetData(uint32 type)
{
switch (type)
{
case TYPE_MEDIVH:
return m_auiEncounter[0];
case TYPE_RIFT:
return m_auiEncounter[1];
case DATA_PORTAL_COUNT:
return mRiftPortalCount;
case DATA_SHIELD:
return mShieldPercent;
}
return 0;
}
uint64 GetData64(uint32 data)
{
if (data == DATA_MEDIVH)
return MedivhGUID;
return 0;
}
Creature* SummonedPortalBoss(Creature* me)
{
uint32 entry = RiftWaves[GetRiftWaveId()].PortalBoss;
if (entry == RIFT_BOSS)
entry = RandRiftBoss();
TC_LOG_DEBUG("scripts", "Instance Dark Portal: Summoning rift boss entry %u.", entry);
Position pos;
me->GetRandomNearPosition(pos, 10.0f);
//normalize Z-level if we can, if rift is not at ground level.
pos.m_positionZ = std::max(me->GetMap()->GetHeight(pos.m_positionX, pos.m_positionY, MAX_HEIGHT), me->GetMap()->GetWaterLevel(pos.m_positionX, pos.m_positionY));
if (Creature* summon = me->SummonCreature(entry, pos, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000))
return summon;
TC_LOG_DEBUG("scripts", "Instance Dark Portal: What just happened there? No boss, no loot, no fun...");
return NULL;
}
void DoSpawnPortal()
{
if (Creature* pMedivh = instance->GetCreature(MedivhGUID))
{
uint8 tmp = urand(0, 2);
if (tmp >= CurrentRiftId)
++tmp;
TC_LOG_DEBUG("scripts", "Instance Dark Portal: Creating Time Rift at locationId %i (old locationId was %u).", tmp, CurrentRiftId);
CurrentRiftId = tmp;
Creature* temp = pMedivh->SummonCreature(C_TIME_RIFT,
PortalLocation[tmp][0], PortalLocation[tmp][1], PortalLocation[tmp][2], PortalLocation[tmp][3],
TEMPSUMMON_CORPSE_DESPAWN, 0);
if (temp)
{
temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
if (Creature* pBoss = SummonedPortalBoss(temp))
{
if (pBoss->GetEntry() == C_AEONUS)
pBoss->AddThreat(pMedivh, 0.0f);
else
{
pBoss->AddThreat(temp, 0.0f);
temp->CastSpell(pBoss, SPELL_RIFT_CHANNEL, false);
}
}
}
}
}
void Update(uint32 diff)
{
if (m_auiEncounter[1] != IN_PROGRESS)
return;
//add delay timer?
if (!CanProgressEvent())
{
Clear();
return;
}
if (NextPortal_Timer)
{
if (NextPortal_Timer <= diff)
{
++mRiftPortalCount;
DoUpdateWorldState(WORLD_STATE_BM_RIFT, mRiftPortalCount);
DoSpawnPortal();
NextPortal_Timer = RiftWaves[GetRiftWaveId()].NextPortalTime;
} else NextPortal_Timer -= diff;
}
}
};
};
void AddSC_instance_dark_portal()
{
new instance_dark_portal();
}
| [
"felianther15@gmail.com"
] | felianther15@gmail.com |
1bf936e157d31bca7fb049e14d8e5a2d98ece116 | ee9c5d0ca8f5b0884827f808fd74289f5f8fc5f2 | /problems/BOJ/BOJ1626.cpp | 272d5b73e2e8d9d8f9ae4db9b797efb405a95a44 | [] | no_license | caoash/competitive-programming | a1f69a03da5ea6eae463c6ae521a55bf32011752 | f98d8d547d25811a26cf28316fbeb76477b6c63f | refs/heads/master | 2022-05-26T12:51:37.952057 | 2021-10-10T22:01:03 | 2021-10-10T22:01:03 | 162,861,707 | 21 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,944 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
#define pb push_back
#define rsz resize
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
using pi = pair<int,int>;
#define f first
#define s second
#define mp make_pair
const int MX = 50005;
const int MOD = (int) (1e9 + 7);
const ll INF = (ll) 1e18;
namespace output {
void pr(int x) {
cout << x;
}
void pr(long x) {
cout << x;
}
void pr(ll x) {
cout << x;
}
void pr(unsigned x) {
cout << x;
}
void pr(unsigned long x) {
cout << x;
}
void pr(unsigned long long x) {
cout << x;
}
void pr(float x) {
cout << x;
}
void pr(double x) {
cout << x;
}
void pr(long double x) {
cout << x;
}
void pr(char x) {
cout << x;
}
void pr(const char * x) {
cout << x;
}
void pr(const string & x) {
cout << x;
}
void pr(bool x) {
pr(x ? "true" : "false");
}
template < class T1, class T2 > void pr(const pair < T1, T2 > & x);
template < class T > void pr(const T & x);
template < class T, class...Ts > void pr(const T & t,
const Ts & ...ts) {
pr(t);
pr(ts...);
}
template < class T1, class T2 > void pr(const pair < T1, T2 > & x) {
pr("{", x.f, ", ", x.s, "}");
}
template < class T > void pr(const T & x) {
pr("{"); // const iterator needed for vector<bool>
bool fst = 1;
for (const auto & a: x) pr(!fst ? ", " : "", a), fst = 0;
pr("}");
}
void ps() {
pr("\n");
} // print w/ spaces
template < class T, class...Ts > void ps(const T & t,
const Ts & ...ts) {
pr(t);
if (sizeof...(ts)) pr(" ");
ps(ts...);
}
void pc() {
cout << "]" << endl;
} // debug w/ commas
template < class T, class...Ts > void pc(const T & t,
const Ts & ...ts) {
pr(t);
if (sizeof...(ts)) pr(", ");
pc(ts...);
}
#define dbg(x...) pr("[", #x, "] = ["), pc(x);
}
#ifdef LOCAL
using namespace output;
#endif
template < int SZ > struct LCA {
int depth[SZ];
int p[SZ][33];
int pmx[SZ][33];
int smx[SZ][33];
vector<pi> adj[SZ];
void addEdge(int u, int v, int w) {
adj[u].push_back(mp(v, w));
adj[v].push_back(mp(u, w));
}
void dfs(int v, int par) {
for (pi to : adj[v]) {
if (to.f != par) {
p[to.f][0] = v;
pmx[to.f][0] = to.s;
depth[to.f] = depth[v] + 1;
dfs(to.f, v);
}
}
}
void precomp() {
for (int i = 0; i < SZ; i++) {
for (int j = 0; j < 32; j++) {
p[i][j] = -1;
pmx[i][j] = -1;
smx[i][j] = -1;
}
}
p[0][0] = 0;
pmx[0][0] = 0;
dfs(0, -1);
for (int j = 1; j < 32; j++) {
for (int i = 0; i < SZ; i++) {
if (p[i][j - 1] == -1) {
p[i][j] = -1;
pmx[i][j] = -1;
} else {
p[i][j] = p[p[i][j - 1]][j - 1];
pmx[i][j] = max(pmx[i][j - 1], pmx[p[i][j - 1]][j - 1]);
smx[i][j] = max(smx[i][j - 1], smx[p[i][j - 1]][j - 1]);
if (pmx[i][j - 1] != pmx[p[i][j - 1]][j - 1]) {
smx[i][j] = max(smx[i][j], min(pmx[i][j - 1], pmx[p[i][j - 1]][j - 1]));
}
}
}
}
}
int query(int a, int b) {
if (depth[a] > depth[b]) {
swap(a, b);
}
int lift = depth[b] - depth[a];
int ans = 0;
for (int j = 31; j >= 0; j--) {
if (lift & (1 << j)) {
ans = max(ans, pmx[b][j]);
b = p[b][j];
}
}
for (int j = 31; j >= 0; j--) {
if (p[a][j] != p[b][j]) {
ans = max(ans, pmx[a][j]);
ans = max(ans, pmx[b][j]);
a = p[a][j];
b = p[b][j];
}
}
return (a == b) ? ans : max(ans, max(pmx[a][0], pmx[b][0]));
}
int query2(int a, int b, int best) {
int ans = 0;
auto chk = [&] (int i, int j) {
if (pmx[i][j] == best) {
ans = max(ans, smx[i][j]);
}
else {
ans = max(ans, pmx[i][j]);
}
};
if (depth[a] > depth[b]) {
swap(a, b);
}
int lift = depth[b] - depth[a];
for (int j = 31; j >= 0; j--) {
if (lift & (1 << j)) {
chk(b, j);
b = p[b][j];
}
}
for (int j = 31; j >= 0; j--) {
if (p[a][j] != p[b][j]) {
chk(a, j);
chk(b, j);
a = p[a][j];
b = p[b][j];
}
}
if (a != b) {
chk(a, 0);
chk(b, 0);
}
return ans;
}
};
template < int SZ > struct DSU {
int p[SZ], sz[SZ];
void init() {
for (int i = 0; i < SZ; i++) {
p[i] = i;
sz[i] = 1;
}
}
int find(int x) {
return p[x] = (p[x] == x ? x : find(p[x]));
}
void merge(int u, int v) {
int a = find(u);
int b = find(v);
if (a != b) {
if (sz[a] < sz[b]) {
swap(a, b);
}
p[b] = a;
sz[a] += sz[b];
}
}
};
vector<pair<int, pi>> edges;
vector<pair<int, pi>> bad;
DSU<MX> dsu;
LCA<MX> lca;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n, m; cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, w; cin >> u >> v >> w;
u--, v--;
edges.pb(mp(w, mp(u, v)));
}
dsu.init();
sort(all(edges));
ll cost = 0;
int num = 0;
for (auto x : edges) {
if (dsu.find(x.s.f) != dsu.find(x.s.s)) {
// dbg(x.s.f, x.s.s);
dsu.merge(x.s.f, x.s.s);
lca.addEdge(x.s.f, x.s.s, x.f);
++num;
cost += x.f;
}
else {
bad.pb(x);
}
}
if (num != n - 1) {
cout << -1 << '\n';
return 0;
}
lca.precomp();
ll ans = INF;
for (auto x : bad) {
int curr = lca.query(x.s.f, x.s.s);
if (curr == x.f) {
curr = lca.query2(x.s.f, x.s.s, curr);
}
ans = min(ans, cost - curr + x.f);
}
cout << (ans == INF ? -1 : ans) << '\n';
}
| [
"caoash@gmail.com"
] | caoash@gmail.com |
e0f7e41260c6cd1a26d716ac9777ced1f1fb5730 | 0dc20516079aaae4756d28e67db7cae9c0d33708 | /jxy/jxy_src/jxysvr/thirdparty/breakpad/src/processor/stackwalker_amd64.cc | 06f4b98e0dbfc023bdc52acb4fed29b7a47a5064 | [
"BSD-3-Clause"
] | permissive | psymicgit/dummy | 149365d586f0d4083a7a5719ad7c7268e7dc4bc3 | 483f2d410f353ae4c42abdfe4c606ed542186053 | refs/heads/master | 2020-12-24T07:48:56.132871 | 2017-08-05T07:20:18 | 2017-08-05T07:20:18 | 32,851,013 | 3 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 10,221 | cc | // Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// stackwalker_amd64.cc: amd64-specific stackwalker.
//
// See stackwalker_amd64.h for documentation.
//
// Author: Mark Mentovai, Ted Mielczarek
#include "google_breakpad/processor/call_stack.h"
#include "google_breakpad/processor/memory_region.h"
#include "google_breakpad/processor/source_line_resolver_interface.h"
#include "google_breakpad/processor/stack_frame_cpu.h"
#include "processor/cfi_frame_info.h"
#include "processor/logging.h"
#include "processor/scoped_ptr.h"
#include "processor/stackwalker_amd64.h"
namespace google_breakpad {
const StackwalkerAMD64::CFIWalker::RegisterSet
StackwalkerAMD64::cfi_register_map_[] = {
// It may seem like $rip and $rsp are callee-saves, because the callee is
// responsible for having them restored upon return. But the callee_saves
// flags here really means that the walker should assume they're
// unchanged if the CFI doesn't mention them --- clearly wrong for $rip
// and $rsp.
{ "$rax", NULL, false,
StackFrameAMD64::CONTEXT_VALID_RAX, &MDRawContextAMD64::rax },
{ "$rdx", NULL, false,
StackFrameAMD64::CONTEXT_VALID_RDX, &MDRawContextAMD64::rdx },
{ "$rcx", NULL, false,
StackFrameAMD64::CONTEXT_VALID_RCX, &MDRawContextAMD64::rcx },
{ "$rbx", NULL, true,
StackFrameAMD64::CONTEXT_VALID_RBX, &MDRawContextAMD64::rbx },
{ "$rsi", NULL, false,
StackFrameAMD64::CONTEXT_VALID_RSI, &MDRawContextAMD64::rsi },
{ "$rdi", NULL, false,
StackFrameAMD64::CONTEXT_VALID_RDI, &MDRawContextAMD64::rdi },
{ "$rbp", NULL, true,
StackFrameAMD64::CONTEXT_VALID_RBP, &MDRawContextAMD64::rbp },
{ "$rsp", ".cfa", false,
StackFrameAMD64::CONTEXT_VALID_RSP, &MDRawContextAMD64::rsp },
{ "$r8", NULL, false,
StackFrameAMD64::CONTEXT_VALID_R8, &MDRawContextAMD64::r8 },
{ "$r9", NULL, false,
StackFrameAMD64::CONTEXT_VALID_R9, &MDRawContextAMD64::r9 },
{ "$r10", NULL, false,
StackFrameAMD64::CONTEXT_VALID_R10, &MDRawContextAMD64::r10 },
{ "$r11", NULL, false,
StackFrameAMD64::CONTEXT_VALID_R11, &MDRawContextAMD64::r11 },
{ "$r12", NULL, true,
StackFrameAMD64::CONTEXT_VALID_R12, &MDRawContextAMD64::r12 },
{ "$r13", NULL, true,
StackFrameAMD64::CONTEXT_VALID_R13, &MDRawContextAMD64::r13 },
{ "$r14", NULL, true,
StackFrameAMD64::CONTEXT_VALID_R14, &MDRawContextAMD64::r14 },
{ "$r15", NULL, true,
StackFrameAMD64::CONTEXT_VALID_R15, &MDRawContextAMD64::r15 },
{ "$rip", ".ra", false,
StackFrameAMD64::CONTEXT_VALID_RIP, &MDRawContextAMD64::rip },
};
StackwalkerAMD64::StackwalkerAMD64(const SystemInfo* system_info,
const MDRawContextAMD64* context,
MemoryRegion* memory,
const CodeModules* modules,
StackFrameSymbolizer* resolver_helper)
: Stackwalker(system_info, memory, modules, resolver_helper),
context_(context),
cfi_walker_(cfi_register_map_,
(sizeof(cfi_register_map_) / sizeof(cfi_register_map_[0]))) {
}
StackFrame* StackwalkerAMD64::GetContextFrame() {
if (!context_) {
BPLOG(ERROR) << "Can't get context frame without context";
return NULL;
}
StackFrameAMD64* frame = new StackFrameAMD64();
// The instruction pointer is stored directly in a register, so pull it
// straight out of the CPU context structure.
frame->context = *context_;
frame->context_validity = StackFrameAMD64::CONTEXT_VALID_ALL;
frame->trust = StackFrame::FRAME_TRUST_CONTEXT;
frame->instruction = frame->context.rip;
return frame;
}
StackFrameAMD64* StackwalkerAMD64::GetCallerByCFIFrameInfo(
const vector<StackFrame*> &frames,
CFIFrameInfo* cfi_frame_info) {
StackFrameAMD64* last_frame = static_cast<StackFrameAMD64*>(frames.back());
scoped_ptr<StackFrameAMD64> frame(new StackFrameAMD64());
if (!cfi_walker_
.FindCallerRegisters(*memory_, *cfi_frame_info,
last_frame->context, last_frame->context_validity,
&frame->context, &frame->context_validity))
return NULL;
// Make sure we recovered all the essentials.
static const int essentials = (StackFrameAMD64::CONTEXT_VALID_RIP
| StackFrameAMD64::CONTEXT_VALID_RSP);
if ((frame->context_validity & essentials) != essentials)
return NULL;
frame->trust = StackFrame::FRAME_TRUST_CFI;
return frame.release();
}
StackFrameAMD64* StackwalkerAMD64::GetCallerByStackScan(
const vector<StackFrame*> &frames) {
StackFrameAMD64* last_frame = static_cast<StackFrameAMD64*>(frames.back());
u_int64_t last_rsp = last_frame->context.rsp;
u_int64_t caller_rip_address, caller_rip;
if (!ScanForReturnAddress(last_rsp, &caller_rip_address, &caller_rip)) {
// No plausible return address was found.
return NULL;
}
// Create a new stack frame (ownership will be transferred to the caller)
// and fill it in.
StackFrameAMD64* frame = new StackFrameAMD64();
frame->trust = StackFrame::FRAME_TRUST_SCAN;
frame->context = last_frame->context;
frame->context.rip = caller_rip;
// The caller's %rsp is directly underneath the return address pushed by
// the call.
frame->context.rsp = caller_rip_address + 8;
frame->context_validity = StackFrameAMD64::CONTEXT_VALID_RIP |
StackFrameAMD64::CONTEXT_VALID_RSP;
// Other unwinders give up if they don't have an %rbp value, so see if we
// can pass some plausible value on.
if (last_frame->context_validity & StackFrameAMD64::CONTEXT_VALID_RBP) {
// Functions typically push their caller's %rbp immediately upon entry,
// and then set %rbp to point to that. So if the callee's %rbp is
// pointing to the first word below the alleged return address, presume
// that the caller's %rbp is saved there.
if (caller_rip_address - 8 == last_frame->context.rbp) {
u_int64_t caller_rbp = 0;
if (memory_->GetMemoryAtAddress(last_frame->context.rbp, &caller_rbp) &&
caller_rbp > caller_rip_address) {
frame->context.rbp = caller_rbp;
frame->context_validity |= StackFrameAMD64::CONTEXT_VALID_RBP;
}
} else if (last_frame->context.rbp >= caller_rip_address + 8) {
// If the callee's %rbp is plausible as a value for the caller's
// %rbp, presume that the callee left it unchanged.
frame->context.rbp = last_frame->context.rbp;
frame->context_validity |= StackFrameAMD64::CONTEXT_VALID_RBP;
}
}
return frame;
}
StackFrame* StackwalkerAMD64::GetCallerFrame(const CallStack* stack) {
if (!memory_ || !stack) {
BPLOG(ERROR) << "Can't get caller frame without memory or stack";
return NULL;
}
const vector<StackFrame*> &frames = *stack->frames();
StackFrameAMD64* last_frame = static_cast<StackFrameAMD64*>(frames.back());
scoped_ptr<StackFrameAMD64> new_frame;
// If we have DWARF CFI information, use it.
scoped_ptr<CFIFrameInfo> cfi_frame_info(
frame_symbolizer_->FindCFIFrameInfo(last_frame));
if (cfi_frame_info.get())
new_frame.reset(GetCallerByCFIFrameInfo(frames, cfi_frame_info.get()));
// If CFI failed, or there wasn't CFI available, fall back
// to stack scanning.
if (!new_frame.get()) {
new_frame.reset(GetCallerByStackScan(frames));
}
// If nothing worked, tell the caller.
if (!new_frame.get())
return NULL;
// Treat an instruction address of 0 as end-of-stack.
if (new_frame->context.rip == 0)
return NULL;
// If the new stack pointer is at a lower address than the old, then
// that's clearly incorrect. Treat this as end-of-stack to enforce
// progress and avoid infinite loops.
if (new_frame->context.rsp <= last_frame->context.rsp)
return NULL;
// new_frame->context.rip is the return address, which is one instruction
// past the CALL that caused us to arrive at the callee. Set
// new_frame->instruction to one less than that. This won't reference the
// beginning of the CALL instruction, but it's guaranteed to be within
// the CALL, which is sufficient to get the source line information to
// match up with the line that contains a function call. Callers that
// require the exact return address value may access the context.rip
// field of StackFrameAMD64.
new_frame->instruction = new_frame->context.rip - 1;
return new_frame.release();
}
} // namespace google_breakpad
| [
"wuzili1234@gmail.com"
] | wuzili1234@gmail.com |
25071a0ded9f81060f559feee155a61b7753d78e | 4c6af24752eda9fc0dec55f198530d447a8494af | /HW_1/task6/task6/task6.cpp | 5c22f90c791a2b3f342e11a3379412884c149fe0 | [] | no_license | vlad24/FIRST-SEMESTER | 45feff9d6ffc165d82956593b855f6944af137f7 | 72d2a6d6ea7d53922a924f00c4182c52508ebbb4 | refs/heads/master | 2020-04-15T20:47:39.805095 | 2013-02-17T18:57:09 | 2013-02-17T18:57:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 814 | cpp | //#include "stdafx.h"
#include "iostream"
using namespace std;
int slen(char c[])
{
int u = 0;
while (c[u] != '\0')
{
u++;
}
return u;
}
int main()
{
char mainstring[100] = {};
char substring[100] = {};
cout << "Enter the main string : " ;
cin >> mainstring;
cout << "Enter the sub string : " ;
cin >> substring;
int lengthmain = slen(mainstring);
int lengthsub = slen(substring);
int amount = 0;
int indicator = 0;
for (int j = 0; j <= lengthmain - lengthsub; j++ )
{
indicator = 0;
for (int k = 0; k <= lengthsub; k++ )
{
if (mainstring[j + k] == substring[k])
{
if ((k == lengthsub - 1) && (indicator == 0))
amount ++;
}
else
{
indicator =- 1;
}
}
}
cout << "Amount of occurences = " << amount ;
int time = 0;
cin >> time;
return 0;
}
| [
"vlad.pavlov24@gmail.com"
] | vlad.pavlov24@gmail.com |
477e89b2440a136f640f2b0fe6c0aae967e1a6dc | 89b7e4a17ae14a43433b512146364b3656827261 | /testcases/CWE122_Heap_Based_Buffer_Overflow/s11/CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad.cpp | 280b0ff3dfd509b7dcfd9556258b1ba84d15b220 | [] | no_license | tuyen1998/Juliet_test_Suite | 7f50a3a39ecf0afbb2edfd9f444ee017d94f99ee | 4f968ac0376304f4b1b369a615f25977be5430ac | refs/heads/master | 2020-08-31T23:40:45.070918 | 2019-11-01T07:43:59 | 2019-11-01T07:43:59 | 218,817,337 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,501 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__sizeof.label.xml
Template File: sources-sink-83_bad.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize the source buffer using the size of a pointer
* GoodSource: Initialize the source buffer using the size of the DataElementType
* Sinks:
* BadSink : Print then free data
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83.h"
namespace CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83
{
CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad::CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad(twoIntsStruct * dataCopy)
{
data = dataCopy;
/* INCIDENTAL: CWE-467 (Use of sizeof() on a pointer type) */
/* FLAW: Using sizeof the pointer and not the data type in malloc() */
data = (twoIntsStruct *)malloc(sizeof(data));
if (data == NULL) {exit(-1);}
data->intOne = 1;
data->intTwo = 2;
}
CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad::~CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad()
{
/* POTENTIAL FLAW: Attempt to use data, which may not have enough memory allocated */
printStructLine(data);
free(data);
}
}
#endif /* OMITBAD */
| [
"35531872+tuyen1998@users.noreply.github.com"
] | 35531872+tuyen1998@users.noreply.github.com |
e2c98e4a9ff836be45f3c3440060f3657a812522 | 06c742cf2cb5568925e24a3f8090347efcf59b0f | /Beam_DX11_3D_ENGINE/Code/Source/Rendering/Material.cpp | ed1761ff68d72a400712a890fbd2e2cf0b74d7ff | [] | no_license | BeamPoints/Beam_Dev_3D_Engine | b71b65b158c12f87fbd365728736b876b7a268a3 | 3d6295834e90775bc70716d46d2dd1c3ee0229de | refs/heads/master | 2020-04-23T00:00:34.108045 | 2019-02-22T15:08:49 | 2019-02-22T15:08:49 | 170,762,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 961 | cpp | #include "../../Include/Rendering/Material.h"
bool CMaterial::LoadShader(std::string const & aFilename, std::vector<char>& aByteCode)
{
std::ifstream file;
file.open(aFilename, std::ios::binary);
bool const ok = not (file.eof() or file.fail());
if (ok)
{
file.seekg(0, std::ios_base::end);
std::streampos fileSize = file.tellg();
aByteCode.resize(fileSize);
file.seekg(0, std::ios_base::beg);
file.read(aByteCode.data(), fileSize);
}
return ok;
}
std::vector<D3D11_INPUT_ELEMENT_DESC> const CMaterial::MaterialInfo::sVertexLayout =
{
{
"POSITION", 0,
DXGI_FORMAT_R32G32B32A32_FLOAT,
0,
0,
D3D11_INPUT_PER_VERTEX_DATA,
0
},
{
"NORMAL", 0,
DXGI_FORMAT_R32G32B32_FLOAT,
1,
0,
D3D11_INPUT_PER_VERTEX_DATA,
0
},
{
"TANGENT", 0,
DXGI_FORMAT_R32G32B32_FLOAT,
2,
0,
D3D11_INPUT_PER_VERTEX_DATA,
0
},
{
"TEXCOORD", 0,
DXGI_FORMAT_R32G32B32A32_FLOAT,
3,
0,
D3D11_INPUT_PER_VERTEX_DATA,
0
}
}; | [
"beampoints@gmail.com"
] | beampoints@gmail.com |
57fec50d11f2df8706f891a0e21c9df4c564569a | 64ed6f392c2c43c359d0aab24c6ec84b14fb7487 | /SharedPtr.h | a4e21003618a431fa0c46c823b1eac82bcd31b95 | [] | no_license | rushing-w/DataStruct | e655a8583b77526a823158271f72ac07b7527e65 | afb77f2eb20b2cbd440f6a1511a66b305a568c0b | refs/heads/master | 2021-01-20T07:21:14.679406 | 2017-05-03T05:22:43 | 2017-05-03T05:22:43 | 83,885,978 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,927 | h | #pragma once
#include<iostream>
using namespace std;
//由于上面的指针存在各种各样的问题,只能适用于特定的场合,所以我们需要实现一种比较通用的,
//在这里,实现了SharedPtr,即引用计数的深拷贝
template<class T>
class SharedPtr
{
public:
SharedPtr(T* ptr = NULL)
: _ptr(ptr)
{
_count = new int(1);
}
SharedPtr(SharedPtr<T>& sp)
: _ptr(sp._ptr)
{
(*sp._count)++;
_count = sp._count;
}
SharedPtr<T>& operator=(SharedPtr<T>& sp)
{
if (_ptr != sp._ptr)
{
_ptr = sp._ptr;
if (*sp._count == 1)
{
(*sp._count)++;
_count = sp._count;
}
else
{
(*sp._count)++;
(*_count)--;
_count = sp._count;
}
}
return *this;
}
~SharedPtr()
{
if (_ptr && --(*_count) == 0)
{
delete _ptr;
delete _count;
}
_ptr = NULL;
_count = NULL;
}
T operator*()
{
if (_ptr)
return *_ptr;
return 0;
}
T* operator->()
{
return _ptr;
}
private:
T* _ptr;
int* _count;
};
void TestSharedPtr()
{
SharedPtr<int> sp1(new int(3));
SharedPtr<int> sp2(sp1);
SharedPtr<int> sp3;
SharedPtr<int> sp4(sp3);
sp4 = sp1;
}
//虽然这种引用计数版本的简化版智能指针SharedPtr解决了释放空间时的问题,但是还存在不少问题
//1、存在线程安全问题
//2、循环引用问题-->当我们使用双向链表时,p1的next指向p2,p2的prev指向p1,这时p1和p2的_count值都为2,因为
//都有两个指针指向了一块空间,所以删除时,需要将其中一个的_count--,但是另外一个还在使用这一块空间,所以总是存在
//两个指针指向这块空间,所以直接删除是删除不了的
//---------->>>所以,在boost库中引入了weak_ptr来打破循环引用(weak_ptr不增加引用计数),weak_ptr是一种
//不控制的所指向对象生存期的智能指针,它指向由一个shared_ptr管理的对象。将一个weak_ptr绑定到一个shared_ptr
//上,不会改变shared_ptr的引用计数。即存在循环引用时将weak_ptr的_count++,不去处理shared_ptr的_count。
//一旦最后一个指向对象的shared_ptr被销毁的话,对象就会被释放,即使weak_ptr有指向的对象,对象也还是会被释放 。
//3、定置删除器--->需要包含boost库,所以这里就贴一下代码(vs里面似乎没有这个库)
//#include <boost/shared_ptr.hpp>
//using namespace boost;
//// 定置的删除器仿函数
//class FClose
//{
//public :
// void operator () (void* ptr)
// {
// cout << "fclose" << endl;
// fclose((FILE *)ptr);
// }
//};
//
//class Free
//{
//public :
// void operator () (void* ptr)
// {
// cout << "free" << endl;
// free(ptr);
// }
//};
//void Test()
//{
// // 定制删除器
// shared_ptr<FILE> p1(fopen("test.txt", "w"), FClose());
// // 定制删除器和分配器
// shared_ptr<int> p2((int *)malloc(sizeof(int)), Free(), allocator<int>());
//}
| [
"1030104052@qq.com"
] | 1030104052@qq.com |
ebef6d955ce85c26db137504d85b30c34ef224e7 | c3b4b1441a6ee5a7b6c48e4f9f0649fe14d881b3 | /ClusterSKSolver/source/SKLoader.cpp | af473b8672d278d57f54f605dff2aad617909c4d | [] | no_license | antsuabon/ClusterSKSolver | c50b4452530e46c7b137f9e1360290f9c67f7c6b | 42dfaa84c6890c6a55e7bac6c7c2961fa98979cf | refs/heads/master | 2023-06-04T10:44:19.759862 | 2021-06-27T20:22:03 | 2021-06-27T20:22:03 | 349,968,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,750 | cpp | #include "../header/SKLoader.h"
using namespace std;
vector<string> tokenize(string s, string del = " ")
{
vector<string> res;
int start = 0;
int end = s.find(del);
while (end != -1)
{
res.push_back(s.substr(start, end - start));
start = end + del.size();
end = s.find(del, start);
}
res.push_back(s.substr(start, end - start));
return res;
}
void loadSudoku(string path, int **sudokuArray, map<vector<pair<int, int>>, int> *blocks, int *n, int *regionX, int *regionY)
{
ifstream infile(path);
string line;
string state = "";
vector<vector<int>> initialState;
while (std::getline(infile, line))
{
if (!line.empty())
{
if (line.find("r") != string::npos)
{
state = "r";
}
else if (line.find("b") != string::npos)
{
state = "b";
}
else if (state == "r")
{
vector<string> tokens = tokenize(line, "x");
(*regionX) = stoi(tokens[0]);
(*regionY) = stoi(tokens[1]);
}
else if (state == "b")
{
vector<string> tokens1 = tokenize(line, "->");
vector<pair<int, int>> positions;
vector<string> tokens2 = tokenize(tokens1[0], "|");
for (string &var2 : tokens2)
{
vector<string> tokens3 = tokenize(var2, ",");
positions.push_back({stoi(tokens3[0]), stoi(tokens3[1])});
}
blocks->insert({positions, stoi(tokens1[1])});
}
else
{
vector<int> row;
vector<string> tokens = tokenize(line, ",");
for (string &var : tokens)
{
row.push_back(stoi(var));
}
initialState.push_back(row);
}
}
}
(*n) = initialState.size();
(*sudokuArray) = new int[(*n) * (*n)];
for (size_t i = 0; i < (*n); i++)
{
for (size_t j = 0; j < (*n); j++)
{
(*sudokuArray)[i * (*n) + j] = initialState[i][j];
}
}
} | [
"antsuabon@alum.us.es"
] | antsuabon@alum.us.es |
097a93bee74000f7668218c4942858d384d4a51f | 26fd4d615946f73ee3964cd48fa06120611bf449 | /104_Maximum_Depth_of_Binary_Tree.cpp | 2e0b80fad7d359bc8fb7b14689deeb60e684680f | [] | no_license | xujie-nm/Leetcode | 1aab8a73a33f954bfb3382a286626a56d2f14617 | eb8a7282083e2d2a6c94475759ba01bd4220f354 | refs/heads/master | 2020-04-12T07:25:51.621189 | 2016-12-03T09:29:36 | 2016-12-03T09:29:36 | 28,400,113 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,553 | cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int maxDepth(TreeNode* root){
if(root == NULL)
return 0;
else{
int left = 1 + maxDepth(root->left);
int right = 1 + maxDepth(root->right);
return left >= right ? left : right;
}
}
int main(int argc, const char *argv[])
{
TreeNode n1(3);
TreeNode n2(9);
TreeNode n3(20);
TreeNode n6(15);
TreeNode n7(7);
n1.left = &n2;
n1.right = &n3;
n3.left = &n6;
n3.right = &n7;
cout << maxDepth(&n1) << endl;
return 0;
}
/**
*
* ━━━━━━神兽出没━━━━━━
* ┏┓ ┏┓
* ┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ ┳┛ ┗┳ ┃
* ┃ ┃
* ┃ ┻ ┃
* ┃ ┃
* ┗━┓ ┏ ┛Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*
*/
| [
"xujie_nm@163.com"
] | xujie_nm@163.com |
28bc78033dfa9a3b5291f1011132178e9af86e93 | 5e2e27daacfddfe119015736fcc6e9a864d66c49 | /GameEngine/Graphics/FrustumCalc.cpp | f3e4d4875d8d0e6c78eb75f677056e41f9e4fa38 | [] | no_license | mdubovoy/Animation_System | 17ddc22740962209e7edbd8ea85bec108499f3e2 | b356d0ea6812e0548336bc4813662463e786de93 | refs/heads/master | 2021-01-22T11:41:13.637727 | 2014-09-22T14:01:20 | 2014-09-22T14:01:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,987 | cpp | #include "FrustumCalc.h"
#include "Camera.h"
extern Camera* pCamera; // only used if we want this object to have its own ModelView for debug
#define COLLISION_DEMO 0 // 1 - keys set up to move cube for collision demo, 0 - keys set up to move camera
FrustumCalc::FrustumCalc()
{
lightColor = Vect(1.0f, 0.0f, 0.0f, 0.0f);
// boundingRadius set inside each GraphicObject's transform
}
void FrustumCalc::updateSphere(const Matrix& World, Vect& center)
{
// get 3 more vectors on sphere besides the center
// we want to know our center and radiuss
Vect Px = center + this->boundingRadius * Vect(1, 0, 0);
Vect Py = center + this->boundingRadius * Vect(0, 1, 0);
Vect Pz = center + this->boundingRadius * Vect(0, 0, 1);
// transform vectors by multiplying by localToVector, just like object itself
Vect transPx = Px * World;
Vect transPy = Py * World;
Vect transPz = Pz * World;
Vect transCenter = center * World; //Check
// our new transformed center
center = transCenter;
// calculate max distance, using transformed vects, this will be new bounding radius for object
float distX = (transPx - center).mag();
float distY = (transPy - center).mag();
float distZ = (transPz - center).mag();
// figure out the max distance, set to DistX first
float maxDist = this->maxBoundingObjectDistance(distX, distY, distZ);
// our new bounding radius
this->boundingRadius = maxDist;
#if COLLISION_DEMO
//********Bounding Object's own ModelView for DEBUG only - used to draw sphere**********
this->center = Vect(0.0f, 0.0f, 0.0f); // For Collision Demo only
static float angle_x = 0.0f;
angle_x += 0.15f;
Matrix Scale(SCALE, 1.0f, 1.0f, 1.0f);
Matrix RotX(ROT_X, angle_x);
Matrix Trans(TRANS, -2.0f, 0.0f, 0.0f);
this->World = Scale * Trans; // not using ROT
this->center *= this->World;
this->ModelView = this->World * pCamera->getViewMatrix();
#else
#endif
}
float FrustumCalc::maxBoundingObjectDistance(const float distX, const float distY, const float distZ) const
{
float maxDist = distX;
// if Z is greater than Y, then only compare DistX with DistZ
if(distZ >= distY)
{
if(distX < distZ)
maxDist = distZ;
}
// otherwise only compare DistX with DistY
else if(distY > distZ)
{
if(distX < distY)
maxDist = distY;
}
return maxDist;
}
bool FrustumCalc::insideFrustum(const Vect& center, const Camera* const camera)
{
bool inside;
// get frustum's corner points
Vect camNearBottomLeft;
Vect camFarTopRight;
camera->getNearBottomLeft(camNearBottomLeft);
camera->getFarTopRight(camFarTopRight);
// get normal from each plane
Vect camFrontNorm;
Vect camBackNorm;
Vect camRightNorm;
Vect camLeftNorm;
Vect camTopNorm;
Vect camBottomNorm;
camera->getFrontNorm(camFrontNorm);
camera->getBackNorm(camBackNorm);
camera->getRightNorm(camRightNorm);
camera->getLeftNorm(camLeftNorm);
camera->getTopNorm(camTopNorm);
camera->getBottomNorm(camBottomNorm);
float distLeft = (center - camNearBottomLeft).dot(camLeftNorm);
float distFront = (center - camNearBottomLeft).dot(camFrontNorm);
float distBottom = (center - camNearBottomLeft).dot(camBottomNorm);
float distRight = (center - camFarTopRight).dot(camRightNorm);
float distBack = (center - camFarTopRight).dot(camBackNorm);
float distTop = (center - camFarTopRight).dot(camTopNorm);
// set to true only if culling tests pass
if(distLeft < this->boundingRadius && distFront < this->boundingRadius &&
distBottom < this->boundingRadius && distRight < this->boundingRadius &&
distBack < this->boundingRadius && distTop < this->boundingRadius)
{
inside = true;
}
else
inside = false;
return inside;
}
bool FrustumCalc::insideCollisionDemoCube(const Cube* const model)
{
bool inside;
float distLeft = (this->center - model->nearBottomLeft).dot(model->leftNorm);
float distFront = (this->center - model->nearBottomLeft).dot(model->frontNorm);
float distBottom = (this->center - model->nearBottomLeft).dot(model->bottomNorm);
float distRight = (this->center - model->farTopRight).dot(model->rightNorm);
float distBack = (this->center - model->farTopRight).dot(model->backNorm);
float distTop = (this->center - model->farTopRight).dot(model->topNorm);
// set to true only if culling tests pass
if(distLeft < this->boundingRadius && distFront < this->boundingRadius &&
distBottom < this->boundingRadius && distRight < this->boundingRadius &&
distBack < this->boundingRadius && distTop < this->boundingRadius)
{
inside = true;
}
else
inside = false;
return inside;
} | [
"michel.dubovoy@gmail.com"
] | michel.dubovoy@gmail.com |
472034a1fe62ab43a454a0ffc33e33345712f17f | 0ede806372e66372edabd130593e6660c222f21f | /hw6/ref.cpp | 33f67d40600b338569e69b32147d9cb28241f471 | [] | no_license | elijahverdoorn/SD-Spring-15 | ee47022dbe30a595efe649fcfd19a52406aedb10 | 7b9afb05d874dc939ecd686905754c5dd54a5d81 | refs/heads/master | 2016-09-05T17:03:05.423101 | 2015-09-15T15:16:43 | 2015-09-15T15:16:43 | 34,302,490 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | cpp | #include <iostream>
using namespace std;
void f1(int& x)
{
x++;
}
main()
{
int x = 2;
cout << x << endl;
f1(x);
cout << x << endl;
return 0;
} | [
"elijahverdoorn@gmail.com"
] | elijahverdoorn@gmail.com |
7e7ee7e400491d8def14209c22d725af2e09833d | f1b5f30436d91a3331cca7fb927e68fad4066b6f | /HX711Serial/HX711Serial.ino | 54e84b53e697dfc3d0ac0378381b82bb9e70140d | [] | no_license | woodif/HX-711 | 1a9da33d28c9baa4a6732b117255bbd9ee46dc36 | 5d4a84491e27eee49a42790c92adc9791dd8a9ea | refs/heads/master | 2016-09-02T04:49:48.756846 | 2015-05-16T10:21:01 | 2015-05-16T10:21:01 | 35,719,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,699 | ino | #include "HX711.h"
#include <SoftwareSerial.h>
#include <Wire.h>
//#include <LiquidCrystal_I2C.h>
// HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0
//LiquidCrystal_I2C lcd(0x27, 16, 2);
HX711 scale(A1, A0); // parameter "gain" is ommited; the default value 128 is used by the library
//SoftwareSerial mySerial(10, 9); // RX, TX
static float buf ;
static float raw ;
void setup() {
Serial.begin(115200);
Serial.println("HX711 Demo");
Serial.println("Before setting up the scale:");
Serial.print("read: \t\t");
Serial.println(scale.read()); // print a raw reading from the ADC
///////////////////////////////////////////////////////////////
// lcd.begin();
// lcd.print("Term Project");
// lcd.setCursor(0, 1);
// lcd.print("Weight Sensor");
// delay(3000);
// Serial.begin(57600);
// mySerial.begin(9600);
}
void loop() {
raw = (scale.read() - 8625100.00f) / 41850.11091f;
raw -= 26.35;
raw *= 2.049335863f;
// buf = buf + 0.9f*(raw - buf);
//// buf -= 0 ;
// buf *= -1 ;
Serial.print("real reading:\t");
Serial.print(scale.read());
Serial.print("\t| one reading:\t");
Serial.println(raw);
// Serial.print("\t| average:\t");
// Serial.println(buf,1);
}
///////////////////////////////////////////////////////
// if (buf >= 1){
//// lcd.begin();
//// lcd.print("Weight Unit Kg.");
//// lcd.setCursor(0, 1);
//// lcd.print(buf,1);
//delay(10);
// }
// else {
//// lcd.begin();
//// lcd.print("Weight Sensor");
//// lcd.setCursor(0, 1);
//// lcd.print("By Elec. RMUTL");
// }
//
////if (mySerial.available())
//// Serial.write(mySerial.read());
//// if (Serial.available())
// mySerial.print(buf,1);
//delay(100);
//}
| [
"sarawoot_202@hotmail.com"
] | sarawoot_202@hotmail.com |
a903ab1beccc7bef5a1dab90c14efc18e0a35495 | a712987d2ef30425eda8af84b3132d25d27da46a | /src/network/client.h | fb13e1d122192f9deaaf09f3302c1b39171c774f | [
"MIT"
] | permissive | ziloka/cpptris | ee85210b951285c5f8b37b0b78edcda6300a2ce6 | 281c478add5a8b2c048754f1264c4b70311c4864 | refs/heads/master | 2023-03-19T05:50:35.786618 | 2018-10-30T13:06:02 | 2018-10-30T13:06:02 | 532,646,997 | 1 | 0 | null | 2022-09-04T20:11:35 | 2022-09-04T20:11:34 | null | UTF-8 | C++ | false | false | 1,174 | h |
#ifndef CLIENT_H
#define CLIENT_H
#include <string>
#include <SFML/Network.hpp>
#include "../piece.h"
class Client {
private:
sf::TcpSocket socket;
bool connected = false;
std::string address;
char username[25];
int id;
std::string * users = new std::string[4];
int userWorlds[4][10*20];
int addBlockCount = 0;
int blockSender = 0;
float userPiecePosition[4][2];
int userPiece[4][4*4];
bool gameOver[4];
bool gameStarted = false;
bool gameFinished = false;
int gameWinner = 0;
void connect();
void send(sf::Packet packet);
public:
Client(std::string name, std::string address);
void resetState();
void updateState(int (&world)[10][20]);
void updatePieceState(Piece* piece);
void sendGameOver();
void sendBlock();
bool isConnected();
std::string getName(int i);
bool isGameStarted();
int* getUserWorld(int usr);
float * getPiecePosition(int usr);
int * getPiece(int usr);
bool getGameOver(int usr);
bool isGameFinished();
int getGameWinner();
bool addBlock();
string getBlockSender();
int getId();
};
#endif //CLIENT_H
| [
"me@evgiz.net"
] | me@evgiz.net |
e63ed43c36b42ab2c0fdbe663d81de565f6a568d | ee5d08a8b806b9a5c3452664b9ec6c8776b8225e | /recording/src/irobot_create/nodes/odometry_rosbag.cpp | 49651c905fccd794964b8fc71422984303fe4ca6 | [
"BSD-3-Clause"
] | permissive | sbrodeur/CREATE-dataset | cff764617883f9186c607482f61cf85c4d4007e6 | 473e0555e81516139b6e70362ca0025af100158b | refs/heads/master | 2021-05-05T02:25:24.459839 | 2018-01-31T20:41:50 | 2018-01-31T20:41:50 | 119,738,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,428 | cpp | /******************************************************************************
*
* Copyright (c) 2016, Simon Brodeur
* 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 NECOTIS research group nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <rosbag/bag.h>
#include <rosbag/view.h>
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/exact_time.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/time_synchronizer.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/JointState.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_datatypes.h>
#include <tf2_msgs/TFMessage.h>
using namespace std;
#define AXLE_LEN 0.258
#define WHEEL_DIAMETER 0.078
// NOTE: adapted from http://wiki.ros.org/rosbag/Cookbook
/**
* Inherits from message_filters::SimpleFilter<M>
* to use protected signalMessage function
*/
template <class M>
class BagSubscriber : public message_filters::SimpleFilter<M>
{
public:
void newMessage(const boost::shared_ptr<M const> &msg)
{
message_filters::SimpleFilter<M>::signalMessage(msg);
}
};
class OdometryRosbag
{
typedef sensor_msgs::Imu ImuMsg;
typedef sensor_msgs::JointState JointMsg;
typedef BagSubscriber<ImuMsg> ImuSubscriber;
typedef BagSubscriber<JointMsg> JointSubscriber;
typedef message_filters::sync_policies::ApproximateTime<ImuMsg, JointMsg> SyncPolicy;
typedef message_filters::Synchronizer<SyncPolicy> Synchronizer;
public:
OdometryRosbag(rosbag::Bag* bag, const std::string& output_odom_topic, const bool& publish_tf): initialized_(false){
bag_ = bag;
nb_msg_generated_ = 0;
nb_tf_msg_generated_ = 0;
output_odom_topic_ = output_odom_topic;
publish_tf_ = publish_tf;
// Set frame_id's
const std::string str_base_baselink("base_link");
tf_odom_.header.frame_id = "odom";
tf_odom_.child_frame_id = str_base_baselink;
odom_msg_.header.frame_id = "odom";
odom_msg_.child_frame_id = str_base_baselink;
// Set up fake subscribers to capture Imu and MagneticField messages
imu_sub_.reset(new ImuSubscriber());
joint_sub_.reset(new JointSubscriber());
sync_.reset(new Synchronizer(
SyncPolicy(50), *imu_sub_, *joint_sub_));
sync_->registerCallback(boost::bind(&OdometryRosbag::imuJointCallback, this, _1, _2));
}
virtual ~OdometryRosbag(){
// TODO: fix the following error at termination:
// terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::lock_error> >'
// what(): boost: mutex lock failed in pthread_mutex_lock: Invalid argument
// Aborted
//
// see: https://github.com/ros/ros_comm/issues/318
// http://answers.ros.org/question/143756/rostimer-leads-to-boostlock_error-at-process-cleanup/
imu_sub_.reset();
joint_sub_.reset();
sync_.reset();
}
void addImuMessage(sensor_msgs::Imu::ConstPtr imu){
imu_sub_->newMessage(imu);
}
void addJointMessage(sensor_msgs::JointState::ConstPtr joint){
joint_sub_->newMessage(joint);
}
private:
rosbag::Bag* bag_;
std::string output_odom_topic_;
nav_msgs::Odometry odom_msg_;
geometry_msgs::TransformStamped tf_odom_;
bool initialized_;
ros::Time last_time_;
bool publish_tf_;
int nb_msg_generated_;
int nb_tf_msg_generated_;
double x_;
double y_;
double lastLeftWheelDist_;
double lastRightWheelDist_;
boost::shared_ptr<Synchronizer> sync_;
boost::shared_ptr<ImuSubscriber> imu_sub_;
boost::shared_ptr<JointSubscriber> joint_sub_;
// **** member functions
void imuJointCallback(const ImuMsg::ConstPtr& imu_msg,
const JointMsg::ConstPtr& joint_state_msg){
ros::Time time = imu_msg->header.stamp;
double wheelRadius = WHEEL_DIAMETER / 2.0;
double leftWheelDist = joint_state_msg->position[0] * wheelRadius;
double rightWheelDist = joint_state_msg->position[1] * wheelRadius;
if (!initialized_){
x_ = 0.0;
y_ = 0.0;
lastLeftWheelDist_ = leftWheelDist;
lastRightWheelDist_ = rightWheelDist;
last_time_ = time;
initialized_ = true;
}
double deltaLeftWheelDist = leftWheelDist - lastLeftWheelDist_;
double deltaRightWheelDist = rightWheelDist - lastRightWheelDist_;
// NOTE: assume we are moving straight (true if dt is small enough)
double roll, pitch, yaw;
tf::Quaternion q;
quaternionMsgToTF(imu_msg->orientation, q);
tf::Matrix3x3 m(q);
m.getRPY(roll, pitch, yaw);
double deltaDist = (deltaLeftWheelDist + deltaRightWheelDist) / 2.0;
x_ += deltaDist * cos(yaw);
y_ += deltaDist * sin(yaw);
// Populate position info
// NOTE: propagate timestamp from the message
odom_msg_.header.stamp = time;
odom_msg_.pose.pose.position.x = x_;
odom_msg_.pose.pose.position.y = y_;
odom_msg_.pose.pose.orientation = imu_msg->orientation;
// Populate velocity info (in the frame of the robot)
double velocitiyForward = (joint_state_msg->velocity[0] + joint_state_msg->velocity[1]) * wheelRadius / 2.0;
odom_msg_.twist.twist.linear.x = velocitiyForward;
odom_msg_.twist.twist.linear.y = 0.0;
odom_msg_.twist.twist.angular = imu_msg->angular_velocity;
if (publish_tf_){
// NOTE: propagate timestamp from the message
tf_odom_.header.stamp = time;
tf_odom_.transform.translation.x = x_;
tf_odom_.transform.translation.y = y_;
tf_odom_.transform.rotation = imu_msg->orientation;
// Write tf message to rosbag
//tf::tfMessage tf_msg;
tf2_msgs::TFMessage tf_msg;
tf_msg.transforms.push_back(tf_odom_);
bag_->write("/tf", tf_odom_.header.stamp, tf_msg);
nb_tf_msg_generated_++;
if (nb_tf_msg_generated_ % 1000 == 0){
printf("Number of tf messages generated: %d \n", nb_tf_msg_generated_);
}
}
// Write msg in rosbag here
bag_->write(output_odom_topic_, odom_msg_.header.stamp, odom_msg_);
nb_msg_generated_++;
if (nb_msg_generated_ % 1000 == 0){
printf("Number of odometry messages generated: %d \n", nb_msg_generated_);
}
last_time_ = time;
lastLeftWheelDist_ = leftWheelDist;
lastRightWheelDist_ = rightWheelDist;
}
};
int main(int argc, char **argv){
ros::Time::init();
std::string input_rosbag = "input.bag";
std::string output_rosbag = "output.bag";
std::string output_odom_topic = "/irobot_create/odom";
std::string input_imu_topic = "/imu/data";
std::string input_joint_topic = "/irobot_create/joints";
bool publish_tf = false;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "describe arguments")
("output,o", po::value(&output_rosbag), "set output rosbag file")
("input,i", po::value(&input_rosbag), "set input rosbag file")
("output-odom-topic,d", po::value(&output_odom_topic), "set topic of the output Odometry messages")
("input-imu-topic,m", po::value(&input_imu_topic), "set topic of the input Imu messages")
("input-joint-topic,j", po::value(&input_joint_topic), "set topic of the input JointState messages")
("publish-tf,t", po::bool_switch(&publish_tf), "set to publish tf messages");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
rosbag::Bag output(output_rosbag, rosbag::bagmode::Write);
rosbag::Bag input(input_rosbag, rosbag::bagmode::Read);
OdometryRosbag odometry(&output, output_odom_topic, publish_tf);
int nb_imu_msg_processed = 0;
int nb_joint_msg_processed = 0;
int nb_total_msg_processed = 0;
rosbag::View view(input);
BOOST_FOREACH(rosbag::MessageInstance const m, view)
{
// Detect Imu messages from the given topic
if (m.getTopic() == input_imu_topic || ("/" + m.getTopic() == input_imu_topic))
{
sensor_msgs::Imu::ConstPtr imu = m.instantiate<sensor_msgs::Imu>();
if (imu != NULL){
odometry.addImuMessage(imu);
nb_imu_msg_processed++;
}
}
// Detect JointState messages from the given topic
if (m.getTopic() == input_joint_topic || ("/" + m.getTopic() == input_joint_topic))
{
sensor_msgs::JointState::ConstPtr mag = m.instantiate<sensor_msgs::JointState>();
if (mag != NULL){
odometry.addJointMessage(mag);
nb_joint_msg_processed++;
}
}
if (m.getTopic() != output_odom_topic){
// Write every message to output bag
output.write(m.getTopic(), m.getTime(), m, m.getConnectionHeader());
nb_total_msg_processed++;
}
if (nb_total_msg_processed % 1000 == 0){
printf("Number of imu messages processed: %d (total %d)\n", nb_imu_msg_processed, nb_total_msg_processed);
printf("Number of joint messages processed: %d (total %d)\n", nb_joint_msg_processed, nb_total_msg_processed);
}
}
output.close();
input.close();
return 0;
}
| [
"Simon Brodeur@USherbrooke.ca"
] | Simon Brodeur@USherbrooke.ca |
5be9054993f9ddc91df121b7adabbedc3b46eba0 | 0897a99cad19fdbc4b5a65571bc148aa28086726 | /include/OutOfCore/BlockwiseImage.hpp | b0673216913a9f30ed17d95ffeecb0f79af4fd2c | [] | no_license | sg47/Out_Of_Core_Module | 10c39c03cc85d448e280591333d402cbed87a96a | d1d907df47a508b8a05473deb7f977b32d80be00 | refs/heads/master | 2021-01-22T15:23:10.524661 | 2012-09-12T12:14:35 | 2012-09-12T12:14:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,225 | hpp | #ifndef _BLOCKWISE_IMAGE_HPP
#define _BLOCKWISE_IMAGE_HPP
#include "BlockwiseImage.h"
#include "IndexMethod.hpp"
#include <boost/assert.hpp>
#include <boost/lexical_cast.hpp>
#include <string>
#include <fstream>
#include <strstream>
#ifdef SAVE_MINI_IMAGE
/*---------------------------------------------*/
/* opencv part */
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#ifdef NDEBUG
#pragma comment(lib, "opencv_highgui240.lib")
#pragma comment(lib, "opencv_core240.lib")
#pragma comment(lib, "opencv_imgproc240.lib")
#else
#pragma comment(lib, "opencv_highgui240d.lib")
#pragma comment(lib, "opencv_core240d.lib")
#pragma comment(lib, "opencv_imgproc240d.lib")
#endif
/*---------------------------------------------*/
#endif
template<typename T, unsigned memory_usage>
BlockwiseImage<T, memory_usage>::BlockwiseImage(int rows, int cols, int mini_rows, int mini_cols,
boost::shared_ptr<IndexMethodInterface> method)
: GiantImageInterface(method ? method : (boost::shared_ptr<IndexMethodInterface>(new ZOrderIndex(rows, cols))))
{
init(rows, cols);
set_minimal_resolution(rows, cols, mini_rows, mini_cols);
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::reset()
{
init(0, 0);
return true;
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::init(int rows, int cols)
{
BOOST_ASSERT(rows >= 0 && cols >= 0);
/* ensure index_method is valid */
BOOST_ASSERT(index_method.use_count() != 0);
img_size.rows = rows;
img_size.cols = cols;
img_container.resize(index_method->get_max_index() + 1);
return true;
}
template<typename T, unsigned memory_usage>
void BlockwiseImage<T, memory_usage>::set_minimal_resolution(int rows, int cols, int mini_rows, int mini_cols)
{
BOOST_ASSERT(m_mini_rows >= 0 && m_mini_cols >= 0 && rows >= mini_rows && cols >= mini_cols);
/* ensure the mini_rows and mini_cols not zero to insure the correctness of the division */
if(mini_rows == 0) mini_rows = 1;
if(mini_cols == 0) mini_cols = 1;
size_t level_row = rows / mini_rows, level_col = cols / mini_cols;
level_row = get_least_order_number(level_row);
level_col = get_least_order_number(level_col);
/* ensure the smallest image (the max scale level) is not less than mini_rows or mini_cols which user specified */
m_max_level = (level_row < level_col) ? level_row : level_col;
/* recalculate the mini_rows and mini_cols */
m_mini_rows = std::ceil((double)(rows) / (1 << m_max_level));
m_mini_cols = std::ceil((double)(cols) / (1 << m_max_level));
}
template<typename T, unsigned memory_usage>
BlockwiseImage<T, memory_usage>::~BlockwiseImage()
{
img_container.clear();
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::set_pixels(int start_row, int start_col, int rows, int cols, const std::vector<T> &data)
{
if(start_row < 0 || start_col < 0 || start_row > (get_image_rows()-1) || start_col > (get_image_cols()-1)
|| rows <= 0 || cols <= 0 || (start_row+rows) > get_image_rows() || (start_col+cols) > get_image_cols()) {
std::cerr << "BlockwiseImage::set_pixels error : Invalid parameter" << std::endl;
return false;
}
if(data.size() < (rows*cols)) return false;
size_t count = 0;
for(IndexMethodInterface::RowMajorIndexType row = 0; row < rows; ++row) {
IndexMethodInterface::IndexType row_result = index_method->get_row_result(start_row+row);
for(IndexMethodInterface::RowMajorIndexType col = 0; col < cols; ++col) {
img_container[index_method->get_index_by_row_result(row_result, start_col+col)] = data[count++];
}
}
return true;
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::get_pixels(int start_row, int start_col, int rows, int cols, std::vector<T> &data) const
{
if(start_row < 0 || start_col < 0 || start_row > (get_image_rows()-1) || start_col > (get_image_cols()-1)
|| rows <= 0 || cols <= 0 || (start_row+rows) > get_image_rows() || (start_col+cols) > get_image_cols()) {
std::cerr << "BlockwiseImage::get_pixels error : Invalid parameter" << std::endl;
return false;
}
data.resize(rows*cols);
static const ContainerType &c_img_container = img_container;
size_t count = 0;
for(IndexMethodInterface::RowMajorIndexType row = 0; row < rows; ++row) {
IndexMethodInterface::IndexType row_result = index_method->get_row_result(start_row+row);
for(IndexMethodInterface::RowMajorIndexType col = 0; col < cols; ++col) {
data[count++] = c_img_container[index_method->get_index_by_row_result(row_result, start_col+col)];
}
}
return true;
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::set_pixels(int start_row, int start_col, int rows, int cols, const T clear_value)
{
if(start_row < 0 || start_col < 0 || start_row > (get_image_rows()-1) || start_col > (get_image_cols()-1)
|| rows <= 0 || cols <= 0 || (start_row+rows) > get_image_rows() || (start_col+cols) > get_image_cols()) {
std::cerr << "BlockwiseImage::set_pixels error : Invalid parameter" << std::endl;
return false;
}
for(IndexMethodInterface::RowMajorIndexType row = 0; row < rows; ++row) {
IndexMethodInterface::IndexType row_result = index_method->get_row_result(start_row+row);
for(IndexMethodInterface::RowMajorIndexType col = 0; col < cols; ++col) {
img_container[index_method->get_index_by_row_result(row_result, start_col+col)] = clear_value;
}
}
return true;
}
template<typename T, unsigned memory_usage>
const T& BlockwiseImage<T, memory_usage>::operator()(int row, int col) const
{
BOOST_ASSERT(0 <= row && row < img_size.rows && 0 <= col && col < img_size.cols);
static const ContainerType &c_img_container = img_container;
return c_img_container[index_method->get_index(row, col)];
}
template<typename T, unsigned memory_usage>
T& BlockwiseImage<T, memory_usage>::operator()(int row, int col)
{
BOOST_ASSERT(0 <= row && row < img_size.rows && 0 <= col && col < img_size.cols);
return img_container[index_method->get_index(row, col)];
}
template<typename T, unsigned memory_usage>
const T& BlockwiseImage<T, memory_usage>::get_pixel(int row, int col) const
{
return this->operator() (row, col);
}
template<typename T, unsigned memory_usage>
T& BlockwiseImage<T, memory_usage>::get_pixel(int row, int col)
{
return this->operator() (row, col);
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::write_image_head_file(const char* file_name)
{
namespace bf = boost::filesystem;
using namespace std;
try {
bf::path file_path(file_name);
if(bf::is_directory(file_path)) {
cerr << "file name should be a normal file" << endl;
return false;
}
if(bf::extension(file_path) != ".bigimage") {
cerr << "extension should be bigimage" << endl;
return false;
}
if(!bf::exists(file_path.parent_path()))
bf::create_directories(file_path.parent_path());
} catch(bf::filesystem_error &err) {
cerr << err.what() << endl;
return false;
}
ofstream fout(file_name, ios::out);
if(!fout.is_open()) {
cerr << "create " << file_name << " failure" << endl;
return false;
}
/* the head file info */
fout << "type=" << "BlockwiseImage" << endl;
fout << "rows=" << img_size.rows << endl;
fout << "cols=" << img_size.cols << endl;
fout << "filenodesize=" << file_node_size << endl;
fout << "filenodeshiftnum=" << file_node_shift_num << endl;
fout << "indexmethod=" << index_method->get_index_method_name() << endl;
fout << "minirows=" << m_mini_rows << endl;
fout << "minicols=" << m_mini_cols << endl;
fout.close();
return true;
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::write_image(const char* file_name)
{
using namespace std;
namespace bf = boost::filesystem;
try {
if(!write_image_head_file(file_name)) return false;
bf::path file_path = file_name;
bf::path data_path = (file_path.parent_path() / file_path.stem()).make_preferred();
if(bf::exists(data_path)) {
bf::remove_all(data_path);
cout << "[Warning] : " << data_path << " is existing, and the original directory will be removed" << endl;
}
/* block wise image only has one level : means the full size level */
data_path /= bf::path("level_0");
if(!bf::create_directories(data_path)) {
cerr << "create directory " << data_path << "failure" << endl;
return false;
}
/* because just read the image data, so just const reference to read for some kind of optimization */
static const ContainerType &c_img_container = img_container;
int64 file_number = std::ceil((double)(c_img_container.size()) / file_node_size);
T *temp_file_data = new T[file_node_size];
/* first write the full one file context */
int64 start_index = 0, file_loop = 0;
for(; file_loop < file_number - 1; ++file_loop) {
std::ostrstream strstream;
strstream << data_path.generic_string() << "/" << file_loop << '\0';
ofstream file_out(strstream.str(), ios::out | ios::binary);
if(!file_out.is_open()) {
cerr << "create " << strstream.str() << " failure" << endl;
return false;
}
start_index = (int64)(file_loop) << file_node_shift_num;
for(int64 i = 0; i < file_node_size; ++i) {
temp_file_data[i] = c_img_container[start_index + i];
}
file_out.write(reinterpret_cast<const char*>(temp_file_data), sizeof(T)*file_node_size);
file_out.close();
}
/* write the last file till the end of the container(maybe not full) */
start_index = (int64)(file_loop) << file_node_shift_num;
std::ostrstream strstream;
strstream << data_path.generic_string() << "/" << file_loop << '\0';
ofstream file_out(strstream.str(), ios::out | ios::binary);
if(!file_out.is_open()) {
cerr << "create " << strstream.str() << " failure" << endl;
return false;
}
int64 last_file_size = c_img_container.size() - start_index;
for(int64 i = 0; i < last_file_size; ++i) {
temp_file_data[i] = c_img_container[start_index + i];
}
file_out.write(reinterpret_cast<const char*>(temp_file_data), sizeof(T)*last_file_size);
file_out.close();
delete []temp_file_data;
if(!save_mini_image(file_name)) return false;
} catch(bf::filesystem_error &err) {
cerr << err.what() << endl;
return false;
}
return true;
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::write_image(const std::string &file_name)
{
return write_image(file_name.c_str());
}
template<typename T, unsigned memory_usage>
const T& BlockwiseImage<T, memory_usage>::at(IndexMethodInterface::IndexType index) const
{
BOOST_ASSERT(index < img_container.size());
static const ContainerType &c_img_container = img_container;
return c_img_container[index];
}
template<typename T, unsigned memory_usage>
T& BlockwiseImage<T, memory_usage>::at(IndexMethodInterface::IndexType index)
{
BOOST_ASSERT(index < img_container.size());
return img_container[index];
}
template<typename T, unsigned memory_usage>
bool BlockwiseImage<T, memory_usage>::save_mini_image(const char *file_name)
{
#ifdef SAVE_MINI_IMAGE
const ContainerType &c_img_container = img_container;
/* total_size is the total cell size of the minimum size image
* delta_count is the delta size when access the minimum size image data in
* the whole size img_container
*/
IndexMethodInterface::IndexType total_size, file_cell_size, delta_count;
total_size = c_img_container.size();
file_cell_size = total_size >> (2*m_max_level);
delta_count = 1 << (2*m_max_level);
std::vector<T> img_data(m_mini_rows*m_mini_cols);
std::vector<T> img_zorder_data(file_cell_size);
/* get the hierarchical image first */
for(IndexMethodInterface::IndexType i = 0, count = 0; i < file_cell_size; ++i, count += delta_count) {
img_zorder_data[i] = c_img_container[count];
}
/* convert it to the row-major format */
for(size_t row = 0; row < m_mini_rows; ++row) {
IndexMethodInterface::IndexType row_result = index_method->get_row_result(row);
for(size_t col = 0; col < m_mini_cols; ++col) {
img_data[row*m_mini_cols+col] = img_zorder_data[index_method->get_index_by_row_result(row_result, col)];
}
}
boost::filesystem::path file_path = file_name;
std::string mini_image_name = (file_path.parent_path() / (file_path.stem().generic_string() + ".jpg")).generic_string();
/* save the image into opencv format */
cv::Mat result_image(m_mini_rows, m_mini_cols, CV_8UC3, img_data.data());
/* convert the RGB format to opencv BGR format */
cv::cvtColor(result_image, result_image, CV_RGB2BGR);
cv::imwrite(mini_image_name.c_str(), result_image);
#endif
return true;
}
/* deprecated function */
//boost::shared_ptr<BlockwiseImage<T, memory_usage> > BlockwiseImage<T, memory_usage>::load_image(const char *file_name)
//{
// typedef boost::shared_ptr<BlockwiseImage<T, memory_usage> > PtrType;
// PtrType dst_image(new BlockwiseImage<T, memory_usage> (0, 0));
// PtrType null_image;
//
// if(!dst_image->load_image_head_file(file_name)) return null_image;
//
// bf::path file_path(file_name);
// bf::path data_path = (file_path.parent_path() / file_path.stem()).make_preferred();
// data_path /= "level_0";
// if(!bf::exists(data_path)) {
// cerr << "image data missing" << endl;
// return null_image;
// }
//
// /* get the new value, then init for using */
// dst_image->init(dst_image->get_image_rows(), dst_image->get_image_cols());
//
// ContainerType &img_container = dst_image->img_container;
// int64 file_number = std::ceil((double)(img_container.size()) / dst_image->file_node_size);
//
// int64 start_index = 0, file_loop = 0;
// int64 file_node_shift_num = dst_image->file_node_shift_num;
// int64 file_node_size = dst_image->file_node_size;
//
// /* first read the full context files */
// for(; file_loop < file_number - 1; ++file_loop) {
// std::ostrstream strstream;
// strstream << data_path.generic_string() << "/" << file_loop << '\0';
// if(!bf::exists(bf::path(strstream.str()))) {
// cerr << "image data missing" << endl;
// return null_image;
// }
//
// /* now read the existing data file */
// ifstream file_in(strstream.str(), ios::out | ios::binary);
// if(!file_in.is_open()) {
// cerr << "open" << strstream.str() << " failure" << endl;
// return null_image;
// }
//
// start_index = (int64)(file_loop) << file_node_shift_num;
// for(int64 i = 0; i < file_node_size; ++i) {
// file_in.read(reinterpret_cast<char*>(&img_container[start_index + i]), sizeof(T));
// }
// file_in.close();
// }
//
// /* now read the last file */
// start_index = (int64)(file_loop) << file_node_shift_num;
// std::ostrstream strstream;
// strstream << data_path.generic_string() << "/" << file_loop << '\0';
// if(!bf::exists(bf::path(strstream.str()))) {
// cerr << "image data missing" << endl;
// return null_image;
// }
// ifstream file_in(strstream.str(), ios::out | ios::binary);
// if(!file_in.is_open()) {
// cerr << "open" << strstream.str() << " failure" << endl;
// return null_image;
// }
// for(int64 last_index = start_index; last_index < img_container.size(); ++last_index) {
// file_in.read(reinterpret_cast<char*>(&img_container[last_index]), sizeof(T));
// }
// file_in.close();
//
// return dst_image;
//}
#endif | [
"whiledoing@sina.com"
] | whiledoing@sina.com |
6130b31e7e0ec9ae51a0c5e9d6e4b1a22320039d | 02b715831737eb94df84910677f6917aa04fa312 | /EIN-SOF/DOMASNO/DOMASNO C++/OBLIK/troDimenzionalni.cpp | 38b9fa535221b9cd5524d2c86d62d31fe3906053 | [] | no_license | DoozyX/EIN-SOF | 05b433e178fbda6fb63e0d61387684158913de1d | 5de0bd42906f9878557d489b617824fe80c4b23b | refs/heads/master | 2021-01-01T18:25:14.240394 | 2017-11-18T12:54:16 | 2017-11-18T12:54:16 | 98,330,930 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | cpp | //programa troDimenzionalni.cpp
//deviniranje na metodi
#include <iostream>
using std::cout;
#include "troDimenzionalni.h"
TroDimenzionalni::TroDimenzionalni(double x,double y,double z):DvoDimenzionalni(x,y)
{
h=z;
}
double TroDimenzionalni::presmetajPlostina()
{
double pom,pom1;
pom=DvoDimenzionalni::presmetajPlostina();
pom1=2*pom+getA()*2*h+getB()*2*h;
return pom1;
}
double TroDimenzionalni::presmetajVolumen()
{
double pom;
pom=DvoDimenzionalni::presmetajPlostina()*h;
return pom;
}
void TroDimenzionalni::print()
{
DvoDimenzionalni::print();
cout<<"Visinata e: "<<h<<"\n";
}
| [
"slobodan.kletnikov@gmail.com"
] | slobodan.kletnikov@gmail.com |
74c55dfce4be27254ac35cafceb951c9708346f8 | f99c0194278639456604ebf76443b65bf1c6ed04 | /paymentchannel/include/paymentchannel/Commitment.hpp | e1d7c563cfe490394a46f0cc2b700c4d871b15fa | [] | no_license | RdeWilde/JoyStream | e4ed42ff61af1f348cb49469caa8e30ccf3f8a52 | 95c2b6fc50251fbe4730b19d47c18bec86e18bf4 | refs/heads/master | 2021-06-11T20:26:46.682624 | 2016-05-10T08:27:05 | 2016-05-10T08:27:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,636 | hpp | /**
* Copyright (C) JoyStream - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Bedeho Mender <bedeho.mender@gmail.com>, August 15 2015
*/
#ifndef PAYMENTCHANNEL_COMMITMENT_HPP
#define PAYMENTCHANNEL_COMMITMENT_HPP
#include <common/PublicKey.hpp>
namespace Coin {
class P2SHScriptPubKey;
class MultisigScriptPubKey;
class TxOut;
}
class Commitment
{
public:
// Default constructor
Commitment();
// Constructor based on members
Commitment(int64_t value, const Coin::PublicKey & firstPk, const Coin::PublicKey & secondPk);
// Copy constructor
Commitment(const Commitment& o);
// Assignement operator
Commitment & operator=(const Commitment & o);
// p2sh 2of2 multisig scriptPubKey controlling contract output
Coin::P2SHScriptPubKey contractOutputScriptPubKey() const;
// Generates contract output
Coin::TxOut contractOutput() const;
// 2o2 multisig scriptpubkey
Coin::MultisigScriptPubKey redeemScript() const;
// Getters and setters
int64_t value() const;
void setValue(int64_t value);
Coin::PublicKey firstPk() const;
void setFirstPk(const Coin::PublicKey & firstPk);
Coin::PublicKey secondPk() const;
void setSecondPk(const Coin::PublicKey & secondPk);
private:
// Funds allocated to output
int64_t _value;
// First public key controlling multisig output
Coin::PublicKey _firstPk;
// Second public key controlling multisig output
Coin::PublicKey _secondPk;
};
#endif // PAYMENTCHANNEL_COMMITMENT_HPP
| [
"bedeho.mender@gmail.com"
] | bedeho.mender@gmail.com |
faee043efffcd28847ea5d433bdd91e6452d1edb | 0233477eeb6d785b816ee017cf670e2830bdd209 | /SDK/SoT_BP_ipg_hair_05_Desc_classes.hpp | d63a95a7ae7acdde9d10a31695bf281f88394ce5 | [] | no_license | compy-art/SoT-SDK | a568d346de3771734d72463fc9ad159c1e1ad41f | 6eb86840a2147c657dcd7cff9af58b382e72c82a | refs/heads/master | 2020-04-17T02:33:02.207435 | 2019-01-13T20:55:42 | 2019-01-13T20:55:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | hpp | #pragma once
// Sea of Thieves (1.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_ipg_hair_05_Desc_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_ipg_hair_05_Desc.BP_ipg_hair_05_Desc_C
// 0x0000 (0x00E0 - 0x00E0)
class UBP_ipg_hair_05_Desc_C : public UClothingDesc
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass BP_ipg_hair_05_Desc.BP_ipg_hair_05_Desc_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
b612e83cb0cee3bbb91e018abc60dc12dc4dc46d | e66d115b1b53b5be0cc6a6a2233ffdb4c22096e0 | /Ogitor/qtOgitor/include/settingsdialog.hxx | 2ac8c73c4b40f0229225f7eb6c0d325d0ad95ffa | [
"MIT"
] | permissive | lockie/HiveGame | 565a6f46b214f7df345c25c0bc05ee5bd6699ece | bb1aa12561f1dfd956d78a53bfb7a746e119692a | refs/heads/master | 2021-06-11T20:56:21.872049 | 2016-12-18T11:28:33 | 2016-12-18T11:28:33 | 1,229,308 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,850 | hxx | /*/////////////////////////////////////////////////////////////////////////////////
/// An
/// ___ ____ ___ _____ ___ ____
/// / _ \ / ___|_ _|_ _/ _ \| _ \
/// | | | | | _ | | | || | | | |_) |
/// | |_| | |_| || | | || |_| | _ <
/// \___/ \____|___| |_| \___/|_| \_\
/// File
///
/// Copyright (c) 2008-2011 Ismail TARIM <ismail@royalspor.com> and the Ogitor Team
//
/// The MIT License
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////*/
#ifndef SETTINGSDIALOG_HXX
#define SETTINGSDIALOG_HXX
#include <QtGui/QDialog>
#include <QtGui/QWidget>
#include "OgitorsPrerequisites.h"
#include "ui_settingsdialog.h"
#include "colourpicker.hxx"
class SettingsDialog : public QDialog, public Ui::settingsdialog {
Q_OBJECT
public:
SettingsDialog(QWidget *parent, Ogitors::PROJECTOPTIONS *options);
virtual ~SettingsDialog();
void addResourceLocation(int loctype, QString path);
public Q_SLOTS:
void onAccept();
void browse();
void onAddDirectory();
void onAddDirectoryRecursive();
void onAddArchive();
void onRemoveEntry();
private:
Ogitors::PROJECTOPTIONS *mOptions;
std::vector<int> mResourceFileTypes;
ColourPickerWidget *mSelRectColourWidget;
ColourPickerWidget *mSelColourWidget;
ColourPickerWidget *mHighlightColourWidget;
ColourPickerWidget *mSelectHighlightColourWidget;
ColourPickerWidget *mGridColourWidget;
bool eventFilter ( QObject * watched, QEvent * e );
// Drag-and drop functions
void dragEnterEvent(QDragEnterEvent * e);
void dropEvent(QDropEvent * e);
static QStringList getFilenames(const QMimeData * data);
};
#endif // SETTINGSDIALOG_HXX
| [
"fake0mail0@gmail.com"
] | fake0mail0@gmail.com |
f3f67e5db33e87b03b0ce3aa1ba033ffa5db70bc | 90efdfa1f56e2082283e510c7aa9a77ceab8ce18 | /template/src/TemplateGame.h | 8c426edcee6f05323707188d4f260324a400fbe1 | [] | no_license | aurodev/GPlay3D | 451e2863d6ac3222762672d358eecd494d9cc272 | ad6b88dd22688e2b6e6e2fa02779daa0b5545592 | refs/heads/master | 2020-07-13T04:28:30.234238 | 2018-06-26T06:48:20 | 2018-06-26T06:48:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 877 | h | #ifndef TemplateGame_H_
#define TemplateGame_H_
#include "gplay3d.h"
using namespace gameplay;
/**
* Main game class.
*/
class TemplateGame: public Game
{
public:
/**
* Constructor.
*/
TemplateGame();
/**
* @see Game::keyEvent
*/
void keyEvent(Keyboard::KeyEvent evt, int key);
/**
* @see Game::touchEvent
*/
void touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex);
protected:
/**
* @see Game::initialize
*/
void initialize();
/**
* @see Game::finalize
*/
void finalize();
/**
* @see Game::update
*/
void update(float elapsedTime);
/**
* @see Game::render
*/
void render(float elapsedTime);
private:
/**
* Draws the scene each frame.
*/
bool drawScene(Node* node);
Scene* _scene;
};
#endif
| [
"fredakilla@gmail.com"
] | fredakilla@gmail.com |
f960a225f0bf911fb98ca368ad195675a34051e5 | 152c8ed80987ac2de10fe03fe6af283f1430d0be | /Classes/Tool.h | 75c5a069c124c72439d35fc22543b2ad190ade63 | [] | no_license | aababy/Begins_New | 2bae369a90f4d4e9f5bba1d2f3669a0eef22d4c5 | 9c3e09c5d38667c2fdc35f4ccf2aa3bbfd7ea627 | refs/heads/master | 2021-01-01T15:55:15.575484 | 2014-12-22T03:58:00 | 2014-12-22T03:58:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 851 | h | #pragma once
#include "IncludeForHeader.h"
#include "ui/UICheckBox.h"
Button * initButton(int iTag, Widget* root, Widget::ccWidgetTouchCallback callback);
ImageView * initImageView(int iTag, Widget* root);
CheckBox * initCheckBox(int iTag, Widget* root, const CheckBox::ccCheckBoxCallback& callback);
Layout * initRoot(const std::string& filename, Layer *layer);
Layout * initRootForCell(const std::string& filename, Layer *layer);
Layout * initLayout(int iTag, Widget* root, Widget::ccWidgetTouchCallback callback);
string itostr(int i);
string getString(char *sz);
Button* initUIButton(int tag, SEL_TouchEvent selector, Layout* root, Ref* target);
Time getCurrentTime();
Time str2MTime(const string &str);
Time str2MTimeForDB(const string &str);
string getShowTime(Time &mtime);
int cycleNum(bool bAdd, int iCount, int *idx);
| [
"jumpchess@163.com"
] | jumpchess@163.com |
ff30ab1177f96472963069ec3d2efaef5b5b6bd1 | 091afb7001e86146209397ea362da70ffd63a916 | /inst/include/boost/simd/constant/include/constants/five.hpp | a1ad45fe0bd224bc95be40398253f8f19297a570 | [] | no_license | RcppCore/RcppNT2 | f156b58c08863243f259d1e609c9a7a8cf669990 | cd7e548daa2d679b6ccebe19744b9a36f1e9139c | refs/heads/master | 2021-01-10T16:15:16.861239 | 2016-02-02T22:18:25 | 2016-02-02T22:18:25 | 50,460,545 | 15 | 1 | null | 2019-11-15T22:08:50 | 2016-01-26T21:29:34 | C++ | UTF-8 | C++ | false | false | 254 | hpp | #ifndef BOOST_SIMD_CONSTANT_INCLUDE_CONSTANTS_FIVE_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_INCLUDE_CONSTANTS_FIVE_HPP_INCLUDED
#include <boost/simd/constant/constants/five.hpp>
#include <boost/simd/constant/constants/simd/vmx/altivec/five.hpp>
#endif
| [
"kevinushey@gmail.com"
] | kevinushey@gmail.com |
34434c5c2c810bf1e750d30effd2a03e6ae7328b | d297a725b3d28ce67796552ddc7341b8793151b0 | /stereo_disparity/main.cpp | bd7e88a3c99d5d426f001a2fcaa3b84d52e06787 | [] | no_license | andrey-golubev/opencl-sandbox | d76a4f4391258ec302f72ae0b5ba0335de5b66ab | ef23dec4876c2365f92ce4896d7fc389ad7128b7 | refs/heads/master | 2020-12-19T19:02:15.420906 | 2020-04-15T11:11:04 | 2020-04-15T11:11:04 | 235,823,367 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,727 | cpp | #include <cstdint>
#include <iostream>
#include <map>
#include <random>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include "common/utils.hpp"
#include "stereo_disparity_cpp_inl.hpp"
#include "stereo_disparity_cpp_opt_inl.hpp"
#include "stereo_disparity_ocl_inl.hpp"
namespace {
void print_usage(const char* program_name) {
PRINTLN("Usage: " + std::string(program_name) +
" IMAGE_LEFT IMAGE_RIGHT [ALGO_VERSION] [MAX_DISPARITY]\n" +
" ALGO_VERSION:\n 0 - C++ basic\n 1 - C++ optimized\n 2 - OpenCL");
}
template<typename CharT, typename Traits = std::char_traits<CharT>>
std::vector<std::basic_string<CharT>> split(const std::basic_string<CharT>& src, CharT delimiter) {
std::vector<std::basic_string<CharT>> dst;
std::basic_istringstream<CharT> ss_src(src);
std::basic_string<CharT> tmp;
while (std::getline(ss_src, tmp, delimiter)) {
dst.push_back(tmp);
}
return dst;
}
enum AlgoType {
CPP_BASIC = 0,
CPP_OPT = 1,
OCL = 2,
};
std::string algo2str(int t) {
switch (t) {
case CPP_BASIC:
return "C++ basic";
case CPP_OPT:
return "C++ optimized";
case OCL:
return "OpenCL";
default:
throw std::runtime_error("Unknown algorithm version");
}
}
} // namespace
// debug controls
#define SHOW_WINDOW 0
#define RESIZE 0
int main(int argc, char* argv[]) {
if (argc < 3 || argc > 5) {
print_usage(argv[0]);
return 1;
}
// read input image
cv::Mat bgr_left = cv::imread(argv[1]);
cv::Mat bgr_right = cv::imread(argv[2]);
int algo_version = 0;
int max_disparity = 50;
// read disparity from user input if specified
if (argc > 3) {
if (argc >= 4) {
algo_version = std::stoi(argv[3]);
}
if (argc == 5) {
max_disparity = std::stoi(argv[4]);
}
}
// convert to grayscale
cv::Mat left;
cv::Mat right;
cv::cvtColor(bgr_left, left, cv::COLOR_BGR2GRAY);
cv::cvtColor(bgr_right, right, cv::COLOR_BGR2GRAY);
#if RESIZE
const auto input_size = left.size();
constexpr double scale = 0.5;
auto size = cv::Size(input_size.width * scale, input_size.height * scale);
cv::resize(left, left, size);
cv::resize(right, right, size);
#endif
// find disparity
cv::Mat map;
std::uint64_t musec = 0;
std::size_t iters = 1;
PRINTLN("Running " + algo2str(algo_version) + " version");
switch (algo_version) {
case CPP_BASIC: {
musec = measure(
iters,
[&]() { map = stereo_cpp_base::stereo_compute_disparity(left, right, max_disparity); },
false);
break;
}
case CPP_OPT: {
musec = measure(
iters,
[&]() { map = stereo_cpp_opt::stereo_compute_disparity(left, right, max_disparity); },
false);
break;
}
case OCL: {
musec = measure(
iters,
[&]() { map = stereo_ocl_base::stereo_compute_disparity(left, right, max_disparity); },
false);
break;
}
default:
throw std::runtime_error("Unknown algorithm version");
}
OUT << "Total time: " << (double(musec) / 1000 / 1000) << " sec" << std::endl;
OUT << "Avg time: " << (double(musec) / iters) / 1000 / 1000 << " sec" << std::endl;
#if SHOW_WINDOW
// show disparity map
cv::String win_name("Disparity Map");
cv::namedWindow(win_name, cv::WINDOW_NORMAL | cv::WINDOW_KEEPRATIO);
cv::resizeWindow(win_name, cv::Size(640 * 2, 480 * 2));
cv::imshow(win_name, map);
while (cv::waitKey(1) != 27) {
};
#endif
return 0;
}
| [
"andpgolubev@gmail.com"
] | andpgolubev@gmail.com |
9ce6b3907dcfec4a8f95f860990c41218de9b1e2 | 7f940f1a54ab400d98d0291248427114acada9ee | /concepts/threads/futures.cpp | 9791c67166ebc5f8496a150451b958ad77788c3c | [] | no_license | anirudhaps/Cplusplus | 7d01e5deb1e0d4dda37257cd8831f3a89f7049b5 | ac180ffe894a39443d6bb6438fda9ff308701e00 | refs/heads/master | 2022-09-29T04:30:40.181243 | 2022-09-13T16:51:02 | 2022-09-13T16:51:02 | 86,616,344 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,108 | cpp | #include <future>
#include <iostream>
// needed for using 300ms as arg in sleep_for
using namespace std::chrono_literals;
// This is the task/callable that will be executed in a separate thread
int operation(int count) {
int sum{};
for (int i = 0; i < count; ++i) {
sum += i;
std::cout << '.';
std::this_thread::sleep_for(300ms);
}
std::cout << "\n";
// This sum is the shared state between this thread and main thread and this
// will be available in the std::future as result when this task returns.
return sum;
}
int main() {
// Because the callable operation returns an int, the template type arg in the
// std::future<> should be int. Here, 10 will be the argument passed to
// operation().
// It seems the std::async is by default using std::launch::async as lanch
// policy. We can explicitly mention it as shown below:
// std::future<int> result = std::async(std::launch::async, operation, 10);
// To run operation() synchronously, use deferred launch policy. In this case,
// operation() task will be executed when main thread tries to get the shared
// state. i.e. when result.get() is invoked. This is as good as calling
// operation() directly in place of result.get().
std::future<int> result = std::async(std::launch::deferred, operation, 10);
// std::future<int> result = std::async(operation, 10);
std::this_thread::sleep_for(1s);
std::cout << "Main thread continues...\n";
if (result.valid()) {
// The shared state will become available via this get() call and until this
// become available, this get() call will block the main thread.
// Important note: once you call get() on the future, the shared state is
// destroyed and you cannot get it again. Also, the future (result here)
// becomes invalid. The .valid() call is used to check if a future is valid
// or not. If it is valid, then only we ar calling the get() it to get the
// shared state.
auto sum = result.get();
std::cout << "Sum from future: " << sum << "\n";
}
return 0;
} | [
"ps.anirudha@gmail.com"
] | ps.anirudha@gmail.com |
ff3e009725d61538b5c086dcbaa1e6fd7436e790 | 8a50a32e7d34df7b6430919bcdd7b971d3baac64 | /v0.1.1/WPJInputUtil.cpp | fd723e353b82587003e7022c551484de778355ba | [] | no_license | woudX/WPJ | 6f0ea0705f38245c9741e7cbde5846b3b2758519 | ec670b8d1f2d42b2723e1463a50a00b887b4a80e | refs/heads/master | 2016-09-16T02:05:34.377895 | 2014-08-14T05:08:24 | 2014-08-14T05:08:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,659 | cpp | #include "WPJInputUtil.h"
USING_NS_WPJ
WPJInputUtil *WPJInputUtil::m_pInst = 0;
WPJInputUtil::WPJInputUtil():m_bFirst(true)
{
memset(m_arKeyPressed, 0, sizeof(m_arKeyPressed));
}
WPJInputUtil *WPJInputUtil::GetSharedInst()
{
if (m_pInst == 0)
m_pInst = new WPJInputUtil();
return m_pInst;
}
WPJInputUtil *WPJInputUtil::RegistDisplay(ALLEGRO_DISPLAY *pDisplay)
{
m_pDisplay = pDisplay;
return this;
}
WPJInputUtil *WPJInputUtil::UnregistDisplay()
{
m_pDisplay = NULL;
return this;
}
bool WPJInputUtil::Init()
{
int bRet;
// init input hardware driver
bRet = al_is_keyboard_installed() && al_is_mouse_installed();
// init event_queue
m_pEventQueue = al_create_event_queue();
if (bRet && m_pEventQueue)
{
al_register_event_source(m_pEventQueue, al_get_keyboard_event_source());
al_register_event_source(m_pEventQueue, al_get_mouse_event_source());
al_register_event_source(m_pEventQueue, al_get_display_event_source(m_pDisplay));
}
return bRet;
}
int WPJInputUtil::PeekEvent(ALLEGRO_EVENT &e)
{
return al_wait_for_event_timed(m_pEventQueue, &e, 0.001f);
}
void WPJInputUtil::AnalysisEvent(ALLEGRO_EVENT &e)
{
// key pressed
if (e.type == ALLEGRO_EVENT_KEY_DOWN)
m_arKeyPressed[e.keyboard.keycode] = true;
else if (e.type == ALLEGRO_EVENT_KEY_UP)
m_arKeyPressed[e.keyboard.keycode] = false;
// event trigged
if (e.type == ALLEGRO_EVENT_KEY_DOWN
|| e.type == ALLEGRO_EVENT_KEY_UP
|| e.type == ALLEGRO_EVENT_KEY_CHAR)
{
ALLEGRO_EVENT copyE = e;
WPJEvent *pEvent = new WPJEvent(copyE, e.type);
m_lTriggedEvents.push_back(pEvent);
}
}
bool WPJInputUtil::IsKeyPressed(int keyID)
{
if (keyID < MAX_INPUT_SIZE)
return m_arKeyPressed[keyID];
else
{
//WPJLOG("[%s] There is no keyID = %ud, please change MAX_INPUT_SIZE\n", _D_NOW_TIME__, keyID);
ASSERT(false);
return false;
}
}
WPJEvent *WPJInputUtil::NextTriggedEvent()
{
WPJEvent *bRet = NULL;
if (m_lTriggedEvents.size() > 0)
{
if (m_bFirst)
{
m_itNextEvent = m_lTriggedEvents.begin();
m_bFirst = false;
}
else
m_itNextEvent++;
if (m_itNextEvent != m_lTriggedEvents.end())
bRet = pp(m_itNextEvent);
}
return bRet;
}
void WPJInputUtil::ClearAllTriggedEvents()
{
foreach_in_list_auto(WPJEvent*, itor, m_lTriggedEvents)
ptr_safe_del(pp(itor));
m_lTriggedEvents.clear();
m_bFirst = true;
}
WPJInputUtil::~WPJInputUtil()
{
ClearAllTriggedEvents();
if (al_is_keyboard_installed())
al_unregister_event_source(m_pEventQueue, al_get_keyboard_event_source());
if (al_is_mouse_installed())
al_unregister_event_source(m_pEventQueue, al_get_mouse_event_source());
al_destroy_event_queue(m_pEventQueue);
} | [
"jccgls001@126.com"
] | jccgls001@126.com |
071179dcc13fa3cc32aa68486eaed86d12070d4c | abbcbf44964d4557cfcab0fe1056bdcca4e7e60a | /VectorList/src/WordMap.cpp | 063f7b812628b5e8dad177bf1d679291e3bdfb38 | [] | no_license | charit93/Data-Structures-CMPE-180-92 | b4fdc6cda32330b7d199d1b7f52dcf9517fbcdc8 | 8937f71a1e6df21a4e66c18702f5404591c1155a | refs/heads/master | 2020-03-11T12:11:10.374829 | 2018-09-04T18:31:58 | 2018-09-04T18:31:58 | 129,990,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,357 | cpp | #include <map>
#include <string>
#include<iostream>
#include "WordMap.h"
using namespace std;
WordMap::WordMap() {}
WordMap::~WordMap() {}
map<string, Word>& WordMap::get_data() { return data; }
int WordMap::get_count(const string text) const
{
/***** Complete this function. *****/
map<string, Word>::const_iterator it = data.find(text);
return it != data.end() ? (it->second).get_count() : -1;
}
void WordMap::insert(const string text)
{
/***** Complete this function. *****/
steady_clock::time_point start = steady_clock::now(); // start timer
map<string, Word>::iterator it = data.find(text); // word in the map
if (it == data.end()) // Entering the word
{
data[text] = Word(text);
}
else
{
(it->second).increment_count(); // increment word count
}
steady_clock::time_point end = steady_clock::now(); // count end time
increment_elapsed_time(start,end); // total elapsed time
}
map<string, Word>::iterator WordMap::search(const string text)
{
/***** Complete this function. *****/
steady_clock::time_point start = steady_clock().now(); // start timer
map<string, Word>::iterator it=data.find(text); // word in the map
steady_clock::time_point end_time = steady_clock().now(); // count end time
increment_elapsed_time(start,end_time); // total elapsed time
return it;
}
int WordMap::size(){
return data.size();
}
| [
"charitupadhyay@gmail.com"
] | charitupadhyay@gmail.com |
cc6c6bada59d68862902f283830b12380c63e91c | c36761457f62066159fdb4409f7787ee0d9b43b0 | /IrisLangLibrary/src/IrisLangLibrary.cpp | 73bf266b4a2a4eabeacb92ded1ad5956700e3c4f | [
"Apache-2.0"
] | permissive | RedFog/Iris-Language | d8ee855da6a748cb7a5753bc56a68b5834ce18a1 | cde174f3e17b9747b7876487bfa4ab81fcfc5952 | refs/heads/master | 2020-04-06T06:41:21.242453 | 2016-03-14T16:41:55 | 2016-03-14T16:51:08 | 54,444,300 | 1 | 0 | null | 2016-03-22T04:08:27 | 2016-03-22T04:08:26 | null | GB18030 | C++ | false | false | 12,959 | cpp | // IrisLangLibrary.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "IrisLangLibrary.h"
#include "IrisDevelopUtil.h"
#include "IrisInterpreter/IrisStructure/IrisClass.h"
#include "IrisInterpreter/IrisStructure/IrisModule.h"
#include "IrisInterpreter.h"
#include "IrisInterpreter/IrisNativeClasses/IrisInteger.h"
#include "IrisInterpreter/IrisNativeClasses/IrisFloat.h"
#include "IrisInterpreter/IrisNativeClasses/IrisString.h"
#include "IrisInterpreter/IrisNativeClasses/IrisUniqueString.h"
#include "IrisInterpreter/IrisNativeModules/IrisGC.H"
#include "IrisFatalErrorHandler.h"
#include <string>
using namespace std;
IrisDev_FatalErrorMessageFunction g_pfFatalErrorMessageFunction = nullptr;
IrisDev_ExitConditionFunction g_pfExitConditionFunction = nullptr;
IRISLANGLIBRARY_API bool IrisDev_CheckClass(const IrisValue & ivValue, const char* strClassName)
{
auto pClass = ((IrisValue&)ivValue).GetIrisObject()->GetClass();
auto& strName = pClass->GetInternClass()->GetClassName();
return strName == strClassName;
}
IRISLANGLIBRARY_API void IrisDev_GroanIrregularWithString(const char* strIrregularString)
{
IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter();
IrisValue ivValue = IrisDev_CreateStringInstanceByInstantValue(strIrregularString);
pInterpreter->RegistIrregular(ivValue);
}
IRISLANGLIBRARY_API int IrisDev_GetInt(const IrisValue & ivValue)
{
return IrisInteger::GetIntData((IrisValue&)ivValue);
}
IRISLANGLIBRARY_API double IrisDev_GetFloat(const IrisValue & ivValue)
{
return IrisFloat::GetFloatData((IrisValue&)ivValue);
}
IRISLANGLIBRARY_API const char* IrisDev_GetString(const IrisValue & ivValue)
{
if (IrisDev_CheckClass(ivValue, "String")) {
return IrisString::GetString((IrisValue&)ivValue).c_str();
}
else {
return IrisUniqueString::GetString((IrisValue&)ivValue).c_str();
}
}
IRISLANGLIBRARY_API IrisValue IrisDev_CallMethod(const IrisValue & ivObj, IIrisValues * pParameters, const char* strMethodName)
{
return static_cast<IrisObject*>(((IrisValue&)ivObj).GetIrisObject())->CallInstanceFunction(strMethodName, nullptr, pParameters, CallerSide::Outside);
}
IRISLANGLIBRARY_API IIrisClass * IrisDev_GetClass(const char* strClassPathName)
{
return IrisInterpreter::CurrentInterpreter()->GetIrisClass(strClassPathName)->GetExternClass();
}
IRISLANGLIBRARY_API IIrisModule * IrisDev_GetModule(const char * strClassPathName)
{
return IrisInterpreter::CurrentInterpreter()->GetIrisModule(strClassPathName)->GetExternModule();
}
IRISLANGLIBRARY_API IIrisInterface * IrisDev_GetInterface(const char * strClassPathName)
{
return IrisInterpreter::CurrentInterpreter()->GetIrisInterface(strClassPathName)->GetExternInterface();
}
IRISLANGLIBRARY_API const IrisValue & IrisDev_Nil()
{
return IrisInterpreter::CurrentInterpreter()->Nil();
}
IRISLANGLIBRARY_API const IrisValue & IrisDev_False()
{
return IrisInterpreter::CurrentInterpreter()->False();
}
IRISLANGLIBRARY_API const IrisValue & IrisDev_True()
{
return IrisInterpreter::CurrentInterpreter()->True();
}
IRISLANGLIBRARY_API bool IrisDev_RegistClass(const char * szPath, IIrisClass * pClass)
{
return IrisInterpreter::CurrentInterpreter()->RegistClass(szPath, pClass);
}
IRISLANGLIBRARY_API bool IrisDev_RegistModule(const char * szPath, IIrisModule * pModule)
{
return IrisInterpreter::CurrentInterpreter()->RegistModule(szPath, pModule);
}
IRISLANGLIBRARY_API bool IrisDev_RegistInterface(const char * szPath, IIrisInterface * pInterface)
{
return IrisInterpreter::CurrentInterpreter()->RegistInterface(szPath, pInterface);
}
IRISLANGLIBRARY_API void IrisDev_AddInstanceMethod(IIrisClass * pClass, const char * szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter)
{
pClass->GetInternClass()->AddInstanceMethod(new IrisMethod(szMethodName, pfFunction, nParamCount, bIsWithVariableParameter));
}
IRISLANGLIBRARY_API void IrisDev_AddClassMethod(IIrisClass * pClass, const char * szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter)
{
pClass->GetInternClass()->AddClassMethod(new IrisMethod(szMethodName, pfFunction, nParamCount, bIsWithVariableParameter));
}
IRISLANGLIBRARY_API void IrisDev_AddInstanceMethod(IIrisModule * pModule, const char * szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter)
{
pModule->GetInternModule()->AddInstanceMethod(new IrisMethod(szMethodName, pfFunction, nParamCount, bIsWithVariableParameter));
}
IRISLANGLIBRARY_API void IrisDev_AddClassMethod(IIrisModule * pModule, const char * szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter)
{
pModule->GetInternModule()->AddClassMethod(new IrisMethod(szMethodName, pfFunction, nParamCount, bIsWithVariableParameter));
}
IRISLANGLIBRARY_API void IrisDev_AddGetter(IIrisClass * pClass, const char * szInstanceVariableName, IrisNativeFunction pfFunction)
{
pClass->GetInternClass()->AddGetter(szInstanceVariableName, pfFunction);
}
IRISLANGLIBRARY_API void IrisDev_AddSetter(IIrisClass* pClass, const char * szInstanceVariableName, IrisNativeFunction pfFunction)
{
pClass->GetInternClass()->AddSetter(szInstanceVariableName, pfFunction);
}
IRISLANGLIBRARY_API void IrisDev_AddConstance(IIrisClass * pClass, const char * szConstanceName, const IrisValue & ivValue)
{
pClass->GetInternClass()->AddConstance(szConstanceName, ivValue);
}
IRISLANGLIBRARY_API void IrisDev_AddConstance(IIrisModule * pModule, const char * szConstanceName, const IrisValue & ivValue)
{
pModule->GetInternModule()->AddConstance(szConstanceName, ivValue);
}
IRISLANGLIBRARY_API void IrisDev_AddClassVariable(IIrisClass * pClass, const char * szVariableName, const IrisValue & ivValue)
{
pClass->GetInternClass()->AddClassVariable(szVariableName, ivValue);
}
IRISLANGLIBRARY_API void IrisDev_AddClassVariable(IIrisModule * pClass, const char * szVariableName, const IrisValue & ivValue)
{
pClass->GetInternModule()->AddClassVariable(szVariableName, ivValue);
}
IRISLANGLIBRARY_API void IrisDev_AddModule(IIrisClass * pClass, IIrisModule * pTargetModule)
{
pClass->GetInternClass()->AddModule(pTargetModule->GetInternModule());
}
IRISLANGLIBRARY_API void IrisDev_AddModule(IIrisModule * pModule, IIrisModule * pTargetModule)
{
pModule->GetInternModule()->AddModule(pTargetModule->GetInternModule());
}
IRISLANGLIBRARY_API IrisValue IrisDev_CreateNormalInstance(IIrisClass * pClass, IIrisValues * ivsParams, IIrisContextEnvironment * pContexEnvironment)
{
return pClass->GetInternClass()->CreateInstance(ivsParams, pContexEnvironment);
}
IRISLANGLIBRARY_API IrisValue IrisDev_CreateStringInstanceByInstantValue(const char * szString)
{
auto pClass = IrisDev_GetClass("String");
IrisValue ivValue;
IrisObject* pObject = new IrisObject();
pObject->SetClass(pClass);
IrisStringTag* pString = new IrisStringTag(szString);
pObject->SetNativeObject(pString);
ivValue.SetIrisObject(pObject);
IrisGC::CurrentGC()->AddSize(sizeof(IrisObject) + pObject->GetClass()->GetTrustteeSize(pObject->GetNativeObject()));
IrisGC::CurrentGC()->Start();
// 将新对象保存到堆里
IrisInterpreter::CurrentInterpreter()->AddNewInstanceToHeap(ivValue);
return ivValue;
}
IRISLANGLIBRARY_API IrisValue IrisDev_CreateFloatInstanceByInstantValue(double dFloat)
{
auto pClass = IrisDev_GetClass("Float");
IrisValue ivValue;
IrisObject* pObject = new IrisObject();
pObject->SetClass(pClass);
IrisFloatTag* pFloat = new IrisFloatTag(dFloat);
pObject->SetNativeObject(pFloat);
ivValue.SetIrisObject(pObject);
IrisGC::CurrentGC()->AddSize(sizeof(IrisObject) + pObject->GetClass()->GetTrustteeSize(pObject->GetNativeObject()));
IrisGC::CurrentGC()->Start();
// 将新对象保存到堆里
IrisInterpreter::CurrentInterpreter()->AddNewInstanceToHeap(ivValue);
return ivValue;
}
IRISLANGLIBRARY_API IrisValue IrisDev_CreateIntegerInstanceByInstantValue(int nInteger)
{
auto pClass = IrisDev_GetClass("Integer");
IrisValue ivValue;
IrisObject* pObject = new IrisObject();
pObject->SetClass(pClass);
IrisIntegerTag* pInteger = new IrisIntegerTag(nInteger);
pObject->SetNativeObject(pInteger);
ivValue.SetIrisObject(pObject);
IrisGC::CurrentGC()->AddSize(sizeof(IrisObject) + pObject->GetClass()->GetTrustteeSize(pObject->GetNativeObject()));
IrisGC::CurrentGC()->Start();
// 将新对象保存到堆里
IrisInterpreter::CurrentInterpreter()->AddNewInstanceToHeap(ivValue);
return ivValue;
}
IRISLANGLIBRARY_API IrisValue IrisDev_CreateUniqueStringInstanceByUniqueIndex(size_t nIndex)
{
IrisValue ivValue;
bool bResult = false;
ivValue = IrisUniqueString::GetUniqueString(nIndex, bResult);
if (bResult) {
return ivValue;
}
auto pClass = IrisDev_GetClass("UniqueString");
IrisObject* pObject = new IrisObject();
pObject->SetClass(pClass);
pObject->SetPermanent(true);
IrisUniqueStringTag* pString = new IrisUniqueStringTag(IrisCompiler::CurrentCompiler()->GetUniqueString(nIndex, IrisCompiler::CurrentCompiler()->GetCurrentFileIndex()));
pObject->SetNativeObject(pString);
ivValue.SetIrisObject(pObject);
IrisGC::CurrentGC()->AddSize(sizeof(IrisObject) + pObject->GetClass()->GetTrustteeSize(pObject->GetNativeObject()));
IrisGC::CurrentGC()->Start();
// 将新对象保存到堆里
IrisInterpreter::CurrentInterpreter()->AddNewInstanceToHeap(ivValue);
IrisUniqueString::AddUniqueString(nIndex, ivValue);
return ivValue;
}
IRISLANGLIBRARY_API void IrisDev_SetObjectInstanceVariable(IrisValue & ivObj, char * szInstanceVariableName, const IrisValue & ivValue)
{
bool bResult = false;
auto& ivResult = ivObj.GetIrisObject()->GetInstanceValue(szInstanceVariableName, bResult);
if (bResult) {
((IrisValue&)ivResult).SetIrisObject(ivResult.GetIrisObject());
}
else {
ivObj.GetIrisObject()->AddInstanceValue(szInstanceVariableName, ivValue);
}
}
IRISLANGLIBRARY_API IrisValue IrisDev_GetObjectInstanceVariable(IrisValue & ivObj, char * szInstanceVariableName)
{
bool bResult = false;
auto& ivResult = ivObj.GetIrisObject()->GetInstanceValue(szInstanceVariableName, bResult);
return ivResult;
}
IRISLANGLIBRARY_API bool IrisDev_IrregularHappened()
{
return IrisInterpreter::CurrentInterpreter()->IrregularHappened();
}
IRISLANGLIBRARY_API bool IrisDev_FatalErrorHappened()
{
return IrisInterpreter::CurrentInterpreter()->FatalErrorHappened();
}
void _InternFatalErrorMessageFunction(const string& pMessage) {
g_pfFatalErrorMessageFunction((char*)pMessage.c_str());
}
bool _InternExitConditionFunction() {
return g_pfExitConditionFunction() ? true : false;
}
IRISLANGLIBRARY_API bool IR_Initialize(PIrisInitializeStruct pInitializeStruct)
{
IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler();
IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter();
g_pfExitConditionFunction = pInitializeStruct->m_pfExitConditionFunction;
g_pfFatalErrorMessageFunction = pInitializeStruct->m_pfFatalErrorMessageFunction;
IrisFatalErrorHandler::CurrentFatalHandler()->SetFatalErrorMessageFuncton(_InternFatalErrorMessageFunction);
pInterpreter->SetExitConditionFunction(_InternExitConditionFunction);
return true;
}
IRISLANGLIBRARY_API bool IR_Run()
{
IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler();
IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter();
pInterpreter->SetCompiler(pCompiler);
// Run
IrisGC::CurrentGC()->SetGCFlag(false);
if (!pInterpreter->Initialize()) {
return false;
}
IrisGC::CurrentGC()->ResetNextThreshold();
IrisGC::CurrentGC()->SetGCFlag(true);
if (!pInterpreter->Run()) {
return false;
}
return true;
}
IRISLANGLIBRARY_API bool IR_ShutDown()
{
IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter();
return pInterpreter->ShutDown();
}
IRISLANGLIBRARY_API bool IR_LoadScriptFromPath(char * pScriptFilePath)
{
string strOrgFileName(pScriptFilePath);
string strDestFileName;
auto nPos = strOrgFileName.find_last_of(".");
if (nPos != std::string::npos) {
strDestFileName.assign(strOrgFileName, 0, nPos);
}
strDestFileName += ".irc";
IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler();
pCompiler->LoadScript(pScriptFilePath);
bool bCompileResult = pCompiler->Generate();
if (!bCompileResult) {
remove(strDestFileName.c_str());
}
return bCompileResult;
}
IRISLANGLIBRARY_API bool IR_LoadScriptFromVirtualPathAndText(char* pPath, char * pScriptText)
{
string strDestFileName(pPath);
strDestFileName += ".irc";
IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler();
pCompiler->LoadScriptFromVirtualPathAndText(pPath, pScriptText);
bool bCompileResult = pCompiler->Generate();
if (!bCompileResult) {
remove(strDestFileName.c_str());
}
return bCompileResult;
}
IRISLANGLIBRARY_API bool IR_LoadExtention(char * pExtentionPath)
{
IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter();
return pInterpreter->LoadExtension(pExtentionPath);
} | [
"a1026121287@hotmail.com"
] | a1026121287@hotmail.com |
f6dbc7835f49e3975e7d47d4ff8d4df76bb2d393 | 490ec0d2c4d0ae5d54095c71e90d99bbc87049b8 | /ECE551-cpp/mp_miniproject/My_project/source/parsing.cpp | f069043794810b4bcd7630229a24fde35f4e4d7b | [
"MIT"
] | permissive | sicongzhao/cht_Duke_courses | b8c1f03c2fda05b5e73552e6bdb7f3c323810620 | d889e85e677f419c67c12e78143f3e8143457944 | refs/heads/master | 2022-01-06T23:18:36.962017 | 2019-06-12T20:33:33 | 2019-06-12T20:33:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,592 | cpp | #define MAXFLAG 1
#define MINFLAG -1
#include "parsing.h"
#include "helpers.h"
/*************************************************
Function: parsing
Description: to wrap-up the parsers for each step
Calls:
Called By: numeric.cpp/main
Input: 1.read-in file content 2.mapped-function pairs 3.all valid commands.
Return: void
Others:
*************************************************/
std::string check_command(std::string &input, const std::vector<std::string> &command_list) {
unsigned i = 0;
std::string::iterator it = input.begin();
std::string::iterator it_first = it;
while(i < command_list.size()) {
if(input.find(command_list[i]) != std::string::npos) {
// to check if there is something like "abcdefinexyz and eliminate it"
std::string temp_define_string = get_next_valid_str(it);
// remove spaces
delete_spaces_and_tabs_on_head_and_tail(temp_define_string);
if(temp_define_string.compare(command_list[i]) != 0) {
std::stringstream err_msg1;
err_msg1 << "Error: In input: >> " << input << " << have strange " << command_list[i] << "!";
throw err_msg1.str();
}
std::cout << "Try to define input: >> " << input << " <<." << std::endl;
input.erase(it_first, it);
return command_list[i];
}
i++;
}
if(i == command_list.size()) {
std::stringstream err_msg2;
err_msg2 << "Error: In input: >> " << input << " << command not found!" << std::endl;
throw err_msg2.str();
}
return NULL;
}
void parsing(const std::string &input, std::map<std::string, function*> &function_map, const std::vector<std::string> &command_list) {
std::string temp_compare;
std::string temp_input;
temp_input = input;
try {
temp_compare = check_command(temp_input, command_list);
}
catch(std::string err_msg) {
std::cerr << err_msg << std::endl;
return;
}
std::cout << "Command is: >> " << temp_compare << " <<." << std::endl;
if(!temp_compare.compare(0, 6, "define")) {
parsing_define(temp_input, function_map);
}
else if(!temp_compare.compare(0, 8, "evaluate")) {
parsing_eval(temp_input, function_map);
}
else if(!temp_compare.compare(0, 6, "numint")) {
parsing_numint(temp_input, function_map);
}
else if(!temp_compare.compare(0, 5, "mcint")) {
parsing_mcint(temp_input, function_map);
}
else if(!temp_compare.compare(0, 3, "max")) {
parsing_gradient(temp_input, function_map, MAXFLAG);
}
else if(!temp_compare.compare(0, 3, "min")) {
parsing_gradient(temp_input, function_map, MINFLAG);
}
else {
std::cerr << "Unknown command: can only take in 6 pre-defined types of commands." << std::endl;
}
} | [
"cht@bupt.edu.cn"
] | cht@bupt.edu.cn |
9bb2695c911ba2c39b5ab4b73de7d9ff066d43f7 | 7e00a527a91a4bd2a60c7f1f0ae339730daa7ad1 | /src/Statistics.cpp | c5470a7351ab753d606a98975d7272c7a0b3416e | [] | no_license | tzavellas/ObserverPattern | 4a12a99c8c2a0b2abc4f5f01580bc9dda699fc40 | 6d95db6c89812062500ff62ccd6ff918d51835c9 | refs/heads/master | 2023-01-20T18:42:08.244843 | 2020-11-29T17:16:22 | 2020-11-29T17:16:22 | 316,933,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 738 | cpp | #include "Statistics.hpp"
#include <algorithm>
Statistics::Statistics(const float& value) : m_MinValue{value}, m_MaxValue{value}, m_ValueSum{value}, m_Count{ (value != 0.0) ? 1u : 0u}
{
// nothing to do
}
void Statistics::update(const float& newValue)
{
if (m_Count > 0)
{
m_MinValue = std::min(m_MinValue, newValue);
m_MaxValue = std::max(m_MaxValue, newValue);
}
else
{
m_MinValue = newValue;
m_MaxValue = newValue;
}
m_ValueSum += newValue;
m_Count++;
}
float Statistics::getMin() const
{
return m_MinValue;
}
float Statistics::getMax() const
{
return m_MaxValue;
}
float Statistics::getAverage() const
{
return m_ValueSum/m_Count;
} | [
"tzavellas@gmail.com"
] | tzavellas@gmail.com |
4145b1d07620be6a4bf337206b5c03f9d5bc4913 | 84257c31661e43bc54de8ea33128cd4967ecf08f | /ppc_85xx/usr/include/c++/4.2.2/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.h | 421ce0e9b7be5f9b275a3097407a7fcf48d98d97 | [] | no_license | nateurope/eldk | 9c334a64d1231364980cbd7bd021d269d7058240 | 8895f914d192b83ab204ca9e62b61c3ce30bb212 | refs/heads/master | 2022-11-15T01:29:01.991476 | 2020-07-10T14:31:34 | 2020-07-10T14:31:34 | 278,655,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,232 | h | // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __gnu_javax_crypto_sasl_crammd5_CramMD5AuthInfoProvider__
#define __gnu_javax_crypto_sasl_crammd5_CramMD5AuthInfoProvider__
#pragma interface
#include <java/lang/Object.h>
extern "Java"
{
namespace gnu
{
namespace javax
{
namespace crypto
{
namespace sasl
{
namespace crammd5
{
class CramMD5AuthInfoProvider;
class PasswordFile;
}
}
}
}
}
}
class gnu::javax::crypto::sasl::crammd5::CramMD5AuthInfoProvider : public ::java::lang::Object
{
public:
virtual void activate (::java::util::Map *);
virtual void passivate ();
virtual jboolean contains (::java::lang::String *);
virtual ::java::util::Map *lookup (::java::util::Map *);
virtual void update (::java::util::Map *);
virtual ::java::util::Map *getConfiguration (::java::lang::String *);
CramMD5AuthInfoProvider ();
private:
::gnu::javax::crypto::sasl::crammd5::PasswordFile * __attribute__((aligned(__alignof__( ::java::lang::Object )))) passwordFile;
public:
static ::java::lang::Class class$;
};
#endif /* __gnu_javax_crypto_sasl_crammd5_CramMD5AuthInfoProvider__ */
| [
"Andre.Mueller@nateurope.com"
] | Andre.Mueller@nateurope.com |
dff29843ca798cef5c05755a5ffe7bf01763b79b | 0509e367ee369133f0c57f2cbd6cb6fd959da1d5 | /chapter7/rei7.3_1.cpp | da2190f58aff74d78efa2500b01187864305d86f | [] | no_license | Hiroaki-K4/cpp_learn | 5a1e6916d504027c18c64a16c353ee72429ed383 | 69d38f317f9c144b4e092361936d61b62d3bed3b | refs/heads/main | 2023-02-25T12:40:56.497944 | 2021-01-30T13:27:00 | 2021-01-30T13:27:00 | 317,693,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | #include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
using namespace std;
class base {
public:
base() { cout << "baseクラスのコンストラクタ呼び出し" << endl; }
~base() { cout << "baseクラスのデストラクタ呼び出し" << endl; }
};
class derived : public base {
public:
derived() { cout << "derivedクラスのコンストラクタ呼び出し" << endl; }
~derived() { cout << "derivedクラスのデストラクタ呼び出し" << endl; }
};
int main()
{
derived o;
return 0;
} | [
"49no19@gmail.com"
] | 49no19@gmail.com |
f2709ed6b1b5a63738c24e1b6950c1054029c676 | b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1 | /tensorflow/compiler/xla/service/gpu/for_thunk.cc | 7ccfcf3bd6363e6a66b4b3e05f1a0a47a689b5bb | [
"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 | 2,461 | 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/gpu/for_thunk.h"
#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/service/gpu/hlo_execution_profiler.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"
namespace xla {
namespace gpu {
ForThunk::ForThunk(const int64 loop_limit,
std::unique_ptr<ThunkSequence> body_thunk_sequence,
const HloInstruction* hlo)
: Thunk(Kind::kWhile, hlo),
loop_limit_(loop_limit),
body_thunk_sequence_(absl::make_unique<SequentialThunk>(
// Pass nullptr as the HloInstruction* to the body_thunk_sequence_
// constructor because this SequentialThunk is logically "part of"
// this ForThunk, and shouldn't be profiled separately from it.
std::move(*body_thunk_sequence), nullptr)) {}
Status ForThunk::Initialize(const GpuExecutable& executable,
se::StreamExecutor* executor) {
TF_RETURN_IF_ERROR(body_thunk_sequence_->Initialize(executable, executor));
return Status::OK();
}
Status ForThunk::ExecuteOnStream(const ExecuteParams& params) {
VLOG(2) << "Executing ForThunk with " << loop_limit_ << " iters for "
<< (hlo_instruction() ? hlo_instruction()->ToString() : "<null>");
auto op_profiler =
params.profiler->MakeScopedInstructionProfiler(hlo_instruction());
for (int64 i = 0; i < loop_limit_; ++i) {
params.profiler->StartHloComputation();
// Invoke loop body thunk sequence.
TF_RETURN_IF_ERROR(body_thunk_sequence_->ExecuteOnStream(params));
params.profiler->FinishHloComputation(hlo_instruction()->while_body());
}
return Status::OK();
}
} // namespace gpu
} // namespace xla
| [
"v-grniki@microsoft.com"
] | v-grniki@microsoft.com |
693f0e9f11914c5ef612b791f053362cad11fa97 | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/chrome/browser/android/offline_pages/offline_page_tab_helper.h | 22ff4a148d1db2f201c57e451d954748580ddd62 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 4,589 | h | // 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.
#ifndef CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINE_PAGE_TAB_HELPER_H_
#define CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINE_PAGE_TAB_HELPER_H_
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "components/offline_pages/offline_page_types.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "url/gurl.h"
namespace content {
class WebContents;
}
namespace offline_pages {
struct OfflinePageItem;
// Per-tab class to manage switch between online version and offline version.
class OfflinePageTabHelper :
public content::WebContentsObserver,
public content::WebContentsUserData<OfflinePageTabHelper> {
public:
// Delegate that is used to better handle external dependencies.
// Default implementation is in .cc file, while tests provide an override.
class Delegate {
public:
virtual ~Delegate() {}
virtual bool GetTabId(content::WebContents* web_contents,
std::string* tab_id) const = 0;
};
// This enum is used for UMA reporting. It contains all possible outcomes of
// redirect intent and result. Generally one of these outcomes will happen.
// The fringe errors (like no OfflinePageModel, etc.) are not reported due
// to their low probability.
// NOTE: because this is used for UMA reporting, these values should not be
// changed or reused; new values should be ended immediately before the MAX
// value. Make sure to update the histogram enum
// (OfflinePagesRedirectResult in histograms.xml) accordingly.
// Public for testing.
enum class RedirectResult {
REDIRECTED_ON_DISCONNECTED_NETWORK = 0,
PAGE_NOT_FOUND_ON_DISCONNECTED_NETWORK = 1,
REDIRECTED_ON_FLAKY_NETWORK = 2,
PAGE_NOT_FOUND_ON_FLAKY_NETWORK = 3,
IGNORED_FLAKY_NETWORK_FORWARD_BACK = 4,
REDIRECTED_ON_CONNECTED_NETWORK = 5,
NO_TAB_ID = 6,
SHOW_NET_ERROR_PAGE = 7,
REDIRECT_LOOP_OFFLINE = 8,
REDIRECT_LOOP_ONLINE = 9,
REDIRECT_RESULT_MAX,
};
~OfflinePageTabHelper() override;
const OfflinePageItem* offline_page() { return offline_page_.get(); }
private:
friend class content::WebContentsUserData<OfflinePageTabHelper>;
friend class OfflinePageTabHelperTest;
FRIEND_TEST_ALL_PREFIXES(OfflinePageTabHelperTest,
NewNavigationCancelsPendingRedirects);
explicit OfflinePageTabHelper(content::WebContents* web_contents);
void SetDelegateForTesting(std::unique_ptr<Delegate> delegate);
// Overridden from content::WebContentsObserver:
void DidStartNavigation(
content::NavigationHandle* navigation_handle) override;
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
void RedirectToOnline(const GURL& from_url,
const OfflinePageItem* offline_page);
// 3 step redirection to the offline page. First getting all the pages, then
// selecting appropriate page to redirect to and finally attempting to
// redirect to that offline page, and caching metadata of that page locally.
// RedirectResult is accumulated along the codepath to reflect the overall
// result of redirection - and be reported to UMA at the end.
void GetPagesForRedirectToOffline(RedirectResult result,
const GURL& online_url);
void SelectBestPageForRedirectToOffline(
RedirectResult result,
const GURL& online_url,
const MultipleOfflinePageItemResult& pages);
void TryRedirectToOffline(RedirectResult result,
const GURL& from_url,
const OfflinePageItem& offline_page);
void Redirect(const GURL& from_url, const GURL& to_url);
// Returns true if a given URL is in redirect chain already.
bool IsInRedirectLoop(const GURL& to_url) const;
void ReportRedirectResultUMA(RedirectResult result);
// Iff the tab we are associated with is redirected to an offline page,
// |offline_page_| will be non-null. This can be used to synchronously ask
// about the offline state of the current web contents.
std::unique_ptr<OfflinePageItem> offline_page_;
std::unique_ptr<Delegate> delegate_;
base::WeakPtrFactory<OfflinePageTabHelper> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(OfflinePageTabHelper);
};
} // namespace offline_pages
#endif // CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINE_PAGE_TAB_HELPER_H_
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
a5b4e57d6c8a0949442398ae6a22e7f669684ecb | 3324b70597e57ac9f3ccaff859aff40852a513c6 | /classwork/ParticleField/src/testApp.cpp | 52f666e428d5dcc1d56038d919fa299595e5c7db | [] | no_license | oherterich/algo2013-owenherterich | 0cc8aaa93318d026f627188fd6ba4e1f2cc23c16 | 0988b2dd821b44fca7216b4ec1eab365836dc381 | refs/heads/master | 2021-01-21T05:05:47.571780 | 2013-12-16T21:29:20 | 2013-12-16T21:29:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,339 | cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
myField.setup( ofGetWindowWidth(), ofGetWindowHeight(), 20 );
ofBackground(0);
for (int i = 0; i < 500; i++) {
addParticle();
}
}
//--------------------------------------------------------------
void testApp::update(){
for( int i = 0; i < particleList.size(); i++ ) {
particleList[i].applyForce( myField.getForceAtPosition( particleList[i].pos ) * 0.005 );
particleList[i].update();
}
myField.update();
}
//--------------------------------------------------------------
void testApp::draw(){
for( int i = 0; i < particleList.size(); i++ ) {
particleList[i].draw();
}
myField.draw();
}
void testApp::addParticle() {
Particle tmp;
tmp.pos = ofVec2f( ofRandomWidth(), ofRandomHeight() );
particleList.push_back( tmp );
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
if( key == '1'){
myField.setRandom( 20.0 );
}else if( key == '2' ){
myField.setPerlin();
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
if( button == OF_MOUSE_BUTTON_1 ){
// myField.addRepelForce(x, y, 100, 2.0);
myField.addCircularForce(x, y, 300, 2.0);
}else{
myField.addAttractForce(x, y, 100, 2.0);
}
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
mouseDragged(x, y, button);
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
}
| [
"oherterich@gmail.com"
] | oherterich@gmail.com |
254872aa8a3e03462daf9808b8e7877450570e1a | c36c51b605873e674efdf1a9c2198be2b24ba1cc | /Source/Core/EventSpecification.cpp | 6b29242ae5c401f0aeba409ace5a0ac95e293e62 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | aquawicket2/RmlUi | 5454c673af3b307f9d079495b0515894f71b4893 | 264d3630f435855aa67b4db1e081c3a727713c1c | refs/heads/master | 2021-04-23T04:58:12.383232 | 2020-03-28T16:33:59 | 2020-03-28T16:33:59 | 249,899,751 | 4 | 0 | MIT | 2020-03-25T06:03:25 | 2020-03-25T06:03:25 | null | UTF-8 | C++ | false | false | 8,399 | cpp | /*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
* Copyright (c) 2019 The RmlUi Team, and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "EventSpecification.h"
#include "../../Include/RmlUi/Core/ID.h"
namespace Rml {
namespace Core {
// An EventId is an index into the specifications vector.
static std::vector<EventSpecification> specifications = { { EventId::Invalid, "invalid", false, false, DefaultActionPhase::None } };
// Reverse lookup map from event type to id.
static UnorderedMap<String, EventId> type_lookup;
namespace EventSpecificationInterface {
void Initialize()
{
// Must be specified in the same order as in EventId
specifications = {
// id type interruptible bubbles default_action
{EventId::Invalid , "invalid" , false , false , DefaultActionPhase::None},
{EventId::Mousedown , "mousedown" , true , true , DefaultActionPhase::TargetAndBubble},
{EventId::Mousescroll , "mousescroll" , true , true , DefaultActionPhase::TargetAndBubble},
{EventId::Mouseover , "mouseover" , true , true , DefaultActionPhase::Target},
{EventId::Mouseout , "mouseout" , true , true , DefaultActionPhase::Target},
{EventId::Focus , "focus" , false , false , DefaultActionPhase::Target},
{EventId::Blur , "blur" , false , false , DefaultActionPhase::Target},
{EventId::Keydown , "keydown" , true , true , DefaultActionPhase::TargetAndBubble},
{EventId::Keyup , "keyup" , true , true , DefaultActionPhase::TargetAndBubble},
{EventId::Textinput , "textinput" , true , true , DefaultActionPhase::TargetAndBubble},
{EventId::Mouseup , "mouseup" , true , true , DefaultActionPhase::TargetAndBubble},
{EventId::Click , "click" , true , true , DefaultActionPhase::TargetAndBubble},
{EventId::Dblclick , "dblclick" , true , true , DefaultActionPhase::TargetAndBubble},
{EventId::Load , "load" , false , false , DefaultActionPhase::None},
{EventId::Unload , "unload" , false , false , DefaultActionPhase::None},
{EventId::Show , "show" , false , false , DefaultActionPhase::None},
{EventId::Hide , "hide" , false , false , DefaultActionPhase::None},
{EventId::Mousemove , "mousemove" , true , true , DefaultActionPhase::None},
{EventId::Dragmove , "dragmove" , true , true , DefaultActionPhase::None},
{EventId::Drag , "drag" , false , true , DefaultActionPhase::Target},
{EventId::Dragstart , "dragstart" , false , true , DefaultActionPhase::Target},
{EventId::Dragover , "dragover" , true , true , DefaultActionPhase::None},
{EventId::Dragdrop , "dragdrop" , true , true , DefaultActionPhase::None},
{EventId::Dragout , "dragout" , true , true , DefaultActionPhase::None},
{EventId::Dragend , "dragend" , true , true , DefaultActionPhase::None},
{EventId::Handledrag , "handledrag" , false , true , DefaultActionPhase::None},
{EventId::Resize , "resize" , false , false , DefaultActionPhase::None},
{EventId::Scroll , "scroll" , false , true , DefaultActionPhase::None},
{EventId::Animationend , "animationend" , false , true , DefaultActionPhase::None},
{EventId::Transitionend , "transitionend" , false , true , DefaultActionPhase::None},
{EventId::Change , "change" , false , true , DefaultActionPhase::None},
{EventId::Submit , "submit" , true , true , DefaultActionPhase::None},
{EventId::Tabchange , "tabchange" , false , true , DefaultActionPhase::None},
{EventId::Columnadd , "columnadd" , false , true , DefaultActionPhase::None},
{EventId::Rowadd , "rowadd" , false , true , DefaultActionPhase::None},
{EventId::Rowchange , "rowchange" , false , true , DefaultActionPhase::None},
{EventId::Rowremove , "rowremove" , false , true , DefaultActionPhase::None},
{EventId::Rowupdate , "rowupdate" , false , true , DefaultActionPhase::None},
};
type_lookup.clear();
type_lookup.reserve(specifications.size());
for (auto& specification : specifications)
type_lookup.emplace(specification.type, specification.id);
#ifdef RMLUI_DEBUG
// Verify that all event ids are specified
RMLUI_ASSERT((int)specifications.size() == (int)EventId::NumDefinedIds);
for (int i = 0; i < (int)specifications.size(); i++)
{
// Verify correct order
RMLUI_ASSERT(i == (int)specifications[i].id);
}
#endif
}
static EventSpecification& GetMutable(EventId id)
{
size_t i = static_cast<size_t>(id);
if (i < specifications.size())
return specifications[i];
return specifications[0];
}
// Get event specification for the given type.
// If not found: Inserts a new entry with given values.
static EventSpecification& GetOrInsert(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase)
{
auto it = type_lookup.find(event_type);
if (it != type_lookup.end())
return GetMutable(it->second);
const size_t new_id_num = specifications.size();
if (new_id_num >= size_t(EventId::MaxNumIds))
{
Log::Message(Log::LT_ERROR, "Error while registering event type '%s': Maximum number of allowed events exceeded.", event_type.c_str());
RMLUI_ERROR;
return specifications.front();
}
// No specification found for this name, insert a new entry with default values
EventId new_id = static_cast<EventId>(new_id_num);
specifications.push_back(EventSpecification{ new_id, event_type, interruptible, bubbles, default_action_phase });
type_lookup.emplace(event_type, new_id);
return specifications.back();
}
const EventSpecification& Get(EventId id)
{
return GetMutable(id);
}
const EventSpecification& GetOrInsert(const String& event_type)
{
// Default values for new event types defined as follows:
constexpr bool interruptible = true;
constexpr bool bubbles = true;
constexpr DefaultActionPhase default_action_phase = DefaultActionPhase::None;
return GetOrInsert(event_type, interruptible, bubbles, default_action_phase);
}
EventId GetIdOrInsert(const String& event_type)
{
auto it = type_lookup.find(event_type);
if (it != type_lookup.end())
return it->second;
return GetOrInsert(event_type).id;
}
EventId InsertOrReplaceCustom(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase)
{
const size_t size_before = specifications.size();
EventSpecification& specification = GetOrInsert(event_type, interruptible, bubbles, default_action_phase);
bool got_existing_entry = (size_before == specifications.size());
// If we found an existing entry of same type, replace it, but only if it is a custom event id.
if (got_existing_entry && (int)specification.id >= (int)EventId::FirstCustomId)
{
specification.interruptible = interruptible;
specification.bubbles = bubbles;
specification.default_action_phase = default_action_phase;
}
return specification.id;
}
}
}
}
| [
"michael.ragazzon@gmail.com"
] | michael.ragazzon@gmail.com |
0e8c7105810471c8d3209efebd54856edbc91ee3 | b155f6ba313cfd5c02441ac3d639fff2273daae0 | /Source/Server.cpp | dc2b94643b2083d75e78e54de976ed710f6c67f8 | [] | no_license | numver8638/EndTermProjectV2 | 86128fc6111ca42965054710b02b83983107f780 | 5e4ca89fef54cd545b1b20ee08b551ecb5b1fd01 | refs/heads/master | 2023-03-22T01:26:06.558307 | 2021-03-18T08:14:44 | 2021-03-18T08:14:44 | 348,604,277 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,855 | cpp | #include "Server.h"
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include "ConnectionState.h"
#include "PacketStream.h"
#include "Socket.h"
#include "Thread.h"
#define MIN_WIDTH (0)
#define MAX_WIDTH (10)
#define MIN_HEIGHT (0)
#define MAX_HEIGHT (10)
#define BUFFER_HEIGHT (4)
// 클라이언트와 통신하는 스레드. 클라이언트 당 하나씩 생성됨.
class ClientThread : public Thread {
private:
Socket m_socket;
PacketStream m_stream;
std::string m_username;
ConnectionState m_state = ConnectionState::Login;
bool m_connected = true;
std::vector<Block> m_blocks;
Block m_currentBlock;
int m_maxHeight;
// 타이머 정보
DWORD m_ticks;
DWORD m_tickCount;
DWORD m_tickBase;
void Disconnect() {
m_connected = false;
m_socket.Close();
}
// 현재 블럭 상태에서 주어진 위치로 블럭을 이동 할 수 있는지 판단하는 메서드.
bool CanMove(const Position& pos, const BlockData& data) {
std::vector<bool> plane(MAX_WIDTH * MAX_HEIGHT);
// 현재 쌓인 블록을 기준으로 bool vector 생성.
auto it = m_blocks.begin();
const auto end = --m_blocks.end(); // 마지막 블럭은 현재 블럭(움직이고 있는 블럭)으로 취급함.
while (it != end) {
auto& b = *(it++);
const auto& pos = b.GetPosition();
for (const auto& p : b.GetData().Data) {
if ((pos.Y + p.first.Y) >= 0) {
plane[(pos.Y + p.first.Y) * MAX_WIDTH + (pos.X + p.first.X)] = true;
}
}
}
// 위에서 생성한 bool vector와 현재 블럭이 겹치는지 판단.
auto collide = false;
for (const auto& p : data.Data) {
// 블럭이 위에서 내려오는 경우 일부가 잘릴수도 있음.
// 그런 예외 상황을 고려해서 Y가 0 이상인 부분만 판단.
if ((pos.Y + p.first.Y) >= 0) {
collide |= plane[(pos.Y + p.first.Y) * MAX_WIDTH + (pos.X + p.first.X)];
}
}
// 충돌하지 않는다면 옮길 수 있고, 아니라면 옮길 수 없음.
return !collide;
}
void SendCreateBlock() {
// Send random block
auto block = Block::GenerateRandomBlock();
// 블럭이 X축 밖으로 넘어가지 않는 범위에서 랜덤으로 X 위치를 결정함.
auto pos = Position(rand() % (MAX_WIDTH - block.GetData().Width), 0);
// 블럭의 위치를 설정.
block.SetAbsolutePosition(pos);
// 클라이언트에게 전송.
m_stream.SendEvent(CreateBlockEvent(block.GetKind(), block.GetDirection(), block.GetPosition()));
// 서버에 저장.
m_blocks.push_back(block);
}
void CheckBlocks() {
auto overflow = false;
std::vector<bool> plane(MAX_WIDTH * MAX_HEIGHT);
// 현재 쌓인 블록을 기준으로 bool vector 생성.
auto it = m_blocks.begin();
const auto end = --m_blocks.end(); // 마지막 블럭은 현재 블럭(움직이고 있는 블럭)으로 취급함.
while (it != end) {
auto& b = *(it++);
const auto& pos = b.GetPosition();
for (const auto& p : b.GetData().Data) {
// 블럭이 XY 범위를 넘어간다면 게임 실패 조건 성립.
// Y == 0인 경우 블럭이 천장에 닿은 경우이므로 이 경우도 게임 실패.
if ((pos.Y + p.first.Y) > 0) {
plane[(pos.Y + p.first.Y) * MAX_WIDTH + (pos.X + p.first.X)] = true;
}
else {
overflow = true;
}
}
}
// 실패 조건 판별
// 블럭이 최고 높이에 도달하거나 초과함.
if (overflow) {
m_state = ConnectionState::GameOver;
m_stream.SendEvent(GameOverEvent("Block overflow."));
}
// 성공 조건 판별
// 구성면이 모두 블럭으로 참.
auto succeed = true;
for (auto i = (MAX_WIDTH * (MAX_HEIGHT - m_maxHeight)); i < (MAX_WIDTH * MAX_HEIGHT); i++) {
succeed &= plane[i];
}
if (succeed) {
m_state = ConnectionState::GameOver;
m_stream.SendEvent(GameOverEvent("You won!"));
}
}
void MoveBlock(Key key) {
auto& block = m_blocks.back(); // 복사본 하나 생성.
auto pos = block.GetPosition();
auto delta = Position();
auto direction = block.GetDirection();
// 사용자 키 입력에 따라 블럭 변화 처리.
switch (key) {
case Key::Right:
delta.X = 1;
break;
case Key::Left:
delta.X = -1;
break;
case Key::Down:
delta.Y = 1;
break;
case Key::Space:
direction = (direction == BlockDirection::Horizontal) ? BlockDirection::Vertical : BlockDirection::Horizontal;
break;
default:
return;
}
// 위에서 위치 데이터 반영한 새로운 블록 데이터 가져옴.
auto& data = Block::GetData(block.GetKind(), direction);
pos += delta;
// 블록이 X 범위 밖으로 나가는 경우 위치 보정.
if (pos.X < 0) {
pos.X = 0;
}
if ((pos.X + data.Width) > MAX_WIDTH) {
pos.X = MAX_WIDTH - data.Width;
}
if (pos.Y >= MAX_HEIGHT) {
pos.Y = MAX_HEIGHT - 1;
}
// 옮길 위치가 이동 가능할 경우 현재 데이터에 반영하고 이벤트 전송.
if (CanMove(pos, data)) {
block.SetAbsolutePosition(pos);
block.SetDirection(direction);
MoveBlockEvent e(direction, pos);
m_stream.SendEvent(e);
std::printf("[thread %d] User pressed %d key. Move block to (%d,%d).\n",
GetThreadID(), static_cast<int>(key), pos.X, pos.Y);
}
else if (delta.Y > 0) {
// 움직일 수 없는 상태서 y 변위가 있을경우 바닥에 도달한 것으로 간주.
// 새로운 블럭을 생성함.
std::printf("[thread %d] Reached to the base(%d,%d). Create next block.\n",
GetThreadID(), pos.X, pos.Y);
SendCreateBlock();
}
else {
// 블럭을 움직 일 수 없음(디버깅용 메세지)
std::printf("[thread %d] Cannot move block to (%d, %d). Ignore it.\n",
GetThreadID(), pos.X, pos.Y);
}
// 현재 블록 상태 점검.
CheckBlocks();
}
// 타이머 이벤트. 사용자가 지정한 주기가 되면 이벤트가 발생함.
void OnTimer() {
// 현재 게임 상태에 따라 다르게 행동.
switch (m_state) {
// 게임 초기화 단계
case ConnectionState::GameInit: {
int width = 0;
int height = 0;
// 현재까지의 블럭들을 순회하면서 최고 높이와 현재 폭을 계산함.
for (const auto& block : m_blocks) {
const auto& data = block.GetData();
width += data.Width;
height = max(height, data.Height);
}
if (width == MAX_WIDTH) {
// Building initial state complete.
// Switch to GameStart state.
m_maxHeight = height;
m_state = ConnectionState::GameStart;
m_stream.SendEvent(GameStartEvent());
SendCreateBlock();
}
else {
// 적합한 블럭을 생성할 때 까지 반복.
while (true) {
auto block = Block::GenerateRandomBlock(true);
// 현재 남은 공간에 적합한 블럭인지 확인하고
// 적합한 경우 블럭 위치를 설정하고 블럭 생성 이벤트를 전송.
if (block.GetData().Width <= (MAX_WIDTH - width)) {
block.SetAbsolutePosition(Position(width, MAX_HEIGHT - 1));
m_blocks.push_back(block);
m_stream.SendEvent(CreateBlockEvent(block.GetKind(), block.GetDirection(), block.GetPosition()));
break;
}
}
}
break;
}
// 게임 시작 단계.
case ConnectionState::GameStart:
MoveBlock(Key::Down);
break;
default:
// Ignore it.
break;
}
}
void OnKeyPress(const KeyPressEvent* event) {
// 게임 시작 단계에서만 사용자 입력을 처리함.
if (m_state != ConnectionState::GameStart) {
std::printf("[thread %d] User pressed key but not in GameStart state. Ignore it.\n", GetThreadID());
}
else {
MoveBlock(event->GetKey());
}
}
void OnLogin(const LoginEvent* event) {
// 로그인 상태서 로그인 이벤트 발생시 연결 해제(오류로 취급).
if (m_state != ConnectionState::Login) {
std::printf("[thread %d] User sent LoginEvent while logged in.\n", GetThreadID());
ServerDisconnectEvent event("you're already logged in.");
m_stream.SendEvent(event);
Disconnect();
}
else {
// 로그인 성공. 게임 초기화 단계로 넘어 감.
std::printf("[thread %d] User %s logged in. (speed: %d)\n", GetThreadID(), event->GetName().c_str(), event->GetSpeed());
m_username = event->GetName();
m_tickBase = event->GetSpeed();
m_state = ConnectionState::GameInit;
GameInitEvent event;
m_stream.SendEvent(event);
}
}
void OnClientDisconnect(const ClientDisconnectEvent* event) {
// 클라이언트에서 연결 종료. 서버도 연결 종료함.
std::printf("[thread %d] User disconnected. cause: %s\n", GetThreadID(), event->GetCuase().c_str());
Disconnect();
}
public:
ClientThread(Server& server, Socket socket)
: m_socket(std::move(socket)), m_stream(m_socket) {}
int Run() {
assert(m_socket.IsConnected());
// Set random seed.
srand(time(NULL));
m_tickCount = GetTickCount();
DWORD deltaSum = 0;
while (m_connected) {
auto current = GetTickCount();
auto delta = (current - m_tickCount);
m_ticks += delta;
deltaSum += delta;
m_tickCount = current;
// 정해진 주기에 도달하면 타이머 이벤트 호출.
if (deltaSum > m_tickBase) {
deltaSum = 0;
OnTimer();
}
// 이벤트가 들어 온 경우 이벤트 처리.
if (m_socket.HasAcceptRequest()) {
Event* event = nullptr;
auto status = m_stream.ReceiveEvent(event);
if (status == SocketStatus::Success) {
// 클라이언트가 보낸 이벤트의 수신에 성공했다면
// 수신된 이벤트에 따라 이벤트 처리 코드 호출.
switch (event->GetEventID()) {
case EventID::KeyPress:
OnKeyPress(static_cast<const KeyPressEvent*>(event));
break;
case EventID::Login:
OnLogin(static_cast<const LoginEvent*>(event));
break;
case EventID::ClientDisconnect:
OnClientDisconnect(static_cast<const ClientDisconnectEvent*>(event));
break;
default:
std::printf("[thread %d] user %s: Not-to-be-sent packet %d is received from client. Ignore it.\n",
GetThreadID(), m_username.c_str(), static_cast<int>(event->GetEventID()));
break;
}
delete event;
}
else {
// 수신 실패. 연결 종료.
std::printf("[thread %d] Connection error: %s\n", GetThreadID(), Socket::StatusToString(status));
Disconnect();
}
}
}
return 0;
}
};
int Server::Start() {
Socket listenSocket;
std::string ip;
unsigned short port;
char buffer[16 + 1];
std::cout << "Server IP (default: localhost): ";
std::cin.getline(buffer, sizeof(buffer));
if (buffer[0] != '\0') {
ip.assign(buffer);
}
else {
ip = "127.0.0.1";
}
std::cout << "Server Port (default: 50000): ";
std::cin.getline(buffer, sizeof(buffer));
if (buffer[0] != '\0') {
port = std::atoi(buffer);
}
else {
port = 50000;
}
auto status = listenSocket.Bind(ip.c_str(), port);
if (status != SocketStatus::Success) {
std::cout << "Socket error: " << Socket::StatusToString(status) << std::endl;
return 0;
}
std::cout << "Created server on " << ip << ":" << port << std::endl;
const auto searchFunction = [this](Thread* thread) -> bool { return !thread->IsRunning(); };
while (true) {
// 클라이언트 접속 요청이 있으면 수락.
if (listenSocket.HasAcceptRequest()) {
auto thread = new ClientThread(*this, listenSocket.Accept());
m_threads.emplace(thread);
thread->Start();
}
// 종료된 스레드가 있으면 자원 정리.
auto it = std::find_if(m_threads.begin(), m_threads.end(), searchFunction);
while (it != m_threads.end()) {
Thread* thread = *it;
std::cout << "Removing terminated thread " << thread->GetThreadID() << std::endl;
thread->Wait();
delete thread;
it = m_threads.erase(it);
it = std::find_if(it, m_threads.end(), searchFunction);
}
}
return 0;
} | [
"numver8638@naver.com"
] | numver8638@naver.com |
94c275be25e47904c3b285a44648a78255fa4bec | 1e58f86db88d590ce63110c885c52305d67f8136 | /Common/messagelistdelegate.cpp | f89d1da790a13889ea4f96f582f611267dba6d32 | [] | no_license | urielyan/F270 | 32a9b87780b6b0bbbd8e072ca4305cd38dc975c1 | c3d1eceead895ded12166eeb6748df111f46ef2d | refs/heads/master | 2021-01-10T02:06:40.335370 | 2016-03-02T03:23:02 | 2016-03-02T03:23:02 | 52,927,128 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,475 | cpp | /*********************************************************************
* Copyright(c) 2014, 大豪信息技术有限公司上海研发部
*
* All Rights reserved
*
* 文件名称:MessageListDelegate.cpp
* 概 要:信息显示接口的代理
*
* 当前版本:V1.0.0
* 作 者:葛 海 浪
* 完成日期:2016-2-22
*
* 修改版本:
* 修改说明:
* 修改作者:
*
********************************************************************/
#include "messagelistdelegate.h"
#include <QPainter>
MessageListDelegate::MessageListDelegate(QObject *parent) :
QAbstractItemDelegate(parent)
{
}
void MessageListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
QRect sequnceRect, messageRect;
doLayout(option, sequnceRect, messageRect);
drawBackGround(painter, option, index);
drawSequnceRect(painter, option, index, sequnceRect);
drawMessageRect(painter, option, index, messageRect);
painter->restore();
}
QSize MessageListDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const
{
return option.rect.size();
}
bool MessageListDelegate::helpEvent(QHelpEvent */*event*/, QAbstractItemView */*view*/, const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/)
{
return false;
}
void MessageListDelegate::doLayout(const QStyleOptionViewItem &option, QRect &sequnceRect, QRect &messageRect) const
{
/** draw Message Sequnce Rect **/
sequnceRect = option.rect;
sequnceRect.setWidth(option.rect.width() / 9);
sequnceRect.moveLeft(option.rect.left());
/** draw Message Information Rect **/
messageRect = option.rect;
messageRect.moveLeft(option.rect.left());
}
void MessageListDelegate::drawBackGround(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
painter->save();
/** draw background **/
QRect rect = option.rect;
painter->setPen(QColor(202, 201, 200));
if(index.data(MousePressRole).toBool()) { // 鼠标下押状态
painter->setBrush(QBrush(QColor(179, 231, 255)));
} else {
if((index.data(MouseClickedRole).toBool())) { // 鼠标单击状态
painter->setBrush(QBrush(QColor(220, 244, 255)));
} else { // 默认状态
painter->setBrush(QBrush(QColor(248, 248, 248)));
}
}
painter->drawRoundedRect(rect, 0, 0);
/** draw over **/
painter->restore();
}
void MessageListDelegate::drawSequnceRect(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index, const QRect &rect) const
{
painter->save();
int pixSize = rect.height() * 0.25;
QFont font = option.font;
QTextOption txtAlign(Qt::AlignHCenter | Qt::AlignTop);
font.setPixelSize(pixSize);
painter->setFont(font);
painter->drawText(rect, index.data(SequnceRole).toString(), txtAlign);
painter->restore();
}
void MessageListDelegate::drawMessageRect(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index, const QRect &rect) const
{
painter->save();
int pixSize = rect.height() * 0.35;
QFont font = option.font;
QTextOption txtAlign(Qt::AlignCenter);
font.setPixelSize(pixSize);
painter->setFont(font);
painter->drawText(rect, index.data(MessageRole).toString(), txtAlign);
painter->restore();
}
| [
"urielyan@sina.com"
] | urielyan@sina.com |
0ce5ae63add551a2a5577117f1bb8a8456d623ad | db5bba94cf3eae6f1a16b1e780aa36f4b8c3c2da | /r-kvstore/src/model/TagResourcesRequest.cc | 28901f02465ddba3b3aec598bb42e2db93c363f9 | [
"Apache-2.0"
] | permissive | chaomengnan/aliyun-openapi-cpp-sdk | 42eb87a6119c25fd2d2d070a757b614a5526357e | bb7d12ae9db27f2d1b3ba7736549924ec8d9ef85 | refs/heads/master | 2020-07-25T00:15:29.526225 | 2019-09-12T15:34:29 | 2019-09-12T15:34:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,433 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/r-kvstore/model/TagResourcesRequest.h>
using AlibabaCloud::R_kvstore::Model::TagResourcesRequest;
TagResourcesRequest::TagResourcesRequest() :
RpcServiceRequest("r-kvstore", "2015-01-01", "TagResources")
{}
TagResourcesRequest::~TagResourcesRequest()
{}
long TagResourcesRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void TagResourcesRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setCoreParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::vector<std::string> TagResourcesRequest::getResourceId()const
{
return resourceId_;
}
void TagResourcesRequest::setResourceId(const std::vector<std::string>& resourceId)
{
resourceId_ = resourceId;
for(int i = 0; i!= resourceId.size(); i++)
setCoreParameter("ResourceId."+ std::to_string(i), resourceId.at(i));
}
std::string TagResourcesRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void TagResourcesRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setCoreParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string TagResourcesRequest::getRegionId()const
{
return regionId_;
}
void TagResourcesRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setCoreParameter("RegionId", regionId);
}
std::string TagResourcesRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void TagResourcesRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setCoreParameter("OwnerAccount", ownerAccount);
}
std::vector<TagResourcesRequest::Tag> TagResourcesRequest::getTag()const
{
return tag_;
}
void TagResourcesRequest::setTag(const std::vector<Tag>& tag)
{
tag_ = tag;
int i = 0;
for(int i = 0; i!= tag.size(); i++) {
auto obj = tag.at(i);
std::string str ="Tag."+ std::to_string(i);
setCoreParameter(str + ".Value", obj.value);
setCoreParameter(str + ".Key", obj.key);
}
}
long TagResourcesRequest::getOwnerId()const
{
return ownerId_;
}
void TagResourcesRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setCoreParameter("OwnerId", std::to_string(ownerId));
}
std::string TagResourcesRequest::getResourceType()const
{
return resourceType_;
}
void TagResourcesRequest::setResourceType(const std::string& resourceType)
{
resourceType_ = resourceType;
setCoreParameter("ResourceType", resourceType);
}
std::string TagResourcesRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void TagResourcesRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setCoreParameter("AccessKeyId", accessKeyId);
}
| [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
83afdfeb36d03188fe3cea71448daf1c01be4e75 | 7f8648727d44a04cf98fa3cf80ac010acbe43474 | /Feld.h | 83b13637dc3ba321c4e9a516c7df761053fd348b | [] | no_license | christiannoubi/Feld-WS15 | 5b2cbd2bb647a1a541fb2109888c4f3056f5715b | 9f25b6ec3b512b28908c799f46134e6f58f98b55 | refs/heads/master | 2020-04-15T03:00:34.844152 | 2019-01-06T18:08:16 | 2019-01-06T18:08:16 | 164,332,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 610 | h | #include <iostream>
struct Feld {
// Destruktor:
virtual ~Feld () {}
// Liefert die Länge des Felds zurück:
virtual int laenge() const = 0;
// Klammeroperator für nicht-konstante Objekte:
virtual double &operator [] (int a) = 0;
// Klammeroperator für konstante Objekte:
virtual double &operator [] (int a) const = 0;
};
// Feld auf den Ausgabestrom ausgeben:
std::ostream& operator << (std::ostream& os, Feld& feld) {
os << "[";
for(int i=0; i<feld.laenge(); i++) {
os << " " << feld [i];
}
os << " ]";
return os;
} | [
"noubichristian@yahoo.fr"
] | noubichristian@yahoo.fr |
a2461e5474c1dcabd9641913ae4ebf7dd534f3e6 | 85f6241123446541443cfd33045cbbfe63365295 | /unit_tests/test.cpp | b1ca962b232cabaa3ad11ff897487433049cdc68 | [] | no_license | sharonen/RateLimitingRequestsModule | 3df01ea97693d7ff7090c906415dfd7fbff26f18 | cf1991cae24c7fc7ca6b1132af492e4dd1524898 | refs/heads/master | 2020-03-29T11:03:14.582647 | 2018-09-30T06:07:52 | 2018-09-30T06:07:52 | 149,833,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,308 | cpp | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "../src/lib/requests_handler/requests_handler.hpp"
#include "../src/lib/requests_handler/response.hpp"
TEST_CASE("Checking the limit of requests")
{
GIVEN("a Requests Handle"){
auto pRequestsHandler = new RequestsHadler(100, 60);
THEN("the requests limits is as expected")
REQUIRE(pRequestsHandler->requests_limit()== 100);
}
}
TEST_CASE("Checking getter and setter methods of requests limits")
{
GIVEN("a Requests Handle"){
auto pRequestsHandler = new RequestsHadler(100, 60);
WHEN("setting a new value requests_limit"){
pRequestsHandler->requests_limit(200);
THEN("the new requests limits is as expected"){
REQUIRE(pRequestsHandler->requests_limit() == 200);
}
}
}
}
TEST_CASE("Checking getter and setter methods of timer_rate_in_sec")
{
GIVEN("a Requests Handle"){
auto pRequestsHandler = new RequestsHadler(100, 60);
WHEN("setting a new value timer_rate_in_sec"){
pRequestsHandler->timer_rate_in_sec(10);
THEN("the new requests limits is as expected"){
REQUIRE(pRequestsHandler->timer_rate_in_sec() == 10);
}
}
}
}
TEST_CASE("checking the limit of requests")
{
GIVEN("a Requests Handle"){
Response reps;
std::string url = "www.google.com";
RequestsHadler* pRequestsHandler = new RequestsHadler(5, 60);
REQUIRE(pRequestsHandler->requests_limit() == 5);
WHEN("sending 6 HTTP requests"){
for(int i = 0; i < 5; i++){
reps = pRequestsHandler->handleNewRequest(url);
REQUIRE(reps.code == ErrorCode::ok);
}
reps = pRequestsHandler->handleNewRequest(url);
THEN("the method returns an error code too many requests (HTTP error code 429)"){
REQUIRE(reps.code == ErrorCode::TooManyRequests);
}
}
}
}
TEST_CASE("checking the update requests limit")
{
GIVEN("a Requests Handle"){
Response reps;
std::string url = "www.google.com";
RequestsHadler* pRequestsHandler = new RequestsHadler(10, 2);
REQUIRE(pRequestsHandler->current_requests_limit() == 10);
for(int i = 0; i < 5; i++){
reps = pRequestsHandler->handleNewRequest(url);
REQUIRE(reps.code == ErrorCode::ok);
}
REQUIRE(pRequestsHandler->current_requests_limit()== 5);
WHEN("calling updateRequestsLimit"){
boost::asio::io_service io_s;
boost::asio::deadline_timer timer(io_s);
pRequestsHandler->updateRequestsLimit(&timer);
THEN("the current requests limit is restart"){
REQUIRE(pRequestsHandler->current_requests_limit()== 10);
}
}
}
}
TEST_CASE("checking the url requests ")
{
GIVEN("a Requests Handle"){
Response reps;
RequestsHadler* pRequestsHandler = new RequestsHadler(10, 2);
REQUIRE(pRequestsHandler->current_requests_limit()== 10);
WHEN("requesting a correct URL request"){
std::string url = "www.google.com";
reps = pRequestsHandler->handleNewRequest(url);
THEN("the method returns okay (HTTP code 200)"){
REQUIRE(reps.code == ErrorCode::ok);
}
}
WHEN("requesting a worng URL request"){
std::string url = "www.no_such_url_fot_testing.com";
reps = pRequestsHandler->handleNewRequest(url);
THEN("the method returns an error code bad request (HTTP error code 400)"){
REQUIRE(reps.code == ErrorCode::BadRequest);
}
}
}
}
| [
"sharonronen@sharons-air.lan"
] | sharonronen@sharons-air.lan |
1cc2ce02d3e6fce501dbac598270bceade3bc7ab | 0a30b9871858064844f4644121ac423244a95bb4 | /EngineModeController.h | e0f5f2788c068bd9bccbd2a698d06b7dbbff3f6e | [
"Apache-2.0"
] | permissive | elsewhat/gtav-mod-battlechess | 045a44b8171880ce325147a20b9a43343f57a1ca | 76c5fef1337e45dc13b6447354ffe96a1099b22b | refs/heads/master | 2021-06-23T14:18:45.506241 | 2017-09-05T20:45:50 | 2017-09-05T20:45:50 | 98,060,054 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | h | #pragma once
#include "inc\types.h"
#include "ChessBoard.h"
#include <vector>
class EngineModeController {
public:
virtual void onEnterMode(ChessBoard* chessBoard)=0;
virtual void onExitMode(ChessBoard* chessBoard)=0 ;
virtual bool actionOnTick(DWORD tick, ChessBoard* chessBoard)=0;
};
| [
"dagfinn.parnas@gmail.com"
] | dagfinn.parnas@gmail.com |
30116a9b6a93560dc800be72d83edd550df89b1c | 5bc237a4755d1d17218343d95eb95594b8fadb3d | /application/test/test_application.cpp | 912e3e75ce6fe8fe2bd99a1257cb76974d86b053 | [] | no_license | duynii/btproject | 557b85d14fd47de6acca8f4e05c9c38b22075ac5 | 7f87305e3e2dd524a5bd85ded76241d9eb7d0a17 | refs/heads/master | 2020-06-20T21:00:39.995727 | 2016-11-27T11:33:26 | 2016-11-27T11:33:26 | 74,821,652 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | cpp | #include <limits>
#include <gtest/gtest.h>
#include <comma/application/command_line_options.h>
#include <comma/application/signal_flag.h>
/// Some dummy tests to test linking
TEST( application, dj_algorithm )
{
EXPECT_TRUE( 1 == 1 );
EXPECT_FALSE( 1 != 1 );
EXPECT_EQ( 5, 5 );
// TODO: definitely more tests!
}
| [
"duynii@gmail.com"
] | duynii@gmail.com |
05ac0ff5e12159682345386089de99a1129b2f05 | e9025d80026f7d00e0fd69e0ee7e0f97533bd630 | /400/round494/C.cpp | a6ae38014c679ad27cb8d0d4606ce2d4d3c9f31a | [] | no_license | rishup132/Codeforces-Solutions | 66170b368d851b7076c03f42c9463a2342bac5df | 671d16b0beec519b99fc79058ab9035c6f956670 | refs/heads/master | 2020-04-12T04:32:10.451666 | 2019-03-22T14:04:31 | 2019-03-22T14:04:31 | 162,298,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 569 | cpp | #include <bits/stdc++.h>
#define ll long long
#define mod 1000000007
using namespace std;
int a[100010];
int main()
{
int n,k;
cin >> n >> k;
a[0] = 0;
for(int i=1;i<=n;i++)
cin >> a[i];
for(int i=1;i<=n;i++)
a[i] += a[i-1];
double ans = 0;
while(k <= n)
{
for(int i=0;i<=n-k;i++)
{
double temp = a[k+i] - a[i];
temp = temp/k;
if(ans < temp)
ans = temp;
}
k++;
}
cout << setprecision(15) << ans << endl;
} | [
"rishupgupta132@gmail.com"
] | rishupgupta132@gmail.com |
274e1aaa64ddecdd8f6c38163ae2d4cc81f13e4d | ad1ce910ab5d9382a87bebd2480f73ecca4c37a5 | /examples/bvp1d/simple3.cpp | 0981c86ae15c616589ecf90dc1309d7c8dafb5c6 | [
"MIT"
] | permissive | grenkin/joker-fdm | 33fee3fff4aa948bd4ba82c7016227a84b3cc5d8 | 21d60479ca0dd7f2deb0d8ce000f79a7c53f3202 | refs/heads/master | 2020-04-09T04:14:21.820983 | 2018-09-21T02:04:35 | 2018-09-21T02:04:35 | 68,077,571 | 4 | 0 | null | 2016-10-14T21:30:28 | 2016-09-13T05:35:13 | Matlab | UTF-8 | C++ | false | false | 1,499 | cpp | /*
A simple linear problem in 1D
-u''(x) = -2 on (0, 1)
u(0) = 0, u'(1) + 2 * (u(1) - 2) = 0
Exact solution: u(x) = x ^ 2
*/
#include <iostream>
#include <vector>
#include <cmath>
#include <joker-fdm/bvp1d.h>
using namespace std;
double zero(double x)
{
return 0;
}
double gfun(double x)
{
return -2;
}
double exact(double x)
{
return x * x;
}
int main() {
double L0 = 1;
int K0 = 10;
double rms_old;
for (int test = 0; test <= 5; ++test) {
vector<double> L(1); L[0] = L0;
vector<int> K(1); K[0] = K0;
Grid1D grid(L, K);
Data1D data(1, grid);
data.a[0][0] = 1;
data.b[0][0] = INFINITY; data.w[0][0] = 0;
data.b[0][1] = 2; data.w[0][1] = 4;
data.f[0][0][0] = data.df[0][0][0] = zero;
vector<GridFunction1D> sol(1);
sol[0].set_grid(grid);
for (int n = 0; n <= K0; ++n) {
data.g[0](0, n) = gfun(grid.coord(0, n));
sol[0](0, n) = 0;
}
Parameters1D param;
param.max_Newton_iterations = 1;
SolveBVP1D(data, param, sol);
double rms = 0;
for (int n = 0; n <= K0; ++n)
rms += pow(sol[0](0, n) - exact(grid.coord(0, n)), 2);
rms = sqrt(rms / (K0 + 1));
cout << "h = " << grid.h[0] << endl;
cout << "rms = " << rms << endl;
if (test > 0)
cout << "rms_old / rms = " << rms_old / rms << "\n\n";
rms_old = rms;
K0 *= 2;
}
return 0;
}
| [
"glebgrenkin@gmail.com"
] | glebgrenkin@gmail.com |
0516cf09ee4a486f2fc1d8da1201d376de9fe140 | 9989ec29859d067f0ec4c7b82e6255e227bd4b54 | /atcoder.jp/abc_170/abc170_e.cpp | 525e2763dc443538d56e5785de61e486d9043214 | [] | no_license | hikko624/prog_contest | 8fa8b0e36e4272b6ad56d6506577c13f9a11c9de | 34350e2d298deb52c99680d72345ca44ab6f8849 | refs/heads/master | 2022-09-10T20:43:28.046873 | 2022-08-26T13:59:29 | 2022-08-26T13:59:29 | 217,740,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11 | cpp | // abc170_e | [
"hikko624@gmail.com"
] | hikko624@gmail.com |
560ec2df631e868708dbc2dcc4e636d06505f510 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /chrome/browser/notifications/fullscreen_notification_blocker.h | f8d6107fd88f7910d68af8e26ad296d88e3455aa | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 1,531 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_NOTIFICATIONS_FULLSCREEN_NOTIFICATION_BLOCKER_H_
#define CHROME_BROWSER_NOTIFICATIONS_FULLSCREEN_NOTIFICATION_BLOCKER_H_
#include "base/macros.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "ui/message_center/notification_blocker.h"
// A notification blocker which checks the fullscreen state.
class FullscreenNotificationBlocker
: public message_center::NotificationBlocker,
public content::NotificationObserver {
public:
explicit FullscreenNotificationBlocker(
message_center::MessageCenter* message_center);
~FullscreenNotificationBlocker() override;
bool is_fullscreen_mode() const { return is_fullscreen_mode_; }
// message_center::NotificationBlocker overrides:
void CheckState() override;
bool ShouldShowNotificationAsPopup(
const message_center::Notification& notification) const override;
private:
// content::NotificationObserver override.
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
bool is_fullscreen_mode_;
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(FullscreenNotificationBlocker);
};
#endif // CHROME_BROWSER_NOTIFICATIONS_FULLSCREEN_NOTIFICATION_BLOCKER_H_
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
b0912f4e8a3aacb729fc3de5de3cbde661b38994 | 4ad2ec9e00f59c0e47d0de95110775a8a987cec2 | /_HackerCup/2016/Round 1/Boomerang Tournament/Help/Brute/main.cpp | 4b7b3efa2e975b229cfada78325791aa96021800 | [] | no_license | atatomir/work | 2f13cfd328e00275672e077bba1e84328fccf42f | e8444d2e48325476cfbf0d4cfe5a5aa1efbedce9 | refs/heads/master | 2021-01-23T10:03:44.821372 | 2021-01-17T18:07:15 | 2021-01-17T18:07:15 | 33,084,680 | 2 | 1 | null | 2015-08-02T20:16:02 | 2015-03-29T18:54:24 | C++ | UTF-8 | C++ | false | false | 1,764 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define mp make_pair
#define pb push_back
#define maxN 20
int t, test, n, i, j;
int better[maxN][maxN];
int ans[maxN][2];
int perm[maxN];
int point[maxN];
queue<int> Q;
int main()
{
freopen("input.in","r",stdin);
freopen("output.ok","w",stdout);
scanf("%d", &t);
for (test = 1; test <= t; test++) {
scanf("%d", &n);
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &better[i][j]);
if (n == 16)
continue;
for (i = 1; i <= n; i++) {
ans[i][0] = 20;
ans[i][1] = 0;
}
for (i = 1; i <= n; i++)
perm[i] = i;
do {
while (!Q.empty()) Q.pop();
for (i = 1; i <= n; i++) {
Q.push(perm[i]);
point[i] = n / 2;
}
for (i = 1; i < n; i++) {
int id1 = Q.front(); Q.pop();
int id2 = Q.front(); Q.pop();
if (better[id1][id2]) {
point[id1] >>= 1;
Q.push(id1);
} else {
point[id2] >>= 1;
Q.push(id2);
}
}
for (i = 1; i <= n; i++) {
ans[i][0] = min(ans[i][0], point[i] + 1);
ans[i][1] = max(ans[i][1], point[i] + 1);
}
} while (next_permutation(perm + 1, perm + n + 1));
printf("Case #%d: \n", test);
for (i = 1; i <= n; i++)
printf("%d %d\n", ans[i][0], ans[i][1]);
printf("\n");
}
return 0;
}
| [
"atatomir5@gmail.com"
] | atatomir5@gmail.com |
0f12f0b2ad3525184b1198a04bd6f3755c3cc9ba | c0caed81b5b3e1498cbca4c1627513c456908e38 | /src/core/pose/rna/BaseStack.cc | e32f15496a78bb46fbe35584ba5a8772b4387636 | [] | no_license | malaifa/source | 5b34ac0a4e7777265b291fc824da8837ecc3ee84 | fc0af245885de0fb82e0a1144422796a6674aeae | refs/heads/master | 2021-01-19T22:10:22.942155 | 2017-04-19T14:13:07 | 2017-04-19T14:13:07 | 88,761,668 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,059 | cc | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu.
/// @file core/pose/rna/BaseStack.cc
/// @brief
/// @details
/// @author Rhiju Das, rhiju@stanford.edu
#include <core/pose/rna/BaseStack.hh>
#include <basic/Tracer.hh>
static basic::Tracer TR( "core.pose.rna.BaseStack" );
#ifdef SERIALIZATION
// Utility serialization headers
#include <utility/serialization/serialization.hh>
// Cereal headers
#include <cereal/types/polymorphic.hpp>
#endif // SERIALIZATION
namespace core {
namespace pose {
namespace rna {
///////////////////////////////////////////////////////////////////
BaseStack::BaseStack():
res1_( 0 ),
res2_( 0 ),
orientation_( ANY_BASE_DOUBLET_ORIENTATION ),
which_side_( ANY_BASE_STACK_SIDE )
{
}
///////////////////////////////////////////////////////////////////
bool
operator < ( BaseStack const & lhs, BaseStack const & rhs ){
//There must be a more elegant way to do this...
if ( lhs.res1_ < rhs.res1_ ) {
return true;
} else if ( lhs.res1_ == rhs.res1_ ) {
if ( lhs.res2_ < rhs.res2_ ) {
return true;
} else if ( lhs.res2_ == rhs.res2_ ) {
if ( lhs.orientation_ < rhs.orientation_ ) {
return true;
} else if ( lhs.orientation_ == rhs.orientation_ ) {
return ( lhs.which_side_ < rhs.which_side_ );
}
}
}
return false;
}
///////////////////////////////////////////////////////////////////
std::ostream &
operator << ( std::ostream & out, BaseStack const & s )
{
out << s.res1_ << " " << s.res2_ << " "
<< get_full_orientation_from_num( s.orientation_ ) << " " << get_full_side_from_num( s.which_side_ );
return out;
}
} //rna
} //pose
} //core
#ifdef SERIALIZATION
/// @brief Automatically generated serialization method
template< class Archive >
void
core::pose::rna::BaseStack::save( Archive & arc ) const {
arc( CEREAL_NVP( res1_ ) ); // Size
arc( CEREAL_NVP( res2_ ) ); // Size
arc( CEREAL_NVP( orientation_ ) ); // enum core::chemical::rna::BaseDoubletOrientation
arc( CEREAL_NVP( which_side_ ) ); // enum core::chemical::rna::BaseStackWhichSide
}
/// @brief Automatically generated deserialization method
template< class Archive >
void
core::pose::rna::BaseStack::load( Archive & arc ) {
arc( res1_ ); // Size
arc( res2_ ); // Size
arc( orientation_ ); // enum core::chemical::rna::BaseDoubletOrientation
arc( which_side_ ); // enum core::chemical::rna::BaseStackWhichSide
}
SAVE_AND_LOAD_SERIALIZABLE( core::pose::rna::BaseStack );
CEREAL_REGISTER_TYPE( core::pose::rna::BaseStack )
CEREAL_REGISTER_DYNAMIC_INIT( core_pose_rna_BaseStack )
#endif // SERIALIZATION
| [
"malaifa@yahoo.com"
] | malaifa@yahoo.com |
316c527c9f8d2af83225cea89bb4422a61b2e6a5 | 33e1799b6f320f2ab17f41f39492aeaf60bcf969 | /AgileFontSet/CEditImpl.h | 55b36ce35eb82dddb5748804754b9e774a39e500 | [] | no_license | patton88/AgileFontSet | feac17fb84e906e02db822ce14d71ddf37ba5358 | da0e26865f76bd053fc23896ab4abd1247b6ac54 | refs/heads/master | 2020-08-15T11:38:50.691081 | 2019-10-16T02:25:28 | 2019-10-16T02:25:28 | 215,334,815 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,323 | h | // CEditImpl.h
//
//////////////////////////////////////////////////////////////////////////
#if !defined(AFX_CEditImpl_H__C84_E69_d49_i41_t05_I29_00007733__INCLUDED_)
#define AFX_CEditImpl_H__C84_E69_d49_i41_t05_I29_00007733__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// CEditImpl - CWindowImpl-derived class that implements a button. We need a
// class like this to do subclassing or DDX.
class CEditImpl : public CWindowImpl<CEditImpl, CEdit>
{
public:
CEditImpl();
virtual ~CEditImpl();
void SetTooltipText(LPCTSTR lpszText, BOOL bActivate = TRUE);
BEGIN_MSG_MAP(CEditImpl)
MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseMessage)
MSG_WM_MOUSEHOVER(OnMouseHover)
MSG_WM_MOUSELEAVE(OnMouseLeave)
END_MSG_MAP()
LRESULT OnMouseMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
void OnMouseHover(WPARAM wParam, CPoint point);
void OnMouseLeave();
private:
CToolTipCtrl m_toolTip;
BOOL m_bHovering;
void InitToolTip();
};
#endif // !defined(AFX_CEditImpl_H__C84_E69_d49_i41_t05_I29_00007733__INCLUDED_)
//////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
| [
"name2017@163.com"
] | name2017@163.com |
bf43aace070e60aa68f575550d8ddd30201b3f6e | 247a1bc8595079a22c18786b52f84bd9ba84f3c8 | /Cpp/318.maximum-product-of-word-lengths.cpp | 22da8ee207db90f7de14b4e26caf7bc19ffa15fc | [
"MIT"
] | permissive | zszyellow/leetcode | cad541a3c34b243031417ea2ac0c77f63e511516 | 2ef6be04c3008068f8116bf28d70586e613a48c2 | refs/heads/master | 2021-07-15T23:37:37.414560 | 2021-02-14T05:56:00 | 2021-02-14T05:56:00 | 26,573,267 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 574 | cpp | class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size(), mask = 0, res = 0;
vector<int> masks;
for (string word : words) {
mask = 0;
for (char c : word) mask |= (1 << (c-'a'));
masks.push_back(mask);
}
for (int i = 0; i < n-1; ++ i) {
for (int j = i+1; j < n; ++ j) {
if ((masks[i] & masks[j]) == 0) res = max(res, static_cast<int>(words[i].size()*words[j].size()));
}
}
return res;
}
}; | [
"zszyellow@hotmail.com"
] | zszyellow@hotmail.com |
1ce209b337816ebf2a7cc25df40b85131d197e94 | 81f2b85a9542b8fd365b44d0caa39f2fb6f8e122 | /GPE/unfinish/24731 Roads in the North.cpp | 9f93b16e2fac99998531750c44a2d1117009b25e | [] | no_license | setsal/coding | c66aa55e43805240c95e1c4f330f08b0fb0df7ba | 7ee094b8b680107efe88a0abb3aba5c18d148665 | refs/heads/master | 2023-08-26T20:03:03.723747 | 2021-09-24T18:04:14 | 2021-09-24T18:04:14 | 298,565,963 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | /*
Problem: 24731: Roads in the North
subs: 247, ACs: 53, AcceptRate: 21.46, onsite: 16, access: 2213
Link: https://gpe3.acm-icpc.tw/showproblemtab.php?probid=24731&cid=5
*/ | [
"contact@setsal.dev"
] | contact@setsal.dev |
968cea15579707fd3874d05cf991217afbf6f06c | 9c2de8d42ba3f23b0b6d74a2518e6834f98251d2 | /src/server/MinecraftChunk.cpp | 3b8b100623ae19092315d9fb35f5f486600c8169 | [] | no_license | tntguy12355/MinecraftPlaysPortal | c96025e660ed6861119d70f4431414697d41e757 | ddb491bcc508de65ad6647ef9f1aadabfee69cd4 | refs/heads/master | 2023-03-17T09:59:06.715233 | 2021-02-24T02:11:30 | 2021-02-24T02:11:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,807 | cpp | #include "MinecraftChunk.hpp"
#include "common.hpp"
namespace MCP {
Chunk::Chunk(int x, int z)
: x(x)
, z(z)
{
}
void Chunk::SetBlockID(int x, int y, int z, short id)
{
sections[(int)floor(y / 16.0)].SetBlockID(x, y % 16, z, id);
}
short Chunk::GetBlockID(int x, int y, int z)
{
return sections[(int)floor(y / 16.0)].GetBlockID(x, y % 16, z);
}
uint32_t Chunk::GetPrimaryBitMask()
{
uint32_t mask = 0;
for (int i = 15; i >= 0; i--) {
mask = mask << 1;
if (sections[i].GetBlockCount() > 0)mask += 1;
}
return mask;
}
int Chunk::GetSentSectionsCount()
{
int count = 0;
for (int i = 0; i < 16; i++) {
if (sections[i].GetBlockCount() > 0)count++;
}
return count;
}
void ChunkSection::SetBlockID(int x, int y, int z, short id)
{
assert(x < 16 && y < 16 && z < 16 && x >= 0 && y>=0 && z>=0);
short prevID = GetBlockID(x, y, z);
blocks[x][y][z] = id;
if (prevID == 0 && id != 0)blockCount++;
if (prevID != 0 && id == 0)blockCount--;
}
short ChunkSection::GetBlockID(int x, int y, int z)
{
if (x >= 16 || y >= 16 || z >= 16 || x<0 || y<0 || z<0) return 0;
else return blocks[x][y][z];
}
void ChunkWorld::SetBlockID(int x, int y, int z, short id)
{
int chunkX = (int)floor(x / 16.0);
int chunkZ = (int)floor(z / 16.0);
Chunk * c = GetChunk(chunkX, chunkZ);
//if there's no chunk, create one
if (c == nullptr && id > 0) {
c = new Chunk(chunkX, chunkZ);
chunks.push_back(c);
}
if (c == nullptr) return;
int blockX = x - chunkX * 16;
int blockZ = z - chunkZ * 16;
c->SetBlockID(blockX, y, blockZ, id);
// if cleaned up whole chunk, remove it from list
if (c->GetSentSectionsCount() == 0) {
for (auto it = chunks.begin(); it != chunks.end(); it++) {
if ((*it)->x == chunkX && (*it)->z == chunkZ) {
chunks.erase(it);
break;
}
}
}
}
short ChunkWorld::GetBlockID(int x, int y, int z)
{
int chunkX = (int)floor(x / 16.0);
int chunkZ = (int)floor(z / 16.0);
Chunk * c = GetChunk(chunkX, chunkZ);
if (c != nullptr) {
return c->GetBlockID(x % 16, y, z % 16);
}
return 0;
}
Chunk* ChunkWorld::GetChunk(int chunkX, int chunkZ)
{
for (Chunk* chunk : chunks) {
if (chunk->x == chunkX && chunk->z == chunkZ) {
return chunk;
}
}
return nullptr;
}
ChunkPacket::ChunkPacket(Chunk* c) : Packet(0x20)
{
WriteInt(c->x); // chunk X coords
WriteInt(c->z); // chunk Z coords
bool fullChunk = true;
WriteByte(fullChunk ? 1 : 0); // full chunk bool
WriteVarInt(c->GetPrimaryBitMask()); // primary bit mask (what chunks will be sent)
WriteInt(0x0A000000); // heightmap NBT list. not needed for what I do, so I send empty compound
if (fullChunk) {
// biome array of 4x4x4 sections
WriteVarInt(1024);
for (int i = 0; i < 1024; i++) {
WriteVarInt(c->biomeArray[i]);
}
}
// size of upcoming data (one chunk section is 8192 + 2 + 1 + 2)
WriteVarInt(c->GetSentSectionsCount() * 8197);
// writing every chunk section
for (int i = 0; i < 16; i++) {
ChunkSection& cs = c->sections[i];
if (cs.GetBlockCount() == 0)continue;
WriteShort(cs.GetBlockCount()); // block count
WriteByte(15); // bits per block, using max bytes for direct pallete (15 for 1.16 smh)
WriteVarInt(1024); // count of longs that will be sent
for (int y = 0; y < 16; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x += 4) {
uint64_t data = 0;
for (int b = 3; b >= 0; b--) {
data = data << 15;
data += cs.GetBlockID(x + b, y, z);
}
WriteLong(data);
}
}
// block entities. i don't need them, so simply sending empty array
WriteVarInt(0);
}
FullBrightLightChunkPacket::FullBrightLightChunkPacket(Chunk* c) : Packet(0x23)
{
WriteVarInt(c->x); // Chunk X
WriteVarInt(c->z); // Chunk Y
WriteByte(1); // trust edges?
uint32_t lightMask = c->GetPrimaryBitMask() << 1;
/*
WriteVarInt(lightMask); // sky light mask
WriteVarInt(lightMask); // block light mask
WriteVarInt(lightMask ^ 0b111111111111111111); // empty sky light mask
WriteVarInt(lightMask ^ 0b111111111111111111); // empty block light mask
int sectionCount = c->GetSentSectionsCount();
*/
//sending full bright for ALL of sections
WriteVarInt(0b111111111111111111); // sky light mask
WriteVarInt(0b111111111111111111); // block light mask
WriteVarInt(0); // empty sky light mask
WriteVarInt(0); // empty block light mask
int sectionCount = 18;
// sky light
for (int i = 0; i < sectionCount; i++) {
WriteVarInt(2048);
for (int i = 0; i < 256; i++) {
WriteLong(0xFFFFFFFFFFFFFFFF);
}
}
//block light
for (int i = 0; i < sectionCount; i++) {
WriteVarInt(2048);
for (int i = 0; i < 256; i++) {
WriteLong(0xFFFFFFFFFFFFFFFF);
}
}
}
}
| [
"krzyht@gmail.com"
] | krzyht@gmail.com |
95e8f23afb2022613157722e2da03a844b8d8be8 | 61b07e8d14f85800d6fad641a77ef8bbef8d3859 | /gameStats.cpp | 188082eab9b5bac626461fbc8db710a00011fe9c | [] | no_license | Jared-Adamson/CSE_C_Cpp_LISP_Prolog_Programs | d9fc85dac95abf0447f2d1538fbf329a387cd3b4 | 194236b8944e65f5850a1fd0addacc0b2a6e36b7 | refs/heads/master | 2021-06-20T20:59:51.948456 | 2017-08-11T06:32:57 | 2017-08-11T06:32:57 | 23,534,774 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | cpp | //Jared Adamson
//C++ Practice from Beginning C++ Book
// Demonstrates declaring and initializing variables
#include <iostream>
using namespace std;
int main()
{
int score;
double distance;
char playAgain;
bool shieldsUp;
short lives, aliensKilled;
score = 0;
distance = 1200.76;
playAgain = 'y';
shieldsUp = true;
lives = 3;
aliensKilled = 10;
double engineTemp = 6572.89;
cout << "\nscore: " << score << endl;
cout << "distance: " << distance << endl;
cout << "playAgain: " << playAgain << endl;
cout << "lives: " << lives << endl;
cout << "aliensKilled: "<< aliensKilled << endl;
cout << "engineTemp: " << engineTemp << endl;
int fuel;
cout << "\nHow much fuel? ";
cin >> fuel;
cout << "fuel: " << fuel << endl;
typedef unsigned short int ushort;
ushort bonus = 10;
cout << "\nbonus: " << bonus << endl;
return 0;
}
| [
"jared.d.adamson@gmail.com"
] | jared.d.adamson@gmail.com |
bddc2cb7c0d402edbb1e62b3e7e50e9c6f97bb17 | 92756269d7ba6a7c0a57ba8fcc1fd5f17cfba88f | /source/dialog_createtask.cpp | baae82be57eca827bb8fc6532bc289c96f0808d0 | [] | no_license | kapiten79/timecontrol | 1a2ee54986029dd21e7109ad7aa3c90d2d2b4755 | 59b70fb99e105f8f7552b046dfbec003080e528f | refs/heads/master | 2020-04-05T15:44:05.397613 | 2018-11-10T12:51:32 | 2018-11-10T12:51:32 | 156,981,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | cpp | #include "dialog_createtask.h"
#include "ui_dialog_createtask.h"
Dialog_createTask::Dialog_createTask(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog_createTask)
{
ui->setupUi(this);
ui->lineEdit->setFocus();
}
Dialog_createTask::~Dialog_createTask()
{
delete ui;
}
/* Инициализируем параметры окна */
void Dialog_createTask::init_windowParams()
{
qDebug() << "Функция Dialog_createTask::init_windowParams() запустилась";
this->open();
ui->label->setText(labelText);
qDebug() << labelText;
}
/* Нажатие кнопки OK в диалоге */
void Dialog_createTask::on_buttonBox_accepted()
{
emit nameEntered(ui->lineEdit->text());
ui->lineEdit->clear();
}
| [
"mihon79@inbox.ru"
] | mihon79@inbox.ru |
b3f9484513d7ec0aa13ff5bb8df6608c8804429e | def39f068050b234df9f6909d4277f96b740f11c | /E-olimp/1287. Tennis competitions .cpp | 9c83eb1c033c9119a8fc356f951dd46b8d979f90 | [] | no_license | azecoder/Problem-Solving | 41a9a4302c48c8de59412ab9175b253df99f1f28 | a920b7bac59830c7b798127f6eed0e2ab31a5fa2 | refs/heads/master | 2023-02-10T09:47:48.322849 | 2021-01-05T14:14:09 | 2021-01-05T14:14:09 | 157,236,604 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 188 | cpp | #include <stdio.h>
#include <stdlib.h>
unsigned long long a,b,s;
int main(int argc, char *argv[])
{
scanf("%llu %llu", &a,&b);
s=a*b;
printf("%llu\n", s);
return 0;
} | [
"tabriz.haji@gmail.com"
] | tabriz.haji@gmail.com |
ff83a831f93208e5ba592676e880cb44c9a529a0 | 968ad92cc0b69ec1fb0225f8c6912443e63cc260 | /algorithms/implementation/ManasaAndStones.cpp | 3fb64267a842b61f4fc0f1b089264729d8a2842e | [] | no_license | duonghdo/hackerrank | ba4c529ae08d58a23daca751c92d605ca69acfea | 0299a2d30b8083f2ec7a5636ae8584e948c77e03 | refs/heads/master | 2021-01-10T20:09:49.396319 | 2015-11-23T05:14:32 | 2015-11-23T05:14:32 | 40,314,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 340 | cpp | #include <iostream>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n, a, b;
cin >> n >> a >> b;
for(int i = 0; i < n; i++){
if(a == b) {
cout << a*(n-i-1);
break;
}
else if(a > b) cout << (i*a + (n-i-1)*b) << " ";
else cout << (i*b + (n-i-1)*a) << " ";
}
cout << endl;
}
return 0;
}
| [
"duonghdo@users.noreply.github.com"
] | duonghdo@users.noreply.github.com |
141658ca8d66785c12266583b5887e68e82be27d | 410e45283cf691f932b07c5fdf18d8d8ac9b57c3 | /chrome/browser/chromeos/policy/status_uploader_unittest.cc | a314bb8cc899b4ad25348722d273d25a7f2643ce | [
"BSD-3-Clause"
] | permissive | yanhuashengdian/chrome_browser | f52a7f533a6b8417e19b85f765f43ea63307a1fb | 972d284a9ffa4b794f659f5acc4116087704394c | refs/heads/master | 2022-12-21T03:43:07.108853 | 2019-04-29T14:20:05 | 2019-04-29T14:20:05 | 184,068,841 | 0 | 2 | BSD-3-Clause | 2022-12-17T17:35:55 | 2019-04-29T12:40:27 | null | UTF-8 | C++ | false | false | 15,487 | cc | // Copyright (c) 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.
#include "chrome/browser/chromeos/policy/status_uploader.h"
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/run_loop.h"
#include "base/test/test_simple_task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/chromeos/policy/device_local_account.h"
#include "chrome/browser/chromeos/policy/status_collector/device_status_collector.h"
#include "chrome/browser/chromeos/settings/scoped_testing_cros_settings.h"
#include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power/power_manager_client.h"
#include "chromeos/settings/cros_settings_names.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
#include "components/policy/core/common/cloud/mock_device_management_service.h"
#include "components/prefs/testing_pref_service.h"
#include "components/session_manager/core/session_manager.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "net/url_request/url_request_context_getter.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/user_activity/user_activity_detector.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/events/platform/platform_event_source.h"
#include "ui/events/platform_event.h"
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::SaveArg;
using ::testing::WithArgs;
namespace em = enterprise_management;
namespace {
constexpr base::TimeDelta kDefaultStatusUploadDelay =
base::TimeDelta::FromHours(1);
constexpr base::TimeDelta kMinImmediateUploadInterval =
base::TimeDelta::FromSeconds(10);
// Using a DeviceStatusCollector to have a concrete StatusCollector, but the
// exact type doesn't really matter, as it is being mocked.
class MockDeviceStatusCollector : public policy::DeviceStatusCollector {
public:
explicit MockDeviceStatusCollector(PrefService* local_state)
: DeviceStatusCollector(
local_state,
nullptr,
policy::DeviceStatusCollector::VolumeInfoFetcher(),
policy::DeviceStatusCollector::CPUStatisticsFetcher(),
policy::DeviceStatusCollector::CPUTempFetcher(),
policy::DeviceStatusCollector::AndroidStatusFetcher(),
policy::DeviceStatusCollector::TpmStatusFetcher(),
policy::DeviceStatusCollector::EMMCLifetimeFetcher(),
base::TimeDelta(), /* Day starts at midnight */
true /* is_enterprise_device */) {}
MOCK_METHOD1(GetStatusAsync, void(const policy::StatusCollectorCallback&));
MOCK_METHOD0(OnSubmittedSuccessfully, void());
// Explicit mock implementation declared here, since gmock::Invoke can't
// handle returning non-moveable types like scoped_ptr.
std::unique_ptr<policy::DeviceLocalAccount> GetAutoLaunchedKioskSessionInfo()
override {
return std::make_unique<policy::DeviceLocalAccount>(
policy::DeviceLocalAccount::TYPE_KIOSK_APP, "account_id", "app_id",
"update_url");
}
};
} // namespace
namespace policy {
class StatusUploaderTest : public testing::Test {
public:
StatusUploaderTest() : task_runner_(new base::TestSimpleTaskRunner()) {
DeviceStatusCollector::RegisterPrefs(prefs_.registry());
}
void SetUp() override {
// Required for policy::DeviceStatusCollector
chromeos::DBusThreadManager::Initialize();
chromeos::CryptohomeClient::InitializeFake();
chromeos::PowerManagerClient::InitializeFake();
client_.SetDMToken("dm_token");
collector_.reset(new MockDeviceStatusCollector(&prefs_));
// Keep a pointer to the mock collector because collector_ gets cleared
// when it is passed to the StatusUploader constructor.
collector_ptr_ = collector_.get();
}
void TearDown() override {
content::RunAllTasksUntilIdle();
chromeos::PowerManagerClient::Shutdown();
chromeos::CryptohomeClient::Shutdown();
chromeos::DBusThreadManager::Shutdown();
}
// Given a pending task to upload status, runs the task and returns the
// callback waiting to get device status / session status. The status upload
// task will be blocked until the test code calls that callback.
StatusCollectorCallback CollectStatusCallback() {
// Running the task should pass a callback into
// GetStatusAsync. We'll grab this callback.
EXPECT_TRUE(task_runner_->HasPendingTask());
StatusCollectorCallback status_callback;
EXPECT_CALL(*collector_ptr_, GetStatusAsync)
.WillOnce(SaveArg<0>(&status_callback));
task_runner_->RunPendingTasks();
testing::Mock::VerifyAndClearExpectations(&device_management_service_);
return status_callback;
}
// Given a pending task to upload status, mocks out a server response.
void RunPendingUploadTaskAndCheckNext(const StatusUploader& uploader,
base::TimeDelta expected_delay,
bool upload_success) {
StatusCollectorCallback status_callback = CollectStatusCallback();
// Running the status collected callback should trigger
// CloudPolicyClient::UploadDeviceStatus.
CloudPolicyClient::StatusCallback callback;
EXPECT_CALL(client_, UploadDeviceStatus).WillOnce(SaveArg<3>(&callback));
// Send some "valid" (read: non-nullptr) device/session data to the
// callback in order to simulate valid status data.
StatusCollectorParams status_params;
status_callback.Run(std::move(status_params));
testing::Mock::VerifyAndClearExpectations(&device_management_service_);
// Make sure no status upload is queued up yet (since an upload is in
// progress).
EXPECT_FALSE(task_runner_->HasPendingTask());
// StatusUpdater is only supposed to tell DeviceStatusCollector to clear its
// caches if the status upload succeeded.
EXPECT_CALL(*collector_ptr_, OnSubmittedSuccessfully())
.Times(upload_success ? 1 : 0);
// Now invoke the response.
callback.Run(upload_success);
// Now that the previous request was satisfied, a task to do the next
// upload should be queued.
EXPECT_EQ(1U, task_runner_->NumPendingTasks());
CheckPendingTaskDelay(uploader, expected_delay,
task_runner_->NextPendingTaskDelay());
}
void CheckPendingTaskDelay(const StatusUploader& uploader,
base::TimeDelta expected_delay,
base::TimeDelta task_delay) {
// The next task should be scheduled sometime between |last_upload| +
// |expected_delay| and |now| + |expected_delay|.
base::Time now = base::Time::NowFromSystemTime();
base::Time next_task = now + task_delay;
EXPECT_LE(next_task, now + expected_delay);
EXPECT_GE(next_task, uploader.last_upload() + expected_delay);
}
std::unique_ptr<StatusUploader> CreateStatusUploader() {
return std::make_unique<StatusUploader>(&client_, std::move(collector_),
task_runner_,
kDefaultStatusUploadDelay);
}
content::TestBrowserThreadBundle thread_bundle_;
scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
chromeos::ScopedTestingCrosSettings scoped_testing_cros_settings_;
std::unique_ptr<MockDeviceStatusCollector> collector_;
MockDeviceStatusCollector* collector_ptr_;
ui::UserActivityDetector detector_;
MockCloudPolicyClient client_;
MockDeviceManagementService device_management_service_;
TestingPrefServiceSimple prefs_;
// This property is required to instantiate the session manager, a singleton
// which is used by the device status collector.
session_manager::SessionManager session_manager_;
};
TEST_F(StatusUploaderTest, BasicTest) {
EXPECT_FALSE(task_runner_->HasPendingTask());
auto uploader = CreateStatusUploader();
EXPECT_EQ(1U, task_runner_->NumPendingTasks());
// On startup, first update should happen in 1 minute.
EXPECT_EQ(base::TimeDelta::FromMinutes(1),
task_runner_->NextPendingTaskDelay());
}
TEST_F(StatusUploaderTest, DifferentFrequencyAtStart) {
const base::TimeDelta new_delay = kDefaultStatusUploadDelay * 2;
scoped_testing_cros_settings_.device_settings()->SetInteger(
chromeos::kReportUploadFrequency, new_delay.InMilliseconds());
EXPECT_FALSE(task_runner_->HasPendingTask());
auto uploader = CreateStatusUploader();
ASSERT_EQ(1U, task_runner_->NumPendingTasks());
// On startup, first update should happen in 1 minute.
EXPECT_EQ(base::TimeDelta::FromMinutes(1),
task_runner_->NextPendingTaskDelay());
// Second update should use the delay specified in settings.
RunPendingUploadTaskAndCheckNext(*uploader, new_delay,
true /* upload_success */);
}
TEST_F(StatusUploaderTest, ResetTimerAfterStatusCollection) {
auto uploader = CreateStatusUploader();
RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay,
true /* upload_success */);
// Handle this response also, and ensure new task is queued.
RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay,
true /* upload_success */);
// Now that the previous request was satisfied, a task to do the next
// upload should be queued again.
EXPECT_EQ(1U, task_runner_->NumPendingTasks());
}
TEST_F(StatusUploaderTest, ResetTimerAfterFailedStatusCollection) {
auto uploader = CreateStatusUploader();
// Running the queued task should pass a callback into
// GetStatusAsync. We'll grab this callback and send nullptrs
// to it in order to simulate failure to get status.
EXPECT_EQ(1U, task_runner_->NumPendingTasks());
StatusCollectorCallback status_callback;
EXPECT_CALL(*collector_ptr_, GetStatusAsync)
.WillOnce(SaveArg<0>(&status_callback));
task_runner_->RunPendingTasks();
testing::Mock::VerifyAndClearExpectations(&device_management_service_);
// Running the callback should trigger StatusUploader::OnStatusReceived, which
// in turn should recognize the failure to get status and queue another status
// upload.
StatusCollectorParams status_params;
status_params.device_status.reset();
status_params.session_status.reset();
status_params.child_status.reset();
status_callback.Run(std::move(status_params));
EXPECT_EQ(1U, task_runner_->NumPendingTasks());
// Check the delay of the queued upload
CheckPendingTaskDelay(*uploader, kDefaultStatusUploadDelay,
task_runner_->NextPendingTaskDelay());
}
TEST_F(StatusUploaderTest, ResetTimerAfterUploadError) {
auto uploader = CreateStatusUploader();
// Simulate upload error
RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay,
false /* upload_success */);
// Now that the previous request was satisfied, a task to do the next
// upload should be queued again.
EXPECT_EQ(1U, task_runner_->NumPendingTasks());
}
TEST_F(StatusUploaderTest, ResetTimerAfterUnregisteredClient) {
auto uploader = CreateStatusUploader();
client_.SetDMToken("");
EXPECT_FALSE(client_.is_registered());
StatusCollectorCallback status_callback = CollectStatusCallback();
// Make sure no status upload is queued up yet (since an upload is in
// progress).
EXPECT_FALSE(task_runner_->HasPendingTask());
// StatusUploader should not try to upload using an unregistered client
EXPECT_CALL(client_, UploadDeviceStatus).Times(0);
StatusCollectorParams status_params;
status_callback.Run(std::move(status_params));
// A task to try again should be queued.
ASSERT_EQ(1U, task_runner_->NumPendingTasks());
CheckPendingTaskDelay(*uploader, kDefaultStatusUploadDelay,
task_runner_->NextPendingTaskDelay());
}
TEST_F(StatusUploaderTest, ChangeFrequency) {
auto uploader = CreateStatusUploader();
// Change the frequency. The new frequency should be reflected in the timing
// used for the next callback.
const base::TimeDelta new_delay = kDefaultStatusUploadDelay * 2;
scoped_testing_cros_settings_.device_settings()->SetInteger(
chromeos::kReportUploadFrequency, new_delay.InMilliseconds());
RunPendingUploadTaskAndCheckNext(*uploader, new_delay,
true /* upload_success */);
}
TEST_F(StatusUploaderTest, NoUploadAfterUserInput) {
auto uploader = CreateStatusUploader();
// Should allow data upload before there is user input.
EXPECT_TRUE(uploader->IsSessionDataUploadAllowed());
// Now mock user input, and no session data should be allowed.
ui::MouseEvent e(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
const ui::PlatformEvent& native_event = &e;
ui::UserActivityDetector::Get()->DidProcessEvent(native_event);
EXPECT_FALSE(uploader->IsSessionDataUploadAllowed());
}
TEST_F(StatusUploaderTest, NoUploadAfterVideoCapture) {
auto uploader = CreateStatusUploader();
// Should allow data upload before there is video capture.
EXPECT_TRUE(uploader->IsSessionDataUploadAllowed());
// Now mock video capture, and no session data should be allowed.
MediaCaptureDevicesDispatcher::GetInstance()->OnMediaRequestStateChanged(
0, 0, 0, GURL("http://www.google.com"), blink::MEDIA_DEVICE_VIDEO_CAPTURE,
content::MEDIA_REQUEST_STATE_OPENING);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(uploader->IsSessionDataUploadAllowed());
}
TEST_F(StatusUploaderTest, ScheduleImmediateStatusUpload) {
EXPECT_FALSE(task_runner_->HasPendingTask());
auto uploader = CreateStatusUploader();
EXPECT_EQ(1U, task_runner_->NumPendingTasks());
// On startup, first update should happen in 1 minute.
EXPECT_EQ(base::TimeDelta::FromMinutes(1),
task_runner_->NextPendingTaskDelay());
// Schedule an immediate status upload.
uploader->ScheduleNextStatusUploadImmediately();
EXPECT_EQ(2U, task_runner_->NumPendingTasks());
CheckPendingTaskDelay(*uploader, base::TimeDelta(),
task_runner_->FinalPendingTaskDelay());
}
TEST_F(StatusUploaderTest, ScheduleImmediateStatusUploadConsecutively) {
EXPECT_FALSE(task_runner_->HasPendingTask());
auto uploader = CreateStatusUploader();
EXPECT_EQ(1U, task_runner_->NumPendingTasks());
// On startup, first update should happen in 1 minute.
EXPECT_EQ(base::TimeDelta::FromMinutes(1),
task_runner_->NextPendingTaskDelay());
// Schedule an immediate status upload and run it.
uploader->ScheduleNextStatusUploadImmediately();
RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay,
true /* upload_success */);
// Schedule the next one and check that it was scheduled after
// kMinImmediateUploadInterval of the last upload.
uploader->ScheduleNextStatusUploadImmediately();
EXPECT_EQ(2U, task_runner_->NumPendingTasks());
CheckPendingTaskDelay(*uploader, kMinImmediateUploadInterval,
task_runner_->FinalPendingTaskDelay());
}
} // namespace policy
| [
"279687673@qq.com"
] | 279687673@qq.com |
31d8057c61aad58272afcb781fc29698c298738a | cd2f5e7775dbca9eec9f0fcd88a4635a2d2b0414 | /components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc | 2d119daf57463250b8cc64b8446fc6426762fa12 | [
"BSD-3-Clause"
] | permissive | ghj1040110333/chromium-1 | 8462ba0ca940fe3f4284d66036fb41f83cb7065e | 374d3a7593027eb6b26bf290e387e7de1fa9612a | refs/heads/master | 2023-03-02T22:22:29.564010 | 2018-02-11T09:21:22 | 2018-02-11T09:21:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 95,911 | 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 "components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <map>
#include <string>
#include <utility>
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/numerics/safe_conversions.h"
#include "base/optional.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/safe_sprintf.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/test/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_test_utils.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_data.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_metrics.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_request_options.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_features.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params_test_utils.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_server.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_switches.h"
#include "components/data_reduction_proxy/core/common/lofi_decider.h"
#include "components/data_reduction_proxy/proto/client_config.pb.h"
#include "components/previews/core/previews_decider.h"
#include "components/previews/core/previews_experiments.h"
#include "components/previews/core/previews_features.h"
#include "net/base/host_port_pair.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/proxy_server.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
#include "net/nqe/effective_connection_type.h"
#include "net/nqe/network_quality_estimator_test_util.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/proxy_resolution/proxy_info.h"
#include "net/proxy_resolution/proxy_retry_info.h"
#include "net/proxy_resolution/proxy_service.h"
#include "net/socket/socket_test_util.h"
#include "net/test/cert_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_data_directory.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_status.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace data_reduction_proxy {
namespace {
using TestNetworkDelegate = net::NetworkDelegateImpl;
const char kOtherProxy[] = "testproxy:17";
const char kTestURL[] = "http://www.google.com/";
const char kSecureTestURL[] = "https://www.google.com/";
const char kReceivedValidOCLHistogramName[] =
"Net.HttpContentLengthWithValidOCL";
const char kOriginalValidOCLHistogramName[] =
"Net.HttpOriginalContentLengthWithValidOCL";
const char kDifferenceValidOCLHistogramName[] =
"Net.HttpContentLengthDifferenceWithValidOCL";
// HTTP original content length
const char kOriginalInsecureDirectHistogramName[] =
"Net.HttpOriginalContentLengthV2.Http.Direct";
const char kOriginalInsecureViaDRPHistogramName[] =
"Net.HttpOriginalContentLengthV2.Http.ViaDRP";
const char kOriginalInsecureBypassedHistogramName[] =
"Net.HttpOriginalContentLengthV2.Http.BypassedDRP";
const char kOriginalInsecureOtherHistogramName[] =
"Net.HttpOriginalContentLengthV2.Http.Other";
// HTTP video original content length
const char kOriginalVideoInsecureDirectHistogramName[] =
"Net.HttpOriginalContentLengthV2.Http.Direct.Video";
const char kOriginalVideoInsecureViaDRPHistogramName[] =
"Net.HttpOriginalContentLengthV2.Http.ViaDRP.Video";
const char kOriginalVideoInsecureBypassedHistogramName[] =
"Net.HttpOriginalContentLengthV2.Http.BypassedDRP.Video";
const char kOriginalVideoInsecureOtherHistogramName[] =
"Net.HttpOriginalContentLengthV2.Http.Other.Video";
// HTTPS original content length
const char kOriginalSecureDirectHistogramName[] =
"Net.HttpOriginalContentLengthV2.Https.Direct";
const char kOriginalSecureViaDRPHistogramName[] =
"Net.HttpOriginalContentLengthV2.Https.ViaDRP";
const char kOriginalSecureBypassedHistogramName[] =
"Net.HttpOriginalContentLengthV2.Https.BypassedDRP";
const char kOriginalSecureOtherHistogramName[] =
"Net.HttpOriginalContentLengthV2.Https.Other";
// HTTPS video original content length
const char kOriginalVideoSecureDirectHistogramName[] =
"Net.HttpOriginalContentLengthV2.Https.Direct.Video";
const char kOriginalVideoSecureViaDRPHistogramName[] =
"Net.HttpOriginalContentLengthV2.Https.ViaDRP.Video";
const char kOriginalVideoSecureBypassedHistogramName[] =
"Net.HttpOriginalContentLengthV2.Https.BypassedDRP.Video";
const char kOriginalVideoSecureOtherHistogramName[] =
"Net.HttpOriginalContentLengthV2.Https.Other.Video";
// Lo-Fi histograms.
const char kReceivedValidOCLLoFiOnHistogramName[] =
"Net.HttpContentLengthWithValidOCL.LoFiOn";
const char kOriginalValidOCLLoFiOnHistogramName[] =
"Net.HttpOriginalContentLengthWithValidOCL.LoFiOn";
const char kDifferenceValidOCLLoFiOnHistogramName[] =
"Net.HttpContentLengthDifferenceWithValidOCL.LoFiOn";
const char kReceivedHistogramName[] = "Net.HttpContentLength";
const char kReceivedInsecureDirectHistogramName[] =
"Net.HttpContentLengthV2.Http.Direct";
const char kReceivedInsecureViaDRPHistogramName[] =
"Net.HttpContentLengthV2.Http.ViaDRP";
const char kReceivedInsecureBypassedHistogramName[] =
"Net.HttpContentLengthV2.Http.BypassedDRP";
const char kReceivedInsecureOtherHistogramName[] =
"Net.HttpContentLengthV2.Http.Other";
const char kReceivedSecureDirectHistogramName[] =
"Net.HttpContentLengthV2.Https.Direct";
const char kReceivedSecureViaDRPHistogramName[] =
"Net.HttpContentLengthV2.Https.ViaDRP";
const char kReceivedSecureBypassedHistogramName[] =
"Net.HttpContentLengthV2.Https.BypassedDRP";
const char kReceivedSecureOtherHistogramName[] =
"Net.HttpContentLengthV2.Https.Other";
const char kReceivedVideoInsecureDirectHistogramName[] =
"Net.HttpContentLengthV2.Http.Direct.Video";
const char kReceivedVideoInsecureViaDRPHistogramName[] =
"Net.HttpContentLengthV2.Http.ViaDRP.Video";
const char kReceivedVideoInsecureBypassedHistogramName[] =
"Net.HttpContentLengthV2.Http.BypassedDRP.Video";
const char kReceivedVideoInsecureOtherHistogramName[] =
"Net.HttpContentLengthV2.Http.Other.Video";
const char kReceivedVideoSecureDirectHistogramName[] =
"Net.HttpContentLengthV2.Https.Direct.Video";
const char kReceivedVideoSecureViaDRPHistogramName[] =
"Net.HttpContentLengthV2.Https.ViaDRP.Video";
const char kReceivedVideoSecureBypassedHistogramName[] =
"Net.HttpContentLengthV2.Https.BypassedDRP.Video";
const char kReceivedVideoSecureOtherHistogramName[] =
"Net.HttpContentLengthV2.Https.Other.Video";
const char kOriginalHistogramName[] = "Net.HttpOriginalContentLength";
const char kDifferenceHistogramName[] = "Net.HttpContentLengthDifference";
const char kFreshnessLifetimeHistogramName[] =
"Net.HttpContentFreshnessLifetime";
const char kCacheableHistogramName[] = "Net.HttpContentLengthCacheable";
const char kCacheable4HoursHistogramName[] =
"Net.HttpContentLengthCacheable4Hours";
const char kCacheable24HoursHistogramName[] =
"Net.HttpContentLengthCacheable24Hours";
const int64_t kResponseContentLength = 100;
const int64_t kOriginalContentLength = 200;
#if defined(OS_ANDROID)
const Client kClient = Client::CHROME_ANDROID;
#elif defined(OS_IOS)
const Client kClient = Client::CHROME_IOS;
#elif defined(OS_MACOSX)
const Client kClient = Client::CHROME_MAC;
#elif defined(OS_CHROMEOS)
const Client kClient = Client::CHROME_CHROMEOS;
#elif defined(OS_LINUX)
const Client kClient = Client::CHROME_LINUX;
#elif defined(OS_WIN)
const Client kClient = Client::CHROME_WINDOWS;
#elif defined(OS_FREEBSD)
const Client kClient = Client::CHROME_FREEBSD;
#elif defined(OS_OPENBSD)
const Client kClient = Client::CHROME_OPENBSD;
#elif defined(OS_SOLARIS)
const Client kClient = Client::CHROME_SOLARIS;
#elif defined(OS_QNX)
const Client kClient = Client::CHROME_QNX;
#else
const Client kClient = Client::UNKNOWN;
#endif
class TestLoFiDecider : public LoFiDecider {
public:
TestLoFiDecider()
: should_be_client_lofi_(false),
should_be_client_lofi_auto_reload_(false),
should_request_lofi_resource_(false),
ignore_is_using_data_reduction_proxy_check_(false) {}
~TestLoFiDecider() override {}
bool IsUsingLoFi(const net::URLRequest& request) const override {
return should_request_lofi_resource_;
}
void SetIsUsingLoFi(bool should_request_lofi_resource) {
should_request_lofi_resource_ = should_request_lofi_resource;
}
void SetIsUsingClientLoFi(bool should_be_client_lofi) {
should_be_client_lofi_ = should_be_client_lofi;
}
void SetIsClientLoFiAutoReload(bool should_be_client_lofi_auto_reload) {
should_be_client_lofi_auto_reload_ = should_be_client_lofi_auto_reload;
}
void MaybeSetAcceptTransformHeader(
const net::URLRequest& request,
net::HttpRequestHeaders* headers) const override {
if (should_request_lofi_resource_) {
headers->SetHeader(chrome_proxy_accept_transform_header(),
empty_image_directive());
}
}
bool IsSlowPagePreviewRequested(
const net::HttpRequestHeaders& headers) const override {
std::string header_value;
if (headers.GetHeader(chrome_proxy_accept_transform_header(),
&header_value)) {
return header_value == empty_image_directive() ||
header_value == lite_page_directive();
}
return false;
}
bool IsLitePagePreviewRequested(
const net::HttpRequestHeaders& headers) const override {
std::string header_value;
if (headers.GetHeader(chrome_proxy_accept_transform_header(),
&header_value)) {
return header_value == lite_page_directive();
}
return false;
}
void MaybeApplyAMPPreview(
net::URLRequest* request,
GURL* new_url,
previews::PreviewsDecider* previews_decider) const override {
return;
}
void RemoveAcceptTransformHeader(
net::HttpRequestHeaders* headers) const override {
if (ignore_is_using_data_reduction_proxy_check_)
return;
headers->RemoveHeader(chrome_proxy_accept_transform_header());
}
bool ShouldRecordLoFiUMA(const net::URLRequest& request) const override {
return should_request_lofi_resource_;
}
bool IsClientLoFiImageRequest(const net::URLRequest& request) const override {
return should_be_client_lofi_;
}
bool IsClientLoFiAutoReloadRequest(
const net::URLRequest& request) const override {
return should_be_client_lofi_auto_reload_;
}
void ignore_is_using_data_reduction_proxy_check() {
ignore_is_using_data_reduction_proxy_check_ = true;
}
private:
bool should_be_client_lofi_;
bool should_be_client_lofi_auto_reload_;
bool should_request_lofi_resource_;
bool ignore_is_using_data_reduction_proxy_check_;
};
class TestLoFiUIService : public LoFiUIService {
public:
TestLoFiUIService() : on_lofi_response_(false) {}
~TestLoFiUIService() override {}
bool DidNotifyLoFiResponse() const { return on_lofi_response_; }
void OnLoFiReponseReceived(const net::URLRequest& request) override {
on_lofi_response_ = true;
}
void ClearResponse() { on_lofi_response_ = false; }
private:
bool on_lofi_response_;
};
class TestPreviewsDecider : public previews::PreviewsDecider {
public:
TestPreviewsDecider() {}
~TestPreviewsDecider() override {}
// previews::PreviewsDecider:
bool ShouldAllowPreviewAtECT(
const net::URLRequest& request,
previews::PreviewsType type,
net::EffectiveConnectionType effective_connection_type_threshold,
const std::vector<std::string>& host_blacklist_from_server)
const override {
return true;
}
// Same as ShouldAllowPreviewAtECT, but uses the previews default
// EffectiveConnectionType and no blacklisted hosts from the server.
bool ShouldAllowPreview(const net::URLRequest& request,
previews::PreviewsType type) const override {
return true;
}
};
enum ProxyTestConfig { USE_SECURE_PROXY, USE_INSECURE_PROXY, BYPASS_PROXY };
class DataReductionProxyNetworkDelegateTest : public testing::Test {
public:
DataReductionProxyNetworkDelegateTest()
: lofi_decider_(nullptr),
lofi_ui_service_(nullptr),
ssl_socket_data_provider_(net::ASYNC, net::OK) {
ssl_socket_data_provider_.next_proto = net::kProtoHTTP11;
ssl_socket_data_provider_.ssl_info.cert = net::ImportCertFromFile(
net::GetTestCertsDirectory(), "unittest.selfsigned.der");
}
void Init(ProxyTestConfig proxy_config, bool enable_brotli_globally) {
net::ProxyServer proxy_server;
switch (proxy_config) {
case BYPASS_PROXY:
proxy_server = net::ProxyServer::Direct();
break;
case USE_SECURE_PROXY:
proxy_server = net::ProxyServer::FromURI(
"https://origin.net:443", net::ProxyServer::SCHEME_HTTPS);
break;
case USE_INSECURE_PROXY:
proxy_server = net::ProxyServer::FromURI("http://origin.net:80",
net::ProxyServer::SCHEME_HTTP);
break;
}
context_.reset(new net::TestURLRequestContext(true));
context_storage_.reset(new net::URLRequestContextStorage(context_.get()));
proxy_resolution_service_ = net::ProxyResolutionService::CreateFixedFromPacResult(
proxy_server.ToPacString());
context_->set_proxy_resolution_service(proxy_resolution_service_.get());
context_->set_network_quality_estimator(&test_network_quality_estimator_);
mock_socket_factory_.reset(new net::MockClientSocketFactory());
DataReductionProxyTestContext::Builder builder;
builder = builder.WithClient(kClient)
.WithMockClientSocketFactory(mock_socket_factory_.get())
.WithURLRequestContext(context_.get());
if (proxy_config != BYPASS_PROXY) {
builder = builder.WithProxiesForHttp({DataReductionProxyServer(
proxy_server, ProxyServer::UNSPECIFIED_TYPE)});
}
test_context_ = builder.Build();
context_->set_client_socket_factory(mock_socket_factory_.get());
test_context_->AttachToURLRequestContext(context_storage_.get());
std::unique_ptr<TestLoFiDecider> lofi_decider(new TestLoFiDecider());
lofi_decider_ = lofi_decider.get();
test_context_->io_data()->set_lofi_decider(std::move(lofi_decider));
std::unique_ptr<TestLoFiUIService> lofi_ui_service(new TestLoFiUIService());
lofi_ui_service_ = lofi_ui_service.get();
test_context_->io_data()->set_lofi_ui_service(std::move(lofi_ui_service));
context_->set_enable_brotli(enable_brotli_globally);
context_->Init();
test_context_->DisableWarmupURLFetch();
test_context_->EnableDataReductionProxyWithSecureProxyCheckSuccess();
}
// Build the sockets by adding appropriate mock data for
// |effective_connection_types.size()| number of requests. Data for
// chrome-Proxy-ect header is added to the mock data if |expect_ect_header|
// is true. |reads_list|, |mock_writes| and |writes_list| should be empty, and
// are owned by the caller.
void BuildSocket(const std::string& response_headers,
const std::string& response_body,
bool expect_ect_header,
const std::vector<net::EffectiveConnectionType>&
effective_connection_types,
std::vector<net::MockRead>* reads_list,
std::vector<std::string>* mock_writes,
std::vector<net::MockWrite>* writes_list) {
EXPECT_LT(0u, effective_connection_types.size());
EXPECT_TRUE(reads_list->empty());
EXPECT_TRUE(mock_writes->empty());
EXPECT_TRUE(writes_list->empty());
for (size_t i = 0; i < effective_connection_types.size(); ++i) {
reads_list->push_back(net::MockRead(response_headers.c_str()));
reads_list->push_back(net::MockRead(response_body.c_str()));
}
reads_list->push_back(net::MockRead(net::SYNCHRONOUS, net::OK));
std::string prefix = std::string("GET ")
.append(kTestURL)
.append(" HTTP/1.1\r\n")
.append("Host: ")
.append(GURL(kTestURL).host())
.append(
"\r\n"
"Proxy-Connection: keep-alive\r\n"
"User-Agent:\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept-Language: en-us,fr\r\n");
if (io_data()->test_request_options()->GetHeaderValueForTesting().empty()) {
// Force regeneration of Chrome-Proxy header.
io_data()->test_request_options()->SetSecureSession("123");
}
EXPECT_FALSE(
io_data()->test_request_options()->GetHeaderValueForTesting().empty());
std::string suffix =
std::string("Chrome-Proxy: ") +
io_data()->test_request_options()->GetHeaderValueForTesting() +
std::string("\r\n\r\n");
mock_socket_factory_->AddSSLSocketDataProvider(&ssl_socket_data_provider_);
for (net::EffectiveConnectionType effective_connection_type :
effective_connection_types) {
std::string ect_header;
if (expect_ect_header) {
ect_header = "chrome-proxy-ect: " +
std::string(net::GetNameForEffectiveConnectionType(
effective_connection_type)) +
"\r\n";
}
std::string mock_write = prefix + ect_header + suffix;
mock_writes->push_back(mock_write);
writes_list->push_back(net::MockWrite(mock_writes->back().c_str()));
}
EXPECT_FALSE(socket_);
socket_ = std::make_unique<net::StaticSocketDataProvider>(
reads_list->data(), reads_list->size(), writes_list->data(),
writes_list->size());
mock_socket_factory_->AddSocketDataProvider(socket_.get());
}
static void VerifyHeaders(bool expected_data_reduction_proxy_used,
bool expected_lofi_used,
const net::HttpRequestHeaders& headers) {
EXPECT_EQ(expected_data_reduction_proxy_used,
headers.HasHeader(chrome_proxy_header()));
std::string header_value;
headers.GetHeader(chrome_proxy_accept_transform_header(), &header_value);
EXPECT_EQ(expected_data_reduction_proxy_used && expected_lofi_used,
header_value.find("empty-image") != std::string::npos);
}
void VerifyDidNotifyLoFiResponse(bool lofi_response) const {
EXPECT_EQ(lofi_response, lofi_ui_service_->DidNotifyLoFiResponse());
}
void ClearLoFiUIService() { lofi_ui_service_->ClearResponse(); }
void VerifyDataReductionProxyData(const net::URLRequest& request,
bool data_reduction_proxy_used,
bool lofi_used) {
DataReductionProxyData* data = DataReductionProxyData::GetData(request);
if (!data_reduction_proxy_used) {
EXPECT_FALSE(data);
} else {
EXPECT_TRUE(data->used_data_reduction_proxy());
EXPECT_EQ(lofi_used, data->lofi_requested());
}
}
// Each line in |response_headers| should end with "\r\n" and not '\0', and
// the last line should have a second "\r\n".
// An empty |response_headers| is allowed. It works by making this look like
// an HTTP/0.9 response, since HTTP/0.9 responses don't have headers.
std::unique_ptr<net::URLRequest> FetchURLRequest(
const GURL& url,
net::HttpRequestHeaders* request_headers,
const std::string& response_headers,
int64_t response_content_length,
int load_flags) {
const std::string response_body(
base::checked_cast<size_t>(response_content_length), ' ');
net::MockRead reads[] = {net::MockRead(response_headers.c_str()),
net::MockRead(response_body.c_str()),
net::MockRead(net::SYNCHRONOUS, net::OK)};
net::StaticSocketDataProvider socket(reads, arraysize(reads), nullptr, 0);
mock_socket_factory_->AddSocketDataProvider(&socket);
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> request = context_->CreateRequest(
url, net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
if (request_headers)
request->SetExtraRequestHeaders(*request_headers);
request->SetLoadFlags(request->load_flags() | load_flags);
request->Start();
base::RunLoop().RunUntilIdle();
return request;
}
// Reads brotli encoded content to |encoded_brotli_buffer_|.
void ReadBrotliFile() {
// Get the path of data directory.
const size_t kDefaultBufferSize = 4096;
base::FilePath data_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &data_dir);
data_dir = data_dir.AppendASCII("net");
data_dir = data_dir.AppendASCII("data");
data_dir = data_dir.AppendASCII("filter_unittests");
// Read data from the encoded file into buffer.
base::FilePath encoded_file_path;
encoded_file_path = data_dir.AppendASCII("google.br");
ASSERT_TRUE(
base::ReadFileToString(encoded_file_path, &encoded_brotli_buffer_));
ASSERT_GE(kDefaultBufferSize, encoded_brotli_buffer_.size());
}
// Fetches a single URL request, verifies the correctness of Accept-Encoding
// header, and verifies that the response is cached only if |expect_cached|
// is set to true. Each line in |response_headers| should end with "\r\n" and
// not '\0', and the last line should have a second "\r\n". An empty
// |response_headers| is allowed. It works by making this look like an
// HTTP/0.9 response, since HTTP/0.9 responses don't have headers.
void FetchURLRequestAndVerifyBrotli(net::HttpRequestHeaders* request_headers,
const std::string& response_headers,
bool expect_cached,
bool expect_brotli) {
test_network_quality_estimator()->set_effective_connection_type(
net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN);
GURL url(kTestURL);
int response_body_size = 140;
std::string response_body;
if (expect_brotli && !expect_cached) {
response_body = encoded_brotli_buffer_;
response_body_size = response_body.size();
} else {
response_body =
std::string(base::checked_cast<size_t>(response_body_size), ' ');
}
mock_socket_factory_->AddSSLSocketDataProvider(&ssl_socket_data_provider_);
net::MockRead reads[] = {net::MockRead(response_headers.c_str()),
net::MockRead(response_body.c_str()),
net::MockRead(net::SYNCHRONOUS, net::OK)};
if (io_data()->test_request_options()->GetHeaderValueForTesting().empty()) {
// Force regeneration of Chrome-Proxy header.
io_data()->test_request_options()->SetSecureSession("123");
}
EXPECT_FALSE(
io_data()->test_request_options()->GetHeaderValueForTesting().empty());
std::string host = GURL(kTestURL).host();
std::string prefix_headers = std::string("GET ")
.append(kTestURL)
.append(
" HTTP/1.1\r\n"
"Host: ")
.append(host)
.append(
"\r\n"
"Proxy-Connection: keep-alive\r\n"
"User-Agent:\r\n");
std::string accept_language_header("Accept-Language: en-us,fr\r\n");
std::string ect_header = "chrome-proxy-ect: " +
std::string(net::GetNameForEffectiveConnectionType(
net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN)) +
"\r\n";
// Brotli is included in accept-encoding header only if the request went
// to the network (i.e., it was not a cached response), and if data
// reduction ptroxy network delegate added Brotli to the header.
std::string accept_encoding_header =
expect_brotli && !expect_cached
? "Accept-Encoding: gzip, deflate, br\r\n"
: "Accept-Encoding: gzip, deflate\r\n";
std::string suffix_headers =
std::string("Chrome-Proxy: ") +
io_data()->test_request_options()->GetHeaderValueForTesting() +
std::string("\r\n\r\n");
std::string mock_write = prefix_headers + accept_language_header +
ect_header + accept_encoding_header +
suffix_headers;
if (expect_cached || !expect_brotli) {
// Order of headers is different if the headers were modified by data
// reduction proxy network delegate.
mock_write = prefix_headers + accept_encoding_header +
accept_language_header + ect_header + suffix_headers;
}
net::MockWrite writes[] = {net::MockWrite(mock_write.c_str())};
net::StaticSocketDataProvider socket(reads, arraysize(reads), writes,
arraysize(writes));
mock_socket_factory_->AddSocketDataProvider(&socket);
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> request = context_->CreateRequest(
url, net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
if (request_headers)
request->SetExtraRequestHeaders(*request_headers);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, request->status().ToNetError());
if (!expect_cached) {
EXPECT_EQ(response_body_size,
request->received_response_content_length());
EXPECT_NE(0, request->GetTotalSentBytes());
EXPECT_NE(0, request->GetTotalReceivedBytes());
EXPECT_FALSE(request->was_cached());
VerifyBrotliPresent(request.get(), expect_brotli);
} else {
EXPECT_TRUE(request->was_cached());
std::string content_encoding_value;
request->GetResponseHeaderByName("Content-Encoding",
&content_encoding_value);
EXPECT_EQ(expect_brotli, content_encoding_value == "br");
}
}
void VerifyBrotliPresent(net::URLRequest* request, bool expect_brotli) {
net::HttpRequestHeaders request_headers_sent;
EXPECT_TRUE(request->GetFullRequestHeaders(&request_headers_sent));
std::string accept_encoding_value;
EXPECT_TRUE(request_headers_sent.GetHeader("Accept-Encoding",
&accept_encoding_value));
EXPECT_NE(std::string::npos, accept_encoding_value.find("gzip"));
std::string content_encoding_value;
request->GetResponseHeaderByName("Content-Encoding",
&content_encoding_value);
if (expect_brotli) {
// Brotli should be the last entry in the Accept-Encoding header.
EXPECT_EQ(accept_encoding_value.length() - 2,
accept_encoding_value.find("br"));
EXPECT_EQ("br", content_encoding_value);
} else {
EXPECT_EQ(std::string::npos, accept_encoding_value.find("br"));
}
}
void FetchURLRequestAndVerifyPageIdDirective(base::Optional<uint64_t> page_id,
bool redirect_once) {
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"Cache-Control: max-age=1200\r\n"
"Vary: accept-encoding\r\n\r\n";
GURL url(kTestURL);
int response_body_size = 140;
std::string response_body =
std::string(base::checked_cast<size_t>(response_body_size), ' ');
mock_socket_factory_->AddSSLSocketDataProvider(&ssl_socket_data_provider_);
net::MockRead redirect_reads[] = {
net::MockRead("HTTP/1.1 302 Redirect\r\n"),
net::MockRead("Location: http://www.google.com/\r\n"),
net::MockRead("Content-Length: 0\r\n\r\n"),
net::MockRead(net::SYNCHRONOUS, net::OK),
net::MockRead(response_headers.c_str()),
net::MockRead(response_body.c_str()),
net::MockRead(net::SYNCHRONOUS, net::OK)};
net::MockRead reads[] = {net::MockRead(response_headers.c_str()),
net::MockRead(response_body.c_str()),
net::MockRead(net::SYNCHRONOUS, net::OK)};
EXPECT_FALSE(
io_data()->test_request_options()->GetHeaderValueForTesting().empty());
std::string page_id_value;
if (page_id) {
char page_id_buffer[17];
if (base::strings::SafeSPrintf(page_id_buffer, "%x", page_id.value()) >
0) {
page_id_value = std::string("pid=") + page_id_buffer;
}
}
std::string mock_write =
"GET http://www.google.com/ HTTP/1.1\r\nHost: "
"www.google.com\r\nProxy-Connection: "
"keep-alive\r\nUser-Agent:\r\nAccept-Encoding: gzip, "
"deflate\r\nAccept-Language: en-us,fr\r\n"
"chrome-proxy-ect: 4G\r\n"
"Chrome-Proxy: " +
io_data()->test_request_options()->GetHeaderValueForTesting() +
(page_id_value.empty() ? "" : (", " + page_id_value)) + "\r\n\r\n";
net::MockWrite redirect_writes[] = {net::MockWrite(mock_write.c_str()),
net::MockWrite(mock_write.c_str())};
net::MockWrite writes[] = {net::MockWrite(mock_write.c_str())};
std::unique_ptr<net::StaticSocketDataProvider> socket;
if (!redirect_once) {
socket = std::make_unique<net::StaticSocketDataProvider>(
reads, arraysize(reads), writes, arraysize(writes));
} else {
socket = std::make_unique<net::StaticSocketDataProvider>(
redirect_reads, arraysize(redirect_reads), redirect_writes,
arraysize(redirect_writes));
}
mock_socket_factory_->AddSocketDataProvider(socket.get());
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> request = context_->CreateRequest(
url, net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
if (!page_id_value.empty()) {
request->SetLoadFlags(request->load_flags() |
net::LOAD_MAIN_FRAME_DEPRECATED);
}
request->Start();
base::RunLoop().RunUntilIdle();
}
// Fetches a request while the effective connection type is set to
// |effective_connection_type|. Verifies that the request headers include the
// chrome-proxy-ect header only if |expect_ect_header| is true. The response
// must be served from the cache if |expect_cached| is true.
void FetchURLRequestAndVerifyECTHeader(
net::EffectiveConnectionType effective_connection_type,
bool expect_ect_header,
bool expect_cached) {
test_network_quality_estimator()->set_effective_connection_type(
effective_connection_type);
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> request = context_->CreateRequest(
GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(140, request->received_response_content_length());
EXPECT_EQ(expect_cached, request->was_cached());
EXPECT_EQ(expect_cached, request->GetTotalSentBytes() == 0);
EXPECT_EQ(expect_cached, request->GetTotalReceivedBytes() == 0);
net::HttpRequestHeaders sent_request_headers;
EXPECT_NE(expect_cached,
request->GetFullRequestHeaders(&sent_request_headers));
if (expect_cached) {
// Request headers are missing. Return since there is nothing left to
// check.
return;
}
// Verify that chrome-proxy-ect header is present in the request headers
// only if |expect_ect_header| is true.
std::string ect_value;
EXPECT_EQ(expect_ect_header, sent_request_headers.GetHeader(
chrome_proxy_ect_header(), &ect_value));
if (!expect_ect_header)
return;
EXPECT_EQ(net::GetNameForEffectiveConnectionType(effective_connection_type),
ect_value);
}
void DelegateStageDone(int result) {}
void NotifyNetworkDelegate(net::URLRequest* request,
const net::ProxyInfo& data_reduction_proxy_info,
const net::ProxyRetryInfoMap& proxy_retry_info,
net::HttpRequestHeaders* headers) {
network_delegate()->NotifyBeforeURLRequest(
request,
base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone,
base::Unretained(this)),
nullptr);
network_delegate()->NotifyBeforeStartTransaction(
request,
base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone,
base::Unretained(this)),
headers);
network_delegate()->NotifyBeforeSendHeaders(
request, data_reduction_proxy_info, proxy_retry_info, headers);
}
net::MockClientSocketFactory* mock_socket_factory() {
return mock_socket_factory_.get();
}
net::TestURLRequestContext* context() { return context_.get(); }
net::NetworkDelegate* network_delegate() const {
return context_->network_delegate();
}
TestDataReductionProxyParams* params() const {
return test_context_->config()->test_params();
}
TestDataReductionProxyConfig* config() const {
return test_context_->config();
}
TestDataReductionProxyIOData* io_data() const {
return test_context_->io_data();
}
TestLoFiDecider* lofi_decider() const { return lofi_decider_; }
net::TestNetworkQualityEstimator* test_network_quality_estimator() {
return &test_network_quality_estimator_;
}
net::SSLSocketDataProvider* ssl_socket_data_provider() {
return &ssl_socket_data_provider_;
}
private:
base::MessageLoopForIO message_loop_;
std::unique_ptr<net::MockClientSocketFactory> mock_socket_factory_;
std::unique_ptr<net::ProxyResolutionService> proxy_resolution_service_;
std::unique_ptr<net::TestURLRequestContext> context_;
std::unique_ptr<net::URLRequestContextStorage> context_storage_;
TestLoFiDecider* lofi_decider_;
TestLoFiUIService* lofi_ui_service_;
std::unique_ptr<DataReductionProxyTestContext> test_context_;
net::TestNetworkQualityEstimator test_network_quality_estimator_;
net::SSLSocketDataProvider ssl_socket_data_provider_;
std::unique_ptr<net::StaticSocketDataProvider> socket_;
// Encoded Brotli content read from a file. May be empty.
std::string encoded_brotli_buffer_;
};
TEST_F(DataReductionProxyNetworkDelegateTest, AuthenticationTest) {
Init(USE_INSECURE_PROXY, false);
std::unique_ptr<net::URLRequest> fake_request(
FetchURLRequest(GURL(kTestURL), nullptr, std::string(), 0, 0));
net::ProxyInfo data_reduction_proxy_info;
net::ProxyRetryInfoMap proxy_retry_info;
std::string data_reduction_proxy;
data_reduction_proxy_info.UseProxyServer(
params()->proxies_for_http().front().proxy_server());
net::HttpRequestHeaders headers;
// Call network delegate methods to ensure that appropriate chrome proxy
// headers get added/removed.
network_delegate()->NotifyBeforeStartTransaction(
fake_request.get(),
base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone,
base::Unretained(this)),
&headers);
network_delegate()->NotifyBeforeSendHeaders(fake_request.get(),
data_reduction_proxy_info,
proxy_retry_info, &headers);
EXPECT_TRUE(headers.HasHeader(chrome_proxy_header()));
std::string header_value;
headers.GetHeader(chrome_proxy_header(), &header_value);
EXPECT_TRUE(header_value.find("ps=") != std::string::npos);
EXPECT_TRUE(header_value.find("sid=") != std::string::npos);
}
TEST_F(DataReductionProxyNetworkDelegateTest, LoFiTransitions) {
Init(USE_INSECURE_PROXY, false);
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitWithFeatures(
{previews::features::kPreviews,
features::kDataReductionProxyDecidesTransform},
{});
// Enable Lo-Fi.
bool is_data_reduction_proxy_enabled[] = {false, true};
for (size_t i = 0; i < arraysize(is_data_reduction_proxy_enabled); ++i) {
net::ProxyInfo data_reduction_proxy_info;
std::string proxy;
if (is_data_reduction_proxy_enabled[i]) {
data_reduction_proxy_info.UseProxyServer(
params()->proxies_for_http().front().proxy_server());
} else {
base::TrimString(kOtherProxy, "/", &proxy);
data_reduction_proxy_info.UseNamedProxy(proxy);
}
// Needed as a parameter, but functionality is not tested.
TestPreviewsDecider test_previews_decider;
{
// Main frame loaded. Lo-Fi should be used.
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest(
GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
fake_request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED);
lofi_decider()->SetIsUsingLoFi(config()->ShouldAcceptServerPreview(
*fake_request.get(), test_previews_decider));
NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info,
proxy_retry_info, &headers);
VerifyHeaders(is_data_reduction_proxy_enabled[i], true, headers);
VerifyDataReductionProxyData(
*fake_request, is_data_reduction_proxy_enabled[i],
config()->ShouldAcceptServerPreview(*fake_request.get(),
test_previews_decider));
}
{
// Lo-Fi is already off. Lo-Fi should not be used.
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest(
GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
lofi_decider()->SetIsUsingLoFi(false);
NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info,
proxy_retry_info, &headers);
VerifyHeaders(is_data_reduction_proxy_enabled[i], false, headers);
VerifyDataReductionProxyData(*fake_request,
is_data_reduction_proxy_enabled[i], false);
}
{
// Lo-Fi is already on. Lo-Fi should be used.
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest(
GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
lofi_decider()->SetIsUsingLoFi(true);
NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info,
proxy_retry_info, &headers);
VerifyHeaders(is_data_reduction_proxy_enabled[i], true, headers);
VerifyDataReductionProxyData(*fake_request,
is_data_reduction_proxy_enabled[i], true);
}
{
// Main frame request with Lo-Fi off. Lo-Fi should not be used.
// State of Lo-Fi should persist until next page load.
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest(
GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
fake_request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED);
lofi_decider()->SetIsUsingLoFi(false);
NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info,
proxy_retry_info, &headers);
VerifyHeaders(is_data_reduction_proxy_enabled[i], false, headers);
VerifyDataReductionProxyData(*fake_request,
is_data_reduction_proxy_enabled[i], false);
}
{
// Lo-Fi is off. Lo-Fi is still not used.
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest(
GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
lofi_decider()->SetIsUsingLoFi(false);
NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info,
proxy_retry_info, &headers);
VerifyHeaders(is_data_reduction_proxy_enabled[i], false, headers);
VerifyDataReductionProxyData(*fake_request,
is_data_reduction_proxy_enabled[i], false);
}
{
// Main frame request. Lo-Fi should be used.
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
net::TestDelegate delegate;
std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest(
GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
fake_request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED);
lofi_decider()->SetIsUsingLoFi(config()->ShouldAcceptServerPreview(
*fake_request.get(), test_previews_decider));
NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info,
proxy_retry_info, &headers);
VerifyDataReductionProxyData(
*fake_request, is_data_reduction_proxy_enabled[i],
config()->ShouldAcceptServerPreview(*fake_request.get(),
test_previews_decider));
}
}
}
TEST_F(DataReductionProxyNetworkDelegateTest, RequestDataConfigurations) {
Init(USE_INSECURE_PROXY, false);
const struct {
bool lofi_on;
bool used_data_reduction_proxy;
bool main_frame;
} tests[] = {
// Lo-Fi off. Main Frame Request.
{false, true, true},
// Data reduction proxy not used. Main Frame Request.
{false, false, true},
// Data reduction proxy not used, Lo-Fi should not be used. Main Frame
// Request.
{true, false, true},
// Lo-Fi on. Main Frame Request.
{true, true, true},
// Lo-Fi off. Not a Main Frame Request.
{false, true, false},
// Data reduction proxy not used. Not a Main Frame Request.
{false, false, false},
// Data reduction proxy not used, Lo-Fi should not be used. Not a Main
// Frame Request.
{true, false, false},
// Lo-Fi on. Not a Main Frame Request.
{true, true, false},
};
for (const auto& test : tests) {
net::ProxyInfo data_reduction_proxy_info;
if (test.used_data_reduction_proxy) {
data_reduction_proxy_info.UseProxyServer(
params()->proxies_for_http().front().proxy_server());
} else {
data_reduction_proxy_info.UseNamedProxy("port.of.other.proxy");
}
// Main frame loaded. Lo-Fi should be used.
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
test_network_quality_estimator()->set_effective_connection_type(
net::EFFECTIVE_CONNECTION_TYPE_OFFLINE);
std::unique_ptr<net::URLRequest> request =
context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE,
nullptr, TRAFFIC_ANNOTATION_FOR_TESTS);
request->SetLoadFlags(test.main_frame ? net::LOAD_MAIN_FRAME_DEPRECATED
: 0);
lofi_decider()->SetIsUsingLoFi(test.lofi_on);
io_data()->request_options()->SetSecureSession("fake-session");
// Call network delegate methods to ensure that appropriate chrome proxy
// headers get added/removed.
network_delegate()->NotifyBeforeStartTransaction(
request.get(),
base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone,
base::Unretained(this)),
&headers);
network_delegate()->NotifyBeforeSendHeaders(
request.get(), data_reduction_proxy_info, proxy_retry_info, &headers);
DataReductionProxyData* data =
DataReductionProxyData::GetData(*request.get());
if (!test.used_data_reduction_proxy) {
EXPECT_FALSE(data);
} else {
EXPECT_TRUE(data);
EXPECT_EQ(test.main_frame ? net::EFFECTIVE_CONNECTION_TYPE_OFFLINE
: net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN,
data->effective_connection_type());
EXPECT_TRUE(data->used_data_reduction_proxy());
EXPECT_EQ(test.main_frame ? GURL(kTestURL) : GURL(), data->request_url());
EXPECT_EQ(test.main_frame ? "fake-session" : "", data->session_key());
EXPECT_EQ(test.lofi_on, data->lofi_requested());
}
}
}
TEST_F(DataReductionProxyNetworkDelegateTest,
RequestDataHoldbackConfigurations) {
Init(USE_INSECURE_PROXY, false);
const struct {
bool data_reduction_proxy_enabled;
bool used_direct;
} tests[] = {
{
false, true,
},
{
false, false,
},
{
true, false,
},
{
true, true,
},
};
test_network_quality_estimator()->set_effective_connection_type(
net::EFFECTIVE_CONNECTION_TYPE_4G);
base::FieldTrialList field_trial_list(nullptr);
ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
"DataCompressionProxyHoldback", "Enabled"));
for (const auto& test : tests) {
net::ProxyInfo data_reduction_proxy_info;
if (test.used_direct)
data_reduction_proxy_info.UseDirect();
else
data_reduction_proxy_info.UseNamedProxy("some.other.proxy");
config()->UpdateConfigForTesting(test.data_reduction_proxy_enabled, true,
true);
std::unique_ptr<net::URLRequest> request =
context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE,
nullptr, TRAFFIC_ANNOTATION_FOR_TESTS);
request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED);
request->set_method("GET");
io_data()->request_options()->SetSecureSession("fake-session");
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
network_delegate()->NotifyBeforeSendHeaders(
request.get(), data_reduction_proxy_info, proxy_retry_info, &headers);
DataReductionProxyData* data =
DataReductionProxyData::GetData(*request.get());
if (!test.data_reduction_proxy_enabled || !test.used_direct) {
EXPECT_FALSE(data);
} else {
EXPECT_TRUE(data);
EXPECT_TRUE(data->used_data_reduction_proxy());
EXPECT_EQ("fake-session", data->session_key());
EXPECT_EQ(GURL(kTestURL), data->request_url());
EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_4G,
data->effective_connection_type());
EXPECT_TRUE(data->page_id());
}
}
}
TEST_F(DataReductionProxyNetworkDelegateTest, RedirectRequestDataCleared) {
Init(USE_INSECURE_PROXY, false);
net::ProxyInfo data_reduction_proxy_info;
data_reduction_proxy_info.UseProxyServer(
params()->proxies_for_http().front().proxy_server());
// Main frame loaded. Lo-Fi should be used.
net::HttpRequestHeaders headers_original;
net::ProxyRetryInfoMap proxy_retry_info;
test_network_quality_estimator()->set_effective_connection_type(
net::EFFECTIVE_CONNECTION_TYPE_OFFLINE);
std::unique_ptr<net::URLRequest> request =
context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE,
nullptr, TRAFFIC_ANNOTATION_FOR_TESTS);
request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED);
lofi_decider()->SetIsUsingLoFi(true);
io_data()->request_options()->SetSecureSession("fake-session");
// Call network delegate methods to ensure that appropriate chrome proxy
// headers get added/removed.
network_delegate()->NotifyBeforeStartTransaction(
request.get(),
base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone,
base::Unretained(this)),
&headers_original);
network_delegate()->NotifyBeforeSendHeaders(
request.get(), data_reduction_proxy_info, proxy_retry_info,
&headers_original);
DataReductionProxyData* data =
DataReductionProxyData::GetData(*request.get());
EXPECT_TRUE(data);
EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_OFFLINE,
data->effective_connection_type());
EXPECT_TRUE(data->used_data_reduction_proxy());
EXPECT_EQ(GURL(kTestURL), data->request_url());
EXPECT_EQ("fake-session", data->session_key());
EXPECT_TRUE(data->lofi_requested());
data_reduction_proxy_info.UseNamedProxy("port.of.other.proxy");
// Simulate a redirect even though the same URL is used. Should clear
// DataReductionProxyData.
network_delegate()->NotifyBeforeRedirect(request.get(), GURL(kTestURL));
data = DataReductionProxyData::GetData(*request.get());
EXPECT_FALSE(data && data->used_data_reduction_proxy());
// Call NotifyBeforeSendHeaders again with different proxy info to check that
// new data isn't added. Use a new set of headers since the redirected HTTP
// jobs do not reuse headers from the previous jobs. Also, call network
// delegate methods to ensure that appropriate chrome proxy headers get
// added/removed.
net::HttpRequestHeaders headers_redirect;
network_delegate()->NotifyBeforeStartTransaction(
request.get(),
base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone,
base::Unretained(this)),
&headers_redirect);
network_delegate()->NotifyBeforeSendHeaders(
request.get(), data_reduction_proxy_info, proxy_retry_info,
&headers_redirect);
data = DataReductionProxyData::GetData(*request.get());
EXPECT_FALSE(data);
}
TEST_F(DataReductionProxyNetworkDelegateTest, NetHistograms) {
Init(USE_INSECURE_PROXY, false);
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitWithFeatures(
{previews::features::kPreviews,
features::kDataReductionProxyDecidesTransform},
{});
base::HistogramTester histogram_tester;
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: " +
base::Int64ToString(kOriginalContentLength) + "\r\n\r\n";
std::unique_ptr<net::URLRequest> fake_request(FetchURLRequest(
GURL(kTestURL), nullptr, response_headers, kResponseContentLength, 0));
fake_request->SetLoadFlags(fake_request->load_flags() |
net::LOAD_MAIN_FRAME_DEPRECATED);
base::TimeDelta freshness_lifetime =
fake_request->response_info().headers->GetFreshnessLifetimes(
fake_request->response_info().response_time).freshness;
histogram_tester.ExpectUniqueSample(kReceivedValidOCLHistogramName,
kResponseContentLength, 1);
histogram_tester.ExpectUniqueSample(kOriginalValidOCLHistogramName,
kOriginalContentLength, 1);
histogram_tester.ExpectUniqueSample(kOriginalInsecureViaDRPHistogramName,
kOriginalContentLength, 1);
histogram_tester.ExpectUniqueSample(
kDifferenceValidOCLHistogramName,
kOriginalContentLength - kResponseContentLength, 1);
histogram_tester.ExpectUniqueSample(kReceivedHistogramName,
kResponseContentLength, 1);
histogram_tester.ExpectUniqueSample(kReceivedInsecureViaDRPHistogramName,
kResponseContentLength, 1);
histogram_tester.ExpectTotalCount(kReceivedInsecureDirectHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedSecureDirectHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedVideoInsecureViaDRPHistogramName,
0);
histogram_tester.ExpectUniqueSample(kReceivedInsecureViaDRPHistogramName,
kResponseContentLength, 1);
histogram_tester.ExpectUniqueSample(kOriginalHistogramName,
kOriginalContentLength, 1);
histogram_tester.ExpectUniqueSample(
kDifferenceHistogramName,
kOriginalContentLength - kResponseContentLength, 1);
histogram_tester.ExpectUniqueSample(kFreshnessLifetimeHistogramName,
freshness_lifetime.InSeconds(), 1);
histogram_tester.ExpectUniqueSample(kCacheableHistogramName,
kResponseContentLength, 1);
histogram_tester.ExpectUniqueSample(kCacheable4HoursHistogramName,
kResponseContentLength, 1);
histogram_tester.ExpectUniqueSample(kCacheable24HoursHistogramName,
kResponseContentLength, 1);
// Check Lo-Fi histograms.
const struct {
bool lofi_enabled;
int expected_count;
} tests[] = {
{
// Lo-Fi disabled.
false, 0,
},
{
// Lo-Fi enabled so should populate Lo-Fi content length histogram.
true, 1,
},
};
for (size_t i = 0; i < arraysize(tests); ++i) {
base::test::ScopedFeatureList scoped_feature_list;
if (tests[i].lofi_enabled) {
scoped_feature_list.InitAndEnableFeature(
features::kDataReductionProxyDecidesTransform);
} else {
scoped_feature_list.InitAndDisableFeature(
features::kDataReductionProxyDecidesTransform);
}
// Needed as a parameter, but functionality is not tested.
TestPreviewsDecider test_previews_decider;
lofi_decider()->SetIsUsingLoFi(config()->ShouldAcceptServerPreview(
*fake_request.get(), test_previews_decider));
fake_request = (FetchURLRequest(GURL(kTestURL), nullptr, response_headers,
kResponseContentLength, 0));
fake_request->SetLoadFlags(fake_request->load_flags() |
net::LOAD_MAIN_FRAME_DEPRECATED);
// Histograms are accumulative, so get the sum of all the tests so far.
int expected_count = 0;
for (size_t j = 0; j <= i; ++j)
expected_count += tests[j].expected_count;
if (expected_count == 0) {
histogram_tester.ExpectTotalCount(kReceivedValidOCLLoFiOnHistogramName,
expected_count);
histogram_tester.ExpectTotalCount(kOriginalValidOCLLoFiOnHistogramName,
expected_count);
histogram_tester.ExpectTotalCount(kDifferenceValidOCLLoFiOnHistogramName,
expected_count);
} else {
histogram_tester.ExpectUniqueSample(kReceivedValidOCLLoFiOnHistogramName,
kResponseContentLength,
expected_count);
histogram_tester.ExpectUniqueSample(kOriginalValidOCLLoFiOnHistogramName,
kOriginalContentLength,
expected_count);
histogram_tester.ExpectUniqueSample(
kDifferenceValidOCLLoFiOnHistogramName,
kOriginalContentLength - kResponseContentLength, expected_count);
}
}
}
TEST_F(DataReductionProxyNetworkDelegateTest, NetVideoHistograms) {
Init(USE_INSECURE_PROXY, false);
base::HistogramTester histogram_tester;
// Check video
std::string video_response_headers =
"HTTP/1.1 200 OK\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Content-Type: video/mp4\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: " +
base::Int64ToString(kOriginalContentLength) + "\r\n\r\n";
FetchURLRequest(GURL(kTestURL), nullptr, video_response_headers,
kResponseContentLength, 0);
histogram_tester.ExpectUniqueSample(kReceivedInsecureViaDRPHistogramName,
kResponseContentLength, 1);
histogram_tester.ExpectTotalCount(kReceivedInsecureDirectHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedInsecureBypassedHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedInsecureOtherHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedSecureViaDRPHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedSecureDirectHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedSecureBypassedHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedSecureOtherHistogramName, 0);
histogram_tester.ExpectUniqueSample(kReceivedVideoInsecureViaDRPHistogramName,
kResponseContentLength, 1);
histogram_tester.ExpectTotalCount(kReceivedVideoInsecureDirectHistogramName,
0);
histogram_tester.ExpectTotalCount(kReceivedVideoInsecureBypassedHistogramName,
0);
histogram_tester.ExpectTotalCount(kReceivedVideoInsecureOtherHistogramName,
0);
histogram_tester.ExpectTotalCount(kReceivedVideoSecureViaDRPHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedVideoSecureDirectHistogramName, 0);
histogram_tester.ExpectTotalCount(kReceivedVideoSecureBypassedHistogramName,
0);
histogram_tester.ExpectTotalCount(kReceivedVideoSecureOtherHistogramName, 0);
}
struct ExpectedHistogram {
const std::string name;
int64_t value;
};
bool operator<(const ExpectedHistogram& hist1, const ExpectedHistogram& hist2) {
return hist1.name < hist2.name;
}
TEST_F(DataReductionProxyNetworkDelegateTest, DetailedNetHistograms) {
// List of all the histograms we're concerned with.
// Each test case can define interesting histograms from this list.
// Any histogram not called out in an invidual test will have an expected
// count of 0 samples.
const std::set<std::string> all_new_net_histograms{
// HTTP received content length
kReceivedInsecureDirectHistogramName,
kReceivedInsecureViaDRPHistogramName,
kReceivedInsecureBypassedHistogramName,
kReceivedInsecureOtherHistogramName,
// HTTP video received content length
kReceivedVideoInsecureDirectHistogramName,
kReceivedVideoInsecureViaDRPHistogramName,
kReceivedVideoInsecureBypassedHistogramName,
kReceivedVideoInsecureOtherHistogramName,
// HTTPS received content length
kReceivedSecureDirectHistogramName, kReceivedSecureViaDRPHistogramName,
kReceivedSecureBypassedHistogramName, kReceivedSecureOtherHistogramName,
// HTTPS video received content length
kReceivedVideoSecureDirectHistogramName,
kReceivedVideoSecureViaDRPHistogramName,
kReceivedVideoSecureBypassedHistogramName,
kReceivedVideoSecureOtherHistogramName,
// HTTP Original content length
kOriginalInsecureDirectHistogramName,
kOriginalInsecureViaDRPHistogramName,
kOriginalInsecureBypassedHistogramName,
kOriginalInsecureOtherHistogramName,
// HTTP video Original content length
kOriginalVideoInsecureDirectHistogramName,
kOriginalVideoInsecureViaDRPHistogramName,
kOriginalVideoInsecureBypassedHistogramName,
kOriginalVideoInsecureOtherHistogramName,
// HTTPS Original content length
kOriginalSecureDirectHistogramName, kOriginalSecureViaDRPHistogramName,
kOriginalSecureBypassedHistogramName, kOriginalSecureOtherHistogramName,
// HTTPS video Original content length
kOriginalVideoSecureDirectHistogramName,
kOriginalVideoSecureViaDRPHistogramName,
kOriginalVideoSecureBypassedHistogramName,
kOriginalVideoSecureOtherHistogramName,
};
const struct {
const std::string name;
bool is_video;
bool is_https;
ProxyTestConfig proxy_config;
int64_t original_content_length;
int64_t content_length;
// Any histogram listed in all_new_net_histograms but not here should have
// no samples.
const std::set<ExpectedHistogram> expected_histograms;
} tests[] = {
{"HTTP nonvideo request via DRP",
false,
false,
USE_INSECURE_PROXY,
kOriginalContentLength,
kResponseContentLength,
{
{kReceivedInsecureViaDRPHistogramName, kResponseContentLength},
{kOriginalInsecureViaDRPHistogramName, kOriginalContentLength},
}},
{"HTTP video request via DRP",
true,
false,
USE_INSECURE_PROXY,
kOriginalContentLength,
kResponseContentLength,
{
{kReceivedInsecureViaDRPHistogramName, kResponseContentLength},
{kOriginalInsecureViaDRPHistogramName, kOriginalContentLength},
{kReceivedVideoInsecureViaDRPHistogramName, kResponseContentLength},
{kOriginalVideoInsecureViaDRPHistogramName, kOriginalContentLength},
}},
{"DRP not configured for http",
false,
false,
BYPASS_PROXY,
kOriginalContentLength,
kResponseContentLength,
{
{kReceivedInsecureDirectHistogramName, kResponseContentLength},
{kOriginalInsecureDirectHistogramName, kResponseContentLength},
}},
{"DRP not configured for http video",
true,
false,
BYPASS_PROXY,
kOriginalContentLength,
kResponseContentLength,
{
{kReceivedInsecureDirectHistogramName, kResponseContentLength},
{kOriginalInsecureDirectHistogramName, kResponseContentLength},
{kReceivedVideoInsecureDirectHistogramName, kResponseContentLength},
{kOriginalVideoInsecureDirectHistogramName, kResponseContentLength},
}},
{"nonvideo over https",
false,
true,
BYPASS_PROXY,
kOriginalContentLength,
kResponseContentLength,
{
{kReceivedSecureDirectHistogramName, kResponseContentLength},
{kOriginalSecureDirectHistogramName, kResponseContentLength},
}},
{"video over https",
true,
true,
BYPASS_PROXY,
kOriginalContentLength,
kResponseContentLength,
{
{kReceivedSecureDirectHistogramName, kResponseContentLength},
{kOriginalSecureDirectHistogramName, kResponseContentLength},
{kReceivedVideoSecureDirectHistogramName, kResponseContentLength},
{kOriginalVideoSecureDirectHistogramName, kResponseContentLength},
}},
};
for (const auto& test : tests) {
LOG(INFO) << "NetHistograms: " << test.name;
Init(test.proxy_config, false);
base::HistogramTester histogram_tester;
GURL test_url = GURL(kTestURL);
if (test.is_https) {
test_url = GURL(kSecureTestURL);
mock_socket_factory()->AddSSLSocketDataProvider(
ssl_socket_data_provider());
}
std::string via_header = "";
std::string ocl_header = "";
if (test.proxy_config == USE_INSECURE_PROXY) {
via_header = "Via: 1.1 Chrome-Compression-Proxy\r\n";
ocl_header = "x-original-content-length: " +
base::Int64ToString(kOriginalContentLength) + "\r\n";
}
if (test.is_video) {
// Check video
std::string video_response_headers =
"HTTP/1.1 200 OK\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Content-Type: video/mp4\r\n" +
via_header + ocl_header + "\r\n";
FetchURLRequest(test_url, nullptr, video_response_headers,
kResponseContentLength, 0);
} else {
// Check https
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" +
via_header + ocl_header + "\r\n\r\n";
FetchURLRequest(test_url, nullptr, response_headers,
kResponseContentLength, 0);
}
for (const auto& histogram : all_new_net_histograms) {
auto expected_it = test.expected_histograms.find({histogram, 0});
if (expected_it == test.expected_histograms.end()) {
histogram_tester.ExpectTotalCount(histogram, 0);
} else {
histogram_tester.ExpectUniqueSample(expected_it->name,
expected_it->value, 1);
}
}
}
}
TEST_F(DataReductionProxyNetworkDelegateTest,
NonServerLoFiResponseDoesNotTriggerInfobar) {
Init(USE_INSECURE_PROXY, false);
ClearLoFiUIService();
lofi_decider()->SetIsUsingClientLoFi(false);
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n\r\n";
auto request =
FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0);
EXPECT_FALSE(DataReductionProxyData::GetData(*request)->lofi_received());
VerifyDidNotifyLoFiResponse(false);
}
TEST_F(DataReductionProxyNetworkDelegateTest,
ServerLoFiResponseDoesTriggerInfobar) {
Init(USE_INSECURE_PROXY, false);
ClearLoFiUIService();
lofi_decider()->SetIsUsingClientLoFi(false);
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"Chrome-Proxy-Content-Transform: empty-image\r\n\r\n";
auto request =
FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0);
EXPECT_TRUE(DataReductionProxyData::GetData(*request)->lofi_received());
VerifyDidNotifyLoFiResponse(true);
}
TEST_F(DataReductionProxyNetworkDelegateTest,
NonClientLoFiResponseDoesNotTriggerInfobar) {
Init(USE_INSECURE_PROXY, false);
ClearLoFiUIService();
lofi_decider()->SetIsUsingClientLoFi(false);
FetchURLRequest(GURL(kTestURL), nullptr,
"HTTP/1.1 206 Partial Content\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"Content-Range: bytes 0-139/2048\r\n\r\n",
140, 0);
VerifyDidNotifyLoFiResponse(false);
}
TEST_F(DataReductionProxyNetworkDelegateTest,
ClientLoFiCompleteResponseDoesNotTriggerInfobar) {
Init(USE_INSECURE_PROXY, false);
const char* const test_response_headers[] = {
"HTTP/1.1 200 OK\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n\r\n",
"HTTP/1.1 204 No Content\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n\r\n",
"HTTP/1.1 404 Not Found\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n\r\n",
"HTTP/1.1 206 Partial Content\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"Content-Range: bytes 0-139/140\r\n\r\n",
};
for (const char* headers : test_response_headers) {
ClearLoFiUIService();
lofi_decider()->SetIsUsingClientLoFi(true);
FetchURLRequest(GURL(kTestURL), nullptr, headers, 140, 0);
VerifyDidNotifyLoFiResponse(false);
}
}
TEST_F(DataReductionProxyNetworkDelegateTest,
ClientLoFiPartialRangeDoesTriggerInfobar) {
Init(USE_INSECURE_PROXY, false);
const char* const test_response_headers[] = {
"HTTP/1.1 206 Partial Content\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"Content-Range: bytes 0-139/2048\r\n\r\n",
"HTTP/1.1 206 Partial Content\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"Content-Range: bytes 5-144/145\r\n\r\n",
};
for (const char* headers : test_response_headers) {
ClearLoFiUIService();
lofi_decider()->SetIsUsingClientLoFi(true);
FetchURLRequest(GURL(kTestURL), nullptr, headers, 140, 0);
VerifyDidNotifyLoFiResponse(true);
}
}
TEST_F(DataReductionProxyNetworkDelegateTest,
TestLoFiTransformationTypeHistogram) {
const std::string regular_response_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"Cache-Control: max-age=0\r\n"
"Vary: accept-encoding\r\n\r\n";
Init(USE_INSECURE_PROXY, false);
const char kLoFiTransformationTypeHistogram[] =
"DataReductionProxy.LoFi.TransformationType";
base::HistogramTester histogram_tester;
net::HttpRequestHeaders request_headers;
request_headers.SetHeader("chrome-proxy-accept-transform", "lite-page");
lofi_decider()->ignore_is_using_data_reduction_proxy_check();
FetchURLRequest(GURL(kTestURL), &request_headers, regular_response_headers,
140, 0);
histogram_tester.ExpectBucketCount(kLoFiTransformationTypeHistogram,
NO_TRANSFORMATION_LITE_PAGE_REQUESTED, 1);
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Chrome-Proxy-Content-Transform: lite-page\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n";
response_headers += "\r\n";
auto request =
FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0);
EXPECT_TRUE(DataReductionProxyData::GetData(*request)->lite_page_received());
histogram_tester.ExpectBucketCount(kLoFiTransformationTypeHistogram,
LITE_PAGE, 1);
}
// Test that Brotli is not added to the accept-encoding header when it is
// disabled globally.
TEST_F(DataReductionProxyNetworkDelegateTest,
BrotliAdvertisement_BrotliDisabled) {
Init(USE_SECURE_PROXY, false /* enable_brotli_globally */);
ReadBrotliFile();
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"Cache-Control: max-age=1200\r\n"
"Vary: accept-encoding\r\n";
response_headers += "\r\n";
// Use secure sockets when fetching the request since Brotli is only enabled
// for secure connections.
FetchURLRequestAndVerifyBrotli(nullptr, response_headers, false, false);
}
// Test that Brotli is not added to the accept-encoding header when the request
// is fetched from an insecure proxy.
TEST_F(DataReductionProxyNetworkDelegateTest,
BrotliAdvertisementInsecureProxy) {
Init(USE_INSECURE_PROXY, true /* enable_brotli_globally */);
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"Cache-Control: max-age=1200\r\n"
"Vary: accept-encoding\r\n";
response_headers += "\r\n";
// Use secure sockets when fetching the request since Brotli is only enabled
// for secure connections.
std::unique_ptr<net::URLRequest> request(
FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0));
EXPECT_EQ(140, request->received_response_content_length());
EXPECT_NE(0, request->GetTotalSentBytes());
EXPECT_NE(0, request->GetTotalReceivedBytes());
EXPECT_FALSE(request->was_cached());
// Brotli should be added to Accept Encoding header only if secure proxy is in
VerifyBrotliPresent(request.get(), false);
}
// Test that Brotli is not added to the accept-encoding header when it is
// disabled via data reduction proxy field trial.
TEST_F(DataReductionProxyNetworkDelegateTest,
BrotliAdvertisementDisabledViaFieldTrial) {
Init(USE_SECURE_PROXY, true /* enable_brotli_globally */);
base::FieldTrialList field_trial_list(nullptr);
ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
"DataReductionProxyBrotliAcceptEncoding", "Disabled"));
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"Cache-Control: max-age=1200\r\n"
"Vary: accept-encoding\r\n";
response_headers += "\r\n";
FetchURLRequestAndVerifyBrotli(nullptr, response_headers, false, false);
FetchURLRequestAndVerifyBrotli(nullptr, response_headers, true, false);
}
// Test that Brotli is correctly added to the accept-encoding header when it is
// enabled globally.
TEST_F(DataReductionProxyNetworkDelegateTest, BrotliAdvertisement) {
Init(USE_SECURE_PROXY, true /* enable_brotli_globally */);
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"Cache-Control: max-age=1200\r\n"
"Content-Encoding: br\r\n"
"Vary: accept-encoding\r\n";
response_headers += "\r\n";
FetchURLRequestAndVerifyBrotli(nullptr, response_headers, false, true);
FetchURLRequestAndVerifyBrotli(nullptr, response_headers, true, true);
}
TEST_F(DataReductionProxyNetworkDelegateTest, IncrementingMainFramePageId) {
// This is unaffacted by brotil and insecure proxy.
Init(USE_SECURE_PROXY, false /* enable_brotli_globally */);
io_data()->request_options()->SetSecureSession("new-session");
uint64_t page_id = io_data()->request_options()->GeneratePageId();
FetchURLRequestAndVerifyPageIdDirective(++page_id, false);
FetchURLRequestAndVerifyPageIdDirective(++page_id, false);
FetchURLRequestAndVerifyPageIdDirective(++page_id, false);
}
TEST_F(DataReductionProxyNetworkDelegateTest, ResetSessionResetsId) {
// This is unaffacted by brotil and insecure proxy.
Init(USE_SECURE_PROXY, false /* enable_brotli_globally */);
io_data()->request_options()->SetSecureSession("new-session");
uint64_t page_id = io_data()->request_options()->GeneratePageId();
FetchURLRequestAndVerifyPageIdDirective(++page_id, false);
io_data()->request_options()->SetSecureSession("new-session-2");
page_id = io_data()->request_options()->GeneratePageId();
FetchURLRequestAndVerifyPageIdDirective(++page_id, false);
}
TEST_F(DataReductionProxyNetworkDelegateTest, SubResourceNoPageId) {
// This is unaffacted by brotil and insecure proxy.
Init(USE_SECURE_PROXY, false /* enable_brotli_globally */);
io_data()->request_options()->SetSecureSession("new-session");
FetchURLRequestAndVerifyPageIdDirective(base::Optional<uint64_t>(), false);
}
TEST_F(DataReductionProxyNetworkDelegateTest, RedirectSharePid) {
// This is unaffacted by brotil and insecure proxy.
Init(USE_SECURE_PROXY, false /* enable_brotli_globally */);
io_data()->request_options()->SetSecureSession("new-session");
uint64_t page_id = io_data()->request_options()->GeneratePageId();
FetchURLRequestAndVerifyPageIdDirective(++page_id, true);
}
TEST_F(DataReductionProxyNetworkDelegateTest,
SessionChangeResetsPageIDOnRedirect) {
// This test calls directly into network delegate as it is difficult to mock
// state changing in between redirects within an URLRequest's lifetime.
// This is unaffacted by brotil and insecure proxy.
Init(USE_INSECURE_PROXY, false /* enable_brotli_globally */);
net::ProxyInfo data_reduction_proxy_info;
data_reduction_proxy_info.UseProxyServer(
params()->proxies_for_http().front().proxy_server());
std::unique_ptr<net::URLRequest> request =
context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE,
nullptr, TRAFFIC_ANNOTATION_FOR_TESTS);
request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED);
io_data()->request_options()->SetSecureSession("fake-session");
uint64_t page_id = io_data()->request_options()->GeneratePageId();
net::HttpRequestHeaders headers;
net::ProxyRetryInfoMap proxy_retry_info;
// Send a request and verify the page ID is 1.
network_delegate()->NotifyBeforeStartTransaction(
request.get(),
base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone,
base::Unretained(this)),
&headers);
network_delegate()->NotifyBeforeSendHeaders(
request.get(), data_reduction_proxy_info, proxy_retry_info, &headers);
DataReductionProxyData* data =
DataReductionProxyData::GetData(*request.get());
EXPECT_TRUE(data_reduction_proxy_info.is_http());
EXPECT_EQ(++page_id, data->page_id().value());
// Send a second request and verify the page ID incremements.
request = context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE,
nullptr, TRAFFIC_ANNOTATION_FOR_TESTS);
request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED);
network_delegate()->NotifyBeforeStartTransaction(
request.get(),
base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone,
base::Unretained(this)),
&headers);
network_delegate()->NotifyBeforeSendHeaders(
request.get(), data_reduction_proxy_info, proxy_retry_info, &headers);
data = DataReductionProxyData::GetData(*request.get());
EXPECT_EQ(++page_id, data->page_id().value());
// Verify that redirects are the same page ID.
network_delegate()->NotifyBeforeRedirect(request.get(), GURL(kTestURL));
network_delegate()->NotifyBeforeSendHeaders(
request.get(), data_reduction_proxy_info, proxy_retry_info, &headers);
data = DataReductionProxyData::GetData(*request.get());
EXPECT_EQ(page_id, data->page_id().value());
network_delegate()->NotifyBeforeRedirect(request.get(), GURL(kTestURL));
io_data()->request_options()->SetSecureSession("new-session");
page_id = io_data()->request_options()->GeneratePageId();
network_delegate()->NotifyBeforeSendHeaders(
request.get(), data_reduction_proxy_info, proxy_retry_info, &headers);
data = DataReductionProxyData::GetData(*request.get());
EXPECT_EQ(++page_id, data->page_id().value());
}
// Test that effective connection type is correctly added to the request
// headers when it is enabled using field trial. The server is varying on the
// effective connection type (ECT).
TEST_F(DataReductionProxyNetworkDelegateTest, ECTHeaderEnabledWithVary) {
Init(USE_SECURE_PROXY, false /* enable_brotli_globally */);
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"Cache-Control: max-age=1200\r\n"
"Vary: chrome-proxy-ect\r\n"
"x-original-content-length: 200\r\n\r\n";
int response_body_size = 140;
std::string response_body(base::checked_cast<size_t>(response_body_size),
' ');
std::vector<net::MockRead> reads_list;
std::vector<std::string> mock_writes;
std::vector<net::MockWrite> writes_list;
std::vector<net::EffectiveConnectionType> effective_connection_types;
effective_connection_types.push_back(net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
effective_connection_types.push_back(net::EFFECTIVE_CONNECTION_TYPE_2G);
BuildSocket(response_headers, response_body, true, effective_connection_types,
&reads_list, &mock_writes, &writes_list);
// Add 2 socket providers since 2 requests in this test are fetched from the
// network.
FetchURLRequestAndVerifyECTHeader(effective_connection_types[0], true, false);
// When the ECT is set to the same value, fetching the same resource should
// result in a cache hit.
FetchURLRequestAndVerifyECTHeader(effective_connection_types[0], true, true);
// When the ECT is set to a different value, the response should not be
// served from the cache.
FetchURLRequestAndVerifyECTHeader(effective_connection_types[1], true, false);
}
// Test that effective connection type is correctly added to the request
// headers when it is enabled using field trial. The server is not varying on
// the effective connection type (ECT).
TEST_F(DataReductionProxyNetworkDelegateTest, ECTHeaderEnabledWithoutVary) {
Init(USE_SECURE_PROXY, false /* enable_brotli_globally */);
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"Cache-Control: max-age=1200\r\n"
"x-original-content-length: 200\r\n\r\n";
int response_body_size = 140;
std::string response_body(base::checked_cast<size_t>(response_body_size),
' ');
std::vector<net::MockRead> reads_list;
std::vector<std::string> mock_writes;
std::vector<net::MockWrite> writes_list;
std::vector<net::EffectiveConnectionType> effective_connection_types;
effective_connection_types.push_back(net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
effective_connection_types.push_back(net::EFFECTIVE_CONNECTION_TYPE_2G);
BuildSocket(response_headers, response_body, true, effective_connection_types,
&reads_list, &mock_writes, &writes_list);
// Add 1 socket provider since 1 request in this test is fetched from the
// network.
FetchURLRequestAndVerifyECTHeader(effective_connection_types[0], true, false);
// When the ECT is set to the same value, fetching the same resource should
// result in a cache hit.
FetchURLRequestAndVerifyECTHeader(effective_connection_types[0], true, true);
// When the ECT is set to a different value, the response should still be
// served from the cache.
FetchURLRequestAndVerifyECTHeader(effective_connection_types[1], true, true);
}
class DataReductionProxyNetworkDelegateClientLoFiTest : public testing::Test {
public:
DataReductionProxyNetworkDelegateClientLoFiTest() : baseline_savings_(0) {}
~DataReductionProxyNetworkDelegateClientLoFiTest() override;
void Reset() {
drp_test_context_.reset();
mock_socket_factory_.reset();
context_storage_.reset();
context_.reset(new net::TestURLRequestContext(true));
context_storage_.reset(new net::URLRequestContextStorage(context_.get()));
mock_socket_factory_.reset(new net::MockClientSocketFactory());
context_->set_client_socket_factory(mock_socket_factory_.get());
drp_test_context_ =
DataReductionProxyTestContext::Builder()
.WithURLRequestContext(context_.get())
.WithMockClientSocketFactory(mock_socket_factory_.get())
.Build();
drp_test_context_->AttachToURLRequestContext(context_storage_.get());
context_->Init();
base::RunLoop().RunUntilIdle();
baseline_savings_ =
drp_test_context()->settings()->GetTotalHttpContentLengthSaved();
}
void SetUpLoFiDecider(bool is_client_lofi_image,
bool is_client_lofi_auto_reload) const {
std::unique_ptr<TestLoFiDecider> lofi_decider(new TestLoFiDecider());
lofi_decider->SetIsUsingClientLoFi(is_client_lofi_image);
lofi_decider->SetIsClientLoFiAutoReload(is_client_lofi_auto_reload);
drp_test_context_->io_data()->set_lofi_decider(
std::unique_ptr<LoFiDecider>(std::move(lofi_decider)));
}
int64_t GetSavings() const {
return drp_test_context()->settings()->GetTotalHttpContentLengthSaved() -
baseline_savings_;
}
net::TestURLRequestContext* context() const { return context_.get(); }
net::MockClientSocketFactory* mock_socket_factory() const {
return mock_socket_factory_.get();
}
DataReductionProxyTestContext* drp_test_context() const {
return drp_test_context_.get();
}
private:
base::MessageLoopForIO loop;
std::unique_ptr<net::TestURLRequestContext> context_;
std::unique_ptr<net::URLRequestContextStorage> context_storage_;
std::unique_ptr<net::MockClientSocketFactory> mock_socket_factory_;
std::unique_ptr<DataReductionProxyTestContext> drp_test_context_;
int64_t baseline_savings_;
};
DataReductionProxyNetworkDelegateClientLoFiTest::
~DataReductionProxyNetworkDelegateClientLoFiTest() {}
TEST_F(DataReductionProxyNetworkDelegateClientLoFiTest, DataSavingsNonDRP) {
const char kSimple200ResponseHeaders[] =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n\r\n";
const struct {
const char* headers;
size_t response_length;
bool is_client_lofi_image;
bool is_client_lofi_auto_reload;
int64_t expected_savings;
} tests[] = {
// 200 responses shouldn't see any savings.
{kSimple200ResponseHeaders, 140, false, false, 0},
{kSimple200ResponseHeaders, 140, true, false, 0},
// Client Lo-Fi Auto-reload responses should see negative savings.
{kSimple200ResponseHeaders, 140, false, true,
-(static_cast<int64_t>(sizeof(kSimple200ResponseHeaders) - 1) + 140)},
{kSimple200ResponseHeaders, 140, true, true,
-(static_cast<int64_t>(sizeof(kSimple200ResponseHeaders) - 1) + 140)},
// A range response that doesn't use Client Lo-Fi shouldn't see any
// savings.
{"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: bytes 0-2047/10000\r\n"
"Content-Length: 2048\r\n\r\n",
2048, false, false, 0},
// A Client Lo-Fi range response should see savings based on the
// Content-Range header.
{"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: bytes 0-2047/10000\r\n"
"Content-Length: 2048\r\n\r\n",
2048, true, false, 10000 - 2048},
// A Client Lo-Fi range response should see savings based on the
// Content-Range header, which in this case is 0 savings because the range
// response contained the entire resource.
{"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: bytes 0-999/1000\r\n"
"Content-Length: 1000\r\n\r\n",
1000, true, false, 0},
// Client Lo-Fi range responses that don't have a Content-Range with the
// full resource length shouldn't see any savings.
{"HTTP/1.1 206 Partial Content\r\n"
"Content-Length: 2048\r\n\r\n",
2048, true, false, 0},
{"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: bytes 0-2047/*\r\n"
"Content-Length: 2048\r\n\r\n",
2048, true, false, 0},
{"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: invalid_content_range\r\n"
"Content-Length: 2048\r\n\r\n",
2048, true, false, 0},
};
for (const auto& test : tests) {
Reset();
SetUpLoFiDecider(test.is_client_lofi_image,
test.is_client_lofi_auto_reload);
std::string response_body(test.response_length, 'a');
net::MockRead reads[] = {net::MockRead(test.headers),
net::MockRead(response_body.c_str()),
net::MockRead(net::ASYNC, net::OK)};
net::StaticSocketDataProvider socket(reads, arraysize(reads), nullptr, 0);
mock_socket_factory()->AddSocketDataProvider(&socket);
net::TestDelegate test_delegate;
std::unique_ptr<net::URLRequest> request = context()->CreateRequest(
GURL("http://example.com"), net::RequestPriority::IDLE, &test_delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(test.expected_savings, GetSavings()) << (&test - tests);
}
}
TEST_F(DataReductionProxyNetworkDelegateClientLoFiTest, DataSavingsThroughDRP) {
Reset();
drp_test_context()->DisableWarmupURLFetch();
drp_test_context()->EnableDataReductionProxyWithSecureProxyCheckSuccess();
SetUpLoFiDecider(true, false);
const char kHeaders[] =
"HTTP/1.1 206 Partial Content\r\n"
"Content-Range: bytes 0-2047/10000\r\n"
"Content-Length: 2048\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"X-Original-Content-Length: 3000\r\n\r\n";
std::string response_body(2048, 'a');
net::MockRead reads[] = {net::MockRead(kHeaders),
net::MockRead(response_body.c_str()),
net::MockRead(net::ASYNC, net::OK)};
net::StaticSocketDataProvider socket(reads, arraysize(reads), nullptr, 0);
mock_socket_factory()->AddSocketDataProvider(&socket);
net::TestDelegate test_delegate;
std::unique_ptr<net::URLRequest> request = context()->CreateRequest(
GURL("http://example.com"), net::RequestPriority::IDLE, &test_delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
base::RunLoop().RunUntilIdle();
// Since the Data Reduction Proxy is enabled, the length of the raw headers
// should be used in the estimated original size. The X-OCL should be ignored.
EXPECT_EQ(static_cast<int64_t>(net::HttpUtil::AssembleRawHeaders(
kHeaders, sizeof(kHeaders) - 1)
.size() +
10000 - request->GetTotalReceivedBytes()),
GetSavings());
}
TEST_F(DataReductionProxyNetworkDelegateTest, TestAcceptTransformHistogram) {
Init(USE_INSECURE_PROXY, false);
base::HistogramTester histogram_tester;
const std::string regular_response_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 140\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"Cache-Control: max-age=0\r\n"
"Vary: accept-encoding\r\n\r\n";
const char kResponseHeadersWithCPCTFormat[] =
"HTTP/1.1 200 OK\r\n"
"Chrome-Proxy-Content-Transform: %s\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"\r\n";
// Verify lite page request.
net::HttpRequestHeaders request_headers;
request_headers.SetHeader("chrome-proxy-accept-transform", "lite-page");
FetchURLRequest(GURL(kTestURL), &request_headers, regular_response_headers,
140, 0);
histogram_tester.ExpectTotalCount(
"DataReductionProxy.Protocol.AcceptTransform", 1);
histogram_tester.ExpectBucketCount(
"DataReductionProxy.Protocol.AcceptTransform",
0 /* LITE_PAGE_REQUESTED */, 1);
// Check legacy histogram too:
histogram_tester.ExpectBucketCount(
"DataReductionProxy.LoFi.TransformationType",
NO_TRANSFORMATION_LITE_PAGE_REQUESTED, 1);
// Verify empty image request.
request_headers.SetHeader("chrome-proxy-accept-transform", "empty-image");
FetchURLRequest(GURL(kTestURL), &request_headers, regular_response_headers,
140, 0);
histogram_tester.ExpectTotalCount(
"DataReductionProxy.Protocol.AcceptTransform", 2);
histogram_tester.ExpectBucketCount(
"DataReductionProxy.Protocol.AcceptTransform",
3 /* EMPTY_IMAGE_REQUESTED */, 1);
// Verify lite page response.
auto request = FetchURLRequest(
GURL(kTestURL), nullptr,
base::StringPrintf(kResponseHeadersWithCPCTFormat, "lite-page"), 140, 0);
EXPECT_TRUE(DataReductionProxyData::GetData(*request)->lite_page_received());
histogram_tester.ExpectTotalCount(
"DataReductionProxy.Protocol.AcceptTransform", 3);
histogram_tester.ExpectBucketCount(
"DataReductionProxy.Protocol.AcceptTransform",
1 /* LITE_PAGE_TRANSFORM_RECEIVED */, 1);
// Check legacy histogram too:
histogram_tester.ExpectBucketCount(
"DataReductionProxy.LoFi.TransformationType", LITE_PAGE, 1);
// Verify page policy response.
std::string response_headers =
"HTTP/1.1 200 OK\r\n"
"Chrome-Proxy: page-policies=empty-image\r\n"
"Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n"
"Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n"
"Via: 1.1 Chrome-Compression-Proxy\r\n"
"x-original-content-length: 200\r\n"
"\r\n";
request = FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0);
EXPECT_FALSE(DataReductionProxyData::GetData(*request)->lite_page_received());
histogram_tester.ExpectTotalCount(
"DataReductionProxy.Protocol.AcceptTransform", 4);
histogram_tester.ExpectBucketCount(
"DataReductionProxy.Protocol.AcceptTransform",
2 /* EMPTY_IMAGE_POLICY_DIRECTIVE_RECEIVED */, 1);
// Verify empty image response.
request = FetchURLRequest(
GURL(kTestURL), nullptr,
base::StringPrintf(kResponseHeadersWithCPCTFormat, "empty-image"), 140,
0);
EXPECT_TRUE(DataReductionProxyData::GetData(*request)->lofi_received());
histogram_tester.ExpectTotalCount(
"DataReductionProxy.Protocol.AcceptTransform", 5);
histogram_tester.ExpectBucketCount(
"DataReductionProxy.Protocol.AcceptTransform",
4 /* EMPTY_IMAGE_TRANSFORM_RECEIVED */, 1);
// Verify compressed-video request.
request_headers.SetHeader("chrome-proxy-accept-transform",
"compressed-video");
FetchURLRequest(GURL(kTestURL), &request_headers, std::string(), 140, 0);
histogram_tester.ExpectTotalCount(
"DataReductionProxy.Protocol.AcceptTransform", 6);
histogram_tester.ExpectBucketCount(
"DataReductionProxy.Protocol.AcceptTransform",
5 /* COMPRESSED_VIDEO_REQUESTED */, 1);
// Verify compressed-video response.
request = FetchURLRequest(
GURL(kTestURL), nullptr,
base::StringPrintf(kResponseHeadersWithCPCTFormat, "compressed-video"),
140, 0);
EXPECT_FALSE(DataReductionProxyData::GetData(*request)->lofi_received());
histogram_tester.ExpectTotalCount(
"DataReductionProxy.Protocol.AcceptTransform", 7);
histogram_tester.ExpectBucketCount(
"DataReductionProxy.Protocol.AcceptTransform",
8 /* COMPRESSED_VIDEO_RECEIVED */, 1);
// Verify response with an unknown CPAT value.
request = FetchURLRequest(GURL(kTestURL), nullptr,
base::StringPrintf(kResponseHeadersWithCPCTFormat,
"this-is-a-fake-transform"),
140, 0);
EXPECT_FALSE(DataReductionProxyData::GetData(*request)->lofi_received());
histogram_tester.ExpectTotalCount(
"DataReductionProxy.Protocol.AcceptTransform", 8);
histogram_tester.ExpectBucketCount(
"DataReductionProxy.Protocol.AcceptTransform",
9 /* UNKNOWN_TRANSFORM_RECEIVED */, 1);
}
} // namespace
} // namespace data_reduction_proxy
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.