blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
5a85496ee915cd42b4b397c5f47f7bef32143f6b
2458387683093f9a3561acac2795aad9ee2b061f
/include/Foto.h
7d7218d2aa66f8c809d6fec7f855cbf501e924b6
[]
no_license
matteo95g/tareaP4_2017
fb9b0733076bc361dcba90c6a3293c24b47b8360
b7c0b22568805de06c969024f3a7246621a415bc
refs/heads/master
2021-01-01T19:49:25.637287
2017-07-29T01:14:15
2017-07-29T01:14:15
98,699,203
0
0
null
null
null
null
UTF-8
C++
false
false
562
h
#ifndef FOTO_H_ #define FOTO_H_ #include <string> #include "Multimedia.h" using namespace std; class Foto : public Multimedia { string imagen; string formato; string tamanio; string texto; public: Foto(); Foto(int id, Fecha* fecha, Usuario* emisor, string imagen, string formato, string tamanio, string texto); string getImagen(); void setImagen(string imagen); string getFormato(); void setFormato(string formato); string getTamanio(); void setTamanio(string tamanio); string getTexto(); void setTexto(string texto); ~Foto(); }; #endif
[ "matteo95guerrieri@gmail.com" ]
matteo95guerrieri@gmail.com
2c8f6fdf79ab0f8cdb79fcf5dc73a8195b2ca38d
5f22ee5db30fbe434489a329edd05289220e5b51
/Intersectii/vector2D.h
c407281a779b39f549e550ed7c9fe6949167bb12
[]
no_license
botezatumihaicatalin/Geometry-Homeworks
ed3791b64a1be2f973b113d3636150cc6987bd47
8e0761f5f087541b8eae698399432616d96ddd20
refs/heads/master
2020-05-20T16:50:30.222061
2015-11-15T18:59:53
2015-11-15T18:59:53
25,073,297
1
1
null
null
null
null
UTF-8
C++
false
false
441
h
#ifndef VECTOR2D_H #define VECTOR2D_H #include "point2D.h" class Vector2D { public: double X, Y; Vector2D(const double & xVect , const double & yVect) : X(xVect) , Y(yVect) {}; Vector2D(const Point2D & point) : Vector2D(point.X , point.Y) {}; Vector2D(const Point2D & point1 , const Point2D & point2) : X(point2.X - point1.X) , Y(point2.Y - point1.Y) {}; double CrossProduct(const Vector2D & other) const; }; #endif /* VECTOR2D_H */
[ "botezatu.mihaicatalin@gmail.com" ]
botezatu.mihaicatalin@gmail.com
0b98d3d29147e5c0111463bc43131ad76e1a5dab
dd598a9bbbd8f7f065df846d79349b753f2d22ae
/src/libdriver/devicetree/FdtRoot.cpp
6f272da199a4ab1e020e345fb32b7f6018d2138c
[ "MIT" ]
permissive
skyformat99/chino-os
830e71b920b5bcc944729f1be5722462eb7d1122
cb6c74278470595741766eaa72420d2ac8a6632b
refs/heads/master
2020-03-28T02:39:41.539722
2018-09-04T07:57:51
2018-09-04T07:57:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,082
cpp
// // Kernel Device // #include "Fdt.hpp" #include <libbsp/bsp.hpp> #include <kernel/kdebug.hpp> #include <kernel/device/DeviceManager.hpp> #include <libfdt/libfdt.h> using namespace Chino; using namespace Chino::Device; class FdtRootDriver : public Driver { public: virtual void Install() override { auto fdt = BSPGetFdtData(); std::vector<ObjectPtr<FDTDevice>> fdtDevices; int depth = 0; auto first_node = fdt_next_node(fdt.data(), -1, &depth); if (first_node >= 0) ForeachNode(fdtDevices, fdt.data(), first_node, depth); for (auto& device : fdtDevices) g_DeviceMgr->InstallDevice(device); } private: void ForeachNode(std::vector<ObjectPtr<FDTDevice>>& fdtDevices, const void* fdt, int node, int depth) { fdtDevices.emplace_back(MakeObject<FDTDevice>(fdt, node, depth)); int subnode; fdt_for_each_subnode(subnode, fdt, node) { ForeachNode(fdtDevices, fdt, subnode, fdt_node_depth(fdt, subnode)); } } }; Chino::ObjectPtr<Driver> Chino::Device::BSPInstallRootDriver(const BootParameters& bootParams) { return MakeObject<FdtRootDriver>(); }
[ "sunnycase@live.cn" ]
sunnycase@live.cn
1007db92c5c991fe1f3ac54495cb0e3683c4fab3
4fe80f71bbd5bb0bcc68c85342e796756b6a1658
/function.cpp
cb2ec1dd16dd1ea9dafb80825822de010c707f42
[]
no_license
Intiser/SEUSummerDataStructureLab
d214fbf9661def3f6f67168e0c34fe94505d9f67
7b422b68922d30ae24b4c346734fc8389e73e85c
refs/heads/master
2020-06-18T08:55:18.579548
2019-07-13T16:43:16
2019-07-13T16:43:16
196,241,989
1
0
null
null
null
null
UTF-8
C++
false
false
518
cpp
#include<stdio.h> #include<iostream> using namespace std; /*** a sample code to show the sample functions ***/ /** function for sum **/ int sum(int a, int b, int c){ return a+b+c; } /** function for multiply **/ int multiply(int a,int b){ return a*b; } /** function for printing a number **/ void printValue(int n){ printf("Value = %d\n",n); } int main(){ int a,b,c,d; cin>>a>>b>>c>>d; int val = sum(a,b,c); printValue(val); int mul = multiply(val,d); printValue(mul); }
[ "Intiser@users.noreply.github.com" ]
Intiser@users.noreply.github.com
13a8e7f6c0c29a80278b7bf605771a2e0b47a488
c322776b39fd9a7cd993f483a5384b700b0c520e
/cegui.mod/cegui/src/WindowRendererSets/Falagard/FalTabButton.cpp
2d34cdf59d7def30f105efa3aa5e6516ed68e283
[ "Zlib", "BSD-3-Clause", "MIT" ]
permissive
maxmods/bah.mod
c1af2b009c9f0c41150000aeae3263952787c889
6b7b7cb2565820c287eaff049071dba8588b70f7
refs/heads/master
2023-04-13T10:12:43.196598
2023-04-04T20:54:11
2023-04-04T20:54:11
14,444,179
28
26
null
2021-11-01T06:50:06
2013-11-16T08:29:27
C++
UTF-8
C++
false
false
2,906
cpp
/*********************************************************************** filename: FalTabTabButton.cpp created: Fri Jul 8 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "FalTabButton.h" #include "falagard/CEGUIFalWidgetLookManager.h" #include "falagard/CEGUIFalWidgetLookFeel.h" #include "elements/CEGUITabButton.h" #include "elements/CEGUITabControl.h" // Start of CEGUI namespace section namespace CEGUI { const utf8 FalagardTabButton::TypeName[] = "Falagard/TabButton"; FalagardTabButton::FalagardTabButton(const String& type) : WindowRenderer(type, "TabButton") { } void FalagardTabButton::render() { TabButton* w = (TabButton*)d_window; // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); TabControl* tc = static_cast<TabControl*>(w->getParent()->getParent()); String state; String prefix((tc->getTabPanePosition() == TabControl::Top) ? "Top" : "Bottom"); if (w->isDisabled()) state = "Disabled"; else if (w->isSelected()) state = "Selected"; else if (w->isPushed()) state = "Pushed"; else if (w->isHovering()) state = "Hover"; else state = "Normal"; if (!wlf.isStateImageryPresent(prefix + state)) { state = "Normal"; if (!wlf.isStateImageryPresent(prefix + state)) prefix = ""; } wlf.getStateImagery(prefix + state).render(*w); } } // End of CEGUI namespace section
[ "woollybah@b77917fb-863c-0410-9a43-030a88dac9d3" ]
woollybah@b77917fb-863c-0410-9a43-030a88dac9d3
aa7dd46b5ad3cc9fb5d7338e6a1ddf542448cf51
5386865e2ea964397b8127aba4b2592d939cd9f2
/grupa C/olimpiada/oblasten/2011/raboti/Sofia/Sofia/C/MBS/roses.cpp
ba064d8c7021eadce543b4bc0cd7cb5275f1d017
[]
no_license
HekpoMaH/Olimpiads
e380538b3de39ada60b3572451ae53e6edbde1be
d358333e606e60ea83e0f4b47b61f649bd27890b
refs/heads/master
2021-07-07T14:51:03.193642
2017-10-04T16:38:11
2017-10-04T16:38:11
105,790,126
2
0
null
null
null
null
UTF-8
C++
false
false
546
cpp
#include <iostream> using namespace std; int main(){ short int m, n, k; cin >> m >> n >> k; short int arr[m][n], i, j; short int curr, maxr = -1, sum = 0; for(i = 0; i < m; i++){ for(j = 0; j < n; j++){ cin >> arr[i][j]; sum += arr[i][j]; if(i != 0 && j != 0){ curr = arr[i][j]+arr[i-1][j]+arr[i][j-1]+arr[i-1][j-1]; if(curr > maxr) maxr = curr; } } } cout << sum-maxr << endl; return 0; }
[ "dgg30" ]
dgg30
6af21d6027349943363f738a34a1f591b5a71d4a
f6a7feffcf3a7f150d92a84a615ed18442abb410
/QtPrinter/QtRptProject/QtRptDesigner/tmp-win32/moc_TContainerLine.cpp
463f8522c498ae78d005dc6c843cecdc47240b2c
[]
no_license
echo95200/QtWorkSpace
3d84b4a128e9ce463c6d57ff34f2644a792fedd2
a893e70385f7caa49d08c07c3cc6059b869a5162
refs/heads/master
2020-03-19T06:17:22.553536
2018-06-12T15:54:17
2018-06-12T15:54:17
136,007,524
0
0
null
null
null
null
UTF-8
C++
false
false
6,927
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'TContainerLine.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../TContainerLine.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'TContainerLine.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.7.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_TContainerLine_t { QByteArrayData data[13]; char stringdata0[118]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_TContainerLine_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_TContainerLine_t qt_meta_stringdata_TContainerLine = { { QT_MOC_LITERAL(0, 0, 14), // "TContainerLine" QT_MOC_LITERAL(1, 15, 11), // "lineChanged" QT_MOC_LITERAL(2, 27, 0), // "" QT_MOC_LITERAL(3, 28, 13), // "delItemInTree" QT_MOC_LITERAL(4, 42, 15), // "geomContChanged" QT_MOC_LITERAL(5, 58, 7), // "newRect" QT_MOC_LITERAL(6, 66, 9), // "m_inFocus" QT_MOC_LITERAL(7, 76, 5), // "value" QT_MOC_LITERAL(8, 82, 4), // "Line" QT_MOC_LITERAL(9, 87, 5), // "OldP1" QT_MOC_LITERAL(10, 93, 5), // "OldP2" QT_MOC_LITERAL(11, 99, 9), // "arrowStar" QT_MOC_LITERAL(12, 109, 8) // "arrowEnd" }, "TContainerLine\0lineChanged\0\0delItemInTree\0" "geomContChanged\0newRect\0m_inFocus\0" "value\0Line\0OldP1\0OldP2\0arrowStar\0" "arrowEnd" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_TContainerLine[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 5, 48, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 2, 34, 2, 0x08 /* Private */, 3, 0, 39, 2, 0x08 /* Private */, 4, 2, 40, 2, 0x08 /* Private */, 6, 1, 45, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::QRect, QMetaType::QRect, 2, 2, QMetaType::Void, QMetaType::Void, QMetaType::QRect, QMetaType::QRect, 2, 5, QMetaType::Void, QMetaType::Bool, 7, // properties: name, type, flags 8, QMetaType::QLineF, 0x00095103, 9, QMetaType::QRect, 0x00095103, 10, QMetaType::QRect, 0x00095103, 11, QMetaType::Bool, 0x00095003, 12, QMetaType::Bool, 0x00095103, 0 // eod }; void TContainerLine::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { TContainerLine *_t = static_cast<TContainerLine *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->lineChanged((*reinterpret_cast< QRect(*)>(_a[1])),(*reinterpret_cast< QRect(*)>(_a[2]))); break; case 1: _t->delItemInTree(); break; case 2: _t->geomContChanged((*reinterpret_cast< QRect(*)>(_a[1])),(*reinterpret_cast< QRect(*)>(_a[2]))); break; case 3: _t->m_inFocus((*reinterpret_cast< bool(*)>(_a[1]))); break; default: ; } } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty) { TContainerLine *_t = static_cast<TContainerLine *>(_o); Q_UNUSED(_t) void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< QLineF*>(_v) = _t->getLine(); break; case 1: *reinterpret_cast< QRect*>(_v) = _t->getOldP1(); break; case 2: *reinterpret_cast< QRect*>(_v) = _t->getOldP2(); break; case 3: *reinterpret_cast< bool*>(_v) = _t->getArrowStart(); break; case 4: *reinterpret_cast< bool*>(_v) = _t->getArrowEnd(); break; default: break; } } else if (_c == QMetaObject::WriteProperty) { TContainerLine *_t = static_cast<TContainerLine *>(_o); Q_UNUSED(_t) void *_v = _a[0]; switch (_id) { case 0: _t->setLine(*reinterpret_cast< QLineF*>(_v)); break; case 1: _t->setOldP1(*reinterpret_cast< QRect*>(_v)); break; case 2: _t->setOldP2(*reinterpret_cast< QRect*>(_v)); break; case 3: _t->setArrowStart(*reinterpret_cast< bool*>(_v)); break; case 4: _t->setArrowEnd(*reinterpret_cast< bool*>(_v)); break; default: break; } } else if (_c == QMetaObject::ResetProperty) { } #endif // QT_NO_PROPERTIES } const QMetaObject TContainerLine::staticMetaObject = { { &RptContainer::staticMetaObject, qt_meta_stringdata_TContainerLine.data, qt_meta_data_TContainerLine, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *TContainerLine::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *TContainerLine::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_TContainerLine.stringdata0)) return static_cast<void*>(const_cast< TContainerLine*>(this)); return RptContainer::qt_metacast(_clname); } int TContainerLine::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = RptContainer::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 4) qt_static_metacall(this, _c, _id, _a); _id -= 4; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 4) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 4; } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty || _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) { qt_static_metacall(this, _c, _id, _a); _id -= 5; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 5; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 5; } #endif // QT_NO_PROPERTIES return _id; } QT_END_MOC_NAMESPACE
[ "jiaoqiangxu@gmail.com" ]
jiaoqiangxu@gmail.com
d3d89499fcaa7a566ec90d7a873b68fd7ab16d54
5f611553c10169e059cd657d1de9e6c990c6fbd8
/thread_entry_demo/src/registry.h
01e310c4be7569b1df3b6e49363aaff0227a41ec
[]
no_license
wadeling/c-practice
7331e2b54153243d830c651c988e077862e096a9
41a901353a855f4110518ff5937a6c2d34b1eb6d
refs/heads/master
2021-07-18T09:49:47.530398
2020-01-17T07:02:01
2020-01-17T07:02:01
220,131,820
0
0
null
2021-07-06T07:25:32
2019-11-07T02:14:21
C
UTF-8
C++
false
false
853
h
#pragma once #include <string> #include <vector> #include <map> using namespace std; template <class Base> class FactoryRegistry { public: static std::string allFactory() { std::vector<std::string> ret; ret.reserve(factories().size()); for (const auto& factory : factories()) { ret.push_back(factory.first); } // std::sort(ret.begin(), ret.end()); return std::string(""); } static std::map<std::string, Base*>& factories() { static auto* factories = new std::map<std::string, Base*>; return *factories; } static void registerFactory(Base& factory, std::string name) { auto result = factories().emplace(std::make_pair(name, &factory)); if (!result.second) { printf("double register %s\r\n",name.c_str()); } } };
[ "wadeling@gmail.com" ]
wadeling@gmail.com
5972215cdc68ad89e01c78f705d64de5d40bb49f
abcb51cd9ff246d955919bc575a6d8676e38d2dc
/src/Output/Output_L1Error.cpp
71cb9b43d66c80c725a0219f82cb447a017dd8f6
[ "BSD-3-Clause" ]
permissive
hfhsieh/gamer-fork
2ddcc9e540793f5ebe978b744c5b90a96bfed1d8
c6d5964316b03401633033b0fb3816b7ea3bba4b
refs/heads/master
2023-07-05T17:57:22.166536
2022-04-04T07:08:30
2022-04-04T07:08:30
216,956,636
1
0
NOASSERTION
2020-07-13T05:49:49
2019-10-23T03:05:06
null
UTF-8
C++
false
false
15,444
cpp
#include "GAMER.h" static void WriteFile( void (*AnalFunc_Flu)( real fluid[], const double x, const double y, const double z, const double Time, const int lv, double AuxArray[] ), void (*AnalFunc_Mag)( real magnetic[], const double x, const double y, const double z, const double Time, const int lv, double AuxArray[] ), FILE *File[], const int lv, const int PID, const int i, const int j, const int k, double L1_Err[], const OptOutputPart_t Part ); #define NERR ( NCOMP_TOTAL + NCOMP_MAG ) //------------------------------------------------------------------------------------------------------- // Function : Output_L1Error // Description : Compare the numerical and analytical solutions and output the L1 errors // // Note : 1. Mainly invoked by various test problems // 2. Similar to Output_DumpData_Part() // 3. L1 errors are recorded in "Record__L1Err" // 4. For MHD, this function uses the average **cell-centered** magnetic field to compute errors // 5. Errors of passive scalars are NOT computed // // Parameter : AnalFunc_Flu : Function pointer to return the analytical solution of the fluid variables // --> Usually set to the same function pointer for initializing grids // (e.g., SetGridIC() in various test problems) // --> For MHD, the total energy set by this function must NOT include magnetic energy // AnalFunc_Mag : Function pointer to return the analytical solution of the magnetic field (MHD only) // --> Usually set to the same function pointer for initializing B field // (e.g., SetBFieldIC() in various test problems) // Prefix : Prefix of the output filename // Part : OUTPUT_X : x line // OUTPUT_Y : y line // OUTPUT_Z : z line // OUTPUT_DIAG : diagonal along (+1,+1,+1) // x/y/z : spatial coordinates for Part // // Return : None //------------------------------------------------------------------------------------------------------- void Output_L1Error( void (*AnalFunc_Flu)( real fluid[], const double x, const double y, const double z, const double Time, const int lv, double AuxArray[] ), void (*AnalFunc_Mag)( real magnetic[], const double x, const double y, const double z, const double Time, const int lv, double AuxArray[] ), const char *Prefix, const OptOutputPart_t Part, const double x, const double y, const double z ) { if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s (DumpID = %d) ...\n", __FUNCTION__, DumpID ); // check if ( Part == OUTPUT_DIAG && ( amr->BoxSize[0] != amr->BoxSize[1] || amr->BoxSize[0] != amr->BoxSize[2] ) ) Aux_Error( ERROR_INFO, "simulation domain must be cubic for \"OUTPUT_DIAG\" !!\n" ); for (int lv=1; lv<NLEVEL; lv++) if ( NPatchTotal[lv] != 0 ) Mis_CompareRealValue( Time[0], Time[lv], __FUNCTION__, true ); if ( AnalFunc_Flu == NULL ) Aux_Error( ERROR_INFO, "AnalyFunc_Flu == NULL !!\n" ); # ifdef MHD if ( AnalFunc_Mag == NULL ) Aux_Error( ERROR_INFO, "AnalyFunc_Mag == NULL !!\n" ); # endif // output filename char FileName[NERR][MAX_STRING]; # if ( MODEL == HYDRO ) sprintf( FileName[ 0], "%s_Dens_%06d", Prefix, DumpID ); sprintf( FileName[ 1], "%s_MomX_%06d", Prefix, DumpID ); sprintf( FileName[ 2], "%s_MomY_%06d", Prefix, DumpID ); sprintf( FileName[ 3], "%s_MomZ_%06d", Prefix, DumpID ); sprintf( FileName[ 4], "%s_Pres_%06d", Prefix, DumpID ); for (int v=0; v<NCOMP_PASSIVE; v++) sprintf( FileName[NCOMP_FLUID+v], "%s_Passive%02d_%06d", Prefix, v, DumpID ); # ifdef MHD sprintf( FileName[NCOMP_TOTAL+0], "%s_MagX_%06d", Prefix, DumpID ); sprintf( FileName[NCOMP_TOTAL+1], "%s_MagY_%06d", Prefix, DumpID ); sprintf( FileName[NCOMP_TOTAL+2], "%s_MagZ_%06d", Prefix, DumpID ); # endif # elif ( MODEL == ELBDM ) sprintf( FileName[ 0], "%s_Dens_%06d", Prefix, DumpID ); sprintf( FileName[ 1], "%s_Real_%06d", Prefix, DumpID ); sprintf( FileName[ 2], "%s_Imag_%06d", Prefix, DumpID ); # else # error : unsupported MODEL !! # endif // MODEL // check if the output files already exist if ( MPI_Rank == 0 ) { for (int v=0; v<NERR; v++) { FILE *File_Check = fopen( FileName[v], "r" ); if ( File_Check != NULL ) { Aux_Message( stderr, "WARNING : file \"%s\" already exists and will be overwritten !!\n", FileName[v] ); fclose( File_Check ); FILE *Temp = fopen( FileName[v], "w" ); fclose( Temp ); } } } // prepare to output errors double dh, xx, yy, zz; int *Corner = NULL; double *EdgeL = NULL; double *EdgeR = NULL; bool Check_x = false; bool Check_y = false; bool Check_z = false; double L1_Err[NERR]; static bool FirstTime = true; for (int v=0; v<NERR; v++) L1_Err[v] = 0.0; switch ( Part ) { case OUTPUT_X : Check_y = true; Check_z = true; break; case OUTPUT_Y : Check_x = true; Check_z = true; break; case OUTPUT_Z : Check_x = true; Check_y = true; break; case OUTPUT_DIAG : Check_x = false; Check_y = false; Check_z = false; break; default : Aux_Error( ERROR_INFO, "unsupported option \"Part = %d\" [4/5/6/7] !!\n", Part ); } // output one MPI rank at a time for (int TRank=0; TRank<MPI_NRank; TRank++) { if ( MPI_Rank == TRank ) { FILE *File[NERR]; for (int v=0; v<NERR; v++) File[v] = fopen( FileName[v], "a" ); // output header if ( TRank == 0 ) { for (int v=0; v<NERR; v++) fprintf( File[v], "#%20s %20s %20s %20s\n", "Coord.", "Numerical", "Analytical", "Error" ); } // output data for (int lv=0; lv<NLEVEL; lv++) { dh = amr->dh[lv]; for (int PID=0; PID<amr->NPatchComma[lv][1]; PID++) { // only check the leaf patches if ( amr->patch[0][lv][PID]->son == -1 ) { Corner = amr->patch[0][lv][PID]->corner; EdgeL = amr->patch[0][lv][PID]->EdgeL; EdgeR = amr->patch[0][lv][PID]->EdgeR; if ( Part == OUTPUT_DIAG ) // (+1,+1,+1) diagonal { if ( Corner[0] == Corner[1] && Corner[0] == Corner[2] ) { for (int k=0; k<PS1; k++) { WriteFile( AnalFunc_Flu, AnalFunc_Mag, File, lv, PID, k, k, k, L1_Err, Part ); } } } // if ( Part == OUTPUT_DIAG ) else // x/y/z lines || xy/yz/xz slices { // check whether the patch corner is within the target range if ( !Check_x || ( EdgeL[0] <= x && EdgeR[0] > x ) ) if ( !Check_y || ( EdgeL[1] <= y && EdgeR[1] > y ) ) if ( !Check_z || ( EdgeL[2] <= z && EdgeR[2] > z ) ) { // check whether the cell is within the target range for (int k=0; k<PS1; k++) { zz = EdgeL[2] + k*dh; if ( Check_z && ( zz>z || zz+dh<=z ) ) continue; for (int j=0; j<PS1; j++) { yy = EdgeL[1] + j*dh; if ( Check_y && ( yy>y || yy+dh<=y ) ) continue; for (int i=0; i<PS1; i++) { xx = EdgeL[0] + i*dh; if ( Check_x && ( xx>x || xx+dh<=x ) ) continue; WriteFile( AnalFunc_Flu, AnalFunc_Mag, File, lv, PID, i, j, k, L1_Err, Part ); }}} } } // if ( Part == OUTPUT_DIAG ... else ... ) } // if ( amr->patch[0][lv][PID]->son == -1 ) } // for (int PID=0; PID<amr->NPatchComma[lv][1]; PID++) } // for (int lv=0; lv<NLEVEL; lv++) for (int v=0; v<NERR; v++) fclose( File[v] ); } // if ( MPI_Rank == TRank ) MPI_Barrier( MPI_COMM_WORLD ); } // for (int TRank=0; TRank<MPI_NRank; TRank++) // gather the L1 error from all ranks and output the results double L1_Err_Sum[NERR], Norm; MPI_Reduce( L1_Err, L1_Err_Sum, NERR, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD ); if ( MPI_Rank == 0 ) { switch ( Part ) { case OUTPUT_X : Norm = amr->BoxSize[0]; break; case OUTPUT_Y : Norm = amr->BoxSize[1]; break; case OUTPUT_Z : Norm = amr->BoxSize[2]; break; case OUTPUT_DIAG : Norm = amr->BoxSize[0]; break; default : Aux_Error( ERROR_INFO, "unsupported option \"Part = %d\" [4/5/6/7] !!\n", Part ); } for (int v=0; v<NERR; v++) L1_Err_Sum[v] /= Norm; FILE *File_L1 = fopen( "Record__L1Err", "a" ); // output header if ( FirstTime ) { # if ( MODEL == HYDRO ) fprintf( File_L1, "#%5s %13s %19s %19s %19s %19s %19s", "NGrid", "Time", "Error(Dens)", "Error(MomX)", "Error(MomY)", "Error(MomZ)", "Error(Pres)" ); for (int v=0; v<NCOMP_PASSIVE; v++) fprintf( File_L1, " Error(Passive%02d)", v ); # ifdef MHD fprintf( File_L1, " %19s %19s %19s", "Error(MagX)", "Error(MagY)", "Error(MagZ)" ); # endif fprintf( File_L1, "\n" ); # elif ( MODEL == ELBDM ) fprintf( File_L1, "#%5s %13s %19s %19s %19s\n", "NGrid", "Time", "Error(Dens)", "Error(Real)", "Error(Imag)" ); # else # error : unsupported MODEL !! # endif // MODEL FirstTime = false; } // if ( FirstTime ) // output data fprintf( File_L1, "%6d %13.7e", (Part==OUTPUT_DIAG)?NX0_TOT[0]:NX0_TOT[Part-OUTPUT_X], Time[0] ); for (int v=0; v<NERR; v++) fprintf( File_L1, " %19.12e", L1_Err_Sum[v] ); fprintf( File_L1, "\n" ); fclose( File_L1 ); } // if ( MPI_Rank == 0 ) if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s (DumpID = %d) ... done\n", __FUNCTION__, DumpID ); } // FUNCTION : Output_L1Error //------------------------------------------------------------------------------------------------------- // Function : WriteFile // Description : Write the data of a single cell // // Note : 1. Invoked by Output_L1Error() // // Parameter : AnalFunc_Flu : Function pointer to return the analytical solution of the fluid variables // --> For MHD, the total energy set by this function must NOT include magnetic energy // AnalFunc_Mag : Function pointer to return the analytical solution of the magnetic field (MHD only) // File : File pointer // lv : Target refinement level // PID : Patch ID // i/j/k : Cell indices within the patch // L1_Err : Array to record the L1 errors of all variables // Part : OUTPUT_X : x line // OUTPUT_Y : y line // OUTPUT_Z : z line // OUTPUT_DIAG : diagonal along (+1,+1,+1) // // Return : L1_Err //------------------------------------------------------------------------------------------------------- void WriteFile( void (*AnalFunc_Flu)( real fluid[], const double x, const double y, const double z, const double Time, const int lv, double AuxArray[] ), void (*AnalFunc_Mag)( real magnetic[], const double x, const double y, const double z, const double Time, const int lv, double AuxArray[] ), FILE *File[], const int lv, const int PID, const int i, const int j, const int k, double L1_Err[], const OptOutputPart_t Part ) { real Nume[NERR], Anal[NERR], Err[NERR]; // get the numerical solution for (int v=0; v<NCOMP_TOTAL; v++) Nume[v] = amr->patch[ amr->FluSg[lv] ][lv][PID]->fluid[v][k][j][i]; // note that we use the cell-centered B field to compute errors # ifdef MHD MHD_GetCellCenteredBFieldInPatch( Nume+NCOMP_TOTAL, lv, PID, i, j, k, amr->MagSg[lv] ); # endif // convert total energy to pressure # if ( MODEL == HYDRO ) const bool CheckMinPres_No = false; # ifdef MHD const real *B_Nume = Nume + NCOMP_TOTAL; const real Emag_Nume = (real)0.5*( SQR(B_Nume[MAGX]) + SQR(B_Nume[MAGY]) + SQR(B_Nume[MAGZ]) ); # else const real Emag_Nume = NULL_REAL; # endif Nume[ENGY] = Hydro_Con2Pres( Nume[DENS], Nume[MOMX], Nume[MOMY], Nume[MOMZ], Nume[ENGY], Nume+NCOMP_FLUID, CheckMinPres_No, NULL_REAL, Emag_Nume, EoS_DensEint2Pres_CPUPtr, EoS_AuxArray_Flt, EoS_AuxArray_Int, h_EoS_Table, NULL ); # endif // #if ( MODEL == HYDRO ) // get the analytical solution const double dh = amr->dh[lv]; const double x = amr->patch[0][lv][PID]->EdgeL[0] + (i+0.5)*dh; const double y = amr->patch[0][lv][PID]->EdgeL[1] + (j+0.5)*dh; const double z = amr->patch[0][lv][PID]->EdgeL[2] + (k+0.5)*dh; AnalFunc_Flu( Anal, x, y, z, Time[0], lv, NULL ); # ifdef MHD AnalFunc_Mag( Anal+NCOMP_TOTAL, x, y, z, Time[0], lv, NULL ); # endif // convert total energy to pressure # if ( MODEL == HYDRO ) const real Emag_Zero = 0.0; // Anal[ENGY] set by AnalFunc_Flu() does NOT include magentic energy Anal[ENGY] = Hydro_Con2Pres( Anal[DENS], Anal[MOMX], Anal[MOMY], Anal[MOMZ], Anal[ENGY], Anal+NCOMP_FLUID, CheckMinPres_No, NULL_REAL, Emag_Zero, EoS_DensEint2Pres_CPUPtr, EoS_AuxArray_Flt, EoS_AuxArray_Int, h_EoS_Table, NULL ); # endif // record the physical coordinate double r; switch ( Part ) { case OUTPUT_X : r = x; break; case OUTPUT_Y : r = y; break; case OUTPUT_Z : r = z; break; case OUTPUT_DIAG : r = sqrt(3.0)*x; break; default : Aux_Error( ERROR_INFO, "unsupported option \"Part = %d\" [4/5/6/7] !!\n", Part ); } // estimate and output errors for (int v=0; v<NERR; v++) { Err [v] = FABS( Anal[v] - Nume[v] ); L1_Err[v] += Err[v]*dh; fprintf( File[v], " %20.13e %20.13e %20.13e %20.13e\n", r, Nume[v], Anal[v], Err[v] ); } } // FUNCTION : WriteFile
[ "hyschive@gmail.com" ]
hyschive@gmail.com
f8eb76463d9339c1440ab7f7a21f92910a120747
822c74b936d46bdfd7323de3434b3ff86ee25a8e
/src/modules/graphics/Color.h
ffd1d2e481f9ece38332b2d92b1ff8b83b43a07c
[ "Zlib" ]
permissive
leafo/moonscript-love
4ece4802928e1f35bad978f4e0461fd93ec819da
602489af61dcd0adf40348345f886afffccd415d
refs/heads/master
2023-08-28T00:13:00.879118
2012-03-11T18:06:51
2012-03-11T18:06:51
2,214,283
20
0
null
null
null
null
UTF-8
C++
false
false
2,283
h
/** * Copyright (c) 2006-2011 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #ifndef LOVE_GRAPHICS_COLOR_H #define LOVE_GRAPHICS_COLOR_H namespace love { namespace graphics { template <typename T> struct ColorT { T r; T g; T b; T a; ColorT() : r(0), g(0), b(0), a(0) {} ColorT(T r_, T g_, T b_, T a_) : r(r_), g(g_), b(b_), a(a_) {} void set(T r_, T g_, T b_, T a_) { r = r_; g = g_; b = b_; a = a_; } ColorT<T> operator+=(const ColorT<T>& other); ColorT<T> operator*=(T s); ColorT<T> operator/=(T s); }; template <typename T> ColorT<T> ColorT<T>::operator+=(const ColorT<T>& other) { r += other.r; g += other.g; b += other.b; a += other.a; return *this; } template <typename T> ColorT<T> ColorT<T>::operator*=(T s) { r *= s; g *= s; b *= s; a *= s; return *this; } template <typename T> ColorT<T> ColorT<T>::operator/=(T s) { r /= s; g /= s; b /= s; a /= s; return *this; } template <typename T> ColorT<T> operator+(const ColorT<T>& a, const ColorT<T>& b) { ColorT<T> tmp(a); return tmp += b; } template <typename T> ColorT<T> operator*(const ColorT<T>& a, T s) { ColorT<T> tmp(a); return tmp *= s; } template <typename T> ColorT<T> operator/(const ColorT<T>& a, T s) { ColorT<T> tmp(a); return tmp /= s; } typedef ColorT<unsigned char> Color; typedef ColorT<float> Colorf; } // graphics } // love #endif // LOVE_GRAPHICS_COLOR_H
[ "leafot@gmail.com" ]
leafot@gmail.com
5f4cc33245a60677b7724de801ca84ddeb058522
180de988618b154a690837d3b76acf5ffbb3a8eb
/pong_game/pong_game/Sprite.cpp
0db38851aaf8ce729a21d0bc60ba92c5e11aba63
[]
no_license
eggetcool/Space-Invaders
e90969988b461c953741f5108cd26880dcbfdc2f
a448e468ef00d52bdb48de2b996fb272b02d1cdc
refs/heads/master
2021-01-10T12:30:42.625315
2016-02-09T11:08:44
2016-02-09T11:08:44
49,012,882
0
0
null
null
null
null
UTF-8
C++
false
false
526
cpp
#include "stdafx.h" #include "Sprite.h" Sprite::Sprite(SDL_Texture* p_pxTexture) { m_pxTexture = p_pxTexture; m_xRegion.x = 0; m_xRegion.y = 0; m_xRegion.h = 0; m_xRegion.w = 0; } Sprite::Sprite(SDL_Texture* p_pxTexture, int p_iX, int p_iY, int p_iW, int p_iH) { m_pxTexture = p_pxTexture; m_xRegion.x = p_iX; m_xRegion.y = p_iY; m_xRegion.h = p_iH; m_xRegion.w = p_iW; } Sprite::~Sprite() { } SDL_Texture* Sprite::GetTexture() { return m_pxTexture; } SDL_Rect* Sprite::GetRegion() { return &m_xRegion; }
[ "erijig@hotmail.com" ]
erijig@hotmail.com
68729cd6d450c48ff2fcc4f2a0acb070170b6315
3341f663e286a733f8a8335464037384f6e4bf94
/third_party/blink/renderer/core/style/text_decoration_thickness.cc
0e98a7483855b6c4bbcc0f20a122f44e5fe18a21
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
ZZbitmap/chromium
f18b462aa22a574f3850fe87ce0b2a614c6ffe06
bc796eea45503c990ab65173b6bcb469811aaaf3
refs/heads/master
2022-11-15T04:05:01.082328
2020-06-08T13:55:53
2020-06-08T13:55:53
270,664,211
0
0
BSD-3-Clause
2020-06-08T13:55:55
2020-06-08T12:41:58
null
UTF-8
C++
false
false
926
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/style/text_decoration_thickness.h" namespace blink { TextDecorationThickness::TextDecorationThickness() = default; TextDecorationThickness::TextDecorationThickness(const Length& length) : thickness_(length) {} TextDecorationThickness::TextDecorationThickness(CSSValueID from_font_keyword) { DCHECK_EQ(from_font_keyword, CSSValueID::kFromFont); thickness_from_font_ = true; } Length TextDecorationThickness::Thickness() const { DCHECK(!thickness_from_font_); return thickness_; } bool TextDecorationThickness::operator==( const TextDecorationThickness& other) const { return thickness_from_font_ == other.thickness_from_font_ && thickness_ == other.thickness_; } } // namespace blink
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
bf1d99b85f23a4629436e989c21a8657fd36aa70
efd81d18412b52596d8f47e5c17b1e1c31d530d5
/pins.hpp
a119bfdeeef8579bb0aba601e047d2b5da2f4ee1
[]
no_license
gary600/meche-project2
0d21a5c7015bae947b1123e4038da455781cef52
f169d91d38bc9ce70d9e56272103494c38642908
refs/heads/master
2023-09-03T13:14:47.239813
2021-11-12T17:00:28
2021-11-12T17:00:28
421,631,370
0
0
null
null
null
null
UTF-8
C++
false
false
923
hpp
///////////////////////////////////////////////////////////////////////// // `pins.hpp`: Pin definitions and associated objects (servo and LED). // ///////////////////////////////////////////////////////////////////////// #pragma once #include <Servo.h> #include <FastLED.h> // Ultrasonic pins #define ULTRASONIC_TRIG 13 #define ULTRASONIC_ECHO 12 #define SERVO_PIN 10 // Ultrasonic pan servo extern Servo ultrasonic_servo; // `extern` allows this global variable to be shared among files // Motor pins: SPEED defines the speed based on PWM, and DIR defines the direction #define SPEED_L 6 #define SPEED_R 5 #define DIR_L 8 #define DIR_R 7 #define ENABLE 3 // Motor enable - must be HIGH for any motors to run // Line follower pins: higher value means less reflectance #define LINE_L A2 #define LINE_M A1 #define LINE_R A0 // Misc #define MODE_BUTTON 2 #define LED_PIN 4 extern CRGB leds[1]; // FastLED's LED object
[ "me@gary600.xyz" ]
me@gary600.xyz
5d3a717f1da65cda56183b61c6ed41e377b74383
6a6487cb64424d4ccdc05d3bb6607e8976517a80
/Auto/splatform/local/Cluster.h
816ab5508ff25227acf7c549279e089d92db1113
[]
no_license
trueman1990/VistaModels
79d933a150f80166c9062294f4725b812bb5d4fc
5766de72c844a9e14fa65cb752ea81dfd6e7c42a
refs/heads/master
2021-06-08T22:02:32.737552
2017-01-23T16:10:23
2017-01-23T16:10:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,887
h
#pragma once #include "mgc_vista_schematics.h" $includes_begin; #include <systemc.h> #include "../models/can_model.h" #include "../models/FileCanData_model.h" $includes_end; $module_begin("Cluster"); SC_MODULE(Cluster) { public: typedef Cluster SC_CURRENT_USER_MODULE; Cluster(::sc_core::sc_module_name name): ::sc_core::sc_module(name) $initialization_begin $init("RX0"), RX0("RX0") $end $init("TX0"), TX0("TX0") $end $init("CanIF"), CanIF(0) $end $init("clusterdriver0"), clusterdriver0(0) $end $initialization_end { $elaboration_begin; $create_component("CanIF"); CanIF = new can_pvt("CanIF"); $end; $create_component("clusterdriver0"); clusterdriver0 = new FileCanData_pvt("clusterdriver0"); $end; $bind("CanIF->GI_Rx","clusterdriver0->rxi"); vista_bind(CanIF->GI_Rx, clusterdriver0->rxi); $end; $bind("CanIF->TX0","TX0"); vista_bind(CanIF->TX0, TX0); $end; $bind("RX0","CanIF->RX0"); vista_bind(RX0, CanIF->RX0); $end; $bind("clusterdriver0->m","CanIF->reg"); vista_bind(clusterdriver0->m, CanIF->reg); $end; $elaboration_end; $vlnv_assign_begin; m_library = "local"; m_vendor = ""; m_version = ""; $vlnv_assign_end; } ~Cluster() { $destructor_begin; $destruct_component("CanIF"); delete CanIF; CanIF = 0; $end; $destruct_component("clusterdriver0"); delete clusterdriver0; clusterdriver0 = 0; $end; $destructor_end; } public: $fields_begin; $socket("RX0"); tlm::tlm_target_socket< 8U,tlm::tlm_base_protocol_types,1,sc_core::SC_ZERO_OR_MORE_BOUND > RX0; $end; $socket("TX0"); tlm::tlm_initiator_socket< 8U,tlm::tlm_base_protocol_types,1,sc_core::SC_ZERO_OR_MORE_BOUND > TX0; $end; $component("CanIF"); can_pvt *CanIF; $end; $component("clusterdriver0"); FileCanData_pvt *clusterdriver0; $end; $fields_end; $vlnv_decl_begin; public: const char* m_library; const char* m_vendor; const char* m_version; $vlnv_decl_end; }; $module_end;
[ "jonmcdonald@gmail.com" ]
jonmcdonald@gmail.com
3228f80a9a8ad35825468b43aae46f737386ffb1
c42fe9b955a07b7a5882ddc395aa7fbd8fdd9b0e
/src/games/tic_tac_toe.cpp
e8130c6e4b98431af92018d34f15133f1a1f3d4e
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thaddeusdiamond/Board-Games
c117d52cb03488ae7e544f82be8aebb837de7f1d
85bf4f821edd4f4eefc45e3812171055aece2a67
refs/heads/master
2021-01-21T13:48:56.955018
2011-11-30T02:23:00
2011-11-30T02:23:00
2,857,510
4
1
null
null
null
null
UTF-8
C++
false
false
5,165
cpp
/** * @file * @author Thaddeus Diamond <diamond@cs.yale.edu> * @version 0.1 * @since 26 Nov 2011 * * @section DESCRIPTION * * This file defines a quick implementation of TicTacToe **/ #include "games/tic_tac_toe.hpp" void Games::SampleGames::TicTacToe::CreateBoard() { board_ = new Board(3, 3, 270, 270); if (!board_->AttachTileHandlers(this)) exit(EXIT_FAILURE); /// @todo Use Die Macro } void Games::SampleGames::TicTacToe::CreateMenu() { Label* filler = new Label(); filler->set_size_request(300, 25); Button* new_game_button = new Button("Start New Game"); new_game_button->signal_clicked().connect( sigc::mem_fun(this, &Game::ClearTheBoard)); options_ = new Menu(); options_->pack_start(filler); options_->pack_start(new_game_button); } void Games::SampleGames::TicTacToe::CreateHeader() { header_ = new Label(); header_->set_text(INITIAL_DIRECTIVE); header_->set_size_request(300, 50); } void Games::SampleGames::TicTacToe::OnTileClicked(int row, int col) { // Don't do anything if we're resetting the game if (game_state_ == RESETTING) return; Tile* tile_pressed = board_->tile(row, col); board_state_[row][col] = player_; // Mark the tile and inactivate it tile_pressed->set_label(PLAYER_MARK[player_]); tile_pressed->set_sensitive(false); // Make it a little prettier tile_pressed->modify_bg(Gtk::STATE_INSENSITIVE, Color(PLAYER_COLOR[player_])); CompleteTurn(); } void Games::SampleGames::TicTacToe::CompleteTurn() { // Row-wise check for (int i = 0; i < board_->height(); i++) { Player initial_player = board_state_[i][0]; set<Tile*> winning_tiles; winning_tiles.insert(board_->tile(i, 0)); int j; for (j = 1; j < board_->width(); j++) { if (board_state_[i][j] != initial_player) break; else winning_tiles.insert(board_->tile(i, j)); } if (initial_player != NEITHER && j == board_->width()) EndGame(winning_tiles); } // Column-wise check for (int i = 0; i < board_->width(); i++) { Player initial_player = board_state_[0][i]; set<Tile*> winning_tiles; winning_tiles.insert(board_->tile(0, i)); int j; for (j = 1; j < board_->height(); j++) { if (board_state_[j][i] != initial_player) break; else winning_tiles.insert(board_->tile(j, i)); } if (initial_player != NEITHER && j == board_->height()) EndGame(winning_tiles); } // Diagonal-check (R to L) int i; Player initial_player = board_state_[0][0]; set<Tile*> winning_tiles; winning_tiles.insert(board_->tile(0, 0)); for (i = 1; i < board_->width(); i++) { if (board_state_[i][i] != initial_player) break; else winning_tiles.insert(board_->tile(i, i)); } if (initial_player != NEITHER && i == board_->height()) EndGame(winning_tiles); // Diagonal-check (L to R) initial_player = board_state_[board_->width() - 1][0]; winning_tiles.clear(); winning_tiles.insert(board_->tile(board_->width() - 1, 0)); for (i = 1; i < board_->width(); i++) { if (board_state_[board_->width() - i - 1][i] != initial_player) break; else winning_tiles.insert(board_->tile(board_->width() - i - 1, i)); } if (initial_player != NEITHER && i == board_->height()) EndGame(winning_tiles); // Update the game state if (game_state_ != GAME_OVER) { player_ = (player_ + 1) % NUMBER_OF_PLAYERS; game_state_ = (game_state_ + 1) % NUMBER_OF_PLAYERS; } // Draw? bool draw = true; for (int i = 0; i < board_->height(); i++) { for (int j = 0; j < board_->width(); j++) { if (board_state_[i][j] == NEITHER) draw = false; } } if (game_state_ != GAME_OVER && draw) header_->set_text(DRAW_DIRECTIVE); else header_->set_text(PLAYER_NAME[player_] + PLAYER_DIRECTIVE[game_state_]); } void Games::SampleGames::TicTacToe::EndGame(set<Tile*> winning_tiles) { // White out any tiles selected, but not on the winning path for (int i = 0; i < board_->height(); i++) { for (int j = 0; j < board_->width(); j++) { if (board_state_[i][j] != NEITHER && winning_tiles.find(board_->tile(i, j)) == winning_tiles.end()) board_->tile(i, j)->modify_bg(Gtk::STATE_INSENSITIVE, Color("gray")); } } // Game's over, no more moves allowed for (int i = 0; i < board_->height(); i++) { for (int j = 0; j < board_->width(); j++) board_->tile(i, j)->set_sensitive(false); } game_state_ = GAME_OVER; } void Games::SampleGames::TicTacToe::ClearTheBoard() { game_state_ = RESETTING; header_->set_text(PLAYER_DIRECTIVE[game_state_]); // Reset the tile characteristics and abstract board state player_ = PLAYER_ONE; for (int i = 0; i < board_->height(); i++) { for (int j = 0; j < board_->width(); j++) { board_->tile(i, j)->set_active(false); board_->tile(i, j)->set_sensitive(true); board_->tile(i, j)->set_label(""); board_->tile(i, j)->modify_bg(Gtk::STATE_INSENSITIVE, Color(NULL)); board_state_[i][j] = NEITHER; } } game_state_ = PLAYER_ONE_TURN; header_->set_text(INITIAL_DIRECTIVE); }
[ "thaddeus.diamond@yale.edu" ]
thaddeus.diamond@yale.edu
43dd65fb836d09da3f5ebfa085fb0643a2ec8ef5
0f2e74e3d8f6afe1b3a1bef090e465d7f95c7128
/game/object.cpp
b0f6c21e07827023bbad2c7ae674c84240287184
[]
no_license
MasahiroNakajima1202/commander
ce6e8171eca82bcb11967052b93c0315bd99f199
7a4caa293789d6e3afb036ed58f2255b12248aef
refs/heads/master
2020-05-21T13:29:26.863176
2016-06-30T12:22:42
2016-06-30T12:22:42
62,306,232
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
9,030
cpp
//***************************************************************************** // sceneモジュール // サンプルシーン // author: 中島将浩 // update: 2014/04/15 //***************************************************************************** #include "renderer.h" #include "object.h" Object *Object::_top[DRAW_LAYER_MAX] = {}; //***************************************************************************** //【初期化】 //***************************************************************************** HRESULT Object::SetUp(void){ //_next = nullptr; _death = false; _position = D3DXVECTOR3(0.0f, 0.0f, 0.0f); _pre_position = D3DXVECTOR3(0.0f, 0.0f, 0.0f); _velocity = D3DXVECTOR3(0.0f, 0.0f, 0.0f); _rotation = D3DXVECTOR3(0.0f, 0.0f, 0.0f); _size = D3DXVECTOR3(1.0f, 1.0f, 1.0f); _radius = 0.0f; return S_OK; } //***************************************************************************** //【更新】 //***************************************************************************** void Object::Update(void){ _pre_position = _position; _position += _velocity; _pre_rotation = _rotation; } //***************************************************************************** //【リストへ参加】 // 返り値: なし // 引数: なし //***************************************************************************** void Object::PushBackToList(int layer_no){ Object *cur = nullptr; if(_top[layer_no] == nullptr){//最初のひとり _top[layer_no] = this; return; } //二人目以降 cur = _top[layer_no]; //curを末尾まで動かす while(cur->_next != nullptr){ cur = cur->_next; } //curに要素追加 cur->_next = this; } //***************************************************************************** //【リストから削除】 // 返り値: なし // 引数: なし //***************************************************************************** void Object::RemoveFromList(int layer_no){ Object *cur = nullptr; Object *pre = nullptr; cur = _top[layer_no]; //ぼくが見つかるまで進める 念のためnullptr checkも ありえないけど while(cur != this && cur != nullptr){ pre = cur; cur = cur->_next; } if(cur == nullptr){//ぼくがいなかった return; //アーリエーン } if(cur == _top[layer_no]){ _top[layer_no] = cur->_next; } else{ pre->_next = cur->_next; } } //***************************************************************************** //【全更新】 // 返り値: なし // 引数: なし //***************************************************************************** void Object::UpdateAll(void){ Object *cur = nullptr; int i = 0; //loop index for(i=0; i<DRAW_LAYER_MAX; i++){ cur = _top[i]; while(cur != nullptr){ cur->Update(); cur = cur->_next; } } } //***************************************************************************** //【描画】 // 返り値: なし // 引数: なし //***************************************************************************** void Object::DrawAll(void){ Object *cur = nullptr; int i = 0; //loop index for(i=0; i<DRAW_LAYER_MAX; i++){ cur = _top[i]; while(cur != nullptr){ if(cur->_visible){ cur->Draw(); } cur = cur->_next; } } } void Object::DrawLayer(DRAW_LAYER layer){ Object *cur = nullptr; cur = _top[layer]; while (cur != nullptr){ if (cur->_visible){ cur->Draw(); } cur = cur->_next; } } //***************************************************************************** //【しね!ハイエナどもめ!】 // 返り値: なし // 引数: なし //***************************************************************************** void Object::DestroyAll(void){ int i = 0; //loop index for(i=0; i<DRAW_LAYER_MAX; i++){ while(_top[i] != nullptr){ _top[i]->Release(); delete _top[i]; } } } //***************************************************************************** //【全更新】 // 返り値: なし // 引数: なし //***************************************************************************** void Object::Flush(void){ Object *cur = nullptr; Object *next = nullptr; int i = 0; //loop index for(i=0; i<DRAW_LAYER_MAX; i++){ cur = _top[i]; while(cur != nullptr){ next = cur->_next; if(cur->_death){ cur->Release(); delete cur; } cur = next; } } } //***************************************************************************** //【こいつ、います?】 // 対象のオブジェクトが存在するかどうか // 返り値: なし // 引数: なし //***************************************************************************** bool Object::Extist(Object *object){ int i = 0; //loop index Object *cur = nullptr; for(i=0; i<DRAW_LAYER_MAX; i++){ cur = _top[i]; while(cur != nullptr){ if(cur == object){ return true; } cur = cur->_next; } } //いなかったよ…… return false; } //***************************************************************************** //【当たり判定(球と球)】 // 二つのオブジェクトの当たり判定を調べます as ball and ball // 返り値: なし // 引数: なし //***************************************************************************** bool Object::HitCheckBallBall(Object* ball_a, Object* ball_b){ float sum = ball_a->_radius + ball_b->_radius; D3DXVECTOR3 v = ball_a->_position - ball_b->_position; float sq_length = v.x*v.x + v.y*v.y + v.z*v.z; if(sum*sum < sq_length){ return false; } return true; } //***************************************************************************** //【当たり判定(点と箱)】 // 二つのオブジェクトの当たり判定を調べます as point and box // 返り値: なし // 引数: なし //***************************************************************************** bool Object::HitCheckPointBox(Object* point, Object* box){ D3DXVECTOR3 box_position(0.0f, 0.0f, 0.0f); D3DXVECTOR3 box_rotation(0.0f, 0.0f, 0.0f); D3DXMATRIX rot_mtx, trs_mtx, inv_mtx; bool ret = false; //boxのposrotを両方に逆算 D3DXMatrixIdentity(&inv_mtx); D3DXMatrixTranslation(&trs_mtx, box->_position.x, box->_position.y, box->_position.z); D3DXMatrixRotationYawPitchRoll(&rot_mtx, box->_rotation.y, box->_rotation.x, box->_rotation.z); D3DXMatrixMultiply(&inv_mtx, &inv_mtx, &rot_mtx); D3DXMatrixMultiply(&inv_mtx, &inv_mtx, &trs_mtx); D3DXMatrixInverse(&inv_mtx, nullptr, &inv_mtx); D3DXVECTOR3 point_pos = point->_position; D3DXVec3TransformCoord(&point_pos, &point_pos, &inv_mtx); if(-box->_size.x/2.0f < point_pos.x && point_pos.x < box->_size.x/2.0f && -box->_size.y/2.0f < point_pos.y && point_pos.y < box->_size.y/2.0f && -box->_size.z/2.0f < point_pos.z && point_pos.z < box->_size.z/2.0f){ ret = true; } return ret; } //***************************************************************************** //【当たり判定(点と円柱)】 // 二つのオブジェクトの当たり判定を調べます as point and pole // 返り値: なし // 引数: なし //***************************************************************************** bool Object::HitCheckPointPole(Object* point, Object* pole){ D3DXVECTOR3 pole_position(0.0f, 0.0f, 0.0f); D3DXVECTOR3 pole_rotation(0.0f, 0.0f, 0.0f); D3DXMATRIX rot_mtx, trs_mtx, inv_mtx; bool ret = false; //boxのposrotを両方に逆算 D3DXMatrixIdentity(&inv_mtx); D3DXMatrixTranslation(&trs_mtx, pole->_position.x, pole->_position.y, pole->_position.z); D3DXMatrixRotationYawPitchRoll(&rot_mtx, pole->_rotation.y, pole->_rotation.x, pole->_rotation.z); D3DXMatrixMultiply(&inv_mtx, &inv_mtx, &rot_mtx); D3DXMatrixMultiply(&inv_mtx, &inv_mtx, &trs_mtx); D3DXMatrixInverse(&inv_mtx, nullptr, &inv_mtx); D3DXVECTOR3 point_pos = point->_position; D3DXVec3TransformCoord(&point_pos, &point_pos, &inv_mtx); //高さ判定 if(point_pos.y > pole->_size.y / 2.0f + point->_radius || point_pos.y < -pole->_size.y / 2.0f - point->_radius){ return false; } float h_radius(point->_radius); if(point_pos.y > pole->_size.y / 2.0f || point_pos.y < -pole->_size.y / 2.0f){ float height(point_pos.y - pole->_size.y / 2.0f); if(height < 0.0f){height = -height;} h_radius = sqrtf(point->_radius * point->_radius - height * height); } float length(h_radius + pole->_radius); if(point_pos.x * point_pos.x + point_pos.z * point_pos.z < length * length){ //あたっちょる ret = true; } return ret; } void Object::GetWorldMatrix(D3DXMATRIX* out){ if(out == nullptr){return;} D3DXMATRIX world_mtx, rot_mtx, translate_mtx; D3DXMatrixIdentity(&world_mtx); //ワールド行列をとりあえずEにする D3DXMatrixRotationYawPitchRoll(&rot_mtx, _rotation.y, _rotation.x, _rotation.z); //rotation D3DXMatrixMultiply(&world_mtx, &world_mtx, &rot_mtx); D3DXMatrixTranslation(&translate_mtx, _position.x, _position.y, _position.z); //translation D3DXMatrixMultiply(&world_mtx, &world_mtx, &translate_mtx); *out = world_mtx; }
[ "masahiro.nakajima.1202@gmail.com" ]
masahiro.nakajima.1202@gmail.com
69c513fde0547439763386892d2aae9ceae53f27
cafa40ddfe3124dba8e6bc3fc706c2681dcfb6e6
/Platform/common/VDK_API_GetThreadID.cpp
59148cc1f9f43c59880838bb51c5d98e5e07ffeb
[]
no_license
analogdevicesinc/VDK
1c0fececcca89f10077ade97415bb9ed38f1db71
b19ecfa313551dc6bf4a513c0ad868294e221484
refs/heads/master
2021-04-28T09:23:01.104008
2018-04-24T11:33:59
2018-04-24T11:33:59
122,038,147
3
1
null
null
null
null
UTF-8
C++
false
false
1,187
cpp
/******************************************************************* Copyright (C) 2001-2018 Analog Devices, Inc. All Rights Reserved *******************************************************************/ /* ============================================================================= * * $RCSfile$ * * Description: The implementation of the public API function GetThreadID * * Last modified $Date$ * Last modified by $Author$ * $Revision$ * $Source$ * * ----------------------------------------------------------------------------- * Comments: * ----------------------------------------------------------------------------- * ===========================================================================*/ #include "VDK_API.h" #include "VDK_Thread.h" #include "ThreadTable.h" #pragma file_attr("OS_Component=Threads") #pragma file_attr("Threads") namespace VDK { ThreadID GetThreadID() { if (TMK_AtKernelLevel()) { return (ThreadID) VDK_KERNEL_LEVEL_; } else { #pragma suppress_null_check Thread *pThread = static_cast<Thread*>(TMK_GetCurrentThread()); // Return the current thread's ID... return pThread->ID(); } } }
[ "David.Gibson@analog.com" ]
David.Gibson@analog.com
4bd3ce29bcf6e8a171eda592f47dc75dac587a8b
878175c7acd229de8d905cf7affdd2e1a879951f
/contests/uri/uri-1144.cpp
87ba25ee8ea348c44128bcadf230b09470a18c9e
[ "MIT" ]
permissive
leomaurodesenv/contest-codes
a9c99dad48db4804c5b5aa6d54b0f7b296922d7e
f7ae7e9d8c67e43dea7ac7dd71afce20d804f518
refs/heads/master
2021-10-16T09:12:30.988244
2019-02-09T20:26:37
2019-02-09T20:26:37
126,015,286
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,208
cpp
/* * Problema: Sequência Lógica * https://www.urionlinejudge.com.br/judge/pt/problems/view/1144 */ #include <iostream> #include <iomanip> #include <cstdio> #include <cstdlib> #include <numeric> #include <string> #include <sstream> #include <iomanip> #include <locale> #include <bitset> #include <map> #include <vector> #include <queue> #include <stack> #include <algorithm> #include <cmath> #define INF 0x3F3F3F3F #define PI 3.14159265358979323846 #define EPS 1e-10 #define vet_i(var, tipo, lin, col, inic) vector< vector< tipo > > var (lin, vector< tipo > (col, inic)) #define vet_d(tipo) vector< vector< tipo > > #define lli long long int #define llu unsigned long long int #define fore(var, inicio, final) for(int var=inicio; var<final; var++) #define forec(var, inicio, final, incremento) for(int var=inicio; var<final; incremento) #define forit(it, var) for( it = var.begin(); it != var.end(); it++ ) using namespace std; int main(){ int n, val; cin>>n; fore(i, 1, n+1){ fore(k, 0, 2){ val = i; cout<<val<<" "; val *= i; cout<<val+k<<" "; val *= i; cout<<val+k<<endl; } } return 0; }
[ "leo.mauro.desenv@gmail.com" ]
leo.mauro.desenv@gmail.com
8ab24353623fb04c1a8670a13dc73320da5695a0
ecf0bc675b4225da23f1ea36c0eda737912ef8a9
/Reco_Csrc/Engine/Network/SessionState.cpp
a46b788ae7122d029c20d727e16e6d249504f29d
[]
no_license
Artarex/MysteryV2
6015af1b501ce5b970fdc9f5b28c80a065fbcfed
2fa5608a4e48be36f56339db685ae5530107a520
refs/heads/master
2022-01-04T17:00:05.899039
2019-03-11T19:41:19
2019-03-11T19:41:19
175,065,496
0
0
null
null
null
null
UTF-8
C++
false
false
131
cpp
version https://git-lfs.github.com/spec/v1 oid sha256:e66a6da18d58282f3472b4266f5c979e6c2eb5de4cf41dbf71b9e014245200f3 size 485130
[ "artarex@web.de" ]
artarex@web.de
a9ae4b5a23f528a1e73e8fbd68be76bc79c17bfb
b284721dd6e0b0c5ce3d0a4514238dc8f5fa5b31
/src/internet/model/ipv4-address-generator.h
e99b6880351bcd2c2a05ad971042b8eaf35e7302
[]
no_license
apoorvashenoy/ns3
2131b3d53698dfc8e2944e86889b0c25edcfd82f
b1f143813b5f1f31f8014606349adab847f55e5c
refs/heads/master
2021-01-18T14:14:12.722295
2013-01-17T01:54:31
2013-01-17T01:54:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,717
h
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2008 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef IPV4_ADDRESS_GENERATOR_H #define IPV4_ADDRESS_GENERATOR_H #include "ns3/ipv4-address.h" namespace ns3 { /** * \ingroup address * * \brief This generator assigns addresses sequentially from a provided * network address; used in topology code. */ class Ipv4AddressGenerator { public: static void Init (const Ipv4Address net, const Ipv4Mask mask, const Ipv4Address addr = "0.0.0.1"); static Ipv4Address NextNetwork (const Ipv4Mask mask); static Ipv4Address GetNetwork (const Ipv4Mask mask); static void InitAddress (const Ipv4Address addr, const Ipv4Mask mask); static Ipv4Address NextAddress (const Ipv4Mask mask); static Ipv4Address GetAddress (const Ipv4Mask mask); static void Reset (void); static bool AddAllocated (const Ipv4Address addr); static bool IsAllocated (const Ipv4Address addr); static void TestMode (void); }; } // namespace ns3 #endif /* IPV4_ADDRESS_GENERATOR_H */
[ "kebenson@uci.edu" ]
kebenson@uci.edu
0b0ec63047a139418a8b639af250cce5e4da1e3d
d14e34e28def869dd9a4d27b58f3228ed4c15f31
/java2csharp/java/Samsung/ProfessionalAudio.SapaSimplePiano/jni/SynthBase/SynthBase_math.cpp
927aa7e5c402dbe78b5b945124979056d622f986
[]
no_license
korjenko/Samples.Data.Porting
f9438e9adcc982ff1a15a98c48f006286fbcb638
603eb819c7e17af6669a4b37c4bc57bc3d8fb4a5
refs/heads/master
2020-12-03T06:32:30.455266
2016-06-29T12:21:12
2016-06-29T12:21:12
50,441,525
0
0
null
2016-01-26T16:20:36
2016-01-26T16:20:36
null
UTF-8
C++
false
false
777
cpp
#include "SynthBase_math.h" const float EXP_T[(NOTE_RANGE_POG - NOTE_RANGE_NEG)+1] = { #include "exp.txt" }; const float POW_T[NOTE_RANGE_POG][REAL_RANGE_POS*2+1] = { #include "pow.txt" }; /* pitch wheel value 14bit value 0x0000 to 0x3ffff centor 0x2000 -> synthbase 0x00 to 0xff center 0x80(128) */ const float PITCH_WHEEL_T[256] = { #include "pitch_wheel.txt" }; const float pan_tab[PAN_SIZE] = { #include "pan_tab.txt" }; const float Attenuation_tab[ATTENUATION_SIZE] = { #include "attenuation.txt" }; void pan_gain_ref(int c, float &l, float &r ) { int index; index = c + (PAN_RIGHT); if (index < 0) { index = 0; } else if (index > PAN_SIZE -1 ) { index = PAN_SIZE - 1; } r = pan_tab[(int) index]; l = pan_tab[(int) (PAN_SIZE - index -1)]; }
[ "mcvjetko@holisticware.net" ]
mcvjetko@holisticware.net
22d2806d2217a2bd45ced3e5cbe982eb0fd802b9
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/examples/APG/Signals/SigAction.cpp
d4f092e054fdd3c9c02b0ec51b19f26a901e4278
[ "Apache-2.0" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
1,643
cpp
#include "ace/OS_NS_unistd.h" #include "ace/OS_NS_stdlib.h" #include "ace/Log_Msg.h" // Listing 1 code/ch11 #include "ace/Signal.h" // Forward declaration. static void register_actions (); int ACE_TMAIN (int, ACE_TCHAR *[]) { ACE_TRACE ("::main"); ::register_actions (); // Register actions to happen. // This will be raised immediately. ACE_OS::kill (ACE_OS::getpid(), SIGUSR2); // This will pend until the first signal is completely // handled and returns, because we masked it out // in the registerAction call. ACE_OS::kill (ACE_OS::getpid (), SIGUSR1); while (ACE_OS::sleep (100) == -1) { if (errno == EINTR) continue; else ACE_OS::exit (1); } return 0; } // Listing 1 #if defined (ACE_HAS_SIG_C_FUNC) extern "C" { #endif // Listing 3 code/ch11 static void my_sighandler (int signo) { ACE_TRACE ("::my_sighandler"); ACE_OS::kill (ACE_OS::getpid (), SIGUSR1); if (signo == SIGUSR1) ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Signal SIGUSR1\n"))); else ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Signal SIGUSR2\n"))); ACE_OS::sleep (10); } #if defined (ACE_HAS_SIG_C_FUNC) } #endif // Listing 3 // Listing 2 code/ch11 static void register_actions () { ACE_TRACE ("::register_actions"); ACE_Sig_Action sa (reinterpret_cast <ACE_SignalHandler> (my_sighandler)); // Make sure we specify that SIGUSR1 will be masked out // during the signal handler's execution. ACE_Sig_Set ss; ss.sig_add (SIGUSR1); sa.mask (ss); // Register the same handler function for these // two signals. sa.register_action (SIGUSR1); sa.register_action (SIGUSR2); } // Listing 2
[ "lihuibin705@163.com" ]
lihuibin705@163.com
eaf5ba3773b91080574894358cd72f047c6ebc81
32b934cb3ef99474b7295da510420ca4a03d6017
/GamosSD/include/GmTrajPointSD.hh
50d7166079413f5c84192cb5e38784e9a7348756
[]
no_license
ethanlarochelle/GamosCore
450fc0eeb4a5a6666da7fdb75bcf5ee23a026238
70612e9a2e45b3b1381713503eb0f405530d44f0
refs/heads/master
2022-03-24T16:03:39.569576
2018-01-20T12:43:43
2018-01-20T12:43:43
116,504,426
2
0
null
null
null
null
UTF-8
C++
false
false
2,102
hh
// // ******************************************************************** // * License and Disclaimer * // * * // * The GAMOS software is copyright of the Copyright Holders of * // * the GAMOS Collaboration. It is provided under the terms and * // * conditions of the GAMOS Software License, included in the file * // * LICENSE and available at http://fismed.ciemat.es/GAMOS/license .* // * These include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GAMOS collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the GAMOS Software license. * // ******************************************************************** // #ifndef GmTrajPointSD_H #define GmTrajPointSD_H #include <vector> #include "globals.hh" #include "G4ThreeVector.hh" #include "GamosCore/GamosSD/include/GmVSD.hh" #include "GamosCore/GamosAnalysis/include/GmTrajPoint.hh" class GmTrajPointSD : public GmTrajPoint { public: GmTrajPointSD( const G4StepPoint* ); virtual ~GmTrajPointSD(); // SDType GetSDType() const { return theSDType; } private: // SDType theSDType; }; #endif
[ "ethanlarochelle@gmail.com" ]
ethanlarochelle@gmail.com
1e4c9c61b80788429aef7b3d888d0f23529ba05c
be6ca124488199b0a11a1c1a6b0e1f553d011bb1
/USB_Test/源.cpp
22f08f45581861b7815c658ea6e90d788504e078
[]
no_license
z1061227423/USB_Test
37665b2f7b091039fe1da7c08fd086c5c204c860
4fead885aa077e72e65d7f7a7017039080a3c37d
refs/heads/master
2020-03-28T10:11:09.282139
2018-09-10T09:19:20
2018-09-10T09:19:20
148,089,176
1
0
null
null
null
null
GB18030
C++
false
false
7,052
cpp
#pragma once #include <stdio.h> #include <windows.h> #include <dbt.h> #include <math.h> #include <string> #include <iostream> #include <vector> #include <fstream> #include <io.h> //#include "json/json.h" using namespace std; /* 函数名称:ReadJsonFromFile 函数功能:从Json文件中读取数据 函数入参:文件名 返回值:0 */ string ReadJsonFromFile(const char *filename) { string MasterKey = ""; string KCV = ""; Json::Reader reader;//解析json用Json::Reader Json::Value root;//Json::Value是一个很重要的类型,可以代表任意类型,如int,string,object,array. ifstream is; is.open(filename, ios::binary); if (reader.parse(is, root, FALSE)) { MasterKey = root["MasterKey"].asString(); //cout << "MasterKey:" << MasterKey << endl; KCV = root["KCV"].asString(); //cout << "KCV:" << KCV << endl; } string MainKey = MasterKey +"@"+ KCV; is.close(); if (MasterKey == "" || KCV == "") return "FALSE"; return MainKey; } /* 函数名称:GetUDiskRoot 函数功能:判断U盘是否插入并获得U盘盘符 函数入参:无 返回值:若有U盘插入,返回其盘符;无U盘插入,返回空字符 */ string GetUDiskRoot() { string UDiskRoot = ""; UINT DiskType; size_t szAllDriveStr = GetLogicalDriveStrings(0, NULL); char *pDriveStr = new char[szAllDriveStr]; char *pForDelete = pDriveStr; GetLogicalDriveStrings(szAllDriveStr, pDriveStr); size_t szDriveStr = strlen(pDriveStr); while (szDriveStr > 0) { DiskType = GetDriveType(pDriveStr); switch (DiskType) { case DRIVE_NO_ROOT_DIR: break; case DRIVE_REMOVABLE: // 移动存储设备 UDiskRoot = pDriveStr; break; case DRIVE_FIXED: // 固定硬盘驱动器 break; case DRIVE_REMOTE: // 网络驱动器 break; case DRIVE_CDROM: // 光盘驱动器 break; } pDriveStr += szDriveStr + 1; szDriveStr = strlen(pDriveStr); } delete pForDelete; return UDiskRoot; } /* 函数名称:getFiles 函数功能:在特定目录下查找特定后缀名的文件 函数入参:path,exd, */ void getFiles(string path, string exd, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string pathName, exdName; if (0 != strcmp(exd.c_str(), "")) { exdName = "\\*." + exd; } else { exdName = "\\*"; } if ((hFile = _findfirst(pathName.assign(path).append(exdName).c_str(), &fileinfo)) != -1) { do { //如果是文件夹中仍有文件夹,迭代之 //如果不是,加入列表 //不推荐使用,硬要使用的话,需要修改else 里面的语句 /*if((fileinfo.attrib & _A_SUBDIR)) { if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0) getFiles( pathName.assign(path).append("\\").append(fileinfo.name), exd, files ); } else */ { if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) //files.push_back(pathName.assign(path).append("\\").append(fileinfo.name)); // 要得到绝对目录使用该语句 //如果使用 files.push_back(fileinfo.name); // 只要得到文件名字使用该语句 } } while (_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } } /* 函数名称:GetMainKey 函数功能:获取主密钥 函数入参:无 返回值:主密钥 */ string GetMainKey() { string strTemp = GetUDiskRoot();//文件夹目录 //cout << "strTemp:" << strTemp << endl; if (strTemp == "") { cout << "please insert USB!!" << endl; system("pause"); return "false"; } string FileCatalog = strTemp + "key"; string FileExtension = "json";//文件后缀名 vector<string> files; //获取该路径下的所有json文件 getFiles(FileCatalog, FileExtension, files); int size = files.size(); for (int i = 0; i < size; i++) { cout<<files[i].c_str()<<endl; } string FILE = FileCatalog + "\\" + files[0].c_str(); string MasterKey = "";//保存密钥中MasterKey字段的值 string KCV = "";//保存密钥中KCV字段中的值 string MainKey = "";//保存Master+KCV的值,中间以@隔开 MainKey = ReadJsonFromFile(FILE.c_str()); if (MainKey == "") { cout << "read MainKey error!" << endl; return "false"; } //cout << "MainKey:" << MainKey << endl; return MainKey; } int main() { string MainKey = GetMainKey(); cout << "MainKey:" << MainKey << endl; system("pause"); return 0; } /*  LRESULT--指的是从窗口程序或者回调函数返回的32位值 CALLBACK--回调函数 当设备被插入/拔出的时候,WINDOWS会向每个窗体发送WM_DEVICECHANGE 消息, 当消息的wParam 值等于 DBT_DEVICEARRIVAL 时,表示Media设备被插入并且已经可用; 如果wParam值等于DBT_DEVICEREMOVECOMPLETE,表示Media设备已经被移出。 HWND--是类型描述,表示句柄(handle),Wnd 是变量对象描述,表示窗口,所以hWnd 表示窗口句柄 UINT msg--windows上来的消息(消息常量标识符) WPARAM--32位整型变量,无符号整数(unsigned int),具体表示什么处决于message LPARM--32位整型变量,长整型(long),具体表示什么处决于message DWORD--全称Double Word,是指注册表的键值,每个word为2个字节的长度,DWORD 双字即为4个字节,每个字节是8位,共32位。 typedef struct _DEV_BROADCAST_VOLUME { DWORD dbcv_size; DWORD dbcv_devicetype; DWORD dbcv_reserved; DWORD dbcv_unitmask; WORD dbcv_flags; } DEV_BROADCAST_VOLUME, *PDEV_BROADCAST_VOLUME; 其中dbcv_unitmask 字段表示当前改变的驱动器掩码,第一位表示驱动器号A,第二位表示驱动器号B,第三位表示驱动器号C,以此类推…… dbcv_flags 表示驱动器的类别,如果等于1,则是光盘驱动器;如果是2,则是网络驱动器;如果是硬盘、U盘则都等于0 */ LRESULT CALLBACK WndProc(HWND h, UINT msg, WPARAM wp, LPARAM lp) { if (msg == WM_DEVICECHANGE)//判断是否有Media设备插入 { if ((DWORD)wp == DBT_DEVICEARRIVAL)//判断Media设备是否已被插入并且可以使用 { DEV_BROADCAST_VOLUME* p = (DEV_BROADCAST_VOLUME*)lp; if (p->dbcv_devicetype == DBT_DEVTYP_VOLUME) { int l = (int)(log(double(p->dbcv_unitmask)) / log(double(2))); printf("%c盘插进来了\n", 'A' + l); } } else if ((DWORD)wp == DBT_DEVICEREMOVECOMPLETE)//判断Media设备是否已经被移出 { DEV_BROADCAST_VOLUME* p = (DEV_BROADCAST_VOLUME*)lp; if (p->dbcv_devicetype == DBT_DEVTYP_VOLUME) { int l = (int)(log(double(p->dbcv_unitmask)) / log(double(2))); printf("%c盘被拔掉了\n", 'A' + l); } } //cout << TRUE << endl; return 0; } else return DefWindowProc(h, msg, wp, lp); } void main01() { WNDCLASS wc; ZeroMemory(&wc, sizeof(wc)); wc.lpszClassName = TEXT("myusbmsg"); wc.lpfnWndProc = WndProc; RegisterClass(&wc); HWND h = CreateWindow(TEXT("myusbmsg"), TEXT(""), 0, 0, 0, 0, 0, 0, 0, GetModuleHandle(0), 0); MSG msg; cout << wc.lpfnWndProc << endl; while (GetMessage(&msg, 0, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } }
[ "1061227423@qq.com" ]
1061227423@qq.com
4cb197a1651cf60618873208c5fae40b0f43784d
ce8c02d3f657abc96c04c6a841b0d0f0412a2a11
/src/rpcmining.cpp
ab84cc341ca6ffb2286704dc4ed5b5049d1393dc
[ "MIT" ]
permissive
stanfordE/ETC
520e9f96da0482267f0691e74078e13901329118
47f65a81c2df2fed59db4ecb7fca25b01915eeb2
refs/heads/master
2021-01-15T14:18:50.951514
2016-09-19T18:59:07
2016-09-19T18:59:07
68,458,366
0
0
null
null
null
null
UTF-8
C++
false
false
19,431
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; // Return average network hashes per second based on the last 'lookup' blocks, // or from the last difficulty change if 'lookup' is nonpositive. // If 'height' is nonnegative, compute the estimate at the time when a given block was found. Value GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = pindexBest; if (height >= 0 && height < nBestHeight) pb = FindBlockByHeight(height); if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64 minTime = pb0->GetBlockTime(); int64 maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64 time = pb0->GetBlockTime(); minTime = std::min(time, minTime); maxTime = std::max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64 timeDiff = maxTime - minTime; return (boost::int64_t)(workDiff.getdouble() / timeDiff); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getnetworkhashps [blocks] [height]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); } // Key used by getwork/getblocktemplate miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining static CReserveKey* pMiningKey = NULL; void InitRPCMining() { if (!pwalletMain) return; // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); } void ShutdownRPCMining() { if (!pMiningKey) return; delete pMiningKey; pMiningKey = NULL; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "EnteCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "EnteCoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "EnteCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "EnteCoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); assert(pwalletMain != NULL); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "EnteCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "EnteCoin is downloading blocks..."); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int index_in_template = i - 1; entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template])); entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template])); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); if (!fAccepted) return "rejected"; // TODO: report validation state return Value::null; }
[ "sttattatndoffford@standdforddc.com" ]
sttattatndoffford@standdforddc.com
3732e54d6a08d9a1180151b7c20ac57f18267639
2276e1797b87b59e4b46af7cbcb84e920f5f9a92
/C++/A + B Problem.h
f897687e07011a77fdf555860fa10a43e26a4538
[]
no_license
ZhengyangXu/LintCode-1
dd2d6b16969ed4a39944e4f678249f2e67f20e0a
bd56ae69b4fa6a742406ec3202148b39b8f4c035
refs/heads/master
2020-03-18T04:44:31.094572
2016-01-10T00:20:44
2016-01-10T00:20:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,218
h
/* Write a function that add two numbers A and B. You should not use + or any arithmetic operators. Example Given a=1 and b=2 return 3 Note There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it. Challenge Of course you can just return a + b to get accepted. But Can you challenge not do it like that? Clarification Are a and b both 32-bit integers? Yes. Can I use bit operation? Sure you can. */ class Solution { public: /* * @param a: The first integer * @param b: The second integer * @return: The sum of a and b */ int aplusb(int a, int b) { // write your code here, try to do it without arithmetic operators. /* Support we want to add 101 and 011. iteration 1: a = 110 b = 010 iteration 2: a = 100 b = 100 iteration 3: a = 000 b = 1000 x ^ y is the add operator without considering the carry x & y << 1 is the carry */ while (b != 0) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; } };
[ "anthonyjin0619@gmail.com" ]
anthonyjin0619@gmail.com
425fe621d4ec8d79c80b4f359b4f021a09a1df47
66b557ff5280fab4dc4bc59fe893b28baffb7e3a
/Car/Car.ino
e680a9295750ea563504db520e7261df67a858e6
[]
no_license
iamashwin26/Arduino
204f07c493d062f566477b03e5f4f8d62680aee8
fb7ec567b73a6a6119bfcaa35245bd5cacbbdd45
refs/heads/master
2020-04-12T20:43:10.770555
2018-12-21T18:28:57
2018-12-21T18:28:57
162,744,946
0
0
null
null
null
null
UTF-8
C++
false
false
3,803
ino
//Components struct Wheel{ int x,y; char dirn; void setWheel(int i,int j) { pinMode(i,OUTPUT); pinMode(j,OUTPUT); x=i;y=j; } void runWheel(char dirn) { if(dirn=='f') { digitalWrite(x,HIGH); digitalWrite(y,LOW); } else if(dirn=='b') { digitalWrite(x,LOW); digitalWrite(y,HIGH); } else if(dirn=='n') { digitalWrite(x,LOW); digitalWrite(y,LOW); } } }; class IRSensor { private: int i,o; public: void Setup(int pinIn,int pinOut) { i=pinIn; o=pinOut; pinMode(i,INPUT); pinMode(o,OUTPUT); digitalWrite(o,HIGH); } bool GetsObs() { if(digitalRead(i)==0) { return false; } if(digitalRead(i)==1) { return true; } } }; class Car { private: Wheel Left,Right; bool isStarted=false; int n; public: IRSensor IR1,IR2; void Setup(int Left0,int Left1,int Right0,int Right1,int IR1_1,int IR1_2,int IR2_1,int IR2_2) { Left.setWheel(Left0,Left1); Right.setWheel(Right0,Right1); IR1.Setup(IR1_1,IR1_2); IR2.Setup(IR2_1,IR2_2); isStarted=true; n=0; } void Count(int N) { if(n>=N) { isStarted=false; } n++; } void MoveUp(int t) const { if(isStarted) { Left.runWheel('f'); Right.runWheel('f'); digitalWrite(4,HIGH); delay(t); digitalWrite(4,LOW); } else DoNothing(); } void MoveDown(int t) const { if(isStarted) { Left.runWheel('b'); Right.runWheel('b'); delay(t); } else DoNothing(); } void TurnRight(int degree) const { float t= (degree/3)* 52; if(isStarted) { Left.runWheel('f'); Right.runWheel('b'); digitalWrite(3,HIGH); delay(t); digitalWrite(3,LOW); } else DoNothing(); } void TurnLeft(int degree) const { float t=(degree/3)*46; if(isStarted) { Left.runWheel('b'); Right.runWheel('f'); pinMode(2,OUTPUT); digitalWrite(2,HIGH); delay(t); digitalWrite(2,LOW); } else DoNothing(); } void DoNothing() const { Left.runWheel('n'); Right.runWheel('n'); } void DoNothing(int t) const { DoNothing(); delay(t); } void FollowBlackLine() { if(IR1.GetsObs()&&IR2.GetsObs()) { MoveUp(1); } else if(!IR1.GetsObs()) { TurnRight(1); } else if(!IR2.GetsObs()) { TurnLeft(1); } } void FollowMe() { if(IR1.GetsObs()&&IR2.GetsObs()) { MoveUp(1); } else if(!IR1.GetsObs()&&!IR2.GetsObs()) { DoNothing(); } else if(!IR1.GetsObs()) { TurnRight(1); } else if(!IR2.GetsObs()) { TurnLeft(1); } } void FollowWallRight() { if(!IR1.GetsObs()) { MoveUp(1); } else TurnRight(1); } void FollowWallLeft() { if(!IR2.GetsObs()) { MoveUp(1); } else TurnLeft(1); } void RunAwayFromMe() { if(IR1.GetsObs()&&IR2.GetsObs()) { MoveDown(1); } else if(!IR1.GetsObs()&&!IR2.GetsObs()) { MoveUp(1); } else if(!IR1.GetsObs()) { TurnLeft(1); } else if(!IR2.GetsObs()) { TurnRight(1); } } }; //Main Logic Car car; void setup() { car.Setup(7,8,6,5,13,A0,12,A1); // Serial.begin(9600); } void loop() { // if(Serial.available()>0) // { // char data=Serial.read(); // if(data=='w')car.MoveUp(1); // if(data=='s')car.MoveDown(1); // if(data=='a')car.TurnLeft(1); // if(data=='d')car.TurnRight(1); // if(data=='e')car.DoNothing(); // } car.FollowWallRight(); }
[ "iamashwin99@gmail.com" ]
iamashwin99@gmail.com
72f7202461e7aa2e2ab9626109c3af7db3a6535b
1b070721e460125f4f4aab8649f3ca76dc48e1a7
/website/node_modules/protagonist/drafter/ext/snowcrash/test/test-MSONOneOfParser.cc
04b84f3da1df4a811497a5e6926035ae88d4e4f6
[ "MIT" ]
permissive
lewiskan/hackprojectorg
1ae9e115febcbe2b2dabaac782e8940a45d149b0
ac6e65103f4b15511668859abf76f757568d5d34
refs/heads/gh-pages
2020-05-29T17:06:13.073430
2016-09-12T22:01:07
2016-09-12T22:01:07
54,931,916
2
9
null
2016-09-12T21:53:16
2016-03-28T23:57:55
HTML
UTF-8
C++
false
false
8,439
cc
// // test-MSONOneOfParser.cc // snowcrash // // Created by Pavan Kumar Sunkara on 11/5/14. // Copyright (c) 2014 Apiary Inc. All rights reserved. // #include "snowcrashtest.h" #include "MSONOneOfParser.h" using namespace snowcrash; using namespace snowcrashtest; TEST_CASE("OneOf block classifier", "[mson][one_of]") { mdp::ByteBuffer source = \ "- one Of"; mdp::MarkdownParser markdownParser; mdp::MarkdownNode markdownAST; SectionType sectionType; markdownParser.parse(source, markdownAST); REQUIRE(!markdownAST.children().empty()); REQUIRE(markdownAST.children().front().type == mdp::ListItemMarkdownNodeType); REQUIRE(!markdownAST.children().front().children().empty()); sectionType = SectionProcessor<mson::OneOf>::sectionType(markdownAST.children().begin()); REQUIRE(sectionType == MSONOneOfSectionType); markdownAST.children().front().children().front().text = "One of"; sectionType = SectionProcessor<mson::OneOf>::sectionType(markdownAST.children().begin()); REQUIRE(sectionType == MSONOneOfSectionType); } TEST_CASE("OneOf be tolerant on parsing input","[mson][one_of]") { mdp::ByteBuffer source = \ "- one \t Of"; mdp::MarkdownParser markdownParser; mdp::MarkdownNode markdownAST; SectionType sectionType; markdownParser.parse(source, markdownAST); sectionType = SectionProcessor<mson::OneOf>::sectionType(markdownAST.children().begin()); REQUIRE(sectionType == MSONOneOfSectionType); } TEST_CASE("Parse canonical mson one of", "[mson][one_of]") { mdp::ByteBuffer source = \ "- One of\n"\ " - state: Andhra Pradesh\n"\ " - province: Madras"; ParseResult<mson::OneOf> oneOf; SectionParserHelper<mson::OneOf, MSONOneOfParser>::parseMSON(source, MSONOneOfSectionType, oneOf, ExportSourcemapOption); REQUIRE(oneOf.report.error.code == Error::OK); REQUIRE(oneOf.report.warnings.empty()); REQUIRE(oneOf.node.size() == 2); REQUIRE(oneOf.node.at(0).klass == mson::Element::PropertyClass); REQUIRE(oneOf.node.at(0).content.property.name.literal == "state"); REQUIRE(oneOf.node.at(0).content.property.valueDefinition.values.size() == 1); REQUIRE(oneOf.node.at(0).content.property.valueDefinition.values.at(0).literal == "Andhra Pradesh"); REQUIRE(oneOf.node.at(0).content.property.sections.empty()); REQUIRE(oneOf.node.at(0).content.property.description.empty()); REQUIRE(oneOf.node.at(0).content.property.name.variable.empty()); REQUIRE(oneOf.node.at(0).content.mixin.empty()); REQUIRE(oneOf.node.at(0).content.value.empty()); REQUIRE(oneOf.node.at(0).content.oneOf().empty()); REQUIRE(oneOf.node.at(0).content.elements().empty()); REQUIRE(oneOf.node.at(1).klass == mson::Element::PropertyClass); REQUIRE(oneOf.node.at(1).content.property.name.literal == "province"); REQUIRE(oneOf.node.at(1).content.property.valueDefinition.values.size() == 1); REQUIRE(oneOf.node.at(1).content.property.valueDefinition.values.at(0).literal == "Madras"); REQUIRE(oneOf.node.at(1).content.property.sections.empty()); REQUIRE(oneOf.node.at(1).content.property.description.empty()); REQUIRE(oneOf.node.at(1).content.property.name.variable.empty()); REQUIRE(oneOf.sourceMap.collection.size() == 2); SourceMapHelper::check(oneOf.sourceMap.collection[0].property.name.sourceMap, 13, 22); SourceMapHelper::check(oneOf.sourceMap.collection[0].property.valueDefinition.sourceMap, 13, 22); SourceMapHelper::check(oneOf.sourceMap.collection[1].property.name.sourceMap, 37, 19); SourceMapHelper::check(oneOf.sourceMap.collection[1].property.valueDefinition.sourceMap, 37, 19); } TEST_CASE("Parse mson one of without any nested members", "[mson][one_of]") { mdp::ByteBuffer source = "- One of\n"; ParseResult<mson::OneOf> oneOf; SectionParserHelper<mson::OneOf, MSONOneOfParser>::parseMSON(source, MSONOneOfSectionType, oneOf, ExportSourcemapOption); REQUIRE(oneOf.report.error.code == Error::OK); REQUIRE(oneOf.report.warnings.size() == 1); REQUIRE(oneOf.report.warnings[0].code == EmptyDefinitionWarning); REQUIRE(oneOf.node.empty()); REQUIRE(oneOf.sourceMap.collection.empty()); } TEST_CASE("Parse mson one of with one of", "[mson][one_of]") { mdp::ByteBuffer source = \ "- One of\n"\ " - last_name\n"\ " - one of\n"\ " - given_name\n"\ " - suffixed_name"; ParseResult<mson::OneOf> oneOf; SectionParserHelper<mson::OneOf, MSONOneOfParser>::parseMSON(source, MSONOneOfSectionType, oneOf, ExportSourcemapOption); REQUIRE(oneOf.report.error.code == Error::OK); REQUIRE(oneOf.report.warnings.empty()); REQUIRE(oneOf.node.size() == 2); REQUIRE(oneOf.node.at(0).klass == mson::Element::PropertyClass); REQUIRE(oneOf.node.at(0).content.property.name.literal == "last_name"); REQUIRE(oneOf.node.at(0).content.property.sections.empty()); REQUIRE(oneOf.node.at(0).content.property.description.empty()); REQUIRE(oneOf.node.at(0).content.property.valueDefinition.empty()); REQUIRE(oneOf.node.at(1).klass == mson::Element::OneOfClass); REQUIRE(oneOf.node.at(1).content.oneOf().size() == 2); REQUIRE(oneOf.node.at(1).content.oneOf().at(0).klass == mson::Element::PropertyClass); REQUIRE(oneOf.node.at(1).content.oneOf().at(0).content.property.name.literal == "given_name"); REQUIRE(oneOf.node.at(1).content.oneOf().at(0).content.property.valueDefinition.empty()); REQUIRE(oneOf.node.at(1).content.oneOf().at(1).klass == mson::Element::PropertyClass); REQUIRE(oneOf.node.at(1).content.oneOf().at(1).content.property.name.literal == "suffixed_name"); REQUIRE(oneOf.node.at(1).content.oneOf().at(1).content.property.valueDefinition.empty()); REQUIRE(oneOf.sourceMap.collection.size() == 2); SourceMapHelper::check(oneOf.sourceMap.collection[0].property.name.sourceMap, 15, 10); REQUIRE(oneOf.sourceMap.collection[0].property.valueDefinition.sourceMap.empty()); REQUIRE(oneOf.sourceMap.collection[1].oneOf().collection.size() == 2); SourceMapHelper::check(oneOf.sourceMap.collection[1].oneOf().collection[0].property.name.sourceMap, 48, 11); SourceMapHelper::check(oneOf.sourceMap.collection[1].oneOf().collection[1].property.name.sourceMap, 67, 16); } TEST_CASE("Parse mson one of with member group", "[mson][one_of]") { mdp::ByteBuffer source = \ "- One Of\n"\ " - full_name\n"\ " - Properties\n"\ " - first_name\n"\ " - last_name"; ParseResult<mson::OneOf> oneOf; SectionParserHelper<mson::OneOf, MSONOneOfParser>::parseMSON(source, MSONOneOfSectionType, oneOf, ExportSourcemapOption); REQUIRE(oneOf.report.error.code == Error::OK); REQUIRE(oneOf.report.warnings.empty()); REQUIRE(oneOf.node.size() == 2); REQUIRE(oneOf.node.at(0).klass == mson::Element::PropertyClass); REQUIRE(oneOf.node.at(0).content.property.name.literal == "full_name"); REQUIRE(oneOf.node.at(0).content.property.sections.empty()); REQUIRE(oneOf.node.at(0).content.property.description.empty()); REQUIRE(oneOf.node.at(0).content.property.valueDefinition.empty()); REQUIRE(oneOf.node.at(1).klass == mson::Element::GroupClass); REQUIRE(oneOf.node.at(1).content.property.empty()); REQUIRE(oneOf.node.at(1).content.mixin.empty()); REQUIRE(oneOf.node.at(1).content.value.empty()); REQUIRE(oneOf.node.at(1).content.elements().size() == 2); REQUIRE(oneOf.node.at(1).content.elements().at(0).klass == mson::Element::PropertyClass); REQUIRE(oneOf.node.at(1).content.elements().at(0).content.property.name.literal == "first_name"); REQUIRE(oneOf.node.at(1).content.elements().at(1).klass == mson::Element::PropertyClass); REQUIRE(oneOf.node.at(1).content.elements().at(1).content.property.name.literal == "last_name"); REQUIRE(oneOf.sourceMap.collection.size() == 2); SourceMapHelper::check(oneOf.sourceMap.collection[0].property.name.sourceMap, 15, 10); REQUIRE(oneOf.sourceMap.collection[0].property.valueDefinition.sourceMap.empty()); REQUIRE(oneOf.sourceMap.collection[1].elements().collection.size() == 2); SourceMapHelper::check(oneOf.sourceMap.collection[1].elements().collection[0].property.name.sourceMap, 52, 11); SourceMapHelper::check(oneOf.sourceMap.collection[1].elements().collection[1].property.name.sourceMap, 71, 12); }
[ "lewiskan@Lewiss-MacBook-Pro.local" ]
lewiskan@Lewiss-MacBook-Pro.local
6ada70a3dbe3519a99b29b8cf3b837144c42d37a
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_5918_last_repos.cpp
a2acadeb5e3681f963c4aef7ffb7b2b73e5d5779
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
109
cpp
void helperfail(const char *reason) { #if FAIL_DEBUG fail_debug_enabled =1; #endif SEND_BH(reason); }
[ "993273596@qq.com" ]
993273596@qq.com
ef3f8423136948ed3046329ab3b8a67493b1fb73
86b55c5bfd3cbce99db30907ecc63c0038b0f1e2
/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider.h
28c8e8c16481cf34162ebd51afda93f8993a4d40
[ "BSD-3-Clause" ]
permissive
Claw-Lang/chromium
3ed8160ea3f2b5d51fdc2a7d764aadd5b443eb3f
651cebac57fcd0ce2c7c974494602cc098fe7348
refs/heads/master
2022-11-19T07:46:03.573023
2020-07-28T06:45:27
2020-07-28T06:45:27
283,134,740
1
0
BSD-3-Clause
2020-07-28T07:26:49
2020-07-28T07:26:48
null
UTF-8
C++
false
false
2,788
h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_REGEX_PROVIDER_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_REGEX_PROVIDER_H_ #include <memory> #include <string> #include "base/containers/flat_map.h" #include "base/no_destructor.h" #include "base/synchronization/lock.h" #include "third_party/re2/src/re2/re2.h" namespace autofill { namespace structured_address { // Enumeration of all regular expressions supported for matching and parsing // values in an AddressComponent tree. enum class RegEx { kSingleWord, kLastRegEx = kSingleWord, }; // This singleton class builds and caches the regular expressions for value // parsing and characterization of values in an AddressComponent tree. // It also builds the foundation for acquiring expressions from different // sources. class StructuredAddressesRegExProvider { public: StructuredAddressesRegExProvider& operator=( const StructuredAddressesRegExProvider&) = delete; StructuredAddressesRegExProvider(const StructuredAddressesRegExProvider&) = delete; ~StructuredAddressesRegExProvider() = delete; // Returns a singleton instance of this class. static StructuredAddressesRegExProvider* Instance(); // Returns the regular expression corresponding to // |expression_identifier|. If the expression is not cached yet, it is build // by calling |BuildRegEx(expression_identifier)|. If the expression // can't be build, nullptr is returned. const RE2* GetRegEx(RegEx expression_identifier); #if UNIT_TEST bool IsCachedForTesting(RegEx expression_identifier) { return cached_expressions_.count(expression_identifier) > 0; } #endif private: StructuredAddressesRegExProvider(); // Since the constructor is private, |base::NoDestructor| must be a friend to // be allowed to construct the cache. friend class base::NoDestructor<StructuredAddressesRegExProvider>; // Fetches a pattern identified by |expression_identifier|. // This method is virtual and is meant to be overridden by future // implementations that utilize multiple sources for retrieving patterns. virtual std::string GetPattern(RegEx expression_identifier); // A map to store already compiled enumerated expressions keyed by // |RegEx|. base::flat_map<RegEx, std::unique_ptr<const RE2>> cached_expressions_; // A lock to prevent concurrent access to the cached expressions map. base::Lock lock_; }; } // namespace structured_address } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_PATTERN_REGEX_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
12fb686c54f66b3243f52459747dc14a9221f616
ffb568806e34199501c4ca6b61ac86ee9cc8de2e
/gflib2/RenderingEngine/include/SceneGraph/Resource/gfl2_MaterialResourceNodeFactory.h
40676bbc70a5c515cd6bcdb61a5d4bf8093d2452
[]
no_license
Fumikage8/gen7-source
433fb475695b2d5ffada25a45999f98419b75b6b
f2f572b8355d043beb468004f5e293b490747953
refs/heads/main
2023-01-06T00:00:14.171807
2020-10-20T18:49:53
2020-10-20T18:49:53
305,500,113
3
1
null
null
null
null
UTF-8
C++
false
false
9,136
h
#ifndef GFLIB2_RENDERINGENGINE_SCENEGRAPH_RESOURCE_MATERIALRESOURCENODEFAACTRY_H_INCLUDED #define GFLIB2_RENDERINGENGINE_SCENEGRAPH_RESOURCE_MATERIALRESOURCENODEFAACTRY_H_INCLUDED //#include <iostream> #include <memory> #include <types/include/gfl2_Typedef.h> #include <gfx/include/gfl2_GLMemory.h> #include <RenderingEngine/include/SceneGraph/Resource/gfl2_IResourceData.h> #include <RenderingEngine/include/SceneGraph/Resource/gfl2_ResourceNode.h> #include <RenderingEngine/include/SceneGraph/Resource/gfl2_IResourceNodeFactory.h> #include <RenderingEngine/include/SceneGraph/Resource/gfl2_MaterialResourceNode.h> namespace gfl2 { namespace renderingengine { namespace scenegraph { namespace resource { /** * @brief マテリアルリソースノードのファクトリインターフェース */ class MaterialResourceNodeFactory : public IResourceNodeFactory { public: /** * @brief BinaryFileAccessor1.0 (GfModelVersion::MeshOptCTR15103116までのローダー) */ class BinaryFileAccessor10 : public MaterialResourceNode::IBinaryFileAccessor { public: struct MaterialColor { math::Vector4 m_Emission; math::Vector4 m_Ambient; math::Vector4 m_Diffuse; math::Vector4 m_Specular0; math::Vector4 m_Specular1; }; struct EtcColor { math::Vector4 m_BlendColor; math::Vector4 m_BufferColor; math::Vector4 m_TextureBorderColor[CombinerAttribute::TextureMax]; }; struct AttributeParam{ u32 m_Priority; // 描画の優先度(描画ソートで使用, 0〜3の値しか取らない) u32 m_MaterialHash; // マテリアルのハッシュ値 b32 m_PsLightingEnable; b32 m_VsLightingEnable; s16 m_LightSetNo; b32 m_FogEnable; s16 m_FogNo; gfl2::gfx::CullMode m_CullMode; MaterialColor m_MaterialColor; //カラー/マテリアルカラー math::Vector4 m_ConstantColor[CombinerAttribute::ConstantMax]; //カラー/コンスタントカラー EtcColor m_EtcColor; //カラー/その他のカラー s16 m_BumpMapNo; //テクスチャ/バンプマッピング/バンプ使用テクスチャ s16 m_BumpMapType; //テクスチャ/バンプマッピング/使用方法 b32 m_ZRecastEnable; //テクスチャ/バンプマッピング/Z成分の再計算 MaterialResourceNode::TextureAttribute m_TextureAttribute[CombinerAttribute::TextureMax]; //テクスチャ一覧/テクスチャ b32 m_TextureAttributeEnable[CombinerAttribute::TextureMax]; b32 m_LookUpTableEnable[LookUpTableType::NumberOf]; MaterialResourceNode::LookUpTable m_LookUpTable[LookUpTableType::NumberOf]; //フラグメント/フラグメントライティング b32 m_PrimaryFresnelEnable; //フラグメント/フラグメントライティング/フレネルをプライマリに適応 b32 m_SecondaryFresnelEnable; //フラグメント/フラグメントライティング/フレネルをセカンダリに適応 b32 m_SpecularColorClamp; //フラグメント/フラグメントライティング/スペキュラをクランプ b32 m_CookTorrance0Enable; //フラグメント/フラグメントライティング/ジオメトリファクタ0 b32 m_CookTorrance1Enable; //フラグメント/フラグメントライティング/ジオメトリファクタ0 MaterialResourceNode::TextureCombinerAttribute m_TextureCombinerAttribute[CombinerColorType::NumberOf][CombinerAttribute::CombinerMax]; //フラグメント/テクスチャコンバイナ s16 m_TextureCombinerConstant[CombinerAttribute::CombinerMax]; //フラグメント/テクスチャコンバイナ/各コンスタントカラー // 特殊設定 b32 m_IsPokemonShader;//CR様の対応が完了したら削除 b32 m_UseShadowTexture; b32 m_UseObjectSpaceNormalMap; b32 m_HighLightTextureEnable; b32 m_OutLineColorTextureEnable; b32 m_BlurScaleTextureEnable; PokeNormalType m_PokeNormalType; BlendType m_BlendType; b32 m_UpdateShaderParam; }; #pragma pack(1) struct AttributeParamSlim{ u32 m_LutTextureNameHash[4]; s8 m_BumpMapNo; s8 m_ConstantColorIndex[CombinerAttribute::CombinerMax]; s8 m_LightSetNo; math::Vector4 m_ConstantColor[CombinerAttribute::ConstantMax]; b8 m_VsLightingEnable; b8 m_PsLightingEnable; b8 m_FogEnable; s8 m_FogNo; b8 m_VertexColorEnable[4]; b8 m_UseShadowTexture; b8 dummy[3]; math::Vector4 m_EmissionColor; math::Vector4 m_AmbientColor; math::Vector4 m_DiffuseColor; static const u32 s_FirstSize = (sizeof(u32) * 4) + sizeof(s8) + 3; static const u32 s_SupportConstantColorAnimSize = (sizeof(u32) * 4) + (sizeof(s8)*(1+CombinerAttribute::ConstantMax+1)) + (sizeof(math::Vector4)*CombinerAttribute::ConstantMax); static const u32 s_VertexShaderUpdate15031412Size = (sizeof(u32) * 4) + (sizeof(math::Vector4)*CombinerAttribute::ConstantMax) + 12; static const u32 s_VertexShaderUpdate15041820Size = (sizeof(u32) * 4) + (sizeof(math::Vector4)*CombinerAttribute::ConstantMax) + 12 + 4; static const u32 s_SupportShadowTexture15090718Size = s_VertexShaderUpdate15041820Size + 4; static const u32 s_SupportMaterialColor15101716Size = s_SupportShadowTexture15090718Size + (sizeof(math::Vector4) * 3);//m_EmissionColor + m_AmbientColor + m_DiffuseColor }; #pragma pack() BinaryFileAccessor10::BinaryFileAccessor10( u32 versionId ) : MaterialResourceNode::IBinaryFileAccessor(), m_VersionId( versionId ){} virtual ~BinaryFileAccessor10(){} virtual void SetAttributeParam( gfx::IGLAllocator *pAllocator, MaterialResourceNode::MaterialResourceData *pMaterialResourceData, const void *pSrc ); private: u32 m_VersionId; }; /** * @brief BinaryFileAccessor1.1 (GfModelVersion::ColorU8CTR15111314からのローダー) */ class BinaryFileAccessor11 : public MaterialResourceNode::IBinaryFileAccessor { public: #pragma pack(1) struct AttributeParamSlim{ u32 m_LutTextureNameHash[4]; s8 m_BumpMapNo; s8 m_ConstantColorIndex[CombinerAttribute::CombinerMax]; s8 m_LightSetNo; gfx::ColorU8 m_ConstantColor[CombinerAttribute::ConstantMax]; b8 m_VsLightingEnable; b8 m_PsLightingEnable; b8 m_FogEnable; s8 m_FogNo; b8 m_VertexColorEnable[4]; b8 m_UseShadowTexture; b8 dummy[3]; gfx::ColorU8 m_EmissionColor; gfx::ColorU8 m_AmbientColor; gfx::ColorU8 m_DiffuseColor; }; #pragma pack() BinaryFileAccessor11( u32 versionId ) : MaterialResourceNode::IBinaryFileAccessor(), m_VersionId( versionId ){} virtual ~BinaryFileAccessor11(){} virtual void SetAttributeParam( gfx::IGLAllocator *pAllocator, MaterialResourceNode::MaterialResourceData *pMaterialResourceData, const void *pSrc ); private: u32 m_VersionId; }; MaterialResourceNodeFactory():IResourceNodeFactory(){} virtual ~MaterialResourceNodeFactory() {} /** * @brief ResourceNodeのファクトリメソッド 所有権付きのリソースノードを返す */ //virtual ResourceNode* CreateResourceNode(const void* data, int size); virtual ResourceNode* CreateResourceNode(gfx::IGLAllocator* pAllocator, const void* data, int size); virtual b32 IsSupport( IResourceData::Type type ); }; }}}} #endif
[ "forestgamer141@gmail.com" ]
forestgamer141@gmail.com
76737afd16e0b13ac81ec75a55a64f568d34a5ba
33e67303e33744f3f9c32a44fbe37aad878a0bca
/aws-cpp-sdk-ec2/source/model/DirectoryServiceAuthentication.cpp
06c820b60808c046c0f2a25b0c593489012065bd
[ "Apache-2.0", "MIT", "JSON" ]
permissive
crazecdwn/aws-sdk-cpp
2694bebef950e85af0104d10f8f326d54c057844
e74b9181a56e82ee04cf36a4cb31686047f4be42
refs/heads/master
2022-07-09T05:06:43.395448
2020-06-12T01:38:17
2020-06-12T01:38:17
192,119,343
0
0
Apache-2.0
2022-05-20T22:07:13
2019-06-15T20:03:54
C++
UTF-8
C++
false
false
2,208
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/ec2/model/DirectoryServiceAuthentication.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace EC2 { namespace Model { DirectoryServiceAuthentication::DirectoryServiceAuthentication() : m_directoryIdHasBeenSet(false) { } DirectoryServiceAuthentication::DirectoryServiceAuthentication(const XmlNode& xmlNode) : m_directoryIdHasBeenSet(false) { *this = xmlNode; } DirectoryServiceAuthentication& DirectoryServiceAuthentication::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode directoryIdNode = resultNode.FirstChild("directoryId"); if(!directoryIdNode.IsNull()) { m_directoryId = StringUtils::Trim(directoryIdNode.GetText().c_str()); m_directoryIdHasBeenSet = true; } } return *this; } void DirectoryServiceAuthentication::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_directoryIdHasBeenSet) { oStream << location << index << locationValue << ".DirectoryId=" << StringUtils::URLEncode(m_directoryId.c_str()) << "&"; } } void DirectoryServiceAuthentication::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_directoryIdHasBeenSet) { oStream << location << ".DirectoryId=" << StringUtils::URLEncode(m_directoryId.c_str()) << "&"; } } } // namespace Model } // namespace EC2 } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
87c0392d7e8c670a078b07701daaf97035223fba
b0dd7779c225971e71ae12c1093dc75ed9889921
/libs/spirit/test/support/utree_debug.cpp
8e8dc5da93db67dd2ac84ab74b8b05b034697a47
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
828
cpp
// Copyright (c) 2001-2011 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/detail/lightweight_test.hpp> #define BOOST_SPIRIT_DEBUG 1 #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/support_utree.hpp> #include <string> namespace qi = boost::spirit::qi; namespace spirit = boost::spirit; int main() { qi::rule<std::string::iterator, spirit::utree()> r = qi::int_; BOOST_SPIRIT_DEBUG_NODE(r); spirit::utree ut; std::string input("1"); BOOST_TEST(qi::parse(input.begin(), input.end(), r, ut)); BOOST_TEST(ut.which() == spirit::utree_type::int_type && ut.get<int>() == 1); return boost::report_errors(); }
[ "tvaneerd@rim.com" ]
tvaneerd@rim.com
a6578a0efc809cb62bfb0e32b45a7681a34790f4
e396342013eb72e56ab526b2f43f8377e5846d7d
/cpp/json_client/main.cpp
c5659c6debfbde55e0113db1ca42dfb85c9696a1
[ "MIT" ]
permissive
AtsushiSakai/JSONServerAndClient
e7f4099b60be3ecb5d31ee30a14fc6dd95fe4946
a7e7cea92616c7e42d46d198f8276aa6c1c50b49
refs/heads/master
2021-06-03T17:17:31.921829
2020-10-10T05:24:27
2020-10-10T05:24:27
134,957,224
3
0
null
null
null
null
UTF-8
C++
false
false
1,110
cpp
// // Json http client in C++ // // Author: Atsushi Sakai // #include <iostream> #include "../cpp-httplib/httplib.h" #include "../json/single_include/nlohmann/json.hpp" using namespace std; using json = nlohmann::json; string get_server_ip(){ string SERVER_IP="localhost"; char* env_SERVER_IP = getenv("SERVER_IP"); if (env_SERVER_IP != NULL){ SERVER_IP=string(env_SERVER_IP); } return SERVER_IP; } int main(void){ cout<<"c++ Json client start !!"<<endl; // Create request json map<string, string> c_map { {"Name", "request_from_cpp_client"}, {"Test", "test"} }; json j_map(c_map); string sjson = j_map.dump(); cout << "Request:" << endl; cout << sjson << endl; string SERVER_IP = get_server_ip(); httplib::Client cli(SERVER_IP.c_str(), 8000); auto res = cli.Post("/", sjson, "application/json"); if (res && res->status == 200) { cout << "Response:" << endl; auto jres = json::parse(res->body); for (json::iterator it = jres.begin(); it != jres.end(); ++it) { cout << it.key() << " : " << it.value() << endl; } } }
[ "asakai.amsl+github@gmail.com" ]
asakai.amsl+github@gmail.com
da57f807cd61b16d513ec4c76a377bc7e2bcc40c
b57597cebe2feb4a2455256f47da4e464b2787ff
/string/819.cpp
1c6e87618ec06cf8d1deb65ec22352bfc3c8be5f
[]
no_license
lijiahao-debug/leetcode
beda7e17cee3ac93c09ce0350896a1836db14085
a3e345215337b4d9ba0dd46cad05371bdfe5fcf5
refs/heads/master
2021-07-01T08:35:23.651536
2021-03-08T08:21:14
2021-03-08T08:21:14
225,348,344
2
2
null
2019-12-14T14:18:17
2019-12-02T10:32:57
C
UTF-8
C++
false
false
1,726
cpp
#include <algorithm> #include <iostream> #include <map> #include <string> #include <vector> using namespace std; class Solution { public: string mostCommonWord(string paragraph, vector<string> &banned) { map<string, int> table; int len = paragraph.length(); transform(paragraph.begin(), paragraph.end(), paragraph.begin(), [](unsigned char c) { return tolower(c); }); int index = 0; map<string, int>::iterator iter; for (int i = 0; i < len; i++) { if (!isalpha(paragraph[i]) || i == len - 1) { if (i == len - 1 && isalpha(paragraph[i])) { ++i; } if (i - index > 0) { string word = paragraph.substr(index, i - index); if (find(banned.begin(), banned.end(), word) == banned.end()) { iter = table.find(word); if (iter != table.end()) { iter->second += 1; } else { table.insert(pair<string, int>(word, 1)); } } } index = i + 1; } } int max = 0; string ret = ""; for (iter = table.begin(); iter != table.end(); iter++) { if (max < iter->second) { max = iter->second; ret = iter->first; } } return ret; } }; int main() { Solution s; vector<string> v = {"hit"}; cout << s.mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", v) << endl; cout << s.mostCommonWord("Bob", v) << endl; return 0; }
[ "lijh.sdu@gmail.com" ]
lijh.sdu@gmail.com
9758365e08efc74f12e84580036a6ebed6a3d0ee
38030e497b6e172cb926ebce4d25019175713bbd
/Basic/Sum of numbers in a string.cpp
99e44b693f5cd3d167c3e8b3e57194180d1dcbd7
[]
no_license
KushRohra/GFG_Codes
7e6126434360bd0e376ce13be7e855c380b88d24
54e2b0affeaac3406aa052c28cfebcefc6492f90
refs/heads/master
2021-03-26T00:37:05.871686
2020-12-27T12:51:53
2020-12-27T12:51:53
247,659,010
0
0
null
null
null
null
UTF-8
C++
false
false
487
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int i,n=0,sum=0,sum1=0,f=0; string s; cin>>s; n=s.length(); for(i=0;i<n;i++) { int x = int(s[i]); if(x>=48 && x<=57) { if(f==0) { sum1=0; sum1+=x-48; f=1; } else { sum1=sum1*10+x-48; } } else { sum+=sum1; f=0; sum1=0; } } sum+=sum1; cout<<sum<<endl; } } /* 4 1abc23 geeks4geeks 1abc2s30aw67 123abc */
[ "iec2017024@iiita.ac.in" ]
iec2017024@iiita.ac.in
d4ac19757d1880173637ca6c2d7c076a38a88762
101d2a53dc097aa9e7bf2599e7c1be24b3813016
/src/bind/Board.cxx
df31f70b3658db1f197ff997b09bfb21d569487d
[ "Apache-2.0" ]
permissive
RohiniBisht/group-13-smce-gd
1cc0dfca063c79588c4b02a8c5e3d343f5dffb09
d58e68ebace1757ed315951c92e374514cf6512d
refs/heads/master
2023-09-02T12:51:56.932409
2021-11-05T08:27:39
2021-11-05T08:27:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,461
cxx
/* * Board.cxx * Copyright 2021 ItJustWorksTM * * 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 <iostream> #include "bind/Board.hxx" #include "bind/BoardView.hxx" using namespace godot; #define STR(s) #s #define U(f) \ std::pair { STR(f), &Board::f } void Board::_register_methods() { register_signals<Board>("initialized", "configured", "started", "suspended_resumed", "stopped", "cleaned", "log"); register_fns(U(reset), U(start), U(suspend), U(resume), U(terminate), U(configure), U(status), U(view), U(uart), U(_physics_process), U(attach_sketch), U(get_sketch)); } #undef STR #undef U Board::Board() : board{[&](int res) { set_view(); emit_signal("stopped", res); }} {} void Board::_init() { view_node = BoardView::_new(); uart_node = UartSlurper::_new(); add_child(view_node); add_child(uart_node); set_physics_process(false); } smce::Board& Board::native() { return board; } void Board::set_view() { auto view = board.view(); view_node->set_view(view); uart_node->set_view(view); } Ref<GDResult> Board::configure(Ref<BoardConfig> board_config) { if (!board_config.is_valid()) return GDResult::err("Invalid BoardConfig"); bconfig = board_config->to_native(); auto res = reconfigure(); if (res->is_ok()) emit_signal("configured"); return res; } Ref<GDResult> Board::reconfigure() { if (!is_status(smce::Board::Status::clean)) return GDResult::err("Board not clean"); if (!board.configure(bconfig)) return GDResult::err("Failed to configure internal runner"); if (sketch.is_valid()) if (auto res = attach_sketch(sketch); !res->is_ok()) return res; set_view(); return GDResult::ok(); } Ref<GDResult> Board::attach_sketch(Ref<Sketch> sketch) { if (sketch.is_null()) return GDResult::err("Invalid sketch"); if (is_status(smce::Board::Status::running, smce::Board::Status::running)) return GDResult::err("Board still running"); if (!board.attach_sketch(sketch->native())) return GDResult::err("Failed to attach sketch"); this->sketch = sketch; return GDResult::ok(); } Ref<GDResult> Board::start() { if (sketch.is_null()) return GDResult::err("No sketch attached"); if (!sketch->is_compiled()) return GDResult::err("Sketch is not compiled"); if (is_status(smce::Board::Status::clean)) return GDResult::err("Board not configured"); if (is_status(smce::Board::Status::running, smce::Board::Status::suspended)) return GDResult::err("Board already started"); // Workaround for libSMCE crash when starting a sketch again if (is_status(smce::Board::Status::stopped)) { if (!board.reset()) return GDResult::err("Failed to reset"); if (auto res = reconfigure(); !res->is_ok()) return res; } if (!board.start()) return GDResult::err("Failed to start internal runner"); set_view(); emit_signal("started"); set_physics_process(true); return GDResult::ok(); } Ref<GDResult> Board::suspend() { if (!is_status(smce::Board::Status::running)) return GDResult::err("Sketch is not running"); if (!board.suspend()) return GDResult::err("Failed to suspend internal runner"); emit_signal("suspended_resumed", true); return GDResult::ok(); } Ref<GDResult> Board::resume() { if (!is_status(smce::Board::Status::suspended)) return GDResult::err("Sketch is not suspended"); if (!board.resume()) return GDResult::err("Failed to resume internal runner"); emit_signal("suspended_resumed", false); return GDResult::ok(); } Ref<GDResult> Board::reset() { if (!board.reset()) return GDResult::err("Failed to reset"); emit_signal("cleaned"); return GDResult::ok(); } void Board::_physics_process() { auto [_, str] = board.runtime_log(); if (!is_status(smce::Board::Status::running, smce::Board::Status::suspended) && str.empty()) set_physics_process(false); if (!str.empty()) { std::replace_if( str.begin(), str.end(), [](const auto& c) { return c == '\r'; }, '\t'); emit_signal("log", String{str.data()}); std::cout << str; str.clear(); } board.tick(); } Ref<GDResult> Board::terminate() { if (!board.terminate()) return GDResult::err("Failed to terminate internal runner"); set_view(); emit_signal("stopped", 0); return GDResult::ok(); } int Board::status() { return static_cast<int>(board.status()); } UartSlurper* Board::uart() { return uart_node; } BoardView* Board::view() { return view_node; } Ref<Sketch> Board::get_sketch() { return sketch; }
[ "ruthgerdijt@gmail.com" ]
ruthgerdijt@gmail.com
bc6bcbc8079d5b2a9428cde6b86860deb74a1100
259a7cb060c839abda6cca8e7072f78df1e33a0e
/src/main.cpp
a607f3a58e4c8ce5d9ccfb5bcedea59dd21b9881
[]
no_license
bayuajik2403/observer-pattern-simple-example-c-
9001930ab2f3e659aa28a9806f3d09e09815fb78
08b2df2d4ab230f6f2e8ba56e1c47ce13bce42df
refs/heads/master
2022-12-20T01:34:52.605534
2020-09-25T01:51:55
2020-09-25T01:51:55
298,439,653
0
0
null
null
null
null
UTF-8
C++
false
false
672
cpp
#include "../include/Observer.h" #include "../include/statusObserver1.h" #include "../include/statusObserver2.h" #include "../include/statusObserver3.h" #include "../include/statusSubject.h" #include <iostream> #include <string> int main(int argc, char const *argv[]) { statusSubject a; statusObserver1 *b = new statusObserver1; statusObserver2 *c = new statusObserver2; statusObserver3 *d = new statusObserver3; // add status oberver, so it will be notified when there is status change a.addStatusObserver(b); a.addStatusObserver(c); a.addStatusObserver(d); // to notify a status change a.Notify(true); return 0; }
[ "24bayu03@gmail.com" ]
24bayu03@gmail.com
8636f252de15e38db1d31ae88e2b328b3fcbcacd
2b4926fd49a0fcebbed2b39b589202fc686836a5
/lib-src/trees/fibheap.cc
e6e2dec95d7212d5a6cfb54aeba65c9b3b22d9b1
[ "BSD-2-Clause" ]
permissive
prop-cc/prop-cc
c88eef95490b2fad048d0df617333ab94fdd497f
3569940fc0d039d10b9d6389e8e7a5aa6daae3a2
refs/heads/master
2020-12-25T05:27:49.470629
2011-09-14T21:20:19
2011-09-14T21:20:19
2,223,487
1
0
null
null
null
null
UTF-8
C++
false
false
1,044
cc
////////////////////////////////////////////////////////////////////////////// // NOTICE: // // ADLib, Prop and their related set of tools and documentation are in the // public domain. The author(s) of this software reserve no copyrights on // the source code and any code generated using the tools. You are encouraged // to use ADLib and Prop to develop software, in both academic and commercial // settings, and are free to incorporate any part of ADLib and Prop into // your programs. // // Although you are under no obligation to do so, we strongly recommend that // you give away all software developed using our tools. // // We also ask that credit be given to us when ADLib and/or Prop are used in // your programs, and that this notice be preserved intact in all the source // code. // // This software is still under development and we welcome any suggestions // and help from the users. // // Allen Leung // 1994 ////////////////////////////////////////////////////////////////////////////// #include <AD/trees/fibheap.h>
[ "aaronngray@gmail.com" ]
aaronngray@gmail.com
d0dd7be732bf5c61cd233818bd8578db38cccfc6
69a22a21b7df8a23c74ce34d75a375936e3b426f
/coline/smartlib/Smart/scintilla/RESearch.cxx
e00cdfe6fb9af33bd05daec9b5fa3799e5ff5978
[]
no_license
lanyawu/coline
ba8681c1b2242365cccef2b95bcb771c18af45fa
b63b997002e2e1d14674cde9a8ff1c95a6a299aa
refs/heads/master
2021-05-04T05:16:10.474229
2016-10-15T05:52:47
2016-10-15T05:52:47
70,963,112
0
0
null
null
null
null
UTF-8
C++
false
false
27,536
cxx
// Scintilla source code edit control /** @file RESearch.cxx ** Regular expression search library. **/ /* * regex - Regular expression pattern matching and replacement * * By: Ozan S. Yigit (oz) * Dept. of Computer Science * York University * * Original code available from http://www.cs.yorku.ca/~oz/ * Translation to C++ by Neil Hodgson neilh@scintilla.org * Removed all use of register. * Converted to modern function prototypes. * Put all global/static variables into an object so this code can be * used from multiple threads, etc. * Some extensions by Philippe Lhoste PhiLho(a)GMX.net * * These routines are the PUBLIC DOMAIN equivalents of regex * routines as found in 4.nBSD UN*X, with minor extensions. * * These routines are derived from various implementations found * in software tools books, and Conroy's grep. They are NOT derived * from licensed/restricted software. * For more interesting/academic/complicated implementations, * see Henry Spencer's regexp routines, or GNU Emacs pattern * matching module. * * Modification history removed. * * Interfaces: * RESearch::Compile: compile a regular expression into a NFA. * * const char *RESearch::Compile(const char *pattern, int length, * bool caseSensitive, bool posix) * * Returns a short error string if they fail. * * RESearch::Execute: execute the NFA to match a pattern. * * int RESearch::Execute(characterIndexer &ci, int lp, int endp) * * RESearch::Substitute: substitute the matched portions in a new string. * * int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst) * * re_fail: failure routine for RESearch::Execute. (no longer used) * * void re_fail(char *msg, char op) * * Regular Expressions: * * [1] char matches itself, unless it is a special * character (metachar): . \ [ ] * + ^ $ * and ( ) if posix option. * * [2] . matches any character. * * [3] \ matches the character following it, except: * - \a, \b, \f, \n, \r, \t, \v match the corresponding C * escape char, respectively BEL, BS, FF, LF, CR, TAB and VT; * Note that \r and \n are never matched because Scintilla * regex searches are made line per line * (stripped of end-of-line chars). * - if not in posix mode, when followed by a * left or right round bracket (see [7]); * - when followed by a digit 1 to 9 (see [8]); * - when followed by a left or right angle bracket * (see [9]); * - when followed by d, D, s, S, w or W (see [10]); * - when followed by x and two hexa digits (see [11]. * Backslash is used as an escape character for all * other meta-characters, and itself. * * [4] [set] matches one of the characters in the set. * If the first character in the set is "^", * it matches the characters NOT in the set, i.e. * complements the set. A shorthand S-E (start dash end) * is used to specify a set of characters S up to * E, inclusive. S and E must be characters, otherwise * the dash is taken literally (eg. in expression [\d-a]). * The special characters "]" and "-" have no special * meaning if they appear as the first chars in the set. * To include both, put - first: [-]A-Z] * (or just backslash them). * examples: match: * * [-]|] matches these 3 chars, * * []-|] matches from ] to | chars * * [a-z] any lowercase alpha * * [^-]] any char except - and ] * * [^A-Z] any char except uppercase * alpha * * [a-zA-Z] any alpha * * [5] * any regular expression form [1] to [4] * (except [7], [8] and [9] forms of [3]), * followed by closure char (*) * matches zero or more matches of that form. * * [6] + same as [5], except it matches one or more. * Both [5] and [6] are greedy (they match as much as possible). * * [7] a regular expression in the form [1] to [12], enclosed * as \(form\) (or (form) with posix flag) matches what * form matches. The enclosure creates a set of tags, * used for [8] and for pattern substitution. * The tagged forms are numbered starting from 1. * * [8] a \ followed by a digit 1 to 9 matches whatever a * previously tagged regular expression ([7]) matched. * * [9] \< a regular expression starting with a \< construct * \> and/or ending with a \> construct, restricts the * pattern matching to the beginning of a word, and/or * the end of a word. A word is defined to be a character * string beginning and/or ending with the characters * A-Z a-z 0-9 and _. Scintilla extends this definition * by user setting. The word must also be preceded and/or * followed by any character outside those mentioned. * * [10] \l a backslash followed by d, D, s, S, w or W, * becomes a character class (both inside and * outside sets []). * d: decimal digits * D: any char except decimal digits * s: whitespace (space, \t \n \r \f \v) * S: any char except whitespace (see above) * w: alphanumeric & underscore (changed by user setting) * W: any char except alphanumeric & underscore (see above) * * [11] \xHH a backslash followed by x and two hexa digits, * becomes the character whose Ascii code is equal * to these digits. If not followed by two digits, * it is 'x' char itself. * * [12] a composite regular expression xy where x and y * are in the form [1] to [11] matches the longest * match of x followed by a match for y. * * [13] ^ a regular expression starting with a ^ character * $ and/or ending with a $ character, restricts the * pattern matching to the beginning of the line, * or the end of line. [anchors] Elsewhere in the * pattern, ^ and $ are treated as ordinary characters. * * * Acknowledgements: * * HCR's Hugh Redelmeier has been most helpful in various * stages of development. He convinced me to include BOW * and EOW constructs, originally invented by Rob Pike at * the University of Toronto. * * References: * Software tools Kernighan & Plauger * Software tools in Pascal Kernighan & Plauger * Grep [rsx-11 C dist] David Conroy * ed - text editor Un*x Programmer's Manual * Advanced editing on Un*x B. W. Kernighan * RegExp routines Henry Spencer * * Notes: * * This implementation uses a bit-set representation for character * classes for speed and compactness. Each character is represented * by one bit in a 256-bit block. Thus, CCL always takes a * constant 32 bytes in the internal nfa, and RESearch::Execute does a single * bit comparison to locate the character in the set. * * Examples: * * pattern: foo*.* * compile: CHR f CHR o CLO CHR o END CLO ANY END END * matches: fo foo fooo foobar fobar foxx ... * * pattern: fo[ob]a[rz] * compile: CHR f CHR o CCL bitset CHR a CCL bitset END * matches: fobar fooar fobaz fooaz * * pattern: foo\\+ * compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END * matches: foo\ foo\\ foo\\\ ... * * pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo) * compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END * matches: foo1foo foo2foo foo3foo * * pattern: \(fo.*\)-\1 * compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END * matches: foo-foo fo-fo fob-fob foobar-foobar ... */ #include <stdlib.h> #include "CharClassify.h" #include "RESearch.h" // Shut up annoying Visual C++ warnings: #ifdef _MSC_VER #pragma warning(disable: 4514) #endif #ifdef SCI_NAMESPACE using namespace Scintilla; #endif #define OKP 1 #define NOP 0 #define CHR 1 #define ANY 2 #define CCL 3 #define BOL 4 #define EOL 5 #define BOT 6 #define EOT 7 #define BOW 8 #define EOW 9 #define REF 10 #define CLO 11 #define END 0 /* * The following defines are not meant to be changeable. * They are for readability only. */ #define BLKIND 0370 #define BITIND 07 const char bitarr[] = { 1, 2, 4, 8, 16, 32, 64, '\200' }; #define badpat(x) (*nfa = END, x) /* * Character classification table for word boundary operators BOW * and EOW is passed in by the creator of this object (Scintilla * Document). The Document default state is that word chars are: * 0-9, a-z, A-Z and _ */ RESearch::RESearch(CharClassify *charClassTable) { failure = 0; charClass = charClassTable; Init(); } RESearch::~RESearch() { Clear(); } void RESearch::Init() { sta = NOP; /* status of lastpat */ bol = 0; for (int i = 0; i < MAXTAG; i++) pat[i] = 0; for (int j = 0; j < BITBLK; j++) bittab[j] = 0; } void RESearch::Clear() { for (int i = 0; i < MAXTAG; i++) { delete []pat[i]; pat[i] = 0; bopat[i] = NOTFOUND; eopat[i] = NOTFOUND; } } bool RESearch::GrabMatches(CharacterIndexer &ci) { bool success = true; for (unsigned int i = 0; i < MAXTAG; i++) { if ((bopat[i] != NOTFOUND) && (eopat[i] != NOTFOUND)) { unsigned int len = eopat[i] - bopat[i]; pat[i] = new char[len + 1]; if (pat[i]) { for (unsigned int j = 0; j < len; j++) pat[i][j] = ci.CharAt(bopat[i] + j); pat[i][len] = '\0'; } else { success = false; } } } return success; } void RESearch::ChSet(unsigned char c) { bittab[((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND]; } void RESearch::ChSetWithCase(unsigned char c, bool caseSensitive) { if (caseSensitive) { ChSet(c); } else { if ((c >= 'a') && (c <= 'z')) { ChSet(c); ChSet(static_cast<unsigned char>(c - 'a' + 'A')); } else if ((c >= 'A') && (c <= 'Z')) { ChSet(c); ChSet(static_cast<unsigned char>(c - 'A' + 'a')); } else { ChSet(c); } } } const unsigned char escapeValue(unsigned char ch) { switch (ch) { case 'a': return '\a'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; } return 0; } static int GetHexaChar(unsigned char hd1, unsigned char hd2) { int hexValue = 0; if (hd1 >= '0' && hd1 <= '9') { hexValue += 16 * (hd1 - '0'); } else if (hd1 >= 'A' && hd1 <= 'F') { hexValue += 16 * (hd1 - 'A' + 10); } else if (hd1 >= 'a' && hd1 <= 'f') { hexValue += 16 * (hd1 - 'a' + 10); } else return -1; if (hd2 >= '0' && hd2 <= '9') { hexValue += hd2 - '0'; } else if (hd2 >= 'A' && hd2 <= 'F') { hexValue += hd2 - 'A' + 10; } else if (hd2 >= 'a' && hd2 <= 'f') { hexValue += hd2 - 'a' + 10; } else return -1; return hexValue; } /** * Called when the parser finds a backslash not followed * by a valid expression (like \( in non-Posix mode). * @param pattern: pointer on the char after the backslash. * @param incr: (out) number of chars to skip after expression evaluation. * @return the char if it resolves to a simple char, * or -1 for a char class. In this case, bittab is changed. */ int RESearch::GetBackslashExpression( const char *pattern, int &incr) { // Since error reporting is primitive and messages are not used anyway, // I choose to interpret unexpected syntax in a logical way instead // of reporting errors. Otherwise, we can stick on, eg., PCRE behavior. incr = 0; // Most of the time, will skip the char "naturally". int c; int result = -1; unsigned char bsc = *pattern; if (!bsc) { // Avoid overrun result = '\\'; // \ at end of pattern, take it literally return result; } switch (bsc) { case 'a': case 'b': case 'n': case 'f': case 'r': case 't': case 'v': result = escapeValue(bsc); break; case 'x': { unsigned char hd1 = *(pattern + 1); unsigned char hd2 = *(pattern + 2); int hexValue = GetHexaChar(hd1, hd2); if (hexValue >= 0) { result = hexValue; incr = 2; // Must skip the digits } else { result = 'x'; // \x without 2 digits: see it as 'x' } } break; case 'd': for (c = '0'; c <= '9'; c++) { ChSet(static_cast<unsigned char>(c)); } break; case 'D': for (c = 0; c < MAXCHR; c++) { if (c < '0' || c > '9') { ChSet(static_cast<unsigned char>(c)); } } break; case 's': ChSet(' '); ChSet('\t'); ChSet('\n'); ChSet('\r'); ChSet('\f'); ChSet('\v'); break; case 'S': for (c = 0; c < MAXCHR; c++) { if (c != ' ' && !(c >= 0x09 && c <= 0x0D)) { ChSet(static_cast<unsigned char>(c)); } } break; case 'w': for (c = 0; c < MAXCHR; c++) { if (iswordc(static_cast<unsigned char>(c))) { ChSet(static_cast<unsigned char>(c)); } } break; case 'W': for (c = 0; c < MAXCHR; c++) { if (!iswordc(static_cast<unsigned char>(c))) { ChSet(static_cast<unsigned char>(c)); } } break; default: result = bsc; } return result; } const char *RESearch::Compile(const char *pattern, int length, bool caseSensitive, bool posix) { char *mp=nfa; /* nfa pointer */ char *lp; /* saved pointer */ char *sp=nfa; /* another one */ char *mpMax = mp + MAXNFA - BITBLK - 10; int tagi = 0; /* tag stack index */ int tagc = 1; /* actual tag count */ int n; char mask; /* xor mask -CCL/NCL */ int c1, c2, prevChar; if (!pattern || !length) { if (sta) return 0; else return badpat("No previous regular expression"); } sta = NOP; const char *p=pattern; /* pattern pointer */ for (int i=0; i<length; i++, p++) { if (mp > mpMax) return badpat("Pattern too long"); lp = mp; switch (*p) { case '.': /* match any char */ *mp++ = ANY; break; case '^': /* match beginning */ if (p == pattern) *mp++ = BOL; else { *mp++ = CHR; *mp++ = *p; } break; case '$': /* match endofline */ if (!*(p+1)) *mp++ = EOL; else { *mp++ = CHR; *mp++ = *p; } break; case '[': /* match char class */ *mp++ = CCL; prevChar = 0; i++; if (*++p == '^') { mask = '\377'; i++; p++; } else mask = 0; if (*p == '-') { /* real dash */ i++; prevChar = *p; ChSet(*p++); } if (*p == ']') { /* real brace */ i++; prevChar = *p; ChSet(*p++); } while (*p && *p != ']') { if (*p == '-') { if (prevChar < 0) { // Previous def. was a char class like \d, take dash literally prevChar = *p; ChSet(*p); } else if (*(p+1)) { if (*(p+1) != ']') { c1 = prevChar + 1; i++; c2 = *++p; if (c2 == '\\') { if (!*(p+1)) // End of RE return badpat("Missing ]"); else { i++; p++; int incr; c2 = GetBackslashExpression(p, incr); i += incr; p += incr; if (c2 >= 0) { // Convention: \c (c is any char) is case sensitive, whatever the option ChSet(static_cast<unsigned char>(c2)); prevChar = c2; } else { // bittab is already changed prevChar = -1; } } } if (prevChar < 0) { // Char after dash is char class like \d, take dash literally prevChar = '-'; ChSet('-'); } else { // Put all chars between c1 and c2 included in the char set while (c1 <= c2) { ChSetWithCase(static_cast<unsigned char>(c1++), caseSensitive); } } } else { // Dash before the ], take it literally prevChar = *p; ChSet(*p); } } else { return badpat("Missing ]"); } } else if (*p == '\\' && *(p+1)) { i++; p++; int incr; int c = GetBackslashExpression(p, incr); i += incr; p += incr; if (c >= 0) { // Convention: \c (c is any char) is case sensitive, whatever the option ChSet(static_cast<unsigned char>(c)); prevChar = c; } else { // bittab is already changed prevChar = -1; } } else { prevChar = *p; ChSetWithCase(*p, caseSensitive); } i++; p++; } if (!*p) return badpat("Missing ]"); for (n = 0; n < BITBLK; bittab[n++] = 0) *mp++ = static_cast<char>(mask ^ bittab[n]); break; case '*': /* match 0 or more... */ case '+': /* match 1 or more... */ if (p == pattern) return badpat("Empty closure"); lp = sp; /* previous opcode */ if (*lp == CLO) /* equivalence... */ break; switch (*lp) { case BOL: case BOT: case EOT: case BOW: case EOW: case REF: return badpat("Illegal closure"); default: break; } if (*p == '+') for (sp = mp; lp < sp; lp++) *mp++ = *lp; *mp++ = END; *mp++ = END; sp = mp; while (--mp > lp) *mp = mp[-1]; *mp = CLO; mp = sp; break; case '\\': /* tags, backrefs... */ i++; switch (*++p) { case '<': *mp++ = BOW; break; case '>': if (*sp == BOW) return badpat("Null pattern inside \\<\\>"); *mp++ = EOW; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': n = *p-'0'; if (tagi > 0 && tagstk[tagi] == n) return badpat("Cyclical reference"); if (tagc > n) { *mp++ = static_cast<char>(REF); *mp++ = static_cast<char>(n); } else return badpat("Undetermined reference"); break; default: if (!posix && *p == '(') { if (tagc < MAXTAG) { tagstk[++tagi] = tagc; *mp++ = BOT; *mp++ = static_cast<char>(tagc++); } else return badpat("Too many \\(\\) pairs"); } else if (!posix && *p == ')') { if (*sp == BOT) return badpat("Null pattern inside \\(\\)"); if (tagi > 0) { *mp++ = static_cast<char>(EOT); *mp++ = static_cast<char>(tagstk[tagi--]); } else return badpat("Unmatched \\)"); } else { int incr; int c = GetBackslashExpression(p, incr); i += incr; p += incr; if (c >= 0) { *mp++ = CHR; *mp++ = static_cast<unsigned char>(c); } else { *mp++ = CCL; mask = 0; for (n = 0; n < BITBLK; bittab[n++] = 0) *mp++ = static_cast<char>(mask ^ bittab[n]); } } } break; default : /* an ordinary char */ if (posix && *p == '(') { if (tagc < MAXTAG) { tagstk[++tagi] = tagc; *mp++ = BOT; *mp++ = static_cast<char>(tagc++); } else return badpat("Too many () pairs"); } else if (posix && *p == ')') { if (*sp == BOT) return badpat("Null pattern inside ()"); if (tagi > 0) { *mp++ = static_cast<char>(EOT); *mp++ = static_cast<char>(tagstk[tagi--]); } else return badpat("Unmatched )"); } else { unsigned char c = *p; if (!c) // End of RE c = '\\'; // We take it as raw backslash if (caseSensitive || !iswordc(c)) { *mp++ = CHR; *mp++ = c; } else { *mp++ = CCL; mask = 0; ChSetWithCase(c, false); for (n = 0; n < BITBLK; bittab[n++] = 0) *mp++ = static_cast<char>(mask ^ bittab[n]); } } break; } sp = lp; } if (tagi > 0) return badpat((posix ? "Unmatched (" : "Unmatched \\(")); *mp = END; sta = OKP; return 0; } /* * RESearch::Execute: * execute nfa to find a match. * * special cases: (nfa[0]) * BOL * Match only once, starting from the * beginning. * CHR * First locate the character without * calling PMatch, and if found, call * PMatch for the remaining string. * END * RESearch::Compile failed, poor luser did not * check for it. Fail fast. * * If a match is found, bopat[0] and eopat[0] are set * to the beginning and the end of the matched fragment, * respectively. * */ int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) { unsigned char c; int ep = NOTFOUND; char *ap = nfa; bol = lp; failure = 0; Clear(); switch (*ap) { case BOL: /* anchored: match from BOL only */ ep = PMatch(ci, lp, endp, ap); break; case EOL: /* just searching for end of line normal path doesn't work */ if (*(ap+1) == END) { lp = endp; ep = lp; break; } else { return 0; } case CHR: /* ordinary char: locate it fast */ c = *(ap+1); while ((lp < endp) && (ci.CharAt(lp) != c)) lp++; if (lp >= endp) /* if EOS, fail, else fall thru. */ return 0; default: /* regular matching all the way. */ while (lp < endp) { ep = PMatch(ci, lp, endp, ap); if (ep != NOTFOUND) break; lp++; } break; case END: /* munged automaton. fail always */ return 0; } if (ep == NOTFOUND) return 0; bopat[0] = lp; eopat[0] = ep; return 1; } /* * PMatch: internal routine for the hard part * * This code is partly snarfed from an early grep written by * David Conroy. The backref and tag stuff, and various other * innovations are by oz. * * special case optimizations: (nfa[n], nfa[n+1]) * CLO ANY * We KNOW .* will match everything upto the * end of line. Thus, directly go to the end of * line, without recursive PMatch calls. As in * the other closure cases, the remaining pattern * must be matched by moving backwards on the * string recursively, to find a match for xy * (x is ".*" and y is the remaining pattern) * where the match satisfies the LONGEST match for * x followed by a match for y. * CLO CHR * We can again scan the string forward for the * single char and at the point of failure, we * execute the remaining nfa recursively, same as * above. * * At the end of a successful match, bopat[n] and eopat[n] * are set to the beginning and end of subpatterns matched * by tagged expressions (n = 1 to 9). */ extern void re_fail(char *,char); #define isinset(x,y) ((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND]) /* * skip values for CLO XXX to skip past the closure */ #define ANYSKIP 2 /* [CLO] ANY END */ #define CHRSKIP 3 /* [CLO] CHR chr END */ #define CCLSKIP 34 /* [CLO] CCL 32 bytes END */ int RESearch::PMatch(CharacterIndexer &ci, int lp, int endp, char *ap) { int op, c, n; int e; /* extra pointer for CLO */ int bp; /* beginning of subpat... */ int ep; /* ending of subpat... */ int are; /* to save the line ptr. */ while ((op = *ap++) != END) switch (op) { case CHR: if (ci.CharAt(lp++) != *ap++) return NOTFOUND; break; case ANY: if (lp++ >= endp) return NOTFOUND; break; case CCL: if (lp >= endp) return NOTFOUND; c = ci.CharAt(lp++); if (!isinset(ap,c)) return NOTFOUND; ap += BITBLK; break; case BOL: if (lp != bol) return NOTFOUND; break; case EOL: if (lp < endp) return NOTFOUND; break; case BOT: bopat[*ap++] = lp; break; case EOT: eopat[*ap++] = lp; break; case BOW: if ((lp!=bol && iswordc(ci.CharAt(lp-1))) || !iswordc(ci.CharAt(lp))) return NOTFOUND; break; case EOW: if (lp==bol || !iswordc(ci.CharAt(lp-1)) || iswordc(ci.CharAt(lp))) return NOTFOUND; break; case REF: n = *ap++; bp = bopat[n]; ep = eopat[n]; while (bp < ep) if (ci.CharAt(bp++) != ci.CharAt(lp++)) return NOTFOUND; break; case CLO: are = lp; switch (*ap) { case ANY: while (lp < endp) lp++; n = ANYSKIP; break; case CHR: c = *(ap+1); while ((lp < endp) && (c == ci.CharAt(lp))) lp++; n = CHRSKIP; break; case CCL: while ((lp < endp) && isinset(ap+1,ci.CharAt(lp))) lp++; n = CCLSKIP; break; default: failure = true; //re_fail("closure: bad nfa.", *ap); return NOTFOUND; } ap += n; while (lp >= are) { if ((e = PMatch(ci, lp, endp, ap)) != NOTFOUND) return e; --lp; } return NOTFOUND; default: //re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op)); return NOTFOUND; } return lp; } /* * RESearch::Substitute: * substitute the matched portions of the src in dst. * * & substitute the entire matched pattern. * * \digit substitute a subpattern, with the given tag number. * Tags are numbered from 1 to 9. If the particular * tagged subpattern does not exist, null is substituted. */ int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst) { unsigned char c; int pin; int bp; int ep; if (!*src || !bopat[0]) return 0; while ((c = *src++) != 0) { switch (c) { case '&': pin = 0; break; case '\\': c = *src++; if (c >= '0' && c <= '9') { pin = c - '0'; break; } default: *dst++ = c; continue; } if ((bp = bopat[pin]) != 0 && (ep = eopat[pin]) != 0) { while (ci.CharAt(bp) && bp < ep) *dst++ = ci.CharAt(bp++); if (bp < ep) return 0; } } *dst = '\0'; return 1; }
[ "lanya.wu@foxmail.com" ]
lanya.wu@foxmail.com
ca4c4c0c21476268508eeefb1dba5903f3a97160
f10b9ccbb69cb2116b72cd69867bb344ea8ef843
/impact/week1/BOJ2309.cpp
77d4ec11a6e1ce678db09e1523c157595f61808f
[]
no_license
eotkd4791/Algorithms
164277a6638b5231307f121b375df6b2b01f0a1c
307d3114d0347fc831bf50b2695fb286690fa5dc
refs/heads/main
2023-06-08T23:13:43.046307
2023-06-04T11:47:16
2023-06-04T11:47:16
165,011,185
0
0
null
null
null
null
UTF-8
C++
false
false
430
cpp
#include <bits/stdc++.h> using namespace std; int heights[9]; int main() { ios::sync_with_stdio(0); cin.tie(0); for(int i = 0; i < 9; i++) { cin >> heights[i]; } sort(heights, heights + 9); do { int sum = 0; for(int i = 0; i < 7; i++) sum += heights[i]; if(sum == 100) break; } while(next_permutation(heights, heights + 9)); for(int i = 0; i < 7; i++) cout << heights[i] << '\n'; return 0; }
[ "eotkd4791@gmail.com" ]
eotkd4791@gmail.com
46cb091cc914109b5014f427e827d4e96db81fe6
5ae655aa69a34f5bde6d5ec9a8009a767e6a88f4
/thirdparty/cuda/api/types.h
217eeaf05ddf8d890d9ccacf6be93c9682971e5a
[ "MIT", "BSD-3-Clause" ]
permissive
143401050125/GDataStructures
3d58cd95eb3141e2077205b27e66313e3c86e1f3
595e63c578d6d88cf9fe21493b2e86004c5822e7
refs/heads/master
2021-09-19T19:26:32.925452
2018-07-31T08:17:10
2018-07-31T08:17:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,510
h
/** * @file types.h * * @brief Fundamental, plain-old-data, CUDA-related type definitions. * This is a common file for all definitions fundamental, * plain-old-data, CUDA-related types - those with no methods, or with * only constexpr methods (which, specifically, do not involve making * any Runtime API calls). */ #pragma once #ifndef CUDA_API_WRAPPERS_TYPES_H_ #define CUDA_API_WRAPPERS_TYPES_H_ #ifndef __CUDACC__ #include <builtin_types.h> #include <driver_types.h> #endif #include <type_traits> namespace cuda { /* * The 3 ID types - for devices, streams && events - in this file are just * numeric identifiers (mostly useful for breaking dependencies && for * interaction with code using the original CUDA APIs); we also have wrapper * classes for them (each constructible by the corresponding numeric ID type) * which allow convenient access to their related functionality: these are * @ref cuda::device_t, @ref cuda::stream_t && @ref cuda::event_t. * * TODO: Perhaps we should call them cuda::device::type, * cuda::stream::type && cuda::event::type, */ /** * Indicates either the result (success or error index) of a CUDA Runtime API call, * or the overall status of the Runtime API (which is typically the last triggered * error). */ using status_t = cudaError_t; /** * CUDA kernels are launched in grids of blocks of threads, in 3 dimensions. * In each of these, the numbers of blocks per grid is specified in this type. * * @note Theoretically, CUDA could split the type for blocks per grid and * threads per block, but for now they're the same. */ using grid_dimension_t = decltype(dim3::x); /** * CUDA kernels are launched in grids of blocks of threads, in 3 dimensions. * In each of these, the number of threads per block is specified in this type. * * @note Theoretically, CUDA could split the type for blocks per grid and * threads per block, but for now they're the same. */ using grid_block_dimension_t = grid_dimension_t; namespace event { using id_t = cudaEvent_t; } // namespace event namespace stream { using id_t = cudaStream_t; /** * CUDA streams have a scheduling priority, with lower values meaning higher priority. * The types represents a larger range of values than those actually used; they can * be obtained by @ref device_t::stream_priority_range() . */ using priority_t = int; enum : priority_t { /** * the scheduling priority of a stream created without specifying any other priority * value */ default_priority = 0, unbounded_priority = -1 }; } // namespace stream /** * A richer (kind-of-a-)wrapper for CUDA's @ref dim3 class, used * to specify dimensions for blocks && grid (up to 3 dimensions). * * @note Unfortunately, dim3 does not have constexpr methods - * preventing us from having constexpr methods here. */ struct dimensions_t // this almost-inherits dim3 { grid_dimension_t x, y, z; constexpr __host__ __device__ dimensions_t(unsigned x_ = 1, unsigned y_ = 1, unsigned z_ = 1) : x(x_), y(y_), z(z_) {} __host__ __device__ constexpr dimensions_t(const uint3& v) : dimensions_t(v.x, v.y, v.z) { } __host__ __device__ constexpr dimensions_t(const dim3& dims) : dimensions_t(dims.x, dims.y, dims.z) { } __host__ __device__ constexpr operator uint3(void) const { return { x, y, z }; } __host__ __device__ operator dim3(void) const { return { x, y, z }; } __host__ __device__ inline size_t volume() const { return (size_t) x * y * z; } __host__ __device__ inline bool empty() const { return volume() == 0; } __host__ __device__ inline unsigned char dimensionality() const { return ((z > 1) + (y > 1) + (x > 1)) * (!empty()); } }; constexpr inline bool operator==(const dim3& lhs, const dim3& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; } constexpr inline bool operator==(const dimensions_t& lhs, const dimensions_t& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; } /** * CUDA kernels are launched in grids of blocks of threads. This expresses the * dimensions of a grid, in terms of blocks. */ using grid_dimensions_t = dimensions_t; /** * CUDA kernels are launched in grids of blocks of threads. This expresses the * dimensions of a block within such a grid, in terms of threads. */ using grid_block_dimensions_t = dimensions_t; /** * Each physical core ("Symmetric Multiprocessor") on an nVIDIA GPU has a space * of shared memory (see * @link https://devblogs.nvidia.com/parallelforall/using-shared-memory-cuda-cc/ * ). This type is large enough to hold its size. */ using shared_memory_size_t = unsigned short; // Like size_t, but for shared memory spaces, which, currently in nVIDIA (and AMD) // GPUs are sized at no more than 64 KiB. Note that using this for computations // might not be the best idea since there are penalties for sub-32-bit computation // sometimes /** * Holds the parameters necessary to "launch" a CUDA kernel (i.e. schedule it for * execution on some stream of some device). */ typedef struct { grid_dimensions_t grid_dimensions; grid_block_dimensions_t block_dimensions; shared_memory_size_t dynamic_shared_memory_size; // in bytes } launch_configuration_t; inline launch_configuration_t make_launch_config( grid_dimensions_t grid_dimensions, grid_block_dimensions_t block_dimensions, shared_memory_size_t dynamic_shared_memory_size = 0) { return { grid_dimensions, block_dimensions, dynamic_shared_memory_size }; } inline bool operator==(const launch_configuration_t lhs, const launch_configuration_t& rhs) { return lhs.grid_dimensions == rhs.grid_dimensions && lhs.block_dimensions == rhs.block_dimensions && lhs.dynamic_shared_memory_size == rhs.dynamic_shared_memory_size; } /** * @brief L1-vs-shared-memory balance option * * In some GPU micro-architectures, it's possible to have the multiprocessors * change the balance in the allocation of L1-cache-like resources between * actual L1 cache && shared memory; these are the possible choices. */ enum class multiprocessor_cache_preference_t { /** No preference for more L1 cache or for more shared memory; the API can do as it please */ no_preference = cudaFuncCachePreferNone, /** Divide the cache resources equally between actual L1 cache && shared memory */ equal_l1_and_shared_memory = cudaFuncCachePreferEqual, /** Divide the cache resources to maximize available shared memory at the expense of L1 cache */ prefer_shared_memory_over_l1 = cudaFuncCachePreferShared, /** Divide the cache resources to maximize available L1 cache at the expense of shared memory */ prefer_l1_over_shared_memory = cudaFuncCachePreferL1, // aliases none = no_preference, equal = equal_l1_and_shared_memory, prefer_shared = prefer_shared_memory_over_l1, prefer_l1 = prefer_l1_over_shared_memory, }; /** * A physical core (SM)'s shared memory has multiple "banks"; at most * one datum per bank may be accessed simultaneously, while data in * different banks can be accessed in parallel. The number of banks * && bank sizes differ for different GPU architecture generations; * but in some of them (e.g. Kepler), they are configurable - && you * can trade the number of banks for bank size, in case that makes * sense for your data access pattern - by using * @ref device_t::shared_memory_bank_size . */ enum multiprocessor_shared_memory_bank_size_option_t : std::underlying_type<cudaSharedMemConfig>::type { device_default = cudaSharedMemBankSizeDefault, four_bytes_per_bank = cudaSharedMemBankSizeFourByte, eight_bytes_per_bank = cudaSharedMemBankSizeEightByte }; namespace device { /** * @brief Numeric ID of a CUDA device used by the CUDA Runtime API. */ using id_t = int; /** * CUDA devices have both "attributes" && "properties". This is the * type for attribute identifiers/indices, aliasing {@ref cudaDeviceAttr}. */ using attribute_t = enum cudaDeviceAttr; /** * All CUDA device attributes (@ref attribute_t) have a value of this type. */ using attribute_value_t = int; /** * While Individual CUDA devices have individual "attributes" (@ref attribute_t), * there are also attributes characterizing pairs; this type is used for * identifying/indexing them, aliasing {@ref cudaDeviceP2PAttr}. */ using pair_attribute_t = cudaDeviceP2PAttr; } // namespace device namespace detail { enum : bool { assume_device_is_current = true, do_not_assume_device_is_current = false }; } // namespace detail /** * Scheduling policies the Runtime API may use when the host-side * thread it is running in needs to wait for results from a certain * device */ enum host_thread_synch_scheduling_policy_t : unsigned int { /** * @brief Default behavior; yield or spin based on a heuristic. * * The default value if the flags parameter is zero, uses a heuristic * based on the number of active CUDA contexts in the process C and * the number of logical processors in the system P. If C > P, then * CUDA will yield to other OS threads when waiting for the device, * otherwise CUDA will not yield while waiting for results and * actively spin on the processor. */ heuristic = cudaDeviceScheduleAuto, /** * @brief Keep control && spin-check for result availability * * Instruct CUDA to actively spin when waiting for results from the * device. This can decrease latency when waiting for the device, but * may lower the performance of CPU threads if they are performing * work in parallel with the CUDA thread. * */ spin = cudaDeviceScheduleSpin, /** * @brief Yield control while waiting for results. * * Instruct CUDA to yield its thread when waiting for results from * the device. This can increase latency when waiting for the * device, but can increase the performance of CPU threads * performing work in parallel with the device. * */ block = cudaDeviceScheduleBlockingSync, /** * @brief Block the thread until results are available. * * Instruct CUDA to block the CPU thread on a synchronization * primitive when waiting for the device to finish work. */ yield = cudaDeviceScheduleYield, /** see @ref heuristic */ automatic = heuristic, }; using native_word_t = unsigned; } // namespace cuda #endif /* CUDA_API_WRAPPERS_TYPES_H_ */
[ "yourihubaut@hotmail.com" ]
yourihubaut@hotmail.com
6700d21e68c18d3bdde10f3c4999f0d9f4e00bed
91e3e30fd6ccc085ca9dccb5c91445fa9ab156a2
/Examples/Display/Timing/Sources/timing.h
e6a4d8315aa7d72fc0116108095b94fd9e01eed1
[ "Zlib" ]
permissive
Pyrdacor/ClanLib
1bc4d933751773e5bca5c3c544d29f351a2377fb
72426fd445b59aa0b2e568c65ceccc0b3ed6fcdb
refs/heads/master
2020-04-06T06:41:34.252331
2014-10-03T21:47:06
2014-10-03T21:47:06
23,551,359
1
0
null
null
null
null
UTF-8
C++
false
false
1,596
h
/* ** ClanLib SDK ** Copyright (c) 1997-2013 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Mark Page */ #pragma once class Star { public: float xpos; float ypos; float speed; clan::Colorf color; }; // This is the Application class (That is instantiated by the Program Class) class Timing { public: int start(const std::vector<std::string> &args); private: void on_input_up(const clan::InputEvent &key); void on_window_close(); void draw_graphics(clan::Canvas &canvas, float time_delta); void set_stars(clan::Canvas &canvas, int star_cnt); private: bool quit; std::vector<Star> stars; };
[ "rombust@hotmail.co.uk" ]
rombust@hotmail.co.uk
513bb9192d4ef427df6bbe532888f097643ebdff
59b76dfbdbb96066ddd207e13c1d4495f924ed9c
/vtsServer/request/NotesHandler.h
97e6b40ed0725f37ed3527eb486be979fb8babfc
[]
no_license
GithubAtBob/vtsServer
371f7e7e9dc14b31fe3b15f2181446cea5efbf8d
64a34829cf1d6934df2f2f2f5c8053ed1ed2d5fd
refs/heads/master
2020-09-05T13:36:05.981336
2019-11-07T00:57:06
2019-11-07T00:57:06
220,121,084
0
0
null
null
null
null
UTF-8
C++
false
false
602
h
#pragma once #include "frame/vtsRequestHandler.h" class DBNotesHandler; class NotesRequest; class NotesHandler : public vtsRequestHandler { public: NotesHandler(); ~NotesHandler(void); WorkMode workMode(); void handle(boost::asio::const_buffer& data); void timeout(time_t last); void afterDb(DBNotesHandler* db); void UpdateFunction(NotesRequest msg); void RemoveFunction(NotesRequest msg); void AllFunction(NotesRequest msg); protected: void afterResponse(const boost::system::error_code& e); }; vtsDECLARE_REQUEST_HANDLER("notes", NotesHandler);
[ "Administrator@MUTGU62RE12Z4H2" ]
Administrator@MUTGU62RE12Z4H2
f3421187b0c1d4e238ab6d56df24ab3f96ba1f90
ac72a8a6f684f036e58d94ca7b00255759049baf
/SLB/include/SLB/Class.hpp
2c9604d088dbad9d5612c189f37e0ae18a5dba05
[]
no_license
VBelles/MomentumEngine-Real
27e988f3d46b19837e5f71fafe9a1591b2b85ce3
a549158a1bbf1e1ca088a0f4bdd039ca17a3228d
refs/heads/master
2023-08-04T14:11:17.000159
2018-11-15T16:48:33
2018-11-15T16:48:33
120,664,651
0
0
null
null
null
null
UTF-8
C++
false
false
15,335
hpp
/* SLB - Simple Lua Binder Copyright (C) 2007-2011 Jose L. Hidalgo Valiño (PpluX) 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. Jose L. Hidalgo (www.pplux.com) pplux@pplux.com */ #ifndef __SLB_CLASS__ #define __SLB_CLASS__ #include "SPP.hpp" #include "Allocator.hpp" #include "Export.hpp" #include "Debug.hpp" #include "ClassInfo.hpp" #include "ClassHelpers.hpp" #include "Manager.hpp" #include "FuncCall.hpp" #include "Value.hpp" #include "Instance.hpp" #include "Iterator.hpp" #include "Hybrid.hpp" #include "String.hpp" #include <typeinfo> #include <map> #include <vector> #include <iostream> struct lua_State; namespace SLB { struct ClassBase { ClassBase() {} virtual ~ClassBase() {} }; template< typename T, typename W = Instance::Default > class Class : public ClassBase { public: typedef Class<T,W> __Self; Class(const char *name, Manager *m = Manager::defaultManager()); Class(const Class&); Class& operator=(const Class&); __Self &rawSet(const char *name, Object *obj); template<typename TValue> __Self &set(const char *name, const TValue &obj) { return rawSet(name, (Object*) Value::copy(obj)); } template<typename TValue> __Self &set_ref(const char *name, TValue& obj) { return rawSet(name, Value::ref(obj)); } template<typename TValue> __Self &set_autoDelete(const char *name, TValue *obj) { return rawSet(name, Value::autoDelete(obj)); } __Self &set(const char *name, lua_CFunction func) { return rawSet(name, FuncCall::create(func)); } template<typename TEnum> __Self &enumValue(const char *name, TEnum obj); __Self &constructor(); /** Declares a class as hybrid, this will imply that the __index * and __newindex methods will be overriden, see * Hybrid::registerAsHybrid */ __Self &hybrid() { dynamic_inherits<HybridBase>(); HybridBase::registerAsHybrid( _class ); return *this; } template<typename TBase> __Self &dynamic_inherits() { _class->dynamicInheritsFrom<T,TBase>(); return *this;} template<typename TBase> __Self &static_inherits() { _class->staticInheritsFrom<T,TBase>(); return *this;} template<typename TBase> __Self &inherits() { return static_inherits<TBase>(); } template<typename T_to> __Self &convertibleTo( T_to* (*func)(T*) = &(ClassConversor<T,T_to>::defaultConvert) ) { _class->convertibleTo<T,T_to>(func); return *this; } template<typename M> __Self &property(const char *name, M T::*member) { _class->addProperty(name, BaseProperty::create(member)); return *this; } /* Class__index for (non-const)methods */ template<class C, class R, class P> __Self &class__index( R (C::*func)(P) ) { _class->setClass__index( FuncCall::create(func) ); return *this; } /* Class__index for const methods */ template<class C, class R, class P> __Self &class__index( R (C::*func)(P) const ) { _class->setClass__index( FuncCall::create(func) ); return *this; } /* Class__index for C functions */ template<class R, class P> __Self &class__index( R (*func)(P) ) { _class->setClass__index( FuncCall::create(func) ); return *this; } /* Class__index for lua_functions */ __Self &class__index(lua_CFunction func) { _class->setClass__index( FuncCall::create(func) ); return *this; } /* Class__newindex for (non-const)methods */ template<class C, class R, class K, class V> __Self &class__newindex( R (C::*func)(K,V) ) { _class->setClass__newindex( FuncCall::create(func) ); return *this; } /* Class__newindex for const methods */ template<class C, class R, class K, class V> __Self &class__newindex( R (C::*func)(K,V) const ) { _class->setClass__newindex( FuncCall::create(func) ); return *this; } /* Class__newindex for C functions */ template<class R, class K, class V> __Self &class__newindex( R (*func)(K,V) ) { _class->setClass__newindex( FuncCall::create(func) ); return *this; } /* Class__newindex for lua_functions */ __Self &class__newindex(lua_CFunction func) { _class->setClass__newindex( FuncCall::create(func) ); return *this; } /* Object__index for (non-const)methods */ template<class C, class R, class P> __Self &object__index( R (C::*func)(P) ) { _class->setObject__index( FuncCall::create(func) ); return *this; } /* Object__index for const methods */ template<class C, class R, class P> __Self &object__index( R (C::*func)(P) const ) { _class->setObject__index( FuncCall::create(func) ); return *this; } /* Object__index for C functions */ template<class R, class P> __Self &object__index( R (*func)(P) ) { _class->setObject__index( FuncCall::create(func) ); return *this; } /* Object__index for lua_functions */ __Self &object__index(lua_CFunction func) { _class->setObject__index( FuncCall::create(func) ); return *this; } /* Object__newindex for (non-const)methods */ template<class C, class R, class K, class V> __Self &object__newindex( R (C::*func)(K,V) ) { _class->setObject__newindex( FuncCall::create(func) ); return *this; } /* Object__newindex for const methods */ template<class C, class R, class K, class V> __Self &object__newindex( R (C::*func)(K,V) const ) { _class->setObject__newindex( FuncCall::create(func) ); return *this; } /* Object__newindex for C functions */ template<class R, class K, class V> __Self &object__newindex( R (*func)(K,V) ) { _class->setObject__newindex( FuncCall::create(func) ); return *this; } /* Object__newindex for lua_functions */ __Self &object__newindex(lua_CFunction func) { _class->setObject__newindex( FuncCall::create(func) ); return *this; } template<class T1, class T2> __Self &__eq( bool (*func)(T1,T2) ) { _class->setObject__newindex( FuncCall::create(func) ); return *this; } __Self &__eq(lua_CFunction func) { _class->set__eq( FuncCall::create(func) ); return *this; } __Self &__add() { SLB_DEBUG_CALL; SLB_DEBUG(0, "NOT IMPLEMENTED!"); return *this; } __Self &__mult() { SLB_DEBUG_CALL; SLB_DEBUG(0, "NOT IMPLEMENTED!"); return *this; } template<class IT> /* IT == Iterator Traits */ __Self &customIterator( const char *name, typename IT::GetIteratorMember first, typename IT::GetIteratorMember end ) { Iterator* it; StdIterator< IT >* sit; sit = new (Malloc(sizeof(StdIterator<IT>))) StdIterator<IT>(first, end); it = new (Malloc(sizeof(Iterator))) Iterator(sit); return rawSet(name, it ); } template<typename C, typename T_Iterator> __Self &iterator(const char *name, T_Iterator (C::*first)(), T_Iterator (C::*end)() ) { return customIterator< StdIteratorTraits<C, T_Iterator> > (name,first, end ) ; } template<typename C, typename T_Iterator> __Self &const_iterator(const char *name, T_Iterator (C::*first)() const, T_Iterator (C::*end)() const ) { return customIterator< StdConstIteratorTraits<C, T_Iterator> > (name,first, end ) ; } // Metada __Self &comment(const String&); __Self &param(const String&); #define SLB_REPEAT(N) \ \ /* Methods */ \ template<class C, class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ __Self &set(const char *name, R (C::*func)(SPP_ENUM_D(N,T)) ); \ template<class C, class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ __Self &nonconst_set(const char *name, R (C::*func)(SPP_ENUM_D(N,T)) ); \ \ /* CONST Methods */ \ template<class C, class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ __Self &set(const char *name, R (C::*func)(SPP_ENUM_D(N,T)) const ); \ template<class C, class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ __Self &const_set(const char *name, R (C::*func)(SPP_ENUM_D(N,T)) const); \ \ /* C-functions */ \ template<class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ __Self &set(const char *name, R (func)(SPP_ENUM_D(N,T)) ); \ \ /* constructors */ \ template<class T0 SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ __Self &constructor(); \ \ /* Constructors (wrappers to c-functions) */ \ template<class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ __Self &constructor(R (func)(SPP_ENUM_D(N,T)) ); \ SPP_MAIN_REPEAT_Z(MAX,SLB_REPEAT) #undef SLB_REPEAT protected: ClassInfo *_class; // For metadata Object *_lastObj; size_t _param; Manager* _mgr; }; template<typename T, typename W> inline Class<T,W>::Class(const char *name, Manager *m) : _class(0), _lastObj(0), _param(0), _mgr(m) { SLB_DEBUG_CALL; // we expect to have a template "Implementation" inside W typedef typename W::template Implementation<T> Adapter; _class = m->getOrCreateClass( _TIW(T) ); _class->setName( name ); typedef InstanceFactoryAdapter< T, Adapter > t_IFA; _class->setInstanceFactory( new (Malloc(sizeof(t_IFA))) t_IFA ); SLB_DEBUG(1, "Class declaration for %s[%s]", name, _TIW(T).name()); } template<typename T, typename W> inline Class<T,W>::Class(const Class &c) : _class(c._class), _mgr(c._mgr) { } template<typename T, typename W> inline Class<T,W>& Class<T,W>::operator=(const Class &c) { _class = c._class; _mgr = c._mgr; } template<typename T, typename W> inline Class<T,W> &Class<T,W>::rawSet(const char *name, Object *obj) { _class->set(name, obj); _lastObj = obj; _param = 0; return *this; } template<typename T, typename W> inline Class<T,W> &Class<T,W>::constructor() { _class->setConstructor( FuncCall::defaultClassConstructor<T>() ); return *this; } template<typename T, typename W> template<typename TEnum> inline Class<T,W> &Class<T,W>::enumValue(const char *name, TEnum obj) { // "fake" Declaration of TEnum... ClassInfo *c = _mgr->getOrCreateClass( _TIW(TEnum) ); if (!c->initialized()) { struct Aux { static bool equal(TEnum a, TEnum b) { return a == b; } }; // if it is not initialized then add a simple adapter for // references. typedef InstanceFactoryAdapter< TEnum, SLB::Instance::Default::Implementation<TEnum> > t_IFA; c->setInstanceFactory( new (Malloc(sizeof(t_IFA))) t_IFA ); c->set__eq( FuncCall::create( &Aux::equal )); } // push a reference return rawSet(name, Value::copy(obj)); } template<typename T, typename W> inline Class<T,W> &Class<T,W>::comment( const String &s ) { if (_lastObj) _lastObj->setInfo(s); else _class->setInfo(s); return *this; } template<typename T, typename W> inline Class<T,W> &Class<T,W>::param( const String &s ) { //TODO: This should also work for constructors, and so on. if (_lastObj) { FuncCall *fc = slb_dynamic_cast<FuncCall>(_lastObj); if (fc) { size_t max_param = fc->getNumArguments(); if (_param >= max_param) { std::cerr << "SLB_Warning: " << fc->getInfo() <<" to many parameters (total args=" << max_param << ")" << "(" << _param << ", " << s << ")" << std::endl; } else { fc->setArgComment(_param, s); } } else { std::cerr << "SLB_Warning: Can not set param info to a non-funcCall object " << "(" << _param << ", " << s << ")" << std::endl; } } _param++; return *this; } #define SLB_REPEAT(N) \ \ /* Methods */ \ template<typename T, typename W>\ template<class C, class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ inline Class<T,W> &Class<T,W>::set(const char *name, R (C::*func)(SPP_ENUM_D(N,T)) ){ \ if (_TIW(T) != _TIW(C)) static_inherits<C>();\ return rawSet(name, FuncCall::create(func)); \ } \ template<typename T, typename W>\ template<class C, class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ inline Class<T,W> &Class<T,W>::nonconst_set(const char *name, R (C::*func)(SPP_ENUM_D(N,T)) ){ \ if (_TIW(T) != _TIW(C)) static_inherits<C>();\ return rawSet(name, FuncCall::create(func)); \ } \ \ /* CONST Methods */ \ template<typename T, typename W>\ template<class C, class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ inline Class<T,W> &Class<T,W>::set(const char *name, R (C::*func)(SPP_ENUM_D(N,T)) const ){ \ if (_TIW(T) != _TIW(C)) static_inherits<C>();\ return rawSet(name, FuncCall::create(func)); \ } \ template<typename T, typename W>\ template<class C, class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ inline Class<T,W> &Class<T,W>::const_set(const char *name, R (C::*func)(SPP_ENUM_D(N,T)) const ){ \ if (_TIW(T) != _TIW(C)) static_inherits<C>();\ return rawSet(name, FuncCall::create(func)); \ } \ \ /* C-functions */ \ template<typename T, typename W> \ template<class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ inline Class<T,W> &Class<T,W>::set(const char *name, R (func)(SPP_ENUM_D(N,T)) ){ \ return rawSet(name, FuncCall::create(func)); \ } \ \ /* constructor */ \ template<typename T, typename W> \ template<class T0 SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ inline Class<T,W> &Class<T,W>::constructor(){ \ FuncCall *fc = FuncCall::defaultClassConstructor<T,T0 SPP_COMMA_IF(N) SPP_ENUM_D(N,T)>();\ _class->setConstructor( fc );\ return *this; \ } \ /* Constructors (wrappers c-functions) */ \ template<typename T, typename W> \ template<class R SPP_COMMA_IF(N) SPP_ENUM_D(N, class T)> \ inline Class<T,W> &Class<T,W>::constructor( R (func)(SPP_ENUM_D(N,T)) ){ \ _class->setConstructor( FuncCall::create( func ) ); \ return *this;\ } \ \ SPP_MAIN_REPEAT_Z(MAX,SLB_REPEAT) #undef SLB_REPEAT } #endif
[ "vicentbelles@gmail.com" ]
vicentbelles@gmail.com
e960998cb63f692524485f82a7c0cac72ea21d5b
95e438728fd668a7305a43b8493bf9d07269e6c6
/PilaMazo.cpp
e1f2d2f5041bedd08f85ec6ff0bd0c42423de830
[]
no_license
emiliobacon/Lab05_Emilio_Barillas_1150620
756be2f0cdc8e6d22e2bed8009c98f12c53cb56b
703d5293cd65fc1afb1bfae4f10a807b26028b8a
refs/heads/master
2023-08-25T11:00:21.466001
2021-11-05T07:20:34
2021-11-05T07:20:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,092
cpp
#include "PilaMazo.h" void PilaMazo::Insertar(Carta^ nodo) { Carta^ Nuevo = gcnew Carta(); Nuevo = nodo; Nuevo->Siguiente = Cabeza; Cabeza = Nuevo; } void PilaMazo::Limpiar() { while (!PilaVacia()) { Quitar(); } } Carta^ PilaMazo::Quitar() { if (Cabeza ==nullptr) { return nullptr; } Carta^ Retorno = gcnew Carta(); Retorno = Cabeza; Carta^ Top = Cabeza; Cabeza = Cabeza->Siguiente; delete(Top); return Retorno; } bool PilaMazo::PilaVacia() { if (Cabeza == nullptr) { return true; } else { return false; } } int PilaMazo::Size() { int Cantidad = 0; for (Carta^ i = Cabeza; i != nullptr; i = i->Siguiente) { Cantidad++; } return Cantidad; } String^ PilaMazo::Peek() { if (!PilaVacia()) { String^ Retorno = Cabeza->Valor + " " + Cabeza->Color; return Retorno; } else { return nullptr; } } String^ PilaMazo::Recorrer() { Carta^ Recorrer = gcnew Carta(); String^ Datos; Recorrer = Cabeza; while (Recorrer != nullptr) { Datos += Recorrer->Valor + "-" + Recorrer->Color + "\n"; Recorrer = Recorrer->Siguiente; } return Datos; }
[ "eabarillasco@correo.url.edu.gt" ]
eabarillasco@correo.url.edu.gt
c93145384dfd4c64c732ada033b67c16d3475924
1c0eece226ed1d3506004426f5a248970326e304
/jni/GameController.h
9259c0e3f0ccbf2eb3e9a110c5a23c25781729ef
[]
no_license
optiklab/Asteroids-Mobile
74ee4d7313ba58ff6cbadb2f364befd9adf0f15e
bf45d80d826fe5d45e968a3f4f287c61b9b8a933
refs/heads/master
2021-08-28T18:15:19.105415
2021-07-31T13:25:40
2021-07-31T13:25:40
22,528,379
6
1
null
null
null
null
UTF-8
C++
false
false
2,157
h
#pragma once #ifndef __gamecontroller_h__ #define __gamecontroller_h__ #include <vector> #include "Player.h" #include "EnemyDust.h" #include "AsteroidEnemy.h" #include "Statistics.h" #include "ActivityHandler.h" #include "InputHandler.h" #include "TimeService.h" #include <EGL/egl.h> // TODO //#include FT_FREETYPE_H namespace asteroids { // Manage all the game resources and logic. class GameController : public ActivityHandler, public InputHandler { public: // Constructor. GameController(EGLDisplay display, EGLSurface surface, int32_t width, int32_t height); // Clears resources. virtual ~GameController(); // Determines is game initialized. bool IsInitialized(); status OnActivate(); void OnDeactivate(); status OnStep(); bool OnTouchEvent(AInputEvent* pEvent); bool OnKeyboardEvent(AInputEvent* pEvent); bool OnTrackballEvent(AInputEvent* pEvent); bool OnAccelerometerEvent(ASensorEvent* pEvent); private: // Updates all the game logic and draws all parts of the game. void _Update(); // Draws game controller itself. void _Draw(); // Initializes display to show game. void _InitDisplay(); // Updates logic related to asteroids. void _UpdateAsteroids(float time, float total); // Solves all collisions between player, asteroids and rockets. void _SolveCollisions(); // Shows initial screen. void _ShowInitialScreen(); // Show number on screen. void _ShowNumber(int number); private: // Player data. Player* _player; // Some time intervals using for live/visibility time. float _lastAppearTime; float _lastTimeAfterKill; // States control. bool _isGameState; bool _isScoreState; bool _quit; bool _restart; float _horizontal; float _vertical; int32_t _width; int32_t _height; // Display properties. EGLDisplay _display; EGLSurface _surface; Statistics* _statistics; // Collection of dust (enemy trash) objects. std::vector<EnemyDust*> _dust; // Collection of enemies itself: asteroids. std::vector<AsteroidEnemy*> _asteroids; // Time services to work with. TimeService* _pTimeService; }; } #endif /* __gamecontroller_h__ */
[ "byslash@gmail.com" ]
byslash@gmail.com
4835d65f0e126814fec700faf289f4cde4cf346f
48421fe98c19ba8b9212cefcfb97007f32110852
/Module1/LA1-2/myArray2.cpp
d4cc161ee01df4301aa8586cf3d1bc1989006198
[]
no_license
Conjur99/hafb-cpp-fundamentals
b8ea73b699022e95a57f4c647b4473aed4730c54
5f0fa8a904d30be01fb1421eda56e87cc927ace4
refs/heads/master
2020-11-25T01:26:36.985393
2019-12-19T23:27:24
2019-12-19T23:27:24
228,429,359
0
0
null
2019-12-16T16:33:16
2019-12-16T16:33:16
null
UTF-8
C++
false
false
845
cpp
/** * @file myArray.cpp * @author your name (you@domain.com) * @brief Use arrays and C++ container * @version 0.1 * @date 2019-12-16 * * @copyright Copyright (c) 2019 * */ #include <iostream> using namespace std; const int kMaxNum = 5; int main() //TODO: unfinished { // C-style array notation: type name[elements] int grades[kMaxNum] = {10,20,30}; //array of 5 integers, indexed 0-4, last two filled float average_grade = 0; int sum = 0; cout << "Enter exam grades: " << endl; for (int num =0; num <kMaxNum; ++num) { // cout << "Enter " << num +1 << " grades: " << endl; // cin >> grades[num]; // access each element using [] // sum += grades[num]; // } average_grade = static_cast<float>(sum) / kMaxNum; cout << "Average is: " << average_grade; return 0; }
[ "CCEClass1@ad.weber.edu" ]
CCEClass1@ad.weber.edu
f3a57822de7af9b092442656f360b93a8ab93d50
dfa70a6e6e0ed36e71eccdf8d983ee2f611dcb4e
/src/test/sighash_tests.cpp
5b4e55aaadb897a7a57e353a4ad563779186895a
[ "MIT" ]
permissive
empower-network/empower
e39a879bac620cfa1d837f92a2d4283b3747bbdf
3b63fbfe394574855d176262d604060f49ad77c1
refs/heads/master
2020-06-10T07:13:18.745654
2019-06-25T02:49:11
2019-06-25T02:49:11
193,615,634
3
4
null
null
null
null
UTF-8
C++
false
false
7,756
cpp
// Copyright (c) 2013-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/tx_check.h> #include <consensus/validation.h> #include <test/data/sighash.json.h> #include <hash.h> #include <script/interpreter.h> #include <script/script.h> #include <serialize.h> #include <streams.h> #include <test/setup_common.h> #include <util/system.h> #include <util/strencodings.h> #include <version.h> #include <iostream> #include <boost/test/unit_test.hpp> #include <univalue.h> extern UniValue read_json(const std::string& jsondata); // Old script.cpp SignatureHash function uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001")); if (nIn >= txTo.vin.size()) { return one; } CMutableTransaction txTmp(txTo); // In case concatenating two scripts ends up with two codeseparators, // or an extra one at the end, this prevents all those possible incompatibilities. FindAndDelete(scriptCode, CScript(OP_CODESEPARATOR)); // Blank out other inputs' signatures for (unsigned int i = 0; i < txTmp.vin.size(); i++) txTmp.vin[i].scriptSig = CScript(); txTmp.vin[nIn].scriptSig = scriptCode; // Blank out some of the outputs if ((nHashType & 0x1f) == SIGHASH_NONE) { // Wildcard payee txTmp.vout.clear(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } else if ((nHashType & 0x1f) == SIGHASH_SINGLE) { // Only lock-in the txout payee at same index as txin unsigned int nOut = nIn; if (nOut >= txTmp.vout.size()) { return one; } txTmp.vout.resize(nOut+1); for (unsigned int i = 0; i < nOut; i++) txTmp.vout[i].SetNull(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } // Blank out other inputs completely, not recommended for open transactions if (nHashType & SIGHASH_ANYONECANPAY) { txTmp.vin[0] = txTmp.vin[nIn]; txTmp.vin.resize(1); } // Serialize and hash CHashWriter ss(SER_GETHASH, SERIALIZE_TRANSACTION_NO_WITNESS); ss << txTmp << nHashType; return ss.GetHash(); } void static RandomScript(CScript &script) { static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; script = CScript(); int ops = (InsecureRandRange(10)); for (int i=0; i<ops; i++) script << oplist[InsecureRandRange(sizeof(oplist)/sizeof(oplist[0]))]; } void static RandomTransaction(CMutableTransaction &tx, bool fSingle) { tx.nVersion = ((uint32_t)InsecureRand32()) % (EMPOWER_TXN_VERSION-1); tx.vin.clear(); tx.vout.clear(); tx.nLockTime = (InsecureRandBool()) ? InsecureRand32() : 0; int ins = (InsecureRandBits(2)) + 1; int outs = fSingle ? ins : (InsecureRandBits(2)) + 1; for (int in = 0; in < ins; in++) { tx.vin.push_back(CTxIn()); CTxIn &txin = tx.vin.back(); txin.prevout.hash = InsecureRand256(); txin.prevout.n = InsecureRandBits(2); RandomScript(txin.scriptSig); txin.nSequence = (InsecureRandBool()) ? InsecureRand32() : std::numeric_limits<uint32_t>::max(); } for (int out = 0; out < outs; out++) { tx.vout.push_back(CTxOut()); CTxOut &txout = tx.vout.back(); txout.nValue = InsecureRandRange(100000000); RandomScript(txout.scriptPubKey); } } BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(sighash_test) { SeedInsecureRand(false); #if defined(PRINT_SIGHASH_JSON) std::cout << "[\n"; std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n"; int nRandomTests = 500; #else int nRandomTests = 50000; #endif for (int i=0; i<nRandomTests; i++) { int nHashType = InsecureRand32(); CMutableTransaction txTo; RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE); CScript scriptCode; RandomScript(scriptCode); int nIn = InsecureRandRange(txTo.vin.size()); uint256 sh, sho; sho = SignatureHashOld(scriptCode, CTransaction(txTo), nIn, nHashType); CAmount amount = 0; std::vector<uint8_t> vchAmount(8); memcpy(&vchAmount[0], &amount, 8); sh = SignatureHash(scriptCode, txTo, nIn, nHashType, vchAmount, SigVersion::BASE); #if defined(PRINT_SIGHASH_JSON) CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << txTo; std::cout << "\t[\"" ; std::cout << HexStr(ss.begin(), ss.end()) << "\", \""; std::cout << HexStr(scriptCode) << "\", "; std::cout << nIn << ", "; std::cout << nHashType << ", \""; std::cout << sho.GetHex() << "\"]"; if (i+1 != nRandomTests) { std::cout << ","; } std::cout << "\n"; #endif BOOST_CHECK(sh == sho); } #if defined(PRINT_SIGHASH_JSON) std::cout << "]\n"; #endif } // Goal: check that SignatureHash generates correct hash BOOST_AUTO_TEST_CASE(sighash_from_data) { UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); if (test.size() < 1) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } if (test.size() == 1) continue; // comment std::string raw_tx, raw_script, sigHashHex; int nIn, nHashType; uint256 sh; CTransactionRef tx; CScript scriptCode = CScript(); bool fExpectHashFailure = false; // adjusting test vectors >= EMPOWER_TXN_VERSION try { // deserialize test data raw_tx = test[0].get_str(); raw_script = test[1].get_str(); nIn = test[2].get_int(); nHashType = test[3].get_int(); sigHashHex = test[4].get_str(); char strHex[2]; strHex[0] = raw_tx[0]; strHex[1] = raw_tx[1]; if (std::strtoul(strHex, 0, 16) >= EMPOWER_TXN_VERSION) { raw_tx[0] = '0'; raw_tx[1] = '0'; fExpectHashFailure = true; }; CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION); stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(CheckTransaction(*tx, state), strTest); BOOST_CHECK(state.IsValid()); std::vector<unsigned char> raw = ParseHex(raw_script); scriptCode.insert(scriptCode.end(), raw.begin(), raw.end()); } catch (...) { BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest); continue; } CAmount amount = 0; std::vector<uint8_t> vchAmount(8); memcpy(&vchAmount[0], &amount, 8); sh = SignatureHash(scriptCode, *tx, nIn, nHashType, vchAmount, SigVersion::BASE); if (!fExpectHashFailure) BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest); } } BOOST_AUTO_TEST_SUITE_END()
[ "prissyme67@aol.com" ]
prissyme67@aol.com
6f80918d49a8632b56b04f0f8836162491c2f939
ae14d7582407bdf04c3cd10900e8f6576fc2fad0
/advanced_cpp/day2/6_enable_if6.cpp
3ff1bec54160af6ea7f5055a8bf5819a79757862
[]
no_license
jingal/Lecture
feebab4283353a79dd410cbead22cd67d652a929
c1c1709bc3effbc4883970f1439a4c6a24531ae0
refs/heads/master
2021-01-19T20:11:18.543858
2018-04-27T06:50:39
2018-04-27T06:50:39
88,491,615
0
0
null
null
null
null
UHC
C++
false
false
599
cpp
// 6_enable_if6 - 77 page #include <iostream> #include <type_traits> using namespace std; template<typename T> void print(T a) { //if (is_pointer<T>::value) // if(false) // 컴파일 시간 if문.. 조건의 조사를 컴파일 시간에 조사 // false가 나오면 컴파일 제외 // c++ 17, 컴파일 타임 상수만 사용 가능 if constexpr (is_pointer<T>::value) cout << a << " : " << *a << endl; else cout << a << endl; } typename enable_if<!is_pointer<T>::value, void>::type foo(T a) { //... } int main() { int n = 10; print(n); // 1. 에러의 원인. print(&n); }
[ "ilovejinjoo@gmail.com" ]
ilovejinjoo@gmail.com
f335f6af2521947b7978745c3a22d8a1e9103c03
de59608f9d9d6cc46b588329f1b6b5b27ec2141d
/source/Bit/Network/Net/HostMessage.cpp
00b0ee01f4f367ee6d399cea60caa091f0bd495f
[ "Zlib" ]
permissive
jimmiebergmann/Bit-Engine
85a892ef12493451e932a7d9dab97a5bf6e059db
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
refs/heads/master
2021-01-17T11:48:35.628014
2016-06-13T20:26:22
2016-06-13T20:26:22
9,845,099
0
0
null
2013-06-24T15:46:06
2013-05-03T21:36:09
C
UTF-8
C++
false
false
4,592
cpp
// Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com // // This software is provided 'as-is', without any express or // implied warranty. In no event will the authors be held // liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute // it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but // is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any // source distribution. // /////////////////////////////////////////////////////////////////////////// #include <Bit/Network/Net/HostMessage.hpp> #include <Bit/Network/Net/Server.hpp> #include <Bit/System/MemoryLeak.hpp> namespace Bit { namespace Net { HostMessage::HostMessage( ) { } HostMessage::HostMessage( const std::string & p_Name, Server * p_pServer, Int32 p_MessageSize ) : m_Name( p_Name ), m_pServer( p_pServer ) { if( p_MessageSize > 0 ) { m_Message.reserve( static_cast<MessageVector::size_type>( p_MessageSize ) + static_cast<MessageVector::size_type>( p_Name.size( ) ) + 2 ); } else { m_Message.reserve( static_cast<MessageVector::size_type>( p_Name.size( ) ) + 2 ); } // Add the message type and message name m_Message.push_back( static_cast<Uint8>( eMessageType::UserMessageType ) ); for( std::string::size_type i = 0; i < p_Name.size( ); i++ ) { m_Message.push_back( static_cast<Uint8>( p_Name[ i ] ) ); } m_Message.push_back( 0 ); } void HostMessage::WriteByte( const Uint8 p_Byte ) { m_Message.push_back( p_Byte ); } void HostMessage::WriteInt( const Int32 p_Int ) { Uint32 integer = Hton32( static_cast<Uint32>( p_Int ) ); m_Message.push_back( static_cast<Uint8>( integer ) ); m_Message.push_back( static_cast<Uint8>( integer >> 8 ) ); m_Message.push_back( static_cast<Uint8>( integer >> 16 ) ); m_Message.push_back( static_cast<Uint8>( integer >> 24 ) ); } void HostMessage::WriteFloat( const Float32 p_Float ) { // Get void pointer to float const Uint8 * pPointer = reinterpret_cast<const Uint8 *>( &p_Float ); m_Message.push_back( pPointer[ 0 ] ); m_Message.push_back( pPointer[ 1 ] ); m_Message.push_back( pPointer[ 2 ] ); m_Message.push_back( pPointer[ 3 ] ); } void HostMessage::WriteString( const std::string & p_String ) { for( std::string::size_type i = 0; i < p_String.size( ); i++ ) { m_Message.push_back( static_cast<Uint8>( p_String[ i ] ) ); } m_Message.push_back( 0 ); } void HostMessage::WriteArray( const void * p_pArray, const SizeType p_Size ) { for( SizeType i = 0; i < p_Size; i++ ) { m_Message.push_back( reinterpret_cast<const Uint8 *>( p_pArray )[ i ] ); } } Bool HostMessage::Send( HostRecipientFilter * p_pFilter ) { // Error check the filter pointer. if( p_pFilter == NULL ) { return false; } // Go throguh the connections from the server and send the data m_pServer->m_ConnectionMutex.Lock( ); HostRecipientFilter::UserSet::const_iterator it1 = p_pFilter->m_Users.begin( ); while(it1 != p_pFilter->m_Users.end( ) ) { // Find the connection Server::UserConnectionMap::iterator it2 = m_pServer->m_UserConnections.find( *it1 ); if( it2 == m_pServer->m_UserConnections.end( ) ) { // Remove the user from the set if it doesn't exist. p_pFilter->m_Users.erase( it1 ); // Continue to the next user continue; } else { // Increase the iterator for users. it1++; } // Get the connection Connection * pConnection = it2->second; // Send the message if( p_pFilter->IsReliable( ) ) { pConnection->SendReliable(PacketType::HostMessage, reinterpret_cast<void*>(m_Message.data()), m_Message.size(), true ); } else { pConnection->SendUnreliable(PacketType::HostMessage, reinterpret_cast<void*>(m_Message.data()), m_Message.size(), true, true); } } m_pServer->m_ConnectionMutex.Unlock( ); return true; } const std::string & HostMessage::GetName( ) const { return m_Name; } } }
[ "jimmiebergmann@gmail.com" ]
jimmiebergmann@gmail.com
345e3a86a3a84afa32c9fb966f549dad3da132ad
39adfee7b03a59c40f0b2cca7a3b5d2381936207
/leetcode/livestream7/394_decode_string.cpp
d5c074c9127a924d618ab877c528342e38786b38
[]
no_license
ngthanhtrung23/CompetitiveProgramming
c4dee269c320c972482d5f56d3808a43356821ca
642346c18569df76024bfb0678142e513d48d514
refs/heads/master
2023-07-06T05:46:25.038205
2023-06-24T14:18:48
2023-06-24T14:18:48
179,512,787
78
22
null
null
null
null
UTF-8
C++
false
false
1,621
cpp
class Solution { public: string decodeString(string s) { if (s == "") return ""; // find matching bracket int n = s.size(); vector<int> matching(n, -1); stack<int> st; for (int i = 0; i < n; i++) { if (s[i] == '[') st.push(i); else if (s[i] == ']') { assert(!st.empty()); int j = st.top(); matching[i] = j; matching[j] = i; st.pop(); } } // recursively decode string return solve(s, 0, n-1, matching); } private: string solve(const string& s, int l, int r, const vector<int>& matching) { if (l > r) return ""; string res = ""; int i = l; while (i <= r) { if (s[i] >= '0' && s[i] <= '9') { int repeat = s[i] - '0'; int j = i + 1; while (s[j] != '[') { assert(s[j] >= '0' && s[j] <= '9'); repeat = repeat * 10 + s[j] - '0'; ++j; } // now s[j] == [ assert(s[j] == '['); assert(s[matching[j]] == ']'); string child = solve(s, j + 1, matching[j] - 1, matching); for (int tmp = 0; tmp < repeat; tmp++) { res += child; } i = matching[j] + 1; } else { res += s[i]; ++i; } } return res; } };
[ "ngthanhtrung23@gmail.com" ]
ngthanhtrung23@gmail.com
821b0032ea65675ad0c82da172e1ee98f9c9a072
41a76318e5b9eef2c69bbf922724f8b191d7d124
/kokkos/core/unit_test/openmptarget/TestOpenMPTarget_SubView_c05.cpp
c02c38cfcf6aed4bd6a4c3cfdb03ed3c300c1974
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
zishengye/compadre
d0ff10deca224284e7e153371a738e053e66012a
75b738a6a613c89e3c3232cbf7b2589a6b28d0a3
refs/heads/master
2021-06-25T06:16:38.327543
2021-04-02T02:08:48
2021-04-02T02:08:48
223,650,267
0
0
NOASSERTION
2019-11-23T20:41:03
2019-11-23T20:41:02
null
UTF-8
C++
false
false
2,323
cpp
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ #include <openmptarget/TestOpenMPTarget_Category.hpp> #include <TestViewSubview.hpp> namespace Test { TEST_F(openmptarget, view_subview_2d_from_3d_atomic) { TestViewSubview::test_2d_subview_3d<TEST_EXECSPACE, Kokkos::MemoryTraits<Kokkos::Atomic> >(); } } // namespace Test
[ "pakuber@sandia.gov" ]
pakuber@sandia.gov
c5f4f2bad016959dc7e13b21c6ebc5b252a17502
c6060cc96a6ebc798309bb43f7c4ceac906b5316
/Vim/FacebookHackerCup2017/Qualification/FightingTheZombie.cc
f032163237e462cb00a8a5f4db770c7362be5554
[]
no_license
brycesandlund/CompetitiveProgramming
f05de33922a5bf01740e93c0266d72a49d6c8469
9d82a269c926c47c149bfff1ec8c90b8f80f5da1
refs/heads/master
2020-08-05T12:03:09.071620
2018-10-04T15:57:18
2018-10-04T15:57:18
23,522,788
0
1
null
null
null
null
UTF-8
C++
false
false
1,065
cc
#include <iostream> #include <vector> using namespace std; typedef long long ll; typedef vector<double> vd; ll H, S; double process_spell() { ll X, Y, Z = 0; char c; scanf("%lldd%lld%c", &X, &Y, &c); if (c == '+' || c == '-') { cin >> Z; if (c == '-') Z *= -1; } vd odds(410, 0); odds[0] = 1; for (ll i = 0; i < X; ++i) { vd new_odds(410, 0); for (ll j = 1; j <= Y; ++j) { for (ll k = 0; k < 410-j; ++k) { new_odds[k+j] += odds[k] * (1.0/Y); } } odds = new_odds; } double winning = 0; for (ll i = 0; i < 410; ++i) { if (i + Z >= H) { winning += odds[i]; } } return winning; } int main() { ll T; cin >> T; for (ll cs = 1; cs <= T; ++cs) { cin >> H >> S; double p_max = 0; for (ll i = 0; i < S; ++i) { p_max = max(p_max, process_spell()); } printf("Case #%lld: %.10lf\n", cs, p_max); } }
[ "bcsandlund@gmail.com" ]
bcsandlund@gmail.com
eab6c8583b8e18021f95ce1c3d5a21622156d64f
0f116a81ecf651d149ac6323e69468b523312057
/c++/parrot/core/Vertex.h
f272b1624949bc8b20f520750c64c3aa61fe01ac
[]
no_license
booirror/codelabs
4bbb500afb94f61e98fa16a59e27c2df270f09d6
92d21de25f84da8134ac2db56e36bac968915896
refs/heads/master
2022-11-23T22:14:07.065551
2020-08-03T15:10:47
2020-08-03T15:10:47
280,185,047
1
0
null
null
null
null
GB18030
C++
false
false
1,727
h
#ifndef _PARROT_VERTEX_H_ #define _PARROT_VERTEX_H_ #include "Vector.h" #include "MathUtil.h" namespace parrot { class Vertex { public: Vector4f pos; Vector4f color; Vector2f texPos; Vector4f normal; Vertex() = default; Vertex(Vector4f pos, Vector4f color, Vector2f texPos, Vector4f normal) :pos(pos), color(color), texPos(texPos), normal(normal){} Vertex(const Vertex& rhs) :pos(rhs.pos), color(rhs.color), texPos(rhs.texPos), normal(rhs.normal){} }; class VertexOut { public: Vector4f pos;//世界变换后的坐标 Vector4f projPos;//投影变换后的坐标 Vector2f texPos;// 纹理坐标 Vector4f normal;//法线 Vector4f color; float deepTest; // 1 / z VertexOut() = default; VertexOut(Vector4f pos, Vector4f projPos, Vector4f normal, Vector2f texPos, Vector4f color, float deep) : pos(pos), projPos(projPos), normal(normal), texPos(texPos), color(color), deepTest(deep) { } VertexOut(const VertexOut& rhs) :pos(rhs.pos), projPos(rhs.projPos), texPos(rhs.texPos), normal(rhs.normal), color(rhs.color), deepTest(rhs.deepTest) { } VertexOut& operator= (const VertexOut& rhs) { if (this == &rhs) return *this; this->normal = rhs.normal; this->pos = rhs.pos; this->projPos = rhs.projPos; this->texPos = rhs.texPos; this->color = rhs.color; this->deepTest = rhs.deepTest; return *this; } inline VertexOut interpolate(const VertexOut& v2, float t) const { return VertexOut( this->pos.interpolate(v2.pos, t), this->projPos.interpolate(v2.projPos, t), this->normal.interpolate(v2.normal, t), this->texPos.interpolate(v2.texPos, t), this->color.interpolate(v2.color, t), MathUtil::interpolate(this->deepTest, v2.deepTest, t) ); } }; } #endif
[ "booirror@163.com" ]
booirror@163.com
3c0e1b0bff9c51f2438adddf72f6db370c20485c
1468b015f5ce882dbd39dc75c9a6560179a936fb
/card/M2634.cpp
f7e1812a2a004cda0a8ca9aa9eca86b21b36b523
[]
no_license
Escobaj/HearthstoneResolver
cbfc682993435c01f8b75d4409c99fb4870b9bb3
c93b693ef318fc9f43d35e81931371f626147083
refs/heads/master
2021-04-30T22:31:01.247134
2017-01-31T00:05:32
2017-01-31T00:05:32
74,474,216
8
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
// // Created by Jo on 19/12/2016. // #include "M2634.h" M2634::M2634(const EventHandler &e) : Minion(e) { this->set_id(2634); this->set_attackMax(4); this->set_defaultCost(3); this->set_name("Écaille-d’effroi"); this->set_membership(Class::HUNTER); this->set_type(CardType::BEAST); this->set_attackMax(4); this->set_maxHealth(2); } void M2634::init() { }
[ "joffrey.ecobar@epitech.eu" ]
joffrey.ecobar@epitech.eu
e3eb94a50f8881e62ca8b277ae03fc734f163b2d
1edf53fb0a1e22180ce33e1319c56f92ff6a5ce7
/Neon/source/graphics/objects/command/command_queue_type.h
3075c93c7c3538dda537cfa506a6d09c471dfcea
[]
no_license
PepijnAverink/NEON
3b8a5fab202059bb60d9e0a67336766de066fe60
8019bad34b42e6ca065430c85bbe9ff9875f4e9b
refs/heads/master
2022-10-03T13:00:35.167865
2020-06-04T10:51:33
2020-06-04T10:51:33
255,528,429
0
0
null
null
null
null
UTF-8
C++
false
false
361
h
#pragma once namespace Neon { namespace Graphics { // ------------------------------------------ // CommandQueueType enum // Specifies the type and or level of a CommandQueue obbject // ------------------------------------------ enum CommandQueueType { NEON_COMMAND_QUEUE_TYPE_NONE = 0x00, NEON_COMMAND_QUEUE_TYPE_DIRECT = 0x01, }; } }
[ "p.averink@gmail.com" ]
p.averink@gmail.com
e946ffac651239dc1cf60dd0323dd255751a3d3d
d9af6ca49774c009c4b277c24fb78f796fe8476b
/src/obfuscation.cpp
3123a679ceb1261602512b385952adbc0086fd9e
[ "MIT" ]
permissive
loxevesavu/Ingenuity
7924abf996ca1b96885b961b924a565b7fd41312
f57a4d8f089c245d0d7ea676dd4573bb30c05300
refs/heads/master
2020-04-25T22:34:05.740695
2018-12-11T05:56:01
2018-12-11T05:56:01
173,115,384
0
0
null
2019-02-28T13:17:58
2019-02-28T13:17:57
null
UTF-8
C++
false
false
83,877
cpp
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The Ingenuity developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "obfuscation.h" #include "coincontrol.h" #include "init.h" #include "main.h" #include "masternodeman.h" #include "script/sign.h" #include "swifttx.h" #include "ui_interface.h" #include "util.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #include <boost/assign/list_of.hpp> #include <openssl/rand.h> using namespace std; using namespace boost; // The main object for accessing Obfuscation CObfuscationPool obfuScationPool; // A helper object for signing messages from Masternodes CObfuScationSigner obfuScationSigner; // The current Obfuscations in progress on the network std::vector<CObfuscationQueue> vecObfuscationQueue; // Keep track of the used Masternodes std::vector<CTxIn> vecMasternodesUsed; // Keep track of the scanning errors I've seen map<uint256, CObfuscationBroadcastTx> mapObfuscationBroadcastTxes; // Keep track of the active Masternode CActiveMasternode activeMasternode; /* *** BEGIN OBFUSCATION MAGIC - INGY ********** Copyright (c) 2014-2015, Dash Developers eduffield - evan@dashpay.io udjinm6 - udjinm6@dashpay.io */ void CObfuscationPool::ProcessMessageObfuscation(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality if (!masternodeSync.IsBlockchainSynced()) return; if (strCommand == "dsa") { //Obfuscation Accept Into Pool int errorID; if (pfrom->nVersion < ActiveProtocol()) { errorID = ERR_VERSION; LogPrintf("dsa -- incompatible version! \n"); pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (!fMasterNode) { errorID = ERR_NOT_A_MN; LogPrintf("dsa -- not a Masternode! \n"); pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } int nDenom; CTransaction txCollateral; vRecv >> nDenom >> txCollateral; CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn == NULL) { errorID = ERR_MN_LIST; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (sessionUsers == 0) { if (pmn->nLastDsq != 0 && pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) / 5 > mnodeman.nDsqCount) { LogPrintf("dsa -- last dsq too recent, must wait. %s \n", pfrom->addr.ToString()); errorID = ERR_RECENT; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } } if (!IsCompatibleWithSession(nDenom, txCollateral, errorID)) { LogPrintf("dsa -- not compatible with existing transactions! \n"); pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } else { LogPrintf("dsa -- is compatible, please submit! \n"); pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_ACCEPTED, errorID); return; } } else if (strCommand == "dsq") { //Obfuscation Queue TRY_LOCK(cs_obfuscation, lockRecv); if (!lockRecv) return; if (pfrom->nVersion < ActiveProtocol()) { return; } CObfuscationQueue dsq; vRecv >> dsq; CService addr; if (!dsq.GetAddress(addr)) return; if (!dsq.CheckSignature()) return; if (dsq.IsExpired()) return; CMasternode* pmn = mnodeman.Find(dsq.vin); if (pmn == NULL) return; // if the queue is ready, submit if we can if (dsq.ready) { if (!pSubmittedToMasternode) return; if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)addr) { LogPrintf("dsq - message doesn't match current Masternode - %s != %s\n", pSubmittedToMasternode->addr.ToString(), addr.ToString()); return; } if (state == POOL_STATUS_QUEUE) { LogPrint("obfuscation", "Obfuscation queue is ready - %s\n", addr.ToString()); PrepareObfuscationDenominate(); } } else { BOOST_FOREACH (CObfuscationQueue q, vecObfuscationQueue) { if (q.vin == dsq.vin) return; } LogPrint("obfuscation", "dsq last %d last2 %d count %d\n", pmn->nLastDsq, pmn->nLastDsq + mnodeman.size() / 5, mnodeman.nDsqCount); //don't allow a few nodes to dominate the queuing process if (pmn->nLastDsq != 0 && pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) / 5 > mnodeman.nDsqCount) { LogPrint("obfuscation", "dsq -- Masternode sending too many dsq messages. %s \n", pmn->addr.ToString()); return; } mnodeman.nDsqCount++; pmn->nLastDsq = mnodeman.nDsqCount; pmn->allowFreeTx = true; LogPrint("obfuscation", "dsq - new Obfuscation queue object - %s\n", addr.ToString()); vecObfuscationQueue.push_back(dsq); dsq.Relay(); dsq.time = GetTime(); } } else if (strCommand == "dsi") { //ObfuScation vIn int errorID; if (pfrom->nVersion < ActiveProtocol()) { LogPrintf("dsi -- incompatible version! \n"); errorID = ERR_VERSION; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (!fMasterNode) { LogPrintf("dsi -- not a Masternode! \n"); errorID = ERR_NOT_A_MN; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } std::vector<CTxIn> in; CAmount nAmount; CTransaction txCollateral; std::vector<CTxOut> out; vRecv >> in >> nAmount >> txCollateral >> out; //do we have enough users in the current session? if (!IsSessionReady()) { LogPrintf("dsi -- session not complete! \n"); errorID = ERR_SESSION; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } //do we have the same denominations as the current session? if (!IsCompatibleWithEntries(out)) { LogPrintf("dsi -- not compatible with existing transactions! \n"); errorID = ERR_EXISTING_TX; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } //check it like a transaction { CAmount nValueIn = 0; CAmount nValueOut = 0; bool missingTx = false; CValidationState state; CMutableTransaction tx; BOOST_FOREACH (const CTxOut o, out) { nValueOut += o.nValue; tx.vout.push_back(o); if (o.scriptPubKey.size() != 25) { LogPrintf("dsi - non-standard pubkey detected! %s\n", o.scriptPubKey.ToString()); errorID = ERR_NON_STANDARD_PUBKEY; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (!o.scriptPubKey.IsNormalPaymentScript()) { LogPrintf("dsi - invalid script! %s\n", o.scriptPubKey.ToString()); errorID = ERR_INVALID_SCRIPT; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } } BOOST_FOREACH (const CTxIn i, in) { tx.vin.push_back(i); LogPrint("obfuscation", "dsi -- tx in %s\n", i.ToString()); CTransaction tx2; uint256 hash; if (GetTransaction(i.prevout.hash, tx2, hash, true)) { if (tx2.vout.size() > i.prevout.n) { nValueIn += tx2.vout[i.prevout.n].nValue; } } else { missingTx = true; } } if (nValueIn > OBFUSCATION_POOL_MAX) { LogPrintf("dsi -- more than Obfuscation pool max! %s\n", tx.ToString()); errorID = ERR_MAXIMUM; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (!missingTx) { if (nValueIn - nValueOut > nValueIn * .01) { LogPrintf("dsi -- fees are too high! %s\n", tx.ToString()); errorID = ERR_FEES; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } } else { LogPrintf("dsi -- missing input tx! %s\n", tx.ToString()); errorID = ERR_MISSING_TX; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } { LOCK(cs_main); if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL, false, true)) { LogPrintf("dsi -- transaction not valid! \n"); errorID = ERR_INVALID_TX; pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } } } if (AddEntry(in, nAmount, txCollateral, out, errorID)) { pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_ACCEPTED, errorID); Check(); RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET); } else { pfrom->PushMessage("dssu", sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); } } else if (strCommand == "dssu") { //Obfuscation status update if (pfrom->nVersion < ActiveProtocol()) { return; } if (!pSubmittedToMasternode) return; if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { //LogPrintf("dssu - message doesn't match current Masternode - %s != %s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int sessionIDMessage; int state; int entriesCount; int accepted; int errorID; vRecv >> sessionIDMessage >> state >> entriesCount >> accepted >> errorID; LogPrint("obfuscation", "dssu - state: %i entriesCount: %i accepted: %i error: %s \n", state, entriesCount, accepted, GetMessageByID(errorID)); if ((accepted != 1 && accepted != 0) && sessionID != sessionIDMessage) { LogPrintf("dssu - message doesn't match current Obfuscation session %d %d\n", sessionID, sessionIDMessage); return; } StatusUpdate(state, entriesCount, accepted, errorID, sessionIDMessage); } else if (strCommand == "dss") { //Obfuscation Sign Final Tx if (pfrom->nVersion < ActiveProtocol()) { return; } vector<CTxIn> sigs; vRecv >> sigs; bool success = false; int count = 0; BOOST_FOREACH (const CTxIn item, sigs) { if (AddScriptSig(item)) success = true; LogPrint("obfuscation", " -- sigs count %d %d\n", (int)sigs.size(), count); count++; } if (success) { obfuScationPool.Check(); RelayStatus(obfuScationPool.sessionID, obfuScationPool.GetState(), obfuScationPool.GetEntriesCount(), MASTERNODE_RESET); } } else if (strCommand == "dsf") { //Obfuscation Final tx if (pfrom->nVersion < ActiveProtocol()) { return; } if (!pSubmittedToMasternode) return; if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { //LogPrintf("dsc - message doesn't match current Masternode - %s != %s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int sessionIDMessage; CTransaction txNew; vRecv >> sessionIDMessage >> txNew; if (sessionID != sessionIDMessage) { LogPrint("obfuscation", "dsf - message doesn't match current Obfuscation session %d %d\n", sessionID, sessionIDMessage); return; } //check to see if input is spent already? (and probably not confirmed) SignFinalTransaction(txNew, pfrom); } else if (strCommand == "dsc") { //Obfuscation Complete if (pfrom->nVersion < ActiveProtocol()) { return; } if (!pSubmittedToMasternode) return; if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { //LogPrintf("dsc - message doesn't match current Masternode - %s != %s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int sessionIDMessage; bool error; int errorID; vRecv >> sessionIDMessage >> error >> errorID; if (sessionID != sessionIDMessage) { LogPrint("obfuscation", "dsc - message doesn't match current Obfuscation session %d %d\n", obfuScationPool.sessionID, sessionIDMessage); return; } obfuScationPool.CompletedTransaction(error, errorID); } } int randomizeList(int i) { return std::rand() % i; } void CObfuscationPool::Reset() { cachedLastSuccess = 0; lastNewBlock = 0; txCollateral = CMutableTransaction(); vecMasternodesUsed.clear(); UnlockCoins(); SetNull(); } void CObfuscationPool::SetNull() { // MN side sessionUsers = 0; vecSessionCollateral.clear(); // Client side entriesCount = 0; lastEntryAccepted = 0; countEntriesAccepted = 0; sessionFoundMasternode = false; // Both sides state = POOL_STATUS_IDLE; sessionID = 0; sessionDenom = 0; entries.clear(); finalTransaction.vin.clear(); finalTransaction.vout.clear(); lastTimeChanged = GetTimeMillis(); // -- seed random number generator (used for ordering output lists) unsigned int seed = 0; RAND_bytes((unsigned char*)&seed, sizeof(seed)); std::srand(seed); } bool CObfuscationPool::SetCollateralAddress(std::string strAddress) { CBitcoinAddress address; if (!address.SetString(strAddress)) { LogPrintf("CObfuscationPool::SetCollateralAddress - Invalid Obfuscation collateral address\n"); return false; } collateralPubKey = GetScriptForDestination(address.Get()); return true; } // // Unlock coins after Obfuscation fails or succeeds // void CObfuscationPool::UnlockCoins() { while (true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if (!lockWallet) { MilliSleep(50); continue; } BOOST_FOREACH (CTxIn v, lockedCoins) pwalletMain->UnlockCoin(v.prevout); break; } lockedCoins.clear(); } std::string CObfuscationPool::GetStatus() { static int showingObfuScationMessage = 0; showingObfuScationMessage += 10; std::string suffix = ""; if (chainActive.Tip()->nHeight - cachedLastSuccess < minBlockSpacing || !masternodeSync.IsBlockchainSynced()) { return strAutoDenomResult; } switch (state) { case POOL_STATUS_IDLE: return _("Obfuscation is idle."); case POOL_STATUS_ACCEPTING_ENTRIES: if (entriesCount == 0) { showingObfuScationMessage = 0; return strAutoDenomResult; } else if (lastEntryAccepted == 1) { if (showingObfuScationMessage % 10 > 8) { lastEntryAccepted = 0; showingObfuScationMessage = 0; } return _("Obfuscation request complete:") + " " + _("Your transaction was accepted into the pool!"); } else { std::string suffix = ""; if (showingObfuScationMessage % 70 <= 40) return strprintf(_("Submitted following entries to masternode: %u / %d"), entriesCount, GetMaxPoolTransactions()); else if (showingObfuScationMessage % 70 <= 50) suffix = "."; else if (showingObfuScationMessage % 70 <= 60) suffix = ".."; else if (showingObfuScationMessage % 70 <= 70) suffix = "..."; return strprintf(_("Submitted to masternode, waiting for more entries ( %u / %d ) %s"), entriesCount, GetMaxPoolTransactions(), suffix); } case POOL_STATUS_SIGNING: if (showingObfuScationMessage % 70 <= 40) return _("Found enough users, signing ..."); else if (showingObfuScationMessage % 70 <= 50) suffix = "."; else if (showingObfuScationMessage % 70 <= 60) suffix = ".."; else if (showingObfuScationMessage % 70 <= 70) suffix = "..."; return strprintf(_("Found enough users, signing ( waiting %s )"), suffix); case POOL_STATUS_TRANSMISSION: return _("Transmitting final transaction."); case POOL_STATUS_FINALIZE_TRANSACTION: return _("Finalizing transaction."); case POOL_STATUS_ERROR: return _("Obfuscation request incomplete:") + " " + lastMessage + " " + _("Will retry..."); case POOL_STATUS_SUCCESS: return _("Obfuscation request complete:") + " " + lastMessage; case POOL_STATUS_QUEUE: if (showingObfuScationMessage % 70 <= 30) suffix = "."; else if (showingObfuScationMessage % 70 <= 50) suffix = ".."; else if (showingObfuScationMessage % 70 <= 70) suffix = "..."; return strprintf(_("Submitted to masternode, waiting in queue %s"), suffix); ; default: return strprintf(_("Unknown state: id = %u"), state); } } // // Check the Obfuscation progress and send client updates if a Masternode // void CObfuscationPool::Check() { if (fMasterNode) LogPrint("obfuscation", "CObfuscationPool::Check() - entries count %lu\n", entries.size()); //printf("CObfuscationPool::Check() %d - %d - %d\n", state, anonTx.CountEntries(), GetTimeMillis()-lastTimeChanged); if (fMasterNode) { LogPrint("obfuscation", "CObfuscationPool::Check() - entries count %lu\n", entries.size()); // If entries is full, then move on to the next phase if (state == POOL_STATUS_ACCEPTING_ENTRIES && (int)entries.size() >= GetMaxPoolTransactions()) { LogPrint("obfuscation", "CObfuscationPool::Check() -- TRYING TRANSACTION \n"); UpdateState(POOL_STATUS_FINALIZE_TRANSACTION); } } // create the finalized transaction for distribution to the clients if (state == POOL_STATUS_FINALIZE_TRANSACTION) { LogPrint("obfuscation", "CObfuscationPool::Check() -- FINALIZE TRANSACTIONS\n"); UpdateState(POOL_STATUS_SIGNING); if (fMasterNode) { CMutableTransaction txNew; // make our new transaction for (unsigned int i = 0; i < entries.size(); i++) { BOOST_FOREACH (const CTxOut& v, entries[i].vout) txNew.vout.push_back(v); BOOST_FOREACH (const CTxDSIn& s, entries[i].sev) txNew.vin.push_back(s); } // shuffle the outputs for improved anonymity std::random_shuffle(txNew.vin.begin(), txNew.vin.end(), randomizeList); std::random_shuffle(txNew.vout.begin(), txNew.vout.end(), randomizeList); LogPrint("obfuscation", "Transaction 1: %s\n", txNew.ToString()); finalTransaction = txNew; // request signatures from clients RelayFinalTransaction(sessionID, finalTransaction); } } // If we have all of the signatures, try to compile the transaction if (fMasterNode && state == POOL_STATUS_SIGNING && SignaturesComplete()) { LogPrint("obfuscation", "CObfuscationPool::Check() -- SIGNING\n"); UpdateState(POOL_STATUS_TRANSMISSION); CheckFinalTransaction(); } // reset if we're here for 10 seconds if ((state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) && GetTimeMillis() - lastTimeChanged >= 10000) { LogPrint("obfuscation", "CObfuscationPool::Check() -- timeout, RESETTING\n"); UnlockCoins(); SetNull(); if (fMasterNode) RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET); } } void CObfuscationPool::CheckFinalTransaction() { if (!fMasterNode) return; // check and relay final tx only on masternode CWalletTx txNew = CWalletTx(pwalletMain, finalTransaction); LOCK2(cs_main, pwalletMain->cs_wallet); { LogPrint("obfuscation", "Transaction 2: %s\n", txNew.ToString()); // See if the transaction is valid if (!txNew.AcceptToMemoryPool(false, true, true)) { LogPrintf("CObfuscationPool::Check() - CommitTransaction : Error: Transaction not valid\n"); SetNull(); // not much we can do in this case UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); RelayCompletedTransaction(sessionID, true, ERR_INVALID_TX); return; } LogPrintf("CObfuscationPool::Check() -- IS MASTER -- TRANSMITTING OBFUSCATION\n"); // sign a message int64_t sigTime = GetAdjustedTime(); std::string strMessage = txNew.GetHash().ToString() + boost::lexical_cast<std::string>(sigTime); std::string strError = ""; std::vector<unsigned char> vchSig; CKey key2; CPubKey pubkey2; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, strError, key2, pubkey2)) { LogPrintf("CObfuscationPool::Check() - ERROR: Invalid Masternodeprivkey: '%s'\n", strError); return; } if (!obfuScationSigner.SignMessage(strMessage, strError, vchSig, key2)) { LogPrintf("CObfuscationPool::Check() - Sign message failed\n"); return; } if (!obfuScationSigner.VerifyMessage(pubkey2, vchSig, strMessage, strError)) { LogPrintf("CObfuscationPool::Check() - Verify message failed\n"); return; } if (!mapObfuscationBroadcastTxes.count(txNew.GetHash())) { CObfuscationBroadcastTx dstx; dstx.tx = txNew; dstx.vin = activeMasternode.vin; dstx.vchSig = vchSig; dstx.sigTime = sigTime; mapObfuscationBroadcastTxes.insert(make_pair(txNew.GetHash(), dstx)); } CInv inv(MSG_DSTX, txNew.GetHash()); RelayInv(inv); // Tell the clients it was successful RelayCompletedTransaction(sessionID, false, MSG_SUCCESS); // Randomly charge clients ChargeRandomFees(); // Reset LogPrint("obfuscation", "CObfuscationPool::Check() -- COMPLETED -- RESETTING\n"); SetNull(); RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET); } } // // Charge clients a fee if they're abusive // // Why bother? Obfuscation uses collateral to ensure abuse to the process is kept to a minimum. // The submission and signing stages in Obfuscation are completely separate. In the cases where // a client submits a transaction then refused to sign, there must be a cost. Otherwise they // would be able to do this over and over again and bring the mixing to a hault. // // How does this work? Messages to Masternodes come in via "dsi", these require a valid collateral // transaction for the client to be able to enter the pool. This transaction is kept by the Masternode // until the transaction is either complete or fails. // void CObfuscationPool::ChargeFees() { if (!fMasterNode) return; //we don't need to charge collateral for every offence. int offences = 0; int r = rand() % 100; if (r > 33) return; if (state == POOL_STATUS_ACCEPTING_ENTRIES) { BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { bool found = false; BOOST_FOREACH (const CObfuScationEntry& v, entries) { if (v.collateral == txCollateral) { found = true; } } // This queue entry didn't send us the promised transaction if (!found) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't send transaction). Found offence.\n"); offences++; } } } if (state == POOL_STATUS_SIGNING) { // who didn't sign? BOOST_FOREACH (const CObfuScationEntry v, entries) { BOOST_FOREACH (const CTxDSIn s, v.sev) { if (!s.fHasSig) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't sign). Found offence\n"); offences++; } } } } r = rand() % 100; int target = 0; //mostly offending? if (offences >= Params().PoolMaxTransactions() - 1 && r > 33) return; //everyone is an offender? That's not right if (offences >= Params().PoolMaxTransactions()) return; //charge one of the offenders randomly if (offences > 1) target = 50; //pick random client to charge r = rand() % 100; if (state == POOL_STATUS_ACCEPTING_ENTRIES) { BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { bool found = false; BOOST_FOREACH (const CObfuScationEntry& v, entries) { if (v.collateral == txCollateral) { found = true; } } // This queue entry didn't send us the promised transaction if (!found && r > target) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't send transaction). charging fees.\n"); CWalletTx wtxCollateral = CWalletTx(pwalletMain, txCollateral); // Broadcast if (!wtxCollateral.AcceptToMemoryPool(true)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CObfuscationPool::ChargeFees() : Error: Transaction not valid"); } wtxCollateral.RelayWalletTransaction(); return; } } } if (state == POOL_STATUS_SIGNING) { // who didn't sign? BOOST_FOREACH (const CObfuScationEntry v, entries) { BOOST_FOREACH (const CTxDSIn s, v.sev) { if (!s.fHasSig && r > target) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't sign). charging fees.\n"); CWalletTx wtxCollateral = CWalletTx(pwalletMain, v.collateral); // Broadcast if (!wtxCollateral.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CObfuscationPool::ChargeFees() : Error: Transaction not valid"); } wtxCollateral.RelayWalletTransaction(); return; } } } } } // charge the collateral randomly // - Obfuscation is completely free, to pay miners we randomly pay the collateral of users. void CObfuscationPool::ChargeRandomFees() { if (fMasterNode) { int i = 0; BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { int r = rand() % 100; /* Collateral Fee Charges: Being that Obfuscation has "no fees" we need to have some kind of cost associated with using it to stop abuse. Otherwise it could serve as an attack vector and allow endless transaction that would bloat Ingenuity and make it unusable. To stop these kinds of attacks 1 in 10 successful transactions are charged. This adds up to a cost of 0.001 INGY per transaction on average. */ if (r <= 10) { LogPrintf("CObfuscationPool::ChargeRandomFees -- charging random fees. %u\n", i); CWalletTx wtxCollateral = CWalletTx(pwalletMain, txCollateral); // Broadcast if (!wtxCollateral.AcceptToMemoryPool(true)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CObfuscationPool::ChargeRandomFees() : Error: Transaction not valid"); } wtxCollateral.RelayWalletTransaction(); } } } } // // Check for various timeouts (queue objects, Obfuscation, etc) // void CObfuscationPool::CheckTimeout() { if (!fEnableZeromint && !fMasterNode) return; // catching hanging sessions if (!fMasterNode) { switch (state) { case POOL_STATUS_TRANSMISSION: LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Session complete -- Running Check()\n"); Check(); break; case POOL_STATUS_ERROR: LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Pool error -- Running Check()\n"); Check(); break; case POOL_STATUS_SUCCESS: LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Pool success -- Running Check()\n"); Check(); break; } } // check Obfuscation queue objects for timeouts int c = 0; vector<CObfuscationQueue>::iterator it = vecObfuscationQueue.begin(); while (it != vecObfuscationQueue.end()) { if ((*it).IsExpired()) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() : Removing expired queue entry - %d\n", c); it = vecObfuscationQueue.erase(it); } else ++it; c++; } int addLagTime = 0; if (!fMasterNode) addLagTime = 10000; //if we're the client, give the server a few extra seconds before resetting. if (state == POOL_STATUS_ACCEPTING_ENTRIES || state == POOL_STATUS_QUEUE) { c = 0; // check for a timeout and reset if needed vector<CObfuScationEntry>::iterator it2 = entries.begin(); while (it2 != entries.end()) { if ((*it2).IsExpired()) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() : Removing expired entry - %d\n", c); it2 = entries.erase(it2); if (entries.size() == 0) { UnlockCoins(); SetNull(); } if (fMasterNode) { RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET); } } else ++it2; c++; } if (GetTimeMillis() - lastTimeChanged >= (OBFUSCATION_QUEUE_TIMEOUT * 1000) + addLagTime) { UnlockCoins(); SetNull(); } } else if (GetTimeMillis() - lastTimeChanged >= (OBFUSCATION_QUEUE_TIMEOUT * 1000) + addLagTime) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Session timed out (%ds) -- resetting\n", OBFUSCATION_QUEUE_TIMEOUT); UnlockCoins(); SetNull(); UpdateState(POOL_STATUS_ERROR); lastMessage = _("Session timed out."); } if (state == POOL_STATUS_SIGNING && GetTimeMillis() - lastTimeChanged >= (OBFUSCATION_SIGNING_TIMEOUT * 1000) + addLagTime) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Session timed out (%ds) -- restting\n", OBFUSCATION_SIGNING_TIMEOUT); ChargeFees(); UnlockCoins(); SetNull(); UpdateState(POOL_STATUS_ERROR); lastMessage = _("Signing timed out."); } } // // Check for complete queue // void CObfuscationPool::CheckForCompleteQueue() { if (!fEnableZeromint && !fMasterNode) return; /* Check to see if we're ready for submissions from clients */ // // After receiving multiple dsa messages, the queue will switch to "accepting entries" // which is the active state right before merging the transaction // if (state == POOL_STATUS_QUEUE && sessionUsers == GetMaxPoolTransactions()) { UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); CObfuscationQueue dsq; dsq.nDenom = sessionDenom; dsq.vin = activeMasternode.vin; dsq.time = GetTime(); dsq.ready = true; dsq.Sign(); dsq.Relay(); } } // check to see if the signature is valid bool CObfuscationPool::SignatureValid(const CScript& newSig, const CTxIn& newVin) { CMutableTransaction txNew; txNew.vin.clear(); txNew.vout.clear(); int found = -1; CScript sigPubKey = CScript(); unsigned int i = 0; BOOST_FOREACH (CObfuScationEntry& e, entries) { BOOST_FOREACH (const CTxOut& out, e.vout) txNew.vout.push_back(out); BOOST_FOREACH (const CTxDSIn& s, e.sev) { txNew.vin.push_back(s); if (s == newVin) { found = i; sigPubKey = s.prevPubKey; } i++; } } if (found >= 0) { //might have to do this one input at a time? int n = found; txNew.vin[n].scriptSig = newSig; LogPrint("obfuscation", "CObfuscationPool::SignatureValid() - Sign with sig %s\n", newSig.ToString().substr(0, 24)); if (!VerifyScript(txNew.vin[n].scriptSig, sigPubKey, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, MutableTransactionSignatureChecker(&txNew, n))) { LogPrint("obfuscation", "CObfuscationPool::SignatureValid() - Signing - Error signing input %u\n", n); return false; } } LogPrint("obfuscation", "CObfuscationPool::SignatureValid() - Signing - Successfully validated input\n"); return true; } // check to make sure the collateral provided by the client is valid bool CObfuscationPool::IsCollateralValid(const CTransaction& txCollateral) { if (txCollateral.vout.size() < 1) return false; if (txCollateral.nLockTime != 0) return false; int64_t nValueIn = 0; int64_t nValueOut = 0; bool missingTx = false; BOOST_FOREACH (const CTxOut o, txCollateral.vout) { nValueOut += o.nValue; if (!o.scriptPubKey.IsNormalPaymentScript()) { LogPrintf("CObfuscationPool::IsCollateralValid - Invalid Script %s\n", txCollateral.ToString()); return false; } } BOOST_FOREACH (const CTxIn i, txCollateral.vin) { CTransaction tx2; uint256 hash; if (GetTransaction(i.prevout.hash, tx2, hash, true)) { if (tx2.vout.size() > i.prevout.n) { nValueIn += tx2.vout[i.prevout.n].nValue; } } else { missingTx = true; } } if (missingTx) { LogPrint("obfuscation", "CObfuscationPool::IsCollateralValid - Unknown inputs in collateral transaction - %s\n", txCollateral.ToString()); return false; } //collateral transactions are required to pay out OBFUSCATION_COLLATERAL as a fee to the miners if (nValueIn - nValueOut < OBFUSCATION_COLLATERAL) { LogPrint("obfuscation", "CObfuscationPool::IsCollateralValid - did not include enough fees in transaction %d\n%s\n", nValueOut - nValueIn, txCollateral.ToString()); return false; } LogPrint("obfuscation", "CObfuscationPool::IsCollateralValid %s\n", txCollateral.ToString()); { LOCK(cs_main); CValidationState state; if (!AcceptableInputs(mempool, state, txCollateral, true, NULL)) { if (fDebug) LogPrintf("CObfuscationPool::IsCollateralValid - didn't pass IsAcceptable\n"); return false; } } return true; } // // Add a clients transaction to the pool // bool CObfuscationPool::AddEntry(const std::vector<CTxIn>& newInput, const CAmount& nAmount, const CTransaction& txCollateral, const std::vector<CTxOut>& newOutput, int& errorID) { if (!fMasterNode) return false; BOOST_FOREACH (CTxIn in, newInput) { if (in.prevout.IsNull() || nAmount < 0) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - input not valid!\n"); errorID = ERR_INVALID_INPUT; sessionUsers--; return false; } } if (!IsCollateralValid(txCollateral)) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - collateral not valid!\n"); errorID = ERR_INVALID_COLLATERAL; sessionUsers--; return false; } if ((int)entries.size() >= GetMaxPoolTransactions()) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - entries is full!\n"); errorID = ERR_ENTRIES_FULL; sessionUsers--; return false; } BOOST_FOREACH (CTxIn in, newInput) { LogPrint("obfuscation", "looking for vin -- %s\n", in.ToString()); BOOST_FOREACH (const CObfuScationEntry& v, entries) { BOOST_FOREACH (const CTxDSIn& s, v.sev) { if ((CTxIn)s == in) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - found in vin\n"); errorID = ERR_ALREADY_HAVE; sessionUsers--; return false; } } } } CObfuScationEntry v; v.Add(newInput, nAmount, txCollateral, newOutput); entries.push_back(v); LogPrint("obfuscation", "CObfuscationPool::AddEntry -- adding %s\n", newInput[0].ToString()); errorID = MSG_ENTRIES_ADDED; return true; } bool CObfuscationPool::AddScriptSig(const CTxIn& newVin) { LogPrint("obfuscation", "CObfuscationPool::AddScriptSig -- new sig %s\n", newVin.scriptSig.ToString().substr(0, 24)); BOOST_FOREACH (const CObfuScationEntry& v, entries) { BOOST_FOREACH (const CTxDSIn& s, v.sev) { if (s.scriptSig == newVin.scriptSig) { LogPrint("obfuscation", "CObfuscationPool::AddScriptSig - already exists\n"); return false; } } } if (!SignatureValid(newVin.scriptSig, newVin)) { LogPrint("obfuscation", "CObfuscationPool::AddScriptSig - Invalid Sig\n"); return false; } LogPrint("obfuscation", "CObfuscationPool::AddScriptSig -- sig %s\n", newVin.ToString()); BOOST_FOREACH (CTxIn& vin, finalTransaction.vin) { if (newVin.prevout == vin.prevout && vin.nSequence == newVin.nSequence) { vin.scriptSig = newVin.scriptSig; vin.prevPubKey = newVin.prevPubKey; LogPrint("obfuscation", "CObfuScationPool::AddScriptSig -- adding to finalTransaction %s\n", newVin.scriptSig.ToString().substr(0, 24)); } } for (unsigned int i = 0; i < entries.size(); i++) { if (entries[i].AddSig(newVin)) { LogPrint("obfuscation", "CObfuScationPool::AddScriptSig -- adding %s\n", newVin.scriptSig.ToString().substr(0, 24)); return true; } } LogPrintf("CObfuscationPool::AddScriptSig -- Couldn't set sig!\n"); return false; } // Check to make sure everything is signed bool CObfuscationPool::SignaturesComplete() { BOOST_FOREACH (const CObfuScationEntry& v, entries) { BOOST_FOREACH (const CTxDSIn& s, v.sev) { if (!s.fHasSig) return false; } } return true; } // // Execute a Obfuscation denomination via a Masternode. // This is only ran from clients // void CObfuscationPool::SendObfuscationDenominate(std::vector<CTxIn>& vin, std::vector<CTxOut>& vout, CAmount amount) { if (fMasterNode) { LogPrintf("CObfuscationPool::SendObfuscationDenominate() - Obfuscation from a Masternode is not supported currently.\n"); return; } if (txCollateral == CMutableTransaction()) { LogPrintf("CObfuscationPool:SendObfuscationDenominate() - Obfuscation collateral not set"); return; } // lock the funds we're going to use BOOST_FOREACH (CTxIn in, txCollateral.vin) lockedCoins.push_back(in); BOOST_FOREACH (CTxIn in, vin) lockedCoins.push_back(in); //BOOST_FOREACH(CTxOut o, vout) // LogPrintf(" vout - %s\n", o.ToString()); // we should already be connected to a Masternode if (!sessionFoundMasternode) { LogPrintf("CObfuscationPool::SendObfuscationDenominate() - No Masternode has been selected yet.\n"); UnlockCoins(); SetNull(); return; } if (!CheckDiskSpace()) { UnlockCoins(); SetNull(); fEnableZeromint = false; LogPrintf("CObfuscationPool::SendObfuscationDenominate() - Not enough disk space, disabling Obfuscation.\n"); return; } UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); LogPrintf("CObfuscationPool::SendObfuscationDenominate() - Added transaction to pool.\n"); ClearLastMessage(); //check it against the memory pool to make sure it's valid { CAmount nValueOut = 0; CValidationState state; CMutableTransaction tx; BOOST_FOREACH (const CTxOut& o, vout) { nValueOut += o.nValue; tx.vout.push_back(o); } BOOST_FOREACH (const CTxIn& i, vin) { tx.vin.push_back(i); LogPrint("obfuscation", "dsi -- tx in %s\n", i.ToString()); } LogPrintf("Submitting tx %s\n", tx.ToString()); while (true) { TRY_LOCK(cs_main, lockMain); if (!lockMain) { MilliSleep(50); continue; } if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL, false, true)) { LogPrintf("dsi -- transaction not valid! %s \n", tx.ToString()); UnlockCoins(); SetNull(); return; } break; } } // store our entry for later use CObfuScationEntry e; e.Add(vin, amount, txCollateral, vout); entries.push_back(e); RelayIn(entries[0].sev, entries[0].amount, txCollateral, entries[0].vout); Check(); } // Incoming message from Masternode updating the progress of Obfuscation // newAccepted: -1 mean's it'n not a "transaction accepted/not accepted" message, just a standard update // 0 means transaction was not accepted // 1 means transaction was accepted bool CObfuscationPool::StatusUpdate(int newState, int newEntriesCount, int newAccepted, int& errorID, int newSessionID) { if (fMasterNode) return false; if (state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) return false; UpdateState(newState); entriesCount = newEntriesCount; if (errorID != MSG_NOERR) strAutoDenomResult = _("Masternode:") + " " + GetMessageByID(errorID); if (newAccepted != -1) { lastEntryAccepted = newAccepted; countEntriesAccepted += newAccepted; if (newAccepted == 0) { UpdateState(POOL_STATUS_ERROR); lastMessage = GetMessageByID(errorID); } if (newAccepted == 1 && newSessionID != 0) { sessionID = newSessionID; LogPrintf("CObfuscationPool::StatusUpdate - set sessionID to %d\n", sessionID); sessionFoundMasternode = true; } } if (newState == POOL_STATUS_ACCEPTING_ENTRIES) { if (newAccepted == 1) { LogPrintf("CObfuscationPool::StatusUpdate - entry accepted! \n"); sessionFoundMasternode = true; //wait for other users. Masternode will report when ready UpdateState(POOL_STATUS_QUEUE); } else if (newAccepted == 0 && sessionID == 0 && !sessionFoundMasternode) { LogPrintf("CObfuscationPool::StatusUpdate - entry not accepted by Masternode \n"); UnlockCoins(); UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); DoAutomaticDenominating(); //try another Masternode } if (sessionFoundMasternode) return true; } return true; } // // After we receive the finalized transaction from the Masternode, we must // check it to make sure it's what we want, then sign it if we agree. // If we refuse to sign, it's possible we'll be charged collateral // bool CObfuscationPool::SignFinalTransaction(CTransaction& finalTransactionNew, CNode* node) { if (fMasterNode) return false; finalTransaction = finalTransactionNew; LogPrintf("CObfuscationPool::SignFinalTransaction %s", finalTransaction.ToString()); vector<CTxIn> sigs; //make sure my inputs/outputs are present, otherwise refuse to sign BOOST_FOREACH (const CObfuScationEntry e, entries) { BOOST_FOREACH (const CTxDSIn s, e.sev) { /* Sign my transaction and all outputs */ int mine = -1; CScript prevPubKey = CScript(); CTxIn vin = CTxIn(); for (unsigned int i = 0; i < finalTransaction.vin.size(); i++) { if (finalTransaction.vin[i] == s) { mine = i; prevPubKey = s.prevPubKey; vin = s; } } if (mine >= 0) { //might have to do this one input at a time? int foundOutputs = 0; CAmount nValue1 = 0; CAmount nValue2 = 0; for (unsigned int i = 0; i < finalTransaction.vout.size(); i++) { BOOST_FOREACH (const CTxOut& o, e.vout) { if (finalTransaction.vout[i] == o) { foundOutputs++; nValue1 += finalTransaction.vout[i].nValue; } } } BOOST_FOREACH (const CTxOut o, e.vout) nValue2 += o.nValue; int targetOuputs = e.vout.size(); if (foundOutputs < targetOuputs || nValue1 != nValue2) { // in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's // better then signing if the transaction doesn't look like what we wanted. LogPrintf("CObfuscationPool::Sign - My entries are not correct! Refusing to sign. %d entries %d target. \n", foundOutputs, targetOuputs); UnlockCoins(); SetNull(); return false; } const CKeyStore& keystore = *pwalletMain; LogPrint("obfuscation", "CObfuscationPool::Sign - Signing my input %i\n", mine); if (!SignSignature(keystore, prevPubKey, finalTransaction, mine, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { // changes scriptSig LogPrint("obfuscation", "CObfuscationPool::Sign - Unable to sign my own transaction! \n"); // not sure what to do here, it will timeout...? } sigs.push_back(finalTransaction.vin[mine]); LogPrint("obfuscation", " -- dss %d %d %s\n", mine, (int)sigs.size(), finalTransaction.vin[mine].scriptSig.ToString()); } } LogPrint("obfuscation", "CObfuscationPool::Sign - txNew:\n%s", finalTransaction.ToString()); } // push all of our signatures to the Masternode if (sigs.size() > 0 && node != NULL) node->PushMessage("dss", sigs); return true; } void CObfuscationPool::NewBlock() { LogPrint("obfuscation", "CObfuscationPool::NewBlock \n"); //we we're processing lots of blocks, we'll just leave if (GetTime() - lastNewBlock < 10) return; lastNewBlock = GetTime(); obfuScationPool.CheckTimeout(); } // Obfuscation transaction was completed (failed or successful) void CObfuscationPool::CompletedTransaction(bool error, int errorID) { if (fMasterNode) return; if (error) { LogPrintf("CompletedTransaction -- error \n"); UpdateState(POOL_STATUS_ERROR); Check(); UnlockCoins(); SetNull(); } else { LogPrintf("CompletedTransaction -- success \n"); UpdateState(POOL_STATUS_SUCCESS); UnlockCoins(); SetNull(); // To avoid race conditions, we'll only let DS run once per block cachedLastSuccess = chainActive.Tip()->nHeight; } lastMessage = GetMessageByID(errorID); } void CObfuscationPool::ClearLastMessage() { lastMessage = ""; } // // Passively run Obfuscation in the background to anonymize funds based on the given configuration. // // This does NOT run by default for daemons, only for QT. // bool CObfuscationPool::DoAutomaticDenominating(bool fDryRun) { return false; // Disabled until Obfuscation is completely removed if (!fEnableZeromint) return false; if (fMasterNode) return false; if (state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) return false; if (GetEntriesCount() > 0) { strAutoDenomResult = _("Mixing in progress..."); return false; } TRY_LOCK(cs_obfuscation, lockDS); if (!lockDS) { strAutoDenomResult = _("Lock is already in place."); return false; } if (!masternodeSync.IsBlockchainSynced()) { strAutoDenomResult = _("Can't mix while sync in progress."); return false; } if (!fDryRun && pwalletMain->IsLocked()) { strAutoDenomResult = _("Wallet is locked."); return false; } if (chainActive.Tip()->nHeight - cachedLastSuccess < minBlockSpacing) { LogPrintf("CObfuscationPool::DoAutomaticDenominating - Last successful Obfuscation action was too recent\n"); strAutoDenomResult = _("Last successful Obfuscation action was too recent."); return false; } if (mnodeman.size() == 0) { LogPrint("obfuscation", "CObfuscationPool::DoAutomaticDenominating - No Masternodes detected\n"); strAutoDenomResult = _("No Masternodes detected."); return false; } // ** find the coins we'll use std::vector<CTxIn> vCoins; CAmount nValueMin = CENT; CAmount nValueIn = 0; CAmount nOnlyDenominatedBalance; CAmount nBalanceNeedsDenominated; // should not be less than fees in OBFUSCATION_COLLATERAL + few (lets say 5) smallest denoms CAmount nLowestDenom = OBFUSCATION_COLLATERAL + obfuScationDenominations[obfuScationDenominations.size() - 1] * 5; // if there are no OBF collateral inputs yet if (!pwalletMain->HasCollateralInputs()) // should have some additional amount for them nLowestDenom += OBFUSCATION_COLLATERAL * 4; CAmount nBalanceNeedsAnonymized = nAnonymizeIngenuityAmount * COIN - pwalletMain->GetAnonymizedBalance(); // if balanceNeedsAnonymized is more than pool max, take the pool max if (nBalanceNeedsAnonymized > OBFUSCATION_POOL_MAX) nBalanceNeedsAnonymized = OBFUSCATION_POOL_MAX; // if balanceNeedsAnonymized is more than non-anonymized, take non-anonymized CAmount nAnonymizableBalance = pwalletMain->GetAnonymizableBalance(); if (nBalanceNeedsAnonymized > nAnonymizableBalance) nBalanceNeedsAnonymized = nAnonymizableBalance; if (nBalanceNeedsAnonymized < nLowestDenom) { LogPrintf("DoAutomaticDenominating : No funds detected in need of denominating \n"); strAutoDenomResult = _("No funds detected in need of denominating."); return false; } LogPrint("obfuscation", "DoAutomaticDenominating : nLowestDenom=%d, nBalanceNeedsAnonymized=%d\n", nLowestDenom, nBalanceNeedsAnonymized); // select coins that should be given to the pool if (!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vCoins, nValueIn, 0, nZeromintPercentage)) { nValueIn = 0; vCoins.clear(); if (pwalletMain->SelectCoinsDark(nValueMin, 9999999 * COIN, vCoins, nValueIn, -2, 0)) { nOnlyDenominatedBalance = pwalletMain->GetDenominatedBalance(true) + pwalletMain->GetDenominatedBalance() - pwalletMain->GetAnonymizedBalance(); nBalanceNeedsDenominated = nBalanceNeedsAnonymized - nOnlyDenominatedBalance; if (nBalanceNeedsDenominated > nValueIn) nBalanceNeedsDenominated = nValueIn; if (nBalanceNeedsDenominated < nLowestDenom) return false; // most likely we just waiting for denoms to confirm if (!fDryRun) return CreateDenominated(nBalanceNeedsDenominated); return true; } else { LogPrintf("DoAutomaticDenominating : Can't denominate - no compatible inputs left\n"); strAutoDenomResult = _("Can't denominate: no compatible inputs left."); return false; } } if (fDryRun) return true; nOnlyDenominatedBalance = pwalletMain->GetDenominatedBalance(true) + pwalletMain->GetDenominatedBalance() - pwalletMain->GetAnonymizedBalance(); nBalanceNeedsDenominated = nBalanceNeedsAnonymized - nOnlyDenominatedBalance; //check if we have should create more denominated inputs if (nBalanceNeedsDenominated > nOnlyDenominatedBalance) return CreateDenominated(nBalanceNeedsDenominated); //check if we have the collateral sized inputs if (!pwalletMain->HasCollateralInputs()) return !pwalletMain->HasCollateralInputs(false) && MakeCollateralAmounts(); std::vector<CTxOut> vOut; // initial phase, find a Masternode if (!sessionFoundMasternode) { // Clean if there is anything left from previous session UnlockCoins(); SetNull(); int nUseQueue = rand() % 100; UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); if (pwalletMain->GetDenominatedBalance(true) > 0) { //get denominated unconfirmed inputs LogPrintf("DoAutomaticDenominating -- Found unconfirmed denominated outputs, will wait till they confirm to continue.\n"); strAutoDenomResult = _("Found unconfirmed denominated outputs, will wait till they confirm to continue."); return false; } //check our collateral nad create new if needed std::string strReason; CValidationState state; if (txCollateral == CMutableTransaction()) { if (!pwalletMain->CreateCollateralTransaction(txCollateral, strReason)) { LogPrintf("% -- create collateral error:%s\n", __func__, strReason); return false; } } else { if (!IsCollateralValid(txCollateral)) { LogPrintf("%s -- invalid collateral, recreating...\n", __func__); if (!pwalletMain->CreateCollateralTransaction(txCollateral, strReason)) { LogPrintf("%s -- create collateral error: %s\n", __func__, strReason); return false; } } } //if we've used 90% of the Masternode list then drop all the oldest first int nThreshold = (int)(mnodeman.CountEnabled(ActiveProtocol()) * 0.9); LogPrint("obfuscation", "Checking vecMasternodesUsed size %d threshold %d\n", (int)vecMasternodesUsed.size(), nThreshold); while ((int)vecMasternodesUsed.size() > nThreshold) { vecMasternodesUsed.erase(vecMasternodesUsed.begin()); LogPrint("obfuscation", " vecMasternodesUsed size %d threshold %d\n", (int)vecMasternodesUsed.size(), nThreshold); } //don't use the queues all of the time for mixing if (nUseQueue > 33) { // Look through the queues and see if anything matches BOOST_FOREACH (CObfuscationQueue& dsq, vecObfuscationQueue) { CService addr; if (dsq.time == 0) continue; if (!dsq.GetAddress(addr)) continue; if (dsq.IsExpired()) continue; int protocolVersion; if (!dsq.GetProtocolVersion(protocolVersion)) continue; if (protocolVersion < ActiveProtocol()) continue; //non-denom's are incompatible if ((dsq.nDenom & (1 << 4))) continue; bool fUsed = false; //don't reuse Masternodes BOOST_FOREACH (CTxIn usedVin, vecMasternodesUsed) { if (dsq.vin == usedVin) { fUsed = true; break; } } if (fUsed) continue; std::vector<CTxIn> vTempCoins; std::vector<COutput> vTempCoins2; // Try to match their denominations if possible if (!pwalletMain->SelectCoinsByDenominations(dsq.nDenom, nValueMin, nBalanceNeedsAnonymized, vTempCoins, vTempCoins2, nValueIn, 0, nZeromintPercentage)) { LogPrintf("DoAutomaticDenominating --- Couldn't match denominations %d\n", dsq.nDenom); continue; } CMasternode* pmn = mnodeman.Find(dsq.vin); if (pmn == NULL) { LogPrintf("DoAutomaticDenominating --- dsq vin %s is not in masternode list!", dsq.vin.ToString()); continue; } LogPrintf("DoAutomaticDenominating --- attempt to connect to masternode from queue %s\n", pmn->addr.ToString()); lastTimeChanged = GetTimeMillis(); // connect to Masternode and submit the queue request CNode* pnode = ConnectNode((CAddress)addr, NULL, true); if (pnode != NULL) { pSubmittedToMasternode = pmn; vecMasternodesUsed.push_back(dsq.vin); sessionDenom = dsq.nDenom; pnode->PushMessage("dsa", sessionDenom, txCollateral); LogPrintf("DoAutomaticDenominating --- connected (from queue), sending dsa for %d - %s\n", sessionDenom, pnode->addr.ToString()); strAutoDenomResult = _("Mixing in progress..."); dsq.time = 0; //remove node return true; } else { LogPrintf("DoAutomaticDenominating --- error connecting \n"); strAutoDenomResult = _("Error connecting to Masternode."); dsq.time = 0; //remove node continue; } } } // do not initiate queue if we are a liquidity proveder to avoid useless inter-mixing if (nLiquidityProvider) return false; int i = 0; // otherwise, try one randomly while (i < 10) { CMasternode* pmn = mnodeman.FindRandomNotInVec(vecMasternodesUsed, ActiveProtocol()); if (pmn == NULL) { LogPrintf("DoAutomaticDenominating --- Can't find random masternode!\n"); strAutoDenomResult = _("Can't find random Masternode."); return false; } if (pmn->nLastDsq != 0 && pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) / 5 > mnodeman.nDsqCount) { i++; continue; } lastTimeChanged = GetTimeMillis(); LogPrintf("DoAutomaticDenominating --- attempt %d connection to Masternode %s\n", i, pmn->addr.ToString()); CNode* pnode = ConnectNode((CAddress)pmn->addr, NULL, true); if (pnode != NULL) { pSubmittedToMasternode = pmn; vecMasternodesUsed.push_back(pmn->vin); std::vector<CAmount> vecAmounts; pwalletMain->ConvertList(vCoins, vecAmounts); // try to get a single random denom out of vecAmounts while (sessionDenom == 0) sessionDenom = GetDenominationsByAmounts(vecAmounts); pnode->PushMessage("dsa", sessionDenom, txCollateral); LogPrintf("DoAutomaticDenominating --- connected, sending dsa for %d\n", sessionDenom); strAutoDenomResult = _("Mixing in progress..."); return true; } else { vecMasternodesUsed.push_back(pmn->vin); // postpone MN we wasn't able to connect to i++; continue; } } strAutoDenomResult = _("No compatible Masternode found."); return false; } strAutoDenomResult = _("Mixing in progress..."); return false; } bool CObfuscationPool::PrepareObfuscationDenominate() { std::string strError = ""; // Submit transaction to the pool if we get here // Try to use only inputs with the same number of rounds starting from lowest number of rounds possible for (int i = 0; i < nZeromintPercentage; i++) { strError = pwalletMain->PrepareObfuscationDenominate(i, i + 1); LogPrintf("DoAutomaticDenominating : Running Obfuscation denominate for %d rounds. Return '%s'\n", i, strError); if (strError == "") return true; } // We failed? That's strange but let's just make final attempt and try to mix everything strError = pwalletMain->PrepareObfuscationDenominate(0, nZeromintPercentage); LogPrintf("DoAutomaticDenominating : Running Obfuscation denominate for all rounds. Return '%s'\n", strError); if (strError == "") return true; // Should never actually get here but just in case strAutoDenomResult = strError; LogPrintf("DoAutomaticDenominating : Error running denominate, %s\n", strError); return false; } bool CObfuscationPool::SendRandomPaymentToSelf() { int64_t nBalance = pwalletMain->GetBalance(); int64_t nPayment = (nBalance * 0.35) + (rand() % nBalance); if (nPayment > nBalance) nPayment = nBalance - (0.1 * COIN); // make our change address CReserveKey reservekey(pwalletMain); CScript scriptChange; CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); CWalletTx wtx; CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; // ****** Add fees ************ / vecSend.push_back(make_pair(scriptChange, nPayment)); CCoinControl* coinControl = NULL; bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekey, nFeeRet, strFail, coinControl, ONLY_DENOMINATED); if (!success) { LogPrintf("SendRandomPaymentToSelf: Error - %s\n", strFail); return false; } pwalletMain->CommitTransaction(wtx, reservekey); LogPrintf("SendRandomPaymentToSelf Success: tx %s\n", wtx.GetHash().GetHex()); return true; } // Split up large inputs or create fee sized inputs bool CObfuscationPool::MakeCollateralAmounts() { CWalletTx wtx; CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; CCoinControl coinControl; coinControl.fAllowOtherInputs = false; coinControl.fAllowWatchOnly = false; // make our collateral address CReserveKey reservekeyCollateral(pwalletMain); // make our change address CReserveKey reservekeyChange(pwalletMain); CScript scriptCollateral; CPubKey vchPubKey; assert(reservekeyCollateral.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptCollateral = GetScriptForDestination(vchPubKey.GetID()); vecSend.push_back(make_pair(scriptCollateral, OBFUSCATION_COLLATERAL * 4)); // try to use non-denominated and not mn-like funds bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, strFail, &coinControl, ONLY_NONDENOMINATED_NOT10000IFMN); if (!success) { // if we failed (most likeky not enough funds), try to use all coins instead - // MN-like funds should not be touched in any case and we can't mix denominated without collaterals anyway CCoinControl* coinControlNull = NULL; LogPrintf("MakeCollateralAmounts: ONLY_NONDENOMINATED_NOT10000IFMN Error - %s\n", strFail); success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, strFail, coinControlNull, ONLY_NOT10000IFMN); if (!success) { LogPrintf("MakeCollateralAmounts: ONLY_NOT10000IFMN Error - %s\n", strFail); reservekeyCollateral.ReturnKey(); return false; } } reservekeyCollateral.KeepKey(); LogPrintf("MakeCollateralAmounts: tx %s\n", wtx.GetHash().GetHex()); // use the same cachedLastSuccess as for DS mixinx to prevent race if (!pwalletMain->CommitTransaction(wtx, reservekeyChange)) { LogPrintf("MakeCollateralAmounts: CommitTransaction failed!\n"); return false; } cachedLastSuccess = chainActive.Tip()->nHeight; return true; } // Create denominations bool CObfuscationPool::CreateDenominated(CAmount nTotalValue) { CWalletTx wtx; CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; CAmount nValueLeft = nTotalValue; // make our collateral address CReserveKey reservekeyCollateral(pwalletMain); // make our change address CReserveKey reservekeyChange(pwalletMain); // make our denom addresses CReserveKey reservekeyDenom(pwalletMain); CScript scriptCollateral; CPubKey vchPubKey; assert(reservekeyCollateral.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptCollateral = GetScriptForDestination(vchPubKey.GetID()); // ****** Add collateral outputs ************ / if (!pwalletMain->HasCollateralInputs()) { vecSend.push_back(make_pair(scriptCollateral, OBFUSCATION_COLLATERAL * 4)); nValueLeft -= OBFUSCATION_COLLATERAL * 4; } // ****** Add denoms ************ / BOOST_REVERSE_FOREACH (CAmount v, obfuScationDenominations) { int nOutputs = 0; // add each output up to 10 times until it can't be added again while (nValueLeft - v >= OBFUSCATION_COLLATERAL && nOutputs <= 10) { CScript scriptDenom; CPubKey vchPubKey; //use a unique change address assert(reservekeyDenom.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptDenom = GetScriptForDestination(vchPubKey.GetID()); // TODO: do not keep reservekeyDenom here reservekeyDenom.KeepKey(); vecSend.push_back(make_pair(scriptDenom, v)); //increment outputs and subtract denomination amount nOutputs++; nValueLeft -= v; LogPrintf("CreateDenominated1 %d\n", nValueLeft); } if (nValueLeft == 0) break; } LogPrintf("CreateDenominated2 %d\n", nValueLeft); // if we have anything left over, it will be automatically send back as change - there is no need to send it manually CCoinControl* coinControl = NULL; bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, strFail, coinControl, ONLY_NONDENOMINATED_NOT10000IFMN); if (!success) { LogPrintf("CreateDenominated: Error - %s\n", strFail); // TODO: return reservekeyDenom here reservekeyCollateral.ReturnKey(); return false; } // TODO: keep reservekeyDenom here reservekeyCollateral.KeepKey(); // use the same cachedLastSuccess as for DS mixinx to prevent race if (pwalletMain->CommitTransaction(wtx, reservekeyChange)) cachedLastSuccess = chainActive.Tip()->nHeight; else LogPrintf("CreateDenominated: CommitTransaction failed!\n"); LogPrintf("CreateDenominated: tx %s\n", wtx.GetHash().GetHex()); return true; } bool CObfuscationPool::IsCompatibleWithEntries(std::vector<CTxOut>& vout) { if (GetDenominations(vout) == 0) return false; BOOST_FOREACH (const CObfuScationEntry v, entries) { LogPrintf(" IsCompatibleWithEntries %d %d\n", GetDenominations(vout), GetDenominations(v.vout)); /* BOOST_FOREACH(CTxOut o1, vout) LogPrintf(" vout 1 - %s\n", o1.ToString()); BOOST_FOREACH(CTxOut o2, v.vout) LogPrintf(" vout 2 - %s\n", o2.ToString()); */ if (GetDenominations(vout) != GetDenominations(v.vout)) return false; } return true; } bool CObfuscationPool::IsCompatibleWithSession(int64_t nDenom, CTransaction txCollateral, int& errorID) { if (nDenom == 0) return false; LogPrintf("CObfuscationPool::IsCompatibleWithSession - sessionDenom %d sessionUsers %d\n", sessionDenom, sessionUsers); if (!unitTest && !IsCollateralValid(txCollateral)) { LogPrint("obfuscation", "CObfuscationPool::IsCompatibleWithSession - collateral not valid!\n"); errorID = ERR_INVALID_COLLATERAL; return false; } if (sessionUsers < 0) sessionUsers = 0; if (sessionUsers == 0) { sessionID = 1 + (rand() % 999999); sessionDenom = nDenom; sessionUsers++; lastTimeChanged = GetTimeMillis(); if (!unitTest) { //broadcast that I'm accepting entries, only if it's the first entry through CObfuscationQueue dsq; dsq.nDenom = nDenom; dsq.vin = activeMasternode.vin; dsq.time = GetTime(); dsq.Sign(); dsq.Relay(); } UpdateState(POOL_STATUS_QUEUE); vecSessionCollateral.push_back(txCollateral); return true; } if ((state != POOL_STATUS_ACCEPTING_ENTRIES && state != POOL_STATUS_QUEUE) || sessionUsers >= GetMaxPoolTransactions()) { if ((state != POOL_STATUS_ACCEPTING_ENTRIES && state != POOL_STATUS_QUEUE)) errorID = ERR_MODE; if (sessionUsers >= GetMaxPoolTransactions()) errorID = ERR_QUEUE_FULL; LogPrintf("CObfuscationPool::IsCompatibleWithSession - incompatible mode, return false %d %d\n", state != POOL_STATUS_ACCEPTING_ENTRIES, sessionUsers >= GetMaxPoolTransactions()); return false; } if (nDenom != sessionDenom) { errorID = ERR_DENOM; return false; } LogPrintf("CObfuScationPool::IsCompatibleWithSession - compatible\n"); sessionUsers++; lastTimeChanged = GetTimeMillis(); vecSessionCollateral.push_back(txCollateral); return true; } //create a nice string to show the denominations void CObfuscationPool::GetDenominationsToString(int nDenom, std::string& strDenom) { // Function returns as follows: // // bit 0 - 100INGY+1 ( bit on if present ) // bit 1 - 10INGY+1 // bit 2 - 1INGY+1 // bit 3 - .1INGY+1 // bit 3 - non-denom strDenom = ""; if (nDenom & (1 << 0)) { if (strDenom.size() > 0) strDenom += "+"; strDenom += "100"; } if (nDenom & (1 << 1)) { if (strDenom.size() > 0) strDenom += "+"; strDenom += "10"; } if (nDenom & (1 << 2)) { if (strDenom.size() > 0) strDenom += "+"; strDenom += "1"; } if (nDenom & (1 << 3)) { if (strDenom.size() > 0) strDenom += "+"; strDenom += "0.1"; } } int CObfuscationPool::GetDenominations(const std::vector<CTxDSOut>& vout) { std::vector<CTxOut> vout2; BOOST_FOREACH (CTxDSOut out, vout) vout2.push_back(out); return GetDenominations(vout2); } // return a bitshifted integer representing the denominations in this list int CObfuscationPool::GetDenominations(const std::vector<CTxOut>& vout, bool fSingleRandomDenom) { std::vector<pair<int64_t, int> > denomUsed; // make a list of denominations, with zero uses BOOST_FOREACH (int64_t d, obfuScationDenominations) denomUsed.push_back(make_pair(d, 0)); // look for denominations and update uses to 1 BOOST_FOREACH (CTxOut out, vout) { bool found = false; BOOST_FOREACH (PAIRTYPE(int64_t, int) & s, denomUsed) { if (out.nValue == s.first) { s.second = 1; found = true; } } if (!found) return 0; } int denom = 0; int c = 0; // if the denomination is used, shift the bit on. // then move to the next BOOST_FOREACH (PAIRTYPE(int64_t, int) & s, denomUsed) { int bit = (fSingleRandomDenom ? rand() % 2 : 1) * s.second; denom |= bit << c++; if (fSingleRandomDenom && bit) break; // use just one random denomination } // Function returns as follows: // // bit 0 - 100INGY+1 ( bit on if present ) // bit 1 - 10INGY+1 // bit 2 - 1INGY+1 // bit 3 - .1INGY+1 return denom; } int CObfuscationPool::GetDenominationsByAmounts(std::vector<CAmount>& vecAmount) { CScript e = CScript(); std::vector<CTxOut> vout1; // Make outputs by looping through denominations, from small to large BOOST_REVERSE_FOREACH (CAmount v, vecAmount) { CTxOut o(v, e); vout1.push_back(o); } return GetDenominations(vout1, true); } int CObfuscationPool::GetDenominationsByAmount(CAmount nAmount, int nDenomTarget) { CScript e = CScript(); CAmount nValueLeft = nAmount; std::vector<CTxOut> vout1; // Make outputs by looping through denominations, from small to large BOOST_REVERSE_FOREACH (CAmount v, obfuScationDenominations) { if (nDenomTarget != 0) { bool fAccepted = false; if ((nDenomTarget & (1 << 0)) && v == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((nDenomTarget & (1 << 1)) && v == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((nDenomTarget & (1 << 2)) && v == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((nDenomTarget & (1 << 3)) && v == ((.1 * COIN) + 100)) { fAccepted = true; } if (!fAccepted) continue; } int nOutputs = 0; // add each output up to 10 times until it can't be added again while (nValueLeft - v >= 0 && nOutputs <= 10) { CTxOut o(v, e); vout1.push_back(o); nValueLeft -= v; nOutputs++; } LogPrintf("GetDenominationsByAmount --- %d nOutputs %d\n", v, nOutputs); } return GetDenominations(vout1); } std::string CObfuscationPool::GetMessageByID(int messageID) { switch (messageID) { case ERR_ALREADY_HAVE: return _("Already have that input."); case ERR_DENOM: return _("No matching denominations found for mixing."); case ERR_ENTRIES_FULL: return _("Entries are full."); case ERR_EXISTING_TX: return _("Not compatible with existing transactions."); case ERR_FEES: return _("Transaction fees are too high."); case ERR_INVALID_COLLATERAL: return _("Collateral not valid."); case ERR_INVALID_INPUT: return _("Input is not valid."); case ERR_INVALID_SCRIPT: return _("Invalid script detected."); case ERR_INVALID_TX: return _("Transaction not valid."); case ERR_MAXIMUM: return _("Value more than Obfuscation pool maximum allows."); case ERR_MN_LIST: return _("Not in the Masternode list."); case ERR_MODE: return _("Incompatible mode."); case ERR_NON_STANDARD_PUBKEY: return _("Non-standard public key detected."); case ERR_NOT_A_MN: return _("This is not a Masternode."); case ERR_QUEUE_FULL: return _("Masternode queue is full."); case ERR_RECENT: return _("Last Obfuscation was too recent."); case ERR_SESSION: return _("Session not complete!"); case ERR_MISSING_TX: return _("Missing input transaction information."); case ERR_VERSION: return _("Incompatible version."); case MSG_SUCCESS: return _("Transaction created successfully."); case MSG_ENTRIES_ADDED: return _("Your entries added successfully."); case MSG_NOERR: default: return ""; } } bool CObfuScationSigner::IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey) { CScript payee2; payee2 = GetScriptForDestination(pubkey.GetID()); CTransaction txVin; uint256 hash; if (GetTransaction(vin.prevout.hash, txVin, hash, true)) { BOOST_FOREACH (CTxOut out, txVin.vout) { if (out.nValue == 1000 * COIN) { if (out.scriptPubKey == payee2) return true; } } } return false; } bool CObfuScationSigner::SetKey(std::string strSecret, std::string& errorMessage, CKey& key, CPubKey& pubkey) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) { errorMessage = _("Invalid private key."); return false; } key = vchSecret.GetKey(); pubkey = key.GetPubKey(); return true; } bool CObfuScationSigner::GetKeysFromSecret(std::string strSecret, CKey& keyRet, CPubKey& pubkeyRet) { CBitcoinSecret vchSecret; if (!vchSecret.SetString(strSecret)) return false; keyRet = vchSecret.GetKey(); pubkeyRet = keyRet.GetPubKey(); return true; } bool CObfuScationSigner::SignMessage(std::string strMessage, std::string& errorMessage, vector<unsigned char>& vchSig, CKey key) { CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; if (!key.SignCompact(ss.GetHash(), vchSig)) { errorMessage = _("Signing failed."); return false; } return true; } bool CObfuScationSigner::VerifyMessage(CPubKey pubkey, vector<unsigned char>& vchSig, std::string strMessage, std::string& errorMessage) { CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey2; if (!pubkey2.RecoverCompact(ss.GetHash(), vchSig)) { errorMessage = _("Error recovering public key."); return false; } if (fDebug && pubkey2.GetID() != pubkey.GetID()) LogPrintf("CObfuScationSigner::VerifyMessage -- keys don't match: %s %s\n", pubkey2.GetID().ToString(), pubkey.GetID().ToString()); return (pubkey2.GetID() == pubkey.GetID()); } bool CObfuscationQueue::Sign() { if (!fMasterNode) return false; std::string strMessage = vin.ToString() + boost::lexical_cast<std::string>(nDenom) + boost::lexical_cast<std::string>(time) + boost::lexical_cast<std::string>(ready); CKey key2; CPubKey pubkey2; std::string errorMessage = ""; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, key2, pubkey2)) { LogPrintf("CObfuscationQueue():Relay - ERROR: Invalid Masternodeprivkey: '%s'\n", errorMessage); return false; } if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, key2)) { LogPrintf("CObfuscationQueue():Relay - Sign message failed"); return false; } if (!obfuScationSigner.VerifyMessage(pubkey2, vchSig, strMessage, errorMessage)) { LogPrintf("CObfuscationQueue():Relay - Verify message failed"); return false; } return true; } bool CObfuscationQueue::Relay() { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { // always relay to everyone pnode->PushMessage("dsq", (*this)); } return true; } bool CObfuscationQueue::CheckSignature() { CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { std::string strMessage = vin.ToString() + boost::lexical_cast<std::string>(nDenom) + boost::lexical_cast<std::string>(time) + boost::lexical_cast<std::string>(ready); std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { return error("CObfuscationQueue::CheckSignature() - Got bad Masternode address signature %s \n", vin.ToString().c_str()); } return true; } return false; } void CObfuscationPool::RelayFinalTransaction(const int sessionID, const CTransaction& txNew) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { pnode->PushMessage("dsf", sessionID, txNew); } } void CObfuscationPool::RelayIn(const std::vector<CTxDSIn>& vin, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxDSOut>& vout) { if (!pSubmittedToMasternode) return; std::vector<CTxIn> vin2; std::vector<CTxOut> vout2; BOOST_FOREACH (CTxDSIn in, vin) vin2.push_back(in); BOOST_FOREACH (CTxDSOut out, vout) vout2.push_back(out); CNode* pnode = FindNode(pSubmittedToMasternode->addr); if (pnode != NULL) { LogPrintf("RelayIn - found master, relaying message - %s \n", pnode->addr.ToString()); pnode->PushMessage("dsi", vin2, nAmount, txCollateral, vout2); } } void CObfuscationPool::RelayStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const int errorID) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) pnode->PushMessage("dssu", sessionID, newState, newEntriesCount, newAccepted, errorID); } void CObfuscationPool::RelayCompletedTransaction(const int sessionID, const bool error, const int errorID) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) pnode->PushMessage("dsc", sessionID, error, errorID); } //TODO: Rename/move to core void ThreadCheckObfuScationPool() { if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality // Make this thread recognisable as the wallet flushing thread RenameThread("ingenuity-obfuscation"); unsigned int c = 0; while (true) { MilliSleep(1000); //LogPrintf("ThreadCheckObfuScationPool::check timeout\n"); // try to sync from all available nodes, one step at a time masternodeSync.Process(); if (masternodeSync.IsBlockchainSynced()) { c++; // check if we should activate or ping every few minutes, // start right after sync is considered to be done if (c % MASTERNODE_PING_SECONDS == 1) activeMasternode.ManageStatus(); if (c % 60 == 0) { mnodeman.CheckAndRemove(); mnodeman.ProcessMasternodeConnections(); masternodePayments.CleanPaymentList(); CleanTransactionLocksList(); } //if(c % MASTERNODES_DUMP_SECONDS == 0) DumpMasternodes(); obfuScationPool.CheckTimeout(); obfuScationPool.CheckForCompleteQueue(); if (obfuScationPool.GetState() == POOL_STATUS_IDLE && c % 15 == 0) { obfuScationPool.DoAutomaticDenominating(); } } } }
[ "44764450+IngenuityCoin@users.noreply.github.com" ]
44764450+IngenuityCoin@users.noreply.github.com
a2a30f34b4a5ac5aaf25797d4426412c75473700
f44abd1e2a3da5b523a9ed061315edef9ddabf30
/example/aes.hpp
b55837b651089c33f6e76c8935ad03c1a6c90590
[]
no_license
nikita-veshchikov/silk
9624ebb8f327a54c0612309637c0ab69cbc5ccc0
67e9af4455ea59875510efe37515725cd0119c94
refs/heads/master
2020-12-30T15:43:14.966020
2017-05-13T13:13:27
2017-05-13T13:13:27
91,174,388
6
0
null
null
null
null
UTF-8
C++
false
false
5,095
hpp
// constants, aes sbox, function declarations for AES #ifndef __AES_HPP__ #define __AES_HPP__ #include <iostream> #include <stdio.h> #include <stdint.h> #include "../silk/silk.hpp" using namespace std; //128 bit AES #define Nrows 4 #define Ncols 4 #define Nr 10 const U8 sBox[] = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16}; const U8 mCM2[] = { 0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e,0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e, 0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e,0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e, 0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e,0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e, 0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e,0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e, 0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e,0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e, 0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae,0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe, 0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce,0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde, 0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee,0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe, 0x1b,0x19,0x1f,0x1d,0x13,0x11,0x17,0x15,0x0b,0x09,0x0f,0x0d,0x03,0x01,0x07,0x05, 0x3b,0x39,0x3f,0x3d,0x33,0x31,0x37,0x35,0x2b,0x29,0x2f,0x2d,0x23,0x21,0x27,0x25, 0x5b,0x59,0x5f,0x5d,0x53,0x51,0x57,0x55,0x4b,0x49,0x4f,0x4d,0x43,0x41,0x47,0x45, 0x7b,0x79,0x7f,0x7d,0x73,0x71,0x77,0x75,0x6b,0x69,0x6f,0x6d,0x63,0x61,0x67,0x65, 0x9b,0x99,0x9f,0x9d,0x93,0x91,0x97,0x95,0x8b,0x89,0x8f,0x8d,0x83,0x81,0x87,0x85, 0xbb,0xb9,0xbf,0xbd,0xb3,0xb1,0xb7,0xb5,0xab,0xa9,0xaf,0xad,0xa3,0xa1,0xa7,0xa5, 0xdb,0xd9,0xdf,0xdd,0xd3,0xd1,0xd7,0xd5,0xcb,0xc9,0xcf,0xcd,0xc3,0xc1,0xc7,0xc5, 0xfb,0xf9,0xff,0xfd,0xf3,0xf1,0xf7,0xf5,0xeb,0xe9,0xef,0xed,0xe3,0xe1,0xe7,0xe5}; const U8 mCM3[] = { 0x00,0x03,0x06,0x05,0x0c,0x0f,0x0a,0x09,0x18,0x1b,0x1e,0x1d,0x14,0x17,0x12,0x11, 0x30,0x33,0x36,0x35,0x3c,0x3f,0x3a,0x39,0x28,0x2b,0x2e,0x2d,0x24,0x27,0x22,0x21, 0x60,0x63,0x66,0x65,0x6c,0x6f,0x6a,0x69,0x78,0x7b,0x7e,0x7d,0x74,0x77,0x72,0x71, 0x50,0x53,0x56,0x55,0x5c,0x5f,0x5a,0x59,0x48,0x4b,0x4e,0x4d,0x44,0x47,0x42,0x41, 0xc0,0xc3,0xc6,0xc5,0xcc,0xcf,0xca,0xc9,0xd8,0xdb,0xde,0xdd,0xd4,0xd7,0xd2,0xd1, 0xf0,0xf3,0xf6,0xf5,0xfc,0xff,0xfa,0xf9,0xe8,0xeb,0xee,0xed,0xe4,0xe7,0xe2,0xe1, 0xa0,0xa3,0xa6,0xa5,0xac,0xaf,0xaa,0xa9,0xb8,0xbb,0xbe,0xbd,0xb4,0xb7,0xb2,0xb1, 0x90,0x93,0x96,0x95,0x9c,0x9f,0x9a,0x99,0x88,0x8b,0x8e,0x8d,0x84,0x87,0x82,0x81, 0x9b,0x98,0x9d,0x9e,0x97,0x94,0x91,0x92,0x83,0x80,0x85,0x86,0x8f,0x8c,0x89,0x8a, 0xab,0xa8,0xad,0xae,0xa7,0xa4,0xa1,0xa2,0xb3,0xb0,0xb5,0xb6,0xbf,0xbc,0xb9,0xba, 0xfb,0xf8,0xfd,0xfe,0xf7,0xf4,0xf1,0xf2,0xe3,0xe0,0xe5,0xe6,0xef,0xec,0xe9,0xea, 0xcb,0xc8,0xcd,0xce,0xc7,0xc4,0xc1,0xc2,0xd3,0xd0,0xd5,0xd6,0xdf,0xdc,0xd9,0xda, 0x5b,0x58,0x5d,0x5e,0x57,0x54,0x51,0x52,0x43,0x40,0x45,0x46,0x4f,0x4c,0x49,0x4a, 0x6b,0x68,0x6d,0x6e,0x67,0x64,0x61,0x62,0x73,0x70,0x75,0x76,0x7f,0x7c,0x79,0x7a, 0x3b,0x38,0x3d,0x3e,0x37,0x34,0x31,0x32,0x23,0x20,0x25,0x26,0x2f,0x2c,0x29,0x2a, 0x0b,0x08,0x0d,0x0e,0x07,0x04,0x01,0x02,0x13,0x10,0x15,0x16,0x1f,0x1c,0x19,0x1a }; void keyExpansion(U8 key [][Ncols], U8 w[][Ncols*(Nr+1)]); void subBytes(U8 state [][Ncols]); void shiftRows(U8 state [][Ncols]); void mixColumns(U8 state [][Ncols]); void addRoundKey(U8 state [][Ncols], U8 w [][Ncols * (Nr +1)]); void cipher(U8 state [Nrows][Ncols], U8 key [][Ncols]); void print(U8 state [Nrows][Ncols]); void printKey(U8 k [][Ncols * (Nr +1)]); #endif // __AES_HPP__
[ "veshchikov.nikita@gmail.com" ]
veshchikov.nikita@gmail.com
c3f7e2186f534a036bea3ffad355674d47d82a01
1b2a5c6c07814f265471a0c42019bdca2e352433
/数组_01/数组_01/test.cpp
d613f118a8109106c02e4eb6c2a030bbb8592ec8
[]
no_license
HotPot-J/algorithms
d83c11a58876830ea44e849c061884449ea3d5c2
ad4e55ca6529108738b72c3c3d49409d9a2b1bcb
refs/heads/master
2021-01-02T00:30:31.216442
2020-09-25T08:39:23
2020-09-25T08:39:23
239,411,304
0
0
null
null
null
null
GB18030
C++
false
false
1,183
cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> #include<vector> using namespace std; /*链接:https://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46 来源:牛客网 [编程题]构建乘积数组 热度指数:240898时间限制:C / C++ 1秒,其他语言2秒空间限制:C / C++ 32M,其他语言64M 算法知识视频讲解 给定一个数组A[0, 1, ..., n - 1], 请构建一个数组B[0, 1, ..., n - 1], 其中B中的元素B[i] = A[0] * A[1] * ...*A[i - 1] * A[i + 1] * ...*A[n - 1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * ... * A[n - 1],B[n - 1] = A[0] * A[1] * ... * A[n - 2]; ) 对于A长度为1的情况,B无意义,故而无法构建,因此该情况不会存在。 */ /* 思路:上下三角连乘,动态规划 f(i+1) = f(i-1)*A[i-1] */ class Solution { public: vector<int> multiply(const vector<int>& A) { int len = A.size(); vector<int> B; B.resize(len, 0); B[0] = 1; for (int i = 1; i<len; ++i){ B[i] = B[i - 1] * A[i - 1]; } int tmp = 1;//改tmp起到保留上一层乘积的作用 for (int i = len - 2; i >= 0; --i){ tmp *= A[i + 1]; B[i] *= tmp; } return B; } };
[ "807126916@qq.com" ]
807126916@qq.com
a95fb92db620ef3306119fad83c04ee5298b4ac8
067a54a335d900fbcb01c77205d1d45eb38fe7dd
/LightOJ/Number_Theory/.svn/text-base/1234.cxx.svn-base
4de9d9624a1d4b4f446a1cd7529575f11f26690f
[]
no_license
pallab-gain/LightOJ
997cf858d5af79f8de34fb8237a79e54f7f706f4
867186dcfcf9501797f8467c7ffa8cab87a7b197
refs/heads/master
2020-04-07T05:20:46.855100
2013-01-25T07:57:45
2013-01-25T07:57:45
3,844,699
2
1
null
null
null
null
UTF-8
C++
false
false
2,738
/* * Author : Pallab * Program : 1234 * * 2012-05-02 15:32:51 * I have not failed, I have just found 10000 ways that won't work. * */ #include <iostream> #include <algorithm> #include <vector> #include <sstream> #include <fstream> #include <string> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <functional> #include <bitset> #include <iomanip> #include <ctime> #include <cassert> #include <cstdio> #include <cmath> #include <cstring> #include <climits> #include <cstring> #include <cstdlib> using namespace std; #define foR(i1,st,ed) for(int i1 = st , j1 = ed ; i1 < j1 ; ++i1 ) #define fo(i1,ed) foR( i1 , 0 , ed ) #define foE(i1,st,ed) foR( i1, st, ed+1 ) #define foit(i, x) for (typeof((x).begin()) i = (x).begin(); i != (x).end(); i++) #define bip system("pause") #define Int long long #define pb push_back #define SZ(X) (int)(X).size() #define LN(X) (int)(X).length() #define mk make_pair #define SET( ARRAY , VALUE ) memset( ARRAY , VALUE , sizeof(ARRAY) ) #define line puts("") template<class T1> inline void debug(T1 _x) { cout<<_x<<'\n'; } template<class T1, class T2> inline void debug(T1 _x,T2 _y) { cout<<_x<<' '<<_y<<'\n'; } template<class T1, class T2, class T3> inline void debug(T1 _x,T2 _y,T3 _z) { cout<<_x<<' '<<_y<<' '<<_z<<'\n'; } template<class T1, class T2, class T3, class T4> inline void debug(T1 _x,T2 _y,T3 _z,T4 _zz) { cout<<_x<<' '<<_y<<' '<<_z<<' '<<_zz<<'\n'; } template< class T1> inline void debug(T1 _array,int _size) { cout<<"["; for (int i=0;i<_size;++i) { cout<<' '<<_array[i]; } puts(" ]"); } inline bool CI(int &_x) { return scanf("%d",&_x)==1; } inline bool CI(int &_x, int &_y) { return CI(_x)&&CI(_y) ; } inline bool CI(int &_x, int &_y, int &_z) { return CI(_x)&&CI(_y)&&CI(_z) ; } inline bool CI(int &_x, int &_y, int &_z, int &_zz) { return CI(_x)&&CI(_y)&&CI(_z)&&CI(_zz) ; } const double gammaa = 0.5772156649; const double Bn[] = {1.0/6.0, -1.0/30.0, 1.0/42.0, -1.0/30.0, 5.0/66.0}; //calculates n-th Harmonic number //Hn = 1 + 1/2 + 1/3 + ..... + 1/n inline double Hn(int n) { if (n <= 0) return 0; double r = 0; int i; if (n <= 1000) { for (i = 1; i <= n; i++) { r += (1.0/(double)i); } return r; } r = log(n) + gammaa + .5/n; for (i = 0; i < 5; i++) { r -= (Bn[i] / (2.0*(i+1)*pow(n,2*(i+1)))) ; } return r; } int n; inline void Read() { CI(n); } inline void Proc() { cout<<Hn(n); line; } int main() { cout<<setprecision(8)<<fixed; int tt; CI(tt); foE(i,1,tt) { Read(); cout<<"Case "<<i<<": "; Proc(); } return 0; }
[ "pallab.gain@gmail.com" ]
pallab.gain@gmail.com
68c0247db07cc9e9603ed5da09a0287c3306c1f5
c733fdee7235a7bb17177c95f3d6f5e203dd1fce
/autotests/roommodeltest.h
dc930abde0d5ca94847f196ad8084956cb6da0cb
[]
no_license
ruphy/ruqola
9d024708fd43162f6f8e94eddcd141fed03aeda6
6046eb7e2990a840e3f2dfba640df1adb524030b
refs/heads/master
2021-01-20T23:51:50.019501
2017-08-30T06:15:10
2017-08-30T06:15:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,232
h
/* Copyright (c) 2017 Montel Laurent <montel@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ROOMMODELTEST_H #define ROOMMODELTEST_H #include <QObject> class RoomModelTest : public QObject { Q_OBJECT public: explicit RoomModelTest(QObject *parent = nullptr); ~RoomModelTest() = default; private Q_SLOTS: void shouldSerialized(); }; #endif // ROOMMODELTEST_H
[ "montel@kde.org" ]
montel@kde.org
f55aac28922b64ab4bfbf6ac3131403b3492a46b
77589d6eb789a5208bedb49d8b2a3986a2071333
/Sliding window/Minimum Size Subarray Sum.cpp
198855fa8c88f642940eebec6a05effa01b655a5
[]
no_license
vishgoel007/Leetcode-problems
09904994c2f7287256094d4dd20c71ace648311d
2de3b703135ee5d43ca536be206ec6288c88c8ca
refs/heads/master
2023-03-05T10:57:43.774863
2021-02-20T21:25:32
2021-02-20T21:25:32
287,869,090
0
0
null
null
null
null
UTF-8
C++
false
false
1,718
cpp
// https://leetcode.com/problems/minimum-size-subarray-sum/ #include <iostream> #include <map> #include <queue> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; // sliding window O(n) class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int len = nums.size(); int start = 0, end = 0, res = len + 1, currSum = 0; while (start < len) { if (end < len && currSum < s) { currSum += nums[end]; end++; } else { currSum -= nums[start]; start++; } if (currSum >= s) res = min(res, end - start); } return res % (len + 1); } }; // above simplified (sliding window) O(n) class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int len = nums.size(); int start = 0, end = 0, res = len + 1, currSum = 0; while (end < len) { currSum += nums[end]; end++; while (currSum >= s) { res = min(res, end - start); currSum -= nums[start]; start++; } } return res % (len + 1); } }; // using binary search (nlogn) class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int len = nums.size(); vector<int> prefix(len + 1, 0); for (int i = 1; i <= len; i++) { prefix[i] = prefix[i - 1] + nums[i - 1]; } int res = len + 1; for (int i = 1; i <= len; i++) { int toFind = s + prefix[i - 1]; auto bound = lower_bound(prefix.begin(), prefix.end(), toFind); if (bound != prefix.end()) { int j = bound - prefix.begin(); res = min(res, j - (i - 1)); } } return res % (len + 1); } };
[ "vishal@wakencode.com" ]
vishal@wakencode.com
cc6a4752668611d8489d07b9c6160701be8c38b9
45e66980d15a06b264f31f9a7d6dcd6dc271b815
/src/fs.h
90b988e3311d6f03bb3015045aa7c6a46e6c0c81
[ "MIT" ]
permissive
Lucky1689/ukcoin
e3ff17c66c85f5531d81580e4bc84ff3994924af
11bcd6ded7b11a7179e32f1bf0d6f75615c0dde1
refs/heads/master
2022-09-20T17:25:14.553647
2020-06-03T18:08:17
2020-06-03T18:08:17
262,382,958
0
0
null
null
null
null
UTF-8
C++
false
false
821
h
// Copyright (c) 2017-2018 The Bitcoin Core developers // Copyright (c) 2017 The Raven Core developers // Copyright (c) 2018 The Rito Core developers // Copyright (c) 2020 The Ukcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef UKC_FS_H #define UKC_FS_H #include <stdio.h> #include <string> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/detail/utf8_codecvt_facet.hpp> /** Filesystem operations and types */ namespace fs = boost::filesystem; /** Bridge operations to C stdio */ namespace fsbridge { FILE *fopen(const fs::path& p, const char *mode); FILE *freopen(const fs::path& p, const char *mode, FILE *stream); }; #endif // UKC_FS_H
[ "Ukcoin168@gmail.com" ]
Ukcoin168@gmail.com
58271bb8fb904e385e532e3e74e0ecc73dbbf610
477f7dcdd775b0ae607251a415e1058b7d2be454
/include/arkanoid/model/LevelTextFile.hpp
2edd6ded7a6920038a863ad29c284e3ce53c3b57
[]
no_license
zwostein/arkanoid
4175d03386274607ab63808753160602b932277a
8f966b696593687a532afbdb0bbb1b950f76176b
refs/heads/master
2021-01-19T20:18:49.696288
2014-01-13T09:38:22
2014-01-13T09:38:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
327
hpp
#ifndef _ARKANOID_MODEL_LEVELTEXTFILE_INCLUDED_ #define _ARKANOID_MODEL_LEVELTEXTFILE_INCLUDED_ #include <string> namespace arkanoid { namespace model { class Level; class LevelTextFile { public: static Level * load( const std::string & fileName ); static bool save( const Level * level ); }; } } #endif
[ "provisorisch@online.de" ]
provisorisch@online.de
e66f2c0d7db0f2355a9d91232bed0f69c330f103
1598841acea56eaaee53026195ce07d8c9c253a4
/prewritten-code/templates/all_includes.hpp
89e77a0c0ce940a0f825477ad0ca1ddb84460a78
[]
no_license
PavelSavchenkov/competitive-programming
de9d3b14e8b7286d411946905bfb7586cb8c6db2
b3a41a809bf1b483b1cf76df0a83c96ff74a12d5
refs/heads/master
2021-06-25T09:47:12.403610
2019-06-30T08:09:07
2019-06-30T08:09:07
144,401,056
0
0
null
null
null
null
UTF-8
C++
false
false
449
hpp
#pragma once #include <cstdio> #include <iostream> #include <cmath> #include <utility> #include <memory> #include <memory.h> #include <cstdlib> #include <set> #include <map> #include <cassert> #include <bitset> #include <unordered_set> #include <unordered_map> #include <functional> #include <numeric> #include <algorithm> #include <complex> #include <vector> #include <random> #include <ctime> #include <ostream> #include <queue> #include <array>
[ "savchenkov@adorable.ai" ]
savchenkov@adorable.ai
763f760fd670e3ea4df066ebe4967b94c6845fba
0fab1998c78d0476845f3194202ba59c723777f1
/C++/snake/snake/Source.cpp
893a373248d3ca0166f13be5915dc6cea229a5da
[ "Apache-2.0" ]
permissive
PrinnyH/Small-Games
34c3e5685be909b0c5ca923220e2201be418bbc4
b8bdcac813af02412652e5e6e39348acebe4a451
refs/heads/main
2023-01-13T09:52:24.341400
2020-11-20T04:39:50
2020-11-20T04:39:50
307,379,116
0
0
null
null
null
null
UTF-8
C++
false
false
3,353
cpp
#include <iostream> #include <windows.h> #include <vector> using namespace std; enum direction {NONE ,UP, DOWN, LEFT, RIGHT }; direction dir = direction::NONE; int length = 12, width = 24; vector<int> player_x = {width/2}; vector<int> player_y = {length/2}; int playerlength = 1; int score = 0; vector<int> worm_x = { 3 }; vector<int> worm_y = { 3 }; bool gameOver = false; void movePlayer(int yMAX, int xMAX){ for (int i = player_x.size() - 1; i > 0; --i) { player_x[i] = player_x[i - 1]; player_y[i] = player_y[i - 1]; } //moves the players head around if (dir == direction::UP) { player_y[0] -= 1; if (player_y[0] == 0) { player_y[0] = yMAX - 1; } } else if (dir == direction::DOWN) { player_y[0] += 1; if (player_y[0] == yMAX) { player_y[0] = 1; } } else if (dir == direction::RIGHT) { player_x[0] += 1; if (player_x[0] == xMAX) { player_x[0] = 1; } } else if (dir == direction::LEFT) { player_x[0] -= 1; if (player_x[0] == 0) { player_x[0] = xMAX - 1; } } for (int i = 1; i < player_x.size(); i++) { if ((player_x[0] == player_x[i]) && (player_y[0] == player_y[i])) { gameOver = true; } } //checks if player is touching fuit; if (player_x[0] == worm_x[0] && player_y[0] == worm_y[0]) { score++; playerlength++; player_x.push_back(0); player_y.push_back(0); worm_x[0] = (rand() % (width-1)) + 1; worm_y[0] = (rand() % (length - 1)) + 1; } } //grabs inputs and changes the direction of player void getInputs(int length, int height) { Sleep(100); bool keyPressed = false; if (!keyPressed) { keyPressed = true; if (GetAsyncKeyState(VK_UP)) { dir = direction::UP; } else if (GetAsyncKeyState(VK_DOWN)) { dir = direction::DOWN; } else if (GetAsyncKeyState(VK_RIGHT)) { dir = direction::RIGHT; } else if (GetAsyncKeyState(VK_LEFT)) { dir = direction::LEFT; } } movePlayer(length, height); } // simple function to test current enum setting void checkEnum() { if (dir == direction::UP) { cout << "up"; } } void draw(const int &length, const int& width) { //Sleep(500); system("cls"); //clears the console // WILL DRAW WALLS AND CHARACTER //draws walls for (int i = 0; i <= length; i++) { for (int j = 0; j <= width; j++) { bool bodyPrinted = false; if ( i == 0 || i == length) { // prints line for top and bottm cout << "#"; } else if ( (j == 0 || j == width) && (i != 0 || i != length) ) { // prints side walls cout << "#"; } else { // prints empty space between ~~ will also house the player drawing for (int bod = 0; bod < player_x.size(); ++bod) { if (player_x[bod] == j && player_y[bod] == i) { cout << "@"; bodyPrinted = true; } } if (worm_x[0] == j && worm_y[0] == i) { cout << "~"; bodyPrinted = true; } if (!bodyPrinted){ cout << " "; } } } cout << endl; } cout << "Score: " << score; //cout << "\nPlayer X: " << player_x[0] << " Player Y: " << player_y[0]; //cout << "\nWorm X: " << worm_x[0] << " Worm Y: " << worm_y[0]; } int main() { //loops the main while (true) { //checkEnum(); draw(length, width); if (GetAsyncKeyState(VK_ESCAPE) || gameOver) { //exit dir = direction::NONE; cout << "\nGAME OVER"; return 0; } getInputs(length, width); // grabs the inputs // also move the player } }
[ "prince.hussain@city.ac.uk" ]
prince.hussain@city.ac.uk
07a5a6d3966770d79ac0eb36712f9cf94dbf23d4
36f68adb0fd4e647a416f20ed18278b62988858c
/TanCraft/MainListener.cpp
b708d88740ce0bc805294cf1375f25c7fe7d50f7
[]
no_license
daniel0128/Tancraft
5e6ce177fbea15d96f444b29dc66b7ba2ae208e3
152122149c3833a62d6804bd757d1519a4633ba1
refs/heads/master
2021-01-10T12:47:34.236054
2016-04-06T04:43:25
2016-04-06T04:43:25
54,285,107
0
0
null
null
null
null
UTF-8
C++
false
false
1,378
cpp
#include "MainListener.h" #include "UserInput.h" #include "InputHandler.h" #include "World.h" #include "Camera.h" #include <ois.h> MainListener::MainListener(Ogre::RenderWindow *mainWindow, InputHandler *inputManager, UserInput *input, World *world, TankCamera *cam): mRenderWindow(mainWindow), mInputHandler(inputManager), mUserInput(input), mWorld(world), mTankCamera(cam) { x = 0; } // On every frame, call the appropriate managers bool MainListener::frameStarted(const Ogre::FrameEvent &evt) { float time = evt.timeSinceLastFrame; if (time > 0.5) { time = 0.5; } // The only reason we have the Think method of the InputHandler return // a value, is for the escape key to cause our application to end. // Feel free to change this to something that makes more sense to you. mInputHandler->Think(time); mWorld->Think(time); mTankCamera->Think(time); mUserInput->Think(time); // Call think methods on any other managers / etc you want to add bool keepGoing = true; // Ogre will shut down if a listener returns false. We will shut everything down if // either the user presses escape or the main render window is closed. Feel free to // modify this as you like. if (mInputHandler->IsKeyDown(OIS::KC_ESCAPE) || mRenderWindow->isClosed()) { keepGoing = false; } return keepGoing; }
[ "survey600@qq.com" ]
survey600@qq.com
6db97b725444f3d4df1e661956b495cfaf787bb9
731742351364307a7808ac514b325439e957977f
/coding_vectorized/example_test.cpp
86241e198f24607e78a9fc199086f87a9cdc8f8d
[ "Apache-2.0" ]
permissive
tanvirarafin/HLS-Tiny-Tutorials
90bdc6fc5ff1063b09ef95ed763a448d35ccea66
475c5d0f23deab72db59196021ba77a5f522de30
refs/heads/master
2023-03-31T18:47:15.661590
2021-04-10T01:31:22
2021-04-10T01:31:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,203
cpp
/* * Copyright 2020 Xilinx, 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 <vector> #include <iostream> typedef float float16 __attribute__((vector_size(64))); extern "C" void example(float16*res, const float16 *lhs, const float16 *rhs, int n); int main(int, char**) { std::vector<float16> lhs(1000); std::vector<float16> rhs(1000); std::vector<float16> res(1000); float16 temp = {3.2, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 3.2, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1}; lhs[1] = temp; rhs[1] = temp; example(res.data(), lhs.data(), rhs.data(), 4); std::cout << "The output value for res[1][1] should be 2.2 and is " << res[1][1] << std::endl; return 0; }
[ "frederic@xilinx.com" ]
frederic@xilinx.com
6dd38958ecf106ef09ba664e123f8e1dbf8cbe3e
d1428e48eedaa17bf875c291336cb466b9489804
/QTcheck-worker/createtab/tab.h
b5ee8614f28d8ac0e358b554fd4aaa52b3dc3def
[]
no_license
wangxu989/wisecheckterminal
b7b392de77ceaefe73041c01078a9c47b2ecd266
7267e577382b70b5abff5f607a57d893a06a0c90
refs/heads/master
2023-02-11T01:49:05.489310
2021-01-06T14:59:19
2021-01-06T14:59:19
327,344,110
0
0
null
null
null
null
UTF-8
C++
false
false
8,059
h
#ifndef TAB_H #define TAB_H #include<QWidget> #include<QString> #include <QFile> #include<QtXml/QDomDocument> #include<QTableWidget> #include<QMouseEvent> #include<QDateTime> #include<QTime> #include<QObject> #include<QCoreApplication> #include<QVector> #include<QLabel> #include<QApplication> #include<QAbstractButton> #include<QStyleOption> #include<QStylePainter> #include<QTableView> #include<QHeaderView> #include<QScrollArea> #include<QAbstractScrollArea> #include<QScrollBar> #pragma pack(1) //子功能1的tab类 //发送给进程2的信息(人员,设备信息) struct worker_info{ QString name; int role; friend QDataStream& operator << (QDataStream &os,const worker_info &workInfo); }; struct local_env{ QString process; QString process_id; QString workstation; QString gauge_no; friend QDataStream& operator << (QDataStream &os,const local_env &localEnv); }; struct Equip{ QString test_place; QString equip; friend QDataStream& operator << (QDataStream &os,const Equip& equip); }; struct message_worker_evn{ worker_info workerInfo; local_env localEnv; Equip equip; friend QDataStream& operator << (QDataStream &os,const message_worker_evn &messageWorkerEnv); }; //接受扫码枪信息 struct work_info{ QString worker_id; QString product_id; QString instruction_id; QString checker_id; friend QDataStream& operator>>(QDataStream &os,struct work_info &info); public: QString get_worker_id(){ return this->worker_id.split(",")[1]; } }; class infomation{ public: friend QDataStream& operator<<(QDataStream &os,const infomation &a); QString product_no;//产品号 QString warn_thr;//预警阈值 QString chk_warn_thr;//复核报警阈值 QString detect_mode;//抽检方式 QString time_interval;//抽检时间间隔 QString cycle_time;//加工时间 QString sample_cnt;//抽检件数单位 QString disp_element_cnt;//屏幕展示个数 QString trend_warn_win;//趋势预警 QString lock_time;//锁定时间 }; struct tflag{ int flag;//该列状态:初始值为0,1代表工人赋值,2代表审核员赋值 int worker_row_flag;//操作员列标识 int checker_row_flag;//审核员列标识 int flash_flag;//是否被刷新过 int recover_flag;//是否被恢复为当前工作时间 QColor temp_worker_color;//操作员颜色暂存(用于操作员和核验员点击同一单元格) int t_time;//修改锁定时间 }; struct tabinfo{ friend QDataStream& operator<<(QDataStream &os,const tabinfo&a); QString gauge; QString featureid;//零件特性号 QString char_desc;//特征描述(长宽,内径...) double normvalue;//规格值 double zgc;//正公差 double fgc;//负公差 double jddw;//精度单位 double ejjddw;//二级精度单位 //int chk_warn_thr;//二级预警值 //int warn_thr;//一级预警值 }; class my_tablewidget:public QTableWidget { public: int gap;//工作时间间隔 int trend_val = 0;//增长方向趋势值(超出配置预警) int temp_trend_val = 0;//暂存,用于修改。下个时间段初始赋值给上面的值 int trend_plus_minus = 0;//该趋势是正/负趋势 int temp_trend_plus_minus = 0;//暂存正负标识 double val = -1;//上次次操作值. double temp_val = -1;//暂存本次操作值 //int QVector<tflag>flag;//标记该列是否被赋值过 int warn_thr; // ~my_tablewidget() override{//无指针可以不用虚析构 // } my_tablewidget(){ // this->setStyleSheet("QTableView QTableCornerButton::section{padding:12px 0 0 10px" // "background-position:center;"); //this->setFocusPolicy(Qt::NoFocus); QAbstractButton *btn = this->findChild<QAbstractButton *>(); if (btn) { btn->setText(QStringLiteral("范围/时间")); btn->installEventFilter(this); //btn->setStyleSheet("QAbstractButton{text-align : right;}"); QStyleOptionHeader opt; opt.text = btn->text(); QSize s = (btn->style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), btn).expandedTo(QApplication::globalStrut())); if (s.isValid()){ this->verticalHeader()->setMinimumWidth(s.width()); //t->verticalHeader()->setMinimumSize(btn->size()); } } //去掉横竖scrollbar this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } explicit my_tablewidget(const int& row,const int& column) { this->setColumnCount(column); this->setRowCount(row); this->horizontalHeader()->setHidden(true); this->verticalHeader()->setHidden(true); this->setEditTriggers(QAbstractItemView::NoEditTriggers); this->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); this->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); for (int i = 0;i < row;i++) { for (int j = 0;j < row;j++) { if (!(this->item(i,j))) { this->setItem(i,j,new QTableWidgetItem()); this->item(i,j)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter); } } } } bool eventFilter(QObject *o, QEvent *e) { if (e->type() == QEvent::Paint) { QAbstractButton* btn = qobject_cast<QAbstractButton*>(o); if (btn) { // paint by hand (borrowed from QTableCornerButton) QStyleOptionHeader opt; opt.init(btn); QStyle::State state = QStyle::State_None; if (btn->isEnabled()) state |= QStyle::State_Enabled; if (btn->isActiveWindow()) state |= QStyle::State_Active; if (btn->isDown()) state |= QStyle::State_Sunken; opt.textAlignment = Qt::AlignCenter;//居中 opt.state = state; opt.rect = btn->rect(); opt.text = btn->text(); // this line is the only difference to QTableCornerButton opt.position = QStyleOptionHeader::OnlyOneSection; QStylePainter painter(btn); painter.drawControl(QStyle::CE_Header, opt); return true; // eat event } } return false; } }; typedef struct { QVector<QVector<double> >x; QVector<QVector<double> >y; volatile int tabnum; } communication; typedef struct { int hour; int minute; int second; }create_time; #pragma pack() class mytab:public QTabWidget { Q_OBJECT public: //QVector<serialport_info>Serial_port; mytab(); ~mytab(); //QTabWidget *tabWidget; void tabadd(tabinfo& createinfo,infomation& info); int readxml(const work_info &work_info,int flag = 0); int read_local_authuser(const work_info &work_info); int read_local_env(const work_info &work_info,int flag); void flash_table(int current_time); int nekwork_or_local(); QVector<my_tablewidget*> table;//所有表格对象的地址 QVector<tabinfo> createinfo;//所有表格的基本信息 //QVector<QVector<tflag>>flag;//标记表格 communication my; infomation info; QVector<float>table_gap; QVector<QColor> color_scheme;//配色方案 message_worker_evn messageWorkerEvn; QString auto_zero(double from,double to);//自动补全'0' int start_time;//当前tab工作开始时间 int work_start_time;//当天工作开始时间 void read_gauge(work_info &workInfo); void modify_gauge(work_info &workInfo,int index); private: bool eventFilter(QObject *watched, QEvent *event); void trend_warn();//趋势预警处理函数 void showEvent(QShowEvent *); //void resizeEvent(QResizeEvent *e); private slots: }; #endif // TAB_H
[ "wangxu20103817@qq.com" ]
wangxu20103817@qq.com
32b6bbc6c49bb016cc5fbb8ebb21eb8e57a0bd2f
356b1ef5bfb7a67dc774ff7d7b3c0a3007438fe8
/GameEngine/SOILImage.h
6d5223c4bf5de87d0f511686574d61ddf7135d4d
[]
no_license
nickmly/engine
cbc9a6be93bdd74676cc337d80d90b012b187c5d
64c43b2dd40134301a99e647154ea44443c98765
refs/heads/master
2020-04-11T04:29:14.990341
2017-04-02T02:18:10
2017-04-02T02:18:10
68,014,869
1
1
null
null
null
null
UTF-8
C++
false
false
609
h
#pragma once #include "Image.h" class SOILImage : public Image { private: unsigned char* image; int width, height; public: SOILImage(const char * fname, int width, int height); ~SOILImage(); virtual int getBitsPerPixel(); virtual GLenum getFormat(); virtual int getHeight(); virtual int getWidth(); virtual unsigned char * getImage(); virtual int getPixelStorageParameter(); virtual GLenum getPixelStorageType(); virtual GLenum getPixelType(); virtual void Init(int _width, int _height); virtual void Init(std::string fname); virtual void setPixel(int x, int y, float r, float g, float b); };
[ "nickmly@gmail.com" ]
nickmly@gmail.com
a8e0356ca9f5b9fb37e53a82c66a285451ca7b0f
bc90e70ee2139b034c65a5755395ff55faac87d0
/sprout/tuple/tuple.hpp
99afdd3557bfedffa5e9335daff0aa6c3fa00e14
[ "BSL-1.0" ]
permissive
Manu343726/Sprout
0a8e2d090dbede6f469f6b875d217716d0200bf7
feac3f52c785deb0e5e6cd70c8b4960095b064be
refs/heads/master
2021-01-21T07:20:16.742204
2015-05-28T04:11:39
2015-05-28T04:11:39
37,670,169
0
1
null
2015-06-18T16:09:41
2015-06-18T16:09:41
null
UTF-8
C++
false
false
1,169
hpp
/*============================================================================= Copyright (c) 2011-2015 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_TUPLE_TUPLE_HPP #define SPROUT_TUPLE_TUPLE_HPP #include <sprout/config.hpp> #include <sprout/tuple/tuple/tuple_fwd.hpp> #include <sprout/tuple/tuple/tuple_decl.hpp> #include <sprout/tuple/tuple/tuple.hpp> #include <sprout/tuple/tuple/comparison.hpp> #include <sprout/tuple/tuple/tuple_size.hpp> #include <sprout/tuple/tuple/tuple_element.hpp> #include <sprout/tuple/tuple/get.hpp> #include <sprout/tuple/tuple/hash.hpp> #include <sprout/tuple/tuple/ignore.hpp> #include <sprout/tuple/tuple/make_tuple.hpp> #include <sprout/tuple/tuple/type_traits.hpp> #include <sprout/tuple/tuple/traits.hpp> #include <sprout/tuple/flexibly_construct.hpp> #include <sprout/tuple/default_construct.hpp> #endif // #ifndef SPROUT_TUPLE_TUPLE_HPP
[ "bolero.murakami@gmail.com" ]
bolero.murakami@gmail.com
8631d297bf5fe3d9471c6fb7cc962cc9140713af
aad6b08ee56c2760b207d562f16be0a5bb8e3e2a
/tags/Doduo/BAL/OWBAL/Concretizations/Facilities/Gtk/BCFileChooserGtk.cpp
f277040d1d59ad294f4055e15c8103bc9f8bd9bf
[]
no_license
Chengjian-Tang/owb-mirror
5ffd127685d06f2c8e00832c63cd235bec63f753
b48392a07a2f760bfc273d8d8b80e8d3f43b6b55
refs/heads/master
2021-05-27T02:09:03.654458
2010-06-23T11:10:12
2010-06-23T11:10:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,809
cpp
/* * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. * Copyright (C) 2007 Holger Hans Peter Freyther * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "FileChooser.h" #include "CString.h" #include "Document.h" #include "FrameView.h" #include "Icon.h" #include "LocalizedStrings.h" #include "StringTruncator.h" #include <glib.h> #include <glib/gi18n.h> #include <gtk/gtk.h> namespace OWBAL { static bool stringByAdoptingFileSystemRepresentation(gchar* systemFilename, String& result) { if (!systemFilename) return false; gchar* filename = g_filename_to_utf8(systemFilename, -1, 0, 0, 0); g_free(systemFilename); if (!filename) return false; result = String::fromUTF8(filename); g_free(filename); return true; } void FileChooser::openFileChooser(Document* document) { FrameView* view = document->view(); if (!view) return; GtkWidget* dialog = gtk_file_chooser_dialog_new(_("Upload File"), GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(view->containingWindow()))), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); // We need this protector because otherwise we can be deleted if the file upload control is detached while // we're within the gtk_run_dialog call. RefPtr<FileChooser> protector(this); String result; const bool acceptedDialog = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT; if (acceptedDialog && stringByAdoptingFileSystemRepresentation(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)), result)) chooseFile(result); gtk_widget_destroy(dialog); } String FileChooser::basenameForWidth(const Font& font, int width) const { if (width <= 0) return String(); String string = fileButtonNoFileSelectedLabel(); if (!m_filename.isEmpty()) { gchar* systemFilename = g_filename_from_utf8(m_filename.utf8().data(), -1, 0, 0, 0); if (systemFilename) { gchar* systemBasename = g_path_get_basename(systemFilename); g_free(systemFilename); stringByAdoptingFileSystemRepresentation(systemBasename, string); } } return StringTruncator::centerTruncate(string, width, font, false); } }
[ "mbensi@a3cd4a6d-042f-0410-9b26-d8d12826d3fb" ]
mbensi@a3cd4a6d-042f-0410-9b26-d8d12826d3fb
5d814bc8fc0f5b0d3c087062805e4b20364b76d1
b8dba2579a45e91710f6bc51d50e2bd7d56d01a3
/044_多继承原理抛砖.cpp
929ac7ec30cb76a0edb1d8c73a0881802025a19b
[]
no_license
shahhimtest/cpp_test_code_20190603
4fd0a34b149babca19636c503ca62e1bc717697d
0cdb63c66a39906410040b34d7eceba684abae2e
refs/heads/master
2023-07-14T21:40:39.273192
2019-07-06T11:34:08
2019-07-06T11:34:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,046
cpp
#include <iostream> using namespace std; class B { public: B() { cout << "B构造函数执行\n"; } int b; protected: private: }; class B1 : virtual public B //12 { public: int b1; }; class B2 : public B //8 { public: int b2; }; class C : public B1, public B2 { public: int c; }; void test03() { cout << sizeof(B) << endl; //4 cout << sizeof(B1) << endl; //12 //加上virtual以后 , C++编译器会在给变量偷偷增加属性 cout << sizeof(B2) << endl; //8 //cout<<sizeof(B)<<endl; } void test01() { C c1; c1.b1 = 100; c1.b2 = 200; c1.c = 300; //c1.b = 500; //继承的二义性 和 虚继承解决方案 //c1.B1::b = 500; //c1.B2::b = 500; cout << "hello..." << endl; system("pause"); return; } class D1 { public: int k; protected: private: }; class D2 { public: int k; protected: private: }; class E : public D1, public D2 { public: protected: private: }; void test02() { E e1; e1.D1::k = 100; e1.D2::k = 200; system("pause"); } int main() { test01(); test02(); test03(); return 0; }
[ "40995328+007skyfall@users.noreply.github.com" ]
40995328+007skyfall@users.noreply.github.com
404367adb5ae75e55ddad2606b0cf85732ee5efb
f02a2f65c974c9959f83c9d2e651b661190394c4
/src/Pulses/PulMLEV.h
5fbd7e5eff3f526c5b84bda91f3bde9ef6724be1
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
kaustubhmote/gamma
f207afd5f17ebc0a0b66dc82631256c854667e49
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
refs/heads/main
2023-03-14T12:18:59.566123
2021-03-03T17:58:07
2021-03-03T17:58:07
419,639,294
1
0
null
null
null
null
UTF-8
C++
false
false
20,830
h
/* PulMLEV.h ****************************************************-*-c++-*- ** ** ** G A M M A ** ** ** ** MLEV Pulse Functions Interface ** ** ** ** Copyright (c) 1998 ** ** Dr. Scott A. Smith ** ** National High Magnetic Field Laboratory ** ** 1800 E. Paul Dirac Drive ** ** Box 4005 ** ** Tallahassee, FL 32306 ** ** ** ** $Header: $ ** ** *************************************************************************/ /************************************************************************* ** ** ** This file contains the a variety of functions supporting the use ** ** of MLEV pulses and pulse trains in the GAMMA simulation platform. ** ** The basic MLEV waveforms are composite 180 pulses and these are ** ** cycled to build up longer MLEV based pulse trains. MLEV sequences ** ** are used in both mixing and broad-band decoupling. For details see ** ** ** ** ** *************************************************************************/ #ifndef GMLEV_h_ // Is this file already included? # define GMLEV_h_ 1 // If no, then remember it # if defined(GAMPRAGMA) // Using the GNU compiler? # pragma interface // This is the implementation # endif #include <GamGen.h> // Know MSVCDLL (__declspec) # include <Pulses/Pulse.h> // Know base pulse parameters # include <Pulses/PulWaveform.h> // Know pulse waveforms # include <Pulses/PulComposite.h> // Know composite pulses # include <Pulses/PulCycle.h> // Know pulse cycles # include <Matrix/row_vector.h> # include <Basics/ParamSet.h> class MLEV : public Pulse { private: // ---------------------------------------------------------------------------- // --------------------------- PRIVATE FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // i CLASS MLEV ERROR HANDLING // ____________________________________________________________________________ void MLEVerror(int eidx, int noret=0) const; // Input MLEV : MLEV parameters(this) // eidx : Error flag // noret : Return flag // Output none : Error Message Output void volatile MLEVfatality(int error) const; // Input MLEV : MLEV parameters(this) // eidx : Error flag // Output none : Stops execution & error Message void MLEVerror(int eidx, const std::string& pname, int noret=0) const; // Input MLEV : MLEV parameters(this) // eidx : Error index // pname : String included in message // noret : Flag for return (0=return) // Output none : Error message void volatile MLEVfatality(int eidx, const std::string& pname, int noret=0) const; // Input MLEV : MLEV parameters // eidx : Error flag // pname : Part of error message // noret : Flag for return (0=return) // Output none : Stops execution & error Message // ____________________________________________________________________________ // ii CLASS MLEV PARAMETER SET FUNCTIONS // ____________________________________________________________________________ void SetPhase(const ParameterSet& pset, int idx=-1); // Intput DT : MLEV parameters // pset : Parameter set // idx : MLEV index // Output none : MLEV pulse phase read in // from parameter in pset // with index idx void SetChannel(const ParameterSet& pset, int idx=-1); // Intput DT : MLEV parameters // pset : Parameter set // idx : MLEV index // Output none : MLEV pulse channel read in // from parameter in pset // with index idx int SetGamB1(const ParameterSet& pset, int idx=-1); // Intput DT : MLEV parameters // pset : Parameter set // idx : MLEV index // Output TF : MLEV pulse strength read in // from parameter in pset // with index idx // ---------------------------------------------------------------------------- // ---------------------------- PUBLIC FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- public: // ____________________________________________________________________________ // A CLASS MLEV CONSTRUCTION, DESTRUCTION // ____________________________________________________________________________ MSVCDLC MLEV(); // Input none : // Output MLEV : MLEV parameters(this) ///F_list MLEV - Constructor MSVCDLC MLEV(double gB1, const std::string& ch, double ph=0, double off=0); // Input gB1 : RF-field strength (Hz) // ch : RF-channel // ph : RF-phase (degrees) // off : RF-offset (Hz) // Output MLEV : MLEV parameters(this) MSVCDLC MLEV(const MLEV& PT1); // Intput MLEV1 : MLEV parameters // Output MLEV : MLEV parameters(this) from MLEV1 // ------------------------------ Destruction --------------------------------- MSVCDLC ~MLEV(); // Intput MLEV1 : MLEV parameters (this) // Output none : MLEV is destructed // ------------------------------- Assignment --------------------------------- MSVCDLL MLEV& operator = (const MLEV& MLEV1); // Intput MLEV1 : MLEV parameters // Output MLEV : MLEV parameters(this) from MLEV1 ///F_list = - Assignment // ____________________________________________________________________________ // B CLASS MLEV ACCESS FUNCTIONS // ____________________________________________________________________________ /* std::string channel() const; INHERITED double strength() const; INHERITED double phase() const; INHERITED double offset() const; INHERITED */ // Intput MLEV1 : MLEV parameters // Output channel : MLEV isotope channel // strength: MLEV pulse strength (Hz) // phase : MLEV pulse phase (sec) // offset : MLEV pulse offset (Hz) // ____________________________________________________________________________ // C CLASS MLEV HILBERT SPACE PROPAGATORS // ____________________________________________________________________________ // ____________________________________________________________________________ // D CLASS MLEV LIOUVILLE SPACE PROPAGATORS // ____________________________________________________________________________ // ____________________________________________________________________________ // E MLEV WAVEFORM FUNCTIONS // ____________________________________________________________________________ /****************************************************************************** There are 3 steps in a MLEV composite 180 sequence, as shown below. U = U (90)*U (180)*U (90) x y x Each U represents a pulse of the specified angle about the axis indicates by the subscript. ******************************************************************************/ MSVCDLL PulWaveform WF( ) const; MSVCDLL PulWaveform WF_C180( ) const; // Input MP : MLEV parameters // Output PWF : Pulse waveform for MLEV composite 180 // Note : Constant rf-amplitude each step // Note : Ideal pulses are allowed // ____________________________________________________________________________ // F MLEV COMPOSITE PULSE FUNCTIONS // ____________________________________________________________________________ /****************************************************************************** There are 3 steps in a MLEV composite 180 sequence, as shown below. U = U (90)*U (180)*U (90) x y x Each U represents a pulse of the specified angle about the axis indicates by the subscript. ******************************************************************************/ MSVCDLL PulComposite PCmp(const spin_system& sys) const; MSVCDLL PulComposite PCmp_C180(const spin_system& sys) const; // Input MP : MLEV parameters // sys : A spin system // Output PCmp : Composite pulse for MLEV composite 180 // applicable to sys // ____________________________________________________________________________ // G MLEV PULSE CYCLE FUNCTIONS // ____________________________________________________________________________ /* **************************************************************************** There are 4 cycles associated with MLEV-4, as shown below _ _ U = R R R R R = 90 180 90 x y x Each R represents a pulse waveform and the bar indicates a 180 degree phase shift. A MLEV-4 pulse train will employ R = MLEV which is just a composite 180 pulse. The MLEV-4 cycle is simply the phi phi phi+180 phi+180 phase sequence. ******************************************************************************/ MSVCDLL PulCycle CycMLEV4(const spin_system& sys) const; // Input MP : MLEV parameters // sys : A spin system // Output PCyc : MLEV-4 pulse cycle for sys /* **************************************************************************** There are 8 cycles associated with MLEV-8, as shown below _ _ _ _ U = R R R R R R R R R = 90 180 90 x y x Each R represents a pulse waveform and the bar indicates a 180 degree phase shift. A MLEV-8 pulse train will employ R = MLEV which is just a composite 180 pulse. The MLEV-8 cycle is simply the phi phi phi+180 phi+180 phi+180 phi phi phi+180 phase sequence. ******************************************************************************/ MSVCDLL PulCycle CycMLEV8(const spin_system& sys) const; // Input MP : MLEV parameters // sys : A spin system // Output PCyc : MLEV-8 pulse cycle for sys /* **************************************************************************** There are 16 cycles associated with MLEV-16, as shown below _ _ _ _ _ _ _ _ U = R R R R R R R R R R R R R R R R R = 90 180 90 x y x Each R represents a pulse waveform and the bar indicates a 180 degree phase shift. A MLEV-16 pulse train will employ R = MLEV which is just a composite 180 pulse. The MLEV-16 cycle is simply the phi phi phi+180 phi+180 phi+180 phi phi phi+180 ..... phase sequence. ******************************************************************************/ MSVCDLL PulCycle CycMLEV16(const spin_system& sys) const; // Input MP : MLEV parameters // sys : A spin system // Output PCyc : MLEV-16 pulse cycle for sys // ____________________________________________________________________________ // H MLEV PULSE SUPERCYCLE FUNCTIONS // ____________________________________________________________________________ // ____________________________________________________________________________ // I MLEV PULSE TRAIN FUNCTIONS // ____________________________________________________________________________ // ____________________________________________________________________________ // K CLASS MLEV INPUT FUNCTIONS // ____________________________________________________________________________ MSVCDLL void read(const std::string &filename, int idx=-1); // Intput MP : MLEV parameters // idx : MLEV index // Output none : MLEV parameters are read in // from parameters in file filename // with index idx MSVCDLL void read(const ParameterSet& pset, int idx=-1); // Intput MP : MLEV parameters // pset : Parameter set // idx : MLEV index // Output none : MLEV parameters are read in // from parameters in pset // with index idx // Read MLEV Delay & Pulse Parameters // For The Pulse We Need Two of Three: {Pulse Angle, RF Strength, Pulse Length} // Note: Reading order is angle --> length --> strength for MLEV. If only // the angle is specified the length will be set to zero (ideal pulse) MSVCDLL void ask_read(int argc, char* argv[], int argn); // Intput ML : MLEV parameters // argc : Number of arguments // argv : Vecotr of argc arguments // argn : Argument index // Output void : The parameter argn of array argc // is used to supply a filename // from which the MLEV parameters // are read // If the argument argn is not in argv, // the user is asked for a filename // Note : The file should be an ASCII file // containing recognized sys parameters // Note : MLEV parameters are modifed (filled) // ____________________________________________________________________________ // L CLASS MLEV I/O FUNCTIONS // ____________________________________________________________________________ MSVCDLL std::ostream& printBase(std::ostream &ostr) const; // Intput ML : MLEV parameters // ostr : Output stream // Output none : MLEV basic parameters are sent // to the output stream MSVCDLL std::ostream& print(std::ostream &ostr) const; // Intput GP : MLEV parameters // ostr : Output stream // Output none : MLEV parameters are sent // to the output stream MSVCDLL friend std::ostream &operator << (std::ostream &ostr, const MLEV &GP); // Intput GP : MLEV parameters // ostr : Output stream // Output none : MLEV parameters are sent // to the output stream }; // ____________________________________________________________________________ // AA ADDITIONAL MLEV PHASE CYCLE FUNCTIONS // ____________________________________________________________________________ /* **************************************************************************** There are 4 cycles associated with MLEV-4, as shown below _ _ U = R R R R R = 90 180 90 x y x Each R represents a pulse waveform and the bar indicates a 180 degree phase shift. A MLEV-4 pulse train will employ R = MLEV which is just a composite 180 pulse. The MLEV-4 cycle is simply the phi phi phi+180 phi+180 phase sequence. ******************************************************************************/ MSVCDLL row_vector CYC_MLEV4(double phi=0); // Input void : None // phi : Phase angle (degrees) // Output PCyc : MLEV-4 pulse cycle /* **************************************************************************** There are 8 cycles associated with MLEV-8, as shown below _ _ _ _ U = R R R R R R R R R = 90 180 90 x y x Each R represents a pulse waveform and the bar indicates a 180 degree phase shift. A MLEV-8 pulse train will employ R = MLEV which is just a composite 180 pulse. The MLEV-8 cycle is simply the phi phi phi+180 phi+180 phi+180 phi phi phi+180 phase sequence. ******************************************************************************/ MSVCDLL row_vector CYC_MLEV8(double phi=0); // Input void : None // phi : Phase angle (degrees) // Output PCyc : MLEV-4 pulse cycle /* **************************************************************************** There are 16 cycles associated with MLEV-16, as shown below _ _ _ _ _ _ _ _ U = R R R R R R R R R R R R R R R R R = 90 180 90 x y x Each R represents a pulse waveform and the bar indicates a 180 degree phase shift. A MLEV-16 pulse train will employ R = MLEV which is just a composite 180 pulse. The MLEV-16 cycle is simply the phi phi phi+180 phi+180 phi+180 phi phi phi+180 ..... phase sequence. ******************************************************************************/ MSVCDLL row_vector CYC_MLEV16(double phi=0); // Input void : None // phi : Phase angle (degrees) // Output PCyc : MLEV-16 pulse cycle #endif // PulMLEV.h
[ "bsoher@briansoher.com" ]
bsoher@briansoher.com
64048467511dd14064e3718081e5454dacdbe25d
3094900b28f09ae64e2d462fdf269764555d4c2f
/src/db/dbBlk.hpp
7b6f6e78957cbb62f4534076c36d9b14580b6860
[]
no_license
HecatePhy/anaroute
109b1afb5ddedbaf46eb479eb7436224ae0d03d7
a7c99aaa1b9a43b0b2f7e0dfbdc9250ec0886cba
refs/heads/master
2023-08-15T02:55:54.559283
2021-06-25T03:22:51
2021-06-25T03:22:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,655
hpp
/** * @file dbBlk.hpp * @brief Circuit Element - Blkage * @author Hao Chen * @date 09/20/2019 * **/ #ifndef _DB_BLOCK_HPP_ #define _DB_BLOCK_HPP_ #include "src/global/global.hpp" #include "src/geo/box.hpp" PROJECT_NAMESPACE_START class Blk { friend class Parser; friend class CirDB; public: Blk() : _idx(MAX_UINT), _layerIdx(MAX_UINT), _bDummy(false), _pinIdx(MAX_UINT), _bLVS(false) {} Blk(const UInt_t i, const UInt_t l, const Box<Int_t>& b, const bool bLVS = false) : _idx(i), _layerIdx(l), _box(b), _bDummy(false), _pinIdx(MAX_UINT), _bLVS(bLVS) {} ~Blk() {} //////////////////////////////////////// // Getter // //////////////////////////////////////// UInt_t idx() const { return _idx; } UInt_t layerIdx() const { return _layerIdx; } const Box<Int_t>& box() const { return _box; } Int_t xl() const { return _box.xl(); } Int_t yl() const { return _box.yl(); } Int_t xh() const { return _box.xh(); } Int_t yh() const { return _box.yh(); } const Point<Int_t>& bl() const { return _box.bl(); } const Point<Int_t>& tr() const { return _box.tr(); } const Point<Int_t>& min_corner() const { return _box.min_corner(); } const Point<Int_t>& max_corner() const { return _box.max_corner(); } // connected pin bool bConnect2Pin() const { return _pinIdx != MAX_UINT; } UInt_t pinIdx() const { return _pinIdx; } // bool bDummy() const { return _bDummy; } bool bLVS() const { return _bLVS; } private: UInt_t _idx; UInt_t _layerIdx; Box<Int_t> _box; bool _bDummy; UInt_t _pinIdx; bool _bLVS; //////////////////////////////////////// // Setter // //////////////////////////////////////// void setIdx(const UInt_t i) { _idx = i; } void setLayerIdx(const UInt_t i) { _layerIdx = i; } void setBox(const Box<Int_t>& b) { _box = b; } void setPinIdx(const UInt_t i) { _pinIdx = i; } void setDummy() { _bDummy = true; } void setLVS() { _bLVS = true; } }; PROJECT_NAMESPACE_END #endif /// _DB_BLOCK_HPP_
[ "haoc@utexas.edu" ]
haoc@utexas.edu
7b94c58bbe01da4cc3f89b2ceca1f9758a6996da
bcc37726efdb8a72d1106d0b99abbb5ab446a176
/include/requests/error.hpp
85e616e7fd2c651f277acfdb627e300bbdb9d6ae
[ "MIT" ]
permissive
miniriley2012/requests
506dcd85bfdf032e7c646db57b2fff0ae0ac7238
81039bc2f0fce99b22f6395a290e31f698a9aeaf
refs/heads/master
2022-12-11T00:24:26.477914
2020-08-29T18:40:55
2020-08-29T18:40:55
291,320,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,385
hpp
// // Created by Riley Quinn on 8/29/20. // #ifndef REQUESTS_REQUESTS_ERROR_HPP #define REQUESTS_REQUESTS_ERROR_HPP #include <string> #include <system_error> namespace requests { enum class [[maybe_unused]] error_code { OK = 0, INITIALIZATION_ERROR, }; std::string error_code_str(error_code ec); class error_category : std::error_category { [[nodiscard]] const char *name() const noexcept override { return "requests error"; } [[nodiscard]] std::error_condition default_error_condition(int ev) const noexcept override { return {ev, *this}; } [[nodiscard]] bool equivalent(int code, const std::error_condition &condition) const noexcept override { return code == condition.value(); } [[nodiscard]] bool equivalent(const std::error_code &code, int condition) const noexcept override { return code.value() == condition; } [[nodiscard]] std::string message(int ev) const override { return error_code_str(error_code{ev}); } }; struct requests_error : std::runtime_error { explicit requests_error(error_code ec) : std::runtime_error{error_code_str(ec)} {} }; } template<> struct ::std::is_error_code_enum<requests::error_code> : std::true_type { }; #endif //REQUESTS_REQUESTS_ERROR_HPP
[ "merileyquinn@gmail.com" ]
merileyquinn@gmail.com
12f7de355746d9774a58a3bc8968fb9953d94374
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/android_ndk/sources/third_party/vulkan/src/libs/vkjson/vkjson_instance.cc
7784d53926a7991fe480efdf126779a5e5b62feb
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
5,665
cc
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015-2016 The Khronos Group Inc. // Copyright (c) 2015-2016 Valve Corporation // Copyright (c) 2015-2016 LunarG, Inc. // Copyright (c) 2015-2016 Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////////// #define VK_PROTOTYPES #include "vkjson.h" #include <utility> namespace { bool EnumerateExtensions(const char* layer_name, std::vector<VkExtensionProperties>* extensions) { VkResult result; uint32_t count = 0; result = vkEnumerateInstanceExtensionProperties(layer_name, &count, nullptr); if (result != VK_SUCCESS) return false; extensions->resize(count); result = vkEnumerateInstanceExtensionProperties(layer_name, &count, extensions->data()); if (result != VK_SUCCESS) return false; return true; } } // anonymous namespace VkJsonDevice VkJsonGetDevice(VkPhysicalDevice physical_device) { VkJsonDevice device; vkGetPhysicalDeviceProperties(physical_device, &device.properties); vkGetPhysicalDeviceFeatures(physical_device, &device.features); vkGetPhysicalDeviceMemoryProperties(physical_device, &device.memory); uint32_t queue_family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &queue_family_count, nullptr); if (queue_family_count > 0) { device.queues.resize(queue_family_count); vkGetPhysicalDeviceQueueFamilyProperties( physical_device, &queue_family_count, device.queues.data()); } // Only device extensions. // TODO(piman): do we want to show layer extensions? uint32_t extension_count = 0; vkEnumerateDeviceExtensionProperties(physical_device, nullptr, &extension_count, nullptr); if (extension_count > 0) { device.extensions.resize(extension_count); vkEnumerateDeviceExtensionProperties( physical_device, nullptr, &extension_count, device.extensions.data()); } uint32_t layer_count = 0; vkEnumerateDeviceLayerProperties(physical_device, &layer_count, nullptr); if (layer_count > 0) { device.layers.resize(layer_count); vkEnumerateDeviceLayerProperties(physical_device, &layer_count, device.layers.data()); } VkFormatProperties format_properties = {}; for (VkFormat format = VK_FORMAT_R4G4_UNORM_PACK8; format <= VK_FORMAT_END_RANGE; format = static_cast<VkFormat>(format + 1)) { vkGetPhysicalDeviceFormatProperties(physical_device, format, &format_properties); if (format_properties.linearTilingFeatures || format_properties.optimalTilingFeatures || format_properties.bufferFeatures) { device.formats.insert(std::make_pair(format, format_properties)); } } return device; } VkJsonInstance VkJsonGetInstance() { VkJsonInstance instance; VkResult result; uint32_t count; count = 0; result = vkEnumerateInstanceLayerProperties(&count, nullptr); if (result != VK_SUCCESS) return VkJsonInstance(); if (count > 0) { std::vector<VkLayerProperties> layers(count); result = vkEnumerateInstanceLayerProperties(&count, layers.data()); if (result != VK_SUCCESS) return VkJsonInstance(); instance.layers.reserve(count); for (auto& layer : layers) { instance.layers.push_back(VkJsonLayer{layer, std::vector<VkExtensionProperties>()}); if (!EnumerateExtensions(layer.layerName, &instance.layers.back().extensions)) return VkJsonInstance(); } } if (!EnumerateExtensions(nullptr, &instance.extensions)) return VkJsonInstance(); const VkApplicationInfo app_info = {VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr, "vkjson_info", 1, "", 0, VK_API_VERSION_1_0}; VkInstanceCreateInfo instance_info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, nullptr, 0, &app_info, 0, nullptr, 0, nullptr}; VkInstance vkinstance; result = vkCreateInstance(&instance_info, nullptr, &vkinstance); if (result != VK_SUCCESS) return VkJsonInstance(); count = 0; result = vkEnumeratePhysicalDevices(vkinstance, &count, nullptr); if (result != VK_SUCCESS) { vkDestroyInstance(vkinstance, nullptr); return VkJsonInstance(); } std::vector<VkPhysicalDevice> devices(count, VK_NULL_HANDLE); result = vkEnumeratePhysicalDevices(vkinstance, &count, devices.data()); if (result != VK_SUCCESS) { vkDestroyInstance(vkinstance, nullptr); return VkJsonInstance(); } instance.devices.reserve(devices.size()); for (auto device : devices) instance.devices.emplace_back(VkJsonGetDevice(device)); vkDestroyInstance(vkinstance, nullptr); return instance; }
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
329da1dbbd3893175e4c9c95b4aab87366123d04
160742f8a8b4f159578cd1f2bfa27b9819d232e8
/Unit_1/range/impl.h
4c2499045e32e26fdbd3aabfa32798bdbc5c2bfc
[]
no_license
wrxcode/C-11
1103c518e3a839d486cf19678f0edaa040c29ac2
d4d7336d668178f23fcef9128bd38c5dfc1461c6
refs/heads/master
2021-06-02T18:55:29.757838
2016-08-18T07:39:33
2016-08-18T07:39:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,668
h
/************************************************************************* > File Name: impl.h > Author: > Mail: > Created Time: 2016年08月04日 星期四 16时41分29秒 ************************************************************************/ #ifndef _IMPL_H #define _IMPL_H #include "iterator.h" namespace detail_range{ template <typename T> class impl { public: using value_type = T; using reference = const value_type&; using const_reference = const value_type&; using iterator = const detail_range::iterator<value_type>; using const_iterator = const detail_range::iterator<value_type>; using size_type = typename iterator::size_type; private: const value_type begin_; //迭代器中begin的值 const value_type end_; //迭代器中end的值 const value_type step_; //代步长 const size_type max_count_; //迭代次数 size_type get_adjusted_count(void) const { if (step_ > 0 && begin_ >= end_) throw std::logic_error("END value must be greater than begin value."); if (step_ < 0 && begin_ <= end_) throw std::logic_error("END value must be less than begin value"); size_type x = static_cast<size_type>((end_ - begin_) / step_); if (begin_ + (step_ * x) != end_) { ++x; } return x; } public: impl(value_type begin_val, value_type end_val, value_type step_val) :begin_(begin_val), end_(end_val), step_(step_val), max_count_(get_adjusted_count()) { } size_type szie(void) const { return max_count_; } const_iterator begin(void) const { return { 0, begin_, step_ }; } const_iterator end(void) const { return { max_count_, begin_, step_ }; } }; } #endif
[ "1721267632@qq.com" ]
1721267632@qq.com
38886b2ef077ae1bb78f91bb5d2821d8f72dbf72
1354eb6100e2841cc6ef5faa4f71ce0d34a0ca9b
/src/widgets/stil_chatctrls.h
91e55c54306d431e54240d997f53c4fa7ead9dbc
[]
no_license
ysur/stildcpp
87fbed1c167938ff43a80d1b78694ebcba45b1fc
acb2c3d24459e5345b75f0d208e0a326884c67ed
refs/heads/master
2021-05-28T09:55:33.581812
2008-12-23T12:24:53
2008-12-23T12:24:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,374
h
/*************************************************************************** * Copyright (C) 2007 - 2008 by Pavel Andreev * * Mail: apavelm on gmail point com (apavelm@gmail.com) * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef STIL_CHATCTRLS_H #define STIL_CHATCTRLS_H #include <QTextEdit> #include <QDateTime> #include "stil_textview.h" class LineEdit; class QEvent; class QKeyEvent; class QResizeEvent; class QTimer; class ChatView : public StilTextView { Q_OBJECT public: ChatView(QWidget* parent); ~ChatView() { } // reimplemented void appendText(const QString &text); protected: void keyPressEvent(QKeyEvent *); protected slots: void autoCopy() { if (isReadOnly()) copy(); } }; class LineEdit : public QTextEdit { Q_OBJECT public: LineEdit(QWidget* parent); ~LineEdit(); // reimplemented QSize minimumSizeHint() const; QSize sizeHint() const; void keyPressEvent(QKeyEvent *); protected: // reimplemented void resizeEvent(QResizeEvent*); bool focusNextPrevChild(bool next); private slots: void recalculateSize(); void updateScrollBar(); signals: void SendText(const QString &); }; #endif
[ "apavelm@ce0af37e-8b3b-0410-b313-1d31aded5f2d" ]
apavelm@ce0af37e-8b3b-0410-b313-1d31aded5f2d
41c8d8ce7bd24e32352445a3fb155b61e5e26dd9
037dc4a90f4fe0ffa4b0a4b735ce7ef703feeddd
/aws-cpp-sdk-rds/source/model/DescribePendingMaintenanceActionsResult.cpp
1e678bd1d7256ebb222f756d3c75e627febfb565
[ "JSON", "MIT", "Apache-2.0" ]
permissive
pokey909/aws-sdk-cpp
2e74e83236f931a4ced74a916dec17e086f6d286
8a02586dee99bc00ab3ea3929c165b0c974e8fbb
refs/heads/master
2021-01-15T11:24:09.348887
2015-12-15T08:56:49
2015-12-15T08:56:49
47,977,310
0
0
null
2015-12-14T13:41:29
2015-12-14T13:41:29
null
UTF-8
C++
false
false
2,719
cpp
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/rds/model/DescribePendingMaintenanceActionsResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <utility> using namespace Aws::RDS::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils::Logging; using namespace Aws::Utils; using namespace Aws; DescribePendingMaintenanceActionsResult::DescribePendingMaintenanceActionsResult() { } DescribePendingMaintenanceActionsResult::DescribePendingMaintenanceActionsResult(const AmazonWebServiceResult<XmlDocument>& result) { *this = result; } DescribePendingMaintenanceActionsResult& DescribePendingMaintenanceActionsResult::operator =(const AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode; if (rootNode.GetName() != "DescribePendingMaintenanceActionsResult") { resultNode = rootNode.FirstChild("DescribePendingMaintenanceActionsResult"); } if(!resultNode.IsNull()) { XmlNode pendingMaintenanceActionsNode = resultNode.FirstChild("PendingMaintenanceActions"); if(!pendingMaintenanceActionsNode.IsNull()) { XmlNode pendingMaintenanceActionsMember = pendingMaintenanceActionsNode.FirstChild("ResourcePendingMaintenanceActions"); while(!pendingMaintenanceActionsMember.IsNull()) { m_pendingMaintenanceActions.push_back(pendingMaintenanceActionsMember); pendingMaintenanceActionsMember = pendingMaintenanceActionsMember.NextNode("ResourcePendingMaintenanceActions"); } } XmlNode markerNode = resultNode.FirstChild("Marker"); if(!markerNode.IsNull()) { m_marker = StringUtils::Trim(markerNode.GetText().c_str()); } } XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; AWS_LOGSTREAM_DEBUG("Aws::RDS::Model::DescribePendingMaintenanceActionsResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); return *this; }
[ "henso@amazon.com" ]
henso@amazon.com
dc265e4dd0c5f2fa3b5ef9938b907b75aa5482a6
c0d291eed180ef5c03cf818dd501faa2c435c8b2
/Network/UNIXSocket.h
bb195fbd15ad84665a69a752cd08bcfad509773d
[]
no_license
alex-min/rtype-2014-minetta
61e27ce2813fd499f1eb95a2b1fa53673c563cc5
442c6a472b9c50e3d586a6dcea40317356417a9e
refs/heads/master
2016-08-12T06:34:30.565350
2012-01-31T10:36:11
2012-01-31T10:36:11
46,982,048
0
0
null
null
null
null
UTF-8
C++
false
false
3,274
h
#ifndef UNIXSOCKET_H #ifdef OS_UNIX #define UNIXSOCKET_H #include "Exception.h" #include "ISocket.h" #include "NetworkDisconnect.h" #include "IpAddress.h" #include <string> #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/time.h> #include <sys/resource.h> #ifndef SOCKET_ERROR #define SOCKET_ERROR -1 #else #error "SOCKET_ERROR Should not be defined on UNIX Platform" #endif namespace Network { sockaddr_in addressToSockAddr(Network::IpAddress const &ip, UInt16 port); void sockAddrToAddress(Network::IpAddress *ip, sockaddr_in const & sin); class UNIXSocket : public APortableSocket { public: UNIXSocket(); virtual bool connect(Network::IpAddress const & remote, UInt16 port, ISocket::SockType type = ISocket::TCP); virtual bool TCPConnect(Network::IpAddress const & remote, UInt16 port); virtual bool UDPConnect(Network::IpAddress const & remote, UInt16 port); virtual void UDPConnectWithoutSocket(Network::IpAddress const &remote, UInt16 port, ISocket *); virtual void disconnect(); virtual UInt16 sendTo(Network::IpAddress const &remote, UInt32 port, const void *data, UInt32 len); virtual UInt16 sendFake(Network::IpAddress const &remote, UInt32 port, const void *data, UInt32 len); virtual UInt16 send(const void *data, UInt32 len); // return : size of byte written in buf; virtual UInt16 readFrom(Network::IpAddress *remote, UInt16 *port, void *data, UInt32 len); virtual UInt16 read(void *data, UInt32 len); // return : size of byte written in buf virtual bool isServerSock() const; virtual UInt16 getPort() const; virtual UNIXSocket * waitForClient(); virtual bool createServerSocket(UInt16 port, ISocket::SockType type = ISocket::TCP); virtual bool createTCPServerSocket(UInt16 port); virtual bool createUDPServerSocket(UInt16 port); virtual bool isConnected(); virtual SockType getType() const; virtual Network::IpAddress const &getRemoteIp() const; virtual UInt32 getRemotePort() const; virtual void setRemoteIp(Network::IpAddress const &); virtual void setRemotePort(UInt16 port); public: Int32 UNIXGetSocket() const; private: UNIXSocket(int sock, struct sockaddr_in sin, unsigned short port); private: bool createClientSock(); protected: Network::IpAddress _udpClientToServerIp; Int16 _udpClientToServerPort; int _sock; struct sockaddr_in _sin; struct sockaddr_in _udpSinTmp; socklen_t _udpLenTmp; bool _isServerSock; std::string _ip; char _ipbuf[30]; bool _fakesocket; int _fakesocketreference; }; } // !namespace : Network #endif #endif // UNIXSOCKET_H
[ "joris.profili@gmail.com" ]
joris.profili@gmail.com
9174382e1f50364d0ae298161a02cfd1efe4a95f
05a65c385dc5ba32bff4e1af5f9d523a4e831449
/Source/USemLog/Classes/Runtime/SLLoggerManager.h
5eb7ee7ed699cd85e51bdbf2a7bdcea00c34f8e9
[ "BSD-3-Clause" ]
permissive
robcog-iai/USemLog
5571212e9c7fba04a441a89f269f02195a3b3643
d22c3b8876bec66a667023078f370a81f7ce9d2b
refs/heads/master
2023-09-01T08:53:09.932916
2022-11-03T11:20:35
2022-11-03T11:20:35
69,003,081
9
22
BSD-3-Clause
2023-03-29T14:44:52
2016-09-23T07:59:30
C++
UTF-8
C++
false
false
6,127
h
// Copyright 2017-present, Institute for Artificial Intelligence - University of Bremen // Author: Andrei Haidu (http://haidu.eu) #pragma once #include "CoreMinimal.h" #include "GameFramework/Info.h" #include "Runtime/SLLoggerStructs.h" #include "SLLoggerManager.generated.h" // Forward declarations class ASLWorldStateLogger; class ASLSymbolicLogger; UCLASS(ClassGroup = (SL), DisplayName = "SL Logger Manager") class USEMLOG_API ASLLoggerManager : public AInfo { GENERATED_BODY() public: // Sets default values for this actor's properties ASLLoggerManager(); // Call finish ~ASLLoggerManager(); protected: // Gets called both in the editor and during gameplay. This is not called for newly spawned actors. virtual void PostLoad() override; // Allow actors to initialize themselves on the C++ side virtual void PostInitializeComponents() override; // Called when the game starts or when spawned virtual void BeginPlay() override; // Called when actor removed from game or game ended virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; #if WITH_EDITOR // Called when a property is changed in the editor virtual void PostEditChangeProperty(struct FPropertyChangedEvent& PropertyChangedEvent) override; #endif // WITH_EDITOR public: // Init loggers void Init(); // Start loggers void Start(); // Finish loggers (forced if called from destructor) void Finish(bool bForced = false); // Get init state bool IsInit() const { return bIsInit; }; // Get started state bool IsStarted() const { return bIsStarted; }; // Get finished state bool IsFinished() const { return bIsFinished; }; // Set the location parameters (useful when controlled externally) void SetLocationParams(const FSLLoggerLocationParams& InParams) { LocationParams = InParams; }; // Set the start parameters (useful when controlled externally) void SetStartParams(const FSLLoggerStartParams& InParams) { StartParams = InParams; }; // Set the world state logger parameters (useful when controlled externally) void SetWorldStateLoggerParams(const FSLWorldStateLoggerParams& InParams, const FSLLoggerDBServerParams InDBServerParams) { bLogWorldState = true; DBServerParams = InDBServerParams; WorldStateLoggerParams = InParams; }; // Set the symbolic logger parameters (useful when controlled externally) void SetSymbolicLoggerParams(const FSLSymbolicLoggerParams& InParams) { bLogActionsAndEvents = true; SymbolicLoggerParams = InParams; }; // Set log world state flag void SetLogWorldState(bool Value) { bLogWorldState = Value; }; // Set log symbolic data void SetLogActionsAndEvens(bool Value) { bLogActionsAndEvents = Value; }; // Get semantic map id FString GetSemanticMapId() const { return LocationParams.SemanticMapId; }; // Get TaskId FString GetTaskId() const { return LocationParams.TaskId; }; // Get episode id FString GetEpisodeId() const { return LocationParams.EpisodeId; }; // Check if the manager is running independently bool IsRunningIndependently() const { return bUseIndependently; }; protected: // Setup user input bindings void SetupInputBindings(); // Start/finish logger from user input void UserInputToggleCallback(); private: // Get the reference or spawn a new initialized world state logger bool SetWorldStateLogger(); // Get the reference or spawn a new initialized symbolic logger bool SetSymbolicLogger(); // Write semantic map owl file using the semantic map id void WriteSemanticMap(bool bOverwrite = true); // Write task owl file using the task id void WriteTask(bool bOverwrite = true); protected: // Set when manager is initialized uint8 bIsInit : 1; // Set when manager is started uint8 bIsStarted : 1; // Set when manager is finished uint8 bIsFinished : 1; private: // Call init and start once the world is started, or execute externally UPROPERTY(EditAnywhere, Category = "Semantic Logger") uint8 bUseIndependently : 1; // Logger location parameters UPROPERTY(EditAnywhere, Category = "Semantic Logger", meta = (editcondition = "bUseIndependently")) FSLLoggerLocationParams LocationParams; // Logger start parameters UPROPERTY(EditAnywhere, Category = "Semantic Logger", meta = (editcondition = "bUseIndependently")) FSLLoggerStartParams StartParams; /* World state logger */ // True if the world state should be logged UPROPERTY(EditAnywhere, Category = "Semantic Logger", meta = (editcondition = "bUseIndependently")) bool bLogWorldState = false; // World state logger (if nullptr at runtime the reference will be searched for, or a new one will be spawned) UPROPERTY(VisibleAnywhere, Category = "Semantic Logger|World State Logger", meta = (editcondition = "bLogWorldState")) ASLWorldStateLogger* WorldStateLogger; // World state logger parameters used for logging UPROPERTY(EditAnywhere, Category = "Semantic Logger|World State Logger", meta = (editcondition = "bLogWorldState")) FSLWorldStateLoggerParams WorldStateLoggerParams; // DB server parameters UPROPERTY(EditAnywhere, Category = "Semantic Logger|World State Logger", meta = (editcondition = "bLogWorldState")) FSLLoggerDBServerParams DBServerParams; /* Symbolic logger */ UPROPERTY(EditAnywhere, Category = "Semantic Logger", meta = (editcondition = "bUseIndependently")) bool bLogActionsAndEvents = false; // World state logger (if nullptr at runtime the reference will be searched for, or a new one will be spawned) UPROPERTY(VisibleAnywhere, Category = "Semantic Logger|Symbolic Logger", meta = (editcondition = "bLogActionsAndEvents")) ASLSymbolicLogger* SymbolicLogger; // World state logger parameters used for logging UPROPERTY(EditAnywhere, Category = "Semantic Logger|Symbolic Logger", meta = (editcondition = "bLogActionsAndEvents")) FSLSymbolicLoggerParams SymbolicLoggerParams; // Editor button hack to write the semantic map UPROPERTY(EditAnywhere, Category = "Semantic Logger|Edit") bool bWriteSemanticMapButton = false; // Editor button hack to write the task owl file UPROPERTY(EditAnywhere, Category = "Semantic Logger|Edit") bool bWriteTaskButton = false; };
[ "andrei.haidu@yahoo.com" ]
andrei.haidu@yahoo.com
cedcd8d3f5e996e25ba256e376500c5eb40f3330
fe09db7431ca319829bb951793750dd3a58ded3d
/1-fundamentals/if3.cpp
e1f98bd43d2bd65662de32d71759e7eb0ba12009
[]
no_license
tiagomelojuca/cod3r-cpp-essential
ca657ff21d4076f98fdb3a99f55f6b16b0e3847e
8a214d067bdc439924e8cfe887de26b60da04644
refs/heads/master
2023-03-28T17:37:42.003432
2021-03-27T11:33:47
2021-03-27T11:33:47
352,048,837
0
0
null
null
null
null
UTF-8
C++
false
false
829
cpp
#include <iostream> using namespace std; int main() { // double num1, num2, num3, choosenNum; // cout << "Enter number 1: "; // cin >> num1; // cout << "Enter number 2: "; // cin >> num2; // cout << "Enter number 3: "; // cin >> num3; // if( num1 >= num2 ) { // choosenNum = num1; // } // if( num1 < num2 ) { // choosenNum = num2; // } // if( num3 >= choosenNum ) { // choosenNum = num3; // } // cout << "The higher number is: " << choosenNum << endl; int n1, n2, n3; cin >> n1; cin >> n2; cin >> n3; if( n1 >= n2 && n1 >= n3 ) { cout << n1 << endl; } if( n2 >= n1 && n2 >= n3 ) { cout << n2 << endl; } if( n3 >= n1 && n3 >= n2 ) { cout << n3 << endl; } return 0; }
[ "tiagomelojuca@gmail.com" ]
tiagomelojuca@gmail.com
13e960019ca76d7df8a71b35b2643702eba69b33
6d56eceb8f89e0a8f99ceb675232bae93ee2422f
/109.convert-sorted-list-to-binary-search-tree.cpp
5115aa0069a866b3cd96f0654f132aec091c1d08
[]
no_license
ketankr9/leetcode-solutions
6ecadd3f12de905c75c42e6718f9adc1c0cf1323
0c51ca65e0f45ef4c2594fd5dcd97261e2c4a859
refs/heads/master
2021-08-15T22:15:31.583196
2020-04-18T17:56:19
2020-04-18T17:56:19
161,271,232
0
0
null
null
null
null
UTF-8
C++
false
false
2,150
cpp
/* * @lc app=leetcode id=109 lang=cpp * * [109] Convert Sorted List to Binary Search Tree * * https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/ * * algorithms * Medium (41.04%) * Likes: 1063 * Dislikes: 68 * Total Accepted: 180.7K * Total Submissions: 437.3K * Testcase Example: '[-10,-3,0,5,9]' * * Given a singly linked list where elements are sorted in ascending order, * convert it to a height balanced BST. * * For this problem, a height-balanced binary tree is defined as a binary tree * in which the depth of the two subtrees of every node never differ by more * than 1. * * Example: * * * Given the sorted linked list: [-10,-3,0,5,9], * * One possible answer is: [0,-3,9,-10,null,5], which represents the following * height balanced BST: * * ⁠ 0 * ⁠ / \ * ⁠ -3 9 * ⁠ / / * ⁠-10 5 * * */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include<bits/stdc++.h> using namespace std; class Solution { public: TreeNode* sortedListToBST(ListNode* head) { if(head == NULL) return NULL; if(head->next == NULL) return new TreeNode(head->val); if(head->next->next == NULL){ TreeNode* root = new TreeNode(head->next->val); root->left = new TreeNode(head->val); return root; } ListNode* cur1 = head; ListNode* cur2 = head->next; ListNode* prev = NULL; while(cur2!=NULL && cur2->next!=NULL) prev = cur1, cur1 = cur1->next, cur2 = cur2->next->next; if(prev!=NULL) prev->next = NULL; TreeNode* root = new TreeNode(cur1->val); root->left = sortedListToBST(head); root->right= sortedListToBST(cur1->next); return root; } };
[ "utsav.krishnan.cse15@iitbhu.ac.in" ]
utsav.krishnan.cse15@iitbhu.ac.in
21a9a54776372b31531a9ed823e08226e64af5fa
7307c03c24753f9c7e148c5145b52b04a79e879d
/ListaEnlace.cpp
4eaa0d5db7385253fa91fd85a7c9256c9dc5da2b
[ "MIT" ]
permissive
JA7XJ/Examen2_JosephMoscoso_P3
838afcfcd915e5e156a289e7a2ac8dd5b220203e
b34ae0dca14f4e4dc0c166abfa2c728cfc20b3c2
refs/heads/master
2020-04-11T13:46:33.021590
2018-12-15T03:59:32
2018-12-15T03:59:32
161,828,821
0
0
null
null
null
null
UTF-8
C++
false
false
949
cpp
#include "ListaEnlace.h" #include "Usuario.h" #include <iostream> using std::cout; using std::endl; ListaEnlace::ListaEnlace(){ inicio=0; size=0; } bool ListaEnlace::push(Usuario* obj){ Node* newNode= new Node(obj); newNode->setNext(inicio); inicio=newNode; size=size+1; return true; } Usuario* ListaEnlace::top(){ if (inicio==0) { return 0; }else{ return inicio->getData(); } } Usuario* ListaEnlace::pop(){ if (inicio==0) { return 0; }else{ Node* tmp=inicio; inicio=inicio->getNext(); Usuario* retValue=tmp->getData(); tmp->setData(0); tmp->setNext(0); delete tmp; size=size-1; return retValue; } } void ListaEnlace::print(){ Node* tmp=inicio; cout<<"Stack:>>"; while (tmp!=0) { cout<<"<"<<tmp->getData()->toString()<<">"; tmp=tmp->getNext(); } cout<<endl; } int ListaEnlace::getSize(){ return size; } ListaEnlace::~ListaEnlace(){ delete inicio; }
[ "josephmoscoso70@hotmail.com" ]
josephmoscoso70@hotmail.com
e8bee0ce8a8019b25ef3f7fc8a3e9a03a9fce077
131e226630f5c0c2bc881f841f6f0bc9dd0c40eb
/include/advancegl/FrameBufferTest.h
b31fdc78c1f4963524d32d5da1bd57e4eef6cf6f
[]
no_license
journey-M/mLeanOpengl
80da6f3c79a17e0ba3ec6e783dcfedb9215a3af1
419d06a6a536038ec455885760ebfc80a9edc2b7
refs/heads/master
2023-06-22T08:18:02.837103
2022-07-18T22:23:30
2022-07-18T22:23:30
230,425,297
0
0
null
null
null
null
UTF-8
C++
false
false
3,680
h
#ifndef __FrameBufferTest_H__ #define __FrameBufferTest_H__ #include "../IOperator.h" #include "../Shader.h" #include "../glm/glm.hpp" #include "../Camera.h" #include "../stb_image.h" #include "../glm/gtc/matrix_transform.hpp" #include "../glm/gtc/type_ptr.hpp" #include "../glm/fwd.hpp" #include <GLFW/glfw3.h> class FrameBufferTest:public IOperator{ private: void init() override; void destroy() override; public: Camera camera = Camera(glm::vec3(0.0f, 0.0f, 3.0f)); float lastX = 800 / 2.0f; float lastY = 600 / 2.0f; bool firstMouse = true; // timing float deltaTime = 0.0f; float lastFrame = 0.0f; Shader* shader; Shader* screenShader; float cubeVertices[180] = { // positions // texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; float planeVertices[30] = { // positions // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this will cause the floor texture to repeat) 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, -5.0f, 2.0f, 2.0f }; float quadVertices[24] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates. // positions // texCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; // framebuffer configuration unsigned int framebuffer; // create a color attachment texture unsigned int textureColorbuffer; // create a renderbuffer object for depth and stencil attachment (we won't be sampling these) unsigned int rbo; unsigned int cubeVAO, cubeVBO; // plane VAO unsigned int planeVAO, planeVBO; // screen quad VAO unsigned int quadVAO, quadVBO; unsigned int cubeTexture; unsigned int floorTexture ; void render() override; void mouse_callback(double xoffset, double yoffset) override; void scroll_callback(double xoffset, double yoffset) override; virtual void proceessKeyEvent(int key) override; void initShader(); void initVertex(); void initModel(); unsigned int loadTexture(char const *path); }; #endif
[ "guoweijie@mail.360.cn" ]
guoweijie@mail.360.cn
2014ed54757747ed3423a994d1bbb8df60e38c70
306453defe5afdf344d25322ccc1ccc8f6e01813
/src/cli/opt_convert.cc
edb5ade6660df29ca05c3fe79e842a9941b21383
[]
no_license
hepangda/zbench
163fea1f8e5d5240e2914f1b8577e909b09ac3fb
9ed9417fe9b21087450995c72555d8171d5dd618
refs/heads/master
2020-05-05T10:22:44.942896
2019-05-26T10:19:57
2019-05-26T10:19:57
179,943,496
0
0
null
null
null
null
UTF-8
C++
false
false
821
cc
#include "opt_convert.h" const char* OptConvert::ConvertMethod(HttpMethod method) { const char *convert_map[] = { "GET", "POST", "PUT", "DELETE" }; return convert_map[method]; } const char* OptConvert::ConvertVersion(HttpVersion version) { const char *convert_map[] = { "1.0", "1.1" }; return convert_map[version]; } const char* OptConvert::ConvertProtocol(Protocol protocol) { const char *convert_map[] = { "HTTP", "HTTPS" }; return convert_map[protocol]; } const char* OptConvert::ConvertService(Protocol protocol) { const char *convert_map[] = { "http", "https" }; return convert_map[protocol]; } const char *OptConvert::ConvertVersionString(HttpVersion version) { const char *convert_map[] = { "HTTP/1.0", "HTTP/1.1" }; return convert_map[version]; }
[ "pangda@xiyoulinux.org" ]
pangda@xiyoulinux.org
03284df63d613f5b9c19da1c072e40ce38132635
08057c01f6612023f72d7cc3872ff1b68679ec5d
/Assignments/Assignment_5/Gaddis_8thEdition_Chap6_ProgChal16_Population/main.cpp
211940a076688f9dba1b0292879a060890f8d43c
[]
no_license
xMijumaru/RamosKevin_CSC5_SPRING2018__
d42519a426391303af3e77480b4451a3e07e7f62
7d904ed93c8490786dc62d546a93a01a999b0b69
refs/heads/master
2021-07-24T04:21:46.427089
2018-08-11T20:49:03
2018-08-11T20:49:03
125,411,373
0
0
null
null
null
null
UTF-8
C++
false
false
1,569
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: kevin * * Created on May 6, 2018, 2:49 PM */ #include <cstdlib> #include <iostream> using namespace std; //function declaration float population (float, float, float, float); int main(int argc, char** argv) { //declare variables here float p, //current population size year,//years to calculate ahead birth,//annual birth rate birthp,//birthrate percentage death,//annual death rate deathp;//death rate percentages float sum;//answer to all the data cout << "Population program" <<endl; cout << "What is the current population" << endl; cin>>p; cout << "How many years do you want to calculate" <<endl; cin >>year; cout << "What is the birth rate in percentages" <<endl; cin>>birth; cout<<"What is the death rate in percentages" << endl; cin >> death; //output sum= population (p,year, birth, death); cout << "In " << year << " year(s), the population will be " <<endl; cout << "approximately " << static_cast<int>(sum) << " inhabitants" <<endl; return 0; } float population (float p, float year, float birth, float death) { //Equations processed float deathp=death*1e-2; float birthp=birth*1e-2; float sum; sum=(p + (birthp * p) - (deathp * p)); return sum; }
[ "kramos24@student.rccd.edu" ]
kramos24@student.rccd.edu
b98191c2f2f0b65b1a440b337a61b3cd28328535
3b443b057a968c348703dfaab0ffa3fdb2781520
/text13/text13/text13View.cpp
bee6cec32a846e307e50cf8eb260cdd0474ccb9f
[]
no_license
gxnu-zyj/Myproject
601bd269ad52d997f33b77c6f8ea0cc8ac59a377
6170116f221ecc8fa71b0c0ccd2827de7b37a175
refs/heads/master
2022-11-08T19:11:15.997805
2020-07-03T04:48:30
2020-07-03T04:48:30
276,803,780
0
0
null
null
null
null
GB18030
C++
false
false
1,779
cpp
// text13View.cpp : Ctext13View 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "text13.h" #endif #include "text13Doc.h" #include "text13View.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // Ctext13View IMPLEMENT_DYNCREATE(Ctext13View, CView) BEGIN_MESSAGE_MAP(Ctext13View, CView) ON_WM_LBUTTONDOWN() END_MESSAGE_MAP() // Ctext13View 构造/析构 Ctext13View::Ctext13View() { // TODO: 在此处添加构造代码 } Ctext13View::~Ctext13View() { } BOOL Ctext13View::PreCreateWindow(CREATESTRUCT& cs) { // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 return CView::PreCreateWindow(cs); } // Ctext13View 绘制 void Ctext13View::OnDraw(CDC* /*pDC*/) { Ctext13Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: 在此处为本机数据添加绘制代码 } // Ctext13View 诊断 #ifdef _DEBUG void Ctext13View::AssertValid() const { CView::AssertValid(); } void Ctext13View::Dump(CDumpContext& dc) const { CView::Dump(dc); } Ctext13Doc* Ctext13View::GetDocument() const // 非调试版本是内联的 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(Ctext13Doc))); return (Ctext13Doc*)m_pDocument; } #endif //_DEBUG // Ctext13View 消息处理程序 void Ctext13View::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CString s; int C; Ctext13Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; C = pDoc->A + pDoc->B; s.Format(_T("A+B=%d"), C); CClientDC dc(this); dc.TextOutW(20, 20, s); CView::OnLButtonDown(nFlags, point); }
[ "1922148179@qq.com" ]
1922148179@qq.com
0a4e7123cabf438b20fce230de416595ad31171f
8214b5985eed062670bc69c3234450c4d0b6d6a0
/layers.h
a8da276b50c20a543fd6f8069cb9d20c2d2664d5
[]
no_license
tianjunz/Halide_NN_squeeze
e4ab096fb6ae8b0a0255dd75f9d3e16ccb3ee171
b53ff6e464a3217029139d1f53905e6299a72561
refs/heads/master
2020-03-28T13:04:38.892782
2018-09-27T21:11:11
2018-09-27T21:11:11
148,363,265
0
0
null
null
null
null
UTF-8
C++
false
false
29,432
h
#include "Halide.h" using namespace Halide; #include "halide_image.h" using namespace Halide::Tools; class Layer { public: Layer(Layer* in) { // The first layer in the pipeline does not have an input layer if (in) { // Get the halide function that computes values // of the input layer assert(in->forward.defined()); // Record the input layer in_layer = in; } } // Layer that serves as an input to the current layer Layer* in_layer; // Number of output dimensions virtual int out_dims() = 0; // Size of output dimension i, 0 <= i < out_dims() virtual int out_dim_size( int i) = 0; // Storage for layer parameters std::vector<Image<float> > params; std::vector<Image<float> > param_grads; std::vector<Image<float> > params_cache; // Halide function that computes the output of the layer Func forward; // Vector of halide functions which compute the gradients // with respect to layer parameters std::vector<Func> f_param_grads; // Halide function which computes gradient with respect // to layer input Func f_in_grad; // Defines the functions which compute gradient of the objective // function with respective to parameters and input. Given a function // which computes the derivate of the objective with respect to layer // outputs. Does this recursively for the input layer. virtual void back_propagate(Func dforward) = 0; virtual ~Layer() {}; }; class SoftMax: public Layer { public: Var in_dim, n; int num_classes, num_samples; // Expects 2-dimensional input layer (num_classes x num_samples) SoftMax(Layer* in, int schedule = 0) : Layer(in) { assert(in->out_dims() == 2); Func in_f = in_layer->forward; num_classes = in->out_dim_size(0); num_samples = in->out_dim_size(1); // Define forward Func exp_max, expo, normalizer; RDom r(0, num_classes); exp_max(n) = maximum(in_f(r.x, n)); expo(in_dim, n) = exp(in_f(in_dim, n) - exp_max(n)); normalizer(n) = cast(in_f.output_types()[0], 0); normalizer(n) += expo(r.x, n); forward(in_dim, n) = expo(in_dim, n)/normalizer(n); if (schedule) { // Local schedule exp_max.compute_at(forward, n); expo.compute_at(forward, n); normalizer.compute_at(forward, n); forward.compute_root().parallel(n); } } void back_propagate(Func labels) { if (!f_in_grad.defined()) { assert(labels.defined()); assert(forward.defined()); Expr label = clamp(labels(n), 0, num_classes -1); Expr t = (forward(in_dim, n) - 1)/num_samples; Expr f = (forward(in_dim, n)/num_samples); f_in_grad(in_dim, n) = select(in_dim == label, t, f); in_layer->back_propagate(f_in_grad); } } // Returns a halide function that computes softmax loss given // the correct labels for each sample Func loss(Func labels) { // Should loss be a layer? // Check if labels is defined assert(labels.defined()); // Check if the dimensions make sense assert(labels.dimensions() == 1); // TODO Figure out if there is a scalar type Var x; Func loss_p; RDom r(0, num_samples); loss_p(x) = cast(forward.output_types()[0], 0); // The clamp is necessary. Otherwise, halide will assume that the // label can be anything during bounds inference. loss_p(0) += -log(forward(clamp(labels(r.x), 0, num_classes - 1), r.x))/num_samples; return loss_p; } int out_dims() { return 2;} int out_dim_size( int i) { assert(i < 2); int size = 0; if (i == 0) size = num_classes; else if (i == 1) size = num_samples; return size; } }; class Affine: public Layer { public: Var in_dim, n, unit_dim; // num_units is the number of units in the layer // num_inputs is the size of each input sample int num_units, num_samples, num_inputs; float reg; // parameters for scheduling Var par; Affine(int _num_units, float _reg, Layer* in, int schedule = 0) : Layer(in) { Func in_f = in_layer->forward; num_units = _num_units; reg = _reg; // Create parameters num_inputs = in->out_dim_size(0); num_samples = in->out_dim_size(1); Image<float> W(num_inputs, num_units), b(num_units); params.push_back(W); params.push_back(b); // Define forward RDom r(0, num_inputs); // Initialize reduction to baises forward(unit_dim, n) = b(unit_dim); // Dot product forward(unit_dim, n) += in_f(r.x, n) * W(r.x, unit_dim); if (schedule) { forward.compute_root().fuse(unit_dim, n, par).parallel(par); forward.update().fuse(unit_dim, n, par).parallel(par); } } void back_propagate(Func dout) { assert(dout.defined()); if (!f_in_grad.defined()) { Func dW, db; Image<float> W = params[0]; Image<float> b = params[1]; RDom r1(0, num_units); // initializing to zero f_in_grad(in_dim, n) = cast(dout.output_types()[0], 0); f_in_grad(in_dim, n) += dout(r1.x, n) * W(in_dim, r1.x); RDom r2(0, num_samples); // initializing to regularized weights dW(in_dim, unit_dim) = cast(dout.output_types()[0], reg*W(in_dim, unit_dim)); Func in_f = in_layer->forward; dW(in_dim, unit_dim) += dout(unit_dim, r2.x) * in_f(in_dim, r2.x); f_param_grads.push_back(dW); // initializing to zero db(unit_dim) = cast(dout.output_types()[0], 0); db(unit_dim) += dout(unit_dim, r2.x); f_param_grads.push_back(db); // Create storage for gradients and caching params Image<float> W_grad(num_inputs, num_units); param_grads.push_back(W_grad); Image<float> W_cache(num_inputs, num_units); params_cache.push_back(W_cache); Image<float> b_grad(num_units); param_grads.push_back(b_grad); Image<float> b_cache(num_units); params_cache.push_back(b_cache); in_layer->back_propagate(f_in_grad); } } int out_dims() { return 2;} int out_dim_size( int i) { assert(i < 2); int size = 0; if(i==0) size = num_units; else if(i==1) size = num_samples; return size; } }; class DropOut: public Layer { public: Var x, y, z, w; // Threshold value between 0-1 representing the probability // with which a unit's output will be dropped float thresh; // Mask containing the drop out coefficients in the forward pass Func mask; DropOut(float _thresh, Layer* in) : Layer(in) { thresh = _thresh; Func in_f = in_layer->forward; // Define forward // See if there is a better way to do this Expr scale = 1.0f/(1.0f - thresh); switch(in_layer->out_dims()) { case 1: mask(x) = select(random_float() > thresh, scale, 0.0f); forward(x) = mask(x) * in_f(x); break; case 2: mask(x, y) = select(random_float() > thresh, scale, 0.0f); forward(x, y) = mask(x, y) * in_f(x, y); break; case 3: mask(x, y, z) = select(random_float() > thresh, scale, 0.0f); forward(x, y, z) = mask(x, y, z) * in_f(x, y, z); break; case 4: mask(x, y, z, w) = select(random_float() > thresh, scale, 0.0f); forward(x, y, z, w) = mask(x, y, z, w) * in_f(x, y, z, w); break; default: assert(0); } // The mask has to be stored at root. It will be incorrect to // recompute the mask since the random number generator will // generate different values. mask.compute_root(); } void back_propagate(Func dout) { assert(dout.defined()); if(!f_in_grad.defined()) { switch(in_layer->out_dims()) { case 1: f_in_grad(x) = dout(x) * mask(x); break; case 2: f_in_grad(x, y) = dout(x, y) * mask(x, y); break; case 3: f_in_grad(x, y, z) = dout(x, y, z) * mask(x, y, z); break; case 4: f_in_grad(x, y, z, w) = dout(x, y, z, w) * mask(x, y, z, w); break; default: assert(0); } in_layer->back_propagate(f_in_grad); } } int out_dims() { return in_layer->out_dims();} int out_dim_size( int i) { return in_layer->out_dim_size(i); } }; class ReLU: public Layer { public: Var x, y, z, w; int vec_len = 8; ReLU(Layer* in, int schedule = 0) : Layer(in) { Func in_f = in_layer->forward; // Define forward switch(in_layer->out_dims()) { case 1: forward(x) = max(0, in_f(x)); // schedule if (schedule) { //forward.compute_root(); //forward.vectorize(x, vec_len); } break; case 2: forward(x, y) = max(0, in_f(x, y)); // schedule if (schedule) { //forward.compute_root(); //forward.vectorize(x, vec_len); //forward.parallel(y); } break; case 3: forward(x, y, z) = max(0, in_f(x, y, z)); // schedule if (schedule) { //forward.compute_root(); //forward.vectorize(x, vec_len); //forward.parallel(z); } break; case 4: forward(x, y, z, w) = max(0, in_f(x, y, z, w)); // schedule if (schedule) { //forward.compute_root(); //forward.vectorize(x, vec_len); //forward.parallel(w); } break; default: assert(0); } } void back_propagate(Func dout) { assert(dout.defined()); if (!f_in_grad.defined()) { Func in_f = in_layer->forward; switch(in_layer->out_dims()) { case 1: f_in_grad(x) = dout(x) * select( in_f(x) > 0, 1, 0); break; case 2: f_in_grad(x, y) = dout(x, y) * select( in_f(x, y) > 0, 1, 0); break; case 3: f_in_grad(x, y, z) = dout(x, y, z) * select(in_f(x, y, z) > 0, 1, 0); break; case 4: f_in_grad(x, y, z, w) = dout(x, y, z, w) * select(in_f(x, y, z, w) > 0, 1, 0); break; default: assert(0); } in_layer->back_propagate(f_in_grad); } } int out_dims() { return in_layer->out_dims();} int out_dim_size( int i) { return in_layer->out_dim_size(i); } }; class Convolutional: public Layer { public: Var x, y, z, n; // number of channels, height and width of the input to the layer int num_samples, in_ch, in_h, in_w; // number of filters, filter height, filter width, padding and stride int num_f, f_h, f_w, pad, stride; float reg; Func f_in_bound; // parameters for scheduling Var y_t, z_t, par; int o_block_size = 16; int y_block_size = 32; int vec_len = 8; Convolutional(int _num_f, int _f_w, int _f_h, int _pad, int _stride, float _reg, Layer* in, int schedule=0) : Layer(in) { assert(in_layer->out_dims() == 4); num_samples = in_layer->out_dim_size(3); in_ch = in_layer->out_dim_size(2); in_h = in_layer->out_dim_size(1); in_w = in_layer->out_dim_size(0); reg = _reg; assert( (in_h + 2 * _pad - _f_h) % _stride == 0); assert( (in_w + 2 * _pad - _f_w) % _stride == 0); num_f = _num_f; f_h = _f_h; f_w = _f_w; pad = _pad; stride = _stride; // Boundary condition // This creates a padded input and avoids checking boundary // conditions while computing the actual convolution f_in_bound = BoundaryConditions::constant_exterior( in_layer->forward, 0, 0, in_w, 0, in_h); // Create parameters Image<float> W(f_w, f_h, in_ch, num_f), b(num_f); params.push_back(W); params.push_back(b); // Define forward RDom r(0, f_w, 0, f_h, 0, in_ch); // Initialize to bias forward(x, y, z, n) = b(z); forward(x, y, z, n) += W(r.x, r.y, r.z, z) * f_in_bound(x*stride + r.x - pad, y*stride + r.y - pad, r.z, n); if (schedule) { forward.update().reorder(y, x, r.z); // blocking spatially with vectorization //f_in_bound.compute_at(f_simple, n); forward.compute_root(); forward.fuse(z, n, par).parallel(par); forward.update().reorder(x, y, r.z); forward.update().split(y, y, y_t, y_block_size); forward.update().split(z, z, z_t, o_block_size); forward.update().reorder(y_t, z_t, y, r.z, z); forward.update().vectorize(x, vec_len); forward.update().fuse(z, n, par).parallel(par); //forward.update().fuse(y, par, par).parallel(par); forward.update().unroll(r.x); forward.update().unroll(r.y); // There are performance implications to this and seems to // be incompatible with some schedules. Have to investigate // this more closely. //f_in_bound.compute_at(forward, n); f_in_bound.compute_at(forward, z_t); } } void back_propagate(Func dout) { assert(dout.defined()); if (!f_in_grad.defined()) { Func dW, db; int out_w = this->out_dim_size(0); int out_h = this->out_dim_size(1); Image<float> W = params[0]; Image<float> b = params[1]; RDom r1(0, out_w, 0, out_h, 0, num_samples); // intialize to regularized weights dW(x, y, z, n) = cast(dout.output_types()[0], reg * W(x, y, z, n)); dW(x, y, z, n) += dout(r1.x, r1.y, n, r1.z) * f_in_bound(r1.x*stride + x - pad, r1.y*stride + y - pad, z, r1.z); f_param_grads.push_back(dW); // intialize to zero db(x) = cast(dout.output_types()[0], 0); db(x) += dout(r1.x, r1.y, x, r1.z); f_param_grads.push_back(db); RDom r2(0, num_f); // intialize to zero f_in_grad(x, y, z, n) = cast(dout.output_types()[0], 0); f_in_grad(x, y, z, n) += dout(x, y, r2.x, n) * W(x, y, z, r2.x); // Create storage for gradients and caching params Image<float> W_grad(f_w, f_h, in_ch, num_f); param_grads.push_back(W_grad); Image<float> W_cache(f_w, f_h, in_ch, num_f); params_cache.push_back(W_cache); Image<float> b_grad(num_f); param_grads.push_back(b_grad); Image<float> b_cache(num_f); params_cache.push_back(b_cache); in_layer->back_propagate(f_in_grad); } } int out_dims() { return 4; } int out_dim_size( int i) { assert(i < 4); int size = 0; if (i == 0) size = (1 + (in_w + 2 * pad - f_w)/stride); else if (i == 1) size = (1 + (in_h + 2 * pad - f_h)/stride); else if (i == 2) size = num_f; else if (i == 3) size = num_samples; return size; } }; class MaxPooling: public Layer { public: // number of color channels in input in_c // height and width of the input in_h, in_w int num_samples, in_ch, in_h, in_w; // height and width of the pool // stride at which the pooling is applied int p_h, p_w, stride; Var x, y, z, n; // parameters for scheduling Var par; int vec_len = 8; MaxPooling(int _p_w, int _p_h, int _stride, Layer* in, int schedule = 0) : Layer(in) { assert(in_layer->out_dims() == 4); num_samples = in_layer->out_dim_size(3); in_ch = in_layer->out_dim_size(2); in_h = in_layer->out_dim_size(1); in_w = in_layer->out_dim_size(0); assert((in_h - _p_h) % _stride == 0); assert((in_w - _p_w) % _stride == 0); p_w = _p_w; p_h = _p_h; stride = _stride; // Define forward Func in_f = in_layer->forward; RDom r(0, p_w, 0, p_h); forward(x, y, z, n) = maximum(in_f(x * stride + r.x, y * stride + r.y, z, n)); if (schedule) { forward.vectorize(x, vec_len); forward.compute_root().fuse(z, n, par).parallel(par); } } void back_propagate(Func dout) { assert(dout.defined()); if (!f_in_grad.defined()) { Func in_f = in_layer->forward; Func pool_argmax; RDom r1(0, p_w, 0, p_h); pool_argmax(x, y, z, n) = argmax(in_f(x * stride + r1.x, y * stride + r1.y, z, n)); pool_argmax.compute_root(); RDom r2(0, this->out_dim_size(0), 0, this->out_dim_size(1)); f_in_grad(x, y, z, n) = cast(dout.output_types()[0], 0); Expr x_bin = clamp(r2.x * stride + pool_argmax(r2.x, r2.y, z, n)[0], 0, in_w); Expr y_bin = clamp(r2.y * stride + pool_argmax(r2.x, r2.y, z, n)[1], 0, in_h); f_in_grad(x_bin, y_bin, z, n) += dout(r2.x, r2.y, z, n); in_layer->back_propagate(f_in_grad); } } int out_dims() { return 4; } int out_dim_size( int i) { assert(i < 4); int size = 0; if (i == 0) size = 1 + ((in_w - p_w)/stride); else if (i == 1) size = 1 + ((in_h - p_h)/stride); else if (i == 2) size = in_layer->out_dim_size(2); else if (i == 3) size = num_samples; return size; } }; class DataLayer: public Layer { public: int in_w, in_h, in_ch, num_samples; Var x, y, z, n; DataLayer(int _in_w, int _in_h, int _in_ch, int _num_samples, Image<float> &data) : Layer(0) { in_w = _in_w; in_h = _in_w; in_ch = _in_ch; num_samples = _num_samples; // Define forward forward(x, y, z, n) = data(x, y, z, n); } // Nothing to propagate void back_propagate(Func dout) { assert(dout.defined()); return; } int out_dims() { return 4; } int out_dim_size( int i) { assert(i < 4); int size = 0; if (i == 0) size = in_w; else if (i == 1) size = in_h; else if (i == 2) size = in_ch; else if (i == 3) size = num_samples; return size; } }; class Flatten: public Layer { public: Var x, y, z, n; int out_width; int num_samples; Flatten(Layer *in, int schedule = 0) : Layer(in) { assert(in->out_dims() >= 2 && in->out_dims() <= 4); num_samples = in_layer->out_dim_size(in_layer->out_dims() - 1); // Define forward if (in_layer->out_dims() == 2) { out_width = in_layer->out_dim_size(0); forward(x, n) = in_layer->forward(x, n); } else if (in_layer->out_dims() == 3) { int w = in_layer->out_dim_size(0); int h = in_layer->out_dim_size(1); out_width = w * h; forward(x, n) = in_layer->forward(x%w, (x/w), n); } else if (in_layer->out_dims() == 4) { int w = in_layer->out_dim_size(0); int h = in_layer->out_dim_size(1); int c = in_layer->out_dim_size(2); out_width = w * h * c; forward(x, n) = in_layer->forward(x%w, (x/w)%h, x/(w*h), n); } // schedule if (schedule) { forward.compute_root().parallel(n); } } void back_propagate(Func dout) { assert(dout.defined()); if(!f_in_grad.defined()) { if(in_layer->out_dims() == 2) f_in_grad(x, n) = dout(x, n); else if(in_layer->out_dims() == 3) { int w = in_layer->out_dim_size(0); f_in_grad(x, y, n) = dout(y*w + x, n); } else if (in_layer->out_dims() == 4) { int w = in_layer->out_dim_size(0); int h = in_layer->out_dim_size(1); f_in_grad(x, y, z, n) = dout(z*w*h + y*w + x, n); } in_layer->back_propagate(f_in_grad); } } int out_dims() { return 2; } int out_dim_size( int i) { assert(i < 2); int size = 0; if (i == 0) size = out_width; else if (i == 1) size = num_samples; return size; } }; class BatchNorm: public Layer { public: Var x, y, z, w; int vec_len = 8; float epsilon; int num_samples, in_ch, in_h, in_w; Func std; Func normalize; BatchNorm(Layer* in, float _epsilon = 0.001, int schedule = 0) : Layer(in) { Func in_f = in_layer->forward; epsilon = _epsilon; num_samples = in_layer->out_dim_size(3); in_ch = in_layer->out_dim_size(2); in_h = in_layer->out_dim_size(1); in_w = in_layer->out_dim_size(0); // Define forward Func c_mean; RDom r_m(0, num_samples); c_mean(x, y, z) = sum(in_f(x, y, z, r_m)) / num_samples; RDom r_n(0, num_samples); normalize(x, y, z) = sum((in_f(x, y, z, r_n) - c_mean(x, y, z)) * (in_f(x, y, z, r_n) - c_mean(x, y, z))) / num_samples; std(x, y, z, w) = (in_f(x, y, z, w) - c_mean(x, y, z)) / sqrt(normalize(x, y, z) + epsilon); std.compute_root(); // Create parameters Image<float> W(in_w, in_h, in_ch), b(in_w, in_h, in_ch); params.push_back(W); params.push_back(b); forward(x, y, z, w) = b(x, y, z) + W(x, y, z) * std(x, y, z, w); //TODO: Implement schedule for optimizing speed if (schedule) { } } void back_propagate(Func dout) { assert(dout.defined()); if (!f_in_grad.defined()) { Func in_f = in_layer->forward; switch(in_layer->out_dims()) { case 1: break; case 2: break; case 3: break; case 4: { Func dW, db; RDom r(0, num_samples); //Compute db for the function db(x, y, z) = cast(dout.output_types()[0], 0); db(x, y, z) += sum(dout(x, y, z, r)); //Var fused_1; f_param_grads.push_back(db); //Compute dW for the function Func mult_1; mult_1(x, y, z, w) = dout(x, y, z, w) * std(x, y, z, w); std.compute_root(); dW(x, y, z) = cast(dout.output_types()[0], 0); dW(x, y, z) += sum(mult_1(x, y, z, r)); f_param_grads.push_back(dW); //Compute dout for the function Image<float> gamma = params[0]; Func dxhat; dxhat(x, y, z, w) = dout(x, y, z, w) * gamma(x, y, z); Func inv_var; inv_var(x, y, z) = 1 / (num_samples * sqrt(normalize(x, y, z) + epsilon)); inv_var.compute_root(); Func mult_2; mult_2(x, y, z, w) = dxhat(x, y, z, w) * std(x, y, z, w); mult_2.compute_root(); f_in_grad(x, y, z, w) = (num_samples * dxhat(x, y, z, w) - sum(dxhat(x, y, z, r)) - std(x, y, z, w) * sum(mult_2(x, y, z, r))) * inv_var(x, y, z); //f_in_grad.compute_root(); //f_in_grad.trace_stores(); // Create storage for gradients and caching params Image<float> W_grad(in_w, in_h, in_ch); param_grads.push_back(W_grad); Image<float> W_cache(in_w, in_h, in_ch); params_cache.push_back(W_cache); Image<float> b_grad(in_w, in_h, in_ch); param_grads.push_back(b_grad); Image<float> b_cache(in_w, in_h, in_ch); params_cache.push_back(b_grad); break; } default: assert(0); } in_layer->back_propagate(f_in_grad); } } int out_dims() { return in_layer->out_dims();} int out_dim_size( int i) { return in_layer->out_dim_size(i); } };
[ "tianjunz@dhcp-47-172.EECS.Berkeley.EDU" ]
tianjunz@dhcp-47-172.EECS.Berkeley.EDU
7533d1055fddddb3e390f344d3ed0a202a3e714e
7c45c37dcbe114822026332c9d3eb8bae720ff47
/fw/include/support/util-str.h
079899b383ab04930d46387be6120fe27ad597dd
[]
no_license
lucaspcamargo/hydrus-v2
ebc65afe2de6e30b05fa479260fed3330d294ece
169bf60860a1b7ce27953fad57e4c6bdc48b03b1
refs/heads/master
2020-03-25T04:01:46.059730
2018-08-03T03:41:52
2018-08-03T03:41:52
143,374,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,986
h
#pragma once #include <sstream> #include <string> #include <vector> #include <cstdlib> typedef std::vector<std::string> stringvec_t; typedef stringvec_t::iterator stringvec_it_t; namespace Util { bool startsWith(const char *pre, const char *str) { size_t lenpre = strlen(pre), lenstr = strlen(str); return lenstr < lenpre ? false : strncmp(pre, str, lenpre) == 0; } long parseLong( const std::string & str, int begin = 0, int end = -1) { if(end == -1) end = str.length(); if(begin != 0 || end != str.length()) return strtol(str.substr(begin, end - begin).c_str(), 0, 10); else return strtol(str.c_str(), 0, 10); } int parseInt( const std::string & str, int begin = 0, int end = -1) { return (int) parseLong(str, begin, end); } double parseDouble( const std::string & str, int begin = 0, int end = -1) { if(end == -1) end = str.length(); if(begin != 0 || end != str.length()) return strtod(str.substr(begin, end - begin).c_str(), 0); else return strtod(str.c_str(), 0); } float parseFloat( const std::string & str, int begin = 0, int end = -1) { return (float) parseDouble(str, begin, end); } // from stackoverflow std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { if(item.length() && item[item.length()-1] == delim) item.erase(item.length() -1); elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } // end stackoverflow }
[ "camargo@lisha.ufsc.br" ]
camargo@lisha.ufsc.br
6009430f47a810c3f300e18d1367f2172d19d4ca
8bad57b1b5b08e9dada6ad89271d406a46117efb
/Assignment3/Assignment3.cpp
1cd9b7ec3c40f1292f4b95a46743cdfc681715cc
[]
no_license
blarsen005/bjornlarsen-CSCI20-Spr2017
c66030b2cea4199abe785003402bbc11b6793c57
b3f3c920304b679d2b40f32152c49628114724ad
refs/heads/master
2021-01-11T15:57:12.114412
2017-05-23T05:04:44
2017-05-23T05:04:44
79,965,072
0
0
null
null
null
null
UTF-8
C++
false
false
18,607
cpp
// Bjorn Larsen // 4/6/2017 /* Program Description: This program allows the user to play "Rock Paper Scissors Lizard Spock" against a computer. The computer chooses one of the five options and the user chooses one. The program determines who has won each round and outputs current score at the end of each round. The user can choose an option of best out of 3, 5, or 7 rounds. The program determines who wins based on who reaches required number of rounds first. Here are the specific rules to the game: Scissors cuts Paper Paper covers Rock Rock crushes Lizard Lizard poisons Spock Spock smashes Scissors Scissors decapitates Lizard Lizard eats Paper Paper disproves Spock Spock vaporizes Rock Rock crushes Scissors Pseudocode: Create "Game" class: private data includes: Rounds computer/player needs to win Rounds computer/player has won Choice (RPSLS) Choice as an integer (for use in switch case) Mutator function to select random option for computer's choice (rock, paper, scissors, lizard, or spock) Uses Random Number Generator and switch case Mutator function to select player's choice Takes user input Do-while loop to set choice in private data. Accessor function to return selection (computer and player) Mutator function: while loop with nested switch case to turn number of rounds into rounds needed to win Default is to reenter number of rounds, while loop repeats Accessor function called in round of play Function to adjust round parameters Function to return rounds won Constructors: set number of rounds to 3, computer and player to rock Main: User cin number of rounds Call mutator function for rounds needed for computer/player to win While loop for round of play: Condition: Rounds needed to win is less than rounds won by either player Call function to select player choice Call computer choice function Switch conditions for user choice (RPSLS): Condition for computer wins (2 selections) Accessor functions for choices on both sides; output computer choice beats player choice Rounds won by computer +1 Condition for player wins Accessor functions for choices on both sides; output player choice beats computer choice Rounds won by player +1 Condition for tie Accessor functions for choices on both sides; output both sides cancel No Rounds won change Output the current score at the end of the round If Rounds needed for computer to win > Rounds for player, computer wins! If Rounds needed for player to win > round for computer, player wins! */ #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; //Create "Computer" class class Computer { //Create private data members for rounds to win, rounds that have been won, choice, and choice integer private: //Rounds computer/player needs to win int rounds_to_win; //Rounds computer/player has won int rounds_won; //Choice (RPSLS) string choice_; //Choice as an integer (for use in switch case) int choice_integer; //In public, create mutator/accessor functions for choices and rounds, and declare constructor. public: //Mutator function to select random option for computer's choice (rock, paper, scissors, lizard, or spock) void SetComputerChoice() { //Uses Random Number Generator and Switch case srand(time(0)); //This sets random numbers to a seed based on the current time. int randomNum = 0; randomNum = (rand() % 5) + 1; //% 100 sets random number range 0-4. +1 changes it to 1-5. switch (randomNum) { //Computer selects choice based on the randomly generated number case 1: choice_ = "rock"; choice_integer = 1; break; case 2: choice_ = "paper"; choice_integer = 2; break; case 3: choice_ = "scissors"; choice_integer = 3; break; case 4: choice_ = "lizard"; choice_integer = 4; break; case 5: choice_ = "spock"; choice_integer = 5; break; default: choice_ = "rock"; choice_integer = 1; } return; } //Accessor function to return selection (computer and player) string GetChoice() { //For use in telling player results return choice_; } int GetChoiceInteger() { //For use in determining outcome of results return choice_integer; } //Mutator function: while loop with nested switch case to turn number of rounds into rounds needed to win void SetNumRoundsToWin(int& rounds) { //& used to ascribe rounds a value of zero to reactive do-while loop in main switch (rounds) { case 3: //These cases are equivalent to the operation: rounds_to_win = rounds / 2 + 1 rounds_to_win = 2; break; case 5: rounds_to_win = 3; break; case 7: rounds_to_win = 4; break; //Default is to reenter number of rounds, while loop repeats default: rounds = 0; //This is just a convention to active the loop break; } } //Accessor function called in round of play int GetNumRoundsToWin() { return rounds_to_win; } //Function to adjust round parameters void IncreaseNumRoundsWon() { rounds_won = rounds_won + 1; return; } //Function to return rounds won int GetNumRoundsWon() { return rounds_won; } //Constructor Function Computer(); }; //Create "Player" class Computer::Computer() { rounds_to_win = 2; rounds_won = 0; choice_ = "rock"; choice_integer = 0; return; } //Create "Player" class class Player { //Create private data members for rounds to win, rounds that have been won, choice, and choice integer private: //Rounds computer/player needs to win int rounds_to_win; //Rounds computer/player has won int rounds_won; //Choice (RPSLS) string choice_; //Choice as an integer (for use in switch case) int choice_integer; //In public, create mutator/accessor functions for choices and rounds, and declare constructor. public: //Mutator function to select player's choice void SetPlayerChoice(string choice) { //Takes user input choice_ = choice; choice_integer = 0; //Do-while loop to set choice in private data. while (choice_integer == 0) { if (choice_ == "rock") { choice_integer = 1; } else if (choice_ == "paper") { choice_integer = 2; } else if (choice_ == "scissors") { choice_integer = 3; } else if (choice_ == "lizard") { choice_integer = 4; } else if (choice_ == "spock") { choice_integer = 5; } else { //Player gets to re-enter input cout << "Not a valid choice. Enter rock, paper, scissors, lizard, or spock: "; cin >> choice; choice_ = choice; } } return; } //Accessor function to return selection (computer and player) string GetChoice() { //For use in telling player results return choice_; } int GetChoiceInteger() { //For use in determining outcome of results return choice_integer; } //Mutator function: while loop with nested switch case to turn number of rounds into rounds needed to win void SetNumRoundsToWin(int& rounds) { //& used to ascribe rounds a value of zero to reactive do-while loop in main switch (rounds) { case 3: //These cases are equivalent to the operation: rounds_to_win = rounds / 2 + 1 rounds_to_win = 2; break; case 5: rounds_to_win = 3; break; case 7: rounds_to_win = 4; break; //Default is to reenter number of rounds, while loop repeats default: rounds = 0; //This is just a convention to active the loop break; } } //Accessor function called in round of play int GetNumRoundsToWin() { return rounds_to_win; } //Function to adjust round parameters void IncreaseNumRoundsWon() { rounds_won = rounds_won + 1; return; } //Function to return rounds won int GetNumRoundsWon() { return rounds_won; } //Constructor Function Player(); }; //Constructors: set number of rounds to 3, computer and player to rock Player::Player() { rounds_to_win = 2; rounds_won = 0; choice_ = "rock"; choice_integer = 0; return; } int main() { string choice = "rock"; int rounds = 0; Computer computer; Player player; //User cin number of rounds while (rounds == 0) { cout << "Set number of rounds (3, 5, or 7): "; cin >> rounds; //Call mutator function for rounds needed for computer/player to win computer.SetNumRoundsToWin(rounds); player.SetNumRoundsToWin(rounds); } cout << endl; //While loop for round of play //Condition: Rounds needed to win is less than rounds won by either player while (computer.GetNumRoundsWon() < computer.GetNumRoundsToWin() && player.GetNumRoundsWon() < player.GetNumRoundsToWin()) { //Num Rounds to Win is constant for both objects. //Call function to select player choice cout << "Enter rock, paper, scissors, lizard, or spock: "; cin >> choice; player.SetPlayerChoice(choice); //Call computer choice function computer.SetComputerChoice(); cout << "Player: " << player.GetChoice() << endl; cout << "Computer: " << computer.GetChoice() << endl; /* Switch conditions for user choice (RPSLS): Condition for computer wins (2 selections) Accessor functions for choices on both sides; output computer choice beats player choice Rounds won by computer +1 Condition for player wins Accessor functions for choices on both sides; output player choice beats computer choice Rounds won by player +1 Condition for tie Accessor functions for choices on both sides; output both sides cancel No Rounds won change */ switch (player.GetChoiceInteger()) { case 1: //Computer choice options nested in player choice options switch (computer.GetChoiceInteger()) { case 3: case 4: cout << "Player Wins Round." << endl; player.IncreaseNumRoundsWon(); break; case 2: case 5: cout << "Computer Wins Round." << endl; computer.IncreaseNumRoundsWon(); break; case 1: cout << "Draw." << endl; break; default: cout << "Error." << endl; return 2; //This indicates possible issue with the computer choice generation. } break; case 2: switch (computer.GetChoiceInteger()) { case 1: case 5: cout << "Player Wins Round." << endl; player.IncreaseNumRoundsWon(); break; case 3: case 4: cout << "Computer Wins Round." << endl; computer.IncreaseNumRoundsWon(); break; case 2: cout << "Draw." << endl; break; default: cout << "Error." << endl; return 2; //This indicates possible issue with the computer choice generation. } break; case 3: switch (computer.GetChoiceInteger()) { case 2: case 4: cout << "Player Wins Round." << endl; player.IncreaseNumRoundsWon(); break; case 1: case 5: cout << "Computer Wins Round." << endl; computer.IncreaseNumRoundsWon(); break; case 3: cout << "Draw." << endl; break; default: cout << "Error." << endl; return 2; //This indicates possible issue with the computer choice generation. } break; case 4: switch (computer.GetChoiceInteger()) { case 5: case 2: cout << "Player Wins Round." << endl; player.IncreaseNumRoundsWon(); break; case 3: case 1: cout << "Computer Wins Round." << endl; computer.IncreaseNumRoundsWon(); break; case 4: cout << "Draw." << endl; break; default: cout << "Error." << endl; return 2; //This indicates possible issue with the computer choice generation. } break; case 5: switch (computer.GetChoiceInteger()) { case 1: case 3: cout << "Player Wins Round." << endl; player.IncreaseNumRoundsWon(); break; case 4: case 2: cout << "Computer Wins Round." << endl; computer.IncreaseNumRoundsWon(); break; case 5: cout << "Draw." << endl; break; default: cout << "Error." << endl; return 2; //This indicates possible issue with the computer choice generation. } break; default: //This shouldn't get used but exists just in case. cout << "Invalid. Redo:" << endl; break; } //Output the current score at the end of the round cout << "Player: " << player.GetNumRoundsWon() << " Computer: " << computer.GetNumRoundsWon() << endl; cout << endl; } //If Rounds needed for player to win > round for computer, player wins! if (player.GetNumRoundsWon() > computer.GetNumRoundsWon()) { cout << "You Win!" << endl; } //If Rounds needed for computer to win > Rounds for player, computer wins! else if (player.GetNumRoundsWon() < computer.GetNumRoundsWon()) { cout << "You Lose!" << endl; } else { cout << "Error" << endl; return 3; //This indicates possible error in setting the round conditions. } return 0; }
[ "blarsen005@student.butte.edu" ]
blarsen005@student.butte.edu
4208dccd4bd4bf318c61dbad0e0b7da23ea8a38a
4da5ea9c5a1d48fe519c716d22a1e61b554387fe
/main/web/WebServer.cpp
b95330ff1ec56c17f70260fc01b67cd618e68bce
[ "MIT" ]
permissive
greatriver007/Homepoint
fbbeccb88e00e1aea7cd81b2f3c8935b7e8cd8e5
69bf30fb089bfcf7141de01d5766dddb9af45bac
refs/heads/master
2021-01-07T12:19:09.209949
2020-02-15T21:37:16
2020-02-15T21:37:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
#include <AppContext.h> #include <fs/Filesystem.h> #include <web/WebServer.h> #include "SPIFFS.h" #include "SPIFFSEditor.h" namespace web { WebServer::WebServer(std::shared_ptr<ctx::AppContext> appCtx, WebCredentials webCredentials) : mpAppContext(appCtx), mCredentials(webCredentials) { mpServer = std::make_unique<AsyncWebServer>(80); using namespace std::placeholders; const auto username = std::get<0>(mCredentials); const auto password = std::get<1>(mCredentials); mpServer->serveStatic("/", SPIFFS, "/web").setAuthentication(username.c_str(), password.c_str()); mpServer->addHandler(new SPIFFSEditor(SPIFFS, username.c_str(), password.c_str())); mpServer->on("/reboot.htm", HTTP_POST, std::bind(&WebServer::handleRebootRequest, this, _1)); } void WebServer::startServer() { mpServer->begin(); } void WebServer::handleRebootRequest(AsyncWebServerRequest *request) { ESP.restart(); } } // namespace web
[ "matthias@s-r-n.de" ]
matthias@s-r-n.de
dc9af139712ec474c3fb33143a295281e5a27d0b
a209c498dd6523a6c6e451d936dcab577fe2b733
/Tower/Intermediate/Build/Win64/UE4Editor/Inc/Tower/Enemy.gen.cpp
a01617758f593c21540028ce4f1086ab7a08d820
[]
no_license
AidanMJW/TowerDefenceAssignment
f96bd7f92fdd112398b4c82680eee9e24d5c53a9
9c713ce22b6d452043431477669054a3f48e6972
refs/heads/master
2020-06-27T23:29:26.866170
2019-08-08T07:39:04
2019-08-08T07:39:04
200,079,512
0
0
null
null
null
null
UTF-8
C++
false
false
4,152
cpp
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "Tower/Enemy.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeEnemy() {} // Cross Module References TOWER_API UClass* Z_Construct_UClass_AEnemy_NoRegister(); TOWER_API UClass* Z_Construct_UClass_AEnemy(); ENGINE_API UClass* Z_Construct_UClass_AActor(); UPackage* Z_Construct_UPackage__Script_Tower(); ENGINE_API UClass* Z_Construct_UClass_UStaticMeshComponent_NoRegister(); // End Cross Module References void AEnemy::StaticRegisterNativesAEnemy() { } UClass* Z_Construct_UClass_AEnemy_NoRegister() { return AEnemy::StaticClass(); } struct Z_Construct_UClass_AEnemy_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_body_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_body; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_AEnemy_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AActor, (UObject* (*)())Z_Construct_UPackage__Script_Tower, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AEnemy_Statics::Class_MetaDataParams[] = { { "IncludePath", "Enemy.h" }, { "ModuleRelativePath", "Enemy.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AEnemy_Statics::NewProp_body_MetaData[] = { { "Category", "Enemy" }, { "EditInline", "true" }, { "ModuleRelativePath", "Enemy.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AEnemy_Statics::NewProp_body = { UE4CodeGen_Private::EPropertyClass::Object, "body", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x001000000008000d, 1, nullptr, STRUCT_OFFSET(AEnemy, body), Z_Construct_UClass_UStaticMeshComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AEnemy_Statics::NewProp_body_MetaData, ARRAY_COUNT(Z_Construct_UClass_AEnemy_Statics::NewProp_body_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AEnemy_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AEnemy_Statics::NewProp_body, }; const FCppClassTypeInfoStatic Z_Construct_UClass_AEnemy_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<AEnemy>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AEnemy_Statics::ClassParams = { &AEnemy::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x009000A0u, nullptr, 0, Z_Construct_UClass_AEnemy_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_AEnemy_Statics::PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_AEnemy_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_AEnemy_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_AEnemy() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AEnemy_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(AEnemy, 3891562507); static FCompiledInDefer Z_CompiledInDefer_UClass_AEnemy(Z_Construct_UClass_AEnemy, &AEnemy::StaticClass, TEXT("/Script/Tower"), TEXT("AEnemy"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(AEnemy); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "Aidan_Walker@live.com.au" ]
Aidan_Walker@live.com.au
b4eeab2ca8b8c1beae8b84a7404fa22e734f1f60
dbec1490074c38e0a6a9fc8981a51b169f438412
/src/main.cpp
f2318294d15a37630a09ba4f2eb490ee352be66a
[ "MIT" ]
permissive
mincardona/xmphash
e85239f5a432df15944e1b03c681e9cb8ee76e72
c602bd628a9e4a1b22a2e733883a8cfe75fc5a9e
refs/heads/master
2023-02-23T05:46:35.861972
2021-01-29T04:30:42
2021-01-29T04:30:42
328,828,359
0
0
null
null
null
null
UTF-8
C++
false
false
9,144
cpp
#include <cassert> #include <cstdio> #include <cstring> #include <optional> #include <string> #include <thread> #include <utility> #include <vector> #include <getopt.h> #include <xmphash/hasher.hpp> #include <xmphash/xplat.hpp> namespace xmph = mji::xmph; #define DIE(S) do { std::fprintf(stderr, S); exit(-1); } while (false); unsigned int hardware_thread_count() { // clamp to minimum of 1 return std::max<unsigned int>(std::thread::hardware_concurrency(), 1); } namespace karg { enum Arg : int { // single-char compatible CHECK_INTEGRITY = 'i', USE_BINARY_MODE = 'b', USE_TEXT_MODE = 't', USE_ZERO_TERMINATE = 'z', CONTINUE = 'c', // long only HELP = 1001 }; constexpr char optShortStr[] = "ibtzc"; } // namespace karg struct ProcFlags { public: bool checkIntegrity = false; bool binaryMode = true; bool zeroTerminate = false; bool help = false; bool doContinue = false; }; // note: returned pos args excludes program name std::optional<std::pair<ProcFlags, std::vector<std::string>>> parseCliArgs(int argc, char** argv) { ProcFlags procFlags; bool fileReadModeSet = false; ::option longOpts[] = { {"check-integrity", no_argument, nullptr, karg::CHECK_INTEGRITY}, {"binary", no_argument, nullptr, karg::USE_BINARY_MODE}, {"text", no_argument, nullptr, karg::USE_TEXT_MODE}, {"zero", no_argument, nullptr, karg::USE_ZERO_TERMINATE}, {"continue", no_argument, nullptr, karg::CONTINUE}, {"help", no_argument, nullptr, karg::HELP}, {nullptr, 0, nullptr, 0} }; int optionIdx = 0; // enable automatically printing error messages for unknown options or // missing required arguments ::opterr = 1; for (;;) { // Arguments to short and long options will be stored in ::optarg // (char*) // Unknown option characters, or characters with missing arguments, will // be stored in ::optopt (int) // The optionIdx variable contains the index of the detected long option // entry in the longOpts array (so the name is easily obtained) int c = ::getopt_long(argc, argv, karg::optShortStr, longOpts, &optionIdx); if (c == -1) { // no more options break; } else if (c == '?' || c == ':') { // unknown option char or option char with missing argument, stored // in ::optopt (char*) // TODO: handle this std::fprintf(stderr, "getopt_long returned %d\n", c); return {}; } // TODO: what happens if a long option is missing a required argument? // Does getopt_long just set ::optarg to null and expect that you check // whether the argument should have been supplied using optionIdx? // Also check returning ':' on missing arguments if ':' is the first // character in the short string. // Assuming for now that it just returns '?' or ':'. switch (c) { case karg::CHECK_INTEGRITY: procFlags.checkIntegrity = true; break; case karg::USE_BINARY_MODE: if (fileReadModeSet) { std::fprintf(stderr, "File read mode set twice\n"); return {}; } fileReadModeSet = true; procFlags.binaryMode = true; break; case karg::USE_TEXT_MODE: if (fileReadModeSet) { fprintf(stderr, "File read mode set twice\n"); return {}; } fileReadModeSet = true; procFlags.binaryMode = false; break; case karg::USE_ZERO_TERMINATE: procFlags.zeroTerminate = true; break; case karg::CONTINUE: procFlags.doContinue = true; break; case karg::HELP: procFlags.help = true; break; case 0: // a long option requested that a value be stored instead of // returned. We don't specify any such options assert(false); continue; default: std::fprintf(stderr, "Unexpected getopt_long return value %d\n", c); return {}; } } return std::optional<std::pair<ProcFlags, std::vector<std::string>>>( std::in_place, std::move(procFlags), std::vector<std::string>(argv + ::optind, argv + argc) ); } void printHelp() { std::printf("[insert help]\n"); } class CFileWrapper final { public: std::FILE* fp; CFileWrapper(std::FILE* fp) : fp(fp) {} CFileWrapper(const CFileWrapper&) = delete; CFileWrapper& operator=(const CFileWrapper&) = delete; CFileWrapper(CFileWrapper&& other) : fp(other.fp) { other.fp = nullptr; } CFileWrapper& operator=(CFileWrapper&& other) { fp = other.fp; other.fp = nullptr; return *this; } int close() { if (fp != nullptr) { int ret = std::fclose(fp); fp = nullptr; return ret; } else { return EOF; } } ~CFileWrapper() { close(); } }; int main(int argc, char** argv) { std::printf("Detected %u hardware threads\n", hardware_thread_count()); std::optional<std::pair<ProcFlags, std::vector<std::string>>> cliArgs = parseCliArgs(argc, argv); if (!cliArgs) { std::fprintf(stderr, "Error processing command arguments\n"); return -1; } ProcFlags& procFlags = cliArgs->first; std::vector<std::string>& posArgs = cliArgs->second; if (procFlags.help) { printHelp(); return 0; } else if (posArgs.size() != 2) { std::fprintf(stderr, "Wrong number of positional arguments - expected 2\n"); return -1; } std::vector<std::string> algoEls = xmph::splitOnChar(posArgs[0].data(), ','); assert(algoEls.size() > 0); if (procFlags.checkIntegrity) { assert("not implemented"); } else { // compute hashes of multiple files // for algo in algoEls, construct a hasher std::vector<std::unique_ptr<xmph::Hasher>> hashers; // TODO: should duplicate hash names be an error? for (const auto& algoName : algoEls) { if (algoName == "crc32") { hashers.push_back(std::make_unique<xmph::Crc32Hasher>()); } else { // TODO: could throw! hashers.push_back(std::make_unique<xmph::EvpHasher>(algoName.c_str())); } } // open file const std::string& inFileName = posArgs[1]; std::FILE* inFilePtr = nullptr; errno = 0; if (inFileName == "-") { // stdin if (procFlags.binaryMode && !mji::xplat::reopenStdinAsBinary()) { std::fprintf(stderr, "Failed to reopen stdin as binary"); return -1; } inFilePtr = stdin; } else { const char* openMode; if (procFlags.binaryMode) { openMode = "rb"; } else { openMode = "r"; } inFilePtr = std::fopen(inFileName.c_str(), openMode); } if (!inFilePtr) { std::fprintf(stderr, "Unable to open file: %s", std::strerror(errno)); return -1; } CFileWrapper inFile{inFilePtr}; // send file data through hashers constexpr std::size_t inBufSize = 4096; auto inBuf = std::make_unique<unsigned char[]>(inBufSize); // this is the critical loop for (;;) { std::size_t bytesRead = std::fread(inBuf.get(), 1, inBufSize, inFile.fp); if (bytesRead == 0) { if (std::feof(inFile.fp)) { break; } else { std::fprintf(stderr, "Failed while reading data from file\n"); return -1; } } for (auto& hasher : hashers) { if (!hasher->consume(inBuf.get(), bytesRead)) { std::fprintf(stderr, "Hasher \"%s\" failed to consume data\n", hasher->getName()); return -1; } } } // close file inFile.close(); std::vector<std::unique_ptr<unsigned char[]>> digests; // finalize hashers for (auto& hasher : hashers) { digests.push_back(std::make_unique<unsigned char[]>(xmph::hash_max_digest_size)); if (!hasher->finalize(digests.back().get(), xmph::hash_max_digest_size)) { std::fprintf(stderr, "Failed to finalize hasher \"%s\"\n", hasher->getName()); return -1; } } // print results for (std::size_t i = 0; i < hashers.size(); i++) { std::printf("%s: %s\n", hashers[i]->getName(), xmph::bytesToStr(digests[i].get(), hashers[i]->getDigestSize()).c_str() ); } } return 0; }
[ "michael.incardona@outlook.com" ]
michael.incardona@outlook.com
93216919c81822276449380ae255be9a128de0dd
02a7715694c10ad7cdb5fca2db5db4d2c14b358e
/include/cslib/data_structure/linked_list.hpp
1113f2e587e66516abd079052a837b6c5074ee5f
[ "MIT" ]
permissive
sandyre/cslib
b1e96bea64be7c42e87f534af15aaabcdc44ba51
2ee0fe8a8b6b7fc47858ae47fa820cf70f8aa4d3
refs/heads/master
2020-03-23T21:54:52.280831
2018-11-19T18:09:28
2018-11-19T18:09:28
142,140,984
2
0
MIT
2018-11-19T18:09:29
2018-07-24T10:09:52
C++
UTF-8
C++
false
false
2,291
hpp
#ifndef CSLIB_DATA_STRUCTURE_LINKED_LIST_HPP #define CSLIB_DATA_STRUCTURE_LINKED_LIST_HPP // MIT License // // Copyright (c) 2018 Alexandr Borzykh // // 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> namespace cslib { namespace data_structure { /* Name: Singly linked list * * TODO: * 1. operations complexity */ template < typename ValueT > class singly_linked_list { using PassingValueT = typename std::conditional<std::is_fundamental<ValueT>::value, ValueT, const ValueT&>::type; private: struct list_node { ValueT Value; list_node* Next; public: list_node(PassingValueT value, list_node* next = std::nullptr) : Value(value), Next(next) { } }; private: list_node* _root; public: singly_linked_list() : _root(std::nullptr), _size() { } ~singly_linked_list() { clear(); } void push_front(PassingValueT value) { _root = new list_node(value, _root); } void pop_front() { if (!_root) return; list_node* newRoot = _root->Next; delete _root; _root = newRoot; } /* void erase_after(iterator); */ /* void insert_after(iterator); */ /* void swap(iterator, iterator); */ void clear() { while (_root) pop_front(); } }; }} #endif
[ "aleksandr.borzyh@gs-labs.ru" ]
aleksandr.borzyh@gs-labs.ru
c5c9e1fd400e53b48b6d6e0112d36c476d5989c5
f418d0691d5fc49090325bc3bf022f27973967d2
/third_party/odb-2.5.0-x86_64-windows/include/libbutl/ft/shared_mutex.hxx
2ee5546e4b6182a63ed7d707e02c58bcd77354a8
[]
no_license
asdlei99/libodb-release
c4350d35a67608c7ace92c5760cd4e30f469db24
c4a4dfb7f490ba367f10477963712e4395acfebd
refs/heads/master
2020-08-22T19:25:02.023815
2019-09-29T02:48:33
2019-09-29T02:51:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,856
hxx
// file : libbutl/ft/shared_mutex.hxx -*- C++ -*- // copyright : Copyright (c) 2014-2019 Code Synthesis Ltd // license : MIT; see accompanying LICENSE file #ifndef LIBBUTL_FT_SHARED_MUTEX_HXX #define LIBBUTL_FT_SHARED_MUTEX_HXX #if defined(__clang__) # if __has_include(<__config>) # include <__config> // _LIBCPP_VERSION # endif #endif // __cpp_lib_shared_mutex // #ifndef __cpp_lib_shared_mutex // // VC has it since 1900. // # if defined(_MSC_VER) # if _MSC_VER >= 1900 # define __cpp_lib_shared_mutex 201505 # endif // // Clang's libc++ seems to have it for a while (but not before 1200) so we // assume it's there from 1200. It's also only enabled after C++14. But not // for MacOS, where it is explicitly marked as unavailable until MacOS // 10.12. // # elif defined(_LIBCPP_VERSION) && defined(_LIBCPP_STD_VER) # if _LIBCPP_VERSION >= 1200 && \ _LIBCPP_STD_VER > 14 && \ (!defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \ __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101200) # define __cpp_lib_shared_mutex 201505 # endif // // GCC libstdc++ has it since GCC 6 and it defines the feature test macro. // We will also use this for any other runtime. // # endif #endif // __cpp_lib_shared_timed_mutex // #ifndef __cpp_lib_shared_timed_mutex // // On MacOS shared_timed_mutex is marked as unavailable until MacOS // 10.12. // # if defined(_LIBCPP_VERSION) # if !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \ __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101200 # define __cpp_lib_shared_timed_mutex 201402 # endif # else # define __cpp_lib_shared_timed_mutex 201402 # endif #endif #endif // LIBBUTL_FT_SHARED_MUTEX_HXX
[ "jack.wgm@gmail.com" ]
jack.wgm@gmail.com
c9073ec171c28fa28250441ef478b28807883f88
f0cfa1f5e30845a6061fefbf87547e63b2c22b41
/devel/include/gc_msgs/ObstacleAheadMsg.h
5b2468adcde5e995b65327cb2a2d323a1482ae38
[ "MIT" ]
permissive
WeirdCoder/rss-2014-team-3
d9ba488dff5b7f17bd278a3eef135a39bdcf8e19
f7565e14de018b3fac5e2cfeb6633d32047eb70a
refs/heads/master
2021-01-01T06:55:14.626711
2014-05-06T23:25:24
2014-05-06T23:25:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,553
h
/* Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Auto-generated by genmsg_cpp from file /home/rss-student/rss-2014-team-3/src/gc_msgs/msg/ObstacleAheadMsg.msg * */ #ifndef GC_MSGS_MESSAGE_OBSTACLEAHEADMSG_H #define GC_MSGS_MESSAGE_OBSTACLEAHEADMSG_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace gc_msgs { template <class ContainerAllocator> struct ObstacleAheadMsg_ { typedef ObstacleAheadMsg_<ContainerAllocator> Type; ObstacleAheadMsg_() { } ObstacleAheadMsg_(const ContainerAllocator& _alloc) { } typedef boost::shared_ptr< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> const> ConstPtr; boost::shared_ptr<std::map<std::string, std::string> > __connection_header; }; // struct ObstacleAheadMsg_ typedef ::gc_msgs::ObstacleAheadMsg_<std::allocator<void> > ObstacleAheadMsg; typedef boost::shared_ptr< ::gc_msgs::ObstacleAheadMsg > ObstacleAheadMsgPtr; typedef boost::shared_ptr< ::gc_msgs::ObstacleAheadMsg const> ObstacleAheadMsgConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> & v) { ros::message_operations::Printer< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace gc_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/hydro/share/std_msgs/cmake/../msg'], 'gc_msgs': ['/home/rss-student/rss-2014-team-3/src/gc_msgs/msg'], 'lab5_msgs': ['/home/rss-student/rss-2014-team-3/src/lab5_msgs/msg'], 'lab6_msgs': ['/home/rss-student/rss-2014-team-3/src/lab6_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > { static const char* value() { return "d41d8cd98f00b204e9800998ecf8427e"; } static const char* value(const ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL; static const uint64_t static_value2 = 0xe9800998ecf8427eULL; }; template<class ContainerAllocator> struct DataType< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > { static const char* value() { return "gc_msgs/ObstacleAheadMsg"; } static const char* value(const ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > { static const char* value() { return " \n\ "; } static const char* value(const ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream&, T) {} ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct ObstacleAheadMsg_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator> > { template<typename Stream> static void stream(Stream&, const std::string&, const ::gc_msgs::ObstacleAheadMsg_<ContainerAllocator>&) {} }; } // namespace message_operations } // namespace ros #endif // GC_MSGS_MESSAGE_OBSTACLEAHEADMSG_H
[ "rss-student@Turtle.mit.edu" ]
rss-student@Turtle.mit.edu
2a43c356701413fb91b6f7599936aaf94c01c447
e17c43db9488f57cb835129fa954aa2edfdea8d5
/Libraries/IFC/IFC4/include/IfcLightSourcePositional.h
32ed72db54f07a72c7aa902d4a4dd2ea39009c3e
[]
no_license
claudioperez/Rts
6e5868ab8d05ea194a276b8059730dbe322653a7
3609161c34f19f1649b713b09ccef0c8795f8fe7
refs/heads/master
2022-11-06T15:57:39.794397
2020-06-27T23:00:11
2020-06-27T23:00:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,586
h
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "IfcPPBasicTypes.h" #include "IfcPPObject.h" #include "IfcPPGlobal.h" #include "IfcLightSource.h" class IFCPP_EXPORT IfcCartesianPoint; class IFCPP_EXPORT IfcPositiveLengthMeasure; class IFCPP_EXPORT IfcReal; //ENTITY class IFCPP_EXPORT IfcLightSourcePositional : public IfcLightSource { public: IfcLightSourcePositional(); IfcLightSourcePositional( int id ); ~IfcLightSourcePositional(); virtual shared_ptr<IfcPPObject> getDeepCopy( IfcPPCopyOptions& options ); virtual void getStepLine( std::stringstream& stream ) const; virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; virtual void readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<IfcPPEntity> >& map ); virtual void setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self ); virtual size_t getNumAttributes() { return 9; } virtual void getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes ); virtual void getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes ); virtual void unlinkFromInverseCounterparts(); virtual const char* className() const { return "IfcLightSourcePositional"; } virtual const std::wstring toString() const; // IfcRepresentationItem ----------------------------------------------------------- // inverse attributes: // std::vector<weak_ptr<IfcPresentationLayerAssignment> > m_LayerAssignment_inverse; // std::vector<weak_ptr<IfcStyledItem> > m_StyledByItem_inverse; // IfcGeometricRepresentationItem ----------------------------------------------------------- // IfcLightSource ----------------------------------------------------------- // attributes: // shared_ptr<IfcLabel> m_Name; //optional // shared_ptr<IfcColourRgb> m_LightColour; // shared_ptr<IfcNormalisedRatioMeasure> m_AmbientIntensity; //optional // shared_ptr<IfcNormalisedRatioMeasure> m_Intensity; //optional // IfcLightSourcePositional ----------------------------------------------------------- // attributes: shared_ptr<IfcCartesianPoint> m_Position; shared_ptr<IfcPositiveLengthMeasure> m_Radius; shared_ptr<IfcReal> m_ConstantAttenuation; shared_ptr<IfcReal> m_DistanceAttenuation; shared_ptr<IfcReal> m_QuadricAttenuation; };
[ "steva44@hotmail.com" ]
steva44@hotmail.com