blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
listlengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5cf0f3686e50a5d915e6e0dfe47c87e3e4e4656c | dc11693557b088c61c0f773ceecc55cfe1cb5a36 | /Servo_btn_fix_pelipat_baju/Servo_btn_fix_pelipat_baju.ino | ea6c9e10ffda83e00f1dfc925a618a1aafd884ae | []
| no_license | irwan75/Arduino-Project | c849c6eaa092630fc18c8378b840848ad72a5437 | 200fae5cb229a13eb6bea60b79e641555e8ef256 | refs/heads/master | 2022-06-04T00:12:16.611056 | 2020-05-04T08:40:24 | 2020-05-04T08:40:24 | 261,112,907 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | ino | #include <Servo.h>
int button = 7;
int led = 12;
int btnState = 0;
Servo servo1;
//Servo servo2;
//Servo servo3;
//Servo servo4;
void setup() {
pinMode(button, INPUT);
// pinMode(led, OUTPUT);
servo1.attach(5);
// servo2.attach(6);
// servo3.attach(8);
// servo4.attach(9);
}
void loop() {
btnState = digitalRead(button);
if(btnState==LOW){
servo1.write(90);
delay(2000);
}else{
servo1.write(0);
delay(1000);
}
}
| [
"[email protected]"
]
| |
047ac049d796bc75aabf55dc34ccddc038e13b97 | e917dd96f8485f9679702184216d5798e1782415 | /FrameWnd/WkeWebkit.h | b7bb4f050d3c4f6193daf8ec8399a70486a8e17a | []
| no_license | chxj1980/Demo-Of-Duilib | 99dd9a1f63f3b2de73f2db79b42ee6e93449bca2 | 5137921ee8f26007d6c6a23ecf58bfdcbd50b279 | refs/heads/master | 2021-09-14T09:33:37.967215 | 2018-05-11T09:37:32 | 2018-05-11T09:37:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,412 | h | #ifndef WKEWEBKIT_H
#define WKEWEBKIT_H
#include "stdafx.h"
#include "wke.h"
#pragma comment(lib,"../lib/wke.lib")
const char TM_TICKER = 1;
class CWkeWebkitUI;
class CWkeWebkitWnd : public CWindowWnd ,protected wkeBufHandler
{
friend class CWkeWebkitUI;
public:
CWkeWebkitWnd();
~CWkeWebkitWnd();
void Init(CWkeWebkitUI* pOwner);
wkeWebView GetWebView();
LPCTSTR GetWindowClassName() const;
void OnFinalMessage(HWND hWnd);
LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnMouseEvent(UINT uMsg, WPARAM wParam,LPARAM lParam, BOOL& bHandled);
LRESULT OnMouseWheel(UINT uMsg, WPARAM wParam,LPARAM lParam, BOOL& bHandled);
LRESULT OnKeyDown(UINT uMsg, WPARAM wParam,LPARAM lParam, BOOL& bHandled);
LRESULT OnKeyUp(UINT uMsg, WPARAM wParam,LPARAM lParam, BOOL& bHandled);
LRESULT OnChar(UINT uMsg, WPARAM wParam,LPARAM lParam, BOOL& bHandled);
LRESULT OnImeStartComposition(UINT uMsg, WPARAM wParam,LPARAM lParam, BOOL& bHandled);
LRESULT OnSetFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnKillFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnTimer(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnContextMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
protected:
virtual void onBufUpdated (const HDC hdc,int x, int y, int cx, int cy);
protected:
CWkeWebkitUI* m_pOwner;
wkeWebView m_pWebView;
wstring m_strUrl;
bool m_bInit;
};
class CWkeWebkitUI :public CControlUI
{
friend class CWkeWebkitWnd;
public:
CWkeWebkitUI(void);
~CWkeWebkitUI(void);
static void WkeWebkit_Init();
static void WkeWebkit_Shutdown();
LPCTSTR GetClass() const;
LPVOID GetInterface(LPCTSTR pstrName);
void DoInit();
void SetPos(RECT rc);
void DoEvent(TEventUI& event);
void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue);
void SetURL( wstring strValue);
void SetFile(wstring strValue);
wstring RunJS(wstring strValue);
void SetClientHandler(const wkeClientHandler* handler);
void GoBack();
void GoForward();
protected:
CWkeWebkitWnd *m_pWindow;
};
#endif
| [
"[email protected]"
]
| |
3ac37a172cb6db47a5d78a7559f8a80942d0f540 | a5456881ccf348327fab10e61a37129cee923a9f | /server_bot_settings.cpp | c5696d37936027106f08c2d1ae451e01cc98b090 | []
| no_license | Ashlyyn/discord_bot | 01f3d9c8085bc325ccd972b1bbe308845fcea491 | c7385cef21b60faed40a68ae7c2539c48ae7449a | refs/heads/main | 2023-06-12T13:27:01.695421 | 2021-04-11T18:38:30 | 2021-04-11T18:38:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,484 | cpp | #include "sleepy_discord/sleepy_discord.h"
#include "server_bot_settings.hpp"
ServerBotSettings::ServerBotSettings() {
logsChannelID = SleepyDiscord::Snowflake<SleepyDiscord::Channel>();
botAdminRoleID = SleepyDiscord::Snowflake<SleepyDiscord::Role>();
//mutedUsers = std::vector<SleepyDiscord::Snowflake<SleepyDiscord::User> >();
permissions = {2, 2};
}
bool ServerBotSettings::operator==(const ServerBotSettings& acrRhs) const {
if((silent == acrRhs.silent) && (noLogs == acrRhs.noLogs) && (prefix == acrRhs.prefix)
&& (logsChannelID == acrRhs.logsChannelID) && (botAdminRoleID == acrRhs.botAdminRoleID)
&& (mutedUserIDs == acrRhs.mutedUserIDs) && (permissions == acrRhs.permissions)
) {
return true;
}
else {
return false;
}
}
bool ServerBotSettings::operator!=(const ServerBotSettings& acrRhs) const {
if(!operator==(acrRhs)) {
return true;
}
else {
return false;
}
}
bool ServerBotSettingsComparator::operator()(const ServerBotSettings& acrLhs, const ServerBotSettings& acrRhs) const {
if(acrRhs == ServerBotSettings() && acrRhs != ServerBotSettings()) {
return 0;
}
else {
return 1;
}
}
bool ServerBotSettingsComparator::operator()(const SleepyDiscord::Snowflake<SleepyDiscord::Server>& acrLhs, const SleepyDiscord::Snowflake<SleepyDiscord::Server>& acrRhs) const {
if(acrLhs == SleepyDiscord::Snowflake<SleepyDiscord::Server>() && acrRhs != SleepyDiscord::Snowflake<SleepyDiscord::Server>()) {
return 0;
}
else {
return 1;
}
} | [
"[email protected]"
]
| |
2008f7a26ae69749b6205c8e3a8515f131716489 | b1f04c4f1e00f6efb78f2ce62b8735ee16bfb529 | /Bit-Manipulations/(CODECHEF)missing_a_point.cpp | 87fbf40296b17629ecc90384b17c42f4ea8131a6 | []
| no_license | hardikhere/competitive-programming | b2843737837d6dbff7570f4f29ef9329472abe92 | 0af7a77dde5a6e60319ff8b55ecba662d643ebeb | refs/heads/master | 2022-12-21T12:54:27.353378 | 2020-10-01T15:19:13 | 2020-10-01T15:19:13 | 300,214,588 | 3 | 1 | null | 2020-10-01T09:03:27 | 2020-10-01T09:03:26 | null | UTF-8 | C++ | false | false | 1,487 | cpp | #include <bits/stdc++.h>
#include <set>
#include <cstdlib>
using namespace std;
// #include <ext/pb_ds/assoc_container.hpp>
// using namespace __gnu_pbds;
#include<algorithm>
#include <typeinfo>
// cout << typeid(mm).name() << endl;
#define ff first
#define ss second
#define int long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define mii map<int,int>
#define pqb priority_queue<int>
#define pqs priority_queue<int,vi,greater<int> >
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define mod 1000000007
#define inf 1e18
#define ps(x,y) fixed<<setprecision(y)<<x
#define mk(arr,n,type) type *arr=new type[n];
#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define deb(x) cout<<#x<<" "<<x<<"\n";
int32_t main() {
FIO;
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int x; cin >> x; while (x--) {
int n; cin >> n;
int xc[4 * n - 1], yc[4 * n - 1];
int xx, yy;
for (int i = 0; i < 4 * n - 1; ++i)
{
cin >> xx >> yy;
xc[i] = xx;
yc[i] = yy;
}
int ax = 0, ay = 0;
for (int i = 0; i < 4 * n - 1; ++i)
{
ax ^= xc[i];
ay ^= yc[i];
}
cout << ax << " " << ay << "\n";
}
return 0;
}
| [
"[email protected]"
]
| |
9fd23d702bbcd2fb2b64256c918ff7e3644121f1 | 0728a2e165808cfe5651693a6e7f47804bfb085f | /rek/2013/libs/OLD_LIBS/mongo-cxx-driver-v1.6/mongo/scripting/engine_spidermonkey.h | 4617b5d878f4d91d576ed9c4ade2e45d2ca3a1c6 | [
"Apache-2.0"
]
| permissive | testTemtProj/OLD_PROJECT | 5b026e072017f5135159b0940370fda860241d39 | 9e5b165f4e8acf9003536e05dcefd33a5ae46890 | refs/heads/master | 2020-05-18T15:30:24.543319 | 2013-07-23T15:17:32 | 2013-07-23T15:17:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,374 | h | // engine_spidermonkey.h
/* Copyright 2009 10gen 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.
*/
#pragma once
#include "engine.h"
// START inc hacking
#if defined( MOZJS )
#define MOZILLA_1_8_BRANCH
#include "mozjs/jsapi.h"
#include "mozjs/jsdate.h"
#include "mozjs/jsregexp.h"
#warning if you are using an ubuntu version of spider monkey, we recommend installing spider monkey from source
#elif defined( OLDJS )
#ifdef WIN32
#include "jstypes.h"
#undef JS_PUBLIC_API
#undef JS_PUBLIC_DATA
#define JS_PUBLIC_API(t) t __cdecl
#define JS_PUBLIC_DATA(t) t
#endif
#include "jsapi.h"
#include "jsobj.h"
#include "jsdate.h"
#include "jsregexp.h"
#else
#include "js/jsapi.h"
#include "js/jsobj.h"
#include "js/jsdate.h"
#include "js/jsregexp.h"
#endif
// END inc hacking
// -- SM 1.6 hacks ---
#ifndef JSCLASS_GLOBAL_FLAGS
#warning old version of spider monkey ( probably 1.6 ) you should upgrade to at least 1.7
#define JSCLASS_GLOBAL_FLAGS 0
JSBool JS_CStringsAreUTF8(){
return false;
}
#define SM16
#endif
// -- END SM 1.6 hacks ---
#ifdef JSVAL_IS_TRACEABLE
#define SM18
#endif
#ifdef XULRUNNER
#define SM181
#endif
namespace mongo {
class SMScope;
class Convertor;
extern JSClass bson_class;
extern JSClass bson_ro_class;
extern JSClass object_id_class;
extern JSClass dbpointer_class;
extern JSClass dbref_class;
extern JSClass bindata_class;
extern JSClass timestamp_class;
extern JSClass numberlong_class;
extern JSClass minkey_class;
extern JSClass maxkey_class;
// internal things
void dontDeleteScope( SMScope * s ){}
void errorReporter( JSContext *cx, const char *message, JSErrorReport *report );
extern boost::thread_specific_ptr<SMScope> currentScope;
// bson
JSBool resolveBSONField( JSContext *cx, JSObject *obj, jsval id, uintN flags, JSObject **objp );
// mongo
void initMongoJS( SMScope * scope , JSContext * cx , JSObject * global , bool local );
bool appendSpecialDBObject( Convertor * c , BSONObjBuilder& b , const string& name , jsval val , JSObject * o );
#define JSVAL_IS_OID(v) ( JSVAL_IS_OBJECT( v ) && JS_InstanceOf( cx , JSVAL_TO_OBJECT( v ) , &object_id_class , 0 ) )
bool isDate( JSContext * cx , JSObject * o );
// JS private data must be 2byte aligned, so we use a holder to refer to an unaligned pointer.
struct BinDataHolder {
BinDataHolder( const char *c, int copyLen = -1 ) :
c_( const_cast< char * >( c ) ),
iFree_( copyLen != -1 ) {
if ( copyLen != -1 ) {
c_ = (char*)malloc( copyLen );
memcpy( c_, c, copyLen );
}
}
~BinDataHolder() {
if ( iFree_ )
free( c_ );
}
char *c_;
bool iFree_;
};
}
| [
"[email protected]"
]
| |
472e826254f08080392ca3f1018623b8002d7c3b | 673eaab40a1b13c7ce41b3f6ab580ba0855ea12a | /ED/L01Q08.cpp | 2256af779f6170dac990b3fa306df6c8a5c81cb9 | []
| no_license | marcosf63/CC | bb9b8a609b9e08ae6f59fce40c2bcade1137c5ba | 95559828c6bf1a02434b7fb3720661541aede7c7 | refs/heads/master | 2021-01-21T13:41:58.941563 | 2016-05-03T01:16:09 | 2016-05-03T01:16:09 | 45,278,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,330 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
int main() {
int i, j, n, x, k, l, **ma, **mb;
do {
printf("Digite a ordem da matriz: ");
scanf("%d", &n);
} while (n < 0 || n > 99);
do {
printf("Digite digite o numero x (1 a ordem da matriz): ");
scanf("%d", &x);
} while (x < 0 || x > n);
ma = (int **) calloc(n, sizeof(int*));
mb = (int **) calloc(x, sizeof(int*));
for (i = 0; i < n; i++)
ma[i] = (int *) calloc(n, sizeof(int));
for (i = 0; i < n - 1; i++)
mb[i] = (int *) calloc(n, sizeof(int));
srand(time(0));
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
ma[i][j] = rand() % 10 + 1;
for (i = 0 ; i < n; i++){
if (i == x - 1){
i++;
k = i - 1;
}
else
k = i < x - 1 ? i : i - 1 ;
for (j = 0; j < n; j ++){
if (j == x - 1) {
j++;
l = j - 1;
}
else
l = j < x - 1 ? j : j - 1;
mb[k][l] = ma[i][j];
}
}
printf("\n Matriz A \n\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf(" %02d", ma[i][j]);
printf("\n");
}
printf("\n Matriz B \n\n");
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1; j++)
printf(" %02d", mb[i][j]);
printf("\n");
}
return 0;
}
| [
"[email protected]"
]
| |
f4e4110ae251ed7cca0a76225c866e3be4523951 | 75148e9c83552d32e79a11853160104c820dd2a6 | /MCSoftware/FOAM2.06/TRND.cxx | 777c39e33fc2c74fd4bf9e4534adc1a4f624c6fb | []
| no_license | vhalyolee/PhaseSpace | 3ae96867928da9c6b984104afbf41270f451fda9 | ef697001405626f7aa6de0fc1e38e10ac97d1d3e | refs/heads/master | 2021-01-20T05:15:37.810315 | 2018-05-23T16:27:12 | 2018-05-23T16:27:12 | 101,424,177 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | cxx | #include "TRND.h"
#ifdef ROOT_DEF
ClassImp(TRND)
#endif
///////////////////////////////////////////////////////////////////////////////
// //
// Class TRND //
// Abstract class representing any type of random number generator //
// //
///////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
]
| |
bf09334d132600553d8c34fd4599af412a422736 | 10b0d8b163b772e485b64953ff1abeae486d7154 | /src/cpu/inorder/resources/mult_div_unit.cc | e7bd6750f897cd4286506b6e496ed446731b6371 | [
"BSD-3-Clause"
]
| permissive | hassahma/m5 | fd38cf6e1192716ad97e8c4a45268e3378cf2912 | b52324b1b5fda06b11a04f87734c25391d99c8b0 | refs/heads/master | 2021-01-16T19:41:53.382649 | 2010-12-14T20:49:59 | 2010-12-14T20:49:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,542 | cc | /*
* Copyright (c) 2007 MIPS Technologies, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Korey Sewell
*
*/
#include <vector>
#include <list>
#include "cpu/inorder/resources/mult_div_unit.hh"
#include "cpu/inorder/resource_pool.hh"
#include "cpu/inorder/cpu.hh"
#include "cpu/op_class.hh"
using namespace std;
using namespace ThePipeline;
MultDivUnit::MultDivUnit(string res_name, int res_id, int res_width,
int res_latency, InOrderCPU *_cpu, ThePipeline::Params *params)
: Resource(res_name, res_id, res_width, res_latency, _cpu),
multRepeatRate(params->multRepeatRate), multLatency(params->multLatency),
div8RepeatRate(params->div8RepeatRate), div8Latency(params->div8Latency),
div16RepeatRate(params->div16RepeatRate), div16Latency(params->div16Latency),
div24RepeatRate(params->div24RepeatRate), div24Latency(params->div24Latency),
div32RepeatRate(params->div32RepeatRate), div32Latency(params->div32Latency),
lastMDUCycle(0), lastOpType(No_OpClass)
{ }
void
MultDivUnit::regStats()
{
multInstReqsProcessed
.name(name() + ".multInstReqsProcessed")
.desc("Number of Multiply Requests Processed.");
divInstReqsProcessed
.name(name() + ".divInstReqsProcessed")
.desc("Number of Divide Requests Processed.");
Resource::regStats();
}
void
MultDivUnit::init()
{
// Set Up Resource Events to Appropriate Resource BandWidth
resourceEvent = new MDUEvent[width];
initSlots();
}
int
MultDivUnit::findSlot(DynInstPtr inst)
{
DPRINTF(InOrderMDU, "Finding slot for inst:%i\n | slots-free:%i | slots-used:%i\n",
inst->seqNum, slotsAvail(), slotsInUse());
return Resource::findSlot(inst);
}
void
MultDivUnit::freeSlot(int slot_idx)
{
DPRINTF(InOrderMDU, "Freeing slot for inst:%i\n | slots-free:%i | slots-used:%i\n",
reqMap[slot_idx]->getInst()->seqNum, slotsAvail(), slotsInUse());
Resource::freeSlot(slot_idx);
}
//@TODO: Should we push this behavior into base-class to generically
// accomodate all multicyle resources?
void
MultDivUnit::requestAgain(DynInstPtr inst, bool &service_request)
{
ResReqPtr mult_div_req = findRequest(inst);
assert(mult_div_req);
service_request = true;
// Check to see if this instruction is requesting the same command
// or a different one
if (mult_div_req->cmd != inst->resSched.top()->cmd) {
// If different, then update command in the request
mult_div_req->cmd = inst->resSched.top()->cmd;
DPRINTF(InOrderMDU,
"[tid:%i]: [sn:%i]: Updating the command for this instruction\n",
inst->readTid(), inst->seqNum);
} else {
// If same command, just check to see if memory access was completed
// but dont try to re-execute
DPRINTF(InOrderMDU,
"[tid:%i]: [sn:%i]: requesting this resource again\n",
inst->readTid(), inst->seqNum);
}
}
int
MultDivUnit::getSlot(DynInstPtr inst)
{
// If MDU already has instruction, return current slot.
int slot_num = findSlot(inst);
// If we have this instruction's request already then return
if (slot_num != -1 &&
inst->resSched.top()->cmd == reqMap[slot_num]->cmd)
return slot_num;
unsigned repeat_rate = 0;
/** Enforce MDU dependencies after a multiply is seen last */
if (lastOpType == IntMultOp) {
repeat_rate = multRepeatRate;
}
/** Enforce dependencies after a divide is seen last */
if (lastOpType == IntDivOp) {
switch (lastDivSize) {
case 8:
repeat_rate = div8RepeatRate;
break;
case 16:
repeat_rate = div16RepeatRate;
break;
case 24:
repeat_rate = div24RepeatRate;
break;
case 32:
repeat_rate = div32RepeatRate;
break;
}
}
if (lastMDUCycle + repeat_rate > curTick) {
DPRINTF(InOrderMDU, "MDU not ready to process another inst. until %i, denying request.\n",
lastMDUCycle + repeat_rate);
return -1;
} else {
int rval = Resource::getSlot(inst);
DPRINTF(InOrderMDU, "MDU request should pass: %i.\n",
rval);
if (rval != -1) {
lastMDUCycle = curTick;
lastOpType = inst->opClass();
lastInstName = inst->staticInst->getName();
}
return rval;
}
}
int
MultDivUnit::getDivOpSize(DynInstPtr inst)
{
// Get RT Register from instruction (index #1)
uint32_t div_op = inst->readIntSrc(1);
if (div_op <= 0xFF) {
return 8;
} else if (div_op <= 0xFFFF) {
return 16;
} else if (div_op <= 0xFFFFFF) {
return 24;
} else {
return 32;
}
}
void
MultDivUnit::execute(int slot_num)
{
ResourceRequest* mult_div_req = reqMap[slot_num];
DynInstPtr inst = reqMap[slot_num]->inst;
Fault fault = reqMap[slot_num]->fault;
//ThreadID tid = inst->readTid();
//int seq_num = inst->seqNum;
switch (mult_div_req->cmd)
{
case StartMultDiv:
DPRINTF(InOrderMDU, "Start MDU called ...\n");
if (inst->opClass() == IntMultOp) {
scheduleEvent(slot_num, multLatency);
multInstReqsProcessed++;
} else if (inst->opClass() == IntDivOp) {
int op_size = getDivOpSize(inst);
switch (op_size)
{
case 8:
scheduleEvent(slot_num, div8Latency);
break;
case 16:
scheduleEvent(slot_num, div16Latency);
break;
case 24:
scheduleEvent(slot_num, div24Latency);
break;
case 32:
scheduleEvent(slot_num, div32Latency);
break;
}
lastDivSize = op_size;
divInstReqsProcessed++;
}
// Allow to pass through to next stage while
// event processes
mult_div_req->setCompleted();
break;
case MultDiv:
DPRINTF(InOrderMDU, "Execute MDU called ...\n");
exeMulDiv(slot_num);
mult_div_req->done();
break;
case EndMultDiv:
//@TODO: Why not allow high-latency requests to sleep
// within stage until event wakes up????
// Seems wasteful to continually check to see if
// this is done when we have a event in parallel
// counting down the time
{
DPRINTF(InOrderMDU, "End MDU called ...\n");
if (mult_div_req->getInst()->isExecuted()) {
DPRINTF(InOrderMDU, "Mult/Div finished.\n");
mult_div_req->done();
} else {
mult_div_req->setCompleted(false);
}
}
break;
default:
fatal("Unrecognized command to %s", resName);
}
}
void
MultDivUnit::exeMulDiv(int slot_num)
{
ResourceRequest* mult_div_req = reqMap[slot_num];
DynInstPtr inst = reqMap[slot_num]->inst;
Fault fault = reqMap[slot_num]->fault;
ThreadID tid = inst->readTid();
int seq_num = inst->seqNum;
fault = inst->execute();
if (fault == NoFault) {
inst->setExecuted();
mult_div_req->setCompleted();
DPRINTF(Resource, "[tid:%i]: The result of execution is 0x%x.\n",
inst->readTid(), inst->readIntResult(0));
} else {
warn("inst [sn:%i] had a %s fault", seq_num, fault->name());
cpu->trap(fault, tid);
}
}
MDUEvent::MDUEvent()
: ResourceEvent()
{ }
void
MDUEvent::process()
{
MultDivUnit* mdu_res = reinterpret_cast<MultDivUnit*>(resource);
mdu_res->exeMulDiv(slotIdx);
ResourceRequest* mult_div_req = resource->reqMap[slotIdx];
mult_div_req->done();
}
| [
"[email protected]"
]
| |
7d63185cd55077c0eea70c70786646fd5d0fcd9f | 6e2d4044121e2e59240a3e9c7600b04f0fb1cc3a | /leetcode/leetcode_232/main1.cpp | c1108aa20594a2633d01a1858e42c1c93d9ef6c6 | []
| no_license | gxsoar/algorithm_practice | 01bdd08615e1be3025acfa00a1ca430d27c351f1 | f375eb5269bacf85e6c82f3196d6875b76c81c1e | refs/heads/master | 2022-05-31T04:29:46.280914 | 2020-02-11T13:42:01 | 2020-02-11T13:42:01 | 221,185,956 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,383 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <vector>
using namespace std;
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> st;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack<int> temp;
while(!st.empty()) {
temp.push(st.top());
st.pop();
}
st.push(x);
while(!temp.empty()) {
st.push(temp.top());
temp.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int d = st.top();
st.pop();
return d;
}
/** Get the front element. */
int peek() {
return st.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return st.empty();
}
};
int main() {
int x;
cin >> x;
MyQueue* obj = new MyQueue();
obj->push(x);
int param_2 = obj->pop();
int param_3 = obj->peek();
bool param_4 = obj->empty();
cout << param_2 << " " << param_3 << " " << param_4 << endl;
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/ | [
"[email protected]"
]
| |
a5293da94e899aad6a3accd8cd0030ccc8569eb2 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /components/gcm_driver/crypto/gcm_encryption_provider_unittest.cc | 384dc76b43e240a479318a7de813b1667985e47f | [
"BSD-3-Clause"
]
| permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 23,075 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/gcm_driver/crypto/gcm_encryption_provider.h"
#include <stddef.h>
#include <sstream>
#include <string>
#include "base/base64url.h"
#include "base/big_endian.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/test/histogram_tester.h"
#include "components/gcm_driver/common/gcm_messages.h"
#include "components/gcm_driver/crypto/gcm_decryption_result.h"
#include "components/gcm_driver/crypto/gcm_key_store.h"
#include "components/gcm_driver/crypto/gcm_message_cryptographer.h"
#include "components/gcm_driver/crypto/p256_key_util.h"
#include "crypto/random.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gcm {
namespace {
const char kExampleAppId[] = "my-app-id";
const char kExampleAuthorizedEntity[] = "my-sender-id";
const char kExampleMessage[] = "Hello, world, this is the GCM Driver!";
const char kValidEncryptionHeader[] =
"keyid=foo;salt=MTIzNDU2Nzg5MDEyMzQ1Ng;rs=1024";
const char kInvalidEncryptionHeader[] = "keyid";
const char kValidCryptoKeyHeader[] =
"keyid=foo;dh=BL_UGhfudEkXMUd4U4-D4nP5KHxKjQHsW6j88ybbehXM7fqi1OMFefDUEi0eJ"
"vsKfyVBWYkQjH-lSPJKxjAyslg";
const char kValidThreeValueCryptoKeyHeader[] =
"keyid=foo,keyid=bar,keyid=baz;dh=BL_UGhfudEkXMUd4U4-D4nP5KHxKjQHsW6j88ybbe"
"hXM7fqi1OMFefDUEi0eJvsKfyVBWYkQjH-lSPJKxjAyslg";
const char kInvalidCryptoKeyHeader[] = "keyid";
const char kInvalidThreeValueCryptoKeyHeader[] =
"keyid=foo,dh=BL_UGhfudEkXMUd4U4-D4nP5KHxKjQHsW6j88ybbehXM7fqi1OMFefDUEi0eJ"
"vsKfyVBWYkQjH-lSPJKxjAyslg,keyid=baz,dh=BL_UGhfudEkXMUd4U4-D4nP5KHxKjQHsW6"
"j88ybbehXM7fqi1OMFefDUEi0eJvsKfyVBWYkQjH-lSPJKxjAyslg";
} // namespace
class GCMEncryptionProviderTest : public ::testing::Test {
public:
void SetUp() override {
ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
encryption_provider_.reset(new GCMEncryptionProvider);
encryption_provider_->Init(scoped_temp_dir_.GetPath(),
message_loop_.task_runner());
}
void TearDown() override {
encryption_provider_.reset();
// |encryption_provider_| owns a ProtoDatabaseImpl whose destructor deletes
// the underlying LevelDB database on the task runner.
base::RunLoop().RunUntilIdle();
}
// To be used as a callback for GCMEncryptionProvider::GetEncryptionInfo().
void DidGetEncryptionInfo(std::string* p256dh_out,
std::string* auth_secret_out,
const std::string& p256dh,
const std::string& auth_secret) {
*p256dh_out = p256dh;
*auth_secret_out = auth_secret;
}
// To be used as a callback for GCMKeyStore::{GetKeys,CreateKeys}.
void HandleKeysCallback(KeyPair* pair_out,
std::string* auth_secret_out,
const KeyPair& pair,
const std::string& auth_secret) {
*pair_out = pair;
*auth_secret_out = auth_secret;
}
protected:
// Decrypts the |message| and then synchronously waits until either the
// success or failure callbacks has been invoked.
void Decrypt(const IncomingMessage& message) {
encryption_provider_->DecryptMessage(
kExampleAppId, message,
base::Bind(&GCMEncryptionProviderTest::DidDecryptMessage,
base::Unretained(this)));
// The encryption keys will be read asynchronously.
base::RunLoop().RunUntilIdle();
}
// Checks that the underlying key store has a key for the |kExampleAppId| +
// authorized entity pair if and only if |should_have_key| is true. Must wrap
// with ASSERT/EXPECT_NO_FATAL_FAILURE.
void CheckHasKey(const std::string& authorized_entity, bool should_have_key) {
KeyPair pair;
std::string auth_secret;
encryption_provider()->key_store_->GetKeys(
kExampleAppId, authorized_entity,
false /* fallback_to_empty_authorized_entity */,
base::Bind(&GCMEncryptionProviderTest::HandleKeysCallback,
base::Unretained(this), &pair, &auth_secret));
base::RunLoop().RunUntilIdle();
if (should_have_key) {
ASSERT_GT(pair.public_key().size(), 0u);
ASSERT_GT(pair.private_key().size(), 0u);
ASSERT_GT(auth_secret.size(), 0u);
} else {
ASSERT_EQ(0u, pair.public_key().size());
ASSERT_EQ(0u, pair.private_key().size());
ASSERT_EQ(0u, auth_secret.size());
}
}
// Returns the result of the previous decryption operation.
GCMDecryptionResult decryption_result() { return decryption_result_; }
// Returns the message resulting from the previous decryption operation.
const IncomingMessage& decrypted_message() { return decrypted_message_; }
GCMEncryptionProvider* encryption_provider() {
return encryption_provider_.get();
}
// Performs a full round-trip test of the encryption feature. Must wrap this
// in ASSERT_NO_FATAL_FAILURE.
void TestEncryptionRoundTrip(const std::string& app_id,
const std::string& authorized_entity,
GCMMessageCryptographer::Version version);
private:
void DidDecryptMessage(GCMDecryptionResult result,
const IncomingMessage& message) {
decryption_result_ = result;
decrypted_message_ = message;
}
base::MessageLoop message_loop_;
base::ScopedTempDir scoped_temp_dir_;
base::HistogramTester histogram_tester_;
std::unique_ptr<GCMEncryptionProvider> encryption_provider_;
GCMDecryptionResult decryption_result_ = GCMDecryptionResult::UNENCRYPTED;
IncomingMessage decrypted_message_;
};
TEST_F(GCMEncryptionProviderTest, IsEncryptedMessage) {
// Both the Encryption and Encryption-Key headers must be present, and the raw
// data must be non-empty for a message to be considered encrypted.
IncomingMessage empty_message;
EXPECT_FALSE(encryption_provider()->IsEncryptedMessage(empty_message));
IncomingMessage single_header_message;
single_header_message.data["encryption"] = "";
EXPECT_FALSE(encryption_provider()->IsEncryptedMessage(
single_header_message));
IncomingMessage double_header_message;
double_header_message.data["encryption"] = "";
double_header_message.data["crypto-key"] = "";
EXPECT_FALSE(encryption_provider()->IsEncryptedMessage(
double_header_message));
IncomingMessage double_header_with_data_message;
double_header_with_data_message.data["encryption"] = "";
double_header_with_data_message.data["crypto-key"] = "";
double_header_with_data_message.raw_data = "foo";
EXPECT_TRUE(encryption_provider()->IsEncryptedMessage(
double_header_with_data_message));
IncomingMessage draft08_message;
draft08_message.data["content-encoding"] = "aes128gcm";
draft08_message.raw_data = "foo";
EXPECT_TRUE(encryption_provider()->IsEncryptedMessage(draft08_message));
}
TEST_F(GCMEncryptionProviderTest, VerifiesEncryptionHeaderParsing) {
// The Encryption header must be parsable and contain valid values.
// Note that this is more extensively tested in EncryptionHeaderParsersTest.
IncomingMessage invalid_message;
invalid_message.data["encryption"] = kInvalidEncryptionHeader;
invalid_message.data["crypto-key"] = kValidCryptoKeyHeader;
invalid_message.raw_data = "foo";
ASSERT_NO_FATAL_FAILURE(Decrypt(invalid_message));
EXPECT_EQ(GCMDecryptionResult::INVALID_ENCRYPTION_HEADER,
decryption_result());
IncomingMessage valid_message;
valid_message.data["encryption"] = kValidEncryptionHeader;
valid_message.data["crypto-key"] = kInvalidCryptoKeyHeader;
valid_message.raw_data = "foo";
ASSERT_NO_FATAL_FAILURE(Decrypt(valid_message));
EXPECT_NE(GCMDecryptionResult::INVALID_ENCRYPTION_HEADER,
decryption_result());
}
TEST_F(GCMEncryptionProviderTest, VerifiesCryptoKeyHeaderParsing) {
// The Crypto-Key header must be parsable and contain valid values.
// Note that this is more extensively tested in EncryptionHeaderParsersTest.
IncomingMessage invalid_message;
invalid_message.data["encryption"] = kValidEncryptionHeader;
invalid_message.data["crypto-key"] = kInvalidCryptoKeyHeader;
invalid_message.raw_data = "foo";
ASSERT_NO_FATAL_FAILURE(Decrypt(invalid_message));
EXPECT_EQ(GCMDecryptionResult::INVALID_CRYPTO_KEY_HEADER,
decryption_result());
IncomingMessage valid_message;
valid_message.data["encryption"] = kValidEncryptionHeader;
valid_message.data["crypto-key"] = kValidCryptoKeyHeader;
valid_message.raw_data = "foo";
ASSERT_NO_FATAL_FAILURE(Decrypt(valid_message));
EXPECT_NE(GCMDecryptionResult::INVALID_CRYPTO_KEY_HEADER,
decryption_result());
}
TEST_F(GCMEncryptionProviderTest, VerifiesCryptoKeyHeaderParsingThirdValue) {
// The Crypto-Key header must be parsable and contain valid values, in which
// values will be ignored unless they contain a "dh" property.
IncomingMessage valid_message;
valid_message.data["encryption"] = kValidEncryptionHeader;
valid_message.data["crypto-key"] = kValidThreeValueCryptoKeyHeader;
valid_message.raw_data = "foo";
ASSERT_NO_FATAL_FAILURE(Decrypt(valid_message));
EXPECT_NE(GCMDecryptionResult::INVALID_CRYPTO_KEY_HEADER,
decryption_result());
}
TEST_F(GCMEncryptionProviderTest, VerifiesCryptoKeyHeaderSingleDhEntry) {
// The Crypto-Key header must include at most one value that contains the
// "dh" property. Having more than once occurrence is forbidden.
IncomingMessage valid_message;
valid_message.data["encryption"] = kValidEncryptionHeader;
valid_message.data["crypto-key"] = kInvalidThreeValueCryptoKeyHeader;
valid_message.raw_data = "foo";
ASSERT_NO_FATAL_FAILURE(Decrypt(valid_message));
EXPECT_EQ(GCMDecryptionResult::INVALID_CRYPTO_KEY_HEADER,
decryption_result());
}
TEST_F(GCMEncryptionProviderTest, VerifiesExistingKeys) {
// When both headers are valid, the encryption keys still must be known to
// the GCM key store before the message can be decrypted.
IncomingMessage message;
message.data["encryption"] = kValidEncryptionHeader;
message.data["crypto-key"] = kValidCryptoKeyHeader;
message.raw_data = "foo";
ASSERT_NO_FATAL_FAILURE(Decrypt(message));
EXPECT_EQ(GCMDecryptionResult::NO_KEYS, decryption_result());
std::string public_key, auth_secret;
encryption_provider()->GetEncryptionInfo(
kExampleAppId, "" /* empty authorized entity for non-InstanceID */,
base::Bind(&GCMEncryptionProviderTest::DidGetEncryptionInfo,
base::Unretained(this), &public_key, &auth_secret));
// Getting (or creating) the public key will be done asynchronously.
base::RunLoop().RunUntilIdle();
ASSERT_GT(public_key.size(), 0u);
ASSERT_GT(auth_secret.size(), 0u);
ASSERT_NO_FATAL_FAILURE(Decrypt(message));
EXPECT_NE(GCMDecryptionResult::NO_KEYS, decryption_result());
}
TEST_F(GCMEncryptionProviderTest, VerifiesKeyRemovalGCMRegistration) {
// Removing encryption info for an InstanceID token shouldn't affect a
// non-InstanceID GCM registration.
// Non-InstanceID callers pass an empty string for authorized_entity.
std::string authorized_entity_gcm = "";
std::string authorized_entity_1 = kExampleAuthorizedEntity + std::string("1");
std::string authorized_entity_2 = kExampleAuthorizedEntity + std::string("2");
// Should create encryption info.
std::string public_key, auth_secret;
encryption_provider()->GetEncryptionInfo(
kExampleAppId, authorized_entity_gcm,
base::Bind(&GCMEncryptionProviderTest::DidGetEncryptionInfo,
base::Unretained(this), &public_key, &auth_secret));
base::RunLoop().RunUntilIdle();
// Should get encryption info created above.
std::string read_public_key, read_auth_secret;
encryption_provider()->GetEncryptionInfo(
kExampleAppId, authorized_entity_gcm,
base::Bind(&GCMEncryptionProviderTest::DidGetEncryptionInfo,
base::Unretained(this), &read_public_key, &read_auth_secret));
base::RunLoop().RunUntilIdle();
EXPECT_GT(public_key.size(), 0u);
EXPECT_GT(auth_secret.size(), 0u);
EXPECT_EQ(public_key, read_public_key);
EXPECT_EQ(auth_secret, read_auth_secret);
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_gcm, true));
encryption_provider()->RemoveEncryptionInfo(
kExampleAppId, authorized_entity_1, base::Bind(&base::DoNothing));
base::RunLoop().RunUntilIdle();
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_gcm, true));
encryption_provider()->RemoveEncryptionInfo(kExampleAppId, "*",
base::Bind(&base::DoNothing));
base::RunLoop().RunUntilIdle();
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_gcm, true));
encryption_provider()->RemoveEncryptionInfo(
kExampleAppId, authorized_entity_gcm, base::Bind(&base::DoNothing));
base::RunLoop().RunUntilIdle();
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_gcm, false));
}
TEST_F(GCMEncryptionProviderTest, VerifiesKeyRemovalInstanceIDToken) {
// Removing encryption info for a non-InstanceID GCM registration shouldn't
// affect an InstanceID token.
// Non-InstanceID callers pass an empty string for authorized_entity.
std::string authorized_entity_gcm = "";
std::string authorized_entity_1 = kExampleAuthorizedEntity + std::string("1");
std::string authorized_entity_2 = kExampleAuthorizedEntity + std::string("2");
std::string public_key_1, auth_secret_1;
encryption_provider()->GetEncryptionInfo(
kExampleAppId, authorized_entity_1,
base::Bind(&GCMEncryptionProviderTest::DidGetEncryptionInfo,
base::Unretained(this), &public_key_1, &auth_secret_1));
base::RunLoop().RunUntilIdle();
EXPECT_GT(public_key_1.size(), 0u);
EXPECT_GT(auth_secret_1.size(), 0u);
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_1, true));
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_2, false));
std::string public_key_2, auth_secret_2;
encryption_provider()->GetEncryptionInfo(
kExampleAppId, authorized_entity_2,
base::Bind(&GCMEncryptionProviderTest::DidGetEncryptionInfo,
base::Unretained(this), &public_key_2, &auth_secret_2));
base::RunLoop().RunUntilIdle();
EXPECT_GT(public_key_2.size(), 0u);
EXPECT_GT(auth_secret_2.size(), 0u);
EXPECT_NE(public_key_1, public_key_2);
EXPECT_NE(auth_secret_1, auth_secret_2);
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_1, true));
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_2, true));
std::string read_public_key_1, read_auth_secret_1;
encryption_provider()->GetEncryptionInfo(
kExampleAppId, authorized_entity_1,
base::Bind(&GCMEncryptionProviderTest::DidGetEncryptionInfo,
base::Unretained(this), &read_public_key_1,
&read_auth_secret_1));
base::RunLoop().RunUntilIdle();
// Should have returned existing info for authorized_entity_1.
EXPECT_EQ(public_key_1, read_public_key_1);
EXPECT_EQ(auth_secret_1, read_auth_secret_1);
encryption_provider()->RemoveEncryptionInfo(
kExampleAppId, authorized_entity_gcm, base::Bind(&base::DoNothing));
base::RunLoop().RunUntilIdle();
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_1, true));
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_2, true));
encryption_provider()->RemoveEncryptionInfo(
kExampleAppId, authorized_entity_1, base::Bind(&base::DoNothing));
base::RunLoop().RunUntilIdle();
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_1, false));
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_2, true));
std::string public_key_1_refreshed, auth_secret_1_refreshed;
encryption_provider()->GetEncryptionInfo(
kExampleAppId, authorized_entity_1,
base::Bind(&GCMEncryptionProviderTest::DidGetEncryptionInfo,
base::Unretained(this), &public_key_1_refreshed,
&auth_secret_1_refreshed));
base::RunLoop().RunUntilIdle();
// Since the info was removed, GetEncryptionInfo should have created new info.
EXPECT_GT(public_key_1_refreshed.size(), 0u);
EXPECT_GT(auth_secret_1_refreshed.size(), 0u);
EXPECT_NE(public_key_1, public_key_1_refreshed);
EXPECT_NE(auth_secret_1, auth_secret_1_refreshed);
EXPECT_NE(public_key_2, public_key_1_refreshed);
EXPECT_NE(auth_secret_2, auth_secret_1_refreshed);
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_1, true));
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_2, true));
encryption_provider()->RemoveEncryptionInfo(kExampleAppId, "*",
base::Bind(&base::DoNothing));
base::RunLoop().RunUntilIdle();
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_1, false));
ASSERT_NO_FATAL_FAILURE(CheckHasKey(authorized_entity_2, false));
}
void GCMEncryptionProviderTest::TestEncryptionRoundTrip(
const std::string& app_id,
const std::string& authorized_entity,
GCMMessageCryptographer::Version version) {
// Performs a full round-trip of the encryption feature, including getting a
// public/private key-pair and performing the cryptographic operations. This
// is more of an integration test than a unit test.
KeyPair pair, server_pair;
std::string auth_secret, server_authentication;
// Retrieve the public/private key-pair immediately from the key store, given
// that the GCMEncryptionProvider will only share the public key with users.
// Also create a second pair, which will act as the server's keys.
encryption_provider()->key_store_->CreateKeys(
app_id, authorized_entity,
base::Bind(&GCMEncryptionProviderTest::HandleKeysCallback,
base::Unretained(this), &pair, &auth_secret));
encryption_provider()->key_store_->CreateKeys(
"server-" + app_id, authorized_entity,
base::Bind(&GCMEncryptionProviderTest::HandleKeysCallback,
base::Unretained(this), &server_pair, &server_authentication));
// Creating the public keys will be done asynchronously.
base::RunLoop().RunUntilIdle();
ASSERT_GT(pair.public_key().size(), 0u);
ASSERT_GT(server_pair.public_key().size(), 0u);
ASSERT_GT(pair.private_key().size(), 0u);
ASSERT_GT(server_pair.private_key().size(), 0u);
std::string salt;
// Creates a cryptographically secure salt of |salt_size| octets in size, and
// calculate the shared secret for the message.
crypto::RandBytes(base::WriteInto(&salt, 16 + 1), 16);
std::string shared_secret;
ASSERT_TRUE(ComputeSharedP256Secret(
pair.private_key(), server_pair.public_key(), &shared_secret));
IncomingMessage message;
size_t record_size;
message.sender_id = kExampleAuthorizedEntity;
// Encrypts the |kExampleMessage| using the generated shared key and the
// random |salt|, storing the result in |record_size| and the message.
GCMMessageCryptographer cryptographer(version);
std::string ciphertext;
ASSERT_TRUE(cryptographer.Encrypt(
pair.public_key(), server_pair.public_key(), shared_secret, auth_secret,
salt, kExampleMessage, &record_size, &ciphertext));
switch (version) {
case GCMMessageCryptographer::Version::DRAFT_03: {
std::string encoded_salt, encoded_key;
// Compile the incoming GCM message, including the required headers.
base::Base64UrlEncode(salt, base::Base64UrlEncodePolicy::INCLUDE_PADDING,
&encoded_salt);
base::Base64UrlEncode(server_pair.public_key(),
base::Base64UrlEncodePolicy::INCLUDE_PADDING,
&encoded_key);
std::stringstream encryption_header;
encryption_header << "rs=" << base::SizeTToString(record_size) << ";";
encryption_header << "salt=" << encoded_salt;
message.data["encryption"] = encryption_header.str();
message.data["crypto-key"] = "dh=" + encoded_key;
message.raw_data.swap(ciphertext);
break;
}
case GCMMessageCryptographer::Version::DRAFT_08: {
uint32_t rs = record_size;
uint8_t key_length = server_pair.public_key().size();
std::vector<char> payload(salt.size() + sizeof(rs) + sizeof(key_length) +
server_pair.public_key().size() +
ciphertext.size());
char* current = &payload.front();
memcpy(current, salt.data(), salt.size());
current += salt.size();
base::WriteBigEndian(current, rs);
current += sizeof(rs);
base::WriteBigEndian(current, key_length);
current += sizeof(key_length);
memcpy(current, server_pair.public_key().data(),
server_pair.public_key().size());
current += server_pair.public_key().size();
memcpy(current, ciphertext.data(), ciphertext.size());
message.data["content-encoding"] = "aes128gcm";
message.raw_data.assign(payload.begin(), payload.end());
break;
}
}
ASSERT_TRUE(encryption_provider()->IsEncryptedMessage(message));
// Decrypt the message, and expect everything to go wonderfully well.
ASSERT_NO_FATAL_FAILURE(Decrypt(message));
ASSERT_EQ(version == GCMMessageCryptographer::Version::DRAFT_03
? GCMDecryptionResult::DECRYPTED_DRAFT_03
: GCMDecryptionResult::DECRYPTED_DRAFT_08,
decryption_result());
EXPECT_TRUE(decrypted_message().decrypted);
EXPECT_EQ(kExampleMessage, decrypted_message().raw_data);
}
TEST_F(GCMEncryptionProviderTest, EncryptionRoundTripGCMRegistration) {
// GCMEncryptionProvider::DecryptMessage should succeed when the message was
// sent to a non-InstanceID GCM registration (empty authorized_entity).
ASSERT_NO_FATAL_FAILURE(TestEncryptionRoundTrip(
kExampleAppId, "" /* empty authorized entity for non-InstanceID */,
GCMMessageCryptographer::Version::DRAFT_03));
}
TEST_F(GCMEncryptionProviderTest, EncryptionRoundTripInstanceIDToken) {
// GCMEncryptionProvider::DecryptMessage should succeed when the message was
// sent to an InstanceID token (non-empty authorized_entity).
ASSERT_NO_FATAL_FAILURE(
TestEncryptionRoundTrip(kExampleAppId, kExampleAuthorizedEntity,
GCMMessageCryptographer::Version::DRAFT_03));
}
TEST_F(GCMEncryptionProviderTest, EncryptionRoundTripDraft08) {
// GCMEncryptionProvider::DecryptMessage should succeed when the message was
// encrypted following raft-ietf-webpush-encryption-08.
ASSERT_NO_FATAL_FAILURE(
TestEncryptionRoundTrip(kExampleAppId, kExampleAuthorizedEntity,
GCMMessageCryptographer::Version::DRAFT_08));
}
} // namespace gcm
| [
"[email protected]"
]
| |
90d81dfe40e618e93b8d5d78e644d72b68a31776 | 7c60a4cd1cc117f1b76d2cbf101074500e72f471 | /common_utils/include/common_utils/random.hpp | ef08cb104174bdb4e2b6d8b99aab429fceb6ff3d | [
"Apache-2.0"
]
| permissive | Yanick-Salzmann/carpi | 0d32b452fe2c0e69434e3aa5989b6993af90e0db | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | refs/heads/master | 2020-09-15T23:26:07.396758 | 2020-03-28T22:07:36 | 2020-03-28T22:07:36 | 223,575,460 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | hpp | #ifndef CARPI_COMMON_UTILS_RANDOM_HPP
#define CARPI_COMMON_UTILS_RANDOM_HPP
#include <random>
namespace carpi::utils {
std::vector<uint8_t> random_bytes(std::size_t num_bytes);
uint32_t random_uint32();
}
#endif //CARPI_COMMON_UTILS_RANDOM_HPP
| [
"[email protected]"
]
| |
164b6c0fe6e2bb8925e063a67e2c5c8fe88ad531 | 282aaadc0f9b8458a053ebda72f8887ca2cb2e6f | /C++ Games/BomberMan/BomberMan/Player.cpp | 08ba3e5a6fbe2bd1a45133cedfaf4a33b81e7f0d | []
| no_license | milletf1/BIT | 0be30452eaa531a9780c5950138b8b7c990fa931 | 0c216b96719062096e6a8fe781fbbeb259823b8a | refs/heads/master | 2020-12-31T00:54:47.039435 | 2017-06-03T06:05:33 | 2017-06-03T06:05:33 | 80,593,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,184 | cpp | #include "StdAfx.h"
#include "Player.h"
/// <summary>
/// Constructor
/// </summary>
Player::Player(Graphics^ sCanvas, String^ upSheet, String^ downSheet, String^ leftSheet, String^ rightSheet,
int sNFrames, Point^ sDrawPos, int sDrawWidth, int sDrawHeight, int sMoveSpeed, int sLives,
int sHitBoxXOffset, int sHitBoxYOffset, int sHitBoxWidth, int sHitBoxHeight)
: Sprite(sCanvas, upSheet, downSheet, leftSheet, rightSheet, sNFrames, sDrawPos, sDrawWidth,
sDrawHeight, sMoveSpeed, sLives, sHitBoxXOffset, sHitBoxYOffset, sHitBoxWidth, sHitBoxHeight)
{
//initialize the players game powerup variables
hasBombAOEBuff = false;
bombAOEBuffTimer = 0;
hasMultiBombs = false;
multiBombsTimer = 0;
hasMoveSpeedBuff = false;
MoveSpeedBuffTimer = 0;
//once the player drops a bomb, they can temporarily move over the bomb, once they have moved off it
//they can no longer walk past them
canMovePastBomb = false;
MoveCenterPoint();
}//End//////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Moves the players center point. the center point is used to determine what tile the
/// player drops a bomb on, and when they use a warp portal.
/// </summary>
void Player::MoveCenterPoint()
{
int newXPos = hitBoxPos->X + (hitBoxWidth / 2);
int newYPos = hitBoxPos->Y + (hitBoxHeight / 2);
centerPoint = gcnew Point(newXPos, newYPos);
}//End//////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Activates a given buff on the player, and sets the buff duration timer.
/// </summary>
void Player::RecieveBuff(int buff)
{
switch(buff)
{
case AOE_BUFF:
hasBombAOEBuff = true;
bombAOEBuffTimer = BUFF_DURATION;
break;
case BOMB_NUM_BUFF:
hasMultiBombs = true;
multiBombsTimer = BUFF_DURATION;
break;
case MOVE_BUFF:
hasMoveSpeedBuff = true;
MoveSpeedBuffTimer = BUFF_DURATION;
}
}//End//////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Checks if the player has any of the buffs. If they have, it decrements that buffs
/// timer. when the timer reaches 0, it removes the buff from the player.
/// </summary>
void Player::PerformBuffUpkeep()
{
//Bomb AOE Buff
if(hasBombAOEBuff)
{
bombAOEBuffTimer -= TIMER_DECAY;
//check if the "timer" has run out
if(bombAOEBuffTimer == 0)
hasBombAOEBuff = false;
}
//Multi Bombs
if(hasMultiBombs)
{
multiBombsTimer -= TIMER_DECAY;
//check if the "timer" has run out
if(multiBombsTimer == 0)
hasMultiBombs = false;
}
//Move Speed Buff
if(hasMoveSpeedBuff)
{
MoveSpeedBuffTimer -= TIMER_DECAY;
//check if the "timer" has run out
if(MoveSpeedBuffTimer == 0)
hasMoveSpeedBuff = false;
}
}//End//////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Removes all buffs from the player. Is used when the player dies or changes level
/// </summary>
void Player::ClearAllBuffs()
{
hasBombAOEBuff = false;
bombAOEBuffTimer = 0;
hasMultiBombs = false;
multiBombsTimer = 0;
hasMoveSpeedBuff = false;
MoveSpeedBuffTimer = 0;
}//End////////////////////////////////////////////////////////////////////////////// | [
"[email protected]"
]
| |
c30dfa7b7ffb0d734ba4363d29be64ac122df848 | 0bada19fd7fbfc96c48e006976dac40d69f3898e | /firmware/Prototype_v4/Display/3.5inch_Arduino_8BIT_Module_ILI9486_MAR3501_V1.1/1-Demo/Demo_Arduino/Example/Example_04_display_graphics/display_graphics/display_graphics.ino | be459745bce00de832225bf528a6c889f907594d | [
"MIT"
]
| permissive | oxycon/ProjectApollo | 21e797762c0f21192daeef42f1ce7e7d47675e09 | e9dce060e55b708489106f58cf334be1f9ba677a | refs/heads/master | 2022-08-07T16:29:09.658452 | 2022-08-03T11:25:42 | 2022-08-03T11:25:42 | 248,296,869 | 45 | 26 | MIT | 2021-09-27T10:52:28 | 2020-03-18T17:21:38 | C | UTF-8 | C++ | false | false | 10,537 | ino | /***********************************************************************************
*This program is a demo of how to display picture and
*how to use rotate function to display string.
*This demo was made for LCD modules with 8bit or 16bit data port.
*This program requires the the LCDKIWI library.
* File : display_graphics.ino
* Hardware Environment: Arduino UNO&Mega2560
* Build Environment : Arduino
*Set the pins to the correct ones for your development shield or breakout board.
*This demo use the BREAKOUT BOARD only and use these 8bit data lines to the LCD,
*pin usage as follow:
* LCD_CS LCD_CD LCD_WR LCD_RD LCD_RST SD_SS SD_DI SD_DO SD_SCK
* Arduino Uno A3 A2 A1 A0 A4 10 11 12 13
*Arduino Mega2560 A3 A2 A1 A0 A4 10 11 12 13
* LCD_D0 LCD_D1 LCD_D2 LCD_D3 LCD_D4 LCD_D5 LCD_D6 LCD_D7
* Arduino Uno 8 9 2 3 4 5 6 7
*Arduino Mega2560 8 9 2 3 4 5 6 7
*Remember to set the pins to suit your display module!
*
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, QD electronic SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
**********************************************************************************/
#include <LCDWIKI_GUI.h> //Core graphics library
#include <LCDWIKI_KBV.h> //Hardware-specific library
//if the IC model is known or the modules is unreadable,you can use this constructed function
LCDWIKI_KBV mylcd(ILI9486,A3,A2,A1,A0,A4); //model,cs,cd,wr,rd,reset
//if the IC model is not known and the modules is readable,you can use this constructed function
//LCDWIKI_KBV mylcd(320,480,A3,A2,A1,A0,A4);//width,height,cs,cd,wr,rd,reset
//define some colour values
#define BLACK 0x0000
#define BLUE 0x001F
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
//clear screen
void fill_screen_test()
{
mylcd.Fill_Screen(BLACK);
mylcd.Fill_Screen(RED);
mylcd.Fill_Screen(GREEN);
mylcd.Fill_Screen(BLUE);
mylcd.Fill_Screen(BLACK);
}
//display some strings
void text_test()
{
mylcd.Set_Text_Mode(0);
mylcd.Fill_Screen(BLACK);
mylcd.Set_Text_Back_colour(BLACK);
mylcd.Set_Text_colour(WHITE);
mylcd.Set_Text_Size(1);
mylcd.Print_String("Hello World!", 0, 0);
mylcd.Set_Text_colour(YELLOW);
mylcd.Set_Text_Size(2);
mylcd.Print_Number_Float(1234.56,2,0, 8, '.', 0, ' ');
mylcd.Set_Text_colour(RED);
mylcd.Set_Text_Size(3);
//mylcd.Print_String("DEADBEEF", 0, 24);
mylcd.Print_Number_Int(0xDEADBEF, 0, 24, 0, ' ', 16);
mylcd.Set_Text_colour(GREEN);
mylcd.Set_Text_Size(5);
mylcd.Print_String("Groop", 0, 56);
mylcd.Set_Text_Size(2);
mylcd.Print_String("I implore thee,", 0, 96);
mylcd.Set_Text_Size(1);
mylcd.Print_String("my foonting turlingdromes.", 0, 112);
mylcd.Print_String("And hooptiously drangle me", 0, 120);
mylcd.Print_String("with crinkly bindlewurdles,", 0, 128);
mylcd.Print_String("Or I will rend thee", 0, 136);
mylcd.Print_String("in the gobberwarts", 0, 144);
mylcd.Print_String("with my blurglecruncheon,", 0, 152);
mylcd.Print_String("see if I don't!", 0, 160);
}
//draw some oblique lines
void lines_test(void)
{
mylcd.Fill_Screen(BLACK);
mylcd.Set_Draw_color(GREEN);
int i = 0;
for(i = 0; i< mylcd.Get_Display_Width();i+=5)
{
mylcd.Draw_Line(0, 0, i, mylcd.Get_Display_Height()-1);
}
for(i = mylcd.Get_Display_Height()-1; i>= 0;i-=5)
{
mylcd.Draw_Line(0, 0, mylcd.Get_Display_Width()-1, i);
}
mylcd.Fill_Screen(BLACK);
mylcd.Set_Draw_color(RED);
for(i = mylcd.Get_Display_Width() -1; i>=0;i-=5)
{
mylcd.Draw_Line(mylcd.Get_Display_Width()-1, 0, i, mylcd.Get_Display_Height()-1);
}
for(i = mylcd.Get_Display_Height()-1; i>=0;i-=5)
{
mylcd.Draw_Line(mylcd.Get_Display_Width()-1, 0, 0, i);
}
mylcd.Fill_Screen(BLACK);
mylcd.Set_Draw_color(BLUE);
for(i = 0; i < mylcd.Get_Display_Width();i+=5)
{
mylcd.Draw_Line(0, mylcd.Get_Display_Height()-1, i, 0);
}
for(i = 0; i < mylcd.Get_Display_Height();i+=5)
{
mylcd.Draw_Line(0, mylcd.Get_Display_Height()-1, mylcd.Get_Display_Width()-1, i);
}
mylcd.Fill_Screen(BLACK);
mylcd.Set_Draw_color(YELLOW);
for(i = mylcd.Get_Display_Width()-1; i >=0;i-=5)
{
mylcd.Draw_Line(mylcd.Get_Display_Width()-1, mylcd.Get_Display_Height()-1, i, 0);
}
for(i = 0; i<mylcd.Get_Display_Height();i+=5)
{
mylcd.Draw_Line(mylcd.Get_Display_Width()-1, mylcd.Get_Display_Height()-1, 0, i);
}
}
//draw some vertical lines and horizontal lines
void h_l_lines_test(void)
{
int i=0;
mylcd.Fill_Screen(BLACK);
mylcd.Set_Draw_color(GREEN);
for(i =0;i<mylcd.Get_Display_Height();i+=5)
{
mylcd.Draw_Fast_HLine(0,i,mylcd.Get_Display_Width());
delay(5);
}
mylcd.Set_Draw_color(BLUE);
for(i =0;i<mylcd.Get_Display_Width();i+=5)
{
mylcd.Draw_Fast_VLine(i,0,mylcd.Get_Display_Height());
delay(5);
}
}
//draw some rectangles
void rectangle_test(void)
{
int i = 0;
mylcd.Fill_Screen(BLACK);
mylcd.Set_Draw_color(GREEN);
for(i = 0;i<mylcd.Get_Display_Width()/2;i+=4)
{
mylcd.Draw_Rectangle(i,(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2+i,mylcd.Get_Display_Width()-1-i,mylcd.Get_Display_Height()-(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2-i);
delay(5);
}
}
//draw some filled rectangles
void fill_rectangle_test(void)
{
int i = 0;
mylcd.Fill_Screen(BLACK);
mylcd.Set_Draw_color(YELLOW);
mylcd.Fill_Rectangle(0,(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2,mylcd.Get_Display_Width()-1,mylcd.Get_Display_Height()-(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2);
mylcd.Set_Draw_color(MAGENTA);
for(i = 0;i<mylcd.Get_Display_Width()/2;i+=4)
{
mylcd.Draw_Rectangle(i,(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2+i,mylcd.Get_Display_Width()-1-i,mylcd.Get_Display_Height()-(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2-i);
delay(5);
}
for(i = 0;i<mylcd.Get_Display_Width()/2;i+=4)
{
mylcd.Set_Draw_color(random(255), random(255), random(255));
mylcd.Fill_Rectangle(i,(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2+i,mylcd.Get_Display_Width()-1-i,mylcd.Get_Display_Height()-(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2-i);
delay(5);
}
}
//draw some filled circles
void fill_circles_test(void)
{
int r=10,i=0,j=0;
mylcd.Fill_Screen(BLACK);
mylcd.Set_Draw_color(MAGENTA);
for(i=r;i<mylcd.Get_Display_Width();i+=2*r)
{
for(j=r;j<mylcd.Get_Display_Height();j+=2*r)
{
mylcd.Fill_Circle(i, j, r);
}
}
}
//draw some circles
void circles_test(void)
{
int r=10,i=0,j=0;
mylcd.Set_Draw_color(GREEN);
for(i=0;i<mylcd.Get_Display_Width()+r;i+=2*r)
{
for(j=0;j<mylcd.Get_Display_Height()+r;j+=2*r)
{
mylcd.Draw_Circle(i, j, r);
}
}
}
//draw some triangles
void triangles_test(void)
{
int i = 0;
mylcd.Fill_Screen(BLACK);
for(i=0;i<mylcd.Get_Display_Width()/2;i+=5)
{
mylcd.Set_Draw_color(0,i+64,i+64);
mylcd.Draw_Triangle(mylcd.Get_Display_Width()/2-1,mylcd.Get_Display_Height()/2-1-i,
mylcd.Get_Display_Width()/2-1-i,mylcd.Get_Display_Height()/2-1+i,
mylcd.Get_Display_Width()/2-1+i,mylcd.Get_Display_Height()/2-1+i);
}
}
//draw some filled triangles
void fill_triangles_test(void)
{
int i = 0;
mylcd.Fill_Screen(BLACK);
for(i=mylcd.Get_Display_Width()/2-1;i>0;i-=5)
{
mylcd.Set_Draw_color(0,i+64,i+64);
mylcd.Fill_Triangle(mylcd.Get_Display_Width()/2-1,mylcd.Get_Display_Height()/2-1-i,
mylcd.Get_Display_Width()/2-1-i,mylcd.Get_Display_Height()/2-1+i,
mylcd.Get_Display_Width()/2-1+i,mylcd.Get_Display_Height()/2-1+i);
mylcd.Set_Draw_color(i,0,i);
mylcd.Draw_Triangle(mylcd.Get_Display_Width()/2-1,mylcd.Get_Display_Height()/2-1-i,
mylcd.Get_Display_Width()/2-1-i,mylcd.Get_Display_Height()/2-1+i,
mylcd.Get_Display_Width()/2-1+i,mylcd.Get_Display_Height()/2-1+i);
}
}
//draw some round rectangles
void round_rectangle(void)
{
int i = 0;
mylcd.Fill_Screen(BLACK);
for(i = 0;i<mylcd.Get_Display_Width()/2;i+=4)
{
mylcd.Set_Draw_color(255-i,0,160-i);
mylcd.Draw_Round_Rectangle(i,(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2+i,mylcd.Get_Display_Width()-1-i,mylcd.Get_Display_Height()-(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2-i,8);
delay(5);
}
}
//draw some filled round rectangles
void fill_round_rectangle(void)
{
int i = 0;
mylcd.Fill_Screen(BLACK);
for(i = 0;i<mylcd.Get_Display_Width()/2;i+=4)
{
mylcd.Set_Draw_color(255-i,160-i,0);
mylcd.Fill_Round_Rectangle(i,(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2+i,mylcd.Get_Display_Width()-1-i,mylcd.Get_Display_Height()-(mylcd.Get_Display_Height()-mylcd.Get_Display_Width())/2-i,8);
delay(5);
}
}
void setup()
{
Serial.begin(9600);
mylcd.Init_LCD();
Serial.println(mylcd.Read_ID(), HEX);
fill_screen_test();
delay(500);
text_test();
delay(500);
lines_test();
delay(500);
h_l_lines_test();
delay(500);
rectangle_test();
delay(500);
fill_rectangle_test();
delay(500);
fill_circles_test();
delay(500);
circles_test();
delay(500);
triangles_test();
delay(500);
fill_triangles_test();
delay(500);
round_rectangle();
delay(500);
fill_round_rectangle();
delay(3000);
}
void loop()
{
//rotate for four directions
for(uint8_t rotation=0; rotation<4; rotation++)
{
mylcd.Set_Rotation(rotation);
text_test();
delay(2000);
}
}
| [
"[email protected]"
]
| |
2a2a87a0bf860186628a491e66052b752611ee20 | e2885d6a73e93a8991dd8bd076d682b6692143c1 | /src/qt/masternodetablemodel.cpp | 10f64c7a3b28ff87bc6580515171dbf8ebd62fcc | [
"MIT"
]
| permissive | HashUnlimited/chaincoin | 419954d66f87a92b7e7cbac0ecabec85d365cfee | 9a035680d6d9b9a0524dc7524c55cfedd1a683ca | refs/heads/master | 2021-07-13T10:35:51.762640 | 2020-05-31T12:55:03 | 2020-05-31T12:55:03 | 139,189,912 | 0 | 0 | MIT | 2019-04-28T19:35:44 | 2018-06-29T19:53:49 | C++ | UTF-8 | C++ | false | false | 15,485 | cpp | // Copyright (c) 2011-2018 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 <qt/masternodetablemodel.h>
#include <qt/clientmodel.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <interfaces/node.h>
#include <key_io.h>
#include <algorithm>
#include <QColor>
#include <QFont>
#include <QDebug>
const QString MasternodeTableModel::MyNodes = "M";
const QString MasternodeTableModel::AllNodes = "A";
static int column_alignments[] = {
Qt::AlignLeft|Qt::AlignVCenter,
Qt::AlignLeft|Qt::AlignVCenter,
Qt::AlignCenter|Qt::AlignVCenter,
Qt::AlignLeft|Qt::AlignVCenter,
Qt::AlignCenter|Qt::AlignVCenter,
Qt::AlignRight|Qt::AlignVCenter,
Qt::AlignRight|Qt::AlignVCenter,
Qt::AlignLeft|Qt::AlignVCenter
};
struct MasternodeTableEntry
{
enum Type {
MyNodeList,
AllNodeList,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString txhash;
qint32 n;
QString alias;
QString address;
int protocol;
qint32 daemon;
qint32 sentinel;
QString status;
qint64 active;
qint64 lastseen;
QString payee;
int banscore;
QString outpoint() const
{
return QString::fromStdString(strprintf("%s-%u", txhash.toStdString().substr(0,64), n));
}
MasternodeTableEntry() {}
MasternodeTableEntry(Type _type, const QString & _txhash, const qint32& _n, const QString &_alias, const QString &_address,
const int &_protocol, const qint32 &_daemon, const qint32 &_sentinel, const QString &_status,
const qint64 &_active, const qint64 &_lastseen, const QString &_payee, const int &_banscore) :
type(_type), txhash(_txhash), n(_n), alias(_alias), address(_address), protocol(_protocol), daemon (_daemon),
sentinel (_sentinel), status(_status), active(_active), lastseen(_lastseen), payee(_payee), banscore(_banscore) {}
};
/* Determine if our own masternode */
static MasternodeTableEntry::Type translateMasternodeType(const QString &strAlias)
{
MasternodeTableEntry::Type addressType = MasternodeTableEntry::Hidden;
if (strAlias != "")
addressType = MasternodeTableEntry::MyNodeList;
else
addressType = MasternodeTableEntry::AllNodeList;
return addressType;
}
struct outpointEntryLessThan
{
bool operator()(const MasternodeTableEntry &a, const MasternodeTableEntry &b) const
{
return a.outpoint() < b.outpoint();
}
bool operator()(const MasternodeTableEntry &a, const QString &b) const
{
return a.outpoint() < b;
}
bool operator()(const QString &a, const MasternodeTableEntry &b) const
{
return a < b.outpoint();
}
};
// Private implementation
class MasternodeTablePriv
{
public:
explicit MasternodeTablePriv(MasternodeTableModel *_parent):
parent(_parent) {}
MasternodeTableModel *parent;
QList<MasternodeTableEntry> cachedMasternodeTable;
void refreshMasternodeTable(interfaces::Node& node)
{
cachedMasternodeTable.clear();
{
for (const auto& masternode : node.getMasternodes())
{
MasternodeTableEntry::Type addressType = translateMasternodeType(
QString::fromStdString(masternode.alias));
cachedMasternodeTable.append(MasternodeTableEntry(
addressType,
QString::fromStdString(masternode.outpoint.hash.ToString()),
masternode.outpoint.n,
QString::fromStdString(masternode.alias),
QString::fromStdString(masternode.address),
masternode.protocol,
masternode.daemon,
masternode.sentinel,
QString::fromStdString(masternode.status),
masternode.active,
masternode.last_seen,
QString::fromStdString(masternode.payee),
masternode.banscore));
}
}
// std::lower_bound() and std::upper_bound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
std::sort(cachedMasternodeTable.begin(), cachedMasternodeTable.end(), outpointEntryLessThan());
}
void updateMasternode(interfaces::Node& node, const COutPoint& outpoint, int status)
{
qDebug() << "MasternodeTablePriv::updateMasternode" + QString::fromStdString(strprintf("%s-%d", outpoint.hash.ToString(), outpoint.n)) + " " + QString::number(status);
// Find bounds of this masternode in model
QString strOutpoint = QString::fromStdString(outpoint.ToStringShort());
QList<MasternodeTableEntry>::iterator lower = std::lower_bound(
cachedMasternodeTable.begin(), cachedMasternodeTable.end(), strOutpoint, outpointEntryLessThan());
QList<MasternodeTableEntry>::iterator upper = std::upper_bound(
cachedMasternodeTable.begin(), cachedMasternodeTable.end(), strOutpoint, outpointEntryLessThan());
int lowerIndex = (lower - cachedMasternodeTable.begin());
int upperIndex = (upper - cachedMasternodeTable.begin());
bool inModel = (lower != upper);
switch(status)
{
case CT_NEW:
if(inModel)
{
//must be our own one and we are just at a clean start -> try to update
interfaces::Masternode masternode = node.getMasternode(outpoint);
lower->txhash = QString::fromStdString(masternode.outpoint.hash.ToString());
lower->n = masternode.outpoint.n;
lower->alias = QString::fromStdString(masternode.alias);
lower->address = QString::fromStdString(masternode.address);
lower->protocol = masternode.protocol;
lower->daemon = masternode.daemon;
lower->sentinel = masternode.sentinel;
lower->status = QString::fromStdString(masternode.status);
lower->active = masternode.active;
lower->lastseen = masternode.last_seen;
lower->payee = QString::fromStdString(masternode.payee);
lower->banscore = masternode.banscore;
parent->emitDataChanged(lowerIndex);
break;
}
{
// Find masternode on platform
interfaces::Masternode masternode = node.getMasternode(outpoint);
if(masternode.outpoint == COutPoint())
{
qWarning() << "MasternodeTablePriv::updateMasternode: Warning: Got CT_NEW, but masternode is not on platform: " + QString::fromStdString(strprintf("%s-%d", outpoint.hash.ToString(), outpoint.n)) + " " + QString::number(status);
break;
}
// Added -- insert at the right position
MasternodeTableEntry::Type addressType = translateMasternodeType(
QString::fromStdString(masternode.alias));
MasternodeTableEntry toInsert =
MasternodeTableEntry(
addressType,
QString::fromStdString(masternode.outpoint.hash.ToString()),
masternode.outpoint.n,
QString::fromStdString(masternode.alias),
QString::fromStdString(masternode.address),
masternode.protocol,
masternode.daemon,
masternode.sentinel,
QString::fromStdString(masternode.status),
masternode.active,
masternode.last_seen,
QString::fromStdString(masternode.payee),
masternode.banscore);
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedMasternodeTable.insert(lowerIndex, toInsert);
parent->endInsertRows();
}
break;
case CT_DELETED:
if(!inModel)
{
qWarning() << "MasternodeTablePriv::updateMasternode: Warning: Got CT_DELETED, but masternode is not in model: " + QString::fromStdString(strprintf("%s-%d", outpoint.hash.ToString(), outpoint.n)) + " " + QString::number(status);
break;
}
// Removed -- remove entire masternode from table
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedMasternodeTable.erase(lower, upper);
parent->endRemoveRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "MasternodeTablePriv::updateMasternode: Warning: Got CT_UPDATED, but entry is not in model: "+ QString::fromStdString(strprintf("%s-%d", outpoint.hash.ToString(), outpoint.n)) + " " + QString::number(status);
break;
}
{
// Find masternode on platform
interfaces::Masternode masternode = node.getMasternode(outpoint);
//don't remove our own nodes
if(lower->alias == "" && masternode.outpoint == COutPoint())
{
// did we receive a wrong signal? The node got highes priority, delete the entry
qWarning() << "MasternodeTablePriv::updateMasternode: Warning: Got CT_UPDATED, but masternode is not on platform: " + QString::fromStdString(strprintf("%s-%d", outpoint.hash.ToString(), outpoint.n)) + " " + QString::number(status);
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedMasternodeTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
MasternodeTableEntry::Type addressType = translateMasternodeType(
QString::fromStdString(masternode.alias));
lower->type = addressType;
lower->txhash = QString::fromStdString(masternode.outpoint.hash.ToString());
lower->n = masternode.outpoint.n;
lower->alias = QString::fromStdString(masternode.alias);
lower->address = QString::fromStdString(masternode.address);
lower->protocol = masternode.protocol;
lower->daemon = masternode.daemon;
lower->sentinel = masternode.sentinel;
lower->status = QString::fromStdString(masternode.status);
lower->active = masternode.active;
lower->lastseen = masternode.last_seen;
lower->payee = QString::fromStdString(masternode.payee);
lower->banscore = masternode.banscore;
parent->emitDataChanged(lowerIndex);
}
break;
}
}
int size()
{
return cachedMasternodeTable.size();
}
MasternodeTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedMasternodeTable.size())
{
MasternodeTableEntry *rec = &cachedMasternodeTable[idx];
return rec;
}
return 0;
}
};
MasternodeTableModel::MasternodeTableModel(ClientModel *parent) :
QAbstractTableModel(parent),
clientModel(parent),
priv(new MasternodeTablePriv(this))
{
columns << tr("Alias") << tr("Address") << tr("Version") << tr("Status") << tr("Score") << tr("Active") << tr("Last Seen") << tr("Payee");
priv->refreshMasternodeTable(clientModel->node());
// Subscribe for updates
connect(clientModel, &ClientModel::updateMasternode, this, &MasternodeTableModel::updateMasternode);
}
MasternodeTableModel::~MasternodeTableModel()
{
delete priv;
}
void MasternodeTableModel::updateMasternode(const QString &_hash, const int &_n, int status)
{
COutPoint outpoint = COutPoint(uint256S(_hash.toStdString()), _n);
priv->updateMasternode(clientModel->node(), outpoint, status);
}
int MasternodeTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int MasternodeTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant MasternodeTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
MasternodeTableEntry *rec = static_cast<MasternodeTableEntry*>(index.internalPointer());
switch(role)
{
case Qt::DisplayRole:
switch(index.column())
{
case Alias:
return QString(rec->alias);
case Address:
return QString(rec->address);
case Daemon:
return qint32(rec->daemon);
case Status:
return QString(rec->status);
case Score:
return int(rec->banscore);
case Active:
return GUIUtil::formatNiceTimeOffset(rec->active);
case Last_Seen:
if (rec->lastseen > 0)
return (QDateTime::fromTime_t(rec->lastseen)).date().toString(Qt::SystemLocaleLongDate);
else {
QString ret = tr("never");
return ret;
}
case Payee:
return QString(rec->payee);
default: break;
}
case TypeRole:
switch(rec->type)
{
case MasternodeTableEntry::MyNodeList:
return MyNodes;
case MasternodeTableEntry::AllNodeList:
return AllNodes;
default: break;
}
case TxHashRole:
return rec->txhash;
case TxOutIndexRole:
return rec->n;
case Qt::TextAlignmentRole:
return column_alignments[index.column()];
case Qt::ForegroundRole:
if(index.column() == Status) {
if(rec->status == "MISSING" || rec->status == "NEW_START_REQUIRED") {
return COLOR_NEGATIVE;
} else if (rec->status == "ENABLED"){
return COLOR_GREEN;
}
}
return COLOR_BLACK;
default: break;
}
return QVariant();
}
QVariant MasternodeTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
QModelIndex MasternodeTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
MasternodeTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void MasternodeTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
| [
""
]
| |
633eada1279987e41c87ed66c1c465982f13638f | 025d8ec5de37eb5f4270d23dec9899b08fdef391 | /src/qt/signverifymessagedialog.cpp | c62b21eb42b4297c4775237782ebb63f2bfaa189 | [
"MIT"
]
| permissive | ed-ro0t/GrimMasterNode | e877a9bb98ca6af02dcea848700b3dd2c4c5b754 | bec5bed23a22b49cc9ce6c6f8c7ddc213bcf0fcd | refs/heads/master | 2020-03-23T14:46:01.099858 | 2018-07-18T20:39:01 | 2018-07-18T20:39:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,789 | cpp | #include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "base58.h"
#include "guiutil.h"
#include "init.h"
#include "main.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include <QClipboard>
#include <string>
#include <vector>
SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0)
{
ui->setupUi(this);
#if (QT_VERSION >= 0x040700)
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addressIn_SM->setPlaceholderText(tr("Enter a Grim address (e.g. E8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)"));
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
ui->addressIn_VM->setPlaceholderText(tr("Enter a Grim address (e.g. E8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)"));
ui->signatureIn_VM->setPlaceholderText(tr("Enter Grim signature"));
#endif
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *model)
{
this->model = model;
}
void SignVerifyMessageDialog::setAddress_SM(QString address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(QString address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
if (!model)
return;
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CGrimAddress addr(ui->addressIn_SM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!pwalletMain->GetKey(keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
QApplication::clipboard()->setText(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CGrimAddress addr(ui->addressIn_VM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CPubKey pubkey;
if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CGrimAddress(pubkey.GetID()) == addr))
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
| [
"[email protected]"
]
| |
691031a2c6e6cb095e9c5732c6a425cd85f6708a | 7b2456c98c94ff1c9a0334b24797a85ecc5cff21 | /codeforces/507B - Amr and pins.cpp | 21cfa54b5ed2d0e8c320a01c92d796362f48d5cb | []
| no_license | bkorecic/competitive-programming-solutions | fe694b485f10d5b90903552efd3e740e90891c94 | f7edecc7bfb318992ea4e49cae11942e1e1e6879 | refs/heads/master | 2021-12-15T04:43:23.722769 | 2021-12-12T05:59:50 | 2021-12-12T05:59:50 | 211,429,503 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ii> vii;
#define FOR(i, a, b) for (int i=a; i<(b); i++)
#define F0R(i, a) for (int i=0; i<(a); i++)
#define EPS 1-e6
#define INF 1e6
#define PI acos(-1.0)
#define mp make_pair
#define pb push_back
#define f first
#define s second
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
double r, x, y, xf, yf; cin >> r >> x >> y >> xf >> yf;
double distance = sqrt((xf-x)*(xf-x) + (yf-y)*(yf-y));
distance /= 2.0*r;
cout << ceil(distance) << '\n';
return 0;
}
| [
"[email protected]"
]
| |
15596fcdd975fe33a8ac9f8fba35418e19ce9fcb | 675ad919b372939fcc4cd2ccffd62817522caaad | /source/core/testing/testing_spectrum.hpp | bd878dfb0a0b6aef2089ee1727dfd86a3ac6def4 | []
| no_license | lineCode/sprout | 2308ff7de515c6499ffb5bf6889bf9ccebc6b2bd | ffaefc1c6ffd5f8fb6da3acbe98d05555586791e | refs/heads/master | 2020-04-05T06:15:25.954312 | 2018-11-07T09:41:57 | 2018-11-07T09:41:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54 | hpp | #pragma once
namespace testing {
void spectrum();
}
| [
"[email protected]"
]
| |
3366ffc09f145c6ef5d85ab3a6a4c944df915958 | 7538073b4bbb6ee7f199db698f2a0fa8d883416e | /main.cpp | 8489a15b6f8925068a1e44a95a1816f2340fa00e | []
| no_license | danielcu888/ColourChart | 96eaddb6d71ccc793cf7b21ac1e724caa7431e3a | 15725406a25b0dbe1bbfc969bc43e8bda08782eb | refs/heads/master | 2020-03-26T18:34:24.213776 | 2018-08-18T12:57:53 | 2018-08-18T12:58:58 | 85,432,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,847 | cpp | #define CONDUCT_UNIT_TESTING 1 //Set to 1 for unit testing, otherwise 0 to run normal application.
#include <cstdlib>
#include <iostream>
#include <string>
#include "Utilities.h"
#include "Display.h"
#include "ColourRGB565.h"
#include "ColourRampGenerator.h"
#include "unit_tests.h"
using std::cerr; using std::endl;
using std::string; using std::cout;
int main(int argc, char *argv[])
{
#if CONDUCT_UNIT_TESTING
// conduct unit testing
call_unit_tests();
#else
// check for correct number of arguments (min 2 colours, max of 4 colours)
if(argc < 4 || argc > 6)
{
cerr << "Usage: <program name> <display name> <top left colour (hex or dec)> <top right colour (hex or dec)> "
"[<bottom left colour (hex or dec)>] [<bottom right colour (hex or dec)>]" << endl;
return EXIT_FAILURE;
}
const string display_name = argv[1]; // get display device name
// get [2,4] 16-bit RGB colour codes from CL arguments:
bool *valid = new bool[4]; // check if valid input
for(unsigned int i = 0; i < 4; ++i) // set validity to false by default
valid[i] = false;
unsigned short *cols = new unsigned short[4]; // storage for colour codes (we read up to 4)
//get colours passed in via command line
for(unsigned int i = 0; i < static_cast<unsigned int>(argc-2); ++i)
{
const string tmp = argv[i+2]; // next argument
if(utilities::valid_16bit_hex(tmp)) // check if its a valid hex
{
valid[i] = true;
cols[i] = utilities::hex_to_ushort(tmp);
}
else if(utilities::valid_ushort(tmp))
{
valid[i] = true;
cols[i] = utilities::str_to_ushort(tmp);
}
else
{
cerr << "Warning: invalid colour!" << endl;
// skip argument, validity still false
}
}
// Get 4 colours' codes, utilising valid inputs, if possible. If not, exit.
if(valid[0] && !valid[2])
cols[2] = cols[0];
else if(!valid[0] && valid[2])
{
cerr << "Warning: Invalid top-left colour - replacing with bottom-left colour." << endl;
cols[0] = cols[2];
}
else if(!valid[0] && !valid[2])
{
cout << "ERROR: Insufficient colours on left hand side - exiting." << endl;
return EXIT_FAILURE;
}
if(valid[1] && !valid[3])
cols[3] = cols[1];
else if(!valid[1] && valid[3])
{
cout << "Warning: Invalid top-right colour - replacing with bottom-right colour." << endl;
cols[1] = cols[3];
}
else if(!valid[1] && !valid[3])
{
cerr << "Insufficient colours on right hand side - exiting." << endl;
return EXIT_FAILURE;
}
delete [] valid; valid = NULL;
// Now we should have 4 unsigned shorts corresponding to 4 colours.
// set up display object and connect to device
Display display;
if(!display.connect(display_name.c_str()))
{
cerr << "ERROR: Cannot connect to display device - exiting!" << endl;
return EXIT_FAILURE;
}
// get screen dimensions
int screen_width, screen_height;
display.get_size(screen_width, screen_height);
if (screen_width < 1 || screen_height < 1)
{
cerr << "ERROR: Area of screen is zero - exiting!" << endl;
return EXIT_FAILURE;
}
// construct the 4 corner colours
const ColourRGB565 tl(cols[0]), tr(cols[1]), bl(cols[2]), br(cols[3]);
const unsigned int min_row = 0, min_col = 0; // we are to fill entire screen
// get abstract base class reference to generator of rows of pixels via static factory method
ColourRampGenerator* crg = ColourRampGenerator::create(tl, tr, bl, br, screen_width, screen_height, min_row, min_col);
// populate screen with interpolate rows of pixels
unsigned short *pixels = new unsigned short[screen_width];
for(unsigned int row = 0; row < static_cast<unsigned int>(screen_height); ++row)
{
crg->get_row(min_col, row, screen_width, pixels);
display.draw_raster(min_col, row, pixels, screen_width);
}
// free resources
delete [] pixels; pixels = NULL;
delete [] cols; cols = NULL;
delete crg; crg = NULL;
#endif
return EXIT_SUCCESS;
}
| [
"[email protected]"
]
| |
6260e5b4e492de8f72905402e97be5c596c7d358 | 81a942d959f8712491be7a92e535020f24c7096d | /test/extensions/filters/http/ext_proc/utils.cc | c9bb93b4738d5c143b2251b9db64280957de27a9 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | siepkes/envoy-smartos | c83d4498a11eb6e866f81b19bfe0b439af9a3a8b | e5ffbbb24f7b53d594f6acf6b3f74df82b1c972d | refs/heads/smartos-v1.18.4 | 2023-08-16T11:33:19.306548 | 2021-10-21T07:58:51 | 2021-10-21T07:58:51 | 135,030,335 | 7 | 0 | Apache-2.0 | 2021-10-05T23:36:57 | 2018-05-27T08:51:09 | C++ | UTF-8 | C++ | false | false | 833 | cc | #include "test/extensions/filters/http/ext_proc/utils.h"
#include "test/test_common/utility.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace ExternalProcessing {
bool ExtProcTestUtility::headerProtosEqualIgnoreOrder(
const Http::HeaderMap& expected, const envoy::config::core::v3::HeaderMap& actual) {
// Comparing header maps is hard because they have duplicates in them.
// So we're going to turn them into a HeaderMap and let Envoy do the work.
Http::TestRequestHeaderMapImpl actual_headers;
for (const auto& header : actual.headers()) {
actual_headers.addCopy(header.key(), header.value());
}
return TestUtility::headerMapEqualIgnoreOrder(expected, actual_headers);
}
} // namespace ExternalProcessing
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
| [
"[email protected]"
]
| |
0f995309c64523f2be00d5366c09f1e0e62e51ba | 8b5f0a1c8e56fabc757daf06fc595e56f281279c | /android-flutter/app/src/main/cpp/WfirstRWLock.h | e94e6a683eb0d6f91b64fe649c77894cca58434f | []
| no_license | toberole/flutter-hybrid | 2eef10917c6aa1f732988069f1fb853a43df3138 | 586d2a0b35713746d9d7134b6fe6e41fad644118 | refs/heads/main | 2023-07-22T21:24:34.637598 | 2021-09-01T05:06:10 | 2021-09-01T05:06:10 | 331,244,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,248 | h | #ifndef __WRITE_FIRST_RW_LOCK_H
#define __WRITE_FIRST_RW_LOCK_H
#include <mutex>
#include <condition_variable>
class WfirstRWLock {
public:
WfirstRWLock() = default;
~WfirstRWLock() = default;
public:
void lock_read() {
std::unique_lock <std::mutex> ulk(counter_mutex);
cond_r.wait(ulk, [=]() -> bool { return write_cnt == 0; });
++read_cnt;
}
void lock_write() {
std::unique_lock <std::mutex> ulk(counter_mutex);
++write_cnt;
cond_w.wait(ulk, [=]() -> bool { return read_cnt == 0 && !inwriteflag; });
inwriteflag = true;
}
void release_read() {
std::unique_lock <std::mutex> ulk(counter_mutex);
if (--read_cnt == 0 && write_cnt > 0) {
cond_w.notify_one();
}
}
void release_write() {
std::unique_lock <std::mutex> ulk(counter_mutex);
if (--write_cnt == 0) {
cond_r.notify_all();
} else {
cond_w.notify_one();
}
inwriteflag = false;
}
private:
volatile size_t read_cnt{0};
volatile size_t write_cnt{0};
volatile bool inwriteflag{false};
std::mutex counter_mutex;
std::condition_variable cond_w;
std::condition_variable cond_r;
};
template<typename _RWLockable>
class unique_writeguard {
public:
explicit unique_writeguard(_RWLockable &rw_lockable)
: rw_lockable_(rw_lockable) {
rw_lockable_.lock_write();
}
~unique_writeguard() {
rw_lockable_.release_write();
}
private:
unique_writeguard() = delete;
unique_writeguard(const unique_writeguard &) = delete;
unique_writeguard &operator=(const unique_writeguard &) = delete;
private:
_RWLockable &rw_lockable_;
};
template<typename _RWLockable>
class unique_readguard {
public:
explicit unique_readguard(_RWLockable &rw_lockable)
: rw_lockable_(rw_lockable) {
rw_lockable_.lock_read();
}
~unique_readguard() {
rw_lockable_.release_read();
}
private:
unique_readguard() = delete;
unique_readguard(const unique_readguard &) = delete;
unique_readguard &operator=(const unique_readguard &) = delete;
private:
_RWLockable &rw_lockable_;
};
#endif | [
"[email protected]"
]
| |
c43765f17f3f623181a1b539a5a42eb89bf24aa0 | f45c8775c0517fdc46939e6d5d728a09a7fe55e3 | /atcoder/abc182/C.cpp | b716f684c62cfdd90e85cd3f015d2bb0f8fe6c93 | []
| no_license | Radhesh-Sarma/Competitive-Coding | 6550af86545d7456923c559a78784af201f57e4e | ce71acaa912249717a8f6cbf7584034548db7951 | refs/heads/main | 2023-02-23T09:40:57.401882 | 2021-01-31T15:53:24 | 2021-01-31T15:53:24 | 191,410,831 | 0 | 1 | null | 2019-06-11T16:34:32 | 2019-06-11T16:34:31 | null | UTF-8 | C++ | false | false | 2,137 | cpp | #include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define int long long
#define endl "\n"
#define all(v) v.begin(),v.end()
#define double long double
#define trace1(x) cerr<<#x<<": "<<x<<endl
#define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e) cerr<<#a<<": "<<a<<" | "<<#b<< ": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl
#define cases int testcases;cin>>testcases; while(testcases--)
const int N = 200005;
int zero,one,two;
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
IOS
string s;
cin >> s;
int sum = 0;
for(int i = 0;i < s.size(); i++)
{
int x = s[i] - '0';
sum += x%3;
if(x % 3 == 0)zero++;
else if(x%3 == 1)one++;
else two++;
}
sum %= 3;
if(sum == 0)
{
cout << 0 << endl;
return 0;
}
if(sum == 1)
{
if(one> 0 and s.size() - 1 != 0)
{
cout << 1 << endl;
return 0;
}
if(two > 1 and s.size() - 2 != 0)
{
cout << 2 << endl;
return 0;
}
cout << -1 << endl;
}
if(sum == 2)
{
if(two > 0 and s.size() - 1 != 0)
{
cout << 1 << endl;
return 0;
}
if(one > 1 and s.size() - 2 != 0)
{
cout << 2 << endl;
return 0;
}
cout << -1 << endl;
}
return 0;
}
| [
"[email protected]"
]
| |
7d8cb218dac9cb5614e8eaddbcf5122113cb955c | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chromeos/services/device_sync/cryptauth_v2_enrollment_manager_impl.cc | 3815d1683f4c37b71184b1074e3b6c9e10ad3148 | [
"BSD-3-Clause"
]
| permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 20,254 | cc | // Copyright 2019 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 "chromeos/services/device_sync/cryptauth_v2_enrollment_manager_impl.h"
#include <utility>
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/no_destructor.h"
#include "base/time/clock.h"
#include "base/timer/timer.h"
#include "base/values.h"
#include "chromeos/components/multidevice/logging/logging.h"
#include "chromeos/services/device_sync/cryptauth_constants.h"
#include "chromeos/services/device_sync/cryptauth_key_registry.h"
#include "chromeos/services/device_sync/cryptauth_v2_enroller_impl.h"
#include "chromeos/services/device_sync/pref_names.h"
#include "chromeos/services/device_sync/public/cpp/client_app_metadata_provider.h"
#include "chromeos/services/device_sync/value_string_encoding.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
namespace chromeos {
namespace device_sync {
namespace {
// Timeout values for asynchronous operations.
// TODO(https://crbug.com/933656): Tune these values.
constexpr base::TimeDelta kWaitingForGcmRegistrationTimeout =
base::TimeDelta::FromSeconds(10);
constexpr base::TimeDelta kWaitingForClientAppMetadataTimeout =
base::TimeDelta::FromSeconds(10);
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class UserKeyPairState {
// No v1 key; no v2 key. (Not enrolled)
kNoV1KeyNoV2Key = 0,
// v1 key exists; no v2 key. (Only v1 enrolled)
kYesV1KeyNoV2Key = 1,
// No v1 key; v2 key exists. (Only v2 enrolled)
kNoV1KeyYesV2Key = 2,
// v1 and v2 keys exist and agree.
kYesV1KeyYesV2KeyAgree = 3,
// v1 and v2 keys exist and disagree. (Enrolled with v2, rolled back to v1,
// enrolled with v1, rolled forward to v2)
kYesV1KeyYesV2KeyDisagree = 4,
kMaxValue = kYesV1KeyYesV2KeyDisagree
};
cryptauthv2::ClientMetadata::InvocationReason ConvertInvocationReasonV1ToV2(
cryptauth::InvocationReason invocation_reason_v1) {
switch (invocation_reason_v1) {
case cryptauth::InvocationReason::INVOCATION_REASON_UNKNOWN:
return cryptauthv2::ClientMetadata::INVOCATION_REASON_UNSPECIFIED;
case cryptauth::InvocationReason::INVOCATION_REASON_INITIALIZATION:
return cryptauthv2::ClientMetadata::INITIALIZATION;
case cryptauth::InvocationReason::INVOCATION_REASON_PERIODIC:
return cryptauthv2::ClientMetadata::PERIODIC;
case cryptauth::InvocationReason::INVOCATION_REASON_SLOW_PERIODIC:
return cryptauthv2::ClientMetadata::SLOW_PERIODIC;
case cryptauth::InvocationReason::INVOCATION_REASON_FAST_PERIODIC:
return cryptauthv2::ClientMetadata::FAST_PERIODIC;
case cryptauth::InvocationReason::INVOCATION_REASON_EXPIRATION:
return cryptauthv2::ClientMetadata::EXPIRATION;
case cryptauth::InvocationReason::INVOCATION_REASON_FAILURE_RECOVERY:
return cryptauthv2::ClientMetadata::FAILURE_RECOVERY;
case cryptauth::InvocationReason::INVOCATION_REASON_NEW_ACCOUNT:
return cryptauthv2::ClientMetadata::NEW_ACCOUNT;
case cryptauth::InvocationReason::INVOCATION_REASON_CHANGED_ACCOUNT:
return cryptauthv2::ClientMetadata::CHANGED_ACCOUNT;
case cryptauth::InvocationReason::INVOCATION_REASON_FEATURE_TOGGLED:
return cryptauthv2::ClientMetadata::FEATURE_TOGGLED;
case cryptauth::InvocationReason::INVOCATION_REASON_SERVER_INITIATED:
return cryptauthv2::ClientMetadata::SERVER_INITIATED;
case cryptauth::InvocationReason::INVOCATION_REASON_ADDRESS_CHANGE:
return cryptauthv2::ClientMetadata::ADDRESS_CHANGE;
case cryptauth::InvocationReason::INVOCATION_REASON_SOFTWARE_UPDATE:
return cryptauthv2::ClientMetadata::SOFTWARE_UPDATE;
case cryptauth::InvocationReason::INVOCATION_REASON_MANUAL:
return cryptauthv2::ClientMetadata::MANUAL;
default:
PA_LOG(WARNING) << "Unknown v1 invocation reason: "
<< invocation_reason_v1;
return cryptauthv2::ClientMetadata::INVOCATION_REASON_UNSPECIFIED;
}
}
void RecordEnrollmentResult(CryptAuthEnrollmentResult result) {
base::UmaHistogramBoolean("CryptAuth.EnrollmentV2.Result.Success",
result.IsSuccess());
base::UmaHistogramEnumeration("CryptAuth.EnrollmentV2.Result.ResultCode",
result.result_code());
}
void RecordUserKeyPairState(const std::string& public_key_v1,
const std::string& private_key_v1,
const CryptAuthKey* key_v2) {
bool v1_key_exists = !public_key_v1.empty() && !private_key_v1.empty();
UserKeyPairState key_pair_state;
if (v1_key_exists && key_v2) {
if (public_key_v1 == key_v2->public_key() &&
private_key_v1 == key_v2->private_key()) {
key_pair_state = UserKeyPairState::kYesV1KeyYesV2KeyAgree;
} else {
key_pair_state = UserKeyPairState::kYesV1KeyYesV2KeyDisagree;
}
} else if (v1_key_exists && !key_v2) {
key_pair_state = UserKeyPairState::kYesV1KeyNoV2Key;
} else if (!v1_key_exists && key_v2) {
key_pair_state = UserKeyPairState::kNoV1KeyYesV2Key;
} else {
key_pair_state = UserKeyPairState::kNoV1KeyNoV2Key;
}
base::UmaHistogramEnumeration("CryptAuth.EnrollmentV2.UserKeyPairState",
key_pair_state);
}
} // namespace
// static
CryptAuthV2EnrollmentManagerImpl::Factory*
CryptAuthV2EnrollmentManagerImpl::Factory::test_factory_ = nullptr;
// static
CryptAuthV2EnrollmentManagerImpl::Factory*
CryptAuthV2EnrollmentManagerImpl::Factory::Get() {
if (test_factory_)
return test_factory_;
static base::NoDestructor<CryptAuthV2EnrollmentManagerImpl::Factory> factory;
return factory.get();
}
// static
void CryptAuthV2EnrollmentManagerImpl::Factory::SetFactoryForTesting(
Factory* test_factory) {
test_factory_ = test_factory;
}
// static
void CryptAuthV2EnrollmentManagerImpl::RegisterPrefs(
PrefRegistrySimple* registry) {
// TODO(nohle): Remove when v1 Enrollment is deprecated.
registry->RegisterStringPref(prefs::kCryptAuthEnrollmentUserPublicKey,
std::string());
registry->RegisterStringPref(prefs::kCryptAuthEnrollmentUserPrivateKey,
std::string());
}
// static
// Note: The enroller handles timeouts internally.
base::Optional<base::TimeDelta>
CryptAuthV2EnrollmentManagerImpl::GetTimeoutForState(State state) {
switch (state) {
case State::kWaitingForGcmRegistration:
return kWaitingForGcmRegistrationTimeout;
case State::kWaitingForClientAppMetadata:
return kWaitingForClientAppMetadataTimeout;
default:
// Signifies that there should not be a timeout.
return base::nullopt;
}
}
// static
base::Optional<CryptAuthEnrollmentResult::ResultCode>
CryptAuthV2EnrollmentManagerImpl::ResultCodeErrorFromState(State state) {
switch (state) {
case State::kWaitingForGcmRegistration:
return CryptAuthEnrollmentResult::ResultCode::
kErrorTimeoutWaitingForGcmRegistration;
case State::kWaitingForClientAppMetadata:
return CryptAuthEnrollmentResult::ResultCode::
kErrorTimeoutWaitingForClientAppMetadata;
default:
return base::nullopt;
}
}
CryptAuthV2EnrollmentManagerImpl::Factory::~Factory() = default;
std::unique_ptr<CryptAuthEnrollmentManager>
CryptAuthV2EnrollmentManagerImpl::Factory::BuildInstance(
ClientAppMetadataProvider* client_app_metadata_provider,
CryptAuthKeyRegistry* key_registry,
CryptAuthClientFactory* client_factory,
CryptAuthGCMManager* gcm_manager,
CryptAuthScheduler* scheduler,
PrefService* pref_service,
base::Clock* clock,
std::unique_ptr<base::OneShotTimer> timer) {
return base::WrapUnique(new CryptAuthV2EnrollmentManagerImpl(
client_app_metadata_provider, key_registry, client_factory, gcm_manager,
scheduler, pref_service, clock, std::move(timer)));
}
CryptAuthV2EnrollmentManagerImpl::CryptAuthV2EnrollmentManagerImpl(
ClientAppMetadataProvider* client_app_metadata_provider,
CryptAuthKeyRegistry* key_registry,
CryptAuthClientFactory* client_factory,
CryptAuthGCMManager* gcm_manager,
CryptAuthScheduler* scheduler,
PrefService* pref_service,
base::Clock* clock,
std::unique_ptr<base::OneShotTimer> timer)
: client_app_metadata_provider_(client_app_metadata_provider),
key_registry_(key_registry),
client_factory_(client_factory),
gcm_manager_(gcm_manager),
scheduler_(scheduler),
pref_service_(pref_service),
clock_(clock),
timer_(std::move(timer)),
callback_weak_ptr_factory_(this),
scheduler_weak_ptr_factory_(this) {
// TODO(nohle): Remove when v1 Enrollment is deprecated.
AddV1UserKeyPairToRegistryIfNecessary();
gcm_manager_->AddObserver(this);
}
CryptAuthV2EnrollmentManagerImpl::~CryptAuthV2EnrollmentManagerImpl() {
gcm_manager_->RemoveObserver(this);
}
void CryptAuthV2EnrollmentManagerImpl::Start() {
scheduler_->StartEnrollmentScheduling(
scheduler_weak_ptr_factory_.GetWeakPtr());
// It is possible, though unlikely, that |scheduler_| has previously enrolled
// successfully but |key_registry_| no longer holds the enrolled keys, for
// example, if keys are deleted from the key registry or if the persisted key
// registry pref cannot be parsed due to an encoding change. In this case,
// force a re-enrollment.
if (scheduler_->GetLastSuccessfulEnrollmentTime() &&
(GetUserPublicKey().empty() || GetUserPrivateKey().empty())) {
ForceEnrollmentNow(
cryptauth::InvocationReason::INVOCATION_REASON_FAILURE_RECOVERY,
base::nullopt /* session_id */);
}
}
void CryptAuthV2EnrollmentManagerImpl::ForceEnrollmentNow(
cryptauth::InvocationReason invocation_reason,
const base::Optional<std::string>& session_id) {
scheduler_->RequestEnrollment(
ConvertInvocationReasonV1ToV2(invocation_reason), session_id);
}
bool CryptAuthV2EnrollmentManagerImpl::IsEnrollmentValid() const {
base::Optional<base::Time> last_successful_enrollment_time =
scheduler_->GetLastSuccessfulEnrollmentTime();
if (!last_successful_enrollment_time)
return false;
if (GetUserPublicKey().empty() || GetUserPrivateKey().empty())
return false;
return (clock_->Now() - *last_successful_enrollment_time) <
scheduler_->GetRefreshPeriod();
}
base::Time CryptAuthV2EnrollmentManagerImpl::GetLastEnrollmentTime() const {
base::Optional<base::Time> last_successful_enrollment_time =
scheduler_->GetLastSuccessfulEnrollmentTime();
if (!last_successful_enrollment_time)
return base::Time();
return *last_successful_enrollment_time;
}
base::TimeDelta CryptAuthV2EnrollmentManagerImpl::GetTimeToNextAttempt() const {
return scheduler_->GetTimeToNextEnrollmentRequest().value_or(
base::TimeDelta::Max());
}
bool CryptAuthV2EnrollmentManagerImpl::IsEnrollmentInProgress() const {
return state_ != State::kIdle;
}
bool CryptAuthV2EnrollmentManagerImpl::IsRecoveringFromFailure() const {
return scheduler_->GetNumConsecutiveEnrollmentFailures() > 0;
}
std::string CryptAuthV2EnrollmentManagerImpl::GetUserPublicKey() const {
const CryptAuthKey* user_key_pair =
key_registry_->GetActiveKey(CryptAuthKeyBundle::Name::kUserKeyPair);
// If a v1 key exists, it should have been added to the v2 registry already by
// AddV1UserKeyPairToRegistryIfNecessary().
DCHECK(
GetV1UserPublicKey().empty() ||
(user_key_pair && user_key_pair->public_key() == GetV1UserPublicKey()));
if (!user_key_pair)
return std::string();
return user_key_pair->public_key();
}
std::string CryptAuthV2EnrollmentManagerImpl::GetUserPrivateKey() const {
const CryptAuthKey* user_key_pair =
key_registry_->GetActiveKey(CryptAuthKeyBundle::Name::kUserKeyPair);
std::string private_key_v1 = GetV1UserPrivateKey();
// If a v1 key exists, it should have been added to the v2 registry already by
// AddV1UserKeyPairToRegistryIfNecessary().
DCHECK(
GetV1UserPrivateKey().empty() ||
(user_key_pair && user_key_pair->private_key() == GetV1UserPrivateKey()));
if (!user_key_pair)
return std::string();
return user_key_pair->private_key();
}
void CryptAuthV2EnrollmentManagerImpl::OnEnrollmentRequested(
const cryptauthv2::ClientMetadata& client_metadata,
const base::Optional<cryptauthv2::PolicyReference>&
client_directive_policy_reference) {
DCHECK(state_ == State::kIdle);
NotifyEnrollmentStarted();
current_client_metadata_ = client_metadata;
client_directive_policy_reference_ = client_directive_policy_reference;
base::UmaHistogramExactLinear(
"CryptAuth.EnrollmentV2.InvocationReason",
current_client_metadata_->invocation_reason(),
cryptauthv2::ClientMetadata::InvocationReason_ARRAYSIZE);
AttemptEnrollment();
}
void CryptAuthV2EnrollmentManagerImpl::OnGCMRegistrationResult(bool success) {
if (state_ != State::kWaitingForGcmRegistration)
return;
if (!success || gcm_manager_->GetRegistrationId().empty()) {
OnEnrollmentFinished(CryptAuthEnrollmentResult(
CryptAuthEnrollmentResult::ResultCode::kErrorGcmRegistrationFailed,
base::nullopt /* client_directive */));
return;
}
AttemptEnrollment();
}
void CryptAuthV2EnrollmentManagerImpl::OnReenrollMessage(
const base::Optional<std::string>& session_id,
const base::Optional<CryptAuthFeatureType>& feature_type) {
ForceEnrollmentNow(cryptauth::INVOCATION_REASON_SERVER_INITIATED, session_id);
}
void CryptAuthV2EnrollmentManagerImpl::OnClientAppMetadataFetched(
const base::Optional<cryptauthv2::ClientAppMetadata>& client_app_metadata) {
DCHECK(state_ == State::kWaitingForClientAppMetadata);
if (!client_app_metadata) {
OnEnrollmentFinished(
CryptAuthEnrollmentResult(CryptAuthEnrollmentResult::ResultCode::
kErrorClientAppMetadataFetchFailed,
base::nullopt /* client_directive */));
return;
}
client_app_metadata_ = client_app_metadata;
AttemptEnrollment();
}
void CryptAuthV2EnrollmentManagerImpl::AttemptEnrollment() {
if (gcm_manager_->GetRegistrationId().empty()) {
SetState(State::kWaitingForGcmRegistration);
gcm_manager_->RegisterWithGCM();
return;
}
if (!client_app_metadata_) {
SetState(State::kWaitingForClientAppMetadata);
client_app_metadata_provider_->GetClientAppMetadata(
gcm_manager_->GetRegistrationId(),
base::BindOnce(
&CryptAuthV2EnrollmentManagerImpl::OnClientAppMetadataFetched,
callback_weak_ptr_factory_.GetWeakPtr()));
return;
}
Enroll();
}
void CryptAuthV2EnrollmentManagerImpl::Enroll() {
DCHECK(current_client_metadata_);
DCHECK(client_app_metadata_);
enroller_ = CryptAuthV2EnrollerImpl::Factory::Get()->BuildInstance(
key_registry_, client_factory_);
SetState(State::kWaitingForEnrollment);
enroller_->Enroll(
*current_client_metadata_, *client_app_metadata_,
client_directive_policy_reference_,
base::BindOnce(&CryptAuthV2EnrollmentManagerImpl::OnEnrollmentFinished,
callback_weak_ptr_factory_.GetWeakPtr()));
}
void CryptAuthV2EnrollmentManagerImpl::OnEnrollmentFinished(
const CryptAuthEnrollmentResult& enrollment_result) {
// Once an enrollment attempt finishes, no other callbacks should be
// invoked. This is particularly relevant for timeout failures.
callback_weak_ptr_factory_.InvalidateWeakPtrs();
enroller_.reset();
if (enrollment_result.IsSuccess()) {
PA_LOG(INFO) << "Enrollment attempt with invocation reason "
<< current_client_metadata_->invocation_reason()
<< " succeeded with result code "
<< enrollment_result.result_code();
} else {
PA_LOG(WARNING) << "Enrollment attempt with invocation reason "
<< current_client_metadata_->invocation_reason()
<< " failed with result code "
<< enrollment_result.result_code();
}
current_client_metadata_.reset();
RecordEnrollmentResult(enrollment_result);
scheduler_->HandleEnrollmentResult(enrollment_result);
PA_LOG(INFO) << "Time until next enrollment attempt: "
<< GetTimeToNextAttempt();
if (!enrollment_result.IsSuccess()) {
PA_LOG(INFO) << "Number of consecutive Enrollment failures: "
<< scheduler_->GetNumConsecutiveEnrollmentFailures();
}
SetState(State::kIdle);
NotifyEnrollmentFinished(enrollment_result.IsSuccess());
}
void CryptAuthV2EnrollmentManagerImpl::SetState(State state) {
timer_->Stop();
PA_LOG(INFO) << "Transitioning from " << state_ << " to " << state;
state_ = state;
base::Optional<base::TimeDelta> timeout_for_state = GetTimeoutForState(state);
if (!timeout_for_state)
return;
base::Optional<CryptAuthEnrollmentResult::ResultCode> error_code =
ResultCodeErrorFromState(state);
// If there's a timeout specified, there should be a corresponding error
// code.
DCHECK(error_code);
// TODO(https://crbug.com/936273): Add metrics to track failure rates due to
// async timeouts.
timer_->Start(
FROM_HERE, *timeout_for_state,
base::BindOnce(&CryptAuthV2EnrollmentManagerImpl::OnEnrollmentFinished,
callback_weak_ptr_factory_.GetWeakPtr(),
CryptAuthEnrollmentResult(
*error_code, base::nullopt /*client_directive */)));
}
std::string CryptAuthV2EnrollmentManagerImpl::GetV1UserPublicKey() const {
base::Optional<std::string> public_key = util::DecodeFromValueString(
pref_service_->Get(prefs::kCryptAuthEnrollmentUserPublicKey));
if (!public_key) {
PA_LOG(ERROR) << "Invalid public key stored in user prefs.";
return std::string();
}
return *public_key;
}
std::string CryptAuthV2EnrollmentManagerImpl::GetV1UserPrivateKey() const {
base::Optional<std::string> private_key = util::DecodeFromValueString(
pref_service_->Get(prefs::kCryptAuthEnrollmentUserPrivateKey));
if (!private_key) {
PA_LOG(ERROR) << "Invalid private key stored in user prefs.";
return std::string();
}
return *private_key;
}
void CryptAuthV2EnrollmentManagerImpl::AddV1UserKeyPairToRegistryIfNecessary() {
std::string public_key_v1 = GetV1UserPublicKey();
std::string private_key_v1 = GetV1UserPrivateKey();
const CryptAuthKey* key_v2 =
key_registry_->GetActiveKey(CryptAuthKeyBundle::Name::kUserKeyPair);
RecordUserKeyPairState(public_key_v1, private_key_v1, key_v2);
// If the v1 user key pair does not exist, no action is needed.
if (public_key_v1.empty() || private_key_v1.empty())
return;
// If the v1 and v2 user key pairs already agree, no action is needed.
if (key_v2 && key_v2->public_key() == public_key_v1 &&
key_v2->private_key() == private_key_v1) {
return;
}
key_registry_->AddKey(
CryptAuthKeyBundle::Name::kUserKeyPair,
CryptAuthKey(public_key_v1, private_key_v1, CryptAuthKey::Status::kActive,
cryptauthv2::KeyType::P256,
kCryptAuthFixedUserKeyPairHandle));
}
std::ostream& operator<<(std::ostream& stream,
const CryptAuthV2EnrollmentManagerImpl::State& state) {
switch (state) {
case CryptAuthV2EnrollmentManagerImpl::State::kIdle:
stream << "[EnrollmentManager state: Idle]";
break;
case CryptAuthV2EnrollmentManagerImpl::State::kWaitingForGcmRegistration:
stream << "[EnrollmentManager state: Waiting for GCM registration]";
break;
case CryptAuthV2EnrollmentManagerImpl::State::kWaitingForClientAppMetadata:
stream << "[EnrollmentManager state: Waiting for ClientAppMetadata]";
break;
case CryptAuthV2EnrollmentManagerImpl::State::kWaitingForEnrollment:
stream << "[EnrollmentManager state: Waiting for enrollment to finish]";
break;
}
return stream;
}
} // namespace device_sync
} // namespace chromeos
| [
"[email protected]"
]
| |
59375bfcec72501de892a745a71814dd7b35f9b7 | 955e610518a741a37a9db726942a48cb14523e6b | /C12/DXApp.h | 4fc4cc5be72ee5e7ed7b957bd88f48e525335e03 | []
| no_license | GuillaumeWerle/C12 | 253a6f8328527ba84164cf9bcb8e11e55966fbc6 | 431b028d3a2bb402b78f44ecb188b9597b729bf4 | refs/heads/master | 2021-01-18T11:57:16.137659 | 2017-10-12T18:15:10 | 2017-10-12T18:15:10 | 100,361,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,357 | h | #pragma once
#include "DXResourceContext.h"
#include "DXDescriptorHandle.h"
#include "DXSRV.h"
class DXRenderer;
class DXDescriptorHeap;
class DXDescriptorHeapLinear;
class DXDescriptorPool;
class DXFence;
class DXRenderer;
class DXTexture2D;
class Timer;
class DXRenderContext;
class MasterRenderThread;
class DXDepthStencil;
class DXApp
{
public:
static DXApp* ms_instance;
static const u32 k_RenderLatency = 2;
uint32_t m_width = 1920;
uint32_t m_height = 1080;
void Init(HWND hWnd);
void Update();
void Render();
DXApp();
~DXApp();
void ShutdownRendercontexts();
private:
//DXDescriptorHeap* m_swapChainBuffersDescriptorHeap = nullptr;
DXRTV m_swapChainRTVs[k_RenderLatency];
//DXResourceContext m_resourceContexts[k_RenderLatency];
DXResourceContext* m_rc;
DXRenderContext* m_renderContexts[k_RenderLatency];
u32 m_dxgiFactoryFlags;
ComPtr<IDXGIFactory4> m_dxgiFactory;
ComPtr<ID3D12Device> m_device;
DXDepthStencil* m_depthStencil = nullptr;
ComPtr<IDXGISwapChain3> m_swapChain;
ComPtr<ID3D12Resource> m_swapChainBuffers[k_RenderLatency];
ComPtr<ID3D12CommandQueue> m_commandQueue;
u32 m_frameIndex;
// Render
DXRenderer* m_renderer;
DXTexture2D* m_texture = nullptr;
Timer * m_timer = nullptr;
MasterRenderThread * m_masterRenderThread = nullptr;
void InitDebugLayer();
void InitSwapChain(HWND hWnd);
};
| [
"[email protected]"
]
| |
dddfcee4c22e8f77ba045be0c728b129635fc4a0 | 240de63555b826e5e43837bca0fad84aff40ab87 | /src/tiger/net.cpp | ceb49823d515a1442d39e1504a66af1d6eedaf8f | []
| no_license | zhangmengzxz/Tiger | b4b6995726eba5b0d80b46eca51af62d38a8b1b1 | 924885b4471fe27d74687eafe109df7d4613e938 | refs/heads/master | 2022-02-16T12:14:29.949411 | 2019-08-17T12:21:09 | 2019-08-17T12:21:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,601 | cpp | #include <algorithm>
#include "tiger/net.hpp"
#include "tiger/layer_factory.hpp"
namespace tiger{
static void show_map(std::map<std::string, int>& blob_name_to_idx){
std::vector<std::pair<std::string, int> > vec(blob_name_to_idx.begin(),
blob_name_to_idx.end());
std::sort(vec.begin(), vec.end(), [](std::pair<string, int>& lhs,
std::pair<string, int>& rhs){
return lhs.second < rhs.second;
});
for(auto item : vec){
LOG(INFO) << item.first << "\t" << item.second;
}
}
template <typename Dtype>
Net<Dtype>::Net(const NetParameter& param){
init(param);
}
template <typename Dtype>
void Net<Dtype>::init(const NetParameter& in_param){
NetParameter param = in_param;
phase_ = param.state().phase();
name_ = param.name();
memory_used_ = 0;
bottom_vecs_.resize(param.layer_size());
bottom_id_vecs_.resize(param.layer_size());
top_vecs_.resize(param.layer_size());
top_id_vecs_.resize(param.layer_size());
bottom_need_backward_.resize(param.layer_size());
std::set<std::string> available_blobs;
std::map<std::string, int> blob_name_to_idx;
for(int layer_id = 0; layer_id < param.layer_size(); ++layer_id){
if(!param.layer(layer_id).has_phase()){
param.mutable_layer(layer_id)->set_phase(phase_);
}
const LayerParameter layer_param = param.layer(layer_id);
layers_.push_back(LayerRegistry<Dtype>::create_layer(layer_param));
layer_names_.push_back(layer_param.name());
LOG(INFO) << "creating layer: " << layer_param.name();
// 需要添加层的bottom信息
for(int bottom_id = 0; bottom_id < layer_param.bottom_size(); ++bottom_id){
const int blob_id = append_bottom(param, layer_id, bottom_id,
&available_blobs, &blob_name_to_idx);
}
LOG(INFO) << "before append top blobs";
show_map(blob_name_to_idx);
int num_top = layer_param.top_size();
for(int top_id = 0; top_id < num_top; ++top_id){
append_top(param, layer_id, top_id, &available_blobs, &blob_name_to_idx);
}
layers_[layer_id]->setup(bottom_vecs_[layer_id], top_vecs_[layer_id]);
LOG(INFO) << "after append_top blobs ";
show_map(blob_name_to_idx);
}
LOG(INFO) << "show blob names: ";
for(auto item : blob_names_){
std::cout << item << " ";
}
std::cout << std::endl;
}
template <typename Dtype>
void Net<Dtype>::append_top(const NetParameter& param, const int layer_id,
const int top_id, std::set<string>* available_blobs,
std::map<string, int>* blob_name_to_idx){
std::shared_ptr<LayerParameter> layer_param(
new LayerParameter(param.layer(layer_id)));
// 一般数据输入层是有两个top
const std::string blob_name = (layer_param->top_size() > top_id) ?
layer_param->top(top_id) : "(automatic)";
if(blob_name_to_idx && layer_param->bottom_size() > top_id &&
blob_name == layer_param->bottom(top_id)){
LOG(INFO) << blob_name << "----->" << blob_name << " (in-place)";
// 如果是in-place计算,则不需要开辟新的内存空间了,否则
// 我们像下面一下还需要new一个Blob的内存空间
top_vecs_[layer_id].push_back(blobs_[(*blob_name_to_idx)[blob_name]].get());
top_id_vecs_[layer_id].push_back((*blob_name_to_idx)[blob_name]);
}
else if(blob_name_to_idx &&
blob_name_to_idx->find(blob_name) != blob_name_to_idx->end()){
LOG(FATAL) << blob_name << "produced by multiple sources";
}
else{
std::shared_ptr<Blob<Dtype> > blob_pointer(new Blob<Dtype>());
const int blob_id = blobs_.size();
blobs_.push_back(blob_pointer);
blob_names_.push_back(blob_name);
blob_need_backward_.push_back(false);
if(blob_name_to_idx){
(*blob_name_to_idx)[blob_name] = blob_id;
}
top_id_vecs_[layer_id].push_back(blob_id);
top_vecs_[layer_id].push_back(blob_pointer.get());
}
if(available_blobs){
available_blobs->insert(blob_name);
}
}
template <typename Dtype>
int Net<Dtype>::append_bottom(const NetParameter& param, const int layer_id,
const int bottom_id, std::set<string>* available_blobs,
std::map<string, int>* blob_name_to_idx){
std::shared_ptr<LayerParameter> layer_param(
new LayerParameter(param.layer(layer_id)));
const std::string blob_name = layer_param->bottom(bottom_id);
if(blob_name_to_idx->find(blob_name) == blob_name_to_idx->end()){
LOG(FATAL) << "unknown bottom blob: " << blob_name << " ( layer name is "
<< layer_param->name() << " )";
}
const int blob_id = (*blob_name_to_idx)[blob_name];
bottom_vecs_[layer_id].push_back(blobs_[blob_id].get());
bottom_id_vecs_[layer_id].push_back(blob_id);
bool need_backward = blob_need_backward_[blob_id];
return blob_id;
}
template <typename Dtype>
void Net<Dtype>::append_param(const NetParameter& param, const int layer_id,
const int param_id){
}
template <typename Dtype>
Dtype Net<Dtype>::forward_from_to(int start, int end){
CHECK_GE(start, 0);
CHECK_LT(end, this->layers_.size());
Dtype loss = 0;
for(int i = start; i <= end; ++i){
Dtype layer_loss = layers_[i]->forward(bottom_vecs_[i], top_vecs_[i]);
// 尽管每一层都有计算loss,但是一般如果不是最后层是不去真正计算loss的。
loss += layer_loss;
}
return loss;
}
template <typename Dtype>
void Net<Dtype>::backward_from_to(int start, int end){
CHECK_GE(end, 0);
CHECK_LT(start, this->layers_.size());
for(int i = start; i >= end; --i){
if(this->layer_need_backward_[i]){
layers_[i]->backward(top_vecs_[i], bottom_need_backward_[i],
bottom_vecs_[i]);
}
}
}
template class Net<float>;
template class Net<double>;
}
| [
"[email protected]"
]
| |
7b587a410b79114d6e7fa479f3523893284ce4bc | 26ad4cc35496d364b31396e43a863aee08ef2636 | /SDK/SoT_capstan_underwater_01_CustomizationDesc_functions.cpp | be4b757f35ea3b18a32dc44e0ad465eb50f6c91c | []
| no_license | cw100/SoT-SDK | ddb9b19ce6ae623299b2b02dee51c29581537ba1 | 3e6f12384c8e21ed83ef56f00030ca0506d297fb | refs/heads/master | 2020-05-05T12:09:55.938323 | 2019-03-20T14:11:57 | 2019-03-20T14:11:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | cpp | // Sea of Thieves (1.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_capstan_underwater_01_CustomizationDesc_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
]
| |
61cf210b901d2d35b7f62a5cba7ef26a9fff06ff | 5456502f97627278cbd6e16d002d50f1de3da7bb | /device/bluetooth/dbus/fake_bluetooth_gatt_application_service_provider.h | 98da11d9550e2f1797d7e4d8566bcfb57c7f19ff | [
"BSD-3-Clause"
]
| permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,957 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_BLUETOOTH_DBUS_FAKE_BLUETOOTH_GATT_APPLICATION_SERVICE_PROVIDER_H_
#define DEVICE_BLUETOOTH_DBUS_FAKE_BLUETOOTH_GATT_APPLICATION_SERVICE_PROVIDER_H_
#include <map>
#include <vector>
#include "base/macros.h"
#include "dbus/object_path.h"
#include "device/bluetooth/bluetooth_export.h"
#include "device/bluetooth/bluez/bluetooth_local_gatt_service_bluez.h"
#include "device/bluetooth/dbus/bluetooth_gatt_application_service_provider.h"
#include "device/bluetooth/dbus/bluetooth_gatt_characteristic_service_provider.h"
#include "device/bluetooth/dbus/bluetooth_gatt_descriptor_service_provider.h"
#include "device/bluetooth/dbus/bluetooth_gatt_service_service_provider.h"
namespace bluez {
class BluetoothLocalGattCharacteristicBlueZ;
class BluetoothLocalGattDescriptorBlueZ;
class BluetoothLocalGattServiceBlueZ;
// FakeBluetoothGattApplicationServiceProvider simulates behavior of a local
// GATT service object and is used both in test cases in place of a mock and on
// the Linux desktop.
class DEVICE_BLUETOOTH_EXPORT FakeBluetoothGattApplicationServiceProvider
: public BluetoothGattApplicationServiceProvider {
public:
FakeBluetoothGattApplicationServiceProvider(
const dbus::ObjectPath& object_path,
const std::map<dbus::ObjectPath, BluetoothLocalGattServiceBlueZ*>&
services);
~FakeBluetoothGattApplicationServiceProvider() override;
const dbus::ObjectPath& object_path() const { return object_path_; }
private:
// D-Bus object path of the fake GATT service.
dbus::ObjectPath object_path_;
DISALLOW_COPY_AND_ASSIGN(FakeBluetoothGattApplicationServiceProvider);
};
} // namespace bluez
#endif // DEVICE_BLUETOOTH_DBUS_FAKE_BLUETOOTH_GATT_APPLICATION_SERVICE_PROVIDER_H_
| [
"[email protected]"
]
| |
1008de4186891b77442901ca157a0f8fa81c7ac3 | 402128d394151f038888d198f17bb93c09dd0d7d | /Source/GAS/Private/GAS_DebugMenu_ItemWidget.cpp | 8d9972e706f9851e12f95766f631725c340010eb | []
| no_license | fogeZombie/GAS | 24a0e5fe4963e5aaa999b6f7b77c740e72a775e9 | 9e4db66263e5a129b630654281af386137774c4a | refs/heads/master | 2020-06-23T20:43:47.118754 | 2019-08-04T12:02:35 | 2019-08-04T12:02:35 | 198,746,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,551 | cpp | // Copyright BroachForge 2019
#include "GAS_DebugMenu_ItemWidget.h"
#include "Engine/Console.h"
int UGAS_DebugMenu_ItemWidget::GetDebugMenuVariableValue_Bool()
{
IConsoleVariable* Variable = IConsoleManager::Get().FindConsoleVariable(*DMIW_Data.CommandString);
if (Variable && !Variable->TestFlags(ECVF_Unregistered))
{
return Variable->GetInt();
}
UE_LOG(LogTemp, Error, TEXT("UGAS_DebugMenu_ItemWidget::GetDebugMenuVariableValue_Bool failed to find the specified variable: %s"), *DMIW_Data.CommandString);
return -1;
}
void UGAS_DebugMenu_ItemWidget::ExecuteDebugMenuCommand()
{
if (DMIW_Data.CommandType == EDebugMenuItemCommandType::DMIC_Exec)
{
//UE_LOG(LogTemp, Warning, TEXT("Exec type: %s"), *DMIW_Data.CommandString);
GetOwningPlayer()->ConsoleCommand(*DMIW_Data.CommandString);
}
else if (DMIW_Data.CommandType == EDebugMenuItemCommandType::DMIC_Bool)
{
//UE_LOG(LogTemp, Warning, TEXT("Bool type."));
IConsoleVariable* Variable = IConsoleManager::Get().FindConsoleVariable(*DMIW_Data.CommandString);
if (Variable && !Variable->TestFlags(ECVF_Unregistered))
{
int32 value = Variable->GetInt();
switch (value)
{
case 0: value = 1; break;
case 1: value = 0; break;
default: value = 0; break; // handles case of flag values leaving the 'unassigned' state
}
Variable->Set(value, ECVF_SetByConsole);
}
}
else if (DMIW_Data.CommandType == EDebugMenuItemCommandType::DMIC_Int)
{
//UE_LOG(LogTemp, Warning, TEXT("Int type."));
IConsoleVariable* Variable = IConsoleManager::Get().FindConsoleVariable(*DMIW_Data.CommandString);
if (Variable && !Variable->TestFlags(ECVF_Unregistered))
{
int32 value = Variable->GetInt();
// pull new value from DMIW_Data
// Need a setup for defining min/max
// value = FMath::Clamp(value, Binding.Int.Min, Binding.Int.Max);
UE_LOG(LogTemp, Warning, TEXT("%s = %d"), *DMIW_Data.CommandString, value);
Variable->Set(value, ECVF_SetByConsole);
}
}
else if (DMIW_Data.CommandType == EDebugMenuItemCommandType::DMIC_Float)
{
//UE_LOG(LogTemp, Warning, TEXT("Float type."));
IConsoleVariable* Variable = IConsoleManager::Get().FindConsoleVariable(*DMIW_Data.CommandString);
if (Variable && !Variable->TestFlags(ECVF_Unregistered))
{
float value = Variable->GetFloat();
// pull new value from DMIW_Data
// value = FMath::Clamp(value, Binding.Float.Min, Binding.Float.Max);
UE_LOG(LogTemp, Warning, TEXT("%s = %f"), *DMIW_Data.CommandString, value);
Variable->Set(value, ECVF_SetByConsole);
}
}
}
| [
"[email protected]"
]
| |
ae6da62b42cf563f9ca1b297ee94e79b84f320fc | 9ba33709768397096fe7ccf8da7aa90feec66cc6 | /lengthSum.cpp | 701ff3b152721279852b267bf80b38bcc565f1cb | []
| no_license | subhankar-ghosh/CCPractice | b9d549dad48ba608bc63a3e29d649b02d38be633 | 7377e91154a22275f0a7f20c2d0595af3873f4e5 | refs/heads/master | 2021-01-01T19:48:29.454787 | 2017-09-09T08:08:42 | 2017-09-09T08:08:42 | 98,691,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int m, s;
cin>>m>>s;
if(s==0 && m==1) {
cout<<"0 0";
return 0;
}
if(9*m<s || s==0) {
cout<<"-1 -1";
return 0;
}
string mn(m, '0');
string mx(m, '0');
int k=s;
int j=m-1;
while(j>=0) {
mn[j]=k>9?9+'0':k+'0';
k-=9;
k=max(k,0);
j--;
}
//cout<<mn<<endl;
if(mn[0]=='0') {
mn[0]=1+'0';
j=1;
while(mn[j]=='0') j++;
//cout<<j<<endl;
mn[j]=mn[j]-1;
}
cout<<mn<<" ";
k=s,j=0;
while(j<m) {
mx[j]=(k>9)?9+'0':k+'0';
k=max(k-9,0);
j++;
}
cout<<mx<<endl;
return 0;
}
| [
"[email protected]"
]
| |
dac2949c0c073362f7fb183f4a1eedbafe842ead | fe82c71f2fd798a52d5668460eef34bf1b47468b | /ecs_sgav/src/main.cpp | e32e8bc01ba055d14a7be5ebfc475ad8053554a5 | [
"MIT"
]
| permissive | sgavil/ECS | b6eb76886028b6ff3ede7a5445b2eedb36b67dca | 7aef63138fe4bb5e0b48733cd1a6ec9b7e9efb46 | refs/heads/master | 2023-02-07T18:28:19.117131 | 2021-01-02T20:07:17 | 2021-01-02T20:07:17 | 324,826,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | #include <iostream>
#include "registry.hpp"
int main()
{
ecg::registry reg;
auto entt = reg.create_entity();
auto entt1 = reg.create_entity();
auto entt2 = reg.create_entity();
reg.erase_entity(entt1);
std::cout << entt << entt1 << entt2 << '\n';
return 0;
}
| [
"[email protected]"
]
| |
c9a0c1e9c2d8a10cd84eb67cafdf56aeaf77c3e5 | af204c83fe7f942a7b028f39ee054bc3b8df737b | /HomeworksCG/Task3.h | 6d1fd47f1fcbc3d16e59c252e6d5128402aa34b4 | []
| no_license | Radostinaa/HomeworksCG | f85e6ac953435d0f6e71a450c781c9e6d83a31eb | 666904dbf68bd491cee1f524875ec94ff78a1fcc | refs/heads/master | 2021-01-11T20:31:18.382412 | 2017-01-19T21:40:39 | 2017-01-19T21:40:39 | 79,132,764 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 769 | h | #pragma once
#include "Task.h"
#include <SDL.h>
struct Pixel
{
int x, y;
SDL_Color color;
Pixel(int _x = -1, int _y = -1, SDL_Color _color = {0,0,0,0})
: x(_x), y(_y), color(_color) {}
};
class Task3 : public Task
{
public:
Task3(SDL_Renderer* r, int _w, int _h) : Task(r, 5)
{
pointsNeeded = 2;//first side
w = _w;
h = _h;
filledPixels = new Pixel[w*h];
pixelsCount = 0;
colorSides = { 255,0,0,1 };
colorFill = { 255,165,0,1 };
edges = 0;
clear = true;
}
~Task3();
void Draw();
private:
SDL_Color colorSides;
SDL_Color colorFill;
int edges;
Pixel* filledPixels;
int pixelsCount;
int w, h;
bool clear;
bool freePixel(Point p);
void BoundryFill(Point begin);
void drawside();
void BresenhamLine(Point from, Point to);
};
| [
"[email protected]"
]
| |
827bef382d24243df2fc3b6135b2e209754808a0 | 3b94872795555b631eedf5ca548ad18cd1f31f29 | /automatedtesting/can-simulator-ng/lib/cansimulatorcore.h | 86602282bd70d7d75f4db643b69dc15082b5a4e4 | []
| no_license | hanwei7788/LM-auto | 715950644489c4db8bb3a3c48e95f023213cf2dc | cb3ac067efe9588a0a2debf98ab564d5053e6bd8 | refs/heads/master | 2020-03-27T09:47:17.059040 | 2018-09-26T02:18:30 | 2018-09-26T02:18:30 | 146,372,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,207 | h | /*!
* \file
* \brief cansimulatorcore.h foo
*
* Copyright of Link Motion Ltd. All rights reserved.
*
* Contact: [email protected]
*
* \author Matti Lehtimäki <[email protected]>
*
* any other legal text to be defined later
*/
#ifndef CANSIMULATORCORE_H
#define CANSIMULATORCORE_H
#include "ascreader.h"
#include "cantransceiver.h"
#include "configuration.h"
#include "queue.h"
#include "value.h"
#include <cstdint>
#include <exception>
#include <map>
#include <memory>
#include <string>
#include <thread>
#include <vector>
struct errorMetrics {
std::uint64_t errorMessages; // Total number of error messages
std::uint64_t unknownMessages; // Total number of unknown messages
std::uint64_t errorSize; // Total size of all error messages
std::uint64_t unknownSize; // Total size of all unknown messages
};
class CANSimulatorCoreException : public std::exception
{
public:
virtual const char *what() const throw();
};
class CANSimulatorCore
{
public:
explicit CANSimulatorCore(const std::string &cfg, const std::string &dbc, const std::string &asc,
const std::string &socketName, bool suppressDefaults=false, bool ignoreDirections=false,
unsigned int interval=10, int runTime=-1);
~CANSimulatorCore();
bool loadConfiguration(const std::string &cfg, const std::string &dbc, bool suppressDefaults, bool ignoreDirections);
std::string getCfgVersion() const;
std::string getDBCVersion() const;
static bool getUseNativeUnits();
static void setUseNativeUnits(bool enable);
bool getSendTime() const;
void setSendTime(bool enable);
bool getUseUTCTime() const;
void setUseUTCTime(bool enable);
// Data simulator
void startDataSimulator();
void stopDataSimulator();
bool isDataSimulatorRunning() const;
int getRunTime() const;
int getRunTimeRemaining() const;
void setRunTime(int runTime);
// Manual control
bool setValue(std::string key, Value value);
bool setValue(std::string key, std::string value);
bool setValues(std::vector<std::string> &input);
void setDefaultValues(bool sendMessages = false);
const CANSignal *getSignal(const std::string &key);
const CANMessage *getMessage(const std::string &key);
const CANMessage *getMessage(std::uint32_t id);
const std::map<std::uint32_t, CANMessage> &getMessages() const;
const std::set<std::string> &getVariables() const;
bool sendCANMessage(std::uint32_t id, bool forceSend = false);
bool sendCANMessage(const std::string &key, bool forceSend = false);
bool sendCANMessages(bool sendAll = false);
void startCANReaderThread();
void startCANSenderThread();
void stopCANThreads();
int getCANBitrate();
Queue<std::shared_ptr<CANMessage>> *getMessageQueue();
std::map<std::uint64_t, canFrameQueueItem> *getFrameQueue();
bool setMessageFilterState(std::uint32_t id, bool filterState);
bool isMessageFiltered(std::uint32_t id);
bool initializeMessageFilterList(std::vector<std::string> *ids, bool filterState, bool reset = false);
struct errorMetrics getErrorMetrics() const;
private:
int m_interval;
int m_runTime;
bool m_sendTime;
bool m_useUTCTime;
bool m_threadsRunning;
static bool m_useNativeUnits;
Configuration *m_config;
Queue<std::shared_ptr<CANMessage>> m_messageQueue;
std::thread m_senderThread;
std::thread m_readerThread;
std::mutex m_inputMutex;
std::map<std::uint32_t, bool> m_filterList;
struct errorMetrics m_errorMetrics;
ASCReader *m_ascReader;
CANTransceiver *m_canTransceiver;
bool m_simulationRunning;
uint64_t m_simulationTime;
// Do not copy CANSimulatorCore
CANSimulatorCore(const CANSimulatorCore&) { }
void CANReaderThread();
void CANSenderThread();
std::uint32_t readCANMessage();
void updateTime(std::chrono::time_point<std::chrono::system_clock> &timeSendCounter,
std::chrono::time_point<std::chrono::system_clock> &now,
std::chrono::duration<int,std::milli> &timeSendInterval);
};
#endif // CANSIMULATORCORE_H
| [
"[email protected]"
]
| |
4b7cd3c367be92dea6774f566812a06b4068e6f3 | 05dfd955d19004e931c25eb6a9c755916c3908ce | /Arduino/SparkFun_ADXL345_Single_Output/SparkFun_ADXL345_Single_Output.ino | f1adff01c181821acbc446789297aa894c12d4d0 | []
| no_license | evilda/Recognition-of-pHRI-by-Vibration-Analysis | 6c3eb3777587fa9e01df8f2d4925ea6d580af8ee | c1b1037e95b309daa16142b7a69bde2d60c2dcb0 | refs/heads/master | 2020-04-04T21:09:42.813433 | 2019-01-24T13:02:30 | 2019-01-24T13:02:30 | 156,276,090 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,800 | ino | #include <SparkFun_ADXL345.h> // SparkFun ADXL345 Library
/*********** COMMUNICATION SELECTION ***********/
/* Comment Out The One You Are Not Using */
//ADXL345 adxl = ADXL345(10); // USE FOR SPI COMMUNICATION, ADXL345(CS_PIN);
ADXL345 adxl = ADXL345(); // USE FOR I2C COMMUNICATION
/****************** INTERRUPT ******************/
/* Uncomment If Attaching Interrupt */
//int interruptPin = 2; // Setup pin 2 to be the interrupt pin (for most Arduino Boards)
double mal = 0.25;
/******************** SETUP ********************/
/* Configure ADXL345 Settings */
void setup(){
Serial.begin(9600); // Start the serial terminal
adxl.powerOn(); // Power on the ADXL345
adxl.setRangeSetting(2); // Give the range settings
// Accepted values are 2g, 4g, 8g or 16g
// Higher Values = Wider Measurement Range
// Lower Values = Greater Sensitivity
int x,y,z;
for(int var = 0;var <150;var++)
{
adxl.readAccel(&x, &y, &z);
if(var >100)
{
if(abs(x)>480||abs(y)>480||abs(z)>480)
{
adxl.setRangeSetting(4);
// mal = 0.125;
break;
}
}
}
}
/****************** MAIN CODE ******************/
/* Accelerometer Readings and Interrupt */
void loop(){
// Accelerometer Readings
int x,y,z;
adxl.readAccel(&x, &y, &z); // Read the accelerometer values and store them in variables declared above x,y,z
x= x*mal;
y= y*mal;
z=z*mal;
Serial.write(x);
// Serial.print(", ");
Serial.write(y);
// Serial.print(", ");
Serial.write(z);
// Serial.println();
}
| [
"[email protected]"
]
| |
c20852662d8e8c05ab84579cd8eed85a904817d1 | 618c02b1b10fce11f53a976a4ed40fd2b700ebf6 | /SlideGame/Classes/Utility/SceneManager.cpp | f67ec151d7e285070a71de52a7f0f19b8f66e4f0 | []
| no_license | yamashita8655/CocosSample | 263ae80eff82180f7ddb8f570da2c7c2809047d4 | 3e5b69626f289917b26fa6b03a93f7c80aae5330 | refs/heads/master | 2021-01-19T20:26:38.673842 | 2015-12-05T05:16:21 | 2015-12-05T05:16:21 | 34,890,811 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,189 | cpp | // ============================================================
//! @file SceneManager.cpp
//! @brief シーンの管理
//! @note
//! @attention
//! @warning
// ============================================================
#include "SceneManager.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "../GameScene.h"
#include "../CharacterSelectScene.h"
#include "../StageSelectScene.h"
USING_NS_CC;
using namespace cocostudio::timeline;
// ============================================================
//! @brief インスタンス取得関数
//! @note
//! @return シーンマネージャインスタンス
//! @retval instance
// ============================================================
SceneManager &SceneManager::getInstance() {
static SceneManager instance;
return instance;
}
// ============================================================
//! @brief 初期化
//! @note
//! @return
// ============================================================
void SceneManager::init()
{
mNowScene = nullptr;
for(int i = 0; i < (int)ZORDER::MAX; i++)
{
auto stack = new std::stack<cocos2d::Layer*>();
mLayerStack.push_back(stack);
}
}
void SceneManager::runScene(SCENE_NAME name)
{
// 仮 あとで、Sceneを継承か内包して、SCENE_NAME毎の差別化されたクラスインスタンスに変更する
mNowScene = Scene::create();
Director::getInstance()->runWithScene(mNowScene);
}
void SceneManager::replaceScene(SCENE_NAME name)
{
// 仮 あとで、Sceneを継承か内包して、SCENE_NAME毎の差別化されたクラスインスタンスに変更する
mNowScene = Scene::create();
Director::getInstance()->replaceScene(mNowScene);
}
void SceneManager::pushLayer(std::string name, int zOrder)
{
cocos2d::Node* ret = mNowScene->getChildByName(name);
if (ret != nullptr)
{
return;
}
cocos2d::Layer* layer = nullptr;
if(name == LAYER_NAME_GAME)
{
layer = GameScene::create();
}
else if (name == LAYER_NAME_STAGE_SELECT)
{
layer = StageSelectScene::create();
}
else if (name == LAYER_NAME_CHARACTER_SELECT)
{
layer = CharacterSelectScene::create();
}
mNowScene->addChild(layer, zOrder, name);
mLayerStack.at(zOrder)->push(layer);
}
void SceneManager::popLayer(std::string name)
{
mNowScene->removeChildByName(name);
for(int i = 0; i < (int)ZORDER::MAX; i++)
{
auto stack = mLayerStack.at(i);
if (stack->empty() != true)
{
auto layer = stack->top();
if (layer->getName() == name)
{
stack->pop();
break;
}
}
}
}
void SceneManager::popLayer()
{
cocos2d::Layer* layer = nullptr;
for (int i = 0; i < (int)ZORDER::MAX; i++)
{
auto stack = mLayerStack.at(i);
if (stack->empty() != true)
{
layer = stack->top();
stack->pop();
break;
}
}
if (layer != nullptr)
{
mNowScene->removeChild(layer);
}
}
void SceneManager::popLayer(int zOrder)
{
cocos2d::Layer* layer = nullptr;
auto stack = mLayerStack.at(zOrder);
if (stack->empty() != true)
{
layer = stack->top();
stack->pop();
}
if (layer != nullptr)
{
mNowScene->removeChild(layer);
}
}
cocos2d::Scene* SceneManager::getNowScene()
{
return mNowScene;
}
| [
"[email protected]"
]
| |
d29257a351e21480542a11b20ef42d7422f0620c | a0f2e39645ea284939b5d5b8acf70e879300b277 | /sketches/a_haos_infrared_linetracer/haos_smartcar_linetracer.cpp | c570e71342e1a952a52e67f6589ad36387a55502 | []
| no_license | EntropyHaos/codebender_cleanup | 3bf515035129ddc27dd674978361a9c295655f5b | 11b5002b0d72a583af8077a1e1dac91ae7c92617 | refs/heads/master | 2021-06-16T06:53:12.818086 | 2017-04-09T16:28:30 | 2017-04-09T16:28:30 | 87,721,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,716 | cpp | #include "Arduino.h"
#include "haos_smartcar_movement.h"
#include "haos_smartcar_infrared.h"
int main_loop_delay = 5; // = ms between chechs in the IR.
boolean move_wheels_for_reals = false;
boolean line_tracing;
boolean smartcar_is_still_learning_and_has_lost_his_way;
void move_car_for_line_tracing(int left_speed, int right_speed)
{
if (move_wheels_for_reals)
{
Serial.println("" + String(left_speed) + "/"+ "" + String(right_speed) + "");
move_car_analogue(left_speed, right_speed);
}
else
{
// Fake it. See notes on various ways to simulate all types of robotics.
//Serial.println("LT : " + String(left_speed) + " RT : " + String(right_speed) + "");
Serial.println("" + String(left_speed) + "/"+ "" + String(right_speed) + "");
}
}
void turn_on_some_line_tracing_please()
{
line_tracing = true;
//smartcar_is_still_learning_and_has_lost_his_way = false;
}
void turn_off_line_tracer()
{
line_tracing = false;
//smartcar_is_dumb_and_lost_his_way = false;
}
void line_trace_loop()
{
if (line_tracing == true)
{
unsigned char sensor_data = 0;
int the_readings[8]={0, 0, 0, 0, 0, 0, 0, 0};
infrared_sensor_read(the_readings);
for(int z = 0; z < 8; z++)
{
unsigned int val = the_readings[z];
sensor_data |= (val << z);
}
/*
for(int z = 0; z < 8; z++)
{
unsigned int val = digitalRead(SensorD[z]);
sensor_data |= (val << z);
}
*/
sensor_data = ~sensor_data;
//Serial.print(sensor_data, HEX);
//Serial.write(" ");
switch (sensor_data)
{
//our move forward situations.
case 0x18:
case 0x10:
case 0x08:
case 0x38:
case 0x1c:
case 0x3c:
move_car_for_line_tracing(150,150);
//status = "moving Forward";
break;
//our turn right situations.
case 0x0c:
case 0x04:
case 0x06:
case 0x0e:
case 0x1e:
case 0x0f:
move_car_for_line_tracing(75, 150);
//new_text_to_send = "Turn Right";
break;
//our turn left situations.
case 0x30:
case 0x20:
case 0x60:
case 0x70:
case 0x78:
case 0xf0:
//turn_left_speed(30, 75);
move_car_for_line_tracing(150, 75);
//new_text_to_send = "Turn Left";
break;
//our spin right situations.
case 0x07:
case 0x03:
case 0x02:
case 0x01:
move_car_for_line_tracing(-150, 150);
//new_text_to_send = "Pivot Right";
break;
//our spin left situations.
case 0xc0:
case 0x40:
case 0x80:
case 0xe0:
move_car_for_line_tracing(150, -150);
//new_text_to_send = "Pivot Left";
break;
case 0x00:
case 0xff:
//new_text_to_send = "No line to follow";
move_car_for_line_tracing(0, 0);
break;
default:
//new_text_to_send = "Hit Default";
move_car_for_line_tracing(0, 0);
break;
}
delay(main_loop_delay);
}
/*
if (new_text_to_send != stored_text_to_send)
{
stored_text_to_send = new_text_to_send;
Serial.print(stored_text_to_send);
}
*/
}
| [
"[email protected]"
]
| |
39c47e72d1de97438e62c4257b4623b20a56cf3f | 7820d7cb4fc1f277928924c5552ce7b256bde2aa | /暑假集训8/Estd.cpp | 6b3219e699de1fe5bfa54d793d470916c24b3c70 | []
| no_license | AllenOris/ACM-Solution | 49c7013bba818652360896217c6c6d8d3f899f43 | 41b7ab5489b966e69fff83c823c912cfd3d6a30a | refs/heads/master | 2020-03-23T11:41:42.701908 | 2018-08-21T13:34:45 | 2018-08-21T13:34:45 | 141,516,498 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | cpp | #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <cstdio>
using namespace std;
#define rep(i,a,b) for(__typeof(b) i=a; i<(b); ++i)
typedef pair<int, int> pii;
int main()
{
int n, k;
scanf("%d %d", &n, &k);
vector<pii> intervals(n);
rep(i,0,n)
scanf("%d %d", &intervals[i].second, &intervals[i].first);
sort(intervals.begin(), intervals.end());
multiset<int, greater<int> > ends;
rep(i,0,k) ends.insert(0);
int res = 0;
for (pii &o : intervals)
{
auto it = ends.lower_bound(o.second);
if (it != ends.end())
{
ends.erase(it);
ends.insert(o.first);
res++;
}
}
cout << res << endl;
} | [
"[email protected]"
]
| |
aebda815efb688158f212344a7cf181f0cd7aec8 | 93d39ed4ac9dcd1e060d7284b3485857a177f80a | /c++begins/ch_nested_class.cpp | 87483c580c70cf8d4c7362921e6d54e9df88b610 | []
| no_license | rajat1293/ALL_PROGRAMS | fa11202f761fd6bc23b70132d9f4714e6a1e68ff | bce0d2338770688341dd24ec7c1b9f848f7b5cb8 | refs/heads/master | 2021-03-12T23:03:49.125602 | 2014-02-10T17:45:14 | 2014-02-10T17:45:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | #include<iostream>
using namespace std;
#include<stdlib.h>
#define size 5
class mahastack
{
class stack
{
public:
int arr[size],top,roll;
public:
stack()
{top=-1;
}
void push(int element)
{
if(top==size-1)
cout<<"stack full\n";//here 5 is added in stack
else
arr[++top]=element;
}
void display()
{
cout<<endl<<arr[0];
}
};
stack a;
public:
void ds()
{
a.push(5);
a.display();
}
};
main()
{
mahastack s;
s.ds();
}
| [
"[email protected]"
]
| |
62afecc28145d8fa8dc99e70f21c08f2b54c4c71 | 440001e2363180d1c7fd7f74b3459fa8e07111bc | /src/cpp/runner/HandBenchmark.cpp | 96261362caf395d4718cb918cb4add244abc7ebe | []
| no_license | novikov-alexander-zz/ADBench | 1ba31fba8855b911d933e47ecb54ffa6b3d63f44 | 500d213ed3877ad2f29ab4c32d94cdce29c33904 | refs/heads/master | 2022-01-28T18:10:20.078138 | 2019-07-22T11:33:58 | 2019-07-31T06:55:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | cpp | #include "HandBenchmark.h"
template <>
HandInput read_input_data<HandInput, HandParameters>(const std::string& input_file, const HandParameters& params)
{
HandInput input;
const auto model_dir = filepath_to_dirname(input_file) + "model\\";
// Read instance
if (params.is_complicated) {
read_hand_instance(model_dir, input_file, &input.theta, &input.data, &input.us);
}
else {
read_hand_instance(model_dir, input_file, &input.theta, &input.data);
}
return input;
}
template <>
unique_ptr<ITest<HandInput, HandOutput>> get_test<HandInput, HandOutput>(const ModuleLoader& module_loader)
{
return module_loader.get_hand_test();
}
template <>
void save_output_to_file<HandOutput>(const HandOutput& output, const string& output_prefix,
const string& input_basename, const string& module_basename)
{
save_vector_to_file(objective_file_name(output_prefix, input_basename, module_basename), output.objective);
save_jacobian_to_file(jacobian_file_name(output_prefix, input_basename, module_basename), output.jacobian_ncols, output.jacobian_nrows, output.jacobian);
}
| [
"[email protected]"
]
| |
fe24efc6de6bc8a83ecbefc5cb19d60c18636833 | fd4dcb01cdbb1d8663264551586fd21eb36e2626 | /PSO/mainwindow.h | b430af00d461d85a347c604df839f65ad861495d | []
| no_license | ardfard/AI_Tinkering | ee51dfa476ce7cf3c3abdfbbef3e2c5781fa98b3 | 777c4dc00332e4aa9085fb56f7971b6c6388d42a | refs/heads/master | 2020-04-05T23:41:05.917094 | 2014-01-18T11:55:19 | 2014-01-18T11:55:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 819 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <vector>
class GraphicsScene;
class Particle;
class QGraphicsEllipseItem;
class QGraphicsSimpleTextItem;
class GraphicsEdge;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
GraphicsScene *graphicsScene;
private slots:
void on_actionRunSimulation_triggered();
void on_actionPointer_triggered();
void on_actionInsertVertex_triggered();
void on_actionInsertEdge_triggered();
void addVertex(QGraphicsEllipseItem*);
void addEdge(GraphicsEdge* edge);
private:
QGraphicsSimpleTextItem* bestCostText;
QList<GraphicsEdge*> edges_;
};
#endif // MAINWINDOW_H
| [
"[email protected]"
]
| |
82188d994ec7c44a6fa7e2ae71a5c6ddb92f3027 | 4d32e11fd6a5891adb9f48d6de4ae97e5c78f2f0 | /proj-rt-files/dump_png.cpp | ae6e4e8752fe7a40e94637bd59bf2dbc7a18620f | []
| no_license | mjime051/CS_130_Graphics | ef763e5b2ead2e5f4219366d0f05406b7b9aef2f | acc07cef037101c3eb12983a39cfc11891f35523 | refs/heads/main | 2023-04-15T13:40:42.397590 | 2021-04-21T08:21:31 | 2021-04-21T08:21:31 | 359,947,279 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,108 | cpp | #include <png.h>
#include <cassert>
typedef unsigned int Pixel;
void Dump_png(Pixel* data,int width,int height,const char* filename)
{
FILE* file=fopen(filename,"wb");
assert(file);
png_structp png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING,0,0,0);
assert(png_ptr);
png_infop info_ptr=png_create_info_struct(png_ptr);
assert(info_ptr);
bool result=setjmp(png_jmpbuf(png_ptr));
assert(!result);
png_init_io(png_ptr,file);
int color_type=PNG_COLOR_TYPE_RGBA;
png_set_IHDR(png_ptr,info_ptr,width,height,8,color_type,PNG_INTERLACE_NONE,PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT);
Pixel** row_pointers=new Pixel*[height];
for(int j=0;j<height;j++) row_pointers[j]=data+width*(height-j-1);
png_set_rows(png_ptr,info_ptr,(png_byte**)row_pointers);
png_write_png(png_ptr,info_ptr,PNG_TRANSFORM_BGR|PNG_TRANSFORM_SWAP_ALPHA,0);
delete[] row_pointers;
png_destroy_write_struct(&png_ptr,&info_ptr);
fclose(file);
}
void Read_png(Pixel*& data,int& width,int& height,const char* filename)
{
FILE *file = fopen(filename, "rb");
assert(file);
unsigned char header[8];
int num_read=fread(&header, 1, sizeof header, file);
assert(num_read==sizeof header);
int ret_sig=png_sig_cmp((png_bytep)header, 0, sizeof header);
assert(!ret_sig);
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
assert(png_ptr);
png_infop info_ptr = png_create_info_struct(png_ptr);
assert(info_ptr);
png_infop end_info = png_create_info_struct(png_ptr);
assert(end_info);
png_init_io(png_ptr, file);
png_set_sig_bytes(png_ptr, sizeof header);
png_read_info(png_ptr, info_ptr);
int color_type = png_get_color_type(png_ptr, info_ptr);
int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
if(color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_expand_gray_1_2_4_to_8(png_ptr);
if(png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png_ptr);
if(bit_depth == 16)
png_set_strip_16(png_ptr);
if(bit_depth < 8)
png_set_packing(png_ptr);
if(color_type == PNG_COLOR_TYPE_GRAY_ALPHA || color_type == PNG_COLOR_TYPE_RGB_ALPHA)
png_set_swap_alpha(png_ptr);
if(color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
if(color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA)
png_set_bgr(png_ptr);
if(color_type == PNG_COLOR_TYPE_RGB)
png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
height = png_get_image_height(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
data = new Pixel[width * height];
png_read_update_info(png_ptr, info_ptr);
for(int i = 0; i < height; i++)
png_read_row(png_ptr, (png_bytep)(data + (height-i-1) * width), 0);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(file);
}
| [
"[email protected]"
]
| |
9afb750c63ca3cc4ea4b8a234ee652e4ee0862b4 | 61d5bd9f11c5b0c2cf61ada6831571843d6c78a4 | /alscloud.h | 9bb78c40e518d9785ba53f949aaa54499667f4a7 | []
| no_license | dreamfulMoonlight/Alscollation | 79be5c69a1fca5a156cc94ef225cb2cadb3418fe | 7aa1a4dd474f286e82d0de6c601e48dd1c8b6689 | refs/heads/main | 2023-03-10T03:51:49.203699 | 2021-02-26T05:58:44 | 2021-02-26T05:58:44 | 342,475,687 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,611 | h | #pragma once
#include <pcl/io/io.h>
#include<pcl/io/pcd_io.h>
#include<pcl/point_types.h>
#include <pcl/common/common.h>
#include<pcl/visualization/pcl_visualizer.h>//可视化头文件
#include "lasreader.hpp"
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/radius_outlier_removal.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/passthrough.h> //直通滤波相关
#include <pcl/registration/icp.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/sample_consensus/method_types.h>
#include"CTrajectory.h"
using namespace std;
typedef pcl::PointXYZI ptype;
typedef pcl::PointCloud<ptype>::Ptr ptrtype;
class alscloud
{
public:
alscloud() {}
alscloud(string s1);
//alscloud(ptrtype p1):als_cloud(p1){}
~alscloud();
void readlas();
void radiusFilter();
void visual(ptrtype p1);
void passthrough();
ptrtype getcloud() { return als_cloud; }
void roofExtract();
void roadExtract();
ptrtype road_cloud, roof_cloud;
private:
const char* als_path;
ptrtype als_cloud;
};
class AlsManager
{
public:
AlsManager() {}
AlsManager(alscloud s1, alscloud s2);
~AlsManager() {}
void centralize(ptrtype mls_vscloud, ptrtype als_vscloud);
void WriteLas();
void cloudvisual(ptrtype src,ptrtype tgt, const char* name);
void Hcollation();
void XYcollation();
private:
alscloud als_1, als_2;
CTScanTrj trj;
};
typedef struct flat_grid {
int grayScale = 0;
float maxdif_height = 0;
float max_height = 0;
int candidate = 0;
vector<int> indexID;
}flat_grid; | [
"[email protected]"
]
| |
d186f2afddd52891f2d0d59b3a01d012f668c723 | f3efdf8c4466a8e1dffa40282979d68958d2cb14 | /atcoder.jp/abc179/abc179_d/Main.cpp | 6114fe890637287eddd647320f88d3b353c45c87 | []
| no_license | bokusunny/atcoder-archive | be1abd03a59ef753837e3bada6c489a990dd4ee5 | 248aca070960ee5519df5d4432595298864fa0f9 | refs/heads/master | 2023-08-20T03:37:14.215842 | 2021-10-20T04:19:15 | 2021-10-20T04:19:15 | 355,762,924 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 563 | cpp | #include <bits/stdc++.h>
using namespace std;
#include <atcoder/modint>
using namespace atcoder;
using mint = modint998244353;
int main() {
int N, K;
cin >> N >> K;
vector<int> L(K), R(K);
for (int i = 0; i < K; i++) cin >> L[i] >> R[i];
vector<mint> dp(N);
dp[0] = 1, dp[1] = -1;
for (int i = 0; i < N; i++) {
if (i != 0) dp[i] += dp[i - 1];
for (int j = 0; j < K; j++) {
if (i + L[j] < N) dp[i + L[j]] += dp[i];
if (i + R[j] + 1 < N) dp[i + R[j] + 1] -= dp[i];
}
}
cout << dp[N - 1].val() << endl;
return 0;
}
| [
"[email protected]"
]
| |
4a024385f52f0c8c06aedeaa2b6fb770570c4bd0 | 9d0c1da53da9e60d4a891d7edb7a02c31c8d26b9 | /kresources/blogging/kcal_resourceblogging_plugin.cpp | 33884c21b26a8b9ecc1f36afa1bf93e1d3738c33 | []
| no_license | serghei/kde3-kdepim | 7e6d4a0188c35a2c9c17babd317bfe3c0f1377d2 | a1980f1560de118f19f54a5eff5bae87a6aa4784 | refs/heads/master | 2021-01-17T10:03:14.624954 | 2018-11-04T21:31:00 | 2018-11-04T21:31:00 | 3,688,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,403 | cpp | /*
This file is part of kdepim.
Copyright (c) 2004 Reinhold Kainhofer <[email protected]>
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) 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.
*/
#include "kcal_resourceblogging.h"
#include "kcal_resourcebloggingconfig.h"
#include <kglobal.h>
#include <klocale.h>
using namespace KCal;
typedef KRES::PluginFactory< ResourceBlogging, ResourceBloggingConfig > BloggingFactory;
//K_EXPORT_COMPONENT_FACTORY( kcal_blogging, BloggingFactory )
extern "C" {
void *init_kcal_blogging()
{
KGlobal::locale()->insertCatalogue("kdepimresources");
KGlobal::locale()->insertCatalogue("kres_blogging");
return new BloggingFactory;
}
}
| [
"[email protected]"
]
| |
8371ca4e7a3135c568dd3d1a22c7b7b82c53dbcf | 8a0aa6df0318e7d171ca45d1273ce98f8a922fd6 | /cpp/cpp/PropertyUtil.h | 0eb32c5b6333d76aa9f607da9d576d9427b1e298 | []
| no_license | jgalfaro/mirrored-tbridge-modbus | 52780cda197c207ee4d19871af1de633d96c68d5 | f850b1e91e5490821ff90823b59885c1c22b96aa | refs/heads/master | 2021-01-21T17:10:12.336400 | 2017-06-21T11:58:31 | 2017-06-21T11:58:31 | 91,938,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | h | #pragma once
#include <map>
#include <string>
#include <iostream>
class PropertyException : std::exception {
public:
PropertyException(const char* message) {
this->message = message;
}
const char* what() {
return message;
}
private:
const char* message;
};
class PropertyUtil
{
enum { DEBUG = 0 };
public:
typedef std::map<std::string, std::string> PropertyMapT;
typedef PropertyMapT::value_type value_type;
typedef PropertyMapT::iterator iterator;
static void read(const char *filename, PropertyMapT &map);
static void read(std::istream &is, PropertyMapT &map);
static void write(const char *filename, PropertyMapT &map, const char *header = NULL);
static void write(std::ostream &os, PropertyMapT &map, const char *header = NULL);
static void print(std::ostream &os, PropertyMapT &map);
private:
static inline char m_hex(int nibble)
{
static const char *digits = "0123456789ABCDEF";
return digits[nibble & 0xf];
}
}; | [
"[email protected]"
]
| |
41063f5df84269ec4ed5586764f3b995df7d8d76 | 744c38647f9ad6ef13da1c1be711491cfdc4effe | /pessoa3.hpp | 8b89a3bac7ccf486a57ab267f2387254b611cbe6 | []
| no_license | pauloatavila/estrutura_dados_II | e041a29431d8ba03bbc9c2f6804d508663fa4856 | 97f79548618120cf062343425f65a1b94c19b15c | refs/heads/master | 2019-05-16T13:48:55.304533 | 2016-06-16T00:44:20 | 2016-06-16T00:44:20 | 55,104,997 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,709 | hpp | #include <iostream>
#include <string>
using namespace std;
// class PessoaTeste {
// protected:
// int variavel;
// public:
// PessoaTeste();
// void Aula();
// };
//
// PessoaTeste *raiz_teste = NULL;
//
// void PessoaTeste::Aula()
// {
// raiz_teste = NULL;
//
// };
class Pessoa {
protected:
string nome;
int idade;
Pessoa *filhoEsquerda;
Pessoa *filhoDireita;
Pessoa *pai;
public:
Pessoa(){
nome = "NULL";
idade = 0;
};
Pessoa(string name, int age){
nome = name;
idade = age;
filhoDireita = NULL;
filhoEsquerda = NULL;
};
~Pessoa(){
cout << "IML sendo acionado..." << endl;
};
void inserirFilho(Pessoa *novo){
if (novo->idade > this->idade){
if (filhoDireita == NULL){
filhoDireita = novo;
novo->pai = this;
} else {
this->filhoDireita->inserirFilho(novo);
}
} else {
if (filhoEsquerda == NULL){
filhoEsquerda = novo;
novo->pai = this;
} else {
this->filhoEsquerda->inserirFilho(novo);
}
}
}
void caminhoPreOrdem (){
cout << " " << this->nome;
if (filhoEsquerda != NULL){
this->filhoEsquerda->caminhoPreOrdem();
}
if (filhoDireita != NULL){
this->filhoDireita->caminhoPreOrdem();
}
}
void caminhoOrdem (){
if (filhoEsquerda != NULL){
this->filhoEsquerda->caminhoOrdem();
}
cout << " " << this->nome;
if (filhoDireita != NULL){
this->filhoDireita->caminhoOrdem();
}
}
void caminhoPosOrdem (){
if (filhoEsquerda != NULL){
this->filhoEsquerda->caminhoPosOrdem();
}
if (filhoDireita != NULL){
this->filhoDireita->caminhoPosOrdem();
}
cout << " " << this->nome;
}
void caminhoPosOrdemDelete (){
if (filhoEsquerda != NULL){
this->filhoEsquerda->caminhoPosOrdemDelete();
}
if (filhoDireita != NULL){
this->filhoDireita->caminhoPosOrdemDelete();
}
delete this;
}
void deleteEscolhido (Pessoa ** apagar, Pessoa ** raiz)
{
if (filhoDireita == NULL && filhoEsquerda == NULL) deleteNoFolha(apagar, raiz);
else if (filhoDireita == NULL) delete1FilhoD(apagar);
else if (filhoEsquerda == NULL) delete1FilhoE(apagar);
else delete2Filhos(apagar);
}
void deleteNoFolha (Pessoa ** apagar, Pessoa ** raiz){
if ((*apagar)->pai != NULL)
{
if ((*apagar)->pai->filhoDireita == (*apagar))
{
(*apagar)->pai->filhoDireita = NULL;
delete (*apagar);
}
else
{
(*apagar)->pai->filhoEsquerda = NULL;
delete (*apagar);
}
}
else { //caso não tenha pai
delete (*apagar);
(*raiz) = NULL;
}
}
void delete1FilhoD (Pessoa ** apagar, Pessoa ** raiz){
if ((*apagar) != (*raiz)){
if ((*apagar)->pai->filhoDireita == (*apagar))
{
(*apagar)->pai->filhoDireita = (*apagar)->filhoEsquerda;
delete (*apagar);
}
else
{
(*apagar)->pai->filhoEsquerda = (*apagar)->filhoEsquerda;
delete (*apagar);
}
} else {
(*raiz) = (*apagar)->filhoEsquerda;
delete (*apagar);
}
}
void delete1FilhoE (Pessoa ** apagar){
if ((*apagar) != (*raiz)){
if ((*apagar)->pai->filhoDireita == (*apagar))
{
(*apagar)->pai->filhoDireita = (*apagar)->filhoDireita;
delete (*apagar);
}
else
{
(*apagar)->pai->filhoEsquerda = (*apagar)->filhoDireita;
delete (*apagar);
}
} else {
(*raiz) = (*apagar)->filhoDireita;
delete (*apagar);
}
}
void delete2Filhos (Pessoa ** apagar){
Pessoa *aux;
aux = (*apagar)->filhoDireita;
if ((*apagar)->pai->filhoEsquerda == (*apagar)){
while (aux->filhoEsquerda != NULL){
aux = aux->filhoEsquerda;
}
aux->pai->filhoEsquerda = aux->filhoDireita;
if (aux->filhoDireita != NULL){
aux->filhoDireita->pai = aux->pai;
}
aux->pai = (*apagar)->pai;
(*apagar)->pai->filhoEsquerda = aux;
aux->filhoDireita = (*apagar)->filhoDireita;
aux->filhoEsquerda = (*apagar)->filhoEsquerda;
(*apagar)->filhoDireita->pai = aux;
(*apagar)->filhoEsquerda->pai = aux;
delete (*apagar);
} else {
while (aux->filhoEsquerda != NULL){
aux = aux->filhoEsquerda;
}
aux->pai->filhoEsquerda = aux->filhoDireita;
if (aux->filhoDireita != NULL){
aux->filhoDireita->pai = aux->pai;
}
aux->pai = (*apagar)->pai;
(*apagar)->pai->filhoDireita = aux;
aux->filhoDireita = (*apagar)->filhoDireita;
aux->filhoEsquerda = (*apagar)->filhoEsquerda;
(*apagar)->filhoDireita->pai = aux;
(*apagar)->filhoEsquerda->pai = aux;
delete (*apagar);
}
}
Pessoa * buscar (int idade){
if (idade == this->idade) return this;
else {
if (idade > this->idade && filhoDireita != NULL) this->filhoDireita->buscar(idade);
else {
if (idade < this->idade && filhoEsquerda != NULL) this->filhoEsquerda->buscar(idade);
else return NULL;
}
}
}
string getNome(){
return nome;
};
void setNome(string name){
nome = name;
};
int getIdade(){
return idade;
};
void setIdade(int ida){
idade = ida;
};
void setPai(){
pai = NULL;
};
};
class PessoaFisica: public Pessoa {
private:
string cpf;
public:
PessoaFisica(){
cpf = "NULL";
};
PessoaFisica(string cadastroF){
cpf = cadastroF;
};
~PessoaFisica(){
cout << "Cadastro Fisico sendo excluido" << endl << endl;
};
string getCPF(){
return cpf;
};
void setCPF(string cadastroF){
cpf = cadastroF;
};
};
class PessoaJuridica: public Pessoa {
private:
string cnpj;
public:
PessoaJuridica(){
cnpj = "NULL";
};
PessoaJuridica(string cadastroJ){
cnpj = cadastroJ;
};
~PessoaJuridica(){
cout << "Cadastro Juridico sendo excluido" << endl << endl;
};
string getCPF(){
return cnpj;
};
void setCPF(string cadastroJ){
cnpj = cadastroJ;
};
};
| [
"[email protected]"
]
| |
271bed1b81f3e1f6b54054828517a60ffb53b288 | be427a149157edf3f702b8775cfcf6e690e386d1 | /CastleVania/CastleVania/TopStair.h | ba11c49d26779f747004a13fb61b9ea53e2ad35c | []
| no_license | Liinhleo/17520691-GameUIT-CastleVania | 934dbb3f120360efc36b6e96124b95511cdb0347 | 808954632f69946832397202b43ac70f08398874 | refs/heads/master | 2022-03-28T23:01:26.390760 | 2019-12-06T02:45:25 | 2019-12-06T02:45:25 | 215,361,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | h | #pragma once
#include "GameObject.h"
class TopStair : public CGameObject
{
int id;
int width; // rong
int height; // cao
public:
TopStair(int _id, int _width, int _height)
{
type = ObjectType::TOP_STAIR; // TREN CAU THANG -> ON GRAVITY
this->id = _id;
this->width = _width;
this->height = _height;
AddAnimation(601);
}
virtual void Render();
virtual void GetBoundingBox(float& left, float& top, float& right, float& bottom);
};
| [
"17520691"
]
| 17520691 |
903352c69709e5a775e0cfcdb5dc0401cb24dca3 | de2a8f634a0e99f463df2ad79853dcf35bf23deb | /src/rpcmgr.h | fc53b97daf7b70037f2bf8071e35652225bbe981 | [
"MIT"
]
| permissive | SelfSellTeam/Wallet | 35a5bc42831fe43005ce055b13ff0623b235deba | 15a047a308fb0145c6d5df4e54c53a58b59fbf07 | refs/heads/master | 2020-03-10T10:43:23.934099 | 2018-04-13T08:50:59 | 2018-04-13T08:50:59 | 129,339,549 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,023 | h | #ifndef __RPC_MGR_H__
#define __RPC_MGR_H__
#include "misc.h"
#include <QObject>
#include <QMap>
#include <QSettings>
#include <QFile>
#include <QProcess>
#include <QMutex>
#include "outputmessage.h"
class QTimer;
class QFrame;
class WorkerThreadManager;
static QMutex _mutex_for_current_process;
class RpcMgr : public QObject {
Q_OBJECT
public:
static RpcMgr* getInstance();
static void deleteInstance();
void postRPC(QString cmd, int type = 0);
public:
void startBlockChain();
void closeBlockChain();
void initWorkThreadManager();
void uninitThreadManager();
void updateResult(QString id, QString data);
QString configGetContractAddress(QString path);
void configSetContractAddress(QString path, QString address);
QString configRemoveContractAddress(QString address);
QString configGetScriptId(QString path);
void configSetScriptId(QString path, QString scriptId);
QStringList configGetAllScripts();
QString configRemoveScriptId(QString scriptId);
bool isContractFileRegistered(QString path);
bool isContractFileUpgraded(QString path);
bool isScriptAdded(QString path);
QProcess* currentProcess();
int currentPort();
void setCurrentAccount(QString accountName);
QProcess* _test_chain_process;
QProcess* _formal_chain_process;
BlockChainType getCurChainType();
void setCurChainType(BlockChainType type);
QMap<QString, SmartContractInfo> contractInfoMap;
bool _is_in_sandbox;
signals:
void onTestChainStarted();
void onFormalChainStarted();
void testRpcPosted(QString cmd);
void formalRpcPosted(QString cmd);
private:
RpcMgr();
~RpcMgr();
static RpcMgr* _rpc_mgr;
WorkerThreadManager* _worker_thread_manager_test;
WorkerThreadManager* _worker_thread_manager_formal;
QThread* _test_worker_manager_thread;
QThread* _formal_worker_manager_thread;
BlockChainType _curren_chain_type;
};
#endif // RpcMgr
| [
"[email protected]"
]
| |
b0a32b67df84fc6037ab2f141b23328a14a46a73 | 6470fe9c1d498018d8661c12f8a0152dfc7e53b1 | /GP3CW-Final/GP3Coursework/cSphere.h | 9aef398021501e169c2998ca0ab59dcf8ddbfb26 | []
| no_license | Declanw07/Games-Programming-3-Coursework-Final | b886ec60b5fb33e8e1e0bb182eab6a1618959a00 | 0ee8fa2407ac589e4d50c25fade80daa5f4722fd | refs/heads/master | 2021-09-03T11:15:00.802468 | 2018-01-08T16:03:02 | 2018-01-08T16:03:02 | 116,697,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | h | /*
==========================================================================
cSphere.h
==========================================================================
*/
#ifndef _SPHERE_H
#define _SPHERE_H
#include "windowOGL.h"
#include "glm\glm.hpp"
#include "glx\glext.h"
#include "wglext.h"
#include "GL\glut.h"
#include "cShapes.h"
class cSphere : public cShapes
{
public:
cSphere();
cSphere(GLdouble dRadius, GLint dSlices, GLint dStacks);
virtual void render(float rotAngle);
virtual void initialise(cTexture theTexture);
virtual void initialise(GLint theTextureID, glm::vec3 thePosition, glm::vec3 theTranslation);
private:
GLdouble sRadius;
GLint sSlices;
GLint sStacks;
glm::vec3 m_Position;
glm::vec3 m_Translation;
GLUquadric *quad;
GLuint m_TextureID;
};
#endif | [
"[email protected]"
]
| |
1fe7f38f5f1d0b4636961c4fd1be349bf46c2d89 | c05867651bb33a4b30e9d41f483b991657122478 | /src/qt/bitcoin.cpp | 333e4425040449a1fa0487817b8ab02b867b3a4b | [
"MIT"
]
| permissive | TetraProject/Tetra | 05127dd95f7d692bb725b7f1d30aac42ef87ff6b | 1174dda734672e2e238f062520cf24ca61e891d3 | refs/heads/master | 2021-01-09T20:46:38.682558 | 2016-06-06T16:46:37 | 2016-06-06T16:46:37 | 60,505,975 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,764 | cpp | // Copyright (c) 2011-2013 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 <QApplication>
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "paymentserver.h"
#include "splashscreen.h"
#include <QMessageBox>
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
#include <QLocale>
#include <QTimer>
#include <QTranslator>
#include <QLibraryInfo>
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Declare meta types used for QMetaObject::invokeMethod
Q_DECLARE_METATYPE(bool*)
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static SplashScreen *splashref;
static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(guiref, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
return false;
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired)
{
if(!guiref)
return false;
if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55));
qApp->processEvents();
}
printf("init message: %s\n", message.c_str());
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Tetra can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Command-line options take precedence:
ParseParameters(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Register meta types used for QMetaObject::invokeMethod
qRegisterMetaType< bool* >();
// Do this early as we don't want to bother initializing if we are just calling IPC
// ... but do it after creating app, so QCoreApplication::arguments is initialized:
if (PaymentServer::ipcSendCommandLine())
exit(0);
PaymentServer* paymentServer = new PaymentServer(&app);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Tetra",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
QApplication::setOrganizationName("Tetra");
QApplication::setOrganizationDomain("tetra.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
QApplication::setApplicationName("Tetra-Qt-testnet");
else
QApplication::setApplicationName("Tetra-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
#ifdef Q_OS_MAC
// on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange)
if(GetBoolArg("-testnet")) {
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
}
#endif
SplashScreen splash(QPixmap(), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
#ifndef Q_OS_MAC
// Regenerate startup link, to fix links to old versions
// OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs)
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
#endif
boost::thread_group threadGroup;
BitcoinGUI window;
guiref = &window;
QTimer* pollShutdownTimer = new QTimer(guiref);
QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
if(AppInit2(threadGroup))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel *walletModel = 0;
if(pwalletMain)
walletModel = new WalletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
if(walletModel)
{
window.addWallet("~Default", walletModel);
window.setCurrentWallet("~Default");
}
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Now that initialization/startup is done, process any command-line
// bitcoin: URIs
QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
app.exec();
window.hide();
window.setClientModel(0);
window.removeAllWallets();
guiref = 0;
delete walletModel;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
}
else
{
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
| [
"[email protected]"
]
| |
e247286a3eb496660b8b7a33b26e8b20252d5720 | c98bcc95294d3cc38d103a6dbbafb10a0d3540c5 | /CarDrivingSim/src/Report.cpp | a93088329ed802b6ddf001fe7ef5b0e31edbd025 | []
| no_license | mor91/cs | 19d35ddb5045737f2ba04d633296ded246748059 | 951db0dcff50adcb8e92b18722a28705c4091e91 | refs/heads/master | 2021-01-18T14:59:02.200497 | 2015-01-05T14:58:45 | 2015-01-05T14:58:45 | 28,816,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | cpp | /*
* File: Report.cpp
* Author: chen
*
* Created on November 15, 2014, 11:45 AM
*/
#include "Report.h"
#include "ini.h"
#include <map>
#include <vector>
#include <string>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
Report::Report() {
}
Report::Report(const std::string &reportID) {
_reportID=reportID;
}
Report::~Report() {
/*(auto& key:_cars){
delete key.second;
delete key.first;
}
for(auto& key:_junctions){
delete key.second;
delete key.first;
}
for(auto& key:_roadMap){
for(auto inKey:key.second){
delete inKey.second;
delete inKey.first;
}
delete key;
}*/
std::cout << "Report deleted"<< std::endl;
}
void Report::setCars(std::map<std::string, Car*> &cars) {
_cars=&cars;
}
void Report::setJunctions(std::map<std::string, Junction*> &junctions) {
_junctions=&junctions;
}
void Report::setRoadMap(std::map<std::string, std::map<std::string, Road*>> &roadMap) {
_roadMap=&roadMap;
}
void Report::writeReports() {
/*for(int i=0; i<_reoprts.size();i++){
if(_reoprts[i]->getReportType()=="car_report"){
std::string carId=_reoprts[i]->getCarId();
std::string history=_reoprts[i]->getHistory();
std::string faultyTimeLeft=_reoprts[i]->getFaultyTimeLeft
}
if(_reoprts[i]->getReportType()=="road_report"){
}
if(_reoprts[i]->getReportType()=="junction_report"){
}
}*/
}
| [
"[email protected]"
]
| |
d5396dffa6e7d9d9c6630d414627d2ca9721bff2 | e0a02adb87ebeed031be11f190cf43945ec08ab9 | /robot_controll/historic/PhoneThread.cpp | 7edac9c4a709222f8069b165c3684654ed843e90 | []
| no_license | Robotics-DAI-FMFI-UK/smely-zajko | e596195ec75e8c2b8628b049cdd58756fb2d2563 | aaae62e01f67c6b70dc8d2a5b6e64f5d81441a34 | refs/heads/master | 2020-04-12T03:44:07.054752 | 2016-09-19T19:02:09 | 2016-09-19T19:02:09 | 40,720,258 | 0 | 1 | null | 2016-09-14T11:10:09 | 2015-08-14T14:51:14 | C++ | UTF-8 | C++ | false | false | 2,788 | cpp | /*
* File: PhoneThread.cpp
* Author: robotour
*
* Created on September 10, 2012, 12:37 AM
*/
#include <string.h>
#include "PhoneThread.h"
bool PhoneThread::end;
SbotThread* PhoneThread::sbot;
PhoneThread::PhoneThread(SbotThread* sbot1)
{
sbot = sbot1;
end = false;
}
PhoneThread::~PhoneThread() {
}
void PhoneThread::run()
{
pthread_create( &t, NULL, mainLoop, NULL );
pthread_detach( t );
}
void PhoneThread::stop()
{
if(!end){
end = true;
if( pthread_join( t, NULL )!=0){
printf("phone thread join error");
}
}
}
void* PhoneThread::mainLoop(void*)
{
int speed = 0;
int direction = 0;
char *command = (char *)"/home/robotour/btserver/server";
FILE* f;
while (!end)
{
// launch the program that will wait for a connection from the phone
if ( !(f = (FILE*)popen(command,"r")) ){
// If fpipe is NULL
perror("PhoneThread::mainLoop() - popen()");
exit(-1);
}
if (f < 0) return 0;
printf("waiting for user connecting on BT from a phone...\n");
char b[80];
do {
if (0 == fgets( b, 70, f)) break;
// user with phone has specified some command
printf("phone: %s", b);
if (strncmp(b, "fwd", 3) == 0)
{
speed++;
if( speed>10 ) speed = 10;
sbot->setDirection(direction);
sbot->setSpeed(speed);
}
else if (strncmp(b, "back", 4) == 0)
{
speed--;
if( speed<-10) speed = -10;
sbot->setDirection(direction);
sbot->setSpeed(speed);
}
else if (strncmp(b, "left", 4) == 0)
{
direction--;
if(direction< -30) direction = -30;
sbot->setDirection(direction);
sbot->setSpeed(speed);
}
else if (strncmp(b, "right", 5) == 0)
{
direction++;
if(direction> 30) direction = 30;
sbot->setDirection(direction);
sbot->setSpeed(speed);
}
else if (strncmp(b, "stop", 4) == 0)
{
autonomy = false;
speed = 0;
direction = 0;
sbot->setSpeed(speed);
sbot->setDirection(direction);
}
else if (strncmp(b, "go", 2) == 0)
{
autonomy = true;
}
} while (strncmp(b, "bye", 3) != 0);
printf("phone has disconnected.");
// user with the phone has disconnected
pclose(f);
} // while (!end)
}
| [
"[email protected]"
]
| |
f5679589f940f3a2247e5dead1fa051dcf244183 | 4ffbc2e49202a19cf39699819a8a6804b696f4ff | /src/CLRObject.h | 2ae67ed2b63bdddd477510b1dadbeb8af03c930d | []
| no_license | BenitoJedai/node-clr | 357b2dccb1b1851ed744b15b831df7829a554c07 | 4f49d3ea3ba27bb6c8993d7f1229f70eca2fb02e | refs/heads/master | 2020-02-26T14:00:25.612586 | 2015-03-31T16:39:06 | 2015-03-31T16:39:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | h | #ifndef CLROBJECT_H_
#define CLROBJECT_H_
#include "node-clr.h"
// node object wrapper that holds System::Object^
class CLRObject : public node::ObjectWrap
{
public:
static void Init();
static bool IsCLRObject(v8::Handle<v8::Value> obj);
static v8::Handle<v8::Value> GetType(v8::Handle<v8::Value> value);
static bool IsCLRConstructor(v8::Handle<v8::Value> value);
static v8::Handle<v8::Value> TypeOf(v8::Handle<v8::Value> value);
static v8::Handle<v8::Object> Wrap(v8::Handle<v8::Object> obj, System::Object^ value);
static v8::Handle<v8::Object> Wrap(System::Object^ value);
static System::Object^ Unwrap(v8::Handle<v8::Value> obj);
static v8::Local<v8::Function> CreateConstructor(v8::Handle<v8::String> typeName, v8::Handle<v8::Function> initializer);
private:
static NAN_METHOD(New);
static v8::Persistent<v8::ObjectTemplate> objectTemplate_;
gcroot<System::Object^> value_;
CLRObject(System::Object^ value);
~CLRObject();
};
#endif
| [
"[email protected]"
]
| |
5aa5a9c68bc0769c233770d50e550d6ae7be3aa7 | 28490f37f4c4393963718d1539d00bbfdf97047f | /assignment_8-B/main.cpp | a37b3cd02a89867917d3ed08a4b68a509b12b3ff | []
| no_license | collinbrake/computerscienceI | d4bb8e755b4e9653c44d9b451e16251c8f8b8aca | 532d09c6ed306f7ca389aa808292f073f46dce01 | refs/heads/master | 2023-01-25T01:57:23.204612 | 2020-12-09T00:24:13 | 2020-12-09T00:24:13 | 290,885,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,474 | cpp | /*
COPYRIGHT (C) 2020 Collin Brake (cmb361)
All rights reserved.
Computer Science I - ASSIGNMENT 8-B
Author: Collin Brake
[email protected]
Purpose: Practice vectors and strings by decoding a code.
*/
#include <iostream>
#include <string>
#include <cstring>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
char encoded[] = ":mmZ\\dxZmx]Zpgy";
string decoded = "";
char originalChar, minusKey;
// Loop over each possible key and attempt to decode the message
for (int key = 1; key < 101; ++key)
{
for (char encryptedChar : encoded)
{
// Subtract the key we are trying to start with
minusKey = encryptedChar - key;
// If the difference falls in the range of valid
// ASCII codes, accept it. Otherwise, try to add
// the upper bound and subtract the lower bound, per
// the information given.
if (minusKey <= 126 && minusKey >= 32)
originalChar = minusKey;
else
originalChar = (minusKey + 127) - 32;
// Add the decoded char to the string.
decoded += originalChar;
}
// Display the decoded message at each key.
cout << "Key: " << key << " Decoded message: " << decoded << endl;
// Clear the contents of the string for the next try.
decoded.clear();
}
return 0;
}
| [
"[email protected]"
]
| |
4be3c939195103d5aa5d6702ab7f497b913edc63 | 0ab72b7740337ec0bcfec102aa7c740ce3e60ca3 | /include/minimizer/copy.h | 35427468b468dc66a998751d85f230ee410fa4e2 | []
| no_license | junwang-nju/mysimulator | 1d1af4ad7ddbe114433ebdadd92de8bb3a45c04f | 9c99970173ce87c249d2a2ca6e6df3a29dfc9b86 | refs/heads/master | 2021-01-10T21:43:01.198526 | 2012-12-15T23:22:56 | 2012-12-15T23:22:56 | 3,367,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | h |
#ifndef _Minimizer_Copy_H_
#define _Minimizer_Copy_H_
#include "minimizer/interface.h"
namespace mysimulator {
template <MinimizerName MN, LineMinimizerName LMN, typename KT,
template<typename> class VT, typename PT, typename T>
void copy(Minimizer<MN,LMN,KT,VT,PT,T>& M,
const Minimizer<MN,LMN,KT,VT,PT,T>& cM) {
Error("Operation Copy for this Object Disabled!");
}
}
#include "minimizer/steep/copy-specification.h"
#include "minimizer/conjg/copy-specification.h"
#include "minimizer/lbfgs/copy-specification.h"
#endif
| [
"[email protected]"
]
| |
5ec04ef478bfed4172c3583a05db07da8cea9efa | 571e4a9d6ef8b651fa847180858cc441d3de4e7d | /Source/FiftGit/FiftGitCharacter.h | 89e2930b8cc1fba3ce5476409e0cb2f5d01d13bf | []
| no_license | smallB007/FiftGit | d10ebedd26dd563de5162796608ba7fe08b35f2c | 040a1ea71dcd481f7d83075f8e02a58db2caa2b8 | refs/heads/master | 2021-01-06T20:37:53.635619 | 2015-06-14T12:08:30 | 2015-06-14T12:08:30 | 37,410,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,264 | h | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/Character.h"
#include "FiftGitCharacter.generated.h"
class UInputComponent;
UCLASS(config=Game)
class AFiftGitCharacter : public ACharacter
{
GENERATED_BODY()
/** Pawn mesh: 1st person view (arms; seen only by self) */
UPROPERTY(VisibleDefaultsOnly, Category=Mesh)
class USkeletalMeshComponent* Mesh1P;
/** First person camera */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FirstPersonCameraComponent;
public:
AFiftGitCharacter();
/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
float BaseTurnRate;
/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
float BaseLookUpRate;
/** Gun muzzle's offset from the characters location */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Gameplay)
FVector GunOffset;
/** Projectile class to spawn */
UPROPERTY(EditDefaultsOnly, Category=Projectile)
TSubclassOf<class AFiftGitProjectile> ProjectileClass;
/** Sound to play each time we fire */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Gameplay)
class USoundBase* FireSound;
/** AnimMontage to play each time we fire */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)
class UAnimMontage* FireAnimation;
protected:
/** Fires a projectile. */
void OnFire();
/** Handles moving forward/backward */
void MoveForward(float Val);
/** Handles stafing movement, left and right */
void MoveRight(float Val);
/**
* Called via input to turn at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void TurnAtRate(float Rate);
/**
* Called via input to turn look up/down at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void LookUpAtRate(float Rate);
struct TouchData
{
TouchData() { bIsPressed = false;Location=FVector::ZeroVector;}
bool bIsPressed;
ETouchIndex::Type FingerIndex;
FVector Location;
bool bMoved;
};
void BeginTouch(const ETouchIndex::Type FingerIndex, const FVector Location);
void EndTouch(const ETouchIndex::Type FingerIndex, const FVector Location);
void TouchUpdate(const ETouchIndex::Type FingerIndex, const FVector Location);
TouchData TouchItem;
protected:
// APawn interface
virtual void SetupPlayerInputComponent(UInputComponent* InputComponent) override;
// End of APawn interface
/*
* Configures input for touchscreen devices if there is a valid touch interface for doing so
*
* @param InputComponent The input component pointer to bind controls to
* @returns true if touch controls were enabled.
*/
bool EnableTouchscreenMovement(UInputComponent* InputComponent);
public:
/** Returns Mesh1P subobject **/
FORCEINLINE class USkeletalMeshComponent* GetMesh1P() const { return Mesh1P; }
/** Returns FirstPersonCameraComponent subobject **/
FORCEINLINE class UCameraComponent* GetFirstPersonCameraComponent() const { return FirstPersonCameraComponent; }
};
| [
"[email protected]"
]
| |
874494b3d2a50fdfeee41818e24c580145993a01 | 5559e9585efcc8ca1724b86a0105253271f5ce0c | /Source/FileSystem/Directory.h | 855136e316b1d349bcd33012b0830003d3f6285e | []
| no_license | ProjectStortSpel/MasterServer | 0923e0e605522f889857825a72d5d3deabea2598 | fc62a9a3e41e3b03082d8593d3a7e4726ec5e936 | refs/heads/master | 2020-05-17T00:12:04.838976 | 2015-04-22T11:05:14 | 2015-04-22T11:05:14 | 30,415,584 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 844 | h | #ifndef DIRECTORY_H
#define DIRECTORY_H
#include <string>
#include <vector>
#if defined(WIN32)
#define EXPORT __declspec(dllexport)
#define IMPORT __declspec(dllimport)
#else
#define EXPORT __attribute__((visibility("default")))
#define IMPORT
#endif
namespace FileSystem
{
enum Type
{
_Directory,
_File
};
struct Entry
{
std::string name;
Type type;
};
namespace Directory
{
bool EXPORT Create(std::string _path);
bool EXPORT Exist(std::string _path);
EXPORT std::vector<Entry> GetEntries(std::string _path);
EXPORT std::vector<std::string> GetSubDirectories(std::string _path);
EXPORT std::vector<std::string> GetFiles(std::string _path);
EXPORT std::vector<std::string> GetAllFiles(std::string _path);
}
}
#endif | [
"[email protected]"
]
| |
1c67802062bded6aaa2bd36dabccd3b2c35ed45d | 32f8a5ad85b87cbf7bd031a09164a50725f49847 | /Source/LuminoEngine/Source/Animation/AnimationCurve.cpp | b36f65817610ad18693da531cd5dabdd3cb13cb5 | [
"MIT"
]
| permissive | mediabuff/Lumino | 9787c588bac3a983c79199cbc168a919bb17a0f6 | 684be8f25631a104f5236e6131c0fcb84df8bb57 | refs/heads/master | 2021-05-14T17:04:46.553426 | 2017-12-28T14:33:47 | 2017-12-28T14:33:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,341 | cpp |
#include "../Internal.h"
#include <Lumino/Animation/AnimationCurve.h>
LN_NAMESPACE_BEGIN
//==============================================================================
// AnimationCurve
//==============================================================================
//------------------------------------------------------------------------------
AnimationCurve::AnimationCurve()
: m_wrapMode(WrapMode_Once)
{
}
//------------------------------------------------------------------------------
AnimationCurve::~AnimationCurve()
{
}
//------------------------------------------------------------------------------
void AnimationCurve::getTime(double time)
{
if (m_wrapMode == WrapMode_Once)
{
updateValue(time);
}
else if (m_wrapMode == WrapMode_Loop)
{
double lastTime = getLastFrameTime();
if (time > lastTime)
{
time = fmod(time, lastTime);
}
updateValue(time);
}
else
{
LN_NOTIMPLEMENTED();
}
//mTime = time;
//time *= mTimeTick; // フレーム位置へ変換
//double last_frame_pos = getLastFramePos();
//if (last_frame_pos == 0)
//{
// time = 0;
//}
//else if (mLoopMode == LN_ANIMATIONLOOPMODE_REPEAT_LOOP)
//{
// // ループ位置未設定
// if (mLoopEndPos == 0.0f && mLoopBeginPos == 0.0f)
// {
// // 終端のキーフレームの時間を使ってループ
// if (time > last_frame_pos)
// {
// time = fmod(time, last_frame_pos);
// }
// }
// // ループ位置設定済み
// else
// {
// // time_ がループ領域を超えていた場合は開始時間からループ
// if (time > mLoopEndPos)
// {
// time -= mLoopBeginPos;
// time = fmod(time, (mLoopEndPos - mLoopBeginPos));
// time = mLoopBeginPos + time;
// }
// }
//}
//else if (mLoopMode == LN_ANIMATIONLOOPMODE_REPEAT_LOOP)
//{
// LN_PRINT_NOT_IMPL_FUNCTION;
//}
//mCurrentFramePos = time;
}
//==============================================================================
// VMDBezierTable
//==============================================================================
//------------------------------------------------------------------------------
FloatAnimationCurve::FloatAnimationCurve()
: m_defaultValue(0.0f)
, m_value(0.0f)
{
}
//------------------------------------------------------------------------------
FloatAnimationCurve::~FloatAnimationCurve()
{
}
//------------------------------------------------------------------------------
void FloatAnimationCurve::addKeyFrame(const FloatKeyFrame& keyFrame)
{
// そのまま追加できる
if (m_keyFrameList.isEmpty() || m_keyFrameList.getLast().FrameTime <= keyFrame.FrameTime)
{
m_keyFrameList.add(keyFrame);
}
// 追加後のソートが必要
else
{
// 比較用ファンクタ
struct compare
{
bool operator()(const FloatKeyFrame& l, const FloatKeyFrame& r)
{
return l.FrameTime < r.FrameTime;
}
};
m_keyFrameList.add(keyFrame);
std::stable_sort(m_keyFrameList.begin(), m_keyFrameList.end(), compare());
}
}
//------------------------------------------------------------------------------
void FloatAnimationCurve::addKeyFrame(double frame_pos, float value, InterpolationMode mode)
{
FloatKeyFrame key;
key.FrameTime = frame_pos;
key.Value = value;
key.Mode = mode;
addKeyFrame(key);
}
static int _cmpKey(const void* a_, const void* b_)
{
FloatKeyFrame* l = (FloatKeyFrame*)a_;
FloatKeyFrame* r = (FloatKeyFrame*)b_;
if ((l)->FrameTime < (r)->FrameTime)
return -1;
else if ((l)->FrameTime >= (r)->FrameTime && (l)->FrameTime < ((r + 1))->FrameTime)
return 0;
else
return 1;
}
//------------------------------------------------------------------------------
void FloatAnimationCurve::updateValue(double time)
{
if (!m_keyFrameList.isEmpty())
{
// time_ が最初のフレーム位置より前の場合はデフォルト値
if (time < m_keyFrameList.getFront().FrameTime)
{
m_value = m_defaultValue;
}
// キーがひとつだけの場合はそのキーの値
else if (m_keyFrameList.getCount() == 1)
{
m_value = m_keyFrameList.getFront().Value;
}
// time_ が終端以降の場合は終端の値
else if (time >= m_keyFrameList.getLast().FrameTime)
{
m_value = m_keyFrameList.getLast().Value;
}
// 以上以外の場合は補間する
else
{
const FloatKeyFrame* key0 = (FloatKeyFrame*)bsearch(&time, &(m_keyFrameList[0]), m_keyFrameList.getCount(), sizeof(FloatKeyFrame), _cmpKey);
const FloatKeyFrame* key1 = key0 + 1;
float p0 = key0->Value;
float p1 = key1->Value;
float t0 = static_cast< float >(key0->FrameTime);
float t1 = static_cast< float >(key1->FrameTime);
float t = static_cast< float >(time - t0) / (t1 - t0);
switch (key0->Mode)
{
// 補間無し
case InterpolationMode_None:
{
m_value = p0;
break;
}
// 線形
case InterpolationMode_Linear:
{
m_value = p0 + (p1 - p0) * t;
break;
}
// 等加速度
case InterpolationMode_QuadAccel:
{
m_value = Math::quadAccel(p0, key0->Velocity, key0->Accel, static_cast< float >(time - key0->FrameTime));
break;
}
// 三次補間
case InterpolationMode_Hermite:
{
m_value = Math::hermite(
p0, p1,
key0->RightSlope,
key1->LeftSlope,
t);
break;
}
// Catmull-Rom
case InterpolationMode_CatmullRom:
{
// ループ再生で time が終端を超えている場合、
// この時点でkey の値は ループ開始位置のひとつ前のキーを指している
const FloatKeyFrame& begin = m_keyFrameList.getFront();
const FloatKeyFrame& end = m_keyFrameList.getLast();
// この補間には、begin のひとつ前と end のひとつ後の値が必要。
// それぞれが始点、終点の場合はループするように補間する
m_value = Math::catmullRom(
((key0->FrameTime == begin.FrameTime) ? end.Value : (key0 - 1)->Value),
p0,
p1,
((key1->FrameTime == end.FrameTime) ? begin.Value : (key0 + 2)->Value),
t);
break;
}
}
}
}
else
{
m_value = m_defaultValue;
}
}
//------------------------------------------------------------------------------
double FloatAnimationCurve::getLastFrameTime() const
{
if (m_keyFrameList.isEmpty()) return 0;
return m_keyFrameList.getLast().FrameTime;
}
//==============================================================================
// VMDBezierTable
//==============================================================================
//------------------------------------------------------------------------------
void VMDBezierTable::initialize(float fPointX1, float fPointY1, float fPointX2, float fPointY2)
{
if (fPointX1 == fPointY1 && fPointX2 == fPointY2)
{
m_isLinear = true;
}
else
{
fPointX1 = (fPointX1 / 127.0f) * 3.0f;
fPointY1 = (fPointY1 / 127.0f) * 3.0f;
fPointX2 = (fPointX2 / 127.0f) * 3.0f;
fPointY2 = (fPointY2 / 127.0f) * 3.0f;
// 高速化のためテーブル化しておく
m_yValue[0] = 0.0f;
m_yValue[YVAL_DIV_NUM] = 1.0f;
float fAddX = 1.0f / (float)YVAL_DIV_NUM;
for (int i = 1; i < YVAL_DIV_NUM; i++)
{
m_yValue[i] = getYVal(fAddX * i, fPointX1, fPointY1, fPointX2, fPointY2);
}
m_isLinear = false;
}
}
//------------------------------------------------------------------------------
float VMDBezierTable::getInterValue(float fX)
{
if (m_isLinear) return fX; // 線形補間
// テーブルを線形補間する
fX *= (float)YVAL_DIV_NUM;
int iIdx = (int)fX;
fX -= iIdx;
return m_yValue[iIdx] * (1.0f - fX) + m_yValue[iIdx + 1] * fX;
}
//------------------------------------------------------------------------------
float VMDBezierTable::getYVal(float fX, float fX1, float fY1, float fX2, float fY2)
{
float fT = fX;
float fInvT = 1.0f - fT;
for (int i = 0; i < 32; i++)
{
float fTempX = fInvT*fInvT*fT*fX1 + fInvT*fT*fT*fX2 + fT*fT*fT;
fTempX -= fX;
if (fabsf(fTempX) < 0.0001f)
{
break;
}
else
{
fT -= fTempX * 0.5f;
fInvT = 1.0f - fT;
}
}
return fInvT*fInvT*fT*fY1 + fInvT*fT*fT*fY2 + fT*fT*fT;
}
//==============================================================================
// VMDBezierAttitudeTransformAnimation
//==============================================================================
//------------------------------------------------------------------------------
VMDBezierAttitudeTransformAnimation::VMDBezierAttitudeTransformAnimation()
{
}
//------------------------------------------------------------------------------
VMDBezierAttitudeTransformAnimation::~VMDBezierAttitudeTransformAnimation()
{
}
//------------------------------------------------------------------------------
void VMDBezierAttitudeTransformAnimation::addKeyFrame(
double framePos, const Vector3& pos, const Quaternion& rot,
char* interpolation_x,
char* interpolation_y,
char* interpolation_z,
char* interpolation_rot)
{
m_keyFrameList.add(KeyFrame());
KeyFrame& key = m_keyFrameList.getLast();
key.Time = framePos;
key.Position = pos;
key.Rotation = rot;
key.Rotation.normalize();
key.PosXInterBezier.initialize(interpolation_x[0], interpolation_x[4], interpolation_x[8], interpolation_x[12]);
key.PosYInterBezier.initialize(interpolation_y[0], interpolation_y[4], interpolation_y[8], interpolation_y[12]);
key.PosZInterBezier.initialize(interpolation_z[0], interpolation_z[4], interpolation_z[8], interpolation_z[12]);
key.RotInterBezier.initialize(interpolation_rot[0], interpolation_rot[4], interpolation_rot[8], interpolation_rot[12]);
}
//------------------------------------------------------------------------------
void VMDBezierAttitudeTransformAnimation::sortKeyFrame()
{
struct
{
bool operator()(const KeyFrame& l, const KeyFrame& r) const
{
return l.Time < r.Time;
}
} compare;
std::stable_sort(m_keyFrameList.begin(), m_keyFrameList.end(), compare);
//std::sort(m_keyFrameList.begin(), m_keyFrameList.end(), compare);
}
//------------------------------------------------------------------------------
void VMDBezierAttitudeTransformAnimation::updateValue(double time)
{
// フレーム数 1 個
if (m_keyFrameList.getCount() == 1)
{
m_transform.rotation = m_keyFrameList.getFront().Rotation;
m_transform.translation = m_keyFrameList.getFront().Position;
return;
}
// 最初のフレーム以前であれば最初のフレームの値を返す
if (time <= m_keyFrameList.getFront().Time)
{
m_transform.rotation = m_keyFrameList.getFront().Rotation;
m_transform.translation = m_keyFrameList.getFront().Position;
return;
}
// 最後のフレーム以降であれば最後のフレームの値を返す
if (time >= m_keyFrameList.getLast().Time)
{
m_transform.rotation = m_keyFrameList.getLast().Rotation;
m_transform.translation = m_keyFrameList.getLast().Position;
return;
}
// あるフレーム位置直前のキーフレームを検索するための関数オブジェクト
struct GreaterEqual
{
double FramePos;
bool operator()(const KeyFrame& key) const
{
return FramePos <= key.Time;
}
} compare;
compare.FramePos = time;
// キー検索
KeyFrameList::iterator itr = std::find_if(m_keyFrameList.begin(), m_keyFrameList.end(), compare);
size_t k1idx = itr - m_keyFrameList.begin();
size_t k0idx = k1idx - 1;
KeyFrame& k0 = m_keyFrameList[k0idx];
KeyFrame& k1 = m_keyFrameList[k1idx];
double t0 = k0.Time;
double t1 = k1.Time;
// float ⇔ double の型変換を抑えるため、以下は float で計算を行う
float rate = static_cast< float >((time - t0) / (t1 - t0));
float inter;
inter = k1.PosXInterBezier.getInterValue(rate);
m_transform.translation.x = k0.Position.x * (1.0f - inter) + k1.Position.x * inter;
inter = k1.PosYInterBezier.getInterValue(rate);
m_transform.translation.y = k0.Position.y * (1.0f - inter) + k1.Position.y * inter;
inter = k1.PosZInterBezier.getInterValue(rate);
m_transform.translation.z = k0.Position.z * (1.0f - inter) + k1.Position.z * inter;
inter = k1.RotInterBezier.getInterValue(rate);
m_transform.rotation = Quaternion::slerp(k0.Rotation, k1.Rotation, inter);
}
//------------------------------------------------------------------------------
double VMDBezierAttitudeTransformAnimation::getLastFrameTime() const
{
if (m_keyFrameList.isEmpty()) return 0;
return m_keyFrameList.getLast().Time;
}
//==============================================================================
// VMDBezierAttitudeTransformAnimation
//==============================================================================
VMDBezierSQTTransformAnimation2::VMDBezierSQTTransformAnimation2()
{
}
VMDBezierSQTTransformAnimation2::~VMDBezierSQTTransformAnimation2()
{
}
void VMDBezierSQTTransformAnimation2::sortKeyFrame()
{
struct
{
bool operator()(const BoneFrameData& l, const BoneFrameData& r) const
{
return l.Time < r.Time;
}
} compare;
//std::stable_sort(m_keyFrameList.begin(), m_keyFrameList.end(), compare);
std::sort(m_keyFrameList.begin(), m_keyFrameList.end(), compare);
}
void VMDBezierSQTTransformAnimation2::updateValue(double time)
{
// フレーム数 1 個
if (m_keyFrameList.getCount() == 1)
{
m_transform.rotation = m_keyFrameList.getFront().Rotation;
m_transform.translation = m_keyFrameList.getFront().Position;
return;
}
// 最初のフレーム以前であれば最初のフレームの値を返す
if (time <= m_keyFrameList.getFront().Time)
{
m_transform.rotation = m_keyFrameList.getFront().Rotation;
m_transform.translation = m_keyFrameList.getFront().Position;
return;
}
// 最後のフレーム以降であれば最後のフレームの値を返す
if (time >= m_keyFrameList.getLast().Time)
{
m_transform.rotation = m_keyFrameList.getLast().Rotation;
m_transform.translation = m_keyFrameList.getLast().Position;
return;
}
// あるフレーム位置直前のキーフレームを検索するための関数オブジェクト
struct GreaterEqual
{
double FramePos;
bool operator()(const BoneFrameData& key) const
{
return FramePos <= key.Time;
}
} compare;
compare.FramePos = time;
// キー検索
KeyFrameList::iterator itr = std::find_if(m_keyFrameList.begin(), m_keyFrameList.end(), compare);
size_t k1idx = itr - m_keyFrameList.begin();
size_t k0idx = k1idx - 1;
BoneFrameData& k0 = m_keyFrameList[k0idx];
BoneFrameData& k1 = m_keyFrameList[k1idx];
// 現在のフレームの前後キーフレーム間での進行度を求めてペジェ関数で変換する
float s = (k1.Time == k0.Time) ? 0 :
(float)(time - k0.Time) / (float)(k1.Time - k0.Time); // 進行度
float ss[4];
for (int i = 0; i < 4; ++i) ss[i] = k0.Curves[i].evaluate(s);
// ボーンを更新する
Vector3 progress(ss[0], ss[1], ss[2]);
m_transform.translation =
Vector3(Math::lerp(k0.Position.x, k1.Position.x, progress.x),
Math::lerp(k0.Position.y, k1.Position.y, progress.y),
Math::lerp(k0.Position.z, k1.Position.z, progress.z));
m_transform.rotation =
Quaternion::slerp(k0.Rotation, k1.Rotation, ss[3]);
//CGHelper.ComplementRotateQuaternion(k0, k1, ss[3]);
}
//------------------------------------------------------------------------------
double VMDBezierSQTTransformAnimation2::getLastFrameTime() const
{
if (m_keyFrameList.isEmpty()) return 0;
return m_keyFrameList.getLast().Time;
}
LN_NAMESPACE_END
| [
"[email protected]"
]
| |
d2965ad71440e2fea24607458ad37394378ca24e | b1aef802c0561f2a730ac3125c55325d9c480e45 | /src/test/csf/timers.h | ba699647e339329372d0e7d06ba0ca28483b1c6e | []
| no_license | sgy-official/sgy | d3f388cefed7cf20513c14a2a333c839aa0d66c6 | 8c5c356c81b24180d8763d3bbc0763f1046871ac | refs/heads/master | 2021-05-19T07:08:54.121998 | 2020-03-31T11:08:16 | 2020-03-31T11:08:16 | 251,577,856 | 6 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,434 | h |
#ifndef RIPPLE_TEST_CSF_TIMERS_H_INCLUDED
#define RIPPLE_TEST_CSF_TIMERS_H_INCLUDED
#include <chrono>
#include <ostream>
#include <test/csf/Scheduler.h>
#include <test/csf/SimTime.h>
namespace ripple {
namespace test {
namespace csf {
class HeartbeatTimer
{
Scheduler & scheduler_;
SimDuration interval_;
std::ostream & out_;
RealTime startRealTime_;
SimTime startSimTime_;
public:
HeartbeatTimer(
Scheduler& sched,
SimDuration interval = std::chrono::seconds {60},
std::ostream& out = std::cerr)
: scheduler_{sched}, interval_{interval}, out_{out},
startRealTime_{RealClock::now()},
startSimTime_{sched.now()}
{
}
void
start()
{
scheduler_.in(interval_, [this](){beat(scheduler_.now());});
}
void
beat(SimTime when)
{
using namespace std::chrono;
RealTime realTime = RealClock::now();
SimTime simTime = when;
RealDuration realDuration = realTime - startRealTime_;
SimDuration simDuration = simTime - startSimTime_;
out_ << "Heartbeat. Time Elapsed: {sim: "
<< duration_cast<seconds>(simDuration).count()
<< "s | real: "
<< duration_cast<seconds>(realDuration).count()
<< "s}\n" << std::flush;
scheduler_.in(interval_, [this](){beat(scheduler_.now());});
}
};
}
}
}
#endif
| [
"[email protected]"
]
| |
e76efa86a34f9a5c71ee2c294d6c4098a5b8554d | 7d1a96565a1b46eaa38770bc592f0f508ba659b3 | /OpencupGrandPrixOfKazan/I_normal.cpp | ec5cc42ace2f47d15b89b0c91d67058302805ea3 | []
| no_license | RubenAshughyan/Programming-olympiads | f09dff286677d65da19f0ba4c288aa6e97ba9fd5 | 2bc85f5e6dc6879105353d90e8417b73c0be2389 | refs/heads/master | 2021-09-26T17:18:47.100625 | 2021-09-13T09:58:41 | 2021-09-13T09:58:41 | 73,565,659 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,783 | cpp | #pragma GCC optimize "-O1"
#pragma GCC optimize "-O2"
#pragma GCC optimize "-O3"
#include<bits/stdc++.h>
//#include "rubo.h"
#define MP make_pair
#define PB push_back
#define in int
#define ll long long
#define ull unsigned long long
#define vc vector
#define SQ(j) (j)*(j)
//#define i first
//#define j second
//#define ld long double
#define dbl double
#define pll pair<long long,long long>
#define pii pair<int,int>
#define all(j) j.begin(), j.end()
#define loop(xxx, yyy) for(int xxx = 0; xxx < yyy; xxx++)
//#define printf(fmt, ...) (0)
//#define HOME
//#define y0 ngacaleiebinvoaeu
//#define y1 gnarpipipaigare
#define j1 adsfndnasfafoasp
//#define printf(...) (0)
const int DEBUG = 0;
#define db(x) if(DEBUG){cout << #x << " = " << x << endl;}
#define dbCont(x) if(DEBUG){cout << #x << ": "; for(auto shun: x) cout << shun << ' '; cout<<endl;}
using namespace std;
const int N = 200* 1000 + 5;
set<int> g[N];
int n;
int par[N];
int sz[N];
set<int> candidates;
void dfsSizes(int v, int p){
candidates.insert(v);
par[v] = p;
sz[v] = 1;
for(int to : g[v]){
if(to != par[v]){
dfsSizes(to, v);
sz[v] += sz[to];
}
}
}
int ASK = 0;
bool ask(vc<int> vs, int x) {
ASK++;
// if (ASK > 4 * ceil(log2(n))) {
// assert(false);
// }
cout << "? " << vs.size() << " " << x+1;
for (int e: vs) cout << " " << e+1;
cout << endl;
fflush(stdout);
int res;
cin >> res;
return res == 1;
}
int findX(int root){
vc<pii> diffAndVertex;
for(int v : candidates){
int diff = abs(sz[v] * 2 - (int)candidates.size());
diffAndVertex.push_back({diff, v});
}
return min_element(all(diffAndVertex))->second;
}
void say(int a){
cout << "! " << a+1 << endl;
fflush(stdout);
exit(0);
}
vc<int> subVector(vc<int> &v, int l, int r) {
vc<int> res;
for (int i = l; i <= r; i++) {
res.push_back(v[i]);
}
return res;
}
int main(){
cin >> n;
loop(i,n-1){
int u,v;
cin >> u >> v;
u--,v--;
g[u].insert(v);
g[v].insert(u);
}
int root = 0;
dfsSizes(root,-1);
while(candidates.size() > 2){
db(root+1);
int x = findX(root);
// kaxeci
root = x;
dfsSizes(root, -1);
vc<int> children(all(g[x]));
auto it = find(all(children), par[root]);
if (it != children.end()) children.erase(it);
bool isXCloser = ask(children, x);
if (isXCloser){
say(x);
}
int l = 0, r = children.size() - 1, mid;
while (l < r) {
mid = (l + r) / 2;
vc<int> left_part = subVector(children, l, mid);
vc<int> right_part = subVector(children, mid + 1, r);
if (ask(left_part, x)) {
// for (int i = 0; i < left_part.size(); ++i) {
// g[x].erase(left_part[i]);
// }
l = mid + 1;
} else {
// for (int i = 0; i < right_part.size(); ++i) {
// g[x].erase(right_part[i]);
// }
r = mid;
}
}
assert(l == r);
int child_containing = children[l];
candidates.clear();
g[child_containing].erase(x);
root = child_containing;
dfsSizes(root, -1);
}
if (candidates.size() == 1) {
say(*candidates.begin());
} else {
vc<int> vectorCandidates(all(candidates));
if (ask(subVector(vectorCandidates, 0, 0), vectorCandidates[1])) {
say (vectorCandidates[1]);
} else {
say(vectorCandidates[0]);
}
}
return 0;
}
/*
5
1 2
1 3
1 4
1 5
7
1 2
2 3
3 4
4 5
3 6
6 7
*/ | [
"[email protected]"
]
| |
094cdff386ec580d73ddc91cfa55f7a5457e84bb | 35596c34d80d1378091090e6183cb0e1c27fdc4d | /src/pcl_tutorial/src/linemod/linemod_train.cpp | f6051919f3bf2420b0e21570797a81343632510e | []
| no_license | YeeKal/grasp_ws | bdb22a04a52919621fd69d15a5ba274322f61102 | 7e40ddb871c4975f39f677ada035aac56d79e511 | refs/heads/master | 2020-09-02T04:12:41.745818 | 2019-12-31T05:26:35 | 2019-12-31T05:26:35 | 219,128,067 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,377 | cpp | #include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/recognition/linemod.h>
#include <pcl/recognition/color_gradient_modality.h>
#include <pcl/recognition/surface_normal_modality.h>
#include <boost/range/irange.hpp>
#include <boost/range/counting_range.hpp>
#include <boost/smart_ptr/make_shared.hpp>
// Typedefs
using PointType = pcl::PointXYZRGBA;
using Cloud = pcl::PointCloud <PointType>;
//const auto& range = boost::irange;
namespace fs = boost::filesystem;
// User defined literals
// @formatter:off
constexpr size_t operator "" _sz (unsigned long long size) { return size_t{size}; }
constexpr double operator "" _deg (long double deg) { return deg * M_PI / 180.0; }
constexpr double operator "" _deg (unsigned long long deg) { return deg * M_PI / 180.0; }
constexpr double operator "" _cm (long double cm) { return cm / 100.0; }
constexpr double operator "" _cm (unsigned long long cm) { return cm / 100.0; }
constexpr double operator "" _mm (long double mm) { return mm / 1000.0; }
constexpr double operator "" _mm (unsigned long long mm) { return mm / 1000.0; }
// @formatter:on
// Constants
constexpr auto MIN_VALID_ARGS = 3U;
constexpr auto MAX_VALID_ARGS = 9U;
//constexpr auto NUM_PCD_FILES_EXPECTED = 2U;
//constexpr auto NUM_PCD_DIRS_EXPECTED = 2U;
constexpr auto INPUT_DIR_ARG_POS = 1U;
//constexpr auto OUTPUT_DIR_ARG_POS = 2U;
//constexpr auto DEFAULT_MIN_CLUSTER_SIZE = 100U;
//constexpr auto DEFAULT_MAX_CLUSTER_SIZE = 25000U;
//constexpr auto DEFAULT_TOLERANCE = 2_cm;
//constexpr auto DEFAULT_MAX_NUM_CLUSTERS = 20U;
template <typename T>
constexpr auto izrange (T upper)
-> decltype (auto) {
return boost::irange (static_cast <T> (0), upper);
}
void printHelp (int argc, char ** argv) {
using pcl::console::print_error;
using pcl::console::print_info;
// TODO: Update this help
print_error ("Syntax is: %s (<path-to-pcd-files> <path-to-output_lmt_file>) <options> | "
"-h | --help\n", argv[0]);
print_info ("%s -h | --help : shows this help\n", argv[0]);
// print_info ("-min X : use a minimum of X points per cluster (default: 100)\n");
// print_info ("-max X : use a maximum of X points per cluster (default: 25000)\n");
// print_info ("-tol X : the spatial distance (in meters) between clusters (default: 0.002.\n");
}
fs::path expandTilde (std::string path_string) -> {
if (path_string.at (0) == '~')
path_string.replace (0, 1, getenv ("HOME"));
return fs::path{path_string};
}
std::vector <fs::path> getPcdFilesInPath (fs::path const & pcd_dir){
std::vector <fs::path> result_set = std::vector <fs::path>{};
for (std::vector <fs::path> const & entry : boost::make_iterator_range (fs::directory_iterator{pcd_dir})) {
if (fs::is_regular_file (entry.status ())) {
if (entry.path ().extension () == ".pcd") {
result_set.emplace_back (entry);
}
}
}
return result_set;
}
bool checkValidOutputFile (fs::path const & filepath){
// Check that the file is valid
auto parent_path = filepath.parent_path ();
return fs::exists (parent_path) && fs::is_directory (parent_path);
}
constexpr bool checkValidPoint (PointType const & point){
return (pcl_isfinite (point.x) && pcl_isfinite (point.y) && pcl_isfinite (point.z));
}
/**
* This assumes that the (organised) cloud only contains foreground points.
*
* returns a vector of bools representing the valid points in the cloud
* or an empty vector if the cloud is not organised
*/
std::vector <bool> getForegroundMask (Cloud::ConstPtr const & cloud){
if (!cloud->isOrganized ())
return std::vector <bool>{};
std::vector <bool> mask = std::vector <bool> (cloud->size (), false);
auto index = 0_sz;
for (auto const & point : cloud->points) {
if (checkValidPoint (point))
mask.at (index) = true;
++index;
}
return mask;
}
void trainAndAddTemplate (Cloud::ConstPtr const & input,
std::vector <bool> const & foreground_mask,
pcl::LINEMOD & linemod) {
auto color_grad_mod = pcl::ColorGradientModality <PointType> {};
color_grad_mod.setInputCloud (input);
color_grad_mod.processInputData ();
auto surface_norm_mod = pcl::SurfaceNormalModality <pcl::PointXYZRGBA> {};
surface_norm_mod.setInputCloud (input);
surface_norm_mod.processInputData ();
auto modalities = std::vector <pcl::QuantizableModality *> (2);
modalities[0] = &color_grad_mod;
modalities[1] = &surface_norm_mod;
auto min_x = input->width;
auto min_y = input->height;
auto max_x = decltype (min_x) {0};
auto max_y = decltype (min_y) {0};
auto mask_map = pcl::MaskMap {input->width, input->height};
for (auto const j : izrange (input->height)) {
for (auto const i : izrange (input->width)) {
auto const & mask_el = foreground_mask[j * input->width + i];
mask_map (i, j) = static_cast <unsigned char> (mask_el);
if (mask_el) {
min_x = std::min (min_x, i);
max_x = std::max (max_x, i);
min_y = std::min (min_y, j);
max_y = std::max (max_y, j);
}
}
}
auto masks = std::vector <pcl::MaskMap *> (2);
masks[0] = &mask_map;
masks[1] = &mask_map;
auto region = pcl::RegionXY {};
region.x = static_cast<int> (min_x);
region.y = static_cast<int> (min_y);
region.width = static_cast<int> (max_x - min_x + 1);
region.height = static_cast<int> (max_y - min_y + 1);
auto ss = std::stringstream {};
ss << "Object region: (" << region.x << ", " << region.y << ", " <<
region.x + region.width << ", " << region.y + region.height << ") "<< std::endl;
std::cout << ss.str ();
linemod.createAndAddTemplate (modalities, masks, region);
}
pcl::LINEMOD getTemplates (std::vector <fs::path> & pcd_files){
auto linemod = pcl::LINEMOD {};
for (auto const & pcd_file : pcd_files) {
auto const input_cloud = boost::make_shared <Cloud> ();
if (pcl::io::loadPCDFile <pcl::PointXYZRGBA> (pcd_file.c_str (), *input_cloud) == -1) {
pcl::console::print_error ("Failed to load: %s\n", pcd_file);
continue;
}
auto const & foreground_mask = getForegroundMask (input_cloud);
if (foreground_mask.size () == 0) {
pcl::console::print_error ("No foreground points found: %s\n", pcd_file);
continue;
}
trainAndAddTemplate (input_cloud, foreground_mask, linemod);
}
return linemod;
}
auto saveTemplates (pcl::LINEMOD const & linemod, fs::path const & output_lmt_file) {
linemod.saveTemplates (output_lmt_file.c_str ());
}
int main (int argc, char * argv[]){
pcl::console::print_highlight ("Tool to extract the largest cluster found in a point cloud.\n");
auto help_flag_1 = pcl::console::find_switch (argc, argv, "-h");
auto help_flag_2 = pcl::console::find_switch (argc, argv, "--help");
if (help_flag_1 || help_flag_2) {
printHelp (argc, argv);
return -1;
}
if (argc > MAX_VALID_ARGS || argc < MIN_VALID_ARGS) {
pcl::console::print_error ("Invalid number of arguments.\n");
printHelp (argc, argv);
return -1;
}
// Check if we are working with individual files
auto const lmt_arg_indices = pcl::console::parse_file_extension_argument (argc, argv, ".lmt");
if (lmt_arg_indices.size () != 1) {
pcl::console::print_error ("Invalid number of arguments.\n");
printHelp (argc, argv);
return -1;
}
auto lmt_file = fs::path {argv[lmt_arg_indices.at (0)]};
if (!checkValidOutputFile (lmt_file)) {
pcl::console::print_error ("A valid output file was not specified.\n");
printHelp (argc, argv);
return -1;
}
auto const input_dir = expandTilde (std::string {argv[INPUT_DIR_ARG_POS]});
if (!fs::exists (input_dir) || !fs::is_directory (input_dir)) {
pcl::console::print_error ("A valid input directory was not specified.\n");
printHelp (argc, argv);
return -1;
}
auto input_files = getPcdFilesInPath (input_dir);
auto templates = getTemplates (input_files);
saveTemplates (templates, lmt_file);
templates.loadTemplates (lmt_file.c_str ());
std::cout << templates.getNumOfTemplates ();
return (0);
}
| [
"[email protected]"
]
| |
c74227075308c70005024391ff1fd1afd72b59b3 | b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1 | /tensorflow/compiler/xla/service/gpu/kernel_thunk.cc | 969fb7976360f83d40dd23c5347a7559718ba540 | [
"Apache-2.0"
]
| permissive | uve/tensorflow | e48cb29f39ed24ee27e81afd1687960682e1fbef | e08079463bf43e5963acc41da1f57e95603f8080 | refs/heads/master | 2020-11-29T11:30:40.391232 | 2020-01-11T13:43:10 | 2020-01-11T13:43:10 | 230,088,347 | 0 | 0 | Apache-2.0 | 2019-12-25T10:49:15 | 2019-12-25T10:49:14 | null | UTF-8 | C++ | false | false | 4,113 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/kernel_thunk.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_executable.h"
#include "tensorflow/compiler/xla/service/gpu/hlo_execution_profiler.h"
#include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stream_executor_no_cuda.h"
#include "tensorflow/stream_executor/device_memory.h"
#include "tensorflow/stream_executor/kernel.h"
namespace xla {
namespace gpu {
KernelThunk::KernelThunk(absl::Span<const BufferAllocation* const> args,
const string& kernel_name,
const HloInstruction* hlo_instruction,
int unroll_factor)
: Thunk(Kind::kKernel, hlo_instruction),
args_(args.begin(), args.end()),
kernel_name_(kernel_name),
unroll_factor_(unroll_factor) {}
Status KernelThunk::Initialize(const GpuExecutable& executable,
se::StreamExecutor* executor) {
tensorflow::mutex_lock lock(mutex_);
// Load the kernel into the device if necessary.
//
// We could alternatively do this within ExecuteOnStream, but doing it here
// lets the time spent loading the kernel not count towards our execution
// profiles.
auto it = kernel_cache_.find(executor);
if (kernel_cache_.end() == it) {
TF_ASSIGN_OR_RETURN(
std::unique_ptr<se::KernelBase> kernel,
CreateKernel(kernel_name_, args_.size(), executable.text(),
executable.binary(), executor));
kernel_cache_.emplace(executor, std::move(kernel));
}
return Status::OK();
}
void KernelThunk::SetLaunchDimensions(const LaunchDimensions& launch_dims) {
tensorflow::mutex_lock lock(mutex_);
launch_dimensions_ = launch_dims;
}
Status KernelThunk::ExecuteOnStream(const ExecuteParams& params) {
// Load the kernel.
se::StreamExecutor* executor = params.stream->parent();
LaunchDimensions launch_dimensions;
const se::KernelBase* kernel = nullptr;
{
tensorflow::mutex_lock lock(mutex_);
auto it = kernel_cache_.find(executor);
CHECK(it != kernel_cache_.end())
<< "Initialize() not called for StreamExecutor " << executor;
launch_dimensions = launch_dimensions_;
kernel = it->second.get();
}
VLOG(3) << "Launching " << kernel->name();
absl::InlinedVector<se::DeviceMemoryBase, 4> buffer_args;
for (const BufferAllocation* arg : args_) {
se::DeviceMemoryBase buf =
params.buffer_allocations->GetDeviceAddress(arg->index());
VLOG(3) << " Arg: alloc #" << arg->index() << ": " << buf.opaque() << " ("
<< buf.size() << "B)";
buffer_args.push_back(buf);
}
auto op_profiler =
params.profiler->MakeScopedInstructionProfiler(hlo_instruction());
return ExecuteKernelOnStream(*kernel, buffer_args,
launch_dimensions.threads_per_block(),
launch_dimensions.block_count(), params.stream);
}
} // namespace gpu
} // namespace xla
| [
"[email protected]"
]
| |
99217aaab110ed9e0f0c4b460771e2a09c993f37 | 8ac3e61c78b617269800376e9bfa3e729a40f1ce | /Class_code/Class_5/drum_machine_2/drum_machine_2.ino | 0d4cd6227c63cd255aaf7b45d4324fbc5d3ee6f1 | []
| no_license | BleepLabs/dadageek-April-21 | 4d2451b844ee6c12bd4476bf0a1c6323e9900ad5 | 82a6d175f9eb3e62b086e7029bd9a78730102cac | refs/heads/main | 2023-05-23T00:07:38.292565 | 2021-06-08T16:55:31 | 2021-06-08T16:55:31 | 358,999,605 | 10 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,167 | ino | /*
Use arrays to play a beat with the drum and noise objects
Random chance is added
*/
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
// GUItool: begin automatically generated code
AudioSynthSimpleDrum drum1; //xy=151,187
AudioSynthSimpleDrum drum2; //xy=166,235
AudioSynthNoiseWhite noise1; //xy=170,294
AudioEffectEnvelope envelope1; //xy=340,291
AudioMixer4 mixer1; //xy=443,217
AudioOutputI2S i2s1; //xy=619,210
AudioConnection patchCord1(drum1, 0, mixer1, 0);
AudioConnection patchCord2(drum2, 0, mixer1, 1);
AudioConnection patchCord3(noise1, envelope1);
AudioConnection patchCord4(envelope1, 0, mixer1, 2);
AudioConnection patchCord5(mixer1, 0, i2s1, 0);
AudioConnection patchCord6(mixer1, 0, i2s1, 1);
AudioControlSGTL5000 sgtl5000_1; //xy=408,113
// GUItool: end automatically generated code
#include <Bounce2.h>
#define NUM_BUTTONS 8
const int BUTTON_PINS[NUM_BUTTONS] = {30, 31, 32, 33, 34, 35, 36, 37};
Bounce * buttons = new Bounce[NUM_BUTTONS];
#define BOUNCE_LOCK_OUT
//then you can declare any variables you want.
unsigned long current_time;
unsigned long prev_time[8]; //an array of 8 variables all named "prev_time"
//starts at midi note 12, C0
PROGMEM const static float chromatic[121] = {16.3516, 17.32391673, 18.35405043, 19.44543906, 20.60172504, 21.82676736, 23.12465449, 24.499718, 25.95654704, 27.50000365, 29.13523896, 30.86771042, 32.7032, 34.64783346, 36.70810085, 38.89087812, 41.20345007, 43.65353471, 46.24930897, 48.99943599, 51.91309407, 55.00000728, 58.27047791, 61.73542083, 65.40639999, 69.29566692, 73.4162017, 77.78175623, 82.40690014, 87.30706942, 92.49861792, 97.99887197, 103.8261881, 110.0000146, 116.5409558, 123.4708417, 130.8128, 138.5913338, 146.8324034, 155.5635124, 164.8138003, 174.6141388, 184.9972358, 195.9977439, 207.6523763, 220.0000291, 233.0819116, 246.9416833, 261.6255999, 277.1826676, 293.6648067, 311.1270248, 329.6276005, 349.2282776, 369.9944716, 391.9954878, 415.3047525, 440.0000581, 466.1638231, 493.8833665, 523.2511997, 554.3653352, 587.3296134, 622.2540496, 659.2552009, 698.4565551, 739.9889431, 783.9909755, 830.6095048, 880.0001162, 932.3276461, 987.7667329, 1046.502399, 1108.73067, 1174.659227, 1244.508099, 1318.510402, 1396.91311, 1479.977886, 1567.981951, 1661.219009, 1760.000232, 1864.655292, 1975.533466, 2093.004798, 2217.46134, 2349.318453, 2489.016198, 2637.020803, 2793.82622, 2959.955772, 3135.963901, 3322.438019, 3520.000464, 3729.310584, 3951.066931, 4186.009596, 4434.92268, 4698.636906, 4978.032395, 5274.041605, 5587.652439, 5919.911543, 6271.927802, 6644.876037, 7040.000927, 7458.621167, 7902.133861, 8372.019192, 8869.845359, 9397.273811, 9956.06479, 10548.08321, 11175.30488, 11839.82309, 12543.8556, 13289.75207, 14080.00185, 14917.24233, 15804.26772, 16744.03838};
//Three, sixteen step sequencers
int seq[3][16] = {
{1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1},
{2, 0, 2, 3, 4, 8, 0, 0, 2, 6, 2, 2, 5, 0, 10, 10},
{0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0},
};
//the first loop there might be some odd things happening due to some bust w the 4.1 and audio library
int melody_location;
unsigned long noise_timer;
int noise_latch;
int melody_speed;
int hat_length;
void setup() {
//there's a lot we need to do in setup now but most of it is just copy paste.
// This first group should only be done in setup how much RAM to set aside for the audio library to use.
// The audio library uses blocks of a set size so this is not a percentage or kilobytes, just a kind of arbitrary number.
// On our Teensy 4.1 we can go up to almost 2000 but that won't leave any RAM for anyone else.
// It's usually the delay and reverb that hog it.
AudioMemory(100);
sgtl5000_1.enable(); //Turn the adapter board on
sgtl5000_1.inputSelect(AUDIO_INPUT_LINEIN); //Tell it what input we want to use. Not necessary is you're not using the ins
sgtl5000_1.lineInLevel(10); //The volume of the input. 0-15 with 15 bing more amplifications
//sgtl5000_1.inputSelect(AUDIO_INPUT_MIC);
//sgtl5000_1.micGain(13); //0 - 63db of gain.
//headphone jack output volume. Goes from 0.0 to 1.0 but a 100% signal will clip over .8 or so.
// For headphones it's pretty loud at .4
// There are lots of places we can change the final volume level.
// For now lets set this one once and leave it alone.
sgtl5000_1.volume(0.25);
//The line out has a separate level control but it's not meant to be adjusted like the volume function above.
// If you're not using the line out don't worry about it.
sgtl5000_1.lineOutLevel(21); //11-32, the smaller the louder. 21 is about 2 Volts peak to peak
mixer1.gain(0, 0); //kick
mixer1.gain(1, 0); //pew
mixer1.gain(2, .2); //noise
drum1.frequency(80); //starting freq
drum1.length(75);//how long to fade out
drum1.pitchMod(.55); //less than .5 the pitch will rise, great and it will drop
drum2.frequency(880); //starting freq
drum2.length(200);//how long to fade out
drum2.pitchMod(.75); //less than .5 the pitch will rise, great and it will drop
envelope1.attack(1);
envelope1.decay(0);
envelope1.sustain(1);
envelope1.release(4);
noise1.amplitude(1);
analogReadAveraging(64); //take lots of readings and average them each time we do analogRead. This is one stage of smoothing
for (int i = 0; i < NUM_BUTTONS; i++) {
buttons[i].attach( BUTTON_PINS[i] , INPUT_PULLUP ); //setup the bounce instance for the current button
buttons[i].interval(10); // interval in ms
}
} //setup is over
void loop() {
current_time = millis();
//melody_speed = 1000;
melody_speed = (analogRead(A10) / 1023.0) * 500; //0-500
if (current_time - prev_time[2] > melody_speed) { //step through the sequence which hold our melody
prev_time[2] = current_time;
melody_location++; //same as saying melody_location = melody_location + 1
if (melody_location > 15) {
melody_location = 0;
}
int temp0 = seq[0][melody_location];
if (temp0 > 0) {
drum1.noteOn(); //Unlike the envelope a drum will just play for a certain amount of time
}
int temp1 = seq[1][melody_location];
if (temp1 > 0) {
hat_length = temp1 * (analogRead(A12) / 1023.0) * 10.0; //use the reading in the array and the pot to change how long the note is on
//hat_length = random(2, 10);
float rn1 = ((random(100) / 100.0) * .5) + .5;
noise1.amplitude(rn1);
envelope1.noteOn();
noise_timer = current_time; //remember the time so we can tune the envelope off at a set time
noise_latch = 1;
}
int temp2 = seq[2][melody_location];
if (temp2 > 0) {
int r1 = random(24); //0-23
drum2.frequency(chromatic[60 + r1]); //use chromatic for the frequency
int r2 = random(100, 500);
drum2.length(r2);
drum2.noteOn(); //Unlike the envelope a drum will just play for a certain amount of time
}
Serial.println(melody_location);
}
// int hat_length = (analogRead(A11) / 1023.0) * 100.0;
if (current_time - noise_timer > hat_length && noise_latch == 1) {
envelope1.noteOff();
noise_latch = 0; //so it won't keep happening every loop
}
if (current_time - prev_time[0] > 500 && 0) { //change "&& 0" to "&& 1" to print this
prev_time[0] = current_time;
//Here we print out the usage of the audio library
// If we go over 90% processor usage or get near the value of memory blocks we set aside in the setup we'll have issues or crash.
// If you're using too many block, jut increase the number up top until you're over it by a couple
Serial.print("processor: ");
Serial.print(AudioProcessorUsageMax());
Serial.print("% Memory: ");
Serial.print(AudioMemoryUsageMax());
Serial.println();
AudioProcessorUsageMaxReset(); //We need to reset these values so we get a real idea of what the audio code is doing rather than just peaking in every half a second
AudioMemoryUsageMaxReset();
}
}// loop is over
| [
"[email protected]"
]
| |
3da1b2f47f7bc957a9cee325bfb8445b336df9e3 | 346e7f4aa65d89e3ca1e4b6210e1a68eb99bab5d | /Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h | ff405a89b0a0e786b2fff080a7e93c54e5eebbea | [
"Apache-2.0"
]
| permissive | raptoravis/DiligentCore | cd74be889968cfebab635fcc07d382c22f9065a5 | a2ee49069659eb650b912463a8e380c1c49a0605 | refs/heads/master | 2020-08-12T19:30:35.599793 | 2019-11-02T04:04:54 | 2019-11-02T04:04:54 | 214,829,391 | 0 | 0 | Apache-2.0 | 2019-10-13T13:55:22 | 2019-10-13T13:55:22 | null | UTF-8 | C++ | false | false | 2,421 | h | /* Copyright 2019 Diligent Graphics LLC
*
* 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
*
* 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 OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
/// \file
/// Declaration of Diligent::TextureViewD3D11Impl class
#include "TextureViewD3D11.h"
#include "RenderDeviceD3D11.h"
#include "TextureViewBase.h"
#include "RenderDeviceD3D11Impl.h"
namespace Diligent
{
class FixedBlockMemoryAllocator;
/// Implementation of the Diligent::ITextureViewD3D11 interface
class TextureViewD3D11Impl final : public TextureViewBase<ITextureViewD3D11, RenderDeviceD3D11Impl>
{
public:
using TTextureViewBase = TextureViewBase<ITextureViewD3D11, RenderDeviceD3D11Impl>;
TextureViewD3D11Impl( IReferenceCounters* pRefCounters,
RenderDeviceD3D11Impl* pDevice,
const TextureViewDesc& ViewDesc,
class ITexture* pTexture,
ID3D11View* pD3D11View,
bool bIsDefaultView);
virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override final;
virtual ID3D11View* GetD3D11View()override final
{
return m_pD3D11View;
}
protected:
/// D3D11 view
CComPtr<ID3D11View> m_pD3D11View;
};
}
| [
"[email protected]"
]
| |
80192a93307d10fd25ece7353e922eb004cecbd7 | 7ec52f1eeb83bbc27f1674af805948858b2bd9a7 | /Keyframe.cpp | d4df7b6bec03219da07107e192c48a8f65ea1ebc | []
| no_license | amirbaghi/skeletal-animation-opengl | c1b4000e14baa804b86a3cf1d7565d4f48a4fa6c | bc53e9014d67159b6a9149c7844ce97041782dfe | refs/heads/main | 2023-05-28T02:22:19.070958 | 2021-06-13T09:31:35 | 2021-06-13T09:31:35 | 375,739,287 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 359 | cpp | #include "./Headers/Keyframe.h"
void Keyframe::addOrientation(std::string boneName, glm::quat orientation)
{
this->orientations[boneName] = orientation;
}
glm::quat Keyframe::getOrientation(std::string boneName)
{
return this->orientations[boneName];
}
std::map<std::string, glm::quat> Keyframe::getOrientations()
{
return this->orientations;
} | [
"[email protected]"
]
| |
58d18123462347223f8a6558389f4a0f49735749 | 75119b12a8d15ad7f700ac9db302dc557777ea81 | /src/myo_ros_windows.cpp | 98521d85a21ad9ee1a4341800d028ee556f045b8 | [
"BSD-2-Clause"
]
| permissive | jossichrist/myo_ros_windows | 267901f5a08ff6059d90aec7407e8dee88a02d79 | 508dc03f9d2798bc1eaf95e5d1555d038dd52319 | refs/heads/master | 2020-03-07T13:39:43.832445 | 2015-01-07T15:52:18 | 2015-01-07T15:52:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,041 | cpp | // Copyright (C) 2013-2014 Thalmic Labs Inc.
// Confidential and not for redistribution. See LICENSE.txt.
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <string>
// The only file that needs to be included to use the Myo C++ SDK is myo.hpp.
#include <myo/myo.hpp>
// ROS/rosserial includes
#include "ros.h"
#include <geometry_msgs/Vector3.h>
#include <geometry_msgs/Quaternion.h>
#include <myo_ros/Gesture.h>
#include <myo_ros/Vibration.h>
#include <myo_ros/Status.h>
#include <std_msgs/Bool.h>
// Static classes that handle callbacks + Myo instance
// This is a limitation of rosserial + Windows. In uCs, this doesn't matter, and in Linux, we use boost::bind
myo::Myo* my_myo = NULL;
// Creates vibrations
void vibrationCallback(const myo_ros::Vibration& vibration) {
if (my_myo) {
my_myo->vibrate(static_cast<myo::Myo::VibrationType>(vibration.vibration));
}
}
// Sets the unlock timing
void unlockCallback(const std_msgs::Bool& unlock) {
if (my_myo) {
if (unlock.data == true)
{
my_myo->unlock(myo::Myo::unlockHold);
}
else
{
my_myo->unlock(myo::Myo::unlockTimed);
}
}
}
// Classes that inherit from myo::DeviceListener can be used to receive events from Myo devices. DeviceListener
// provides several virtual functions for handling different kinds of events. If you do not override an event, the
// default behavior is to do nothing.
class DataCollector : public myo::DeviceListener {
public:
// Information that will be going out
geometry_msgs::Quaternion msg_rotation;
myo_ros::Gesture msg_gesture;
myo_ros::Status msg_status;
geometry_msgs::Vector3 msg_gyro;
geometry_msgs::Vector3 msg_accel;
// Various pointers - Pointers because rosserial publishers don't have default constructors yet
ros::Publisher* pub_rotation;
ros::Publisher* pub_gesture;
ros::Publisher* pub_gyro;
ros::Publisher* pub_accel;
ros::Publisher* pub_status;
ros::Subscriber<myo_ros::Vibration>* sub_vibration;
ros::Subscriber<std_msgs::Bool>* sub_unlock_override;
DataCollector(ros::NodeHandle &nh)
{
// Subscribe & publish setup
pub_rotation = new ros::Publisher("rotation", &msg_rotation);
nh.advertise(*pub_rotation);
pub_gesture = new ros::Publisher("gesture", &msg_gesture);
nh.advertise(*pub_gesture);
pub_gyro = new ros::Publisher("gyro", &msg_gyro);
nh.advertise(*pub_gyro);
pub_accel = new ros::Publisher("accel", &msg_accel);
nh.advertise(*pub_accel);
pub_status = new ros::Publisher("status", &msg_status);
nh.advertise(*pub_status);
sub_vibration = new ros::Subscriber<myo_ros::Vibration>("vibration", &vibrationCallback);
nh.subscribe(*sub_vibration);
sub_unlock_override = new ros::Subscriber<std_msgs::Bool>("unlock_override", &unlockCallback);
nh.subscribe(*sub_unlock_override);
}
// onConnect() is called when a paired Myo is connected
void onConnect(myo::Myo* myo, uint64_t timestamp) {
my_myo = myo;
}
// onConnect() is called when a paired Myo is disconnected
void onDisconnect(myo::Myo* myo, uint64_t timestamp) {
my_myo = NULL;
}
// onOrientationData() is called whenever the Myo device provides its current orientation, which is represented
// as a unit quaternion.
void onOrientationData(myo::Myo* myo, uint64_t timestamp, const myo::Quaternion<float>& quat)
{
msg_rotation.w = quat.w();
msg_rotation.x = quat.x();
msg_rotation.y = quat.y();
msg_rotation.z = quat.z();
pub_rotation->publish(&msg_rotation);
}
// onPose() is called whenever the Myo detects that the person wearing it has changed their pose, for example,
// making a fist, or not making a fist anymore.
void onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose)
{
msg_gesture.gesture = pose.type();
pub_gesture->publish(&msg_gesture);
}
// onGyroscopeData() called when a paired Myo has provided new gyroscope data in units of deg/s
void onGyroscopeData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3<float> &gyro) {
msg_gyro.x = gyro.x();
msg_gyro.y = gyro.y();
msg_gyro.z = gyro.z();
pub_gyro->publish(&msg_gyro);
}
// onAccelerometerData() called when a paired Myo has provided new accelerometer data in units of g.
void onAccelerometerData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3< float > &accel) {
msg_accel.x = accel.x();
msg_accel.y = accel.y();
msg_accel.z = accel.z();
pub_accel->publish(&msg_accel);
}
// onArmSync() is called whenever Myo has recognized a Sync Gesture after someone has put it on their
// arm. This lets Myo know which arm it's on and which way it's facing.
void onArmSync(myo::Myo* myo, uint64_t timestamp, myo::Arm arm, myo::XDirection xDirection)
{
msg_status.sync = true;
msg_status.unlock = false;
msg_status.arm = static_cast<int8_t>(arm);
msg_status.direction = static_cast<int8_t>(xDirection);
pub_status->publish(&msg_status);
}
// onArmUnsync() is called whenever Myo has detected that it was moved from a stable position on a person's arm after
// it recognized the arm. Typically this happens when someone takes Myo off of their arm, but it can also happen
// when Myo is moved around on the arm.
void onArmUnsync(myo::Myo* myo, uint64_t timestamp)
{
msg_status.sync = false;
msg_status.unlock = false;
msg_status.arm = static_cast<int8_t>(myo::armUnknown);
msg_status.direction = static_cast<int8_t>(myo::xDirectionUnknown);
pub_status->publish(&msg_status);
}
// onUnlock() is called whenever Myo has become unlocked, and will start delivering pose events.
void onUnlock(myo::Myo* myo, uint64_t timestamp)
{
msg_status.unlock = true;
pub_status->publish(&msg_status);
}
// onLock() is called whenever Myo has become locked. No pose events will be sent until the Myo is unlocked again.
void onLock(myo::Myo* myo, uint64_t timestamp)
{
msg_status.unlock = false;
pub_status->publish(&msg_status);
}
};
int main(int argc, char** argv)
{
// We catch any exceptions that might occur below -- see the catch statement for more details.
try {
// First, we create a Hub. The Hub provides access to one or more Myos.
myo::Hub hub("org.ros.myo_ros_windows");
std::cout << "Attempting to find a Myo..." << std::endl;
// Next, we try to find a Myo (any Myo) that's nearby and connect to it. waitForAnyMyo() takes a timeout
// value in milliseconds. In this case we will try to find a Myo for 10 seconds, and if that fails, the function
// will return a null pointer.
my_myo = hub.waitForMyo(10000);
// If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message.
if (!my_myo) {
throw std::runtime_error("Unable to find a Myo!");
}
// We've found a Myo, let's output its MAC address.
std::cout << "Connected to a Myo." << std::endl << std::endl;
// Now we connect to ROS
ros::NodeHandle nh;
if (argc < 2) {
std::cout << "No server:port argument found, using localhost:11411";
nh.initNode("localhost:11411");
}
else {
nh.initNode(argv[1]);
}
// Next we construct an instance of our DeviceListener, so that we can register it with the Hub.
DataCollector collector (nh);
// Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause
// Hub::run() to send events to all registered device listeners.
hub.addListener(&collector);
// Finally we enter our main loop.
while (1) {
// In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds.
// In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds.
hub.run(1000/20);
// Spin ROS
nh.spinOnce();
}
// If a standard exception occurred, we print out its message and exit.
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Press enter to continue.";
std::cin.ignore();
return 1;
}
}
| [
"[email protected]"
]
| |
3a36536bfabaabb84bd02a02c27451069b886f4f | 3b749f6471e0649d705edcaab722945d59378440 | /drawable.h | f21e7a98c493863fa4b782b1e1645b06024fd967 | []
| no_license | xuanyu233/CS543-F18-HW-Reflection | 350185b8edc5279e36127b3565b39a4b807006ce | bb8a60e21545a03036de0a1b97c370306147bf0e | refs/heads/master | 2020-03-29T15:17:04.042998 | 2018-12-04T22:20:59 | 2018-12-04T22:20:59 | 150,054,512 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 80 | h | #pragma once
class Drawable {
public:
virtual void Render() const = 0;
}; | [
"[email protected]"
]
| |
a2c2f9211ca103dd419a74cfb7b5ed1f9520b967 | 394a279fc8b82f3e7e980698023f84bdab30beb9 | /src/init.cpp | 0d246abeda18b5d68acbfc52ec756533a5f21d6c | [
"MIT"
]
| permissive | hocf/h1 | d9dd886908776f6f6cdd7116a464ce9fbbc54d66 | 36ed792a0507f415e98cd2c9d3b1b6e3562571bf | refs/heads/master | 2020-07-21T02:42:37.129061 | 2016-11-14T21:16:27 | 2016-11-14T21:16:27 | 73,740,920 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 41,725 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The HuobiCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "main.h"
#include "core.h"
#include "chainparams.h"
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "util.h"
#include "miner.h"
#include "ui_interface.h"
#include "checkpoints.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
std::string strWalletFile;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
// Used to pass flags to the Bind() function
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1)
};
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
static CCoinsViewDB *pcoinsdbview;
void Shutdown()
{
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) return;
RenameThread("bitcoin-shutoff");
nTransactionsUpdated++;
StopRPCThreads();
ShutdownRPCMining();
bitdb.Flush(false);
GenerateBitcoins(false, NULL);
StopNode();
{
LOCK(cs_main);
if (pwalletMain)
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
if (pblocktree)
pblocktree->Flush();
if (pcoinsTip)
pcoinsTip->Flush();
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pblocktree; pblocktree = NULL;
}
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterAllWallets();
delete pwalletMain;
}
//
// Signal handlers are very limited in what they are allowed to do, so:
//
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n";
strUsage += " -? " + _("This help message") + "\n";
strUsage += " -conf=<file> " + _("Specify configuration file (default: huobicoin.conf)") + "\n";
strUsage += " -pid=<file> " + _("Specify pid file (default: huobicoind.pid)") + "\n";
strUsage += " -gen " + _("Generate coins (default: 0)") + "\n";
strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n";
strUsage += " -wallet=<file> " + _("Specify wallet file (within data directory)") + "\n";
strUsage += " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n";
strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n";
strUsage += " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n";
strUsage += " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n";
strUsage += " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n";
strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n";
strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 9115 or testnet: 19115)") + "\n";
strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n";
strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n";
strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n";
strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n";
strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n";
strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n";
strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n";
strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n";
strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n";
strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n";
strUsage += " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n";
strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n";
strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n";
strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n";
strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n";
#ifdef USE_UPNP
#if USE_UPNP
strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n";
#else
strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n";
#endif
#endif
strUsage += " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n";
if (fHaveGUI)
strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n";
#if !defined(WIN32)
if (fHaveGUI)
strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n";
#endif
strUsage += " -testnet " + _("Use the test network") + "\n";
strUsage += " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n";
strUsage += " -debugnet " + _("Output extra network debugging information") + "\n";
strUsage += " -logtimestamps " + _("Prepend debug output with timestamp") + "\n";
strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n";
strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n";
strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be "
"solved instantly. This is intended for regression testing tools and app development.") + "\n";
#ifdef WIN32
strUsage += " -printtodebugger " + _("Send trace/debug info to debugger") + "\n";
#endif
strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n";
strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n";
strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 9116 or testnet: 19116)") + "\n";
strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n";
if (!fHaveGUI)
strUsage += " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n";
strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n";
strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n";
strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n";
strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)") + "\n";
strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + "\n";
strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n";
strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n";
strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n";
strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n";
strUsage += " -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n";
strUsage += " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n";
strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n";
strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n";
strUsage += " -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n";
strUsage += "\n" + _("Block creation options:") + "\n";
strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n";
strUsage += " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n";
strUsage += " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n";
strUsage += "\n" + _("SSL options: (see the HuobiCoin Wiki for SSL setup instructions)") + "\n";
strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n";
strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n";
strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("bitcoin-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
FILE *file = OpenBlockFile(pos, true);
if (!file)
break;
printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
printf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
printf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
printf("Importing %s...\n", path.string().c_str());
LoadExternalBlockFile(file);
}
}
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
{
return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
}
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
Checkpoints::fEnabled = GetBoolArg("-checkpoints", true);
if (!SelectParamsFromCommandLine()) {
return InitError("Invalid combination of -testnet and -regtest.");
}
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet", false)) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug", false);
fBenchmark = GetBoolArg("-benchmark", false);
mempool.fChecks = GetBoolArg("-checkmempool", RegTest());
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", 0);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet", false);
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server", false);
/* force fServer when running without GUI */
if (!fHaveGUI)
fServer = true;
fPrintToConsole = GetBoolArg("-printtoconsole", false);
fPrintToDebugger = GetBoolArg("-printtodebugger", false);
fLogTimestamps = GetBoolArg("-logtimestamps", false);
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-mintxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
}
if (mapArgs.count("-minrelaytxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
strWalletFile = GetArg("-wallet", "wallet.dat");
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
// Wallet file must be a plain filename without a directory
if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile.c_str(), strDataDir.c_str()));
// Make sure only a single HuobiCoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. HuobiCoin is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("HuobiCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Using data directory %s\n", strDataDir.c_str());
printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "HuobiCoin server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
int64 nStart;
// ********************************************************* Step 5: verify wallet database integrity
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet", false))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, strWalletFile, true))
return false;
}
if (filesystem::exists(GetDataDir() / strWalletFile))
{
CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
// ********************************************************* Step 6: network initialization
RegisterNodeSignals(GetNodeSignals());
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
bool fBound = false;
if (!fNoListen) {
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
#endif
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load block chain
fReindex = GetBoolArg("-reindex", false);
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = GetArg("-dbcache", 25) << 20;
if (nTotalCache < (1 << 22))
nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex)
pblocktree->WriteReindexing(true);
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != GetBoolArg("-txindex", false)) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (!VerifyDB(GetArg("-checklevel", 3),
GetArg( "-checkblocks", 288))) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
if (fDebug) printf("%s\n", e.what());
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
printf("Aborted block database rebuild. Exiting.\n");
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
ReadBlockFromDisk(block, pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Step 8: load wallet
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFile);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of HuobiCoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart HuobiCoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan", false))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb(strWalletFile);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ConnectBestBlock(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
StartNode(threadGroup);
// InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
InitRPCMining();
if (fServer)
StartRPCThreads();
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
return !fRequestShutdown;
}
| [
"[email protected]"
]
| |
628e0fd9f2fcfb408b13ac53e71e40a5a63d3a52 | 995fef3accf2aedbcd431dd98bc9ab2a2ecace9d | /src/plugins/advancednotifications/advancednotifications.cpp | b19747b08f7953c31174c66938fcedad458deaf1 | [
"BSL-1.0"
]
| permissive | eringus/leechcraft | 2e3da6263e7530f002b532aae616a4b158d53ff6 | 415a9a49aa4c942a4953e8c6e59876fc7e217b24 | refs/heads/master | 2020-12-26T04:56:09.461868 | 2013-12-17T13:03:26 | 2013-12-17T13:03:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,956 | cpp | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2013 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "advancednotifications.h"
#include <QIcon>
#include <interfaces/entitytesthandleresult.h>
#include <xmlsettingsdialog/xmlsettingsdialog.h>
#include <util/resourceloader.h>
#include <util/util.h>
#include <util/sys/paths.h>
#include "generalhandler.h"
#include "xmlsettingsmanager.h"
#include "notificationruleswidget.h"
#include "core.h"
#include "rulesmanager.h"
#include "quarkproxy.h"
namespace LeechCraft
{
namespace AdvancedNotifications
{
void Plugin::Init (ICoreProxy_ptr proxy)
{
Util::InstallTranslator ("advancednotifications");
Proxy_ = proxy;
Core::Instance ().SetProxy (proxy);
connect (&Core::Instance (),
SIGNAL (gotEntity (const LeechCraft::Entity&)),
this,
SIGNAL (gotEntity (const LeechCraft::Entity&)));
SettingsDialog_.reset (new Util::XmlSettingsDialog ());
SettingsDialog_->RegisterObject (&XmlSettingsManager::Instance (),
"advancednotificationssettings.xml");
SettingsDialog_->SetCustomWidget ("RulesWidget",
Core::Instance ().GetNRW ());
SettingsDialog_->SetDataSource ("AudioTheme",
Core::Instance ().GetAudioThemeLoader ()->GetSubElemModel ());
GeneralHandler_.reset (new GeneralHandler (proxy));
connect (GeneralHandler_.get (),
SIGNAL (gotActions (QList<QAction*>, LeechCraft::ActionsEmbedPlace)),
this,
SIGNAL (gotActions (QList<QAction*>, LeechCraft::ActionsEmbedPlace)));
Component_.reset (new QuarkComponent ("advancednotifications", "ANQuark.qml"));
Component_->StaticProps_.push_back ({ "AN_quarkTooltip", tr ("Toggle Advanced Notifications rules...") });
Component_->DynamicProps_.push_back ({ "AN_rulesManager", Core::Instance ().GetRulesManager () });
Component_->DynamicProps_.push_back ({ "AN_proxy", new QuarkProxy });
}
void Plugin::SecondInit ()
{
}
QByteArray Plugin::GetUniqueID () const
{
return "org.LeechCraft.AdvancedNotifications";
}
void Plugin::Release ()
{
GeneralHandler_.reset ();
Core::Instance ().Release ();
}
QString Plugin::GetName () const
{
return "Advanced Notifications";
}
QString Plugin::GetInfo () const
{
return tr ("Module for the advanced notifications framework.");
}
QIcon Plugin::GetIcon () const
{
static QIcon icon ("lcicons:/plugins/advancednotifications/resources/images/advancednotifications.svg");
return icon;
}
EntityTestHandleResult Plugin::CouldHandle (const Entity& e) const
{
const bool can = e.Mime_.startsWith ("x-leechcraft/notification") &&
e.Additional_.contains ("org.LC.AdvNotifications.SenderID") &&
e.Additional_.contains ("org.LC.AdvNotifications.EventID") &&
e.Additional_.contains ("org.LC.AdvNotifications.EventCategory");
if (!can)
return EntityTestHandleResult ();
EntityTestHandleResult result (EntityTestHandleResult::PIdeal);
result.CancelOthers_ = true;
return result;
}
void Plugin::Handle (Entity e)
{
GeneralHandler_->Handle (e);
}
Util::XmlSettingsDialog_ptr Plugin::GetSettingsDialog () const
{
return SettingsDialog_;
}
QList<QAction*> Plugin::GetActions (ActionsEmbedPlace) const
{
return QList<QAction*> ();
}
QuarkComponents_t Plugin::GetComponents () const
{
return QuarkComponents_t () << Component_;
}
}
}
LC_EXPORT_PLUGIN (leechcraft_advancednotifications, LeechCraft::AdvancedNotifications::Plugin);
| [
"[email protected]"
]
| |
28f8272944b7d8c72cf50448dd5746e9e2e39bad | bf1b6f8125f4784c13ea02da085c4bfa37a4b712 | /test_source/hoge.cc | 03852003cb78d2573855d4f213d709b63971ad88 | []
| no_license | Ailes-Grises/ELF | e8b42cbb044b82b5c82b5d4deda423e169d56826 | e9280ef89d68f46b4c09b02dca9c8dbe3b7c333f | refs/heads/master | 2023-01-19T16:10:46.174294 | 2020-08-26T13:20:27 | 2020-08-26T13:20:27 | 258,823,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | cc | #include<iostream>
#include<memory>
#include<string>
using namespace std;
class foo;
class hoge{
private:
int key;
string value;
public:
hoge(void){
};
hoge(int key, string value){
this->key = key;
this->value = value;
};
~hoge(void){
};
void key_to_value(int key){
cout << value << endl;
return;
};
void value_to_key(string value){
cout << key << endl;
return;
};
void get_foo(shared_ptr<foo> Foo){
// Foo->show();
return;
};
};
class foo{
private:
int x;
public:
foo(void){
};
foo(int x){
this->x=x;
};
~foo(void){
};
void show(void){
cout<<"x : "<<x<<endl;
return;
};
void get_hoge(shared_ptr<hoge> Hoge){
Hoge->key_to_value(23);
return;
};
};
int main(void){
// hoge X(23, "Naoto");
shared_ptr<hoge> Hoge(new hoge(23, "Naoto"));
shared_ptr<foo> Foo(new foo(10));
Foo->get_hoge(Hoge);
return 0;
}
| [
"[email protected]"
]
| |
742cbd2a083e0f91879a6e0ac4cffcae44f7c56e | 040abbdbf19ebdde475a26769377f6ae7319cc0c | /1.HelloJNI/app/src/main/cpp/native-lib.h | 6ab2d324706304b6b2dcc64015dab4c9b6c17ec1 | [
"MIT"
]
| permissive | spacecase123/Native-Android-Examples | 1e8e34e2f0405f6806a8f34b22b5f365556ca77b | a4618b753f8e5af471125ca3e926b4aef3f7bdd6 | refs/heads/master | 2023-08-13T21:15:51.037059 | 2021-10-11T02:45:37 | 2021-10-11T02:45:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | h | //MIT License
//
//Copyright (c) 2020 Saket Upadhyay
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
#ifndef HELLOJNI_NATIVE_LIB_H
#define HELLOJNI_NATIVE_LIB_H
#include <jni.h>
#include <string>
#endif //HELLOJNI_NATIVE_LIB_H
| [
"[email protected]"
]
| |
f4d4854c0178a6c1bb545e02b021a949f08b4d1a | 1d039b7b820a9b6c04db14eb6a73be9b0358ac4a | /desktop_src/Arduino.cpp | a181201618c8b35f19b675bb613a87b0dc9660a3 | []
| no_license | FernandoVelcic/nfsu2_speedometer | 7d95758303a61b3afe52342d961002e255b9200c | 0072c0663441e6eadb9067a0feb204435b97c3d0 | refs/heads/master | 2020-03-26T12:20:49.683394 | 2018-08-15T18:55:51 | 2018-08-15T18:55:51 | 144,887,713 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,789 | cpp | #include "stdafx.h"
#include "Arduino.h"
#include <math.h>
HANDLE hPort;
#pragma pack(2)
struct sSpeedometerInfo
{
/*<thisrel this+0x0>*/ /*|0x2|*/ unsigned short Speed;
/*<thisrel this+0x2>*/ /*|0x1|*/ unsigned char Shift;
/*<thisrel this+0x3>*/ /*|0x1|*/ unsigned char Leds;
} SpeedometerInfo;
#pragma pack()
void SendSpeedometerInfo()
{
SpeedometerInfo.Speed = (unsigned short)(MPH2KMH(g_fpVelocity));
SpeedometerInfo.Shift = g_byShift;
//SpeedometerInfo.Leds = (unsigned char)pow((double)(g_fpDial-1000.0f), (double)1/4.5);
SpeedometerInfo.Leds = (unsigned char)(g_fpDial/1000)-1;
DWORD dwDst;
WriteFile(hPort, (LPCVOID)&SpeedometerInfo, sizeof(SpeedometerInfo), &dwDst, NULL);
}
bool ArduinoSerialConnection()
{
hPort = CreateFile(L"\\\\.\\COM13", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if(hPort == INVALID_HANDLE_VALUE) {
printf("[DEBUG] Serial connection error: %d", GetLastError());
return false;
}
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if ( !GetCommState(hPort, &dcbSerialParams) ) {
printf("[DEBUG] Cannot get serial communication status: %d", GetLastError());
return false;
}
dcbSerialParams.BaudRate = CBR_19200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if( !SetCommState(hPort, &dcbSerialParams) )
{
printf("[DEBUG] Cannot set serial communication status: %d", GetLastError());
return false;
}
return true;
}
/*
bitfield method
SpeedometerInfo.Leds |= 0 << 0;
SpeedometerInfo.Leds |= 0 << 1;
SpeedometerInfo.Leds |= 1 << 2;
SpeedometerInfo.Leds |= 1 << 3;
SpeedometerInfo.Leds |= 1 << 4;
SpeedometerInfo.Leds |= 1 << 5;
SpeedometerInfo.Leds |= 1 << 6;
SpeedometerInfo.Leds |= 0 << 7;
*/ | [
"[email protected]"
]
| |
083d4fec3087c45c243f20eff039a32b6217e023 | 6a1c85f2342971896e538eb3089b76ef39afcdbb | /source/radeon_gpu_analyzer_gui/rg_start_tab_opencl.cpp | b547fadec8bdc7521b57065369e03c92ac2d8fbc | [
"MIT"
]
| permissive | clayne/RGA | e5add6183c44df652c58383bfb5d78252660c926 | 6271d5636a790fa87d2c07f1c580cda9a84d3079 | refs/heads/master | 2023-06-25T10:54:27.363181 | 2023-06-13T22:48:25 | 2023-06-13T22:48:25 | 192,228,832 | 0 | 0 | MIT | 2019-06-16T19:27:49 | 2019-06-16T19:27:49 | null | UTF-8 | C++ | false | false | 2,362 | cpp | // C++.
#include <cassert>
// Qt.
#include <QAction>
// Local.
#include "radeon_gpu_analyzer_gui/qt/rg_start_tab_opencl.h"
#include "radeon_gpu_analyzer_gui/qt/rg_app_state_opencl.h"
#include "radeon_gpu_analyzer_gui/rg_data_types_opencl.h"
#include "radeon_gpu_analyzer_gui/rg_utils.h"
RgStartTabOpencl::RgStartTabOpencl(QWidget* parent)
: RgStartTab(parent)
{
// Initialize the OpenCL start buttons.
InitializeStartButtons();
// Connect OpenCL start page signals.
ConnectSignals();
}
void RgStartTabOpencl::ApplyApiStringConstants()
{
// Set label/button text.
create_new_cl_source_file_->setText(kStrMenuBarCreateNewFileOpencl);
add_existing_cl_source_file_->setText(kStrMenuBarOpenExistingFileOpencl);
// Set tooltips and status tips.
RgUtils::SetToolAndStatusTip(kStrMenuBarCreateNewFileTooltipOpencl, create_new_cl_source_file_);
RgUtils::SetToolAndStatusTip(kStrMenuBarOpenExistingFileTooltipOpencl, add_existing_cl_source_file_);
}
void RgStartTabOpencl::GetStartButtons(std::vector<QPushButton*>& start_buttons)
{
start_buttons.push_back(create_new_cl_source_file_);
start_buttons.push_back(add_existing_cl_source_file_);
}
void RgStartTabOpencl::InitializeStartButtons()
{
// Create the "Create .cl file" button.
create_new_cl_source_file_ = new QPushButton(this);
create_new_cl_source_file_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
create_new_cl_source_file_->setText(kStrMenuBarCreateNewFileOpencl);
create_new_cl_source_file_->setToolTip(kStrMenuBarCreateNewFileTooltipOpencl);
// Create the "Add existing .cl file" button.
add_existing_cl_source_file_ = new QPushButton(this);
add_existing_cl_source_file_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
add_existing_cl_source_file_->setText(kStrMenuBarOpenExistingFileOpencl);
add_existing_cl_source_file_->setToolTip(kStrMenuBarOpenExistingFileTooltipOpencl);
}
void RgStartTabOpencl::ConnectSignals()
{
// Create New File action.
bool is_connected = connect(create_new_cl_source_file_, &QPushButton::clicked, this, &RgStartTabOpencl::CreateNewCLFileEvent);
assert(is_connected);
// Open a file.
is_connected = connect(add_existing_cl_source_file_, &QPushButton::clicked, this, &RgStartTabOpencl::OpenExistingFileEvent);
assert(is_connected);
}
| [
"[email protected]"
]
| |
cf02d6178a84e6179bfbab4816558c0cd2876ae6 | 33b567f6828bbb06c22a6fdf903448bbe3b78a4f | /opencascade/NCollection_HSequence.hxx | 4cb6f1e366e43d09ce17fae100e00388afef9066 | [
"Apache-2.0"
]
| permissive | CadQuery/OCP | fbee9663df7ae2c948af66a650808079575112b5 | b5cb181491c9900a40de86368006c73f169c0340 | refs/heads/master | 2023-07-10T18:35:44.225848 | 2023-06-12T18:09:07 | 2023-06-12T18:09:07 | 228,692,262 | 64 | 28 | Apache-2.0 | 2023-09-11T12:40:09 | 2019-12-17T20:02:11 | C++ | UTF-8 | C++ | false | false | 1,069 | hxx | // Created on: 2001-01-29
// Created by: Alexander GRIGORIEV
// Copyright (c) 2001-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef NCollection_HSequence_HeaderFile
#define NCollection_HSequence_HeaderFile
#include <NCollection_DefineHSequence.hxx>
#include <NCollection_Sequence.hxx>
// Declaration of Sequence class managed by Handle
#define NCOLLECTION_HSEQUENCE(HClassName,Type) \
DEFINE_HSEQUENCE(HClassName,NCollection_Sequence<Type >)
#endif
| [
"[email protected]"
]
| |
672dbe710acb62ac8f0e8be89bd5be8fac8a6008 | 59418b5794f251391650d8593704190606fa2b41 | /plugin_api/qsf/qsf/renderer/material/material/MaterialTexture-inl.h | 32be4c0ecaeba50fc7044aa3ef655f79005e24e0 | []
| no_license | JeveruBerry/emergency5_sdk | 8e5726f28123962541f7e9e4d70b2d8d5cc76cff | e5b23d905c356aab6f8b26432c72d18e5838ccf6 | refs/heads/master | 2023-08-25T12:25:19.117165 | 2018-12-18T16:55:16 | 2018-12-18T17:09:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,318 | h | // Copyright (C) 2012-2018 Promotion Software GmbH
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace qsf
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
inline MaterialTexture::MaterialTexture(uint32 _rootParameterIndex, const MaterialProperty& _materialProperty, Ogre::TextureType _ogreTextureType, uint32 _numberOfMipmaps, bool _hardwareGammaCorrection) :
rootParameterIndex(_rootParameterIndex),
materialProperty(_materialProperty),
ogreTextureType(_ogreTextureType),
numberOfMipmaps(_numberOfMipmaps),
hardwareGammaCorrection(_hardwareGammaCorrection),
textureUnit(getUninitialized<uint16>()),
mStreamedTexture(nullptr)
{
// Nothing here
}
inline MaterialTexture::MaterialTexture(uint32 _rootParameterIndex, const MaterialProperty& _materialProperty, Ogre::TextureType _ogreTextureType, uint32 _numberOfMipmaps, bool _hardwareGammaCorrection, const Ogre::TexturePtr& _ogreTexturePtr, uint16 _textureUnit) :
rootParameterIndex(_rootParameterIndex),
materialProperty(_materialProperty),
ogreTextureType(_ogreTextureType),
numberOfMipmaps(_numberOfMipmaps),
hardwareGammaCorrection(_hardwareGammaCorrection),
ogreTexturePtr(_ogreTexturePtr),
textureUnit(_textureUnit),
mStreamedTexture(nullptr)
{
// Nothing here
}
inline MaterialTexture::MaterialTexture(uint32 _rootParameterIndex, Ogre::TextureType _ogreTextureType, uint32 _numberOfMipmaps, bool _hardwareGammaCorrection, const Ogre::TexturePtr& _ogreTexturePtr, uint16 _textureUnit) :
rootParameterIndex(_rootParameterIndex),
ogreTextureType(_ogreTextureType),
numberOfMipmaps(_numberOfMipmaps),
hardwareGammaCorrection(_hardwareGammaCorrection),
ogreTexturePtr(_ogreTexturePtr),
textureUnit(_textureUnit),
mStreamedTexture(nullptr)
{
// Nothing here
}
inline MaterialTexture::~MaterialTexture()
{
resetStreamedTexture();
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // qsf
| [
"[email protected]"
]
| |
de9a021afb7dc237c207e18e9bc7a44afa9ca226 | 916ef1b31f0b683de4f043626d9df59f37edbbc4 | /atcoder/05_AtCoder-Beginner-Contest/abc128/D/main.cpp | 2c936cfe1c0ac4bef26a78458497e8fb5b43e21d | []
| no_license | solareenlo/cpp | 56cc33673d30dd4a4031e4b81cec16b08b3490e0 | f78f8a098849938153e6e3a282737e067dbe2c58 | refs/heads/master | 2021-03-31T04:31:39.420394 | 2020-11-29T22:22:25 | 2020-11-29T22:22:25 | 248,076,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | cpp | #include <iostream>
#include <map>
#include <set>
#include <vector>
#define REP(i, n) for (int i = 0; i < (n); i++)
using namespace std;
void solve(long long N, long long K, std::vector<long long> V){
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
long long N;
scanf("%lld",&N);
long long K;
scanf("%lld",&K);
std::vector<long long> V(N);
for(int i = 0 ; i < N ; i++){
scanf("%lld",&V[i]);
}
solve(N, K, std::move(V));
return 0;
}
| [
"[email protected]"
]
| |
ab89e1f841ff05fe0ef57c484c4b450744283859 | b9d9b29c2a180399393c6ab298b9e5bfba17831e | /每日一题/day126-63. 不同路径 II.cpp | f1acbc34fda181a771402a3b554ab42017740e07 | []
| no_license | qqwangxiaow/leetcode-fast-and-elegant | 08b7c6120b82f7ee3b5a99b84e7ba0f0eb38a477 | f5081a9e1d893b9d936d9486cf6141b5b35684e1 | refs/heads/master | 2022-02-11T00:36:22.911461 | 2022-01-02T05:14:20 | 2022-01-02T05:14:20 | 199,302,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,002 | cpp | //if(obstacleGrid[0][0]==1)
// return 0;
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if(obstacleGrid.empty())
return 0;
int m=obstacleGrid.size(),n=obstacleGrid[0].size();
if(obstacleGrid[0][0]==1)
return 0;
vector<vector<int>>dp(m,vector<int>(n,0));
dp[0][0]=1;
for(int i=1;i<m;i++)
{
if(obstacleGrid[i][0]==1)
break;
else
dp[i][0]=1;
}
for(int j=1;j<n;j++)
{
if(obstacleGrid[0][j]==1)
break;
else
dp[0][j]=1;
}
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
if(obstacleGrid[i][j]==1)
dp[i][j]=0;
else
dp[i][j]=dp[i-1][j]+dp[i][j-1];
}
}
return dp[m-1][n-1];
}
}; | [
"[email protected]"
]
| |
170f289222675ad42ee7318075f29f457f12f3d1 | f66d568c3a4fa3ae985f8cfa4b9db064a6eb33c1 | /src/unit-test/cpp/VariantFields.cpp | 069cbbc4bae01f94ed1b789c8b1dddf79be24353 | []
| no_license | ribomation/OverlayRecord | e8a7e3fb7d55648b71c9166e23e9b0a3d1d4730c | d84a0fb8495c36d5b1ad70be38c182c6841b4f2e | refs/heads/master | 2020-03-26T07:48:21.188350 | 2014-08-31T04:37:01 | 2014-08-31T04:37:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | cpp | /*
* VariantFields.cpp
*
* Created on: Aug 29, 2014
* Author: jens
*/
#include <cppunit/extensions/HelperMacros.h>
#include "Record.hpp"
using namespace overlay_record;
using namespace std;
struct VariantFields : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( VariantFields );
CPPUNIT_TEST( few_overlaid_fields_should_work );
CPPUNIT_TEST_SUITE_END();
void few_overlaid_fields_should_work() {
struct R : public Record {
Text<12> all = {this};
Text<6> half1 = {this, all};
Text<6> half2 = {this};
Text<4> third1 = {this, all};
Text<4> third2 = {this};
Text<4> third3 = {this};
Text<2> tail1 = {this, third3};
Text<2> tail2 = {this};
R() { allocateDynamicBuffer(); }
};
R r;
CPPUNIT_ASSERT_EQUAL(12U, r.size());
CPPUNIT_ASSERT_EQUAL(string(12, ' '), r.all.value());
CPPUNIT_ASSERT_EQUAL(string( 6, ' '), r.half2.value());
CPPUNIT_ASSERT_EQUAL(string( 4, ' '), r.third1.value());
CPPUNIT_ASSERT_EQUAL(string( 2, ' '), r.tail2.value());
r.all = "aabbccddeeff";
CPPUNIT_ASSERT_EQUAL(string("ddeeff"), r.half2.value());
CPPUNIT_ASSERT_EQUAL(string("ccdd") , r.third2.value());
CPPUNIT_ASSERT_EQUAL(string("ee") , r.tail1.value());
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( VariantFields );
| [
"[email protected]"
]
| |
30123664e8e8deeb991203231ff62470dccb49c7 | 41021a03e168f0ff10c574c8d306e15c5848c00c | /8383/kolmykov/OOP/OOP/GunAttack.cpp | 5479cea6d76700000fb9bad30823ea2a9d1e70da | []
| no_license | ephemerno/oop | 1f9e2a0968543a1e92f49c376f3edaee34397c86 | 70c042295f5aee753667ce6cd5c4d8dce7f7f56e | refs/heads/master | 2021-05-21T20:46:11.140302 | 2020-06-01T21:36:04 | 2020-06-01T21:36:04 | 252,789,144 | 0 | 0 | null | 2020-04-03T16:51:15 | 2020-04-03T16:51:15 | null | UTF-8 | C++ | false | false | 619 | cpp | #include "GunAttack.h"
#include "Unit.h"
GunAttack::GunAttack()
{
}
GunAttack::~GunAttack()
{
}
void GunAttack::attack(std::shared_ptr<Unit> unit) {
std::vector<Point> points;
Point point1;
point1.x = unit->getX();
point1.y = unit->getY() - 1;
points.push_back(point1);
Point point2;
point2.x = unit->getX();
point2.y = unit->getY() - 2;
points.push_back(point2);
Point point3;
point3.x = unit->getX();
point3.y = unit->getY() - 3;
points.push_back(point3);
unit->getMediator()->reactOnUnitAttack(unit->getWeapon()->getDamage() + unit->getOwnDamage() + unit->getOwnDamage(), unit, points, true);
}
| [
"[email protected]"
]
| |
df50750faee3c213471aed40ba3ec3c4abf05311 | 492b8f041bc0fd203869c9d682706839e69c1c2b | /2º Semestre/AEDs II/Aula Prática/TPs/TP1/TP01Q11 - Palíndromo em C/TP01Q11PalindromoEmC.cpp | 2b5f5cf535b349d4f9c8ccc9160ea5a5360e64ea | []
| no_license | GeovaneF55/pucminas | 93e595d64ea84af3b4455d6a5d554ab5aae53ef4 | 285272e17c744598c8a2b5222479659b136d8382 | refs/heads/master | 2022-05-20T11:00:48.917687 | 2022-05-01T22:20:44 | 2022-05-01T22:20:44 | 102,910,040 | 1 | 1 | null | 2017-09-17T20:41:09 | 2017-09-08T22:36:11 | HTML | UTF-8 | C++ | false | false | 1,579 | cpp | #include <stdio.h>
// Variável para simular valores booleanos
int falso=0, verdadeiro=1, tamanho=1000;
// Método que retorna o tamanho de uma string
int length(char str[]){
int cont = 0;
while(str[cont] != '\0'){
cont++;
}
return cont;
}
// Método que retorna verdadeiro caso as duas strings passadas por parâmetro seja iguais
int igual(char fraseA[], char fraseB[]){
int ehIgual = verdadeiro;
if(length(fraseA) != length(fraseB)){
ehIgual = falso;
} else{
int i=0;
while(i<length(fraseA) && ehIgual == verdadeiro){
if(fraseA[i] != fraseB[i]){
ehIgual = falso;
}
i++;
}
}
return ehIgual;
}
// Método remove caractere especial de nova linha da string
char *trim(char *string) {
int i = length(string)-1;
if ((i > 0) && (string[i] == '\n')){
string[i] = '\0';
}
return string;
}
// Método que retorna verdadeiro se a string for um palíndromo
int ehPalindromo(char frase[]){
int ehPalindromo = verdadeiro;
int ultimoChar = length(frase)-1;
int i=0;
while(i<(float)ultimoChar/2 && ehPalindromo == verdadeiro){
if(frase[i] != frase[ultimoChar-i]){
ehPalindromo = falso;
}
i++;
}
return ehPalindromo;
}
int main(){
int i=0;
char entrada[tamanho];
char fim[] = "FIM";
fgets(entrada, tamanho, stdin);
while(igual(trim(entrada), fim) == falso){
//Verifica se a frase entregue pelo parâmetro é um palíndromo
if(ehPalindromo(entrada) == verdadeiro){
printf("%s", "SIM\n");
} else{
printf("%s", "NAO\n");
}
fgets(entrada, tamanho, stdin);
}
return 0;
}
| [
"[email protected]"
]
| |
4fc6f8cfd559313c2d84087f8f19936ec1fff320 | 5782659fd7827a61d3f21043ddb915313c9eabe0 | /Windows_version/Interpreter/src/AloadInstruction.cpp | 248ffe9c27f710b8c5e2972ac2a3a3e75153c0ae | []
| no_license | mlboua/Mini-jaja | 5c87d9fd8befda3bfeacf72a0633b3704af9bde6 | b6b642a1b92a97b033e91eafe00b06c52494e15a | refs/heads/master | 2016-08-04T03:11:56.190242 | 2015-05-20T11:55:17 | 2015-05-20T11:55:17 | 18,727,743 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 838 | cpp | #include "AloadInstruction.h"
using namespace std;
AloadInstruction::AloadInstruction(string label, string ident):Instruction(label)
{
this->ident = ident;
}
string AloadInstruction::getLabel() const
{
return label;
}
void AloadInstruction::setLabel(std::string label)
{
this->label = label;
}
string AloadInstruction::getIdent() const
{
return ident;
}
void AloadInstruction::setIdent(string ident)
{
this->ident = ident;
}
void AloadInstruction::interpret (Memory* mem, int* address){
int indice = mem->getStack()->top()->getValue();
mem->getStack()->pop();
int result = Interpreter::valT(this->ident, indice, mem);
//MODIF
//mem->getStack()->pop();
Quadruplet* quadruplet = new Quadruplet ("",result,CST,T_OMEGA);
mem->getStack()->push(quadruplet);
*address = *address + 1;
}
| [
"[email protected]"
]
| |
335a8f580ddb1dab35040ab3f6edb4470904ad81 | 1fea001ec1d935c30cd5927629cdcb51a7331f6c | /client-pc/source/DlgUploadList.cpp | 7b3ae009efa9293f77ab8b1c07e11058a43499a6 | []
| no_license | black0592/BlueClick | 5d884114b71f93de642df04ae4686a6bd5a1b1b0 | 5295f23b99ebe5f0aac793cf6e24274313fb1e9c | refs/heads/master | 2021-05-29T11:50:06.671785 | 2015-04-19T12:24:16 | 2015-04-19T12:24:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,131 | cpp | // DlgUploadList.cpp : implementation file
//
#include "stdafx.h"
#include "BlueClick.h"
#include "DlgUploadList.h"
#include "BlueClickDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgUploadList dialog
CDlgUploadList::CDlgUploadList(CWnd* pParent /*=NULL*/)
: CDialog(CDlgUploadList::IDD, pParent)
{
//{{AFX_DATA_INIT(CDlgUploadList)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CDlgUploadList::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgUploadList)
DDX_Control(pDX, IDC_LIST_UPLOAD, m_listUpload);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgUploadList, CDialog)
//{{AFX_MSG_MAP(CDlgUploadList)
ON_COMMAND(ID_MENUITEM_NEW_SHARE, OnMenuitemNewShare)
ON_COMMAND(ID_MENUITEM_DELETE_SHARE, OnMenuitemDeleteShare)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgUploadList message handlers
BOOL CDlgUploadList::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
CWnd *pParentWnd = GetParent();
CRect parentRect;
pParentWnd->GetClientRect(&parentRect);
SetWindowPos(NULL, 0, 0, parentRect.Width(), parentRect.Height(), SWP_SHOWWINDOW);
CRect listRect;
GetClientRect(&listRect);
m_listUpload.SetWindowPos(NULL, 0, 0, listRect.Width(), listRect.Height(), SWP_SHOWWINDOW);
m_listUpload.SetExtendedStyle( LVS_EX_FLATSB | LVS_EX_FULLROWSELECT |
LVS_EX_ONECLICKACTIVATE | LVS_OWNERDRAWFIXED );
//设置资源列表视图行高,前提是需要设置自绘风格,即LVS_OWNERDRAWFIXED
m_listUpload.SetItemHeight(40);
m_listUpload.ModifyStyle( LVS_OWNERDRAWFIXED, 0, 0 );//去掉自绘风格
m_listUpload.SetColumnType(1, BUFFREE_COLUMN_ICON);//设置第二列显示图标
m_listUpload.SetColumnType(4, BUFFREE_COLUMN_PROGRESS);//设置第四列显示进度条
m_listUpload.SetRightMenuID(IDR_MENU_UPLOAD);//设置右键菜单
//这块需要注意的是,第一列宽度设置为0,即不显示第一列,因为第一列不能设置居中对齐
//并且通过GetClientRect()获取到的第一列宽度并不是真正的第一列宽度,而是整个列表的宽度
//上传列表:
// 0:弃用,这里用来存储资源路径;
// 1:文件后缀;
// 2:文件名;
// 3:文件大小
// 4:进度条,字串无效,这里用来存储资源标签;
// 5:文件MD5
// data:进度条进度
m_listUpload.InsertColumn(0, "文件路径", LVCFMT_LEFT, 0, 0);
m_listUpload.InsertColumn(1, "类型", LVCFMT_LEFT, 100, 1);//第二列
m_listUpload.InsertColumn(2, "文件名", LVCFMT_LEFT, 250, 2);
m_listUpload.InsertColumn(3, "大小", LVCFMT_LEFT, 70, 3);
m_listUpload.InsertColumn(4, "进度", LVCFMT_LEFT, listRect.Width()-438, 4);//通过计算,使得最后一列刚好填满列表宽度
m_listUpload.InsertColumn(5, "资源标识", LVCFMT_LEFT, 0, 5);//不显示
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BOOL CDlgUploadList::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if(pMsg->message == WM_KEYDOWN) {
if(pMsg->wParam == VK_ESCAPE) {
return true;
}
if(pMsg->wParam == VK_RETURN) {
return true;
}
}
return CDialog::PreTranslateMessage(pMsg);
}
void CDlgUploadList::OnMenuitemNewShare()
{
// TODO: Add your command handler code here
CBlueClickDlg * mainWnd = (CBlueClickDlg*)AfxGetMainWnd();
mainWnd->AddNewShare();
}
void CDlgUploadList::OnMenuitemDeleteShare()
{
// TODO: Add your command handler code here
int nItem = m_listUpload.GetNextItem(-1, LVNI_SELECTED);
CBlueClickDlg *mainWnd = (CBlueClickDlg*)(this->GetParent()->GetParent());
mainWnd->DeleteShare(nItem);
} | [
"[email protected]"
]
| |
a40acb1668db308b3fa60b11bd6a04db53e25ceb | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Advanced 2D Game Development/sources/ch10/Engine/Advanced2D.h | b2270991440af38d235429cae39dbd827936813a | []
| no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 5,673 | h | // Advanced2D Engine
// Main header file
#pragma once
//#ifndef _ADVANCED2D_H
//#define _ADVANCED2D_H 1
//*****ADD TO CHAPTER 1 LISTING
#define WIN32_EXTRA_LEAN
#include <windows.h>
//****CHAPTER 7 NOTE: winmain.h was removed
//#include "winmain.h"
#include <iostream>
#include <list>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cmath>
#define DIRECTINPUT_VERSION 0x0800
#include <d3d9.h>
#include <d3dx9.h>
#include <dxerr9.h>
#include <dinput.h>
#include "Timer.h"
#include "Camera.h"
#include "Mesh.h"
#include "Texture.h"
#include "Light.h"
#include "Vector3.h"
#include "Sprite.h"
#include "ParticleEmitter.h"
#include "Input.h"
#include "fmod.hpp"
#include "Audio.h"
#include "Entity.h"
#include "Font.h"
#include "Console.h"
#include "Rect.h"
#include "Math.h"
#include "lua.hpp"
#include "Script.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 0
#define REVISION 0
//external variables and functions
extern bool gameover;
//*****CHANGE INT TO BOOL IN CHAPTER 1 LISTING
extern bool game_preload();
extern bool game_init(HWND);
extern void game_update();
extern void game_end();
extern void game_render3d();
extern void game_render2d();
//****CHAPTER 5
extern void game_keyPress(int);
extern void game_keyRelease(int);
extern void game_mouseButton(int);
extern void game_mouseMotion(int,int);
extern void game_mouseMove(int,int);
extern void game_mouseWheel(int);
//****CHAPTER 7
extern void game_entityUpdate(Advanced2D::Entity*);
extern void game_entityRender(Advanced2D::Entity*);
//add this one in chapter 9
extern void game_entityCollision(Advanced2D::Entity*,Advanced2D::Entity*);
//*****ADD TO CHAPTER 1
//macro to read the keyboard asynchronously
#define KEY_DOWN(vk) ((GetAsyncKeyState(vk) & 0x8000)?1:0)
namespace Advanced2D
{
class Engine {
private:
int p_versionMajor, p_versionMinor, p_revision;
HWND p_windowHandle;
LPDIRECT3D9 p_d3d;
LPDIRECT3DDEVICE9 p_device;
LPDIRECT3DSURFACE9 p_backbuffer;
LPD3DXSPRITE p_sprite_handler;
std::string p_apptitle;
bool p_fullscreen;
int p_screenwidth;
int p_screenheight;
int p_colordepth;
bool p_pauseMode;
D3DCOLOR p_ambientColor;
bool p_maximizeProcessor;
Timer p_coreTimer;
long p_frameCount_core;
long p_frameRate_core;
Timer p_realTimer;
long p_frameCount_real;
long p_frameRate_real;
//****MOVED HERE FROM CPP FILE IN CHAPTER 9
Timer timedUpdate;
//*****ADDED IN CHAPTER 9
Timer collisionTimer;
//****ADDED IN CHAPTER 5
Input *p_input;
void UpdateKeyboard();
void UpdateMouse();
//*****ADDED IN CHAPTER 7
void UpdateEntities();
void Draw2DEntities();
void Draw3DEntities();
void BuryEntities();
//****ADDED IN CHAPTER 9
bool collision(Sprite *sprite1, Sprite *sprite2);
bool collisionBR(Sprite *sprite1, Sprite *sprite2);
bool collisionD(Sprite *sprite1, Sprite *sprite2);
void TestForCollisions();
std::list<Entity*> p_entities;
public:
Engine();
virtual ~Engine();
int Init(int width, int height, int colordepth, bool fullscreen);
void Close();
void Update();
void message(std::string message, std::string title = "ADVANCED 2D");
void fatalerror(std::string message, std::string title = "FATAL ERROR");
void Shutdown();
void ClearScene(D3DCOLOR color);
void SetDefaultMaterial();
void SetAmbient(D3DCOLOR colorvalue);
void SetIdentity();
int RenderStart();
int RenderStop();
int Render2D_Start();
int Render2D_Stop();
int Release();
//public Audio object
Audio *audio;
//CHAPTER 10
//public Math object
Math *math;
//accessor/mutator functions expose the private variables
bool isPaused() { return this->p_pauseMode; }
void setPaused(bool value) { this->p_pauseMode = value; }
LPDIRECT3DDEVICE9 getDevice() { return this->p_device; }
LPDIRECT3DSURFACE9 getBackBuffer() { return this->p_backbuffer; }
LPD3DXSPRITE getSpriteHandler() { return this->p_sprite_handler; }
void setWindowHandle(HWND hwnd) { this->p_windowHandle = hwnd; }
HWND getWindowHandle() { return this->p_windowHandle; }
std::string getAppTitle() { return this->p_apptitle; }
void setAppTitle(std::string value) { this->p_apptitle = value; }
int getVersionMajor() { return this->p_versionMajor; }
int getVersionMinor() { return this->p_versionMinor; }
int getRevision() { return this->p_revision; }
std::string getVersionText();
long getFrameRate_core() { return this->p_frameRate_core; };
long getFrameRate_real() { return this->p_frameRate_real; };
int getScreenWidth() { return this->p_screenwidth; }
void setScreenWidth(int value) { this->p_screenwidth = value; }
int getScreenHeight() { return this->p_screenheight; }
void setScreenHeight(int value) { this->p_screenheight = value; }
int getColorDepth() { return this->p_colordepth; }
void setColorDepth(int value) { this->p_colordepth = value; }
bool getFullscreen() { return this->p_fullscreen; }
void setFullscreen(bool value) { this->p_fullscreen = value; }
bool getMaximizeProcessor() { return this->p_maximizeProcessor; }
void setMaximizeProcessor(bool value) { this->p_maximizeProcessor = value; }
//******NEED TO ADD
std::list<Entity*> getEntityList() { return p_entities; }
long getEntityCount() { return (long)p_entities.size(); }
void addEntity(Entity *entity);
Entity *findEntity(std::string name);
Entity *findEntity(int objectType);
//****ADDED IN CHAPTER 10
int getEntityCount(int objectType);
}; //class
}; //namespace
//define the global engine object (visible everywhere!)
extern Advanced2D::Engine *g_engine;
//#endif
| [
"[email protected]"
]
| |
e4e91ab62d7a209f68bb8204209aa8ea6330adb0 | c372bc24b3337a0b2be215e5fca2f7ab7536d663 | /SendMail.h | e08369e68a082c9e4c57c599a142e6734f1ebbc1 | []
| no_license | ecuyar/Logger | 8b403b463f5732087b22738bd56852d85633603c | b7c5bbc8504b98e46f49bb57755e12655f3dd125 | refs/heads/master | 2020-07-12T06:42:26.028201 | 2019-08-27T16:39:09 | 2019-08-27T16:39:09 | 204,746,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,902 | h | #ifndef SENDMAIL_H
#define SENDMAIL_H
#include <fstream>
#include <vector>
#include "windows.h"
#include "IO.h"
#include "Timer.h"
#include "Helper.h"
#define SCRIPT_NAME "sm.ps1"
namespace Mail
{
#define X_EM_TO "[email protected]"
#define X_EM_FROM "[email protected]"
#define X_EM_PASS "Deneme123"
const std::string &PowerShellScript =
"Param( \r\n [String]$Att,\r\n [String]$Subj,\r\n "
"[String]$Body\r\n)\r\n\r\nFunction Send-EMail"
" {\r\n Param (\r\n [Parameter(`\r\n Mandatory=$true)]\r\n "
"[String]$To,\r\n [Parameter(`\r\n Mandatory=$true)]\r\n "
"[String]$From,\r\n [Parameter(`\r\n mandatory=$true)]\r\n "
"[String]$Password,\r\n [Parameter(`\r\n Mandatory=$true)]\r\n "
"[String]$Subject,\r\n [Parameter(`\r\n Mandatory=$true)]\r\n "
"[String]$Body,\r\n [Parameter(`\r\n Mandatory=$true)]\r\n "
"[String]$attachment\r\n )\r\n try\r\n {\r\n $Msg = New-Object "
"System.Net.Mail.MailMessage($From, $To, $Subject, $Body)\r\n $Srv = \"smtp.gmail.com\" "
"\r\n if ($attachment -ne $null) {\r\n try\r\n {\r\n"
" $Attachments = $attachment -split (\"\\:\\:\");\r\n "
" ForEach ($val in $Attachments)\r\n "
" {\r\n "
" $attch = New-Object System.Net.Mail.Attachment($val)\r\n "
" $Msg.Attachments.Add($attch)\r\n }\r\n "
"}\r\n catch\r\n {\r\n exit 2; "
"\r\n }\r\n }\r\n "
" $Client = New-Object Net.Mail.SmtpClient($Srv, 587) #587 port for smtp.gmail.com SSL\r\n "
" $Client.EnableSsl = $true \r\n $Client.Credentials = New-Object "
"System.Net.NetworkCredential($From.Split(\"@\")[0], $Password); \r\n $Client.Send($Msg)\r\n "
" Remove-Variable -Name Client\r\n Remove-Variable -Name Password\r\n "
"exit 7; \r\n }\r\n catch\r\n {\r\n exit 3; "
" \r\n }\r\n} #End Function Send-EMail\r\ntry\r\n {\r\n "
"Send-EMail -attachment $Att "
"-To \"" +
std::string (X_EM_TO) +
"\""
" -Body $Body -Subject $Subj "
"-password \"" +
std::string (X_EM_PASS) +
"\""
" -From \"" +
std::string (X_EM_FROM) +
"\"""\r\n }\r\ncatch\r\n {\r\n exit 4; \r\n }";
#undef X_EM_FROM
#undef X_EM_TO
#undef X_EM_PASS
std::string StringReplace(std::string s, const std::string &what, const std::string &with)
{
if(what.empty())
return s;
size_t sp = 0;
while((sp = s.find(what, sp)) != std::string::npos)
s.replace(sp, what.length(), with), sp += with.length();
return s;
}
bool CheckFileExist(const std::string &f)
{
std::ifstream file (f);
return (bool)file ;
}
bool CreateScript()
{
std::ofstream script(IO::GetOurPath(true) + std::string(SCRIPT_NAME));
if(!script)
return false;
script << PowerShellScript;
if(!script)
return false;
script.close();
return true;
}
Timer m_timer;
int SendMail(const std::string &subject, const std::string &body, const std::string &attachments)
{
bool ok;
ok = IO::MkDir(IO::GetOurPath(true));
if(!ok)
return -1;
std::string scr_path = IO::GetOurPath(true) + std::string(SCRIPT_NAME);
if(!CheckFileExist(scr_path))
ok = CreateScript();
if(!ok)
return -2;
std::string param = "-ExecutionPolicy ByPass -File \"" + scr_path + "\" -Subj \""
+ StringReplace(subject, "\"", "\\\"") +
"\" -Body \""
+ StringReplace(body, "\"", "\\\"") +
"\" -Att \"" + attachments + "\"";
SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = "open";
ShExecInfo.lpFile = "powershell";
ShExecInfo.lpParameters = param.c_str();
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL;
ok = (bool)ShellExecuteEx(&ShExecInfo);
if(!ok)
return -3;
WaitForSingleObject(ShExecInfo.hProcess, 7000);
DWORD exit_code = 100;
GetExitCodeProcess(ShExecInfo.hProcess, &exit_code);
m_timer.SetFunction([&]()
{
WaitForSingleObject(ShExecInfo.hProcess, 60000);
GetExitCodeProcess(ShExecInfo.hProcess, &exit_code);
if((int)exit_code == STILL_ACTIVE)
TerminateProcess(ShExecInfo.hProcess, 100);
Helper::WriteAppLog("<From SendMail> Return code: " + Helper::ToString((int)exit_code));
});
m_timer.RepeatCount(1L);
m_timer.SetInterval(10L);
m_timer.Start(true);
return (int)exit_code;
}
int SendMail(const std::string &subject,
const std::string &body,
const std::vector<std::string> &att)
{
std::string attachments = "";
if(att.size() == 1U)
attachments = att.at(0);
else
{
for(const auto &v : att)
attachments += v + "::";
attachments = attachments.substr(0, attachments.length() - 2);
}
return SendMail(subject, body, attachments);
}
}
#endif // SENDMAIL_H
| [
"[email protected]"
]
| |
6c5a53455496517e2f9dd045d1af2efc0d514804 | f14626611951a4f11a84cd71f5a2161cd144a53a | /武侠世界/代码/Common/Packets/GCCharJump.h | 2507435212749856a84c356c7c56c7a43ce0781b | []
| no_license | Deadmanovi4/mmo-resourse | 045616f9be76f3b9cd4a39605accd2afa8099297 | 1c310e15147ae775a59626aa5b5587c6895014de | refs/heads/master | 2021-05-29T06:14:28.650762 | 2015-06-18T01:16:43 | 2015-06-18T01:16:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,156 | h | #ifndef __GCCHARJUMP_H__
#define __GCCHARJUMP_H__
#include "Type.h"
#include "Packet.h"
#include "PacketFactory.h"
namespace Packets
{
class GCCharJump : public Packet
{
public:
GCCharJump( ){} ;
virtual ~GCCharJump( ){} ;
//公用继承接口
virtual BOOL Read( SocketInputStream& iStream ) ;
virtual BOOL Write( SocketOutputStream& oStream )const ;
virtual UINT Execute( Player* pPlayer ) ;
virtual PacketID_t GetPacketID()const { return PACKET_GC_CHARJUMP; }
virtual UINT GetPacketSize()const { return sizeof(ObjID_t); }
public:
//使用数据接口
VOID setObjID(ObjID_t id) { m_ObjID = id; }
ObjID_t getObjID(VOID)const { return m_ObjID; }
private:
ObjID_t m_ObjID; // ObjID
};
class GCCharJumpFactory : public PacketFactory
{
public:
Packet* CreatePacket() { return new GCCharJump() ; }
PacketID_t GetPacketID()const { return PACKET_GC_CHARJUMP; }
UINT GetPacketMaxSize()const { return sizeof(ObjID_t); }
};
class GCCharJumpHandler
{
public:
static UINT Execute( GCCharJump* pPacket, Player* pPlayer ) ;
};
}
using namespace Packets;
#endif | [
"[email protected]"
]
| |
7f39a4a09d736ac860477da9951d81a3960405c1 | d6895da6461fcf99415ca895e82d57bf425d7ccb | /C++/CppExercises/LinkedList/src/SinglyLinkedList.cpp | 6bc54d9e533854d2c04eeb106943f564da723846 | []
| no_license | MichaelAnthonyP96/LeetCode-Scripts | 9fe14bc4c1356a5cf661bd90d34ab0c691ccc5cc | bbd2c146256f5db5f633a7282bc5a653ef6745b0 | refs/heads/master | 2021-11-22T09:45:13.345656 | 2021-10-01T13:55:23 | 2021-10-01T13:55:23 | 176,650,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,340 | cpp | //
// ListNodeUtilities.cpp
// CppExercises
//
// Created by Michael Anthony Pope on 6/4/19.
// Copyright © 2019 Michael Anthony Pope. All rights reserved.
//
#include "SinglyLinkedList.hpp"
#include <cmath>
#include <stack>
#include <unordered_set>
template<typename T>
SinglyLinkedList<T>::ListNode::ListNode(const T& x) : val(x), next(nullptr)
{
}
template<typename T>
SinglyLinkedList<T>::ListNode::ListNode(T x, ListNode* next) : val(x), next(next)
{
}
template<typename T>
SinglyLinkedList<T>::ListNode::~ListNode() = default;
template<typename T>
SinglyLinkedList<T>::ListNode::ListNode() : val(), next(nullptr)
{
}
template<typename T>
SinglyLinkedList<T>::ListIterator::ListIterator() : p(nullptr)
{
}
template<typename T>
SinglyLinkedList<T>::ListIterator::ListIterator(ListNode* x) : p(x)
{
}
template<typename T>
typename SinglyLinkedList<T>::ListIterator& SinglyLinkedList<T>::ListIterator::operator++()
{
p = p->next;
return *this;
}
template<typename T>
const typename SinglyLinkedList<T>::ListIterator SinglyLinkedList<T>::ListIterator::operator++(int)
{
ListNode* r = p;
p = p->next;
return ListIterator(r);
}
template<typename T>
bool SinglyLinkedList<T>::ListIterator::operator==(const SinglyLinkedList::ListIterator& rhs)
{
if (p == nullptr && rhs.p == nullptr)
{
return true;
}
else if ((p != nullptr && rhs.p == nullptr) || (p == nullptr && rhs.p != nullptr))
{
return false;
}
else
{
return p == rhs.p;
}
}
template<typename T>
bool SinglyLinkedList<T>::ListIterator::operator!=(const SinglyLinkedList::ListIterator& rhs)
{
return p != rhs.p;
}
template<typename T>
const T& SinglyLinkedList<T>::ListIterator::operator*()
{
return p->val;
}
template<typename T>
const T* SinglyLinkedList<T>::ListIterator::operator->()
{
return &(p->val);
}
template<typename T>
typename SinglyLinkedList<T>::ListNode*& SinglyLinkedList<T>::ListIterator::getNode()
{
return p;
}
template<typename T>
SinglyLinkedList<T>::SinglyLinkedList() : m_pHead(nullptr), m_pTail(nullptr), m_length(0)
{
}
template<typename T>
SinglyLinkedList<T>::~SinglyLinkedList()
{
clear();
}
template<class T>
template<class Iter>
SinglyLinkedList<T>::SinglyLinkedList(const Iter& begin_iterator, const Iter& end_iterator) :
m_pHead(nullptr), m_pTail(nullptr), m_length(0)
{
for (Iter i = begin_iterator; i != end_iterator; ++i)
{
insertBack(*i);
}
}
template<typename T>
SinglyLinkedList<T>::SinglyLinkedList(const SinglyLinkedList<T>& other)
{
copy(other);
}
template<typename T>
SinglyLinkedList<T>::SinglyLinkedList(const SinglyLinkedList<T>&& other) noexcept
{
if (this != &other)
{
clear();
m_pHead = std::move(other.m_pHead);
m_pTail = std::move(other.m_pTail);
m_length = std::move(other.m_length);
}
}
template<typename T>
SinglyLinkedList<T>& SinglyLinkedList<T>::operator=(const SinglyLinkedList<T>& rhs)
{
if (this != &rhs)
{
clear();
copy(rhs);
}
return *this;
}
template<typename T>
SinglyLinkedList<T>& SinglyLinkedList<T>::operator=(SinglyLinkedList<T>&& rhs) noexcept
{
if (this != &rhs)
{
clear();
m_pHead = std::move(rhs.m_pHead);
m_pTail = std::move(rhs.m_pTail);
m_length = std::move(rhs.m_length);
}
return *this;
}
template<typename T>
void SinglyLinkedList<T>::copy(const SinglyLinkedList<T>& other)
{
// set up the default, empty list
m_pHead = nullptr;
m_pTail = nullptr;
m_length = 0;
// if we have things to copy
if (!other.empty())
{
ListNode* curr = other.m_pHead;
ListNode* previous = nullptr;
// iterate down the parameter list
while (curr != nullptr)
{
auto* node = new ListNode(curr->data);
// set the head of the new list
if (m_pHead == nullptr)
{
m_pHead = node;
}
// correct pointer of the previous node if it exists
if (previous != nullptr)
{
previous->next = node;
}
previous = node;
curr = curr->next;
}
// prev will contain our new tail---set it up accordingly
m_pTail = previous;
m_pTail->next = nullptr;
m_length = other.m_length;
}
}
template<typename T>
void SinglyLinkedList<T>::clear()
{
ListNode* temp = m_pHead; // points to beginning of linked list
while (temp != nullptr)
{
ListNode* previous = temp; // holds the past link while we move to the next
temp = temp->next; // move onto next link
delete previous; // deletes the old link
}
m_pTail = nullptr; // sets tail and head pointers to null
m_pHead = nullptr;
m_length = 0;
}
template<typename T>
int SinglyLinkedList<T>::size() const
{
return m_length;
}
template<typename T>
void SinglyLinkedList<T>::print(std::ostream& os) const
{
os << "<";
ListNode* curr = m_pHead;
while (curr != nullptr)
{
os << " " << curr->val;
if (curr->next != nullptr)
{
os << ",";
}
curr = curr->next;
}
os << " >";
}
template<typename T>
bool SinglyLinkedList<T>::empty() const
{
return m_pHead == nullptr && m_pTail == nullptr && m_length == 0;
}
template<typename T>
void SinglyLinkedList<T>::insertFront(const T& nData)
{
auto* node = new ListNode(nData);
if (m_pHead == nullptr)
{
// this is the only node in the list
node->next = nullptr;
// now the head and tail point to the new Node
m_pHead = node;
m_pTail = m_pHead;
}
else
{
node->next = m_pHead; // new Node's next is the second Node
m_pHead = node; // head points to the new Node at the front
}
m_length++;
}
template<typename T>
void SinglyLinkedList<T>::insertBack(const T& nData)
{
auto* node = new ListNode(nData);
if (m_pTail == nullptr)
{
// this is the only node in the list
node->next = nullptr;
// now the head and tail point to the new Node
m_pHead = node;
m_pTail = m_pHead;
}
else
{
m_pTail->next = node; // second to last Node's next is the New Node
m_pTail = node; // tail points to the new Node at the back
}
m_length++;
}
template<typename T>
void SinglyLinkedList<T>::reverse()
{
// if the list is empty, or has one node in it. then return
if ((m_pHead == nullptr) || (m_pTail == nullptr) || (m_pHead == m_pTail))
{
return;
}
ListNode* originalFront = m_pHead;
ListNode* originalBack = m_pTail;
// iterate through the list and push pointers onto a stack
ListNode* itr = m_pHead;
std::stack<ListNode*> s;
while (itr != nullptr)
{
s.push(itr);
itr = itr->next;
}
// Assign the first pointer on the stack to the head of the list
itr = m_pHead = s.top();
ListNode* previous = itr;
// Now pop from the stack, assigning the next pointers along the way
while (itr != nullptr)
{
s.pop();
itr = s.top();
if (s.size() == 1)
{
// Assign tail to the last pointer
m_pTail = itr;
}
previous->next = itr;
previous = previous->next;
}
}
template<typename T>
SinglyLinkedList<T> SinglyLinkedList<T>::split(int splitPoint)
{
// split is exceeds the length of the list
// return an empty list
if (splitPoint > m_length || splitPoint < 0)
{
return SinglyLinkedList<T>();
}
//
ListNode* secondHead = split(m_pHead, splitPoint);
int originalLength = m_length;
if (secondHead == m_pHead)
{
// if both heads point to the same place then the list is empty
m_pHead = nullptr;
m_pTail = nullptr;
m_length = 0;
}
else
{
// setup the first list
// marching through the list and finding the end
m_pTail = m_pHead;
while (m_pTail->next != nullptr)
{
m_pTail = m_pTail->next;
}
// reset the length
m_length = splitPoint;
}
// initialize the second list
SinglyLinkedList<T> second;
second.m_pHead = secondHead;
second.m_pTail = secondHead;
// finding the second list's tail
if (second.m_pTail != nullptr)
{
while (second.m_pTail->next != nullptr)
{
second.m_pTail = second.m_pTail->next;
}
}
second.length_ = originalLength - splitPoint;
return second;
}
template<typename T>
SinglyLinkedList<T> SinglyLinkedList<T>::split(ListNode* start, int splitPoint)
{
// empty list edge case
// if its an empty list then return starting point pointer
if (start == NULL || splitPoint <= 0)
{
return start;
}
else
{
ListNode* temp1 = m_pHead;
ListNode* otherTail = nullptr;
while (splitPoint > 0)
{
// move down the list until you get to the startPoint of list 2
--splitPoint;
temp1 = temp1->next;
if (splitPoint == 1)
{
// now I am at the end of the other list, I need this pointer to disconnect the two
// Lists
otherTail = temp1;
}
}
otherTail->next = nullptr;
return temp1;
}
}
template<typename T>
typename SinglyLinkedList<T>::ListNode* SinglyLinkedList<T>::merge(
SinglyLinkedList::ListNode* first, SinglyLinkedList::ListNode* second)
{
// two empty lists, return NULL
if (first == nullptr && second == nullptr)
{
return nullptr;
}
// merging the same list, results in the same list
if (first == second)
{
return first;
}
// if one is empty then return the other
if (first == nullptr)
{
return second;
}
if (second == nullptr)
{
return first;
}
ListNode* returnHead = first;
ListNode* tempFirst = first;
ListNode* tempSecond = second;
ListNode* tempFinal = returnHead;
// Initializes the pointers before iterating down the lists
// whichever list has the smaller starting node, place the
// start of the resulting list there
if (first->data < second->data)
{
tempFirst = first->next;
}
else
{
returnHead = second;
tempFinal = returnHead;
tempSecond = second->next;
}
// Now iterate now both lists, extracting the smaller value
while (tempFirst != nullptr && tempSecond != nullptr)
{
if (tempFirst->data < tempSecond->data || tempSecond == nullptr)
{
// first's data is smaller, so the final's next points to that data
tempFinal->next = tempFirst;
// move the resulting pointer up one up the final list
tempFinal = tempFinal->next;
// move the first pointer up one on the first list
tempFirst = tempFirst->next;
}
else
{
// second's data is smaller, so the final's next points to that data
tempFinal->next = tempSecond;
// move the resulting pointer up one up the final list
tempFinal = tempFinal->next;
// move the second pointer up one on the second list
tempSecond = tempSecond->next;
}
}
// now either the first or second list's pointer points to nullptr
if (tempFirst == nullptr)
{
// now the rest of the final list is what remains of the second list
tempFinal->next = tempSecond;
}
if (tempSecond == nullptr)
{
// now the rest of the final list is what remains of the first list
tempFinal->next = tempFirst;
}
return returnHead;
}
template<typename T>
void SinglyLinkedList<T>::mergeWith(SinglyLinkedList<T> const& otherList)
{
// set up the current list
m_pHead = merge(m_pHead, otherList.m_pHead);
m_pTail = m_pHead;
// make sure there is a node in the new list
if (m_pTail != nullptr)
{
while (m_pTail->next != nullptr)
{
m_pTail = m_pTail->next;
}
}
m_length = m_length + otherList.m_length;
// empty out the parameter list
otherList.m_pHead = nullptr;
otherList.m_pTail = nullptr;
otherList.m_length = 0;
}
template<typename T>
void SinglyLinkedList<T>::sort()
{
if (m_pHead == nullptr || m_pHead->next == nullptr)
{
return;
}
ListNode* currHead = m_pHead;
ListNode *itr, *currMin;
while (currHead->next != nullptr)
{
itr = currHead->next;
currMin = currHead;
while (itr != nullptr)
{
if (itr->val < currMin->val)
{
currMin = itr;
}
itr = itr->next;
}
T tmp = currHead->val;
currHead->val = currMin->val;
currMin->val = tmp;
currHead = currHead->next;
}
}
/**
* \brief Remove duplicate nodes from the linked list, assumes the list is already sorted
* \tparam T type of the value contained in the linked list
*/
template<typename T>
void SinglyLinkedList<T>::removeDuplicates()
{
if (m_pHead == nullptr || m_pHead->next == nullptr)
{
// base case
return;
}
SinglyLinkedList<T>::ListIterator itr(this->begin());
while (itr != this->end() && itr.getNode()->next != nullptr)
{
// if the current value and the next are the same, skip over the next Node and try again
if (*itr == *(++itr))
{
deleteNode(find(*itr));
}
}
}
/**
* You are given two non-empty linked lists representing two non-negative
* integers. The digits are stored in reverse order and each of their nodes
* contain a single digit. Add the two numbers and return it as a linked
* list.You may assume the two numbers do not contain any leading zero, except
* the number 0 itself.
* \param
* \param
* \return
*/
template<typename T>
SinglyLinkedList<T>* SinglyLinkedList<T>::addTwoNumbers(SinglyLinkedList<T>& l1,
SinglyLinkedList<T>& l2)
{
SinglyLinkedList<T>::ListIterator itr1(l1.begin());
SinglyLinkedList<T>::ListIterator itr2(l2.begin());
if (itr1 == l1.end() && itr2 == l2.end())
{
return nullptr;
}
short carryOver = 0;
auto* ret = new SinglyLinkedList<T>();
while (itr1 != l1.end() && itr2 != l2.end())
{
if (*itr1 + *itr2 + carryOver < 10)
{
ret->insertBack(*itr1 + *itr2 + carryOver);
carryOver = 0;
}
else
{
short temp = (*itr1 + *itr2 + carryOver);
ret->insertBack(temp % 10);
carryOver = (T)temp / 10;
}
itr1++;
itr2++;
}
// list2 is longer than list1, copy the remaining values from list2
if (itr1 == l1.end() && itr2 != l2.end())
{
while (itr2 != l2.end())
{
ret->insertBack(*itr2);
itr2++;
}
}
// list1 is longer than list2, copy the remaining values from list1
if (itr2 == l2.end() && itr1 != l1.end())
{
while (itr1 != l1.end())
{
ret->insertBack(*itr1);
itr1++;
}
}
return ret;
}
template<typename T>
T SinglyLinkedList<T>::linkedListToInteger()
{
// return value
T ret = 0;
// exponent value used to march through linked list
int exponent = 0;
SinglyLinkedList<int>::ListIterator itr(this->begin());
// until the end of the list
while (itr != this->end())
{
// Power function is accurately enlarge the current value by the proper
// power of ten
ret += (*itr * pow(10, exponent));
// increment the exponent and move onto the next Node
exponent++;
++itr;
}
return ret;
}
/**
* \brief Convert an integer to a linked list of nodes representing the digits
* of the original number
* @param num Integer to convert to a linked list
* @return ListNode* to the head of the resulting List
*/
template<typename T>
SinglyLinkedList<T>* SinglyLinkedList<T>::integerToLinkedList(T num)
{
// save the head of the list to return
auto* list = new SinglyLinkedList<T>();
// while the number is not zero
while (num > 0)
{
// create a new node initialized to the last digit in the number to attach
// to the end of the list
list->insertFront(num % 10);
// remove the last digit
num /= 10;
}
return list;
}
/**
* Given a non-empty, singly linked list with head node head, return a middle
* node of the linked list. If there are two middle nodes, return the second
* middle node. O(n) time, O(1) space
*/
template<typename T>
typename SinglyLinkedList<T>::ListNode* SinglyLinkedList<T>::middleNode()
{
int count = 0;
ListNode* temp = m_pHead;
for (; temp != nullptr; temp = temp->next)
{
count++;
}
count = (count / 2) + 1;
temp = m_pHead;
for (int i = 1; i < count; i++)
{
temp = temp->next;
}
return temp;
}
/**
* Write a function to delete a node (except the tail) in a singly linked list,
* given only access to that node. The linked list will have at least two
* elements. All of the nodes' values will be unique. The given node will not be
* the tail and it will always be a valid node of the linked list.
*/
template<typename T>
void SinglyLinkedList<T>::deleteNode(SinglyLinkedList<T>::ListIterator deleteNode)
{
SinglyLinkedList<T>::ListIterator itr(this->begin());
// Search for the node before the node to delete
while (itr != this->end())
{
if (itr.getNode()->next == deleteNode.getNode())
{
// We found the previous node to the one we wish to delete
break;
}
++itr;
}
itr.getNode()->next = deleteNode.getNode()->next;
delete deleteNode.getNode();
m_length--;
}
/**
* \brief insertion sort implementation O(n^2) method
*
* \param head Beginning of the linked list to be sorted
* \return Beginning of the sorted linked list
*/
template<typename T>
typename SinglyLinkedList<T>::ListNode* SinglyLinkedList<T>::insertionSort(ListNode* head)
{
if (head == nullptr || head->getNext() == nullptr)
return head;
ListNode* currHead = head;
ListNode *itr, *currMin;
while (currHead->getNext() != nullptr)
{
itr = currHead->getNext();
currMin = currHead;
while (itr != nullptr)
{
if (itr->getVal() < currMin->getVal())
{
currMin = itr;
}
itr = itr->getNext();
}
T tmp = currHead->getVal();
currHead->setVal(currMin->getVal());
currMin->setVal(tmp);
currHead = currHead->getNext();
}
return head;
}
template<typename T>
T SinglyLinkedList<T>::sum(SinglyLinkedList<T>::ListIterator itr)
{
T result {};
while (itr != ListIterator(nullptr))
{
result = result + *itr;
itr++;
}
return result;
}
template<typename T>
typename SinglyLinkedList<T>::ListIterator SinglyLinkedList<T>::find(T searchVal)
{
SinglyLinkedList::ListIterator itr(m_pHead);
while (itr != this->end())
{
if (*(++itr) == searchVal)
{
return itr;
}
}
return SinglyLinkedList<T>::ListIterator();
}
/**
* \brief Helper method to directly pass in a SinglyLinkedList obj when determining if two Lists
* intersect
* \tparam T template parameter stored within each ListNode
* \param lA List object A
* \param lB List object B
* \return The node at which the two lists intersect, if they do at all
*/
template<typename T>
typename SinglyLinkedList<T>::ListNode* SinglyLinkedList<T>::getIntersectionNode(
SinglyLinkedList<T>& lA, SinglyLinkedList<T>& lB)
{
return getIntersectionNode(lA.m_pHead, lB.m_pHead);
}
/**
* \brief Given the heads of two singly linked-lists headA and headB, return the node at which the
* two lists intersect. If the two linked lists have no intersection at all, return nullptr. It is
* guaranteed that there are no cycles anywhere in the entire linked structure. Note that the linked
* lists must retain their original structure after the function returns. LeetCode problem 160
* \tparam T templated parameter stored within each ListNode
* \param headA Starting node for List A
* \param headB Starting Node for List B
* \note O(m + n) runtime, O(1) space
* \return The node at which the two lists intersect, if they do at all
*/
template<typename T>
typename SinglyLinkedList<T>::ListNode* SinglyLinkedList<T>::getIntersectionNode(
SinglyLinkedList::ListNode* headA, SinglyLinkedList::ListNode* headB)
{
ListNode* pA = headA;
ListNode* pB = headB;
while (pA != pB)
{
pA = pA == nullptr ? headB : pA->next;
pB = pB == nullptr ? headA : pB->next;
}
return pA;
}
/**
* \brief append on SinglyLinkedList to another without allocating anymore memory
* \tparam T template parameter stored within each ListNode
* \param otherList to append to the current List calling this method
* \note O(1) runtime, O(1) space
*/
template<typename T>
void SinglyLinkedList<T>::append(const SinglyLinkedList<T>& otherList)
{
this->m_pTail->next = otherList.m_pHead;
}
/**
* \brief Helper method to directly pass in a SinglyLinkedList obj when determining if a list has a
* cycle. LeetCode Problem 141
* \tparam T template parameter stored within each ListNode
* \param l List with which to determine if it has a cycle
* \note O(n) runtime, O(n) space
* \return True or False whether a cycle was detected
*/
template<typename T>
bool SinglyLinkedList<T>::hasCycle(SinglyLinkedList<T>& l)
{
return SinglyLinkedList<T>::hasCycle(l.m_pHead);
}
/**
* \brief Determine whether a list has a cycle. LeetCode Problem 141
* \tparam T template parameter stored within each ListNode
* \param head ListNode* pointing to where you should start searching for a cycle
* \note O(n) runtime, O(n) space
* \return True or False whether a cycle was detected
*/
template<typename T>
bool SinglyLinkedList<T>::hasCycle(SinglyLinkedList::ListNode* head)
{
std::unordered_set<SinglyLinkedList<T>::ListNode*> set;
while (head != nullptr)
{
set.insert(head);
head = head->next;
if (set.find(head) != set.end())
{
return true;
}
}
return false;
}
/**
* \brief Given the head of a singly linked list, return true if it is a palindrome. LeetCode
* Problem 234
* \tparam T template parameter stored in each ListNode
* \param l List with which to determine if its a valid palindrome
* \note O(n) runtime, O(n) space
* \return True or False whether or not the list is a valid palindrome
*/
template<typename T>
bool SinglyLinkedList<T>::isPalindrome(SinglyLinkedList<T>& l)
{
return isPalindrome(l.m_pHead);
}
/**
* \brief Given the head of a singly linked list, return true if it is a palindrome. LeetCode
* Problem 234
* \tparam T template parameter stored in each ListNode
* \param head Start of the list with which to start determining whether or not a is a palindrome
* \note O(n) runtime, O(n) space
* \return True or False whether or not the list is a valid palindrome
*/
template<typename T>
bool SinglyLinkedList<T>::isPalindrome(SinglyLinkedList::ListNode* head)
{
// get the size of the linked list
int size = 0;
std::stack<int> s;
ListNode* itr = head;
while (itr != nullptr)
{
itr = itr->next;
++size;
}
if (size == 1)
{
return true;
}
bool isOdd = (size % 2) == 1;
int idx = 1;
itr = head;
while (itr != nullptr)
{
// push the first half of the list onto a stack
if (idx <= (size / 2))
{
s.push(itr->val);
}
else
{
if (isOdd && (idx == ((size / 2) + 1)))
{
// ignore the middle most node on odd length linked lists
}
else
{
if (s.top() != itr->val)
{
// Check that the node onto of the stack is equal to the current
return false;
}
s.pop();
}
}
itr = itr->next;
++idx;
}
return true;
}
/**
* \brief Given the head of a linked list and an integer val, remove all the nodes of the linked
* list that has Node.val == val, and return the new head. LeetCode Problem 203.
* \tparam T template parameter stored in each ListNode
* \param l A SinglyLinkedList obj to perform this on, afterwards the function the values have been
* removed from this List
* \param val Value(s) to remove from the linked list
* \note O(n) runtime, O(1) space
*/
template<typename T>
void SinglyLinkedList<T>::removeElements(SinglyLinkedList<T>& l, int val)
{
SinglyLinkedList<T>::removeElements(l.m_pHead, l.m_pTail, val);
}
/**
* \brief Given the head of a linked list and an integer val, remove all the nodes of the linked
* list that has Node.val == val, and return the new head. LeetCode Problem 203.
* \tparam T template parameter stored in each ListNode
* \param head ListNode* pointer to the start of the linked list, updated during the function
* \param tail ListNode* pointer to the end of the linked list, updated during the function
* \param val Value(s) to remove from the linked list
* \return The new head of the linked list
*/
template<typename T>
void SinglyLinkedList<T>::removeElements(
SinglyLinkedList::ListNode*& head, SinglyLinkedList::ListNode*& tail, int val)
{
// ensure that the head is not the val we want to remove
while(head != nullptr && head->val == val)
{
ListNode* tmp = head;
head = head->next;
delete tmp;
}
// head is now either nullptr, or pointing to the first node that does not match val
// iterate through the list, discarding nodes which match the value
ListNode* itr = head;
ListNode* prev = itr;
while(itr != nullptr)
{
// itr matches the current value, be sure to deallocate the node
if (itr->val == val)
{
// prev should remain the same, since the value is being removed
prev->next = itr->next;
// create a temporary pointer to deallocate our node
ListNode* tmp = itr;
// always move itr forward
itr = itr->next;
// deallocate the node we determined to be a match
delete tmp;
}
else
{
// move prev forward since the value didn't match
prev = itr;
// always move itr forward
itr = itr->next;
}
}
tail = prev;
}
| [
"[email protected]"
]
| |
6b4f54d75daf0fb9789445c4ae2f845d7226894e | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/chrome/browser/chromeos/cros/network_library_impl_stub.h | c7d607514dd34f75343de76f41db690d6937d5bc | [
"BSD-3-Clause"
]
| permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,727 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_CROS_NETWORK_LIBRARY_IMPL_STUB_H_
#define CHROME_BROWSER_CHROMEOS_CROS_NETWORK_LIBRARY_IMPL_STUB_H_
#include "chrome/browser/chromeos/cros/network_library_impl_base.h"
namespace chromeos {
class NetworkLibraryImplStub : public NetworkLibraryImplBase {
public:
NetworkLibraryImplStub();
virtual ~NetworkLibraryImplStub();
virtual void Init() OVERRIDE;
virtual bool IsCros() const OVERRIDE;
// NetworkLibraryImplBase implementation.
virtual void MonitorNetworkStart(const std::string& service_path) OVERRIDE;
virtual void MonitorNetworkStop(const std::string& service_path) OVERRIDE;
virtual void MonitorNetworkDeviceStart(
const std::string& device_path) OVERRIDE;
virtual void MonitorNetworkDeviceStop(
const std::string& device_path) OVERRIDE;
virtual void CallConfigureService(const std::string& identifier,
const DictionaryValue* info) OVERRIDE;
virtual void CallConnectToNetwork(Network* network) OVERRIDE;
virtual void CallRequestWifiNetworkAndConnect(
const std::string& ssid, ConnectionSecurity security) OVERRIDE;
virtual void CallRequestVirtualNetworkAndConnect(
const std::string& service_name,
const std::string& server_hostname,
ProviderType provider_type) OVERRIDE;
virtual void CallDeleteRememberedNetwork(
const std::string& profile_path,
const std::string& service_path) OVERRIDE;
virtual void CallEnableNetworkDeviceType(
ConnectionType device, bool enable) OVERRIDE;
virtual void CallRemoveNetwork(const Network* network) OVERRIDE;
// NetworkLibrary implementation.
virtual void ChangePin(const std::string& old_pin,
const std::string& new_pin) OVERRIDE;
virtual void ChangeRequirePin(bool require_pin,
const std::string& pin) OVERRIDE;
virtual void EnterPin(const std::string& pin) OVERRIDE;
virtual void UnblockPin(const std::string& puk,
const std::string& new_pin) OVERRIDE;
virtual void RequestCellularScan() OVERRIDE;
virtual void RequestCellularRegister(
const std::string& network_id) OVERRIDE;
virtual void SetCellularDataRoamingAllowed(bool new_value) OVERRIDE;
virtual void SetCarrier(const std::string& carrier,
const NetworkOperationCallback& completed) OVERRIDE;
virtual bool IsCellularAlwaysInRoaming() OVERRIDE;
virtual void RequestNetworkScan() OVERRIDE;
virtual void DisconnectFromNetwork(const Network* network) OVERRIDE;
virtual void GetIPConfigs(
const std::string& device_path,
HardwareAddressFormat format,
const NetworkGetIPConfigsCallback& callback) OVERRIDE;
virtual void SetIPParameters(const std::string& service_path,
const std::string& address,
const std::string& netmask,
const std::string& gateway,
const std::string& name_servers,
int dhcp_usage_mask) OVERRIDE;
virtual void RequestNetworkServiceProperties(
const std::string& service_path,
const NetworkServicePropertiesCallback& callback) OVERRIDE;
// For testing only:
// Returns the configurations applied in LoadOncNetworks. The key is the
// network's service path which is mapped to the Shill dictionary.
const std::map<std::string, base::DictionaryValue*>& GetConfigurations();
private:
void CompleteWifiInit();
void CompleteCellularInit();
void CompleteCellularActivate();
void AddStubNetwork(Network* network, NetworkProfileType profile_type);
void AddStubRememberedNetwork(Network* network);
void ConnectToNetwork(Network* network);
void ScanCompleted();
void SendNetworkServiceProperties(
const std::string& service_path,
const NetworkServicePropertiesCallback& callback);
std::string ip_address_;
std::string hardware_address_;
NetworkIPConfigVector ip_configs_;
std::string pin_;
bool pin_required_;
bool pin_entered_;
int network_priority_order_;
WifiNetworkVector disabled_wifi_networks_;
CellularNetworkVector disabled_cellular_networks_;
WimaxNetworkVector disabled_wimax_networks_;
std::map<std::string, base::DictionaryValue*> service_configurations_;
base::WeakPtrFactory<NetworkLibraryImplStub> weak_pointer_factory_;
DISALLOW_COPY_AND_ASSIGN(NetworkLibraryImplStub);
};
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_CROS_NETWORK_LIBRARY_IMPL_STUB_H_
| [
"[email protected]"
]
| |
74ca846d2719e9eb8335aef930bf7a17c35b04d5 | d9a66840bf09cb926de8ee1749a47acc11bcdd05 | /old/Codeforces/379/A.cpp | ddb896ba85f1cc2b5b08eda16a4d9c5278bf67d8 | [
"Unlicense"
]
| permissive | not522/CompetitiveProgramming | b632603a49d3fec5e0815458bd2c5f355e96a84f | a900a09bf1057d37d08ddc7090a9c8b8f099dc74 | refs/heads/master | 2023-05-12T12:14:57.888297 | 2023-05-07T07:36:29 | 2023-05-07T07:36:29 | 129,512,758 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 157 | cpp | #include "template.hpp"
int main() {
int a, b;
cin >> a >> b;
int res = a;
for (; a >= b; a = a / b + a % b) res += a / b;
cout << res << endl;
}
| [
"[email protected]"
]
| |
178fb8497e1a640e4cce177b2f9aaa95a01856c0 | c102d77e7e363d043e017360d329c93b9285a6be | /Sources/Plugins/Model_3DS/3DSModelPlugin.h | f0b759cddf4e3b2604bca5893d0338b9ed632414 | [
"MIT"
]
| permissive | jdelezenne/Sonata | b7b1faee54ea9dbd273eab53a7dedbf106373110 | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | refs/heads/master | 2020-07-15T22:32:47.094973 | 2019-09-01T11:07:03 | 2019-09-01T11:07:03 | 205,662,360 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | h | /*=============================================================================
3DSModelPlugin.h
Project: Sonata Engine
Author: Julien Delezenne
=============================================================================*/
#ifndef _SE_3DSMODELPLUGIN_H_
#define _SE_3DSMODELPLUGIN_H_
namespace SE_3DS
{
#define SE_ID_DATAMODEL_3DS SonataEngine::SE_ID(0x99fb4c44,0xa2d8422a)
#ifdef SE_STATIC
class PluginModule
{
public:
PluginModule();
};
#ifndef SE_LIB
PluginModule g_PluginModule;
#endif
#endif
}
#endif
| [
"[email protected]"
]
| |
bc447784686b40ce08b28edfd1ee05610384ea1f | 54b7f521b0a7ec791b502489cbc3d6eb7f9bb163 | /For/exercicio6.cpp | bd0afb19c10f399133b544c00b44f10cb44df05c | []
| no_license | HenriqueOliveiradaRocha/programcaoealgoritmos | eb3f63a30bcaa501b2b42595d591ea5eb412b326 | 1cb337f0a9afa063f06e6a7f77cdec7ab137340e | refs/heads/master | 2020-03-27T02:18:33.906502 | 2018-11-28T23:49:14 | 2018-11-28T23:49:14 | 145,780,937 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 549 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<locale.h>
int main(){
setlocale(LC_ALL,"Portuguese");
int i;
float a,b,c;
for(i=1;i<=5;i++){
puts("Calculo das medidas de um triâgulo");
puts ("digite o lado A a do triangulo");
scanf("%f", &a);
puts ("digite o lado B do triangulo");
scanf("%f", &b);
puts ("digite o lado C do triangulo");
scanf("%f", &c);
if(a==b && a==c ){printf("equilátero\n");}
else{if(a==b && b!=c || a==c && c!=b){printf("isósceles\n");}
else{if(a!=b && a!=c && b!=c){printf("escaleno\n");}
}
}
}
}
| [
"[email protected]"
]
| |
6656b7907ed3b5c067e5a5358d8f5cfcfda5caaa | c2e6f84b7d97afb7a34de9785f420830c33f79b5 | /7.cpp | 157d95486e4b9f11837ecb164fed85cd0335d078 | []
| no_license | AFutureD/Leetcode | 2b2c294a386aeefcdfa722181d1ec0eda1c253e7 | d3dea93b3ff6993b532ad7d278546d477bc0339c | refs/heads/main | 2023-03-08T08:01:21.292494 | 2021-02-24T13:41:21 | 2021-02-24T13:41:21 | 339,813,527 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | cpp | /*
* @lc app=leetcode id=7 lang=cpp
*
* [7] Reverse Integer
*
* Source : https://leetcode.com/problems/reverse-integer/description/
* Author : AFuture
* Date : 2021-02-18T13:39
*
* algorithms
* Easy (25.90%)
* Total Accepted: 1.4M
* Total Submissions: 5.4M
* Testcase Example: '123'
*
*/
#include "0_pre.h"
// #define INT_MAX 2147483647
// #define INT_MIN (-INT_MAX - 1)
class Solution {
public:
int reverse(int x) {
int ans = 0;
while(x) {
if(ans > INT_MAX / 10 || ans < INT_MIN / 10)
return 0;
ans = ans * 10 + x % 10;
x /= 10;
}
return ans;
}
};
#define TEST(n, e) printf("%12d => %-12d %s!\n", n, s.reverse(n), e == s.reverse(n)?"passed":"failed")
int main() {
Solution s;
//basic cases
TEST( 123, 321);
TEST( -123, -321);
TEST( -100, -1);
TEST( 1002, 2001);
//big integer
TEST( 1463847412, 2147483641);
TEST(-2147447412, -2147447412);
TEST( 2147447412, 2147447412);
//overflow
TEST( 1000000003, 0);
TEST( 2147483647, 0);
TEST(-2147483648, 0);
return 0;
}
| [
"[email protected]"
]
| |
be359c92c2679dd7d40fbbdfbec09ca63bf0e408 | 01ed846bf5367f391711e3799ba58a40d03df67e | /sem2/hw1/2183/B1.cpp | 2dfea86429ba34b681eda1fe57566c84f6b7223d | []
| no_license | katyamineeva/learning-algoritms | a540ed4c9a5cd8bfc25d07d67c59baf3a0ab4bc2 | 0ea7e3f15cbed710f975bef14d83ed2102b62878 | refs/heads/master | 2021-06-08T05:59:16.023426 | 2016-12-03T14:43:46 | 2016-12-03T14:43:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,269 | cpp | #include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using std::ifstream;
using std::cout;
using std::endl;
using std::sort;
using std::vector;
using std::pair;
void readData(vector<pair<int, int>>& segments) {
ifstream fin("input.txt");
int n = 0;
fin >> n;
int segBegin = 0;
int segEnd = 0;
for (int i = 0; i < n; ++i) {
fin >> segBegin >> segEnd;
segments.push_back({segBegin, 0});
segments.push_back({segEnd, 1});
}
}
int cntPainted(vector<pair<int, int>>& segments) {
if (segments.size() == 0) {
return 0;
}
sort(segments.begin(), segments.end());
int res = 0;
int curBalance = 0;
int lastBegin = -1;
for (auto point : segments) {
if (point.second == 0) {
if (curBalance == 0) {
lastBegin = point.first;
}
++curBalance;
} else {
--curBalance;
if (curBalance == 0) {
res += (point.first - lastBegin + 1);
}
}
}
return res;
}
int main() {
vector<pair<int, int>> segments;
readData(segments);
cout << cntPainted(segments);
return 0;
}
| [
"[email protected]"
]
| |
b42073cc78c75560a6dafbcb6879811a6c00d46b | eea2361c7a829f961e2619e2e425a9e205ba9a0a | /main.cpp | 4f610a033eb3e611a5f9ab16dcfe0fae92176e82 | [
"MIT"
]
| permissive | salleaffaire/ISOMP4MP | cbb7fae857820c1005d0b6f062c4b22ddca8b738 | 4cfe24efab541e98ec049d6baef4e8d76a014a38 | refs/heads/master | 2018-12-28T06:46:46.461013 | 2015-02-08T20:43:16 | 2015-02-08T20:43:16 | 29,097,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,108 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "bitextractor.hpp"
#include "mp4parser.hpp"
// TEST CLASSES
// ---------------------------------
class ATOM {
public:
ATOM() {
std::cout << "ATOM C" << std::endl;
}
ATOM(const ATOM &x) {
std::cout << "ATOM CC" << std::endl;
}
~ATOM() {
std::cout << "ATOM D" << std::endl;
}
};
class TEST {
public:
TEST() {
mV.reserve(32);
}
void add(ATOM &&x) {
mV.emplace_back(std::move<ATOM&>(x));
}
std::vector<ATOM> mV;
};
// ------------------------------------
int main(int argc, char *argv[]) {
// TESTS
// -----------------------------------
#if 0
TEST t;
t.add(ATOM());
#endif
std::string filename = "sample_mpeg4.mp4";
// Read the file into memory
// ------------------------------------------
std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
unsigned int filesize = in.tellg();
std::cout << "File size of : " << filesize << " bytes." << std::endl;
// return at the begining
in.seekg(0, in.beg);
// Allocate mem ory for file
unsigned char *filedata = new unsigned char [filesize];
// Read
in.read((char *)filedata, filesize);
in.close();
// Test bit extractor
#if 0
bit_extractor be(filedata, filesize);
unsigned int code0 = be.get_bits(8);
unsigned int code1 = be.get_bits(4);
unsigned int code2 = be.get_bits(4);
unsigned int code3 = be.get_bits(5);
unsigned int code4 = be.get_bits(5);
unsigned int code5 = be.get_bits(6);
std::cout << bit_code{code0, 8} << std::endl;
std::cout << bit_code{code1, 4} << std::endl;
std::cout << bit_code{code2, 4} << std::endl;
std::cout << bit_code{code3, 5} << std::endl;
std::cout << bit_code{code4, 5} << std::endl;
std::cout << bit_code{code5, 6} << std::endl;
#endif
#if 0
// Create the ISO MP4 box tree
mp4tree mp4t;
mp4t.parseboxtree(filedata, filesize);
// Instanciate an MP4 parser
mp4parser mp4p;
#endif
delete [] filedata;
return 0;
}
| [
"[email protected]"
]
| |
dc3227b711c47b8449adbfe1a1d92a1c6d69a090 | 382b263342579db70bc64194148e1a637cf796d3 | /include/File.hpp | 54b133a37ce10912a09102af3c8bb304b20ab879 | []
| no_license | caminin/ResolutionDeProbleme | 3c6d3bea2161d11c9dccd789d69fd24ef343d3eb | a89a30b80cfe14f18ac93570d3fcdff192dc7fff | refs/heads/master | 2021-01-10T13:27:55.384699 | 2017-06-21T13:16:03 | 2017-06-21T13:16:03 | 52,887,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | hpp | #ifndef __MYFILE
#define __MYFILE
#include "Table.hpp"
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
vector<int> &split(const string &s, char delim, vector<int> &elems) ;
vector<int> split(const string &s, char delim);
void parseFile(Table *mytable, vector<Piece*> &mypile,string file_name);
#endif
| [
"[email protected]"
]
| |
04aeb791e6b05df13ea718cf28f91b50d68a87b8 | 89a6e0eca52e0cb31915fa43d9b1ba3f0145b257 | /演算法題型分類/Dynamic-Program/Knapsack_Problem/01-Knapsack/trap/f467-UVa10025.cc | 6fec11205eaf40d2ca0b4a04740fbf85a1f62c83 | []
| no_license | rollfatcat/ProblemSet | 03a3a960ec324b831d3db422a52d623f2d04b6f0 | f9c76320e8812304b73ac348e8e34e8a55e08a10 | refs/heads/master | 2023-04-03T15:48:44.551030 | 2023-03-21T19:09:32 | 2023-03-21T19:09:32 | 191,777,230 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,121 | cc | /* 給定目標數字K,± 1 ± 2 ± 3 …… ± N = K,滿足上述條件最小的 N (N ≧ 1) ?
* 其中「±」代表可以是「加法(正)」或「減法(負)」,從其中擇一。
* 題目盲點:乍看之下是對每個數字調整正負號的01背包分堆問題,但K極大一定是不可能。
* 解題關鍵:數學問題
* K=-K:K和-K的答案只要將每個數字選取的正負號顛倒即可。
* 從 N*(N+1)/2 ≧ K開始枚舉,差值 N*(N+1)/2-K 只要是偶數代表存在一解( 奇數一定不存在解 )?
* + 1 + 2 + 3 …… + X + …… + N 時將X的符號改為負的時候和原本的總和差值為"偶數"
* 差值必定可以透調整任意個數字組成( 將差值的一半轉為二進位後可以知道要調整的是哪幾個 )
*/
#include <bits/stdc++.h>
using namespace std;
const int MaxK=1e9;
int main(){
int caseT, K;
scanf("%d\n",&caseT);
while(caseT-->0){
scanf("%d\n",&K);
if(K<0)
K=-K;
int N=(K==0)? 1:sqrt(K<<1);
for(N+= (N+1)*N<(K<<1); ((N+1)*N/2-K)&1 ; N+=1);
printf("%d\n",N);
}
} | [
"[email protected]"
]
| |
b17f2fafb4a4f8aed19a8e7155234a24ebb1e6f9 | 29a4c1e436bc90deaaf7711e468154597fc379b7 | /modules/gsl_specfun/include/nt2/toolbox/gsl_specfun/function/simd/sse/ssse3/gsl_sf_legendre_p2.hpp | 6aadf4585c492a6b3a9da3994c00262e614d72f3 | [
"BSL-1.0"
]
| permissive | brycelelbach/nt2 | 31bdde2338ebcaa24bb76f542bd0778a620f8e7c | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | refs/heads/master | 2021-01-17T12:41:35.021457 | 2011-04-03T17:37:15 | 2011-04-03T17:37:15 | 1,263,345 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 770 | hpp | //////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_SSE_SSSE3_GSL_SF_LEGENDRE_P2_HPP_INCLUDED
#define NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_SSE_SSSE3_GSL_SF_LEGENDRE_P2_HPP_INCLUDED
#include <nt2/toolbox/gsl_specfun/function/simd/sse/sse3/gsl_sf_legendre_P2.hpp>
#endif
| [
"[email protected]"
]
| |
2893761b7f2446bdb3eee7eecbea222154de2e34 | 2694f0524ff14dd619ab8a2b56257308ea0d55b3 | /src/collector.cpp | 3c4fa395dd4ba71c6330730f1cfc77de00693461 | []
| no_license | xdgc/python-condor | fa0531f5336313c65ceadf31e349cb734ae3c8c9 | 4e2af78095b050dd74c474b3235426939ad30c34 | refs/heads/master | 2021-01-16T21:49:42.198869 | 2013-01-04T01:05:32 | 2013-01-04T01:05:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,898 | cpp |
#include "condor_adtypes.h"
#include "dc_collector.h"
#include "condor_version.h"
#include <memory>
#include <boost/python.hpp>
#include "old_boost.h"
#include "classad_wrapper.h"
using namespace boost::python;
AdTypes convert_to_ad_type(daemon_t d_type)
{
AdTypes ad_type = NO_AD;
switch (d_type)
{
case DT_MASTER:
ad_type = MASTER_AD;
break;
case DT_STARTD:
ad_type = STARTD_AD;
break;
case DT_SCHEDD:
ad_type = SCHEDD_AD;
break;
case DT_NEGOTIATOR:
ad_type = NEGOTIATOR_AD;
break;
case DT_COLLECTOR:
ad_type = COLLECTOR_AD;
break;
default:
PyErr_SetString(PyExc_ValueError, "Unknown daemon type.");
throw_error_already_set();
}
return ad_type;
}
struct Collector {
Collector(const std::string &pool="")
: m_collectors(NULL)
{
if (pool.size())
m_collectors = CollectorList::create(pool.c_str());
else
m_collectors = CollectorList::create();
}
~Collector()
{
if (m_collectors) delete m_collectors;
}
object query(AdTypes ad_type, const std::string &constraint, list attrs)
{
CondorQuery query(ad_type);
if (constraint.length())
{
query.addANDConstraint(constraint.c_str());
}
std::vector<const char *> attrs_char;
std::vector<std::string> attrs_str;
int len_attrs = py_len(attrs);
if (len_attrs)
{
attrs_str.reserve(len_attrs);
attrs_char.reserve(len_attrs+1);
attrs_char[len_attrs] = NULL;
for (int i=0; i<len_attrs; i++)
{
std::string str = extract<std::string>(attrs[i]);
attrs_str.push_back(str);
attrs_char[i] = attrs_str[i].c_str();
}
query.setDesiredAttrs(&attrs_char[0]);
}
ClassAdList adList;
QueryResult result = m_collectors->query(query, adList, NULL);
switch (result)
{
case Q_OK:
break;
case Q_INVALID_CATEGORY:
PyErr_SetString(PyExc_RuntimeError, "Category not supported by query type.");
boost::python::throw_error_already_set();
case Q_MEMORY_ERROR:
PyErr_SetString(PyExc_MemoryError, "Memory allocation error.");
boost::python::throw_error_already_set();
case Q_PARSE_ERROR:
PyErr_SetString(PyExc_SyntaxError, "Query constraints could not be parsed.");
boost::python::throw_error_already_set();
case Q_COMMUNICATION_ERROR:
PyErr_SetString(PyExc_IOError, "Failed communication with collector.");
boost::python::throw_error_already_set();
case Q_INVALID_QUERY:
PyErr_SetString(PyExc_RuntimeError, "Invalid query.");
boost::python::throw_error_already_set();
case Q_NO_COLLECTOR_HOST:
PyErr_SetString(PyExc_RuntimeError, "Unable to determine collector host.");
boost::python::throw_error_already_set();
default:
PyErr_SetString(PyExc_RuntimeError, "Unknown error from collector query.");
boost::python::throw_error_already_set();
}
list retval;
ClassAd * ad;
adList.Open();
while ((ad = adList.Next()))
{
boost::shared_ptr<ClassAdWrapper> wrapper(new ClassAdWrapper());
wrapper->CopyFrom(*ad);
retval.append(wrapper);
}
return retval;
}
object locateAll(daemon_t d_type)
{
AdTypes ad_type = convert_to_ad_type(d_type);
return query(ad_type, "", list());
}
object locate(daemon_t d_type, const std::string &name)
{
std::string constraint = ATTR_NAME " =?= \"" + name + "\"";
object result = query(convert_to_ad_type(d_type), constraint, list());
if (py_len(result) >= 1) {
return result[0];
}
PyErr_SetString(PyExc_ValueError, "Unable to find daemon.");
throw_error_already_set();
return object();
}
ClassAdWrapper *locateLocal(daemon_t d_type)
{
Daemon my_daemon( d_type, 0, 0 );
ClassAdWrapper *wrapper = new ClassAdWrapper();
if (my_daemon.locate())
{
classad::ClassAd *daemonAd;
if ((daemonAd = my_daemon.daemonAd()))
{
wrapper->CopyFrom(*daemonAd);
}
else
{
std::string addr = my_daemon.addr();
if (!my_daemon.addr() || !wrapper->InsertAttr(ATTR_MY_ADDRESS, addr))
{
PyErr_SetString(PyExc_RuntimeError, "Unable to locate daemon address.");
throw_error_already_set();
}
std::string name = my_daemon.name() ? my_daemon.name() : "Unknown";
if (!wrapper->InsertAttr(ATTR_NAME, name))
{
PyErr_SetString(PyExc_RuntimeError, "Unable to insert daemon name.");
throw_error_already_set();
}
std::string hostname = my_daemon.fullHostname() ? my_daemon.fullHostname() : "Unknown";
if (!wrapper->InsertAttr(ATTR_MACHINE, hostname))
{
PyErr_SetString(PyExc_RuntimeError, "Unable to insert daemon hostname.");
throw_error_already_set();
}
std::string version = my_daemon.version() ? my_daemon.version() : "";
if (!wrapper->InsertAttr(ATTR_VERSION, version))
{
PyErr_SetString(PyExc_RuntimeError, "Unable to insert daemon version.");
throw_error_already_set();
}
const char * my_type = AdTypeToString(convert_to_ad_type(d_type));
if (!my_type)
{
PyErr_SetString(PyExc_ValueError, "Unable to determined daemon type.");
throw_error_already_set();
}
std::string my_type_str = my_type;
if (!wrapper->InsertAttr(ATTR_MY_TYPE, my_type_str))
{
PyErr_SetString(PyExc_RuntimeError, "Unable to insert daemon type.");
throw_error_already_set();
}
std::string cversion = CondorVersion(); std::string platform = CondorPlatform();
if (!wrapper->InsertAttr(ATTR_VERSION, cversion) || !wrapper->InsertAttr(ATTR_PLATFORM, platform))
{
PyErr_SetString(PyExc_RuntimeError, "Unable to insert HTCondor version.");
throw_error_already_set();
}
}
}
else
{
PyErr_SetString(PyExc_RuntimeError, "Unable to locate local daemon");
boost::python::throw_error_already_set();
}
return wrapper;
}
// Overloads for the Collector; can't be done in boost.python and provide
// docstrings.
object query0()
{
return query(ANY_AD, "", list());
}
object query1(AdTypes ad_type)
{
return query(ad_type, "", list());
}
object query2(AdTypes ad_type, const std::string &constraint)
{
return query(ad_type, constraint, list());
}
// TODO: this has crappy error handling when there are multiple collectors.
void advertise(list ads, const std::string &command_str="UPDATE_AD_GENERIC", bool use_tcp=false)
{
m_collectors->rewind();
Daemon *collector;
std::auto_ptr<Sock> sock;
int command = getCollectorCommandNum(command_str.c_str());
if (command == -1)
{
PyErr_SetString(PyExc_ValueError, ("Invalid command " + command_str).c_str());
throw_error_already_set();
}
if (command == UPDATE_STARTD_AD_WITH_ACK)
{
PyErr_SetString(PyExc_NotImplementedError, "Startd-with-ack protocol is not implemented at this time.");
}
int list_len = py_len(ads);
if (!list_len)
return;
compat_classad::ClassAd ad;
while (m_collectors->next(collector))
{
if(!collector->locate()) {
PyErr_SetString(PyExc_ValueError, "Unable to locate collector.");
throw_error_already_set();
}
int list_len = py_len(ads);
sock.reset();
for (int i=0; i<list_len; i++)
{
ClassAdWrapper &wrapper = extract<ClassAdWrapper &>(ads[i]);
ad.CopyFrom(wrapper);
if (use_tcp)
{
if (!sock.get())
sock.reset(collector->startCommand(command,Stream::reli_sock,20));
else
{
sock->encode();
sock->put(command);
}
}
else
{
sock.reset(collector->startCommand(command,Stream::safe_sock,20));
}
int result = 0;
if (sock.get()) {
result += ad.put(*sock);
result += sock->end_of_message();
}
if (result != 2) {
PyErr_SetString(PyExc_ValueError, "Failed to advertise to collector");
throw_error_already_set();
}
}
sock->encode();
sock->put(DC_NOP);
sock->end_of_message();
}
}
private:
CollectorList *m_collectors;
};
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(advertise_overloads, advertise, 1, 3);
void export_collector()
{
class_<Collector>("Collector", "Client-side operations for the HTCondor collector")
.def(init<std::string>(":param pool: Name of collector to query; if not specified, uses the local one."))
.def("query", &Collector::query0)
.def("query", &Collector::query1)
.def("query", &Collector::query2)
.def("query", &Collector::query,
"Query the contents of a collector.\n"
":param ad_type: Type of ad to return from the AdTypes enum; if not specified, uses ANY_AD.\n"
":param constraint: A constraint for the ad query; defaults to true.\n"
":param attrs: A list of attributes; if specified, the returned ads will be "
"projected along these attributes.\n"
":return: A list of ads in the collector matching the constraint.")
.def("locate", &Collector::locateLocal, return_value_policy<manage_new_object>())
.def("locate", &Collector::locate,
"Query the collector for a particular daemon.\n"
":param daemon_type: Type of daemon; must be from the DaemonTypes enum.\n"
":param name: Name of daemon to locate. If not specified, it searches for the local daemon.\n"
":return: The ad of the corresponding daemon.")
.def("locateAll", &Collector::locateAll,
"Query the collector for all ads of a particular type.\n"
":param daemon_type: Type of daemon; must be from the DaemonTypes enum.\n"
":return: A list of matching ads.")
.def("advertise", &Collector::advertise, advertise_overloads(
"Advertise a list of ClassAds into the collector.\n"
":param ad_list: A list of ClassAds.\n"
":param command: A command for the collector; defaults to UPDATE_AD_GENERIC;"
" other commands, such as UPDATE_STARTD_AD, may require reduced authorization levels.\n"
":param use_tcp: When set to true, updates are sent via TCP."))
;
}
| [
"[email protected]"
]
| |
ab28d2662c02533f392c39972707f7da263fbc88 | b7128624d25b8a34431751fe504e3c8ad79ee0ce | /src/protocols/coap/impl/coapserver.cc | a0c16ab500dc37b63be35c4433ebd38e5a522701 | [
"LicenseRef-scancode-x11-xconsortium-veillard",
"BSD-2-Clause"
]
| permissive | DOORS-Framework/DOORS | e7a0e9d84064334822f20722ad48d9330ee9368f | 999343fc3a40d9c5ec6e8ef7b46cce95bc751fcd | refs/heads/master | 2022-03-31T16:07:06.960467 | 2019-12-23T15:06:31 | 2019-12-23T15:06:31 | 209,012,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,420 | cc |
#include "coapserver.hh"
CoAPServerSM :: CoAPServerSM(void)
: states (2), events(5)
{
execute [0][0] = &CoAPserverTask :: listen_default;
execute [1][0] = &CoAPserverTask :: listen_CON;
execute [2][0] = &CoAPserverTask :: listen_default;
execute [3][0] = &CoAPserverTask :: listen_default;
execute [4][0] = &CoAPserverTask :: listen_default;
execute [0][1] = &CoAPserverTask :: wait_default;
execute [1][1] = &CoAPserverTask :: wait_default;
execute [2][1] = &CoAPserverTask :: wait_ACK;
execute [3][1] = &CoAPserverTask :: wait_RST;
execute [4][1] = &CoAPserverTask :: wait_ACKtimeout;
}
CoAPServerSM :: ~CoAPServerSM(void) {
}
bool CoAPServerSM :: transit (EventType t, Message *msg, PTask *h) {
int msgId = 0;
if (t == SystemEvent) {
msgId = 4;
} else
if (msg->getTarget () == &((CoAPserverTask *) h)->peer) {
switch(msg->getType ()) {
case CoAPPeer :: rst :
msgId = 3;
break;
case CoAPPeer :: ack :
msgId = 2;
break;
case CoAPPeer :: con :
msgId = 1;
break;
}
}
return (((CoAPserverTask*) h)->*execute [msgId][h->getState ()]) (msg);
}
std::string CoAPServerSM :: stateName (PTask *h) {
const char *rc = 0;
switch (h->getState ()) {
case 0 :
rc = "Listen";
break;
case 1 :
rc = "Wait";
break;
default:
rc = 0;
}
return rc;
}
| [
"[email protected]"
]
| |
e849892bc730743c33ae4f255001b763e622907b | 359b55a2f58978009e9a825defe2e16042becc55 | /BS-Thesis/Code-Project/Yacc - Intermediate Parser/Phase1/main.cpp | 13eea321ace5f1d94cf40104a6454a9a42dc30f5 | []
| no_license | emadpres/BS | 65bc48389c75bbcfaf15886fd42e8278ef7b6068 | 3ef94281100256f2e22d9f27b12eb3a387a839b5 | refs/heads/master | 2023-02-27T21:06:12.978361 | 2021-02-06T23:30:13 | 2021-02-06T23:30:13 | 336,388,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 393 | cpp | #define _HAS_EXCEPTIONS 0 // because of cl.exe warning. more: http://stackoverflow.com/questions/552695/how-can-i-switch-off-exception-handling-in-msvc
#include <iostream>
extern "C"
int StartParsing(char inputFile[100]);
extern "C"
void cppFunc()
{
}
void main(int arg_count,char ** arg_values)
{
if(arg_count<=1)
StartParsing("test.cpp");
else
StartParsing(arg_values[1]);
} | [
"[email protected]"
]
| |
c35b5c0d32624d65d4c4d44edf6ccbfec5efc88a | 262fd9f5c73abd3a778b4b77be65fc8f9bc13334 | /src/perftesting/runcase.cpp | d8ca3b58bbe13ffc0d6100343f3cb0e9084c5817 | []
| no_license | Slaedr/Struct3d | 532f2eb80432fb19aed73592e9e47a9d23ff7e61 | 604a9f8581a814b66154c3dbfdca69185fa41e4e | refs/heads/master | 2021-06-20T00:38:24.034442 | 2019-03-23T00:02:02 | 2019-03-23T00:02:02 | 164,519,442 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,760 | cpp | #undef NDEBUG
#include <cfloat>
#include <cassert>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <petscsys.h>
#include "pde/pdefactory.hpp"
#include "common_utils.hpp"
#include "case.hpp"
#include "linalg/solverfactory.hpp"
#include "scaling_openmp.hpp"
#define PETSCOPTION_STR_LEN 30
int main(int argc, char* argv[])
{
if(argc < 3) {
printf("Please specify a control file and a Petsc options file.\n");
return 0;
}
char help[] = "Compares PETSc solvers with Struct3d native solvers.\
Arguments: (1) Control file (2) Petsc options file\n\n";
const char *confile = argv[1];
int ierr = 0;
ierr = PetscInitialize(&argc, &argv, NULL, help); CHKERRQ(ierr);
MPI_Comm comm = MPI_COMM_WORLD;
const int mpisize = get_mpi_size(comm);
const int mpirank = get_mpi_rank(comm);
if(mpirank == 0)
printf("Number of MPI ranks = %d.\n", mpisize);
if(mpisize > 1) {
printf("Multi-process runs are nor yet supported!\n");
PetscFinalize();
exit(-1);
}
#ifdef _OPENMP
const int nthreads = omp_get_max_threads();
if(mpirank == 0)
printf("Max OMP threads = %d\n", nthreads);
#endif
// Read control file
FILE* conf = fopen(confile, "r");
const CaseData cdata = readCtrl(conf);
fclose(conf);
printf("PDE: %s\n", cdata.pdetype.c_str());
const PDEBase *const pde = construct_pde(cdata);
if(mpirank == 0) {
printf("Domain boundaries in each dimension:\n");
for(int i = 0; i < NDIM; i++)
printf("%f %f ", cdata.rmin[i], cdata.rmax[i]);
printf("\n");
printf("Number of runs: %d\n", cdata.nruns);
fflush(stdout);
}
// grid structure - a copy of the mesh is stored by all processes as the mesh structure is very small
CartMesh m;
ierr = m.createMesh(cdata.npdim);
// generate grid
if(cdata.gridtype == S3D_CHEBYSHEV)
m.generateMesh_ChebyshevDistribution(cdata.rmin,cdata.rmax);
else
m.generateMesh_UniformDistribution(cdata.rmin,cdata.rmax);
// Prepare native solver
const SVec b = pde->computeVector(&m, pde->test_rhs());
const SMat A = pde->computeLHS(&m);
// run the solve to be tested as many times as requested
ThreadCaseInfo tci = runcase(m, A, b, cdata.nruns);
printf("Time taken by preconditioner build = %f\n", tci.avg_precbuildtime);
printf("Time taken by all preconditioner applications = %f\n", tci.avg_precapplytime);
printf("Time taken by native linear solver = %f\n\n", tci.avg_solvetime);
printf("Deviation in preconditioner build time = %f\n", tci.dev_precbuildtime);
printf("Deviation in all preconditioner applications time = %f\n\n", tci.dev_precapplytime);
printf("Avg solver iters: %d.\n", tci.avg_niter);
printf("Deviation in solver iters = %f\n\n", tci.dev_niter);
fflush(stdout);
delete pde;
PetscFinalize();
return ierr;
}
| [
"[email protected]"
]
| |
d5e95a3b9a4742f23893ac0fdfd5b550c6085083 | 1fc6d2baa958992adecd42d57e89f979972dc3c5 | /random/cpp/tmp5.cpp | 023fb067690d284f252190a7060abf93fc04116f | []
| no_license | Ritapravo/cpp | b5c56d3b649b0fd2698482e960e39217d547e8fb | 0510f41b5ff5c59126461f4c36b3d05c9b1a362e | refs/heads/master | 2021-08-20T06:30:49.176592 | 2021-07-12T17:43:43 | 2021-07-12T17:43:43 | 216,426,587 | 5 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp | #include<iostream>
using namespace std;
bool strcmp(string s1, string s2){
int n1 = s1.size(), n2 = s2.size();
if(n1!=n2)return false;
for(int i = 0; i<n1; i++)
if(s1[i]!=s2[i])return false;
return true;
}
string strcpy(string s1){
string s2 = "";
int i = 0;
while(s1[i]!='\0')s2 += s1[i++];
return s2;
}
int main(){
string s1 = "alpha";
string s2 = "alpha";
string s3 = strcpy(s2);
cout<<s3<<endl;
}
//g++ "tmp5.cpp" && a
//g++ "F:\cpp\random\tmp5.cpp" && a | [
"[email protected]"
]
| |
61a1caf41e32f82e295ad680e623045bbfd935c1 | c51febc209233a9160f41913d895415704d2391f | /library/ATF/TPI.hpp | 605877585d6a9a43f4c08856f53a98e633bbd5ab | [
"MIT"
]
| permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 265 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <TPIVtbl.hpp>
START_ATF_NAMESPACE
struct TPI
{
TPIVtbl *vfptr;
};
END_ATF_NAMESPACE
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.