blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d23ec87cb3c33db1b88bee7f9e0487e8ed2acb27
|
9c3edb19f7a3cbcd9e7948394313d6776f3d6a1d
|
/statemachine/stringmaxlengthtransition.h
|
5d8c1ec98c50532c3df09f031a844d908651e482
|
[] |
no_license
|
Aschen/cutebox-public
|
6dd198c04608db199d7cf3fe90b3136ec4b19b5b
|
672c3512ee4f1f1fa60a2163c80d32735c3febc0
|
refs/heads/master
| 2021-01-19T06:06:12.742472
| 2016-09-13T12:17:13
| 2016-09-13T12:17:13
| 65,465,713
| 0
| 1
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 1,172
|
h
|
/******************************************************************************
COPYRIGHT (c) 2008 - 2010 by RG Systèmes Corporation.
This software has been provided pursuant to a License Agreement
containing restrictions on its use. This software contains
valuable trade secrets and proprietary information of
RG Systèmes Corporation and is protected by law. It may
not be copied or distributed in any form or medium, disclosed
to third parties, reverse engineered or used in any manner not
provided for in said License Agreement except with the prior
written authorization from RG Systèmes Corporation.
******************************************************************************/
#ifndef STRINGMAXLENGTHTRANSITION_H
#define STRINGMAXLENGTHTRANSITION_H
#include <QString>
#include "transition.h"
class StringMaxLengthTransition : public Transition
{
public:
StringMaxLengthTransition(int maxLength);
protected:
virtual bool eventTest(TransitionEvent * event) const;
private:
int m_maxLength;
};
#endif // STRINGMAXLENGTHTRANSITION_H
|
[
"a.maret@studio-hb.com"
] |
a.maret@studio-hb.com
|
abcdf1bff260ae165d7cff0ea915374a95087daf
|
edcde36aec5ab5166510e9e2fb6afd369deaf13c
|
/src/compiler/tempest/sema/convert/subtype.cpp
|
5107b8c7f76c50107c45f396afa71af2780018c2
|
[] |
no_license
|
viridia/tempest
|
585f6f44b7047f60a9799fd082e168e815bd8264
|
a0ecf8269dc68edf182dce62bbef6b9602a0adc6
|
refs/heads/master
| 2020-03-23T11:53:47.431485
| 2018-11-16T01:59:28
| 2018-11-16T01:59:28
| 141,525,372
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,075
|
cpp
|
#include "tempest/error/diagnostics.hpp"
#include "tempest/sema/convert/predicate.hpp"
#include "tempest/sema/graph/primitivetype.hpp"
#include "tempest/sema/transform/applyspec.hpp"
namespace tempest::sema::convert {
using namespace tempest::sema::graph;
using namespace llvm;
using tempest::error::diag;
using tempest::sema::transform::TempMapTypeVars;
bool isSubtype(
const TypeDefn* st, Env& stEnv,
const TypeDefn* bt, Env& btEnv) {
if (bt == st) {
if (btEnv.args.size() != stEnv.args.size()) {
return false;
}
// Make sure type arguments are the same
for (auto param : bt->allTypeParams()) {
if (!isEqual(btEnv.args[param->index()], stEnv.args[param->index()])) {
return false;
}
}
return true;
}
MemberArray bases;
if (bt->type()->kind == st->type()->kind) {
bases = st->extends();
} else if (bt->type()->kind == Type::Kind::INTERFACE || bt->type()->kind == Type::Kind::TRAIT) {
bases = st->implements();
} else {
return false;
}
for (auto base : bases) {
if (base->kind == Defn::Kind::SPECIALIZED) {
auto sp = static_cast<const SpecializedDefn*>(base);
TempMapTypeVars apply(stEnv.args);
Env newEnv;
newEnv.params = sp->typeParams();
newEnv.args = apply.transformArray(sp->typeArgs());
if (auto baseDefn = dyn_cast<TypeDefn>(sp->generic())) {
if (isSubtype(baseDefn, newEnv, bt, btEnv)) {
return true;
}
} else {
assert(false && "Invalid base type");
}
} else if (auto baseDefn = dyn_cast<TypeDefn>(base)) {
if (isSubtype(baseDefn, stEnv, bt, btEnv)) {
return true;
}
} else {
assert(false && "Invalid base type");
}
}
return false;
}
// TODO: Check for structural typing.
// If st is a class and bt is an interface or trait;
// if st is a struct, interface, trait, alias, and bt is a trait.
// And we probably want to cache the result.
}
|
[
"viridia@gmail.com"
] |
viridia@gmail.com
|
b4ed4774432be06a428b43c938ee6e93ebb63587
|
f1e3b4751f3d74cfd19528f6890f2095e2cd4147
|
/tools/Wix/sdk/inc/dutil.h
|
9f98883f802d1836abbea9a3c6c74a342ad0cff5
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"CPL-1.0"
] |
permissive
|
matteobruni/NLog
|
703dd690b7026a3fb3a04b84b59900667281920f
|
07a4f0db752a4127586a13127d1021b4eb2b9155
|
refs/heads/master
| 2023-04-11T22:38:55.720947
| 2015-09-30T08:34:48
| 2015-09-30T08:34:48
| 29,958,899
| 1
| 0
|
BSD-3-Clause
| 2023-04-03T23:57:38
| 2015-01-28T09:02:50
|
C#
|
UTF-8
|
C++
| false
| false
| 11,505
|
h
|
#pragma once
//-------------------------------------------------------------------------------------------------
// <copyright file="dutil.h" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// <summary>
// Header for utility layer that provides standard support for asserts, exit macros
// </summary>
//-------------------------------------------------------------------------------------------------
#define DAPI __stdcall
#define DAPIV __cdecl // used only for functions taking variable length arguments
#define DAPI_(type) EXTERN_C type DAPI
#define DAPIV_(type) EXTERN_C type DAPIV
// enums
enum REPORT_LEVEL
{
REPORT_NONE, // turns off report (only valid for XXXSetLevel())
REPORT_STANDARD, // written if reporting is on
REPORT_VERBOSE, // written only if verbose reporting is on
REPORT_DEBUG, // reporting useful when debugging code
REPORT_ERROR, // always gets reported, but can never be specified
};
// asserts and traces
#ifdef DEBUG
typedef BOOL (DAPI *DUTIL_ASSERTDISPLAYFUNCTION)(LPCSTR sz);
extern "C" void DAPI Dutil_SetAssertModule(__in HMODULE hAssertModule);
extern "C" void DAPI Dutil_SetAssertDisplayFunction(__in DUTIL_ASSERTDISPLAYFUNCTION pfn);
extern "C" void DAPI Dutil_Assert(const CHAR* szFile, int iLine);
extern "C" void DAPI Dutil_AssertSz(const CHAR* szFile, int iLine, const CHAR *szMsg);
extern "C" void DAPI Dutil_TraceSetLevel(__in REPORT_LEVEL ll, __in BOOL fTraceFilenames);
extern "C" REPORT_LEVEL DAPI Dutil_TraceGetLevel();
extern "C" void __cdecl Dutil_Trace(__in LPCSTR szFile, __in int iLine, __in REPORT_LEVEL rl, __in LPCSTR szMessage, ...);
extern "C" void __cdecl Dutil_TraceError(__in LPCSTR szFile, __in int iLine, __in REPORT_LEVEL rl, __in HRESULT hr, __in LPCSTR szMessage, ...);
#endif
extern "C" void DAPI Dutil_RootFailure(__in LPCSTR szFile, __in int iLine, __in HRESULT hrError);
#ifdef DEBUG
#define AssertSetModule(m) (void)Dutil_SetAssertModule(m)
#define AssertSetDisplayFunction(pfn) (void)Dutil_SetAssertDisplayFunction(pfn)
#define Assert(f) ((f) ? (void)0 : (void)Dutil_Assert(__FILE__, __LINE__))
#define AssertSz(f, sz) ((f) ? (void)0 : (void)Dutil_AssertSz(__FILE__, __LINE__, sz))
#define TraceSetLevel(l, f) (void)Dutil_TraceSetLevel(l, f)
#define TraceGetLevel() (REPORT_LEVEL)Dutil_TraceGetLevel()
#define Trace(l, f) (void)Dutil_Trace(__FILE__, __LINE__, l, f, NULL)
#define Trace1(l, f, s) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s)
#define Trace2(l, f, s, t) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s, t)
#define Trace3(l, f, s, t, u) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s, t, u)
#define TraceError(x, f) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, NULL)
#define TraceError1(x, f, s) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s)
#define TraceError2(x, f, s, t) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s, t)
#define TraceError3(x, f, s, t, u) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s, t, u)
#define TraceErrorDebug(x, f) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, NULL)
#define TraceErrorDebug1(x, f, s) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s)
#define TraceErrorDebug2(x, f, s, t) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s, t)
#define TraceErrorDebug3(x, f, s, t, u) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s, t, u)
#else // !DEBUG
#define AssertSetModule(m)
#define AssertSetDisplayFunction(pfn)
#define Assert(f)
#define AssertSz(f, sz)
#define TraceSetLevel(l, f)
#define Trace(l, f)
#define Trace1(l, f, s)
#define Trace2(l, f, s, t)
#define Trace3(l, f, s, t, u)
#define TraceError(x, f)
#define TraceError1(x, f, s)
#define TraceError2(x, f, s, t)
#define TraceError3(x, f, s, t, u)
#define TraceErrorDebug(x, f)
#define TraceErrorDebug1(x, f, s)
#define TraceErrorDebug2(x, f, s, t)
#define TraceErrorDebug3(x, f, s, t, u)
#endif // DEBUG
// ExitTrace can be overriden
#ifndef ExitTrace
#define ExitTrace TraceError
#endif
#ifndef ExitTrace1
#define ExitTrace1 TraceError1
#endif
#ifndef ExitTrace2
#define ExitTrace2 TraceError2
#endif
#ifndef ExitTrace3
#define ExitTrace3 TraceError3
#endif
// Exit macros
#define ExitFunction() { goto LExit; }
#define ExitFunction1(x) { x; goto LExit; }
#define ExitOnLastError(x, s) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; } }
#define ExitOnLastError1(x, f, s) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; } }
#define ExitOnLastError2(x, f, s, t) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; } }
#define ExitOnLastErrorDebugTrace(x, s) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug(x, s); goto LExit; } }
#define ExitOnLastErrorDebugTrace1(x, f, s) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug1(x, f, s); goto LExit; } }
#define ExitOnLastErrorDebugTrace2(x, f, s, t) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug2(x, f, s, t); goto LExit; } }
#define ExitWithLastError(x, s) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitWithLastError1(x, f, s) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }
#define ExitWithLastError2(x, f, s, t) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }
#define ExitWithLastError3(x, f, s, t, u) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace3(x, f, s, t, u); goto LExit; }
#define ExitOnFailure(x, s) if (FAILED(x)) { ExitTrace(x, s); goto LExit; }
#define ExitOnFailure1(x, f, s) if (FAILED(x)) { ExitTrace1(x, f, s); goto LExit; }
#define ExitOnFailure2(x, f, s, t) if (FAILED(x)) { ExitTrace2(x, f, s, t); goto LExit; }
#define ExitOnFailure3(x, f, s, t, u) if (FAILED(x)) { ExitTrace3(x, f, s, t, u); goto LExit; }
#define ExitOnRootFailure(x, s) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitOnRootFailure1(x, f, s) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }
#define ExitOnRootFailure2(x, f, s, t) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }
#define ExitOnRootFailure3(x, f, s, t, u) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace3(x, f, s, t, u); goto LExit; }
#define ExitOnFailureDebugTrace(x, s) if (FAILED(x)) { TraceErrorDebug(x, s); goto LExit; }
#define ExitOnFailureDebugTrace1(x, f, s) if (FAILED(x)) { TraceErrorDebug1(x, f, s); goto LExit; }
#define ExitOnFailureDebugTrace2(x, f, s, t) if (FAILED(x)) { TraceErrorDebug2(x, f, s, t); goto LExit; }
#define ExitOnFailureDebugTrace3(x, f, s, t, u) if (FAILED(x)) { TraceErrorDebug3(x, f, s, t, u); goto LExit; }
#define ExitOnNull(p, x, e, s) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitOnNull1(p, x, e, f, s) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }
#define ExitOnNull2(p, x, e, f, s, t) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }
#define ExitOnNullWithLastError(p, x, s) if (NULL == p) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitOnNullWithLastError1(p, x, f, s) if (NULL == p) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }
#define ExitOnNullDebugTrace(p, x, e, s) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug(x, s); goto LExit; }
#define ExitOnNullDebugTrace1(p, x, e, f, s) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug1(x, f, s); goto LExit; }
#define ExitOnInvalidHandleWithLastError(p, x, s) if (INVALID_HANDLE_VALUE == p) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitOnInvalidHandleWithLastError1(p, x, f, s) if (INVALID_HANDLE_VALUE == p) { x = ::GetLastError(); x = HRESULT_FROM_WIN32(x); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }
#define ExitOnWin32Error(e, x, s) if (ERROR_SUCCESS != e) { x = HRESULT_FROM_WIN32(e); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }
#define ExitOnWin32Error1(e, x, f, s) if (ERROR_SUCCESS != e) { x = HRESULT_FROM_WIN32(e); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }
// release macros
#define ReleaseObject(x) if (x) { x->Release(); }
#define ReleaseObjectArray(prg, cel) if (prg) { for (DWORD Dutil_ReleaseObjectArrayIndex = 0; Dutil_ReleaseObjectArrayIndex < cel; ++Dutil_ReleaseObjectArrayIndex) { ReleaseObject(prg[Dutil_ReleaseObjectArrayIndex]); } ReleaseMem(prg); }
#define ReleaseVariant(x) { ::VariantClear(&x); }
#define ReleaseNullObject(x) if (x) { (x)->Release(); x = NULL; }
#define ReleaseCertificate(x) if (x) { ::CertFreeCertificateContext(x); x=NULL; }
#define ReleaseHandle(x) if (x) { ::CloseHandle(x); x = NULL; }
// useful defines and macros
#define Unused(x) ((void)x)
#ifndef countof
#if 1
#define countof(ary) (sizeof(ary) / sizeof(ary[0]))
#else
#ifndef __cplusplus
#define countof(ary) (sizeof(ary) / sizeof(ary[0]))
#else
template<typename T> static char countofVerify(void const *, T) throw() { return 0; }
template<typename T> static void countofVerify(T *const, T *const *) throw() {};
#define countof(arr) (sizeof(countofVerify(arr,&(arr))) * sizeof(arr)/sizeof(*(arr)))
#endif
#endif
#endif
#define roundup(x, n) roundup_typed(x, n, DWORD)
#define roundup_typed(x, n, t) (((t)(x) + ((t)(n) - 1)) & ~((t)(n) - 1))
#define HRESULT_FROM_RPC(x) ((HRESULT) ((x) | FACILITY_RPC))
#ifndef MAXSIZE_T
#define MAXSIZE_T ((SIZE_T)~((SIZE_T)0))
#endif
typedef const BYTE* LPCBYTE;
#define E_FILENOTFOUND HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
#define E_INVALIDSTATE HRESULT_FROM_WIN32(ERROR_INVALID_STATE)
#define E_MOREDATA HRESULT_FROM_WIN32(ERROR_MORE_DATA)
#define E_NOMOREITEMS HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS)
#define E_NOTFOUND HRESULT_FROM_WIN32(ERROR_NOT_FOUND)
#define AddRefAndRelease(x) { x->AddRef(); x->Release(); }
#define MAKEQWORDVERSION(mj, mi, b, r) (((DWORD64)MAKELONG(r, b)) | (((DWORD64)MAKELONG(mi, mj)) << 32))
|
[
"jaak@jkowalski.net"
] |
jaak@jkowalski.net
|
6a3d3958f55df50ab20f21ab6fb20e197fb55dca
|
851387ba96f2cd553f198b18a73881ecea420bc4
|
/src/svgpath_quadratic_curve_abs.h
|
e5350d88ce9cf848283504647d066b66f33665bf
|
[] |
no_license
|
SetCalm/XPlotterSVG
|
56588bdb5655c4f44a6221d20cbaeb3172c2f13e
|
ad86f6f62cc815144253f40f59ab6e5cb1d40e71
|
refs/heads/master
| 2022-01-13T20:17:49.918322
| 2017-11-04T15:15:09
| 2017-11-04T15:15:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,285
|
h
|
/* XPlotterSVG - Convert SVG to GCode
Copyright (C) 2017 Samuel Pickard
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
#ifndef SVGPATH_QUADRATIC_CURVE_ABS_H
#define SVGPATH_QUADRATIC_CURVE_ABS_H
#include "svgpath_command.h"
class SVGPath_Quadratic_Curve_Abs : public SVGPath_Command
{
protected:
QTextStream* mGcode;
TransformationStack* mTrans;
void plotCurve(double stepSize, Point2D startPoint, Point2D endPoint, Point2D controlPoint);
public:
SVGPath_Quadratic_Curve_Abs();
void process(QQueue<QString>* commandQueue, QTextStream* gcode, TransformationStack trans);
};
#endif // SVGPATH_QUADRATIC_CURVE_ABS_H
|
[
"sjp@appmancer.com"
] |
sjp@appmancer.com
|
af105e3635b248e4b394de2ee69316651a81c4dc
|
c776476e9d06b3779d744641e758ac3a2c15cddc
|
/examples/litmus/c/run-scripts/tmp_1/IRIW+poacquireacquire+fencembonceonce+OnceRelease.c.cbmc_out.cpp
|
dc9af5dc7ac78a980af4f6db92b55c9d9a32b3d8
|
[] |
no_license
|
ashutosh0gupta/llvm_bmc
|
aaac7961c723ba6f7ffd77a39559e0e52432eade
|
0287c4fb180244e6b3c599a9902507f05c8a7234
|
refs/heads/master
| 2023-08-02T17:14:06.178723
| 2023-07-31T10:46:53
| 2023-07-31T10:46:53
| 143,100,825
| 3
| 4
| null | 2023-05-25T05:50:55
| 2018-08-01T03:47:00
|
C++
|
UTF-8
|
C++
| false
| false
| 53,442
|
cpp
|
// 0:vars:2
// 5:atom_3_X2_0:1
// 2:atom_1_X0_1:1
// 3:atom_1_X2_0:1
// 4:atom_3_X0_1:1
// 6:thr0:1
// 7:thr1:1
// 8:thr2:1
// 9:thr3:1
#define ADDRSIZE 10
#define NPROC 5
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
int r0= 0;
char creg_r0;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
int r6= 0;
char creg_r6;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
int r10= 0;
char creg_r10;
int r11= 0;
char creg_r11;
int r12= 0;
char creg_r12;
int r13= 0;
char creg_r13;
int r14= 0;
char creg_r14;
int r15= 0;
char creg_r15;
int r16= 0;
char creg_r16;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
buff(0,8) = 0;
pw(0,8) = 0;
cr(0,8) = 0;
iw(0,8) = 0;
cw(0,8) = 0;
cx(0,8) = 0;
is(0,8) = 0;
cs(0,8) = 0;
crmax(0,8) = 0;
buff(0,9) = 0;
pw(0,9) = 0;
cr(0,9) = 0;
iw(0,9) = 0;
cw(0,9) = 0;
cx(0,9) = 0;
is(0,9) = 0;
cs(0,9) = 0;
crmax(0,9) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
buff(1,8) = 0;
pw(1,8) = 0;
cr(1,8) = 0;
iw(1,8) = 0;
cw(1,8) = 0;
cx(1,8) = 0;
is(1,8) = 0;
cs(1,8) = 0;
crmax(1,8) = 0;
buff(1,9) = 0;
pw(1,9) = 0;
cr(1,9) = 0;
iw(1,9) = 0;
cw(1,9) = 0;
cx(1,9) = 0;
is(1,9) = 0;
cs(1,9) = 0;
crmax(1,9) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
buff(2,8) = 0;
pw(2,8) = 0;
cr(2,8) = 0;
iw(2,8) = 0;
cw(2,8) = 0;
cx(2,8) = 0;
is(2,8) = 0;
cs(2,8) = 0;
crmax(2,8) = 0;
buff(2,9) = 0;
pw(2,9) = 0;
cr(2,9) = 0;
iw(2,9) = 0;
cw(2,9) = 0;
cx(2,9) = 0;
is(2,9) = 0;
cs(2,9) = 0;
crmax(2,9) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
buff(3,8) = 0;
pw(3,8) = 0;
cr(3,8) = 0;
iw(3,8) = 0;
cw(3,8) = 0;
cx(3,8) = 0;
is(3,8) = 0;
cs(3,8) = 0;
crmax(3,8) = 0;
buff(3,9) = 0;
pw(3,9) = 0;
cr(3,9) = 0;
iw(3,9) = 0;
cw(3,9) = 0;
cx(3,9) = 0;
is(3,9) = 0;
cs(3,9) = 0;
crmax(3,9) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
buff(4,0) = 0;
pw(4,0) = 0;
cr(4,0) = 0;
iw(4,0) = 0;
cw(4,0) = 0;
cx(4,0) = 0;
is(4,0) = 0;
cs(4,0) = 0;
crmax(4,0) = 0;
buff(4,1) = 0;
pw(4,1) = 0;
cr(4,1) = 0;
iw(4,1) = 0;
cw(4,1) = 0;
cx(4,1) = 0;
is(4,1) = 0;
cs(4,1) = 0;
crmax(4,1) = 0;
buff(4,2) = 0;
pw(4,2) = 0;
cr(4,2) = 0;
iw(4,2) = 0;
cw(4,2) = 0;
cx(4,2) = 0;
is(4,2) = 0;
cs(4,2) = 0;
crmax(4,2) = 0;
buff(4,3) = 0;
pw(4,3) = 0;
cr(4,3) = 0;
iw(4,3) = 0;
cw(4,3) = 0;
cx(4,3) = 0;
is(4,3) = 0;
cs(4,3) = 0;
crmax(4,3) = 0;
buff(4,4) = 0;
pw(4,4) = 0;
cr(4,4) = 0;
iw(4,4) = 0;
cw(4,4) = 0;
cx(4,4) = 0;
is(4,4) = 0;
cs(4,4) = 0;
crmax(4,4) = 0;
buff(4,5) = 0;
pw(4,5) = 0;
cr(4,5) = 0;
iw(4,5) = 0;
cw(4,5) = 0;
cx(4,5) = 0;
is(4,5) = 0;
cs(4,5) = 0;
crmax(4,5) = 0;
buff(4,6) = 0;
pw(4,6) = 0;
cr(4,6) = 0;
iw(4,6) = 0;
cw(4,6) = 0;
cx(4,6) = 0;
is(4,6) = 0;
cs(4,6) = 0;
crmax(4,6) = 0;
buff(4,7) = 0;
pw(4,7) = 0;
cr(4,7) = 0;
iw(4,7) = 0;
cw(4,7) = 0;
cx(4,7) = 0;
is(4,7) = 0;
cs(4,7) = 0;
crmax(4,7) = 0;
buff(4,8) = 0;
pw(4,8) = 0;
cr(4,8) = 0;
iw(4,8) = 0;
cw(4,8) = 0;
cx(4,8) = 0;
is(4,8) = 0;
cs(4,8) = 0;
crmax(4,8) = 0;
buff(4,9) = 0;
pw(4,9) = 0;
cr(4,9) = 0;
iw(4,9) = 0;
cw(4,9) = 0;
cx(4,9) = 0;
is(4,9) = 0;
cs(4,9) = 0;
crmax(4,9) = 0;
cl[4] = 0;
cdy[4] = 0;
cds[4] = 0;
cdl[4] = 0;
cisb[4] = 0;
caddr[4] = 0;
cctrl[4] = 0;
cstart[4] = get_rng(0,NCONTEXT-1);
creturn[4] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(5+0,0) = 0;
mem(2+0,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
mem(8+0,0) = 0;
mem(9+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
co(8,0) = 0;
delta(8,0) = -1;
co(9,0) = 0;
delta(9,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !39, metadata !DIExpression()), !dbg !45
// br label %label_1, !dbg !46
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !44), !dbg !47
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !40, metadata !DIExpression()), !dbg !48
// call void @llvm.dbg.value(metadata i64 1, metadata !43, metadata !DIExpression()), !dbg !48
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !49
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// ret i8* null, !dbg !50
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !53, metadata !DIExpression()), !dbg !72
// br label %label_2, !dbg !60
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !71), !dbg !74
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !56, metadata !DIExpression()), !dbg !75
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) acquire, align 8, !dbg !63
// LD: Guess
// : Acquire
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
ASSUME(cr(2,0) >= cx(2,0));
ASSUME(cr(2,0) >= cs(2,0+0));
ASSUME(cr(2,0) >= cs(2,0+1));
ASSUME(cr(2,0) >= cs(2,5+0));
ASSUME(cr(2,0) >= cs(2,2+0));
ASSUME(cr(2,0) >= cs(2,3+0));
ASSUME(cr(2,0) >= cs(2,4+0));
ASSUME(cr(2,0) >= cs(2,6+0));
ASSUME(cr(2,0) >= cs(2,7+0));
ASSUME(cr(2,0) >= cs(2,8+0));
ASSUME(cr(2,0) >= cs(2,9+0));
// Update
creg_r0 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r0 = buff(2,0);
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r0 = mem(0,cr(2,0));
}
cl[2] = max(cl[2],cr(2,0));
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !58, metadata !DIExpression()), !dbg !75
// %conv = trunc i64 %0 to i32, !dbg !64
// call void @llvm.dbg.value(metadata i32 %conv, metadata !54, metadata !DIExpression()), !dbg !72
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !60, metadata !DIExpression()), !dbg !78
// %1 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) acquire, align 8, !dbg !66
// LD: Guess
// : Acquire
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
ASSUME(cr(2,0+1*1) >= cx(2,0+1*1));
ASSUME(cr(2,0+1*1) >= cs(2,0+0));
ASSUME(cr(2,0+1*1) >= cs(2,0+1));
ASSUME(cr(2,0+1*1) >= cs(2,5+0));
ASSUME(cr(2,0+1*1) >= cs(2,2+0));
ASSUME(cr(2,0+1*1) >= cs(2,3+0));
ASSUME(cr(2,0+1*1) >= cs(2,4+0));
ASSUME(cr(2,0+1*1) >= cs(2,6+0));
ASSUME(cr(2,0+1*1) >= cs(2,7+0));
ASSUME(cr(2,0+1*1) >= cs(2,8+0));
ASSUME(cr(2,0+1*1) >= cs(2,9+0));
// Update
creg_r1 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r1 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r1 = mem(0+1*1,cr(2,0+1*1));
}
cl[2] = max(cl[2],cr(2,0+1*1));
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %1, metadata !62, metadata !DIExpression()), !dbg !78
// %conv4 = trunc i64 %1 to i32, !dbg !67
// call void @llvm.dbg.value(metadata i32 %conv4, metadata !59, metadata !DIExpression()), !dbg !72
// %cmp = icmp eq i32 %conv, 1, !dbg !68
// %conv5 = zext i1 %cmp to i32, !dbg !68
// call void @llvm.dbg.value(metadata i32 %conv5, metadata !63, metadata !DIExpression()), !dbg !72
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !64, metadata !DIExpression()), !dbg !82
// %2 = zext i32 %conv5 to i64
// call void @llvm.dbg.value(metadata i64 %2, metadata !66, metadata !DIExpression()), !dbg !82
// store atomic i64 %2, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !70
// ST: Guess
iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,2);
cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,2)] == 2);
ASSUME(active[cw(2,2)] == 2);
ASSUME(sforbid(2,cw(2,2))== 0);
ASSUME(iw(2,2) >= max(creg_r0,0));
ASSUME(iw(2,2) >= 0);
ASSUME(cw(2,2) >= iw(2,2));
ASSUME(cw(2,2) >= old_cw);
ASSUME(cw(2,2) >= cr(2,2));
ASSUME(cw(2,2) >= cl[2]);
ASSUME(cw(2,2) >= cisb[2]);
ASSUME(cw(2,2) >= cdy[2]);
ASSUME(cw(2,2) >= cdl[2]);
ASSUME(cw(2,2) >= cds[2]);
ASSUME(cw(2,2) >= cctrl[2]);
ASSUME(cw(2,2) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,2) = (r0==1);
mem(2,cw(2,2)) = (r0==1);
co(2,cw(2,2))+=1;
delta(2,cw(2,2)) = -1;
ASSUME(creturn[2] >= cw(2,2));
// %cmp7 = icmp eq i32 %conv4, 0, !dbg !71
// %conv8 = zext i1 %cmp7 to i32, !dbg !71
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !67, metadata !DIExpression()), !dbg !72
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !68, metadata !DIExpression()), !dbg !85
// %3 = zext i32 %conv8 to i64
// call void @llvm.dbg.value(metadata i64 %3, metadata !70, metadata !DIExpression()), !dbg !85
// store atomic i64 %3, i64* @atom_1_X2_0 seq_cst, align 8, !dbg !73
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r1,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r1==0);
mem(3,cw(2,3)) = (r1==0);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// ret i8* null, !dbg !74
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !90, metadata !DIExpression()), !dbg !95
// br label %label_3, !dbg !46
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !94), !dbg !97
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !91, metadata !DIExpression()), !dbg !98
// call void @llvm.dbg.value(metadata i64 1, metadata !93, metadata !DIExpression()), !dbg !98
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !49
// ST: Guess
// : Release
iw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,0+1*1);
cw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,0+1*1)] == 3);
ASSUME(active[cw(3,0+1*1)] == 3);
ASSUME(sforbid(0+1*1,cw(3,0+1*1))== 0);
ASSUME(iw(3,0+1*1) >= 0);
ASSUME(iw(3,0+1*1) >= 0);
ASSUME(cw(3,0+1*1) >= iw(3,0+1*1));
ASSUME(cw(3,0+1*1) >= old_cw);
ASSUME(cw(3,0+1*1) >= cr(3,0+1*1));
ASSUME(cw(3,0+1*1) >= cl[3]);
ASSUME(cw(3,0+1*1) >= cisb[3]);
ASSUME(cw(3,0+1*1) >= cdy[3]);
ASSUME(cw(3,0+1*1) >= cdl[3]);
ASSUME(cw(3,0+1*1) >= cds[3]);
ASSUME(cw(3,0+1*1) >= cctrl[3]);
ASSUME(cw(3,0+1*1) >= caddr[3]);
ASSUME(cw(3,0+1*1) >= cr(3,0+0));
ASSUME(cw(3,0+1*1) >= cr(3,0+1));
ASSUME(cw(3,0+1*1) >= cr(3,5+0));
ASSUME(cw(3,0+1*1) >= cr(3,2+0));
ASSUME(cw(3,0+1*1) >= cr(3,3+0));
ASSUME(cw(3,0+1*1) >= cr(3,4+0));
ASSUME(cw(3,0+1*1) >= cr(3,6+0));
ASSUME(cw(3,0+1*1) >= cr(3,7+0));
ASSUME(cw(3,0+1*1) >= cr(3,8+0));
ASSUME(cw(3,0+1*1) >= cr(3,9+0));
ASSUME(cw(3,0+1*1) >= cw(3,0+0));
ASSUME(cw(3,0+1*1) >= cw(3,0+1));
ASSUME(cw(3,0+1*1) >= cw(3,5+0));
ASSUME(cw(3,0+1*1) >= cw(3,2+0));
ASSUME(cw(3,0+1*1) >= cw(3,3+0));
ASSUME(cw(3,0+1*1) >= cw(3,4+0));
ASSUME(cw(3,0+1*1) >= cw(3,6+0));
ASSUME(cw(3,0+1*1) >= cw(3,7+0));
ASSUME(cw(3,0+1*1) >= cw(3,8+0));
ASSUME(cw(3,0+1*1) >= cw(3,9+0));
// Update
caddr[3] = max(caddr[3],0);
buff(3,0+1*1) = 1;
mem(0+1*1,cw(3,0+1*1)) = 1;
co(0+1*1,cw(3,0+1*1))+=1;
delta(0+1*1,cw(3,0+1*1)) = -1;
is(3,0+1*1) = iw(3,0+1*1);
cs(3,0+1*1) = cw(3,0+1*1);
ASSUME(creturn[3] >= cw(3,0+1*1));
// ret i8* null, !dbg !50
ret_thread_3 = (- 1);
// Dumping thread 4
int ret_thread_4 = 0;
cdy[4] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[4] >= cstart[4]);
T4BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !103, metadata !DIExpression()), !dbg !121
// br label %label_4, !dbg !60
goto T4BLOCK1;
T4BLOCK1:
// call void @llvm.dbg.label(metadata !120), !dbg !123
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !105, metadata !DIExpression()), !dbg !124
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !63
// LD: Guess
old_cr = cr(4,0+1*1);
cr(4,0+1*1) = get_rng(0,NCONTEXT-1);// 4 ASSIGN LDCOM
// Check
ASSUME(active[cr(4,0+1*1)] == 4);
ASSUME(cr(4,0+1*1) >= iw(4,0+1*1));
ASSUME(cr(4,0+1*1) >= 0);
ASSUME(cr(4,0+1*1) >= cdy[4]);
ASSUME(cr(4,0+1*1) >= cisb[4]);
ASSUME(cr(4,0+1*1) >= cdl[4]);
ASSUME(cr(4,0+1*1) >= cl[4]);
// Update
creg_r2 = cr(4,0+1*1);
crmax(4,0+1*1) = max(crmax(4,0+1*1),cr(4,0+1*1));
caddr[4] = max(caddr[4],0);
if(cr(4,0+1*1) < cw(4,0+1*1)) {
r2 = buff(4,0+1*1);
} else {
if(pw(4,0+1*1) != co(0+1*1,cr(4,0+1*1))) {
ASSUME(cr(4,0+1*1) >= old_cr);
}
pw(4,0+1*1) = co(0+1*1,cr(4,0+1*1));
r2 = mem(0+1*1,cr(4,0+1*1));
}
ASSUME(creturn[4] >= cr(4,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !107, metadata !DIExpression()), !dbg !124
// %conv = trunc i64 %0 to i32, !dbg !64
// call void @llvm.dbg.value(metadata i32 %conv, metadata !104, metadata !DIExpression()), !dbg !121
// call void (...) @dmbsy(), !dbg !65
// dumbsy: Guess
old_cdy = cdy[4];
cdy[4] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[4] >= old_cdy);
ASSUME(cdy[4] >= cisb[4]);
ASSUME(cdy[4] >= cdl[4]);
ASSUME(cdy[4] >= cds[4]);
ASSUME(cdy[4] >= cctrl[4]);
ASSUME(cdy[4] >= cw(4,0+0));
ASSUME(cdy[4] >= cw(4,0+1));
ASSUME(cdy[4] >= cw(4,5+0));
ASSUME(cdy[4] >= cw(4,2+0));
ASSUME(cdy[4] >= cw(4,3+0));
ASSUME(cdy[4] >= cw(4,4+0));
ASSUME(cdy[4] >= cw(4,6+0));
ASSUME(cdy[4] >= cw(4,7+0));
ASSUME(cdy[4] >= cw(4,8+0));
ASSUME(cdy[4] >= cw(4,9+0));
ASSUME(cdy[4] >= cr(4,0+0));
ASSUME(cdy[4] >= cr(4,0+1));
ASSUME(cdy[4] >= cr(4,5+0));
ASSUME(cdy[4] >= cr(4,2+0));
ASSUME(cdy[4] >= cr(4,3+0));
ASSUME(cdy[4] >= cr(4,4+0));
ASSUME(cdy[4] >= cr(4,6+0));
ASSUME(cdy[4] >= cr(4,7+0));
ASSUME(cdy[4] >= cr(4,8+0));
ASSUME(cdy[4] >= cr(4,9+0));
ASSUME(creturn[4] >= cdy[4]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !109, metadata !DIExpression()), !dbg !128
// %1 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !67
// LD: Guess
old_cr = cr(4,0);
cr(4,0) = get_rng(0,NCONTEXT-1);// 4 ASSIGN LDCOM
// Check
ASSUME(active[cr(4,0)] == 4);
ASSUME(cr(4,0) >= iw(4,0));
ASSUME(cr(4,0) >= 0);
ASSUME(cr(4,0) >= cdy[4]);
ASSUME(cr(4,0) >= cisb[4]);
ASSUME(cr(4,0) >= cdl[4]);
ASSUME(cr(4,0) >= cl[4]);
// Update
creg_r3 = cr(4,0);
crmax(4,0) = max(crmax(4,0),cr(4,0));
caddr[4] = max(caddr[4],0);
if(cr(4,0) < cw(4,0)) {
r3 = buff(4,0);
} else {
if(pw(4,0) != co(0,cr(4,0))) {
ASSUME(cr(4,0) >= old_cr);
}
pw(4,0) = co(0,cr(4,0));
r3 = mem(0,cr(4,0));
}
ASSUME(creturn[4] >= cr(4,0));
// call void @llvm.dbg.value(metadata i64 %1, metadata !111, metadata !DIExpression()), !dbg !128
// %conv4 = trunc i64 %1 to i32, !dbg !68
// call void @llvm.dbg.value(metadata i32 %conv4, metadata !108, metadata !DIExpression()), !dbg !121
// %cmp = icmp eq i32 %conv, 1, !dbg !69
// %conv5 = zext i1 %cmp to i32, !dbg !69
// call void @llvm.dbg.value(metadata i32 %conv5, metadata !112, metadata !DIExpression()), !dbg !121
// call void @llvm.dbg.value(metadata i64* @atom_3_X0_1, metadata !113, metadata !DIExpression()), !dbg !132
// %2 = zext i32 %conv5 to i64
// call void @llvm.dbg.value(metadata i64 %2, metadata !115, metadata !DIExpression()), !dbg !132
// store atomic i64 %2, i64* @atom_3_X0_1 seq_cst, align 8, !dbg !71
// ST: Guess
iw(4,4) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STIW
old_cw = cw(4,4);
cw(4,4) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STCOM
// Check
ASSUME(active[iw(4,4)] == 4);
ASSUME(active[cw(4,4)] == 4);
ASSUME(sforbid(4,cw(4,4))== 0);
ASSUME(iw(4,4) >= max(creg_r2,0));
ASSUME(iw(4,4) >= 0);
ASSUME(cw(4,4) >= iw(4,4));
ASSUME(cw(4,4) >= old_cw);
ASSUME(cw(4,4) >= cr(4,4));
ASSUME(cw(4,4) >= cl[4]);
ASSUME(cw(4,4) >= cisb[4]);
ASSUME(cw(4,4) >= cdy[4]);
ASSUME(cw(4,4) >= cdl[4]);
ASSUME(cw(4,4) >= cds[4]);
ASSUME(cw(4,4) >= cctrl[4]);
ASSUME(cw(4,4) >= caddr[4]);
// Update
caddr[4] = max(caddr[4],0);
buff(4,4) = (r2==1);
mem(4,cw(4,4)) = (r2==1);
co(4,cw(4,4))+=1;
delta(4,cw(4,4)) = -1;
ASSUME(creturn[4] >= cw(4,4));
// %cmp7 = icmp eq i32 %conv4, 0, !dbg !72
// %conv8 = zext i1 %cmp7 to i32, !dbg !72
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !116, metadata !DIExpression()), !dbg !121
// call void @llvm.dbg.value(metadata i64* @atom_3_X2_0, metadata !117, metadata !DIExpression()), !dbg !135
// %3 = zext i32 %conv8 to i64
// call void @llvm.dbg.value(metadata i64 %3, metadata !119, metadata !DIExpression()), !dbg !135
// store atomic i64 %3, i64* @atom_3_X2_0 seq_cst, align 8, !dbg !74
// ST: Guess
iw(4,5) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STIW
old_cw = cw(4,5);
cw(4,5) = get_rng(0,NCONTEXT-1);// 4 ASSIGN STCOM
// Check
ASSUME(active[iw(4,5)] == 4);
ASSUME(active[cw(4,5)] == 4);
ASSUME(sforbid(5,cw(4,5))== 0);
ASSUME(iw(4,5) >= max(creg_r3,0));
ASSUME(iw(4,5) >= 0);
ASSUME(cw(4,5) >= iw(4,5));
ASSUME(cw(4,5) >= old_cw);
ASSUME(cw(4,5) >= cr(4,5));
ASSUME(cw(4,5) >= cl[4]);
ASSUME(cw(4,5) >= cisb[4]);
ASSUME(cw(4,5) >= cdy[4]);
ASSUME(cw(4,5) >= cdl[4]);
ASSUME(cw(4,5) >= cds[4]);
ASSUME(cw(4,5) >= cctrl[4]);
ASSUME(cw(4,5) >= caddr[4]);
// Update
caddr[4] = max(caddr[4],0);
buff(4,5) = (r3==0);
mem(5,cw(4,5)) = (r3==0);
co(5,cw(4,5))+=1;
delta(5,cw(4,5)) = -1;
ASSUME(creturn[4] >= cw(4,5));
// ret i8* null, !dbg !75
ret_thread_4 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// %thr3 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !145, metadata !DIExpression()), !dbg !191
// call void @llvm.dbg.value(metadata i8** %argv, metadata !146, metadata !DIExpression()), !dbg !191
// %0 = bitcast i64* %thr0 to i8*, !dbg !91
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !91
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !147, metadata !DIExpression()), !dbg !193
// %1 = bitcast i64* %thr1 to i8*, !dbg !93
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !93
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !151, metadata !DIExpression()), !dbg !195
// %2 = bitcast i64* %thr2 to i8*, !dbg !95
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !95
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !152, metadata !DIExpression()), !dbg !197
// %3 = bitcast i64* %thr3 to i8*, !dbg !97
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %3) #7, !dbg !97
// call void @llvm.dbg.declare(metadata i64* %thr3, metadata !153, metadata !DIExpression()), !dbg !199
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !154, metadata !DIExpression()), !dbg !200
// call void @llvm.dbg.value(metadata i64 0, metadata !156, metadata !DIExpression()), !dbg !200
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !100
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !157, metadata !DIExpression()), !dbg !202
// call void @llvm.dbg.value(metadata i64 0, metadata !159, metadata !DIExpression()), !dbg !202
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !102
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !160, metadata !DIExpression()), !dbg !204
// call void @llvm.dbg.value(metadata i64 0, metadata !162, metadata !DIExpression()), !dbg !204
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !104
// ST: Guess
iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,2);
cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,2)] == 0);
ASSUME(active[cw(0,2)] == 0);
ASSUME(sforbid(2,cw(0,2))== 0);
ASSUME(iw(0,2) >= 0);
ASSUME(iw(0,2) >= 0);
ASSUME(cw(0,2) >= iw(0,2));
ASSUME(cw(0,2) >= old_cw);
ASSUME(cw(0,2) >= cr(0,2));
ASSUME(cw(0,2) >= cl[0]);
ASSUME(cw(0,2) >= cisb[0]);
ASSUME(cw(0,2) >= cdy[0]);
ASSUME(cw(0,2) >= cdl[0]);
ASSUME(cw(0,2) >= cds[0]);
ASSUME(cw(0,2) >= cctrl[0]);
ASSUME(cw(0,2) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,2) = 0;
mem(2,cw(0,2)) = 0;
co(2,cw(0,2))+=1;
delta(2,cw(0,2)) = -1;
ASSUME(creturn[0] >= cw(0,2));
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !163, metadata !DIExpression()), !dbg !206
// call void @llvm.dbg.value(metadata i64 0, metadata !165, metadata !DIExpression()), !dbg !206
// store atomic i64 0, i64* @atom_1_X2_0 monotonic, align 8, !dbg !106
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_3_X0_1, metadata !166, metadata !DIExpression()), !dbg !208
// call void @llvm.dbg.value(metadata i64 0, metadata !168, metadata !DIExpression()), !dbg !208
// store atomic i64 0, i64* @atom_3_X0_1 monotonic, align 8, !dbg !108
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// call void @llvm.dbg.value(metadata i64* @atom_3_X2_0, metadata !169, metadata !DIExpression()), !dbg !210
// call void @llvm.dbg.value(metadata i64 0, metadata !171, metadata !DIExpression()), !dbg !210
// store atomic i64 0, i64* @atom_3_X2_0 monotonic, align 8, !dbg !110
// ST: Guess
iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,5);
cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,5)] == 0);
ASSUME(active[cw(0,5)] == 0);
ASSUME(sforbid(5,cw(0,5))== 0);
ASSUME(iw(0,5) >= 0);
ASSUME(iw(0,5) >= 0);
ASSUME(cw(0,5) >= iw(0,5));
ASSUME(cw(0,5) >= old_cw);
ASSUME(cw(0,5) >= cr(0,5));
ASSUME(cw(0,5) >= cl[0]);
ASSUME(cw(0,5) >= cisb[0]);
ASSUME(cw(0,5) >= cdy[0]);
ASSUME(cw(0,5) >= cdl[0]);
ASSUME(cw(0,5) >= cds[0]);
ASSUME(cw(0,5) >= cctrl[0]);
ASSUME(cw(0,5) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,5) = 0;
mem(5,cw(0,5)) = 0;
co(5,cw(0,5))+=1;
delta(5,cw(0,5)) = -1;
ASSUME(creturn[0] >= cw(0,5));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !111
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call11 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !112
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call12 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !113
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %call13 = call i32 @pthread_create(i64* noundef %thr3, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t3, i8* noundef null) #7, !dbg !114
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[4] >= cdy[0]);
// %4 = load i64, i64* %thr0, align 8, !dbg !115, !tbaa !116
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r5 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r5 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r5 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// %call14 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !120
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %5 = load i64, i64* %thr1, align 8, !dbg !121, !tbaa !116
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r6 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r6 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r6 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call15 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !122
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %6 = load i64, i64* %thr2, align 8, !dbg !123, !tbaa !116
// LD: Guess
old_cr = cr(0,8);
cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,8)] == 0);
ASSUME(cr(0,8) >= iw(0,8));
ASSUME(cr(0,8) >= 0);
ASSUME(cr(0,8) >= cdy[0]);
ASSUME(cr(0,8) >= cisb[0]);
ASSUME(cr(0,8) >= cdl[0]);
ASSUME(cr(0,8) >= cl[0]);
// Update
creg_r7 = cr(0,8);
crmax(0,8) = max(crmax(0,8),cr(0,8));
caddr[0] = max(caddr[0],0);
if(cr(0,8) < cw(0,8)) {
r7 = buff(0,8);
} else {
if(pw(0,8) != co(8,cr(0,8))) {
ASSUME(cr(0,8) >= old_cr);
}
pw(0,8) = co(8,cr(0,8));
r7 = mem(8,cr(0,8));
}
ASSUME(creturn[0] >= cr(0,8));
// %call16 = call i32 @pthread_join(i64 noundef %6, i8** noundef null), !dbg !124
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// %7 = load i64, i64* %thr3, align 8, !dbg !125, !tbaa !116
// LD: Guess
old_cr = cr(0,9);
cr(0,9) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,9)] == 0);
ASSUME(cr(0,9) >= iw(0,9));
ASSUME(cr(0,9) >= 0);
ASSUME(cr(0,9) >= cdy[0]);
ASSUME(cr(0,9) >= cisb[0]);
ASSUME(cr(0,9) >= cdl[0]);
ASSUME(cr(0,9) >= cl[0]);
// Update
creg_r8 = cr(0,9);
crmax(0,9) = max(crmax(0,9),cr(0,9));
caddr[0] = max(caddr[0],0);
if(cr(0,9) < cw(0,9)) {
r8 = buff(0,9);
} else {
if(pw(0,9) != co(9,cr(0,9))) {
ASSUME(cr(0,9) >= old_cr);
}
pw(0,9) = co(9,cr(0,9));
r8 = mem(9,cr(0,9));
}
ASSUME(creturn[0] >= cr(0,9));
// %call17 = call i32 @pthread_join(i64 noundef %7, i8** noundef null), !dbg !126
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[4]);
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !173, metadata !DIExpression()), !dbg !228
// %8 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !128
// LD: Guess
old_cr = cr(0,2);
cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,2)] == 0);
ASSUME(cr(0,2) >= iw(0,2));
ASSUME(cr(0,2) >= 0);
ASSUME(cr(0,2) >= cdy[0]);
ASSUME(cr(0,2) >= cisb[0]);
ASSUME(cr(0,2) >= cdl[0]);
ASSUME(cr(0,2) >= cl[0]);
// Update
creg_r9 = cr(0,2);
crmax(0,2) = max(crmax(0,2),cr(0,2));
caddr[0] = max(caddr[0],0);
if(cr(0,2) < cw(0,2)) {
r9 = buff(0,2);
} else {
if(pw(0,2) != co(2,cr(0,2))) {
ASSUME(cr(0,2) >= old_cr);
}
pw(0,2) = co(2,cr(0,2));
r9 = mem(2,cr(0,2));
}
ASSUME(creturn[0] >= cr(0,2));
// call void @llvm.dbg.value(metadata i64 %8, metadata !175, metadata !DIExpression()), !dbg !228
// %conv = trunc i64 %8 to i32, !dbg !129
// call void @llvm.dbg.value(metadata i32 %conv, metadata !172, metadata !DIExpression()), !dbg !191
// call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !177, metadata !DIExpression()), !dbg !231
// %9 = load atomic i64, i64* @atom_1_X2_0 seq_cst, align 8, !dbg !131
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r10 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r10 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r10 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %9, metadata !179, metadata !DIExpression()), !dbg !231
// %conv21 = trunc i64 %9 to i32, !dbg !132
// call void @llvm.dbg.value(metadata i32 %conv21, metadata !176, metadata !DIExpression()), !dbg !191
// call void @llvm.dbg.value(metadata i64* @atom_3_X0_1, metadata !181, metadata !DIExpression()), !dbg !234
// %10 = load atomic i64, i64* @atom_3_X0_1 seq_cst, align 8, !dbg !134
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r11 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r11 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r11 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %10, metadata !183, metadata !DIExpression()), !dbg !234
// %conv25 = trunc i64 %10 to i32, !dbg !135
// call void @llvm.dbg.value(metadata i32 %conv25, metadata !180, metadata !DIExpression()), !dbg !191
// call void @llvm.dbg.value(metadata i64* @atom_3_X2_0, metadata !185, metadata !DIExpression()), !dbg !237
// %11 = load atomic i64, i64* @atom_3_X2_0 seq_cst, align 8, !dbg !137
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r12 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r12 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r12 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// call void @llvm.dbg.value(metadata i64 %11, metadata !187, metadata !DIExpression()), !dbg !237
// %conv29 = trunc i64 %11 to i32, !dbg !138
// call void @llvm.dbg.value(metadata i32 %conv29, metadata !184, metadata !DIExpression()), !dbg !191
// %and = and i32 %conv25, %conv29, !dbg !139
creg_r13 = max(creg_r11,creg_r12);
ASSUME(active[creg_r13] == 0);
r13 = r11 & r12;
// call void @llvm.dbg.value(metadata i32 %and, metadata !188, metadata !DIExpression()), !dbg !191
// %and30 = and i32 %conv21, %and, !dbg !140
creg_r14 = max(creg_r10,creg_r13);
ASSUME(active[creg_r14] == 0);
r14 = r10 & r13;
// call void @llvm.dbg.value(metadata i32 %and30, metadata !189, metadata !DIExpression()), !dbg !191
// %and31 = and i32 %conv, %and30, !dbg !141
creg_r15 = max(creg_r9,creg_r14);
ASSUME(active[creg_r15] == 0);
r15 = r9 & r14;
// call void @llvm.dbg.value(metadata i32 %and31, metadata !190, metadata !DIExpression()), !dbg !191
// %cmp = icmp eq i32 %and31, 1, !dbg !142
// br i1 %cmp, label %if.then, label %if.end, !dbg !144
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r15);
ASSUME(cctrl[0] >= 0);
if((r15==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([134 x i8], [134 x i8]* @.str.1, i64 0, i64 0), i32 noundef 85, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !145
// unreachable, !dbg !145
r16 = 1;
T0BLOCK2:
// %12 = bitcast i64* %thr3 to i8*, !dbg !148
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %12) #7, !dbg !148
// %13 = bitcast i64* %thr2 to i8*, !dbg !148
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %13) #7, !dbg !148
// %14 = bitcast i64* %thr1 to i8*, !dbg !148
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %14) #7, !dbg !148
// %15 = bitcast i64* %thr0 to i8*, !dbg !148
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %15) #7, !dbg !148
// ret i32 0, !dbg !149
ret_thread_0 = 0;
ASSERT(r16== 0);
}
|
[
"tuan-phong.ngo@it.uu.se"
] |
tuan-phong.ngo@it.uu.se
|
336c142c0ea06c3627f66d6151b9a2e8d99596a3
|
4ec6194bb6d1f8ad3e7c382dc6d98b8267a9f3e3
|
/src/storage/FCS.h
|
3f6eb530bf6248554c0aafd0dffd1e4050f362bc
|
[
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
goodwill2684/Firebase-ESP-Client
|
025c1b46cccdc51c00c67d7b8fa03bb0de22d414
|
861a08257d732093a699bee385675d73c65c3797
|
refs/heads/main
| 2023-07-02T23:12:56.464087
| 2021-08-15T10:02:15
| 2021-08-15T10:02:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,199
|
h
|
/**
* Google's Firebase Storage class, FCS.h version 1.1.3
*
* This library supports Espressif ESP8266 and ESP32
*
* Created August 15, 2021
*
* This work is a part of Firebase ESP Client library
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "FirebaseFS.h"
#ifdef ENABLE_FB_STORAGE
#ifndef FB_Storage_H
#define FB_Storage_H
#include <Arduino.h>
#include "Utils.h"
#include "session/FB_Session.h"
class FB_Storage
{
friend class Firebase_ESP_Client;
public:
struct RequestType;
FB_Storage();
~FB_Storage();
/** Upload file to the Firebase Storage data bucket.
*
* @param fbdo The pointer to Firebase Data Object.
* @param bucketID The Firebase storage bucket ID in the project.
* @param localFileName The file path includes its name to upload.
* @param storageType The enum of memory storage type e.g. mem_storage_type_flash and mem_storage_type_sd. The file systems can be changed in FirebaseFS.h.
* @param remotetFileName The file path includes its name of uploaded file in data bucket.
* @param mime The file MIME type
* .
* @return Boolean value, indicates the success of the operation.
*
* @note Use FirebaseData.downloadURL() to get the download link.
*
*/
bool upload(FirebaseData *fbdo, const char *bucketID, const char *localFileName, fb_esp_mem_storage_type storageType, const char *remotetFileName, const char *mime);
/** Upload byte array to the Firebase Storage data bucket.
*
* @param fbdo The pointer to Firebase Data Object.
* @param bucketID The Firebase storage bucket ID in the project.
* @param data The byte array of data.
* @param len The size of byte array data in bytes.
* @param remotetFileName The file path includes its name of uploaded file in data bucket.
* @param mime The file MIME type
* .
* @return Boolean value, indicates the success of the operation.
*
* @note Use FirebaseData.downloadURL() to get the download link.
*
*/
bool upload(FirebaseData *fbdo, const char *bucketID, const uint8_t *data, size_t len, const char *remoteFileName, const char *mime);
/** Download file from the Firebase Storage data bucket.
*
* @param fbdo The pointer to Firebase Data Object.
* @param bucketID The Firebase storage bucket ID in the project.
* @param remotetFileName The file path includes its name of file in the data bucket to download.
* @param localFileName The file path includes its name to save.
* @param storageType The enum of memory storage type e.g. mem_storage_type_flash and mem_storage_type_sd. The file systems can be changed in FirebaseFS.h.
*
* @return Boolean value, indicates the success of the operation.
*
*/
bool download(FirebaseData *fbdo, const char *bucketID, const char *remoteFileName, const char *localFileName, fb_esp_mem_storage_type storageType);
/** Get the meta data of file in Firebase Storage data bucket
*
* @param fbdo The pointer to Firebase Data Object.
* @param bucketID The Firebase storage bucket ID in the project.
* @param remotetFileName The file path includes its name of file in the data bucket.
*
* @return Boolean value, indicates the success of the operation.
*
* @note Use the FileMetaInfo type data to get name, bucket, contentType, size,
* generation, etag, crc32, downloadTokens properties from file.
*
*/
bool getMetadata(FirebaseData *fbdo, const char *bucketID, const char *remoteFileName);
/** Delete file from Firebase Storage data bucket
*
* @param fbdo The pointer to Firebase Data Object.
* @param bucketID The Firebase storage bucket ID in the project.
* @param remotetFileName The file path includes its name of file in the data bucket.
*
* @return Boolean value, indicates the success of the operation.
*
*/
bool deleteFile(FirebaseData *fbdo, const char *bucketID, const char *fileName);
/** List all files in the Firebase Storage data bucket.
*
* @param fbdo The pointer to Firebase Data Object.
* @param bucketID The Firebase storage bucket ID in the project.
*
* @return Boolean value, indicates the success of the operation.
*
* @note Use the FileList type data to get name and bucket properties for each item.
*
*/
bool listFiles(FirebaseData *fbdo, const char *bucketID);
private:
UtilsClass *ut = nullptr;
void begin(UtilsClass *u);
bool sendRequest(FirebaseData *fbdo, struct fb_esp_fcs_req_t *req);
void rescon(FirebaseData *fbdo, const char *host);
bool fcs_connect(FirebaseData *fbdo);
bool fcs_sendRequest(FirebaseData *fbdo, struct fb_esp_fcs_req_t *req);
bool handleResponse(FirebaseData *fbdo);
};
#endif
#endif //ENABLE
|
[
"k_suwatchai@hotmail.com"
] |
k_suwatchai@hotmail.com
|
536ce871b2b7638985d229e16b779df093ac3c2c
|
64d0ac5b23aea2dd1ec50d34ef59edd023f77326
|
/src/onePole.cpp
|
f6cdab05fdf3b75101b913b45699b8c911d4936b
|
[] |
no_license
|
Dante2/AVP
|
32fedff2a17fb127a0410872f405cd2417189ed4
|
156800f83812222f03a55fcd2704ada00784912c
|
refs/heads/master
| 2021-05-13T14:28:04.511307
| 2018-01-08T23:46:17
| 2018-01-08T23:46:17
| 116,741,603
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,314
|
cpp
|
//
// onePole.cpp
// mySketch
//
// Created by Jools on 08/01/2018.
//
#include "onePole.hpp"
// One Pole constructor ----------------------------------
// Initialise its variables
OnePole::OnePole(){
z = 0;
b = 0.99;
a = 1 - b;
}
// -----------------------------------------------------------
// One Pole Process function ---------------------------------
// This takes all the coefficients and applies the folloeing mathematical operation to them. 1 is the normalised maximum value of the process. 1 minus b gives us a very small
// number which is then multiplied by our incoming signal (the 2d vector array) and then added to b to calculate the difference between
// the vector's initial state and its changed one. It is all then multiplied by z to modify our original z signal by the newly updated z signal.
float OnePole::Process(float sig){
z = a * sig + b * z;
return z;
}
// One Pole setCoefficients function ---------------------------------
// Calculates the coefficients of a and b relative to the time domain and sample rate
// I have tried messing around with the exponent in variable b a little to see what sort of data smoothing effects I get
void OnePole::SetCoefficients(float time, int sampleRate){
b = exp(-0.5/(time * sampleRate));
a = 1.0 - b;
}
|
[
"jools@Joolss-MacBook-Pro.local"
] |
jools@Joolss-MacBook-Pro.local
|
0cc7887022472ea1ebfe252123113f63c504c82f
|
40983fab9dffef97d61730310632f96356112ad3
|
/CSC8503/CSC8503/GameTech/NetworkedGame.h
|
2293443af0159cbe177f0425a6c138a8f3add8df
|
[] |
no_license
|
tywhite123/GameTech
|
4e310d2a063519ba9f0e1f15dd75ccc6eea852c1
|
c4c3b72da0b93e667f32d806847b04b78710f367
|
refs/heads/master
| 2020-04-08T08:00:24.790502
| 2018-12-13T23:05:37
| 2018-12-13T23:05:37
| 159,160,914
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,227
|
h
|
#pragma once
#include "TutorialGame.h"
#include "../CSC8503Common/GameServer.h"
#include "PacketReceiver.h"
#include "../CSC8503Common/PlayerObject.h"
#include "../CSC8503Common/StateMachine.h"
//TODO: Somehow sort this out
struct PlayerBall
{
int playerToUpdate;
Vector3 ballForce;
Vector3 collidedAt;
};
class NetworkGame
{
public:
NetworkGame();
~NetworkGame();
virtual void UpdateServer(float dt);
void LoadLevel(string name);
void InitialiseAssets();
void InitCamera();
void InitWorld();
GameObject* AddPlayerToWorld(int objID, const Vector3& position, float radius, float inverseMass = 10.0f);
GameObject* AddWallToWorld(int objID, const Vector3& position, Vector3 dimensions, float inverseMass = 10.0f);
GameObject* AddGoalToWorld(int objID, const Vector3& position, Vector3 dimensions, float inverseMass = 10.0f);
GameObject* AddMovingToWorld(int objID, const Vector3& position, Vector3 dimensions, float inverseMass = 10.0f);
GameObject* AddRobotToWorld(int objID, const Vector3& position, Vector3 dimensions, float inverseMass = 10.0f);
GameObject* AddSpinnerToWorld(int objID, const Vector3&position, Vector3 dimensions, float inverseMass = 10.0f, float spinVal = 10.0f);
GameObject* AddFloorToWorld(int objID, const Vector3 & position, Vector3 dimensions);
protected:
GameServer* server;
StringPacketReceiver stringReceiver;
PlayerConnectedPacketReceiver playerReceiver;
ScorePacketReceiver scoreReceiver;
BallForcePacketReceiver ballForceReceiver;
ReadyPlayerPacketReceiver readyPlayerReceiver;
//Player
vector<int> playerIDs;
std::map<int, string> players;
std::map<int, int> scores;
std::map<int, bool> readyPlayers;
std::vector<GameObject*> dynamicObjects;
std::vector<BallData*> ballData;
std::map<int, PlayerObject*> playerBalls;
std::map<int, bool> finishedLevel;
GameWorld* world;
PhysicsSystem* physics;
GameTechRenderer* renderer;
bool newPlayer = false;
string level;
Vector3 startingPos;
int sendUpdate;
vector<StateMachine*> stateMachines;
int stateID;
NCL::OGLMesh* cubeMesh = nullptr;
NCL::OGLMesh* sphereMesh = nullptr;
NCL::OGLTexture* basicTex = nullptr;
NCL::OGLShader* basicShader = nullptr;
Level* lvl;
bool finished;
};
|
[
"tywhitehead@hotmail.co.uk"
] |
tywhitehead@hotmail.co.uk
|
cdd25edf0503dbc54f87f59ab27386a80472a9c7
|
abed321ee597cede0e1585a7f2fdbd887a50f020
|
/realsense_ros_object/test/object_test.cpp
|
8951de15983cb793463ce16252642d6c7a961325
|
[
"Apache-2.0"
] |
permissive
|
Hadisalman/realsense_samples_ros
|
fa2efa4ac6e50d900e58ac1dc9f339938155141b
|
82c53df9413b5a6d859e65c7fd3d8736086f169e
|
refs/heads/kinetic-devel
| 2021-01-18T19:05:52.914213
| 2017-08-17T16:39:34
| 2017-08-17T16:39:34
| 100,526,891
| 1
| 0
| null | 2017-08-16T19:51:02
| 2017-08-16T19:51:01
| null |
UTF-8
|
C++
| false
| false
| 2,344
|
cpp
|
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved
#include <gtest/gtest.h>
#include <ros/ros.h>
#include "realsense_ros_object/ObjectsInBoxes.h"
#include <image_transport/image_transport.h>
bool objects_in_boxes_recieved = false;
bool camera_info_recieved = false;
int image_width = 0;
int image_height = 0;
realsense_ros_object::ObjectsInBoxes last_objs;
TEST(RealsenseTests, testObj)
{
EXPECT_TRUE(camera_info_recieved);
EXPECT_TRUE(objects_in_boxes_recieved);
if (!objects_in_boxes_recieved) return;
for(auto objs : last_objs.objects_vector)
{
EXPECT_GT(objs.object.object_name.length(), 1);
EXPECT_GT(objs.object_bbox.width, 0);
EXPECT_GT(objs.object_bbox.height, 0);
if(objs.object_bbox.height > objs.object_bbox.width)
{
if(objs.location.vert_margin != 0 || objs.location.horiz_margin != 0)
{
EXPECT_GT(objs.location.vert_margin, objs.location.horiz_margin);
}
}
else if (objs.object_bbox.height < objs.object_bbox.width)
{
if(objs.location.vert_margin != 0 || objs.location.horiz_margin != 0)
{
EXPECT_LT(objs.location.vert_margin, objs.location.horiz_margin);
}
}
}
}
void localized_tracked_objects_callback(
const realsense_ros_object::ObjectsInBoxes::ConstPtr& msg)
{
objects_in_boxes_recieved = true;
last_objs = *msg;
}
void color_camera_info_callback(const sensor_msgs::CameraInfo::ConstPtr & camera_info)
{
camera_info_recieved = true;
image_width = camera_info->width;
image_height = camera_info->height;
}
int main(int argc, char **argv) try
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "utest");
ros::NodeHandle nh;
ROS_INFO_STREAM("RealSense OBJECT test - Initializing Tests...");
ros::Subscriber sub_cam_pose = nh.subscribe("camera/color/camera_info", 10, &color_camera_info_callback);
ros::Subscriber sub_reloc_pose = nh.subscribe("realsense/localized_tracked_objects", 10, &localized_tracked_objects_callback);
ros::Duration duration;
duration.sec = 10;
duration.sleep();
ros::spinOnce();
ROS_INFO_STREAM("RealSense OBJECT test - Running Tests...");
return RUN_ALL_TESTS();
}
catch (...) {} // catch the "testing::internal::<unnamed>::ClassUniqueToAlwaysTrue" from gtest
|
[
"matthew.c.curfman@intel.com"
] |
matthew.c.curfman@intel.com
|
82da019a6a10c288e472ce5f42a52887fb10b406
|
2cae54fe441ad0e84b8df6917153bbe3c81ae986
|
/alphabetspam/alphabetspam.cpp
|
b826442abb0ba4130e1875b55473a8ea53559520
|
[
"MIT"
] |
permissive
|
omarchehab98/open.kattis.com-problems
|
3cb08a475ca4fb156462904a221362b98c2813c9
|
0523e2e641151dad719ef05cc9811a8ef5c6a278
|
refs/heads/master
| 2020-03-31T04:23:06.415280
| 2019-10-29T00:50:08
| 2019-10-29T00:50:08
| 151,903,075
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 620
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
string input;
cin >> input;
cout << setprecision(10) << (double(input.size() - regex_replace(input, regex("_"), "").size()) / input.size()) << endl;
cout << setprecision(10) << (double(input.size() - regex_replace(input, regex("[a-z]"), "").size()) / input.size()) << endl;
cout << setprecision(10) << (double(input.size() - regex_replace(input, regex("[A-Z]"), "").size()) / input.size()) << endl;
cout << setprecision(10) << (double(input.size() - regex_replace(input, regex("[^_A-Za-z]"), "").size()) / input.size()) << endl;
return 0;
}
|
[
"omarchehab98@gmail.com"
] |
omarchehab98@gmail.com
|
016b47739a6af4513a098713ebe4501a0f5c0642
|
dd949f215d968f2ee69bf85571fd63e4f085a869
|
/systems/spring-school-2011/subarchitectures/vision.sa/src/c++/vision/components/StereoFlapDetector/vs3/GestaltPrinciple.cc
|
aeb6822e906be3ebdd0df796100b595a928b2b07
|
[] |
no_license
|
marc-hanheide/cogx
|
a3fd395805f1b0ad7d713a05b9256312757b37a9
|
cb9a9c9cdfeba02afac6a83d03b7c6bb778edb95
|
refs/heads/master
| 2022-03-16T23:36:21.951317
| 2013-12-10T23:49:07
| 2013-12-10T23:49:07
| 219,460,352
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,324
|
cc
|
/**
* $Id: GestaltPrinciple.cc,v 1.15 2006/11/24 13:47:03 mxz Exp mxz $
*/
#include <string.h>
#include "VisionCore.hh"
#include "GestaltPrinciple.hh"
namespace Z
{
static const int NAME_LENGTH = 40;
static const char type_names[][NAME_LENGTH] = {
"FORM_SEGMENTS",
"FORM_LINES",
"FORM_ARCS",
"FORM_PARALLEL_LINE_GROUPS",
"FORM_ARC_JUNCTIONS",
"FORM_CONVEX_ARC_GROUPS",
"FORM_ELLIPSES",
"FORM_JUNCTIONS",
"FORM_CLOSURES",
"FORM_RECTANGLES",
"FORM_FLAPS",
"UNDEF"
};
/**
* Returns the name of a given gestalt principle type.
*/
const char* GestaltPrinciple::TypeName(Type t)
{
return type_names[t];
}
GestaltPrinciple::GestaltPrinciple(VisionCore *vc)
{
core = vc;
ResetRunTime();
}
/**
* Return the enum type of a given gestalt principle type name.
*/
GestaltPrinciple::Type GestaltPrinciple::EnumType(const char *type_name)
{
for(int i = 0; i < MAX_TYPE; i++)
if(strncmp(type_name, type_names[i], NAME_LENGTH) == 0)
return (Type)i;
return UNDEF;
}
void GestaltPrinciple::RankGestalts(Gestalt::Type type,
int(*compar)(const void *, const void *))
{
// first rank gestalts
core->RankedGestalts(type).Sort(compar);
// then set rank for each gestalt
for(unsigned i = 0; i < core->NumGestalts(type); i++)
core->RankedGestalts(type, i)->SetRank(i);
}
}
|
[
"marc@hanheide.net"
] |
marc@hanheide.net
|
013a75ea9c06b05e0367c8d33f1d5eb526afd572
|
485e1d6bd46195b77c3d3095ea0f7a9bf2a63594
|
/.localhistory/F/school/year4/courses/DBpractice/pagination/pagination/pagination/1602667412$memory.cpp
|
0e99f77d784d040d5b2b40dbea43c95d70e35138
|
[] |
no_license
|
ZESl/pagination
|
67ceaa2ecfaf985034d5d57d5fbe1268e23b2031
|
e1fc369dc16c40baead903ab51512d5ea1a85ed3
|
refs/heads/master
| 2022-12-28T17:46:45.338565
| 2020-10-14T12:59:33
| 2020-10-14T12:59:33
| 304,015,976
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,916
|
cpp
|
#include "memory.h"
#include <iostream>
#include <fstream>
using namespace std;
memory::memory()
{
m_pMemory = (MemBlock *)malloc(MEM_NUM * sizeof(MemBlock));
memset(m_anStack, -1, MEM_NUM * sizeof(int));
stackTop = -1;
}
memory::~memory()
{
}
// 1. read the file
// 2. page the file according to the file size, 4*1024 bytes per page
// 3. generate the page table index information.
int memory::LoadFile(QString fileName)
{
// 1. read the file
qDebug() << "opening file" << fileName << endl;
QFile myfile(fileName);
if (myfile.open(QFile::ReadOnly | QIODevice::Text)) {
txtFileName = fileName;
// 2. page the file according to the file size, 4*1024 bytes per page
int size = myfile.size();
qDebug() << "size:" << QString::number(size) << endl;
if (size % PAGE_SIZE != 0) {
pageNum = size / PAGE_SIZE + 1;
}
else {
pageNum = size / PAGE_SIZE;
}
m_pPageTable = NULL;
m_pPageTable = (PageItem *)malloc(pageNum * sizeof(PageItem));
// 3. generate the page table index information.
for (int i = 0; i < pageNum; i++) {
PageItem tmp = { i, false, false, (ULONGLONG)i*PAGE_SIZE, -1 };
m_pPageTable[i] = tmp;
}
return pageNum;
}
else {
return 0;
}
}
char* memory::ReadPage(const int pageno)
{
PushStack(pageno);
if (m_pPageTable[pageno].load) {
int memno = m_pPageTable[pageno].memno;
//char* pStr = (char*)malloc(PAGE_SIZE);
char pStr[PAGE_SIZE];
memcpy(pStr, m_pMemory[memno].content, PAGE_SIZE);
qDebug() << "FROM MEMORY";
//qDebug() << pStr << endl;
return pStr;
}
else {
m_pPageTable[pageno].load = true;
string str = txtFileName.toStdString();
const char* name = str.c_str();
char pStr[PAGE_SIZE];
FILE* pfile = nullptr;
fopen_s(&pfile, name, "rb");
fseek(pfile, m_pPageTable[pageno].position, SEEK_SET);
fread(pStr, 1, PAGE_SIZE, pfile);
fclose(pfile);
int memno = m_pPageTable[pageno].memno;
m_pMemory[memno].no = memno;
memcpy(m_pMemory[memno].content, pStr, PAGE_SIZE);
qDebug() << "FROM FILE";
//qDebug() << pStr << endl;
return pStr;
}
}
bool memory::UpdatePage(const int pageno, string str, const int nMaxSize)
{
// Query whether this page has existed in the current memory block.
// If it has existed, update the content in the memory block, and set the modification identifier as true.
// If it does not exist, load this page.
bool exist = false;
for (int i = 0; i < MEM_NUM; i++) {
if (pageno == m_anStack[i]) {
exist = true;
}
}
// search whether this page number has existed in the stack
if (exist) {
// fill in the blank
int len = str.length();
qDebug() << "len" << len <<endl;
if (len < PAGE_SIZE) {
for (int b = len; b <= PAGE_SIZE; b++) {
str += " ";
}
}
str += '\0';
m_pPageTable[pageno].modify = true;
int no = m_pPageTable[pageno].memno;
const char* pStr = str.c_str();
memcpy(m_pMemory[no].content, pStr, PAGE_SIZE);
}
/*else {
ReadPage(pageno, pStr, nMaxSize);
}*/
return true;
}
void memory::addPage()
{
// When a new page is added, allocate the memory space for the page table again
pageNum++;
m_pPageTable = (PageItem *)realloc(m_pPageTable, pageNum * sizeof(PageItem));
PageItem tmp = { pageNum-1, true, true, (pageNum-1)*PAGE_SIZE, -1 };
m_pPageTable[pageNum - 1] = tmp;
string text = "";
for (int g = 0; g < PAGE_SIZE; g++) {
text = text + " ";
}
text = text + '\0';
const char* str = text.c_str();
FILE* pfile = nullptr;
string name = txtFileName.toStdString();
const char* fileName = name.c_str();
// 在文件最后追加
fopen_s(&pfile, fileName, "ab+");
fprintf_s(pfile, str);
fclose(pfile);
}
void memory::WriteBack()
{
// When the window is logged out, write back all records in the page table.
// traverse the whole page table, find the modified page in the memory, and write back into the file.
FILE* pfile = nullptr;
FILE* temp = nullptr;
string str = txtFileName.toStdString();
const char* fileName = str.c_str();
fopen_s(&pfile, fileName, "rb");
fopen_s(&temp, "temp.txt", "wb");
for (int i = 0; i < pageNum; i++) {
if (m_pPageTable[i].modify) {
int memno = m_pPageTable[i].memno;
// writeback the memory
fwrite(m_pMemory[memno].content, 1, PAGE_SIZE, temp);
m_pPageTable[i].modify = false;
}
else {
// writeback the original file
char* pStr = NULL;
pStr = (char *)malloc(PAGE_SIZE * sizeof(char));
fseek(pfile, m_pPageTable[i].position, SEEK_SET);
fread(pStr, 1, PAGE_SIZE, pfile);
fwrite(pStr, 1, PAGE_SIZE, temp);
}
}
fclose(pfile);
fclose(temp);
remove("Little Prince.txt");
rename("temp.txt", "Little Prince.txt");
}
int memory::GetPageNum()
{
return pageNum;
}
int memory::QueryMemory(const int pageno)
{
return m_pPageTable[pageno].memno;
}
void memory::PushStack(const int pageno)
{
bool exist = false;
for (int i = 0; i < MEM_NUM; i++) {
if (pageno == m_anStack[i]) {
exist = true;
}
}
// search whether this page number has existed in the stack
if (exist) {
// move this page number to the stack top
for (int i = 0; i < MEM_NUM; i++) {
if (pageno == m_anStack[i]) {
for (int j = i; j < stackTop; j++) {
m_anStack[j] = m_anStack[j + 1];
}
m_anStack[stackTop] = pageno;
break;
}
}
}
else {
// If it does not exist, add it.
if (stackTop == MEM_NUM - 1) {
// If the stack has been full, move out the element of the stack bottom
// and put this number on the stack top.
m_pPageTable[m_anStack[0]].modify = false;
m_pPageTable[m_anStack[0]].load = false;
m_pPageTable[pageno].memno = m_pPageTable[m_anStack[0]].memno; // replace
m_pPageTable[m_anStack[0]].memno = -1;
for (int j = 0; j < MEM_NUM - 1; j++) {
m_anStack[j] = m_anStack[j + 1];
}
m_anStack[MEM_NUM - 1] = pageno;
}
else {
stackTop++;
m_anStack[stackTop] = pageno;
m_pPageTable[pageno].memno = stackTop;
}
}
}
int memory::PopStack()
{
return m_anStack[0];
}
|
[
"823989065@qq.com"
] |
823989065@qq.com
|
6408baed7f1a1504ea4a71f7c02eae35236e6652
|
83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1
|
/gen/v8_7_5/torque-generated/builtins-array-find-from-dsl-gen.h
|
a3c07ab60b22c89ef99cbcac3def07f0841b440d
|
[
"Apache-2.0"
] |
permissive
|
cool2528/miniblink49
|
d909e39012f2c5d8ab658dc2a8b314ad0050d8ea
|
7f646289d8074f098cf1244adc87b95e34ab87a8
|
refs/heads/master
| 2020-06-05T03:18:43.211372
| 2019-06-01T08:57:37
| 2019-06-01T08:59:56
| 192,294,645
| 2
| 0
|
Apache-2.0
| 2019-06-17T07:16:28
| 2019-06-17T07:16:27
| null |
UTF-8
|
C++
| false
| false
| 993
|
h
|
#ifndef V8_TORQUE_ARRAY_FIND_FROM_DSL_BASE_H__
#define V8_TORQUE_ARRAY_FIND_FROM_DSL_BASE_H__
#include "src/compiler/code-assembler.h"
#include "src/code-stub-assembler.h"
#include "src/utils.h"
#include "torque-generated/class-definitions-from-dsl.h"
namespace v8 {
namespace internal {
class ArrayFindBuiltinsFromDSLAssembler {
public:
explicit ArrayFindBuiltinsFromDSLAssembler(compiler::CodeAssemblerState* state) : state_(state), ca_(state) { USE(state_, ca_); }
compiler::TNode<Object> FastArrayFind(compiler::TNode<Context> p_context, compiler::TNode<JSReceiver> p_o, compiler::TNode<Number> p_len, compiler::TNode<JSReceiver> p_callbackfn, compiler::TNode<Object> p_thisArg, compiler::CodeAssemblerLabel* label_Bailout, compiler::TypedCodeAssemblerVariable<Smi>* label_Bailout_parameter_0);
private:
compiler::CodeAssemblerState* const state_;
compiler::CodeAssembler ca_;
};
} // namespace internal
} // namespace v8
#endif // V8_TORQUE_ARRAY_FIND_FROM_DSL_BASE_H__
|
[
"22249030@qq.com"
] |
22249030@qq.com
|
a0ecba1dc363d690e6570c203fb90e322aa7651d
|
e7305bf4b50cedfbecf236a545f109bd825840fa
|
/core/LinearForm.hpp
|
8efe92419d980eaee2cae472f00ede127ee24aa5
|
[] |
no_license
|
lucmobz/pacs-project
|
df03257ccf4b745692b1daf30919e7db188ef573
|
e54500b96dcf0e3d44aa07fa2970f95a5ac5c4b5
|
refs/heads/main
| 2023-04-30T11:49:55.701913
| 2021-05-21T20:27:13
| 2021-05-21T20:27:13
| 369,647,056
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,682
|
hpp
|
#pragma once
#include <Eigen/Core>
#include <algorithm>
#include <iostream>
#include <set>
#include <type_traits>
#include <utility>
#include "Expression.hpp"
#include "FeElement.hpp"
#include "FeFace.hpp"
#include "FeSpace.hpp"
#include "Traits.hpp"
#include "expression_type_traits.hpp"
#include "utilities_include.hpp"
namespace wave {
/**
\brief This class represents a LinearForm as in the variational formulation.
A LinearForm is built on top of a FeSpace, it can be given an expression as
imput to the int2d and int3d methods as a mathematical integral expression
written on paper (these two methods takes as template parameter the quadrature
rule as in QuadratureGaussLegendre or other rules). Once the expression is
given, the assembly happens and all the vector coefficients are saved. The
method vector will return the dense underlying vector to be used for further
computations.
*/
class LinearForm {
public:
using scalar_t = Traits::scalar_t;
using point_t = Traits::point_t;
using dense_t = Traits::dense_t;
/// \brief Construct a LinearForm from an FeSpace
explicit LinearForm(const FeSpace &fespace);
/// \brief Get the number of degrees of freedom (the length of the vector)
int size() const;
/// \brief Get the form associated vector.
const dense_t &vector() const;
/// \brief See BilinearForm int3d method.
/// The only difference is the absence of the symmetry flag.
template <typename Quadrature, typename Op, typename... Args>
void int3d(const Expression<Op, Args...> &expr);
/// \brief See BilinearForm int2d method.
/// The only difference is the absence of the symmetry flag.
template <typename Quadrature, typename Op, typename... Args>
void int2d(const Expression<Op, Args...> &expr,
const std::set<int> boundaries);
private:
/// The FeSpace on which the form is built.
const FeSpace &_fespace;
/// The vector associated with the form.
dense_t _vector;
};
//------------------------------------------------------------------------------
inline LinearForm::LinearForm(const FeSpace &fespace) : _fespace(fespace) {
_vector.resize(fespace.ndof());
_vector.setZero();
};
inline int LinearForm::size() const { return _fespace.ndof(); }
inline const LinearForm::dense_t &LinearForm::vector() const { return _vector; }
//------------------------------------------------------------------------------
// See BilinearForm int3d method for info
template <typename Quadrature, typename Op, typename... Args>
void LinearForm::int3d(const Expression<Op, Args...> &expr) {
#ifdef VERBOSE
utl::Timer timer("linear int3d");
#endif
// prefetch mesh
const auto &mesh = _fespace.mesh();
// prefetch quadrature information
constexpr auto QSIZE = Quadrature::size();
constexpr auto reference_measure = Quadrature::measure();
const auto weights = Quadrature::weights();
const auto nodes = Quadrature::nodes();
// helper to treat vectors as matrices (like sub2ind)
auto at = [&QSIZE](auto q, auto i) { return q + i * QSIZE; };
// loop over the elements
for (ElementIterator e(mesh); !e.end(); ++e) {
const auto &fe = _fespace(*e);
for (const auto &[jacobian, translation, simplex_measure] :
fe.triangulation()) {
// precompute ratio
scalar_t measure_ratio = simplex_measure / reference_measure;
// precompute transformed nodes
std::array<point_t, QSIZE> x;
std::array<point_t, QSIZE> xf;
int index = 0;
for (const auto &node : nodes) {
xf[index] = jacobian * node + translation;
x[index] = fe.map(xf[index]);
++index;
}
// precompute basis functions on nodes (seg-fault access never
// happens and this avoids realloc)
std::vector<scalar_t> phi;
std::vector<point_t> dphi;
if constexpr (has_Trial_or_Test_v<decltype(expr)>) {
phi = fe.eval_basis(x);
}
if constexpr (has_GradTrial_or_GradTest_v<decltype(expr)>) {
dphi = fe.eval_basis_derivatives(x);
}
// compute values
for (int i = 0; i < fe.ndof(); ++i) {
scalar_t value = 0.0;
for (int q = 0; q < QSIZE; ++q) {
value += expr.eval(phi[at(q, i)], dphi[at(q, i)], xf[q]) * weights[q];
}
_vector[fe.dof(i)] += value * measure_ratio;
}
}
}
}
//------------------------------------------------------------------------------
// See BilinearForm int2d method for info
template <typename Quadrature, typename Op, typename... Args>
void LinearForm::int2d(const Expression<Op, Args...> &expr,
const std::set<int> boundaries) {
#ifdef VERBOSE
utl::Timer timer("linear int2d");
#endif
// prefetch mesh
const auto &mesh = _fespace.mesh();
// prefetch quadrature information
constexpr auto QSIZE = Quadrature::size();
constexpr auto reference_measure = Quadrature::measure();
const auto weights = Quadrature::weights();
const auto nodes = Quadrature::nodes();
// helper to treat vectors as matrices (like sub2ind)
auto at = [&QSIZE](auto q, auto i) { return q + i * QSIZE; };
// loop over the faces (signed)
for (FaceIterator f(mesh); !f.end(); ++f) {
const auto &fef = _fespace(*f);
if (fef.is_exterior() && boundaries.contains(fef.boundary())) {
ElementIterator e(*f);
const auto &fe = _fespace(*e);
for (const auto &[jacobian, translation, simplex_measure] :
fef.triangulation()) {
// precompute ratio
scalar_t measure_ratio = simplex_measure / reference_measure;
// precompute transformed nodes
std::array<point_t, QSIZE> x;
std::array<point_t, QSIZE> xf;
int index = 0;
for (const auto &node : nodes) {
xf[index] = jacobian * node + translation;
x[index] = fe.map(xf[index]);
++index;
}
// precompute basis functions on nodes (seg-fault access never
// happens and this avoids realloc)
std::vector<scalar_t> phi;
std::vector<point_t> dphi;
if constexpr (has_Trial_or_Test_v<decltype(expr)>) {
phi = fe.eval_basis(x);
}
if constexpr (has_GradTrial_or_GradTest_v<decltype(expr)>) {
dphi = fe.eval_basis_derivatives(x);
}
for (int i = 0; i < fe.ndof(); ++i) {
scalar_t value = 0.0;
for (int q = 0; q < QSIZE; ++q) {
value += expr.eval(fef, FeFace::Side::POSITIVE, phi[at(q, i)],
dphi[at(q, i)], xf[q]) *
weights[q];
}
_vector[fe.dof(i)] += value * measure_ratio;
}
}
}
}
}
} // namespace wave
|
[
"luca.mobz.work@gmail.com"
] |
luca.mobz.work@gmail.com
|
e41c3c527c7217e4dfbdc7c05e9b9ea602aedd29
|
d333a3cbdcf089746d17bbd8d89cd978982d83d7
|
/Cpp/test/a.cpp
|
5671959e32d2e7e7ae64346a05e122ac98010afc
|
[] |
no_license
|
duantao74520/workspace
|
59bfd5d886533035da4ed46c86cbdff0f828a29d
|
5922d4f6715801919d9c84fd6f17f4a9fba8346f
|
refs/heads/master
| 2020-07-14T22:27:53.708007
| 2019-08-30T15:55:01
| 2019-08-30T15:55:01
| 205,416,103
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 211
|
cpp
|
#include <stdio.h>
void debug(char *str)
{
printf("debug info :%s\n",str );
}
main(int argc,char *argv[]){
int i,j;
j=0;
for(i=0;i<10;i++){
j+=5;
printf("now a=%d\n", j);
}
}
|
[
"841618016@qq.com"
] |
841618016@qq.com
|
60f44331f88af906ab8ebf1cfdceaf571eb05727
|
81de7d09d92e602d32055b5e84c12d07034e99ce
|
/Minimum Spanning Tree(최소 스패닝 트리)/1647_도시 분할 계획.cpp
|
d68be0edc2ceadb31f5885e0ab7798d49bcc6c90
|
[] |
no_license
|
newdeal123/BOJ
|
13499fe476ae1aee2b3174e147b4fafbc071985b
|
20a161e46018fc1baba1710f36d3d29fa3bf20db
|
refs/heads/master
| 2021-08-08T15:41:57.601898
| 2021-06-30T14:41:14
| 2021-06-30T14:41:14
| 164,074,479
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,504
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
const int INF=987654321;
const int MAX_N=100000+2;
int N,M;
vector<pair<int,int>> adj[MAX_N];
struct UNION_FIND
{
vector <int> parent,height;
UNION_FIND(){;};
UNION_FIND(int n)
{
parent.resize(n+1),height.resize(n+1,1);
for(int i=1;i<=n;i++)
parent[i]=i;
}
int find(int n)
{
if(parent[n]==n) return n;
return find(parent[n]);
}
void merge(int u,int v)
{
u=find(u),v=find(v);
if(u==v)
return;
if(height[u]>height[v])
swap(u,v);
parent[u]=v;
if(height[u]==height[v])
height[v]++;
}
};
int kruskal()
{
int ret=0,maxCost=0;
vector <pair<int,pair<int,int>>> edges;
for(int i=1;i<=N;i++)
for(auto j:adj[i])
edges.push_back(make_pair(j.second,make_pair(i,j.first)));
sort(edges.begin(),edges.end());
UNION_FIND uf(N);
for(auto i:edges)
{
int cost=i.first,u=i.second.first,v=i.second.second;
if(uf.find(u)==uf.find(v)) continue;
uf.merge(u,v);
ret+=cost;
maxCost=max(maxCost,cost);
}
return ret-maxCost;
}
int main()
{
ios_base :: sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>N>>M;
for(int i=0;i<M;i++)
{
int a,b,c;
cin>>a>>b>>c;
adj[a].push_back(make_pair(b,c));
adj[b].push_back(make_pair(a,c));
}
cout<<kruskal();
}
|
[
"newdeal123@nate.com"
] |
newdeal123@nate.com
|
3922dbce1469c11fc5b8a3eae9d4de33a807ad3a
|
95d0de25a793dcdcb27ac5c8804ccda6088f6480
|
/src/rpcmining.cpp
|
279986b20b4e41154b6416d686e6c990aa1dc85a
|
[
"MIT"
] |
permissive
|
HOANGHAI6876/CrimsonCoin1
|
738e5e9b3222e0b66d0c4888c175d6f85decdb74
|
0a15ffca478cd87670859ae7e1e3cd99dd7b76e3
|
refs/heads/master
| 2020-03-23T07:39:03.382693
| 2017-07-13T11:52:04
| 2017-07-13T11:52:04
| 141,283,508
| 0
| 1
| null | 2018-07-17T11:59:03
| 2018-07-17T11:59:02
| null |
UTF-8
|
C++
| false
| false
| 19,231
|
cpp
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
extern unsigned int nTargetSpacing;
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (uint64_t)GetProofOfWorkReward(0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
Object obj, diff, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(0)));
obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
weight.push_back(Pair("minimum", (uint64_t)nMinWeight));
weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
obj.push_back(Pair("stakeinterest", (uint64_t)COIN_YEAR_REWARD));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
uint64_t nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
int nExpectedTime = staking ? (nTargetSpacing * nNetworkWeight / nWeight) : -1;
Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "CrimsonCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "CrimsonCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "CrimsonCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "CrimsonCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "CrimsonCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "CrimsonCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
|
[
"takobrooks@dr.com"
] |
takobrooks@dr.com
|
6c86ca854929d2c2cb0de3e21901bb343041e93f
|
edad7a6ae21782e63cb4992cbf29625f7a5b866f
|
/1541.cpp
|
5d5e883b470c903128a31c4e94a8ea61c5219d45
|
[] |
no_license
|
iamDip171/URI-Probelms
|
6f95339c2ab9ff5f3bd0b649a922166689585a65
|
786ea3121c12202e1109c0e7314afc4ce76fd545
|
refs/heads/master
| 2023-03-10T01:08:37.720151
| 2021-02-26T05:50:56
| 2021-02-26T05:50:56
| 336,617,169
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 242
|
cpp
|
#include <bits/stdc++.h>
using namespace std ;
int main ()
{
int a,b, percent ;
while (1) {
cin >> a ;
if (a == 0) break ;
cin >> b >> percent ;
cout << (int) sqrt((a*b)*100/percent) << "\n" ;
}
}
|
[
"dsaha201171@bscse.uiu.ac.bd"
] |
dsaha201171@bscse.uiu.ac.bd
|
ba9690ef049018796b11875c48debf8968158cc3
|
7bcb66d652628227febe3b19579ac9efbe98addd
|
/PAUI/PlottingImageListener.hpp
|
6785ab87f8d88fb38f5c1ff785b0b78c44db713f
|
[] |
no_license
|
AntonioTavares24/PAUI-RAPOSA
|
ab2bdda925b6b99912f090928b5595ded0129a24
|
a2786ecb88dc883724d4a23d2823ce7d03273e6f
|
refs/heads/master
| 2023-01-09T12:38:22.628219
| 2020-11-06T18:05:15
| 2020-11-06T18:05:15
| 310,671,485
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,738
|
hpp
|
#pragma once
#include <iostream>
#include <memory>
#include <chrono>
#include <thread>
#include <mutex>
#include <fstream>
#include <map>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <boost/filesystem.hpp>
#include <boost/timer/timer.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include "ImageListener.h"
using namespace affdex;
class PlottingImageListener : public ImageListener
{
std::mutex mMutex;
std::deque<std::pair<Frame, std::map<FaceId, Face> > > mDataArray;
double mCaptureLastTS;
double mCaptureFPS;
double mProcessLastTS;
double mProcessFPS;
std::ofstream &fStream;
std::chrono::time_point<std::chrono::system_clock> mStartT;
const bool mDrawDisplay;
const int spacing = 10;
const float font_size = 0.5f;
const int font = cv::FONT_HERSHEY_COMPLEX_SMALL;
std::vector<std::string> expressions;
std::vector<std::string> emotions;
std::vector<std::string> emojis;
std::vector<std::string> headAngles;
std::map<affdex::Glasses, std::string> glassesMap;
std::map<affdex::Gender, std::string> genderMap;
std::map<affdex::Age, std::string> ageMap;
std::map<affdex::Ethnicity, std::string> ethnicityMap;
public:
PlottingImageListener(std::ofstream &csv, const bool draw_display)
: fStream(csv), mDrawDisplay(draw_display), mStartT(std::chrono::system_clock::now()),
mCaptureLastTS(-1.0f), mCaptureFPS(-1.0f),
mProcessLastTS(-1.0f), mProcessFPS(-1.0f)
{
expressions = {
"smile", "innerBrowRaise", "browRaise", "browFurrow", "noseWrinkle",
"upperLipRaise", "lipCornerDepressor", "chinRaise", "lipPucker", "lipPress",
"lipSuck", "mouthOpen", "smirk", "eyeClosure", "attention", "eyeWiden", "cheekRaise",
"lidTighten", "dimpler", "lipStretch", "jawDrop"
};
emotions = {
"joy", "fear", "disgust", "sadness", "anger",
"surprise", "contempt", "valence", "engagement"
};
headAngles = { "pitch", "yaw", "roll" };
emojis = std::vector<std::string> {
"relaxed", "smiley", "laughing",
"kissing", "disappointed",
"rage", "smirk", "wink",
"stuckOutTongueWinkingEye", "stuckOutTongue",
"flushed", "scream"
};
genderMap = std::map<affdex::Gender, std::string> {
{ affdex::Gender::Male, "male" },
{ affdex::Gender::Female, "female" },
{ affdex::Gender::Unknown, "unknown" },
};
glassesMap = std::map<affdex::Glasses, std::string> {
{ affdex::Glasses::Yes, "yes" },
{ affdex::Glasses::No, "no" }
};
ageMap = std::map<affdex::Age, std::string> {
{ affdex::Age::AGE_UNKNOWN, "unknown"},
{ affdex::Age::AGE_UNDER_18, "under 18" },
{ affdex::Age::AGE_18_24, "18-24" },
{ affdex::Age::AGE_25_34, "25-34" },
{ affdex::Age::AGE_35_44, "35-44" },
{ affdex::Age::AGE_45_54, "45-54" },
{ affdex::Age::AGE_55_64, "55-64" },
{ affdex::Age::AGE_65_PLUS, "65 plus" }
};
ethnicityMap = std::map<affdex::Ethnicity, std::string> {
{ affdex::Ethnicity::UNKNOWN, "unknown"},
{ affdex::Ethnicity::CAUCASIAN, "caucasian" },
{ affdex::Ethnicity::BLACK_AFRICAN, "black african" },
{ affdex::Ethnicity::SOUTH_ASIAN, "south asian" },
{ affdex::Ethnicity::EAST_ASIAN, "east asian" },
{ affdex::Ethnicity::HISPANIC, "hispanic" }
};
fStream << "TimeStamp,faceId,interocularDistance,glasses,age,ethnicity,gender,dominantEmoji,";
for (std::string angle : headAngles) fStream << angle << ",";
for (std::string emotion : emotions) fStream << emotion << ",";
for (std::string expression : expressions) fStream << expression << ",";
for (std::string emoji : emojis) fStream << emoji << ",";
fStream << std::endl;
fStream.precision(4);
fStream << std::fixed;
}
FeaturePoint minPoint(VecFeaturePoint points)
{
VecFeaturePoint::iterator it = points.begin();
FeaturePoint ret = *it;
for (; it != points.end(); it++)
{
if (it->x < ret.x) ret.x = it->x;
if (it->y < ret.y) ret.y = it->y;
}
return ret;
};
FeaturePoint maxPoint(VecFeaturePoint points)
{
VecFeaturePoint::iterator it = points.begin();
FeaturePoint ret = *it;
for (; it != points.end(); it++)
{
if (it->x > ret.x) ret.x = it->x;
if (it->y > ret.y) ret.y = it->y;
}
return ret;
};
double getProcessingFrameRate()
{
std::lock_guard<std::mutex> lg(mMutex);
return mProcessFPS;
}
double getCaptureFrameRate()
{
std::lock_guard<std::mutex> lg(mMutex);
return mCaptureFPS;
}
int getDataSize()
{
std::lock_guard<std::mutex> lg(mMutex);
return mDataArray.size();
}
std::pair<Frame, std::map<FaceId, Face>> getData()
{
std::lock_guard<std::mutex> lg(mMutex);
std::pair<Frame, std::map<FaceId, Face>> dpoint = mDataArray.front();
mDataArray.pop_front();
return dpoint;
}
void onImageResults(std::map<FaceId, Face> faces, Frame image) override
{
std::lock_guard<std::mutex> lg(mMutex);
mDataArray.push_back(std::pair<Frame, std::map<FaceId, Face>>(image, faces));
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
std::chrono::milliseconds milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now - mStartT);
double seconds = milliseconds.count() / 1000.f;
mProcessFPS = 1.0f / (seconds - mProcessLastTS);
mProcessLastTS = seconds;
};
void onImageCapture(Frame image) override
{
std::lock_guard<std::mutex> lg(mMutex);
mCaptureFPS = 1.0f / (image.getTimestamp() - mCaptureLastTS);
mCaptureLastTS = image.getTimestamp();
};
void outputToFile(const std::map<FaceId, Face> faces, const double timeStamp)
{
if (faces.empty())
{
fStream << timeStamp << ",nan,nan,no,unknown,unknown,unknown,unknown,";
for (std::string angle : headAngles) fStream << "nan,";
for (std::string emotion : emotions) fStream << "nan,";
for (std::string expression : expressions) fStream << "nan,";
for (std::string emoji : emojis) fStream << "nan,";
fStream << std::endl;
}
for (auto & face_id_pair : faces)
{
Face f = face_id_pair.second;
fStream << timeStamp << ","
<< f.id << ","
<< f.measurements.interocularDistance << ","
<< glassesMap[f.appearance.glasses] << ","
<< ageMap[f.appearance.age] << ","
<< ethnicityMap[f.appearance.ethnicity] << ","
<< genderMap[f.appearance.gender] << ","
<< affdex::EmojiToString(f.emojis.dominantEmoji) << ",";
float *values = (float *)&f.measurements.orientation;
for (std::string angle : headAngles)
{
fStream << (*values) << ",";
values++;
}
values = (float *)&f.emotions;
for (std::string emotion : emotions)
{
fStream << (*values) << ",";
values++;
}
values = (float *)&f.expressions;
for (std::string expression : expressions)
{
fStream << (*values) << ",";
values++;
}
values = (float *)&f.emojis;
for (std::string emoji : emojis)
{
fStream << (*values) << ",";
values++;
}
fStream << std::endl;
}
}
void drawValues(const float * first, const std::vector<std::string> names,
const int x, int &padding, const cv::Scalar clr,
cv::Mat img)
{
for (std::string name : names)
{
if (std::abs(*first) > 5.0f)
{
char m[50];
sprintf(m, "%s: %3.2f", name.c_str(), (*first));
cv::putText(img, m, cv::Point(x, padding += spacing), font, font_size, clr);
}
first++;
}
}
void draw(const std::map<FaceId, Face> faces, Frame image)
{
std::shared_ptr<BYTE> imgdata = image.getBGRByteArray();
cv::Mat img = cv::Mat(image.getHeight(), image.getWidth(), CV_8UC3, imgdata.get());
const int left_margin = 30;
cv::Scalar clr = cv::Scalar(0, 0, 255);
cv::Scalar header_clr = cv::Scalar(255, 0, 0);
for (auto & face_id_pair : faces)
{
Face f = face_id_pair.second;
VecFeaturePoint points = f.featurePoints;
for (auto& point : points) //Draw face feature points.
{
cv::circle(img, cv::Point(point.x, point.y), 2.0f, cv::Scalar(0, 0, 255));
}
FeaturePoint tl = minPoint(points);
FeaturePoint br = maxPoint(points);
//Output the results of the different classifiers.
int padding = tl.y + 10;
cv::putText(img, "APPEARANCE", cv::Point(br.x, padding += (spacing * 2)), font, font_size, header_clr);
cv::putText(img, genderMap[f.appearance.gender], cv::Point(br.x, padding += spacing), font, font_size, clr);
cv::putText(img, glassesMap[f.appearance.glasses], cv::Point(br.x, padding += spacing), font, font_size, clr);
cv::putText(img, ageMap[f.appearance.age], cv::Point(br.x, padding += spacing), font, font_size, clr);
cv::putText(img, ethnicityMap[f.appearance.ethnicity], cv::Point(br.x, padding += spacing), font, font_size, clr);
Orientation headAngles = f.measurements.orientation;
char strAngles[100];
sprintf(strAngles, "Pitch: %3.2f Yaw: %3.2f Roll: %3.2f Interocular: %3.2f",
headAngles.pitch, headAngles.yaw, headAngles.roll, f.measurements.interocularDistance);
char fId[10];
sprintf(fId, "ID: %i", f.id);
cv::putText(img, fId, cv::Point(br.x, padding += spacing), font, font_size, clr);
cv::putText(img, "MEASUREMENTS", cv::Point(br.x, padding += (spacing * 2)), font, font_size, header_clr);
cv::putText(img, strAngles, cv::Point(br.x, padding += spacing), font, font_size, clr);
cv::putText(img, "EMOJIS", cv::Point(br.x, padding += (spacing * 2)), font, font_size, header_clr);
cv::putText(img, "dominantEmoji: " + affdex::EmojiToString(f.emojis.dominantEmoji),
cv::Point(br.x, padding += spacing), font, font_size, clr);
drawValues((float *)&f.emojis, emojis, br.x, padding, clr, img);
cv::putText(img, "EXPRESSIONS", cv::Point(br.x, padding += (spacing * 2)), font, font_size, header_clr);
drawValues((float *)&f.expressions, expressions, br.x, padding, clr, img);
cv::putText(img, "EMOTIONS", cv::Point(br.x, padding += (spacing * 2)), font, font_size, header_clr);
drawValues((float *)&f.emotions, emotions, br.x, padding, clr, img);
}
char fps_str[50];
sprintf(fps_str, "capture fps: %2.0f", mCaptureFPS);
cv::putText(img, fps_str, cv::Point(img.cols - 110, img.rows - left_margin - spacing), font, font_size, clr);
sprintf(fps_str, "process fps: %2.0f", mProcessFPS);
cv::putText(img, fps_str, cv::Point(img.cols - 110, img.rows - left_margin), font, font_size, clr);
cv::imshow("analyze video", img);
std::lock_guard<std::mutex> lg(mMutex);
cv::waitKey(30);
}
};
|
[
"66315859+AntonioTavares24@users.noreply.github.com"
] |
66315859+AntonioTavares24@users.noreply.github.com
|
c654d7e6f809feeb20527fa19e99e3b63e66b264
|
37cca16f12e7b1d4d01d6f234da6d568c318abee
|
/src/org/mpisws/p2p/testing/filetransfer/ProfileFileTest_main_2_incomingSocket_2_1.hpp
|
f723c905be7e791debcd53a2ce7565e21dcb685f
|
[] |
no_license
|
subhash1-0/thirstyCrow
|
e48155ce68fc886f2ee8e7802567c1149bc54206
|
78b7e4e3d2b9a9530ad7d66b44eacfe73ceea582
|
refs/heads/master
| 2016-09-06T21:25:54.075724
| 2015-09-21T17:21:15
| 2015-09-21T17:21:15
| 42,881,521
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,691
|
hpp
|
// Generated from /pastry-2.1/src/org/mpisws/p2p/testing/filetransfer/ProfileFileTest.java
#pragma once
#include <java/io/fwd-pastry-2.1.hpp>
#include <java/lang/fwd-pastry-2.1.hpp>
#include <java/nio/fwd-pastry-2.1.hpp>
#include <org/mpisws/p2p/testing/filetransfer/fwd-pastry-2.1.hpp>
#include <rice/environment/logging/fwd-pastry-2.1.hpp>
#include <java/lang/Object.hpp>
#include <org/mpisws/p2p/filetransfer/FileTransferCallback.hpp>
struct default_init_tag;
class org::mpisws::p2p::testing::filetransfer::ProfileFileTest_main_2_incomingSocket_2_1
: public virtual ::java::lang::Object
, public virtual ::org::mpisws::p2p::filetransfer::FileTransferCallback
{
public:
typedef ::java::lang::Object super;
void messageReceived(::java::nio::ByteBuffer* bb) override;
void fileReceived(::java::io::File* f, ::java::nio::ByteBuffer* metadata) override;
void receiveException(::java::lang::Exception* ioe) override;
// Generated
ProfileFileTest_main_2_incomingSocket_2_1(ProfileFileTest_main_2 *ProfileFileTest_main_2_this, ::rice::environment::logging::Logger* logger);
static ::java::lang::Class *class_();
ProfileFileTest_main_2 *ProfileFileTest_main_2_this;
::rice::environment::logging::Logger* logger;
private:
virtual ::java::lang::Class* getClass0();
friend class ProfileFileTest;
friend class ProfileFileTest_main_1;
friend class ProfileFileTest_main_2;
friend class ProfileFileTest_main_2_incomingSocket_2_2;
friend class ProfileFileTest_main_3;
friend class ProfileFileTest_main_4;
friend class ProfileFileTest_main_4_receiveResult_4_1;
friend class ProfileFileTest_main_4_receiveResult_4_2;
};
|
[
"sgurjar@adobe.com"
] |
sgurjar@adobe.com
|
2762855789fd72ec9e2156ed72bfe0e67a3286cc
|
dd11fc3311b61ddbe196e21c14226d0b60777650
|
/src/classical/mign/mign_rewriting_majn_to_smaller.hpp
|
753659ce35ed00a6bbe579716c98812591ec1fc2
|
[
"MIT"
] |
permissive
|
eletesta/cirkit-addon-mign
|
3d03b72f2c6b3254c77c88aad0f81971eebb6bd0
|
65c79809495957892dbf3e48550d035970a2169b
|
refs/heads/master
| 2021-09-20T01:04:14.135418
| 2018-08-02T00:14:00
| 2018-08-02T00:14:00
| 84,551,715
| 0
| 0
| null | 2017-10-03T10:20:12
| 2017-03-10T11:08:31
|
C++
|
UTF-8
|
C++
| false
| false
| 1,404
|
hpp
|
/* CirKit: A circuit toolkit
* Copyright (C) 2009-2015 University of Bremen
* Copyright (C) 2015-2016 EPFL
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file mig_rewriting.hpp
*
* @brief MIG rewriting
*
* @author Mathias Soeken
* @since 2.3
*/
#ifndef MIGN_REWRITING_MAJN_TO_SMALLER_HPP
#define MIGN_REWRITING_MAJN_TO_SMALLER_HPP
#include <core/properties.hpp>
#include <classical/mign/mign.hpp>
namespace cirkit
{
mign_graph mign_rewriting_majn_to_smaller( mign_graph& mign, const unsigned n,
const properties::ptr& settings,
const properties::ptr& statistics );
}
#endif
// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:
|
[
"eleonora.testa@epfl.ch"
] |
eleonora.testa@epfl.ch
|
b1df127d5d1a110abb9ba34d2a0f1ab0e9c3fcc5
|
aa8c315b03c10e46bda03d2ce6d334ad5b91ee01
|
/arduino_play/instrument.h
|
08700f81daade435792933fc64fcf8d092fe3815
|
[] |
no_license
|
jachang820/InstrumentPlayingRobot
|
84eed1b6104b92fae017cdaeefa0216d927d23ee
|
3cb38c5f4b454dc40ec120c52d4f6743bbb7b88d
|
refs/heads/master
| 2021-05-02T10:01:28.275188
| 2018-02-09T22:22:10
| 2018-02-09T22:22:10
| 120,786,855
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 140
|
h
|
#ifndef INSTRUMENT_H
#define INSTRUMENT_H
class Instrument {
public:
virtual void begin() = 0;
virtual void play(int) = 0;
};
#endif
|
[
"j.a.chang820@gmail.com"
] |
j.a.chang820@gmail.com
|
4d8e3c773b3f3daf4bb1160f7baa7ab553e2028d
|
b4393b82bcccc59e2b89636f1fde16d82f060736
|
/devtools/lit/lib/ShellCommands.h
|
1897c46237d9a18f1a13cf10caa55e45e32e2894
|
[] |
no_license
|
phpmvc/polarphp
|
abb63ed491a0175aa43c873b1b39811f4eb070a2
|
eb0b406e515dd550fd99b9383d4b2952fed0bfa9
|
refs/heads/master
| 2020-04-08T06:51:03.842159
| 2018-11-23T06:32:04
| 2018-11-23T06:32:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,941
|
h
|
// This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2018 polarphp software foundation
// Copyright (c) 2017 - 2018 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://polarphp.org/LICENSE.txt for license information
// See http://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/09/04.
#ifndef POLAR_DEVLTOOLS_LIT_SHELL_COMMANDS_H
#define POLAR_DEVLTOOLS_LIT_SHELL_COMMANDS_H
#include <list>
#include <string>
#include <any>
#include <memory>
#include <assert.h>
#include "LitGlobal.h"
#include "ForwardDefs.h"
namespace polar {
namespace lit {
using RedirectTokenType = std::tuple<ShellTokenType, std::string>;
class AbstractCommand
{
public:
enum class Type {
Command,
Pipeline,
Seq
};
public:
virtual void toShell(std::string &str, bool pipeFail = false) const = 0;
virtual operator std::string() = 0;
virtual Type getCommandType() = 0;
};
class Command : public AbstractCommand
{
public:
Command(const std::list<std::any> &args, const std::list<RedirectTokenType > &redirects)
: m_args(args),
m_redirects(redirects)
{}
operator std::string() override;
bool operator ==(const Command &other) const;
std::list<std::any> &getArgs();
const std::list<RedirectTokenType > &getRedirects();
void toShell(std::string &str, bool pipeFail = false) const override;
Type getCommandType() override
{
return Type::Command;
}
private:
bool compareTokenAny(const std::any &lhs, const std::any &rhs) const;
protected:
// GlobItem or std::tuple<std::string, int>
std::list<std::any> m_args;
std::list<RedirectTokenType> m_redirects;
};
class GlobItem
{
public:
GlobItem(const std::string &pattern)
: m_pattern(pattern)
{}
std::list<std::string> resolve(const std::string &cwd) const;
operator std::string();
bool operator ==(const GlobItem &other) const;
bool operator !=(const GlobItem &other) const
{
return !operator ==(other);
}
protected:
std::string m_pattern;
};
class Pipeline : public AbstractCommand
{
public:
Pipeline(const std::list<std::shared_ptr<AbstractCommand>> &commands, bool negate = false, bool pipeError = false)
: m_commands(commands),
m_negate(negate),
m_pipeError(pipeError)
{
}
operator std::string() override;
bool isNegate();
bool isPipeError();
bool operator ==(const Pipeline &other) const;
bool operator !=(const Pipeline &other) const
{
return !operator ==(other);
}
void toShell(std::string &str, bool pipeFail = false) const override;
Type getCommandType() override
{
return Type::Pipeline;
}
const CommandList &getCommands() const;
protected:
CommandList m_commands;
bool m_negate;
bool m_pipeError;
};
class Seq : public AbstractCommand
{
public:
Seq(std::shared_ptr<AbstractCommand> lhs, const std::string &op, std::shared_ptr<AbstractCommand> rhs)
: m_op(op),
m_lhs(lhs),
m_rhs(rhs)
{
assert(op.find(';') != std::string::npos ||
op.find('&') != std::string::npos ||
op.find("||") != std::string::npos ||
op.find("&&") != std::string::npos);
}
operator std::string() override;
bool operator ==(const Seq &other) const;
bool operator !=(const Seq &other) const
{
return !operator ==(other);
}
Type getCommandType() override
{
return Type::Seq;
}
const std::string &getOp() const;
AbstractCommandPointer getLhs() const;
AbstractCommandPointer getRhs() const;
void toShell(std::string &str, bool pipeFail = false) const override;
protected:
std::string m_op;
AbstractCommandPointer m_lhs;
AbstractCommandPointer m_rhs;
};
} // lit
} // polar
#endif // POLAR_DEVLTOOLS_LIT_SHELL_COMMANDS_H
|
[
"zzu_softboy@163.com"
] |
zzu_softboy@163.com
|
42e54e77c32c31c25643974f7de7fcf49359162c
|
158a8bb4d5e40c3f1655969fe8c9d06356925f2d
|
/Reverse Linked List II .cpp
|
e30186d7e182c7c92f79969de3e1ee0e1dea5a8f
|
[] |
no_license
|
xjh10389290/leetcode
|
1ade186b1d1d43bab6706718ce1c595da771e0bd
|
f7d9fe4e944a024093a2383447078983513505b1
|
refs/heads/master
| 2020-04-18T00:52:33.794217
| 2015-06-13T01:34:20
| 2015-06-13T01:34:20
| 28,729,799
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 893
|
cpp
|
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
int nn=m;
int k=m-1;
ListNode *chead=head;
ListNode *ptr0=head;
ListNode *ptr1=head;
ListNode *ptr2=head;
ListNode *ptr3=head;
while((--k)>0) ptr0=ptr0->next;
while((--m)>0) ptr1=ptr1->next;
while((--n)>0) ptr2=ptr2->next;
ptr3=ptr2->next;
if (ptr1!=NULL&&ptr2!=NULL&&ptr1!=ptr2)reverseKGroup(ptr1,ptr2);
if (nn!=1)ptr0->next=ptr2;
ptr1->next=ptr3;
if (nn==1) return ptr2;
else return chead;
}
void reverseKGroup(ListNode *head,ListNode *tail)
{
ListNode *ptr1=head;
ListNode *ptr2=ptr1->next;
ListNode *ptr3=ptr2->next;
while (ptr2!=NULL&&(ptr1!=tail))
{
ptr2->next=ptr1;
ptr1=ptr2;
ptr2=ptr3;
if (ptr2!=NULL) ptr3=ptr2->next;
}
}
};
|
[
"307154003@qq.com"
] |
307154003@qq.com
|
3e3bf33a4555f212a38d60b45f204a80a270286b
|
d14b5d78b72711e4614808051c0364b7bd5d6d98
|
/third_party/llvm-10.0/llvm/lib/DebugInfo/PDB/PDBSymbolTypeCustom.cpp
|
6723894c90ea80f4293520bd9ceae3444899b209
|
[
"Apache-2.0"
] |
permissive
|
google/swiftshader
|
76659addb1c12eb1477050fded1e7d067f2ed25b
|
5be49d4aef266ae6dcc95085e1e3011dad0e7eb7
|
refs/heads/master
| 2023-07-21T23:19:29.415159
| 2023-07-21T19:58:29
| 2023-07-21T20:50:19
| 62,297,898
| 1,981
| 306
|
Apache-2.0
| 2023-07-05T21:29:34
| 2016-06-30T09:25:24
|
C++
|
UTF-8
|
C++
| false
| false
| 666
|
cpp
|
//===- PDBSymbolTypeCustom.cpp - --------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include <utility>
using namespace llvm;
using namespace llvm::pdb;
void PDBSymbolTypeCustom::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
[
"bclayton@google.com"
] |
bclayton@google.com
|
abbe8c60195667f438ff862b8dc81214f760e34d
|
882b06a0f5b570c6072afddf3ab1d5684fe982f4
|
/jge/Projects/cspsp/src/Person.h
|
ec3ded30d9fdc501559449a9a2eb9bb95fe5fa4b
|
[
"BSD-3-Clause"
] |
permissive
|
kevinbchen/cspsp
|
75a06a7decc826ec788ff79e01d1d31de4b43d5f
|
51abd9ed47ca39c576030a8ed233523e2d41d44c
|
refs/heads/master
| 2022-07-13T04:41:00.832823
| 2022-06-27T06:18:06
| 2022-06-27T06:18:06
| 6,846,752
| 26
| 10
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,568
|
h
|
#ifndef _PERSON_H_
#define _PERSON_H_
#include "JRenderer.h"
#include "JSoundSystem.h"
#include "Bullet.h"
#include "Grenade.h"
#include "GunObject.h"
#include "SfxManager.h"
#include <vector>
#include "Node.h"
#include "GunObjectOnline.h"
#include "Animation.h"
#define RELATIVE1 0
#define ABSOLUTE1 1
#define MOVING 0
#define NOTMOVING 1
#define NORMAL 0
#define DEAD 1
#define ATTACKING 2
#define RELOADING 3
#define DRYFIRING 4
#define SWITCHING 5
#define PRIMARY 0
#define SECONDARY 1
#define KNIFE 2
#define GRENADE 3
#define BODY 0
#define RIGHTARM 1
#define RIGHTHAND 2
#define LEFTARM 3
#define LEFTHAND 4
#define GUN 5
#define HEAD 5
#define LEGS 6
#define NUM_QUADS 7
#define WALKTIME 160.0f
enum {
ANIM_PRIMARY = 0,
ANIM_SECONDARY,
ANIM_KNIFE,
ANIM_GRENADE,
ANIM_BOMB,
ANIM_PRIMARY_FIRE,
ANIM_SECONDARY_FIRE,
ANIM_KNIFE_SLASH,
ANIM_GRENADE_PULLBACK,
ANIM_PRIMARY_RELOAD,
ANIM_SECONDARY_RELOAD
};
enum {
WALK1 = 0,
WALK2,
WALK3,
WALK4
};
//------------------------------------------------------------------------------------------------
class Person
{
private:
protected:
static JRenderer* mRenderer;
static JSoundSystem* mSoundSystem;
int mSoundId;
int mNumDryFire;
KeyFrame mKeyFrame;
Animation* mAnimations[11];
Animation* mCurrentAnimation;
int mMuzzleFlashIndex;
float mMuzzleFlashAngle;
float mMuzzleFlashTime;
float mWalkX;
float mWalkY;
void UpdateAngle(float &angle, float targetangle, float speed);
public:
JQuad* mQuads[NUM_QUADS];
//JQuad* mPartQuads[6];
JQuad* mDeadQuad;
float mAngle;
float mSpeed;
float mRotation;
float mX;
float mY;
float mOldX;
float mOldY;
std::vector<Person*>* mPeople;
std::vector<Bullet*>* mBullets;
std::vector<GunObject*>* mGunObjects;
float mMaxSpeed;
int mState;
int mMoveState;
float mStateTime;
float mFadeTime;
float mStepTime;
int mHealth;
int mMoney;
float mFacingAngle;
float mRecoilAngle;
float mLastFireAngle;
bool mIsActive;
GunObject* mGuns[5];
int mGunIndex;
//GunObject* mPrimaryGun;
//GunObject* mSecondaryGun;
//GunObject* mKnife;
int mTeam;
char mName[32];
int mMovementStyle;
int mNumKills;
int mNumDeaths;
float mPing;
bool mIsPlayerOnline;
bool mIsFiring;
bool mHasFired;
bool mIsFlashed;
float mFlashTime;
float mFlashIntensity;
bool mIsInBuyZone;
std::vector<Node*> mNodes;
Node* mNode;
Node* mTargetNode;
int mWalkState;
float mWalkTime;
float mWalkAngle;
float mRadarTime;
float mRadarX;
float mRadarY;
bool mHasFlag;
float mInvincibleTime;
Person(JQuad* quads[], JQuad* deadquad, std::vector<Bullet*>* bullets, std::vector<GunObject*>* guns, int team, char* name, int movementstyle);
virtual ~Person();
void PreUpdate(float dt);
virtual void Update(float dt);
virtual void Render(float x, float y);
virtual void Move(float speed, float angle);
virtual std::vector<Bullet*> Fire();
virtual std::vector<Bullet*> StopFire();
virtual bool Reload();
virtual void Switch(int index);
void SwitchNext();
bool PickUp(GunObject* gunobject);
virtual bool Drop(int index, float speed = 0.35f);
void RotateFacing(float theta);
void SetMoveState(int state);
void SetState(int state);
void SetAnimation(int animation);
void SetTotalRotation(float theta);
virtual void Die();
virtual void Reset();
void TakeDamage(int damage);
void ReceiveFlash(float intensity);
void SetQuads(JQuad* quads[], JQuad* deadquad);
GunObject* GetCurrentGun();
virtual void Teleport(float x, float y);
};
inline GunObject* Person::GetCurrentGun() {
return mGuns[mGunIndex];
}
#endif
|
[
"kevinchen1992@gmail.com"
] |
kevinchen1992@gmail.com
|
6e2f0a71474f123b25c7860ad25e766df929815f
|
580258c3959289967335bdf26638693ff7770bd8
|
/Source/Project_X_Ray/TurretHardPoint.cpp
|
a7253f6568616464877119e2368e51351827e174
|
[] |
no_license
|
Tiba3195/Project_X_Ray_Full
|
ab997659be3e0a41fad860b389a58c3c58dbe634
|
53283808b71589988217b0a1242c456bccff031e
|
refs/heads/master
| 2021-01-25T09:10:38.405054
| 2017-06-09T07:07:39
| 2017-06-09T07:07:39
| 93,795,445
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,219
|
cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Project_X_Ray.h"
#include "TurretHardPoint.h"
#include "GlobalGameState.h"
#include "MediumTurretActor.h"
#include "LightTurretActor.h"
#include "HeavyTurretActor.h"
#include "HeavyAntiAirTurretActor.h"
#include "AntiAirTurretActor.h"
#include "DuelCannonTurretActor.h"
#include "AntiPawnTurretActor.h"
#include "PlasmaTurretActor.h"
//the turret classes that will be imported and filled with a blueprint
UClass* HeavyTurretActorClassHolder;
UClass* MediumTurretActorClassHolder;
UClass* LightTurretActorClassHolder;
UClass* HeavyAntiAirTurretActorClassHolder;
UClass* AntiAirTurretActorClassHolder;
UClass* DuelTurretActorClassHolder;
UClass* AntiPawnTurretActorClassHolder;
UClass* TurretActorClassHolder;
UClass* PlasmaTurretClassHolder;
//Names of the blueprints for checking if we can build a turret type
static FString HeavyTurretName = "/Game/Turrets/BP_HeavyTurretActor.BP_HeavyTurretActor_C";
static FString MediumTurretTurretName = "/Game/Turrets/BP_MediumTurretActor.BP_MediumTurretActor_C";
static FString LightTurretName = "/Game/Turrets/BP_LightTurretActor.BP_LightTurretActor_C";
static FString HeavyAntiAirTurretName = "/Game/Turrets/BP_HeavyAntiAirTurretActor.BP_HeavyAntiAirTurretActor_C";
static FString AntiAirTurretTurretName = "/Game/Turrets/BP_AntiAirTurretActor.BP_AntiAirTurretActor_C";
static FString DuelTurretName = "/Game/Turrets/BP_DuelCannonTurretActor.BP_DuelCannonTurretActor_C";
static FString AntiPawnTurretName = "/Game/Turrets/BP_AntiPawnTurretActor.BP_AntiPawnTurretActor_C";
static FString PlasmaTurretName = "/Game/Turrets/BP_PlasmaTurretActor.BP_PlasmaTurretActor_C";
ATurretHardPoint::ATurretHardPoint(const class FObjectInitializer& PCIP)
: Super(PCIP)
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
HardpointBase = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("HardpointBase Mesh"));
HardpointBase->SetupAttachment(RootComponent);
TurretAttachment = CreateDefaultSubobject<UTurretAttachmenttComponent>(TEXT("Turret Attachment"));
TurretAttachment->SetupAttachment(HardpointBase);
HardPointAttachment = CreateDefaultSubobject<UHardPointAttachment>(TEXT("HardPoint Attachment"));
HardPointAttachment->SetupAttachment(HardpointBase);
//TurretAttachment->SetRelativeLocation(FVector(0.0f, 0.0f, 113.179932));
UWorld* World = GetWorld();
if (World)
{
}
//importing blueprints
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret(TEXT("/Game/Turrets/BP_LightTurretActor.BP_LightTurretActor_C"));
if (TheTurret.Class != NULL)
{
LightTurretActorClassHolder = TheTurret.Class;
}
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret2(TEXT("/Game/Turrets/BP_MediumTurretActor.BP_MediumTurretActor_C"));
if (TheTurret2.Class != NULL)
{
MediumTurretActorClassHolder = TheTurret2.Class;
}
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret3(TEXT("/Game/Turrets/BP_HeavyTurretActor.BP_HeavyTurretActor_C"));
if (TheTurret3.Class != NULL)
{
HeavyTurretActorClassHolder = TheTurret3.Class;
}
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret4(TEXT("/Game/Turrets/BP_TurretActor.BP_TurretActor_C"));
if (TheTurret4.Class != NULL)
{
TurretActorClassHolder = TheTurret4.Class;
}
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret5(TEXT("/Game/Turrets/BP_HeavyAntiAirTurretActor.BP_HeavyAntiAirTurretActor_C"));
if (TheTurret5.Class != NULL)
{
HeavyAntiAirTurretActorClassHolder = TheTurret5.Class;
}
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret6(TEXT("/Game/Turrets/BP_AntiAirTurretActor.BP_AntiAirTurretActor_C"));
if (TheTurret6.Class != NULL)
{
AntiAirTurretActorClassHolder = TheTurret6.Class;
}
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret8(TEXT("/Game/Turrets/BP_DuelCannonTurretActor.BP_DuelCannonTurretActor_C"));
if (TheTurret8.Class != NULL)
{
DuelTurretActorClassHolder = TheTurret8.Class;
}
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret9(TEXT("/Game/Turrets/BP_AntiPawnTurretActor.BP_AntiPawnTurretActor_C"));
if (TheTurret9.Class != NULL)
{
AntiPawnTurretActorClassHolder = TheTurret9.Class;
}
static ConstructorHelpers::FClassFinder<ATurretActor> TheTurret10(TEXT("/Game/Turrets/BP_PlasmaTurretActor.BP_PlasmaTurretActor_C"));
if (TheTurret10.Class != NULL)
{
PlasmaTurretClassHolder = TheTurret10.Class;
}
}
ATurretHardPoint::ATurretHardPoint()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root Component"));
HardpointBase = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("HardpointBase Mesh"));
HardpointBase->SetupAttachment(RootComponent);
TurretAttachment = CreateDefaultSubobject<UTurretAttachmenttComponent>(TEXT("Turret Attachment"));
TurretAttachment->SetupAttachment(HardpointBase);
//TurretAttachment->SetRelativeLocation(FVector(0.0f, 0.0f,113.179932));
HardPointAttachment = CreateDefaultSubobject<UHardPointAttachment>(TEXT("HardPoint Attachment"));
HardPointAttachment->SetupAttachment(HardpointBase);
}
void ATurretHardPoint::RegisterDelegate()
{
}
void ATurretHardPoint::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
}
void ATurretHardPoint::BeginPlay()
{
Super::BeginPlay();
RegisterDelegate();
UWorld* World = GetWorld();
AGlobalGameState* GS= Cast<AGlobalGameState>(World->GetGameState());
if (GS)
{
//adding the hardpoint to the gamestate and saving the index for fast lookups
int counter = GS->TurretHardPoints.Num();
HardPointIndex = counter;
GS->TurretHardPoints.Add(this);
}
// BuildTurret();
}
void ATurretHardPoint::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
//builds the base turret actor blueprint
void ATurretHardPoint::BuildTurret()
{
if (TurretActorClassHolder != NULL)
{
UWorld* World = GetWorld();
if (World)
{
FActorSpawnParameters SpawnParams;
//SpawnParams.Instigator = this;
ATurretActor* temp = Cast<ATurretActor>(TurretActorClassHolder->GetDefaultObject());
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
ATurretActor* NewTurret = World->SpawnActor<ATurretActor>(TurretActorClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
}
}
}
//builds a turret based on the name of the blueprint passed in, the name will come from the selection rose menu actor
void ATurretHardPoint::BuildTurret(FString TurretName)
{
UWorld* World = GetWorld();
if (World)
{
AGlobalGameState* GS= Cast<AGlobalGameState>(World->GetGameState());
FActorSpawnParameters SpawnParams;
if (TurretName == HeavyTurretName)
{
if (HeavyTurretActorClassHolder != NULL)
{
//getting a temp copy of this turret so we can find all the offsets, proly a much better way to do this. With an array like the muzzle offsets
AHeavyTurretActor* temp = Cast<AHeavyTurretActor>(HeavyTurretActorClassHolder->GetDefaultObject());
//finding the attachment offset for world placement
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
//spawning the turret we will se in the game
AHeavyTurretActor* NewTurret = World->SpawnActor<AHeavyTurretActor>(HeavyTurretActorClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
//telling the gamestae we just built a turret
GS->NewActorSpawned(NewTurret);
//cleaning up
temp->Destroy();
}
}
if (TurretName == MediumTurretTurretName)
{
if (MediumTurretActorClassHolder != NULL)
{
AMediumTurretActor* temp = Cast<AMediumTurretActor>(MediumTurretActorClassHolder->GetDefaultObject());
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
AMediumTurretActor* NewTurret = World->SpawnActor<AMediumTurretActor>(MediumTurretActorClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
GS->NewActorSpawned(NewTurret);
temp->Destroy();
}
}
if (TurretName == LightTurretName)
{
if (LightTurretActorClassHolder != NULL)
{
ALightTurretActor* temp = Cast<ALightTurretActor>(LightTurretActorClassHolder->GetDefaultObject());
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
ALightTurretActor* NewTurret = World->SpawnActor<ALightTurretActor>(LightTurretActorClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
GS->NewActorSpawned(NewTurret);
}
}
if (TurretName == HeavyAntiAirTurretName)
{
if (HeavyAntiAirTurretActorClassHolder != NULL)
{
AHeavyAntiAirTurretActor* temp = Cast<AHeavyAntiAirTurretActor>(HeavyAntiAirTurretActorClassHolder->GetDefaultObject());
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
AHeavyAntiAirTurretActor* NewTurret = World->SpawnActor<AHeavyAntiAirTurretActor>(HeavyAntiAirTurretActorClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
GS->NewActorSpawned(NewTurret);
temp->Destroy();
}
}
if (TurretName == AntiAirTurretTurretName)
{
if (AntiAirTurretActorClassHolder != NULL)
{
AAntiAirTurretActor* temp = Cast<AAntiAirTurretActor>(AntiAirTurretActorClassHolder->GetDefaultObject());
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
AAntiAirTurretActor* NewTurret = World->SpawnActor<AAntiAirTurretActor>(AntiAirTurretActorClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
GS->NewActorSpawned(NewTurret);
temp->Destroy();
}
}
if (TurretName == DuelTurretName)
{
if (DuelTurretActorClassHolder != NULL)
{
ADuelCannonTurretActor* temp = Cast<ADuelCannonTurretActor>(DuelTurretActorClassHolder->GetDefaultObject());
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
ADuelCannonTurretActor* NewTurret = World->SpawnActor<ADuelCannonTurretActor>(DuelTurretActorClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
GS->NewActorSpawned(NewTurret);
temp->Destroy();
}
}
if (TurretName == AntiPawnTurretName)
{
if (AntiPawnTurretActorClassHolder != NULL)
{
AAntiPawnTurretActor* temp = Cast<AAntiPawnTurretActor>(AntiPawnTurretActorClassHolder->GetDefaultObject());
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
AAntiPawnTurretActor* NewTurret = World->SpawnActor<AAntiPawnTurretActor>(AntiPawnTurretActorClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
GS->NewActorSpawned(NewTurret);
temp->Destroy();
}
}
if (TurretName == PlasmaTurretName)
{
if (PlasmaTurretClassHolder != NULL)
{
APlasmaTurretActor* temp = Cast<APlasmaTurretActor>(PlasmaTurretClassHolder->GetDefaultObject());
FVector tempV = temp->TurretAttachment->RelativeLocation;
FVector tempV2 = TurretAttachment->RelativeLocation;
FVector tempV3 = GetActorLocation() + tempV2 + tempV;
APlasmaTurretActor* NewTurret = World->SpawnActor<APlasmaTurretActor>(PlasmaTurretClassHolder, tempV3, FRotator(0.0f, 0.0f, 0.0f), SpawnParams);
GS->NewActorSpawned(NewTurret);
temp->Destroy();
}
}
}
}
void ATurretHardPoint::RunCommand(FString command)
{
BuildTurret(command);
}
|
[
"justin_beast@hotmail.com"
] |
justin_beast@hotmail.com
|
cc3e9c0bf3097bb6e03cc0b0ef011f4d90a5291c
|
19cd9c1397558dc2c815ad10e354a8b7a7b0ea47
|
/scemi/scemi_pipes.cc
|
db8151e99a83f507ec2d5edfa58b23d77a180374
|
[
"MIT"
] |
permissive
|
Arja7/scemi_lib
|
1741898e68465d083ade38b49498ff09eee77811
|
2358f613a4defe613493a68094c313cb0f570d47
|
refs/heads/master
| 2023-06-22T06:51:37.480323
| 2019-07-13T17:25:07
| 2019-07-13T17:25:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,260
|
cc
|
#include <fcntl.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <unistd.h>
#include <inttypes.h>
#include <errno.h>
#include <cstring>
#include <string>
#include <map>
#include <queue>
#include "vpi_user.h"
#include "scemi_defines.h"
#include "scemi_pipes.h"
static unsigned char fifoi[RWBUF_SIZE];
static unsigned char fifoo[RWBUF_SIZE];
static svScope svscope = NULL, svpscope = NULL;
static bool SceMiFinish = false, data_keeper_vpi = true;
static uint32_t process_tokens(uint32_t cmd, uint32_t num_args, uint32_t idx);
static void * _scemi_pipe_c_handle( uint32_t uid );
static void scemi_data_keeper();
static void scemi_final_cleanup();
struct InBuffer {
unsigned char *buf; /* That holds data */
uint16_t lidx, idx; /* read index */
int file_id;
bool init_done;
InBuffer(unsigned char *b) {
buf = b;
lidx = idx = 0;
init_done = false;
}
void Init() {
errno = 0;
file_id = open(SVC_FIFO_R, O_RDONLY);
// DBG_PRINT("%s file_id:%d errno:%d\n", SVC_FIFO_R, file_id, errno);
assert ((-1 != file_id) && (0 == errno));
int flags = fcntl(file_id, F_GETFL, 0);
assert(0 == fcntl(file_id, F_SETFL, flags | O_NONBLOCK));
init_done = true;
}
~InBuffer() {
close(file_id);
scemi_final_cleanup();
}
void clear() {
if (lidx == idx) {
lidx = idx = 0;
return;
}
if (0 != idx) {
bcopy((char *)buf+idx, (char *)buf, lidx-idx);
lidx -= idx;
idx = 0;
}
}
bool get_token_valid(uint32_t t_idx) {
return init_done && (t_idx < lidx) && ((lidx-t_idx) >= sizeof(uint32_t));
}
uint32_t get_token(uint32_t t_idx) {
uint32_t dt=0, ui1=0;
for (; (ui1<sizeof(uint32_t)); ui1++, t_idx++) {
dt |= uint32_t(buf[t_idx])<<(ui1<<3);
}
return dt;
}
int32_t data_keeper() {
clear();
errno = 0;
int32_t count = read(file_id, buf+idx, RWBUF_SIZE-idx);
if (count < 0) {
assert(EAGAIN == errno);
return errno;
} else if (0 == count) {
return 0;
}
lidx += count;
/* We are attempting to read RWBUF_SIZE data. So
in theory lidx could be == RWBUF_SIZE. */
assert(lidx <= RWBUF_SIZE);
/* Process the data : Packet info
SCEMI_CMD, [DEST], NUM_ARGS, __VA_ARGS__
process only if you have on complete transactions
*/
do {
uint32_t cmd = get_token(idx);
uint32_t num_args = get_token(idx+sizeof(uint32_t));
if ( get_token_valid(idx+sizeof(uint32_t)) &&
get_token_valid(idx+((2/*CMD, NUM_ARGS*/+num_args-1)*sizeof(uint32_t))) ) {
idx += process_tokens(cmd, num_args, idx);
} else break;
} while (idx < lidx);
#ifndef SVC_DUT
if (svscope) {
svSetScope(svscope);
scemi_data_avail_trigger();
}
#endif
return 0;
}
uint32_t process_tokens(uint32_t cmd, uint32_t num_args, uint32_t idx);
};
struct OutBuffer {
unsigned char *buf; /* That holds data */
uint16_t idx; /* index */
int file_id;
bool init_done;
OutBuffer(unsigned char *b) {
buf = b;
idx = 0;
init_done = false;
}
void Init() {
errno = 0;
file_id = open(SVC_FIFO, O_WRONLY | O_SYNC, 0);
// DBG_PRINT("%s file_id:%d errno:%d\n", SVC_FIFO, file_id, errno);
assert ((-1 != file_id) && (0 == errno));
init_done = true;
}
~OutBuffer() {
close(file_id);
}
bool can_put(uint32_t n) {
return init_done && (((sizeof(uint32_t)*n) + idx) <= RWBUF_SIZE);
}
/* Only support integers */
void put(uint32_t v) {
/* if can't hold the value, flush */
if ((sizeof(uint32_t) + idx) > RWBUF_SIZE)
flush();
for (uint32_t ui1=0; ui1<sizeof(uint32_t); ui1++, idx++) {
buf[idx] = v >> (ui1<<3);
}
assert(idx <= RWBUF_SIZE);
}
#if 0
void put_vaargs(uint32_t n, ...) {
uint32_t dat;
va_list argp;
va_start (argp, n);
for (uint32_t ui2=0; ui2<n; ui2++) {
dat = va_arg(argp, uint32_t);
/* if can't hold the value, flush */
if ((sizeof(uint32_t) + idx) > RWBUF_SIZE)
flush();
for (uint32_t ui1=0; ui1<sizeof(uint32_t); ui1++, idx++) {
buf[idx] = dat >> (ui1<<3);
}
}
va_end(argp);
assert (idx <= RWBUF_SIZE);
}
#endif
void flush() {
if (! init_done) return;
if (idx) DBG_PRINT("Flushing Out Stream:");
for (uint32_t ui1=0; ui1<idx; ui1++) { DBG_PRINT("%3x", buf[ui1]); }
if (idx) DBG_PRINT("\n");
write(file_id, buf, idx);
idx = 0;
}
};
enum {DIR_OUT, DIR_IN};
typedef std::map<void *, void*> udata_t;
struct Pipe {
uint32_t uid;
uint16_t bytes_per_element, callback_threshold, pending_data;
uint8_t direction, auto_flush, connected;
std::queue<uint32_t> data;
std::queue<uint32_t> data_buf;
udata_t udata;
scemi_pipe_notify_callback notify_callback;
void* notify_context;
Pipe(uint32_t uid_l) {
uid = uid_l;
direction = DIR_OUT;
bytes_per_element = connected = 0;
pending_data = callback_threshold = 0;
notify_callback = NULL;
}
};
static InBuffer inbuf(fifoi);
static OutBuffer outbuf(fifoo);
typedef std::map<uint32_t, struct Pipe *> hash2path_t;
typedef std::map<uint32_t, std::string> hash2name_t;
static hash2path_t hash2path;
extern "C"
unsigned int
scemi_shash(char* s)
{
unsigned int hash = 5381;
int c;
while ((c = *s++)) {
/* hash = hash * 33 ^ c */
hash = ((hash << 5) + hash) + c;
}
return hash;
}
uint32_t
InBuffer::process_tokens(uint32_t cmd, uint32_t num_args, uint32_t idx)
{
uint32_t uid = get_token(idx+(2/*CMD, NUM_ARGS*/+1-1)*sizeof(uint32_t));
Pipe *p = (Pipe *)_scemi_pipe_c_handle(uid);
if (SCMD_CONNECT_PATH == cmd) {
assert(3 == num_args);
p->bytes_per_element = get_token(idx+(2/*CMD, NUM_ARGS*/+2-1)*sizeof(uint32_t));
p->direction = get_token(idx+(2/*CMD, NUM_ARGS*/+3-1)*sizeof(uint32_t));
DBG_PRINT("Obtained command SCMD_CONNECT_PATH: uid:%x bytes_per_element:%u p->direction:%u\n", uid, p->bytes_per_element, p->direction);
p->connected = 1;
assert(p->bytes_per_element > 0);
assert(0 == (p->bytes_per_element % sizeof(svBitVecVal)));
} else if (SCMD_DATA == cmd) {
assert(num_args > 1);
p->data.push(SCMD_DATA);
p->data.push(num_args-1); /* num args */
DBG_PRINT("Obtained command SCMD_DATA num_args:%u uid:%x", num_args, uid);
for (uint32_t t_ui1=2; t_ui1<=num_args; t_ui1++) {
uint32_t t_ui2 = get_token(idx+(2/*CMD, NUM_ARGS*/+t_ui1-1)*sizeof(uint32_t));
p->data.push(t_ui2);
DBG_PRINT(" %u:%8x", t_ui1, t_ui2);
}
DBG_PRINT("\n");
/* callback */
p->pending_data++;
if ((NULL != p->notify_callback) && (p->pending_data > p->callback_threshold)) {
(*(p->notify_callback))(p->notify_context);
}
} else if (SCMD_DATA_EOM == cmd) {
DBG_PRINT("Obtained command SCMD_DATA_EOM\n");
p->data.push(SCMD_DATA_EOM);
} else if (SCMD_FINISH == cmd) {
DBG_PRINT("Obtained command SCMD_FINISH\n");
SceMiFinish = true;
} else {
DBG_PRINT("Unknown cmd %u\n", cmd);
assert(0);
}
return (2/*CMD, ARGS*/+num_args)*sizeof(uint32_t);
}
extern "C"
PLI_INT32
scemi_data_keeper_callback
(struct t_cb_data *cbd)
{
/* */
if ( (! inbuf.init_done) || (! outbuf.init_done) ) {
scemi_data_keeper();
return 0;
}
/* housekeeping 1: flush outbuf */
int32_t ret_val = inbuf.data_keeper();
scemi_data_keeper();
if ((0 != ret_val) && (EAGAIN != ret_val)) {
DBG_PRINT("Some problem with Communications channel, Triggering Finish\n");
SceMiFinish = true;
}
/* housekeeping 2: flush outbuf */
outbuf.flush();
return 0;
}
static
void
scemi_data_keeper()
{
if (! data_keeper_vpi) return;
s_cb_data cbData;
cbData.reason = cbNextSimTime;
cbData.cb_rtn = scemi_data_keeper_callback;
cbData.time = NULL;
cbData.value = NULL;
cbData.obj = NULL;
cbData.user_data = NULL;
vpiHandle cbHandle = vpi_register_cb(&cbData);
vpi_free_object(cbHandle);
}
static
void * // return: pipe handle
_scemi_pipe_c_handle( uint32_t uid ) // input: path to HDL endpoint instance
{
/* if pipe available return the same */
hash2path_t::iterator it = hash2path.find(uid);
if (it != hash2path.end()) {
return it->second;
}
/* new object */
Pipe *p = new Pipe(uid);
hash2path.insert( std::pair<uint32_t, struct Pipe *>(uid, p) );
return p;
}
void * // return: pipe handle
scemi_pipe_c_handle( const char *endpoint_path ) // input: path to HDL endpoint instance
{
uint32_t uid = scemi_shash((char *)endpoint_path);
return _scemi_pipe_c_handle(uid);
}
svBit // return: 1 for input pipe, 0 for output pipe
scemi_pipe_get_direction( void *pipe_handle ) // input: pipe handle
{
return static_cast<struct Pipe *>(pipe_handle)->direction;
}
int // return: current depth (in elements) of the pipe
scemi_pipe_get_depth( void *pipe_handle ) // input: pipe handle
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
return (int)((RWBUF_SIZE-outbuf.idx) / p->bytes_per_element);
}
int // return: bytes per element
scemi_pipe_get_bytes_per_element( void *pipe_handle ) // input: pipe handle
{
return static_cast<struct Pipe *>(pipe_handle)->bytes_per_element;
}
svBit
scemi_pipe_set_eom_auto_flush( void *pipe_handle, svBit enabled ) // input: enable/disable
{
return static_cast<struct Pipe *>(pipe_handle)->auto_flush = enabled;
}
extern "C"
void
scemi_initialize()
{
static bool init_done = false;
/* make sure you don't init twice */
if (init_done) return;
init_done = true;
#ifdef SVC_DUT
inbuf.Init();
outbuf.Init();
#else
outbuf.Init();
inbuf.Init();
#endif
svscope = svGetScopeFromName(SVC_SV_SCOPE);
svpscope = svGetScopeFromName(SVC_SVP_SCOPE);
scemi_data_keeper();
}
static
void
scemi_final_cleanup()
{
for (hash2path_t::iterator it = hash2path.begin(); it!=hash2path.end(); it++) {
delete it->second;
}
}
extern "C"
void
scemi_pipes_finish()
{
SceMiFinish = true;
outbuf.put(SCMD_FINISH);
outbuf.put(0);
outbuf.flush();
}
void
scemi_pipe_c_send_data (
void *pipe_handle,
uint32_t data)
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
p->data_buf.push(data);
}
void
scemi_pipe_c_send_nodata (
void *pipe_handle, // input: pipe handle
int num_elements, // input: #elements to be written
svBit eom ) // input: end-of-message marker flag (and flush)
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
if (! p->connected) {
svSetScope(svpscope);
ERROR("Attempt to send to '%s' before establishing connection\n", hash2string(p->uid));
return;
}
for (uint32_t elem=0; elem<num_elements; elem++) {
/* */
uint32_t num_args = (p->bytes_per_element/sizeof(svBitVecVal)) + 1; /* UID */
outbuf.put(SCMD_DATA);
outbuf.put(num_args);
outbuf.put(p->uid);
/* */
for (uint32_t ui1=0; ui1<(p->bytes_per_element/sizeof(svBitVecVal)); ui1++) {
assert(! (p->data_buf.empty()));
outbuf.put((uint32_t)(p->data_buf.front()));
p->data_buf.pop();
}
}
/* */
if (0 != num_elements) {
if (eom && p->auto_flush) {
outbuf.put(SCMD_DATA_EOM);
outbuf.put(1);
outbuf.put(p->uid);
outbuf.flush();
}
}
}
void
scemi_pipe_c_send (
void *pipe_handle, // input: pipe handle
int num_elements, // input: #elements to be written
const svBitVecVal *data, // input: data
svBit eom ) // input: end-of-message marker flag (and flush)
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
if (! p->connected) {
ERROR("Attempt to send in pipe '%s' before establishing connection\n", hash2string(p->uid));
return;
}
for (uint32_t elem=0; elem<num_elements; elem++) {
/* */
uint32_t num_args = (p->bytes_per_element/sizeof(svBitVecVal)) + 1; /* UID */
outbuf.put(SCMD_DATA);
outbuf.put(num_args);
outbuf.put(p->uid);
/* */
for (uint32_t ui1=0; ui1<(p->bytes_per_element/sizeof(svBitVecVal)); ui1++) {
outbuf.put((uint32_t)data[ui1]);
}
}
/* */
if (0 != num_elements) {
if (eom && p->auto_flush) {
outbuf.put(SCMD_DATA_EOM);
outbuf.put(1);
outbuf.put(p->uid);
outbuf.flush();
}
}
}
int /* # elements sent */
scemi_pipe_c_try_send (
void *pipe_handle, // input: pipe handle
int byte_offset, // input: byte offset within data array
int num_elements, // input: #elements to be written
const svBitVecVal *data, // input: data
svBit eom ) // input: end-of-message marker flag
{
scemi_pipe_c_send(pipe_handle, num_elements-byte_offset, data, eom);
return num_elements;
}
void
scemi_pipe_c_flush( void *pipe_handle ) // input: pipe handle
{
outbuf.flush();
}
int
scemi_pipe_c_try_flush( void *pipe_handle ) // input: pipe handle
{
scemi_pipe_c_flush( pipe_handle );
return 1;
}
svBit // return: whether pipe is in Flush state
scemi_pipe_c_in_flush_state( void *pipe_handle ) // input: pipe handle
{
return (0 == outbuf.idx) ? 1 : 0;
}
int
scemi_pipe_c_can_send( void *pipe_handle )
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
return (DIR_OUT == p->direction) ? 1 : 0;
}
int
scemi_pipe_c_can_receive( void *pipe_handle )
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
return (DIR_IN == p->direction) ? 1 : 0;
}
void
scemi_pipe_put_user_data (
void *pipe_handle, // input: pipe handle
void *user_key, // input: user key
void *user_data ) // input: user data
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
p->udata.insert( std::pair<void *, void *>(user_key, user_data) );
}
void *
scemi_pipe_get_user_data (
void *pipe_handle, // input: pipe handle
void *user_key ) // input: user key
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
udata_t::iterator it = p->udata.find(user_key);
return (it != p->udata.end()) ? it->second: NULL;
}
uint32_t
scemi_pipe_c_receive_data ( void *pipe_handle )
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
assert (! (p->data_buf.empty()));
uint32_t ret_val = p->data_buf.front();
p->data_buf.pop();
return ret_val;
}
void
scemi_pipe_c_receive_nodata (
void *pipe_handle, // input: pipe handle
int num_elements, // input: #elements to be read
int *num_elements_valid, // output: #elements that are valid
svBit *eom ) // output: end-of-message marker flag (and flush)
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
*num_elements_valid = 0;
*eom = 0;
if ((p->data.empty()) || !(p->connected)) {
return;
}
uint32_t data_idx = 0;
do {
uint32_t cmd = p->data.front(); p->data.pop();
if (SCMD_DATA == cmd) {
uint32_t num_args = p->data.front(); p->data.pop();
for (uint32_t ui1=0; ui1<num_args; data_idx++, ui1++) {
assert(! p->data.empty());
p->data_buf.push(p->data.front());
// DBG_PRINT("Receiving data %x\n", p->data.front());
p->data.pop();
}
(*num_elements_valid)++;
assert(p->pending_data > 0);
p->pending_data--;
} else if (SCMD_DATA_EOM == cmd) {
*eom = 1;
break;
} else { /* Unknown command */
assert(0);
}
} while ((! p->data.empty()) && ((*num_elements_valid) < num_elements));
}
void
scemi_pipe_c_receive (
void *pipe_handle, // input: pipe handle
int num_elements, // input: #elements to be read
int *num_elements_valid, // output: #elements that are valid
svBitVecVal *data, // output: data
svBit *eom ) // output: end-of-message marker flag (and flush)
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
*num_elements_valid = 0;
*eom = 0;
if ((p->data.empty()) || !(p->connected)) {
return;
}
uint32_t data_idx = 0;
do {
uint32_t cmd = p->data.front(); p->data.pop();
if (SCMD_DATA == cmd) {
uint32_t num_args = p->data.front(); p->data.pop();
for (uint32_t ui1=0; ui1<num_args; data_idx++, ui1++) {
assert(! p->data.empty());
data[data_idx] = p->data.front();
// DBG_PRINT("Receiving data %x\n", p->data.front());
p->data.pop();
}
(*num_elements_valid)++;
assert(p->pending_data > 0);
p->pending_data--;
} else if (SCMD_DATA_EOM == cmd) {
*eom = 1;
break;
} else { /* Unknown command */
assert(0);
}
} while ((! p->data.empty()) && ((*num_elements_valid) < num_elements));
}
int /* # elements received */
scemi_pipe_c_try_receive (
void *pipe_handle, // input: pipe handle
int byte_offset, // input: byte offset within data array
int num_elements, // input: #elements to be read
svBitVecVal *data, // output: data
svBit *eom ) // output: end-of-message marker flag
{
int num_elem_received = 0;
/* num_elem_received is returned as byte_offset after mult with p->bytes_per_element */
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
uint32_t offset_svbitvec = byte_offset / p->bytes_per_element;
scemi_pipe_c_receive(pipe_handle, num_elements, &num_elem_received, data+offset_svbitvec, eom);
return num_elem_received;
}
scemi_pipe_notify_callback_handle
scemi_pipe_set_notify_callback (
void *pipe_handle, // input: pipe handle
scemi_pipe_notify_callback notify_callback, // input: notify callback function
void *notify_context, // input: notify context
int callback_threshold ) // input: threshold for notify callback function
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
p->notify_callback = notify_callback;
p->notify_context = notify_context;
p->callback_threshold = callback_threshold;
return pipe_handle;
}
void
scemi_pipe_clear_notify_callback (
scemi_pipe_notify_callback_handle notify_callback_handle )
{
Pipe *p = static_cast<struct Pipe *>(notify_callback_handle);
p->notify_callback = NULL;
}
void * //return: notify context object pointer
scemi_pipe_get_notify_context(
scemi_pipe_notify_callback_handle notify_callback_handle ) // input: notify handle
{
Pipe *p = static_cast<struct Pipe *>(notify_callback_handle);
return p->notify_context;
}
uint32_t
scemi_pipe_pending_data(void *pipe_handle)
{
return static_cast<struct Pipe *>(pipe_handle)->pending_data;
}
extern "C"
void
scemi_pipe_outport_configure(void *pipe_handle, int unsigned num_bits)
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
/* */
p->bytes_per_element = ((num_bits+31)/32)*sizeof(uint32_t);
p->direction = DIR_OUT;
p->connected = 1;
/* */
outbuf.put(SCMD_CONNECT_PATH);
outbuf.put(3);
outbuf.put(p->uid);
outbuf.put(p->bytes_per_element);
outbuf.put(p->direction);
}
extern "C"
void
scemi_pipe_inport_configure(void *pipe_handle, int unsigned num_bits)
{
Pipe *p = static_cast<struct Pipe *>(pipe_handle);
/* */
p->bytes_per_element = ((num_bits+31)/32)*sizeof(uint32_t);
p->direction = DIR_IN;
p->connected = 1;
/* */
outbuf.put(SCMD_CONNECT_PATH);
outbuf.put(3);
outbuf.put(p->uid);
outbuf.put(p->bytes_per_element);
outbuf.put(p->direction);
}
|
[
"narenkn@gmail.com"
] |
narenkn@gmail.com
|
992ec6199433c68edc229631b2a0cbb415a0c276
|
4ba0b403637e7aa3e18c9bafae32034e3c394fe4
|
/cplusplus/eLang/eLang/el_sequence_expr.h
|
e005739943d6fa4c4d2fccf7ed940186a0bbef3a
|
[] |
no_license
|
ASMlover/study
|
3767868ddae63ac996e91b73700d40595dd1450f
|
1331c8861fcefbef2813a2bdd1ee09c1f1ee46d6
|
refs/heads/master
| 2023-09-06T06:45:45.596981
| 2023-09-01T08:19:49
| 2023-09-01T08:19:49
| 7,519,677
| 23
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,044
|
h
|
// Copyright (c) 2015 ASMlover. 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 ofconditions 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 materialsprovided 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 __EL_SEQUENCE_EXPR_HEADER_H__
#define __EL_SEQUENCE_EXPR_HEADER_H__
#include "el_expr.h"
#include "el_expr_compiler_base.h"
namespace el {
class SequenceExpr : public Expr {
Array<Ref<Expr> > expressions_;
public:
explicit SequenceExpr(const Array<Ref<Expr> >& expressions)
: expressions_(expressions) {
}
inline const Array<Ref<Expr> >& Expressions(void) const {
return expressions_;
}
virtual void Trace(std::ostream& stream) const override {
stream << expressions_[0];
for (auto i = 1; i < expressions_.Count(); ++i)
stream << "; " << expressions_[i];
}
EL_EXPR_VISITOR
};
}
#endif // __EL_SEQUENCE_EXPR_HEADER_H__
|
[
"asmlover@126.com"
] |
asmlover@126.com
|
b080b223a919a845787503a33a0650ee5e53e46c
|
240259adb5fd085aecac513b73e316d869a4f877
|
/CodeJam_qualification_2021/Reversort_Engineering.cpp
|
73980276199177163d5f3d4c1de09af2bddd5811
|
[] |
no_license
|
sumandutta8877/CP
|
11aba5a77d6494aff314a522ec82d680415f31b0
|
dbdf74cd1759bfaf1e8605b1f0d7b49c0e6fa83c
|
refs/heads/main
| 2023-05-29T07:44:55.236913
| 2021-06-20T07:46:05
| 2021-06-20T07:46:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,094
|
cpp
|
//! ╭━━━╮╱╱╱╱╱╱╱╱╭╮╱╱╱╭━━━┳━━━╮
//! ┃╭━╮┃╱╱╱╱╱╱╱╭╯╰╮╱╱┃╭━╮┃╭━╮┃
//? ┃┃╱┃┣━┳┳━━┳━┻╮╭╋━━┫┃┃┃┣╯╭╯┃
//? ┃╰━╯┃╭╋┫╭╮┃╭╮┃┃┃╭╮┃┃┃┃┃╱┃╭╯
//? ┃╭━╮┃┃┃┃╰╯┃╭╮┃╰┫╰╯┃╰━╯┃╱┃┃
//? ╰╯╱╰┻╯╰┻━╮┣╯╰┻━┻━━┻━━━╯╱╰╯
//* ╱╱╱╱╱╱╱╭━╯┃
//* ╱╱╱╱╱╱╱╰━━╯
#include <bits/stdc++.h>
using namespace std;
#define fo(i, a, n) for (i = a; i < n; i++)
#define ll long long
#define deb(x) cout << #x << '=' << x << endl
#define deb2(x, y) cout << #x << '=' << x << ',' << #y << '=' << y << endl
#define clr(x) memset(x, 0, sizeof(x))
#define PI 3.1415926535897932384626
#define pb push_back
//===========================
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
typedef vector<vl> vvl;
//=======================
const int MOD = 1'000'000'007;
const int N = INT_MAX, M = N;
//=======================
void solve()
{
int i, j, c, n, m, k;
ll temp = 0, flag = 1;
cin >> n >> c;
if (c < n - 1)
{
cout << "IMPOSSIBLE" << endl;
return;
}
vl A;
c -= n - 1;
for (i = n - 1; i >= 1; i--)
{
if (c - i >= 0)
{
A.pb(i);
c -= i;
}
}
if (c)
{
cout << "IMPOSSIBLE" << endl;
return;
}
vi ans(n);
fo(i, 0, n)
{
ans[i] = i + 1;
}
reverse(A.begin(), A.end());
for (auto x : A)
{
// cout << x << " ";
reverse(ans.end() - x - 1, ans.end());
}
// cout << endl;
fo(i, 0, n)
{
cout << ans[i] << " ";
}
cout << endl;
}
int main()
{
int t = 1;
cin >> t;
int k = 1;
while (t--)
{
cout << "Case #" << k << ": ";
solve();
k++;
}
return 0;
}
//=======================
|
[
"dbdibyendu5@gmail.com"
] |
dbdibyendu5@gmail.com
|
430f435a74ab4821f3a5b12bb7678d09002bee5b
|
9d364070c646239b2efad7abbab58f4ad602ef7b
|
/platform/external/chromium_org/media/base/mock_filters.h
|
ccf28d0806de20ab60efec263101107a2a6a5576
|
[
"BSD-3-Clause"
] |
permissive
|
denix123/a32_ul
|
4ffe304b13c1266b6c7409d790979eb8e3b0379c
|
b2fd25640704f37d5248da9cc147ed267d4771c2
|
refs/heads/master
| 2021-01-17T20:21:17.196296
| 2016-08-16T04:30:53
| 2016-08-16T04:30:53
| 65,786,970
| 0
| 2
| null | 2020-03-06T22:00:52
| 2016-08-16T04:15:54
| null |
UTF-8
|
C++
| false
| false
| 8,336
|
h
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_BASE_MOCK_FILTERS_H_
#define MEDIA_BASE_MOCK_FILTERS_H_
#include <string>
#include "base/callback.h"
#include "media/base/audio_decoder.h"
#include "media/base/audio_decoder_config.h"
#include "media/base/audio_renderer.h"
#include "media/base/decoder_buffer.h"
#include "media/base/decryptor.h"
#include "media/base/demuxer.h"
#include "media/base/pipeline_status.h"
#include "media/base/renderer.h"
#include "media/base/text_track.h"
#include "media/base/time_source.h"
#include "media/base/video_decoder.h"
#include "media/base/video_decoder_config.h"
#include "media/base/video_frame.h"
#include "media/base/video_renderer.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace media {
class MockDemuxer : public Demuxer {
public:
MockDemuxer();
virtual ~MockDemuxer();
MOCK_METHOD3(Initialize,
void(DemuxerHost* host, const PipelineStatusCB& cb, bool));
MOCK_METHOD1(SetPlaybackRate, void(float playback_rate));
MOCK_METHOD2(Seek, void(base::TimeDelta time, const PipelineStatusCB& cb));
MOCK_METHOD0(Stop, void());
MOCK_METHOD0(OnAudioRendererDisabled, void());
MOCK_METHOD1(GetStream, DemuxerStream*(DemuxerStream::Type));
MOCK_CONST_METHOD0(GetStartTime, base::TimeDelta());
MOCK_CONST_METHOD0(GetTimelineOffset, base::Time());
MOCK_CONST_METHOD0(GetLiveness, Liveness());
private:
DISALLOW_COPY_AND_ASSIGN(MockDemuxer);
};
class MockDemuxerStream : public DemuxerStream {
public:
explicit MockDemuxerStream(DemuxerStream::Type type);
virtual ~MockDemuxerStream();
virtual Type type() OVERRIDE;
MOCK_METHOD1(Read, void(const ReadCB& read_cb));
virtual AudioDecoderConfig audio_decoder_config() OVERRIDE;
virtual VideoDecoderConfig video_decoder_config() OVERRIDE;
MOCK_METHOD0(EnableBitstreamConverter, void());
MOCK_METHOD0(SupportsConfigChanges, bool());
void set_audio_decoder_config(const AudioDecoderConfig& config);
void set_video_decoder_config(const VideoDecoderConfig& config);
virtual VideoRotation video_rotation() OVERRIDE;
private:
DemuxerStream::Type type_;
AudioDecoderConfig audio_decoder_config_;
VideoDecoderConfig video_decoder_config_;
DISALLOW_COPY_AND_ASSIGN(MockDemuxerStream);
};
class MockVideoDecoder : public VideoDecoder {
public:
MockVideoDecoder();
virtual ~MockVideoDecoder();
virtual std::string GetDisplayName() const;
MOCK_METHOD4(Initialize, void(const VideoDecoderConfig& config,
bool low_delay,
const PipelineStatusCB& status_cb,
const OutputCB& output_cb));
MOCK_METHOD2(Decode, void(const scoped_refptr<DecoderBuffer>& buffer,
const DecodeCB&));
MOCK_METHOD1(Reset, void(const base::Closure&));
MOCK_CONST_METHOD0(HasAlpha, bool());
private:
DISALLOW_COPY_AND_ASSIGN(MockVideoDecoder);
};
class MockAudioDecoder : public AudioDecoder {
public:
MockAudioDecoder();
virtual ~MockAudioDecoder();
virtual std::string GetDisplayName() const;
MOCK_METHOD3(Initialize,
void(const AudioDecoderConfig& config,
const PipelineStatusCB& status_cb,
const OutputCB& output_cb));
MOCK_METHOD2(Decode,
void(const scoped_refptr<DecoderBuffer>& buffer,
const DecodeCB&));
MOCK_METHOD1(Reset, void(const base::Closure&));
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioDecoder);
};
class MockVideoRenderer : public VideoRenderer {
public:
MockVideoRenderer();
virtual ~MockVideoRenderer();
MOCK_METHOD8(Initialize, void(DemuxerStream* stream,
bool low_delay,
const PipelineStatusCB& init_cb,
const StatisticsCB& statistics_cb,
const BufferingStateCB& buffering_state_cb,
const base::Closure& ended_cb,
const PipelineStatusCB& error_cb,
const TimeDeltaCB& get_time_cb));
MOCK_METHOD1(Flush, void(const base::Closure& callback));
MOCK_METHOD1(StartPlayingFrom, void(base::TimeDelta));
private:
DISALLOW_COPY_AND_ASSIGN(MockVideoRenderer);
};
class MockAudioRenderer : public AudioRenderer {
public:
MockAudioRenderer();
virtual ~MockAudioRenderer();
MOCK_METHOD6(Initialize, void(DemuxerStream* stream,
const PipelineStatusCB& init_cb,
const StatisticsCB& statistics_cb,
const BufferingStateCB& buffering_state_cb,
const base::Closure& ended_cb,
const PipelineStatusCB& error_cb));
MOCK_METHOD0(GetTimeSource, TimeSource*());
MOCK_METHOD1(Flush, void(const base::Closure& callback));
MOCK_METHOD0(StartPlaying, void());
MOCK_METHOD1(SetVolume, void(float volume));
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioRenderer);
};
class MockRenderer : public Renderer {
public:
MockRenderer();
virtual ~MockRenderer();
MOCK_METHOD5(Initialize, void(const base::Closure& init_cb,
const StatisticsCB& statistics_cb,
const base::Closure& ended_cb,
const PipelineStatusCB& error_cb,
const BufferingStateCB& buffering_state_cb));
MOCK_METHOD1(Flush, void(const base::Closure& flush_cb));
MOCK_METHOD1(StartPlayingFrom, void(base::TimeDelta timestamp));
MOCK_METHOD1(SetPlaybackRate, void(float playback_rate));
MOCK_METHOD1(SetVolume, void(float volume));
MOCK_METHOD0(GetMediaTime, base::TimeDelta());
MOCK_METHOD0(HasAudio, bool());
MOCK_METHOD0(HasVideo, bool());
MOCK_METHOD1(SetCdm, void(MediaKeys* cdm));
private:
DISALLOW_COPY_AND_ASSIGN(MockRenderer);
};
class MockTimeSource : public TimeSource {
public:
MockTimeSource();
virtual ~MockTimeSource();
MOCK_METHOD0(StartTicking, void());
MOCK_METHOD0(StopTicking, void());
MOCK_METHOD1(SetPlaybackRate, void(float));
MOCK_METHOD1(SetMediaTime, void(base::TimeDelta));
MOCK_METHOD0(CurrentMediaTime, base::TimeDelta());
MOCK_METHOD0(CurrentMediaTimeForSyncingVideo, base::TimeDelta());
private:
DISALLOW_COPY_AND_ASSIGN(MockTimeSource);
};
class MockTextTrack : public TextTrack {
public:
MockTextTrack();
virtual ~MockTextTrack();
MOCK_METHOD5(addWebVTTCue, void(const base::TimeDelta& start,
const base::TimeDelta& end,
const std::string& id,
const std::string& content,
const std::string& settings));
private:
DISALLOW_COPY_AND_ASSIGN(MockTextTrack);
};
class MockDecryptor : public Decryptor {
public:
MockDecryptor();
virtual ~MockDecryptor();
MOCK_METHOD2(RegisterNewKeyCB, void(StreamType stream_type,
const NewKeyCB& new_key_cb));
MOCK_METHOD3(Decrypt, void(StreamType stream_type,
const scoped_refptr<DecoderBuffer>& encrypted,
const DecryptCB& decrypt_cb));
MOCK_METHOD1(CancelDecrypt, void(StreamType stream_type));
MOCK_METHOD2(InitializeAudioDecoder,
void(const AudioDecoderConfig& config,
const DecoderInitCB& init_cb));
MOCK_METHOD2(InitializeVideoDecoder,
void(const VideoDecoderConfig& config,
const DecoderInitCB& init_cb));
MOCK_METHOD2(DecryptAndDecodeAudio,
void(const scoped_refptr<media::DecoderBuffer>& encrypted,
const AudioDecodeCB& audio_decode_cb));
MOCK_METHOD2(DecryptAndDecodeVideo,
void(const scoped_refptr<media::DecoderBuffer>& encrypted,
const VideoDecodeCB& video_decode_cb));
MOCK_METHOD1(ResetDecoder, void(StreamType stream_type));
MOCK_METHOD1(DeinitializeDecoder, void(StreamType stream_type));
private:
DISALLOW_COPY_AND_ASSIGN(MockDecryptor);
};
}
#endif
|
[
"allegrant@mail.ru"
] |
allegrant@mail.ru
|
d42f35ba441ed81032ef76ff4cc018ff61e2aba6
|
4244b498b3bd674b535d35da38b2ac80adf424ca
|
/Dynamic Programming/Longest Increasing Subsequence.cpp
|
3f18de903a86d4329f2681b7d39e0ae4a508f73c
|
[] |
no_license
|
rachitgupta98/competitive-programming
|
9064cafa79696f069ea582152c9b08aa3cd12280
|
b7af0c87f6d1a2ad97a9e8460715c463f2d40713
|
refs/heads/master
| 2022-08-21T19:20:24.421999
| 2022-08-19T11:29:02
| 2022-08-19T11:29:02
| 204,412,121
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 712
|
cpp
|
//Time Complexity is o(n^2)
#include <bits/stdc++.h>
using namespace std;
int main(){
int n=5;
int arr[n] = {2,4,6,1,4};
vector<vector<int>>R(n);
R[0].push_back(arr[0]);
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if((arr[i] > arr[j]) && (R[i].size() < R[j].size()+1)){
R[i] = R[j];
}
}
R[i].push_back(arr[i]);
}
// extracting the bigger size arr in adjacency list
vector<int>res = R[0];
for(vector<int>x : R){
if(x.size() > res.size()){
res = x;
}
}
// output the longest increasing subsequence
for(auto y : res){
cout<< y <<" ";
}
return 0;
}
|
[
"rachit371@gmail.com"
] |
rachit371@gmail.com
|
656027f26ff11e3656157b5f371e7f7b08830ad7
|
198806ccd0b5a7d476c701be5943e9a7afacb7d0
|
/xdaq/include/jal/jtagSVFSequencer/JTAGSVFCommandFrequency.h
|
efc1942571dc29317a3132759e50d7ab1366bb21
|
[] |
no_license
|
marcomuzio/EMULib_CLCT_Timing
|
df5999b5f1187725d7f5b6196ba566045ba60f55
|
04e930d46cadaa0c73b94a0c22e4478f55fac844
|
refs/heads/master
| 2021-01-16T13:47:26.141865
| 2014-08-14T12:04:33
| 2014-08-14T12:04:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,415
|
h
|
/**
* @class JTAGSVFCommandFrequency
*
* @short JTAG SVF Frequency command.
* Sets the maximum frequency in Hz.
*
* @see ---
* @author Hannes Sakulin
* $Revision: 1.1 $
* $Date: 2007/03/27 07:59:09 $
*
*
**/
#ifndef jal_JTAGSVFCommandFrequency_H
#define jal_JTAGSVFCommandFrequency_H
#include "jal/jtagSVFSequencer/JTAGSVFCommand.h"
#include "jal/jtagSVFSequencer/JTAGSVFChain.h"
namespace jal {
class JTAGSVFCommandFrequency : public JTAGSVFCommand {
public:
/// constructor
/// @param f is the frequency in Hz or -1. if the frequency should be set back to the default.
JTAGSVFCommandFrequency(double f) :
_frequency(f) {};
/// destructor.
virtual ~JTAGSVFCommandFrequency() {};
/// execute the command. returns true if successful, false if not.
virtual bool execute (JTAGSVFChain& svf_ch) const
throw(jal::HardwareException,
jal::TimeoutException,
jal::OutOfRangeException,
jal::SVFSyntaxException) {
svf_ch.setFrequency ( _frequency );
return true;
};
protected:
virtual std::ostream& display(std::ostream& os) const {
if (_frequency != -1.)
os << "Command FREQUENCY " << _frequency << " Hz" << std::endl;
else
os << "Command FREQUENCY. (return to original frequency) " << std::endl;
return os;
}
double _frequency;
};
}
#endif
|
[
"hogenshpogen@gmail.com"
] |
hogenshpogen@gmail.com
|
e849471865cf714e2f8d7b05428a498c391c2197
|
5241a49fc86a3229e1127427146b5537b3dfd48f
|
/src/Sparrow/App/CommandLineOptions.h
|
0ea5a73a08eabb0425b26febd004f02a347182ff
|
[
"BSD-3-Clause"
] |
permissive
|
qcscine/sparrow
|
05fb1e53ce0addc74e84251ac73d6871f0807337
|
f1a1b149d7ada9ec9d5037c417fbd10884177cba
|
refs/heads/master
| 2023-05-29T21:58:56.712197
| 2023-05-12T06:56:50
| 2023-05-12T06:56:50
| 191,568,488
| 68
| 14
|
BSD-3-Clause
| 2021-12-15T08:19:47
| 2019-06-12T12:39:30
|
C++
|
UTF-8
|
C++
| false
| false
| 4,650
|
h
|
/**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#ifndef SPARROW_COMMANDLINEOPTIONS_H
#define SPARROW_COMMANDLINEOPTIONS_H
#include <memory>
#include <ostream>
namespace Scine {
namespace Core {
class Log;
} // namespace Core
namespace Utils {
class Settings;
} // namespace Utils
namespace Sparrow {
/**
* @brief Class to parse the command line options for non-default options and passes them to a Util::Settings class.
* This class uses the pImpl idiom to hide the boost::program_options dependency.
*/
class CommandLineOptions {
public:
/**
* @brief Class constructor, parses the command line arguments and maps them to the according setting.
* @param argv the vector with the argument strings.
* @param argc the number of arguments.
*/
CommandLineOptions(int argc, char* argv[]);
~CommandLineOptions();
/** @brief returns the command call used to run the program. */
std::string getCallStatement() const;
/** @brief returns whether the help flag option has been set. */
bool helpRequired() const;
/** @brief returns whether the matrices should be saved as files. */
bool outputToFileRequired() const;
/** @brief returns the method name given as command-line argument. */
std::string getSelectedMethodName() const;
/** @brief returns the xyz file containing the coordinates with the desired structures. */
std::string getStructureCoordinatesFile() const;
/** @brief returns the desired calculation description. */
std::string getCalculationDescription() const;
/** @brief returns the desired verbosity of the logging. */
std::string getLoggerVerbosity() const;
/** @brief returns the name of the file where the logging should be printed. */
std::string getLogFilename() const;
/** @brief returns the desired number of orbital steers. */
int getNumberOfOrbitalSteers() const;
/** @brief returns whether the gradients have to be computed. */
bool gradientRequired() const;
/** @brief returns whether the hessian matrix has to be computed. */
bool hessianRequired() const;
/** @brief returns whether the atomic Hessians have to be computed. */
bool atomicHessiansRequired() const;
/** @brief returns whether the bond order matrix has to be computed. */
bool bondOrdersRequired() const;
/** @brief returns whether the normal modes output is printed or suppressed. */
bool suppressNormalModes() const;
/** @brief returns whether an excited states calculation has to be performed. */
bool excitedStatesRequired() const;
/** @brief returns whether an orbital steering calculation has to be performed. */
bool orbitalSteeringRequired() const;
/** @brief returns whether the wavefunction output is printed as a molden file. */
bool wavefunctionRequired() const;
/** @brief returns whether the thermochemical properties are calculated. */
bool thermochemistryRequired() const;
/** @brief returns whether the excited state basis needs to be pruned. */
bool pruneBasis() const;
/** @brief updates a logger with the verbosity parsed from the command line. */
void updateLogger(Core::Log& log) const;
/** @brief updates a setting with the option parsed from the command line. */
void updateSettings(Utils::Settings& settingsToUpdate) const;
/** @brief updates the excited states setting with the option parsed from the command line. */
void updateExcitedStatesSettings(Utils::Settings& settingsToUpdate) const;
/** @brief updates the orbital steering setting with the option parsed from the command line. */
void updateOrbitalSteeringSettings(Utils::Settings& settingsToUpdate) const;
/** @brief prints the help message. */
void printHelp(std::ostream& out) const;
private:
struct Impl;
std::unique_ptr<Impl> pImpl_;
/// @brief Parses the command line to generate a call statement.
std::string generateCallStatement(int argc, char* argv[]) const;
/// templated function to allow using with string and const char pointers as argument.
/// Checks whether the option given by optionIdentifier can be used in the corresponding settings.
template<class CharType>
bool validOptionToSet(CharType optionIdentifier, const Utils::Settings& settings) const;
/// Combines two character types to form a single const char*.
template<class CharPtrType, class StringType>
std::string combineNamesForOptions(CharPtrType nameOfOption, StringType abbreviatedOption) const;
};
} // namespace Sparrow
} // namespace Scine
#endif // SPARROW_COMMANDLINEOPTIONS_H
|
[
"scine@phys.chem.ethz.ch"
] |
scine@phys.chem.ethz.ch
|
8152d0c0609e7ee3f1235a44439ec06b71312db2
|
b7d730a231a94e2efb220ed6252c1c6f14eb0070
|
/gestionnaire_ordre.cpp
|
5329784f22dc2fc0de502a79dccca919d94f57ac
|
[] |
no_license
|
sebangi/serveur_afficheur
|
dd71ee3fd61f2f57cd0e06c8a7ba5154b2ef0b48
|
8f3dbd3823bdaf2698d7cd2d1406a8ee16ff9c09
|
refs/heads/master
| 2021-05-15T14:03:35.264571
| 2017-11-13T07:53:02
| 2017-11-13T07:53:02
| 106,415,541
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,217
|
cpp
|
/** \file gestionnaire_ordre.cpp
* \brief Fichier d'implémentation de la classe GestionnaireOrdre.
* \author Sébastien Angibaud
*/
#include "gestionnaire_ordre.h"
#include "afficheur_interface.h"
#include "message_afficheur.h"
#include <iostream>
/** --------------------------------------------------------------------------------------
* \brief Constructeur de la classe GestionnaireOrdre.
*/
GestionnaireOrdre::GestionnaireOrdre()
{
}
/** --------------------------------------------------------------------------------------
* \brief Traite un ordre donné.
* \param mess L'ordre à traiter.
* \return Le message à renvoyer au client.
*/
MessageClient GestionnaireOrdre::traiterOrdre(const MessageClient &mess)
{
MessageClient result;
if ( mess.valide() )
{
std::cout << "traitement du message n°" << mess.numero() << std::endl;
std::cout << "\t- ordre = " << mess.ordre().toStdString() << std::endl;
if ( mess.a_parametre() )
std::cout << "\t- parametre = " << mess.parametre().toStdString() << std::endl;
if ( mess.ordre().compare("AFFICHER") == 0 )
result = traiterOrdreAfficher(mess);
else if ( mess.ordre().compare("COULEUR") == 0 )
result = traiterOrdreCouleur(mess);
}
else
{
std::cout << "message invalide : pas de traitement de : " << mess.texte().toStdString() << std::endl;
result = MessageClient(0,"message invalide : " + mess.texte());
}
return result;
}
/** --------------------------------------------------------------------------------------
* \brief Traitement d'un ordre d'affichage.
* \param mess Le message client reçu.
* \return Le message à renvoyer au client.
*/
MessageClient GestionnaireOrdre::traiterOrdreAfficher(const MessageClient &mess)
{
if ( AfficheurInterface::instance()->connexionEtablie() )
{
if ( mess.a_parametre() )
{
AfficheurInterface::instance()->envoyerMessage( mess );
return MessageClient(mess.numero(),"Le message a ete envoye à l'afficheur.");
}
else
return MessageClient(mess.numero(),"Erreur : Le message à envoyer est vide.");
}
else
return MessageClient(mess.numero(),"Erreur : le serveur n'est pas connecte a l'afficheur.");
}
/** --------------------------------------------------------------------------------------
* \brief Traitement d'un ordre de choix de couleur.
* \param mess Le message client reçu.
* \return Le message à renvoyer au client.
*/
MessageClient GestionnaireOrdre::traiterOrdreCouleur(const MessageClient &mess)
{
bool result = AfficheurInterface::instance()->setCouleur( mess );
if ( result )
return MessageClient(mess.numero(),"Le message a ete envoye à l'afficheur.");
else
return MessageClient(mess.numero(),"Le choix de couleur n'est pas conforme.");
}
/** --------------------------------------------------------------------------------------
* \brief Traitement d'un ordre d'initialisation d'une variable de type String.
* \param mess Le message client reçu.
* \return Le message à renvoyer au client.
*/
MessageClient GestionnaireOrdre::traiterSetStringVariable(const MessageClient &mess)
{
if ( mess.a_parametre() )
if ( mess.nb_parametres() == 2 )
{
m_string_variables[ mess.parametre(0) ] = mess.parametre(1);
return MessageClient(mess.numero(),"L'initialisation est effectuée.");
}
return MessageClient(mess.numero(),"La demande d'initialisation n'est pas au bon format.");
}
/** --------------------------------------------------------------------------------------
* \brief Traitement d'un ordre d'initialisation d'une variable de type int.
* \param mess Le message client reçu.
* \return Le message à renvoyer au client.
*/
MessageClient GestionnaireOrdre::traiterSetIntVariable(const MessageClient &mess)
{
if ( mess.a_parametre() )
if ( mess.nb_parametres() == 2 )
{
m_int_variables[ mess.parametre(0) ] = mess.parametre(1).toInt();
return MessageClient(mess.numero(),"L'initialisation est effectuée.");
}
return MessageClient(mess.numero(),"La demande d'initialisation n'est pas au bon format.");
}
/** --------------------------------------------------------------------------------------
* \brief Traitement d'un ordre d'accès à une variable de type String.
* \param mess Le message client reçu.
* \return Le message à renvoyer au client.
*/
MessageClient GestionnaireOrdre::traiterGetStringVariable(const MessageClient &mess)
{
if ( mess.a_parametre() )
if ( mess.nb_parametres() == 1 )
{
std::map<QString, QString>::iterator it = m_string_variables.find( mess.parametre(0) );
if ( it == m_string_variables.end() )
return MessageClient(mess.numero(),"La variable demandée n'existe pas.");
else
{
std::vector<QString> l;
l.push_back( it->second );
return MessageClient(mess.numero(),"GET",l);
}
}
return MessageClient(mess.numero(),"La demande d'accès n'est pas au bon format.");
}
/** --------------------------------------------------------------------------------------
* \brief Traitement d'un ordre d'accès à une variable de type Int.
* \param mess Le message client reçu.
* \return Le message à renvoyer au client.
*/
MessageClient GestionnaireOrdre::traiterGetIntVariable(const MessageClient &mess)
{
if ( mess.a_parametre() )
if ( mess.nb_parametres() == 1 )
{
std::map<QString, int>::iterator it = m_int_variables.find( mess.parametre(0) );
if ( it == m_int_variables.end() )
return MessageClient(mess.numero(),"La variable demandée n'existe pas.");
else
{
std::vector<QString> l;
l.push_back( QString::number(it->second) );
return MessageClient(mess.numero(),"GET",l);
}
}
return MessageClient(mess.numero(),"La demande d'accès n'est pas au bon format.");
}
|
[
"sebastien_angibaud@yahoo.fr"
] |
sebastien_angibaud@yahoo.fr
|
6a899430f7023b69508630f772ce8514c3a4285e
|
73e7c20803be5d8ae467af1feba8a4a7fe219f4b
|
/Modules/Registration/RegistrationMethodsv4/test/itkSyNImageRegistrationTest.cxx
|
2d11bde505951ed63b9833556e05b3d20b8fe0a2
|
[
"LicenseRef-scancode-other-permissive",
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-free-unknown",
"BSD-4.3TAHOE",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"IJG",
"Zlib",
"Spencer-86",
"libtiff",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-public-domain",
"NTP",
"BSD-2-Clause",
"GPL-1.0-or-later",
"FSFUL",
"Libpng"
] |
permissive
|
CIBC-Internal/itk
|
deaa8aabe3995f3465ec70a46805bd333967ed5b
|
6f7b1014a73857115d6da738583492008bea8205
|
refs/heads/master
| 2021-01-10T18:48:58.502855
| 2018-01-26T21:25:51
| 2018-01-26T21:25:51
| 31,582,564
| 0
| 2
|
Apache-2.0
| 2018-05-21T07:59:53
| 2015-03-03T06:12:12
|
C++
|
UTF-8
|
C++
| false
| false
| 20,437
|
cxx
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegistrationMethodv4.h"
#include "itkSyNImageRegistrationMethod.h"
#include "itkAffineTransform.h"
#include "itkANTSNeighborhoodCorrelationImageToImageMetricv4.h"
#include "itkCompositeTransform.h"
#include "itkDisplacementFieldTransformParametersAdaptor.h"
#include "itkVector.h"
#include "itkTestingMacros.h"
template<typename TFilter>
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
typedef typename TFilter::FixedImageType FixedImageType;
itkStaticConstMacro( ImageDimension, unsigned int, FixedImageType::ImageDimension ); /** ImageDimension constants */
typedef itk::ShrinkImageFilter<FixedImageType, FixedImageType> ShrinkFilterType;
typedef typename TFilter::OutputTransformType::ScalarType RealType;
typedef itk::DisplacementFieldTransform<RealType, ImageDimension> DisplacementFieldTransformType;
typedef typename DisplacementFieldTransformType::DisplacementFieldType DisplacementFieldType;
protected:
CommandIterationUpdate() {};
public:
virtual void Execute(itk::Object *caller, const itk::EventObject & event) ITK_OVERRIDE
{
Execute( (const itk::Object *) caller, event);
}
virtual void Execute(const itk::Object * object, const itk::EventObject & event) ITK_OVERRIDE
{
const TFilter * filter =
dynamic_cast< const TFilter * >( object );
if( typeid( event ) != typeid( itk::IterationEvent ) )
{ return; }
unsigned int currentLevel = filter->GetCurrentLevel();
typename TFilter::ShrinkFactorsPerDimensionContainerType shrinkFactors = filter->GetShrinkFactorsPerDimension( currentLevel );
typename TFilter::SmoothingSigmasArrayType smoothingSigmas = filter->GetSmoothingSigmasPerLevel();
typename TFilter::TransformParametersAdaptorsContainerType adaptors = filter->GetTransformParametersAdaptorsPerLevel();
std::cout << " Current level = " << currentLevel << std::endl;
std::cout << " shrink factor = " << shrinkFactors << std::endl;
std::cout << " smoothing sigma = " << smoothingSigmas[currentLevel] << std::endl;
std::cout << " required fixed parameters = " << adaptors[currentLevel]->GetRequiredFixedParameters() << std::endl;
/*
testing "itkGetConstObjectMacro" at each iteration
*/
typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();
shrinkFilter->SetShrinkFactors( shrinkFactors );
shrinkFilter->SetInput( filter->GetFixedImage() );
shrinkFilter->Update();
const typename FixedImageType::SizeType ImageSize = shrinkFilter->GetOutput()->GetBufferedRegion().GetSize();
const typename DisplacementFieldType::SizeType FixedDisplacementFieldSize =
filter->GetFixedToMiddleTransform()->GetDisplacementField()->GetBufferedRegion().GetSize();
const typename DisplacementFieldType::SizeType MovingDisplacementFieldSize =
filter->GetMovingToMiddleTransform()->GetDisplacementField()->GetBufferedRegion().GetSize();
if( ( FixedDisplacementFieldSize == ImageSize ) && ( MovingDisplacementFieldSize == ImageSize ) )
{
std::cout << " *Filter returns its internal transforms properly*" << std::endl;
}
else
{
itkExceptionMacro( "Internal transforms should be consistent with input image size at each iteration. "
<< "Image size = " << ImageSize << ". Fixed field size = " << FixedDisplacementFieldSize
<< ". Moving field size = " << MovingDisplacementFieldSize << "." );
}
}
};
template<unsigned int TDimension>
int PerformDisplacementFieldImageRegistration( int itkNotUsed( argc ), char *argv[] )
{
const unsigned int ImageDimension = TDimension;
typedef double PixelType;
typedef itk::Image<PixelType, ImageDimension> FixedImageType;
typedef itk::Image<PixelType, ImageDimension> MovingImageType;
typedef itk::ImageFileReader<FixedImageType> ImageReaderType;
typename ImageReaderType::Pointer fixedImageReader = ImageReaderType::New();
fixedImageReader->SetFileName( argv[2] );
fixedImageReader->Update();
typename FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();
fixedImage->Update();
fixedImage->DisconnectPipeline();
typename ImageReaderType::Pointer movingImageReader = ImageReaderType::New();
movingImageReader->SetFileName( argv[3] );
movingImageReader->Update();
typename MovingImageType::Pointer movingImage = movingImageReader->GetOutput();
movingImage->Update();
movingImage->DisconnectPipeline();
typedef itk::AffineTransform<double, ImageDimension> AffineTransformType;
typedef itk::ImageRegistrationMethodv4<FixedImageType, MovingImageType, AffineTransformType> AffineRegistrationType;
typename AffineRegistrationType::Pointer affineSimple = AffineRegistrationType::New();
affineSimple->SetFixedImage( fixedImage );
affineSimple->SetMovingImage( movingImage );
// Shrink the virtual domain by specified factors for each level. See documentation
// for the itkShrinkImageFilter for more detailed behavior.
typename AffineRegistrationType::ShrinkFactorsArrayType affineShrinkFactorsPerLevel;
affineShrinkFactorsPerLevel.SetSize( 3 );
affineShrinkFactorsPerLevel[0] = 4;
affineShrinkFactorsPerLevel[1] = 4;
affineShrinkFactorsPerLevel[2] = 4;
affineSimple->SetShrinkFactorsPerLevel( affineShrinkFactorsPerLevel );
// Set the number of iterations
typedef itk::GradientDescentOptimizerv4 GradientDescentOptimizerv4Type;
GradientDescentOptimizerv4Type * optimizer = dynamic_cast<GradientDescentOptimizerv4Type *>( affineSimple->GetModifiableOptimizer() );
TEST_EXPECT_TRUE( optimizer != ITK_NULLPTR );
#ifdef NDEBUG
optimizer->SetNumberOfIterations( 100 );
#else
optimizer->SetNumberOfIterations( 1 );
#endif
try
{
std::cout << "Affine transform" << std::endl;
affineSimple->Update();
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Exception caught: " << e << std::endl;
return EXIT_FAILURE;
}
//
// Now do the displacement field transform with gaussian smoothing using
// the composite transform.
//
typedef typename AffineRegistrationType::RealType RealType;
typedef itk::CompositeTransform<RealType, ImageDimension> CompositeTransformType;
typename CompositeTransformType::Pointer compositeTransform = CompositeTransformType::New();
compositeTransform->AddTransform( affineSimple->GetModifiableTransform() );
typedef itk::ResampleImageFilter<MovingImageType, FixedImageType> AffineResampleFilterType;
typename AffineResampleFilterType::Pointer affineResampler = AffineResampleFilterType::New();
affineResampler->SetTransform( compositeTransform );
affineResampler->SetInput( movingImage );
affineResampler->SetSize( fixedImage->GetBufferedRegion().GetSize() );
affineResampler->SetOutputOrigin( fixedImage->GetOrigin() );
affineResampler->SetOutputSpacing( fixedImage->GetSpacing() );
affineResampler->SetOutputDirection( fixedImage->GetDirection() );
affineResampler->SetDefaultPixelValue( 0 );
affineResampler->Update();
std::string affineMovingImageFileName = std::string( argv[4] ) + std::string( "MovingImageAfterAffineTransform.nii.gz" );
typedef itk::ImageFileWriter<FixedImageType> AffineWriterType;
typename AffineWriterType::Pointer affineWriter = AffineWriterType::New();
affineWriter->SetFileName( affineMovingImageFileName.c_str() );
affineWriter->SetInput( affineResampler->GetOutput() );
affineWriter->Update();
typedef itk::Vector<RealType, ImageDimension> VectorType;
VectorType zeroVector( 0.0 );
// Create the SyN deformable registration method
typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType;
typename DisplacementFieldType::Pointer displacementField = DisplacementFieldType::New();
displacementField->CopyInformation( fixedImage );
displacementField->SetRegions( fixedImage->GetBufferedRegion() );
displacementField->Allocate();
displacementField->FillBuffer( zeroVector );
typename DisplacementFieldType::Pointer inverseDisplacementField = DisplacementFieldType::New();
inverseDisplacementField->CopyInformation( fixedImage );
inverseDisplacementField->SetRegions( fixedImage->GetBufferedRegion() );
inverseDisplacementField->Allocate();
inverseDisplacementField->FillBuffer( zeroVector );
typedef itk::SyNImageRegistrationMethod<FixedImageType, MovingImageType> DisplacementFieldRegistrationType;
typename DisplacementFieldRegistrationType::Pointer displacementFieldRegistration = DisplacementFieldRegistrationType::New();
typedef typename DisplacementFieldRegistrationType::OutputTransformType OutputTransformType;
typename OutputTransformType::Pointer outputTransform = OutputTransformType::New();
outputTransform->SetDisplacementField( displacementField );
outputTransform->SetInverseDisplacementField( inverseDisplacementField );
displacementFieldRegistration->SetInitialTransform( outputTransform );
displacementFieldRegistration->InPlaceOn();
//Test member functions
displacementFieldRegistration->SetDownsampleImagesForMetricDerivatives(false);
if( displacementFieldRegistration->GetDownsampleImagesForMetricDerivatives() != false )
{
return EXIT_FAILURE;
}
displacementFieldRegistration->SetDownsampleImagesForMetricDerivatives(true);
if( displacementFieldRegistration->GetDownsampleImagesForMetricDerivatives() != true )
{
return EXIT_FAILURE;
}
displacementFieldRegistration->SetAverageMidPointGradients(false);
if( displacementFieldRegistration->GetAverageMidPointGradients() != false )
{
return EXIT_FAILURE;
}
displacementFieldRegistration->SetAverageMidPointGradients(true);
if( displacementFieldRegistration->GetAverageMidPointGradients() != true )
{
return EXIT_FAILURE;
}
// Create the transform adaptors
typedef itk::DisplacementFieldTransformParametersAdaptor<OutputTransformType> DisplacementFieldTransformAdaptorType;
typename DisplacementFieldRegistrationType::TransformParametersAdaptorsContainerType adaptors;
// Create the transform adaptors
// For the gaussian displacement field, the specified variances are in image spacing terms
// and, in normal practice, we typically don't change these values at each level. However,
// if the user wishes to add that option, they can use the class
// GaussianSmoothingOnUpdateDisplacementFieldTransformAdaptor
unsigned int numberOfLevels = 3;
typename DisplacementFieldRegistrationType::NumberOfIterationsArrayType numberOfIterationsPerLevel;
numberOfIterationsPerLevel.SetSize( 3 );
#ifdef NDEBUG
numberOfIterationsPerLevel[0] = atoi( argv[5] );
numberOfIterationsPerLevel[1] = 2;
numberOfIterationsPerLevel[2] = 1;
#else
numberOfIterationsPerLevel[0] = 1;
numberOfIterationsPerLevel[1] = 1;
numberOfIterationsPerLevel[2] = 1;
#endif
RealType varianceForUpdateField = 1.75;
RealType varianceForTotalField = 0.5;
typename DisplacementFieldRegistrationType::ShrinkFactorsArrayType shrinkFactorsPerLevel;
shrinkFactorsPerLevel.SetSize( 3 );
shrinkFactorsPerLevel[0] = 3;
shrinkFactorsPerLevel[1] = 2;
shrinkFactorsPerLevel[2] = 1;
typename DisplacementFieldRegistrationType::SmoothingSigmasArrayType smoothingSigmasPerLevel;
smoothingSigmasPerLevel.SetSize( 3 );
smoothingSigmasPerLevel[0] = 2;
smoothingSigmasPerLevel[1] = 1;
smoothingSigmasPerLevel[2] = 0;
for( unsigned int level = 0; level < numberOfLevels; level++ )
{
// We use the shrink image filter to calculate the fixed parameters of the virtual
// domain at each level. To speed up calculation and avoid unnecessary memory
// usage, we could calculate these fixed parameters directly.
typedef itk::ShrinkImageFilter<DisplacementFieldType, DisplacementFieldType> ShrinkFilterType;
typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();
shrinkFilter->SetShrinkFactors( shrinkFactorsPerLevel[level] );
shrinkFilter->SetInput( displacementField );
shrinkFilter->Update();
typename DisplacementFieldTransformAdaptorType::Pointer fieldTransformAdaptor = DisplacementFieldTransformAdaptorType::New();
fieldTransformAdaptor->SetRequiredSpacing( shrinkFilter->GetOutput()->GetSpacing() );
fieldTransformAdaptor->SetRequiredSize( shrinkFilter->GetOutput()->GetBufferedRegion().GetSize() );
fieldTransformAdaptor->SetRequiredDirection( shrinkFilter->GetOutput()->GetDirection() );
fieldTransformAdaptor->SetRequiredOrigin( shrinkFilter->GetOutput()->GetOrigin() );
fieldTransformAdaptor->SetTransform( outputTransform );
adaptors.push_back( fieldTransformAdaptor.GetPointer() );
}
typedef itk::ANTSNeighborhoodCorrelationImageToImageMetricv4<FixedImageType, MovingImageType> CorrelationMetricType;
typename CorrelationMetricType::Pointer correlationMetric = CorrelationMetricType::New();
typename CorrelationMetricType::RadiusType radius;
radius.Fill( 4 );
correlationMetric->SetRadius( radius );
correlationMetric->SetUseMovingImageGradientFilter( false );
correlationMetric->SetUseFixedImageGradientFilter( false );
displacementFieldRegistration->SetFixedImage( fixedImage );
displacementFieldRegistration->SetMovingImage( movingImage );
displacementFieldRegistration->SetNumberOfLevels( 3 );
displacementFieldRegistration->SetMovingInitialTransform( compositeTransform );
displacementFieldRegistration->SetShrinkFactorsPerLevel( shrinkFactorsPerLevel );
displacementFieldRegistration->SetSmoothingSigmasPerLevel( smoothingSigmasPerLevel );
displacementFieldRegistration->SetMetric( correlationMetric );
const typename DisplacementFieldRegistrationType::RealType local_epsilon = itk::NumericTraits< typename DisplacementFieldRegistrationType::RealType >::epsilon();
const typename DisplacementFieldRegistrationType::RealType local_LearningRate = atof( argv[6] );
displacementFieldRegistration->SetLearningRate( local_LearningRate );
if ( displacementFieldRegistration->GetLearningRate() - local_LearningRate > local_epsilon )
{
return EXIT_FAILURE;
}
displacementFieldRegistration->SetNumberOfIterationsPerLevel( numberOfIterationsPerLevel );
if ( displacementFieldRegistration->GetNumberOfIterationsPerLevel() != numberOfIterationsPerLevel )
{
return EXIT_FAILURE;
}
displacementFieldRegistration->SetTransformParametersAdaptorsPerLevel( adaptors );
displacementFieldRegistration->SetGaussianSmoothingVarianceForTheUpdateField( varianceForUpdateField );
if ( displacementFieldRegistration->GetGaussianSmoothingVarianceForTheUpdateField() - varianceForUpdateField > local_epsilon )
{
return EXIT_FAILURE;
}
displacementFieldRegistration->SetGaussianSmoothingVarianceForTheTotalField( varianceForTotalField );
if ( displacementFieldRegistration->GetGaussianSmoothingVarianceForTheTotalField() - varianceForTotalField > local_epsilon )
{
return EXIT_FAILURE;
}
const typename DisplacementFieldRegistrationType::RealType local_ConvergenceThreshold = 1.0e-6;
displacementFieldRegistration->SetConvergenceThreshold( local_ConvergenceThreshold );
if ( displacementFieldRegistration->GetConvergenceThreshold() - local_ConvergenceThreshold > local_epsilon )
{
return EXIT_FAILURE;
}
const unsigned int local_ConvergenceWindowSize = 10;
displacementFieldRegistration->SetConvergenceWindowSize( local_ConvergenceWindowSize );
if ( displacementFieldRegistration->GetConvergenceWindowSize() != local_ConvergenceWindowSize )
{
return EXIT_FAILURE;
}
typedef CommandIterationUpdate<DisplacementFieldRegistrationType> DisplacementFieldCommandType;
typename DisplacementFieldCommandType::Pointer DisplacementFieldObserver = DisplacementFieldCommandType::New();
displacementFieldRegistration->AddObserver( itk::IterationEvent(), DisplacementFieldObserver );
try
{
std::cout << "SyN registration" << std::endl;
displacementFieldRegistration->Update();
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Exception caught: " << e << std::endl;
return EXIT_FAILURE;
}
compositeTransform->AddTransform( outputTransform );
typedef itk::ResampleImageFilter<MovingImageType, FixedImageType> ResampleFilterType;
typename ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetTransform( compositeTransform );
resampler->SetInput( movingImage );
resampler->SetSize( fixedImage->GetBufferedRegion().GetSize() );
resampler->SetOutputOrigin( fixedImage->GetOrigin() );
resampler->SetOutputSpacing( fixedImage->GetSpacing() );
resampler->SetOutputDirection( fixedImage->GetDirection() );
resampler->SetDefaultPixelValue( 0 );
resampler->Update();
std::string warpedMovingImageFileName = std::string( argv[4] ) + std::string( "MovingImageAfterSyN.nii.gz" );
typedef itk::ImageFileWriter<FixedImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( warpedMovingImageFileName.c_str() );
writer->SetInput( resampler->GetOutput() );
writer->Update();
typedef itk::ResampleImageFilter<FixedImageType, MovingImageType> InverseResampleFilterType;
typename InverseResampleFilterType::Pointer inverseResampler = ResampleFilterType::New();
inverseResampler->SetTransform( compositeTransform->GetInverseTransform() );
inverseResampler->SetInput( fixedImage );
inverseResampler->SetSize( movingImage->GetBufferedRegion().GetSize() );
inverseResampler->SetOutputOrigin( movingImage->GetOrigin() );
inverseResampler->SetOutputSpacing( movingImage->GetSpacing() );
inverseResampler->SetOutputDirection( movingImage->GetDirection() );
inverseResampler->SetDefaultPixelValue( 0 );
inverseResampler->Update();
std::string inverseWarpedFixedImageFileName = std::string( argv[4] ) + std::string( "InverseWarpedFixedImage.nii.gz" );
typedef itk::ImageFileWriter<MovingImageType> InverseWriterType;
typename InverseWriterType::Pointer inverseWriter = InverseWriterType::New();
inverseWriter->SetFileName( inverseWarpedFixedImageFileName.c_str() );
inverseWriter->SetInput( inverseResampler->GetOutput() );
inverseWriter->Update();
std::string displacementFieldFileName = std::string( argv[4] ) + std::string( "DisplacementField.nii.gz" );
typedef itk::ImageFileWriter<DisplacementFieldType> DisplacementFieldWriterType;
typename DisplacementFieldWriterType::Pointer displacementFieldWriter = DisplacementFieldWriterType::New();
displacementFieldWriter->SetFileName( displacementFieldFileName.c_str() );
displacementFieldWriter->SetInput( outputTransform->GetDisplacementField() );
displacementFieldWriter->Update();
return EXIT_SUCCESS;
}
int itkSyNImageRegistrationTest( int argc, char *argv[] )
{
if ( argc < 5 )
{
std::cout << argv[0] << " imageDimension fixedImage movingImage outputPrefix numberOfDeformableIterations learningRate" << std::endl;
exit( 1 );
}
switch( atoi( argv[1] ) )
{
case 2:
PerformDisplacementFieldImageRegistration<2>( argc, argv );
break;
case 3:
PerformDisplacementFieldImageRegistration<3>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
return EXIT_SUCCESS;
}
|
[
"ayla@sci.utah.edu"
] |
ayla@sci.utah.edu
|
0c1a2ab292d52e84fb37d6c9ccbadfa01cd80dd7
|
34efeca8e6aaa1f28a88140d41b44bdbeb31b10f
|
/GUIInternal/GUIInternal.cpp
|
f9fc75cd5588b0a1db4aae8cb98e9e797e827315
|
[] |
no_license
|
arunmudhaliar/GEAR_Alpha
|
e1b7abc68bcba2582f2e6bbb38a55e808aa1d3b3
|
55120e1cdc71f833cf5a05c4830177e7ecd8c9ff
|
refs/heads/master
| 2020-12-20T23:39:19.189604
| 2015-06-24T20:58:05
| 2015-06-24T20:58:05
| 13,659,721
| 0
| 0
| null | 2015-06-24T20:58:05
| 2013-10-17T20:03:21
|
C++
|
UTF-8
|
C++
| false
| false
| 21,480
|
cpp
|
// GUIInternal.cpp : Defines the entry point for the application.
//
//#ifndef USEMONOENGINE
#pragma comment(lib,"GEAREngine.lib")
//#endif
#include "stdafx.h"
#include "GUIInternal.h"
#include "GEAREditor\EditorApp.h"
//#include "../GEAREngine/src/core/Timer.h"
#include <WindowsX.h>
#include <ShlObj.h>
#ifdef _DEBUG
#define ENABLE_MEMORY_CHECK
#include <crtdbg.h>
#endif
#if DEPRECATED
#include "MDragGropInterface.h"
#include "GEAREditor\win32\MDropSource.h"
#include "GEAREditor\win32\eventHook.h"
#include "GEAREditor\secondryViews\geColorDlg.h"
#include <direct.h>
#include <Commdlg.h>
#ifdef _DEBUG
#define ENABLE_MEMORY_CHECK
#include <crtdbg.h>
#endif
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
EditorApp m_cEditorApp;
//#if DEPRECATED
MDragDropInterface* m_cDropTargetInterfacePtr=NULL; //must not delete this pointer
//#endif
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK Proj_DlgProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
char* browseFolder(HWND hWndParent, const char* title, const char* root_dir=NULL);
LPITEMIDLIST convertPathToLpItemIdList(const char *pszPath);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
#if defined(_DEBUG) && defined(ENABLE_MEMORY_CHECK)
_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF);
_CrtSetReportMode ( _CRT_ERROR, _CRTDBG_MODE_DEBUG);
//SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);
SymInitialize(GetCurrentProcess(), NULL, TRUE);
#endif
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_GUIINTERNAL, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, SW_SHOWMAXIMIZED/*nCmdShow*/))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GUIINTERNAL));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage are only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GUIINTERNAL));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_GUIINTERNAL);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
static TCHAR szAppName2[] = TEXT ("childWnd");
WNDCLASSEX childWndClass;
childWndClass.cbSize = sizeof(WNDCLASSEX);
childWndClass.style = CS_HREDRAW | CS_VREDRAW;
childWndClass.lpfnWndProc = geSecondryView::SecondryView_DlgProc;
childWndClass.cbClsExtra = 0;
childWndClass.cbWndExtra = 0;
childWndClass.hInstance = hInstance;
childWndClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GUIINTERNAL));
childWndClass.hCursor = LoadCursor (NULL, IDC_ARROW);
childWndClass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
childWndClass.lpszMenuName = NULL;
childWndClass.lpszClassName = szAppName2;
childWndClass.hIconSm = LoadIcon(childWndClass.hInstance, MAKEINTRESOURCE(IDI_SMALL));
if (!RegisterClassEx(&childWndClass))
{
MessageBox (NULL, TEXT ("This program requires Windows 95/98/NT"),
szAppName2, MB_ICONERROR);
return NULL;
}
return RegisterClassEx(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
switch (message)
{
case WM_CREATE:
{
char current_working_directory[1024];
GetCurrentDirectory(sizeof(current_working_directory), current_working_directory);
geUtil::convertPathToUnixFormat(current_working_directory);
EditorApp::setAppDirectory(current_working_directory);
monoWrapper::initDebugConsole();
monoWrapper::loadMonoModules();
m_cDropTargetInterfacePtr=NULL;
if(DialogBox(hInst, MAKEINTRESOURCE(IDD_PROJ_DLG), hWnd, reinterpret_cast<DLGPROC>(Proj_DlgProc))==0)
{
PostQuitMessage(0);
}
else
{
monoWrapper::reInitMono(EditorApp::getProjectHomeDirectory());
monoWrapper::mono_engine_test_function_for_mono();
m_cEditorApp.init(hWnd, hInst);
OleInitialize(NULL);
MDragDropInterface* dropTarget = new MDragDropInterface(&m_cEditorApp);
// acquire a strong lock
CoLockObjectExternal(dropTarget, TRUE, FALSE);
RegisterDragDrop(hWnd, dropTarget);
m_cDropTargetInterfacePtr=dropTarget;
Timer::init();
//eventHook::g_pEditorAppPtr=&m_cEditorApp;
//eventHook::hookEvent(hWnd);
//load the current scene
std::string root_dir = EditorApp::getProjectHomeDirectory();
root_dir+="/ProjectSettings/currentscene";
gxFile currenSceneFile;
if(currenSceneFile.OpenFile(root_dir.c_str()))
{
const char* relativepath = currenSceneFile.ReadString();
currenSceneFile.CloseFile();
root_dir = EditorApp::getProjectHomeDirectory();
root_dir+="/Assets";
root_dir+=relativepath;
if(EditorApp::getSceneHierarchy()->loadScene(root_dir.c_str()))
{
std::string wndTitle ="GEAR Alpha [";
wndTitle+=relativepath;
wndTitle+=+"]";
SetWindowText(hWnd, wndTitle.c_str());
EditorApp::getSceneProject()->populateProjectView();
EditorApp::getSceneFileView()->populateFileView();
}
GX_DELETE_ARY(relativepath);
}
//
}
}
break;
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
m_cEditorApp.DoCommand(wmId);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case ID_TEST_COMMAND:
{
gxFile file;
file.OpenFile("01_snow_planet.scene.xml.bin");
int nActor=0;
file.Read(nActor);
geGUIBase* tvnode=EditorApp::getSceneHierarchy()->getSelectedTreeNode();
if(!tvnode)
break;
object3d* selectedobj=(object3d*)tvnode->getUserData();
if(!selectedobj)
break;
for(int x=0;x<nActor;x++)
{
char* actorname=file.ReadString();
bool bPrefab=false;
file.Read(bPrefab);
char* prefabname=NULL;
if(bPrefab)
prefabname=file.ReadString();
float rotation[3];
float translation[3];
file.Read(rotation[0]);
file.Read(rotation[1]);
file.Read(rotation[2]);
file.Read(translation[0]);
file.Read(translation[1]);
file.Read(translation[2]);
if(prefabname)
{
std::vector<object3d*>* list=selectedobj->getChildList();
for(std::vector<object3d*>::iterator it = list->begin(); it != list->end(); ++it)
{
object3d* childobj = *it;
if(strcmp(prefabname, childobj->getName())==0)
{
//apply transforms
childobj->rotateLocalXf(rotation[0]);
childobj->rotateLocalXf(rotation[1]);
childobj->rotateLocalXf(rotation[2]);
childobj->updatePositionf(translation[0], translation[2], translation[1]);
break;
}
}
}
GX_DELETE_ARY(actorname);
GX_DELETE_ARY(prefabname);
}
file.CloseFile();
}
break;
case ID_PROJECT_BUILDFORANDROID:
{
printf("\n================ANDROID BUILD ENGINE===============\n");
char inputbuffer[1024*6];
sprintf(inputbuffer, "%s//AndroidProjectMaker.exe %s %s", EditorApp::getAppDirectory().c_str(), EditorApp::getAppDirectory().c_str(), EditorApp::getProjectHomeDirectory());
if(monoWrapper::exec_cmd(inputbuffer)!=0)
{
printf("\nERROR\n");
}
printf("\n======================================================\n");
}
break;
case ID_EDIT_ACTIVECAMERAPROPERTY:
{
object3d* cam=monoWrapper::mono_engine_getWorld(0)->getActiveCamera();
EditorApp::getSceneWorldEditor()->selectedObject3D(cam);
EditorApp::getScenePropertyEditor()->populatePropertyOfObject(cam);
}
break;
case ID_EDIT_OCTREEPROPERTY:
{
EditorApp::getScenePropertyEditor()->populatePropertyOfOctree();
}
break;
case ID_EDIT_LAYERSPROPERTY:
{
EditorApp::getScenePropertyEditor()->populatePropertyOfLayers();
}
break;
case ID_EDIT_FOGSETTINGS:
{
EditorApp::getScenePropertyEditor()->populateSettingsOfFog();
}
break;
case ID_FILE_SAVESCENE:
{
std::string root_dir = EditorApp::getProjectHomeDirectory();
root_dir+="/Assets";
std::replace( root_dir.begin(), root_dir.end(), '/', '\\');
char output_buffer[MAX_PATH];
if(EditorApp::showSaveCommonDlg(hWnd, output_buffer, MAX_PATH, "GEAR Scene (*.gearscene)\0*.gearscene\0", "gearscene", root_dir.c_str()))
{
if(EditorApp::getSceneHierarchy()->saveCurrentScene(output_buffer))
{
EditorApp::getSceneProject()->populateProjectView();
EditorApp::getSceneFileView()->populateFileView();
//update the currentscene file
root_dir = EditorApp::getProjectHomeDirectory();
root_dir+="/ProjectSettings/currentscene";
gxFile currenSceneFile;
if(currenSceneFile.OpenFile(root_dir.c_str(), gxFile::FILE_w))
{
const char* relativepath=AssetImporter::relativePathFromProjectHomeDirectory_AssetFolder(output_buffer);
char unix_path[MAX_PATH];
memset(unix_path, 0, MAX_PATH);
strcpy(unix_path, relativepath);
geUtil::convertPathToUnixFormat(unix_path);
currenSceneFile.Write(unix_path);
currenSceneFile.CloseFile();
std::string wndTitle ="GEAR Alpha [";
wndTitle+=relativepath;
wndTitle+=+"]";
SetWindowText(hWnd, wndTitle.c_str());
}
//
}
}
}
break;
case ID_FILE_OPENSCENE:
{
std::string root_dir = EditorApp::getProjectHomeDirectory();
root_dir+="/Assets";
std::replace( root_dir.begin(), root_dir.end(), '/', '\\');
char output_buffer[MAX_PATH];
if(EditorApp::showOpenCommonDlg(hWnd, output_buffer, MAX_PATH, "GEAR Scene (*.gearscene)\0*.gearscene\0", "gearscene", root_dir.c_str()))
{
if(EditorApp::getSceneHierarchy()->loadScene(output_buffer))
{
EditorApp::getSceneProject()->populateProjectView();
EditorApp::getSceneFileView()->populateFileView();
//update the currentscene file
root_dir = EditorApp::getProjectHomeDirectory();
root_dir+="/ProjectSettings/currentscene";
gxFile currenSceneFile;
if(currenSceneFile.OpenFile(root_dir.c_str(), gxFile::FILE_w))
{
const char* relativepath=AssetImporter::relativePathFromProjectHomeDirectory_AssetFolder(output_buffer);
char unix_path[MAX_PATH];
memset(unix_path, 0, MAX_PATH);
strcpy(unix_path, relativepath);
geUtil::convertPathToUnixFormat(unix_path);
currenSceneFile.Write(unix_path);
currenSceneFile.CloseFile();
std::string wndTitle ="GEAR Alpha [";
wndTitle+=relativepath;
wndTitle+=+"]";
SetWindowText(hWnd, wndTitle.c_str());
}
//
}
}
}
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
{
Timer::update();
m_cEditorApp.update(Timer::getDtinSec());
m_cEditorApp.draw();
}
break;
case WM_SIZE:
{
if((LOWORD(wParam)==SIZE_MAXIMIZED || LOWORD(wParam)==SIZE_RESTORED) && m_cEditorApp.isInitialized())
{
monoWrapper::reInitMono(EditorApp::getProjectHomeDirectory());
m_cEditorApp.importAssetToMetaData(hWnd, hInst);
EditorApp::getSceneProject()->populateProjectView();
EditorApp::getSceneFileView()->populateFileView();
}
m_cEditorApp.size(LOWORD(lParam), HIWORD(lParam));
}
break;
case WM_MOUSEMOVE:
{
int nFlags=LOWORD(wParam);
int xx=LOWORD(lParam);
int yy=HIWORD(lParam);
m_cEditorApp.MouseMove(xx, yy, nFlags);
}
break;
case WM_MOUSEWHEEL:
{
int nFlags=LOWORD(wParam);
int xx=LOWORD(lParam);
int yy=HIWORD(lParam);
xx = GET_X_LPARAM(lParam);
yy = GET_Y_LPARAM(lParam);
int zDelta = GET_WHEEL_DELTA_WPARAM(wParam);
m_cEditorApp.MouseWheel(zDelta, xx, yy, nFlags);
}
break;
case WM_LBUTTONDOWN:
{
//if(geTextBox::g_pCurrentlyActiveTextBoxPtr)
// geTextBox::g_pCurrentlyActiveTextBoxPtr->clearSelection();
geTextBox::g_pCurrentlyActiveTextBoxPtr=NULL;
int nFlags=LOWORD(wParam);
int xx=LOWORD(lParam);
int yy=HIWORD(lParam);
m_cEditorApp.MouseLButtonDown(xx, yy, nFlags);
}
break;
case WM_LBUTTONUP:
{
int nFlags=LOWORD(wParam);
int xx=LOWORD(lParam);
int yy=HIWORD(lParam);
m_cEditorApp.MouseLButtonUp(xx, yy, nFlags);
}
break;
case WM_DESTROY:
{
if(m_cDropTargetInterfacePtr)
{
RevokeDragDrop(hWnd);
// remove the strong lock
CoLockObjectExternal(m_cDropTargetInterfacePtr, FALSE, TRUE);
// release our own reference
m_cDropTargetInterfacePtr->Release();
OleUninitialize();
}
monoWrapper::destroyMono();
monoWrapper::destroyDebugConsole();
#if defined(_DEBUG) && defined(ENABLE_MEMORY_CHECK)
SymCleanup(GetCurrentProcess());
#endif
PostQuitMessage(0);
}
break;
case WM_KEYDOWN:
{
if(geTextBox::g_pCurrentlyActiveTextBoxPtr)
{
if(wParam==VK_SHIFT)
break;
short shift_keystate=GetKeyState(VK_SHIFT);
char ch=MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
if(ch>=0x41 && ch<=0x5A)
{
if(!(shift_keystate&0x8000))
ch=ch+32;
}
else if(ch>=0x31 && ch<=0x39)
{
if((shift_keystate&0x8000))
ch=ch-16;
}
bool bCaptured=geTextBox::g_pCurrentlyActiveTextBoxPtr->KeyDown(ch, lParam);
}
else
{
m_cEditorApp.KeyDown(wParam, lParam);
}
}
break;
case WM_KEYUP:
{
if(geTextBox::g_pCurrentlyActiveTextBoxPtr)
{
if(wParam==VK_SHIFT)
break;
short shift_keystate=GetKeyState(VK_SHIFT);
char ch=MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
if(ch>=0x41 && ch<=0x5A)
{
if(!(shift_keystate&0x8000))
ch=ch+32;
}
else if(ch>=0x31 && ch<=0x39)
{
if((shift_keystate&0x8000))
ch=ch-16;
}
geTextBox::g_pCurrentlyActiveTextBoxPtr->KeyUp(ch, lParam);
}
else
{
m_cEditorApp.KeyUp(wParam, lParam);
}
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
//WINOLEAPI dllimport DoDragDrop(
// IDataObject * pDataObject, // Pointer to the data object
// IDropSource * pDropSource, // Pointer to the source
// DWORD dwOKEffect, // Effects allowed by the source
// DWORD * pdwEffect // Pointer to effects on the source
// )
//{
//
//}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
case WM_CLOSE:
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
break;
default:
return DefWindowProc(hDlg, message, wParam, lParam);
}
return (INT_PTR)FALSE;
}
#endif
char* browseFolder(HWND hWndParent, const char* title, const char* root_dir=NULL);
LPITEMIDLIST convertPathToLpItemIdList(const char *pszPath);
LRESULT CALLBACK projectSelector_DlgProc(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch(Msg)
{
case WM_INITDIALOG:
{
//read the recent dialog
FILE* fp = fopen("recentProjects", "r");
if(fp)
{
char temp_buffer[1024];
while (fscanf(fp, "%s\n", temp_buffer) != EOF)
{
SendDlgItemMessage(hWndDlg, IDC_PROJ_DLG_RECENT_PROJECT_LIST, LB_ADDSTRING, NULL, (LPARAM)temp_buffer);
}
fclose(fp);
}
return TRUE;
}
break;
case WM_COMMAND:
switch(wParam)
{
case ID_PROJ_DLG_OPEN_NEW_PROJECT:
{
char* project_directory=browseFolder(hWndDlg, _T("Select an empty folder to create project."));
if(EditorGEARApp::createNewProject(project_directory)!=0)
{
MessageBox(hWndDlg, "Project creation failed", "Error.", MB_OK | MB_ICONERROR);
GE_DELETE_ARY(project_directory);
return true;
}
EditorGEARApp::setProjectHomeDirectory(project_directory);
GE_DELETE_ARY(project_directory);
EndDialog(hWndDlg, 1);
return true;
}
break;
case ID_PROJ_DLG_OPEN_RECENT_PROJECT:
{
// Get current selection index in listbox
int itemIndex = (int) SendDlgItemMessage(hWndDlg, IDC_PROJ_DLG_RECENT_PROJECT_LIST, LB_GETCURSEL, (WPARAM)0, (LPARAM) 0);
if (itemIndex == LB_ERR)
{
MessageBox(hWndDlg, "Select atleast one recent project", "GEAR.", MB_OK | MB_ICONINFORMATION);
}
else
{
// Get actual text in buffer
char temp_buffer[1024];
SendDlgItemMessage(hWndDlg, IDC_PROJ_DLG_RECENT_PROJECT_LIST, LB_GETTEXT, (WPARAM) itemIndex, (LPARAM) temp_buffer );
EditorGEARApp::setProjectHomeDirectory(temp_buffer);
EndDialog(hWndDlg, 2);
}
return true;
}
break;
}
break;
case WM_CLOSE:
{
return EndDialog(hWndDlg, 0);
}
break;
//commented this default block, since the SHBrowseForFolder [New project option] wont work
//default:
// return DefWindowProc(hWndDlg, Msg, wParam, lParam);
//
}
return FALSE;
}
char* browseFolder(HWND hWndParent, const char* title, const char* root_dir)
{
char* return_buffer=NULL;
BROWSEINFO bi = { 0 };
bi.hwndOwner=hWndParent;
bi.lpszTitle = title;
if(root_dir)
{
bi.pidlRoot = convertPathToLpItemIdList(root_dir);
}
bi.ulFlags=BIF_USENEWUI;// | BIF_RETURNONLYFSDIRS;
HRESULT r=OleInitialize(NULL);
LPITEMIDLIST pidl = SHBrowseForFolder ( &bi );
if ( pidl != 0 )
{
// get the name of the folder
TCHAR path[MAX_PATH];
if ( SHGetPathFromIDList ( pidl, path ) )
{
_tprintf ( _T("Selected Folder: %s\n"), path );
return_buffer = new char[strlen(path)+1];
strcpy(return_buffer, path);
return_buffer[strlen(path)]='\0';
}
// free memory used
IMalloc * imalloc = 0;
if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
{
imalloc->Free ( pidl );
imalloc->Release ( );
}
}
OleUninitialize();
if(return_buffer)
{
//win32 to unix style path
geUtil::convertPathToUnixFormat(return_buffer);
}
return return_buffer;
}
LPITEMIDLIST convertPathToLpItemIdList(const char *pszPath)
{
LPITEMIDLIST pidl = NULL;
LPSHELLFOLDER pDesktopFolder = NULL;
OLECHAR olePath[MAX_PATH];
ULONG chEaten;
HRESULT hr;
if (SUCCEEDED(SHGetDesktopFolder(&pDesktopFolder)))
{
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszPath, -1,
olePath, MAX_PATH);
hr = pDesktopFolder->ParseDisplayName(NULL, NULL,
olePath, &chEaten, &pidl, NULL);
pDesktopFolder->Release();
return pidl;
}
return NULL;
}
#include "../macosProj/GEARInternal/GEARInternal/appEntry.h"
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
#if defined(_DEBUG) && defined(ENABLE_MEMORY_CHECK)
_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF);
_CrtSetReportMode ( _CRT_ERROR, _CRTDBG_MODE_DEBUG);
//SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);
SymInitialize(GetCurrentProcess(), NULL, TRUE);
#endif
int return_val=0;
if(DialogBox(hInstance, MAKEINTRESOURCE(IDD_PROJ_DLG), NULL, reinterpret_cast<DLGPROC>(projectSelector_DlgProc))!=0)
{
monoWrapper::initDebugConsole();
return_val = macos_main();
monoWrapper::destroyDebugConsole();
}
#if defined(_DEBUG) && defined(ENABLE_MEMORY_CHECK)
SymCleanup(GetCurrentProcess());
#endif
return return_val;
}
|
[
"arun.mudhaliar@gmail.com"
] |
arun.mudhaliar@gmail.com
|
d9081df9b3eb0fd4eb59a31a21a610fe9d0c4dfa
|
e21a933f4c455ed36aedace59c100feabb390bce
|
/regexp_matcher.h
|
dd6de29eff8fcc8e08c5e22bd6a4ae73e3d178f9
|
[] |
no_license
|
smokys123/PL_hw1
|
e868b6f314f22575f9fd4023dd10e927d8b806ea
|
c3f1078559071e0a1b43069e8159bf818aff7ff5
|
refs/heads/master
| 2021-01-21T18:33:54.804709
| 2017-05-24T06:32:23
| 2017-05-24T06:32:23
| 92,058,954
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,811
|
h
|
// PL homework: hw2
// regexp_matcher.h
#ifndef _PL_HOMEWORK_REGEXP_MATCHER_H_
#define _PL_HOMEWORK_REGEXP_MATCHER_H_
#include <vector>
#include <string>
#include <map>
#include <set>
#include <stack>
using namespace std;
struct FSATableElement {
int state;
int next_state;
char str;
};
struct RegExpMatcher {
// Design your RegExpMatcher structure
map<pair<set<int>, char>, set<int> > FSA;
set<int> accept;
set<int> init_state;
};
// Homework 1.3
bool BuildRegExpMatcher(const char* regexp, RegExpMatcher* regexp_matcher);
// Homework 1.3
bool RunRegExpMatcher(const RegExpMatcher& regexp_matcher, const char* str);
vector<int> FindOR(const char* str, int start, int end);
int BuildNFA(const char*regexp, int state, vector<FSATableElement>* FSA_table, int start_str, int end_str);
void pushNFAelement(vector<FSATableElement>* FSA_table, char input_symbol, int state, int next_state);
bool CheckRegexp(const char* regexp); //check correct regexp
void SetStarProduction(vector<FSATableElement>* FSA_table, stack<pair<int,int> > pairs);
int CalculNextState(vector<int> state_list);
vector<int >findAllAccept(vector<FSATableElement>& elements, int accept);
bool NFAtoDFA1(const std::vector<FSATableElement>& elements, const std::vector<int>& accept_states, RegExpMatcher* fsa);
vector<pair<int,int> > FindAllEpsilon1(const std::vector<FSATableElement>& elements);
vector<FSATableElement> FindState1(const std::vector<FSATableElement>& elements);
set<int> StatebyEplison1(vector<pair<int,int> >& EpsilonState, set<int>& next_state,int state);
bool PrintFSAelements1(set<int> state, set<int>next_states, char symbol);
bool MoveToNextState(const RegExpMatcher& regexp_matcher, set<int>& curstate, const char symbol);
bool CheckSymbols(const char str);
#endif //_PL_HOMEWORK_REGEXP_MATCHER_H_
|
[
"smkoy123@hanyang.ac.kr"
] |
smkoy123@hanyang.ac.kr
|
1f4d6f518fd4f3fa65a790187aeeb244923e28c6
|
234b0f90cf473f091e24d972b02d67ee1c128fe8
|
/Quadrotor/Quadrotor_V06/data_update.ino
|
b985ba6c171d39a1a494260d75cda28c6ef286aa
|
[] |
no_license
|
wcleithinking/Arduino-based-Embedded-Development
|
023734553260263b0684e853fbea1bfc9c277c98
|
163879a48958751a2fbb7e931dd88e69f159c4ac
|
refs/heads/master
| 2020-03-09T17:46:32.358183
| 2018-08-30T08:42:26
| 2018-08-30T08:42:26
| 128,916,082
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 301
|
ino
|
void data_update() {
roll_ooo = roll_oo;
pitch_ooo = pitch_oo;
yaw_ooo = yaw_oo;
roll_oo = roll_o;
pitch_oo = pitch_o;
yaw_oo = yaw_o;
roll_o = roll;
pitch_o = pitch;
yaw_o = yaw;
for (int i = 0; i < 4; i++) {
u_ooo[i] = u_oo[i];
u_oo[i] = u_o[i];
u_o[i] = u[i];
}
}
|
[
"wcleithinking@gmail.com"
] |
wcleithinking@gmail.com
|
fa4820f18e0654adde51863dddf5c1cc909f710d
|
9fbcf234409424c330eef32036c7f2acbcd4b72a
|
/movie.h
|
47c241468bc6568dad7a88085e91413355f18c94
|
[] |
no_license
|
Lazy-Y/Mini-Amazon
|
f1ecc5d7c1c58ca53eee612307f89aaca234af38
|
163b7e8457d4a293d9078332e0b87ef1e11eb492
|
refs/heads/master
| 2021-01-10T16:51:46.565705
| 2015-11-30T19:08:49
| 2015-11-30T19:08:49
| 47,139,989
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 588
|
h
|
#ifndef MOVIE_H
#define MOVIE_H
#include <iostream>
#include <string>
#include <set>
#include <fstream>
#include "product.h"
using namespace std;
class Movie : public Product
{
public:
Movie(const string category, const string name, double price,
int qty, const string genre, const string rating);
set<string> keywords() const;
string displayString() const;
//bool isMatch(vector<string>& searchTerms) const;
void dump(ostream& os) const;
const string getA() const;
const string getB() const;
private:
string genre_;
string rating_;
};
#endif
|
[
"zhenyanz@usc.edu"
] |
zhenyanz@usc.edu
|
5f5f433c6b8087e4c7f9f95649b0e7332cd1437e
|
2cd0803ba1e648d591cb3bae11e879de179f0f93
|
/Contests/Virtual Judge/ShengSaiXunLian02/4.cc
|
f9dc968b97faea80cb6c005f7f454820852fe1e6
|
[
"MIT"
] |
permissive
|
DCTewi/CodeWorkspace
|
62e323fc126d92c9e20c711cae4bac9220907e64
|
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
|
refs/heads/master
| 2023-05-31T23:46:55.126704
| 2021-06-23T12:11:45
| 2021-06-23T12:11:45
| 175,194,197
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 917
|
cc
|
//B duipai
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int ans = 0;
int check(string a, int l)
{
int len = 0;
string na;
for (int i = l; i >= 0; i--)
{
if (a[i] == '(') na += ')';
else if (a[i] == ')') na += '(';
else na += a[i];
}
for (int i = l + 1; i < a.size(); i++)
{
na += a[i];
}
for (int i = 1; i < na.size(); i++)
{
if (na[i] == ')' && na[i - 1] == ':')
{
len++;
}
}
return len;
}
int checkif(string a, int wanna)
{
for (int i = 0; i < a.size(); i++)
{
if (check(a, i) == wanna)
{
return i;
}
}
}
int main()
{
string a; cin>>a;
for (int i = 0; i < a.size(); i++)
{
ans = max(ans, check(a, i));
}
cout<<ans<<endl;
cout<<checkif(a, ans)<<endl;
return 0;
}
|
[
"dctewi@dctewi.com"
] |
dctewi@dctewi.com
|
c81902a51bfac38b8c0004530e45b6eeabfa32e6
|
ef4f66a7753d09f4ed58a5486c8b6454c27db17d
|
/platek/platek.cpp
|
9e7fca1eb896cc16d48c48f93d5af2974d453eaf
|
[] |
no_license
|
Krizuu/C_Files_from_old_repo
|
7a76227b1dc8a0b26f1ffa27a0c85cbf6ab0f7b0
|
9c8e5442c41c0138d1f4add563e172ae1c1b936a
|
refs/heads/master
| 2020-06-17T03:18:08.677261
| 2019-07-08T10:03:14
| 2019-07-08T10:03:14
| 195,778,252
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,150
|
cpp
|
#include "platek.h"
platek::platek(bool * switcher, unsigned char * gimmeArray, unsigned int * sleepingTime, unsigned int x, unsigned int y) : x_(x), y_(y), arr(gimmeArray)
{
dontStopMe = switcher;
sleepingTime_ = sleepingTime;
startingX = x;
saveNewToArray();
}
std::mutex platek::mtx;
bool platek::dealWithMovement()
{
if (!getLow())
{
if (!WhereDoYouGo())
return false;
}
else
randomlyMoveLeftorRight();
return true;
}
void platek::makeTheSnowStartsFalling()
{
iMovesLikeaJagger = new std::thread(&platek::youSpinMeRoundTheThread, this);
}
void platek::eraseFromArray()
{
*(arr + (y_ * xsize) + x_) = ' ';
}
void platek::saveNewToArray()
{
*(arr + (y_ * xsize) + x_) = 'x';
}
void platek::gotxy(UINT x, UINT y)
{
COORD coord;
coord.X = static_cast<SHORT>(x);
coord.Y = static_cast<SHORT>(y);
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void platek::randomlyMoveLeftorRight()
{
srand(time(nullptr));
if (80 < (rand() % 101)) // 20% szans na poruszenie
{
if (*(arr + (y_ * xsize) + x_ + 1) != 'x' && *(arr + (y_ * xsize) + x_ - 1) != 'x')
{
if ((rand() % 3) == 1)
{
moveToTheLeft();
}
else
{
moveToTheRight();
}
}
else if (*(arr + (y_ * xsize) + x_ + 1) != 'x')
moveToTheRight();
else
moveToTheLeft();
}
}
bool platek::WhereDoYouGo()
{
bool howDoYouDo = false;
if (y_ < ysize)
{
if (*(arr + ((y_ + 1) * xsize) + x_ - 1) != 'x' && *(arr + ((y_ + 1) * xsize) + x_ + 1) != 'x' && x_ > 1 && x_ < xsize)
{
if ((rand() % 3) == 1)
{
howDoYouDo = moveToTheLeft();
}
else
{
howDoYouDo = moveToTheRight();
}
}
else if (*(arr + ((y_ + 1) * xsize) + x_ - 1) != 'x' && x_ > 1)
howDoYouDo = moveToTheLeft();
else if (*(arr + ((y_ + 1) * xsize) + x_ + 1) != 'x' && x_ < xsize)
howDoYouDo = moveToTheRight();
}
return howDoYouDo;
}
bool platek::moveToTheRight()
{
mtx.lock();
if (x_ < xsize - 1 && *(arr + (y_ * xsize) + x_ + 1) != 'x')
{
eraseFromArray();
gotxy(x_, y_);
std::cout << ' ';
x_++;
gotxy(x_, y_);
std::cout << 'x';
saveNewToArray();
mtx.unlock();
return true;
}
mtx.unlock();
return false;
}
bool platek::moveToTheLeft()
{
mtx.lock();
if (x_ > 1 && *(arr + (y_ * xsize) + x_ - 1) != 'x')
{
eraseFromArray();
gotxy(x_, y_);
std::cout << ' ';
x_--;
gotxy(x_, y_);
std::cout << 'x';
saveNewToArray();
mtx.unlock();
return true;
}
mtx.unlock();
return false;
}
bool platek::getLow()
{
mtx.lock();
if (*(arr + ((y_ + 1) * xsize) + x_) != 'x' && y_ < ysize)
{
eraseFromArray();
gotxy(x_, y_);
std::cout << " ";
y_++;
saveNewToArray();
gotxy(x_, y_);
std::cout << "x";
Sleep(30);
mtx.unlock();
return true;
}
mtx.unlock();
return false;
}
void platek::spawnNewBeautifulPieceOfSnow()
{
mtx.lock();
y_ = 0;
x_ = startingX;
saveNewToArray();
mtx.unlock();
}
void platek::youSpinMeRoundTheThread()
{
while (!*dontStopMe)
{
if (!dealWithMovement())
spawnNewBeautifulPieceOfSnow();
Sleep(*sleepingTime_);
}
}
void platek::waitToStop()
{
iMovesLikeaJagger->join();
}
platek::~platek()
{
delete iMovesLikeaJagger;
}
|
[
"krzysztof.agas.lange@gmail.com"
] |
krzysztof.agas.lange@gmail.com
|
58291cfb650f8e95490e580d5d3f3aa43cca87b3
|
d6a27f3d563073337dbe1a91e4c6c927ffe1632b
|
/include/loco/contact_detection/ContactDetectorFeedThrough.hpp
|
3b003884103e2de12b4010716865af43388176a6
|
[
"BSD-3-Clause"
] |
permissive
|
YC-collection/loco
|
c4f808115b893a3147f295710eddeacc5c22bc74
|
f76a4ee2c0f6e44a3be33bafd23f107fcfba9480
|
refs/heads/master
| 2020-12-24T09:15:13.371496
| 2014-12-12T01:07:11
| 2014-12-12T01:07:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,345
|
hpp
|
/*****************************************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Christian Gehring, Péter Fankhauser, C. Dario Bellicoso, Stelian Coros
* 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 Autonomous Systems Lab nor ETH Zurich
* nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* ContactDetectorFeedThrough.h
*
* Created on: May 26, 2014
* Author: gech
*/
#ifndef LOCO_CONTACTDETECTORFEEDTHROUGH_H_
#define LOCO_CONTACTDETECTORFEEDTHROUGH_H_
#include "loco/contact_detection/ContactDetectorBase.hpp"
namespace loco {
class ContactDetectorFeedThrough: public ContactDetectorBase {
public:
ContactDetectorFeedThrough();
virtual ~ContactDetectorFeedThrough();
virtual bool initialize(double dt);
virtual bool advance(double dt);
};
} /* namespace loco */
#endif /* CONTACTDETECTORFEEDTHROUGH_H_ */
|
[
"gehrinch@ethz.ch"
] |
gehrinch@ethz.ch
|
050c83f17ab2fce12449dd77b2ef8d411408b12a
|
dc9959be244ed9285a03a10fbc6046ea75f17f5d
|
/agency/detail/tuple_utility.hpp
|
9e3afc427354e7ff3df54526f56fbc4afa97a932
|
[] |
no_license
|
sali98/agency
|
09d708555bd329b32a5dd48ba339d163257ee074
|
022c69d37064542cde7d20c8401efdace08fa68e
|
refs/heads/master
| 2021-01-21T08:25:22.727368
| 2017-05-12T20:31:34
| 2017-05-12T20:31:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 192
|
hpp
|
#pragma once
#include <agency/detail/config.hpp>
#define TUPLE_UTILITY_ANNOTATION __AGENCY_ANNOTATION
#define TUPLE_UTILITY_NAMESPACE __tu
#include <agency/detail/tuple_utility_impl.hpp>
|
[
"jaredhoberock@gmail.com"
] |
jaredhoberock@gmail.com
|
367884af0e90d1e57605c37e22fe0ba832f8ff2c
|
433a5e2db78508aeceb6169892ac8572401af192
|
/src/shell.hpp
|
c9e55de30d1096604609db692a60b7a514ff5953
|
[] |
no_license
|
EggOetgen/seaShellOFX
|
961aa79765a05ec20604d27a720f58f93d4372cc
|
25a862f4d459fdee663e39634c0f3b190b44e83b
|
refs/heads/master
| 2021-01-01T17:54:54.250171
| 2017-07-26T15:33:27
| 2017-07-26T15:33:27
| 98,197,779
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,634
|
hpp
|
//
// shell.hpp
// seashellOFX
//
// Created by Edmund Oetgen on 18/07/2017.
//
//
#pragma once
#include "ofMain.h"
class shell{
public:
void generate(int n, int m, int D, float turns, float alpha, float beta, float A, float mu, float omega, float phi, float a, float b, float L, float P, float W1, float W2, int N);
void generateMesh(int n, int m, float turns);
void draw(int m);
void updateMesh(int n, int m, float turns);
void setNormals( ofMesh &mesh );
void move(int x, int y, ofVec2f lastMouse);
/*TAKEN FROM https://github.com/genekogan/SeashellGenerator */
// // spiral parameters
// int D = 1; //varying this stretches and compresses along an axis orthoganal to the "A" parameter
// float turns = 6 * TWO_PI;
//
// float alpha = 1.49;
// float beta = .47;
// float A = 0;
// float k = 0.86; // test variable for rate of growth
//
// // ellipse orientation parameters
// float mu = .08; // angle given in radians
// float omega = .01; // angle given in radians
// float phi = 2.6; //rotation of elipse about normal axis, angle given in radians
//
// // ellipsoid parameters
// float a = 13.13; //elipse radii
// float b = 20; //elipse radii
//
// // surface parameters
// float L = 5;
// float P = 5;
// float W1 = 5;
// float W2 = .39;
// int N = 10;
//
vector<ofPoint> spiral;
vector<vector<ofPoint>> shell;
vector<ofPoint> vertices;
ofQuaternion curRot;
ofVec3f centroid;
ofVboMesh shellMesh;
ofNode test;
// of3dPrimitive shellNode;
};
|
[
"edmundoetgen@Edmunds-MBP.home"
] |
edmundoetgen@Edmunds-MBP.home
|
3993a06866fd52fff2e00d91322d4784690c8f28
|
ca602ac81a00ad82d539519502d764180ae57ba9
|
/Num09_11_futures.cpp
|
a308f72c227fff41f98150a3a7a7f92d8b532526
|
[] |
no_license
|
jpiccoli/Cpp_Weekly
|
8b6251b367fe2399754cddf443c29c86204f0116
|
d640ab43c18c4ecdd81eb494d5daf75d886a9b0e
|
refs/heads/master
| 2021-09-17T09:29:14.602062
| 2018-06-30T01:40:52
| 2018-06-30T01:40:52
| 110,934,144
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,865
|
cpp
|
#include <algorithm>
#include <iostream>
#include <random>
#include <set>
#include <future>
std::set<int> make_sorted_random( size_t const& num_elems )
{
std::set<int> retval;
std::random_device rd;
std::mt19937 gen( rd() );
std::uniform_int_distribution<> dis( 0, num_elems - 1 );
std::generate_n( std::inserter( retval, retval.end() ), num_elems,
[&]() { return dis(gen); });
return retval;
}
int main()
{
// std::cout << std::async( make_sorted_random(1000000).get().size() << "\n";
// std::cout << std::async( make_sorted_random, 1000000).get().size() << "\n";
// Does not block. Also may be faster since runtime should spawn new threads
//auto f1 = std::async( std::launch::async, make_sorted_random, 1000000);
//auto f2 = std::async( std::launch::async, make_sorted_random, 1000000);
//std::future<std::set<int>> f3 = std::async( std::launch::async, make_sorted_random, 1000000);
// std::launch::async not necessary but slower since does not ALWAYS spawn a new thread
// Thread creation is runtime decision
// Default is std::launch::async | std::launch::deferred if flags not included
auto f1 = std::async(make_sorted_random, 1000000);
auto f2 = std::async(make_sorted_random, 1000000);
std::future<std::set<int>> f3 = std::async( make_sorted_random, 1000000);
auto f4 = std::async( std::launch::deferred, make_sorted_random, 1000000);
auto f5 = std::async( std::launch::deferred, make_sorted_random, 1000000);
// f4 and f5 never called since not requested with std::launch::deferred
std::cout << f1.get().size() << " " << f2.get().size() << " " << f3.get().size() << "\n";
// Call to "get()" is blocking
//std::cout << std::async(make_sorted_random, 1000000).get().size();
//std::cout << " ";
//std::cout << std::async(make_sorted_random, 1000000).get().size();
//std::cout << "\n";
}
|
[
"joe13676@comcast.net"
] |
joe13676@comcast.net
|
f76ad927b875dc80d04d0b40433cdffebfb6f763
|
7ee38209f161837b4ccf83e3abe1cccb7991cf5a
|
/include/FileManager.hpp
|
8dd96a88c53b345ec44cd4c87a12e428933fae08
|
[] |
no_license
|
Fairbrook/dispersion
|
07e5e9a77407ab550b4ba0e4b74c8736892b8665
|
4936aa8e2eee972b641adbfcfa9e4c1f92af69ed
|
refs/heads/master
| 2023-01-23T14:29:18.973497
| 2020-12-01T18:28:12
| 2020-12-01T18:28:12
| 316,794,040
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,736
|
hpp
|
/**
* Maestro:
* Gracela Lara Lopez
*
* Materia:
* Estructura de DatosII D03
*
* Participantes:
* Arturo Carrillo Solórzano 218744333
* Josué Yizreel Jauregui Rodríguez 219293556
* Kevin Alan Martínez Virgen 219294382
*/
#ifndef FILE_MANAGER_INCLUDE_H
#define FILE_MANAGER_INCLUDE_H
#include <string>
#include <sstream>
#include <array>
#include <vector>
#include <fstream>
#include "Propietario.h"
//Declaración de la clase para el manejo de los archivos
class FileManager
{
private:
// Declaracion del array para guardar las direcciones
std::array<propietario*, 100> directions;
// Declaracion del array para guardar los registro obtenidos del archivo
std::vector<propietario> registries;
// Declaracion del array para guardar la frecuencia de las direcciones
std::array<short, 100> frequency;
// Declaración de la función para realizar las dipersion de folk
int dispersionFolk(char *);
public:
//Constructor
FileManager();
//Funcion para leer el archivo y almacenar sus registros
bool readFile(const std::string &);
//Aplica la función de dispersion a todos los registros leidos
bool applyDispersion();
//Guarda el arreglo de direcciones en el archivo
bool saveFile(const std::string &);
//Guarda el arreglo de frecuencia en el archivo
bool saveFrequencyToFile(const std::string &);
//devuelve el arreglo de direcciones
std::array<propietario*, 100> getDirections() const { return directions; }
//devuelve el arreglo de registros
std::vector<propietario> getResgistries() const { return registries; }
//devuelve el arreglo de frecuencias
std::array<short, 100> getFrequency() const { return frequency; }
};
#endif
|
[
"kevinvr@hotmail.es"
] |
kevinvr@hotmail.es
|
d2f2b220d6e2aadd6919d9c1ffc3cd1c8e41fa3f
|
ef35bb53fe910f8aab77600adbaa5a7370c479da
|
/src/net.cpp
|
ce73e014c652e53faf6b357ef9f9f0a712db3320
|
[
"MIT"
] |
permissive
|
jboss008/trollcoin
|
41eaf23c09fe4c50b2116b45590681cb84d8895d
|
d44de9bafc384b2d9cba39b742724a5d6b646d00
|
refs/heads/master
| 2021-01-01T17:04:59.583904
| 2014-01-06T11:52:36
| 2014-01-06T11:52:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 57,970
|
cpp
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "strlcpy.h"
#include "addrman.h"
#include "ui_interface.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8;
void ThreadMessageHandler2(void* parg);
void ThreadSocketHandler2(void* parg);
void ThreadOpenConnections2(void* parg);
void ThreadOpenAddedConnections2(void* parg);
#ifdef USE_UPNP
void ThreadMapPort2(void* parg);
#endif
void ThreadDNSAddressSeed2(void* parg);
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fClient = false;
bool fDiscover = true;
bool fUseUPnP = false;
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64 nLocalHostNonce = 0;
array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64> mapAlreadyAskedFor;
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
loop
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
if (fShutdown)
return false;
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
Sleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore;
info.nPort = addr.GetPort() + (fAlready ? 1 : 0);
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
loop
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
// We now get our external IP from the IRC server first and only use this as a backup
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their webserver that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
}
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to nonblocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
vRecv.clear();
}
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: local node %s misbehaving\n", addrName.c_str());
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
printf("Disconnected %s for misbehavior (score=%d)\n", addrName.c_str(), nMisbehavior);
return true;
}
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(strSubVer);
X(fInbound);
X(nReleaseTime);
X(nStartingHeight);
X(nMisbehavior);
}
#undef X
void ThreadSocketHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));
// Make this thread recognisable as the networking thread
RenameThread("bitcoin-net");
try
{
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
ThreadSocketHandler2(parg);
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
PrintException(&e, "ThreadSocketHandler()");
} catch (...) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
throw; // support pthread_cancel()
}
printf("ThreadSocketHandler exited\n");
}
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
list<CNode*> vNodesDisconnected;
unsigned int nPrevNodeCount = 0;
loop
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_mapRequests, lockReq);
if (lockReq)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetRecv);
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSend.empty())
FD_SET(pnode->hSocket, &fdsetSend);
}
}
}
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
if (fShutdown)
return;
if (nSelect == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (hSocketMax != INVALID_SOCKET)
{
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
Sleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("warning: unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", WSAGetLastError());
}
else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (fShutdown)
return;
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
CDataStream& vRecv = pnode->vRecv;
unsigned int nPos = vRecv.size();
if (nPos > ReceiveBufferSize()) {
if (!pnode->fDisconnect)
printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());
pnode->CloseSocketDisconnect();
}
else {
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
vRecv.resize(nPos + nBytes);
memcpy(&vRecv[nPos], pchBuf, nBytes);
pnode->nLastRecv = GetTime();
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
CDataStream& vSend = pnode->vSend;
if (!vSend.empty())
{
int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0)
{
vSend.erase(vSend.begin(), vSend.begin() + nBytes);
pnode->nLastSend = GetTime();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Inactivity checking
//
if (pnode->vSend.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
Sleep(10);
}
}
#ifdef USE_UPNP
void ThreadMapPort(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadMapPort(parg));
// Make this thread recognisable as the UPnP thread
RenameThread("bitcoin-UPnP");
try
{
vnThreadsRunning[THREAD_UPNP]++;
ThreadMapPort2(parg);
vnThreadsRunning[THREAD_UPNP]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(&e, "ThreadMapPort()");
} catch (...) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(NULL, "ThreadMapPort()");
}
printf("ThreadMapPort exited\n");
}
void ThreadMapPort2(void* parg)
{
printf("ThreadMapPort started\n");
char port[6];
sprintf(port, "%d", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "TrollCoin " + FormatFullVersion();
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port, port, lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");
int i = 1;
loop {
if (fShutdown || !fUseUPnP)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port, "TCP", 0);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
return;
}
if (i % 600 == 0) // Refresh every 20 minutes
{
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port, port, lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");;
}
Sleep(2000);
i++;
}
} else {
printf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
loop {
if (fShutdown || !fUseUPnP)
return;
Sleep(2000);
}
}
}
void MapPort()
{
if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
{
if (!CreateThread(ThreadMapPort, NULL))
printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
}
}
#else
void MapPort()
{
// Intentionally left blank.
}
#endif
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strDNSSeed[][2] = {
{"cpool1.cryptminer.net", "dnsseed.cryptminer.net"},
//{"bytesized-vps.com", "dnsseed.bytesized-vps.com"},
//{"xurious.com", "dnsseed.ltc.xurious.com"},
};
void ThreadDNSAddressSeed(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadDNSAddressSeed(parg));
// Make this thread recognisable as the DNS seeding thread
RenameThread("bitcoin-dnsseed");
try
{
vnThreadsRunning[THREAD_DNSSEED]++;
ThreadDNSAddressSeed2(parg);
vnThreadsRunning[THREAD_DNSSEED]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_DNSSEED]--;
PrintException(&e, "ThreadDNSAddressSeed()");
} catch (...) {
vnThreadsRunning[THREAD_DNSSEED]--;
throw; // support pthread_cancel()
}
printf("ThreadDNSAddressSeed exited\n");
}
void ThreadDNSAddressSeed2(void* parg)
{
printf("ThreadDNSAddressSeed started\n");
int found = 0;
if (!fTestNet)
{
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
if (GetNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
0x2EFDCB71, 0xCC1B3AD6, 0xADA77149,
};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void ThreadDumpAddress2(void* parg)
{
vnThreadsRunning[THREAD_DUMPADDRESS]++;
while (!fShutdown)
{
DumpAddresses();
vnThreadsRunning[THREAD_DUMPADDRESS]--;
Sleep(100000);
vnThreadsRunning[THREAD_DUMPADDRESS]++;
}
vnThreadsRunning[THREAD_DUMPADDRESS]--;
}
void ThreadDumpAddress(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadDumpAddress(parg));
// Make this thread recognisable as the address dumping thread
RenameThread("bitcoin-adrdump");
try
{
ThreadDumpAddress2(parg);
}
catch (std::exception& e) {
PrintException(&e, "ThreadDumpAddress()");
}
printf("ThreadDumpAddress exited\n");
}
void ThreadOpenConnections(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
ThreadOpenConnections2(parg);
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(&e, "ThreadOpenConnections()");
} catch (...) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(NULL, "ThreadOpenConnections()");
}
printf("ThreadOpenConnections exited\n");
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections2(void* parg)
{
printf("ThreadOpenConnections started\n");
// Connect to specific addresses
if (mapArgs.count("-connect"))
{
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
Sleep(500);
if (fShutdown)
return;
}
}
}
}
// Initiate network connections
int64 nStart = GetTime();
loop
{
ProcessOneShot();
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
Sleep(500);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CSemaphoreGrant grant(*semOutbound);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64 nANow = GetAdjustedTime();
int nTries = 0;
loop
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
nTries++;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadOpenAddedConnections(parg));
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
ThreadOpenAddedConnections2(parg);
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(&e, "ThreadOpenAddedConnections()");
} catch (...) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(NULL, "ThreadOpenAddedConnections()");
}
printf("ThreadOpenAddedConnections exited\n");
}
void ThreadOpenAddedConnections2(void* parg)
{
printf("ThreadOpenAddedConnections started\n");
if (mapArgs.count("-addnode") == 0)
return;
if (GetNameProxy()) {
while(!fShutdown) {
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
Sleep(500);
}
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
}
return;
}
vector<vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
vservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
loop
{
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = vservConnectAddresses.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
Sleep(500);
if (fShutdown)
return;
}
if (fShutdown)
return;
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
if (fShutdown)
return;
}
}
// if succesful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
if (fShutdown)
return false;
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CNode* pnode = ConnectNode(addrConnect, strDest);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return false;
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
// Make this thread recognisable as the message handling thread
RenameThread("bitcoin-msghand");
try
{
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
ThreadMessageHandler2(parg);
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(&e, "ThreadMessageHandler()");
} catch (...) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(NULL, "ThreadMessageHandler()");
}
printf("ThreadMessageHandler exited\n");
}
void ThreadMessageHandler2(void* parg)
{
printf("ThreadMessageHandler started\n");
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (!fShutdown)
{
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
// Receive messages
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
ProcessMessages(pnode);
}
if (fShutdown)
return;
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
if (fShutdown)
return;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
// Wait and allow messages to bunch up.
// Reduce vnThreadsRunning so StopNode has permission to exit while
// we're sleeping, but we must always check fShutdown after doing this.
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
Sleep(100);
if (fRequestShutdown)
StartShutdown();
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
if (fShutdown)
return;
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
printf("%s\n", strError.c_str());
return false;
}
#endif
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to nonblocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. TrollCoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host ip
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
CreateThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(void* parg)
{
// Make this thread recognisable as the startup thread
RenameThread("bitcoin-start");
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
if (!CreateThread(ThreadDNSAddressSeed, NULL))
printf("Error: CreateThread(ThreadDNSAddressSeed) failed\n");
// Map ports with UPnP
if (fUseUPnP)
MapPort();
// Get addresses from IRC and advertise ours
if (!CreateThread(ThreadIRCSeed, NULL))
printf("Error: CreateThread(ThreadIRCSeed) failed\n");
// Send and receive from sockets, accept connections
if (!CreateThread(ThreadSocketHandler, NULL))
printf("Error: CreateThread(ThreadSocketHandler) failed\n");
// Initiate outbound connections from -addnode
if (!CreateThread(ThreadOpenAddedConnections, NULL))
printf("Error: CreateThread(ThreadOpenAddedConnections) failed\n");
// Initiate outbound connections
if (!CreateThread(ThreadOpenConnections, NULL))
printf("Error: CreateThread(ThreadOpenConnections) failed\n");
// Process messages
if (!CreateThread(ThreadMessageHandler, NULL))
printf("Error: CreateThread(ThreadMessageHandler) failed\n");
// Dump network addresses
if (!CreateThread(ThreadDumpAddress, NULL))
printf("Error; CreateThread(ThreadDumpAddress) failed\n");
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
}
bool StopNode()
{
printf("StopNode()\n");
fShutdown = true;
nTransactionsUpdated++;
int64 nStart = GetTime();
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
do
{
int nThreadsRunning = 0;
for (int n = 0; n < THREAD_MAX; n++)
nThreadsRunning += vnThreadsRunning[n];
if (nThreadsRunning == 0)
break;
if (GetTime() - nStart > 20)
break;
Sleep(20);
} while(true);
if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
if (vnThreadsRunning[THREAD_MINER] > 0) printf("ThreadBitcoinMiner still running\n");
if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
#ifdef USE_UPNP
if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
#endif
if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
Sleep(20);
Sleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
|
[
"root@cpool1.cryptminer.net"
] |
root@cpool1.cryptminer.net
|
9fb6b92fe2dca9a21240160cf6673ec0c0a2991d
|
fb5b25b4fbe66c532672c14dacc520b96ff90a04
|
/export/release/windows/obj/src/openfl/display/IGraphicsStroke.cpp
|
11dc37373739f4c28d1a13695b1eaabeae39f565
|
[
"Apache-2.0"
] |
permissive
|
Tyrcnex/tai-mod
|
c3849f817fe871004ed171245d63c5e447c4a9c3
|
b83152693bb3139ee2ae73002623934f07d35baf
|
refs/heads/main
| 2023-08-15T07:15:43.884068
| 2021-09-29T23:39:23
| 2021-09-29T23:39:23
| 383,313,424
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 652
|
cpp
|
#include <hxcpp.h>
#ifndef INCLUDED_openfl_display_IGraphicsStroke
#include <openfl/display/IGraphicsStroke.h>
#endif
namespace openfl{
namespace display{
::hx::Class IGraphicsStroke_obj::__mClass;
void IGraphicsStroke_obj::__register()
{
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.display.IGraphicsStroke",02,f8,be,97);
__mClass->mSuper = &super::__SGetClass();
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TIsInterface< (int)0xf088881a >;
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace display
|
[
"72734817+khiodev@users.noreply.github.com"
] |
72734817+khiodev@users.noreply.github.com
|
9d52fc87e4fdedc3c0926deb505f56eada56aea4
|
3195ea3c507d958eb598c4054f2f382eb6b49ec3
|
/Object Oriented/jdo3643_HW12/jdo3643_Video_Game_Window.h
|
9b3fa1fcf126ea499e1eb94d4f06ed0d3e759ece
|
[] |
no_license
|
jdolds09/Jerry-Olds-Projects
|
3c75d5d4240cd3cccbbfdcaab238ff9735551211
|
eec161042861ef80021edba181c931dbe08ae555
|
refs/heads/master
| 2023-01-03T11:25:18.900613
| 2021-01-19T01:46:08
| 2021-01-19T01:46:08
| 243,045,245
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 444
|
h
|
#include<iostream>
#include<gtkmm.h>
#include<string>
using namespace std;
class Video_Game_Window : public Gtk::Window
{
public:
Video_Game_Window();
~Video_Game_Window();
vector<string> get_entries();
protected:
void on_button_enter();
Gtk::Box m_VBox;
Gtk::Label Title_Label;
Gtk::Entry Title_Entry;
Gtk::Label Year_Label;
Gtk::Entry Year_Entry;
Gtk::Label Studio_Label;
Gtk::Entry Studio_Entry;
Gtk::Button m_Button_Enter;
};
|
[
"jerry.olds@mavs.uta.edu"
] |
jerry.olds@mavs.uta.edu
|
50216b34b6527e052ff273a856a0c4a5a14f285e
|
51635684d03e47ebad12b8872ff469b83f36aa52
|
/external/gcc-12.1.0/libstdc++-v3/testsuite/23_containers/unordered_set/debug/debug_functions.cc
|
84c98d3eba93e8f76ded831d85be44e107dca08b
|
[
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] |
permissive
|
zhmu/ananas
|
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
|
30850c1639f03bccbfb2f2b03361792cc8fae52e
|
refs/heads/master
| 2022-06-25T10:44:46.256604
| 2022-06-12T17:04:40
| 2022-06-12T17:04:40
| 30,108,381
| 59
| 8
|
Zlib
| 2021-09-26T17:30:30
| 2015-01-31T09:44:33
|
C
|
UTF-8
|
C++
| false
| false
| 1,640
|
cc
|
// Copyright (C) 2013-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
//
// { dg-do run { target c++11 } }
// { dg-require-debug-mode "" }
#include <unordered_set>
#include <testsuite_hooks.h>
void test02()
{
using namespace __gnu_debug;
std::unordered_set<int> u = { 0, 1, 2 };
VERIFY( !__check_singular(u.end()) );
auto it = u.end();
VERIFY( !__check_singular(it) );
VERIFY( !__check_singular(u.begin()) );
it = u.begin();
VERIFY( !__check_singular(it) );
u.clear();
VERIFY( it._M_singular() );
VERIFY( __check_singular(it) );
it = u.end();
VERIFY( !it._M_singular() );
VERIFY( !__check_singular(it) );
u = { 0, 1, 2 };
auto bucket = u.bucket(0);
VERIFY( !__check_singular(u.begin(bucket)) );
auto lit = u.begin(bucket);
VERIFY( !__check_singular(lit) );
VERIFY( !__check_singular(u.end(bucket)) );
u.clear();
VERIFY( __check_singular(lit) );
}
int main()
{
test02();
return 0;
}
|
[
"rink@rink.nu"
] |
rink@rink.nu
|
ecec8a68c11523b516da2b336a2b93abde9d627b
|
f703bebbc497e6c91b8da9c19d26cbcc98a897fb
|
/acmp.ru/1161/1161.cpp
|
94a71fd698761316d5d1c6e995036a737a4ec1f9
|
[
"MIT"
] |
permissive
|
mstrechen/competitive-programming
|
1dc48163fc2960c54099077b7bfc0ed84912d2c2
|
ffac439840a71f70580a0ef197e47479e167a0eb
|
refs/heads/master
| 2021-09-22T21:09:24.340863
| 2018-09-16T13:48:51
| 2018-09-16T13:48:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 741
|
cpp
|
#include<iostream>
#include<vector>
using namespace std;
vector<int> zFunction(const string & s)
{
vector<int> z(s.size());
z[0] = 0;
int l = 0, r = 0;
for(int i = 1; i<(int)z.size(); i++)
{
int val = 0;
if(i<=r)
val = min(r-i+1, z[i-l]);
while(i+val < (int)s.size() && s[val] == s[i+val])
val++;
z[i] = val;
if(i + val > r)
{
l = i;
r = i+val-1;
}
}
return z;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
cin >> s;
vector<int> z = zFunction(s);
for(auto i : z)
cout << i << ' ';
return 0;
}
|
[
"mvstrechen@gmail.com"
] |
mvstrechen@gmail.com
|
fb4d9431dfc8a1527c4bc6f561e3c618da2794ab
|
118b042a28eebf624eb76152614a6066933cef7a
|
/lib/Logger/src/Logger.cpp
|
9d011f68712229f9b850f5266ce1333e60bf859c
|
[] |
no_license
|
windymar/monitoring_server_nodemcu
|
de0ada4972cef717e022708c9a2b2172a9bb77d4
|
2c96e2250883da060dc1a62fd888c06118ef7f53
|
refs/heads/master
| 2020-09-21T05:01:54.012797
| 2019-11-28T16:11:47
| 2019-11-28T16:11:47
| 224,686,574
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 354
|
cpp
|
#include <WString.h>
#include <HardwareSerial.h>
void serial_log(const __FlashStringHelper* p_text)
{
Serial.print(p_text);
}
void serial_logln(const __FlashStringHelper* p_text)
{
Serial.println(p_text);
}
void serial_logln(const __FlashStringHelper* p_text, const String& p_option)
{
Serial.print(p_text);
Serial.println(p_option);
}
|
[
"marcin.windys@gmail.com"
] |
marcin.windys@gmail.com
|
0e8beb278e20fd039d086c26690bd9df2129c196
|
01258c31195cf7525657e74c036482eec74d67e4
|
/子游戏/百人红九/机器人服务/AndroidUserItemSink.cpp
|
d375cd5935aee678d09fa1488a0c10736c0f0ce7
|
[] |
no_license
|
zhaozw/Server-1
|
cb418a8a78fa9795fdc12335de6549eeb751ec17
|
ccdd65090a07f994b10a2dc10b8eff2b4068fd7d
|
refs/heads/master
| 2020-04-03T22:11:00.436246
| 2018-12-09T08:44:55
| 2018-12-09T08:44:55
| 155,592,667
| 0
| 0
| null | 2018-10-31T16:51:17
| 2018-10-31T16:51:16
| null |
GB18030
|
C++
| false
| false
| 23,497
|
cpp
|
#include "Stdafx.h"
#include "AndroidUserItemSink.h"
#include "math.h"
//////////////////////////////////////////////////////////////////////////
//时间标识
#define IDI_BANK_OPERATE 3 //银行定时
#define IDI_PLACE_JETTON1 103 //下注定时
#define IDI_PLACE_JETTON2 104 //下注定时
#define IDI_PLACE_JETTON3 105 //下注定时
#define IDI_PLACE_JETTON4 106 //下注定时
#define IDI_PLACE_JETTON5 107 //下注定时
#define IDI_CHECK_BANKER 108 //检查上庄
#define IDI_REQUEST_BANKER 101 //申请定时
#define IDI_GIVEUP_BANKER 102 //下庄定时
#define IDI_PLACE_JETTON 110 //下注定义 (预留110-160)
//////////////////////////////////////////////////////////////////////////
int CAndroidUserItemSink::m_stlApplyBanker = 0L;
int CAndroidUserItemSink::m_stnApplyCount = 0L;
//构造函数
CAndroidUserItemSink::CAndroidUserItemSink()
{
//游戏变量
m_lMaxChipBanker = 0;
m_lMaxChipUser = 0;
m_wCurrentBanker = 0;
m_nChipTime = 0;
m_nChipTimeCount = 0;
m_cbTimeLeave = 0;
ZeroMemory(m_lAreaChip, sizeof(m_lAreaChip));
ZeroMemory(m_nChipLimit, sizeof(m_nChipLimit));
//上庄变量
m_bMeApplyBanker=false;
m_nWaitBanker=0;
m_nBankerCount=0;
m_nListUserCount=0;
m_bReduceJettonLimit = false;
//上庄数量
m_nRobotListMaxCount = 5;
m_nRobotListMinCount = 2;
srand((unsigned)time(NULL));
return;
}
//析构函数
CAndroidUserItemSink::~CAndroidUserItemSink()
{
}
//接口查询
VOID * CAndroidUserItemSink::QueryInterface(REFGUID Guid, DWORD dwQueryVer)
{
QUERYINTERFACE(IAndroidUserItemSink,Guid,dwQueryVer);
QUERYINTERFACE_IUNKNOWNEX(IAndroidUserItemSink,Guid,dwQueryVer);
return NULL;
}
//初始接口
bool CAndroidUserItemSink::Initialization(IUnknownEx * pIUnknownEx)
{
//查询接口
ASSERT(QUERY_OBJECT_PTR_INTERFACE(pIUnknownEx,IAndroidUserItem)!=NULL);
m_pIAndroidUserItem=QUERY_OBJECT_PTR_INTERFACE(pIUnknownEx,IAndroidUserItem);
//错误判断
if(m_pIAndroidUserItem==NULL)
{
ASSERT(FALSE);
return false;
}
return true;
}
//重置接口
bool CAndroidUserItemSink::RepositionSink()
{
//游戏变量
m_lMaxChipBanker = 0;
m_lMaxChipUser = 0;
m_wCurrentBanker = 0;
m_nChipTime = 0;
m_nChipTimeCount = 0;
m_cbTimeLeave = 0;
ZeroMemory(m_lAreaChip, sizeof(m_lAreaChip));
ZeroMemory(m_nChipLimit, sizeof(m_nChipLimit));
//上庄变量
m_bMeApplyBanker=false;
m_nWaitBanker=0;
m_nBankerCount=0;
return true;
}
//时间消息
bool CAndroidUserItemSink::OnEventTimer(UINT nTimerID)
{
switch(nTimerID)
{
case IDI_CHECK_BANKER: //检查上庄
{
m_pIAndroidUserItem->KillGameTimer(nTimerID);
if(m_wCurrentBanker == m_pIAndroidUserItem->GetChairID())
{
return false;
}
int nMinCount = m_nRobotListMaxCount;
if(m_nRobotListMaxCount > m_nRobotListMinCount)
{
nMinCount = (rand()%(m_nRobotListMaxCount - m_nRobotListMinCount+1)) + m_nRobotListMinCount;
}
//空庄
m_nWaitBanker++;
//机器人上庄
if(m_bRobotBanker
&& !m_bMeApplyBanker
&& m_nWaitBanker >= m_nRobotWaitBanker
&& m_nListUserCount < m_nRobotListMaxCount
&& m_stlApplyBanker < m_nRobotListMaxCount
&& m_stlApplyBanker < nMinCount
&& m_stnApplyCount < 2)
{
m_nWaitBanker = 0;
//合法判断
IServerUserItem *pIUserItemBanker = m_pIAndroidUserItem->GetMeUserItem();
if(pIUserItemBanker->GetUserScore() > m_lBankerCondition)
{
//机器人上庄
m_nBankerCount = 0;
m_stlApplyBanker++;
m_stnApplyCount++;
m_pIAndroidUserItem->SetGameTimer(IDI_REQUEST_BANKER, (rand() % m_cbTimeLeave) + 1);
}
else
{
//执行取款
SCORE lDiffScore = (m_lRobotBankGetScoreBankerMax-m_lRobotBankGetScoreBankerMin)/100;
SCORE lScore = m_lRobotBankGetScoreBankerMin + (m_pIAndroidUserItem->GetUserID()%10)*(rand()%10)*lDiffScore +
(rand()%10+1)*(rand()%(lDiffScore/10));
if(lScore > 0)
{
m_pIAndroidUserItem->PerformTakeScore(lScore);
}
IServerUserItem *pIUserItemBanker = m_pIAndroidUserItem->GetMeUserItem();
if(pIUserItemBanker->GetUserScore() > m_lBankerCondition)
{
//机器人上庄
m_nBankerCount = 0;
m_stlApplyBanker++;
m_pIAndroidUserItem->SetGameTimer(IDI_REQUEST_BANKER, (rand() % m_cbTimeLeave) + 1);
}
}
}
return false;
}
case IDI_REQUEST_BANKER: //申请上庄
{
m_pIAndroidUserItem->KillGameTimer(nTimerID);
m_pIAndroidUserItem->SendSocketData(SUB_C_APPLY_BANKER);
return false;
}
case IDI_GIVEUP_BANKER: //申请下庄
{
m_pIAndroidUserItem->KillGameTimer(nTimerID);
m_pIAndroidUserItem->SendSocketData(SUB_C_CANCEL_BANKER);
return false;
}
case IDI_BANK_OPERATE: //银行操作
{
m_pIAndroidUserItem->KillGameTimer(nTimerID);
//变量定义
IServerUserItem *pUserItem = m_pIAndroidUserItem->GetMeUserItem();
LONGLONG lRobotScore = pUserItem->GetUserScore();
{
//判断存取
if(lRobotScore > m_lRobotScoreRange[1])
{
LONGLONG lSaveScore=0L;
lSaveScore = LONGLONG(lRobotScore*m_nRobotBankStorageMul/100);
if(lSaveScore > lRobotScore)
{
lSaveScore = lRobotScore;
}
if(lSaveScore > 0 && m_wCurrentBanker != m_pIAndroidUserItem->GetChairID())
{
m_pIAndroidUserItem->PerformSaveScore(lSaveScore);
}
}
else if(lRobotScore < m_lRobotScoreRange[0])
{
SCORE lDiffScore = (m_lRobotBankGetScoreMax-m_lRobotBankGetScoreMin)/100;
SCORE lScore = m_lRobotBankGetScoreMin + (m_pIAndroidUserItem->GetUserID()%10)*(rand()%10)*lDiffScore +
(rand()%10+1)*(rand()%(lDiffScore/10));
if(lScore > 0)
{
m_pIAndroidUserItem->PerformTakeScore(lScore);
}
}
}
return false;
}
default:
{
if(nTimerID >= IDI_PLACE_JETTON && nTimerID <= IDI_PLACE_JETTON+MAX_CHIP_TIME)
{
//srand(GetTickCount());
//变量定义
int nRandNum = 0, nChipArea = 0, nCurChip = 0, nACTotal = 0, nCurJetLmt[2] = {};
LONGLONG lMaxChipLmt = __min(m_lMaxChipBanker, m_lMaxChipUser); //最大可下注值
WORD wMyID = m_pIAndroidUserItem->GetChairID();
for(int i = 0; i < AREA_COUNT; i++)
{
nACTotal += m_RobotInfo.nAreaChance[i];
}
//统计次数
m_nChipTimeCount++;
//检测退出
if(lMaxChipLmt < m_RobotInfo.nChip[m_nChipLimit[0]])
{
return false;
}
for(int i = 0; i < AREA_COUNT; i++)
{
if(m_lAreaChip[i] >= m_RobotInfo.nChip[m_nChipLimit[0]])
{
break;
}
if(i == AREA_COUNT-1)
{
return false;
}
}
//下注区域
ASSERT(nACTotal>0);
static int nStFluc = 1; //随机辅助
if(nACTotal <= 0)
{
return false;
}
do
{
nRandNum = (rand()+wMyID+nStFluc*3) % nACTotal;
for(int i = 0; i < AREA_COUNT; i++)
{
nRandNum -= m_RobotInfo.nAreaChance[i];
if(nRandNum < 0)
{
nChipArea = i;
break;
}
}
}
while(m_lAreaChip[nChipArea] < m_RobotInfo.nChip[m_nChipLimit[0]]);
nStFluc = nStFluc%3 + 1;
//下注大小
if(m_nChipLimit[0] == m_nChipLimit[1])
{
nCurChip = m_nChipLimit[0];
}
else
{
//设置变量
lMaxChipLmt = __min(lMaxChipLmt, m_lAreaChip[nChipArea]);
nCurJetLmt[0] = m_nChipLimit[0];
nCurJetLmt[1] = m_nChipLimit[0];
//计算当前最大筹码
for(int i = m_nChipLimit[1]; i > m_nChipLimit[0]; i--)
{
if(lMaxChipLmt > m_RobotInfo.nChip[i])
{
nCurJetLmt[1] = i;
break;
}
}
//随机下注
nRandNum = (rand()+wMyID) % (nCurJetLmt[1]-nCurJetLmt[0]+1);
nCurChip = nCurJetLmt[0] + nRandNum;
//多下控制 (当庄家金币较少时会尽量保证下足次数)
if(m_nChipTimeCount < m_nChipTime)
{
LONGLONG lLeftJetton = LONGLONG((lMaxChipLmt-m_RobotInfo.nChip[nCurChip])/(m_nChipTime-m_nChipTimeCount));
//不够次数 (即全用最小限制筹码下注也少了)
if(lLeftJetton < m_RobotInfo.nChip[m_nChipLimit[0]] && nCurChip > m_nChipLimit[0])
{
nCurChip--;
}
}
}
//变量定义
CMD_C_PlaceJetton PlaceJetton = {};
//构造变量
PlaceJetton.cbJettonArea = nChipArea+1; //区域宏从1开始
PlaceJetton.lJettonScore = m_RobotInfo.nChip[nCurChip];
//发送消息
m_pIAndroidUserItem->SendSocketData(SUB_C_PLACE_JETTON, &PlaceJetton, sizeof(PlaceJetton));
}
m_pIAndroidUserItem->KillGameTimer(nTimerID);
return false;
}
}
return false;
}
//游戏消息
bool CAndroidUserItemSink::OnEventGameMessage(WORD wSubCmdID, VOID * pBuffer, WORD wDataSize)
{
switch(wSubCmdID)
{
case SUB_S_GAME_FREE: //游戏空闲
{
return OnSubGameFree(pBuffer, wDataSize);
}
case SUB_S_GAME_START: //游戏开始
{
return OnSubGameStart(pBuffer, wDataSize);
}
case SUB_S_PLACE_JETTON: //用户加注
{
return OnSubPlaceJetton(pBuffer, wDataSize);
}
case SUB_S_APPLY_BANKER: //申请做庄
{
return OnSubUserApplyBanker(pBuffer,wDataSize);
}
case SUB_S_CANCEL_BANKER: //取消做庄
{
return OnSubUserCancelBanker(pBuffer,wDataSize);
}
case SUB_S_CHANGE_BANKER: //切换庄家
{
return OnSubChangeBanker(pBuffer,wDataSize);
}
case SUB_S_GAME_END: //游戏结束
{
return OnSubGameEnd(pBuffer, wDataSize);
}
case SUB_S_SEND_RECORD: //游戏记录 (忽略)
{
return true;
}
case SUB_S_PLACE_JETTON_FAIL: //下注失败 (忽略)
{
return true;
}
}
//错误断言
ASSERT(FALSE);
return true;
}
//游戏消息
bool CAndroidUserItemSink::OnEventFrameMessage(WORD wSubCmdID, VOID * pData, WORD wDataSize)
{
return true;
}
//场景消息
bool CAndroidUserItemSink::OnEventSceneMessage(BYTE cbGameStatus, bool bLookonOther, VOID * pData, WORD wDataSize)
{
switch(cbGameStatus)
{
case GAME_SCENE_FREE: //空闲状态
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_S_StatusFree));
if(wDataSize!=sizeof(CMD_S_StatusFree))
{
return false;
}
//消息处理
CMD_S_StatusFree * pStatusFree=(CMD_S_StatusFree *)pData;
m_lUserLimitScore = pStatusFree->lUserMaxScore;
m_lAreaLimitScore = pStatusFree->lAreaLimitScore;
m_lBankerCondition = pStatusFree->lApplyBankerCondition;
memcpy(m_szRoomName, pStatusFree->szGameRoomName, sizeof(m_szRoomName));
ReadConfigInformation(&pStatusFree->CustomAndroid);
//上庄处理
if(pStatusFree->wBankerUser == INVALID_CHAIR)
{
if(m_bRobotBanker && m_nRobotWaitBanker == 0 && m_stlApplyBanker < m_nRobotApplyBanker)
{
//合法判断
IServerUserItem *pIUserItemBanker = m_pIAndroidUserItem->GetMeUserItem();
if(pIUserItemBanker->GetUserScore() > m_lBankerCondition)
{
//机器人上庄
m_nBankerCount = 0;
m_stlApplyBanker++;
BYTE cbTime = (pStatusFree->cbTimeLeave>0?(rand()%pStatusFree->cbTimeLeave+1):2);
if(cbTime == 0)
{
cbTime = 2;
}
m_pIAndroidUserItem->SetGameTimer(IDI_REQUEST_BANKER, cbTime);
}
}
}
return true;
}
case GS_PLACE_JETTON: //游戏状态
case GS_GAME_END: //结束状态
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_S_StatusPlay));
if(wDataSize!=sizeof(CMD_S_StatusPlay))
{
return false;
}
//消息处理
CMD_S_StatusPlay * pStatusPlay=(CMD_S_StatusPlay *)pData;
//庄家信息
m_wCurrentBanker = pStatusPlay->wBankerUser;
m_lUserLimitScore = pStatusPlay->lUserMaxScore;
m_lAreaLimitScore = pStatusPlay->lAreaLimitScore;
m_lBankerCondition = pStatusPlay->lApplyBankerCondition;
memcpy(m_szRoomName, pStatusPlay->szGameRoomName, sizeof(m_szRoomName));
ReadConfigInformation(&pStatusPlay->CustomAndroid);
return true;
}
}
return true;
}
//用户进入
void CAndroidUserItemSink::OnEventUserEnter(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser)
{
return;
}
//用户离开
void CAndroidUserItemSink::OnEventUserLeave(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser)
{
return;
}
//用户积分
void CAndroidUserItemSink::OnEventUserScore(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser)
{
return;
}
//用户状态
void CAndroidUserItemSink::OnEventUserStatus(IAndroidUserItem * pIAndroidUserItem, bool bLookonUser)
{
return;
}
//游戏空闲
bool CAndroidUserItemSink::OnSubGameFree(const void * pBuffer, WORD wDataSize)
{
//消息处理
CMD_S_GameFree* pGameFree=(CMD_S_GameFree *)pBuffer;
m_cbTimeLeave = pGameFree->cbTimeLeave;
m_nListUserCount = pGameFree->nListUserCount;
//银行操作
if(pGameFree->cbTimeLeave > 1)
{
m_pIAndroidUserItem->SetGameTimer(IDI_BANK_OPERATE, (rand() % (pGameFree->cbTimeLeave-1)) + 1);
}
bool bMeGiveUp = false;
if(m_wCurrentBanker == m_pIAndroidUserItem->GetChairID())
{
m_nBankerCount++;
if(m_nBankerCount >= m_nRobotBankerCount)
{
//机器人走庄
m_nBankerCount = 0;
m_pIAndroidUserItem->SetGameTimer(IDI_GIVEUP_BANKER, rand()%2 + 1);
bMeGiveUp = true;
}
}
//检查上庄
//if (m_wCurrentBanker != m_pIAndroidUserItem->GetChairID() || bMeGiveUp)
{
m_cbTimeLeave = pGameFree->cbTimeLeave - 3;
m_pIAndroidUserItem->SetGameTimer(IDI_CHECK_BANKER, 3);
}
return true;
}
//游戏开始
bool CAndroidUserItemSink::OnSubGameStart(const void * pBuffer, WORD wDataSize)
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_S_GameStart));
if(wDataSize!=sizeof(CMD_S_GameStart))
{
return false;
}
//消息处理
CMD_S_GameStart * pGameStart=(CMD_S_GameStart *)pBuffer;
srand(GetTickCount());
//自己当庄或无下注机器人
if(pGameStart->wBankerUser == m_pIAndroidUserItem->GetChairID() || pGameStart->nChipRobotCount <= 0)
{
return true;
}
//设置变量
m_lMaxChipBanker = pGameStart->lBankerScore/m_RobotInfo.nMaxTime;
m_lMaxChipUser = pGameStart->lUserMaxScore/m_RobotInfo.nMaxTime;
m_wCurrentBanker = pGameStart->wBankerUser;
m_nChipTimeCount = 0;
ZeroMemory(m_nChipLimit, sizeof(m_nChipLimit));
for(int i = 0; i < AREA_COUNT; i++)
{
m_lAreaChip[i] = m_lAreaLimitScore;
}
//系统当庄
if(pGameStart->wBankerUser == INVALID_CHAIR)
{
m_lMaxChipBanker = 2147483647/m_RobotInfo.nMaxTime;
}
else
{
m_lMaxChipUser = __min(m_lMaxChipUser, m_lMaxChipBanker);
}
if(pGameStart->nAndriodApplyCount > 0)
{
m_stlApplyBanker=pGameStart->nAndriodApplyCount;
}
else
{
m_stlApplyBanker=0;
}
//计算下注次数
int nElapse = 0;
WORD wMyID = m_pIAndroidUserItem->GetChairID();
if(m_nRobotBetTimeLimit[0] == m_nRobotBetTimeLimit[1])
{
m_nChipTime = m_nRobotBetTimeLimit[0];
}
else
{
m_nChipTime = (rand()+wMyID)%(m_nRobotBetTimeLimit[1]-m_nRobotBetTimeLimit[0]+1) + m_nRobotBetTimeLimit[0];
}
ASSERT(m_nChipTime>=0);
if(m_nChipTime <= 0)
{
return false; //的确,2个都带等于
}
if(m_nChipTime > MAX_CHIP_TIME)
{
m_nChipTime = MAX_CHIP_TIME; //限定MAX_CHIP次下注
}
//计算范围
if(!CalcJettonRange(__min(m_lMaxChipBanker, m_lMaxChipUser), m_lRobotJettonLimit, m_nChipTime, m_nChipLimit))
{
return true;
}
//设置时间
int nTimeGrid = int(pGameStart->cbTimeLeave-2)*800/m_nChipTime; //时间格,前2秒不下注,所以-2,800表示机器人下注时间范围千分比
for(int i = 0; i < m_nChipTime; i++)
{
int nRandRage = int(nTimeGrid * i / (1500*sqrt((double)m_nChipTime))) + 1; //波动范围
nElapse = 2 + (nTimeGrid*i)/1000 + ((rand()+wMyID)%(nRandRage*2) - (nRandRage-1));
ASSERT(nElapse>=2&&nElapse<=pGameStart->cbTimeLeave);
if(nElapse < 2 || nElapse > pGameStart->cbTimeLeave)
{
continue;
}
m_pIAndroidUserItem->SetGameTimer(IDI_PLACE_JETTON+i+1, nElapse);
}
return true;
}
//用户加注
bool CAndroidUserItemSink::OnSubPlaceJetton(const void * pBuffer, WORD wDataSize)
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_S_PlaceJetton));
if(wDataSize!=sizeof(CMD_S_PlaceJetton))
{
return false;
}
//消息处理
CMD_S_PlaceJetton * pPlaceJetton=(CMD_S_PlaceJetton *)pBuffer;
//设置变量
//m_lMaxChipBanker -= pPlaceJetton->lJettonScore;
m_lAreaChip[pPlaceJetton->cbJettonArea-1] -= pPlaceJetton->lJettonScore;
if(pPlaceJetton->wChairID == m_pIAndroidUserItem->GetChairID())
{
m_lMaxChipUser -= pPlaceJetton->lJettonScore;
}
return true;
}
//下注失败
bool CAndroidUserItemSink::OnSubPlaceJettonFail(const void * pBuffer, WORD wDataSize)
{
return true;
}
//游戏结束
bool CAndroidUserItemSink::OnSubGameEnd(const void * pBuffer, WORD wDataSize)
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_S_GameEnd));
if(wDataSize!=sizeof(CMD_S_GameEnd))
{
return false;
}
//消息处理
CMD_S_GameEnd * pGameEnd=(CMD_S_GameEnd *)pBuffer;
m_stnApplyCount = 0;
return true;
}
//申请做庄
bool CAndroidUserItemSink::OnSubUserApplyBanker(const void * pBuffer, WORD wDataSize)
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_S_ApplyBanker));
if(wDataSize!=sizeof(CMD_S_ApplyBanker))
{
return false;
}
//消息处理
CMD_S_ApplyBanker * pApplyBanker=(CMD_S_ApplyBanker *)pBuffer;
//自己判断
if(m_pIAndroidUserItem->GetChairID()==pApplyBanker->wApplyUser)
{
m_bMeApplyBanker=true;
}
return true;
}
//取消做庄
bool CAndroidUserItemSink::OnSubUserCancelBanker(const void * pBuffer, WORD wDataSize)
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_S_CancelBanker));
if(wDataSize!=sizeof(CMD_S_CancelBanker))
{
return false;
}
//消息处理
CMD_S_CancelBanker * pCancelBanker=(CMD_S_CancelBanker *)pBuffer;
//自己判断
if(m_pIAndroidUserItem->GetChairID()==pCancelBanker->wCancelUser)
{
m_bMeApplyBanker=false;
}
return true;
}
//切换庄家
bool CAndroidUserItemSink::OnSubChangeBanker(const void * pBuffer, WORD wDataSize)
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_S_ChangeBanker));
if(wDataSize!=sizeof(CMD_S_ChangeBanker))
{
return false;
}
//消息处理
CMD_S_ChangeBanker * pChangeBanker = (CMD_S_ChangeBanker *)pBuffer;
if(m_wCurrentBanker == m_pIAndroidUserItem->GetChairID() && m_wCurrentBanker != pChangeBanker->wBankerUser)
{
//m_stlApplyBanker--;
m_nWaitBanker = 0;
m_bMeApplyBanker = false;
}
m_wCurrentBanker = pChangeBanker->wBankerUser;
return true;
}
//读取配置
void CAndroidUserItemSink::ReadConfigInformation(tagCustomAndroid *pCustomAndroid)
{
//次数限制
m_nRobotBetTimeLimit[0] = pCustomAndroid->lRobotMinBetTime;
m_nRobotBetTimeLimit[1] = pCustomAndroid->lRobotMaxBetTime;
if(m_nRobotBetTimeLimit[0] < 0)
{
m_nRobotBetTimeLimit[0] = 0;
}
if(m_nRobotBetTimeLimit[1] < m_nRobotBetTimeLimit[0])
{
m_nRobotBetTimeLimit[1] = m_nRobotBetTimeLimit[0];
}
//筹码限制
m_lRobotJettonLimit[0] = pCustomAndroid->lRobotMinJetton;
m_lRobotJettonLimit[1] = pCustomAndroid->lRobotMaxJetton;
if(m_lRobotJettonLimit[1] > 5000000)
{
m_lRobotJettonLimit[1] = 5000000;
}
if(m_lRobotJettonLimit[0] < 100)
{
m_lRobotJettonLimit[0] = 100;
}
if(m_lRobotJettonLimit[1] < m_lRobotJettonLimit[0])
{
m_lRobotJettonLimit[1] = m_lRobotJettonLimit[0];
}
//是否坐庄
m_bRobotBanker = (pCustomAndroid->nEnableRobotBanker == TRUE)?true:false;
//坐庄次数
LONGLONG lRobotBankerCountMin = pCustomAndroid->lRobotBankerCountMin;
LONGLONG lRobotBankerCountMax = pCustomAndroid->lRobotBankerCountMax;
m_nRobotBankerCount = rand()%(lRobotBankerCountMax-lRobotBankerCountMin+1) + lRobotBankerCountMin;
//列表人数
m_nRobotListMinCount = pCustomAndroid->lRobotListMinCount;
m_nRobotListMaxCount = pCustomAndroid->lRobotListMaxCount;
//最多个数
m_nRobotApplyBanker = pCustomAndroid->lRobotApplyBanker;
//空盘重申
m_nRobotWaitBanker = pCustomAndroid->lRobotWaitBanker;
//分数限制
m_lRobotScoreRange[0] = pCustomAndroid->lRobotScoreMin;
m_lRobotScoreRange[1] = pCustomAndroid->lRobotScoreMax;
if(m_lRobotScoreRange[1] < m_lRobotScoreRange[0])
{
m_lRobotScoreRange[1] = m_lRobotScoreRange[0];
}
//提款数额
m_lRobotBankGetScoreMin = pCustomAndroid->lRobotBankGetMin;
m_lRobotBankGetScoreMax = pCustomAndroid->lRobotBankGetMax;
//提款数额 (庄家)
m_lRobotBankGetScoreBankerMin = pCustomAndroid->lRobotBankGetBankerMin;
m_lRobotBankGetScoreBankerMax = pCustomAndroid->lRobotBankGetBankerMax;
//存款倍数
m_nRobotBankStorageMul = pCustomAndroid->lRobotBankStoMul;
if(m_nRobotBankStorageMul<0 || m_nRobotBankStorageMul>100)
{
m_nRobotBankStorageMul = 20;
}
return;
}
//计算范围 (返回值表示是否可以通过下降下限达到下注)
bool CAndroidUserItemSink::CalcJettonRange(LONGLONG lMaxScore, LONGLONG lChipLmt[], int & nChipTime, int lJetLmt[])
{
//定义变量
bool bHaveSetMinChip = false;
//不够一注
if(lMaxScore < m_RobotInfo.nChip[0])
{
return false;
}
//配置范围
for(int i = 0; i < CountArray(m_RobotInfo.nChip); i++)
{
if(!bHaveSetMinChip && m_RobotInfo.nChip[i] >= lChipLmt[0])
{
lJetLmt[0] = i;
bHaveSetMinChip = true;
}
if(m_RobotInfo.nChip[i] <= lChipLmt[1])
{
lJetLmt[1] = i;
}
}
if(lJetLmt[0] > lJetLmt[1])
{
lJetLmt[0] = lJetLmt[1];
}
//是否降低下限
if(m_bReduceJettonLimit)
{
if(nChipTime * m_RobotInfo.nChip[lJetLmt[0]] > lMaxScore)
{
//是否降低下注次数
if(nChipTime * m_RobotInfo.nChip[0] > lMaxScore)
{
nChipTime = int(lMaxScore/m_RobotInfo.nChip[0]);
lJetLmt[0] = 0;
lJetLmt[1] = 0;
}
else
{
//降低到合适下限
while(nChipTime * m_RobotInfo.nChip[lJetLmt[0]] > lMaxScore)
{
lJetLmt[0]--;
ASSERT(lJetLmt[0]>=0);
}
}
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////
//组件创建函数
DECLARE_CREATE_MODULE(AndroidUserItemSink);
|
[
"wang274380874@126.com"
] |
wang274380874@126.com
|
9f5b7320f825ee900ec21bbae91c95813d385e6b
|
072dd83ffe14401dfc083e911d28daed1f74b489
|
/src/global.cpp
|
065f2122fe70c1bcfb8adfa679bbe51331a09823
|
[] |
no_license
|
osmium18452/co
|
a7871fcee8b72015cde0840dbafbe4c2d8d48096
|
a9d993d1fb47e69c8696000bb11f78e802ec8a42
|
refs/heads/master
| 2022-11-16T21:55:39.147095
| 2020-07-07T08:57:05
| 2020-07-07T08:57:05
| 262,258,060
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 62
|
cpp
|
#include "../headers/global.h"
#include "../headers/lex.h"
|
[
"1711042219@qq.com"
] |
1711042219@qq.com
|
8b2ab7563cd2749f50b4bd3a154a886efe43bad2
|
602dab0925af232f18be0c2fb9dddb287385bf3e
|
/codechef programs/Polynomial.cpp
|
6e1f6beab6e29ff25dd9e7c49977fbb75af992b5
|
[] |
no_license
|
srnit/codeon
|
c5af9cd3de6f5f7e2bd63251451fc1e1e3b2b23e
|
fa51c809d263fb99d947d58a1a838dd9e1c2e7ad
|
refs/heads/master
| 2021-01-12T12:40:55.879728
| 2018-01-14T20:06:40
| 2018-01-14T20:06:40
| 69,899,399
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 853
|
cpp
|
//#include<stdio.h>
#include<bits/stdc++.h>
//#define M 786433
long long int fast_pow(long long base, long long n,long long M)
{
if(n==0)
return 1;
if(n==1)
return base;
long long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
int findMMI_fermat(int n,int M)
{
return fast_pow(n,M-2,M);
}
int main()
{
long long int M=786433;
long long int result;
long long int n,q,x,i,p,pa;
//long long int a[];
scanf("%lld",&n);
long long int a[n+1];
//a=(long int *)malloc(n*sizeof(long int));
//a=new long int(n);
for(i=0;i<=n;i++)
{
scanf("%lld",&a[i]);
}
scanf("%lld",&q);
while(q--)
{
result=0;
scanf("%lld",&x);
for(i=0;i<=n;i++)
{
p=fast_pow(x,i,M);
p=p%M;
pa=(a[i]*p)%M;
result=(result%M+pa%M)%M;
}
printf("%lld\n",result);
}
}
|
[
"ramansudhanshu150@gmail.com"
] |
ramansudhanshu150@gmail.com
|
37ebd2c194b83311a35c34c896300700314e245b
|
82fa7771ec3122a8e6b4b50495ecbcfd2f861639
|
/functions.hpp
|
bbe84f396e55b3de42be49d6af344f47d349c611
|
[
"Unlicense"
] |
permissive
|
michpolicht/BdfCGAL
|
4fc05a5026534296499fd7f2436f400a5b4938b5
|
0ceba33bee8a017c1f37cffcaae5fab8183f01ff
|
refs/heads/master
| 2022-12-17T10:25:08.430513
| 2020-09-20T16:20:45
| 2020-09-20T16:20:45
| 296,093,271
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 404
|
hpp
|
#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP
#include <vector>
#include <utility>
inline
int squashIndex(int i, const std::vector<std::pair<int, int>> & ranges)
{
int squashed = i;
for (auto range : ranges) {
if (i > range.second)
squashed -= range.second - range.first;
else if ((i <= range.second) && (i >= range.first))
return squashed - (i - range.first);
}
return squashed;
}
#endif
|
[
"michpolicht@gmail.com"
] |
michpolicht@gmail.com
|
bb44e81afd6d80cfb40a906477f22d9d1483a70e
|
e54dcb71a395d3743c664db488153f495d0d91e6
|
/source/runtime.cpp
|
d57751c37bfaa725999ab93ee6be0a52220f45d8
|
[
"BSD-3-Clause"
] |
permissive
|
ghostinthecamera/reshade
|
c7ea6b0392bce719f828c5132ccd833c132588a1
|
25422a378a5e67cb3ccd9c316e9dfe6255090c39
|
refs/heads/master
| 2020-08-22T16:19:08.076805
| 2019-10-20T22:06:38
| 2019-10-20T22:06:38
| 216,435,590
| 2
| 0
|
BSD-3-Clause
| 2019-10-20T22:25:10
| 2019-10-20T22:25:10
| null |
UTF-8
|
C++
| false
| false
| 54,647
|
cpp
|
/**
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "log.hpp"
#include "version.h"
#include "runtime.hpp"
#include "runtime_objects.hpp"
#include "effect_parser.hpp"
#include "effect_codegen.hpp"
#include "effect_preprocessor.hpp"
#include "input.hpp"
#include "ini_file.hpp"
#include <assert.h>
#include <thread>
#include <algorithm>
#include <stb_image.h>
#include <stb_image_dds.h>
#include <stb_image_write.h>
#include <stb_image_resize.h>
extern volatile long g_network_traffic;
extern std::filesystem::path g_reshade_dll_path;
extern std::filesystem::path g_target_executable_path;
static inline std::filesystem::path absolute_path(std::filesystem::path path)
{
std::error_code ec;
// First convert path to an absolute path
path = std::filesystem::absolute(g_reshade_dll_path.parent_path() / path, ec);
// Finally try to canonicalize the path too (this may fail though, so it is optional)
if (auto canonical_path = std::filesystem::canonical(path, ec); !ec)
path = std::move(canonical_path);
return path;
}
static inline bool check_preset_path(std::filesystem::path preset_path)
{
// First make sure the extension matches, before diving into the file system
if (preset_path.extension() != L".ini" && preset_path.extension() != L".txt")
return false;
preset_path = absolute_path(preset_path);
std::error_code ec;
const std::filesystem::file_type file_type = std::filesystem::status(preset_path, ec).type();
if (file_type == std::filesystem::file_type::directory || ec.value() == 0x7b) // 0x7b: ERROR_INVALID_NAME
return false;
if (file_type == std::filesystem::file_type::not_found)
return true; // A non-existent path is valid for a new preset
return reshade::ini_file::load_cache(preset_path).has({}, "Techniques");
}
static bool find_file(const std::vector<std::filesystem::path> &search_paths, std::filesystem::path &path)
{
std::error_code ec;
if (path.is_absolute())
return std::filesystem::exists(path, ec);
for (std::filesystem::path search_path : search_paths)
{
// Append relative file path to absolute search path
search_path = absolute_path(std::move(search_path)) / path;
if (std::filesystem::exists(search_path, ec)) {
path = std::move(search_path);
return true;
}
}
return false;
}
static std::vector<std::filesystem::path> find_files(const std::vector<std::filesystem::path> &search_paths, std::initializer_list<const char *> extensions)
{
std::error_code ec;
std::vector<std::filesystem::path> files;
for (std::filesystem::path search_path : search_paths)
{
// Ignore the working directory and instead start relative paths at the DLL location
search_path = absolute_path(std::move(search_path));
for (const auto &entry : std::filesystem::directory_iterator(search_path, ec))
for (auto ext : extensions)
if (entry.path().extension() == ext)
files.push_back(entry.path());
}
return files;
}
reshade::runtime::runtime() :
_start_time(std::chrono::high_resolution_clock::now()),
_last_present_time(std::chrono::high_resolution_clock::now()),
_last_frame_duration(std::chrono::milliseconds(1)),
_effect_search_paths({ ".\\" }),
_texture_search_paths({ ".\\" }),
_global_preprocessor_definitions({
"RESHADE_DEPTH_LINEARIZATION_FAR_PLANE=1000.0",
"RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN=0",
"RESHADE_DEPTH_INPUT_IS_REVERSED=1",
"RESHADE_DEPTH_INPUT_IS_LOGARITHMIC=0" }),
_reload_key_data(),
_effects_key_data(),
_screenshot_key_data(),
_previous_preset_key_data(),
_next_preset_key_data(),
_screenshot_path(g_target_executable_path.parent_path())
{
// Default shortcut PrtScrn
_screenshot_key_data[0] = 0x2C;
_configuration_path = g_reshade_dll_path;
_configuration_path.replace_extension(".ini");
// First look for an API-named configuration file
if (std::error_code ec; !std::filesystem::exists(_configuration_path, ec))
// On failure check for a "ReShade.ini" in the application directory
_configuration_path = g_target_executable_path.parent_path() / "ReShade.ini";
if (std::error_code ec; !std::filesystem::exists(_configuration_path, ec))
// If neither exist create a "ReShade.ini" in the ReShade DLL directory
_configuration_path = g_reshade_dll_path.parent_path() / "ReShade.ini";
_needs_update = check_for_update(_latest_version);
#if RESHADE_GUI
init_ui();
#endif
load_config();
}
reshade::runtime::~runtime()
{
assert(_worker_threads.empty());
assert(!_is_initialized && _techniques.empty());
#if RESHADE_GUI
deinit_ui();
#endif
}
bool reshade::runtime::on_init(input::window_handle window)
{
LOG(INFO) << "Recreated runtime environment on runtime " << this << '.';
_input = input::register_window(window);
// Reset frame count to zero so effects are loaded in 'update_and_render_effects'
_framecount = 0;
_is_initialized = true;
_last_reload_time = std::chrono::high_resolution_clock::now();
#if RESHADE_GUI
build_font_atlas();
#endif
return true;
}
void reshade::runtime::on_reset()
{
unload_effects();
if (!_is_initialized)
return;
#if RESHADE_GUI
destroy_font_atlas();
#endif
LOG(INFO) << "Destroyed runtime environment on runtime " << this << '.';
_width = _height = 0;
_is_initialized = false;
}
void reshade::runtime::on_present()
{
// Get current time and date
time_t t = std::time(nullptr); tm tm;
localtime_s(&tm, &t);
_date[0] = tm.tm_year + 1900;
_date[1] = tm.tm_mon + 1;
_date[2] = tm.tm_mday;
_date[3] = tm.tm_hour * 3600 + tm.tm_min * 60 + tm.tm_sec;
_framecount++;
const auto current_time = std::chrono::high_resolution_clock::now();
_last_frame_duration = current_time - _last_present_time;
_last_present_time = current_time;
// Lock input so it cannot be modified by other threads while we are reading it here
const auto input_lock = _input->lock();
// Handle keyboard shortcuts
if (!_ignore_shortcuts)
{
if (_input->is_key_pressed(_effects_key_data))
_effects_enabled = !_effects_enabled;
if (_input->is_key_pressed(_screenshot_key_data))
_should_save_screenshot = true; // Notify 'update_and_render_effects' that we want to save a screenshot
// Do not allow the next shortcuts while effects are being loaded or compiled (since they affect that state)
if (!is_loading() && _reload_compile_queue.empty())
{
if (_input->is_key_pressed(_reload_key_data))
load_effects();
const bool is_next_preset_key_pressed = _input->is_key_pressed(_next_preset_key_data);
const bool is_previous_preset_key_pressed = _input->is_key_pressed(_previous_preset_key_data);
if (is_next_preset_key_pressed || is_previous_preset_key_pressed)
{
// The preset shortcut key was pressed down, so start the transition
if (switch_to_next_preset({}, is_previous_preset_key_pressed))
{
_last_preset_switching_time = current_time;
_is_in_between_presets_transition = true;
save_config();
}
}
// Continuously update preset values while a transition is in progress
if (_is_in_between_presets_transition)
load_current_preset();
}
}
#if RESHADE_GUI
// Draw overlay
draw_ui();
#endif
// Reset input status
_input->next_frame();
// Save modified INI files
ini_file::flush_cache();
// Detect high network traffic
static int cooldown = 0, traffic = 0;
if (cooldown-- > 0)
{
traffic += g_network_traffic > 0;
}
else
{
_has_high_network_activity = traffic > 10;
traffic = 0;
cooldown = 30;
}
// Reset frame statistics
g_network_traffic = 0;
_drawcalls = _vertices = 0;
}
void reshade::runtime::load_effect(const std::filesystem::path &path, size_t &out_id)
{
effect_data effect;
effect.source_file = path;
effect.compile_sucess = true;
{ // Load, pre-process and compile the source file
reshadefx::preprocessor pp;
if (path.is_absolute())
pp.add_include_path(path.parent_path());
for (std::filesystem::path include_path : _effect_search_paths)
{
include_path = absolute_path(include_path);
if (!include_path.empty())
pp.add_include_path(include_path);
}
pp.add_macro_definition("__RESHADE__", std::to_string(VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_REVISION));
pp.add_macro_definition("__RESHADE_PERFORMANCE_MODE__", _performance_mode ? "1" : "0");
pp.add_macro_definition("__VENDOR__", std::to_string(_vendor_id));
pp.add_macro_definition("__DEVICE__", std::to_string(_device_id));
pp.add_macro_definition("__RENDERER__", std::to_string(_renderer_id));
// Truncate hash to 32-bit, since lexer currently only supports 32-bit numbers anyway
pp.add_macro_definition("__APPLICATION__", std::to_string(std::hash<std::string>()(g_target_executable_path.stem().u8string()) & 0xFFFFFFFF));
pp.add_macro_definition("BUFFER_WIDTH", std::to_string(_width));
pp.add_macro_definition("BUFFER_HEIGHT", std::to_string(_height));
pp.add_macro_definition("BUFFER_RCP_WIDTH", "(1.0 / BUFFER_WIDTH)");
pp.add_macro_definition("BUFFER_RCP_HEIGHT", "(1.0 / BUFFER_HEIGHT)");
pp.add_macro_definition("BUFFER_COLOR_BIT_DEPTH", std::to_string(_color_bit_depth));
std::vector<std::string> preprocessor_definitions = _global_preprocessor_definitions;
preprocessor_definitions.insert(preprocessor_definitions.end(), _preset_preprocessor_definitions.begin(), _preset_preprocessor_definitions.end());
for (const auto &definition : preprocessor_definitions)
{
if (definition.empty())
continue; // Skip invalid definitions
const size_t equals_index = definition.find('=');
if (equals_index != std::string::npos)
pp.add_macro_definition(
definition.substr(0, equals_index),
definition.substr(equals_index + 1));
else
pp.add_macro_definition(definition);
}
if (!pp.append_file(path))
{
LOG(ERROR) << "Failed to load " << path << ":\n" << pp.errors();
effect.compile_sucess = false;
}
unsigned shader_model;
if (_renderer_id == 0x9000) // D3D9
shader_model = 30;
else if (_renderer_id < 0xa100) // D3D10
shader_model = 40;
else if (_renderer_id < 0xb000) // D3D11
shader_model = 41;
else if (_renderer_id < 0xc000) // D3D12
shader_model = 50;
else
shader_model = 60;
std::unique_ptr<reshadefx::codegen> codegen;
if ((_renderer_id & 0xF0000) == 0)
codegen.reset(reshadefx::create_codegen_hlsl(shader_model, true, _performance_mode));
else if (_renderer_id < 0x20000)
codegen.reset(reshadefx::create_codegen_glsl(true, _performance_mode));
else // Vulkan uses SPIR-V input
codegen.reset(reshadefx::create_codegen_spirv(true, true, _performance_mode));
reshadefx::parser parser;
// Compile the pre-processed source code (try the compile even if the preprocessor step failed to get additional error information)
if (!parser.parse(std::move(pp.output()), codegen.get()))
{
LOG(ERROR) << "Failed to compile " << path << ":\n" << pp.errors() << parser.errors();
effect.compile_sucess = false;
}
// Append preprocessor and parser errors to the error list
effect.errors = std::move(pp.errors()) + std::move(parser.errors());
// Write result to effect module
codegen->write_result(effect.module);
}
// Fill all specialization constants with values from the current preset
if (_performance_mode && !_current_preset_path.empty() && effect.compile_sucess)
{
const ini_file preset(_current_preset_path);
const std::string section(path.filename().u8string());
for (reshadefx::uniform_info &constant : effect.module.spec_constants)
{
effect.preamble += "#define SPEC_CONSTANT_" + constant.name + ' ';
switch (constant.type.base)
{
case reshadefx::type::t_int:
preset.get(section, constant.name, constant.initializer_value.as_int);
break;
case reshadefx::type::t_bool:
case reshadefx::type::t_uint:
preset.get(section, constant.name, constant.initializer_value.as_uint);
break;
case reshadefx::type::t_float:
preset.get(section, constant.name, constant.initializer_value.as_float);
break;
}
for (unsigned int i = 0; i < constant.type.components(); ++i)
{
switch (constant.type.base)
{
case reshadefx::type::t_bool:
effect.preamble += constant.initializer_value.as_uint[i] ? "true" : "false";
break;
case reshadefx::type::t_int:
effect.preamble += std::to_string(constant.initializer_value.as_int[i]);
break;
case reshadefx::type::t_uint:
effect.preamble += std::to_string(constant.initializer_value.as_uint[i]);
break;
case reshadefx::type::t_float:
effect.preamble += std::to_string(constant.initializer_value.as_float[i]);
break;
}
if (i + 1 < constant.type.components())
effect.preamble += ", ";
}
effect.preamble += '\n';
}
}
// Guard access to shared variables
const std::lock_guard<std::mutex> lock(_reload_mutex);
effect.index = out_id = _loaded_effects.size();
effect.storage_offset = _uniform_data_storage.size();
for (const reshadefx::uniform_info &info : effect.module.uniforms)
{
uniform &variable = _uniforms.emplace_back(info);
variable.effect_index = effect.index;
variable.storage_offset = effect.storage_offset + variable.offset;
// Create space for the new variable in the storage area and fill it with the initializer value
_uniform_data_storage.resize(variable.storage_offset + variable.size);
// Copy initial data into uniform storage area
reset_uniform_value(variable);
const std::string_view special = variable.annotation_as_string("source");
if (special.empty()) /* Ignore if annotation is missing */;
else if (special == "frametime")
variable.special = special_uniform::frame_time;
else if (special == "framecount")
variable.special = special_uniform::frame_count;
else if (special == "random")
variable.special = special_uniform::random;
else if (special == "pingpong")
variable.special = special_uniform::ping_pong;
else if (special == "date")
variable.special = special_uniform::date;
else if (special == "timer")
variable.special = special_uniform::timer;
else if (special == "key")
variable.special = special_uniform::key;
else if (special == "mousepoint")
variable.special = special_uniform::mouse_point;
else if (special == "mousedelta")
variable.special = special_uniform::mouse_delta;
else if (special == "mousebutton")
variable.special = special_uniform::mouse_button;
}
effect.storage_size = (_uniform_data_storage.size() - effect.storage_offset + 15) & ~15;
_uniform_data_storage.resize(effect.storage_offset + effect.storage_size);
for (const reshadefx::texture_info &info : effect.module.textures)
{
// Try to share textures with the same name across effects
if (const auto existing_texture = std::find_if(_textures.begin(), _textures.end(),
[&info](const auto &item) { return item.unique_name == info.unique_name; });
existing_texture != _textures.end())
{
// Cannot share texture if this is a normal one, but the existing one is a reference and vice versa
if (info.semantic.empty() != (existing_texture->impl_reference == texture_reference::none))
{
effect.errors += "error: " + info.unique_name + ": another effect (";
effect.errors += _loaded_effects[existing_texture->effect_index].source_file.filename().u8string();
effect.errors += ") already created a texture with the same name but different usage; rename the variable to fix this error\n";
effect.compile_sucess = false;
break;
}
else if (info.semantic.empty() && !existing_texture->matches_description(info))
{
effect.errors += "warning: " + info.unique_name + ": another effect (";
effect.errors += _loaded_effects[existing_texture->effect_index].source_file.filename().u8string();
effect.errors += ") already created a texture with the same name but different dimensions; textures are shared across all effects, so either rename the variable or adjust the dimensions so they match\n";
}
existing_texture->shared = true;
continue;
}
texture &texture = _textures.emplace_back(info);
texture.effect_index = effect.index;
if (info.semantic == "COLOR")
texture.impl_reference = texture_reference::back_buffer;
else if (info.semantic == "DEPTH")
texture.impl_reference = texture_reference::depth_buffer;
else if (!info.semantic.empty())
effect.errors += "warning: " + info.unique_name + ": unknown semantic '" + info.semantic + "'\n";
}
_loaded_effects.push_back(effect); // The 'enable_technique' call below needs to access this, so append the effect now
for (const reshadefx::technique_info &info : effect.module.techniques)
{
technique &technique = _techniques.emplace_back(info);
technique.effect_index = effect.index;
technique.hidden = technique.annotation_as_int("hidden") != 0;
technique.timeout = technique.annotation_as_int("timeout");
technique.timeleft = technique.timeout;
technique.toggle_key_data[0] = technique.annotation_as_int("toggle");
technique.toggle_key_data[1] = technique.annotation_as_int("togglectrl");
technique.toggle_key_data[2] = technique.annotation_as_int("toggleshift");
technique.toggle_key_data[3] = technique.annotation_as_int("togglealt");
if (technique.annotation_as_int("enabled"))
enable_technique(technique);
}
if (effect.compile_sucess)
if (effect.errors.empty())
LOG(INFO) << "Successfully loaded " << path << '.';
else
LOG(WARN) << "Successfully loaded " << path << " with warnings:\n" << effect.errors;
_reload_remaining_effects--;
_last_reload_successful &= effect.compile_sucess;
}
void reshade::runtime::load_effects()
{
// Clear out any previous effects
unload_effects();
_last_reload_successful = true;
// Reload preprocessor definitions from current preset before compiling
if (!_current_preset_path.empty())
{
_preset_preprocessor_definitions.clear();
const ini_file &preset = ini_file::load_cache(_current_preset_path);
preset.get({}, "PreprocessorDefinitions", _preset_preprocessor_definitions);
}
// Build a list of effect files by walking through the effect search paths
const std::vector<std::filesystem::path> effect_files =
find_files(_effect_search_paths, { ".fx" });
_reload_total_effects = effect_files.size();
_reload_remaining_effects = _reload_total_effects;
if (_reload_total_effects == 0)
return; // No effect files found, so nothing more to do
// Now that we have a list of files, load them in parallel
// Split workload into batches instead of launching a thread for every file to avoid launch overhead and stutters due to too many threads being in flight
const size_t num_splits = std::min<size_t>(effect_files.size(), std::max<size_t>(std::thread::hardware_concurrency(), 2u) - 1);
// Keep track of the spawned threads, so the runtime cannot be destroyed while they are still running
for (size_t n = 0; n < num_splits; ++n)
_worker_threads.emplace_back([this, effect_files, num_splits, n]() {
for (size_t id, i = 0; i < effect_files.size(); ++i)
if (i * num_splits / effect_files.size() == n)
load_effect(effect_files[i], id);
});
}
void reshade::runtime::load_textures()
{
LOG(INFO) << "Loading image files for textures ...";
for (texture &texture : _textures)
{
if (texture.impl == nullptr || texture.impl_reference != texture_reference::none)
continue; // Ignore textures that are not created yet and those that are handled in the runtime implementation
std::filesystem::path source_path = std::filesystem::u8path(
texture.annotation_as_string("source"));
// Ignore textures that have no image file attached to them (e.g. plain render targets)
if (source_path.empty())
continue;
// Search for image file using the provided search paths unless the path provided is already absolute
if (!find_file(_texture_search_paths, source_path)) {
LOG(ERROR) << "> Source " << source_path << " for texture '" << texture.unique_name << "' could not be found in any of the texture search paths.";
continue;
}
unsigned char *filedata = nullptr;
int width = 0, height = 0, channels = 0;
if (FILE *file; _wfopen_s(&file, source_path.c_str(), L"rb") == 0)
{
// Read texture data into memory in one go since that is faster than reading chunk by chunk
std::vector<uint8_t> mem(static_cast<size_t>(std::filesystem::file_size(source_path)));
fread(mem.data(), 1, mem.size(), file);
fclose(file);
if (stbi_dds_test_memory(mem.data(), static_cast<int>(mem.size())))
filedata = stbi_dds_load_from_memory(mem.data(), static_cast<int>(mem.size()), &width, &height, &channels, STBI_rgb_alpha);
else
filedata = stbi_load_from_memory(mem.data(), static_cast<int>(mem.size()), &width, &height, &channels, STBI_rgb_alpha);
}
if (filedata == nullptr) {
LOG(ERROR) << "> Source " << source_path << " for texture '" << texture.unique_name << "' could not be loaded! Make sure it is of a compatible file format.";
continue;
}
// Need to potentially resize image data to the texture dimensions
if (texture.width != uint32_t(width) || texture.height != uint32_t(height))
{
LOG(INFO) << "> Resizing image data for texture '" << texture.unique_name << "' from " << width << "x" << height << " to " << texture.width << "x" << texture.height << " ...";
std::vector<uint8_t> resized(texture.width * texture.height * 4);
stbir_resize_uint8(filedata, width, height, 0, resized.data(), texture.width, texture.height, 0, 4);
upload_texture(texture, resized.data());
}
else
{
upload_texture(texture, filedata);
}
stbi_image_free(filedata);
}
_textures_loaded = true;
}
void reshade::runtime::unload_effect(size_t id)
{
#if RESHADE_GUI
_selected_effect = std::numeric_limits<size_t>::max();
_selected_effect_changed = true; // Force editor to clear text after effects where reloaded
_preview_texture = nullptr;
_effect_filter_buffer[0] = '\0'; // And reset filter too, since the list of techniques might have changed
#endif
_uniforms.erase(std::remove_if(_uniforms.begin(), _uniforms.end(),
[id](const auto &it) { return it.effect_index == id; }), _uniforms.end());
_textures.erase(std::remove_if(_textures.begin(), _textures.end(),
[id](const auto &it) { return it.effect_index == id; }), _textures.end());
_techniques.erase(std::remove_if(_techniques.begin(), _techniques.end(),
[id](const auto &it) { return it.effect_index == id; }), _techniques.end());
_loaded_effects[id].source_file.clear();
}
void reshade::runtime::unload_effects()
{
#if RESHADE_GUI
_selected_effect = std::numeric_limits<size_t>::max();
_selected_effect_changed = true; // Force editor to clear text after effects where reloaded
_preview_texture = nullptr;
_effect_filter_buffer[0] = '\0'; // And reset filter too, since the list of techniques might have changed
#endif
// Make sure no threads are still accessing effect data
for (std::thread &thread : _worker_threads)
thread.join();
_worker_threads.clear();
_uniforms.clear();
_textures.clear();
_techniques.clear();
_loaded_effects.clear();
_uniform_data_storage.clear();
_textures_loaded = false;
}
void reshade::runtime::update_and_render_effects()
{
// Delay first load to the first render call to avoid loading while the application is still initializing
if (_framecount == 0 && !_no_reload_on_init)
load_effects();
if (_reload_remaining_effects == 0)
{
// Finished loading effects, so apply preset to figure out which ones need compiling
load_current_preset();
_last_reload_time = std::chrono::high_resolution_clock::now();
_reload_total_effects = 0;
_reload_remaining_effects = std::numeric_limits<size_t>::max();
}
else if (_reload_remaining_effects != std::numeric_limits<size_t>::max())
{
return; // Cannot render while effects are still being loaded
}
else
{
if (!_reload_compile_queue.empty())
{
// Pop an effect from the queue
size_t effect_index = _reload_compile_queue.back();
_reload_compile_queue.pop_back();
effect_data &effect = _loaded_effects[effect_index];
// Create textures now, since they are referenced when building samplers in the 'compile_effect' call below
bool success = true;
for (texture &texture : _textures)
{
if (texture.impl == nullptr && (texture.effect_index == effect_index || texture.shared))
{
if (!init_texture(texture))
{
success = false;
effect.errors += "Failed to create texture " + texture.unique_name;
break;
}
}
}
// Compile the effect with the back-end implementation
if (success && !compile_effect(effect))
{
// De-duplicate error lines (D3DCompiler sometimes repeats the same error multiple times)
for (size_t cur_line_offset = 0, next_line_offset, end_offset;
(next_line_offset = effect.errors.find('\n', cur_line_offset)) != std::string::npos && (end_offset = effect.errors.find('\n', next_line_offset + 1)) != std::string::npos; cur_line_offset = next_line_offset + 1)
{
const std::string_view cur_line(effect.errors.c_str() + cur_line_offset, next_line_offset - cur_line_offset);
const std::string_view next_line(effect.errors.c_str() + next_line_offset + 1, end_offset - next_line_offset - 1);
if (cur_line == next_line)
{
effect.errors.erase(next_line_offset, end_offset - next_line_offset);
next_line_offset = cur_line_offset - 1;
}
}
LOG(ERROR) << "Failed to compile " << effect.source_file << ":\n" << effect.errors;
success = false;
}
if (!success) // Something went wrong, do clean up
{
// Destroy all textures belonging to this effect
for (texture &texture : _textures)
if (texture.effect_index == effect_index && !texture.shared)
texture.impl.reset();
// Disable all techniques belonging to this effect
for (technique &technique : _techniques)
if (technique.effect_index == effect_index)
disable_technique(technique);
effect.compile_sucess = false;
_last_reload_successful = false;
}
effect.runtime_loaded = success;
// An effect has changed, need to reload textures
_textures_loaded = false;
}
else if (!_textures_loaded)
{
// Now that all effects were compiled, load all textures
load_textures();
}
}
// Lock input so it cannot be modified by other threads while we are reading it here
// TODO: This does not catch input happening between now and 'on_present'
const auto input_lock = _input->lock();
if (_should_save_screenshot && (_screenshot_save_before || !_effects_enabled))
save_screenshot(_effects_enabled ? L"-original" : std::wstring(), !_effects_enabled);
// Nothing to do here if effects are disabled globally
if (!_effects_enabled)
{
_should_save_screenshot = false;
return;
}
// Update special uniform variables
for (uniform &variable : _uniforms)
{
if (!_ignore_shortcuts && variable.toggle_key_data[0] != 0 && _input->is_key_pressed(variable.toggle_key_data))
{
assert(variable.supports_toggle_key());
// Change to next value if the associated shortcut key was pressed
switch (variable.type.base)
{
case reshadefx::type::t_bool: {
bool data;
get_uniform_value(variable, &data, 1);
set_uniform_value(variable, !data);
break; }
case reshadefx::type::t_int:
case reshadefx::type::t_uint: {
int data[4];
get_uniform_value(variable, data, 4);
const std::string_view ui_items = variable.annotation_as_string("ui_items");
size_t num_items = 0;
for (size_t offset = 0, next; (next = ui_items.find('\0', offset)) != std::string::npos; offset = next + 1)
num_items++;
data[0] = (data[0] + 1 >= num_items) ? 0 : data[0] + 1;
set_uniform_value(variable, data, 4);
break; }
}
save_current_preset();
}
switch (variable.special)
{
case special_uniform::frame_time:
set_uniform_value(variable, _last_frame_duration.count() * 1e-6f, 0.0f, 0.0f, 0.0f);
break;
case special_uniform::frame_count:
if (variable.type.is_boolean())
set_uniform_value(variable, (_framecount % 2) == 0);
else
set_uniform_value(variable, static_cast<unsigned int>(_framecount % UINT_MAX));
break;
case special_uniform::random: {
const int min = variable.annotation_as_int("min");
const int max = variable.annotation_as_int("max");
set_uniform_value(variable, min + (std::rand() % (max - min + 1)));
break; }
case special_uniform::ping_pong: {
const float min = variable.annotation_as_float("min");
const float max = variable.annotation_as_float("max");
const float step_min = variable.annotation_as_float("step", 0);
const float step_max = variable.annotation_as_float("step", 1);
float increment = step_max == 0 ? step_min : (step_min + std::fmodf(static_cast<float>(std::rand()), step_max - step_min + 1));
const float smoothing = variable.annotation_as_float("smoothing");
float value[2] = { 0, 0 };
get_uniform_value(variable, value, 2);
if (value[1] >= 0)
{
increment = std::max(increment - std::max(0.0f, smoothing - (max - value[0])), 0.05f);
increment *= _last_frame_duration.count() * 1e-9f;
if ((value[0] += increment) >= max)
value[0] = max, value[1] = -1;
}
else
{
increment = std::max(increment - std::max(0.0f, smoothing - (value[0] - min)), 0.05f);
increment *= _last_frame_duration.count() * 1e-9f;
if ((value[0] -= increment) <= min)
value[0] = min, value[1] = +1;
}
set_uniform_value(variable, value, 2);
break; }
case special_uniform::date:
set_uniform_value(variable, _date, 4);
break;
case special_uniform::timer:
set_uniform_value(variable, static_cast<unsigned int>(std::chrono::duration_cast<std::chrono::milliseconds>(_last_present_time - _start_time).count()));
break;
case special_uniform::key:
if (const int keycode = variable.annotation_as_int("keycode");
keycode > 7 && keycode < 256)
if (const std::string_view mode = variable.annotation_as_string("mode");
mode == "toggle" || variable.annotation_as_int("toggle")) {
bool current_value = false;
get_uniform_value(variable, ¤t_value, 1);
if (_input->is_key_pressed(keycode))
set_uniform_value(variable, !current_value);
} else if (mode == "press")
set_uniform_value(variable, _input->is_key_pressed(keycode));
else
set_uniform_value(variable, _input->is_key_down(keycode));
break;
case special_uniform::mouse_point:
set_uniform_value(variable, _input->mouse_position_x(), _input->mouse_position_y());
break;
case special_uniform::mouse_delta:
set_uniform_value(variable, _input->mouse_movement_delta_x(), _input->mouse_movement_delta_y());
break;
case special_uniform::mouse_button:
if (const int keycode = variable.annotation_as_int("keycode");
keycode >= 0 && keycode < 5)
if (const std::string_view mode = variable.annotation_as_string("mode");
mode == "toggle" || variable.annotation_as_int("toggle")) {
bool current_value = false;
get_uniform_value(variable, ¤t_value, 1);
if (_input->is_mouse_button_pressed(keycode))
set_uniform_value(variable, !current_value);
} else if (mode == "press")
set_uniform_value(variable, _input->is_mouse_button_pressed(keycode));
else
set_uniform_value(variable, _input->is_mouse_button_down(keycode));
break;
}
}
// Render all enabled techniques
for (technique &technique : _techniques)
{
if (technique.timeleft > 0)
{
technique.timeleft -= std::chrono::duration_cast<std::chrono::milliseconds>(_last_frame_duration).count();
if (technique.timeleft <= 0)
disable_technique(technique);
}
else if (!_ignore_shortcuts && (_input->is_key_pressed(technique.toggle_key_data) ||
(technique.toggle_key_data[0] >= 0x01 && technique.toggle_key_data[0] <= 0x06 && _input->is_mouse_button_pressed(technique.toggle_key_data[0] - 1))))
{
if (!technique.enabled)
enable_technique(technique);
else
disable_technique(technique);
}
if (technique.impl == nullptr || !technique.enabled)
continue; // Ignore techniques that are not fully loaded or currently disabled
const auto time_technique_started = std::chrono::high_resolution_clock::now();
render_technique(technique);
const auto time_technique_finished = std::chrono::high_resolution_clock::now();
technique.average_cpu_duration.append(std::chrono::duration_cast<std::chrono::nanoseconds>(time_technique_finished - time_technique_started).count());
}
if (_should_save_screenshot)
{
save_screenshot(std::wstring(), true);
_should_save_screenshot = false;
}
}
void reshade::runtime::enable_technique(technique &technique)
{
if (!_loaded_effects[technique.effect_index].compile_sucess)
return; // Cannot enable techniques that failed to compile
const bool status_changed = !technique.enabled;
technique.enabled = true;
technique.timeleft = technique.timeout;
// Queue effect file for compilation if it was not fully loaded yet
if (technique.impl == nullptr && // Avoid adding the same effect multiple times to the queue if it contains multiple techniques that were enabled simultaneously
std::find(_reload_compile_queue.begin(), _reload_compile_queue.end(), technique.effect_index) == _reload_compile_queue.end())
{
_reload_total_effects++;
_reload_compile_queue.push_back(technique.effect_index);
}
if (status_changed) // Increase rendering reference count
_loaded_effects[technique.effect_index].rendering++;
}
void reshade::runtime::disable_technique(technique &technique)
{
const bool status_changed = technique.enabled;
technique.enabled = false;
technique.timeleft = 0;
technique.average_cpu_duration.clear();
technique.average_gpu_duration.clear();
if (status_changed) // Decrease rendering reference count
_loaded_effects[technique.effect_index].rendering--;
}
void reshade::runtime::subscribe_to_load_config(std::function<void(const ini_file &)> function)
{
_load_config_callables.push_back(function);
function(ini_file::load_cache(_configuration_path));
}
void reshade::runtime::subscribe_to_save_config(std::function<void(ini_file &)> function)
{
_save_config_callables.push_back(function);
function(ini_file::load_cache(_configuration_path));
}
void reshade::runtime::load_config()
{
const ini_file &config = ini_file::load_cache(_configuration_path);
std::filesystem::path current_preset_path;
config.get("INPUT", "KeyReload", _reload_key_data);
config.get("INPUT", "KeyEffects", _effects_key_data);
config.get("INPUT", "KeyScreenshot", _screenshot_key_data);
config.get("INPUT", "KeyPreviousPreset", _previous_preset_key_data);
config.get("INPUT", "KeyNextPreset", _next_preset_key_data);
config.get("INPUT", "PresetTransitionDelay", _preset_transition_delay);
config.get("GENERAL", "PerformanceMode", _performance_mode);
config.get("GENERAL", "EffectSearchPaths", _effect_search_paths);
config.get("GENERAL", "TextureSearchPaths", _texture_search_paths);
config.get("GENERAL", "PreprocessorDefinitions", _global_preprocessor_definitions);
config.get("GENERAL", "CurrentPresetPath", current_preset_path);
config.get("GENERAL", "ScreenshotPath", _screenshot_path);
config.get("GENERAL", "ScreenshotFormat", _screenshot_format);
config.get("GENERAL", "ScreenshotIncludePreset", _screenshot_include_preset);
config.get("GENERAL", "ScreenshotSaveBefore", _screenshot_save_before);
config.get("GENERAL", "NoReloadOnInit", _no_reload_on_init);
if (current_preset_path.empty())
{
// Convert legacy preset index to new preset path
size_t preset_index = 0;
std::vector<std::filesystem::path> preset_files;
config.get("GENERAL", "PresetFiles", preset_files);
config.get("GENERAL", "CurrentPreset", preset_index);
if (preset_index < preset_files.size())
current_preset_path = preset_files[preset_index];
}
if (check_preset_path(current_preset_path))
_current_preset_path = g_reshade_dll_path.parent_path() / current_preset_path;
else // Select a default preset file if none exists yet
_current_preset_path = g_reshade_dll_path.parent_path() / L"DefaultPreset.ini";
for (const auto &callback : _load_config_callables)
callback(config);
}
void reshade::runtime::save_config() const
{
ini_file &config = ini_file::load_cache(_configuration_path);
config.set("INPUT", "KeyReload", _reload_key_data);
config.set("INPUT", "KeyEffects", _effects_key_data);
config.set("INPUT", "KeyScreenshot", _screenshot_key_data);
config.set("INPUT", "KeyPreviousPreset", _previous_preset_key_data);
config.set("INPUT", "KeyNextPreset", _next_preset_key_data);
config.set("INPUT", "PresetTransitionDelay", _preset_transition_delay);
config.set("GENERAL", "PerformanceMode", _performance_mode);
config.set("GENERAL", "EffectSearchPaths", _effect_search_paths);
config.set("GENERAL", "TextureSearchPaths", _texture_search_paths);
config.set("GENERAL", "PreprocessorDefinitions", _global_preprocessor_definitions);
config.set("GENERAL", "CurrentPresetPath", _current_preset_path);
config.set("GENERAL", "ScreenshotPath", _screenshot_path);
config.set("GENERAL", "ScreenshotFormat", _screenshot_format);
config.set("GENERAL", "ScreenshotIncludePreset", _screenshot_include_preset);
config.set("GENERAL", "ScreenshotSaveBefore", _screenshot_save_before);
config.set("GENERAL", "NoReloadOnInit", _no_reload_on_init);
for (const auto &callback : _save_config_callables)
callback(config);
}
void reshade::runtime::load_current_preset()
{
const reshade::ini_file &preset = ini_file::load_cache(_current_preset_path);
std::vector<std::string> technique_list;
preset.get({}, "Techniques", technique_list);
std::vector<std::string> sorted_technique_list;
preset.get({}, "TechniqueSorting", sorted_technique_list);
std::vector<std::string> preset_preprocessor_definitions;
preset.get({}, "PreprocessorDefinitions", preset_preprocessor_definitions);
// Recompile effects if preprocessor definitions have changed or running in performance mode (in which case all preset values are compile-time constants)
if (_reload_remaining_effects != 0 && // ... unless this is the 'load_current_preset' call in 'update_and_render_effects'
(_performance_mode || preset_preprocessor_definitions != _preset_preprocessor_definitions))
{
_preset_preprocessor_definitions = std::move(preset_preprocessor_definitions);
load_effects();
return; // Preset values are loaded in 'update_and_render_effects' during effect loading
}
// Reorder techniques
if (sorted_technique_list.empty())
sorted_technique_list = technique_list;
std::sort(_techniques.begin(), _techniques.end(),
[&sorted_technique_list](const auto &lhs, const auto &rhs) {
return (std::find(sorted_technique_list.begin(), sorted_technique_list.end(), lhs.name) - sorted_technique_list.begin()) <
(std::find(sorted_technique_list.begin(), sorted_technique_list.end(), rhs.name) - sorted_technique_list.begin());
});
// Compute times since the transition has started and how much is left till it should end
auto transition_time = std::chrono::duration_cast<std::chrono::microseconds>(_last_present_time - _last_preset_switching_time).count();
auto transition_ms_left = _preset_transition_delay - transition_time / 1000;
auto transition_ms_left_from_last_frame = transition_ms_left + std::chrono::duration_cast<std::chrono::microseconds>(_last_frame_duration).count() / 1000;
if (_is_in_between_presets_transition && transition_ms_left <= 0)
_is_in_between_presets_transition = false;
for (uniform &variable : _uniforms)
{
const std::string section = _loaded_effects[variable.effect_index].source_file.filename().u8string();
reshadefx::constant values, values_old;
if (variable.supports_toggle_key())
{
// Load shortcut key, but first reset it, since it may not exist in the preset file
memset(variable.toggle_key_data, 0, sizeof(variable.toggle_key_data));
preset.get(section, "Key" + variable.name, variable.toggle_key_data);
}
switch (variable.type.base)
{
case reshadefx::type::t_int:
get_uniform_value(variable, values.as_int, 16);
preset.get(section, variable.name, values.as_int);
set_uniform_value(variable, values.as_int, 16);
break;
case reshadefx::type::t_bool:
case reshadefx::type::t_uint:
get_uniform_value(variable, values.as_uint, 16);
preset.get(section, variable.name, values.as_uint);
set_uniform_value(variable, values.as_uint, 16);
break;
case reshadefx::type::t_float:
get_uniform_value(variable, values.as_float, 16);
values_old = values;
preset.get(section, variable.name, values.as_float);
if (_is_in_between_presets_transition)
{
// Perform smooth transition on floating point values
for (unsigned int i = 0; i < 16; i++)
{
const auto transition_ratio = (values.as_float[i] - values_old.as_float[i]) / transition_ms_left_from_last_frame;
values.as_float[i] = values.as_float[i] - transition_ratio * transition_ms_left;
}
}
set_uniform_value(variable, values.as_float, 16);
break;
}
}
for (technique &technique : _techniques)
{
// Ignore preset if "enabled" annotation is set
if (technique.annotation_as_int("enabled")
|| std::find(technique_list.begin(), technique_list.end(), technique.name) != technique_list.end())
enable_technique(technique);
else
disable_technique(technique);
// Reset toggle key first, since it may not exist in the preset
memset(technique.toggle_key_data, 0, sizeof(technique.toggle_key_data));
preset.get({}, "Key" + technique.name, technique.toggle_key_data);
}
}
void reshade::runtime::save_current_preset() const
{
reshade::ini_file &preset = ini_file::load_cache(_current_preset_path);
// Build list of active techniques and effects
std::vector<size_t> effect_list;
std::vector<std::string> technique_list;
std::vector<std::string> sorted_technique_list;
effect_list.reserve(_techniques.size());
technique_list.reserve(_techniques.size());
sorted_technique_list.reserve(_techniques.size());
for (const technique &technique : _techniques)
{
if (technique.enabled)
technique_list.push_back(technique.name);
if (technique.enabled || technique.toggle_key_data[0] != 0)
effect_list.push_back(technique.effect_index);
// Keep track of the order of all techniques and not just the enabled ones
sorted_technique_list.push_back(technique.name);
if (technique.toggle_key_data[0] != 0)
preset.set({}, "Key" + technique.name, technique.toggle_key_data);
else if (int value = 0; preset.get({}, "Key" + technique.name, value), value != 0)
preset.set({}, "Key" + technique.name, 0); // Clear toggle key data
}
preset.set({}, "Techniques", std::move(technique_list));
preset.set({}, "TechniqueSorting", std::move(sorted_technique_list));
preset.set({}, "PreprocessorDefinitions", _preset_preprocessor_definitions);
// TODO: Do we want to save spec constants here too? The preset will be rather empty in performance mode otherwise.
for (const uniform &variable : _uniforms)
{
if (variable.special != special_uniform::none
|| std::find(effect_list.begin(), effect_list.end(), variable.effect_index) == effect_list.end())
continue;
assert(variable.type.components() <= 16);
const std::string section = _loaded_effects[variable.effect_index].source_file.filename().u8string();
reshadefx::constant values;
if (variable.supports_toggle_key())
{
// save the shortcut key into the preset files
if (variable.toggle_key_data[0] != 0)
preset.set(section, "Key" + variable.name, variable.toggle_key_data);
else if (int value = 0; preset.get(section, "Key" + variable.name, value), value != 0)
preset.set(section, "Key" + variable.name, 0); // Clear toggle key data
}
switch (variable.type.base)
{
case reshadefx::type::t_int:
get_uniform_value(variable, values.as_int, 16);
preset.set(section, variable.name, values.as_int, variable.type.components());
break;
case reshadefx::type::t_bool:
case reshadefx::type::t_uint:
get_uniform_value(variable, values.as_uint, 16);
preset.set(section, variable.name, values.as_uint, variable.type.components());
break;
case reshadefx::type::t_float:
get_uniform_value(variable, values.as_float, 16);
preset.set(section, variable.name, values.as_float, variable.type.components());
break;
}
}
}
bool reshade::runtime::switch_to_next_preset(const std::filesystem::path &filter_path, bool reversed)
{
std::error_code ec; // This is here to ignore file system errors below
std::filesystem::path filter_text = filter_path.filename();
std::filesystem::path search_path = absolute_path(filter_path);
if (std::filesystem::is_directory(search_path, ec))
filter_text.clear();
else if (!filter_text.empty())
search_path = search_path.parent_path();
size_t current_preset_index = std::numeric_limits<size_t>::max();
std::vector<std::filesystem::path> preset_paths;
for (const auto &entry : std::filesystem::directory_iterator(search_path, std::filesystem::directory_options::skip_permission_denied, ec))
{
// Skip anything that is not a valid preset file
if (!check_preset_path(entry.path()))
continue;
// Keep track of the index of the current preset in the list of found preset files that is being build
if (std::filesystem::equivalent(entry, _current_preset_path, ec)) {
current_preset_index = preset_paths.size();
preset_paths.push_back(entry);
continue;
}
const std::wstring preset_name = entry.path().stem();
// Only add those files that are matching the filter text
if (filter_text.empty() || std::search(preset_name.begin(), preset_name.end(), filter_text.native().begin(), filter_text.native().end(),
[](wchar_t c1, wchar_t c2) { return towlower(c1) == towlower(c2); }) != preset_name.end())
preset_paths.push_back(entry);
}
if (preset_paths.begin() == preset_paths.end())
return false; // No valid preset files were found, so nothing more to do
if (current_preset_index == std::numeric_limits<size_t>::max())
{
// Current preset was not in the container path, so just use the first or last file
if (reversed)
_current_preset_path = preset_paths.back();
else
_current_preset_path = preset_paths.front();
}
else
{
// Current preset was found in the container path, so use the file before or after it
if (auto it = std::next(preset_paths.begin(), current_preset_index); reversed)
_current_preset_path = it == preset_paths.begin() ? preset_paths.back() : *--it;
else
_current_preset_path = it == std::prev(preset_paths.end()) ? preset_paths.front() : *++it;
}
return true;
}
void reshade::runtime::save_screenshot(const std::wstring &postfix, const bool should_save_preset)
{
const int hour = _date[3] / 3600;
const int minute = (_date[3] - hour * 3600) / 60;
const int seconds = _date[3] - hour * 3600 - minute * 60;
char filename[21];
sprintf_s(filename, " %.4d-%.2d-%.2d %.2d-%.2d-%.2d", _date[0], _date[1], _date[2], hour, minute, seconds);
const std::wstring least = (_screenshot_path.is_relative() ? g_target_executable_path.parent_path() / _screenshot_path : _screenshot_path) / g_target_executable_path.stem().concat(filename);
const std::wstring screenshot_path = least + postfix + (_screenshot_format == 0 ? L".bmp" : L".png");
LOG(INFO) << "Saving screenshot to " << screenshot_path << " ...";
_screenshot_save_success = false; // Default to a save failure unless it is reported to succeed below
if (std::vector<uint8_t> data(_width * _height * 4); capture_screenshot(data.data()))
{
if (FILE *file; _wfopen_s(&file, screenshot_path.c_str(), L"wb") == 0)
{
const auto write_callback = [](void *context, void *data, int size) {
fwrite(data, 1, size, static_cast<FILE *>(context));
};
switch (_screenshot_format)
{
case 0:
_screenshot_save_success = stbi_write_bmp_to_func(write_callback, file, _width, _height, 4, data.data()) != 0;
break;
case 1:
_screenshot_save_success = stbi_write_png_to_func(write_callback, file, _width, _height, 4, data.data(), 0) != 0;
break;
}
fclose(file);
}
}
_last_screenshot_file = screenshot_path;
_last_screenshot_time = std::chrono::high_resolution_clock::now();
if (!_screenshot_save_success)
{
LOG(ERROR) << "Failed to write screenshot to " << screenshot_path << '!';
}
else if (_screenshot_include_preset && should_save_preset && ini_file::flush_cache(_current_preset_path))
{
// Preset was flushed to disk, so can just copy it over to the new location
std::error_code ec; std::filesystem::copy_file(_current_preset_path, least + L".ini", std::filesystem::copy_options::overwrite_existing, ec);
}
}
void reshade::runtime::get_uniform_value(const uniform &variable, uint8_t *data, size_t size) const
{
assert(data != nullptr);
size = std::min(size, size_t(variable.size));
assert(variable.storage_offset + size <= _uniform_data_storage.size());
std::memcpy(data, &_uniform_data_storage[variable.storage_offset], size);
}
void reshade::runtime::get_uniform_value(const uniform &variable, bool *values, size_t count) const
{
count = std::min(count, size_t(variable.size / 4));
assert(values != nullptr);
const auto data = static_cast<uint8_t *>(alloca(variable.size));
get_uniform_value(variable, data, variable.size);
for (size_t i = 0; i < count; i++)
values[i] = reinterpret_cast<const uint32_t *>(data)[i] != 0;
}
void reshade::runtime::get_uniform_value(const uniform &variable, int32_t *values, size_t count) const
{
if (!variable.type.is_floating_point() && _renderer_id != 0x9000)
{
get_uniform_value(variable, reinterpret_cast<uint8_t *>(values), count * sizeof(int32_t));
return;
}
count = std::min(count, variable.size / sizeof(float));
assert(values != nullptr);
const auto data = static_cast<uint8_t *>(alloca(variable.size));
get_uniform_value(variable, data, variable.size);
for (size_t i = 0; i < count; i++)
values[i] = static_cast<int32_t>(reinterpret_cast<const float *>(data)[i]);
}
void reshade::runtime::get_uniform_value(const uniform &variable, uint32_t *values, size_t count) const
{
get_uniform_value(variable, reinterpret_cast<int32_t *>(values), count);
}
void reshade::runtime::get_uniform_value(const uniform &variable, float *values, size_t count) const
{
if (variable.type.is_floating_point() || _renderer_id == 0x9000)
{
get_uniform_value(variable, reinterpret_cast<uint8_t *>(values), count * sizeof(float));
return;
}
count = std::min(count, variable.size / sizeof(int32_t));
assert(values != nullptr);
const auto data = static_cast<uint8_t *>(alloca(variable.size));
get_uniform_value(variable, data, variable.size);
for (size_t i = 0; i < count; ++i)
if (variable.type.is_signed())
values[i] = static_cast<float>(reinterpret_cast<const int32_t *>(data)[i]);
else
values[i] = static_cast<float>(reinterpret_cast<const uint32_t *>(data)[i]);
}
void reshade::runtime::set_uniform_value(uniform &variable, const uint8_t *data, size_t size)
{
assert(data != nullptr);
size = std::min(size, size_t(variable.size));
assert(variable.storage_offset + size <= _uniform_data_storage.size());
std::memcpy(&_uniform_data_storage[variable.storage_offset], data, size);
}
void reshade::runtime::set_uniform_value(uniform &variable, const bool *values, size_t count)
{
const auto data = static_cast<uint8_t *>(alloca(count * 4));
switch (_renderer_id != 0x9000 ? variable.type.base : reshadefx::type::t_float)
{
case reshadefx::type::t_bool:
for (size_t i = 0; i < count; ++i)
reinterpret_cast<int32_t *>(data)[i] = values[i] ? -1 : 0;
break;
case reshadefx::type::t_int:
case reshadefx::type::t_uint:
for (size_t i = 0; i < count; ++i)
reinterpret_cast<int32_t *>(data)[i] = values[i] ? 1 : 0;
break;
case reshadefx::type::t_float:
for (size_t i = 0; i < count; ++i)
reinterpret_cast<float *>(data)[i] = values[i] ? 1.0f : 0.0f;
break;
}
set_uniform_value(variable, data, count * 4);
}
void reshade::runtime::set_uniform_value(uniform &variable, const int32_t *values, size_t count)
{
if (!variable.type.is_floating_point() && _renderer_id != 0x9000)
{
set_uniform_value(variable, reinterpret_cast<const uint8_t *>(values), count * sizeof(int));
return;
}
const auto data = static_cast<float *>(alloca(count * sizeof(float)));
for (size_t i = 0; i < count; ++i)
data[i] = static_cast<float>(values[i]);
set_uniform_value(variable, reinterpret_cast<const uint8_t *>(data), count * sizeof(float));
}
void reshade::runtime::set_uniform_value(uniform &variable, const uint32_t *values, size_t count)
{
if (!variable.type.is_floating_point() && _renderer_id != 0x9000)
{
set_uniform_value(variable, reinterpret_cast<const uint8_t *>(values), count * sizeof(int));
return;
}
const auto data = static_cast<float *>(alloca(count * sizeof(float)));
for (size_t i = 0; i < count; ++i)
data[i] = static_cast<float>(values[i]);
set_uniform_value(variable, reinterpret_cast<const uint8_t *>(data), count * sizeof(float));
}
void reshade::runtime::set_uniform_value(uniform &variable, const float *values, size_t count)
{
if (variable.type.is_floating_point() || _renderer_id == 0x9000)
{
set_uniform_value(variable, reinterpret_cast<const uint8_t *>(values), count * sizeof(float));
return;
}
const auto data = static_cast<int32_t *>(alloca(count * sizeof(int32_t)));
for (size_t i = 0; i < count; ++i)
data[i] = static_cast<int32_t>(values[i]);
set_uniform_value(variable, reinterpret_cast<const uint8_t *>(data), count * sizeof(int32_t));
}
void reshade::runtime::reset_uniform_value(uniform &variable)
{
if (!variable.has_initializer_value)
{
memset(_uniform_data_storage.data() + variable.storage_offset, 0, variable.size);
return;
}
if (_renderer_id == 0x9000)
{
// Force all uniforms to floating-point in D3D9
for (size_t i = 0; i < variable.size / sizeof(float); i++)
{
switch (variable.type.base)
{
case reshadefx::type::t_int:
reinterpret_cast<float *>(_uniform_data_storage.data() + variable.storage_offset)[i] = static_cast<float>(variable.initializer_value.as_int[i]);
break;
case reshadefx::type::t_bool:
case reshadefx::type::t_uint:
reinterpret_cast<float *>(_uniform_data_storage.data() + variable.storage_offset)[i] = static_cast<float>(variable.initializer_value.as_uint[i]);
break;
case reshadefx::type::t_float:
reinterpret_cast<float *>(_uniform_data_storage.data() + variable.storage_offset)[i] = variable.initializer_value.as_float[i];
break;
}
}
}
else
{
memcpy(_uniform_data_storage.data() + variable.storage_offset, variable.initializer_value.as_uint, variable.size);
}
}
|
[
"crosiredev@gmail.com"
] |
crosiredev@gmail.com
|
f9953f24a36e419415c3ac1be27839a2dfc223b4
|
16ebac78d01241c999ea11bd3e7ab73d11bea51e
|
/src/Scene2.h
|
8323407bacd378af4f0763ad3dd33fd97df72818
|
[] |
no_license
|
qingqhua/draw_the_world
|
1dcf904a15f4b6d5cdac755dc50d30be2fa181fe
|
4189778b5b4adc1949d168cad79eb2d730960a15
|
refs/heads/master
| 2021-06-23T21:00:46.641813
| 2017-09-04T06:40:03
| 2017-09-04T06:40:03
| 83,887,038
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 769
|
h
|
#pragma once
#include "ofApp.h"
#include "baseScene.h"
class Scene2 : public baseScene {
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y);
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void initSequenceClimb();
void drawSequenceClimb();
private:
ofImage Background;//第一张背景
ofRectangle AreaUp;//向上的箭头位置
ofRectangle AreaLeft;//向左的箭头位置
ofRectangle AreaRight;//向右的箭头位置
vector <ofImage> climb;
int climbIndex;
bool ClimbAni,HasClimb;
ofSoundPlayer Tree;
EffectTree effect_Tree;
};
|
[
"ferhua.coder@outlook.com"
] |
ferhua.coder@outlook.com
|
73e1831292033bb8bfbcb11dd3a0fc65034de9c7
|
14c2d3193d39e973e00df21351ed5d0186526dd2
|
/ch3/RacingCarOuterFunc.cpp
|
2982d3a285de9f2dcc254e28c26544da425082d0
|
[] |
no_license
|
younnggsuk/cpp
|
f914b8deb6436b527615bf30ee0b040526648ca8
|
2b99d9e447ad7c91f49bbd38b4b18b74c0a98dac
|
refs/heads/master
| 2020-05-19T08:43:58.955580
| 2019-05-04T17:58:53
| 2019-05-04T17:58:53
| 184,927,631
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,090
|
cpp
|
#include <iostream>
using std::endl;
using std::cout;
using std::cin;
namespace CAR_CONST
{
enum
{
ID_LEN = 20,
MAX_SPD = 200,
ACC_STEP = 10,
BRK_STEP = 10,
FUEL_STEP = 2
};
}
struct Car{
char gamerID[CAR_CONST::ID_LEN];
int fuelGauge;
int curSpeed;
void ShowCarState();
void Accel();
void Break();
};
int main(void)
{
Car car1 = {"car1", 100, 0};
Car car2 = {"car2", 100, 0};
car1.Accel();
car1.Accel();
car1.ShowCarState();
car1.Break();
car1.ShowCarState();
car2.Accel();
car2.Break();
car2.ShowCarState();
return 0;
}
inline void Car::ShowCarState()
{
cout<<"ID : "<<gamerID<<endl;
cout<<"Fuel : "<<fuelGauge<<"%"<<endl;
cout<<"Speed : "<<curSpeed<<"km/h"<<endl<<endl;
}
inline void Car::Accel()
{
if(fuelGauge <= 0)
return;
else
fuelGauge -= CAR_CONST::FUEL_STEP;
if((curSpeed + CAR_CONST::ACC_STEP) >= CAR_CONST::MAX_SPD)
{
curSpeed = CAR_CONST::MAX_SPD;
return;
}
curSpeed += CAR_CONST::ACC_STEP;
}
inline void Car::Break()
{
if(curSpeed <= 0)
{
curSpeed = 0;
return;
}
curSpeed -= CAR_CONST::BRK_STEP;
}
|
[
"younnggsuk@naver.com"
] |
younnggsuk@naver.com
|
88a35fb98409165a97f50a8c992dba285994c378
|
4c6bddbe93a8d3d525184a80548d0d7e76d51084
|
/GVRf/Framework/framework/src/main/jni/objects/components/component_types.h
|
344e4c7be445bb96c65ad27f4e31ee588ee1e5a9
|
[
"Apache-2.0"
] |
permissive
|
corgiflash/GearVRf
|
c54b8a8932159a1fa8ec7315ddc765d88fa9e3da
|
54135fc7bd961ab47aba599e60ced3ea0c7e43b1
|
refs/heads/master
| 2020-05-21T06:07:06.766759
| 2017-03-10T16:04:52
| 2017-03-10T16:04:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,458
|
h
|
/* Copyright 2015 Samsung Electronics Co., LTD
*
* 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 COMPONENT_TYPES_H
#define COMPONENT_TYPES_H
namespace gvr {
static const long long COMPONENT_TYPE_TRANSFORM = 10001;
static const long long COMPONENT_TYPE_LIGHT = 10002;
static const long long COMPONENT_TYPE_BONE = 10003;
static const long long COMPONENT_TYPE_BONE_WEIGHT = 10004;
static const long long COMPONENT_TYPE_CAMERA = 10005;
static const long long COMPONENT_TYPE_CAMERA_RIG = 10006;
static const long long COMPONENT_TYPE_COLLIDER = 10007;
static const long long COMPONENT_TYPE_RENDER_DATA = 10008;
static const long long COMPONENT_TYPE_TEXTURE_CAPTURER = 10009;
static const long long COMPONENT_TYPE_PHYSICS_RIGID_BODY = 10010;
static const long long COMPONENT_TYPE_PHYSICS_WORLD = 10011;
}
#endif
|
[
"m.marinov@samsung.com"
] |
m.marinov@samsung.com
|
1402d5e82ce860b92569eae9190e6b009a11294e
|
12ff8204ef7404153fa06cc4a74275fbc132d77d
|
/data_dependency.cpp
|
0993155ceace699b95eacfa879bc7cc5500da0d8
|
[] |
no_license
|
xiaowei0312/coal
|
cbb6aedc9ad72d9b7da5702f69cad29d53d1c20a
|
a8186396cfce5693b902f56988351fd55c43a1e6
|
refs/heads/master
| 2021-07-05T08:12:02.522388
| 2017-09-28T11:30:08
| 2017-09-28T11:30:08
| 105,141,476
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 5,098
|
cpp
|
#include "data_dependency.h"
#include <QStack>
#include <QDebug>
#include <QRegExpValidator>
#include <QMessageBox>
DataDependency::DataDependency()
{
error = 0;
}
bool DataDependency::textIsNotNumber(QString &text)
{
int pos = 0;
QRegExpValidator numReg(QRegExp("^([1-9]\\d{0,15}|0)(\\.\\d{1,4})?$"),this);
if(text.isNull() || text.trimmed().isEmpty()) //依赖项为空
return true;
if(numReg.validate(text,pos) != QValidator::Acceptable) //依赖项不是纯数字(或者小数)
return true;
return false;
}
bool DataDependency::depHasEmptyElement()
{
QString text;
for(int i=0;i<depList_final.size();i++)
{
text = depList_final[i]->text();
if(textIsNotNumber(text))
return true;
}
return false;
}
void DataDependency::markEmptyDepElement()
{
// for(int i=0;i<depList.size();i++)
// {
// if(depList.value(i)->text().trimmed().isEmpty())
// {
// depList.value(i)->setStyleSheet("QLineEdit{border:1px solid green}");
// }
// }
for(int i=0;i<depList.size();i++)
{
depList.value(i)->setStyleSheet("QLineEdit{border:1px solid green}");
}
}
double DataDependency::__execFormula(char *szFormula)
{
QStack<double> stack1;
QStack<char> stack2;
int status = 0;
double dTmp = 0; //数字
double tmp = 10; //小数计算因子,10,100-->1000
int count = 0;
QString text;
char *szTmp;
//qDebug() << szFormula;
while(1){
char c = *szFormula++;
//qDebug() << c;
if(c>='0' && c<='9'){
if(status == 0){
dTmp = 0;
tmp = 10;
status = 1; //计算数字
}
if(status == 1)
dTmp = dTmp * 10 + (c - '0');
else if(status == 2){
dTmp = dTmp + (c-'0')/tmp;
tmp *= 10;
}
}else if(c=='.'){
if(status == 1)
status = 2; //计算数字(小数点之后)
else{
QMessageBox::critical(NULL,QString::fromLocal8Bit("公式错误"),
QString::fromLocal8Bit("公式错误,出现不可预期的小数点"),QMessageBox::Ok);
exit(-1);
}
}else{
if(status != 0){ //数字处理完毕
if(!stack2.empty()){
switch(stack2.top()){
case '-':
dTmp *= -1;
stack2.pop();
stack2.push('+');
break;
case '*':
dTmp *= stack1.pop();
stack2.pop();
break;
case '/':
if(dTmp == 0){
error = 1;
return -1;
}
dTmp = stack1.pop() / dTmp;
stack2.pop();
break;
}
}
stack1.push(dTmp);
status = 0;
}
if(c == 0)
break; //跳出循环
switch(c){
case ' ':
continue;
case '+':
case '-':
case '*':
case '/':
stack2.push(c);
continue;
case 'n':
status = 2;
c = *szFormula++;
text = depList[c-'0'-1]->text();
if(textIsNotNumber(text)){
//qDebug() << QString("Text[") + text + "]is Not number.";
error = 1;
return -1;
}
dTmp = text.toDouble();
break;
case '(':
status = 2;
szTmp = szFormula;
count = 0;
while(*szTmp && count!=1){
char t = *szTmp++;
if(t == '(')
count--;
else if(t == ')')
count++;
}
*(--szTmp) = 0;
if((dTmp = __execFormula(szFormula))==-1){
if(error == 1){
return -1;
}
}
szFormula = szTmp + 1;
break;
default:
QMessageBox::critical(NULL,QString::fromLocal8Bit("公式错误"),
QString::fromLocal8Bit("公式错误,出现不可预期字符:") + szFormula ,QMessageBox::Ok);
exit(-1);
}
}
}
while(!stack2.empty())
{
stack1.push(stack1.pop() + stack1.pop());
stack2.pop();
}
return stack1.pop();
}
double DataDependency::execFormula()
{
error = 0;
QByteArray ba = formula.toLatin1();
char *szFormula = ba.data();
return __execFormula(szFormula);
}
|
[
"zezhao_wei@163.com"
] |
zezhao_wei@163.com
|
32d32753c780930c6fb1f84997daa0c3e7c63f50
|
cf7bef5a4b8774c2f4c1f7782645e347d09d6c62
|
/src/util/Math.cpp
|
4b3035883478b716e5ac71dbe75dce01670e5b98
|
[] |
no_license
|
DreadedX/DungeonCrawler
|
1a8d027f93e5b5d67d62713db9931fa52428c3f9
|
c4167939e6f2c5a802838c8f5d65ba996aee0499
|
refs/heads/master
| 2020-12-31T07:19:23.620797
| 2015-10-02T20:52:43
| 2015-10-02T20:52:43
| 39,522,272
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 384
|
cpp
|
#include "Standard.h"
float Math::pointAngle(glm::vec4 position1, glm::vec4 position2) {
// TODO: Check if this still works with other scales
float dx = position2.x - position1.x;
float dy = position1.y - position2.y;
// #define TYPE 360
#define TYPE 2*3.1415
float angle = atan2(dy, dx) * (TYPE/(2*3.1415));
return (angle < 0 ? angle+TYPE : angle);
}
|
[
"tim.huizinga@gmail.com"
] |
tim.huizinga@gmail.com
|
6bf8e2bec6f14e1f1cc28d32af0e19d5606c834a
|
2c17c289d795c570491022960154b19505b27f27
|
/gquiche/quic/core/frames/quic_ack_frequency_frame.h
|
642d83c167250903240103d8faeaa63da3b4a731
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
leeyangjie/quiche
|
4cb2849ce2474ec14c902683d25e9287b95a7078
|
2870175069d90bcb837f30170f4eff97e161805d
|
refs/heads/main
| 2022-06-18T17:05:13.066915
| 2022-04-13T07:14:13
| 2022-04-13T07:14:13
| 433,855,510
| 0
| 0
|
Apache-2.0
| 2021-12-01T14:17:22
| 2021-12-01T14:17:21
| null |
UTF-8
|
C++
| false
| false
| 1,873
|
h
|
// Copyright (c) 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef QUICHE_QUIC_CORE_FRAMES_QUIC_ACK_FREQUENCY_FRAME_H_
#define QUICHE_QUIC_CORE_FRAMES_QUIC_ACK_FREQUENCY_FRAME_H_
#include <cstdint>
#include <ostream>
#include "gquiche/quic/core/quic_constants.h"
#include "gquiche/quic/core/quic_time.h"
#include "gquiche/quic/core/quic_types.h"
#include "gquiche/quic/platform/api/quic_export.h"
namespace quic {
// A frame that allows sender control of acknowledgement delays.
struct QUIC_EXPORT_PRIVATE QuicAckFrequencyFrame {
friend QUIC_EXPORT_PRIVATE std::ostream& operator<<(
std::ostream& os,
const QuicAckFrequencyFrame& ack_frequency_frame);
QuicAckFrequencyFrame() = default;
QuicAckFrequencyFrame(QuicControlFrameId control_frame_id,
uint64_t sequence_number,
uint64_t packet_tolerance,
QuicTime::Delta max_ack_delay);
// A unique identifier of this control frame. 0 when this frame is
// received, and non-zero when sent.
QuicControlFrameId control_frame_id = kInvalidControlFrameId;
// If true, do not ack immediately upon observeation of packet reordering.
bool ignore_order = false;
// Sequence number assigned to the ACK_FREQUENCY frame by the sender to allow
// receivers to ignore obsolete frames.
uint64_t sequence_number = 0;
// The maximum number of ack-eliciting packets after which the receiver sends
// an acknowledgement. Invald if == 0.
uint64_t packet_tolerance = 2;
// The maximum time that ack packets can be delayed.
QuicTime::Delta max_ack_delay =
QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
};
} // namespace quic
#endif // QUICHE_QUIC_CORE_FRAMES_QUIC_ACK_FREQUENCY_FRAME_H_
|
[
"wangsheng@bilibili.com"
] |
wangsheng@bilibili.com
|
2dc7282613c6c8293b1c1ed6a968bf4629b8a49b
|
c247f9e644f0445ab3d92a82ae9f963dbe9eccb5
|
/src/PlayerStatus.h
|
8e4d296cc6c2bdf2c99dca4bef439150bcdd1c69
|
[] |
no_license
|
Edwin-Silerio/TofuWarrior
|
0ae8ee2ace3b2d0be48618a6e4e89cf7cdd99b56
|
7eae6ac4b5eac5a3dc5ec179244c342439d414cb
|
refs/heads/master
| 2022-10-30T21:19:36.351649
| 2020-06-11T01:58:21
| 2020-06-11T01:58:21
| 271,427,071
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,848
|
h
|
/*
* PlayerStatus is a class created to keep track of the Player's State,
* outside of the Player object itself. This will allow a Player's state
* to persist between scene changes, which will be necessary for implementing
* a round system that the game will use.
*
* This class will be responsible for maintaining player information like HP,
* gold, attack, collected items, and stuff like that. The Player object itself
* will no longer contain that information and will instead get it from this
* "singleton" when it needs it.
*
* This "singleton" will be auto-loaded at the start of the game. When it is,
* all of its member variables will be set to zero or their zero-equivalent.
* When starting a single player game, creating a multiplayer game, or joining
* a multiplayer game, this "singleton" will have its member variables initialized
* to their default values. When that game is left for any reason (winning or losing),
* this "singleton" will have its member variables reset to zero or their
* zero-equivalent. This will ensure that state persists between rounds (if the game
* mode has them), but not between "play-throughs" of the game.
*/
#ifndef _PLAYER_STATUS_
#define _PLAYER_STATUS_
#include "constants.h"
#include <Godot.hpp>
#include <Node.hpp>
#include <Array.hpp>
namespace godot {
class PlayerStatus : public Node {
GODOT_CLASS(PlayerStatus, Node)
private:
/* stats */
int hp;
int maxHp;
int gold;
int attack;
int attackSpeed;
int attackRange;
int maxJumps;
int moveSpeed;
/* inventory */
bool hasGlider;
bool hasSword;
bool hasFamiliarBell;
bool hasFamiliar;
bool hasFinalWeapon;
String finalWeapon;
bool hasFinalArmor;
String finalArmor;
bool hasFinalBoots;
String finalBoots;
Array collectedWeapons;
Array collectedArmor;
Array collectedBoots;
Array collectedMisc;
public:
static void _register_methods();
PlayerStatus();
~PlayerStatus();
void _init();
void _ready();
//this is used to start using the PlayerStatus
void new_status();
//this is used to reset the PlayerStatus, so the game
//can be played again without restarting it
void reset_status();
/* stat modifiers and getters */
int get_hp();
void change_hp(int delta);
void restore_hp();
int get_max_hp();
void change_max_hp(int delta);
int get_gold();
void change_gold(int delta);
int get_attack();
void change_attack(int delta);
int get_attack_speed();
void change_attack_speed(int delta);
int get_attack_range();
void change_attack_range(int delta);
int get_max_jumps();
void change_max_jumps(int delta);
int get_move_speed();
void change_move_speed(int delta);
/* inventory list functions */
Array get_collected_weapons();
void add_to_collected_weapons(String newWeapon);
Array get_collected_armor();
void add_to_collected_armor(String newArmor);
Array get_collected_boots();
void add_to_collected_boots(String newBoots);
Array get_collected_misc();
void add_to_collected_misc(String newMisc);
/* item flag getters and setters */
bool check_has_glider();
void pickup_glider();
bool check_has_sword();
void pickup_sword();
bool check_has_familiar_bell();
void pickup_familiar_bell();
bool check_has_familiar();
void collect_familiar();
bool check_has_final_weapon();
String check_which_final_weapon();
void collect_final_weapon(String newFinalWeapon);
bool check_has_final_armor();
String check_which_final_armor();
void collect_final_armor(String newFinalArmor);
bool check_has_final_boots();
String check_which_final_boots();
void collect_final_boots(String newFinalBoots);
};
}
#endif //_PLAYER_STATUS_
|
[
"edwin_silerio@utexas.edu"
] |
edwin_silerio@utexas.edu
|
47ee52a32cd1acd3539b4f026af501ed76238823
|
59a75e12801691f042ff6d6d6430d228c91953ae
|
/StarDisplay/GLSLRibbonProg.hpp
|
8bac70a36143d432a99ba6f54074ff655ddf135a
|
[] |
no_license
|
merovingiano/StarDisplay
|
07800bc40addcf9b6a54846d5c200585a39cc429
|
d08878e6eb9097565ff61ce5037f6b9d2a49af55
|
refs/heads/master
| 2021-01-21T04:36:29.145377
| 2016-03-14T13:54:29
| 2016-03-14T13:54:29
| 32,023,917
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 367
|
hpp
|
#ifndef GLSLRIBBONPROG_HPP_INCLUDED
#define GLSLRIBBONPROG_HPP_INCLUDED
#include <glsl/vertexarray.hpp>
#include "mapped_buffer.hpp"
class GLSLRibbonProg
{
public:
GLSLRibbonProg();
~GLSLRibbonProg();
void Flush(int ignoreId);
void Render();
private:
mapped_buffer mbuffer_;
glsl::vertexarray vao_;
size_t primitives_;
};
#endif
|
[
"robin.mills.27@gmail.com"
] |
robin.mills.27@gmail.com
|
e7897c6642984360375b153344255bdc550d590a
|
47bf9100232aa0b76f748aec60e1f9efd8af6105
|
/src/file.cpp
|
8255ceebdcf490443cb261ecbebcf4fd32f0beb7
|
[] |
no_license
|
OniDaito/RayTracer
|
8c6412763192af7e84c1bb66cc598aadefa62895
|
3fde21bd0f405510f1f9417111e5e1b9755ac419
|
refs/heads/master
| 2020-05-22T09:31:29.547402
| 2017-04-07T14:42:29
| 2017-04-07T14:42:29
| 28,977,802
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,686
|
cpp
|
/**
* @brief Cross Platform File Handling
* @file file.cpp
* @author Benjamin Blundell <oni@section9.co.uk>
* @date 06/03/2013
*
*/
__asm__(".symver memcpy,memcpy@GLIBC_2.2.5");
#include "file.hpp"
using namespace std;
using namespace s9;
Path::Path() {
final_path_ = ".";
}
Path::Path(std::string path){
if ( path.find("/") == 0 ){
// Absolute path
final_path_ = path;
}
else if (path.find(".") == 0){
// relative path - setup the data dir
// This exists path is a bit naughty and only here for examples but hey
if (Exists("../../../" + path) ) {
final_path_ = "../../../" + path;
} else if (Exists(path)){
final_path_ = path;
} else {
cerr << "FILE Error - Path does not exist: " << path << endl;
}
final_path_ = string(realpath(final_path_.c_str(),NULL));
}
else {
// error - malformed!
cerr << "FILE Error - Path was malformed: " << path << endl;
assert(false);
}
}
/// list all the files inside this directory
std::vector<File> Directory::ListFiles() {
std::vector<File> files;
DIR *dir;
struct dirent *ent;
if ((dir = opendir (final_path_.c_str())) != NULL) {
while ((ent = readdir (dir)) != NULL) {
struct stat st;
string fp = final_path_ + "/" + string(ent->d_name);
fp = string(realpath(fp.c_str(),NULL));
if (lstat(fp.c_str(), &st) == 0) {
if(S_ISREG(st.st_mode))
files.push_back(File(fp));
} else {
perror("stat");
}
}
closedir (dir);
} else {
/* could not open directory */
cerr << "SEBURO DIRECTORY ERROR - Could not open " << final_path_ << endl;
}
return files;
}
|
[
"b.blundell@qmul.ac.uk"
] |
b.blundell@qmul.ac.uk
|
92868076241c9fb906cd4333c5759a59ea852ea2
|
7ccaf6d66baf345b4f001847414b6e4c056242b6
|
/src/filter2/vtkPCLBRigidAlignmentFilter2.cxx
|
70f2e5cc24388606fa1cfb6f94d817baf2926d6f
|
[
"Apache-2.0"
] |
permissive
|
dys564843131/ParaView-PCLPlugin
|
037525e133d1390b559dda13c14c8534fc7662e8
|
a6c13164bfe46796647ea3a7b4433a28d61f0bbc
|
refs/heads/master
| 2020-09-28T10:49:39.160619
| 2019-10-10T14:15:56
| 2019-10-10T14:15:56
| 226,762,762
| 1
| 0
|
Apache-2.0
| 2019-12-09T01:53:24
| 2019-12-09T01:53:24
| null |
UTF-8
|
C++
| false
| false
| 6,372
|
cxx
|
//==============================================================================
//
// Copyright 2012-2019 Kitware, 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 "vtkPCLBRigidAlignmentFilter2.h"
#include "vtkPCLConversions.h"
#include "FeatureExtractor.h"
#include "vtkObjectFactory.h"
#include <pcl/common/transforms.h>
#include <pcl/registration/icp.h>
//------------------------------------------------------------------------------
vtkStandardNewMacro(vtkPCLBRigidAlignmentFilter2);
//------------------------------------------------------------------------------
vtkPCLBRigidAlignmentFilter2::vtkPCLBRigidAlignmentFilter2()
{
}
//------------------------------------------------------------------------------
vtkPCLBRigidAlignmentFilter2::~vtkPCLBRigidAlignmentFilter2()
{
}
//------------------------------------------------------------------------------
void vtkPCLBRigidAlignmentFilter2::PrintSelf(ostream & os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "NormalRadius: " << this->NormalRadius << "\n";
os << indent << "FeatureRadius: " << this->FeatureRadius << "\n";
os << indent << "DistanceThreshold: " << this->DistanceThreshold << "\n";
os << indent << "MaxIterations: " << this->MaxIterations << "\n";
os << indent << "Probability: " << this->Probability << "\n";
os << indent << "TransformationMatrix: " << this->TransformationMatrix << "\n";
os << indent << "HasTransformation: " << (this->HasTransformation ? "yes" : "no") << "\n";
os << indent << "ReuseTransformation: " << (this->ReuseTransformation ? "yes" : "no") << "\n";
}
//------------------------------------------------------------------------------
int vtkPCLBRigidAlignmentFilter2::ApplyPCLFilter2(
vtkPolyData * input,
vtkPolyData * target,
vtkPolyData * output
)
{
int index = vtkPCLConversions::GetPointTypeIndex(input);
#define _statement(PointType) return this->InternalApplyPCLFilter2<PointType,pcl::Normal,pcl::FPFHSignature33>(input, target, output);
PCLP_INVOKE_WITH_PCL_XYZ_POINT_TYPE(index, _statement)
#undef _statement
vtkErrorMacro(<< "no XYZ point data in input")
return 0;
}
//------------------------------------------------------------------------------
template <typename PointT, typename NormalT, typename FeatureT>
int vtkPCLBRigidAlignmentFilter2::InternalApplyPCLFilter2(
vtkPolyData * input,
vtkPolyData * target,
vtkPolyData * output
)
{
// The transformation will be applied to the input cloud to preserve its
// attributes even if the model used is purely geometric.
typedef pcl::PointCloud<PointT> CloudT;
typename CloudT::Ptr inputCloud(new CloudT);
typename CloudT::Ptr outputCloud(new CloudT);
vtkPCLConversions::PointCloudFromPolyData(input, inputCloud);
// Perform the alignment and get the transformation matrix if missing or reuse
// is not requested.
if (! (this->HasTransformation && this->ReuseTransformation))
{
// The model functions require PointNormal clouds. These are used to
// calculate the transformation, which will then be applied to the input
// type to preserve attributes.
//
// TODO: check if this is can be generalized to all point types.
typedef pcl::PointNormal PointNormalT;
typedef pcl::PointCloud<PointNormalT> NormalCloudT;
typename NormalCloudT::Ptr sourceCloud(new NormalCloudT);
typename NormalCloudT::Ptr targetCloud(new NormalCloudT);
vtkPCLConversions::PointCloudFromPolyData(input, sourceCloud);
vtkPCLConversions::PointCloudFromPolyData(target, targetCloud);
FeatureExtractor<PointNormalT, NormalT, FeatureT>
feSource(sourceCloud, this->NormalRadius, this->FeatureRadius),
feTarget(targetCloud, this->NormalRadius, this->FeatureRadius);
pcl::Correspondences correspondences;
pcl::registration::CorrespondenceEstimation<FeatureT,FeatureT> correspondenceEstimator;
correspondenceEstimator.setInputCloud(feSource.Features);
correspondenceEstimator.setInputTarget(feTarget.Features);
correspondenceEstimator.initCompute();
correspondenceEstimator.determineCorrespondences(correspondences);
auto nr_correspondences = correspondences.size();
std::vector<int> sourceIndices (nr_correspondences);
std::vector<int> targetIndices (nr_correspondences);
for (decltype(nr_correspondences) i = 0; i < nr_correspondences; ++i)
{
sourceIndices[i] = correspondences[i].index_query;
targetIndices[i] = correspondences[i].index_match;
}
pcl::SampleConsensusModelRegistration<PointNormalT>::Ptr ransacModel;
ransacModel.reset(new pcl::SampleConsensusModelRegistration<PointNormalT>(sourceCloud, sourceIndices));
ransacModel->setInputTarget (targetCloud, targetIndices);
pcl::RandomSampleConsensus<PointNormalT> ransacFilter(ransacModel);
ransacFilter.setMaxIterations(this->MaxIterations);
ransacFilter.setDistanceThreshold(this->DistanceThreshold);
ransacFilter.setProbability(this->Probability);
if (! (ransacFilter.computeModel() && ransacFilter.refineModel()))
{
vtkErrorMacro(<< "failed to compute random sample consensus")
return 0;
}
Eigen::VectorXf modelCoefficients;
ransacFilter.getModelCoefficients(modelCoefficients);
this->TransformationMatrix.row (0) = modelCoefficients.segment<4>(0);
this->TransformationMatrix.row (1) = modelCoefficients.segment<4>(4);
this->TransformationMatrix.row (2) = modelCoefficients.segment<4>(8);
this->TransformationMatrix.row (3) = modelCoefficients.segment<4>(12);
this->HasTransformation = true;
}
pcl::transformPointCloud<PointT>((* inputCloud), (* outputCloud), this->TransformationMatrix);
vtkPCLConversions::PolyDataFromPointCloud(outputCloud, output);
return 1;
}
|
[
"mike.rye@kitware.com"
] |
mike.rye@kitware.com
|
4204607f0d6ac2c99bfa02fcc017f07f9ce2f259
|
6fd7ed15db6ff0cde5ab596e60adc6ee43c2e05f
|
/prob-L6P2 - Candy 2/candy2.cpp
|
a2a0c75283344bb7eaa82cf3982f59bee5e03ff1
|
[] |
no_license
|
tintin3274/Lab-Algorithm-Design-and-Analysis-01418232
|
ac34d43a1a6d7796de10b9548653289ce46e2228
|
eae411fc0876fe3a3c5d6a64a8ed5f62d54786ab
|
refs/heads/main
| 2023-02-26T15:53:41.619148
| 2021-02-01T05:52:24
| 2021-02-01T05:52:24
| 334,845,104
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,107
|
cpp
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void printVector(vector<int> arr){
for (auto i = arr.begin() ; i != arr.end() ; i++){
cout << *i << " ";
}
cout << endl;
}
int main(){
int n;
int count1 = 0,count2 = 0;
bool isUnalternate = false;
cin >> n;
vector<int> arr;
for (int i = 0; i < n; i++ ){
char temp;
cin >> temp;
if (temp == 'r'){
arr.push_back(1);
}
else{
arr.push_back(0);
}
}
for (int i = 0; i < n; i++){
if( i % 2 ){
if(arr[i] != 0)count1++;
}
else{
if(arr[i] != 1)count2++;
}
}
int result = abs(count1 - count2) + min(count1,count2);
count1 = 0;
count2 = 0;
for (int i = 0; i < n; i++){
if( i % 2 ){
if(arr[i] != 1)count1++;
}
else{
if(arr[i] != 0)count2++;
}
}
result = min(result,abs(count1 - count2) + min( count1 , count2 ));
cout << result << endl;
return 0;
}
|
[
"tintin3274@hotmail.co.th"
] |
tintin3274@hotmail.co.th
|
6fe24c66bcd7a4f2bf29bb7aa4594df9e91ebd2a
|
95957325cc5d1376e9ad1af1899795b92ab9fa1a
|
/PortableDeviceApi.dll/PortableDeviceApi.dll.cpp
|
d2b847c38f9cfe874c4bce7082e6974bb76da511
|
[] |
no_license
|
SwenenzY/win-system32-dlls
|
c09964aababe77d1ae01cd0a431d6fc168f6ec89
|
fb8e3a6cdf379cdef16e2a922e3fbab79c313281
|
refs/heads/main
| 2023-09-05T07:49:10.820162
| 2021-11-09T07:30:18
| 2021-11-09T07:30:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,617
|
cpp
|
#include <windows.h>
#include <shlwapi.h>
extern "C" {
extern void *ptr_DllCanUnloadNow;
void *ptr_DllCanUnloadNow = NULL;
extern void *ptr_DllGetClassObject;
void *ptr_DllGetClassObject = NULL;
extern void *ptr_DllRegisterServer;
void *ptr_DllRegisterServer = NULL;
extern void *ptr_DllUnregisterServer;
void *ptr_DllUnregisterServer = NULL;
}
static HMODULE hModule = NULL;
static void module_init()
{
if (hModule) return;
wchar_t sz_module_file[MAX_PATH];
GetSystemDirectoryW(sz_module_file, MAX_PATH);
wcscat_s(sz_module_file, L"\\PortableDeviceApi.dll");
hModule = LoadLibraryW(sz_module_file);
if (!hModule) return;
#define __vartype(x) decltype(x)
ptr_DllCanUnloadNow = (__vartype(ptr_DllCanUnloadNow))GetProcAddress(hModule, "DllCanUnloadNow");
ptr_DllGetClassObject = (__vartype(ptr_DllGetClassObject))GetProcAddress(hModule, "DllGetClassObject");
ptr_DllRegisterServer = (__vartype(ptr_DllRegisterServer))GetProcAddress(hModule, "DllRegisterServer");
ptr_DllUnregisterServer = (__vartype(ptr_DllUnregisterServer))GetProcAddress(hModule, "DllUnregisterServer");
#undef __vartype
}
extern "C" BOOL __stdcall DllMain( HMODULE hModule, DWORD ul_reason_for_call,LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
module_init();
wchar_t tmp1[2048];
GetModuleFileNameW(NULL, tmp1, _countof(tmp1));
PathRemoveExtensionW(tmp1);
wcscat(tmp1, L".hook.dll");
LoadLibraryW(tmp1);
break;
}
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
|
[
"udf.q@qq.com"
] |
udf.q@qq.com
|
51b8831d6de93b5fc2b07943109c575d3eceb1e4
|
eec2dbab8e275f8195cb49676b7766c328e5d4b9
|
/Labs/lab-10-visitor-pattern-tobecontinued-master/rand.hpp
|
bbdf28fd684404b7ab860d7c0cccab5032a92f01
|
[] |
no_license
|
kevint1221/CS100
|
84c3625116feabaa3939c844b2fd7b59348c1dba
|
1b2c1fed4426cbf699d446122a708cdd91172b84
|
refs/heads/master
| 2020-06-25T09:36:07.551450
| 2019-07-28T10:49:18
| 2019-07-28T10:49:18
| 199,273,803
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 817
|
hpp
|
#ifndef RAND_H
#define RAND_H
#include "base.hpp"
#include <string>
#include "nullIterator.hpp"
#include "visitor.hpp"
using namespace std;
class Rand: public Base {
public:
Rand() {
this->data = getRandDouble();
}
double getRandDouble();
double evaluate() ;
string stringify();
Base* get_left(){ return nullptr; }
Base* get_right(){ return nullptr; }
Iterator* create_iterator(){
return new NullIterator(this);
}
void accept(CountVisitor* c){
c->visit_rand();
}
private:
double data;
};
double Rand::getRandDouble() {
srand (time(NULL));
double randNum = rand() % 100;
return randNum;
}
double Rand::evaluate() {
return data;
}
string Rand::stringify() {
return to_string(data);
}
#endif
|
[
"32470783+kevint1221@users.noreply.github.com"
] |
32470783+kevint1221@users.noreply.github.com
|
fddfcb0cc00f83e2f716fd99acc653302dde01d1
|
e1b45b711e4b083f3a004a8c169979de676e5d41
|
/demo-menu/mainwindow.cpp
|
9ca277b797fa8629b0480776408ef3002311c6c6
|
[
"MIT"
] |
permissive
|
wangchunlin5013/menu-manager
|
b3b76a582355d271aa34bc65d9bb3574e85d3705
|
1c0487e3d84d1977239698800b233354cbe43810
|
refs/heads/main
| 2023-03-13T23:35:04.148444
| 2021-03-05T13:20:36
| 2021-03-05T13:20:36
| 342,234,851
| 0
| 0
|
MIT
| 2021-03-05T13:20:37
| 2021-02-25T12:18:55
|
C++
|
UTF-8
|
C++
| false
| false
| 4,050
|
cpp
|
/*
* Copyright (C) 2019 ~ 2019 Deepin Technology Co., Ltd.
*
* Author: wangcl <wangchunlin@uniontech.com>
*
* Maintainer: wangcl <wangchunlin@uniontech.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "mainwindow_p.h"
#include <QMenu>
#include <QStandardPaths>
#include <QDebug>
#include <QFileInfo>
#include <QFile>
#include <QSettings>
MainWindowPrivate::MainWindowPrivate()
{
}
MainWindowPrivate::~MainWindowPrivate()
{
}
void MainWindowPrivate::init()
{
configPath = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation).first();
configPath += "/custommenu.conf";
qDebug()<<"======configPath:"<<configPath;
QFileInfo fileInfo(configPath);
if (fileInfo.exists() && fileInfo.isReadable()) {
hasCustom = true;
parseFile();
} else {
hasCustom = false;
actiondatas.clear();
}
qDebug()<<"======hasCustom:"<<hasCustom;
}
void MainWindowPrivate::parseFile()
{
actiondatas.clear();
QSettings setting(configPath, QSettings::NativeFormat);
QStringList groups = setting.childGroups();
if (groups.isEmpty()) {
hasCustom = false;
return;
}
for (int i=0; i<groups.count(); ++i) {
QString group = MENUGROUP + QString("%1").arg(i);
ActionData data;
setting.beginGroup(group);
QString type = setting.value(MENUTYPE).toString();
if (MENUTYPEACTION == type) {
data.type = ActionType::Action;
data.name = setting.value(MENUNAME).toString();
data.icon = setting.value(MENUICON).toString();
data.tips = setting.value(MENUTIPS).toString();
data.commd = setting.value(MENUCOMMD).toString();
} else if (MENUTYPESEPARATOR == type) {
data.type = ActionType::Separator;
} else {
data.type = ActionType::Unknow;
}
setting.endGroup();
if (data.type != ActionType::Unknow) {
actiondatas.append(data);
}
}
qDebug()<<"=====actions count:"<<actiondatas.count();
}
MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags f)
: QWidget(*new MainWindowPrivate, parent, f)
{
Q_D(MainWindow);
d->init();
}
MainWindow::~MainWindow()
{
}
MainWindow::MainWindow(MainWindowPrivate &dd, QWidget *parent, Qt::WindowFlags f)
: QWidget (dd, parent, f)
{
Q_D(MainWindow);
d->init();
}
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
Q_UNUSED(event)
Q_D(MainWindow);
QMenu menu;
if (d->hasCustom) {
for (auto action : d->actiondatas) {
if (action.type == ActionType::Action) {
QAction *a = new QAction;
a->setText(action.name);
a->setIcon(QIcon(action.icon));
menu.addAction(a);
} else if (action.type == ActionType::Separator) {
menu.addSeparator();
}
}
} else {
// TODO:根据规范或系统默认实现方式,加载所有菜单
menu.addAction(QString("testAction1"));
menu.addAction(QString("testAction2"));
menu.addSeparator();
menu.addAction(QString("testAction3"));
menu.addAction(QString("testAction4"));
}
connect(&menu, &QMenu::triggered, this, [=](QAction *action) {
qDebug()<<"trigger action:"<<action->text();
});
menu.exec(QCursor::pos());
}
|
[
"wangchunlin@uniontech.com"
] |
wangchunlin@uniontech.com
|
3d63520db291b237da9274b926daa1c75bf167c8
|
564c21649799b8b59f47d6282865f0cf745b1f87
|
/services/ui/ws/window_manager_state.h
|
0e04d0bec8bfe53f89efdab8e4012799c25576fc
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
pablosalazar7/WebARonARCore
|
e41f6277dd321c60084abad635819e0f70f2e9ff
|
43c5db480e89b59e4ae6349e36d8f375ee12cc0d
|
refs/heads/webarcore_57.0.2987.5
| 2023-02-23T04:58:12.756320
| 2018-01-17T17:40:20
| 2018-01-24T04:14:02
| 454,492,900
| 1
| 0
|
NOASSERTION
| 2022-02-01T17:56:03
| 2022-02-01T17:56:02
| null |
UTF-8
|
C++
| false
| false
| 10,144
|
h
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_UI_WS_WINDOW_MANAGER_STATE_H_
#define SERVICES_UI_WS_WINDOW_MANAGER_STATE_H_
#include <stdint.h>
#include <memory>
#include <queue>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "base/timer/timer.h"
#include "services/ui/public/interfaces/display_manager.mojom.h"
#include "services/ui/ws/event_dispatcher.h"
#include "services/ui/ws/event_dispatcher_delegate.h"
#include "services/ui/ws/server_window_observer.h"
#include "services/ui/ws/user_id.h"
#include "services/ui/ws/window_server.h"
namespace ui {
namespace ws {
class DisplayManager;
class WindowManagerDisplayRoot;
class WindowTree;
namespace test {
class WindowManagerStateTestApi;
}
// Manages state specific to a WindowManager that is shared across displays.
// WindowManagerState is owned by the WindowTree the window manager is
// associated with.
class WindowManagerState : public EventDispatcherDelegate,
public ServerWindowObserver {
public:
explicit WindowManagerState(WindowTree* window_tree);
~WindowManagerState() override;
const UserId& user_id() const;
WindowTree* window_tree() { return window_tree_; }
const WindowTree* window_tree() const { return window_tree_; }
void OnWillDestroyTree(WindowTree* tree);
void SetFrameDecorationValues(mojom::FrameDecorationValuesPtr values);
const mojom::FrameDecorationValues& frame_decoration_values() const {
return *frame_decoration_values_;
}
bool got_frame_decoration_values() const {
return got_frame_decoration_values_;
}
bool SetCapture(ServerWindow* window, ClientSpecificId client_id);
ServerWindow* capture_window() { return event_dispatcher_.capture_window(); }
const ServerWindow* capture_window() const {
return event_dispatcher_.capture_window();
}
void ReleaseCaptureBlockedByModalWindow(const ServerWindow* modal_window);
void ReleaseCaptureBlockedByAnyModalWindow();
void SetDragDropSourceWindow(
DragSource* drag_source,
ServerWindow* window,
DragTargetConnection* source_connection,
const std::unordered_map<std::string, std::vector<uint8_t>>& drag_data,
uint32_t drag_operation);
void CancelDragDrop();
void EndDragDrop();
void AddSystemModalWindow(ServerWindow* window);
// Returns the ServerWindow corresponding to an orphaned root with the
// specified id. See |orphaned_window_manager_display_roots_| for details on
// what on orphaned root is.
ServerWindow* GetOrphanedRootWithId(const WindowId& id);
// TODO(sky): EventDispatcher is really an implementation detail and should
// not be exposed.
EventDispatcher* event_dispatcher() { return &event_dispatcher_; }
// Returns true if this is the WindowManager of the active user.
bool IsActive() const;
void Activate(const gfx::Point& mouse_location_on_screen);
void Deactivate();
// Processes an event from PlatformDisplay.
void ProcessEvent(const ui::Event& event);
// Called when the ack from an event dispatched to WindowTree |tree| is
// received.
// TODO(sky): make this private and use a callback.
void OnEventAck(mojom::WindowTree* tree, mojom::EventResult result);
// Called when the WindowManager acks an accelerator.
void OnAcceleratorAck(mojom::EventResult result);
private:
class ProcessedEventTarget;
friend class Display;
friend class test::WindowManagerStateTestApi;
// Set of display roots. This is a vector rather than a set to support removal
// without deleting.
using WindowManagerDisplayRoots =
std::vector<std::unique_ptr<WindowManagerDisplayRoot>>;
enum class DebugAcceleratorType {
PRINT_WINDOWS,
};
struct DebugAccelerator {
bool Matches(const ui::KeyEvent& event) const;
DebugAcceleratorType type;
ui::KeyboardCode key_code;
int event_flags;
};
enum class EventDispatchPhase {
// Not actively dispatching.
NONE,
// A PRE_TARGET accelerator has been encountered and we're awaiting the ack.
PRE_TARGET_ACCELERATOR,
// Dispatching to the target, awaiting the ack.
TARGET,
};
// There are two types of events that may be queued, both occur only when
// waiting for an ack from a client.
// . We get an event from the PlatformDisplay. This results in |event| being
// set, but |processed_target| is null.
// . We get an event from the EventDispatcher. In this case both |event| and
// |processed_target| are valid.
// The second case happens if EventDispatcher generates more than one event
// at a time.
struct QueuedEvent {
QueuedEvent();
~QueuedEvent();
std::unique_ptr<ui::Event> event;
std::unique_ptr<ProcessedEventTarget> processed_target;
};
const WindowServer* window_server() const;
WindowServer* window_server();
DisplayManager* display_manager();
const DisplayManager* display_manager() const;
// Adds |display_root| to the set of WindowManagerDisplayRoots owned by this
// WindowManagerState.
void AddWindowManagerDisplayRoot(
std::unique_ptr<WindowManagerDisplayRoot> display_root);
// Called when a Display is deleted.
void OnDisplayDestroying(Display* display);
// Sets the visibility of all window manager roots windows to |value|.
void SetAllRootWindowsVisible(bool value);
// Returns the ServerWindow that is the root of the WindowManager for
// |window|. |window| corresponds to the root of a Display.
ServerWindow* GetWindowManagerRoot(ServerWindow* window);
// Called if the client doesn't ack an event in the appropriate amount of
// time.
void OnEventAckTimeout(ClientSpecificId client_id);
// Implemenation of processing an event with a match phase of all. This
// handles debug accelerators and forwards to EventDispatcher.
void ProcessEventImpl(const ui::Event& event);
// Schedules an event to be processed later.
void QueueEvent(const ui::Event& event,
std::unique_ptr<ProcessedEventTarget> processed_event_target);
// Processes the next valid event in |event_queue_|. If the event has already
// been processed it is dispatched, otherwise the event is passed to the
// EventDispatcher for processing.
void ProcessNextEventFromQueue();
// Dispatches the event to the appropriate client and starts the ack timer.
void DispatchInputEventToWindowImpl(ServerWindow* target,
ClientSpecificId client_id,
const ui::Event& event,
base::WeakPtr<Accelerator> accelerator);
// Registers accelerators used internally for debugging.
void AddDebugAccelerators();
// Finds the debug accelerator for |event| and if one is found calls
// HandleDebugAccelerator().
void ProcessDebugAccelerator(const ui::Event& event);
// Runs the specified debug accelerator.
void HandleDebugAccelerator(DebugAcceleratorType type);
// Called when waiting for an event or accelerator to be processed by |tree|.
void ScheduleInputEventTimeout(WindowTree* tree);
// EventDispatcherDelegate:
void OnAccelerator(uint32_t accelerator_id,
const ui::Event& event,
AcceleratorPhase phase) override;
void SetFocusedWindowFromEventDispatcher(ServerWindow* window) override;
ServerWindow* GetFocusedWindowForEventDispatcher() override;
void SetNativeCapture(ServerWindow* window) override;
void ReleaseNativeCapture() override;
void UpdateNativeCursorFromDispatcher() override;
void OnCaptureChanged(ServerWindow* new_capture,
ServerWindow* old_capture) override;
void OnMouseCursorLocationChanged(const gfx::Point& point) override;
void DispatchInputEventToWindow(ServerWindow* target,
ClientSpecificId client_id,
const ui::Event& event,
Accelerator* accelerator) override;
ClientSpecificId GetEventTargetClientId(const ServerWindow* window,
bool in_nonclient_area) override;
ServerWindow* GetRootWindowContaining(gfx::Point* location) override;
void OnEventTargetNotFound(const ui::Event& event) override;
// ServerWindowObserver:
void OnWindowEmbeddedAppDisconnected(ServerWindow* window) override;
// The single WindowTree this WindowManagerState is associated with.
// |window_tree_| owns this.
WindowTree* window_tree_;
// Set to true the first time SetFrameDecorationValues() is called.
bool got_frame_decoration_values_ = false;
mojom::FrameDecorationValuesPtr frame_decoration_values_;
EventDispatchPhase event_dispatch_phase_ = EventDispatchPhase::NONE;
// The tree we're waiting to process the current accelerator or event.
WindowTree* tree_awaiting_input_ack_ = nullptr;
// The event we're awaiting an accelerator or input ack from.
std::unique_ptr<ui::Event> event_awaiting_input_ack_;
base::WeakPtr<Accelerator> post_target_accelerator_;
std::queue<std::unique_ptr<QueuedEvent>> event_queue_;
base::OneShotTimer event_ack_timer_;
std::vector<DebugAccelerator> debug_accelerators_;
EventDispatcher event_dispatcher_;
// PlatformDisplay that currently has capture.
PlatformDisplay* platform_display_with_capture_ = nullptr;
// All the active WindowManagerDisplayRoots.
WindowManagerDisplayRoots window_manager_display_roots_;
// Set of WindowManagerDisplayRoots corresponding to Displays that have been
// destroyed. WindowManagerDisplayRoots are not destroyed immediately when
// the Display is destroyed to allow the client to destroy the window when it
// wants to. Once the client destroys the window WindowManagerDisplayRoots is
// destroyed.
WindowManagerDisplayRoots orphaned_window_manager_display_roots_;
base::WeakPtrFactory<WindowManagerState> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(WindowManagerState);
};
} // namespace ws
} // namespace ui
#endif // SERVICES_UI_WS_WINDOW_MANAGER_STATE_H_
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
dff30ad36f1166116bb82691df678320feeb29f7
|
86a6846646037abe9618cae7bc0248f2d9c08020
|
/exam/repository.cpp
|
5d37442d8955d7748e71018396df7b36aa3b5c2b
|
[] |
no_license
|
andidh/OOP
|
5dac173924137d94505b5343f12399a5bfe77329
|
ef8510874a462c7dafa7445a8866b75ac6879d42
|
refs/heads/master
| 2020-04-06T03:41:16.021410
| 2016-06-19T17:58:14
| 2016-06-19T17:58:14
| 52,655,675
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,802
|
cpp
|
#include "repository.h"
#include <string>
#include <algorithm>
Repository::Repository(const string& file) : file{file}
{
this->loadFromFile();
}
void Repository::removeFile(Source &s){
this->files.erase(remove(files.begin(), files.end(), s), files.end());
notify();
}
void Repository::reviseFile(const string& file,const string &name) {
for(auto it = files.begin(); it != files.end(); it++) {
if( (*it).getName() == file){
(*it).changeStatus("revised");
(*it).changeReviewer(name);
}
}
notify();
}
Repository::~Repository() {
this->writeToFile();
}
//------------------------------------------------
void Repository::loadFromFile() {
ifstream f(file);
string line;
while(getline(f, line)){
stringstream ss(line);
vector<string> tokens;
string token;
while(getline(ss, token, ','))
tokens.push_back(token);
progs.push_back(Programmer(tokens[0], stoi(tokens[1])));
}
f.close();
f.open("/Users/AndiD/Documents/C++/exam/source.txt");
while(getline(f, line)){
stringstream ss(line);
vector<string> tokens;
string token;
while(getline(ss, token ,','))
tokens.push_back(token);
files.push_back(Source(tokens[0], tokens[1], tokens[2], tokens[3]));
}
f.close();
this->sortData();
notify();
}
void Repository::sortData() {
sort(files.begin(), files.end(), [](const Source& a,const Source& b){
return a.getName() < b.getName();
});
}
void Repository::writeToFile(){
ofstream f("/Users/AndiD/Documents/C++/exam/source.txt");
for(auto it : files)
f<<it.getName()<<","<<it.getStatus()<<","<<it.getCreator()<<","<<it.getReviewer()<<"\n";
f.close();
}
|
[
"andi.deh30@icloud.com"
] |
andi.deh30@icloud.com
|
7522d74331191d64ee6c2309b1d7755b361a6d68
|
ed20cf1539dbc0aa2f57f3451f0aba2c77e02eb8
|
/week-01/day-3/AnimalsAndLegs/main.cpp
|
340714bd507be2fdc156eb8e2650cf3cc11e4968
|
[] |
no_license
|
green-fox-academy/Joco456
|
60b0090dcc9f368240cca045eea4b3f67df69f83
|
3b98cdb39f26010246ecc38837b62e4f37d00b91
|
refs/heads/master
| 2020-05-04T08:59:18.192461
| 2019-10-03T09:17:11
| 2019-10-03T09:17:11
| 179,058,002
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 629
|
cpp
|
#include <iostream>
int main(int argc, char* args[]) {
// Write a program that asks for two integers
// The first represents the number of chickens the farmer has
// The second represents the number of pigs owned by the farmer
// It should print how many legs all the animals have
int chicken;
int pig;
std::cout << "Please enter the number of chickens!" <<std::endl;
std::cin >> chicken;
std::cout << "Please enter the number of pigs!" << std::endl;
std::cin >> pig;
int legs = chicken * 2 + pig * 4;
std::cout << "The number of legs: " << legs << std::endl;
return 0;
}
|
[
"jozsef.varga.123@gmail.com"
] |
jozsef.varga.123@gmail.com
|
d16e72eb62b0ea6a528110a7746777564d3b9b85
|
b958286bb016a56f5ddff5514f38fbd29f3e9072
|
/include/ublox/message/LogInfoPoll.h
|
72f0b757de4e7a14d0cb8d72178f8e282f6ac488
|
[] |
no_license
|
yxw027/cc.ublox.generated
|
abdda838945777a498f433b0d9624a567ab1ea80
|
a8bf468281d2d06e32d3e029c40bc6d38e4a34de
|
refs/heads/master
| 2021-01-14T23:03:20.722801
| 2020-02-20T06:24:46
| 2020-02-20T06:24:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,376
|
h
|
// Generated by commsdsl2comms v3.3.2
/// @file
/// @brief Contains definition of <b>"LOG-INFO (Poll)"</b> message and its fields.
#pragma once
#include <tuple>
#include "comms/MessageBase.h"
#include "ublox/MsgId.h"
#include "ublox/message/LogInfoPollCommon.h"
#include "ublox/options/DefaultOptions.h"
namespace ublox
{
namespace message
{
/// @brief Fields of @ref LogInfoPoll.
/// @tparam TOpt Extra options
/// @see @ref LogInfoPoll
/// @headerfile "ublox/message/LogInfoPoll.h"
template <typename TOpt = ublox::options::DefaultOptions>
struct LogInfoPollFields
{
/// @brief All the fields bundled in std::tuple.
using All = std::tuple<
>;
};
/// @brief Definition of <b>"LOG-INFO (Poll)"</b> message class.
/// @details
/// See @ref LogInfoPollFields for definition of the fields this message contains.
/// @tparam TMsgBase Base (interface) class.
/// @tparam TOpt Extra options
/// @headerfile "ublox/message/LogInfoPoll.h"
template <typename TMsgBase, typename TOpt = ublox::options::DefaultOptions>
class LogInfoPoll : public
comms::MessageBase<
TMsgBase,
typename TOpt::message::LogInfoPoll,
comms::option::def::StaticNumIdImpl<ublox::MsgId_LogInfo>,
comms::option::def::FieldsImpl<typename LogInfoPollFields<TOpt>::All>,
comms::option::def::MsgType<LogInfoPoll<TMsgBase, TOpt> >,
comms::option::def::HasName
>
{
// Redefinition of the base class type
using Base =
comms::MessageBase<
TMsgBase,
typename TOpt::message::LogInfoPoll,
comms::option::def::StaticNumIdImpl<ublox::MsgId_LogInfo>,
comms::option::def::FieldsImpl<typename LogInfoPollFields<TOpt>::All>,
comms::option::def::MsgType<LogInfoPoll<TMsgBase, TOpt> >,
comms::option::def::HasName
>;
public:
// Compile time check for serialisation length.
static const std::size_t MsgMinLen = Base::doMinLength();
static const std::size_t MsgMaxLen = Base::doMaxLength();
static_assert(MsgMinLen == 0U, "Unexpected min serialisation length");
static_assert(MsgMaxLen == 0U, "Unexpected max serialisation length");
/// @brief Name of the message.
static const char* doName()
{
return ublox::message::LogInfoPollCommon::name();
}
};
} // namespace message
} // namespace ublox
|
[
"arobenko@gmail.com"
] |
arobenko@gmail.com
|
ad31786f160f44adfcdf7294309707b2c1da59c7
|
53b28ebf3028837eaf69870ea14f1393a7728cf4
|
/src/Engine/XmlExpertSystemLoader.cpp
|
6d017bd024fc700f76d0440610ca41067f29d1e7
|
[
"MIT"
] |
permissive
|
AndreyBuyanov/ExpertSystem
|
a538aa34a9401fc2f228430b73697a92801b14ce
|
a4208300ad3f1095259345511debb9e28af0c9fc
|
refs/heads/main
| 2023-02-02T17:45:04.201868
| 2020-12-17T13:02:56
| 2020-12-17T13:02:56
| 319,333,142
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,521
|
cpp
|
#include "XmlExpertSystemLoader.hpp"
#include "ILogger.hpp"
#include "pugixml.hpp"
#include <stdexcept>
namespace ES
{
/**
* Создание загрузчика по умолчанию.
*
* \return Экземпляр загрузчика
*/
std::unique_ptr<IExpertSystemLoader> CreateExpertSystemLoader()
{
return std::make_unique<XmlExpertSystemLoader>();
}
/**
* Загрузка экспертной системы из файла конфигурации.
*
* \param configPath путь к файлу конфигурации
* \return
*/
void XmlExpertSystemLoader::Load(
const std::string& configPath) noexcept(false)
{
// xml-файл
pugi::xml_document doc;
// Открываем файл
pugi::xml_parse_result result = doc.load_file(configPath.c_str());
// Проверяем результат открытия и парсинга файла
if (!result) {
// Что-то пошло не так. Кидаем исключение
throw std::runtime_error(result.description());
}
// Ищем в документе элемент <es>
auto elEs = doc.child("es");
if (!elEs) {
// Элемент <es> не найден. Кидаем исключение
throw std::runtime_error(
u8"В конфигурационном файле не найден элемент <es>");
}
// Ищем в дочерних элементах элемента <es> элемент <name>
auto elName = elEs.child("name");
if (!elName) {
// Элемент <name> не найден. Кидаем исключение
throw std::runtime_error(
u8"В конфигурационном файле не найден элемент <name>");
}
// Сохраняем название экспертной системы
m_name = elName.text().as_string();
// Ищем в дочерних элементах элемента <es> элемент <tree>
auto elTree = elEs.child("tree");
if (!elTree) {
// Элемент <tree> не найден. Кидаем исключение
throw std::runtime_error(
u8"В конфигурационном файле не найден элемент <tree>");
}
// Ищем в дочерних элементах элемента <tree> элемент <nodes>
auto elNodes = elTree.child("nodes");
if (!elNodes) {
// Элемент <nodes> не найден. Кидаем исключение
throw std::runtime_error(
u8"В конфигурационном файле не найден элемент <nodes>");
}
// Проходим по дочерним элементам <node> элемента <nodes>
for (auto node = elNodes.child("node"); node; node = node.next_sibling("node")) {
// Считываем атрибут type
auto nodeType = node.attribute("type");
if (!nodeType) {
// Атрибут type не найден. Запишем предупреждение в лог
logger->Log(LogLevel::Warning,
u8"У элемента <node> не найден атрибут type");
// Проигнорируем текущйи элемент и перейдём к следующему элементу
continue;
}
// Считываем атрибут id
auto nodeID = node.attribute("id");
if (!nodeID) {
// Атрибут id не найден. Запишем предупреждение в лог
logger->Log(LogLevel::Warning,
u8"У элемента <node> не найден атрибут id");
// Проигнорируем текущйи элемент и перейдём к следующему элементу
continue;
}
// Считываем данные узла
auto nodeData = node.text();
if (!nodeData) {
// Данных не оказалось. Запишем предупреждение в лог
logger->Log(LogLevel::Warning,
u8"Элемент <node> не содержит данных");
// Проигнорируем текущйи элемент и перейдём к следующему элементу
continue;
}
// Получаем стороковое представление типа узла
std::string nodeTypeStr = nodeType.as_string();
if (nodeTypeStr == "question") {
// Если текущий узел - это вопрос, то добавляем данные этого узла к списку вопросов
m_questions.emplace_back(nodeID.as_int(), std::string(nodeData.as_string()));
}
else if (nodeTypeStr == "answer") {
// Если текущий узел - это ответ, то добавляем данные этого узла к списку ответов
m_answers.emplace_back(nodeID.as_int(), nodeData.as_string());
}
else {
// Неизвестный тип узла. Запишем предупреждение в лог
logger->Log(LogLevel::Warning,
u8"Элемент <node> имеет неизвестный тип");
}
}
// Ищем в дочерних элементах элемента <tree> элемент <connections>
auto nodeConnections = elTree.child("connections");
if (!nodeConnections) {
// Элемент <connections> не найден. Кидаем исключение
throw std::runtime_error(
u8"В конфигурационном файле не найден элемент <connections>");
}
// Проходим по дочерним элементам <connection> элемента <connections>
for (auto connection = nodeConnections.child("connection"); connection; connection = connection.next_sibling("connection")) {
// Считываем атрибут src
auto src = connection.attribute("src");
if (!src) {
// Атрибут src не найден. Запишем предупреждение в лог
logger->Log(LogLevel::Warning,
u8"У элемента <connection> не найден атрибут src");
// Проигнорируем текущйи элемент и перейдём к следующему элементу
continue;
}
// Считываем атрибут dst
auto dst = connection.attribute("dst");
if (!dst) {
// Атрибут dst не найден. Запишем предупреждение в лог
logger->Log(LogLevel::Warning,
u8"У элемента <connection> не найден атрибут dst");
// Проигнорируем текущйи элемент и перейдём к следующему элементу
continue;
}
// Считываем атрибут predicat
auto predicat = connection.attribute("predicat");
if (!predicat) {
// Атрибут predicat не найден. Запишем предупреждение в лог
logger->Log(LogLevel::Warning,
u8"У элемента <connection> не найден атрибут predicat");
// Проигнорируем текущйи элемент и перейдём к следующему элементу
continue;
}
// Добавляем соединение к списку соединений.
// Предикат - это функция сравнения числа с заданным в атрибуте predicat.
// Те если параметр предиката раен 0, то если вызвать данный предикат,
// передав в него 0, то получим ture.
// Предикаты понадабятся при хождении по дереву
m_connections.emplace_back(src.as_int(), dst.as_int(),
[predicat=predicat.as_int()] (const int value) -> bool
{
return value == predicat;
});
}
logger->Log(LogLevel::Info, u8"Экспертная система загружена");
}
}
|
[
"andreew.12.87@gmail.com"
] |
andreew.12.87@gmail.com
|
67ea3a42022021207bf872642692326877df368d
|
786de89be635eb21295070a6a3452f3a7fe6712c
|
/psddl_hdf2psana/tags/V00-02-02/include/epics.ddl.h
|
af4c7b8d2527c81dcb4079577eabc2d828ab2ca4
|
[] |
no_license
|
connectthefuture/psdmrepo
|
85267cfe8d54564f99e17035efe931077c8f7a37
|
f32870a987a7493e7bf0f0a5c1712a5a030ef199
|
refs/heads/master
| 2021-01-13T03:26:35.494026
| 2015-09-03T22:22:11
| 2015-09-03T22:22:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,966
|
h
|
#ifndef PSDDL_HDF2PSANA_EPICS_DDL_H
#define PSDDL_HDF2PSANA_EPICS_DDL_H 1
// *** Do not edit this file, it is auto-generated ***
#include "psddl_psana/epics.ddl.h"
#include "hdf5pp/Group.h"
#include "hdf5pp/Type.h"
#include "PSEvt/Proxy.h"
namespace psddl_hdf2psana {
namespace Epics {
enum {
iXtcVersion = 1 /**< */
};
enum {
iMaxPvNameLength = 64 /**< Maximum size of PV name string. */
};
enum {
MAX_STRING_SIZE = 40 /**< Maximum length of strings in EPICS. */
};
enum {
MAX_UNITS_SIZE = 8 /**< Maximum lenght of units strings. */
};
enum {
MAX_ENUM_STRING_SIZE = 26 /**< Maximum length of strings specifying ENUMs. */
};
enum {
MAX_ENUM_STATES = 16 /**< Maximum number of different ENUM constants. */
};
/** Enum specifying type of DBR structures. */
enum DbrTypes {
DBR_STRING = 0,
DBR_SHORT = 1,
DBR_FLOAT = 2,
DBR_ENUM = 3,
DBR_CHAR = 4,
DBR_LONG = 5,
DBR_DOUBLE = 6,
DBR_STS_STRING = 7,
DBR_STS_SHORT = 8,
DBR_STS_FLOAT = 9,
DBR_STS_ENUM = 10,
DBR_STS_CHAR = 11,
DBR_STS_LONG = 12,
DBR_STS_DOUBLE = 13,
DBR_TIME_STRING = 14,
DBR_TIME_INT = 15,
DBR_TIME_SHORT = 15,
DBR_TIME_FLOAT = 16,
DBR_TIME_ENUM = 17,
DBR_TIME_CHAR = 18,
DBR_TIME_LONG = 19,
DBR_TIME_DOUBLE = 20,
DBR_GR_STRING = 21,
DBR_GR_SHORT = 22,
DBR_GR_FLOAT = 23,
DBR_GR_ENUM = 24,
DBR_GR_CHAR = 25,
DBR_GR_LONG = 26,
DBR_GR_DOUBLE = 27,
DBR_CTRL_STRING = 28,
DBR_CTRL_SHORT = 29,
DBR_CTRL_FLOAT = 30,
DBR_CTRL_ENUM = 31,
DBR_CTRL_CHAR = 32,
DBR_CTRL_LONG = 33,
DBR_CTRL_DOUBLE = 34,
};
namespace ns_epicsTimeStamp_v0 {
struct dataset_data {
static hdf5pp::Type native_type();
static hdf5pp::Type stored_type();
dataset_data();
dataset_data(const Psana::Epics::epicsTimeStamp& psanaobj);
~dataset_data();
uint32_t secPastEpoch;
uint32_t nsec;
operator Psana::Epics::epicsTimeStamp() const { return Psana::Epics::epicsTimeStamp(secPastEpoch, nsec); }
};
}
namespace ns_EpicsPvHeader_v0 {
struct dataset_data {
static hdf5pp::Type native_type();
static hdf5pp::Type stored_type();
dataset_data();
dataset_data(const Psana::Epics::EpicsPvHeader& psanaobj);
~dataset_data();
int16_t pvId;
int16_t dbrType;
int16_t numElements;
};
}
class EpicsPvHeader_v0 : public Psana::Epics::EpicsPvHeader {
public:
typedef Psana::Epics::EpicsPvHeader PsanaType;
EpicsPvHeader_v0() {}
EpicsPvHeader_v0(hdf5pp::Group group, hsize_t idx)
: m_group(group), m_idx(idx) {}
EpicsPvHeader_v0(const boost::shared_ptr<Epics::ns_EpicsPvHeader_v0::dataset_data>& ds) : m_ds_data(ds) {}
virtual ~EpicsPvHeader_v0() {}
virtual int16_t pvId() const;
virtual int16_t dbrType() const;
virtual int16_t numElements() const;
/** Returns 1 if PV is one of CTRL types, 0 otherwise. */
uint8_t isCtrl() const;
/** Returns 1 if PV is one of TIME types, 0 otherwise. */
uint8_t isTime() const;
/** Returns status value for the PV. */
uint16_t status() const;
/** Returns severity value for the PV. */
uint16_t severity() const;
private:
mutable hdf5pp::Group m_group;
hsize_t m_idx;
mutable boost::shared_ptr<Epics::ns_EpicsPvHeader_v0::dataset_data> m_ds_data;
void read_ds_data() const;
};
namespace ns_PvConfigV1_v0 {
struct dataset_data {
static hdf5pp::Type native_type();
static hdf5pp::Type stored_type();
dataset_data();
dataset_data(const Psana::Epics::PvConfigV1& psanaobj);
~dataset_data();
int16_t pvId;
char description[64];
float interval;
operator Psana::Epics::PvConfigV1() const { return Psana::Epics::PvConfigV1(pvId, description, interval); }
};
}
namespace ns_ConfigV1_v0 {
struct dataset_config {
static hdf5pp::Type native_type();
static hdf5pp::Type stored_type();
dataset_config();
dataset_config(const Psana::Epics::ConfigV1& psanaobj);
~dataset_config();
int32_t numPv;
};
}
class ConfigV1_v0 : public Psana::Epics::ConfigV1 {
public:
typedef Psana::Epics::ConfigV1 PsanaType;
ConfigV1_v0() {}
ConfigV1_v0(hdf5pp::Group group, hsize_t idx)
: m_group(group), m_idx(idx) {}
virtual ~ConfigV1_v0() {}
virtual int32_t numPv() const;
virtual ndarray<const Psana::Epics::PvConfigV1, 1> pvControls() const;
private:
mutable hdf5pp::Group m_group;
hsize_t m_idx;
mutable boost::shared_ptr<Epics::ns_ConfigV1_v0::dataset_config> m_ds_config;
void read_ds_config() const;
mutable ndarray<const Psana::Epics::PvConfigV1, 1> m_ds_pvConfig;
void read_ds_pvConfig() const;
};
boost::shared_ptr<PSEvt::Proxy<Psana::Epics::ConfigV1> > make_ConfigV1(int version, hdf5pp::Group group, hsize_t idx);
void store(const Psana::Epics::ConfigV1& obj, hdf5pp::Group group, int version = -1);
void append(const Psana::Epics::ConfigV1& obj, hdf5pp::Group group, int version = -1);
} // namespace Epics
} // namespace psddl_hdf2psana
#endif // PSDDL_HDF2PSANA_EPICS_DDL_H
|
[
"salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7"
] |
salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7
|
be9557e78bc46f61f20e3cb66096cf1cb6d44901
|
cf4876d97646702a89e10bf9c59cd071aba2852b
|
/src/controller_JIK.h
|
55595e12b02a8cf071734a89382364280cfea182
|
[] |
no_license
|
rbackman/odeapp
|
1d269625bd3f1b8edb473586274e64349a48caf0
|
058aedb4dc50a387f1b9c5195ef6f10e3fa3818f
|
refs/heads/main
| 2023-06-20T15:55:01.810361
| 2021-07-17T02:31:31
| 2021-07-17T02:31:31
| 386,815,549
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 973
|
h
|
#pragma once
#include "controller.h"
#include "common.h"
#include <gsim/gs_matn.h>
//this controller is responsible for solving the analytical ik to achieve the root and foot positions as close as possible
//
class IkBody;
class KnScene;
class JIKController : public Controller
{
public:
JIKController(ODEHuman* human);
~JIKController(void);
bool evaluate();
void setRoot(GsVec p);
void setLeft(GsVec p);
void setRight(GsVec p);
void solveIK(SnManipulator* manip,ODEJoint* endJoint, ODEJoint* baseJoint);
/*
void setRightY(float y);
void setLeftY(float y);
void setHeight(float h);
void setRightVisible(bool vis);
void setLeftVisible(bool vis);
void setRootVisible(bool vis);
*/
void matchIK();
private:
GsMatn J,Jt,JJt,JJTPG,JJt_inv,j_plus, Idt;
GsMatn eff,theta;
int n,m;
bool manual;
GsVec rootStart;
GsVec rootOffset;
SnManipulator* rootManip;
SnManipulator* leftManip;
SnManipulator* rightManip;
void makeIK();
//stuff
};
|
[
"rbackman07@gmail.com"
] |
rbackman07@gmail.com
|
5e7044c3378aadd8b70110ac3694d321ccf2043c
|
49f88ff91aa582e1a9d5ae5a7014f5c07eab7503
|
/gen/third_party/perfetto/protos/perfetto/trace/ftrace/sched_process_exit.pbzero.cc
|
09ace1a3abeb3c06288dc3cf179382fe34834a98
|
[] |
no_license
|
AoEiuV020/kiwibrowser-arm64
|
b6c719b5f35d65906ae08503ec32f6775c9bb048
|
ae7383776e0978b945e85e54242b4e3f7b930284
|
refs/heads/main
| 2023-06-01T21:09:33.928929
| 2021-06-22T15:56:53
| 2021-06-22T15:56:53
| 379,186,747
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,267
|
cc
|
// Autogenerated by the ProtoZero compiler plugin. DO NOT EDIT.
#include "perfetto/trace/ftrace/sched_process_exit.pbzero.h"
namespace {
static const ::protozero::ProtoFieldDescriptor kInvalidField = {"", ::protozero::ProtoFieldDescriptor::Type::TYPE_INVALID, 0, false};
}
namespace perfetto {
namespace protos {
namespace pbzero {
static const ::protozero::ProtoFieldDescriptor kFields_SchedProcessExitFtraceEvent[] = {
{"comm", ::protozero::ProtoFieldDescriptor::Type::TYPE_STRING, 1, 0},
{"pid", ::protozero::ProtoFieldDescriptor::Type::TYPE_INT32, 2, 0},
{"tgid", ::protozero::ProtoFieldDescriptor::Type::TYPE_INT32, 3, 0},
{"prio", ::protozero::ProtoFieldDescriptor::Type::TYPE_INT32, 4, 0},
};
const ::protozero::ProtoFieldDescriptor* SchedProcessExitFtraceEvent::GetFieldDescriptor(uint32_t field_id) {
switch (field_id) {
case kCommFieldNumber:
return &kFields_SchedProcessExitFtraceEvent[0];
case kPidFieldNumber:
return &kFields_SchedProcessExitFtraceEvent[1];
case kTgidFieldNumber:
return &kFields_SchedProcessExitFtraceEvent[2];
case kPrioFieldNumber:
return &kFields_SchedProcessExitFtraceEvent[3];
default:
return &kInvalidField;
}
}
} // Namespace.
} // Namespace.
} // Namespace.
|
[
"aoeiuv020@gmail.com"
] |
aoeiuv020@gmail.com
|
535453268335bd882b9fb645fe0835aa7b37bf1c
|
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
|
/components/content_settings/core/test/content_settings_test_utils.cc
|
9ec3edb023a3f76561d95112bdd3912ff2d9f116
|
[
"BSD-3-Clause"
] |
permissive
|
massnetwork/mass-browser
|
7de0dfc541cbac00ffa7308541394bac1e945b76
|
67526da9358734698c067b7775be491423884339
|
refs/heads/master
| 2022-12-07T09:01:31.027715
| 2017-01-19T14:29:18
| 2017-01-19T14:29:18
| 73,799,690
| 4
| 4
|
BSD-3-Clause
| 2022-11-26T11:53:23
| 2016-11-15T09:49:29
| null |
UTF-8
|
C++
| false
| false
| 2,364
|
cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/content_settings/core/test/content_settings_test_utils.h"
#include "components/content_settings/core/browser/content_settings_observable_provider.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_types.h"
namespace content_settings {
// static
base::Value* TestUtils::GetContentSettingValue(
const ProviderInterface* provider,
const GURL& primary_url,
const GURL& secondary_url,
ContentSettingsType content_type,
const std::string& resource_identifier,
bool include_incognito) {
return HostContentSettingsMap::GetContentSettingValueAndPatterns(
provider, primary_url, secondary_url, content_type, resource_identifier,
include_incognito, NULL, NULL).release();
}
// static
ContentSetting TestUtils::GetContentSetting(
const ProviderInterface* provider,
const GURL& primary_url,
const GURL& secondary_url,
ContentSettingsType content_type,
const std::string& resource_identifier,
bool include_incognito) {
std::unique_ptr<base::Value> value(
GetContentSettingValue(provider, primary_url, secondary_url, content_type,
resource_identifier, include_incognito));
return ValueToContentSetting(value.get());
}
// static
std::unique_ptr<base::Value> TestUtils::GetContentSettingValueAndPatterns(
content_settings::RuleIterator* rule_iterator,
const GURL& primary_url,
const GURL& secondary_url,
ContentSettingsPattern* primary_pattern,
ContentSettingsPattern* secondary_pattern) {
return HostContentSettingsMap::GetContentSettingValueAndPatterns(
rule_iterator, primary_url, secondary_url, primary_pattern,
secondary_pattern);
}
// static
void TestUtils::OverrideProvider(
HostContentSettingsMap* map,
std::unique_ptr<content_settings::ObservableProvider> provider,
HostContentSettingsMap::ProviderType type) {
if (map->content_settings_providers_[type]) {
map->content_settings_providers_[type]->ShutdownOnUIThread();
}
map->content_settings_providers_[type] = std::move(provider);
}
} // namespace content_settings
|
[
"xElvis89x@gmail.com"
] |
xElvis89x@gmail.com
|
3a5d27b7e91af74d728dc2e78abe3b24e1b1de51
|
e73d2cea4aaeb9be92105581df617d524a532ba5
|
/Space_Invaders_Linux/src/Pilot.cpp
|
f450596f2c280d0cd6c1e76aa155f011c6aa0698
|
[] |
no_license
|
shanesatterfield/Space_Invaders
|
f9200650dab80d9fd26ab4f99ffb2fa23a53a57a
|
4ca0e2e359daeafec391de33fdc555287631355e
|
refs/heads/master
| 2016-08-07T04:51:30.025577
| 2012-08-27T10:57:09
| 2012-08-27T10:57:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,376
|
cpp
|
#include "Pilot.h"
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include "Shot.h"
#include <vector>
#include <time.h>
#include <stdio.h>
#include <math.h>
Pilot::Pilot( int X, int Y, SDL_Surface* temp, SDL_Surface* shieldTemp, SDL_Surface* lowTemp, int shield_)
{
//Initialize the offsets
x = X;
y = Y;
//Initialize the velocity
xVel = 0;
yVel = 0;
shield = shield_;
image = temp;
shieldImage = shieldTemp;
lowShield = lowTemp;
hardMode = true;
//Create the necessary SDL_Rects
box.resize( 6 );
//Initialize the collision boxes' width and height
box[ 0 ].w = 4;
box[ 0 ].h = 12;
box[ 1 ].w = 3*4;
box[ 1 ].h = 4;
box[ 2 ].w = 20;
box[ 2 ].h = 4;
box[ 3 ].w = 36;
box[ 3 ].h = 4;
box[ 4 ].w = 52;
box[ 4 ].h = 4;
box[ 5 ].w = 68;
box[ 5 ].h = 20;
//Move the collision boxes to their proper spot
shift_boxes();
}
void Pilot::apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination){
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface(source, NULL, destination, &offset);
}
void Pilot::shift_boxes()
{
//The row offset
int r = 0;
//Go through the dot's collision boxes
for( int set = 0; set < box.size(); set++ )
{
//Center the collision box
box[ set ].x = x + ( image->w - box[ set ].w ) / 2;
//Set the collision box at its row offset
box[ set ].y = y + r;
//Move the row offset down the height of the collision box
r += box[ set ].h;
}
}
void Pilot::pilotMovement(std::vector<Shot> &hyperBeam, SDL_Surface* shots, clock_t &shotPause, int SCREEN_WIDTH, int FRAMES_PER_SECOND, int frames_per){
Uint8 *keystates = SDL_GetKeyState(NULL);
if( (keystates[SDLK_RIGHT] || keystates[SDLK_d] ) && x + image->w < SCREEN_WIDTH){
if(frames_per > 0){
x += 10 * ceil(float(FRAMES_PER_SECOND) / frames_per);
}
else
x += 10;
shift_boxes();
}
if( (keystates[SDLK_LEFT] || keystates[SDLK_a]) && x > 0){
if(frames_per > 0 && frames_per < FRAMES_PER_SECOND){
x -= 10 * (float(FRAMES_PER_SECOND) / frames_per);
}
else
x -= 10;
shift_boxes();
}
if(keystates[SDLK_SPACE] && (float(clock()) - float(shotPause))/CLOCKS_PER_SEC*10 > .2){
Shot temp2(x + (image->w - shots->w)/2, y, shots);
hyperBeam.push_back(temp2);
shotPause = clock();
}
}
void Pilot::show(SDL_Surface* screen, SDL_Surface* tempMessage){
if(!hardMode){
if(shield >= 3){
apply_surface(x,y,shieldImage,screen);
}
else if(shield > 0){
apply_surface(x,y,lowShield,screen);
}
else{
apply_surface(x,y,image,screen);
}
}
else
apply_surface(x,y,image,screen);
apply_surface(x + (image->w - tempMessage->w)/2, y + (image->h - tempMessage->h)/1.35, tempMessage, screen);
}
std::vector<SDL_Rect> &Pilot::get_rects()
{
//Retrieve the collision boxes
return box;
}
bool Pilot::check_collision( std::vector<SDL_Rect> &B )
{
//The sides of the rectangles
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Go through the A boxes
for( int Abox = 0; Abox < box.size(); Abox++ )
{
//Calculate the sides of rect A
leftA = box[ Abox ].x;
rightA = box[ Abox ].x + box[ Abox ].w;
topA = box[ Abox ].y;
bottomA = box[ Abox ].y + box[ Abox ].h;
//Go through the B boxes
for( int Bbox = 0; Bbox < B.size(); Bbox++ )
{
//Calculate the sides of rect B
leftB = B[ Bbox ].x;
rightB = B[ Bbox ].x + B[ Bbox ].w;
topB = B[ Bbox ].y;
bottomB = B[ Bbox ].y + B[ Bbox ].h;
//If no sides from A are outside of B
if( ( ( bottomA <= topB ) || ( topA >= bottomB ) || ( rightA <= leftB ) || ( leftA >= rightB ) ) == false )
{
//A collision is detected
return true;
}
}
}
//If neither set of collision boxes touched
return false;
}
|
[
"dustyplant@gmail.com"
] |
dustyplant@gmail.com
|
ad19aa05a8f0c384d25590db27f7cf41915fa688
|
9030ce2789a58888904d0c50c21591632eddffd7
|
/SDK/ARKSurvivalEvolved_Dimorph_Character_BP_Aberrant_parameters.hpp
|
8bcf207f6bba5e77c03a80af773ede4f778f4f25
|
[
"MIT"
] |
permissive
|
2bite/ARK-SDK
|
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
|
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
|
refs/heads/master
| 2022-09-19T06:28:20.076298
| 2022-09-03T17:21:00
| 2022-09-03T17:21:00
| 232,411,353
| 14
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 949
|
hpp
|
#pragma once
// ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Dimorph_Character_BP_Aberrant_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Dimorph_Character_BP_Aberrant.Dimorph_Character_BP_Aberrant_C.UserConstructionScript
struct ADimorph_Character_BP_Aberrant_C_UserConstructionScript_Params
{
};
// Function Dimorph_Character_BP_Aberrant.Dimorph_Character_BP_Aberrant_C.ExecuteUbergraph_Dimorph_Character_BP_Aberrant
struct ADimorph_Character_BP_Aberrant_C_ExecuteUbergraph_Dimorph_Character_BP_Aberrant_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"sergey.2bite@gmail.com"
] |
sergey.2bite@gmail.com
|
403a204ffd461b782e7a43fe1243ff5b71db04e2
|
322edfff463a328adfa8e418f8f2d5f03b990715
|
/src/comm-device-interface/op20.cpp
|
91c594083e83961999ff66726b370019fedb9127
|
[] |
no_license
|
DowJhob/Evo-live-map
|
123b4f56a40537311c4c7dbe717de2d293d069bb
|
c764bc2fa79c648dfe435e69a48f053b32590c53
|
refs/heads/master
| 2023-08-19T01:51:25.030081
| 2022-06-11T11:32:33
| 2022-06-11T11:32:33
| 155,981,294
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,454
|
cpp
|
#include "op20.h"
OP20::OP20(QString dllName, QString DeviceDesc, QString DeviceUniqueID) : j2534_interface(dllName, DeviceDesc, DeviceUniqueID)
{
//devType = deviceType::OP20;
//qDebug() << "OP20" << DeviceUniqueID;
QThread *this_thread = new QThread();
QObject::connect(this_thread, &QThread::started, this, [this](){
pollTimer = new QTimer(this);
QObject::connect(pollTimer, &QTimer::timeout, this, [this](){
QByteArray a = readWB();
if (a.size() > 0)
emit readyRead(a);
});
}
);
//connect(this_thread, &QThread::started, this, &controller::loop, Qt::QueuedConnection);
QObject::connect(this, &OP20::destroyed, this_thread, &QThread::quit); // Когда удалим объект остановим поток
QObject::connect(this_thread, &QThread::finished, this_thread, &QThread::deleteLater); // Когда остановим поток удалим его
moveToThread(this_thread);
this_thread->start();
}
OP20::~OP20()
{
}
bool OP20::isClosed()
{
if (chanID_INNO == 0)
return true;
else
return false;
}
bool OP20::openWB(uint baudRate)
{
//qDebug() << "==================== OP20:openWB ==================================" << j2534->lastErrorString();
if (isNotUse())
if (j2534->PassThruOpen(nullptr, &devID)) // Get devID
{
qDebug() << "==================== OP20:openWB::PassThruOpen ==================================" << j2534->lastErrorString();
return false;
}
setUse();
//qDebug() << "==================== OP20:openWB3 ==================================" << j2534->lastErrorString();
// try to connect to the specific channel we would like to use
//
// in this case, it is the 2.5mm jack on the Openport 2.0 which can be used as
// a RS-232 voltage level receive only input. the Innovate MTS bus
// can be used this way, as it is 19200 baud, N,8,1 serial and transmits continuously
// without any polling needed.
//
// note that the ISO9141_NO_CHECKSUM connection flag is used to avoid requiring the data
// to have valid ISO9141 checksums (it doesn't)
qDebug() << "==================== OP20:openWB::PassThruConnect before ==================================" << j2534->lastErrorString() << "devID" << devID << "chanID_INNO" << chanID_INNO;
if (chanID_INNO == 0)
if (j2534->PassThruConnect(devID, Protocol::ISO9141_INNO, ConnectFlag::ISO9141NoChecksum, baudRate, &chanID_INNO))
{
qDebug() << "==================== OP20:openWB::PassThruConnect after ==================================" << j2534->lastErrorString() << "devID" << devID << "chanID_INNO" << chanID_INNO;
return false;
}
qDebug() << "==================== OP20:openWB::PassThruConnect2 ==================================" << "devID" << devID << "chanID_INNO" << chanID_INNO;
// all J2534 channels need filters in order to receive anything at all
//
// in this case, we simply create a "pass all" filter so that we can see
// everything unfiltered in the raw stream
rxmsg.setProtocolId(Protocol::ISO9141_INNO);
rxmsg.m_rxStatus = 0;
rxmsg.m_txFlags = 0;
rxmsg.m_timestamp = 0;
rxmsg.m_dataSize = 1;
rxmsg.m_extraDataIndex = 0;
msgMask = msgPattern = rxmsg;
msgMask.m_data[0] = 0; // mask the first byte to 0
msgPattern.m_data[0] = 0; // match it with 0 (i.e. pass everything)
if (j2534->PassThruStartMsgFilter(chanID_INNO, PassThru::PassFilter, &msgMask, &msgPattern, NULL, &msgId))
{
qDebug() << "==================== OP20:openWB::PassThruStartMsgFilter ==================================" << j2534->lastErrorString();
return false;
}
return true;
}
bool OP20::connectWB(uint baudRate)
{
return true;
}
bool OP20::closeWB()
{
qDebug() << "\n==================== OP20::closeWB ==================================" << "chanID_INNO" << chanID_INNO;
if (j2534->PassThruDisconnect(chanID_INNO))
{
qDebug() << "==================== OP20:closeWB::PassThruDisconnect ==================================" << j2534->lastErrorString();
}
resetUse();
if(countUSE <= 0) // если последний то закрываем
{
countUSE = 0; // на всякий случай
j2534->PassThruClose(devID);
chanID_INNO = 0;
}
chanID_INNO = 0;
return true;
}
QByteArray OP20::readWB()
{
QByteArray a;
numRxMsg = 1;
do
{
j2534->PassThruReadMsgs(chanID_INNO, &rxmsg, &numRxMsg, 140);
qDebug() << "==================== OP20:readWB ==================================" << j2534->lastErrorString() << chanID_INNO;
a.append(QByteArray((char*)rx_msg.m_data, rx_msg.m_dataSize));
// qDebug()<< "j2534_interface::read " << "rx_msg.m_rxStatus" << rx_msg.m_rxStatus
// << "rx_msg.m_dataSize" << rx_msg.m_dataSize
// << "time" << QString::number( tt.nsecsElapsed()/1000000.0)
// << "NumMsgs=" << NumMsgs
// //<< "rx_msg[0].data" << QByteArray((char*)rx_msg[0].m_data, 4).toHex(':')
// ;
}
while(rx_msg.m_rxStatus == Message::RxStatusBit::InStartOfMessage);
//qDebug() << "OP20::read: readWB" << a << "\n\n";
//
return a;
}
|
[
"eulle@ya.ru"
] |
eulle@ya.ru
|
9858e297cb0b29f3f180a901f8f56c02bb3f4e0b
|
1974b1cd6499c5b121f035557e59308b2d39a8f9
|
/include/json/json.h
|
9777c6ac067df64ccfd6d3afe9707b84a267c6ec
|
[] |
no_license
|
harestomper/json-parser
|
7885622450a5fc12290ff3d3a2b0e3fa5804752a
|
aa9bfd6acfa8d95a88893c6a5525ca32424e55eb
|
refs/heads/master
| 2021-01-10T11:03:43.806049
| 2016-02-04T08:07:49
| 2016-02-04T08:07:49
| 50,937,788
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,655
|
h
|
/*
* json.h
*
* Created on: 18 янв. 2016 г.
* Author: Voldemar Khramtsov <harestomper@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _JSON_JSON_H_
#define _JSON_JSON_H_
#ifndef null
# if __cplusplus >= 201103L
# define null nullptr
# else
# define null 0
# endif
#endif /* null */
namespace json {
struct Value;
class Map;
class Array;
using Uint = unsigned int;
using Integer = long long int;
using iterator = Value*;
using const_iterator = Value const*;
struct MapBase
{
protected:
Value* m_values = null;
Uint* m_codes = null;
char** m_keys = null;
Uint m_num_buckets = 0;
Uint m_num_items = 0;
Uint m_capacity = 0;
};
struct ArrayBase
{
protected:
Value* m_data = null;
Uint m_num_items = 0;
Uint m_allocated_size = 0;
};
} /* namespace json */
#define BUFSIZE 1024
#define check_and_return(expr, ...) { \
if (not (expr)) \
{ \
char __b[BUFSIZE]; \
::snprintf(__b, BUFSIZE, " " __VA_ARGS__); \
fprintf(::stderr, "ERROR:%s:%s:%i:'%s', failure. %s\n", __FILE__, __func__, __LINE__, #expr, __b); \
return; \
} }
#define check_and_return_val(expr, retval, ...) { \
if (not (expr)) \
{ \
char __b[BUFSIZE]; \
::snprintf(__b, BUFSIZE, " " __VA_ARGS__); \
fprintf(::stderr, "ERROR:%s:%s:%i:'%s', failure. %s\n", __FILE__, __func__, __LINE__, #expr, __b); \
return (retval); \
} }
#include "jsonvalue.h"
#include "jsonarray.h"
#include "jsonmap.h"
#endif /* _JSON_JSON_H_ */
|
[
"harestomper@gmail.com"
] |
harestomper@gmail.com
|
26ace993b16b82ff66f7be95c7a58af088b811aa
|
bd80c038d443123c7b46102587e04afc0eeae80f
|
/GCJ2016/BFFs/bff.cpp
|
97bf4c2ce5c90323aebe3abc000853e13cfa4ffa
|
[] |
no_license
|
SiweiYang/CodingChallenge
|
73e0e3a47a7feafef472fea239c4ea37e0af3cc0
|
fb77dcdba597782f0447cbd7a2158fe3694957dc
|
refs/heads/master
| 2022-01-13T06:44:47.866243
| 2019-06-28T11:55:46
| 2019-06-28T11:55:46
| 3,609,562
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,313
|
cpp
|
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int run(int *m, bool *v, int i) {
if (v[i])return i;
v[i] = true;
return run(m, v, m[i]);
}
int count(bool *v, int s) {
int total = 0;
for (int i = 1; i < s + 1; i++) {
if (v[i])total++;
}
return total;
}
int main(int argc, char **argv) {
const char *fn = "sample3.in";
if (argc > 1)fn = argv[1];
ifstream in(fn);
int total_case;
in >> total_case;
for (int i = 1; i < total_case + 1; i++) {
int c_size;
in >> c_size;
int *m = new int[c_size + 1];
for (int j = 0; j < c_size; j++) {
in >> m[j+1];
}
int *mc = (int *)calloc(c_size + 1, sizeof(int));
bool *v = (bool *)calloc(c_size + 1, sizeof(bool));
for (int j = 1; j < c_size + 1; j++) {
v = (bool *)calloc(c_size + 1, sizeof(bool));
int end = run(m, v, j);
if (m[m[end]] == end) {
int c = count(v, c_size) - 1;
if (c > mc[end])mc[end] = c;
}
}
int max_c = 0;
for (int j = 1; j < c_size + 1; j++) {
max_c += mc[j];
}
for (int j = 1; j < c_size + 1; j++) {
v = (bool *)calloc(c_size + 1, sizeof(bool));
int end = run(m, v, j);
if (end != j) {
continue;
}
int c = count(v, c_size);
if (c > max_c)max_c = c;
}
cout << "Case #" << i << ": " << max_c << endl;
}
return 0;
}
|
[
"yangsiwei880813@gmail.com"
] |
yangsiwei880813@gmail.com
|
9e945bec14a0531a73af145394168a7536d4cebe
|
155bb920a8fc8fb3a0a545e923952e902e4ef3df
|
/XEngine.Core/Source/XEngine.Core.GeometryResource.h
|
53a85766134ff027a4e9f00fb907ca381c1c258e
|
[] |
no_license
|
rbmkp4800/XEngine
|
2035d0c7b81bc291b42e55e7ea91af1f6a86e8bc
|
f689d20d8deffd48399ba0d86432caf644235992
|
refs/heads/master
| 2021-01-01T15:59:43.013938
| 2019-03-10T13:14:53
| 2019-03-10T19:24:53
| 30,755,730
| 0
| 1
| null | 2020-07-13T21:23:33
| 2015-02-13T12:36:29
|
C++
|
UTF-8
|
C++
| false
| false
| 2,007
|
h
|
#pragma once
#include <XLib.Types.h>
#include <XLib.NonCopyable.h>
#include <XEngine.Render.Base.h>
#include <XEngine.Render.Scene.h>
#include "XEngine.Core.ResourceCache.h"
namespace XEngine::Core
{
using GeometryResourceUID = uint64;
using GeometryResourceHandle = uint16;
class GeometryResource : public XLib::NonCopyable
{
private:
uint32 vertexCount = 0;
uint32 indexCount = 0;
Render::BufferHandle buffer = Render::BufferHandle(0);
uint8 vertexStride = 0;
bool indexIs32Bit = false;
public:
GeometryResource() = default;
~GeometryResource() = default;
// NOTE: temporary
bool createFromFile(const char* filename);
void createCube();
void createPlane_texture();
void createPlane_tangentTexture();
void createCubicSphere(uint32 detalizationLevel);
inline Render::GeometryDesc getGeometryDesc() const
{
Render::GeometryDesc result;
result.vertexBufferHandle = buffer;
result.indexBufferHandle = buffer;
result.vertexDataOffset = 0;
result.indexDataOffset = vertexCount * vertexStride;
result.vertexDataSize = result.indexDataOffset;
result.indexCount = indexCount;
result.vertexStride = vertexStride;
result.indexIs32Bit = indexIs32Bit;
return result;
}
public: // creation
enum class CreationType : uint8;
struct CreationArgs;
class CreationTask;
static bool Create(const CreationArgs& args, CreationTask& task);
};
enum class GeometryResource::CreationType : uint8
{
None = 0,
Cube,
CubicSphere,
FromFile,
};
struct GeometryResource::CreationArgs
{
CreationType type = CreationType::None;
union
{
struct
{
uint16 detalization;
} cubicSphere;
struct
{
char filename[32];
} fromFile;
};
};
class GeometryResource::CreationTask : public XLib::NonCopyable
{
private:
public:
CreationTask() = default;
~CreationTask();
bool cancel();
};
//using GeometryResourceCache = ResourceCache<
// GeometryResourceUID, GeometryResourceHandle, GeometryResource>;
}
|
[
"rbmkp4800@gmail.com"
] |
rbmkp4800@gmail.com
|
cd6b10381de8c92142db8de3c46cd83932e3449a
|
27bb5ed9eb1011c581cdb76d96979a7a9acd63ba
|
/aws-cpp-sdk-ec2/source/model/ReservedInstancesOffering.cpp
|
6a82ce3490506889624d94c80d15a508f39bfed1
|
[
"Apache-2.0",
"JSON",
"MIT"
] |
permissive
|
exoscale/aws-sdk-cpp
|
5394055f0876a0dafe3c49bf8e804d3ddf3ccc54
|
0876431920136cf638e1748d504d604c909bb596
|
refs/heads/master
| 2023-08-25T11:55:20.271984
| 2017-05-05T17:32:25
| 2017-05-05T17:32:25
| 90,744,509
| 0
| 0
| null | 2017-05-09T12:43:30
| 2017-05-09T12:43:30
| null |
UTF-8
|
C++
| false
| false
| 13,634
|
cpp
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/ec2/model/ReservedInstancesOffering.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace EC2
{
namespace Model
{
ReservedInstancesOffering::ReservedInstancesOffering() :
m_reservedInstancesOfferingIdHasBeenSet(false),
m_instanceType(InstanceType::NOT_SET),
m_instanceTypeHasBeenSet(false),
m_availabilityZoneHasBeenSet(false),
m_duration(0),
m_durationHasBeenSet(false),
m_usagePrice(0.0),
m_usagePriceHasBeenSet(false),
m_fixedPrice(0.0),
m_fixedPriceHasBeenSet(false),
m_productDescription(RIProductDescription::NOT_SET),
m_productDescriptionHasBeenSet(false),
m_instanceTenancy(Tenancy::NOT_SET),
m_instanceTenancyHasBeenSet(false),
m_currencyCode(CurrencyCodeValues::NOT_SET),
m_currencyCodeHasBeenSet(false),
m_offeringType(OfferingTypeValues::NOT_SET),
m_offeringTypeHasBeenSet(false),
m_recurringChargesHasBeenSet(false),
m_marketplace(false),
m_marketplaceHasBeenSet(false),
m_pricingDetailsHasBeenSet(false),
m_offeringClass(OfferingClassType::NOT_SET),
m_offeringClassHasBeenSet(false),
m_scope(Scope::NOT_SET),
m_scopeHasBeenSet(false)
{
}
ReservedInstancesOffering::ReservedInstancesOffering(const XmlNode& xmlNode) :
m_reservedInstancesOfferingIdHasBeenSet(false),
m_instanceType(InstanceType::NOT_SET),
m_instanceTypeHasBeenSet(false),
m_availabilityZoneHasBeenSet(false),
m_duration(0),
m_durationHasBeenSet(false),
m_usagePrice(0.0),
m_usagePriceHasBeenSet(false),
m_fixedPrice(0.0),
m_fixedPriceHasBeenSet(false),
m_productDescription(RIProductDescription::NOT_SET),
m_productDescriptionHasBeenSet(false),
m_instanceTenancy(Tenancy::NOT_SET),
m_instanceTenancyHasBeenSet(false),
m_currencyCode(CurrencyCodeValues::NOT_SET),
m_currencyCodeHasBeenSet(false),
m_offeringType(OfferingTypeValues::NOT_SET),
m_offeringTypeHasBeenSet(false),
m_recurringChargesHasBeenSet(false),
m_marketplace(false),
m_marketplaceHasBeenSet(false),
m_pricingDetailsHasBeenSet(false),
m_offeringClass(OfferingClassType::NOT_SET),
m_offeringClassHasBeenSet(false),
m_scope(Scope::NOT_SET),
m_scopeHasBeenSet(false)
{
*this = xmlNode;
}
ReservedInstancesOffering& ReservedInstancesOffering::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode reservedInstancesOfferingIdNode = resultNode.FirstChild("reservedInstancesOfferingId");
if(!reservedInstancesOfferingIdNode.IsNull())
{
m_reservedInstancesOfferingId = StringUtils::Trim(reservedInstancesOfferingIdNode.GetText().c_str());
m_reservedInstancesOfferingIdHasBeenSet = true;
}
XmlNode instanceTypeNode = resultNode.FirstChild("instanceType");
if(!instanceTypeNode.IsNull())
{
m_instanceType = InstanceTypeMapper::GetInstanceTypeForName(StringUtils::Trim(instanceTypeNode.GetText().c_str()).c_str());
m_instanceTypeHasBeenSet = true;
}
XmlNode availabilityZoneNode = resultNode.FirstChild("availabilityZone");
if(!availabilityZoneNode.IsNull())
{
m_availabilityZone = StringUtils::Trim(availabilityZoneNode.GetText().c_str());
m_availabilityZoneHasBeenSet = true;
}
XmlNode durationNode = resultNode.FirstChild("duration");
if(!durationNode.IsNull())
{
m_duration = StringUtils::ConvertToInt64(StringUtils::Trim(durationNode.GetText().c_str()).c_str());
m_durationHasBeenSet = true;
}
XmlNode usagePriceNode = resultNode.FirstChild("usagePrice");
if(!usagePriceNode.IsNull())
{
m_usagePrice = StringUtils::ConvertToDouble(StringUtils::Trim(usagePriceNode.GetText().c_str()).c_str());
m_usagePriceHasBeenSet = true;
}
XmlNode fixedPriceNode = resultNode.FirstChild("fixedPrice");
if(!fixedPriceNode.IsNull())
{
m_fixedPrice = StringUtils::ConvertToDouble(StringUtils::Trim(fixedPriceNode.GetText().c_str()).c_str());
m_fixedPriceHasBeenSet = true;
}
XmlNode productDescriptionNode = resultNode.FirstChild("productDescription");
if(!productDescriptionNode.IsNull())
{
m_productDescription = RIProductDescriptionMapper::GetRIProductDescriptionForName(StringUtils::Trim(productDescriptionNode.GetText().c_str()).c_str());
m_productDescriptionHasBeenSet = true;
}
XmlNode instanceTenancyNode = resultNode.FirstChild("instanceTenancy");
if(!instanceTenancyNode.IsNull())
{
m_instanceTenancy = TenancyMapper::GetTenancyForName(StringUtils::Trim(instanceTenancyNode.GetText().c_str()).c_str());
m_instanceTenancyHasBeenSet = true;
}
XmlNode currencyCodeNode = resultNode.FirstChild("currencyCode");
if(!currencyCodeNode.IsNull())
{
m_currencyCode = CurrencyCodeValuesMapper::GetCurrencyCodeValuesForName(StringUtils::Trim(currencyCodeNode.GetText().c_str()).c_str());
m_currencyCodeHasBeenSet = true;
}
XmlNode offeringTypeNode = resultNode.FirstChild("offeringType");
if(!offeringTypeNode.IsNull())
{
m_offeringType = OfferingTypeValuesMapper::GetOfferingTypeValuesForName(StringUtils::Trim(offeringTypeNode.GetText().c_str()).c_str());
m_offeringTypeHasBeenSet = true;
}
XmlNode recurringChargesNode = resultNode.FirstChild("recurringCharges");
if(!recurringChargesNode.IsNull())
{
XmlNode recurringChargesMember = recurringChargesNode.FirstChild("item");
while(!recurringChargesMember.IsNull())
{
m_recurringCharges.push_back(recurringChargesMember);
recurringChargesMember = recurringChargesMember.NextNode("item");
}
m_recurringChargesHasBeenSet = true;
}
XmlNode marketplaceNode = resultNode.FirstChild("marketplace");
if(!marketplaceNode.IsNull())
{
m_marketplace = StringUtils::ConvertToBool(StringUtils::Trim(marketplaceNode.GetText().c_str()).c_str());
m_marketplaceHasBeenSet = true;
}
XmlNode pricingDetailsNode = resultNode.FirstChild("pricingDetailsSet");
if(!pricingDetailsNode.IsNull())
{
XmlNode pricingDetailsMember = pricingDetailsNode.FirstChild("item");
while(!pricingDetailsMember.IsNull())
{
m_pricingDetails.push_back(pricingDetailsMember);
pricingDetailsMember = pricingDetailsMember.NextNode("item");
}
m_pricingDetailsHasBeenSet = true;
}
XmlNode offeringClassNode = resultNode.FirstChild("offeringClass");
if(!offeringClassNode.IsNull())
{
m_offeringClass = OfferingClassTypeMapper::GetOfferingClassTypeForName(StringUtils::Trim(offeringClassNode.GetText().c_str()).c_str());
m_offeringClassHasBeenSet = true;
}
XmlNode scopeNode = resultNode.FirstChild("scope");
if(!scopeNode.IsNull())
{
m_scope = ScopeMapper::GetScopeForName(StringUtils::Trim(scopeNode.GetText().c_str()).c_str());
m_scopeHasBeenSet = true;
}
}
return *this;
}
void ReservedInstancesOffering::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_reservedInstancesOfferingIdHasBeenSet)
{
oStream << location << index << locationValue << ".ReservedInstancesOfferingId=" << StringUtils::URLEncode(m_reservedInstancesOfferingId.c_str()) << "&";
}
if(m_instanceTypeHasBeenSet)
{
oStream << location << index << locationValue << ".InstanceType=" << InstanceTypeMapper::GetNameForInstanceType(m_instanceType) << "&";
}
if(m_availabilityZoneHasBeenSet)
{
oStream << location << index << locationValue << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&";
}
if(m_durationHasBeenSet)
{
oStream << location << index << locationValue << ".Duration=" << m_duration << "&";
}
if(m_usagePriceHasBeenSet)
{
oStream << location << index << locationValue << ".UsagePrice=" << m_usagePrice << "&";
}
if(m_fixedPriceHasBeenSet)
{
oStream << location << index << locationValue << ".FixedPrice=" << m_fixedPrice << "&";
}
if(m_productDescriptionHasBeenSet)
{
oStream << location << index << locationValue << ".ProductDescription=" << RIProductDescriptionMapper::GetNameForRIProductDescription(m_productDescription) << "&";
}
if(m_instanceTenancyHasBeenSet)
{
oStream << location << index << locationValue << ".InstanceTenancy=" << TenancyMapper::GetNameForTenancy(m_instanceTenancy) << "&";
}
if(m_currencyCodeHasBeenSet)
{
oStream << location << index << locationValue << ".CurrencyCode=" << CurrencyCodeValuesMapper::GetNameForCurrencyCodeValues(m_currencyCode) << "&";
}
if(m_offeringTypeHasBeenSet)
{
oStream << location << index << locationValue << ".OfferingType=" << OfferingTypeValuesMapper::GetNameForOfferingTypeValues(m_offeringType) << "&";
}
if(m_recurringChargesHasBeenSet)
{
unsigned recurringChargesIdx = 1;
for(auto& item : m_recurringCharges)
{
Aws::StringStream recurringChargesSs;
recurringChargesSs << location << index << locationValue << ".RecurringCharges." << recurringChargesIdx++;
item.OutputToStream(oStream, recurringChargesSs.str().c_str());
}
}
if(m_marketplaceHasBeenSet)
{
oStream << location << index << locationValue << ".Marketplace=" << std::boolalpha << m_marketplace << "&";
}
if(m_pricingDetailsHasBeenSet)
{
unsigned pricingDetailsIdx = 1;
for(auto& item : m_pricingDetails)
{
Aws::StringStream pricingDetailsSs;
pricingDetailsSs << location << index << locationValue << ".PricingDetailsSet." << pricingDetailsIdx++;
item.OutputToStream(oStream, pricingDetailsSs.str().c_str());
}
}
if(m_offeringClassHasBeenSet)
{
oStream << location << index << locationValue << ".OfferingClass=" << OfferingClassTypeMapper::GetNameForOfferingClassType(m_offeringClass) << "&";
}
if(m_scopeHasBeenSet)
{
oStream << location << index << locationValue << ".Scope=" << ScopeMapper::GetNameForScope(m_scope) << "&";
}
}
void ReservedInstancesOffering::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_reservedInstancesOfferingIdHasBeenSet)
{
oStream << location << ".ReservedInstancesOfferingId=" << StringUtils::URLEncode(m_reservedInstancesOfferingId.c_str()) << "&";
}
if(m_instanceTypeHasBeenSet)
{
oStream << location << ".InstanceType=" << InstanceTypeMapper::GetNameForInstanceType(m_instanceType) << "&";
}
if(m_availabilityZoneHasBeenSet)
{
oStream << location << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&";
}
if(m_durationHasBeenSet)
{
oStream << location << ".Duration=" << m_duration << "&";
}
if(m_usagePriceHasBeenSet)
{
oStream << location << ".UsagePrice=" << m_usagePrice << "&";
}
if(m_fixedPriceHasBeenSet)
{
oStream << location << ".FixedPrice=" << m_fixedPrice << "&";
}
if(m_productDescriptionHasBeenSet)
{
oStream << location << ".ProductDescription=" << RIProductDescriptionMapper::GetNameForRIProductDescription(m_productDescription) << "&";
}
if(m_instanceTenancyHasBeenSet)
{
oStream << location << ".InstanceTenancy=" << TenancyMapper::GetNameForTenancy(m_instanceTenancy) << "&";
}
if(m_currencyCodeHasBeenSet)
{
oStream << location << ".CurrencyCode=" << CurrencyCodeValuesMapper::GetNameForCurrencyCodeValues(m_currencyCode) << "&";
}
if(m_offeringTypeHasBeenSet)
{
oStream << location << ".OfferingType=" << OfferingTypeValuesMapper::GetNameForOfferingTypeValues(m_offeringType) << "&";
}
if(m_recurringChargesHasBeenSet)
{
unsigned recurringChargesIdx = 1;
for(auto& item : m_recurringCharges)
{
Aws::StringStream recurringChargesSs;
recurringChargesSs << location << ".RecurringCharges." << recurringChargesIdx++;
item.OutputToStream(oStream, recurringChargesSs.str().c_str());
}
}
if(m_marketplaceHasBeenSet)
{
oStream << location << ".Marketplace=" << std::boolalpha << m_marketplace << "&";
}
if(m_pricingDetailsHasBeenSet)
{
unsigned pricingDetailsIdx = 1;
for(auto& item : m_pricingDetails)
{
Aws::StringStream pricingDetailsSs;
pricingDetailsSs << location << ".PricingDetailsSet." << pricingDetailsIdx++;
item.OutputToStream(oStream, pricingDetailsSs.str().c_str());
}
}
if(m_offeringClassHasBeenSet)
{
oStream << location << ".OfferingClass=" << OfferingClassTypeMapper::GetNameForOfferingClassType(m_offeringClass) << "&";
}
if(m_scopeHasBeenSet)
{
oStream << location << ".Scope=" << ScopeMapper::GetNameForScope(m_scope) << "&";
}
}
} // namespace Model
} // namespace EC2
} // namespace Aws
|
[
"henso@amazon.com"
] |
henso@amazon.com
|
18d40a79af641da050c4ee3748513d38431bdb83
|
67fc9e51437e351579fe9d2d349040c25936472a
|
/wrappers/8.1.1/vtkEdgeSubdivisionCriterionWrap.h
|
5f7c79641464526f921e4a8fc1265dddf4295274
|
[] |
permissive
|
axkibe/node-vtk
|
51b3207c7a7d3b59a4dd46a51e754984c3302dec
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
refs/heads/master
| 2023-03-05T07:45:45.577220
| 2020-03-30T09:31:07
| 2020-03-30T09:31:07
| 48,490,707
| 6
| 0
|
BSD-3-Clause
| 2022-12-07T20:41:45
| 2015-12-23T12:58:43
|
C++
|
UTF-8
|
C++
| false
| false
| 1,652
|
h
|
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#ifndef NATIVE_EXTENSION_VTK_VTKEDGESUBDIVISIONCRITERIONWRAP_H
#define NATIVE_EXTENSION_VTK_VTKEDGESUBDIVISIONCRITERIONWRAP_H
#include <nan.h>
#include <vtkSmartPointer.h>
#include <vtkEdgeSubdivisionCriterion.h>
#include "vtkObjectWrap.h"
#include "../../plus/plus.h"
class VtkEdgeSubdivisionCriterionWrap : public VtkObjectWrap
{
public:
using Nan::ObjectWrap::Wrap;
static void Init(v8::Local<v8::Object> exports);
static void InitPtpl();
static void ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info);
VtkEdgeSubdivisionCriterionWrap(vtkSmartPointer<vtkEdgeSubdivisionCriterion>);
VtkEdgeSubdivisionCriterionWrap();
~VtkEdgeSubdivisionCriterionWrap( );
static Nan::Persistent<v8::FunctionTemplate> ptpl;
private:
static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void DontPassField(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetNumberOfFields(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetOutputField(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void PassField(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void ResetFieldList(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
#ifdef VTK_NODE_PLUS_VTKEDGESUBDIVISIONCRITERIONWRAP_CLASSDEF
VTK_NODE_PLUS_VTKEDGESUBDIVISIONCRITERIONWRAP_CLASSDEF
#endif
};
#endif
|
[
"axkibe@gmail.com"
] |
axkibe@gmail.com
|
29edfc3213be2179e0d63e1a49bd26fd6840980a
|
bdb6c2c3f863f1c24a84a0f83e662b0965f04dc5
|
/src/gRRF/Data.cpp
|
5144f29ca2f8b178805e0ea2ea14c423ed1b170c
|
[] |
no_license
|
geovens/gRRF
|
1093878af245819e29ea043d24504bf75c6ec05a
|
d4540777e45c68a12b993a8c0777797bc5692615
|
refs/heads/master
| 2020-03-15T03:23:18.899411
| 2018-08-30T07:02:20
| 2018-08-30T07:02:20
| 131,940,984
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,698
|
cpp
|
#include "Data.h"
#include "stdafx.h"
Data::Data()
{
Features = NULL;
Values = NULL;
ReachedNodes = NULL;
Predictions = NULL;
}
Data* Data::GetSample(int index, int* local_index_out)
{
*local_index_out = index;
return this;
}
featuretype* Data::GetFeatureP(int index, featuretype* abc)
{
return Features + index * D;
}
void Data::GetFeature(int index, featuretype* abc, featuretype* feature_out)
{
memcpy(feature_out, Features + index * D, sizeof(featuretype)* D);
}
valuetype* Data::GetValueP(int index)
{
return Values + index;
}
void Data::GetFeatureValue(int index, featuretype* abc, featuretype* feature_out, valuetype* value_out)
{
/*
memcpy(feature_out, Features + index * D, sizeof(featuretype) * D);
*label_out = *(Values + index);
*/
GetFeature(index, abc, feature_out);
GetValue(index, value_out);
}
void Data::GetValue(int index, valuetype* value_out)
{
*value_out = *(Values + index);
}
int Data::SetReachedNode(int index, Node* node)
{
if (ReachedNodes == NULL)
ReachedNodes = new Node*[N];
ReachedNodes[index] = node;
return 0;
}
Node* Data::GetReachedNode(int index)
{
if (ReachedNodes == NULL)
return NULL;
return ReachedNodes[index];
}
int Data::SetPrediction(int index, valuetype prediction)
{
if (Predictions == NULL)
Predictions = new valuetype[N];
Predictions[index] = prediction;
return 0;
}
valuetype Data::GetPrediction(int index)
{
if (Predictions == NULL)
return -99;
return Predictions[index];
}
int Data::Release()
{
if (Features != NULL)
delete Features;
if (Values != NULL)
delete Values;
if (ReachedNodes != NULL)
delete ReachedNodes;
if (Predictions != NULL)
delete Predictions;
delete this;
return 0;
}
|
[
"hi@geovens.name"
] |
hi@geovens.name
|
68dabbe0b05f88e6a19e64b086437daf82e5b1ff
|
e274ecc01c1828a796fc727426419809431a8896
|
/camerapreview/src/main/cpp/libcommon/message_queue/message_queue.h
|
dc52089ba28e47a69699794c10661547c07ea9b4
|
[] |
no_license
|
LymanYe/FFmpeg
|
39cc528d45e08fbf1caf33fc34c43672175236ba
|
c7a310a35506f89766804c92d9ed8bc8244dd938
|
refs/heads/master
| 2020-03-22T05:09:00.478217
| 2018-08-10T06:41:21
| 2018-08-10T06:41:21
| 139,545,546
| 6
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,227
|
h
|
#ifndef VIDEO_COMMON_MESSAGE_QUEUE_H
#define VIDEO_COMMON_MESSAGE_QUEUE_H
#include "../libcommon/CommonTools.h"
#include <pthread.h>
#define MESSAGE_QUEUE_LOOP_QUIT_FLAG 19900909
class Handler;
class Message {
private:
int what;
int arg1;
int arg2;
void* obj;
public:
Message();
Message(int what);
Message(int what, int arg1, int arg2);
Message(int what, void* obj);
Message(int what, int arg1, int arg2, void* obj);
~Message();
int execute();
int getWhat(){
return what;
};
int getArg1(){
return arg1;
};
int getArg2(){
return arg2;
};
void* getObj(){
return obj;
};
Handler* handler;
};
typedef struct MessageNode {
Message *msg;
struct MessageNode *next;
MessageNode(){
msg = NULL;
next = NULL;
}
} MessageNode;
class MessageQueue {
private:
MessageNode* mFirst;
MessageNode* mLast;
int mNbPackets;
bool mAbortRequest;
pthread_mutex_t mLock;
pthread_cond_t mCondition;
const char* queueName;
public:
MessageQueue();
MessageQueue(const char* queueNameParam);
~MessageQueue();
void init();
void flush();
int enqueueMessage(Message* msg);
int dequeueMessage(Message **msg, bool block);
int size();
void abort();
};
#endif // VIDEO_COMMON_MESSAGE_QUEUE_H
|
[
"lymanye@gmail.com"
] |
lymanye@gmail.com
|
b922819c100c6076e085765a5dcf9d1dfbd459fa
|
e9f82e2ba230c31be4e624c94c6399d1f77010f7
|
/Shovel Knight_Fin/Shovel Knight/Shovel Knight.cpp
|
6d168480d77ce2fdffe46af630cfde20025bf587
|
[] |
no_license
|
beny91/Get-a-time
|
475d1160b066831846eb84633037a5d5262c1097
|
5ca822a9d86265ba31f558e57e17c9ced76a01e3
|
refs/heads/master
| 2020-04-05T14:02:42.666752
| 2017-07-06T23:00:15
| 2017-07-06T23:00:15
| 94,745,144
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 5,469
|
cpp
|
// Shovel Knight.cpp : 응용 프로그램에 대한 진입점을 정의합니다.
//
#include "stdafx.h"
#include "Shovel Knight.h"
#include "maingame.h"
#define MAX_LOADSTRING 100
// 전역 변수:
HINSTANCE hInst; // 현재 인스턴스입니다.
TCHAR szTitle[MAX_LOADSTRING]; // 제목 표시줄 텍스트입니다.
TCHAR szWindowClass[MAX_LOADSTRING]; // 기본 창 클래스 이름입니다.
HWND g_hWnd;
// 이 코드 모듈에 들어 있는 함수의 정방향 선언입니다.
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
//_CrtSetBreakAlloc(175);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: 여기에 코드를 입력합니다.
MSG msg;
HACCEL hAccelTable;
// 전역 문자열을 초기화합니다.
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_SHOVELKNIGHT, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// 응용 프로그램 초기화를 수행합니다.
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SHOVELKNIGHT));
msg.message = WM_NULL;
CMainGame MainGame;
MainGame.Initialize();
DWORD dwTime = GetTickCount();
while (msg.message != WM_QUIT)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
if(dwTime + 30 < GetTickCount())
{
dwTime = GetTickCount();
MainGame.Progress();
MainGame.Render();
}
}
}
//// 기본 메시지 루프입니다.
//while (GetMessage(&msg, NULL, 0, 0))
//{
// if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
// {
// TranslateMessage(&msg);
// DispatchMessage(&msg);
// }
//}
// _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
return (int) msg.wParam;
}
//
// 함수: MyRegisterClass()
//
// 목적: 창 클래스를 등록합니다.
//
// 설명:
//
// Windows 95에서 추가된 'RegisterClassEx' 함수보다 먼저
// 해당 코드가 Win32 시스템과 호환되도록
// 하려는 경우에만 이 함수를 사용합니다. 이 함수를 호출해야
// 해당 응용 프로그램에 연결된
// '올바른 형식의' 작은 아이콘을 가져올 수 있습니다.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SHOVELKNIGHT));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// 함수: InitInstance(HINSTANCE, int)
//
// 목적: 인스턴스 핸들을 저장하고 주 창을 만듭니다.
//
// 설명:
//
// 이 함수를 통해 인스턴스 핸들을 전역 변수에 저장하고
// 주 프로그램 창을 만든 다음 표시합니다.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // 인스턴스 핸들을 전역 변수에 저장합니다.
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, g_iWINCX, g_iWINCY, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
g_hWnd = hWnd;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// 함수: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 목적: 주 창의 메시지를 처리합니다.
//
// WM_COMMAND - 응용 프로그램 메뉴를 처리합니다.
// WM_PAINT - 주 창을 그립니다.
// WM_DESTROY - 종료 메시지를 게시하고 반환합니다.
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_KEYDOWN:
switch(wParam)
{
case VK_ESCAPE:
DestroyWindow(hWnd);
break;
}
break;
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// 메뉴의 선택 영역을 구문 분석합니다.
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: 여기에 그리기 코드를 추가합니다.
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// 정보 대화 상자의 메시지 처리기입니다.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
|
[
"sosik4@gmail.com"
] |
sosik4@gmail.com
|
e7e0921881b753e5162699969461b6f3d499e478
|
2affdd1d5a6ba682076925e32f48566ee16ee413
|
/src/thn9732_Main_Menu.h
|
fb611f22120cc78921603fc373677fbbc13987d4
|
[] |
no_license
|
thtnguyen/Library-System
|
211a05552207e1306b161e70e13d5a6c0fdd277a
|
c4703ebbe595e92e1f14b756469c8f9193946307
|
refs/heads/master
| 2020-04-01T18:18:33.568137
| 2018-10-17T15:58:49
| 2018-10-17T15:58:49
| 153,484,069
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 684
|
h
|
#ifndef MAIN_MENU_H
#define MAIN_MENU_H
#include <gtkmm.h>
#include "thn9732_Controller.h"
class Main_Menu : public Gtk::Window {
public:
Main_Menu(Library& l, Controller& c);
virtual ~Main_Menu();
protected:
Gtk::Box* vbox;
void create_lbrn_clicked();
void load_data_clicked();
void save_data_clicked();
void default_save_clicked();
void default_load_clicked();
void create_media_clicked();
void create_bundle_clicked();
void check_out_list();
void check_out_clicked();
void check_in_clicked();
void create_customer_clicked();
void view_catalog_clicked();
void pay_balance_clicked();
void on_exit_clicked();
Library& lib;
Controller& controller;
};
#endif
|
[
"teresa@uta.edu"
] |
teresa@uta.edu
|
6a8df83fe6e3fe315e55d3ee6a7d6cc57fa65042
|
b1aa27b66c3c4136ad09470f1bbe065674475ac5
|
/Engine/Renderer/Gfx/include/GfxSampler.h
|
3d0796bdeb8e1bcd54409c62b1925576dd09b72b
|
[
"BSD-2-Clause"
] |
permissive
|
LiangYue1981816/AresEngine
|
489ab0ed977c36327343797dd1499f56f434e06f
|
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
|
refs/heads/master
| 2021-06-27T06:18:17.253841
| 2020-05-15T04:37:02
| 2020-05-15T04:37:02
| 148,959,938
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 243
|
h
|
#pragma once
#include "PreHeader.h"
class CALL_API CGfxSampler
{
public:
CGfxSampler(GfxFilter minFilter, GfxFilter magFilter, GfxSamplerMipmapMode mipmapMode, GfxSamplerAddressMode addressMode)
{
}
virtual ~CGfxSampler(void)
{
}
};
|
[
"LiangYue1981816@Hotmail.com"
] |
LiangYue1981816@Hotmail.com
|
50e6afc79ace18d6a986949e40820085b4225fae
|
78f459b98a8f4517263cbe8df25552bd14e2590d
|
/src/main/include/config/TestConfig.hpp
|
f8eac664d9a4c60396eccfa40731ee74da277b08
|
[] |
no_license
|
FRC-Team3538/FRC2020MotionProfiling
|
6f2990b7642f0e3c0466146d2998aaa9d8c1bda8
|
a7d8b54c798133237473428a6d808de472766ad1
|
refs/heads/master
| 2023-03-10T00:26:34.457647
| 2020-10-27T05:19:55
| 2020-10-27T05:19:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 308
|
hpp
|
#pragma once
#include "ctre/Phoenix.h"
#include "lib/ctreJsonSerde.hpp"
#include "lib/json.hpp"
class TestConfig
{
public:
int a = 0;
ctre::phoenix::CustomParamConfiguration cpc;
ctre::phoenix::motorcontrol::can::TalonFXConfiguration fx;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(TestConfig, a, cpc, fx)
|
[
"jlmcmchl@gmail.com"
] |
jlmcmchl@gmail.com
|
965d9088ac71d561543b8fba8526381a2308dcd6
|
7801cc1335cb60500b76bbb247b69ddf5e9b82a4
|
/osrm/inc/engine/map_matching/hidden_markov_model.hpp
|
e4281a917ff7e20e03fd4be723210dd1daed004b
|
[] |
no_license
|
bblu/osrm-core
|
412f733dcc415f6e94280ddf1df73ac3dd09a477
|
a696cd9d6770c30240c87830613fce5c7e54d008
|
refs/heads/master
| 2020-12-31T04:55:51.660185
| 2016-04-15T03:48:41
| 2016-04-15T03:48:41
| 56,051,863
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,092
|
hpp
|
#ifndef HIDDEN_MARKOV_MODEL
#define HIDDEN_MARKOV_MODEL
#include "util/integer_range.hpp"
#include <boost/assert.hpp>
#include <boost/math/constants/constants.hpp>
#include <cmath>
#include <limits>
#include <vector>
namespace osrm
{
namespace engine
{
namespace map_matching
{
static const double log_2_pi = std::log(2. * boost::math::constants::pi<double>());
static const double IMPOSSIBLE_LOG_PROB = -std::numeric_limits<double>::infinity();
static const double MINIMAL_LOG_PROB = std::numeric_limits<double>::lowest();
static const std::size_t INVALID_STATE = std::numeric_limits<std::size_t>::max();
// closures to precompute log -> only simple floating point operations
struct EmissionLogProbability
{
double sigma_z;
double log_sigma_z;
EmissionLogProbability(const double sigma_z) : sigma_z(sigma_z), log_sigma_z(std::log(sigma_z))
{
}
double operator()(const double distance) const
{
return -0.5 * (log_2_pi + (distance / sigma_z) * (distance / sigma_z)) - log_sigma_z;
}
};
struct TransitionLogProbability
{
double beta;
double log_beta;
TransitionLogProbability(const double beta) : beta(beta), log_beta(std::log(beta)) {}
double operator()(const double d_t) const { return -log_beta - d_t / beta; }
};
template <class CandidateLists> struct HiddenMarkovModel
{
std::vector<std::vector<double>> viterbi;
std::vector<std::vector<std::pair<unsigned, unsigned>>> parents;
std::vector<std::vector<float>> path_lengths;
std::vector<std::vector<bool>> pruned;
std::vector<std::vector<bool>> suspicious;
std::vector<bool> breakage;
const CandidateLists &candidates_list;
const EmissionLogProbability &emission_log_probability;
HiddenMarkovModel(const CandidateLists &candidates_list,
const EmissionLogProbability &emission_log_probability)
: breakage(candidates_list.size()), candidates_list(candidates_list),
emission_log_probability(emission_log_probability)
{
viterbi.resize(candidates_list.size());
parents.resize(candidates_list.size());
path_lengths.resize(candidates_list.size());
suspicious.resize(candidates_list.size());
pruned.resize(candidates_list.size());
breakage.resize(candidates_list.size());
for (const auto i : util::irange<std::size_t>(0u, candidates_list.size()))
{
const auto &num_candidates = candidates_list[i].size();
// add empty vectors
if (num_candidates > 0)
{
viterbi[i].resize(num_candidates);
parents[i].resize(num_candidates);
path_lengths[i].resize(num_candidates);
suspicious[i].resize(num_candidates);
pruned[i].resize(num_candidates);
}
}
clear(0);
}
void clear(std::size_t initial_timestamp)
{
BOOST_ASSERT(viterbi.size() == parents.size() && parents.size() == path_lengths.size() &&
path_lengths.size() == pruned.size() && pruned.size() == breakage.size());
for (const auto t : util::irange(initial_timestamp, viterbi.size()))
{
std::fill(viterbi[t].begin(), viterbi[t].end(), IMPOSSIBLE_LOG_PROB);
std::fill(parents[t].begin(), parents[t].end(), std::make_pair(0u, 0u));
std::fill(path_lengths[t].begin(), path_lengths[t].end(), 0);
std::fill(suspicious[t].begin(), suspicious[t].end(), true);
std::fill(pruned[t].begin(), pruned[t].end(), true);
}
std::fill(breakage.begin() + initial_timestamp, breakage.end(), true);
}
std::size_t initialize(std::size_t initial_timestamp)
{
auto num_points = candidates_list.size();
do
{
BOOST_ASSERT(initial_timestamp < num_points);
for (const auto s : util::irange<std::size_t>(0u, viterbi[initial_timestamp].size()))
{
viterbi[initial_timestamp][s] =
emission_log_probability(candidates_list[initial_timestamp][s].distance);
parents[initial_timestamp][s] = std::make_pair(initial_timestamp, s);
pruned[initial_timestamp][s] = viterbi[initial_timestamp][s] < MINIMAL_LOG_PROB;
suspicious[initial_timestamp][s] = false;
breakage[initial_timestamp] =
breakage[initial_timestamp] && pruned[initial_timestamp][s];
}
++initial_timestamp;
} while (initial_timestamp < num_points && breakage[initial_timestamp - 1]);
if (initial_timestamp >= num_points)
{
return INVALID_STATE;
}
BOOST_ASSERT(initial_timestamp > 0);
--initial_timestamp;
BOOST_ASSERT(breakage[initial_timestamp] == false);
return initial_timestamp;
}
};
}
}
}
#endif // HIDDEN_MARKOV_MODEL
|
[
"gmwblu@gmail.com"
] |
gmwblu@gmail.com
|
a7a2f6d38e8a8f8186745b8d070b8e1ba94f08f1
|
672881ca0ff84aff973b90c53c54d7a608ac57ad
|
/src/Musings/Mechanisms/LogWeaver.h
|
278127d07ce79956607b785b33b2f6979362e6ac
|
[] |
no_license
|
kieransimkin/TangleNet-micro
|
03654983f92b31b2f99e505a1c5be44e0af3ce9f
|
34bde2af3b2770ef16a46db2d97c8f019950c720
|
refs/heads/master
| 2021-01-10T08:23:03.150174
| 2016-04-05T04:23:49
| 2016-04-05T04:23:49
| 54,948,771
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 416
|
h
|
#include "Print.h"
#include <stddef.h>
#include <stdarg.h>
#define PRINTF_BUF 80 // define the tmp buffer size (change if desired)
class LogWeaver : public Print {
virtual size_t write(uint8_t);
public:
void printf(const char *format, ...);
#ifdef F // check to see if F() macro is available
void printf(const __FlashStringHelper *format, ...);
#endif
void vli_print(uint8_t *vli, unsigned int size);
};
|
[
"kieran@slinq.com"
] |
kieran@slinq.com
|
e1653b072c64c3cb62a871e3305449037644b7b2
|
6736f139a3c166b3dcb6ca655e3c26e4adfd7252
|
/daydream_viewer/app/src/main/jni/renderer.cc
|
1ee10fc6028b7f06f8c5e591fb42f48e600c8079
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Libpng",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
alexey-odintsov/tango
|
bb67f7b3739884424fbcfc1396f3a51f09e09075
|
3555d1f52e9ac1b078b3304a789a446d92d7ac4c
|
refs/heads/master
| 2021-01-01T19:12:43.266094
| 2017-07-22T08:04:54
| 2017-07-22T08:04:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,900
|
cc
|
#include "renderer.h" // NOLINT
#include "shaders.h" // NOLINT
#include "data/file3d.h"
#include <android/log.h>
#include <assert.h>
#include <stdlib.h>
#include <cmath>
#include <random>
namespace {
static const float kReticleDistance = 3.0f;
static const int kCoordsPerVertex = 3;
static const uint64_t kPredictionTimeWithoutVsyncNanos = 50000000;
static const float kAngleLimit = 0.12f;
static const float kPitchLimit = 0.12f;
static const float kYawLimit = 0.12f;
float reticle_vertices_[] = {
-1.f, 1.f, 0.0f,
-1.f, -1.f, 0.0f,
1.f, 1.f, 0.0f,
-1.f, -1.f, 0.0f,
1.f, -1.f, 0.0f,
1.f, 1.f, 0.0f,
};
static std::array<float, 16> MatrixToGLArray(const gvr::Mat4f& matrix) {
std::array<float, 16> result;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
result[j * 4 + i] = matrix.m[i][j];
}
}
return result;
}
static std::array<float, 4> MatrixVectorMul(const gvr::Mat4f& matrix, const std::array<float, 4>& vec) {
std::array<float, 4> result;
for (int i = 0; i < 4; ++i) {
result[i] = 0;
for (int k = 0; k < 4; ++k) {
result[i] += matrix.m[i][k] * vec[k];
}
}
return result;
}
static gvr::Mat4f MatrixMul(const gvr::Mat4f& matrix1, const gvr::Mat4f& matrix2) {
gvr::Mat4f result;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
result.m[i][j] = 0.0f;
for (int k = 0; k < 4; ++k) {
result.m[i][j] += matrix1.m[i][k] * matrix2.m[k][j];
}
}
}
return result;
}
static std::array<float, 3> Vec4ToVec3(const std::array<float, 4>& vec) {
return {vec[0], vec[1], vec[2]};
}
static gvr::Mat4f PerspectiveMatrixFromView(const gvr::Rectf& fov, float z_near, float z_far) {
gvr::Mat4f result;
const float x_left = -std::tan(fov.left * M_PI / 180.0f) * z_near;
const float x_right = std::tan(fov.right * M_PI / 180.0f) * z_near;
const float y_bottom = -std::tan(fov.bottom * M_PI / 180.0f) * z_near;
const float y_top = std::tan(fov.top * M_PI / 180.0f) * z_near;
const float zero = 0.0f;
assert(x_left < x_right && y_bottom < y_top && z_near < z_far && z_near > zero && z_far > zero);
const float X = (2 * z_near) / (x_right - x_left);
const float Y = (2 * z_near) / (y_top - y_bottom);
const float A = (x_right + x_left) / (x_right - x_left);
const float B = (y_top + y_bottom) / (y_top - y_bottom);
const float C = (z_near + z_far) / (z_near - z_far);
const float D = (2 * z_near * z_far) / (z_near - z_far);
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
result.m[i][j] = 0.0f;
}
}
result.m[0][0] = X;
result.m[0][2] = A;
result.m[1][1] = Y;
result.m[1][2] = B;
result.m[2][2] = C;
result.m[2][3] = D;
result.m[3][2] = -1;
return result;
}
static gvr::Rectf ModulateRect(const gvr::Rectf& rect, float width, float height) {
gvr::Rectf result = {rect.left * width, rect.right * width, rect.bottom * height, rect.top * height};
return result;
}
static gvr::Recti CalculatePixelSpaceRect(const gvr::Sizei& texture_size, const gvr::Rectf& texture_rect) {
const float width = static_cast<float>(texture_size.width);
const float height = static_cast<float>(texture_size.height);
const gvr::Rectf rect = ModulateRect(texture_rect, width, height);
const gvr::Recti result = {
static_cast<int>(rect.left), static_cast<int>(rect.right),
static_cast<int>(rect.bottom), static_cast<int>(rect.top)};
return result;
}
static gvr::Sizei HalfPixelCount(const gvr::Sizei& in) {
// Scale each dimension by sqrt(2)/2 ~= 7/10ths.
gvr::Sizei out;
out.width = (7 * in.width) / 10;
out.height = (7 * in.height) / 10;
return out;
}
static gvr::Mat4f ControllerQuatToMatrix(const gvr::ControllerQuat& quat) {
gvr::Mat4f result;
const float x = quat.qx;
const float x2 = quat.qx * quat.qx;
const float y = quat.qy;
const float y2 = quat.qy * quat.qy;
const float z = quat.qz;
const float z2 = quat.qz * quat.qz;
const float w = quat.qw;
const float xy = quat.qx * quat.qy;
const float xz = quat.qx * quat.qz;
const float xw = quat.qx * quat.qw;
const float yz = quat.qy * quat.qz;
const float yw = quat.qy * quat.qw;
const float zw = quat.qz * quat.qw;
const float m11 = 1.0f - 2.0f * y2 - 2.0f * z2;
const float m12 = 2.0f * (xy - zw);
const float m13 = 2.0f * (xz + yw);
const float m21 = 2.0f * (xy + zw);
const float m22 = 1.0f - 2.0f * x2 - 2.0f * z2;
const float m23 = 2.0f * (yz - xw);
const float m31 = 2.0f * (xz - yw);
const float m32 = 2.0f * (yz + xw);
const float m33 = 1.0f - 2.0f * x2 - 2.0f * y2;
return {{{m11, m12, m13, 0.0f},
{m21, m22, m23, 0.0f},
{m31, m32, m33, 0.0f},
{0.0f, 0.0f, 0.0f, 1.0f}}};
}
} // anonymous namespace
Renderer::Renderer(gvr_context* gvr_context, std::string filename)
: gvr_api_(gvr::GvrApi::WrapNonOwned(gvr_context)),
viewport_left_(gvr_api_->CreateBufferViewport()),
viewport_right_(gvr_api_->CreateBufferViewport()),
reticle_render_size_{128, 128},
gvr_controller_api_(nullptr),
gvr_viewer_type_(gvr_api_->GetViewerType()) {
ResumeControllerApiAsNeeded();
if (gvr_viewer_type_ == GVR_VIEWER_TYPE_CARDBOARD) {
LOGI("Viewer type: CARDBOARD");
} else if (gvr_viewer_type_ == GVR_VIEWER_TYPE_DAYDREAM) {
LOGI("Viewer type: DAYDREAM");
} else {
LOGE("Unexpected viewer type.");
}
oc::File3d io(filename, false);
textured_ = io.GetType() == oc::OBJ;
io.ReadModel(20000, static_meshes_);
}
Renderer::~Renderer() {
}
void Renderer::InitializeGl() {
gvr_api_->InitializeGl();
int index = textured_ ? 0 : 1;
const int vertex_shader = LoadGLShader(GL_VERTEX_SHADER, &kTextureVertexShaders[index]);
const int fragment_shader = LoadGLShader(GL_FRAGMENT_SHADER, &kTextureFragmentShaders[index]);
const int pass_through_shader = LoadGLShader(GL_FRAGMENT_SHADER, &kPassthroughFragmentShaders[0]);
const int reticle_vertex_shader = LoadGLShader(GL_VERTEX_SHADER, &kReticleVertexShaders[0]);
const int reticle_fragment_shader = LoadGLShader(GL_FRAGMENT_SHADER, &kReticleFragmentShaders[0]);
model_program_ = glCreateProgram();
glAttachShader(model_program_, vertex_shader);
glAttachShader(model_program_, fragment_shader);
glLinkProgram(model_program_);
glUseProgram(model_program_);
model_position_param_ = glGetAttribLocation(model_program_, "a_Position");
if (textured_)
model_uv_param_ = glGetAttribLocation(model_program_, "a_UV");
else
model_uv_param_ = glGetAttribLocation(model_program_, "a_Color");
model_modelview_projection_param_ = glGetUniformLocation(model_program_, "u_MVP");
model_translatex_param_ = glGetUniformLocation(model_program_, "u_X");
model_translatey_param_ = glGetUniformLocation(model_program_, "u_Y");
model_translatez_param_ = glGetUniformLocation(model_program_, "u_Z");
reticle_program_ = glCreateProgram();
glAttachShader(reticle_program_, reticle_vertex_shader);
glAttachShader(reticle_program_, reticle_fragment_shader);
glLinkProgram(reticle_program_);
glUseProgram(reticle_program_);
reticle_position_param_ = glGetAttribLocation(reticle_program_, "a_Position");
reticle_modelview_projection_param_ = glGetUniformLocation(reticle_program_, "u_MVP");
// Object first appears directly in front of user.
model_model_ = {{{100.0f, 0.0f, 0.0f, 0.0f},
{0.0f, 100.0f, 0.0f, 0.0},
{0.0f, 0.0f, 100.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 1.0f}}};
const float rs = 0.04f; // Reticle scale.
model_reticle_ = {{{rs, 0.0f, 0.0f, 0.0f},
{0.0f, rs, 0.0f, 0.0f},
{0.0f, 0.0f, rs, -kReticleDistance},
{0.0f, 0.0f, 0.0f, 1.0f}}};
// Because we are using 2X MSAA, we can render to half as many pixels and
// achieve similar quality.
render_size_ = HalfPixelCount(gvr_api_->GetMaximumEffectiveRenderTargetSize());
std::vector<gvr::BufferSpec> specs;
specs.push_back(gvr_api_->CreateBufferSpec());
specs[0].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);
specs[0].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_16);
specs[0].SetSamples(2);
specs[0].SetSize(render_size_);
specs.push_back(gvr_api_->CreateBufferSpec());
specs[1].SetSize(reticle_render_size_);
specs[1].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);
specs[1].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_NONE);
specs[1].SetSamples(1);
swapchain_.reset(new gvr::SwapChain(gvr_api_->CreateSwapChain(specs)));
viewport_list_.reset(
new gvr::BufferViewportList(gvr_api_->CreateEmptyBufferViewportList()));
}
void Renderer::ResumeControllerApiAsNeeded() {
switch (gvr_viewer_type_) {
case GVR_VIEWER_TYPE_CARDBOARD:
gvr_controller_api_.reset();
break;
case GVR_VIEWER_TYPE_DAYDREAM:
if (!gvr_controller_api_) {
// Initialized controller api.
gvr_controller_api_.reset(new gvr::ControllerApi);
gvr_controller_api_->Init(gvr::ControllerApi::DefaultOptions(), gvr_api_->cobj());
}
gvr_controller_api_->Resume();
break;
default:
LOGE("unexpected viewer type.");
break;
}
}
void Renderer::ProcessControllerInput() {
const int old_status = gvr_controller_state_.GetApiStatus();
const int old_connection_state = gvr_controller_state_.GetConnectionState();
// Read current controller state.
gvr_controller_state_.Update(*gvr_controller_api_);
if (gvr_controller_state_.GetApiStatus() != old_status ||
gvr_controller_state_.GetConnectionState() != old_connection_state) {
}
// Trigger click event if app/click button is clicked.
if (gvr_controller_state_.GetButtonDown(GVR_CONTROLLER_BUTTON_APP) ||
gvr_controller_state_.GetButtonDown(GVR_CONTROLLER_BUTTON_CLICK)) {
OnTriggerEvent();
}
}
void Renderer::DrawFrame() {
if (gvr_viewer_type_ == GVR_VIEWER_TYPE_DAYDREAM) {
ProcessControllerInput();
}
PrepareFramebuffer();
gvr::Frame frame = swapchain_->AcquireFrame();
// A client app does its rendering here.
gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow();
target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos;
gvr::BufferViewport* viewport[2] = { &viewport_left_, &viewport_right_, };
head_view_ = gvr_api_->GetHeadSpaceFromStartSpaceRotation(target_time);
viewport_list_->SetToRecommendedBufferViewports();
gvr::BufferViewport reticle_viewport = gvr_api_->CreateBufferViewport();
reticle_viewport.SetSourceBufferIndex(1);
reticle_viewport.SetReprojection(GVR_REPROJECTION_NONE);
const gvr_rectf fullscreen = { 0, 1, 0, 1 };
reticle_viewport.SetSourceUv(fullscreen);
gvr::Mat4f controller_matrix = ControllerQuatToMatrix(gvr_controller_state_.GetOrientation());
model_cursor_ = MatrixMul(controller_matrix, model_reticle_);
gvr::Mat4f eye_views[2];
for (int eye = 0; eye < 2; ++eye) {
const gvr::Eye gvr_eye = eye == 0 ? GVR_LEFT_EYE : GVR_RIGHT_EYE;
const gvr::Mat4f eye_from_head = gvr_api_->GetEyeFromHeadMatrix(gvr_eye);
eye_views[eye] = MatrixMul(eye_from_head, head_view_);
viewport_list_->GetBufferViewport(eye, viewport[eye]);
reticle_viewport.SetTransform(MatrixMul(eye_from_head, model_reticle_));
reticle_viewport.SetTargetEye(gvr_eye);
viewport_list_->SetBufferViewport(2 + eye, reticle_viewport);
modelview_model_[eye] = MatrixMul(eye_views[eye], model_model_);
const gvr_rectf fov = viewport[eye]->GetSourceFov();
const gvr::Mat4f perspective = PerspectiveMatrixFromView(fov, 1, 10000);
modelview_projection_model_[eye] = MatrixMul(perspective, modelview_model_[eye]);
modelview_projection_cursor_[eye] = MatrixMul(perspective, MatrixMul(eye_views[eye], model_cursor_));
}
cur_position = 0.95f * cur_position + 0.05f * dst_position;
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_BLEND);
// Draw the world.
frame.BindBuffer(0);
glClearColor(0.1f, 0.1f, 0.1f, 0.5f); // Dark background so text shows up.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
DrawWorld(kLeftView);
DrawWorld(kRightView);
frame.Unbind();
frame.BindBuffer(1);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Transparent background.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (gvr_viewer_type_ == GVR_VIEWER_TYPE_CARDBOARD)
DrawCardboardReticle();
frame.Unbind();
// Submit frame.
frame.Submit(*viewport_list_, head_view_);
}
void Renderer::PrepareFramebuffer() {
// Because we are using 2X MSAA, we can render to half as many pixels and
// achieve similar quality.
const gvr::Sizei recommended_size = HalfPixelCount(gvr_api_->GetMaximumEffectiveRenderTargetSize());
if (render_size_.width != recommended_size.width || render_size_.height != recommended_size.height) {
// We need to resize the framebuffer.
swapchain_->ResizeBuffer(0, recommended_size);
render_size_ = recommended_size;
}
}
void Renderer::OnTriggerEvent() {
glm::mat4 left = glm::make_mat4(MatrixToGLArray(modelview_model_[kLeftView]).data());
glm::mat4 right = glm::make_mat4(MatrixToGLArray(modelview_model_[kRightView]).data());
glm::vec4 lv = glm::vec4(0, 0, 1, 1) * left;
glm::vec4 rv = glm::vec4(0, 0, 1, 1) * right;
lv /= fabs(lv.w);
rv /= fabs(rv.w);
dst_position += (lv + rv) * 0.0025f;
}
void Renderer::OnPause() {
gvr_api_->PauseTracking();
if (gvr_controller_api_) gvr_controller_api_->Pause();
}
void Renderer::OnResume() {
gvr_api_->ResumeTracking();
gvr_api_->RefreshViewerProfile();
gvr_viewer_type_ = gvr_api_->GetViewerType();
ResumeControllerApiAsNeeded();
}
int Renderer::LoadGLShader(int type, const char** shadercode) {
int shader = glCreateShader(type);
glShaderSource(shader, 1, shadercode, nullptr);
glCompileShader(shader);
const unsigned int BUFFER_SIZE = 512;
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
GLsizei length = 0;
glGetShaderInfoLog(shader, BUFFER_SIZE, &length, buffer);
if (length > 0)
LOGI("GLSL compile log: %s\n%s", buffer, *shadercode);
// Get the compilation status.
int compileStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);
// If the compilation failed, delete the shader.
if (compileStatus == 0) {
glDeleteShader(shader);
shader = 0;
}
return shader;
}
void Renderer::DrawWorld(ViewType view) {
const gvr::BufferViewport& viewport = view == kLeftView ? viewport_left_ : viewport_right_;
const gvr::Recti pixel_rect = CalculatePixelSpaceRect(render_size_, viewport.GetSourceUv());
glViewport(pixel_rect.left, pixel_rect.bottom,
pixel_rect.right - pixel_rect.left,
pixel_rect.top - pixel_rect.bottom);
DrawModel(view);
if (gvr_viewer_type_ == GVR_VIEWER_TYPE_DAYDREAM)
DrawDaydreamCursor(view);
}
void Renderer::DrawModel(ViewType view) {
glUseProgram(model_program_);
float* matrix = MatrixToGLArray(modelview_projection_model_[view]).data();
glUniform1f(model_translatex_param_, cur_position.x);
glUniform1f(model_translatey_param_, cur_position.y);
glUniform1f(model_translatez_param_, cur_position.z);
glUniformMatrix4fv(model_modelview_projection_param_, 1, GL_FALSE, MatrixToGLArray(modelview_projection_model_[view]).data());
glEnableVertexAttribArray(model_position_param_);
for(oc::Mesh& mesh : static_meshes_) {
if (mesh.image && (mesh.texture == -1)) {
GLuint textureID;
glGenTextures(1, &textureID);
mesh.texture = textureID;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, mesh.image->GetWidth(), mesh.image->GetHeight(),
0, GL_RGB, GL_UNSIGNED_BYTE, mesh.image->GetData());
}
glVertexAttribPointer(model_position_param_, 3, GL_FLOAT, false, 0, mesh.vertices.data());
if (textured_)
{
glBindTexture(GL_TEXTURE_2D, (unsigned int)mesh.texture);
glVertexAttribPointer(model_uv_param_, 2, GL_FLOAT, false, 0, mesh.uv.data());
glDrawArrays(GL_TRIANGLES, 0, mesh.vertices.size());
}
else
{
glVertexAttribPointer(model_uv_param_, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, mesh.colors.data());
glDrawArrays(GL_TRIANGLES, 0, mesh.vertices.size());
}
}
glDisableVertexAttribArray(model_position_param_);
}
void Renderer::DrawDaydreamCursor(ViewType view) {
glUseProgram(reticle_program_);
glUniformMatrix4fv(reticle_modelview_projection_param_, 1, GL_FALSE, MatrixToGLArray(modelview_projection_cursor_[view]).data());
glVertexAttribPointer(reticle_position_param_, kCoordsPerVertex, GL_FLOAT, false, 0, reticle_vertices_);
glEnableVertexAttribArray(reticle_position_param_);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(reticle_position_param_);
}
void Renderer::DrawCardboardReticle() {
glViewport(0, 0, reticle_render_size_.width, reticle_render_size_.height);
glUseProgram(reticle_program_);
const gvr::Mat4f uniform_matrix = {{{1.f, 0.f, 0.f, 0.f},
{0.f, 1.f, 0.f, 0.f},
{0.f, 0.f, 1.f, 0.f},
{0.f, 0.f, 0.f, 1.f}}};
glUniformMatrix4fv(reticle_modelview_projection_param_, 1, GL_FALSE, MatrixToGLArray(uniform_matrix).data());
glVertexAttribPointer(reticle_position_param_, kCoordsPerVertex, GL_FLOAT, false, 0, reticle_vertices_);
glEnableVertexAttribArray(reticle_position_param_);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(reticle_position_param_);
}
|
[
"lubos@mapfactor.com"
] |
lubos@mapfactor.com
|
28d15e2cf364bf182ccf4bbd5696338c34069354
|
d4151c5907634bedca10e29b422191d79d728508
|
/src/tui/main.cxx
|
1f3c909f65dd0cf05412475125b8e79b189ac821
|
[] |
no_license
|
Ryanel/Ymgyrch
|
b5a73b4a7f741d52e36c95f5ea7174848215d213
|
d596be3f1e5eb2c6284cdc895e99f249976d26a6
|
refs/heads/master
| 2021-06-17T13:07:51.198746
| 2017-05-23T04:51:24
| 2017-05-23T04:51:24
| 78,317,872
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 786
|
cxx
|
#include <tui/tui.hpp>
#include <rlutil/rlutil.h>
#include <logging.hpp>
#include <ymgyrch/core.hpp>
#include <ymgyrch/state.hpp>
#include <ymgyrch/systems/nes.hpp>
int main() {
g_tui = new TextUI();
g_log = new Logger();
g_core = new Ymgyrch::Core();
Ymgyrch::System * sys = new Ymgyrch::Systems::NES();
State::romImage = "D:\\ROMS\\NES\\DonkeyKong.nes";
//State::romImage = "D:\\Developer\\NES\\test.nes";
g_core->Init(sys);
g_core->Start();
while (g_core->current->isActive) {
g_core->Tick(0.0);
// Draw UI
g_tui->Update();
g_tui->Draw();
//rlutil::msleep(16);
}
g_log->Log("Core", "Execution Ended. Press any key to quit");
while (rlutil::nb_getch() == 0) {
// Draw UI
g_tui->Update();
g_tui->Draw();
//rlutil::msleep(16);
}
return 0;
}
|
[
"lioneltabre@gmail.com"
] |
lioneltabre@gmail.com
|
c02d4fdee266e0a16d463f227cb0c2ae072bbef5
|
90e03cdb144fd14abaaebe0138351bac754bb5a4
|
/tests/firebird/firebird-variant-conv.cc
|
fe4dceeb534d01bb8d27e2a5fd9e864ca4abb6f1
|
[
"BSD-3-Clause"
] |
permissive
|
informave/dbwtl
|
2038e9c8e1c17b3ab83e5035014271ec15a649ae
|
fed8f84ac42949d906a34b6a5a1b61b3a7b74356
|
refs/heads/master
| 2018-12-11T12:20:39.438122
| 2018-09-12T18:56:38
| 2018-09-12T19:06:16
| 13,350,267
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,894
|
cc
|
#include "../cxxc.hh"
#include "fixture_firebird.hh"
CXXC_FIXTURE_TEST(FirebirdTestbaseFixture, DatabaseVersion)
{
std::cout << dbc.dbmsName() << std::endl;
}
CXXC_FIXTURE_TEST(FirebirdTestbaseFixture, ScalarValueSelect)
{
DBMS::Statement stmt(dbc);
DBMS::Resultset rs;
stmt.execDirect("SELECT 5 FROM RDB$DATABASE");
rs.attach(stmt);
rs.first();
CXXC_CHECK( !rs.eof() );
CXXC_CHECK( rs.column(1).get<int>() == 5 );
}
CXXC_FIXTURE_TEST(FirebirdTestbaseFixture, BindScalarValueSelect)
{
DBMS::Statement stmt(dbc);
DBMS::Resultset rs;
stmt.prepare("SELECT 10 FROM RDB$DATABASE WHERE 5 = ?");
short a = 0;
stmt.bind(1, &a);
a = 5;
stmt.execute();
rs.attach(stmt);
rs.first();
CXXC_CHECK( !rs.eof() );
CXXC_CHECK( rs.column(1).get<int>() == 10 );
}
CXXC_FIXTURE_TEST(FirebirdTestbaseFixture, UnknownBind)
{
DBMS::Statement stmt(dbc);
DBMS::Resultset rs;
stmt.prepare("SELECT coalesce(?, 10) FROM RDB$DATABASE");
stmt.bind(1, 20);
stmt.execute();
rs.attach(stmt);
rs.first();
CXXC_CHECK( !rs.eof() );
CXXC_CHECK( rs.column(1).get<int>() == 20 );
}
CXXC_FIXTURE_TEST(FirebirdTestbaseFixture, StmtReuse)
{
DBMS::Statement stmt(dbc);
DBMS::Resultset rs;
stmt.prepare("SELECT 1 FROM RDB$DATABASE WHERE 10 = ?");
stmt.bind(1, 10);
stmt.execute();
rs.attach(stmt);
rs.first();
CXXC_CHECK( !rs.eof() );
CXXC_CHECK( rs.column(1).get<int>() == 1 );
stmt.close();
//stmt.clearBindings(); // @bug
stmt.prepare("SELECT 1 FROM RDB$DATABASE WHERE 10 = ?");
//stmt.bind(1, 20);
stmt.execute();
rs.attach(stmt);
rs.first();
CXXC_CHECK( rs.eof() );
}
int main(void)
{
std::locale::global(std::locale(""));
std::cout.imbue(std::locale());
std::cerr.imbue(std::locale());
std::clog.imbue(std::locale());
std::wcout.imbue(std::locale());
std::wcerr.imbue(std::locale());
std::wclog.imbue(std::locale());
return cxxc::runAll();
}
|
[
"daniel@vogelbacher.name"
] |
daniel@vogelbacher.name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.