hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fdac081e1c692002a920c526e8b4021cdf42a4b5
| 3,129
|
cpp
|
C++
|
src/NetWidgets/Widgets/nTldEditor.cpp
|
Vladimir-Lin/QtNetWidgets
|
e09339c47d40b65875f15bd0839e0bdf89951601
|
[
"MIT"
] | null | null | null |
src/NetWidgets/Widgets/nTldEditor.cpp
|
Vladimir-Lin/QtNetWidgets
|
e09339c47d40b65875f15bd0839e0bdf89951601
|
[
"MIT"
] | null | null | null |
src/NetWidgets/Widgets/nTldEditor.cpp
|
Vladimir-Lin/QtNetWidgets
|
e09339c47d40b65875f15bd0839e0bdf89951601
|
[
"MIT"
] | null | null | null |
#include <netwidgets.h>
N::TldEditor:: TldEditor ( QWidget * parent , Plan * p )
: TreeWidget ( parent , p )
, NetworkManager ( p )
{
WidgetClass ;
Configure ( ) ;
}
N::TldEditor::~TldEditor(void)
{
}
void N::TldEditor::Configure(void)
{
setWindowTitle ( tr("Top level domains") ) ;
setDragDropMode ( DragOnly ) ;
setRootIsDecorated ( false ) ;
setAlternatingRowColors ( true ) ;
setHorizontalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ;
setVerticalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ;
setColumnCount ( 6 ) ;
NewTreeWidgetItem ( header ) ;
header->setText ( 0,tr("Top level domain")) ;
header->setText ( 1,tr("Country" )) ;
header->setText ( 2,tr("NIC" )) ;
header->setText ( 3,tr("SLDs" )) ;
header->setText ( 4,tr("Sites" )) ;
header->setText ( 5,tr("Comment" )) ;
setHeaderItem ( header ) ;
plan -> setFont ( this ) ;
}
bool N::TldEditor::FocusIn(void)
{
LinkAction ( Refresh , List () ) ;
LinkAction ( Copy , CopyToClipboard() ) ;
return true ;
}
void N::TldEditor::List(void)
{
SqlConnection SC ( plan->sql ) ;
QString CN = QtUUID::createUuidString ( ) ;
if (SC.open("TldEditor",CN)) {
if (LoadDomainIndex(SC)) {
QString tld ;
foreach (tld,TLDs) {
NewTreeWidgetItem ( IT ) ;
SUID uuid = TldUuids [ tld ] ;
int country = TldNations [ uuid ] ;
SUID cuid = Countries [ country ] ;
QString nic = NICs [ uuid ] ;
int slds = TldCounts ( SC,uuid ) ;
int tlds = TldTotal ( SC,uuid ) ;
QString comment = Comments [ uuid ] ;
IT -> setData (0,Qt::UserRole,uuid ) ;
IT -> setTextAlignment(3,Qt::AlignRight) ;
IT -> setTextAlignment(4,Qt::AlignRight) ;
IT -> setText (0,tld ) ;
IT -> setText (1,Nations[cuid] ) ;
IT -> setText (2,nic ) ;
IT -> setText (3,QString::number(slds) ) ;
IT -> setText (4,QString::number(tlds) ) ;
IT -> setText (5,comment ) ;
addTopLevelItem ( IT ) ;
} ;
} ;
SC . close ( ) ;
} ;
SC.remove() ;
SuitableColumns ( ) ;
Alert ( Done ) ;
}
| 41.171053
| 61
| 0.388623
|
Vladimir-Lin
|
fdad58b919553a96e292c08df88a8af29d0a0cb6
| 1,264
|
cpp
|
C++
|
Fudl/easy/solved/Encryption Decryption of Enigma Machine.cpp
|
AhmedMostafa7474/Codingame-Solutions
|
da696a095c143c5d216bc06f6689ad1c0e25d0e0
|
[
"MIT"
] | 1
|
2022-03-16T08:56:31.000Z
|
2022-03-16T08:56:31.000Z
|
Fudl/easy/solved/Encryption Decryption of Enigma Machine.cpp
|
AhmedMostafa7474/Codingame-Solutions
|
da696a095c143c5d216bc06f6689ad1c0e25d0e0
|
[
"MIT"
] | 2
|
2022-03-17T11:27:14.000Z
|
2022-03-18T07:41:00.000Z
|
Fudl/easy/solved/Encryption Decryption of Enigma Machine.cpp
|
AhmedMostafa7474/Codingame-Solutions
|
da696a095c143c5d216bc06f6689ad1c0e25d0e0
|
[
"MIT"
] | 6
|
2022-03-13T19:56:11.000Z
|
2022-03-17T12:08:22.000Z
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
string operation;
getline(cin, operation);
int pseudo_random_number;
cin >> pseudo_random_number; cin.ignore();
string rotor[3];
for (int i = 0; i < 3; i++) {
getline(cin, rotor[i]);
}
string message;
getline(cin, message);
if (operation[0] == 'E') {
for (int i = 0; i < message.size(); i++) {
message[i] = ((message[i] - 'A' + pseudo_random_number + i) % 26) + 'A';
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < message.size(); j++)
message[j] = rotor[i][message[j] - 'A'];
}
else {
for (int i = 2; i > -1; i--)
for (int j = 0; j < message.size(); j++)
message[j] = rotor[i].find(message[j]) + 'A';
for (int i = 0; i < message.size(); i++) {
int idx = (message[i] - 'A' - pseudo_random_number - i);
while (idx < 0)
idx += 26;
message[i] = (idx % 26) + 'A';
}
}
// Write an answer using cout. DON'T FORGET THE "<< endl"
// To debug: cerr << "Debug messages..." << endl;
cout << message << endl;
}
| 25.28
| 78
| 0.544304
|
AhmedMostafa7474
|
fdaedc490fc1b69a288dc9d8c68da8e0c78a361b
| 210,988
|
cpp
|
C++
|
src/ConEmuCD/ConsoleMain.cpp
|
shawwn/ConEmu
|
53adb1d4e899369bb108374df2890d5031daf9af
|
[
"BSD-3-Clause"
] | null | null | null |
src/ConEmuCD/ConsoleMain.cpp
|
shawwn/ConEmu
|
53adb1d4e899369bb108374df2890d5031daf9af
|
[
"BSD-3-Clause"
] | null | null | null |
src/ConEmuCD/ConsoleMain.cpp
|
shawwn/ConEmu
|
53adb1d4e899369bb108374df2890d5031daf9af
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2009-present Maximus5
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*/
#undef VALIDATE_AND_DELAY_ON_TERMINATE
#ifdef _DEBUG
// Раскомментировать, чтобы сразу после запуска процесса (conemuc.exe) показать MessageBox, чтобы прицепиться дебаггером
// #define SHOW_STARTED_MSGBOX
// #define SHOW_ADMIN_STARTED_MSGBOX
// #define SHOW_MAIN_MSGBOX
// #define SHOW_ALTERNATIVE_MSGBOX
// #define SHOW_DEBUG_STARTED_MSGBOX
// #define SHOW_COMSPEC_STARTED_MSGBOX
// #define SHOW_SERVER_STARTED_MSGBOX
// #define SHOW_STARTED_ASSERT
// #define SHOW_STARTED_PRINT
// #define SHOW_STARTED_PRINT_LITE
#define SHOW_EXITWAITKEY_MSGBOX
// #define SHOW_INJECT_MSGBOX
// #define SHOW_INJECTREM_MSGBOX
// #define SHOW_ATTACH_MSGBOX
// #define SHOW_ROOT_STARTED
// #define SHOW_ASYNC_STARTED
#define WINE_PRINT_PROC_INFO
// #define USE_PIPE_DEBUG_BOXES
// #define SHOW_SETCONTITLE_MSGBOX
#define SHOW_LOADCFGFILE_MSGBOX
// #define DEBUG_ISSUE_623
// #define VALIDATE_AND_DELAY_ON_TERMINATE
#elif defined(__GNUC__)
// Раскомментировать, чтобы сразу после запуска процесса (conemuc.exe) показать MessageBox, чтобы прицепиться дебаггером
// #define SHOW_STARTED_MSGBOX
#else
//
#endif
#define SHOWDEBUGSTR
#define DEBUGSTRCMD(x) DEBUGSTR(x)
#define DEBUGSTARTSTOPBOX(x) //MessageBox(NULL, x, WIN3264TEST(L"ConEmuC",L"ConEmuC64"), MB_ICONINFORMATION|MB_SYSTEMMODAL)
#define DEBUGSTRFIN(x) DEBUGSTR(x)
#define DEBUGSTRCP(x) DEBUGSTR(x)
#define DEBUGSTRSIZE(x) DEBUGSTR(x)
//#define SHOW_INJECT_MSGBOX
#include "ConEmuSrv.h"
#include "../common/CmdLine.h"
#include "../common/ConsoleAnnotation.h"
#include "../common/ConsoleMixAttr.h"
#include "../common/ConsoleRead.h"
#include "../common/EmergencyShow.h"
#include "../common/execute.h"
#include "../common/HkFunc.h"
#include "../common/MArray.h"
#include "../common/MPerfCounter.h"
#include "../common/MProcess.h"
#include "../common/MMap.h"
#include "../common/MModule.h"
#include "../common/MRect.h"
#include "../common/MSectionSimple.h"
#include "../common/MWow64Disable.h"
#include "../common/ProcessSetEnv.h"
#include "../common/ProcessData.h"
#include "../common/RConStartArgs.h"
#include "../common/SetEnvVar.h"
#include "../common/StartupEnvEx.h"
#include "../common/wcwidth.h"
#include "../common/WCodePage.h"
#include "../common/WConsole.h"
#include "../common/WFiles.h"
#include "../common/WThreads.h"
#include "../common/WUser.h"
#include "../ConEmu/version.h"
#include "../ConEmuHk/Injects.h"
#include "Actions.h"
#include "ConProcess.h"
#include "ConsoleHelp.h"
#include "GuiMacro.h"
#include "Debugger.h"
#include "StartEnv.h"
#include "UnicodeTest.h"
#ifndef __GNUC__
#pragma comment(lib, "shlwapi.lib")
#endif
WARNING("Обязательно после запуска сделать apiSetForegroundWindow на GUI окно, если в фокусе консоль");
WARNING("Обязательно получить код и имя родительского процесса");
#ifdef USEPIPELOG
namespace PipeServerLogger
{
Event g_events[BUFFER_SIZE];
LONG g_pos = -1;
}
#endif
WARNING("!!!! Пока можно при появлении события запоминать текущий тик");
// и проверять его в RefreshThread. Если он не 0 - и дельта больше (100мс?)
// то принудительно перечитать консоль и сбросить тик в 0.
WARNING("Наверное все-же стоит производить периодические чтения содержимого консоли, а не только по событию");
WARNING("Стоит именно здесь осуществлять проверку живости GUI окна (если оно было). Ведь может быть запущен не far, а CMD.exe");
WARNING("Если GUI умер, или не подцепился по таймауту - показать консольное окно и наверное установить шрифт поболе");
WARNING("В некоторых случаях не срабатывает ни EVENT_CONSOLE_UPDATE_SIMPLE ни EVENT_CONSOLE_UPDATE_REGION");
// Пример. Запускаем cmd.exe. печатаем какую-то муйню в командной строке и нажимаем 'Esc'
// При Esc никаких событий ВООБЩЕ не дергается, а экран в консоли изменился!
FGetConsoleKeyboardLayoutName pfnGetConsoleKeyboardLayoutName = NULL;
FGetConsoleProcessList pfnGetConsoleProcessList = NULL;
FDebugActiveProcessStop pfnDebugActiveProcessStop = NULL;
FDebugSetProcessKillOnExit pfnDebugSetProcessKillOnExit = NULL;
FGetConsoleDisplayMode pfnGetConsoleDisplayMode = NULL;
/* Console Handles */
//MConHandle ghConIn ( L"CONIN$" );
MConHandle ghConOut(L"CONOUT$");
// Время ожидания завершения консольных процессов, когда юзер нажал крестик в КОНСОЛЬНОМ окне
// The system also displays this dialog box if the process does not respond within a certain time-out period
// (5 seconds for CTRL_CLOSE_EVENT, and 20 seconds for CTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT).
// Поэтому ждать пытаемся - не больше 4 сек
#define CLOSE_CONSOLE_TIMEOUT 4000
/* Global */
CEStartupEnv* gpStartEnv = NULL;
HMODULE ghOurModule = NULL; // ConEmuCD.dll
DWORD gnSelfPID = 0;
wchar_t gsModuleName[32] = L"";
wchar_t gsVersion[20] = L"";
wchar_t gsSelfExe[MAX_PATH] = L""; // Full path+exe to our executable
wchar_t gsSelfPath[MAX_PATH] = L""; // Directory of our executable
BOOL gbTerminateOnExit = FALSE;
//HANDLE ghConIn = NULL, ghConOut = NULL;
HWND ghConWnd = NULL;
DWORD gnConEmuPID = 0; // PID of ConEmu[64].exe (ghConEmuWnd)
HWND ghConEmuWnd = NULL; // Root! window
HWND ghConEmuWndDC = NULL; // ConEmu DC window
HWND ghConEmuWndBack = NULL; // ConEmu Back window
DWORD gnMainServerPID = 0;
DWORD gnAltServerPID = 0;
BOOL gbLogProcess = FALSE;
BOOL gbWasBufferHeight = FALSE;
BOOL gbNonGuiMode = FALSE;
DWORD gnExitCode = 0;
HANDLE ghRootProcessFlag = NULL;
HANDLE ghExitQueryEvent = NULL; int nExitQueryPlace = 0, nExitPlaceStep = 0;
#define EPS_WAITING4PROCESS 550
#define EPS_ROOTPROCFINISHED 560
SetTerminateEventPlace gTerminateEventPlace = ste_None;
HANDLE ghQuitEvent = NULL;
bool gbQuit = false;
BOOL gbInShutdown = FALSE;
BOOL gbInExitWaitForKey = FALSE;
BOOL gbStopExitWaitForKey = FALSE;
BOOL gbCtrlBreakStopWaitingShown = FALSE;
BOOL gbTerminateOnCtrlBreak = FALSE;
BOOL gbPrintRetErrLevel = FALSE; // Вывести в StdOut код завершения процесса (RM_COMSPEC в основном)
bool gbSkipHookersCheck = false;
RConStartArgs::CloseConfirm gnConfirmExitParm = RConStartArgs::eConfDefault; // | eConfAlways | eConfNever | eConfEmpty | eConfHalt
BOOL gbAlwaysConfirmExit = FALSE;
BOOL gbAutoDisableConfirmExit = FALSE; // если корневой процесс проработал достаточно (10 сек) - будет сброшен gbAlwaysConfirmExit
BOOL gbRootAliveLess10sec = FALSE; // корневой процесс проработал менее CHECK_ROOTOK_TIMEOUT
int gbRootWasFoundInCon = 0;
BOOL gbComspecInitCalled = FALSE;
AttachModeEnum gbAttachMode = am_None; // сервер запущен НЕ из conemu.exe (а из плагина, из CmdAutoAttach, или -new_console, или /GUIATTACH, или /ADMIN)
BOOL gbAlienMode = FALSE; // сервер НЕ является владельцем консоли (корневым процессом этого консольного окна)
BOOL gbDefTermCall = FALSE; // сервер запущен из DefTerm приложения (*.vshost.exe), конcоль может быть скрыта
BOOL gbCreatingHiddenConsole = FALSE; // Используется для "тихого" открытия окна RealConsole из *.vshost.exe
BOOL gbForceHideConWnd = FALSE;
DWORD gdwMainThreadId = 0;
wchar_t* gpszRunCmd = NULL;
wchar_t* gpszRootExe = NULL; // may be set with '/ROOTEXE' switch if used with '/TRMPID'. full path to root exe
wchar_t* gpszTaskCmd = NULL;
CProcessEnvCmd* gpSetEnv = NULL;
LPCWSTR gpszCheck4NeedCmd = NULL; // Для отладки
wchar_t gszComSpec[MAX_PATH+1] = {0};
bool gbRunInBackgroundTab = false;
BOOL gbRunViaCmdExe = FALSE;
DWORD gnImageSubsystem = 0, gnImageBits = 32;
//HANDLE ghCtrlCEvent = NULL, ghCtrlBreakEvent = NULL;
//HANDLE ghHeap = NULL; //HeapCreate(HEAP_GENERATE_EXCEPTIONS, nMinHeapSize, 0);
#ifdef _DEBUG
size_t gnHeapUsed = 0, gnHeapMax = 0;
HANDLE ghFarInExecuteEvent;
#endif
RunMode gnRunMode = RM_UNDEFINED;
BOOL gbDumpServerInitStatus = FALSE;
BOOL gbNoCreateProcess = FALSE;
BOOL gbDontInjectConEmuHk = FALSE;
BOOL gbAsyncRun = FALSE;
UINT gnPTYmode = 0; // 1 enable PTY, 2 - disable PTY (work as plain console), 0 - don't change
BOOL gbRootIsCmdExe = TRUE;
BOOL gbAttachFromFar = FALSE;
BOOL gbAlternativeAttach = FALSE; // Подцепиться к существующей консоли, без внедрения в процесс ConEmuHk.dll
BOOL gbSkipWowChange = FALSE;
BOOL gbConsoleModeFlags = TRUE;
DWORD gnConsoleModeFlags = 0; //(ENABLE_QUICK_EDIT_MODE|ENABLE_INSERT_MODE);
WORD gnDefTextColors = 0, gnDefPopupColors = 0; // Передаются через "/TA=..."
BOOL gbVisibleOnStartup = FALSE;
OSVERSIONINFO gOSVer;
WORD gnOsVer = 0x500;
bool gbIsWine = false;
bool gbIsDBCS = false;
SrvInfo* gpSrv = NULL;
//#pragma pack(push, 1)
//CESERVER_CONSAVE* gpStoredOutput = NULL;
//#pragma pack(pop)
//MSection* gpcsStoredOutput = NULL;
//CmdInfo* gpSrv = NULL;
COORD gcrVisibleSize = {80,25}; // gcrBufferSize переименован в gcrVisibleSize
BOOL gbParmVisibleSize = FALSE;
BOOL gbParmBufSize = FALSE;
SHORT gnBufferHeight = 0;
SHORT gnBufferWidth = 0; // Определяется в MyGetConsoleScreenBufferInfo
#ifdef _DEBUG
wchar_t* gpszPrevConTitle = NULL;
#endif
MFileLogEx* gpLogSize = NULL;
BOOL gbInRecreateRoot = FALSE;
namespace InputLogger
{
Event g_evt[BUFFER_INFO_SIZE];
LONG g_evtidx = -1;
LONG g_overflow = 0;
};
void ShutdownSrvStep(LPCWSTR asInfo, int nParm1 /*= 0*/, int nParm2 /*= 0*/, int nParm3 /*= 0*/, int nParm4 /*= 0*/)
{
#ifdef SHOW_SHUTDOWNSRV_STEPS
static int nDbg = 0;
if (!nDbg)
nDbg = IsDebuggerPresent() ? 1 : 2;
if (nDbg != 1)
return;
wchar_t szFull[512];
msprintf(szFull, countof(szFull), L"%u:ConEmuC:PID=%u:TID=%u: ",
GetTickCount(), GetCurrentProcessId(), GetCurrentThreadId());
if (asInfo)
{
int nLen = lstrlen(szFull);
msprintf(szFull+nLen, countof(szFull)-nLen, asInfo, nParm1, nParm2, nParm3, nParm4);
}
lstrcat(szFull, L"\n");
OutputDebugString(szFull);
#endif
}
void InitVersion()
{
wchar_t szMinor[8] = L""; lstrcpyn(szMinor, _T(MVV_4a), countof(szMinor));
//msprintf не умеет "%02u"
swprintf_c(gsVersion, L"%02u%02u%02u%s", MVV_1, MVV_2, MVV_3, szMinor);
}
#ifdef _DEBUG
int ShowInjectRemoteMsg(int nRemotePID, LPCWSTR asCmdArg)
{
int iBtn = IDOK;
#ifdef SHOW_INJECTREM_MSGBOX
wchar_t szDbgMsg[512], szTitle[128];
PROCESSENTRY32 pinf;
GetProcessInfo(nRemotePID, &pinf);
swprintf_c(szTitle, L"ConEmuCD PID=%u", GetCurrentProcessId());
swprintf_c(szDbgMsg, L"Hooking PID=%s {%s}\nConEmuCD PID=%u. Continue with injects?", asCmdArg ? asCmdArg : L"", pinf.szExeFile, GetCurrentProcessId());
iBtn = MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL|MB_OKCANCEL);
#endif
return iBtn;
}
#endif
//UINT gnMsgActivateCon = 0;
UINT gnMsgSwitchCon = 0;
UINT gnMsgHookedKey = 0;
//UINT gnMsgConsoleHookedKey = 0;
void LoadSrvInfoMap(LPCWSTR pszExeName = NULL, LPCWSTR pszDllName = NULL)
{
if (ghConWnd)
{
MFileMapping<CESERVER_CONSOLE_MAPPING_HDR> ConInfo;
ConInfo.InitName(CECONMAPNAME, LODWORD(ghConWnd)); //-V205
CESERVER_CONSOLE_MAPPING_HDR *pInfo = ConInfo.Open();
if (pInfo)
{
if (pInfo->cbSize >= sizeof(CESERVER_CONSOLE_MAPPING_HDR))
{
if (pInfo->hConEmuRoot && IsWindow(pInfo->hConEmuRoot))
{
SetConEmuWindows(pInfo->hConEmuRoot, pInfo->hConEmuWndDc, pInfo->hConEmuWndBack);
}
if (pInfo->nServerPID && pInfo->nServerPID != gnSelfPID)
{
gnMainServerPID = pInfo->nServerPID;
gnAltServerPID = pInfo->nAltServerPID;
}
gbLogProcess = (pInfo->nLoggingType == glt_Processes);
if (pszExeName && gbLogProcess)
{
CEStr lsDir;
int ImageBits = 0, ImageSystem = 0;
#ifdef _WIN64
ImageBits = 64;
#else
ImageBits = 32;
#endif
CESERVER_REQ* pIn = ExecuteNewCmdOnCreate(pInfo, ghConWnd, eSrvLoaded,
L"", pszExeName, pszDllName, GetDirectory(lsDir), NULL, NULL, NULL, NULL,
ImageBits, ImageSystem,
GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE));
if (pIn)
{
CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
ExecuteFreeResult(pIn);
if (pOut) ExecuteFreeResult(pOut);
}
}
ConInfo.CloseMap();
}
else
{
_ASSERTE(pInfo->cbSize == sizeof(CESERVER_CONSOLE_MAPPING_HDR));
}
}
}
}
#if defined(__GNUC__)
extern "C"
#endif
BOOL WINAPI DllMain(HINSTANCE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
ghOurModule = (HMODULE)hModule;
ghWorkingModule = hModule;
hkFunc.Init(WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"), ghOurModule);
DWORD nImageBits = WIN3264TEST(32,64), nImageSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
GetImageSubsystem(nImageSubsystem,nImageBits);
if (nImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
ghConWnd = NULL;
else
ghConWnd = GetConEmuHWND(2);
gnSelfPID = GetCurrentProcessId();
gfnSearchAppPaths = SearchAppPaths;
wchar_t szExeName[MAX_PATH] = L"", szDllName[MAX_PATH] = L"";
GetModuleFileName(NULL, szExeName, countof(szExeName));
GetModuleFileName((HMODULE)hModule, szDllName, countof(szDllName));
if (IsConsoleServer(PointToName(szExeName)))
wcscpy_c(gsModuleName, WIN3264TEST(L"ConEmuC",L"ConEmuC64"));
else
wcscpy_c(gsModuleName, WIN3264TEST(L"ConEmuCD",L"ConEmuCD64"));
InitVersion();
#ifdef _DEBUG
HANDLE hProcHeap = GetProcessHeap();
gAllowAssertThread = am_Pipe;
#endif
#ifdef SHOW_STARTED_MSGBOX
if (!IsDebuggerPresent())
{
char szMsg[128] = ""; msprintf(szMsg, countof(szMsg), WIN3264TEST("ConEmuCD.dll","ConEmuCD64.dll") " loaded, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
char szFile[MAX_PATH] = ""; GetModuleFileNameA(NULL, szFile, countof(szFile));
MessageBoxA(NULL, szMsg, PointToName(szFile), 0);
}
#endif
#ifdef _DEBUG
DWORD dwConMode = -1;
GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &dwConMode);
#endif
//_ASSERTE(ghHeap == NULL);
//ghHeap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 200000, 0);
HeapInitialize();
/* *** DEBUG PURPOSES */
gpStartEnv = LoadStartupEnvEx::Create();
/* *** DEBUG PURPOSES */
// Preload some function pointers to get proper addresses,
// before some other hooking dlls may replace them
GetLoadLibraryAddress(); // gfLoadLibrary
if (IsWin7()) // and gfLdrGetDllHandleByName
GetLdrGetDllHandleByNameAddress();
//#ifndef TESTLINK
gpLocalSecurity = LocalSecurity();
//gnMsgActivateCon = RegisterWindowMessage(CONEMUMSG_ACTIVATECON);
gnMsgSwitchCon = RegisterWindowMessage(CONEMUMSG_SWITCHCON);
gnMsgHookedKey = RegisterWindowMessage(CONEMUMSG_HOOKEDKEY);
//gnMsgConsoleHookedKey = RegisterWindowMessage(CONEMUMSG_CONSOLEHOOKEDKEY);
//#endif
//wchar_t szSkipEventName[128];
//swprintf_c(szSkipEventName, CEHOOKDISABLEEVENT, GetCurrentProcessId());
//HANDLE hSkipEvent = OpenEvent(EVENT_ALL_ACCESS , FALSE, szSkipEventName);
////BOOL lbSkipInjects = FALSE;
//if (hSkipEvent)
//{
// gbSkipInjects = (WaitForSingleObject(hSkipEvent, 0) == WAIT_OBJECT_0);
// CloseHandle(hSkipEvent);
//}
//else
//{
// gbSkipInjects = FALSE;
//}
// Открыть мэппинг консоли и попытаться получить HWND GUI, PID сервера, и пр...
if (ghConWnd)
LoadSrvInfoMap(szExeName, szDllName);
//if (!gbSkipInjects && ghConWnd)
//{
// InitializeConsoleInputSemaphore();
//}
//#ifdef _WIN64
//DWORD nImageBits = 64, nImageSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
//#else
//DWORD nImageBits = 32, nImageSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
//#endif
//GetImageSubsystem(nImageSubsystem,nImageBits);
//CShellProc sp;
//if (sp.LoadGuiMapping())
//{
// wchar_t szExeName[MAX_PATH+1]; //, szBaseDir[MAX_PATH+2];
// //BOOL lbDosBoxAllowed = FALSE;
// if (!GetModuleFileName(NULL, szExeName, countof(szExeName))) szExeName[0] = 0;
// CESERVER_REQ* pIn = sp.NewCmdOnCreate(
// gbSkipInjects ? eHooksLoaded : eInjectingHooks,
// L"", szExeName, GetCommandLineW(),
// NULL, NULL, NULL, NULL, // flags
// nImageBits, nImageSubsystem,
// GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE));
// if (pIn)
// {
// //HWND hConWnd = GetConEmuHWND(2);
// CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
// ExecuteFreeResult(pIn);
// if (pOut) ExecuteFreeResult(pOut);
// }
//}
//if (!gbSkipInjects)
//{
// #ifdef _DEBUG
// wchar_t szModule[MAX_PATH+1]; szModule[0] = 0;
// #endif
// #ifdef SHOW_INJECT_MSGBOX
// wchar_t szDbgMsg[1024], szTitle[128];//, szModule[MAX_PATH];
// if (!GetModuleFileName(NULL, szModule, countof(szModule)))
// wcscpy_c(szModule, L"GetModuleFileName failed");
// swprintf_c(szTitle, L"ConEmuHk, PID=%u", GetCurrentProcessId());
// swprintf_c(szDbgMsg, L"SetAllHooks, ConEmuHk, PID=%u\n%s", GetCurrentProcessId(), szModule);
// MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
// #endif
// gnRunMode = RM_APPLICATION;
// #ifdef _DEBUG
// //wchar_t szModule[MAX_PATH+1]; szModule[0] = 0;
// GetModuleFileName(NULL, szModule, countof(szModule));
// const wchar_t* pszName = PointToName(szModule);
// _ASSERTE((nImageSubsystem==IMAGE_SUBSYSTEM_WINDOWS_CUI) || (lstrcmpi(pszName, L"DosBox.exe")==0));
// //if (!lstrcmpi(pszName, L"far.exe") || !lstrcmpi(pszName, L"mingw32-make.exe"))
// //if (!lstrcmpi(pszName, L"as.exe"))
// // MessageBoxW(NULL, L"as.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
// //else if (!lstrcmpi(pszName, L"cc1plus.exe"))
// // MessageBoxW(NULL, L"cc1plus.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
// //else if (!lstrcmpi(pszName, L"mingw32-make.exe"))
// // MessageBoxW(NULL, L"mingw32-make.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
// //if (!lstrcmpi(pszName, L"g++.exe"))
// // MessageBoxW(NULL, L"g++.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
// //{
// #endif
// gbHooksWasSet = StartupHooks(ghOurModule);
// #ifdef _DEBUG
// //}
// #endif
// // Если NULL - значит это "Detached" консольный процесс, посылать "Started" в сервер смысла нет
// if (ghConWnd != NULL)
// {
// SendStarted();
// //#ifdef _DEBUG
// //// Здесь это приводит к обвалу _chkstk,
// //// похоже из-за того, что dll-ка загружена НЕ из известных модулей,
// //// а из специально сформированного блока памяти
// // -- в одной из функций, под локальные переменные выделялось слишком много памяти
// // -- переделал в malloc/free, все заработало
// //TestShellProcessor();
// //#endif
// }
//}
//else
//{
// gbHooksWasSet = FALSE;
//}
}
break;
case DLL_PROCESS_DETACH:
{
ShutdownSrvStep(L"DLL_PROCESS_DETACH");
//if (!gbSkipInjects && gbHooksWasSet)
//{
// gbHooksWasSet = FALSE;
// ShutdownHooks();
//}
#ifdef _DEBUG
if ((gnRunMode == RM_SERVER) && (nExitPlaceStep == EPS_WAITING4PROCESS/*550*/))
{
// Это происходило после Ctrl+C если не был установлен HandlerRoutine
// Ни _ASSERT ни DebugBreak здесь позвать уже не получится - все закрывается и игнорируется
OutputDebugString(L"!!! Server was abnormally terminated !!!\n");
LogString("!!! Server was abnormally terminated !!!\n");
}
#endif
if ((gnRunMode == RM_APPLICATION) || (gnRunMode == RM_ALTSERVER))
{
SendStopped();
}
//else if (gnRunMode == RM_ALTSERVER)
//{
// WARNING("RM_ALTSERVER тоже должен посылать уведомление в главный сервер о своем завершении");
// // Но пока - оставим, для отладки ситуации, когда процесс завершается аварийно (Kill).
// _ASSERTE(gnRunMode != RM_ALTSERVER && "AltServer must inform MainServer about self-termination");
//}
//#ifndef TESTLINK
CommonShutdown();
//ReleaseConsoleInputSemaphore();
//#endif
//if (ghHeap)
//{
// HeapDestroy(ghHeap);
// ghHeap = NULL;
//}
HeapDeinitialize();
ShutdownSrvStep(L"DLL_PROCESS_DETACH done");
}
break;
}
return TRUE;
}
//#if defined(GNUCRTSTARTUP)
//extern "C" {
// BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved);
//};
//
//BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved)
//{
// DllMain(hDll, dwReason, lpReserved);
// return TRUE;
//}
//#endif
#ifdef _DEBUG
void OnProcessCreatedDbg(BOOL bRc, DWORD dwErr, LPPROCESS_INFORMATION pProcessInformation, LPSHELLEXECUTEINFO pSEI)
{
int iDbg = 0;
#ifdef SHOW_ASYNC_STARTED
if (gbAsyncRun)
{
_ASSERTE(FALSE && "Async startup requested");
}
#endif
#ifdef SHOW_ROOT_STARTED
if (bRc)
{
wchar_t szTitle[64], szMsg[128];
swprintf_c(szTitle, L"ConEmuSrv, PID=%u", GetCurrentProcessId());
swprintf_c(szMsg, L"Root process started, PID=%u", pProcessInformation->dwProcessId);
MessageBox(NULL,szMsg,szTitle,0);
}
#endif
}
#endif
BOOL createProcess(BOOL abSkipWowChange, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
{
CEStr fnDescr(lstrmerge(L"createProcess App={", lpApplicationName, L"} Cmd={", lpCommandLine, L"}"));
LogFunction(fnDescr);
MWow64Disable wow;
if (!abSkipWowChange)
wow.Disable();
// %PATHS% from [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths]
// must be already processed in IsNeedCmd >> FileExistsSearch >> SearchAppPaths
DWORD nStartTick = GetTickCount();
#if defined(SHOW_STARTED_PRINT_LITE)
if (gnRunMode == RM_SERVER)
{
_printf("Starting root: ");
_wprintf(lpCommandLine ? lpCommandLine : lpApplicationName ? lpApplicationName : L"<NULL>");
}
#endif
SetLastError(0);
BOOL lbRc = CreateProcess(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
DWORD dwErr = GetLastError();
DWORD nStartDuration = GetTickCount() - nStartTick;
wchar_t szRunRc[80];
if (lbRc)
swprintf_c(szRunRc, L"Succeeded (%u ms) PID=%u", nStartDuration, lpProcessInformation->dwProcessId);
else
swprintf_c(szRunRc, L"Failed (%u ms) Code=%u(x%04X)", nStartDuration, dwErr, dwErr);
LogFunction(szRunRc);
#if defined(SHOW_STARTED_PRINT_LITE)
if (gnRunMode == RM_SERVER)
{
if (lbRc)
_printf("\nSuccess (%u ms), PID=%u\n\n", nStartDuration, lpProcessInformation->dwProcessId);
else
_printf("\nFailed (%u ms), Error code=%u(x%04X)\n", nStartDuration, dwErr, dwErr);
}
#endif
#ifdef _DEBUG
OnProcessCreatedDbg(lbRc, dwErr, lpProcessInformation, NULL);
#endif
if (!abSkipWowChange)
{
wow.Restore();
}
SetLastError(dwErr);
return lbRc;
}
// Возвращает текст с информацией о пути к сохраненному дампу
// DWORD CreateDumpForReport(LPEXCEPTION_POINTERS ExceptionInfo, wchar_t (&szFullInfo)[1024], LPWSTR pszComment = NULL);
#include "../common/Dump.h"
bool CopyToClipboard(LPCWSTR asText)
{
if (!asText)
return false;
bool bCopied = false;
if (OpenClipboard(NULL))
{
DWORD cch = lstrlen(asText);
HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (cch + 1) * sizeof(*asText));
if (hglbCopy)
{
wchar_t* lptstrCopy = (wchar_t*)GlobalLock(hglbCopy);
if (lptstrCopy)
{
_wcscpy_c(lptstrCopy, cch+1, asText);
GlobalUnlock(hglbCopy);
EmptyClipboard();
bCopied = (SetClipboardData(CF_UNICODETEXT, hglbCopy) != NULL);
}
}
CloseClipboard();
}
return bCopied;
}
LPTOP_LEVEL_EXCEPTION_FILTER gpfnPrevExFilter = NULL;
bool gbCreateDumpOnExceptionInstalled = false;
LONG WINAPI CreateDumpOnException(LPEXCEPTION_POINTERS ExceptionInfo)
{
bool bKernelTrap = (gnInReadConsoleOutput > 0);
wchar_t szExcptInfo[1024] = L"";
wchar_t szDmpFile[MAX_PATH+64] = L"";
wchar_t szAdd[2000];
DWORD dwErr = CreateDumpForReport(ExceptionInfo, szExcptInfo, szDmpFile);
szAdd[0] = 0;
if (bKernelTrap)
{
wcscat_c(szAdd, L"Due to Microsoft kernel bug the crash was occurred\r\n");
wcscat_c(szAdd, CEMSBUGWIKI /* http://conemu.github.io/en/MicrosoftBugs.html */);
wcscat_c(szAdd, L"\r\n\r\n" L"The only possible workaround: enabling ‘Inject ConEmuHk’\r\n");
wcscat_c(szAdd, CEHOOKSWIKI /* http://conemu.github.io/en/ConEmuHk.html */);
wcscat_c(szAdd, L"\r\n\r\n");
}
wcscat_c(szAdd, szExcptInfo);
if (szDmpFile[0])
{
wcscat_c(szAdd, L"\r\n\r\n" L"Memory dump was saved to\r\n");
wcscat_c(szAdd, szDmpFile);
if (!bKernelTrap)
{
wcscat_c(szAdd, L"\r\n\r\n" L"Please Zip it and send to developer (via DropBox etc.)\r\n");
wcscat_c(szAdd, CEREPORTCRASH /* http://conemu.github.io/en/Issues.html... */);
}
}
wcscat_c(szAdd, L"\r\n\r\nPress <Yes> to copy this text to clipboard");
if (!bKernelTrap)
{
wcscat_c(szAdd, L"\r\nand open project web page");
}
// Message title
wchar_t szTitle[100], szExe[MAX_PATH] = L"", *pszExeName;
GetModuleFileName(NULL, szExe, countof(szExe));
pszExeName = (wchar_t*)PointToName(szExe);
if (pszExeName && lstrlen(pszExeName) > 63) pszExeName[63] = 0;
swprintf_c(szTitle, L"%s crashed, PID=%u", pszExeName ? pszExeName : L"<process>", GetCurrentProcessId());
DWORD nMsgFlags = MB_YESNO|MB_ICONSTOP|MB_SYSTEMMODAL
| (bKernelTrap ? MB_DEFBUTTON2 : 0);
int nBtn = MessageBox(NULL, szAdd, szTitle, nMsgFlags);
if (nBtn == IDYES)
{
CopyToClipboard(szAdd);
if (!bKernelTrap)
{
ShellExecute(NULL, L"open", CEREPORTCRASH, NULL, NULL, SW_SHOWNORMAL);
}
}
LONG lExRc = EXCEPTION_EXECUTE_HANDLER;
if (gpfnPrevExFilter)
{
// если фильтр уже был установлен перед нашим - будем звать его
// все-равно уже свалились, на валидность адреса можно не проверяться
lExRc = gpfnPrevExFilter(ExceptionInfo);
}
return lExRc;
}
void SetupCreateDumpOnException()
{
if (gnRunMode == RM_GUIMACRO)
{
// Must not be called in GuiMacro mode!
_ASSERTE(gnRunMode!=RM_GUIMACRO);
return;
}
// По умолчанию - фильтр в AltServer не включается, но в настройках ConEmu есть опция
// gpSet->isConsoleExceptionHandler --> CECF_ConExcHandler
_ASSERTE((gnRunMode == RM_ALTSERVER) && (gpSrv->pConsole && (gpSrv->pConsole->hdr.Flags & CECF_ConExcHandler)));
// Far 3.x, telnet, Vim, etc.
// В этих программах ConEmuCD.dll может загружаться для работы с альтернативными буферами и TrueColor
if (!gpfnPrevExFilter && !IsDebuggerPresent())
{
// Сохраним, если фильтр уже был установлен - будем звать его из нашей функции
gpfnPrevExFilter = SetUnhandledExceptionFilter(CreateDumpOnException);
gbCreateDumpOnExceptionInstalled = true;
}
}
#ifdef SHOW_SERVER_STARTED_MSGBOX
void ShowServerStartedMsgBox(LPCWSTR asCmdLine)
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"ConEmuC [Server] started (PID=%i)", gnSelfPID);
const wchar_t* pszCmdLine = asCmdLine;
MessageBox(NULL,pszCmdLine,szTitle,0);
}
#endif
void LoadExePath()
{
// Already loaded?
if (gsSelfExe[0] && gsSelfPath[0])
return;
DWORD nSelfLen = GetModuleFileNameW(NULL, gsSelfExe, countof(gsSelfExe));
if (!nSelfLen || (nSelfLen >= countof(gsSelfExe)))
{
_ASSERTE(FALSE && "GetModuleFileNameW(NULL) failed");
gsSelfExe[0] = 0;
}
else
{
lstrcpyn(gsSelfPath, gsSelfExe, countof(gsSelfPath));
wchar_t* pszSlash = (wchar_t*)PointToName(gsSelfPath);
if (pszSlash && (pszSlash > gsSelfPath))
*pszSlash = 0;
else
gsSelfPath[0] = 0;
}
}
void UnlockCurrentDirectory()
{
if ((gnRunMode == RM_SERVER) && gsSelfPath[0])
{
SetCurrentDirectory(gsSelfPath);
}
}
bool CheckAndWarnHookers()
{
if (gbSkipHookersCheck)
{
if (gpLogSize) gpLogSize->LogString(L"CheckAndWarnHookers skipped due to /OMITHOOKSWARN switch");
return false;
}
bool bHooked = false;
struct CheckModules {
LPCWSTR Title, File;
} modules [] = {
{L"MacType", WIN3264TEST(L"MacType.dll", L"MacType64.dll")},
{L"AnsiCon", WIN3264TEST(L"ANSI32.dll", L"ANSI64.dll")},
{NULL}
};
CEStr szMessage;
wchar_t szPath[MAX_PATH+16] = L"", szAddress[32] = L"";
LPCWSTR pszTitle = NULL, pszName = NULL;
HMODULE hModule = NULL;
bool bConOutChecked = false, bRedirected = false;
//BOOL bColorChanged = FALSE;
CONSOLE_SCREEN_BUFFER_INFO sbi = {};
HANDLE hOut = NULL;
for (INT_PTR i = 0; modules[i].Title; i++)
{
pszTitle = modules[i].Title;
pszName = modules[i].File;
hModule = GetModuleHandle(pszName);
if (hModule)
{
bHooked = true;
if (!GetModuleFileName(hModule, szPath, countof(szPath)))
{
wcscpy_c(szPath, pszName); // Must not get here, but show a name at least on errors
}
if (!bConOutChecked)
{
bConOutChecked = true;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut, &sbi);
bRedirected = IsOutputRedirected();
#if 0
// Useless in most cases, most of users are running cmd.exe
// but it clears all existing text attributes on start
if (!bRedirected)
bColorChanged = SetConsoleTextAttribute(hOut, 12); // LightRed on Black
#endif
}
swprintf_c(szAddress, WIN3264TEST(L"0x%08X",L"0x%08X%08X"), WIN3264WSPRINT((DWORD_PTR)hModule));
szMessage = lstrmerge(
L"WARNING! The ", pszTitle, L"'s hooks are detected at ", szAddress, L"\r\n"
L" ");
LPCWSTR pszTail = L"\r\n"
L" Please add ConEmuC.exe and ConEmuC64.exe\r\n"
L" to the exclusion list to avoid crashes!\r\n"
L" " CEMACTYPEWARN L"\r\n\r\n";
_wprintf(szMessage);
_wprintf(szPath);
_wprintf(pszTail);
}
}
#if 0
// If we've set warning colors - return original ones
if (bColorChanged)
SetConsoleTextAttribute(hOut, sbi.wAttributes);
#endif
return bHooked;
}
// Main entry point for ConEmuC.exe
#if defined(__GNUC__)
extern "C"
#endif
int __stdcall ConsoleMain3(int anWorkMode/*0-Server&ComSpec,1-AltServer,2-Reserved,3-GuiMacro*/, LPCWSTR asCmdLine)
{
#if defined(SHOW_MAIN_MSGBOX) || defined(SHOW_ADMIN_STARTED_MSGBOX)
bool bShowWarn = false;
#if defined(SHOW_MAIN_MSGBOX)
if (!IsDebuggerPresent()) bShowWarn = true;
#endif
#if defined(SHOW_ADMIN_STARTED_MSGBOX)
if (IsUserAdmin()) bShowWarn = true;
#endif
if (bShowWarn)
{
char szMsg[MAX_PATH+128]; msprintf(szMsg, countof(szMsg), WIN3264TEST("ConEmuCD.dll","ConEmuCD64.dll") " loaded, PID=%u, TID=%u\r\n", GetCurrentProcessId(), GetCurrentThreadId());
int nMsgLen = lstrlenA(szMsg);
GetModuleFileNameA(NULL, szMsg+nMsgLen, countof(szMsg)-nMsgLen);
MessageBoxA(NULL, szMsg, "ConEmu server" WIN3264TEST(""," x64"), 0);
}
#endif
if (!anWorkMode)
{
if (!IsDebuggerPresent())
{
// Наш exe-шник, gpfnPrevExFilter не нужен
SetUnhandledExceptionFilter(CreateDumpOnException);
gbCreateDumpOnExceptionInstalled = true;
}
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleMode(hOut, ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT);
WARNING("Этот атрибут нужно задавать в настройках GUI!");
#if 0
SetConsoleTextAttribute(hOut, 7);
#endif
}
switch (anWorkMode)
{
case 0:
gnRunMode = RM_SERVER; break;
case 1:
gnRunMode = RM_ALTSERVER; break;
case 3:
gnRunMode = RM_GUIMACRO; break;
default:
gnRunMode = RM_UNDEFINED;
}
// Check linker fails!
if (ghOurModule == NULL)
{
wchar_t szTitle[128]; swprintf_c(szTitle, WIN3264TEST(L"ConEmuCD",L"ConEmuCD64") L", PID=%u", GetCurrentProcessId());
MessageBox(NULL, L"ConsoleMain2: ghOurModule is NULL\nDllMain was not executed", szTitle, MB_ICONSTOP|MB_SYSTEMMODAL);
return CERR_DLLMAIN_SKIPPED;
}
if (!gpSrv && (gnRunMode != RM_GUIMACRO))
gpSrv = (SrvInfo*)calloc(sizeof(SrvInfo),1);
if (gpSrv)
{
gpSrv->InitFields();
if (ghConEmuWnd)
{
GetWindowThreadProcessId(ghConEmuWnd, &gnConEmuPID);
}
}
#if defined(SHOW_STARTED_PRINT)
BOOL lbDbgWrite; DWORD nDbgWrite; HANDLE hDbg; char szDbgString[255], szHandles[128];
wchar_t szTitle[255];
swprintf_c(szTitle, L"ConEmuCD[%u]: PID=%u", WIN3264TEST(32,64), GetCurrentProcessId());
MessageBox(0, asCmdLine, szTitle, MB_SYSTEMMODAL);
hDbg = CreateFile(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
sprintf_c(szHandles, "STD_OUTPUT_HANDLE(0x%08X) STD_ERROR_HANDLE(0x%08X) CONOUT$(0x%08X)",
(DWORD)GetStdHandle(STD_OUTPUT_HANDLE), (DWORD)GetStdHandle(STD_ERROR_HANDLE), (DWORD)hDbg);
printf("ConEmuC: Printf: %s\n", szHandles);
sprintf_c(szDbgString, "ConEmuC: STD_OUTPUT_HANDLE: %s\n", szHandles);
lbDbgWrite = WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), szDbgString, lstrlenA(szDbgString), &nDbgWrite, NULL);
sprintf_c(szDbgString, "ConEmuC: STD_ERROR_HANDLE: %s\n", szHandles);
lbDbgWrite = WriteFile(GetStdHandle(STD_ERROR_HANDLE), szDbgString, lstrlenA(szDbgString), &nDbgWrite, NULL);
sprintf_c(szDbgString, "ConEmuC: CONOUT$: %s", szHandles);
lbDbgWrite = WriteFile(hDbg, szDbgString, lstrlenA(szDbgString), &nDbgWrite, NULL);
CloseHandle(hDbg);
//sprintf_c(szDbgString, "ConEmuC: PID=%u", GetCurrentProcessId());
//MessageBoxA(0, "Press Ok to continue", szDbgString, MB_SYSTEMMODAL);
#elif defined(SHOW_STARTED_PRINT_LITE)
{
wchar_t szPath[MAX_PATH]; GetModuleFileNameW(NULL, szPath, countof(szPath));
wchar_t szDbgMsg[MAX_PATH*2];
swprintf_c(szDbgMsg, L"%s started, PID=%u\n", PointToName(szPath), GetCurrentProcessId());
_wprintf(szDbgMsg);
gbDumpServerInitStatus = TRUE;
}
#endif
int iRc = 100;
PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(pi));
STARTUPINFOW si = {sizeof(STARTUPINFOW)};
// ConEmuC должен быть максимально прозрачен для конечного процесса
GetStartupInfo(&si);
DWORD dwErr = 0, nWait = 0, nWaitExitEvent = -1, nWaitDebugExit = -1, nWaitComspecExit = -1;
DWORD dwWaitGui = -1, dwWaitRoot = -1;
BOOL lbRc = FALSE;
//DWORD mode = 0;
//BOOL lb = FALSE;
//ghHeap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 200000, 0);
memset(&gOSVer, 0, sizeof(gOSVer));
gOSVer.dwOSVersionInfoSize = sizeof(gOSVer);
GetOsVersionInformational(&gOSVer);
gnOsVer = ((gOSVer.dwMajorVersion & 0xFF) << 8) | (gOSVer.dwMinorVersion & 0xFF);
gbIsWine = IsWine(); // В общем случае, на флажок ориентироваться нельзя. Это для информации.
gbIsDBCS = IsWinDBCS();
gpLocalSecurity = LocalSecurity();
HMODULE hKernel = GetModuleHandleW(L"kernel32.dll");
// Хэндл консольного окна
ghConWnd = GetConEmuHWND(2);
gbVisibleOnStartup = IsWindowVisible(ghConWnd);
// здесь действительно может быть NULL при запуска как detached comspec
//_ASSERTE(ghConWnd!=NULL);
//if (!ghConWnd)
//{
// dwErr = GetLastError();
// _printf("ghConWnd==NULL, ErrCode=0x%08X\n", dwErr);
// iRc = CERR_GETCONSOLEWINDOW; goto wrap;
//}
// PID
gnSelfPID = GetCurrentProcessId();
gdwMainThreadId = GetCurrentThreadId();
DWORD nCurrentPIDCount = 0, nCurrentPIDs[64] = {};
if (hKernel)
{
pfnGetConsoleKeyboardLayoutName = (FGetConsoleKeyboardLayoutName)GetProcAddress(hKernel, "GetConsoleKeyboardLayoutNameW");
pfnGetConsoleProcessList = (FGetConsoleProcessList)GetProcAddress(hKernel, "GetConsoleProcessList");
pfnGetConsoleDisplayMode = (FGetConsoleDisplayMode)GetProcAddress(hKernel, "GetConsoleDisplayMode");
}
#ifdef _DEBUG
if (ghConWnd)
{
// Это событие дергается в отладочной (мной поправленной) версии фара
// Suppress warning C4311 'type cast': pointer truncation from 'HWND' to 'DWORD'
wchar_t szEvtName[64]; swprintf_c(szEvtName, L"FARconEXEC:%08X", LODWORD(ghConWnd));
ghFarInExecuteEvent = CreateEvent(0, TRUE, FALSE, szEvtName);
}
#endif
#if defined(SHOW_STARTED_MSGBOX) || defined(SHOW_COMSPEC_STARTED_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"ConEmuCD[%u]: PID=%u", WIN3264TEST(32,64), GetCurrentProcessId());
MessageBox(NULL, asCmdLine, szTitle, MB_SYSTEMMODAL);
}
#endif
#ifdef SHOW_STARTED_ASSERT
if (!IsDebuggerPresent())
{
_ASSERT(FALSE);
}
#endif
LoadExePath();
PRINT_COMSPEC(L"ConEmuC started: %s\n", asCmdLine);
nExitPlaceStep = 50;
xf_check();
#ifdef _DEBUG
{
wchar_t szCpInfo[128];
DWORD nCP = GetConsoleOutputCP();
swprintf_c(szCpInfo, L"Current Output CP = %u\n", nCP);
DEBUGSTRCP(szCpInfo);
}
#endif
// Event is used in almost all modes, even in "debugger"
if (!ghExitQueryEvent
&& (gnRunMode != RM_GUIMACRO)
)
{
ghExitQueryEvent = CreateEvent(NULL, TRUE/*используется в нескольких нитях, manual*/, FALSE, NULL);
}
LPCWSTR pszFullCmdLine = asCmdLine;
wchar_t szDebugCmdLine[MAX_PATH];
lstrcpyn(szDebugCmdLine, pszFullCmdLine ? pszFullCmdLine : L"", countof(szDebugCmdLine));
if (gnRunMode == RM_GUIMACRO)
{
// Separate parser function
iRc = GuiMacroCommandLine(pszFullCmdLine);
_ASSERTE(iRc == CERR_GUIMACRO_SUCCEEDED || iRc == CERR_GUIMACRO_FAILED);
goto wrap;
}
else if (anWorkMode)
{
// Alternative mode
_ASSERTE(anWorkMode==1); // может еще и 2 появится - для StandAloneGui
_ASSERTE(gnRunMode == RM_UNDEFINED || gnRunMode == RM_ALTSERVER);
gnRunMode = RM_ALTSERVER;
_ASSERTE(!gbCreateDumpOnExceptionInstalled);
_ASSERTE(gbAttachMode==am_None);
if (!(gbAttachMode & am_Modes))
gbAttachMode |= am_Simple;
gnConfirmExitParm = RConStartArgs::eConfNever;
gbAlwaysConfirmExit = FALSE; gbAutoDisableConfirmExit = FALSE;
gbNoCreateProcess = TRUE;
gbAlienMode = TRUE;
gpSrv->dwRootProcess = GetCurrentProcessId();
gpSrv->hRootProcess = GetCurrentProcess();
//gnConEmuPID = ...;
gpszRunCmd = (wchar_t*)calloc(1,2);
CreateColorerHeader();
}
else if ((iRc = ParseCommandLine(pszFullCmdLine)) != 0)
{
wchar_t szLog[80];
swprintf_c(szLog, L"ParseCommandLine returns %i, exiting", iRc);
LogFunction(szLog);
// Especially if our process was started under non-interactive account,
// than ExitWaitForKey causes the infinitely running process, which user can't kill easily
gbInShutdown = true;
goto wrap;
}
if (gbInShutdown)
goto wrap;
// По идее, при вызове дебаггера ParseCommandLine сразу должна послать на выход.
_ASSERTE(!(gpSrv->DbgInfo.bDebuggerActive || gpSrv->DbgInfo.bDebugProcess || gpSrv->DbgInfo.bDebugProcessTree))
if (gnRunMode == RM_SERVER)
{
// Until the root process is not terminated - set to STILL_ACTIVE
gnExitCode = STILL_ACTIVE;
#ifdef _DEBUG
// отладка для Wine
#ifdef USE_PIPE_DEBUG_BOXES
gbPipeDebugBoxes = true;
#endif
if (gbIsWine)
{
wchar_t szMsg[128];
msprintf(szMsg, countof(szMsg), L"ConEmuC Started, Wine detected\r\nConHWND=x%08X(%u), PID=%u\r\nCmdLine: ",
LODWORD(ghConWnd), LODWORD(ghConWnd), gnSelfPID);
_wprintf(szMsg);
_wprintf(asCmdLine);
_wprintf(L"\r\n");
}
#endif
// Warn about external hookers
CheckAndWarnHookers();
}
_ASSERTE(!gpSrv->hRootProcessGui || ((LODWORD(gpSrv->hRootProcessGui))!=0xCCCCCCCC && IsWindow(gpSrv->hRootProcessGui)));
//#ifdef _DEBUG
//CreateLogSizeFile();
//#endif
nExitPlaceStep = 100;
xf_check();
#ifdef SHOW_SERVER_STARTED_MSGBOX
if ((gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER) && !IsDebuggerPresent() && gbNoCreateProcess)
{
ShowServerStartedMsgBox(asCmdLine);
}
#endif
/* ***************************** */
/* *** "Общая" инициализация *** */
/* ***************************** */
nExitPlaceStep = 150;
if (!ghExitQueryEvent)
{
dwErr = GetLastError();
_printf("CreateEvent() failed, ErrCode=0x%08X\n", dwErr);
iRc = CERR_EXITEVENT; goto wrap;
}
ResetEvent(ghExitQueryEvent);
if (!ghQuitEvent)
ghQuitEvent = CreateEvent(NULL, TRUE/*used in several threads, manual!*/, FALSE, NULL);
if (!ghQuitEvent)
{
dwErr = GetLastError();
_printf("CreateEvent() failed, ErrCode=0x%08X\n", dwErr);
iRc = CERR_EXITEVENT; goto wrap;
}
ResetEvent(ghQuitEvent);
xf_check();
if (gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER || gnRunMode == RM_AUTOATTACH)
{
if ((HANDLE)ghConOut == INVALID_HANDLE_VALUE)
{
dwErr = GetLastError();
_printf("CreateFile(CONOUT$) failed, ErrCode=0x%08X\n", dwErr);
iRc = CERR_CONOUTFAILED; goto wrap;
}
if (pfnGetConsoleProcessList)
{
SetLastError(0);
nCurrentPIDCount = pfnGetConsoleProcessList(nCurrentPIDs, countof(nCurrentPIDs));
// Wine bug
if (!nCurrentPIDCount)
{
DWORD nErr = GetLastError();
_ASSERTE(nCurrentPIDCount || gbIsWine);
wchar_t szDbgMsg[512], szFile[MAX_PATH] = {};
GetModuleFileName(NULL, szFile, countof(szFile));
msprintf(szDbgMsg, countof(szDbgMsg), L"%s: PID=%u: GetConsoleProcessList failed, code=%u\r\n", PointToName(szFile), gnSelfPID, nErr);
_wprintf(szDbgMsg);
pfnGetConsoleProcessList = NULL;
}
}
}
nExitPlaceStep = 200;
/* ******************************** */
/* ****** "Server-mode" init ****** */
/* ******************************** */
if (gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER || gnRunMode == RM_AUTOATTACH)
{
_ASSERTE(anWorkMode == (gnRunMode == RM_ALTSERVER));
if ((iRc = ServerInit()) != 0)
{
nExitPlaceStep = 250;
goto wrap;
}
}
else
{
xf_check();
if ((iRc = ComspecInit()) != 0)
{
nExitPlaceStep = 300;
goto wrap;
}
}
/* ********************************* */
/* ****** Start child process ****** */
/* ********************************* */
#ifdef SHOW_STARTED_PRINT
sprintf_c(szDbgString, "ConEmuC: PID=%u", GetCurrentProcessId());
MessageBoxA(0, "Press Ok to continue", szDbgString, MB_SYSTEMMODAL);
#endif
// Don't use CREATE_NEW_PROCESS_GROUP, or Ctrl-C stops working
// We need to set `0` before CreateProcess, otherwise we may get timeout,
// due to misc antivirus software, BEFORE CreateProcess finishes
if (!(gbAttachMode & am_Modes))
gpSrv->processes->nProcessStartTick = 0;
if (gbNoCreateProcess)
{
// Process already started, just attach RealConsole to ConEmu (VirtualConsole)
lbRc = TRUE;
pi.hProcess = gpSrv->hRootProcess;
pi.dwProcessId = gpSrv->dwRootProcess;
}
else
{
_ASSERTE(gnRunMode != RM_ALTSERVER);
nExitPlaceStep = 350;
// Process environment variables
wchar_t* pszExpandedCmd = ParseConEmuSubst(gpszRunCmd);
if (pszExpandedCmd)
{
free(gpszRunCmd);
gpszRunCmd = pszExpandedCmd;
}
#ifdef _DEBUG
if (ghFarInExecuteEvent && wcsstr(gpszRunCmd,L"far.exe"))
ResetEvent(ghFarInExecuteEvent);
#endif
LPCWSTR pszCurDir = NULL;
WARNING("The process handle must have the PROCESS_VM_OPERATION access right!");
if (gbUseDosBox)
{
DosBoxHelp();
}
else if (gnRunMode == RM_SERVER && !gbRunViaCmdExe)
{
// Проверить, может пытаются запустить GUI приложение как вкладку в ConEmu?
if (((si.dwFlags & STARTF_USESHOWWINDOW) && (si.wShowWindow == SW_HIDE))
|| !(si.dwFlags & STARTF_USESHOWWINDOW) || (si.wShowWindow != SW_SHOWNORMAL))
{
//_ASSERTEX(si.wShowWindow != SW_HIDE); -- да, окно сервера (консоль) спрятана
// Имеет смысл, только если окно хотят изначально спрятать
const wchar_t *psz = gpszRunCmd, *pszStart;
CEStr szExe;
if (NextArg(&psz, szExe, &pszStart) == 0)
{
MWow64Disable wow;
if (!gbSkipWowChange) wow.Disable();
DWORD RunImageSubsystem = 0, RunImageBits = 0, RunFileAttrs = 0;
bool bSubSystem = GetImageSubsystem(szExe, RunImageSubsystem, RunImageBits, RunFileAttrs);
if (!bSubSystem)
{
// szExe may be simple "notepad", we must seek for executable...
CEStr szFound;
// We are interesting only on ".exe" files,
// supposing that other executable extensions can't be GUI applications
if (apiSearchPath(NULL, szExe, L".exe", szFound))
bSubSystem = GetImageSubsystem(szFound, RunImageSubsystem, RunImageBits, RunFileAttrs);
}
if (bSubSystem)
{
if (RunImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
{
si.dwFlags |= STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOWNORMAL;
}
}
}
}
}
// ConEmuC должен быть максимально прозрачен для конечного процесса
WARNING("При компиляции gcc все равно прозрачно не получается");
BOOL lbInheritHandle = (gnRunMode!=RM_SERVER);
// Если не делать вставку ConEmuC.exe в промежуток между g++.exe и (as.exe или cc1plus.exe)
// то все хорошо, если вставлять - то лезет куча ошибок вида
// c:/gcc/mingw/bin/../libexec/gcc/mingw32/4.3.2/cc1plus.exe:1: error: stray '\220' in program
// c:/gcc/mingw/bin/../libexec/gcc/mingw32/4.3.2/cc1plus.exe:1:4: warning: null character(s) ignored
// c:/gcc/mingw/bin/../libexec/gcc/mingw32/4.3.2/cc1plus.exe:1: error: stray '\3' in program
// c:/gcc/mingw/bin/../libexec/gcc/mingw32/4.3.2/cc1plus.exe:1:6: warning: null character(s) ignored
// Возможно, проблема в наследовании pipe-ов, проверить бы... или в другом SecurityDescriptor.
//MWow64Disable wow;
////#ifndef _DEBUG
//if (!gbSkipWowChange) wow.Disable();
////#endif
#ifdef _DEBUG
LPCWSTR pszRunCmpApp = NULL;
#endif
CEStr szExeName;
{
LPCWSTR pszStart = gpszRunCmd;
if (NextArg(&pszStart, szExeName) == 0)
{
#ifdef _DEBUG
if (FileExists(szExeName))
{
pszRunCmpApp = szExeName;
pszRunCmpApp = NULL;
}
#endif
}
}
LPSECURITY_ATTRIBUTES lpSec = LocalSecurity();
//#ifdef _DEBUG
// lpSec = NULL;
//#endif
// Не будем разрешать наследование, если нужно - сделаем DuplicateHandle
lbRc = createProcess(!gbSkipWowChange, NULL, gpszRunCmd, lpSec,lpSec, lbInheritHandle,
NORMAL_PRIORITY_CLASS/*|CREATE_NEW_PROCESS_GROUP*/
|CREATE_SUSPENDED/*((gnRunMode == RM_SERVER) ? CREATE_SUSPENDED : 0)*/,
NULL, pszCurDir, &si, &pi);
dwErr = GetLastError();
if (!lbRc && (gnRunMode == RM_SERVER) && dwErr == ERROR_FILE_NOT_FOUND)
{
// Фикс для перемещения ConEmu.exe в подпапку фара. т.е. far.exe находится на одну папку выше
if (gsSelfExe[0] != 0)
{
wchar_t szSelf[MAX_PATH*2];
wcscpy_c(szSelf, gsSelfExe);
wchar_t* pszSlash = wcsrchr(szSelf, L'\\');
if (pszSlash)
{
*pszSlash = 0; // получили папку с exe-шником
pszSlash = wcsrchr(szSelf, L'\\');
if (pszSlash)
{
*pszSlash = 0; // получили родительскую папку
pszCurDir = szSelf;
SetCurrentDirectory(pszCurDir);
// Пробуем еще раз, в родительской директории
// Не будем разрешать наследование, если нужно - сделаем DuplicateHandle
lbRc = createProcess(!gbSkipWowChange, NULL, gpszRunCmd, NULL,NULL, FALSE/*TRUE*/,
NORMAL_PRIORITY_CLASS/*|CREATE_NEW_PROCESS_GROUP*/
|CREATE_SUSPENDED/*((gnRunMode == RM_SERVER) ? CREATE_SUSPENDED : 0)*/,
NULL, pszCurDir, &si, &pi);
dwErr = GetLastError();
}
}
}
}
//wow.Restore();
if (lbRc) // && (gnRunMode == RM_SERVER))
{
nExitPlaceStep = 400;
#ifdef SHOW_INJECT_MSGBOX
wchar_t szDbgMsg[128], szTitle[128];
swprintf_c(szTitle, L"%s PID=%u", gsModuleName, GetCurrentProcessId());
szDbgMsg[0] = 0;
#endif
if (gbDontInjectConEmuHk
|| (!szExeName.IsEmpty() && IsConsoleServer(szExeName)))
{
#ifdef SHOW_INJECT_MSGBOX
swprintf_c(szDbgMsg, L"%s PID=%u\nConEmuHk injects skipped, PID=%u", gsModuleName, GetCurrentProcessId(), pi.dwProcessId);
#endif
}
else
{
TODO("Не только в сервере, но и в ComSpec, чтобы дочерние КОНСОЛЬНЫЕ процессы могли пользоваться редиректами");
//""F:\VCProject\FarPlugin\ConEmu\Bugs\DOS\TURBO.EXE ""
TODO("При выполнении DOS приложений - VirtualAllocEx(hProcess, обламывается!");
TODO("В принципе - завелось, но в сочетании с Anamorphosis получается странное зацикливание far->conemu->anamorph->conemu");
#ifdef SHOW_INJECT_MSGBOX
swprintf_c(szDbgMsg, L"%s PID=%u\nInjecting hooks into PID=%u", gsModuleName, GetCurrentProcessId(), pi.dwProcessId);
MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
#endif
//BOOL gbLogProcess = FALSE;
//TODO("Получить из мэппинга glt_Process");
//#ifdef _DEBUG
//gbLogProcess = TRUE;
//#endif
CINJECTHK_EXIT_CODES iHookRc = CIH_GeneralError/*-1*/;
if (((gnImageSubsystem == IMAGE_SUBSYSTEM_DOS_EXECUTABLE) || (gnImageBits == 16))
&& !gbUseDosBox)
{
// Если запускается ntvdm.exe - все-равно хук поставить не даст
iHookRc = CIH_OK/*0*/;
}
else
{
// Чтобы модуль хуков в корневом процессе знал, что оно корневое
_ASSERTE(ghRootProcessFlag==NULL);
wchar_t szEvtName[64];
msprintf(szEvtName, countof(szEvtName), CECONEMUROOTPROCESS, pi.dwProcessId);
ghRootProcessFlag = CreateEvent(LocalSecurity(), TRUE, TRUE, szEvtName);
if (ghRootProcessFlag)
{
SetEvent(ghRootProcessFlag);
}
else
{
_ASSERTE(ghRootProcessFlag!=NULL);
}
// Теперь ставим хуки
iHookRc = InjectHooks(pi, gbLogProcess);
}
if (iHookRc != CIH_OK/*0*/)
{
DWORD nErrCode = GetLastError();
//_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox
wchar_t szDbgMsg[255], szTitle[128];
swprintf_c(szTitle, L"ConEmuC[%u], PID=%u", WIN3264TEST(32,64), GetCurrentProcessId());
swprintf_c(szDbgMsg, L"ConEmuC.M, PID=%u\nInjecting hooks into PID=%u\nFAILED, code=%i:0x%08X", GetCurrentProcessId(), pi.dwProcessId, iHookRc, nErrCode);
MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
}
if (gbUseDosBox)
{
// Если запустился - то сразу добавим в список процессов (хотя он и не консольный)
ghDosBoxProcess = pi.hProcess; gnDosBoxPID = pi.dwProcessId;
//ProcessAdd(pi.dwProcessId);
}
}
#ifdef SHOW_INJECT_MSGBOX
wcscat_c(szDbgMsg, L"\nPress OK to resume started process");
MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
#endif
// Отпустить процесс (это корневой процесс консоли, например far.exe)
ResumeThread(pi.hThread);
}
if (!lbRc && dwErr == 0x000002E4)
{
nExitPlaceStep = 450;
// Допустимо только в режиме comspec - тогда запустится новая консоль
_ASSERTE(gnRunMode != RM_SERVER);
PRINT_COMSPEC(L"Vista+: The requested operation requires elevation (ErrCode=0x%08X).\n", dwErr);
// Vista: The requested operation requires elevation.
LPCWSTR pszCmd = gpszRunCmd;
wchar_t szVerb[10];
CEStr szExec;
if (NextArg(&pszCmd, szExec) == 0)
{
SHELLEXECUTEINFO sei = {sizeof(SHELLEXECUTEINFO)};
sei.hwnd = ghConEmuWnd;
sei.fMask = SEE_MASK_NO_CONSOLE; //SEE_MASK_NOCLOSEPROCESS; -- смысла ждать завершения нет - процесс запускается в новой консоли
wcscpy_c(szVerb, L"open"); sei.lpVerb = szVerb;
sei.lpFile = szExec.ms_Val;
sei.lpParameters = pszCmd;
sei.lpDirectory = pszCurDir;
sei.nShow = SW_SHOWNORMAL;
MWow64Disable wow; wow.Disable();
lbRc = ShellExecuteEx(&sei);
dwErr = GetLastError();
#ifdef _DEBUG
OnProcessCreatedDbg(lbRc, dwErr, NULL, &sei);
#endif
wow.Restore();
if (lbRc)
{
// OK
pi.hProcess = NULL; pi.dwProcessId = 0;
pi.hThread = NULL; pi.dwThreadId = 0;
// т.к. запустилась новая консоль - подтверждение на закрытие этой точно не нужно
DisableAutoConfirmExit();
iRc = 0; goto wrap;
}
}
}
}
if (!lbRc)
{
nExitPlaceStep = 900;
PrintExecuteError(gpszRunCmd, dwErr);
iRc = CERR_CREATEPROCESS; goto wrap;
}
if ((gbAttachMode & am_Modes))
{
// мы цепляемся к уже существующему процессу:
// аттач из фар плагина или запуск dos-команды в новой консоли через -new_console
// в последнем случае отключение подтверждения закрытия однозначно некорректно
// -- DisableAutoConfirmExit(); - низя
}
else
{
if (!gpSrv->processes->nProcessStartTick) // Уже мог быть проинициализирован из cmd_CmdStartStop
gpSrv->processes->nProcessStartTick = GetTickCount();
}
if (pi.dwProcessId)
AllowSetForegroundWindow(pi.dwProcessId);
#ifdef _DEBUG
xf_validate(NULL);
#endif
/* *************************** */
/* *** Waiting for startup *** */
/* *************************** */
// Don't "lock" startup folder
UnlockCurrentDirectory();
if (gnRunMode == RM_SERVER)
{
//DWORD dwWaitGui = -1;
nExitPlaceStep = 500;
gpSrv->hRootProcess = pi.hProcess; pi.hProcess = NULL; // Required for Win2k
gpSrv->hRootThread = pi.hThread; pi.hThread = NULL;
gpSrv->dwRootProcess = pi.dwProcessId;
gpSrv->dwRootThread = pi.dwThreadId;
gpSrv->dwRootStartTime = GetTickCount();
// Скорее всего процесс в консольном списке уже будет
gpSrv->processes->CheckProcessCount(TRUE);
#ifdef _DEBUG
if (gpSrv->processes->nProcessCount && !gpSrv->DbgInfo.bDebuggerActive)
{
_ASSERTE(gpSrv->processes->pnProcesses[gpSrv->processes->nProcessCount-1]!=0);
}
#endif
//if (pi.hProcess) SafeCloseHandle(pi.hProcess);
//if (pi.hThread) SafeCloseHandle(pi.hThread);
if (gpSrv->hConEmuGuiAttached)
{
DEBUGTEST(DWORD t1 = timeGetTime());
dwWaitGui = WaitForSingleObject(gpSrv->hConEmuGuiAttached, 1000);
#ifdef _DEBUG
DWORD t2 = timeGetTime(), tDur = t2-t1;
if (tDur > GUIATTACHEVENT_TIMEOUT)
{
_ASSERTE(tDur <= GUIATTACHEVENT_TIMEOUT);
}
#endif
if (dwWaitGui == WAIT_OBJECT_0)
{
// GUI пайп готов
swprintf_c(gpSrv->szGuiPipeName, CEGUIPIPENAME, L".", LODWORD(ghConWnd)); // был gnSelfPID //-V205
}
}
// Ждем, пока в консоли не останется процессов (кроме нашего)
TODO("Проверить, может ли так получиться, что CreateProcess прошел, а к консоли он не прицепился? Может, если процесс GUI");
// "Подцепление" процесса к консоли наверное может задержать антивирус
nWait = nWaitExitEvent = WaitForSingleObject(ghExitQueryEvent, CHECK_ANTIVIRUS_TIMEOUT);
if (nWait != WAIT_OBJECT_0) // Если таймаут
{
iRc = gpSrv->processes->nProcessCount
+ (((gpSrv->processes->nProcessCount==1) && gbUseDosBox && (WaitForSingleObject(ghDosBoxProcess,0)==WAIT_TIMEOUT)) ? 1 : 0);
// И процессов в консоли все еще нет
if (iRc == 1 && !gpSrv->DbgInfo.bDebuggerActive)
{
if (!gbInShutdown)
{
gbTerminateOnCtrlBreak = TRUE;
gbCtrlBreakStopWaitingShown = TRUE;
//_printf("Process was not attached to console. Is it GUI?\nCommand to be executed:\n");
//_wprintf(gpszRunCmd);
PrintExecuteError(gpszRunCmd, 0, L"Process was not attached to console. Is it GUI?\n");
_printf("\n\nPress Ctrl+Break to stop waiting\n");
while (!gbInShutdown && (nWait != WAIT_OBJECT_0))
{
nWait = nWaitExitEvent = WaitForSingleObject(ghExitQueryEvent, 250);
if (nWaitExitEvent == WAIT_OBJECT_0)
{
dwWaitRoot = WaitForSingleObject(gpSrv->hRootProcess, 0);
if (dwWaitRoot == WAIT_OBJECT_0)
{
gbTerminateOnCtrlBreak = FALSE;
gbCtrlBreakStopWaitingShown = FALSE; // сбросим, чтобы ассерты не лезли
}
else
{
// Root process must be terminated at this point (can't start/initialize)
_ASSERTE(dwWaitRoot == WAIT_OBJECT_0);
}
}
if ((nWait != WAIT_OBJECT_0) && (gpSrv->processes->nProcessCount > 1))
{
gbTerminateOnCtrlBreak = FALSE;
gbCtrlBreakStopWaitingShown = FALSE; // сбросим, чтобы ассерты не лезли
goto wait; // OK, переходим в основной цикл ожидания завершения
}
}
}
// Что-то при загрузке компа иногда все-таки не дожидается, когда процесс в консоли появится
_ASSERTE(FALSE && gbTerminateOnCtrlBreak && gbInShutdown);
iRc = CERR_PROCESSTIMEOUT; goto wrap;
}
}
}
else if (gnRunMode == RM_COMSPEC)
{
// В режиме ComSpec нас интересует завершение ТОЛЬКО дочернего процесса
_ASSERTE(pi.dwProcessId!=0);
gpSrv->dwRootProcess = pi.dwProcessId;
gpSrv->dwRootThread = pi.dwThreadId;
}
/* *************************** */
/* *** Ожидание завершения *** */
/* *************************** */
wait:
#ifdef _DEBUG
xf_validate(NULL);
#endif
#ifdef _DEBUG
if (gnRunMode == RM_SERVER)
{
gbPipeDebugBoxes = false;
}
#endif
// JIC, if there was "goto"
UnlockCurrentDirectory();
if (gnRunMode == RM_ALTSERVER)
{
// Alternative server, we can't wait for "self" termination
iRc = 0;
goto AltServerDone;
} // (gnRunMode == RM_ALTSERVER)
else if (gnRunMode == RM_SERVER)
{
nExitPlaceStep = EPS_WAITING4PROCESS/*550*/;
// There is at least one process in console. Wait until there would be nobody except us.
nWait = WAIT_TIMEOUT; nWaitExitEvent = -2;
_ASSERTE(!gpSrv->DbgInfo.bDebuggerActive);
#ifdef _DEBUG
while (nWait == WAIT_TIMEOUT)
{
nWait = nWaitExitEvent = WaitForSingleObject(ghExitQueryEvent, 100);
// Not actual? Что-то при загрузке компа иногда все-таки не дожидается, когда процесс в консоли появится
_ASSERTE(!(gbCtrlBreakStopWaitingShown && (nWait != WAIT_TIMEOUT)));
}
#else
nWait = nWaitExitEvent = WaitForSingleObject(ghExitQueryEvent, INFINITE);
_ASSERTE(!(gbCtrlBreakStopWaitingShown && (nWait != WAIT_TIMEOUT)));
#endif
ShutdownSrvStep(L"ghExitQueryEvent was set");
#ifdef _DEBUG
xf_validate(NULL);
#endif
// Root ExitCode
GetExitCodeProcess(gpSrv->hRootProcess, &gnExitCode);
nExitPlaceStep = EPS_ROOTPROCFINISHED/*560*/;
#ifdef _DEBUG
if (nWait == WAIT_OBJECT_0)
{
DEBUGSTRFIN(L"*** FinalizeEvent was set!\n");
}
#endif
} // (gnRunMode == RM_SERVER)
else
{
nExitPlaceStep = 600;
//HANDLE hEvents[3];
//hEvents[0] = pi.hProcess;
//hEvents[1] = ghCtrlCEvent;
//hEvents[2] = ghCtrlBreakEvent;
//WaitForSingleObject(pi.hProcess, INFINITE);
#ifdef _DEBUG
xf_validate(NULL);
#endif
DWORD nWaitMS = gbAsyncRun ? 0 : INFINITE;
nWaitComspecExit = WaitForSingleObject(pi.hProcess, nWaitMS);
#ifdef _DEBUG
xf_validate(NULL);
#endif
// Получить ExitCode
GetExitCodeProcess(pi.hProcess, &gnExitCode);
#ifdef _DEBUG
xf_validate(NULL);
#endif
// Close all handles now
if (pi.hProcess)
SafeCloseHandle(pi.hProcess);
if (pi.hThread)
SafeCloseHandle(pi.hThread);
#ifdef _DEBUG
xf_validate(NULL);
#endif
} // (gnRunMode == RM_COMSPEC)
/* *********************** */
/* *** Finalizing work *** */
/* *********************** */
iRc = 0;
wrap:
ShutdownSrvStep(L"Finalizing.1");
#if defined(SHOW_STARTED_PRINT_LITE)
if (gnRunMode == RM_SERVER)
{
_printf("\n" WIN3264TEST("ConEmuC.exe","ConEmuC64.exe") " finalizing, PID=%u\n", GetCurrentProcessId());
}
#endif
#ifdef VALIDATE_AND_DELAY_ON_TERMINATE
// Проверка кучи
xf_validate(NULL);
// Отлов изменения высоты буфера
if (gnRunMode == RM_SERVER)
Sleep(1000);
#endif
// К сожалению, HandlerRoutine может быть еще не вызван, поэтому
// в самой процедуре ExitWaitForKey вставлена проверка флага gbInShutdown
PRINT_COMSPEC(L"Finalizing. gbInShutdown=%i\n", gbInShutdown);
#ifdef SHOW_STARTED_MSGBOX
MessageBox(GetConEmuHWND(2), L"Finalizing", (gnRunMode == RM_SERVER) ? L"ConEmuC.Server" : L"ConEmuC.ComSpec", 0);
#endif
#ifdef VALIDATE_AND_DELAY_ON_TERMINATE
xf_validate(NULL);
#endif
if (iRc == CERR_GUIMACRO_SUCCEEDED)
{
iRc = 0;
}
if (gnRunMode == RM_SERVER && gpSrv->hRootProcess)
GetExitCodeProcess(gpSrv->hRootProcess, &gnExitCode);
else if (pi.hProcess)
GetExitCodeProcess(pi.hProcess, &gnExitCode);
// Ассерт может быть если был запрос на аттач, который не удался
_ASSERTE(gnExitCode!=STILL_ACTIVE || (iRc==CERR_ATTACHFAILED) || (iRc==CERR_RUNNEWCONSOLE) || gbAsyncRun);
// Log exit code
if (((gnRunMode == RM_SERVER && gpSrv->hRootProcess) ? gpSrv->dwRootProcess : pi.dwProcessId) != 0)
{
wchar_t szInfo[80];
LPCWSTR pszName = (gnRunMode == RM_SERVER && gpSrv->hRootProcess) ? L"Shell" : L"Process";
DWORD nPID = (gnRunMode == RM_SERVER && gpSrv->hRootProcess) ? gpSrv->dwRootProcess : pi.dwProcessId;
if (gnExitCode >= 0x80000000)
swprintf_c(szInfo, L"\n%s PID=%u ExitCode=%u (%i) {x%08X}", pszName, nPID, gnExitCode, (int)gnExitCode, gnExitCode);
else
swprintf_c(szInfo, L"\n%s PID=%u ExitCode=%u {x%08X}", pszName, nPID, gnExitCode, gnExitCode);
LogFunction(szInfo+1);
if (gbPrintRetErrLevel)
{
wcscat_c(szInfo, L"\n");
_wprintf(szInfo);
}
// Post information to GUI
if (gnMainServerPID && !gpSrv->bWasDetached)
{
CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_GETROOTINFO, sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_ROOT_INFO));
if (pIn && gpSrv->processes->GetRootInfo(pIn))
{
CESERVER_REQ *pSrvOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd, TRUE/*async*/);
ExecuteFreeResult(pSrvOut);
}
ExecuteFreeResult(pIn);
}
}
if (iRc && (gbAttachMode & am_Auto))
{
// Issue 1003: Non zero exit codes leads to problems in some applications...
iRc = 0;
}
ShutdownSrvStep(L"Finalizing.2");
if (!gbInShutdown // только если юзер не нажал крестик в заголовке окна, или не удался /ATTACH (чтобы в консоль не гадить)
&& ((iRc!=0 && iRc!=CERR_RUNNEWCONSOLE && iRc!=CERR_EMPTY_COMSPEC_CMDLINE
&& iRc!=CERR_UNICODE_CHK_FAILED && iRc!=CERR_UNICODE_CHK_OKAY
&& iRc!=CERR_GUIMACRO_SUCCEEDED && iRc!=CERR_GUIMACRO_FAILED
&& iRc!=CERR_AUTOATTACH_NOT_ALLOWED && iRc!=CERR_ATTACHFAILED
&& iRc!=CERR_WRONG_GUI_VERSION
&& !(gnRunMode!=RM_SERVER && iRc==CERR_CREATEPROCESS))
|| gbAlwaysConfirmExit)
)
{
UnlockCurrentDirectory();
//#ifdef _DEBUG
//if (!gbInShutdown)
// MessageBox(0, L"ExitWaitForKey", L"ConEmuC", MB_SYSTEMMODAL);
//#endif
BOOL lbProcessesLeft = FALSE, lbDontShowConsole = FALSE;
BOOL lbLineFeedAfter = TRUE;
DWORD nProcesses[10] = {};
DWORD nProcCount = -1;
if (pfnGetConsoleProcessList)
{
// консоль может не успеть среагировать на "закрытие" корневого процесса
nProcCount = pfnGetConsoleProcessList(nProcesses, 10);
if (nProcCount > 1)
{
DWORD nValid = 0;
for (DWORD i = 0; i < nProcCount; i++)
{
if ((nProcesses[i] != gpSrv->dwRootProcess)
#ifndef WIN64
&& (nProcesses[i] != gpSrv->processes->nNtvdmPID)
#endif
)
{
nValid++;
}
}
lbProcessesLeft = (nValid > 1);
}
}
LPCWSTR pszMsg = NULL;
if (lbProcessesLeft)
{
pszMsg = L"\n\nPress Enter or Esc to exit...";
lbDontShowConsole = gnRunMode != RM_SERVER;
}
else if ((gnConfirmExitParm == RConStartArgs::eConfEmpty)
|| (gnConfirmExitParm == RConStartArgs::eConfHalt))
{
lbLineFeedAfter = FALSE; // Don't print anything to console
}
else
{
if (gbRootWasFoundInCon == 1)
{
// If root process has been working less than CHECK_ROOTOK_TIMEOUT
if (gbRootAliveLess10sec && (gnConfirmExitParm != RConStartArgs::eConfAlways))
{
static wchar_t szMsg[255];
if (gnExitCode)
{
PrintExecuteError(gpszRunCmd, 0, L"\n");
}
wchar_t szExitCode[40];
if (gnExitCode > 255)
swprintf_c(szExitCode, L"x%08X(%u)", gnExitCode, gnExitCode);
else
swprintf_c(szExitCode, L"%u", gnExitCode);
swprintf_c(szMsg,
L"\n\nConEmuC: Root process was alive less than 10 sec, ExitCode=%s.\nPress Enter or Esc to close console...",
szExitCode);
pszMsg = szMsg;
}
else
{
pszMsg = L"\n\nPress Enter or Esc to close console...";
}
}
}
if (!pszMsg
&& (gnConfirmExitParm != RConStartArgs::eConfEmpty)
&& (gnConfirmExitParm != RConStartArgs::eConfHalt))
{
// Let's show anything (default message)
pszMsg = L"\n\nPress Enter or Esc to close console, or wait...";
#ifdef _DEBUG
static wchar_t szDbgMsg[255];
swprintf_c(szDbgMsg,
L"\n\ngbInShutdown=%i, iRc=%i, gbAlwaysConfirmExit=%i, nExitQueryPlace=%i"
L"%s",
(int)gbInShutdown, iRc, (int)gbAlwaysConfirmExit, nExitQueryPlace,
pszMsg);
pszMsg = szDbgMsg;
#endif
}
DWORD keys = (gnConfirmExitParm == RConStartArgs::eConfHalt) ? 0
: (VK_RETURN|(VK_ESCAPE<<8));
ExitWaitForKey(keys, pszMsg, lbLineFeedAfter, lbDontShowConsole);
UNREFERENCED_PARAMETER(nProcCount);
UNREFERENCED_PARAMETER(nProcesses[0]);
// During the wait, new process may be started in our console
{
int nCount = gpSrv->processes->nProcessCount;
if ((gpSrv->ConnectInfo.bConnected && (nCount > 1))
|| gpSrv->DbgInfo.bDebuggerActive)
{
// OK, new root found, wait for it
goto wait;
}
}
}
// На всякий случай - выставим событие
if (ghExitQueryEvent)
{
_ASSERTE(gbTerminateOnCtrlBreak==FALSE);
if (!nExitQueryPlace) nExitQueryPlace = 11+(nExitPlaceStep);
SetTerminateEvent(ste_ConsoleMain);
}
// Завершение RefreshThread, InputThread, ServerThread
if (ghQuitEvent) SetEvent(ghQuitEvent);
ShutdownSrvStep(L"Finalizing.3");
#ifdef _DEBUG
xf_validate(NULL);
#endif
/* ***************************** */
/* *** "Режимное" завершение *** */
/* ***************************** */
if (gnRunMode == RM_SERVER)
{
ServerDone(iRc, true);
//MessageBox(0,L"Server done...",L"ConEmuC",0);
SafeCloseHandle(gpSrv->DbgInfo.hDebugReady);
SafeCloseHandle(gpSrv->DbgInfo.hDebugThread);
}
else if (gnRunMode == RM_COMSPEC)
{
_ASSERTE(iRc==CERR_RUNNEWCONSOLE || gbComspecInitCalled);
if (gbComspecInitCalled)
{
ComspecDone(iRc);
}
//MessageBox(0,L"Comspec done...",L"ConEmuC",0);
}
else if (gnRunMode == RM_APPLICATION)
{
SendStopped();
}
ShutdownSrvStep(L"Finalizing.4");
/* ************************** */
/* *** "Общее" завершение *** */
/* ************************** */
#ifdef _DEBUG
#if 0
if (gnRunMode == RM_COMSPEC)
{
if (gpszPrevConTitle)
{
if (ghConWnd)
SetTitle(gpszPrevConTitle);
}
}
#endif
SafeFree(gpszPrevConTitle);
#endif
SafeCloseHandle(ghRootProcessFlag);
LogSize(NULL, 0, "Shutdown");
//ghConIn.Close();
ghConOut.Close();
SafeDelete(gpLogSize);
//if (wpszLogSizeFile)
//{
// //DeleteFile(wpszLogSizeFile);
// free(wpszLogSizeFile); wpszLogSizeFile = NULL;
//}
#ifdef _DEBUG
SafeCloseHandle(ghFarInExecuteEvent);
#endif
SafeFree(gpszRunCmd);
SafeFree(gpszTaskCmd);
SafeFree(gpszForcedTitle);
CommonShutdown();
ShutdownSrvStep(L"Finalizing.5");
// -> DllMain
//if (ghHeap)
//{
// HeapDestroy(ghHeap);
// ghHeap = NULL;
//}
// борьба с оптимизатором
if (szDebugCmdLine[0] != 0)
{
int nLen = lstrlen(szDebugCmdLine);
UNREFERENCED_PARAMETER(nLen);
}
// Если режим ComSpec - вернуть код возврата из запущенного процесса
if (iRc == 0 && gnRunMode == RM_COMSPEC)
iRc = gnExitCode;
#ifdef SHOW_STARTED_MSGBOX
MessageBox(GetConEmuHWND(2), L"Exiting", (gnRunMode == RM_SERVER) ? L"ConEmuC.Server" : L"ConEmuC.ComSpec", 0);
#endif
if (gpSrv)
{
gpSrv->FinalizeFields();
free(gpSrv);
gpSrv = NULL;
}
AltServerDone:
ShutdownSrvStep(L"Finalizing done");
UNREFERENCED_PARAMETER(gpszCheck4NeedCmd);
UNREFERENCED_PARAMETER(nWaitDebugExit);
UNREFERENCED_PARAMETER(nWaitComspecExit);
#if 0
if (gnRunMode == RM_SERVER)
{
xf_dump();
}
#endif
return iRc;
}
#if defined(__GNUC__)
extern "C"
#endif
int __stdcall ConsoleMain2(int anWorkMode/*0-Server&ComSpec,1-AltServer,2-Reserved*/)
{
return ConsoleMain3(anWorkMode, GetCommandLineW());
}
int WINAPI RequestLocalServer(/*[IN/OUT]*/RequestLocalServerParm* Parm)
{
//_ASSERTE(FALSE && "ConEmuCD. Continue to RequestLocalServer");
int iRc = 0;
wchar_t szName[64];
if (!Parm || (Parm->StructSize != sizeof(*Parm)))
{
iRc = CERR_CARGUMENT;
goto wrap;
}
// Если больше ничего кроме регистрации событий нет
if ((Parm->Flags & slsf__EventsOnly) == Parm->Flags)
{
goto DoEvents;
}
Parm->pAnnotation = NULL;
Parm->Flags &= ~slsf_PrevAltServerPID;
// Хэндл обновим сразу
if (Parm->Flags & slsf_SetOutHandle)
{
ghConOut.SetBufferPtr(Parm->ppConOutBuffer);
}
if (gnRunMode != RM_ALTSERVER)
{
#ifdef SHOW_ALTERNATIVE_MSGBOX
if (!IsDebuggerPresent())
{
char szMsg[128]; msprintf(szMsg, countof(szMsg), "AltServer: " WIN3264TEST("ConEmuCD.dll","ConEmuCD64.dll") " loaded, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
MessageBoxA(NULL, szMsg, "ConEmu AltServer" WIN3264TEST(""," x64"), 0);
}
#endif
_ASSERTE(gpSrv == NULL);
_ASSERTE(gnRunMode == RM_UNDEFINED);
HWND hConEmu = GetConEmuHWND(1/*Gui Main window*/);
if (!hConEmu || !IsWindow(hConEmu))
{
iRc = CERR_GUI_NOT_FOUND;
goto wrap;
}
// Need to block all requests to output buffer in other threads
MSectionLockSimple csRead;
if (gpSrv)
csRead.Lock(&gpSrv->csReadConsoleInfo, LOCK_READOUTPUT_TIMEOUT);
// Инициализировать gcrVisibleSize и прочие переменные
CONSOLE_SCREEN_BUFFER_INFO sbi = {};
// MyGetConsoleScreenBufferInfo пользовать нельзя - оно gpSrv и gnRunMode хочет
if (GetConsoleScreenBufferInfo(ghConOut, &sbi))
{
gcrVisibleSize.X = sbi.srWindow.Right - sbi.srWindow.Left + 1;
gcrVisibleSize.Y = sbi.srWindow.Bottom - sbi.srWindow.Top + 1;
gbParmVisibleSize = FALSE;
gnBufferHeight = (sbi.dwSize.Y == gcrVisibleSize.Y) ? 0 : sbi.dwSize.Y;
gnBufferWidth = (sbi.dwSize.X == gcrVisibleSize.X) ? 0 : sbi.dwSize.X;
gbParmBufSize = (gnBufferHeight != 0);
}
_ASSERTE(gcrVisibleSize.X>0 && gcrVisibleSize.X<=400 && gcrVisibleSize.Y>0 && gcrVisibleSize.Y<=300);
csRead.Unlock();
iRc = ConsoleMain2(1/*0-Server&ComSpec,1-AltServer,2-Reserved*/);
if ((iRc == 0) && gpSrv && gpSrv->dwPrevAltServerPID)
{
Parm->Flags |= slsf_PrevAltServerPID;
Parm->nPrevAltServerPID = gpSrv->dwPrevAltServerPID;
}
}
// Если поток RefreshThread был "заморожен" при запуске другого сервера
if ((gpSrv->nRefreshFreezeRequests > 0) && !(Parm->Flags & slsf_OnAllocConsole))
{
ThawRefreshThread();
}
TODO("Инициализация TrueColor буфера - Parm->ppAnnotation");
DoEvents:
if (Parm->Flags & slsf_GetFarCommitEvent)
{
if (gpSrv)
{
_ASSERTE(gpSrv->hFarCommitEvent != NULL); // Уже должно быть создано!
}
else
{
;
}
swprintf_c(szName, CEFARWRITECMTEVENT, gnSelfPID);
Parm->hFarCommitEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, szName);
_ASSERTE(Parm->hFarCommitEvent!=NULL);
if (Parm->Flags & slsf_FarCommitForce)
{
gpSrv->bFarCommitRegistered = TRUE;
}
}
if (Parm->Flags & slsf_GetCursorEvent)
{
_ASSERTE(gpSrv->hCursorChangeEvent != NULL); // Уже должно быть создано!
swprintf_c(szName, CECURSORCHANGEEVENT, gnSelfPID);
Parm->hCursorChangeEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, szName);
_ASSERTE(Parm->hCursorChangeEvent!=NULL);
gpSrv->bCursorChangeRegistered = TRUE;
}
if (Parm->Flags & slsf_OnFreeConsole)
{
FreezeRefreshThread();
}
if (Parm->Flags & slsf_OnAllocConsole)
{
ghConWnd = GetConEmuHWND(2);
LoadSrvInfoMap();
//TODO: Request AltServer state from MainServer?
ThawRefreshThread();
}
wrap:
return iRc;
}
//#if defined(CRTSTARTUP)
//extern "C"{
// BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved);
//};
//
//BOOL WINAPI mainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved)
//{
// DllMain(hDll, dwReason, lpReserved);
// return TRUE;
//}
//#endif
void PrintVersion()
{
char szProgInfo[255];
sprintf_c(szProgInfo,
"ConEmuC build %s %s. " CECOPYRIGHTSTRING_A "\n",
CONEMUVERS, WIN3264TEST("x86","x64"));
_printf(szProgInfo);
}
void Help()
{
PrintVersion();
// See definition in "ConEmuCD/ConsoleHelp.h"
_wprintf(pConsoleHelp);
_wprintf(pNewConsoleHelp);
// Don't ask keypress before exit
gbInShutdown = TRUE;
}
void DosBoxHelp()
{
// See definition in "ConEmuCD/ConsoleHelp.h"
_wprintf(pDosBoxHelp);
}
void PrintExecuteError(LPCWSTR asCmd, DWORD dwErr, LPCWSTR asSpecialInfo/*=NULL*/)
{
if (asSpecialInfo)
{
if (*asSpecialInfo)
_wprintf(asSpecialInfo);
}
else
{
wchar_t* lpMsgBuf = NULL;
DWORD nFmtRc, nFmtErr = 0;
if (dwErr == 5)
{
lpMsgBuf = (wchar_t*)LocalAlloc(LPTR, 128*sizeof(wchar_t));
_wcscpy_c(lpMsgBuf, 128, L"Access is denied.\nThis may be cause of antiviral or file permissions denial.");
}
else
{
nFmtRc = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL);
if (!nFmtRc)
nFmtErr = GetLastError();
}
_printf("Can't create process, ErrCode=0x%08X, Description:\n", dwErr);
_wprintf((lpMsgBuf == NULL) ? L"<Unknown error>" : lpMsgBuf);
if (lpMsgBuf) LocalFree(lpMsgBuf);
UNREFERENCED_PARAMETER(nFmtErr);
}
size_t nCchMax = MAX_PATH*2+32;
wchar_t* lpInfo = (wchar_t*)calloc(nCchMax,sizeof(*lpInfo));
if (lpInfo)
{
_wcscpy_c(lpInfo, nCchMax, L"\nCurrent directory:\n");
_ASSERTE(nCchMax>=(MAX_PATH*2+32));
if (gpStartEnv && gpStartEnv->pszWorkDir)
{
_wcscat_c(lpInfo, nCchMax, gpStartEnv->pszWorkDir);
}
else
{
_ASSERTE(gpStartEnv && gpStartEnv->pszWorkDir);
GetCurrentDirectory(MAX_PATH*2, lpInfo+lstrlen(lpInfo));
}
_wcscat_c(lpInfo, nCchMax, L"\n");
_wprintf(lpInfo);
free(lpInfo);
}
_printf("\nCommand to be executed:\n");
_wprintf(asCmd ? asCmd : L"<null>");
_printf("\n");
}
int CheckAttachProcess()
{
LogFunction(L"CheckAttachProcess");
int liArgsFailed = 0;
wchar_t szFailMsg[512]; szFailMsg[0] = 0;
DWORD nProcesses[20] = {};
DWORD nProcCount;
BOOL lbRootExists = FALSE;
wchar_t szProc[255] = {}, szTmp[10] = {};
DWORD nFindId;
if (gpSrv->hRootProcessGui)
{
if (!IsWindow(gpSrv->hRootProcessGui))
{
swprintf_c(szFailMsg, L"Attach of GUI application was requested,\n"
L"but required HWND(0x%08X) not found!", LODWORD(gpSrv->hRootProcessGui));
LogString(szFailMsg);
liArgsFailed = 1;
// will return CERR_CARGUMENT
}
else
{
DWORD nPid; GetWindowThreadProcessId(gpSrv->hRootProcessGui, &nPid);
if (!gpSrv->dwRootProcess || (gpSrv->dwRootProcess != nPid))
{
swprintf_c(szFailMsg, L"Attach of GUI application was requested,\n"
L"but PID(%u) of HWND(0x%08X) does not match Root(%u)!",
nPid, LODWORD(gpSrv->hRootProcessGui), gpSrv->dwRootProcess);
LogString(szFailMsg);
liArgsFailed = 2;
// will return CERR_CARGUMENT
}
}
}
else if (pfnGetConsoleProcessList==NULL)
{
wcscpy_c(szFailMsg, L"Attach to console app was requested, but required WinXP or higher!");
LogString(szFailMsg);
liArgsFailed = 3;
// will return CERR_CARGUMENT
}
else
{
nProcCount = pfnGetConsoleProcessList(nProcesses, 20);
if ((nProcCount == 1) && gbCreatingHiddenConsole)
{
// Подождать, пока вызвавший процесс прицепится к нашей созданной консоли
DWORD nStart = GetTickCount(), nMaxDelta = 30000, nDelta = 0;
while (nDelta < nMaxDelta)
{
Sleep(100);
nProcCount = pfnGetConsoleProcessList(nProcesses, 20);
if (nProcCount > 1)
break;
nDelta = (GetTickCount() - nStart);
}
}
// 2 процесса, потому что это мы сами и минимум еще один процесс в этой консоли,
// иначе смысла в аттаче нет
if (nProcCount < 2)
{
wcscpy_c(szFailMsg, L"Attach to console app was requested, but there is no console processes!");
LogString(szFailMsg);
liArgsFailed = 4;
//will return CERR_CARGUMENT
}
// не помню, зачем такая проверка была введена, но (nProcCount > 2) мешает аттачу.
// в момент запуска сервера (/ATTACH /PID=n) еще жив родительский (/ATTACH /NOCMD)
//// Если cmd.exe запущен из cmd.exe (в консоли уже больше двух процессов) - ничего не делать
else if ((gpSrv->dwRootProcess != 0) || (nProcCount > 2))
{
lbRootExists = (gpSrv->dwRootProcess == 0);
// И ругаться только под отладчиком
nFindId = 0;
for (int n = ((int)nProcCount-1); n >= 0; n--)
{
if (szProc[0]) wcscat_c(szProc, L", ");
swprintf_c(szTmp, L"%i", nProcesses[n]);
wcscat_c(szProc, szTmp);
if (gpSrv->dwRootProcess)
{
if (!lbRootExists && nProcesses[n] == gpSrv->dwRootProcess)
lbRootExists = TRUE;
}
else if ((nFindId == 0) && (nProcesses[n] != gnSelfPID))
{
// Будем считать его корневым.
// Собственно, кого считать корневым не важно, т.к.
// сервер не закроется до тех пор пока жив хотя бы один процесс
nFindId = nProcesses[n];
}
}
if ((gpSrv->dwRootProcess == 0) && (nFindId != 0))
{
gpSrv->dwRootProcess = nFindId;
lbRootExists = TRUE;
}
if ((gpSrv->dwRootProcess != 0) && !lbRootExists)
{
swprintf_c(szFailMsg, L"Attach to GUI was requested, but\n" L"root process (%u) does not exists", gpSrv->dwRootProcess);
LogString(szFailMsg);
liArgsFailed = 5;
//will return CERR_CARGUMENT
}
else if ((gpSrv->dwRootProcess == 0) && (nProcCount > 2))
{
swprintf_c(szFailMsg, L"Attach to GUI was requested, but\n" L"there is more than 2 console processes: %s\n", szProc);
LogString(szFailMsg);
liArgsFailed = 6;
//will return CERR_CARGUMENT
}
}
}
if (liArgsFailed)
{
DWORD nSelfPID = GetCurrentProcessId();
PROCESSENTRY32 self = {sizeof(self)}, parent = {sizeof(parent)};
// Not optimal, needs refactoring
if (GetProcessInfo(nSelfPID, &self))
GetProcessInfo(self.th32ParentProcessID, &parent);
LPCWSTR pszCmdLine = GetCommandLineW(); if (!pszCmdLine) pszCmdLine = L"";
wchar_t szTitle[MAX_PATH*2];
swprintf_c(szTitle,
L"ConEmuC %s [%u], PID=%u, Code=%i" L"\r\n"
L"ParentPID=%u: %s" L"\r\n"
L" ", // szFailMsg follows this
gsVersion, WIN3264TEST(32,64), nSelfPID, liArgsFailed,
self.th32ParentProcessID, parent.szExeFile[0] ? parent.szExeFile : L"<terminated>");
CEStr lsMsg = lstrmerge(szTitle, szFailMsg, L"\r\nCommand line:\r\n ", pszCmdLine);
// Avoid automatic termination of ExitWaitForKey
gbInShutdown = FALSE;
// Force light-red on black for error message
MSetConTextAttr setAttr(ghConOut, 12);
const DWORD nAttachErrorTimeoutMessage = 15*1000; // 15 sec
ExitWaitForKey(VK_RETURN|(VK_ESCAPE<<8), lsMsg, true, true, nAttachErrorTimeoutMessage);
LogString(L"CheckAttachProcess: CERR_CARGUMENT after ExitWaitForKey");
gbInShutdown = TRUE;
return CERR_CARGUMENT;
}
return 0; // OK
}
void SetWorkEnvVar()
{
_ASSERTE(gnRunMode == RM_SERVER && !gbNoCreateProcess);
SetConEmuWorkEnvVar(ghOurModule);
}
// 1. Заменить подстановки вида: !ConEmuHWND!, !ConEmuDrawHWND!, !ConEmuBackHWND!, !ConEmuWorkDir!
// 2. Развернуть переменные окружения (PowerShell, например, не признает переменные в качестве параметров)
wchar_t* ParseConEmuSubst(LPCWSTR asCmd)
{
if (!asCmd || !*asCmd)
{
LogFunction(L"ParseConEmuSubst - skipped");
return NULL;
}
LogFunction(L"ParseConEmuSubst");
// Другие имена нет смысла передавать через "!" вместо "%"
LPCWSTR szNames[] = {ENV_CONEMUHWND_VAR_W, ENV_CONEMUDRAW_VAR_W, ENV_CONEMUBACK_VAR_W, ENV_CONEMUWORKDIR_VAR_W};
#ifdef _DEBUG
// Переменные уже должны быть определены!
for (size_t i = 0; i < countof(szNames); ++i)
{
LPCWSTR pszName = szNames[i];
wchar_t szDbg[MAX_PATH+1] = L"";
GetEnvironmentVariable(pszName, szDbg, countof(szDbg));
if (!*szDbg)
{
LogFunction(L"Variables must be set already!");
_ASSERTE(*szDbg && "Variables must be set already!");
break; // другие не проверять - лишние ассерты
}
}
#endif
// Если ничего похожего нет, то и не дергаться
wchar_t szFind[] = L"!ConEmu";
bool bExclSubst = (StrStrI(asCmd, szFind) != NULL);
if (!bExclSubst && (wcschr(asCmd, L'%') == NULL))
return NULL;
//_ASSERTE(FALSE && "Continue to ParseConEmuSubst");
wchar_t* pszCmdCopy = NULL;
if (bExclSubst)
{
wchar_t* pszCmdCopy = lstrdup(asCmd);
if (!pszCmdCopy)
return NULL; // Ошибка выделения памяти вообще-то
for (size_t i = 0; i < countof(szNames); ++i)
{
wchar_t szName[64]; swprintf_c(szName, L"!%s!", szNames[i]);
size_t iLen = lstrlen(szName);
wchar_t* pszStart = StrStrI(pszCmdCopy, szName);
if (!pszStart)
continue;
while (pszStart)
{
pszStart[0] = L'%';
pszStart[iLen-1] = L'%';
pszStart = StrStrI(pszStart+iLen, szName);
}
}
asCmd = pszCmdCopy;
}
wchar_t* pszExpand = ExpandEnvStr(pszCmdCopy ? pszCmdCopy : asCmd);
SafeFree(pszCmdCopy);
return pszExpand;
}
BOOL SetTitle(LPCWSTR lsTitle)
{
LogFunction(L"SetTitle");
LPCWSTR pszSetTitle = lsTitle ? lsTitle : L"";
#ifdef SHOW_SETCONTITLE_MSGBOX
MessageBox(NULL, pszSetTitle, WIN3264TEST(L"ConEmuCD - set title",L"ConEmuCD64 - set title"), MB_SYSTEMMODAL);
#endif
BOOL bRc = SetConsoleTitle(pszSetTitle);
if (gpLogSize)
{
wchar_t* pszLog = lstrmerge(bRc ? L"Done: " : L"Fail: ", pszSetTitle);
LogFunction(pszLog);
SafeFree(pszLog);
}
return bRc;
}
void UpdateConsoleTitle()
{
LogFunction(L"UpdateConsoleTitle");
CEStr szTemp;
wchar_t *pszBuffer = NULL;
LPCWSTR pszSetTitle = NULL, pszCopy;
LPCWSTR pszReq = gpszForcedTitle ? gpszForcedTitle : gpszRunCmd;
if (!pszReq || !*pszReq)
{
// Не должны сюда попадать - сброс заголовка не допустим
#ifdef _DEBUG
if (!(gbAttachMode & am_Modes))
{
_ASSERTE(pszReq && *pszReq);
}
#endif
return;
}
pszBuffer = ParseConEmuSubst(pszReq);
if (pszBuffer)
pszReq = pszBuffer;
pszCopy = pszReq;
if (!gpszForcedTitle && (NextArg(&pszCopy, szTemp) == 0))
{
wchar_t* pszName = (wchar_t*)PointToName(szTemp.ms_Val);
wchar_t* pszExt = (wchar_t*)PointToExt(pszName);
if (pszExt)
*pszExt = 0;
pszSetTitle = pszName;
}
else
{
pszSetTitle = pszReq;
}
// Need to change title? Do it.
if (pszSetTitle && *pszSetTitle)
{
#ifdef _DEBUG
int nLen = 4096; //GetWindowTextLength(ghConWnd); -- KIS2009 гундит "Посылка оконного сообщения"...
gpszPrevConTitle = (wchar_t*)calloc(nLen+1,2);
if (gpszPrevConTitle)
GetConsoleTitleW(gpszPrevConTitle, nLen+1);
#endif
SetTitle(pszSetTitle);
}
SafeFree(pszBuffer);
}
void CdToProfileDir()
{
BOOL bRc = FALSE;
wchar_t szPath[MAX_PATH] = L"";
HRESULT hr = SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath);
if (FAILED(hr))
GetEnvironmentVariable(L"USERPROFILE", szPath, countof(szPath));
if (szPath[0])
bRc = SetCurrentDirectory(szPath);
// Write action to log file
if (gpLogSize)
{
wchar_t* pszMsg = lstrmerge(bRc ? L"Work dir changed to %USERPROFILE%: " : L"CD failed to %USERPROFILE%: ", szPath);
LogFunction(pszMsg);
SafeFree(pszMsg);
}
}
#ifndef WIN64
void CheckNeedSkipWowChange(LPCWSTR asCmdLine)
{
LogFunction(L"CheckNeedSkipWowChange");
// Команды вида: C:\Windows\SysNative\reg.exe Query "HKCU\Software\Far2"|find "Far"
// Для них нельзя отключать редиректор (wow.Disable()), иначе SysNative будет недоступен
if (IsWindows64())
{
LPCWSTR pszTest = asCmdLine;
CEStr szApp;
if (NextArg(&pszTest, szApp) == 0)
{
wchar_t szSysnative[MAX_PATH+32];
int nLen = GetWindowsDirectory(szSysnative, MAX_PATH);
if (nLen >= 2 && nLen < MAX_PATH)
{
AddEndSlash(szSysnative, countof(szSysnative));
wcscat_c(szSysnative, L"Sysnative\\");
nLen = lstrlenW(szSysnative);
int nAppLen = lstrlenW(szApp);
if (nAppLen > nLen)
{
szApp.ms_Val[nLen] = 0;
if (lstrcmpiW(szApp, szSysnative) == 0)
{
gbSkipWowChange = TRUE;
}
}
}
}
}
}
#endif
// When DefTerm debug console is started for Win32 app
// we need to allocate hidden console, and there is no
// active process, until parent DevEnv successfully starts
// new debugging process session
DWORD WaitForRootConsoleProcess(DWORD nTimeout)
{
if (pfnGetConsoleProcessList==NULL)
{
_ASSERTE(FALSE && "Attach to console app was requested, but required WinXP or higher!");
return 0;
}
_ASSERTE(gbCreatingHiddenConsole);
_ASSERTE(ghConWnd!=NULL);
DWORD nFoundPID = 0;
DWORD nStart = GetTickCount(), nDelta = 0;
DWORD nProcesses[20] = {}, nProcCount, i;
PROCESSENTRY32 pi = {};
GetProcessInfo(gnSelfPID, &pi);
while (!nFoundPID && (nDelta < nTimeout))
{
Sleep(50);
nProcCount = pfnGetConsoleProcessList(nProcesses, countof(nProcesses));
for (i = 0; i < nProcCount; i++)
{
DWORD nPID = nProcesses[i];
if (nPID && (nPID != gnSelfPID) && (nPID != pi.th32ParentProcessID))
{
nFoundPID = nPID;
break;
}
}
nDelta = (GetTickCount() - nStart);
}
if (!nFoundPID)
{
apiShowWindow(ghConWnd, SW_SHOWNORMAL);
_ASSERTE(FALSE && "Was unable to find starting process");
}
return nFoundPID;
}
void ApplyProcessSetEnvCmd()
{
#ifdef _DEBUG
CStartEnv::UnitTests();
#endif
if (gpSetEnv)
{
CStartEnv setEnv;
gpSetEnv->Apply(&setEnv);
}
}
// Lines come from Settings/Environment page
void ApplyEnvironmentCommands(LPCWSTR pszCommands)
{
if (!pszCommands || !*pszCommands)
{
_ASSERTE(pszCommands && *pszCommands);
return;
}
UINT nSetCP = 0; // Postponed
if (!gpSetEnv)
gpSetEnv = new CProcessEnvCmd();
// These must be applied before commands from CommandLine
gpSetEnv->AddLines(pszCommands, true);
}
// Allow smth like: ConEmuC -c {Far} /e text.txt
wchar_t* ExpandTaskCmd(LPCWSTR asCmdLine)
{
if (!ghConWnd)
{
_ASSERTE(ghConWnd);
return NULL;
}
if (!asCmdLine || (asCmdLine[0] != TaskBracketLeft))
{
_ASSERTE(asCmdLine && (asCmdLine[0] == TaskBracketLeft));
return NULL;
}
LPCWSTR pszNameEnd = wcschr(asCmdLine, TaskBracketRight);
if (!pszNameEnd)
return NULL;
pszNameEnd++;
size_t cchCount = (pszNameEnd - asCmdLine);
DWORD cbSize = sizeof(CESERVER_REQ_HDR) + sizeof(CESERVER_REQ_TASK) + cchCount*sizeof(asCmdLine[0]);
CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_GETTASKCMD, cbSize);
if (!pIn)
return NULL;
wmemmove(pIn->GetTask.data, asCmdLine, cchCount);
_ASSERTE(pIn->GetTask.data[cchCount] == 0);
wchar_t* pszResult = NULL;
CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
if (pOut && (pOut->DataSize() > sizeof(pOut->GetTask)) && pOut->GetTask.data[0])
{
LPCWSTR pszTail = SkipNonPrintable(pszNameEnd);
pszResult = lstrmerge(pOut->GetTask.data, (pszTail && *pszTail) ? L" " : NULL, pszTail);
}
ExecuteFreeResult(pIn);
ExecuteFreeResult(pOut);
return pszResult;
}
// Parse ConEmuC command line switches
int ParseCommandLine(LPCWSTR asCmdLine)
{
int iRc = 0;
CEStr szArg;
CEStr szExeTest;
LPCWSTR pszArgStarts = NULL;
gbRunViaCmdExe = TRUE;
gbRootIsCmdExe = TRUE;
gbRunInBackgroundTab = FALSE;
size_t nCmdLine = 0;
LPCWSTR pwszStartCmdLine = asCmdLine;
LPCWSTR lsCmdLine = asCmdLine;
BOOL lbNeedCutStartEndQuot = FALSE;
bool lbNeedCdToProfileDir = false;
ConEmuStateCheck eStateCheck = ec_None;
ConEmuExecAction eExecAction = ea_None;
MacroInstance MacroInst = {}; // Special ConEmu instance for GUIMACRO and other options
if (!lsCmdLine || !*lsCmdLine)
{
DWORD dwErr = GetLastError();
_printf("GetCommandLineW failed! ErrCode=0x%08X\n", dwErr);
return CERR_GETCOMMANDLINE;
}
#ifdef _DEBUG
// Для отлова запуска дебаггера
//_ASSERTE(wcsstr(lsCmdLine, L"/DEBUGPID=")==0);
#endif
gnRunMode = RM_UNDEFINED;
BOOL lbAttachGuiApp = FALSE;
struct {
CEStr szConEmuAddArgs;
void Append(LPCWSTR asSwitch, LPCWSTR asValue)
{
lstrmerge(&szConEmuAddArgs.ms_Val, asSwitch);
if (asValue && *asValue)
{
bool needQuot = IsQuotationNeeded(asValue);
lstrmerge(&szConEmuAddArgs.ms_Val,
needQuot ? L" \"" : L" ",
asValue,
needQuot ? L"\"" : NULL);
}
SetEnvironmentVariable(ENV_CONEMU_EXEARGS_W, szConEmuAddArgs);
}
} AddArgs;
while ((iRc = NextArg(&lsCmdLine, szArg, &pszArgStarts)) == 0)
{
xf_check();
if ((szArg[0] == L'/' || szArg[0] == L'-')
&& (szArg[1] == L'?' || ((szArg[1] & ~0x20) == L'H'))
&& szArg[2] == 0)
{
Help();
return CERR_HELPREQUESTED;
}
// Following code wants '/'style arguments
// Change '-'style to '/'style
if (szArg[0] == L'-')
szArg.SetAt(0, L'/');
else if (szArg[0] != L'/')
continue;
#ifdef _DEBUG
if (lstrcmpi(szArg, L"/DEBUGTRAP")==0)
{
int i, j = 1; j--; i = 1 / j;
}
else
#endif
// **** Unit tests ****
if (lstrcmpi(szArg, L"/Args")==0 || lstrcmpi(szArg, L"/ParseArgs")==0)
{
eExecAction = ea_ParseArgs;
break;
}
else if (lstrcmpi(szArg, L"/ConInfo")==0)
{
eExecAction = ea_PrintConsoleInfo;
break;
}
else if (lstrcmpi(szArg, L"/CheckUnicode")==0)
{
eExecAction = ea_CheckUnicodeFont;
break;
}
else if (lstrcmpi(szArg, L"/TestUnicode")==0)
{
eExecAction = ea_TestUnicodeCvt;
break;
}
else if (lstrcmpi(szArg, L"/OsVerInfo")==0)
{
eExecAction = ea_OsVerInfo;
break;
}
else if (lstrcmpi(szArg, L"/ErrorLevel")==0)
{
eExecAction = ea_ErrorLevel;
break;
}
else if (lstrcmpi(szArg, L"/Result")==0)
{
gbPrintRetErrLevel = TRUE;
}
else if (lstrcmpi(szArg, L"/echo")==0 || lstrcmpi(szArg, L"/e")==0)
{
eExecAction = ea_OutEcho;
break;
}
else if (lstrcmpi(szArg, L"/type")==0 || lstrcmpi(szArg, L"/t")==0)
{
eExecAction = ea_OutType;
break;
}
// **** Regular use ****
else if (wcsncmp(szArg, L"/REGCONFONT=", 12)==0)
{
eExecAction = ea_RegConFont;
lsCmdLine = szArg.Mid(12);
break;
}
else if (wcsncmp(szArg, L"/SETHOOKS=", 10) == 0)
{
eExecAction = ea_InjectHooks;
lsCmdLine = szArg.Mid(10);
break;
}
else if (wcsncmp(szArg, L"/INJECT=", 8) == 0)
{
eExecAction = ea_InjectRemote;
lsCmdLine = szArg.Mid(8);
break;
}
else if (wcsncmp(szArg, L"/DEFTRM=", 8) == 0)
{
eExecAction = ea_InjectDefTrm;
lsCmdLine = szArg.Mid(8);
break;
}
// /GUIMACRO[:PID|HWND] <Macro string>
else if (lstrcmpni(szArg, L"/GUIMACRO", 9) == 0)
{
// Все что в lsCmdLine - выполнить в Gui
ArgGuiMacro(szArg, MacroInst);
eExecAction = ea_GuiMacro;
break;
}
else if (lstrcmpi(szArg, L"/STORECWD") == 0)
{
eExecAction = ea_StoreCWD;
break;
}
else if (lstrcmpi(szArg, L"/STRUCT") == 0)
{
eExecAction = ea_DumpStruct;
break;
}
else if (lstrcmpi(szArg, L"/SILENT")==0)
{
gbPreferSilentMode = true;
}
else if (lstrcmpi(szArg, L"/USEEXPORT")==0)
{
gbMacroExportResult = true;
}
else if (lstrcmpni(szArg, L"/EXPORT", 7)==0)
{
//_ASSERTE(FALSE && "Continue to export");
if (lstrcmpi(szArg, L"/EXPORT=ALL")==0 || lstrcmpi(szArg, L"/EXPORTALL")==0)
eExecAction = ea_ExportAll;
else if (lstrcmpi(szArg, L"/EXPORT=CON")==0 || lstrcmpi(szArg, L"/EXPORTCON")==0)
eExecAction = ea_ExportCon;
else if (lstrcmpi(szArg, L"/EXPORT=GUI")==0 || lstrcmpi(szArg, L"/EXPORTGUI")==0)
eExecAction = ea_ExportGui;
else
eExecAction = ea_ExportTab;
break;
}
else if (lstrcmpi(szArg, L"/IsConEmu")==0)
{
eStateCheck = ec_IsConEmu;
break;
}
else if (lstrcmpi(szArg, L"/IsTerm")==0)
{
eStateCheck = ec_IsTerm;
break;
}
else if (lstrcmpi(szArg, L"/IsAnsi")==0)
{
eStateCheck = ec_IsAnsi;
break;
}
else if (lstrcmpi(szArg, L"/IsAdmin")==0)
{
eStateCheck = ec_IsAdmin;
break;
}
else if (lstrcmpi(szArg, L"/IsRedirect")==0)
{
eStateCheck = ec_IsRedirect;
break;
}
else if ((wcscmp(szArg, L"/CONFIRM")==0)
|| (wcscmp(szArg, L"/CONFHALT")==0)
|| (wcscmp(szArg, L"/ECONFIRM")==0))
{
gnConfirmExitParm = (wcscmp(szArg, L"/CONFIRM")==0) ? RConStartArgs::eConfAlways
: (wcscmp(szArg, L"/CONFHALT")==0) ? RConStartArgs::eConfHalt
: RConStartArgs::eConfEmpty;
gbAlwaysConfirmExit = TRUE; gbAutoDisableConfirmExit = FALSE;
}
else if (wcscmp(szArg, L"/NOCONFIRM")==0)
{
gnConfirmExitParm = RConStartArgs::eConfNever;
gbAlwaysConfirmExit = FALSE; gbAutoDisableConfirmExit = FALSE;
}
else if (wcscmp(szArg, L"/OMITHOOKSWARN")==0)
{
gbSkipHookersCheck = true;
}
else if (wcscmp(szArg, L"/ADMIN")==0)
{
#if defined(SHOW_ATTACH_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"%s PID=%u /ADMIN", gsModuleName, gnSelfPID);
const wchar_t* pszCmdLine = GetCommandLineW();
MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
}
#endif
gbAttachMode |= am_Admin;
gnRunMode = RM_SERVER;
}
else if (wcscmp(szArg, L"/ATTACH")==0)
{
#if defined(SHOW_ATTACH_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"%s PID=%u /ATTACH", gsModuleName, gnSelfPID);
const wchar_t* pszCmdLine = GetCommandLineW();
MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
}
#endif
if (!(gbAttachMode & am_Modes))
gbAttachMode |= am_Simple;
gnRunMode = RM_SERVER;
}
else if ((lstrcmpi(szArg, L"/AUTOATTACH")==0) || (lstrcmpi(szArg, L"/ATTACHDEFTERM")==0))
{
#if defined(SHOW_ATTACH_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"%s PID=%u %s", gsModuleName, gnSelfPID, szArg.ms_Val);
const wchar_t* pszCmdLine = GetCommandLineW();
MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
}
#endif
gbAttachMode |= am_Auto;
gbAlienMode = TRUE;
gbNoCreateProcess = TRUE;
if (lstrcmpi(szArg, L"/AUTOATTACH")==0)
{
gnRunMode = RM_AUTOATTACH;
gbAttachMode |= am_Async;
}
if (lstrcmpi(szArg, L"/ATTACHDEFTERM")==0)
{
gnRunMode = RM_SERVER;
gbAttachMode |= am_DefTerm;
}
// Еще может быть "/GHWND=NEW" но оно ниже. Там ставится "gpSrv->bRequestNewGuiWnd=TRUE"
//ConEmu autorun (c) Maximus5
//Starting "%ConEmuPath%" in "Attach" mode (NewWnd=%FORCE_NEW_WND%)
if (!IsAutoAttachAllowed())
{
if (ghConWnd && IsWindowVisible(ghConWnd))
{
_printf("AutoAttach was requested, but skipped\n");
}
DisableAutoConfirmExit();
//_ASSERTE(FALSE && "AutoAttach was called while Update process is in progress?");
return CERR_AUTOATTACH_NOT_ALLOWED;
}
}
else if (wcsncmp(szArg, L"/GUIATTACH=", 11)==0)
{
#if defined(SHOW_ATTACH_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"%s PID=%u /GUIATTACH", gsModuleName, gnSelfPID);
const wchar_t* pszCmdLine = GetCommandLineW();
MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
}
#endif
if (!(gbAttachMode & am_Modes))
gbAttachMode |= am_Simple;
lbAttachGuiApp = TRUE;
wchar_t* pszEnd;
// suppress warning C4312 'type cast': conversion from 'unsigned long' to 'HWND' of greater size
HWND hAppWnd = (HWND)(UINT_PTR)wcstoul(szArg.Mid(11), &pszEnd, 16);
if (IsWindow(hAppWnd))
gpSrv->hRootProcessGui = hAppWnd;
gnRunMode = RM_SERVER;
}
else if (wcscmp(szArg, L"/NOCMD")==0)
{
gnRunMode = RM_SERVER;
gbNoCreateProcess = TRUE;
gbAlienMode = TRUE;
}
else if (wcsncmp(szArg, L"/PARENTFARPID=", 14)==0)
{
// Для режима RM_COMSPEC нужно будет сохранить "длинный вывод"
wchar_t* pszEnd = NULL, *pszStart;
pszStart = szArg.ms_Val+14;
gpSrv->dwParentFarPID = wcstoul(pszStart, &pszEnd, 10);
}
else if (wcscmp(szArg, L"/CREATECON")==0)
{
gbCreatingHiddenConsole = TRUE;
//_ASSERTE(FALSE && "Continue to create con");
}
else if (wcscmp(szArg, L"/ROOTEXE")==0)
{
if (0 == NextArg(&lsCmdLine, szArg))
gpszRootExe = lstrmerge(L"\"", szArg, L"\"");
}
else if (wcsncmp(szArg, L"/PID=", 5)==0 || wcsncmp(szArg, L"/TRMPID=", 8)==0
|| wcsncmp(szArg, L"/FARPID=", 8)==0 || wcsncmp(szArg, L"/CONPID=", 8)==0)
{
gnRunMode = RM_SERVER;
gbNoCreateProcess = TRUE; // Процесс УЖЕ запущен
gbAlienMode = TRUE; // Консоль создана НЕ нами
wchar_t* pszEnd = NULL, *pszStart;
if (wcsncmp(szArg, L"/TRMPID=", 8)==0)
{
// This is called from *.vshost.exe when "AllocConsole" just created
gbDefTermCall = TRUE;
gbDontInjectConEmuHk = TRUE;
pszStart = szArg.ms_Val+8;
}
else if (wcsncmp(szArg, L"/FARPID=", 8)==0)
{
gbAttachFromFar = TRUE;
gbRootIsCmdExe = FALSE;
pszStart = szArg.ms_Val+8;
}
else if (wcsncmp(szArg, L"/CONPID=", 8)==0)
{
//_ASSERTE(FALSE && "Continue to alternative attach mode");
gbAlternativeAttach = TRUE;
gbRootIsCmdExe = FALSE;
pszStart = szArg.ms_Val+8;
}
else
{
pszStart = szArg.ms_Val+5;
}
gpSrv->dwRootProcess = wcstoul(pszStart, &pszEnd, 10);
if ((gpSrv->dwRootProcess == 0) && gbCreatingHiddenConsole)
{
gpSrv->dwRootProcess = WaitForRootConsoleProcess(30000);
}
// --
//if (gpSrv->dwRootProcess)
//{
// _ASSERTE(gpSrv->hRootProcess==NULL); // Еще не должен был быть открыт
// gpSrv->hRootProcess = OpenProcess(MY_PROCESS_ALL_ACCESS, FALSE, gpSrv->dwRootProcess);
// if (gpSrv->hRootProcess == NULL)
// {
// gpSrv->hRootProcess = OpenProcess(SYNCHRONIZE|PROCESS_QUERY_INFORMATION, FALSE, gpSrv->dwRootProcess);
// }
//}
if (gbAlternativeAttach && gpSrv->dwRootProcess)
{
// Если процесс был запущен "с консольным окном"
if (ghConWnd)
{
#ifdef _DEBUG
SafeCloseHandle(ghFarInExecuteEvent);
#endif
}
BOOL bAttach = FALSE;
HMODULE hKernel = GetModuleHandle(L"kernel32.dll");
AttachConsole_t AttachConsole_f = hKernel ? (AttachConsole_t)GetProcAddress(hKernel,"AttachConsole") : NULL;
HWND hSaveCon = GetConsoleWindow();
RetryAttach:
if (AttachConsole_f)
{
// FreeConsole нужно дергать даже если ghConWnd уже NULL. Что-то в винде глючит и
// AttachConsole вернет ERROR_ACCESS_DENIED, если FreeConsole не звать...
FreeConsole();
ghConWnd = NULL;
// Issue 998: Need to wait, while real console will appear
// gpSrv->hRootProcess еще не открыт
HANDLE hProcess = OpenProcess(SYNCHRONIZE, FALSE, gpSrv->dwRootProcess);
while (hProcess && hProcess != INVALID_HANDLE_VALUE)
{
DWORD nConPid = 0;
HWND hNewCon = FindWindowEx(NULL, NULL, RealConsoleClass, NULL);
while (hNewCon)
{
if (GetWindowThreadProcessId(hNewCon, &nConPid) && (nConPid == gpSrv->dwRootProcess))
break;
hNewCon = FindWindowEx(NULL, hNewCon, RealConsoleClass, NULL);
}
if ((hNewCon != NULL) || (WaitForSingleObject(hProcess, 100) == WAIT_OBJECT_0))
break;
}
SafeCloseHandle(hProcess);
// Sometimes conhost handles are created with lags, wait for a while
DWORD nStartTick = GetTickCount();
const DWORD reattach_duration = 5000; // 5 sec
while (!bAttach)
{
bAttach = AttachConsole_f(gpSrv->dwRootProcess);
if (bAttach)
break;
Sleep(50);
DWORD nDelta = (GetTickCount() - nStartTick);
if (nDelta >= reattach_duration)
break;
LogString(L"Retrying AttachConsole after 50ms delay");
}
}
else
{
SetLastError(ERROR_PROC_NOT_FOUND);
}
if (!bAttach)
{
DWORD nErr = GetLastError();
size_t cchMsgMax = 10*MAX_PATH;
wchar_t* pszMsg = (wchar_t*)calloc(cchMsgMax,sizeof(*pszMsg));
wchar_t szTitle[MAX_PATH];
HWND hFindConWnd = FindWindowEx(NULL, NULL, RealConsoleClass, NULL);
DWORD nFindConPID = 0; if (hFindConWnd) GetWindowThreadProcessId(hFindConWnd, &nFindConPID);
PROCESSENTRY32 piCon = {}, piRoot = {};
GetProcessInfo(gpSrv->dwRootProcess, &piRoot);
if (nFindConPID == gpSrv->dwRootProcess)
piCon = piRoot;
else if (nFindConPID)
GetProcessInfo(nFindConPID, &piCon);
if (hFindConWnd)
GetWindowText(hFindConWnd, szTitle, countof(szTitle));
else
szTitle[0] = 0;
_wsprintf(pszMsg, SKIPLEN(cchMsgMax)
L"AttachConsole(PID=%u) failed, code=%u\n"
L"[%u]: %s\n"
L"Top console HWND=x%08X, PID=%u, %s\n%s\n---\n"
L"Prev (self) console HWND=x%08X\n\n"
L"Retry?",
gpSrv->dwRootProcess, nErr,
gpSrv->dwRootProcess, piRoot.szExeFile,
LODWORD(hFindConWnd), nFindConPID, piCon.szExeFile, szTitle,
LODWORD(hSaveCon)
);
swprintf_c(szTitle, L"%s: PID=%u", gsModuleName, GetCurrentProcessId());
int nBtn = MessageBox(NULL, pszMsg, szTitle, MB_ICONSTOP|MB_SYSTEMMODAL|MB_RETRYCANCEL);
free(pszMsg);
if (nBtn == IDRETRY)
{
goto RetryAttach;
}
gbInShutdown = TRUE;
gbAlwaysConfirmExit = FALSE;
LogString(L"CERR_CARGUMENT: (gbAlternativeAttach && gpSrv->dwRootProcess)");
return CERR_CARGUMENT;
}
ghConWnd = GetConEmuHWND(2);
gbVisibleOnStartup = IsWindowVisible(ghConWnd);
// Need to be set, because of new console === new handler
SetConsoleCtrlHandler((PHANDLER_ROUTINE)HandlerRoutine, true);
#ifdef _DEBUG
_ASSERTE(ghFarInExecuteEvent==NULL);
_ASSERTE(ghConWnd!=NULL);
#endif
}
else if (gpSrv->dwRootProcess == 0)
{
LogString("CERR_CARGUMENT: Attach to GUI was requested, but invalid PID specified");
_printf("Attach to GUI was requested, but invalid PID specified:\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE && "Attach to GUI was requested, but invalid PID specified");
return CERR_CARGUMENT;
}
}
else if (wcsncmp(szArg, L"/CINMODE=", 9)==0)
{
wchar_t* pszEnd = NULL, *pszStart = szArg.ms_Val+9;
gnConsoleModeFlags = wcstoul(pszStart, &pszEnd, 16);
// если передан 0 - включится (ENABLE_QUICK_EDIT_MODE|ENABLE_EXTENDED_FLAGS|ENABLE_INSERT_MODE)
gbConsoleModeFlags = (gnConsoleModeFlags != 0);
}
else if (wcscmp(szArg, L"/HIDE")==0)
{
gbForceHideConWnd = TRUE;
}
else if (wcsncmp(szArg, L"/B", 2)==0)
{
wchar_t* pszEnd = NULL;
if (wcsncmp(szArg, L"/BW=", 4)==0)
{
gcrVisibleSize.X = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10); gbParmVisibleSize = TRUE;
}
else if (wcsncmp(szArg, L"/BH=", 4)==0)
{
gcrVisibleSize.Y = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10); gbParmVisibleSize = TRUE;
}
else if (wcsncmp(szArg, L"/BZ=", 4)==0)
{
gnBufferHeight = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10); gbParmBufSize = TRUE;
}
TODO("/BX для ширины буфера?");
}
else if (wcsncmp(szArg, L"/F", 2)==0 && szArg[2] && szArg[3] == L'=')
{
wchar_t* pszEnd = NULL;
if (wcsncmp(szArg, L"/FN=", 4)==0) //-V112
{
lstrcpynW(gpSrv->szConsoleFont, szArg.Mid(4), 32); //-V112
}
else if (wcsncmp(szArg, L"/FW=", 4)==0) //-V112
{
gpSrv->nConFontWidth = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10);
}
else if (wcsncmp(szArg, L"/FH=", 4)==0) //-V112
{
gpSrv->nConFontHeight = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10);
//} else if (wcsncmp(szArg, L"/FF=", 4)==0) {
// lstrcpynW(gpSrv->szConsoleFontFile, szArg+4, MAX_PATH);
}
}
else if (lstrcmpni(szArg, L"/LOG", 4) == 0) //-V112
{
int nLevel = 0;
if (szArg[4]==L'1') nLevel = 1; else if (szArg[4]>=L'2') nLevel = 2;
CreateLogSizeFile(nLevel);
}
else if (wcsncmp(szArg, L"/GID=", 5)==0)
{
gnRunMode = RM_SERVER;
wchar_t* pszEnd = NULL;
gnConEmuPID = wcstoul(szArg.Mid(5), &pszEnd, 10);
if (gnConEmuPID == 0)
{
LogString(L"CERR_CARGUMENT: Invalid GUI PID specified");
_printf("Invalid GUI PID specified:\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
}
else if (wcsncmp(szArg, L"/AID=", 5)==0)
{
wchar_t* pszEnd = NULL;
gpSrv->dwGuiAID = wcstoul(szArg.Mid(5), &pszEnd, 10);
}
else if (wcsncmp(szArg, L"/GHWND=", 7)==0)
{
if (gnRunMode == RM_UNDEFINED)
{
gnRunMode = RM_SERVER;
}
else
{
_ASSERTE(gnRunMode == RM_AUTOATTACH || gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER);
}
wchar_t* pszEnd = NULL;
if (lstrcmpi(szArg.Mid(7), L"NEW") == 0)
{
gpSrv->hGuiWnd = NULL;
_ASSERTE(gnConEmuPID == 0);
gnConEmuPID = 0;
gpSrv->bRequestNewGuiWnd = TRUE;
}
else
{
wchar_t szLog[120];
LPCWSTR pszDescr = szArg.Mid(7);
if (pszDescr[0] == L'0' && (pszDescr[1] == L'x' || pszDescr[1] == L'X'))
pszDescr += 2; // That may be useful for calling from batch files
gpSrv->hGuiWnd = (HWND)(UINT_PTR)wcstoul(pszDescr, &pszEnd, 16);
gpSrv->bRequestNewGuiWnd = FALSE;
BOOL isWnd = gpSrv->hGuiWnd ? IsWindow(gpSrv->hGuiWnd) : FALSE;
DWORD nErr = gpSrv->hGuiWnd ? GetLastError() : 0;
swprintf_c(szLog, L"GUI HWND=0x%08X, %s, ErrCode=%u", LODWORD(gpSrv->hGuiWnd), isWnd ? L"Valid" : L"Invalid", nErr);
LogString(szLog);
if (!isWnd)
{
LogString(L"CERR_CARGUMENT: Invalid GUI HWND was specified in /GHWND arg");
_printf("Invalid GUI HWND specified: ");
_wprintf(szArg);
_printf("\n" "Command line:\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE && "Invalid window was specified in /GHWND arg");
return CERR_CARGUMENT;
}
DWORD nPID = 0;
GetWindowThreadProcessId(gpSrv->hGuiWnd, &nPID);
_ASSERTE(gnConEmuPID == 0 || gnConEmuPID == nPID);
gnConEmuPID = nPID;
}
}
else if (wcsncmp(szArg, L"/TA=", 4)==0)
{
wchar_t* pszEnd = NULL;
DWORD nColors = wcstoul(szArg.Mid(4), &pszEnd, 16);
if (nColors)
{
DWORD nTextIdx = (nColors & 0xFF);
DWORD nBackIdx = ((nColors >> 8) & 0xFF);
DWORD nPopTextIdx = ((nColors >> 16) & 0xFF);
DWORD nPopBackIdx = ((nColors >> 24) & 0xFF);
if ((nTextIdx <= 15) && (nBackIdx <= 15) && (nTextIdx != nBackIdx))
gnDefTextColors = MAKECONCOLOR(nTextIdx, nBackIdx);
if ((nPopTextIdx <= 15) && (nPopBackIdx <= 15) && (nPopTextIdx != nPopBackIdx))
gnDefPopupColors = MAKECONCOLOR(nPopTextIdx, nPopBackIdx);
HANDLE hConOut = ghConOut;
CONSOLE_SCREEN_BUFFER_INFO csbi5 = {};
GetConsoleScreenBufferInfo(hConOut, &csbi5);
if (gnDefTextColors || gnDefPopupColors)
{
BOOL bPassed = FALSE;
if (gnDefPopupColors && (gnOsVer >= 0x600))
{
MY_CONSOLE_SCREEN_BUFFER_INFOEX csbi = {sizeof(csbi)};
if (apiGetConsoleScreenBufferInfoEx(hConOut, &csbi))
{
// Microsoft bug? When console is started elevated - it does NOT show
// required attributes, BUT GetConsoleScreenBufferInfoEx returns them.
if (!(gbAttachMode & am_Admin)
&& (!gnDefTextColors || (csbi.wAttributes = gnDefTextColors))
&& (!gnDefPopupColors || (csbi.wPopupAttributes = gnDefPopupColors)))
{
bPassed = TRUE; // Менять не нужно, консоль соответствует
}
else
{
if (gnDefTextColors)
csbi.wAttributes = gnDefTextColors;
if (gnDefPopupColors)
csbi.wPopupAttributes = gnDefPopupColors;
_ASSERTE(FALSE && "Continue to SetConsoleScreenBufferInfoEx");
// Vista/Win7. _SetConsoleScreenBufferInfoEx unexpectedly SHOWS console window
//if (gnOsVer == 0x0601)
//{
// RECT rcGui = {};
// if (gpSrv->hGuiWnd)
// GetWindowRect(gpSrv->hGuiWnd, &rcGui);
// //SetWindowPos(ghConWnd, HWND_BOTTOM, rcGui.left+3, rcGui.top+3, 0,0, SWP_NOSIZE|SWP_SHOWWINDOW|SWP_NOZORDER);
// SetWindowPos(ghConWnd, NULL, -30000, -30000, 0,0, SWP_NOSIZE|SWP_SHOWWINDOW|SWP_NOZORDER);
// apiShowWindow(ghConWnd, SW_SHOWMINNOACTIVE);
// #ifdef _DEBUG
// apiShowWindow(ghConWnd, SW_SHOWNORMAL);
// apiShowWindow(ghConWnd, SW_HIDE);
// #endif
//}
bPassed = apiSetConsoleScreenBufferInfoEx(hConOut, &csbi);
// Что-то Win7 хулиганит
if (!gbVisibleOnStartup)
{
apiShowWindow(ghConWnd, SW_HIDE);
}
}
}
}
if (!bPassed && gnDefTextColors)
{
SetConsoleTextAttribute(hConOut, gnDefTextColors);
RefillConsoleAttributes(csbi5, csbi5.wAttributes, gnDefTextColors);
}
}
}
}
else if (lstrcmpni(szArg, L"/DEBUGPID=", 10)==0)
{
//gnRunMode = RM_SERVER; -- не будем ставить, RM_UNDEFINED будет признаком того, что просто хотят дебаггер
gbNoCreateProcess = TRUE;
gpSrv->DbgInfo.bDebugProcess = TRUE;
gpSrv->DbgInfo.bDebugProcessTree = FALSE;
wchar_t* pszEnd = NULL;
gpSrv->dwRootProcess = wcstoul(szArg.Mid(10), &pszEnd, 10);
if (gpSrv->dwRootProcess == 0)
{
LogString(L"CERR_CARGUMENT: Debug of process was requested, but invalid PID specified");
_printf("Debug of process was requested, but invalid PID specified:\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
// "Comma" is a mark that debug/dump was requested for a bunch of processes
if (pszEnd && (*pszEnd == L','))
{
gpSrv->DbgInfo.bDebugMultiProcess = TRUE;
gpSrv->DbgInfo.pDebugAttachProcesses = new MArray<DWORD>;
while (pszEnd && (*pszEnd == L',') && *(pszEnd+1))
{
DWORD nPID = wcstoul(pszEnd+1, &pszEnd, 10);
if (nPID != 0)
gpSrv->DbgInfo.pDebugAttachProcesses->push_back(nPID);
}
}
}
else if (lstrcmpi(szArg, L"/DEBUGEXE")==0 || lstrcmpi(szArg, L"/DEBUGTREE")==0)
{
//gnRunMode = RM_SERVER; -- не будем ставить, RM_UNDEFINED будет признаком того, что просто хотят дебаггер
_ASSERTE(gpSrv->DbgInfo.bDebugProcess==FALSE);
gbNoCreateProcess = TRUE;
gpSrv->DbgInfo.bDebugProcess = TRUE;
gpSrv->DbgInfo.bDebugProcessTree = (lstrcmpi(szArg, L"/DEBUGTREE")==0);
wchar_t* pszLine = lstrdup(GetCommandLineW());
if (!pszLine || !*pszLine)
{
LogString(L"CERR_CARGUMENT: Debug of process was requested, but GetCommandLineW failed");
_printf("Debug of process was requested, but GetCommandLineW failed\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
LPWSTR pszDebugCmd = wcsstr(pszLine, szArg);
if (pszDebugCmd)
{
pszDebugCmd = (LPWSTR)SkipNonPrintable(pszDebugCmd + lstrlen(szArg));
}
if (!pszDebugCmd || !*pszDebugCmd)
{
LogString(L"CERR_CARGUMENT: Debug of process was requested, but command was not found");
_printf("Debug of process was requested, but command was not found\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
gpSrv->DbgInfo.pszDebuggingCmdLine = pszDebugCmd;
break;
}
else if (lstrcmpi(szArg, L"/DUMP")==0)
{
gpSrv->DbgInfo.nDebugDumpProcess = 1;
}
else if (lstrcmpi(szArg, L"/MINIDUMP")==0 || lstrcmpi(szArg, L"/MINI")==0)
{
gpSrv->DbgInfo.nDebugDumpProcess = 2;
}
else if (lstrcmpi(szArg, L"/FULLDUMP")==0 || lstrcmpi(szArg, L"/FULL")==0)
{
gpSrv->DbgInfo.nDebugDumpProcess = 3;
}
else if (lstrcmpi(szArg, L"/AUTOMINI")==0)
{
//_ASSERTE(FALSE && "Continue to /AUTOMINI");
gpSrv->DbgInfo.nDebugDumpProcess = 0;
gpSrv->DbgInfo.bAutoDump = TRUE;
gpSrv->DbgInfo.nAutoInterval = 1000;
if (lsCmdLine && *lsCmdLine && isDigit(lsCmdLine[0])
&& (NextArg(&lsCmdLine, szArg, &pszArgStarts) == 0))
{
wchar_t* pszEnd;
DWORD nVal = wcstol(szArg, &pszEnd, 10);
if (nVal)
{
if (pszEnd && *pszEnd)
{
if (lstrcmpni(pszEnd, L"ms", 2) == 0)
{
// Already milliseconds
pszEnd += 2;
}
else if (lstrcmpni(pszEnd, L"s", 1) == 0)
{
nVal *= 60; // seconds
pszEnd++;
}
else if (lstrcmpni(pszEnd, L"m", 2) == 0)
{
nVal *= 60*60; // minutes
pszEnd++;
}
}
gpSrv->DbgInfo.nAutoInterval = nVal;
}
}
}
else if (lstrcmpi(szArg, L"/PROFILECD")==0)
{
lbNeedCdToProfileDir = true;
}
else if (lstrcmpi(szArg, L"/CONFIG")==0)
{
if ((iRc = NextArg(&lsCmdLine, szArg)) != 0)
{
_ASSERTE(FALSE && "Config name was not specified!");
_wprintf(L"Config name was not specified!\r\n");
break;
}
// Reuse config if starting "ConEmu.exe" from console server!
SetEnvironmentVariable(ENV_CONEMU_CONFIG_W, szArg);
AddArgs.Append(L"-config", szArg);
}
else if (lstrcmpi(szArg, L"/LoadCfgFile")==0)
{
// Reuse specified xml file if starting "ConEmu.exe" from console server!
#ifdef SHOW_LOADCFGFILE_MSGBOX
MessageBox(NULL, lsCmdLine, L"/LoadCfgFile", MB_SYSTEMMODAL);
#endif
if ((iRc = NextArg(&lsCmdLine, szArg)) != 0)
{
_ASSERTE(FALSE && "Xml file name was not specified!");
_wprintf(L"Xml file name was not specified!\r\n");
break;
}
AddArgs.Append(L"-LoadCfgFile", szArg);
}
else if (lstrcmpi(szArg, L"/ASYNC") == 0 || lstrcmpi(szArg, L"/FORK") == 0)
{
gbAsyncRun = TRUE;
}
else if (lstrcmpi(szArg, L"/NOINJECT")==0)
{
gbDontInjectConEmuHk = TRUE;
}
else if (lstrcmpi(szArg, L"/DOSBOX")==0)
{
gbUseDosBox = TRUE;
}
// После этих аргументов - идет то, что передается в CreateProcess!
else if (lstrcmpi(szArg, L"/ROOT")==0)
{
#ifdef SHOW_SERVER_STARTED_MSGBOX
ShowServerStartedMsgBox(asCmdLine);
#endif
gnRunMode = RM_SERVER; gbNoCreateProcess = FALSE;
gbAsyncRun = FALSE;
SetWorkEnvVar();
break; // lsCmdLine уже указывает на запускаемую программу
}
// После этих аргументов - идет то, что передается в COMSPEC (CreateProcess)!
//if (wcscmp(szArg, L"/C")==0 || wcscmp(szArg, L"/c")==0 || wcscmp(szArg, L"/K")==0 || wcscmp(szArg, L"/k")==0) {
else if (szArg[0] == L'/' && (((szArg[1] & ~0x20) == L'C') || ((szArg[1] & ~0x20) == L'K')))
{
gbNoCreateProcess = FALSE;
if (szArg[2] == 0) // "/c" или "/k"
gnRunMode = RM_COMSPEC;
if (gnRunMode == RM_UNDEFINED && szArg[4] == 0
&& ((szArg[2] & ~0x20) == L'M') && ((szArg[3] & ~0x20) == L'D'))
{
_ASSERTE(FALSE && "'/cmd' obsolete switch. use /c, /k, /root");
gnRunMode = RM_SERVER;
}
// Если тип работа до сих пор не определили - считаем что режим ComSpec
// и команда начинается сразу после /c (может быть "cmd /cecho xxx")
if (gnRunMode == RM_UNDEFINED)
{
gnRunMode = RM_COMSPEC;
// Поддержка возможности "cmd /cecho xxx"
lsCmdLine = SkipNonPrintable(pszArgStarts + 2);
}
if (gnRunMode == RM_COMSPEC)
{
gpSrv->bK = (szArg[1] & ~0x20) == L'K';
}
if (lsCmdLine && (lsCmdLine[0] == TaskBracketLeft) && wcschr(lsCmdLine, TaskBracketRight))
{
// Allow smth like: ConEmuC -c {Far} /e text.txt
gpszTaskCmd = ExpandTaskCmd(lsCmdLine);
if (gpszTaskCmd && *gpszTaskCmd)
lsCmdLine = gpszTaskCmd;
}
break; // lsCmdLine уже указывает на запускаемую программу
}
else
{
_ASSERTE(FALSE && "Unknown switch!");
_wprintf(L"Unknown switch: ");
_wprintf(szArg);
_wprintf(L"\r\n");
}
}
LogFunction(L"ParseCommandLine{in-progress}");
// Switch "/PROFILECD" used when server to be started under different credentials as GUI.
// So, we need to do "cd %USERPROFILE%" which is more suitable to user.
if (lbNeedCdToProfileDir)
{
CdToProfileDir();
}
// Some checks or actions
if (eStateCheck || eExecAction)
{
int iFRc = CERR_CARGUMENT;
if (eStateCheck)
{
bool bOn = DoStateCheck(eStateCheck);
iFRc = bOn ? CERR_CHKSTATE_ON : CERR_CHKSTATE_OFF;
}
else if (eExecAction)
{
iFRc = DoExecAction(eExecAction, lsCmdLine, MacroInst);
}
// И сразу на выход
gbInShutdown = TRUE;
return iFRc;
}
if ((gbAttachMode & am_DefTerm) && !gbParmVisibleSize)
{
// To avoid "small" and trimmed text after starting console
_ASSERTE(gcrVisibleSize.X==80 && gcrVisibleSize.Y==25);
gbParmVisibleSize = TRUE;
}
// Параметры из комстроки разобраны. Здесь могут уже быть известны
// gpSrv->hGuiWnd {/GHWND}, gnConEmuPID {/GPID}, gpSrv->dwGuiAID {/AID}
// gbAttachMode для ключей {/ADMIN}, {/ATTACH}, {/AUTOATTACH}, {/GUIATTACH}
// В принципе, gbAttachMode включается и при "/ADMIN", но при запуске из ConEmu такого быть не может,
// будут установлены и gpSrv->hGuiWnd, и gnConEmuPID
// Issue 364, например, идет билд в VS, запускается CustomStep, в этот момент автоаттач нафиг не нужен
// Теоретически, в Студии не должно бы быть запуска ConEmuC.exe, но он может оказаться в "COMSPEC", так что проверим.
if (gbAttachMode
&& ((gnRunMode == RM_SERVER) || (gnRunMode == RM_AUTOATTACH))
&& (gnConEmuPID == 0))
{
//-- ассерт не нужен вроде
//_ASSERTE(!gbAlternativeAttach && "Alternative mode must be already processed!");
BOOL lbIsWindowVisible = FALSE;
// Добавим проверку на telnet
if (!ghConWnd
|| !(lbIsWindowVisible = IsAutoAttachAllowed())
|| isTerminalMode())
{
if (gpLogSize)
{
if (!ghConWnd) { LogFunction(L"!ghConWnd"); }
else if (!lbIsWindowVisible) { LogFunction(L"!IsAutoAttachAllowed"); }
else { LogFunction(L"isTerminalMode"); }
}
// Но это может быть все-таки наше окошко. Как проверить...
// Найдем первый параметр
LPCWSTR pszSlash = lsCmdLine ? wcschr(lsCmdLine, L'/') : NULL;
if (pszSlash)
{
LogFunction(pszSlash);
// И сравним с используемыми у нас. Возможно потом еще что-то добавить придется
if (wmemcmp(pszSlash, L"/DEBUGPID=", 10) != 0)
pszSlash = NULL;
}
if (pszSlash == NULL)
{
// Не наше окошко, выходим
gbInShutdown = TRUE;
return CERR_ATTACH_NO_CONWND;
}
}
if (!gbAlternativeAttach && !(gbAttachMode & am_DefTerm) && !gpSrv->dwRootProcess)
{
// В принципе, сюда мы можем попасть при запуске, например: "ConEmuC.exe /ADMIN /ROOT cmd"
// Но только не при запуске "из ConEmu" (т.к. будут установлены gpSrv->hGuiWnd, gnConEmuPID)
// Из батника убрал, покажем инфу тут
PrintVersion();
char szAutoRunMsg[128];
sprintf_c(szAutoRunMsg, "Starting attach autorun (NewWnd=%s)\n", gpSrv->bRequestNewGuiWnd ? "YES" : "NO");
_printf(szAutoRunMsg);
}
}
xf_check();
// Debugger or minidump requested?
// Switches ‘/DEBUGPID=PID1[,PID2[...]]’ to debug already running process
// or ‘/DEBUGEXE <your command line>’ or ‘/DEBUGTREE <your command line>’
// to start new process and debug it (and its children if ‘/DEBUGTREE’)
if (gpSrv->DbgInfo.bDebugProcess)
{
_ASSERTE(gnRunMode == RM_UNDEFINED);
// Run debugger thread and wait for its completion
int iDbgRc = RunDebugger();
return iDbgRc;
}
// Validate Сonsole (find it may be) or ChildGui process we need to attach into ConEmu window
if (((gnRunMode == RM_SERVER) || (gnRunMode == RM_AUTOATTACH))
&& (gbNoCreateProcess && gbAttachMode))
{
// Проверить процессы в консоли, подобрать тот, который будем считать "корневым"
int nChk = CheckAttachProcess();
if (nChk != 0)
return nChk;
gpszRunCmd = (wchar_t*)calloc(1,2);
if (!gpszRunCmd)
{
_printf("Can't allocate 1 wchar!\n");
return CERR_NOTENOUGHMEM1;
}
gpszRunCmd[0] = 0;
return 0;
}
xf_check();
// iRc is result of our ‘NextArg(&lsCmdLine,...)’
if (iRc != 0)
{
if (iRc == CERR_CMDLINEEMPTY)
{
Help();
_printf("\n\nParsing command line failed (/C argument not found):\n");
_wprintf(GetCommandLineW());
_printf("\n");
}
else
{
_printf("Parsing command line failed:\n");
_wprintf(asCmdLine);
_printf("\n");
}
return iRc;
}
if (gnRunMode == RM_UNDEFINED)
{
LogString(L"CERR_CARGUMENT: Parsing command line failed (/C argument not found)");
_printf("Parsing command line failed (/C argument not found):\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
xf_check();
// Prepare our environment and GUI window
if (gnRunMode == RM_SERVER)
{
// We need to reserve or start new ConEmu tab/window...
// Если уже известен HWND ConEmu (root window)
if (gpSrv->hGuiWnd)
{
DWORD nGuiPID = 0; GetWindowThreadProcessId(gpSrv->hGuiWnd, &nGuiPID);
DWORD nWrongValue = 0;
SetLastError(0);
LGSResult lgsRc = ReloadGuiSettings(NULL, &nWrongValue);
if (lgsRc < lgs_Succeeded)
{
wchar_t szLgsError[200], szLGS[80];
swprintf_c(szLGS, L"LGS=%u, Code=%u, GUI PID=%u, Srv PID=%u", lgsRc, GetLastError(), nGuiPID, GetCurrentProcessId());
switch (lgsRc)
{
case lgs_WrongVersion:
swprintf_c(szLgsError, L"Failed to load ConEmu info!\n"
L"Found ProtocolVer=%u but Required=%u.\n"
L"%s.\n"
L"Please update all ConEmu components!",
nWrongValue, (DWORD)CESERVER_REQ_VER, szLGS);
break;
case lgs_WrongSize:
swprintf_c(szLgsError, L"Failed to load ConEmu info!\n"
L"Found MapSize=%u but Required=%u."
L"%s.\n"
L"Please update all ConEmu components!",
nWrongValue, (DWORD)sizeof(ConEmuGuiMapping), szLGS);
break;
default:
swprintf_c(szLgsError, L"Failed to load ConEmu info!\n"
L"%s.\n"
L"Please update all ConEmu components!",
szLGS);
}
// Add log info
LogFunction(szLGS);
// Show user message
wchar_t szTitle[128];
swprintf_c(szTitle, L"ConEmuC[Srv]: PID=%u", GetCurrentProcessId());
MessageBox(NULL, szLgsError, szTitle, MB_ICONSTOP|MB_SYSTEMMODAL);
return CERR_WRONG_GUI_VERSION;
}
}
}
xf_check();
if (gnRunMode == RM_COMSPEC)
{
// New console was requested?
if (IsNewConsoleArg(lsCmdLine))
{
HWND hConWnd = ghConWnd, hConEmu = ghConEmuWnd;
if (!hConWnd)
{
// This may be ConEmuC started from WSL or connector
CEStr guiPid(GetEnvVar(ENV_CONEMUPID_VAR_W));
CEStr srvPid(GetEnvVar(ENV_CONEMUSERVERPID_VAR_W));
if (guiPid && srvPid)
{
DWORD GuiPID = wcstoul(guiPid, NULL, 10);
DWORD SrvPID = wcstoul(srvPid, NULL, 10);
ConEmuGuiMapping GuiMapping = {sizeof(GuiMapping)};
if (GuiPID && LoadGuiMapping(GuiPID, GuiMapping))
{
for (size_t i = 0; i < countof(GuiMapping.Consoles); ++i)
{
if (GuiMapping.Consoles[i].ServerPID == SrvPID)
{
hConWnd = GuiMapping.Consoles[i].Console;
hConEmu = GuiMapping.hGuiWnd;
break;
}
}
}
}
}
if (!hConWnd)
{
// Executed outside of ConEmu, impossible to continue
_ASSERTE(hConWnd != NULL);
}
else
{
xf_check();
// тогда обрабатываем
gpSrv->bNewConsole = TRUE;
// По идее, должен запускаться в табе ConEmu (в существующей консоли), но если нет
if (!hConEmu || !IsWindow(hConEmu))
{
// попытаться найти открытый ConEmu
hConEmu = FindWindowEx(NULL, NULL, VirtualConsoleClassMain, NULL);
if (hConEmu)
gbNonGuiMode = TRUE; // Чтобы не пытаться выполнить SendStopped (ибо некому)
}
int iNewConRc = CERR_RUNNEWCONSOLE;
// Query current environment
CEnvStrings strs(GetEnvironmentStringsW());
DWORD nCmdLen = lstrlen(lsCmdLine)+1;
CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_NEWCMD, sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_NEWCMD)+((nCmdLen+strs.mcch_Length)*sizeof(wchar_t)));
if (pIn)
{
pIn->NewCmd.hFromConWnd = hConWnd;
// hConWnd may differ from parent process, but ENV_CONEMUDRAW_VAR_W would be inherited
wchar_t* pszDcWnd = GetEnvVar(ENV_CONEMUDRAW_VAR_W);
if (pszDcWnd && (pszDcWnd[0] == L'0') && (pszDcWnd[1] == L'x'))
{
wchar_t* pszEnd = NULL;
pIn->NewCmd.hFromDcWnd.u = wcstoul(pszDcWnd+2, &pszEnd, 16);
}
SafeFree(pszDcWnd);
GetCurrentDirectory(countof(pIn->NewCmd.szCurDir), pIn->NewCmd.szCurDir);
pIn->NewCmd.SetCommand(lsCmdLine);
pIn->NewCmd.SetEnvStrings(strs.ms_Strings, strs.mcch_Length);
CESERVER_REQ* pOut = ExecuteGuiCmd(hConEmu, pIn, hConWnd);
if (pOut)
{
if (pOut->hdr.cbSize <= sizeof(pOut->hdr) || pOut->Data[0] == FALSE)
{
iNewConRc = CERR_RUNNEWCONSOLEFAILED;
}
ExecuteFreeResult(pOut);
}
else
{
_ASSERTE(pOut!=NULL);
iNewConRc = CERR_RUNNEWCONSOLEFAILED;
}
ExecuteFreeResult(pIn);
}
else
{
iNewConRc = CERR_NOTENOUGHMEM1;
}
DisableAutoConfirmExit();
return iNewConRc;
}
}
//pwszCopy = lsCmdLine;
//if ((iRc = NextArg(&pwszCopy, szArg)) != 0) {
// wprintf (L"Parsing command line failed:\n%s\n", lsCmdLine);
// return iRc;
//}
//pwszCopy = wcsrchr(szArg, L'\\'); if (!pwszCopy) pwszCopy = szArg;
//#pragma warning( push )
//#pragma warning(disable : 6400)
//if (lstrcmpiW(pwszCopy, L"cmd")==0 || lstrcmpiW(pwszCopy, L"cmd.exe")==0) {
// gbRunViaCmdExe = FALSE; // уже указан командный процессор, cmd.exe в начало добавлять не нужно
//}
//#pragma warning( pop )
//} else {
// gbRunViaCmdExe = FALSE; // командным процессором выступает сам ConEmuC (серверный режим)
}
LPCWSTR pszArguments4EnvVar = NULL;
if (gnRunMode == RM_COMSPEC && (!lsCmdLine || !*lsCmdLine))
{
if (gpSrv->bK)
{
gbRunViaCmdExe = TRUE;
}
else
{
// В фаре могут повесить пустую ассоциацию на маску
// *.ini -> "@" - тогда фар как бы ничего не делает при запуске этого файла, но ComSpec зовет...
gbNonGuiMode = TRUE;
DisableAutoConfirmExit();
return CERR_EMPTY_COMSPEC_CMDLINE;
}
}
else
{
BOOL bAlwaysConfirmExit = gbAlwaysConfirmExit, bAutoDisableConfirmExit = gbAutoDisableConfirmExit;
if (gnRunMode == RM_SERVER)
{
LogFunction(L"ProcessSetEnvCmd {set, title, chcp, etc.}");
// Console may be started as follows:
// "set PATH=C:\Program Files;%PATH%" & ... & cmd
// Supported commands:
// set abc=val
// "set PATH=C:\Program Files;%PATH%"
// chcp [utf8|ansi|oem|<cp_no>]
// title "Console init title"
if (!gpSetEnv)
gpSetEnv = new CProcessEnvCmd();
CStartEnvTitle setTitleVar(&gpszForcedTitle);
ProcessSetEnvCmd(lsCmdLine, gpSetEnv, &setTitleVar);
}
gpszCheck4NeedCmd = lsCmdLine; // Для отладки
gbRunViaCmdExe = IsNeedCmd((gnRunMode == RM_SERVER), lsCmdLine, szExeTest,
&pszArguments4EnvVar, &lbNeedCutStartEndQuot, &gbRootIsCmdExe, &bAlwaysConfirmExit, &bAutoDisableConfirmExit);
if (gnConfirmExitParm == 0)
{
gbAlwaysConfirmExit = bAlwaysConfirmExit;
gbAutoDisableConfirmExit = bAutoDisableConfirmExit;
}
}
#ifndef WIN64
// Команды вида: C:\Windows\SysNative\reg.exe Query "HKCU\Software\Far2"|find "Far"
// Для них нельзя отключать редиректор (wow.Disable()), иначе SysNative будет недоступен
CheckNeedSkipWowChange(lsCmdLine);
#endif
nCmdLine = lstrlenW(lsCmdLine);
if (!gbRunViaCmdExe)
{
nCmdLine += 1; // только место под 0
if (pszArguments4EnvVar && *szExeTest)
nCmdLine += lstrlen(szExeTest)+3;
}
else
{
gszComSpec[0] = 0;
if (!GetEnvironmentVariable(L"ComSpec", gszComSpec, MAX_PATH) || gszComSpec[0] == 0)
gszComSpec[0] = 0;
// ComSpec/ComSpecC не определен, используем cmd.exe
if (gszComSpec[0] == 0)
{
LPCWSTR pszFind = GetComspecFromEnvVar(gszComSpec, countof(gszComSpec));
if (!pszFind || !wcschr(pszFind, L'\\') || !FileExists(pszFind))
{
_ASSERTE("cmd.exe not found!");
_printf("Can't find cmd.exe!\n");
return CERR_CMDEXENOTFOUND;
}
}
nCmdLine += lstrlenW(gszComSpec)+15; // "/C", кавычки и возможный "/U"
}
size_t nCchLen = nCmdLine+1; // nCmdLine учитывает длину lsCmdLine + gszComSpec + еще чуть-чуть на "/C" и прочее
gpszRunCmd = (wchar_t*)calloc(nCchLen,sizeof(wchar_t));
if (!gpszRunCmd)
{
_printf("Can't allocate %i wchars!\n", (DWORD)nCmdLine);
return CERR_NOTENOUGHMEM1;
}
// это нужно для смены заголовка консоли. при необходимости COMSPEC впишем ниже, после смены
if (pszArguments4EnvVar && *szExeTest && !gbRunViaCmdExe)
{
gpszRunCmd[0] = L'"';
_wcscat_c(gpszRunCmd, nCchLen, szExeTest);
if (*pszArguments4EnvVar)
{
_wcscat_c(gpszRunCmd, nCchLen, L"\" ");
_wcscat_c(gpszRunCmd, nCchLen, pszArguments4EnvVar);
}
else
{
_wcscat_c(gpszRunCmd, nCchLen, L"\"");
}
}
else
{
_wcscpy_c(gpszRunCmd, nCchLen, lsCmdLine);
}
// !!! gpszRunCmd может поменяться ниже!
// ====
if (gbRunViaCmdExe)
{
// -- always quotate
gpszRunCmd[0] = L'"';
_wcscpy_c(gpszRunCmd+1, nCchLen-1, gszComSpec);
_wcscat_c(gpszRunCmd, nCchLen, gpSrv->bK ? L"\" /K " : L"\" /C ");
// Собственно, командная строка
_wcscat_c(gpszRunCmd, nCchLen, lsCmdLine);
}
else if (lbNeedCutStartEndQuot)
{
// ""c:\arc\7z.exe -?"" - не запустится!
_wcscpy_c(gpszRunCmd, nCchLen, lsCmdLine+1);
wchar_t *pszEndQ = gpszRunCmd + lstrlenW(gpszRunCmd) - 1;
_ASSERTE(pszEndQ && *pszEndQ == L'"');
if (pszEndQ && *pszEndQ == L'"') *pszEndQ = 0;
}
// Теперь выкусить и обработать "-new_console" / "-cur_console"
RConStartArgs args;
args.pszSpecialCmd = gpszRunCmd;
args.ProcessNewConArg();
args.pszSpecialCmd = NULL; // Чтобы не разрушилась память отведенная в gpszRunCmd
// Если указана рабочая папка
if (args.pszStartupDir && *args.pszStartupDir)
{
SetCurrentDirectory(args.pszStartupDir);
}
//
gbRunInBackgroundTab = (args.BackgroundTab == crb_On);
if (args.BufHeight == crb_On)
{
TODO("gcrBufferSize - и ширину буфера");
gnBufferHeight = args.nBufHeight;
gbParmBufSize = TRUE;
}
// DosBox?
if (args.ForceDosBox == crb_On)
{
gbUseDosBox = TRUE;
}
// Overwrite mode in Prompt?
if (args.OverwriteMode == crb_On)
{
gnConsoleModeFlags |= (ENABLE_INSERT_MODE << 16); // Mask
gnConsoleModeFlags &= ~ENABLE_INSERT_MODE; // Turn bit OFF
// Поскольку ключик указан через "-cur_console/-new_console"
// смену режима нужно сделать сразу, т.к. функа зовется только для сервера
ServerInitConsoleMode();
}
#ifdef _DEBUG
OutputDebugString(gpszRunCmd); OutputDebugString(L"\n");
#endif
UNREFERENCED_PARAMETER(pwszStartCmdLine);
_ASSERTE(pwszStartCmdLine==asCmdLine);
return 0;
}
// Проверить, что nPID это "ConEmuC.exe" или "ConEmuC64.exe"
bool IsMainServerPID(DWORD nPID)
{
PROCESSENTRY32 Info;
if (!GetProcessInfo(nPID, &Info))
return false;
if ((lstrcmpi(Info.szExeFile, L"ConEmuC.exe") == 0)
|| (lstrcmpi(Info.szExeFile, L"ConEmuC64.exe") == 0))
{
return true;
}
return false;
}
int ExitWaitForKey(DWORD vkKeys, LPCWSTR asConfirm, BOOL abNewLine, BOOL abDontShowConsole, DWORD anMaxTimeout /*= 0*/)
{
gbInExitWaitForKey = TRUE;
int nKeyPressed = -1;
//-- Don't exit on ANY key if -new_console:c1
//if (!vkKeys) vkKeys = VK_ESCAPE;
// Чтобы ошибку было нормально видно
if (!abDontShowConsole)
{
BOOL lbNeedVisible = FALSE;
if (!ghConWnd) ghConWnd = GetConEmuHWND(2);
if (ghConWnd) // Если консоль была скрыта
{
WARNING("Если GUI жив - отвечает на запросы SendMessageTimeout - показывать консоль не нужно. Не красиво получается");
if (!IsWindowVisible(ghConWnd))
{
BOOL lbGuiAlive = FALSE;
if (ghConEmuWndDC && !isConEmuTerminated())
{
// ConEmu will deal the situation?
// EmergencyShow annoys user if parent window was killed (InsideMode)
lbGuiAlive = TRUE;
}
else if (ghConEmuWnd && IsWindow(ghConEmuWnd))
{
DWORD_PTR dwLRc = 0;
if (SendMessageTimeout(ghConEmuWnd, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 1000, &dwLRc))
lbGuiAlive = TRUE;
}
if (!lbGuiAlive && !IsWindowVisible(ghConWnd))
{
lbNeedVisible = TRUE;
// не надо наверное... // поставить "стандартный" 80x25, или то, что было передано к ком.строке
//SMALL_RECT rcNil = {0}; SetConsoleSize(0, gcrVisibleSize, rcNil, ":Exiting");
//SetConsoleFontSizeTo(ghConWnd, 8, 12); // установим шрифт побольше
//apiShowWindow(ghConWnd, SW_SHOWNORMAL); // и покажем окошко
EmergencyShow(ghConWnd);
}
}
}
}
HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
// Сначала почистить буфер
INPUT_RECORD r = {0}; DWORD dwCount = 0;
DWORD nPreFlush = 0, nPostFlush = 0;
#ifdef _DEBUG
DWORD nPreQuit = 0;
#endif
GetNumberOfConsoleInputEvents(hIn, &nPreFlush);
FlushConsoleInputBuffer(hIn);
PRINT_COMSPEC(L"Finalizing. gbInShutdown=%i\n", gbInShutdown);
GetNumberOfConsoleInputEvents(hIn, &nPostFlush);
if (gbInShutdown)
goto wrap; // Event закрытия мог припоздниться
SetConsoleMode(hOut, ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT);
//
if (asConfirm && *asConfirm)
{
_wprintf(asConfirm);
}
DWORD nStartTick = GetTickCount(), nDelta = 0;
while (TRUE)
{
if (gbStopExitWaitForKey)
{
// Был вызван HandlerRoutine(CLOSE)
break;
}
// Allow exit by timeout
if (anMaxTimeout)
{
nDelta = GetTickCount() - nStartTick;
if (nDelta >= anMaxTimeout)
{
break;
}
}
// If server was connected to GUI, but we get here because
// root process was not attached to console yet (antivirus lags?)
if (gpSrv->ConnectInfo.bConnected)
{
TODO("It would be nice to check for new console processed started in console?");
}
if (!PeekConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &r, 1, &dwCount))
dwCount = 0;
if (!gbInExitWaitForKey)
{
if (gnRunMode == RM_SERVER)
{
int nCount = gpSrv->processes->nProcessCount;
if (nCount > 1)
{
// Теперь Peek, так что просто выходим
//// ! Процесс таки запустился, закрываться не будем. Вернуть событие в буфер!
//WriteConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &r, 1, &dwCount);
break;
}
}
if (gbInShutdown)
{
break;
}
}
if (dwCount)
{
#ifdef _DEBUG
GetNumberOfConsoleInputEvents(hIn, &nPreQuit);
#endif
// Avoid ConIn overflow, even if (vkKeys == 0)
if (ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &r, 1, &dwCount)
&& dwCount
&& vkKeys)
{
bool lbMatch = false;
if (r.EventType == KEY_EVENT && r.Event.KeyEvent.bKeyDown)
{
for (DWORD vk = vkKeys; !lbMatch && LOBYTE(vk); vk=vk>>8)
{
lbMatch = (r.Event.KeyEvent.wVirtualKeyCode == LOBYTE(vk));
}
}
if (lbMatch)
{
nKeyPressed = r.Event.KeyEvent.wVirtualKeyCode;
break;
}
}
}
Sleep(50);
}
//MessageBox(0,L"Debug message...............1",L"ConEmuC",0);
//int nCh = _getch();
if (abNewLine)
_printf("\n");
wrap:
#if defined(_DEBUG) && defined(SHOW_EXITWAITKEY_MSGBOX)
wchar_t szTitle[128];
swprintf_c(szTitle, L"ConEmuC[Srv]: PID=%u", GetCurrentProcessId());
if (!gbStopExitWaitForKey)
MessageBox(NULL, asConfirm ? asConfirm : L"???", szTitle, MB_ICONEXCLAMATION|MB_SYSTEMMODAL);
#endif
return nKeyPressed;
}
// Используется в режиме RM_APPLICATION, чтобы не тормозить основной поток (жалобы на замедление запуска программ из батников)
DWORD gnSendStartedThread = 0;
HANDLE ghSendStartedThread = NULL;
DWORD WINAPI SendStartedThreadProc(LPVOID lpParameter)
{
_ASSERTE(gnMainServerPID!=0 && gnMainServerPID!=GetCurrentProcessId() && "Main server PID must be determined!");
CESERVER_REQ *pIn = (CESERVER_REQ*)lpParameter;
_ASSERTE(pIn && (pIn->hdr.cbSize>=sizeof(pIn->hdr)) && (pIn->hdr.nCmd==CECMD_CMDSTARTSTOP));
// Сам результат не интересует
CESERVER_REQ *pSrvOut = ExecuteSrvCmd(gnMainServerPID, pIn, ghConWnd, TRUE/*async*/);
ExecuteFreeResult(pSrvOut);
ExecuteFreeResult(pIn);
return 0;
}
void SetTerminateEvent(SetTerminateEventPlace eFrom)
{
#ifdef DEBUG_ISSUE_623
_ASSERTE((eFrom == ste_ProcessCountChanged) && "Calling SetTerminateEvent");
#endif
if (!gTerminateEventPlace)
gTerminateEventPlace = eFrom;
SetEvent(ghExitQueryEvent);
}
bool isConEmuTerminated()
{
// HWND of our VirtualConsole
if (!ghConEmuWndDC)
{
_ASSERTE(FALSE && "ghConEmuWndDC is expected to be NOT NULL");
return false;
}
if (::IsWindow(ghConEmuWndDC))
{
// ConEmu is alive
return false;
}
//TODO: It would be better to check process presence via connected Pipe
//TODO: Same as in ConEmu, it must check server presence via pipe
// For now, don't annoy user with RealConsole if all processes were finished
if (gbInExitWaitForKey // We are waiting for Enter or Esc
&& (gpSrv->processes->nProcessCount <= 1) // No active processes are found in console (except our SrvPID)
)
{
// Let RealConsole remain invisible, ConEmu will deal the situation
return false;
}
// ConEmu was killed?
return true;
}
void SendStarted()
{
LogFunction(L"SendStarted");
WARNING("Подозрение, что слишком много вызовов при старте сервера. Неаккуратно");
static bool bSent = false;
if (bSent)
{
_ASSERTE(FALSE && "SendStarted repetition");
return; // отсылать только один раз
}
//crNewSize = gpSrv->sbi.dwSize;
//_ASSERTE(crNewSize.X>=MIN_CON_WIDTH && crNewSize.Y>=MIN_CON_HEIGHT);
HWND hConWnd = GetConEmuHWND(2);
if (!gnSelfPID)
{
_ASSERTE(gnSelfPID!=0);
gnSelfPID = GetCurrentProcessId();
}
if (!hConWnd)
{
// Это Detached консоль. Скорее всего запущен вместо COMSPEC
_ASSERTE(gnRunMode == RM_COMSPEC);
gbNonGuiMode = TRUE; // Не посылать ExecuteGuiCmd при выходе. Это не наша консоль
return;
}
_ASSERTE(hConWnd == ghConWnd);
ghConWnd = hConWnd;
DWORD nMainServerPID = 0, nAltServerPID = 0, nGuiPID = 0;
// Для ComSpec-а сразу можно проверить, а есть-ли сервер в этой консоли...
if ((gnRunMode != RM_AUTOATTACH) && (gnRunMode /*== RM_COMSPEC*/ > RM_SERVER))
{
MFileMapping<CESERVER_CONSOLE_MAPPING_HDR> ConsoleMap;
ConsoleMap.InitName(CECONMAPNAME, LODWORD(hConWnd)); //-V205
const CESERVER_CONSOLE_MAPPING_HDR* pConsoleInfo = ConsoleMap.Open();
if (!pConsoleInfo)
{
_ASSERTE((gnRunMode == RM_COMSPEC) && (ghConWnd && !ghConEmuWnd && IsWindowVisible(ghConWnd)) && "ConsoleMap was not initialized for AltServer/ComSpec");
}
else
{
nMainServerPID = pConsoleInfo->nServerPID;
nAltServerPID = pConsoleInfo->nAltServerPID;
nGuiPID = pConsoleInfo->nGuiPID;
if (pConsoleInfo->cbSize >= sizeof(CESERVER_CONSOLE_MAPPING_HDR))
{
if (pConsoleInfo->nLogLevel)
CreateLogSizeFile(pConsoleInfo->nLogLevel, pConsoleInfo);
}
//UnmapViewOfFile(pConsoleInfo);
ConsoleMap.CloseMap();
}
if (nMainServerPID == 0)
{
gbNonGuiMode = TRUE; // Не посылать ExecuteGuiCmd при выходе. Это не наша консоль
return; // Режим ComSpec, но сервера нет, соответственно, в GUI ничего посылать не нужно
}
}
else
{
nGuiPID = gnConEmuPID;
}
CESERVER_REQ *pIn = NULL, *pOut = NULL, *pSrvOut = NULL;
int nSize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_STARTSTOP);
pIn = ExecuteNewCmd(CECMD_CMDSTARTSTOP, nSize);
if (pIn)
{
if (!GetModuleFileName(NULL, pIn->StartStop.sModuleName, countof(pIn->StartStop.sModuleName)))
pIn->StartStop.sModuleName[0] = 0;
#ifdef _DEBUG
LPCWSTR pszFileName = PointToName(pIn->StartStop.sModuleName);
#endif
// Cmd/Srv режим начат
switch (gnRunMode)
{
case RM_SERVER:
pIn->StartStop.nStarted = sst_ServerStart;
IsKeyboardLayoutChanged(pIn->StartStop.dwKeybLayout);
break;
case RM_ALTSERVER:
pIn->StartStop.nStarted = sst_AltServerStart;
IsKeyboardLayoutChanged(pIn->StartStop.dwKeybLayout);
break;
case RM_COMSPEC:
pIn->StartStop.nParentFarPID = gpSrv->dwParentFarPID;
pIn->StartStop.nStarted = sst_ComspecStart;
break;
default:
pIn->StartStop.nStarted = sst_AppStart;
}
pIn->StartStop.hWnd = ghConWnd;
pIn->StartStop.dwPID = gnSelfPID;
pIn->StartStop.dwAID = gpSrv->dwGuiAID;
#ifdef _WIN64
pIn->StartStop.nImageBits = 64;
#else
pIn->StartStop.nImageBits = 32;
#endif
TODO("Ntvdm/DosBox -> 16");
//pIn->StartStop.dwInputTID = (gnRunMode == RM_SERVER) ? gpSrv->dwInputThreadId : 0;
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
pIn->StartStop.bUserIsAdmin = IsUserAdmin();
// Перед запуском 16бит приложений нужно подресайзить консоль...
gnImageSubsystem = 0;
LPCWSTR pszTemp = gpszRunCmd;
CEStr lsRoot;
if (gnRunMode == RM_SERVER && gpSrv->DbgInfo.bDebuggerActive)
{
// "Отладчик"
gnImageSubsystem = 0x101;
gbRootIsCmdExe = TRUE; // Чтобы буфер появился
}
else if (/*!gpszRunCmd &&*/ gbAttachFromFar)
{
// Аттач из фар-плагина
gnImageSubsystem = 0x100;
}
else if (gpszRunCmd && ((0 == NextArg(&pszTemp, lsRoot))))
{
PRINT_COMSPEC(L"Starting: <%s>", lsRoot);
MWow64Disable wow;
if (!gbSkipWowChange) wow.Disable();
DWORD nImageFileAttr = 0;
if (!GetImageSubsystem(lsRoot, gnImageSubsystem, gnImageBits, nImageFileAttr))
gnImageSubsystem = 0;
PRINT_COMSPEC(L", Subsystem: <%i>\n", gnImageSubsystem);
PRINT_COMSPEC(L" Args: %s\n", pszTemp);
}
else
{
GetImageSubsystem(gnImageSubsystem, gnImageBits);
}
pIn->StartStop.nSubSystem = gnImageSubsystem;
if ((gnImageSubsystem == IMAGE_SUBSYSTEM_DOS_EXECUTABLE) || (gbUseDosBox))
pIn->StartStop.nImageBits = 16;
else if (gnImageBits)
pIn->StartStop.nImageBits = gnImageBits;
pIn->StartStop.bRootIsCmdExe = gbRootIsCmdExe; //2009-09-14
// НЕ MyGet..., а то можем заблокироваться...
DWORD dwErr1 = 0;
BOOL lbRc1;
{
HANDLE hOut;
// Need to block all requests to output buffer in other threads
MSectionLockSimple csRead; csRead.Lock(&gpSrv->csReadConsoleInfo, LOCK_READOUTPUT_TIMEOUT);
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
hOut = (HANDLE)ghConOut;
else
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
lbRc1 = GetConsoleScreenBufferInfo(hOut, &pIn->StartStop.sbi);
if (!lbRc1)
dwErr1 = GetLastError();
else
pIn->StartStop.crMaxSize = MyGetLargestConsoleWindowSize(hOut);
}
// Если (для ComSpec) указан параметр "-cur_console:h<N>"
if (gbParmBufSize)
{
pIn->StartStop.bForceBufferHeight = TRUE;
TODO("gcrBufferSize - и ширину буфера");
pIn->StartStop.nForceBufferHeight = gnBufferHeight;
}
PRINT_COMSPEC(L"Starting %s mode (ExecuteGuiCmd started)\n", (RunMode==RM_SERVER) ? L"Server" : (RunMode==RM_ALTSERVER) ? L"AltServer" : L"ComSpec");
// CECMD_CMDSTARTSTOP
if (gnRunMode == RM_SERVER)
{
_ASSERTE(nGuiPID!=0 && gnRunMode==RM_SERVER);
pIn->StartStop.hServerProcessHandle = DuplicateProcessHandle(nGuiPID);
// послать CECMD_CMDSTARTSTOP/sst_ServerStart в GUI
pOut = ExecuteGuiCmd(ghConEmuWnd, pIn, ghConWnd);
}
else if (gnRunMode == RM_ALTSERVER)
{
// Подготовить хэндл своего процесса для MainServer
pIn->StartStop.hServerProcessHandle = DuplicateProcessHandle(nMainServerPID);
_ASSERTE(pIn->hdr.nCmd == CECMD_CMDSTARTSTOP);
pSrvOut = ExecuteSrvCmd(nMainServerPID, pIn, ghConWnd);
// MainServer должен был вернуть PID предыдущего AltServer (если он был)
if (pSrvOut && (pSrvOut->DataSize() >= sizeof(CESERVER_REQ_STARTSTOPRET)))
{
gpSrv->dwPrevAltServerPID = pSrvOut->StartStopRet.dwPrevAltServerPID;
}
else
{
_ASSERTE(pSrvOut && (pSrvOut->DataSize() >= sizeof(CESERVER_REQ_STARTSTOPRET)) && "StartStopRet.dwPrevAltServerPID expected");
}
}
else if (gnRunMode == RM_APPLICATION)
{
if (nMainServerPID == 0)
{
_ASSERTE(nMainServerPID && "Main Server must be detected already!");
}
else
{
// Сразу запомнить в глобальной переменной PID сервера
gnMainServerPID = nMainServerPID;
gnAltServerPID = nAltServerPID;
// чтобы не тормозить основной поток (жалобы на замедление запуска программ из батников)
ghSendStartedThread = apiCreateThread(SendStartedThreadProc, pIn, &gnSendStartedThread, "SendStartedThreadProc");
DWORD nErrCode = ghSendStartedThread ? 0 : GetLastError();
if (ghSendStartedThread == NULL)
{
_ASSERTE(ghSendStartedThread && L"SendStartedThreadProc creation failed!")
pSrvOut = ExecuteSrvCmd(nMainServerPID, pIn, ghConWnd);
}
else
{
pIn = NULL; // Освободит сама SendStartedThreadProc
}
UNREFERENCED_PARAMETER(nErrCode);
}
_ASSERTE(pOut == NULL); // нада
}
else
{
WARNING("TODO: Может быть это тоже в главный сервер посылать?");
_ASSERTE(nGuiPID!=0 && gnRunMode==RM_COMSPEC);
pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
// pOut должен содержать инфу, что должен сделать ComSpec
// при завершении (вернуть высоту буфера)
_ASSERTE(pOut!=NULL && "Prev buffer size must be returned!");
}
#if 0
if (nServerPID && (nServerPID != gnSelfPID))
{
_ASSERTE(nServerPID!=0 && (gnRunMode==RM_ALTSERVER || gnRunMode==RM_COMSPEC));
if ((gnRunMode == RM_ALTSERVER) || (gnRunMode == RM_SERVER))
{
pIn->StartStop.hServerProcessHandle = DuplicateProcessHandle(nServerPID);
}
WARNING("Optimize!!!");
WARNING("Async");
pSrvOut = ExecuteSrvCmd(nServerPID, pIn, ghConWnd);
if (gnRunMode == RM_ALTSERVER)
{
if (pSrvOut && (pSrvOut->DataSize() >= sizeof(CESERVER_REQ_STARTSTOPRET)))
{
gpSrv->dwPrevAltServerPID = pSrvOut->StartStopRet.dwPrevAltServerPID;
}
else
{
_ASSERTE(pSrvOut && (pSrvOut->DataSize() >= sizeof(CESERVER_REQ_STARTSTOPRET)));
}
}
}
else
{
_ASSERTE(gnRunMode==RM_SERVER && (nServerPID && (nServerPID != gnSelfPID)) && "nServerPID MUST be known already!");
}
#endif
#if 0
WARNING("Только для RM_SERVER. Все остальные должны докладываться главному серверу, а уж он разберется");
if (gnRunMode != RM_APPLICATION)
{
_ASSERTE(nGuiPID!=0 || gnRunMode==RM_SERVER);
if ((gnRunMode == RM_ALTSERVER) || (gnRunMode == RM_SERVER))
{
pIn->StartStop.hServerProcessHandle = DuplicateProcessHandle(nGuiPID);
}
WARNING("Optimize!!!");
pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
}
#endif
PRINT_COMSPEC(L"Starting %s mode (ExecuteGuiCmd finished)\n",(RunMode==RM_SERVER) ? L"Server" : (RunMode==RM_ALTSERVER) ? L"AltServer" : L"ComSpec");
if (pOut == NULL)
{
if (gnRunMode != RM_COMSPEC)
{
// для RM_APPLICATION будет pOut==NULL?
_ASSERTE(gnRunMode == RM_ALTSERVER);
}
else
{
gbNonGuiMode = TRUE; // Не посылать ExecuteGuiCmd при выходе. Это не наша консоль
}
}
else
{
bSent = true;
BOOL bAlreadyBufferHeight = pOut->StartStopRet.bWasBufferHeight;
DWORD nGuiPID = pOut->StartStopRet.dwPID;
SetConEmuWindows(pOut->StartStopRet.hWnd, pOut->StartStopRet.hWndDc, pOut->StartStopRet.hWndBack);
if (gpSrv)
{
_ASSERTE(gnConEmuPID == pOut->StartStopRet.dwPID);
gnConEmuPID = pOut->StartStopRet.dwPID;
#ifdef _DEBUG
DWORD dwPID; GetWindowThreadProcessId(ghConEmuWnd, &dwPID);
_ASSERTE(ghConEmuWnd==NULL || dwPID==gnConEmuPID);
#endif
}
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
{
if (gpSrv)
{
gpSrv->bWasDetached = FALSE;
}
else
{
_ASSERTE(gpSrv!=NULL);
}
}
UpdateConsoleMapHeader(L"SendStarted");
_ASSERTE(gnMainServerPID==0 || gnMainServerPID==pOut->StartStopRet.dwMainSrvPID || (gbAttachMode && gbAlienMode && (pOut->StartStopRet.dwMainSrvPID==gnSelfPID)));
gnMainServerPID = pOut->StartStopRet.dwMainSrvPID;
gnAltServerPID = pOut->StartStopRet.dwAltSrvPID;
AllowSetForegroundWindow(nGuiPID);
TODO("gnBufferHeight->gcrBufferSize");
TODO("gcrBufferSize - и ширину буфера");
gnBufferHeight = (SHORT)pOut->StartStopRet.nBufferHeight;
gbParmBufSize = TRUE;
// gcrBufferSize переименован в gcrVisibleSize
_ASSERTE(pOut->StartStopRet.nWidth && pOut->StartStopRet.nHeight);
gcrVisibleSize.X = (SHORT)pOut->StartStopRet.nWidth;
gcrVisibleSize.Y = (SHORT)pOut->StartStopRet.nHeight;
gbParmVisibleSize = TRUE;
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
{
// Если режим отладчика - принудительно включить прокрутку
if (gpSrv->DbgInfo.bDebuggerActive && !gnBufferHeight)
{
_ASSERTE(gnRunMode != RM_ALTSERVER);
gnBufferHeight = 9999;
}
SMALL_RECT rcNil = {0};
SetConsoleSize(gnBufferHeight, gcrVisibleSize, rcNil, "::SendStarted");
// Смена раскладки клавиатуры
if ((gnRunMode != RM_ALTSERVER) && pOut->StartStopRet.bNeedLangChange)
{
#ifndef INPUTLANGCHANGE_SYSCHARSET
#define INPUTLANGCHANGE_SYSCHARSET 0x0001
#endif
WPARAM wParam = INPUTLANGCHANGE_SYSCHARSET;
TODO("Проверить на x64, не будет ли проблем с 0xFFFFFFFFFFFFFFFFFFFFF");
LPARAM lParam = (LPARAM)(DWORD_PTR)pOut->StartStopRet.NewConsoleLang;
SendMessage(ghConWnd, WM_INPUTLANGCHANGEREQUEST, wParam, lParam);
}
}
else
{
// Может так получиться, что один COMSPEC запущен из другого.
// 100628 - неактуально. COMSPEC сбрасывается в cmd.exe
//if (bAlreadyBufferHeight)
// gpSrv->bNonGuiMode = TRUE; // Не посылать ExecuteGuiCmd при выходе - прокрутка должна остаться
gbWasBufferHeight = bAlreadyBufferHeight;
}
//nNewBufferHeight = ((DWORD*)(pOut->Data))[0];
//crNewSize.X = (SHORT)((DWORD*)(pOut->Data))[1];
//crNewSize.Y = (SHORT)((DWORD*)(pOut->Data))[2];
TODO("Если он запущен как COMSPEC - то к GUI никакого отношения иметь не должен");
//if (rNewWindow.Right >= crNewSize.X) // размер был уменьшен за счет полосы прокрутки
// rNewWindow.Right = crNewSize.X-1;
ExecuteFreeResult(pOut); //pOut = NULL;
//gnBufferHeight = nNewBufferHeight;
} // (pOut != NULL)
ExecuteFreeResult(pIn);
ExecuteFreeResult(pSrvOut);
}
}
CESERVER_REQ* SendStopped(CONSOLE_SCREEN_BUFFER_INFO* psbi)
{
LogFunction(L"SendStopped");
int iHookRc = -1;
if (gnRunMode == RM_ALTSERVER)
{
// сообщение о завершении будет посылать ConEmuHk.dll
HMODULE hHooks = GetModuleHandle(WIN3264TEST(L"ConEmuHk.dll",L"ConEmuHk64.dll"));
RequestLocalServer_t fRequestLocalServer = (RequestLocalServer_t)(hHooks ? GetProcAddress(hHooks, "RequestLocalServer") : NULL);
if (fRequestLocalServer)
{
RequestLocalServerParm Parm = {sizeof(Parm), slsf_AltServerStopped};
iHookRc = fRequestLocalServer(&Parm);
}
_ASSERTE((iHookRc == 0) && "SendStopped must be sent from ConEmuHk.dll");
return NULL;
}
if (ghSendStartedThread)
{
_ASSERTE(gnRunMode!=RM_COMSPEC);
// Чуть-чуть подождать, может все-таки успеет?
DWORD nWait = WaitForSingleObject(ghSendStartedThread, 50);
if (nWait == WAIT_TIMEOUT)
{
#ifndef __GNUC__
#pragma warning( push )
#pragma warning( disable : 6258 )
#endif
apiTerminateThread(ghSendStartedThread, 100); // раз корректно не хочет...
#ifndef __GNUC__
#pragma warning( pop )
#endif
}
HANDLE h = ghSendStartedThread; ghSendStartedThread = NULL;
CloseHandle(h);
}
else
{
_ASSERTE(gnRunMode!=RM_APPLICATION);
}
CESERVER_REQ *pIn = NULL, *pOut = NULL;
int nSize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_STARTSTOP);
pIn = ExecuteNewCmd(CECMD_CMDSTARTSTOP,nSize);
if (pIn)
{
switch (gnRunMode)
{
case RM_SERVER:
// По идее, sst_ServerStop не посылается
_ASSERTE(gnRunMode != RM_SERVER);
pIn->StartStop.nStarted = sst_ServerStop;
break;
case RM_ALTSERVER:
pIn->StartStop.nStarted = sst_AltServerStop;
break;
case RM_COMSPEC:
pIn->StartStop.nStarted = sst_ComspecStop;
pIn->StartStop.nOtherPID = gpSrv->dwRootProcess;
pIn->StartStop.nParentFarPID = gpSrv->dwParentFarPID;
break;
default:
pIn->StartStop.nStarted = sst_AppStop;
}
if (!GetModuleFileName(NULL, pIn->StartStop.sModuleName, countof(pIn->StartStop.sModuleName)))
pIn->StartStop.sModuleName[0] = 0;
pIn->StartStop.hWnd = ghConWnd;
pIn->StartStop.dwPID = gnSelfPID;
pIn->StartStop.nSubSystem = gnImageSubsystem;
if ((gnImageSubsystem == IMAGE_SUBSYSTEM_DOS_EXECUTABLE) || (gbUseDosBox))
pIn->StartStop.nImageBits = 16;
else if (gnImageBits)
pIn->StartStop.nImageBits = gnImageBits;
else
{
#ifdef _WIN64
pIn->StartStop.nImageBits = 64;
#else
pIn->StartStop.nImageBits = 32;
#endif
}
pIn->StartStop.bWasBufferHeight = gbWasBufferHeight;
if (psbi != NULL)
{
pIn->StartStop.sbi = *psbi;
}
else
{
// НЕ MyGet..., а то можем заблокироваться...
// ghConOut может быть NULL, если ошибка произошла во время разбора аргументов
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pIn->StartStop.sbi);
}
pIn->StartStop.crMaxSize = MyGetLargestConsoleWindowSize(GetStdHandle(STD_OUTPUT_HANDLE));
if ((gnRunMode == RM_APPLICATION) || (gnRunMode == RM_ALTSERVER))
{
if (gnMainServerPID == 0)
{
_ASSERTE(gnMainServerPID!=0 && "MainServer PID must be determined");
}
else
{
pIn->StartStop.nOtherPID = (gnRunMode == RM_ALTSERVER) ? gpSrv->dwPrevAltServerPID : 0;
pOut = ExecuteSrvCmd(gnMainServerPID, pIn, ghConWnd);
}
}
else
{
PRINT_COMSPEC(L"Finalizing comspec mode (ExecuteGuiCmd started)\n",0);
WARNING("Это надо бы совместить, но пока - нужно сначала передернуть главный сервер!");
pOut = ExecuteSrvCmd(gnMainServerPID, pIn, ghConWnd);
_ASSERTE(pOut!=NULL);
ExecuteFreeResult(pOut);
pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
PRINT_COMSPEC(L"Finalizing comspec mode (ExecuteGuiCmd finished)\n",0);
}
ExecuteFreeResult(pIn); pIn = NULL;
}
return pOut;
}
void CreateLogSizeFile(int nLevel, const CESERVER_CONSOLE_MAPPING_HDR* pConsoleInfo /*= NULL*/)
{
if (gpLogSize) return; // уже
DWORD dwErr = 0;
wchar_t szFile[MAX_PATH+64], *pszDot, *pszName, *pszDir = NULL;
wchar_t szDir[MAX_PATH+16];
if (!GetModuleFileName(NULL, szFile, MAX_PATH))
{
dwErr = GetLastError();
_printf("GetModuleFileName failed! ErrCode=0x%08X\n", dwErr);
return; // не удалось
}
pszName = (wchar_t*)PointToName(szFile);
if ((pszDot = wcsrchr(pszName, L'.')) == NULL)
{
_printf("wcsrchr failed!\n", 0, szFile); //-V576
return; // ошибка
}
if (pszName && (pszName > szFile))
{
// If we were started from ConEmu, the pConsoleInfo must be defined...
if (pConsoleInfo && pConsoleInfo->cbSize && pConsoleInfo->sConEmuExe[0])
{
lstrcpyn(szDir, pConsoleInfo->sConEmuExe, countof(szDir));
wchar_t* pszConEmuExe = (wchar_t*)PointToName(szDir);
if (pszConEmuExe)
{
*(pszConEmuExe-1) = 0;
pszDir = szDir;
}
}
if (!pszDir)
{
// if our exe lays in subfolder of ConEmu.exe?
*(pszName-1) = 0;
wcscpy_c(szDir, szFile);
pszDir = wcsrchr(szDir, L'\\');
if (!pszDir || (lstrcmpi(pszDir, L"\\ConEmu") != 0))
{
// Если ConEmuC.exe лежит НЕ в папке "ConEmu"
pszDir = szDir; // писать в текущую папку или на десктоп
}
else
{
// Иначе - попытаться найти соответствующий файл GUI
wchar_t szGuiFiles[] = L"\\ConEmu.exe" L"\0" L"\\ConEmu64.exe" L"\0\0";
if (FilesExists(szDir, szGuiFiles))
{
pszDir = szFile; // GUI лежит в той же папке, что и "сервер"
}
else
{
// На уровень выше?
*pszDir = 0;
if (FilesExists(szDir, szGuiFiles))
{
*pszDir = 0;
pszDir = szDir; // GUI лежит в родительской папке
}
else
{
pszDir = szFile; // GUI не нашли
}
}
}
}
}
gpLogSize = new MFileLogEx(L"ConEmu-srv", pszDir, GetCurrentProcessId());
if (!gpLogSize)
return;
dwErr = (DWORD)gpLogSize->CreateLogFile();
if (dwErr != 0)
{
_printf("Create console log file failed! ErrCode=0x%08X\n", dwErr, gpLogSize->GetLogFileName()); //-V576
_ASSERTE(FALSE && "gpLogSize->CreateLogFile failed");
SafeDelete(gpLogSize);
return;
}
gpLogSize->LogStartEnv(gpStartEnv);
LogSize(NULL, 0, "Startup");
}
bool LogString(LPCSTR asText)
{
if (!gpLogSize)
{
#ifdef _DEBUG
if (asText && *asText)
{
wchar_t* pszWide = lstrdupW(asText);
if (pszWide)
{
DEBUGSTR(pszWide);
free(pszWide);
}
}
#endif
return false;
}
char szInfo[255]; szInfo[0] = 0;
LPCSTR pszThread = " <unknown thread>";
DWORD dwId = GetCurrentThreadId();
if (dwId == gdwMainThreadId)
pszThread = "MainThread";
else if (gpSrv->CmdServer.IsPipeThread(dwId))
pszThread = "ServThread";
else if (dwId == gpSrv->dwRefreshThread)
pszThread = "RefrThread";
//#ifdef USE_WINEVENT_SRV
//else if (dwId == gpSrv->dwWinEventThread)
// pszThread = " WinEventThread";
//#endif
else if (gpSrv->InputServer.IsPipeThread(dwId))
pszThread = "InptThread";
else if (gpSrv->DataServer.IsPipeThread(dwId))
pszThread = "DataThread";
gpLogSize->LogString(asText, true, pszThread);
return true;
}
bool LogString(LPCWSTR asText)
{
if (!gpLogSize)
{
DEBUGSTR(asText);
return false;
}
wchar_t szInfo[255]; szInfo[0] = 0;
LPCWSTR pszThread = L" <unknown thread>";
DWORD dwId = GetCurrentThreadId();
if (dwId == gdwMainThreadId)
pszThread = L"MainThread";
else if (gpSrv->CmdServer.IsPipeThread(dwId))
pszThread = L"ServThread";
else if (dwId == gpSrv->dwRefreshThread)
pszThread = L"RefrThread";
else if (gpSrv->InputServer.IsPipeThread(dwId))
pszThread = L"InptThread";
else if (gpSrv->DataServer.IsPipeThread(dwId))
pszThread = L"DataThread";
gpLogSize->LogString(asText, true, pszThread);
return false;
}
void LogSize(const COORD* pcrSize, int newBufferHeight, LPCSTR pszLabel, bool bForceWriteLog)
{
if (!gpLogSize) return;
static DWORD nLastWriteTick = 0;
const DWORD TickDelta = 1000;
static LONG nSkipped = 0;
const LONG SkipDelta = 50;
static CONSOLE_SCREEN_BUFFER_INFO lsbiLast = {};
bool bWriteLog = false;
CONSOLE_SCREEN_BUFFER_INFO lsbi = {};
CONSOLE_CURSOR_INFO ci = {(DWORD)-1};
HANDLE hCon = ghConOut;
BOOL bHandleOK = (hCon != NULL);
if (!bHandleOK)
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
// В дебажный лог помещаем реальные значения
BOOL bConsoleOK = GetConsoleScreenBufferInfo(hCon, &lsbi);
char szInfo[400]; szInfo[0] = 0;
DWORD nErrCode = GetLastError();
// Cursor information (gh-718)
GetConsoleCursorInfo(hCon, &ci);
int fontX = 0, fontY = 0; wchar_t szFontName[LF_FACESIZE] = L""; char szFontInfo[60] = "<NA>";
if (apiGetConsoleFontSize(hCon, fontY, fontX, szFontName))
{
LPCSTR szState = "";
if (!g_LastSetConsoleFont.cbSize)
{
szState = " <?>";
}
else if ((g_LastSetConsoleFont.dwFontSize.Y != fontY)
|| (g_LastSetConsoleFont.dwFontSize.X != fontX))
{
// nConFontHeight/nConFontWidth не совпадает с получаемым,
// нужно организовать спец переменные в WConsole
_ASSERTE(g_LastSetConsoleFont.dwFontSize.Y==fontY && g_LastSetConsoleFont.dwFontSize.X==fontX);
szState = " <!>";
}
szFontInfo[0] = '`';
int iCvt = WideCharToMultiByte(CP_UTF8, 0, szFontName, -1, szFontInfo+1, 40, NULL, NULL);
if (iCvt <= 0) lstrcpynA(szFontInfo+1, "??", 40); else szFontInfo[iCvt+1] = 0;
int iLen = lstrlenA(szFontInfo); // result of WideCharToMultiByte is not suitable (contains trailing zero)
sprintf_c(szFontInfo+iLen, countof(szFontInfo)-iLen/*#SECURELEN*/, "` %ix%i%s",
fontY, fontX, szState);
}
#ifdef _DEBUG
wchar_t szClass[100] = L"";
GetClassName(ghConWnd, szClass, countof(szClass));
_ASSERTE(lstrcmp(szClass, L"ConsoleWindowClass")==0);
#endif
char szWindowInfo[40] = "<NA>"; RECT rcConsole = {};
if (GetWindowRect(ghConWnd, &rcConsole))
{
sprintf_c(szWindowInfo, "{(%i,%i) (%ix%i)}", rcConsole.left, rcConsole.top, LOGRECTSIZE(rcConsole));
}
if (pcrSize)
{
bWriteLog = true;
sprintf_c(szInfo, "CurSize={%i,%i,%i} ChangeTo={%i,%i,%i} Cursor={%i,%i,%i%%%c} ConRect={%i,%i}-{%i,%i} %s (skipped=%i) {%u:%u:x%X:%u} %s %s",
lsbi.dwSize.X, lsbi.srWindow.Bottom-lsbi.srWindow.Top+1, lsbi.dwSize.Y, pcrSize->X, pcrSize->Y, newBufferHeight,
lsbi.dwCursorPosition.X, lsbi.dwCursorPosition.Y, ci.dwSize, ci.bVisible ? L'V' : L'H',
lsbi.srWindow.Left, lsbi.srWindow.Top, lsbi.srWindow.Right, lsbi.srWindow.Bottom,
(pszLabel ? pszLabel : ""), nSkipped,
bConsoleOK, bHandleOK, (DWORD)(DWORD_PTR)hCon, nErrCode,
szWindowInfo, szFontInfo);
}
else
{
if (bForceWriteLog)
bWriteLog = true;
// Avoid numerous writing of equal lines to log
else if ((lsbi.dwSize.X != lsbiLast.dwSize.X) || (lsbi.dwSize.Y != lsbiLast.dwSize.Y))
bWriteLog = true;
else if (((GetTickCount() - nLastWriteTick) >= TickDelta) || (nSkipped >= SkipDelta))
bWriteLog = true;
sprintf_c(szInfo, "CurSize={%i,%i,%i} Cursor={%i,%i,%i%%%c} ConRect={%i,%i}-{%i,%i} %s (skipped=%i) {%u:%u:x%X:%u} %s %s",
lsbi.dwSize.X, lsbi.srWindow.Bottom-lsbi.srWindow.Top+1, lsbi.dwSize.Y,
lsbi.dwCursorPosition.X, lsbi.dwCursorPosition.Y, ci.dwSize, ci.bVisible ? L'V' : L'H',
lsbi.srWindow.Left, lsbi.srWindow.Top, lsbi.srWindow.Right, lsbi.srWindow.Bottom,
(pszLabel ? pszLabel : ""), nSkipped,
bConsoleOK, bHandleOK, (DWORD)(DWORD_PTR)hCon, nErrCode,
szWindowInfo, szFontInfo);
}
lsbiLast = lsbi;
if (!bWriteLog)
{
InterlockedIncrement(&nSkipped);
}
else
{
nSkipped = 0;
LogFunction(szInfo);
nLastWriteTick = GetTickCount();
}
}
void LogModeChange(LPCWSTR asName, DWORD oldVal, DWORD newVal)
{
if (!gpLogSize) return;
LPCWSTR pszLabel = asName ? asName : L"???";
CEStr lsInfo;
INT_PTR cchLen = lstrlen(pszLabel) + 80;
swprintf_c(lsInfo.GetBuffer(cchLen), cchLen/*#SECURELEN*/, L"Mode %s changed: old=x%04X new=x%04X", pszLabel, oldVal, newVal);
LogString(lsInfo);
}
int CLogFunction::m_FnLevel = 0; // Simple, without per-thread devision
CLogFunction::CLogFunction() : mb_Logged(false)
{
}
CLogFunction::CLogFunction(const char* asFnName) : mb_Logged(false)
{
int nLen = MultiByteToWideChar(CP_ACP, 0, asFnName, -1, NULL, 0);
wchar_t sBuf[80] = L"";
wchar_t *pszBuf = NULL;
if (nLen >= 80)
pszBuf = (wchar_t*)calloc(nLen+1,sizeof(*pszBuf));
else
pszBuf = sBuf;
MultiByteToWideChar(CP_ACP, 0, asFnName, -1, pszBuf, nLen+1);
DoLogFunction(pszBuf);
if (pszBuf != sBuf)
SafeFree(pszBuf);
}
CLogFunction::CLogFunction(const wchar_t* asFnName) : mb_Logged(false)
{
DoLogFunction(asFnName);
}
void CLogFunction::DoLogFunction(const wchar_t* asFnName)
{
if (mb_Logged)
return;
LONG lLevel = InterlockedIncrement((LONG*)&m_FnLevel);
mb_Logged = true;
if (!gpLogSize) return;
if (lLevel > 20) lLevel = 20;
wchar_t cFnInfo[120];
wchar_t* pc = cFnInfo;
for (LONG l = 1; l < lLevel; l++)
{
*(pc++) = L' '; *(pc++) = L' '; *(pc++) = L' ';
}
*pc = 0;
INT_PTR nPrefix = (pc - cFnInfo);
INT_PTR nFnLen = lstrlen(asFnName);
if (nFnLen < ((INT_PTR)countof(cFnInfo) - nPrefix))
{
lstrcpyn(pc, asFnName, countof(cFnInfo) - (pc - cFnInfo));
LogString(cFnInfo);
}
else
{
wchar_t* pszMrg = lstrmerge(cFnInfo, asFnName);
LogString(pszMrg);
SafeFree(pszMrg);
}
}
CLogFunction::~CLogFunction()
{
if (!mb_Logged)
return;
InterlockedDecrement((LONG*)&m_FnLevel);
}
int CALLBACK FontEnumProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam)
{
if ((FontType & TRUETYPE_FONTTYPE) == TRUETYPE_FONTTYPE)
{
// OK, подходит
wcscpy_c(gpSrv->szConsoleFont, lpelfe->elfLogFont.lfFaceName);
return 0;
}
return TRUE; // ищем следующий фонт
}
static void UndoConsoleWindowZoom()
{
BOOL lbRc = FALSE;
// Если юзер случайно нажал максимизацию, когда консольное окно видимо - ничего хорошего не будет
if (IsZoomed(ghConWnd))
{
SendMessage(ghConWnd, WM_SYSCOMMAND, SC_RESTORE, 0);
DWORD dwStartTick = GetTickCount();
do
{
Sleep(20); // подождем чуть, но не больше секунды
}
while (IsZoomed(ghConWnd) && (GetTickCount()-dwStartTick)<=1000);
Sleep(20); // и еще чуть-чуть, чтобы консоль прочухалась
// Теперь нужно вернуть (вдруг он изменился) размер буфера консоли
// Если этого не сделать - размер консоли нельзя УМЕНЬШИТЬ
RECT rcConPos;
GetWindowRect(ghConWnd, &rcConPos);
MoveWindow(ghConWnd, rcConPos.left, rcConPos.top, 1, 1, 1);
TODO("Horizontal scroll");
if (gnBufferHeight == 0)
{
//specified width and height cannot be less than the width and height of the console screen buffer's window
lbRc = SetConsoleScreenBufferSize(ghConOut, gcrVisibleSize);
}
else
{
// ресайз для BufferHeight
COORD crHeight = {gcrVisibleSize.X, gnBufferHeight};
MoveWindow(ghConWnd, rcConPos.left, rcConPos.top, 1, 1, 1);
lbRc = SetConsoleScreenBufferSize(ghConOut, crHeight); // а не crNewSize - там "оконные" размеры
}
// И вернуть тот видимый прямоугольник, который был получен в последний раз (успешный раз)
lbRc = SetConsoleWindowInfo(ghConOut, TRUE, &gpSrv->sbi.srWindow);
}
UNREFERENCED_PARAMETER(lbRc);
}
bool static NeedLegacyCursorCorrection()
{
static bool bNeedCorrection = false, bChecked = false;
if (!bChecked)
{
// gh-1051: In NON DBCS systems there are cursor problems too (Win10 stable build 15063 or higher)
if (IsWin10() && !IsWinDBCS() && !IsWin10LegacyConsole())
{
OSVERSIONINFOEXW osvi = { sizeof(osvi), 10, 0, 15063 };
DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(VerSetConditionMask(0,
VER_MAJORVERSION, VER_GREATER_EQUAL),
VER_MINORVERSION, VER_GREATER_EQUAL),
VER_BUILDNUMBER, VER_GREATER_EQUAL);
BOOL ibIsWin = _VerifyVersionInfo(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER, dwlConditionMask);
if (ibIsWin)
{
bNeedCorrection = true;
}
}
bChecked = true;
}
return bNeedCorrection;
}
// TODO: Optimize - combine ReadConsoleData/ReadConsoleInfo
void static CorrectDBCSCursorPosition(HANDLE ahConOut, CONSOLE_SCREEN_BUFFER_INFO& csbi)
{
if (csbi.dwSize.X <= 0 || csbi.dwCursorPosition.X <= 0)
return;
// Issue 577: Chinese display error on Chinese
// -- GetConsoleScreenBufferInfo returns DBCS cursor coordinates, but we require wchar_t !!!
if (!IsConsoleDoubleCellCP()
// gh-1057: In NON DBCS systems there are cursor problems too (Win10 stable build 15063)
&& !NeedLegacyCursorCorrection())
return;
// The correction process
{
CHAR Chars[200];
LONG cchMax = countof(Chars);
LPSTR pChars = (csbi.dwCursorPosition.X <= cchMax) ? Chars : (LPSTR)calloc(csbi.dwCursorPosition.X, sizeof(*pChars));
if (pChars)
cchMax = csbi.dwCursorPosition.X;
else
pChars = Chars; // memory allocation fail? try part of line?
COORD crRead = {0, csbi.dwCursorPosition.Y};
// gh-1501: Windows 10 CJK version set COMMON_LVB_*_BYTE even for SOME non-ASCII characters (e.g. Greek "Α", Russian "Я", etc.)
#if 0
//120830 - DBCS uses 2 cells per hieroglyph
// TODO: Optimize
DWORD nRead = 0;
BOOL bRead = NeedLegacyCursorCorrection() ? FALSE : ReadConsoleOutputCharacterA(ahConOut, pChars, cchMax, crRead, &nRead);
// ReadConsoleOutputCharacterA may return "???" instead of DBCS codes in Non-DBCS systems
if (bRead && (nRead == cchMax))
{
_ASSERTE(nRead==cchMax);
int nXShift = 0;
LPSTR p = pChars, pEnd = pChars+nRead;
while (p < pEnd)
{
if (IsDBCSLeadByte(*p))
{
nXShift++;
p++;
_ASSERTE(p < pEnd);
}
p++;
}
_ASSERTE(nXShift <= csbi.dwCursorPosition.X);
csbi.dwCursorPosition.X = std::max(0,(csbi.dwCursorPosition.X - nXShift));
}
else if (IsWin10() && (NeedLegacyCursorCorrection() || (GetConsoleOutputCP() == CP_UTF8)))
#endif
{
// Temporary workaround for conhost bug!
CHAR_INFO CharsEx[200];
CHAR_INFO* pCharsEx = (cchMax <= countof(CharsEx)) ? CharsEx
: (CHAR_INFO*)calloc(cchMax, sizeof(*pCharsEx));
if (pCharsEx)
{
COORD bufSize = {cchMax, 1}; COORD bufCoord = {0,0};
SMALL_RECT rgn = MakeSmallRect(0, csbi.dwCursorPosition.Y, cchMax-1, csbi.dwCursorPosition.Y);
BOOL bRead = ReadConsoleOutputW(ahConOut, pCharsEx, bufSize, bufCoord, &rgn);
if (bRead)
{
int nXShift = 0;
CHAR_INFO *p = pCharsEx, *pEnd = pCharsEx+cchMax;
// gh-1206: correct position after "こんばんはGood Evening"
while (p < pEnd)
{
if (!(p->Attributes & COMMON_LVB_TRAILING_BYTE)
/*&& get_wcwidth(p->Char.UnicodeChar) == 2*/)
{
_ASSERTE(p < pEnd);
if (((p + 1) < pEnd)
&& (p->Attributes & COMMON_LVB_LEADING_BYTE)
&& ((p+1)->Attributes & COMMON_LVB_TRAILING_BYTE)
&& (p->Char.UnicodeChar == (p+1)->Char.UnicodeChar))
{
p++; nXShift++;
}
_ASSERTE(p < pEnd);
}
p++;
}
_ASSERTE(nXShift <= csbi.dwCursorPosition.X);
csbi.dwCursorPosition.X = std::max<int>(0, (csbi.dwCursorPosition.X - nXShift));
if (pCharsEx != CharsEx)
free(pCharsEx);
}
}
}
if (pChars != Chars)
free(pChars);
}
}
/**
Reload current console palette, IF it WAS NOT specified explicitly before
@param ahConOut << (HANDLE)ghConOut
@result true if palette was successfully retrieved
**/
bool MyLoadConsolePalette(HANDLE ahConOut, CESERVER_CONSOLE_PALETTE& Palette)
{
bool bRc = false;
if (gpSrv->ConsolePalette.bPalletteLoaded)
{
Palette = gpSrv->ConsolePalette;
bRc = true;
}
else
{
Palette.bPalletteLoaded = false;
}
CONSOLE_SCREEN_BUFFER_INFO sbi = {};
MY_CONSOLE_SCREEN_BUFFER_INFOEX sbi_ex = {sizeof(sbi_ex)};
if (apiGetConsoleScreenBufferInfoEx(ahConOut, &sbi_ex))
{
Palette.wAttributes = sbi_ex.wAttributes;
Palette.wPopupAttributes = sbi_ex.wPopupAttributes;
if (!bRc)
{
_ASSERTE(sizeof(Palette.ColorTable) == sizeof(sbi_ex.ColorTable));
memmove(Palette.ColorTable, sbi_ex.ColorTable, sizeof(Palette.ColorTable));
// Store for future use?
// -- gpSrv->ConsolePalette = Palette;
bRc = true;
}
}
else if (GetConsoleScreenBufferInfo(ahConOut, &sbi))
{
Palette.wAttributes = Palette.wPopupAttributes = sbi.wAttributes;
// Load palette from registry?
}
return bRc;
}
WARNING("Use MyGetConsoleScreenBufferInfo instead of GetConsoleScreenBufferInfo");
// Действует аналогично функции WinApi (GetConsoleScreenBufferInfo), но в режиме сервера:
// 1. запрещает (то есть отменяет) максимизацию консольного окна
// 2. корректирует srWindow: сбрасывает горизонтальную прокрутку,
// а если не обнаружен "буферный режим" - то и вертикальную.
BOOL MyGetConsoleScreenBufferInfo(HANDLE ahConOut, PCONSOLE_SCREEN_BUFFER_INFO apsc)
{
BOOL lbRc = FALSE, lbSetRc = TRUE;
DWORD nErrCode = 0;
// ComSpec окно менять НЕ ДОЛЖЕН!
if ((gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER)
&& ghConEmuWnd && IsWindow(ghConEmuWnd))
{
// Если юзер случайно нажал максимизацию, когда консольное окно видимо - ничего хорошего не будет
if (IsZoomed(ghConWnd))
{
UndoConsoleWindowZoom();
}
}
SMALL_RECT srRealWindow = {};
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
lbRc = GetConsoleScreenBufferInfo(ahConOut, &csbi);
if (!lbRc)
{
nErrCode = GetLastError();
if (gpLogSize) LogSize(NULL, 0, ":MyGetConsoleScreenBufferInfo(FAIL)");
_ASSERTE(FALSE && "GetConsoleScreenBufferInfo failed, conhost was destroyed?");
goto wrap;
}
if ((csbi.dwSize.X <= 0)
|| (csbi.dwSize.Y <= 0)
|| (csbi.dwSize.Y > LONGOUTPUTHEIGHT_MAX)
)
{
nErrCode = GetLastError();
if (gpLogSize) LogSize(NULL, 0, ":MyGetConsoleScreenBufferInfo(dwSize)");
_ASSERTE(FALSE && "GetConsoleScreenBufferInfo failed, conhost was destroyed?");
goto wrap;
}
if (csbi.srWindow.Left < 0 || csbi.srWindow.Top < 0 || csbi.srWindow.Right < csbi.srWindow.Left || csbi.srWindow.Bottom < csbi.srWindow.Top)
{
nErrCode = GetLastError();
if (gpLogSize) LogSize(NULL, 0, ":MyGetConsoleScreenBufferInfo(srWindow)");
_ASSERTE(FALSE && "GetConsoleScreenBufferInfo failed, Invalid srWindow coordinates");
goto wrap;
}
srRealWindow = csbi.srWindow;
// Issue 373: wmic (Horizontal buffer)
{
TODO("Его надо и из ConEmu обновлять");
if (csbi.dwSize.X && (gnBufferWidth != csbi.dwSize.X))
gnBufferWidth = csbi.dwSize.X;
else if (gnBufferWidth == (csbi.srWindow.Right - csbi.srWindow.Left + 1))
gnBufferWidth = 0;
}
// CONSOLE_FULLSCREEN/*1*/ or CONSOLE_FULLSCREEN_HARDWARE/*2*/
if (pfnGetConsoleDisplayMode && pfnGetConsoleDisplayMode(&gpSrv->dwDisplayMode))
{
// The bug of Windows 10 b9879
if ((gnOsVer == 0x0604) && (gOSVer.dwBuildNumber == 9879))
gpSrv->dwDisplayMode = 0;
if (gpSrv->dwDisplayMode & CONSOLE_FULLSCREEN_HARDWARE)
{
// While in hardware fullscreen - srWindow still shows window region
// as it can be, if returned in GUI mode (I suppose)
//_ASSERTE(!csbi.srWindow.Left && !csbi.srWindow.Top);
csbi.dwSize.X = csbi.srWindow.Right+1-csbi.srWindow.Left;
csbi.dwSize.Y = csbi.srWindow.Bottom+1+csbi.srWindow.Top;
// Log that change
if (gpLogSize)
{
char szLabel[80];
sprintf_c(szLabel, "CONSOLE_FULLSCREEN_HARDWARE{x%08X}", gpSrv->dwDisplayMode);
LogSize(&csbi.dwSize, 0, szLabel);
}
}
}
//
_ASSERTE((csbi.srWindow.Bottom-csbi.srWindow.Top)<200);
// ComSpec окно менять НЕ ДОЛЖЕН!
// ??? Приложениям запрещено менять размер видимой области.
// ??? Размер буфера - могут менять, но не менее чем текущая видимая область
if ((gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER) && gpSrv)
{
// Если мы НЕ в ресайзе, проверить максимально допустимый размер консоли
if (!gpSrv->nRequestChangeSize && (gpSrv->crReqSizeNewSize.X > 0) && (gpSrv->crReqSizeNewSize.Y > 0))
{
COORD crMax = MyGetLargestConsoleWindowSize(ghConOut);
// Это может случиться, если пользователь резко уменьшил разрешение экрана
// ??? Польза здесь сомнительная
if (crMax.X > 0 && crMax.X < gpSrv->crReqSizeNewSize.X)
{
gpSrv->crReqSizeNewSize.X = crMax.X;
TODO("Обновить gcrVisibleSize");
}
if (crMax.Y > 0 && crMax.Y < gpSrv->crReqSizeNewSize.Y)
{
gpSrv->crReqSizeNewSize.Y = crMax.Y;
TODO("Обновить gcrVisibleSize");
}
}
}
// Issue 577: Chinese display error on Chinese
// -- GetConsoleScreenBufferInfo возвращает координаты курсора в DBCS, а нам нужен wchar_t !!!
if (csbi.dwSize.X && csbi.dwCursorPosition.X)
{
CorrectDBCSCursorPosition(ahConOut, csbi);
}
// Блокировка видимой области, TopLeft задается из GUI
if ((gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER) && gpSrv)
{
// Коррекция srWindow
if (gpSrv->TopLeft.isLocked())
{
SHORT nWidth = (csbi.srWindow.Right - csbi.srWindow.Left + 1);
SHORT nHeight = (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
if (gpSrv->TopLeft.x >= 0)
{
csbi.srWindow.Right = std::min<int>(csbi.dwSize.X, gpSrv->TopLeft.x + nWidth) - 1;
csbi.srWindow.Left = std::max<int>(0, csbi.srWindow.Right - nWidth + 1);
}
if (gpSrv->TopLeft.y >= 0)
{
csbi.srWindow.Bottom = std::min<int>(csbi.dwSize.Y, gpSrv->TopLeft.y+nHeight) - 1;
csbi.srWindow.Top = std::max<int>(0, csbi.srWindow.Bottom-nHeight+1);
}
}
// Eсли
// a) в прошлый раз курсор БЫЛ видим, а сейчас нет, И
// b) TopLeft не был изменен с тех пор (GUI не прокручивали)
// Это значит, что в консоли, например, нажали Enter в prompt
// или приложение продолжает вывод в консоль, в общем,
// содержимое консоли прокручивается,
// и то же самое нужно сделать в GUI
if (gpSrv->pConsole && gpSrv->TopLeft.isLocked())
{
// Был видим в той области, которая ушла в GUI
if (CoordInSmallRect(gpSrv->pConsole->ConState.sbi.dwCursorPosition, gpSrv->pConsole->ConState.sbi.srWindow)
// и видим сейчас в RealConsole
&& CoordInSmallRect(csbi.dwCursorPosition, srRealWindow)
// но стал НЕ видим в скорректированном (по TopLeft) прямоугольнике
&& !CoordInSmallRect(csbi.dwCursorPosition, csbi.srWindow)
// И TopLeft в GUI не менялся
&& gpSrv->TopLeft.Equal(gpSrv->pConsole->ConState.TopLeft))
{
// Сбросить блокировку и вернуть реальное положение в консоли
gpSrv->TopLeft.Reset();
csbi.srWindow = srRealWindow;
}
}
if (gpSrv->pConsole)
{
gpSrv->pConsole->ConState.TopLeft = gpSrv->TopLeft;
gpSrv->pConsole->ConState.srRealWindow = srRealWindow;
}
}
wrap:
if (apsc)
*apsc = csbi;
// Возвращаем (возможно) скорректированные данные
UNREFERENCED_PARAMETER(nErrCode);
return lbRc;
}
static bool AdaptConsoleFontSize(const COORD& crNewSize)
{
bool lbRc = true;
char szLogInfo[128];
// Minimum console size
int curSizeY = -1, curSizeX = -1;
wchar_t sFontName[LF_FACESIZE] = L"";
bool bCanChangeFontSize = false; // Vista+ only
if (apiGetConsoleFontSize(ghConOut, curSizeY, curSizeX, sFontName) && curSizeY && curSizeX)
{
bCanChangeFontSize = true;
int nMinY = GetSystemMetrics(SM_CYMIN) - GetSystemMetrics(SM_CYSIZEFRAME) - GetSystemMetrics(SM_CYCAPTION);
int nMinX = GetSystemMetrics(SM_CXMIN) - 2*GetSystemMetrics(SM_CXSIZEFRAME);
if ((nMinX > 0) && (nMinY > 0))
{
// Теперь прикинуть, какой размер шрифта нам нужен
int minSizeY = (nMinY / curSizeY);
int minSizeX = (nMinX / curSizeX);
if ((minSizeX > crNewSize.X) || (minSizeY > crNewSize.Y))
{
if (gpLogSize)
{
sprintf_c(szLogInfo, "Need to reduce minSize. Cur={%i,%i}, Req={%i,%i}", minSizeX, minSizeY, crNewSize.X, crNewSize.Y);
LogString(szLogInfo);
}
apiFixFontSizeForBufferSize(ghConOut, crNewSize, szLogInfo, countof(szLogInfo));
LogString(szLogInfo);
apiGetConsoleFontSize(ghConOut, curSizeY, curSizeX, sFontName);
}
}
if (gpLogSize)
{
sprintf_c(szLogInfo, "Console font size H=%i W=%i N=", curSizeY, curSizeX);
int nLen = lstrlenA(szLogInfo);
WideCharToMultiByte(CP_UTF8, 0, sFontName, -1, szLogInfo+nLen, countof(szLogInfo)-nLen, NULL, NULL);
LogFunction(szLogInfo);
}
}
else
{
LogFunction(L"Function GetConsoleFontSize is not available");
}
RECT rcConPos = {0};
COORD crMax = MyGetLargestConsoleWindowSize(ghConOut);
// Если размер превышает допустимый - лучше ничего не делать,
// иначе получается неприятный эффект при попытке AltEnter:
// размер окна становится сильно больше чем был, но FullScreen НЕ включается
//if (crMax.X && crNewSize.X > crMax.X)
// crNewSize.X = crMax.X;
//if (crMax.Y && crNewSize.Y > crMax.Y)
// crNewSize.Y = crMax.Y;
if ((crMax.X && crNewSize.X > crMax.X)
|| (crMax.Y && crNewSize.Y > crMax.Y))
{
if (bCanChangeFontSize)
{
BOOL bChangeRc = apiFixFontSizeForBufferSize(ghConOut, crNewSize, szLogInfo, countof(szLogInfo));
LogString(szLogInfo);
if (bChangeRc)
{
crMax = MyGetLargestConsoleWindowSize(ghConOut);
if (gpLogSize)
{
sprintf_c(szLogInfo, "Largest console size is {%i,%i}", crMax.X, crMax.Y);
LogString(szLogInfo);
}
}
if (!bChangeRc
|| (crMax.X && crNewSize.X > crMax.X)
|| (crMax.Y && crNewSize.Y > crMax.Y))
{
lbRc = false;
LogString("Change console size skipped: can't adapt font");
goto wrap;
}
}
else
{
LogString("Change console size skipped: too large");
lbRc = false;
goto wrap;
}
}
wrap:
return lbRc;
}
// No buffer (scrolling) in the console
// По идее, это только для приложений которые сами меняют высоту буфера
// для работы в "полноэкранном" режиме, типа Far 1.7x или Far 2+ без ключа /w
static bool ApplyConsoleSizeSimple(const COORD& crNewSize, const CONSOLE_SCREEN_BUFFER_INFO& csbi, DWORD& dwErr, bool bForceWriteLog)
{
bool lbRc = true;
dwErr = 0;
DEBUGSTRSIZE(L"SetConsoleSize: ApplyConsoleSizeSimple started");
bool lbNeedChange = (csbi.dwSize.X != crNewSize.X) || (csbi.dwSize.Y != crNewSize.Y)
|| ((csbi.srWindow.Right - csbi.srWindow.Left + 1) != crNewSize.X)
|| ((csbi.srWindow.Bottom - csbi.srWindow.Top + 1) != crNewSize.Y);
RECT rcConPos = {};
GetWindowRect(ghConWnd, &rcConPos);
SMALL_RECT rNewRect = {};
#ifdef _DEBUG
if (!lbNeedChange)
{
int nDbg = 0;
}
#endif
if (lbNeedChange)
{
// Если этого не сделать - размер консоли нельзя УМЕНЬШИТЬ
if (crNewSize.X <= (csbi.srWindow.Right-csbi.srWindow.Left) || crNewSize.Y <= (csbi.srWindow.Bottom-csbi.srWindow.Top))
{
rNewRect.Left = 0; rNewRect.Top = 0;
rNewRect.Right = std::min<int>((crNewSize.X - 1), (csbi.srWindow.Right - csbi.srWindow.Left));
rNewRect.Bottom = std::min<int>((crNewSize.Y - 1), (csbi.srWindow.Bottom - csbi.srWindow.Top));
if (!SetConsoleWindowInfo(ghConOut, TRUE, &rNewRect))
{
// Last chance to shrink visible area of the console if ConApi was failed
MoveWindow(ghConWnd, rcConPos.left, rcConPos.top, 1, 1, 1);
}
}
//specified width and height cannot be less than the width and height of the console screen buffer's window
if (!SetConsoleScreenBufferSize(ghConOut, crNewSize))
{
lbRc = false;
dwErr = GetLastError();
}
//TODO: а если правый нижний край вылезет за пределы экрана?
rNewRect.Left = 0; rNewRect.Top = 0;
rNewRect.Right = crNewSize.X - 1;
rNewRect.Bottom = crNewSize.Y - 1;
if (!SetConsoleWindowInfo(ghConOut, TRUE, &rNewRect))
{
// Non-critical error?
dwErr = GetLastError();
}
}
LogSize(NULL, 0, lbRc ? "ApplyConsoleSizeSimple OK" : "ApplyConsoleSizeSimple FAIL", bForceWriteLog);
return lbRc;
}
static SHORT FindFirstDirtyLine(SHORT anFrom, SHORT anTo, SHORT anWidth, WORD wDefAttrs)
{
SHORT iFound = anFrom;
SHORT iStep = (anTo < anFrom) ? -1 : 1;
HANDLE hCon = ghConOut;
BOOL bReadRc;
CHAR_INFO* pch = (CHAR_INFO*)calloc(anWidth, sizeof(*pch));
COORD crBufSize = {anWidth, 1}, crNil = {};
SMALL_RECT rcRead = {0, anFrom, anWidth-1, anFrom};
BYTE bDefAttr = LOBYTE(wDefAttrs); // Trim to colors only, do not compare extended attributes!
for (rcRead.Top = anFrom; rcRead.Top != anTo; rcRead.Top += iStep)
{
rcRead.Bottom = rcRead.Top;
InterlockedIncrement(&gnInReadConsoleOutput);
bReadRc = ReadConsoleOutput(hCon, pch, crBufSize, crNil, &rcRead);
InterlockedDecrement(&gnInReadConsoleOutput);
if (!bReadRc)
break;
// Is line dirty?
for (SHORT i = 0; i < anWidth; i++)
{
// Non-space char or non-default color/background
if ((pch[i].Char.UnicodeChar != L' ') || (LOBYTE(pch[i].Attributes) != bDefAttr))
{
iFound = rcRead.Top;
goto wrap;
}
}
}
iFound = std::min<SHORT>(anTo, anFrom);
wrap:
SafeFree(pch);
return iFound;
}
// По идее, rNewRect должен на входе содержать текущую видимую область
static void EvalVisibleResizeRect(SMALL_RECT& rNewRect,
SHORT anOldBottom,
const COORD& crNewSize,
bool bCursorInScreen, SHORT nCursorAtBottom,
SHORT nScreenAtBottom,
const CONSOLE_SCREEN_BUFFER_INFO& csbi)
{
// Абсолютная (буферная) координата
const SHORT nMaxX = csbi.dwSize.X-1, nMaxY = csbi.dwSize.Y-1;
// сначала - не трогая rNewRect.Left, вдруг там горизонтальная прокрутка?
// anWidth - желаемая ширина видимой области
rNewRect.Right = rNewRect.Left + crNewSize.X - 1;
// не может выходить за пределы ширины буфера
if (rNewRect.Right > nMaxX)
{
rNewRect.Left = std::max<int>(0, (csbi.dwSize.X - crNewSize.X));
rNewRect.Right = std::min<int>(nMaxX, (rNewRect.Left + crNewSize.X - 1));
}
// Теперь - танцы с вертикалью. Логика такая
// * Если ДО ресайза все видимые строки были заполнены (кейбар фара внизу экрана) - оставить anOldBottom
// * Иначе, если курсор был видим
// * приоритетно - двигать верхнюю границу видимой области (показывать максимум строк из back-scroll-buffer)
// * не допускать, чтобы расстояние между курсором и низом видимой области УМЕНЬШИЛОСЬ до менее чем 2-х строк
// * Иначе если курсор был НЕ видим
// * просто показывать максимум стро из back-scroll-buffer (фиксирую нижнюю границу)
// BTW, сейчас при ресайзе меняется только ширина csbi.dwSize.X (ну, кроме случаев изменения высоты буфера)
if ((nScreenAtBottom <= 0) && (nCursorAtBottom <= 0))
{
// Все просто, фиксируем нижнюю границу по размеру буфера
rNewRect.Bottom = csbi.dwSize.Y-1;
rNewRect.Top = std::max<int>(0, (rNewRect.Bottom - crNewSize.Y + 1));
}
else
{
// Значит консоль еще не дошла до низа
SHORT nRectHeight = (rNewRect.Bottom - rNewRect.Top + 1);
if (nCursorAtBottom > 0)
{
_ASSERTE(nCursorAtBottom<=3);
// Оставить строку с курсором "приклеенной" к нижней границе окна (с макс. отступом nCursorAtBottom строк)
rNewRect.Bottom = std::min<int>(nMaxY, (csbi.dwCursorPosition.Y + nCursorAtBottom - 1));
}
// Уменьшение видимой области
else if (crNewSize.Y < nRectHeight)
{
if ((nScreenAtBottom > 0) && (nScreenAtBottom <= 3))
{
// Оставить nScreenAtBottom строк (включая) между anOldBottom и низом консоли
rNewRect.Bottom = std::min<int>(nMaxY, anOldBottom+nScreenAtBottom-1);
}
else if (anOldBottom > (rNewRect.Top + crNewSize.Y - 1))
{
// Если нижняя граница приблизилась или перекрыла
// нашу старую строку (которая была anOldBottom)
rNewRect.Bottom = std::min<int>(anOldBottom, csbi.dwSize.Y-1);
}
else
{
// Иначе - не трогать верхнюю границу
rNewRect.Bottom = std::min<int>(nMaxY, rNewRect.Top+crNewSize.Y-1);
}
//rNewRect.Top = rNewRect.Bottom-crNewSize.Y+1; // на 0 скорректируем в конце
}
// Увеличение видимой области
else if (crNewSize.Y > nRectHeight)
{
if (nScreenAtBottom > 0)
{
// Оставить nScreenAtBottom строк (включая) между anOldBottom и низом консоли
rNewRect.Bottom = std::min<int>(nMaxY, anOldBottom+nScreenAtBottom-1);
}
//rNewRect.Top = rNewRect.Bottom-crNewSize.Y+1; // на 0 скорректируем в конце
}
// Но курсор не должен уходить за пределы экрана
if (bCursorInScreen && (csbi.dwCursorPosition.Y < (rNewRect.Bottom-crNewSize.Y+1)))
{
rNewRect.Bottom = std::max<int>(0, csbi.dwCursorPosition.Y+crNewSize.Y-1);
}
// And top, will be corrected to (>0) below
rNewRect.Top = rNewRect.Bottom-crNewSize.Y+1;
// Проверка на выход за пределы буфера
if (rNewRect.Bottom > nMaxY)
{
rNewRect.Bottom = nMaxY;
rNewRect.Top = std::max<int>(0, rNewRect.Bottom-crNewSize.Y+1);
}
else if (rNewRect.Top < 0)
{
rNewRect.Top = 0;
rNewRect.Bottom = std::min<int>(nMaxY, rNewRect.Top+crNewSize.Y-1);
}
}
_ASSERTE((rNewRect.Bottom-rNewRect.Top+1) == crNewSize.Y);
}
// There is the buffer (scrolling) in the console
// Ресайз для BufferHeight
static bool ApplyConsoleSizeBuffer(const USHORT BufferHeight, const COORD& crNewSize, const CONSOLE_SCREEN_BUFFER_INFO& csbi, DWORD& dwErr, bool bForceWriteLog)
{
bool lbRc = true;
dwErr = 0;
DEBUGSTRSIZE(L"SetConsoleSize: ApplyConsoleSizeBuffer started");
RECT rcConPos = {};
GetWindowRect(ghConWnd, &rcConPos);
TODO("Horizontal scrolling?");
COORD crHeight = MakeCoord(crNewSize.X, BufferHeight);
SMALL_RECT rcTemp = {};
// По идее (в планах), lbCursorInScreen всегда должен быть true,
// если только само консольное приложение не выполняет прокрутку.
// Сам ConEmu должен "крутить" консоль только виртуально, не трогая физический скролл.
bool lbCursorInScreen = CoordInSmallRect(csbi.dwCursorPosition, csbi.srWindow);
bool lbScreenAtBottom = (csbi.srWindow.Top > 0) && (csbi.srWindow.Bottom >= (csbi.dwSize.Y - 1));
bool lbCursorAtBottom = (lbCursorInScreen && (csbi.dwCursorPosition.Y >= (csbi.srWindow.Bottom - 2)));
SHORT nCursorAtBottom = lbCursorAtBottom ? (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1) : 0;
SHORT nBottomLine = csbi.srWindow.Bottom;
SHORT nScreenAtBottom = 0;
// Прикинуть, где должна будет быть нижняя граница видимой области
if (!lbScreenAtBottom)
{
// Ищем снизу вверх (найти самую нижнюю грязную строку)
SHORT nTo = lbCursorInScreen ? csbi.dwCursorPosition.Y : csbi.srWindow.Top;
SHORT nWidth = (csbi.srWindow.Right - csbi.srWindow.Left + 1);
SHORT nDirtyLine = FindFirstDirtyLine(nBottomLine, nTo, nWidth, csbi.wAttributes);
// Если удачно
if (nDirtyLine >= csbi.srWindow.Top && nDirtyLine < csbi.dwSize.Y)
{
if (lbCursorInScreen)
{
nBottomLine = std::max<int>(nDirtyLine, std::min<int>(csbi.dwCursorPosition.Y+1/*-*/,csbi.srWindow.Bottom));
}
else
{
nBottomLine = nDirtyLine;
}
}
nScreenAtBottom = (csbi.srWindow.Bottom - nBottomLine + 1);
// Чтобы информации НАД курсором не стало меньше чем пустых строк ПОД курсором
if (lbCursorInScreen)
{
if (nScreenAtBottom <= 4)
{
SHORT nAboveLines = (crNewSize.Y - nScreenAtBottom);
if (nAboveLines <= (nScreenAtBottom + 1))
{
nCursorAtBottom = std::max<int>(1, crNewSize.Y - nScreenAtBottom - 1);
}
}
}
}
SMALL_RECT rNewRect = csbi.srWindow;
EvalVisibleResizeRect(rNewRect, nBottomLine, crNewSize, lbCursorInScreen, nCursorAtBottom, nScreenAtBottom, csbi);
#if 0
// Подправим будущую видимую область
if (csbi.dwSize.Y == (csbi.srWindow.Bottom - csbi.srWindow.Top + 1))
{
// Прокрутки сейчас нет, оставляем .Top без изменений!
}
// При изменении высоты буфера (если он уже был включен), нужно скорректировать новую видимую область
else if (rNewRect.Bottom >= (csbi.dwSize.Y - (csbi.srWindow.Bottom - csbi.srWindow.Top)))
{
// Считаем, что рабочая область прижата к низу экрана. Нужно подвинуть .Top
int nBottomLines = (csbi.dwSize.Y - csbi.srWindow.Bottom - 1); // Сколько строк сейчас снизу от видимой области?
SHORT nTop = BufferHeight - crNewSize.Y - nBottomLines;
rNewRect.Top = (nTop > 0) ? nTop : 0;
// .Bottom подправится ниже, перед последним SetConsoleWindowInfo
}
else
{
// Считаем, что верх рабочей области фиксирован, коррекция не требуется
}
#endif
// Если этого не сделать - размер консоли нельзя УМЕНЬШИТЬ
if (crNewSize.X <= (csbi.srWindow.Right-csbi.srWindow.Left)
|| crNewSize.Y <= (csbi.srWindow.Bottom-csbi.srWindow.Top))
{
#if 0
rcTemp.Left = 0;
WARNING("А при уменьшении высоты, тащим нижнюю границе окна вверх, Top глючить не будет?");
rcTemp.Top = std::max(0,(csbi.srWindow.Bottom-crNewSize.Y+1));
rcTemp.Right = std::min((crNewSize.X - 1),(csbi.srWindow.Right-csbi.srWindow.Left));
rcTemp.Bottom = std::min((BufferHeight - 1),(rcTemp.Top+crNewSize.Y-1));//(csbi.srWindow.Bottom-csbi.srWindow.Top)); //-V592
_ASSERTE(((rcTemp.Bottom-rcTemp.Top+1)==crNewSize.Y) && ((rcTemp.Bottom-rcTemp.Top)==(rNewRect.Bottom-rNewRect.Top)));
#endif
if (!SetConsoleWindowInfo(ghConOut, TRUE, &rNewRect))
{
// Last chance to shrink visible area of the console if ConApi was failed
MoveWindow(ghConWnd, rcConPos.left, rcConPos.top, 1, 1, 1);
}
}
// crHeight, а не crNewSize - там "оконные" размеры
if (!SetConsoleScreenBufferSize(ghConOut, crHeight))
{
lbRc = false;
dwErr = GetLastError();
}
// Особенно в Win10 после "заворота строк",
// нужно получить новое реальное состояние консоли после изменения буфера
CONSOLE_SCREEN_BUFFER_INFO csbiNew = {};
if (GetConsoleScreenBufferInfo(ghConOut, &csbiNew))
{
rNewRect = csbiNew.srWindow;
EvalVisibleResizeRect(rNewRect, nBottomLine, crNewSize, lbCursorAtBottom, nCursorAtBottom, nScreenAtBottom, csbiNew);
}
#if 0
// Последняя коррекция видимой области.
// Левую граница - всегда 0 (горизонтальную прокрутку пока не поддерживаем)
// Вертикальное положение - пляшем от rNewRect.Top
rNewRect.Left = 0;
rNewRect.Right = crHeight.X-1;
if (lbScreenAtBottom)
{
}
else if (lbCursorInScreen)
{
}
else
{
TODO("Маркеры для блокировки положения в окне после заворота строк в Win10?");
}
rNewRect.Bottom = std::min((crHeight.Y-1), (rNewRect.Top+gcrVisibleSize.Y-1)); //-V592
#endif
_ASSERTE((rNewRect.Bottom-rNewRect.Top)<200);
if (!SetConsoleWindowInfo(ghConOut, TRUE, &rNewRect))
{
dwErr = GetLastError();
}
LogSize(NULL, 0, lbRc ? "ApplyConsoleSizeBuffer OK" : "ApplyConsoleSizeBuffer FAIL", bForceWriteLog);
return lbRc;
}
void RefillConsoleAttributes(const CONSOLE_SCREEN_BUFFER_INFO& csbi5, WORD OldText, WORD NewText)
{
wchar_t szLog[140];
swprintf_c(szLog, L"RefillConsoleAttributes started Lines=%u Cols=%u Old=x%02X New=x%02X", csbi5.dwSize.Y, csbi5.dwSize.X, OldText, NewText);
LogString(szLog);
// Считать из консоли текущие атрибуты (построчно/поблочно)
// И там, где они совпадают с OldText - заменить на in.SetConColor.NewTextAttributes
DWORD nMaxLines = std::max<int>(1, std::min<int>((8000 / csbi5.dwSize.X), csbi5.dwSize.Y));
WORD* pnAttrs = (WORD*)malloc(nMaxLines*csbi5.dwSize.X*sizeof(*pnAttrs));
if (!pnAttrs)
{
// Memory allocation error
return;
}
PerfCounter c_read = {0}, c_fill = {1};
MPerfCounter perf(2);
BOOL b;
COORD crRead = {0,0};
while (crRead.Y < csbi5.dwSize.Y)
{
DWORD nReadLn = std::min<int>(nMaxLines, (csbi5.dwSize.Y-crRead.Y));
DWORD nReady = 0;
perf.Start(c_read);
b = ReadConsoleOutputAttribute(ghConOut, pnAttrs, nReadLn * csbi5.dwSize.X, crRead, &nReady);
perf.Stop(c_read);
if (!b)
break;
bool bStarted = false;
COORD crFrom = crRead;
//SHORT nLines = (SHORT)(nReady / csbi5.dwSize.X);
DWORD i = 0, iStarted = 0, iWritten;
while (i < nReady)
{
if ((pnAttrs[i] & 0xFF) == OldText)
{
if (!bStarted)
{
_ASSERT(crRead.X == 0);
crFrom.Y = (SHORT)(crRead.Y + (i / csbi5.dwSize.X));
crFrom.X = i % csbi5.dwSize.X;
iStarted = i;
bStarted = true;
}
}
else
{
if (bStarted)
{
bStarted = false;
if (iStarted < i)
{
perf.Start(c_fill);
FillConsoleOutputAttribute(ghConOut, NewText, i - iStarted, crFrom, &iWritten);
perf.Stop(c_fill);
}
}
}
// Next cell checking
i++;
}
// Если хвост остался
if (bStarted && (iStarted < i))
{
perf.Start(c_fill);
FillConsoleOutputAttribute(ghConOut, NewText, i - iStarted, crFrom, &iWritten);
perf.Stop(c_fill);
}
// Next block
crRead.Y += (USHORT)nReadLn;
}
free(pnAttrs);
ULONG l_read_p, l_read = perf.GetCounter(c_read.ID, &l_read_p, NULL, NULL);
ULONG l_fill_p, l_fill = perf.GetCounter(c_fill.ID, &l_fill_p, NULL, NULL);
swprintf_c(szLog, L"RefillConsoleAttributes finished, Reads(%u, %u%%), Fills(%u, %u%%)", l_read, l_read_p, l_fill, l_fill_p);
LogString(szLog);
}
// BufferHeight - высота БУФЕРА (0 - без прокрутки)
// crNewSize - размер ОКНА (ширина окна == ширине буфера)
// rNewRect - для (BufferHeight!=0) определяет new upper-left and lower-right corners of the window
// !!! rNewRect по идее вообще не нужен, за блокировку при прокрутке отвечает nSendTopLine
BOOL SetConsoleSize(USHORT BufferHeight, COORD crNewSize, SMALL_RECT rNewRect, LPCSTR asLabel, bool bForceWriteLog)
{
_ASSERTE(ghConWnd);
_ASSERTE(BufferHeight==0 || BufferHeight>crNewSize.Y); // Otherwise - it will be NOT a bufferheight...
if (!ghConWnd)
{
DEBUGSTRSIZE(L"SetConsoleSize: Skipped due to ghConWnd==NULL");
return FALSE;
}
if (CheckWasFullScreen())
{
DEBUGSTRSIZE(L"SetConsoleSize was skipped due to CONSOLE_FULLSCREEN_HARDWARE");
LogString("SetConsoleSize was skipped due to CONSOLE_FULLSCREEN_HARDWARE");
return FALSE;
}
DWORD dwCurThId = GetCurrentThreadId();
DWORD dwWait = 0;
DWORD dwErr = 0;
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
{
// Запомним то, что последний раз установил сервер. пригодится
gpSrv->nReqSizeBufferHeight = BufferHeight;
gpSrv->crReqSizeNewSize = crNewSize;
_ASSERTE(gpSrv->crReqSizeNewSize.X!=0);
WARNING("выпилить gpSrv->rReqSizeNewRect и rNewRect");
gpSrv->rReqSizeNewRect = rNewRect;
gpSrv->sReqSizeLabel = asLabel;
gpSrv->bReqSizeForceLog = bForceWriteLog;
// Ресайз выполнять только в нити RefreshThread. Поэтому если нить другая - ждем...
if (gpSrv->dwRefreshThread && dwCurThId != gpSrv->dwRefreshThread)
{
DEBUGSTRSIZE(L"SetConsoleSize: Waiting for RefreshThread");
ResetEvent(gpSrv->hReqSizeChanged);
if (InterlockedIncrement(&gpSrv->nRequestChangeSize) <= 0)
{
_ASSERTE(FALSE && "gpSrv->nRequestChangeSize has invalid value");
gpSrv->nRequestChangeSize = 1;
}
// Ожидание, пока сработает RefreshThread
HANDLE hEvents[2] = {ghQuitEvent, gpSrv->hReqSizeChanged};
DWORD nSizeTimeout = REQSIZE_TIMEOUT;
#ifdef _DEBUG
if (IsDebuggerPresent())
nSizeTimeout = INFINITE;
#endif
dwWait = WaitForMultipleObjects(2, hEvents, FALSE, nSizeTimeout);
// Generally, it must be decremented by RefreshThread...
if ((dwWait == WAIT_TIMEOUT) && (gpSrv->nRequestChangeSize > 0))
{
InterlockedDecrement(&gpSrv->nRequestChangeSize);
}
// Checking invalid value...
if (gpSrv->nRequestChangeSize < 0)
{
// Decremented by RefreshThread and CurrentThread? Must not be...
_ASSERTE(gpSrv->nRequestChangeSize >= 0);
gpSrv->nRequestChangeSize = 0;
}
if (dwWait == WAIT_OBJECT_0)
{
// ghQuitEvent !!
return FALSE;
}
if (dwWait == (WAIT_OBJECT_0+1))
{
return gpSrv->bRequestChangeSizeResult;
}
// ?? Может быть стоит самим попробовать?
return FALSE;
}
}
DEBUGSTRSIZE(L"SetConsoleSize: Started");
MSectionLock RCS;
if (gpSrv->pReqSizeSection && !RCS.Lock(gpSrv->pReqSizeSection, TRUE, 30000))
{
DEBUGSTRSIZE(L"SetConsoleSize: !!!Failed to lock section!!!");
_ASSERTE(FALSE);
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (gpLogSize) LogSize(&crNewSize, BufferHeight, asLabel);
_ASSERTE(crNewSize.X>=MIN_CON_WIDTH && crNewSize.Y>=MIN_CON_HEIGHT);
// Проверка минимального размера
if (crNewSize.X</*4*/MIN_CON_WIDTH)
crNewSize.X = /*4*/MIN_CON_WIDTH;
if (crNewSize.Y</*3*/MIN_CON_HEIGHT)
crNewSize.Y = /*3*/MIN_CON_HEIGHT;
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
// Нам нужно реальное состояние консоли, чтобы не поломать ее вид после ресайза
if (!GetConsoleScreenBufferInfo(ghConOut, &csbi))
{
DWORD nErrCode = GetLastError();
DEBUGSTRSIZE(L"SetConsoleSize: !!!GetConsoleScreenBufferInfo failed!!!");
_ASSERTE(FALSE && "GetConsoleScreenBufferInfo was failed");
SetLastError(nErrCode ? nErrCode : ERROR_INVALID_HANDLE);
return FALSE;
}
BOOL lbRc = TRUE;
if (!AdaptConsoleFontSize(crNewSize))
{
DEBUGSTRSIZE(L"SetConsoleSize: !!!AdaptConsoleFontSize failed!!!");
lbRc = FALSE;
goto wrap;
}
// Делаем это ПОСЛЕ MyGetConsoleScreenBufferInfo, т.к. некоторые коррекции размера окна
// она делает ориентируясь на gnBufferHeight
gnBufferHeight = BufferHeight;
// Размер видимой области (слишком большой?)
_ASSERTE(crNewSize.X<=500 && crNewSize.Y<=300);
gcrVisibleSize = crNewSize;
if (gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER)
UpdateConsoleMapHeader(L"SetConsoleSize"); // Обновить pConsoleMap.crLockedVisible
if (gnBufferHeight)
{
// В режиме BufferHeight - высота ДОЛЖНА быть больше допустимого размера окна консоли
// иначе мы запутаемся при проверках "буферный ли это режим"...
if (gnBufferHeight <= (csbi.dwMaximumWindowSize.Y * 12 / 10))
gnBufferHeight = std::max<int>(300, (csbi.dwMaximumWindowSize.Y * 12 / 10));
// В режиме cmd сразу уменьшим максимальный FPS
gpSrv->dwLastUserTick = GetTickCount() - USER_IDLE_TIMEOUT - 1;
}
// The resize itself
if (BufferHeight == 0)
{
// No buffer in the console
lbRc = ApplyConsoleSizeSimple(crNewSize, csbi, dwErr, bForceWriteLog);
}
else
{
// Начался ресайз для BufferHeight
lbRc = ApplyConsoleSizeBuffer(gnBufferHeight, crNewSize, csbi, dwErr, bForceWriteLog);
}
#ifdef _DEBUG
DEBUGSTRSIZE(lbRc ? L"SetConsoleSize: FINISHED" : L"SetConsoleSize: !!! FAILED !!!");
#endif
wrap:
gpSrv->bRequestChangeSizeResult = lbRc;
if ((gnRunMode == RM_SERVER) && gpSrv->hRefreshEvent)
{
SetEvent(gpSrv->hRefreshEvent);
}
return lbRc;
}
#if defined(__GNUC__)
extern "C"
#endif
BOOL WINAPI HandlerRoutine(DWORD dwCtrlType)
{
// Log it first
wchar_t szLog[80], szType[20];
switch (dwCtrlType)
{
case CTRL_C_EVENT:
wcscpy_c(szType, L"CTRL_C_EVENT"); break;
case CTRL_BREAK_EVENT:
wcscpy_c(szType, L"CTRL_BREAK_EVENT"); break;
case CTRL_CLOSE_EVENT:
wcscpy_c(szType, L"CTRL_CLOSE_EVENT"); break;
case CTRL_LOGOFF_EVENT:
wcscpy_c(szType, L"CTRL_LOGOFF_EVENT"); break;
case CTRL_SHUTDOWN_EVENT:
wcscpy_c(szType, L"CTRL_SHUTDOWN_EVENT"); break;
default:
msprintf(szType, countof(szType), L"ID=%u", dwCtrlType);
}
wcscpy_c(szLog, L" --- ConsoleCtrlHandler triggered: ");
wcscat_c(szLog, szType);
LogString(szLog);
// Continue processing
//PRINT_COMSPEC(L"HandlerRoutine triggered. Event type=%i\n", dwCtrlType);
if ((dwCtrlType == CTRL_CLOSE_EVENT)
|| (dwCtrlType == CTRL_LOGOFF_EVENT)
|| (dwCtrlType == CTRL_SHUTDOWN_EVENT))
{
PRINT_COMSPEC(L"Console about to be closed\n", 0);
WARNING("Тут бы подождать немного, пока другие консольные процессы завершатся... а то таб закрывается раньше времени");
gbInShutdown = TRUE;
if (gbInExitWaitForKey)
gbStopExitWaitForKey = TRUE;
// Our debugger is running?
if (gpSrv->DbgInfo.bDebuggerActive)
{
// pfnDebugActiveProcessStop is useless, because
// 1. pfnDebugSetProcessKillOnExit was called already
// 2. we can debug more than a one process
//gpSrv->DbgInfo.bDebuggerActive = FALSE;
}
else
{
#if 0
wchar_t szTitle[128]; wsprintf(szTitle, L"ConEmuC, PID=%u", GetCurrentProcessId());
//MessageBox(NULL, L"CTRL_CLOSE_EVENT in ConEmuC", szTitle, MB_SYSTEMMODAL);
DWORD nWait = WaitForSingleObject(ghExitQueryEvent, CLOSE_CONSOLE_TIMEOUT);
if (nWait == WAIT_OBJECT_0)
{
#ifdef _DEBUG
OutputDebugString(L"All console processes was terminated\n");
#endif
}
else
{
// Поскольку мы (сервер) сейчас свалимся, то нужно показать
// консольное окно, раз в нем остались какие-то процессы
EmergencyShow();
}
#endif
// trick to let ConsoleMain2() finish correctly
ExitThread(1);
}
}
else if ((dwCtrlType == CTRL_C_EVENT) || (dwCtrlType == CTRL_BREAK_EVENT))
{
if (gbTerminateOnCtrlBreak)
{
PRINT_COMSPEC(L"Ctrl+Break received, server will be terminated\n", 0);
gbInShutdown = TRUE;
}
else if (gpSrv->DbgInfo.bDebugProcess)
{
DWORD nWait = WaitForSingleObject(gpSrv->hRootProcess, 0);
#ifdef _DEBUG
DWORD nErr = GetLastError();
#endif
if (nWait == WAIT_OBJECT_0)
{
_ASSERTE(gbTerminateOnCtrlBreak==FALSE);
PRINT_COMSPEC(L"Ctrl+Break received, debugger will be stopped\n", 0);
//if (pfnDebugActiveProcessStop) pfnDebugActiveProcessStop(gpSrv->dwRootProcess);
//gpSrv->DbgInfo.bDebuggerActive = FALSE;
//gbInShutdown = TRUE;
SetTerminateEvent(ste_HandlerRoutine);
}
else
{
GenerateMiniDumpFromCtrlBreak();
}
}
}
return TRUE;
}
int GetProcessCount(DWORD *rpdwPID, UINT nMaxCount)
{
if (!rpdwPID || (nMaxCount < 3))
{
_ASSERTE(rpdwPID && (nMaxCount >= 3));
return gpSrv->processes->nProcessCount;
}
UINT nRetCount = 0;
rpdwPID[nRetCount++] = gnSelfPID;
// Windows 7 and higher: there is "conhost.exe"
if (gnOsVer >= 0x0601)
{
#if 0
typedef BOOL (WINAPI* GetNamedPipeServerProcessId_t)(HANDLE Pipe,PULONG ServerProcessId);
HMODULE hKernel = GetModuleHandle(L"kernel32.dll");
GetNamedPipeServerProcessId_t GetNamedPipeServerProcessId_f = hKernel
? (GetNamedPipeServerProcessId_t)GetProcAddress(hKernel, "GetNamedPipeServerProcessId") : NULL;
HANDLE hOut; BOOL bSrv = FALSE; ULONG nSrvPid = 0;
_ASSERTE(FALSE && "calling GetNamedPipeServerProcessId_f");
if (GetNamedPipeServerProcessId_f)
{
hOut = (HANDLE)ghConOut;
if (hOut)
{
bSrv = GetNamedPipeServerProcessId_f(hOut, &nSrvPid);
}
}
#endif
if (!gpSrv->processes->nConhostPID)
{
// Найти порожденный conhost.exe
//TODO: Reuse MToolHelp.h
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (h && (h != INVALID_HANDLE_VALUE))
{
// Учтем альтернативные серверы (Far/Telnet/...)
DWORD nSrvPID = gpSrv->dwMainServerPID ? gpSrv->dwMainServerPID : gnSelfPID;
PROCESSENTRY32 PI = {sizeof(PI)};
if (Process32First(h, &PI))
{
do {
if ((PI.th32ParentProcessID == nSrvPID)
&& (lstrcmpi(PI.szExeFile, L"conhost.exe") == 0))
{
gpSrv->processes->nConhostPID = PI.th32ProcessID;
break;
}
} while (Process32Next(h, &PI));
}
CloseHandle(h);
}
if (!gpSrv->processes->nConhostPID)
gpSrv->processes->nConhostPID = (UINT)-1;
}
if (gpSrv->processes->nConhostPID && (gpSrv->processes->nConhostPID != (UINT)-1))
{
rpdwPID[nRetCount++] = gpSrv->processes->nConhostPID;
}
}
MSectionLock CS;
UINT nCurCount = 0;
if (CS.Lock(gpSrv->processes->csProc, TRUE/*abExclusive*/, 200))
{
nCurCount = gpSrv->processes->nProcessCount;
for (INT_PTR i1 = (nCurCount-1); (i1 >= 0) && (nRetCount < nMaxCount); i1--)
{
DWORD PID = gpSrv->processes->pnProcesses[i1];
if (PID && PID != gnSelfPID)
{
rpdwPID[nRetCount++] = PID;
}
}
}
for (size_t i = nRetCount; i < nMaxCount; i++)
{
rpdwPID[i] = 0;
}
//if (nSize > nMaxCount)
//{
// memset(rpdwPID, 0, sizeof(DWORD)*nMaxCount);
// rpdwPID[0] = gnSelfPID;
// for(int i1=0, i2=(nMaxCount-1); i1<(int)nSize && i2>0; i1++, i2--)
// rpdwPID[i2] = gpSrv->processes->pnProcesses[i1]; //-V108
// nSize = nMaxCount;
//}
//else
//{
// memmove(rpdwPID, gpSrv->processes->pnProcesses, sizeof(DWORD)*nSize);
// for (UINT i=nSize; i<nMaxCount; i++)
// rpdwPID[i] = 0; //-V108
//}
_ASSERTE(rpdwPID[0]);
return nRetCount;
}
void _printf(LPCSTR asFormat, DWORD dw1, DWORD dw2, LPCWSTR asAddLine)
{
char szError[MAX_PATH];
sprintf_c(szError, asFormat, dw1, dw2);
_printf(szError);
if (asAddLine)
{
_wprintf(asAddLine);
_printf("\n");
}
}
void _printf(LPCSTR asFormat, DWORD dwErr, LPCWSTR asAddLine)
{
char szError[MAX_PATH];
sprintf_c(szError, asFormat, dwErr);
_printf(szError);
if (asAddLine)
{
_wprintf(asAddLine);
_printf("\n");
}
}
void _printf(LPCSTR asFormat, DWORD dwErr)
{
char szError[MAX_PATH];
sprintf_c(szError, asFormat, dwErr);
_printf(szError);
}
void _printf(LPCSTR asBuffer)
{
if (!asBuffer) return;
int nAllLen = lstrlenA(asBuffer);
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwWritten = 0;
DEBUGTEST(BOOL bWriteRC =)
WriteFile(hOut, asBuffer, nAllLen, &dwWritten, 0);
UNREFERENCED_PARAMETER(dwWritten);
}
void print_error(DWORD dwErr/*= 0*/, LPCSTR asFormat/*= NULL*/)
{
if (!dwErr)
dwErr = GetLastError();
wchar_t* lpMsgBuf = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL);
_printf(asFormat ? asFormat : "\nErrCode=0x%08X, Description:\n", dwErr);
_wprintf((!lpMsgBuf || !*lpMsgBuf) ? L"<Unknown error>" : lpMsgBuf);
if (lpMsgBuf) LocalFree(lpMsgBuf);
SetLastError(dwErr);
}
bool IsOutputRedirected()
{
static int isRedirected = 0;
if (isRedirected)
{
return (isRedirected == 2);
}
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO sbi = {};
BOOL bIsConsole = GetConsoleScreenBufferInfo(hOut, &sbi);
if (bIsConsole)
{
isRedirected = 1;
return false;
}
else
{
isRedirected = 2;
return true;
}
}
void _wprintf(LPCWSTR asBuffer)
{
if (!asBuffer) return;
WriteOutput(asBuffer);
}
void DisableAutoConfirmExit(BOOL abFromFarPlugin)
{
// Консоль могла быть приаттачена к GUI в тот момент, когда сервер ожидает
// от юзера подтверждение закрытия консоли
if (!gbInExitWaitForKey)
{
_ASSERTE(gnConfirmExitParm==0 || abFromFarPlugin);
gbAutoDisableConfirmExit = FALSE; gbAlwaysConfirmExit = FALSE;
// менять nProcessStartTick не нужно. проверка только по флажкам
//gpSrv->nProcessStartTick = GetTickCount() - 2*CHECK_ROOTSTART_TIMEOUT;
}
}
bool IsKeyboardLayoutChanged(DWORD& pdwLayout, LPDWORD pdwErrCode /*= NULL*/)
{
bool bChanged = false;
if (!gpSrv)
{
_ASSERTE(gpSrv!=NULL);
return false;
}
static bool bGetConsoleKeyboardLayoutNameImplemented = true;
if (bGetConsoleKeyboardLayoutNameImplemented && pfnGetConsoleKeyboardLayoutName)
{
wchar_t szCurKeybLayout[32] = L"";
//#ifdef _DEBUG
//wchar_t szDbgKeybLayout[KL_NAMELENGTH/*==9*/];
//BOOL lbGetRC = GetKeyboardLayoutName(szDbgKeybLayout); // -- не дает эффекта, поскольку "на процесс", а не на консоль
//#endif
// The expected result of GetConsoleKeyboardLayoutName is like "00000419"
BOOL bConApiRc = pfnGetConsoleKeyboardLayoutName(szCurKeybLayout) && szCurKeybLayout[0];
DWORD nErr = bConApiRc ? 0 : GetLastError();
if (pdwErrCode)
*pdwErrCode = nErr;
/*
if (!bConApiRc && (nErr == ERROR_GEN_FAILURE))
{
_ASSERTE(FALSE && "ConsKeybLayout failed");
MModule kernel(GetModuleHandle(L"kernel32.dll"));
BOOL (WINAPI* getLayoutName)(LPWSTR,int);
if (kernel.GetProcAddress("GetConsoleKeyboardLayoutNameW", getLayoutName))
{
bConApiRc = getLayoutName(szCurKeybLayout, countof(szCurKeybLayout));
nErr = bConApiRc ? 0 : GetLastError();
}
}
*/
if (!bConApiRc)
{
// If GetConsoleKeyboardLayoutName is not implemented in Windows, ERROR_MR_MID_NOT_FOUND or E_NOTIMPL will be returned.
// (there is no matching DOS/Win32 error code for NTSTATUS code returned)
// When this happens, we don't want to continue to call the function.
if (nErr == ERROR_MR_MID_NOT_FOUND || LOWORD(nErr) == LOWORD(E_NOTIMPL))
{
bGetConsoleKeyboardLayoutNameImplemented = false;
}
if (gpSrv->szKeybLayout[0])
{
// Log only first error per session
wcscpy_c(szCurKeybLayout, gpSrv->szKeybLayout);
}
else
{
wchar_t szErr[80];
swprintf_c(szErr, L"ConsKeybLayout failed with code=%u forcing to GetKeyboardLayoutName or 0409", nErr);
_ASSERTE(!bGetConsoleKeyboardLayoutNameImplemented && "ConsKeybLayout failed");
LogString(szErr);
if (!GetKeyboardLayoutName(szCurKeybLayout) || (szCurKeybLayout[0] == 0))
{
wcscpy_c(szCurKeybLayout, L"00000419");
}
}
}
if (szCurKeybLayout[0])
{
if (lstrcmpW(szCurKeybLayout, gpSrv->szKeybLayout))
{
#ifdef _DEBUG
wchar_t szDbg[128];
swprintf_c(szDbg,
L"ConEmuC: InputLayoutChanged (GetConsoleKeyboardLayoutName returns) '%s'\n",
szCurKeybLayout);
OutputDebugString(szDbg);
#endif
if (gpLogSize)
{
char szInfo[128]; wchar_t szWide[128];
swprintf_c(szWide, L"ConsKeybLayout changed from %s to %s", gpSrv->szKeybLayout, szCurKeybLayout);
WideCharToMultiByte(CP_ACP,0,szWide,-1,szInfo,128,0,0);
LogFunction(szInfo);
}
// Сменился
wcscpy_c(gpSrv->szKeybLayout, szCurKeybLayout);
bChanged = true;
}
}
}
else if (pdwErrCode)
{
*pdwErrCode = (DWORD)-1;
}
// The result, if possible
{
wchar_t *pszEnd = NULL; //szCurKeybLayout+8;
//WARNING("BUGBUG: 16 цифр не вернет"); -- тут именно 8 цифр. Это LayoutNAME, а не string(HKL)
// LayoutName: "00000409", "00010409", ...
// А HKL от него отличается, так что передаем DWORD
// HKL в x64 выглядит как: "0x0000000000020409", "0xFFFFFFFFF0010409"
pdwLayout = wcstoul(gpSrv->szKeybLayout, &pszEnd, 16);
}
return bChanged;
}
//WARNING("BUGBUG: x64 US-Dvorak"); - done
void CheckKeyboardLayout()
{
DWORD dwLayout = 0;
//WARNING("BUGBUG: 16 цифр не вернет"); -- тут именно 8 цифр. Это LayoutNAME, а не string(HKL)
// LayoutName: "00000409", "00010409", ...
// А HKL от него отличается, так что передаем DWORD
// HKL в x64 выглядит как: "0x0000000000020409", "0xFFFFFFFFF0010409"
if (IsKeyboardLayoutChanged(dwLayout))
{
// Сменился, Отошлем в GUI
CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_LANGCHANGE,sizeof(CESERVER_REQ_HDR)+sizeof(DWORD)); //-V119
if (pIn)
{
//memmove(pIn->Data, &dwLayout, 4);
pIn->dwData[0] = dwLayout;
CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
ExecuteFreeResult(pOut);
ExecuteFreeResult(pIn);
}
}
}
/*
LPVOID calloc(size_t nCount, size_t nSize)
{
#ifdef _DEBUG
//HeapValidate(ghHeap, 0, NULL);
#endif
size_t nWhole = nCount * nSize;
_ASSERTE(nWhole>0);
LPVOID ptr = HeapAlloc ( ghHeap, HEAP_GENERATE_EXCEPTIONS|HEAP_ZERO_MEMORY, nWhole );
#ifdef HEAP_LOGGING
wchar_t szDbg[64];
swprintf_c(szDbg, L"%i: ALLOCATED 0x%08X..0x%08X (%i bytes)\n", GetCurrentThreadId(), (DWORD)ptr, ((DWORD)ptr)+nWhole, nWhole);
DEBUGSTR(szDbg);
#endif
#ifdef _DEBUG
HeapValidate(ghHeap, 0, NULL);
if (ptr)
{
gnHeapUsed += nWhole;
if (gnHeapMax < gnHeapUsed)
gnHeapMax = gnHeapUsed;
}
#endif
return ptr;
}
void free(LPVOID ptr)
{
if (ptr && ghHeap)
{
#ifdef _DEBUG
//HeapValidate(ghHeap, 0, NULL);
size_t nMemSize = HeapSize(ghHeap, 0, ptr);
#endif
#ifdef HEAP_LOGGING
wchar_t szDbg[64];
swprintf_c(szDbg, L"%i: FREE BLOCK 0x%08X..0x%08X (%i bytes)\n", GetCurrentThreadId(), (DWORD)ptr, ((DWORD)ptr)+nMemSize, nMemSize);
DEBUGSTR(szDbg);
#endif
HeapFree ( ghHeap, 0, ptr );
#ifdef _DEBUG
HeapValidate(ghHeap, 0, NULL);
if (gnHeapUsed > nMemSize)
gnHeapUsed -= nMemSize;
#endif
}
}
*/
/* Используются как extern в ConEmuCheck.cpp */
/*
LPVOID _calloc(size_t nCount,size_t nSize) {
return calloc(nCount,nSize);
}
LPVOID _malloc(size_t nCount) {
return calloc(nCount,1);
}
void _free(LPVOID ptr) {
free(ptr);
}
*/
/*
void * __cdecl operator new(size_t _Size)
{
void * p = calloc(_Size,1);
return p;
}
void __cdecl operator delete(void *p)
{
free(p);
}
*/
| 29.013751
| 343
| 0.685532
|
shawwn
|
fdaff450fae58a320c147339e085c3fe07618ada
| 4,968
|
cpp
|
C++
|
samples/snippets/cpp/VS_Snippets_Remoting/IPEndPoint_Properties/CPP/ipendpoint_properties.cpp
|
BaruaSourav/docs
|
c288ed777de6b091f5e074d3488f7934683f3eb5
|
[
"CC-BY-4.0",
"MIT"
] | 3,294
|
2016-10-30T05:27:20.000Z
|
2022-03-31T15:59:30.000Z
|
samples/snippets/cpp/VS_Snippets_Remoting/IPEndPoint_Properties/CPP/ipendpoint_properties.cpp
|
BaruaSourav/docs
|
c288ed777de6b091f5e074d3488f7934683f3eb5
|
[
"CC-BY-4.0",
"MIT"
] | 16,739
|
2016-10-28T19:41:29.000Z
|
2022-03-31T22:38:48.000Z
|
samples/snippets/cpp/VS_Snippets_Remoting/IPEndPoint_Properties/CPP/ipendpoint_properties.cpp
|
BaruaSourav/docs
|
c288ed777de6b091f5e074d3488f7934683f3eb5
|
[
"CC-BY-4.0",
"MIT"
] | 6,701
|
2016-10-29T20:56:11.000Z
|
2022-03-31T12:32:26.000Z
|
// System.Net.IPEndPoint.MaxPort; System.Net.IPEndPoint.MinPort;
// System.Net.IPEndPoint.AddressFamily; System.Net.IPEndPoint.IPEndPoint(long,int)
// System.Net.IPEndPoint.Address; System.Net.IPEndPoint.Port;
/*This program demonstrates the properties 'MaxPort', 'MinPort','Address','Port'
and 'AddressFamily' and a constructor 'IPEndPoint(long,int)' of class 'IPEndPoint'.
A procedure DoSocketGet is created which internally uses a socket to transmit http "Get" requests to a Web resource.
The program accepts a resource Url, Resolves it to obtain 'IPAddress',Constructs 'IPEndPoint' instance using this
'IPAddress' and port 80.Invokes DoSocketGet procedure to obtain a response and displays the response to a console.
It then accepts another Url, Resolves it to obtain 'IPAddress'. Assigns this IPAddress and port to the 'IPEndPoint'
and again invokes DoSocketGet to obtain a response and display.
*/
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::Text;
using namespace System::Net::Sockets;
using namespace System::Runtime::InteropServices;
String^ DoSocketGet( IPEndPoint^ hostIPEndPoint, String^ getString ); // forward reference
int main()
{
try
{
Console::Write( "\nPlease enter an INTRANET Url as shown: [e.g. www.microsoft.com]:" );
String^ hostString1 = Console::ReadLine();
// <Snippet1>
// <Snippet2>
// <Snippet3>
// <Snippet4>
IPAddress^ hostIPAddress1 = (Dns::Resolve( hostString1 ))->AddressList[ 0 ];
Console::WriteLine( hostIPAddress1 );
IPEndPoint^ hostIPEndPoint = gcnew IPEndPoint( hostIPAddress1,80 );
Console::WriteLine( "\nIPEndPoint information:{0}", hostIPEndPoint );
Console::WriteLine( "\n\tMaximum allowed Port Address :{0}", IPEndPoint::MaxPort );
Console::WriteLine( "\n\tMinimum allowed Port Address :{0}", (int^)IPEndPoint::MinPort );
Console::WriteLine( "\n\tAddress Family :{0}", hostIPEndPoint->AddressFamily );
// </Snippet4>
Console::Write( "\nPress Enter to continue" );
Console::ReadLine();
String^ getString = String::Format( "GET / HTTP/1.1\r\nHost: {0}\r\nConnection: Close\r\n\r\n", hostString1 );
String^ pageContent = DoSocketGet( hostIPEndPoint, getString );
if ( pageContent != nullptr )
{
Console::WriteLine( "Default HTML page on {0} is:\r\n{1}", hostString1, pageContent );
}
// </Snippet3>
// </Snippet2>
// </Snippet1>
Console::Write( "\n\n\nPlease enter another INTRANET Url as shown[e.g. www.microsoft.com]: " );
String^ hostString2 = Console::ReadLine();
// <Snippet5>
// <Snippet6>
IPAddress^ hostIPAddress2 = (Dns::Resolve( hostString2 ))->AddressList[ 0 ];
hostIPEndPoint->Address = hostIPAddress2;
hostIPEndPoint->Port = 80;
getString = String::Format( "GET / HTTP/1.1\r\nHost: {0}\r\nConnection: Close\r\n\r\n", hostString2 );
pageContent = DoSocketGet( hostIPEndPoint, getString );
if ( pageContent != nullptr )
{
Console::WriteLine( "Default HTML page on {0} is:\r\n{1}", hostString2, pageContent );
}
// </Snippet6>
// </Snippet5>
}
catch ( SocketException^ e )
{
Console::WriteLine( "SocketException caught!!!" );
Console::WriteLine( "Source : {0}", e->Source );
Console::WriteLine( "Message : {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception caught!!!" );
Console::WriteLine( "Message : {0}", e->Message );
}
}
String^ DoSocketGet( IPEndPoint^ hostIPEndPoint, String^ getString )
{
try
{
// Set up variables and String to write to the server.
Encoding^ ASCII = Encoding::ASCII;
array<Byte>^ byteGet = ASCII->GetBytes( getString );
array<Byte>^ recvBytes = gcnew array<Byte>(256);
String^ strRetPage = nullptr;
// Create the Socket for sending data over TCP.
Socket^ mySocket = gcnew Socket( AddressFamily::InterNetwork,
SocketType::Stream,ProtocolType::Tcp );
// Connect to host using IPEndPoint.
mySocket->Connect( hostIPEndPoint );
// Send the GET text to the host.
mySocket->Send( byteGet, byteGet->Length, (SocketFlags)( 0 ) );
// Receive the page, loop until all bytes are received.
Int32 byteCount = mySocket->Receive( recvBytes, recvBytes->Length, (SocketFlags)( 0 ) );
strRetPage = String::Concat( strRetPage, ASCII->GetString( recvBytes, 0, byteCount ) );
while ( byteCount > 0 )
{
byteCount = mySocket->Receive( recvBytes, recvBytes->Length, (SocketFlags)( 0 ) );
strRetPage = String::Concat( strRetPage, ASCII->GetString( recvBytes, 0, byteCount ) );
}
return strRetPage;
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception : {0}", e->Message );
Console::WriteLine( "WinSock Error : {0}", Convert::ToString( Marshal::GetLastWin32Error() ) );
return nullptr;
}
}
| 40.064516
| 116
| 0.665056
|
BaruaSourav
|
fdb1bb6ce786592a5dfd812b86d11c07f08817ec
| 3,091
|
cc
|
C++
|
src/net/third_party/quiche/src/quic/tools/quic_toy_server.cc
|
btwiuse/naiveproxy
|
67852b0abc88e59d5853c4a5db47541f298fb469
|
[
"BSD-3-Clause"
] | 1
|
2019-11-05T05:26:53.000Z
|
2019-11-05T05:26:53.000Z
|
quic/tools/quic_toy_server.cc
|
fcharlie/quiche
|
56835aa2c2e3645e0eec85bff07f9d58e3bace63
|
[
"BSD-3-Clause"
] | null | null | null |
quic/tools/quic_toy_server.cc
|
fcharlie/quiche
|
56835aa2c2e3645e0eec85bff07f9d58e3bace63
|
[
"BSD-3-Clause"
] | null | null | null |
// 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 "net/third_party/quiche/src/quic/tools/quic_toy_server.h"
#include <utility>
#include <vector>
#include "net/third_party/quiche/src/quic/core/quic_versions.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_default_proof_providers.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
#include "net/third_party/quiche/src/quic/tools/quic_memory_cache_backend.h"
DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t,
port,
6121,
"The port the quic server will listen on.");
DEFINE_QUIC_COMMAND_LINE_FLAG(
std::string,
quic_response_cache_dir,
"",
"Specifies the directory used during QuicHttpResponseCache "
"construction to seed the cache. Cache directory can be "
"generated using `wget -p --save-headers <url>`");
DEFINE_QUIC_COMMAND_LINE_FLAG(
bool,
generate_dynamic_responses,
false,
"If true, then URLs which have a numeric path will send a dynamically "
"generated response of that many bytes.");
DEFINE_QUIC_COMMAND_LINE_FLAG(bool,
quic_ietf_draft,
false,
"Use the IETF draft version. This also enables "
"required internal QUIC flags.");
namespace quic {
std::unique_ptr<quic::QuicSimpleServerBackend>
QuicToyServer::MemoryCacheBackendFactory::CreateBackend() {
auto memory_cache_backend = std::make_unique<QuicMemoryCacheBackend>();
if (GetQuicFlag(FLAGS_generate_dynamic_responses)) {
memory_cache_backend->GenerateDynamicResponses();
}
if (!GetQuicFlag(FLAGS_quic_response_cache_dir).empty()) {
memory_cache_backend->InitializeBackend(
GetQuicFlag(FLAGS_quic_response_cache_dir));
}
return memory_cache_backend;
}
QuicToyServer::QuicToyServer(BackendFactory* backend_factory,
ServerFactory* server_factory)
: backend_factory_(backend_factory), server_factory_(server_factory) {}
int QuicToyServer::Start() {
ParsedQuicVersionVector supported_versions;
if (GetQuicFlag(FLAGS_quic_ietf_draft)) {
QuicVersionInitializeSupportForIetfDraft();
ParsedQuicVersion version(PROTOCOL_TLS1_3, QUIC_VERSION_99);
QuicEnableVersion(version);
supported_versions = {version};
} else {
supported_versions = AllSupportedVersions();
}
auto proof_source = quic::CreateDefaultProofSource();
auto backend = backend_factory_->CreateBackend();
auto server = server_factory_->CreateServer(
backend.get(), std::move(proof_source), supported_versions);
if (!server->CreateUDPSocketAndListen(quic::QuicSocketAddress(
quic::QuicIpAddress::Any6(), GetQuicFlag(FLAGS_port)))) {
return 1;
}
server->HandleEventsForever();
return 0;
}
} // namespace quic
| 35.94186
| 86
| 0.709479
|
btwiuse
|
fdb88e251cd9269f4c7ee441c391c7eb1f7f181d
| 1,715
|
cpp
|
C++
|
tests/ranges/wrappers.cpp
|
s0rav/spcppl
|
a17886c9082055490dab09c47a250accfadd8513
|
[
"WTFPL"
] | 30
|
2015-04-19T17:04:33.000Z
|
2022-03-22T13:26:53.000Z
|
tests/ranges/wrappers.cpp
|
s0rav/spcppl
|
a17886c9082055490dab09c47a250accfadd8513
|
[
"WTFPL"
] | 4
|
2018-05-27T18:20:10.000Z
|
2021-11-28T15:22:12.000Z
|
tests/ranges/wrappers.cpp
|
s0rav/spcppl
|
a17886c9082055490dab09c47a250accfadd8513
|
[
"WTFPL"
] | 8
|
2016-10-28T16:46:05.000Z
|
2021-02-24T16:49:20.000Z
|
#include <gtest/gtest.h>
#include <vector>
#include <spcppl/ranges/wrappers.hpp>
#include <spcppl/ranges/Range.hpp>
TEST(WrappersTest, Reversed) {
EXPECT_EQ(reversed(std::vector<int>{5, 7, 2, 3}), (std::vector<int>{3, 2, 7, 5}));
}
TEST(WrappersTest, Sorted) {
EXPECT_EQ(sorted(std::vector<int>{5, 7, 2, 3}), (std::vector<int>{2, 3, 5, 7}));
}
TEST(WrapperTest, SortedWithComparator) {
EXPECT_EQ(sorted(std::vector<int>{5, 7, 2, 3}, std::greater<int>()), (std::vector<int>{7, 5, 3, 2}));
}
TEST(WrapperTest, Unique) {
std::vector<int> v = {5, 7, 7, 7, 3};
unique(v);
EXPECT_EQ(v, (std::vector<int>{5, 7, 3}));
}
TEST(WrapperTest, UniquePreservesNotAdjascentElements) {
std::vector<int> v = {1, 2, 1};
std::vector<int> original_v = v;
unique(v);
EXPECT_EQ(v, original_v);
}
TEST(WrapperTest, FindsMaxElement) {
std::vector<int> v = {5, 7, 3};
EXPECT_EQ(*max_element(v), 7);
}
TEST(WrapperTest, MaxOfEmptyRangeIsBegin) {
std::vector<int> v;
EXPECT_EQ(max_element(v), v.begin());
}
TEST(WrapperTest, FindsMinElement) {
std::vector<int> v = {5, 7, 3};
EXPECT_EQ(*min_element(v), 3);
}
TEST(WrapperTest, MinOfEmptyRangeIsBegin) {
std::vector<int> v;
EXPECT_EQ(min_element(v), v.begin());
}
TEST(WrapperTest, FindsMaxOfPartOfRange) {
std::vector<int> v = {100, 1, 2, 5, 0, 15, -1};
EXPECT_EQ(*max_element(make_range(v.begin() + 1, v.begin() + 4)), 5);
}
TEST(WrappersTest, FindsNextPermutation) {
std::vector<int> v = {1, 3, 2};
EXPECT_TRUE(next_permutation(v));
EXPECT_EQ(v, (std::vector<int>{2, 1, 3}));
}
TEST(WrappersTest, NextPermuationCyclesAfterLastPermutation) {
std::vector<int> v = {3, 2, 1};
EXPECT_FALSE(next_permutation(v));
EXPECT_EQ(v, (std::vector<int>{1, 2, 3}));
}
| 25.597015
| 102
| 0.662974
|
s0rav
|
fdb9b06bf5f7c550eaf00083038d44ebe9096470
| 4,343
|
hpp
|
C++
|
libraries/fc/include/fc/container/flat.hpp
|
Laighno/evt
|
90b94e831aebb62c6ad19ce59c9089e9f51cfd77
|
[
"MIT"
] | 1,411
|
2018-04-23T03:57:30.000Z
|
2022-02-13T10:34:22.000Z
|
libraries/fc/include/fc/container/flat.hpp
|
Zhang-Zexi/evt
|
e90fe4dbab4b9512d120c79f33ecc62791e088bd
|
[
"Apache-2.0"
] | 27
|
2018-06-11T10:34:42.000Z
|
2019-07-27T08:50:02.000Z
|
libraries/fc/include/fc/container/flat.hpp
|
Zhang-Zexi/evt
|
e90fe4dbab4b9512d120c79f33ecc62791e088bd
|
[
"Apache-2.0"
] | 364
|
2018-06-09T12:11:53.000Z
|
2020-12-15T03:26:48.000Z
|
#pragma once
#include <fc/variant.hpp>
#include <fc/container/flat_fwd.hpp>
#include <fc/container/container_detail.hpp>
#include <fc/crypto/hex.hpp>
namespace fc {
namespace raw {
template<typename Stream, typename T, typename A>
void
pack(Stream& s, const boost::container::vector<T, A>& value) {
FC_ASSERT(value.size() <= MAX_NUM_ARRAY_ELEMENTS);
pack(s, unsigned_int((uint32_t)value.size()));
if(!std::is_fundamental<T>::value) {
for(const auto& item : value) {
pack(s, item);
}
}
else if(value.size()) {
s.write((const char*)value.data(), value.size());
}
}
template<typename Stream, typename T, typename A>
void
unpack(Stream& s, boost::container::vector<T, A>& value) {
unsigned_int size;
unpack(s, size);
FC_ASSERT(size.value <= MAX_NUM_ARRAY_ELEMENTS);
value.clear();
value.resize(size.value);
if(!std::is_fundamental<T>::value) {
for(auto& item : value) {
unpack(s, item);
}
}
else if(value.size()) {
s.read((char*)value.data(), value.size());
}
}
template<typename Stream, typename A>
void
pack(Stream& s, const boost::container::vector<char, A>& value) {
FC_ASSERT(value.size() <= MAX_SIZE_OF_BYTE_ARRAYS);
pack(s, unsigned_int((uint32_t)value.size()));
if(value.size())
s.write((const char*)value.data(), value.size());
}
template<typename Stream, typename A>
void
unpack(Stream& s, boost::container::vector<char, A>& value) {
unsigned_int size;
unpack(s, size);
FC_ASSERT(size.value <= MAX_SIZE_OF_BYTE_ARRAYS);
value.clear();
value.resize(size.value);
if(value.size())
s.read((char*)value.data(), value.size());
}
template<typename Stream, typename T, typename... U>
void
pack(Stream& s, const flat_set<T, U...>& value) {
detail::pack_set(s, value);
}
template<typename Stream, typename T, typename... U>
void
unpack(Stream& s, flat_set<T, U...>& value) {
detail::unpack_flat_set(s, value);
}
template<typename Stream, typename K, typename V, typename... U>
void
pack(Stream& s, const flat_map<K, V, U...>& value) {
detail::pack_map(s, value);
}
template<typename Stream, typename K, typename V, typename... U>
void
unpack(Stream& s, flat_map<K, V, U...>& value) {
detail::unpack_flat_map(s, value);
}
} // namespace raw
template<typename T, typename... U>
void
to_variant(const boost::container::vector<T, U...>& vec, fc::variant& vo) {
FC_ASSERT(vec.size() <= MAX_NUM_ARRAY_ELEMENTS);
variants vars;
vars.reserve(vec.size());
for(const auto& item : vec) {
vars.emplace_back(item);
}
vo = std::move(vars);
}
template<typename T, typename... U>
void
from_variant(const fc::variant& v, boost::container::vector<T, U...>& vec) {
const variants& vars = v.get_array();
FC_ASSERT(vars.size() <= MAX_NUM_ARRAY_ELEMENTS);
vec.clear();
vec.resize(vars.size());
for(uint32_t i = 0; i < vars.size(); ++i) {
from_variant(vars[i], vec[i]);
}
}
template<typename... U>
void
to_variant(const boost::container::vector<char, U...>& vec, fc::variant& vo) {
FC_ASSERT(vec.size() <= MAX_SIZE_OF_BYTE_ARRAYS);
if(vec.size())
vo = variant(fc::to_hex(vec.data(), vec.size()));
else
vo = "";
}
template<typename... U>
void
from_variant(const fc::variant& v, boost::container::vector<char, U...>& vec) {
const auto& str = v.get_string();
FC_ASSERT(str.size() <= 2 * MAX_SIZE_OF_BYTE_ARRAYS); // Doubled because hex strings needs two characters per byte
vec.resize(str.size() / 2);
if(vec.size()) {
size_t r = fc::from_hex(str, vec.data(), vec.size());
FC_ASSERT(r == vec.size());
}
}
template<typename T, typename... U>
void
to_variant(const flat_set<T, U...>& s, fc::variant& vo) {
detail::to_variant_from_set(s, vo);
}
template<typename T, typename... U>
void
from_variant(const fc::variant& v, flat_set<T, U...>& s) {
detail::from_variant_to_flat_set(v, s);
}
template<typename K, typename V, typename... U>
void
to_variant(const flat_map<K, V, U...>& m, fc::variant& vo) {
detail::to_variant_from_map(m, vo);
}
template<typename K, typename V, typename... U>
void
from_variant(const variant& v, flat_map<K, V, U...>& m) {
detail::from_variant_to_flat_map(v, m);
}
} // namespace fc
| 26.975155
| 119
| 0.638729
|
Laighno
|
fdbac7b8eb60f180a6ca5e891dbe15ee393486fd
| 801
|
cc
|
C++
|
0389_Find_the_Difference/0389.cc
|
LuciusKyle/LeetCode
|
66c9090e5244b10eca0be50398764da2b4b48a6c
|
[
"Apache-2.0"
] | null | null | null |
0389_Find_the_Difference/0389.cc
|
LuciusKyle/LeetCode
|
66c9090e5244b10eca0be50398764da2b4b48a6c
|
[
"Apache-2.0"
] | null | null | null |
0389_Find_the_Difference/0389.cc
|
LuciusKyle/LeetCode
|
66c9090e5244b10eca0be50398764da2b4b48a6c
|
[
"Apache-2.0"
] | null | null | null |
#include <string>
using std::string;
class Solution {
public:
char findTheDifference(const string s, const string t) {
size_t dict_s[26] = {0};
size_t dict_t[26] = {0};
for (const char ch : s) ++dict_s[ch - 'a'];
for (const char ch : t) ++dict_t[ch - 'a'];
for (size_t i = 0; i < 26; ++i)
if (dict_s[i] != dict_t[i]) return static_cast<char>(i + 'a');
return '?';
}
private:
char moreGeneralFunction(const string s, const string t) {
size_t dict_s[0x100] = {0};
size_t dict_t[0x100] = {0};
for (const char ch : s) ++dict_s[ch];
for (const char ch : t) ++dict_t[ch];
for (size_t i = 0; i < 0x100; ++i)
if (dict_s[i] != dict_t[i]) return static_cast<char>(i);
return '?';
}
};
int main(void) {
Solution sln;
return 0;
}
| 23.558824
| 68
| 0.569288
|
LuciusKyle
|
fdc16a9ddcdc7a213723934395290ff533153525
| 4,708
|
hpp
|
C++
|
include/lexer/Lexer.hpp
|
SimplyDanny/bitsy-llvm
|
125e404388ef65847eac8cb533c5321a2289bb85
|
[
"MIT"
] | 4
|
2021-01-07T10:29:49.000Z
|
2021-07-17T22:10:54.000Z
|
include/lexer/Lexer.hpp
|
SimplyDanny/bitsy-llvm
|
125e404388ef65847eac8cb533c5321a2289bb85
|
[
"MIT"
] | null | null | null |
include/lexer/Lexer.hpp
|
SimplyDanny/bitsy-llvm
|
125e404388ef65847eac8cb533c5321a2289bb85
|
[
"MIT"
] | 2
|
2021-02-07T21:15:20.000Z
|
2021-07-17T22:10:55.000Z
|
#ifndef LEXER_HPP
#define LEXER_HPP
#include "lexer/Token.hpp"
#include "llvm/ADT/StringSwitch.h"
#include <functional>
#include <iterator>
#include <memory>
#include <optional>
#include <string>
#include <type_traits>
template <class InputIterator>
class Lexer : public std::iterator<std::input_iterator_tag, Token> {
static_assert(std::is_same<typename std::iterator_traits<InputIterator>::value_type, char>(),
"Expecting iterator over 'char' type.");
InputIterator current_character;
InputIterator characters_end;
std::optional<Token> current_token;
public:
Lexer(InputIterator begin, InputIterator end);
Lexer() = default;
Token operator*() const;
Token &operator++();
Token operator++(int);
bool operator==(const Lexer &other) const;
bool operator!=(const Lexer &other) const;
private:
std::optional<Token> next();
template <class TokenMatcher>
std::string get_while_matching(const TokenMatcher &matcher);
static bool is_operator(char c);
static bool is_identifier(char c);
};
template <class InputIterator>
Lexer<InputIterator>::Lexer(InputIterator begin, InputIterator end)
: current_character(begin)
, characters_end(end) {
if (current_character != characters_end) {
++(*this);
}
}
template <class InputIterator>
Token Lexer<InputIterator>::operator*() const {
return *current_token;
}
template <class InputIterator>
Token &Lexer<InputIterator>::operator++() {
return *(current_token = next());
}
template <class InputIterator>
Token Lexer<InputIterator>::operator++(int) {
auto tmp_token = std::move(current_token);
++(*this);
return *tmp_token;
}
template <class InputIterator>
bool Lexer<InputIterator>::operator==(const Lexer &other) const {
return current_token.has_value() == other.current_token.has_value();
}
template <class InputIterator>
bool Lexer<InputIterator>::operator!=(const Lexer &other) const {
return !(*this == other);
}
template <class InputIterator>
std::optional<Token> Lexer<InputIterator>::next() {
while (current_character != characters_end) {
if (isspace(*current_character) != 0) {
++current_character;
} else if (isdigit(*current_character) != 0) {
return Token(TokenType::number_t, get_while_matching(isdigit));
} else if (is_operator(*current_character)) {
return Token(TokenType::operator_t, get_while_matching(is_operator));
} else if (*current_character == '=') {
return Token(TokenType::assignment_t, *current_character++);
} else if (*current_character == '(') {
return Token(TokenType::left_parenthesis_t, *current_character++);
} else if (*current_character == ')') {
return Token(TokenType::right_parenthesis_t, *current_character++);
} else if (is_identifier(*current_character)) {
auto token = get_while_matching(is_identifier);
auto token_type = llvm::StringSwitch<TokenType>(token)
.Case("BEGIN", TokenType::begin_t)
.Case("END", TokenType::end_t)
.Case("LOOP", TokenType::loop_t)
.Case("BREAK", TokenType::break_t)
.Case("IFN", TokenType::ifn_t)
.Case("IFP", TokenType::ifp_t)
.Case("IFZ", TokenType::ifz_t)
.Case("ELSE", TokenType::else_t)
.Case("PRINT", TokenType::print_t)
.Case("READ", TokenType::read_t)
.Default(TokenType::variable_t);
return Token(token_type, token);
} else if (*current_character == '{') {
current_character = std::next(std::find(current_character, characters_end, '}'));
} else {
throw std::logic_error("Cannot handle the current character.");
}
}
return {};
}
template <class InputIterator>
template <class TokenMatcher>
std::string Lexer<InputIterator>::get_while_matching(const TokenMatcher &matcher) {
std::string value;
do {
value += *current_character++;
} while (current_character != characters_end && matcher(*current_character));
return value;
}
template <class InputIterator>
bool Lexer<InputIterator>::is_operator(const char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}
template <class InputIterator>
bool Lexer<InputIterator>::is_identifier(const char c) {
return (isalnum(c) != 0) || c == '_';
}
#endif
| 33.390071
| 97
| 0.618946
|
SimplyDanny
|
fdc1f14823cc3a1f4f4ad1278b3248f8f397dd0c
| 7,593
|
cpp
|
C++
|
earth_enterprise/src/fusion/khrasterize/rasterize.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 2,661
|
2017-03-20T22:12:50.000Z
|
2022-03-30T09:43:19.000Z
|
earth_enterprise/src/fusion/khrasterize/rasterize.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 1,531
|
2017-03-24T17:20:32.000Z
|
2022-03-16T18:11:14.000Z
|
earth_enterprise/src/fusion/khrasterize/rasterize.cpp
|
ezeeyahoo/earthenterprise
|
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
|
[
"Apache-2.0"
] | 990
|
2017-03-24T11:54:28.000Z
|
2022-03-22T11:51:47.000Z
|
// Copyright 2017 Google 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 "rasterize.h"
#include <stdio.h>
using namespace std;
// Global declarations
bool g_verbose = true;
typedef vector<VPoints> VVPoints;
struct InternalGrid {
double xmin;
double ymin;
double resolution;
int rows;
int cols;
VVPoints points;
};
void ComputeXYBounds(VPoints& points,
double resolution,
InternalGrid& internalGrid)
{
double xmin, xmax, ymin, ymax;
xmin = ymin = INFINITY;
xmax = ymax = -INFINITY;
int numPoints = points.size();
int i;
for(i=0; i<numPoints; i++) {
if (points[i].x < xmin) {
xmin = points[i].x;
}
if (points[i].y < ymin) {
ymin = points[i].y;
}
if (points[i].x > xmax) {
xmax = points[i].x;
}
if (points[i].y > ymax) {
ymax = points[i].y;
}
}
int rows = (int)ceil(double(ymax - ymin)/resolution + 1);
int cols = (int)ceil(double(xmax - xmin)/resolution + 1);
internalGrid.xmin = xmin;
internalGrid.ymin = ymin;
internalGrid.resolution = resolution;
internalGrid.rows = rows;
internalGrid.cols = cols;
return;
}
InternalGrid CreateXYMesh( VPoints points,
double resolution)
{
InternalGrid internalGrid;
ComputeXYBounds(points, resolution, internalGrid);
if (g_verbose) {
fprintf(stdout, "Rows: %d\n", internalGrid.rows);
fprintf(stdout, "Cols: %d\n", internalGrid.cols);
}
int i, j;
for (i=0; i<internalGrid.rows; i++) {
VPoints row;
for (j=0; j<internalGrid.cols; j++) {
Point aPoint = {internalGrid.xmin + j*resolution, internalGrid.ymin + i*resolution, 0};
row.push_back(aPoint);
}
internalGrid.points.push_back(row);
}
return internalGrid;
}
inline double Compute2DDistance(Point a, Point b)
{
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
int FindNearestPoint(VPoints& points,
Point aPoint)
{
int index=0;
double minDistance = INFINITY;
int numPoints = points.size();
int i;
for (i=0; i<numPoints; i++) {
double distance = Compute2DDistance(points[i], aPoint);
if (distance < minDistance) {
minDistance = distance;
index = i;
}
}
return index;
}
double FindNeighboringGridPoint(InternalGrid& internalGrid,
VVDouble& minDistanceGrid,
int row,
int col,
int radius )
{
int i, j;
double minDist=INFINITY;
double distance;
double minZ = KH_MISSING_ZVALUE;
for (i=row-(radius-1); i<row+radius; i++) {
if (i<0 || i>=internalGrid.rows) {
continue;
}
for (j=col-(radius-1); j<col+radius; j++) {
if (j<0 || j>=internalGrid.cols) {
continue;
}
if (minDistanceGrid[i][j] < INFINITY) {
distance = i*i + j*j;
if (distance < minDist) {
minZ = internalGrid.points[i][j].z;
}
}
}
}
return minZ;
}
void RasterizeNearest(VPoints& points,
InternalGrid& internalGrid,
int fillRadius=3)
{
VVDouble minDistanceGrid;
// initalize the minimum distance grid
int i, j;
VDouble row;
row.resize(internalGrid.cols*sizeof(double));
for (j=0; j<internalGrid.cols; j++) {
row[j] = INFINITY;
}
for (i=0; i<internalGrid.rows; i++) {
minDistanceGrid.push_back(row);
}
int numPoints = points.size();
double xd, yd;
int cx, cy, fx, fy;
for (i=0; i<numPoints; i++) {
// find the index of the 4 grid points
// surrounding the point
xd = (points[i].x - internalGrid.xmin) / internalGrid.resolution;
cx = (int)ceil(xd);
fx = (int)floor(xd);
yd = (points[i].y - internalGrid.ymin) / internalGrid.resolution;
cy = (int)ceil(yd);
fy = (int)floor(yd);
// this point will affect all 4 points surrounding it
int xarr[] = {fx, cx, fx, cx};
int yarr[] = {fy, fy, cy, cy};
int k;
int xi, yi;
for(k=0; k<4; k++) {
xi = xarr[k];
yi = yarr[k];
double distance = Compute2DDistance(points[i], internalGrid.points[yi][xi]);
if (distance < minDistanceGrid[yi][xi]) {
minDistanceGrid[yi][xi] = distance;
internalGrid.points[yi][xi].z = points[i].z;
}
}
}
int ip=0;
const int progStep = 10;
double dp=0;
if (g_verbose) {
fprintf(stdout, "0");
}
/*
for (i=0; i<internalGrid.rows; i++) {
for (j=0; j<internalGrid.cols; j++) {
if (minDistanceGrid[i][j] < INFINITY) {
continue;
}
int index = FindNearestPoint(points, internalGrid.points[i][j]);
internalGrid.points[i][j].z = points[index].z;
}
if (g_verbose) {
dp += 100.0/double(internalGrid.rows-1);
if ((int(dp) % progStep == 0) && int(dp) != ip) {
ip += progStep;
fprintf(stdout, "..%d", ip);
}
}
}
*/
for (i=0; i<internalGrid.rows; i++) {
for (j=0; j<internalGrid.cols; j++) {
if (minDistanceGrid[i][j] < INFINITY) {
continue;
}
internalGrid.points[i][j].z = FindNeighboringGridPoint(internalGrid, minDistanceGrid, i, j, fillRadius);
}
if (g_verbose) {
dp += 100.0/double(internalGrid.rows-1);
if ((int(dp) % progStep == 0) && int(dp) != ip) {
ip += progStep;
fprintf(stdout, "..%d", ip);
}
}
}
fprintf(stdout, "\n");
return;
}
void RasterizeLinear(VPoints& points,
InternalGrid& internalGrid)
{
fprintf(stderr, "Notice: Only Nearest Neighbor Interpolation implemented so far\n");
RasterizeNearest(points, internalGrid);
return;
}
Grid Rasterize( VPoints points,
double resolution,
int fillRadius,
int method,
bool verbose)
{
Grid grid;
int numPoints = points.size();
if (numPoints <= 3) {
fprintf(stderr, "Error: Insufficient points\n");
return grid;
}
if (resolution <= 0) {
fprintf(stderr, "Error: Bad resolution\n");
return grid;
}
g_verbose = verbose;
// Create the XY mesh
InternalGrid internalGrid = CreateXYMesh(points, resolution);
// Now compute z values based on one of the
// following methods
switch (method) {
case INTP_NEAREST:
RasterizeNearest(points, internalGrid, fillRadius);
break;
case INTP_LINEAR:
RasterizeLinear(points, internalGrid);
break;
}
grid.rows = internalGrid.rows;
grid.cols = internalGrid.cols;
grid.xmin = internalGrid.xmin;
grid.ymin = internalGrid.ymin;
grid.resolution = internalGrid.resolution;
int i,j;
for (i=0; i<internalGrid.rows; i++) {
VDouble row;
for (j=0; j<internalGrid.cols; j++) {
row.push_back(internalGrid.points[i][j].z);
}
grid.z.push_back(row);
}
return grid;
}
| 24.493548
| 110
| 0.577769
|
ezeeyahoo
|
fdc3e2fbb8cf0213ea786cef0fd23f787a193aef
| 2,176
|
cpp
|
C++
|
vector_version/iRein/rein.cpp
|
shiwanghua/matching-algorithm
|
a09714b76d8722a7891b72f4740948814369b40e
|
[
"MIT"
] | 14
|
2019-01-18T12:56:27.000Z
|
2020-12-09T12:31:21.000Z
|
vector_version/iRein/rein.cpp
|
shiwanghua/matching-algorithm
|
a09714b76d8722a7891b72f4740948814369b40e
|
[
"MIT"
] | null | null | null |
vector_version/iRein/rein.cpp
|
shiwanghua/matching-algorithm
|
a09714b76d8722a7891b72f4740948814369b40e
|
[
"MIT"
] | 8
|
2019-03-11T13:22:32.000Z
|
2021-04-27T04:18:57.000Z
|
#include "rein.h"
void Rein::insert(IntervalSub sub)
{
for (int i = 0; i < sub.size; i++)
{
IntervalCnt cnt = sub.constraints.at(i);
Combo c;
c.val = cnt.lowValue;
c.subID = sub.id;
data[cnt.att][0][c.val / buckStep].push_back(c);
c.val = cnt.highValue;
data[cnt.att][1][c.val / buckStep].push_back(c);
}
}
void Rein::match(const Pub &pub, int &matchSubs, const vector<IntervalSub> &subList, int x)
{
Timer subStart;
vector<bool> bits (subList.size(), false);
for (int i = 0; i < pub.size; i++)
{
int value = pub.pairs[i].value, att = pub.pairs[i].att, buck = value / buckStep;
int upper = min(bucks, buck + x);
int lower = max(0, buck - x);
for (int k = 0; k < data[att][0][buck].size(); k++)
if (data[att][0][buck].at(k).val > value)
bits.at(data[att][0][buck].at(k).subID) = true;
for (int j = buck + 1; j < upper; j++)
for (int k = 0; k < data[att][0][j].size(); k++)
bits.at(data[att][0][j].at(k).subID) = true;
for (int k = 0; k < data[att][1][buck].size(); k++)
if (data[att][1][buck].at(k).val < value)
bits.at(data[att][1][buck].at(k).subID) = true;
for (int j = buck - 1; j >= lower; j--)
for (int k = 0; k < data[att][1][j].size(); k++)
bits.at(data[att][1][j].at(k).subID) = true;
}
int att2value[MAX_ATTS];
for (int i = 0; i < pub.size; i ++)
att2value[pub.pairs.at(i).att] = pub.pairs.at(i).value;
for (int i = 0; i < subList.size(); i++)
if (!bits.at(i))
{
IntervalSub sub = subList.at(i);
bool flag = true;
for (int j = 0; j < sub.size; j ++)
{
int att = sub.constraints.at(j).att, pub_value = att2value[att];
if (pub_value < sub.constraints.at(j).lowValue || pub_value > sub.constraints.at(j).highValue)
{
flag = false;
break;
}
}
if (flag)
++ matchSubs;
}
}
| 32.969697
| 110
| 0.472886
|
shiwanghua
|
fdc5bfdbe96aa0f222ba2f7c68a1225e1bf52b25
| 4,835
|
hpp
|
C++
|
libs/ledger/include/ledger/storage_unit/storage_unit_client.hpp
|
baykaner/ledger
|
f45fbd49297a419e3a90a46e9aed0cfa65602109
|
[
"Apache-2.0"
] | null | null | null |
libs/ledger/include/ledger/storage_unit/storage_unit_client.hpp
|
baykaner/ledger
|
f45fbd49297a419e3a90a46e9aed0cfa65602109
|
[
"Apache-2.0"
] | null | null | null |
libs/ledger/include/ledger/storage_unit/storage_unit_client.hpp
|
baykaner/ledger
|
f45fbd49297a419e3a90a46e9aed0cfa65602109
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "core/future_timepoint.hpp"
#include "core/logging.hpp"
#include "core/service_ids.hpp"
#include "crypto/merkle_tree.hpp"
#include "ledger/shard_config.hpp"
#include "ledger/storage_unit/lane_connectivity_details.hpp"
#include "ledger/storage_unit/lane_identity.hpp"
#include "ledger/storage_unit/lane_identity_protocol.hpp"
#include "ledger/storage_unit/lane_service.hpp"
#include "ledger/storage_unit/storage_unit_interface.hpp"
#include "network/generics/backgrounded_work.hpp"
#include "network/generics/has_worker_thread.hpp"
#include "network/management/connection_register.hpp"
#include "network/muddle/muddle.hpp"
#include "network/muddle/rpc/client.hpp"
#include "network/muddle/rpc/server.hpp"
#include "network/service/service_client.hpp"
#include "storage/document_store_protocol.hpp"
#include "storage/object_stack.hpp"
#include "storage/object_store_protocol.hpp"
#include <array>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <exception>
#include <memory>
#include <string>
#include <vector>
namespace fetch {
namespace ledger {
class StorageUnitClient final : public StorageUnitInterface
{
public:
using MuddleEndpoint = muddle::MuddleEndpoint;
using Address = MuddleEndpoint::Address;
static constexpr char const *LOGGING_NAME = "StorageUnitClient";
// Construction / Destruction
StorageUnitClient(MuddleEndpoint &muddle, ShardConfigs const &shards, uint32_t log2_num_lanes);
StorageUnitClient(StorageUnitClient const &) = delete;
StorageUnitClient(StorageUnitClient &&) = delete;
~StorageUnitClient() override = default;
// Helpers
uint32_t num_lanes() const;
/// @name Storage Unit Interface
/// @{
void AddTransaction(Transaction const &tx) override;
bool GetTransaction(ConstByteArray const &digest, Transaction &tx) override;
bool HasTransaction(ConstByteArray const &digest) override;
void IssueCallForMissingTxs(DigestSet const &tx_set) override;
TxLayouts PollRecentTx(uint32_t max_to_poll) override;
Document GetOrCreate(ResourceAddress const &key) override;
Document Get(ResourceAddress const &key) override;
void Set(ResourceAddress const &key, StateValue const &value) override;
Keys KeyDump() const override;
void Reset() override;
// state hash functions
byte_array::ConstByteArray CurrentHash() override;
byte_array::ConstByteArray LastCommitHash() override;
bool RevertToHash(Hash const &hash, uint64_t index) override;
byte_array::ConstByteArray Commit(uint64_t index) override;
bool HashExists(Hash const &hash, uint64_t index) override;
bool Lock(ShardIndex index) override;
bool Unlock(ShardIndex index) override;
/// @}
StorageUnitClient &operator=(StorageUnitClient const &) = delete;
StorageUnitClient &operator=(StorageUnitClient &&) = delete;
private:
using Client = muddle::rpc::Client;
using ClientPtr = std::shared_ptr<Client>;
using LaneIndex = LaneIdentity::lane_type;
using AddressList = std::vector<MuddleEndpoint::Address>;
using MerkleTree = crypto::MerkleTree;
using PermanentMerkleStack = fetch::storage::ObjectStack<crypto::MerkleTree>;
static constexpr char const *MERKLE_FILENAME_DOC = "merkle_stack.db";
static constexpr char const *MERKLE_FILENAME_INDEX = "merkle_stack_index.db";
Address const &LookupAddress(ShardIndex shard) const;
Address const &LookupAddress(storage::ResourceID const &resource) const;
bool HashInStack(Hash const &hash, uint64_t index);
/// @name Client Information
/// @{
AddressList const addresses_;
uint32_t const log2_num_lanes_ = 0;
ClientPtr rpc_client_;
/// @}
/// @name State Hash Support
/// @{
mutable Mutex merkle_mutex_;
MerkleTree current_merkle_;
PermanentMerkleStack permanent_state_merkle_stack_{};
/// @}
};
} // namespace ledger
} // namespace fetch
| 36.908397
| 97
| 0.706101
|
baykaner
|
fdc6621e2f738b0a2c93f23596b3172bab14487e
| 1,977
|
hpp
|
C++
|
sprout/container/get_deep_internal.hpp
|
kariya-mitsuru/Sprout
|
8274f34db498b02bff12277bac5416ea72e018cd
|
[
"BSL-1.0"
] | null | null | null |
sprout/container/get_deep_internal.hpp
|
kariya-mitsuru/Sprout
|
8274f34db498b02bff12277bac5416ea72e018cd
|
[
"BSL-1.0"
] | null | null | null |
sprout/container/get_deep_internal.hpp
|
kariya-mitsuru/Sprout
|
8274f34db498b02bff12277bac5416ea72e018cd
|
[
"BSL-1.0"
] | null | null | null |
/*=============================================================================
Copyright (c) 2011-2017 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP
#define SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/container/get_internal.hpp>
#include <sprout/container/deep_internal.hpp>
#include <sprout/container/is_sub_container.hpp>
#include <sprout/utility/forward.hpp>
#include <sprout/type_traits/enabler_if.hpp>
namespace sprout {
namespace detail {
template<
typename Container,
typename sprout::enabler_if<!sprout::containers::is_sub_container<Container>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type
get_deep_internal_impl(Container&& cont) {
return SPROUT_FORWARD(Container, cont);
}
template<
typename Container,
typename sprout::enabler_if<sprout::containers::is_sub_container<Container>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type
get_deep_internal_impl(Container&& cont) {
return sprout::detail::get_deep_internal_impl(
sprout::get_internal(SPROUT_FORWARD(Container, cont))
);
}
} // namespace detail
//
// get_deep_internal
//
template<typename Container>
inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type
get_deep_internal(Container&& cont) {
return sprout::detail::get_deep_internal_impl(SPROUT_FORWARD(Container, cont));
}
} // namespace sprout
#endif // #ifndef SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP
| 38.764706
| 112
| 0.70258
|
kariya-mitsuru
|
fdc67f8895c7a8de79e71dda14028b09ba9f5f19
| 2,660
|
cpp
|
C++
|
src/Examples/RouteSimulationAnimation/RouteSimulationAnimationExampleFactory.cpp
|
wrld3d/eegeo-sdk-samples
|
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
|
[
"BSD-2-Clause"
] | 11
|
2017-06-26T08:59:03.000Z
|
2021-09-28T13:12:22.000Z
|
src/Examples/RouteSimulationAnimation/RouteSimulationAnimationExampleFactory.cpp
|
wrld3d/eegeo-sdk-samples
|
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
|
[
"BSD-2-Clause"
] | 4
|
2016-07-09T14:54:22.000Z
|
2017-04-26T14:02:53.000Z
|
src/Examples/RouteSimulationAnimation/RouteSimulationAnimationExampleFactory.cpp
|
wrld3d/eegeo-sdk-samples
|
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
|
[
"BSD-2-Clause"
] | 9
|
2016-04-08T03:43:13.000Z
|
2016-12-12T02:07:49.000Z
|
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved
#include "RouteSimulationAnimationExampleFactory.h"
#include "RouteSimulationAnimationExample.h"
#include "LocalAsyncTextureLoader.h"
#include "RenderContext.h"
#include "CollisionMeshResourceRepository.h"
#include "MapModule.h"
#include "TerrainModelModule.h"
#include "RoutesModule.h"
#include "RenderingModule.h"
#include "IPlatformAbstractionModule.h"
#include "AsyncLoadersModule.h"
#include "SceneModelsModule.h"
namespace Examples
{
RouteSimulationAnimationExampleFactory::RouteSimulationAnimationExampleFactory(Eegeo::EegeoWorld& world,
DefaultCameraControllerFactory& defaultCameraControllerFactory,
Eegeo::Camera::GlobeCamera::GlobeCameraTouchController& globeCameraTouchController,
const IScreenPropertiesProvider& screenPropertiesProvider)
: m_world(world)
, m_screenPropertiesProvider(screenPropertiesProvider)
, m_pRouteSimulationGlobeCameraControllerFactory(NULL)
{
Eegeo::Modules::Map::MapModule& mapModule = m_world.GetMapModule();
Eegeo::Modules::Map::Layers::TerrainModelModule& terrainModelModule = m_world.GetTerrainModelModule();
m_pRouteSimulationGlobeCameraControllerFactory = new Eegeo::Routes::Simulation::Camera::RouteSimulationGlobeCameraControllerFactory
(
terrainModelModule.GetTerrainHeightProvider(),
mapModule.GetEnvironmentFlatteningService(),
mapModule.GetResourceCeilingProvider(),
terrainModelModule.GetTerrainCollisionMeshResourceRepository()
);
}
RouteSimulationAnimationExampleFactory::~RouteSimulationAnimationExampleFactory()
{
delete m_pRouteSimulationGlobeCameraControllerFactory;
}
IExample* RouteSimulationAnimationExampleFactory::CreateExample() const
{
Eegeo::Modules::RoutesModule& routesModule = m_world.GetRoutesModule();
Eegeo::Modules::Core::SceneModelsModule& sceneModelsModule = m_world.GetCoreModule().GetSceneModelsModule();
return new Examples::RouteSimulationAnimationExample(routesModule.GetRouteService(),
routesModule.GetRouteSimulationService(),
routesModule.GetRouteSimulationViewService(),
sceneModelsModule.GetLocalModelLoader(),
*m_pRouteSimulationGlobeCameraControllerFactory,
m_screenPropertiesProvider,
m_world);
}
std::string RouteSimulationAnimationExampleFactory::ExampleName() const
{
return Examples::RouteSimulationAnimationExample::GetName();
}
}
| 40.30303
| 162
| 0.735714
|
wrld3d
|
fdc6ddc3909e7f24bf93a655ebf075562f6b5a18
| 5,084
|
cpp
|
C++
|
samples/03_sdp/2019-20_kn/stacks/rpn.cpp
|
code-hunger/lecture-notes
|
0200c57a4c2539b4d8b7cb172c2b6e4f5c689268
|
[
"MIT"
] | 32
|
2016-11-24T01:40:21.000Z
|
2021-11-01T19:24:22.000Z
|
samples/03_sdp/2019-20_kn/stacks/rpn.cpp
|
code-hunger/lecture-notes
|
0200c57a4c2539b4d8b7cb172c2b6e4f5c689268
|
[
"MIT"
] | 6
|
2016-10-15T05:57:00.000Z
|
2021-08-13T12:29:24.000Z
|
samples/03_sdp/2019-20_kn/stacks/rpn.cpp
|
code-hunger/lecture-notes
|
0200c57a4c2539b4d8b7cb172c2b6e4f5c689268
|
[
"MIT"
] | 49
|
2016-01-26T13:36:02.000Z
|
2022-03-16T10:24:41.000Z
|
#include <iostream>
#include <stack>
#include <cassert>
#include <vector>
#include <sstream>
bool isdigit (char c)
{
return c >= '0' && c <= '9';
}
int apply (char op, int x, int y)
{
switch (op)
{
case '+': return x+y;
case '*': return x*y;
default: assert (false);
}
return 0;
}
void killwhite (std::istream &in)
{
while (in.peek () == ' ' || in.peek() == '\n')
{
in.get();
}
}
int calcrpp (std::istream &in)
{
killwhite (in);
std::stack <int> s;
while (in.peek() != ';')
{
if (isdigit (in.peek()))
{
int arg;
in >> arg;
s.push (arg);
} else {
char op = in.get();
assert (s.size() >= 2);
int larg = s.top(); s.pop();
int rarg = s.top(); s.pop();
s.push (apply(op,larg,rarg));
}
killwhite (in);
}
assert (s.size() == 1);
return s.top();
}
struct Token
{
int type;
static const int NUM = 0;
static const int OPER = 1;
static const int LPAR = 2;
static const int RPAR = 3;
int val;
char op;
};
int priority (char op)
{
switch (op)
{
case '*': return 10;
case '+': return 5;
default: assert (false);
}
return 0;
}
std::vector<Token> makerpn (std::istream &in)
{
std::vector<Token> result;
std::stack<Token> s;
killwhite (in);
while (in.peek() != ';')
{
Token next;
if (isdigit (in.peek()))
{
next.type = Token::NUM;
in >> next.val;
result.push_back (next);
} else if (in.peek() == '(')
{
next.type = Token::LPAR;
s.push (next);
in.get();
} else if (in.peek() == ')')
{
in.get();
while (s.size() >= 1 &&
s.top().type != Token::LPAR)
{
next = s.top(); s.pop();
result.push_back (next);
assert (next.type == Token::OPER);
}
assert (s.size () >= 1);
s.pop();
} else {
next.type = Token::OPER;
next.op = in.get();
while (s.size()>=1 &&
s.top().type == Token::OPER &&
priority(s.top().op) > priority (next.op))
{
result.push_back(s.top());
s.pop();
}
s.push (next);
}
killwhite (in);
}
while (s.size () > 0)
{
result.push_back (s.top()); s.pop();
}
return result;
}
std::stringstream tostream (std::vector<Token> rpn)
{
std::stringstream res;
for (Token t : rpn)
{
switch (t.type)
{
case Token::NUM: res << t.val; break;
case Token::OPER: res << t.op; break;
default: assert (false);
}
res << " ";
}
return res;
}
int calcexprrec (std::istream &in)
{
killwhite (in);
if (isdigit (in.peek()))
{
int x;
in >> x;
return x;
}
assert (in.peek() == '(');
in.get();
int larg = calcexprrec (in);
killwhite (in);
char op = in.get();
int rarg = calcexprrec (in);
killwhite (in);
assert (in.get() == ')');
return apply (op,larg,rarg);
}
Token readToken (std::istream &in)
{
killwhite (in);
Token t;
if (isdigit (in.peek()))
{
t.type = Token::NUM;
in >> t.val;
return t;
} else if (in.peek() == '(')
{
t.type = Token::LPAR;
in.get();
return t;
} else if (in.peek() == ')')
{
t.type = Token::RPAR;
in.get();
return t;
} else
{
t.type = Token::OPER;
t.op = in.get();
return t;
}
}
int calcexprit (std::istream &in)
{
std::stack <Token> s;
Token next = readToken (in);
s.push (next);
while (s.size () > 1 || s.top().type != Token::NUM)
{
next = readToken (in);
if (next.type == Token::RPAR)
{
assert (s.top().type == Token::NUM);
int rarg = s.top().val; s.pop();
assert (s.top().type == Token::OPER);
char op = s.top().op; s.pop();
assert (s.top().type == Token::NUM);
int larg = s.top().val; s.pop();
assert (s.top().type == Token::LPAR);
s.pop();
next.type = Token::NUM;
next.val = apply (op,larg,rarg);
s.push (next);
} else {
s.push (next);
}
}
// std::cerr << "Top of stack = " << s.top().type << std::endl;
assert (s.top().type == Token::NUM);
return s.top().val;
}
int main ()
{
//std::cout << calcrpp (std::cin);
//std::vector<Token> rpn = makerpn (std::cin);
//std::stringstream srpn = tostream (rpn);
//std::cout << srpn.str();
//std::cout << calcexprrec (std::cin);
std::cout << calcexprit (std::cin);
}
| 20.417671
| 66
| 0.428993
|
code-hunger
|
fdc75e652f3f1085f89bf1de065fc619c1ee1ebd
| 12,432
|
cpp
|
C++
|
src/ast/rewriter/der.cpp
|
VaseninaAnna/z3
|
5da71dc8478ef581d38de56a54e9a904bd670d19
|
[
"MIT"
] | 26
|
2020-06-20T15:13:14.000Z
|
2022-03-30T12:49:51.000Z
|
src/ast/rewriter/der.cpp
|
VaseninaAnna/z3
|
5da71dc8478ef581d38de56a54e9a904bd670d19
|
[
"MIT"
] | 7
|
2018-06-01T15:48:07.000Z
|
2020-08-23T17:36:43.000Z
|
src/ast/rewriter/der.cpp
|
VaseninaAnna/z3
|
5da71dc8478ef581d38de56a54e9a904bd670d19
|
[
"MIT"
] | 8
|
2020-07-09T23:39:23.000Z
|
2021-04-21T20:21:20.000Z
|
/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
der.cpp
Abstract:
<abstract>
Author:
Leonardo de Moura (leonardo) 2008-01-27.
Revision History:
Christoph Wintersteiger, 2010-03-30: Added Destr. Multi-Equality Resolution
--*/
#include "ast/rewriter/der.h"
#include "ast/occurs.h"
#include "ast/for_each_expr.h"
#include "ast/rewriter/rewriter_def.h"
#include "ast/ast_util.h"
#include "ast/ast_pp.h"
#include "ast/ast_ll_pp.h"
#include "ast/ast_smt2_pp.h"
static bool is_var(expr * e, unsigned num_decls) {
return is_var(e) && to_var(e)->get_idx() < num_decls;
}
static bool is_neg_var(ast_manager & m, expr * e, var*& v, unsigned num_decls) {
expr* n = nullptr;
return m.is_not(e, n) && is_var(n) && (v = to_var(n), v->get_idx() < num_decls);
}
/**
\brief Return true if \c e is of the form (not (= VAR t)) or (not (iff VAR t)) or (iff VAR t) or (iff (not VAR) t) or (VAR IDX) or (not (VAR IDX)).
The last case can be viewed
Remark: Occurs check is not necessary here... the top-sort procedure will check for cycles...
*/
bool der::is_var_diseq(expr * e, unsigned num_decls, var * & v, expr_ref & t) {
expr *eq, * lhs, *rhs;
auto set_result = [&](var *w, expr* s) {
v = w;
t = s;
TRACE("der", tout << mk_pp(e, m) << "\n";);
return true;
};
// (not (= VAR t))
if (m.is_not(e, eq) && m.is_eq(eq, lhs, rhs)) {
if (!is_var(lhs, num_decls))
std::swap(lhs, rhs);
if (!is_var(lhs, num_decls))
return false;
return set_result(to_var(lhs), rhs);
}
// (= VAR t)
if (m.is_eq(e, lhs, rhs) && m.is_bool(lhs)) {
// (iff VAR t) case
if (!is_var(lhs, num_decls))
std::swap(lhs, rhs);
if (is_var(lhs, num_decls)) {
rhs = mk_not(m, rhs);
m_new_exprs.push_back(rhs);
return set_result(to_var(lhs), rhs);
}
// (iff (not VAR) t) case
if (!is_neg_var(m, lhs, v, num_decls))
std::swap(lhs, rhs);
if (is_neg_var(m, lhs, v, num_decls)) {
return set_result(v, rhs);
}
return false;
}
// VAR
if (is_var(e, num_decls)) {
return set_result(to_var(e), m.mk_false());
}
// (not VAR)
if (is_neg_var(m, e, v, num_decls)) {
return set_result(v, m.mk_true());
}
return false;
}
void der::operator()(quantifier * q, expr_ref & r, proof_ref & pr) {
bool reduced = false;
pr = nullptr;
r = q;
TRACE("der", tout << mk_pp(q, m) << "\n";);
// Keep applying it until r doesn't change anymore
do {
proof_ref curr_pr(m);
q = to_quantifier(r);
reduce1(q, r, curr_pr);
if (q != r)
reduced = true;
if (m.proofs_enabled()) {
pr = m.mk_transitivity(pr, curr_pr);
}
}
while (q != r && is_quantifier(r));
// Eliminate variables that have become unused
if (reduced && is_forall(r)) {
quantifier * q = to_quantifier(r);
r = elim_unused_vars(m, q, params_ref());
if (m.proofs_enabled()) {
proof * p1 = m.mk_elim_unused_vars(q, r);
pr = m.mk_transitivity(pr, p1);
}
}
m_new_exprs.reset();
}
void der::reduce1(quantifier * q, expr_ref & r, proof_ref & pr) {
if (!is_forall(q)) {
pr = nullptr;
r = q;
return;
}
expr * e = q->get_expr();
unsigned num_decls = q->get_num_decls();
var * v = nullptr;
expr_ref t(m);
if (m.is_or(e)) {
unsigned num_args = to_app(e)->get_num_args();
unsigned diseq_count = 0;
unsigned largest_vinx = 0;
m_map.reset();
m_pos2var.reset();
m_inx2var.reset();
m_pos2var.reserve(num_args, -1);
// Find all disequalities
for (unsigned i = 0; i < num_args; i++) {
if (is_var_diseq(to_app(e)->get_arg(i), num_decls, v, t)) {
unsigned idx = v->get_idx();
if (m_map.get(idx, nullptr) == nullptr) {
m_map.reserve(idx + 1);
m_inx2var.reserve(idx + 1, 0);
m_map[idx] = t;
m_inx2var[idx] = v;
m_pos2var[i] = idx;
diseq_count++;
largest_vinx = (idx>largest_vinx) ? idx : largest_vinx;
}
}
}
if (diseq_count > 0) {
get_elimination_order();
SASSERT(m_order.size() <= diseq_count); // some might be missing because of cycles
if (!m_order.empty()) {
create_substitution(largest_vinx + 1);
apply_substitution(q, r);
}
}
else {
TRACE("der_bug", tout << "Did not find any diseq\n" << mk_pp(q, m) << "\n";);
r = q;
}
}
// Remark: get_elimination_order/top-sort checks for cycles, but it is not invoked for unit clauses.
// So, we must perform a occurs check here.
else if (is_var_diseq(e, num_decls, v, t) && !occurs(v, t)) {
r = m.mk_false();
}
else
r = q;
if (m.proofs_enabled()) {
pr = r == q ? nullptr : m.mk_der(q, r);
}
}
static void der_sort_vars(ptr_vector<var> & vars, expr_ref_vector & definitions, unsigned_vector & order) {
order.reset();
// eliminate self loops, and definitions containing quantifiers.
bool found = false;
for (unsigned i = 0; i < definitions.size(); i++) {
var * v = vars[i];
expr * t = definitions.get(i);
if (t == nullptr || has_quantifiers(t) || occurs(v, t))
definitions[i] = nullptr;
else
found = true; // found at least one candidate
}
if (!found)
return;
typedef std::pair<expr *, unsigned> frame;
svector<frame> todo;
expr_fast_mark1 visiting;
expr_fast_mark2 done;
unsigned vidx, num;
for (unsigned i = 0; i < definitions.size(); i++) {
if (!definitions.get(i))
continue;
var * v = vars[i];
SASSERT(v->get_idx() == i);
SASSERT(todo.empty());
todo.push_back(frame(v, 0));
while (!todo.empty()) {
start:
frame & fr = todo.back();
expr * t = fr.first;
if (done.is_marked(t)) {
todo.pop_back();
continue;
}
switch (t->get_kind()) {
case AST_VAR:
vidx = to_var(t)->get_idx();
if (fr.second == 0) {
CTRACE("der_bug", vidx >= definitions.size(), tout << "vidx: " << vidx << "\n";);
// Remark: The size of definitions may be smaller than the number of variables occurring in the quantified formula.
if (definitions.get(vidx, nullptr) != nullptr) {
if (visiting.is_marked(t)) {
// cycle detected: remove t
visiting.reset_mark(t);
definitions[vidx] = nullptr;
}
else {
visiting.mark(t);
fr.second = 1;
todo.push_back(frame(definitions.get(vidx), 0));
goto start;
}
}
}
else {
SASSERT(fr.second == 1);
if (definitions.get(vidx, nullptr) != nullptr) {
visiting.reset_mark(t);
order.push_back(vidx);
}
else {
// var was removed from the list of candidate vars to elim cycle
// do nothing
}
}
done.mark(t);
todo.pop_back();
break;
case AST_QUANTIFIER:
UNREACHABLE();
todo.pop_back();
break;
case AST_APP:
num = to_app(t)->get_num_args();
while (fr.second < num) {
expr * arg = to_app(t)->get_arg(fr.second);
fr.second++;
if (done.is_marked(arg))
continue;
todo.push_back(frame(arg, 0));
goto start;
}
done.mark(t);
todo.pop_back();
break;
default:
UNREACHABLE();
todo.pop_back();
break;
}
}
}
}
void der::get_elimination_order() {
m_order.reset();
TRACE("top_sort",
tout << "DEFINITIONS: " << std::endl;
unsigned i = 0;
for (expr* e : m_map) {
if (e) tout << "VAR " << i << " = " << mk_pp(e, m) << std::endl;
++i;
}
);
// der::top_sort ts(m);
der_sort_vars(m_inx2var, m_map, m_order);
TRACE("der",
tout << "Elimination m_order:" << "\n";
tout << m_order << "\n";);
}
void der::create_substitution(unsigned sz) {
m_subst_map.reset();
m_subst_map.resize(sz, nullptr);
for(unsigned i = 0; i < m_order.size(); i++) {
expr_ref cur(m_map.get(m_order[i]), m);
// do all the previous substitutions before inserting
expr_ref r = m_subst(cur, m_subst_map.size(), m_subst_map.c_ptr());
unsigned inx = sz - m_order[i]- 1;
SASSERT(m_subst_map[inx]==0);
m_subst_map[inx] = r;
}
}
void der::apply_substitution(quantifier * q, expr_ref & r) {
expr * e = q->get_expr();
unsigned num_args=to_app(e)->get_num_args();
// get a new expression
m_new_args.reset();
for(unsigned i = 0; i < num_args; i++) {
int x = m_pos2var[i];
if (x != -1 && m_map.get(x) != nullptr)
continue; // this is a disequality with definition (vanishes)
m_new_args.push_back(to_app(e)->get_arg(i));
}
unsigned sz = m_new_args.size();
expr_ref t(m);
t = (sz == 1) ? m_new_args[0] : m.mk_or(sz, m_new_args.c_ptr());
expr_ref new_e = m_subst(t, m_subst_map.size(), m_subst_map.c_ptr());
// don't forget to update the quantifier patterns
expr_ref_buffer new_patterns(m);
expr_ref_buffer new_no_patterns(m);
for (unsigned j = 0; j < q->get_num_patterns(); j++) {
new_patterns.push_back(m_subst(q->get_pattern(j), m_subst_map.size(), m_subst_map.c_ptr()));
}
for (unsigned j = 0; j < q->get_num_no_patterns(); j++) {
new_no_patterns.push_back(m_subst(q->get_no_pattern(j), m_subst_map.size(), m_subst_map.c_ptr()));
}
r = m.update_quantifier(q, new_patterns.size(), new_patterns.c_ptr(),
new_no_patterns.size(), new_no_patterns.c_ptr(), new_e);
}
struct der_rewriter_cfg : public default_rewriter_cfg {
ast_manager& m;
der m_der;
der_rewriter_cfg(ast_manager & m): m(m), m_der(m) {}
bool reduce_quantifier(quantifier * old_q,
expr * new_body,
expr * const * new_patterns,
expr * const * new_no_patterns,
expr_ref & result,
proof_ref & result_pr) {
quantifier_ref q1(m);
q1 = m.update_quantifier(old_q, old_q->get_num_patterns(), new_patterns,
old_q->get_num_no_patterns(), new_no_patterns, new_body);
m_der(q1, result, result_pr);
return true;
}
};
template class rewriter_tpl<der_rewriter_cfg>;
struct der_rewriter::imp : public rewriter_tpl<der_rewriter_cfg> {
der_rewriter_cfg m_cfg;
imp(ast_manager & m):
rewriter_tpl<der_rewriter_cfg>(m, m.proofs_enabled(), m_cfg),
m_cfg(m) {
}
};
der_rewriter::der_rewriter(ast_manager & m) {
m_imp = alloc(imp, m);
}
der_rewriter::~der_rewriter() {
dealloc(m_imp);
}
void der_rewriter::operator()(expr * t, expr_ref & result, proof_ref & result_pr) {
m_imp->operator()(t, result, result_pr);
}
void der_rewriter::cleanup() {
ast_manager & m = m_imp->m_cfg.m;
dealloc(m_imp);
m_imp = alloc(imp, m);
}
void der_rewriter::reset() {
m_imp->reset();
}
| 29.741627
| 150
| 0.511744
|
VaseninaAnna
|
fdc88c3c1e2524cc322c86bab5e34430bacf515f
| 7,254
|
cpp
|
C++
|
c10/test/util/TypeIndex_test.cpp
|
brooks-anderson/pytorch
|
dd928097938b6368fc7e2dc67721550d50ab08ea
|
[
"Intel"
] | 7
|
2021-05-29T16:31:51.000Z
|
2022-02-21T18:52:25.000Z
|
c10/test/util/TypeIndex_test.cpp
|
stas00/pytorch
|
6a085648d81ce88ff59d6d1438fdb3707a0d6fb7
|
[
"Intel"
] | 1
|
2021-05-10T01:18:33.000Z
|
2021-05-10T01:18:33.000Z
|
c10/test/util/TypeIndex_test.cpp
|
stas00/pytorch
|
6a085648d81ce88ff59d6d1438fdb3707a0d6fb7
|
[
"Intel"
] | 1
|
2021-12-26T23:20:06.000Z
|
2021-12-26T23:20:06.000Z
|
#include <c10/util/Metaprogramming.h>
#include <c10/util/TypeIndex.h>
#include <gtest/gtest.h>
using c10::string_view;
using c10::util::get_fully_qualified_type_name;
using c10::util::get_type_index;
namespace {
static_assert(get_type_index<int>() == get_type_index<int>(), "");
static_assert(get_type_index<float>() == get_type_index<float>(), "");
static_assert(get_type_index<int>() != get_type_index<float>(), "");
static_assert(
get_type_index<int(double, double)>() ==
get_type_index<int(double, double)>(),
"");
static_assert(
get_type_index<int(double, double)>() != get_type_index<int(double)>(),
"");
static_assert(
get_type_index<int(double, double)>() ==
get_type_index<int (*)(double, double)>(),
"");
static_assert(
get_type_index<std::function<int(double, double)>>() ==
get_type_index<std::function<int(double, double)>>(),
"");
static_assert(
get_type_index<std::function<int(double, double)>>() !=
get_type_index<std::function<int(double)>>(),
"");
static_assert(get_type_index<int>() == get_type_index<int&>(), "");
static_assert(get_type_index<int>() == get_type_index<int&&>(), "");
static_assert(get_type_index<int>() == get_type_index<const int&>(), "");
static_assert(get_type_index<int>() == get_type_index<const int>(), "");
static_assert(get_type_index<const int>() == get_type_index<int&>(), "");
static_assert(get_type_index<int>() != get_type_index<int*>(), "");
static_assert(get_type_index<int*>() != get_type_index<int**>(), "");
static_assert(
get_type_index<int(double&, double)>() !=
get_type_index<int(double, double)>(),
"");
struct Dummy final {};
struct Functor final {
int64_t operator()(uint32_t, Dummy&&, const Dummy&) const;
};
static_assert(
get_type_index<int64_t(uint32_t, Dummy&&, const Dummy&)>() ==
get_type_index<
c10::guts::infer_function_traits_t<Functor>::func_type>(),
"");
namespace test_top_level_name {
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos != get_fully_qualified_type_name<Dummy>().find("Dummy"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, TopLevelName) {
EXPECT_NE(
string_view::npos, get_fully_qualified_type_name<Dummy>().find("Dummy"));
}
} // namespace test_top_level_name
namespace test_nested_name {
struct Dummy final {};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Dummy>().find("test_nested_name::Dummy"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, NestedName) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Dummy>().find("test_nested_name::Dummy"));
}
} // namespace test_nested_name
namespace test_type_template_parameter {
template <class T>
struct Outer final {};
struct Inner final {};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Outer<Inner>>().find(
"test_type_template_parameter::Outer"),
"");
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Outer<Inner>>().find(
"test_type_template_parameter::Inner"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, TypeTemplateParameter) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Outer<Inner>>().find(
"test_type_template_parameter::Outer"));
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Outer<Inner>>().find(
"test_type_template_parameter::Inner"));
}
} // namespace test_type_template_parameter
namespace test_nontype_template_parameter {
template <size_t N>
struct Class final {};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Class<38474355>>().find("38474355"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, NonTypeTemplateParameter) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Class<38474355>>().find("38474355"));
}
} // namespace test_nontype_template_parameter
namespace test_type_computations_are_resolved {
template <class T>
struct Type final {
using type = const T*;
};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<typename Type<int>::type>().find("int"),
"");
static_assert(
string_view::npos !=
get_fully_qualified_type_name<typename Type<int>::type>().find("*"),
"");
// but with remove_pointer applied, there is no '*' in the type name anymore
static_assert(
string_view::npos ==
get_fully_qualified_type_name<
typename std::remove_pointer<typename Type<int>::type>::type>()
.find("*"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, TypeComputationsAreResolved) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<typename Type<int>::type>().find("int"));
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<typename Type<int>::type>().find("*"));
// but with remove_pointer applied, there is no '*' in the type name anymore
EXPECT_EQ(
string_view::npos,
get_fully_qualified_type_name<
typename std::remove_pointer<typename Type<int>::type>::type>()
.find("*"));
}
struct Functor final {
std::string operator()(int64_t a, const Type<int>& b) const;
};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
get_fully_qualified_type_name<std::string(int64_t, const Type<int>&)>() ==
get_fully_qualified_type_name<
typename c10::guts::infer_function_traits_t<Functor>::func_type>(),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, FunctionTypeComputationsAreResolved) {
EXPECT_EQ(
get_fully_qualified_type_name<std::string(int64_t, const Type<int>&)>(),
get_fully_qualified_type_name<
typename c10::guts::infer_function_traits_t<Functor>::func_type>());
}
} // namespace test_type_computations_are_resolved
namespace test_function_arguments_and_returns {
class Dummy final {};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Dummy(int)>().find(
"test_function_arguments_and_returns::Dummy"),
"");
static_assert(
string_view::npos !=
get_fully_qualified_type_name<void(Dummy)>().find(
"test_function_arguments_and_returns::Dummy"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, FunctionArgumentsAndReturns) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Dummy(int)>().find(
"test_function_arguments_and_returns::Dummy"));
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<void(Dummy)>().find(
"test_function_arguments_and_returns::Dummy"));
}
} // namespace test_function_arguments_and_returns
} // namespace
| 32.823529
| 79
| 0.709677
|
brooks-anderson
|
fdcbb9e33a74a8a0b0961d1f6963d5806d5f8896
| 997
|
cpp
|
C++
|
tests/Dogecoin/TWDogeTests.cpp
|
taha-husain/pp-wallet-core
|
68862468398854cef2d194cad8498801afcc3344
|
[
"MIT"
] | null | null | null |
tests/Dogecoin/TWDogeTests.cpp
|
taha-husain/pp-wallet-core
|
68862468398854cef2d194cad8498801afcc3344
|
[
"MIT"
] | null | null | null |
tests/Dogecoin/TWDogeTests.cpp
|
taha-husain/pp-wallet-core
|
68862468398854cef2d194cad8498801afcc3344
|
[
"MIT"
] | 1
|
2020-12-03T03:24:12.000Z
|
2020-12-03T03:24:12.000Z
|
// Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "../interface/TWTestUtilities.h"
#include <PPTrustWalletCore/TWBitcoinScript.h>
#include <gtest/gtest.h>
TEST(Doge, LockScripts) {
auto script = WRAP(TWBitcoinScript, TWBitcoinScriptBuildForAddress(STRING("DLSSSUS3ex7YNDACJDxMER1ZMW579Vy8Zy").get(), TWCoinTypeDogecoin));
auto scriptData = WRAPD(TWBitcoinScriptData(script.get()));
assertHexEqual(scriptData, "76a914a7d191ec42aa113e28cd858cceaa7c733ba2f77788ac");
auto script2 = WRAP(TWBitcoinScript, TWBitcoinScriptBuildForAddress(STRING("AETZJzedcmLM2rxCM6VqCGF3YEMUjA3jMw").get(), TWCoinTypeDogecoin));
auto scriptData2 = WRAPD(TWBitcoinScriptData(script2.get()));
assertHexEqual(scriptData2, "a914f191149f72f235548746654f5b473c58258f7fb687");
}
| 45.318182
| 145
| 0.791374
|
taha-husain
|
fdcc529b479636c103c7260afe289b0883281fed
| 7,112
|
hpp
|
C++
|
legion/legion-hpcg/explicit-spmd/LegionStuff.hpp
|
samuelkgutierrez/CODY
|
d51bbd863f4f8b9ab05ad21cad4bf1104516ac72
|
[
"BSD-2-Clause"
] | 7
|
2017-02-09T17:39:22.000Z
|
2021-09-02T14:58:12.000Z
|
legion/legion-hpcg/explicit-spmd/LegionStuff.hpp
|
samuelkgutierrez/CODY
|
d51bbd863f4f8b9ab05ad21cad4bf1104516ac72
|
[
"BSD-2-Clause"
] | 1
|
2017-08-29T17:58:53.000Z
|
2017-08-29T17:58:53.000Z
|
legion/legion-hpcg/explicit-spmd/LegionStuff.hpp
|
samuelkgutierrez/CODY
|
d51bbd863f4f8b9ab05ad21cad4bf1104516ac72
|
[
"BSD-2-Clause"
] | 7
|
2017-06-01T12:06:22.000Z
|
2020-03-19T08:27:59.000Z
|
/**
* Copyright (c) 2016-2017 Los Alamos National Security, LLC
* All rights reserved.
*
* Copyright (c) 2016 Stanford University
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* LA-CC 10-123
*/
#pragma once
#include "TaskTIDs.hpp"
#include "Types.hpp"
#include "legion.h"
#include <vector>
#include <map>
#include <unistd.h>
using namespace LegionRuntime::HighLevel;
using namespace LegionRuntime::Accessor;
using namespace LegionRuntime::HighLevel;
#define RW READ_WRITE
#define RO READ_ONLY
#define WO WRITE_ONLY
#define RW_E READ_WRITE, EXCLUSIVE
#define RO_E READ_ONLY , EXCLUSIVE
#define WO_E WRITE_ONLY, EXCLUSIVE
#define RW_S READ_WRITE, SIMULTANEOUS
#define RO_S READ_ONLY , SIMULTANEOUS
#define WO_S WRITE_ONLY, SIMULTANEOUS
// Let the RT know that we 'know what we are doing'
static constexpr bool silenceWarnings = true;
////////////////////////////////////////////////////////////////////////////////
// Task forward declarations.
////////////////////////////////////////////////////////////////////////////////
void
mainTask(
const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime
);
void
genProblemTask(
const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime
);
void
startBenchmarkTask(
const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime
);
void
regionToRegionCopyTask(
const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime
);
void
registerCollectiveOpsTasks(void);
void
registerVectorOpTasks(void);
void
registerWAXPBYTasks(void);
void
registerSPMVTasks(void);
void
registerDDotTasks(void);
void
registerSYMGSTasks(void);
void
registerProlongationTasks(void);
void
registerRestrictionTasks(void);
void
registerFutureMathTasks(void);
void
registerComputeResidualTasks(void);
void
registerExchangeHaloTasks(void);
////////////////////////////////////////////////////////////////////////////////
// Task Registration
////////////////////////////////////////////////////////////////////////////////
inline void
registerTasks(void)
{
TaskVariantRegistrar tvr(MAIN_TID, "mainTask");
tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<mainTask>(tvr, "mainTask");
Runtime::set_top_level_task_id(MAIN_TID);
//
HighLevelRuntime::register_legion_task<genProblemTask>(
GEN_PROB_TID /* task id */,
Processor::LOC_PROC /* proc kind */,
true /* single */,
true /* index */,
AUTO_GENERATE_ID,
TaskConfigOptions(false /* leaf task */),
"genProblemTask"
);
HighLevelRuntime::register_legion_task<startBenchmarkTask>(
START_BENCHMARK_TID /* task id */,
Processor::LOC_PROC /* proc kind */,
true /* single */,
true /* index */,
AUTO_GENERATE_ID,
TaskConfigOptions(false /* leaf task */),
"startBenchmarkTask"
);
HighLevelRuntime::register_legion_task<regionToRegionCopyTask>(
REGION_TO_REGION_COPY_TID /* task id */,
Processor::LOC_PROC /* proc kind */,
true /* single */,
true /* index */,
AUTO_GENERATE_ID,
TaskConfigOptions(true /* leaf task */),
"regionToRegionCopyTask"
);
//
registerCollectiveOpsTasks();
//
registerVectorOpTasks();
//
registerWAXPBYTasks();
//
registerSPMVTasks();
//
registerDDotTasks();
//
registerSYMGSTasks();
//
registerProlongationTasks();
//
registerRestrictionTasks();
//
registerFutureMathTasks();
//
registerComputeResidualTasks();
//
registerExchangeHaloTasks();
}
////////////////////////////////////////////////////////////////////////////////
inline void
updateMappers(
Machine machine,
HighLevelRuntime *runtime,
const std::set<Processor> &local_procs
) {
#if 0 // Disable for now.
for (const auto &p : local_procs) {
runtime->replace_default_mapper(new CGMapper(machine, runtime, p), p);
}
#endif
}
////////////////////////////////////////////////////////////////////////////////
inline void
LegionInit(void)
{
registerTasks();
HighLevelRuntime::set_registration_callback(updateMappers);
}
/**
* Courtesy of some other legion code.
*/
template <unsigned DIM, typename T>
inline bool
offsetsAreDense(
const Rect<DIM> &bounds,
const LegionRuntime::Accessor::ByteOffset *offset
) {
#ifdef LGNCG_ASSUME_DENSE_OFFSETS
return true;
#else
off_t exp_offset = sizeof(T);
for (unsigned i = 0; i < DIM; i++) {
bool found = false;
for (unsigned j = 0; j < DIM; j++)
if (offset[j].offset == exp_offset) {
found = true;
exp_offset *= (bounds.hi[j] - bounds.lo[j] + 1);
break;
}
if (!found) return false;
}
return true;
#endif
}
/**
* Courtesy of some other legion code.
*/
inline bool
offsetMismatch(
int i,
const LegionRuntime::Accessor::ByteOffset *off1,
const LegionRuntime::Accessor::ByteOffset *off2
) {
#ifdef LGNCG_ASSUME_MATCHING_OFFSETS
return false;
#else
while (i-- > 0) {
if ((off1++)->offset != (off2++)->offset) return true;
}
return false;
#endif
}
/**
* Convenience routine to get a task's ID.
*/
inline int
getTaskID(
const Task *task
) {
return task->index_point.point_data[0];
}
/**
*
*/
inline size_t
getNumProcs(void)
{
size_t nProc = 0;
std::set<Processor> allProcs;
Realm::Machine::get_machine().get_all_processors(allProcs);
for (auto &p : allProcs) {
if (p.kind() == Processor::LOC_PROC) nProc++;
}
return nProc;
}
| 25.309609
| 80
| 0.639483
|
samuelkgutierrez
|
fdcd4306f93d23ab3a6de17a15d56edffd128c4a
| 4,921
|
cpp
|
C++
|
src/bbf_fix_file.cpp
|
trapexit/bbf
|
c57696e74dd87e00d3ac660eb3ee9423b6f55c89
|
[
"0BSD"
] | 82
|
2016-12-05T22:58:48.000Z
|
2022-03-21T12:38:19.000Z
|
src/bbf_fix_file.cpp
|
trapexit/bbf
|
c57696e74dd87e00d3ac660eb3ee9423b6f55c89
|
[
"0BSD"
] | 7
|
2018-12-12T03:33:51.000Z
|
2020-11-30T23:14:52.000Z
|
src/bbf_fix_file.cpp
|
trapexit/bbf
|
c57696e74dd87e00d3ac660eb3ee9423b6f55c89
|
[
"0BSD"
] | 5
|
2019-07-10T17:39:55.000Z
|
2021-07-17T21:47:31.000Z
|
/*
ISC License
Copyright (c) 2016, Antonio SJ Musumeci <trapexit@spawn.link>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "blkdev.hpp"
#include "captcha.hpp"
#include "errors.hpp"
#include "file.hpp"
#include "filetoblkdev.hpp"
#include "options.hpp"
#include "signals.hpp"
#include <iostream>
#include <utility>
#include <errno.h>
#include <stdint.h>
namespace l
{
static
int
fix_file_loop_core(BlkDev &blkdev_,
char *buf_,
const uint64_t buflen_,
const unsigned int retries_,
const uint64_t badblock_)
{
int rv;
uint64_t attempts;
if(signals::signaled_to_exit())
return -EINTR;
rv = blkdev_.read(badblock_,1,buf_,buflen_);
for(attempts = 1; ((attempts <= retries_) && (rv < 0)); attempts++)
{
std::cout << "Reading block "
<< badblock_
<< " failed (attempt "
<< attempts << " of " << retries_
<< "[" << Error::to_string(-rv) << "]: trying again"
<< std::endl;
rv = blkdev_.read(badblock_,1,buf_,buflen_);
}
if(rv < 0)
{
std::cout << "Reading block "
<< badblock_
<< " failed ("
<< attempts << " attempts) "
<< "[" << Error::to_string(-rv) << "]: using zeros"
<< std::endl;
::memset(buf_,0,buflen_);
}
rv = blkdev_.write(badblock_,1,buf_,buflen_);
for(attempts = 1; ((attempts <= retries_) && (rv < 0)); attempts++)
{
std::cout << "Writing block "
<< badblock_
<< " failed (attempt "
<< attempts << " of " << retries_
<< "[" << Error::to_string(-rv) << "]: trying again"
<< std::endl;
rv = blkdev_.write(badblock_,1,buf_,buflen_);
}
if(rv < 0)
std::cout << "Writing block "
<< badblock_
<< " failed ("
<< attempts << " attempts) "
<< "[" << Error::to_string(-rv) << "]"
<< std::endl;
return 0;
}
static
int
fix_file_loop(BlkDev &blkdev_,
const File::BlockVector &blockvector_,
const unsigned int retries_)
{
int rv;
char *buf;
uint64_t buflen;
buflen = blkdev_.logical_block_size();
buf = new char[buflen];
for(uint64_t i = 0, ei = blockvector_.size(); i != ei; i++)
{
uint64_t j = blockvector_[i].block;
const uint64_t ej = blockvector_[i].length + j;
for(; j != ej; j++)
{
rv = l::fix_file_loop_core(blkdev_,buf,buflen,retries_,j);
if(rv < 0)
break;
}
}
delete[] buf;
return rv;
}
static
void
set_blkdev_rwtype(BlkDev &blkdev,
const Options::RWType rwtype)
{
switch(rwtype)
{
case Options::ATA:
blkdev.set_rw_ata();
break;
case Options::OS:
blkdev.set_rw_os();
break;
}
}
static
AppError
fix_file(const Options &opts_)
{
int rv;
BlkDev blkdev;
std::string devpath;
File::BlockVector blockvector;
rv = File::blocks(opts_.device,blockvector);
if(rv < 0)
return AppError::opening_file(-rv,opts_.device);
devpath = FileToBlkDev::find(opts_.device);
if(devpath.empty())
return AppError::opening_device(ENOENT,opts_.device);
rv = blkdev.open_rdwr(devpath,!opts_.force);
if(rv < 0)
return AppError::opening_device(-rv,devpath);
l::set_blkdev_rwtype(blkdev,opts_.rwtype);
const std::string captcha = captcha::calculate(blkdev);
if(opts_.captcha != captcha)
return AppError::captcha(opts_.captcha,captcha);
rv = l::fix_file_loop(blkdev,blockvector,opts_.retries);
rv = blkdev.close();
if(rv < 0)
return AppError::closing_device(-rv,opts_.device);
return AppError::success();
}
}
namespace bbf
{
AppError
fix_file(const Options &opts_)
{
return l::fix_file(opts_);
}
}
| 26.175532
| 74
| 0.555375
|
trapexit
|
fdcdaa01e911c757c69d2e4092b4459fa42aaf61
| 608
|
cpp
|
C++
|
Machines/Utility/MemoryFuzzer.cpp
|
reidrac/CLK
|
a38974ef2e706d87f8ce7320b91c76c13dcede09
|
[
"MIT"
] | 1
|
2019-07-05T18:09:34.000Z
|
2019-07-05T18:09:34.000Z
|
Machines/Utility/MemoryFuzzer.cpp
|
reidrac/CLK
|
a38974ef2e706d87f8ce7320b91c76c13dcede09
|
[
"MIT"
] | null | null | null |
Machines/Utility/MemoryFuzzer.cpp
|
reidrac/CLK
|
a38974ef2e706d87f8ce7320b91c76c13dcede09
|
[
"MIT"
] | null | null | null |
//
// MemoryFuzzer.cpp
// Clock Signal
//
// Created by Thomas Harte on 19/10/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "MemoryFuzzer.hpp"
#include <cstdlib>
void Memory::Fuzz(uint8_t *buffer, std::size_t size) {
unsigned int divider = (static_cast<unsigned int>(RAND_MAX) + 1) / 256;
unsigned int shift = 1, value = 1;
while(value < divider) {
value <<= 1;
shift++;
}
for(std::size_t c = 0; c < size; c++) {
buffer[c] = static_cast<uint8_t>(std::rand() >> shift);
}
}
void Memory::Fuzz(std::vector<uint8_t> &buffer) {
Fuzz(buffer.data(), buffer.size());
}
| 20.965517
| 72
| 0.646382
|
reidrac
|
fdce1591412dba7a60268b232e46262eb9f26acb
| 5,172
|
cpp
|
C++
|
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_SysInfoClass.cpp
|
eudora-jia/CIDLib
|
02795d283d95f8a5a4fafa401b6189851901b81b
|
[
"MIT"
] | 1
|
2019-05-28T06:33:01.000Z
|
2019-05-28T06:33:01.000Z
|
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_SysInfoClass.cpp
|
eudora-jia/CIDLib
|
02795d283d95f8a5a4fafa401b6189851901b81b
|
[
"MIT"
] | null | null | null |
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_SysInfoClass.cpp
|
eudora-jia/CIDLib
|
02795d283d95f8a5a4fafa401b6189851901b81b
|
[
"MIT"
] | null | null | null |
//
// FILE NAME: CIDMacroEng_SysInfoClass.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 02/20/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the macro level MEng.System.Runtime.SysInfo class.
// It just provides some global information of interest, and defines a
// commonly used error enum.
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CIDMacroEng_.hpp"
// ---------------------------------------------------------------------------
// Magic RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TMEngSysInfoInfo,TMEngClassInfo)
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
namespace CIDMacroEng_SysInfoClass
{
};
// ---------------------------------------------------------------------------
// CLASS: TMEngSysInfoInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngSysInfoInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngSysInfoInfo::TMEngSysInfoInfo(TCIDMacroEngine& meOwner) :
TMEngClassInfo
(
L"SysInfo"
, TFacCIDMacroEng::strRuntimeClassPath
, meOwner
, kCIDLib::False
, tCIDMacroEng::EClassExt::Final
, L"MEng.Object"
)
, m_c2MethId_DefCtor(kMacroEng::c2BadId)
, m_c2MethId_GetCPUCount(kMacroEng::c2BadId)
, m_c2MethId_GetNodeName(kMacroEng::c2BadId)
{
}
TMEngSysInfoInfo::~TMEngSysInfoInfo()
{
}
// ---------------------------------------------------------------------------
// TMEngSysInfoInfo: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TMEngSysInfoInfo::Init(TCIDMacroEngine&)
{
// Add the default constructor
{
TMEngMethodInfo methiNew
(
L"ctor1_MEng.System.Runtime.SysInfo"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.bIsCtor(kCIDLib::True);
m_c2MethId_DefCtor = c2AddMethodInfo(methiNew);
}
// Get the local node name
{
TMEngMethodInfo methiNew
(
L"GetNodeName"
, tCIDMacroEng::EIntrinsics::String
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
m_c2MethId_GetNodeName = c2AddMethodInfo(methiNew);
}
// Get the number of CPUs
{
TMEngMethodInfo methiNew
(
L"GetCPUCount"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
m_c2MethId_GetCPUCount = c2AddMethodInfo(methiNew);
}
}
TMEngClassVal*
TMEngSysInfoInfo::pmecvMakeStorage( const TString& strName
, TCIDMacroEngine& meOwner
, const tCIDMacroEng::EConstTypes eConst) const
{
return new TMEngStdClassVal(strName, c2Id(), eConst);
}
// ---------------------------------------------------------------------------
// TMacroEngSysInfoInfo: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngSysInfoInfo::bInvokeMethod( TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance)
{
const tCIDLib::TCard4 c4FirstInd = meOwner.c4FirstParmInd(methiTarget);
const tCIDLib::TCard2 c2MethId = methiTarget.c2Id();
if (c2MethId == m_c2MethId_DefCtor)
{
// Nothing to do
}
else if (c2MethId == m_c2MethId_GetCPUCount)
{
// Get the return value and set it with the indicated char
TMEngCard4Val& mecvRet
= meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(TSysInfo::c4CPUCount());
}
else if (c2MethId == m_c2MethId_GetNodeName)
{
// Get the return value and set it with the indicated char
TMEngStringVal& mecvRet
= meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd - 1);
mecvRet.strValue(TSysInfo::strIPHostName());
}
else
{
return kCIDLib::False;
}
return kCIDLib::True;
}
| 29.724138
| 84
| 0.490333
|
eudora-jia
|
fdcf3f1e2446d7ff96074127314b6b40bf0a6a69
| 1,810
|
cpp
|
C++
|
tests/src/ProcessTests/ChildProcessTests.cpp
|
codesmithyide/Process
|
a4b037803737a60bbb9568db61967ffd18ba8818
|
[
"MIT"
] | null | null | null |
tests/src/ProcessTests/ChildProcessTests.cpp
|
codesmithyide/Process
|
a4b037803737a60bbb9568db61967ffd18ba8818
|
[
"MIT"
] | null | null | null |
tests/src/ProcessTests/ChildProcessTests.cpp
|
codesmithyide/Process
|
a4b037803737a60bbb9568db61967ffd18ba8818
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2016-2020 Xavier Leclercq
Released under the MIT License
See https://github.com/Ishiko-cpp/Process/blob/master/LICENSE.txt
*/
#include "ChildProcessTests.h"
#include "Ishiko/Process/ChildProcess.h"
using namespace Ishiko;
using namespace Ishiko::Process;
using namespace Ishiko::Tests;
ChildProcessTests::ChildProcessTests(const TestNumber& number, const TestEnvironment& environment)
: TestSequence(number, "ChildProcess tests", environment)
{
append<HeapAllocationErrorsTest>("Constructor test 1", ConstructorTest1);
append<HeapAllocationErrorsTest>("Spawn test 1", SpawnTest1);
append<HeapAllocationErrorsTest>("Spawn test 2", SpawnTest2);
}
void ChildProcessTests::ConstructorTest1(Test& test)
{
ChildProcess handle;
ISHTF_PASS();
}
void ChildProcessTests::SpawnTest1(Test& test)
{
#ifdef __linux__
boost::filesystem::path executablePath(test.environment().getTestDataDirectory() / "Bin/ExitCodeTestHelper");
#else
boost::filesystem::path executablePath(test.environment().getTestDataDirectory() / "Bin/ExitCodeTestHelper.exe");
#endif
ChildProcess handle = ChildProcess::Spawn(executablePath.string());
handle.waitForExit();
ISHTF_FAIL_IF_NEQ(handle.exitCode(), 0);
ISHTF_PASS();
}
void ChildProcessTests::SpawnTest2(Test& test)
{
#ifdef __linux__
boost::filesystem::path executablePath(test.environment().getTestDataDirectory() / "Bin/ExitCodeTestHelper");
#else
boost::filesystem::path executablePath(test.environment().getTestDataDirectory() / "Bin/ExitCodeTestHelper.exe");
#endif
Error error(0);
ChildProcess handle = ChildProcess::Spawn(executablePath.string(), error);
ISHTF_ABORT_IF(error);
handle.waitForExit();
ISHTF_FAIL_IF_NEQ(handle.exitCode(), 0);
ISHTF_PASS();
}
| 28.730159
| 117
| 0.749724
|
codesmithyide
|
fdd1f31279f6c08494f94939cbe42d4e27b68267
| 10,476
|
cpp
|
C++
|
SOURCES/sim/digi/gunsjink.cpp
|
IsraelyFlightSimulator/Negev-Storm
|
86de63e195577339f6e4a94198bedd31833a8be8
|
[
"Unlicense"
] | 1
|
2021-02-19T06:06:31.000Z
|
2021-02-19T06:06:31.000Z
|
src/sim/digi/gunsjink.cpp
|
markbb1957/FFalconSource
|
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
|
[
"BSD-2-Clause"
] | null | null | null |
src/sim/digi/gunsjink.cpp
|
markbb1957/FFalconSource
|
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
|
[
"BSD-2-Clause"
] | 2
|
2019-08-20T13:35:13.000Z
|
2021-04-24T07:32:04.000Z
|
#include "stdhdr.h"
#include "simveh.h"
#include "digi.h"
#include "object.h"
#include "simbase.h"
#include "airframe.h"
#include "team.h"
#include "aircrft.h"
#include "sms.h"
#define INIT_GUN_VEL 4500.0f //me123 changed from 3500.0F
extern float SimLibLastMajorFrameTime;
void DigitalBrain::GunsJinkCheck(void)
{
float tgt_time=0.0F,att_time=0.0F,z=0.0F, timeDelta=0.0F;
int twoSeconds=0;
unsigned long lastUpdate=0;
SimObjectType* obj = targetPtr;
SimObjectLocalData* localData=NULL;
/*-----------------------------------------------*/
/* Entry conditions- */
/* */
/* 1. Target range <= INIT_GUN_VEL feet. */
/* 2. Target time to fire < ownship time to fire */
/* 3. Predicted bullet fire <= 2 seconds. */
/*-----------------------------------------------*/
//me123 lets check is closure is resonable too before goin into jink mode
if (curMode != GunsJinkMode)
{
if ( obj == NULL )
return;
if ( obj->BaseData()->IsSim() &&
(((SimBaseClass*)obj->BaseData())->IsFiring() ||
TeamInfo[self->GetTeam()]->TStance(obj->BaseData()->GetTeam()) == War))
{
localData = obj->localData;
if ((localData->range > 0.0f) && (localData->range < 6000.0f))//localData->rangedot > -240.0f * FTPSEC_TO_KNOTS )//me123 don't jink if he's got a high closure, he probaly woun't shoot a low Pk shot
{
if (localData->range < INIT_GUN_VEL )
{
/*-----------------------------------*/
/* predict time of possible gun fire */
/*-----------------------------------*/
twoSeconds = FALSE;
jinkTime = -1;
z = localData->range / INIT_GUN_VEL;
if ( localData->azFrom > -15.0F * DTR && localData->azFrom < (15.0F * DTR))//me123 status test. changed from 2.0 to 5.0 multible places here becourse we are not always in plane when gunning
{
twoSeconds = TRUE;
}
else if (localData->azFrom > (5.0F * DTR) && localData->azFromdot < 0.0F)
{
if (localData->azFrom + z * localData->azFromdot < (5.0F * DTR))
twoSeconds = TRUE;
}
else if (localData->azFrom < (-5.0F * DTR) && localData->azFromdot > 0.0F)
{
if (localData->azFrom + z * localData->azFromdot > (-5.0F * DTR))
twoSeconds = TRUE;
}
if (twoSeconds)
{
twoSeconds = FALSE;
if (localData->elFrom < (4.0F *DTR) && localData->elFrom > (-10.0F * DTR))//me123 status test. changed all
{
twoSeconds = TRUE;
}
// else if (localData->elFrom > (-2.0F *DTR) && localData->elFromdot < 0.0F)
// {
// if (localData->elFrom + z* localData->elFromdot < (-2.0F *DTR))
// twoSeconds = TRUE;
// }
// else if (localData->elFrom < (-13.0F * DTR) && localData->elFromdot > 0.0F)
// {
// if (localData->elFrom + z* localData->elFromdot > (-13.0F * DTR))
// twoSeconds = TRUE;
// }
/*-------------------------------------------------*/
/* estimate time to be targeted and time to attack */
/*-------------------------------------------------*/
lastUpdate = targetPtr->BaseData()->LastUpdateTime();
if (lastUpdate == vuxGameTime)
timeDelta = SimLibMajorFrameTime;
else
timeDelta = SimLibLastMajorFrameTime;
/*-----------*/
/* him -> me */
/*-----------*/
tgt_time = ((localData->ataFrom / localData->ataFromdot) * timeDelta);
// if (tgt_time < 0.0F)//me123 status test,
// tgt_time = 99.0F;//me123 status test,
if (localData->ataFrom > -13.0f *DTR && localData->ataFrom < 13.0f *DTR) {tgt_time = 0.0f;}//me123 status test,
/*-----------*/
/* me -> him */
/*-----------*/
att_time = (localData->ata / localData->atadot) * timeDelta;
// if (att_time < 0.0F)//me123 status test,
// att_time = 99.0F;//me123 status test,
if (localData->ata > -13.0f *DTR && localData->ata < 13.0f *DTR) {att_time = 0.0f;}//me123 status test,
}
/*--------------*/
/* trigger jink */
/*--------------*/
if (twoSeconds && tgt_time <= att_time)
{
AddMode(GunsJinkMode);
}
}
}
}
} // if not guns jink mode
/*------------------------------------*/
/* else already in guns jink */
/* this maneuver is timed and removes */
/* itself, but we must make sure the */
/* threat is still around */
/*------------------------------------*/
}
void DigitalBrain::GunsJink(void)
{
float aspect, roll_offset, eroll;
SimObjectLocalData* gunsJinkData;
SimObjectType* obj = targetList;
//int randVal;
float maxPull;
/*------------------------------------*/
/* this maneuver is timed and removes */
/* itself, but we must make sure the */
/* threat is still around */
/*------------------------------------*/
if ( targetPtr == NULL || targetPtr->BaseData()->IsExploding() ||
targetPtr && targetPtr->localData->range > 4000)
{
// bail, no target
jinkTime = -1;
return;
}
// Cobra No need to go through all the stuff if we need to avoid the ground
if(groundAvoidNeeded)
return;
/*-------------------*/
/* energy management */
/*-------------------*/
MachHold(cornerSpeed,self->GetKias(), FALSE);//me123 from TRUE
/*--------------------*/
/* find target aspect */
/*--------------------*/
gunsJinkData = targetPtr->localData;
aspect = 180.0F * DTR - gunsJinkData->ata;
/*-----------------*/
/* pick roll angle */
/*-----------------*/
if (jinkTime == -1)
{
// Should I jettison stores?
if (self->CombatClass() != MnvrClassBomber)
{
//Cobra we do this always
self->Sms->AGJettison();
SelectGroundWeapon();
}
ResetMaxRoll();
/*--------------------------------*/
/* aspect >= 60 degrees */
/* put plane of wings on attacker */
/*--------------------------------*/
if (aspect >= 90.0F * DTR)//me123 changed from 60
{
/* offset required to put wings on attacker */
if (gunsJinkData->droll >= 0.0F) roll_offset = gunsJinkData->droll - 90.0F * DTR;
else roll_offset = gunsJinkData->droll + 90.0F * DTR;
/* generate new phi angle */
newroll = self->Roll() + roll_offset;
}
/*---------------------*/
/* aspect < 60 degrees */
/* roll +- 90 degrees */
/*---------------------*/
else
{
/* special in-plane crossing case, go the opposite direction */
if (targetPtr && ((targetPtr->BaseData()->Yaw() - self->Yaw() < 15.0F * DTR) &&
(targetPtr->BaseData()->Pitch() - self->Pitch() < 15.0F * DTR) &&
(targetPtr->BaseData()->Roll() - self->Roll() < 15.0F * DTR)))
{
if (gunsJinkData->droll >= 0.0F && gunsJinkData->az > 0.0F)
{
newroll = self->Roll() + 90.0F * DTR;
}
else if (gunsJinkData->droll < 0.0F && gunsJinkData->az < 0.0F)
{
newroll = self->Roll() - 90.0F * DTR;
}
else /* fall out, normal case */
{
if (gunsJinkData->droll > 0.0F)
newroll = self->Roll() - 70.0F * DTR; //me123 status test changed from 90
else
newroll = self->Roll() + 70.0F * DTR;//me123 status test changed from 90
}
}
/* normal jink */
else
{
if (gunsJinkData->droll > 0.0F)
newroll = self->Roll() - 70.0F * DTR;//me123 status test changed from 90
else
newroll = self->Roll() + 70.0F * DTR;//me123 status test changed from 90
}
/*--------------------------------------------*/
/* roll down if speed <= 60% of corner speed */
/*--------------------------------------------*/
if (self->GetKias() <= 0.8F * cornerSpeed)//me123 status test. changed from 0.6
{
if (newroll >= 0.0F && newroll <= 45.0F * DTR)
newroll += 30.0F * DTR;//me123 status test changed from 20
else if (newroll <= 0.0F && newroll >= -45.0F * DTR)
newroll -= 30.0F * DTR;//me123 status test changed from 20
}
}
/*------------------------*/
/* roll angle corrections */
/*------------------------*/
if (newroll > 180.0F * DTR)
newroll -= 360.0F * DTR;
else if (newroll < -180.0F * DTR)
newroll += 360.0F * DTR;
// Clamp roll to limits
if (newroll > af->MaxRoll())
newroll = af->MaxRoll();
else if (newroll < -af->MaxRoll())
newroll = -af->MaxRoll();
jinkTime = 0;
}
// Allow unlimited rolling
if (self->CombatClass() != MnvrClassBomber)
SetMaxRoll (190.0F);
/*---------------------------*/
/* roll to the desired angle */
/*---------------------------*/
if (jinkTime == 0)
{
SetPstick (-2.0F, maxGs, AirframeClass::GCommand);
/*------------*/
/* roll error */
/*------------*/
eroll = newroll - self->Roll();
/*-----------------------------*/
/* roll the shortest direction */
/*-----------------------------*/
eroll = SetRstick( eroll * RTD * 4.0F) * DTR;
SetMaxRollDelta (eroll);
//me123 and pull like hell
maxPull = max (0.8F * af->MaxGs(), maxGs);
SetPstick ( maxPull, af->MaxGs(), AirframeClass::GCommand);
/*-----------------------*/
/* stop rolling and pull */
/*-----------------------*/
if (fabs(eroll) < 5.0F * DTR)//me123 status test, from 5
{
jinkTime = 1;
SetRstick( 0.5F );//me123 status test, from 0
}
}
/*-----------------------*/
/* pull max gs for 2 sec */
/*-----------------------*/
if (jinkTime > 0 || groundAvoidNeeded)
{
maxPull = max (0.8F * af->MaxGs(), maxGs);
SetPstick ( maxPull, af->MaxGs(), AirframeClass::GCommand);
if (jinkTime++ > SimLibMajorFrameRate*2.0F + 1.0F)//me123 status test, pull for 5sec instead of 2
{
ResetMaxRoll();
jinkTime = -1;
}
else
{
// Stay in guns jink
AddMode(GunsJinkMode);
}
}
else
{
// Stay in guns jink
AddMode(GunsJinkMode);
}
}
| 32.943396
| 200
| 0.473559
|
IsraelyFlightSimulator
|
fdd2c7bf730c3af1a54fb47ca81e2795b43c8b7a
| 16,978
|
cpp
|
C++
|
src/FileContainer.cpp
|
ElliotAlexander/EDSAC-FORTRAN-Compiler
|
f5a14d0f4c42fcba5eb1d277cab4b8d700eab699
|
[
"Apache-2.0"
] | null | null | null |
src/FileContainer.cpp
|
ElliotAlexander/EDSAC-FORTRAN-Compiler
|
f5a14d0f4c42fcba5eb1d277cab4b8d700eab699
|
[
"Apache-2.0"
] | null | null | null |
src/FileContainer.cpp
|
ElliotAlexander/EDSAC-FORTRAN-Compiler
|
f5a14d0f4c42fcba5eb1d277cab4b8d700eab699
|
[
"Apache-2.0"
] | null | null | null |
#include "FileContainer.h"
/**
*
* Class FileContainer:
*
* Member Variables:
* std::string file_name; -> initialised in the constructor
* std::vector<std::string> -> loaded from file file_name in the constructor.
*
*
**/
// FileContainer::FileContainer(std::string file_name_in);
// @param file_name_in - the name of the input file the FileContainer object represents.
// FileContainer is a 1:1 relationship between an input file and it's representation in the program.
// each FileContainer is a container for one specific file.
// The constructor loads the file into a std::vector<std::string> stored as a member variable.
FileContainer::FileContainer(std::string file_name_in) : file_name(file_name_in){
std::ifstream input(FileContainer::file_name);
std::string line_buffer_temp;
int line_counter_temp = 1;
// Iterate through the whole file.
while( std::getline( input, line_buffer_temp ) ) {
// if a line is too short, remove it and mark it as a comment (where line length < MINIMUM_LINE_LENGTH)
line_buffer_temp = removeShortLines(line_buffer_temp, line_counter_temp);
// If a line is blank, remove it and mark it as a comment.
line_buffer_temp = removeNewlines(line_buffer_temp);
// Build a member variable of the complete file text.
FileContainer::file_text.push_back(line_buffer_temp);
// update line counter.
line_counter_temp++;
}
if(Globals::dump_data_structures){
// enabled through a commmand line flag, dump the file to the command line if required.
dumpFileText();
}
}
// std::vector<Segment> FileContainer::dissectSegments(){
// @return std::vector<Segment> - The built list of Segment objects contained within the file represented by the FileContainer object.
// This function breaks down the program text contained in the member variable file_text into a list of Segment objects.
// This function does not change class state
std::vector<Segment> FileContainer::dissectSegments(){
std::vector<Segment> segment_arr;
// Start outside a segment, the first line of the file willl input
bool in_function_or_subroutine_block = false;
// Start inside the main program block, remain there until we see a FUNCTION or SUBROUTINE statement.
bool in_main_block = true;
// Indicating the current type of segment we are inside, FUNCTION, SUBROUTINE or MAIN PROGRAM.
SEGMENT_TYPE current_type = {};
int start_line = 0;
/**
* This loop iterates through each line in the file text
* The loop tracks which a) type of segment it is currently in b) if it is currently in a segment c) where the current segment started
* At the end of each segment (i.e. when a return or END statement is seen) the loop backtracks, builds a string vector of
* all the lines in that segment (since the starting line), and then builds a segment object with this list
* Once a segment object is built, it is added to segment_arr, the return value for the whole function.
* This algorithm hence breaks down the file into a list of segments, and warns the user when they try to do things
* they shouldn't either outside of a segment or in the wrong segment type
* */
for(std::vector<std::string>::size_type i = 0; i != FileContainer::file_text.size(); i++) {
// Skip comments
if(!::lineIsComment(FileContainer::file_text[i])){
// Set the program text to a local variable. Ignore the line label i.e. chars 0 -> 6
std::string useful_statement = FileContainer::file_text[i].substr(LINE_LABEL_LENGTH, FileContainer::file_text[i].length());
// If the line is an END statement. Note that there might be possible problems here with ENDVARIABLE, for example.
if(useful_statement.substr(0,END_STATEMENT_LENGTH) == "END" && useful_statement.length() == END_STATEMENT_LENGTH){
// END should signify the END of the program as a whole. If we're inside a segment, the prgorammer needs to RETURN first.
// This only applies to FUNCTION and SUBROUTINE blocks, as the MAIN program can exit without a return.
if(in_function_or_subroutine_block){
Logging::logErrorMessage( "END statement found inside a segment block. Are you missing a return? [" + std::to_string(i) + "].");
} else if(in_main_block){
// Leave the main block
in_main_block = false;
// Begin building a list of thee lines inside that segment.
std::vector<std::string> segment_text;
// For each line in the segment
for(int x = start_line; x < ( i+1 ); x++){
segment_text.push_back(FileContainer::file_text.at(x));
}
Logging::logMessage("+" + ::getEnumString(SEGMENT_TYPE::PROGRAM) + " [" + std::to_string(start_line + 1) + "," + std::to_string(i + 1) + "]");
// Build a segment with our list of strings, add it to the overarching data structure.
segment_arr.push_back(Segment(SEGMENT_TYPE::PROGRAM, start_line, i, segment_text));
} else {
Logging::logWarnMessage("END detected outside of Main Program Block[" + std::to_string(i) + "]"); // THis should only catch if the program starts with END.
}
} else if(useful_statement.substr(0, 6) == "RETURN") {
// If we're not in a function or subroutine block, we can't call return. Throw the user an error if they try this.
if(in_function_or_subroutine_block){
// Build an array of the program lines in this segment
std::vector<std::string> segment_text;
// iterate through the segment
for(int x = start_line; x < ( i+1 ); x++){
segment_text.push_back(FileContainer::file_text.at(x));
}
Logging::logMessage("+" + ::getEnumString(current_type) + " [" + std::to_string(start_line + 1) + "," + std::to_string(i + 1) + "]{" + ::stripWhitespaceString(segment_text.at(0)) + "}.");
// Construct a segment object, add it back to our return array. This segment is now finished with.
segment_arr.push_back(Segment(current_type, start_line, i, segment_text));
// We are no longer in a function or subroutine block, the user has just exited this by calling return.
in_function_or_subroutine_block = false;
start_line = i+1;
current_type = {};
} else {
// if we're in the main program block - the user should not be calling return.
Logging::logWarnMessage("RETURN detected outside of Subroutine Block [start=" + std::to_string(start_line + 1) + ", end=" + std::to_string(i+1) + "].");
}
} else if(useful_statement.substr(0, 10) == "SUBROUTINE"){
// Nested subrutines / functions aren't allowed - so we should never see this statement inside another function or subroutine.
if(!in_function_or_subroutine_block){
// Set current type
current_type = SEGMENT_TYPE::SUBROUTINE;
// Set start line - once we see a RETURN statement, we'll iterate from this line down and build the segment.
start_line = i;
in_function_or_subroutine_block = true;
} else {
Logging::logWarnMessage("SUBROUTINE Block detected inside another segment block [start=" + std::to_string(start_line+1) + ", end=" + std::to_string(i+1) + "].");
}
} else if(useful_statement.substr(0, 8) == "FUNCTION"){
// Nested subroutines / functions aren't allowed - we should never see this statemenet when inside another function or subroutine
if(!in_function_or_subroutine_block){
// Set current segmetn type
current_type = SEGMENT_TYPE::FUNCTION;
// Set start line - we'll iterate from this to the end of the function once we see it
start_line = i;
in_function_or_subroutine_block = true;
} else {
Logging::logWarnMessage("FUNCTION Block detected inside another segment block [start=" + std::to_string(start_line+1)+ ", end=" + std::to_string(i+1) + "].");
}
// If we're not in the main block, and see a statement that isn't already specified - enter the main block!
} else if(!in_main_block) {
in_main_block = true;
current_type = SEGMENT_TYPE::PROGRAM;
Logging::logInfoMessage("Entered main program at line " + std::to_string(i + 1));
}
}
}
// If we find a segment with no statements in it - warn the user.
// This also catches non-terminated segments - i.e. a Main Program segment without an END.
if(segment_arr.size() == 0){
Logging::logErrorMessage("Warning - failed to load a fail program block from file " + file_name);
Logging::logErrorMessage("Did you forget to include an END Statement?");
}
Logging::logNewLine();
// Returns std::vector<Segment> -> built inside above for loop.
return segment_arr;
}
// void FileContainer::dumpFileText()
//
//
// This function takes and returns no arguments
// the purpose of this function is to dump + format the file text to the command line.
// This is activated upon a user enabled command line flag.
// The file text is loaded and constructed in the constructor.
void FileContainer::dumpFileText(){
Logging::logMessage("Begin File Dump(Name=" + file_name + "):\n"); // Pretty printing
for (std::vector<std::string>::const_iterator i = FileContainer::file_text.begin(); i != FileContainer::file_text.end(); ++i) //
Logging::logMessage(*i + ' '); // For each - print that line with no formmatting.
Logging::logMessage("\nEnd File Dump\n");
}
// bool FileContainer::expandContinuations()
//
// @return bool -> indicates success / failure.
// @member file_text
//
// This function modifies class state
// This function iterates through the member variable file_text, removing continuations and appending them into a single line.
// The continuation lines removed as replaced by comments.
// This modification is done *in place* inside FileContainer::file_text.
bool FileContainer::expandContinuations(){
int continuation_count = CONTINUATION_COUNT_STARTING;
// Iterate through file text
for(std::vector<std::string>::size_type i = 0; i != FileContainer::file_text.size(); i++) {
// Ignore comments in the file text - they cannot be continuations.
if(!::lineIsComment(FileContainer::file_text[i])){
// FAIL - if over 20 consecutive continuations have been seen.
if(continuation_count == 20) {
// Exit with an error - return this to the calling class.
Logging::logErrorMessage("Over 20 Continuations detected! Aborting. Line[" + std::to_string(i-19) + "]{'" + FileContainer::file_text[i-continuation_count] + "'}.");
return false;
} else if(
( FileContainer::file_text[i].at(CONTINUATION_INDICATION_BIT) != ' ')
&& (i != 0))
{
// Continuations cannot be line labels. Warn the user and abort if it is.
if( FileContainer::file_text[i].substr(0,4).find_first_not_of(' ') != std::string::npos){
Logging::logErrorMessage("Line {'" + FileContainer::file_text[i] + "'}[" + std::to_string(i+1) + "] is marked as a continuation, but contains a label. Aborting.");
return false; // Exit to the calling class.
} else {
// Make a copy of the line we're modifying - in case we need to print it later.
std::string line_text_backup = FileContainer::file_text[i];
// This MUST be empty - so it can be removed. This includes deleting the continuation character.
FileContainer::file_text[i].erase(0,6);
// Check that the rest of the line is not zero.
if(FileContainer::file_text[i].length() == 0){
Logging::logErrorMessage("Empty continuation - Continuation labelled lines must contained at least one character.");
// Print an error - note use case of previous backup.
::printErrorLocation(7, line_text_backup);
} else {
// Append continuation to prervious non-continuation line, forming one longer line.
FileContainer::file_text[i-continuation_count] += FileContainer::file_text[i];
// Mark the line IN PLACE as a blank comment
FileContainer::file_text[i] = std::string("C");
// Keep track of the number of continuations we've seen.
continuation_count += 1;
}
}
} else {
// If the line is not a continuation - reset the continuation count.
continuation_count = 1;
}
}
}
return true;
}
// std::string FileContainer::removeNewlines(std::string line)
//
// @param an input line - a single line input which will have it's newline characters removed.
// @return The modified input line, with all CR LF characters removed
//
//This function acts as a utility class - it has no impact on class state nor does it use any member variables.
//
std::string FileContainer::removeNewlines(std::string line){
std::string::size_type pos = 0; // iterate from position zero
while ( ( pos = line.find ("\r",pos) ) != std::string::npos ) // Find all \r characters, remove them.
{
line.erase ( pos, 2 );
}
pos = 0; // Repeat this process for \r\n
while ( ( pos = line.find ("\r\n",pos) ) != std::string::npos ) //
{
line.erase ( pos, 2 );
}
return line; // Return the modified line.
}
// std::string FileContainer::removeShortLines(std::string line, int line_counter)
//
// @param std::string line - the input line to check
// @param int line_counter - The line number - used for error messages.
//
// This function takes an input line, check's it's length and informs the user if it's too short
// If the line is of a proper length, it's returned to the calling class intact.
// If the line is too shorrt, it's marked as a COMMENT and returned to the calling class alongside an error message to the user.
std::string FileContainer::removeShortLines(std::string line, int line_counter){
// If line length warnings are enabled, warn the user on lines < 5 chars long.
if((line.length() < MINIMUM_LINE_LENGTH) && !(::lineIsComment(line))) {
Logging::logWarnMessage("Line { " + line + " }[" + std::to_string(line_counter) + "] has an unusually short length. It will be marked as a comment and ignored.");
line.insert(0, COMMENT_STRING);
}
return line;
}
| 61.292419
| 207
| 0.570503
|
ElliotAlexander
|
fdd3e49bdee1fa7ff0ac22ddaeaccd025fdb5841
| 3,159
|
cc
|
C++
|
Alignment/MuonAlignment/src/AlignableCSCRing.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | 3
|
2018-08-24T19:10:26.000Z
|
2019-02-19T11:45:32.000Z
|
Alignment/MuonAlignment/src/AlignableCSCRing.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | 3
|
2018-08-23T13:40:24.000Z
|
2019-12-05T21:16:03.000Z
|
Alignment/MuonAlignment/src/AlignableCSCRing.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | 5
|
2018-08-21T16:37:52.000Z
|
2020-01-09T13:33:17.000Z
|
/** \file
*
* $Date: 2008/04/10 16:36:41 $
* $Revision: 1.2 $
* \author Jim Pivarski - Texas A&M University
*/
#include "Alignment/MuonAlignment/interface/AlignableCSCRing.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
/// The constructor simply copies the vector of CSC Chambers and computes the surface from them
AlignableCSCRing::AlignableCSCRing( const std::vector<AlignableCSCChamber*>& cscChambers )
: AlignableComposite(cscChambers[0]->id(), align::AlignableCSCRing)
{
theCSCChambers.insert( theCSCChambers.end(), cscChambers.begin(), cscChambers.end() );
// maintain also list of components
for (const auto& chamber: cscChambers) {
const auto mother = chamber->mother();
this->addComponent(chamber); // components will be deleted by dtor of AlignableComposite
chamber->setMother(mother); // restore previous behaviour where mother is not set
}
setSurface( computeSurface() );
compConstraintType_ = Alignable::CompConstraintType::POSITION_Z;
}
/// Return Alignable CSC Chamber at given index
AlignableCSCChamber &AlignableCSCRing::chamber(int i)
{
if (i >= size() )
throw cms::Exception("LogicError") << "CSC Chamber index (" << i << ") out of range";
return *theCSCChambers[i];
}
/// Returns surface corresponding to current position
/// and orientation, as given by average on all components
AlignableSurface AlignableCSCRing::computeSurface()
{
return AlignableSurface( computePosition(), computeOrientation() );
}
/// Compute average z position from all components (x and y forced to 0)
AlignableCSCRing::PositionType AlignableCSCRing::computePosition()
{
float zz = 0.;
for ( std::vector<AlignableCSCChamber*>::iterator ichamber = theCSCChambers.begin();
ichamber != theCSCChambers.end(); ichamber++ )
zz += (*ichamber)->globalPosition().z();
zz /= static_cast<float>(theCSCChambers.size());
return PositionType( 0.0, 0.0, zz );
}
/// Just initialize to default given by default constructor of a RotationType
AlignableCSCRing::RotationType AlignableCSCRing::computeOrientation()
{
return RotationType();
}
// /// Twists all components by given angle
// void AlignableCSCRing::twist(float rad)
// {
// for ( std::vector<AlignableCSCChamber*>::iterator iter = theCSCChambers.begin();
// iter != theCSCChambers.end(); iter++ )
// (*iter)->twist(rad);
// }
/// Output Ring information
std::ostream &operator << (std::ostream& os, const AlignableCSCRing& b )
{
os << "This CSC Ring contains " << b.theCSCChambers.size() << " CSC chambers" << std::endl;
os << "(phi, r, z) = (" << b.globalPosition().phi() << ","
<< b.globalPosition().perp() << "," << b.globalPosition().z();
os << "), orientation:" << std::endl<< b.globalRotation() << std::endl;
return os;
}
/// Recursive printout of whole CSC Ring structure
void AlignableCSCRing::dump( void ) const
{
edm::LogInfo("AlignableDump") << (*this);
for ( std::vector<AlignableCSCChamber*>::const_iterator iChamber = theCSCChambers.begin();
iChamber != theCSCChambers.end(); iChamber++ )
edm::LogInfo("AlignableDump") << (**iChamber);
}
| 27.955752
| 95
| 0.692624
|
nistefan
|
fdd493d32f76a7ed6b8fa178d9fcc64a0da46888
| 2,889
|
cpp
|
C++
|
stacks-and-queues/queue-implementation-using-stacks.cpp
|
kanishkdudeja/cracking-the-coding-interview-solutions
|
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
|
[
"MIT"
] | 1
|
2019-12-29T17:47:53.000Z
|
2019-12-29T17:47:53.000Z
|
stacks-and-queues/queue-implementation-using-stacks.cpp
|
kanishkdudeja/cracking-the-coding-interview-solutions
|
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
|
[
"MIT"
] | null | null | null |
stacks-and-queues/queue-implementation-using-stacks.cpp
|
kanishkdudeja/cracking-the-coding-interview-solutions
|
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
|
[
"MIT"
] | null | null | null |
/* Implement a Queue (FIFO) using 2 Stacks (LIFO)
Method 1 (By making enQueue operation costly): This method makes sure that oldest entered element is
always at the top of stack 1, so that deQueue operation just pops from stack1.
To put the element at top of stack1, stack2 is used.
enQueue(q, x)
1) While stack1 is not empty, push everything from satck1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
dnQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it
Method 2 (By making deQueue operation costly): In this method, in en-queue operation,
the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty
then all the elements are moved to stack2 and finally top of stack2 is returned.
enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).
deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything from stack1 to stack2.
3) Pop the element from stack2 and return it.
Method 2 is definitely better than method 1.
Method 1 moves all the elements twice in enQueue operation, while method 2 (in deQueue operation)
moves the elements once and moves elements only if stack2 empty.
Space Complexity = O(n) where n is the number of elements in the stack
Time Complexuity = O(n) where n is the number of elements in the stack
*/
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class Stack {
Node* head;
public:
Stack() {
head = NULL;
}
Node* getNewNode(int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void push(int data) {
if(head == NULL) {
head = getNewNode(data);
}
else {
Node* newNode = getNewNode(data);
newNode->next = head;
head = newNode;
}
}
int pop() {
if(head == NULL) {
return -1;
}
else {
int data = head->data;
if(head->next == NULL) {
free(head);
head = NULL;
}
else {
Node* tmp;
tmp = head;
head = head->next;
free(tmp);
}
return data;
}
}
bool isEmpty() {
if(head == NULL) {
return true;
}
else {
return false;
}
}
int getElementAtTop() {
if(head == NULL) {
return -1;
}
else {
return head->data;
}
}
};
class Queue {
Stack s1;
Stack s2;
public:
Queue() {
s1 = Stack();
s2 = Stack();
}
void enqueue(int data) {
s1.push(data);
}
int dequeue() {
if(s2.isEmpty()) {
while(!(s1.isEmpty())) {
s2.push(s1.pop());
}
}
return s2.pop();
}
bool isEmpty() {
return s1.isEmpty() && s2.isEmpty();
}
};
int main() {
Queue q = Queue();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
cout<<q.dequeue();
cout<<q.dequeue();
cout<<q.dequeue();
cout<<q.dequeue();
}
| 17.833333
| 101
| 0.642437
|
kanishkdudeja
|
fdd4964cc6e19703f63f2854dec0de25a2a2d478
| 989
|
cpp
|
C++
|
Customized-Build/il2cpp/Il2CppOutputProject/IL2CPP/libil2cpp/vm-utils/NativeDelegateMethodCache.cpp
|
cqtd/custom-il2cpp-build-pipeline-example
|
9ec4973d98ddfcefee72b01225a3b7613312096b
|
[
"MIT"
] | 1
|
2022-03-28T07:59:17.000Z
|
2022-03-28T07:59:17.000Z
|
Customized-Build/il2cpp/Il2CppOutputProject/IL2CPP/libil2cpp/vm-utils/NativeDelegateMethodCache.cpp
|
cqtd/custom-il2cpp-build-pipeline-example
|
9ec4973d98ddfcefee72b01225a3b7613312096b
|
[
"MIT"
] | null | null | null |
Customized-Build/il2cpp/Il2CppOutputProject/IL2CPP/libil2cpp/vm-utils/NativeDelegateMethodCache.cpp
|
cqtd/custom-il2cpp-build-pipeline-example
|
9ec4973d98ddfcefee72b01225a3b7613312096b
|
[
"MIT"
] | 2
|
2022-03-24T19:58:31.000Z
|
2022-03-24T22:55:43.000Z
|
#include "il2cpp-config.h"
#if !RUNTIME_TINY
#include "NativeDelegateMethodCache.h"
#include "os/Mutex.h"
namespace il2cpp
{
namespace utils
{
baselib::ReentrantLock NativeDelegateMethodCache::m_CacheMutex;
NativeDelegateMap NativeDelegateMethodCache::m_NativeDelegateMethods;
const VmMethod* NativeDelegateMethodCache::GetNativeDelegate(Il2CppMethodPointer nativeFunctionPointer)
{
os::FastAutoLock lock(&m_CacheMutex);
NativeDelegateMap::iterator i = m_NativeDelegateMethods.find(nativeFunctionPointer);
if (i == m_NativeDelegateMethods.end())
return NULL;
return i->second;
}
void NativeDelegateMethodCache::AddNativeDelegate(Il2CppMethodPointer nativeFunctionPointer, const VmMethod* managedMethodInfo)
{
os::FastAutoLock lock(&m_CacheMutex);
m_NativeDelegateMethods.insert(std::make_pair(nativeFunctionPointer, managedMethodInfo));
}
} // namespace utils
} // namespace il2cpp
#endif
| 28.257143
| 131
| 0.751264
|
cqtd
|
fdd6494a5c9ea4e7546efa4dd559c5d98be9614f
| 2,192
|
cc
|
C++
|
day05/ex05/Form.cc
|
BimManager/cpp_piscine
|
170cdb37a057bff5a5d1299d51a6dcfef469bfad
|
[
"MIT"
] | null | null | null |
day05/ex05/Form.cc
|
BimManager/cpp_piscine
|
170cdb37a057bff5a5d1299d51a6dcfef469bfad
|
[
"MIT"
] | null | null | null |
day05/ex05/Form.cc
|
BimManager/cpp_piscine
|
170cdb37a057bff5a5d1299d51a6dcfef469bfad
|
[
"MIT"
] | null | null | null |
// Copyright 2020 kkozlov
#include <string>
#include <iostream>
#include "Form.h"
Form::Form(std::string const &name,
unsigned minGradeToSign,
unsigned minGradeToExecute,
std::string const &target) throw()
: name_(name) , minGradeToSign_(minGradeToSign),
minGradeToExecute_(minGradeToExecute), target_(target) {
if (minGradeToSign > Bureaucrat::MinGrade() ||
minGradeToExecute > Bureaucrat::MinGrade() )
throw GradeTooLowException();
if (minGradeToSign < Bureaucrat::MaxGrade() ||
minGradeToExecute < Bureaucrat::MaxGrade())
throw GradeTooHighException();
}
Form::Form(Form const &other)
: name_(other.Name()), minGradeToSign_(other.MinGradeToSign()),
minGradeToExecute_(other.MinGradeToExecute()) {}
Form::~Form(void) {}
Form &Form::operator=(Form const &rhs) {
if (&rhs != this) {
isSigned_ = rhs.IsSigned();
}
return *this;
}
std::string const &Form::Name(void) const {
return name_;
}
unsigned Form::MinGradeToSign(void) const {
return minGradeToSign_;
}
unsigned Form::MinGradeToExecute(void) const {
return minGradeToExecute_;
}
bool Form::IsSigned(void) const {
return isSigned_;
}
std::string const &Form::Target(void) const {
return target_;
}
void Form::BeSigned(Bureaucrat const &bureaucrat) throw() {
if (bureaucrat.Grade() > minGradeToSign_)
throw GradeTooLowException();
isSigned_ = true;
}
void Form::Execute(Bureaucrat const &bureaucrat) throw() {
if (bureaucrat.Grade() > minGradeToExecute_)
throw GradeTooLowException();
if (!isSigned_) {
std::cout << name_ << " is not signed." << std::endl;
} else {
this->Action();
}
}
char const *Form::GradeTooLowException::what(void) const throw() {
return "The grade too low exception\n";
}
char const *Form::GradeTooHighException::what(void) const throw() {
return "The maximum grade is 150\n";
}
std::ostream &operator<<(std::ostream &os, Form const &in) {
os << in.Name() << "\nMinimum grade to sign it: " << in.MinGradeToSign()
<< "\nMinimum grade to execute it: " << in.MinGradeToExecute()
<< "\nIs signed: " << (in.IsSigned() ? "yes" : "no") << std::endl;
return os;
}
| 25.788235
| 74
| 0.671533
|
BimManager
|
fdd686b00bc83b03781868f014f154e3f7690824
| 5,722
|
cpp
|
C++
|
Applications/ctkPluginBrowser/ctkQtResourcesTreeModel.cpp
|
ntoussaint/CTK
|
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
|
[
"Apache-2.0"
] | 515
|
2015-01-13T05:42:10.000Z
|
2022-03-29T03:10:01.000Z
|
Applications/ctkPluginBrowser/ctkQtResourcesTreeModel.cpp
|
ntoussaint/CTK
|
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
|
[
"Apache-2.0"
] | 425
|
2015-01-06T05:28:38.000Z
|
2022-03-08T19:42:18.000Z
|
Applications/ctkPluginBrowser/ctkQtResourcesTreeModel.cpp
|
ntoussaint/CTK
|
fc7a5f78fff4c4394ee5ede2f21975c6a44dfea4
|
[
"Apache-2.0"
] | 341
|
2015-01-08T06:18:17.000Z
|
2022-03-29T21:47:49.000Z
|
/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "ctkQtResourcesTreeModel.h"
class ctkQtResourceTreeNode;
class ctkQtResourceTreeItem
{
public:
ctkQtResourceTreeItem(const QFileInfo& fileInfo, ctkQtResourceTreeNode* parent = 0);
virtual ~ctkQtResourceTreeItem();
virtual ctkQtResourceTreeItem* child(int row);
virtual int childCount() const;
int row();
QVariant data(int role) const;
ctkQtResourceTreeNode* parent() const;
protected:
QFileInfo entry;
ctkQtResourceTreeNode* parentNode;
};
class ctkQtResourceTreeNode : public ctkQtResourceTreeItem
{
public:
ctkQtResourceTreeNode(const QFileInfo& dirInfo, ctkQtResourceTreeNode* parent = 0);
~ctkQtResourceTreeNode();
ctkQtResourceTreeItem* child(int row);
int childCount() const;
int indexOf(ctkQtResourceTreeItem* child) const;
private:
QList<ctkQtResourceTreeItem*> children;
};
ctkQtResourceTreeItem::ctkQtResourceTreeItem(const QFileInfo& fileInfo, ctkQtResourceTreeNode* parent)
: entry(fileInfo), parentNode(parent)
{
}
ctkQtResourceTreeItem::~ctkQtResourceTreeItem()
{
}
ctkQtResourceTreeItem* ctkQtResourceTreeItem::child(int row)
{
Q_UNUSED(row)
return 0;
}
int ctkQtResourceTreeItem::childCount() const
{
return 0;
}
int ctkQtResourceTreeItem::row()
{
if (parentNode)
{
return parentNode->indexOf(this);
}
return 0;
}
QVariant ctkQtResourceTreeItem::data(int role) const
{
if (role == Qt::DisplayRole)
{
if (entry.isFile())
return entry.fileName();
QString lastDir = entry.absoluteFilePath();
int i = lastDir.lastIndexOf('/');
if (i == lastDir.size()-1) return lastDir;
return lastDir.mid(i+1);
}
return QVariant();
}
ctkQtResourceTreeNode* ctkQtResourceTreeItem::parent() const
{
return parentNode;
}
ctkQtResourceTreeNode::ctkQtResourceTreeNode(const QFileInfo& dirInfo, ctkQtResourceTreeNode* parent)
: ctkQtResourceTreeItem(dirInfo, parent)
{
QFileInfoList infoList = QDir(dirInfo.absoluteFilePath()).entryInfoList();
QListIterator<QFileInfo> it(infoList);
while (it.hasNext())
{
const QFileInfo& info = it.next();
if (info.isFile())
{
children.push_back(new ctkQtResourceTreeItem(info, this));
}
else
{
children.push_back(new ctkQtResourceTreeNode(info, this));
}
}
}
ctkQtResourceTreeNode::~ctkQtResourceTreeNode()
{
qDeleteAll(children);
}
ctkQtResourceTreeItem* ctkQtResourceTreeNode::child(int row)
{
return children.value(row);
}
int ctkQtResourceTreeNode::childCount() const
{
return children.size();
}
int ctkQtResourceTreeNode::indexOf(ctkQtResourceTreeItem* child) const
{
return children.indexOf(child);
}
ctkQtResourcesTreeModel::ctkQtResourcesTreeModel(QObject* parent)
: QAbstractItemModel(parent)
{
rootItem = new ctkQtResourceTreeNode(QFileInfo(":/"));
}
ctkQtResourcesTreeModel::~ctkQtResourcesTreeModel()
{
delete rootItem;
}
QVariant ctkQtResourcesTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::DisplayRole)
{
ctkQtResourceTreeItem* item = static_cast<ctkQtResourceTreeItem*>(index.internalPointer());
return item->data(role);
}
return QVariant();
}
Qt::ItemFlags ctkQtResourcesTreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
QVariant ctkQtResourcesTreeModel::headerData(int section, Qt::Orientation orientation,
int role) const
{
Q_UNUSED(section)
Q_UNUSED(orientation)
Q_UNUSED(role)
return QVariant();
}
QModelIndex ctkQtResourcesTreeModel::index(int row, int column,
const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
if (!parent.isValid())
return createIndex(row, column, rootItem);
ctkQtResourceTreeItem* parentItem = static_cast<ctkQtResourceTreeItem*>(parent.internalPointer());
ctkQtResourceTreeItem* childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex ctkQtResourcesTreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
ctkQtResourceTreeItem* childItem = static_cast<ctkQtResourceTreeItem*>(index.internalPointer());
ctkQtResourceTreeItem* parentItem = childItem->parent();
if (parentItem)
return createIndex(parentItem->row(), 0, parentItem);
return QModelIndex();
}
int ctkQtResourcesTreeModel::rowCount(const QModelIndex &parent) const
{
if (parent.column() > 0) return 0;
if (!parent.isValid())
{
return 1;
}
else
{
ctkQtResourceTreeItem* parentItem = static_cast<ctkQtResourceTreeItem*>(parent.internalPointer());
return parentItem->childCount();
}
}
int ctkQtResourcesTreeModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return 1;
}
| 21.756654
| 102
| 0.714086
|
ntoussaint
|
fdd6ee4f7a4e42ba9c2f87ceda9e6be1812f94f5
| 1,404
|
cpp
|
C++
|
app/ios/frame/Application.cpp
|
Houkime/echo
|
d115ca55faf3a140bea04feffeb2efdedb0e7f82
|
[
"MIT"
] | 675
|
2019-02-07T01:23:19.000Z
|
2022-03-28T05:45:10.000Z
|
app/ios/frame/Application.cpp
|
Houkime/echo
|
d115ca55faf3a140bea04feffeb2efdedb0e7f82
|
[
"MIT"
] | 843
|
2019-01-25T01:06:46.000Z
|
2022-03-16T11:15:53.000Z
|
app/ios/frame/Application.cpp
|
Houkime/echo
|
d115ca55faf3a140bea04feffeb2efdedb0e7f82
|
[
"MIT"
] | 83
|
2019-02-20T06:18:46.000Z
|
2022-03-20T09:36:09.000Z
|
#include "Application.h"
#include <engine/core/util/PathUtil.h>
#include <engine/core/main/Engine.h>
#include <engine/core/render/base/Renderer.h>
extern float iOSGetScreenWidth();
extern float iOSGetScreenHeight();
namespace Echo
{
Application::Application()
{
}
Application::~Application()
{
}
Application* Application::instance()
{
static Application* inst = EchoNew(Application);
return inst;
}
void Application::init(int width, int height, const String& rootPath, const String& userPath)
{
m_log = EchoNew(GameLog("Game"));
Echo::Log::instance()->addOutput(m_log);
Echo::initRender(0);
Engine::Config rootcfg;
rootcfg.m_projectFile = rootPath + "/data/app.echo";
rootcfg.m_userPath = userPath;
rootcfg.m_isGame = true;
Engine::instance()->initialize(rootcfg);
}
// tick ms
void Application::tick(float elapsedTime)
{
checkScreenSize();
Engine::instance()->tick(elapsedTime);
}
// check screen size
void Application::checkScreenSize()
{
static float width = 0;
static float height = 0;
if(width!=iOSGetScreenWidth() || height!=iOSGetScreenHeight())
{
width = iOSGetScreenWidth();
height = iOSGetScreenHeight();
Engine::instance()->onSize( width, height);
}
}
}
| 23.016393
| 97
| 0.619658
|
Houkime
|
fdda4badbd4738a5852cf2ad0007285c82b92690
| 17,015
|
cc
|
C++
|
programs/mctimings/mctimings.cc
|
rualso/kv_engine
|
17680c38a77d3a67fda55f763cc2631f924ed42d
|
[
"BSD-3-Clause"
] | null | null | null |
programs/mctimings/mctimings.cc
|
rualso/kv_engine
|
17680c38a77d3a67fda55f763cc2631f924ed42d
|
[
"BSD-3-Clause"
] | null | null | null |
programs/mctimings/mctimings.cc
|
rualso/kv_engine
|
17680c38a77d3a67fda55f763cc2631f924ed42d
|
[
"BSD-3-Clause"
] | null | null | null |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, 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 "programs/hostname_utils.h"
#include "programs/getpass.h"
#include <getopt.h>
#include <memcached/protocol_binary.h>
#include <nlohmann/json.hpp>
#include <platform/string_hex.h>
#include <protocol/connection/client_connection.h>
#include <protocol/connection/client_mcbp_commands.h>
#include <utilities/json_utilities.h>
#include <utilities/terminate_handler.h>
#include <inttypes.h>
#include <strings.h>
#include <array>
#include <cstdlib>
#include <gsl/gsl>
#include <iostream>
#include <stdexcept>
#define JSON_DUMP_INDENT_SIZE 4
class Timings {
public:
explicit Timings(const nlohmann::json& json) {
initialize(json);
}
uint64_t getTotal() const {
return total;
}
void dumpHistogram(const std::string& opcode) {
if (data.is_null()) {
return;
}
std::cout << "The following data is collected for \"" << opcode << "\""
<< std::endl;
auto dataArray = data.get<std::vector<std::vector<nlohmann::json>>>();
for (auto item : dataArray) {
auto count = item[1].get<uint64_t>();
if (count > maxCount) {
maxCount = count;
}
}
using namespace std::chrono;
// loop though all the buckets in the json object and print them
// to std out
uint64_t lastBuckLow = bucketsLow;
for (auto bucket : dataArray) {
// Get the current bucket's highest value it would track counts for
auto buckHigh = bucket[0].get<uint64_t>();
// Get the counts for this bucket
auto count = bucket[1].get<uint64_t>();
// Get the percentile of counts that are <= buckHigh
auto percentile = bucket[2].get<double>();
if (lastBuckLow != buckHigh) {
// Cast the high bucket width to us, ms and seconds so we
// can check which units we should be using for this bucket
auto buckHighUs = microseconds(buckHigh);
auto buckHighMs = duration_cast<milliseconds>(buckHighUs);
auto buckHighS = duration_cast<seconds>(buckHighUs);
// If the bucket width values are in the order of tens of
// seconds or milli seconds then print them as seconds or milli
// seconds respectively. Otherwise print them as micro seconds
// We're using tens of unit thresh holds so that each bucket
// has 2 sig fig of differentiation in their width, so we dont
// have buckets that are [1 - 1]s 100 (90.000%)
if (buckHighS.count() > 10) {
auto low =
duration_cast<seconds>(microseconds(lastBuckLow));
dump("s",
low.count(),
buckHighS.count(),
count,
percentile);
} else if (buckHighMs.count() > 10) {
auto low = duration_cast<milliseconds>(
microseconds(lastBuckLow));
dump("ms",
low.count(),
buckHighMs.count(),
count,
percentile);
} else {
dump("us", lastBuckLow, buckHigh, count, percentile);
}
}
// Set the low bucket value to this buckets high width value.
lastBuckLow = buckHigh;
}
std::cout << "Total: " << total << " operations" << std::endl;
}
private:
void initialize(const nlohmann::json& root) {
if (root.find("error") != root.end()) {
// The server responded with an error.. send that to the user
throw std::runtime_error(root["error"].get<std::string>());
}
if (root.find("data") != root.end()) {
total = cb::jsonGet<uint64_t>(root, "total");
data = cb::jsonGet<nlohmann::json>(root, "data");
bucketsLow = cb::jsonGet<uint64_t>(root, "bucketsLow");
}
}
void dump(const char* timeunit,
int64_t low,
int64_t high,
int64_t count,
double percentile) {
char buffer[1024];
int offset = sprintf(
buffer, "[%5" PRId64 " - %5" PRId64 "]%s", low, high, timeunit);
offset += sprintf(buffer + offset, " (%6.4lf%%)\t", percentile);
// Determine how wide the max value would be, and pad all counts
// to that width.
int max_width = snprintf(buffer, 0, "%" PRIu64, maxCount);
offset += sprintf(buffer + offset, " %*" PRId64, max_width, count);
double factionOfHashes = (count / static_cast<double>(maxCount));
int num = static_cast<int>(44.0 * factionOfHashes);
offset += sprintf(buffer + offset, " | ");
for (int ii = 0; ii < 44 && ii < num; ++ii) {
offset += sprintf(buffer + offset, "#");
}
std::cout << buffer << std::endl;
}
/**
* The highest value of all the samples (used to figure out the width
* used for each sample in the printout)
*/
uint64_t maxCount = 0;
/**
* Json object to store the data returned by memcached
*/
nlohmann::json data;
/**
* The starting point of the lowest buckets width.
* E.g. if buckets were [10 - 20][20 - 30] it would be 10.
* Used to help reduce the amount the amount of json sent to
* mctimings
*/
uint64_t bucketsLow = 0;
/**
* Total number of counts recorded in the histogram
*/
uint64_t total = 0;
};
std::string opcode2string(cb::mcbp::ClientOpcode opcode) {
try {
return to_string(opcode);
} catch (const std::exception&) {
return cb::to_hex(uint8_t(opcode));
}
}
static void request_cmd_timings(MemcachedConnection& connection,
const std::string& bucket,
cb::mcbp::ClientOpcode opcode,
bool verbose,
bool skip,
bool json) {
BinprotGetCmdTimerCommand cmd;
cmd.setBucket(bucket);
cmd.setOpcode(opcode);
connection.sendCommand(cmd);
BinprotGetCmdTimerResponse resp;
connection.recvResponse(resp);
if (!resp.isSuccess()) {
switch (resp.getStatus()) {
case cb::mcbp::Status::KeyEnoent:
std::cerr << "Cannot find bucket: " << bucket << std::endl;
break;
case cb::mcbp::Status::Eaccess:
if (bucket == "/all/") {
std::cerr << "Not authorized to access aggregated timings data."
<< std::endl
<< "Try specifying a bucket by using -b bucketname"
<< std::endl;
} else {
std::cerr << "Not authorized to access timings data"
<< std::endl;
}
break;
default:
std::cerr << "Command failed: " << to_string(resp.getStatus())
<< std::endl;
}
exit(EXIT_FAILURE);
}
try {
auto command = opcode2string(opcode);
if (json) {
auto timings = resp.getTimings();
if (timings == nullptr) {
if (!skip) {
std::cerr << "The server doesn't have information about \""
<< command << "\"" << std::endl;
}
} else {
timings["command"] = command;
std::cout << timings.dump(JSON_DUMP_INDENT_SIZE) << std::endl;
}
} else {
Timings timings(resp.getTimings());
if (timings.getTotal() == 0) {
if (skip == 0) {
std::cout << "The server doesn't have information about \""
<< command << "\"" << std::endl;
}
} else {
if (verbose) {
timings.dumpHistogram(command);
} else {
std::cout << command << " " << timings.getTotal()
<< " operations" << std::endl;
}
}
}
} catch (const std::exception& e) {
std::cerr << "Fatal error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
}
static void request_stat_timings(MemcachedConnection& connection,
const std::string& key,
bool verbose,
bool json_output) {
std::map<std::string, std::string> map;
try {
map = connection.statsMap(key);
} catch (const ConnectionError& ex) {
if (ex.isNotFound()) {
std::cerr << "Cannot find statistic: " << key << std::endl;
} else if (ex.isAccessDenied()) {
std::cerr << "Not authorized to access timings data" << std::endl;
} else {
std::cerr << "Fatal error: " << ex.what() << std::endl;
}
exit(EXIT_FAILURE);
}
// The return value from stats injects the result in a k-v pair, but
// these responses (i.e. subdoc_execute) don't include a key,
// so the statsMap adds them into the map with a counter to make sure
// that you can fetch all of them. We only expect a single entry, which
// would be named "0"
auto iter = map.find("0");
if (iter == map.end()) {
std::cerr << "Failed to fetch statistics for \"" << key << "\""
<< std::endl;
exit(EXIT_FAILURE);
}
// And the value for the item should be valid JSON
nlohmann::json json = nlohmann::json::parse(iter->second);
if (json.is_null()) {
std::cerr << "Failed to fetch statistics for \"" << key
<< "\". Not json" << std::endl;
exit(EXIT_FAILURE);
}
try {
if (json_output) {
json["command"] = key;
std::cout << json.dump(JSON_DUMP_INDENT_SIZE) << std::endl;
} else {
Timings timings(json);
if (verbose) {
timings.dumpHistogram(key);
} else {
std::cout << key << " " << timings.getTotal() << " operations"
<< std::endl;
}
}
} catch (const std::exception& e) {
std::cerr << "Fatal error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
}
void usage() {
std::cerr << "Usage mctimings [options] [opcode / statname]\n"
<< R"(Options:
-h or --host hostname[:port] The host (with an optional port) to connect to
-p or --port port The port number to connect to
-b or --bucket bucketname The name of the bucket to operate on
-u or --user username The name of the user to authenticate as
-P or --password password The passord to use for authentication
(use '-' to read from standard input)
-s or --ssl Connect to the server over SSL
-4 or --ipv4 Connect over IPv4
-6 or --ipv6 Connect over IPv6
-v or --verbose Use verbose output
-S Read password from standard input
-j or --json[=pretty] Print JSON instead of histograms
--help This help text
)" << std::endl
<< std::endl
<< "Example:" << std::endl
<< " mctimings --user operator --bucket /all/ --password - "
"--verbose GET SET"
<< std::endl;
}
int main(int argc, char** argv) {
// Make sure that we dump callstacks on the console
install_backtrace_terminate_handler();
int cmd;
std::string port{"11210"};
std::string host{"localhost"};
std::string user{};
std::string password{};
std::string bucket{"/all/"};
sa_family_t family = AF_UNSPEC;
bool verbose = false;
bool secure = false;
bool json = false;
/* Initialize the socket subsystem */
cb_initialize_sockets();
struct option long_options[] = {
{"ipv4", no_argument, nullptr, '4'},
{"ipv6", no_argument, nullptr, '6'},
{"host", required_argument, nullptr, 'h'},
{"port", required_argument, nullptr, 'p'},
{"bucket", required_argument, nullptr, 'b'},
{"password", required_argument, nullptr, 'P'},
{"user", required_argument, nullptr, 'u'},
{"ssl", no_argument, nullptr, 's'},
{"verbose", no_argument, nullptr, 'v'},
{"json", optional_argument, nullptr, 'j'},
{"help", no_argument, nullptr, 0},
{nullptr, 0, nullptr, 0}};
while ((cmd = getopt_long(
argc, argv, "46h:p:u:b:P:sSvj", long_options, nullptr)) !=
EOF) {
switch (cmd) {
case '6':
family = AF_INET6;
break;
case '4':
family = AF_INET;
break;
case 'h':
host.assign(optarg);
break;
case 'p':
port.assign(optarg);
break;
case 'S':
password.assign("-");
break;
case 'b':
bucket.assign(optarg);
break;
case 'u':
user.assign(optarg);
break;
case 'P':
password.assign(optarg);
break;
case 's':
secure = true;
break;
case 'v':
verbose = true;
break;
case 'j':
json = true;
if (optarg && strcasecmp(optarg, "pretty") == 0) {
verbose = true;
}
break;
default:
usage();
return cmd == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
}
if (password == "-") {
password.assign(getpass());
} else if (password.empty()) {
const char* env_password = std::getenv("CB_PASSWORD");
if (env_password) {
password = env_password;
}
}
try {
in_port_t in_port;
sa_family_t fam;
std::tie(host, in_port, fam) = cb::inet::parse_hostname(host, port);
if (family == AF_UNSPEC) { // The user may have used -4 or -6
family = fam;
}
MemcachedConnection connection(host, in_port, family, secure);
connection.connect();
// MEMCACHED_VERSION contains the git sha
connection.setAgentName("mctimings " MEMCACHED_VERSION);
connection.setFeatures({cb::mcbp::Feature::XERROR});
if (!user.empty()) {
connection.authenticate(user, password,
connection.getSaslMechanisms());
}
if (!bucket.empty() && bucket != "/all/") {
connection.selectBucket(bucket);
}
if (optind == argc) {
for (int ii = 0; ii < 256; ++ii) {
request_cmd_timings(connection,
bucket,
cb::mcbp::ClientOpcode(ii),
verbose,
true,
json);
}
} else {
for (; optind < argc; ++optind) {
try {
const auto opcode = to_opcode(argv[optind]);
request_cmd_timings(
connection, bucket, opcode, verbose, false, json);
} catch (const std::invalid_argument&) {
// Not a command timing, try as statistic timing.
request_stat_timings(
connection, argv[optind], verbose, json);
}
}
}
} catch (const ConnectionError& ex) {
std::cerr << ex.what() << std::endl;
return EXIT_FAILURE;
} catch (const std::runtime_error& ex) {
std::cerr << ex.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 34.866803
| 80
| 0.505848
|
rualso
|
fddcc50a16eccb727b556de2749bbb3f4f47376b
| 5,536
|
cc
|
C++
|
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/src/commands/hmi/bc_get_app_properties_request.cc
|
Sohei-Suzuki-Nexty/sdl_core
|
68f082169e0a40fccd9eb0db3c83911c28870f07
|
[
"BSD-3-Clause"
] | 249
|
2015-01-15T16:50:53.000Z
|
2022-03-24T13:23:34.000Z
|
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/src/commands/hmi/bc_get_app_properties_request.cc
|
Sohei-Suzuki-Nexty/sdl_core
|
68f082169e0a40fccd9eb0db3c83911c28870f07
|
[
"BSD-3-Clause"
] | 2,917
|
2015-01-12T16:17:49.000Z
|
2022-03-31T11:57:47.000Z
|
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/src/commands/hmi/bc_get_app_properties_request.cc
|
Sohei-Suzuki-Nexty/sdl_core
|
68f082169e0a40fccd9eb0db3c83911c28870f07
|
[
"BSD-3-Clause"
] | 306
|
2015-01-12T09:23:20.000Z
|
2022-01-28T18:06:30.000Z
|
/*
Copyright (c) 2020, Ford Motor Company, Livio
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 the copyright holders nor the names of their
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 "sdl_rpc_plugin/commands/hmi/bc_get_app_properties_request.h"
#include "application_manager/policies/policy_handler_interface.h"
#include "application_manager/rpc_service.h"
#include "interfaces/MOBILE_API.h"
namespace sdl_rpc_plugin {
using namespace application_manager;
namespace commands {
SDL_CREATE_LOG_VARIABLE("Commands")
BCGetAppPropertiesRequest::BCGetAppPropertiesRequest(
const application_manager::commands::MessageSharedPtr& message,
ApplicationManager& application_manager,
app_mngr::rpc_service::RPCService& rpc_service,
app_mngr::HMICapabilities& hmi_capabilities,
policy::PolicyHandlerInterface& policy_handler)
: RequestFromHMI(message,
application_manager,
rpc_service,
hmi_capabilities,
policy_handler) {}
void BCGetAppPropertiesRequest::FillAppProperties(
const std::string& policy_app_id,
smart_objects::SmartObject& out_properties) const {
SDL_LOG_AUTO_TRACE();
policy::AppProperties app_properties;
const bool result =
policy_handler_.GetAppProperties(policy_app_id, app_properties);
if (!result) {
SDL_LOG_DEBUG(
"Failed to get app parameters for policy_app_id: " << policy_app_id);
return;
}
out_properties[strings::policy_app_id] = policy_app_id;
out_properties[strings::enabled] = app_properties.enabled;
policy::StringArray nicknames;
policy::StringArray app_hmi_types;
policy_handler_.GetInitialAppData(policy_app_id, &nicknames, &app_hmi_types);
smart_objects::SmartObject nicknames_array(smart_objects::SmartType_Array);
size_t i = 0;
for (const auto& nickname : nicknames) {
nicknames_array[i++] = nickname;
}
out_properties[strings::nicknames] = nicknames_array;
if (!app_properties.auth_token.empty()) {
out_properties[strings::auth_token] = app_properties.auth_token;
}
if (!app_properties.transport_type.empty()) {
out_properties[strings::transport_type] = app_properties.transport_type;
}
if (!app_properties.hybrid_app_preference.empty()) {
out_properties[strings::hybrid_app_preference] =
app_properties.hybrid_app_preference;
}
if (!app_properties.endpoint.empty()) {
out_properties[strings::endpoint] = app_properties.endpoint;
}
}
void BCGetAppPropertiesRequest::Run() {
SDL_LOG_AUTO_TRACE();
const auto& msg_params = (*message_)[strings::msg_params];
smart_objects::SmartObject response_params(smart_objects::SmartType_Map);
if (msg_params.keyExists(strings::policy_app_id)) {
const auto policy_app_id = msg_params[strings::policy_app_id].asString();
smart_objects::SmartObject properties(smart_objects::SmartType_Map);
FillAppProperties(policy_app_id, properties);
if (!properties.empty()) {
response_params[strings::properties][0] = properties;
}
} else {
SDL_LOG_DEBUG(
"policyAppID was absent in request, all apps properties "
"will be returned.");
const auto app_ids = policy_handler_.GetApplicationPolicyIDs();
int i = 0;
for (auto& app_id : app_ids) {
smart_objects::SmartObject properties(smart_objects::SmartType_Map);
FillAppProperties(app_id, properties);
response_params[strings::properties][i++] = properties;
}
}
if (response_params[strings::properties].empty()) {
SendErrorResponse(
(*message_)[strings::params][strings::correlation_id].asUInt(),
hmi_apis::FunctionID::BasicCommunication_GetAppProperties,
hmi_apis::Common_Result::DATA_NOT_AVAILABLE,
"Requested data not available",
application_manager::commands::Command::SOURCE_SDL_TO_HMI);
return;
}
SendResponse(true,
(*message_)[strings::params][strings::correlation_id].asUInt(),
hmi_apis::FunctionID::BasicCommunication_GetAppProperties,
hmi_apis::Common_Result::SUCCESS,
&response_params);
}
} // namespace commands
} // namespace sdl_rpc_plugin
| 37.917808
| 79
| 0.748736
|
Sohei-Suzuki-Nexty
|
fddd0fa97b30ca9e0f8cb35a3252b3458570fc21
| 3,368
|
cpp
|
C++
|
common/Log.cpp
|
MaynardMiner/energiminer
|
25fabd8293de254e62b6d5117a8c077c120124ec
|
[
"MIT"
] | null | null | null |
common/Log.cpp
|
MaynardMiner/energiminer
|
25fabd8293de254e62b6d5117a8c077c120124ec
|
[
"MIT"
] | null | null | null |
common/Log.cpp
|
MaynardMiner/energiminer
|
25fabd8293de254e62b6d5117a8c077c120124ec
|
[
"MIT"
] | null | null | null |
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Log.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Log.h"
#include "common.h"
#include <iomanip>
#include <iostream>
#include <mutex>
#include <thread>
#ifdef __APPLE__
#include <pthread.h>
#endif
using namespace std;
using namespace energi;
//⊳⊲◀▶■▣▢□▷◁▧▨▩▲◆◉◈◇◎●◍◌○◼☑☒☎☢☣☰☀♽♥♠✩✭❓✔✓✖✕✘✓✔✅⚒⚡⦸⬌∅⁕«««»»»⚙
// Logging
int g_logVerbosity = 5;
bool g_logNoColor = false;
bool g_logSyslog = false;
const char* LogChannel::name()
{
return EthGray "..";
}
const char* WarnChannel::name()
{
return EthRed " X";
}
const char* NoteChannel::name()
{
return EthBlue " i";
}
LogOutputStreamBase::LogOutputStreamBase(char const* _id, unsigned _v) : m_verbosity(_v)
{
static std::locale logLocl = std::locale("");
if ((int)_v <= g_logVerbosity) {
m_sstr.imbue(logLocl);
if (g_logSyslog)
m_sstr << std::left << std::setw(8) << getThreadName() << " " EthReset;
else {
time_t rawTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char buf[24];
if (strftime(buf, 24, "%X", localtime(&rawTime)) == 0)
buf[0] = '\0'; // empty if case strftime fails
m_sstr << _id << " " EthViolet << buf << " " EthBlue << std::left << std::setw(8)
<< getThreadName() << " " EthReset;
}
}
}
/// Associate a name with each thread for nice logging.
struct ThreadLocalLogName
{
ThreadLocalLogName(char const* _name) { name = _name; }
thread_local static char const* name;
};
thread_local char const* ThreadLocalLogName::name;
ThreadLocalLogName g_logThreadName("main");
string energi::getThreadName()
{
#if defined(__linux__) || defined(__APPLE__)
char buffer[128];
pthread_getname_np(pthread_self(), buffer, 127);
buffer[127] = 0;
return buffer;
#else
return ThreadLocalLogName::name ? ThreadLocalLogName::name : "<unknown>";
#endif
}
void energi::setThreadName(char const* _n)
{
#if defined(__linux__)
pthread_setname_np(pthread_self(), _n);
#elif defined(__APPLE__)
pthread_setname_np(_n);
#else
ThreadLocalLogName::name = _n;
#endif
}
void energi::simpleDebugOut(std::string const& _s)
{
try {
if (!g_logNoColor) {
std::cerr << _s + '\n';
return;
}
bool skip = false;
std::stringstream ss;
for (auto it : _s) {
if (!skip && it == '\x1b')
skip = true;
else if (skip && it == 'm')
skip = false;
else if (!skip)
ss << it;
}
ss << '\n';
std::cerr << ss.str();
} catch (...) {
return;
}
}
| 25.134328
| 100
| 0.610154
|
MaynardMiner
|
fde0d375f28b846216645d07210a2389a7a18f58
| 9,665
|
cpp
|
C++
|
src/condor_utils/filesystem_remap.cpp
|
zhangzhehust/htcondor
|
e07510d62161f38fa2483b299196ef9a7b9f7941
|
[
"Apache-2.0"
] | 1
|
2017-02-13T01:25:34.000Z
|
2017-02-13T01:25:34.000Z
|
src/condor_utils/filesystem_remap.cpp
|
AmesianX/htcondor
|
10aea32f1717637972af90459034d1543004cb83
|
[
"Apache-2.0"
] | 1
|
2021-04-06T04:19:40.000Z
|
2021-04-06T04:19:40.000Z
|
src/condor_utils/filesystem_remap.cpp
|
AmesianX/htcondor
|
10aea32f1717637972af90459034d1543004cb83
|
[
"Apache-2.0"
] | 2
|
2016-05-24T17:12:13.000Z
|
2017-02-13T01:25:35.000Z
|
/***************************************************************
*
* Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "filename_tools.h"
#include "condor_debug.h"
#include "MyString.h"
#include "condor_uid.h"
#include "filesystem_remap.h"
#include "condor_config.h"
#include "directory.h"
#if defined(LINUX)
#include <sys/mount.h>
#endif
FilesystemRemap::FilesystemRemap() :
m_mappings(),
m_mounts_shared(),
m_remap_proc(false)
{
ParseMountinfo();
FixAutofsMounts();
}
int FilesystemRemap::AddMapping(std::string source, std::string dest) {
if (!is_relative_to_cwd(source) && !is_relative_to_cwd(dest)) {
std::list<pair_strings>::const_iterator it;
for (it = m_mappings.begin(); it != m_mappings.end(); it++) {
if ((it->second.length() == dest.length()) && (it->second.compare(dest) == 0)) {
dprintf(D_ALWAYS, "Mapping already present for %s.\n", dest.c_str());
return -1;
}
}
if (CheckMapping(dest)) {
dprintf(D_ALWAYS, "Failed to convert shared mount to private mapping");
return -1;
}
m_mappings.push_back( std::pair<std::string, std::string>(source, dest) );
} else {
dprintf(D_ALWAYS, "Unable to add mappings for relative directories (%s, %s).\n", source.c_str(), dest.c_str());
return -1;
}
return 0;
}
int FilesystemRemap::CheckMapping(const std::string & mount_point) {
#ifndef HAVE_UNSHARE
dprintf(D_ALWAYS, "This system doesn't support remounting of filesystems: %s\n", mount_point.c_str());
return -1;
#else
bool best_is_shared = false;
size_t best_len = 0;
const std::string *best = NULL;
dprintf(D_FULLDEBUG, "Checking the mapping of mount point %s.\n", mount_point.c_str());
for (std::list<pair_str_bool>::const_iterator it = m_mounts_shared.begin(); it != m_mounts_shared.end(); it++) {
std::string first = it->first;
if ((strncmp(first.c_str(), mount_point.c_str(), first.size()) == 0) && (first.size() > best_len)) {
best_len = first.size();
best = &(it->first);
best_is_shared = it->second;
}
}
if (!best_is_shared) {
return 0;
}
dprintf(D_ALWAYS, "Current mount, %s, is shared.\n", best->c_str());
#if !defined(HAVE_MS_SLAVE) && !defined(HAVE_MS_REC)
TemporaryPrivSentry sentry(PRIV_ROOT);
// Re-mount the mount point as a bind mount, so we can subsequently
// re-mount it as private.
if (mount(mount_point.c_str(), mount_point.c_str(), NULL, MS_BIND, NULL)) {
dprintf(D_ALWAYS, "Marking %s as a bind mount failed. (errno=%d, %s)\n", mount_point.c_str(), errno, strerror(errno));
return -1;
}
#ifdef HAVE_MS_PRIVATE
if (mount(mount_point.c_str(), mount_point.c_str(), NULL, MS_PRIVATE, NULL)) {
dprintf(D_ALWAYS, "Marking %s as a private mount failed. (errno=%d, %s)\n", mount_point.c_str(), errno, strerror(errno));
return -1;
} else {
dprintf(D_FULLDEBUG, "Marking %s as a private mount successful.\n", mount_point.c_str());
}
#endif
#endif
return 0;
#endif
}
int FilesystemRemap::FixAutofsMounts() {
#ifndef HAVE_UNSHARE
// An appropriate error message is printed in FilesystemRemap::CheckMapping;
// Not doing anything here.
return -1;
#else
#ifdef HAVE_MS_SHARED
TemporaryPrivSentry sentry(PRIV_ROOT);
for (std::list<pair_strings>::const_iterator it=m_mounts_autofs.begin(); it != m_mounts_autofs.end(); it++) {
if (mount(it->first.c_str(), it->second.c_str(), NULL, MS_SHARED, NULL)) {
dprintf(D_ALWAYS, "Marking %s->%s as a shared-subtree autofs mount failed. (errno=%d, %s)\n", it->first.c_str(), it->second.c_str(), errno, strerror(errno));
return -1;
} else {
dprintf(D_FULLDEBUG, "Marking %s as a shared-subtree autofs mount successful.\n", it->second.c_str());
}
}
#endif
return 0;
#endif
}
// This is called within the exec
// IT CANNOT CALL DPRINTF!
int FilesystemRemap::PerformMappings() {
int retval = 0;
#if defined(LINUX)
std::list<pair_strings>::iterator it;
for (it = m_mappings.begin(); it != m_mappings.end(); it++) {
if (strcmp(it->second.c_str(), "/") == 0) {
if ((retval = chroot(it->first.c_str()))) {
break;
}
if ((retval = chdir("/"))) {
break;
}
} else if ((retval = mount(it->first.c_str(), it->second.c_str(), NULL, MS_BIND, NULL))) {
break;
}
}
if ((!retval) && m_remap_proc) {
retval = mount("proc", "/proc", "proc", 0, NULL);
}
#endif
return retval;
}
std::string FilesystemRemap::RemapFile(std::string target) {
if (target[0] != '/')
return std::string();
size_t pos = target.rfind("/");
if (pos == std::string::npos)
return target;
std::string filename = target.substr(pos, target.size() - pos);
std::string directory = target.substr(0, target.size() - filename.size());
return RemapDir(directory) + filename;
}
std::string FilesystemRemap::RemapDir(std::string target) {
if (target[0] != '/')
return std::string();
std::list<pair_strings>::iterator it;
for (it = m_mappings.begin(); it != m_mappings.end(); it++) {
if ((it->first.compare(0, it->first.length(), target, 0, it->first.length()) == 0)
&& (it->second.compare(0, it->second.length(), it->first, 0, it->second.length()) == 0)) {
target.replace(0, it->first.length(), it->second);
}
}
return target;
}
void FilesystemRemap::RemapProc() {
m_remap_proc = true;
}
/*
Sample mountinfo contents (from http://www.kernel.org/doc/Documentation/filesystems/proc.txt):
36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
(1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11)
(1) mount ID: unique identifier of the mount (may be reused after umount)
(2) parent ID: ID of parent (or of self for the top of the mount tree)
(3) major:minor: value of st_dev for files on filesystem
(4) root: root of the mount within the filesystem
(5) mount point: mount point relative to the process's root
(6) mount options: per mount options
(7) optional fields: zero or more fields of the form "tag[:value]"
(8) separator: marks the end of the optional fields
(9) filesystem type: name of filesystem of the form "type[.subtype]"
(10) mount source: filesystem specific information or "none"
(11) super options: per super block options
*/
#define ADVANCE_TOKEN(token, str) { \
if ((token = str.GetNextToken(" ", false)) == NULL) { \
fclose(fd); \
dprintf(D_ALWAYS, "Invalid line in mountinfo file: %s\n", str.Value()); \
return; \
} \
}
#define SHARED_STR "shared:"
void FilesystemRemap::ParseMountinfo() {
MyString str, str2;
const char * token;
FILE *fd;
bool is_shared;
if ((fd = fopen("/proc/self/mountinfo", "r")) == NULL) {
if (errno == ENOENT) {
dprintf(D_FULLDEBUG, "The /proc/self/mountinfo file does not exist; kernel support probably lacking. Will assume normal mount structure.\n");
} else {
dprintf(D_ALWAYS, "Unable to open the mountinfo file (/proc/self/mountinfo). (errno=%d, %s)\n", errno, strerror(errno));
}
return;
}
while (str2.readLine(fd, false)) {
str = str2;
str.Tokenize();
ADVANCE_TOKEN(token, str) // mount ID
ADVANCE_TOKEN(token, str) // parent ID
ADVANCE_TOKEN(token, str) // major:minor
ADVANCE_TOKEN(token, str) // root
ADVANCE_TOKEN(token, str) // mount point
std::string mp(token);
ADVANCE_TOKEN(token, str) // mount options
ADVANCE_TOKEN(token, str) // optional fields
is_shared = false;
while (strcmp(token, "-") != 0) {
is_shared = is_shared || (strncmp(token, SHARED_STR, strlen(SHARED_STR)) == 0);
ADVANCE_TOKEN(token, str)
}
ADVANCE_TOKEN(token, str) // filesystem type
if ((!is_shared) && (strcmp(token, "autofs") == 0)) {
ADVANCE_TOKEN(token, str)
m_mounts_autofs.push_back(pair_strings(token, mp));
}
// This seems a bit too chatty - disabling for now.
// dprintf(D_FULLDEBUG, "Mount: %s, shared: %d.\n", mp.c_str(), is_shared);
m_mounts_shared.push_back(pair_str_bool(mp, is_shared));
}
fclose(fd);
}
pair_strings_vector
root_dir_list()
{
pair_strings_vector execute_dir_list;
execute_dir_list.push_back(pair_strings("root","/"));
const char * allowed_root_dirs = param("NAMED_CHROOT");
if (allowed_root_dirs) {
StringList chroot_list(allowed_root_dirs);
chroot_list.rewind();
const char * next_chroot;
while ( (next_chroot=chroot_list.next()) ) {
MyString chroot_spec(next_chroot);
chroot_spec.Tokenize();
const char * chroot_name = chroot_spec.GetNextToken("=", false);
if (chroot_name == NULL) {
dprintf(D_ALWAYS, "Invalid named chroot: %s\n", chroot_spec.Value());
continue;
}
const char * next_dir = chroot_spec.GetNextToken("=", false);
if (next_dir == NULL) {
dprintf(D_ALWAYS, "Invalid named chroot: %s\n", chroot_spec.Value());
continue;
}
if (IsDirectory(next_dir)) {
pair_strings p(chroot_name, next_dir);
execute_dir_list.push_back(p);
}
}
}
return execute_dir_list;
}
bool
is_trivial_rootdir(const std::string &root_dir)
{
for (std::string::const_iterator it=root_dir.begin(); it!=root_dir.end(); it++) {
if (*it != '/')
return false;
}
return true;
}
| 31.792763
| 160
| 0.66715
|
zhangzhehust
|
fde30e8fd55170e5a4a06991fe24bb0d19d51545
| 46,926
|
cpp
|
C++
|
modules/gles31/functional/es31fAtomicCounterTests.cpp
|
iabernikhin/VK-GL-CTS
|
a3338eb2ded98b5befda64f9325db0d219095a00
|
[
"Apache-2.0"
] | 354
|
2017-01-24T17:12:38.000Z
|
2022-03-30T07:40:19.000Z
|
modules/gles31/functional/es31fAtomicCounterTests.cpp
|
iabernikhin/VK-GL-CTS
|
a3338eb2ded98b5befda64f9325db0d219095a00
|
[
"Apache-2.0"
] | 275
|
2017-01-24T20:10:36.000Z
|
2022-03-24T16:24:50.000Z
|
modules/gles31/functional/es31fAtomicCounterTests.cpp
|
iabernikhin/VK-GL-CTS
|
a3338eb2ded98b5befda64f9325db0d219095a00
|
[
"Apache-2.0"
] | 190
|
2017-01-24T18:02:04.000Z
|
2022-03-27T13:11:23.000Z
|
/*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.1 Module
* -------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* 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.
*
*//*!
* \file
* \brief Basic Compute Shader Tests.
*//*--------------------------------------------------------------------*/
#include "es31fAtomicCounterTests.hpp"
#include "gluShaderProgram.hpp"
#include "gluObjectWrapper.hpp"
#include "gluRenderContext.hpp"
#include "glwFunctions.hpp"
#include "glwEnums.hpp"
#include "tcuTestLog.hpp"
#include "deStringUtil.hpp"
#include "deRandom.hpp"
#include "deMemory.h"
#include <vector>
#include <string>
using namespace glw;
using tcu::TestLog;
using std::vector;
using std::string;
namespace deqp
{
namespace gles31
{
namespace Functional
{
namespace
{
class AtomicCounterTest : public TestCase
{
public:
enum Operation
{
OPERATION_INC = (1<<0),
OPERATION_DEC = (1<<1),
OPERATION_GET = (1<<2)
};
enum OffsetType
{
OFFSETTYPE_NONE = 0,
OFFSETTYPE_BASIC,
OFFSETTYPE_REVERSE,
OFFSETTYPE_FIRST_AUTO,
OFFSETTYPE_DEFAULT_AUTO,
OFFSETTYPE_RESET_DEFAULT,
OFFSETTYPE_INVALID,
OFFSETTYPE_INVALID_OVERLAPPING,
OFFSETTYPE_INVALID_DEFAULT
};
enum BindingType
{
BINDINGTYPE_BASIC = 0,
BINDINGTYPE_INVALID,
BINDINGTYPE_INVALID_DEFAULT
};
struct TestSpec
{
TestSpec (void)
: atomicCounterCount (0)
, operations ((Operation)0)
, callCount (0)
, useBranches (false)
, threadCount (0)
, offsetType (OFFSETTYPE_NONE)
, bindingType (BINDINGTYPE_BASIC)
{
}
int atomicCounterCount;
Operation operations;
int callCount;
bool useBranches;
int threadCount;
OffsetType offsetType;
BindingType bindingType;
};
AtomicCounterTest (Context& context, const char* name, const char* description, const TestSpec& spec);
~AtomicCounterTest (void);
void init (void);
void deinit (void);
IterateResult iterate (void);
private:
const TestSpec m_spec;
bool checkAndLogCounterValues (TestLog& log, const vector<deUint32>& counters) const;
bool checkAndLogCallValues (TestLog& log, const vector<deUint32>& increments, const vector<deUint32>& decrements, const vector<deUint32>& preGets, const vector<deUint32>& postGets, const vector<deUint32>& gets) const;
void splitBuffer (const vector<deUint32>& buffer, vector<deUint32>& increments, vector<deUint32>& decrements, vector<deUint32>& preGets, vector<deUint32>& postGets, vector<deUint32>& gets) const;
deUint32 getInitialValue (void) const { return m_spec.callCount * m_spec.threadCount + 1; }
static string generateShaderSource (const TestSpec& spec);
static void getCountersValues (vector<deUint32>& counterValues, const vector<deUint32>& values, int ndx, int counterCount);
static bool checkRange (TestLog& log, const vector<deUint32>& values, const vector<deUint32>& min, const vector<deUint32>& max);
static bool checkUniquenessAndLinearity (TestLog& log, const vector<deUint32>& values);
static bool checkPath (const vector<deUint32>& increments, const vector<deUint32>& decrements, int initialValue, const TestSpec& spec);
int getOperationCount (void) const;
AtomicCounterTest& operator= (const AtomicCounterTest&);
AtomicCounterTest (const AtomicCounterTest&);
};
int AtomicCounterTest::getOperationCount (void) const
{
int count = 0;
if (m_spec.operations & OPERATION_INC)
count++;
if (m_spec.operations & OPERATION_DEC)
count++;
if (m_spec.operations == OPERATION_GET)
count++;
else if (m_spec.operations & OPERATION_GET)
count += 2;
return count;
}
AtomicCounterTest::AtomicCounterTest (Context& context, const char* name, const char* description, const TestSpec& spec)
: TestCase (context, name, description)
, m_spec (spec)
{
}
AtomicCounterTest::~AtomicCounterTest (void)
{
}
void AtomicCounterTest::init (void)
{
}
void AtomicCounterTest::deinit (void)
{
}
string AtomicCounterTest::generateShaderSource (const TestSpec& spec)
{
std::ostringstream src;
src
<< "#version 310 es\n"
<< "layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;\n";
{
bool wroteLayout = false;
switch (spec.bindingType)
{
case BINDINGTYPE_INVALID_DEFAULT:
src << "layout(binding=10000";
wroteLayout = true;
break;
default:
// Do nothing
break;
}
switch (spec.offsetType)
{
case OFFSETTYPE_DEFAULT_AUTO:
if (!wroteLayout)
src << "layout(binding=0, ";
else
src << ", ";
src << "offset=4";
wroteLayout = true;
break;
case OFFSETTYPE_RESET_DEFAULT:
DE_ASSERT(spec.atomicCounterCount > 2);
if (!wroteLayout)
src << "layout(binding=0, ";
else
src << ", ";
src << "offset=" << (4 * spec.atomicCounterCount/2);
wroteLayout = true;
break;
case OFFSETTYPE_INVALID_DEFAULT:
if (!wroteLayout)
src << "layout(binding=0, ";
else
src << ", ";
src << "offset=1";
wroteLayout = true;
break;
default:
// Do nothing
break;
}
if (wroteLayout)
src << ") uniform atomic_uint;\n";
}
src
<< "layout(binding = 1, std430) buffer Output {\n";
if ((spec.operations & OPERATION_GET) != 0 && spec.operations != OPERATION_GET)
src << " uint preGet[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
if ((spec.operations & OPERATION_INC) != 0)
src << " uint increment[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
if ((spec.operations & OPERATION_DEC) != 0)
src << " uint decrement[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
if ((spec.operations & OPERATION_GET) != 0 && spec.operations != OPERATION_GET)
src << " uint postGet[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
if (spec.operations == OPERATION_GET)
src << " uint get[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
src << "} sb_in;\n\n";
for (int counterNdx = 0; counterNdx < spec.atomicCounterCount; counterNdx++)
{
bool layoutStarted = false;
if (spec.offsetType == OFFSETTYPE_RESET_DEFAULT && counterNdx == spec.atomicCounterCount/2)
src << "layout(binding=0, offset=0) uniform atomic_uint;\n";
switch (spec.bindingType)
{
case BINDINGTYPE_BASIC:
layoutStarted = true;
src << "layout(binding=0";
break;
case BINDINGTYPE_INVALID:
layoutStarted = true;
src << "layout(binding=10000";
break;
case BINDINGTYPE_INVALID_DEFAULT:
// Nothing
break;
default:
DE_ASSERT(false);
}
switch (spec.offsetType)
{
case OFFSETTYPE_NONE:
if (layoutStarted)
src << ") ";
src << "uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_BASIC:
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=" << (counterNdx * 4) << ") uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_INVALID_DEFAULT:
if (layoutStarted)
src << ") ";
src << "uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_INVALID:
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=" << (1 + counterNdx * 2) << ") uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_INVALID_OVERLAPPING:
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=0) uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_REVERSE:
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=" << (spec.atomicCounterCount - counterNdx - 1) * 4 << ") uniform atomic_uint counter" << (spec.atomicCounterCount - counterNdx - 1) << ";\n";
break;
case OFFSETTYPE_FIRST_AUTO:
DE_ASSERT(spec.atomicCounterCount > 2);
if (counterNdx + 1 == spec.atomicCounterCount)
{
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=0) uniform atomic_uint counter0;\n";
}
else if (counterNdx == 0)
{
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=4) uniform atomic_uint counter1;\n";
}
else
{
if (layoutStarted)
src << ") ";
src << "uniform atomic_uint counter" << (counterNdx + 1) << ";\n";
}
break;
case OFFSETTYPE_DEFAULT_AUTO:
if (counterNdx + 1 == spec.atomicCounterCount)
{
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=0) uniform atomic_uint counter0;\n";
}
else
{
if (layoutStarted)
src << ") ";
src << "uniform atomic_uint counter" << (counterNdx + 1) << ";\n";
}
break;
case OFFSETTYPE_RESET_DEFAULT:
if (layoutStarted)
src << ") ";
if (counterNdx < spec.atomicCounterCount/2)
src << "uniform atomic_uint counter" << (counterNdx + spec.atomicCounterCount/2) << ";\n";
else
src << "uniform atomic_uint counter" << (counterNdx - spec.atomicCounterCount/2) << ";\n";
break;
default:
DE_ASSERT(false);
}
}
src
<< "\n"
<< "void main (void)\n"
<< "{\n";
if (spec.callCount > 1)
src << "\tfor (uint i = 0u; i < " << spec.callCount << "u; i++)\n";
src
<< "\t{\n"
<< "\t\tuint id = (gl_GlobalInvocationID.x";
if (spec.callCount > 1)
src << " * "<< spec.callCount << "u";
if (spec.callCount > 1)
src << " + i)";
else
src << ")";
if (spec.atomicCounterCount > 1)
src << " * " << spec.atomicCounterCount << "u";
src << ";\n";
for (int counterNdx = 0; counterNdx < spec.atomicCounterCount; counterNdx++)
{
if ((spec.operations & OPERATION_GET) != 0 && spec.operations != OPERATION_GET)
src << "\t\tsb_in.preGet[id + " << counterNdx << "u] = atomicCounter(counter" << counterNdx << ");\n";
if (spec.useBranches && ((spec.operations & (OPERATION_INC|OPERATION_DEC)) == (OPERATION_INC|OPERATION_DEC)))
{
src
<< "\t\tif (((gl_GlobalInvocationID.x" << (spec.callCount > 1 ? " + i" : "") << ") % 2u) == 0u)\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.increment[id + " << counterNdx << "u] = atomicCounterIncrement(counter" << counterNdx << ");\n"
<< "\t\t\tsb_in.decrement[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n"
<< "\t\telse\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.decrement[id + " << counterNdx << "u] = atomicCounterDecrement(counter" << counterNdx << ") + 1u;\n"
<< "\t\t\tsb_in.increment[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n";
}
else
{
if ((spec.operations & OPERATION_INC) != 0)
{
if (spec.useBranches)
{
src
<< "\t\tif (((gl_GlobalInvocationID.x" << (spec.callCount > 1 ? " + i" : "") << ") % 2u) == 0u)\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.increment[id + " << counterNdx << "u] = atomicCounterIncrement(counter" << counterNdx << ");\n"
<< "\t\t}\n"
<< "\t\telse\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.increment[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n";
}
else
src << "\t\tsb_in.increment[id + " << counterNdx << "u] = atomicCounterIncrement(counter" << counterNdx << ");\n";
}
if ((spec.operations & OPERATION_DEC) != 0)
{
if (spec.useBranches)
{
src
<< "\t\tif (((gl_GlobalInvocationID.x" << (spec.callCount > 1 ? " + i" : "") << ") % 2u) == 0u)\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.decrement[id + " << counterNdx << "u] = atomicCounterDecrement(counter" << counterNdx << ") + 1u;\n"
<< "\t\t}\n"
<< "\t\telse\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.decrement[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n";
}
else
src << "\t\tsb_in.decrement[id + " << counterNdx << "u] = atomicCounterDecrement(counter" << counterNdx << ") + 1u;\n";
}
}
if ((spec.operations & OPERATION_GET) != 0 && spec.operations != OPERATION_GET)
src << "\t\tsb_in.postGet[id + " << counterNdx << "u] = atomicCounter(counter" << counterNdx << ");\n";
if ((spec.operations == OPERATION_GET) != 0)
{
if (spec.useBranches)
{
src
<< "\t\tif (((gl_GlobalInvocationID.x" << (spec.callCount > 1 ? " + i" : "") << ") % 2u) == 0u)\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.get[id + " << counterNdx << "u] = atomicCounter(counter" << counterNdx << ");\n"
<< "\t\t}\n"
<< "\t\telse\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.get[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n";
}
else
src << "\t\tsb_in.get[id + " << counterNdx << "u] = atomicCounter(counter" << counterNdx << ");\n";
}
}
src
<< "\t}\n"
<< "}\n";
return src.str();
}
bool AtomicCounterTest::checkAndLogCounterValues (TestLog& log, const vector<deUint32>& counters) const
{
tcu::ScopedLogSection counterSection (log, "Counter info", "Show initial value, current value and expected value of each counter.");
bool isOk = true;
// Check that atomic counters have sensible results
for (int counterNdx = 0; counterNdx < (int)counters.size(); counterNdx++)
{
const deUint32 value = counters[counterNdx];
const deUint32 initialValue = getInitialValue();
deUint32 expectedValue = (deUint32)-1;
if ((m_spec.operations & OPERATION_INC) != 0 && (m_spec.operations & OPERATION_DEC) == 0)
expectedValue = initialValue + (m_spec.useBranches ? m_spec.threadCount*m_spec.callCount - m_spec.threadCount*m_spec.callCount/2 : m_spec.threadCount*m_spec.callCount);
if ((m_spec.operations & OPERATION_INC) == 0 && (m_spec.operations & OPERATION_DEC) != 0)
expectedValue = initialValue - (m_spec.useBranches ? m_spec.threadCount*m_spec.callCount - m_spec.threadCount*m_spec.callCount/2 : m_spec.threadCount*m_spec.callCount);
if ((m_spec.operations & OPERATION_INC) != 0 && (m_spec.operations & OPERATION_DEC) != 0)
expectedValue = initialValue + (m_spec.useBranches ? m_spec.threadCount*m_spec.callCount - m_spec.threadCount*m_spec.callCount/2 : 0) - (m_spec.useBranches ? m_spec.threadCount*m_spec.callCount/2 : 0);
if ((m_spec.operations & OPERATION_INC) == 0 && (m_spec.operations & OPERATION_DEC) == 0)
expectedValue = initialValue;
log << TestLog::Message << "atomic_uint counter" << counterNdx << " initial value: " << initialValue << ", value: " << value << ", expected: " << expectedValue << (value == expectedValue ? "" : ", failed!") << TestLog::EndMessage;
if (value != expectedValue)
isOk = false;
}
return isOk;
}
void AtomicCounterTest::splitBuffer (const vector<deUint32>& buffer, vector<deUint32>& increments, vector<deUint32>& decrements, vector<deUint32>& preGets, vector<deUint32>& postGets, vector<deUint32>& gets) const
{
const int bufferValueCount = m_spec.callCount * m_spec.threadCount * m_spec.atomicCounterCount;
int firstPreGet = -1;
int firstPostGet = -1;
int firstGet = -1;
int firstInc = -1;
int firstDec = -1;
increments.clear();
decrements.clear();
preGets.clear();
postGets.clear();
gets.clear();
if (m_spec.operations == OPERATION_GET)
firstGet = 0;
else if (m_spec.operations == OPERATION_INC)
firstInc = 0;
else if (m_spec.operations == OPERATION_DEC)
firstDec = 0;
else if (m_spec.operations == (OPERATION_GET|OPERATION_INC))
{
firstPreGet = 0;
firstInc = bufferValueCount;
firstPostGet = bufferValueCount * 2;
}
else if (m_spec.operations == (OPERATION_GET|OPERATION_DEC))
{
firstPreGet = 0;
firstDec = bufferValueCount;
firstPostGet = bufferValueCount * 2;
}
else if (m_spec.operations == (OPERATION_GET|OPERATION_DEC|OPERATION_INC))
{
firstPreGet = 0;
firstInc = bufferValueCount;
firstDec = bufferValueCount * 2;
firstPostGet = bufferValueCount * 3;
}
else if (m_spec.operations == (OPERATION_DEC|OPERATION_INC))
{
firstInc = 0;
firstDec = bufferValueCount;
}
else
DE_ASSERT(false);
for (int threadNdx = 0; threadNdx < m_spec.threadCount; threadNdx++)
{
for (int callNdx = 0; callNdx < m_spec.callCount; callNdx++)
{
for (int counterNdx = 0; counterNdx < m_spec.atomicCounterCount; counterNdx++)
{
const int id = ((threadNdx * m_spec.callCount) + callNdx) * m_spec.atomicCounterCount + counterNdx;
if (firstInc != -1)
increments.push_back(buffer[firstInc + id]);
if (firstDec != -1)
decrements.push_back(buffer[firstDec + id]);
if (firstPreGet != -1)
preGets.push_back(buffer[firstPreGet + id]);
if (firstPostGet != -1)
postGets.push_back(buffer[firstPostGet + id]);
if (firstGet != -1)
gets.push_back(buffer[firstGet + id]);
}
}
}
}
void AtomicCounterTest::getCountersValues (vector<deUint32>& counterValues, const vector<deUint32>& values, int ndx, int counterCount)
{
counterValues.resize(values.size()/counterCount, 0);
DE_ASSERT(values.size() % counterCount == 0);
for (int valueNdx = 0; valueNdx < (int)counterValues.size(); valueNdx++)
counterValues[valueNdx] = values[valueNdx * counterCount + ndx];
}
bool AtomicCounterTest::checkRange (TestLog& log, const vector<deUint32>& values, const vector<deUint32>& min, const vector<deUint32>& max)
{
int failedCount = 0;
DE_ASSERT(values.size() == min.size());
DE_ASSERT(values.size() == max.size());
for (int valueNdx = 0; valueNdx < (int)values.size(); valueNdx++)
{
if (values[valueNdx] != (deUint32)-1)
{
if (!deInRange32(values[valueNdx], min[valueNdx], max[valueNdx]))
{
if (failedCount < 20)
log << TestLog::Message << "Value " << values[valueNdx] << " not in range [" << min[valueNdx] << ", " << max[valueNdx] << "]." << TestLog::EndMessage;
failedCount++;
}
}
}
if (failedCount > 20)
log << TestLog::Message << "Number of values not in range: " << failedCount << ", displaying first 20 values." << TestLog::EndMessage;
return failedCount == 0;
}
bool AtomicCounterTest::checkUniquenessAndLinearity (TestLog& log, const vector<deUint32>& values)
{
vector<deUint32> counts;
int failedCount = 0;
deUint32 minValue = (deUint32)-1;
deUint32 maxValue = 0;
DE_ASSERT(!values.empty());
for (int valueNdx = 0; valueNdx < (int)values.size(); valueNdx++)
{
if (values[valueNdx] != (deUint32)-1)
{
minValue = std::min(minValue, values[valueNdx]);
maxValue = std::max(maxValue, values[valueNdx]);
}
}
counts.resize(maxValue - minValue + 1, 0);
for (int valueNdx = 0; valueNdx < (int)values.size(); valueNdx++)
{
if (values[valueNdx] != (deUint32)-1)
counts[values[valueNdx] - minValue]++;
}
for (int countNdx = 0; countNdx < (int)counts.size(); countNdx++)
{
if (counts[countNdx] != 1)
{
if (failedCount < 20)
log << TestLog::Message << "Value " << (minValue + countNdx) << " is not unique. Returned " << counts[countNdx] << " times." << TestLog::EndMessage;
failedCount++;
}
}
if (failedCount > 20)
log << TestLog::Message << "Number of values not unique: " << failedCount << ", displaying first 20 values." << TestLog::EndMessage;
return failedCount == 0;
}
bool AtomicCounterTest::checkPath (const vector<deUint32>& increments, const vector<deUint32>& decrements, int initialValue, const TestSpec& spec)
{
const deUint32 lastValue = initialValue + (spec.useBranches ? spec.threadCount*spec.callCount - spec.threadCount*spec.callCount/2 : 0) - (spec.useBranches ? spec.threadCount*spec.callCount/2 : 0);
bool isOk = true;
vector<deUint32> incrementCounts;
vector<deUint32> decrementCounts;
deUint32 minValue = 0xFFFFFFFFu;
deUint32 maxValue = 0;
for (int valueNdx = 0; valueNdx < (int)increments.size(); valueNdx++)
{
if (increments[valueNdx] != (deUint32)-1)
{
minValue = std::min(minValue, increments[valueNdx]);
maxValue = std::max(maxValue, increments[valueNdx]);
}
}
for (int valueNdx = 0; valueNdx < (int)decrements.size(); valueNdx++)
{
if (decrements[valueNdx] != (deUint32)-1)
{
minValue = std::min(minValue, decrements[valueNdx]);
maxValue = std::max(maxValue, decrements[valueNdx]);
}
}
minValue = std::min(minValue, (deUint32)initialValue);
maxValue = std::max(maxValue, (deUint32)initialValue);
incrementCounts.resize(maxValue - minValue + 1, 0);
decrementCounts.resize(maxValue - minValue + 1, 0);
for (int valueNdx = 0; valueNdx < (int)increments.size(); valueNdx++)
{
if (increments[valueNdx] != (deUint32)-1)
incrementCounts[increments[valueNdx] - minValue]++;
}
for (int valueNdx = 0; valueNdx < (int)decrements.size(); valueNdx++)
{
if (decrements[valueNdx] != (deUint32)-1)
decrementCounts[decrements[valueNdx] - minValue]++;
}
int pos = initialValue - minValue;
while (incrementCounts[pos] + decrementCounts[pos] != 0)
{
if (incrementCounts[pos] > 0 && pos >= (int)(lastValue - minValue))
{
// If can increment and incrementation would move us away from result value, increment
incrementCounts[pos]--;
pos++;
}
else if (decrementCounts[pos] > 0)
{
// If can, decrement
decrementCounts[pos]--;
pos--;
}
else if (incrementCounts[pos] > 0)
{
// If increment moves closer to result value and can't decrement, increment
incrementCounts[pos]--;
pos++;
}
else
DE_ASSERT(false);
if (pos < 0 || pos >= (int)incrementCounts.size())
break;
}
if (minValue + pos != lastValue)
isOk = false;
for (int valueNdx = 0; valueNdx < (int)incrementCounts.size(); valueNdx++)
{
if (incrementCounts[valueNdx] != 0)
isOk = false;
}
for (int valueNdx = 0; valueNdx < (int)decrementCounts.size(); valueNdx++)
{
if (decrementCounts[valueNdx] != 0)
isOk = false;
}
return isOk;
}
bool AtomicCounterTest::checkAndLogCallValues (TestLog& log, const vector<deUint32>& increments, const vector<deUint32>& decrements, const vector<deUint32>& preGets, const vector<deUint32>& postGets, const vector<deUint32>& gets) const
{
bool isOk = true;
for (int counterNdx = 0; counterNdx < m_spec.atomicCounterCount; counterNdx++)
{
vector<deUint32> counterIncrements;
vector<deUint32> counterDecrements;
vector<deUint32> counterPreGets;
vector<deUint32> counterPostGets;
vector<deUint32> counterGets;
getCountersValues(counterIncrements, increments, counterNdx, m_spec.atomicCounterCount);
getCountersValues(counterDecrements, decrements, counterNdx, m_spec.atomicCounterCount);
getCountersValues(counterPreGets, preGets, counterNdx, m_spec.atomicCounterCount);
getCountersValues(counterPostGets, postGets, counterNdx, m_spec.atomicCounterCount);
getCountersValues(counterGets, gets, counterNdx, m_spec.atomicCounterCount);
if (m_spec.operations == OPERATION_GET)
{
tcu::ScopedLogSection valueCheck(log, ("counter" + de::toString(counterNdx) + " value check").c_str(), ("Check that counter" + de::toString(counterNdx) + " values haven't changed.").c_str());
int changedValues = 0;
for (int valueNdx = 0; valueNdx < (int)gets.size(); valueNdx++)
{
if ((!m_spec.useBranches || gets[valueNdx] != (deUint32)-1) && gets[valueNdx] != getInitialValue())
{
if (changedValues < 20)
log << TestLog::Message << "atomicCounter(counter" << counterNdx << ") returned " << gets[valueNdx] << " expected " << getInitialValue() << TestLog::EndMessage;
isOk = false;
changedValues++;
}
}
if (changedValues == 0)
log << TestLog::Message << "All values returned by atomicCounter(counter" << counterNdx << ") match initial value " << getInitialValue() << "." << TestLog::EndMessage;
else if (changedValues > 20)
log << TestLog::Message << "Total number of invalid values returned by atomicCounter(counter" << counterNdx << ") " << changedValues << " displaying first 20 values." << TestLog::EndMessage;
}
else if ((m_spec.operations & (OPERATION_INC|OPERATION_DEC)) == (OPERATION_INC|OPERATION_DEC))
{
tcu::ScopedLogSection valueCheck(log, ("counter" + de::toString(counterNdx) + " path check").c_str(), ("Check that there is order in which counter" + de::toString(counterNdx) + " increments and decrements could have happened.").c_str());
if (!checkPath(counterIncrements, counterDecrements, getInitialValue(), m_spec))
{
isOk = false;
log << TestLog::Message << "No possible order of calls to atomicCounterIncrement(counter" << counterNdx << ") and atomicCounterDecrement(counter" << counterNdx << ") found." << TestLog::EndMessage;
}
else
log << TestLog::Message << "Found possible order of calls to atomicCounterIncrement(counter" << counterNdx << ") and atomicCounterDecrement(counter" << counterNdx << ")." << TestLog::EndMessage;
}
else if ((m_spec.operations & OPERATION_INC) != 0)
{
{
tcu::ScopedLogSection uniquenesCheck(log, ("counter" + de::toString(counterNdx) + " check uniqueness and linearity").c_str(), ("Check that counter" + de::toString(counterNdx) + " returned only unique and linear values.").c_str());
if (!checkUniquenessAndLinearity(log, counterIncrements))
{
isOk = false;
log << TestLog::Message << "atomicCounterIncrement(counter" << counterNdx << ") returned non unique values." << TestLog::EndMessage;
}
else
log << TestLog::Message << "atomicCounterIncrement(counter" << counterNdx << ") returned only unique values." << TestLog::EndMessage;
}
if (isOk && ((m_spec.operations & OPERATION_GET) != 0))
{
tcu::ScopedLogSection uniquenesCheck(log, ("counter" + de::toString(counterNdx) + " check range").c_str(), ("Check that counter" + de::toString(counterNdx) + " returned only values values between previous and next atomicCounter(counter" + de::toString(counterNdx) + ").").c_str());
if (!checkRange(log, counterIncrements, counterPreGets, counterPostGets))
{
isOk = false;
log << TestLog::Message << "atomicCounterIncrement(counter" << counterNdx << ") returned value that is not between previous and next call to atomicCounter(counter" << counterNdx << ")." << TestLog::EndMessage;
}
else
log << TestLog::Message << "atomicCounterIncrement(counter" << counterNdx << ") returned only values between previous and next call to atomicCounter(counter" << counterNdx << ")." << TestLog::EndMessage;
}
}
else if ((m_spec.operations & OPERATION_DEC) != 0)
{
{
tcu::ScopedLogSection uniquenesCheck(log, ("counter" + de::toString(counterNdx) + " check uniqueness and linearity").c_str(), ("Check that counter" + de::toString(counterNdx) + " returned only unique and linear values.").c_str());
if (!checkUniquenessAndLinearity(log, counterDecrements))
{
isOk = false;
log << TestLog::Message << "atomicCounterDecrement(counter" << counterNdx << ") returned non unique values." << TestLog::EndMessage;
}
else
log << TestLog::Message << "atomicCounterDecrement(counter" << counterNdx << ") returned only unique values." << TestLog::EndMessage;
}
if (isOk && ((m_spec.operations & OPERATION_GET) != 0))
{
tcu::ScopedLogSection uniquenesCheck(log, ("counter" + de::toString(counterNdx) + " check range").c_str(), ("Check that counter" + de::toString(counterNdx) + " returned only values values between previous and next atomicCounter(counter" + de::toString(counterNdx) + ".").c_str());
if (!checkRange(log, counterDecrements, counterPostGets, counterPreGets))
{
isOk = false;
log << TestLog::Message << "atomicCounterDecrement(counter" << counterNdx << ") returned value that is not between previous and next call to atomicCounter(counter" << counterNdx << ")." << TestLog::EndMessage;
}
else
log << TestLog::Message << "atomicCounterDecrement(counter" << counterNdx << ") returned only values between previous and next call to atomicCounter(counter" << counterNdx << ")." << TestLog::EndMessage;
}
}
}
return isOk;
}
TestCase::IterateResult AtomicCounterTest::iterate (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
TestLog& log = m_testCtx.getLog();
const glu::Buffer counterBuffer (m_context.getRenderContext());
const glu::Buffer outputBuffer (m_context.getRenderContext());
const glu::ShaderProgram program (m_context.getRenderContext(), glu::ProgramSources() << glu::ShaderSource(glu::SHADERTYPE_COMPUTE, generateShaderSource(m_spec)));
const deInt32 counterBufferSize = m_spec.atomicCounterCount * 4;
const deInt32 ssoSize = m_spec.atomicCounterCount * m_spec.callCount * m_spec.threadCount * 4 * getOperationCount();
log << program;
if (m_spec.offsetType == OFFSETTYPE_INVALID || m_spec.offsetType == OFFSETTYPE_INVALID_DEFAULT || m_spec.bindingType == BINDINGTYPE_INVALID || m_spec.bindingType == BINDINGTYPE_INVALID_DEFAULT || m_spec.offsetType == OFFSETTYPE_INVALID_OVERLAPPING)
{
if (program.isOk())
{
log << TestLog::Message << "Expected program to fail, but compilation passed." << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Compile succeeded");
return STOP;
}
else
{
log << TestLog::Message << "Compilation failed as expected." << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Compile failed");
return STOP;
}
}
else if (!program.isOk())
{
log << TestLog::Message << "Compile failed." << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Compile failed");
return STOP;
}
gl.useProgram(program.getProgram());
GLU_EXPECT_NO_ERROR(gl.getError(), "glUseProgram()");
// Create output buffer
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, *outputBuffer);
gl.bufferData(GL_SHADER_STORAGE_BUFFER, ssoSize, NULL, GL_STATIC_DRAW);
GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to create output buffer");
// Create atomic counter buffer
{
vector<deUint32> data(m_spec.atomicCounterCount, getInitialValue());
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, *counterBuffer);
gl.bufferData(GL_SHADER_STORAGE_BUFFER, counterBufferSize, &(data[0]), GL_STATIC_DRAW);
GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to create buffer for atomic counters");
}
// Bind output buffer
gl.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, *outputBuffer);
GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to setup output buffer");
// Bind atomic counter buffer
gl.bindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, *counterBuffer);
GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to setup atomic counter buffer");
// Dispath compute
gl.dispatchCompute(m_spec.threadCount, 1, 1);
GLU_EXPECT_NO_ERROR(gl.getError(), "glDispatchCompute()");
gl.finish();
GLU_EXPECT_NO_ERROR(gl.getError(), "glFinish()");
vector<deUint32> output(ssoSize/4, 0);
vector<deUint32> counters(m_spec.atomicCounterCount, 0);
// Read back output buffer
{
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, *outputBuffer);
GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer()");
void* ptr = gl.mapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, (GLsizeiptr)(output.size() * sizeof(deUint32)), GL_MAP_READ_BIT);
GLU_EXPECT_NO_ERROR(gl.getError(), "glMapBufferRange()");
deMemcpy(&(output[0]), ptr, (int)output.size() * sizeof(deUint32));
if (!gl.unmapBuffer(GL_SHADER_STORAGE_BUFFER))
{
GLU_EXPECT_NO_ERROR(gl.getError(), "glUnmapBuffer()");
TCU_CHECK_MSG(false, "Mapped buffer corrupted");
}
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer()");
}
// Read back counter buffer
{
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, *counterBuffer);
GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer()");
void* ptr = gl.mapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, (GLsizeiptr)(counters.size() * sizeof(deUint32)), GL_MAP_READ_BIT);
GLU_EXPECT_NO_ERROR(gl.getError(), "glMapBufferRange()");
deMemcpy(&(counters[0]), ptr, (int)counters.size() * sizeof(deUint32));
if (!gl.unmapBuffer(GL_SHADER_STORAGE_BUFFER))
{
GLU_EXPECT_NO_ERROR(gl.getError(), "glUnmapBuffer()");
TCU_CHECK_MSG(false, "Mapped buffer corrupted");
}
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer()");
}
bool isOk = true;
if (!checkAndLogCounterValues(log, counters))
isOk = false;
{
vector<deUint32> increments;
vector<deUint32> decrements;
vector<deUint32> preGets;
vector<deUint32> postGets;
vector<deUint32> gets;
splitBuffer(output, increments, decrements, preGets, postGets, gets);
if (!checkAndLogCallValues(log, increments, decrements, preGets, postGets, gets))
isOk = false;
}
if (isOk)
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
else
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail");
return STOP;
}
string specToTestName (const AtomicCounterTest::TestSpec& spec)
{
std::ostringstream stream;
stream << spec.atomicCounterCount << (spec.atomicCounterCount == 1 ? "_counter" : "_counters");
stream << "_" << spec.callCount << (spec.callCount == 1 ? "_call" : "_calls");
stream << "_" << spec.threadCount << (spec.threadCount == 1 ? "_thread" : "_threads");
return stream.str();
}
string specToTestDescription (const AtomicCounterTest::TestSpec& spec)
{
std::ostringstream stream;
bool firstOperation = 0;
stream
<< "Test ";
if ((spec.operations & AtomicCounterTest::OPERATION_GET) != 0)
{
stream << "atomicCounter()";
firstOperation = false;
}
if ((spec.operations & AtomicCounterTest::OPERATION_INC) != 0)
{
if (!firstOperation)
stream << ", ";
stream << " atomicCounterIncrement()";
firstOperation = false;
}
if ((spec.operations & AtomicCounterTest::OPERATION_DEC) != 0)
{
if (!firstOperation)
stream << ", ";
stream << " atomicCounterDecrement()";
firstOperation = false;
}
stream << " calls with ";
if (spec.useBranches)
stream << " branches, ";
stream << spec.atomicCounterCount << " atomic counters, " << spec.callCount << " calls and " << spec.threadCount << " threads.";
return stream.str();
}
string operationToName (const AtomicCounterTest::Operation& operations, bool useBranch)
{
std::ostringstream stream;
bool first = true;
if ((operations & AtomicCounterTest::OPERATION_GET) != 0)
{
stream << "get";
first = false;
}
if ((operations & AtomicCounterTest::OPERATION_INC) != 0)
{
if (!first)
stream << "_";
stream << "inc";
first = false;
}
if ((operations & AtomicCounterTest::OPERATION_DEC) != 0)
{
if (!first)
stream << "_";
stream << "dec";
first = false;
}
if (useBranch)
stream << "_branch";
return stream.str();
}
string operationToDescription (const AtomicCounterTest::Operation& operations, bool useBranch)
{
std::ostringstream stream;
bool firstOperation = 0;
stream
<< "Test ";
if ((operations & AtomicCounterTest::OPERATION_GET) != 0)
{
stream << "atomicCounter()";
firstOperation = false;
}
if ((operations & AtomicCounterTest::OPERATION_INC) != 0)
{
if (!firstOperation)
stream << ", ";
stream << " atomicCounterIncrement()";
firstOperation = false;
}
if ((operations & AtomicCounterTest::OPERATION_DEC) != 0)
{
if (!firstOperation)
stream << ", ";
stream << " atomicCounterDecrement()";
firstOperation = false;
}
if (useBranch)
stream << " calls with branches.";
else
stream << ".";
return stream.str();
}
string layoutTypesToName (const AtomicCounterTest::BindingType& bindingType, const AtomicCounterTest::OffsetType& offsetType)
{
std::ostringstream stream;
switch (bindingType)
{
case AtomicCounterTest::BINDINGTYPE_BASIC:
// Nothing
break;
case AtomicCounterTest::BINDINGTYPE_INVALID:
stream << "invalid_binding";
break;
default:
DE_ASSERT(false);
}
if (bindingType != AtomicCounterTest::BINDINGTYPE_BASIC && offsetType != AtomicCounterTest::OFFSETTYPE_NONE)
stream << "_";
switch (offsetType)
{
case AtomicCounterTest::OFFSETTYPE_BASIC:
stream << "basic_offset";
break;
case AtomicCounterTest::OFFSETTYPE_REVERSE:
stream << "reverse_offset";
break;
case AtomicCounterTest::OFFSETTYPE_INVALID:
stream << "invalid_offset";
break;
case AtomicCounterTest::OFFSETTYPE_FIRST_AUTO:
stream << "first_offset_set";
break;
case AtomicCounterTest::OFFSETTYPE_DEFAULT_AUTO:
stream << "default_offset_set";
break;
case AtomicCounterTest::OFFSETTYPE_RESET_DEFAULT:
stream << "reset_default_offset";
break;
case AtomicCounterTest::OFFSETTYPE_NONE:
// Do nothing
break;
default:
DE_ASSERT(false);
}
return stream.str();
}
string layoutTypesToDesc (const AtomicCounterTest::BindingType& bindingType, const AtomicCounterTest::OffsetType& offsetType)
{
std::ostringstream stream;
switch (bindingType)
{
case AtomicCounterTest::BINDINGTYPE_BASIC:
stream << "Test using atomic counters with explicit layout bindings and";
break;
case AtomicCounterTest::BINDINGTYPE_INVALID:
stream << "Test using atomic counters with invalid explicit layout bindings and";
break;
case AtomicCounterTest::BINDINGTYPE_INVALID_DEFAULT:
stream << "Test using atomic counters with invalid default layout binding and";
break;
default:
DE_ASSERT(false);
}
switch (offsetType)
{
case AtomicCounterTest::OFFSETTYPE_NONE:
stream << " no explicit offsets.";
break;
case AtomicCounterTest::OFFSETTYPE_BASIC:
stream << "explicit continuos offsets.";
break;
case AtomicCounterTest::OFFSETTYPE_REVERSE:
stream << "reversed explicit offsets.";
break;
case AtomicCounterTest::OFFSETTYPE_INVALID:
stream << "invalid explicit offsets.";
break;
case AtomicCounterTest::OFFSETTYPE_FIRST_AUTO:
stream << "only first counter with explicit offset.";
break;
case AtomicCounterTest::OFFSETTYPE_DEFAULT_AUTO:
stream << "default offset.";
break;
case AtomicCounterTest::OFFSETTYPE_RESET_DEFAULT:
stream << "default offset specified twice.";
break;
default:
DE_ASSERT(false);
}
return stream.str();
}
} // Anonymous
AtomicCounterTests::AtomicCounterTests (Context& context)
: TestCaseGroup(context, "atomic_counter", "Atomic counter tests")
{
// Runtime use tests
{
const int counterCounts[] =
{
1, 4, 8
};
const int callCounts[] =
{
1, 5, 100
};
const int threadCounts[] =
{
1, 10, 5000
};
const AtomicCounterTest::Operation operations[] =
{
AtomicCounterTest::OPERATION_GET,
AtomicCounterTest::OPERATION_INC,
AtomicCounterTest::OPERATION_DEC,
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_GET),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_DEC|AtomicCounterTest::OPERATION_GET),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_DEC),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_DEC|AtomicCounterTest::OPERATION_GET)
};
for (int operationNdx = 0; operationNdx < DE_LENGTH_OF_ARRAY(operations); operationNdx++)
{
const AtomicCounterTest::Operation operation = operations[operationNdx];
for (int branch = 0; branch < 2; branch++)
{
const bool useBranch = (branch == 1);
TestCaseGroup* operationGroup = new TestCaseGroup(m_context, operationToName(operation, useBranch).c_str(), operationToDescription(operation, useBranch).c_str());
for (int counterCountNdx = 0; counterCountNdx < DE_LENGTH_OF_ARRAY(counterCounts); counterCountNdx++)
{
const int counterCount = counterCounts[counterCountNdx];
for (int callCountNdx = 0; callCountNdx < DE_LENGTH_OF_ARRAY(callCounts); callCountNdx++)
{
const int callCount = callCounts[callCountNdx];
for (int threadCountNdx = 0; threadCountNdx < DE_LENGTH_OF_ARRAY(threadCounts); threadCountNdx++)
{
const int threadCount = threadCounts[threadCountNdx];
if (threadCount * callCount * counterCount > 10000)
continue;
if (useBranch && threadCount * callCount == 1)
continue;
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = counterCount;
spec.operations = operation;
spec.callCount = callCount;
spec.useBranches = useBranch;
spec.threadCount = threadCount;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_NONE;
operationGroup->addChild(new AtomicCounterTest(m_context, specToTestName(spec).c_str(), specToTestDescription(spec).c_str(), spec));
}
}
}
addChild(operationGroup);
}
}
}
{
TestCaseGroup* layoutGroup = new TestCaseGroup(m_context, "layout", "Layout qualifier tests.");
const int counterCounts[] = { 1, 8 };
const int callCounts[] = { 1, 5 };
const int threadCounts[] = { 1, 1000 };
const AtomicCounterTest::Operation operations[] =
{
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_GET),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_DEC|AtomicCounterTest::OPERATION_GET),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_DEC)
};
const AtomicCounterTest::OffsetType offsetTypes[] =
{
AtomicCounterTest::OFFSETTYPE_REVERSE,
AtomicCounterTest::OFFSETTYPE_FIRST_AUTO,
AtomicCounterTest::OFFSETTYPE_DEFAULT_AUTO,
AtomicCounterTest::OFFSETTYPE_RESET_DEFAULT
};
for (int offsetTypeNdx = 0; offsetTypeNdx < DE_LENGTH_OF_ARRAY(offsetTypes); offsetTypeNdx++)
{
const AtomicCounterTest::OffsetType offsetType = offsetTypes[offsetTypeNdx];
TestCaseGroup* layoutQualifierGroup = new TestCaseGroup(m_context, layoutTypesToName(AtomicCounterTest::BINDINGTYPE_BASIC, offsetType).c_str(), layoutTypesToDesc(AtomicCounterTest::BINDINGTYPE_BASIC, offsetType).c_str());
for (int operationNdx = 0; operationNdx < DE_LENGTH_OF_ARRAY(operations); operationNdx++)
{
const AtomicCounterTest::Operation operation = operations[operationNdx];
TestCaseGroup* operationGroup = new TestCaseGroup(m_context, operationToName(operation, false).c_str(), operationToDescription(operation, false).c_str());
for (int counterCountNdx = 0; counterCountNdx < DE_LENGTH_OF_ARRAY(counterCounts); counterCountNdx++)
{
const int counterCount = counterCounts[counterCountNdx];
if (offsetType == AtomicCounterTest::OFFSETTYPE_FIRST_AUTO && counterCount < 3)
continue;
if (offsetType == AtomicCounterTest::OFFSETTYPE_DEFAULT_AUTO && counterCount < 2)
continue;
if (offsetType == AtomicCounterTest::OFFSETTYPE_RESET_DEFAULT && counterCount < 2)
continue;
if (offsetType == AtomicCounterTest::OFFSETTYPE_REVERSE && counterCount < 2)
continue;
for (int callCountNdx = 0; callCountNdx < DE_LENGTH_OF_ARRAY(callCounts); callCountNdx++)
{
const int callCount = callCounts[callCountNdx];
for (int threadCountNdx = 0; threadCountNdx < DE_LENGTH_OF_ARRAY(threadCounts); threadCountNdx++)
{
const int threadCount = threadCounts[threadCountNdx];
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = counterCount;
spec.operations = operation;
spec.callCount = callCount;
spec.useBranches = false;
spec.threadCount = threadCount;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = offsetType;
operationGroup->addChild(new AtomicCounterTest(m_context, specToTestName(spec).c_str(), specToTestDescription(spec).c_str(), spec));
}
}
}
layoutQualifierGroup->addChild(operationGroup);
}
layoutGroup->addChild(layoutQualifierGroup);
}
{
TestCaseGroup* invalidGroup = new TestCaseGroup(m_context, "invalid", "Test invalid layouts");
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 1;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_INVALID;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_NONE;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_binding", "Test layout qualifiers with invalid binding.", spec));
}
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 1;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_INVALID_DEFAULT;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_NONE;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_default_binding", "Test layout qualifiers with invalid default binding.", spec));
}
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 1;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_INVALID;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_offset_align", "Test layout qualifiers with invalid alignment offset.", spec));
}
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 2;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_INVALID_OVERLAPPING;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_offset_overlap", "Test layout qualifiers with invalid overlapping offset.", spec));
}
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 1;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_INVALID_DEFAULT;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_default_offset", "Test layout qualifiers with invalid default offset.", spec));
}
layoutGroup->addChild(invalidGroup);
}
addChild(layoutGroup);
}
}
AtomicCounterTests::~AtomicCounterTests (void)
{
}
void AtomicCounterTests::init (void)
{
}
} // Functional
} // gles31
} // deqp
| 30.333549
| 285
| 0.677535
|
iabernikhin
|
fde3159a7e6c4e73aca3f9a5713c32d614c1a3cb
| 3,110
|
cxx
|
C++
|
Modules/Filtering/Contrast/test/otbHelperCLAHE.cxx
|
qingswu/otb
|
ed903b6a5e51a27a3d04786e4ad1637cf6b2772e
|
[
"Apache-2.0"
] | null | null | null |
Modules/Filtering/Contrast/test/otbHelperCLAHE.cxx
|
qingswu/otb
|
ed903b6a5e51a27a3d04786e4ad1637cf6b2772e
|
[
"Apache-2.0"
] | null | null | null |
Modules/Filtering/Contrast/test/otbHelperCLAHE.cxx
|
qingswu/otb
|
ed903b6a5e51a27a3d04786e4ad1637cf6b2772e
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "itkImageRegionIterator.h"
#include "otbCLHistogramEqualizationFilter.h"
int otbHelperCLAHE(int itkNotUsed(argc), char* argv[])
{
typedef int InputPixelType;
const unsigned int Dimension = 2;
typedef otb::Image<InputPixelType, Dimension> InputImageType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::ImageFileWriter<InputImageType> WriterType;
ReaderType::Pointer reader(ReaderType::New());
WriterType::Pointer writer(WriterType::New());
reader->SetFileName(argv[1]);
writer->SetFileName(argv[2]);
reader->UpdateOutputInformation();
typedef otb::VectorImage<int, 2> HistogramType;
typedef otb::VectorImage<double, 2> LutType;
typedef itk::StreamingImageFilter<LutType, LutType> StreamingImageFilter;
typedef otb::InPlacePassFilter<InputImageType> BufferFilter;
typedef otb::ComputeHistoFilter<InputImageType, HistogramType> HistoFilter;
typedef otb::ComputeGainLutFilter<HistogramType, LutType> GainLutFilter;
typedef otb::ApplyGainFilter<InputImageType, LutType, InputImageType> ApplyGainFilter;
HistoFilter::Pointer histoFilter(HistoFilter::New());
GainLutFilter::Pointer lutFilter(GainLutFilter::New());
ApplyGainFilter::Pointer applyFilter(ApplyGainFilter::New());
BufferFilter::Pointer buffer(BufferFilter::New());
StreamingImageFilter::Pointer streamFilter(StreamingImageFilter::New());
InputImageType::SizeType size;
size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
// histoEqualize->SetThreshold(100);
histoFilter->SetInput(reader->GetOutput());
buffer->SetInput(reader->GetOutput());
lutFilter->SetInput(histoFilter->GetHistoOutput());
streamFilter->SetInput(lutFilter->GetOutput());
applyFilter->SetInputLut(streamFilter->GetOutput());
applyFilter->SetInputImage(buffer->GetOutput());
histoFilter->SetMin(0);
histoFilter->SetMax(255);
lutFilter->SetMin(0);
lutFilter->SetMax(255);
applyFilter->SetMin(0);
applyFilter->SetMax(255);
histoFilter->SetThumbSize(size);
applyFilter->SetThumbSize(size);
lutFilter->SetNbPixel(size[0] * size[1]);
writer->SetInput(applyFilter->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
| 35.340909
| 88
| 0.73537
|
qingswu
|
fde4300895f3d7abf07ee1a5269aff895cf24a7b
| 129
|
cpp
|
C++
|
f9_os/src/xv6cpp/sem.cpp
|
ghsecuritylab/arm-cortex-v7-unix
|
cd499fa94d6ee6cd78a31387f3512d997335df52
|
[
"Apache-2.0"
] | null | null | null |
f9_os/src/xv6cpp/sem.cpp
|
ghsecuritylab/arm-cortex-v7-unix
|
cd499fa94d6ee6cd78a31387f3512d997335df52
|
[
"Apache-2.0"
] | null | null | null |
f9_os/src/xv6cpp/sem.cpp
|
ghsecuritylab/arm-cortex-v7-unix
|
cd499fa94d6ee6cd78a31387f3512d997335df52
|
[
"Apache-2.0"
] | 1
|
2020-03-08T01:08:38.000Z
|
2020-03-08T01:08:38.000Z
|
/*
* sem.cpp
*
* Created on: Apr 21, 2017
* Author: Paul
*/
#include "sem.h"
namespace xv6 {
} /* namespace xv6 */
| 9.923077
| 28
| 0.534884
|
ghsecuritylab
|
fde789f3bde884920d5184fb047ba1a61817cd56
| 13,463
|
cpp
|
C++
|
src/commonui/CNodeEdgePropertiesUI.cpp
|
wojtek48/qvge
|
3c39128384a3ab3456bc559bda2e957e5bc814af
|
[
"MIT"
] | null | null | null |
src/commonui/CNodeEdgePropertiesUI.cpp
|
wojtek48/qvge
|
3c39128384a3ab3456bc559bda2e957e5bc814af
|
[
"MIT"
] | null | null | null |
src/commonui/CNodeEdgePropertiesUI.cpp
|
wojtek48/qvge
|
3c39128384a3ab3456bc559bda2e957e5bc814af
|
[
"MIT"
] | null | null | null |
/*
This file is a part of
QVGE - Qt Visual Graph Editor
(c) 2016-2019 Ars L. Masiuk (ars.masiuk@gmail.com)
It can be used freely, maintaining the information above.
*/
#include <QInputDialog>
#include <QMessageBox>
#include "CAttributesEditorUI.h"
#include "CPropertyEditorUIBase.h"
#include "CNodeEdgePropertiesUI.h"
#include "ui_CNodeEdgePropertiesUI.h"
#include <qvge/CNodeEditorScene.h>
#include <qvge/CNode.h>
#include <qvge/CEdge.h>
#include <qvge/CDirectEdge.h>
#include <qvge/CAttribute.h>
#include <qvge/CEditorSceneDefines.h>
#include <Const.h>
#include <qvge/currentvalues.h>
CNodeEdgePropertiesUI::CNodeEdgePropertiesUI(QWidget *parent) :
QWidget(parent),
m_scene(NULL),
m_updateLock(false),
ui(new Ui::CNodeEdgePropertiesUI)
{
m_nodeFactory = new CNode;
m_edgeFactory = new CDirectEdge;
ui->setupUi(this);
//WPaw - dodawanie ikon nodów
ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/bankDanych.PNG"), cBankDanych, cBankDanych);
ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/harmonogram.PNG"), cHarmonogram, cHarmonogram);
ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/generatorZdarzen.PNG"), cGeneratorZdarzen, cGeneratorZdarzen);
ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/procedury.PNG"), cProcedury, cProcedury);
ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/zasobStatyczny.PNG"), cZasobStatyczny, cZasobStatyczny);
ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/zegar.PNG"), cZegar, cZegar);
ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompUniwersalny.PNG"), cKompUniwersalny, cKompUniwersalny);
ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompPrzetwarzania.PNG"), cKompPrzetwarzania, cKompPrzetwarzania);
ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompPrzeplywu.PNG"), cKompPrzeplywu, cKompPrzeplywu);
ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompWymuszPrzeplyw.PNG"), cKompWymuszPrzeplywu, cKompWymuszPrzeplywu);
ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/zrodloZasobu.PNG"), cZrodloZasobu, cZrodloZasobu);
ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/celZasobu.PNG"), cCelZasobu, cCelZasobu);
// ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Directed"), tr("Directed (one end)"), "directed");
// ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Mutual"), tr("Mutual (both ends)"), "mutual");
// ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Undirected"), tr("None (no ends)"), "undirected");
// ui->EdgeColor->setColorScheme(QSint::OpenOfficeColors());
//ui->EdgeStyle->setUsedRange(Qt::SolidLine, Qt::DashDotDotLine);
ui->Edge->addAction (QIcon(cIkonaKanalZdarzen), cKanalZdarzen, cKanalZdarzen);
ui->Edge->addAction (QIcon(cIkonaKanalZasobu), cKanalZasobu, cKanalZasobu);
ui->Edge->addAction (QIcon(cIkonaKanalDanych), cKanalDanych, cKanalDanych);
ui->Edge->addAction (QIcon(cIkonaKanalKomunikacyjny), cKanalKomunikacyjny, cKanalKomunikacyjny);
ui->Edge->addAction (QIcon(cIkonaProceduryWbudowane), cProceduryWbudowane, cProceduryWbudowane);
ui->Edge->addAction (QIcon(cIkonaDostepnoscZasobu), cDostepnoscZasobu, cDostepnoscZasobu);
// font size
QList<int> fontSizes = { 5,6,7,8,9,10,11,12,14,16,18,20,24,28,32,36,40,44,48,54,60,66,72,80,88,96 };
ui->LabelFontSize->setValueList(fontSizes);
// node size
QList<int> nodeSizes = { 5,10,15,20,30,40,50,75,100,150,200 };
ui->NodeSizeX->setValueList(nodeSizes);
// update status & tooltips etc.
ui->retranslateUi(this);
}
CNodeEdgePropertiesUI::~CNodeEdgePropertiesUI()
{
delete m_nodeFactory;
delete ui;
}
void CNodeEdgePropertiesUI::doReadSettings(QSettings& settings)
{
int pos = settings.value("nodes/splitterPosition", -1).toInt();
/*int*/ pos = settings.value("edges/splitterPosition", -1).toInt();
}
void CNodeEdgePropertiesUI::doWriteSettings(QSettings& settings)
{
}
void CNodeEdgePropertiesUI::setScene(CNodeEditorScene* scene)
{
if (m_scene)
onSceneDetached(m_scene);
m_scene = scene;
setEnabled(m_scene);
if (m_scene)
onSceneAttached(m_scene);
}
void CNodeEdgePropertiesUI::connectSignals(CEditorScene* scene)
{
connect(scene, SIGNAL(sceneChanged()), this, SLOT(onSceneChanged()));
connect(scene, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
}
void CNodeEdgePropertiesUI::updateFromScene(CEditorScene* scene)
{
// default attrs
auto nodeAttrs = scene->getClassAttributes("node", false);
ui->NodeFlowShape->selectAction(nodeAttrs["shape"].defaultValue);
QSize size = nodeAttrs["size"].defaultValue.toSize();
ui->NodeSizeX->setValue(size.width());
auto edgeAttrs = scene->getClassAttributes("edge", false);
// ui->EdgeColor->setColor(edgeAttrs["color"].defaultValue.value<QColor>());
// ui->EdgeWeight->setValue(edgeAttrs["weight"].defaultValue.toDouble());
// ui->EdgeStyle->setPenStyle(CUtils::textToPenStyle(edgeAttrs["style"].defaultValue.toString()));
//ui->EdgeDirection->selectAction(edgeAttrs["direction"].defaultValue);
QFont f(edgeAttrs["label.font"].defaultValue.value<QFont>());
ui->LabelFont->setCurrentFont(f);
ui->LabelFontSize->setValue(f.pointSize());
ui->LabelColor->setColor(edgeAttrs["label.color"].defaultValue.value<QColor>());
}
void CNodeEdgePropertiesUI::onSceneAttached(CEditorScene* scene)
{
// factories for new items
//scene->setActiveItemFactory(m_nodeFactory);
//scene->setActiveItemFactory(m_edgeFactory);
// default attrs
updateFromScene(scene);
// connect & go
connectSignals(scene);
onSceneChanged();
}
void CNodeEdgePropertiesUI::onSceneDetached(CEditorScene* scene)
{
scene->disconnect(this);
}
void CNodeEdgePropertiesUI::onSceneChanged()
{
// update active selections if any
onSelectionChanged();
}
void CNodeEdgePropertiesUI::onSelectionChanged()
{
if (m_updateLock || m_scene == NULL)
return;
m_updateLock = true;
QList<CEdge*> edges = m_scene->getSelectedEdges();
QList<CNode*> nodes = m_scene->getSelectedNodes();
// nodes
ui->NodesBox->setTitle(tr("Selected components (%1)").arg(nodes.count()));
if (nodes.count())
{
auto node = nodes.first();
ui->NodeFlowShape->selectAction(node->getAttribute("shape"));
QSize size = node->getAttribute("size").toSize();
ui->NodeSizeX->setValue(size.width());
}
QList<CItem*> nodeItems;
// edges
ui->EdgesBox->setTitle(tr("Selected connections (%1)").arg(edges.count()));
if (edges.count())
{
auto edge = edges.first();
// ui->EdgeColor->setColor(edge->getAttribute("color").value<QColor>());
// ui->EdgeWeight->setValue(edge->getAttribute("weight").toDouble());
// ui->EdgeStyle->setPenStyle(CUtils::textToPenStyle(edge->getAttribute("style").toString()));
// ui->EdgeDirection->selectAction(edge->getAttribute("direction"));
}
QList<CItem*> edgeItems;
for (auto item: edges) edgeItems << item;
// labels
QList<CItem*> itemList;
for (auto edgeItem: edges) itemList << edgeItem;
for (auto nodeItem: nodes) itemList << nodeItem;
for (auto item: itemList)
{
QFont f(item->getAttribute("label.font").value<QFont>());
ui->LabelFont->setCurrentFont(f);
ui->LabelFontSize->setValue(f.pointSize());
ui->LabelFontBold->setChecked(f.bold());
ui->LabelFontItalic->setChecked(f.italic());
ui->LabelFontUnderline->setChecked(f.underline());
ui->LabelColor->setColor(item->getAttribute("label.color").value<QColor>());
break;
}
// allow updates
m_updateLock = false;
}
void CNodeEdgePropertiesUI::setNodesAttribute(const QByteArray& attrId, const QVariant& v)
{
QString s = QVariant(v).toString();
if (attrId == "shape")
CurrentValues::instance().shape = s;
if (m_nodeFactory)
m_nodeFactory->setAttribute(attrId, v);
if (m_updateLock || m_scene == NULL)
return;
QList<CNode*> nodes = m_scene->getSelectedNodes();
if (nodes.isEmpty())
return;
//WPaw - tu ustawia się atrybut dla konkretnego noda
for (auto node : nodes)
node->setAttribute(attrId, v);
m_scene->addUndoState();
}
void CNodeEdgePropertiesUI::setEdgesAttribute(const QByteArray& attrId, const QVariant& v)
{
if (m_edgeFactory)
m_edgeFactory->setAttribute(attrId, v);
if (m_updateLock || m_scene == NULL)
return;
QList<CEdge*> edges = m_scene->getSelectedEdges();
if (edges.isEmpty())
return;
for (auto edge : edges)
edge->setAttribute(attrId, v);
m_scene->addUndoState();
}
void CNodeEdgePropertiesUI::on_NodeColor_activated(const QColor &color)
{
setNodesAttribute("color", color);
}
void CNodeEdgePropertiesUI::on_NodeFlowShape_activated(QVariant data)
{
setNodesAttribute("shape", data);
ui->rButFlow->setChecked(1);
// ui->rButFlow->clicked(true);
// ui->rButProc->clicked(false);
}
void CNodeEdgePropertiesUI::on_NodeProcShape_activated(QVariant data)
{
setNodesAttribute("shape", data);
ui->rButProc->setChecked(1);
// ui->rButFlow->clicked(false);
// ui->rButProc->clicked(true);
}
void CNodeEdgePropertiesUI::on_NodeSizeX_valueChanged(int /*value*/)
{
ui->NodeSizeX->blockSignals(true);
QSize size(ui->NodeSizeX->value(), ui->NodeSizeX->value());
setNodesAttribute("size", size);
ui->NodeSizeX->blockSignals(false);
}
void CNodeEdgePropertiesUI::on_StrokeColor_activated(const QColor &color)
{
setNodesAttribute("stroke.color", color);
}
void CNodeEdgePropertiesUI::on_StrokeStyle_activated(QVariant data)
{
QString style = CUtils::penStyleToText(data.toInt());
setNodesAttribute("stroke.style", style);
}
void CNodeEdgePropertiesUI::on_StrokeSize_valueChanged(double value)
{
setNodesAttribute("stroke.size", value);
}
void CNodeEdgePropertiesUI::on_EdgeColor_activated(const QColor &color)
{
setEdgesAttribute("color", color);
}
void CNodeEdgePropertiesUI::on_EdgeWeight_valueChanged(double value)
{
setEdgesAttribute("weight", value);
}
void CNodeEdgePropertiesUI::on_EdgeStyle_activated(QVariant data)
{
QString style = CUtils::penStyleToText(data.toInt());
setEdgesAttribute("style", style);
}
void CNodeEdgePropertiesUI::on_Edge_activated(QVariant data)
{
QString s = QVariant(data).toString();
CurrentValues::instance().connection = s;
setEdgesAttribute("style", data);
}
void CNodeEdgePropertiesUI::on_EdgeDirection_activated(QVariant data)
{
setEdgesAttribute("direction", data);
}
void CNodeEdgePropertiesUI::on_LabelFont_activated(const QFont &font)
{
ui->LabelFontSize->blockSignals(true);
ui->LabelFontSize->setValue(font.pointSize());
ui->LabelFontSize->blockSignals(false);
if (m_updateLock || m_scene == NULL)
return;
QList<CItem*> items = m_scene->getSelectedNodesEdges();
if (items.isEmpty())
return;
for (auto item : items)
{
item->setAttribute(attr_label_font, font);
}
m_scene->addUndoState();
}
void CNodeEdgePropertiesUI::on_LabelColor_activated(const QColor &color)
{
if (m_updateLock || m_scene == NULL)
return;
QList<CItem*> items = m_scene->getSelectedNodesEdges();
if (items.isEmpty())
return;
for (auto item : items)
{
item->setAttribute(attr_label_color, color);
}
m_scene->addUndoState();
}
void CNodeEdgePropertiesUI::on_LabelFontSize_valueChanged(int value)
{
if (m_updateLock || m_scene == NULL)
return;
QList<CItem*> items = m_scene->getSelectedNodesEdges();
if (items.isEmpty())
return;
bool set = false;
for (auto item : items)
{
QFont font = item->getAttribute(attr_label_font).value<QFont>();
if (font.pointSize() != value)
{
font.setPointSize(value);
item->setAttribute(attr_label_font, font);
set = true;
}
}
if (set)
m_scene->addUndoState();
}
void CNodeEdgePropertiesUI::on_LabelFontBold_toggled(bool on)
{
if (m_updateLock || m_scene == NULL)
return;
QList<CItem*> items = m_scene->getSelectedNodesEdges();
if (items.isEmpty())
return;
bool set = false;
for (auto item : items)
{
QFont font = item->getAttribute(attr_label_font).value<QFont>();
if (font.bold() != on)
{
font.setBold(on);
item->setAttribute(attr_label_font, font);
set = true;
}
}
if (set)
m_scene->addUndoState();
}
void CNodeEdgePropertiesUI::on_LabelFontItalic_toggled(bool on)
{
if (m_updateLock || m_scene == NULL)
return;
QList<CItem*> items = m_scene->getSelectedNodesEdges();
if (items.isEmpty())
return;
bool set = false;
for (auto item : items)
{
QFont font = item->getAttribute(attr_label_font).value<QFont>();
if (font.italic() != on)
{
font.setItalic(on);
item->setAttribute(attr_label_font, font);
item->updateLabelContent();
set = true;
}
}
if (set)
m_scene->addUndoState();
}
void CNodeEdgePropertiesUI::on_LabelFontUnderline_toggled(bool on)
{
if (m_updateLock || m_scene == NULL)
return;
QList<CItem*> items = m_scene->getSelectedNodesEdges();
if (items.isEmpty())
return;
bool set = false;
for (auto item : items)
{
QFont font = item->getAttribute(attr_label_font).value<QFont>();
if (font.underline() != on)
{
font.setUnderline(on);
item->setAttribute(attr_label_font, font);
set = true;
}
}
if (set)
m_scene->addUndoState();
}
void CNodeEdgePropertiesUI::on_NodeFlowShape_windowIconChanged(const QIcon &icon)
{
QMessageBox qmb;
qmb.setText( " duuuap");
qmb.exec();
}
| 25.449905
| 135
| 0.714997
|
wojtek48
|
fde988d21be7b6ef5651632c1be04987542238f8
| 606
|
cc
|
C++
|
Part-II/Ch09/9.3.3/9.25.cc
|
RingZEROtlf/Cpp-Primer
|
bde40534eeca733350825c41f268415fdccb1cc3
|
[
"MIT"
] | 1
|
2021-09-23T13:13:12.000Z
|
2021-09-23T13:13:12.000Z
|
Part-II/Ch09/9.3.3/9.25.cc
|
RingZEROtlf/Cpp-Primer
|
bde40534eeca733350825c41f268415fdccb1cc3
|
[
"MIT"
] | null | null | null |
Part-II/Ch09/9.3.3/9.25.cc
|
RingZEROtlf/Cpp-Primer
|
bde40534eeca733350825c41f268415fdccb1cc3
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
int main()
{
{
vector<int> vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto elem1 = vec.begin() + 2, elem2 = vec.begin() + 2;
elem1 = vec.erase(elem1, elem2);
for (auto &v: vec) {
cout << v << " ";
}
cout << "\n";
}
{
vector<int> vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto elem1 = vec.end(), elem2 = vec.end();
elem1 = vec.erase(elem1, elem2);
for (auto &v: vec) {
cout << v << " ";
}
cout << "\n";
}
return 0;
}
| 23.307692
| 62
| 0.410891
|
RingZEROtlf
|
fdeb4e989fe8830379629f873cd7d1c30e777d6b
| 17,596
|
cc
|
C++
|
repos/ComponentRosJoystick/smartsoft/src-gen/ComponentRosJoystick.cc
|
skarvtech/uwrosys
|
c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4
|
[
"Apache-2.0"
] | null | null | null |
repos/ComponentRosJoystick/smartsoft/src-gen/ComponentRosJoystick.cc
|
skarvtech/uwrosys
|
c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4
|
[
"Apache-2.0"
] | null | null | null |
repos/ComponentRosJoystick/smartsoft/src-gen/ComponentRosJoystick.cc
|
skarvtech/uwrosys
|
c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4
|
[
"Apache-2.0"
] | null | null | null |
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "ComponentRosJoystick.hh"
#include "smartTimedTaskTrigger.h"
//FIXME: implement logging
//#include "smartGlobalLogger.hh"
// the ace port-factory is used as a default port-mapping
#include "ComponentRosJoystickAcePortFactory.hh"
// initialize static singleton pointer to zero
ComponentRosJoystick* ComponentRosJoystick::_componentRosJoystick = 0;
// constructor
ComponentRosJoystick::ComponentRosJoystick()
{
std::cout << "constructor of ComponentRosJoystick\n";
// set all pointer members to NULL
joystickActivity = NULL;
joystickActivityTrigger = NULL;
joystickServiceOut = NULL;
//_joy = NULL;
stateChangeHandler = NULL;
stateSlave = NULL;
wiringSlave = NULL;
// set default ini parameter values
connections.component.name = "ComponentRosJoystick";
connections.component.initialComponentMode = "Neutral";
connections.component.defaultScheduler = "DEFAULT";
connections.component.useLogger = false;
connections.joystickServiceOut.serviceName = "JoystickServiceOut";
connections.joystickServiceOut.roboticMiddleware = "ACE_SmartSoft";
connections.joystickActivity.minActFreq = 0.0;
connections.joystickActivity.maxActFreq = 0.0;
connections.joystickActivity.trigger = "PeriodicTimer";
connections.joystickActivity.periodicActFreq = 10.0;
// scheduling default parameters
connections.joystickActivity.scheduler = "DEFAULT";
connections.joystickActivity.priority = -1;
connections.joystickActivity.cpuAffinity = -1;
// initialize members of ComponentRosJoystickROSExtension
rosPorts = 0;
// initialize members of OpcUaBackendComponentGeneratorExtension
// initialize members of PlainOpcUaComponentRosJoystickExtension
}
void ComponentRosJoystick::addPortFactory(const std::string &name, ComponentRosJoystickPortFactoryInterface *portFactory)
{
portFactoryRegistry[name] = portFactory;
}
void ComponentRosJoystick::addExtension(ComponentRosJoystickExtension *extension)
{
componentExtensionRegistry[extension->getName()] = extension;
}
SmartACE::SmartComponent* ComponentRosJoystick::getComponentImpl()
{
return dynamic_cast<ComponentRosJoystickAcePortFactory*>(portFactoryRegistry["ACE_SmartSoft"])->getComponentImpl();
}
/**
* Notify the component that setup/initialization is finished.
* You may call this function from anywhere in the component.
*
* Set component's internal lifecycle state automaton (if any) into
* Alive mode (from here on the component is ready to provide its services)
*/
void ComponentRosJoystick::setStartupFinished() {
stateSlave->setWaitState("Alive");
std::cout << "ComponentDefinition initialization/startup finished." << std::endl;
}
/**
* First connect ALL client ports contained in this component, then start all services:
* activate state, push, etc...
*/
Smart::StatusCode ComponentRosJoystick::connectAndStartAllServices() {
Smart::StatusCode status = Smart::SMART_OK;
return status;
}
/**
* Start all tasks contained in this component.
*/
void ComponentRosJoystick::startAllTasks() {
// start task JoystickActivity
if(connections.joystickActivity.scheduler != "DEFAULT") {
ACE_Sched_Params joystickActivity_SchedParams(ACE_SCHED_OTHER, ACE_THR_PRI_OTHER_DEF);
if(connections.joystickActivity.scheduler == "FIFO") {
joystickActivity_SchedParams.policy(ACE_SCHED_FIFO);
joystickActivity_SchedParams.priority(ACE_THR_PRI_FIFO_MIN);
} else if(connections.joystickActivity.scheduler == "RR") {
joystickActivity_SchedParams.policy(ACE_SCHED_RR);
joystickActivity_SchedParams.priority(ACE_THR_PRI_RR_MIN);
}
joystickActivity->start(joystickActivity_SchedParams, connections.joystickActivity.cpuAffinity);
} else {
joystickActivity->start();
}
}
/**
* Start all timers contained in this component
*/
void ComponentRosJoystick::startAllTimers() {
}
Smart::TaskTriggerSubject* ComponentRosJoystick::getInputTaskTriggerFromString(const std::string &client)
{
return NULL;
}
void ComponentRosJoystick::init(int argc, char *argv[])
{
try {
Smart::StatusCode status;
// load initial parameters from ini-file (if found)
loadParameter(argc, argv);
// initializations of ComponentRosJoystickROSExtension
// initializations of OpcUaBackendComponentGeneratorExtension
// initializations of PlainOpcUaComponentRosJoystickExtension
// initialize all registered port-factories
for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++)
{
portFactory->second->initialize(this, argc, argv);
}
// initialize all registered component-extensions
for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++)
{
extension->second->initialize(this, argc, argv);
}
ComponentRosJoystickPortFactoryInterface *acePortFactory = portFactoryRegistry["ACE_SmartSoft"];
if(acePortFactory == 0) {
std::cerr << "ERROR: acePortFactory NOT instantiated -> exit(-1)" << std::endl;
exit(-1);
}
// this pointer is used for backwards compatibility (deprecated: should be removed as soon as all patterns, including coordination, are moved to port-factory)
SmartACE::SmartComponent *component = dynamic_cast<ComponentRosJoystickAcePortFactory*>(acePortFactory)->getComponentImpl();
std::cout << "ComponentDefinition ComponentRosJoystick is named " << connections.component.name << std::endl;
if(connections.component.useLogger == true) {
//FIXME: use logging
//Smart::LOGGER->openLogFileInFolder("data/"+connections.component.name);
//Smart::LOGGER->startLogging();
}
// create event-test handlers (if needed)
// create server ports
// TODO: set minCycleTime from Ini-file
joystickServiceOut = portFactoryRegistry[connections.joystickServiceOut.roboticMiddleware]->createJoystickServiceOut(connections.joystickServiceOut.serviceName);
// create client ports
// create InputTaskTriggers and UpcallManagers
// create input-handler
// create request-handlers
// create state pattern
stateChangeHandler = new SmartStateChangeHandler();
stateSlave = new SmartACE::StateSlave(component, stateChangeHandler);
status = stateSlave->setUpInitialState(connections.component.initialComponentMode);
if (status != Smart::SMART_OK) std::cerr << status << "; failed setting initial ComponentMode: " << connections.component.initialComponentMode << std::endl;
// activate state slave
status = stateSlave->activate();
if(status != Smart::SMART_OK) std::cerr << "ERROR: activate state" << std::endl;
wiringSlave = new SmartACE::WiringSlave(component);
// add client port to wiring slave
// create Task JoystickActivity
joystickActivity = new JoystickActivity(component);
// configure input-links
// configure task-trigger (if task is configurable)
if(connections.joystickActivity.trigger == "PeriodicTimer") {
// create PeriodicTimerTrigger
int microseconds = 1000*1000 / connections.joystickActivity.periodicActFreq;
if(microseconds > 0) {
Smart::TimedTaskTrigger *triggerPtr = new Smart::TimedTaskTrigger();
triggerPtr->attach(joystickActivity);
component->getTimerManager()->scheduleTimer(triggerPtr, (void *) 0, std::chrono::microseconds(microseconds), std::chrono::microseconds(microseconds));
// store trigger in class member
joystickActivityTrigger = triggerPtr;
} else {
std::cerr << "ERROR: could not set-up Timer with cycle-time " << microseconds << " as activation source for Task JoystickActivity" << std::endl;
}
} else if(connections.joystickActivity.trigger == "DataTriggered") {
joystickActivityTrigger = getInputTaskTriggerFromString(connections.joystickActivity.inPortRef);
if(joystickActivityTrigger != NULL) {
joystickActivityTrigger->attach(joystickActivity, connections.joystickActivity.prescale);
} else {
std::cerr << "ERROR: could not set-up InPort " << connections.joystickActivity.inPortRef << " as activation source for Task JoystickActivity" << std::endl;
}
} else
{
// setup default task-trigger as PeriodicTimer
Smart::TimedTaskTrigger *triggerPtr = new Smart::TimedTaskTrigger();
int microseconds = 1000*1000 / 10.0;
if(microseconds > 0) {
component->getTimerManager()->scheduleTimer(triggerPtr, (void *) 0, std::chrono::microseconds(microseconds), std::chrono::microseconds(microseconds));
triggerPtr->attach(joystickActivity);
// store trigger in class member
joystickActivityTrigger = triggerPtr;
} else {
std::cerr << "ERROR: could not set-up Timer with cycle-time " << microseconds << " as activation source for Task JoystickActivity" << std::endl;
}
}
// link observers with subjects
} catch (const std::exception &ex) {
std::cerr << "Uncaught std exception" << ex.what() << std::endl;
} catch (...) {
std::cerr << "Uncaught exception" << std::endl;
}
}
// run the component
void ComponentRosJoystick::run()
{
stateSlave->acquire("init");
// startup all registered port-factories
for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++)
{
portFactory->second->onStartup();
}
// startup all registered component-extensions
for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++)
{
extension->second->onStartup();
}
stateSlave->release("init");
// do not call this handler within the init state (see above) as this handler internally calls setStartupFinished() (this should be fixed in future)
compHandler.onStartup();
// this call blocks until the component is commanded to shutdown
stateSlave->acquire("shutdown");
// shutdown all registered component-extensions
for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++)
{
extension->second->onShutdown();
}
// shutdown all registered port-factories
for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++)
{
portFactory->second->onShutdown();
}
if(connections.component.useLogger == true) {
//FIXME: use logging
//Smart::LOGGER->stopLogging();
}
compHandler.onShutdown();
stateSlave->release("shutdown");
}
// clean-up component's resources
void ComponentRosJoystick::fini()
{
// unlink all observers
// destroy all task instances
// unlink all UpcallManagers
// unlink the TaskTrigger
if(joystickActivityTrigger != NULL){
joystickActivityTrigger->detach(joystickActivity);
delete joystickActivity;
}
// destroy all input-handler
// destroy InputTaskTriggers and UpcallManagers
// destroy client ports
// destroy server ports
delete joystickServiceOut;
// destroy event-test handlers (if needed)
// destroy request-handlers
delete stateSlave;
// destroy state-change-handler
delete stateChangeHandler;
// destroy all master/slave ports
delete wiringSlave;
// destroy all registered component-extensions
for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++)
{
extension->second->destroy();
}
// destroy all registered port-factories
for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++)
{
portFactory->second->destroy();
}
// destruction of ComponentRosJoystickROSExtension
// destruction of OpcUaBackendComponentGeneratorExtension
// destruction of PlainOpcUaComponentRosJoystickExtension
}
void ComponentRosJoystick::loadParameter(int argc, char *argv[])
{
/*
Parameters can be specified via command line --filename=<filename> or -f <filename>
With this parameter present:
- The component will look for the file in the current working directory,
a path relative to the current directory or any absolute path
- The component will use the default values if the file cannot be found
With this parameter absent:
- <Name of Component>.ini will be read from current working directory, if found there
- $SMART_ROOT/etc/<Name of Component>.ini will be read otherwise
- Default values will be used if neither found in working directory or /etc
*/
SmartACE::SmartIniParameter parameter;
std::ifstream parameterfile;
bool parameterFileFound = false;
// load parameters
try
{
// if paramfile is given as argument
if(parameter.tryAddFileFromArgs(argc,argv,"filename", 'f'))
{
parameterFileFound = true;
std::cout << "parameter file is loaded from an argv argument \n";
} else if(parameter.searchFile("ComponentRosJoystick.ini", parameterfile)) {
parameterFileFound = true;
std::cout << "load ComponentRosJoystick.ini parameter file\n";
parameter.addFile(parameterfile);
} else {
std::cout << "WARNING: ComponentRosJoystick.ini parameter file not found! (using default values or command line arguments)\n";
}
// add command line arguments to allow overwriting of parameters
// from file
parameter.addCommandLineArgs(argc,argv,"component");
// initialize the naming service using the command line parameters parsed in the
// SmartIniParameter class. The naming service parameters are expected to be in
// the "component" parameter group.
SmartACE::NAMING::instance()->checkForHelpArg(argc,argv);
if(parameterFileFound)
{
if(SmartACE::NAMING::instance()->init(parameter.getAllParametersFromGroup("component")) != 0) {
// initialization of naming service failed
throw std::logic_error( "<NamingService> Service initialization failed!\nPossible causes could be:\n-> Erroneous configuration.\n-> Naming service not reachable.\n" );
}
} else {
if(SmartACE::NAMING::instance()->init(argc, argv) != 0) {
// initialization of naming service failed
throw std::logic_error( "<NamingService> Service initialization failed!\nPossible causes could be:\n-> Erroneous configuration.\n-> Naming service not reachable.\n" );
}
}
// print all known parameters
// parameter.print();
//--- server port // client port // other parameter ---
// load parameter
parameter.getString("component", "name", connections.component.name);
parameter.getString("component", "initialComponentMode", connections.component.initialComponentMode);
if(parameter.checkIfParameterExists("component", "defaultScheduler")) {
parameter.getString("component", "defaultScheduler", connections.component.defaultScheduler);
}
if(parameter.checkIfParameterExists("component", "useLogger")) {
parameter.getBoolean("component", "useLogger", connections.component.useLogger);
}
// load parameters for server JoystickServiceOut
parameter.getString("JoystickServiceOut", "serviceName", connections.joystickServiceOut.serviceName);
if(parameter.checkIfParameterExists("JoystickServiceOut", "roboticMiddleware")) {
parameter.getString("JoystickServiceOut", "roboticMiddleware", connections.joystickServiceOut.roboticMiddleware);
}
// load parameters for task JoystickActivity
parameter.getDouble("JoystickActivity", "minActFreqHz", connections.joystickActivity.minActFreq);
parameter.getDouble("JoystickActivity", "maxActFreqHz", connections.joystickActivity.maxActFreq);
parameter.getString("JoystickActivity", "triggerType", connections.joystickActivity.trigger);
if(connections.joystickActivity.trigger == "PeriodicTimer") {
parameter.getDouble("JoystickActivity", "periodicActFreqHz", connections.joystickActivity.periodicActFreq);
} else if(connections.joystickActivity.trigger == "DataTriggered") {
parameter.getString("JoystickActivity", "inPortRef", connections.joystickActivity.inPortRef);
parameter.getInteger("JoystickActivity", "prescale", connections.joystickActivity.prescale);
}
if(parameter.checkIfParameterExists("JoystickActivity", "scheduler")) {
parameter.getString("JoystickActivity", "scheduler", connections.joystickActivity.scheduler);
}
if(parameter.checkIfParameterExists("JoystickActivity", "priority")) {
parameter.getInteger("JoystickActivity", "priority", connections.joystickActivity.priority);
}
if(parameter.checkIfParameterExists("JoystickActivity", "cpuAffinity")) {
parameter.getInteger("JoystickActivity", "cpuAffinity", connections.joystickActivity.cpuAffinity);
}
// load parameters for ComponentRosJoystickROSExtension
// load parameters for OpcUaBackendComponentGeneratorExtension
// load parameters for PlainOpcUaComponentRosJoystickExtension
// load parameters for all registered component-extensions
for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++)
{
extension->second->loadParameters(parameter);
}
} catch (const SmartACE::IniParameterError & e) {
std::cerr << e.what() << std::endl;
} catch (const std::exception &ex) {
std::cerr << "Uncaught std::exception: " << ex.what() << std::endl;
} catch (...) {
std::cerr << "Uncaught exception" << std::endl;
}
}
| 36.734864
| 171
| 0.746874
|
skarvtech
|
fdec234fe5bdd5e77784bc5cab7a5b8a4585ce29
| 15,092
|
cpp
|
C++
|
inetcore/outlookexpress/mailnews/util/exchrep/mapiconv.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
inetcore/outlookexpress/mailnews/util/exchrep/mapiconv.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
inetcore/outlookexpress/mailnews/util/exchrep/mapiconv.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
// =====================================================================================
// m a p c o n v . c p p
// conver a MAPI message to and from an RFC 822/RFC 1521 (mime) internet message
// =====================================================================================
#include "pch.hxx"
#include "Imnapi.h"
#include "Exchrep.h"
#include "Mapiconv.h"
#include "Error.h"
HRESULT HrCopyStream (LPSTREAM lpstmIn, LPSTREAM lpstmOut, ULONG *pcb);
// =====================================================================================
// MAPI Message Properties that I want
// =====================================================================================
enum
{
colSenderAddrType,
colSenderName,
colSenderEMail,
colSubject,
colDeliverTime,
colBody,
colPriority,
colLast1
};
SizedSPropTagArray (colLast1, sptMessageProps) =
{
colLast1,
{
PR_SENDER_ADDRTYPE,
PR_SENDER_NAME,
PR_SENDER_EMAIL_ADDRESS,
PR_SUBJECT,
PR_MESSAGE_DELIVERY_TIME,
PR_BODY,
PR_PRIORITY
}
};
// =====================================================================================
// MAPI Recip Props
// =====================================================================================
enum
{
colRecipAddrType,
colRecipName,
colRecipAddress,
colRecipType,
colLast2
};
SizedSPropTagArray (colLast2, sptRecipProps) =
{
colLast2,
{
PR_ADDRTYPE,
PR_DISPLAY_NAME,
PR_EMAIL_ADDRESS,
PR_RECIPIENT_TYPE
}
};
// =====================================================================================
// MAPI Attachment Props
// =====================================================================================
enum
{
colAttMethod,
colAttNum,
colAttLongFilename,
colAttLongPathname,
colAttPathname,
colAttTag,
colAttFilename,
colAttExtension,
colAttSize,
colLast3
};
SizedSPropTagArray (colLast3, sptAttProps) =
{
colLast3,
{
PR_ATTACH_METHOD,
PR_ATTACH_NUM,
PR_ATTACH_LONG_FILENAME,
PR_ATTACH_LONG_PATHNAME,
PR_ATTACH_PATHNAME,
PR_ATTACH_TAG,
PR_ATTACH_FILENAME,
PR_ATTACH_EXTENSION,
PR_ATTACH_SIZE
}
};
// =============================================================================================
// StringDup - duplicates a string
// =============================================================================================
LPTSTR StringDup (LPCTSTR lpcsz)
{
// Locals
LPTSTR lpszDup;
if (lpcsz == NULL)
return NULL;
INT nLen = lstrlen (lpcsz) + 1;
lpszDup = (LPTSTR)malloc (nLen * sizeof (TCHAR));
if (lpszDup)
CopyMemory (lpszDup, lpcsz, nLen);
return lpszDup;
}
// =====================================================================================
// HrMapiToImsg
// =====================================================================================
HRESULT HrMapiToImsg (LPMESSAGE lpMessage, LPIMSG lpImsg)
{
// Locals
HRESULT hr = S_OK;
ULONG cProp, i;
LPSPropValue lpMsgPropValue = NULL;
LPSRowSet lpRecipRows = NULL, lpAttRows = NULL;
LPMAPITABLE lptblRecip = NULL, lptblAtt = NULL;
LPATTACH lpAttach = NULL;
LPMESSAGE lpMsgAtt = NULL;
LPSTREAM lpstmRtfComp = NULL, lpstmRtf = NULL;
// Zero init
ZeroMemory (lpImsg, sizeof (IMSG));
// Get the propsw
hr = lpMessage->GetProps ((LPSPropTagArray)&sptMessageProps, 0, &cProp, &lpMsgPropValue);
if (FAILED (hr))
goto exit;
// Subject
if (PROP_TYPE(lpMsgPropValue[colSubject].ulPropTag) != PT_ERROR)
lpImsg->lpszSubject = StringDup (lpMsgPropValue[colSubject].Value.lpszA);
// Body
if (PROP_TYPE(lpMsgPropValue[colBody].ulPropTag) != PT_ERROR)
lpImsg->lpszBody = StringDup (lpMsgPropValue[colBody].Value.lpszA);
// RTF
if (!FAILED (lpMessage->OpenProperty (PR_RTF_COMPRESSED, (LPIID)&IID_IStream, 0, 0, (LPUNKNOWN *)&lpstmRtfComp)))
if (!FAILED (WrapCompressedRTFStream (lpstmRtfComp, 0, &lpstmRtf)))
if (!FAILED (CreateStreamOnHFile (NULL, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL, &lpImsg->lpstmRtf)))
HrCopyStream (lpstmRtf, lpImsg->lpstmRtf, NULL);
// Delivery Time
if (PROP_TYPE(lpMsgPropValue[colDeliverTime].ulPropTag) != PT_ERROR)
CopyMemory (&lpImsg->ftDelivery, &lpMsgPropValue[colDeliverTime].Value.ft, sizeof (FILETIME));
// Priority
lpImsg->wPriority = PRI_NORMAL;
if (PROP_TYPE(lpMsgPropValue[colPriority].ulPropTag) != PT_ERROR)
{
switch (lpMsgPropValue[colPriority].Value.l)
{
case PRIO_NORMAL:
lpImsg->wPriority = PRI_NORMAL;
break;
case PRIO_URGENT:
lpImsg->wPriority = PRI_HIGH;
break;
case PRIO_NONURGENT:
default:
lpImsg->wPriority = PRI_LOW;
break;
}
}
// Get the recipient table
hr = lpMessage->GetRecipientTable (0, &lptblRecip);
if (FAILED (hr))
goto exit;
// Get all the rows of the recipient table
hr = HrQueryAllRows (lptblRecip, (LPSPropTagArray)&sptRecipProps, NULL, NULL, 0, &lpRecipRows);
if (FAILED (hr))
goto exit;
// Allocate Recipient Array
lpImsg->cAddress = lpRecipRows->cRows + 1;
lpImsg->lpIaddr = (LPIADDRINFO)malloc (sizeof (IADDRINFO) * lpImsg->cAddress);
if (lpImsg->lpIaddr == NULL)
goto exit;
// Originator of the message "From: "
lpImsg->lpIaddr[0].dwType = IADDR_FROM;
if (PROP_TYPE(lpMsgPropValue[colSenderName].ulPropTag) != PT_ERROR)
{
lpImsg->lpIaddr[0].lpszDisplay = StringDup (lpMsgPropValue[colSenderName].Value.lpszA);
lpImsg->lpIaddr[0].lpszAddress = StringDup (lpMsgPropValue[colSenderName].Value.lpszA);
}
if (PROP_TYPE(lpMsgPropValue[colSenderEMail].ulPropTag) != PT_ERROR &&
PROP_TYPE(lpMsgPropValue[colSenderAddrType].ulPropTag) != PT_ERROR &&
lstrcmpi (lpMsgPropValue[colSenderAddrType].Value.lpszA, "SMTP") == 0)
{
lpImsg->lpIaddr[0].lpszAddress = StringDup (lpMsgPropValue[colSenderEMail].Value.lpszA);
}
// Add in the rest of the recipients
for (i=0; i<lpRecipRows->cRows; i++)
{
assert (i+1 < lpImsg->cAddress);
if (PROP_TYPE(lpRecipRows->aRow[i].lpProps[colRecipType].ulPropTag) != PT_ERROR)
{
switch (lpRecipRows->aRow[i].lpProps[colRecipType].Value.ul)
{
case MAPI_TO:
lpImsg->lpIaddr[i+1].dwType = IADDR_TO;
break;
case MAPI_ORIG:
lpImsg->lpIaddr[i+1].dwType = IADDR_FROM;
break;
case MAPI_CC:
lpImsg->lpIaddr[i+1].dwType = IADDR_CC;
break;
case MAPI_BCC:
lpImsg->lpIaddr[i+1].dwType = IADDR_BCC;
break;
default:
Assert (FALSE);
lpImsg->lpIaddr[i+1].dwType = IADDR_TO;
break;
}
}
else
lpImsg->lpIaddr[i+1].dwType = IADDR_TO;
if (PROP_TYPE(lpRecipRows->aRow[i].lpProps[colRecipName].ulPropTag) != PT_ERROR)
{
lpImsg->lpIaddr[i+1].lpszDisplay = StringDup (lpRecipRows->aRow[i].lpProps[colRecipName].Value.lpszA);
lpImsg->lpIaddr[i+1].lpszAddress = StringDup (lpRecipRows->aRow[i].lpProps[colRecipName].Value.lpszA);
}
if (PROP_TYPE(lpRecipRows->aRow[i].lpProps[colRecipName].ulPropTag) != PT_ERROR &&
PROP_TYPE(lpMsgPropValue[colRecipAddrType].ulPropTag) != PT_ERROR &&
lstrcmpi (lpMsgPropValue[colRecipAddrType].Value.lpszA, "SMTP") == 0)
{
lpImsg->lpIaddr[i+1].lpszAddress = StringDup (lpRecipRows->aRow[i].lpProps[colRecipAddress].Value.lpszA);
}
}
// Free Rows
if (lpRecipRows)
FreeProws (lpRecipRows);
lpRecipRows = NULL;
// Attachments
hr = lpMessage->GetAttachmentTable (0, &lptblAtt);
if (FAILED (hr))
goto exit;
// Get all the rows of the recipient table
hr = HrQueryAllRows (lptblAtt, (LPSPropTagArray)&sptAttProps, NULL, NULL, 0, &lpAttRows);
if (FAILED (hr))
goto exit;
// Allocate files list
if (lpAttRows->cRows == 0)
goto exit;
// Allocate memory
lpImsg->cAttach = lpAttRows->cRows;
lpImsg->lpIatt = (LPIATTINFO)malloc (sizeof (IATTINFO) * lpImsg->cAttach);
if (lpImsg->lpIatt == NULL)
goto exit;
// Zero init
ZeroMemory (lpImsg->lpIatt, sizeof (IATTINFO) * lpImsg->cAttach);
// Walk the rows
for (i=0; i<lpAttRows->cRows; i++)
{
if (PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttMethod].ulPropTag) != PT_ERROR &&
PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttNum].ulPropTag) != PT_ERROR)
{
// Basic Properties
if (PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttPathname].ulPropTag) != PT_ERROR)
lpImsg->lpIatt[i].lpszPathName = StringDup (lpAttRows->aRow[i].lpProps[colAttPathname].Value.lpszA);
if (PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttFilename].ulPropTag) != PT_ERROR)
lpImsg->lpIatt[i].lpszFileName = StringDup (lpAttRows->aRow[i].lpProps[colAttFilename].Value.lpszA);
if (PROP_TYPE(lpAttRows->aRow[i].lpProps[colAttExtension].ulPropTag) != PT_ERROR)
lpImsg->lpIatt[i].lpszExt = StringDup (lpAttRows->aRow[i].lpProps[colAttExtension].Value.lpszA);
// Open the attachment
hr = lpMessage->OpenAttach (lpAttRows->aRow[i].lpProps[colAttNum].Value.l, NULL, MAPI_BEST_ACCESS, &lpAttach);
if (FAILED (hr))
{
lpImsg->lpIatt[i].fError = TRUE;
continue;
}
// Handle the attachment method
switch (lpAttRows->aRow[i].lpProps[colAttMethod].Value.ul)
{
case NO_ATTACHMENT:
lpImsg->lpIatt[i].dwType = 0;
lpImsg->lpIatt[i].fError = TRUE;
break;
case ATTACH_BY_REF_RESOLVE:
case ATTACH_BY_VALUE:
lpImsg->lpIatt[i].dwType = IATT_FILE;
hr = lpAttach->OpenProperty (PR_ATTACH_DATA_BIN, (LPIID)&IID_IStream, 0, 0, (LPUNKNOWN *)&lpImsg->lpIatt[i].lpstmAtt);
if (FAILED (hr))
lpImsg->lpIatt[i].fError = TRUE;
break;
case ATTACH_BY_REF_ONLY:
case ATTACH_BY_REFERENCE:
lpImsg->lpIatt[i].dwType = IATT_FILE;
hr = CreateStreamOnHFile (lpImsg->lpIatt[i].lpszPathName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL, &lpImsg->lpIatt[i].lpstmAtt);
if (FAILED (hr))
lpImsg->lpIatt[i].fError = TRUE;
break;
case ATTACH_EMBEDDED_MSG:
lpImsg->lpIatt[i].dwType = IATT_MSG;
hr = lpAttach->OpenProperty (PR_ATTACH_DATA_OBJ, (LPIID)&IID_IMessage, 0, 0, (LPUNKNOWN *)&lpMsgAtt);
if (FAILED (hr) || lpMsgAtt == NULL)
lpImsg->lpIatt[i].fError = TRUE;
else
{
lpImsg->lpIatt[i].lpImsg = (LPIMSG)malloc (sizeof (IMSG));
if (lpImsg->lpIatt[i].lpImsg == NULL)
lpImsg->lpIatt[i].fError = TRUE;
else
{
hr = HrMapiToImsg (lpMsgAtt, lpImsg->lpIatt[i].lpImsg);
if (FAILED (hr))
lpImsg->lpIatt[i].fError = TRUE;
}
lpMsgAtt->Release ();
lpMsgAtt = NULL;
}
break;
case ATTACH_OLE:
default:
lpImsg->lpIatt[i].dwType = IATT_OLE;
lpImsg->lpIatt[i].fError = TRUE;
break;
}
// Free Attachment
if (lpAttach)
lpAttach->Release ();
lpAttach = NULL;
}
}
exit:
// Cleanup
if (lpAttach)
lpAttach->Release ();
if (lptblAtt)
lptblAtt->Release ();
if (lpAttRows)
FreeProws (lpAttRows);
if (lpRecipRows)
FreeProws (lpRecipRows);
if (lpMsgPropValue)
MAPIFreeBuffer (lpMsgPropValue);
if (lptblRecip)
lptblRecip->Release ();
if (lpMsgAtt)
lpMsgAtt->Release ();
if (lpstmRtfComp)
lpstmRtfComp->Release ();
if (lpstmRtf)
lpstmRtf->Release ();
// Done
return hr;
}
void AssertSzFn(LPSTR szMsg, LPSTR szFile, int nLine)
{
static const char rgch1[] = "File %s, line %d:";
static const char rgch2[] = "Unknown file:";
static const char szAssert[] = "Assert Failure";
char rgch[512];
char *lpsz;
int ret, cch;
if (szFile)
wnsprintf(rgch, ARRAYSIZE(rgch),rgch1, szFile, nLine);
else
StrCpyN(rgch, rgch2,ARRAYSIZE(rgch));
cch = lstrlen(rgch);
Assert(lstrlen(szMsg)<(512-cch-3));
lpsz = &rgch[cch];
*lpsz++ = '\n';
*lpsz++ = '\n';
StrCpyN(lpsz, szMsg, (ARRAYSIZE(rgch)-cch-2));
ret = MessageBox(GetActiveWindow(), rgch, szAssert, MB_ABORTRETRYIGNORE|MB_ICONHAND|MB_SYSTEMMODAL|MB_SETFOREGROUND);
if (ret != IDIGNORE)
DebugBreak();
/* Force a hard exit w/ a GP-fault so that Dr. Watson generates a nice stack trace log. */
if (ret == IDABORT)
*(LPBYTE)0 = 1; // write to address 0 causes GP-fault
}
// =====================================================================================
// HrCopyStream - caller must do the commit
// =====================================================================================
HRESULT HrCopyStream (LPSTREAM lpstmIn, LPSTREAM lpstmOut, ULONG *pcb)
{
// Locals
HRESULT hr = S_OK;
BYTE buf[4096];
ULONG cbRead = 0, cbTotal = 0;
do
{
hr = lpstmIn->Read (buf, sizeof (buf), &cbRead);
if (FAILED (hr))
goto exit;
if (cbRead == 0) break;
hr = lpstmOut->Write (buf, cbRead, NULL);
if (FAILED (hr))
goto exit;
cbTotal += cbRead;
}
while (cbRead == sizeof (buf));
exit:
if (pcb)
*pcb = cbTotal;
return hr;
}
| 32.737527
| 186
| 0.515505
|
npocmaka
|
fdede8c97289e8e1a2e3afe1e3a585ba45eefaa2
| 1,068
|
cpp
|
C++
|
src/kits/package/ActivateRepositoryCacheJob.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 1,338
|
2015-01-03T20:06:56.000Z
|
2022-03-26T13:49:54.000Z
|
src/kits/package/ActivateRepositoryCacheJob.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 15
|
2015-01-17T22:19:32.000Z
|
2021-12-20T12:35:00.000Z
|
src/kits/package/ActivateRepositoryCacheJob.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 350
|
2015-01-08T14:15:27.000Z
|
2022-03-21T18:14:35.000Z
|
/*
* Copyright 2011, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Oliver Tappe <zooey@hirschkaefer.de>
*/
#include <package/ActivateRepositoryCacheJob.h>
#include <File.h>
#include <package/Context.h>
namespace BPackageKit {
namespace BPrivate {
ActivateRepositoryCacheJob::ActivateRepositoryCacheJob(const BContext& context,
const BString& title, const BEntry& fetchedRepoCacheEntry,
const BString& repositoryName, const BDirectory& targetDirectory)
:
inherited(context, title),
fFetchedRepoCacheEntry(fetchedRepoCacheEntry),
fRepositoryName(repositoryName),
fTargetDirectory(targetDirectory)
{
}
ActivateRepositoryCacheJob::~ActivateRepositoryCacheJob()
{
}
status_t
ActivateRepositoryCacheJob::Execute()
{
status_t result = fFetchedRepoCacheEntry.MoveTo(&fTargetDirectory,
fRepositoryName.String(), true);
if (result != B_OK)
return result;
// TODO: propagate some repository attributes to file attributes
return B_OK;
}
} // namespace BPrivate
} // namespace BPackageKit
| 19.071429
| 79
| 0.774345
|
Kirishikesan
|
fdf571cbf3745b06c7a985d99512bf853c0d87b2
| 12,639
|
cpp
|
C++
|
src/effects/SkColorCubeFilter.cpp
|
tmpvar/skia.cc
|
6e36ba7bf19cc7597837bb0416882ad4d699916b
|
[
"Apache-2.0"
] | 3
|
2015-08-16T03:44:19.000Z
|
2015-08-16T17:31:59.000Z
|
third_party/skia/src/effects/SkColorCubeFilter.cpp
|
maidiHaitai/haitaibrowser
|
a232a56bcfb177913a14210e7733e0ea83a6b18d
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/skia/src/effects/SkColorCubeFilter.cpp
|
maidiHaitai/haitaibrowser
|
a232a56bcfb177913a14210e7733e0ea83a6b18d
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkColorCubeFilter.h"
#include "SkColorPriv.h"
#include "SkOnce.h"
#include "SkOpts.h"
#include "SkReadBuffer.h"
#include "SkUnPreMultiply.h"
#include "SkWriteBuffer.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrCoordTransform.h"
#include "GrInvariantOutput.h"
#include "GrTexturePriv.h"
#include "SkGr.h"
#include "glsl/GrGLSLFragmentProcessor.h"
#include "glsl/GrGLSLFragmentShaderBuilder.h"
#include "glsl/GrGLSLProgramDataManager.h"
#include "glsl/GrGLSLUniformHandler.h"
#endif
///////////////////////////////////////////////////////////////////////////////
namespace {
int32_t SkNextColorCubeUniqueID() {
static int32_t gColorCubeUniqueID;
// do a loop in case our global wraps around, as we never want to return a 0
int32_t genID;
do {
genID = sk_atomic_inc(&gColorCubeUniqueID) + 1;
} while (0 == genID);
return genID;
}
} // end namespace
static const int MIN_CUBE_SIZE = 4;
static const int MAX_CUBE_SIZE = 64;
static bool is_valid_3D_lut(SkData* cubeData, int cubeDimension) {
size_t minMemorySize = sizeof(uint8_t) * 4 * cubeDimension * cubeDimension * cubeDimension;
return (cubeDimension >= MIN_CUBE_SIZE) && (cubeDimension <= MAX_CUBE_SIZE) &&
(nullptr != cubeData) && (cubeData->size() >= minMemorySize);
}
sk_sp<SkColorFilter> SkColorCubeFilter::Make(sk_sp<SkData> cubeData, int cubeDimension) {
if (!is_valid_3D_lut(cubeData.get(), cubeDimension)) {
return nullptr;
}
return sk_sp<SkColorFilter>(new SkColorCubeFilter(std::move(cubeData), cubeDimension));
}
SkColorCubeFilter::SkColorCubeFilter(sk_sp<SkData> cubeData, int cubeDimension)
: fCubeData(std::move(cubeData))
, fUniqueID(SkNextColorCubeUniqueID())
, fCache(cubeDimension)
{}
uint32_t SkColorCubeFilter::getFlags() const {
return this->INHERITED::getFlags() | kAlphaUnchanged_Flag;
}
SkColorCubeFilter::ColorCubeProcesingCache::ColorCubeProcesingCache(int cubeDimension)
: fCubeDimension(cubeDimension) {
fColorToIndex[0] = fColorToIndex[1] = nullptr;
fColorToFactors[0] = fColorToFactors[1] = nullptr;
fColorToScalar = nullptr;
}
void SkColorCubeFilter::ColorCubeProcesingCache::getProcessingLuts(
const int* (*colorToIndex)[2], const SkScalar* (*colorToFactors)[2],
const SkScalar** colorToScalar) {
fLutsInitOnce(SkColorCubeFilter::ColorCubeProcesingCache::initProcessingLuts, this);
SkASSERT((fColorToIndex[0] != nullptr) &&
(fColorToIndex[1] != nullptr) &&
(fColorToFactors[0] != nullptr) &&
(fColorToFactors[1] != nullptr) &&
(fColorToScalar != nullptr));
(*colorToIndex)[0] = fColorToIndex[0];
(*colorToIndex)[1] = fColorToIndex[1];
(*colorToFactors)[0] = fColorToFactors[0];
(*colorToFactors)[1] = fColorToFactors[1];
(*colorToScalar) = fColorToScalar;
}
void SkColorCubeFilter::ColorCubeProcesingCache::initProcessingLuts(
SkColorCubeFilter::ColorCubeProcesingCache* cache) {
static const SkScalar inv8bit = SkScalarInvert(SkIntToScalar(255));
// We need 256 int * 2 for fColorToIndex, so a total of 512 int.
// We need 256 SkScalar * 2 for fColorToFactors and 256 SkScalar
// for fColorToScalar, so a total of 768 SkScalar.
cache->fLutStorage.reset(512 * sizeof(int) + 768 * sizeof(SkScalar));
uint8_t* storage = cache->fLutStorage.get();
cache->fColorToIndex[0] = (int*)storage;
cache->fColorToIndex[1] = cache->fColorToIndex[0] + 256;
cache->fColorToFactors[0] = (SkScalar*)(storage + (512 * sizeof(int)));
cache->fColorToFactors[1] = cache->fColorToFactors[0] + 256;
cache->fColorToScalar = cache->fColorToFactors[1] + 256;
SkScalar size = SkIntToScalar(cache->fCubeDimension);
SkScalar scale = (size - SK_Scalar1) * inv8bit;
for (int i = 0; i < 256; ++i) {
SkScalar index = scale * i;
cache->fColorToIndex[0][i] = SkScalarFloorToInt(index);
cache->fColorToIndex[1][i] = cache->fColorToIndex[0][i] + 1;
cache->fColorToScalar[i] = inv8bit * i;
if (cache->fColorToIndex[1][i] < cache->fCubeDimension) {
cache->fColorToFactors[1][i] = index - SkIntToScalar(cache->fColorToIndex[0][i]);
cache->fColorToFactors[0][i] = SK_Scalar1 - cache->fColorToFactors[1][i];
} else {
cache->fColorToIndex[1][i] = cache->fColorToIndex[0][i];
cache->fColorToFactors[0][i] = SK_Scalar1;
cache->fColorToFactors[1][i] = 0;
}
}
}
void SkColorCubeFilter::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const {
const int* colorToIndex[2];
const SkScalar* colorToFactors[2];
const SkScalar* colorToScalar;
fCache.getProcessingLuts(&colorToIndex, &colorToFactors, &colorToScalar);
SkOpts::color_cube_filter_span(src, count, dst, colorToIndex,
colorToFactors, fCache.cubeDimension(),
(const SkColor*)fCubeData->data());
}
sk_sp<SkFlattenable> SkColorCubeFilter::CreateProc(SkReadBuffer& buffer) {
int cubeDimension = buffer.readInt();
auto cubeData(buffer.readByteArrayAsData());
if (!buffer.validate(is_valid_3D_lut(cubeData.get(), cubeDimension))) {
return nullptr;
}
return Make(std::move(cubeData), cubeDimension);
}
void SkColorCubeFilter::flatten(SkWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeInt(fCache.cubeDimension());
buffer.writeDataAsByteArray(fCubeData.get());
}
#ifndef SK_IGNORE_TO_STRING
void SkColorCubeFilter::toString(SkString* str) const {
str->append("SkColorCubeFilter ");
}
#endif
///////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
class GrColorCubeEffect : public GrFragmentProcessor {
public:
static const GrFragmentProcessor* Create(GrTexture* colorCube) {
return (nullptr != colorCube) ? new GrColorCubeEffect(colorCube) : nullptr;
}
virtual ~GrColorCubeEffect();
const char* name() const override { return "ColorCube"; }
int colorCubeSize() const { return fColorCubeAccess.getTexture()->width(); }
void onComputeInvariantOutput(GrInvariantOutput*) const override;
class GLSLProcessor : public GrGLSLFragmentProcessor {
public:
void emitCode(EmitArgs&) override;
static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*);
protected:
void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override;
private:
GrGLSLProgramDataManager::UniformHandle fColorCubeSizeUni;
GrGLSLProgramDataManager::UniformHandle fColorCubeInvSizeUni;
typedef GrGLSLFragmentProcessor INHERITED;
};
private:
virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps,
GrProcessorKeyBuilder* b) const override;
GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
GrColorCubeEffect(GrTexture* colorCube);
GrTextureAccess fColorCubeAccess;
typedef GrFragmentProcessor INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
GrColorCubeEffect::GrColorCubeEffect(GrTexture* colorCube)
: fColorCubeAccess(colorCube, GrTextureParams::kBilerp_FilterMode) {
this->initClassID<GrColorCubeEffect>();
this->addTextureAccess(&fColorCubeAccess);
}
GrColorCubeEffect::~GrColorCubeEffect() {
}
void GrColorCubeEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps,
GrProcessorKeyBuilder* b) const {
GLSLProcessor::GenKey(*this, caps, b);
}
GrGLSLFragmentProcessor* GrColorCubeEffect::onCreateGLSLInstance() const {
return new GLSLProcessor;
}
void GrColorCubeEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
inout->setToUnknown(GrInvariantOutput::kWill_ReadInput);
}
///////////////////////////////////////////////////////////////////////////////
void GrColorCubeEffect::GLSLProcessor::emitCode(EmitArgs& args) {
if (nullptr == args.fInputColor) {
args.fInputColor = "vec4(1)";
}
GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
fColorCubeSizeUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
kFloat_GrSLType, kDefault_GrSLPrecision,
"Size");
const char* colorCubeSizeUni = uniformHandler->getUniformCStr(fColorCubeSizeUni);
fColorCubeInvSizeUni = uniformHandler->addUniform(kFragment_GrShaderFlag,
kFloat_GrSLType, kDefault_GrSLPrecision,
"InvSize");
const char* colorCubeInvSizeUni = uniformHandler->getUniformCStr(fColorCubeInvSizeUni);
const char* nonZeroAlpha = "nonZeroAlpha";
const char* unPMColor = "unPMColor";
const char* cubeIdx = "cubeIdx";
const char* cCoords1 = "cCoords1";
const char* cCoords2 = "cCoords2";
// Note: if implemented using texture3D in OpenGL ES older than OpenGL ES 3.0,
// the shader might need "#extension GL_OES_texture_3D : enable".
GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
// Unpremultiply color
fragBuilder->codeAppendf("\tfloat %s = max(%s.a, 0.00001);\n", nonZeroAlpha, args.fInputColor);
fragBuilder->codeAppendf("\tvec4 %s = vec4(%s.rgb / %s, %s);\n",
unPMColor, args.fInputColor, nonZeroAlpha, nonZeroAlpha);
// Fit input color into the cube.
fragBuilder->codeAppendf(
"vec3 %s = vec3(%s.rg * vec2((%s - 1.0) * %s) + vec2(0.5 * %s), %s.b * (%s - 1.0));\n",
cubeIdx, unPMColor, colorCubeSizeUni, colorCubeInvSizeUni, colorCubeInvSizeUni,
unPMColor, colorCubeSizeUni);
// Compute y coord for for texture fetches.
fragBuilder->codeAppendf("vec2 %s = vec2(%s.r, (floor(%s.b) + %s.g) * %s);\n",
cCoords1, cubeIdx, cubeIdx, cubeIdx, colorCubeInvSizeUni);
fragBuilder->codeAppendf("vec2 %s = vec2(%s.r, (ceil(%s.b) + %s.g) * %s);\n",
cCoords2, cubeIdx, cubeIdx, cubeIdx, colorCubeInvSizeUni);
// Apply the cube.
fragBuilder->codeAppendf("%s = vec4(mix(", args.fOutputColor);
fragBuilder->appendTextureLookup(args.fTexSamplers[0], cCoords1);
fragBuilder->codeAppend(".bgr, ");
fragBuilder->appendTextureLookup(args.fTexSamplers[0], cCoords2);
// Premultiply color by alpha. Note that the input alpha is not modified by this shader.
fragBuilder->codeAppendf(".bgr, fract(%s.b)) * vec3(%s), %s.a);\n",
cubeIdx, nonZeroAlpha, args.fInputColor);
}
void GrColorCubeEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman,
const GrProcessor& proc) {
const GrColorCubeEffect& colorCube = proc.cast<GrColorCubeEffect>();
SkScalar size = SkIntToScalar(colorCube.colorCubeSize());
pdman.set1f(fColorCubeSizeUni, SkScalarToFloat(size));
pdman.set1f(fColorCubeInvSizeUni, SkScalarToFloat(SkScalarInvert(size)));
}
void GrColorCubeEffect::GLSLProcessor::GenKey(const GrProcessor& proc,
const GrGLSLCaps&, GrProcessorKeyBuilder* b) {
}
const GrFragmentProcessor* SkColorCubeFilter::asFragmentProcessor(GrContext* context) const {
static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
GrUniqueKey key;
GrUniqueKey::Builder builder(&key, kDomain, 2);
builder[0] = fUniqueID;
builder[1] = fCache.cubeDimension();
builder.finish();
GrSurfaceDesc desc;
desc.fWidth = fCache.cubeDimension();
desc.fHeight = fCache.cubeDimension() * fCache.cubeDimension();
desc.fConfig = kRGBA_8888_GrPixelConfig;
desc.fIsMipMapped = false;
SkAutoTUnref<GrTexture> textureCube(
context->textureProvider()->findAndRefTextureByUniqueKey(key));
if (!textureCube) {
textureCube.reset(context->textureProvider()->createTexture(
desc, SkBudgeted::kYes, fCubeData->data(), 0));
if (textureCube) {
context->textureProvider()->assignUniqueKeyToTexture(key, textureCube);
} else {
return nullptr;
}
}
return GrColorCubeEffect::Create(textureCube);
}
#endif
| 38.416413
| 99
| 0.662552
|
tmpvar
|
fdfa888bcb63bc22509d43a5a2e44fe9eef792d4
| 2,802
|
cpp
|
C++
|
Codeforces/EDU/Segment Tree/Sum.cpp
|
Code-With-Aagam/competitive-programming
|
610520cc396fb13a03c606b5fb6739cfd68cc444
|
[
"MIT"
] | 2
|
2022-02-08T12:37:41.000Z
|
2022-03-09T03:48:56.000Z
|
Codeforces/EDU/Segment Tree/Sum.cpp
|
ShubhamJagtap2000/competitive-programming-1
|
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
|
[
"MIT"
] | null | null | null |
Codeforces/EDU/Segment Tree/Sum.cpp
|
ShubhamJagtap2000/competitive-programming-1
|
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
|
[
"MIT"
] | null | null | null |
/****************************************************
* Template for coding contests *
* Author : Sanjeev Sharma *
* Email : thedevelopersanjeev@gmail.com *
*****************************************************/
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("fast-math")
#pragma GCC target("sse4")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define deb(x) cout << #x << " is " << x << "\n"
#define int long long
#define mod 1000000007
const double PI = 2 * acos(0.0);
const long long INF = 1e18L + 5;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class... Args>
auto create(size_t n, Args&&... args) {
if constexpr (sizeof...(args) == 1)
return vector(n, args...);
else
return vector(n, create(args...));
}
template <typename... T>
void read(T&... args) {
((cin >> args), ...);
}
template <typename... T>
void write(T&&... args) {
((cout << args), ...);
}
struct segtree {
int size;
vector<int> tree;
void init(int n) {
size = 1;
while (size < n) size *= 2;
tree.assign(2 * size, 0LL);
}
void set(int i, int v, int x, int lx, int rx) {
if (rx - lx == 1) {
tree[x] = v;
return;
}
int mx = lx + (rx - lx) / 2;
if (i < mx) {
set(i, v, 2 * x + 1, lx, mx);
} else {
set(i, v, 2 * x + 2, mx, rx);
}
tree[x] = tree[2 * x + 1] + tree[2 * x + 2];
}
int sum(int l, int r, int x, int lx, int rx) {
if (lx >= r || rx <= l)
return 0;
if (lx >= l && rx <= r)
return tree[x];
int mx = lx + (rx - lx) / 2;
return sum(l, r, 2 * x + 1, lx, mx) + sum(l, r, 2 * x + 2, mx, rx);
}
int sum(int l, int r) {
return sum(l, r, 0, 0, size);
}
void set(int i, int v) {
set(i, v, 0, 0, size);
}
};
void solve() {
int n, m, a, b, c;
read(n, m);
segtree st;
st.init(n);
vector<int> arr(n);
for (int i = 0; i < n; i++) {
read(arr[i]);
st.set(i, arr[i]);
}
while (m--) {
read(a, b, c);
if (a == 1) {
st.set(b, c);
} else {
write(st.sum(b, c), "\n");
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
solve();
return 0;
}
| 23.35
| 96
| 0.47359
|
Code-With-Aagam
|
a9007d06abceb1d5719325ef85ae1ee771867234
| 3,018
|
cpp
|
C++
|
src/PhysicalEntities/Characters/Enemies/Enemy.cpp
|
edusidsan/GameProg-OO
|
c74bedb6c592386a40eefbd61770184994a75aa6
|
[
"MIT"
] | null | null | null |
src/PhysicalEntities/Characters/Enemies/Enemy.cpp
|
edusidsan/GameProg-OO
|
c74bedb6c592386a40eefbd61770184994a75aa6
|
[
"MIT"
] | null | null | null |
src/PhysicalEntities/Characters/Enemies/Enemy.cpp
|
edusidsan/GameProg-OO
|
c74bedb6c592386a40eefbd61770184994a75aa6
|
[
"MIT"
] | null | null | null |
#include "Enemy.hpp"
namespace OgrO // Namespace com o nome do jogo.
{
namespace PhysicalEntities // Namespace do Pacote Entities.
{
namespace Characters // Namespace do Pacote Personagens.
{
namespace Enemies // Namespace do Pacote Enemies.
{
// Construtora da classe Enemy.
Enemy::Enemy(Utilities::gameVector2F pos, Utilities::gameVector2F s, const char *tPath, unsigned int life) : Character(pos, s, tPath, life),
timeReference(0),
projectileInterval(0)
{
}
Enemy::Enemy(nlohmann::json source) : Enemy(Utilities::gameVector2F{static_cast<float>(source["position x"]), static_cast<float>(source["position y"])}, Utilities::gameVector2F{static_cast<float>(source["speed x"]), static_cast<float>(source["speed y"])}, "", static_cast<unsigned int>(source["life"]))
{
}
// Destrutora da classe Enemy.
Enemy::~Enemy()
{
}
// Método carrega a textura do enemy na window e inicializa gerenciadores do mesmo.
void Enemy::initialize()
{
// Carrega textura no player.
pGraphicManager->loadAsset(texturePath);
// Retorna dimensão da imagem.
dimension = pGraphicManager->getDimensionsOfAsset(texturePath);
// Adiciona enemy na lista de entidades físicas colidiveis.
pCollisionManager->addToLCollidablesPhysicalEntities((this));
}
void Enemy::update(float t)
{
}
// Método verifica colisão entre dois objetos da classe Entidade Física.
void Enemy::collided(int idOther, Utilities::gameVector2F positionOther, Utilities::gameVector2F dimensionOther)
{
// Caso colida com Enemy.
if ((idOther == 102) || (idOther == 103))
{
// Cálculo da distância entre os enemy no momento da colisão.
Utilities::gameVector2F distance = position - positionOther;
// Medida para não manter um enemy preso dentro do outro.
position += distance * (1 / 2);
// std::cout << "OBJETO ENEMY >>> COLISAO COM OBJETO ENEMY." << std::endl;
// Muda o sentido da velocidade em x.
speed.coordX *= -1;
// Muda o sentido da velocidade em y.
speed.coordY *= -1;
}
}
}
}
}
}
| 51.152542
| 318
| 0.474818
|
edusidsan
|
a902cfee6f0885ca8c4c5a44f5d5425588582219
| 757
|
hpp
|
C++
|
src/roq/samples/zeromq/strategy.hpp
|
roq-trading/roq-examples
|
7b7d9508b624c7ec6d74e2fd0206796cf934263b
|
[
"BSD-3-Clause"
] | null | null | null |
src/roq/samples/zeromq/strategy.hpp
|
roq-trading/roq-examples
|
7b7d9508b624c7ec6d74e2fd0206796cf934263b
|
[
"BSD-3-Clause"
] | null | null | null |
src/roq/samples/zeromq/strategy.hpp
|
roq-trading/roq-examples
|
7b7d9508b624c7ec6d74e2fd0206796cf934263b
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2017-2022, Hans Erik Thrane */
#pragma once
#include <arpa/inet.h>
#include "roq/api.hpp"
#include "roq/client.hpp"
// note! thin wrappers around libzmq
#include "roq/samples/zeromq/zmq/context.hpp"
#include "roq/samples/zeromq/zmq/socket.hpp"
namespace roq {
namespace samples {
namespace zeromq {
// strategy implementation
class Strategy final : public client::Handler {
public:
explicit Strategy(client::Dispatcher &);
Strategy(Strategy &&) = default;
Strategy(const Strategy &) = delete;
protected:
void operator()(const Event<TopOfBook> &) override;
private:
client::Dispatcher &dispatcher_;
zmq::Context context_;
zmq::Socket socket_;
};
} // namespace zeromq
} // namespace samples
} // namespace roq
| 19.410256
| 53
| 0.714663
|
roq-trading
|
a9045f9e0fb0defe3869a05acf4a63b3bf08a65f
| 1,860
|
cpp
|
C++
|
test/training_data/plag_original_codes/dp_h_6221550_808_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | 13
|
2021-01-20T19:53:16.000Z
|
2021-11-14T16:30:32.000Z
|
test/training_data/plag_original_codes/dp_h_6221550_808_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | null | null | null |
test/training_data/plag_original_codes/dp_h_6221550_808_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | null | null | null |
/*
引用元:https://atcoder.jp/contests/dp/tasks/dp_h
H - Grid 1Editorial
// ソースコードの引用元 : https://atcoder.jp/contests/dp/submissions/6221550
// 提出ID : 6221550
// 問題ID : dp_h
// コンテストID : dp
// ユーザID : xryuseix
// コード長 : 2238
// 実行時間 : 19
*/
#include <algorithm>
#include <bitset>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<ll> vi;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pair<ll, ll>> vpii;
typedef vector<vector<ll>> vvi;
typedef vector<vector<char>> vvc;
typedef vector<vector<string>> vvs;
#define rep(i, n) for (ll i = 0; i < (n); ++i)
#define rrep(i, n) for (ll i = 1; i <= (n); ++i)
#define drep(i, n) for (ll i = (n)-1; i >= 0; --i)
#define fin(ans) cout << (ans) << endl
#define P 1000000007
int main(void) {
ll h, w;
cin >> h >> w;
char grid[h][w];
ll path[h][w];
rep(i, h) rep(j, w) cin >> grid[i][j];
for (ll i = 0; i < h; i++) {
for (ll j = 0; j < w; j++) {
path[i][j] = 0;
}
}
for (ll i = 0; i < w; i++) {
if (grid[0][i] == '.')
path[0][i] = 1;
else
break;
}
for (ll i = 0; i < h; i++) {
if (grid[i][0] == '.')
path[i][0] = 1;
else
break;
}
for (ll i = 1; i < h; i++) {
for (ll j = 1; j < w; j++) {
if (grid[i][j] == '#')
path[i][j] = 0;
else {
path[i][j] = max(path[i][j], path[i - 1][j] + path[i][j - 1]);
path[i][j] %= P;
}
}
}
cout << path[h - 1][w - 1] << endl;
}
| 22.682927
| 78
| 0.499462
|
xryuseix
|
a907ac64e0a1b8f272e75afa3d08dc5eeb0f4f42
| 1,903
|
cc
|
C++
|
nn/simplenet/main/Simplenet.cc
|
research-note/Many-as-One
|
eb9520c30b4b2b944d4f3713aada256feaf322bc
|
[
"Apache-2.0"
] | null | null | null |
nn/simplenet/main/Simplenet.cc
|
research-note/Many-as-One
|
eb9520c30b4b2b944d4f3713aada256feaf322bc
|
[
"Apache-2.0"
] | 4
|
2021-11-13T23:49:46.000Z
|
2021-12-03T03:09:44.000Z
|
nn/simplenet/main/Simplenet.cc
|
research-note/Many-as-One
|
eb9520c30b4b2b944d4f3713aada256feaf322bc
|
[
"Apache-2.0"
] | 2
|
2021-11-13T03:45:19.000Z
|
2021-11-13T03:47:42.000Z
|
/* Copyright 2021 The Many as One 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 <stdexcept>
#include <utility>
#include <random>
template <typename T>
Simplenet<T>::Simplenet(size_t width, size_t height)
: mWidth(width)
, mHeight(height)
{
mCells.resize(mWidth);
for (auto& column : mCells) {
column.resize(mHeight);
}
}
template <typename T>
void randomize()
{
random_device seeder;
const auto seed = seeder.entropy() ? seeder() : time(nullptr);
mt19937 eng(static_cast<mt19937::result_type>(seed));
normal_distribution<T> dist(0.0, 1.0);
auto gen = bind(dist, eng);
// for (auto& column : mCells) {
// for (auto& row : column) {
// row = gen();
// std::cout << ' ' << row << std::end;
// }
// std::cout << std::end;
// }
}
template <typename T>
void Simplenet<T>::verifyCoordinate(size_t x, size_t y) const
{
if (x >= mWidth || y >= mHeight) {
throw std::out_of_range("");
}
}
template <typename T>
const std::optional<T>& Simplenet<T>::at(size_t x, size_t y) const
{
verifyCoordinate(x, y);
return mCells[x][y];
}
template <typename T>
std::optional<T>& Simplenet<T>::at(size_t x, size_t y)
{
return const_cast<std::optional<T>&>(std::as_const(*this).at(x, y));
}
| 28.402985
| 80
| 0.630583
|
research-note
|
a90a2e236f493055edc524d068f061a3d88f074c
| 581
|
cpp
|
C++
|
rotate-image.cpp
|
5ooo/LeetCode
|
5f250cd38696f581e5c891b8977f6c27eea26ffa
|
[
"MIT"
] | null | null | null |
rotate-image.cpp
|
5ooo/LeetCode
|
5f250cd38696f581e5c891b8977f6c27eea26ffa
|
[
"MIT"
] | null | null | null |
rotate-image.cpp
|
5ooo/LeetCode
|
5f250cd38696f581e5c891b8977f6c27eea26ffa
|
[
"MIT"
] | null | null | null |
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n / 2; i++)
{
for (int j = i; j < n - i - 1; j++)
{
//A[i][j] -> A[j][n-1-i] -> A[n-1-i][n-1-j] -> A[n-1-j][i] -> A[i][j]
int temp = matrix[j][n-i-1];
matrix[j][n-i-1] = matrix[i][j];
matrix[i][j] = matrix[n-j-1][i];
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1] = temp;
}
}
}
};
| 27.666667
| 85
| 0.349398
|
5ooo
|
a90c0ad639940bfe3953ad0683c03bebad2f0616
| 11,888
|
cpp
|
C++
|
source/model/Model.cpp
|
sormo/simpleSDL
|
79a830a013f911c4670c86ccf68bd068a887670d
|
[
"MIT"
] | null | null | null |
source/model/Model.cpp
|
sormo/simpleSDL
|
79a830a013f911c4670c86ccf68bd068a887670d
|
[
"MIT"
] | null | null | null |
source/model/Model.cpp
|
sormo/simpleSDL
|
79a830a013f911c4670c86ccf68bd068a887670d
|
[
"MIT"
] | null | null | null |
#include "Model.h"
#include "OpenGL.h"
#include "model_generated.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "utils/Texture.h"
#include "utils/Shader.h"
#include "Common.h"
#include "CommonProject.h"
#include "TextureManager.h"
glm::mat4 Convert(const ModelData::Mat4 & m)
{
return glm::mat4{
{ m.a1(), m.b1(), m.c1(), m.d1() },
{ m.a2(), m.b2(), m.c2(), m.d2() },
{ m.a3(), m.b3(), m.c3(), m.d3() },
{ m.a4(), m.b4(), m.c4(), m.d4() }
};
}
Mesh::Mesh(const ModelData::MeshT & mesh, std::vector<std::unique_ptr<ModelMaterial>> & materials)
{
uint32_t materialIndex = mesh.material;
if (materialIndex >= materials.size())
{
printf("Error loading model, mesh has invalid material index (%d)", materialIndex);
throw std::runtime_error("Error loading model.");
}
m_material = materials[materialIndex].get();
InitBuffers(mesh.positions, mesh.normals, mesh.texCoords, mesh.tangents, mesh.bitangents, mesh.indices);
}
Mesh::~Mesh()
{
glDeleteBuffers(1, &m_positions);
glDeleteBuffers(1, &m_vboIndices);
glDeleteBuffers(1, &m_normals);
if (m_material->shader->GetConfig().GetUVChannelsCount())
glDeleteBuffers(m_texCoords.size(), m_texCoords.data());
if (m_material->shader->GetConfig().textures.normal.size())
{
glDeleteBuffers(1, &m_tangents);
glDeleteBuffers(1, &m_bitangents);
}
if (IsVAOSupported())
glDeleteVertexArrays(1, &m_vao);
}
void Mesh::BindUniforms(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection)
{
glm::mat4 MVP = projection * view * model;
m_material->shader->GetShader().SetUniform(MVP, "MVP");
m_material->shader->GetShader().SetUniform(model, "M");
}
void Mesh::BindBuffers()
{
if (IsVAOSupported())
{
m_material->shader->GetShader().BindVAO(m_vao);
}
else
{
m_material->shader->GetShader().BindBuffer<glm::vec3>(m_positions, m_material->shader->GetLocations().buffers.positions);
m_material->shader->GetShader().BindBuffer<glm::vec3>(m_normals, m_material->shader->GetLocations().buffers.normals);
for (uint32_t i = 0; i < m_material->shader->GetConfig().GetUVChannelsCount(); ++i)
m_material->shader->GetShader().BindBuffer<glm::vec2>(m_texCoords[i], m_material->shader->GetLocations().buffers.texCoords[i]);
if (m_material->shader->GetConfig().textures.normal.size())
{
m_material->shader->GetShader().BindBuffer<glm::vec3>(m_tangents, m_material->shader->GetLocations().buffers.tangents);
//m_material->shader->GetShader().BindBuffer<glm::vec3>(m_bitangents, m_shader->GetLocations().buffers.bitangents);
}
}
// TODO can be bound to VAO ???
m_material->shader->GetShader().BindElementBuffer(m_vboIndices);
}
// render the mesh
void Mesh::Draw(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection)
{
m_material->shader->BeginRender();
m_material->shader->BindTransform(model, view, projection);
m_material->shader->BindTextures(m_material->textures);
BindBuffers();
glDrawElements(GL_TRIANGLES, m_verticesCount, GL_UNSIGNED_SHORT, (void*)0);
CheckGlError("glDrawElements");
m_material->shader->EndRender();
}
template<class T, uint32_t N>
GLuint CreateFloatVBO(GLuint index, const T * data, size_t size, bool isVaoBinded)
{
GLuint vbo;
glGenBuffers(1, &vbo);
CheckGlError("glGenBuffers");
glBindBuffer(GL_ARRAY_BUFFER, vbo);
CheckGlError("glBindBuffer");
glBufferData(GL_ARRAY_BUFFER, size*sizeof(T), data, GL_STATIC_DRAW);
CheckGlError("glBufferData");
if (isVaoBinded)
{
glEnableVertexAttribArray(index);
CheckGlError("glEnableVertexAttribArray");
glVertexAttribPointer(index, N, GL_FLOAT, GL_FALSE, 0, nullptr);
CheckGlError("glVertexAttribPointer");
}
return vbo;
}
template<class T, uint32_t N>
GLuint CreateFloatVBO(GLuint index, const std::vector<T> & data, bool isVaoBinded)
{
return CreateFloatVBO<T, N>(index, &data[0], data.size(), isVaoBinded);
}
void Mesh::InitBuffers(const std::vector<ModelData::Vec3> & positions,
const std::vector<ModelData::Vec3> & normals,
const std::vector<ModelData::Vec2> & texCoords,
const std::vector<ModelData::Vec3> & tangents,
const std::vector<ModelData::Vec3> & bitangents,
const std::vector<uint16_t> & indices)
{
bool bindVAO = IsVAOSupported();
// prepare and bind VAO if possible
if (bindVAO)
{
glGenVertexArrays(1, &m_vao);
CheckGlError("glGenVertexArrays");
glBindVertexArray(m_vao);
CheckGlError("glBindVertexArray");
}
m_positions = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("positionModelSpace", Shader::LocationType::Attrib), positions, bindVAO);
m_normals = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("normalModelSpace", Shader::LocationType::Attrib), normals, bindVAO);
if (m_material->shader->GetConfig().textures.normal.size())
{
m_tangents = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("tangentModelSpace", Shader::LocationType::Attrib), tangents, bindVAO);
//m_bitangents = CreateFloatVBO<ModelData::Vec3, 3>(m_shader->GetShader().GetLocation("bitangentModelSpace", Shader::LocationType::Attrib), bitangents, bindVAO);
}
for (uint32_t i = 0; i < m_material->shader->GetConfig().GetUVChannelsCount(); ++i)
{
m_texCoords.push_back(CreateFloatVBO<ModelData::Vec2, 2>(m_material->shader->GetShader().GetLocation("vertexUV" + std::to_string(i), Shader::LocationType::Attrib),
&texCoords[i * positions.size()], positions.size(), bindVAO));
}
glBindVertexArray(0);
// TODO can be element buffer binded to vao ???
glGenBuffers(1, &m_vboIndices);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_vboIndices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(uint16_t), &indices[0], GL_STATIC_DRAW);
m_verticesCount = indices.size();
}
ModelShader::TextureStackEntry::Operation Convert(ModelData::TextureOperation operation)
{
switch (operation)
{
case ModelData::TextureOperation_Add:
return ModelShader::TextureStackEntry::Operation::Add;
case ModelData::TextureOperation_Multiply:
return ModelShader::TextureStackEntry::Operation::Multiply;
case ModelData::TextureOperation_Substract:
return ModelShader::TextureStackEntry::Operation::Substract;
case ModelData::TextureOperation_Divide:
return ModelShader::TextureStackEntry::Operation::Divide;
case ModelData::TextureOperation_SmoothAdd:
return ModelShader::TextureStackEntry::Operation::SmoothAdd;
case ModelData::TextureOperation_SignedAdd:
return ModelShader::TextureStackEntry::Operation::SignedAdd;
}
return ModelShader::TextureStackEntry::Operation::Add;
}
bool ProcessTextures(const std::string & root, std::vector<std::unique_ptr<ModelData::TextureT>> & data, std::vector<ModelShader::TextureStackEntry> & stack, std::vector<GLuint> & textures)
{
for (size_t i = 0; i < data.size(); ++i)
{
ModelShader::TextureStackEntry entry;
entry.factor = data[i]->blendFactor;
entry.operation = Convert(data[i]->operation);
entry.uvIndex = data[i]->uvIndex;
auto texture = TextureManager::Instance().GetTexture((root + data[i]->path).c_str());
if (!texture)
{
printf("Error loading texture %s", (root + data[i]->path).c_str());
return false;
}
textures.push_back(*texture);
stack.push_back(entry);
}
return true;
}
std::unique_ptr<ModelMaterial> Model::CreateMaterial(const std::string & root, ModelData::MaterialT & material)
{
ModelShader::Config config;
std::unique_ptr<ModelMaterial> result = std::make_unique<ModelMaterial>();
config.light = m_configLight;
memset(&config.material, 0, sizeof(config.material));
if (material.ambient)
config.material.ambient = Convert(*material.ambient);
if (material.diffuse)
config.material.diffuse = Convert(*material.diffuse);
if (material.specular)
config.material.specular = Convert(*material.specular);
config.material.shininess = material.shininess;
config.material.shininessStrength = material.shininessStrength;
if (!ProcessTextures(root, material.textureAmbient, config.textures.ambient, result->textures.ambient))
return nullptr;
if (!ProcessTextures(root, material.textureDiffuse, config.textures.diffuse, result->textures.diffuse))
return nullptr;
if (!ProcessTextures(root, material.textureSpecular, config.textures.specular, result->textures.specular))
return nullptr;
if (!ProcessTextures(root, material.textureNormal, config.textures.normal, result->textures.normal))
return nullptr;
if (!ProcessTextures(root, material.textureLightmap, config.textures.lightmap, result->textures.lightmap))
return nullptr;
config.shading = ModelShader::ShadingModel::BlinnPhong;
result->shader = std::make_unique<ModelShader>(config);
if (!result->shader.get())
return nullptr;
return result;
}
Model::Model(const char * path, Light::Config light)
: m_configLight(light)
{
auto data = Common::ReadFile(path);
auto model = ModelData::UnPackModel(data.data());
auto root = Common::GetDirectoryFromFilePath(path);
// process materials
ProcessMaterials(model.get(), root);
// process meshes
ProcessMeshes(model.get());
// recursively process tree
m_tree = ProcessTree(*model->tree);
}
Model::~Model()
{
// clear meshes before materials
m_meshes.clear();
}
void Model::ProcessMaterials(ModelData::ModelT * model, const std::string & root)
{
for (size_t i = 0; i < model->materials.size(); ++i)
{
auto material = CreateMaterial(root, *model->materials[i].get());
if (!material)
{
printf("Error creating material.");
throw std::runtime_error("Error creating material.");
}
m_materials.push_back(std::move(material));
}
}
void Model::ProcessMeshes(ModelData::ModelT * model)
{
for (size_t i = 0; i < model->meshes.size(); ++i)
{
// TODO check is mesh constructed successfully
m_meshes.push_back(std::make_unique<Mesh>(*model->meshes[i].get(), m_materials));
}
}
Model::Tree Model::ProcessTree(ModelData::TreeT & node)
{
Model::Tree result;
result.transform = Convert(*node.transform);
result.meshes = node.meshes;
for (auto & child : node.childs)
result.childs.push_back(ProcessTree(*child));
return result;
}
void Model::Bind(const Data & data)
{
for (auto & material : m_materials)
{
material->shader->BeginRender();
material->shader->BindCamera(data.cameraWorldSpace);
material->shader->BindLight(data.light);
material->shader->BindMaterial(data.material);
material->shader->EndRender();
}
}
void Model::Draw(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection)
{
DrawInternal(m_tree, model, view, projection);
}
void Model::DrawInternal(Tree & tree, const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection)
{
glm::mat4 nodeModel = model * tree.transform;
//glm::mat4 nodeModel = model;
for (uint32_t i : tree.meshes)
m_meshes[i]->Draw(nodeModel, view, projection);
for (Tree & child : tree.childs)
DrawInternal(child, nodeModel, view, projection);
}
| 33.965714
| 189
| 0.672527
|
sormo
|
a90f9d7637d0ef9210d781ad9adf49453fa08067
| 317
|
hpp
|
C++
|
include/RED4ext/Scripting/Natives/Generated/game/CityAreaType.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 42
|
2020-12-25T08:33:00.000Z
|
2022-03-22T14:47:07.000Z
|
include/RED4ext/Scripting/Natives/Generated/game/CityAreaType.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 38
|
2020-12-28T22:36:06.000Z
|
2022-02-16T11:25:47.000Z
|
include/RED4ext/Scripting/Natives/Generated/game/CityAreaType.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 20
|
2020-12-28T22:17:38.000Z
|
2022-03-22T17:19:01.000Z
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace game {
enum class CityAreaType : uint32_t
{
Undefined = 0,
PublicZone = 1,
SafeZone = 2,
RestrictedZone = 3,
DangerousZone = 4,
};
} // namespace game
} // namespace RED4ext
| 16.684211
| 57
| 0.678233
|
jackhumbert
|
a911e7c5a1bfe9267b42dd3ca297bf4fd789b61b
| 2,662
|
hpp
|
C++
|
src/main/include/communications/PublishNode.hpp
|
MattSa952073/PubSubLub
|
a20bd82d72f3d5a1599234d638afd578259f3553
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/include/communications/PublishNode.hpp
|
MattSa952073/PubSubLub
|
a20bd82d72f3d5a1599234d638afd578259f3553
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/include/communications/PublishNode.hpp
|
MattSa952073/PubSubLub
|
a20bd82d72f3d5a1599234d638afd578259f3553
|
[
"BSD-2-Clause"
] | null | null | null |
// Copyright (c) 2018-2019 FRC Team 3512. All Rights Reserved.
#pragma once
#include <atomic>
#include <condition_variable>
#include <string>
#include <thread>
#include <vector>
#include <frc/circular_buffer.h>
#include "communications/PublishNodeBase.hpp"
namespace frc3512 {
/**
* A communication layer that can pass messages between others who have
* inherited it through a publish-subscribe architecture
*/
class PublishNode : public PublishNodeBase {
public:
/**
* Construct a PublishNode.
*
* @param nodeName Name of node.
*/
explicit PublishNode(std::string nodeName = "Misc");
virtual ~PublishNode();
/**
* Adds this object to the specified PublishNode's subscriber list.
*
* @param publisher The PublishNode that this instance wants to recieve
* event from.
*/
void Subscribe(PublishNode& publisher);
/**
* Removes this object from the specified PublishNode's subscriber list.
*
* @param publisher The PublishNode that this instance wants to stop
* recieving event from.
*/
void Unsubscribe(PublishNode& publisher);
/**
* Get the button value (starting at button 1).
*
* The buttons are returned in a single 16 bit value with one bit
* representing the state of each button. The appropriate button is returned
* as a boolean value.
*
* @param message The message whose member variables contain deserialized
* data.
* @param joystick The joystick number.
* @param button The button number to be read (starting at 1).
* @return The state of the button.
*/
static bool GetRawButton(const HIDPacket& msg, int joystick, int button);
/**
* Sends a packet to every subscriber.
*
* @param p Any packet with a Serialize() method.
*/
template <class P>
void Publish(P p);
/**
* Sends a packet to the object it's called on.
*
* @param p Any packet with a Serialize() method.
*/
template <class P>
void PushMessage(P p);
private:
static constexpr int kNodeQueueSize = 1024;
std::string m_nodeName;
std::vector<PublishNode*> m_subList;
frc::circular_buffer<char> m_queue{kNodeQueueSize};
std::thread m_thread;
std::atomic<bool> m_isRunning{true};
std::condition_variable m_ready;
/**
* Blocks the thread until the queue receives at least one set of characters
* of a message or until the node deconstructs, then processes each message.
*/
void RunFramework();
};
} // namespace frc3512
#include "PublishNode.inc"
| 26.888889
| 80
| 0.654395
|
MattSa952073
|
a91368140c5cc9f9ac4178c80b0985b4212cf130
| 29,900
|
cpp
|
C++
|
src/armnn/Runtime.cpp
|
Srivathsav-max/armnn-clone
|
af2daa6526623c91ee97f7141be4d1b07de92a48
|
[
"MIT"
] | 1
|
2022-03-31T18:21:59.000Z
|
2022-03-31T18:21:59.000Z
|
src/armnn/Runtime.cpp
|
Elm8116/armnn
|
e571cde8411803aec545b1070ed677e481f46f3f
|
[
"MIT"
] | null | null | null |
src/armnn/Runtime.cpp
|
Elm8116/armnn
|
e571cde8411803aec545b1070ed677e481f46f3f
|
[
"MIT"
] | null | null | null |
//
// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "Runtime.hpp"
#include <armnn/Version.hpp>
#include <armnn/BackendRegistry.hpp>
#include <armnn/BackendHelper.hpp>
#include <armnn/Logging.hpp>
#include <armnn/utility/Timer.hpp>
#include <armnn/backends/IBackendContext.hpp>
#include <backendsCommon/DynamicBackendUtils.hpp>
#include <backendsCommon/memoryOptimizerStrategyLibrary/MemoryOptimizerStrategyLibrary.hpp>
#include <armnn/utility/PolymorphicDowncast.hpp>
#include <common/include/LabelsAndEventClasses.hpp>
#include <iostream>
#include <backends/BackendProfiling.hpp>
using namespace armnn;
using namespace std;
namespace armnn
{
IRuntime::IRuntime() : pRuntimeImpl( new RuntimeImpl(armnn::IRuntime::CreationOptions())) {}
IRuntime::IRuntime(const IRuntime::CreationOptions& options) : pRuntimeImpl(new RuntimeImpl(options)) {}
IRuntime::~IRuntime() = default;
IRuntime* IRuntime::CreateRaw(const CreationOptions& options)
{
return new IRuntime(options);
}
IRuntimePtr IRuntime::Create(const CreationOptions& options)
{
return IRuntimePtr(CreateRaw(options), &IRuntime::Destroy);
}
void IRuntime::Destroy(IRuntime* runtime)
{
delete runtime;
}
Status IRuntime::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr network)
{
return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network));
}
Status IRuntime::LoadNetwork(NetworkId& networkIdOut,
IOptimizedNetworkPtr network,
std::string& errorMessage)
{
return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network), errorMessage);
}
Status IRuntime::LoadNetwork(NetworkId& networkIdOut,
IOptimizedNetworkPtr network,
std::string& errorMessage,
const INetworkProperties& networkProperties)
{
return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network), errorMessage, networkProperties);
}
armnn::TensorInfo IRuntime::GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const
{
return pRuntimeImpl->GetInputTensorInfo(networkId, layerId);
}
armnn::TensorInfo IRuntime::GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const
{
return pRuntimeImpl->GetOutputTensorInfo(networkId, layerId);
}
std::vector<ImportedInputId> IRuntime::ImportInputs(NetworkId networkId, const InputTensors& inputTensors,
MemorySource forceImportMemorySource)
{
return pRuntimeImpl->ImportInputs(networkId, inputTensors, forceImportMemorySource);
}
std::vector<ImportedOutputId> IRuntime::ImportOutputs(NetworkId networkId, const OutputTensors& outputTensors,
MemorySource forceImportMemorySource)
{
return pRuntimeImpl->ImportOutputs(networkId, outputTensors, forceImportMemorySource);
}
void IRuntime::ClearImportedInputs(NetworkId networkId, const std::vector<ImportedInputId> inputIds)
{
return pRuntimeImpl->ClearImportedInputs(networkId, inputIds);
}
void IRuntime::ClearImportedOutputs(NetworkId networkId, const std::vector<ImportedOutputId> outputIds)
{
return pRuntimeImpl->ClearImportedOutputs(networkId, outputIds);
}
Status IRuntime::EnqueueWorkload(NetworkId networkId,
const InputTensors& inputTensors,
const OutputTensors& outputTensors,
std::vector<ImportedInputId> preImportedInputIds,
std::vector<ImportedOutputId> preImportedOutputIds)
{
return pRuntimeImpl->EnqueueWorkload(networkId, inputTensors, outputTensors,
preImportedInputIds, preImportedOutputIds);
}
Status IRuntime::Execute(IWorkingMemHandle& workingMemHandle,
const InputTensors& inputTensors,
const OutputTensors& outputTensors,
std::vector<ImportedInputId> preImportedInputs,
std::vector<ImportedOutputId> preImportedOutputs)
{
return pRuntimeImpl->Execute(workingMemHandle, inputTensors, outputTensors, preImportedInputs, preImportedOutputs);
}
Status IRuntime::UnloadNetwork(NetworkId networkId)
{
return pRuntimeImpl->UnloadNetwork(networkId);
}
const IDeviceSpec& IRuntime::GetDeviceSpec() const
{
return pRuntimeImpl->GetDeviceSpec();
}
std::unique_ptr<IWorkingMemHandle> IRuntime::CreateWorkingMemHandle(NetworkId networkId)
{
return pRuntimeImpl->CreateWorkingMemHandle(networkId);
}
const std::shared_ptr<IProfiler> IRuntime::GetProfiler(NetworkId networkId) const
{
return pRuntimeImpl->GetProfiler(networkId);
}
void IRuntime::RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction& func)
{
return pRuntimeImpl->RegisterDebugCallback(networkId, func);
}
int RuntimeImpl::GenerateNetworkId()
{
return m_NetworkIdCounter++;
}
Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr inNetwork)
{
std::string ignoredErrorMessage;
return LoadNetwork(networkIdOut, std::move(inNetwork), ignoredErrorMessage);
}
Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut,
IOptimizedNetworkPtr inNetwork,
std::string& errorMessage)
{
INetworkProperties networkProperties(
false, MemorySource::Undefined, MemorySource::Undefined);
return LoadNetwork(networkIdOut, std::move(inNetwork), errorMessage, networkProperties);
}
Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut,
IOptimizedNetworkPtr inNetwork,
std::string& errorMessage,
const INetworkProperties& networkProperties)
{
// Register the profiler
auto profiler = inNetwork->GetProfiler();
ProfilerManager::GetInstance().RegisterProfiler(profiler.get());
IOptimizedNetwork* rawNetwork = inNetwork.release();
networkIdOut = GenerateNetworkId();
for (auto&& context : m_BackendContexts)
{
context.second->BeforeLoadNetwork(networkIdOut);
}
unique_ptr<LoadedNetwork> loadedNetwork = LoadedNetwork::MakeLoadedNetwork(
std::unique_ptr<IOptimizedNetwork>(rawNetwork),
errorMessage,
networkProperties,
m_ProfilingService);
if (!loadedNetwork)
{
return Status::Failure;
}
{
std::lock_guard<std::mutex> lockGuard(m_Mutex);
// Stores the network
m_LoadedNetworks[networkIdOut] = std::move(loadedNetwork);
}
for (auto&& context : m_BackendContexts)
{
context.second->AfterLoadNetwork(networkIdOut);
}
if (m_ProfilingService.IsProfilingEnabled())
{
m_ProfilingService.IncrementCounterValue(armnn::profiling::NETWORK_LOADS);
}
return Status::Success;
}
Status RuntimeImpl::UnloadNetwork(NetworkId networkId)
{
bool unloadOk = true;
for (auto&& context : m_BackendContexts)
{
unloadOk &= context.second->BeforeUnloadNetwork(networkId);
}
if (!unloadOk)
{
ARMNN_LOG(warning) << "RuntimeImpl::UnloadNetwork(): failed to unload "
"network with ID:" << networkId << " because BeforeUnloadNetwork failed";
return Status::Failure;
}
std::unique_ptr<profiling::TimelineUtilityMethods> timelineUtils =
profiling::TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService);
{
std::lock_guard<std::mutex> lockGuard(m_Mutex);
// If timeline recording is on mark the Network end of life
if (timelineUtils)
{
auto search = m_LoadedNetworks.find(networkId);
if (search != m_LoadedNetworks.end())
{
profiling::ProfilingGuid networkGuid = search->second->GetNetworkGuid();
timelineUtils->RecordEvent(networkGuid,
profiling::LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS);
}
}
if (m_LoadedNetworks.erase(networkId) == 0)
{
ARMNN_LOG(warning) << "WARNING: RuntimeImpl::UnloadNetwork(): " << networkId << " not found!";
return Status::Failure;
}
if (m_ProfilingService.IsProfilingEnabled())
{
m_ProfilingService.IncrementCounterValue(armnn::profiling::NETWORK_UNLOADS);
}
}
for (auto&& context : m_BackendContexts)
{
context.second->AfterUnloadNetwork(networkId);
}
// Unregister the profiler
ProfilerManager::GetInstance().RegisterProfiler(nullptr);
ARMNN_LOG(debug) << "RuntimeImpl::UnloadNetwork(): Unloaded network with ID: " << networkId;
return Status::Success;
}
const std::shared_ptr<IProfiler> RuntimeImpl::GetProfiler(NetworkId networkId) const
{
auto it = m_LoadedNetworks.find(networkId);
if (it != m_LoadedNetworks.end())
{
auto& loadedNetwork = it->second;
return loadedNetwork->GetProfiler();
}
return nullptr;
}
void RuntimeImpl::ReportStructure() // armnn::profiling::IProfilingService& profilingService as param
{
// No-op for the time being, but this may be useful in future to have the profilingService available
// if (profilingService.IsProfilingEnabled()){}
LoadedNetworks::iterator it = m_LoadedNetworks.begin();
while (it != m_LoadedNetworks.end())
{
auto& loadedNetwork = it->second;
loadedNetwork->SendNetworkStructure();
// Increment the Iterator to point to next entry
it++;
}
}
RuntimeImpl::RuntimeImpl(const IRuntime::CreationOptions& options)
: m_NetworkIdCounter(0),
m_ProfilingService(*this)
{
const auto start_time = armnn::GetTimeNow();
ARMNN_LOG(info) << "ArmNN v" << ARMNN_VERSION;
if ( options.m_ProfilingOptions.m_TimelineEnabled && !options.m_ProfilingOptions.m_EnableProfiling )
{
throw RuntimeException(
"It is not possible to enable timeline reporting without profiling being enabled");
}
// Load any available/compatible dynamic backend before the runtime
// goes through the backend registry
LoadDynamicBackends(options.m_DynamicBackendsPath);
BackendIdSet supportedBackends;
for (const auto& id : BackendRegistryInstance().GetBackendIds())
{
// Store backend contexts for the supported ones
try {
auto factoryFun = BackendRegistryInstance().GetFactory(id);
ARMNN_ASSERT(factoryFun != nullptr);
auto backend = factoryFun();
ARMNN_ASSERT(backend != nullptr);
ARMNN_ASSERT(backend.get() != nullptr);
auto customAllocatorMapIterator = options.m_CustomAllocatorMap.find(id);
if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end() &&
customAllocatorMapIterator->second == nullptr)
{
// We need to manually clean up the dynamic backends before throwing an exception.
DynamicBackendUtils::DeregisterDynamicBackends(m_DeviceSpec.GetDynamicBackends());
m_DeviceSpec.ClearDynamicBackends();
throw armnn::Exception("Allocator associated with id " + id.Get() + " is null");
}
// If the runtime is created in protected mode only add backends that support this mode
if (options.m_ProtectedMode)
{
// check if backend supports ProtectedMode
using BackendCapability = BackendOptions::BackendOption;
BackendCapability protectedContentCapability {"ProtectedContentAllocation", true};
if (!HasCapability(protectedContentCapability, id))
{
// Protected Content Allocation is not supported by the backend
// backend should not be registered
ARMNN_LOG(warning) << "Backend "
<< id
<< " is not registered as does not support protected content allocation.";
continue;
}
// The user is responsible to provide a custom memory allocator which allows to allocate
// protected memory
if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end())
{
std::string err;
if (customAllocatorMapIterator->second->GetMemorySourceType()
== armnn::MemorySource::DmaBufProtected)
{
if (!backend->UseCustomMemoryAllocator(customAllocatorMapIterator->second, err))
{
ARMNN_LOG(error) << "The backend "
<< id
<< " reported an error when entering protected mode. Backend won't be"
<< " used. ErrorMsg: " << err;
continue;
}
// No errors so register the Custom Allocator with the BackendRegistry
BackendRegistryInstance().RegisterAllocator(id, customAllocatorMapIterator->second);
}
else
{
ARMNN_LOG(error) << "The CustomAllocator provided with the runtime options doesn't support "
"protected memory. Protected mode can't be activated. The backend "
<< id
<< " is not going to be used. MemorySource must be MemorySource::DmaBufProtected";
continue;
}
}
else
{
ARMNN_LOG(error) << "Protected mode can't be activated for backend: "
<< id
<< " no custom allocator was provided to the runtime options.";
continue;
}
}
else
{
// If a custom memory allocator is provided make the backend use that instead of the default
if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end())
{
std::string err;
if (!backend->UseCustomMemoryAllocator(customAllocatorMapIterator->second, err))
{
ARMNN_LOG(error) << "The backend "
<< id
<< " reported an error when trying to use the provided custom allocator."
" Backend won't be used."
<< " ErrorMsg: " << err;
continue;
}
// No errors so register the Custom Allocator with the BackendRegistry
BackendRegistryInstance().RegisterAllocator(id, customAllocatorMapIterator->second);
}
}
// check if custom memory optimizer strategy map is set
if (!options.m_MemoryOptimizerStrategyMap.empty())
{
auto customMemoryOptimizerStrategyMapIterator = options.m_MemoryOptimizerStrategyMap.find(id);
// if a memory optimizer strategy is provided make the backend use that instead of the default
if (customMemoryOptimizerStrategyMapIterator != options.m_MemoryOptimizerStrategyMap.end())
{
// no errors.. register the memory optimizer strategy with the BackendRegistry
BackendRegistryInstance().RegisterMemoryOptimizerStrategy(
id, customMemoryOptimizerStrategyMapIterator->second);
ARMNN_LOG(info) << "MemoryOptimizerStrategy "
<< customMemoryOptimizerStrategyMapIterator->second->GetName()
<< " set for the backend " << id << ".";
}
}
else
{
// check if to use one of the existing memory optimizer strategies is set
std::string memoryOptimizerStrategyName = "";
ParseOptions(options.m_BackendOptions, id, [&](std::string name, const BackendOptions::Var& value)
{
if (name == "MemoryOptimizerStrategy")
{
memoryOptimizerStrategyName = ParseStringBackendOption(value, "");
}
});
if (memoryOptimizerStrategyName != "")
{
std::shared_ptr<IMemoryOptimizerStrategy> strategy =
GetMemoryOptimizerStrategy(memoryOptimizerStrategyName);
if (!strategy)
{
ARMNN_LOG(warning) << "MemoryOptimizerStrategy: " << memoryOptimizerStrategyName
<< " was not found.";
}
else
{
using BackendCapability = BackendOptions::BackendOption;
auto strategyType = GetMemBlockStrategyTypeName(strategy->GetMemBlockStrategyType());
BackendCapability memOptimizeStrategyCapability {strategyType, true};
if (HasCapability(memOptimizeStrategyCapability, id))
{
BackendRegistryInstance().RegisterMemoryOptimizerStrategy(id, strategy);
ARMNN_LOG(info) << "MemoryOptimizerStrategy: "
<< memoryOptimizerStrategyName << " set for the backend " << id << ".";
}
else
{
ARMNN_LOG(warning) << "Backend "
<< id
<< " does not have multi-axis packing capability and cannot support"
<< "MemoryOptimizerStrategy: " << memoryOptimizerStrategyName << ".";
}
}
}
}
auto context = backend->CreateBackendContext(options);
// backends are allowed to return nullptrs if they
// don't wish to create a backend specific context
if (context)
{
m_BackendContexts.emplace(std::make_pair(id, std::move(context)));
}
supportedBackends.emplace(id);
unique_ptr<armnn::profiling::IBackendProfiling> profilingIface =
std::make_unique<armnn::profiling::BackendProfiling>(armnn::profiling::BackendProfiling(
options, m_ProfilingService, id));
// Backends may also provide a profiling context. Ask for it now.
auto profilingContext = backend->CreateBackendProfilingContext(options, profilingIface);
// Backends that don't support profiling will return a null profiling context.
if (profilingContext)
{
// Pass the context onto the profiling service.
m_ProfilingService.AddBackendProfilingContext(id, profilingContext);
}
}
catch (const BackendUnavailableException&)
{
// Ignore backends which are unavailable
}
}
BackendRegistryInstance().SetProfilingService(m_ProfilingService);
// pass configuration info to the profiling service
m_ProfilingService.ConfigureProfilingService(options.m_ProfilingOptions);
if (options.m_ProfilingOptions.m_EnableProfiling)
{
// try to wait for the profiling service to initialise
m_ProfilingService.WaitForProfilingServiceActivation(3000);
}
m_DeviceSpec.AddSupportedBackends(supportedBackends);
ARMNN_LOG(info) << "Initialization time: " << std::setprecision(2)
<< std::fixed << armnn::GetTimeDuration(start_time).count() << " ms.";
}
RuntimeImpl::~RuntimeImpl()
{
const auto startTime = armnn::GetTimeNow();
std::vector<int> networkIDs;
try
{
// Coverity fix: The following code may throw an exception of type std::length_error.
std::transform(m_LoadedNetworks.begin(), m_LoadedNetworks.end(),
std::back_inserter(networkIDs),
[](const auto &pair) { return pair.first; });
}
catch (const std::exception& e)
{
// Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
// exception of type std::length_error.
// Using stderr instead in this context as there is no point in nesting try-catch blocks here.
std::cerr << "WARNING: An error has occurred when getting the IDs of the networks to unload: " << e.what()
<< "\nSome of the loaded networks may not be unloaded" << std::endl;
}
// We then proceed to unload all the networks which IDs have been appended to the list
// up to the point the exception was thrown (if any).
for (auto networkID : networkIDs)
{
try
{
// Coverity fix: UnloadNetwork() may throw an exception of type std::length_error,
// boost::log::v2s_mt_posix::odr_violation or boost::log::v2s_mt_posix::system_error
UnloadNetwork(networkID);
}
catch (const std::exception& e)
{
// Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
// exception of type std::length_error.
// Using stderr instead in this context as there is no point in nesting try-catch blocks here.
std::cerr << "WARNING: An error has occurred when unloading network " << networkID << ": " << e.what()
<< std::endl;
}
}
// Clear all dynamic backends.
DynamicBackendUtils::DeregisterDynamicBackends(m_DeviceSpec.GetDynamicBackends());
m_DeviceSpec.ClearDynamicBackends();
m_BackendContexts.clear();
BackendRegistryInstance().SetProfilingService(armnn::EmptyOptional());
ARMNN_LOG(info) << "Shutdown time: " << std::setprecision(2)
<< std::fixed << armnn::GetTimeDuration(startTime).count() << " ms.";
}
LoadedNetwork* RuntimeImpl::GetLoadedNetworkPtr(NetworkId networkId) const
{
std::lock_guard<std::mutex> lockGuard(m_Mutex);
return m_LoadedNetworks.at(networkId).get();
}
TensorInfo RuntimeImpl::GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const
{
return GetLoadedNetworkPtr(networkId)->GetInputTensorInfo(layerId);
}
TensorInfo RuntimeImpl::GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const
{
return GetLoadedNetworkPtr(networkId)->GetOutputTensorInfo(layerId);
}
std::vector<ImportedInputId> RuntimeImpl::ImportInputs(NetworkId networkId, const InputTensors& inputTensors,
MemorySource forceImportMemorySource)
{
return GetLoadedNetworkPtr(networkId)->ImportInputs(inputTensors, forceImportMemorySource);
}
std::vector<ImportedOutputId> RuntimeImpl::ImportOutputs(NetworkId networkId, const OutputTensors& outputTensors,
MemorySource forceImportMemorySource)
{
return GetLoadedNetworkPtr(networkId)->ImportOutputs(outputTensors, forceImportMemorySource);
}
void RuntimeImpl::ClearImportedInputs(NetworkId networkId, const std::vector<ImportedInputId> inputIds)
{
return GetLoadedNetworkPtr(networkId)->ClearImportedInputs(inputIds);
}
void RuntimeImpl::ClearImportedOutputs(NetworkId networkId, const std::vector<ImportedOutputId> outputIds)
{
return GetLoadedNetworkPtr(networkId)->ClearImportedOutputs(outputIds);
}
Status RuntimeImpl::EnqueueWorkload(NetworkId networkId,
const InputTensors& inputTensors,
const OutputTensors& outputTensors,
std::vector<ImportedInputId> preImportedInputIds,
std::vector<ImportedOutputId> preImportedOutputIds)
{
const auto startTime = armnn::GetTimeNow();
LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId);
if (!loadedNetwork)
{
ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist.";
return Status::Failure;
}
if (loadedNetwork->IsAsyncEnabled())
{
ARMNN_LOG(error) << "Network " << networkId << " is async enabled.";
return Status::Failure;
}
ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get());
ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "EnqueueWorkload");
static thread_local NetworkId lastId = networkId;
if (lastId != networkId)
{
LoadedNetworkFuncSafe(lastId, [](LoadedNetwork* network)
{
network->FreeWorkingMemory();
});
}
lastId=networkId;
auto status = loadedNetwork->EnqueueWorkload(inputTensors, outputTensors,
preImportedInputIds, preImportedOutputIds);
// Check if we imported, if not there's no need to call the After EnqueueWorkload events
if (!preImportedInputIds.empty() || !preImportedOutputIds.empty())
{
// Call After EnqueueWorkload events
for (auto&& context : m_BackendContexts)
{
context.second->AfterEnqueueWorkload(networkId);
}
}
ARMNN_LOG(info) << "Execution time: " << std::setprecision(2)
<< std::fixed << armnn::GetTimeDuration(startTime).count() << " ms.";
return status;
}
Status RuntimeImpl::Execute(IWorkingMemHandle& iWorkingMemHandle,
const InputTensors& inputTensors,
const OutputTensors& outputTensors,
std::vector<ImportedInputId> preImportedInputs,
std::vector<ImportedOutputId> preImportedOutputs)
{
const auto startTime = armnn::GetTimeNow();
NetworkId networkId = iWorkingMemHandle.GetNetworkId();
LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId);
if (!loadedNetwork)
{
ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist.";
return Status::Failure;
}
if (!loadedNetwork->IsAsyncEnabled())
{
ARMNN_LOG(error) << "Attempting execute " << networkId << " when it is not async enabled.";
return Status::Failure;
}
ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get());
ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "Execute");
auto status = loadedNetwork->Execute(inputTensors,
outputTensors,
iWorkingMemHandle,
preImportedInputs,
preImportedOutputs);
ARMNN_LOG(info) << "Execution time: " << std::setprecision(2)
<< std::fixed << armnn::GetTimeDuration(startTime).count() << " ms.";
return status;
}
/// Create a new unique WorkingMemHandle object. Create multiple handles if you wish to have
/// overlapped Execution by calling this function from different threads.
std::unique_ptr<IWorkingMemHandle> RuntimeImpl::CreateWorkingMemHandle(NetworkId networkId)
{
LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId);
if (!loadedNetwork)
{
ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist.";
return nullptr;
}
if (!loadedNetwork->IsAsyncEnabled())
{
ARMNN_LOG(error) << "Network " << networkId << " is not async enabled.";
return nullptr;
}
ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get());
ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "CreateWorkingMemHandle");
static thread_local NetworkId lastId = networkId;
if (lastId != networkId)
{
LoadedNetworkFuncSafe(lastId, [](LoadedNetwork* network)
{
network->FreeWorkingMemory();
});
}
lastId=networkId;
return loadedNetwork->CreateWorkingMemHandle(networkId);
}
void RuntimeImpl::RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction& func)
{
LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId);
loadedNetwork->RegisterDebugCallback(func);
}
void RuntimeImpl::LoadDynamicBackends(const std::string& overrideBackendPath)
{
// Get the paths where to load the dynamic backends from
std::vector<std::string> backendPaths = DynamicBackendUtils::GetBackendPaths(overrideBackendPath);
// Get the shared objects to try to load as dynamic backends
std::vector<std::string> sharedObjects = DynamicBackendUtils::GetSharedObjects(backendPaths);
// Create a list of dynamic backends
m_DynamicBackends = DynamicBackendUtils::CreateDynamicBackends(sharedObjects);
// Register the dynamic backends in the backend registry
BackendIdSet registeredBackendIds = DynamicBackendUtils::RegisterDynamicBackends(m_DynamicBackends);
// Add the registered dynamic backend ids to the list of supported backends
m_DeviceSpec.AddSupportedBackends(registeredBackendIds, true);
}
} // namespace armnn
| 40.242261
| 119
| 0.621605
|
Srivathsav-max
|
a913bc466d97d9bf64475a01ab64256980fa1294
| 6,670
|
hpp
|
C++
|
src/base/util/TimeSystemConverter.hpp
|
supalogix/GMAT
|
eea9987ef0978b3e6702e70b587a098b2cbce14e
|
[
"Apache-2.0"
] | null | null | null |
src/base/util/TimeSystemConverter.hpp
|
supalogix/GMAT
|
eea9987ef0978b3e6702e70b587a098b2cbce14e
|
[
"Apache-2.0"
] | null | null | null |
src/base/util/TimeSystemConverter.hpp
|
supalogix/GMAT
|
eea9987ef0978b3e6702e70b587a098b2cbce14e
|
[
"Apache-2.0"
] | null | null | null |
//$Id$
//------------------------------------------------------------------------------
// TimeSystemConverter
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2017 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number S-67573-G
//
// Author: Allison Greene
// Created: 2005/02/03
//
/**
* Definition of the TimeSystemConverter class
*/
//------------------------------------------------------------------------------
#ifndef TimeSystemConverter_hpp
#define TimeSystemConverter_hpp
//#include <iostream>
//#include <iomanip>
//#include <sstream>
//#include "BaseException.hpp"
#include "EopFile.hpp"
#include "LeapSecsFileReader.hpp"
//#include "GmatConstants.hpp"
// struct TimeSystemConverterExceptions
// {
class GMAT_API UnimplementedException : public BaseException
{
public:
UnimplementedException(const std::string &message =
"TimeSystemConverter: Conversion not implemented: ")
: BaseException(message) {};
};
class GMAT_API TimeFileException : public BaseException
{
public:
TimeFileException(const std::string &message =
"TimeSystemConverter: File is unknown: ")
: BaseException(message) {};
};
class GMAT_API TimeFormatException : public BaseException
{
public:
TimeFormatException(const std::string &message =
"TimeSystemConverter: Requested format not implemented: ")
: BaseException(message) {};
};
class GMAT_API InvalidTimeException : public BaseException
{
public:
InvalidTimeException(const std::string &message =
"TimeSystemConverter: Requested time is invalid: ")
: BaseException(message) {};
};
// };
namespace TimeConverterUtil
{
// Specified in Math Spec section 2.3
static const Real TDB_COEFF1 = 0.001658;
static const Real TDB_COEFF2 = 0.00001385;
static const Real M_E_OFFSET = 357.5277233;
static const Real M_E_COEFF1 = 35999.05034;
static const Real T_TT_OFFSET = GmatTimeConstants::JD_OF_J2000;
static const Real T_TT_COEFF1 = GmatTimeConstants::DAYS_PER_JULIAN_CENTURY;
static const Real L_B = 1.550505e-8;
static const Real NUM_SECS = GmatTimeConstants::SECS_PER_DAY;
enum TimeSystemTypes
{
A1MJD = 0,
TAIMJD,
UTCMJD,
UT1MJD,
TDBMJD,
TTMJD,
A1,
TAI,
UTC,
UT1,
TDB,
TT,
TimeSystemCount
};
static const std::string TIME_SYSTEM_TEXT[TimeSystemCount] =
{
"A1Mjd",
"TaiMjd",
"UtcMjd",
"Ut1Mjd",
"TdbMjd",
"TtMjd",
// New entries added by DJC
"A1",
"TAI",
"UTC",
"UT1",
"TDB",
"TT",
};
/* Real Convert(const Real origValue,
const std::string &fromType,
const std::string &toType,
Real refJd = GmatTimeConstants::JD_NOV_17_1858);
Real ConvertToTaiMjd(std::string fromType, Real origValue,
Real refJd= GmatTimeConstants::JD_NOV_17_1858);
Real ConvertFromTaiMjd(std::string toType, Real origValue,
Real refJd= GmatTimeConstants::JD_NOV_17_1858);
*/
Integer GMAT_API GetTimeTypeID(std::string &str);
Real GMAT_API Convert(const Real origValue,
const Integer fromType,
const Integer toType,
Real refJd = GmatTimeConstants::JD_JAN_5_1941);
Real GMAT_API ConvertToTaiMjd(Integer fromType, Real origValue,
Real refJd = GmatTimeConstants::JD_NOV_17_1858);
Real GMAT_API ConvertFromTaiMjd(Integer toType, Real origValue,
Real refJd = GmatTimeConstants::JD_NOV_17_1858);
Real GMAT_API NumberOfLeapSecondsFrom(Real utcMjd,
Real jdOfMjdRef = GmatTimeConstants::JD_JAN_5_1941);
Real GMAT_API GetFirstLeapSecondMJD(Real fromUtcMjd, Real toUtcMjd,
Real jdOfMjdRef = GmatTimeConstants::JD_JAN_5_1941);
void GMAT_API SetEopFile(EopFile *eopFile);
void GMAT_API SetLeapSecsFileReader(LeapSecsFileReader *leapSecsFileReader);
void GMAT_API GetTimeSystemAndFormat(const std::string &type, std::string &system,
std::string &format);
std::string GMAT_API ConvertMjdToGregorian(const Real mjd, bool handleLeapSecond = false,
Integer format = 1);
Real GMAT_API ConvertGregorianToMjd(const std::string &greg);
void GMAT_API Convert(const char *fromType, Real fromMjd,
const char *fromStr, const char *toType,
Real &toMjd, std::string &toStr, Integer format = 1);
void GMAT_API Convert(const char *fromType, Real fromMjd,
const std::string &fromStr, const std::string &toType,
Real &toMjd, std::string &toStr, Integer format = 1);
void GMAT_API Convert(const std::string &fromType, Real fromMjd,
const std::string &fromStr, const std::string &toType,
Real &toMjd, std::string &toStr, Integer format = 1);
bool GMAT_API ValidateTimeSystem(std::string sys);
bool GMAT_API ValidateTimeFormat(const std::string &format, const std::string &value,
bool checkValue = true);
StringArray GMAT_API GetValidTimeRepresentations();
bool GMAT_API IsValidTimeSystem(const std::string& system);
bool GMAT_API IsInLeapSecond(Real theTaiMjd);
bool GMAT_API HandleLeapSecond();
static bool isInLeapSecond;
}
#endif // TimeSystemConverter_hpp
| 36.25
| 96
| 0.610945
|
supalogix
|
a9146acd8fd8c8fd66ae29fe413354cc18c59348
| 5,342
|
cpp
|
C++
|
programs/program2/tests/validator_test.cpp
|
Notgnoshi/parallel
|
4fce05ac90682f7daa9986dcdb82c9df24e42c74
|
[
"MIT"
] | null | null | null |
programs/program2/tests/validator_test.cpp
|
Notgnoshi/parallel
|
4fce05ac90682f7daa9986dcdb82c9df24e42c74
|
[
"MIT"
] | null | null | null |
programs/program2/tests/validator_test.cpp
|
Notgnoshi/parallel
|
4fce05ac90682f7daa9986dcdb82c9df24e42c74
|
[
"MIT"
] | null | null | null |
#include "validator_test.h"
#include "kernels/kernel.h"
#include "kernels/kernel_factory.h"
#include "matrix.h"
#include "validator.h"
void ValidationTest::ValidateAddition()
{
CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 0, 0 ), Matrix_t( 0, 0 ) ) );
CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 1, 1 ), Matrix_t( 1, 1 ) ) );
CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 16, 16 ), Matrix_t( 16, 16 ) ) );
CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 234, 1234 ), Matrix_t( 234, 1234 ) ) );
CPPUNIT_ASSERT( AdditionValidator( Matrix_t( 13, 1 ), Matrix_t( 13, 1 ) ) );
CPPUNIT_ASSERT( !AdditionValidator( Matrix_t( 15, 16 ), Matrix_t( 16, 16 ) ) );
CPPUNIT_ASSERT( !AdditionValidator( Matrix_t( 16, 15 ), Matrix_t( 16, 16 ) ) );
CPPUNIT_ASSERT( !AdditionValidator( Matrix_t( 16, 16 ), Matrix_t( 15, 16 ) ) );
CPPUNIT_ASSERT( !AdditionValidator( Matrix_t( 16, 16 ), Matrix_t( 16, 15 ) ) );
}
void ValidationTest::ValidateMultiplication()
{
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 4, 4 ) ) );
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 0, 0 ), Matrix_t( 0, 0 ) ) );
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 1, 1 ), Matrix_t( 1, 1 ) ) );
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 4, 3 ) ) );
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 4, 5 ) ) );
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 4, 1 ) ) );
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 1, 4 ), Matrix_t( 4, 4 ) ) );
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 3, 4 ), Matrix_t( 4, 3 ) ) );
CPPUNIT_ASSERT( MultiplicationValidator( Matrix_t( 5, 4 ), Matrix_t( 4, 5 ) ) );
CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) );
CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) );
CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) );
CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) );
CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 3 ), Matrix_t( 4, 3 ) ) );
CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 4, 5 ), Matrix_t( 4, 5 ) ) );
CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 1, 4 ), Matrix_t( 3, 4 ) ) );
CPPUNIT_ASSERT( !MultiplicationValidator( Matrix_t( 3, 4 ), Matrix_t( 5, 3 ) ) );
}
void ValidationTest::ValidateMultiplicationKernels()
{
const Matrix_t expected( 0, 0 );
auto kernel = KernelFactory( OPERATION_VECTOR_MULTIPLICATION, KERNEL_DEFAULT ).GetKernel();
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected );
kernel = KernelFactory( OPERATION_VECTOR_MULTIPLICATION, KERNEL_CPU ).GetKernel();
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected );
kernel = KernelFactory( OPERATION_VECTOR_MULTIPLICATION, KERNEL_CUDA ).GetKernel();
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected );
}
void ValidationTest::ValidateAdditionKernels()
{
const Matrix_t expected( 0, 0 );
auto kernel = KernelFactory( OPERATION_ADDITION, KERNEL_DEFAULT ).GetKernel();
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected );
kernel = KernelFactory( OPERATION_ADDITION, KERNEL_CPU ).GetKernel();
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected );
kernel = KernelFactory( OPERATION_ADDITION, KERNEL_CUDA ).GetKernel();
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 3 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 3, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 5 ), Matrix_t( 4, 4 ) ) == expected );
CPPUNIT_ASSERT( *kernel->Operation( Matrix_t( 4, 4 ), Matrix_t( 5, 4 ) ) == expected );
}
| 55.645833
| 95
| 0.661176
|
Notgnoshi
|
a9165d97ffaa13234978dbbe69f1b17ac2ee4cbd
| 22,130
|
cpp
|
C++
|
3.Auction/Static-Bin/scv-main.cpp
|
Parwatsingh/OptSmart
|
0564abdd04e7bc37a3586982a1d7ca5a97be88d5
|
[
"Apache-2.0"
] | 1
|
2021-03-13T08:55:13.000Z
|
2021-03-13T08:55:13.000Z
|
3.Auction/Static-Bin/scv-main.cpp
|
Parwatsingh/OptSmart
|
0564abdd04e7bc37a3586982a1d7ca5a97be88d5
|
[
"Apache-2.0"
] | null | null | null |
3.Auction/Static-Bin/scv-main.cpp
|
Parwatsingh/OptSmart
|
0564abdd04e7bc37a3586982a1d7ca5a97be88d5
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <thread>
#include "Util/Timer.cpp"
#include "Contract/SimpleAuctionSCV.cpp"
#include "Util/FILEOPR.cpp"
#include <unistd.h>
#include <list>
#include <vector>
#include <atomic>
#include <condition_variable>
#include <set>
#include <algorithm>
#define maxThreads 128
#define maxBObj 5000
#define maxbEndT 5000 //millseconds
#define funInContract 6
#define pl "===================================================\n"
#define MValidation true //! true or false
#define malMiner true //! set the flag to make miner malicious.
#define NumOfDoubleSTx 2 //! # double-spending Tx for malicious final state by Miner.
using namespace std;
using namespace std::chrono;
int NumBlock = 26; //! at least two blocks, the first run is warmup run.
int numValidator = 50;
int beneficiary = 0; //! fixed beneficiary id to 0, it can be any unique address/id.
int nBidder = 2; //! nBidder: number of bidder shared objects. default is 2.
int nThread = 1; //! nThread: total number of concurrent threads; default is 1.
int numAUs; //! numAUs: total number of Atomic Unites to be executed.
double lemda; //! λ: random delay seed.
int bidEndT; //! time duration for auction.
double tTime[2]; //! total time taken by miner and validator algorithm respectively.
SimpleAuction *auction; //! smart contract for miner.
int *aCount = NULL; //! aborted transaction count.
float_t *mTTime = NULL; //! time taken by each miner Thread to execute AUs (Transactions).
float_t *vTTime = NULL; //! time taken by each validator Thread to execute AUs (Transactions).
float_t *gTtime = NULL; //! time taken by each miner Thread to add edges and nodes in the conflict graph.
vector<string>listAUs; //! holds AUs to be executed on smart contract: "listAUs" index+1 represents AU_ID.
vector<string>seqBin; //! holds sequential Bin AUs.
vector<string>concBin; //! holds concurrent Bin AUs.
vector<int>ccSet; //! Set holds the IDs of the shared objects accessed by concurrent Bin Tx.
std::atomic<int>currAU; //! used by miner-thread to get index of Atomic Unit to execute.
std::atomic<int>vCount; //! # of valid AU node added in graph (invalid AUs will not be part of the graph & conflict list).
std::atomic<int>eAUCount; //! used by validator threads to keep track of how many valid AUs executed by validator threads.
mutex concLock, seqLock; //! Lock used to access seq and conc bin.
float_t seqTime[3]; //! Used to store seq exe time.
std::atomic<bool>mm; //! miner is malicious, this is used by validators.
//! STATE DATA
int mHBidder;
int mHBid;
int vHBidder;
int vHBid;
int *mPendingRet;
int *vPendingRet;
/*************************BARRIER CODE BEGINS****************************/
std::mutex mtx;
std::mutex pmtx; // to print in concurrent scene
std::condition_variable cv;
bool launch = false;
void wait_for_launch() {
std::unique_lock<std::mutex> lck(mtx);
while (!launch) cv.wait(lck);
}
void shoot() {
std::unique_lock<std::mutex> lck(mtx);
launch = true;
cv.notify_all();
}
/*************************BARRIER CODE ENDS*****************************/
/*************************MINER CODE BEGINS*****************************/
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Class "Miner" create & run "n" miner-thread concurrently !
!"concMiner()" called by miner-thread to perfrom oprs of respective AUs !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
class Miner
{
public:
Miner( )
{
//! initialize the counter used to execute the numAUs
currAU = 0;
vCount = 0;
//! index location represents respective thread id.
mTTime = new float_t [nThread];
gTtime = new float_t [nThread];
aCount = new int [nThread];
for(int i = 0; i < nThread; i++) {
mTTime[i] = 0;
gTtime[i] = 0;
aCount[i] = 0;
}
auction = new SimpleAuction(bidEndT, beneficiary, nBidder);
}
//!--------------------------------------------
//!!!!!! MAIN MINER:: CREATE MINER THREADS !!!!
//!--------------------------------------------
void mainMiner()
{
Timer mTimer;
thread T[nThread];
// seqTime[0] = 0;
Timer staticTimer;
//! start timer to get time taken by static analysis.
auto start = staticTimer._timeStart();
staticAnalysis();
seqTime[0] += staticTimer._timeStop( start );
//!---------------------------------------------------------
//!!!!!!!!!! Concurrent Phase !!!!!!!!!!
//!!!!!!!!!! Create 'nThread' Miner threads !!!!!!!!!!
//!---------------------------------------------------------
double s = mTimer.timeReq();
for(int i = 0; i < nThread; i++)
T[i] = thread(concMiner, i, concBin.size());
for(auto& th : T) th.join();
tTime[0] = mTimer.timeReq() - s;
//!------------------------------------------
//!!!!!!!!! Sequential Phase !!!!!!!!!!
//!------------------------------------------
// seqTime[1] = 0;
Timer SeqTimer;
//! start timer to get time taken by this thread.
start = SeqTimer._timeStart();
seqBinExe();
seqTime[1] += SeqTimer._timeStop( start );
//! print the final state of the shared objects.
finalState();
}
//! returns the sObj accessed by AU.
void getSobjId(vector<int> &sObj, string AU) {
istringstream ss(AU);
string tmp;
ss >> tmp; //! AU_ID to Execute.
ss >> tmp; //! Function Name (smart contract).
if(tmp.compare("bid") == 0) {
ss >> tmp;
int payable = stoi(tmp);//! payable
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
sObj.push_back(bID);
return;
}
if(tmp.compare("withdraw") == 0) {
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
sObj.push_back(bID);
return;
}
}
//!-----------------------------------------------------------
//! Performs the static analysis based on set Operations. !
//!-----------------------------------------------------------
void staticAnalysis() {
//holds the IDs of the shared object accessed by an AU.
vector<int> sObj;
if(numAUs != 0) {
//! Add first AU to concBin and Add Sobj accessed by it to ccSet.
concBin.push_back(listAUs[0]);
getSobjId(sObj, listAUs[0]);
auto it = sObj.begin();
for( ; it != sObj.end(); ++it) {
ccSet.push_back(*it);
}
}
int index = 1;
while( index < numAUs ) {
sObj.clear();
getSobjId(sObj, listAUs[index]);
sort (ccSet.begin(), ccSet.end());
sort (sObj.begin(), sObj.end());
vector<int> intersect(ccSet.size() + sObj.size());
vector<int>:: iterator it;
it = set_intersection( ccSet.begin(), ccSet.end(),
sObj.begin(), sObj.end(),
intersect.begin());
intersect.resize(it-intersect.begin());
if(intersect.size() == 0 ) {
auto it = sObj.begin();
for(; it != sObj.end(); ++it) ccSet.push_back(*it);
concBin.push_back(listAUs[index]);
}
else {
seqBin.push_back(listAUs[index]);
}
index++;
}
}
//!-----------------------------------------------------------------
//!!!!!!!!!! Concurrent Phase !!!!!!!!!!
//! The function to be executed by all the miner threads. Thread !
//! executes the transaction concurrently from Concurrent Bin !
//!-----------------------------------------------------------------
static void concMiner(int t_ID, int numAUs) {
Timer thTimer;
//! get the current index, and increment it.
int curInd = currAU++;
//! statrt clock to get time taken by this.AU
auto start = thTimer._timeStart();
while(curInd < concBin.size()) {
//!get the AU to execute, which is of string type.
istringstream ss(concBin[curInd]);
string tmp;
ss >> tmp;
int AU_ID = stoi(tmp);
ss >> tmp;
if(tmp.compare("bid") == 0) {
ss >> tmp;
int payable = stoi(tmp);//! payable
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
ss >> tmp;
int bAmt = stoi(tmp);//! Bidder value
int v = auction->bid(payable, bID, bAmt);
}
if(tmp.compare("withdraw") == 0) {
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
int v = auction->withdraw(bID);
}
if(tmp.compare("auction_end") == 0) {
int v = auction->auction_end( );
}
//! get the current index to execute, and increment it.
curInd = currAU++;
}
mTTime[t_ID] += thTimer._timeStop(start);
}
//!------------------------------------------
//!!!!!!!!! Sequential Phase !!!!!!!!!!
//!------------------------------------------
void seqBinExe( ) {
int t_ID = 0;
int count = 0;
while(count < seqBin.size()) {
//! get the AU to execute, which is of string type.
istringstream ss(seqBin[count]);
string tmp;
ss >> tmp;
int AU_ID = stoi(tmp);
ss >> tmp;
if(tmp.compare("bid") == 0) {
ss >> tmp;
int payable = stoi(tmp);//! payable
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
ss >> tmp;
int bAmt = stoi(tmp);//! Bidder value
int v = auction->bid(payable, bID, bAmt);
}
if(tmp.compare("withdraw") == 0) {
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
int v = auction->withdraw(bID);
}
if(tmp.compare("auction_end") == 0) {
int v = auction->auction_end( );
}
count++;
}
}
//!-------------------------------------------------
//!Final state of all the shared object. Once all |
//!AUs executed. We are geting this using state_m()|
//!-------------------------------------------------
void finalState() {
auction->state(&mHBidder, &mHBid, mPendingRet);
}
~Miner() { };
};
/********************MINER CODE ENDS*********************************/
/********************VALIDATOR CODE BEGINS***************************/
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Class "Validator" create & run "n" validator-Thread concurrently !
! based on CONC and SEQ BIN given by miner operations of respective !
! AUs. Thread 0 is considered as smart contract deployer. !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
class Validator
{
public:
Validator()
{
//! int the execution counter used by validator threads.
eAUCount = 0;
//! array index location represents respective thread id.
vTTime = new float_t [nThread];
for(int i = 0; i < nThread; i++) vTTime[i] = 0;
};
//!----------------------------------------
//! create n concurrent validator threads |
//! to execute valid AUs. |
//!----------------------------------------
void mainValidator()
{
for(int i = 0; i < nThread; i++) vTTime[i] = 0;
eAUCount = 0;
Timer vTimer;
thread T[nThread];
auction->reset(bidEndT);
//!---------------------------------------------------------
//!!!!!!!!!! Concurrent Phase !!!!!!!!!!
//!!!!!!!!!! Create 'nThread' Validator threads !!!!!!!!!!
//!---------------------------------------------------------
double s = vTimer.timeReq();
for(int i = 0; i<nThread; i++) T[i] = thread(concValidator, i);
shoot();
for(auto& th : T) th.join( );
tTime[1] = vTimer.timeReq() - s;
//!------------------------------------------
//!!!!!!!!! Sequential Phase !!!!!!!!!!
//!------------------------------------------
// seqTime[2] = 0;
Timer SeqTimer;
auto start = SeqTimer._timeStart();
seqBinExe();
seqTime[2] += SeqTimer._timeStop( start );
//!print the final state of the shared objects by validator.
finalState();
// auction->AuctionEnded( );
}
//!------------------------------------------------------------
//!!!!!!! Concurrent Phase !!!!!!!!
//!!!!!! 'nThread' Validator threads Executes this Fun !!!!!!!
//!------------------------------------------------------------
static void concValidator( int t_ID ) {
//barrier to synchronise all threads for a coherent launch
wait_for_launch();
Timer Ttimer;
//!statrt clock to get time taken by this thread.
auto start = Ttimer._timeStart();
int curInd = eAUCount++;
while( curInd< concBin.size() && mm == false) {
//! get the AU to execute, which is of string type.
istringstream ss(concBin[curInd]);
string tmp;
ss >> tmp; //! AU_ID to Execute.
int AU_ID = stoi(tmp);
ss >> tmp; //! Function Name (smart contract).
if(tmp.compare("bid") == 0) {
ss >> tmp;
int payable = stoi(tmp);//! payable
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
ss >> tmp;
int bAmt = stoi(tmp);//! Bidder value
int v = auction->bid(payable, bID, bAmt);
if(v == -1) mm = true;
}
if(tmp.compare("withdraw") == 0) {
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
int v = auction->withdraw(bID);
if(v == -1) mm = true;
}
if(tmp.compare("auction_end") == 0) {
int v = auction->auction_end( );
}
curInd = eAUCount++;
}
//!stop timer to get time taken by this thread
vTTime[t_ID] += Ttimer._timeStop( start );
}
//!------------------------------------------
//!!!!!!!!! Sequential Phase !!!!!!!!!!
//!------------------------------------------
void seqBinExe( ) {
int t_ID = 0;
int count = 0;
while(count < seqBin.size() && mm == false) {
//! get the AU to execute, which is of string type.
istringstream ss(seqBin[count]);
string tmp;
ss >> tmp; //! AU_ID to Execute.
int AU_ID = stoi(tmp);
ss >> tmp; //! Function Name (smart contract).
if(tmp.compare("bid") == 0) {
ss >> tmp;
int payable = stoi(tmp);//! payable
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
ss >> tmp;
int bAmt = stoi(tmp);//! Bidder value
int v = auction->bid(payable, bID, bAmt);
if(v == -1) mm = true;
}
if(tmp.compare("withdraw") == 0) {
ss >> tmp;
int bID = stoi(tmp);//! Bidder ID
int v = auction->withdraw(bID);
if(v == -1) mm = true;
}
if(tmp.compare("auction_end") == 0) {
int v = auction->auction_end( );
}
count++;
}
}
//!-------------------------------------------------
//!Final state of all the shared object. Once all |
//!AUs executed. We are geting this using state() |
//!-------------------------------------------------
void finalState() {
//state
auction->state(&vHBidder, &vHBid, vPendingRet);
}
~Validator() { };
};
/**********************VALIDATOR CODE ENDS***************************/
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//! atPoss:: from which double-spending Tx to be stored at begining !
//! of the list. Add malicious final state with double-spending Tx !
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
bool addMFS(int atPoss) {
istringstream ss(listAUs[atPoss-2]);
string trns1;
ss >> trns1; //! AU_ID to Execute.
int AU_ID1 = stoi(trns1);
ss >> trns1;//function name
ss >> trns1; //! payable.
int payable = stoi(trns1);
ss >> trns1; //! bidder ID.
int bidderID = stoi(trns1);
ss >> trns1; //! Ammount to bid.
int bidValue = stoi(trns1);
istringstream ss1(listAUs[atPoss-1]);
string trns2;
ss1 >> trns1; //! AU_ID to Execute.
int AU_ID2 = stoi(trns1);
ss1 >> trns1;//function name
ss1 >> trns1; //! payable.
int payable1 = stoi(trns1);
ss1 >> trns1; //! bidderID.
int bidderID1 = stoi(trns1);
ss1 >> trns1; //! Ammount to bid.
int bidValue1 = stoi(trns1);
bidValue = 999;
trns1 = to_string(AU_ID1)+" bid "+to_string(payable)+" "
+to_string(bidderID)+" "+to_string(bidValue);
listAUs[AU_ID1-1] = trns1;
bidValue1 = 1000;
trns2 = to_string(AU_ID2)+" bid "+to_string(payable1)+" "
+to_string(bidderID1)+" "+to_string(bidValue1);
listAUs[AU_ID2-1] = trns1;
mHBidder = bidderID1;
mHBid = bidValue;
//! add the confliciting AUs in conc bin and remove them from seq bin. Add
//! one of the AU from seq bin to conc Bin and remove that AU from seq bin.
auto it = concBin.begin();
concBin.erase(it);
concBin.insert(concBin.begin(), trns1);
concBin.insert(concBin.begin()+1, trns2);
it = seqBin.begin();
seqBin.erase(it);
return true;
}
void printBins( ) {
int concCount = 0, seqCount = 0;
cout<<endl<<"=====================\n"
<<"Concurrent Bin AUs\n=====================";
for(int i = 0; i < concBin.size(); i++) {
cout<<"\n"<<concBin[i];
concCount++;
}
cout<<endl;
cout<<endl<<"=====================\n"
<<"Sequential Bin AUs\n=====================";
for(int i = 0; i < seqBin.size(); i++) {
cout<<"\n"<<seqBin[i];
seqCount++;
}
cout<<"\n=====================\n"
<<"Conc AU Count "<< concCount
<<"\nSeq AU Count "<<seqCount
<<"\n=====================\n";
}
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
/*!!!!!!!! State Validation !!!!!!!!!!*/
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
bool stateVal() {
//State Validation
bool flag = false;
if(mHBidder != vHBidder || mHBid != vHBid) flag = true;
// cout<<"\n============================================"
// <<"\n Miner Auction Winer "<<mHBidder
// <<" | Amount "<<mHBid;
// cout<<"\n Validator Auction Winer "<<to_string(vHBidder)
// <<" | Amount "<<to_string(vHBid);
// cout<<"\n============================================\n";
return flag;
}
/**********************MAIN FUN CODE BEGINS***************************/
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
/*!!!!!!!! main() !!!!!!!!!!*/
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
int main(int argc, char *argv[])
{
cout<<pl<<"Static Bin Miner and Smart Concurrent Validator\n";
cout<<"--------------------------------\n";
if(argc<3)
cout<<"\nPlease Enter Command Line Argument as follows:"
<<"\n\t./a.out <num Blocks> <num Validator> <num Iteration>\n";
NumBlock = atoi(argv[1]);
numValidator = atoi(argv[2]);
int nItertion = atoi(argv[3]);
if(NumBlock < 2) cout<<"\nNumber of Blocks should be >= 2\n";
if(numValidator < 1)cout<<"\nNumber of Validators should be >= 1\n";
if(nItertion < 1)cout<<"\nNumber of Iterations should be >= 1\n";
float tMiner = 0, tVal = 0;
int tReject = 0, tMaxAcc = 0;
float tStatT = 0, tSeqMT = 0;
float tSeqVT = 0;
//! list holds the avg time taken by miner and Validator
//! thread s for multiple consecutive runs.
list<float>mItrT;
list<float>vItrT;
int totalRejCont = 0; //number of validator rejected the blocks;
int maxAccepted = 0;
int totalRun = NumBlock; //at least 2
FILEOPR file_opr;
//! read from input file:: nBidder = #nBidder; nThread = #threads;
//! numAUs = #AUs; λ = random delay seed.
file_opr.getInp(&nBidder, &bidEndT, &nThread, &numAUs, &lemda);
if(nBidder > maxBObj) {
nBidder = maxBObj;
cout<<"Max number Bidder Shared Object can be "<<maxBObj<<"\n";
}
float valTime;
for(int itr = 0; itr < nItertion; itr++)
{
seqTime[0] = seqTime[1] = seqTime[2] = 0;
totalRejCont = 0;
maxAccepted = 0;
valTime = 0;
float Blockvalt;
for(int nBlock = 0; nBlock < NumBlock; nBlock++)
{
file_opr.genAUs(numAUs, nBidder, funInContract, listAUs);
tTime[0] = 0, tTime[1] = 0;
Blockvalt = 0;
mPendingRet = new int [nBidder+1];
vPendingRet = new int [nBidder+1];
mm = new std::atomic<bool>;
mm = false;
Timer mTimer;
mTimer.start();
//MINER
Miner *miner = new Miner();
miner ->mainMiner();
if(lemda != 0) bool rv = addMFS(NumOfDoubleSTx);
// printBins();
//VALIDATOR
float valt = 0;
int acceptCount = 0, rejectCount = 0;
for(int nval = 0; nval < numValidator; nval++)
{
valt = 0;
Validator *validator = new Validator();
validator ->mainValidator();
bool flag = stateVal();
if(flag == true) rejectCount++;
else acceptCount++;
mm = false;
int counterv = 0;
for( int x = 0; x < nThread; x++ ){
if(vTTime[x] != 0) {
valt += vTTime[x];
counterv++;
}
}
if(nBlock > 0) Blockvalt += valt/counterv;
}
if(nBlock > 0 && malMiner == true) {
totalRejCont += rejectCount;
if(maxAccepted < acceptCount ) maxAccepted = acceptCount;
}
//! total valid AUs among total AUs executed
//! by miner and varified by Validator.
int vAUs = seqBin.size() + concBin.size();
if(nBlock > 0)
file_opr.writeOpt(nBidder, nThread, numAUs, tTime, mTTime, vTTime,
aCount, vAUs, mItrT, vItrT, 1);
ccSet.clear();
concBin.clear();
seqBin.clear();
listAUs.clear();
delete miner;
miner = NULL;
valTime += Blockvalt/numValidator;
}
//to get total avg miner and validator
//time after number of totalRun runs.
float tAvgMinerT = 0, tAvgValidT = 0;
int cnt = 0;
auto mit = mItrT.begin();
auto vit = vItrT.begin();
for(int j = 1; j < totalRun; j++){
tAvgMinerT = tAvgMinerT + *mit;
if(*vit != 0){
tAvgValidT = tAvgValidT + *vit;
cnt++;
}
mit++;
vit++;
}
tMiner += tAvgMinerT/(NumBlock-1);
tVal += valTime/(NumBlock-1);
tReject += totalRejCont /(NumBlock-1);
tStatT += seqTime[0];
tSeqMT += seqTime[1];
tSeqVT += seqTime[2];
if(tMaxAcc < maxAccepted) tMaxAcc = maxAccepted;
mItrT.clear();
vItrT.clear();
}
//Static Analysis Time
float avgMAtime = tStatT/(NumBlock*nItertion);
//Miner Sequential Phase Time
float avgMStime = tSeqMT/(NumBlock*nItertion);
//Validator Sequential Phase Time
float avgVStime = tSeqVT/(nItertion*NumBlock*numValidator);
cout<< "Avg Miner Time in microseconds = "
<<(tMiner/nItertion)+avgMStime+avgMAtime;
cout<<"\nAvg Validator Time in microseconds = "
<<(tVal/nItertion)+avgVStime;
cout<<"\n-----------------------------";
cout<<"\nStaic Analysis Time in microseconds = "<<avgMAtime;
cout<<"\nMiner Seq Time in microseconds = "<<avgMStime
<<"\nValidator Seq Time in microseconds = "<<avgVStime;
cout<<"\n-----------------------------";
cout<<"\nAvg Validator Accepted a Block = "
<<(numValidator-(tReject/nItertion));
cout<<"\nAvg Validator Rejcted a Block = "
<<tReject/nItertion;
cout<<"\nMax Validator Accepted any Block = "<<tMaxAcc;
cout<<"\n"<<endl;
mItrT.clear();
vItrT.clear();
delete mTTime;
delete vTTime;
return 0;
}
/*********************MAIN FUN CODE ENDS***********************/
| 30.524138
| 124
| 0.534388
|
Parwatsingh
|
a9181f05a86adc49ff9697c7d7d99a3ef2d7f872
| 939
|
cpp
|
C++
|
src/cpp/uml/signal.cpp
|
nemears/uml-cpp
|
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
|
[
"MIT"
] | null | null | null |
src/cpp/uml/signal.cpp
|
nemears/uml-cpp
|
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
|
[
"MIT"
] | 1
|
2022-02-25T18:14:21.000Z
|
2022-03-10T08:59:55.000Z
|
src/cpp/uml/signal.cpp
|
nemears/uml-cpp
|
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
|
[
"MIT"
] | null | null | null |
#include "uml/signal.h"
#include "uml/interface.h"
#include "uml/operation.h"
#include "uml/manifestation.h"
#include "uml/stereotype.h"
#include "uml/behavior.h"
#include "uml/dataType.h"
#include "uml/association.h"
#include "uml/deployment.h"
using namespace UML;
Set<Property, Signal>& Signal::getOwnedAttributesSet() {
return m_ownedAttributes;
}
void Signal::init() {
m_ownedAttributes.subsets(m_attributes);
m_ownedAttributes.subsets(m_ownedMembers);
m_ownedAttributes.m_signature = &Signal::getOwnedAttributesSet;
}
Signal::Signal() : Element(ElementType::SIGNAL) {
init();
}
Signal::~Signal() {
mountAndRelease();
}
OrderedSet<Property, Signal>& Signal::getOwnedAttributes() {
return m_ownedAttributes;
}
bool Signal::isSubClassOf(ElementType eType) const {
bool ret = Classifier::isSubClassOf(eType);
if (!ret) {
ret = eType == ElementType::SIGNAL;
}
return ret;
}
| 21.837209
| 67
| 0.707135
|
nemears
|
a91a44a393e834ff5c1f02ae15d203733cb04796
| 1,857
|
cpp
|
C++
|
libraries/lnn/src/NeuronInitializer.cpp
|
langelog/lnn
|
aaa6e4847886649ee78337237fbe01521a994136
|
[
"MIT"
] | null | null | null |
libraries/lnn/src/NeuronInitializer.cpp
|
langelog/lnn
|
aaa6e4847886649ee78337237fbe01521a994136
|
[
"MIT"
] | null | null | null |
libraries/lnn/src/NeuronInitializer.cpp
|
langelog/lnn
|
aaa6e4847886649ee78337237fbe01521a994136
|
[
"MIT"
] | null | null | null |
#include "NeuronInitializer.h"
void Initializators::ConstantInitializer(double *weigths, unsigned int n_values, double value) {
for(unsigned int i=0; i<n_values; i++) {
weigths[i] = value;
}
}
void Initializators::NormalDistributionInitializer(double *weights, unsigned int n_values, default_random_engine &randEngine, double mean, double dev) {
normal_distribution<double> dist(mean,dev);
for(unsigned int i=0; i<n_values; i++) {
double val = dist(randEngine);
//std::cout << "Value: " << val << std::endl;
weights[i] = val;
}
}
void** Initializators::ConstantParamsGen(double value) {
void **vals;
double* val = new double;
*val = value;
vals = new void*[1];
vals[0] = (void*)val;
return vals;
}
void** Initializators::GaussParamsGen(default_random_engine &randEngine, double mean, double dev) {
void **vals;
double* val_mean = new double;
double* val_dev = new double;
*val_mean = mean;
*val_dev = dev;
vals = new void*[3];
vals[0] = (void*)&randEngine;
vals[1] = (void*)val_mean;
vals[2] = (void*)val_dev;
return vals;
}
Initializer NeuronInitializer::ConstantInitializer(double value) {
Initializer initer;
initer.init = Initializators::Constant;
initer.initializatorFunction = (void*)&Initializators::ConstantInitializer;
initer.vals = Initializators::ConstantParamsGen(value);
return initer;
}
Initializer NeuronInitializer::NormalInitializer(default_random_engine& randEngine, double mean, double deviation) {
Initializer initer;
initer.init = Initializators::Gauss;
initer.initializatorFunction = (void*)&Initializators::NormalDistributionInitializer;
initer.vals = Initializators::GaussParamsGen(randEngine, mean, deviation);
return initer;
}
| 32.578947
| 152
| 0.677975
|
langelog
|
a91a9d4c6aa6bf35c63cea531c34b537431fd9dc
| 4,583
|
hpp
|
C++
|
3rdparty/stout/include/stout/os/process.hpp
|
zagrev/mesos
|
eefec152dffc4977183089b46fbfe37dbd19e9d7
|
[
"Apache-2.0"
] | 4,537
|
2015-01-01T03:26:40.000Z
|
2022-03-31T03:07:00.000Z
|
3rdparty/stout/include/stout/os/process.hpp
|
zagrev/mesos
|
eefec152dffc4977183089b46fbfe37dbd19e9d7
|
[
"Apache-2.0"
] | 227
|
2015-01-29T02:21:39.000Z
|
2022-03-29T13:35:50.000Z
|
3rdparty/stout/include/stout/os/process.hpp
|
zagrev/mesos
|
eefec152dffc4977183089b46fbfe37dbd19e9d7
|
[
"Apache-2.0"
] | 1,992
|
2015-01-05T12:29:19.000Z
|
2022-03-31T03:07:07.000Z
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_PROCESS_HPP__
#define __STOUT_OS_PROCESS_HPP__
#include <sys/types.h> // For pid_t.
#include <list>
#include <ostream>
#include <sstream>
#include <string>
#include <stout/bytes.hpp>
#include <stout/duration.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/strings.hpp>
namespace os {
struct Process
{
Process(pid_t _pid,
pid_t _parent,
pid_t _group,
const Option<pid_t>& _session,
const Option<Bytes>& _rss,
const Option<Duration>& _utime,
const Option<Duration>& _stime,
const std::string& _command,
bool _zombie)
: pid(_pid),
parent(_parent),
group(_group),
session(_session),
rss(_rss),
utime(_utime),
stime(_stime),
command(_command),
zombie(_zombie) {}
const pid_t pid;
const pid_t parent;
const pid_t group;
const Option<pid_t> session;
const Option<Bytes> rss;
const Option<Duration> utime;
const Option<Duration> stime;
const std::string command;
const bool zombie;
// TODO(bmahler): Add additional data as needed.
bool operator<(const Process& p) const { return pid < p.pid; }
bool operator<=(const Process& p) const { return pid <= p.pid; }
bool operator>(const Process& p) const { return pid > p.pid; }
bool operator>=(const Process& p) const { return pid >= p.pid; }
bool operator==(const Process& p) const { return pid == p.pid; }
bool operator!=(const Process& p) const { return pid != p.pid; }
};
class ProcessTree
{
public:
// Returns a process subtree rooted at the specified PID, or none if
// the specified pid could not be found in this process tree.
Option<ProcessTree> find(pid_t pid) const
{
if (process.pid == pid) {
return *this;
}
foreach (const ProcessTree& tree, children) {
Option<ProcessTree> option = tree.find(pid);
if (option.isSome()) {
return option;
}
}
return None();
}
// Checks if the specified pid is contained in this process tree.
bool contains(pid_t pid) const
{
return find(pid).isSome();
}
operator Process() const
{
return process;
}
operator pid_t() const
{
return process.pid;
}
const Process process;
const std::list<ProcessTree> children;
private:
friend struct Fork;
friend Try<ProcessTree> pstree(pid_t, const std::list<Process>&);
ProcessTree(
const Process& _process,
const std::list<ProcessTree>& _children)
: process(_process),
children(_children) {}
};
inline std::ostream& operator<<(std::ostream& stream, const ProcessTree& tree)
{
if (tree.children.empty()) {
stream << "--- " << tree.process.pid << " ";
if (tree.process.zombie) {
stream << "(" << tree.process.command << ")";
} else {
stream << tree.process.command;
}
} else {
stream << "-+- " << tree.process.pid << " ";
if (tree.process.zombie) {
stream << "(" << tree.process.command << ")";
} else {
stream << tree.process.command;
}
size_t size = tree.children.size();
foreach (const ProcessTree& child, tree.children) {
std::ostringstream out;
out << child;
stream << "\n";
if (--size != 0) {
stream << " |" << strings::replace(out.str(), "\n", "\n |");
} else {
stream << " \\" << strings::replace(out.str(), "\n", "\n ");
}
}
}
return stream;
}
} // namespace os {
// An overload of stringify for printing a list of process trees
// (since printing a process tree is rather particular).
inline std::string stringify(const std::list<os::ProcessTree>& list)
{
std::ostringstream out;
out << "[ " << std::endl;
std::list<os::ProcessTree>::const_iterator iterator = list.begin();
while (iterator != list.end()) {
out << stringify(*iterator);
if (++iterator != list.end()) {
out << std::endl << std::endl;
}
}
out << std::endl << "]";
return out.str();
}
#endif // __STOUT_OS_PROCESS_HPP__
| 25.747191
| 78
| 0.629937
|
zagrev
|
a91afba5e3d5769f6cbf11a9b7c3e59111861360
| 6,578
|
cpp
|
C++
|
src/tools/meddler/meddler.cpp
|
fossabot/metta
|
a5f56403886ddfb93f2262e4f03b49b38bbcce00
|
[
"BSL-1.0"
] | null | null | null |
src/tools/meddler/meddler.cpp
|
fossabot/metta
|
a5f56403886ddfb93f2262e4f03b49b38bbcce00
|
[
"BSL-1.0"
] | null | null | null |
src/tools/meddler/meddler.cpp
|
fossabot/metta
|
a5f56403886ddfb93f2262e4f03b49b38bbcce00
|
[
"BSL-1.0"
] | null | null | null |
//
// Part of Metta OS. Check https://atta-metta.net for latest version.
//
// Copyright 2007 - 2017, Stanislav Karchebnyy <berkus@atta-metta.net>
//
// Distributed under the Boost Software License, Version 1.0.
// (See file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "parser.h"
#include "logger.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/CommandLine.h>
using namespace llvm;
using namespace std;
static cl::opt<string>
inputFilename(cl::Positional, cl::desc("<input .if file>"), cl::init("-"));
static cl::list<string>
includeDirectories("I", cl::Prefix, cl::desc("Include path"), cl::value_desc("directory"), cl::ZeroOrMore);
static cl::opt<bool>
verbose("v", cl::desc("Increase verbosity level."), cl::ZeroOrMore);
static cl::opt<string>
outputDirectory("o", cl::Prefix, cl::desc("Output path"), cl::value_desc("directory"), cl::init("."));
class Meddler
{
llvm::SourceMgr sm;
bool verbose;
vector<parser_t*> parser_stack;
vector<string> include_dirs;
public:
Meddler(bool verbose_) : sm(), verbose(verbose_) {}
void set_include_dirs(vector<string> dirs)
{
include_dirs = dirs;
sm.setIncludeDirs(include_dirs);
}
bool add_source(string file)
{
L(cout << "### Adding file " << file << endl);
std::string full_path;
unsigned bufn = sm.AddIncludeFile(file, llvm::SMLoc(), full_path);
if (bufn == ~0U)
{
cerr << "*** Could not load file " << file << ". Please check that you have spelled the interface name correctly and specified all include paths." << endl;
return false;
}
L(cout << "### Parsing file " << file << endl);
parser_t* parser = new parser_t(sm, verbose);
L(cout << "### Initing parser" << endl);
parser->init(sm.getMemoryBuffer(bufn));
L(cout << "### Adding parser to stack" << endl);
parser_stack.push_back(parser);
return true;
}
bool parse()
{
assert(parser_stack.size() > 0);
bool res = true;
do {
L(cout << "### Running parse" << endl);
res &= parser_stack.at(parser_stack.size()-1)->run();
// Since parent interfaces can only "extend" current interface, we put them into parent interfaces list of current interface
// after parsing and consult them during emit phase for matching types, exceptions and methods - they are considered LOCAL to this
// interface.
if (parser_stack.size() > 1)
{
L(cout << "### Linking interface to parent" << endl);
parser_stack.at(parser_stack.size()-2)->link_to_parent(parser_stack.at(parser_stack.size()-1));
}
if (res && (parser_stack.at(parser_stack.size()-1)->parent_interface() != ""))
{
L(cout << "### Adding another interface file" << endl);
add_source(parser_stack.at(parser_stack.size()-1)->parent_interface() + ".if");
}
L(cout << "### Running another round" << endl);
} while (res && (parser_stack.at(parser_stack.size()-1)->parent_interface() != ""));
L(cout << "### Finished parsing!" << endl);
return res;
}
bool emit(const string& output_dir)
{
ostringstream boilerplate_header;
ostringstream impl_h, interface_h, interface_cpp, typedefs_cpp, filename;
parser_t& parser = *parser_stack[0];
char* user_name = getenv("USER");
char* host_name = getenv("HOSTNAME");
time_t now;
time(&now);
struct tm *current;
current = localtime(&now);
L(cout << "### Generating boilerplate header" << endl);
boilerplate_header << "/*" << endl
<< " * " << parser.parse_tree->name() << " generated";
if (user_name)
boilerplate_header << " by " << user_name;
if (host_name)
boilerplate_header << " at " << host_name;
boilerplate_header << " on " << (1900 + current->tm_year) << "." << (1 + current->tm_mon) << "." << current->tm_mday
<< "T" << current->tm_hour << ":" << current->tm_min << ":" << current->tm_sec << endl;
boilerplate_header << " * AUTOMATICALLY GENERATED FILE, DO NOT EDIT!" << endl
<< " */" << endl
<< endl;
L(cout << "### Emitting impl_h" << endl);
parser.parse_tree->emit_impl_h(impl_h, "");
L(cout << "### Emitting interface_h" << endl);
parser.parse_tree->emit_interface_h(interface_h, "");
L(cout << "### Emitting interface_cpp" << endl);
parser.parse_tree->emit_interface_cpp(interface_cpp, "");
L(cout << "### Emitting type definitions cpp" << endl);
parser.parse_tree->renumber_methods();
parser.parse_tree->emit_typedef_cpp(typedefs_cpp, "");
// todo: boost.filesystem for paths
filename << output_dir << "/" << parser.parse_tree->name() << "_impl.h";
ofstream of(filename.str().c_str(), ios::out|ios::trunc);
of << boilerplate_header.str() << impl_h.str();
of.close();
filename.str("");
filename << output_dir << "/" << parser.parse_tree->name() << "_interface.h";
of.open(filename.str().c_str(), ios::out|ios::trunc);
of << boilerplate_header.str() << interface_h.str();
of.close();
filename.str("");
filename << output_dir << "/" << parser.parse_tree->name() << "_interface.cpp";
of.open(filename.str().c_str(), ios::out|ios::trunc);
of << boilerplate_header.str() << interface_cpp.str();
of.close();
filename.str("");
filename << output_dir << "/" << parser.parse_tree->name() << "_typedefs.cpp";
of.open(filename.str().c_str(), ios::out|ios::trunc);
of << boilerplate_header.str() << typedefs_cpp.str();
of.close();
return true;
}
};
int main(int argc, char** argv)
{
cl::ParseCommandLineOptions(argc, argv, "Meddler - Metta IDL parser.\n");
Meddler m(verbose);
m.set_include_dirs(includeDirectories);
if (!m.add_source(inputFilename))
{
cerr << "Could not open input file " << inputFilename << endl;
return -1;
}
if (m.parse())
{
m.emit(outputDirectory);
}
else
return -1;
return 0;
}
| 35.945355
| 167
| 0.576619
|
fossabot
|
a91c43a60cee2c8f1c25d0e0b7681e155975b0a4
| 612
|
cpp
|
C++
|
src/IVTEntry.cpp
|
shkemilo/milOSke
|
6d2498a65689ee8000818012ebbca7eea3937d12
|
[
"MIT"
] | null | null | null |
src/IVTEntry.cpp
|
shkemilo/milOSke
|
6d2498a65689ee8000818012ebbca7eea3937d12
|
[
"MIT"
] | null | null | null |
src/IVTEntry.cpp
|
shkemilo/milOSke
|
6d2498a65689ee8000818012ebbca7eea3937d12
|
[
"MIT"
] | 1
|
2021-09-02T13:14:35.000Z
|
2021-09-02T13:14:35.000Z
|
/*
* IVTEntry.cpp
*
* Created on: Sep 13, 2020
* Author: OS1
*/
#include "IVTEntry.h"
#include "Kernel.h"
#include "KernelEv.h"
IVTEntry* IVTEntry::ivtEntires[] = { 0 };
IVTEntry* IVTEntry::getEntry(IVTNo ivtNo) {
return ivtEntires[ivtNo];
}
IVTEntry::IVTEntry(IVTNo ivtNo, InterruptRoutine newRoutine) : ivtNo(ivtNo), event(0), oldRoutine(newRoutine) {
ivtEntires[ivtNo] = this;
}
IVTEntry::~IVTEntry() {
ivtEntires[ivtNo] = 0;
}
void IVTEntry::signal() {
if(event) {
event->signal();
}
}
void IVTEntry::callOldRoutine() {
if(oldRoutine) {
lock();
oldRoutine();
unlock();
}
}
| 14.926829
| 111
| 0.651961
|
shkemilo
|
a91f25812953f6b33e2391becd216c7a429b68f7
| 555
|
cpp
|
C++
|
Codechef/JewelStones.cpp
|
aajjbb/contest-files
|
b8842681b96017063a7baeac52ae1318bf59d74d
|
[
"Apache-2.0"
] | 1
|
2018-08-28T19:58:40.000Z
|
2018-08-28T19:58:40.000Z
|
Codechef/JewelStones.cpp
|
aajjbb/contest-files
|
b8842681b96017063a7baeac52ae1318bf59d74d
|
[
"Apache-2.0"
] | 2
|
2017-04-16T00:48:05.000Z
|
2017-08-03T20:12:26.000Z
|
Codechef/JewelStones.cpp
|
aajjbb/contest-files
|
b8842681b96017063a7baeac52ae1318bf59d74d
|
[
"Apache-2.0"
] | 4
|
2016-03-04T19:42:00.000Z
|
2018-01-08T11:42:00.000Z
|
#include <iostream>
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int T, lenJ, lenS;
string s, j;
int main(void) {
cin >> T;
while(T--) {
cin >> j >> s;
map<char, int> ct;
for(int i = 0; i < j.size(); i++) {
ct[j[i]] += 1;
}
int ans = 0;
for(int i = 0; i < s.size(); i++) {
if(ct[s[i]] > 0) {
ans += 1;
}
}
cout << ans << endl;
}
return 0;
}
| 18.5
| 44
| 0.381982
|
aajjbb
|
a91f5eae1d62155313a958230e905ffee7110b9a
| 2,395
|
cpp
|
C++
|
OpenCVDemo/sobel_edge.cpp
|
sumandeepb/OpenCVDemo2.4
|
0a1d4ef6cef913a5bc3de928327a1678794fcf8e
|
[
"Apache-2.0"
] | null | null | null |
OpenCVDemo/sobel_edge.cpp
|
sumandeepb/OpenCVDemo2.4
|
0a1d4ef6cef913a5bc3de928327a1678794fcf8e
|
[
"Apache-2.0"
] | null | null | null |
OpenCVDemo/sobel_edge.cpp
|
sumandeepb/OpenCVDemo2.4
|
0a1d4ef6cef913a5bc3de928327a1678794fcf8e
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2012-2018 Sumandeep Banerjee, sumandeep.banerjee@gmail.com
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 <opencv2\opencv.hpp> //OpenCV library of IP functions
void sobel_edge_demo ()
{
//declare image buffer pointers
IplImage *pImage, *pSobelXImage, *pSobelYImage, *pOutXImage, *pOutYImage;
// create display windows
cvNamedWindow ("Input");
cvNamedWindow ("Sobel X");
cvNamedWindow ("Sobel Y");
// load image as grayscale
pImage = cvLoadImage ("input/lena_grey.bmp", CV_LOAD_IMAGE_GRAYSCALE);
cvShowImage ("Input", pImage);
// allocate memory buffer for output of same size as input
pOutXImage = cvCreateImage (cvGetSize(pImage), pImage->depth, pImage->nChannels);
pOutYImage = cvCreateImage (cvGetSize(pImage), pImage->depth, pImage->nChannels);
// sobel operator may produce -ve pixel values, therefore it requires 32bit floating images for temporary storage
pSobelXImage = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_32F, pImage->nChannels);
pSobelYImage = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_32F, pImage->nChannels);
// perform sobel edge detection
cvSobel (pImage, pSobelXImage, 1, 0);
cvSobel (pImage, pSobelYImage, 0, 1);
// convert sobel output back to 8bit grayscale image
cvConvert (pSobelXImage, pOutXImage);
cvConvert (pSobelYImage, pOutYImage);
// show output
cvShowImage ("Sobel X", pOutXImage);
cvShowImage ("Sobel Y", pOutYImage);
// save output
cvSaveImage ("output/sobelx.bmp", pOutXImage);
cvSaveImage ("output/sobely.bmp", pOutYImage);
// wait till key press
cvWaitKey (0);
// release memory
cvReleaseImage (&pImage);
cvReleaseImage (&pOutXImage);
cvReleaseImage (&pOutYImage);
cvReleaseImage (&pSobelXImage);
cvReleaseImage (&pSobelYImage);
// destroy gui windows
cvDestroyAllWindows ();
}
| 34.214286
| 115
| 0.721921
|
sumandeepb
|
a91fbb85a53efdf53fc96181a577fc97d870379b
| 11,058
|
cpp
|
C++
|
TripPrep/Read_Activity.cpp
|
kravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | 2
|
2018-04-27T11:07:02.000Z
|
2020-04-24T06:53:21.000Z
|
TripPrep/Read_Activity.cpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
TripPrep/Read_Activity.cpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
//*********************************************************
// Read_Activity.cpp - Read the Activity File
//*********************************************************
#include "TripPrep.hpp"
//---------------------------------------------------------
// Read_Activity
//---------------------------------------------------------
bool TripPrep::Read_Activity (int file_num)
{
int last_hhold, last_person, hhold, person, purpose, mode, start, end, origin, destination;
int time1, time2, num_kept, num_out, count, vehicle, *parking, nparking, pass;
int next_in, next_merge, replace_id, last_keep;
bool flag, read_merge, read_in, save_merge, keep;
Activity_File *activity_file, *new_file;
Trip_File *trip_file, *in_file;
Vehicle_File *veh_file;
Vehicle_Data *veh_ptr;
Location_Data *loc_ptr;
Access_Data *acc_ptr;
activity_file = (Activity_File *) Demand_Db_Base (ACTIVITY);
in_file = (Trip_File *) Demand_Db_Base (TRIP);
nparking = 0;
parking = 0;
if (file_num > 0) {
if (!split_flag) {
if (!activity_file->Open (file_num)) return (false);
} else {
activity_file->Rewind ();
}
if (hhlist_flag && hhlist_file.Extend ()) {
if (!Household_List (file_num)) {
if (split_flag) return (false);
Error ("Opening %s", hhlist_file.File_Type ());
}
}
}
if (output_flag) {
new_file = (Activity_File *) Demand_Db_Base (NEW_ACTIVITY);
if (file_num > 0) {
if (new_file->Extend ()) {
if (!new_file->Open (file_num)) {
Error ("Creating %s", new_file->File_Type ());
}
}
if (prob_flag && newhh_flag && newhh_file.Extend ()) {
if (!newhh_file.Open (file_num)) {
Error ("Opening %s", newhh_file.File_Type ());
}
}
if (merge_act_flag && merge_act_file.Extend ()) {
if (!merge_act_file.Open (file_num)) {
Error ("Opening %s", merge_act_file.File_Type ());
}
}
}
}
if (create_flag || convert_flag) {
trip_file = (Trip_File *) Demand_Db_Base (NEW_TRIP);
if (file_num > 0 && trip_file->Extend ()) {
if (!trip_file->Open (file_num)) {
Error ("Creating %s", trip_file->File_Type ());
}
}
if (create_flag) {
veh_file = (Vehicle_File *) Demand_Db_Base (NEW_VEHICLE);
if (file_num > 0) {
if (newhh_flag && newhh_file.Extend ()) {
if (!newhh_file.Open (file_num)) {
Error ("Opening %s", newhh_file.File_Type ());
}
fprintf (newhh_file.File (), "HHOLD\tOLDHH\n");
}
} else if (newhh_flag) {
fprintf (newhh_file.File (), "HHOLD\tOLDHH\n");
}
//---- build the parking map ----
loc_ptr = location_data.Last ();
nparking = loc_ptr->Location () + 1;
parking = new int [nparking];
memset (parking, '\0', nparking * sizeof (int));
for (acc_ptr = access_data.First (); acc_ptr; acc_ptr = access_data.Next ()) {
if (acc_ptr->From_Type () == LOCATION_ID && acc_ptr->To_Type () == PARKING_ID) {
parking [acc_ptr->From_ID ()] = acc_ptr->To_ID ();
}
}
}
}
//---- process each trip ----
if (merge_act_flag) {
if (activity_file->Extend ()) {
Show_Message ("Merging %s %s -- Record", activity_file->File_Type (), activity_file->Extension ());
} else {
Show_Message ("Merging %s -- Record", activity_file->File_Type ());
}
if (merge_act_file.Read ()) {
next_merge = merge_act_file.Household ();
} else {
next_merge = MAX_INTEGER;
}
} else {
if (activity_file->Extend ()) {
Show_Message ("Reading %s %s -- Record", activity_file->File_Type (), activity_file->Extension ());
} else {
Show_Message ("Reading %s -- Record", activity_file->File_Type ());
}
next_merge = MAX_INTEGER;
}
Set_Progress (10000);
last_hhold = last_person = num_kept = num_out = replace_id = last_keep = 0;
read_merge = read_in = save_merge = false;
count = 1;
flag = true;
if (activity_file->Read ()) {
next_in = activity_file->Household ();
} else {
next_in = MAX_INTEGER;
}
//---- process each record ----
while (next_in != MAX_INTEGER || next_merge != MAX_INTEGER) {
Show_Progress ();
//---- set the processing flags ----
if (next_merge < next_in) {
if (next_merge == replace_id) {
save_merge = false;
} else {
save_merge = true;
}
read_merge = true;
read_in = false;
} else {
hhold = activity_file->Household ();
if (hhlist_flag && hhold_list.Get_Index (hhold) == 0) {
if (all_flag) {
new_file->Copy_Fields (activity_file);
flag = false;
if (!new_file->Write ()) {
Error ("Writing %s", new_file->File_Type ());
}
num_out++;
keep = true;
replace_id = next_in;
} else {
keep = false;
}
} else {
person = activity_file->Person ();
purpose = activity_file->Purpose ();
mode = activity_file->Mode ();
vehicle = activity_file->Vehicle ();
destination = activity_file->Location ();
time1 = time_periods.Step (activity_file->Start_Min ());
time2 = time_periods.Step (activity_file->Start_Max ());
if (time1 < 0 || time2 < 0) {
Error ("Converting Start Time for Household %d", hhold);
}
end = (time1 + time2 + 1) / 2;
if (hhold == last_hhold && person == last_person) {
flag = Trip_Check (hhold, origin, destination, start, end, mode, purpose, vehicle);
if (flag) {
if (create_flag) {
trip_file->Household (hhold_id);
trip_file->Person (person);
trip_file->Trip (activity_file->Activity ());
trip_file->Purpose (purpose);
pass = activity_file->Passengers ();
if (mode == DRIVE_ALONE) {
if (pass > 2) {
mode = CARPOOL4;
} else if (pass > 1) {
mode = CARPOOL3;
} else if (pass > 0) {
mode = CARPOOL2;
}
} else if (mode == CARPOOL2 || mode == CARPOOL3 || mode == CARPOOL4) {
mode = MAGIC_MOVE;
}
trip_file->Mode (mode);
trip_file->Start (time_periods.Format_Step (start));
trip_file->Origin (origin);
trip_file->Arrive (time_periods.Format_Step (end));
trip_file->Destination (destination);
trip_file->Constraint (activity_file->Constraint ());
if (vehicle > 0) {
trip_file->Vehicle (veh_id);
veh_ptr = vehicle_data.Get (vehicle);
if (veh_ptr != NULL && origin < nparking) {
veh_file->Vehicle (veh_id);
veh_file->Household (hhold_id);
veh_file->Location (parking [origin]);
veh_file->Type (veh_ptr->Type ());
veh_file->Sub_Type (veh_ptr->Sub_Type ());
if (!veh_file->Write ()) {
Error ("Writing %s", veh_file->File_Type ());
}
}
veh_id++;
} else {
trip_file->Vehicle (vehicle);
}
if (!trip_file->Write ()) {
Error ("Writing %s", trip_file->File_Type ());
}
if (newhh_flag) {
fprintf (newhh_file.File (), "%d\t%d\n", hhold_id, hhold);
}
hhold_id++;
} else if (convert_flag) {
trip_file->Household (hhold);
trip_file->Person (person);
trip_file->Trip (activity_file->Activity ());
trip_file->Purpose (purpose);
pass = activity_file->Passengers ();
if (mode == DRIVE_ALONE) {
if (pass > 2) {
mode = CARPOOL4;
} else if (pass > 1) {
mode = CARPOOL3;
} else if (pass > 0) {
mode = CARPOOL2;
}
} else if (mode == CARPOOL2 || mode == CARPOOL3 || mode == CARPOOL4) {
mode = MAGIC_MOVE;
}
trip_file->Mode (mode);
trip_file->Start (time_periods.Format_Step (start));
trip_file->Origin (origin);
trip_file->Arrive (time_periods.Format_Step (end));
trip_file->Destination (destination);
trip_file->Constraint (activity_file->Constraint ());
trip_file->Vehicle (vehicle);
if (!trip_file->Write ()) {
Error ("Writing %s", trip_file->File_Type ());
}
}
}
} else {
flag = Trip_Check (hhold, origin, destination, start, end, mode, purpose, vehicle);
}
origin = destination;
time1 = time_periods.Step (activity_file->End_Min ());
time2 = time_periods.Step (activity_file->End_Max ());
if (time1 < 0 || time2 < 0) {
Error ("Converting End Time for Household %d", hhold);
}
start = (time1 + time2 + 1) / 2;
last_hhold = hhold;
last_person = person;
if ((flag || all_flag) && output_flag) {
new_file->Copy_Fields (activity_file);
if (script_flag) {
if (trip_flag) {
in_file->Reset_Record ();
}
keep = (program.Execute () != 0);
} else {
keep = flag;
}
if (keep || all_flag) {
if (flag && keep) {
num_kept++;
if (newhh_flag && hhold != last_keep) {
fprintf (newhh_file.File (), "%d\n", hhold);
last_keep = hhold;
}
}
if (!new_file->Write ()) {
Error ("Writing %s", new_file->File_Type ());
}
num_out++;
}
}
}
if (next_merge == next_in) {
if (flag) {
replace_id = next_in;
save_merge = false;
} else {
save_merge = true;
}
read_merge = read_in = true;
} else {
read_in = true;
read_merge = save_merge = false;
}
}
//---- write the merge activity to the output file ----
if (save_merge) {
vehicle = merge_act_file.Vehicle ();
if (vehicle_list.Get_Index (vehicle) == 0) {
if (!vehicle_list.Add (vehicle)) {
Error ("Adding Vehicle %d to the List", vehicle);
}
}
if (output_flag) {
new_file->Copy_Fields (&merge_act_file);
if (script_flag) {
if (trip_flag) {
in_file->Reset_Record ();
}
keep = (program.Execute () != 0);
} else {
keep = true;
}
if (keep) {
if (!new_file->Write ()) {
Error ("Writing %s", new_file->File_Type ());
}
num_out++;
}
}
}
//---- get the next merge activity ----
if (read_merge) {
if (merge_act_file.Read ()) {
next_merge = merge_act_file.Household ();
} else {
next_merge = MAX_INTEGER;
}
}
//---- get the next input activity ----
if (read_in) {
if (activity_file->Read ()) {
next_in = activity_file->Household ();
} else {
next_in = MAX_INTEGER;
}
}
}
End_Progress ();
if (file_num == 0 || !split_flag) {
total_in += Progress_Count ();
}
if (activity_file->Extend ()) {
Print (2, "Number of Activity Records Read from %s = %d", activity_file->Extension (), Progress_Count ());
} else {
Print (2, "Number of Activity Records Read = %d", Progress_Count ());
}
if (output_flag) {
total_out += num_out;
if (new_file->Extend ()) {
Print (1, "Number of Activity Records Written to %s = %d", new_file->Extension (), num_out);
} else {
Print (1, "Number of Activity Records Written = %d", num_out);
}
}
total_used += num_kept;
if (prob_flag) {
Print (1, "Number of Activity Records Selected = %d", num_kept);
if (num_out > 0) Print (0, " (%.1lf%%)", 100.0 * num_kept / num_out);
}
if (nparking > 0 && parking) {
delete [] parking;
}
return (true);
}
| 27.036675
| 108
| 0.570356
|
kravitz
|
a9222c686d83fb4dd6644b7109300184a01ede33
| 8,628
|
cc
|
C++
|
src/QmlControls/QmlObjectListModel.cc
|
uav-operation-system/qgroundcontrol
|
c24029938e88d7a45a04f4e4e64bf588f595afed
|
[
"Apache-2.0"
] | 2,133
|
2015-01-04T03:10:22.000Z
|
2022-03-31T01:51:07.000Z
|
src/QmlControls/QmlObjectListModel.cc
|
uav-operation-system/qgroundcontrol
|
c24029938e88d7a45a04f4e4e64bf588f595afed
|
[
"Apache-2.0"
] | 6,166
|
2015-01-02T18:47:42.000Z
|
2022-03-31T03:44:10.000Z
|
src/QmlControls/QmlObjectListModel.cc
|
uav-operation-system/qgroundcontrol
|
c24029938e88d7a45a04f4e4e64bf588f595afed
|
[
"Apache-2.0"
] | 2,980
|
2015-01-01T03:09:18.000Z
|
2022-03-31T04:13:55.000Z
|
/****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "QmlObjectListModel.h"
#include <QDebug>
#include <QQmlEngine>
const int QmlObjectListModel::ObjectRole = Qt::UserRole;
const int QmlObjectListModel::TextRole = Qt::UserRole + 1;
QmlObjectListModel::QmlObjectListModel(QObject* parent)
: QAbstractListModel (parent)
, _dirty (false)
, _skipDirtyFirstItem (false)
, _externalBeginResetModel (false)
{
}
QmlObjectListModel::~QmlObjectListModel()
{
}
QObject* QmlObjectListModel::get(int index)
{
if (index < 0 || index >= _objectList.count()) {
return nullptr;
}
return _objectList[index];
}
int QmlObjectListModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return _objectList.count();
}
QVariant QmlObjectListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (index.row() < 0 || index.row() >= _objectList.count()) {
return QVariant();
}
if (role == ObjectRole) {
return QVariant::fromValue(_objectList[index.row()]);
} else if (role == TextRole) {
return QVariant::fromValue(_objectList[index.row()]->objectName());
} else {
return QVariant();
}
}
QHash<int, QByteArray> QmlObjectListModel::roleNames(void) const
{
QHash<int, QByteArray> hash;
hash[ObjectRole] = "object";
hash[TextRole] = "text";
return hash;
}
bool QmlObjectListModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (index.isValid() && role == ObjectRole) {
_objectList.replace(index.row(), value.value<QObject*>());
emit dataChanged(index, index);
return true;
}
return false;
}
bool QmlObjectListModel::insertRows(int position, int rows, const QModelIndex& parent)
{
Q_UNUSED(parent);
if (position < 0 || position > _objectList.count() + 1) {
qWarning() << "Invalid position position:count" << position << _objectList.count();
}
beginInsertRows(QModelIndex(), position, position + rows - 1);
endInsertRows();
emit countChanged(count());
return true;
}
bool QmlObjectListModel::removeRows(int position, int rows, const QModelIndex& parent)
{
Q_UNUSED(parent);
if (position < 0 || position >= _objectList.count()) {
qWarning() << "Invalid position position:count" << position << _objectList.count();
} else if (position + rows > _objectList.count()) {
qWarning() << "Invalid rows position:rows:count" << position << rows << _objectList.count();
}
beginRemoveRows(QModelIndex(), position, position + rows - 1);
for (int row=0; row<rows; row++) {
_objectList.removeAt(position);
}
endRemoveRows();
emit countChanged(count());
return true;
}
void QmlObjectListModel::move(int from, int to)
{
if(0 <= from && from < count() && 0 <= to && to < count() && from != to) {
// Workaround to allow move item to the bottom. Done according to
// beginMoveRows() documentation and implementation specificity:
// https://doc.qt.io/qt-5/qabstractitemmodel.html#beginMoveRows
// (see 3rd picture explanation there)
if(from == to - 1) {
to = from++;
}
beginMoveRows(QModelIndex(), from, from, QModelIndex(), to);
_objectList.move(from, to);
endMoveRows();
}
}
QObject* QmlObjectListModel::operator[](int index)
{
if (index < 0 || index >= _objectList.count()) {
return nullptr;
}
return _objectList[index];
}
const QObject* QmlObjectListModel::operator[](int index) const
{
if (index < 0 || index >= _objectList.count()) {
return nullptr;
}
return _objectList[index];
}
void QmlObjectListModel::clear()
{
if (!_externalBeginResetModel) {
beginResetModel();
}
_objectList.clear();
if (!_externalBeginResetModel) {
endResetModel();
emit countChanged(count());
}
}
QObject* QmlObjectListModel::removeAt(int i)
{
QObject* removedObject = _objectList[i];
if(removedObject) {
// Look for a dirtyChanged signal on the object
if (_objectList[i]->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) {
if (!_skipDirtyFirstItem || i != 0) {
QObject::disconnect(_objectList[i], SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool)));
}
}
}
removeRows(i, 1);
setDirty(true);
return removedObject;
}
void QmlObjectListModel::insert(int i, QObject* object)
{
if (i < 0 || i > _objectList.count()) {
qWarning() << "Invalid index index:count" << i << _objectList.count();
}
if(object) {
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
// Look for a dirtyChanged signal on the object
if (object->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) {
if (!_skipDirtyFirstItem || i != 0) {
QObject::connect(object, SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool)));
}
}
}
_objectList.insert(i, object);
insertRows(i, 1);
setDirty(true);
}
void QmlObjectListModel::insert(int i, QList<QObject*> objects)
{
if (i < 0 || i > _objectList.count()) {
qWarning() << "Invalid index index:count" << i << _objectList.count();
}
int j = i;
for (QObject* object: objects) {
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
// Look for a dirtyChanged signal on the object
if (object->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) {
if (!_skipDirtyFirstItem || j != 0) {
QObject::connect(object, SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool)));
}
}
j++;
_objectList.insert(j, object);
}
insertRows(i, objects.count());
setDirty(true);
}
void QmlObjectListModel::append(QObject* object)
{
insert(_objectList.count(), object);
}
void QmlObjectListModel::append(QList<QObject*> objects)
{
insert(_objectList.count(), objects);
}
QObjectList QmlObjectListModel::swapObjectList(const QObjectList& newlist)
{
QObjectList oldlist(_objectList);
if (!_externalBeginResetModel) {
beginResetModel();
}
_objectList = newlist;
if (!_externalBeginResetModel) {
endResetModel();
emit countChanged(count());
}
return oldlist;
}
int QmlObjectListModel::count() const
{
return rowCount();
}
void QmlObjectListModel::setDirty(bool dirty)
{
if (_dirty != dirty) {
_dirty = dirty;
if (!dirty) {
// Need to clear dirty from all children
for(QObject* object: _objectList) {
if (object->property("dirty").isValid()) {
object->setProperty("dirty", false);
}
}
}
emit dirtyChanged(_dirty);
}
}
void QmlObjectListModel::_childDirtyChanged(bool dirty)
{
_dirty |= dirty;
// We want to emit dirtyChanged even if the actual value of _dirty didn't change. It can be a useful
// signal to know when a child has changed dirty state
emit dirtyChanged(_dirty);
}
void QmlObjectListModel::deleteListAndContents()
{
for (int i=0; i<_objectList.count(); i++) {
_objectList[i]->deleteLater();
}
deleteLater();
}
void QmlObjectListModel::clearAndDeleteContents()
{
beginResetModel();
for (int i=0; i<_objectList.count(); i++) {
_objectList[i]->deleteLater();
}
clear();
endResetModel();
}
void QmlObjectListModel::beginReset()
{
if (_externalBeginResetModel) {
qWarning() << "QmlObjectListModel::beginReset already set";
}
_externalBeginResetModel = true;
beginResetModel();
}
void QmlObjectListModel::endReset()
{
if (!_externalBeginResetModel) {
qWarning() << "QmlObjectListModel::endReset begin not set";
}
_externalBeginResetModel = false;
endResetModel();
}
| 26.878505
| 120
| 0.6137
|
uav-operation-system
|
a9228b75912aec7497a8c3d41725d5f40d5cca6c
| 2,163
|
cpp
|
C++
|
src/tolua/LuaImGui.cpp
|
TerensTare/tnt
|
916067a9bf697101afb1d0785112aa34014e8126
|
[
"MIT"
] | 29
|
2020-04-22T01:31:30.000Z
|
2022-02-03T12:21:29.000Z
|
src/tolua/LuaImGui.cpp
|
TerensTare/tnt
|
916067a9bf697101afb1d0785112aa34014e8126
|
[
"MIT"
] | 6
|
2020-04-17T10:31:56.000Z
|
2021-09-10T12:07:22.000Z
|
src/tolua/LuaImGui.cpp
|
TerensTare/tnt
|
916067a9bf697101afb1d0785112aa34014e8126
|
[
"MIT"
] | 7
|
2020-03-13T01:50:41.000Z
|
2022-03-06T23:44:29.000Z
|
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
#include <sol/sol.hpp>
#include "tolua/LuaImGui.hpp"
#include "imgui/ImGui.hpp"
void tnt::lua::loadImGui(sol::state_view lua_)
{
auto imgui{lua_["imgui"].get_or_create<sol::table>()};
imgui.new_enum("win_flags",
"colapsible", ImGui::WindowFlags::Collapsible,
"closable", ImGui::WindowFlags::Closable,
"resizable", ImGui::WindowFlags::Resizable,
"movable", ImGui::WindowFlags::Movable,
"with_titlebar", ImGui::WindowFlags::WithTitleBar,
"opaque_bg", ImGui::WindowFlags::OpaqueBackground,
"widget_first", ImGui::WindowFlags::WidgetThenText);
imgui["init"] = &tnt_imgui_init;
imgui["Begin"] = sol::overload(
[](Window const &win, std::string_view name, int x, int y) -> bool {
return ImGui::Begin(win, name, x, y);
},
&ImGui::Begin);
imgui["End"] = &ImGui::End;
imgui["begin_section"] = &ImGui::BeginSection;
imgui["end_section"] = &ImGui::EndSection;
imgui["begin_list"] = &ImGui::BeginList;
imgui["list_item"] = &ImGui::list_item;
imgui["end_list"] = &ImGui::EndList;
imgui["begin_menubar"] = &ImGui::BeginMenuBar;
imgui["menu_button"] = &ImGui::menu_button;
imgui["menu_item"] = &ImGui::menu_item;
imgui["end_menubar"] = &ImGui::EndMenuBar;
imgui["button"] = &ImGui::button;
imgui["slider_int"] = &ImGui::slider_int;
imgui["slider_float"] = &ImGui::slider_float;
imgui["hslider_int"] = &ImGui::hslider_int;
imgui["hslider_float"] = &ImGui::hslider_float;
imgui["hslider_int2"] = &ImGui::hslider_int2;
imgui["hslider_float2"] = &ImGui::hslider_float2;
imgui["hslider_vec"] = &ImGui::hslider_vec;
imgui["checkbox"] = &ImGui::checkbox;
imgui["progress_bar"] = &ImGui::progress_bar;
imgui["newline"] = &ImGui::newline;
imgui["text"] = &ImGui::text;
imgui["colored_text"] = &ImGui::colored_text;
}
| 35.459016
| 95
| 0.624595
|
TerensTare
|
a92358f715e6bc27322c4ed3375e2219084b6983
| 5,634
|
hpp
|
C++
|
src/mlpack/core/dists/laplace_distribution.hpp
|
KimSangYeon-DGU/mlpack
|
defa29791f43d3372b019f552134abc39def234a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
src/mlpack/core/dists/laplace_distribution.hpp
|
KimSangYeon-DGU/mlpack
|
defa29791f43d3372b019f552134abc39def234a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
src/mlpack/core/dists/laplace_distribution.hpp
|
KimSangYeon-DGU/mlpack
|
defa29791f43d3372b019f552134abc39def234a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2020-06-05T13:27:26.000Z
|
2020-06-23T09:44:31.000Z
|
/*
* @file core/dists/laplace_distribution.hpp
* @author Zhihao Lou
* @author Rohan Raj
*
* Laplace (double exponential) distribution used in SA.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_CORE_DISTRIBUTIONS_LAPLACE_DISTRIBUTION_HPP
#define MLPACK_CORE_DISTRIBUTIONS_LAPLACE_DISTRIBUTION_HPP
namespace mlpack {
namespace distribution {
/**
* The multivariate Laplace distribution centered at 0 has pdf
*
* \f[
* f(x|\theta) = \frac{1}{2 \theta}\exp\left(-\frac{\|x - \mu\|}{\theta}\right)
* \f]
*
* given scale parameter \f$\theta\f$ and mean \f$\mu\f$. This implementation
* assumes a diagonal covariance, but a rewrite to support arbitrary
* covariances is possible.
*
* See the following paper for more information on the non-diagonal-covariance
* Laplace distribution and estimation techniques:
*
* @code
* @article{eltoft2006multivariate,
* title={{On the Multivariate Laplace Distribution}},
* author={Eltoft, Torbj\orn and Kim, Taesu and Lee, Te-Won},
* journal={IEEE Signal Processing Letters},
* volume={13},
* number={5},
* pages={300--304},
* year={2006}
* }
* @endcode
*
* Note that because of the diagonal covariance restriction, much of the
* algebra in the paper above becomes simplified, and the PDF takes roughly
* the same form as the univariate case.
*/
class LaplaceDistribution
{
public:
/**
* Default constructor, which creates a Laplace distribution with zero
* dimension and zero scale parameter.
*/
LaplaceDistribution() : scale(0) { }
/**
* Construct the Laplace distribution with the given scale and
* dimensionality. The mean is initialized to zero.
*
* @param dimensionality Dimensionality of distribution.
* @param scale Scale of distribution.
*/
LaplaceDistribution(const size_t dimensionality, const double scale) :
mean(arma::zeros<arma::vec>(dimensionality)), scale(scale) { }
/**
* Construct the Laplace distribution with the given mean and scale
* parameter.
*
* @param mean Mean of distribution.
* @param scale Scale of distribution.
*/
LaplaceDistribution(const arma::vec& mean, const double scale) :
mean(mean), scale(scale) { }
//! Return the dimensionality of this distribution.
size_t Dimensionality() const { return mean.n_elem; }
/**
* Return the probability of the given observation.
*
* @param observation Point to evaluate probability at.
*/
double Probability(const arma::vec& observation) const
{
return exp(LogProbability(observation));
}
/**
* Evaluate probability density function of given observation.
*
* @param x List of observations.
* @param probabilities Output probabilities for each input observation.
*/
void Probability(const arma::mat& x, arma::vec& probabilities) const;
/**
* Return the log probability of the given observation.
*
* @param observation Point to evaluate logarithm of probability.
*/
double LogProbability(const arma::vec& observation) const;
/**
* Evaluate log probability density function of given observation.
*
* @param x List of observations.
* @param logProbabilities Output probabilities for each input observation.
*/
void LogProbability(const arma::mat& x, arma::vec& logProbabilities) const
{
logProbabilities.set_size(x.n_cols);
for (size_t i = 0; i < x.n_cols; i++)
{
logProbabilities(i) = LogProbability(x.unsafe_col(i));
}
}
/**
* Return a randomly generated observation according to the probability
* distribution defined by this object. This is inlined for speed.
*
* @return Random observation from this Laplace distribution.
*/
arma::vec Random() const
{
arma::vec result(mean.n_elem);
result.randu();
// Convert from uniform distribution to Laplace distribution.
// arma::sign() does not exist in Armadillo < 3.920 so we have to do this
// elementwise.
for (size_t i = 0; i < result.n_elem; ++i)
{
if (result[i] < 0.5)
result[i] = mean[i] + scale * std::log(1 + 2.0 * (result[i] - 0.5));
else
result[i] = mean[i] - scale * std::log(1 - 2.0 * (result[i] - 0.5));
}
return result;
}
/**
* Estimate the Laplace distribution directly from the given observations.
*
* @param observations List of observations.
*/
void Estimate(const arma::mat& observations);
/**
* Estimate the Laplace distribution from the given observations, taking into
* account the probability of each observation actually being from this
* distribution.
*/
void Estimate(const arma::mat& observations,
const arma::vec& probabilities);
//! Return the mean.
const arma::vec& Mean() const { return mean; }
//! Modify the mean.
arma::vec& Mean() { return mean; }
//! Return the scale parameter.
double Scale() const { return scale; }
//! Modify the scale parameter.
double& Scale() { return scale; }
/**
* Serialize the distribution.
*/
template<typename Archive>
void serialize(Archive& ar, const unsigned int /* version */)
{
ar & BOOST_SERIALIZATION_NVP(mean);
ar & BOOST_SERIALIZATION_NVP(scale);
}
private:
//! Mean of the distribution.
arma::vec mean;
//! Scale parameter of the distribution.
double scale;
};
} // namespace distribution
} // namespace mlpack
#endif
| 29.19171
| 79
| 0.682464
|
KimSangYeon-DGU
|
a92473dcfc041be42ed1281ed2d4ee8cd47660e6
| 1,259
|
cpp
|
C++
|
project/Harman_T500/idlecurrentpage.cpp
|
happyrabbit456/Qt5_dev
|
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
|
[
"MIT"
] | null | null | null |
project/Harman_T500/idlecurrentpage.cpp
|
happyrabbit456/Qt5_dev
|
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
|
[
"MIT"
] | null | null | null |
project/Harman_T500/idlecurrentpage.cpp
|
happyrabbit456/Qt5_dev
|
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
|
[
"MIT"
] | null | null | null |
#include "idlecurrentpage.h"
#include <QGridLayout>
#include <QVBoxLayout>
#include "testform.h"
#include "currentform.h"
#include "mainwindow.h"
IdleCurrentPage::IdleCurrentPage(QWidget *parent)
{
currentForm=qobject_cast<TestForm*>(parent);
// setTitle(QString::fromLocal8Bit("关机电流测试"));
QFont font;
font.setPointSize(11);
QLabel *label = new QLabel(QString::fromLocal8Bit("二维码扫描操作完成了,现在请准备好关机电流测试,然后点击测试按钮,开始测试。"));
label->setWordWrap(true);
label->setFont(font);
setButtonText(QWizard::NextButton,QString::fromLocal8Bit("测试"));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(label);
setLayout(layout);
}
bool IdleCurrentPage::validatePage()
{
TestForm* pCurrentForm=static_cast<TestForm*>(currentForm);
MainWindow *pMainWindow=MainWindow::getMainWindow();
string value;
pCurrentForm->appendMessagebox(tr("The idle current test begin to test ......"));
pMainWindow->m_niVisaGPIB.reset();
// pMainWindow->m_niVisaGPIB.autoZero(true);
bool bGetCurrent=pMainWindow->m_niVisaGPIB.getCurrent(value);
if(bGetCurrent){
bool bUpdate=pCurrentForm->updateIdleCurrent(true,value);
if(bUpdate){
return true;
}
}
return false;
}
| 25.693878
| 97
| 0.702145
|
happyrabbit456
|
a926983810a119de6841da246c3b28ec38d4e45e
| 880
|
cpp
|
C++
|
android-30/javax/xml/xpath/XPathFactoryConfigurationException.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/javax/xml/xpath/XPathFactoryConfigurationException.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/javax/xml/xpath/XPathFactoryConfigurationException.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../../JString.hpp"
#include "../../../JThrowable.hpp"
#include "./XPathFactoryConfigurationException.hpp"
namespace javax::xml::xpath
{
// Fields
// QJniObject forward
XPathFactoryConfigurationException::XPathFactoryConfigurationException(QJniObject obj) : javax::xml::xpath::XPathException(obj) {}
// Constructors
XPathFactoryConfigurationException::XPathFactoryConfigurationException(JString arg0)
: javax::xml::xpath::XPathException(
"javax.xml.xpath.XPathFactoryConfigurationException",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
) {}
XPathFactoryConfigurationException::XPathFactoryConfigurationException(JThrowable arg0)
: javax::xml::xpath::XPathException(
"javax.xml.xpath.XPathFactoryConfigurationException",
"(Ljava/lang/Throwable;)V",
arg0.object<jthrowable>()
) {}
// Methods
} // namespace javax::xml::xpath
| 30.344828
| 131
| 0.748864
|
YJBeetle
|
a9284fbfd3b12d64acf1b5ae32823bb6ccc32984
| 1,336
|
cpp
|
C++
|
ros_ws/src/intro_pkg1/src/TempSensor.cpp
|
TheProjectsGuy/Learning-ROS
|
612f8eeeed0d3308cfff9084dbf7dda4732ec1ae
|
[
"MIT"
] | 2
|
2019-08-14T11:46:45.000Z
|
2020-05-13T21:03:40.000Z
|
ros_ws/src/intro_pkg1/src/TempSensor.cpp
|
TheProjectsGuy/Learning-ROS
|
612f8eeeed0d3308cfff9084dbf7dda4732ec1ae
|
[
"MIT"
] | 1
|
2018-12-07T18:54:09.000Z
|
2018-12-08T13:18:44.000Z
|
ros_ws/src/intro_pkg1/src/TempSensor.cpp
|
TheProjectsGuy/Learning-ROS
|
612f8eeeed0d3308cfff9084dbf7dda4732ec1ae
|
[
"MIT"
] | null | null | null |
#include "ros/ros.h"
#include "std_msgs/Header.h"
#include "sensor_msgs/Temperature.h"
int main(int argc, char **argv) {
// Initialize the ROS node
ros::init(argc, argv, "TemperatureSensor", ros::init_options::AnonymousName);
// Node handler
ros::NodeHandle nodeHandler;
// Publisher object
ros::Publisher publisherObject = nodeHandler.advertise<sensor_msgs::Temperature>("temp_readings", 5);
// Rate handler (5 Hz)
ros::Rate rateHandler = ros::Rate(5);
// Buffer variables
float tempValue = 30.0;
bool increment = true;
// Publishing message
sensor_msgs::Temperature msg;
// Default properties
msg.header.frame_id = "source";
msg.variance = 0.05;
while(ros::ok()) {
// Assign it time
msg.header.stamp = ros::Time::now();
// Temperature value
msg.temperature = tempValue;
ROS_DEBUG("Temperature value : %f", tempValue);
// Modify the temperature value
tempValue += (increment) ? 0.1 : -0.1;
if (tempValue >= 50 || tempValue <= 20) {
increment = !increment;
}
// Publish the message
publisherObject.publish(msg);
// Increase sequence number
msg.header.seq++;
// Sleep for the rate satisfaction
rateHandler.sleep();
}
return 0;
}
| 32.585366
| 105
| 0.614521
|
TheProjectsGuy
|
a92da91d699517c4ae2ef6a0627f450aaa3b6abe
| 5,810
|
hpp
|
C++
|
include/ecoro/when_any.hpp
|
msvetkin/ecoro
|
3d292f0d8bf16d57dcacdf6868c81669bdcb15e7
|
[
"MIT"
] | 4
|
2021-10-24T00:50:22.000Z
|
2022-01-10T11:53:40.000Z
|
include/ecoro/when_any.hpp
|
msvetkin/ecoro
|
3d292f0d8bf16d57dcacdf6868c81669bdcb15e7
|
[
"MIT"
] | 3
|
2022-02-01T20:14:15.000Z
|
2022-02-02T19:29:48.000Z
|
include/ecoro/when_any.hpp
|
msvetkin/ecoro
|
3d292f0d8bf16d57dcacdf6868c81669bdcb15e7
|
[
"MIT"
] | null | null | null |
// Copyright 2021 - present, Mikhail Svetkin
// All rights reserved.
//
// For the license information refer to LICENSE
#ifndef ECORO_WHEN_ANY_HPP
#define ECORO_WHEN_ANY_HPP
#include "ecoro/awaitable_traits.hpp"
#include "ecoro/detail/invoke_or_pass.hpp"
#include "ecoro/task.hpp"
#include <tuple>
#include <variant>
namespace ecoro {
namespace detail {
class when_any_observer {
public:
explicit when_any_observer(const std::size_t awaitables_count) noexcept
: completed_index_(awaitables_count) {}
bool set_continuation(std::coroutine_handle<> awaiting_coroutine) noexcept {
awaiting_coroutine_ = awaiting_coroutine;
return true;
}
void on_awaitable_completed(const std::size_t index) noexcept {
completed_index_ = index;
if (awaiting_coroutine_) {
awaiting_coroutine_.resume();
return;
}
}
std::size_t completed_index() const noexcept {
return completed_index_;
}
private:
std::size_t completed_index_;
std::coroutine_handle<> awaiting_coroutine_;
};
template<std::size_t Index, typename T>
class when_any_task_promise : public task_promise<T> {
struct final_awaiter {
bool await_ready() const noexcept {
return false;
}
template<typename Promise>
void await_suspend(
std::coroutine_handle<Promise> current_coroutine) noexcept {
current_coroutine.promise().observer_->on_awaitable_completed(Index);
}
void await_resume() noexcept {}
};
public:
using task_promise<T>::task_promise;
using value_type = std::conditional_t<std::is_void_v<T>, std::monostate, T>;
final_awaiter final_suspend() noexcept {
return {};
}
value_type result() {
if constexpr (std::is_void_v<T>) {
return {};
} else {
return task_promise<T>::result();
}
}
void set_observer(when_any_observer &observer) noexcept {
observer_ = &observer;
}
private:
when_any_observer *observer_{nullptr};
};
template<std::size_t Index, typename T>
class when_any_task final : public task<T, when_any_task_promise<Index, T>> {
public:
using base = task<T, when_any_task_promise<Index, T>>;
using base::base;
when_any_task(base &&other) noexcept : base(std::move(other)) {}
void resume(when_any_observer &observer) noexcept {
base::handle().promise().set_observer(observer);
base::resume();
}
};
template<std::size_t Index, typename Awaitable>
when_any_task<Index, awaitable_return_type<Awaitable>> make_when_any_task(
Awaitable awaitable) {
co_return co_await awaitable;
}
template<typename... Awaitables>
class when_any_executor {
using storage_type = std::tuple<Awaitables...>;
struct result {
std::size_t index{0};
storage_type awaitables;
result(const std::size_t i, storage_type &&awaitables)
: index(i), awaitables(std::move(awaitables)) {}
result(result &&) noexcept = default;
result &operator=(result &&) noexcept = default;
result(result &) = delete;
result operator=(result &) = delete;
};
struct awaiter {
bool await_ready() const noexcept {
return false;
}
bool await_suspend(std::coroutine_handle<> awaiting_coroutine) noexcept {
return executor_.start(awaiting_coroutine);
}
result await_resume() noexcept {
return {executor_.observer_.completed_index(),
std::move(executor_.awaitables_)};
}
when_any_executor &executor_;
};
public:
explicit when_any_executor(Awaitables &&...awaitables) noexcept(
std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>)
: awaitables_(std::forward<Awaitables>(awaitables)...) {}
explicit when_any_executor(when_any_executor &&other) noexcept(
std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>)
: observer_(std::move(other.observer_)),
awaitables_(std::exchange(other.awaitables_, {})) {}
when_any_executor &operator=(when_any_executor &&other) noexcept(
std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>) {
if (std::addressof(other) != this) {
observer_ = std::move(other.observer_);
awaitables_ = std::move(other.awaitables_);
}
return *this;
}
auto operator co_await() noexcept {
return awaiter{const_cast<when_any_executor &>(*this)};
}
protected:
bool start(std::coroutine_handle<> awaiting_coroutine) noexcept {
std::apply([this](auto &&...args) { (start(args), ...); }, awaitables_);
if (finished()) {
return false;
}
observer_.set_continuation(awaiting_coroutine);
return true;
}
template<typename Awaitable>
void start(Awaitable &awaitable) noexcept {
if (!finished())
awaitable.resume(observer_);
}
bool finished() const noexcept {
return observer_.completed_index() < sizeof...(Awaitables);
}
private:
when_any_observer observer_{sizeof...(Awaitables)};
storage_type awaitables_;
};
template<typename... Awaitables>
decltype(auto) make_when_any_executor(Awaitables &&...awaitables) {
return when_any_executor<Awaitables...>(
std::forward<Awaitables>(awaitables)...);
}
template<std::size_t... Indexes, typename... Awaitables>
[[nodiscard]] decltype(auto) when_any(std::index_sequence<Indexes...>,
Awaitables &&...awaitables) {
return detail::make_when_any_executor(
detail::make_when_any_task<Indexes, Awaitables>(
detail::invoke_or_pass(std::forward<Awaitables>(awaitables)))...);
}
} // namespace detail
template<typename... Awaitables>
[[nodiscard]] decltype(auto) when_any(Awaitables &&...awaitables) {
return detail::when_any(std::index_sequence_for<Awaitables...>{},
std::forward<Awaitables>(awaitables)...);
}
} // namespace ecoro
#endif // ECORO_WHEN_ANY_HPP
| 26.651376
| 78
| 0.694836
|
msvetkin
|
a9304e2cd440e9351966cca74c8df4a1362279da
| 729
|
cpp
|
C++
|
04_mp11_with_values/main.cpp
|
BorisSchaeling/boost-meta-programming-2020
|
1bb70e88070953daa4bc19f91f891b43583df06e
|
[
"BSL-1.0"
] | null | null | null |
04_mp11_with_values/main.cpp
|
BorisSchaeling/boost-meta-programming-2020
|
1bb70e88070953daa4bc19f91f891b43583df06e
|
[
"BSL-1.0"
] | null | null | null |
04_mp11_with_values/main.cpp
|
BorisSchaeling/boost-meta-programming-2020
|
1bb70e88070953daa4bc19f91f891b43583df06e
|
[
"BSL-1.0"
] | null | null | null |
#include <boost/mp11/mpl.hpp>
#include <type_traits>
template <int I>
using int_ = std::integral_constant<int, I>;
using namespace boost::mp11;
template <typename Sequence, typename Value>
struct index_of_impl
{
using index = mp_find<Sequence, Value>;
using size = mp_size<Sequence>;
using index_smaller_than_size = mp_less<index, size>;
using type = mp_if<index_smaller_than_size, index, int_<-1>>;
};
template <typename Sequence, typename Value>
using index_of = typename index_of_impl<Sequence, Value>::type;
int main()
{
using l = mp_list_c<int, 5, 2, 3, 1, 4>;
constexpr int r1 = index_of<l, int_<3>>::value;
static_assert(r1 == 2);
constexpr int r2 = index_of<l, int_<6>>::value;
static_assert(r2 == -1);
}
| 23.516129
| 63
| 0.720165
|
BorisSchaeling
|
a93106476d7585426a5cecc1398d348a54d2bf2c
| 3,862
|
cpp
|
C++
|
test/shape_tester/shape_testGenTrap.cpp
|
cxwx/VecGeom
|
c86c00bd7d4db08f4fc20a625020da329784aaac
|
[
"ECL-2.0",
"Apache-2.0"
] | 1
|
2020-06-27T18:43:36.000Z
|
2020-06-27T18:43:36.000Z
|
test/shape_tester/shape_testGenTrap.cpp
|
cxwx/VecGeom
|
c86c00bd7d4db08f4fc20a625020da329784aaac
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
test/shape_tester/shape_testGenTrap.cpp
|
cxwx/VecGeom
|
c86c00bd7d4db08f4fc20a625020da329784aaac
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
#include "../benchmark/ArgParser.h"
#include "ShapeTester.h"
#include "VecGeom/volumes/GenTrap.h"
typedef vecgeom::SimpleGenTrap GenTrap_t;
int main(int argc, char *argv[])
{
if (argc == 1) {
std::cout << "Usage: shape_testGenTrap -test <#>:\n"
" 0 - twisted\n"
" 1 - planar\n"
" 2 - one face triangle\n"
" 3 - one face line\n"
" 4 - one face point\n"
" 5 - one face line, other triangle\n"
" 6 - degenerated planar\n";
}
OPTION_INT(npoints, 10000);
OPTION_BOOL(debug, false);
OPTION_BOOL(stat, false);
OPTION_INT(type, 0);
using namespace vecgeom;
// 4 different vertices, twisted
Precision verticesx0[8] = {-3, -2.5, 3, 2.5, -2, -2, 2, 2};
Precision verticesy0[8] = {-2.5, 3, 2.5, -3, -2, 2, 2, -2};
// 4 different vertices, planar
Precision verticesx1[8] = {-3, -3, 3, 3, -2, -2, 2, 2};
Precision verticesy1[8] = {-3, 3, 3, -3, -2, 2, 2, -2};
// 3 different vertices
Precision verticesx2[8] = {-3, -3, 3, 2.5, -2, -2, 2, 2};
Precision verticesy2[8] = {-2.5, -2.5, 2.5, -3, -2, 2, 2, -2};
// 2 different vertices
Precision verticesx3[8] = {-3, -3, 2.5, 2.5, -2, -2, 2, 2};
Precision verticesy3[8] = {-2.5, -2.5, -3, -3, -2, 2, 2, -2};
// 1 vertex (pyramid)
Precision verticesx4[8] = {-3, -3, -3, -3, -2, -2, 2, 2};
Precision verticesy4[8] = {-2.5, -2.5, -2.5, -2.5, -2, 2, 2, -2};
// 2 vertex bottom, 3 vertices top
Precision verticesx5[8] = {-3, -3, 2.5, 2.5, -2, -2, 2, 2};
Precision verticesy5[8] = {-2.5, -2.5, -3, -3, -2, -2, 2, -2};
//
Precision verticesx6[8] = {-0.507492, -0.507508, 1.522492, -0.507492, -0.507492, -0.507508, 1.522492, -0.507492};
Precision verticesy6[8] = {-3.634000, 3.63400, 3.634000, -3.634000, -3.634000, 3.634000, 3.634000, -3.634000};
GenTrap_t *solid = 0;
switch (type) {
case 0:
// 4 different vertices, twisted
std::cout << "Testing twisted trapezoid\n";
solid = new GenTrap_t("test_VecGeomGenTrap", verticesx0, verticesy0, 5);
break;
case 1:
// 4 different vertices, planar
std::cout << "Testing planar trapezoid\n";
solid = new GenTrap_t("test_VecGeomGenTrap", verticesx1, verticesy1, 5);
break;
case 2:
// 3 different vertices
std::cout << "Testing trapezoid with one face triangle\n";
solid = new GenTrap_t("test_VecGeomGenTrap", verticesx2, verticesy2, 5);
break;
case 3:
// 2 different vertices
std::cout << "Testing trapezoid with one face line degenerated\n";
solid = new GenTrap_t("test_VecGeomGenTrap", verticesx3, verticesy3, 5);
break;
case 4:
// 1 vertex (pyramid)
std::cout << "Testing trapezoid with one face point degenerated (pyramid)\n";
solid = new GenTrap_t("test_VecGeomGenTrap", verticesx4, verticesy4, 5);
break;
case 5:
// 2 vertex bottom, 3 vertices top
std::cout << "Testing trapezoid with line on one face and triangle on other\n";
solid = new GenTrap_t("test_VecGeomGenTrap", verticesx5, verticesy5, 5);
break;
case 6:
// 3 vertexes top, 3 vertexes bottom
std::cout << "Testing degenerated planar trapezoid\n";
solid = new GenTrap_t("test_VecGeomGenTrap", verticesx6, verticesy6, 5);
break;
default:
std::cout << "Unknown test case.\n";
}
solid->Print();
ShapeTester<vecgeom::VPlacedVolume> tester;
tester.setDebug(debug);
tester.setStat(stat);
tester.SetMaxPoints(npoints);
tester.SetSolidTolerance(1.e-7);
tester.SetTestBoundaryErrors(true);
int errCode = tester.Run(solid);
std::cout << "Final Error count for Shape *** " << solid->GetName() << "*** = " << errCode << "\n";
std::cout << "=========================================================" << std::endl;
if (solid) delete solid;
return 0;
}
| 37.862745
| 115
| 0.588814
|
cxwx
|
a933008a9bdfb54d6295a005cbd838b10ea79a6f
| 472
|
cpp
|
C++
|
src/atcoder/abc211/c/sol_0.cpp
|
kagemeka/competitive-programming
|
c70fe481bcd518f507b885fc9234691d8ce63171
|
[
"MIT"
] | 1
|
2021-07-11T03:20:10.000Z
|
2021-07-11T03:20:10.000Z
|
src/atcoder/abc211/c/sol_0.cpp
|
kagemeka/competitive-programming
|
c70fe481bcd518f507b885fc9234691d8ce63171
|
[
"MIT"
] | 39
|
2021-07-10T05:21:09.000Z
|
2021-12-15T06:10:12.000Z
|
src/atcoder/abc211/c/sol_0.cpp
|
kagemeka/competitive-programming
|
c70fe481bcd518f507b885fc9234691d8ce63171
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int mod = (int)1e9 + 7;
string s; cin >> s;
string t = "$chokudai";
map<char, int> ind;
for (
int i = 0;
i < (int)t.size();
i++
) {
ind[t[i]] = i;
}
map<char, int> cnt;
cnt['$'] = 1;
for (char x: s) {
if (!ind.count(x))
continue;
cnt[x] += cnt[t[ind[x]-1]];
cnt[x] %= mod;
}
cout << cnt['i'] << '\n';
}
| 15.225806
| 31
| 0.466102
|
kagemeka
|
a933046b05cd2eedf6dc6e1464c7abda4c9e8bb8
| 693
|
cpp
|
C++
|
source/DeskEditor/StartApp.cpp
|
Vladimir-Novick/DesktopToolbox
|
13ed631d91a8b622d3b6c0803141aec5572f36d2
|
[
"MIT"
] | null | null | null |
source/DeskEditor/StartApp.cpp
|
Vladimir-Novick/DesktopToolbox
|
13ed631d91a8b622d3b6c0803141aec5572f36d2
|
[
"MIT"
] | null | null | null |
source/DeskEditor/StartApp.cpp
|
Vladimir-Novick/DesktopToolbox
|
13ed631d91a8b622d3b6c0803141aec5572f36d2
|
[
"MIT"
] | 1
|
2021-11-21T07:25:50.000Z
|
2021-11-21T07:25:50.000Z
|
// StartApp.cpp: implementation of the StartApp class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "commctrl.h"
#include "DeskEditor1.h"
#include "windowsx.h"
#include "DeskEditor1.h"
#include "StartApp.h"
//#include "commctrl.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
StartApp::StartApp()
{
}
StartApp::~StartApp()
{
}
HWND StartApp::Run()
{
CDeskEditor *pD;
pD = new CDeskEditor;
pD->DoModal(::GetDesktopWindow());
return pD->m_hWnd ;
}
| 18.236842
| 71
| 0.428571
|
Vladimir-Novick
|
a9343145be0114ce4e2fec36eeb9894d3cddebf3
| 53,548
|
cc
|
C++
|
modules/rtp_rtcp/source/rtcp_receiver.cc
|
TeamNuclear/external_chromium_org_third_party_webrtc
|
5bd5c72d7c01872fea80698dac196ff9a01dfcba
|
[
"DOC",
"BSD-3-Clause"
] | null | null | null |
modules/rtp_rtcp/source/rtcp_receiver.cc
|
TeamNuclear/external_chromium_org_third_party_webrtc
|
5bd5c72d7c01872fea80698dac196ff9a01dfcba
|
[
"DOC",
"BSD-3-Clause"
] | null | null | null |
modules/rtp_rtcp/source/rtcp_receiver.cc
|
TeamNuclear/external_chromium_org_third_party_webrtc
|
5bd5c72d7c01872fea80698dac196ff9a01dfcba
|
[
"DOC",
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h"
#include <assert.h> //assert
#include <string.h> //memset
#include <algorithm>
#include "webrtc/modules/rtp_rtcp/source/rtcp_utility.h"
#include "webrtc/modules/rtp_rtcp/source/rtp_rtcp_impl.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/trace_event.h"
namespace webrtc {
using namespace RTCPUtility;
using namespace RTCPHelp;
// The number of RTCP time intervals needed to trigger a timeout.
const int kRrTimeoutIntervals = 3;
RTCPReceiver::RTCPReceiver(const int32_t id, Clock* clock,
ModuleRtpRtcpImpl* owner)
: TMMBRHelp(),
_id(id),
_clock(clock),
_method(kRtcpOff),
_lastReceived(0),
_rtpRtcp(*owner),
_criticalSectionFeedbacks(
CriticalSectionWrapper::CreateCriticalSection()),
_cbRtcpFeedback(NULL),
_cbRtcpBandwidthObserver(NULL),
_cbRtcpIntraFrameObserver(NULL),
_criticalSectionRTCPReceiver(
CriticalSectionWrapper::CreateCriticalSection()),
main_ssrc_(0),
_remoteSSRC(0),
_remoteSenderInfo(),
_lastReceivedSRNTPsecs(0),
_lastReceivedSRNTPfrac(0),
_lastReceivedXRNTPsecs(0),
_lastReceivedXRNTPfrac(0),
xr_rr_rtt_ms_(0),
_receivedInfoMap(),
_packetTimeOutMS(0),
_lastReceivedRrMs(0),
_lastIncreasedSequenceNumberMs(0),
stats_callback_(NULL) {
memset(&_remoteSenderInfo, 0, sizeof(_remoteSenderInfo));
}
RTCPReceiver::~RTCPReceiver() {
delete _criticalSectionRTCPReceiver;
delete _criticalSectionFeedbacks;
while (!_receivedReportBlockMap.empty()) {
std::map<uint32_t, RTCPReportBlockInformation*>::iterator first =
_receivedReportBlockMap.begin();
delete first->second;
_receivedReportBlockMap.erase(first);
}
while (!_receivedInfoMap.empty()) {
std::map<uint32_t, RTCPReceiveInformation*>::iterator first =
_receivedInfoMap.begin();
delete first->second;
_receivedInfoMap.erase(first);
}
while (!_receivedCnameMap.empty()) {
std::map<uint32_t, RTCPCnameInformation*>::iterator first =
_receivedCnameMap.begin();
delete first->second;
_receivedCnameMap.erase(first);
}
}
void
RTCPReceiver::ChangeUniqueId(const int32_t id)
{
_id = id;
}
RTCPMethod
RTCPReceiver::Status() const
{
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
return _method;
}
int32_t
RTCPReceiver::SetRTCPStatus(const RTCPMethod method)
{
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
_method = method;
return 0;
}
int64_t
RTCPReceiver::LastReceived()
{
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
return _lastReceived;
}
int64_t
RTCPReceiver::LastReceivedReceiverReport() const {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
int64_t last_received_rr = -1;
for (ReceivedInfoMap::const_iterator it = _receivedInfoMap.begin();
it != _receivedInfoMap.end(); ++it) {
if (it->second->lastTimeReceived > last_received_rr) {
last_received_rr = it->second->lastTimeReceived;
}
}
return last_received_rr;
}
int32_t
RTCPReceiver::SetRemoteSSRC( const uint32_t ssrc)
{
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
// new SSRC reset old reports
memset(&_remoteSenderInfo, 0, sizeof(_remoteSenderInfo));
_lastReceivedSRNTPsecs = 0;
_lastReceivedSRNTPfrac = 0;
_remoteSSRC = ssrc;
return 0;
}
uint32_t RTCPReceiver::RemoteSSRC() const {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
return _remoteSSRC;
}
void RTCPReceiver::RegisterRtcpObservers(
RtcpIntraFrameObserver* intra_frame_callback,
RtcpBandwidthObserver* bandwidth_callback,
RtcpFeedback* feedback_callback) {
CriticalSectionScoped lock(_criticalSectionFeedbacks);
_cbRtcpIntraFrameObserver = intra_frame_callback;
_cbRtcpBandwidthObserver = bandwidth_callback;
_cbRtcpFeedback = feedback_callback;
}
void RTCPReceiver::SetSsrcs(uint32_t main_ssrc,
const std::set<uint32_t>& registered_ssrcs) {
uint32_t old_ssrc = 0;
{
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
old_ssrc = main_ssrc_;
main_ssrc_ = main_ssrc;
registered_ssrcs_ = registered_ssrcs;
}
{
CriticalSectionScoped lock(_criticalSectionFeedbacks);
if (_cbRtcpIntraFrameObserver && old_ssrc != main_ssrc) {
_cbRtcpIntraFrameObserver->OnLocalSsrcChanged(old_ssrc, main_ssrc);
}
}
}
int32_t RTCPReceiver::ResetRTT(const uint32_t remoteSSRC) {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
RTCPReportBlockInformation* reportBlock =
GetReportBlockInformation(remoteSSRC);
if (reportBlock == NULL) {
LOG(LS_WARNING) << "Failed to reset rtt for ssrc " << remoteSSRC;
return -1;
}
reportBlock->RTT = 0;
reportBlock->avgRTT = 0;
reportBlock->minRTT = 0;
reportBlock->maxRTT = 0;
return 0;
}
int32_t RTCPReceiver::RTT(uint32_t remoteSSRC,
uint16_t* RTT,
uint16_t* avgRTT,
uint16_t* minRTT,
uint16_t* maxRTT) const {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
RTCPReportBlockInformation* reportBlock =
GetReportBlockInformation(remoteSSRC);
if (reportBlock == NULL) {
return -1;
}
if (RTT) {
*RTT = reportBlock->RTT;
}
if (avgRTT) {
*avgRTT = reportBlock->avgRTT;
}
if (minRTT) {
*minRTT = reportBlock->minRTT;
}
if (maxRTT) {
*maxRTT = reportBlock->maxRTT;
}
return 0;
}
bool RTCPReceiver::GetAndResetXrRrRtt(uint16_t* rtt_ms) {
assert(rtt_ms);
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
if (xr_rr_rtt_ms_ == 0) {
return false;
}
*rtt_ms = xr_rr_rtt_ms_;
xr_rr_rtt_ms_ = 0;
return true;
}
// TODO(pbos): Make this fail when we haven't received NTP.
bool RTCPReceiver::NTP(uint32_t* ReceivedNTPsecs,
uint32_t* ReceivedNTPfrac,
uint32_t* RTCPArrivalTimeSecs,
uint32_t* RTCPArrivalTimeFrac,
uint32_t* rtcp_timestamp) const
{
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
if(ReceivedNTPsecs)
{
*ReceivedNTPsecs = _remoteSenderInfo.NTPseconds; // NTP from incoming SendReport
}
if(ReceivedNTPfrac)
{
*ReceivedNTPfrac = _remoteSenderInfo.NTPfraction;
}
if(RTCPArrivalTimeFrac)
{
*RTCPArrivalTimeFrac = _lastReceivedSRNTPfrac; // local NTP time when we received a RTCP packet with a send block
}
if(RTCPArrivalTimeSecs)
{
*RTCPArrivalTimeSecs = _lastReceivedSRNTPsecs;
}
if (rtcp_timestamp) {
*rtcp_timestamp = _remoteSenderInfo.RTPtimeStamp;
}
return true;
}
bool RTCPReceiver::LastReceivedXrReferenceTimeInfo(
RtcpReceiveTimeInfo* info) const {
assert(info);
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
if (_lastReceivedXRNTPsecs == 0 && _lastReceivedXRNTPfrac == 0) {
return false;
}
info->sourceSSRC = _remoteXRReceiveTimeInfo.sourceSSRC;
info->lastRR = _remoteXRReceiveTimeInfo.lastRR;
// Get the delay since last received report (RFC 3611).
uint32_t receive_time = RTCPUtility::MidNtp(_lastReceivedXRNTPsecs,
_lastReceivedXRNTPfrac);
uint32_t ntp_sec = 0;
uint32_t ntp_frac = 0;
_clock->CurrentNtp(ntp_sec, ntp_frac);
uint32_t now = RTCPUtility::MidNtp(ntp_sec, ntp_frac);
info->delaySinceLastRR = now - receive_time;
return true;
}
int32_t RTCPReceiver::SenderInfoReceived(RTCPSenderInfo* senderInfo) const {
assert(senderInfo);
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
if (_lastReceivedSRNTPsecs == 0) {
return -1;
}
memcpy(senderInfo, &(_remoteSenderInfo), sizeof(RTCPSenderInfo));
return 0;
}
// statistics
// we can get multiple receive reports when we receive the report from a CE
int32_t RTCPReceiver::StatisticsReceived(
std::vector<RTCPReportBlock>* receiveBlocks) const {
assert(receiveBlocks);
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPReportBlockInformation*>::const_iterator it =
_receivedReportBlockMap.begin();
while (it != _receivedReportBlockMap.end()) {
receiveBlocks->push_back(it->second->remoteReceiveBlock);
it++;
}
return 0;
}
void RTCPReceiver::GetPacketTypeCounter(
RtcpPacketTypeCounter* packet_counter) const {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
*packet_counter = packet_type_counter_;
}
int32_t
RTCPReceiver::IncomingRTCPPacket(RTCPPacketInformation& rtcpPacketInformation,
RTCPUtility::RTCPParserV2* rtcpParser)
{
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
_lastReceived = _clock->TimeInMilliseconds();
RTCPUtility::RTCPPacketTypes pktType = rtcpParser->Begin();
while (pktType != RTCPUtility::kRtcpNotValidCode)
{
// Each "case" is responsible for iterate the parser to the
// next top level packet.
switch (pktType)
{
case RTCPUtility::kRtcpSrCode:
case RTCPUtility::kRtcpRrCode:
HandleSenderReceiverReport(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpSdesCode:
HandleSDES(*rtcpParser);
break;
case RTCPUtility::kRtcpXrHeaderCode:
HandleXrHeader(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpXrReceiverReferenceTimeCode:
HandleXrReceiveReferenceTime(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpXrDlrrReportBlockCode:
HandleXrDlrrReportBlock(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpXrVoipMetricCode:
HandleXRVOIPMetric(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpByeCode:
HandleBYE(*rtcpParser);
break;
case RTCPUtility::kRtcpRtpfbNackCode:
HandleNACK(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpRtpfbTmmbrCode:
HandleTMMBR(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpRtpfbTmmbnCode:
HandleTMMBN(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpRtpfbSrReqCode:
HandleSR_REQ(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpPsfbPliCode:
HandlePLI(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpPsfbSliCode:
HandleSLI(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpPsfbRpsiCode:
HandleRPSI(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpExtendedIjCode:
HandleIJ(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpPsfbFirCode:
HandleFIR(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpPsfbAppCode:
HandlePsfbApp(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpAppCode:
// generic application messages
HandleAPP(*rtcpParser, rtcpPacketInformation);
break;
case RTCPUtility::kRtcpAppItemCode:
// generic application messages
HandleAPPItem(*rtcpParser, rtcpPacketInformation);
break;
default:
rtcpParser->Iterate();
break;
}
pktType = rtcpParser->PacketType();
}
return 0;
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleSenderReceiverReport(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
RTCPUtility::RTCPPacketTypes rtcpPacketType = rtcpParser.PacketType();
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
assert((rtcpPacketType == RTCPUtility::kRtcpRrCode) || (rtcpPacketType == RTCPUtility::kRtcpSrCode));
// SR.SenderSSRC
// The synchronization source identifier for the originator of this SR packet
// rtcpPacket.RR.SenderSSRC
// The source of the packet sender, same as of SR? or is this a CE?
const uint32_t remoteSSRC = (rtcpPacketType == RTCPUtility::kRtcpRrCode) ? rtcpPacket.RR.SenderSSRC:rtcpPacket.SR.SenderSSRC;
const uint8_t numberOfReportBlocks = (rtcpPacketType == RTCPUtility::kRtcpRrCode) ? rtcpPacket.RR.NumberOfReportBlocks:rtcpPacket.SR.NumberOfReportBlocks;
rtcpPacketInformation.remoteSSRC = remoteSSRC;
RTCPReceiveInformation* ptrReceiveInfo = CreateReceiveInformation(remoteSSRC);
if (!ptrReceiveInfo)
{
rtcpParser.Iterate();
return;
}
if (rtcpPacketType == RTCPUtility::kRtcpSrCode)
{
TRACE_EVENT_INSTANT2("webrtc_rtp", "SR",
"remote_ssrc", remoteSSRC,
"ssrc", main_ssrc_);
if (_remoteSSRC == remoteSSRC) // have I received RTP packets from this party
{
// only signal that we have received a SR when we accept one
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpSr;
rtcpPacketInformation.ntp_secs = rtcpPacket.SR.NTPMostSignificant;
rtcpPacketInformation.ntp_frac = rtcpPacket.SR.NTPLeastSignificant;
rtcpPacketInformation.rtp_timestamp = rtcpPacket.SR.RTPTimestamp;
// We will only store the send report from one source, but
// we will store all the receive block
// Save the NTP time of this report
_remoteSenderInfo.NTPseconds = rtcpPacket.SR.NTPMostSignificant;
_remoteSenderInfo.NTPfraction = rtcpPacket.SR.NTPLeastSignificant;
_remoteSenderInfo.RTPtimeStamp = rtcpPacket.SR.RTPTimestamp;
_remoteSenderInfo.sendPacketCount = rtcpPacket.SR.SenderPacketCount;
_remoteSenderInfo.sendOctetCount = rtcpPacket.SR.SenderOctetCount;
_clock->CurrentNtp(_lastReceivedSRNTPsecs, _lastReceivedSRNTPfrac);
}
else
{
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpRr;
}
} else
{
TRACE_EVENT_INSTANT2("webrtc_rtp", "RR",
"remote_ssrc", remoteSSRC,
"ssrc", main_ssrc_);
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpRr;
}
UpdateReceiveInformation(*ptrReceiveInfo);
rtcpPacketType = rtcpParser.Iterate();
while (rtcpPacketType == RTCPUtility::kRtcpReportBlockItemCode)
{
HandleReportBlock(rtcpPacket, rtcpPacketInformation, remoteSSRC, numberOfReportBlocks);
rtcpPacketType = rtcpParser.Iterate();
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void RTCPReceiver::HandleReportBlock(
const RTCPUtility::RTCPPacket& rtcpPacket,
RTCPPacketInformation& rtcpPacketInformation,
const uint32_t remoteSSRC,
const uint8_t numberOfReportBlocks)
EXCLUSIVE_LOCKS_REQUIRED(_criticalSectionRTCPReceiver) {
// This will be called once per report block in the RTCP packet.
// We filter out all report blocks that are not for us.
// Each packet has max 31 RR blocks.
//
// We can calc RTT if we send a send report and get a report block back.
// |rtcpPacket.ReportBlockItem.SSRC| is the SSRC identifier of the source to
// which the information in this reception report block pertains.
// Filter out all report blocks that are not for us.
if (registered_ssrcs_.find(rtcpPacket.ReportBlockItem.SSRC) ==
registered_ssrcs_.end()) {
// This block is not for us ignore it.
return;
}
// To avoid problem with acquiring _criticalSectionRTCPSender while holding
// _criticalSectionRTCPReceiver.
_criticalSectionRTCPReceiver->Leave();
uint32_t sendTimeMS =
_rtpRtcp.SendTimeOfSendReport(rtcpPacket.ReportBlockItem.LastSR);
_criticalSectionRTCPReceiver->Enter();
RTCPReportBlockInformation* reportBlock =
CreateReportBlockInformation(remoteSSRC);
if (reportBlock == NULL) {
LOG(LS_WARNING) << "Failed to CreateReportBlockInformation("
<< remoteSSRC << ")";
return;
}
_lastReceivedRrMs = _clock->TimeInMilliseconds();
const RTCPPacketReportBlockItem& rb = rtcpPacket.ReportBlockItem;
reportBlock->remoteReceiveBlock.remoteSSRC = remoteSSRC;
reportBlock->remoteReceiveBlock.sourceSSRC = rb.SSRC;
reportBlock->remoteReceiveBlock.fractionLost = rb.FractionLost;
reportBlock->remoteReceiveBlock.cumulativeLost =
rb.CumulativeNumOfPacketsLost;
if (rb.ExtendedHighestSequenceNumber >
reportBlock->remoteReceiveBlock.extendedHighSeqNum) {
// We have successfully delivered new RTP packets to the remote side after
// the last RR was sent from the remote side.
_lastIncreasedSequenceNumberMs = _lastReceivedRrMs;
}
reportBlock->remoteReceiveBlock.extendedHighSeqNum =
rb.ExtendedHighestSequenceNumber;
reportBlock->remoteReceiveBlock.jitter = rb.Jitter;
reportBlock->remoteReceiveBlock.delaySinceLastSR = rb.DelayLastSR;
reportBlock->remoteReceiveBlock.lastSR = rb.LastSR;
if (rtcpPacket.ReportBlockItem.Jitter > reportBlock->remoteMaxJitter) {
reportBlock->remoteMaxJitter = rtcpPacket.ReportBlockItem.Jitter;
}
uint32_t delaySinceLastSendReport =
rtcpPacket.ReportBlockItem.DelayLastSR;
// local NTP time when we received this
uint32_t lastReceivedRRNTPsecs = 0;
uint32_t lastReceivedRRNTPfrac = 0;
_clock->CurrentNtp(lastReceivedRRNTPsecs, lastReceivedRRNTPfrac);
// time when we received this in MS
uint32_t receiveTimeMS = Clock::NtpToMs(lastReceivedRRNTPsecs,
lastReceivedRRNTPfrac);
// Estimate RTT
uint32_t d = (delaySinceLastSendReport & 0x0000ffff) * 1000;
d /= 65536;
d += ((delaySinceLastSendReport & 0xffff0000) >> 16) * 1000;
int32_t RTT = 0;
if (sendTimeMS > 0) {
RTT = receiveTimeMS - d - sendTimeMS;
if (RTT <= 0) {
RTT = 1;
}
if (RTT > reportBlock->maxRTT) {
// store max RTT
reportBlock->maxRTT = (uint16_t) RTT;
}
if (reportBlock->minRTT == 0) {
// first RTT
reportBlock->minRTT = (uint16_t) RTT;
} else if (RTT < reportBlock->minRTT) {
// Store min RTT
reportBlock->minRTT = (uint16_t) RTT;
}
// store last RTT
reportBlock->RTT = (uint16_t) RTT;
// store average RTT
if (reportBlock->numAverageCalcs != 0) {
float ac = static_cast<float> (reportBlock->numAverageCalcs);
float newAverage = ((ac / (ac + 1)) * reportBlock->avgRTT)
+ ((1 / (ac + 1)) * RTT);
reportBlock->avgRTT = static_cast<int> (newAverage + 0.5f);
} else {
// first RTT
reportBlock->avgRTT = (uint16_t) RTT;
}
reportBlock->numAverageCalcs++;
}
TRACE_COUNTER_ID1("webrtc_rtp", "RR_RTT", rb.SSRC, RTT);
rtcpPacketInformation.AddReportInfo(*reportBlock);
}
RTCPReportBlockInformation*
RTCPReceiver::CreateReportBlockInformation(uint32_t remoteSSRC) {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPReportBlockInformation*>::iterator it =
_receivedReportBlockMap.find(remoteSSRC);
RTCPReportBlockInformation* ptrReportBlockInfo = NULL;
if (it != _receivedReportBlockMap.end()) {
ptrReportBlockInfo = it->second;
} else {
ptrReportBlockInfo = new RTCPReportBlockInformation;
_receivedReportBlockMap[remoteSSRC] = ptrReportBlockInfo;
}
return ptrReportBlockInfo;
}
RTCPReportBlockInformation*
RTCPReceiver::GetReportBlockInformation(uint32_t remoteSSRC) const {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPReportBlockInformation*>::const_iterator it =
_receivedReportBlockMap.find(remoteSSRC);
if (it == _receivedReportBlockMap.end()) {
return NULL;
}
return it->second;
}
RTCPCnameInformation*
RTCPReceiver::CreateCnameInformation(uint32_t remoteSSRC) {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPCnameInformation*>::iterator it =
_receivedCnameMap.find(remoteSSRC);
if (it != _receivedCnameMap.end()) {
return it->second;
}
RTCPCnameInformation* cnameInfo = new RTCPCnameInformation;
memset(cnameInfo->name, 0, RTCP_CNAME_SIZE);
_receivedCnameMap[remoteSSRC] = cnameInfo;
return cnameInfo;
}
RTCPCnameInformation*
RTCPReceiver::GetCnameInformation(uint32_t remoteSSRC) const {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPCnameInformation*>::const_iterator it =
_receivedCnameMap.find(remoteSSRC);
if (it == _receivedCnameMap.end()) {
return NULL;
}
return it->second;
}
RTCPReceiveInformation*
RTCPReceiver::CreateReceiveInformation(uint32_t remoteSSRC) {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPReceiveInformation*>::iterator it =
_receivedInfoMap.find(remoteSSRC);
if (it != _receivedInfoMap.end()) {
return it->second;
}
RTCPReceiveInformation* receiveInfo = new RTCPReceiveInformation;
_receivedInfoMap[remoteSSRC] = receiveInfo;
return receiveInfo;
}
RTCPReceiveInformation*
RTCPReceiver::GetReceiveInformation(uint32_t remoteSSRC) {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPReceiveInformation*>::iterator it =
_receivedInfoMap.find(remoteSSRC);
if (it == _receivedInfoMap.end()) {
return NULL;
}
return it->second;
}
void RTCPReceiver::UpdateReceiveInformation(
RTCPReceiveInformation& receiveInformation) {
// Update that this remote is alive
receiveInformation.lastTimeReceived = _clock->TimeInMilliseconds();
}
bool RTCPReceiver::RtcpRrTimeout(int64_t rtcp_interval_ms) {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
if (_lastReceivedRrMs == 0)
return false;
int64_t time_out_ms = kRrTimeoutIntervals * rtcp_interval_ms;
if (_clock->TimeInMilliseconds() > _lastReceivedRrMs + time_out_ms) {
// Reset the timer to only trigger one log.
_lastReceivedRrMs = 0;
return true;
}
return false;
}
bool RTCPReceiver::RtcpRrSequenceNumberTimeout(int64_t rtcp_interval_ms) {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
if (_lastIncreasedSequenceNumberMs == 0)
return false;
int64_t time_out_ms = kRrTimeoutIntervals * rtcp_interval_ms;
if (_clock->TimeInMilliseconds() > _lastIncreasedSequenceNumberMs +
time_out_ms) {
// Reset the timer to only trigger one log.
_lastIncreasedSequenceNumberMs = 0;
return true;
}
return false;
}
bool RTCPReceiver::UpdateRTCPReceiveInformationTimers() {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
bool updateBoundingSet = false;
int64_t timeNow = _clock->TimeInMilliseconds();
std::map<uint32_t, RTCPReceiveInformation*>::iterator receiveInfoIt =
_receivedInfoMap.begin();
while (receiveInfoIt != _receivedInfoMap.end()) {
RTCPReceiveInformation* receiveInfo = receiveInfoIt->second;
if (receiveInfo == NULL) {
return updateBoundingSet;
}
// time since last received rtcp packet
// when we dont have a lastTimeReceived and the object is marked
// readyForDelete it's removed from the map
if (receiveInfo->lastTimeReceived) {
/// use audio define since we don't know what interval the remote peer is
// using
if ((timeNow - receiveInfo->lastTimeReceived) >
5 * RTCP_INTERVAL_AUDIO_MS) {
// no rtcp packet for the last five regular intervals, reset limitations
receiveInfo->TmmbrSet.clearSet();
// prevent that we call this over and over again
receiveInfo->lastTimeReceived = 0;
// send new TMMBN to all channels using the default codec
updateBoundingSet = true;
}
receiveInfoIt++;
} else if (receiveInfo->readyForDelete) {
// store our current receiveInfoItem
std::map<uint32_t, RTCPReceiveInformation*>::iterator
receiveInfoItemToBeErased = receiveInfoIt;
receiveInfoIt++;
delete receiveInfoItemToBeErased->second;
_receivedInfoMap.erase(receiveInfoItemToBeErased);
} else {
receiveInfoIt++;
}
}
return updateBoundingSet;
}
int32_t RTCPReceiver::BoundingSet(bool &tmmbrOwner, TMMBRSet* boundingSetRec) {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPReceiveInformation*>::iterator receiveInfoIt =
_receivedInfoMap.find(_remoteSSRC);
if (receiveInfoIt == _receivedInfoMap.end()) {
return -1;
}
RTCPReceiveInformation* receiveInfo = receiveInfoIt->second;
if (receiveInfo == NULL) {
return -1;
}
if (receiveInfo->TmmbnBoundingSet.lengthOfSet() > 0) {
boundingSetRec->VerifyAndAllocateSet(
receiveInfo->TmmbnBoundingSet.lengthOfSet() + 1);
for(uint32_t i=0; i< receiveInfo->TmmbnBoundingSet.lengthOfSet();
i++) {
if(receiveInfo->TmmbnBoundingSet.Ssrc(i) == main_ssrc_) {
// owner of bounding set
tmmbrOwner = true;
}
boundingSetRec->SetEntry(i,
receiveInfo->TmmbnBoundingSet.Tmmbr(i),
receiveInfo->TmmbnBoundingSet.PacketOH(i),
receiveInfo->TmmbnBoundingSet.Ssrc(i));
}
}
return receiveInfo->TmmbnBoundingSet.lengthOfSet();
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleSDES(RTCPUtility::RTCPParserV2& rtcpParser)
{
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
while (pktType == RTCPUtility::kRtcpSdesChunkCode)
{
HandleSDESChunk(rtcpParser);
pktType = rtcpParser.Iterate();
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void RTCPReceiver::HandleSDESChunk(RTCPUtility::RTCPParserV2& rtcpParser) {
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
RTCPCnameInformation* cnameInfo =
CreateCnameInformation(rtcpPacket.CName.SenderSSRC);
assert(cnameInfo);
cnameInfo->name[RTCP_CNAME_SIZE - 1] = 0;
strncpy(cnameInfo->name, rtcpPacket.CName.CName, RTCP_CNAME_SIZE - 1);
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleNACK(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
if (main_ssrc_ != rtcpPacket.NACK.MediaSSRC)
{
// Not to us.
rtcpParser.Iterate();
return;
}
rtcpPacketInformation.ResetNACKPacketIdArray();
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
while (pktType == RTCPUtility::kRtcpRtpfbNackItemCode)
{
HandleNACKItem(rtcpPacket, rtcpPacketInformation);
pktType = rtcpParser.Iterate();
}
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpNack) {
++packet_type_counter_.nack_packets;
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleNACKItem(const RTCPUtility::RTCPPacket& rtcpPacket,
RTCPPacketInformation& rtcpPacketInformation)
{
rtcpPacketInformation.AddNACKPacket(rtcpPacket.NACKItem.PacketID);
uint16_t bitMask = rtcpPacket.NACKItem.BitMask;
if(bitMask)
{
for(int i=1; i <= 16; ++i)
{
if(bitMask & 0x01)
{
rtcpPacketInformation.AddNACKPacket(rtcpPacket.NACKItem.PacketID + i);
}
bitMask = bitMask >>1;
}
}
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpNack;
}
// no need for critsect we have _criticalSectionRTCPReceiver
void RTCPReceiver::HandleBYE(RTCPUtility::RTCPParserV2& rtcpParser) {
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
// clear our lists
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPReportBlockInformation*>::iterator
reportBlockInfoIt = _receivedReportBlockMap.find(
rtcpPacket.BYE.SenderSSRC);
if (reportBlockInfoIt != _receivedReportBlockMap.end()) {
delete reportBlockInfoIt->second;
_receivedReportBlockMap.erase(reportBlockInfoIt);
}
// we can't delete it due to TMMBR
std::map<uint32_t, RTCPReceiveInformation*>::iterator receiveInfoIt =
_receivedInfoMap.find(rtcpPacket.BYE.SenderSSRC);
if (receiveInfoIt != _receivedInfoMap.end()) {
receiveInfoIt->second->readyForDelete = true;
}
std::map<uint32_t, RTCPCnameInformation*>::iterator cnameInfoIt =
_receivedCnameMap.find(rtcpPacket.BYE.SenderSSRC);
if (cnameInfoIt != _receivedCnameMap.end()) {
delete cnameInfoIt->second;
_receivedCnameMap.erase(cnameInfoIt);
}
xr_rr_rtt_ms_ = 0;
rtcpParser.Iterate();
}
void RTCPReceiver::HandleXrHeader(
RTCPUtility::RTCPParserV2& parser,
RTCPPacketInformation& rtcpPacketInformation) {
const RTCPUtility::RTCPPacket& packet = parser.Packet();
rtcpPacketInformation.xr_originator_ssrc = packet.XR.OriginatorSSRC;
parser.Iterate();
}
void RTCPReceiver::HandleXrReceiveReferenceTime(
RTCPUtility::RTCPParserV2& parser,
RTCPPacketInformation& rtcpPacketInformation) {
const RTCPUtility::RTCPPacket& packet = parser.Packet();
_remoteXRReceiveTimeInfo.sourceSSRC =
rtcpPacketInformation.xr_originator_ssrc;
_remoteXRReceiveTimeInfo.lastRR = RTCPUtility::MidNtp(
packet.XRReceiverReferenceTimeItem.NTPMostSignificant,
packet.XRReceiverReferenceTimeItem.NTPLeastSignificant);
_clock->CurrentNtp(_lastReceivedXRNTPsecs, _lastReceivedXRNTPfrac);
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpXrReceiverReferenceTime;
parser.Iterate();
}
void RTCPReceiver::HandleXrDlrrReportBlock(
RTCPUtility::RTCPParserV2& parser,
RTCPPacketInformation& rtcpPacketInformation) {
const RTCPUtility::RTCPPacket& packet = parser.Packet();
// Iterate through sub-block(s), if any.
RTCPUtility::RTCPPacketTypes packet_type = parser.Iterate();
while (packet_type == RTCPUtility::kRtcpXrDlrrReportBlockItemCode) {
HandleXrDlrrReportBlockItem(packet, rtcpPacketInformation);
packet_type = parser.Iterate();
}
}
void RTCPReceiver::HandleXrDlrrReportBlockItem(
const RTCPUtility::RTCPPacket& packet,
RTCPPacketInformation& rtcpPacketInformation)
EXCLUSIVE_LOCKS_REQUIRED(_criticalSectionRTCPReceiver) {
if (registered_ssrcs_.find(packet.XRDLRRReportBlockItem.SSRC) ==
registered_ssrcs_.end()) {
// Not to us.
return;
}
rtcpPacketInformation.xr_dlrr_item = true;
// To avoid problem with acquiring _criticalSectionRTCPSender while holding
// _criticalSectionRTCPReceiver.
_criticalSectionRTCPReceiver->Leave();
int64_t send_time_ms;
bool found = _rtpRtcp.SendTimeOfXrRrReport(
packet.XRDLRRReportBlockItem.LastRR, &send_time_ms);
_criticalSectionRTCPReceiver->Enter();
if (!found) {
return;
}
// The DelayLastRR field is in units of 1/65536 sec.
uint32_t delay_rr_ms =
(((packet.XRDLRRReportBlockItem.DelayLastRR & 0x0000ffff) * 1000) >> 16) +
(((packet.XRDLRRReportBlockItem.DelayLastRR & 0xffff0000) >> 16) * 1000);
int32_t rtt = _clock->CurrentNtpInMilliseconds() - delay_rr_ms - send_time_ms;
xr_rr_rtt_ms_ = static_cast<uint16_t>(std::max(rtt, 1));
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpXrDlrrReportBlock;
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleXRVOIPMetric(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
if(rtcpPacket.XRVOIPMetricItem.SSRC == main_ssrc_)
{
// Store VoIP metrics block if it's about me
// from OriginatorSSRC do we filter it?
// rtcpPacket.XR.OriginatorSSRC;
RTCPVoIPMetric receivedVoIPMetrics;
receivedVoIPMetrics.burstDensity = rtcpPacket.XRVOIPMetricItem.burstDensity;
receivedVoIPMetrics.burstDuration = rtcpPacket.XRVOIPMetricItem.burstDuration;
receivedVoIPMetrics.discardRate = rtcpPacket.XRVOIPMetricItem.discardRate;
receivedVoIPMetrics.endSystemDelay = rtcpPacket.XRVOIPMetricItem.endSystemDelay;
receivedVoIPMetrics.extRfactor = rtcpPacket.XRVOIPMetricItem.extRfactor;
receivedVoIPMetrics.gapDensity = rtcpPacket.XRVOIPMetricItem.gapDensity;
receivedVoIPMetrics.gapDuration = rtcpPacket.XRVOIPMetricItem.gapDuration;
receivedVoIPMetrics.Gmin = rtcpPacket.XRVOIPMetricItem.Gmin;
receivedVoIPMetrics.JBabsMax = rtcpPacket.XRVOIPMetricItem.JBabsMax;
receivedVoIPMetrics.JBmax = rtcpPacket.XRVOIPMetricItem.JBmax;
receivedVoIPMetrics.JBnominal = rtcpPacket.XRVOIPMetricItem.JBnominal;
receivedVoIPMetrics.lossRate = rtcpPacket.XRVOIPMetricItem.lossRate;
receivedVoIPMetrics.MOSCQ = rtcpPacket.XRVOIPMetricItem.MOSCQ;
receivedVoIPMetrics.MOSLQ = rtcpPacket.XRVOIPMetricItem.MOSLQ;
receivedVoIPMetrics.noiseLevel = rtcpPacket.XRVOIPMetricItem.noiseLevel;
receivedVoIPMetrics.RERL = rtcpPacket.XRVOIPMetricItem.RERL;
receivedVoIPMetrics.Rfactor = rtcpPacket.XRVOIPMetricItem.Rfactor;
receivedVoIPMetrics.roundTripDelay = rtcpPacket.XRVOIPMetricItem.roundTripDelay;
receivedVoIPMetrics.RXconfig = rtcpPacket.XRVOIPMetricItem.RXconfig;
receivedVoIPMetrics.signalLevel = rtcpPacket.XRVOIPMetricItem.signalLevel;
rtcpPacketInformation.AddVoIPMetric(&receivedVoIPMetrics);
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpXrVoipMetric; // received signal
}
rtcpParser.Iterate();
}
// no need for critsect we have _criticalSectionRTCPReceiver
void RTCPReceiver::HandlePLI(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation) {
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
if (main_ssrc_ == rtcpPacket.PLI.MediaSSRC) {
TRACE_EVENT_INSTANT0("webrtc_rtp", "PLI");
++packet_type_counter_.pli_packets;
// Received a signal that we need to send a new key frame.
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpPli;
}
rtcpParser.Iterate();
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleTMMBR(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
uint32_t senderSSRC = rtcpPacket.TMMBR.SenderSSRC;
RTCPReceiveInformation* ptrReceiveInfo = GetReceiveInformation(senderSSRC);
if (ptrReceiveInfo == NULL)
{
// This remote SSRC must be saved before.
rtcpParser.Iterate();
return;
}
if(rtcpPacket.TMMBR.MediaSSRC)
{
// rtcpPacket.TMMBR.MediaSSRC SHOULD be 0 if same as SenderSSRC
// in relay mode this is a valid number
senderSSRC = rtcpPacket.TMMBR.MediaSSRC;
}
// Use packet length to calc max number of TMMBR blocks
// each TMMBR block is 8 bytes
ptrdiff_t maxNumOfTMMBRBlocks = rtcpParser.LengthLeft() / 8;
// sanity
if(maxNumOfTMMBRBlocks > 200) // we can't have more than what's in one packet
{
assert(false);
rtcpParser.Iterate();
return;
}
ptrReceiveInfo->VerifyAndAllocateTMMBRSet((uint32_t)maxNumOfTMMBRBlocks);
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
while (pktType == RTCPUtility::kRtcpRtpfbTmmbrItemCode)
{
HandleTMMBRItem(*ptrReceiveInfo, rtcpPacket, rtcpPacketInformation, senderSSRC);
pktType = rtcpParser.Iterate();
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleTMMBRItem(RTCPReceiveInformation& receiveInfo,
const RTCPUtility::RTCPPacket& rtcpPacket,
RTCPPacketInformation& rtcpPacketInformation,
const uint32_t senderSSRC)
{
if (main_ssrc_ == rtcpPacket.TMMBRItem.SSRC &&
rtcpPacket.TMMBRItem.MaxTotalMediaBitRate > 0)
{
receiveInfo.InsertTMMBRItem(senderSSRC, rtcpPacket.TMMBRItem,
_clock->TimeInMilliseconds());
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpTmmbr;
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleTMMBN(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
RTCPReceiveInformation* ptrReceiveInfo = GetReceiveInformation(rtcpPacket.TMMBN.SenderSSRC);
if (ptrReceiveInfo == NULL)
{
// This remote SSRC must be saved before.
rtcpParser.Iterate();
return;
}
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpTmmbn;
// Use packet length to calc max number of TMMBN blocks
// each TMMBN block is 8 bytes
ptrdiff_t maxNumOfTMMBNBlocks = rtcpParser.LengthLeft() / 8;
// sanity
if(maxNumOfTMMBNBlocks > 200) // we cant have more than what's in one packet
{
assert(false);
rtcpParser.Iterate();
return;
}
ptrReceiveInfo->VerifyAndAllocateBoundingSet((uint32_t)maxNumOfTMMBNBlocks);
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
while (pktType == RTCPUtility::kRtcpRtpfbTmmbnItemCode)
{
HandleTMMBNItem(*ptrReceiveInfo, rtcpPacket);
pktType = rtcpParser.Iterate();
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleSR_REQ(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpSrReq;
rtcpParser.Iterate();
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleTMMBNItem(RTCPReceiveInformation& receiveInfo,
const RTCPUtility::RTCPPacket& rtcpPacket)
{
receiveInfo.TmmbnBoundingSet.AddEntry(
rtcpPacket.TMMBNItem.MaxTotalMediaBitRate,
rtcpPacket.TMMBNItem.MeasuredOverhead,
rtcpPacket.TMMBNItem.SSRC);
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleSLI(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
while (pktType == RTCPUtility::kRtcpPsfbSliItemCode)
{
HandleSLIItem(rtcpPacket, rtcpPacketInformation);
pktType = rtcpParser.Iterate();
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleSLIItem(const RTCPUtility::RTCPPacket& rtcpPacket,
RTCPPacketInformation& rtcpPacketInformation)
{
// in theory there could be multiple slices lost
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpSli; // received signal that we need to refresh a slice
rtcpPacketInformation.sliPictureId = rtcpPacket.SLIItem.PictureId;
}
void
RTCPReceiver::HandleRPSI(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPHelp::RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
if(pktType == RTCPUtility::kRtcpPsfbRpsiCode)
{
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpRpsi; // received signal that we have a confirmed reference picture
if(rtcpPacket.RPSI.NumberOfValidBits%8 != 0)
{
// to us unknown
// continue
rtcpParser.Iterate();
return;
}
rtcpPacketInformation.rpsiPictureId = 0;
// convert NativeBitString to rpsiPictureId
uint8_t numberOfBytes = rtcpPacket.RPSI.NumberOfValidBits /8;
for(uint8_t n = 0; n < (numberOfBytes-1); n++)
{
rtcpPacketInformation.rpsiPictureId += (rtcpPacket.RPSI.NativeBitString[n] & 0x7f);
rtcpPacketInformation.rpsiPictureId <<= 7; // prepare next
}
rtcpPacketInformation.rpsiPictureId += (rtcpPacket.RPSI.NativeBitString[numberOfBytes-1] & 0x7f);
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void RTCPReceiver::HandlePsfbApp(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation) {
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
if (pktType == RTCPUtility::kRtcpPsfbRembCode) {
pktType = rtcpParser.Iterate();
if (pktType == RTCPUtility::kRtcpPsfbRembItemCode) {
HandleREMBItem(rtcpParser, rtcpPacketInformation);
rtcpParser.Iterate();
}
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void
RTCPReceiver::HandleIJ(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
while (pktType == RTCPUtility::kRtcpExtendedIjItemCode)
{
HandleIJItem(rtcpPacket, rtcpPacketInformation);
pktType = rtcpParser.Iterate();
}
}
void
RTCPReceiver::HandleIJItem(const RTCPUtility::RTCPPacket& rtcpPacket,
RTCPPacketInformation& rtcpPacketInformation)
{
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpTransmissionTimeOffset;
rtcpPacketInformation.interArrivalJitter =
rtcpPacket.ExtendedJitterReportItem.Jitter;
}
void RTCPReceiver::HandleREMBItem(
RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation) {
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpRemb;
rtcpPacketInformation.receiverEstimatedMaxBitrate =
rtcpPacket.REMBItem.BitRate;
}
// no need for critsect we have _criticalSectionRTCPReceiver
void RTCPReceiver::HandleFIR(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation) {
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
RTCPReceiveInformation* ptrReceiveInfo =
GetReceiveInformation(rtcpPacket.FIR.SenderSSRC);
RTCPUtility::RTCPPacketTypes pktType = rtcpParser.Iterate();
while (pktType == RTCPUtility::kRtcpPsfbFirItemCode) {
HandleFIRItem(ptrReceiveInfo, rtcpPacket, rtcpPacketInformation);
pktType = rtcpParser.Iterate();
}
}
// no need for critsect we have _criticalSectionRTCPReceiver
void RTCPReceiver::HandleFIRItem(RTCPReceiveInformation* receiveInfo,
const RTCPUtility::RTCPPacket& rtcpPacket,
RTCPPacketInformation& rtcpPacketInformation) {
// Is it our sender that is requested to generate a new keyframe
if (main_ssrc_ != rtcpPacket.FIRItem.SSRC) {
return;
}
++packet_type_counter_.fir_packets;
// rtcpPacket.FIR.MediaSSRC SHOULD be 0 but we ignore to check it
// we don't know who this originate from
if (receiveInfo) {
// check if we have reported this FIRSequenceNumber before
if (rtcpPacket.FIRItem.CommandSequenceNumber !=
receiveInfo->lastFIRSequenceNumber) {
int64_t now = _clock->TimeInMilliseconds();
// sanity; don't go crazy with the callbacks
if ((now - receiveInfo->lastFIRRequest) > RTCP_MIN_FRAME_LENGTH_MS) {
receiveInfo->lastFIRRequest = now;
receiveInfo->lastFIRSequenceNumber =
rtcpPacket.FIRItem.CommandSequenceNumber;
// received signal that we need to send a new key frame
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpFir;
}
}
} else {
// received signal that we need to send a new key frame
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpFir;
}
}
void
RTCPReceiver::HandleAPP(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
rtcpPacketInformation.rtcpPacketTypeFlags |= kRtcpApp;
rtcpPacketInformation.applicationSubType = rtcpPacket.APP.SubType;
rtcpPacketInformation.applicationName = rtcpPacket.APP.Name;
rtcpParser.Iterate();
}
void
RTCPReceiver::HandleAPPItem(RTCPUtility::RTCPParserV2& rtcpParser,
RTCPPacketInformation& rtcpPacketInformation)
{
const RTCPUtility::RTCPPacket& rtcpPacket = rtcpParser.Packet();
rtcpPacketInformation.AddApplicationData(rtcpPacket.APP.Data, rtcpPacket.APP.Size);
rtcpParser.Iterate();
}
int32_t RTCPReceiver::UpdateTMMBR() {
int32_t numBoundingSet = 0;
uint32_t bitrate = 0;
uint32_t accNumCandidates = 0;
int32_t size = TMMBRReceived(0, 0, NULL);
if (size > 0) {
TMMBRSet* candidateSet = VerifyAndAllocateCandidateSet(size);
// Get candidate set from receiver.
accNumCandidates = TMMBRReceived(size, accNumCandidates, candidateSet);
} else {
// Candidate set empty.
VerifyAndAllocateCandidateSet(0); // resets candidate set
}
// Find bounding set
TMMBRSet* boundingSet = NULL;
numBoundingSet = FindTMMBRBoundingSet(boundingSet);
if (numBoundingSet == -1) {
LOG(LS_WARNING) << "Failed to find TMMBR bounding set.";
return -1;
}
// Set bounding set
// Inform remote clients about the new bandwidth
// inform the remote client
_rtpRtcp.SetTMMBN(boundingSet);
// might trigger a TMMBN
if (numBoundingSet == 0) {
// owner of max bitrate request has timed out
// empty bounding set has been sent
return 0;
}
// Get net bitrate from bounding set depending on sent packet rate
if (CalcMinBitRate(&bitrate)) {
// we have a new bandwidth estimate on this channel
CriticalSectionScoped lock(_criticalSectionFeedbacks);
if (_cbRtcpBandwidthObserver) {
_cbRtcpBandwidthObserver->OnReceivedEstimatedBitrate(bitrate * 1000);
}
}
return 0;
}
void RTCPReceiver::RegisterRtcpStatisticsCallback(
RtcpStatisticsCallback* callback) {
CriticalSectionScoped cs(_criticalSectionFeedbacks);
stats_callback_ = callback;
}
RtcpStatisticsCallback* RTCPReceiver::GetRtcpStatisticsCallback() {
CriticalSectionScoped cs(_criticalSectionFeedbacks);
return stats_callback_;
}
// Holding no Critical section
void RTCPReceiver::TriggerCallbacksFromRTCPPacket(
RTCPPacketInformation& rtcpPacketInformation) {
// Process TMMBR and REMB first to avoid multiple callbacks
// to OnNetworkChanged.
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpTmmbr) {
// Might trigger a OnReceivedBandwidthEstimateUpdate.
UpdateTMMBR();
}
unsigned int local_ssrc = 0;
{
// We don't want to hold this critsect when triggering the callbacks below.
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
local_ssrc = main_ssrc_;
}
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpSrReq) {
_rtpRtcp.OnRequestSendReport();
}
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpNack) {
if (rtcpPacketInformation.nackSequenceNumbers.size() > 0) {
LOG(LS_VERBOSE) << "Incoming NACK length: "
<< rtcpPacketInformation.nackSequenceNumbers.size();
_rtpRtcp.OnReceivedNACK(rtcpPacketInformation.nackSequenceNumbers);
}
}
{
CriticalSectionScoped lock(_criticalSectionFeedbacks);
// We need feedback that we have received a report block(s) so that we
// can generate a new packet in a conference relay scenario, one received
// report can generate several RTCP packets, based on number relayed/mixed
// a send report block should go out to all receivers.
if (_cbRtcpIntraFrameObserver) {
if ((rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpPli) ||
(rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpFir)) {
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpPli) {
LOG(LS_VERBOSE) << "Incoming PLI from SSRC "
<< rtcpPacketInformation.remoteSSRC;
} else {
LOG(LS_VERBOSE) << "Incoming FIR from SSRC "
<< rtcpPacketInformation.remoteSSRC;
}
_cbRtcpIntraFrameObserver->OnReceivedIntraFrameRequest(local_ssrc);
}
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpSli) {
_cbRtcpIntraFrameObserver->OnReceivedSLI(
local_ssrc, rtcpPacketInformation.sliPictureId);
}
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpRpsi) {
_cbRtcpIntraFrameObserver->OnReceivedRPSI(
local_ssrc, rtcpPacketInformation.rpsiPictureId);
}
}
if (_cbRtcpBandwidthObserver) {
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpRemb) {
LOG(LS_VERBOSE) << "Incoming REMB: "
<< rtcpPacketInformation.receiverEstimatedMaxBitrate;
_cbRtcpBandwidthObserver->OnReceivedEstimatedBitrate(
rtcpPacketInformation.receiverEstimatedMaxBitrate);
}
if (rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpSr ||
rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpRr) {
int64_t now = _clock->TimeInMilliseconds();
_cbRtcpBandwidthObserver->OnReceivedRtcpReceiverReport(
rtcpPacketInformation.report_blocks,
rtcpPacketInformation.rtt,
now);
}
}
if(_cbRtcpFeedback) {
if(!(rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpSr)) {
_cbRtcpFeedback->OnReceiveReportReceived(_id,
rtcpPacketInformation.remoteSSRC);
}
if(rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpXrVoipMetric) {
_cbRtcpFeedback->OnXRVoIPMetricReceived(_id,
rtcpPacketInformation.VoIPMetric);
}
if(rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpApp) {
_cbRtcpFeedback->OnApplicationDataReceived(_id,
rtcpPacketInformation.applicationSubType,
rtcpPacketInformation.applicationName,
rtcpPacketInformation.applicationLength,
rtcpPacketInformation.applicationData);
}
}
}
{
CriticalSectionScoped cs(_criticalSectionFeedbacks);
if (stats_callback_) {
for (ReportBlockList::const_iterator it =
rtcpPacketInformation.report_blocks.begin();
it != rtcpPacketInformation.report_blocks.end();
++it) {
RtcpStatistics stats;
stats.cumulative_lost = it->cumulativeLost;
stats.extended_max_sequence_number = it->extendedHighSeqNum;
stats.fraction_lost = it->fractionLost;
stats.jitter = it->jitter;
stats_callback_->StatisticsUpdated(stats, it->sourceSSRC);
}
}
}
}
int32_t RTCPReceiver::CNAME(const uint32_t remoteSSRC,
char cName[RTCP_CNAME_SIZE]) const {
assert(cName);
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
RTCPCnameInformation* cnameInfo = GetCnameInformation(remoteSSRC);
if (cnameInfo == NULL) {
return -1;
}
cName[RTCP_CNAME_SIZE - 1] = 0;
strncpy(cName, cnameInfo->name, RTCP_CNAME_SIZE - 1);
return 0;
}
// no callbacks allowed inside this function
int32_t RTCPReceiver::TMMBRReceived(const uint32_t size,
const uint32_t accNumCandidates,
TMMBRSet* candidateSet) const {
CriticalSectionScoped lock(_criticalSectionRTCPReceiver);
std::map<uint32_t, RTCPReceiveInformation*>::const_iterator
receiveInfoIt = _receivedInfoMap.begin();
if (receiveInfoIt == _receivedInfoMap.end()) {
return -1;
}
uint32_t num = accNumCandidates;
if (candidateSet) {
while( num < size && receiveInfoIt != _receivedInfoMap.end()) {
RTCPReceiveInformation* receiveInfo = receiveInfoIt->second;
if (receiveInfo == NULL) {
return 0;
}
for (uint32_t i = 0;
(num < size) && (i < receiveInfo->TmmbrSet.lengthOfSet()); i++) {
if (receiveInfo->GetTMMBRSet(i, num, candidateSet,
_clock->TimeInMilliseconds()) == 0) {
num++;
}
}
receiveInfoIt++;
}
} else {
while (receiveInfoIt != _receivedInfoMap.end()) {
RTCPReceiveInformation* receiveInfo = receiveInfoIt->second;
if(receiveInfo == NULL) {
return -1;
}
num += receiveInfo->TmmbrSet.lengthOfSet();
receiveInfoIt++;
}
}
return num;
}
} // namespace webrtc
| 34.907432
| 159
| 0.708747
|
TeamNuclear
|
a935c326dcfd44a395c61a7eba62a08a3f340ca3
| 2,875
|
hpp
|
C++
|
implementations/Metal/pipeline_state.hpp
|
rsayers/abstract-gpu
|
48176fcb88bde7d56de662c9e49d3d0e562819e1
|
[
"MIT"
] | 41
|
2016-03-25T18:14:37.000Z
|
2022-01-20T11:16:52.000Z
|
implementations/Metal/pipeline_state.hpp
|
rsayers/abstract-gpu
|
48176fcb88bde7d56de662c9e49d3d0e562819e1
|
[
"MIT"
] | 4
|
2016-05-05T22:08:01.000Z
|
2021-12-10T13:06:55.000Z
|
implementations/Metal/pipeline_state.hpp
|
rsayers/abstract-gpu
|
48176fcb88bde7d56de662c9e49d3d0e562819e1
|
[
"MIT"
] | 9
|
2016-05-23T01:51:25.000Z
|
2021-08-21T15:32:37.000Z
|
#ifndef AGPU_METAL_PIPELINE_STATE_HPP
#define AGPU_METAL_PIPELINE_STATE_HPP
#include "device.hpp"
#include "pipeline_command_state.hpp"
namespace AgpuMetal
{
class AMtlComputePipelineBuilder;
class AMtlGraphicsPipelineBuilder;
class AGPUMTLPipelineStateExtra
{
public:
virtual ~AGPUMTLPipelineStateExtra() {}
virtual void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder) {}
virtual void applyComputeCommands(id<MTLComputeCommandEncoder> computeEncoder) {}
virtual bool isRender() const
{
return false;
}
virtual bool isCompute() const
{
return false;
}
virtual MTLSize getLocalSize()
{
return MTLSize();
}
virtual agpu_pipeline_command_state *getCommandState()
{
return nullptr;
}
};
class AGPUMTLRenderPipelineState : public AGPUMTLPipelineStateExtra
{
public:
AGPUMTLRenderPipelineState();
~AGPUMTLRenderPipelineState();
virtual void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder) override;
virtual bool isRender() const override
{
return true;
}
virtual agpu_pipeline_command_state *getCommandState() override
{
return &commandState;
}
id<MTLRenderPipelineState> handle;
id<MTLDepthStencilState> depthStencilState;
agpu_pipeline_command_state commandState;
agpu_float depthBiasConstantFactor;
agpu_float depthBiasClamp;
agpu_float depthBiasSlopeFactor;
};
class AGPUMTLComputePipelineState : public AGPUMTLPipelineStateExtra
{
public:
AGPUMTLComputePipelineState();
~AGPUMTLComputePipelineState();
virtual void applyComputeCommands(id<MTLComputeCommandEncoder> renderEncoder) override;
virtual MTLSize getLocalSize() override
{
return localSize;
}
virtual bool isCompute() const override
{
return true;
}
id<MTLComputePipelineState> handle;
MTLSize localSize;
};
struct AMtlPipelineState : public agpu::pipeline_state
{
public:
AMtlPipelineState(const agpu::device_ref &device);
~AMtlPipelineState();
static agpu::pipeline_state_ref createRender(const agpu::device_ref &device, AMtlGraphicsPipelineBuilder *builder, id<MTLRenderPipelineState> handle);
static agpu::pipeline_state_ref createCompute(const agpu::device_ref &device, AMtlComputePipelineBuilder *builder, id<MTLComputePipelineState> handle);
void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder);
void applyComputeCommands(id<MTLComputeCommandEncoder> renderEncoder);
agpu_pipeline_command_state &getCommandState()
{
return *extraState->getCommandState();
}
agpu::device_ref device;
std::unique_ptr<AGPUMTLPipelineStateExtra> extraState;
};
} // End of namespace AgpuMetal
#endif //AGPU_METAL_PIPELINE_STATE_HPP
| 25.219298
| 155
| 0.737043
|
rsayers
|
a9391b60e4b6728117b94c273cd24979f4ac608d
| 20,758
|
cpp
|
C++
|
Code/Framework/GridMate/Tests/StreamSocketDriverTests.cpp
|
aaarsene/o3de
|
37e3b0226958974defd14dd6d808e8557dcd7345
|
[
"Apache-2.0",
"MIT"
] | 1
|
2021-09-13T00:01:12.000Z
|
2021-09-13T00:01:12.000Z
|
Code/Framework/GridMate/Tests/StreamSocketDriverTests.cpp
|
aaarsene/o3de
|
37e3b0226958974defd14dd6d808e8557dcd7345
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
Code/Framework/GridMate/Tests/StreamSocketDriverTests.cpp
|
aaarsene/o3de
|
37e3b0226958974defd14dd6d808e8557dcd7345
|
[
"Apache-2.0",
"MIT"
] | 1
|
2021-07-20T11:07:25.000Z
|
2021-07-20T11:07:25.000Z
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "Tests.h"
#include <GridMate/Carrier/StreamSocketDriver.h>
#include <AzCore/Math/Random.h>
using namespace GridMate;
#define TEST_WITH_EXTERNAL_HOSTS 0
namespace UnitTest
{
bool ConnectStreamSocketDriverServerClient(StreamSocketDriver& server, StreamSocketDriver& client, StreamSocketDriver::SocketDriverAddressPtr& serverAddress, const AZ::u32 attempts)
{
for (AZ::u32 i = 0; i < attempts; ++i)
{
server.Update();
client.Update();
if (server.GetNumberOfConnections() > 0 && client.IsConnectedTo(serverAddress))
{
return true;
}
}
return false;
}
bool ConnectStreamSocketInitializeAndConnect(StreamSocketDriver& server, StreamSocketDriver& client, const AZ::u32 attempts)
{
server.Initialize();
server.StartListen(1);
client.Initialize();
auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort());
auto serverAddress = AZStd::static_pointer_cast<SocketDriverAddress>(client.CreateDriverAddress(serverAddressName));
client.ConnectTo(serverAddress);
return ConnectStreamSocketDriverServerClient(server, client, serverAddress, attempts);
}
class StreamSocketOperationTests
: public GridMateMPTestFixture
{
public:
void run()
{
#if TEST_WITH_EXTERNAL_HOSTS
// using blocking sockets
// create and bind
GridMate::SocketDriverCommon::SocketType theSocket;
{
SocketAddressInfo addressInfo;
addressInfo.Resolve(nullptr, 0, Driver::BSDSocketFamilyType::BSD_AF_INET, false, GridMate::SocketAddressInfo::AdditionalOptionFlags::Passive);
theSocket = SocketOperations::CreateSocket(false, Driver::BSDSocketFamilyType::BSD_AF_INET);
AZ_TEST_ASSERT(SocketOperations::Bind(theSocket, addressInfo.GetAddressInfo()->ai_addr, addressInfo.GetAddressInfo()->ai_addrlen) == GridMate::Driver::EC_OK);
}
// connect and send and receive
{
GridMate::SocketOperations::ConnectionResult connectionResult;
SocketAddressInfo addressInfo;
auto flags = GridMate::SocketAddressInfo::AdditionalOptionFlags::Passive;
AZ_TEST_ASSERT(addressInfo.Resolve("www.github.com", 80, Driver::BSDSocketFamilyType::BSD_AF_INET, false, flags));
AZ_TEST_ASSERT(SocketOperations::Connect(theSocket, addressInfo.GetAddressInfo()->ai_addr, addressInfo.GetAddressInfo()->ai_addrlen, connectionResult) == GridMate::Driver::EC_OK);
// happy path
char buf[] = { "GET http://www.github.com/ HTTP/1.0\r\nUser-Agent: HTTPTool/1.0\r\n\r\n\r\n" };
AZ::u32 bytesSent = sizeof(buf);
AZ_TEST_ASSERT(SocketOperations::Send(theSocket, &buf[0], sizeof(buf), bytesSent) == GridMate::Driver::EC_OK);
AZ_TEST_ASSERT(bytesSent > 0);
char getBuffer[1024];
AZ::u32 bytesToGet = sizeof(getBuffer);
AZ_TEST_ASSERT(SocketOperations::Receive(theSocket, &getBuffer[0], bytesToGet) == GridMate::Driver::EC_OK);
AZ_TEST_ASSERT(bytesToGet > 0);
// fails expected
AZ_TEST_ASSERT(SocketOperations::Send(theSocket, &buf[0], 0, bytesSent) != GridMate::Driver::EC_OK);
AZ_TEST_ASSERT(SocketOperations::Send(theSocket, &buf[0], static_cast<AZ::u32>(-29), bytesSent) != GridMate::Driver::EC_OK);
bytesToGet = 0;
AZ_TEST_ASSERT(SocketOperations::Receive(theSocket, &getBuffer[0], bytesToGet) != GridMate::Driver::EC_OK);
bytesToGet = static_cast<AZ::u32>(-29);
AZ_TEST_ASSERT(SocketOperations::Receive(theSocket, &getBuffer[0], bytesToGet) != GridMate::Driver::EC_OK);
}
#endif // TEST_WITH_EXTERNAL_HOSTS
}
};
class StreamSocketDriverTestsCreateDelete
: public GridMateMPTestFixture
{
public:
void run()
{
StreamSocketDriver driver;
AZ_TEST_ASSERT(driver.GetMaxNumConnections() == 32);
}
};
class StreamSocketDriverTestsBindSocketEmpty
: public GridMateMPTestFixture
{
public:
void run()
{
{
StreamSocketDriver server(32);
auto ret = server.Initialize();
AZ_TEST_ASSERT(ret == GridMate::Driver::EC_OK);
}
{
StreamSocketDriver client(1);
auto ret = client.Initialize();
AZ_TEST_ASSERT(ret == GridMate::Driver::EC_OK);
}
}
};
class StreamSocketDriverTestsSimpleLockStepConnection
: public GridMateMPTestFixture
{
public:
void run()
{
StreamSocketDriver server(32);
auto serverInitialize = server.Initialize();
AZ_TEST_ASSERT(serverInitialize == GridMate::Driver::EC_OK);
StreamSocketDriver client(1);
auto clientInitialize = client.Initialize();
AZ_TEST_ASSERT(clientInitialize == GridMate::Driver::EC_OK);
AZ_TEST_ASSERT(server.StartListen(255) == GridMate::Driver::EC_OK);
auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort());
auto driveAddress = client.CreateDriverAddress(serverAddressName);
auto serverAddress = AZStd::static_pointer_cast<SocketDriverAddress>(driveAddress);
AZ_TEST_ASSERT(client.ConnectTo(serverAddress) == GridMate::Driver::EC_OK);
bool didConnect = false;
const int kNumTimes = 100;
for (int i = 0; i < kNumTimes; ++i)
{
server.Update();
client.Update();
if (server.GetNumberOfConnections() > 0 && client.IsConnectedTo(serverAddress))
{
didConnect = true;
break;
}
}
AZ_TEST_ASSERT(didConnect);
}
};
class StreamSocketDriverTestsEstablishConnectAndSend
: public GridMateMPTestFixture
{
public:
void run()
{
StreamSocketDriver server(2);
auto serverInitialize = server.Initialize(GridMate::Driver::BSDSocketFamilyType::BSD_AF_INET, "0.0.0.0", 29920, false, 0, 0);
AZ_TEST_ASSERT(serverInitialize == GridMate::Driver::EC_OK);
StreamSocketDriver client(1);
auto clientInitialize = client.Initialize();
AZ_TEST_ASSERT(clientInitialize == GridMate::Driver::EC_OK);
AZ_TEST_ASSERT(server.StartListen(2) == GridMate::Driver::EC_OK);
auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort());
auto driveAddress = client.CreateDriverAddress(serverAddressName);
auto serverAddress = AZStd::static_pointer_cast<SocketDriverAddress>(driveAddress);
AZ_TEST_ASSERT(client.ConnectTo(serverAddress) == GridMate::Driver::EC_OK);
bool didConnect = false;
const int kNumTimes = 1000;
for (int i = 0; i < kNumTimes; ++i)
{
server.Update();
client.Update();
if (server.GetNumberOfConnections() > 0 && client.IsConnectedTo(serverAddress))
{
didConnect = true;
break;
}
}
AZ_TEST_ASSERT(didConnect);
char packet[] = { "Hello Server" };
bool didSendPacket = false;
for (int i = 0; i < kNumTimes; ++i)
{
server.Update();
client.Update();
AZStd::intrusive_ptr<DriverAddress> from;
char buffer[64];
AZ::u32 bytesRead = server.Receive(buffer, sizeof(buffer), from);
if (bytesRead > 0)
{
AZ_TEST_ASSERT(bytesRead == sizeof(packet));
didSendPacket = memcmp(buffer, packet, sizeof(packet)) == 0;
break;
}
AZ_TEST_ASSERT(client.Send(driveAddress, packet, sizeof(packet)) == GridMate::Driver::EC_OK);
}
AZ_TEST_ASSERT(didSendPacket);
}
};
class StreamSocketDriverTestsManyRandomPackets
: public GridMateMPTestFixture
{
public:
void run()
{
StreamSocketDriver server(2, 1024);
server.Initialize();
server.StartListen(2);
auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort());
StreamSocketDriver client(1);
client.Initialize();
auto socketAddress = AZStd::static_pointer_cast<SocketDriverAddress>(client.CreateDriverAddress(serverAddressName));
client.ConnectTo(socketAddress);
bool didConnect = ConnectStreamSocketDriverServerClient(server, client, socketAddress, 100);
AZ_TEST_ASSERT(didConnect);
AZ::BetterPseudoRandom rand;
using TestPacket = AZStd::vector<char>;
using PacketQueue = AZStd::queue<TestPacket>;
#define MAX_PACKET_SIZE 128
const auto fnCreatePayload = [&](char* buffer, int size)
{
uint32_t randKey;
rand.GetRandom(randKey);
size_t numChars = randKey % size;
rand.GetRandom(buffer, numChars);
return numChars;
};
const auto fnReadAndCompare = [](PacketQueue& packetList, StreamSocketDriver& driver, AZStd::intrusive_ptr<DriverAddress>& from)
{
GridMate::Driver::ResultCode rc;
char buffer[MAX_PACKET_SIZE];
AZ::u32 bytesRead = driver.Receive(buffer, sizeof(buffer), from, &rc);
AZ_TEST_ASSERT(rc == GridMate::Driver::EC_OK);
while (bytesRead > 0)
{
auto tester = packetList.front();
packetList.pop();
AZ_TEST_ASSERT(memcmp(&buffer[0], &tester[0], bytesRead) == 0);
bytesRead = driver.Receive(buffer, sizeof(buffer), from, &rc);
AZ_TEST_ASSERT(rc == GridMate::Driver::EC_OK);
}
};
PacketQueue toServerPacketList;
PacketQueue toClientPacketList;
AZStd::intrusive_ptr<DriverAddress> clientAddress;
const int kNumTimes = 500;
for (int i = 0; i < kNumTimes; ++i)
{
server.Update();
client.Update();
// do reads
AZStd::intrusive_ptr<DriverAddress> from;
fnReadAndCompare(toServerPacketList, server, clientAddress);
fnReadAndCompare(toClientPacketList, client, from);
// do write
if (i == 0 || (i % 2) == 0)
{
char buffer[MAX_PACKET_SIZE];
size_t numToSend = fnCreatePayload(buffer, sizeof(buffer));
if (numToSend > 0)
{
TestPacket testPacket(&buffer[0], &buffer[numToSend]);
toServerPacketList.push(testPacket);
AZ_TEST_ASSERT(client.Send(socketAddress, &buffer[0], (AZ::u32)numToSend) == GridMate::Driver::EC_OK);
}
}
else if (clientAddress && clientAddress->GetPort() > 0)
{
char buffer[MAX_PACKET_SIZE];
size_t numToSend = fnCreatePayload(buffer, sizeof(buffer));
if (numToSend > 0)
{
TestPacket testPacket(&buffer[0], &buffer[numToSend]);
toClientPacketList.push(testPacket);
AZ_TEST_ASSERT(server.Send(clientAddress, &buffer[0], (AZ::u32)numToSend) == GridMate::Driver::EC_OK);
}
}
}
#undef MAX_PACKET_SIZE
}
};
class Integ_StreamSocketDriverTestsTooManyConnections
: public GridMateMPTestFixture
{
public:
void run()
{
using ClientList = AZStd::vector<StreamSocketDriver*>;
const auto fnUpdate = [](StreamSocketDriver& server, ClientList& clients)
{
server.Update();
for (auto& c : clients)
{
c->Update();
}
};
const AZ::u32 maxConnections = 4;
StreamSocketDriver server(maxConnections);
server.Initialize();
server.StartListen(maxConnections + 1);
auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort());
ClientList clientList;
const AZ::u32 tooManyConnections = 32;
for (int i = 0; i < tooManyConnections; ++i)
{
auto c = aznew StreamSocketDriver(1);
c->Initialize();
auto serverAddress = c->CreateDriverAddress(serverAddressName);
if (c->ConnectTo(AZStd::static_pointer_cast<SocketDriverAddress>(serverAddress)) == GridMate::Driver::EC_OK)
{
clientList.emplace_back(c);
}
else
{
delete c;
}
fnUpdate(server, clientList);
}
const AZ::u32 nUpdates = 100;
for (AZ::u32 i = 0; i < nUpdates; ++i)
{
fnUpdate(server, clientList);
AZ_TEST_ASSERT(server.GetNumberOfConnections() <= maxConnections);
}
for (auto& c : clientList)
{
delete c;
}
}
};
class StreamSocketDriverTestsClientToInvalidServer
: public GridMateMPTestFixture
{
public:
void run()
{
const auto fnUpdateDrivers = [](StreamSocketDriver& server, StreamSocketDriver& client, const AZ::u32 nCount)
{
for (AZ::u32 i = 0; i < nCount; ++i)
{
server.Update();
client.Update();
}
};
StreamSocketDriver server(1);
server.Initialize();
server.StartListen(1);
auto serverAddressName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort());
StreamSocketDriver client(1);
client.Initialize();
auto serverAddress = AZStd::static_pointer_cast<SocketDriverAddress>(client.CreateDriverAddress(serverAddressName));
client.ConnectTo(serverAddress);
bool wasConnected = false;
const AZ::u32 kMaxTries = 10;
for (AZ::u32 i = 0; i < kMaxTries; ++i)
{
fnUpdateDrivers(server, client, 20);
if (client.IsConnectedTo(serverAddress))
{
wasConnected = true;
break;
}
}
AZ_TEST_ASSERT(wasConnected);
AZ_TEST_ASSERT(client.DisconnectFrom(serverAddress) == GridMate::Driver::EC_OK);
for (AZ::u32 i = 0; i < kMaxTries; ++i)
{
// allow for graceful disconnect
fnUpdateDrivers(server, client, 20);
}
AZ_TEST_ASSERT(client.IsConnectedTo(serverAddress) == false);
// try to connect to a bogus server address
auto bogusAddress = AZStd::static_pointer_cast<SocketDriverAddress>(client.CreateDriverAddress("127.0.0.1|1"));
// the attempt should succeed...
AZ_TEST_ASSERT(client.ConnectTo(bogusAddress) == GridMate::Driver::EC_OK);
//... but it should not go into 'connected mode'
for (AZ::u32 i = 0; i < kMaxTries; ++i)
{
fnUpdateDrivers(server, client, 20);
AZ_TEST_ASSERT(client.IsConnectedTo(bogusAddress) == false);
}
//... now reconnect to the server
client.ConnectTo(serverAddress);
wasConnected = false;
for (AZ::u32 i = 0; i < kMaxTries; ++i)
{
fnUpdateDrivers(server, client, 20);
if (client.IsConnectedTo(serverAddress))
{
wasConnected = true;
break;
}
}
AZ_TEST_ASSERT(wasConnected);
}
};
class StreamSocketDriverTestsManySends
: public GridMateMPTestFixture
{
public:
void run()
{
StreamSocketDriver server(1);
StreamSocketDriver client(1);
bool isConnected = ConnectStreamSocketInitializeAndConnect(server, client, 100);
AZ_TEST_ASSERT(isConnected);
auto serverName = SocketDriverCommon::IPPortToAddressString("127.0.0.1", server.GetPort());
auto serverAddr = client.CreateDriverAddress(serverName);
AZ::BetterPseudoRandom rand;
using TestPacket = AZStd::vector<char>;
using PacketQueue = AZStd::queue<TestPacket>;
const auto fnCreatePayload = [&](char* buffer, int size)
{
uint32_t randKey;
rand.GetRandom(randKey);
size_t numChars = (randKey % size) + 1;
rand.GetRandom(buffer, numChars);
return numChars;
};
const AZ::u32 kManyPackets = 1024;
const AZ::u32 kMaxPacketSize = 128;
PacketQueue sentPackets;
for (int i = 0; i < kManyPackets; ++i)
{
char buffer[kMaxPacketSize];
size_t numToSend = fnCreatePayload(buffer, sizeof(buffer));
TestPacket testPacket(&buffer[0], &buffer[numToSend]);
if (client.Send(serverAddr, buffer, static_cast<AZ::u32>(numToSend)) == GridMate::Driver::EC_OK)
{
sentPackets.push(testPacket);
}
else
{
client.Update();
server.Update();
}
}
AZ::u32 numAttempts = 2000;
GridMate::Driver::ResultCode resultCode;
AZStd::intrusive_ptr<GridMate::DriverAddress> from;
char buffer[kMaxPacketSize];
client.Update();
server.Update();
AZ::u32 numBytes = server.Receive(buffer, sizeof(buffer), from, &resultCode);
while (!sentPackets.empty())
{
AZ_TEST_ASSERT(numAttempts > 0);
if (numAttempts == 0)
{
break;
}
--numAttempts;
if (numBytes > 0)
{
auto tester = sentPackets.front();
sentPackets.pop();
auto nCompare = memcmp(&buffer[0], &tester[0], numBytes);
if (nCompare != 0)
{
--numAttempts;
}
AZ_TEST_ASSERT(nCompare == 0);
}
client.Update();
server.Update();
numBytes = server.Receive(buffer, sizeof(buffer), from, &resultCode);
}
}
};
}
#if !AZ_TRAIT_GRIDMATE_UNIT_TEST_DISABLE_STREAM_SOCKET_DRIVER_TESTS
GM_TEST_SUITE(StreamSocketDriverTests)
GM_TEST(StreamSocketOperationTests);
GM_TEST(StreamSocketDriverTestsCreateDelete);
GM_TEST(StreamSocketDriverTestsBindSocketEmpty);
GM_TEST(StreamSocketDriverTestsSimpleLockStepConnection);
GM_TEST(StreamSocketDriverTestsEstablishConnectAndSend);
GM_TEST(StreamSocketDriverTestsManyRandomPackets);
GM_TEST(Integ_StreamSocketDriverTestsTooManyConnections);
GM_TEST(StreamSocketDriverTestsClientToInvalidServer);
GM_TEST(StreamSocketDriverTestsManySends);
GM_TEST_SUITE_END()
#endif // !AZ_TRAIT_GRIDMATE_UNIT_TEST_DISABLE_STREAM_SOCKET_DRIVER_TESTS
| 38.583643
| 195
| 0.558098
|
aaarsene
|
a9393254e80008724c7ebebede9caf3dc7a1d303
| 112
|
hpp
|
C++
|
tests/mygtest.hpp
|
fretboardfreak/audiowav
|
ea7f8b5e0f34557f9fdf2a459320976739647395
|
[
"Apache-2.0"
] | 20
|
2016-02-01T13:07:45.000Z
|
2020-08-30T18:59:39.000Z
|
tests/mygtest.hpp
|
fretboardfreak/audiowav
|
ea7f8b5e0f34557f9fdf2a459320976739647395
|
[
"Apache-2.0"
] | null | null | null |
tests/mygtest.hpp
|
fretboardfreak/audiowav
|
ea7f8b5e0f34557f9fdf2a459320976739647395
|
[
"Apache-2.0"
] | 4
|
2018-05-13T19:05:28.000Z
|
2021-12-29T18:08:46.000Z
|
/* A simple wrapper to suppress all warnings from gtest.h */
#pragma GCC system_header
#include "gtest/gtest.h"
| 28
| 60
| 0.758929
|
fretboardfreak
|
a939ade4483227aa19a35cc587b363ac97506583
| 5,391
|
cpp
|
C++
|
lib/backend/cpu_x86.cpp
|
ptillet/neo-ica
|
f7290219f49169d4cd51c9e58b2b8ee95aeda543
|
[
"MIT"
] | 8
|
2016-12-18T13:31:17.000Z
|
2021-11-03T09:31:14.000Z
|
lib/backend/cpu_x86.cpp
|
ptillet/DSHF-ICA
|
f7290219f49169d4cd51c9e58b2b8ee95aeda543
|
[
"MIT"
] | 1
|
2017-08-16T06:42:33.000Z
|
2017-08-18T22:14:09.000Z
|
lib/backend/cpu_x86.cpp
|
ptillet/DSHF-ICA
|
f7290219f49169d4cd51c9e58b2b8ee95aeda543
|
[
"MIT"
] | 3
|
2017-07-03T08:44:48.000Z
|
2018-08-30T06:54:10.000Z
|
/* cpu_x86.cpp
*
* Author : Alexander J. Yee
* Date Created : 04/12/2014
* Last Modified : 04/12/2014
*
*/
// Dependencies
#include <iostream>
#include <cstring>
#if _WIN32
#include <Windows.h>
#include <intrin.h>
#else
#include <cpuid.h>
#endif
#include "neo_ica/backend/cpu_x86.h"
namespace neo_ica
{
/*
* ---------------------
* WINDOWS CPUID
* --------------------
*/
#if _WIN32
void cpu_x86::cpuid(int32_t out[4], int32_t x){
__cpuidex(out, x, 0);
}
__int64 xgetbv(unsigned int x){
return _xgetbv(x);
}
// Detect 64-bit - Note that this snippet of code for detecting 64-bit has been copied from MSDN.
typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
BOOL IsWow64()
{
BOOL bIsWow64 = FALSE;
LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
if (NULL != fnIsWow64Process)
{
if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
{
printf("Error Detecting Operating System.\n");
printf("Defaulting to 32-bit OS.\n\n");
bIsWow64 = FALSE;
}
}
return bIsWow64;
}
bool cpu_x86::detect_OS_x64(){
#ifdef _M_X64
return true;
#else
return IsWow64() != 0;
#endif
}
#elif (defined __linux) && (defined __GNUC__)
/*
* ---------------------
* LINUX CPUID
* --------------------
*/
void cpu_x86::cpuid(int32_t out[4], int32_t x){
__cpuid_count(x, 0, out[0], out[1], out[2], out[3]);
}
uint64_t xgetbv(unsigned int index){
uint32_t eax, edx;
__asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index));
return ((uint64_t)edx << 32) | eax;
}
#define _XCR_XFEATURE_ENABLED_MASK 0
// Detect 64-bit
bool cpu_x86::detect_OS_x64(){
// We only support x64 on Linux.
return true;
}
#else
#error "No cpuid intrinsic defined."
#endif
bool cpu_x86::detect_OS_AVX(){
// Copied from: http://stackoverflow.com/a/22521619/922184
bool avxSupported = false;
int cpuInfo[4];
cpuid(cpuInfo, 1);
bool osUsesXSAVE_XrhoTORE = (cpuInfo[2] & (1 << 27)) != 0;
bool cpuAVXSuport = (cpuInfo[2] & (1 << 28)) != 0;
if (osUsesXSAVE_XrhoTORE && cpuAVXSuport)
{
uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK);
avxSupported = (xcrFeatureMask & 0x6) == 0x6;
}
return avxSupported;
}
bool cpu_x86::detect_OS_AVX512(){
if (!detect_OS_AVX())
return false;
uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK);
return (xcrFeatureMask & 0xe6) == 0xe6;
}
void cpu_x86::detect_host(){
// OS Features
OS_x64 = detect_OS_x64();
OS_AVX = detect_OS_AVX();
OS_AVX512 = detect_OS_AVX512();
// Vendor
std::string vendor(get_vendor_string());
if (vendor == "GenuineIntel"){
Vendor_Intel = true;
}else if (vendor == "AuthenticAMD"){
Vendor_AMD = true;
}
int info[4];
cpuid(info, 0);
int nIds = info[0];
cpuid(info, 0x80000000);
uint32_t nExIds = info[0];
// Detect Features
if (nIds >= 0x00000001){
cpuid(info, 0x00000001);
HW_MMX = (info[3] & ((int)1 << 23)) != 0;
HW_SSE = (info[3] & ((int)1 << 25)) != 0;
HW_SSE2 = (info[3] & ((int)1 << 26)) != 0;
HW_SSE3 = (info[2] & ((int)1 << 0)) != 0;
HW_SSSE3 = (info[2] & ((int)1 << 9)) != 0;
HW_SSE41 = (info[2] & ((int)1 << 19)) != 0;
HW_SSE42 = (info[2] & ((int)1 << 20)) != 0;
HW_AES = (info[2] & ((int)1 << 25)) != 0;
HW_AVX = (info[2] & ((int)1 << 28)) != 0;
HW_FMA3 = (info[2] & ((int)1 << 12)) != 0;
HW_RDRAND = (info[2] & ((int)1 << 30)) != 0;
}
if (nIds >= 0x00000007){
cpuid(info, 0x00000007);
HW_AVX2 = (info[1] & ((int)1 << 5)) != 0;
HW_BMI1 = (info[1] & ((int)1 << 3)) != 0;
HW_BMI2 = (info[1] & ((int)1 << 8)) != 0;
HW_ADX = (info[1] & ((int)1 << 19)) != 0;
HW_MPX = (info[1] & ((int)1 << 14)) != 0;
HW_SHA = (info[1] & ((int)1 << 29)) != 0;
HW_PREFETCHWT1 = (info[2] & ((int)1 << 0)) != 0;
HW_AVX512_F = (info[1] & ((int)1 << 16)) != 0;
HW_AVX512_CD = (info[1] & ((int)1 << 28)) != 0;
HW_AVX512_PF = (info[1] & ((int)1 << 26)) != 0;
HW_AVX512_ER = (info[1] & ((int)1 << 27)) != 0;
HW_AVX512_VL = (info[1] & ((int)1 << 31)) != 0;
HW_AVX512_BW = (info[1] & ((int)1 << 30)) != 0;
HW_AVX512_DQ = (info[1] & ((int)1 << 17)) != 0;
HW_AVX512_IFMA = (info[1] & ((int)1 << 21)) != 0;
HW_AVX512_VBMI = (info[2] & ((int)1 << 1)) != 0;
}
if (nExIds >= 0x80000001){
cpuid(info, 0x80000001);
HW_x64 = (info[3] & ((int)1 << 29)) != 0;
HW_ABM = (info[2] & ((int)1 << 5)) != 0;
HW_SSE4a = (info[2] & ((int)1 << 6)) != 0;
HW_FMA4 = (info[2] & ((int)1 << 16)) != 0;
HW_XOP = (info[2] & ((int)1 << 11)) != 0;
}
}
cpu_x86::cpu_x86(){
detect_host();
}
std::string cpu_x86::get_vendor_string(){
int32_t CPUInfo[4];
char name[13];
cpuid(CPUInfo, 0);
memcpy(name + 0, &CPUInfo[1], 4);
memcpy(name + 4, &CPUInfo[3], 4);
memcpy(name + 8, &CPUInfo[2], 4);
name[12] = '\0';
return name;
}
}
| 25.671429
| 98
| 0.523836
|
ptillet
|
a93c2d0ed8de1b996119357bebe64199221b7bb8
| 14,451
|
cpp
|
C++
|
TRTCSDK/Windows/QTDemo/base/VideoListView.cpp
|
aliyunvideo/Queen_SDK_Android
|
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
|
[
"Apache-2.0"
] | 2
|
2021-07-06T03:32:25.000Z
|
2021-12-17T02:24:16.000Z
|
TRTCSDK/Mac/QTDemo/base/VideoListView.cpp
|
aliyunvideo/Queen_SDK_Android
|
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
|
[
"Apache-2.0"
] | null | null | null |
TRTCSDK/Mac/QTDemo/base/VideoListView.cpp
|
aliyunvideo/Queen_SDK_Android
|
e46e32e16f8a6ecf3746a5c397a6a1f36189e93c
|
[
"Apache-2.0"
] | 1
|
2022-03-31T09:07:26.000Z
|
2022-03-31T09:07:26.000Z
|
// QTSimpleDemo
//
// Copyright © 2020 tencent. All rights reserved.
//
#include "VideoListView.h"
#include "ui_VideoListView.h"
#include <QtDebug>
#include "ui_TestVideoSetting.h"
#ifdef __APPLE__
#include "GenerateTestUserSig.h"
#endif
#ifdef _WIN32
#include "GenerateTestUsersig.h"
#endif
VideoListView::VideoListView(QWidget *parent) :
QDialog(parent),
ui(new Ui::VideoListView) {
ui->setupUi(this);
m_trtcCloud = getTRTCShareInstance();
if (m_trtcCloud == nullptr) return;
m_trtcCloud->addCallback(this);
setupList();
updateVideoViews(true);
}
VideoListView::~VideoListView() {
reset();
delete ui;
if (m_trtcCloud != nullptr) {
m_trtcCloud->removeCallback(this);
m_trtcCloud = nullptr;
}
}
QWidget *VideoListView::getLocalView() {
if (m_videoViews.count() > 0) {
return m_videoViews.at(0);
}
return nullptr;
}
void VideoListView::enterRoom(const trtc::TRTCParams& params, trtc::TRTCAppScene scene) {
m_userId = QString(params.userId);
m_trtcCloud->setDefaultStreamRecvMode(true, true);
m_trtcCloud->enableAudioVolumeEvaluation(300);
m_trtcCloud->enterRoom(params, scene);
m_trtcCloud->startLocalAudio(trtc::TRTCAudioQualityDefault);
// 真实开发中可根据不同场景灵活调用
m_trtcCloud->startLocalPreview(reinterpret_cast<trtc::TXView>(ui->videoView0->winId()));
m_trtcCloud->setBeautyStyle(trtc::TRTCBeautyStyleSmooth, 6, 6, 6);
}
void VideoListView::updateRoomMembers() {
bool isEmpty = m_roomMembers.count() == 0;
ui->switchAllRemoteVideo->setEnabled(isEmpty == false);
ui->switchAllRemoteAudio->setEnabled(isEmpty == false);
if (isEmpty) {
ui->memberLabel->setText(QString::fromLocal8Bit("暂无成员~").toUtf8());
return;
}
QString memberIds = QString::fromLocal8Bit("成员列表: ");
for (int i = 0; i < m_roomMembers.count(); i++) {
memberIds = memberIds + m_roomMembers.at(i) + (i == m_roomMembers.count() - 1 ? "" : ", ");
}
QByteArray mids = memberIds.toUtf8();
ui->memberLabel->setText(mids);
}
void VideoListView::reset() {
updateVideoViews(true);
updateRoomMembers();
ui->switchAllRemoteVideo->setEnabled(false);
ui->switchAllRemoteAudio->setEnabled(false);
ui->switchDashBoardButton->setEnabled(false);
}
void VideoListView::updateVideoViews(bool hidden) {
std::lock_guard<std::mutex> lk(m_remoteVideoViewsMutex);
for (int i = 0; i < m_videoViews.count(); i++) {
QWidget *videoView = m_videoViews[i];
videoView->setHidden(hidden);
QProgressBar *progressBar = m_progressBars[i];
progressBar->setHidden(hidden);
QPushButton *audio = m_audios[i];
audio->setHidden(hidden);
QPushButton *video = m_videos[i];
video->setHidden(hidden);
updateButtonState(audio, false, Audio, progressBar);
updateButtonState(video, false, Video);
}
#ifdef _WIN32
// fix the white border issue for win-system
if (m_videoViews.count() < 1) return;
QPalette pal;
pal.setColor(QPalette::Background, Qt::black);
m_videoViews[0]->setAutoFillBackground(true);
m_videoViews[0]->setPalette(pal);
#endif
}
void VideoListView::onEnterRoom(int result) {
if (result > 0) {
// 进房成功
ui->videoView0->setHidden(false);
ui->video0->setHidden(false);
ui->audio0->setHidden(false);
ui->progressBar0->setHidden(false);
m_userIds.push_back(m_userId);
ui->switchDashBoardButton->setEnabled(true);
} else {
// 进房失败
QString errorTip(QString::fromLocal8Bit("进房失败,错误码:").toUtf8());
errorTip.append(QString::number(result));
errorTip.append(QString::fromLocal8Bit("\n请您检查房间号、用户ID等输入是否合法\n或您可尝试重新输入房间号、用户ID").toUtf8());
std::string msg = errorTip.toStdString();
m_alertDialog.showMessageTip(msg.c_str());
}
}
void VideoListView::onExitRoom(int reason) {
ui->videoView0->setHidden(true);
m_roomMembers.clear();
m_userIds.clear();
reset();
}
void VideoListView::onRemoteUserEnterRoom(const char *userId) {
m_roomMembers.push_back(QString(userId));
updateRoomMembers();
}
void VideoListView::onRemoteUserLeaveRoom(const char *userId, int reason) {
m_roomMembers.remove(m_roomMembers.indexOf(QString(userId)));
updateRoomMembers();
}
void VideoListView::onUserVoiceVolume(trtc::TRTCVolumeInfo* userVolumes, uint32_t userVolumesCount, uint32_t totalVolume) {
if (userVolumes == nullptr) return;
int volume = (int)userVolumes->volume;
if (strlen(userVolumes->userId) < 1) {
// 自己在说话
ui->progressBar0->setValue(volume);
} else {
QString uid = QString(userVolumes->userId);
int index = m_userIds.indexOf(uid);
if (index > 0 && index < m_progressBars.count() - 1) {
m_progressBars[index]->setValue(volume);
}
}
}
void VideoListView::onUserVideoAvailable(const char *userId, bool available) {
int index = m_userIds.indexOf(QString(userId));
if (available) {
if (index < 0) {
m_userIds.push_back(QString(userId));
refreshRemoteVideoViews(m_userIds.count() - 1);
ui->switchAllRemoteAudio->setChecked(false);
ui->switchAllRemoteVideo->setChecked(false);
} else {
// 因为第0个永远是本地画面,所以从1开始refresh
refreshRemoteVideoViews(1);
}
} else {
m_trtcCloud->stopRemoteView(userId, trtc::TRTCVideoStreamTypeSmall);
m_userIds.remove(index);
refreshRemoteVideoViews(index);
}
}
void VideoListView::refreshRemoteVideoViews(int from) {
for (int i = from; i < m_videoViews.count(); i++) {
bool needUpdate = i < m_userIds.count();
if (needUpdate) {
std::string str = m_userIds.at(i).toStdString();
m_trtcCloud->startRemoteView(str.c_str(), trtc::TRTCVideoStreamTypeSmall, reinterpret_cast<trtc::TXView>(m_videoViews[i]->winId()));
on_switchAllRemoteAudio_clicked(false);
on_switchAllRemoteVideo_clicked(false);
}
m_audios.at(i)->setHidden(!needUpdate);
m_videos.at(i)->setHidden(!needUpdate);
m_videoViews.at(i)->setHidden(!needUpdate);
m_progressBars.at(i)->setHidden(!needUpdate);
}
}
void VideoListView::onUserSubStreamAvailable(const char *userId, bool available) {
if (available) {
m_trtcCloud->startRemoteView(userId, trtc::TRTCVideoStreamTypeSub, (trtc::TXView)(ui->screenCaptureView->winId()));
} else {
m_trtcCloud->stopRemoteView(userId, trtc::TRTCVideoStreamTypeSub);
}
}
void VideoListView::on_switchAllRemoteVideo_clicked(bool checked) {
m_trtcCloud->muteAllRemoteVideoStreams(checked);
for (int i = 1; i < m_videos.count(); i++) {
updateButtonState(m_videos[i], checked, Video);
}
}
void VideoListView::on_switchAllRemoteAudio_clicked(bool checked) {
m_trtcCloud->muteAllRemoteAudio(checked);
for (int i = 1; i < m_audios.count(); i++) {
updateButtonState(m_audios[i], checked, Audio, m_progressBars[i]);
}
}
/**
* 简单起见,本Demo中下述 audio & video 的相关控制事件定义的比较激进粗糙,真实开发中应考虑封装优化 *
*/
void VideoListView::on_audio0_clicked() {
static bool flag = false; flag = !flag;
if (m_progressBars.count() < 1) return;
if (flag) ui->audio0->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/audio_close.png);}");
else ui->audio0->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/audio_normal.png);}");
if (flag == false) {
if (m_progressBars[0] != nullptr) m_progressBars[0]->setValue(0);
}
m_trtcCloud->muteLocalAudio(flag);
}
void VideoListView::on_video0_clicked() {
static bool flag = false; flag = !flag;
if (flag) ui->video0->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/video_close.png);}");
else ui->video0->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/video_normal.png);}");
m_trtcCloud->muteLocalVideo(flag);
}
void VideoListView::on_audio1_clicked() {
static bool flag = false; flag = !flag;
if (m_progressBars.count() < 2) return;
updateButtonState(ui->audio1, flag, Audio, m_progressBars[1]);
muteRemoteStream(Audio, flag, 1);
}
void VideoListView::on_video1_clicked() {
static bool flag = false; flag = !flag;
updateButtonState(ui->video1, flag, Video);
muteRemoteStream(Video, flag, 1);
}
void VideoListView::on_audio2_clicked() {
static bool flag = false; flag = !flag;
if (m_progressBars.count() < 3) return;
updateButtonState(ui->audio2, flag, Audio, m_progressBars[2]);
muteRemoteStream(Audio, flag, 2);
}
void VideoListView::on_video2_clicked() {
static bool flag = false; flag = !flag;
updateButtonState(ui->video2, flag, Video);
muteRemoteStream(Video, flag, 2);
}
void VideoListView::on_audio3_clicked() {
static bool flag = false; flag = !flag;
if (m_progressBars.count() < 4) return;
updateButtonState(ui->audio3, flag, Audio, m_progressBars[3]);
muteRemoteStream(Audio, flag, 3);
}
void VideoListView::on_video3_clicked() {
static bool flag = false; flag = !flag;
updateButtonState(ui->video3, flag, Video);
muteRemoteStream(Video, flag, 3);
}
void VideoListView::on_audio4_clicked() {
static bool flag = false; flag = !flag;
if (m_progressBars.count() < 5) return;
updateButtonState(ui->audio4, flag, Audio, m_progressBars[4]);
muteRemoteStream(Audio, flag, 4);
}
void VideoListView::on_video4_clicked() {
static bool flag = false; flag = !flag;
updateButtonState(ui->video4, flag, Video);
muteRemoteStream(Video, flag, 4);
}
void VideoListView::on_audio5_clicked() {
static bool flag = false; flag = !flag;
if (m_progressBars.count() < 6) return;
updateButtonState(ui->audio5, flag, Audio, m_progressBars[5]);
muteRemoteStream(Audio, flag, 5);
}
void VideoListView::on_video5_clicked() {
static bool flag = false; flag = !flag;
updateButtonState(ui->video5, flag, Video);
muteRemoteStream(Video, flag, 5);
}
void VideoListView::on_audio6_clicked() {
static bool flag = false; flag = !flag;
if (m_progressBars.count() < 7) return;
updateButtonState(ui->audio6, flag, Audio, m_progressBars[6]);
muteRemoteStream(Audio, flag, 6);
}
void VideoListView::on_video6_clicked() {
static bool flag = false; flag = !flag;
updateButtonState(ui->video6, flag, Video);
muteRemoteStream(Video, flag, 6);
}
void VideoListView::on_audio7_clicked() {
static bool flag = false; flag = !flag;
if (m_progressBars.count() < 8) return;
updateButtonState(ui->audio7, flag, Audio, m_progressBars[7]);
muteRemoteStream(Audio, flag, 7);
}
void VideoListView::on_video7_clicked() {
static bool flag = false; flag = !flag;
updateButtonState(ui->video7, flag, Video);
muteRemoteStream(Video, flag, 7);
}
void VideoListView::muteRemoteStream(ControlButtonType type, bool mute, int index) {
if (index < 0 || index > m_userIds.count() - 1) return;
if (type == Audio) {
std::string uid = m_userIds.at(index).toStdString();
m_trtcCloud->muteRemoteAudio(uid.c_str(), mute);
} else if (type == Video) {
std::string uid = m_userIds.at(index).toStdString();
m_trtcCloud->muteRemoteVideoStream(uid.c_str(), mute);
}
}
void VideoListView::updateButtonState(QPushButton *button, bool state, ControlButtonType type, QProgressBar *progressBar) {
if (type == Audio) {
if (state) button->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/audio_close.png);}");
else button->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/audio_normal.png);}");
if (state == false) {
ui->switchAllRemoteAudio->setChecked(false);
if (progressBar != nullptr) progressBar->setValue(0);
}
} else if (type == Video) {
if (state) button->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/video_close.png);}");
else button->setStyleSheet("QPushButton{border-image: url(:/switch/image/switch/video_normal.png);}");
if (state == false) ui->switchAllRemoteVideo->setChecked(false);
}
}
void VideoListView::on_switchDashBoardButton_clicked(bool checked) {
m_trtcCloud->showDebugView(checked ? 2 : 0); // 0不显示信息,1显示简略信息,2显示详细信息
}
void VideoListView::setupList() {
// 目前最多支持 8 个画面的布局
m_videoViews.push_back(ui->videoView0);
m_videoViews.push_back(ui->videoView1);
m_videoViews.push_back(ui->videoView2);
m_videoViews.push_back(ui->videoView3);
m_videoViews.push_back(ui->videoView4);
m_videoViews.push_back(ui->videoView5);
m_videoViews.push_back(ui->videoView6);
m_videoViews.push_back(ui->videoView7);
m_progressBars.push_back(ui->progressBar0);
m_progressBars.push_back(ui->progressBar1);
m_progressBars.push_back(ui->progressBar2);
m_progressBars.push_back(ui->progressBar3);
m_progressBars.push_back(ui->progressBar4);
m_progressBars.push_back(ui->progressBar5);
m_progressBars.push_back(ui->progressBar6);
m_progressBars.push_back(ui->progressBar7);
m_audios.push_back(ui->audio0);
m_audios.push_back(ui->audio1);
m_audios.push_back(ui->audio2);
m_audios.push_back(ui->audio3);
m_audios.push_back(ui->audio4);
m_audios.push_back(ui->audio5);
m_audios.push_back(ui->audio6);
m_audios.push_back(ui->audio7);
m_videos.push_back(ui->video0);
m_videos.push_back(ui->video1);
m_videos.push_back(ui->video2);
m_videos.push_back(ui->video3);
m_videos.push_back(ui->video4);
m_videos.push_back(ui->video5);
m_videos.push_back(ui->video6);
m_videos.push_back(ui->video7);
for (int i = 0; i < m_videoViews.count(); i++) {
QWidget *videoView = m_videoViews.at(i);
if (videoView != nullptr) videoView->setAttribute(Qt::WA_PaintOnScreen, true);
}
}
QPaintEngine *VideoListView::paintEngine() const {
return nullptr;
}
void VideoListView::onError(TXLiteAVError errCode, const char *errMsg, void *extraInfo)
{ qDebug() << "errCode: " << errCode << " errMsg: " << errMsg << " extraInfo: " << extraInfo; }
void VideoListView::onWarning(TXLiteAVWarning warningCode, const char *warningMsg, void *extraInfo)
{ qDebug() << "warningCode: " << warningCode << " warningMsg: " << warningMsg << " extraInfo: " << extraInfo; }
| 35.332518
| 144
| 0.680368
|
aliyunvideo
|
a93c987c6be4cff8fb7c28674f13ec742da22f74
| 7,763
|
cc
|
C++
|
spartyjet-4.0.2_mac/External/fastjet-3.0.0/plugins/SISCone/SISConePlugin.cc
|
mickypaganini/SSI2016-jet-clustering
|
a340558957f55159197e845850fc16e622082e7e
|
[
"MIT"
] | 3
|
2018-06-15T09:12:17.000Z
|
2021-06-20T15:58:21.000Z
|
spartyjet-4.0.2_mac/External/fastjet-3.0.0/plugins/SISCone/SISConePlugin.cc
|
mickypaganini/SSI2016-jet-clustering
|
a340558957f55159197e845850fc16e622082e7e
|
[
"MIT"
] | 1
|
2016-08-19T23:48:43.000Z
|
2016-08-20T01:01:34.000Z
|
spartyjet-4.0.2_mac/External/fastjet-3.0.0/plugins/SISCone/SISConePlugin.cc
|
mickypaganini/SSI2016-jet-clustering
|
a340558957f55159197e845850fc16e622082e7e
|
[
"MIT"
] | 6
|
2016-08-18T23:16:00.000Z
|
2020-04-13T01:13:20.000Z
|
// fastjet stuff
#include "fastjet/ClusterSequence.hh"
#include "fastjet/SISConePlugin.hh"
// sisocne stuff
#include "siscone/momentum.h"
#include "siscone/siscone.h"
// other stuff
#include<sstream>
FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh
using namespace std;
using namespace siscone;
/// shortcut for converting siscone Cmomentum into PseudoJet
template<> PseudoJet::PseudoJet(const siscone::Cmomentum & four_vector) {
(*this) = PseudoJet(four_vector.px,four_vector.py,four_vector.pz,
four_vector.E);
}
/////////////////////////////////////////////
// static members declaration //
/////////////////////////////////////////////
std::auto_ptr<SISConePlugin> SISConePlugin::stored_plugin;
std::auto_ptr<std::vector<PseudoJet> > SISConePlugin::stored_particles;
std::auto_ptr<Csiscone> SISConePlugin::stored_siscone;
/////////////////////////////////////////////
// now comes the implementation itself //
/////////////////////////////////////////////
string SISConePlugin::description () const {
ostringstream desc;
const string on = "on";
const string off = "off";
string sm_scale_string = "split-merge uses " +
split_merge_scale_name(Esplit_merge_scale(split_merge_scale()));
desc << "SISCone jet algorithm with " ;
desc << "cone_radius = " << cone_radius () << ", ";
desc << "overlap_threshold = " << overlap_threshold () << ", ";
desc << "n_pass_max = " << n_pass_max () << ", ";
desc << "protojet_ptmin = " << protojet_ptmin() << ", ";
desc << sm_scale_string << ", ";
desc << "caching turned " << (caching() ? on : off);
desc << ", SM stop scale = " << _split_merge_stopping_scale;
// add a note to the description if we use the pt-weighted splitting
if (_use_pt_weighted_splitting){
desc << ", using pt-weighted splitting";
}
if (_use_jet_def_recombiner){
desc << ", using jet-definition's own recombiner";
}
// create a fake siscone object so that we can find out more about it
Csiscone siscone;
if (siscone.merge_identical_protocones) {
desc << ", and (IR unsafe) merge_indentical_protocones=true" ;
}
desc << ", SISCone code v" << siscone_version();
return desc.str();
}
// overloading the base class implementation
void SISConePlugin::run_clustering(ClusterSequence & clust_seq) const {
Csiscone local_siscone;
Csiscone * siscone;
unsigned n = clust_seq.jets().size();
bool new_siscone = true; // by default we'll be running it
if (caching()) {
// Establish if we have a cached run with the same R, npass and
// particles. If not then do any tidying up / reallocation that's
// necessary for the next round of caching, otherwise just set
// relevant pointers so that we can reuse and old run.
if (stored_siscone.get() != 0) {
new_siscone = !(stored_plugin->cone_radius() == cone_radius()
&& stored_plugin->n_pass_max() == n_pass_max()
&& stored_particles->size() == n);
if (!new_siscone) {
for(unsigned i = 0; i < n; i++) {
// only check momentum because indices will be correctly dealt
// with anyway when extracting the clustering order.
new_siscone |= !have_same_momentum(clust_seq.jets()[i],
(*stored_particles)[i]);
}
}
}
// allocate the new siscone, etc., if need be
if (new_siscone) {
stored_siscone .reset( new Csiscone );
stored_particles.reset( new std::vector<PseudoJet>(clust_seq.jets()));
reset_stored_plugin();
}
siscone = stored_siscone.get();
} else {
siscone = &local_siscone;
}
// make sure stopping scale is set in siscone
siscone->SM_var2_hardest_cut_off = _split_merge_stopping_scale*_split_merge_stopping_scale;
// set the specific parameters
// when running with ghosts for passive areas, do not put the
// ghosts into the stable-cone search (not relevant)
siscone->stable_cone_soft_pt2_cutoff = ghost_separation_scale()
* ghost_separation_scale();
// set the type of splitting we want (default=std one, true->pt-weighted split)
siscone->set_pt_weighted_splitting(_use_pt_weighted_splitting);
if (new_siscone) {
// transfer fastjet initial particles into the siscone type
std::vector<Cmomentum> siscone_momenta(n);
for(unsigned i = 0; i < n; i++) {
const PseudoJet & p = clust_seq.jets()[i]; // shorthand
siscone_momenta[i] = Cmomentum(p.px(), p.py(), p.pz(), p.E());
}
// run the jet finding
//cout << "plg sms: " << split_merge_scale() << endl;
siscone->compute_jets(siscone_momenta, cone_radius(), overlap_threshold(),
n_pass_max(), protojet_or_ghost_ptmin(),
Esplit_merge_scale(split_merge_scale()));
} else {
// rerun the jet finding
// just run the overlap part of the jets.
//cout << "plg rcmp sms: " << split_merge_scale() << endl;
siscone->recompute_jets(overlap_threshold(), protojet_or_ghost_ptmin(),
Esplit_merge_scale(split_merge_scale()));
}
// extract the jets [in reverse order -- to get nice ordering in pt at end]
int njet = siscone->jets.size();
// allocate space for the extras object
SISConeExtras * extras = new SISConeExtras(n);
for (int ijet = njet-1; ijet >= 0; ijet--) {
const Cjet & jet = siscone->jets[ijet]; // shorthand
// Successively merge the particles that make up the cone jet
// until we have all particles in it. Start off with the zeroth
// particle.
int jet_k = jet.contents[0];
for (unsigned ipart = 1; ipart < jet.contents.size(); ipart++) {
// take the last result of the merge
int jet_i = jet_k;
// and the next element of the jet
int jet_j = jet.contents[ipart];
// and merge them (with a fake dij)
double dij = 0.0;
if (_use_jet_def_recombiner) {
clust_seq.plugin_record_ij_recombination(jet_i, jet_j, dij, jet_k);
} else {
// create the new jet by hand so that we can adjust its user index
PseudoJet newjet = clust_seq.jets()[jet_i] + clust_seq.jets()[jet_j];
// set the user index to be the pass in which the jet was discovered
newjet.set_user_index(jet.pass);
clust_seq.plugin_record_ij_recombination(jet_i, jet_j, dij, newjet, jet_k);
}
}
// we have merged all the jet's particles into a single object, so now
// "declare" it to be a beam (inclusive) jet.
// [NB: put a sensible looking d_iB just to be nice...]
double d_iB = clust_seq.jets()[jet_k].perp2();
clust_seq.plugin_record_iB_recombination(jet_k, d_iB);
// now record the pass of the jet in the extras object
extras->_pass[clust_seq.jets()[jet_k].cluster_hist_index()] = jet.pass;
}
// now copy the list of protocones into an "extras" objects
for (unsigned ipass = 0; ipass < siscone->protocones_list.size(); ipass++) {
for (unsigned ipc = 0; ipc < siscone->protocones_list[ipass].size(); ipc++) {
PseudoJet protocone(siscone->protocones_list[ipass][ipc]);
protocone.set_user_index(ipass);
extras->_protocones.push_back(protocone);
}
}
extras->_most_ambiguous_split = siscone->most_ambiguous_split;
// tell it what the jet definition was
extras->_jet_def_plugin = this;
// give the extras object to the cluster sequence.
clust_seq.plugin_associate_extras(std::auto_ptr<ClusterSequence::Extras>(extras));
}
void SISConePlugin::reset_stored_plugin() const{
stored_plugin.reset( new SISConePlugin(*this));
}
FASTJET_END_NAMESPACE // defined in fastjet/internal/base.hh
| 36.106977
| 93
| 0.643437
|
mickypaganini
|
a93cab4362153db35a3b95a592b642826bc2aada
| 441
|
cpp
|
C++
|
SysLib/Network/Data/AB_Data.cpp
|
kravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | 2
|
2018-04-27T11:07:02.000Z
|
2020-04-24T06:53:21.000Z
|
SysLib/Network/Data/AB_Data.cpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
SysLib/Network/Data/AB_Data.cpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
//*********************************************************
// AB_Data.cpp - network link A->B access classes
//*********************************************************
#include "AB_Data.hpp"
//---------------------------------------------------------
// AB_Key constructor
//---------------------------------------------------------
AB_Key::AB_Key (int max_records) :
Complex_Array (sizeof (AB_Data), 2, false, max_records, false)
{
}
| 29.4
| 63
| 0.326531
|
kravitz
|
a93d28ecf46e8e53fa636c0b11369a3800a91a1c
| 6,352
|
cpp
|
C++
|
herald/src/datatype/signal_characteristic_data.cpp
|
w-liam-mcnair/herald-for-cpp
|
cc01c9364c69e4015542ea632efe184a4add9e86
|
[
"Apache-2.0"
] | null | null | null |
herald/src/datatype/signal_characteristic_data.cpp
|
w-liam-mcnair/herald-for-cpp
|
cc01c9364c69e4015542ea632efe184a4add9e86
|
[
"Apache-2.0"
] | null | null | null |
herald/src/datatype/signal_characteristic_data.cpp
|
w-liam-mcnair/herald-for-cpp
|
cc01c9364c69e4015542ea632efe184a4add9e86
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
//
#include "herald/datatype/signal_characteristic_data.h"
#include "herald/ble/ble_sensor_configuration.h"
#include <vector>
#include <optional>
namespace herald {
namespace datatype {
namespace SignalCharacteristicData {
using namespace herald::ble;
// PRIVATE METHODS
std::byte
signalDataActionCode(const Data& signalData) {
if (signalData.size() == 0) {
return std::byte(0);
}
return signalData.at(0);
}
int
int16(const Data& data, std::size_t index, bool& success) {
if (index < data.size() - 1) { // TODO TEST size() boundary limits - as it's two bytes, little endian
int v = (((int)data.at(index)) << 8) | (int)data.at(index + 1);
success = true;
return v;
}
success = false;
return 0;
}
// HEADER PUBLIC METHODS
std::optional<Data>
encodeWriteRssi(const BLESensorConfiguration& config,const RSSI& rssi) noexcept {
int r = rssi.intValue();
std::vector<std::byte> vec(3);
vec.push_back(config.signalCharacteristicActionWriteRSSI);
vec.push_back(std::byte(r)); // force least significant bit
vec.push_back(std::byte(r >> 8)); // msb
return std::optional<Data>(Data(std::move(vec))); // constructs the optional with a value
}
std::optional<RSSI>
decodeWriteRSSI(const BLESensorConfiguration& config,const Data& data) noexcept {
if (signalDataActionCode(data) != config.signalCharacteristicActionWriteRSSI) {
return {};
}
if (data.size() != 3) {
return {};
}
bool success = true;
int rssi = int16(data,1, success); // idx 1 & 2 (little endian)
if (!success) {
return {};
}
return std::optional<RSSI>(RSSI{rssi}); // constructs the optional with a value
}
std::optional<Data>
encodeWritePayload(const BLESensorConfiguration& config,const PayloadData& payloadData) noexcept {
int r = (int)payloadData.size();
std::vector<std::byte> vec(3 + r);
vec.push_back(config.signalCharacteristicActionWritePayload);
vec.push_back(std::byte(r)); // force least significant bit
vec.push_back(std::byte(r >> 8)); // msb
Data d(std::move(vec));
d.append(payloadData);
return std::optional<Data>(d); // constructs the optional with a value
}
std::optional<PayloadData>
decodeWritePayload(const BLESensorConfiguration& config,const Data& data) noexcept {
if (signalDataActionCode(data) != config.signalCharacteristicActionWritePayload) {
return {};
}
if (data.size() < 3) {
return {};
}
bool success = true;
int payloadDataCount = int16(data, 1, success); // idx 1 & 2 (little endian)
if (!success) {
return {};
}
if (data.size() != (3 + std::size_t(payloadDataCount))) {
return {};
}
return std::optional<PayloadData>(PayloadData(data.subdata(3))); // constructs the optional with a value
}
std::optional<Data>
encodeWritePayloadSharing(const BLESensorConfiguration& config,const PayloadSharingData& payloadSharingData) noexcept {
int r = payloadSharingData.rssi.intValue();
int r2 = (int)payloadSharingData.data.size();
std::vector<std::byte> vec(5 + r2);
vec.push_back(config.signalCharacteristicActionWritePayloadSharing);
vec.push_back(std::byte(r)); // force least significant bit
vec.push_back(std::byte(r >> 8)); // msb
vec.push_back(std::byte(r2)); // force least significant bit
vec.push_back(std::byte(r2 >> 8)); // msb
Data d(std::move(vec));
d.append(payloadSharingData.data);
return std::optional<Data>(d); // constructs the optional with a value
}
std::optional<PayloadSharingData>
decodeWritePayloadSharing(const BLESensorConfiguration& config,const Data& data) noexcept {
if (signalDataActionCode(data) != config.signalCharacteristicActionWritePayloadSharing) {
return {};
}
if (data.size() < 5) {
return {};
}
bool success = true;
int rssiValue = int16(data, 1, success);
if (!success) {
return {};
}
int payloadDataCount = int16(data, 3, success); // idx 3 & 4 (little endian)
if (!success) {
return {};
}
if (data.size() != (5 + std::size_t(payloadDataCount))) {
return {};
}
Data d = data.subdata(5);
RSSI rssi(rssiValue);
PayloadSharingData pd{std::move(rssi), std::move(data)};
return std::optional<PayloadSharingData>(pd); // constructs the optional with a value
}
std::optional<Data>
encodeImmediateSend(const BLESensorConfiguration& config,const ImmediateSendData& immediateSendData) noexcept {
int r = (int)immediateSendData.size();
std::vector<std::byte> vec(3 + r);
vec.push_back(config.signalCharacteristicActionWriteImmediate);
vec.push_back(static_cast<std::byte>(r)); // force least significant bit
vec.push_back(static_cast<std::byte>(r >> 8)); // msb
Data d(std::move(vec));
d.append(immediateSendData);
return std::optional<Data>(d); // constructs the optional with a value
}
std::optional<ImmediateSendData>
decodeImmediateSend(const BLESensorConfiguration& config,const Data& data) noexcept {
if (signalDataActionCode(data) != config.signalCharacteristicActionWriteImmediate) {
return {};
}
if (data.size() < 3) {
return {};
}
bool success = true;
int payloadDataCount = int16(data, 1, success); // idx 1 & 2 (little endian)
if (!success) {
return {};
}
if (data.size() != (3 + std::size_t(payloadDataCount))) {
return {};
}
return std::optional<ImmediateSendData>(ImmediateSendData(data.subdata(3))); // constructs the optional with a value
}
SignalCharacteristicDataType
detect(const BLESensorConfiguration& config,const Data& data) noexcept {
auto val = signalDataActionCode(data);
if (config.signalCharacteristicActionWriteRSSI == val) {
return SignalCharacteristicDataType::rssi;
} else if (config.signalCharacteristicActionWritePayload == val) {
return SignalCharacteristicDataType::payload;
} else if (config.signalCharacteristicActionWritePayloadSharing == val) {
return SignalCharacteristicDataType::payloadSharing;
} else if (config.signalCharacteristicActionWriteImmediate == val) {
return SignalCharacteristicDataType::immediateSend;
} else {
return SignalCharacteristicDataType::unknown;
}
}
} // end namespace
} // end namespace
} // end namespace
| 33.787234
| 120
| 0.687343
|
w-liam-mcnair
|
a942c691f21448832e5c2ee9c4e411a4aa3607e9
| 3,106
|
cpp
|
C++
|
dev/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/AnimGraphParameterMaskHandler.cpp
|
pawandayma/lumberyard
|
e178f173f9c21369efd8c60adda3914e502f006a
|
[
"AML"
] | 1,738
|
2017-09-21T10:59:12.000Z
|
2022-03-31T21:05:46.000Z
|
dev/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/AnimGraphParameterMaskHandler.cpp
|
olivier-be/lumberyard
|
3d688932f919dbf5821f0cb8a210ce24abe39e9e
|
[
"AML"
] | 427
|
2017-09-29T22:54:36.000Z
|
2022-02-15T19:26:50.000Z
|
dev/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/AnimGraphParameterMaskHandler.cpp
|
olivier-be/lumberyard
|
3d688932f919dbf5821f0cb8a210ce24abe39e9e
|
[
"AML"
] | 671
|
2017-09-21T08:04:01.000Z
|
2022-03-29T14:30:07.000Z
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <EMotionFX/Source/EventHandler.h>
#include <Editor/PropertyWidgets/AnimGraphParameterMaskHandler.h>
#include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.h>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QTimer>
namespace EMotionFX
{
AZ_CLASS_ALLOCATOR_IMPL(AnimGraphParameterMaskHandler, EditorAllocator, 0)
AnimGraphParameterMaskHandler::AnimGraphParameterMaskHandler()
: QObject()
, AzToolsFramework::PropertyHandler<AZStd::vector<AZStd::string>, AnimGraphParameterPicker>()
, m_object(nullptr)
{
}
AZ::u32 AnimGraphParameterMaskHandler::GetHandlerName() const
{
return AZ_CRC("AnimGraphParameterMask", 0x67dd0993);
}
QWidget* AnimGraphParameterMaskHandler::CreateGUI(QWidget* parent)
{
AnimGraphParameterPicker* picker = aznew AnimGraphParameterPicker(parent, false, true);
connect(picker, &AnimGraphParameterPicker::ParametersChanged, this, [picker](const AZStd::vector<AZStd::string>& newParameters)
{
EBUS_EVENT(AzToolsFramework::PropertyEditorGUIMessages::Bus, RequestWrite, picker);
});
return picker;
}
void AnimGraphParameterMaskHandler::ConsumeAttribute(AnimGraphParameterPicker* GUI, AZ::u32 attrib, AzToolsFramework::PropertyAttributeReader* attrValue, const char* debugName)
{
if (attrValue)
{
AnimGraphNode* node = static_cast<AnimGraphNode*>(attrValue->GetInstancePointer());
m_object = azdynamic_cast<ObjectAffectedByParameterChanges*>(node);
GUI->SetObjectAffectedByParameterChanges(m_object);
}
if (attrib == AZ::Edit::Attributes::ReadOnly)
{
bool value;
if (attrValue->Read<bool>(value))
{
GUI->setEnabled(!value);
}
}
}
void AnimGraphParameterMaskHandler::WriteGUIValuesIntoProperty(size_t index, AnimGraphParameterPicker* GUI, property_t& instance, AzToolsFramework::InstanceDataNode* node)
{
// Don't update the parameter names yet, we still need the information for constructing the command group.
instance = m_object->GetParameters();
}
bool AnimGraphParameterMaskHandler::ReadValuesIntoGUI(size_t index, AnimGraphParameterPicker* GUI, const property_t& instance, AzToolsFramework::InstanceDataNode* node)
{
QSignalBlocker signalBlocker(GUI);
GUI->InitializeParameterNames(instance);
return true;
}
} // namespace EMotionFX
| 39.316456
| 180
| 0.714746
|
pawandayma
|
a94400d4b3785e7d46ec696ce34b7bdb27f3316e
| 13,436
|
cpp
|
C++
|
tests/cxx/isce3/cuda/signal/gpuSignal.cpp
|
isce3-testing/isce3-circleci-poc
|
ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3
|
[
"Apache-2.0"
] | 64
|
2019-08-06T19:22:22.000Z
|
2022-03-20T17:11:46.000Z
|
tests/cxx/isce3/cuda/signal/gpuSignal.cpp
|
isce-framework/isce3
|
59cdd2c659a4879367db5537604b0ca93d26b372
|
[
"Apache-2.0"
] | 8
|
2020-09-01T22:46:53.000Z
|
2021-11-04T00:05:28.000Z
|
tests/cxx/isce3/cuda/signal/gpuSignal.cpp
|
isce-framework/isce3
|
59cdd2c659a4879367db5537604b0ca93d26b372
|
[
"Apache-2.0"
] | 29
|
2019-08-05T21:40:55.000Z
|
2022-03-23T00:17:03.000Z
|
#include <iostream>
#include <cstdio>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
#include <valarray>
#include <complex>
#include <cufft.h>
#include <cufftXt.h>
#include <thrust/complex.h>
#include <gtest/gtest.h>
#include "isce3/signal/Signal.h"
#include "isce3/io/Raster.h"
#include "isce3/cuda/except/Error.h"
#include "isce3/cuda/signal/gpuSignal.h"
using isce3::cuda::signal::gpuSignal;
TEST(gpuSignal, ForwardBackwardRangeFloat)
{
// take a block of data, perform range FFT and then iverse FFT and compare with original data
isce3::io::Raster inputSlc(TESTDATA_DIR "warped_envisat.slc.vrt");
int width = inputSlc.width();
int blockLength = inputSlc.length();
thrust::complex<float> *d_data;
// reserve memory for a block of data
std::valarray<std::complex<float>> data(width*blockLength);
// reserve memory for a block of data computed from inverse FFT
std::valarray<std::complex<float>> inverted_data(width*blockLength);
// read a block of data
inputSlc.getBlock(data, 0, 0, width, blockLength);
// copy data to device
size_t data_sz = width * blockLength * sizeof(thrust::complex<float>);
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz));
checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice));
// a signal object
gpuSignal<float> sig(CUFFT_C2C);
// create the plan
sig.rangeFFT(width, blockLength);
sig.forwardDevMem(d_data);
sig.inverseDevMem(d_data);
cudaMemcpy(&inverted_data[0], d_data, data_sz, cudaMemcpyDeviceToHost);
//normalize the result of inverse fft
inverted_data /=width;
int blockSize = width*blockLength;
std::complex<float> err(0.0, 0.0);
double max_err = 0.0;
for ( size_t i = 0; i < blockSize; ++i ) {
err = inverted_data[i] - data[i];
if (std::abs(err) > max_err){
max_err = std::abs(err);
}
}
ASSERT_LT(max_err, 1.0e-4);
}
TEST(gpuSignal, ForwardBackwardRangeDouble)
{
// take a block of data, perform range FFT and then iverse FFT and compare with original data
isce3::io::Raster inputSlc(TESTDATA_DIR "warped_envisat.slc.vrt");
int width = inputSlc.width();
int blockLength = inputSlc.length();
thrust::complex<double> *d_data;
// reserve memory for a block of data
std::valarray<std::complex<double>> data(width*blockLength);
// reserve memory for a block of data computed from inverse FFT
std::valarray<std::complex<double>> inverted_data(width*blockLength);
// read a block of data
inputSlc.getBlock(data, 0, 0, width, blockLength);
// copy data to device
size_t data_sz = width * blockLength * sizeof(thrust::complex<double>);
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz));
checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice));
// a signal object
gpuSignal<double> sig(CUFFT_Z2Z);
// create the plan
sig.rangeFFT(width, blockLength);
sig.forwardDevMem(d_data);
sig.inverseDevMem(d_data);
cudaMemcpy(&inverted_data[0], d_data, data_sz, cudaMemcpyDeviceToHost);
//normalize the result of inverse fft
inverted_data /=width;
int blockSize = width*blockLength;
std::complex<double> err(0.0, 0.0);
double max_err = 0.0;
for ( size_t i = 0; i < blockSize; ++i ) {
err = inverted_data[i] - data[i];
if (std::abs(err) > max_err){
max_err = std::abs(err);
}
}
ASSERT_LT(max_err, 1.0e-4);
}
TEST(gpuSignal, ForwardBackwardAzimuthFloat)
{
// take a block of data, perform range FFT and then iverse FFT and compare with original data
isce3::io::Raster inputSlc(TESTDATA_DIR "warped_envisat.slc.vrt");
int width = inputSlc.width();
int blockLength = inputSlc.length();
thrust::complex<float> *d_data;
// reserve memory for a block of data
std::valarray<std::complex<float>> data(width*blockLength);
// reserve memory for a block of data computed from inverse FFT
std::valarray<std::complex<float>> inverted_data(width*blockLength);
// read a block of data
inputSlc.getBlock(data, 0, 0, width, blockLength);
// copy data to device
size_t data_sz = width * blockLength * sizeof(thrust::complex<float>);
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz));
checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice));
// a signal object
gpuSignal<float> sig(CUFFT_C2C);
// create the plan
sig.azimuthFFT(width, blockLength);
sig.forwardDevMem(d_data);
sig.inverseDevMem(d_data);
cudaMemcpy(&inverted_data[0], d_data, data_sz, cudaMemcpyDeviceToHost);
//normalize the result of inverse fft
inverted_data /=width;
int blockSize = width*blockLength;
std::complex<float> err(0.0, 0.0);
double max_err = 0.0;
for ( size_t i = 0; i < blockSize; ++i ) {
err = inverted_data[i] - data[i];
if (std::abs(err) > max_err){
max_err = std::abs(err);
}
}
ASSERT_LT(max_err, 1.0e-4);
}
TEST(gpuSignal, ForwardBackwardAzimuthDouble)
{
// take a block of data, perform range FFT and then iverse FFT and compare with original data
isce3::io::Raster inputSlc(TESTDATA_DIR "warped_envisat.slc.vrt");
int width = inputSlc.width();
int blockLength = inputSlc.length();
thrust::complex<double> *d_data;
// reserve memory for a block of data
std::valarray<std::complex<double>> data(width*blockLength);
// reserve memory for a block of data computed from inverse FFT
std::valarray<std::complex<double>> inverted_data(width*blockLength);
// read a block of data
inputSlc.getBlock(data, 0, 0, width, blockLength);
// copy data to device
size_t data_sz = width * blockLength * sizeof(thrust::complex<double>);
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz));
checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice));
// a signal object
gpuSignal<double> sig(CUFFT_Z2Z);
// create the plan
sig.azimuthFFT(width, blockLength);
sig.forwardDevMem(d_data);
sig.inverseDevMem(d_data);
cudaMemcpy(&inverted_data[0], d_data, data_sz, cudaMemcpyDeviceToHost);
//normalize the result of inverse fft
inverted_data /=width;
int blockSize = width*blockLength;
std::complex<double> err(0.0, 0.0);
double max_err = 0.0;
for ( size_t i = 0; i < blockSize; ++i ) {
err = inverted_data[i] - data[i];
if (std::abs(err) > max_err){
max_err = std::abs(err);
}
}
ASSERT_LT(max_err, 1.0e-9);
}
TEST(gpuSignal, upsampleFloat)
{
int width = 100;
// fft length for FFT computations
size_t nfft;
//sig.nextPowerOfTwo(width, nfft);
nfft = width;
// upsampling factor
int oversample = 2;
// reserve memory for a block of data with the size of nfft
std::valarray<std::complex<float>> slc(nfft);
std::valarray<std::complex<float>> slcU(nfft*oversample);
for (size_t i=0; i<width; ++i){
float phase = std::sin(10*M_PI*i/width);
slc[i] = std::complex<float> (std::cos(phase), std::sin(phase));
}
// instantiate a signal object
gpuSignal<float> sig_lo_res(CUFFT_C2C);
gpuSignal<float> sig_hi_res(CUFFT_C2C);
// create plans
sig_lo_res.rangeFFT(nfft, 1);
sig_hi_res.rangeFFT(oversample*nfft, 1);
upsample(sig_lo_res,
sig_hi_res,
slc,
slcU);
// Check if the original smaples have the same phase in the signal before and after upsampling
float max_err = 0.0;
float err = 0.0;
for (size_t col = 0; col<width; col++){
err = std::arg(slc[col] * std::conj(slcU[oversample*col]));
if (std::abs(err) > max_err){
max_err = std::abs(err);
}
}
float max_err_u = 0.0;
float err_u;
float step = 1.0/oversample;
std::complex<float> cpxData;
for (size_t col = 0; col<width*oversample; col++){
float i = col*step;
float phase = std::sin(10*M_PI*i/(width));
cpxData = std::complex<float> (std::cos(phase), std::sin(phase));
err_u = std::arg(cpxData * std::conj(slcU[col]));
if (std::abs(err_u) > max_err_u){
max_err_u = std::abs(err_u);
}
}
ASSERT_LT(max_err, 1.0e-6);
ASSERT_LT(max_err_u, 1.0e-6);
}
TEST(gpuSignal, upsampleDouble)
{
int width = 100;
// fft length for FFT computations
size_t nfft;
//sig.nextPowerOfTwo(width, nfft);
nfft = width;
// upsampling factor
int oversample = 2;
// reserve memory for a block of data with the size of nfft
std::valarray<std::complex<double>> slc(nfft);
std::valarray<std::complex<double>> slcU(nfft*oversample);
for (size_t i=0; i<width; ++i){
double phase = std::sin(10*M_PI*i/width);
slc[i] = std::complex<double> (std::cos(phase), std::sin(phase));
}
// instantiate a signal object
gpuSignal<double> sig_lo_res(CUFFT_Z2Z);
gpuSignal<double> sig_hi_res(CUFFT_Z2Z);
// create plans
sig_lo_res.rangeFFT(nfft, 1);
sig_hi_res.rangeFFT(oversample*nfft, 1);
upsample(sig_lo_res,
sig_hi_res,
slc,
slcU);
// Check if the original smaples have the same phase in the signal before and after upsampling
double max_err = 0.0;
double err = 0.0;
for (size_t col = 0; col<width; col++){
err = std::arg(slc[col] * std::conj(slcU[oversample*col]));
if (std::abs(err) > max_err){
max_err = std::abs(err);
}
}
double max_err_u = 0.0;
double err_u;
double step = 1.0/oversample;
std::complex<double> cpxData;
for (size_t col = 0; col<width*oversample; col++){
double i = col*step;
double phase = std::sin(10*M_PI*i/(width));
cpxData = std::complex<double> (std::cos(phase), std::sin(phase));
err_u = std::arg(cpxData * std::conj(slcU[col]));
if (std::abs(err_u) > max_err_u){
max_err_u = std::abs(err_u);
}
}
ASSERT_LT(max_err, 1.0e-9);
ASSERT_LT(max_err_u, 1.0e-9);
}
TEST(gpuSignal, FFT2D)
{
int width = 12;
int length = 10;
thrust::complex<double> *d_data;
//
int blockLength = length;
// reserve memory for a block of data
std::valarray<std::complex<double>> data(width*blockLength);
// reserve memory for the spectrum of the block of data
std::valarray<std::complex<double>> spectrum(width*blockLength);
// reserve memory for a block of data computed from inverse FFT
std::valarray<std::complex<double>> invertData(width*blockLength);
for (size_t i = 0; i< length; ++i){
for (size_t j = 0; j< width; ++j){
data[i*width + j] = std::complex<double> (std::cos(i*j), std::sin(i*j));
}
}
// copy data to device
size_t data_sz = width * blockLength * sizeof(thrust::complex<double>);
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&d_data), data_sz));
checkCudaErrors(cudaMemcpy(d_data, &data[0], data_sz, cudaMemcpyHostToDevice));
// a signal object
gpuSignal<double> sig(CUFFT_Z2Z);
// create plan
sig.FFT2D(width, blockLength);
sig.forwardDevMem(d_data);
sig.inverseDevMem(d_data);
cudaMemcpy(&invertData[0], d_data, data_sz, cudaMemcpyDeviceToHost);
invertData /= width*length;
double max_err = 0.0;
double err = 0.0;
for (size_t i = 0; i< length; ++i){
for (size_t j = 0; j< width; ++j){
err = std::abs(data[i*width + j] - invertData[i*width + j]);
if (err > max_err)
max_err = err;
}
}
ASSERT_LT(max_err, 1.0e-12);
}
TEST(gpuSignal, realDoubleDataFFT)
{
int width = 120;
int length = 100;
int blockLength = length;
// reserve memory for a block of data
double *data = new double[width*blockLength];
// reserve memory for the spectrum of the block of data
std::complex<double> *spectrum = new std::complex<double>[width*blockLength];
// reserve memory for a block of data computed from inverse FFT
double *invertData = new double[width*blockLength];
for (size_t i = 0; i< length; ++i){
for (size_t j = 0; j< width; ++j){
data[i*width + j] = i+j;
}
}
// a signal objects
gpuSignal<double> sig_D2Z(CUFFT_D2Z);
gpuSignal<double> sig_Z2D(CUFFT_Z2D);
// make plans
sig_D2Z.FFT2D(width, blockLength);
sig_Z2D.FFT2D(width, blockLength);
// forward and inverse transform
sig_D2Z.forwardD2Z(data, spectrum);
sig_Z2D.inverseZ2D(spectrum, invertData);
for (size_t i = 0; i< length; ++i){
for (size_t j = 0; j< width; ++j){
invertData[i*width + j] = i+j;
}
}
double max_err_2DFFT = 0.0;
double err = 0.0;
for (size_t i = 0; i< length; ++i){
for (size_t j = 0; j< width; ++j){
err = std::abs(data[i*width + j] - invertData[i*width + j]);
if (err > max_err_2DFFT)
max_err_2DFFT = err;
}
}
ASSERT_LT(max_err_2DFFT, 1.0e-12);
}
int main(int argc, char * argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
// end of file
| 29.145336
| 98
| 0.634936
|
isce3-testing
|
a945a003ec55f4004106b6fc04fc72bfe49080aa
| 2,463
|
cpp
|
C++
|
src/frontends/tensorflow/src/op/max_pool.cpp
|
pazamelin/openvino
|
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
|
[
"Apache-2.0"
] | 1
|
2021-10-21T03:04:16.000Z
|
2021-10-21T03:04:16.000Z
|
src/frontends/tensorflow/src/op/max_pool.cpp
|
pazamelin/openvino
|
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
|
[
"Apache-2.0"
] | 58
|
2020-11-06T12:13:45.000Z
|
2022-03-28T13:20:11.000Z
|
src/frontends/tensorflow/src/op/max_pool.cpp
|
pazamelin/openvino
|
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
|
[
"Apache-2.0"
] | 2
|
2019-09-20T01:33:37.000Z
|
2019-09-20T08:42:11.000Z
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <openvino/opsets/opset7.hpp>
#include "op_table.hpp"
using namespace std;
using namespace ov;
using namespace ov::frontend::tensorflow::detail;
namespace ov {
namespace frontend {
namespace tensorflow {
namespace op {
OutputVector translate_max_pool_op(const NodeContext& node) {
auto ng_input = node.get_input(0);
auto tf_strides = node.get_attribute<std::vector<int32_t>>("strides");
auto tf_ksize = node.get_attribute<std::vector<int32_t>>("ksize");
auto tf_padding_type = node.get_attribute<std::string>("padding");
auto tf_data_format = node.get_attribute<std::string>("data_format");
bool is_nhwc = (tf_data_format == "NHWC") || (tf_data_format == "NDHWC");
int N = 2;
if (node.get_name() == "MaxPool3D") {
N = 3;
}
Strides ng_strides(N);
Shape ng_image_shape(N);
Shape ng_kernel_shape(N);
Shape ng_dilations(N, 1);
convert_nhwc_to_hw(is_nhwc, tf_strides, ng_strides);
convert_nhwc_to_hw(is_nhwc, ng_input.get_shape(), ng_image_shape);
convert_nhwc_to_hw(is_nhwc, tf_ksize, ng_kernel_shape);
convert_nhwc_to_nchw(node.get_name(), is_nhwc, ng_input);
CoordinateDiff padding_below;
CoordinateDiff padding_above;
make_padding(tf_padding_type,
ng_image_shape,
ng_kernel_shape,
ng_strides,
ng_dilations,
padding_below,
padding_above);
// TODO: remove this once OV supports negative padding
// (CoordinateDiff) for MaxPool
Shape ng_padding_below(padding_below.begin(), padding_below.end());
Shape ng_padding_above(padding_above.begin(), padding_above.end());
auto res_node = make_shared<ov::opset7::MaxPool>(ng_input,
ng_strides,
ng_padding_below,
ng_padding_above,
ng_kernel_shape,
ov::op::RoundingType::FLOOR);
auto res = res_node->output(0);
convert_nchw_to_nhwc(node.get_name(), is_nhwc, res);
set_node_name(node.get_name(), res.get_node_shared_ptr());
return {res};
}
} // namespace op
} // namespace tensorflow
} // namespace frontend
} // namespace ov
| 33.739726
| 82
| 0.61754
|
pazamelin
|
a9472f006b5fc141cda6f12971f74d8bf697173b
| 6,993
|
cpp
|
C++
|
external/SFML-2.5.1/src/SFML/Audio/AudioDevice.cpp
|
Manolomon/blind-jump-portable
|
6149d8b639bc9c50533b7eb5fc26884addf563fd
|
[
"MIT"
] | 140
|
2019-08-31T02:52:17.000Z
|
2022-03-25T12:38:23.000Z
|
external/SFML-2.5.1/src/SFML/Audio/AudioDevice.cpp
|
Manolomon/blind-jump-portable
|
6149d8b639bc9c50533b7eb5fc26884addf563fd
|
[
"MIT"
] | 24
|
2019-10-17T23:26:47.000Z
|
2020-02-08T21:49:52.000Z
|
external/SFML-2.5.1/src/SFML/Audio/AudioDevice.cpp
|
Manolomon/blind-jump-portable
|
6149d8b639bc9c50533b7eb5fc26884addf563fd
|
[
"MIT"
] | 5
|
2020-07-08T23:44:32.000Z
|
2021-11-04T21:17:52.000Z
|
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/AudioDevice.hpp>
#include <SFML/Audio/ALCheck.hpp>
#include <SFML/Audio/Listener.hpp>
#include <SFML/System/Err.hpp>
#include <memory>
namespace
{
ALCdevice* audioDevice = NULL;
ALCcontext* audioContext = NULL;
float listenerVolume = 100.f;
sf::Vector3f listenerPosition (0.f, 0.f, 0.f);
sf::Vector3f listenerDirection(0.f, 0.f, -1.f);
sf::Vector3f listenerUpVector (0.f, 1.f, 0.f);
}
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
AudioDevice::AudioDevice()
{
// Create the device
audioDevice = alcOpenDevice(NULL);
if (audioDevice)
{
// Create the context
audioContext = alcCreateContext(audioDevice, NULL);
if (audioContext)
{
// Set the context as the current one (we'll only need one)
alcMakeContextCurrent(audioContext);
// Apply the listener properties the user might have set
float orientation[] = {listenerDirection.x,
listenerDirection.y,
listenerDirection.z,
listenerUpVector.x,
listenerUpVector.y,
listenerUpVector.z};
alCheck(alListenerf(AL_GAIN, listenerVolume * 0.01f));
alCheck(alListener3f(AL_POSITION, listenerPosition.x, listenerPosition.y, listenerPosition.z));
alCheck(alListenerfv(AL_ORIENTATION, orientation));
}
else
{
err() << "Failed to create the audio context" << std::endl;
}
}
else
{
err() << "Failed to open the audio device" << std::endl;
}
}
////////////////////////////////////////////////////////////
AudioDevice::~AudioDevice()
{
// Destroy the context
alcMakeContextCurrent(NULL);
if (audioContext)
alcDestroyContext(audioContext);
// Destroy the device
if (audioDevice)
alcCloseDevice(audioDevice);
}
////////////////////////////////////////////////////////////
bool AudioDevice::isExtensionSupported(const std::string& extension)
{
// Create a temporary audio device in case none exists yet.
// This device will not be used in this function and merely
// makes sure there is a valid OpenAL device for extension
// queries if none has been created yet.
std::auto_ptr<AudioDevice> device;
if (!audioDevice)
device.reset(new AudioDevice);
if ((extension.length() > 2) && (extension.substr(0, 3) == "ALC"))
return alcIsExtensionPresent(audioDevice, extension.c_str()) != AL_FALSE;
else
return alIsExtensionPresent(extension.c_str()) != AL_FALSE;
}
////////////////////////////////////////////////////////////
int AudioDevice::getFormatFromChannelCount(unsigned int channelCount)
{
// Create a temporary audio device in case none exists yet.
// This device will not be used in this function and merely
// makes sure there is a valid OpenAL device for format
// queries if none has been created yet.
std::auto_ptr<AudioDevice> device;
if (!audioDevice)
device.reset(new AudioDevice);
// Find the good format according to the number of channels
int format = 0;
switch (channelCount)
{
case 1: format = AL_FORMAT_MONO16; break;
case 2: format = AL_FORMAT_STEREO16; break;
case 4: format = alGetEnumValue("AL_FORMAT_QUAD16"); break;
case 6: format = alGetEnumValue("AL_FORMAT_51CHN16"); break;
case 7: format = alGetEnumValue("AL_FORMAT_61CHN16"); break;
case 8: format = alGetEnumValue("AL_FORMAT_71CHN16"); break;
default: format = 0; break;
}
// Fixes a bug on OS X
if (format == -1)
format = 0;
return format;
}
////////////////////////////////////////////////////////////
void AudioDevice::setGlobalVolume(float volume)
{
if (audioContext)
alCheck(alListenerf(AL_GAIN, volume * 0.01f));
listenerVolume = volume;
}
////////////////////////////////////////////////////////////
float AudioDevice::getGlobalVolume()
{
return listenerVolume;
}
////////////////////////////////////////////////////////////
void AudioDevice::setPosition(const Vector3f& position)
{
if (audioContext)
alCheck(alListener3f(AL_POSITION, position.x, position.y, position.z));
listenerPosition = position;
}
////////////////////////////////////////////////////////////
Vector3f AudioDevice::getPosition()
{
return listenerPosition;
}
////////////////////////////////////////////////////////////
void AudioDevice::setDirection(const Vector3f& direction)
{
if (audioContext)
{
float orientation[] = {direction.x, direction.y, direction.z, listenerUpVector.x, listenerUpVector.y, listenerUpVector.z};
alCheck(alListenerfv(AL_ORIENTATION, orientation));
}
listenerDirection = direction;
}
////////////////////////////////////////////////////////////
Vector3f AudioDevice::getDirection()
{
return listenerDirection;
}
////////////////////////////////////////////////////////////
void AudioDevice::setUpVector(const Vector3f& upVector)
{
if (audioContext)
{
float orientation[] = {listenerDirection.x, listenerDirection.y, listenerDirection.z, upVector.x, upVector.y, upVector.z};
alCheck(alListenerfv(AL_ORIENTATION, orientation));
}
listenerUpVector = upVector;
}
////////////////////////////////////////////////////////////
Vector3f AudioDevice::getUpVector()
{
return listenerUpVector;
}
} // namespace priv
} // namespace sf
| 30.537118
| 130
| 0.56242
|
Manolomon
|
a948b3aa649aeb4b088d5543b10eb45a5299b289
| 1,574
|
cpp
|
C++
|
Patterns/Misc/customization_points_adl_sfinae.cpp
|
kant/Always-be-learning
|
7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5
|
[
"Unlicense"
] | null | null | null |
Patterns/Misc/customization_points_adl_sfinae.cpp
|
kant/Always-be-learning
|
7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5
|
[
"Unlicense"
] | null | null | null |
Patterns/Misc/customization_points_adl_sfinae.cpp
|
kant/Always-be-learning
|
7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
#include <type_traits>
// When applying the detection-idiom it may be necessary to rely on ADL - we may want to check
// if some expression can be called on a given type, taking into account free functions provided
// in some namespace and also taking ADL into consideration.
// We can do so, without polluting the given namespace with using declarations.
// Given a `is_detected` idiom template:
template<typename...> using void_t = void;
template<template<typename...> class Expression, typename Void, typename... Ts>
struct is_detected_impl : std::false_type { };
template<template<typename...> class Expression, typename... Ts>
struct is_detected_impl<Expression, void_t<Expression<Ts...>>, Ts...> : std::true_type { };
template<template<typename...> class Expression, typename... Ts>
using is_detected_t = is_detected_impl<Expression, void, Ts...>;
template<template<typename...> class Expression, typename... Ts>
inline constexpr bool is_detected{is_detected_t<Expression, Ts...>::value};
// If and we want to check if calling `begin` and `end` on a given type are valid operations
// we can take ADL into consideration by doing the following:
namespace detail
{
using std::begin;
using std::end;
template<typename T>
using begin_expression = decltype(begin(std::declval<T>()));
template<typename T>
using end_expression = decltype(end(std::declval<T>()));
} // namespace detail
template<typename T>
inline constexpr bool IsRange{is_detected<begin_expression, T> && is_detected<end_expression, T>};
int main()
{
}
| 36.604651
| 98
| 0.740152
|
kant
|
a948bac6b4ba1f9bad1e35ea9a778fbdf40a6b2e
| 718
|
hpp
|
C++
|
libs/core/program_options/include/hpx/program_options/version.hpp
|
Andrea-MariaDB-2/hpx
|
e230dddce4a8783817f38e07f5a77e624f64f826
|
[
"BSL-1.0"
] | 1,822
|
2015-01-03T11:22:37.000Z
|
2022-03-31T14:49:59.000Z
|
libs/core/program_options/include/hpx/program_options/version.hpp
|
Andrea-MariaDB-2/hpx
|
e230dddce4a8783817f38e07f5a77e624f64f826
|
[
"BSL-1.0"
] | 3,288
|
2015-01-05T17:00:23.000Z
|
2022-03-31T18:49:41.000Z
|
libs/core/program_options/include/hpx/program_options/version.hpp
|
Andrea-MariaDB-2/hpx
|
e230dddce4a8783817f38e07f5a77e624f64f826
|
[
"BSL-1.0"
] | 431
|
2015-01-07T06:22:14.000Z
|
2022-03-31T14:50:04.000Z
|
// Copyright Vladimir Prus 2004.
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <hpx/program_options/config.hpp>
/** The version of the source interface.
The value will be incremented whenever a change is made which might
cause compilation errors for existing code.
*/
#ifdef HPX_PROGRAM_OPTIONS_VERSION
#error HPX_PROGRAM_OPTIONS_VERSION already defined
#endif
#define HPX_PROGRAM_OPTIONS_VERSION 2
// Signal that implicit options will use values from next
// token, if available.
#define HPX_PROGRAM_OPTIONS_IMPLICIT_VALUE_NEXT_TOKEN 1
| 31.217391
| 71
| 0.789694
|
Andrea-MariaDB-2
|
a948bd94ab06a58af8897df7319c40a0a7d97467
| 4,230
|
hpp
|
C++
|
mapproxy/src/mapproxy/support/metatile.hpp
|
maka-io/vts-mapproxy
|
13c70b1bd2013d76b387900fae839e3948e741c3
|
[
"BSD-2-Clause"
] | null | null | null |
mapproxy/src/mapproxy/support/metatile.hpp
|
maka-io/vts-mapproxy
|
13c70b1bd2013d76b387900fae839e3948e741c3
|
[
"BSD-2-Clause"
] | null | null | null |
mapproxy/src/mapproxy/support/metatile.hpp
|
maka-io/vts-mapproxy
|
13c70b1bd2013d76b387900fae839e3948e741c3
|
[
"BSD-2-Clause"
] | null | null | null |
/**
* Copyright (c) 2017 Melown Technologies SE
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef mapproxy_support_metatile_hpp_included_
#define mapproxy_support_metatile_hpp_included_
#include "vts-libs/registry.hpp"
#include "vts-libs/vts/basetypes.hpp"
#include "vts-libs/vts/tileop.hpp"
#include "../resource.hpp"
#include "./coverage.hpp"
namespace vts = vtslibs::vts;
namespace vr = vtslibs::registry;
/** Metatile block (part of metatile sharing same spatial division)
*/
struct MetatileBlock {
std::string srs;
vts::TileRange view;
math::Extents2 extents;
/** Common ancestor of nodes in this block
*/
vts::NodeInfo commonAncestor;
vts::TileId offset;
typedef std::vector<MetatileBlock> list;
MetatileBlock(vts::Lod lod, const vr::ReferenceFrame &referenceFrame
, const std::string &srs, const vts::TileRange &view
, const math::Extents2 &extents);
bool valid() const { return commonAncestor.valid(); }
bool partial() const { return commonAncestor.partial(); }
};
/** Generate metatile blocks for given metatile id in given reference frame
*
* \param referenceFrame reference frame
* \param tileId metatile id
* \param metaBinaryOrder metatile binary order override if nonzero
*/
MetatileBlock::list metatileBlocks(const Resource &resource
, const vts::TileId &tileId
, unsigned int metaBinaryOrder = 0
, bool includeInvalid = false);
inline bool special(const vr::ReferenceFrame &referenceFrame
, const vts::TileId &tileId)
{
if (const auto *node
= referenceFrame.find(vts::rfNodeId(tileId), std::nothrow))
{
switch (node->partitioning.mode) {
case vr::PartitioningMode::manual:
case vr::PartitioningMode::barren:
return true;
default:
return false;
}
}
return false;
}
class ShiftMask {
public:
ShiftMask(const MetatileBlock &block, int samplesPerTile
, const MaskTree &maskTree_ = MaskTree())
: offset_(block.offset.x * samplesPerTile
, block.offset.y * samplesPerTile)
, mask_(generateCoverage((1 << block.offset.lod) * samplesPerTile
, block.commonAncestor, maskTree_
, vts::NodeInfo::CoverageType::grid))
{}
bool operator()(int x, int y) const {
return mask_.get(x + offset_(0), y + offset_(1));
}
private:
const math::Point2i offset_;
const vts::NodeInfo::CoverageMask mask_;
};
/** Boundlayer metatile from mask
*/
cv::Mat boundlayerMetatileFromMaskTree(const vts::TileId &tileId
, const MaskTree &maskTree
, const MetatileBlock::list &blocks);
#endif // mapproxy_support_metatile_hpp_included_
| 35.546218
| 78
| 0.668085
|
maka-io
|
a948d603785383548446aeab8d7e5627adf5bb65
| 2,806
|
cpp
|
C++
|
ThirdParty/poco/Foundation/src/HashStatistic.cpp
|
gregmedlock/roadrunnerwork
|
11f18f78ef3e381bc59c546a8d5e3ed46d8ab596
|
[
"Apache-2.0"
] | 39
|
2015-01-23T10:01:31.000Z
|
2021-06-10T03:01:18.000Z
|
Windows/PocoFoundation/src/HashStatistic.cpp
|
luckypen/WiEngine
|
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
|
[
"MIT"
] | 1
|
2015-04-15T08:07:47.000Z
|
2015-04-15T08:07:47.000Z
|
Windows/PocoFoundation/src/HashStatistic.cpp
|
luckypen/WiEngine
|
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
|
[
"MIT"
] | 20
|
2015-01-20T07:36:10.000Z
|
2019-09-15T01:02:19.000Z
|
//
// HashStatistic.cpp
//
// $Id: //poco/1.4/Foundation/src/HashStatistic.cpp#1 $
//
// Library: Foundation
// Package: Hashing
// Module: HashStatistic
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/HashStatistic.h"
#include <sstream>
namespace Poco {
HashStatistic::HashStatistic(
UInt32 tableSize,
UInt32 numEntries,
UInt32 numZeroEntries,
UInt32 maxEntry,
std::vector<UInt32> details):
_sizeOfTable(tableSize),
_numberOfEntries(numEntries),
_numZeroEntries(numZeroEntries),
_maxEntriesPerHash(maxEntry),
_detailedEntriesPerHash(details)
{
}
HashStatistic::~HashStatistic()
{
}
std::string HashStatistic::toString() const
{
std::ostringstream str;
str << "HashTable of size " << _sizeOfTable << " containing " << _numberOfEntries << " entries:\n";
str << " NumberOfZeroEntries: " << _numZeroEntries << "\n";
str << " MaxEntry: " << _maxEntriesPerHash << "\n";
str << " AvgEntry: " << avgEntriesPerHash() << ", excl Zero slots: " << avgEntriesPerHashExclZeroEntries() << "\n";
str << " DetailedStatistics: \n";
for (int i = 0; i < _detailedEntriesPerHash.size(); ++i)
{
// 10 entries per line
if (i % 10 == 0)
{
str << "\n " << i << ":";
}
str << " " << _detailedEntriesPerHash[i];
}
str << "\n";
str.flush();
return str.str();
}
} // namespace Poco
| 32.252874
| 118
| 0.693158
|
gregmedlock
|
a949773d62d7d181fa04ca436f5745676ac631ba
| 8,673
|
cpp
|
C++
|
src/chrono/solver/ChSolverSOR.cpp
|
andrewseidl/chrono
|
ec3d1689fa4d1ca40ef6d9ffdd2f509c0dc2cecd
|
[
"BSD-3-Clause"
] | null | null | null |
src/chrono/solver/ChSolverSOR.cpp
|
andrewseidl/chrono
|
ec3d1689fa4d1ca40ef6d9ffdd2f509c0dc2cecd
|
[
"BSD-3-Clause"
] | null | null | null |
src/chrono/solver/ChSolverSOR.cpp
|
andrewseidl/chrono
|
ec3d1689fa4d1ca40ef6d9ffdd2f509c0dc2cecd
|
[
"BSD-3-Clause"
] | null | null | null |
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora, Radu Serban
// =============================================================================
#include "chrono/solver/ChSolverSOR.h"
namespace chrono {
// Register into the object factory, to enable run-time dynamic creation and persistence
CH_FACTORY_REGISTER(ChSolverSOR)
double ChSolverSOR::Solve(ChSystemDescriptor& sysd ///< system description with constraints and variables
) {
std::vector<ChConstraint*>& mconstraints = sysd.GetConstraintsList();
std::vector<ChVariables*>& mvariables = sysd.GetVariablesList();
tot_iterations = 0;
double maxviolation = 0.;
double maxdeltalambda = 0.;
int i_friction_comp = 0;
double old_lambda_friction[3];
// 1) Update auxiliary data in all constraints before starting,
// that is: g_i=[Cq_i]*[invM_i]*[Cq_i]' and [Eq_i]=[invM_i]*[Cq_i]'
for (unsigned int ic = 0; ic < mconstraints.size(); ic++)
mconstraints[ic]->Update_auxiliary();
// Average all g_i for the triplet of contact constraints n,u,v.
//
int j_friction_comp = 0;
double gi_values[3];
for (unsigned int ic = 0; ic < mconstraints.size(); ic++) {
if (mconstraints[ic]->GetMode() == CONSTRAINT_FRIC) {
gi_values[j_friction_comp] = mconstraints[ic]->Get_g_i();
j_friction_comp++;
if (j_friction_comp == 3) {
double average_g_i = (gi_values[0] + gi_values[1] + gi_values[2]) / 3.0;
mconstraints[ic - 2]->Set_g_i(average_g_i);
mconstraints[ic - 1]->Set_g_i(average_g_i);
mconstraints[ic - 0]->Set_g_i(average_g_i);
j_friction_comp = 0;
}
}
}
// 2) Compute, for all items with variables, the initial guess for
// still unconstrained system:
for (unsigned int iv = 0; iv < mvariables.size(); iv++) {
if (mvariables[iv]->IsActive())
mvariables[iv]->Compute_invMb_v(mvariables[iv]->Get_qb(), mvariables[iv]->Get_fb()); // q = [M]'*fb
}
// 3) For all items with variables, add the effect of initial (guessed)
// lagrangian reactions of contraints, if a warm start is desired.
// Otherwise, if no warm start, simply resets initial lagrangians to zero.
if (warm_start) {
for (unsigned int ic = 0; ic < mconstraints.size(); ic++)
if (mconstraints[ic]->IsActive())
mconstraints[ic]->Increment_q(mconstraints[ic]->Get_l_i());
} else {
for (unsigned int ic = 0; ic < mconstraints.size(); ic++)
mconstraints[ic]->Set_l_i(0.);
}
// 4) Perform the iteration loops
//
for (int iter = 0; iter < max_iterations; iter++) {
// The iteration on all constraints
//
maxviolation = 0;
maxdeltalambda = 0;
i_friction_comp = 0;
for (unsigned int ic = 0; ic < mconstraints.size(); ic++) {
// skip computations if constraint not active.
if (mconstraints[ic]->IsActive()) {
// compute residual c_i = [Cq_i]*q + b_i + cfm_i*l_i
double mresidual = mconstraints[ic]->Compute_Cq_q() + mconstraints[ic]->Get_b_i() +
mconstraints[ic]->Get_cfm_i() * mconstraints[ic]->Get_l_i();
// true constraint violation may be different from 'mresidual' (ex:clamped if unilateral)
double candidate_violation = fabs(mconstraints[ic]->Violation(mresidual));
// compute: delta_lambda = -(omega/g_i) * ([Cq_i]*q + b_i + cfm_i*l_i )
double deltal = (omega / mconstraints[ic]->Get_g_i()) * (-mresidual);
if (mconstraints[ic]->GetMode() == CONSTRAINT_FRIC) {
candidate_violation = 0;
// update: lambda += delta_lambda;
old_lambda_friction[i_friction_comp] = mconstraints[ic]->Get_l_i();
mconstraints[ic]->Set_l_i(old_lambda_friction[i_friction_comp] + deltal);
i_friction_comp++;
if (i_friction_comp == 1)
candidate_violation = fabs(ChMin(0.0, mresidual));
if (i_friction_comp == 3) {
mconstraints[ic - 2]->Project(); // the N normal component will take care of N,U,V
double new_lambda_0 = mconstraints[ic - 2]->Get_l_i();
double new_lambda_1 = mconstraints[ic - 1]->Get_l_i();
double new_lambda_2 = mconstraints[ic - 0]->Get_l_i();
// Apply the smoothing: lambda= sharpness*lambda_new_projected + (1-sharpness)*lambda_old
if (this->shlambda != 1.0) {
new_lambda_0 = shlambda * new_lambda_0 + (1.0 - shlambda) * old_lambda_friction[0];
new_lambda_1 = shlambda * new_lambda_1 + (1.0 - shlambda) * old_lambda_friction[1];
new_lambda_2 = shlambda * new_lambda_2 + (1.0 - shlambda) * old_lambda_friction[2];
mconstraints[ic - 2]->Set_l_i(new_lambda_0);
mconstraints[ic - 1]->Set_l_i(new_lambda_1);
mconstraints[ic - 0]->Set_l_i(new_lambda_2);
}
double true_delta_0 = new_lambda_0 - old_lambda_friction[0];
double true_delta_1 = new_lambda_1 - old_lambda_friction[1];
double true_delta_2 = new_lambda_2 - old_lambda_friction[2];
mconstraints[ic - 2]->Increment_q(true_delta_0);
mconstraints[ic - 1]->Increment_q(true_delta_1);
mconstraints[ic - 0]->Increment_q(true_delta_2);
if (this->record_violation_history) {
maxdeltalambda = ChMax(maxdeltalambda, fabs(true_delta_0));
maxdeltalambda = ChMax(maxdeltalambda, fabs(true_delta_1));
maxdeltalambda = ChMax(maxdeltalambda, fabs(true_delta_2));
}
i_friction_comp = 0;
}
} else {
// update: lambda += delta_lambda;
double old_lambda = mconstraints[ic]->Get_l_i();
mconstraints[ic]->Set_l_i(old_lambda + deltal);
// If new lagrangian multiplier does not satisfy inequalities, project
// it into an admissible orthant (or, in general, onto an admissible set)
mconstraints[ic]->Project();
// After projection, the lambda may have changed a bit..
double new_lambda = mconstraints[ic]->Get_l_i();
// Apply the smoothing: lambda= sharpness*lambda_new_projected + (1-sharpness)*lambda_old
if (this->shlambda != 1.0) {
new_lambda = shlambda * new_lambda + (1.0 - shlambda) * old_lambda;
mconstraints[ic]->Set_l_i(new_lambda);
}
double true_delta = new_lambda - old_lambda;
// For all items with variables, add the effect of incremented
// (and projected) lagrangian reactions:
mconstraints[ic]->Increment_q(true_delta);
if (this->record_violation_history)
maxdeltalambda = ChMax(maxdeltalambda, fabs(true_delta));
}
maxviolation = ChMax(maxviolation, fabs(candidate_violation));
} // end IsActive()
} // end loop on constraints
// For recording into violaiton history, if debugging
if (this->record_violation_history)
AtIterationEnd(maxviolation, maxdeltalambda, iter);
tot_iterations++;
// Terminate the loop if violation in constraints has been succesfully limited.
if (maxviolation < tolerance)
break;
} // end iteration loop
return maxviolation;
}
} // end namespace chrono
| 46.132979
| 113
| 0.54883
|
andrewseidl
|
a94b05d89d40490fc932e6788c489c61c42e2e48
| 2,005
|
hpp
|
C++
|
altona_config.hpp
|
kebby/Werkkzeug4
|
f2ff557020d62c348b54d88e137999175b5c18a3
|
[
"BSD-2-Clause"
] | 10
|
2020-11-26T09:45:15.000Z
|
2022-03-18T00:18:27.000Z
|
altona_config.hpp
|
kebby/Werkkzeug4
|
f2ff557020d62c348b54d88e137999175b5c18a3
|
[
"BSD-2-Clause"
] | null | null | null |
altona_config.hpp
|
kebby/Werkkzeug4
|
f2ff557020d62c348b54d88e137999175b5c18a3
|
[
"BSD-2-Clause"
] | 3
|
2020-01-02T19:11:44.000Z
|
2022-03-18T00:21:45.000Z
|
/****************************************************************************/
/*** ***/
/*** Altona main configuration file. ***/
/*** ***/
/****************************************************************************/
/*** ***/
/*** Please rename this file to "altona_config.hpp" and edit it to ***/
/*** reflect your needs. ***/
/*** ***/
/****************************************************************************/
/*** ***/
/*** This file is compiled in every altona application ***/
/*** In addition to that, makeproject parses this file by hand on ***/
/*** every invokation. ***/
/*** ***/
/****************************************************************************/
// operator new shenanigans (one should investigate this)
#pragma warning (disable: 4595)
#pragma warning (disable: 5043)
// GCed objects don't have delete
#pragma warning (disable: 4291)
// macro redef in shader disasm (conflict between dxsdk and windows sdk)
#pragma warning (disable: 4005)
#define sCONFIG_CODEROOT L""
#define sCONFIG_SDK_DX9 1 // Microsoft DX9 sdk installed (required for input, sound, graphics)
#define sCONFIG_SDK_DX11 1
#define sCONFIG_SDK_CG 0
#define sCONFIG_GUID {0x74F17E89,{0x915F,0x4264,0xB67A},{0xBA,0xDF,0x00,0xD5,0x32,0x5A}}
#define sCONFIG_RENDER_DX9
#define sCONFIG_CEF 1
#ifdef _DEBUG
#define sCONFIG_BUILD_DEBUG
#else
#define sCONFIG_BUILD_RELEASE
#endif
| 44.555556
| 112
| 0.373067
|
kebby
|
a94bb8233adf874ddb31cd7d38d1488096bcf311
| 1,440
|
hpp
|
C++
|
examples/sill/vr-puzzle/frame.hpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | 15
|
2018-02-26T08:20:03.000Z
|
2022-03-06T03:25:46.000Z
|
examples/sill/vr-puzzle/frame.hpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | 32
|
2018-02-26T08:26:38.000Z
|
2020-09-12T17:09:38.000Z
|
examples/sill/vr-puzzle/frame.hpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | null | null | null |
#pragma once
#include <lava/sill.hpp>
#include <nlohmann/json.hpp>
struct GameState;
class Frame {
public:
Frame(GameState& gameState);
Frame(const Frame&) = delete;
Frame& operator=(const Frame&) = delete;
/// Create a frame.
static Frame& make(GameState& gameState);
/// Prepare the frame to be removed.
/// The destructor does not destroy anything
/// so that shutting down the application is fast enough.
virtual void clear(bool removeFromLevel = true);
const std::string& name() const { return m_name; }
void name(const std::string& name) { m_name = name; }
const lava::sill::EntityFrame& entityFrame() const { return *m_entityFrame; }
lava::sill::EntityFrame& entityFrame() { return *m_entityFrame; }
void entityFrame(lava::sill::EntityFrame& entityFrame) { m_entityFrame = &entityFrame; }
const lava::sill::MeshFrameComponent& mesh() const { return m_entityFrame->get<lava::sill::MeshFrameComponent>(); };
lava::sill::MeshFrameComponent& mesh() { return m_entityFrame->get<lava::sill::MeshFrameComponent>(); };
protected:
GameState& m_gameState;
lava::sill::EntityFrame* m_entityFrame = nullptr;
std::string m_name;
};
uint32_t findFrameIndex(GameState& gameState, const lava::sill::EntityFrame& entityFrame);
inline uint32_t findFrameIndex(GameState& gameState, const Frame& frame) {
return findFrameIndex(gameState, frame.entityFrame());
}
| 33.488372
| 120
| 0.709028
|
Breush
|
a94d08e7f1f4872b68209b77babad5630b68215f
| 6,338
|
cpp
|
C++
|
data/52.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
data/52.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
data/52.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
int Jn, ZjHQ/*Y*//*dEky*/
,H , lAIw,
Mb4p ,
Rfpqw,s ,e6k,zuS,sSjf
/*T*//**/
,IBH
, dg4 ,Vhk, iLTc
,X5YU, F4, hL /*2jtUXBP*/,
oHs ,
JC,MHO, joPQ
, zOHJ ;
void
f_f0
() {;//0uh
{ {
int VTT;
volatile int N
,/*kec*/ n , Q,O
;
{
for(int i=1 ;
i<
1 ;++i//zYj
){} {
for
(int i=1;i<2
;++i//X
)
//b
if (/*nG*/true ) {/*aQ*/ }else {//rU
} }} VTT=O +N+ n+
Q ;}{ /*Mp*/return ;if( true ) {; }else if( true ) {; { }{ int
Y//O
; volatile int QVq ,T8RxN ,
gUq;Y =//qBmC
gUq
+
QVq
+ T8RxN ;
if( true
)
{} else for (int
i=1;i<3;++i) ; //Vd
}
}
else if (//a
true)//
;else
{ { };/*Hg4b*/ }{volatile int O5E
,
ceux,
fH0 ;
{//duB
}zOHJ//mI
= fH0 +
O5E+ceux
; }}
for(int i=1;i< 4
;++i)if (true) return
;else
if (true/*VXU*/);else {int FN ;//S
volatile int
Ch
,C9
, Z;{
return ; if (//d
true)
{}else ;
} {
/*M2*/return ;/*kM7*/ for
(int /*V*/i=1
; i< /**/ 5/*k*/
;++i
)
return ;}FN =Z
+/*Fv*/Ch+
C9 ;
}return ; } return ; return ;
return ;}
void f_f1
() {for(int i=1;
i< 6
;++i);{ volatile int ReS
,zP,
PXb//UmM7m
,u4Y,
Bj,
VTCUC , Bz ;
//9S
{//t
volatile int Wj7,
/*nn*/Khx//P9
, mstW , rjoH ,
tSdj;; {
{volatile int W9y
,Ous4
;//H
if(true ) Jn=
Ous4+W9y//8h
//o1DB
; /*d*/else
return ;
}
if//ix
(true
)
{} else
return ;/*yc4z*/}ZjHQ=tSdj
+
Wj7
+ Khx+mstW+//ry
rjoH;
} if( true//RhY
)
H=Bz+ReS//87
+
zP+ PXb + u4Y+Bj +
VTCUC
;else{ { //DglY
{ ;} }
; {
{ ;
}{}
}
}{ if
( true);else return ;{ {} return
;}
}{ volatile int KcUw5P,satW, I5; {
int
ofQ;
volatile int LNPT
, kJf,mY
;{ }
ofQ= mY + LNPT+ kJf;
};lAIw=
I5+
KcUw5P
+
satW ;}} { {int UM;/*mG*/
volatile int
RYkTe,EQcC ,O3 ; if (
true
)
UM =
O3 +RYkTe
+ EQcC //aY
; else
{{
{}{
}{
} }}{ volatile int q,a5gF , X9T03
,
gFe6uE;
if
(
true
) {{/*6n*/volatile int Ln ;if
(true
//
)Mb4p
= Ln
;
else//XD
return ; }
} else/*EFG*/ Rfpqw
=
gFe6uE + q//e
+
a5gF +X9T03; {
} //
}{
volatile int Hr ,XtU ,/*zO*/uQ;
{}
s
=
uQ
+ Hr
+
XtU;}if
(true) {{{}if (
true){ } else{} }{/*tT*/ {} }
}else {{
} }for(int i=1 ; i< 7 ;++i )if( true ) {/*v5o*/ int w5bB
;volatile int QxP//v6N
//HVF6q
,iaa1e; if(true)for(int i=1;i< 8 ;++i
)for
(int
i=1
; i<9 ;++i
)if
(true
)
return ; else return/*J*/ ; else w5bB
= iaa1e
+QxP
;
{ {}{ }
} {{
} } } else
{ volatile int vEH
,C4n3p , Gj3SY,
AFCK;/*qR*/e6k=
AFCK +
vEH
+
C4n3p +
Gj3SY; }
//
return ;}{{ ; if
( true )
{} else{
volatile int j1, lg ; return
;zuS =
lg +j1
;return ; } } ; /*cSAm*/ } {{{{
{ } } }
{
if /*rP*/( true
){ }else return ; } } {/**/return ;{if ( true )
//1
return ;
else{ } }
}if(true
)
;else {/*J*/{
{
}{
}{} }//PGE
{}
/*ffJ*/{ }
} if (true ) { if
/*KZ8*/( true
){}
else ; }else
{for (int i=1;
i< 10 ;++i)return ;
; return/*gCypm*/
;
}
}
;{
{//S
{ return ; {
}//uC5D
}{int AD /*R2*/; volatile int
PRE, Swtj; AD
=Swtj+ PRE
;
return ; { }} } if ( true//uxo
) { /*x*/return ; } else
;
}}return
; return/*k*/ ;
}void f_f2
(){{{ int
n97; volatile int WJT1z , x4N ,
Sy ;n97 //
=Sy+WJT1z //lv
+x4N ;
{
{int
L1N;
volatile int XU/*ahy*/ //w
; L1N= XU ;}//d
for
(int
i=1
//hB7gK
;
i<
11;++i ){} ;} for/*X*/
(int i=1 ;i<12
;++i){
; }}{
int vsp ;
volatile int j ,Ylgro,
RGV9 //YP
,//nmy
GE
,g55 ,
//tA
PkmsX,ms , R
;//pR
//Hx
{volatile int V5 ,
VJsOq,
c ; sSjf=c +V5 +VJsOq //a
;}
IBH
=R
+j+Ylgro+RGV9+GE ;
vsp = g55 +
PkmsX
+ms//
;
} for
(int
i=1 ;
i<13;++i)
{ return ;
if
(true)if(true )
{//O
return ;
return ;}
else return
;
else for (int
i=1
;
i< 14 ;++i
)
{/*UYB*/{} }{; for (int
i=1 ;i<
/*n1S*/ 15 ;++i )for(int
i=1 ;//gf9
//
i<16 ;++i){} }
} {volatile int V89x8, YN8, Cr0jX//Wt
;for (int i=1 //v1o
; i</**/
17 /*PWv*/
;++i ) if (true)
dg4= Cr0jX
+ V89x8 +/**/YN8;else return ;{//fe
;}
if ( true ) {{ } { }{; }{int hX0W;volatile int N5
,
lw0U ; if(true ) {//Tg
//
} else{}
for (int
i=1
;i<
18;++i ) return//D
;
{ }
hX0W=lw0U
+ N5 ;}
} else
{
return ; {};
}}
}{{ int
W1Q;volatile int a ,zW
, D
,E;return
;W1Q//BV0P
=/*J5*/ E
+a
+ zW+D;
{ {
{{ }
}} /*6hb*/{}}{ return ;;
/*n*/
//n
{for (int i=1 ;i<//qzq
19/*IN4*/;++i
)
for (int i=1; i<20 ;++i
) if(
true )return ; else ;/*V56*/if
( true )
{ return ; }else
{} { }}
}/*gNm*/;
} { int
kVag
;volatile int i2,xRW
, //Hjl
bPYOQ7, SdKrE, e6;for (int i=1 ;i<21;++i
//tt9T
)
/*Y*/{;
{
{ } }} /*Gs*/kVag= e6+i2 + xRW +bPYOQ7+ SdKrE ; } ;
} {;return ;//Wo
;} return ; return ;//M6To
}
int
main /*d*/() { /*oh*/volatile int fF3,
W8hKj , rZ ,
/*SN5*/
mj ,r; if//C
(true ) return 1747888762 ;
else/*t*/
/**/ if( true
)
//6o
for (int
i=1; i<22
;++i ) { {
return//2
1892777458;
{{{}
}}
//VBI
return
973039688
//Pmf
;} //fh
{
return 979197843;
{ return 1574272463;}{
{{
}
}return 1112267248
; }
}{;//Kg
{ {volatile int OVcBo
,DL2 ;{
} Vhk = DL2
+
OVcBo;}for
(int i=1;
i< 23 ;++i )
{ return //m
472807525;return 2080782169 ; } {}
}
{ {} {;}
for(int i=1;i< 24;++i//5X
) return 403167836 ;}
}
}else iLTc=
r +
fF3/**/ +
W8hKj+rZ
+
mj//rn
;
{ {
volatile int g99Nx, Sxvj, gmw, Ge//0AXsi
; X5YU
//3E5T
=Ge+ g99Nx
/*m2*/ +
Sxvj+gmw ;
{ {volatile int BGQ
,
u ;F4 =u+ BGQ ; } } //uO
{
{
}
{{}return 1107412337
;}} for
(int i=1; i< 25
;++i) { { {{} { }
}
} {
{if (
true ){ } /*o*/else {//Nr
for
(int i=1
; /*l*/i<
26 ;++i){
} } }
//U2
;for (int
i=1
; i< 27 ;++i )//
{ ; ; } }}
}; {{{{
} {/*m*/ } //P2i
}}//h
for(int
i=1;i<28;++i )
{;
{}
;
{{} }} }}
;if/*J3B*/
( true
)return
2058880243;else/*OO*/
;; {volatile int //Lc
rCK , WZN ,Fm,
Bcc
,
zslP, YrC4
, fD ,/*1*/ wX ,hy ,RIQ
;
hL
=
RIQ
+rCK +
WZN +Fm+ Bcc; {{ //I7Q
{
}
for(int i=1
;i< 29
;++i
)
{ }} { {}//I
return 1287420094//HX
;}} oHs=
//JpO
zslP
+YrC4+
fD+ wX + hy //NuZ
;{{{ int pxnN;
volatile int/*cc3pC*/ hx
,
WQVc ;pxnN=
WQVc+
hx
;
/*v7R*/{
}
}}
{
volatile int
Gh ,
LdwE
, L20 , qoH4 , Opg, aFoc ,NJR ,ba8JC ,//rS
b2mXaio; JC
= b2mXaio
+Gh +LdwE ;{ } if /**/( true ) for(int i=1 ;i<30
;++i //
)
MHO =L20+ qoH4;else joPQ=Opg +
aFoc
+NJR/*4eLY*/
+ba8JC ;
}
//6WE
{{ }} }} }
| 10.373159
| 69
| 0.456453
|
TianyiChen
|
a94ff9967ca545c44b4cc9b92dc18e1b3ae361c8
| 6,368
|
cpp
|
C++
|
src/gausskernel/storage/access/rmgrdesc/nbtdesc.cpp
|
wotchin/openGauss-server
|
ebd92e92b0cfd76b121d98e4c57a22d334573159
|
[
"MulanPSL-1.0"
] | 1
|
2020-06-30T15:00:50.000Z
|
2020-06-30T15:00:50.000Z
|
src/gausskernel/storage/access/rmgrdesc/nbtdesc.cpp
|
wotchin/openGauss-server
|
ebd92e92b0cfd76b121d98e4c57a22d334573159
|
[
"MulanPSL-1.0"
] | null | null | null |
src/gausskernel/storage/access/rmgrdesc/nbtdesc.cpp
|
wotchin/openGauss-server
|
ebd92e92b0cfd76b121d98e4c57a22d334573159
|
[
"MulanPSL-1.0"
] | null | null | null |
/* -------------------------------------------------------------------------
*
* nbtdesc.cpp
* rmgr descriptor routines for access/nbtree/nbtxlog.cpp
*
* Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd.
* Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/gausskernel/storage/access/rmgrdesc/nbtdesc.cpp
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include "access/nbtree.h"
void btree_desc(StringInfo buf, XLogReaderState* record)
{
char* rec = XLogRecGetData(record);
uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
switch (info) {
case XLOG_BTREE_INSERT_LEAF: {
xl_btree_insert* xlrec = (xl_btree_insert*)rec;
appendStringInfo(buf, "insert leaf: ");
appendStringInfo(buf, "off %u", (uint32)xlrec->offnum);
break;
}
case XLOG_BTREE_INSERT_UPPER: {
xl_btree_insert* xlrec = (xl_btree_insert*)rec;
appendStringInfo(buf, "insert upper: ");
appendStringInfo(buf, "off %u", (uint32)xlrec->offnum);
break;
}
case XLOG_BTREE_INSERT_META: {
xl_btree_insert* xlrec = (xl_btree_insert*)rec;
appendStringInfo(buf, "insert meta: ");
appendStringInfo(buf, "off %u",(uint32)xlrec->offnum);
break;
}
case XLOG_BTREE_SPLIT_L: {
xl_btree_split* xlrec = (xl_btree_split*)rec;
appendStringInfo(buf, "split left: ");
appendStringInfo(buf, "level %u; firstright %u; new off %u",
xlrec->level, (uint32)xlrec->firstright, (uint32)xlrec->newitemoff);
break;
}
case XLOG_BTREE_SPLIT_R: {
xl_btree_split* xlrec = (xl_btree_split*)rec;
appendStringInfo(buf, "split right: ");
appendStringInfo(buf, "level %u; firstright %u; new off %u",
xlrec->level, (uint32)xlrec->firstright, (uint32)xlrec->newitemoff);
break;
}
case XLOG_BTREE_SPLIT_L_ROOT: {
xl_btree_split* xlrec = (xl_btree_split*)rec;
appendStringInfo(buf, "split left root: ");
appendStringInfo(buf, "level %u; firstright %u; new off %u",
xlrec->level, (uint32)xlrec->firstright, (uint32)xlrec->newitemoff);
break;
}
case XLOG_BTREE_SPLIT_R_ROOT: {
xl_btree_split* xlrec = (xl_btree_split*)rec;
appendStringInfo(buf, "split right root: ");
appendStringInfo(buf, "level %u; firstright %u; new off %u",
xlrec->level, (uint32)xlrec->firstright, (uint32)xlrec->newitemoff);
break;
}
case XLOG_BTREE_VACUUM: {
xl_btree_vacuum* xlrec = (xl_btree_vacuum*)rec;
appendStringInfo(buf, "vacuum: lastBlockVacuumed %u ", xlrec->lastBlockVacuumed);
break;
}
case XLOG_BTREE_DELETE: {
xl_btree_delete* xlrec = (xl_btree_delete*)rec;
int bucket_id = XLogRecGetBucketId(record);
if (bucket_id == -1) {
appendStringInfo(buf,
"delete: %d items; heap %u/%u/%u",
xlrec->nitems,
xlrec->hnode.spcNode,
xlrec->hnode.dbNode,
xlrec->hnode.relNode);
} else {
appendStringInfo(buf,
"delete: %d items; heap %u/%u/%d/%u",
xlrec->nitems,
xlrec->hnode.spcNode,
xlrec->hnode.dbNode,
bucket_id,
xlrec->hnode.relNode);
}
break;
}
case XLOG_BTREE_DELETE_PAGE: {
xl_btree_delete_page* xlrec = (xl_btree_delete_page*)rec;
appendStringInfo(buf, "delete page: ");
appendStringInfo(buf,
"left %u; right %u; btpo_xact " XID_FMT "; parent off %u",
xlrec->leftblk,
xlrec->rightblk,
xlrec->btpo_xact,
(uint32)xlrec->poffset);
break;
}
case XLOG_BTREE_DELETE_PAGE_META: {
xl_btree_delete_page* xlrec = (xl_btree_delete_page*)rec;
appendStringInfo(buf, "delete page meta: ");
appendStringInfo(buf,
"left %u; right %u; btpo_xact " XID_FMT "; parent off %u",
xlrec->leftblk,
xlrec->rightblk,
xlrec->btpo_xact,
(uint32)xlrec->poffset);
break;
}
case XLOG_BTREE_DELETE_PAGE_HALF: {
xl_btree_delete_page* xlrec = (xl_btree_delete_page*)rec;
appendStringInfo(buf, "delete page half: ");
appendStringInfo(buf,
"left %u; right %u; btpo_xact " XID_FMT "; parent off %u",
xlrec->leftblk,
xlrec->rightblk,
xlrec->btpo_xact,
(uint32)xlrec->poffset);
break;
}
case XLOG_BTREE_NEWROOT: {
xl_btree_newroot* xlrec = (xl_btree_newroot*)rec;
appendStringInfo(buf, "lev %u", xlrec->level);
break;
}
case XLOG_BTREE_REUSE_PAGE: {
xl_btree_reuse_page* xlrec = (xl_btree_reuse_page*)rec;
int bucket_id = XLogRecGetBucketId(record);
if (bucket_id == -1) {
appendStringInfo(buf,
"reuse_page: rel %u/%u/%u; latestRemovedXid " XID_FMT,
xlrec->node.spcNode,
xlrec->node.dbNode,
xlrec->node.relNode,
xlrec->latestRemovedXid);
} else {
appendStringInfo(buf,
"reuse_page: rel %u/%u/%u/%d; latestRemovedXid " XID_FMT,
xlrec->node.spcNode,
xlrec->node.dbNode,
xlrec->node.relNode,
bucket_id,
xlrec->latestRemovedXid);
}
break;
}
default:
appendStringInfo(buf, "UNKNOWN");
break;
}
}
| 36.388571
| 93
| 0.518687
|
wotchin
|
a9502feb3e45152639b936352d0e4a4acc27db05
| 626
|
cpp
|
C++
|
Source/TTreeNodeStack.cpp
|
poissonconsulting/RadCon
|
acbbb974ececbabddd3da91768744bf31982bf93
|
[
"MIT"
] | 1
|
2021-12-26T13:32:52.000Z
|
2021-12-26T13:32:52.000Z
|
Source/TTreeNodeStack.cpp
|
joethorley/RadCon
|
acbbb974ececbabddd3da91768744bf31982bf93
|
[
"MIT"
] | 1
|
2015-02-02T19:28:20.000Z
|
2015-02-02T19:28:20.000Z
|
Source/TTreeNodeStack.cpp
|
poissonconsulting/RadCon
|
acbbb974ececbabddd3da91768744bf31982bf93
|
[
"MIT"
] | null | null | null |
#include "TTreeNodeStack.h"
TTreeNodeStack& TTreeNodeStack::operator = (const TTreeNodeStack& treeNodeStack)
{
fStack = treeNodeStack.fStack;
return (*this);
}
void TTreeNodeStack::Pop (TTreeNode*& item)
{
TObject* obj = NULL;
fStack.Pop (obj);
item = (TTreeNode*)obj;
}
void TTreeNodeStack::Top (const TTreeNode*& item) const
{
const TObject* obj = NULL;
fStack.Top (obj);
item = (TTreeNode*) obj;
}
TTreeNodeStack::TTreeNodeStack (void)
: fStack ()
{
}
TTreeNodeStack::TTreeNodeStack (const TTreeNodeStack& treeNodeStack)
: fStack (treeNodeStack.fStack)
{
}
TTreeNodeStack::~TTreeNodeStack (void)
{
}
| 626
| 626
| 0.714058
|
poissonconsulting
|
a9515c3a9871501b5f38882857e04237882ba60a
| 7,127
|
cc
|
C++
|
base/search.cc
|
haveTryTwo/csutil
|
7cb071f6927db4c52832d3074fb69f273968d66e
|
[
"BSD-2-Clause"
] | 9
|
2015-08-14T08:59:06.000Z
|
2018-08-20T13:46:46.000Z
|
base/search.cc
|
haveTryTwo/csutil
|
7cb071f6927db4c52832d3074fb69f273968d66e
|
[
"BSD-2-Clause"
] | null | null | null |
base/search.cc
|
haveTryTwo/csutil
|
7cb071f6927db4c52832d3074fb69f273968d66e
|
[
"BSD-2-Clause"
] | 1
|
2018-08-20T13:46:29.000Z
|
2018-08-20T13:46:29.000Z
|
// Copyright (c) 2015 The CSUTIL Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/search.h"
namespace base
{
}
#ifdef _SEARCH_MAIN_TEST_
#include <deque>
#include <vector>
#include <utility>
#include <assert.h>
int main(int argc, char *argv[])
{/*{{{*/
using namespace base;
// descend search
int arr_des_odd[] = {40, 35, 30, 25, 20, 15, 10};
Print(arr_des_odd, arr_des_odd + sizeof(arr_des_odd)/sizeof(arr_des_odd[0]), arr_des_odd[0]);
int pos = 0;
int test_arr_odd[] = {43, 40, 37, 35, 32, 30, 28, 25, 21, 20, 16, 15, 13, 10, 2 };
for (int i = 0; i < (int)(sizeof(test_arr_odd)/sizeof(test_arr_odd[0])); ++i)
{
Code ret = BinaryDescendSearch(arr_des_odd, sizeof(arr_des_odd)/sizeof(arr_des_odd[0]),
test_arr_odd[i], &pos, CompareNum<int>);
assert(ret == kOk);
fprintf(stderr, "test_value:%d, find pos:%d, value:%d\n", test_arr_odd[i], pos, arr_des_odd[pos]);
}
fprintf(stderr, "\n");
int arr_des_even[] = {40, 35, 30, 25, 20, 15};
Print(arr_des_even, arr_des_even + sizeof(arr_des_even)/sizeof(arr_des_even[0]), arr_des_even[0]);
int test_arr_even[] = {44, 40, 38, 35, 33, 30, 26, 25, 24, 20, 18, 15, 11};
for (int i = 0; i < (int)(sizeof(test_arr_even)/sizeof(test_arr_even[0])); ++i)
{
Code ret = BinaryDescendSearch(arr_des_even, sizeof(arr_des_even)/sizeof(arr_des_even[0]),
test_arr_even[i], &pos, CompareNum<int>);
assert(ret == kOk);
fprintf(stderr, "test_value:%d, find pos:%d, value:%d\n", test_arr_even[i], pos, arr_des_even[pos]);
}
fprintf(stderr, "\n");
// ascend search
int arr_asc_odd[] = {10, 15, 20, 25, 30, 35, 40};
Print(arr_asc_odd, arr_asc_odd + sizeof(arr_asc_odd)/sizeof(arr_asc_odd[0]), arr_asc_odd[0]);
for (int i = (int)(sizeof(test_arr_odd)/sizeof(test_arr_odd[0])) - 1; i >= 0; --i)
{
Code ret = BinaryAscendSearch(arr_asc_odd, sizeof(arr_asc_odd)/sizeof(arr_asc_odd[0]),
test_arr_odd[i], &pos, CompareNum<int>);
assert(ret == kOk);
fprintf(stderr, "test_value:%d, find pos:%d, value:%d\n", test_arr_odd[i], pos, arr_asc_odd[pos]);
}
fprintf(stderr, "\n");
int arr_asc_even[] = {15, 20, 25, 30, 35, 40};
Print(arr_asc_even, arr_asc_even + sizeof(arr_asc_even)/sizeof(arr_asc_even[0]), arr_asc_even[0]);
for (int i = (int)(sizeof(test_arr_even)/sizeof(test_arr_even[0])) -1; i >= 0; --i)
{
Code ret = BinaryAscendSearch(arr_asc_even, sizeof(arr_asc_even)/sizeof(arr_asc_even[0]),
test_arr_even[i], &pos, CompareNum<int>);
assert(ret == kOk);
fprintf(stderr, "test_value:%d, find pos:%d, value:%d\n", test_arr_even[i], pos, arr_asc_even[pos]);
}
fprintf(stderr, "\n");
// descend search using RandomIterator
std::vector<int> vec_des_odd(arr_des_odd, arr_des_odd+sizeof(arr_des_odd)/sizeof(arr_des_odd[0]));
Print(vec_des_odd.begin(), vec_des_odd.end(), vec_des_odd[0]);
std::vector<int>::iterator it;
for (int i = 0; i < (int)(sizeof(test_arr_odd)/sizeof(test_arr_odd[0])); ++i)
{
Code ret = BinaryDescendSearch(vec_des_odd.begin(), vec_des_odd.end(),
test_arr_odd[i], &it, CompareNum<int>);
assert(ret == kOk);
fprintf(stderr, "test_value:%d, value:%d\n", test_arr_odd[i], *it);
}
fprintf(stderr, "\n");
std::vector<int> vec_des_even(arr_des_even, arr_des_even+sizeof(arr_des_even)/sizeof(arr_des_even[0]));
Print(vec_des_even.begin(), vec_des_even.end(), vec_des_even[0]);
for (int i = 0; i < (int)(sizeof(test_arr_even)/sizeof(test_arr_even[0])); ++i)
{
Code ret = BinaryDescendSearch(vec_des_even.begin(), vec_des_even.end(),
test_arr_even[i], &it, CompareNum<int>);
assert(ret == kOk);
fprintf(stderr, "test_value:%d, value:%d\n", test_arr_even[i], *it);
}
fprintf(stderr, "\n");
// ascend search using RandomIterator
std::deque<int> deq_asc_odd(arr_asc_odd, arr_asc_odd+sizeof(arr_asc_odd)/sizeof(arr_asc_odd[0]));
Print(deq_asc_odd.begin(), deq_asc_odd.end(), deq_asc_odd[0]);
std::deque<int>::iterator deq_it;
for (int i = (int)(sizeof(test_arr_odd)/sizeof(test_arr_odd[0])) - 1; i >= 0; --i)
{
Code ret = BinaryAscendSearch(deq_asc_odd.begin(), deq_asc_odd.end(),
test_arr_odd[i], &deq_it, CompareNum<int>);
assert(ret == kOk);
fprintf(stderr, "test_value:%d, value:%d\n", test_arr_odd[i], *deq_it);
}
fprintf(stderr, "\n");
std::deque<int> deq_asc_even(arr_asc_even, arr_asc_even+sizeof(arr_asc_even)/sizeof(arr_asc_even[0]));
Print(deq_asc_even.begin(), deq_asc_even.end(), deq_asc_even[0]);
for (int i = (int)(sizeof(test_arr_even)/sizeof(test_arr_even[0])) -1; i >= 0; --i)
{
Code ret = BinaryAscendSearch(deq_asc_even.begin(), deq_asc_even.end(),
test_arr_even[i], &deq_it, CompareNum<int>);
assert(ret == kOk);
fprintf(stderr, "test_value:%d, value:%d\n", test_arr_even[i], *deq_it);
}
fprintf(stderr, "\n");
fprintf(stderr, "\n");
// ascend search using RandomIterator and ComparePair
std::vector<std::pair<std::string, std::string> > dir;
dir.push_back(std::make_pair<std::string, std::string>("aa", "aa.txt"));
dir.push_back(std::make_pair<std::string, std::string>("hh", "hh.txt"));
dir.push_back(std::make_pair<std::string, std::string>("oo", "oo.txt"));
dir.push_back(std::make_pair<std::string, std::string>("uu", "uu.txt"));
std::pair<std::string, std::string> finds[] = {/*{{{*/
std::pair<std::string, std::string>("aa", ""),
std::pair<std::string, std::string>("bb", ""),
std::pair<std::string, std::string>("cc", ""),
std::pair<std::string, std::string>("hh", ""),
std::pair<std::string, std::string>("ii", ""),
std::pair<std::string, std::string>("jj", ""),
std::pair<std::string, std::string>("oo", ""),
std::pair<std::string, std::string>("pp", ""),
std::pair<std::string, std::string>("qq", ""),
std::pair<std::string, std::string>("uu", ""),
std::pair<std::string, std::string>("vv", ""),
std::pair<std::string, std::string>("xx", ""),
};/*}}}*/
fprintf(stderr, "finds num:%zu, single size:%zu\n", sizeof(finds)/sizeof(finds[0]), sizeof(finds[0]));
std::vector<std::pair<std::string, std::string> >::iterator pair_it;
for (int i = 0; i < (int)(sizeof(finds)/sizeof(finds[0])); ++i)
{
Code ret = BinaryAscendSearch(dir.begin(), dir.end(), finds[i], &pair_it,
ComparePair<std::pair<std::string, std::string> >);
assert(ret == kOk);
fprintf(stderr, "finds key:%s, value:(%s, %s)\n", finds[i].first.c_str(), pair_it->first.c_str(),
pair_it->second.c_str());
}
fprintf(stderr, "\n");
return 0;
}/*}}}*/
#endif
| 45.107595
| 108
| 0.603059
|
haveTryTwo
|