hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
โ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
โ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
โ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
โ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
โ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
โ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
โ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
โ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
โ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a948bd94ab06a58af8897df7319c40a0a7d97467 | 4,230 | hpp | C++ | mapproxy/src/mapproxy/support/metatile.hpp | maka-io/vts-mapproxy | 13c70b1bd2013d76b387900fae839e3948e741c3 | [
"BSD-2-Clause"
] | null | null | null | mapproxy/src/mapproxy/support/metatile.hpp | maka-io/vts-mapproxy | 13c70b1bd2013d76b387900fae839e3948e741c3 | [
"BSD-2-Clause"
] | null | null | null | mapproxy/src/mapproxy/support/metatile.hpp | maka-io/vts-mapproxy | 13c70b1bd2013d76b387900fae839e3948e741c3 | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef mapproxy_support_metatile_hpp_included_
#define mapproxy_support_metatile_hpp_included_
#include "vts-libs/registry.hpp"
#include "vts-libs/vts/basetypes.hpp"
#include "vts-libs/vts/tileop.hpp"
#include "../resource.hpp"
#include "./coverage.hpp"
namespace vts = vtslibs::vts;
namespace vr = vtslibs::registry;
/** Metatile block (part of metatile sharing same spatial division)
*/
struct MetatileBlock {
std::string srs;
vts::TileRange view;
math::Extents2 extents;
/** Common ancestor of nodes in this block
*/
vts::NodeInfo commonAncestor;
vts::TileId offset;
typedef std::vector<MetatileBlock> list;
MetatileBlock(vts::Lod lod, const vr::ReferenceFrame &referenceFrame
, const std::string &srs, const vts::TileRange &view
, const math::Extents2 &extents);
bool valid() const { return commonAncestor.valid(); }
bool partial() const { return commonAncestor.partial(); }
};
/** Generate metatile blocks for given metatile id in given reference frame
*
* \param referenceFrame reference frame
* \param tileId metatile id
* \param metaBinaryOrder metatile binary order override if nonzero
*/
MetatileBlock::list metatileBlocks(const Resource &resource
, const vts::TileId &tileId
, unsigned int metaBinaryOrder = 0
, bool includeInvalid = false);
inline bool special(const vr::ReferenceFrame &referenceFrame
, const vts::TileId &tileId)
{
if (const auto *node
= referenceFrame.find(vts::rfNodeId(tileId), std::nothrow))
{
switch (node->partitioning.mode) {
case vr::PartitioningMode::manual:
case vr::PartitioningMode::barren:
return true;
default:
return false;
}
}
return false;
}
class ShiftMask {
public:
ShiftMask(const MetatileBlock &block, int samplesPerTile
, const MaskTree &maskTree_ = MaskTree())
: offset_(block.offset.x * samplesPerTile
, block.offset.y * samplesPerTile)
, mask_(generateCoverage((1 << block.offset.lod) * samplesPerTile
, block.commonAncestor, maskTree_
, vts::NodeInfo::CoverageType::grid))
{}
bool operator()(int x, int y) const {
return mask_.get(x + offset_(0), y + offset_(1));
}
private:
const math::Point2i offset_;
const vts::NodeInfo::CoverageMask mask_;
};
/** Boundlayer metatile from mask
*/
cv::Mat boundlayerMetatileFromMaskTree(const vts::TileId &tileId
, const MaskTree &maskTree
, const MetatileBlock::list &blocks);
#endif // mapproxy_support_metatile_hpp_included_
| 35.546218 | 78 | 0.668085 | maka-io |
a94b05d89d40490fc932e6788c489c61c42e2e48 | 2,005 | hpp | C++ | altona_config.hpp | kebby/Werkkzeug4 | f2ff557020d62c348b54d88e137999175b5c18a3 | [
"BSD-2-Clause"
] | 10 | 2020-11-26T09:45:15.000Z | 2022-03-18T00:18:27.000Z | altona_config.hpp | kebby/Werkkzeug4 | f2ff557020d62c348b54d88e137999175b5c18a3 | [
"BSD-2-Clause"
] | null | null | null | altona_config.hpp | kebby/Werkkzeug4 | f2ff557020d62c348b54d88e137999175b5c18a3 | [
"BSD-2-Clause"
] | 3 | 2020-01-02T19:11:44.000Z | 2022-03-18T00:21:45.000Z | /****************************************************************************/
/*** ***/
/*** Altona main configuration file. ***/
/*** ***/
/****************************************************************************/
/*** ***/
/*** Please rename this file to "altona_config.hpp" and edit it to ***/
/*** reflect your needs. ***/
/*** ***/
/****************************************************************************/
/*** ***/
/*** This file is compiled in every altona application ***/
/*** In addition to that, makeproject parses this file by hand on ***/
/*** every invokation. ***/
/*** ***/
/****************************************************************************/
// operator new shenanigans (one should investigate this)
#pragma warning (disable: 4595)
#pragma warning (disable: 5043)
// GCed objects don't have delete
#pragma warning (disable: 4291)
// macro redef in shader disasm (conflict between dxsdk and windows sdk)
#pragma warning (disable: 4005)
#define sCONFIG_CODEROOT L""
#define sCONFIG_SDK_DX9 1 // Microsoft DX9 sdk installed (required for input, sound, graphics)
#define sCONFIG_SDK_DX11 1
#define sCONFIG_SDK_CG 0
#define sCONFIG_GUID {0x74F17E89,{0x915F,0x4264,0xB67A},{0xBA,0xDF,0x00,0xD5,0x32,0x5A}}
#define sCONFIG_RENDER_DX9
#define sCONFIG_CEF 1
#ifdef _DEBUG
#define sCONFIG_BUILD_DEBUG
#else
#define sCONFIG_BUILD_RELEASE
#endif | 44.555556 | 112 | 0.373067 | kebby |
a94bb8233adf874ddb31cd7d38d1488096bcf311 | 1,440 | hpp | C++ | examples/sill/vr-puzzle/frame.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 15 | 2018-02-26T08:20:03.000Z | 2022-03-06T03:25:46.000Z | examples/sill/vr-puzzle/frame.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 32 | 2018-02-26T08:26:38.000Z | 2020-09-12T17:09:38.000Z | examples/sill/vr-puzzle/frame.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | null | null | null | #pragma once
#include <lava/sill.hpp>
#include <nlohmann/json.hpp>
struct GameState;
class Frame {
public:
Frame(GameState& gameState);
Frame(const Frame&) = delete;
Frame& operator=(const Frame&) = delete;
/// Create a frame.
static Frame& make(GameState& gameState);
/// Prepare the frame to be removed.
/// The destructor does not destroy anything
/// so that shutting down the application is fast enough.
virtual void clear(bool removeFromLevel = true);
const std::string& name() const { return m_name; }
void name(const std::string& name) { m_name = name; }
const lava::sill::EntityFrame& entityFrame() const { return *m_entityFrame; }
lava::sill::EntityFrame& entityFrame() { return *m_entityFrame; }
void entityFrame(lava::sill::EntityFrame& entityFrame) { m_entityFrame = &entityFrame; }
const lava::sill::MeshFrameComponent& mesh() const { return m_entityFrame->get<lava::sill::MeshFrameComponent>(); };
lava::sill::MeshFrameComponent& mesh() { return m_entityFrame->get<lava::sill::MeshFrameComponent>(); };
protected:
GameState& m_gameState;
lava::sill::EntityFrame* m_entityFrame = nullptr;
std::string m_name;
};
uint32_t findFrameIndex(GameState& gameState, const lava::sill::EntityFrame& entityFrame);
inline uint32_t findFrameIndex(GameState& gameState, const Frame& frame) {
return findFrameIndex(gameState, frame.entityFrame());
}
| 33.488372 | 120 | 0.709028 | Breush |
a94d08e7f1f4872b68209b77babad5630b68215f | 6,338 | cpp | C++ | data/52.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/52.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/52.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | int Jn, ZjHQ/*Y*//*dEky*/
,H , lAIw,
Mb4p ,
Rfpqw,s ,e6k,zuS,sSjf
/*T*//**/
,IBH
, dg4 ,Vhk, iLTc
,X5YU, F4, hL /*2jtUXBP*/,
oHs ,
JC,MHO, joPQ
, zOHJ ;
void
f_f0
() {;//0uh
{ {
int VTT;
volatile int N
,/*kec*/ n , Q,O
;
{
for(int i=1 ;
i<
1 ;++i//zYj
){} {
for
(int i=1;i<2
;++i//X
)
//b
if (/*nG*/true ) {/*aQ*/ }else {//rU
} }} VTT=O +N+ n+
Q ;}{ /*Mp*/return ;if( true ) {; }else if( true ) {; { }{ int
Y//O
; volatile int QVq ,T8RxN ,
gUq;Y =//qBmC
gUq
+
QVq
+ T8RxN ;
if( true
)
{} else for (int
i=1;i<3;++i) ; //Vd
}
}
else if (//a
true)//
;else
{ { };/*Hg4b*/ }{volatile int O5E
,
ceux,
fH0 ;
{//duB
}zOHJ//mI
= fH0 +
O5E+ceux
; }}
for(int i=1;i< 4
;++i)if (true) return
;else
if (true/*VXU*/);else {int FN ;//S
volatile int
Ch
,C9
, Z;{
return ; if (//d
true)
{}else ;
} {
/*M2*/return ;/*kM7*/ for
(int /*V*/i=1
; i< /**/ 5/*k*/
;++i
)
return ;}FN =Z
+/*Fv*/Ch+
C9 ;
}return ; } return ; return ;
return ;}
void f_f1
() {for(int i=1;
i< 6
;++i);{ volatile int ReS
,zP,
PXb//UmM7m
,u4Y,
Bj,
VTCUC , Bz ;
//9S
{//t
volatile int Wj7,
/*nn*/Khx//P9
, mstW , rjoH ,
tSdj;; {
{volatile int W9y
,Ous4
;//H
if(true ) Jn=
Ous4+W9y//8h
//o1DB
; /*d*/else
return ;
}
if//ix
(true
)
{} else
return ;/*yc4z*/}ZjHQ=tSdj
+
Wj7
+ Khx+mstW+//ry
rjoH;
} if( true//RhY
)
H=Bz+ReS//87
+
zP+ PXb + u4Y+Bj +
VTCUC
;else{ { //DglY
{ ;} }
; {
{ ;
}{}
}
}{ if
( true);else return ;{ {} return
;}
}{ volatile int KcUw5P,satW, I5; {
int
ofQ;
volatile int LNPT
, kJf,mY
;{ }
ofQ= mY + LNPT+ kJf;
};lAIw=
I5+
KcUw5P
+
satW ;}} { {int UM;/*mG*/
volatile int
RYkTe,EQcC ,O3 ; if (
true
)
UM =
O3 +RYkTe
+ EQcC //aY
; else
{{
{}{
}{
} }}{ volatile int q,a5gF , X9T03
,
gFe6uE;
if
(
true
) {{/*6n*/volatile int Ln ;if
(true
//
)Mb4p
= Ln
;
else//XD
return ; }
} else/*EFG*/ Rfpqw
=
gFe6uE + q//e
+
a5gF +X9T03; {
} //
}{
volatile int Hr ,XtU ,/*zO*/uQ;
{}
s
=
uQ
+ Hr
+
XtU;}if
(true) {{{}if (
true){ } else{} }{/*tT*/ {} }
}else {{
} }for(int i=1 ; i< 7 ;++i )if( true ) {/*v5o*/ int w5bB
;volatile int QxP//v6N
//HVF6q
,iaa1e; if(true)for(int i=1;i< 8 ;++i
)for
(int
i=1
; i<9 ;++i
)if
(true
)
return ; else return/*J*/ ; else w5bB
= iaa1e
+QxP
;
{ {}{ }
} {{
} } } else
{ volatile int vEH
,C4n3p , Gj3SY,
AFCK;/*qR*/e6k=
AFCK +
vEH
+
C4n3p +
Gj3SY; }
//
return ;}{{ ; if
( true )
{} else{
volatile int j1, lg ; return
;zuS =
lg +j1
;return ; } } ; /*cSAm*/ } {{{{
{ } } }
{
if /*rP*/( true
){ }else return ; } } {/**/return ;{if ( true )
//1
return ;
else{ } }
}if(true
)
;else {/*J*/{
{
}{
}{} }//PGE
{}
/*ffJ*/{ }
} if (true ) { if
/*KZ8*/( true
){}
else ; }else
{for (int i=1;
i< 10 ;++i)return ;
; return/*gCypm*/
;
}
}
;{
{//S
{ return ; {
}//uC5D
}{int AD /*R2*/; volatile int
PRE, Swtj; AD
=Swtj+ PRE
;
return ; { }} } if ( true//uxo
) { /*x*/return ; } else
;
}}return
; return/*k*/ ;
}void f_f2
(){{{ int
n97; volatile int WJT1z , x4N ,
Sy ;n97 //
=Sy+WJT1z //lv
+x4N ;
{
{int
L1N;
volatile int XU/*ahy*/ //w
; L1N= XU ;}//d
for
(int
i=1
//hB7gK
;
i<
11;++i ){} ;} for/*X*/
(int i=1 ;i<12
;++i){
; }}{
int vsp ;
volatile int j ,Ylgro,
RGV9 //YP
,//nmy
GE
,g55 ,
//tA
PkmsX,ms , R
;//pR
//Hx
{volatile int V5 ,
VJsOq,
c ; sSjf=c +V5 +VJsOq //a
;}
IBH
=R
+j+Ylgro+RGV9+GE ;
vsp = g55 +
PkmsX
+ms//
;
} for
(int
i=1 ;
i<13;++i)
{ return ;
if
(true)if(true )
{//O
return ;
return ;}
else return
;
else for (int
i=1
;
i< 14 ;++i
)
{/*UYB*/{} }{; for (int
i=1 ;i<
/*n1S*/ 15 ;++i )for(int
i=1 ;//gf9
//
i<16 ;++i){} }
} {volatile int V89x8, YN8, Cr0jX//Wt
;for (int i=1 //v1o
; i</**/
17 /*PWv*/
;++i ) if (true)
dg4= Cr0jX
+ V89x8 +/**/YN8;else return ;{//fe
;}
if ( true ) {{ } { }{; }{int hX0W;volatile int N5
,
lw0U ; if(true ) {//Tg
//
} else{}
for (int
i=1
;i<
18;++i ) return//D
;
{ }
hX0W=lw0U
+ N5 ;}
} else
{
return ; {};
}}
}{{ int
W1Q;volatile int a ,zW
, D
,E;return
;W1Q//BV0P
=/*J5*/ E
+a
+ zW+D;
{ {
{{ }
}} /*6hb*/{}}{ return ;;
/*n*/
//n
{for (int i=1 ;i<//qzq
19/*IN4*/;++i
)
for (int i=1; i<20 ;++i
) if(
true )return ; else ;/*V56*/if
( true )
{ return ; }else
{} { }}
}/*gNm*/;
} { int
kVag
;volatile int i2,xRW
, //Hjl
bPYOQ7, SdKrE, e6;for (int i=1 ;i<21;++i
//tt9T
)
/*Y*/{;
{
{ } }} /*Gs*/kVag= e6+i2 + xRW +bPYOQ7+ SdKrE ; } ;
} {;return ;//Wo
;} return ; return ;//M6To
}
int
main /*d*/() { /*oh*/volatile int fF3,
W8hKj , rZ ,
/*SN5*/
mj ,r; if//C
(true ) return 1747888762 ;
else/*t*/
/**/ if( true
)
//6o
for (int
i=1; i<22
;++i ) { {
return//2
1892777458;
{{{}
}}
//VBI
return
973039688
//Pmf
;} //fh
{
return 979197843;
{ return 1574272463;}{
{{
}
}return 1112267248
; }
}{;//Kg
{ {volatile int OVcBo
,DL2 ;{
} Vhk = DL2
+
OVcBo;}for
(int i=1;
i< 23 ;++i )
{ return //m
472807525;return 2080782169 ; } {}
}
{ {} {;}
for(int i=1;i< 24;++i//5X
) return 403167836 ;}
}
}else iLTc=
r +
fF3/**/ +
W8hKj+rZ
+
mj//rn
;
{ {
volatile int g99Nx, Sxvj, gmw, Ge//0AXsi
; X5YU
//3E5T
=Ge+ g99Nx
/*m2*/ +
Sxvj+gmw ;
{ {volatile int BGQ
,
u ;F4 =u+ BGQ ; } } //uO
{
{
}
{{}return 1107412337
;}} for
(int i=1; i< 25
;++i) { { {{} { }
}
} {
{if (
true ){ } /*o*/else {//Nr
for
(int i=1
; /*l*/i<
26 ;++i){
} } }
//U2
;for (int
i=1
; i< 27 ;++i )//
{ ; ; } }}
}; {{{{
} {/*m*/ } //P2i
}}//h
for(int
i=1;i<28;++i )
{;
{}
;
{{} }} }}
;if/*J3B*/
( true
)return
2058880243;else/*OO*/
;; {volatile int //Lc
rCK , WZN ,Fm,
Bcc
,
zslP, YrC4
, fD ,/*1*/ wX ,hy ,RIQ
;
hL
=
RIQ
+rCK +
WZN +Fm+ Bcc; {{ //I7Q
{
}
for(int i=1
;i< 29
;++i
)
{ }} { {}//I
return 1287420094//HX
;}} oHs=
//JpO
zslP
+YrC4+
fD+ wX + hy //NuZ
;{{{ int pxnN;
volatile int/*cc3pC*/ hx
,
WQVc ;pxnN=
WQVc+
hx
;
/*v7R*/{
}
}}
{
volatile int
Gh ,
LdwE
, L20 , qoH4 , Opg, aFoc ,NJR ,ba8JC ,//rS
b2mXaio; JC
= b2mXaio
+Gh +LdwE ;{ } if /**/( true ) for(int i=1 ;i<30
;++i //
)
MHO =L20+ qoH4;else joPQ=Opg +
aFoc
+NJR/*4eLY*/
+ba8JC ;
}
//6WE
{{ }} }} } | 10.373159 | 69 | 0.456453 | TianyiChen |
a9502feb3e45152639b936352d0e4a4acc27db05 | 626 | cpp | C++ | Source/TTreeNodeStack.cpp | poissonconsulting/RadCon | acbbb974ececbabddd3da91768744bf31982bf93 | [
"MIT"
] | 1 | 2021-12-26T13:32:52.000Z | 2021-12-26T13:32:52.000Z | Source/TTreeNodeStack.cpp | joethorley/RadCon | acbbb974ececbabddd3da91768744bf31982bf93 | [
"MIT"
] | 1 | 2015-02-02T19:28:20.000Z | 2015-02-02T19:28:20.000Z | Source/TTreeNodeStack.cpp | poissonconsulting/RadCon | acbbb974ececbabddd3da91768744bf31982bf93 | [
"MIT"
] | null | null | null | #include "TTreeNodeStack.h"
TTreeNodeStack& TTreeNodeStack::operator = (const TTreeNodeStack& treeNodeStack)
{
fStack = treeNodeStack.fStack;
return (*this);
}
void TTreeNodeStack::Pop (TTreeNode*& item)
{
TObject* obj = NULL;
fStack.Pop (obj);
item = (TTreeNode*)obj;
}
void TTreeNodeStack::Top (const TTreeNode*& item) const
{
const TObject* obj = NULL;
fStack.Top (obj);
item = (TTreeNode*) obj;
}
TTreeNodeStack::TTreeNodeStack (void)
: fStack ()
{
}
TTreeNodeStack::TTreeNodeStack (const TTreeNodeStack& treeNodeStack)
: fStack (treeNodeStack.fStack)
{
}
TTreeNodeStack::~TTreeNodeStack (void)
{
}
| 626 | 626 | 0.714058 | poissonconsulting |
a951e001cfe5b4ebabed0c9303b5a0121317ef1a | 427 | cpp | C++ | src/main.cpp | scotto3394/go-bot | b4f45fc796160c7f1e1c8bb593fc1a6c48bc9365 | [
"MIT"
] | null | null | null | src/main.cpp | scotto3394/go-bot | b4f45fc796160c7f1e1c8bb593fc1a6c48bc9365 | [
"MIT"
] | null | null | null | src/main.cpp | scotto3394/go-bot | b4f45fc796160c7f1e1c8bb593fc1a6c48bc9365 | [
"MIT"
] | null | null | null | #include <iostream>
#include "include/rules.hpp"
#include "include/helper.hpp"
int main(int argc, char **argv)
{
std::ios::sync_with_stdio(false);
Game game(BoardSize::SMALL, atoi(argv[1]));
while (true)
{
size_t c, r;
game.render();
input_play(game, game.get_turn());
if (game.get_captured().first != 0)
{
break;
}
game.next_turn();
}
} | 20.333333 | 47 | 0.548009 | scotto3394 |
a95951225ff22873115c9c2b150972321e27f66a | 2,711 | hh | C++ | src/project.hh | LeszekSwirski/ccls | a10d53071ce678a28d9444a6325605d6e22f589f | [
"Apache-2.0"
] | null | null | null | src/project.hh | LeszekSwirski/ccls | a10d53071ce678a28d9444a6325605d6e22f589f | [
"Apache-2.0"
] | null | null | null | src/project.hh | LeszekSwirski/ccls | a10d53071ce678a28d9444a6325605d6e22f589f | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017-2018 ccls Authors
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.
==============================================================================*/
#pragma once
#include "config.hh"
#include "lsp.hh"
#include <functional>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace ccls {
struct WorkingFiles;
std::pair<LanguageId, bool> lookupExtension(std::string_view filename);
struct Project {
struct Entry {
std::string root;
std::string directory;
std::string filename;
std::vector<const char *> args;
// If true, this entry is inferred and was not read from disk.
bool is_inferred = false;
int id = -1;
};
struct Folder {
std::string name;
// Include directories for <> headers
std::vector<std::string> angle_search_list;
// Include directories for "" headers
std::vector<std::string> quote_search_list;
std::vector<Entry> entries;
std::unordered_map<std::string, int> path2entry_index;
};
std::mutex mutex_;
std::unordered_map<std::string, Folder> root2folder;
// Loads a project for the given |directory|.
//
// If |config->compilationDatabaseDirectory| is not empty, look for .ccls or
// compile_commands.json in it, otherwise they are retrieved in
// |root_directory|.
// For .ccls, recursive directory listing is used and files with known
// suffixes are indexed. .ccls files can exist in subdirectories and they
// will affect flags in their subtrees (relative paths are relative to the
// project root, not subdirectories). For compile_commands.json, its entries
// are indexed.
void Load(const std::string &root_directory);
// Lookup the CompilationEntry for |filename|. If no entry was found this
// will infer one based on existing project structure.
Entry FindEntry(const std::string &path, bool can_be_inferred);
// If the client has overridden the flags, or specified them for a file
// that is not in the compilation_database.json make sure those changes
// are permanent.
void SetArgsForFile(const std::vector<const char *> &args,
const std::string &path);
void Index(WorkingFiles *wfiles, RequestId id);
};
} // namespace ccls
| 33.469136 | 80 | 0.704168 | LeszekSwirski |
a95c4a434df29fdba686b0aa8111a8bf6d41ee6c | 338 | hpp | C++ | falcon/helper/use_difference_type.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | 2 | 2018-02-02T14:19:59.000Z | 2018-05-13T02:48:24.000Z | falcon/helper/use_difference_type.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | falcon/helper/use_difference_type.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | #ifndef FALCON_HELPER_USE_DIFFERENCE_TYPE_HPP
#define FALCON_HELPER_USE_DIFFERENCE_TYPE_HPP
#include <falcon/type_traits/use_def.hpp>
namespace falcon {
namespace _aux {
FALCON_USE_XXX_TRAIT_NAMED_DEF(difference_type, use_difference_type);
}
template <class T>
struct use_difference_type
: _aux::use_difference_type<T>
{};
}
#endif
| 16.9 | 69 | 0.828402 | jonathanpoelen |
a96d3f67fa71635807792fd2038e9c3b8deb3d28 | 355 | cc | C++ | 01_Basics/Variables3.cc | SEEM87/UdemyCpp | b1fe398c7134c74760341c9620eabca6c64043a9 | [
"MIT"
] | 14 | 2020-12-18T20:00:49.000Z | 2022-02-23T12:44:26.000Z | 01_Basics/Variables3.cc | SEEM87/UdemyCpp | b1fe398c7134c74760341c9620eabca6c64043a9 | [
"MIT"
] | null | null | null | 01_Basics/Variables3.cc | SEEM87/UdemyCpp | b1fe398c7134c74760341c9620eabca6c64043a9 | [
"MIT"
] | 56 | 2020-11-07T20:14:22.000Z | 2022-03-31T12:36:09.000Z | #include <iostream>
int main()
{
// 1 Byte = 8bit
bool my_value0 = true; // false
// 1 Byte = 8bit
char my_value1 = 10;
// 2 Byte = 16bit
short my_value2 = 42;
// 4 Byte = 32bit
int my_value3 = 22;
// 4 Byte = 32bit
float my_value4 = 12.0f;
// 8 Byte = 64bit
double my_value5 = 13.0;
return 0;
}
| 14.2 | 35 | 0.535211 | SEEM87 |
a96d9b4f9ac6218ac8509ce53b7741a842560504 | 899 | cpp | C++ | DSAA2/TestFastDisjSets.cpp | crosslife/DSAA | 03472db6e61582187192073b6ea4649b6195222b | [
"MIT"
] | 5 | 2017-03-30T23:23:08.000Z | 2020-11-08T00:34:46.000Z | DSAA2/TestFastDisjSets.cpp | crosslife/DSAA | 03472db6e61582187192073b6ea4649b6195222b | [
"MIT"
] | null | null | null | DSAA2/TestFastDisjSets.cpp | crosslife/DSAA | 03472db6e61582187192073b6ea4649b6195222b | [
"MIT"
] | 1 | 2019-04-12T13:17:31.000Z | 2019-04-12T13:17:31.000Z | #include <iostream.h>
#include "DisjSets.h"
// Test main; all finds on same output line should be identical
int main( )
{
int numElements = 128;
int numInSameSet = 16;
DisjSets ds( numElements );
int set1, set2;
for( int k = 1; k < numInSameSet; k *= 2 )
{
for( int j = 0; j + k < numElements; j += 2 * k )
{
set1 = ds.find( j );
set2 = ds.find( j + k );
ds.unionSets( set1, set2 );
}
}
for( int i = 0; i < numElements; i++ )
{
cout << ds.find( i ) << "*";
if( i % numInSameSet == numInSameSet - 1 )
cout << endl;
}
cout << endl;
return 0;
}
| 27.242424 | 71 | 0.362625 | crosslife |
a96f83fa944ce9f5991efb911079510f47668262 | 6,810 | cpp | C++ | hamlet/utilities.cpp | delta4k/infinitelemurs | f0e09dcfdcf3b3e562775a7f6c8b979fed222038 | [
"Apache-2.0"
] | null | null | null | hamlet/utilities.cpp | delta4k/infinitelemurs | f0e09dcfdcf3b3e562775a7f6c8b979fed222038 | [
"Apache-2.0"
] | null | null | null | hamlet/utilities.cpp | delta4k/infinitelemurs | f0e09dcfdcf3b3e562775a7f6c8b979fed222038 | [
"Apache-2.0"
] | null | null | null |
/*****************************************************************************\
Copyright (c) 2011-2017
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 <cstdlib>
#include <ctime>
#include <cstdio>
#include <conio.h>
#include <cstdarg>
#include <mutex>
#include <set>
#include "utilities.h"
bool verboseOutput = true;
// printf is only guaranteed to handle strings up to this length.
// The Microsoft compiler handles much more than this, but
// we want this to be as portable as reasonably possible.
const int MAX_PRINTF_STRLEN = 4095;
static char formatBuffer[MAX_PRINTF_STRLEN + 1];
static std::mutex formatMutex;
#define FORMAT(fmt, buffer, bufflen) \
va_list argptr; \
va_start(argptr, fmt); \
int num_required = vsnprintf((buffer), (bufflen), (fmt), argptr); \
va_end(argptr); \
Assert(num_required < bufflen)
/***********************************************\
Console output can slow a program down a lot.
This is a printf-substitute that can be turned
on or off.
Use this only for stuff that you want to suppress
when running flat-out for speed. Use plain-old
printf for stuff that you want to always be printed.
\***********************************************/
void prn(const char* fmt, ...)
{
if(!verboseOutput)
return;
std::lock_guard<std::mutex> lock{ formatMutex };
FORMAT(fmt, formatBuffer, MAX_PRINTF_STRLEN);
printf("%s", formatBuffer);
}
/***********************************************\
Because printf-style formatting is just too
nice to do without.
\***********************************************/
std::string formatString(const char* fmt, ...)
{
std::lock_guard<std::mutex> lock{ formatMutex };
FORMAT(fmt, formatBuffer, MAX_PRINTF_STRLEN);
std::string result(formatBuffer);
return result;
}
/*****************************************************************************\
Return the size of the given file, or zero if the file can't be obtained
\*****************************************************************************/
size_t getFileSize(const char* filename)
{
struct stat st;
if (stat(filename, &st) != 0)
{
return 0;
}
return st.st_size;
}
/*****************************************************************************\
Load the given file into a single contiguous string.
This function won't return if the load operation fails. It will fail for
the usual reasons file operations fail, or if the file contains embedded
zeros or characters that won't fit in a signed char.
\*****************************************************************************/
std::string loadText(const char* fname)
{
std::string result;
size_t size = getFileSize(fname);
if(size > result.max_size())
{
failf("File %s is too large for a single string", fname);
}
if(size == 0)
{
failf("Failure loading text file %s\n", fname);
}
// We use "rb" because we want an exact copy, with no
// line ending translation.
FILE* fp = fopen(fname, "rb");
if (!fp)
{
failf("Failure loading text file %s\n", fname);
}
result.reserve(size);
char c = fgetc(fp);
int charnum = 0;
while(!feof(fp))
{
if(c == 0)
{
failf("File contains embedded zero character in position %d\n", charnum);
}
if (c > 0x7E)
{
failf("Text contains non-printing character: (char)%d in character #%d\n", c, charnum);
}
result.push_back(c);
c = fgetc(fp);
charnum++;
}
return result;
}
/*****************************************************************************\
A simple, quick checksum, not intended for security or UUID purposes.
\*****************************************************************************/
int checksum(const std::string& str)
{
int result = 0;
for(auto c : str)
{
result += c;
}
return result;
}
/*****************************************************************************\
Fail sort of gracefully with an error message.
\*****************************************************************************/
void failf(const char* fmt, ...)
{
// Something bad has happened, therefore we won't assume we can use
// the shared format buffer.
const int bufsize = 255;
char failbuf[bufsize + 1];
FORMAT(fmt, failbuf, bufsize);
printf("Failure: %s\n", failbuf);
printf("Hit any key to exit..\n");
getch();
exit(-1);
}
/*****************************************************************************\
\*****************************************************************************/
Stopwatch::Stopwatch()
{
clock();
startTime = std::chrono::steady_clock::now();
}
void Stopwatch::start()
{
startTime = std::chrono::steady_clock::now();
}
double Stopwatch::elapsedSeconds() const
{
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> dt = now - startTime;
double elapsed_seconds = dt.count();
return elapsed_seconds;
}
/*****************************************************************************\
Return the fractional difference between x and y: Abs(x-y) / Max(x,y)
\*****************************************************************************/
double fractionalDifference(double x, double y)
{
double maxval = Max(Abs(x), Abs(y));
if (maxval == 0) return 0;
double delta = Abs(x - y);
// This is not intended as a general-purpose function that may
// be called with pathological inputs, so we're going to be
// pragmatic and not stress about things like overflows, except
// for a basic sanity check.
Assert(maxval > 1e-10);
return delta / maxval;
}
| 30 | 100 | 0.483847 | delta4k |
a972820ceae78b393e924d578b031d5218c3d373 | 19,771 | cpp | C++ | test/test_style.cpp | fargies/rapidyaml | 6fd373c860b1eef3b190a521acabebc2fd2dcb04 | [
"MIT"
] | null | null | null | test/test_style.cpp | fargies/rapidyaml | 6fd373c860b1eef3b190a521acabebc2fd2dcb04 | [
"MIT"
] | null | null | null | test/test_style.cpp | fargies/rapidyaml | 6fd373c860b1eef3b190a521acabebc2fd2dcb04 | [
"MIT"
] | null | null | null | #ifndef RYML_SINGLE_HEADER
#include "c4/yml/std/std.hpp"
#include "c4/yml/parse.hpp"
#include "c4/yml/emit.hpp"
#include <c4/format.hpp>
#include <c4/yml/detail/checks.hpp>
#include <c4/yml/detail/print.hpp>
#endif
#include "./test_case.hpp"
#include <gtest/gtest.h>
namespace c4 {
namespace yml {
std::string emit2str(Tree const& t)
{
return emitrs<std::string>(t);
}
TEST(style, flags)
{
Tree tree = parse_in_arena("foo: bar");
EXPECT_TRUE(tree.rootref().type().default_block());
EXPECT_FALSE(tree.rootref().type().marked_flow());
EXPECT_FALSE(tree.rootref().type().marked_flow_sl());
EXPECT_FALSE(tree.rootref().type().marked_flow_ml());
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
EXPECT_FALSE(tree.rootref().type().default_block());
EXPECT_TRUE(tree.rootref().type().marked_flow());
EXPECT_TRUE(tree.rootref().type().marked_flow_sl());
EXPECT_FALSE(tree.rootref().type().marked_flow_ml());
tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_ML);
EXPECT_FALSE(tree.rootref().type().default_block());
EXPECT_TRUE(tree.rootref().type().marked_flow());
EXPECT_FALSE(tree.rootref().type().marked_flow_sl());
EXPECT_TRUE(tree.rootref().type().marked_flow_ml());
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
csubstr scalar_yaml = R"(
this is the key: >-
this is the multiline
"val" with
'empty' lines
)";
void check_same_emit(Tree const& expected)
{
#if 0
#define _showtrees(num) \
std::cout << "--------\nEMITTED" #num "\n--------\n"; \
std::cout << ws ## num; \
std::cout << "--------\nACTUAL" #num "\n--------\n"; \
print_tree(actual ## num); \
std::cout << "--------\nEXPECTED" #num "\n--------\n"; \
print_tree(expected)
#else
#define _showtrees(num)
#endif
std::string ws1, ws2, ws3, ws4;
emitrs(expected, &ws1);
{
SCOPED_TRACE("actual1");
Tree actual1 = parse_in_arena(to_csubstr(ws1));
_showtrees(1);
test_compare(actual1, expected);
emitrs(actual1, &ws2);
}
{
SCOPED_TRACE("actual2");
Tree actual2 = parse_in_arena(to_csubstr(ws2));
_showtrees(2);
test_compare(actual2, expected);
emitrs(actual2, &ws3);
}
{
SCOPED_TRACE("actual3");
Tree actual3 = parse_in_arena(to_csubstr(ws3));
_showtrees(3);
test_compare(actual3, expected);
emitrs(actual3, &ws4);
}
{
SCOPED_TRACE("actual4");
Tree actual4 = parse_in_arena(to_csubstr(ws4));
_showtrees(4);
test_compare(actual4, expected);
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TEST(style, noflags)
{
Tree expected = parse_in_arena("{}");
NodeRef r = expected.rootref();
r["normal"] |= MAP;
r["normal"]["singleline"] = "foo";
r["normal"]["multiline"] |= MAP;
r["normal"]["multiline"]["____________"] = "foo";
r["normal"]["multiline"]["____mid_____"] = "foo\nbar";
r["normal"]["multiline"]["____mid_end1"] = "foo\nbar\n";
r["normal"]["multiline"]["____mid_end2"] = "foo\nbar\n\n";
r["normal"]["multiline"]["____mid_end3"] = "foo\nbar\n\n\n";
r["normal"]["multiline"]["____________"] = "foo";
r["normal"]["multiline"]["____________"] = "foo bar";
r["normal"]["multiline"]["________end1"] = "foo bar\n";
r["normal"]["multiline"]["________end2"] = "foo bar\n\n";
r["normal"]["multiline"]["________end3"] = "foo bar\n\n\n";
r["normal"]["multiline"]["beg_________"] = "\nfoo";
r["normal"]["multiline"]["beg_mid_____"] = "\nfoo\nbar";
r["normal"]["multiline"]["beg_mid_end1"] = "\nfoo\nbar\n";
r["normal"]["multiline"]["beg_mid_end2"] = "\nfoo\nbar\n\n";
r["normal"]["multiline"]["beg_mid_end3"] = "\nfoo\nbar\n\n\n";
r["leading_ws"] |= MAP;
r["leading_ws"]["singleline"] |= MAP;
r["leading_ws"]["singleline"]["space"] = " foo";
r["leading_ws"]["singleline"]["tab"] = "\tfoo";
r["leading_ws"]["singleline"]["space_and_tab0"] = " \tfoo";
r["leading_ws"]["singleline"]["space_and_tab1"] = "\t foo";
r["leading_ws"]["multiline"] |= MAP;
r["leading_ws"]["multiline"]["beg_________"] = "\n \tfoo";
r["leading_ws"]["multiline"]["beg_mid_____"] = "\n \tfoo\nbar";
r["leading_ws"]["multiline"]["beg_mid_end1"] = "\n \tfoo\nbar\n";
r["leading_ws"]["multiline"]["beg_mid_end2"] = "\n \tfoo\nbar\n\n";
r["leading_ws"]["multiline"]["beg_mid_end3"] = "\n \tfoo\nbar\n\n\n";
check_same_emit(expected);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifdef WIP
TEST(style, scalar_retains_style_after_parse)
{
{
Tree t = parse_in_arena("foo");
EXPECT_TRUE(t.rootref().type().val_marked_plain());
EXPECT_FALSE(t.rootref().type().val_marked_squo());
EXPECT_FALSE(t.rootref().type().val_marked_dquo());
EXPECT_FALSE(t.rootref().type().val_marked_literal());
EXPECT_FALSE(t.rootref().type().val_marked_folded());
EXPECT_EQ(emitrs<std::string>(t), std::string("foo\n"));
}
{
Tree t = parse_in_arena("'foo'");
EXPECT_FALSE(t.rootref().type().val_marked_plain());
EXPECT_TRUE(t.rootref().type().val_marked_squo());
EXPECT_FALSE(t.rootref().type().val_marked_dquo());
EXPECT_FALSE(t.rootref().type().val_marked_literal());
EXPECT_FALSE(t.rootref().type().val_marked_folded());
EXPECT_EQ(emitrs<std::string>(t), std::string("'foo'\n"));
}
{
Tree t = parse_in_arena("'foo'");
EXPECT_FALSE(t.rootref().type().val_marked_plain());
EXPECT_FALSE(t.rootref().type().val_marked_squo());
EXPECT_TRUE(t.rootref().type().val_marked_dquo());
EXPECT_FALSE(t.rootref().type().val_marked_literal());
EXPECT_FALSE(t.rootref().type().val_marked_folded());
EXPECT_EQ(emitrs<std::string>(t), std::string("'foo'\n"));
}
{
Tree t = parse_in_arena("[foo, 'baz', \"bat\"]");
EXPECT_TRUE(t.rootref().type().marked_flow());
EXPECT_TRUE(t[0].type().val_marked_plain());
EXPECT_FALSE(t[0].type().val_marked_squo());
EXPECT_FALSE(t[0].type().val_marked_dquo());
EXPECT_FALSE(t[0].type().val_marked_literal());
EXPECT_FALSE(t[0].type().val_marked_folded());
EXPECT_FALSE(t[1].type().val_marked_plain());
EXPECT_TRUE(t[1].type().val_marked_squo());
EXPECT_FALSE(t[1].type().val_marked_dquo());
EXPECT_FALSE(t[1].type().val_marked_literal());
EXPECT_FALSE(t[1].type().val_marked_folded());
EXPECT_FALSE(t[2].type().val_marked_plain());
EXPECT_FALSE(t[2].type().val_marked_squo());
EXPECT_TRUE(t[2].type().val_marked_dquo());
EXPECT_FALSE(t[2].type().val_marked_literal());
EXPECT_FALSE(t[2].type().val_marked_folded());
EXPECT_EQ(emitrs<std::string>(t), std::string("foo"));
}
}
#endif
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TEST(scalar, base)
{
Tree tree = parse_in_arena(scalar_yaml);
EXPECT_EQ(tree[0].key(), csubstr("this is the key"));
EXPECT_EQ(tree[0].val(), csubstr("this is the multiline \"val\" with\n'empty' lines"));
EXPECT_EQ(emit2str(tree), R"(this is the key: |-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
TEST(scalar, block_literal)
{
Tree tree = parse_in_arena(scalar_yaml);
{
SCOPED_TRACE("val only");
EXPECT_FALSE(tree[0].type().key_marked_literal());
EXPECT_FALSE(tree[0].type().val_marked_literal());
tree._add_flags(tree[0].id(), _WIP_VAL_LITERAL);
EXPECT_FALSE(tree[0].type().key_marked_literal());
EXPECT_TRUE(tree[0].type().val_marked_literal());
EXPECT_EQ(emit2str(tree), R"(this is the key: |-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
{
SCOPED_TRACE("key+val");
tree._add_flags(tree[0].id(), _WIP_KEY_LITERAL);
EXPECT_TRUE(tree[0].type().key_marked_literal());
EXPECT_TRUE(tree[0].type().val_marked_literal());
EXPECT_EQ(emit2str(tree), R"(? |-
this is the key
: |-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
{
SCOPED_TRACE("key only");
tree._rem_flags(tree[0].id(), _WIP_VAL_LITERAL);
EXPECT_TRUE(tree[0].type().key_marked_literal());
EXPECT_FALSE(tree[0].type().val_marked_literal());
EXPECT_EQ(emit2str(tree), R"(? |-
this is the key
: |-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
}
TEST(scalar, block_folded)
{
Tree tree = parse_in_arena(scalar_yaml);
{
SCOPED_TRACE("val only");
EXPECT_FALSE(tree[0].type().key_marked_folded());
EXPECT_FALSE(tree[0].type().val_marked_folded());
tree._add_flags(tree[0].id(), _WIP_VAL_FOLDED);
EXPECT_FALSE(tree[0].type().key_marked_folded());
EXPECT_TRUE(tree[0].type().val_marked_folded());
EXPECT_EQ(emit2str(tree), R"(this is the key: >-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
{
SCOPED_TRACE("key+val");
tree._add_flags(tree[0].id(), _WIP_KEY_FOLDED);
EXPECT_TRUE(tree[0].type().key_marked_folded());
EXPECT_TRUE(tree[0].type().val_marked_folded());
EXPECT_EQ(emit2str(tree), R"(? >-
this is the key
: >-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
{
SCOPED_TRACE("val only");
tree._rem_flags(tree[0].id(), _WIP_VAL_FOLDED);
EXPECT_TRUE(tree[0].type().key_marked_folded());
EXPECT_FALSE(tree[0].type().val_marked_folded());
EXPECT_EQ(emit2str(tree), R"(? >-
this is the key
: |-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
}
TEST(scalar, squot)
{
Tree tree = parse_in_arena(scalar_yaml);
EXPECT_FALSE(tree[0].type().key_marked_squo());
EXPECT_FALSE(tree[0].type().val_marked_squo());
{
SCOPED_TRACE("val only");
tree._add_flags(tree[0].id(), _WIP_VAL_SQUO);
EXPECT_FALSE(tree[0].type().key_marked_squo());
EXPECT_TRUE(tree[0].type().val_marked_squo());
EXPECT_EQ(emit2str(tree), R"(this is the key: 'this is the multiline "val" with
''empty'' lines'
)");
check_same_emit(tree);
}
{
SCOPED_TRACE("key+val");
tree._add_flags(tree[0].id(), _WIP_KEY_SQUO);
EXPECT_TRUE(tree[0].type().key_marked_squo());
EXPECT_TRUE(tree[0].type().val_marked_squo());
EXPECT_EQ(emit2str(tree), R"('this is the key': 'this is the multiline "val" with
''empty'' lines'
)");
check_same_emit(tree);
}
{
SCOPED_TRACE("key only");
tree._rem_flags(tree[0].id(), _WIP_VAL_SQUO);
EXPECT_TRUE(tree[0].type().key_marked_squo());
EXPECT_FALSE(tree[0].type().val_marked_squo());
EXPECT_EQ(emit2str(tree), R"('this is the key': |-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
}
TEST(scalar, dquot)
{
Tree tree = parse_in_arena(scalar_yaml);
EXPECT_FALSE(tree[0].type().key_marked_dquo());
EXPECT_FALSE(tree[0].type().val_marked_dquo());
{
SCOPED_TRACE("val only");
tree._add_flags(tree[0].id(), _WIP_VAL_DQUO);
EXPECT_FALSE(tree[0].type().key_marked_dquo());
EXPECT_TRUE(tree[0].type().val_marked_dquo());
// visual studio fails to compile this string when used inside
// the EXPECT_EQ() macro below. So we declare it separately
// instead:
csubstr yaml = R"(this is the key: "this is the multiline \"val\" with
'empty' lines"
)";
EXPECT_EQ(emit2str(tree), yaml);
check_same_emit(tree);
}
{
SCOPED_TRACE("key+val");
tree._add_flags(tree[0].id(), _WIP_KEY_DQUO);
EXPECT_TRUE(tree[0].type().key_marked_dquo());
EXPECT_TRUE(tree[0].type().val_marked_dquo());
// visual studio fails to compile this string when used inside
// the EXPECT_EQ() macro below. So we declare it separately
// instead:
csubstr yaml = R"("this is the key": "this is the multiline \"val\" with
'empty' lines"
)";
EXPECT_EQ(emit2str(tree), yaml);
check_same_emit(tree);
}
{
SCOPED_TRACE("key only");
tree._rem_flags(tree[0].id(), _WIP_VAL_DQUO);
EXPECT_TRUE(tree[0].type().key_marked_dquo());
EXPECT_FALSE(tree[0].type().val_marked_dquo());
EXPECT_EQ(emit2str(tree), R"("this is the key": |-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
}
TEST(scalar, plain)
{
Tree tree = parse_in_arena(scalar_yaml);
EXPECT_FALSE(tree[0].type().key_marked_plain());
EXPECT_FALSE(tree[0].type().val_marked_plain());
{
SCOPED_TRACE("val only");
tree._add_flags(tree[0].id(), _WIP_VAL_PLAIN);
EXPECT_FALSE(tree[0].type().key_marked_plain());
EXPECT_TRUE(tree[0].type().val_marked_plain());
EXPECT_EQ(emit2str(tree), R"(this is the key: this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
{
SCOPED_TRACE("key+val");
tree._add_flags(tree[0].id(), _WIP_KEY_PLAIN);
EXPECT_TRUE(tree[0].type().key_marked_plain());
EXPECT_TRUE(tree[0].type().val_marked_plain());
EXPECT_EQ(emit2str(tree), R"(this is the key: this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
{
SCOPED_TRACE("key only");
tree._rem_flags(tree[0].id(), _WIP_VAL_PLAIN);
EXPECT_TRUE(tree[0].type().key_marked_plain());
EXPECT_FALSE(tree[0].type().val_marked_plain());
EXPECT_EQ(emit2str(tree), R"(this is the key: |-
this is the multiline "val" with
'empty' lines
)");
check_same_emit(tree);
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TEST(stream, block)
{
Tree tree = parse_in_arena(R"(
---
scalar
%YAML 1.2
---
foo
---
bar
)");
EXPECT_TRUE(tree.rootref().is_stream());
EXPECT_TRUE(tree.docref(0).is_doc());
EXPECT_TRUE(tree.docref(0).is_val());
EXPECT_EQ(emit2str(tree), "--- scalar %YAML 1.2\n--- foo\n--- bar\n");
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
EXPECT_EQ(emit2str(tree), "--- scalar %YAML 1.2\n--- foo\n--- bar\n");
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TEST(seq, block)
{
Tree tree = parse_in_arena("[1, 2, 3, 4, 5, 6]");
EXPECT_EQ(emit2str(tree), R"(- 1
- 2
- 3
- 4
- 5
- 6
)");
}
TEST(seq, flow_sl)
{
Tree tree = parse_in_arena("[1, 2, 3, 4, 5, 6]");
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
EXPECT_EQ(emit2str(tree), R"([1,2,3,4,5,6])");
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TEST(keyseq, block)
{
Tree tree = parse_in_arena("{foo: [1, 2, 3, 4, 5, 6]}");
EXPECT_TRUE(tree.rootref().type().default_block());
EXPECT_EQ(emit2str(tree), R"(foo:
- 1
- 2
- 3
- 4
- 5
- 6
)");
tree = parse_in_arena("{foo: [1, [2, 3], 4, [5, 6]]}");
EXPECT_EQ(emit2str(tree), R"(foo:
- 1
- - 2
- 3
- 4
- - 5
- 6
)");
}
TEST(keyseq, flow_sl)
{
Tree tree = parse_in_arena("{foo: [1, 2, 3, 4, 5, 6]}");
EXPECT_TRUE(tree.rootref().type().default_block());
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
EXPECT_FALSE(tree.rootref().type().default_block());
EXPECT_EQ(emit2str(tree), R"({foo: [1,2,3,4,5,6]})");
//
tree = parse_in_arena("{foo: [1, [2, 3], 4, [5, 6]]}");
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
EXPECT_EQ(emit2str(tree), R"({foo: [1,[2,3],4,[5,6]]})");
//
tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
tree._add_flags(tree["foo"][1].id(), _WIP_STYLE_FLOW_SL);
tree._add_flags(tree["foo"][3].id(), _WIP_STYLE_FLOW_SL);
EXPECT_EQ(emit2str(tree), R"(foo:
- 1
- [2,3]
- 4
- [5,6]
)");
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TEST(map, block)
{
Tree tree = parse_in_arena("{1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}");
EXPECT_EQ(emit2str(tree), R"(1: 10
2: 10
3: 10
4: 10
5: 10
6: 10
)");
}
TEST(map, flow_sl)
{
Tree tree = parse_in_arena("{1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}");
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
EXPECT_EQ(emit2str(tree), R"({1: 10,2: 10,3: 10,4: 10,5: 10,6: 10})");
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TEST(keymap, block)
{
Tree tree = parse_in_arena("{foo: {1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}}");
EXPECT_EQ(emit2str(tree), R"(foo:
1: 10
2: 10
3: 10
4: 10
5: 10
6: 10
)");
}
TEST(keymap, flow_sl)
{
Tree tree = parse_in_arena("{foo: {1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}}");
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
EXPECT_EQ(emit2str(tree), R"({foo: {1: 10,2: 10,3: 10,4: 10,5: 10,6: 10}})");
//
tree = parse_in_arena("{foo: {1: 10, 2: {2: 10, 3: 10}, 4: 10, 5: {5: 10, 6: 10}}}");
EXPECT_EQ(emit2str(tree), R"(foo:
1: 10
2:
2: 10
3: 10
4: 10
5:
5: 10
6: 10
)");
tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
EXPECT_EQ(emit2str(tree), R"({foo: {1: 10,2: {2: 10,3: 10},4: 10,5: {5: 10,6: 10}}})");
tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL);
tree._add_flags(tree["foo"][1].id(), _WIP_STYLE_FLOW_SL);
tree._add_flags(tree["foo"][3].id(), _WIP_STYLE_FLOW_SL);
EXPECT_EQ(emit2str(tree), R"(foo:
1: 10
2: {2: 10,3: 10}
4: 10
5: {5: 10,6: 10}
)");
}
//-------------------------------------------
// this is needed to use the test case library
Case const* get_case(csubstr /*name*/)
{
return nullptr;
}
} // namespace yml
} // namespace c4
| 32.04376 | 91 | 0.530019 | fargies |
a973eeb8b5a9e4755937fe237f6a9d598744d314 | 26,091 | cc | C++ | src/storage/fshost/block-watcher-test.cc | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | 2 | 2020-08-16T15:32:35.000Z | 2021-11-07T20:09:46.000Z | src/storage/fshost/block-watcher-test.cc | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | null | null | null | src/storage/fshost/block-watcher-test.cc | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia 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 <fuchsia/device/llcpp/fidl.h>
#include <fuchsia/fshost/llcpp/fidl.h>
#include <lib/devmgr-integration-test/fixture.h>
#include <lib/driver-integration-test/fixture.h>
#include <lib/fdio/cpp/caller.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/watcher.h>
#include <zircon/assert.h>
#include <zircon/device/block.h>
#include <zircon/hw/gpt.h>
#include <ramdevice-client/ramdisk.h>
#include <zxtest/zxtest.h>
#include "block-device-interface.h"
#include "block-watcher-test-data.h"
#include "encrypted-volume-interface.h"
namespace {
using devmgr_integration_test::RecursiveWaitForFile;
using driver_integration_test::IsolatedDevmgr;
class MockBlockDevice : public devmgr::BlockDeviceInterface {
public:
disk_format_t GetFormat() override = 0;
void SetFormat(disk_format_t format) override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
bool Netbooting() override { return false; }
zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override {
fuchsia_hardware_block_BlockInfo info = {};
info.flags = 0;
info.block_size = 512;
info.block_count = 1024;
*out_info = info;
return ZX_OK;
}
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
zx_status_t AttachDriver(const std::string_view& driver) override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
zx_status_t UnsealZxcrypt() override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path,
bool* is_path) override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
zx_status_t FormatZxcrypt() override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
bool ShouldCheckFilesystems() override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
zx_status_t CheckFilesystem() override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
zx_status_t FormatFilesystem() override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
zx_status_t MountFilesystem() override {
ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__);
}
};
// Tests adding a device which has no GUID and an unknown format.
TEST(AddDeviceTestCase, AddUnknownDevice) {
class UnknownDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
return ZX_ERR_NOT_SUPPORTED;
}
};
UnknownDevice device;
EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add());
}
// Tests adding a device with an unknown GUID and unknown format.
TEST(AddDeviceTestCase, AddUnknownPartition) {
class UnknownDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
const uint8_t expected[GPT_GUID_LEN] = GUID_EMPTY_VALUE;
memcpy(out_guid->value, expected, sizeof(expected));
return ZX_OK;
}
};
UnknownDevice device;
EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add());
}
// Tests adding a device which is smaller than the expected header size
TEST(AddDeviceTestCase, AddSmallDevice) {
class SmallDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override {
fuchsia_hardware_block_BlockInfo info = {};
info.flags = 0;
info.block_size = 512;
info.block_count = 1;
*out_info = info;
return ZX_OK;
}
};
SmallDevice device;
EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add());
}
// Tests adding a device with a GPT format.
TEST(AddDeviceTestCase, AddGPTDevice) {
class GptDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_GPT; }
zx_status_t AttachDriver(const std::string_view& driver) final {
EXPECT_STR_EQ(devmgr::kGPTDriverPath, driver.data());
attached = true;
return ZX_OK;
}
bool attached = false;
};
GptDevice device;
EXPECT_OK(device.Add());
EXPECT_TRUE(device.attached);
}
// Tests adding a device with an FVM format.
TEST(AddDeviceTestCase, AddFVMDevice) {
class FvmDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_FVM; }
zx_status_t AttachDriver(const std::string_view& driver) final {
EXPECT_STR_EQ(devmgr::kFVMDriverPath, driver.data());
attached = true;
return ZX_OK;
}
bool attached = false;
};
FvmDevice device;
EXPECT_OK(device.Add());
EXPECT_TRUE(device.attached);
}
// Tests adding a device with an MBR format.
TEST(AddDeviceTestCase, AddMBRDevice) {
class MbrDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_MBR; }
zx_status_t AttachDriver(const std::string_view& driver) final {
EXPECT_STR_EQ(devmgr::kMBRDriverPath, driver.data());
attached = true;
return ZX_OK;
}
bool attached = false;
};
MbrDevice device;
EXPECT_OK(device.Add());
EXPECT_TRUE(device.attached);
}
// Tests adding a device with a factory GUID but an unknown disk format.
TEST(AddDeviceTestCase, AddUnformattedBlockVerityDevice) {
class BlockVerityDevice : public MockBlockDevice {
public:
// in FCT mode we need to be able to bind the block-verity driver to devices that don't yet
// have detectable magic, so Add relies on the gpt guid.
disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; }
zx_status_t AttachDriver(const std::string_view& driver) final {
EXPECT_STR_EQ(devmgr::kBlockVerityDriverPath, driver.data());
attached = true;
return ZX_OK;
}
zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path,
bool* is_path) final {
EXPECT_STR_EQ("/mutable/block", expected_path.data());
*is_path = false;
return ZX_OK;
}
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
*out_guid = GPT_FACTORY_TYPE_GUID;
return ZX_OK;
}
bool attached = false;
};
BlockVerityDevice device;
EXPECT_OK(device.Add());
EXPECT_TRUE(device.attached);
}
// Tests adding a device with a factory GUID but an unknown disk format with the topological path
// suffix /mutable/block
TEST(AddDeviceTestCase, AddUnformattedMutableBlockVerityDevice) {
class BlockVerityDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; }
zx_status_t AttachDriver(const std::string_view& driver) final {
ADD_FATAL_FAILURE("Should not attach a driver");
return ZX_OK;
}
zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path,
bool* is_path) final {
EXPECT_STR_EQ("/mutable/block", expected_path.data());
*is_path = true;
return ZX_OK;
}
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
*out_guid = GPT_FACTORY_TYPE_GUID;
return ZX_OK;
}
};
BlockVerityDevice device;
EXPECT_OK(device.Add());
}
// Tests adding a device with the block-verity disk format.
TEST(AddDeviceTestCase, AddFormattedBlockVerityDevice) {
class BlockVerityDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_BLOCK_VERITY; }
zx_status_t AttachDriver(const std::string_view& driver) final {
EXPECT_STR_EQ(devmgr::kBlockVerityDriverPath, driver.data());
attached = true;
return ZX_OK;
}
bool attached = false;
};
BlockVerityDevice device;
EXPECT_OK(device.Add());
EXPECT_TRUE(device.attached);
}
// Tests adding blobfs which does not not have a valid type GUID.
TEST(AddDeviceTestCase, AddNoGUIDBlobDevice) {
class BlobDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
*out_guid = GUID_TEST_VALUE;
return ZX_OK;
}
zx_status_t CheckFilesystem() final {
ADD_FATAL_FAILURE("Should not check filesystem");
return ZX_OK;
}
zx_status_t MountFilesystem() final {
ADD_FATAL_FAILURE("Should not mount filesystem");
return ZX_OK;
}
};
BlobDevice device;
EXPECT_EQ(ZX_ERR_INVALID_ARGS, device.Add());
}
// Tests adding blobfs with a valid type GUID, but invalid metadata.
TEST(AddDeviceTestCase, AddInvalidBlobDevice) {
class BlobDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
const uint8_t expected[GPT_GUID_LEN] = GUID_BLOB_VALUE;
memcpy(out_guid->value, expected, sizeof(expected));
return ZX_OK;
}
zx_status_t CheckFilesystem() final {
checked = true;
return ZX_ERR_BAD_STATE;
}
zx_status_t FormatFilesystem() final {
formatted = true;
return ZX_OK;
}
zx_status_t MountFilesystem() final {
mounted = true;
return ZX_OK;
}
bool checked = false;
bool formatted = false;
bool mounted = false;
};
BlobDevice device;
EXPECT_EQ(ZX_ERR_BAD_STATE, device.Add());
EXPECT_TRUE(device.checked);
EXPECT_FALSE(device.formatted);
EXPECT_FALSE(device.mounted);
}
// Tests adding blobfs with a valid type GUID and valid metadata.
TEST(AddDeviceTestCase, AddValidBlobDevice) {
class BlobDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
const uint8_t expected[GPT_GUID_LEN] = GUID_BLOB_VALUE;
memcpy(out_guid->value, expected, sizeof(expected));
return ZX_OK;
}
zx_status_t CheckFilesystem() final {
checked = true;
return ZX_OK;
}
zx_status_t FormatFilesystem() final {
formatted = true;
return ZX_OK;
}
zx_status_t MountFilesystem() final {
mounted = true;
return ZX_OK;
}
bool checked = false;
bool formatted = false;
bool mounted = false;
};
BlobDevice device;
EXPECT_OK(device.Add());
EXPECT_TRUE(device.checked);
EXPECT_FALSE(device.formatted);
EXPECT_TRUE(device.mounted);
}
// Tests adding minfs which does not not have a valid type GUID.
TEST(AddDeviceTestCase, AddNoGUIDMinfsDevice) {
class MinfsDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_MINFS; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
*out_guid = GUID_TEST_VALUE;
return ZX_OK;
}
zx_status_t CheckFilesystem() final {
ADD_FATAL_FAILURE("Should not check filesystem");
return ZX_OK;
}
zx_status_t MountFilesystem() final {
ADD_FATAL_FAILURE("Should not mount filesystem");
return ZX_OK;
}
};
MinfsDevice device;
EXPECT_EQ(ZX_ERR_INVALID_ARGS, device.Add());
}
// Tests adding minfs with a valid type GUID and invalid metadata. Observe that
// the filesystem reformats itself.
TEST(AddDeviceTestCase, AddInvalidMinfsDevice) {
class MinfsDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_MINFS; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE;
memcpy(out_guid->value, expected, sizeof(expected));
return ZX_OK;
}
zx_status_t CheckFilesystem() final {
checked = true;
return ZX_ERR_BAD_STATE;
}
zx_status_t FormatFilesystem() final {
formatted = true;
return ZX_OK;
}
zx_status_t MountFilesystem() final {
mounted = true;
return ZX_OK;
}
bool checked = false;
bool formatted = false;
bool mounted = false;
};
MinfsDevice device;
EXPECT_OK(device.Add());
EXPECT_TRUE(device.checked);
EXPECT_TRUE(device.formatted);
EXPECT_TRUE(device.mounted);
}
// Tests adding minfs with a valid type GUID and invalid format. Observe that
// the filesystem reformats itself.
TEST(AddDeviceTestCase, AddUnknownFormatMinfsDevice) {
class MinfsDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return format; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE;
memcpy(out_guid->value, expected, sizeof(expected));
return ZX_OK;
}
zx_status_t FormatFilesystem() final {
formatted = true;
return ZX_OK;
}
zx_status_t CheckFilesystem() final { return ZX_OK; }
zx_status_t MountFilesystem() final {
EXPECT_TRUE(formatted);
mounted = true;
return ZX_OK;
}
zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final {
*is_unsealed_zxcrypt = true;
return ZX_OK;
}
void SetFormat(disk_format_t f) final { format = f; }
disk_format_t format = DISK_FORMAT_UNKNOWN;
bool formatted = false;
bool mounted = false;
};
MinfsDevice device;
EXPECT_FALSE(device.formatted);
EXPECT_FALSE(device.mounted);
EXPECT_OK(device.Add());
EXPECT_TRUE(device.formatted);
EXPECT_TRUE(device.mounted);
}
// Tests adding zxcrypt with a valid type GUID and invalid format. Observe that
// the partition reformats itself.
TEST(AddDeviceTestCase, AddUnknownFormatZxcryptDevice) {
class ZxcryptDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return format; }
zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final {
const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE;
memcpy(out_guid->value, expected, sizeof(expected));
return ZX_OK;
}
zx_status_t FormatZxcrypt() final {
formatted_zxcrypt = true;
return ZX_OK;
}
zx_status_t FormatFilesystem() final {
formatted_filesystem = true;
return ZX_OK;
}
zx_status_t CheckFilesystem() final { return ZX_OK; }
zx_status_t UnsealZxcrypt() final { return ZX_OK; }
zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final {
*is_unsealed_zxcrypt = false;
return ZX_OK;
}
void SetFormat(disk_format_t f) final { format = f; }
zx_status_t AttachDriver(const std::string_view& driver) final {
EXPECT_STR_EQ(devmgr::kZxcryptDriverPath, driver.data());
return ZX_OK;
}
disk_format_t format = DISK_FORMAT_UNKNOWN;
bool formatted_zxcrypt = false;
bool formatted_filesystem = false;
};
ZxcryptDevice device;
EXPECT_OK(device.Add());
EXPECT_TRUE(device.formatted_zxcrypt);
EXPECT_FALSE(device.formatted_filesystem);
}
// Tests adding a boot partition device with unknown format can be added with
// the correct driver.
TEST(AddDeviceTestCase, AddUnknownFormatBootPartitionDevice) {
class BootPartDevice : public MockBlockDevice {
public:
disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; }
zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override {
fuchsia_hardware_block_BlockInfo info = {};
info.flags = BLOCK_FLAG_BOOTPART;
info.block_size = 512;
info.block_count = 1024;
*out_info = info;
return ZX_OK;
}
zx_status_t AttachDriver(const std::string_view& driver) final {
EXPECT_STR_EQ(devmgr::kBootpartDriverPath, driver.data());
return ZX_OK;
}
zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final {
*is_unsealed_zxcrypt = false;
checked_unsealed_zxcrypt = true;
return ZX_OK;
}
bool checked_unsealed_zxcrypt = false;
};
BootPartDevice device;
EXPECT_OK(device.Add());
EXPECT_FALSE(device.checked_unsealed_zxcrypt);
}
TEST(AddDeviceTestCase, AddPermanentlyMiskeyedZxcryptVolume) {
class ZxcryptVolume : public devmgr::EncryptedVolumeInterface {
public:
zx_status_t Unseal() final {
// Simulate a device where we've lost the key -- can't unlock until we
// format the device with a new key, but can afterwards.
if (formatted) {
postformat_unseal_attempt_count++;
return ZX_OK;
} else {
preformat_unseal_attempt_count++;
return ZX_ERR_ACCESS_DENIED;
}
}
zx_status_t Format() final {
formatted = true;
return ZX_OK;
}
int preformat_unseal_attempt_count = 0;
int postformat_unseal_attempt_count = 0;
bool formatted = false;
};
ZxcryptVolume volume;
EXPECT_OK(volume.EnsureUnsealedAndFormatIfNeeded());
EXPECT_TRUE(volume.preformat_unseal_attempt_count > 1);
EXPECT_TRUE(volume.formatted);
EXPECT_EQ(volume.postformat_unseal_attempt_count, 1);
}
TEST(AddDeviceTestCase, AddTransientlyMiskeyedZxcryptVolume) {
class ZxcryptVolume : public devmgr::EncryptedVolumeInterface {
public:
zx_status_t Unseal() final {
// Simulate a transient error -- fail the first time we try to unseal the
// volume, but succeed on a retry or any subsequent attempt.
unseal_attempt_count++;
if (unseal_attempt_count > 1) {
return ZX_OK;
} else {
return ZX_ERR_ACCESS_DENIED;
}
}
zx_status_t Format() final {
// We expect this to never be called.
formatted = true;
return ZX_OK;
}
int unseal_attempt_count = 0;
bool formatted = false;
};
ZxcryptVolume volume;
EXPECT_OK(volume.EnsureUnsealedAndFormatIfNeeded());
EXPECT_FALSE(volume.formatted);
EXPECT_EQ(volume.unseal_attempt_count, 2);
}
TEST(AddDeviceTestCase, AddFailingZxcryptVolumeShouldNotFormat) {
class ZxcryptVolume : public devmgr::EncryptedVolumeInterface {
public:
zx_status_t Unseal() final {
// Errors that are not ZX_ERR_ACCESS_DENIED should not trigger
// formatting.
return ZX_ERR_INTERNAL;
}
zx_status_t Format() final {
// Expect this to not be called.
formatted = true;
return ZX_OK;
}
bool formatted = false;
};
ZxcryptVolume volume;
EXPECT_EQ(ZX_ERR_INTERNAL, volume.EnsureUnsealedAndFormatIfNeeded());
EXPECT_FALSE(volume.formatted);
}
class BlockWatcherTest : public zxtest::Test {
protected:
BlockWatcherTest() {
// Launch the isolated devmgr.
IsolatedDevmgr::Args args;
args.driver_search_paths.push_back("/boot/driver");
args.path_prefix = "/pkg/";
args.disable_block_watcher = false;
ASSERT_OK(IsolatedDevmgr::Create(&args, &devmgr_));
fbl::unique_fd fd;
ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), "misc/ramctl", &fd));
zx::channel remote;
ASSERT_OK(zx::channel::create(0, &watcher_chan_, &remote));
ASSERT_OK(fdio_service_connect_at(devmgr_.fshost_outgoing_dir().get(),
"/svc/fuchsia.fshost.BlockWatcher", remote.release()));
}
void CreateGptRamdisk(ramdisk_client** client) {
zx::vmo ramdisk_vmo;
ASSERT_OK(zx::vmo::create(kTestDiskSectors * kBlockSize, 0, &ramdisk_vmo));
// Write the GPT into the VMO.
ASSERT_OK(ramdisk_vmo.write(kTestGptProtectiveMbr, 0, sizeof(kTestGptProtectiveMbr)));
ASSERT_OK(ramdisk_vmo.write(kTestGptBlock1, kBlockSize, sizeof(kTestGptBlock1)));
ASSERT_OK(ramdisk_vmo.write(kTestGptBlock2, 2 * kBlockSize, sizeof(kTestGptBlock2)));
ASSERT_OK(
ramdisk_create_at_from_vmo(devmgr_.devfs_root().get(), ramdisk_vmo.release(), client));
}
void PauseWatcher() {
auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Pause(watcher_chan_.borrow());
ASSERT_OK(result.status());
ASSERT_OK(result->status);
}
void ResumeWatcher() {
auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Resume(watcher_chan_.borrow());
ASSERT_OK(result.status());
ASSERT_OK(result->status);
}
void WaitForBlockDevice(int number) {
auto path = fbl::StringPrintf("class/block/%03d", number);
fbl::unique_fd fd;
ASSERT_NO_FATAL_FAILURES(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd));
}
// Check that the number of block devices bound by the block watcher
// matches what we expect. Can only be called while the block watcher is running.
//
// This works by adding a new block device with a valid GPT.
// We then wait for that block device to appear at class/block/|next_device_number|.
// The block watcher should then bind the GPT driver to that block device, causing
// another entry in class/block to appear representing the only partition on the GPT.
//
// We make sure that this entry's toplogical path corresponds to it being the first partition
// of the block device we added.
void CheckEventsDropped(int* next_device_number, ramdisk_client** client) {
ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(client));
// Wait for the basic block driver to be bound
auto path = fbl::StringPrintf("class/block/%03d", *next_device_number);
*next_device_number += 1;
fbl::unique_fd fd;
ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd));
// And now, wait for the GPT driver to be bound, and the first
// partition to appear.
path = fbl::StringPrintf("class/block/%03d", *next_device_number);
*next_device_number += 1;
ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd));
// Figure out the expected topological path of the last block device.
std::string expected_path(ramdisk_get_path(*client));
expected_path = "/dev/" + expected_path + "/part-000/block";
zx_handle_t handle;
ASSERT_OK(fdio_get_service_handle(fd.release(), &handle));
zx::channel channel(handle);
// Get the actual topological path of the block device.
auto result = llcpp::fuchsia::device::Controller::Call::GetTopologicalPath(channel.borrow());
ASSERT_OK(result.status());
ASSERT_FALSE(result->result.is_err());
auto actual_path =
std::string(result->result.response().path.begin(), result->result.response().path.size());
// Make sure expected path matches the actual path.
ASSERT_EQ(expected_path, actual_path);
}
IsolatedDevmgr devmgr_;
zx::channel watcher_chan_;
};
TEST_F(BlockWatcherTest, TestBlockWatcherDisable) {
ASSERT_NO_FATAL_FAILURES(PauseWatcher());
int next_device_number = 0;
// Add a block device.
ramdisk_client* client;
ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client));
ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number));
next_device_number++;
ASSERT_NO_FATAL_FAILURES(ResumeWatcher());
ramdisk_client* client2;
ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client2));
ASSERT_OK(ramdisk_destroy(client));
ASSERT_OK(ramdisk_destroy(client2));
}
TEST_F(BlockWatcherTest, TestBlockWatcherAdd) {
int next_device_number = 0;
// Add a block device.
ramdisk_client* client;
ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client));
ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number));
next_device_number++;
ASSERT_NO_FATAL_FAILURES(PauseWatcher());
fbl::unique_fd fd;
// Look for the first partition of the device we just added.
ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), "class/block/001", &fd));
ASSERT_NO_FATAL_FAILURES(ResumeWatcher());
ASSERT_OK(ramdisk_destroy(client));
}
TEST_F(BlockWatcherTest, TestBlockWatcherUnmatchedResume) {
auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Resume(watcher_chan_.borrow());
ASSERT_OK(result.status());
ASSERT_STATUS(result->status, ZX_ERR_BAD_STATE);
}
TEST_F(BlockWatcherTest, TestMultiplePause) {
ASSERT_NO_FATAL_FAILURES(PauseWatcher());
ASSERT_NO_FATAL_FAILURES(PauseWatcher());
int next_device_number = 0;
// Add a block device.
ramdisk_client* client;
ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client));
ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number));
next_device_number++;
// Resume once.
ASSERT_NO_FATAL_FAILURES(ResumeWatcher());
ramdisk_client* client2;
ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client2));
ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number));
next_device_number++;
fbl::unique_fd fd;
RecursiveWaitForFile(devmgr_.devfs_root(), ramdisk_get_path(client2), &fd);
// Resume again. The block watcher should be running again.
ASSERT_NO_FATAL_FAILURES(ResumeWatcher());
// Make sure neither device was seen by the watcher.
ramdisk_client* client3;
ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client3));
// Pause again.
ASSERT_NO_FATAL_FAILURES(PauseWatcher());
ramdisk_client* client4;
ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client4));
ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number));
next_device_number++;
// Resume again.
ASSERT_NO_FATAL_FAILURES(ResumeWatcher());
// Make sure the last device wasn't added.
ramdisk_client* client5;
ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client5));
ASSERT_OK(ramdisk_destroy(client));
ASSERT_OK(ramdisk_destroy(client2));
ASSERT_OK(ramdisk_destroy(client3));
ASSERT_OK(ramdisk_destroy(client4));
ASSERT_OK(ramdisk_destroy(client5));
}
} // namespace
| 33.928479 | 99 | 0.722126 | oshunter |
a974357023fc1fe8281e98082fb732e715eb2cab | 700 | cpp | C++ | source/flow/audio-source-impl.cpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 15 | 2018-02-26T08:20:03.000Z | 2022-03-06T03:25:46.000Z | source/flow/audio-source-impl.cpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 32 | 2018-02-26T08:26:38.000Z | 2020-09-12T17:09:38.000Z | source/flow/audio-source-impl.cpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | null | null | null | #include "./audio-source-impl.hpp"
#include "./audio-engine-impl.hpp"
using namespace lava::flow;
AudioSource::Impl::Impl(AudioEngine::Impl& engine)
: m_engine(engine)
{
}
void AudioSource::Impl::playing(bool playing)
{
m_playing = playing;
playing ? restart() : finish();
}
void AudioSource::Impl::looping(bool looping)
{
m_looping = looping;
}
void AudioSource::Impl::removeOnFinish(bool removeOnFinish)
{
m_removeOnFinish = removeOnFinish;
}
// ----- Sub-class API
void AudioSource::Impl::finish()
{
m_playing = false;
if (m_removeOnFinish) {
m_engine.remove(*this);
}
else if (m_looping) {
m_playing = true;
restart();
}
}
| 16.666667 | 59 | 0.648571 | Breush |
a9747aa1bf77b04a7d6c15d9fb3132517e1e0429 | 3,699 | cpp | C++ | trunk/knewcode/kc_web_plugins/kc_web_page_data_expr/expr_item_if.cpp | zogyzen/knewcode | bd414a52330cde040ceaf91d1b380c402b2814b4 | [
"Apache-2.0"
] | null | null | null | trunk/knewcode/kc_web_plugins/kc_web_page_data_expr/expr_item_if.cpp | zogyzen/knewcode | bd414a52330cde040ceaf91d1b380c402b2814b4 | [
"Apache-2.0"
] | null | null | null | trunk/knewcode/kc_web_plugins/kc_web_page_data_expr/expr_item_if.cpp | zogyzen/knewcode | bd414a52330cde040ceaf91d1b380c402b2814b4 | [
"Apache-2.0"
] | null | null | null | #include "std.h"
#include "expr_item_if.h"
////////////////////////////////////////////////////////////////////////////////
// TOperandNode็ฑป
KC::TOperandNode::TOperandNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn)
: m_work(wk), m_pd(pd), m_pBeginPtr(syn.GetBeginPtr()), m_pEndPtr(syn.GetEndPtr()), m_LineID(pd.GetLineID(syn))
{
}
// ๅพๅฐ่กๅท
int KC::TOperandNode::GetLineID(void) const
{
return m_LineID;
}
////////////////////////////////////////////////////////////////////////////////
// TUnaryNode็ฑป
KC::TUnaryNode::TUnaryNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn)
: TOperandNode(wk, pd, syn)
{
}
// ่ทๅๅผ
boost::any KC::TUnaryNode::GetValue(IKCActionData& act)
{
// ๆไฝๆฐ
IOperandNode *pOperand = dynamic_cast<IOperandNode*>(OperandPtr.get());
if (nullptr == pOperand)
throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work);
// ่ทๅๆไฝๆฐ็ๅผ
boost::any val = pOperand->GetValue(act);
// ่ฟๅ่ฎก็ฎ็ปๆ
return this->Calculate(val);
}
////////////////////////////////////////////////////////////////////////////////
// TBinaryNode็ฑป
KC::TBinaryNode::TBinaryNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn)
: TOperandNode(wk, pd, syn)
{
}
// ่ทๅๅผ
boost::any KC::TBinaryNode::GetValue(IKCActionData& act)
{
// ๅทฆๆไฝๆฐ
IOperandNode *pOperandL = dynamic_cast<IOperandNode*>(OperandPtrL.get());
if (nullptr == pOperandL)
throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_left_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work);
boost::any valL = pOperandL->GetValue(act);
// ๅณๆไฝๆฐ
IOperandNode *pOperandR = dynamic_cast<IOperandNode*>(OperandPtrR.get());
if (nullptr == pOperandR)
throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_right_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work);
boost::any valR = pOperandR->GetValue(act);
// ่ฟๅ่ฎก็ฎ็ปๆ
return this->Calculate(valL, valR);
}
// ๅพๅฐ่ช้ๅบ็ฑปๅ็ๅทฆๅผ
boost::any KC::TBinaryNode::GetLValueNewType(boost::any& lv, boost::any& rv)
{
if (lv.empty())
{
if (rv.empty())
return string("");
else if (rv.type() == typeid(int))
return (int)0;
else if (rv.type() == typeid(double))
return (double)0;
else if (rv.type() == typeid(bool))
return false;
else
return string("");
}
else if (rv.empty() || lv.type() == rv.type()) return lv;
else if (lv.type() == typeid(bool))
{
if (rv.type() == typeid(int))
return boost::any_cast<bool>(lv) ? (int)1 : (int)0;
if (rv.type() == typeid(double))
return boost::any_cast<bool>(lv) ? (double)1 : (double)0;
else
return boost::any_cast<bool>(lv) ? string("true") : string("false");
}
else if (lv.type() == typeid(int))
{
if (rv.type() == typeid(bool))
return lv;
else if (rv.type() == typeid(double))
return (double)boost::any_cast<int>(lv);
else
return lexical_cast<string>(boost::any_cast<int>(lv));
}
else if (lv.type() == typeid(double))
{
if (rv.type() == typeid(bool) || rv.type() == typeid(int))
return lv;
else
return lexical_cast<string>(boost::any_cast<double>(lv));
}
else if (lv.type() == typeid(TKcWebInfVal))
return boost::any_cast<TKcWebInfVal>(lv).str();
else return lv;
}
| 34.570093 | 185 | 0.575561 | zogyzen |
a975fe3f4c047f3bb873ee5edd28042c6395a2e2 | 1,826 | cpp | C++ | libHCore/src/common/time.cpp | adeliktas/Hayha3 | a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5 | [
"MIT"
] | 15 | 2021-11-22T07:31:22.000Z | 2022-02-22T22:53:51.000Z | libHCore/src/common/time.cpp | adeliktas/Hayha3 | a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5 | [
"MIT"
] | 1 | 2021-11-26T19:27:40.000Z | 2021-11-26T19:27:40.000Z | libHCore/src/common/time.cpp | adeliktas/Hayha3 | a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5 | [
"MIT"
] | 5 | 2021-11-20T18:21:24.000Z | 2021-12-26T12:32:47.000Z |
#include "time.hpp"
timeStamp programStart;
timeStamp getCurrentTimeMicro(){
return time_point_cast<microseconds>(steady_clock::now());
}
timeStamp getTimeInFuture(uint64_t usec){
return time_point_cast<microseconds>(steady_clock::now()) + std::chrono::microseconds(usec);
}
int64_t getTimeDifference(timeStamp t0, timeStamp t1){
return duration_cast<microseconds>(t0 - t1).count();
}
int64_t timeSince(timeStamp t0){
return duration_cast<microseconds>(getCurrentTimeMicro() - t0).count();
}
int64_t timeTo(timeStamp t0){
return duration_cast<microseconds>(t0-getCurrentTimeMicro()).count();
}
int64_t timeSinceStart(timeStamp t0){
return duration_cast<microseconds>(t0 - programStart).count();
}
int64_t unixTime(timeStamp t0){
return duration_cast<seconds>(t0.time_since_epoch()).count();
}
/*
#include "time.hpp"
timeStamp programStart;
nanoseconds timespecToDuration(timespec ts){
auto duration = seconds{ts.tv_sec} + nanoseconds{ts.tv_nsec};
return duration_cast<nanoseconds>(duration);
}
time_point<system_clock, nanoseconds>timespecToTimePoint(timespec ts){
return time_point<system_clock, nanoseconds>{duration_cast<system_clock::duration>(timespecToDuration(ts))};
}
timeStamp getCurrentTimeMicro(){
timeStamp ts;
timespec_get(&ts.time, TIME_UTC);
return ts;
}
timeStamp getTimeInFuture(uint64_t usec){
timeStamp ts = getCurrentTimeMicro();
return ts + usec;
}
int64_t timeSince(timeStamp t0){
timeStamp ts = getCurrentTimeMicro() - t0;
int64_t since = ts.time.tv_sec * 1000000 + ts.time.tv_nsec / 1000;
return since;
}
int64_t timeTo(timeStamp t0){
return t0.micros();
}
int64_t getTimeDifference(timeStamp t0, timeStamp t1){
}
int64_t timeSinceStart(timeStamp t0){
}
int64_t unixTime(timeStamp t0);
*/ | 22 | 112 | 0.740416 | adeliktas |
a97e495e4da2e1d5c7884705e9d5bc03376111b1 | 2,444 | cpp | C++ | Source/Engine/Render/VertexArray.cpp | kukiric/SomeGame | 8c058d82a93bc3f276bbb3ec57a3978ae57de82c | [
"MIT"
] | null | null | null | Source/Engine/Render/VertexArray.cpp | kukiric/SomeGame | 8c058d82a93bc3f276bbb3ec57a3978ae57de82c | [
"MIT"
] | null | null | null | Source/Engine/Render/VertexArray.cpp | kukiric/SomeGame | 8c058d82a93bc3f276bbb3ec57a3978ae57de82c | [
"MIT"
] | null | null | null | #include "VertexArray.h"
#include <Engine/Render/API.h>
using namespace Render;
VertexArray::VertexArray()
: indexArraySize(0)
{
glGenVertexArrays(1, &handle);
glGenBuffers(1, &indexArrayID);
}
VertexArray::~VertexArray()
{
for(auto vbo : buffers) {
deleteBuffer(vbo.id);
}
glDeleteBuffers(1, &indexArrayID);
glDeleteVertexArrays(1, &handle);
}
int VertexArray::createBufferEx(void* data, size_t sizeElement, size_t numElements, GLenum usageHint)
{
// Create a new, null buffer
buffers.push_back({0, 0});
// Get a reference to it
auto& newVBO = buffers.back();
// Generate a buffer on its ID
glGenBuffers(1, &newVBO.id);
glBindBuffer(GL_ARRAY_BUFFER, newVBO.id);
glBufferData(GL_ARRAY_BUFFER, sizeElement * numElements, data, usageHint);
// Set the buffer size property
newVBO.count = numElements;
// And return the buffer's index in the array (last position)
return buffers.size()-1;
}
int VertexArray::deleteBuffer(int vbo)
{
if(vbo >= 0 and vbo < (int)buffers.size()) {
glDeleteBuffers(1, &buffers[vbo].id);
buffers.erase(buffers.begin() + vbo);
return vbo;
} else {
return -1;
}
}
int VertexArray::getBufferCount() const
{
return (int)buffers.size();
}
void VertexArray::setIndexArrayEx(void* data, size_t sizeElement, size_t numElements, GLenum usageHint)
{
if(data) {
glBindVertexArray(handle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexArrayID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeElement * numElements, data, usageHint);
indexArraySize = numElements;
} else {
indexArraySize = 0;
}
}
void VertexArray::addAttrib(GLuint index, int vbo, GLuint size, GLenum type, GLvoid* offset, GLint stride)
{
glBindVertexArray(handle);
glEnableVertexAttribArray(index);
glBindBuffer(GL_ARRAY_BUFFER, buffers[vbo].id);
glVertexAttribPointer(index, size, type, GL_FALSE, stride, offset);
}
void VertexArray::removeAttrib(GLuint index)
{
glBindVertexArray(handle);
glDisableVertexAttribArray(index);
}
void VertexArray::drawElements(GLenum mode)
{
glBindVertexArray(handle);
if(indexArraySize) {
glDrawElements(mode, indexArraySize, GL_UNSIGNED_INT, NULL);
} else {
glDrawArrays(mode, 0, buffers[0].count);
}
}
| 27.772727 | 107 | 0.661211 | kukiric |
a97edea22c6dbbc4626abc58a3cc4a41ff792ad1 | 7,562 | cpp | C++ | Chapter_20/program.cpp | 9ndres/Ray-Tracing-Gems-II | 5fef3b49375c823431ef06f8c67d1b44b432304a | [
"MIT"
] | 603 | 2021-08-04T11:46:33.000Z | 2022-03-28T12:12:31.000Z | Chapter_20/program.cpp | 9ndres/Ray-Tracing-Gems-II | 5fef3b49375c823431ef06f8c67d1b44b432304a | [
"MIT"
] | null | null | null | Chapter_20/program.cpp | 9ndres/Ray-Tracing-Gems-II | 5fef3b49375c823431ef06f8c67d1b44b432304a | [
"MIT"
] | 45 | 2021-08-04T18:57:37.000Z | 2022-03-11T11:33:49.000Z | #include "program_defs.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include <stdint.h>
#include <vector>
#include <random>
#ifdef WIN32
#define PCG_LITTLE_ENDIAN 1
#endif
#include "pcg_random.hpp"
// NOTE: Include order is a bit brittle due to some of these appearing exactly as they are int he RTG2 chapter.
#include "functions.h"
#include "balance_heuristic.h" // In article
#include "sample_lights.h" // In article
#include "sample_lights_pdf.h" // In article
//#include "material_lambert.h"
#include "material_rough.h"
#include "direct_light.h" // In article
#include "direct_cos.h" // In article
#include "direct_mat.h" // In article
#include "direct_mis.h" // In article
#include "pathtrace_mis.h" // In article
#include "pathtrace.h"
#include "trace_wrappers.h" // Add camera-trace to functions so they can be used
struct Random {
pcg32 rng;
std::uniform_real_distribution<float> uniform;
Random() {
pcg_extras::seed_seq_from<std::random_device> seed_source;
rng.seed(seed_source);
};
};
thread_local Random random;
// NOTE: uniform is thread-safe since random generator is in a thread_local variable
float uniform() {
return random.uniform(random.rng);
}
// NOTE: This function only applies gamma.
uint32_t convert_sRGB(vec3 color) {
float r = color.x, g = color.y, b = color.z;
r = min(max(r, 0.0), 1.0);
g = min(max(g, 0.0), 1.0);
b = min(max(b, 0.0), 1.0);
// TODO: Is this correct? Validate
r = powf(r, 1.0f/2.2f);
g = powf(g, 1.0f/2.2f);
b = powf(b, 1.0f/2.2f);
uint8_t rb = floor(r * 255.0f);
uint8_t gb = floor(g * 255.0f);
uint8_t bb = floor(b * 255.0f);
return 0xFF000000|(bb<<16)|(gb<<8)|rb;
}
inline vec3 camera_direction(float2 uv, int w, int h, float fov_horizontal_degrees) {
float aspect = float(h) / float(w);
float fov_factor = tanf(fov_horizontal_degrees * (float)(2.0 * PI / 360.0 * 0.5));
vec3 camera_forward = vec3(0.0f, 0.0f, 1.0f);
vec3 camera_right = vec3(1.0f, 0.0f, 0.0f);
vec3 camera_up = vec3(0.0f, 1.0f, 0.0f);
return normalize(camera_forward + camera_right * ((uv.x * 2.0 - 1.0) * fov_factor) + camera_up * ((uv.y * 2.0 - 1.0) * fov_factor * aspect));
}
typedef vec3(*renderFunction)(vec3 pos, vec3 normal);
void render(const std::string &dir, const std::string &filename, const renderFunction per_pixel, int subpixels, int w = 800, int h = 600, const std::string &filename_variance = "") {
printf("Rendering %s%s\n", dir.c_str(), filename.c_str());
int ws = subpixels, hs = subpixels;
// Camera definition
vec3 camera_pos = vec3(0.0f, 1.2f, -7.0f);
std::vector<uint32_t> result(w*h);
std::vector<uint32_t> result_variance;
if (!filename_variance.empty()) {
result_variance.resize(w * h);
}
#pragma omp parallel for // NOTE: Comment away this line to get single-threaded execution
for (int y=0; y<h; y++) {
for (int x=0; x<w; x++) {
vec3 mean = vec3(0);
vec3 M2 = vec3(0);
int N = 0;
for (int sy=0; sy<hs; sy++) {
for (int sx=0; sx<ws; sx++) {
float xc = (x + (sx + uniform()) / ws) * (1.0f / w);
float yc = (y + (sy + uniform()) / hs) * (1.0f / h);
yc = 1.0 - yc; // Turn y-coordinate upside down since image (0,0) is upper-left but we want (0,0) to be lower-left
// NOTE: A "real" renderer would have some sort of tone mapper here and use some filter kernel.
vec3 dir = camera_direction(float2(xc, yc), w, h, 70.0f);
vec3 color = per_pixel(camera_pos, dir);
// Welford's online algorithm so we get variance as well
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
N++;
vec3 delta = color - mean;
mean += delta/N;
vec3 delta2 = color - mean;
M2 += delta * delta2;
}
}
vec3 variance = M2/(N-1)/N; // Sample variance from Welford's online algorithm
result[y*w+x]= convert_sRGB(mean);
if (!result_variance.empty()) {
if (y<8) {
// Fill top-most 8 lines with pink so we don't mix the images
result_variance[y * w + x] = convert_sRGB(vec3(1.0, 0.0, 1.0));
} else {
result_variance[y * w + x] = convert_sRGB(vec3(sqrtf(variance.x), sqrtf(variance.y), sqrtf(variance.z)));
}
}
}
}
stbi_write_png((dir+filename).c_str(), w, h, 4, result.data(), w*4);
if (!filename_variance.empty()) {
stbi_write_png((dir + filename_variance).c_str(), w, h, 4, result_variance.data(), w * 4);
}
}
void render_mis_weights(const std::string& dir, const std::string &filename, int subpixels, int w = 800, int h = 600, const char* const filename_variance = nullptr) {
printf("Rendering %s%s\n", dir.c_str(), filename.c_str());
int ws = subpixels, hs = subpixels;
// Camera definition
vec3 camera_pos = vec3(0.0f, 1.2f, -7.0f);
std::vector<uint32_t> result(w*h);
#pragma omp parallel for // NOTE: Comment away this line to get single-threaded execution
for (int y=0; y<h; y++) {
for (int x=0; x<w; x++) {
vec3 mean_light = vec3(0);
vec3 mean_material = vec3(0);
int N = 0;
for (int sy=0; sy<hs; sy++) {
for (int sx=0; sx<ws; sx++) {
float xc = (x + (sx + uniform()) / ws) * (1.0f / w);
float yc = (y + (sy + uniform()) / hs) * (1.0f / h);
yc = 1.0 - yc; // Turn y-coordinate upside down since image (0,0) is upper-left but we want (0,0) to be lower-left
// NOTE: A "real" renderer would have some sort of tone mapper here and use some filter kernel.
vec3 dir = camera_direction(float2(xc, yc), w, h, 70.0f);
vec3 color_light = trace_direct_mis_light(camera_pos, dir);
vec3 color_material = trace_direct_mis_material(camera_pos, dir);
mean_light += color_light / (ws*hs);
mean_material += color_material / (ws*hs);
}
}
vec3 mean_full = mean_light + mean_material;
float a = dot(mean_light, mean_full);
float b = dot(mean_material, mean_full);
vec3 full = mean_light + mean_material;
mean_light.x /= full.x;
mean_light.y /= full.y;
mean_light.z /= full.z;
mean_material.x /= full.x;
mean_material.y /= full.y;
mean_material.z /= full.z;
float l = a/(a+b);
float m = b/(a+b);
vec3 color = vec3(m,0,0) + vec3(0,l,0);
result[y*w+x]= convert_sRGB(color);
}
}
stbi_write_png((dir + filename).c_str(), w, h, 4, result.data(), w*4);
}
void rtg2_figures(const char * const dir) {
// This is the code that was used to generate the images in the RTG2 chapter
int w = 512, h = 300;
// Direct light sampling
int direct_N = 10;
render(dir, "direct_light_sampling.png", { trace_direct_light_sampling}, direct_N, w, h);
render(dir, "direct_material_sampling.png", {trace_direct_material_sampling }, direct_N, w, h);
render(dir, "direct_cos_sampling.png", { trace_direct_cos_sampling }, direct_N, w, h);
render(dir, "direct_mis.png", { trace_direct_mis }, direct_N, w, h);
render(dir, "direct_mis_light.png", { trace_direct_mis_light<2> }, direct_N, w, h);
render(dir, "direct_mis_material.png", { trace_direct_mis_material<2> }, direct_N, w, h);
render(dir, "scene_description.png", { show_scene }, direct_N, w, h);
// Path tracing
int pathtrace_N = 15;
render(dir, "pathtrace_mis.png", { pathtrace_mis_helper }, pathtrace_N, w, h);
render(dir, "pathtrace_light_sampling.png", { pathtrace<direct_light> }, pathtrace_N, w, h);
//render(dir, "pathtrace_material_sampling.png", { pathtrace<direct_mat> }, pathtrace_N, w, h);
//render(dir, "pathtrace_hemisphere_sampling.png", { pathtrace<direct_hemi> }, pathtrace_N, w, h);
// Weight image for direct MIS
render_mis_weights(dir, "direct_mis_weights.png", 35, w, h);
}
int main(void) {
rtg2_figures("../figures/");
} | 35.336449 | 182 | 0.663052 | 9ndres |
a97f33d7b6158b151be24b213ddd9c1df1dde485 | 11,646 | cpp | C++ | examples/albumcalc/albumcalc.cpp | crf8472/libarcstk | b2c29006c7dda6476bf3e7098f51ee30675439fb | [
"MIT"
] | null | null | null | examples/albumcalc/albumcalc.cpp | crf8472/libarcstk | b2c29006c7dda6476bf3e7098f51ee30675439fb | [
"MIT"
] | null | null | null | examples/albumcalc/albumcalc.cpp | crf8472/libarcstk | b2c29006c7dda6476bf3e7098f51ee30675439fb | [
"MIT"
] | null | null | null | //
// Example for calculating AccurateRip checksums from each track of an album,
// represented by a CUESheet and a single losslessly encoded audio file.
//
#include <cstdint> // for uint32_t etc.
#include <cstdio> // for fopen, fclose, FILE
#include <iomanip> // for setw, setfill, hex
#include <iostream> // for cerr, cout
#include <stdexcept> // for runtime_error
#include <string> // for string
extern "C" {
#include <libcue/libcue.h> // libcue for parsing the CUEsheet
}
#include <sndfile.hh> // libsndfile for reading the audio file
#ifndef __LIBARCSTK_CALCULATE_HPP__ // libarcstk: calculate ARCSs
#include <arcstk/calculate.hpp>
#endif
#ifndef __LIBARCSTK_SAMPLES_HPP__ // libarcstk: normalize input samples
#include <arcstk/samples.hpp>
#endif
#ifndef __LIBARCSTK_LOGGING_HPP__ // libarcstk: log what you do
#include <arcstk/logging.hpp>
#endif
// ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
// NOTE! THIS IS EXAMPLE CODE! IT IS INTENDED TO DEMONSTRATE HOW LIBARCSTK COULD
// BE USED. IT IS NOT INTENDED TO BE USED IN REAL LIFE PRODUCTION. IT IS IN NO
// WAY TESTED FOR PRODUCTION. TAKE THIS AS A STARTING POINT TO YOUR OWN
// SOLUTION, NOT AS A TOOL.
// ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
/**
* \brief Parse a CUEsheet and return offsets and implicitly the track count.
*
* This method is implemented without any use of libarcstk. It just has to be
* available for parsing the CUESheet.
*
* @param[in] cuefilename Name of the CUEsheet file to parse
*
* @return STL-like container with a size_type holding offsets
*/
auto parse_cuesheet(const std::string &cuefilename)
{
FILE* f = std::fopen(cuefilename.c_str(), "r");
if (!f)
{
std::cerr << "Failed to open CUEsheet: " << cuefilename << std::endl;
throw std::runtime_error("Failed to open CUEsheet");
}
::Cd* cdinfo = ::cue_parse_file(f);
if (std::fclose(f))
{
std::cerr << "Failed to close CUEsheet: " << cuefilename << std::endl;
}
f = nullptr;
if (!cdinfo)
{
std::cerr << "Failed to parse CUEsheet: " << cuefilename << std::endl;
throw std::runtime_error("Failed to parse CUEsheet");
}
const auto track_count = ::cd_get_ntrack(cdinfo);
std::vector<int> offsets;
offsets.reserve(static_cast<decltype(offsets)::size_type>(track_count));
::Track* track = nullptr;
for (auto i = int { 1 }; i <= track_count; ++i)
{
track = ::cd_get_track(cdinfo, i);
if (!track)
{
offsets.emplace_back(0);
continue;
}
offsets.emplace_back(::track_get_start(track));
}
::cd_delete(cdinfo);
return offsets;
}
int main(int argc, char* argv[])
{
if (argc != 3)
{
std::cout << "Usage: albumcalc <cuesheet> <audiofile>" << std::endl;
return EXIT_SUCCESS;
}
// Of course you would validate your input parameters in production code.
const auto cuefilename { std::string { argv[1] }};
const auto audiofilename { std::string { argv[2] }};
// If you like, you can activate the internal logging of libarcstk to
// see what's going on behind the scenes. We provide an appender for stdout.
arcstk::Logging::instance().add_appender(
std::make_unique<arcstk::Appender>("stdout", stdout));
// 'INFO' means you should probably not see anything unless you give
// libarcstk unexpected input. Try 'DEBUG' or 'DEBUG1' if you want to
// see more about what libarcstk is doing with your input.
arcstk::Logging::instance().set_level(arcstk::LOGLEVEL::INFO);
// Define input block size in number of samples, where 'sample' means a
// 32 bit unsigned integer holding a pair of PCM 16 bit stereo samples.
const auto samples_per_block { 16777216 }; // == 64 MB block size
// libsndfile API provides the file handle for the audio file
SndfileHandle audiofile(audiofilename, SFM_READ);
// Skip any sanity checks you would do in production code...
// Calculation will have to distinguish the tracks in the audiofile.
// To identify the track bounds, we need the TOC, precisely:
// 1. the number of tracks
// 2. the track offset for each track
// 3. the leadout frame
// We derive 1. total number of tracks and 2. actual track offsets from
// parsing the CUEsheet. We skip the details here for libarcstk does not
// provide this functionality and the author just did a quick hack with
// libcue. (Just consult the implementation of function parse_cuesheet()
// if you are interested in the details, but this is libcue, not libarcstk.)
const auto offsets { parse_cuesheet(cuefilename) };
// Skip santiy checks and everything you could do with try/catch ...
// Two completed, one to go. Since the CUEsheet usually does not know the
// length of the last track, we have to derive the leadout frame from the
// audio data. We could do this quite convenient by using libarcstk's
// AudioReader::acquire_size() method. But thanks to libsndfile, this is
// not even necessary: the information is conveniently provided by the
// audiofile handle:
auto total_samples { arcstk::AudioSize {
audiofile.frames(), arcstk::AudioSize::UNIT::SAMPLES } };
// Remark: what libsndfile calls "frames" is what libarcstk calls
// "PCM 32 bit samples" or just "samples". Our "sample" represents a pair of
// 16 bit stereo samples as a single 32 bit unsigned int (left/right).
// Libsndfile's frame encodes the same information as 2 signed 16 bit
// integers, one per channel.
// We now have derived all relevant metadata from our input files.
// Let's print it one last time before starting with the real business:
for (decltype(offsets)::size_type i = 1; i < offsets.size(); ++i)
{
std::cout << "Track " << std::setw(2) << std::setfill(' ') << i
<< " offset: "
<< std::setw(6) << std::setfill(' ') << offsets[i-1]
<< std::endl;
}
std::cout << "Track count: " << offsets.size() << std::endl;
std::cout << "Leadout: " << total_samples.leadout_frame() << std::endl;
// Step 1: Use libarcstk to construct the TOC.
auto toc { std::unique_ptr<arcstk::TOC> { nullptr }};
try
{
// This validates the parsed toc data and will throw if the parsed data
// is inconsistent.
toc = arcstk::make_toc(offsets, total_samples.leadout_frame());
} catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
// Step 2: Create a context from the TOC and the name of the audiofile.
// The context represents the configuration of the calculation process along
// with the necessary metadata.
auto context { arcstk::make_context(toc, audiofilename) };
// Step 3: Create a Calculation and provide it with the context.
// We do not specify a checksum type, thus the Calculation will provide
// ARCSv1 as well as ARCSv2 values as default result.
auto calculation { arcstk::Calculation { std::move(context) }};
// Let's enumerate the blocks in the output. This is just to give some
// informative logging.
auto total_blocks
{ 1 + (total_samples.total_samples() - 1) / samples_per_block };
std::cout << "Expect " << total_blocks << " blocks" << std::endl;
// Provide simple input buffer for libsndfile's genuine sample/frame format.
// We decide to want 16 bit signed integers.
const auto buffer_len { samples_per_block * 2 };
std::vector<int16_t> buffer(buffer_len);
const auto samples_total {
calculation.context().audio_size().total_samples() };
auto ints_in_block { int32_t { 0 }}; // Count ints read in single operation
auto samples_read { int64_t { 0 }}; // Count total samples actually read
// The input buffer 'buffer' holds each 16 bit sample in a single integer.
// Since we have stereo audio, there are two channels, which makes one
// 16 bit integer per sample for each channel in interleaved (== not planar)
// order, where the 16 bit sample for the left channel makes the start.
// Libarcstk is not interested in those details, so we provide the samples
// via a SampleSequence that abstracts the concrete format away:
arcstk::InterleavedSamples<int16_t> sequence;
// NOTE: These prerequisites are just provided by libsndfile at this
// site in the code. In production code, you would of course verify
// things... If the channel order is switched, the sample format is
// changed or the sequence is planar, the example code will screw up!
// Main loop: let libsndfile read the sample in its own format, normalize it
// and update the prepared Calculation with the samples read in the current
// loop run.
while ((ints_in_block = audiofile.read(&buffer[0], buffer_len)))
{
// Check whether we have read the expected amount of samples in this run
if (buffer_len != ints_in_block)
{
// Ok, no! So, this must be the last block. Check!
const auto samples_in_block {
ints_in_block / arcstk::CDDA::NUMBER_OF_CHANNELS };
const auto samples_expected { samples_total - samples_read };
if (samples_in_block != samples_expected)
{
// Unexpected number of samples for the last block.
// This is an unrecoverable error, act accordingly here.
std::cerr << "Expected " << buffer_len << " integers but got "
<< ints_in_block << ". Bail out." << std::endl;
return EXIT_FAILURE;
}
// Adjust buffer size of the read buffer
buffer.resize(
static_cast<decltype(buffer)::size_type>(ints_in_block));
}
std::cout << "Read block " << (1 + samples_read / samples_per_block)
<< "/" << total_blocks
<< " (" << (buffer.size() / 2) << " samples)" << std::endl;
// Wrap buffer in a reusable SampleSequence
sequence.wrap_int_buffer(&buffer[0], buffer.size());
// Count PCM 32 bit stereo samples processed.
samples_read += sequence.size();
// We could also compute the number of samples ourselves:
// buffer.size() / static_cast<unsigned int>(CDDA::NUMBER_OF_CHANNELS)
// Note: since libsndfile has told us the total sample count, we were
// able to configure the context with the correct leadout.
// Otherwise, we would not yet know the leadout frame number. If that
// were the case we would have to provide our Calculation with this
// information manually by doing:
//
// calculation.update_audiosize(samples_read);
//
// _before_ we send the last block of samples to it. This is absolutely
// essential since otherwise the Calculation will not know when to stop
// and eventually fail. It is sufficient to update the audio size
// just before the last block of samples is passed to Calculation. Since
// we can recognize the last block as demonstrated above, we can also
// count the total number of samples read before the last update.
// Update calculation with next portion of normalized samples.
calculation.update(sequence.begin(), sequence.end());
}
// Ok, no more samples. We demonstrate that the Calculation is complete:
if (calculation.complete())
{
std::cout << "Calculation complete" << std::endl;
} else
{
std::cerr << "Error, calculation incomplete" << std::endl;
}
std::cout << "Read " << samples_read << " samples" << std::endl;
// Let's finally get us the result!
auto checksums { calculation.result() };
// And now, the time has come: print the actual checksums.
std::cout << "Track ARCSv1 ARCSv2" << std::endl;
auto trk_no { 1 };
for (const auto& track_values : checksums)
{
std::cout << std::dec << " " << std::setw(2) << std::setfill(' ')
<< trk_no << " " << std::hex << std::uppercase
<< std::setw(8) << std::setfill('0')
<< track_values.get(arcstk::checksum::type::ARCS1).value()
<< " "
<< std::setw(8) << std::setfill('0')
<< track_values.get(arcstk::checksum::type::ARCS2).value()
<< std::endl;
++trk_no;
}
}
| 37.446945 | 80 | 0.688477 | crf8472 |
a97f7953fca960a16e8196db33b75180168d1990 | 853 | cpp | C++ | c++/nim_game.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | c++/nim_game.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | c++/nim_game.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | /*
You are playing the following Nim Game with your friend: There is a heap of stones on the table,
each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner.
You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win
the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove,
the last stone will always be removed by your friend.
*/
/*
* Win if n is not divisible by 4
*/
#include "helper.h"
class Solution {
public:
bool canWinNim(int n) {
return n % 4 != 0;
}
};
int main() {
Solution s;
cout << s.canWinNim(4) << endl;
return 0;
}
| 25.848485 | 121 | 0.696366 | SongZhao |
a9848c97452e16123eb2c272fe3c0c09d409d170 | 1,522 | hpp | C++ | codegen.hpp | zsr2531/bfc | 5f6917c1d8e084dd2ba4507c7bca8f73bbc4504e | [
"MIT"
] | 5 | 2020-09-06T10:42:41.000Z | 2021-12-22T09:37:44.000Z | codegen.hpp | zsr2531/bfc | 5f6917c1d8e084dd2ba4507c7bca8f73bbc4504e | [
"MIT"
] | null | null | null | codegen.hpp | zsr2531/bfc | 5f6917c1d8e084dd2ba4507c7bca8f73bbc4504e | [
"MIT"
] | 1 | 2021-08-13T09:40:04.000Z | 2021-08-13T09:40:04.000Z | #include <sstream>
#include <unordered_map>
#include "ast.hpp"
class CodeGen : public Listener {
public:
explicit inline CodeGen() {
builder = {};
indentLevel = 1;
builder << "// Generated by bfc\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n";
builder << " unsigned char* memory = (unsigned char*) malloc(80000);\n memset(memory, 0, 80000);\n long long current = 40000;\n";
}
inline auto toString() -> std::string {
indentation();
builder << "free(memory);\n}";
return builder.str();
}
protected:
auto visitPrintStatement(const PrintStatement& printStatement) -> void override;
auto visitInputStatement(const InputStatement& inputStatement) -> void override;
auto visitShiftLeftStatement(const ShiftLeftStatement& shiftLeftStatement) -> void override;
auto visitShiftRightStatement(const ShiftRightStatement& shiftLeftStatement) -> void override;
auto visitIncrementStatement(const IncrementStatement& incrementStatement) -> void override;
auto visitDecrementStatement(const DecrementStatement& decrementStatement) -> void override;
auto enterLoopStatement(const LoopStatement& loopStatement) -> void override;
auto exitLoopStatement(const LoopStatement& loopStatement) -> void override;
private:
std::ostringstream builder;
ulong indentLevel;
inline auto indentation() -> void {
for (auto i = 0; i < indentLevel; ++i)
builder << " ";
}
};
| 40.052632 | 140 | 0.690539 | zsr2531 |
a98bfbfbfd51a0805a97ea88749cfd7a97199d47 | 452 | cpp | C++ | book/cpp_templates/tmplbook/traits/hasmember.cpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | book/cpp_templates/tmplbook/traits/hasmember.cpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | book/cpp_templates/tmplbook/traits/hasmember.cpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | #include "hasmember.hpp"
#include <iostream>
#include <vector>
#include <utility>
DEFINE_HAS_MEMBER(size);
DEFINE_HAS_MEMBER(first);
int main()
{
std::cout << "int::size: "
<< HasMemberT_size<int>::value << '\n';
std::cout << "std::vector<int>::size: "
<< HasMemberT_size<std::vector<int>>::value << '\n';
std::cout << "std::pair<int,int>::first: "
<< HasMemberT_first<std::pair<int,int>>::value << '\n';
}
| 23.789474 | 67 | 0.586283 | houruixiang |
a98c9c9038aebe5a7eb8f50ccd34c321abdee0cd | 5,650 | cc | C++ | src/base/file_reader.test.cc | dspeterson/dory | 7261fb5481283fdd69b382c3cddbc9b9bd24366d | [
"Apache-2.0"
] | 82 | 2016-06-11T23:12:40.000Z | 2022-02-21T21:01:36.000Z | src/base/file_reader.test.cc | dspeterson/dory | 7261fb5481283fdd69b382c3cddbc9b9bd24366d | [
"Apache-2.0"
] | 18 | 2016-06-16T22:55:12.000Z | 2020-07-02T10:32:53.000Z | src/base/file_reader.test.cc | dspeterson/dory | 7261fb5481283fdd69b382c3cddbc9b9bd24366d | [
"Apache-2.0"
] | 14 | 2016-06-15T18:34:08.000Z | 2021-09-06T23:16:28.000Z | /* <base/file_reader.test.cc>
----------------------------------------------------------------------------
Copyright 2017 Dave Peterson <[email protected]>
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.
----------------------------------------------------------------------------
Unit test for <base/file_reader.h>.
*/
#include <base/file_reader.h>
#include <cstring>
#include <fstream>
#include <string>
#include <base/error_util.h>
#include <base/tmp_file.h>
#include <gtest/gtest.h>
using namespace Base;
namespace {
class TFileReaderSimpleTest : public ::testing::Test {
protected:
TFileReaderSimpleTest() {
}
virtual ~TFileReaderSimpleTest() {
}
virtual void SetUp() {
}
virtual void TearDown() {
}
}; // TFileReaderSimpleTest
/* The fixture for testing class TFileReader. */
class TFileReaderTest : public ::testing::Test {
protected:
TFileReaderTest()
: FileContents("a bunch of junk"),
TmpFile("/tmp/file_reader_test.XXXXXX",
true /* delete_on_destroy */),
Reader(TmpFile.GetName().c_str()) {
}
virtual ~TFileReaderTest() {
}
virtual void SetUp() {
std::ofstream f(TmpFile.GetName().c_str(), std::ios_base::out);
f << FileContents;
}
virtual void TearDown() {
}
std::string FileContents;
TTmpFile TmpFile;
TFileReader Reader;
}; // TFileReaderTest
TEST_F(TFileReaderSimpleTest, TestNoSuchFile) {
TFileReader reader("/blah/this_file_should_not_exist");
bool threw = false;
try {
reader.GetSize();
} catch (const std::ios_base::failure &x) {
threw = true;
}
ASSERT_TRUE(threw);
threw = false;
char buf[16];
try {
reader.ReadIntoBuf(buf, sizeof(buf));
} catch (const std::ios_base::failure &x) {
threw = true;
}
ASSERT_TRUE(threw);
threw = false;
std::string s;
try {
reader.ReadIntoString(s);
} catch (const std::ios_base::failure &x) {
threw = true;
}
ASSERT_TRUE(threw);
threw = false;
try {
reader.ReadIntoString();
} catch (const std::ios_base::failure &x) {
threw = true;
}
ASSERT_TRUE(threw);
threw = false;
std::vector<char> v;
try {
reader.ReadIntoBuf(v);
} catch (const std::ios_base::failure &x) {
threw = true;
}
ASSERT_TRUE(threw);
threw = false;
try {
reader.ReadIntoBuf<char>();
} catch (const std::ios_base::failure &x) {
threw = true;
}
ASSERT_TRUE(threw);
}
TEST_F(TFileReaderTest, TestGetSize) {
ASSERT_EQ(Reader.GetSize(), FileContents.size());
/* Make sure a second GetSize() operation with the same reader works. */
ASSERT_EQ(Reader.GetSize(), FileContents.size());
}
TEST_F(TFileReaderTest, TestCallerSuppliedBuf) {
char buf[2 * FileContents.size()];
std::fill(buf, buf + sizeof(buf), 'x');
size_t byte_count = Reader.ReadIntoBuf(buf, sizeof(buf));
ASSERT_EQ(byte_count, FileContents.size());
ASSERT_EQ(std::memcmp(buf, "a bunch of junkxxxxxxxxxxxxxxx", sizeof(buf)),
0);
std::fill(buf, buf + sizeof(buf), 'x');
byte_count = Reader.ReadIntoBuf(buf, 7);
ASSERT_EQ(byte_count, 7U);
ASSERT_EQ(std::memcmp(buf, "a bunchxxxxxxxxxxxxxxxxxxxxxxx", sizeof(buf)),
0);
}
TEST_F(TFileReaderTest, TestCallerSuppliedBuf2) {
char buf[2 * FileContents.size()];
std::fill(buf, buf + sizeof(buf), 'x');
size_t byte_count = ReadFileIntoBuf(TmpFile.GetName(), buf, sizeof(buf));
ASSERT_EQ(byte_count, FileContents.size());
ASSERT_EQ(std::memcmp(buf, "a bunch of junkxxxxxxxxxxxxxxx", sizeof(buf)),
0);
std::fill(buf, buf + sizeof(buf), 'x');
byte_count = ReadFileIntoBuf(TmpFile.GetName(), buf, 7);
ASSERT_EQ(byte_count, 7U);
ASSERT_EQ(std::memcmp(buf, "a bunchxxxxxxxxxxxxxxxxxxxxxxx", sizeof(buf)),
0);
}
TEST_F(TFileReaderTest, TestReadIntoString) {
std::string s;
Reader.ReadIntoString(s);
ASSERT_EQ(s, FileContents);
ASSERT_EQ(Reader.ReadIntoString(), FileContents);
}
TEST_F(TFileReaderTest, TestReadIntoString2) {
std::string s;
ReadFileIntoString(TmpFile.GetName(), s);
ASSERT_EQ(s, FileContents);
ASSERT_EQ(ReadFileIntoString(TmpFile.GetName()), FileContents);
}
TEST_F(TFileReaderTest, TestReadIntoVector) {
std::vector<char> v1;
Reader.ReadIntoBuf(v1);
ASSERT_EQ(v1.size(), FileContents.size());
ASSERT_EQ(std::memcmp(&v1[0], FileContents.data(), v1.size()), 0);
std::vector<char> v2 = Reader.ReadIntoBuf<char>();
ASSERT_EQ(v2, v1);
}
TEST_F(TFileReaderTest, TestReadIntoVector2) {
std::vector<char> v1;
ReadFileIntoBuf(TmpFile.GetName(), v1);
ASSERT_EQ(v1.size(), FileContents.size());
ASSERT_EQ(std::memcmp(&v1[0], FileContents.data(), v1.size()), 0);
std::vector<char> v2 = ReadFileIntoBuf<char>(TmpFile.GetName());
ASSERT_EQ(v2, v1);
}
} // namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
DieOnTerminate();
return RUN_ALL_TESTS();
}
| 26.157407 | 79 | 0.629735 | dspeterson |
a98cd8343f943b0ee828d6eaae7e866c24bf41ce | 6,583 | cpp | C++ | SpatialGDK/Source/SpatialGDKTests/SpatialGDKServices/LocalDeploymentManager/LocalDeploymentManagerTest.cpp | eddyrainy/UnrealGDK | eb86c58d23d55e74b584b91c2d35702ba08448be | [
"MIT"
] | null | null | null | SpatialGDK/Source/SpatialGDKTests/SpatialGDKServices/LocalDeploymentManager/LocalDeploymentManagerTest.cpp | eddyrainy/UnrealGDK | eb86c58d23d55e74b584b91c2d35702ba08448be | [
"MIT"
] | null | null | null | SpatialGDK/Source/SpatialGDKTests/SpatialGDKServices/LocalDeploymentManager/LocalDeploymentManagerTest.cpp | eddyrainy/UnrealGDK | eb86c58d23d55e74b584b91c2d35702ba08448be | [
"MIT"
] | null | null | null | // Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#include "TestDefinitions.h"
#include "LocalDeploymentManager.h"
#include "SpatialCommandUtils.h"
#include "SpatialGDKDefaultLaunchConfigGenerator.h"
#include "SpatialGDKDefaultWorkerJsonGenerator.h"
#include "SpatialGDKEditorSettings.h"
#include "CoreMinimal.h"
#define LOCALDEPLOYMENT_TEST(TestName) \
GDK_TEST(Services, LocalDeployment, TestName)
namespace
{
// TODO: UNR-1969 - Prepare LocalDeployment in CI pipeline
const double MAX_WAIT_TIME_FOR_LOCAL_DEPLOYMENT_OPERATION = 20.0;
// TODO: UNR-1964 - Move EDeploymentState enum to LocalDeploymentManager
enum class EDeploymentState { IsRunning, IsNotRunning };
const FName AutomationWorkerType = TEXT("AutomationWorker");
const FString AutomationLaunchConfig = TEXT("Improbable/AutomationLaunchConfig.json");
FLocalDeploymentManager* GetLocalDeploymentManager()
{
FSpatialGDKServicesModule& GDKServices = FModuleManager::GetModuleChecked<FSpatialGDKServicesModule>("SpatialGDKServices");
FLocalDeploymentManager* LocalDeploymentManager = GDKServices.GetLocalDeploymentManager();
return LocalDeploymentManager;
}
bool GenerateWorkerAssemblies()
{
FString BuildConfigArgs = TEXT("worker build build-config");
FString WorkerBuildConfigResult;
int32 ExitCode;
SpatialCommandUtils::ExecuteSpatialCommandAndReadOutput(BuildConfigArgs, FSpatialGDKServicesModule::GetSpatialOSDirectory(), WorkerBuildConfigResult, ExitCode, false);
const int32 ExitCodeSuccess = 0;
return (ExitCode == ExitCodeSuccess);
}
bool GenerateWorkerJson()
{
const FString WorkerJsonDir = FSpatialGDKServicesModule::GetSpatialOSDirectory(TEXT("workers/unreal"));
FString JsonPath = FPaths::Combine(WorkerJsonDir, TEXT("spatialos.UnrealAutomation.worker.json"));
if (!FPaths::FileExists(JsonPath))
{
bool bRedeployRequired = false;
return GenerateDefaultWorkerJson(JsonPath, AutomationWorkerType.ToString(), bRedeployRequired);
}
return true;
}
}
DEFINE_LATENT_AUTOMATION_COMMAND(FStartDeployment);
bool FStartDeployment::Update()
{
if (const USpatialGDKEditorSettings* SpatialGDKSettings = GetDefault<USpatialGDKEditorSettings>())
{
FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager();
const FString LaunchConfig = FPaths::Combine(FPaths::ConvertRelativePathToFull(FPaths::ProjectIntermediateDir()), AutomationLaunchConfig);
const FString LaunchFlags = SpatialGDKSettings->GetSpatialOSCommandLineLaunchFlags();
const FString SnapshotName = SpatialGDKSettings->GetSpatialOSSnapshotToLoad();
AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [LocalDeploymentManager, LaunchConfig, LaunchFlags, SnapshotName]
{
if (!GenerateWorkerJson())
{
return;
}
if (!GenerateWorkerAssemblies())
{
return;
}
FSpatialLaunchConfigDescription LaunchConfigDescription(AutomationWorkerType);
if (!GenerateDefaultLaunchConfig(LaunchConfig, &LaunchConfigDescription))
{
return;
}
if (LocalDeploymentManager->IsLocalDeploymentRunning())
{
return;
}
LocalDeploymentManager->TryStartLocalDeployment(LaunchConfig, LaunchFlags, SnapshotName, TEXT(""), FLocalDeploymentManager::LocalDeploymentCallback());
});
}
return true;
}
DEFINE_LATENT_AUTOMATION_COMMAND(FStopDeployment);
bool FStopDeployment::Update()
{
FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager();
if (!LocalDeploymentManager->IsLocalDeploymentRunning() && !LocalDeploymentManager->IsDeploymentStopping())
{
return true;
}
if (!LocalDeploymentManager->IsDeploymentStopping())
{
AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [LocalDeploymentManager]
{
LocalDeploymentManager->TryStopLocalDeployment();
});
}
return true;
}
DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FWaitForDeployment, FAutomationTestBase*, Test, EDeploymentState, ExpectedDeploymentState);
bool FWaitForDeployment::Update()
{
const double NewTime = FPlatformTime::Seconds();
if (NewTime - StartTime >= MAX_WAIT_TIME_FOR_LOCAL_DEPLOYMENT_OPERATION)
{
return true;
}
FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager();
if (LocalDeploymentManager->IsDeploymentStopping())
{
return false;
}
else
{
return (ExpectedDeploymentState == EDeploymentState::IsRunning) ? LocalDeploymentManager->IsLocalDeploymentRunning() : !LocalDeploymentManager->IsLocalDeploymentRunning();
}
}
DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FCheckDeploymentState, FAutomationTestBase*, Test, EDeploymentState, ExpectedDeploymentState);
bool FCheckDeploymentState::Update()
{
FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager();
if (ExpectedDeploymentState == EDeploymentState::IsRunning)
{
Test->TestTrue(TEXT("Deployment is running"), LocalDeploymentManager->IsLocalDeploymentRunning() && !LocalDeploymentManager->IsDeploymentStopping());
}
else
{
Test->TestFalse(TEXT("Deployment is not running"), LocalDeploymentManager->IsLocalDeploymentRunning() || LocalDeploymentManager->IsDeploymentStopping());
}
return true;
}
/*
// UNR-1975 after fixing the flakiness of these tests, and investigating how they can be run in CI (UNR-1969), re-enable them
LOCALDEPLOYMENT_TEST(GIVEN_no_deployment_running_WHEN_deployment_started_THEN_deployment_running)
{
// GIVEN
ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment());
ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning));
// WHEN
ADD_LATENT_AUTOMATION_COMMAND(FStartDeployment());
ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsRunning));
// THEN
ADD_LATENT_AUTOMATION_COMMAND(FCheckDeploymentState(this, EDeploymentState::IsRunning));
// Cleanup
ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment());
ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning));
return true;
}
LOCALDEPLOYMENT_TEST(GIVEN_deployment_running_WHEN_deployment_stopped_THEN_deployment_not_running)
{
// GIVEN
ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment());
ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning));
ADD_LATENT_AUTOMATION_COMMAND(FStartDeployment());
ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsRunning));
// WHEN
ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment());
ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning));
// THEN
ADD_LATENT_AUTOMATION_COMMAND(FCheckDeploymentState(this, EDeploymentState::IsNotRunning));
return true;
}*/
| 33.586735 | 173 | 0.809965 | eddyrainy |
a98cf28d3d49efba7b7a290d7fd9ff9ec3c64556 | 1,003 | hpp | C++ | buildSystemTests/multi_targets_project/code/StaticTarget3/public/StaticTarget3/StaticTarget3.hpp | iblis-ms/python_cmake_build_system | 9f52f004241c6e8efc4a036d5c58f67a6d40e7ec | [
"MIT"
] | null | null | null | buildSystemTests/multi_targets_project/code/StaticTarget3/public/StaticTarget3/StaticTarget3.hpp | iblis-ms/python_cmake_build_system | 9f52f004241c6e8efc4a036d5c58f67a6d40e7ec | [
"MIT"
] | 6 | 2020-10-11T21:03:24.000Z | 2020-10-12T20:32:13.000Z | buildSystemTests/multi_targets_project/code/StaticTarget3/public/StaticTarget3/StaticTarget3.hpp | iblis-ms/python_cmake_build_system | 9f52f004241c6e8efc4a036d5c58f67a6d40e7ec | [
"MIT"
] | null | null | null | #ifndef STATIC_TARGET_3_HPP_
#define STATIC_TARGET_3_HPP_
#include <iostream>
#include <InterfaceTarget3/InterfaceTarget3.hpp>
#include <InterfaceTarget2/InterfaceTarget2.hpp>
#include <InterfaceTarget4/InterfaceTarget4.hpp>
#include <StaticTarget1/StaticTarget1.hpp>
#include <StaticTarget2/StaticTarget2.hpp>
/**
* @brief Shared target 3 public class
*
*/
struct CStaticTarget3 : IInterfaceTarget3, IInterfaceTarget4
{
/**
* @brief Function 3.
*
*/
virtual void fun_interface3() override;
/**
* @brief Function 4.
*
*/
virtual void fun_interface4() override;
/**
* @brief Get the Interface Target2 object
*
* @return IInterfaceTarget2&
*/
IInterfaceTarget2& getInterfaceTarget2();
/**
* @brief Get the Static Target1 object
*
* @return CStaticTarget1&
*/
CStaticTarget1& getStaticTarget1();
/**
* @brief Get the Static Target2 object
*
* @return CStaticTarget2&
*/
CStaticTarget2& getStaticTarget2();
};
#endif // STATIC_TARGET_3_HPP_
| 18.924528 | 60 | 0.716849 | iblis-ms |
a98d481499dd8267ddbe4ac416d3996e23c3e622 | 651 | hpp | C++ | homeworks/HW4Source/HW4/header/MountainCar.hpp | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | homeworks/HW4Source/HW4/header/MountainCar.hpp | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | homeworks/HW4Source/HW4/header/MountainCar.hpp | anshuman1811/cs687-reinforcementlearning | cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481 | [
"MIT"
] | null | null | null | #pragma once
#include "stdafx.h"
// MountainCar MDP - see Gridworld.hpp for comments regarding the general structure of these environment/MDP objects
class MountainCar {
public:
MountainCar();
int getStateDim() const;
int getNumActions() const;
double update(const int & action, std::mt19937_64 & generator);
std::vector<double> getState(std::mt19937_64 & generator);
bool inTerminalState() const;
void newEpisode(std::mt19937_64 & generator);
private:
const double minX = -1.2;
const double maxX = 0.5;
const double minXDot = -0.07;
const double maxXDot = 0.07;
std::vector<double> state; // [2] - x and xDot
}; | 28.304348 | 117 | 0.703533 | anshuman1811 |
817da77491a5d3f35b804d3b71400ef3724f42a3 | 3,957 | cpp | C++ | src/core/features/flappybird.cpp | Metaphysical1/gamesneeze | 59d31ee232bbcc80d29329e0f64ebdde599c37df | [
"MIT"
] | 1,056 | 2020-11-17T11:49:12.000Z | 2022-03-23T12:32:42.000Z | src/core/features/flappybird.cpp | dweee/gamesneeze | 99f574db2617263470280125ec78afa813f27099 | [
"MIT"
] | 102 | 2021-01-15T12:05:18.000Z | 2022-02-26T00:19:58.000Z | src/core/features/flappybird.cpp | dweee/gamesneeze | 99f574db2617263470280125ec78afa813f27099 | [
"MIT"
] | 121 | 2020-11-18T12:08:21.000Z | 2022-03-31T07:14:32.000Z | #include "features.hpp"
#include <SDL2/SDL_scancode.h>
#include <vector>
int score;
ImVec2 cursorPos;
float deltaTime;
bool alive = true;
bool paused = false;
float birdHeight;
class Bird {
public:
void draw(ImDrawList* drawList) {
drawList->AddRectFilled(ImVec2{cursorPos.x+60, cursorPos.y+(400-height)}, ImVec2{cursorPos.x+70, cursorPos.y+(400-height)+10}, ImColor(255, 255, 255, 255));
if (alive) {
if (!paused) {
height += velocity*deltaTime; // add velocity
birdHeight = height;
velocity -= 250.f*deltaTime; // gravity
if (height < 50) {
alive = false;
}
}
}
else {
height = 300;
score = 0;
drawList->AddText(ImVec2{ImVec2{cursorPos.x+10, cursorPos.y+10}}, ImColor(255, 255, 255, 255), "You died, press up arrow to respawn");
}
}
void handleInput() {
if (ImGui::IsKeyPressed(SDL_SCANCODE_UP, false) && !paused) {
velocity = 140.f;
alive = true;
}
else if (ImGui::IsKeyPressed(SDL_SCANCODE_DOWN, false) && alive) {
paused = !paused;
}
}
float velocity = 0;
float height = 300;
};
class Pipe {
public:
Pipe(float startX) {
x = startX;
xOriginal = startX;
gapTop = (rand() % 200) + 130;
gapBottom = gapTop - 65;
}
void draw(ImDrawList* drawList) {
drawList->AddRectFilled(ImVec2{cursorPos.x+x, cursorPos.y}, ImVec2{cursorPos.x+x+40, cursorPos.y+(400-gapTop)}, ImColor(0, 65, 0, 255));
drawList->AddRectFilled(ImVec2{cursorPos.x+x, cursorPos.y+400}, ImVec2{cursorPos.x+x+40, cursorPos.y+(400-gapBottom)}, ImColor(0, 65, 0, 255));
if (alive) {
if (!paused) {
x -= 90.f * deltaTime;
if (x < -200) {
x = 400;
gapTop = (rand() % 200) + 130;
gapBottom = gapTop - 65;
hasBirdPassed = false;
}
if ((x < 70) && (x > 20)) {
if ((birdHeight > gapTop) || (birdHeight < gapBottom)) {
alive = false;
}
if (!hasBirdPassed) {
score++;
hasBirdPassed = true;
}
}
}
}
else {
x = xOriginal;
gapTop = (rand() % 200) + 130;
gapBottom = gapTop - 65;
hasBirdPassed = false;
}
}
bool hasBirdPassed = false;
float gapTop = 300, gapBottom = 235;
float x;
float xOriginal;
};
void Features::FlappyBird::draw() {
if (CONFIGBOOL("Misc>Misc>Misc>Flappy Birb")) {
ImGui::Begin("Flappy Birb", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | (Menu::open ? 0 : ImGuiWindowFlags_NoMouseInputs));
ImGui::Text("Flappy Birb (Score %i)", score);
ImGui::Separator();
ImDrawList* drawList = ImGui::GetWindowDrawList();
deltaTime = ImGui::GetIO().DeltaTime;
cursorPos = ImGui::GetCursorScreenPos();
drawList->AddRectFilled(ImVec2{cursorPos.x, cursorPos.y}, ImVec2{cursorPos.x+400, cursorPos.y+400}, ImColor(0, 0, 0, 255));
drawList->AddRectFilled(ImVec2{cursorPos.x, cursorPos.y+360}, ImVec2{cursorPos.x+400, cursorPos.y+400}, ImColor(0, 80, 0, 255));
static Bird bird;
bird.handleInput();
bird.draw(drawList);
static Pipe pipe(400);
pipe.draw(drawList);
static Pipe pipe2(550);
pipe2.draw(drawList);
static Pipe pipe3(700);
pipe3.draw(drawList);
if (paused) {
drawList->AddText(ImVec2{ImVec2{cursorPos.x+10, cursorPos.y+10}}, ImColor(255, 255, 255, 255), "Paused");
}
ImGui::End();
}
} | 31.91129 | 164 | 0.52464 | Metaphysical1 |
817dcad1853d2128a15890b29ec54d9067fdba99 | 2,392 | cpp | C++ | LinearList/LinkedList.cpp | FrostyBonny/DS | 63f951a09a3e67ef89ffc2db4e4780decea2bcef | [
"MIT"
] | 2 | 2019-07-16T08:23:47.000Z | 2021-06-26T13:43:10.000Z | LinearList/LinkedList.cpp | FrostyBonny/DS | 63f951a09a3e67ef89ffc2db4e4780decea2bcef | [
"MIT"
] | null | null | null | LinearList/LinkedList.cpp | FrostyBonny/DS | 63f951a09a3e67ef89ffc2db4e4780decea2bcef | [
"MIT"
] | null | null | null | #include<iostream>
#include<stdlib.h>
using namespace std;
// ๅ้พ่กจ็ๆไฝ
typedef struct LinkNode{
int data;
struct LinkNode *next;
}LinkNode;
// headermake
void creat(LinkNode *L){
LinkNode *node;
for(int i = 0;i < 10;i++){
node = (LinkNode *)malloc(sizeof(LinkNode));
node->data = rand()%13;
node->next = L->next;
L->next = node;
}
// return L;
}
void PrintOut(LinkNode *L){
int time = 1;
while(L->next != NULL){
if(time > 20) return;
cout<<L->next->data<<" ";
L = L->next;
time ++;
}
cout<<endl;
}
//็ฌฌไธไธชไธบๆ ๅ๏ผๅ้ขๆฏไปๅฐ๏ผๅ้ขๆฏไปๅคงใpractice 5
void sortA(LinkNode *L){
int time = 1;
LinkNode *s = L->next;
LinkNode *p = s->next;
LinkNode *pre;
cout<<s->data<<endl;
s->next = NULL;
LinkNode *qre = s;
while(p != NULL){
if(time > 30) return;
time++;
if(p->data < s->data){
pre = p->next;
p->next = L->next;
L->next = p;
p = pre;
}else if(p->data > s->data){
pre = p->next;
p->next = s->next;
s->next = p;
p = pre;
}
}
}
//practice 6 caculate the last site element
int func_6(LinkNode *L,int k){
LinkNode *p,*q;
p = L->next;
q = L->next;
while(k > 1&&q->next != NULL){
q = q->next;
k--;
}
if(q->next == NULL){
cout<<0<<endl;
return 0;
}
while(q->next != NULL){
q = q->next;
p = p->next;
}
cout<<p->data<<endl;
return 1;
}
// reversed way 1
void func_7(LinkNode *L){
LinkNode *p = L->next;
LinkNode *q;
L->next = NULL;
while(p != NULL){
q = p->next;
p->next = L->next;
L->next = p;
p = q;
}
}
// reversede way 2
void func_8(LinkNode *L){
LinkNode *p,*q,*r;
p = L->next;
q = p->next;
p->next = NULL;
while(q->next != NULL){
r = q->next;
q->next = p;
p = q;
q = r;
}
q->next = p;
L->next = q;
}
int main(){
LinkNode *L;
L = (LinkNode *)malloc(sizeof(LinkNode));
L->next = NULL;
creat(L);
PrintOut(L);
//practice 5
//sortA(L);
//PrintOut(L);
//pracetice 6
//func_6(L,4);
//reversed without other space
//func_7(L);
func_8(L);
PrintOut(L);
return 0;
}
| 18.4 | 52 | 0.460284 | FrostyBonny |
8180eaa3530bf717aa9c2fc830ff699b322527d2 | 9,594 | cpp | C++ | Day23/main.cpp | baldwinmatt/AoC-2021 | 4a7f18f6364715f6e61127aba175db6fec6e6b13 | [
"Apache-2.0"
] | 4 | 2021-12-06T17:14:00.000Z | 2021-12-10T06:29:35.000Z | Day23/main.cpp | baldwinmatt/AoC-2021 | 4a7f18f6364715f6e61127aba175db6fec6e6b13 | [
"Apache-2.0"
] | null | null | null | Day23/main.cpp | baldwinmatt/AoC-2021 | 4a7f18f6364715f6e61127aba175db6fec6e6b13 | [
"Apache-2.0"
] | null | null | null | #include "aoc21/helpers.h"
#include <array>
#include <algorithm>
#include <list>
#include <map>
#include <set>
#include <vector>
namespace {
constexpr int RoomCount = 4;
constexpr int RoomDepth = 2;
constexpr int HallwaySize = 4 + (RoomCount * 2) - 1;
using Hallway = std::array<char, HallwaySize>;
using Room = std::string;
using Rooms = std::array<Room, RoomCount>;
using CharIntMap = std::map<char, int>;
CharIntMap EnergyCost = { {'A', 1 }, { 'B', 10 }, { 'C', 100 }, { 'D', 1000 } };
CharIntMap RoomAssignments = { { 'A', 0 }, { 'B', 1 }, { 'C', 2 }, { 'D', 3 } };
const auto IsFish = [](const char f) {
return f >= 'A' && f <= 'D';
};
#if !defined (NDEBUG)
const auto IsRoom = [](const int room) {
return room >= 0 && room < RoomCount;
};
#endif
const auto TargetRoom = [](const char f) {
assert(IsFish(f));
return f - 'A';
};
class MapState {
public:
int energy;
int roomDepth;
Hallway hallway;
Rooms rooms;
std::vector<int>doorways;
MapState(int depth)
: energy(0)
, roomDepth(depth)
{
for (auto& c : hallway) {
c = '.';
}
}
MapState()
: MapState(RoomDepth)
{ }
void insertFish(const std::vector<std::string> fish) {
int i = 0;
for (auto& r : rooms) {
std::string new_r(&r[0], 1);
new_r += fish[i++];
new_r += (r.substr(1));
r = new_r;
}
roomDepth = rooms[0].size();
}
std::string hash() const {
std::string s;
for (const auto&c : hallway) {
s.append(&c, 1);
}
for (const auto& r : rooms) {
s.append(",", 1);
s.append(r);
}
return s;
}
bool isDesiredRoom(char fish, int room) const {
assert(IsFish(fish));
assert(IsRoom(room));
return RoomAssignments[fish] == room;
}
bool isRoomFinal(int room) const {
assert(IsRoom(room));
if (rooms[room].size() < static_cast<size_t>(roomDepth)) {
return false;
}
for (const auto& f : rooms[room]) {
if (!isDesiredRoom(f, room)) {
return false;
}
}
return true;
}
bool final() const {
for (int i = 0; i < RoomCount; i++) {
if (!isRoomFinal(i)) {
return false;
}
}
return true;
}
bool isDoorway(const int p) const {
return std::find(doorways.begin(), doorways.end(), p) != doorways.end();
}
int getRoom(const int p) const {
for (size_t i = 0; i < doorways.size(); i++) {
if (doorways[i] == p) {
return i;
}
}
return -1;
}
MapState move(int from, int to) {
MapState next(*this);
auto fish = next.hallway[from];
int steps = 0;
const int from_room = getRoom(from);
const int to_room = getRoom(to);
if (from_room != -1) {
fish = next.rooms[from_room].front();
// remove the first element from the room
next.rooms[from_room].erase(0, 1);
// steps to get out of room
steps += (next.roomDepth - next.rooms[from_room].size());
} else {
next.hallway[from] = '.';
}
// steps between spaces
steps += ::abs(to - from);
if (to_room != -1) {
// steps to emplace in the room
steps += (next.roomDepth - next.rooms[to_room].size());
next.rooms[to_room] = fish + next.rooms[to_room];
} else {
next.hallway[to] = fish;
}
next.energy += steps * EnergyCost[fish];
return next;
}
bool isHallwayClear(const int from, const int to) const {
assert(std::min(from, to) == from);
assert(std::max(from, to) == to);
for (int k = from; k < to; k++) {
if (isDoorway(k)) { // nothing can be directly above a room
continue;
}
// if a hallway spot is occupied, no bueno
if (hallway[k] != '.') {
return false;
}
}
return true;
}
bool isTargetRoomClear(const int to) const {
assert(IsRoom(to));
if (rooms[to].size() == static_cast<size_t>(roomDepth)) { // room is full
return false;
}
for (const auto& c : rooms[to]) { // room has non-correct occupant
if (!isDesiredRoom(c, to)) {
return false;
}
}
return true;
}
bool canMoveToHall(const int from, const int to) const {
assert(IsRoom(from));
assert(to >= 0 && to < HallwaySize);
const int door_from = doorways[from];
const int i = std::min(door_from, to);
const int j = std::max(door_from, to);
if (isDoorway(to)) {
return false;
}
return isHallwayClear(i, j);
}
bool canMoveToRoom(const int from, const int to) const {
assert(IsRoom(from));
assert(IsRoom(to));
const int door_from = doorways[from];
const int door_to = doorways[to];
const int i = std::min(door_from, door_to);
const int j = std::max(door_from, door_to);
return isTargetRoomClear(to) && isHallwayClear(i, j);
}
bool canMoveFromHall(const int from, const int to) const {
assert(from >= 0 && from < HallwaySize);
assert(IsRoom(to));
const int door_to = doorways[to];
const int i = std::min(from, door_to);
const int j = std::max(from, door_to);
return isTargetRoomClear(to) && isHallwayClear(i + 1, j);
}
bool valid() const {
int fish = 0;
for (const auto& r : rooms) {
fish += r.size();
if (r.size() > static_cast<size_t>(roomDepth)) {
return false;
}
}
for (const auto& c : hallway) {
fish += IsFish(c);
}
return fish == roomDepth * RoomCount;
}
friend std::ostream& operator<<(std::ostream& os, const MapState& m) {
os << aoc::cls;
os << "#";
for (size_t i = 0; i < m.hallway.size(); i++) {
os << "#";
}
os << "#";
os << std::endl;
os << "#";
for (const auto& c : m.hallway) {
os << c;
}
os << "#";
os << std::endl;
os << "#";
for (size_t i = 0; i < m.hallway.size(); i++) {
if (m.isDoorway(i)) {
os << '.';
} else {
os << "#";
}
}
os << "#";
return os;
}
};
struct HeapComparator {
bool operator()(const MapState& lhs, const MapState& rhs) {
return lhs.energy > rhs.energy;
}
};
using StateList = std::vector<MapState>;
const auto HeapPop = [](auto& heap) {
auto s = heap.front();
std::pop_heap(heap.begin(), heap.end(), HeapComparator());
heap.pop_back();
return s;
};
const auto HeapPush = [](auto& heap, auto& s) {
heap.emplace_back(s);
std::push_heap(heap.begin(), heap.end(), HeapComparator());
};
int solve(MapState map) {
aoc::AutoTimer __t;
// Maintain a heap of states
StateList sq;
sq.push_back(map);
std::make_heap(sq.begin(), sq.end(), HeapComparator());
// Maintain a list of visited states, so we can quickly eliminate them from our A*
int result = INT_MAX;
std::set<std::string> seen;
while (result == INT_MAX && !sq.empty()) {
auto s = HeapPop(sq);
const auto r = seen.emplace(s.hash());
if (!r.second) {
continue;
}
if (s.final()) {
result = s.energy;
break;
}
for (int i = 0; i < RoomCount; i++) {
if (!s.isRoomFinal(i)) {
const auto fish = s.rooms[i].front();
if (!IsFish(fish)) { continue; }
const auto t = TargetRoom(fish);
if (s.canMoveToRoom(i, t)) {
const auto next = s.move(s.doorways[i], s.doorways[t]);
assert(next.valid());
HeapPush(sq, next);
}
}
for (int j = 0; j < HallwaySize; j++) {
const auto fish = s.rooms[i].front();
if (!IsFish(fish)) {
continue;
}
const auto tf = s.hallway[j];
if (IsFish(tf)) {
continue;
}
if (s.canMoveToHall(i, j)) {
const auto next = s.move(s.doorways[i], j);
assert(next.valid());
HeapPush(sq, next);
}
}
}
for (int j = 0; j < HallwaySize; j++) {
const char fish = s.hallway[j];
if (!IsFish(fish)) {
continue;
}
const auto t = TargetRoom(fish);
if (s.canMoveFromHall(j, t)) {
const auto next = s.move(j, s.doorways[t]);
assert(next.valid());
HeapPush(sq, next);
}
}
}
return result;
}
};
int main(int argc, char** argv) {
aoc::AutoTimer t;
auto f = aoc::open_argv_1(argc, argv);
MapState map;
std::string line;
while (aoc::getline(f, line)) {
constexpr int MinLineSize = 2 + (RoomCount * 2);
constexpr int RoomOffset = 3;
assert(line.size() > RoomOffset);
const char c = line[RoomOffset];
assert(c == '#' || c == '.' || (c >= 'A' && c <= 'D'));
if (c < 'A' || c > 'D') {
continue;
}
assert(line.size() > MinLineSize);
int room = 0;
for (int i = RoomOffset; i < MinLineSize; i += 2) {
map.rooms[room].push_back(line[i]);
map.doorways.push_back(i - 1);
room++;
}
}
f.close();
const auto part1 = solve(map);
aoc::print_result(1, part1);
map.insertFish({ "DD", "CB", "BA", "AC" });
const auto part2 = solve(map);
aoc::print_result(2, part2);
return 0;
}
| 23.747525 | 86 | 0.512508 | baldwinmatt |
81812d2db6128c0a250e57b5bbb7d8b3b2d7f689 | 7,181 | cpp | C++ | source/models/bundle.cpp | wilsonfonseca/iota.lib.cpp | c49791b8e4f1499dc652fb84dedb016e5f42cdf4 | [
"MIT"
] | null | null | null | source/models/bundle.cpp | wilsonfonseca/iota.lib.cpp | c49791b8e4f1499dc652fb84dedb016e5f42cdf4 | [
"MIT"
] | null | null | null | source/models/bundle.cpp | wilsonfonseca/iota.lib.cpp | c49791b8e4f1499dc652fb84dedb016e5f42cdf4 | [
"MIT"
] | null | null | null | //
// MIT License
//
// Copyright (c) 2017-2018 Thibault Martinez and Simon Ninon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
#include <algorithm>
#include <iota/constants.hpp>
#include <iota/crypto/kerl.hpp>
#include <iota/models/bundle.hpp>
#include <iota/types/trinary.hpp>
#include <iota/types/utils.hpp>
namespace IOTA {
namespace Models {
Bundle::Bundle(const std::vector<Models::Transaction>& transactions) : transactions_(transactions) {
if (!empty()) {
hash_ = transactions_[0].getBundle();
}
}
const std::vector<Models::Transaction>&
Bundle::getTransactions() const {
return transactions_;
}
std::vector<Models::Transaction>&
Bundle::getTransactions() {
return transactions_;
}
std::size_t
Bundle::getLength() const {
return transactions_.size();
}
bool
Bundle::empty() const {
return getLength() == 0;
}
const Types::Trytes&
Bundle::getHash() const {
return hash_;
}
void
Bundle::setHash(const Types::Trytes& hash) {
hash_ = hash;
}
void
Bundle::addTransaction(const Transaction& transaction, int32_t signatureMessageLength) {
if (empty()) {
hash_ = transaction.getBundle();
}
transactions_.push_back(transaction);
if (signatureMessageLength > 1) {
Transaction signatureTransaction = { transaction.getAddress(), 0, transaction.getTag(),
transaction.getTimestamp() };
for (int i = 1; i < signatureMessageLength; i++) {
transactions_.push_back(signatureTransaction);
}
}
}
void
Bundle::generateHash() {
Crypto::Kerl k;
for (std::size_t i = 0; i < transactions_.size(); i++) {
auto& trx = transactions_[i];
trx.setCurrentIndex(i);
trx.setLastIndex(transactions_.size() - 1);
auto value = Types::tritsToTrytes(Types::intToTrits(trx.getValue(), SeedLength));
auto timestamp =
Types::tritsToTrytes(Types::intToTrits(trx.getTimestamp(), TryteAlphabetLength));
auto currentIndex =
Types::tritsToTrytes(Types::intToTrits(trx.getCurrentIndex(), TryteAlphabetLength));
auto lastIndex =
Types::tritsToTrytes(Types::intToTrits(trx.getLastIndex(), TryteAlphabetLength));
auto bytes = Types::trytesToBytes(trx.getAddress().toTrytes() + value +
trx.getObsoleteTag().toTrytesWithPadding() + timestamp +
currentIndex + lastIndex);
k.absorb(bytes);
}
std::vector<uint8_t> hash(ByteHashLength);
k.finalSqueeze(hash);
hash_ = Types::bytesToTrytes(hash);
}
void
Bundle::finalize() {
bool validBundle = false;
while (!validBundle) {
//! generate hash
generateHash();
//! check that normalized hash does not contain "13" (otherwise, this may lead to security flaw)
auto normalizedHash = normalizedBundle(hash_);
if (!transactions_.empty() && std::find(std::begin(normalizedHash), std::end(normalizedHash),
13 /* = M */) != std::end(normalizedHash)) {
// Insecure bundle. Increment Tag and recompute bundle hash.
auto tagTrits = Types::trytesToTrits(transactions_[0].getObsoleteTag().toTrytesWithPadding());
Types::incrementTrits(tagTrits);
transactions_[0].setObsoleteTag(Types::tritsToTrytes(tagTrits));
} else {
validBundle = true;
}
}
//! set bundle hash for each underlying transaction
for (std::size_t i = 0; i < transactions_.size(); i++) {
transactions_[i].setBundle(hash_);
}
}
void
Bundle::addTrytes(const std::vector<Types::Trytes>& signatureFragments) {
Types::Trytes emptySignatureFragment = Types::Utils::rightPad("", 2187, '9');
for (unsigned int i = 0; i < transactions_.size(); i++) {
auto& transaction = transactions_[i];
// Fill empty signatureMessageFragment
transaction.setSignatureFragments(
(signatureFragments.size() <= i || signatureFragments[i].empty()) ? emptySignatureFragment
: signatureFragments[i]);
// Fill empty trunkTransaction
transaction.setTrunkTransaction(EmptyHash);
// Fill empty branchTransaction
transaction.setBranchTransaction(EmptyHash);
// Fill empty nonce
transaction.setNonce(EmptyNonce);
}
}
std::vector<int8_t>
Bundle::normalizedBundle(const Types::Trytes& bundleHash) {
std::vector<int8_t> normalizedBundle(SeedLength, 0);
for (int i = 0; i < 3; i++) {
long sum = 0;
for (unsigned int j = 0; j < TryteAlphabetLength; j++) {
sum += (normalizedBundle[i * TryteAlphabetLength + j] = Types::tritsToInt<int32_t>(
Types::trytesToTrits(Types::Trytes(1, bundleHash[i * TryteAlphabetLength + j]))));
}
if (sum >= 0) {
while (sum-- > 0) {
for (unsigned int j = 0; j < TryteAlphabetLength; j++) {
if (normalizedBundle[i * TryteAlphabetLength + j] > -13) {
normalizedBundle[i * TryteAlphabetLength + j]--;
break;
}
}
}
} else {
while (sum++ < 0) {
for (unsigned int j = 0; j < TryteAlphabetLength; j++) {
if (normalizedBundle[i * TryteAlphabetLength + j] < 13) {
normalizedBundle[i * TryteAlphabetLength + j]++;
break;
}
}
}
}
}
return normalizedBundle;
}
bool
Bundle::operator<(const Bundle& rhs) const {
int64_t lhsTS = empty() ? 0 : transactions_[0].getAttachmentTimestamp();
int64_t rhsTS = rhs.empty() ? 0 : rhs[0].getAttachmentTimestamp();
return lhsTS < rhsTS;
}
bool
Bundle::operator>(const Bundle& rhs) const {
int64_t lhsTS = empty() ? 0 : transactions_[0].getAttachmentTimestamp();
int64_t rhsTS = rhs.empty() ? 0 : rhs[0].getAttachmentTimestamp();
return lhsTS > rhsTS;
}
bool
Bundle::operator==(const Bundle& rhs) const {
return getHash() == rhs.getHash();
}
bool
Bundle::operator!=(const Bundle& rhs) const {
return !operator==(rhs);
}
Transaction& Bundle::operator[](const int index) {
return transactions_[index];
}
const Transaction& Bundle::operator[](const int index) const {
return transactions_[index];
}
} // namespace Models
} // namespace IOTA
| 29.430328 | 100 | 0.662164 | wilsonfonseca |
81833316b0516dda700810c584acdd92c655d8e3 | 1,180 | cpp | C++ | DeviceCode/Targets/Native/BF537/DeviceCode/various.cpp | valoni/STM32F103 | 75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc | [
"Apache-2.0"
] | 1 | 2020-06-09T02:16:43.000Z | 2020-06-09T02:16:43.000Z | DeviceCode/Targets/Native/BF537/DeviceCode/various.cpp | valoni/STM32F103 | 75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc | [
"Apache-2.0"
] | null | null | null | DeviceCode/Targets/Native/BF537/DeviceCode/various.cpp | valoni/STM32F103 | 75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc | [
"Apache-2.0"
] | 1 | 2015-02-08T20:51:53.000Z | 2015-02-08T20:51:53.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#include "tinyhal.h"
#include "tinyhal.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
#if !defined(BUILD_RTM)
void debug_printf(char const* format, ... )
{
}
void lcd_printf(char const * format,...)
{
}
#endif
const ConfigurationSector g_ConfigurationSector;
int hal_strcpy_s( char* strDst, size_t sizeInBytes, const char* strSrc )
{
strncpy(strDst, strSrc, sizeInBytes);
}
int hal_strncpy_s( char* strDst, size_t sizeInBytes, const char* strSrc, size_t count )
{
strncpy(strDst, strSrc, __min(sizeInBytes, count));
}
///////////////////////////////////////////////////////////////////////////////////////////
| 36.875 | 221 | 0.339831 | valoni |
8183bdec4e950b8fd338c7b1916d50cd42e108c2 | 771 | cpp | C++ | JPZsumofdigits/JPZsumofdigits.cpp | jpaz26/intro-to-c-programming | 2fbabfd4f2b53135eca67f781b4a925623dac330 | [
"MIT"
] | null | null | null | JPZsumofdigits/JPZsumofdigits.cpp | jpaz26/intro-to-c-programming | 2fbabfd4f2b53135eca67f781b4a925623dac330 | [
"MIT"
] | null | null | null | JPZsumofdigits/JPZsumofdigits.cpp | jpaz26/intro-to-c-programming | 2fbabfd4f2b53135eca67f781b4a925623dac330 | [
"MIT"
] | null | null | null | // JPZsumofdigits.cpp : Defines the entry point for the console application.
// Joshua Paz; a program that takes a whole integer and adds the digits for a sum
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
//variables
int userint = 0;
int intholder = 0;
int sum = 0;
//prompt for user to enter an integer
cout << "Please enter an integer: ";
cin >> userint;
cout << endl;
//storage for the integer
intholder = userint;
//create loop to run equation
while (userint > 0) {
intholder = userint % 10;
cout << "Digit:" << intholder << endl;
sum += intholder;
userint /= 10;
}
cout << "" << endl;
cout << "The sum of the digits is: " << sum << endl; // output the sum
return 0;
}
| 20.837838 | 82 | 0.618677 | jpaz26 |
81873b4fff537b1b5e4b408d3766b4019bc9717f | 1,290 | hpp | C++ | src/kernel_preprocessor.hpp | vbkaisetsu/CLBlast | 441373c8fd1442cc4c024e59e7778b4811eb210c | [
"Apache-2.0"
] | null | null | null | src/kernel_preprocessor.hpp | vbkaisetsu/CLBlast | 441373c8fd1442cc4c024e59e7778b4811eb210c | [
"Apache-2.0"
] | null | null | null | src/kernel_preprocessor.hpp | vbkaisetsu/CLBlast | 441373c8fd1442cc4c024e59e7778b4811eb210c | [
"Apache-2.0"
] | 1 | 2020-09-09T21:04:21.000Z | 2020-09-09T21:04:21.000Z |
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This file contains the a simple pre-processor for the OpenCL kernels. This pre-processor is used
// in cases where the vendor's OpenCL compiler falls short in loop unrolling and array-to-register
// promotion. This pre-processor is specific for the CLBlast code making many assumptions.
//
// =================================================================================================
#ifndef CLBLAST_KERNEL_PREPROCESSOR_H_
#define CLBLAST_KERNEL_PREPROCESSOR_H_
#include <string>
#include "utilities/utilities.hpp"
namespace clblast {
// =================================================================================================
std::string PreprocessKernelSource(const std::string& kernel_source);
// =================================================================================================
} // namespace clblast
// CLBLAST_KERNEL_PREPROCESSOR_H_
#endif
| 39.090909 | 100 | 0.532558 | vbkaisetsu |
8187da5558734bf61db893fdf3be6507a32b506f | 297 | hh | C++ | src/ChatCommands.hh | clint-david/newserv | 40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679 | [
"MIT"
] | null | null | null | src/ChatCommands.hh | clint-david/newserv | 40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679 | [
"MIT"
] | null | null | null | src/ChatCommands.hh | clint-david/newserv | 40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679 | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
#include <memory>
#include <string>
#include "ServerState.hh"
#include "Lobby.hh"
#include "Client.hh"
void process_chat_command(std::shared_ptr<ServerState> s, std::shared_ptr<Lobby> l,
std::shared_ptr<Client> c, const std::u16string& text);
| 21.214286 | 84 | 0.700337 | clint-david |
8188d665c50246023d35ae91b9c7818a3e4a88af | 29,325 | cpp | C++ | src/appleseed/renderer/kernel/rendering/progressive/progressiveframerenderer.cpp | Aakash1312/appleseed | 0c81cacba6e513ca30a68a038afd67244f0c6b91 | [
"MIT"
] | null | null | null | src/appleseed/renderer/kernel/rendering/progressive/progressiveframerenderer.cpp | Aakash1312/appleseed | 0c81cacba6e513ca30a68a038afd67244f0c6b91 | [
"MIT"
] | null | null | null | src/appleseed/renderer/kernel/rendering/progressive/progressiveframerenderer.cpp | Aakash1312/appleseed | 0c81cacba6e513ca30a68a038afd67244f0c6b91 | [
"MIT"
] | 1 | 2020-10-01T14:42:39.000Z | 2020-10-01T14:42:39.000Z |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "progressiveframerenderer.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/kernel/rendering/iframerenderer.h"
#include "renderer/kernel/rendering/isamplegenerator.h"
#include "renderer/kernel/rendering/itilecallback.h"
#include "renderer/kernel/rendering/progressive/samplecounter.h"
#include "renderer/kernel/rendering/progressive/samplecounthistory.h"
#include "renderer/kernel/rendering/progressive/samplegeneratorjob.h"
#include "renderer/kernel/rendering/sampleaccumulationbuffer.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/project/project.h"
#include "renderer/utility/settingsparsing.h"
// appleseed.foundation headers.
#include "foundation/core/concepts/noncopyable.h"
#include "foundation/image/analysis.h"
#include "foundation/image/canvasproperties.h"
#include "foundation/image/genericimagefilereader.h"
#include "foundation/image/image.h"
#include "foundation/math/aabb.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/defaulttimers.h"
#include "foundation/platform/thread.h"
#include "foundation/platform/timers.h"
#include "foundation/platform/types.h"
#include "foundation/utility/api/apistring.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/gnuplotfile.h"
#include "foundation/utility/job.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/statistics.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
// Boost headers.
#include "boost/filesystem.hpp"
// Standard headers.
#include <cassert>
#include <cmath>
#include <cstddef>
#include <limits>
#include <memory>
#include <string>
#include <vector>
using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;
namespace renderer
{
namespace
{
//
// Progressive frame renderer.
//
//#define PRINT_DISPLAY_THREAD_PERFS
class ProgressiveFrameRenderer
: public IFrameRenderer
{
public:
ProgressiveFrameRenderer(
const Project& project,
ISampleGeneratorFactory* generator_factory,
ITileCallbackFactory* callback_factory,
const ParamArray& params)
: m_project(project)
, m_params(params)
, m_sample_counter(m_params.m_max_sample_count)
, m_ref_image_avg_lum(0.0)
{
// We must have a generator factory, but it's OK not to have a callback factory.
assert(generator_factory);
// Create an accumulation buffer.
m_buffer.reset(generator_factory->create_sample_accumulation_buffer());
// Create and initialize the job manager.
m_job_manager.reset(
new JobManager(
global_logger(),
m_job_queue,
m_params.m_thread_count,
JobManager::KeepRunningOnEmptyQueue));
// Instantiate sample generators, one per rendering thread.
m_sample_generators.reserve(m_params.m_thread_count);
for (size_t i = 0; i < m_params.m_thread_count; ++i)
{
m_sample_generators.push_back(
generator_factory->create(i, m_params.m_thread_count));
}
// Create rendering jobs, one per rendering thread.
m_sample_generator_jobs.reserve(m_params.m_thread_count);
for (size_t i = 0; i < m_params.m_thread_count; ++i)
{
m_sample_generator_jobs.push_back(
new SampleGeneratorJob(
*m_buffer.get(),
m_sample_generators[i],
m_sample_counter,
m_params.m_spectrum_mode,
m_job_queue,
i, // job index
m_params.m_thread_count, // job count
m_abort_switch));
}
// Instantiate a single tile callback.
if (callback_factory)
m_tile_callback.reset(callback_factory->create());
// Load the reference image if one is specified.
if (!m_params.m_ref_image_path.empty())
{
const string ref_image_path =
to_string(project.search_paths().qualify(m_params.m_ref_image_path));
RENDERER_LOG_DEBUG("loading reference image %s...", ref_image_path.c_str());
GenericImageFileReader reader;
m_ref_image.reset(reader.read(ref_image_path.c_str()));
if (are_images_compatible(m_project.get_frame()->image(), *m_ref_image))
{
m_ref_image_avg_lum = compute_average_luminance(*m_ref_image.get());
RENDERER_LOG_DEBUG(
"reference image average luminance is %s.",
pretty_scalar(m_ref_image_avg_lum, 6).c_str());
}
else
{
RENDERER_LOG_ERROR(
"the reference image is not compatible with the output frame "
"(different dimensions, tile size or number of channels).");
m_ref_image.reset();
}
}
RENDERER_LOG_INFO(
"rendering settings:\n"
" spectrum mode %s\n"
" sampling mode %s\n"
" threads %s",
get_spectrum_mode_name(get_spectrum_mode(params)).c_str(),
get_sampling_context_mode_name(get_sampling_context_mode(params)).c_str(),
pretty_int(m_params.m_thread_count).c_str());
}
~ProgressiveFrameRenderer() override
{
// Stop the statistics thread.
m_abort_switch.abort();
if (m_statistics_thread.get() && m_statistics_thread->joinable())
m_statistics_thread->join();
// Stop the display thread.
m_display_thread_abort_switch.abort();
if (m_display_thread.get() && m_display_thread->joinable())
m_display_thread->join();
// Delete the tile callback.
m_tile_callback.reset();
// Delete rendering jobs.
for (const_each<SampleGeneratorJobVector> i = m_sample_generator_jobs; i; ++i)
delete *i;
// Delete sample generators.
for (const_each<SampleGeneratorVector> i = m_sample_generators; i; ++i)
(*i)->release();
}
void release() override
{
delete this;
}
void render() override
{
start_rendering();
m_job_queue.wait_until_completion();
}
bool is_rendering() const override
{
return m_job_queue.has_scheduled_or_running_jobs();
}
void start_rendering() override
{
assert(!is_rendering());
assert(!m_job_queue.has_scheduled_or_running_jobs());
m_abort_switch.clear();
m_buffer->clear();
m_sample_counter.clear();
// Reset sample generators.
for (size_t i = 0, e = m_sample_generators.size(); i < e; ++i)
m_sample_generators[i]->reset();
// Schedule rendering jobs.
for (size_t i = 0, e = m_sample_generator_jobs.size(); i < e; ++i)
{
m_job_queue.schedule(
m_sample_generator_jobs[i],
false); // don't transfer ownership of the job to the queue
}
// Start job execution.
m_job_manager->start();
// Create and start the statistics thread.
m_statistics_func.reset(
new StatisticsFunc(
m_project,
*m_buffer.get(),
m_params.m_perf_stats,
m_params.m_luminance_stats,
m_ref_image.get(),
m_ref_image_avg_lum,
m_abort_switch));
m_statistics_thread.reset(
new boost::thread(
ThreadFunctionWrapper<StatisticsFunc>(m_statistics_func.get())));
// Create and start the display thread.
if (m_tile_callback.get() != nullptr && m_display_thread.get() == nullptr)
{
m_display_func.reset(
new DisplayFunc(
*m_project.get_frame(),
*m_buffer.get(),
m_tile_callback.get(),
m_params.m_max_sample_count,
m_params.m_max_fps,
m_display_thread_abort_switch));
m_display_thread.reset(
new boost::thread(
ThreadFunctionWrapper<DisplayFunc>(m_display_func.get())));
}
// Resume rendering if it was paused.
resume_rendering();
}
void stop_rendering() override
{
// First, delete scheduled jobs to prevent worker threads from picking them up.
m_job_queue.clear_scheduled_jobs();
// Tell rendering jobs and the statistics thread to stop.
m_abort_switch.abort();
// Wait until rendering jobs have effectively stopped.
m_job_queue.wait_until_completion();
// Wait until the statistics thread has stopped.
m_statistics_thread->join();
}
void pause_rendering() override
{
m_job_manager->pause();
if (m_display_func.get())
m_display_func->pause();
m_statistics_func->pause();
}
void resume_rendering() override
{
m_statistics_func->resume();
if (m_display_func.get())
m_display_func->resume();
m_job_manager->resume();
}
void terminate_rendering() override
{
// Completely stop rendering.
stop_rendering();
m_job_manager->stop();
// The statistics thread has already been joined in stop_rendering().
m_statistics_thread.reset();
m_statistics_func.reset();
// Join and delete the display thread.
if (m_display_thread.get())
{
m_display_thread_abort_switch.abort();
m_display_thread->join();
m_display_thread.reset();
}
// Make sure the remaining calls of this method don't get interrupted.
m_abort_switch.clear();
m_display_thread_abort_switch.clear();
if (m_display_func.get())
{
// Merge the last samples and display the final frame.
m_display_func->develop_and_display();
m_display_func.reset();
}
else
{
// Just merge the last samples into the frame.
m_buffer->develop_to_frame(*m_project.get_frame(), m_abort_switch);
}
// Merge and print sample generator statistics.
print_sample_generators_stats();
}
private:
//
// Progressive frame renderer parameters.
//
struct Parameters
{
const Spectrum::Mode m_spectrum_mode;
const size_t m_thread_count; // number of rendering threads
const uint64 m_max_sample_count; // maximum total number of samples to compute
const double m_max_fps; // maximum display frequency in frames/second
const bool m_perf_stats; // collect and print performance statistics?
const bool m_luminance_stats; // collect and print luminance statistics?
const string m_ref_image_path; // path to the reference image
explicit Parameters(const ParamArray& params)
: m_spectrum_mode(get_spectrum_mode(params))
, m_thread_count(get_rendering_thread_count(params))
, m_max_sample_count(params.get_optional<uint64>("max_samples", numeric_limits<uint64>::max()))
, m_max_fps(params.get_optional<double>("max_fps", 30.0))
, m_perf_stats(params.get_optional<bool>("performance_statistics", false))
, m_luminance_stats(params.get_optional<bool>("luminance_statistics", false))
, m_ref_image_path(params.get_optional<string>("reference_image", ""))
{
}
};
//
// Frame display thread.
//
class DisplayFunc
: public NonCopyable
{
public:
DisplayFunc(
Frame& frame,
SampleAccumulationBuffer& buffer,
ITileCallback* tile_callback,
const uint64 max_sample_count,
const double max_fps,
IAbortSwitch& abort_switch)
: m_frame(frame)
, m_buffer(buffer)
, m_tile_callback(tile_callback)
, m_min_sample_count(min<uint64>(max_sample_count, 32 * 32 * 2))
, m_target_elapsed(1.0 / max_fps)
, m_abort_switch(abort_switch)
{
}
void pause()
{
m_pause_flag.set();
}
void resume()
{
m_pause_flag.clear();
}
void operator()()
{
set_current_thread_name("display");
DefaultWallclockTimer timer;
const double rcp_timer_freq = 1.0 / timer.frequency();
uint64 last_time = timer.read();
#ifdef PRINT_DISPLAY_THREAD_PERFS
m_stopwatch.start();
#endif
while (!m_abort_switch.is_aborted())
{
if (m_pause_flag.is_clear())
{
// It's time to display but the sample accumulation buffer doesn't contain
// enough samples yet. Giving up would lead to noticeable jerkiness, so we
// wait until enough samples are available.
while (!m_abort_switch.is_aborted() &&
m_buffer.get_sample_count() < m_min_sample_count)
yield();
// Merge the samples and display the final frame.
develop_and_display();
}
// Compute time elapsed since last call to display().
const uint64 time = timer.read();
const double elapsed = (time - last_time) * rcp_timer_freq;
last_time = time;
// Limit display rate.
if (elapsed < m_target_elapsed)
{
const double ms = ceil(1000.0 * (m_target_elapsed - elapsed));
sleep(truncate<uint32>(ms), m_abort_switch);
}
}
}
void develop_and_display()
{
#ifdef PRINT_DISPLAY_THREAD_PERFS
m_stopwatch.measure();
const double t1 = m_stopwatch.get_seconds();
#endif
// Develop the accumulation buffer to the frame.
m_buffer.develop_to_frame(m_frame, m_abort_switch);
#ifdef PRINT_DISPLAY_THREAD_PERFS
m_stopwatch.measure();
const double t2 = m_stopwatch.get_seconds();
#endif
// Make sure we don't present incomplete frames.
if (m_abort_switch.is_aborted())
return;
// Present the frame.
m_tile_callback->on_progressive_frame_end(&m_frame);
#ifdef PRINT_DISPLAY_THREAD_PERFS
m_stopwatch.measure();
const double t3 = m_stopwatch.get_seconds();
RENDERER_LOG_DEBUG(
"display thread:\n"
" buffer to frame %s\n"
" frame to widget %s\n"
" total %s (%s fps)",
pretty_time(t2 - t1).c_str(),
pretty_time(t3 - t2).c_str(),
pretty_time(t3 - t1).c_str(),
pretty_ratio(1.0, t3 - t1).c_str());
#endif
}
private:
Frame& m_frame;
SampleAccumulationBuffer& m_buffer;
ITileCallback* m_tile_callback;
const uint64 m_min_sample_count;
const double m_target_elapsed;
IAbortSwitch& m_abort_switch;
ThreadFlag m_pause_flag;
Stopwatch<DefaultWallclockTimer> m_stopwatch;
};
//
// Statistics gathering and printing thread.
//
class StatisticsFunc
: public NonCopyable
{
public:
StatisticsFunc(
const Project& project,
SampleAccumulationBuffer& buffer,
const bool perf_stats,
const bool luminance_stats,
const Image* ref_image,
const double ref_image_avg_lum,
IAbortSwitch& abort_switch)
: m_project(project)
, m_buffer(buffer)
, m_perf_stats(perf_stats)
, m_luminance_stats(luminance_stats)
, m_ref_image(ref_image)
, m_ref_image_avg_lum(ref_image_avg_lum)
, m_abort_switch(abort_switch)
, m_rcp_timer_frequency(1.0 / m_timer.frequency())
, m_timer_start_value(m_timer.read())
{
const Vector2u crop_window_extent = m_project.get_frame()->get_crop_window().extent();
const size_t pixel_count = (crop_window_extent.x + 1) * (crop_window_extent.y + 1);
m_rcp_pixel_count = 1.0 / pixel_count;
}
~StatisticsFunc()
{
if (!m_sample_count_records.empty())
{
const string filepath =
(bf::path(m_project.search_paths().get_root_path().c_str()) / "sample_count.gnuplot").string();
RENDERER_LOG_DEBUG("writing %s...", filepath.c_str());
GnuplotFile plotfile;
plotfile.set_xlabel("Time");
plotfile.set_ylabel("Samples");
plotfile
.new_plot()
.set_points(m_sample_count_records)
.set_title("Total Sample Count Over Time");
plotfile.write(filepath);
}
if (!m_rmsd_records.empty())
{
const string filepath =
(bf::path(m_project.search_paths().get_root_path().c_str()) / "rms_deviation.gnuplot").string();
RENDERER_LOG_DEBUG("writing %s...", filepath.c_str());
GnuplotFile plotfile;
plotfile.set_xlabel("Samples per Pixel");
plotfile.set_ylabel("RMS Deviation");
plotfile
.new_plot()
.set_points(m_rmsd_records)
.set_title("RMS Deviation Over Time");
plotfile.write(filepath);
}
}
void pause()
{
m_pause_flag.set();
}
void resume()
{
m_pause_flag.clear();
}
void operator()()
{
set_current_thread_name("statistics");
while (!m_abort_switch.is_aborted())
{
if (m_pause_flag.is_clear())
{
const double time = (m_timer.read() - m_timer_start_value) * m_rcp_timer_frequency;
record_and_print_perf_stats(time);
if (m_luminance_stats || m_ref_image)
record_and_print_convergence_stats();
}
sleep(1000, m_abort_switch);
}
}
private:
const Project& m_project;
SampleAccumulationBuffer& m_buffer;
const bool m_perf_stats;
const bool m_luminance_stats;
const Image* m_ref_image;
const double m_ref_image_avg_lum;
IAbortSwitch& m_abort_switch;
ThreadFlag m_pause_flag;
DefaultWallclockTimer m_timer;
double m_rcp_timer_frequency;
uint64 m_timer_start_value;
double m_rcp_pixel_count;
SampleCountHistory<128> m_sample_count_history;
vector<Vector2d> m_sample_count_records; // total sample count over time
vector<Vector2d> m_rmsd_records; // RMS deviation over time
void record_and_print_perf_stats(const double time)
{
const uint64 samples = m_buffer.get_sample_count();
m_sample_count_history.insert(time, samples);
const double samples_per_pixel = samples * m_rcp_pixel_count;
const uint64 samples_per_second = truncate<uint64>(m_sample_count_history.get_samples_per_second());
RENDERER_LOG_INFO(
"%s samples, %s samples/pixel, %s samples/second",
pretty_uint(samples).c_str(),
pretty_scalar(samples_per_pixel).c_str(),
pretty_uint(samples_per_second).c_str());
if (m_perf_stats)
m_sample_count_records.emplace_back(time, static_cast<double>(samples));
}
void record_and_print_convergence_stats()
{
assert(m_luminance_stats || m_ref_image);
string output;
if (m_luminance_stats)
{
const double avg_lum = compute_average_luminance(m_project.get_frame()->image());
output += "average luminance " + pretty_scalar(avg_lum, 6);
if (m_ref_image)
{
const double avg_lum_delta = abs(m_ref_image_avg_lum - avg_lum);
output += " (";
output += pretty_percent(avg_lum_delta, m_ref_image_avg_lum, 3);
output += " error)";
}
}
if (m_ref_image)
{
const double samples_per_pixel = m_buffer.get_sample_count() * m_rcp_pixel_count;
const double rmsd = compute_rms_deviation(m_project.get_frame()->image(), *m_ref_image);
m_rmsd_records.emplace_back(samples_per_pixel, rmsd);
if (m_luminance_stats)
output += ", ";
output += "rms deviation " + pretty_scalar(rmsd, 6);
}
RENDERER_LOG_DEBUG("%s", output.c_str());
}
};
//
// Progressive frame renderer implementation details.
//
const Project& m_project;
const Parameters m_params;
SampleCounter m_sample_counter;
unique_ptr<SampleAccumulationBuffer> m_buffer;
JobQueue m_job_queue;
unique_ptr<JobManager> m_job_manager;
AbortSwitch m_abort_switch;
typedef vector<ISampleGenerator*> SampleGeneratorVector;
SampleGeneratorVector m_sample_generators;
typedef vector<SampleGeneratorJob*> SampleGeneratorJobVector;
SampleGeneratorJobVector m_sample_generator_jobs;
auto_release_ptr<ITileCallback> m_tile_callback;
unique_ptr<Image> m_ref_image;
double m_ref_image_avg_lum;
unique_ptr<DisplayFunc> m_display_func;
unique_ptr<boost::thread> m_display_thread;
AbortSwitch m_display_thread_abort_switch;
unique_ptr<StatisticsFunc> m_statistics_func;
unique_ptr<boost::thread> m_statistics_thread;
void print_sample_generators_stats() const
{
assert(!m_sample_generators.empty());
StatisticsVector stats;
for (size_t i = 0; i < m_sample_generators.size(); ++i)
stats.merge(m_sample_generators[i]->get_statistics());
RENDERER_LOG_DEBUG("%s", stats.to_string().c_str());
}
};
}
//
// ProgressiveFrameRendererFactory class implementation.
//
ProgressiveFrameRendererFactory::ProgressiveFrameRendererFactory(
const Project& project,
ISampleGeneratorFactory* generator_factory,
ITileCallbackFactory* callback_factory,
const ParamArray& params)
: m_project(project)
, m_generator_factory(generator_factory)
, m_callback_factory(callback_factory)
, m_params(params)
{
}
void ProgressiveFrameRendererFactory::release()
{
delete this;
}
IFrameRenderer* ProgressiveFrameRendererFactory::create()
{
return
new ProgressiveFrameRenderer(
m_project,
m_generator_factory,
m_callback_factory,
m_params);
}
IFrameRenderer* ProgressiveFrameRendererFactory::create(
const Project& project,
ISampleGeneratorFactory* generator_factory,
ITileCallbackFactory* callback_factory,
const ParamArray& params)
{
return
new ProgressiveFrameRenderer(
project,
generator_factory,
callback_factory,
params);
}
Dictionary ProgressiveFrameRendererFactory::get_params_metadata()
{
Dictionary metadata;
metadata.dictionaries().insert(
"max_fps",
Dictionary()
.insert("type", "float")
.insert("default", "30.0")
.insert("label", "Max FPS")
.insert("help", "Maximum progressive rendering update rate in frames per second"));
metadata.dictionaries().insert(
"max_samples",
Dictionary()
.insert("type", "int")
.insert("label", "Max Samples")
.insert("help", "Maximum number of samples per pixel"));
return metadata;
}
} // namespace renderer
| 36.840452 | 120 | 0.541176 | Aakash1312 |
8188e3941d6519d466adae0e0c84c853f659ccfa | 2,591 | cpp | C++ | pwiz/analysis/eharmony/Matrix.cpp | edyp-lab/pwiz-mzdb | d13ce17f4061596c7e3daf9cf5671167b5996831 | [
"Apache-2.0"
] | 11 | 2015-01-08T08:33:44.000Z | 2019-07-12T06:14:54.000Z | pwiz/analysis/eharmony/Matrix.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 61 | 2015-05-27T11:20:11.000Z | 2019-12-20T15:06:21.000Z | pwiz/analysis/eharmony/Matrix.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 4 | 2016-02-03T09:41:16.000Z | 2021-08-01T18:42:36.000Z | //
// $Id: Matrix.cpp 1539 2009-11-19 20:12:28Z khoff $
//
//
// Original author: Kate Hoff <[email protected]>
//
// Copyright 2009 Center for Applied Molecular Medicine
// University of Southern California, Los Angeles, CA
//
// 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.
//
///
/// Matrix.cpp
///
#include "Matrix.hpp"
#include <iostream>
using namespace pwiz;
using namespace eharmony;
Matrix::Matrix(const int& r, const int& c)
{
_rows = vector<vector<double> >(r, vector<double>(c));
_columns = vector<vector<double> >(c, vector<double>(r));
for(int row_index = 0; row_index != r; ++row_index)
{
for(int column_index = 0; column_index != c; ++column_index)
{
_data.insert(make_pair(0,make_pair(row_index,column_index)));
}
}
}
void Matrix::insert(const double& value, const int& rowCoordinate, const int& columnCoordinate)
{
double oldValue = access(rowCoordinate, columnCoordinate);
pair<multimap<double, pair<int,int> >::iterator, multimap<double, pair<int,int> >::iterator> candidates = _data.equal_range(oldValue);
pair<int, int> coords = make_pair(rowCoordinate, columnCoordinate);
multimap<double, pair<int,int> >::iterator it = candidates.first;
for(; it != candidates.second; ++it ) if (it->second == coords) _data.erase(it);
_rows.at(rowCoordinate).at(columnCoordinate) = value;
_columns.at(columnCoordinate).at(rowCoordinate) = value;
_data.insert(make_pair(value, make_pair(rowCoordinate, columnCoordinate)));
}
double Matrix::access(const int& rowCoordinate, const int& columnCoordinate)
{
return _rows.at(rowCoordinate).at(columnCoordinate);
}
ostream& Matrix::write(ostream& os)
{
vector<vector<double> >::const_iterator it = _rows.begin();
for( ; it != _rows.end(); ++it)
{
vector<double>::const_iterator jt = it->begin();
for( ; jt!= it->end(); ++jt)
{
os << *jt << " ";
}
os << endl;
}
return os;
}
| 29.443182 | 138 | 0.655345 | edyp-lab |
818900af12ffe2d35a6f05743c05d9d999fc5da8 | 3,816 | cc | C++ | towr/src/base_motion_constraint.cc | eeoozz/towr | 189fd39b156d1ed80894c3d9086da1b8f7426de3 | [
"BSD-3-Clause"
] | 592 | 2018-01-30T10:36:47.000Z | 2022-03-28T16:40:16.000Z | towr/src/base_motion_constraint.cc | eeoozz/towr | 189fd39b156d1ed80894c3d9086da1b8f7426de3 | [
"BSD-3-Clause"
] | 68 | 2018-02-08T06:00:16.000Z | 2022-03-31T08:46:05.000Z | towr/src/base_motion_constraint.cc | eeoozz/towr | 189fd39b156d1ed80894c3d9086da1b8f7426de3 | [
"BSD-3-Clause"
] | 185 | 2018-02-11T03:22:30.000Z | 2022-03-28T12:56:21.000Z | /******************************************************************************
Copyright (c) 2018, Alexander W. Winkler. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include <towr/constraints/base_motion_constraint.h>
#include <towr/variables/variable_names.h>
#include <towr/variables/cartesian_dimensions.h>
#include <towr/variables/spline_holder.h>
namespace towr {
BaseMotionConstraint::BaseMotionConstraint (double T, double dt,
const SplineHolder& spline_holder)
:TimeDiscretizationConstraint(T, dt, "baseMotion")
{
base_linear_ = spline_holder.base_linear_;
base_angular_ = spline_holder.base_angular_;
double dev_rad = 0.05;
node_bounds_.resize(k6D);
node_bounds_.at(AX) = Bounds(-dev_rad, dev_rad);
node_bounds_.at(AY) = Bounds(-dev_rad, dev_rad);
node_bounds_.at(AZ) = ifopt::NoBound;//Bounds(-dev_rad, dev_rad);
double z_init = base_linear_->GetPoint(0.0).p().z();
node_bounds_.at(LX) = ifopt::NoBound;
node_bounds_.at(LY) = ifopt::NoBound;//Bounds(-0.05, 0.05);
node_bounds_.at(LZ) = Bounds(z_init-0.02, z_init+0.1); // allow to move dev_z cm up and down
int n_constraints_per_node = node_bounds_.size();
SetRows(GetNumberOfNodes()*n_constraints_per_node);
}
void
BaseMotionConstraint::UpdateConstraintAtInstance (double t, int k,
VectorXd& g) const
{
g.middleRows(GetRow(k, LX), k3D) = base_linear_->GetPoint(t).p();
g.middleRows(GetRow(k, AX), k3D) = base_angular_->GetPoint(t).p();
}
void
BaseMotionConstraint::UpdateBoundsAtInstance (double t, int k, VecBound& bounds) const
{
for (int dim=0; dim<node_bounds_.size(); ++dim)
bounds.at(GetRow(k,dim)) = node_bounds_.at(dim);
}
void
BaseMotionConstraint::UpdateJacobianAtInstance (double t, int k,
std::string var_set,
Jacobian& jac) const
{
if (var_set == id::base_ang_nodes)
jac.middleRows(GetRow(k,AX), k3D) = base_angular_->GetJacobianWrtNodes(t, kPos);
if (var_set == id::base_lin_nodes)
jac.middleRows(GetRow(k,LX), k3D) = base_linear_->GetJacobianWrtNodes(t, kPos);
}
int
BaseMotionConstraint::GetRow (int node, int dim) const
{
return node*node_bounds_.size() + dim;
}
} /* namespace towr */
| 40.595745 | 94 | 0.697065 | eeoozz |
818b46118366b6beea8b61c9c2605af1b5647166 | 402 | cpp | C++ | Menu Interno Console/Main.cpp | FuckLaw/Menu-Interno-Console | 8fb2fcd63d280b7443a09daba1c9fbcae57b6a22 | [
"MIT"
] | 1 | 2020-04-09T22:11:47.000Z | 2020-04-09T22:11:47.000Z | Menu Interno Console/Main.cpp | FuckLaw/Menu-Interno-Console | 8fb2fcd63d280b7443a09daba1c9fbcae57b6a22 | [
"MIT"
] | null | null | null | Menu Interno Console/Main.cpp | FuckLaw/Menu-Interno-Console | 8fb2fcd63d280b7443a09daba1c9fbcae57b6a22 | [
"MIT"
] | null | null | null | #include <Windows.h>
#include "Includes.h"
#include "Menu.h"
#include "Keyboard.h"
#include "Items.h"
#include "Colors.h"
#include "EnableDebug.h"
#include "Hacks.h"
#include "DrawMenu.h"
BOOL APIENTRY DllMain(HMODULE hmodule, DWORD ui_reason_for_call, LPVOID lpReserved)
{
EnableDebugPrivilege();
if (ui_reason_for_call == DLL_PROCESS_ATTACH)
{
DrawMenu();
}
return true;
} | 20.1 | 84 | 0.701493 | FuckLaw |
818e8bc200fae67e4e4aa14fb7e82805adc23ebc | 548 | hpp | C++ | src/reporter/resources/rp_different_type_report_resources.hpp | lpea/cppinclude | dc126c6057d2fe30569e6e86f66d2c8eebb50212 | [
"MIT"
] | 177 | 2020-08-24T19:20:35.000Z | 2022-03-27T01:58:04.000Z | src/reporter/resources/rp_different_type_report_resources.hpp | lpea/cppinclude | dc126c6057d2fe30569e6e86f66d2c8eebb50212 | [
"MIT"
] | 15 | 2020-08-30T17:59:42.000Z | 2022-01-12T11:14:10.000Z | src/reporter/resources/rp_different_type_report_resources.hpp | lpea/cppinclude | dc126c6057d2fe30569e6e86f66d2c8eebb50212 | [
"MIT"
] | 11 | 2020-09-17T23:31:10.000Z | 2022-03-04T13:15:21.000Z | #pragma once
//------------------------------------------------------------------------------
namespace reporter::resources::different_type_report
{
//------------------------------------------------------------------------------
extern const char * const Name;
extern const char * const Header;
extern const char * const UserIncludeLabel;
extern const char * const SystemIncludeLabel;
extern const char * const FileFmt;
extern const char * const DetailFmt;
//------------------------------------------------------------------------------
}
| 26.095238 | 80 | 0.432482 | lpea |
818f5d7c3c20565e970518af1ea7f57a32ec325a | 947 | hpp | C++ | robot2019-ros/initial_pose/include/initialpose_node.hpp | junhuizhou/ROS_Learning | bb3a0c867ba2bd147bbd59176cf1224c09a63914 | [
"MIT"
] | null | null | null | robot2019-ros/initial_pose/include/initialpose_node.hpp | junhuizhou/ROS_Learning | bb3a0c867ba2bd147bbd59176cf1224c09a63914 | [
"MIT"
] | 1 | 2021-05-07T07:30:11.000Z | 2021-05-07T07:30:11.000Z | robot2019-ros/initial_pose/include/initialpose_node.hpp | junhuizhou/ROS_Learning | bb3a0c867ba2bd147bbd59176cf1224c09a63914 | [
"MIT"
] | null | null | null | #ifndef INITIALPOSE_NODE_H
#define INITIALPOSE_NODE_H
#include <initialpose_include.hpp>
#include <initialpose_config.hpp>
#include <initialpose_estimation.hpp>
class initialpose_node {
public:
initialpose_node(std::string node_name);
bool setTransform(std::string laser_topic_name);
bool GetStaticMap();
void LaserScanCallback(const sensor_msgs::LaserScanConstPtr msg);
void GameStatusCallback(const roborts_msgs::GameStatusPtr msg);
public:
std::unique_ptr<initialpose_estimation> estimator_ptr_;
bool CheckSide_WithLaser_Valid_ = false;
double x_lb_;
double y_lb_;
double alpha_lb_;
double cos_alpha_lb_;
double sin_alpha_lb_;
private:
ros::NodeHandle n_;
ros::Subscriber LaserScan_sub_;
ros::Subscriber GameStatus_sub_;
ros::ServiceClient static_map_srv_;
std::unique_ptr<tf::TransformListener> tf_listener_ptr_;
std::string base_frame_;
ros::Publisher initialpose_pub_;
bool is_status_valid_;
};
#endif | 21.522727 | 66 | 0.80359 | junhuizhou |
819474638dc5b1cca9837569cd09459ab6c47db7 | 2,199 | cpp | C++ | src/cpp/wkbreader.cpp | sanak/node-geos-c | 7cd965a72627e6a9034c3e2bdb9f9acc5057f868 | [
"MIT"
] | 19 | 2015-01-25T16:50:48.000Z | 2021-08-17T11:34:34.000Z | src/cpp/wkbreader.cpp | sanak/node-geos-c | 7cd965a72627e6a9034c3e2bdb9f9acc5057f868 | [
"MIT"
] | 8 | 2016-03-23T18:29:47.000Z | 2022-01-04T07:18:26.000Z | src/cpp/wkbreader.cpp | sanak/node-geos | 7cd965a72627e6a9034c3e2bdb9f9acc5057f868 | [
"MIT"
] | 9 | 2015-02-04T03:52:40.000Z | 2020-10-11T07:11:02.000Z | #include "wkbreader.hpp"
#include <sstream>
WKBReader::WKBReader() {
_reader = new geos::io::WKBReader();
}
WKBReader::WKBReader(const geos::geom::GeometryFactory *gf) {
_reader = new geos::io::WKBReader(*gf);
}
WKBReader::~WKBReader() {}
Persistent<Function> WKBReader::constructor;
void WKBReader::Initialize(Handle<Object> target)
{
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, WKBReader::New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(String::NewFromUtf8(isolate, "WKBReader"));
NODE_SET_PROTOTYPE_METHOD(tpl, "readHEX", WKBReader::ReadHEX);
constructor.Reset(isolate, tpl->GetFunction());
target->Set(String::NewFromUtf8(isolate, "WKBReader"), tpl->GetFunction());
}
void WKBReader::New(const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
WKBReader *wkbReader;
if(args.Length() == 1) {
GeometryFactory *factory = ObjectWrap::Unwrap<GeometryFactory>(args[0]->ToObject());
wkbReader = new WKBReader(factory->_factory);
} else {
wkbReader = new WKBReader();
}
wkbReader->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
void WKBReader::ReadHEX(const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
WKBReader* reader = ObjectWrap::Unwrap<WKBReader>(args.This());
String::Utf8Value hex(args[0]->ToString());
std::string str = std::string(*hex);
std::istringstream is( str );
try {
geos::geom::Geometry* geom = reader->_reader->readHEX(is);
args.GetReturnValue().Set(Geometry::New(geom));
} catch (geos::io::ParseException e) {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, e.what())));
} catch (geos::util::GEOSException e) {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, e.what())));
} catch (...) {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "Exception while reading WKB.")));
}
}
| 31.414286 | 112 | 0.678035 | sanak |
8196c292c22d7abf127a7afbe219296c7696d64f | 18,247 | cpp | C++ | SpatialGDK/Source/SpatialGDK/Private/Utils/SpatialDebugger.cpp | Bowbee/GDKPrebuilt | 420b3fa19fdc36755a43e655c057b5624264407a | [
"MIT"
] | 363 | 2018-07-30T12:57:42.000Z | 2022-03-25T14:30:28.000Z | SpatialGDK/Source/SpatialGDK/Private/Utils/SpatialDebugger.cpp | Bowbee/GDKPrebuilt | 420b3fa19fdc36755a43e655c057b5624264407a | [
"MIT"
] | 1,634 | 2018-07-30T14:30:25.000Z | 2022-03-03T01:55:15.000Z | SpatialGDK/Source/SpatialGDK/Private/Utils/SpatialDebugger.cpp | Bowbee/GDKPrebuilt | 420b3fa19fdc36755a43e655c057b5624264407a | [
"MIT"
] | 153 | 2018-07-31T13:45:02.000Z | 2022-03-03T05:20:24.000Z | // Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#include "Utils/SpatialDebugger.h"
#include "EngineClasses/SpatialNetDriver.h"
#include "Interop/SpatialReceiver.h"
#include "Interop/SpatialSender.h"
#include "Interop/SpatialStaticComponentView.h"
#include "LoadBalancing/GridBasedLBStrategy.h"
#include "LoadBalancing/LayeredLBStrategy.h"
#include "LoadBalancing/WorkerRegion.h"
#include "Schema/AuthorityIntent.h"
#include "Schema/SpatialDebugging.h"
#include "SpatialCommonTypes.h"
#include "Utils/InspectionColors.h"
#include "Debug/DebugDrawService.h"
#include "Engine/Engine.h"
#include "GameFramework/Pawn.h"
#include "GameFramework/PlayerController.h"
#include "GameFramework/PlayerState.h"
#include "GenericPlatform/GenericPlatformMath.h"
#include "Kismet/GameplayStatics.h"
#include "Net/UnrealNetwork.h"
using namespace SpatialGDK;
DEFINE_LOG_CATEGORY(LogSpatialDebugger);
namespace
{
const FString DEFAULT_WORKER_REGION_MATERIAL = TEXT("/SpatialGDK/SpatialDebugger/Materials/TranslucentWorkerRegion.TranslucentWorkerRegion");
}
ASpatialDebugger::ASpatialDebugger(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.bStartWithTickEnabled = true;
PrimaryActorTick.TickInterval = 1.f;
bAlwaysRelevant = true;
bNetLoadOnClient = false;
bReplicates = true;
NetUpdateFrequency = 1.f;
NetDriver = Cast<USpatialNetDriver>(GetNetDriver());
// For GDK design reasons, this is the approach chosen to get a pointer
// on the net driver to the client ASpatialDebugger. Various alternatives
// were considered and this is the best of a bad bunch.
if (NetDriver != nullptr && GetNetMode() == NM_Client)
{
NetDriver->SetSpatialDebugger(this);
}
}
void ASpatialDebugger::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION(ASpatialDebugger, WorkerRegions, COND_SimulatedOnly);
}
void ASpatialDebugger::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
check(NetDriver != nullptr);
if (!NetDriver->IsServer())
{
for (TMap<Worker_EntityId_Key, TWeakObjectPtr<AActor>>::TIterator It = EntityActorMapping.CreateIterator(); It; ++It)
{
if (!It->Value.IsValid())
{
It.RemoveCurrent();
}
}
// Since we have no guarantee on the order we'll receive the PC/Pawn/PlayerState
// over the wire, we check here once per tick (currently 1 Hz tick rate) to setup our local pointers.
// Note that we can capture the PC in OnEntityAdded() since we know we will only receive one of those.
if (LocalPawn.IsValid() == false && LocalPlayerController.IsValid())
{
LocalPawn = LocalPlayerController->GetPawn();
}
if (LocalPlayerState.IsValid() == false && LocalPawn.IsValid())
{
LocalPlayerState = LocalPawn->GetPlayerState();
}
if (LocalPawn.IsValid())
{
SCOPE_CYCLE_COUNTER(STAT_SortingActors);
const FVector& PlayerLocation = LocalPawn->GetActorLocation();
EntityActorMapping.ValueSort([PlayerLocation](const TWeakObjectPtr<AActor>& A, const TWeakObjectPtr<AActor>& B) {
return FVector::Dist(PlayerLocation, A->GetActorLocation()) > FVector::Dist(PlayerLocation, B->GetActorLocation());
});
}
}
}
void ASpatialDebugger::BeginPlay()
{
Super::BeginPlay();
check(NetDriver != nullptr);
if (!NetDriver->IsServer())
{
EntityActorMapping.Reserve(ENTITY_ACTOR_MAP_RESERVATION_COUNT);
LoadIcons();
TArray<Worker_EntityId_Key> EntityIds;
NetDriver->StaticComponentView->GetEntityIds(EntityIds);
// Capture any entities that are already present on this client (ie they came over the wire before the SpatialDebugger did).
for (const Worker_EntityId_Key EntityId : EntityIds)
{
OnEntityAdded(EntityId);
}
// Register callbacks to get notified of all future entity arrivals / deletes.
OnEntityAddedHandle = NetDriver->Receiver->OnEntityAddedDelegate.AddUObject(this, &ASpatialDebugger::OnEntityAdded);
OnEntityRemovedHandle = NetDriver->Receiver->OnEntityRemovedDelegate.AddUObject(this, &ASpatialDebugger::OnEntityRemoved);
FontRenderInfo.bClipText = true;
FontRenderInfo.bEnableShadow = true;
RenderFont = GEngine->GetSmallFont();
if (bAutoStart)
{
SpatialToggleDebugger();
}
}
}
void ASpatialDebugger::OnAuthorityGained()
{
if (NetDriver->LoadBalanceStrategy)
{
const ULayeredLBStrategy* LayeredLBStrategy = Cast<ULayeredLBStrategy>(NetDriver->LoadBalanceStrategy);
if (LayeredLBStrategy == nullptr)
{
UE_LOG(LogSpatialDebugger, Warning, TEXT("SpatialDebugger enabled but unable to get LayeredLBStrategy."));
return;
}
if (const UGridBasedLBStrategy* GridBasedLBStrategy = Cast<UGridBasedLBStrategy>(LayeredLBStrategy->GetLBStrategyForVisualRendering()))
{
const UGridBasedLBStrategy::LBStrategyRegions LBStrategyRegions = GridBasedLBStrategy->GetLBStrategyRegions();
WorkerRegions.SetNum(LBStrategyRegions.Num());
for (int i = 0; i < LBStrategyRegions.Num(); i++)
{
const TPair<VirtualWorkerId, FBox2D>& LBStrategyRegion = LBStrategyRegions[i];
const PhysicalWorkerName* WorkerName = NetDriver->VirtualWorkerTranslator->GetPhysicalWorkerForVirtualWorker(LBStrategyRegion.Key);
FWorkerRegionInfo WorkerRegionInfo;
WorkerRegionInfo.Color = (WorkerName == nullptr) ? InvalidServerTintColor : SpatialGDK::GetColorForWorkerName(*WorkerName);
WorkerRegionInfo.Extents = LBStrategyRegion.Value;
WorkerRegions[i] = WorkerRegionInfo;
}
}
}
}
void ASpatialDebugger::CreateWorkerRegions()
{
UMaterial* WorkerRegionMaterial = LoadObject<UMaterial>(nullptr, *DEFAULT_WORKER_REGION_MATERIAL);
if (WorkerRegionMaterial == nullptr)
{
UE_LOG(LogSpatialDebugger, Error, TEXT("Worker regions were not rendered. Could not find default material: %s"),
*DEFAULT_WORKER_REGION_MATERIAL);
return;
}
// Create new actors for all new worker regions
FActorSpawnParameters SpawnParams;
SpawnParams.bNoFail = true;
SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
for (const FWorkerRegionInfo& WorkerRegionData : WorkerRegions)
{
AWorkerRegion* WorkerRegion = GetWorld()->SpawnActor<AWorkerRegion>(SpawnParams);
WorkerRegion->Init(WorkerRegionMaterial, WorkerRegionData.Color, WorkerRegionData.Extents, WorkerRegionVerticalScale);
WorkerRegion->SetActorEnableCollision(false);
}
}
void ASpatialDebugger::DestroyWorkerRegions()
{
TArray<AActor*> WorkerRegionsToRemove;
UGameplayStatics::GetAllActorsOfClass(this, AWorkerRegion::StaticClass(), WorkerRegionsToRemove);
for (AActor* WorkerRegion : WorkerRegionsToRemove)
{
WorkerRegion->Destroy();
}
}
void ASpatialDebugger::OnRep_SetWorkerRegions()
{
if (NetDriver != nullptr && !NetDriver->IsServer() && DrawDebugDelegateHandle.IsValid() && bShowWorkerRegions)
{
DestroyWorkerRegions();
CreateWorkerRegions();
}
}
void ASpatialDebugger::Destroyed()
{
if (NetDriver != nullptr && NetDriver->Receiver != nullptr)
{
if (OnEntityAddedHandle.IsValid())
{
NetDriver->Receiver->OnEntityAddedDelegate.Remove(OnEntityAddedHandle);
}
if (OnEntityRemovedHandle.IsValid())
{
NetDriver->Receiver->OnEntityRemovedDelegate.Remove(OnEntityRemovedHandle);
}
}
if (DrawDebugDelegateHandle.IsValid())
{
UDebugDrawService::Unregister(DrawDebugDelegateHandle);
DestroyWorkerRegions();
}
Super::Destroyed();
}
void ASpatialDebugger::LoadIcons()
{
check(NetDriver != nullptr && !NetDriver->IsServer());
UTexture2D* DefaultTexture = LoadObject<UTexture2D>(nullptr, TEXT("/Engine/EngineResources/DefaultTexture.DefaultTexture"));
const float IconWidth = 16.0f;
const float IconHeight = 16.0f;
Icons[ICON_AUTH] = UCanvas::MakeIcon(AuthTexture != nullptr ? AuthTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight);
Icons[ICON_AUTH_INTENT] = UCanvas::MakeIcon(AuthIntentTexture != nullptr ? AuthIntentTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight);
Icons[ICON_UNLOCKED] = UCanvas::MakeIcon(UnlockedTexture != nullptr ? UnlockedTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight);
Icons[ICON_LOCKED] = UCanvas::MakeIcon(LockedTexture != nullptr ? LockedTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight);
Icons[ICON_BOX] = UCanvas::MakeIcon(BoxTexture != nullptr ? BoxTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight);
}
void ASpatialDebugger::OnEntityAdded(const Worker_EntityId EntityId)
{
check(NetDriver != nullptr && !NetDriver->IsServer());
TWeakObjectPtr<AActor>* ExistingActor = EntityActorMapping.Find(EntityId);
if (ExistingActor != nullptr)
{
return;
}
if (AActor* Actor = Cast<AActor>(NetDriver->PackageMap->GetObjectFromEntityId(EntityId).Get()))
{
EntityActorMapping.Add(EntityId, Actor);
// Each client will only receive a PlayerController once.
if (Actor->IsA<APlayerController>())
{
LocalPlayerController = Cast<APlayerController>(Actor);
}
}
}
void ASpatialDebugger::OnEntityRemoved(const Worker_EntityId EntityId)
{
check(NetDriver != nullptr && !NetDriver->IsServer());
EntityActorMapping.Remove(EntityId);
}
void ASpatialDebugger::ActorAuthorityChanged(const Worker_AuthorityChangeOp& AuthOp) const
{
check(AuthOp.authority == WORKER_AUTHORITY_AUTHORITATIVE && AuthOp.component_id == SpatialConstants::AUTHORITY_INTENT_COMPONENT_ID);
if (NetDriver->VirtualWorkerTranslator == nullptr)
{
// Currently, there's nothing to display in the debugger other than load balancing information.
return;
}
VirtualWorkerId LocalVirtualWorkerId = NetDriver->VirtualWorkerTranslator->GetLocalVirtualWorkerId();
FColor LocalVirtualWorkerColor = SpatialGDK::GetColorForWorkerName(NetDriver->VirtualWorkerTranslator->GetLocalPhysicalWorkerName());
SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(AuthOp.entity_id);
if (DebuggingInfo == nullptr)
{
// Some entities won't have debug info, so create it now.
SpatialDebugging NewDebuggingInfo(LocalVirtualWorkerId, LocalVirtualWorkerColor, SpatialConstants::INVALID_VIRTUAL_WORKER_ID, InvalidServerTintColor, false);
NetDriver->Sender->SendAddComponents(AuthOp.entity_id, { NewDebuggingInfo.CreateSpatialDebuggingData() });
return;
}
DebuggingInfo->AuthoritativeVirtualWorkerId = LocalVirtualWorkerId;
DebuggingInfo->AuthoritativeColor = LocalVirtualWorkerColor;
FWorkerComponentUpdate DebuggingUpdate = DebuggingInfo->CreateSpatialDebuggingUpdate();
NetDriver->Connection->SendComponentUpdate(AuthOp.entity_id, &DebuggingUpdate);
}
void ASpatialDebugger::ActorAuthorityIntentChanged(Worker_EntityId EntityId, VirtualWorkerId NewIntentVirtualWorkerId) const
{
SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(EntityId);
check(DebuggingInfo != nullptr);
DebuggingInfo->IntentVirtualWorkerId = NewIntentVirtualWorkerId;
const PhysicalWorkerName* NewAuthoritativePhysicalWorkerName = NetDriver->VirtualWorkerTranslator->GetPhysicalWorkerForVirtualWorker(NewIntentVirtualWorkerId);
check(NewAuthoritativePhysicalWorkerName != nullptr);
DebuggingInfo->IntentColor = SpatialGDK::GetColorForWorkerName(*NewAuthoritativePhysicalWorkerName);
FWorkerComponentUpdate DebuggingUpdate = DebuggingInfo->CreateSpatialDebuggingUpdate();
NetDriver->Connection->SendComponentUpdate(EntityId, &DebuggingUpdate);
}
void ASpatialDebugger::DrawTag(UCanvas* Canvas, const FVector2D& ScreenLocation, const Worker_EntityId EntityId, const FString& ActorName)
{
SCOPE_CYCLE_COUNTER(STAT_DrawTag);
// TODO: Smarter positioning of elements so they're centered no matter how many are enabled https://improbableio.atlassian.net/browse/UNR-2360.
int32 HorizontalOffset = -32.0f;
check(NetDriver != nullptr && !NetDriver->IsServer());
if (!NetDriver->StaticComponentView->HasComponent(EntityId, SpatialConstants::SPATIAL_DEBUGGING_COMPONENT_ID))
{
return;
}
const SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(EntityId);
static const float BaseHorizontalOffset(16.0f);
if (!FApp::CanEverRender()) // DrawIcon can attempt to use the underlying texture resource even when using nullrhi
{
return;
}
if (bShowLock)
{
SCOPE_CYCLE_COUNTER(STAT_DrawIcons);
const bool bIsLocked = DebuggingInfo->IsLocked;
const EIcon LockIcon = bIsLocked ? ICON_LOCKED : ICON_UNLOCKED;
Canvas->SetDrawColor(FColor::White);
Canvas->DrawIcon(Icons[LockIcon], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f);
HorizontalOffset += BaseHorizontalOffset;
}
if (bShowAuth)
{
SCOPE_CYCLE_COUNTER(STAT_DrawIcons);
const FColor& ServerWorkerColor = DebuggingInfo->AuthoritativeColor;
Canvas->SetDrawColor(FColor::White);
Canvas->DrawIcon(Icons[ICON_AUTH], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f);
HorizontalOffset += BaseHorizontalOffset;
Canvas->SetDrawColor(ServerWorkerColor);
const float BoxScaleBasedOnNumberSize = 0.75f * GetNumberOfDigitsIn(DebuggingInfo->AuthoritativeVirtualWorkerId);
Canvas->DrawScaledIcon(Icons[ICON_BOX], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, FVector(BoxScaleBasedOnNumberSize, 1.f, 1.f));
Canvas->SetDrawColor(GetTextColorForBackgroundColor(ServerWorkerColor));
Canvas->DrawText(RenderFont, FString::FromInt(DebuggingInfo->AuthoritativeVirtualWorkerId), ScreenLocation.X + HorizontalOffset + 1, ScreenLocation.Y, 1.1f, 1.1f, FontRenderInfo);
HorizontalOffset += (BaseHorizontalOffset * BoxScaleBasedOnNumberSize);
}
if (bShowAuthIntent)
{
SCOPE_CYCLE_COUNTER(STAT_DrawIcons);
const FColor& VirtualWorkerColor = DebuggingInfo->IntentColor;
Canvas->SetDrawColor(FColor::White);
Canvas->DrawIcon(Icons[ICON_AUTH_INTENT], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f);
HorizontalOffset += 16.0f;
Canvas->SetDrawColor(VirtualWorkerColor);
const float BoxScaleBasedOnNumberSize = 0.75f * GetNumberOfDigitsIn(DebuggingInfo->IntentVirtualWorkerId);
Canvas->DrawScaledIcon(Icons[ICON_BOX], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, FVector(BoxScaleBasedOnNumberSize, 1.f, 1.f));
Canvas->SetDrawColor(GetTextColorForBackgroundColor(VirtualWorkerColor));
Canvas->DrawText(RenderFont, FString::FromInt(DebuggingInfo->IntentVirtualWorkerId), ScreenLocation.X + HorizontalOffset + 1, ScreenLocation.Y, 1.1f, 1.1f, FontRenderInfo);
HorizontalOffset += (BaseHorizontalOffset * BoxScaleBasedOnNumberSize);
}
FString Label;
if (bShowEntityId)
{
SCOPE_CYCLE_COUNTER(STAT_BuildText);
Label += FString::Printf(TEXT("%lld "), EntityId);
}
if (bShowActorName)
{
SCOPE_CYCLE_COUNTER(STAT_BuildText);
Label += FString::Printf(TEXT("(%s)"), *ActorName);
}
if (bShowEntityId || bShowActorName)
{
SCOPE_CYCLE_COUNTER(STAT_DrawText);
Canvas->SetDrawColor(FColor::Green);
Canvas->DrawText(RenderFont, Label, ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f, 1.0f, FontRenderInfo);
}
}
FColor ASpatialDebugger::GetTextColorForBackgroundColor(const FColor& BackgroundColor) const
{
return BackgroundColor.ReinterpretAsLinear().ComputeLuminance() > 0.5 ? FColor::Black : FColor::White;
}
// This will break once we have more than 10,000 workers, happily kicking that can down the road.
int32 ASpatialDebugger::GetNumberOfDigitsIn(int32 SomeNumber) const
{
SomeNumber = FMath::Abs(SomeNumber);
return (SomeNumber < 10 ? 1 : (SomeNumber < 100 ? 2 : (SomeNumber < 1000 ? 3 : 4)));
}
void ASpatialDebugger::DrawDebug(UCanvas* Canvas, APlayerController* /* Controller */) // Controller is invalid.
{
SCOPE_CYCLE_COUNTER(STAT_DrawDebug);
check(NetDriver != nullptr && !NetDriver->IsServer());
#if WITH_EDITOR
// Prevent one client's data rendering in another client's view in PIE when using UDebugDrawService. Lifted from EQSRenderingComponent.
if (Canvas && Canvas->SceneView && Canvas->SceneView->Family && Canvas->SceneView->Family->Scene && Canvas->SceneView->Family->Scene->GetWorld() != GetWorld())
{
return;
}
#endif
DrawDebugLocalPlayer(Canvas);
FVector PlayerLocation = FVector::ZeroVector;
if (LocalPawn.IsValid())
{
PlayerLocation = LocalPawn->GetActorLocation();
}
for (TPair<Worker_EntityId_Key, TWeakObjectPtr<AActor>>& EntityActorPair : EntityActorMapping)
{
const TWeakObjectPtr<AActor> Actor = EntityActorPair.Value;
const Worker_EntityId EntityId = EntityActorPair.Key;
if (Actor != nullptr)
{
FVector ActorLocation = Actor->GetActorLocation();
if (ActorLocation.IsZero())
{
continue;
}
if (FVector::Dist(PlayerLocation, ActorLocation) > MaxRange)
{
continue;
}
FVector2D ScreenLocation = FVector2D::ZeroVector;
if (LocalPlayerController.IsValid())
{
SCOPE_CYCLE_COUNTER(STAT_Projection);
UGameplayStatics::ProjectWorldToScreen(LocalPlayerController.Get(), ActorLocation + WorldSpaceActorTagOffset, ScreenLocation, false);
}
if (ScreenLocation.IsZero())
{
continue;
}
DrawTag(Canvas, ScreenLocation, EntityId, Actor->GetName());
}
}
}
void ASpatialDebugger::DrawDebugLocalPlayer(UCanvas* Canvas)
{
if (LocalPawn == nullptr || LocalPlayerController == nullptr || LocalPlayerState == nullptr)
{
return;
}
const TArray<TWeakObjectPtr<AActor>> LocalPlayerActors =
{
LocalPawn,
LocalPlayerController,
LocalPlayerState
};
FVector2D ScreenLocation(PlayerPanelStartX, PlayerPanelStartY);
for (int32 i = 0; i < LocalPlayerActors.Num(); ++i)
{
if (LocalPlayerActors[i].IsValid())
{
const Worker_EntityId EntityId = NetDriver->PackageMap->GetEntityIdFromObject(LocalPlayerActors[i].Get());
DrawTag(Canvas, ScreenLocation, EntityId, LocalPlayerActors[i]->GetName());
ScreenLocation.Y -= PLAYER_TAG_VERTICAL_OFFSET;
}
}
}
void ASpatialDebugger::SpatialToggleDebugger()
{
check(NetDriver != nullptr && !NetDriver->IsServer());
if (DrawDebugDelegateHandle.IsValid())
{
UDebugDrawService::Unregister(DrawDebugDelegateHandle);
DrawDebugDelegateHandle.Reset();
DestroyWorkerRegions();
}
else
{
DrawDebugDelegateHandle = UDebugDrawService::Register(TEXT("Game"), FDebugDrawDelegate::CreateUObject(this, &ASpatialDebugger::DrawDebug));
if (bShowWorkerRegions)
{
CreateWorkerRegions();
}
}
}
| 34.690114 | 181 | 0.775744 | Bowbee |
8198abf50adc2d6525c9e1e7d0e6dc61507d28e8 | 1,490 | cc | C++ | examples/UniformObjectPoolExample/main.cc | PerttuP/PPUtils | 97971d6e2b662bab9a4966b4c39ac59509c01359 | [
"MIT"
] | null | null | null | examples/UniformObjectPoolExample/main.cc | PerttuP/PPUtils | 97971d6e2b662bab9a4966b4c39ac59509c01359 | [
"MIT"
] | null | null | null | examples/UniformObjectPoolExample/main.cc | PerttuP/PPUtils | 97971d6e2b662bab9a4966b4c39ac59509c01359 | [
"MIT"
] | null | null | null | /*
* This is a simple example program to demonstrate the usage of the
* PPUtils::UniformObjectPool class template.
*
* Author: Perttu Paarlahti [email protected]
* Created: 29-June-2015
*/
#include <iostream>
#include <functional>
#include "../../source/PPUtils/uniformobjectpool.hh"
class VeryComplexClass
{
static int n;
public:
VeryComplexClass()
{
// Very expensive construction
std::cout << "Constructing a massively complex object" << std::endl;
++n;
}
void foo()
{
std::cout << "Expensive constructor was called " << n << " times\n";
}
};
int VeryComplexClass::n = 0;
int main()
{
// Create the object pool
PPUtils::UniformObjectPool<VeryComplexClass> pool;
std::cout << "Pool contains: " << pool.size() << " objects" << std::endl;
std::unique_ptr<VeryComplexClass> obj = pool.reserve();
std::cout << "Pool contains: " << pool.size() << " objects" << std::endl;
pool.release( std::move(obj) );
std::cout << "Pool contains: " << pool.size() << " objects" << std::endl;
obj = pool.reserve();
std::cout << "Pool contains: " << pool.size() << " objects" << std::endl;
obj->foo();
return 0;
}
/*
* Expected output:
*
* Pool contains 0 objects
* Constructing a massively complex object
* Pool contains 0 objects
* Pool contains 1 objects
* Pool contains 0 objects
* Expensive constructor was called 1 times
*
*/
| 22.575758 | 77 | 0.610738 | PerttuP |
819d2321ac2018d65bf373e8e9e768e8b162ca37 | 530 | cxx | C++ | rutil/ParseException.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 1 | 2019-04-15T14:10:58.000Z | 2019-04-15T14:10:58.000Z | rutil/ParseException.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | null | null | null | rutil/ParseException.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 2 | 2019-10-31T09:11:09.000Z | 2021-09-17T01:00:49.000Z | #include "rutil/ParseException.hxx"
namespace resip
{
ParseException::ParseException(const Data& msg,
const Data& context,
const Data& file,
const int line)
: resip::BaseException(msg, file, line),
mContext(context)
{}
ParseException::~ParseException() throw()
{}
const char*
ParseException::name() const
{
return "ParseException";
}
const Data&
ParseException::getContext() const
{
return mContext;
}
}
| 17.666667 | 54 | 0.575472 | dulton |
819e1cbc99fc76163756220c8033c8e8415940c7 | 2,183 | hpp | C++ | miopengemm/include/miopengemm/tinytwo.hpp | pruthvistony/MIOpenGEMM | 8f844e134d54244a6138504a4190486d8702e8fd | [
"MIT"
] | 52 | 2017-06-30T06:45:19.000Z | 2021-11-04T01:53:48.000Z | miopengemm/include/miopengemm/tinytwo.hpp | pruthvistony/MIOpenGEMM | 8f844e134d54244a6138504a4190486d8702e8fd | [
"MIT"
] | 31 | 2017-08-01T03:17:25.000Z | 2022-03-22T18:19:41.000Z | miopengemm/include/miopengemm/tinytwo.hpp | pruthvistony/MIOpenGEMM | 8f844e134d54244a6138504a4190486d8702e8fd | [
"MIT"
] | 23 | 2017-07-17T02:09:17.000Z | 2021-11-10T00:38:19.000Z | /*******************************************************************************
* Copyright (C) 2017 Advanced Micro Devices, Inc. All rights reserved.
*******************************************************************************/
#ifndef GUARD_MIOPENGEMM_DEGEMMAPIQQ_HPP
#define GUARD_MIOPENGEMM_DEGEMMAPIQQ_HPP
#include <memory>
#include <stdlib.h>
#include <string>
#include <vector>
#include <miopengemm/geometry.hpp>
#include <miopengemm/oclutil.hpp>
#include <miopengemm/solution.hpp>
#include <miopengemm/tinyone.hpp>
namespace MIOpenGEMM
{
namespace dev
{
class TinyTwo
{
private:
std::unique_ptr<TinyOne<double>> d_moa{nullptr};
std::unique_ptr<TinyOne<float>> f_moa{nullptr};
char active_type{'?'};
template <typename TFloat>
std::unique_ptr<TinyOne<TFloat>>& get_up_moa()
{
throw miog_error("unrecognised template parameter TFloat in TinyTwo get_up_moa");
}
template <typename TFloat>
void set_active_type()
{
throw miog_error("unrecognised template parameter TFloat in TinyTwo set_active_type");
}
public:
template <typename TFloat>
TinyTwo(Geometry gg_,
Offsets toff_,
const TFloat* a_,
const TFloat* b_,
const TFloat* c_,
owrite::Writer& mowri_,
const CLHint& xhint)
{
get_up_moa<TFloat>().reset(new TinyOne<TFloat>(gg_, toff_, a_, b_, c_, mowri_, xhint));
set_active_type<TFloat>();
}
TinyTwo(Geometry gg_, Offsets toff_, owrite::Writer& mowri_, const CLHint& xhint);
std::vector<std::vector<double>> benchgemm(const std::vector<HyPas>& hps, const Halt& hl);
Solution find2(const FindParams& find_params, const Constraints& constraints);
// template <typename TFloat>
// void accuracy_test(const HyPas& hp)
//{
// get_up_moa<TFloat>()->accuracy_test(hp);
//}
void accuracy_test(const HyPas& hp);
};
template <>
std::unique_ptr<TinyOne<float>>& TinyTwo::get_up_moa<float>();
template <>
std::unique_ptr<TinyOne<double>>& TinyTwo::get_up_moa<double>();
template <>
void TinyTwo::set_active_type<float>();
template <>
void TinyTwo::set_active_type<double>();
}
}
#endif
| 25.682353 | 92 | 0.637655 | pruthvistony |
81a0a0d1f022e000527c7301b1d4c1c2d42b9bd9 | 6,346 | cpp | C++ | src/Programs/Terminal/Terminal.cpp | Kaj9296/Electric_OS | 31e1d9318943e50e2bc095dc2ba32d4ce26e7e8b | [
"MIT"
] | 7 | 2022-02-20T16:34:48.000Z | 2022-02-26T06:14:51.000Z | src/Programs/Terminal/Terminal.cpp | Kaj9296/Electric_OS | 31e1d9318943e50e2bc095dc2ba32d4ce26e7e8b | [
"MIT"
] | null | null | null | src/Programs/Terminal/Terminal.cpp | Kaj9296/Electric_OS | 31e1d9318943e50e2bc095dc2ba32d4ce26e7e8b | [
"MIT"
] | 4 | 2022-02-20T16:25:44.000Z | 2022-03-20T07:49:25.000Z | #include "Terminal.h"
#include "STL/Graphics/Framebuffer.h"
#include "STL/String/String.h"
#include "STL/String/cstr.h"
#include "STL/System/System.h"
#include "Version.h"
#define NEWLINE_OFFSET RAISED_WIDTH * 3
namespace Terminal
{
uint64_t PrevTick = 0;
char Command[64];
STL::String Text;
STL::Point CursorPos = STL::Point(0, 0);
bool RedrawText = false;
bool DrawUnderline = false;
bool ClearCommand = false;
void Write(const char* cstr)
{
Text += cstr;
}
STL::PROR Procedure(STL::PROM Message, STL::PROI Input)
{
switch(Message)
{
case STL::PROM::INIT:
{
STL::PINFO* Info = (STL::PINFO*)Input;
Info->Type = STL::PROT::WINDOWED;
Info->Depth = 1;
Info->Left = 360;
Info->Top = 200;
Info->Width = 1000 + NEWLINE_OFFSET * 2;
Info->Height = 650;
Info->Title = "Terminal";
Text = "";
Command[0] = 0;
CursorPos = STL::Point(0, 0);
Write("\n\r");
Write("Welcome to the Terminal of ");
Write(OS_VERSION);
Write("!\n\r");
Write("Type \"help\" for a list of all available commands.\n\n\r");
Write(STL::System("sysfetch"));
Write("\n\r");
Write("> ");
RedrawText = true;
}
break;
case STL::PROM::TICK:
{
uint64_t CurrentTick = *(uint64_t*)Input;
if (PrevTick + 50 < CurrentTick)
{
DrawUnderline = !DrawUnderline;
PrevTick = CurrentTick;
return STL::PROR::DRAW;
}
}
break;
case STL::PROM::DRAW:
{
STL::Framebuffer* Buffer = (STL::Framebuffer*)Input;
//Clear command
for (uint32_t i = 0; i < STL::Length(Command) + 2; i++)
{
Buffer->PutChar(' ', STL::Point(CursorPos.X + 8 * i, CursorPos.Y), 1, STL::ARGB(255), STL::ARGB(0));
}
//Scroll up
if (CursorPos.Y + STL::LineAmount(Text.cstr()) * 16 + NEWLINE_OFFSET * 2 > Buffer->Height)
{
uint64_t Amount = (CursorPos.Y + STL::LineAmount(Text.cstr()) * 16 + NEWLINE_OFFSET * 2) - Buffer->Height;
for (uint32_t y = NEWLINE_OFFSET; y < Buffer->Height - NEWLINE_OFFSET - Amount; y++)
{
for (uint32_t x = NEWLINE_OFFSET; x < Buffer->Width - NEWLINE_OFFSET; x++)
{
*(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + y * Buffer->PixelsPerScanline * 4) =
*(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + (y + Amount) * Buffer->PixelsPerScanline * 4);
}
}
for (uint32_t y = Buffer->Height - NEWLINE_OFFSET - Amount; y < Buffer->Height; y++)
{
for (uint32_t x = NEWLINE_OFFSET; x < Buffer->Width - NEWLINE_OFFSET; x++)
{
*(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + y * Buffer->PixelsPerScanline * 4) = STL::ARGB(0);
}
}
CursorPos.Y -= Amount;
if (CursorPos.Y < 0)
{
CursorPos.Y = 0;
}
}
if (RedrawText)
{
//Print text
Buffer->Print(Text.cstr(), CursorPos, 1, STL::ARGB(255), STL::ARGB(0), NEWLINE_OFFSET);
Text = "";
Command[0] = 0;
RedrawText = false;
//Draw Edge
Buffer->DrawRect(STL::Point(0, 0), STL::Point(Buffer->Width, RAISED_WIDTH * 2), STL::ARGB(200));
Buffer->DrawRect(STL::Point(0, 0), STL::Point(RAISED_WIDTH * 2, Buffer->Height), STL::ARGB(200));
Buffer->DrawRect(STL::Point(Buffer->Width - RAISED_WIDTH * 2, 0), STL::Point(Buffer->Width, Buffer->Height), STL::ARGB(200));
Buffer->DrawRect(STL::Point(0, Buffer->Height - RAISED_WIDTH * 2), STL::Point(Buffer->Width, Buffer->Height), STL::ARGB(200));
Buffer->DrawSunkenRectEdge(STL::Point(RAISED_WIDTH * 2, RAISED_WIDTH * 2), STL::Point(Buffer->Width - RAISED_WIDTH * 2, Buffer->Height - RAISED_WIDTH * 2));
}
//Print command
STL::Point Temp = CursorPos;
Buffer->Print(Command, Temp, 1, STL::ARGB(255), STL::ARGB(0), NEWLINE_OFFSET);
//Print underline
if (DrawUnderline)
{
Buffer->PutChar('_', Temp, 1, STL::ARGB(255), STL::ARGB(0));
}
else
{
Buffer->PutChar(' ', Temp, 1, STL::ARGB(255), STL::ARGB(0));
}
}
break;
case STL::PROM::KEYPRESS:
{
uint8_t Key = *(uint8_t*)Input;
if (Key == ENTER)
{
Text += Command;
Text += "\n\r";
Text += STL::System(Command);
Text += "\n\r> ";
RedrawText = true;
}
else if (Key == BACKSPACE)
{
uint64_t CommandLength = STL::Length(Command);
if (CommandLength != 0)
{
Command[CommandLength - 1] = 0;
Command[CommandLength] = 0;
}
}
else
{
uint64_t CommandLength = STL::Length(Command);
if (CommandLength < 63)
{
Command[CommandLength] = Key;
Command[CommandLength + 1] = 0;
}
}
return STL::PROR::DRAW;
}
break;
case STL::PROM::CLEAR:
{
Text = "";
Command[0] = 0;
CursorPos = STL::Point(0, 0);
}
break;
case STL::PROM::KILL:
{
Text = "";
Command[0] = 0;
}
break;
default:
{
}
break;
}
return STL::PROR::SUCCESS;
}
} | 31.73 | 173 | 0.443744 | Kaj9296 |
81a158690d1e2643f6cc70d65bfeeea9bd7f520c | 2,223 | hpp | C++ | src/3rd party/components/ElPack/Code/Source/ElTreeDTPickEdit.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/3rd party/components/ElPack/Code/Source/ElTreeDTPickEdit.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/3rd party/components/ElPack/Code/Source/ElTreeDTPickEdit.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'ElTreeDTPickEdit.pas' rev: 6.00
#ifndef ElTreeDTPickEditHPP
#define ElTreeDTPickEditHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <ElDTPick.hpp> // Pascal unit
#include <ElHeader.hpp> // Pascal unit
#include <ElTree.hpp> // Pascal unit
#include <Types.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <Forms.hpp> // Pascal unit
#include <Controls.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Eltreedtpickedit
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TElTreeInplaceDateTimePicker;
class PASCALIMPLEMENTATION TElTreeInplaceDateTimePicker : public Eltree::TElTreeInplaceEditor
{
typedef Eltree::TElTreeInplaceEditor inherited;
private:
Classes::TWndMethod SaveWndProc;
void __fastcall EditorWndProc(Messages::TMessage &Message);
protected:
Eldtpick::TElDateTimePicker* FEditor;
virtual void __fastcall DoStartOperation(void);
virtual void __fastcall DoStopOperation(bool Accepted);
virtual bool __fastcall GetVisible(void);
virtual void __fastcall TriggerAfterOperation(bool &Accepted, bool &DefaultConversion);
virtual void __fastcall TriggerBeforeOperation(bool &DefaultConversion);
virtual void __fastcall SetEditorParent(void);
public:
__fastcall virtual TElTreeInplaceDateTimePicker(Classes::TComponent* AOwner);
__fastcall virtual ~TElTreeInplaceDateTimePicker(void);
__property Eldtpick::TElDateTimePicker* Editor = {read=FEditor};
};
//-- var, const, procedure ---------------------------------------------------
} /* namespace Eltreedtpickedit */
using namespace Eltreedtpickedit;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // ElTreeDTPickEdit
| 33.681818 | 94 | 0.695906 | OLR-xray |
81a3842fb532d19187fa8cdb45c554b79470b22d | 8,541 | hpp | C++ | master/core/third/boost/geometry/algorithms/disjoint.hpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | master/core/third/boost/geometry/algorithms/disjoint.hpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 197 | 2017-07-06T16:53:59.000Z | 2019-05-31T17:57:51.000Z | master/core/third/boost/geometry/algorithms/disjoint.hpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP
#include <cstddef>
#include <deque>
#include <boost/mpl/if.hpp>
#include <boost/range.hpp>
#include <boost/static_assert.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/reverse_dispatch.hpp>
#include <boost/geometry/algorithms/detail/disjoint.hpp>
#include <boost/geometry/algorithms/detail/for_each_range.hpp>
#include <boost/geometry/algorithms/detail/point_on_border.hpp>
#include <boost/geometry/algorithms/detail/overlay/get_turns.hpp>
#include <boost/geometry/algorithms/within.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>
#include <boost/geometry/util/math.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace disjoint
{
template<typename Geometry>
struct check_each_ring_for_within
{
bool has_within;
Geometry const& m_geometry;
inline check_each_ring_for_within(Geometry const& g)
: has_within(false)
, m_geometry(g)
{}
template <typename Range>
inline void apply(Range const& range)
{
typename geometry::point_type<Range>::type p;
geometry::point_on_border(p, range);
if (geometry::within(p, m_geometry))
{
has_within = true;
}
}
};
template <typename FirstGeometry, typename SecondGeometry>
inline bool rings_containing(FirstGeometry const& geometry1,
SecondGeometry const& geometry2)
{
check_each_ring_for_within<FirstGeometry> checker(geometry1);
geometry::detail::for_each_range(geometry2, checker);
return checker.has_within;
}
struct assign_disjoint_policy
{
// We want to include all points:
static bool const include_no_turn = true;
static bool const include_degenerate = true;
static bool const include_opposite = true;
// We don't assign extra info:
template
<
typename Info,
typename Point1,
typename Point2,
typename IntersectionInfo,
typename DirInfo
>
static inline void apply(Info& , Point1 const& , Point2 const&,
IntersectionInfo const&, DirInfo const&)
{}
};
template <typename Geometry1, typename Geometry2>
struct disjoint_linear
{
static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)
{
typedef typename geometry::point_type<Geometry1>::type point_type;
typedef overlay::turn_info<point_type> turn_info;
std::deque<turn_info> turns;
// Specify two policies:
// 1) Stop at any intersection
// 2) In assignment, include also degenerate points (which are normally skipped)
disjoint_interrupt_policy policy;
geometry::get_turns
<
false, false,
assign_disjoint_policy
>(geometry1, geometry2, turns, policy);
if (policy.has_intersections)
{
return false;
}
return true;
}
};
template <typename Segment1, typename Segment2>
struct disjoint_segment
{
static inline bool apply(Segment1 const& segment1, Segment2 const& segment2)
{
typedef typename point_type<Segment1>::type point_type;
segment_intersection_points<point_type> is
= strategy::intersection::relate_cartesian_segments
<
policies::relate::segments_intersection_points
<
Segment1,
Segment2,
segment_intersection_points<point_type>
>
>::apply(segment1, segment2);
return is.count == 0;
}
};
template <typename Geometry1, typename Geometry2>
struct general_areal
{
static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)
{
if (! disjoint_linear<Geometry1, Geometry2>::apply(geometry1, geometry2))
{
return false;
}
// If there is no intersection of segments, they might located
// inside each other
if (rings_containing(geometry1, geometry2)
|| rings_containing(geometry2, geometry1))
{
return false;
}
return true;
}
};
}} // namespace detail::disjoint
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
template
<
typename GeometryTag1, typename GeometryTag2,
typename Geometry1, typename Geometry2,
std::size_t DimensionCount
>
struct disjoint
: detail::disjoint::general_areal<Geometry1, Geometry2>
{};
template <typename Point1, typename Point2, std::size_t DimensionCount>
struct disjoint<point_tag, point_tag, Point1, Point2, DimensionCount>
: detail::disjoint::point_point<Point1, Point2, 0, DimensionCount>
{};
template <typename Box1, typename Box2, std::size_t DimensionCount>
struct disjoint<box_tag, box_tag, Box1, Box2, DimensionCount>
: detail::disjoint::box_box<Box1, Box2, 0, DimensionCount>
{};
template <typename Point, typename Box, std::size_t DimensionCount>
struct disjoint<point_tag, box_tag, Point, Box, DimensionCount>
: detail::disjoint::point_box<Point, Box, 0, DimensionCount>
{};
template <typename Linestring1, typename Linestring2>
struct disjoint<linestring_tag, linestring_tag, Linestring1, Linestring2, 2>
: detail::disjoint::disjoint_linear<Linestring1, Linestring2>
{};
template <typename Linestring1, typename Linestring2>
struct disjoint<segment_tag, segment_tag, Linestring1, Linestring2, 2>
: detail::disjoint::disjoint_segment<Linestring1, Linestring2>
{};
template <typename Linestring, typename Segment>
struct disjoint<linestring_tag, segment_tag, Linestring, Segment, 2>
: detail::disjoint::disjoint_linear<Linestring, Segment>
{};
template
<
typename GeometryTag1, typename GeometryTag2,
typename Geometry1, typename Geometry2,
std::size_t DimensionCount
>
struct disjoint_reversed
{
static inline bool apply(Geometry1 const& g1, Geometry2 const& g2)
{
return disjoint
<
GeometryTag2, GeometryTag1,
Geometry2, Geometry1,
DimensionCount
>::apply(g2, g1);
}
};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
/*!
\brief \brief_check2{are disjoint}
\ingroup disjoint
\tparam Geometry1 \tparam_geometry
\tparam Geometry2 \tparam_geometry
\param geometry1 \param_geometry
\param geometry2 \param_geometry
\return \return_check2{are disjoint}
\qbk{[include reference/algorithms/disjoint.qbk]}
*/
template <typename Geometry1, typename Geometry2>
inline bool disjoint(Geometry1 const& geometry1,
Geometry2 const& geometry2)
{
concept::check_concepts_and_equal_dimensions
<
Geometry1 const,
Geometry2 const
>();
return boost::mpl::if_c
<
reverse_dispatch<Geometry1, Geometry2>::type::value,
dispatch::disjoint_reversed
<
typename tag<Geometry1>::type,
typename tag<Geometry2>::type,
Geometry1,
Geometry2,
dimension<Geometry1>::type::value
>,
dispatch::disjoint
<
typename tag<Geometry1>::type,
typename tag<Geometry2>::type,
Geometry1,
Geometry2,
dimension<Geometry1>::type::value
>
>::type::apply(geometry1, geometry2);
}
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP
| 28.281457 | 89 | 0.65449 | importlib |
81a46bb917d47aca2ad6d58fe1943d5095915be2 | 12,782 | cpp | C++ | src/test/simple_kv/checker.cpp | imzhenyu/rDSN.dist.service | 741cdfcaabd7312e64d10f3f194de7790b578d01 | [
"MIT"
] | 2 | 2016-12-08T05:56:22.000Z | 2021-12-08T18:41:47.000Z | src/test/simple_kv/checker.cpp | imzhenyu/rDSN.dist.service | 741cdfcaabd7312e64d10f3f194de7790b578d01 | [
"MIT"
] | 15 | 2016-08-09T23:37:11.000Z | 2018-09-21T09:45:28.000Z | src/test/simple_kv/checker.cpp | imzhenyu/rDSN.dist.service | 741cdfcaabd7312e64d10f3f194de7790b578d01 | [
"MIT"
] | 4 | 2016-11-18T08:25:33.000Z | 2021-12-08T18:41:49.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* Replication testing framework.
*
* Revision history:
* Nov., 2015, @qinzuoyan (Zuoyan Qin), first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include "checker.h"
# include "case.h"
# include "dsn/utility/factory_store.h"
# include "../../replica_server/replication_lib/replica.h"
# include "../../replica_server/replication_lib/replica_stub.h"
# include "../../replica_server/replication_lib/mutation_log.h"
# include "../../meta_server/meta_server_lib/meta_service.h"
# include "../../meta_server/meta_server_lib/meta_server_failure_detector.h"
# include "../../meta_server/meta_server_lib/server_state.h"
# include "../../meta_server/meta_server_lib/server_load_balancer.h"
# include "../../common/replication_ds.h"
# include <sstream>
# include <boost/lexical_cast.hpp>
# include <dsn/tool_api.h>
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "simple_kv.checker"
namespace dsn { namespace replication { namespace test {
class checker_load_balancer: public simple_load_balancer
{
public:
static bool s_disable_balancer;
public:
checker_load_balancer(meta_service* svc): simple_load_balancer(svc) {}
pc_status cure(const meta_view &view, const dsn::gpid& gpid, configuration_proposal_action &action) override
{
const partition_configuration& pc = *get_config(*view.apps, gpid);
action.type = config_type::CT_INVALID;
if (s_disable_balancer)
return pc_status::healthy;
pc_status result;
if (pc.primary.is_invalid())
{
if (pc.secondaries.size() > 0)
{
action.node = pc.secondaries[0];
for (unsigned int i=1; i<pc.secondaries.size(); ++i)
if (pc.secondaries[i] < action.node)
action.node = pc.secondaries[i];
action.type = config_type::CT_UPGRADE_TO_PRIMARY;
result = pc_status::ill;
}
else if (pc.last_drops.size() == 0)
{
std::vector<rpc_address> sort_result;
sort_alive_nodes(*view.nodes, primary_comparator(*view.nodes), sort_result);
action.node = sort_result[0];
action.type = config_type::CT_ASSIGN_PRIMARY;
result = pc_status::ill;
}
// DDD
else
{
action.node = *pc.last_drops.rbegin();
action.type = config_type::CT_ASSIGN_PRIMARY;
derror("%d.%d enters DDD state, we are waiting for its last primary node %s to come back ...",
pc.pid.get_app_id(),
pc.pid.get_partition_index(),
action.node.to_string()
);
result = pc_status::dead;
}
action.target = action.node;
}
else if (static_cast<int>(pc.secondaries.size()) + 1 < pc.max_replica_count)
{
std::vector<rpc_address> sort_result;
sort_alive_nodes(*view.nodes, partition_comparator(*view.nodes), sort_result);
for (auto& node: sort_result) {
if (!is_member(pc, node)) {
action.node = node;
break;
}
}
action.target = pc.primary;
action.type = config_type::CT_ADD_SECONDARY;
result = pc_status::ill;
}
else
{
result = pc_status::healthy;
}
return result;
}
};
bool test_checker::s_inited = false;
bool checker_load_balancer::s_disable_balancer = false;
test_checker::test_checker()
{
}
void test_checker::control_balancer(bool disable_it)
{
checker_load_balancer::s_disable_balancer = disable_it;
if (disable_it && meta_leader()) {
server_state* ss = meta_leader()->_service->_state.get();
for (auto& kv: ss->_exist_apps) {
std::shared_ptr<app_state>& app = kv.second;
app->helpers->clear_proposals();
}
}
}
bool test_checker::init(const char* name, dsn_app_info* info, int count)
{
if (s_inited)
return false;
_apps.resize(count);
for (int i = 0; i < count; i++)
{
_apps[i] = info[i];
}
utils::factory_store<replication::server_load_balancer>::register_factory(
"checker_load_balancer",
replication::server_load_balancer::create<checker_load_balancer>,
PROVIDER_TYPE_MAIN);
for (auto& app : _apps)
{
if (0 == strcmp(app.type, "meta"))
{
meta_service_app* meta_app = (meta_service_app*)app.app.app_context_ptr;
meta_app->_service->_state->set_config_change_subscriber_for_test(
std::bind(&test_checker::on_config_change, this, std::placeholders::_1));
meta_app->_service->_meta_opts.server_load_balancer_type = "checker_load_balancer";
_meta_servers.push_back(meta_app);
}
else if (0 == strcmp(app.type, "replica"))
{
replication_service_app* replica_app = (replication_service_app*)app.app.app_context_ptr;
replica_app->_stub->set_replica_state_subscriber_for_test(
std::bind(&test_checker::on_replica_state_change, this,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),
false);
_replica_servers.push_back(replica_app);
}
}
for (int i = 0; i < count; i++)
{
auto& node = _apps[i];
int id = node.app_id;
std::string name = node.name;
rpc_address paddr(node.primary_address);
int port = paddr.port();
_node_to_address[name] = paddr;
ddebug("=== node_to_address[%s]=%s", name.c_str(), paddr.to_string());
_address_to_node[port] = name;
ddebug("=== address_to_node[%u]=%s", port, name.c_str());
if (id != port)
{
_address_to_node[id] = name;
ddebug("=== address_to_node[%u]=%s", id, name.c_str());
}
}
s_inited = true;
if (!test_case::instance().init(g_case_input))
{
std::cerr << "init test_case failed" << std::endl;
s_inited = false;
return false;
}
return true;
}
void test_checker::exit()
{
if (!s_inited) return;
for (meta_service_app* app : _meta_servers)
{
app->_service->_started = false;
}
if (test_case::s_close_replica_stub_on_exit)
{
dsn::tools::tool_app* app = dsn::tools::get_current_tool();
app->stop_all_apps(true);
}
}
void test_checker::check()
{
test_case::instance().on_check();
if (g_done) return;
// 'config_change' and 'replica_state_change' are detected in two ways:
// - each time this check() is called, checking will be applied
// - register subscribers on meta_server and replica_server to be notified
parti_config cur_config;
if (get_current_config(cur_config) && cur_config != _last_config)
{
test_case::instance().on_config_change(_last_config, cur_config);
_last_config = cur_config;
}
state_snapshot cur_states;
get_current_states(cur_states);
if (cur_states != _last_states)
{
test_case::instance().on_state_change(_last_states, cur_states);
_last_states = cur_states;
}
}
void test_checker::on_replica_state_change(::dsn::rpc_address from, const replica_configuration& new_config, bool is_closing)
{
state_snapshot cur_states;
get_current_states(cur_states);
if (cur_states != _last_states)
{
test_case::instance().on_state_change(_last_states, cur_states);
_last_states = cur_states;
}
}
void test_checker::on_config_change(const app_mapper& new_config)
{
const partition_configuration* pc = get_config(new_config, g_default_gpid);
dassert(pc != nullptr, "drop table is not allowed in test");
parti_config cur_config;
cur_config.convert_from(*pc);
if (cur_config != _last_config)
{
test_case::instance().on_config_change(_last_config, cur_config);
_last_config = cur_config;
}
}
void test_checker::get_current_states(state_snapshot& states)
{
states.state_map.clear();
for (auto& app : _replica_servers)
{
if (!app->is_started())
continue;
for (auto& kv : app->_stub->_replicas)
{
replica_ptr r = kv.second;
dassert(kv.first == r->get_gpid(), "");
replica_id id(r->get_gpid(), app->name());
replica_state& rs = states.state_map[id];
rs.id = id;
rs.status = r->status();
rs.ballot = r->get_ballot();
rs.last_committed_decree = r->last_committed_decree();
rs.last_durable_decree = r->last_durable_decree();
}
}
}
bool test_checker::get_current_config(parti_config& config)
{
meta_service_app* meta = meta_leader();
if (meta == nullptr)
return false;
partition_configuration c;
//we should never try to acquire lock when we are in checker. Because we are the only
//thread that is running.
//The app and emulator have lots in common with the OS's userspace and kernel space.
//In normal case, "apps" runs in "userspace". You can "trap into kernel(i.e. the emulator)" by the rDSN's
//"enqueue,dequeue and lock..."
//meta->_service->_state->query_configuration_by_gpid(g_default_gpid, c);
const meta_view view = meta->_service->_state->get_meta_view();
const partition_configuration* pc = get_config(*(view.apps), g_default_gpid);
c = *pc;
config.convert_from(c);
return true;
}
meta_service_app* test_checker::meta_leader()
{
for (auto& meta : _meta_servers)
{
if (!meta->is_started())
return nullptr;
if (meta->_service->_failure_detector->is_primary())
return meta;
}
return nullptr;
}
bool test_checker::is_server_normal()
{
auto meta = meta_leader();
if (!meta) return false;
return check_replica_state(1, 2, 0);
}
bool test_checker::check_replica_state(int primary_count, int secondary_count, int inactive_count)
{
int p = 0;
int s = 0;
int i = 0;
for (auto& rs : _replica_servers)
{
if (!rs->is_started())
return false;
for (auto& replica : rs->_stub->_replicas)
{
auto status = replica.second->status();
if (status == partition_status::PS_PRIMARY)
p++;
else if (status == partition_status::PS_SECONDARY)
s++;
else if (status == partition_status::PS_INACTIVE)
i++;
}
}
return p == primary_count && s == secondary_count && i == inactive_count;
}
std::string test_checker::address_to_node_name(rpc_address addr)
{
auto find = _address_to_node.find(addr.port());
if (find != _address_to_node.end())
return find->second;
return "node@" + boost::lexical_cast<std::string>(addr.port());
}
rpc_address test_checker::node_name_to_address(const std::string& name)
{
auto find = _node_to_address.find(name);
if (find != _node_to_address.end())
return find->second;
return rpc_address();
}
void install_checkers()
{
dsn_register_app_checker(
"simple_kv.checker",
::dsn::tools::checker::create<wrap_checker>,
::dsn::tools::checker::apply
);
}
}}}
| 31.955 | 125 | 0.622751 | imzhenyu |
81a957f1b1737e8ad6faa7205757a2dab551470d | 2,109 | cpp | C++ | test/src/fetch_request_test.cpp | perchits/libkafka-asio | cbdced006d49a4498955a222915c6514b4ac57a7 | [
"MIT"
] | 77 | 2015-04-07T08:14:14.000Z | 2022-02-14T01:07:05.000Z | test/src/fetch_request_test.cpp | perchits/libkafka-asio | cbdced006d49a4498955a222915c6514b4ac57a7 | [
"MIT"
] | 28 | 2015-04-07T08:57:41.000Z | 2020-04-19T21:25:22.000Z | test/src/fetch_request_test.cpp | perchits/libkafka-asio | cbdced006d49a4498955a222915c6514b4ac57a7 | [
"MIT"
] | 48 | 2015-04-15T05:34:51.000Z | 2022-03-17T11:50:20.000Z | //
// fetch_request_test.cpp
// ----------------------
//
// Copyright (c) 2015 Daniel Joos
//
// Distributed under MIT license. (See file LICENSE)
//
#include <gtest/gtest.h>
#include <libkafka_asio/libkafka_asio.h>
class FetchRequestTest :
public ::testing::Test
{
protected:
virtual void SetUp()
{
ASSERT_EQ(0, request.topics().size());
}
libkafka_asio::FetchRequest request;
};
TEST_F(FetchRequestTest, FetchTopic_New)
{
request.FetchTopic("mytopic", 1, 2);
ASSERT_EQ(1, request.topics().size());
ASSERT_EQ(1, request.topics()[0].partitions.size());
ASSERT_STREQ("mytopic", request.topics()[0].topic_name.c_str());
ASSERT_EQ(1, request.topics()[0].partitions[0].partition);
ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset);
ASSERT_EQ(libkafka_asio::constants::kDefaultFetchMaxBytes,
request.topics()[0].partitions[0].max_bytes);
}
TEST_F(FetchRequestTest, FetchTopic_Override)
{
request.FetchTopic("mytopic", 1, 2);
ASSERT_EQ(1, request.topics().size());
ASSERT_EQ(1, request.topics()[0].partitions.size());
ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset);
request.FetchTopic("mytopic", 1, 4);
ASSERT_EQ(1, request.topics().size());
ASSERT_EQ(1, request.topics()[0].partitions.size());
ASSERT_EQ(4, request.topics()[0].partitions[0].fetch_offset);
}
TEST_F(FetchRequestTest, FetchTopic_MultiplePartitions)
{
request.FetchTopic("mytopic", 0, 2);
request.FetchTopic("mytopic", 1, 4);
ASSERT_EQ(1, request.topics().size());
ASSERT_EQ(2, request.topics()[0].partitions.size());
ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset);
ASSERT_EQ(4, request.topics()[0].partitions[1].fetch_offset);
}
TEST_F(FetchRequestTest, FetchTopic_MultipleTopics)
{
request.FetchTopic("foo", 0, 2);
request.FetchTopic("bar", 1, 4);
ASSERT_EQ(2, request.topics().size());
ASSERT_EQ(1, request.topics()[0].partitions.size());
ASSERT_EQ(1, request.topics()[1].partitions.size());
ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset);
ASSERT_EQ(4, request.topics()[1].partitions[0].fetch_offset);
}
| 30.565217 | 66 | 0.700806 | perchits |
81ac79b2f71f976e02888fc20fceb936a204eb47 | 6,368 | cpp | C++ | src/graphics/Color.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 675 | 2019-05-28T19:00:55.000Z | 2022-03-31T16:44:28.000Z | src/graphics/Color.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 13 | 2020-03-29T06:46:32.000Z | 2022-01-29T03:19:30.000Z | src/graphics/Color.cpp | bigplayszn/nCine | 43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454 | [
"MIT"
] | 53 | 2019-06-02T03:04:10.000Z | 2022-03-11T06:17:50.000Z | #include "Color.h"
#include "Colorf.h"
#include <nctl/algorithms.h>
namespace ncine {
///////////////////////////////////////////////////////////
// STATIC DEFINITIONS
///////////////////////////////////////////////////////////
const Color Color::Black(0, 0, 0, 255);
const Color Color::White(255, 255, 255, 255);
const Color Color::Red(255, 0, 0, 255);
const Color Color::Green(0, 255, 0, 255);
const Color Color::Blue(0, 0, 255, 255);
const Color Color::Yellow(255, 255, 0, 255);
const Color Color::Magenta(255, 0, 255, 255);
const Color Color::Cyan(0, 255, 255, 255);
///////////////////////////////////////////////////////////
// CONSTRUCTORS and DESTRUCTOR
///////////////////////////////////////////////////////////
Color::Color()
: Color(255, 255, 255, 255)
{
}
Color::Color(unsigned int red, unsigned int green, unsigned int blue)
: Color(red, green, blue, 255)
{
}
Color::Color(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha)
: channels_(nctl::StaticArrayMode::EXTEND_SIZE)
{
set(red, green, blue, alpha);
}
Color::Color(unsigned int hex)
: channels_(nctl::StaticArrayMode::EXTEND_SIZE)
{
setAlpha(255);
// The following method might set the alpha channel
set(hex);
}
Color::Color(const unsigned int channels[NumChannels])
: channels_(nctl::StaticArrayMode::EXTEND_SIZE)
{
setVec(channels);
}
Color::Color(const Colorf &color)
: channels_(nctl::StaticArrayMode::EXTEND_SIZE)
{
channels_[0] = static_cast<unsigned char>(color.r() * 255);
channels_[1] = static_cast<unsigned char>(color.g() * 255);
channels_[2] = static_cast<unsigned char>(color.b() * 255);
channels_[3] = static_cast<unsigned char>(color.a() * 255);
}
///////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
///////////////////////////////////////////////////////////
unsigned int Color::rgba() const
{
return (channels_[0] << 24) + (channels_[1] << 16) + (channels_[2] << 8) + channels_[3];
}
unsigned int Color::argb() const
{
return (channels_[3] << 24) + (channels_[0] << 16) + (channels_[1] << 8) + channels_[2];
}
unsigned int Color::abgr() const
{
return (channels_[3] << 24) + (channels_[2] << 16) + (channels_[1] << 8) + channels_[0];
}
unsigned int Color::bgra() const
{
return (channels_[2] << 24) + (channels_[1] << 16) + (channels_[0] << 8) + channels_[3];
}
void Color::set(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha)
{
channels_[0] = static_cast<unsigned char>(red);
channels_[1] = static_cast<unsigned char>(green);
channels_[2] = static_cast<unsigned char>(blue);
channels_[3] = static_cast<unsigned char>(alpha);
}
void Color::set(unsigned int red, unsigned int green, unsigned int blue)
{
channels_[0] = static_cast<unsigned char>(red);
channels_[1] = static_cast<unsigned char>(green);
channels_[2] = static_cast<unsigned char>(blue);
}
void Color::set(unsigned int hex)
{
channels_[0] = static_cast<unsigned char>((hex & 0xFF0000) >> 16);
channels_[1] = static_cast<unsigned char>((hex & 0xFF00) >> 8);
channels_[2] = static_cast<unsigned char>(hex & 0xFF);
if (hex > 0xFFFFFF)
channels_[3] = static_cast<unsigned char>((hex & 0xFF000000) >> 24);
}
void Color::setVec(const unsigned int channels[NumChannels])
{
set(channels[0], channels[1], channels[2], channels[3]);
}
void Color::setAlpha(unsigned int alpha)
{
channels_[3] = static_cast<unsigned char>(alpha);
}
Color &Color::operator=(const Colorf &color)
{
channels_[0] = static_cast<unsigned char>(color.r() * 255.0f);
channels_[1] = static_cast<unsigned char>(color.g() * 255.0f);
channels_[2] = static_cast<unsigned char>(color.b() * 255.0f);
channels_[3] = static_cast<unsigned char>(color.a() * 255.0f);
return *this;
}
bool Color::operator==(const Color &color) const
{
return (r() == color.r() && g() == color.g() &&
b() == color.b() && a() == color.a());
}
Color &Color::operator+=(const Color &color)
{
for (unsigned int i = 0; i < NumChannels; i++)
{
unsigned int channelValue = channels_[i] + color.channels_[i];
channelValue = nctl::clamp(channelValue, 0U, 255U);
channels_[i] = static_cast<unsigned char>(channelValue);
}
return *this;
}
Color &Color::operator-=(const Color &color)
{
for (unsigned int i = 0; i < NumChannels; i++)
{
unsigned int channelValue = channels_[i] - color.channels_[i];
channelValue = nctl::clamp(channelValue, 0U, 255U);
channels_[i] = static_cast<unsigned char>(channelValue);
}
return *this;
}
Color &Color::operator*=(const Color &color)
{
for (unsigned int i = 0; i < NumChannels; i++)
{
float channelValue = channels_[i] * (color.channels_[i] / 255.0f);
channelValue = nctl::clamp(channelValue, 0.0f, 255.0f);
channels_[i] = static_cast<unsigned char>(channelValue);
}
return *this;
}
Color &Color::operator*=(float scalar)
{
for (unsigned int i = 0; i < NumChannels; i++)
{
float channelValue = channels_[i] * scalar;
channelValue = nctl::clamp(channelValue, 0.0f, 255.0f);
channels_[i] = static_cast<unsigned char>(channelValue);
}
return *this;
}
Color Color::operator+(const Color &color) const
{
Color result;
for (unsigned int i = 0; i < NumChannels; i++)
{
unsigned int channelValue = channels_[i] + color.channels_[i];
channelValue = nctl::clamp(channelValue, 0U, 255U);
result.channels_[i] = static_cast<unsigned char>(channelValue);
}
return result;
}
Color Color::operator-(const Color &color) const
{
Color result;
for (unsigned int i = 0; i < NumChannels; i++)
{
unsigned int channelValue = channels_[i] - color.channels_[i];
channelValue = nctl::clamp(channelValue, 0U, 255U);
result.channels_[i] = static_cast<unsigned char>(channelValue);
}
return result;
}
Color Color::operator*(const Color &color) const
{
Color result;
for (unsigned int i = 0; i < NumChannels; i++)
{
float channelValue = channels_[i] * (color.channels_[i] / 255.0f);
channelValue = nctl::clamp(channelValue, 0.0f, 255.0f);
result.channels_[i] = static_cast<unsigned char>(channelValue);
}
return result;
}
Color Color::operator*(float scalar) const
{
Color result;
for (unsigned int i = 0; i < NumChannels; i++)
{
float channelValue = channels_[i] * scalar;
channelValue = nctl::clamp(channelValue, 0.0f, 255.0f);
result.channels_[i] = static_cast<unsigned char>(channelValue);
}
return result;
}
}
| 26.205761 | 92 | 0.642588 | bigplayszn |
81ba9781070eba3e35c32695ddcc6d305e99e3a4 | 2,402 | hpp | C++ | include/UnityEngine/Animations/AnimationHumanStream.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/UnityEngine/Animations/AnimationHumanStream.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/UnityEngine/Animations/AnimationHumanStream.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
// Completed includes
// Type namespace: UnityEngine.Animations
namespace UnityEngine::Animations {
// Forward declaring type: AnimationHumanStream
struct AnimationHumanStream;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::Animations::AnimationHumanStream, "UnityEngine.Animations", "AnimationHumanStream");
// Type namespace: UnityEngine.Animations
namespace UnityEngine::Animations {
// Size: 0x8
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: UnityEngine.Animations.AnimationHumanStream
// [TokenAttribute] Offset: FFFFFFFF
// [MovedFromAttribute] Offset: 5A6440
// [NativeHeaderAttribute] Offset: 5A6440
// [NativeHeaderAttribute] Offset: 5A6440
// [RequiredByNativeCodeAttribute] Offset: 5A6440
struct AnimationHumanStream/*, public ::System::ValueType*/ {
public:
public:
// private System.IntPtr stream
// Size: 0x8
// Offset: 0x0
::System::IntPtr stream;
// Field size check
static_assert(sizeof(::System::IntPtr) == 0x8);
public:
// Creating value type constructor for type: AnimationHumanStream
constexpr AnimationHumanStream(::System::IntPtr stream_ = {}) noexcept : stream{stream_} {}
// Creating interface conversion operator: operator ::System::ValueType
operator ::System::ValueType() noexcept {
return *reinterpret_cast<::System::ValueType*>(this);
}
// Creating conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept {
return stream;
}
// Get instance field reference: private System.IntPtr stream
::System::IntPtr& dyn_stream();
}; // UnityEngine.Animations.AnimationHumanStream
#pragma pack(pop)
static check_size<sizeof(AnimationHumanStream), 0 + sizeof(::System::IntPtr)> __UnityEngine_Animations_AnimationHumanStreamSizeCheck;
static_assert(sizeof(AnimationHumanStream) == 0x8);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 41.413793 | 135 | 0.722315 | RedBrumbler |
81bad7f3ace1ba946ccf02caa28e9a3f7265a159 | 4,709 | cpp | C++ | inference_backend/image_inference/async_with_va_api/va_api_wrapper/vaapi_context.cpp | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 125 | 2020-09-18T10:50:27.000Z | 2022-02-10T06:20:59.000Z | inference_backend/image_inference/async_with_va_api/va_api_wrapper/vaapi_context.cpp | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 155 | 2020-09-10T23:32:29.000Z | 2022-02-05T07:10:26.000Z | inference_backend/image_inference/async_with_va_api/va_api_wrapper/vaapi_context.cpp | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 41 | 2020-09-15T08:49:17.000Z | 2022-01-24T10:39:36.000Z | /*******************************************************************************
* Copyright (C) 2019-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#include "vaapi_context.h"
#include "inference_backend/logger.h"
#include "utils.h"
#include <cassert>
#include <vector>
#include <fcntl.h>
#include <unistd.h>
using namespace InferenceBackend;
VaApiContext::VaApiContext(VADisplay va_display) : _display(va_display) {
create_config_and_contexts();
create_supported_pixel_formats();
assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID.");
assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID.");
}
VaApiContext::VaApiContext(VaApiDisplayPtr va_display_ptr)
: _display_storage(va_display_ptr), _display(va_display_ptr.get()) {
create_config_and_contexts();
create_supported_pixel_formats();
assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID.");
assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID.");
}
VaApiContext::VaApiContext(const std::string &device) {
_display_storage = vaApiCreateVaDisplay(Utils::getRelativeGpuDeviceIndex(device));
_display = VaDpyWrapper::fromHandle(_display_storage.get());
create_config_and_contexts();
create_supported_pixel_formats();
assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID.");
assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID.");
}
VaApiContext::~VaApiContext() {
auto vtable = _display.drvVtable();
auto ctx = _display.drvCtx();
if (_va_context_id != VA_INVALID_ID) {
vtable.vaDestroyContext(ctx, _va_context_id);
}
if (_va_config_id != VA_INVALID_ID) {
vtable.vaDestroyConfig(ctx, _va_config_id);
}
}
VAContextID VaApiContext::Id() const {
return _va_context_id;
}
VaDpyWrapper VaApiContext::Display() const {
return _display;
}
VADisplay VaApiContext::DisplayRaw() const {
return _display.raw();
}
int VaApiContext::RTFormat() const {
return _rt_format;
}
bool VaApiContext::IsPixelFormatSupported(int format) const {
return _supported_pixel_formats.count(format);
}
/**
* Creates config, va context, and sets the driver context using the internal VADisplay.
* Setting the VADriverContextP, VAConfigID, and VAContextID to the corresponding variables.
*
* @pre _display must be set and initialized.
* @post _va_config_id is set.
* @post _va_context_id is set.
*
* @throw std::invalid_argument if the VaDpyWrapper is not created, runtime format not supported, unable to get config
* attributes, unable to create config, or unable to create context.
*/
void VaApiContext::create_config_and_contexts() {
assert(_display);
auto ctx = _display.drvCtx();
auto vtable = _display.drvVtable();
VAConfigAttrib format_attrib;
format_attrib.type = VAConfigAttribRTFormat;
VA_CALL(vtable.vaGetConfigAttributes(ctx, VAProfileNone, VAEntrypointVideoProc, &format_attrib, 1));
if (not(format_attrib.value & _rt_format))
throw std::invalid_argument("Could not create context. Runtime format is not supported.");
VAConfigAttrib attrib;
attrib.type = VAConfigAttribRTFormat;
attrib.value = _rt_format;
VA_CALL(vtable.vaCreateConfig(ctx, VAProfileNone, VAEntrypointVideoProc, &attrib, 1, &_va_config_id));
if (_va_config_id == 0) {
throw std::invalid_argument("Could not create VA config. Cannot initialize VaApiContext without VA config.");
}
VA_CALL(vtable.vaCreateContext(ctx, _va_config_id, 0, 0, VA_PROGRESSIVE, nullptr, 0, &_va_context_id));
if (_va_context_id == 0) {
throw std::invalid_argument("Could not create VA context. Cannot initialize VaApiContext without VA context.");
}
}
/**
* Creates a set of formats supported by image.
*
* @pre _display must be set and initialized.
* @post _supported_pixel_formats is set.
*
* @throw std::runtime_error if vaQueryImageFormats return non success code
*/
void VaApiContext::create_supported_pixel_formats() {
assert(_display);
auto ctx = _display.drvCtx();
auto vtable = _display.drvVtable();
std::vector<VAImageFormat> image_formats(ctx->max_image_formats);
int size = 0;
VA_CALL(vtable.vaQueryImageFormats(ctx, image_formats.data(), &size));
for (int i = 0; i < size; i++)
_supported_pixel_formats.insert(image_formats[i].fourcc);
}
| 33.635714 | 119 | 0.712678 | MisterArslan |
81baf3ae028b0ebf7d0bc882ffb7ba903141ed6e | 2,594 | cpp | C++ | src/lib/tide/api/environment_binding.cpp | dubcanada/TideSDKLite | f2f3959e8d464c1096bd5e0963149a3589d54a25 | [
"Apache-2.0"
] | 2 | 2015-11-05T01:53:44.000Z | 2015-12-17T06:52:12.000Z | src/lib/tide/api/environment_binding.cpp | aykutb/TideSDK | 267e1cb86dc2dc7bef136a78a6f2177233bad233 | [
"Apache-2.0"
] | null | null | null | src/lib/tide/api/environment_binding.cpp | aykutb/TideSDK | 267e1cb86dc2dc7bef136a78a6f2177233bad233 | [
"Apache-2.0"
] | 1 | 2015-07-12T19:35:36.000Z | 2015-07-12T19:35:36.000Z | /**
* This file has been modified from its orginal sources.
*
* Copyright (c) 2012 Software in the Public Interest Inc (SPI)
* Copyright (c) 2012 David Pratt
*
* 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.
*
***
* Copyright (c) 2008-2012 Appcelerator 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 "environment_binding.h"
#include <tideutils/environment_utils.h>
namespace tide
{
ValueRef EnvironmentBinding::Get(const char *name)
{
return Value::NewString(EnvironmentUtils::Get(name));
}
SharedStringList EnvironmentBinding::GetPropertyNames()
{
std::map<std::string, std::string> env = EnvironmentUtils::GetEnvironment();
SharedStringList keys = new StringList();
std::map<std::string, std::string>::iterator iter = env.begin();
for (; iter != env.end(); iter++)
{
keys->push_back(new std::string(iter->first));
}
return keys;
}
void EnvironmentBinding::Set(const char *name, ValueRef value)
{
if (value->IsString())
{
EnvironmentUtils::Set(name, value->ToString());
}
}
SharedString EnvironmentBinding::DisplayString(int levels)
{
std::map<std::string, std::string> env = EnvironmentUtils::GetEnvironment();
std::map<std::string, std::string>::iterator iter = env.begin();
SharedString str = new std::string();
for (; iter != env.end(); iter++)
{
(*str) += iter->first + "=" + iter->second + ",";
}
return str;
}
}
| 32.835443 | 84 | 0.660756 | dubcanada |
81bc6385d9522fc960507eb8b4db75542d010bfd | 3,361 | cpp | C++ | build/linux-build/Sources/src/kha/kore/graphics4/ConstantLocation.cpp | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | build/linux-build/Sources/src/kha/kore/graphics4/ConstantLocation.cpp | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | build/linux-build/Sources/src/kha/kore/graphics4/ConstantLocation.cpp | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | // Generated by Haxe 4.0.5
#include <hxcpp.h>
#ifndef INCLUDED_kha_graphics4_ConstantLocation
#include <hxinc/kha/graphics4/ConstantLocation.h>
#endif
#ifndef INCLUDED_kha_kore_graphics4_ConstantLocation
#include <hxinc/kha/kore/graphics4/ConstantLocation.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_8a98049bf91d5975_10_new,"kha.kore.graphics4.ConstantLocation","new",0x99ddedbd,"kha.kore.graphics4.ConstantLocation.new","kha/kore/graphics4/ConstantLocation.hx",10,0x6d842492)
namespace kha{
namespace kore{
namespace graphics4{
void ConstantLocation_obj::__construct(){
HX_STACKFRAME(&_hx_pos_8a98049bf91d5975_10_new)
}
Dynamic ConstantLocation_obj::__CreateEmpty() { return new ConstantLocation_obj; }
void *ConstantLocation_obj::_hx_vtable = 0;
Dynamic ConstantLocation_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< ConstantLocation_obj > _hx_result = new ConstantLocation_obj();
_hx_result->__construct();
return _hx_result;
}
bool ConstantLocation_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x3f26b36b;
}
static ::kha::graphics4::ConstantLocation_obj _hx_kha_kore_graphics4_ConstantLocation__hx_kha_graphics4_ConstantLocation= {
};
void *ConstantLocation_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0x9aec187e: return &_hx_kha_kore_graphics4_ConstantLocation__hx_kha_graphics4_ConstantLocation;
}
#ifdef HXCPP_SCRIPTABLE
return super::_hx_getInterface(inHash);
#else
return 0;
#endif
}
hx::ObjectPtr< ConstantLocation_obj > ConstantLocation_obj::__new() {
hx::ObjectPtr< ConstantLocation_obj > __this = new ConstantLocation_obj();
__this->__construct();
return __this;
}
hx::ObjectPtr< ConstantLocation_obj > ConstantLocation_obj::__alloc(hx::Ctx *_hx_ctx) {
ConstantLocation_obj *__this = (ConstantLocation_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ConstantLocation_obj), false, "kha.kore.graphics4.ConstantLocation"));
*(void **)__this = ConstantLocation_obj::_hx_vtable;
__this->__construct();
return __this;
}
ConstantLocation_obj::ConstantLocation_obj()
{
}
#ifdef HXCPP_SCRIPTABLE
static hx::StorageInfo *ConstantLocation_obj_sMemberStorageInfo = 0;
static hx::StaticInfo *ConstantLocation_obj_sStaticStorageInfo = 0;
#endif
hx::Class ConstantLocation_obj::__mClass;
void ConstantLocation_obj::__register()
{
ConstantLocation_obj _hx_dummy;
ConstantLocation_obj::_hx_vtable = *(void **)&_hx_dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_("kha.kore.graphics4.ConstantLocation",4b,4b,13,b9);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = hx::TCanCast< ConstantLocation_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ConstantLocation_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ConstantLocation_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace kha
} // end namespace kore
} // end namespace graphics4
| 33.61 | 206 | 0.793216 | 5Mixer |
81c094b450ad01b902cec3b24adeddf2af841f88 | 6,046 | cpp | C++ | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/ThumbnailGenerator.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/ThumbnailGenerator.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/ThumbnailGenerator.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "ThumbnailGenerator.h"
#include "ExceptionPolicy.h"
using namespace concurrency;
using namespace std;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Imaging;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Windows::Storage::FileProperties;
using namespace Hilo;
// See http://go.microsoft.com/fwlink/?LinkId=267275 for info about Hilo's implementation of tiles.
const unsigned int ThumbnailSize = 270;
const wstring ThumbnailImagePrefix = L"thumbImage_";
ThumbnailGenerator::ThumbnailGenerator(std::shared_ptr<ExceptionPolicy> policy) : m_exceptionPolicy(policy)
{
}
task<Vector<StorageFile^>^> ThumbnailGenerator::Generate(
IVector<StorageFile^>^ files,
StorageFolder^ thumbnailsFolder)
{
vector<task<StorageFile^>> thumbnailTasks;
unsigned int imageCounter = 0;
for (auto imageFile : files)
{
wstringstream localFileName;
localFileName << ThumbnailImagePrefix << imageCounter++ << ".jpg";
thumbnailTasks.push_back(
CreateLocalThumbnailAsync(
thumbnailsFolder,
imageFile,
ref new String(localFileName.str().c_str()),
ThumbnailSize,
m_exceptionPolicy));
}
return when_all(begin(thumbnailTasks), end(thumbnailTasks)).then(
[](vector<StorageFile^> files)
{
auto result = ref new Vector<StorageFile^>();
for (auto file : files)
{
if (file != nullptr)
{
result->Append(file);
}
}
return result;
});
}
task<StorageFile^> ThumbnailGenerator::CreateLocalThumbnailAsync(
StorageFolder^ folder,
StorageFile^ imageFile,
String^ localFileName,
unsigned int thumbSize,
std::shared_ptr<ExceptionPolicy> exceptionPolicy)
{
auto createThumbnail = create_task(
CreateThumbnailFromPictureFileAsync(imageFile, thumbSize));
return createThumbnail.then([exceptionPolicy, folder, localFileName](
task<InMemoryRandomAccessStream^> createdThumbnailTask)
{
InMemoryRandomAccessStream^ createdThumbnail;
try
{
createdThumbnail = createdThumbnailTask.get();
}
catch(Exception^ ex)
{
exceptionPolicy->HandleException(ex);
// If we have any exceptions we won't return the results
// of this task, but instead nullptr. Downstream
// tasks will need to account for this.
return create_task_from_result<StorageFile^>(nullptr);
}
return InternalSaveToFile(folder, createdThumbnail, localFileName);
});
}
task<StorageFile^> ThumbnailGenerator::InternalSaveToFile(
StorageFolder^ thumbnailsFolder,
InMemoryRandomAccessStream^ stream,
Platform::String^ filename)
{
auto imageFile = make_shared<StorageFile^>(nullptr);
auto streamReader = ref new DataReader(stream);
auto loadStreamTask = create_task(
streamReader->LoadAsync(static_cast<unsigned int>(stream->Size)));
return loadStreamTask.then(
[thumbnailsFolder, filename](unsigned int loadedBytes)
{
(void)loadedBytes; // Unused parameter
return thumbnailsFolder->CreateFileAsync(
filename,
CreationCollisionOption::ReplaceExisting);
}).then([streamReader, imageFile](StorageFile^ thumbnailDestinationFile)
{
(*imageFile) = thumbnailDestinationFile;
auto buffer = streamReader->ReadBuffer(
streamReader->UnconsumedBufferLength);
return FileIO::WriteBufferAsync(thumbnailDestinationFile, buffer);
}).then([imageFile]()
{
return (*imageFile);
});
}
task<InMemoryRandomAccessStream^> ThumbnailGenerator::CreateThumbnailFromPictureFileAsync(
StorageFile^ sourceFile,
unsigned int thumbSize)
{
(void)thumbSize; // Unused parameter
auto decoder = make_shared<BitmapDecoder^>(nullptr);
auto pixelProvider = make_shared<PixelDataProvider^>(nullptr);
auto resizedImageStream = ref new InMemoryRandomAccessStream();
auto createThumbnail = create_task(
sourceFile->GetThumbnailAsync(
ThumbnailMode::PicturesView,
ThumbnailSize));
return createThumbnail.then([](StorageItemThumbnail^ thumbnail)
{
IRandomAccessStream^ imageFileStream =
static_cast<IRandomAccessStream^>(thumbnail);
return BitmapDecoder::CreateAsync(imageFileStream);
}).then([decoder](BitmapDecoder^ createdDecoder)
{
(*decoder) = createdDecoder;
return createdDecoder->GetPixelDataAsync(
BitmapPixelFormat::Rgba8,
BitmapAlphaMode::Straight,
ref new BitmapTransform(),
ExifOrientationMode::IgnoreExifOrientation,
ColorManagementMode::ColorManageToSRgb);
}).then([pixelProvider, resizedImageStream](PixelDataProvider^ provider)
{
(*pixelProvider) = provider;
return BitmapEncoder::CreateAsync(
BitmapEncoder::JpegEncoderId,
resizedImageStream);
}).then([pixelProvider, decoder](BitmapEncoder^ createdEncoder)
{
createdEncoder->SetPixelData(BitmapPixelFormat::Rgba8,
BitmapAlphaMode::Straight,
(*decoder)->PixelWidth,
(*decoder)->PixelHeight,
(*decoder)->DpiX,
(*decoder)->DpiY,
(*pixelProvider)->DetachPixelData());
return createdEncoder->FlushAsync();
}).then([resizedImageStream]
{
resizedImageStream->Seek(0);
return resizedImageStream;
});
}
| 32.331551 | 107 | 0.676811 | alonmm |
81c1c41f2a88147dab9a2a82d236621e7cddeb25 | 817 | cpp | C++ | src/Stopwatch.cpp | matheuscscp/metallicar | 6508735a7f3ce526637622834fdb95f6d6297687 | [
"MIT"
] | null | null | null | src/Stopwatch.cpp | matheuscscp/metallicar | 6508735a7f3ce526637622834fdb95f6d6297687 | [
"MIT"
] | null | null | null | src/Stopwatch.cpp | matheuscscp/metallicar | 6508735a7f3ce526637622834fdb95f6d6297687 | [
"MIT"
] | null | null | null | /*
* Stopwatch.cpp
*
* Created on: Jul 14, 2014
* Author: Pimenta
*/
// this
#include "metallicar_time.hpp"
namespace metallicar {
Stopwatch::Stopwatch() :
started(false), paused(false), initialTime(0), pauseTime(0)
{
}
void Stopwatch::start() {
started = true;
paused = false;
initialTime = Time::get();
}
void Stopwatch::pause() {
if (!paused) {
paused = true;
pauseTime = Time::get();
}
}
void Stopwatch::resume() {
if (paused) {
paused = false;
initialTime += Time::get() - pauseTime;
}
}
void Stopwatch::reset() {
started = false;
}
uint32_t Stopwatch::time() {
if (!started)
return 0;
if (paused)
return pauseTime - initialTime;
return Time::get() - initialTime;
}
} // namespace metallicar
| 15.711538 | 60 | 0.578947 | matheuscscp |
81c2485a415b77dc4cc7cbaf97f96adba66a3f36 | 330 | cpp | C++ | src/ResourceFormatter/ResourceFormatterText.cpp | farlepet/coapserver | 5709add6cc4c1d61db1b719196d6941bdde96878 | [
"MIT"
] | 1 | 2021-07-04T21:52:23.000Z | 2021-07-04T21:52:23.000Z | src/ResourceFormatter/ResourceFormatterText.cpp | farlepet/coapserver | 5709add6cc4c1d61db1b719196d6941bdde96878 | [
"MIT"
] | 12 | 2022-02-26T16:27:58.000Z | 2022-03-26T17:32:22.000Z | src/ResourceFormatter/ResourceFormatterText.cpp | farlepet/coapserver | 5709add6cc4c1d61db1b719196d6941bdde96878 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "ResourceFormatter/ResourceFormatterText.hpp"
ResourceFormatterText::ResourceFormatterText() {
}
int ResourceFormatterText::decode(const std::vector<uint8_t> &data, std::ostream &out) {
for(size_t i = 0; i < data.size(); i++) {
out << static_cast<char>(data[i]);
}
return 0;
}
| 20.625 | 88 | 0.672727 | farlepet |
81c5225c29991d1c912b627488024fe772733b79 | 145,529 | cpp | C++ | src/crypto/digest.cpp | nextcashtech/nextcash | f16e9938d55dd42ce9a6d6fcfbf948d0ee6165e7 | [
"MIT"
] | 1 | 2017-11-23T03:00:39.000Z | 2017-11-23T03:00:39.000Z | src/crypto/digest.cpp | arcmist/arcmist | f16e9938d55dd42ce9a6d6fcfbf948d0ee6165e7 | [
"MIT"
] | null | null | null | src/crypto/digest.cpp | arcmist/arcmist | f16e9938d55dd42ce9a6d6fcfbf948d0ee6165e7 | [
"MIT"
] | null | null | null | /**************************************************************************
* Copyright 2017-2018 NextCash, LLC *
* Contributors : *
* Curtis Ellis <[email protected]> *
* Distributed under the MIT software license, see the accompanying *
* file license.txt or http://www.opensource.org/licenses/mit-license.php *
**************************************************************************/
#include "digest.hpp"
#include "endian.hpp"
#include "math.hpp"
#include "log.hpp"
#include "stream.hpp"
#include "buffer.hpp"
#include <cstdint>
#include <cstring>
#include <vector>
#define NEXTCASH_DIGEST_LOG_NAME "Digest"
namespace NextCash
{
namespace CRC32
{
static const uint32_t table[256] =
{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
}
void Digest::crc32(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput)
{
uint32_t result = 0xffffffff;
stream_size remaining = pInputLength;
while(remaining--)
result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pInput->readByte()];
result ^= 0xffffffff;
pOutput->writeUnsignedInt(Endian::convert(result, Endian::BIG));
}
uint32_t Digest::crc32(const char *pText)
{
uint32_t result = 0xffffffff;
unsigned int offset = 0;
while(pText[offset])
result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pText[offset++]];
return result ^ 0xffffffff;
}
uint32_t Digest::crc32(const uint8_t *pData, stream_size pSize)
{
uint32_t result = 0xffffffff;
stream_size offset = 0;
while(offset < pSize)
result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pData[offset++]];
return result ^ 0xffffffff;
}
namespace MD5
{
inline int f(int pX, int pY, int pZ)
{
// XY v not(X) Z
return (pX & pY) | (~pX & pZ);
}
inline int g(int pX, int pY, int pZ)
{
// XZ v Y not(Z)
return (pX & pZ) |(pY & ~pZ);
}
inline int h(int pX, int pY, int pZ)
{
// X xor Y xor Z
return (pX ^ pY) ^ pZ;
}
inline int i(int pX, int pY, int pZ)
{
// Y xor(X v not(Z))
return pY ^ (pX | ~pZ);
}
inline void round1(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI)
{
int step1 = (pA + f(pB, pC, pD) + pXK + pTI);
pA = pB + Math::rotateLeft(step1, pS);
}
inline void round2(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI)
{
int step1 = (pA + g(pB, pC, pD) + pXK + pTI);
pA = pB + Math::rotateLeft(step1, pS);
}
inline void round3(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI)
{
int step1 = (pA + h(pB, pC, pD) + pXK + pTI);
pA = pB + Math::rotateLeft(step1, pS);
}
inline void round4(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI)
{
int step1 = (pA + i(pB, pC, pD) + pXK + pTI);
pA = pB + Math::rotateLeft(step1, pS);
}
// Encodes raw bytes into the 16 integer block
inline void encode(uint8_t *pData, int *pBlock)
{
int i, j;
for(i=0,j=0;j<64;i++,j+=4)
pBlock[i] = ((int)pData[j]) | (((int)pData[j+1]) << 8) |
(((int)pData[j+2]) << 16) | (((int)pData[j+3]) << 24);
}
// Decodes 16 integer block into raw bytes
inline void decode(int *pBlock, uint8_t *pData)
{
int i, j;
for(i=0,j=0;j<64;i++,j+=4)
{
pData[j] = (uint8_t)(pBlock[i] & 0xff);
pData[j+1] = (uint8_t)((pBlock[i] >> 8) & 0xff);
pData[j+2] = (uint8_t)((pBlock[i] >> 16) & 0xff);
pData[j+3] = (uint8_t)((pBlock[i] >> 24) & 0xff);
}
}
}
void Digest::md5(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 128 bit(16 byte) result
{
uint8_t *data;
stream_size dataSize = pInputLength + 9;
// Make the data size is congruent to 448, modulo 512 bits(56, 64 modulo bytes)
dataSize += (64 - (dataSize % 64));
data = new uint8_t[dataSize];
stream_size offset = pInputLength;
pInput->read(data, pInputLength);
data[offset++] = 128; // 10000000 - append a one bit and the rest zero bits
// Append the rest zero bits
if(offset <(dataSize - 1))
std::memset(data + offset, 0, dataSize - offset);
// Append the data length as a 64 bit number low order word first
int bitLength = pInputLength * 8;
data[dataSize - 8] = (uint8_t)(bitLength & 0xff);
data[dataSize - 7] = (uint8_t)((bitLength >> 8) & 0xff);
data[dataSize - 6] = (uint8_t)((bitLength >> 16) & 0xff);
data[dataSize - 5] = (uint8_t)((bitLength >> 24) & 0xff);
std::memset((data + dataSize) - 4, 0, 4);
// Setup buffers
int state[4], a, b, c, d;
state[0] = 0x67452301; // A
state[1] = 0xEFCDAB89; // B
state[2] = 0x98BADCFE; // C
state[3] = 0x10325476; // D
// Process 16 word(64 byte) blocks of data
int blockIndex, blockCount = dataSize / 64;
int blockX[16];
for(blockIndex=0;blockIndex<blockCount;blockIndex++)
{
// Copy current block into blockX
MD5::encode(data + (blockIndex * 64), blockX);
a = state[0];
b = state[1];
c = state[2];
d = state[3];
// Round 1 - a = b +((a + F(b,c,d) + X[k] + T[i]) <<< s)
MD5::round1(a, b, c, d, blockX[ 0], 7, 0xD76AA478);
MD5::round1(d, a, b, c, blockX[ 1], 12, 0xE8C7B756);
MD5::round1(c, d, a, b, blockX[ 2], 17, 0x242070DB);
MD5::round1(b, c, d, a, blockX[ 3], 22, 0xC1BDCEEE);
MD5::round1(a, b, c, d, blockX[ 4], 7, 0xF57C0FAF);
MD5::round1(d, a, b, c, blockX[ 5], 12, 0x4787C62A);
MD5::round1(c, d, a, b, blockX[ 6], 17, 0xA8304613);
MD5::round1(b, c, d, a, blockX[ 7], 22, 0xFD469501);
MD5::round1(a, b, c, d, blockX[ 8], 7, 0x698098D8);
MD5::round1(d, a, b, c, blockX[ 9], 12, 0x8B44F7AF);
MD5::round1(c, d, a, b, blockX[10], 17, 0xFFFF5BB1);
MD5::round1(b, c, d, a, blockX[11], 22, 0x895CD7BE);
MD5::round1(a, b, c, d, blockX[12], 7, 0x6B901122);
MD5::round1(d, a, b, c, blockX[13], 12, 0xFD987193);
MD5::round1(c, d, a, b, blockX[14], 17, 0xA679438E);
MD5::round1(b, c, d, a, blockX[15], 22, 0x49B40821);
// Round 2 - a = b +((a + G(b,,d) + X[k] + T[i]) <<< s)
MD5::round2(a, b, c, d, blockX[ 1], 5, 0xF61E2562);
MD5::round2(d, a, b, c, blockX[ 6], 9, 0xC040B340);
MD5::round2(c, d, a, b, blockX[11], 14, 0x265E5A51);
MD5::round2(b, c, d, a, blockX[ 0], 20, 0xE9B6C7AA);
MD5::round2(a, b, c, d, blockX[ 5], 5, 0xD62F105D);
MD5::round2(d, a, b, c, blockX[10], 9, 0x02441453);
MD5::round2(c, d, a, b, blockX[15], 14, 0xD8A1E681);
MD5::round2(b, c, d, a, blockX[ 4], 20, 0xE7D3FBC8);
MD5::round2(a, b, c, d, blockX[ 9], 5, 0x21E1CDE6);
MD5::round2(d, a, b, c, blockX[14], 9, 0xC33707D6);
MD5::round2(c, d, a, b, blockX[ 3], 14, 0xF4D50D87);
MD5::round2(b, c, d, a, blockX[ 8], 20, 0x455A14ED);
MD5::round2(a, b, c, d, blockX[13], 5, 0xA9E3E905);
MD5::round2(d, a, b, c, blockX[ 2], 9, 0xFCEFA3F8);
MD5::round2(c, d, a, b, blockX[ 7], 14, 0x676F02D9);
MD5::round2(b, c, d, a, blockX[12], 20, 0x8D2A4C8A);
// Round 3 - a = b +((a + H(b,,d) + X[k] + T[i]) <<< s)
MD5::round3(a, b, c, d, blockX[ 5], 4, 0xFFFA3942);
MD5::round3(d, a, b, c, blockX[ 8], 11, 0x8771F681);
MD5::round3(c, d, a, b, blockX[11], 16, 0x6D9D6122);
MD5::round3(b, c, d, a, blockX[14], 23, 0xFDE5380C);
MD5::round3(a, b, c, d, blockX[ 1], 4, 0xA4BEEA44);
MD5::round3(d, a, b, c, blockX[ 4], 11, 0x4BDECFA9);
MD5::round3(c, d, a, b, blockX[ 7], 16, 0xF6BB4B60);
MD5::round3(b, c, d, a, blockX[10], 23, 0xBEBFBC70);
MD5::round3(a, b, c, d, blockX[13], 4, 0x289B7EC6);
MD5::round3(d, a, b, c, blockX[ 0], 11, 0xEAA127FA);
MD5::round3(c, d, a, b, blockX[ 3], 16, 0xD4EF3085);
MD5::round3(b, c, d, a, blockX[ 6], 23, 0x04881D05);
MD5::round3(a, b, c, d, blockX[ 9], 4, 0xD9D4D039);
MD5::round3(d, a, b, c, blockX[12], 11, 0xE6DB99E5);
MD5::round3(c, d, a, b, blockX[15], 16, 0x1FA27CF8);
MD5::round3(b, c, d, a, blockX[ 2], 23, 0xC4AC5665);
// Round 4 - a = b +((a + I(b,,d) + X[k] + T[i]) <<< s)
MD5::round4(a, b, c, d, blockX[ 0], 6, 0xF4292244);
MD5::round4(d, a, b, c, blockX[ 7], 10, 0x432AFF97);
MD5::round4(c, d, a, b, blockX[14], 15, 0xAB9423A7);
MD5::round4(b, c, d, a, blockX[ 5], 21, 0xFC93A039);
MD5::round4(a, b, c, d, blockX[12], 6, 0x655B59C3);
MD5::round4(d, a, b, c, blockX[ 3], 10, 0x8F0CCC92);
MD5::round4(c, d, a, b, blockX[10], 15, 0xFFEFF47D);
MD5::round4(b, c, d, a, blockX[ 1], 21, 0x85845DD1);
MD5::round4(a, b, c, d, blockX[ 8], 6, 0x6FA87E4F);
MD5::round4(d, a, b, c, blockX[15], 10, 0xFE2CE6E0);
MD5::round4(c, d, a, b, blockX[ 6], 15, 0xA3014314);
MD5::round4(b, c, d, a, blockX[13], 21, 0x4E0811A1);
MD5::round4(a, b, c, d, blockX[ 4], 6, 0xF7537E82);
MD5::round4(d, a, b, c, blockX[11], 10, 0xBD3AF235);
MD5::round4(c, d, a, b, blockX[ 2], 15, 0x2AD7D2BB);
MD5::round4(b, c, d, a, blockX[ 9], 21, 0xEB86D391);
// Increment each state by it's previous value
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
pOutput->write((const uint8_t *)state, 16);
// Zeroize sensitive information
std::memset(blockX, 0, sizeof(blockX));
std::memset(data, 0, dataSize);
delete[] data;
}
namespace SHA1
{
void initialize(uint32_t *pResult)
{
pResult[0] = 0x67452301;
pResult[1] = 0xEFCDAB89;
pResult[2] = 0x98BADCFE;
pResult[3] = 0x10325476;
pResult[4] = 0xC3D2E1F0;
}
void process(uint32_t *pResult, uint32_t *pBlock)
{
unsigned int i;
uint32_t a, b, c, d, e, f, k, step;
uint32_t extendedBlock[80];
std::memcpy(extendedBlock, pBlock, 64);
// Adjust for big endian
if(Endian::sSystemType != Endian::BIG)
for(i=0;i<16;i++)
extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG);
// Extend the sixteen 32-bit words into eighty 32-bit words:
for(i=16;i<80;i++)
extendedBlock[i] = Math::rotateLeft(extendedBlock[i-3] ^ extendedBlock[i-8] ^ extendedBlock[i-14] ^ extendedBlock[i-16], 1);
// Initialize hash value for this chunk:
a = pResult[0];
b = pResult[1];
c = pResult[2];
d = pResult[3];
e = pResult[4];
// Main loop:
for(i=0;i<80;i++)
{
if(i < 20)
{
f = (b & c) |((~b) & d);
k = 0x5A827999;
}
else if(i < 40)
{
f = b ^ c ^ d;
k = 0x6ED9EBA1;
}
else if(i < 60)
{
f = (b & c) |(b & d) |(c & d);
k = 0x8F1BBCDC;
}
else // if(i < 80)
{
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
step = Math::rotateLeft(a, 5) + f + e + k + extendedBlock[i];
e = d;
d = c;
c = Math::rotateLeft(b, 30);
b = a;
a = step;
}
// Add this chunk's hash to result so far:
pResult[0] += a;
pResult[1] += b;
pResult[2] += c;
pResult[3] += d;
pResult[4] += e;
}
void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength)
{
// Zeroize the end of the block
std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength);
// Add 0x80 byte (basically a 1 bit at the end of the data)
((uint8_t *)pBlock)[pBlockLength] = 0x80;
// Check if there is enough room for the total length in this block
if(pBlockLength > 55) // 55 because of the 0x80 byte already added
{
process(pResult, pBlock); // Process this block
std::memset(pBlock, 0, 64); // Clear the block
}
// Put bit length in last 8 bytes of block (Big Endian)
pTotalLength *= 8;
uint32_t lower = pTotalLength & 0xffffffff;
pBlock[15] = Endian::convert(lower, Endian::BIG);
uint32_t upper = (pTotalLength >> 32) & 0xffffffff;
pBlock[14] = Endian::convert(upper, Endian::BIG);
// Process last block
process(pResult, pBlock);
// Adjust for big endian
if(Endian::sSystemType != Endian::BIG)
for(unsigned int i=0;i<5;i++)
pResult[i] = Endian::convert(pResult[i], Endian::BIG);
}
}
void Digest::sha1(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 160 bit(20 byte) result
{
// Note 1: All variables are unsigned 32 bits and wrap modulo 232 when calculating
// Note 2: All constants in this pseudo code are in big endian.
// Within each word, the most significant bit is stored in the leftmost bit position
stream_size dataSize = pInputLength + (64 - (pInputLength % 64));
uint64_t bitLength = (uint64_t)pInputLength * 8;
Buffer message;
message.setEndian(Endian::BIG);
message.writeStream(pInput, pInputLength);
// Pre-processing:
// append the bit '1' to the message
message.writeByte(0x80);
// append k bits '0', where k is the minimum number ? 0 such that the resulting message
// length(in bits) is congruent to 448(mod 512)
// Append the rest zero bits
while(message.length() < dataSize - 8)
message.writeByte(0);
// append length of message(before pre-processing), in bits, as 64-bit big-endian integer
// Append the data length as a 64 bit number low order word first
message.writeUnsignedLong(bitLength);
uint32_t state[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 };
uint32_t a, b, c, d, e;
// Process the message in successive 512-bit chunks:
// break message into 512-bit chunks
// for each chunk
unsigned int i, blockIndex, blockCount = dataSize / 64;
uint32_t extended[80];
uint32_t f, k, step;
for(blockIndex=0;blockIndex<blockCount;blockIndex++)
{
// break chunk into sixteen 32-bit big-endian words w[i], 0 ? i ? 15
for(i=0;i<16;i++)
extended[i] = message.readUnsignedInt();
// Extend the sixteen 32-bit words into eighty 32-bit words:
for(i=16;i<80;i++)
extended[i] = Math::rotateLeft(extended[i-3] ^ extended[i-8] ^ extended[i-14] ^ extended[i-16], 1);
// Initialize hash value for this chunk:
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
// Main loop:
for(i=0;i<80;i++)
{
if(i < 20)
{
f = (b & c) |((~b) & d);
k = 0x5A827999;
}
else if(i < 40)
{
f = b ^ c ^ d;
k = 0x6ED9EBA1;
}
else if(i < 60)
{
f = (b & c) |(b & d) |(c & d);
k = 0x8F1BBCDC;
}
else // if(i < 80)
{
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
step = Math::rotateLeft(a, 5) + f + e + k + extended[i];
e = d;
d = c;
c = Math::rotateLeft(b, 30);
b = a;
a = step;
}
// Add this chunk's hash to result so far:
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
}
for(unsigned int i=0;i<5;i++)
pOutput->writeUnsignedInt(Endian::convert(state[i], Endian::BIG));
// Zeroize possible sensitive data
message.zeroize();
std::memset(extended, 0, sizeof(int) * 80);
std::memset(state, 0, sizeof(int) * 5);
}
namespace RIPEMD160
{
inline uint32_t f(uint32_t pX, uint32_t pY, uint32_t pZ)
{
return pX ^ pY ^ pZ;
}
inline uint32_t g(uint32_t pX, uint32_t pY, uint32_t pZ)
{
return (pX & pY) | (~pX & pZ);
}
inline uint32_t h(uint32_t pX, uint32_t pY, uint32_t pZ)
{
return (pX | ~pY) ^ pZ;
}
inline uint32_t i(uint32_t pX, uint32_t pY, uint32_t pZ)
{
return (pX & pZ) | (pY & ~pZ);
}
inline uint32_t j(uint32_t pX, uint32_t pY, uint32_t pZ)
{
return pX ^ (pY | ~pZ);
}
inline void ff(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += f(pB, pC, pD) + pX;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void gg(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += g(pB, pC, pD) + pX + 0x5a827999;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void hh(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += h(pB, pC, pD) + pX + 0x6ed9eba1;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void ii(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += i(pB, pC, pD) + pX + 0x8f1bbcdc;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void jj(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += j(pB, pC, pD) + pX + 0xa953fd4e;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void fff(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += f(pB, pC, pD) + pX;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void ggg(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += g(pB, pC, pD) + pX + 0x7a6d76e9;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void hhh(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += h(pB, pC, pD) + pX + 0x6d703ef3;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void iii(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += i(pB, pC, pD) + pX + 0x5c4dd124;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
inline void jjj(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS)
{
pA += j(pB, pC, pD) + pX + 0x50a28be6;
pA = Math::rotateLeft(pA, pS) + pE;
pC = Math::rotateLeft(pC, 10);
}
void initialize(uint32_t *pResult)
{
pResult[0] = 0x67452301;
pResult[1] = 0xefcdab89;
pResult[2] = 0x98badcfe;
pResult[3] = 0x10325476;
pResult[4] = 0xc3d2e1f0;
}
void process(uint32_t *pResult, uint32_t *pBlock)
{
uint32_t aa = pResult[0], bb = pResult[1], cc = pResult[2], dd = pResult[3], ee = pResult[4];
uint32_t aaa = pResult[0], bbb = pResult[1], ccc = pResult[2], ddd = pResult[3], eee = pResult[4];
// Round 1
ff(aa, bb, cc, dd, ee, pBlock[ 0], 11);
ff(ee, aa, bb, cc, dd, pBlock[ 1], 14);
ff(dd, ee, aa, bb, cc, pBlock[ 2], 15);
ff(cc, dd, ee, aa, bb, pBlock[ 3], 12);
ff(bb, cc, dd, ee, aa, pBlock[ 4], 5);
ff(aa, bb, cc, dd, ee, pBlock[ 5], 8);
ff(ee, aa, bb, cc, dd, pBlock[ 6], 7);
ff(dd, ee, aa, bb, cc, pBlock[ 7], 9);
ff(cc, dd, ee, aa, bb, pBlock[ 8], 11);
ff(bb, cc, dd, ee, aa, pBlock[ 9], 13);
ff(aa, bb, cc, dd, ee, pBlock[10], 14);
ff(ee, aa, bb, cc, dd, pBlock[11], 15);
ff(dd, ee, aa, bb, cc, pBlock[12], 6);
ff(cc, dd, ee, aa, bb, pBlock[13], 7);
ff(bb, cc, dd, ee, aa, pBlock[14], 9);
ff(aa, bb, cc, dd, ee, pBlock[15], 8);
// Round 2
gg(ee, aa, bb, cc, dd, pBlock[ 7], 7);
gg(dd, ee, aa, bb, cc, pBlock[ 4], 6);
gg(cc, dd, ee, aa, bb, pBlock[13], 8);
gg(bb, cc, dd, ee, aa, pBlock[ 1], 13);
gg(aa, bb, cc, dd, ee, pBlock[10], 11);
gg(ee, aa, bb, cc, dd, pBlock[ 6], 9);
gg(dd, ee, aa, bb, cc, pBlock[15], 7);
gg(cc, dd, ee, aa, bb, pBlock[ 3], 15);
gg(bb, cc, dd, ee, aa, pBlock[12], 7);
gg(aa, bb, cc, dd, ee, pBlock[ 0], 12);
gg(ee, aa, bb, cc, dd, pBlock[ 9], 15);
gg(dd, ee, aa, bb, cc, pBlock[ 5], 9);
gg(cc, dd, ee, aa, bb, pBlock[ 2], 11);
gg(bb, cc, dd, ee, aa, pBlock[14], 7);
gg(aa, bb, cc, dd, ee, pBlock[11], 13);
gg(ee, aa, bb, cc, dd, pBlock[ 8], 12);
// Round 3
hh(dd, ee, aa, bb, cc, pBlock[ 3], 11);
hh(cc, dd, ee, aa, bb, pBlock[10], 13);
hh(bb, cc, dd, ee, aa, pBlock[14], 6);
hh(aa, bb, cc, dd, ee, pBlock[ 4], 7);
hh(ee, aa, bb, cc, dd, pBlock[ 9], 14);
hh(dd, ee, aa, bb, cc, pBlock[15], 9);
hh(cc, dd, ee, aa, bb, pBlock[ 8], 13);
hh(bb, cc, dd, ee, aa, pBlock[ 1], 15);
hh(aa, bb, cc, dd, ee, pBlock[ 2], 14);
hh(ee, aa, bb, cc, dd, pBlock[ 7], 8);
hh(dd, ee, aa, bb, cc, pBlock[ 0], 13);
hh(cc, dd, ee, aa, bb, pBlock[ 6], 6);
hh(bb, cc, dd, ee, aa, pBlock[13], 5);
hh(aa, bb, cc, dd, ee, pBlock[11], 12);
hh(ee, aa, bb, cc, dd, pBlock[ 5], 7);
hh(dd, ee, aa, bb, cc, pBlock[12], 5);
// Round 4
ii(cc, dd, ee, aa, bb, pBlock[ 1], 11);
ii(bb, cc, dd, ee, aa, pBlock[ 9], 12);
ii(aa, bb, cc, dd, ee, pBlock[11], 14);
ii(ee, aa, bb, cc, dd, pBlock[10], 15);
ii(dd, ee, aa, bb, cc, pBlock[ 0], 14);
ii(cc, dd, ee, aa, bb, pBlock[ 8], 15);
ii(bb, cc, dd, ee, aa, pBlock[12], 9);
ii(aa, bb, cc, dd, ee, pBlock[ 4], 8);
ii(ee, aa, bb, cc, dd, pBlock[13], 9);
ii(dd, ee, aa, bb, cc, pBlock[ 3], 14);
ii(cc, dd, ee, aa, bb, pBlock[ 7], 5);
ii(bb, cc, dd, ee, aa, pBlock[15], 6);
ii(aa, bb, cc, dd, ee, pBlock[14], 8);
ii(ee, aa, bb, cc, dd, pBlock[ 5], 6);
ii(dd, ee, aa, bb, cc, pBlock[ 6], 5);
ii(cc, dd, ee, aa, bb, pBlock[ 2], 12);
// Round 5
jj(bb, cc, dd, ee, aa, pBlock[ 4], 9);
jj(aa, bb, cc, dd, ee, pBlock[ 0], 15);
jj(ee, aa, bb, cc, dd, pBlock[ 5], 5);
jj(dd, ee, aa, bb, cc, pBlock[ 9], 11);
jj(cc, dd, ee, aa, bb, pBlock[ 7], 6);
jj(bb, cc, dd, ee, aa, pBlock[12], 8);
jj(aa, bb, cc, dd, ee, pBlock[ 2], 13);
jj(ee, aa, bb, cc, dd, pBlock[10], 12);
jj(dd, ee, aa, bb, cc, pBlock[14], 5);
jj(cc, dd, ee, aa, bb, pBlock[ 1], 12);
jj(bb, cc, dd, ee, aa, pBlock[ 3], 13);
jj(aa, bb, cc, dd, ee, pBlock[ 8], 14);
jj(ee, aa, bb, cc, dd, pBlock[11], 11);
jj(dd, ee, aa, bb, cc, pBlock[ 6], 8);
jj(cc, dd, ee, aa, bb, pBlock[15], 5);
jj(bb, cc, dd, ee, aa, pBlock[13], 6);
// Parallel round 1
jjj(aaa, bbb, ccc, ddd, eee, pBlock[ 5], 8);
jjj(eee, aaa, bbb, ccc, ddd, pBlock[14], 9);
jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 7], 9);
jjj(ccc, ddd, eee, aaa, bbb, pBlock[ 0], 11);
jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 13);
jjj(aaa, bbb, ccc, ddd, eee, pBlock[ 2], 15);
jjj(eee, aaa, bbb, ccc, ddd, pBlock[11], 15);
jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 4], 5);
jjj(ccc, ddd, eee, aaa, bbb, pBlock[13], 7);
jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 6], 7);
jjj(aaa, bbb, ccc, ddd, eee, pBlock[15], 8);
jjj(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 11);
jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 1], 14);
jjj(ccc, ddd, eee, aaa, bbb, pBlock[10], 14);
jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 3], 12);
jjj(aaa, bbb, ccc, ddd, eee, pBlock[12], 6);
// Parallel round 2
iii(eee, aaa, bbb, ccc, ddd, pBlock[ 6], 9);
iii(ddd, eee, aaa, bbb, ccc, pBlock[11], 13);
iii(ccc, ddd, eee, aaa, bbb, pBlock[ 3], 15);
iii(bbb, ccc, ddd, eee, aaa, pBlock[ 7], 7);
iii(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 12);
iii(eee, aaa, bbb, ccc, ddd, pBlock[13], 8);
iii(ddd, eee, aaa, bbb, ccc, pBlock[ 5], 9);
iii(ccc, ddd, eee, aaa, bbb, pBlock[10], 11);
iii(bbb, ccc, ddd, eee, aaa, pBlock[14], 7);
iii(aaa, bbb, ccc, ddd, eee, pBlock[15], 7);
iii(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 12);
iii(ddd, eee, aaa, bbb, ccc, pBlock[12], 7);
iii(ccc, ddd, eee, aaa, bbb, pBlock[ 4], 6);
iii(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 15);
iii(aaa, bbb, ccc, ddd, eee, pBlock[ 1], 13);
iii(eee, aaa, bbb, ccc, ddd, pBlock[ 2], 11);
// Parallel round 3
hhh(ddd, eee, aaa, bbb, ccc, pBlock[15], 9);
hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 5], 7);
hhh(bbb, ccc, ddd, eee, aaa, pBlock[ 1], 15);
hhh(aaa, bbb, ccc, ddd, eee, pBlock[ 3], 11);
hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 7], 8);
hhh(ddd, eee, aaa, bbb, ccc, pBlock[14], 6);
hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 6], 6);
hhh(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 14);
hhh(aaa, bbb, ccc, ddd, eee, pBlock[11], 12);
hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 13);
hhh(ddd, eee, aaa, bbb, ccc, pBlock[12], 5);
hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 2], 14);
hhh(bbb, ccc, ddd, eee, aaa, pBlock[10], 13);
hhh(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 13);
hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 4], 7);
hhh(ddd, eee, aaa, bbb, ccc, pBlock[13], 5);
// Parallel round 4
ggg(ccc, ddd, eee, aaa, bbb, pBlock[ 8], 15);
ggg(bbb, ccc, ddd, eee, aaa, pBlock[ 6], 5);
ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 4], 8);
ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 1], 11);
ggg(ddd, eee, aaa, bbb, ccc, pBlock[ 3], 14);
ggg(ccc, ddd, eee, aaa, bbb, pBlock[11], 14);
ggg(bbb, ccc, ddd, eee, aaa, pBlock[15], 6);
ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 14);
ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 5], 6);
ggg(ddd, eee, aaa, bbb, ccc, pBlock[12], 9);
ggg(ccc, ddd, eee, aaa, bbb, pBlock[ 2], 12);
ggg(bbb, ccc, ddd, eee, aaa, pBlock[13], 9);
ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 9], 12);
ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 7], 5);
ggg(ddd, eee, aaa, bbb, ccc, pBlock[10], 15);
ggg(ccc, ddd, eee, aaa, bbb, pBlock[14], 8);
// Parallel round 5
fff(bbb, ccc, ddd, eee, aaa, pBlock[12] , 8);
fff(aaa, bbb, ccc, ddd, eee, pBlock[15] , 5);
fff(eee, aaa, bbb, ccc, ddd, pBlock[10] , 12);
fff(ddd, eee, aaa, bbb, ccc, pBlock[ 4] , 9);
fff(ccc, ddd, eee, aaa, bbb, pBlock[ 1] , 12);
fff(bbb, ccc, ddd, eee, aaa, pBlock[ 5] , 5);
fff(aaa, bbb, ccc, ddd, eee, pBlock[ 8] , 14);
fff(eee, aaa, bbb, ccc, ddd, pBlock[ 7] , 6);
fff(ddd, eee, aaa, bbb, ccc, pBlock[ 6] , 8);
fff(ccc, ddd, eee, aaa, bbb, pBlock[ 2] , 13);
fff(bbb, ccc, ddd, eee, aaa, pBlock[13] , 6);
fff(aaa, bbb, ccc, ddd, eee, pBlock[14] , 5);
fff(eee, aaa, bbb, ccc, ddd, pBlock[ 0] , 15);
fff(ddd, eee, aaa, bbb, ccc, pBlock[ 3] , 13);
fff(ccc, ddd, eee, aaa, bbb, pBlock[ 9] , 11);
fff(bbb, ccc, ddd, eee, aaa, pBlock[11] , 11);
// Combine results
ddd += cc + pResult[1];
pResult[1] = pResult[2] + dd + eee;
pResult[2] = pResult[3] + ee + aaa;
pResult[3] = pResult[4] + aa + bbb;
pResult[4] = pResult[0] + bb + ccc;
pResult[0] = ddd;
}
// BlockLength must be less than 64
void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength)
{
// Zeroize the end of the block
std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength);
// Add 0x80 byte (basically a 1 bit at the end of the data)
((uint8_t *)pBlock)[pBlockLength] = 0x80;
// Check if there is enough room for the total length in this block
if(pBlockLength > 55) // 55 because of the 0x80 byte
{
process(pResult, pBlock); // Process this block
std::memset(pBlock, 0, 64); // Clear the block
}
// Put bit length in last 8 bytes of block
pTotalLength *= 8;
((uint64_t *)pBlock)[7] = Endian::convert(pTotalLength, Endian::LITTLE);
// Process last block
process(pResult, pBlock);
}
}
void Digest::ripEMD160(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput)
{
uint32_t result[5];
uint32_t block[16];
stream_size remaining = pInputLength;
RIPEMD160::initialize(result);
// Process all full (64 byte) blocks
while(remaining >= 64)
{
pInput->read(block, 64);
remaining -= 64;
RIPEMD160::process(result, block);
}
// Get last partial block (must be less than 64 bytes)
pInput->read(block, remaining);
// Process last block
RIPEMD160::finish(result, block, remaining, pInputLength);
// Write output
pOutput->write(result, 20);
}
namespace SHA256
{
static const uint32_t table[64] =
{
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
void initialize(uint32_t *pResult)
{
pResult[0] = 0x6a09e667;
pResult[1] = 0xbb67ae85;
pResult[2] = 0x3c6ef372;
pResult[3] = 0xa54ff53a;
pResult[4] = 0x510e527f;
pResult[5] = 0x9b05688c;
pResult[6] = 0x1f83d9ab;
pResult[7] = 0x5be0cd19;
}
void process(uint32_t *pResult, uint32_t *pBlock)
{
unsigned int i;
uint32_t s0, s1, t1, t2;
uint32_t extendedBlock[64];
std::memcpy(extendedBlock, pBlock, 64);
// Adjust for big endian
if(Endian::sSystemType != Endian::BIG)
for(i=0;i<16;i++)
extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG);
// Extend the block to 64 32-bit words:
for(i=16;i<64;i++)
{
s0 = extendedBlock[i-15];
s0 = Math::rotateRight(s0, 7) ^ Math::rotateRight(s0, 18) ^ (s0 >> 3);
s1 = extendedBlock[i-2];
s1 = Math::rotateRight(s1, 17) ^ Math::rotateRight(s1, 19) ^ (s1 >> 10);
extendedBlock[i] = extendedBlock[i-16] + extendedBlock[i-7] + s0 + s1;
}
uint32_t state[8];
std::memcpy(state, pResult, 32);
for(i=0;i<64;i++)
{
s0 = Math::rotateRight(state[0], 2) ^ Math::rotateRight(state[0], 13) ^ Math::rotateRight(state[0], 22);
t2 = s0 +((state[0] & state[1]) ^(state [0] & state[2]) ^(state[1] & state[2]));
s1 = Math::rotateRight(state[4], 6) ^ Math::rotateRight(state[4], 11) ^ Math::rotateRight(state[4], 25);
t1 = state[7] + s1 +((state[4] & state[5]) ^(~state[4] & state[6])) + table[i] + extendedBlock[i];
state[7] = state[6];
state[6] = state[5];
state[5] = state[4];
state[4] = state[3] + t1;
state[3] = state[2];
state[2] = state[1];
state[1] = state[0];
state[0] = t1 + t2;
}
for(i=0;i<8;i++)
pResult[i] += state[i];
}
void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength)
{
// Zeroize the end of the block
std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength);
// Add 0x80 byte (basically a 1 bit at the end of the data)
((uint8_t *)pBlock)[pBlockLength] = 0x80;
// Check if there is enough room for the total length in this block
if(pBlockLength > 55) // 56 - 1 because of the 0x80 byte already added
{
process(pResult, pBlock); // Process this block
std::memset(pBlock, 0, 64); // Clear the block
}
// Put bit length in last 8 bytes of block (Big Endian)
pTotalLength *= 8;
((uint64_t *)pBlock)[7] = Endian::convert(pTotalLength, Endian::BIG);
// Process last block
process(pResult, pBlock);
// Adjust for big endian
if(Endian::sSystemType != Endian::BIG)
for(unsigned int i=0;i<8;i++)
pResult[i] = Endian::convert(pResult[i], Endian::BIG);
}
}
void Digest::sha256(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 256 bit(32 byte) result
{
stream_size remaining = pInputLength;
uint32_t result[8];
uint32_t block[16];
SHA256::initialize(result);
while(remaining >= 64)
{
pInput->read(block, 64);
remaining -= 64;
SHA256::process(result, block);
}
pInput->read(block, remaining);
SHA256::finish(result, block, remaining, pInputLength);
pOutput->write(result, 32);
return;
}
namespace SHA512
{
static const uint64_t table[80] =
{
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
};
void initialize(uint32_t *pResult)
{
((uint64_t *)pResult)[0] = 0x6a09e667f3bcc908;
((uint64_t *)pResult)[1] = 0xbb67ae8584caa73b;
((uint64_t *)pResult)[2] = 0x3c6ef372fe94f82b;
((uint64_t *)pResult)[3] = 0xa54ff53a5f1d36f1;
((uint64_t *)pResult)[4] = 0x510e527fade682d1;
((uint64_t *)pResult)[5] = 0x9b05688c2b3e6c1f;
((uint64_t *)pResult)[6] = 0x1f83d9abfb41bd6b;
((uint64_t *)pResult)[7] = 0x5be0cd19137e2179;
}
void process(uint32_t *pResult, uint32_t *pBlock)
{
unsigned int i;
uint64_t s0, s1, t1, t2;
uint64_t extendedBlock[80];
std::memcpy(extendedBlock, pBlock, 128);
// Adjust for big endian
if(Endian::sSystemType != Endian::BIG)
for(i=0;i<16;++i)
extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG);
// Extend the block to 80 64-bit words:
for(i=16;i<80;++i)
{
s0 = extendedBlock[i-15];
s0 = Math::rotateRight64(s0, 1) ^ Math::rotateRight64(s0, 8) ^ (s0 >> 7);
s1 = extendedBlock[i-2];
s1 = Math::rotateRight64(s1, 19) ^ Math::rotateRight64(s1, 61) ^ (s1 >> 6);
extendedBlock[i] = extendedBlock[i-16] + extendedBlock[i-7] + s0 + s1;
}
uint64_t state[8];
std::memcpy(state, pResult, 64);
for(i=0;i<80;++i)
{
s0 = Math::rotateRight64(state[0], 28) ^ Math::rotateRight64(state[0], 34) ^ Math::rotateRight64(state[0], 39);
t2 = s0 +((state[0] & state[1]) ^ (state [0] & state[2]) ^ (state[1] & state[2]));
s1 = Math::rotateRight64(state[4], 14) ^ Math::rotateRight64(state[4], 18) ^ Math::rotateRight64(state[4], 41);
t1 = state[7] + s1 + ((state[4] & state[5]) ^ (~state[4] & state[6])) + table[i] + extendedBlock[i];
state[7] = state[6];
state[6] = state[5];
state[5] = state[4];
state[4] = state[3] + t1;
state[3] = state[2];
state[2] = state[1];
state[1] = state[0];
state[0] = t1 + t2;
}
for(i=0;i<8;++i)
((uint64_t *)pResult)[i] += state[i];
}
void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength)
{
// Zeroize the end of the block
if(pBlockLength < 128)
std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 128 - pBlockLength);
// Add 0x80 byte (basically a 1 bit at the end of the data)
((uint8_t *)pBlock)[pBlockLength] = 0x80;
// Check if there is enough room for the total length in this block
if(pBlockLength > 111) // 112 - 1 because of the 0x80 byte already added
{
process(pResult, pBlock); // Process this block
std::memset(pBlock, 0, 128); // Clear the block
}
// Put bit length in last 16 bytes of block (Big Endian)
pTotalLength *= 8;
((uint64_t *)pBlock)[15] = Endian::convert(pTotalLength, Endian::BIG);
// Process last block
process(pResult, pBlock);
// Adjust for big endian
if(Endian::sSystemType != Endian::BIG)
for(unsigned int i=0;i<8;++i)
((uint64_t *)pResult)[i] = Endian::convert(((uint64_t *)pResult)[i], Endian::BIG);
}
}
void Digest::sha512(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 512 bit(64 byte) result
{
stream_size remaining = pInputLength;
uint32_t result[16];
uint32_t block[32];
SHA512::initialize(result);
while(remaining >= 128)
{
pInput->read(block, 128);
remaining -= 128;
SHA512::process(result, block);
}
pInput->read(block, remaining);
SHA512::finish(result, block, remaining, pInputLength);
pOutput->write(result, 64);
return;
}
namespace SipHash24
{
void round(uint64_t *pResult, unsigned int pRounds)
{
for(unsigned i=0;i<pRounds;i++)
{
pResult[0] += pResult[1];
pResult[1] = Math::rotateLeft64(pResult[1], 13);
pResult[1] ^= pResult[0];
pResult[0] = Math::rotateLeft64(pResult[0], 32);
pResult[2] += pResult[3];
pResult[3] = Math::rotateLeft64(pResult[3], 16);
pResult[3] ^= pResult[2];
pResult[0] += pResult[3];
pResult[3] = Math::rotateLeft64(pResult[3], 21);
pResult[3] ^= pResult[0];
pResult[2] += pResult[1];
pResult[1] = Math::rotateLeft64(pResult[1], 17);
pResult[1] ^= pResult[2];
pResult[2] = Math::rotateLeft64(pResult[2], 32);
}
}
void initialize(uint64_t *pResult, uint64_t pKey0, uint64_t pKey1)
{
pResult[0] = 0x736f6d6570736575 ^ pKey0;
pResult[1] = 0x646f72616e646f6d ^ pKey1;
pResult[2] = 0x6c7967656e657261 ^ pKey0;
pResult[3] = 0x7465646279746573 ^ pKey1;
}
// Process 8 bytes
void process(uint64_t *pResult, const uint8_t *pBlock)
{
// Grab 8 bytes from pBlock and convert to uint64_t
uint64_t block = 0;
const uint8_t *byte = pBlock;
for(unsigned int i=0;i<8;++i)
block |= (uint64_t)*byte++ << (i * 8);
pResult[3] ^= block;
round(pResult, 2); // The 2 from SipHash-2-4
pResult[0] ^= block;
}
// Process less than 8 bytes and length
uint64_t finish(uint64_t *pResult, const uint8_t *pBlock, unsigned int pBlockLength,
uint64_t pTotalLength)
{
// Create last block
uint8_t lastBlock[8];
std::memset(lastBlock, 0, 8);
// Copy partial block into last block
std::memcpy(lastBlock, pBlock, pBlockLength);
// Put least significant byte of total length into most significant byte of
// last "block"
lastBlock[7] = pTotalLength & 0xff;
// Process last block
process(pResult, lastBlock);
pResult[2] ^= 0xff;
round(pResult, 4); // The 4 from SipHash-2-4
return pResult[0] ^ pResult[1] ^ pResult[2] ^ pResult[3];
}
}
uint64_t Digest::sipHash24(const uint8_t *pData, stream_size pLength, uint64_t pKey0,
uint64_t pKey1)
{
uint64_t result[4];
SipHash24::initialize(result, pKey0, pKey1);
stream_size offset = 0;
while(pLength - offset >= 8)
{
SipHash24::process(result, pData);
pData += 8;
offset += 8;
}
return SipHash24::finish(result, pData, pLength - offset, pLength);
}
namespace MURMUR3
{
// Only 32 bit implemented
void initialize(uint32_t &pResult, uint32_t pSeed)
{
pResult = pSeed;
}
// Process 4 bytes
void process(uint32_t &pResult, uint32_t pBlock)
{
uint32_t block = pBlock;
block *= 0xcc9e2d51;
block = (block << 15) | (block >> 17);
block *= 0x1b873593;
pResult ^= block;
pResult = (pResult << 13) | (pResult >> 19);
pResult = (pResult * 5) + 0xe6546b64;
}
// Process less than 4 bytes and length
void finish(uint32_t &pResult, const uint8_t *pBlockData, unsigned int pBlockLength,
uint64_t pTotalLength)
{
if(pBlockLength > 0)
{
uint32_t block = 0;
const uint8_t *byte = pBlockData;
for(unsigned int i=0;i<pBlockLength;++i)
block |= (uint32_t)*byte++ << (i * 8);
block *= 0xcc9e2d51;
block = (block << 15) | (block >> 17);
block *= 0x1b873593;
pResult ^= block;
}
pResult ^= pTotalLength;
pResult ^= pResult >> 16;
pResult *= 0x85ebca6b;
pResult ^= pResult >> 13;
pResult *= 0xc2b2ae35;
pResult ^= pResult >> 16;
}
}
uint32_t Digest::murMur3(const uint8_t *pData, stream_size pLength, uint32_t pSeed)
{
uint32_t result;
MURMUR3::initialize(result, pSeed);
stream_size offset = 0;
while(pLength - offset >= 4)
{
MURMUR3::process(result, Endian::convert(*(uint32_t *)pData, Endian::LITTLE));
pData += 4;
offset += 4;
}
MURMUR3::finish(result, pData, pLength - offset, pLength);
return result;
}
Digest::Digest(Type pType)
{
mType = pType;
mByteCount = 0;
setOutputEndian(Endian::BIG);
switch(mType)
{
case CRC32:
mBlockSize = 1;
mResultData = new uint32_t[1];
mBlockData = NULL;
break;
//case MD5:
// mBlockSize = 64;
// break;
case SHA1:
case RIPEMD160:
mBlockSize = 64;
mResultData = new uint32_t[5];
mBlockData = new uint32_t[mBlockSize / 4];
break;
case SHA256:
case SHA256_SHA256:
case SHA256_RIPEMD160:
mBlockSize = 64;
mResultData = new uint32_t[8];
mBlockData = new uint32_t[mBlockSize / 4];
break;
case MURMUR3:
mBlockSize = 4;
mResultData = new uint32_t[1];
mBlockData = new uint32_t[mBlockSize / 4];
break;
case SHA512:
mBlockSize = 128;
mResultData = new uint32_t[16];
mBlockData = new uint32_t[mBlockSize / 4];
break;
default:
mBlockSize = 0;
mResultData = NULL;
mBlockData = NULL;
break;
}
initialize();
}
Digest::~Digest()
{
if(mBlockData != NULL)
delete[] mBlockData;
if(mResultData != NULL)
delete[] mResultData;
}
HMACDigest::HMACDigest(Type pType, InputStream *pKey) : Digest(pType)
{
initialize(pKey);
}
void HMACDigest::initialize(InputStream *pKey)
{
Digest::initialize();
Buffer key;
key.writeStream(pKey, pKey->remaining());
if(key.length() > mBlockSize)
{
// Hash key
writeStream(&key, key.length());
key.clear(); // Clear key data
Digest::getResult(&key); // Read key hash into key
Digest::initialize(); // Reinitialize digest
}
// Pad key to block size
while(key.length() < mBlockSize)
key.writeByte(0);
// Create outer padded key
key.setReadOffset(0);
mOuterPaddedKey.setWriteOffset(0);
while(key.remaining())
mOuterPaddedKey.writeByte(0x5c ^ key.readByte());
// Create inner padded key
Buffer innerPaddedKey;
key.setReadOffset(0);
while(key.remaining())
innerPaddedKey.writeByte(0x36 ^ key.readByte());
// Write inner padded key into digest
innerPaddedKey.setReadOffset(0);
writeStream(&innerPaddedKey, innerPaddedKey.length());
}
void HMACDigest::getResult(RawOutputStream *pOutput)
{
// Get digest result
Buffer firstResult;
Digest::getResult(&firstResult);
// Reinitialize digest
Digest::initialize();
// Write outer padded key into digest
mOuterPaddedKey.setReadOffset(0);
writeStream(&mOuterPaddedKey, mOuterPaddedKey.length());
// Write previous digest result into digest
writeStream(&firstResult, firstResult.length());
// Get the final result
Digest::getResult(pOutput);
}
void Digest::write(const void *pInput, stream_size pSize)
{
mInput.write(pInput, pSize);
mByteCount += pSize;
process();
}
void Digest::initialize(uint32_t pSeed)
{
mByteCount = 0;
mInput.clear();
switch(mType)
{
case CRC32:
mResultData[0] = 0xffffffff;
break;
//case MD5:
// break;
case SHA1:
SHA1::initialize(mResultData);
break;
case RIPEMD160:
RIPEMD160::initialize(mResultData);
break;
case SHA256:
case SHA256_SHA256:
case SHA256_RIPEMD160:
SHA256::initialize(mResultData);
break;
case MURMUR3:
MURMUR3::initialize(*mResultData, pSeed);
break;
case SHA512:
SHA512::initialize(mResultData);
break;
}
}
void Digest::process()
{
switch(mType)
{
case CRC32:
while(mInput.remaining() >= mBlockSize)
*mResultData = (*mResultData >> 8) ^ CRC32::table[(*mResultData & 0xFF) ^ mInput.readByte()];
break;
//case MD5:
// break;
case SHA1:
while(mInput.remaining() >= mBlockSize)
{
mInput.read(mBlockData, mBlockSize);
SHA1::process(mResultData, mBlockData);
}
break;
case RIPEMD160:
while(mInput.remaining() >= mBlockSize)
{
mInput.read(mBlockData, mBlockSize);
RIPEMD160::process(mResultData, mBlockData);
}
break;
case SHA256:
case SHA256_SHA256:
case SHA256_RIPEMD160:
while(mInput.remaining() >= mBlockSize)
{
mInput.read(mBlockData, mBlockSize);
SHA256::process(mResultData, mBlockData);
}
break;
case MURMUR3:
while(mInput.remaining() >= mBlockSize)
{
mInput.read(mBlockData, mBlockSize);
MURMUR3::process(*mResultData, *mBlockData);
}
break;
case SHA512:
while(mInput.remaining() >= mBlockSize)
{
mInput.read(mBlockData, mBlockSize);
SHA512::process(mResultData, mBlockData);
}
break;
}
mInput.flush();
}
unsigned int Digest::getResult()
{
switch(mType)
{
case CRC32:
// Finalize result
*mResultData ^= 0xffffffff;
*mResultData = Endian::convert(*mResultData, Endian::BIG);
return *mResultData;
case MURMUR3:
{
// Get last partial block (must be less than 4 bytes)
unsigned int lastBlockSize = mInput.remaining();
mInput.read(mBlockData, lastBlockSize);
MURMUR3::finish(*mResultData, (uint8_t *)mBlockData, lastBlockSize, mByteCount);
return *mResultData;
}
default:
return 0;
}
}
void Digest::getResult(RawOutputStream *pOutput)
{
switch(mType)
{
case CRC32:
// Finalize result
*mResultData ^= 0xffffffff;
*mResultData = Endian::convert(*mResultData, Endian::BIG);
// Output result
pOutput->write(mResultData, 4);
// Zeroize
*mResultData = 0;
break;
//case MD5:
// break;
case SHA1:
{
// Get last partial block (must be less than 64 bytes)
unsigned int lastBlockSize = mInput.remaining();
mInput.read(mBlockData, lastBlockSize);
SHA1::finish(mResultData, mBlockData, lastBlockSize, mByteCount);
// Output result
pOutput->write(mResultData, 20);
// Zeroize
std::memset(mResultData, 0, 20);
std::memset(mBlockData, 0, mBlockSize);
break;
}
case RIPEMD160:
{
// Get last partial block (must be less than 64 bytes)
unsigned int lastBlockSize = mInput.remaining();
mInput.read(mBlockData, lastBlockSize);
RIPEMD160::finish(mResultData, mBlockData, lastBlockSize, mByteCount);
// Output result
pOutput->write(mResultData, 20);
// Zeroize
std::memset(mResultData, 0, 20);
std::memset(mBlockData, 0, mBlockSize);
break;
}
case SHA256:
{
// Get last partial block (must be less than 64 bytes)
unsigned int lastBlockSize = mInput.remaining();
mInput.read(mBlockData, lastBlockSize);
SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount);
// Output result
pOutput->write(mResultData, 32);
// Zeroize
std::memset(mResultData, 0, 32);
std::memset(mBlockData, 0, mBlockSize);
break;
}
case SHA256_SHA256:
{
// Get last partial block (must be less than 64 bytes)
unsigned int lastBlockSize = mInput.remaining();
mInput.read(mBlockData, lastBlockSize);
SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount);
// Compute SHA256 of result
Digest secondSHA256(SHA256);
secondSHA256.write(mResultData, 32);
Buffer secondSHA256Data(32);
secondSHA256.getResult(&secondSHA256Data);
// Output result
pOutput->writeStream(&secondSHA256Data, 32);
// Zeroize
std::memset(mResultData, 0, 32);
std::memset(mBlockData, 0, mBlockSize);
break;
}
case SHA256_RIPEMD160:
{
// Get last partial block (must be less than 64 bytes)
unsigned int lastBlockSize = mInput.remaining();
mInput.read(mBlockData, lastBlockSize);
SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount);
// Compute SHA256 of result
Digest ripEMD160(RIPEMD160);
ripEMD160.write(mResultData, 32);
Buffer ripEMD160Data(20);
ripEMD160.getResult(&ripEMD160Data);
// Output result
pOutput->writeStream(&ripEMD160Data, 20);
// Zeroize
std::memset(mResultData, 0, 20);
std::memset(mBlockData, 0, mBlockSize);
break;
}
case MURMUR3:
{
// Get last partial block (must be less than 4 bytes)
unsigned int lastBlockSize = mInput.remaining();
mInput.read(mBlockData, lastBlockSize);
MURMUR3::finish(*mResultData, (uint8_t *)mBlockData, lastBlockSize, mByteCount);
// Output result
pOutput->write(mResultData, 4);
// Zeroize
std::memset(mResultData, 0, 4);
std::memset(mBlockData, 0, mBlockSize);
break;
}
case SHA512:
{
// Get last partial block (must be less than 64 bytes)
unsigned int lastBlockSize = mInput.remaining();
mInput.read(mBlockData, lastBlockSize);
SHA512::finish(mResultData, mBlockData, lastBlockSize, mByteCount);
// Output result
pOutput->write(mResultData, 64);
// Zeroize
std::memset(mResultData, 0, 64);
std::memset(mBlockData, 0, mBlockSize);
break;
}
}
}
bool buffersMatch(Buffer &pLeft, Buffer &pRight)
{
if(pLeft.length() != pRight.length())
return false;
while(pLeft.remaining())
if(pLeft.readByte() != pRight.readByte())
return false;
return true;
}
void logResults(const char *pDescription, Buffer &pBuffer)
{
Buffer hex;
pBuffer.setReadOffset(0);
hex.writeAsHex(&pBuffer, pBuffer.length(), true);
char *hexText = new char[hex.length()];
hex.read((uint8_t *)hexText, hex.length());
Log::addFormatted(Log::VERBOSE, NEXTCASH_DIGEST_LOG_NAME, "%s : %s", pDescription, hexText);
delete[] hexText;
}
bool Digest::test()
{
Log::add(NextCash::Log::INFO, NEXTCASH_DIGEST_LOG_NAME,
"------------- Starting Digest Tests -------------");
bool result = true;
Buffer input, correctDigest, resultDigest, hmacKey;
/******************************************************************************************
* Test empty (All confirmed from outside sources)
******************************************************************************************/
input.clear();
/*****************************************************************************************
* CRC32 empty
*****************************************************************************************/
input.setReadOffset(0);
crc32(&input, input.length(), &resultDigest);
correctDigest.writeHex("00000000");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MD5 empty
*****************************************************************************************/
input.setReadOffset(0);
md5(&input, input.length(), &resultDigest);
correctDigest.writeHex("d41d8cd98f00b204e9800998ecf8427e");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA1 empty
*****************************************************************************************/
input.setReadOffset(0);
sha1(&input, input.length(), &resultDigest);
correctDigest.writeHex("da39a3ee5e6b4b0d3255bfef95601890afd80709");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA1 digest empty
*****************************************************************************************/
input.setReadOffset(0);
Digest sha1EmptyDigest(SHA1);
sha1EmptyDigest.writeStream(&input, input.length());
sha1EmptyDigest.getResult(&resultDigest);
correctDigest.writeHex("da39a3ee5e6b4b0d3255bfef95601890afd80709");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 digest empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 digest empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* RIPEMD160 empty
*****************************************************************************************/
input.setReadOffset(0);
ripEMD160(&input, input.length(), &resultDigest);
correctDigest.writeHex("9c1185a5c5e9fc54612808977ee8f548b2258d31");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* RIPEMD160 digest empty
*****************************************************************************************/
input.setReadOffset(0);
Digest ripemd160EmptyDigest(RIPEMD160);
ripemd160EmptyDigest.writeStream(&input, input.length());
ripemd160EmptyDigest.getResult(&resultDigest);
correctDigest.writeHex("9c1185a5c5e9fc54612808977ee8f548b2258d31");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 digest empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 digest empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA256 empty
*****************************************************************************************/
input.setReadOffset(0);
sha256(&input, input.length(), &resultDigest);
correctDigest.writeHex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA256 digest empty
*****************************************************************************************/
input.setReadOffset(0);
Digest sha256EmptyDigest(SHA256);
sha256EmptyDigest.writeStream(&input, input.length());
sha256EmptyDigest.getResult(&resultDigest);
correctDigest.writeHex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 digest empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 digest empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA512 empty
*****************************************************************************************/
input.setReadOffset(0);
sha512(&input, input.length(), &resultDigest);
correctDigest.writeHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* HMAC SHA256 digest empty
*****************************************************************************************/
input.setReadOffset(0);
HMACDigest hmacSHA256EmptyDigest(SHA256, &hmacKey);
hmacSHA256EmptyDigest.writeStream(&input, input.length());
hmacSHA256EmptyDigest.getResult(&resultDigest);
correctDigest.writeHex("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA256 digest empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA256 digest empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA512 digest empty
*****************************************************************************************/
input.setReadOffset(0);
Digest sha512EmptyDigest(SHA512);
sha512EmptyDigest.writeStream(&input, input.length());
sha512EmptyDigest.getResult(&resultDigest);
correctDigest.writeHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 digest empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 digest empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* HMAC SHA512 digest empty
*****************************************************************************************/
input.setReadOffset(0);
HMACDigest hmacSHA512EmptyDigest(SHA512, &hmacKey);
hmacSHA512EmptyDigest.writeStream(&input, input.length());
hmacSHA512EmptyDigest.getResult(&resultDigest);
correctDigest.writeHex("b936cee86c9f87aa5d3c6f2e84cb5a4239a5fe50480a6ec66b70ab5b1f4ac6730c6c515421b327ec1d69402e53dfb49ad7381eb067b338fd7b0cb22247225d47");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 digest empty");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 digest empty");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/******************************************************************************************
* Test febooti.com (All confirmed from outside sources)
******************************************************************************************/
input.clear();
input.writeString("Test vector from febooti.com");
/*****************************************************************************************
* CRC32 febooti.com
*****************************************************************************************/
input.setReadOffset(0);
crc32(&input, input.length(), &resultDigest);
correctDigest.writeHex("0c877f61");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 febooti.com");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 febooti.com");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* CRC32 text febooti.com
*****************************************************************************************/
unsigned int crc32Text = crc32("Test vector from febooti.com");
unsigned int crc32Result = Endian::convert(0x0c877f61, Endian::BIG);
if(crc32Text != crc32Result)
Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 text febooti.com");
else
{
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 text febooti.com : 0x0c877f61 != 0x%08x", crc32Text);
result = false;
}
/*****************************************************************************************
* CRC32 binary febooti.com
*****************************************************************************************/
unsigned int crc32Binary = crc32((uint8_t *)"Test vector from febooti.com", 28);
if(crc32Binary != crc32Result)
Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 binary febooti.com");
else
{
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 binary febooti.com : 0x0c877f61 != 0x%08x", crc32Binary);
result = false;
}
/*****************************************************************************************
* MD5 febooti.com
*****************************************************************************************/
input.setReadOffset(0);
md5(&input, input.length(), &resultDigest);
correctDigest.writeHex("500ab6613c6db7fbd30c62f5ff573d0f");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 febooti.com");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 febooti.com");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA1 febooti.com
*****************************************************************************************/
input.setReadOffset(0);
sha1(&input, input.length(), &resultDigest);
correctDigest.writeHex("a7631795f6d59cd6d14ebd0058a6394a4b93d868");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 febooti.com");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 febooti.com");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* RIPEMD160 febooti.com
*****************************************************************************************/
input.setReadOffset(0);
ripEMD160(&input, input.length(), &resultDigest);
correctDigest.writeHex("4e1ff644ca9f6e86167ccb30ff27e0d84ceb2a61");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 febooti.com");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 febooti.com");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA256 febooti.com
*****************************************************************************************/
input.setReadOffset(0);
sha256(&input, input.length(), &resultDigest);
correctDigest.writeHex("077b18fe29036ada4890bdec192186e10678597a67880290521df70df4bac9ab");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 febooti.com");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 febooti.com");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA512 febooti.com
*****************************************************************************************/
input.setReadOffset(0);
sha512(&input, input.length(), &resultDigest);
correctDigest.writeHex("09fb898bc97319a243a63f6971747f8e102481fb8d5346c55cb44855adc2e0e98f304e552b0db1d4eeba8a5c8779f6a3010f0e1a2beb5b9547a13b6edca11e8a");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 febooti.com");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 febooti.com");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA512 digest febooti.com
*****************************************************************************************/
input.setReadOffset(0);
Digest sha512febootiDigest(SHA512);
sha512febootiDigest.writeStream(&input, input.length());
sha512febootiDigest.getResult(&resultDigest);
correctDigest.writeHex("09fb898bc97319a243a63f6971747f8e102481fb8d5346c55cb44855adc2e0e98f304e552b0db1d4eeba8a5c8779f6a3010f0e1a2beb5b9547a13b6edca11e8a");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 digest febooti.com");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 digest febooti.com");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/******************************************************************************************
* Test quick brown fox (All confirmed from outside sources)
******************************************************************************************/
input.clear();
input.writeString("The quick brown fox jumps over the lazy dog");
/*****************************************************************************************
* CRC32 quick brown fox
*****************************************************************************************/
input.setReadOffset(0);
crc32(&input, input.length(), &resultDigest);
correctDigest.writeHex("414FA339");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 quick brown fox");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 quick brown fox");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MD5 quick brown fox
*****************************************************************************************/
input.setReadOffset(0);
md5(&input, input.length(), &resultDigest);
correctDigest.writeHex("9e107d9d372bb6826bd81d3542a419d6");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 quick brown fox");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 quick brown fox");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA1 quick brown fox
*****************************************************************************************/
input.setReadOffset(0);
sha1(&input, input.length(), &resultDigest);
correctDigest.writeHex("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 quick brown fox");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 quick brown fox");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* RIPEMD160 quick brown fox
*****************************************************************************************/
input.setReadOffset(0);
ripEMD160(&input, input.length(), &resultDigest);
correctDigest.writeHex("37f332f68db77bd9d7edd4969571ad671cf9dd3b");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 quick brown fox");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 quick brown fox");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA256 quick brown fox
*****************************************************************************************/
input.setReadOffset(0);
sha256(&input, input.length(), &resultDigest);
correctDigest.writeHex("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 quick brown fox");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 quick brown fox");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* HMAC SHA256 digest quick brown fox
*****************************************************************************************/
input.setReadOffset(0);
hmacKey.clear();
hmacKey.writeString("key");
HMACDigest hmacSHA256QBFDigest(SHA256, &hmacKey);
hmacSHA256QBFDigest.writeStream(&input, input.length());
hmacSHA256QBFDigest.getResult(&resultDigest);
correctDigest.writeHex("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA256 digest quick brown fox");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA256 digest quick brown fox");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA512 quick brown fox
*****************************************************************************************/
input.setReadOffset(0);
sha512(&input, input.length(), &resultDigest);
correctDigest.writeHex("07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 quick brown fox");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 quick brown fox");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* HMAC SHA512 digest quick brown fox
*****************************************************************************************/
input.setReadOffset(0);
hmacKey.clear();
hmacKey.writeString("key");
HMACDigest hmacSHA512QBFDigest(SHA512, &hmacKey);
hmacSHA512QBFDigest.writeStream(&input, input.length());
hmacSHA512QBFDigest.getResult(&resultDigest);
correctDigest.writeHex("b42af09057bac1e2d41708e48a902e09b5ff7f12ab428a4fe86653c73dd248fb82f948a549f7b791a5b41915ee4d1ec3935357e4e2317250d0372afa2ebeeb3a");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 digest quick brown fox");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 digest quick brown fox");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/******************************************************************************************
* Test random data 1024 (All confirmed from outside sources)
******************************************************************************************/
input.clear();
input.writeHex("9cd248ed860b10bbc7cd5f0ef18f81291a90307c91296dc67d3a1759f02e2a34db020eb9c1f401c1");
input.writeHex("1820349dc9401246bab85810989136420a49830fb96a28e22247ec1073536862e6c2ce82adb93b1d");
input.writeHex("b3193a938dfefe8db8aef7eefb784e6af35191b7bf79dd96da777d7b2423fd49c255839232934344");
input.writeHex("41c94a6e2aa84e926a40ff9e640e224d0241a89565feb539791b2dcb31185b3ce463d638c99db0ed");
input.writeHex("e615dded590af0c89e093d0db3637aac61cd052c776409d992ddfc0249221121909bea8085871db2");
input.writeHex("a00011dc46d159b5ce630efff43117e379d7bb105142f4ef6e3af41ff0284624d16987b7ee6187e7");
input.writeHex("3df4761d2710414f216310b8193c530568ce423b76cc0342ad0ed86a3e7c15530c54ab4022ebaeed");
input.writeHex("df4e7996fec005e2d62b3ec1097af9b29443d45531399490cd763a78d58682fcf3bb483aa7448a44");
input.writeHex("9ac089cf695a9285954751f4c139904d10512c3e1adb00de962f4912f5fd160ade61c7e8ba45c5b9");
input.writeHex("4a763c943bf30249026f1c9eaf9be10f3f47ac2f001f633f5df3774bbcbc6cb85738a0d74778a07e");
input.writeHex("736adfd769c99509d2aad922d49b6b1c67fe886578e95988961e20c64ed6b7e4e080bbda3ce24ce6");
input.writeHex("741c51cacf401cc8b373ed6170d7b70a033f553eaef18d94065f06699d6bcd0bf5d845e09fd364e3");
input.writeHex("98e96d3ed54f78dc5d6200560001a3c0f721ccba58eaf9fde2760e937b820e0c41c161530d1f6b25");
input.writeHex("6b30463fd1dfe3e9d293afd5f278bf21e2b8bfc8860f7c86f4575cd7a922e4d9dbb8857815ede9a7");
input.writeHex("628af97c7ecadf59d385de8f2a3b3d114344fd9429f15a4aabe42c3934347bc039121dd666c6cef7");
input.writeHex("a81822889f394b82458f4016ed947fb86d8ef15b40d2a36b751f983339eeb7d4880554c5feebf6a6");
input.writeHex("59467f9716afc92ad05b41aab06e958f5874d431c836419ed2c595282c6804c600e97ce3929380d9");
input.writeHex("7f2687cc210890f95b3cf428ed66cb4e853505ba380bad5bda6c89b835c711a980ea946279051ea8");
input.writeHex("d12d002a52e40b0b162e7ff1464a9474450980ff3354a04522dc869905573ee0418adbe5938e87f2");
input.writeHex("0c3761960bf64c21de39ff305420a2127de03afdc5d117489271671219ccd538c0944ecd9ea869dc");
input.writeHex("135246b03b5ac5474b8d7c1741f68bbe616048c53ebc49814c757435a0f82c48bee85c339bbfb134");
input.writeHex("d4b64f561ca82ca1413eef619966d1e34bffb2771d069f795682e9559991d6239713fca03975d8fd");
input.writeHex("e0c2fd4cfe37daf274a3298fdfb9637191524505aa608573b819b0271b97a76328130c0ad8b60d3d");
input.writeHex("e53272e3e3b49760bfd3d20e5fc57bc5baa4b070c91f4eedd5e398405ac47a4bfa307747449ce0ad");
input.writeHex("7b9e9e6e1cc3b4bdef0be7b773af02b590626c92e3a85e97e0726ac1f7061e149c550a8d1b17360d");
input.writeHex("b22d56251b4fb0a6bb40595d1001d87d799d8544fdc54dfc");
/*****************************************************************************************
* CRC32 random data 1024
*****************************************************************************************/
input.setReadOffset(0);
crc32(&input, input.length(), &resultDigest);
correctDigest.writeHex("1f483b3f");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* CRC32 digest random data 1024
*****************************************************************************************/
input.setReadOffset(0);
Digest crc32Digest(CRC32);
crc32Digest.writeStream(&input, input.length());
crc32Digest.getResult(&resultDigest);
correctDigest.writeHex("1f483b3f");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 digest random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 digest random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MD5 random data 1024
*****************************************************************************************/
input.setReadOffset(0);
md5(&input, input.length(), &resultDigest);
correctDigest.writeHex("6950a08814ee1e774314c28bce8707b0");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA1 random data 1024
*****************************************************************************************/
input.setReadOffset(0);
sha1(&input, input.length(), &resultDigest);
correctDigest.writeHex("2F7A0D349F1B6ABD7354965E94800BDC3D6463AC");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA1 digest random data 1024
*****************************************************************************************/
input.setReadOffset(0);
Digest sha1RandomDigest(SHA1);
sha1RandomDigest.writeStream(&input, input.length());
sha1RandomDigest.getResult(&resultDigest);
correctDigest.writeHex("2F7A0D349F1B6ABD7354965E94800BDC3D6463AC");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 digest random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 digest random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* RIPEMD160 random data 1024
*****************************************************************************************/
input.setReadOffset(0);
ripEMD160(&input, input.length(), &resultDigest);
correctDigest.writeHex("0dae1c4a362242d2ffa49c26204ed5ac2f88c454");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* RIPEMD160 digest random data 1024
*****************************************************************************************/
input.setReadOffset(0);
Digest ripemd160Digest(RIPEMD160);
ripemd160Digest.writeStream(&input, input.length());
ripemd160Digest.getResult(&resultDigest);
correctDigest.writeHex("0dae1c4a362242d2ffa49c26204ed5ac2f88c454");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 digest random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 digest random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA256 random data 1024
*****************************************************************************************/
input.setReadOffset(0);
sha256(&input, input.length(), &resultDigest);
correctDigest.writeHex("2baef0b3638abc90b17f2895e3cb24b6bbe7ff6ba7c291345102ea4eec785730");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA256 digest random data 1024
*****************************************************************************************/
input.setReadOffset(0);
Digest sha256Digest(SHA256);
sha256Digest.writeStream(&input, input.length());
sha256Digest.getResult(&resultDigest);
correctDigest.writeHex("2baef0b3638abc90b17f2895e3cb24b6bbe7ff6ba7c291345102ea4eec785730");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 digest random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 digest random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA512 random data 1024
*****************************************************************************************/
input.setReadOffset(0);
sha512(&input, input.length(), &resultDigest);
correctDigest.writeHex("8c63c499586f24f3209acad229b043f02eddfc19ec04d41c2f0aeee60b3a95e87297b2de4cfaaaca9a6691bbc5f63a0453fa98b02742da313fa9075ef633a94c");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 random data 1024");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 random data 1024");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* HMAC SHA512 RFC4231 Text Case 4
*****************************************************************************************/
input.clear();
input.writeHex("cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd");
hmacKey.clear();
hmacKey.writeHex("0102030405060708090a0b0c0d0e0f10111213141516171819");
HMACDigest hmacSHA512RFC4231Test4Digest(SHA512);
hmacSHA512RFC4231Test4Digest.initialize(&hmacKey);
hmacSHA512RFC4231Test4Digest.writeStream(&input, input.length());
hmacSHA512RFC4231Test4Digest.getResult(&resultDigest);
correctDigest.writeHex("b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 RFC4231 Test Case 4");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 RFC4231 Test Case 4");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* HMAC SHA512 RFC4231 Text Case 7
*****************************************************************************************/
input.clear();
input.writeHex("5468697320697320612074657374207573696e672061206c6172676572207468616e20626c6f636b2d73697a65206b657920616e642061206c6172676572207468616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565647320746f20626520686173686564206265666f7265206265696e6720757365642062792074686520484d414320616c676f726974686d2e");
hmacKey.clear();
hmacKey.writeHex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
HMACDigest hmacSHA512RFC4231Test7Digest(SHA512);
hmacSHA512RFC4231Test7Digest.initialize(&hmacKey);
hmacSHA512RFC4231Test7Digest.writeStream(&input, input.length());
hmacSHA512RFC4231Test7Digest.getResult(&resultDigest);
correctDigest.writeHex("e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 RFC4231 Test Case 7");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 RFC4231 Test Case 7");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/******************************************************************************************
* Test 56 letters (All confirmed from outside sources)
******************************************************************************************/
input.clear();
input.writeString("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq");
/*****************************************************************************************
* RIPEMD160 56 letters
*****************************************************************************************/
input.setReadOffset(0);
ripEMD160(&input, input.length(), &resultDigest);
correctDigest.writeHex("12a053384a9c0c88e405a06c27dcf49ada62eb2b");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 56 letters");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 56 letters");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/******************************************************************************************
* Test 8 times "1234567890" (All confirmed from outside sources)
******************************************************************************************/
input.clear();
input.writeString("12345678901234567890123456789012345678901234567890123456789012345678901234567890");
/*****************************************************************************************
* RIPEMD160 8 times "1234567890"
*****************************************************************************************/
input.setReadOffset(0);
ripEMD160(&input, input.length(), &resultDigest);
correctDigest.writeHex("9b752e45573d4b39f4dbd3323cab82bf63326bfb");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 8 times \"1234567890\"");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 8 times \"1234567890\"");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/******************************************************************************************
* Test million a (All confirmed from outside sources)
******************************************************************************************/
input.clear();
for(unsigned int i=0;i<1000000;i++)
input.writeByte('a');
/*****************************************************************************************
* RIPEMD160 million a
*****************************************************************************************/
input.setReadOffset(0);
ripEMD160(&input, input.length(), &resultDigest);
correctDigest.writeHex("52783243c1697bdbe16d37f97f68f08325dc1528");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 million a");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 million a");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/******************************************************************************************
* Test random data 150 (All confirmed from outside sources)
******************************************************************************************/
input.clear();
input.writeHex("182d86ed47df1c1673558e3d1ed08dcc7de3a906615589084f6316e71cabd18e7c37451d514d9ede653b03d047345a522ef1c55f27ac8bff3564635116855d862bac06d21f8abb3026746b5c74dd46e9679bd30137bf6b143b67249931ff3f0a3f50426a4479871d15603aa4151ef4b9321762553df9946f5bc194ac4a44e94205d8b0854f1722ea6915770f03bc598c306cabf23878");
/*****************************************************************************************
* RIPEMD160 random data 150
*****************************************************************************************/
input.setReadOffset(0);
ripEMD160(&input, input.length(), &resultDigest);
correctDigest.writeHex("de4c02fe629897e3a2658c042f260a96ccfccac9");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 random data 150");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 random data 150");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/******************************************************************************************
* Test hello
******************************************************************************************/
input.clear();
input.writeString("hello");
/*****************************************************************************************
* SHA256_SHA256 hello
*****************************************************************************************/
input.setReadOffset(0);
Digest doubleSHA256(SHA256_SHA256);
doubleSHA256.writeStream(&input, input.length());
doubleSHA256.getResult(&resultDigest);
correctDigest.writeHex("9595c9df90075148eb06860365df33584b75bff782a510c6cd4883a419833d50");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256_SHA256 hello");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256_SHA256 hello");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SHA256_RIPEMD160 hello
*****************************************************************************************/
input.setReadOffset(0);
Digest sha256RIPEMD160(SHA256_RIPEMD160);
sha256RIPEMD160.writeStream(&input, input.length());
sha256RIPEMD160.getResult(&resultDigest);
correctDigest.writeHex("b6a9c8c230722b7c748331a8b450f05566dc7d0f");
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256_RIPEMD160 hello");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256_RIPEMD160 hello");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* SipHash24
*****************************************************************************************/
uint8_t sipHash24Vectors[64][8] =
{
{ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, },
{ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, },
{ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, },
{ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, },
{ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, },
{ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, },
{ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, },
{ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, },
{ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, },
{ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, },
{ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, },
{ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, },
{ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, },
{ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, },
{ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, },
{ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, },
{ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, },
{ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, },
{ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, },
{ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, },
{ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, },
{ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, },
{ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, },
{ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, },
{ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, },
{ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, },
{ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, },
{ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, },
{ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, },
{ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, },
{ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, },
{ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, },
{ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, },
{ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, },
{ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, },
{ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, },
{ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, },
{ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, },
{ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, },
{ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, },
{ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, },
{ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, },
{ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, },
{ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, },
{ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, },
{ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, },
{ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, },
{ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, },
{ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, },
{ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, },
{ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, },
{ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, },
{ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, },
{ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, },
{ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, },
{ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, },
{ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, },
{ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, },
{ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, },
{ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, },
{ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, },
{ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, },
{ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, },
{ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, }
};
uint64_t key0 = 0x0706050403020100;
uint64_t key1 = 0x0f0e0d0c0b0a0908;
//Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "SipHash-2-4 : Key0 0x%08x%08x, Key1 0x%08x%08x",
// key0 >> 32, key0 & 0xffffffff, key1 >> 32, key1 & 0xffffffff);
uint64_t sipResult;
uint64_t check;
uint8_t *byte;
uint8_t sipHash24Data[64];
bool sipSuccess = true;
for(unsigned int i=0;i<64;++i)
{
sipHash24Data[i] = i;
sipResult = sipHash24(sipHash24Data, i, key0, key1);
check = 0;
byte = sipHash24Vectors[i];
for(unsigned int j=0;j<8;++j)
check |= (uint64_t)*byte++ << (j * 8);
if(sipResult != check)
{
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME,
"Failed SipHash24 %d 0x%08x%08x == 0x%08x%08x", i,
sipResult >> 32, sipResult & 0xffffffff,
check >> 32, check & 0xffffffff);
result = false;
sipSuccess = false;
}
}
if(sipSuccess)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SipHash24 test set");
/*****************************************************************************************
* MurMur3 empty 0
*****************************************************************************************/
input.clear();
Digest murmur3Digest(MURMUR3);
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x00000000);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 empty 1
*****************************************************************************************/
input.clear();
murmur3Digest.initialize(1);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x514E28B7);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty 1");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty 1");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 empty ffffffff
*****************************************************************************************/
input.clear();
murmur3Digest.initialize(0xffffffff);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x81F16F39);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty ffffffff");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty ffffffff");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 ffffffff 0
*****************************************************************************************/
input.clear();
input.writeUnsignedInt(0xffffffff);
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x76293B50);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 ffffffff 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 ffffffff 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 87654321 0
*****************************************************************************************/
input.clear();
input.writeUnsignedInt(0x87654321);
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0xF55B516B);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 87654321 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 87654321 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 87654321 5082EDEE
*****************************************************************************************/
input.clear();
input.writeUnsignedInt(0x87654321);
murmur3Digest.initialize(0x5082EDEE);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x2362F9DE);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 87654321 5082EDEE");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 87654321 5082EDEE");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 214365 0
*****************************************************************************************/
input.clear();
input.writeHex("214365");
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x7E4A8634);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 214365 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 214365 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 2143 0
*****************************************************************************************/
input.clear();
input.writeHex("2143");
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0xA0F7B07A);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 2143 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 2143 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 21 0
*****************************************************************************************/
input.clear();
input.writeHex("21");
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x72661CF4);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 21 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 21 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 00000000 0
*****************************************************************************************/
input.clear();
input.writeHex("00000000");
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x2362F9DE);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 00000000 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 00000000 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 000000 0
*****************************************************************************************/
input.clear();
input.writeHex("000000");
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x85F0B427);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 000000 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 000000 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 0000 0
*****************************************************************************************/
input.clear();
input.writeHex("0000");
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x30F4C306);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 0000 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 0000 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 00 0
*****************************************************************************************/
input.clear();
input.writeHex("00");
murmur3Digest.initialize(0);
murmur3Digest.writeStream(&input, input.length());
murmur3Digest.getResult(&resultDigest);
correctDigest.writeUnsignedInt(0x514E28B7);
if(buffersMatch(correctDigest, resultDigest))
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 00 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 00 0");
logResults("Correct Digest", correctDigest);
logResults("Result Digest ", resultDigest);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 empty 0 direct
*****************************************************************************************/
input.clear();
uint32_t murMur3Result = murMur3(input.begin(), input.length(), 0);
uint32_t murMur3Correct = 0x00000000;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 empty 1 direct
*****************************************************************************************/
input.clear();
murMur3Result = murMur3(input.begin(), input.length(), 1);
murMur3Correct = 0x514E28B7;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty 1");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty 1");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 empty ffffffff direct
*****************************************************************************************/
input.clear();
murMur3Result = murMur3(input.begin(), input.length(), 0xffffffff);
murMur3Correct = 0x81F16F39;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty ffffffff");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty ffffffff");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 ffffffff 0 direct
*****************************************************************************************/
input.clear();
input.writeUnsignedInt(0xffffffff);
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0x76293B50;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct ffffffff 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct ffffffff 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 87654321 0 direct
*****************************************************************************************/
input.clear();
input.writeUnsignedInt(0x87654321);
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0xF55B516B;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 87654321 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 87654321 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 87654321 5082EDEE direct
*****************************************************************************************/
input.clear();
input.writeUnsignedInt(0x87654321);
murMur3Result = murMur3(input.begin(), input.length(), 0x5082EDEE);
murMur3Correct = 0x2362F9DE;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 87654321 5082EDEE");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 87654321 5082EDEE");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 214365 0 direct
*****************************************************************************************/
input.clear();
input.writeHex("214365");
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0x7E4A8634;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 214365 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 214365 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 2143 0 direct
*****************************************************************************************/
input.clear();
input.writeHex("2143");
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0xA0F7B07A;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 2143 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 2143 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 21 0 direct
*****************************************************************************************/
input.clear();
input.writeHex("21");
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0x72661CF4;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 21 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 21 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 00000000 0 direct
*****************************************************************************************/
input.clear();
input.writeHex("00000000");
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0x2362F9DE;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 00000000 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 00000000 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 000000 0 direct
*****************************************************************************************/
input.clear();
input.writeHex("000000");
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0x85F0B427;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 000000 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 000000 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 0000 0 direct
*****************************************************************************************/
input.clear();
input.writeHex("0000");
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0x30F4C306;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 0000 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 0000 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
/*****************************************************************************************
* MurMur3 00 0 direct
*****************************************************************************************/
input.clear();
input.writeHex("00");
murMur3Result = murMur3(input.begin(), input.length(), 0);
murMur3Correct = 0x514E28B7;
if(murMur3Correct == murMur3Result)
Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 00 0");
else
{
Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 00 0");
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x",
murMur3Correct);
Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x",
murMur3Result);
result = false;
}
correctDigest.clear();
resultDigest.clear();
return result;
}
}
| 42.182319 | 331 | 0.508833 | nextcashtech |
81c81d437ad7da06a3aa7bd15d319b9d8f9ebdde | 1,356 | cc | C++ | tests/models/pmx/lstm_test.cc | kuroro-tian/ppl.nn | 7b33cd1fd0660540aec483f299b20094425e7138 | [
"Apache-2.0"
] | 1 | 2022-03-27T07:55:37.000Z | 2022-03-27T07:55:37.000Z | tests/models/pmx/lstm_test.cc | kuroro-tian/ppl.nn | 7b33cd1fd0660540aec483f299b20094425e7138 | [
"Apache-2.0"
] | null | null | null | tests/models/pmx/lstm_test.cc | kuroro-tian/ppl.nn | 7b33cd1fd0660540aec483f299b20094425e7138 | [
"Apache-2.0"
] | null | null | null | #include "pmx_utils.h"
#include "ppl/nn/models/pmx/oputils/onnx/lstm.h"
using namespace std;
using namespace ppl::nn::onnx;
using namespace ppl::nn::pmx::onnx;
TEST_F(PmxTest, test_lstm) {
DEFINE_ARG(LSTMParam, lstm);
lstm_param1.activation_alpha = {0.23f};
lstm_param1.activation_beta = {0.33f};
lstm_param1.activations = {ppl::nn::onnx::LSTMParam::ACT_ELU};
lstm_param1.clip = 0.34;
lstm_param1.direction = ppl::nn::onnx::LSTMParam::DIR_REVERSE;
lstm_param1.hidden_size = 44;
lstm_param1.input_forget = 23;
MAKE_BUFFER(LSTMParam, lstm);
std::vector<float> activation_alpha = lstm_param3.activation_alpha;
std::vector<float> activation_beta = lstm_param3.activation_beta;
std::vector<ppl::nn::onnx::LSTMParam::activation_t> activations = lstm_param3.activations;
float clip = lstm_param3.clip;
ppl::nn::onnx::LSTMParam::direction_t direction = lstm_param3.direction;
int32_t hidden_size = lstm_param3.hidden_size;
int32_t input_forget = lstm_param3.input_forget;
EXPECT_FLOAT_EQ(0.23, activation_alpha[0]);
EXPECT_FLOAT_EQ(0.33, activation_beta[0]);
EXPECT_EQ(ppl::nn::onnx::LSTMParam::ACT_ELU, activations[0]);
EXPECT_FLOAT_EQ(0.34, clip);
EXPECT_EQ(ppl::nn::onnx::LSTMParam::DIR_REVERSE, direction);
EXPECT_EQ(44, hidden_size);
EXPECT_EQ(23, input_forget);
}
| 41.090909 | 94 | 0.730088 | kuroro-tian |
81d59017badc7a971abc038128261e7291e7ae71 | 1,234 | cpp | C++ | src/testing/experiment/test_loop_functions.cpp | freedomcondor/argos3-harry | 10cc040af3d5339538cfd801f0317fa8269429a5 | [
"MIT"
] | 1 | 2021-01-15T21:58:34.000Z | 2021-01-15T21:58:34.000Z | src/testing/experiment/test_loop_functions.cpp | freedomcondor/argos3-harry | 10cc040af3d5339538cfd801f0317fa8269429a5 | [
"MIT"
] | 1 | 2021-02-28T23:45:32.000Z | 2021-02-28T23:45:32.000Z | src/testing/experiment/test_loop_functions.cpp | freedomcondor/argos3-harry | 10cc040af3d5339538cfd801f0317fa8269429a5 | [
"MIT"
] | 7 | 2021-02-26T16:41:06.000Z | 2022-01-19T21:36:31.000Z |
/**
* @file <argos3/testing/experiment/test_loop_functions.cpp>
*
* @author Carlo Pinciroli <[email protected]>
*/
#include "test_loop_functions.h"
#include <argos3/plugins/robots/foot-bot/simulator/footbot_entity.h>
#include <argos3/plugins/simulator/entities/led_entity.h>
/****************************************/
/****************************************/
void CTestLoopFunctions::Init(TConfigurationNode& t_tree) {
LOG << "CTestLoopFunctions init running!\n";
CFootBotEntity& fb = dynamic_cast<CFootBotEntity&>(GetSpace().GetEntity("fb"));
CLEDEntity& cLedA = fb.GetComponent<CLEDEntity>("leds.led[led_2]");
CLEDEntity& cLedB = fb.GetComponent<CLEDEntity>("leds.led[led_3]");
CLEDEntity& cLedC = fb.GetComponent<CLEDEntity>("leds.led[led_4]");
cLedA.SetColor(CColor::GREEN);
cLedB.SetColor(CColor::BLUE);
cLedC.SetColor(CColor::YELLOW);
}
CColor CTestLoopFunctions::GetFloorColor(const CVector2& c_pos_on_floor) {
if(Sign(c_pos_on_floor.GetX()) == Sign(c_pos_on_floor.GetY()))
return CColor::GRAY30;
else
return CColor::GRAY70;
}
/****************************************/
/****************************************/
REGISTER_LOOP_FUNCTIONS(CTestLoopFunctions, "test_lf");
| 33.351351 | 82 | 0.634522 | freedomcondor |
81d5db984932e341f16deda1effa122be9e22a15 | 2,381 | hpp | C++ | src/lib/rendering/synchronization/Fence.hpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | 1 | 2021-08-15T19:20:14.000Z | 2021-08-15T19:20:14.000Z | src/lib/rendering/synchronization/Fence.hpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | 17 | 2021-06-05T12:37:04.000Z | 2021-10-01T10:20:09.000Z | src/lib/rendering/synchronization/Fence.hpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | null | null | null | /* FENCE.hpp
* by Lut99
*
* Created:
* 28/06/2021, 16:57:12
* Last edited:
* 28/06/2021, 16:57:12
* Auto updated?
* Yes
*
* Description:
* Contains a class that wraps a VkFence object.
**/
#ifndef RENDERING_FENCE_HPP
#define RENDERING_FENCE_HPP
#include <vulkan/vulkan.h>
#include "../gpu/GPU.hpp"
namespace Makma3D::Rendering {
/* The Fence class, which wraps a VkFence object and manages its memory. */
class Fence {
public:
/* Channel name for the Fence class. */
static constexpr const char* channel = "Fence";
/* The GPU where the semaphore lives. */
const Rendering::GPU& gpu;
private:
/* The VkFence object we wrap. */
VkFence vk_fence;
/* The flags used to create the fence. */
VkFenceCreateFlags vk_create_flags;
public:
/* Constructor for the Fence class, which takes completely nothing! (except for the GPU where it lives, obviously, and optionally some flags) */
Fence(const Rendering::GPU& gpu, VkFenceCreateFlags create_flags = 0);
/* Copy constructor for the Fence class. */
Fence(const Fence& other);
/* Move constructor for the Fence class. */
Fence(Fence&& other);
/* Destructor for the Fence class. */
~Fence();
/* Blocks the CPU until the Fence is signalled. */
inline void wait() const { vkWaitForFences(this->gpu, 1, &this->vk_fence, true, UINT64_MAX); }
/* Resets the Fence once signalled. */
inline void reset() const { vkResetFences(this->gpu, 1, &this->vk_fence); }
/* Expliticly returns the internal VkFence object. */
inline const VkFence& fence() const { return this->vk_fence; }
/* Implicitly returns the internal VkFence object. */
inline operator VkFence() const { return this->vk_fence; }
/* Copy assignment operator for the Fence class. */
inline Fence& operator=(const Fence& other) { return *this = Fence(other); }
/* Move assignment operator for the Fence class. */
inline Fence& operator=(Fence&& other) { if (this != &other) { swap(*this, other); } return *this; }
/* Swap operator for the Fence class. */
friend void swap(Fence& s1, Fence& s2);
};
/* Swap operator for the Fence class. */
void swap(Fence& f1, Fence& f2);
}
#endif
| 33.069444 | 152 | 0.622848 | Lut99 |
81d99cbe8d4a731f81c7b6a84f788f537ab9d98f | 1,120 | cc | C++ | cpp/solutions/006/solution.cc | StephanBischoff-Digle/dcp | 5e0914386ceee5c1aa94a1b2deb8264c7c8bcc3e | [
"Unlicense"
] | null | null | null | cpp/solutions/006/solution.cc | StephanBischoff-Digle/dcp | 5e0914386ceee5c1aa94a1b2deb8264c7c8bcc3e | [
"Unlicense"
] | null | null | null | cpp/solutions/006/solution.cc | StephanBischoff-Digle/dcp | 5e0914386ceee5c1aa94a1b2deb8264c7c8bcc3e | [
"Unlicense"
] | null | null | null | #include "solution.h"
xor_linked_list::xor_linked_list() : memory_(3), size_{0} {}
void xor_linked_list::add(std::int32_t value) {
if (size_ == 0) {
memory_[0] = {0, value};
size_++;
return;
}
// resize internam memory if necessary
if (size_ == memory_.size() - 1) {
memory_.resize(2 * size_);
}
// find last
std::size_t idx = 0;
std::size_t prev = 0;
std::size_t next;
while ((next = memory_[idx].nxp ^ prev) != 0) {
prev = idx;
idx = next;
}
// "allocate memory"
memory_[idx + 1] = {idx ^ 0, value};
memory_[idx].nxp = prev ^ (idx + 1);
size_++;
}
std::optional<std::int32_t> xor_linked_list::get(std::size_t target) {
if (target >= size_) {
return {};
}
if (target == 0) {
return memory_[0].value;
}
std::size_t idx = 0;
std::size_t prev = 0;
std::size_t next;
while ((next = memory_[idx].nxp ^ prev) != 0) {
prev = idx;
idx = next;
if (idx == target) {
return {memory_[idx].value};
}
}
return {};
}
| 20.740741 | 70 | 0.507143 | StephanBischoff-Digle |
81d9ba16900de52ad218827748fd86f2150626a6 | 639 | cpp | C++ | src/Expression.cpp | bmarchon/LG_H4311 | 8a52272a19c13726b8a72b84147d7be27784deb3 | [
"Apache-2.0"
] | null | null | null | src/Expression.cpp | bmarchon/LG_H4311 | 8a52272a19c13726b8a72b84147d7be27784deb3 | [
"Apache-2.0"
] | null | null | null | src/Expression.cpp | bmarchon/LG_H4311 | 8a52272a19c13726b8a72b84147d7be27784deb3 | [
"Apache-2.0"
] | null | null | null | #include "Expression.h"
Expression::Expression(Expressions typeExp, Symboles type):Symbole(type)
{
this->typeExp=typeExp;
expression = NULL;
}
Expression::Expression():Symbole(type)
{
expression = NULL;
}
Expressions Expression::getExprType()
{
return this->typeExp;
}
Expression::~Expression()
{
//dtor
}
void Expression::afficher()
{
cout << "error : call to Expression::afficher()" << endl;
}
Expression * Expression::getExpression()
{
return this->expression;
}
void Expression::setExpression(Expression *expr)
{
this->expression=expr;
}
string Expression::afficherExprType()
{
return exprTypes[this->typeExp];
}
| 14.860465 | 72 | 0.716745 | bmarchon |
81dc1a3053519a1289dd6bd3195f14443e2fbc58 | 9,754 | cpp | C++ | NOLF/ClientShellDLL/BodyFX.cpp | haekb/nolf1-modernizer | 25bac3d43c40a83b8e90201a70a14ef63b4240e7 | [
"Unlicense"
] | 38 | 2019-09-16T14:46:42.000Z | 2022-03-10T20:28:10.000Z | NOLF/ClientShellDLL/BodyFX.cpp | haekb/nolf1-modernizer | 25bac3d43c40a83b8e90201a70a14ef63b4240e7 | [
"Unlicense"
] | 39 | 2019-08-12T01:35:33.000Z | 2022-02-28T16:48:16.000Z | NOLF/ClientShellDLL/BodyFX.cpp | haekb/nolf1-modernizer | 25bac3d43c40a83b8e90201a70a14ef63b4240e7 | [
"Unlicense"
] | 6 | 2019-09-17T12:49:18.000Z | 2022-03-10T20:28:12.000Z | // ----------------------------------------------------------------------- //
//
// MODULE : BodyFX.cpp
//
// PURPOSE : Body special FX - Implementation
//
// CREATED : 8/24/98
//
// (c) 1998-1999 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "BodyFX.h"
#include "GameClientShell.h"
#include "SFXMsgIds.h"
#include "ClientUtilities.h"
#include "SoundMgr.h"
#include "BaseScaleFX.h"
#include "SurfaceFunctions.h"
extern CGameClientShell* g_pGameClientShell;
extern VarTrack g_vtBigHeadMode;
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::CBodyFX()
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
CBodyFX::CBodyFX()
{
m_fFaderTime = 3.0f;
m_fFaderTimer = 3.0f;
m_hMarker = LTNULL;
m_bHasNodeControl = LTFALSE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::~CBodyFX()
//
// PURPOSE: Destructor
//
// ----------------------------------------------------------------------- //
CBodyFX::~CBodyFX()
{
RemoveMarker();
if ( m_hServerObject )
{
g_pModelLT->RemoveTracker(m_hServerObject, &m_TwitchTracker);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::Init
//
// PURPOSE: Init the Body fx
//
// ----------------------------------------------------------------------- //
LTBOOL CBodyFX::Init(HLOCALOBJ hServObj, HMESSAGEREAD hMessage)
{
if (!CSpecialFX::Init(hServObj, hMessage)) return LTFALSE;
if (!hMessage) return LTFALSE;
BODYCREATESTRUCT bcs;
bcs.hServerObj = hServObj;
bcs.Read(g_pLTClient, hMessage);
return Init(&bcs);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::Init
//
// PURPOSE: Init the Body fx
//
// ----------------------------------------------------------------------- //
LTBOOL CBodyFX::Init(SFXCREATESTRUCT* psfxCreateStruct)
{
if (!CSpecialFX::Init(psfxCreateStruct)) return LTFALSE;
m_bs = *((BODYCREATESTRUCT*)psfxCreateStruct);
g_pModelLT->AddTracker(m_bs.hServerObj, &m_TwitchTracker);
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::CreateObject
//
// PURPOSE: Create the various fx
//
// ----------------------------------------------------------------------- //
LTBOOL CBodyFX::CreateObject(ILTClient* pClientDE)
{
if (!CSpecialFX::CreateObject(pClientDE) || !m_hServerObject) return LTFALSE;
uint32 dwCFlags = m_pClientDE->GetObjectClientFlags(m_hServerObject);
m_pClientDE->SetObjectClientFlags(m_hServerObject, dwCFlags | CF_NOTIFYMODELKEYS | CF_INSIDERADIUS);
// uint32 dwCFlags = m_pClientDE->GetObjectClientFlags(m_hServerObject);
// m_pClientDE->SetObjectClientFlags(m_hServerObject, dwCFlags | CF_NOTIFYMODELKEYS);
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::Update
//
// PURPOSE: Update the fx
//
// ----------------------------------------------------------------------- //
LTBOOL CBodyFX::Update()
{
if (!m_pClientDE || !m_hServerObject || m_bWantRemove) return LTFALSE;
// Only register/deregister once
if (!m_bHasNodeControl && g_vtBigHeadMode.GetFloat()) {
m_bHasNodeControl = LTTRUE;
g_pLTClient->ModelNodeControl(m_hServerObject, CBodyFX::HandleBigHeadModeFn, this);
}
else if(m_bHasNodeControl && !g_vtBigHeadMode.GetFloat()) {
m_bHasNodeControl = LTFALSE;
g_pLTClient->ModelNodeControl(m_hServerObject, LTNULL, LTNULL);
}
switch ( m_bs.eBodyState )
{
case eBodyStateFade:
UpdateFade();
break;
}
if (g_pGameClientShell->GetGameType() != SINGLE && m_bs.nClientId != (uint8)-1)
{
UpdateMarker();
}
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::UpdateFade
//
// PURPOSE: Update the fx
//
// ----------------------------------------------------------------------- //
void CBodyFX::UpdateFade()
{
HLOCALOBJ attachList[20];
uint32 dwListSize = 0;
uint32 dwNumAttach = 0;
g_pLTClient->GetAttachments(m_hServerObject, attachList, 20, &dwListSize, &dwNumAttach);
int nNum = dwNumAttach <= dwListSize ? dwNumAttach : dwListSize;
m_fFaderTime = Max<LTFLOAT>(0.0f, m_fFaderTime - g_pGameClientShell->GetFrameTime());
g_pLTClient->SetObjectColor(m_hServerObject, 1, 1, 1, m_fFaderTime/m_fFaderTimer);
for (int i=0; i < nNum; i++)
{
g_pLTClient->SetObjectColor(attachList[i], 1, 1, 1, m_fFaderTime/m_fFaderTimer);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::OnServerMessage
//
// PURPOSE: Handle any messages from our server object...
//
// ----------------------------------------------------------------------- //
LTBOOL CBodyFX::OnServerMessage(HMESSAGEREAD hMessage)
{
if (!CSpecialFX::OnServerMessage(hMessage)) return LTFALSE;
uint8 nMsgId = g_pLTClient->ReadFromMessageByte(hMessage);
switch(nMsgId)
{
case BFX_FADE_MSG:
{
m_bs.eBodyState = eBodyStateFade;
}
break;
}
return LTTRUE;
}
LTBOOL GroundFilterFn(HOBJECT hObj, void *pUserData)
{
return ( IsMainWorld(hObj) || (OT_WORLDMODEL == g_pLTClient->GetObjectType(hObj)) );
}
void CBodyFX::OnModelKey(HLOCALOBJ hObj, ArgList *pArgs)
{
if (!m_hServerObject || !hObj || !pArgs || !pArgs->argv || pArgs->argc == 0) return;
char* pKey = pArgs->argv[0];
if (!pKey) return;
LTBOOL bSlump = !_stricmp(pKey, "NOISE");
LTBOOL bLand = !_stricmp(pKey, "LAND");
if ( bSlump || bLand )
{
LTVector vPos;
g_pLTClient->GetObjectPos(m_hServerObject, &vPos);
IntersectQuery IQuery;
IntersectInfo IInfo;
IQuery.m_From = vPos;
IQuery.m_To = vPos - LTVector(0,96,0);
IQuery.m_Flags = INTERSECT_OBJECTS | INTERSECT_HPOLY | IGNORE_NONSOLID;
IQuery.m_FilterFn = GroundFilterFn;
SurfaceType eSurface;
if (g_pLTClient->IntersectSegment(&IQuery, &IInfo))
{
if (IInfo.m_hPoly && IInfo.m_hPoly != INVALID_HPOLY)
{
eSurface = (SurfaceType)GetSurfaceType(IInfo.m_hPoly);
}
else if (IInfo.m_hObject) // Get the texture flags from the object...
{
eSurface = (SurfaceType)GetSurfaceType(IInfo.m_hObject);
}
else
{
return;
}
}
else
{
return;
}
// Play the noise
SURFACE* pSurf = g_pSurfaceMgr->GetSurface(eSurface);
_ASSERT(pSurf);
if (!pSurf) return;
if (bSlump && pSurf->szBodyFallSnd[0])
{
g_pClientSoundMgr->PlaySoundFromPos(vPos, pSurf->szBodyFallSnd, pSurf->fBodyFallSndRadius, SOUNDPRIORITY_MISC_LOW);
}
else if (bLand && pSurf->szBodyLedgeFallSnd[0])
{
g_pClientSoundMgr->PlaySoundFromPos(vPos, pSurf->szBodyLedgeFallSnd, pSurf->fBodyLedgeFallSndRadius, SOUNDPRIORITY_MISC_LOW);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::UpdateMarker
//
// PURPOSE: Update the marker fx
//
// ----------------------------------------------------------------------- //
void CBodyFX::UpdateMarker()
{
if (!m_pClientDE || !m_hServerObject) return;
CClientInfoMgr *pClientMgr = g_pInterfaceMgr->GetClientInfoMgr();
if (!pClientMgr) return;
CLIENT_INFO* pLocalInfo = pClientMgr->GetLocalClient();
CLIENT_INFO* pInfo = pClientMgr->GetClientByID(m_bs.nClientId);
if (!pInfo || !pLocalInfo) return;
LTBOOL bSame = (pInfo->team == pLocalInfo->team);
if (bSame)
{
if (m_hMarker)
RemoveMarker();
return;
}
uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hServerObject);
if (!(dwFlags & FLAG_VISIBLE))
{
RemoveMarker();
return;
}
LTVector vU, vR, vF, vTemp, vDims, vPos;
LTRotation rRot;
ILTPhysics* pPhysics = m_pClientDE->Physics();
m_pClientDE->GetObjectPos(m_hServerObject, &vPos);
pPhysics->GetObjectDims(m_hServerObject, &vDims);
vPos.y += (vDims.y + 20.0f);
if (!m_hMarker)
{
CreateMarker(vPos,bSame);
}
if (m_hMarker)
{
m_pClientDE->SetObjectPos(m_hMarker, &vPos);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::CreateMarker
//
// PURPOSE: Create marker special fx
//
// ----------------------------------------------------------------------- //
void CBodyFX::CreateMarker(LTVector & vPos, LTBOOL bSame)
{
if (!m_pClientDE || !g_pGameClientShell || !m_hServerObject) return;
if (!bSame) return;
ObjectCreateStruct createStruct;
INIT_OBJECTCREATESTRUCT(createStruct);
CString str = g_pClientButeMgr->GetSpecialFXAttributeString("TeamSprite");
LTFLOAT fScaleMult = g_pClientButeMgr->GetSpecialFXAttributeFloat("TeamScale");
LTFLOAT fAlpha = g_pClientButeMgr->GetSpecialFXAttributeFloat("TeamAlpha");
LTVector vScale(1.0f,1.0f,1.0f);
VEC_MULSCALAR(vScale, vScale, fScaleMult);
SAFE_STRCPY(createStruct.m_Filename, (char *)(LPCSTR)str);
createStruct.m_ObjectType = OT_SPRITE;
createStruct.m_Flags = FLAG_VISIBLE | FLAG_FOGDISABLE | FLAG_NOLIGHT;
createStruct.m_Pos = vPos;
m_hMarker = m_pClientDE->CreateObject(&createStruct);
if (!m_hMarker) return;
m_pClientDE->SetObjectScale(m_hMarker, &vScale);
LTFLOAT r, g, b, a;
m_pClientDE->GetObjectColor(m_hServerObject, &r, &g, &b, &a);
m_pClientDE->SetObjectColor(m_hObject, r, g, b, (fAlpha * a));
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CBodyFX::RemoveMarker
//
// PURPOSE: Remove the marker fx
//
// ----------------------------------------------------------------------- //
void CBodyFX::RemoveMarker()
{
if (!m_hMarker) return;
g_pLTClient->DeleteObject(m_hMarker);
m_hMarker = LTNULL;
} | 24.693671 | 128 | 0.574841 | haekb |
81dc81bbfec0415572e5d7334486fcc66220c540 | 1,584 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPositiveRatioMeasure.cpp | shelltdf/ifcplusplus | 120ef686c4002c1cc77e3808fe00b8653cfcabd7 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPositiveRatioMeasure.cpp | shelltdf/ifcplusplus | 120ef686c4002c1cc77e3808fe00b8653cfcabd7 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPositiveRatioMeasure.cpp | shelltdf/ifcplusplus | 120ef686c4002c1cc77e3808fe00b8653cfcabd7 | [
"MIT"
] | 1 | 2021-04-26T14:56:09.000Z | 2021-04-26T14:56:09.000Z | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcMeasureValue.h"
#include "ifcpp/IFC4/include/IfcSizeSelect.h"
#include "ifcpp/IFC4/include/IfcPositiveRatioMeasure.h"
// TYPE IfcPositiveRatioMeasure = IfcRatioMeasure;
shared_ptr<BuildingObject> IfcPositiveRatioMeasure::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcPositiveRatioMeasure> copy_self( new IfcPositiveRatioMeasure() );
copy_self->m_value = m_value;
return copy_self;
}
void IfcPositiveRatioMeasure::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCPOSITIVERATIOMEASURE("; }
stream << m_value;
if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcPositiveRatioMeasure::toString() const
{
std::wstringstream strs;
strs << m_value;
return strs.str();
}
shared_ptr<IfcPositiveRatioMeasure> IfcPositiveRatioMeasure::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcPositiveRatioMeasure>(); }
if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcPositiveRatioMeasure>(); }
shared_ptr<IfcPositiveRatioMeasure> type_object( new IfcPositiveRatioMeasure() );
readReal( arg, type_object->m_value );
return type_object;
}
| 38.634146 | 163 | 0.748106 | shelltdf |
81dd0fc1dac78844220e9e9d309f26e5fb3b6c78 | 6,750 | cpp | C++ | Source/AllProjects/Tests2/TestEvents/TestEvents_Scheduled.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Tests2/TestEvents/TestEvents_Scheduled.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/Tests2/TestEvents/TestEvents_Scheduled.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: TestEvents_Scheduled.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 09/21/2009
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the tests for the scheduled events.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $Log$
//
// ---------------------------------------------------------------------------
// Include underlying headers
// ---------------------------------------------------------------------------
#include "TestEvents.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TTest_Scheduled1,TTestFWTest)
// ---------------------------------------------------------------------------
// Local types and constants
// ---------------------------------------------------------------------------
namespace TestEvents_Scheduled
{
// Some faux lat/long values
const tCIDLib::TFloat8 f8Lat = 37.3;
const tCIDLib::TFloat8 f8Long = -121.88;
}
// ---------------------------------------------------------------------------
// CLASS: TTest_BasicActVar
// PREFIX: tfwt
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TTest_Scheduled1: Constructor and Destructor
// ---------------------------------------------------------------------------
TTest_Scheduled1::TTest_Scheduled1() :
TTestFWTest
(
L"Scheduled Events 1", L"Basic tests of scheduled events", 3
)
{
}
TTest_Scheduled1::~TTest_Scheduled1()
{
}
// ---------------------------------------------------------------------------
// TTest_Scheduled1: Public, inherited methods
// ---------------------------------------------------------------------------
tTestFWLib::ETestRes
TTest_Scheduled1::eRunTest( TTextStringOutStream& strmOut
, tCIDLib::TBoolean& bWarning)
{
tTestFWLib::ETestRes eRes = tTestFWLib::ETestRes::Success;
tCIDLib::TCard4 c4Hour;
tCIDLib::TCard4 c4Millis;
tCIDLib::TCard4 c4Min;
tCIDLib::TCard4 c4Sec;
tCIDLib::TCard4 c4Year;
tCIDLib::EMonths eMonth;
tCIDLib::TCard4 c4Day;
// Do a basic one shot test
{
tCIDLib::TEncodedTime enctAt(TTime::enctNowPlusMins(2));
TCQCSchEvent csrcOneShot(L"Test one shot");
csrcOneShot.SetOneShot(enctAt);
if (!csrcOneShot.bIsOneShot())
{
strmOut << TFWCurLn << L"Event did not come back as one shot\n\n";
eRes = tTestFWLib::ETestRes::Failed;
}
if (!bCheckInfo(strmOut, TFWCurLn, csrcOneShot, tCQCKit::ESchTypes::Once, enctAt))
eRes = tTestFWLib::ETestRes::Failed;
// Calculating the next time should do nothing
CalcNext(csrcOneShot);
if (!bCheckInfo(strmOut, TFWCurLn, csrcOneShot, tCQCKit::ESchTypes::Once, enctAt))
eRes = tTestFWLib::ETestRes::Failed;
}
// Do a daily one
{
// Set the start time to now
tCIDLib::TEncodedTime enctStartAt = TTime::enctNow();
TCQCSchEvent csrcDaily(L"Daily event");
csrcDaily.SetScheduled
(
tCQCKit::ESchTypes::Daily
, 0
, 13
, 30
, 0
, enctStartAt
);
// The initial starting time is now, so if the hour/minute is past
// the one we set, then it should run today, else it will be tomorrow.
//
TTime tmNext(enctStartAt);
tCIDLib::TEncodedTime enctTmp;
tmNext.eExpandDetails
(
c4Year
, eMonth
, c4Day
, c4Hour
, c4Min
, c4Sec
, c4Millis
, enctTmp
);
tmNext.FromDetails(c4Year, eMonth, c4Day, 13, 30);
if ((c4Hour > 13) || (c4Hour == 13) && (c4Min > 30))
{
//
// It should run tomorrow. Note that this isn't the best way
// to do this, since if we hit a day where there's a leap
// minute or something, it could fail. But not too much risk
// in reality.
//
tmNext += kCIDLib::enctOneDay;
}
if (!bCheckInfo(strmOut, TFWCurLn, csrcDaily, tCQCKit::ESchTypes::Daily, tmNext.enctTime()))
eRes = tTestFWLib::ETestRes::Failed;
}
// Do a weekly one
{
// Set the start time to now
tCIDLib::TEncodedTime enctStartAt = TTime::enctNow();
TCQCSchEvent csrcWeekly(L"Weekly event");
csrcWeekly.SetScheduled
(
tCQCKit::ESchTypes::Weekly
, 0
, 10
, 30
, 0x7F
, enctStartAt
);
}
return eRes;
}
// ---------------------------------------------------------------------------
// TTest_Scheduled1: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TTest_Scheduled1::bCheckInfo( TTextStringOutStream& strmOut
, const TTFWCurLn& tfwclAt
, const TCQCSchEvent& csrcToCheck
, const tCQCKit::ESchTypes eType
, const tCIDLib::TEncodedTime enctNext)
{
if (csrcToCheck.eType() != eType)
{
strmOut << tfwclAt << L"Wrong schedule type\n\n";
return kCIDLib::False;
}
//
// Currently all times are rounded down to the previous minute, so
// the actual value the caller set and passed in won't match.
//
// Probably we should just stop doing that and let them stagger out
// through the minute to avoid peak activity. So, for now we just
// round it here, so that it can be removed easily if we stop this
// rounding.
//
tCIDLib::TEncodedTime enctActual = enctNext / kCIDLib::enctOneMinute;
enctActual *= kCIDLib::enctOneMinute;
if (csrcToCheck.enctAt() != enctActual)
{
strmOut << tfwclAt << L"Wrong next scheduled time\n\n";
return kCIDLib::False;
}
return kCIDLib::True;
}
//
// Calculate the next time for the passed event, using the faux lat/long
// positions.
//
tCIDLib::TVoid TTest_Scheduled1::CalcNext(TCQCSchEvent& csrcTar)
{
csrcTar.CalcNextTime(TestEvents_Scheduled::f8Lat, TestEvents_Scheduled::f8Long);
}
| 29.220779 | 100 | 0.491259 | MarkStega |
81de8f9990a206bc30adfd35bddc9388d5ec7fdf | 601 | hpp | C++ | include/extractor/guidance/turn_lane_augmentation.hpp | peterkist-tinker/osrm-backend-appveyor-test | 1891d7379c1d524ea6dc5a8d95e93f4023481a07 | [
"BSD-2-Clause"
] | null | null | null | include/extractor/guidance/turn_lane_augmentation.hpp | peterkist-tinker/osrm-backend-appveyor-test | 1891d7379c1d524ea6dc5a8d95e93f4023481a07 | [
"BSD-2-Clause"
] | null | null | null | include/extractor/guidance/turn_lane_augmentation.hpp | peterkist-tinker/osrm-backend-appveyor-test | 1891d7379c1d524ea6dc5a8d95e93f4023481a07 | [
"BSD-2-Clause"
] | null | null | null | #ifndef OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_
#define OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_
#include "extractor/guidance/intersection.hpp"
#include "extractor/guidance/turn_lane_data.hpp"
namespace osrm
{
namespace extractor
{
namespace guidance
{
namespace lanes
{
LaneDataVector handleNoneValueAtSimpleTurn(LaneDataVector lane_data,
const Intersection &intersection);
} // namespace lanes
} // namespace guidance
} // namespace extractor
} // namespace osrm
#endif /* OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_ */
| 24.04 | 77 | 0.777038 | peterkist-tinker |
81defce025f673146fb076b3c67dd6f24fc5d927 | 1,529 | cpp | C++ | atcoder/agc006/D.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | atcoder/agc006/D.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | atcoder/agc006/D.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define N 200020
#define ll long long
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
int a[N];
bool b[N];
int n, sz;
bool check(int x) {
for (int i = 1; i <= sz; ++ i) {
b[i] = a[i] <= x;
}
int rp = 0;
for (int i = n + 1; i <= sz; ++ i) {
if (b[i] == b[i - 1]) {
rp = i - n;
break;
}
}
int lp = 0;
for (int i = n - 1; i; -- i) {
if (b[i] == b[i + 1]) {
lp = n - i;
break;
}
}
if (!rp && !lp) return b[1];
if (!rp) return b[n - lp];
if (!lp) return b[n + rp];
if (rp == lp) return b[n - lp];
// printf("%d %d\n", lp, rp);
if (rp < lp) {
return b[n + rp];
} else {
return b[n - lp];
}
}
int main(int argc, char const *argv[]) {
n = read(); sz = 2 * n - 1;
for (int i = 1; i <= sz; ++ i) {
a[i] = read();
}
int l = 1, r = sz;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) r = mid - 1;
else l = mid + 1;
}
printf("%d\n", r + 1);
return 0;
}
/*
ไบๅ็ญๆก๏ผๅฐๆฏไธชๅฐไบ็ญไบ mid ็้ฝ็ๆ 1๏ผๅ
ถไฝ็ๆ 0ใ
ไธ B ้ขๅๆ ท็ๆๆณ๏ผๆไธคไธช็ธ้ป็ 0 ๆ่
็ธ้ป็ 1๏ผไผไธ็ดๅฒๅฐๆ้กถไธใ
ๅคๆญ็ฆปไธญ็บฟๆ่ฟ็ไธๆ นๆฑๅญๅณๅฏใ
1 6 3 7 4 5 2
1: 1 0 0 0 0 0 0 false
2: 1 0 0 0 0 0 1 false
3: 1 0 1 0 0 0 1 false
4: 1 0 1 0 1 0 1 true
5: 1 0 1 0 1 1 1 true
6: 1 1 1 0 1 1 1 true
7: 1 1 1 1 1 1 1 true
ๅฆๆๆฒกๆ็ธ้ป็ๆฐๅญ๏ผ้ฃไน็ญๆกๅฐฑๆฏ็ฌฌไธไธชๅ
็ด ใ
1
1 0 1
1 0 1 0 1
1 0 1 0 1 0 1
ๅคๆๅบฆ O(nlogn)
*/ | 15.927083 | 61 | 0.456508 | swwind |
81dfaff9617ef04a799d6168fb671e82f45bae41 | 363 | cpp | C++ | RandomNumbersLibrary/RandomNumbers/RandomGeneratorBase.cpp | PiotrGardocki/RandomNumbersLibrary | 4657ea288109381538a041ad765d02104414cd3c | [
"Unlicense"
] | null | null | null | RandomNumbersLibrary/RandomNumbers/RandomGeneratorBase.cpp | PiotrGardocki/RandomNumbersLibrary | 4657ea288109381538a041ad765d02104414cd3c | [
"Unlicense"
] | null | null | null | RandomNumbersLibrary/RandomNumbers/RandomGeneratorBase.cpp | PiotrGardocki/RandomNumbersLibrary | 4657ea288109381538a041ad765d02104414cd3c | [
"Unlicense"
] | null | null | null | #include <chrono>
#include "RandomGeneratorBase.hpp"
namespace
{
long long createSeed()
{
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
return seed;
}
}
thread_local std::mt19937 RandomGeneratorBase::mEngine(static_cast<unsigned int>(createSeed()) );
std::mt19937 & RandomGeneratorBase::getEngine() const
{
return mEngine;
}
| 19.105263 | 97 | 0.738292 | PiotrGardocki |
81e6a655366f5b01affb9add00a1bf2d59ed9c1d | 873 | cpp | C++ | connected_components.cpp | GautamSachdeva/Number_of_connected_components | d2f7cefaf956660f027e05836a075653390f66c3 | [
"MIT"
] | null | null | null | connected_components.cpp | GautamSachdeva/Number_of_connected_components | d2f7cefaf956660f027e05836a075653390f66c3 | [
"MIT"
] | null | null | null | connected_components.cpp | GautamSachdeva/Number_of_connected_components | d2f7cefaf956660f027e05836a075653390f66c3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
using std::vector;
using std::pair;
void depth(vector<vector<int> > &adj ,vector<bool> &visited , int curr_node){
visited[curr_node] = true;
for(int i = 0; i < adj[curr_node].size() ; i++){
int v = adj[curr_node][i];
if(!visited[v])
depth(adj,visited,v);
}
}
int number_of_components(vector<vector<int> > &adj) {
int res = 0;
//write your code here
vector<bool> visited(adj.size(),false);
for(int i = 0 ; i < adj.size() ; i++){
if(!visited[i]){
depth(adj,visited,i);
res++;
}
}
return res;
}
int main() {
size_t n, m;
std::cin >> n >> m;
vector<vector<int> > adj(n, vector<int>());
for (size_t i = 0; i < m; i++) {
int x, y;
std::cin >> x >> y;
adj[x - 1].push_back(y - 1);
adj[y - 1].push_back(x - 1);
}
std::cout << number_of_components(adj);
}
| 20.302326 | 77 | 0.578465 | GautamSachdeva |
81e7e0b37b80a1a8a6534fd7a1f96e58c27d798d | 16,712 | cc | C++ | src/ufo/filters/obsfunctions/CLWRetMW.cc | fmahebert/ufo | 2af9b91433553ca473c72fcd131400a01c3aabdb | [
"Apache-2.0"
] | 4 | 2020-12-04T08:26:06.000Z | 2021-11-20T01:18:47.000Z | src/ufo/filters/obsfunctions/CLWRetMW.cc | fmahebert/ufo | 2af9b91433553ca473c72fcd131400a01c3aabdb | [
"Apache-2.0"
] | 21 | 2020-10-30T08:57:16.000Z | 2021-05-17T15:11:20.000Z | src/ufo/filters/obsfunctions/CLWRetMW.cc | fmahebert/ufo | 2af9b91433553ca473c72fcd131400a01c3aabdb | [
"Apache-2.0"
] | 31 | 2021-06-24T18:07:53.000Z | 2021-10-08T15:40:39.000Z | /*
* (C) Copyright 2019 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ufo/filters/obsfunctions/CLWRetMW.h"
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
#include <vector>
#include "ioda/ObsDataVector.h"
#include "oops/util/IntSetParser.h"
#include "ufo/filters/Variable.h"
#include "ufo/utils/Constants.h"
namespace ufo {
static ObsFunctionMaker<CLWRetMW> makerCLWRetMW_("CLWRetMW");
CLWRetMW::CLWRetMW(const eckit::LocalConfiguration & conf)
: invars_() {
// Initialize options
options_.deserialize(conf);
// Check required parameters
// Get variable group types for CLW retrieval from option
ASSERT(options_.varGroup.value().size() == 1 || options_.varGroup.value().size() == 2);
ASSERT((options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) ||
(options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) ||
(options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none &&
options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none));
if (options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) {
// For AMSUA and ATMS retrievals
// Get channels for CLW retrieval from options
const std::vector<int> channels = {options_.ch238.value().get(), options_.ch314.value().get()};
ASSERT(options_.ch238.value().get() != 0 && options_.ch314.value().get() != 0
&& channels.size() == 2);
// Include list of required data from ObsSpace
for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) {
invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels);
}
invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels);
invars_ += Variable("sensor_zenith_angle@MetaData");
// Include list of required data from GeoVaLs
invars_ += Variable("average_surface_temperature_within_field_of_view@GeoVaLs");
invars_ += Variable("water_area_fraction@GeoVaLs");
invars_ += Variable("surface_temperature_where_sea@GeoVaLs");
} else if (options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) {
// For cloud index like GMI's.
// Get channels for CLW retrieval from options
const std::vector<int> channels = {options_.ch37v.value().get(), options_.ch37h.value().get()};
ASSERT(options_.ch37v.value().get() != 0 && options_.ch37h.value().get() != 0 &&
channels.size() == 2);
// Include list of required data from ObsSpace
for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) {
invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels);
}
invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels);
// Include list of required data from ObsDiag
invars_ += Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels);
// Include list of required data from GeoVaLs
invars_ += Variable("water_area_fraction@GeoVaLs");
} else if (options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none &&
options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none) {
const std::vector<int> channels = {options_.ch18v.value().get(), options_.ch18h.value().get(),
options_.ch36v.value().get(), options_.ch36h.value().get()};
ASSERT(options_.ch18v.value().get() != 0 && options_.ch18h.value().get() != 0 &&
options_.ch36v.value().get() != 0 && options_.ch36h.value().get() != 0 &&
channels.size() == 4);
const std::vector<float> &sys_bias = options_.origbias.value().get();
ASSERT(options_.origbias.value() != boost::none);
// Include list of required data from ObsSpace
for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) {
invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels);
}
invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels);
// Include list of required data from GeoVaLs
invars_ += Variable("water_area_fraction@GeoVaLs");
}
}
// -----------------------------------------------------------------------------
CLWRetMW::~CLWRetMW() {}
// -----------------------------------------------------------------------------
void CLWRetMW::compute(const ObsFilterData & in,
ioda::ObsDataVector<float> & out) const {
// Get required parameters
const std::vector<std::string> &vargrp = options_.varGroup.value();
// Get dimension
const size_t nlocs = in.nlocs();
const size_t ngrps = vargrp.size();
// Get area fraction of each surface type
std::vector<float> water_frac(nlocs);
in.get(Variable("water_area_fraction@GeoVaLs"), water_frac);
// --------------- amsua or atms --------------------------
if (options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) {
const std::vector<int> channels = {options_.ch238.value().get(), options_.ch314.value().get()};
// Get variables from ObsSpace
// Get sensor zenith angle
std::vector<float> szas(nlocs);
in.get(Variable("sensor_zenith_angle@MetaData"), szas);
// Get variables from GeoVaLs
// Get average surface temperature in FOV
std::vector<float> tsavg(nlocs);
in.get(Variable("average_surface_temperature_within_field_of_view@GeoVaLs"), tsavg);
// Calculate retrieved cloud liquid water
std::vector<float> bt238(nlocs), bt314(nlocs);
for (size_t igrp = 0; igrp < ngrps; ++igrp) {
// Get data based on group type
in.get(Variable("brightness_temperature@" + vargrp[igrp], channels)[0], bt238);
in.get(Variable("brightness_temperature@" + vargrp[igrp], channels)[1], bt314);
// Get bias based on group type
if (options_.addBias.value() == vargrp[igrp]) {
std::vector<float> bias238(nlocs), bias314(nlocs);
if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels)[0])) {
in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels)[0],
bias238);
in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels)[1],
bias314);
} else {
bias238.assign(nlocs, 0.0f);
bias314.assign(nlocs, 0.0f);
}
// Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias
// correction
if (options_.addBias.value() == "ObsValue") {
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
bt238[iloc] = bt238[iloc] - bias238[iloc];
bt314[iloc] = bt314[iloc] - bias314[iloc];
}
}
}
// Compute the cloud liquid water
cloudLiquidWater(szas, tsavg, water_frac, bt238, bt314, out[igrp]);
}
// -------------------- GMI ---------------------------
} else if (options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) {
const std::vector<int> channels = {options_.ch37v.value().get(), options_.ch37h.value().get()};
// Indices of data at channeles 37v and 37h in the above array "channels"
const int jch37v = 0;
const int jch37h = 1;
std::vector<float> bt_clr_37v(nlocs), bt_clr_37h(nlocs);
in.get(Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels)
[jch37v], bt_clr_37v);
in.get(Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels)
[jch37h], bt_clr_37h);
// Calculate retrieved cloud liquid water
std::vector<float> bt37v(nlocs), bt37h(nlocs);
for (size_t igrp = 0; igrp < ngrps; ++igrp) {
// Get data based on group type
in.get(Variable("brightness_temperature@" + vargrp[igrp], channels) [jch37v], bt37v);
in.get(Variable("brightness_temperature@" + vargrp[igrp], channels) [jch37h], bt37h);
// Get bias based on group type
if (options_.addBias.value() == vargrp[igrp]) {
std::vector<float> bias37v(nlocs), bias37h(nlocs);
if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels)
[jch37v])) {
in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels)
[jch37v], bias37v);
in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels)
[jch37h], bias37h);
} else {
bias37v.assign(nlocs, 0.0f);
bias37h.assign(nlocs, 0.0f);
}
// Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias
// correction
if (options_.addBias.value() == "ObsValue") {
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
bt37v[iloc] = bt37v[iloc] - bias37v[iloc];
bt37h[iloc] = bt37h[iloc] - bias37h[iloc];
}
}
}
// Compute cloud index
CIret_37v37h_diff(bt_clr_37v, bt_clr_37h, water_frac, bt37v, bt37h, out[igrp]);
}
// -------------------- amsr2 ---------------------------
} else if (options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none &&
options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none) {
const std::vector<int> channels = {options_.ch18v.value().get(), options_.ch18h.value().get(),
options_.ch36v.value().get(), options_.ch36h.value().get()};
const int jch18v = 0;
const int jch18h = 1;
const int jch36v = 2;
const int jch36h = 3;
// systematic bias for channels 1-14.
const std::vector<float> &sys_bias = options_.origbias.value().get();
// Calculate retrieved cloud liquid water
std::vector<float> bt18v(nlocs), bt18h(nlocs), bt36v(nlocs), bt36h(nlocs);
for (size_t igrp = 0; igrp < ngrps; ++igrp) {
// Get data based on group type
const Variable btVar("brightness_temperature@" + vargrp[igrp], channels);
in.get(btVar[jch18v], bt18v);
in.get(btVar[jch18h], bt18h);
in.get(btVar[jch36v], bt36v);
in.get(btVar[jch36h], bt36h);
// Get bias based on group type
if (options_.addBias.value() == vargrp[igrp]) {
std::vector<float> bias18v(nlocs), bias18h(nlocs);
std::vector<float> bias36v(nlocs), bias36h(nlocs);
if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels)
[jch36v])) {
const Variable testBias("brightness_temperature@" + options_.testBias.value(), channels);
in.get(testBias[jch18v], bias18v);
in.get(testBias[jch18h], bias18h);
in.get(testBias[jch36v], bias36v);
in.get(testBias[jch36h], bias36h);
} else {
bias18v.assign(nlocs, 0.0f);
bias18h.assign(nlocs, 0.0f);
bias36v.assign(nlocs, 0.0f);
bias36h.assign(nlocs, 0.0f);
}
// Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias
// correction
if (options_.addBias.value() == "ObsValue") {
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
bt18v[iloc] = bt18v[iloc] - bias18v[iloc];
bt18h[iloc] = bt18h[iloc] - bias18h[iloc];
bt36v[iloc] = bt36v[iloc] - bias36v[iloc];
bt36h[iloc] = bt36h[iloc] - bias36h[iloc];
}
}
}
// correct systematic bias.
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
bt18v[iloc] = bt18v[iloc] - sys_bias[6];
bt18h[iloc] = bt18h[iloc] - sys_bias[7];
bt36v[iloc] = bt36v[iloc] - sys_bias[10];
bt36h[iloc] = bt36h[iloc] - sys_bias[11];
}
// Compute cloud index
clw_retr_amsr2(bt18v, bt18h, bt36v, bt36h, out[igrp]);
}
}
}
// -----------------------------------------------------------------------------
void CLWRetMW::cloudLiquidWater(const std::vector<float> & szas,
const std::vector<float> & tsavg,
const std::vector<float> & water_frac,
const std::vector<float> & bt238,
const std::vector<float> & bt314,
std::vector<float> & out) {
///
/// \brief Retrieve cloud liquid water from AMSU-A 23.8 GHz and 31.4 GHz channels.
///
/// Reference: Grody et al. (2001)
/// Determination of precipitable water and cloud liquid water over oceans from
/// the NOAA 15 advanced microwave sounding unit
///
const float t0c = Constants::t0c;
const float d1 = 0.754, d2 = -2.265;
const float c1 = 8.240, c2 = 2.622, c3 = 1.846;
for (size_t iloc = 0; iloc < water_frac.size(); ++iloc) {
if (water_frac[iloc] >= 0.99) {
float cossza = cos(Constants::deg2rad * szas[iloc]);
float d0 = c1 - (c2 - c3 * cossza) * cossza;
if (tsavg[iloc] > t0c - 1.0 && bt238[iloc] <= 284.0 && bt314[iloc] <= 284.0
&& bt238[iloc] > 0.0 && bt314[iloc] > 0.0) {
out[iloc] = cossza * (d0 + d1 * std::log(285.0 - bt238[iloc])
+ d2 * std::log(285.0 - bt314[iloc]));
out[iloc] = std::max(0.f, out[iloc]);
} else {
out[iloc] = getBadValue();
}
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void CLWRetMW::CIret_37v37h_diff(const std::vector<float> & bt_clr_37v,
const std::vector<float> & bt_clr_37h,
const std::vector<float> & water_frac,
const std::vector<float> & bt37v,
const std::vector<float> & bt37h,
std::vector<float> & out) {
///
/// \brief Retrieve cloud index from GMI 37V and 37H channels.
///
/// GMI cloud index: 1.0 - (Tb_37v - Tb_37h)/(Tb_37v_clr - Tb_37h_clr), in which
/// Tb_37v_clr and Tb_37h_clr for calculated Tb at 37 V and 37H GHz from module values
/// assuming in clear-sky condition. Tb_37v and Tb_37h are Tb observations at 37 V and 37H GHz.
///
for (size_t iloc = 0; iloc < water_frac.size(); ++iloc) {
if (water_frac[iloc] >= 0.99) {
if (bt37h[iloc] <= bt37v[iloc]) {
out[iloc] = 1.0 - (bt37v[iloc] - bt37h[iloc])/(bt_clr_37v[iloc] - bt_clr_37h[iloc]);
out[iloc] = std::max(0.f, out[iloc]);
} else {
out[iloc] = getBadValue();
}
} else {
out[iloc] = getBadValue();
}
}
}
// -----------------------------------------------------------------------------
/// \brief Retrieve AMSR2_GCOM-W1 cloud liquid water.
/// This retrieval function is taken from the subroutine "retrieval_amsr2()" in GSI.
void CLWRetMW::clw_retr_amsr2(const std::vector<float> & bt18v,
const std::vector<float> & bt18h,
const std::vector<float> & bt36v,
const std::vector<float> & bt36h,
std::vector<float> & out) {
float clw;
std::vector<float> pred_var_clw(2);
// intercepts
const float a0_clw = -0.65929;
// regression coefficients
float regr_coeff_clw[3] = {-0.00013, 1.64692, -1.51916};
for (size_t iloc = 0; iloc < bt18v.size(); ++iloc) {
if (bt18v[iloc] <= bt18h[iloc]) {
out[iloc] = getBadValue();
} else if (bt36v[iloc] <= bt36h[iloc]) {
out[iloc] = getBadValue();
} else {
// Calculate predictors
pred_var_clw[0] = log(bt18v[iloc] - bt18h[iloc]);
pred_var_clw[1] = log(bt36v[iloc] - bt36h[iloc]);
clw = a0_clw + bt36h[iloc]*regr_coeff_clw[0];
for (size_t nvar_clw=0; nvar_clw < pred_var_clw.size(); ++nvar_clw) {
clw = clw + (pred_var_clw[nvar_clw] * regr_coeff_clw[nvar_clw+1]);
}
clw = std::max(0.0f, clw);
clw = std::min(6.0f, clw);
out[iloc] = clw;
}
}
}
// -----------------------------------------------------------------------------
const ufo::Variables & CLWRetMW::requiredVariables() const {
return invars_;
}
// -----------------------------------------------------------------------------
} // namespace ufo
| 45.045822 | 99 | 0.57366 | fmahebert |
81e8caa080f0e05f4896cf588c709a8e75e495f4 | 76 | hpp | C++ | examples/example2/user1.hpp | ldrozdz93/cpp-visitor-pattern | 542dd041178be665c94b9364a3595ff7cb60e40a | [
"MIT"
] | 1 | 2022-01-13T07:04:41.000Z | 2022-01-13T07:04:41.000Z | examples/example2/user1.hpp | ldrozdz93/cpp-visitor-pattern | 542dd041178be665c94b9364a3595ff7cb60e40a | [
"MIT"
] | null | null | null | examples/example2/user1.hpp | ldrozdz93/cpp-visitor-pattern | 542dd041178be665c94b9364a3595ff7cb60e40a | [
"MIT"
] | null | null | null | #pragma once
#include "base.hpp"
int user1_value_by_visitation(Base& base); | 19 | 42 | 0.789474 | ldrozdz93 |
81ec746e39c96792fecb45725eb7a543a1cd2e87 | 2,765 | hpp | C++ | lite/fpga/KD/layout.hpp | banbishan/Paddle-Lite | 02517c12c31609f413a1c47a83e25d3fbff07074 | [
"Apache-2.0"
] | 1 | 2019-08-21T05:54:42.000Z | 2019-08-21T05:54:42.000Z | lite/fpga/KD/layout.hpp | banbishan/Paddle-Lite | 02517c12c31609f413a1c47a83e25d3fbff07074 | [
"Apache-2.0"
] | null | null | null | lite/fpga/KD/layout.hpp | banbishan/Paddle-Lite | 02517c12c31609f413a1c47a83e25d3fbff07074 | [
"Apache-2.0"
] | 1 | 2019-10-11T09:34:49.000Z | 2019-10-11T09:34:49.000Z | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <vector>
#include "lite/fpga/KD/alignment.h"
namespace paddle {
namespace zynqmp {
enum LayoutType {
N,
NC,
NCHW,
NHWC,
NHW,
};
class Layout {
public:
virtual int numIndex() = 0;
virtual int channelIndex() { return -1; }
virtual int heightIndex() { return -1; }
virtual int widthIndex() { return -1; }
virtual int alignedElementCount(const std::vector<int>& dims) = 0;
virtual int elementCount(const std::vector<int>& dims) = 0;
};
struct NCHW : Layout {
int numIndex() { return 0; }
int channelIndex() { return 1; }
int heightIndex() { return 2; }
int widthIndex() { return 3; }
int alignedElementCount(const std::vector<int>& dims) {
return dims[0] * dims[2] * align_image(dims[1] * dims[3]);
}
virtual int elementCount(const std::vector<int>& dims) {
return dims[0] * dims[1] * dims[2] * dims[3];
}
};
struct NHWC : Layout {
int numIndex() { return 0; }
int heightIndex() { return 1; }
int widthIndex() { return 2; }
int channelIndex() { return 3; }
int alignedElementCount(const std::vector<int>& dims) {
return dims[0] * dims[1] * align_image(dims[2] * dims[3]);
}
virtual int elementCount(const std::vector<int>& dims) {
return dims[0] * dims[1] * dims[2] * dims[3];
}
};
struct NC : Layout {
int numIndex() { return 0; }
int channelIndex() { return 1; }
int alignedElementCount(const std::vector<int>& dims) {
return dims[0] * dims[1];
}
virtual int elementCount(const std::vector<int>& dims) {
return dims[0] * dims[1];
}
};
struct N : Layout {
int numIndex() { return 0; }
int alignedElementCount(const std::vector<int>& dims) { return dims[0]; }
virtual int elementCount(const std::vector<int>& dims) { return dims[0]; }
};
struct NHW : Layout {
int numIndex() { return 0; }
int heightIndex() { return 1; }
int widthIndex() { return 2; }
int alignedElementCount(const std::vector<int>& dims) {
// TODO(chonwhite) align it;
return dims[0] * dims[1] * dims[2];
}
virtual int elementCount(const std::vector<int>& dims) {
return dims[0] * dims[1] * dims[2];
}
};
} // namespace zynqmp
} // namespace paddle
| 27.65 | 76 | 0.666908 | banbishan |
81f03799cb719d11f4c00ae5c5f60e01313a0903 | 854 | cpp | C++ | August_2020_challange/Day 7.cpp | jv640/LeetCode | af07ebf2f4cc5f28a61f78d952febe10782b0e93 | [
"MIT"
] | null | null | null | August_2020_challange/Day 7.cpp | jv640/LeetCode | af07ebf2f4cc5f28a61f78d952febe10782b0e93 | [
"MIT"
] | null | null | null | August_2020_challange/Day 7.cpp | jv640/LeetCode | af07ebf2f4cc5f28a61f78d952febe10782b0e93 | [
"MIT"
] | null | null | null | /*
Problem : Vertical Order Traversal of a Binary Tree
*/
// Approach make variable x and y and attach them with every node x for horizontal distance and y for vertical distance
// Code
map<int,set<pair<int,int>>> ans;
void pre( TreeNode *root, int horizontal_Level, int vertical_Level ){
if(!root)
return ;
ans[horizontal_Level].insert({vertical_Level,root->val});
pre(root->left,horizontal_Level-1,vertical_Level+1);
pre(root->right,horizontal_Level+1,vertical_Level+1);
}
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
pre(root,0 , 0 );
vector<vector<int>> v;
for( auto e : ans ){
vector<int> c;
for( auto x : e.second )
c.push_back(x.second);
v.push_back(c);
}
return v;
}
| 32.846154 | 121 | 0.59719 | jv640 |
81f1b89a3bced4fa9428e1eab4d8b19028256f04 | 268 | cpp | C++ | 1.cpp | baicaihenxiao/LeetCode-Myself | f88fa5b5e76a913d6d9395d75571c8d7c46d37f5 | [
"MIT"
] | null | null | null | 1.cpp | baicaihenxiao/LeetCode-Myself | f88fa5b5e76a913d6d9395d75571c8d7c46d37f5 | [
"MIT"
] | 6 | 2021-03-31T02:43:24.000Z | 2022-01-04T16:40:26.000Z | 1.cpp | baicaihenxiao/LeetCode-Myself | f88fa5b5e76a913d6d9395d75571c8d7c46d37f5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <stack>
#include <deque>
#include <algorithm>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
| 13.4 | 35 | 0.660448 | baicaihenxiao |
81f22282779ab4d0066af37af146da671c028333 | 312 | hpp | C++ | rmvmath/types/quaternion_double_type.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | rmvmath/types/quaternion_double_type.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | rmvmath/types/quaternion_double_type.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | //
// Created by Vitali Kurlovich on 4/13/16.
//
#ifndef RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP
#define RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP
#include "../quaternion/TQuaternion.hpp"
namespace rmmath {
typedef quaternion::TQuaternion<double> dquat;
}
#endif //RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP
| 19.5 | 50 | 0.801282 | vitali-kurlovich |
81f2a8043fea1e31ec5aca13a1808b6898969c0e | 382 | cpp | C++ | sledge/test/analyze/FN_ptr_arith_bad.cpp | sujin0529/infer | f08a09d6896ac2a22081ead4830eb86c64af8813 | [
"MIT"
] | 2 | 2021-12-17T13:38:34.000Z | 2021-12-17T14:06:53.000Z | sledge/test/analyze/FN_ptr_arith_bad.cpp | sujin0529/infer | f08a09d6896ac2a22081ead4830eb86c64af8813 | [
"MIT"
] | 7 | 2017-12-03T16:09:45.000Z | 2018-01-08T15:15:34.000Z | sledge/test/analyze/FN_ptr_arith_bad.cpp | sujin0529/infer | f08a09d6896ac2a22081ead4830eb86c64af8813 | [
"MIT"
] | 2 | 2020-06-23T00:43:10.000Z | 2022-03-24T06:24:50.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
int
main()
{
auto x = new int[8];
auto y = new int[8];
y[0] = 42;
auto x_ptr = x + 8; // one past the end
if (x_ptr == &y[0]) // valid
*x_ptr = 23; // UB
return y[0];
}
| 20.105263 | 66 | 0.586387 | sujin0529 |
81f84de16b7ddce4b6c0ae26e79c0b2ed543fa4b | 907 | hh | C++ | src/pks/flow/FracturePermModel_Linear.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/pks/flow/FracturePermModel_Linear.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/pks/flow/FracturePermModel_Linear.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
Flow PK
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Konstantin Lipnikov ([email protected])
Linear model for effective permeability in fracutres.
*/
#ifndef AMANZI_FRACTURE_PERM_MODEL_LINEAR_HH_
#define AMANZI_FRACTURE_PERM_MODEL_LINEAR_HH_
#include "Teuchos_ParameterList.hpp"
#include "FracturePermModel.hh"
namespace Amanzi {
namespace Flow {
class FracturePermModel_Linear : public FracturePermModel {
public:
explicit FracturePermModel_Linear(Teuchos::ParameterList& plist) {}
~FracturePermModel_Linear() {};
// required methods from the base class
inline double Permeability(double aperture) { return aperture / 12; }
};
} // namespace Flow
} // namespace Amanzi
#endif
| 24.513514 | 71 | 0.76516 | fmyuan |
3b51973e261c9f2e13c3e999c9cdfd2146978689 | 8,986 | cc | C++ | snapshot/test/test_cpu_context.cc | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | null | null | null | snapshot/test/test_cpu_context.cc | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | null | null | null | snapshot/test/test_cpu_context.cc | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | null | null | null | // Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "snapshot/test/test_cpu_context.h"
#include <string.h>
#include <sys/types.h>
#include <iterator>
namespace crashpad {
namespace test {
namespace {
// This is templatized because the CPUContextX86::Fxsave and
// CPUContextX86_64::Fxsave are nearly identical but have different sizes for
// the members |xmm|, |reserved_4|, and |available|.
template <typename FxsaveType>
void InitializeCPUContextFxsave(FxsaveType* fxsave, uint32_t* seed) {
uint32_t value = *seed;
fxsave->fcw = static_cast<uint16_t>(value++);
fxsave->fsw = static_cast<uint16_t>(value++);
fxsave->ftw = static_cast<uint8_t>(value++);
fxsave->reserved_1 = static_cast<uint8_t>(value++);
fxsave->fop = static_cast<uint16_t>(value++);
fxsave->fpu_ip = value++;
fxsave->fpu_cs = static_cast<uint16_t>(value++);
fxsave->reserved_2 = static_cast<uint16_t>(value++);
fxsave->fpu_dp = value++;
fxsave->fpu_ds = static_cast<uint16_t>(value++);
fxsave->reserved_3 = static_cast<uint16_t>(value++);
fxsave->mxcsr = value++;
fxsave->mxcsr_mask = value++;
for (size_t st_mm_index = 0; st_mm_index < std::size(fxsave->st_mm);
++st_mm_index) {
for (size_t byte = 0; byte < std::size(fxsave->st_mm[st_mm_index].st);
++byte) {
fxsave->st_mm[st_mm_index].st[byte] = static_cast<uint8_t>(value++);
}
for (size_t byte = 0;
byte < std::size(fxsave->st_mm[st_mm_index].st_reserved);
++byte) {
fxsave->st_mm[st_mm_index].st_reserved[byte] =
static_cast<uint8_t>(value);
}
}
for (size_t xmm_index = 0; xmm_index < std::size(fxsave->xmm); ++xmm_index) {
for (size_t byte = 0; byte < std::size(fxsave->xmm[xmm_index]); ++byte) {
fxsave->xmm[xmm_index][byte] = static_cast<uint8_t>(value++);
}
}
for (size_t byte = 0; byte < std::size(fxsave->reserved_4); ++byte) {
fxsave->reserved_4[byte] = static_cast<uint8_t>(value++);
}
for (size_t byte = 0; byte < std::size(fxsave->available); ++byte) {
fxsave->available[byte] = static_cast<uint8_t>(value++);
}
*seed = value;
}
} // namespace
void InitializeCPUContextX86Fxsave(CPUContextX86::Fxsave* fxsave,
uint32_t* seed) {
return InitializeCPUContextFxsave(fxsave, seed);
}
void InitializeCPUContextX86_64Fxsave(CPUContextX86_64::Fxsave* fxsave,
uint32_t* seed) {
return InitializeCPUContextFxsave(fxsave, seed);
}
void InitializeCPUContextX86(CPUContext* context, uint32_t seed) {
context->architecture = kCPUArchitectureX86;
if (seed == 0) {
memset(context->x86, 0, sizeof(*context->x86));
return;
}
uint32_t value = seed;
context->x86->eax = value++;
context->x86->ebx = value++;
context->x86->ecx = value++;
context->x86->edx = value++;
context->x86->edi = value++;
context->x86->esi = value++;
context->x86->ebp = value++;
context->x86->esp = value++;
context->x86->eip = value++;
context->x86->eflags = value++;
context->x86->cs = static_cast<uint16_t>(value++);
context->x86->ds = static_cast<uint16_t>(value++);
context->x86->es = static_cast<uint16_t>(value++);
context->x86->fs = static_cast<uint16_t>(value++);
context->x86->gs = static_cast<uint16_t>(value++);
context->x86->ss = static_cast<uint16_t>(value++);
InitializeCPUContextX86Fxsave(&context->x86->fxsave, &value);
context->x86->dr0 = value++;
context->x86->dr1 = value++;
context->x86->dr2 = value++;
context->x86->dr3 = value++;
context->x86->dr4 = value++;
context->x86->dr5 = value++;
context->x86->dr6 = value++;
context->x86->dr7 = value++;
}
void InitializeCPUContextX86_64(CPUContext* context, uint32_t seed) {
context->architecture = kCPUArchitectureX86_64;
if (seed == 0) {
memset(context->x86_64, 0, sizeof(*context->x86_64));
return;
}
uint32_t value = seed;
context->x86_64->rax = value++;
context->x86_64->rbx = value++;
context->x86_64->rcx = value++;
context->x86_64->rdx = value++;
context->x86_64->rdi = value++;
context->x86_64->rsi = value++;
context->x86_64->rbp = value++;
context->x86_64->rsp = value++;
context->x86_64->r8 = value++;
context->x86_64->r9 = value++;
context->x86_64->r10 = value++;
context->x86_64->r11 = value++;
context->x86_64->r12 = value++;
context->x86_64->r13 = value++;
context->x86_64->r14 = value++;
context->x86_64->r15 = value++;
context->x86_64->rip = value++;
context->x86_64->rflags = value++;
context->x86_64->cs = static_cast<uint16_t>(value++);
context->x86_64->fs = static_cast<uint16_t>(value++);
context->x86_64->gs = static_cast<uint16_t>(value++);
InitializeCPUContextX86_64Fxsave(&context->x86_64->fxsave, &value);
context->x86_64->dr0 = value++;
context->x86_64->dr1 = value++;
context->x86_64->dr2 = value++;
context->x86_64->dr3 = value++;
context->x86_64->dr4 = value++;
context->x86_64->dr5 = value++;
context->x86_64->dr6 = value++;
context->x86_64->dr7 = value++;
// Make sure this is sensible. When supplied the size/state come from the OS.
memset(&context->x86_64->xstate, 0, sizeof(context->x86_64->xstate));
}
void InitializeCPUContextARM(CPUContext* context, uint32_t seed) {
context->architecture = kCPUArchitectureARM;
CPUContextARM* arm = context->arm;
if (seed == 0) {
memset(arm, 0, sizeof(*arm));
return;
}
uint32_t value = seed;
for (size_t index = 0; index < std::size(arm->regs); ++index) {
arm->regs[index] = value++;
}
arm->fp = value++;
arm->ip = value++;
arm->ip = value++;
arm->sp = value++;
arm->lr = value++;
arm->pc = value++;
arm->cpsr = value++;
for (size_t index = 0; index < std::size(arm->vfp_regs.vfp); ++index) {
arm->vfp_regs.vfp[index] = value++;
}
arm->vfp_regs.fpscr = value++;
arm->have_fpa_regs = false;
arm->have_vfp_regs = true;
}
void InitializeCPUContextARM64(CPUContext* context, uint32_t seed) {
context->architecture = kCPUArchitectureARM64;
CPUContextARM64* arm64 = context->arm64;
if (seed == 0) {
memset(arm64, 0, sizeof(*arm64));
return;
}
uint32_t value = seed;
for (size_t index = 0; index < std::size(arm64->regs); ++index) {
arm64->regs[index] = value++;
}
arm64->sp = value++;
arm64->pc = value++;
arm64->spsr = value++;
for (size_t index = 0; index < std::size(arm64->fpsimd); ++index) {
arm64->fpsimd[index].lo = value++;
arm64->fpsimd[index].hi = value++;
}
arm64->fpsr = value++;
arm64->fpcr = value++;
}
void InitializeCPUContextMIPS(CPUContext* context, uint32_t seed) {
context->architecture = kCPUArchitectureMIPSEL;
CPUContextMIPS* mipsel = context->mipsel;
if (seed == 0) {
memset(mipsel, 0, sizeof(*mipsel));
return;
}
uint32_t value = seed;
for (size_t index = 0; index < std::size(mipsel->regs); ++index) {
mipsel->regs[index] = value++;
}
mipsel->mdlo = value++;
mipsel->mdhi = value++;
mipsel->cp0_epc = value++;
mipsel->cp0_badvaddr = value++;
mipsel->cp0_status = value++;
mipsel->cp0_cause = value++;
for (size_t index = 0; index < std::size(mipsel->fpregs.fregs); ++index) {
mipsel->fpregs.fregs[index]._fp_fregs = static_cast<float>(value++);
}
mipsel->fpcsr = value++;
mipsel->fir = value++;
for (size_t index = 0; index < 3; ++index) {
mipsel->hi[index] = value++;
mipsel->lo[index] = value++;
}
mipsel->dsp_control = value++;
}
void InitializeCPUContextMIPS64(CPUContext* context, uint32_t seed) {
context->architecture = kCPUArchitectureMIPS64EL;
CPUContextMIPS64* mips64 = context->mips64;
if (seed == 0) {
memset(mips64, 0, sizeof(*mips64));
return;
}
uint64_t value = seed;
for (size_t index = 0; index < std::size(mips64->regs); ++index) {
mips64->regs[index] = value++;
}
mips64->mdlo = value++;
mips64->mdhi = value++;
mips64->cp0_epc = value++;
mips64->cp0_badvaddr = value++;
mips64->cp0_status = value++;
mips64->cp0_cause = value++;
for (size_t index = 0; index < std::size(mips64->fpregs.dregs); ++index) {
mips64->fpregs.dregs[index] = static_cast<double>(value++);
}
mips64->fpcsr = value++;
mips64->fir = value++;
for (size_t index = 0; index < 3; ++index) {
mips64->hi[index] = value++;
mips64->lo[index] = value++;
}
mips64->dsp_control = value++;
}
} // namespace test
} // namespace crashpad
| 29.953333 | 79 | 0.649232 | venge-vimeo |
3b536e10d490f9a00b5ca1787c108c2a3f088e25 | 1,191 | cpp | C++ | competitive_programming/programming_contests/uri/motoboy.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 205 | 2018-12-01T17:49:49.000Z | 2021-12-22T07:02:27.000Z | competitive_programming/programming_contests/uri/motoboy.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 2 | 2020-01-01T16:34:29.000Z | 2020-04-26T19:11:13.000Z | competitive_programming/programming_contests/uri/motoboy.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 50 | 2018-11-28T20:51:36.000Z | 2021-11-29T04:08:25.000Z | // https://www.urionlinejudge.com.br/judge/pt/problems/view/1286
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int max(int a, int b) {
return a > b? a : b;
}
struct Obj {
int time, pizza;
};
bool sortByPizza(Obj obj1, Obj obj2) {
if (obj1.pizza < obj2.pizza) return true;
else if (obj1.pizza > obj2.pizza) return false;
else return obj1.time < obj2.time;
}
int main() {
int N, P, time, pizza;
while (cin >> N && N) {
vector<Obj> objects;
cin >> P;
for (int i = 0; i < N; i++) {
cin >> time >> pizza;
Obj object;
object.time = time;
object.pizza = pizza;
objects.push_back(object);
}
sort(objects.begin(), objects.end(), sortByPizza);
int dp[N][P+1];
for (int i = 0; i <= P; i++) {
if (objects[0].pizza <= i) dp[0][i] = objects[0].time;
else dp[0][i] = 0;
}
for (int i = 1; i < N; i++) {
for (int j = 0; j < P; j++) {
if (j - objects[i].pizza >= 0) dp[i][j] = max(dp[i-1][j - objects[i].pizza] + objects[i].time, dp[i-1][j]);
else dp[i][j] = dp[i-1][j];
}
}
cout << dp[N-1][P-1] << " min."<< endl;
}
return 0;
}
| 20.186441 | 115 | 0.525609 | LeandroTk |
3b5925b76ac1fcfbc1cf4036da4a15deda5565f1 | 3,196 | hpp | C++ | modules/scene_manager/include/urdf/visibility_control.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | modules/scene_manager/include/urdf/visibility_control.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 3 | 2019-11-14T12:20:06.000Z | 2020-08-07T13:51:10.000Z | modules/scene_manager/include/urdf/visibility_control.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Open Source Robotics Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder 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.
*********************************************************************/
/* This header must be included by all urdf headers which declare symbols
* which are defined in the urdf library. When not building the urdf
* library, i.e. when using the headers in other package's code, the contents
* of this header change the visibility of certain symbols which the urdf
* library cannot have, but the consuming code must have inorder to link.
*/
#ifndef URDF__VISIBILITY_CONTROL_HPP_
#define URDF__VISIBILITY_CONTROL_HPP_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define URDF_EXPORT __attribute__ ((dllexport))
#define URDF_IMPORT __attribute__ ((dllimport))
#else
#define URDF_EXPORT __declspec(dllexport)
#define URDF_IMPORT __declspec(dllimport)
#endif
#ifdef URDF_BUILDING_LIBRARY
#define URDF_PUBLIC URDF_EXPORT
#else
#define URDF_PUBLIC URDF_IMPORT
#endif
#define URDF_PUBLIC_TYPE URDF_PUBLIC
#define URDF_LOCAL
#else
#define URDF_EXPORT __attribute__ ((visibility("default")))
#define URDF_IMPORT
#if __GNUC__ >= 4
#define URDF_PUBLIC __attribute__ ((visibility("default")))
#define URDF_LOCAL __attribute__ ((visibility("hidden")))
#else
#define URDF_PUBLIC
#define URDF_LOCAL
#endif
#define URDF_PUBLIC_TYPE
#endif
#endif // URDF__VISIBILITY_CONTROL_HPP_
| 41.506494 | 79 | 0.727472 | Omnirobotic |
3b5966ae0e3db24afa6799df4c5b4dc80b53692c | 240 | cpp | C++ | list1010.cpp | zhangqiangoffice/Explain-C | d804978556ea3000f1718126765606e43223925e | [
"Apache-2.0"
] | null | null | null | list1010.cpp | zhangqiangoffice/Explain-C | d804978556ea3000f1718126765606e43223925e | [
"Apache-2.0"
] | null | null | null | list1010.cpp | zhangqiangoffice/Explain-C | d804978556ea3000f1718126765606e43223925e | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
int main(void) {
int i;
int vc[5] = {10, 20, 30, 40, 50};
int *ptr = &vc[0];
for (i = 0; i < 5; i++)
printf("vc[%d] = %d ptr[%d] = %d *(ptr + %d) = %d\n",
i, vc[i], i, ptr[i], i, *(ptr + i));
return (0);
} | 20 | 57 | 0.429167 | zhangqiangoffice |
3b5dfce7bba25ebda8010d0f04f5f660e7627608 | 892 | cpp | C++ | qprogressbar_hook_c.cpp | mariuszmaximus/qt5pas-aarch64-linux-gnu | c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b | [
"Apache-2.0"
] | null | null | null | qprogressbar_hook_c.cpp | mariuszmaximus/qt5pas-aarch64-linux-gnu | c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b | [
"Apache-2.0"
] | null | null | null | qprogressbar_hook_c.cpp | mariuszmaximus/qt5pas-aarch64-linux-gnu | c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b | [
"Apache-2.0"
] | null | null | null | //******************************************************************************
// Copyright (c) 2005-2013 by Jan Van hijfte
//
// See the included file COPYING.TXT for details about the copyright.
//
// 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.
//******************************************************************************
#include "qprogressbar_hook_c.h"
QProgressBar_hookH QProgressBar_hook_Create(QObjectH handle)
{
return (QProgressBar_hookH) new QProgressBar_hook((QObject*)handle);
}
void QProgressBar_hook_Destroy(QProgressBar_hookH handle)
{
delete (QProgressBar_hook *)handle;
}
void QProgressBar_hook_hook_valueChanged(QProgressBar_hookH handle, QHookH hook)
{
((QProgressBar_hook *)handle)->hook_valueChanged(hook);
}
| 30.758621 | 80 | 0.643498 | mariuszmaximus |
3b5e19002f51f8095c627fcfb44c89a83d29aae5 | 15,875 | cpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/common/LoginWidget.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/common/LoginWidget.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/src/common/LoginWidget.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | /**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* @attention
*
* Copyright (c) 2018 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
#include <gui/common/LoginWidget.hpp>
#include <touchgfx/Color.hpp>
#include <touchgfx/hal/Types.hpp>
#include <texts/TextKeysAndLanguages.hpp>
#include <BitmapDatabase.hpp>
LoginWidget::LoginWidget() :
Container(),
patternStarted(false),
solutionFailed(false),
success(false),
tracing(false),
solutionMinLength(0),
failedAttempts(0),
maxAllowedAttempts(0),
tickCounter(0),
completedEdges(0),
animationEndedCallback(this, &LoginWidget::animationEnded)
{
setTouchable(true);
//default solution
solution.add(0);
solution.add(1);
solution.add(2);
solution.add(3);
solutionMinLength = solution.size();
background.setBitmap(Bitmap(BITMAP_HOME_LOGIN_BACKGROUND_ID));
background.setXY(0, 0);
add(background);
setWidth(background.getWidth());
setHeight(background.getHeight());
//Set up canvas
myColorPainter.setColor(Color::getColorFrom24BitRGB(51, 189, 253));
//Add header and banner
headerTxt.setTypedText(TypedText(T_LOGIN_HEADLINE));
headerTxt.setPosition(0, 20, getWidth(), 50);
headerTxt.setColor(Color::getColorFrom24BitRGB(0xff, 0xff, 0xff));
add(headerTxt);
bannerTxt.setPosition(0, getHeight() - 50, getWidth(), 50);
bannerTxt.setColor(Color::getColorFrom24BitRGB(255, 0, 0));
bannerTxt.setVisible(false);
add(bannerTxt);
reset();
}
void LoginWidget::handleDragEvent(const touchgfx::DragEvent &evt)
{
// Pattern cannot be started if solution failed
if ( (patternStarted && !solutionFailed && !success))
{
line[completedEdges].updateEnd(evt.getNewX(), evt.getNewY());
if (!line[completedEdges].isVisible())
{
line[completedEdges].setVisible(true);
}
//If no elements in input, that means we started away from a marker
for (int i = 0; i < NR_OF_MARKERS; i++)
{
if (hitBoxes[i].getRect().intersect(evt.getNewX(), evt.getNewY()) && !input.contains(i))
{
//Draw additional lines along diagonals and
if (input.size() >= 1)
{
uint8_t prevVal = input[input.size() - 1];
if ((i == 0 || i == 2) && (prevVal == 0 || prevVal == 2))
{
activateNode(1, true);
}
if ((i == 0 || i == 6) && (prevVal == 0 || prevVal == 6))
{
activateNode(3, true);
}
if ((i == 2 || i == 8) && (prevVal == 2 || prevVal == 8))
{
activateNode(5, true);
}
if ((i == 6 || i == 8) && (prevVal == 6 || prevVal == 8))
{
activateNode(7, true);
}
//Activation of skipped contact
if (((i == 3 || i == 5) && (prevVal == 3 || prevVal == 5)) ||
((i == 0 || i == 8) && (prevVal == 0 || prevVal == 8)) ||
((i == 1 || i == 7) && (prevVal == 1 || prevVal == 7)) ||
((i == 2 || i == 6) && (prevVal == 6 || prevVal == 2))
)
{
activateNode(4, true);
}
//activate
activateNode(i);
}
}
}
}
}
void LoginWidget::handleClickEvent(const touchgfx::ClickEvent &evt)
{
//todo: If moving success to activateSingle() RELEASED will never contain a valid solution
if (evt.getType() == touchgfx::ClickEvent::RELEASED && !success && !tracing)
{
if (input.size() > 0)
{
if (input.size() < MIN_ACCEPTED_INPUT_SIZE)
{
//CANCEL CURRENT LINE IF NOT CONNECTED
//completed edges is off by one, so we can use it for a comparison
if (input.size() == completedEdges)
{
line[completedEdges].setVisible(false);
line[completedEdges].invalidate();
}
//solution failed (too short)
solutionFailed = true;
touchgfx::Application::getInstance()->registerTimerWidget(this);
showPatternTooSmallBanner();
return;
}
else
{
processAnswer();
if (!success)
{
//CANCEL CURRENT LINE IF NOT CONNECTED - completed edges is off by one, so we can use it for a comparison
if (input.size() == completedEdges)
{
line[completedEdges].setVisible(false);
}
solutionFailed = true;
failedAttempts++;
//Show failure banner and begin fail timer
showSolutionFailureBanner();
touchgfx::Application::getInstance()->registerTimerWidget(this);
return;
}
}
}
}
else if (evt.getType() == touchgfx::ClickEvent::PRESSED && (!solutionFailed && !success && !tracing)/* || misclick*/)
{
//Begin tracking
for (int i = 0; i < NR_OF_MARKERS; i++)
{
if (hitBoxes[i].getRect().intersect(evt.getX(), evt.getY()) && !input.contains(i)) //we havent' already been there: we never will have, since we either failed (clear) or continued (change screen)
{
//begin first line
line[0].updateStart((hitBoxes[i].getX() + hitBoxes[i].getWidth() / 2), (hitBoxes[i].getY() + hitBoxes[i].getHeight() / 2));
line[0].updateEnd((hitBoxes[i].getX() + hitBoxes[i].getWidth() / 2), (hitBoxes[i].getY() + hitBoxes[i].getHeight() / 2));
line[0].setVisible(true);
//activate
activateNode(i);
patternStarted = true;
}
}
}
}
void LoginWidget::reset()
{
for (int i = 0; i < NR_OF_MARKERS; i++)
{
hitBoxes[i].setColor(touchgfx::Color::getColorFrom24BitRGB(255, 0, 0));
//clear lines
line[i].setVisible(false);
line[i].setAlpha(255);
//reset animations
images[i].stopAnimation();
images[i].setAlpha(255);
}
myColorPainter.setColor(touchgfx::Color::getColorFrom24BitRGB(51, 189, 253));
bannerTxt.setColor(Color::getColorFrom24BitRGB(255, 0, 0));
bannerTxt.setVisible(false);
bannerTxt.invalidate();
//reset stuff
input.clear();
completedEdges = 0;
patternStarted = false;
solutionFailed = false;
success = false;
tracing = false;
invalidate();
}
void LoginWidget::activateNode(uint8_t id, bool completeNext) //should be able to start a new line
{
//Only process solution if completeNext == false.
if (!input.contains(id))
{
hitBoxes[id].setColor(touchgfx::Color::getColorFrom24BitRGB(0, 255, 0)); //todo: invis, so color is unused
hitBoxes[id].invalidate();
images[id].startAnimation(false, true, false);
images[id].invalidate();
if (tracing)
{
images[id].setAlpha(175);
}
//Fixate line - Must be gray when starting the next line
myColorPainter.setColor(touchgfx::Color::getColorFrom24BitRGB(51, 189, 253));
line[completedEdges].updateEnd((hitBoxes[id].getX() + hitBoxes[id].getWidth() / 2), (hitBoxes[id].getY() + hitBoxes[id].getHeight() / 2));
line[completedEdges].invalidate();
input.add(id);
//Inspect if solution correct only if we're not filling out missing dots.
if (!completeNext && !tracing)
{
processAnswer();
if (success)
{
return;
}
}
//begin next line (last possible activation will never be a skip)
if (completedEdges < NR_OF_MARKERS - 1)
{
completedEdges++;
//Fix start of next line to this
myColorPainter.setColor(touchgfx::Color::getColorFrom24BitRGB(51, 189, 253));
line[completedEdges].updateStart((hitBoxes[id].getX() + hitBoxes[id].getWidth() / 2), (hitBoxes[id].getY() + hitBoxes[id].getHeight() / 2));
if (completeNext) /*complete missing dot instantly*/
{
//If filling in missingdots, also fill in the missing line starting from end of previous
line[completedEdges].updateEnd(hitBoxes[input[input.size() - 1]].getX(), hitBoxes[input[input.size() - 1]].getY()); //? this should give wrong result visually
line[completedEdges].setVisible(true);
}
}
else
{
//No edges left to complete, force a release? or move the code from release so that we can call it manually.
patternStarted = false;
}
}
}
void LoginWidget::handleTickEvent()
{
if (!tracing && (solutionFailed))
{
tickCounter++;
if (tickCounter % BANNER_DISPLAY_TIME == 0)
{
//reset banner if we want to have another go (success = end of the road)
//If we want a delay before sending a message to user (view), send callback from here. Make this configurable.
//callback win. Move this to handleTicke if we need to wait a while
if (failureCallback && failureCallback->isValid())
{
failureCallback->execute();
}
// if (!success)
// {
// reset(); //prolly don't need to reset if we're not staying on screen?
// }
resetTimer();
}
}
else if (tracing)
{
tickCounter++;
if (tickCounter % TRACE_DISPLAY_TIME == 0)
{
reset();
resetTimer();
}
}
}
void LoginWidget::setSolution(touchgfx::Vector<uint8_t, 9> solution_)
{
for (int i = 0; i < solution_.size(); i++)
{
//add method to identify uniqueness
uint8_t temp = solution_[i];
for (int j = i + 1; j < solution_.size(); j++)
{
if (temp == solution_[j])
{
assert(false && "Solution must be unique");
}
}
}
//Set solution and update length.
solution = solution_;
solutionMinLength = solution.size();
}
void LoginWidget::showSolutionFailureBanner()
{
updateBannerText(T_LOGIN_SOLUTION_INCORRECT);
}
void LoginWidget::showPatternTooSmallBanner()
{
updateBannerText(T_LOGIN_PATTERN_TOO_SHORT);
}
void LoginWidget::showHintBanner()
{
updateBannerText(T_LOGIN_HINT);
}
void LoginWidget::showSolutionSuccessBanner()
{
bannerTxt.setColor(Color::getColorFrom24BitRGB(51, 189, 253));
updateBannerText(T_LOGIN_SOLUTION_CORRECT);
}
void LoginWidget::setBitmapsAndHitBoxes(BitmapId begin, BitmapId end, uint16_t hitboxWidth, uint16_t hitboxHeight)
{
uint8_t index = 0;
for (int i = 0; i < NR_OF_MARKERS / 3; i++)
{
for (int j = 0; j < NR_OF_MARKERS / 3; j++)
{
hitBoxes[index].setPosition(CANVAS_X_BEGIN + j * DISTANCE_BETWEEN_MARKERS, CANVAS_Y_BEGIN + i * DISTANCE_BETWEEN_MARKERS, hitboxWidth, hitboxHeight);
add(hitBoxes[index]);
hitBoxes[index].setVisible(false);
index++;
}
}
//Hitbox setup. The pos for these should be based on the position of the images. And if the hit boxes are larger then the images...
index = 0;
for (int i = 0; i < NR_OF_MARKERS / 3; i++)
{
for (int j = 0; j < NR_OF_MARKERS / 3; j++)
{
images[index].setBitmaps(begin, end);
images[index].setUpdateTicksInterval(1);
images[index].setDoneAction(animationEndedCallback);
images[index].setXY(CANVAS_X_BEGIN + j * DISTANCE_BETWEEN_MARKERS, CANVAS_Y_BEGIN + i * DISTANCE_BETWEEN_MARKERS);
add(images[index]);
index++;
}
}
//add lines on top
for (int i = 0; i < NR_OF_MARKERS; i++)
{
line[i].setPosition(0, 0, 2 * DISTANCE_BETWEEN_MARKERS + HITBOX_SIZE + CANVAS_X_BEGIN + 50, 2 * DISTANCE_BETWEEN_MARKERS + HITBOX_SIZE + CANVAS_Y_BEGIN + 50);
line[i].setLineWidth(TRACE_LINE_THICKNESS);
line[i].setPainter(myColorPainter);
line[i].setLineEndingStyle(touchgfx::Line::BUTT_CAP_ENDING);
line[i].setVisible(false);
add(line[i]);
}
}
void LoginWidget::showTrace(touchgfx::Vector<uint8_t, 9> solution_)
{
reset();
tracing = true;
failedAttempts = 0;
for (int i = 0; i < solution_.size(); i++)
{
//activate nodes
activateNode(solution_[i]);
//only draw lines when necessary.
if (solution_.size() > 1 && i < solution_.size() - 1)
{
line[i].updateStart((hitBoxes[solution_[i]].getX() + hitBoxes[solution_[i]].getWidth() / 2), (hitBoxes[solution_[i]].getY() + hitBoxes[solution_[i]].getHeight() / 2));
line[i].updateEnd((hitBoxes[solution_[i + 1]].getX() + hitBoxes[solution_[i + 1]].getWidth() / 2), (hitBoxes[solution_[i + 1]].getY() + hitBoxes[solution_[i + 1]].getHeight() / 2));
line[i].setVisible(true);
line[i].setAlpha(50);
}
}
showHintBanner();
//begin timer
touchgfx::Application::getInstance()->registerTimerWidget(this);
}
void LoginWidget::setMaxAllowedAttempts(uint8_t attempts)
{
maxAllowedAttempts = attempts;
}
void LoginWidget::showBannerContent(const char *text, uint8_t ms)
{
//This method copies incoming string to buffer for x ms.
}
void LoginWidget::animationEnded(const AnimatedImage &source)
{
//This method is called when markers are done animating.
//No implementation
}
void LoginWidget::updateBannerText(TypedTextId textId)
{
bannerTxt.setTypedText(TypedText(textId));
bannerTxt.moveTo(getTextCenterXCoord(bannerTxt), bannerTxt.getY());
bannerTxt.setVisible(true);
bannerTxt.invalidate();
}
uint16_t LoginWidget::getTextCenterXCoord(TextArea &ta)
{
return ((getWidth() / 2) - (ta.getWidth() / 2));
}
void LoginWidget::processAnswer()
{
/////////////////////////////////////////////////////
// PROCESS SOLUTION for correct answer
//
success = true;
if (input.size() != solution.size())
{
success = false;
}
else if (input.size() == solution.size())
{
for (int i = 0; i < input.size(); i++)
{
if (input[i] != solution[i])
{
success = false;
break;
}
}
}
//If pattern approved, display static banner
if (success)
{
failedAttempts = 0;
showSolutionSuccessBanner();
if (successCallback && successCallback->isValid())
{
successCallback->execute();
}
}
}
void LoginWidget::resetTimer()
{
tickCounter = 0;
touchgfx::Application::getInstance()->unregisterTimerWidget(this);
}
void LoginWidget::setBannerPosition(uint16_t x, uint16_t y)
{
//This method sets the position of the banner
//No implementation
}
| 31.560636 | 207 | 0.553701 | ramkumarkoppu |
3b61ee22750667eb92981b7e8e0a85b42ad9f45d | 6,668 | cpp | C++ | lab8/src/2/src/kernel/memory.cpp | YatSenOS/YatSenOS-Tutorial-Volume-1 | dc69d576b2cdcece58744eeab4798bd6f1260bb5 | [
"MulanPSL-1.0"
] | 400 | 2021-05-30T04:07:44.000Z | 2022-03-16T04:47:52.000Z | lab8/src/2/src/kernel/memory.cpp | YatSenOS/YatSenOS-Tutorial-Volume-1 | dc69d576b2cdcece58744eeab4798bd6f1260bb5 | [
"MulanPSL-1.0"
] | 2 | 2021-10-10T23:55:02.000Z | 2021-10-11T06:09:36.000Z | lab8/src/2/src/kernel/memory.cpp | YatSenOS/YatSenOS-Tutorial-Volume-1 | dc69d576b2cdcece58744eeab4798bd6f1260bb5 | [
"MulanPSL-1.0"
] | 38 | 2021-05-30T04:22:44.000Z | 2022-03-14T04:41:52.000Z | #include "memory.h"
#include "os_constant.h"
#include "stdlib.h"
#include "asm_utils.h"
#include "stdio.h"
#include "program.h"
#include "os_modules.h"
MemoryManager::MemoryManager()
{
initialize();
}
void MemoryManager::initialize()
{
this->totalMemory = 0;
this->totalMemory = getTotalMemory();
// ้ข็็ๅ
ๅญ
int usedMemory = 256 * PAGE_SIZE + 0x100000;
if (this->totalMemory < usedMemory)
{
printf("memory is too small, halt.\n");
asm_halt();
}
// ๅฉไฝ็็ฉบ้ฒ็ๅ
ๅญ
int freeMemory = this->totalMemory - usedMemory;
int freePages = freeMemory / PAGE_SIZE;
int kernelPages = freePages / 2;
int userPages = freePages - kernelPages;
int kernelPhysicalStartAddress = usedMemory;
int userPhysicalStartAddress = usedMemory + kernelPages * PAGE_SIZE;
int kernelPhysicalBitMapStart = BITMAP_START_ADDRESS;
int userPhysicalBitMapStart = kernelPhysicalBitMapStart + ceil(kernelPages, 8);
int kernelVirtualBitMapStart = userPhysicalBitMapStart + ceil(userPages, 8);
kernelPhysical.initialize(
(char *)kernelPhysicalBitMapStart,
kernelPages,
kernelPhysicalStartAddress);
userPhysical.initialize(
(char *)userPhysicalBitMapStart,
userPages,
userPhysicalStartAddress);
kernelVirtual.initialize(
(char *)kernelVirtualBitMapStart,
kernelPages,
KERNEL_VIRTUAL_START);
printf("total memory: %d bytes ( %d MB )\n",
this->totalMemory,
this->totalMemory / 1024 / 1024);
printf("kernel pool\n"
" start address: 0x%x\n"
" total pages: %d ( %d MB )\n"
" bitmap start address: 0x%x\n",
kernelPhysicalStartAddress,
kernelPages, kernelPages * PAGE_SIZE / 1024 / 1024,
kernelPhysicalBitMapStart);
printf("user pool\n"
" start address: 0x%x\n"
" total pages: %d ( %d MB )\n"
" bit map start address: 0x%x\n",
userPhysicalStartAddress,
userPages, userPages * PAGE_SIZE / 1024 / 1024,
userPhysicalBitMapStart);
printf("kernel virtual pool\n"
" start address: 0x%x\n"
" total pages: %d ( %d MB ) \n"
" bit map start address: 0x%x\n",
KERNEL_VIRTUAL_START,
userPages, kernelPages * PAGE_SIZE / 1024 / 1024,
kernelVirtualBitMapStart);
}
int MemoryManager::allocatePhysicalPages(enum AddressPoolType type, const int count)
{
int start = -1;
if (type == AddressPoolType::KERNEL)
{
start = kernelPhysical.allocate(count);
}
else if (type == AddressPoolType::USER)
{
start = userPhysical.allocate(count);
}
return (start == -1) ? 0 : start;
}
void MemoryManager::releasePhysicalPages(enum AddressPoolType type, const int paddr, const int count)
{
if (type == AddressPoolType::KERNEL)
{
kernelPhysical.release(paddr, count);
}
else if (type == AddressPoolType::USER)
{
userPhysical.release(paddr, count);
}
}
int MemoryManager::getTotalMemory()
{
if (!this->totalMemory)
{
int memory = *((int *)MEMORY_SIZE_ADDRESS);
// axๅฏๅญๅจไฟๅญ็ๅ
ๅฎน
int low = memory & 0xffff;
// bxๅฏๅญๅจไฟๅญ็ๅ
ๅฎน
int high = (memory >> 16) & 0xffff;
this->totalMemory = low * 1024 + high * 64 * 1024;
}
return this->totalMemory;
}
int MemoryManager::allocatePages(enum AddressPoolType type, const int count)
{
// ็ฌฌไธๆญฅ๏ผไป่ๆๅฐๅๆฑ ไธญๅ้
่ฅๅนฒ่ๆ้กต
int virtualAddress = allocateVirtualPages(type, count);
if (!virtualAddress)
{
return 0;
}
bool flag;
int physicalPageAddress;
int vaddress = virtualAddress;
// ไพๆฌกไธบๆฏไธไธช่ๆ้กตๆๅฎ็ฉ็้กต
for (int i = 0; i < count; ++i, vaddress += PAGE_SIZE)
{
flag = false;
// ็ฌฌไบๆญฅ๏ผไป็ฉ็ๅฐๅๆฑ ไธญๅ้
ไธไธช็ฉ็้กต
physicalPageAddress = allocatePhysicalPages(type, 1);
if (physicalPageAddress)
{
//printf("allocate physical page 0x%x\n", physicalPageAddress);
// ็ฌฌไธๆญฅ๏ผไธบ่ๆ้กตๅปบ็ซ้กต็ฎๅฝ้กนๅ้กต่กจ้กน๏ผไฝฟ่ๆ้กตๅ
็ๅฐๅ็ป่ฟๅ้กตๆบๅถๅๆขๅฐ็ฉ็้กตๅ
ใ
flag = connectPhysicalVirtualPage(vaddress, physicalPageAddress);
}
else
{
flag = false;
}
// ๅ้
ๅคฑ่ดฅ๏ผ้ๆพๅ้ขๅทฒ็ปๅ้
็่ๆ้กตๅ็ฉ็้กต่กจ
if (!flag)
{
// ๅiไธช้กต่กจๅทฒ็ปๆๅฎไบ็ฉ็้กต
releasePages(type, virtualAddress, i);
// ๅฉไฝ็้กต่กจๆชๆๅฎ็ฉ็้กต
releaseVirtualPages(type, virtualAddress + i * PAGE_SIZE, count - i);
return 0;
}
}
return virtualAddress;
}
int MemoryManager::allocateVirtualPages(enum AddressPoolType type, const int count)
{
int start = -1;
if (type == AddressPoolType::KERNEL)
{
start = kernelVirtual.allocate(count);
}
return (start == -1) ? 0 : start;
}
bool MemoryManager::connectPhysicalVirtualPage(const int virtualAddress, const int physicalPageAddress)
{
// ่ฎก็ฎ่ๆๅฐๅๅฏนๅบ็้กต็ฎๅฝ้กนๅ้กต่กจ้กน
int *pde = (int *)toPDE(virtualAddress);
int *pte = (int *)toPTE(virtualAddress);
// ้กต็ฎๅฝ้กนๆ ๅฏนๅบ็้กต่กจ๏ผๅ
ๅ้
ไธไธช้กต่กจ
if(!(*pde & 0x00000001))
{
// ไปๅ
ๆ ธ็ฉ็ๅฐๅ็ฉบ้ดไธญๅ้
ไธไธช้กต่กจ
int page = allocatePhysicalPages(AddressPoolType::KERNEL, 1);
if (!page)
return false;
// ไฝฟ้กต็ฎๅฝ้กนๆๅ้กต่กจ
*pde = page | 0x7;
// ๅๅงๅ้กต่กจ
char *pagePtr = (char *)(((int)pte) & 0xfffff000);
memset(pagePtr, 0, PAGE_SIZE);
}
// ไฝฟ้กต่กจ้กนๆๅ็ฉ็้กต
*pte = physicalPageAddress | 0x7;
return true;
}
int MemoryManager::toPDE(const int virtualAddress)
{
return (0xfffff000 + (((virtualAddress & 0xffc00000) >> 22) * 4));
}
int MemoryManager::toPTE(const int virtualAddress)
{
return (0xffc00000 + ((virtualAddress & 0xffc00000) >> 10) + (((virtualAddress & 0x003ff000) >> 12) * 4));
}
void MemoryManager::releasePages(enum AddressPoolType type, const int virtualAddress, const int count)
{
int vaddr = virtualAddress;
int *pte;
for (int i = 0; i < count; ++i, vaddr += PAGE_SIZE)
{
// ็ฌฌไธๆญฅ๏ผๅฏนๆฏไธไธช่ๆ้กต๏ผ้ๆพไธบๅ
ถๅ้
็็ฉ็้กต
releasePhysicalPages(type, vaddr2paddr(vaddr), 1);
// ่ฎพ็ฝฎ้กต่กจ้กนไธบไธๅญๅจ๏ผ้ฒๆญข้ๆพๅ่ขซๅๆฌกไฝฟ็จ
pte = (int *)toPTE(vaddr);
*pte = 0;
}
// ็ฌฌไบๆญฅ๏ผ้ๆพ่ๆ้กต
releaseVirtualPages(type, virtualAddress, count);
}
int MemoryManager::vaddr2paddr(int vaddr)
{
int *pte = (int *)toPTE(vaddr);
int page = (*pte) & 0xfffff000;
int offset = vaddr & 0xfff;
return (page + offset);
}
void MemoryManager::releaseVirtualPages(enum AddressPoolType type, const int vaddr, const int count)
{
if (type == AddressPoolType::KERNEL)
{
kernelVirtual.release(vaddr, count);
}
} | 26.046875 | 110 | 0.613077 | YatSenOS |
3b6251aa2907606b779fd4115b9f2f0d38a22ac3 | 288 | hpp | C++ | pythran/pythonic/__builtin__/UserWarning.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/__builtin__/UserWarning.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/__builtin__/UserWarning.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_BUILTIN_USERWARNING_HPP
#define PYTHONIC_BUILTIN_USERWARNING_HPP
#include "pythonic/include/__builtin__/UserWarning.hpp"
#include "pythonic/types/exceptions.hpp"
namespace pythonic
{
namespace __builtin__
{
PYTHONIC_EXCEPTION_IMPL(UserWarning)
}
}
#endif
| 15.157895 | 55 | 0.805556 | xmar |
3b678a0addf2b3959f949dc84cf3f76fbea1ae2f | 8,651 | cpp | C++ | YorozuyaGSLib/source/VoterDetail.cpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | YorozuyaGSLib/source/VoterDetail.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | YorozuyaGSLib/source/VoterDetail.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | #include <VoterDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Detail
{
Info::VoterDoit2_ptr VoterDoit2_next(nullptr);
Info::VoterDoit2_clbk VoterDoit2_user(nullptr);
Info::VoterInitialize4_ptr VoterInitialize4_next(nullptr);
Info::VoterInitialize4_clbk VoterInitialize4_user(nullptr);
Info::VoterIsRegistedVotePaper6_ptr VoterIsRegistedVotePaper6_next(nullptr);
Info::VoterIsRegistedVotePaper6_clbk VoterIsRegistedVotePaper6_user(nullptr);
Info::Voterctor_Voter8_ptr Voterctor_Voter8_next(nullptr);
Info::Voterctor_Voter8_clbk Voterctor_Voter8_user(nullptr);
Info::Voter_MakeVotePaper10_ptr Voter_MakeVotePaper10_next(nullptr);
Info::Voter_MakeVotePaper10_clbk Voter_MakeVotePaper10_user(nullptr);
Info::Voter_SendVotePaper12_ptr Voter_SendVotePaper12_next(nullptr);
Info::Voter_SendVotePaper12_clbk Voter_SendVotePaper12_user(nullptr);
Info::Voter_SendVotePaperAll14_ptr Voter_SendVotePaperAll14_next(nullptr);
Info::Voter_SendVotePaperAll14_clbk Voter_SendVotePaperAll14_user(nullptr);
Info::Voter_SendVoteScore16_ptr Voter_SendVoteScore16_next(nullptr);
Info::Voter_SendVoteScore16_clbk Voter_SendVoteScore16_user(nullptr);
Info::Voter_SendVoteScoreAll18_ptr Voter_SendVoteScoreAll18_next(nullptr);
Info::Voter_SendVoteScoreAll18_clbk Voter_SendVoteScoreAll18_user(nullptr);
Info::Voter_SetVoteScoreInfo20_ptr Voter_SetVoteScoreInfo20_next(nullptr);
Info::Voter_SetVoteScoreInfo20_clbk Voter_SetVoteScoreInfo20_user(nullptr);
Info::Voter_Vote22_ptr Voter_Vote22_next(nullptr);
Info::Voter_Vote22_clbk Voter_Vote22_user(nullptr);
Info::Voterdtor_Voter27_ptr Voterdtor_Voter27_next(nullptr);
Info::Voterdtor_Voter27_clbk Voterdtor_Voter27_user(nullptr);
int VoterDoit2_wrapper(struct Voter* _this, Cmd eCmd, struct CPlayer* pOne, char* pdata)
{
return VoterDoit2_user(_this, eCmd, pOne, pdata, VoterDoit2_next);
};
bool VoterInitialize4_wrapper(struct Voter* _this)
{
return VoterInitialize4_user(_this, VoterInitialize4_next);
};
bool VoterIsRegistedVotePaper6_wrapper(struct Voter* _this, char byRace, char* pwszName)
{
return VoterIsRegistedVotePaper6_user(_this, byRace, pwszName, VoterIsRegistedVotePaper6_next);
};
void Voterctor_Voter8_wrapper(struct Voter* _this)
{
Voterctor_Voter8_user(_this, Voterctor_Voter8_next);
};
void Voter_MakeVotePaper10_wrapper(struct Voter* _this)
{
Voter_MakeVotePaper10_user(_this, Voter_MakeVotePaper10_next);
};
int Voter_SendVotePaper12_wrapper(struct Voter* _this, struct CPlayer* pOne)
{
return Voter_SendVotePaper12_user(_this, pOne, Voter_SendVotePaper12_next);
};
void Voter_SendVotePaperAll14_wrapper(struct Voter* _this)
{
Voter_SendVotePaperAll14_user(_this, Voter_SendVotePaperAll14_next);
};
void Voter_SendVoteScore16_wrapper(struct Voter* _this, struct CPlayer* pOne)
{
Voter_SendVoteScore16_user(_this, pOne, Voter_SendVoteScore16_next);
};
void Voter_SendVoteScoreAll18_wrapper(struct Voter* _this, char byRace)
{
Voter_SendVoteScoreAll18_user(_this, byRace, Voter_SendVoteScoreAll18_next);
};
void Voter_SetVoteScoreInfo20_wrapper(struct Voter* _this, char byRace, char* wszName, bool bAbstention)
{
Voter_SetVoteScoreInfo20_user(_this, byRace, wszName, bAbstention, Voter_SetVoteScoreInfo20_next);
};
int Voter_Vote22_wrapper(struct Voter* _this, struct CPlayer* pOne, char* pdata)
{
return Voter_Vote22_user(_this, pOne, pdata, Voter_Vote22_next);
};
void Voterdtor_Voter27_wrapper(struct Voter* _this)
{
Voterdtor_Voter27_user(_this, Voterdtor_Voter27_next);
};
::std::array<hook_record, 12> Voter_functions =
{
_hook_record {
(LPVOID)0x1402bea50L,
(LPVOID *)&VoterDoit2_user,
(LPVOID *)&VoterDoit2_next,
(LPVOID)cast_pointer_function(VoterDoit2_wrapper),
(LPVOID)cast_pointer_function((int(Voter::*)(Cmd, struct CPlayer*, char*))&Voter::Doit)
},
_hook_record {
(LPVOID)0x1402be940L,
(LPVOID *)&VoterInitialize4_user,
(LPVOID *)&VoterInitialize4_next,
(LPVOID)cast_pointer_function(VoterInitialize4_wrapper),
(LPVOID)cast_pointer_function((bool(Voter::*)())&Voter::Initialize)
},
_hook_record {
(LPVOID)0x1402bfa90L,
(LPVOID *)&VoterIsRegistedVotePaper6_user,
(LPVOID *)&VoterIsRegistedVotePaper6_next,
(LPVOID)cast_pointer_function(VoterIsRegistedVotePaper6_wrapper),
(LPVOID)cast_pointer_function((bool(Voter::*)(char, char*))&Voter::IsRegistedVotePaper)
},
_hook_record {
(LPVOID)0x1402be860L,
(LPVOID *)&Voterctor_Voter8_user,
(LPVOID *)&Voterctor_Voter8_next,
(LPVOID)cast_pointer_function(Voterctor_Voter8_wrapper),
(LPVOID)cast_pointer_function((void(Voter::*)())&Voter::ctor_Voter)
},
_hook_record {
(LPVOID)0x1402bf610L,
(LPVOID *)&Voter_MakeVotePaper10_user,
(LPVOID *)&Voter_MakeVotePaper10_next,
(LPVOID)cast_pointer_function(Voter_MakeVotePaper10_wrapper),
(LPVOID)cast_pointer_function((void(Voter::*)())&Voter::_MakeVotePaper)
},
_hook_record {
(LPVOID)0x1402c0140L,
(LPVOID *)&Voter_SendVotePaper12_user,
(LPVOID *)&Voter_SendVotePaper12_next,
(LPVOID)cast_pointer_function(Voter_SendVotePaper12_wrapper),
(LPVOID)cast_pointer_function((int(Voter::*)(struct CPlayer*))&Voter::_SendVotePaper)
},
_hook_record {
(LPVOID)0x1402beb20L,
(LPVOID *)&Voter_SendVotePaperAll14_user,
(LPVOID *)&Voter_SendVotePaperAll14_next,
(LPVOID)cast_pointer_function(Voter_SendVotePaperAll14_wrapper),
(LPVOID)cast_pointer_function((void(Voter::*)())&Voter::_SendVotePaperAll)
},
_hook_record {
(LPVOID)0x1402bede0L,
(LPVOID *)&Voter_SendVoteScore16_user,
(LPVOID *)&Voter_SendVoteScore16_next,
(LPVOID)cast_pointer_function(Voter_SendVoteScore16_wrapper),
(LPVOID)cast_pointer_function((void(Voter::*)(struct CPlayer*))&Voter::_SendVoteScore)
},
_hook_record {
(LPVOID)0x1402beec0L,
(LPVOID *)&Voter_SendVoteScoreAll18_user,
(LPVOID *)&Voter_SendVoteScoreAll18_next,
(LPVOID)cast_pointer_function(Voter_SendVoteScoreAll18_wrapper),
(LPVOID)cast_pointer_function((void(Voter::*)(char))&Voter::_SendVoteScoreAll)
},
_hook_record {
(LPVOID)0x1402bf3d0L,
(LPVOID *)&Voter_SetVoteScoreInfo20_user,
(LPVOID *)&Voter_SetVoteScoreInfo20_next,
(LPVOID)cast_pointer_function(Voter_SetVoteScoreInfo20_wrapper),
(LPVOID)cast_pointer_function((void(Voter::*)(char, char*, bool))&Voter::_SetVoteScoreInfo)
},
_hook_record {
(LPVOID)0x1402befd0L,
(LPVOID *)&Voter_Vote22_user,
(LPVOID *)&Voter_Vote22_next,
(LPVOID)cast_pointer_function(Voter_Vote22_wrapper),
(LPVOID)cast_pointer_function((int(Voter::*)(struct CPlayer*, char*))&Voter::_Vote)
},
_hook_record {
(LPVOID)0x1402c0100L,
(LPVOID *)&Voterdtor_Voter27_user,
(LPVOID *)&Voterdtor_Voter27_next,
(LPVOID)cast_pointer_function(Voterdtor_Voter27_wrapper),
(LPVOID)cast_pointer_function((void(Voter::*)())&Voter::dtor_Voter)
},
};
}; // end namespace Detail
END_ATF_NAMESPACE
| 46.510753 | 112 | 0.635765 | lemkova |
3b6908b7dbf5f6f66cac9172cca25d52bab9a4d7 | 2,784 | hpp | C++ | Siv3D/include/Siv3D/BinaryWriter.hpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 2 | 2021-11-22T00:52:48.000Z | 2021-12-24T09:33:55.000Z | Siv3D/include/Siv3D/BinaryWriter.hpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 32 | 2021-10-09T10:04:11.000Z | 2022-02-25T06:10:13.000Z | Siv3D/include/Siv3D/BinaryWriter.hpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 1 | 2021-12-31T05:08:00.000Z | 2021-12-31T05:08:00.000Z | ๏ปฟ//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <memory>
# include "Common.hpp"
# include "IWriter.hpp"
# include "StringView.hpp"
# include "OpenMode.hpp"
namespace s3d
{
class String;
using FilePath = String;
/// @brief ๆธใ่พผใฟ็จใใคใใชใใกใคใซ
class BinaryWriter : public IWriter
{
public:
/// @brief ใใใฉใซใใณใณในใใฉใฏใฟ
SIV3D_NODISCARD_CXX20
BinaryWriter();
/// @brief ใใกใคใซใ้ใใพใใ
/// @param path ใใกใคใซใใน
/// @param openMode ใชใผใใณใขใผใ (`OpenMode` ใฎ็ตใฟๅใใ๏ผ
SIV3D_NODISCARD_CXX20
explicit BinaryWriter(FilePathView path, OpenMode openMode = OpenMode::Trunc);
/// @brief ใใกใคใซใ้ใใพใใ
/// @param path ใใกใคใซใใน
/// @param openMode ใชใผใใณใขใผใ (`OpenMode` ใฎ็ตใฟๅใใ๏ผ
/// @return ใใกใคใซใฎใชใผใใณใซๆๅใใๅ ดๅ true, ใใไปฅๅคใฎๅ ดๅใฏ false
bool open(FilePathView path, OpenMode openMode = OpenMode::Trunc);
/// @brief ใใกใคใซใ้ใใพใใ
/// @remark ใใกใคใซใใชใผใใณใใฆใใชใๅ ดๅใฏไฝใใใพใใใ
void close();
/// @brief ใใกใคใซใ้ใใฆใใใใ่ฟใใพใใ
/// @return ใใกใคใซใ้ใใฆใใๅ ดๅ true, ใใไปฅๅคใฎๅ ดๅใฏ false
[[nodiscard]]
bool isOpen() const noexcept override;
/// @brief ใใกใคใซใ้ใใฆใใใใ่ฟใใพใใ
/// @return ใใกใคใซใ้ใใฆใใๅ ดๅ true, ใใไปฅๅคใฎๅ ดๅใฏ false
[[nodiscard]]
explicit operator bool() const noexcept;
/// @brief ๆธใ่พผใใ ใใผใฟใฎใใใใกใใใฉใใทใฅใใฆใ็ขบๅฎใซใใกใคใซใซๆธใ่พผใฟใพใใ
void flush();
/// @brief ้ใใฆใใใใกใคใซใฎๅ
ๅฎนใใในใฆๆถๅปใใใตใคใบใ 0 ใฎใใกใคใซใซใใพใใ
void clear();
/// @brief ้ใใฆใใใใกใคใซใฎ็พๅจใฎใตใคใบ๏ผใใคใ๏ผใ่ฟใใพใใ
/// @return ้ใใฆใใใใกใคใซใฎ็พๅจใฎใตใคใบ๏ผใใคใ๏ผ
[[nodiscard]]
int64 size() const override;
/// @brief ็พๅจใฎๆธใ่พผใฟไฝ็ฝฎใ่ฟใใพใใ
/// @return ็พๅจใฎๆธใ่พผใฟไฝ็ฝฎ
[[nodiscard]]
int64 getPos() const override;
/// @brief ๆธใ่พผใฟไฝ็ฝฎใๅคๆดใใพใใ
/// @param pos ๆฐใใๆธใ่พผใฟไฝ็ฝฎ๏ผใใคใ๏ผ
/// @return ๆธใ่พผใฟไฝ็ฝฎใฎๅคๆดใซๆๅใใๅ ดๅ true, ใใไปฅๅคใฎๅ ดๅใฏ false
bool setPos(int64 pos) override;
/// @brief ๆธใ่พผใฟไฝ็ฝฎใใใกใคใซใฎ็ต็ซฏใซ็งปๅใใใพใใ
/// @return ๆฐใใๆธใ่พผใฟไฝ็ฝฎ๏ผใใคใ๏ผ
int64 seekToEnd();
/// @brief ็พๅจใฎๆธใ่พผใฟไฝ็ฝฎใซใใผใฟใๆธใ่พผใฟใพใใ
/// @param src ๆธใ่พผใใใผใฟ
/// @param sizeBytes ๆธใ่พผใใตใคใบ๏ผใใคใ๏ผ
/// @remark ๆธใ่พผใฟไฝ็ฝฎใใใกใคใซใฎ็ต็ซฏใฎๅ ดๅใๆธใ่พผใใ ๅใ ใใใกใคใซใฎใตใคใบใๆกๅผตใใใพใใ
/// @return ๅฎ้ใซๆธใ่พผใใ ใตใคใบ๏ผใใคใ๏ผ
int64 write(const void* src, int64 sizeBytes) override;
/// @brief ็พๅจใฎๆธใ่พผใฟไฝ็ฝฎใซใใผใฟใๆธใ่พผใฟใพใใ
/// @tparam TriviallyCopyable ๆธใ่พผใๅคใฎๅ
/// @param src ๆธใ่พผใใใผใฟ
/// @remark ๆธใ่พผใฟไฝ็ฝฎใใใกใคใซใฎ็ต็ซฏใฎๅ ดๅใๆธใ่พผใใ ๅใ ใใใกใคใซใฎใตใคใบใๆกๅผตใใใพใใ
/// @return ๆธใ่พผใฟใซๆๅใใๅ ดๅ true, ใใไปฅๅคใฎๅ ดๅใฏ false
SIV3D_CONCEPT_TRIVIALLY_COPYABLE
bool write(const TriviallyCopyable& src);
/// @brief ้ใใฆใใใใกใคใซใฎใในใ่ฟใใพใใ
/// @return ้ใใฆใใใใกใคใซใฎใในใใใกใคใซใ้ใใฆใใชใๅ ดๅใฏ็ฉบใฎๆๅญๅ
[[nodiscard]]
const FilePath& path() const noexcept;
private:
class BinaryWriterDetail;
std::shared_ptr<BinaryWriterDetail> pImpl;
};
}
# include "detail/BinaryWriter.ipp"
| 24.637168 | 80 | 0.681394 | tas9n |
3b71cd7c8f4d104658fa98bf693f6a494dc504af | 24,957 | cc | C++ | src/transform/vertex_pulling_transform_test.cc | dorba/tint | f81c1081ea7d27ea55f373c0bfaf651e491da7e6 | [
"Apache-2.0"
] | null | null | null | src/transform/vertex_pulling_transform_test.cc | dorba/tint | f81c1081ea7d27ea55f373c0bfaf651e491da7e6 | [
"Apache-2.0"
] | null | null | null | src/transform/vertex_pulling_transform_test.cc | dorba/tint | f81c1081ea7d27ea55f373c0bfaf651e491da7e6 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Tint Authors.
//
// 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 "src/transform/vertex_pulling_transform.h"
#include "gtest/gtest.h"
#include "src/ast/decorated_variable.h"
#include "src/ast/function.h"
#include "src/ast/pipeline_stage.h"
#include "src/ast/stage_decoration.h"
#include "src/ast/type/array_type.h"
#include "src/ast/type/f32_type.h"
#include "src/ast/type/i32_type.h"
#include "src/ast/type/void_type.h"
#include "src/type_determiner.h"
#include "src/validator.h"
namespace tint {
namespace transform {
namespace {
class VertexPullingTransformHelper {
public:
VertexPullingTransformHelper() {
mod_ = std::make_unique<ast::Module>();
transform_ = std::make_unique<VertexPullingTransform>(&ctx_, mod_.get());
}
// Create basic module with an entry point and vertex function
void InitBasicModule() {
auto func = std::make_unique<ast::Function>(
"main", ast::VariableList{},
ctx_.type_mgr().Get(std::make_unique<ast::type::VoidType>()));
func->add_decoration(
std::make_unique<ast::StageDecoration>(ast::PipelineStage ::kVertex));
mod()->AddFunction(std::move(func));
}
// Set up the transformation, after building the module
void InitTransform(VertexStateDescriptor vertex_state) {
EXPECT_TRUE(mod_->IsValid());
TypeDeterminer td(&ctx_, mod_.get());
EXPECT_TRUE(td.Determine());
transform_->SetVertexState(
std::make_unique<VertexStateDescriptor>(std::move(vertex_state)));
transform_->SetEntryPoint("main");
}
// Inserts a variable which will be converted to vertex pulling
void AddVertexInputVariable(uint32_t location,
std::string name,
ast::type::Type* type) {
auto var = std::make_unique<ast::DecoratedVariable>(
std::make_unique<ast::Variable>(name, ast::StorageClass::kInput, type));
ast::VariableDecorationList decorations;
decorations.push_back(std::make_unique<ast::LocationDecoration>(location));
var->set_decorations(std::move(decorations));
mod_->AddGlobalVariable(std::move(var));
}
Context* ctx() { return &ctx_; }
ast::Module* mod() { return mod_.get(); }
VertexPullingTransform* transform() { return transform_.get(); }
private:
Context ctx_;
std::unique_ptr<ast::Module> mod_;
std::unique_ptr<VertexPullingTransform> transform_;
};
class VertexPullingTransformTest : public VertexPullingTransformHelper,
public testing::Test {};
TEST_F(VertexPullingTransformTest, Error_NoVertexState) {
EXPECT_FALSE(transform()->Run());
EXPECT_EQ(transform()->error(), "SetVertexState not called");
}
TEST_F(VertexPullingTransformTest, Error_NoEntryPoint) {
transform()->SetVertexState(std::make_unique<VertexStateDescriptor>());
EXPECT_FALSE(transform()->Run());
EXPECT_EQ(transform()->error(), "Vertex stage entry point not found");
}
TEST_F(VertexPullingTransformTest, Error_InvalidEntryPoint) {
InitBasicModule();
InitTransform({});
transform()->SetEntryPoint("_");
EXPECT_FALSE(transform()->Run());
EXPECT_EQ(transform()->error(), "Vertex stage entry point not found");
}
TEST_F(VertexPullingTransformTest, Error_EntryPointWrongStage) {
auto func = std::make_unique<ast::Function>(
"main", ast::VariableList{},
ctx()->type_mgr().Get(std::make_unique<ast::type::VoidType>()));
func->add_decoration(
std::make_unique<ast::StageDecoration>(ast::PipelineStage::kFragment));
mod()->AddFunction(std::move(func));
InitTransform({});
EXPECT_FALSE(transform()->Run());
EXPECT_EQ(transform()->error(), "Vertex stage entry point not found");
}
TEST_F(VertexPullingTransformTest, BasicModule) {
InitBasicModule();
InitTransform({});
EXPECT_TRUE(transform()->Run());
}
TEST_F(VertexPullingTransformTest, OneAttribute) {
InitBasicModule();
ast::type::F32Type f32;
AddVertexInputVariable(0, "var_a", &f32);
InitTransform({{{4, InputStepMode::kVertex, {{VertexFormat::kF32, 0, 0}}}}});
EXPECT_TRUE(transform()->Run());
EXPECT_EQ(R"(Module{
TintVertexData Struct{
[[block]]
StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4}
}
Variable{
var_a
private
__f32
}
DecoratedVariable{
Decorations{
BuiltinDecoration{vertex_idx}
}
_tint_pulling_vertex_index
in
__i32
}
DecoratedVariable{
Decorations{
BindingDecoration{0}
SetDecoration{4}
}
_tint_pulling_vertex_buffer_0
storage_buffer
__struct_TintVertexData
}
Function main -> __void
StageDecoration{vertex}
()
{
Block{
VariableDeclStatement{
Variable{
_tint_pulling_pos
function
__i32
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{_tint_pulling_vertex_index}
multiply
ScalarConstructor{4}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_a}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Identifier{_tint_pulling_pos}
divide
ScalarConstructor{4}
}
}
}
}
}
}
}
)",
mod()->to_str());
}
TEST_F(VertexPullingTransformTest, OneInstancedAttribute) {
InitBasicModule();
ast::type::F32Type f32;
AddVertexInputVariable(0, "var_a", &f32);
InitTransform(
{{{4, InputStepMode::kInstance, {{VertexFormat::kF32, 0, 0}}}}});
EXPECT_TRUE(transform()->Run());
EXPECT_EQ(R"(Module{
TintVertexData Struct{
[[block]]
StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4}
}
Variable{
var_a
private
__f32
}
DecoratedVariable{
Decorations{
BuiltinDecoration{instance_idx}
}
_tint_pulling_instance_index
in
__i32
}
DecoratedVariable{
Decorations{
BindingDecoration{0}
SetDecoration{4}
}
_tint_pulling_vertex_buffer_0
storage_buffer
__struct_TintVertexData
}
Function main -> __void
StageDecoration{vertex}
()
{
Block{
VariableDeclStatement{
Variable{
_tint_pulling_pos
function
__i32
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{_tint_pulling_instance_index}
multiply
ScalarConstructor{4}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_a}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Identifier{_tint_pulling_pos}
divide
ScalarConstructor{4}
}
}
}
}
}
}
}
)",
mod()->to_str());
}
TEST_F(VertexPullingTransformTest, OneAttributeDifferentOutputSet) {
InitBasicModule();
ast::type::F32Type f32;
AddVertexInputVariable(0, "var_a", &f32);
InitTransform({{{4, InputStepMode::kVertex, {{VertexFormat::kF32, 0, 0}}}}});
transform()->SetPullingBufferBindingSet(5);
EXPECT_TRUE(transform()->Run());
EXPECT_EQ(R"(Module{
TintVertexData Struct{
[[block]]
StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4}
}
Variable{
var_a
private
__f32
}
DecoratedVariable{
Decorations{
BuiltinDecoration{vertex_idx}
}
_tint_pulling_vertex_index
in
__i32
}
DecoratedVariable{
Decorations{
BindingDecoration{0}
SetDecoration{5}
}
_tint_pulling_vertex_buffer_0
storage_buffer
__struct_TintVertexData
}
Function main -> __void
StageDecoration{vertex}
()
{
Block{
VariableDeclStatement{
Variable{
_tint_pulling_pos
function
__i32
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{_tint_pulling_vertex_index}
multiply
ScalarConstructor{4}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_a}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Identifier{_tint_pulling_pos}
divide
ScalarConstructor{4}
}
}
}
}
}
}
}
)",
mod()->to_str());
}
// We expect the transform to use an existing builtin variables if it finds them
TEST_F(VertexPullingTransformTest, ExistingVertexIndexAndInstanceIndex) {
InitBasicModule();
ast::type::F32Type f32;
AddVertexInputVariable(0, "var_a", &f32);
AddVertexInputVariable(1, "var_b", &f32);
ast::type::I32Type i32;
{
auto vertex_index_var = std::make_unique<ast::DecoratedVariable>(
std::make_unique<ast::Variable>("custom_vertex_index",
ast::StorageClass::kInput, &i32));
ast::VariableDecorationList decorations;
decorations.push_back(
std::make_unique<ast::BuiltinDecoration>(ast::Builtin::kVertexIdx));
vertex_index_var->set_decorations(std::move(decorations));
mod()->AddGlobalVariable(std::move(vertex_index_var));
}
{
auto instance_index_var = std::make_unique<ast::DecoratedVariable>(
std::make_unique<ast::Variable>("custom_instance_index",
ast::StorageClass::kInput, &i32));
ast::VariableDecorationList decorations;
decorations.push_back(
std::make_unique<ast::BuiltinDecoration>(ast::Builtin::kInstanceIdx));
instance_index_var->set_decorations(std::move(decorations));
mod()->AddGlobalVariable(std::move(instance_index_var));
}
InitTransform(
{{{4, InputStepMode::kVertex, {{VertexFormat::kF32, 0, 0}}},
{4, InputStepMode::kInstance, {{VertexFormat::kF32, 0, 1}}}}});
EXPECT_TRUE(transform()->Run());
EXPECT_EQ(R"(Module{
TintVertexData Struct{
[[block]]
StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4}
}
Variable{
var_a
private
__f32
}
Variable{
var_b
private
__f32
}
DecoratedVariable{
Decorations{
BuiltinDecoration{vertex_idx}
}
custom_vertex_index
in
__i32
}
DecoratedVariable{
Decorations{
BuiltinDecoration{instance_idx}
}
custom_instance_index
in
__i32
}
DecoratedVariable{
Decorations{
BindingDecoration{0}
SetDecoration{4}
}
_tint_pulling_vertex_buffer_0
storage_buffer
__struct_TintVertexData
}
DecoratedVariable{
Decorations{
BindingDecoration{1}
SetDecoration{4}
}
_tint_pulling_vertex_buffer_1
storage_buffer
__struct_TintVertexData
}
Function main -> __void
StageDecoration{vertex}
()
{
Block{
VariableDeclStatement{
Variable{
_tint_pulling_pos
function
__i32
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{custom_vertex_index}
multiply
ScalarConstructor{4}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_a}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Identifier{_tint_pulling_pos}
divide
ScalarConstructor{4}
}
}
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{custom_instance_index}
multiply
ScalarConstructor{4}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_b}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_1}
Identifier{_tint_vertex_data}
}
Binary{
Identifier{_tint_pulling_pos}
divide
ScalarConstructor{4}
}
}
}
}
}
}
}
)",
mod()->to_str());
}
TEST_F(VertexPullingTransformTest, TwoAttributesSameBuffer) {
InitBasicModule();
ast::type::F32Type f32;
AddVertexInputVariable(0, "var_a", &f32);
ast::type::ArrayType vec4_f32{&f32, 4u};
AddVertexInputVariable(1, "var_b", &vec4_f32);
InitTransform(
{{{16,
InputStepMode::kVertex,
{{VertexFormat::kF32, 0, 0}, {VertexFormat::kVec4F32, 0, 1}}}}});
EXPECT_TRUE(transform()->Run());
EXPECT_EQ(R"(Module{
TintVertexData Struct{
[[block]]
StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4}
}
Variable{
var_a
private
__f32
}
Variable{
var_b
private
__array__f32_4
}
DecoratedVariable{
Decorations{
BuiltinDecoration{vertex_idx}
}
_tint_pulling_vertex_index
in
__i32
}
DecoratedVariable{
Decorations{
BindingDecoration{0}
SetDecoration{4}
}
_tint_pulling_vertex_buffer_0
storage_buffer
__struct_TintVertexData
}
Function main -> __void
StageDecoration{vertex}
()
{
Block{
VariableDeclStatement{
Variable{
_tint_pulling_pos
function
__i32
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{_tint_pulling_vertex_index}
multiply
ScalarConstructor{16}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_a}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Identifier{_tint_pulling_pos}
divide
ScalarConstructor{4}
}
}
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{_tint_pulling_vertex_index}
multiply
ScalarConstructor{16}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_b}
TypeConstructor{
__vec_4__f32
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{0}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{4}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{8}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{12}
}
divide
ScalarConstructor{4}
}
}
}
}
}
}
}
}
)",
mod()->to_str());
}
TEST_F(VertexPullingTransformTest, FloatVectorAttributes) {
InitBasicModule();
ast::type::F32Type f32;
ast::type::ArrayType vec2_f32{&f32, 2u};
AddVertexInputVariable(0, "var_a", &vec2_f32);
ast::type::ArrayType vec3_f32{&f32, 3u};
AddVertexInputVariable(1, "var_b", &vec3_f32);
ast::type::ArrayType vec4_f32{&f32, 4u};
AddVertexInputVariable(2, "var_c", &vec4_f32);
InitTransform(
{{{8, InputStepMode::kVertex, {{VertexFormat::kVec2F32, 0, 0}}},
{12, InputStepMode::kVertex, {{VertexFormat::kVec3F32, 0, 1}}},
{16, InputStepMode::kVertex, {{VertexFormat::kVec4F32, 0, 2}}}}});
EXPECT_TRUE(transform()->Run());
EXPECT_EQ(R"(Module{
TintVertexData Struct{
[[block]]
StructMember{[[ offset 0 ]] _tint_vertex_data: __array__u32_stride_4}
}
Variable{
var_a
private
__array__f32_2
}
Variable{
var_b
private
__array__f32_3
}
Variable{
var_c
private
__array__f32_4
}
DecoratedVariable{
Decorations{
BuiltinDecoration{vertex_idx}
}
_tint_pulling_vertex_index
in
__i32
}
DecoratedVariable{
Decorations{
BindingDecoration{0}
SetDecoration{4}
}
_tint_pulling_vertex_buffer_0
storage_buffer
__struct_TintVertexData
}
DecoratedVariable{
Decorations{
BindingDecoration{1}
SetDecoration{4}
}
_tint_pulling_vertex_buffer_1
storage_buffer
__struct_TintVertexData
}
DecoratedVariable{
Decorations{
BindingDecoration{2}
SetDecoration{4}
}
_tint_pulling_vertex_buffer_2
storage_buffer
__struct_TintVertexData
}
Function main -> __void
StageDecoration{vertex}
()
{
Block{
VariableDeclStatement{
Variable{
_tint_pulling_pos
function
__i32
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{_tint_pulling_vertex_index}
multiply
ScalarConstructor{8}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_a}
TypeConstructor{
__vec_2__f32
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{0}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_0}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{4}
}
divide
ScalarConstructor{4}
}
}
}
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{_tint_pulling_vertex_index}
multiply
ScalarConstructor{12}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_b}
TypeConstructor{
__vec_3__f32
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_1}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{0}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_1}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{4}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_1}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{8}
}
divide
ScalarConstructor{4}
}
}
}
}
}
Assignment{
Identifier{_tint_pulling_pos}
Binary{
Binary{
Identifier{_tint_pulling_vertex_index}
multiply
ScalarConstructor{16}
}
add
ScalarConstructor{0}
}
}
Assignment{
Identifier{var_c}
TypeConstructor{
__vec_4__f32
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_2}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{0}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_2}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{4}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_2}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{8}
}
divide
ScalarConstructor{4}
}
}
}
Bitcast<__f32>{
ArrayAccessor{
MemberAccessor{
Identifier{_tint_pulling_vertex_buffer_2}
Identifier{_tint_vertex_data}
}
Binary{
Binary{
Identifier{_tint_pulling_pos}
add
ScalarConstructor{12}
}
divide
ScalarConstructor{4}
}
}
}
}
}
}
}
}
)",
mod()->to_str());
}
} // namespace
} // namespace transform
} // namespace tint
| 24.18314 | 80 | 0.555075 | dorba |
3b72dffedf31ab9716ad1fbeccc9a2fc976f1b7a | 9,363 | cpp | C++ | src/xml.cpp | Lieutenant-Debaser/rom-checksum | 45104adc2280dac448b9f37e7b637909e69f760c | [
"MIT"
] | null | null | null | src/xml.cpp | Lieutenant-Debaser/rom-checksum | 45104adc2280dac448b9f37e7b637909e69f760c | [
"MIT"
] | null | null | null | src/xml.cpp | Lieutenant-Debaser/rom-checksum | 45104adc2280dac448b9f37e7b637909e69f760c | [
"MIT"
] | null | null | null | /* File: xml.cpp
* Author: Lieutenant Debaser
* Last Update (yyyy-mm-dd_hhMM): 2022-01-27_1441
*
* File contains definitions for the Xml class functions, along with constructor definitions. Functions for handling
* searching within strings and XML data are also defined here.
*
* See xml.h for Xml class definition and other function prototypes.
*/
#include "xml.h"
// Class constructors
Xml::Xml() {
name = "";
description = "";
author = "";
homepage = "";
list_size = 0;
}
Xml::Xml (std::string n,
std::string d,
std::string a,
std::string h) {
name = n;
description = d;
author = a;
homepage = h;
list_size = 0;
}
// Accessors
std::string Xml::get_name() {
return name;
}
std::string Xml::get_description() {
return description;
}
std::string Xml::get_author() {
return author;
}
std::string Xml::get_homepage() {
return homepage;
}
Rom_File Xml::get_game (unsigned int index) {
return list [index];
}
Rom_File* Xml::get_list() {
return &list[0];
}
unsigned int Xml::get_list_size() {
return list_size;
}
// Mutators
void Xml::set_name (std::string s) {
name = s;
}
void Xml::set_description (std::string s) {
description = s;
}
void Xml::set_author (std::string s) {
author = s;
}
void Xml::set_homepage (std::string s) {
homepage = s;
}
bool Xml::set_rom (Rom_File r, unsigned int index) {
if (index < MAX_LIST_SIZE) {
list[index] = r;
return true;
}
return false;
}
bool Xml::append_rom (Rom_File r) {
if (list_size < MAX_LIST_SIZE) {
list[list_size] = r;
list_size++;
return true;
}
return false;
}
void Xml::set_list_size (unsigned int i) {
list_size = i;
}
// Rom searching functions
Rom_File* Xml::search_rom_md5 (std::string key) {
for (unsigned int i = 0; i < list_size; i++) {
if (key == list[i].get_md5())
return &list[i];
}
return NULL;
}
Rom_File* Xml::search_rom_sha1 (std::string key) {
for (unsigned int i = 0; i < list_size; i++) {
if (key == list[i].get_sha1())
return &list[i];
}
return NULL;
}
Rom_File* Xml::search_rom_size (unsigned long long key) {
for (unsigned int i = 0; i < list_size; i++) {
if (key == list[i].get_size())
return &list[i];
}
return NULL;
}
// Non-class functions
// Load the contents of a file into a structure and return that structure
bool load_file (std::string f_name, std::vector <std::string> &xml_data) {
std::ifstream xml_read;
xml_read.open (f_name.c_str());
if (xml_read.is_open()) {
std::string buffer;
while (true) {
getline (xml_read, buffer);
// Check for EOF and stop if it has been reached
if (xml_read.eof()) {
break;
}
// Check for certain characters and delete them if necessary
buffer.erase (remove (buffer.begin(), buffer.end(), '\r'), buffer.end()); // Carridge Return
buffer.erase (remove (buffer.begin(), buffer.end(), '\t'), buffer.end()); // Tab
xml_data.push_back (buffer);
}
xml_read.close();
return true;
}
return false;
}
// Ensure that an input file has the XML_HEADER on its first line
bool verify_xml (std::vector <std::string> &xml_data) {
if (xml_data[0] == XML_HEADER) {
return true;
}
return false;
}
// Search for specific text within the XML's <header> section
std::string find_in_xml_header (std::string keyword, std::vector <std::string> &xml_data) {
const std::string keyword_start_tag {'<' + keyword + '>'},
keyword_end_tag {"</" + keyword + '>'},
header_start_tag {"<header>"},
header_end_tag {"</header>"};
unsigned int header_start_pos {0}, header_end_pos {0};
std::string data_string {""}; // Variable to be returned at the end of the function
// Find the <header> and </header> locations
for (unsigned int line_i = 0; line_i < xml_data.size(); line_i++) {
// Check for the header_start_tag
if (xml_data[line_i] == header_start_tag) {
header_start_pos = line_i;
}
// Check for the header_end_tag
else if (xml_data[line_i] == header_end_tag) {
header_end_pos = line_i;
}
// Stop loop if both the header start and end tags have been found
if ((header_start_pos != 0) && (header_start_pos < header_end_pos))
break;
}
// If the headers were successfully found, find the keyword within the headers
if ((header_start_pos != 0) && (header_end_pos != 0)) {
size_t keyword_start_pos {}, keyword_end_pos {};
// Search lines in header for desired information
for (unsigned int header_i = header_start_pos; header_i < header_end_pos; header_i++) {
keyword_start_pos = xml_data[header_i].find (keyword_start_tag);
keyword_end_pos = xml_data[header_i].find (keyword_end_tag);
if ((keyword_start_pos != std::string::npos) && (keyword_end_pos != std::string::npos)) {
for (unsigned int line_i = keyword_start_pos + keyword_start_tag.size(); line_i < keyword_end_pos; line_i++) {
data_string += xml_data[header_i][line_i];
}
break;
}
}
}
return data_string;
// Empty string = No match found
// String with data = Match found
}
// Search for specific text within the XML's body
unsigned int find_in_xml_body (std::string keyword, Rom_File rom_list[], std::vector <std::string> &xml_data) {
const std::string keyword_start_tag {'<' + keyword},
keyword_end_tag {"/>"};
unsigned int list_size {0};
std::string data_string {""};
size_t keyword_start_pos {}, keyword_end_pos {};
// Search through XML data for all instances of desired information
for (unsigned int line_i = 0; line_i < xml_data.size(); line_i++) {
keyword_start_pos = xml_data[line_i].find (keyword_start_tag);
keyword_end_pos = xml_data[line_i].find (keyword_end_tag);
// A match has been found for the data
if ((keyword_start_pos != std::string::npos) && (keyword_end_pos != std::string::npos)) {
// Variables used to convert string to long
std::string size_str {""};
unsigned long long size_long {0};
data_string = "";
for (unsigned int data_i = keyword_start_pos + keyword_start_tag.size(); data_i < keyword_end_pos; data_i++) {
data_string += xml_data[line_i][data_i];
}
if (list_size + 1 < MAX_LIST_SIZE) {
// Load data from line into rom structure
rom_list[list_size].set_name (find_in_string ("name", data_string));
rom_list[list_size].set_md5 (find_in_string ("md5" , data_string));
rom_list[list_size].set_sha1 (find_in_string ("sha1", data_string));
// Attempt to convert data related to size from a string to a long
size_str = find_in_string ("size", data_string);
try {
size_long = stoull (size_str, nullptr, 10);
rom_list[list_size].set_size (size_long);
}
catch (const std::invalid_argument &bad_arg) { // Argument was not an integer
std::cerr << "\n! String to Long Conversion Error: " << bad_arg.what() << ", Bad Arg."
<< "\n\tEntry: " << rom_list[list_size].get_name()
<< "\n\t Size: " << size_str;
}
catch (const std::out_of_range &bad_range) { // Argument is out of range
std::cerr << "\n! String to Long Conversion Error: " << bad_range.what() << ", Out of Range"
<< "\n\tEntry: " << rom_list[list_size].get_name()
<< "\n\t Size: " << size_str;
}
list_size++;
}
else {
break;
}
}
}
return list_size;
}
// Find a string of text within a string
std::string find_in_string (std::string keyword, std::string input) {
const std::string keyword_start_tag {keyword + "=\""},
keyword_end_tag {"\""};
size_t keyword_start_pos {}, keyword_end_pos {};
std::string data_string {""};
// Find the location of the start tag
keyword_start_pos = input.find (keyword_start_tag);
if (keyword_start_pos != std::string::npos) {
// Find the end tag in a location that comes after the start tag
keyword_end_pos = input.find (keyword_end_tag, keyword_start_pos + keyword_start_tag.size() + 1);
// Data has been found if the start tag and end tag are not npos
if ((keyword_end_pos != std::string::npos) && (keyword_end_pos > keyword_start_pos)) {
for (unsigned int j = keyword_start_pos + keyword_start_tag.size(); j < keyword_end_pos; j++) {
data_string += input[j];
}
}
}
return data_string;
} | 27.866071 | 126 | 0.579729 | Lieutenant-Debaser |
3b76373f85b176cc4fed368925a435e3857faf74 | 1,938 | cpp | C++ | Libraries/RobsJuceModules/rosic/analysis/rosic_PitchDetector.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Libraries/RobsJuceModules/rosic/analysis/rosic_PitchDetector.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Libraries/RobsJuceModules/rosic/analysis/rosic_PitchDetector.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | //#include "rosic_PitchDetector.h"
//using namespace rosic;
// Construction/Destruction:
PitchDetector::PitchDetector() : formantRemover(30)
{
// initialize parameters:
sampleRate = 44100.0;
sampleRateRec = 1.0/sampleRate;
minFundamental = 20.0;
maxFundamental = 10000.0;
minPeriod = 1.0 / maxFundamental;
maxPeriod = 1.0 / minFundamental;
y0 = y1 = y2 = y3 = 0.0;
fracOld = 0.0;
periodEstimate = 0.001;
frequencyEstimate = 1.0 / periodEstimate;
cycleCorrelation = 0.0;
sampleCounter = 0;
formantRemover.setOrder(30);
dcBlocker.setMode(rsOnePoleFilterDD::HIGHPASS_MZT);
dcBlocker.setCutoff(20.0);
dcBlocker.setSampleRate(sampleRate);
lowpass.setMode(FourPoleFilterParameters::LOWPASS_6);
lowpass.useTwoStages(true);
lowpass.setFrequency(50.0);
lowpass.setSampleRate(sampleRate);
envFollower.setMode(EnvelopeFollower::MEAN_ABS);
envFollower.setAttackTime(0.0);
envFollower.setReleaseTime(20.0);
envFollower.setSampleRate(sampleRate);
}
// Setup:
void PitchDetector::setSampleRate(double newSampleRate)
{
if( newSampleRate > 0.0 )
{
sampleRate = newSampleRate;
sampleRateRec = 1.0/sampleRate;
dcBlocker.setSampleRate(sampleRate);
lowpass.setSampleRate(sampleRate);
envFollower.setSampleRate(sampleRate);
}
else
DEBUG_BREAK; // invalid sample-rate
}
void PitchDetector::setMinFundamental(double newMinFundamental)
{
if( newMinFundamental >= 10.0
&& newMinFundamental <= 5000.0
&& newMinFundamental < maxFundamental)
{
minFundamental = newMinFundamental;
maxPeriod = 1.0 / minFundamental;
}
}
void PitchDetector::setMaxFundamental(double newMaxFundamental)
{
if( newMaxFundamental >= 100.0
&& newMaxFundamental <= 20000.0
&& newMaxFundamental > minFundamental)
{
maxFundamental = newMaxFundamental;
minPeriod = 1.0 / maxFundamental;
}
}
| 25.168831 | 63 | 0.701754 | RobinSchmidt |
3b78e97df9a17ef8b3dbc3a2fbd3277645971109 | 769 | cpp | C++ | examples/indent_align_string/false_01.unc.cpp | beardog-ukr/uncrustify-config-examples | 23308192b377107cf287bdb073ae7eccbbf06383 | [
"Unlicense"
] | 1 | 2021-06-23T00:12:23.000Z | 2021-06-23T00:12:23.000Z | examples/indent_align_string/false_01.unc.cpp | beardog-ukr/uncrustify-config-examples | 23308192b377107cf287bdb073ae7eccbbf06383 | [
"Unlicense"
] | null | null | null | examples/indent_align_string/false_01.unc.cpp | beardog-ukr/uncrustify-config-examples | 23308192b377107cf287bdb073ae7eccbbf06383 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <string>
std::string zz = "Lorem ipsum dolor sit amet, \
consectetur adipiscing elit. \
Cras fermentum id diam sit amet consequat.";
std::string z2 = "Lorem ipsum dolor sit amet,"
"consectetur adipiscing elit."
"Cras fermentum id diam sit amet consequat.";
int main()
{
int x = 10;
std::string s = std::string("booo (short)");
if (x<50) {
s = std::string("Lorem ipsum dolor sit amet,"
"consectetur adipiscing elit."
"Cras fermentum id diam sit amet consequat.");
s = ssff(20, "Lorem ipsum dolor sit amet,"
"consectetur adipiscing elit."
"Cras fermentum id diam sit amet consequat.");
}
std::cout << "s is " << s << '\n';
return 0;
} | 26.517241 | 64 | 0.598179 | beardog-ukr |
3b7a9132f2eb951e62f7961b8d82e92d7baa00fa | 2,127 | cc | C++ | desktop_drag_drop_client_egl.cc | zenoalbisser/ozone-egl | 764fa502f28eab052c2f6e9eb992042190c544c4 | [
"BSD-3-Clause"
] | null | null | null | desktop_drag_drop_client_egl.cc | zenoalbisser/ozone-egl | 764fa502f28eab052c2f6e9eb992042190c544c4 | [
"BSD-3-Clause"
] | null | null | null | desktop_drag_drop_client_egl.cc | zenoalbisser/ozone-egl | 764fa502f28eab052c2f6e9eb992042190c544c4 | [
"BSD-3-Clause"
] | null | null | null | /*
* ---------------------------------------------------------------------------------
* Copyright (C) 2015 STMicroelectronics - All Rights Reserved
*
* May be copied or modified under the terms of the LGPL v2.1.
*
* ST makes no warranty express or implied including but not limited to,
* any warranty of
*
* (i) merchantability or fitness for a particular purpose and/or
* (ii) requirements, for a particular purpose in relation to the LICENSED
* MATERIALS, which is provided AS IS, WITH ALL FAULTS. ST does not
* represent or warrant that the LICENSED MATERIALS provided here
* under is free of infringement of any third party patents,
* copyrights, trade secrets or other intellectual property rights.
* ALL WARRANTIES, CONDITIONS OR OTHER TERMS IMPLIED BY LAW ARE
* EXCLUDED TO THE FULLEST EXTENT PERMITTED BY LAW
*
* ---------------------------------------------------------------------------------
*/
#include "ozone/ui/desktop_aura/desktop_drag_drop_client_egl.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/drop_target_event.h"
namespace views {
DesktopDragDropClientEgl::DesktopDragDropClientEgl(
aura::Window* root_window) {
NOTIMPLEMENTED();
}
DesktopDragDropClientEgl::~DesktopDragDropClientEgl() {
NOTIMPLEMENTED();
}
int DesktopDragDropClientEgl::StartDragAndDrop(
const ui::OSExchangeData& data,
aura::Window* root_window,
aura::Window* source_window,
const gfx::Point& root_location,
int operation,
ui::DragDropTypes::DragEventSource source) {
NOTIMPLEMENTED();
return false;
}
void DesktopDragDropClientEgl::DragUpdate(aura::Window* target,
const ui::LocatedEvent& event) {
NOTIMPLEMENTED();
}
void DesktopDragDropClientEgl::Drop(aura::Window* target,
const ui::LocatedEvent& event) {
NOTIMPLEMENTED();
}
void DesktopDragDropClientEgl::DragCancel() {
NOTIMPLEMENTED();
}
bool DesktopDragDropClientEgl::IsDragDropInProgress() {
return false;
}
} // namespace views
| 31.279412 | 84 | 0.64598 | zenoalbisser |
3b7bd09b13852fcf3685def0a40a79b41223cefa | 350 | cpp | C++ | src/decoderms3bits.cpp | leroythelegend/rough_idea_pcars | 07ead73fa04402c860b21039d5aa8c22a33a7d93 | [
"MIT"
] | 4 | 2018-08-09T00:44:01.000Z | 2021-07-03T08:26:39.000Z | src/decoderms3bits.cpp | ejmhub/rough_idea_project_cars | d7cd062cbff2a1df82b5a623205d9c1920c41b1c | [
"MIT"
] | 1 | 2018-02-02T10:44:43.000Z | 2018-02-02T10:44:43.000Z | src/decoderms3bits.cpp | ejmhub/rough_idea_project_cars | d7cd062cbff2a1df82b5a623205d9c1920c41b1c | [
"MIT"
] | 1 | 2018-11-24T09:12:51.000Z | 2018-11-24T09:12:51.000Z | #include "decoderms3bits.h"
#include "exception.h"
namespace pcars {
Decoder_MS3bits::Decoder_MS3bits()
: num_(0) {
}
Decoder_MS3bits::~Decoder_MS3bits() {
}
void Decoder_MS3bits::decode(const PCars_Data & data, Position & position) {
num_ = (data.at(position) >> 4) & 7;
}
unsigned int Decoder_MS3bits::ms3bits() const {
return num_;
}
}
| 14.583333 | 76 | 0.702857 | leroythelegend |
3b7c4cc83c8dfa32e9e58d8596ccd7e8ca91ca99 | 1,212 | cpp | C++ | lib/IDEDiagnostics.cpp | clagah/mull | 9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99 | [
"Apache-2.0"
] | null | null | null | lib/IDEDiagnostics.cpp | clagah/mull | 9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99 | [
"Apache-2.0"
] | null | null | null | lib/IDEDiagnostics.cpp | clagah/mull | 9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99 | [
"Apache-2.0"
] | 1 | 2019-06-10T02:43:04.000Z | 2019-06-10T02:43:04.000Z | #include "mull/IDEDiagnostics.h"
#include "mull/MutationPoint.h"
#include <llvm/IR/DebugInfoMetadata.h>
#include <llvm/IR/Instruction.h>
#include <llvm/Support/raw_ostream.h>
using namespace mull;
using namespace llvm;
void NormalIDEDiagnostics::report(mull::MutationPoint *mutationPoint,
bool killed) {
if (diagnostics == Diagnostics::None) {
return;
}
if (diagnostics == Diagnostics::Survived && killed) {
return;
}
if (diagnostics == Diagnostics::Killed && !killed) {
return;
}
const std::string &diagnostics = mutationPoint->getDiagnostics();
if (diagnostics.empty()) {
return;
}
Instruction *instruction =
dyn_cast<Instruction>(mutationPoint->getOriginalValue());
if (instruction->getMetadata(0) == nullptr) {
return;
}
const DebugLoc &debugLoc = instruction->getDebugLoc();
std::string fileNameOrNil = debugLoc->getFilename().str();
std::string lineOrNil = std::to_string(debugLoc->getLine());
std::string columnOrNil = std::to_string(debugLoc->getColumn());
errs() << "\n";
errs() << fileNameOrNil << ":" << lineOrNil << ":" << columnOrNil << ": "
<< "warning: " << diagnostics << "\n";
}
| 25.787234 | 75 | 0.65099 | clagah |
3b7ca17731a5b04fe48163b077b1b540d96b64e7 | 1,108 | cpp | C++ | structure/develop/vertex-set-path-sum.cpp | neal2018/library | a19f3b29f3355e32f7e5f6768a7943db48fcdff7 | [
"Unlicense"
] | 127 | 2019-07-22T03:52:01.000Z | 2022-03-11T07:20:21.000Z | structure/develop/vertex-set-path-sum.cpp | neal2018/library | a19f3b29f3355e32f7e5f6768a7943db48fcdff7 | [
"Unlicense"
] | 39 | 2019-09-16T12:04:53.000Z | 2022-03-29T15:43:35.000Z | structure/develop/vertex-set-path-sum.cpp | neal2018/library | a19f3b29f3355e32f7e5f6768a7943db48fcdff7 | [
"Unlicense"
] | 29 | 2019-08-10T11:27:06.000Z | 2022-03-11T07:02:43.000Z | #include "super-link-cut-tree.cpp"
/**
* @brief Vertex Set Path Sum
*/
using T = int64_t;
// ้
ๅปถไผๆฌใใใใใใฎไฝ็จ็ด
struct Lazy {
// ๅไฝๅ
Lazy() {}
// ๅๆๅ
Lazy(T v) {}
// ้
ๅปถไผๆฌ
void propagate(const Lazy &p) {}
};
// Light-edge ใฎๆ
ๅ ฑ
template< typename Lazy >
struct LInfo {
// ๅไฝๅ
(ใญใผใฎๅคใฏใขใฏใปในใใชใใฎใงๆชๅๆๅใงใใใ
LInfo() {}
// ๅๆๅ
LInfo(T v) {}
// l, r ใฏ Splay-tree ใฎๅญ (ๅ็ไธใๅใใผใๅบๅฅใฏใชใ)
void update(const LInfo &l, const LInfo &r) {}
// ้จๅๆจใธใฎ้
ๅปถไผๆฌ
void propagate(const Lazy &p) {}
};
// Heavy-edge ใฎๆ
ๅ ฑ
template< typename LInfo, typename Lazy >
struct Info {
T v;
T sum;
// ๅไฝๅ
(ใญใผใฎๅคใฏใขใฏใปในใใชใใฎใงๆชๅๆๅใงใใใ
Info() : sum{0} {}
// ๅๆๅ
Info(T v) : v{v} {}
// ๅ่ปข
void toggle() {}
// pใ่ฆช, cใheavy-edgeใง็ตใฐใใๅญ, lใใใไปฅๅคใฎๅญ
void update(const Info &p, const Info &c, const LInfo &l) {
sum = p.sum + v + c.sum;
}
// ่ฆชใจ light-edge ใง็นใใ
LInfo link() const { return LInfo(); }
// ้
ๅปถไผๆฌ
void propagate(const Lazy &p) {}
// light-edgeใซๅฏพใใ้
ๅปถไผๆฌ
// pathใจsubtreeใฎ้
ๅปถไผๆฌใไธกๆนใใๅ ดๅใซๅฎ่ฃ
ใใ
void propagate_light(const Lazy &p) {}
};
using LCT = SuperLinkCutTree< Info, LInfo, Lazy >;
| 15.605634 | 61 | 0.610108 | neal2018 |
3b85c60b7bb76ea7e59aa9a287054ad60c3046e2 | 15,328 | cpp | C++ | modules/diagnostics/diagnostics.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | null | null | null | modules/diagnostics/diagnostics.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | null | null | null | modules/diagnostics/diagnostics.cpp | Clyde-Beep/sporks-test | c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07 | [
"Apache-2.0"
] | null | null | null | /************************************************************************************
*
* Sporks, the learning, scriptable Discord bot!
*
* Copyright 2019 Craig Edwards <[email protected]>
*
* 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 <sporks/bot.h>
#include <sporks/regex.h>
#include <sporks/modules.h>
#include <sporks/stringops.h>
#include <sporks/database.h>
#include <sstream>
#include <chrono>
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
struct guild_count_data
{
size_t guilds;
size_t members;
};
struct shard_data
{
std::chrono::time_point<std::chrono::steady_clock> last_message;
};
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
return "";
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
/**
* Provides diagnostic commands for monitoring the bot and debugging it interactively while it's running.
*/
class DiagnosticsModule : public Module
{
PCRE* diagnosticmessage;
std::vector<shard_data> shards;
double microseconds_ping;
public:
DiagnosticsModule(Bot* instigator, ModuleLoader* ml) : Module(instigator, ml)
{
ml->Attach({ I_OnMessage, I_OnRestEnd }, this);
diagnosticmessage = new PCRE("^sudo(\\s+(.+?))$", true);
for (uint32_t i = 0; i < bot->core.get_shard_mgr().shard_max_count; ++i) {
shards.push_back({});
}
}
virtual ~DiagnosticsModule()
{
delete diagnosticmessage;
}
virtual std::string GetVersion()
{
/* NOTE: This version string below is modified by a pre-commit hook on the git repository */
std::string version = "$ModVer 24$";
return "1.0." + version.substr(8,version.length() - 9);
}
virtual std::string GetDescription()
{
return "Diagnostic Commands (sudo), '@Sporks sudo'";
}
virtual bool OnRestEnd(std::chrono::steady_clock::time_point start_time, uint16_t code)
{
microseconds_ping = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start_time).count();
return true;
}
virtual bool OnMessage(const modevent::message_create &message, const std::string& clean_message, bool mentioned, const std::vector<std::string> &stringmentions)
{
std::vector<std::string> param;
std::string botusername = bot->user.username;
aegis::gateway::objects::message msg = message.msg;
shards[message.shard.get_id()].last_message = std::chrono::steady_clock::now();
if (mentioned && diagnosticmessage->Match(clean_message, param) && param.size() >= 3) {
aegis::gateway::objects::message msg = message.msg;
std::stringstream tokens(trim(param[2]));
std::string subcommand;
tokens >> subcommand;
bot->core.log->info("SUDO: <{}> {}", msg.get_user().get_username(), clean_message);
/* Get owner snowflake id from config file */
int64_t owner_id = from_string<int64_t>(Bot::GetConfig("owner"), std::dec);
/* Only allow these commands to the bot owner */
if (msg.author.id.get() == owner_id) {
if (param.size() < 3) {
/* Invalid number of parameters */
EmbedSimple("Sudo make me a sandwich.", msg.get_channel_id().get());
} else {
/* Module list command */
if (lowercase(subcommand) == "modules") {
std::stringstream s;
// NOTE: GetModuleList's reference is safe from within a module event
const ModMap& modlist = bot->Loader->GetModuleList();
s << "```diff" << std::endl;
s << fmt::format("- โญโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ") << std::endl;
s << fmt::format("- โ Filename | Version | Description |") << std::endl;
s << fmt::format("- โโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค") << std::endl;
for (auto mod = modlist.begin(); mod != modlist.end(); ++mod) {
s << fmt::format("+ โ {:23} | {:9} | {:46} |", mod->first, mod->second->GetVersion(), mod->second->GetDescription()) << std::endl;
}
s << fmt::format("+ โฐโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ") << std::endl;
s << "```";
aegis::channel* c = bot->core.find_channel(msg.get_channel_id().get());
if (c) {
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == c->get_guild().get_id()) {
c->create_message(s.str());
bot->sent_messages++;
}
}
} else if (lowercase(subcommand) == "load") {
/* Load a module */
std::string modfile;
tokens >> modfile;
if (bot->Loader->Load(modfile)) {
EmbedSimple("Loaded module: " + modfile, msg.get_channel_id().get());
} else {
EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.get_channel_id().get());
}
} else if (lowercase(subcommand) == "unload") {
/* Unload a module */
std::string modfile;
tokens >> modfile;
if (modfile == "module_diagnostics.so") {
EmbedSimple("I suppose you think that's funny, dont you? *I'm sorry. can't do that, dave.*", msg.get_channel_id().get());
} else {
if (bot->Loader->Unload(modfile)) {
EmbedSimple("Unloaded module: " + modfile, msg.get_channel_id().get());
} else {
EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.get_channel_id().get());
}
}
} else if (lowercase(subcommand) == "reload") {
/* Reload a currently loaded module */
std::string modfile;
tokens >> modfile;
if (modfile == "module_diagnostics.so") {
EmbedSimple("I suppose you think that's funny, dont you? *I'm sorry. can't do that, dave.*", msg.get_channel_id().get());
} else {
if (bot->Loader->Reload(modfile)) {
EmbedSimple("Reloaded module: " + modfile, msg.get_channel_id().get());
} else {
EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.get_channel_id().get());
}
}
} else if (lowercase(subcommand) == "threadstats") {
std::string result = exec("top -b -n1 -d0 | head -n7 && top -b -n1 -d0 -H | grep \"./bot\\|run.sh\" | grep -v grep | grep -v perl");
aegis::channel* c = bot->core.find_channel(msg.get_channel_id().get());
if (c) {
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == c->get_guild().get_id()) {
c->create_message("```" + result + "```");
bot->sent_messages++;
}
}
} else if (lowercase(subcommand) == "lock") {
std::string keyword;
std::getline(tokens, keyword);
keyword = trim(keyword);
db::query("UPDATE infobot SET locked = 1 WHERE key_word = '?'", {keyword});
EmbedSimple("**Locked** key word: " + keyword, msg.get_channel_id().get());
} else if (lowercase(subcommand) == "unlock") {
std::string keyword;
std::getline(tokens, keyword);
keyword = trim(keyword);
db::query("UPDATE infobot SET locked = 0 WHERE key_word = '?'", {keyword});
EmbedSimple("**Unlocked** key word: " + keyword, msg.get_channel_id().get());
} else if (lowercase(subcommand) == "sql") {
std::string sql;
std::getline(tokens, sql);
sql = trim(sql);
db::resultset rs = db::query(sql, {});
std::stringstream w;
if (rs.size() == 0) {
if (db::error() != "") {
EmbedSimple("SQL Error: " + db::error(), msg.get_channel_id().get());
} else {
EmbedSimple("Successfully executed, no rows returned.", msg.get_channel_id().get());
}
} else {
w << "- " << sql << std::endl;
auto check = rs[0].begin();
w << "+ Rows Returned: " << rs.size() << std::endl;
for (auto name = rs[0].begin(); name != rs[0].end(); ++name) {
if (name == rs[0].begin()) {
w << " โญ";
}
w << "โโโโโโโโโโโโโโโโโโโโ";
check = name;
w << (++check != rs[0].end() ? "โฌ" : "โฎ\n");
}
w << " ";
for (auto name = rs[0].begin(); name != rs[0].end(); ++name) {
w << fmt::format("โ{:20}", name->first.substr(0, 20));
}
w << "โ" << std::endl;
for (auto name = rs[0].begin(); name != rs[0].end(); ++name) {
if (name == rs[0].begin()) {
w << " โ";
}
w << "โโโโโโโโโโโโโโโโโโโโ";
check = name;
w << (++check != rs[0].end() ? "โผ" : "โค\n");
}
for (auto row : rs) {
if (w.str().length() < 1900) {
w << " ";
for (auto field : row) {
w << fmt::format("โ{:20}", field.second.substr(0, 20));
}
w << "โ" << std::endl;
}
}
for (auto name = rs[0].begin(); name != rs[0].end(); ++name) {
if (name == rs[0].begin()) {
w << " โฐ";
}
w << "โโโโโโโโโโโโโโโโโโโโ";
check = name;
w << (++check != rs[0].end() ? "โด" : "โฏ\n");
}
aegis::channel* c = bot->core.find_channel(msg.get_channel_id().get());
if (c) {
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == c->get_guild().get_id()) {
c->create_message("```diff\n" + w.str() + "```");
bot->sent_messages++;
}
}
}
} else if (lowercase(subcommand) == "reconnect") {
uint32_t snum = 0;
tokens >> snum;
auto & s = bot->core.get_shard_by_id(snum);
if (s.is_connected()) {
EmbedSimple("Shard is already connected.", msg.get_channel_id().get());
} else {
bot->core.get_shard_mgr().queue_reconnect(s);
}
} else if (lowercase(subcommand) == "forcereconnect") {
uint32_t snum = 0;
tokens >> snum;
auto & s = bot->core.get_shard_by_id(snum);
if (s.is_connected()) {
EmbedSimple("Shard is already connected.", msg.get_channel_id().get());
} else {
s.connect();
}
} else if (lowercase(subcommand) == "disconnect") {
uint32_t snum = 0;
tokens >> snum;
auto & s = bot->core.get_shard_by_id(snum);
bot->core.get_shard_mgr().close(s);
EmbedSimple("Shard disconnected.", msg.get_channel_id().get());
} else if (lowercase(subcommand) == "restart") {
EmbedSimple("Restarting...", msg.get_channel_id().get());
::sleep(5);
/* Note: exit here will restart, because we run the bot via run.sh which restarts the bot on quit. */
exit(0);
} else if (lowercase(subcommand) == "ping") {
aegis::channel* c = bot->core.find_channel(msg.get_channel_id().get());
if (c) {
std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
aegis::gateway::objects::message m = c->create_message("Pinging...", msg.get_channel_id().get()).get();
double microseconds_ping = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start_time).count();
m.delete_message();
EmbedSimple(fmt::format("**Pong!** REST Response time: {:.3f} ms", microseconds_ping / 1000, 4), msg.get_channel_id().get());
}
} else if (lowercase(subcommand) == "lookup") {
int64_t gnum = 0;
tokens >> gnum;
aegis::guild* guild = bot->core.find_guild(gnum);
if (guild) {
EmbedSimple(fmt::format("**Guild** {} is on **shard** #{}", gnum, guild->shard_id), msg.get_channel_id().get());
} else {
EmbedSimple(fmt::format("**Guild** {} is not in my list!", gnum), msg.get_channel_id().get());
}
} else if (lowercase(subcommand) == "shardstats") {
std::stringstream w;
w << "```diff\n";
uint64_t count = 0, u_count = 0;
count = bot->core.get_shard_transfer();
u_count = bot->core.get_shard_u_transfer();
std::vector<guild_count_data> shard_guild_c(bot->core.shard_max_count);
for (auto & v : bot->core.guilds)
{
++shard_guild_c[v.second->shard_id].guilds;
shard_guild_c[v.second->shard_id].members += v.second->get_members().size();
}
w << fmt::format(" Total transfer: {} (U: {} | {:.2f}%) Memory usage: {}\n", aegis::utility::format_bytes(count), aegis::utility::format_bytes(u_count), (count / (double)u_count)*100, aegis::utility::format_bytes(aegis::utility::getCurrentRSS()));
w << fmt::format("- โญโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโฌโโโโโโโโฌโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโฌโโโโโโโโโโโโฌโโโโโโโโโโโฎ\n");
w << fmt::format("- โshard#โ sequenceโserversโmembersโuptime โlast messageโtransferredโreconnectsโ\n");
w << fmt::format("- โโโโโโโโผโโโโโโโโโโโผโโโโโโโโผโโโโโโโโผโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโผโโโโโโโโโโโโผโโโโโโโโโโโค\n");
for (uint32_t i = 0; i < bot->core.shard_max_count; ++i)
{
auto & s = bot->core.get_shard_by_id(i);
auto time_count = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - shards[s.get_id()].last_message).count();
std::string divisor = "ms";
if (time_count > 1000) {
time_count /= 1000;
divisor = "s ";
}
if (s.is_connected())
w << "+ ";
else
w << " ";
w << fmt::format("|{:6}|{:10}|{:7}|{:7}|{:>16}|{:10}{:2}|{:>11}|{:10}|",
s.get_id(),
s.get_sequence(),
shard_guild_c[s.get_id()].guilds,
shard_guild_c[s.get_id()].members,
s.uptime_str(),
time_count,
divisor,
s.get_transfer_str(),
s.counters.reconnects);
if (message.shard.get_id() == s.get_id()) {
w << " *\n";
} else {
w << "\n";
}
}
w << fmt::format("+ โฐโโโโโโโดโโโโโโโโโโโดโโโโโโโโดโโโโโโโโดโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโดโโโโโโโโโโโโดโโโโโโโโโโโฏ\n");
w << "```";
aegis::channel *channel = bot->core.find_channel(msg.get_channel_id());
if (channel) {
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == channel->get_guild().get_id()) {
channel->create_message(w.str());
bot->sent_messages++;
}
}
} else {
/* Invalid command */
EmbedSimple("Sudo **what**? I don't know what that command means.", msg.get_channel_id().get());
}
}
} else {
/* Access denied */
EmbedSimple("Make your own sandwich, mortal.", msg.get_channel_id().get());
}
/* Eat the event */
return false;
}
return true;
}
};
ENTRYPOINT(DiagnosticsModule);
| 38.41604 | 254 | 0.545472 | Clyde-Beep |
3b872581b6730fc593c5e0c4436e78be88e664f4 | 5,604 | hpp | C++ | src/Utilities/FakeVirtual.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/Utilities/FakeVirtual.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/Utilities/FakeVirtual.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <type_traits>
#include <typeinfo>
#include "ErrorHandling/Error.hpp"
#include "Utilities/PrettyType.hpp"
#include "Utilities/Requires.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TypeTraits.hpp"
/// \ingroup UtilitiesGroup
/// \brief Define a function that acts similarly to a virtual
/// function, but can take template parameters.
///
/// \details `DEFINE_FAKE_VIRTUAL(func)` defines the function
/// `fake_virtual_func` and the struct `FakeVirtualInherit_func`. It
/// should usually be called in a detail namespace.
///
/// A base class `Base` using this functionality should define a type
/// \code
/// using Inherit = FakeVirtualInherit_func<Base>;
/// \endcode
/// and a member function `func` wrapping `fake_virtual_func`, with
/// the wrapper passing the derived classes as a typelist as the first
/// template argument and the `this` pointer as the first normal
/// argument.
///
/// Derived classes should then inherit from `Base::Inherit` instead
/// of directly from `Base`. (`Base::Inherit` inherits from `Base`.)
///
/// If the base class has no pure virtual functions remaining it will
/// generally be desirable to mark the constructors and assignment
/// operators protected so that a bare base class cannot be instantiated.
///
/// If it is necessary to use multiple fake virtual functions with the
/// same base class, the `Inherit` definition can nest the fake
/// virtual classes:
/// \code
/// using Inherit = FakeVirtualInherit_func1<FakeVirtualInherit_func2<Base>>;
/// \endcode
///
/// \example
/// \snippet Test_FakeVirtual.cpp fake_virtual_example
///
/// \see call_with_dynamic_type
#define DEFINE_FAKE_VIRTUAL(function) \
/* This struct is only needed for producing an error if the function */ \
/* is not overridden in the derived class. */ \
template <typename Base> \
struct FakeVirtualInherit_##function : public Base { \
using Base::Base; \
/* clang-tidy: I think "= delete" was overlooked in the guideline */ \
void function(...) const = delete; /* NOLINT */ \
}; \
\
template <typename Classes, typename... TArgs, typename Base, \
typename... Args> \
decltype(auto) fake_virtual_##function(Base* obj, Args&&... args) noexcept { \
/* clang-tidy: macro arg in parentheses */ \
return call_with_dynamic_type< \
decltype(obj->template function<TArgs...>(args...)), /* NOLINT */ \
Classes>( \
obj, [&args...](auto* const dynamic_obj) noexcept -> decltype(auto) { \
static_assert( \
cpp17::is_base_of_v<typename Base::Inherit, \
std::decay_t<decltype(*dynamic_obj)>>, \
"Derived class does not inherit from Base::Inherit"); \
/* clang-tidy: macro arg in parentheses */ \
return dynamic_obj->template function<TArgs...>(/* NOLINT */ \
std::forward<Args>( \
args)...); \
}); \
}
/// \cond
template <typename Result, typename Classes, typename Base, typename Callable,
Requires<(tmpl::size<Classes>::value == 0)> = nullptr>
[[noreturn]] Result call_with_dynamic_type(Base* const obj,
Callable&& /*f*/) noexcept {
ERROR("Class " << pretty_type::get_runtime_type_name(*obj)
<< " is not registered with "
<< pretty_type::get_name<std::remove_const_t<Base>>());
}
/// \endcond
/// \ingroup Utilities
/// \brief Call a functor with the derived type of a base class pointer.
///
/// \details Calls functor with obj cast to type `T*` where T is the
/// dynamic type of `*obj`. The decay type of `T` must be in the
/// provided list of classes.
///
/// \see DEFINE_FAKE_VIRTUAL
///
/// \tparam Result the return type
/// \tparam Classes the typelist of derived classes
template <typename Result, typename Classes, typename Base, typename Callable,
Requires<(tmpl::size<Classes>::value != 0)> = nullptr>
Result call_with_dynamic_type(Base* const obj, Callable&& f) noexcept {
using Derived = tmpl::front<Classes>;
using DerivedPointer =
std::conditional_t<std::is_const<Base>::value, Derived const*, Derived*>;
// If we want to allow creatable classses to return objects of
// types derived from themselves then this will have to be changed
// to a dynamic_cast, but we probably won't want that and this
// form is significantly faster.
return typeid(*obj) == typeid(Derived)
? std::forward<Callable>(f)(static_cast<DerivedPointer>(obj))
: call_with_dynamic_type<Result, tmpl::pop_front<Classes>>(
obj, std::forward<Callable>(f));
}
| 48.310345 | 80 | 0.563169 | marissawalker |
3b87ec6a310a6a48f6766cd44c12d4082e622cd7 | 238 | cpp | C++ | 2017_05_29_GameStateManager/IGameState_old.cpp | DarthDementous/2017_05_29_GameStateManagement | 207d3bbd2d5184a32a1437d4417343b696f60e60 | [
"MIT"
] | null | null | null | 2017_05_29_GameStateManager/IGameState_old.cpp | DarthDementous/2017_05_29_GameStateManagement | 207d3bbd2d5184a32a1437d4417343b696f60e60 | [
"MIT"
] | null | null | null | 2017_05_29_GameStateManager/IGameState_old.cpp | DarthDementous/2017_05_29_GameStateManagement | 207d3bbd2d5184a32a1437d4417343b696f60e60 | [
"MIT"
] | null | null | null | #include "IGameState.h"
#include "_2017_05_29_GameStateManagerApp.h"
#include <Application.h>
#pragma region Constructors
IGameState::IGameState(aie::Application* a_app) : m_app(a_app) {}
IGameState::~IGameState()
{
}
#pragma endregion
| 19.833333 | 65 | 0.773109 | DarthDementous |
Subsets and Splits