blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3ad9eeea23707c42411cfa025214d4960191bffa | 192507eec73ab6736b5ecc90b8ba160aed090ad0 | /KCheckPoint.cpp | 54322330c3cc64414ecba8d861aa925e475b5815 | [] | no_license | SaadNoor555/cp-practice | 615af29e949e319d6ea058b12c5d2d81d07eaa5d | 70022373ed74017ae30e7c1ae381450f09f37c73 | refs/heads/master | 2023-07-01T05:16:44.071798 | 2021-08-08T21:05:45 | 2021-08-08T21:05:45 | 318,886,998 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,959 | cpp | /*
---. `
:dmms /dho`
ymmmo ymmh`.///`
.dmmm+-:mmms +mmd`
```` :mmmmmddmmm/ .:-.
`.-:+ossyyyyyyyso+/-.` smmmy/+dmmm.`hhh:
`-/ooooo++-.:+syyyyso+++++++++://oyyys:. hmmm+ .dmmh :mmm-
`+hhyo+++oyddhys+/::::::::::::::-` `:oyhy/` hmmm: :mmms smmm.
.hd+/:::/shhs+/-.```-::::::::::::::----:/+oshh+`-//: -yhh:`hmmh`
yd/:::/shs/:::. -::::::::::::::::::yy/:+ssyy. `` :/+-
yd+/oyho/::::- .:::::::::::::::::::ho .syyh:
`-:ommddo:::::::-` ``-:::::////:::::::::::+d+/. `+ysd/``
`/shhyyhmh/::::::::::::::::/shysshhs/:::::::::+dmd/ :++syyo:.
/dho/::+dy/:::::::::::::::::yh- `-sh+:::::::::+dds.-:::/ooyhds-
/my::::+dy:::::::::::::::::::do :ds:::::+o/::::::::::++++oydy.
`hd/:::/dd/:::::::::::::::::::yd+o/` -hs:::++/:::::::::::::/+++ohd:
`dd::::smo::::::::::::::::::::/hmmmh- -+::::::::::::::::::::::::/hd-
omy+::hd/::::::::::::::::::::::ymmmy``.::::::::::::::::::sh/:::::::+my
:ymddmd::::::::::::::::::::::::+sy+:::::::::::::::::::::+d+::::::::hm-
`.-dd:::::::::://++++++++++//::::::::::::::::::::::+shd+:::::::::sm/
`dd:::::::::+++++++++++++++::::::::::::::::/+oyhdmmmm+:::::::::sm/
hd::::::::+++++++++++++++o/::oo::/++osyhhhyyyhdmmmmmd/::::::::hm-
yd/::::::/++++++++++++++++::ymhhhhyysoo+++++++++shmmmo:::::::+mh`
+ms:::::::++++++++++++++/::/ydh++++++++++++++++++++hmo:::::::hm:
`dd::::::::/++++++++//:::::::+dy++++++++++++++++++odh:::::::ym+.:osys:`
`sms::::::::::::::::::::::::::+hds+++++++++++++oshds/:::::/hdoohyo++ohy.
`+hsyds::::::::::::::::::::::::::/shhhysssssyyhhhhs+/::::::odhohh+:::::/ms
od:``+ds::::::::::::::::::::::::::::/++sssssso+//:::::::/ohmhyds/:::::::dh
hh /hh+:::::::::::::::::::::::::::::::::::::::::::/+shddhhs/::::::::/dy
yd. .sdy+::::::::::::::::::::::::::::::::::::::/oydhs+///::::::::::/ym/
-dy. -ohho+/:::::::::::::::::::::::::::::/+oyhhyoyh+:::::::::::::ohd/
:hdo-` .:syhyo+//::::::::::::::://++osyyhhyyo+/:::ody/:::::::::+hds-
`:shys/-.` ./dmdhhyyyyyyyyyyyyyhhhhhyyso+//::::::--.:yh/:://+oyhhs-
`-/hdys/:yhy+/://+++oooo+++++++//:::::::::::::.````.shhhddhyo:.
yy`-yds/::::::::::::::::::::::::::::::::::.``````.sms:-.
/hydh/::::::::::::://::::::-...........---````````.sd-
.dm/::::::::::::+ss/::::-.````````````````````````.yh.
:my:::::::::::+hd+:::::-```````````````````````````-dy
/my::::::::::smh/::::::`````````````````````````````om:
-md::::::::/hms:::::::-`````````````````````````````-do
smh+/::/+ydh+:::::::::`````````````````````````````.hh`
:sddddddms:::::::::::.`````````````````````````````sd.
`.-.`/m+::::::::::::`````````````````````````````sd.
+d/::::::::::::-````````````````````````````sd.
*/
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<stdio.h>
#include<math.h>
#include<queue>
#define ELIF else if
#define FOR(iterator, limit, adder) for(int iterator=0; iterator<limit; iterator+=adder)
#define PI 3.1415926535897932384626433832795
#define PB push_back
#define OutNO cout<<"NO\n"
#define OutYES cout<<"YES\n"
#define Out(n) cout<< n<<"\n"
#define vint vector<int>
#define vll vector<ll>
#define RED 1
#define BLACK 2
#define lim 1000000007
typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef long long ll;
using namespace std;
void InAr(ll *ar, int n)
{
FOR(i, n, 1) cin>> ar[i];
}
void OutAr(ll *a, int n)
{
FOR(i, n, 1) cout<< a[i]<<" ";
cout<<"\n";
}
void OutVin(vint a)
{
FOR(i, a.size(), 1)
cout<< a[i]<< " ";
cout<< "\n";
}
void MEMSET(bool *a, int n, bool v)
{
FOR(i, n, 1)
a[i]= v;
}
vint g[100001], rg[100001];
vector<ll> p;
bool visited[100001];
vint stack;
vector<ll> cnp;
void dfs(int s)
{
visited[s]= true;
FOR(i, g[s].size(), 1)
if(!visited[g[s][i]])
dfs(g[s][i]);
stack.PB(s);
}
void rdfs(int s)
{
cnp.PB(p[s]);
visited[s]= true;
FOR(i, rg[s].size(), 1)
if(!visited[rg[s][i]])
rdfs(rg[s][i]);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
// cin>> t;
t=1;
while(t--)
{
stack.clear();
int n, m, u, v;
ll tmp, c=0, ans= 1;
cin>> n;
FOR(i, n, 1)
{
cin>> tmp;
p.PB(tmp);
}
cin>> m;
FOR(i, m, 1)
{
cin>> u>> v;
g[u-1].PB(v-1);
rg[v-1].PB(u-1);
}
MEMSET(visited, n, 0);
FOR(i, n, 1)
if(!visited[i]) dfs(i);
MEMSET(visited, n, 0);
for(int i= n-1; i>=0; i--)
if(!visited[stack[i]])
{
cnp.clear();
rdfs(stack[i]);
sort(cnp.begin(), cnp.end());
(c+=cnp[0])%lim;
// cout<< cnp[0]<< " ";
tmp= 0;
FOR(i, cnp.size(), 1)
{
if(cnp[i]==cnp[0]) tmp++;
else break;
}
ans*=tmp;
ans%=lim;
}
// cout<< "\n";
cout<< c<< " "<< ans<< "\n";
}
} | [
"ssaadn.555@gmail.com"
] | ssaadn.555@gmail.com |
59015cc2b7f83c9d9eb87c8a0cf5595f83edb22c | 2899579229ebad17ba554ea24e513b8a887ffcbf | /RpcTransportDesign/OMNeT++Simulation/inet/src/inet/transportlayer/tcp_lwip/TCP_lwIP.h | b38267ff9102cd7ab8af65bc5400b919d393c754 | [] | no_license | Stanley131/Research | b0a2f316a4b604e724b49a48f959e4a149c5672e | c5d978b0bcf1ec02eb6903f6178cb9b228a1d803 | refs/heads/master | 2022-07-13T15:52:08.712122 | 2020-04-15T06:25:53 | 2020-04-15T06:25:53 | 209,621,493 | 1 | 0 | null | 2022-06-22T01:32:10 | 2019-09-19T18:21:32 | C++ | UTF-8 | C++ | false | false | 5,327 | h | //
// Copyright (C) 2006 Sam Jansen, Andras Varga,
// 2010 Zoltan Bojthe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef __INET_TCP_LWIP_H
#define __INET_TCP_LWIP_H
#include <map>
#include "inet/common/INETDefs.h"
#include "inet/common/lifecycle/ILifecycle.h"
#include "inet/networklayer/common/L3Address.h"
#include "inet/transportlayer/contract/tcp/TCPCommand_m.h"
#include "lwip/lwip_tcp.h"
#include "inet/transportlayer/tcp_lwip/LwipTcpStackIf.h"
namespace inet {
// forward declarations:
class TCPOpenCommand;
class TCPSendCommand;
namespace tcp {
// forward declarations:
class TCPSegment;
class TcpLwipConnection;
class TcpLwipReceiveQueue;
class TcpLwipSendQueue;
/**
* Encapsulates a Network Simulation Cradle (NSC) instance.
*/
class INET_API TCP_lwIP : public cSimpleModule, public LwipTcpStackIf, public ILifecycle
{
public:
TCP_lwIP();
virtual ~TCP_lwIP();
protected:
// called by the OMNeT++ simulation kernel:
virtual void initialize(int stage);
virtual int numInitStages() const { return NUM_INIT_STAGES; }
virtual void handleMessage(cMessage *msgP);
virtual void finish();
// LwipTcpStackIf functions:
// sometime pcb is NULL (tipically when send a RESET )
virtual void ip_output(LwipTcpLayer::tcp_pcb *pcb,
L3Address const& src, L3Address const& dest, void *tcpseg, int len);
virtual err_t lwip_tcp_event(void *arg, LwipTcpLayer::tcp_pcb *pcb,
LwipTcpLayer::lwip_event event, struct pbuf *p, u16_t size, err_t err);
virtual void lwip_free_pcb_event(LwipTcpLayer::tcp_pcb *pcb);
virtual netif *ip_route(L3Address const& ipAddr);
virtual void notifyAboutIncomingSegmentProcessing(LwipTcpLayer::tcp_pcb *pcb, uint32 seqNo,
const void *dataptr, int len);
// internal event functions:
err_t tcp_event_accept(TcpLwipConnection& conn, LwipTcpLayer::tcp_pcb *pcb, err_t err);
err_t tcp_event_sent(TcpLwipConnection& conn, u16_t size);
err_t tcp_event_recv(TcpLwipConnection& conn, struct pbuf *p, err_t err);
err_t tcp_event_conn(TcpLwipConnection& conn, err_t err);
err_t tcp_event_poll(TcpLwipConnection& conn);
err_t tcp_event_err(TcpLwipConnection& conn, err_t err);
// internal utility functions:
// find a TcpLwipConnection by connection ID
TcpLwipConnection *findAppConn(int connIdP);
// find a TcpLwipConnection by Lwip pcb
TcpLwipConnection *findConnByPcb(LwipTcpLayer::tcp_pcb *pcb);
virtual void updateDisplayString();
void removeConnection(TcpLwipConnection& conn);
void printConnBrief(TcpLwipConnection& connP);
void handleAppMessage(cMessage *msgP);
void handleIpInputMessage(TCPSegment *tcpsegP);
// to be refined...
void processAppCommand(TcpLwipConnection& connP, cMessage *msgP);
// to be refined and filled in with calls into the NSC stack
void process_OPEN_ACTIVE(TcpLwipConnection& connP, TCPOpenCommand *tcpCommandP, cMessage *msgP);
void process_OPEN_PASSIVE(TcpLwipConnection& connP, TCPOpenCommand *tcpCommandP, cMessage *msgP);
void process_SEND(TcpLwipConnection& connP, TCPSendCommand *tcpCommandP, cPacket *msgP);
void process_CLOSE(TcpLwipConnection& connP, TCPCommand *tcpCommandP, cMessage *msgP);
void process_ABORT(TcpLwipConnection& connP, TCPCommand *tcpCommandP, cMessage *msgP);
void process_STATUS(TcpLwipConnection& connP, TCPCommand *tcpCommandP, cMessage *msgP);
// send a connection established msg to application layer
void sendEstablishedMsg(TcpLwipConnection& connP);
// ILifeCycle:
virtual bool handleOperationStage(LifecycleOperation *operation, int stage, IDoneCallback *doneCallback);
public:
LwipTcpLayer *getLwipTcpLayer() { return pLwipTcpLayerM; }
/**
* To be called from TcpLwipConnection: create a new send queue.
*/
virtual TcpLwipSendQueue *createSendQueue(TCPDataTransferMode transferModeP);
/**
* To be called from TcpLwipConnection: create a new receive queue.
*/
virtual TcpLwipReceiveQueue *createReceiveQueue(TCPDataTransferMode transferModeP);
protected:
typedef std::map<int, TcpLwipConnection *> TcpAppConnMap; // connId-to-TcpLwipConnection
// Maps:
TcpAppConnMap tcpAppConnMapM;
// fast timer message:
cMessage *pLwipFastTimerM;
// network interface:
struct netif netIf;
public:
bool recordStatisticsM; // output vectors on/off
protected:
LwipTcpLayer *pLwipTcpLayerM;
bool isAliveM;
TCPSegment *pCurTcpSegM;
};
} // namespace tcp
} // namespace inet
#endif // ifndef __INET_TCP_LWIP_H
| [
"root@node-0.homa.flowscheduler-pg0.utah.cloudlab.us"
] | root@node-0.homa.flowscheduler-pg0.utah.cloudlab.us |
a3dab03d9d60acd181df1df19e3c40618e8efd0a | e14559ad9c575bff417a24b35922d61879d68830 | /CodeForces/CodeForces Contests/Codeforces 677/1433D.cpp | 830a871fc91a082cade04538a723f9a049731911 | [] | no_license | Biditmangal/CompetitiveProgramming | eb34b2c11d362b899b826fadfddc7caa761e5786 | 19a0efcef60eeff451f62cfbd2ef56cd2067d82e | refs/heads/master | 2021-07-09T21:15:43.453882 | 2021-04-02T17:58:40 | 2021-04-02T17:58:40 | 232,278,122 | 2 | 4 | null | 2021-02-17T18:17:42 | 2020-01-07T08:23:43 | C++ | UTF-8 | C++ | false | false | 1,722 | cpp | #include <math.h>
#include <time.h>
#include <ctype.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
#define sp system("pause")
#define FOR(i, a, b) for (int i = a; i < b; ++i)
#define FORD(i, a, b) for (int i = a; i > b; --i)
#define REP(i, n) FOR(i, 0, (int)n - 1)
#define pb(x) push_back(x)
#define mp(a, b) make_pair(a, b)
#define MS0(x) memset(x, 0, sizeof(x))
#define MS1(x) memset(x, 1, sizeof(x))
#define SORT(a, n) sort(begin(a), begin(a) + n)
#define REV(a, n) reverse(begin(a), begin(a) + n)
#define ll long long
#define pii pair<int, int>
#define MOD 1000000007
void solve()
{
// code goes here...
int n;
cin >> n;
vector<int> a(n);
for (int &v : a)
{
cin >> v;
}
vector<pii> ans;
int idx = -1;
for (int i = 1; i < n; i++)
{
if (a[i] != a[0])
{
idx = i;
ans.push_back({1, i + 1});
}
}
if (idx == -1)
{
cout << "NO\n";
}
else
{
for (int i = 1; i < n; i++)
{
if (a[i] == a[0])
{
ans.push_back({idx + 1, i + 1});
}
}
cout << "YES\n";
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i].first << " " << ans[i].second << endl;
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t = 1;
cin >> t;
while (t--)
solve();
return 0;
} | [
"biditmangal9506@gmail.com"
] | biditmangal9506@gmail.com |
4c40672ce8dbd1fa98a079ae66231731e7b6836b | 0543967d1fcd1ce4d682dbed0866a25b4fef73fd | /Midterm/solutions/midterm2017_94/I/000569-midterm2017_94-I.cpp | e5ce7adcf8bb369780d3f22fe5e85050925cc735 | [] | no_license | Beisenbek/PP12017 | 5e21fab031db8a945eb3fa12aac0db45c7cbb915 | 85a314d47cd067f4ecbbc24df1aa7a1acd37970a | refs/heads/master | 2021-01-19T18:42:22.866838 | 2017-11-25T12:13:24 | 2017-11-25T12:13:24 | 101,155,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 678 | cpp | #include<iostream>
using namespace std;
int main()
{
int i,q=-1,n,m,ans=0,l=0,r=0,j;
cin>>n;
int a[n][n];
if(n%2==0)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>a[i][j];
if(i==j){
//cout<<a[i][j]<<endl;
l=l+a[i][j];
}
else if(i+j==n+1)
{
//cout<<a[i][j]<<endl;
r=r+a[i][j];
}
}
}
cout<<l<<endl<<r;
}
else
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>a[i][j];
if(i==j){
//cout<<a[i][j]<<endl;
l=l+a[i][j];
}
else if(i+j==n+1)
{
//cout<<a[i][j]<<endl;
r=r+a[i][j];
}
}
}
cout<<l<<endl<<r+a[n/2+1][n/2+1];
}
return 0;
}
| [
"beysenbek@gmail.com"
] | beysenbek@gmail.com |
337ac9b2b598e073abf5d8d88a658744a32adb3f | 8413273bab84228dad6ff5247f6d581b7796d142 | /sample/sdl/bomberman/InvertedAABBox2D.h | b5e732fb3ef98d00cfc0b66a2b48f206399d3066 | [] | no_license | pdpdds/yuzaos | 91b6f5bb51583da3827594489fc700821bc5cd6a | ce3b6d0907f7be470fcbc408382a20e2b75e9ef2 | refs/heads/master | 2023-05-01T09:51:21.007740 | 2023-04-27T08:37:42 | 2023-04-27T08:37:42 | 289,303,507 | 28 | 5 | null | 2021-03-20T14:58:37 | 2020-08-21T15:30:10 | C | UTF-8 | C++ | false | false | 1,536 | h | #ifndef INVAABBOX2D_H
#define INVAABBOX2D_H
//-----------------------------------------------------------------------------
//
// Name: InvertedAABBox2D.h
//
// Author: Mat Buckland (www.ai-junkie.com)
//
// Desc: v simple inverted (y increases down screen) axis aligned bounding
// box class
//-----------------------------------------------------------------------------
#include "Vector2D.h"
class InvertedAABBox2D
{
private:
Vector2D m_vTopLeft;
Vector2D m_vBottomRight;
Vector2D m_vCenter;
public:
InvertedAABBox2D(Vector2D tl,
Vector2D br):m_vTopLeft(tl),
m_vBottomRight(br),
m_vCenter((tl+br)/2.0)
{}
//returns true if the bbox described by other intersects with this one
bool isOverlappedWith(const InvertedAABBox2D& other)const
{
return !((other.Top() > this->Bottom()) ||
(other.Bottom() < this->Top()) ||
(other.Left() > this->Right()) ||
(other.Right() < this->Left()));
}
Vector2D TopLeft()const{return m_vTopLeft;}
Vector2D BottomRight()const{return m_vBottomRight;}
float Top()const{return m_vTopLeft.m_y;}
float Left()const{ return m_vTopLeft.m_x; }
float Bottom()const{ return m_vBottomRight.m_y; }
float Right()const{ return m_vBottomRight.m_x; }
Vector2D Center()const{return m_vCenter;}
void Render(bool RenderCenter = false)const
{
}
};
#endif | [
"juhang3@daum.net"
] | juhang3@daum.net |
3779fdaaf3ebca95b417464629237c1e9692f16f | 22e3bcfa87096784c012eea0ec8f7db7515d0a6d | /atividade3/timer-timeouts/timer16bits-timeout/Timeout.cpp | cd23ad75350be5955e1f6e54294723e8f361e8ed | [] | no_license | schaiana/STE | f7548fcbb4cd7357c02170052d568647961e23cd | c52c4b56f0384097c110501fd31a8b2c1fbba4ba | refs/heads/master | 2020-04-04T12:30:03.754014 | 2018-12-06T00:41:15 | 2018-12-06T00:41:15 | 155,928,466 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 624 | cpp | #include "Timeout.h"
namespace Timeout {
Timeout::Timeout() : _event(0), _enable(0), _counter(0){}
Timeout::~Timeout() {}
void Timeout::config(uint32_t interval, CALLBACK_t callback){
_enable = true;
_callback = callback;
_interval = interval;
}
void Timeout::checkTimeout() {
if (_enable) {
_counter++;
if (_counter == _interval) {
_event = true;
_counter = 0;
}
}
}
void Timeout::callback() {
if (_event and _enable) {
(*_callback)();
_event = false;
}
}
bool Timeout::event() {
return _event;
}
void Timeout::enable() {
_enable = true;
}
void Timeout::disable(){
_enable = false;
}
}
| [
"schaianasonaglio@gmail.com"
] | schaianasonaglio@gmail.com |
85aecf646628500afdf9a807f74c16afb18e40c9 | a8a29667e73d3659622d57ea948fbebc85a9ef0b | /LeetCode/ByteDance-1.h | 2fe3897f4a1f9d0a1b684ed31504b3f8a0e0f04c | [] | no_license | cosensible/LeetCode | c352acea6caf5c4737f8e1e96d3bedb2885c96e2 | 1bdf2d09ee4bd286e8f1304020928bdd1467e2b5 | refs/heads/master | 2021-09-09T03:11:41.257058 | 2021-09-06T03:40:48 | 2021-09-06T03:40:48 | 217,175,623 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 754 | h | #include <queue>
#include <vector>
#include <iostream>
using namespace std;
vector<double> getMedium(const vector<int> &nums) {
priority_queue<int> maxQue;
priority_queue<int, vector<int>, greater<int>> minQue;
vector<double> res(nums.size());
for (int i = 0; i < nums.size(); ++i) {
if (minQue.size() == maxQue.size()) {
maxQue.push(nums[i]);
minQue.push(maxQue.top());
maxQue.pop();
res[i] = minQue.top();
}
else {
minQue.push(nums[i]);
maxQue.push(minQue.top());
minQue.pop();
res[i] = (minQue.top() + maxQue.top()) / 2.0;
}
}
return res;
}
void test_ByteDance() {
vector<int> nums = { 3,8,9,2,0,5,7 };
vector<double> res = getMedium(nums);
for (double i : res) {
cout << i << ", ";
}
cout << endl;
} | [
"cosensible@gmail.com"
] | cosensible@gmail.com |
acf91dae4498d53e600a18ce9fb1259c72942b18 | 3cae5a2b4093d86558d4633615ffe0afbc551868 | /src/utils/dialog.cpp | 070c0edb85a0a6637dc0d53656cb2a1b0a49b54a | [
"MIT"
] | permissive | andraantariksa/cit207-polygon-paint | 02a54f0050189c8b95ad390045e695edbb2825da | 06d80a0460d57435037d9257a8f0e4acd6620076 | refs/heads/master | 2022-05-05T13:59:34.534573 | 2022-04-04T08:44:20 | 2022-04-04T08:44:20 | 244,630,214 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 922 | cpp | #include <ctime>
#include <sstream>
#include <tinyfiledialogs.h>
#include "dialog.h"
namespace utils
{
char const* Dialog::save()
{
char const* filter[1] = { "*.svg" };
return tinyfd_saveFileDialog(
"Save file",
Dialog::defaultFilename().c_str(),
1,
filter,
"SVG"
);
}
char const* Dialog::load()
{
char const* filter[1] = { "*.svg" };
return tinyfd_openFileDialog(
"Load file",
"",
1,
filter,
"SVG",
false
);
}
std::string Dialog::defaultFilename()
{
std::time_t now = std::time(nullptr);
std::tm* time_s = std::localtime(&now);
std::stringstream name;
name << time_s->tm_year + 1900;
name << "-";
name << time_s->tm_mon + 1;
name << "-";
name << time_s->tm_mday;
name << "-";
name << time_s->tm_hour + 1;
name << "-";
name << time_s->tm_min + 1;
name << "-";
name << time_s->tm_sec + 1;
name << ".svg";
return name.str();
}
} | [
"andra.antariksa@gmail.com"
] | andra.antariksa@gmail.com |
6708edcb11710ed72a4232caf760e9c4e3f3cc82 | 1568eafac4db833b4313a09ae965af9ef2117933 | /X-Archive/Include/Xavier/Xavier_Inputs.mqh | 65f228fd55faa9f86b370fec2d5552441d95b798 | [] | no_license | yurisa2/Robos-Da-Mamae | dae25208c18734aaff58518913f7a998fb03825f | ae993d74511f8e075fbeca6a90c42c54cacaa694 | refs/heads/master | 2020-04-02T13:28:23.104307 | 2019-04-13T20:01:04 | 2019-04-13T20:01:04 | 154,482,603 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 905 | mqh | /* -*- C++ -*- */
//+------------------------------------------------------------------+
//| SA2 - Investment soft|
//+------------------------------------------------------------------+
#property copyright "Sa2, pq são só dois na empresa agora."
#property link "http://www.sa2.com.br"
ENUM_TIMEFRAMES RSI_TimeFrame = TimeFrame_;
int RSI_period = 14;
ENUM_APPLIED_PRICE RSI_preco = PRICE_CLOSE;
input string Indicadores = "-------------------------------------";
input bool Xavier_Sai_Em_Zero = false; //Sai Quando Neutraliza
input double Xavier_Valor_Venda = 98; //Valor Mínimo para Venda do Fuzzão
input double Xavier_Valor_Compra = -98; //Valor Mínimo para Compra do Fuzzão (Negativo)
int Xavier_Autorizado = 0;
| [
"yuri@sa2.com.br"
] | yuri@sa2.com.br |
51e16c86cb808f2ef3d7541eeffd7a2604dbc9d7 | 2a987bf54ac9901db455b33166eb5144a86919ba | /11. Bit Manipulation/clear_all_bits_from_MSB.cpp | 63c3d3a3512e283fda225723d7903c5d6753b237 | [] | no_license | Maniask/Coding-Ninjas-Competitive-Programming | 92fa20af22e4dc96f4e1d83df8d89ae9baf0d648 | 3a520be2cf9f2f2dc92752d2e10810d7711ec7a9 | refs/heads/main | 2023-02-04T09:14:26.170376 | 2020-12-20T11:53:12 | 2020-12-20T11:53:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cpp |
/*
Clear All Bits From MSB
You are given two integers N and i. You need to clear all bits from MSB to ith bit (start i from right to left)
and return the updated N.
Counting of bits starts from 0 from right to left.
Input Format :
Two integers N and i (separated by space)
Output Format :
Updated N
Sample Input 1 :
15 2
Sample Output 1 :
3
Sample Output 1 Explanation :
We need to clear all bits from MSB to ith bit i.e. clear all bits except 0th and 1st.
Sample Input 2 :
4 4
Sample Output 2 :
4
*/
#include<bits/stdc++.h>
using namespace std;
int clearAllBits(int n, int i){
int a = 1<<i;
int b = a-1;
return n&b;
}
int main(){
int n, i;
cin>>n>>i;
cout<<clearAllBits(n, i);
return 0;
}
| [
"ankur.work11@gmail.com"
] | ankur.work11@gmail.com |
0cff20e4d968f93ad076cc1d90e3b2f28e7d5473 | 0494c9caa519b27f3ed6390046fde03a313d2868 | /src/content/app/content_main_runner.cc | dfab14ffe9e726c168529934e2526c73f00c71b5 | [
"BSD-3-Clause"
] | permissive | mhcchang/chromium30 | 9e9649bec6fb19fe0dc2c8b94c27c9d1fa69da2c | 516718f9b7b95c4280257b2d319638d4728a90e1 | refs/heads/master | 2023-03-17T00:33:40.437560 | 2017-08-01T01:13:12 | 2017-08-01T01:13:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,308 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/app/content_main_runner.h"
#include <stdlib.h>
#include "base/allocator/allocator_extension.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/trace_event.h"
#include "base/files/file_path.h"
#include "base/i18n/icu_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/stats_table.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/process/memory.h"
#include "base/process/process_handle.h"
#include "base/profiler/alternate_timer.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "content/browser/browser_main.h"
#include "content/common/set_process_title.h"
#include "content/common/url_schemes.h"
#include "content/public/app/content_main_delegate.h"
#include "content/public/app/startup_helper_win.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/sandbox_init.h"
#include "crypto/nss_util.h"
#include "ipc/ipc_switches.h"
#include "media/base/media.h"
#include "sandbox/win/src/sandbox_types.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/ui_base_switches.h"
#include "ui/base/win/dpi.h"
#include "webkit/common/user_agent/user_agent.h"
#if defined(USE_TCMALLOC)
#include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
#if defined(TYPE_PROFILING)
#include "base/allocator/type_profiler.h"
#include "base/allocator/type_profiler_tcmalloc.h"
#endif
#endif
#if !defined(OS_IOS)
#include "content/public/plugin/content_plugin_client.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/utility/content_utility_client.h"
#endif
#if defined(OS_WIN)
#include <atlbase.h>
#include <atlapp.h>
#include <malloc.h>
#include <cstring>
#elif defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#if !defined(OS_IOS)
#include "base/power_monitor/power_monitor_device_source.h"
#include "content/browser/mach_broker_mac.h"
#include "content/common/sandbox_init_mac.h"
#endif // !OS_IOS
#endif // OS_WIN
#if defined(OS_POSIX)
#include <signal.h>
#include "base/posix/global_descriptors.h"
#include "content/public/common/content_descriptors.h"
#if !defined(OS_MACOSX)
#include "content/public/common/zygote_fork_delegate_linux.h"
#endif
#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
#include "content/zygote/zygote_main.h"
#endif
#endif // OS_POSIX
#if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
extern "C" {
int tc_set_new_mode(int mode);
}
#endif
namespace content {
extern int GpuMain(const content::MainFunctionParams&);
#if defined(ENABLE_PLUGINS)
extern int PluginMain(const content::MainFunctionParams&);
extern int PpapiPluginMain(const MainFunctionParams&);
extern int PpapiBrokerMain(const MainFunctionParams&);
#endif
extern int RendererMain(const content::MainFunctionParams&);
extern int UtilityMain(const MainFunctionParams&);
extern int WorkerMain(const MainFunctionParams&);
} // namespace content
namespace {
#if defined(OS_WIN)
// In order to have Theme support, we need to connect to the theme service.
// This needs to be done before we lock down the process. Officially this
// can be done with OpenThemeData() but it fails unless you pass a valid
// window at least the first time. Interestingly, the very act of creating a
// window also sets the connection to the theme service.
void EnableThemeSupportOnAllWindowStations() {
HDESK desktop_handle = ::OpenInputDesktop(0, FALSE, READ_CONTROL);
if (desktop_handle) {
// This means we are running in an input desktop, which implies WinSta0.
::CloseDesktop(desktop_handle);
return;
}
HWINSTA current_station = ::GetProcessWindowStation();
DCHECK(current_station);
HWINSTA winsta0 = ::OpenWindowStationA("WinSta0", FALSE, GENERIC_READ);
if (!winsta0) {
DLOG(INFO) << "Unable to open to WinSta0, we: "<< ::GetLastError();
return;
}
if (!::SetProcessWindowStation(winsta0)) {
// Could not set the alternate window station. There is a possibility
// that the theme wont be correctly initialized.
NOTREACHED() << "Unable to switch to WinSta0, we: "<< ::GetLastError();
}
HWND window = ::CreateWindowExW(0, L"Static", L"", WS_POPUP | WS_DISABLED,
CW_USEDEFAULT, 0, 0, 0, HWND_MESSAGE, NULL,
::GetModuleHandleA(NULL), NULL);
if (!window) {
DLOG(WARNING) << "failed to enable theme support";
} else {
::DestroyWindow(window);
window = NULL;
}
// Revert the window station.
if (!::SetProcessWindowStation(current_station)) {
// We failed to switch back to the secure window station. This might
// confuse the process enough that we should kill it now.
LOG(FATAL) << "Failed to restore alternate window station";
}
if (!::CloseWindowStation(winsta0)) {
// We might be leaking a winsta0 handle. This is a security risk, but
// since we allow fail over to no desktop protection in low memory
// condition, this is not a big risk.
NOTREACHED();
}
}
#endif // defined(OS_WIN)
} // namespace
namespace content {
base::LazyInstance<ContentBrowserClient>
g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
#if !defined(OS_IOS) && \
(!defined(CHROME_MULTIPLE_DLL) || defined(CHROME_MULTIPLE_DLL_CHILD))
base::LazyInstance<ContentPluginClient>
g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ContentRendererClient>
g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ContentUtilityClient>
g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
#endif // !OS_IOS
#if defined(OS_WIN)
static CAppModule _Module;
#endif // defined(OS_WIN)
#if defined(OS_POSIX) && !defined(OS_IOS)
// Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
void SetupSignalHandlers() {
// Sanitise our signal handling state. Signals that were ignored by our
// parent will also be ignored by us. We also inherit our parent's sigmask.
sigset_t empty_signal_set;
CHECK(0 == sigemptyset(&empty_signal_set));
CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
struct sigaction sigact;
memset(&sigact, 0, sizeof(sigact));
sigact.sa_handler = SIG_DFL;
static const int signals_to_reset[] =
{SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP}; // SIGPIPE is set below.
for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
}
// Always ignore SIGPIPE. We check the return value of write().
CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
}
#endif // OS_POSIX && !OS_IOS
void CommonSubprocessInit(const std::string& process_type) {
#if defined(OS_WIN)
// HACK: Let Windows know that we have started. This is needed to suppress
// the IDC_APPSTARTING cursor from being displayed for a prolonged period
// while a subprocess is starting.
PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
MSG msg;
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
// Various things break when you're using a locale where the decimal
// separator isn't a period. See e.g. bugs 22782 and 39964. For
// all processes except the browser process (where we call system
// APIs that may rely on the correct locale for formatting numbers
// when presenting them to the user), reset the locale for numeric
// formatting.
// Note that this is not correct for plugin processes -- they can
// surface UI -- but it's likely they get this wrong too so why not.
setlocale(LC_NUMERIC, "C");
#endif
}
static base::ProcessId GetBrowserPid(const CommandLine& command_line) {
base::ProcessId browser_pid = base::GetCurrentProcId();
#if !defined(OS_IOS)
if (command_line.HasSwitch(switches::kProcessChannelID)) {
#if defined(OS_WIN) || defined(OS_MACOSX)
std::string channel_name =
command_line.GetSwitchValueASCII(switches::kProcessChannelID);
int browser_pid_int;
base::StringToInt(channel_name, &browser_pid_int);
browser_pid = static_cast<base::ProcessId>(browser_pid_int);
DCHECK_NE(browser_pid_int, 0);
#elif defined(OS_ANDROID)
// On Android, the browser process isn't the parent. A bunch
// of work will be required before callers of this routine will
// get what they want.
//
// Note: On Linux, base::GetParentProcessId() is defined in
// process_util_linux.cc. Note that *_linux.cc is excluded from
// Android builds but a special exception is made in base.gypi
// for a few files including process_util_linux.cc.
LOG(ERROR) << "GetBrowserPid() not implemented for Android().";
#elif defined(OS_POSIX)
// On linux, we're in a process forked from the zygote here; so we need the
// parent's parent process' id.
browser_pid =
base::GetParentProcessId(
base::GetParentProcessId(base::GetCurrentProcId()));
#endif
}
#endif // !OS_IOS
return browser_pid;
}
static void InitializeStatsTable(const CommandLine& command_line) {
// Initialize the Stats Counters table. With this initialized,
// the StatsViewer can be utilized to read counters outside of
// Chrome. These lines can be commented out to effectively turn
// counters 'off'. The table is created and exists for the life
// of the process. It is not cleaned up.
if (command_line.HasSwitch(switches::kEnableStatsTable)) {
// NOTIMPLEMENTED: we probably need to shut this down correctly to avoid
// leaking shared memory regions on posix platforms.
std::string statsfile =
base::StringPrintf("%s-%u", kStatsFilename,
static_cast<unsigned int>(GetBrowserPid(command_line)));
base::StatsTable* stats_table = new base::StatsTable(statsfile,
kStatsMaxThreads, kStatsMaxCounters);
base::StatsTable::set_current(stats_table);
}
}
class ContentClientInitializer {
public:
static void Set(const std::string& process_type,
ContentMainDelegate* delegate) {
ContentClient* content_client = GetContentClient();
if (process_type.empty()) {
if (delegate)
content_client->browser_ = delegate->CreateContentBrowserClient();
if (!content_client->browser_)
content_client->browser_ = &g_empty_content_browser_client.Get();
}
#if !defined(OS_IOS) && \
(!defined(CHROME_MULTIPLE_DLL) || defined(CHROME_MULTIPLE_DLL_CHILD))
if (process_type == switches::kPluginProcess ||
process_type == switches::kPpapiPluginProcess) {
if (delegate)
content_client->plugin_ = delegate->CreateContentPluginClient();
if (!content_client->plugin_)
content_client->plugin_ = &g_empty_content_plugin_client.Get();
// Single process not supported in split dll mode.
} else if (process_type == switches::kRendererProcess ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess)) {
if (delegate)
content_client->renderer_ = delegate->CreateContentRendererClient();
if (!content_client->renderer_)
content_client->renderer_ = &g_empty_content_renderer_client.Get();
}
if (process_type == switches::kUtilityProcess ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess)) {
if (delegate)
content_client->utility_ = delegate->CreateContentUtilityClient();
// TODO(scottmg): http://crbug.com/237249 Should be in _child.
if (!content_client->utility_)
content_client->utility_ = &g_empty_content_utility_client.Get();
}
#endif // !OS_IOS
}
};
// We dispatch to a process-type-specific FooMain() based on a command-line
// flag. This struct is used to build a table of (flag, main function) pairs.
struct MainFunction {
const char* name;
int (*function)(const MainFunctionParams&);
};
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
// On platforms that use the zygote, we have a special subset of
// subprocesses that are launched via the zygote. This function
// fills in some process-launching bits around ZygoteMain().
// Returns the exit code of the subprocess.
int RunZygote(const MainFunctionParams& main_function_params,
ContentMainDelegate* delegate) {
static const MainFunction kMainFunctions[] = {
{ switches::kRendererProcess, RendererMain },
{ switches::kWorkerProcess, WorkerMain },
#if defined(ENABLE_PLUGINS)
{ switches::kPpapiPluginProcess, PpapiPluginMain },
#endif
{ switches::kUtilityProcess, UtilityMain },
};
scoped_ptr<ZygoteForkDelegate> zygote_fork_delegate;
if (delegate) {
zygote_fork_delegate.reset(delegate->ZygoteStarting());
// Each Renderer we spawn will re-attempt initialization of the media
// libraries, at which point failure will be detected and handled, so
// we do not need to cope with initialization failures here.
base::FilePath media_path;
if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
media::InitializeMediaLibrary(media_path);
}
// This function call can return multiple times, once per fork().
if (!ZygoteMain(main_function_params, zygote_fork_delegate.get()))
return 1;
if (delegate) delegate->ZygoteForked();
// Zygote::HandleForkRequest may have reallocated the command
// line so update it here with the new version.
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
ContentClientInitializer::Set(process_type, delegate);
// If a custom user agent was passed on the command line, we need
// to (re)set it now, rather than using the default one the zygote
// initialized.
if (command_line.HasSwitch(switches::kUserAgent)) {
webkit_glue::SetUserAgent(
command_line.GetSwitchValueASCII(switches::kUserAgent), true);
}
// The StatsTable must be initialized in each process; we already
// initialized for the browser process, now we need to initialize
// within the new processes as well.
InitializeStatsTable(command_line);
MainFunctionParams main_params(command_line);
for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
if (process_type == kMainFunctions[i].name)
return kMainFunctions[i].function(main_params);
}
if (delegate)
return delegate->RunProcess(process_type, main_params);
NOTREACHED() << "Unknown zygote process type: " << process_type;
return 1;
}
#endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
#if !defined(OS_IOS)
// Run the FooMain() for a given process type.
// If |process_type| is empty, runs BrowserMain().
// Returns the exit code for this process.
int RunNamedProcessTypeMain(
const std::string& process_type,
const MainFunctionParams& main_function_params,
ContentMainDelegate* delegate) {
static const MainFunction kMainFunctions[] = {
#if !defined(CHROME_MULTIPLE_DLL) || defined(CHROME_MULTIPLE_DLL_BROWSER)
{ "", BrowserMain },
#endif
#if !defined(CHROME_MULTIPLE_DLL) || defined(CHROME_MULTIPLE_DLL_CHILD)
#if defined(ENABLE_PLUGINS)
{ switches::kPluginProcess, PluginMain },
{ switches::kWorkerProcess, WorkerMain },
{ switches::kPpapiPluginProcess, PpapiPluginMain },
{ switches::kPpapiBrokerProcess, PpapiBrokerMain },
#endif // ENABLE_PLUGINS
{ switches::kUtilityProcess, UtilityMain },
{ switches::kRendererProcess, RendererMain },
{ switches::kGpuProcess, GpuMain },
#endif // !CHROME_MULTIPLE_DLL || CHROME_MULTIPLE_DLL_CHILD
};
for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
if (process_type == kMainFunctions[i].name) {
if (delegate) {
int exit_code = delegate->RunProcess(process_type,
main_function_params);
#if defined(OS_ANDROID)
// In Android's browser process, the negative exit code doesn't mean the
// default behavior should be used as the UI message loop is managed by
// the Java and the browser process's default behavior is always
// overridden.
if (process_type.empty())
return exit_code;
#endif
if (exit_code >= 0)
return exit_code;
}
return kMainFunctions[i].function(main_function_params);
}
}
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
// Zygote startup is special -- see RunZygote comments above
// for why we don't use ZygoteMain directly.
if (process_type == switches::kZygoteProcess)
return RunZygote(main_function_params, delegate);
#endif
// If it's a process we don't know about, the embedder should know.
if (delegate)
return delegate->RunProcess(process_type, main_function_params);
NOTREACHED() << "Unknown process type: " << process_type;
return 1;
}
#endif // !OS_IOS
class ContentMainRunnerImpl : public ContentMainRunner {
public:
ContentMainRunnerImpl()
: is_initialized_(false),
is_shutdown_(false),
completed_basic_startup_(false),
delegate_(NULL) {
#if defined(OS_WIN)
memset(&sandbox_info_, 0, sizeof(sandbox_info_));
#endif
}
virtual ~ContentMainRunnerImpl() {
if (is_initialized_ && !is_shutdown_)
Shutdown();
}
#if defined(USE_TCMALLOC)
static bool GetAllocatorWasteSizeThunk(size_t* size) {
size_t heap_size, allocated_bytes, unmapped_bytes;
MallocExtension* ext = MallocExtension::instance();
if (ext->GetNumericProperty("generic.heap_size", &heap_size) &&
ext->GetNumericProperty("generic.current_allocated_bytes",
&allocated_bytes) &&
ext->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
&unmapped_bytes)) {
*size = heap_size - allocated_bytes - unmapped_bytes;
return true;
}
DCHECK(false);
return false;
}
static void GetStatsThunk(char* buffer, int buffer_length) {
MallocExtension::instance()->GetStats(buffer, buffer_length);
}
static void ReleaseFreeMemoryThunk() {
MallocExtension::instance()->ReleaseFreeMemory();
}
#endif
#if defined(OS_WIN)
virtual int Initialize(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox_info,
ContentMainDelegate* delegate) OVERRIDE {
// argc/argv are ignored on Windows; see command_line.h for details.
int argc = 0;
char** argv = NULL;
RegisterInvalidParamHandler();
_Module.Init(NULL, static_cast<HINSTANCE>(instance));
sandbox_info_ = *sandbox_info;
#else // !OS_WIN
virtual int Initialize(int argc,
const char** argv,
ContentMainDelegate* delegate) OVERRIDE {
#if defined(OS_ANDROID)
// See note at the initialization of ExitManager, below; basically,
// only Android builds have the ctor/dtor handlers set up to use
// TRACE_EVENT right away.
TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
#endif // OS_ANDROID
// NOTE(willchan): One might ask why these TCMalloc-related calls are done
// here rather than in process_util_linux.cc with the definition of
// EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
// dependency on TCMalloc. Really, we ought to have our allocator shim code
// implement this EnableTerminationOnOutOfMemory() function. Whateverz.
// This works for now.
#if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
#if defined(TYPE_PROFILING)
base::type_profiler::InterceptFunctions::SetFunctions(
base::type_profiler::NewInterceptForTCMalloc,
base::type_profiler::DeleteInterceptForTCMalloc);
#endif
// For tcmalloc, we need to tell it to behave like new.
tc_set_new_mode(1);
// On windows, we've already set these thunks up in _heap_init()
base::allocator::SetGetAllocatorWasteSizeFunction(
GetAllocatorWasteSizeThunk);
base::allocator::SetGetStatsFunction(GetStatsThunk);
base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
// Provide optional hook for monitoring allocation quantities on a
// per-thread basis. Only set the hook if the environment indicates this
// needs to be enabled.
const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
if (profiling &&
(atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
tracked_objects::SetAlternateTimeSource(
MallocExtension::GetBytesAllocatedOnCurrentThread,
tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
}
#endif
// On Android,
// - setlocale() is not supported.
// - We do not override the signal handlers so that we can get
// stack trace when crashing.
// - The ipc_fd is passed through the Java service.
// Thus, these are all disabled.
#if !defined(OS_ANDROID) && !defined(OS_IOS)
// Set C library locale to make sure CommandLine can parse argument values
// in correct encoding.
setlocale(LC_ALL, "");
SetupSignalHandlers();
base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
g_fds->Set(kPrimaryIPCChannel,
kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
#endif // !OS_ANDROID && !OS_IOS
#if defined(OS_LINUX) || defined(OS_OPENBSD)
g_fds->Set(kCrashDumpSignal,
kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
#endif
#endif // !OS_WIN
is_initialized_ = true;
delegate_ = delegate;
base::EnableTerminationOnHeapCorruption();
base::EnableTerminationOnOutOfMemory();
// The exit manager is in charge of calling the dtors of singleton objects.
// On Android, AtExitManager is set up when library is loaded.
// On iOS, it's set up in main(), which can't call directly through to here.
// A consequence of this is that you can't use the ctor/dtor-based
// TRACE_EVENT methods on Linux or iOS builds till after we set this up.
#if !defined(OS_ANDROID) && !defined(OS_IOS)
exit_manager_.reset(new base::AtExitManager);
#endif // !OS_ANDROID && !OS_IOS
#if defined(OS_MACOSX)
// We need this pool for all the objects created before we get to the
// event loop, but we don't want to leave them hanging around until the
// app quits. Each "main" needs to flush this pool right before it goes into
// its main event loop to get rid of the cruft.
autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
#endif
// On Android, the command line is initialized when library is loaded and
// we have already started our TRACE_EVENT0.
#if !defined(OS_ANDROID)
CommandLine::Init(argc, argv);
#endif // !OS_ANDROID
int exit_code;
if (delegate && delegate->BasicStartupComplete(&exit_code))
return exit_code;
completed_basic_startup_ = true;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
if (!GetContentClient())
SetContentClient(&empty_content_client_);
ContentClientInitializer::Set(process_type, delegate_);
#if defined(OS_WIN)
// Route stdio to parent console (if any) or create one.
if (command_line.HasSwitch(switches::kEnableLogging))
base::RouteStdioToConsole();
#endif
// Enable startup tracing asap to avoid early TRACE_EVENT calls being
// ignored.
if (command_line.HasSwitch(switches::kTraceStartup)) {
base::debug::CategoryFilter category_filter(
command_line.GetSwitchValueASCII(switches::kTraceStartup));
base::debug::TraceLog::GetInstance()->SetEnabled(
category_filter,
base::debug::TraceLog::RECORD_UNTIL_FULL);
}
#if !defined(OS_ANDROID)
// Android tracing started at the beginning of the method.
// Other OSes have to wait till we get here in order for all the memory
// management setup to be completed.
TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
#endif // !OS_ANDROID
#if defined(OS_MACOSX) && !defined(OS_IOS)
// We need to allocate the IO Ports before the Sandbox is initialized or
// the first instance of PowerMonitor is created.
// It's important not to allocate the ports for processes which don't
// register with the power monitor - see crbug.com/88867.
if (process_type.empty() ||
process_type == switches::kPluginProcess ||
process_type == switches::kRendererProcess ||
process_type == switches::kUtilityProcess ||
process_type == switches::kWorkerProcess ||
(delegate &&
delegate->ProcessRegistersWithSystemProcess(process_type))) {
base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
}
if (!process_type.empty() &&
(!delegate || delegate->ShouldSendMachPort(process_type))) {
MachBroker::ChildSendTaskPortToParent();
}
#elif defined(OS_WIN)
// This must be done early enough since some helper functions like
// IsTouchEnabled, needed to load resources, may call into the theme dll.
EnableThemeSupportOnAllWindowStations();
SetupCRT(command_line);
#endif
#if defined(OS_POSIX)
if (!process_type.empty()) {
// When you hit Ctrl-C in a terminal running the browser
// process, a SIGINT is delivered to the entire process group.
// When debugging the browser process via gdb, gdb catches the
// SIGINT for the browser process (and dumps you back to the gdb
// console) but doesn't for the child processes, killing them.
// The fix is to have child processes ignore SIGINT; they'll die
// on their own when the browser process goes away.
//
// Note that we *can't* rely on BeingDebugged to catch this case because
// we are the child process, which is not being debugged.
// TODO(evanm): move this to some shared subprocess-init function.
if (!base::debug::BeingDebugged())
signal(SIGINT, SIG_IGN);
}
#endif
#if defined(USE_NSS)
crypto::EarlySetupForNSSInit();
#endif
ui::RegisterPathProvider();
RegisterPathProvider();
RegisterContentSchemes(true);
CHECK(icu_util::Initialize());
InitializeStatsTable(command_line);
if (delegate)
delegate->PreSandboxStartup();
// Set any custom user agent passed on the command line now so the string
// doesn't change between calls to webkit_glue::GetUserAgent(), otherwise it
// defaults to the user agent set during SetContentClient().
if (command_line.HasSwitch(switches::kUserAgent)) {
webkit_glue::SetUserAgent(
command_line.GetSwitchValueASCII(switches::kUserAgent), true);
}
if (!process_type.empty())
CommonSubprocessInit(process_type);
#if defined(OS_WIN)
CHECK(InitializeSandbox(sandbox_info));
#elif defined(OS_MACOSX) && !defined(OS_IOS)
if (process_type == switches::kRendererProcess ||
process_type == switches::kPpapiPluginProcess ||
(delegate && delegate->DelaySandboxInitialization(process_type))) {
// On OS X the renderer sandbox needs to be initialized later in the
// startup sequence in RendererMainPlatformDelegate::EnableSandbox().
} else {
CHECK(InitializeSandbox());
}
#endif
if (delegate)
delegate->SandboxInitialized(process_type);
#if defined(OS_POSIX) && !defined(OS_IOS)
SetProcessTitleFromCommandLine(argv);
#endif
// Return -1 to indicate no early termination.
return -1;
}
virtual int Run() OVERRIDE {
DCHECK(is_initialized_);
DCHECK(!is_shutdown_);
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
MainFunctionParams main_params(command_line);
#if defined(OS_WIN)
main_params.sandbox_info = &sandbox_info_;
#elif defined(OS_MACOSX)
main_params.autorelease_pool = autorelease_pool_.get();
#endif
#if !defined(OS_IOS)
return RunNamedProcessTypeMain(process_type, main_params, delegate_);
#else
return 1;
#endif
}
virtual void Shutdown() OVERRIDE {
DCHECK(is_initialized_);
DCHECK(!is_shutdown_);
if (completed_basic_startup_ && delegate_) {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
delegate_->ProcessExiting(process_type);
}
#if defined(OS_WIN)
#ifdef _CRTDBG_MAP_ALLOC
_CrtDumpMemoryLeaks();
#endif // _CRTDBG_MAP_ALLOC
_Module.Term();
#endif // OS_WIN
#if defined(OS_MACOSX)
autorelease_pool_.reset(NULL);
#endif
exit_manager_.reset(NULL);
delegate_ = NULL;
is_shutdown_ = true;
}
private:
// True if the runner has been initialized.
bool is_initialized_;
// True if the runner has been shut down.
bool is_shutdown_;
// True if basic startup was completed.
bool completed_basic_startup_;
// Used if the embedder doesn't set one.
ContentClient empty_content_client_;
// The delegate will outlive this object.
ContentMainDelegate* delegate_;
scoped_ptr<base::AtExitManager> exit_manager_;
#if defined(OS_WIN)
sandbox::SandboxInterfaceInfo sandbox_info_;
#elif defined(OS_MACOSX)
scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
#endif
DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
};
// static
ContentMainRunner* ContentMainRunner::Create() {
return new ContentMainRunnerImpl();
}
} // namespace content
| [
"1990zhaoshuang@163.com"
] | 1990zhaoshuang@163.com |
0b48e5c6dc2a6defb7b2ba9b09988777aaeb73ac | cc5ca598c83406faf8836f28ad0f97a539a67289 | /Days/Day05/ex00/Bureaucrat.cpp | 7af7444d6865d74440ea9608e22ce268abdbc1f6 | [] | no_license | JuanCasian/42-CPP-Piscine | 46310a9be08a8f065d5acdb15398af5475d31b58 | 498e68c433ef0820e3d8134bb52ce89d56c153eb | refs/heads/master | 2020-04-17T20:36:33.755308 | 2019-05-11T05:21:55 | 2019-05-11T05:21:55 | 166,913,153 | 1 | 1 | null | 2019-05-11T05:21:56 | 2019-01-22T02:27:58 | C++ | UTF-8 | C++ | false | false | 3,405 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Bureaucrat.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jcasian <jcasian@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/06 20:24:06 by jcasian #+# #+# */
/* Updated: 2019/05/07 15:16:32 by jcasian ### ########.fr */
/* */
/* ************************************************************************** */
#include "Bureaucrat.hpp"
/* Constructors */
Bureaucrat::Bureaucrat(void) {
return ;
}
Bureaucrat::Bureaucrat(std::string name, int grade) : _name(name) {
if (grade < 1) {
throw GradeTooHighException();
} else if (grade > 150) {
throw GradeTooLowException();
}
this->_grade = grade;
return ;
}
Bureaucrat::Bureaucrat(Bureaucrat const &src) : _name(src.getName()) {
*this = src;
return ;
}
/* Destructor */
Bureaucrat::~Bureaucrat(void) {
return ;
}
/* Operator */
Bureaucrat &Bureaucrat::operator=(Bureaucrat const &rhs) {
this->_grade = rhs.getGrade();
return *this;
}
std::ostream &operator<<(std::ostream &o, Bureaucrat const &rhs) {
o << rhs.getName() << ", bureaucrat grade " << rhs.getGrade();
return o;
}
/* Getters and Setters */
const std::string Bureaucrat::getName(void) const {
return this->_name;
}
int Bureaucrat::getGrade(void) const {
return this->_grade;
}
void Bureaucrat::setGrade(int grade) {
if (grade < 1) {
throw GradeTooHighException();
} else if (grade > 150) {
throw GradeTooLowException();
}
this->_grade = grade;
}
/* Functions */
void Bureaucrat::incrementGrade(int increment) {
if (increment < 0)
return ;
this->setGrade(this->_grade - increment);
}
void Bureaucrat::decrementGrade(int decrement) {
if (decrement < 0)
return ;
this->setGrade(this->_grade + decrement);
}
/* Exceptions */
Bureaucrat::GradeTooHighException::GradeTooHighException(void) {
return ;
}
Bureaucrat::GradeTooHighException::GradeTooHighException(Bureaucrat::GradeTooHighException const &) {
return ;
}
Bureaucrat::GradeTooHighException::~GradeTooHighException(void) throw() {
return ;
}
Bureaucrat::GradeTooHighException &Bureaucrat::GradeTooHighException::operator=(Bureaucrat::GradeTooHighException const &) {
return *this;
}
const char *Bureaucrat::GradeTooHighException::what(void) const throw() {
return "The grade that is going to be set is to high!";
}
/* Constructors */
Bureaucrat::GradeTooLowException::GradeTooLowException(void) {
return ;
}
Bureaucrat::GradeTooLowException::GradeTooLowException(Bureaucrat::GradeTooLowException const &) {
return ;
}
/* Destructor */
Bureaucrat::GradeTooLowException::~GradeTooLowException(void) throw() {
return ;
}
/* Operator */
Bureaucrat::GradeTooLowException &Bureaucrat::GradeTooLowException::operator=(Bureaucrat::GradeTooLowException const &) {
return *this;
}
const char *Bureaucrat::GradeTooLowException::what(void) const throw() {
return "The grade that is going to be set is to low!";
}
| [
"juanpedrocasian@gmail.com"
] | juanpedrocasian@gmail.com |
b2d67d17b4bb6cc8520542d53ca8dc72edb6ef17 | 2dda88b2b98f9382f9a47bbbff2329c15bf1db84 | /matt/particles/main.cpp | 6cc0ecc9593d8fbd75cdba679d965efd3746a27a | [
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | techmatt/caffe-windows | 94467d8b041fd2ef3ec5d45410c555134cd42c88 | c3c5b8f815843a52a08a3cb19eaa9c6a6c4fd82a | refs/heads/master | 2021-01-17T10:37:13.980938 | 2015-12-01T08:09:58 | 2015-12-01T08:09:58 | 46,631,456 | 1 | 0 | null | 2015-11-21T20:01:00 | 2015-11-21T20:01:00 | null | UTF-8 | C++ | false | false | 166 | cpp | #include "main.h"
void main()
{
Vizzer callback;
ApplicationWin32 app(nullptr, 1280, 1024, "D3D11 Test", GraphicsDeviceTypeD3D11, callback);
app.messageLoop();
}
| [
"techmatt@gmail.com"
] | techmatt@gmail.com |
afe588306c7e325b047a24b6e8a293cb66aa3ef4 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /codeforce/edu/041-060/045/g.cpp | a458fbd823d331e2f074c1c54fa32df148166328 | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 1,345 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
int N;
int A[202020];
vector<int> E[202020];
ll ret[202020];
map<int,int> M[202020];
void dfs(int cur,int pre) {
ret[A[cur]]++;
M[cur][A[cur]]=1;
FORR(e,E[cur]) if(e!=pre) {
dfs(e,cur);
FORR(m,M[e]) FORR(c,M[cur]) {
int g=__gcd(m.first,c.first);
ret[g]+=1LL*m.second*c.second;
}
FORR(m,M[e]) M[cur][__gcd(A[cur],m.first)]+=m.second;
M[e].clear();
}
}
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>N;
FOR(i,N) cin>>A[i];
FOR(i,N-1) {
cin>>x>>y;
E[x-1].push_back(y-1);
E[y-1].push_back(x-1);
}
dfs(0,0);
for(i=1;i<=200000;i++) if(ret[i]) cout<<i<<" "<<ret[i]<<endl;
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
cout.tie(0); solve(); return 0;
}
| [
"kmjp@users.noreply.github.com"
] | kmjp@users.noreply.github.com |
10c6d9c01c39102d1c89a33187fd4b1d5ae1df8b | 83964e7fb41ee62e3084eef5d3deef07eecdd93e | /clang/test/CodeGenCXX/eh.cpp | 584af40da62def61d701ae9a5df8079d2d979b73 | [
"NCSA",
"BSD-2-Clause"
] | permissive | pbb59/ScaffCC | e0bee9e5b16a6f145224ad6b0b6eb32adb026f95 | 7d28d310063d147930ec4705aa5ebdf94ea8e924 | refs/heads/master | 2020-09-23T04:43:54.059923 | 2019-12-19T03:59:22 | 2019-12-19T03:59:22 | 225,405,289 | 0 | 1 | BSD-2-Clause | 2019-12-02T15:17:37 | 2019-12-02T15:17:36 | null | UTF-8 | C++ | false | false | 13,377 | cpp | // RUN: %clang_cc1 -fcxx-exceptions -fexceptions -triple x86_64-apple-darwin -std=c++11 -emit-llvm %s -o %t.ll
// RUN: FileCheck --input-file=%t.ll %s
struct test1_D {
double d;
} d1;
void test1() {
throw d1;
}
// CHECK: define void @_Z5test1v()
// CHECK: [[EXNOBJ:%.*]] = call i8* @__cxa_allocate_exception(i64 8)
// CHECK-NEXT: [[EXN:%.*]] = bitcast i8* [[EXNOBJ]] to [[DSTAR:%[^*]*\*]]
// CHECK-NEXT: [[EXN2:%.*]] = bitcast [[DSTAR]] [[EXN]] to i8*
// CHECK-NEXT: call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[EXN2]], i8* bitcast ([[DSTAR]] @d1 to i8*), i64 8, i32 8, i1 false)
// CHECK-NEXT: call void @__cxa_throw(i8* [[EXNOBJ]], i8* bitcast ({ i8*, i8* }* @_ZTI7test1_D to i8*), i8* null) noreturn
// CHECK-NEXT: unreachable
struct test2_D {
test2_D(const test2_D&o);
test2_D();
virtual void bar() { }
int i; int j;
} d2;
void test2() {
throw d2;
}
// CHECK: define void @_Z5test2v()
// CHECK: [[EXNVAR:%.*]] = alloca i8*
// CHECK-NEXT: [[SELECTORVAR:%.*]] = alloca i32
// CHECK-NEXT: [[EXNOBJ:%.*]] = call i8* @__cxa_allocate_exception(i64 16)
// CHECK-NEXT: [[EXN:%.*]] = bitcast i8* [[EXNOBJ]] to [[DSTAR:%[^*]*\*]]
// CHECK-NEXT: invoke void @_ZN7test2_DC1ERKS_([[DSTAR]] [[EXN]], [[DSTAR]] @d2)
// CHECK-NEXT: to label %[[CONT:.*]] unwind label %{{.*}}
// : [[CONT]]: (can't check this in Release-Asserts builds)
// CHECK: call void @__cxa_throw(i8* [[EXNOBJ]], i8* bitcast ({{.*}}* @_ZTI7test2_D to i8*), i8* null) noreturn
// CHECK-NEXT: unreachable
struct test3_D {
test3_D() { }
test3_D(volatile test3_D&o);
virtual void bar();
};
void test3() {
throw (volatile test3_D *)0;
}
// CHECK: define void @_Z5test3v()
// CHECK: [[EXNOBJ:%.*]] = call i8* @__cxa_allocate_exception(i64 8)
// CHECK-NEXT: [[EXN:%.*]] = bitcast i8* [[EXNOBJ]] to [[D:%[^*]+]]**
// CHECK-NEXT: store [[D]]* null, [[D]]** [[EXN]]
// CHECK-NEXT: call void @__cxa_throw(i8* [[EXNOBJ]], i8* bitcast ({ i8*, i8*, i32, i8* }* @_ZTIPV7test3_D to i8*), i8* null) noreturn
// CHECK-NEXT: unreachable
void test4() {
throw;
}
// CHECK: define void @_Z5test4v()
// CHECK: call void @__cxa_rethrow() noreturn
// CHECK-NEXT: unreachable
// rdar://problem/7696549
namespace test5 {
struct A {
A();
A(const A&);
~A();
};
void test() {
try { throw A(); } catch (A &x) {}
}
// CHECK: define void @_ZN5test54testEv()
// CHECK: [[EXNOBJ:%.*]] = call i8* @__cxa_allocate_exception(i64 1)
// CHECK: [[EXNCAST:%.*]] = bitcast i8* [[EXNOBJ]] to [[A:%[^*]*]]*
// CHECK-NEXT: invoke void @_ZN5test51AC1Ev([[A]]* [[EXNCAST]])
// CHECK: invoke void @__cxa_throw(i8* [[EXNOBJ]], i8* bitcast ({{.*}}* @_ZTIN5test51AE to i8*), i8* bitcast (void ([[A]]*)* @_ZN5test51AD1Ev to i8*)) noreturn
// CHECK-NEXT: to label {{%.*}} unwind label %[[HANDLER:[^ ]*]]
// : [[HANDLER]]: (can't check this in Release-Asserts builds)
// CHECK: {{%.*}} = call i32 @llvm.eh.typeid.for(i8* bitcast ({{.*}}* @_ZTIN5test51AE to i8*))
}
namespace test6 {
template <class T> struct allocator {
~allocator() throw() { }
};
void foo() {
allocator<int> a;
}
}
// PR7127
namespace test7 {
// CHECK: define i32 @_ZN5test73fooEv()
int foo() {
// CHECK: [[CAUGHTEXNVAR:%.*]] = alloca i8*
// CHECK-NEXT: [[SELECTORVAR:%.*]] = alloca i32
// CHECK-NEXT: [[INTCATCHVAR:%.*]] = alloca i32
try {
try {
// CHECK-NEXT: [[EXNALLOC:%.*]] = call i8* @__cxa_allocate_exception
// CHECK-NEXT: bitcast i8* [[EXNALLOC]] to i32*
// CHECK-NEXT: store i32 1, i32*
// CHECK-NEXT: invoke void @__cxa_throw(i8* [[EXNALLOC]], i8* bitcast (i8** @_ZTIi to i8*), i8* null
throw 1;
}
// CHECK: [[CAUGHTVAL:%.*]] = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*)
// CHECK-NEXT: catch i8* bitcast (i8** @_ZTIi to i8*)
// CHECK-NEXT: catch i8* null
// CHECK-NEXT: [[CAUGHTEXN:%.*]] = extractvalue { i8*, i32 } [[CAUGHTVAL]], 0
// CHECK-NEXT: store i8* [[CAUGHTEXN]], i8** [[CAUGHTEXNVAR]]
// CHECK-NEXT: [[SELECTOR:%.*]] = extractvalue { i8*, i32 } [[CAUGHTVAL]], 1
// CHECK-NEXT: store i32 [[SELECTOR]], i32* [[SELECTORVAR]]
// CHECK-NEXT: br label
// CHECK: [[SELECTOR:%.*]] = load i32* [[SELECTORVAR]]
// CHECK-NEXT: [[T0:%.*]] = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIi to i8*))
// CHECK-NEXT: icmp eq i32 [[SELECTOR]], [[T0]]
// CHECK-NEXT: br i1
// CHECK: [[T0:%.*]] = load i8** [[CAUGHTEXNVAR]]
// CHECK-NEXT: [[T1:%.*]] = call i8* @__cxa_begin_catch(i8* [[T0]])
// CHECK-NEXT: [[T2:%.*]] = bitcast i8* [[T1]] to i32*
// CHECK-NEXT: [[T3:%.*]] = load i32* [[T2]]
// CHECK-NEXT: store i32 [[T3]], i32* {{%.*}}, align 4
// CHECK-NEXT: invoke void @__cxa_rethrow
catch (int) {
throw;
}
}
// CHECK: [[CAUGHTVAL:%.*]] = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*)
// CHECK-NEXT: catch i8* null
// CHECK-NEXT: [[CAUGHTEXN:%.*]] = extractvalue { i8*, i32 } [[CAUGHTVAL]], 0
// CHECK-NEXT: store i8* [[CAUGHTEXN]], i8** [[CAUGHTEXNVAR]]
// CHECK-NEXT: [[SELECTOR:%.*]] = extractvalue { i8*, i32 } [[CAUGHTVAL]], 1
// CHECK-NEXT: store i32 [[SELECTOR]], i32* [[SELECTORVAR]]
// CHECK-NEXT: call void @__cxa_end_catch()
// CHECK-NEXT: br label
// CHECK: load i8** [[CAUGHTEXNVAR]]
// CHECK-NEXT: call i8* @__cxa_begin_catch
// CHECK-NEXT: call void @__cxa_end_catch
catch (...) {
}
// CHECK: ret i32 0
return 0;
}
}
// Ordering of destructors in a catch handler.
namespace test8 {
struct A { A(const A&); ~A(); };
void bar();
// CHECK: define void @_ZN5test83fooEv()
void foo() {
try {
// CHECK: invoke void @_ZN5test83barEv()
bar();
} catch (A a) {
// CHECK: call i8* @__cxa_get_exception_ptr
// CHECK-NEXT: bitcast
// CHECK-NEXT: invoke void @_ZN5test81AC1ERKS0_(
// CHECK: call i8* @__cxa_begin_catch
// CHECK-NEXT: call void @_ZN5test81AD1Ev(
// CHECK: call void @__cxa_end_catch()
// CHECK: ret void
}
}
}
// Constructor function-try-block must rethrow on fallthrough.
// rdar://problem/7696603
namespace test9 {
void opaque();
struct A { A(); };
// CHECK: define void @_ZN5test91AC1Ev(%"struct.test9::A"* %this) unnamed_addr
// CHECK: call void @_ZN5test91AC2Ev
// CHECK-NEXT: ret void
// CHECK: define void @_ZN5test91AC2Ev(%"struct.test9::A"* %this) unnamed_addr
A::A() try {
// CHECK: invoke void @_ZN5test96opaqueEv()
opaque();
} catch (int x) {
// CHECK: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*)
// CHECK-NEXT: catch i8* bitcast (i8** @_ZTIi to i8*)
// CHECK: call i8* @__cxa_begin_catch
// CHECK: invoke void @_ZN5test96opaqueEv()
// CHECK: invoke void @__cxa_rethrow()
opaque();
}
}
// __cxa_end_catch can throw for some kinds of caught exceptions.
namespace test10 {
void opaque();
struct A { ~A(); };
struct B { int x; };
// CHECK: define void @_ZN6test103fooEv()
void foo() {
A a; // force a cleanup context
try {
// CHECK: invoke void @_ZN6test106opaqueEv()
opaque();
} catch (int i) {
// CHECK: call i8* @__cxa_begin_catch
// CHECK-NEXT: bitcast
// CHECK-NEXT: load i32*
// CHECK-NEXT: store i32
// CHECK-NEXT: call void @__cxa_end_catch() nounwind
} catch (B a) {
// CHECK: call i8* @__cxa_begin_catch
// CHECK-NEXT: bitcast
// CHECK-NEXT: bitcast
// CHECK-NEXT: bitcast
// CHECK-NEXT: call void @llvm.memcpy
// CHECK-NEXT: invoke void @__cxa_end_catch()
} catch (...) {
// CHECK: call i8* @__cxa_begin_catch
// CHECK-NEXT: invoke void @__cxa_end_catch()
}
// CHECK: call void @_ZN6test101AD1Ev(
}
}
// __cxa_begin_catch returns pointers by value, even when catching by reference
// <rdar://problem/8212123>
namespace test11 {
void opaque();
// CHECK: define void @_ZN6test113fooEv()
void foo() {
try {
// CHECK: invoke void @_ZN6test116opaqueEv()
opaque();
} catch (int**&p) {
// CHECK: [[EXN:%.*]] = load i8**
// CHECK-NEXT: call i8* @__cxa_begin_catch(i8* [[EXN]]) nounwind
// CHECK-NEXT: [[ADJ1:%.*]] = getelementptr i8* [[EXN]], i32 32
// CHECK-NEXT: [[ADJ2:%.*]] = bitcast i8* [[ADJ1]] to i32***
// CHECK-NEXT: store i32*** [[ADJ2]], i32**** [[P:%.*]]
// CHECK-NEXT: call void @__cxa_end_catch() nounwind
}
}
struct A {};
// CHECK: define void @_ZN6test113barEv()
void bar() {
try {
// CHECK: [[EXNSLOT:%.*]] = alloca i8*
// CHECK-NEXT: [[SELECTORSLOT:%.*]] = alloca i32
// CHECK-NEXT: [[P:%.*]] = alloca [[A:%.*]]**,
// CHECK-NEXT: [[TMP:%.*]] = alloca [[A]]*
// CHECK-NEXT: invoke void @_ZN6test116opaqueEv()
opaque();
} catch (A*&p) {
// CHECK: [[EXN:%.*]] = load i8** [[EXNSLOT]]
// CHECK-NEXT: [[ADJ1:%.*]] = call i8* @__cxa_begin_catch(i8* [[EXN]]) nounwind
// CHECK-NEXT: [[ADJ2:%.*]] = bitcast i8* [[ADJ1]] to [[A]]*
// CHECK-NEXT: store [[A]]* [[ADJ2]], [[A]]** [[TMP]]
// CHECK-NEXT: store [[A]]** [[TMP]], [[A]]*** [[P]]
// CHECK-NEXT: call void @__cxa_end_catch() nounwind
}
}
}
// PR7686
namespace test12 {
struct A { ~A() noexcept(false); };
bool opaque(const A&);
// CHECK: define void @_ZN6test124testEv()
void test() {
// CHECK: [[X:%.*]] = alloca [[A:%.*]],
// CHECK: [[EHCLEANUPDEST:%.*]] = alloca i32
// CHECK: [[Y:%.*]] = alloca [[A]]
// CHECK: [[Z:%.*]] = alloca [[A]]
// CHECK: [[CLEANUPDEST:%.*]] = alloca i32
A x;
// CHECK: invoke zeroext i1 @_ZN6test126opaqueERKNS_1AE(
if (opaque(x)) {
A y;
A z;
// CHECK: invoke void @_ZN6test121AD1Ev([[A]]* [[Z]])
// CHECK: invoke void @_ZN6test121AD1Ev([[A]]* [[Y]])
// CHECK-NOT: switch
goto success;
}
success:
bool _ = true;
// CHECK: call void @_ZN6test121AD1Ev([[A]]* [[X]])
// CHECK-NEXT: ret void
}
}
// Reduced from some TableGen code that was causing a self-host crash.
namespace test13 {
struct A { ~A(); };
void test0(int x) {
try {
switch (x) {
case 0:
break;
case 1:{
A a;
break;
}
default:
return;
}
return;
} catch (int x) {
}
return;
}
void test1(int x) {
A y;
try {
switch (x) {
default: break;
}
} catch (int x) {}
}
}
// rdar://problem/8231514
namespace test14 {
struct A { ~A(); };
struct B { ~B(); };
B b();
void opaque();
void foo() {
A a;
try {
B str = b();
opaque();
} catch (int x) {
}
}
}
// rdar://problem/8231514
// JumpDests shouldn't get confused by scopes that aren't normal cleanups.
namespace test15 {
struct A { ~A(); };
bool opaque(int);
// CHECK: define void @_ZN6test153fooEv()
void foo() {
A a;
try {
// CHECK: [[X:%.*]] = alloca i32
// CHECK: store i32 10, i32* [[X]]
// CHECK-NEXT: br label
// -> while.cond
int x = 10;
while (true) {
// CHECK: load i32* [[X]]
// CHECK-NEXT: [[COND:%.*]] = invoke zeroext i1 @_ZN6test156opaqueEi
// CHECK: br i1 [[COND]]
if (opaque(x))
// CHECK: br label
break;
// CHECK: br label
}
// CHECK: br label
} catch (int x) { }
// CHECK: call void @_ZN6test151AD1Ev
}
}
namespace test16 {
struct A { A(); ~A() noexcept(false); };
struct B { int x; B(const A &); ~B() noexcept(false); };
void foo();
bool cond();
// CHECK: define void @_ZN6test163barEv()
void bar() {
// CHECK: [[EXN_SAVE:%.*]] = alloca i8*
// CHECK-NEXT: [[EXN_ACTIVE:%.*]] = alloca i1
// CHECK-NEXT: [[TEMP:%.*]] = alloca [[A:%.*]],
// CHECK-NEXT: [[EXNSLOT:%.*]] = alloca i8*
// CHECK-NEXT: [[SELECTORSLOT:%.*]] = alloca i32
// CHECK-NEXT: [[TEMP_ACTIVE:%.*]] = alloca i1
cond() ? throw B(A()) : foo();
// CHECK-NEXT: [[COND:%.*]] = call zeroext i1 @_ZN6test164condEv()
// CHECK-NEXT: store i1 false, i1* [[EXN_ACTIVE]]
// CHECK-NEXT: store i1 false, i1* [[TEMP_ACTIVE]]
// CHECK-NEXT: br i1 [[COND]],
// CHECK: [[EXN:%.*]] = call i8* @__cxa_allocate_exception(i64 4)
// CHECK-NEXT: store i8* [[EXN]], i8** [[EXN_SAVE]]
// CHECK-NEXT: store i1 true, i1* [[EXN_ACTIVE]]
// CHECK-NEXT: [[T0:%.*]] = bitcast i8* [[EXN]] to [[B:%.*]]*
// CHECK-NEXT: invoke void @_ZN6test161AC1Ev([[A]]* [[TEMP]])
// CHECK: store i1 true, i1* [[TEMP_ACTIVE]]
// CHECK-NEXT: invoke void @_ZN6test161BC1ERKNS_1AE([[B]]* [[T0]], [[A]]* [[TEMP]])
// CHECK: store i1 false, i1* [[EXN_ACTIVE]]
// CHECK-NEXT: invoke void @__cxa_throw(i8* [[EXN]],
// CHECK: invoke void @_ZN6test163fooEv()
// CHECK: br label
// CHECK: invoke void @_ZN6test161AD1Ev([[A]]* [[TEMP]])
// CHECK: ret void
// CHECK: [[T0:%.*]] = load i1* [[EXN_ACTIVE]]
// CHECK-NEXT: br i1 [[T0]]
// CHECK: [[T1:%.*]] = load i8** [[EXN_SAVE]]
// CHECK-NEXT: call void @__cxa_free_exception(i8* [[T1]])
// CHECK-NEXT: br label
}
}
| [
"ajavadia@princeton.edu"
] | ajavadia@princeton.edu |
7aa7f8fb9b6da627e2b65f7c6c26a28697134b06 | 0e9e5abffeb1bedf81d44ab841999c0ead867b1c | /test/network/network_emulation_manager.h | 449441a3c12f72d5fe51442a0f58a5f0183414c5 | [
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-google-patent-license-webrtc"
] | permissive | open-webrtc-toolkit/owt-deps-webrtc | 6b5983c304098399b11921df23987e627ecfaf22 | 49d511cd8fb8aac8fc92150dc024457dedf3193f | refs/heads/108-sdk | 2023-08-31T13:33:34.172416 | 2023-08-30T02:53:53 | 2023-08-30T02:53:53 | 154,413,230 | 223 | 153 | BSD-3-Clause | 2023-08-30T02:53:54 | 2018-10-24T00:13:08 | C++ | UTF-8 | C++ | false | false | 5,013 | h | /*
* Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef TEST_NETWORK_NETWORK_EMULATION_MANAGER_H_
#define TEST_NETWORK_NETWORK_EMULATION_MANAGER_H_
#include <map>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "api/array_view.h"
#include "api/test/network_emulation_manager.h"
#include "api/test/simulated_network.h"
#include "api/test/time_controller.h"
#include "api/units/time_delta.h"
#include "api/units/timestamp.h"
#include "rtc_base/logging.h"
#include "rtc_base/network.h"
#include "rtc_base/task_queue_for_test.h"
#include "rtc_base/task_utils/repeating_task.h"
#include "rtc_base/thread.h"
#include "system_wrappers/include/clock.h"
#include "test/network/cross_traffic.h"
#include "test/network/emulated_network_manager.h"
#include "test/network/emulated_turn_server.h"
#include "test/network/fake_network_socket_server.h"
#include "test/network/network_emulation.h"
namespace webrtc {
namespace test {
class NetworkEmulationManagerImpl : public NetworkEmulationManager {
public:
explicit NetworkEmulationManagerImpl(TimeMode mode);
~NetworkEmulationManagerImpl();
EmulatedNetworkNode* CreateEmulatedNode(BuiltInNetworkBehaviorConfig config,
uint64_t random_seed = 1) override;
EmulatedNetworkNode* CreateEmulatedNode(
std::unique_ptr<NetworkBehaviorInterface> network_behavior) override;
SimulatedNetworkNode::Builder NodeBuilder() override;
EmulatedEndpointImpl* CreateEndpoint(EmulatedEndpointConfig config) override;
void EnableEndpoint(EmulatedEndpoint* endpoint) override;
void DisableEndpoint(EmulatedEndpoint* endpoint) override;
EmulatedRoute* CreateRoute(EmulatedEndpoint* from,
const std::vector<EmulatedNetworkNode*>& via_nodes,
EmulatedEndpoint* to) override;
EmulatedRoute* CreateRoute(
const std::vector<EmulatedNetworkNode*>& via_nodes) override;
EmulatedRoute* CreateDefaultRoute(
EmulatedEndpoint* from,
const std::vector<EmulatedNetworkNode*>& via_nodes,
EmulatedEndpoint* to) override;
void ClearRoute(EmulatedRoute* route) override;
TcpMessageRoute* CreateTcpRoute(EmulatedRoute* send_route,
EmulatedRoute* ret_route) override;
CrossTrafficRoute* CreateCrossTrafficRoute(
const std::vector<EmulatedNetworkNode*>& via_nodes) override;
CrossTrafficGenerator* StartCrossTraffic(
std::unique_ptr<CrossTrafficGenerator> generator) override;
void StopCrossTraffic(CrossTrafficGenerator* generator) override;
EmulatedNetworkManagerInterface* CreateEmulatedNetworkManagerInterface(
const std::vector<EmulatedEndpoint*>& endpoints) override;
void GetStats(rtc::ArrayView<EmulatedEndpoint* const> endpoints,
std::function<void(std::unique_ptr<EmulatedNetworkStats>)>
stats_callback) override;
TimeController* time_controller() override { return time_controller_.get(); }
TimeMode time_mode() const override { return time_mode_; }
Timestamp Now() const;
EmulatedTURNServerInterface* CreateTURNServer(
EmulatedTURNServerConfig config) override;
private:
using CrossTrafficSource =
std::pair<std::unique_ptr<CrossTrafficGenerator>, RepeatingTaskHandle>;
absl::optional<rtc::IPAddress> GetNextIPv4Address();
const TimeMode time_mode_;
const std::unique_ptr<TimeController> time_controller_;
Clock* const clock_;
int next_node_id_;
RepeatingTaskHandle process_task_handle_;
uint32_t next_ip4_address_;
std::set<rtc::IPAddress> used_ip_addresses_;
// All objects can be added to the manager only when it is idle.
std::vector<std::unique_ptr<EmulatedEndpoint>> endpoints_;
std::vector<std::unique_ptr<EmulatedNetworkNode>> network_nodes_;
std::vector<std::unique_ptr<EmulatedRoute>> routes_;
std::vector<std::unique_ptr<CrossTrafficRoute>> traffic_routes_;
std::vector<CrossTrafficSource> cross_traffics_;
std::list<std::unique_ptr<TcpMessageRouteImpl>> tcp_message_routes_;
std::vector<std::unique_ptr<EndpointsContainer>> endpoints_containers_;
std::vector<std::unique_ptr<EmulatedNetworkManager>> network_managers_;
std::vector<std::unique_ptr<EmulatedTURNServer>> turn_servers_;
std::map<EmulatedEndpoint*, EmulatedNetworkManager*>
endpoint_to_network_manager_;
// Must be the last field, so it will be deleted first, because tasks
// in the TaskQueue can access other fields of the instance of this class.
TaskQueueForTest task_queue_;
};
} // namespace test
} // namespace webrtc
#endif // TEST_NETWORK_NETWORK_EMULATION_MANAGER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
33abc7bfb06766dc748cba5d39af76897b511d48 | 3c2c511cf8c181ab6c5437ef84ea16b4de6f40a2 | /Code/demo_test/libraries/OffChip/Gimbal/Gimbal.cpp | 33cbbb483ffd002d36900487c86718d04458f8b5 | [] | no_license | Neutree/AHRS | c9c53f845df755a93ba8ac6121551ee3c46aa6f6 | 423776e70f06c0b04eb7cd44a08d77610f03de81 | refs/heads/master | 2021-01-17T14:16:49.834662 | 2017-03-11T09:22:59 | 2017-03-11T09:22:59 | 49,999,568 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 248 | cpp | #include "Gimbal.h"
Gimbal::Gimbal(StepMotor &motorRoll,StepMotor &motorPitch):_motor_roll(motorRoll),_motor_pitch(motorPitch)
{
}
void Gimbal::SetSpeed(int vRoll,int vPitch)
{
_motor_roll.SetSpeed(vRoll);
_motor_pitch.SetSpeed(vPitch);
}
| [
"czd666666@gmail.com"
] | czd666666@gmail.com |
32d16bd88b35a87d7368d6bbaa3c91a55c922099 | 674f5fced062dbe7fb53badc105f932888ed0c3b | /proj1/include/darkmaze/Maze.hpp | 335876a32224985247fa49339680fa5131879eb8 | [] | no_license | HericPan/ICS-46-Thornton | 604cb3efe5ceb0981dfe82c424eec33e7da913ae | b5b2c5ed2c8088f1f696d49b73024eb066912389 | refs/heads/main | 2023-08-04T19:45:57.382251 | 2021-09-25T03:49:44 | 2021-09-25T03:49:44 | 410,166,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,726 | hpp | // Maze.hpp
//
// ICS 46 Spring 2021
// Project #1: Dark at the End of the Tunnel
//
// Declares an abstract base class for Maze implementations. An implementation
// of this class is provided already, though the source code for it is not
// being provided to you.
//
// Mazes, in general, have the following properties:
//
// * They have a size, given by a width and a height
// * They are made up of cells with (x, y) coordinates, where 0 <= x <= width-1
// and 0 <= y <= height-1.
// * They have a collection of walls vertically and horizontally that can
// appear in between each pair of adjacent cells. Walls can be added
// and removed.
// * They can be cloned, meaning that, for some Maze object of type M, you can
// create a dynamically-allocated copy of M that has all the same properties.
// * They are "observable," which means that they have a collection of
// "listeners" associated with them, who are notified whenever the maze
// changes. (This is primarily for use in the GUI.)
#ifndef MAZE_HPP
#define MAZE_HPP
#include <ics46/observable/Observable.hpp>
#include "Direction.hpp"
class MazeListener;
class Maze : public ics46::observable::Observable<MazeListener>
{
public:
// Because we'll be inheriting from this class, we'll declare the
// destructor to be virtual, though we don't need it to do anything
// special.
virtual ~Maze() = default;
// getWidth() returns the maze's width (i.e., how many cells across
// is it?)
virtual unsigned int getWidth() const noexcept = 0;
// getHeight() returns the maze's height (i.e., how many cells tall
// is it?)
virtual unsigned int getHeight() const noexcept = 0;
// wallExists() takes a cell's (x, y) coordinate and a Direction,
// returning true if you would see a wall when standing in the cell
// (x, y) and looking in the given direction, false otherwise.
// For example, if you had a Maze m and you wanted to know whether
// there was a wall to the left of cell (3, 4), you would do this:
//
// m.wallExists(3, 4, Direction::left)
virtual bool wallExists(int x, int y, Direction direction) const = 0;
// addWall() takes a cell's (x, y) coordinate and a Direction and
// adds a wall to the maze above, below, to the left, or to the
// right of the given cell. If there is already a wall there, this
// function has no effect. For example, if you wanted to add a wall
// to the left of cell (4, 2) in a Maze m, you would do this:
//
// m.addWall(4, 2, Direction::left)
virtual void addWall(int x, int y, Direction direction) = 0;
// removeWall() takes a cell's (x, y) coordinate and a Direction
// and removes a wall from the maze above, below, to the left, or
// to the right of the given cell. If there is no wall there
// already, this function has no effect. For example, if you wanted
// to remove a wall to the right of cell (2, 9) in a Maze m, you
// would do this:
//
// m.removeWall(2, 9, Direction::right)
virtual void removeWall(int x, int y, Direction direction) = 0;
// addAllWalls() adds all of the possible walls to a maze, so it
// has walls surrounding every cell.
virtual void addAllWalls() = 0;
// removeAllWalls() removes all of the possible walls from a maze,
// so it has no walls around any of its cells.
virtual void removeAllWalls() = 0;
// clone() returns a dynamically-allocated copy of a Maze object.
// The copy will be an object of the same type as the object you
// call it on, though the pointer's type will be Maze.
virtual std::unique_ptr<Maze> clone() const = 0;
};
#endif // MAZE_HPP
| [
"1214423184@qq.com"
] | 1214423184@qq.com |
aae56a709b238fcd2136e6ef88768322b788f2bb | b268ac506771ac5dbdbee9e67e6e112474d0af1e | /Algorithm/Baekjoon/b 1463 1로 만들기_top.cpp | 3e95c3be438f2d631b14400dca0ad054327c4aa8 | [] | no_license | ssoonD/Algorithm | 69c7965c3a3fe42aab0bb211582a170166f5f99c | 8440cf5ce15f15d15746279132398c57b461f968 | refs/heads/master | 2021-02-26T02:23:07.708578 | 2020-10-14T14:56:14 | 2020-10-14T14:56:14 | 232,309,311 | 0 | 0 | null | 2020-01-07T11:41:51 | 2020-01-07T11:21:58 | null | UHC | C++ | false | false | 505 | cpp | /*
D[N] = N을 1로 만드는 최소 연산 횟수
(1) D[N/3] + 1
(2) D[N/2] + 1
(3) D[N-1] + 1
= min(1,2,3)
Top_Down
*/
#include <cstdio>
int d[1000001];
int go(int n) {
if (n == 1) return 0;
if (d[n] > 0) return d[n];
d[n] = go(n - 1) + 1;
if (n % 2 == 0) {
int tmp = go(n / 2) + 1;
if (d[n] > tmp) {
d[n] = tmp;
}
}
if (n % 3 == 0) {
int tmp = go(n / 3) + 1;
if (d[n] > tmp) {
d[n] = tmp;
}
}
return d[n];
}
int main() {
int n;
scanf("%d", &n);
printf("%d\n", go(n));
} | [
"59604134+ssoonD@users.noreply.github.com"
] | 59604134+ssoonD@users.noreply.github.com |
38aabf45fd4f9f4f28e49e9203db786e0eae8f03 | 8f3d9eb1d632282a55ea5a5c3dfe6f23e6d1b76c | /Wawaji-Server-Windows/wwj_demo/tool_kits/ui_component/ui_kit/module/video/video_manager.h | da5b5a2577a2f7d0b035003c6a74571305c4d187 | [
"MIT"
] | permissive | jzsplk/Wawaji | 086580efb5ecf952b990a36bb5cd8a6a9a1fc6f7 | 45c51c3cd1b49a4a926b76b6e4e31a331ede66ee | refs/heads/master | 2020-03-12T15:29:40.437612 | 2018-04-23T12:03:00 | 2018-04-23T12:03:00 | 130,691,413 | 1 | 0 | null | 2018-04-23T12:13:28 | 2018-04-23T12:13:28 | null | UTF-8 | C++ | false | false | 9,039 | h | #pragma once
#include "video_frame_mng.h"
#include "audio_frame_mng.h"
namespace nim_comp
{
struct MEDIA_DEVICE_DRIVE_INFO
{
std::string device_path_;
std::string friendly_name_;
};
enum DeviceSessionType
{
kDeviceSessionTypeNone = 0x0,
kDeviceSessionTypeChat = 0x1,
kDeviceSessionTypeSetting = 0x2,
kDeviceSessionTypeRts = 0x4,
kDeviceSessionTypeChatRoom = 0x8,
};
typedef std::function<void(int code)> ConnectCallback;
typedef std::function<void(std::string uid, bool join_type)> PeopleChangeCallback;
typedef std::function<void(int32_t, std::map<std::string, int32_t>)> VolumeCallback;
/** @class VideoManager
* @brief 音视频管理器
* @copyright (c) 2016, NetEase Inc. All rights reserved
* @date 2016/09/18
*/
class VideoManager : public nbase::SupportWeakCallback
{
public:
SINGLETON_DEFINE(VideoManager);
VideoManager();
~VideoManager();
/**
* 显示一个音视频窗口
* @param[in] id 对方用户id
* @param[in] video 是否包含视频功能
* @param[in] channel_id 通道id
* @return bool true 成功,false 失败
*/
bool ShowVideoChatForm(std::string id, bool video, uint64_t channel_id = 0);
/**
* 显示音视频设置窗口
* @param[in] video 是否包含视频功能
* @return bool true 成功,false 失败
*/
bool ShowVideoSetting(bool video = false);
/**
* 是否存在音视频窗口
* @param[in] show 如果存在并且不处于显示状态,是否让窗口自动显示
* @return bool true 存在,false 不存在
*/
bool IsVideoChatFormExist(bool show);
//监听
//void OnVideoDataCb(bool capture, const std::string& data, unsigned int width, unsigned int height, const std::string& json);
/**
* 设备状态改变的回调
* @param[in] type 设备类型NIMDeviceType,其中kNIMDeviceTypeAudioIn和kNIMDeviceTypeVideo有效
* @param[in] status 为NIMDeviceStatus的多状态
* @param[in] path 当kNIMDeviceStatusReset状态时需要关注此参数,kNIMDeviceStatusReset时有可能选用了非用户选定的设备,这里返回的是重新启动的设备地址
* @return void 无返回值
*/
void OnDeviceStatus(nim::NIMDeviceType type, UINT status, std::string path);
/**
* 启动设备的回调
* @param[in] type 设备类型NIMDeviceType
* @param[in] ret 启动结果,true表示成功
* @return void 无返回值
*/
void OnStartDeviceCb(nim::NIMDeviceType type, bool ret);
/**
* 音视频通话中状态返回的回调
* @param[in] type NIMVideoChatSessionType
* @param[in] channel_id 通话的通道id
* @param[in] code 结果类型或错误类型
* @param[in] json_extension Json string 扩展
* @return void 无返回值
*/
void OnVChatEvent(nim::NIMVideoChatSessionType type, uint64_t channel_id, int code, const std::string& json);
/**
* 获取默认设备路径
* @param[out] no 获取到的设备的序号
* @param[out] device_path 获取到的设备路径
* @param[in] type 设备类型
* @return bool true 成功,false 失败
*/
bool GetDefaultDevicePath(int &no, std::string &device_path, nim::NIMDeviceType type);
/**
* 设置默认设备路径
* @param[in] device_path 设备路径
* @param[in] type 设备类型
* @return bool true 成功,false 失败
*/
void SetDefaultDevicePath(std::string device_path, nim::NIMDeviceType type);
/**
* 获取设备信息
* @param[in] type 设备类型
* @return std::list<MEDIA_DEVICE_DRIVE_INFO> 设备信息列表
*/
std::list<MEDIA_DEVICE_DRIVE_INFO> GetDeviceInfo(nim::NIMDeviceType type);
/**
* 枚举设备回调结果
* @param[in] ret 结果代码,true表示成功
* @param[in] type 设备类型NIMDeviceType,其中kNIMDeviceTypeAudioOut和kNIMDeviceTypeAudioOutChat等效
* @param[in] json Json string 设备列表,可能为空"", 例:json_extension = "[{"name":"Webcam","path":"\\\\?\\usb......"},{"name":"Webcam2","path":"\\\\?\\usb......"}]
* @return void 无返回值
*/
void GetDeviceByJson(bool ret, nim::NIMDeviceType type, const char* json);
/**
* 设置音量
* @param[in] volumn 音量,默认255
* @param[in] capture true 标识设置麦克风音量,false 标识设置播放音量
* @return void 无返回值
*/
void SetAudioVolumn(unsigned char volumn, bool capture);
/**
* 设置自动调节麦克风音量
* @param[in] auto_volumn 是否自动调节音量
* @return void 无返回值
*/
void SetAudioInputAutoVolumn(bool auto_volumn);
/**
* 启动设备
* @param[in] type 设备类型
* @param[in] device_path 设备路径
* @param[in] session_type 会话类型
* @return void 无返回值
*/
void StartDevice(nim::NIMDeviceType type, std::string device_path, DeviceSessionType session_type);
/**
* 结束设备
* @param[in] type 设备类型
* @param[in] session_type 会话类型
* @param[in] forced 是否强制结束
* @return void 无返回值
*/
void EndDevice(nim::NIMDeviceType type, DeviceSessionType session_type, bool forced = false);
/**
* 开始音视频通话
* @param[in] mode 音视频通话类型
* @param[in] apns_text 暂时无用
* @param[in] custom_info 暂时无用
* @param[in] uid 对方用户id
* @param[in] session_id 会话id
* @return bool true 成功,false 失败
*/
bool StartChat(nim::NIMVideoChatMode mode, const std::string& apns_text, const std::string& custom_info, const std::string& uid, const std::string& session_id);
//bool JoinRoomChat(nim::NIMVideoChatMode mode, const std::string& room_id, const std::string& master, nim::NIMVChatVideoQuality quality_type, const std::string& apns_text, const std::string& custom_info);
/**
* 设置视频类型
* @param[in] mode 音视频通话类型
* @return bool true 成功,false 失败
*/
bool SetVoipMode(nim::NIMVideoChatMode mode);
/**
* 回应音视频邀请
* @param[in] channel_id 通道id
* @param[in] accept 是否接受
* @param[in] session_id 会话id
* @return bool true 成功,false 失败
*/
bool VChatCalleeAck(uint64_t channel_id, bool accept, const std::string& session_id);
/**
* 音视频通话控制
* @param[in] channel_id 通道id
* @param[in] type 会话控制类型
* @return bool true 成功,false 失败
*/
bool VChatControl(uint64_t channel_id, nim::NIMVChatControlType type);
/**
* 结束音视频通话
* @param[in] session_id 会话id
* @return void 无返回值
*/
void EndChat(const std::string& session_id);
/**
* 设置观众模式
* @param[in] viewer 是否为观众
* @return void 无返回值
*/
void SetViewerMode(bool viewer);
/**
* 获取观众模式
* @return bool true 是,false 否
*/
bool GetViewerMode();
/**
* 设置音频静音
* @param[in] muted 是否静音
* @return void 无返回值
*/
void SetAudioMuted(bool muted);
/**
* 获取是否音频静音
* @return bool true 静音,false 不静音
*/
bool GetAudioMuteEnabled();
/**
* 设置单个成员的黑名单状态,当前通话有效(只能设置进入过房间的成员)
* @param[in] uid 成员用户id
* @param[in] add true表示添加到黑名单,false表示从黑名单移除
* @param[in] audio true表示音频黑名单,false表示视频黑名单
* @param[in] cb 操作结果回调函数
* @return void 无返回值
*/
void SetMemberBlacklist(const std::string& uid, bool add, bool audio, nim::VChat::OptCallback cb);
/**
* 创建一个多人房间
* @param[in] room_name 房间名
* @param[in] custom_info 自定义的房间信息(加入房间的时候会返回)
* @param[in] cb 操作结果回调函数
* @return void 无返回值
*/
void CreateRoom(const std::string& room_name, const std::string& custom_info, nim::VChat::Opt2Callback cb);
/**
* 加入一个多人房间
* @param[in] mode 音视频通话类型
* @param[in] room_name 房间名
* @param[in] session_id 会话id
* @param[in] rtmp_url 主播推流地址
* @param[in] live_link 是否是观众连麦
* @param[in] cb 操作结果回调函数
* @return bool true 调用成功,false 调用失败可能有正在进行的通话
*/
bool JoinRoom(nim::NIMVideoChatMode mode, const std::string& room_name, const std::string& rtmp_url, bool live_link, const std::string& session_id, nim::VChat::Opt2Callback cb);
/**
* 设置多人音视频回调函数
* @param[in] start_cb 点对点邀请的相关结果
* @param[in] connect_cb 连接状态改变的回调函数
* @param[in] people_cb 成员改变的回调函数
* @param[in] volume_cb 音量的回调函数
* @return void 无返回值
*/
void SetChatRoomCb(ConnectCallback start_cb = nullptr, ConnectCallback connect_cb = nullptr, PeopleChangeCallback people_cb = nullptr, VolumeCallback volume_cb = nullptr);
public:
VideoFrameMng video_frame_mng_;
AudioFrameMng audio_frame_mng_;
private:
std::list<MEDIA_DEVICE_DRIVE_INFO> device_info_list_[4];
std::string def_device_path_[4];
DWORD device_session_type_[4];
ConnectCallback chatroom_start_cb_ = nullptr;
ConnectCallback chatroom_connect_cb_ = nullptr;
PeopleChangeCallback chatroom_people_cb_ = nullptr;
VolumeCallback chatroom_volume_cb_ = nullptr;
};
} | [
"hzgaoqi1@corp.netease.com"
] | hzgaoqi1@corp.netease.com |
67dbe694a82da722223cd9671a18a80dba0016fc | 434bc1d262220209bc602010888551884749e3fd | /Chapter 2/2.3 raii: wait for a thread to finish/main.cpp | e300f061d3f7b3d6e36f52b226aba6fb6e18e3e4 | [] | no_license | viniciusjavs/cpp-concurrency-in-action | 58daa142d2c74727a6170de0cdc0796bc7a44060 | c32b80e7098d54c1ee8e24da15c0c60eb7774976 | refs/heads/main | 2023-01-04T14:51:23.722591 | 2020-11-03T01:28:00 | 2020-11-03T01:28:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | cpp | /*
Listing 2.3
Using RAII to wait for a thread to complete
*/
#include <thread>
class thread_guard {
std::thread &t_;
public:
explicit thread_guard(std::thread &t) : t_{t} {}
~thread_guard() {
if (t_.joinable()) {
t_.join();
}
}
thread_guard(thread_guard const &) = delete;
thread_guard &operator=(thread_guard const &) = delete;
};
void do_something(int);
struct func {
int &i_;
func(int &i) : i_{i} {}
void operator()() {
for (unsigned j{0}; j < 1'000'000; ++j) {
do_something(i_);
}
}
};
void do_something_in_current_thread();
void f() {
int some_local_state{0};
func my_func(some_local_state);
std::thread t{my_func};
thread_guard g{t};
do_something_in_current_thread();
}
| [
"viniciusjavs@gmail.com"
] | viniciusjavs@gmail.com |
3da1d9e535d4cbaaf63d6d731ef9c1dbeb963d5d | 505af02067608c1ed8df06738e44df6e001588d2 | /willToys/include/OpenGL/VertexBuffer.h | 30421cfeee31f5dd8d8aa0cd51b38d6dcee0aaa8 | [] | no_license | willproj/willToys | e9dc3006fe54ab9896bd3c92501ed630fcd26041 | 1a21c487b61ec78707dae47b0e8ced00d276f7ec | refs/heads/master | 2022-04-17T01:22:47.562475 | 2020-04-06T05:14:26 | 2020-04-06T05:14:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | #pragma once
#include "..//Common.h"
namespace gltoys::opengl
{
class VertexBuffer
{
public:
VertexBuffer() :m_VertexBufferID(0) {}
VertexBuffer(size_t size, const void* data);
~VertexBuffer();
void BindVertexBuffer()const;
void UnbindVertexBuffer()const;
void AddBufferData(size_t size, void* data);
void AddSubBufferData(size_t size, size_t offset, void* data);
private:
GLuint m_VertexBufferID;
};
} | [
"williamms669@gmail.com"
] | williamms669@gmail.com |
960fb54c3ffbbcdef0913fb906ec8b2499aaa0cf | 68cb80a04867861bf4eb6aaec351f98057381929 | /RCN001/Common/Screens/GameScreen.cpp | 0be6da3ad741aaa95aeb735c224ac42fa3c5f663 | [] | no_license | jim-leedham/RCN | 66b206324219d631000f3912a8812c877ed40299 | 5f69dc93a913ce072095bbf513216e858b59bc74 | refs/heads/master | 2022-12-31T11:19:59.603642 | 2020-10-19T14:45:58 | 2020-10-19T14:45:58 | 305,415,118 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,255 | cpp | // -----------------------------------------
// INCLUDES
#include "stdheader.h"
#include "GameScreen.h"
#include "Core/TextureManager.h"
#include "Game/Game.h"
// -----------------------------------------
// CLASS DEFINITIONS
CGameScreen::CGameScreen(const char* cScreenName) : CRCNScreen(cScreenName)
{
m_pBackground = g_pApplication->GetTextureManager()->GetTexture(ETexture_GameScreenBackground);
m_pQuitButton = RCNNew CRCNButton();
m_pQuitButton->SetDefaultTexture(g_pApplication->GetTextureManager()->GetTexture(ETexture_MenuScreenQuitButtonOnClick));
m_pQuitButton->SetOnClickTexture(g_pApplication->GetTextureManager()->GetTexture(ETexture_MenuScreenQuitButtonOnClick));
m_pQuitButton->SetPosition(CRCNVector(30.0f, 30.0f, 0.0f));
m_pQuitButton->SetOnReleaseFunction(QuitButtonReleaseFunc);
m_sString1.SetCharacters("This is a demonstration of the RECON engine");
m_sString1.SetRenderCoordinates(500, 600);
m_sString2.SetCharacters("[1][2][3] keys control lighting. [W][A][S][D] keys control movements");
m_sString2.SetRenderCoordinates(400, 630);
m_pMusic = CRCNAudioController::Create("RCNMusic_InGame");
m_pMusic->SetVolume(CRCNAudioSource::ms_fMinimumVolume);
m_pMusic->SetFade(CRCNAudioSource::ms_fMaximumVolume, 2000);
m_pMusic->Play();
SetScreenState(EScreenState_Initialised);
}
CGameScreen::~CGameScreen()
{
RCNDelete m_pQuitButton;
m_pMusic->Release(CRCNAudioSource::ERelease::EImmediate);
}
void CGameScreen::Process()
{
m_pQuitButton->Process();
CRCNScreen::Process();
}
void CGameScreen::ProcessInput(CRCNInput::EInput eInput, CRCNInput::EInputState eInputState)
{
m_pQuitButton->ProcessInput(eInput, eInputState);
}
void CGameScreen::Render2D(float fInterpolation)
{
m_pBackground->Render();
m_pQuitButton->Render(fInterpolation);
m_sString1.Render();
m_sString2.Render();
}
void CGameScreen::QuitButtonReleaseFunc()
{
CRCNAudioSource* pSFX = CRCNAudioController::Create("RCNSFX_OnClick");
pSFX->Play();
pSFX->Release(CRCNAudioSource::ERelease::EOnceFinished);
g_pApplication->GetGame()->UnloadLevel();
CRCNScreenController::GetCurrentScreen()->SetPendingScreen(g_pApplication->m_sMenuScreenName);
CRCNScreenController::GetCurrentScreen()->SetScreenState(EScreenState_Finalising);
}
| [
"jim@leedh.am"
] | jim@leedh.am |
b03cfc0f131efcdc8d798234d6d33a24c428681a | 7cb98d91650d87747ca7c396c3ec3fa1404b482e | /Classes/SplashScene.h | 7da3e39cbf9b26eb94c0030790c01aa46d368687 | [] | no_license | AlexLazarev/Paranoid | ce32502af7a66c3d0cca61959de41156e212b576 | cf982815bc6fd397682812ff8a29c6f594c87776 | refs/heads/master | 2020-12-31T03:41:07.694808 | 2016-05-16T17:30:40 | 2016-05-16T17:30:40 | 56,865,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | h | #pragma once
#include "cocos2d.h"
#include "mainMenuScene.h"
#include "Definition.h"
class SplashScene : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// implement the "static create()" method manually
CREATE_FUNC(SplashScene);
private:
void GoToMainMenuScene(float dt);
};
| [
"alex_lazarev@mail.ua"
] | alex_lazarev@mail.ua |
bb9b44a285dca0d879fd9ec990b120451dbff8f9 | 20487d6bed34c8af7192064a234fe7db1461fdfc | /w10/Final_Project_Yucen_Cao/game.cpp | bcef9441af3b903d48beae44fb8900dd001c9ee4 | [] | no_license | caoyucen/OSU_CS162 | 0eaf911f8914e566df5b8b9e9f60ed0c3ad6340a | 16b9a920f6426ce454917b2e90f31f90cfe5736f | refs/heads/master | 2020-12-11T00:14:08.512837 | 2020-01-14T04:01:29 | 2020-01-14T04:01:29 | 233,749,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,308 | cpp | //
// game.cpp
//*********************************************************************
// Program name: Final project
// Author: YUCEN CAO - CS162 Spring 2019
// Date: June 11, 2019
// Description: In the final project, you will be able to design and implement a one-player, text-based game where the player can move through spaces to get items and accomplish goals.
// It is a collecting item game, when the player collect all the item, it will win.
// The max step is 11, step will reduce by each move.
// Every room has different items, and some of the room is very dangerous
// *********************************************************************
#include "game.hpp"
//check if all the items be collected
bool check_container(vector<char> container)
{
if (container.size() > 0){
std:: cout << std::endl << "The items in the container: ";
}
int a = 0; //&
int b = 0; //$
int c = 0; //#
for ( int i = 0; i < container.size(); i++){
std:: cout << " " << container[i] << " ";
if (container[i] == '&'){
a++;
}
else if (container[i] == '$'){
b++;
}
else if (container[i] == '#'){
c++;
}
}
std:: cout << std::endl << std::endl;
if (a*b*c == 0){
return (0);
}
return (1);
}
bool game(vector<char>* container, int step)
{
Lroom L;
Bedroom B1;
Bedroom B2;
Kitchen K;
Balcony C;
DogRoom D1;
DogRoom D2;
DogRoom D3;
DogRoom D4;
DogRoom D5;
DogRoom D6;
DogRoom D7;
DogRoom D8;
//set all the room in the location
//set_location(Space* left, Space* right, Space* top, Space* bottom);
L.set_location(&C, &K, &B1, &B2);
B1.set_location(&D1, &D3, &D2, &L);
B2.set_location(&D7, &D5, &L, &D6);
K.set_location(&L, &D4, &D3, &D5);
C.set_location(&D8, &L, &D1, &D7);
//test
//std::cout <<"here I am" << std::endl;
Space *standing;
standing = &L;
for (int z = 0; z < step; z++)
{
std::cout << std::endl;
std::cout << "******************************************" << std::endl;
std::cout << "-------------- No." << z+1 << " step ---------------"<< std::endl;
std::cout << "Target: get money($), clothes(&), knife(#)" << std::endl;
std::cout << "Be Careful! Dog is dangerous." << std::endl;
std::cout << step - z -1 << " steps left." << std::endl;
std::cout << "******************************************" << std::endl << std::endl;
int next = 0;
standing->print_map();
if(standing->see_dog() == 0){
if (standing->empty_room() == 0){
std::cout << "The room is empty, nothing to collect." << std::endl;
if (z == step -1){
return (0);
}
}
else{ //not empty room
standing->choose_item(container);
}
}
else{ //see dog
std::cout << "There is a dog in the room, you Pass Out in Shock, and wait for 5 step. " << std::endl;
std::cout << "If you don't die, you will wake up in the living room." << std::endl;
z = z + 5; //mark for step
if (z >= step){
return (0);
}
standing = &L;
}
if (check_container(*container) == 0){
next = menu_next();
if (next == 1){
standing = standing->get_top();
}
if (next == 2){
standing = standing->get_bottom();
}
if (next == 3){
standing = standing->get_left();
}
if (next == 4){
standing = standing->get_right();
}
}
else{
return(1); //win the game
}
}
return (0); //lose the game
}
| [
"caoyucen@gmail.com"
] | caoyucen@gmail.com |
38e2a13cd507fb8739b28bfc14ba013d9fc2dd67 | 1ef8b2e69ddd13e380f0e3b672edcce6032e74ea | /Application/SourceCode/GeneralDemo/Source/dragdroprobot/coloritem.cpp | e12a17bc88a6a697f176385910d6eb9bfc2c4798 | [] | no_license | nealwang123/Qt-Plugin-Project | 2f05f0b2f573cccc0987e8a0c12fb8b07ddc5c36 | dc7675bd1862dead8bc1b7b250b9c77fc570adf2 | refs/heads/master | 2022-07-20T01:29:14.037467 | 2020-05-16T06:59:48 | 2020-05-16T06:59:48 | 288,613,609 | 1 | 0 | null | 2020-08-19T02:30:06 | 2020-08-19T02:30:05 | null | UTF-8 | C++ | false | false | 2,705 | cpp | #include <QtGui>
#include "coloritem.h"
//! [0]
ColorItem::ColorItem()
: color(qrand() % 256, qrand() % 256, qrand() % 256)
{
setToolTip(QString("QColor(%1, %2, %3)\n%4")
.arg(color.red()).arg(color.green()).arg(color.blue())
.arg("Click and drag this color onto the robot!"));
setCursor(Qt::OpenHandCursor);
setAcceptedMouseButtons(Qt::LeftButton);
}
//! [0]
//! [1]
QRectF ColorItem::boundingRect() const
{
return QRectF(-15.5, -15.5, 34, 34);
}
//! [1]
//! [2]
void ColorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setPen(Qt::NoPen);
painter->setBrush(Qt::darkGray);
painter->drawEllipse(-12, -12, 30, 30);
painter->setPen(QPen(Qt::black, 1));
painter->setBrush(QBrush(color));
painter->drawEllipse(-15, -15, 30, 30);
}
//! [2]
//! [3]
void ColorItem::mousePressEvent(QGraphicsSceneMouseEvent *)
{
setCursor(Qt::ClosedHandCursor);
}
//! [3]
//! [5]
void ColorItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton))
.length() < QApplication::startDragDistance()) {
return;
}
//QDrag *drag = new QDrag(qobject_cast<QDrag *>(event->widget()));
QDrag *drag = new QDrag((QDrag *)event->widget());
QMimeData *mime = new QMimeData;
drag->setMimeData(mime);
//! [5]
//! [6]
static int n = 0;
if (n++ > 2 && (qrand() % 3) == 0) {
QImage image(":/images/head.png");
mime->setImageData(image);
drag->setPixmap(QPixmap::fromImage(image).scaled(30, 40));
drag->setHotSpot(QPoint(15, 30));
//! [6]
//! [7]
} else {
mime->setColorData(color);
mime->setText(QString("#%1%2%3")
.arg(color.red(), 2, 16, QLatin1Char('0'))
.arg(color.green(), 2, 16, QLatin1Char('0'))
.arg(color.blue(), 2, 16, QLatin1Char('0')));
QPixmap pixmap(34, 34);
pixmap.fill(Qt::white);
QPainter painter(&pixmap);
painter.translate(15, 15);
painter.setRenderHint(QPainter::Antialiasing);
paint(&painter, 0, 0);
painter.end();
pixmap.setMask(pixmap.createHeuristicMask());
drag->setPixmap(pixmap);
drag->setHotSpot(QPoint(15, 20));
}
//! [7]
//! [8]
drag->exec();
setCursor(Qt::OpenHandCursor);
}
//! [8]
//! [4]
void ColorItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *)
{
setCursor(Qt::OpenHandCursor);
}
//! [4]
| [
"574226409@qq.com"
] | 574226409@qq.com |
055550b6e04fd8e7794479c536c5e2845a322cd3 | 244bf2b00bd1b70d477bcc15465b3779a1bc8f88 | /FELICITY_Ver1.3.1/FELICITY/Static_Codes/Search_Trees/src_hdr/basetree.cc | 3f16cb2f2f3ec9c3f2f5f5b4f121380bca7acd69 | [
"BSD-3-Clause"
] | permissive | eardi/sm-fpca | 2349f0bb6bd3a70c9e3c893fe9843b31f4a6d6b1 | cc080f23681b637e24ca4935a1c85d9fa6003471 | refs/heads/master | 2021-05-16T05:35:05.054557 | 2020-10-23T11:19:53 | 2020-10-23T11:19:53 | 103,156,444 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,231 | cc | /*
============================================================================================
This is an abstract point-region (PR) search tree class. The basic use is to partition
points for fast searching operations.
Copyright (c) 01-14-2014, Shawn W. Walker
============================================================================================
*/
#include <vector>
#include <algorithm>
#include <cmath> // std::abs
typedef double pt_type;
typedef unsigned int UINT_type;
struct trCell; // proto-type
/***************************************************************************************/
/* keeps track of the new node (cell) that a point has traveled to. */
typedef struct
{
trCell* new_node; // pointer to cell that the point now lies in.
UINT_type pt_index; // global point index
} ExitPoint;
// this is used for sorting a vector of these structs
bool order_by_cell(const ExitPoint& i, const ExitPoint& j)
{
return (i.new_node < j.new_node); // sort by pointer value
}
/***************************************************************************************/
/***************************************************************************************/
/* used for doing k-nearest neighbor searches. */
typedef struct
{
UINT_type index;
pt_type dist;
} IndexDist;
// this is used for sorting a vector of these structs
bool order_by_dist(const IndexDist& i, const IndexDist& j)
{
return (i.dist < j.dist);
}
/***************************************************************************************/
// /* Maximum tree depth and related constants */
// #define tr_num_levels 16 // Number of possible levels in the tree
// #define tr_root_level 15 // Level of root cell (tr_num_levels - 1)
// #define tr_max_val 32768.0f // For converting positions to locational codes
// (tr_max_val = 2^tr_root_level)
/***************************************************************************************/
/* C++ (abstract) class */
#define BT basetree
class BT
{
public:
BT (); // constructor
~BT (); // DE-structor
// initializing
void Setup_Levels(const UINT_type);
// used for closest point
const std::vector<IndexDist>& Get_Closest_Point_Data() const {return ind_dist;}
protected:
// maximum tree depth and related constants
UINT_type tr_num_levels;
UINT_type tr_root_level;
UINT_type tr_max_val;
// maximum number of points to store in a tree leaf cell
UINT_type bucket_size;
// the ROOT node
trCell* root;
// track which point indices need to be updated
std::vector<ExitPoint> exited_point;
// counter for making sure the tree print-out lists all of the points (used for error checking)
UINT_type print_count;
// variables for closest point calculations
UINT_type num_neighbors;
std::vector<IndexDist> ind_dist;
// helper
//inline pt_type my_abs(const pt_type&);
inline pt_type clamp(const pt_type&, const pt_type&, const pt_type&);
inline bool in_interval(const pt_type&, const pt_type&, const pt_type&);
inline UINT_type my_trunc(const pt_type&);
};
/***************************************************************************************/
/* constructor */
BT::BT ()
{
// init
root = NULL;
tr_num_levels = 32; // default value
tr_root_level = tr_num_levels - 1;
tr_max_val = 1 << tr_root_level;
bucket_size = 20; // default value
exited_point.clear();
print_count = 0;
num_neighbors = 0;
ind_dist.clear();
}
/***************************************************************************************/
/***************************************************************************************/
/* destructor */
BT::~BT ()
{
}
/***************************************************************************************/
/***************************************************************************************/
/* setup tree levels and depth */
void BT::Setup_Levels(const UINT_type Max_Levels)
{
tr_num_levels = Max_Levels;
if (tr_num_levels < 2) mexErrMsgTxt("Maximum number of tree levels must be at least 2!\n");
if (tr_num_levels > 32) mexErrMsgTxt("Maximum number of tree levels must not exceed 32!\n");
// set these for future use
tr_root_level = tr_num_levels - 1;
tr_max_val = 1 << tr_root_level;
}
/***************************************************************************************/
// /***************************************************************************************/
// /* simple absolute value! */
// inline pt_type BT::my_abs(const pt_type& x)
// {
// if (x < 0)
// return -x;
// else
// return x;
// }
// /***************************************************************************************/
/***************************************************************************************/
/* clamp the value x to the range [a, b]
Note: must have a <= b. */
inline pt_type BT::clamp(const pt_type& x, const pt_type& a, const pt_type& b)
{
if (x <= a)
return a;
else if (x >= b)
return b;
else
return x;
}
/***************************************************************************************/
/***************************************************************************************/
/* Test whether x is in the interval [a,b).
Note: must have a <= b. */
inline bool BT::in_interval(const pt_type& x, const pt_type& a, const pt_type& b)
{
if ( (x >= a) && (x < b) )
return true;
else
return false;
}
/***************************************************************************************/
/***************************************************************************************/
/* truncate ``real'' number. */
inline UINT_type BT::my_trunc(const pt_type& VAL)
{
return (UINT_type) VAL;
}
/***************************************************************************************/
#undef BT
/***/
| [
"eardi.lila@gmail.com"
] | eardi.lila@gmail.com |
b5a4b25f7b997af03a0c21a61b9934c5255d7c09 | 2bf5dda3869b8faca2b0a3b2ad229500891b6879 | /WhiteGL/Src/Data/Notes/Notes.h | 84f0852973456be13683abad3a896f0a04752de2 | [] | no_license | metalS10/WhiteGL | 9347519b415779e44487972d1730364a3aa6e637 | 0194fadfd336a7e5a94de8531941c240e776abd7 | refs/heads/master | 2021-07-15T01:33:42.647101 | 2018-10-31T01:18:58 | 2018-10-31T01:18:58 | 106,292,629 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,234 | h | #pragma once
class CCharacter;
class CNotesUI;
//音に合わせて動かす動きの親
class CNotes
{
private:
public:
//コンストラクタ
CNotes() {};
~CNotes() {};
//2
virtual void half(CCharacter* pChara) = 0;
//4
virtual void quarter(CCharacter* pChara) = 0;
//8
virtual void eighth(CCharacter* pChara) = 0;
};
//音楽に合わせてアニメーションさせるクラス
class CNotesAnimation : CNotes
{
private:
public:
CNotesAnimation();
~CNotesAnimation();
virtual void half(CCharacter* pChara)override;
virtual void quarter(CCharacter* pChara)override;
virtual void eighth(CCharacter* pChara) override;
};
//音に合わせて動かす動きの親
class CNotes2
{
private:
protected:
//コンストラクタ
CNotes2() {};
~CNotes2() {};
//2
virtual void half(CNotesUI* pChara) = 0;
//4
virtual void quarter(CNotesUI* pChara) = 0;
//8
virtual void eighth(CNotesUI* pChara) = 0;
};
//音楽に合わせてアニメーションさせるクラス
class CNotesAnimation2 : CNotes2
{
private:
public:
CNotesAnimation2();
~CNotesAnimation2();
virtual void half(CNotesUI* pChara)override;
virtual void quarter(CNotesUI* pChara)override;
virtual void eighth(CNotesUI* pChara) override;
}; | [
"tatsujin10.04@gmail.com"
] | tatsujin10.04@gmail.com |
589c3a49e6d93d0c61cd5a8fb1b96d9bb7634cc6 | 2869112fdc836e565f9fe68e290affc1e223c1d8 | /pythran/pythonic/include/cmath/log10.hpp | fa90f97ae5b2737f9c87ff79070b1c20e01d216c | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | coyotte508/pythran | ab26e9ddb9a9e00e77b457df316aa33dc8435914 | a5da78f2aebae712a2c6260ab691dab7d09e307c | refs/heads/master | 2021-01-15T10:07:09.597297 | 2015-05-01T07:00:42 | 2015-05-01T07:00:42 | 35,020,532 | 0 | 0 | null | 2015-05-04T07:27:29 | 2015-05-04T07:27:29 | null | UTF-8 | C++ | false | false | 282 | hpp | #ifndef PYTHONIC_INCLUDE_CMATH_LOG10_HPP
#define PYTHONIC_INCLUDE_CMATH_LOG10_HPP
#include "pythonic/utils/proxy.hpp"
#include <cmath>
namespace pythonic {
namespace cmath {
ALIAS_DECL(log10 ,std::log10);
PROXY_DECL(pythonic::cmath, log10);
}
}
#endif
| [
"serge.guelton@telecom-bretagne.eu"
] | serge.guelton@telecom-bretagne.eu |
057b2d0b07eeae46764033911ec017e324c05e7e | aaf15ca1ce228898f32d98b531c35e203925928b | /chunked_stream.hpp | 319fd3518490bf84be08725c35769d9f84b57363 | [] | no_license | jehugaleahsa/spider-cpp | 0125c5e6ba423270374197a9c6e5b54dadf1e85b | ea1cb19ef559dfe043cdb03c3fed44df57c5a5cf | refs/heads/master | 2021-07-21T06:04:39.114955 | 2016-09-11T15:10:25 | 2016-09-11T15:10:25 | 4,440,285 | 15 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | hpp | #include <algorithm>
#include <iostream>
#include <memory>
#include <boost/iostreams/stream.hpp>
namespace {
template <typename CharT, typename Traits = std::char_traits<CharT>>
class ChunkedStreamSource {
std::shared_ptr<std::basic_istream<CharT, Traits>> m_stream;
std::streamsize m_chunkSize;
std::streamsize m_position;
public:
typedef CharT char_type;
typedef boost::iostreams::source_tag category;
ChunkedStreamSource(std::shared_ptr<std::basic_istream<CharT, Traits>> stream)
: m_stream(stream), m_chunkSize(), m_position() {
}
std::streamsize read(char * buffer, std::streamsize n) {
using std::copy;
using std::getline;
using std::hex;
using std::min;
using std::streamsize;
using std::string;
if (*m_stream && m_position == m_chunkSize) {
*m_stream >> hex >> m_chunkSize;
m_position = 0;
string ignore;
getline(*m_stream, ignore);
}
streamsize remaining = m_chunkSize - m_position;
streamsize count = min(remaining, n);
if (!m_stream->read(buffer, count)) {
return -1;
}
m_position += count;
return count;
}
};
}
namespace spider {
template <typename CharT, typename Traits = std::char_traits<CharT>>
class ChunkedStream : public virtual boost::iostreams::stream<ChunkedStreamSource<CharT, Traits>> {
public:
ChunkedStream(std::shared_ptr<std::basic_istream<CharT, Traits>> stream)
: boost::iostreams::stream<ChunkedStreamSource<CharT, Traits>>((ChunkedStreamSource<CharT, Traits>(stream))) {
}
};
}
| [
"jehugaleahsa@gmail.com"
] | jehugaleahsa@gmail.com |
d5ced1f78265dc1c8ea9e306434f9116ed603ea5 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /inc/Handle_TDataXtd_Pattern.hxx | 09ee99516d2afa3fe89aa39fceace9a2ebd2ca84 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _Handle_TDataXtd_Pattern_HeaderFile
#define _Handle_TDataXtd_Pattern_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineHandle_HeaderFile
#include <Standard_DefineHandle.hxx>
#endif
#ifndef _Handle_TDF_Attribute_HeaderFile
#include <Handle_TDF_Attribute.hxx>
#endif
class Standard_Transient;
class Handle(Standard_Type);
class Handle(TDF_Attribute);
class TDataXtd_Pattern;
DEFINE_STANDARD_HANDLE(TDataXtd_Pattern,TDF_Attribute)
#endif
| [
"shoka.sho2@excel.co.jp"
] | shoka.sho2@excel.co.jp |
0049ac08733ba7c3ecfb3ee6ee7f3817ffbaafa5 | becf7caa63d95071221c4120c0f238626b46100a | /src/Density_Estimation/Include/Descent_Direction_Factory.h | 7b2d1873a01fd0939289ddbb89c64ae749055ea9 | [] | no_license | cran/fdaPDE | 1acaf7798553c5582294cbb99c3a7207b78ccb55 | 4c275d6bfbcbbdef81e094fc977e60f68d1e24f3 | refs/heads/master | 2023-03-09T17:20:47.497214 | 2023-03-01T07:22:39 | 2023-03-01T07:22:39 | 49,715,847 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,727 | h | #ifndef __DESCENT_DIRECTION_FACTORY_H__
#define __DESCENT_DIRECTION_FACTORY_H__
#include <memory>
#include "../../Global_Utilities/Include/Make_Unique.h"
//! @brief A Factory class: a class for the choice of the direction for the optimization algorithm.
template<UInt ORDER, UInt mydim, UInt ndim>
class DescentDirection_factory
{
public:
//! A method that builds a pointer to the right object for the direction choice, taking as parameters a string and others objects needed for constructor.
static std::unique_ptr<DirectionBase<ORDER, mydim, ndim>>
createDirectionSolver(const DataProblem<ORDER, mydim, ndim>& dp,
const FunctionalProblem<ORDER, mydim, ndim>& fp, const std::string& d)
{
if (d=="Gradient")
return fdaPDE::make_unique<DirectionGradient<ORDER,mydim,ndim>>(fp);
else if (d=="BFGS")
return fdaPDE::make_unique<DirectionBFGS<ORDER,mydim,ndim>>(fp, dp.getNumNodes());
else{
Rprintf("Unknown direction option - using gradient direction");
return fdaPDE::make_unique<DirectionGradient<ORDER,mydim,ndim>>(fp);
}
}
};
//! @brief A Factory class: a class for the choice of the direction for the optimization algorithm (spatio-temporal setting).
template<UInt ORDER, UInt mydim, UInt ndim>
class DescentDirection_factory_time{
public:
//! A method that builds a pointer to the right object for the direction choice, taking as parameters a string and others objects needed for constructor.
static std::unique_ptr<DirectionBase<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>
createDirectionSolver(const DataProblem_time<ORDER, mydim, ndim>& dp,
const FunctionalProblem_time<ORDER, mydim, ndim>& fp, const std::string& d)
{
if (d=="Gradient")
return fdaPDE::make_unique<DirectionGradient<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp);
else if (d=="ConjugateGradientFR")
return fdaPDE::make_unique<DirectionConjugateGradient<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, 0);
else if (d=="ConjugateGradientPRP")
return fdaPDE::make_unique<DirectionConjugateGradient<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, 1);
else if (d=="ConjugateGradientHS")
return fdaPDE::make_unique<DirectionConjugateGradient<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, 2);
else if (d=="ConjugateGradientDY")
return fdaPDE::make_unique<DirectionConjugateGradient<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, 3);
else if (d=="ConjugateGradientCD")
return fdaPDE::make_unique<DirectionConjugateGradient<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, 4);
else if (d=="ConjugateGradientLS")
return fdaPDE::make_unique<DirectionConjugateGradient<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, 5);
else if (d=="BFGS")
return fdaPDE::make_unique<DirectionBFGS<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, dp.getNumNodes()*dp.getSplineNumber());
else if (d=="L-BFGS5")
return fdaPDE::make_unique<DirectionLBFGS<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, 5);
else if (d=="L-BFGS10")
return fdaPDE::make_unique<DirectionLBFGS<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp, 10);
else{
Rprintf("Unknown direction option - using gradient direction");
return fdaPDE::make_unique<DirectionGradient<ORDER, mydim, ndim, FunctionalProblem_time<ORDER, mydim, ndim>>>(fp);
}
}
};
#endif
| [
"csardi.gabor+cran@gmail.com"
] | csardi.gabor+cran@gmail.com |
36b0d71ec2b7664f5c15cabd837f17ea11e1ee57 | bacb43b4b870a2055d52d29a375ce388fd54d516 | /contracts/test_api/test_transaction.cpp | 2f2de43a59f8f68d6a6b14934e2e2652cfa09241 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | permissive | allenachain/Achainplus | 7ce701fad319de67e2340b51574402f6f7b6e1c3 | 610c0f5ca935de25fa3897023c740d841cdfc82e | refs/heads/master | 2020-05-05T13:07:02.929996 | 2019-04-22T09:06:54 | 2019-04-22T09:06:54 | 178,156,674 | 0 | 0 | MIT | 2019-03-28T08:12:03 | 2019-03-28T08:11:59 | null | UTF-8 | C++ | false | false | 11,406 | cpp | /**
* @file
* @copyright defined in Achainplus/LICENSE
*/
#include <eosiolib/action.hpp>
#include <eosiolib/crypto.h>
#include <eosiolib/transaction.hpp>
#include "test_api.hpp"
#pragma pack(push, 1)
template <uint64_t ACCOUNT, uint64_t NAME>
struct test_action_action {
static account_name get_account() {
return account_name(ACCOUNT);
}
static action_name get_name() {
return action_name(NAME);
}
eosio::vector<char> data;
template <typename DataStream>
friend DataStream& operator << ( DataStream& ds, const test_action_action& a ) {
for ( auto c : a.data )
ds << c;
return ds;
}
/*
template <typename DataStream>
friend DataStream& operator >> ( DataStream& ds, test_action_action& a ) {
return ds;
}
*/
};
template <uint64_t ACCOUNT, uint64_t NAME>
struct test_dummy_action {
static account_name get_account() {
return account_name(ACCOUNT);
}
static action_name get_name() {
return action_name(NAME);
}
char a;
unsigned long long b;
int32_t c;
template <typename DataStream>
friend DataStream& operator << ( DataStream& ds, const test_dummy_action& da ) {
ds << da.a;
ds << da.b;
ds << da.c;
return ds;
}
template <typename DataStream>
friend DataStream& operator >> ( DataStream& ds, test_dummy_action& da ) {
ds >> da.a;
ds >> da.b;
ds >> da.c;
return ds;
}
};
#pragma pack(pop)
void copy_data(char* data, size_t data_len, eosio::vector<char>& data_out) {
for (unsigned int i=0; i < data_len; i++)
data_out.push_back(data[i]);
}
void test_transaction::send_action() {
using namespace eosio;
test_dummy_action<N(testapi), WASM_TEST_ACTION("test_action", "read_action_normal")> test_action = {DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C};
action act(eosio::vector<permission_level>{{N(testapi), N(active)}}, test_action);
act.send();
}
void test_transaction::send_action_empty() {
using namespace eosio;
test_action_action<N(testapi), WASM_TEST_ACTION("test_action", "assert_true")> test_action;
action act(eosio::vector<permission_level>{{N(testapi), N(active)}}, test_action);
act.send();
}
/**
* cause failure due to a large action payload
*/
void test_transaction::send_action_large() {
using namespace eosio;
static char large_message[8 * 1024];
test_action_action<N(testapi), WASM_TEST_ACTION("test_action", "read_action_normal")> test_action;
copy_data(large_message, 8*1024, test_action.data);
action act(vector<permission_level>{{N(testapi), N(active)}}, test_action);
act.send();
eosio_assert(false, "send_message_large() should've thrown an error");
}
/**
* cause failure due recursive loop
*/
void test_transaction::send_action_recurse() {
using namespace eosio;
char buffer[1024];
read_action_data(buffer, 1024);
test_action_action<N(testapi), WASM_TEST_ACTION("test_transaction", "send_action_recurse")> test_action;
copy_data(buffer, 1024, test_action.data);
action act(vector<permission_level>{{N(testapi), N(active)}}, test_action);
act.send();
}
/**
* cause failure due to inline TX failure
*/
void test_transaction::send_action_inline_fail() {
using namespace eosio;
test_action_action<N(testapi), WASM_TEST_ACTION("test_action", "assert_false")> test_action;
action act(vector<permission_level>{{N(testapi), N(active)}}, test_action);
act.send();
}
void test_transaction::test_tapos_block_prefix() {
using namespace eosio;
int tbp;
read_action_data( (char*)&tbp, sizeof(int) );
eosio_assert( tbp == tapos_block_prefix(), "tapos_block_prefix does not match" );
}
void test_transaction::test_tapos_block_num() {
using namespace eosio;
int tbn;
read_action_data( (char*)&tbn, sizeof(int) );
eosio_assert( tbn == tapos_block_num(), "tapos_block_num does not match" );
}
void test_transaction::test_read_transaction() {
using namespace eosio;
checksum256 h;
auto size = transaction_size();
char buf[size];
uint32_t read = read_transaction( buf, size );
eosio_assert( size == read, "read_transaction failed");
sha256(buf, read, &h);
printhex( &h, sizeof(h) );
}
void test_transaction::test_transaction_size() {
using namespace eosio;
uint32_t trans_size = 0;
read_action_data( (char*)&trans_size, sizeof(uint32_t) );
print( "size: ", transaction_size() );
eosio_assert( trans_size == transaction_size(), "transaction size does not match" );
}
void test_transaction::send_transaction(uint64_t receiver, uint64_t, uint64_t) {
using namespace eosio;
dummy_action payload = {DUMMY_ACTION_DEFAULT_A, DUMMY_ACTION_DEFAULT_B, DUMMY_ACTION_DEFAULT_C};
test_action_action<N(testapi), WASM_TEST_ACTION("test_action", "read_action_normal")> test_action;
copy_data((char*)&payload, sizeof(dummy_action), test_action.data);
auto trx = transaction();
trx.actions.emplace_back(vector<permission_level>{{N(testapi), N(active)}}, test_action);
trx.send(0, receiver);
}
void test_transaction::send_action_sender(uint64_t receiver, uint64_t, uint64_t) {
using namespace eosio;
account_name cur_send;
read_action_data( &cur_send, sizeof(account_name) );
test_action_action<N(testapi), WASM_TEST_ACTION("test_action", "test_current_sender")> test_action;
copy_data((char*)&cur_send, sizeof(account_name), test_action.data);
auto trx = transaction();
trx.actions.emplace_back(vector<permission_level>{{N(testapi), N(active)}}, test_action);
trx.send(0, receiver);
}
void test_transaction::send_transaction_empty(uint64_t receiver, uint64_t, uint64_t) {
using namespace eosio;
auto trx = transaction();
trx.send(0, receiver);
eosio_assert(false, "send_transaction_empty() should've thrown an error");
}
void test_transaction::send_transaction_trigger_error_handler(uint64_t receiver, uint64_t, uint64_t) {
using namespace eosio;
auto trx = transaction();
test_action_action<N(testapi), WASM_TEST_ACTION("test_action", "assert_false")> test_action;
trx.actions.emplace_back(vector<permission_level>{{N(testapi), N(active)}}, test_action);
trx.send(0, receiver);
}
void test_transaction::assert_false_error_handler(const eosio::transaction& dtrx) {
eosio_assert(dtrx.actions.size() == 1, "transaction should only have one action");
eosio_assert(dtrx.actions[0].account == N(testapi), "transaction has wrong code");
eosio_assert(dtrx.actions[0].name == WASM_TEST_ACTION("test_action", "assert_false"), "transaction has wrong name");
eosio_assert(dtrx.actions[0].authorization.size() == 1, "action should only have one authorization");
eosio_assert(dtrx.actions[0].authorization[0].actor == N(testapi), "action's authorization has wrong actor");
eosio_assert(dtrx.actions[0].authorization[0].permission == N(active), "action's authorization has wrong permission");
}
/**
* cause failure due to a large transaction size
*/
void test_transaction::send_transaction_large(uint64_t receiver, uint64_t, uint64_t) {
using namespace eosio;
auto trx = transaction();
for (int i = 0; i < 32; i ++) {
char large_message[1024];
test_action_action<N(testapi), WASM_TEST_ACTION("test_action", "read_action_normal")> test_action;
copy_data(large_message, 1024, test_action.data);
trx.actions.emplace_back(vector<permission_level>{{N(testapi), N(active)}}, test_action);
}
trx.send(0, receiver);
eosio_assert(false, "send_transaction_large() should've thrown an error");
}
/**
* deferred transaction
*/
void test_transaction::deferred_print() {
eosio::print("deferred executed\n");
}
void test_transaction::send_deferred_transaction(uint64_t receiver, uint64_t, uint64_t) {
using namespace eosio;
auto trx = transaction();
test_action_action<N(testapi), WASM_TEST_ACTION("test_transaction", "deferred_print")> test_action;
trx.actions.emplace_back(vector<permission_level>{{N(testapi), N(active)}}, test_action);
trx.delay_sec = 2;
trx.send( 0xffffffffffffffff, receiver );
}
void test_transaction::send_deferred_transaction_replace(uint64_t receiver, uint64_t, uint64_t) {
using namespace eosio;
auto trx = transaction();
test_action_action<N(testapi), WASM_TEST_ACTION("test_transaction", "deferred_print")> test_action;
trx.actions.emplace_back(vector<permission_level>{{N(testapi), N(active)}}, test_action);
trx.delay_sec = 2;
trx.send( 0xffffffffffffffff, receiver, true );
}
void test_transaction::send_deferred_tx_with_dtt_action() {
using namespace eosio;
dtt_action dtt_act;
read_action_data(&dtt_act, action_data_size());
action deferred_act;
deferred_act.account = dtt_act.deferred_account;
deferred_act.name = dtt_act.deferred_action;
deferred_act.authorization = vector<permission_level>{{N(testapi), dtt_act.permission_name}};
auto trx = transaction();
trx.actions.emplace_back(deferred_act);
trx.delay_sec = dtt_act.delay_sec;
cancel_deferred( 0xffffffffffffffff ); // TODO: Remove this line after fixing deferred trx replacement RAM bug
trx.send( 0xffffffffffffffff, dtt_act.payer, true );
}
void test_transaction::cancel_deferred_transaction_success() {
using namespace eosio;
auto r = cancel_deferred( 0xffffffffffffffff ); //use the same id (0) as in send_deferred_transaction
eosio_assert( (bool)r, "transaction was not found" );
}
void test_transaction::cancel_deferred_transaction_not_found() {
using namespace eosio;
auto r = cancel_deferred( 0xffffffffffffffff ); //use the same id (0) as in send_deferred_transaction
eosio_assert( !r, "transaction was canceled, whild should not be found" );
}
void test_transaction::send_cf_action() {
using namespace eosio;
test_action_action<N(dummy), N(event1)> cfa;
action act(cfa);
act.send_context_free();
}
void test_transaction::send_cf_action_fail() {
using namespace eosio;
test_action_action<N(dummy), N(event1)> cfa;
action act(vector<permission_level>{{N(dummy), N(active)}}, cfa);
act.send_context_free();
eosio_assert(false, "send_cfa_action_fail() should've thrown an error");
}
void test_transaction::stateful_api() {
char buf[4] = {1};
db_store_i64(N(test_transaction), N(table), N(test_transaction), 0, buf, 4);
}
void test_transaction::context_free_api() {
char buf[128] = {0};
get_context_free_data(0, buf, sizeof(buf));
}
extern "C" { int is_feature_active(int64_t); }
void test_transaction::new_feature() {
eosio_assert(false == is_feature_active((int64_t)N(newfeature)), "we should not have new features unless hardfork");
}
void test_transaction::active_new_feature() {
activate_feature((int64_t)N(newfeature));
}
void test_transaction::repeat_deferred_transaction(uint64_t receiver, uint64_t code, uint64_t action) {
using namespace eosio;
uint128_t sender_id = 0;
uint32_t payload = unpack_action_data<uint32_t>();
print( "repeat_deferred_transaction called: payload = ", payload );
bool res = cancel_deferred( sender_id );
print( "\nrepeat_deferred_transaction cancelled trx with sender_id = ", sender_id, ", result is ", res );
if( payload == 0 ) return;
--payload;
transaction trx;
trx.actions.emplace_back( permission_level{receiver, N(active)}, code, action, payload );
trx.send( sender_id, receiver );
}
| [
"xiaoming@new4g.cn"
] | xiaoming@new4g.cn |
4046180501817276f9bcbbee366f0faca9006c86 | a01ea55cc0a4128587a339536bb6b0411e367fe2 | /22-Agosto/ConsolaVentas/TrabajadorPorHora.h | a9877a375d7988debcb58f378cd8df631938dfdf | [
"MIT"
] | permissive | AlejandroSolares/EDA | 9ee8886ed5e92b8d4797871bc3b022dd131c9b15 | 8c9d24d33f2ff9df5b31a2e782b367582556ef2b | refs/heads/master | 2022-12-11T14:53:14.044568 | 2020-09-13T16:04:27 | 2020-09-13T16:04:27 | 287,684,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 942 | h | #ifndef TRABAJADORPORHORA
#define TRABAJADORPORHORA
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include "Trabajador.h"
class TrabajadorPorHora: public Trabajador{
private:
int numHT;
float salarioPorHora;
public:
TrabajadorPorHora(){
this->numHT = 0;
this->salarioPorHora = 0;
}
TrabajadorPorHora(int idP, string nP, string aP, int nHT, float sPH) : Trabajador(idP,nP,aP){
this->numHT = nHT;
this->salarioPorHora = sPH;
this->sueldo = nHT * sPH;
this->descuentoIsr = this->sueldo * 0.1;
this->totalDescuentos = this->descuentoIsr;
this->totalPagar = this->sueldo - this->totalDescuentos;
}
int getNumHT(){
return this->numHT;
}
int getSalarioPorHora(){
return this->salarioPorHora;
}
int getTipoTrabajador(){
return 1;
}
};
#endif // TRABAJADORPORHORA
| [
"josue.alejandro.solares@gmail.com"
] | josue.alejandro.solares@gmail.com |
d12286886602d6993ec3d8f93d8b05fe8f260f6d | 6312008999fb1fa21190653ed74835bd771e935c | /GeneSplicer.cpp | 5e64eb46fc42431f2623c12bbb2a8dce46c64a9b | [] | no_license | tehilabadi/EX4_A_Cpp | 98afe347a43572644be09cfcfdbdb47767feeae8 | c67b3882566d1c42b4aa51f460d6c7b84f1e38ba | refs/heads/master | 2023-04-12T08:53:01.355259 | 2021-05-04T19:57:00 | 2021-05-04T19:57:00 | 364,370,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | cpp | #include <iostream>
using namespace std;
#include "Player.hpp"
#include "Board.hpp"
#include "GeneSplicer.hpp"
namespace pandemic{
GeneSplicer::GeneSplicer(Board board, City city){
}
} | [
"tehilaqwer@gmail.com"
] | tehilaqwer@gmail.com |
e5b7b5f74d7e37e25f63511c38dedc6a58e766fc | 13d1081bc5d46f979580438a772f47b7dc15550c | /Projects/Logic/Client/Src/UIQuestTrace.cpp | a34a03e50659cfec33565c088102b53e036ace8e | [] | no_license | hackerlank/code-2 | 090035cc470d77a13a589419da7b04d0b97419e8 | c8e72ad7ce7440001293a10619cd01efe5cfd22f | refs/heads/master | 2021-01-13T15:50:39.784391 | 2014-06-16T14:00:06 | 2014-06-16T14:00:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 596 | cpp | //***************************************************************************************************
#include "stdafx.h"
#include "UIQuestTrace.h"
//***************************************************************************************************
namespace MG
{
UIQuestTrace::UIQuestTrace()
{
}
//----------------------------------------------------------------------------------------
UIQuestTrace::~UIQuestTrace()
{
}
//----------------------------------------------------------------------------------------
void UIQuestTrace::setEvent()
{
}
} | [
"linhu917@126.com"
] | linhu917@126.com |
d40a510b6da3204706efb1bd0a1ee3435083b6a8 | 4dc036f9fafdca1d73fa1137c0f3c20b82f9ec64 | /tail_recursion/factorial.cpp | 94fb08a706e1720797b6d44d4c57dd66216897db | [] | no_license | yash-dxt/algos-for-all | 44be5c40039c7461b8006aec5b1ccda71463b709 | 51b6b499b868b0d87caec33b229b25157c5166c0 | refs/heads/master | 2023-04-20T19:45:58.575257 | 2021-05-08T09:16:54 | 2021-05-08T10:54:07 | 308,859,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | cpp | #include <iostream>
using namespace std;
int factorial(int x, int tailFactorial = 1)
{
if (x == 1)
return tailFactorial;
return factorial(x - 1, x * tailFactorial);
}
int main()
{
cout << factorial(3);
}
| [
"yashdixitsq@gmail.com"
] | yashdixitsq@gmail.com |
99f583a6e948f9e9beb16359bc6abbb373bab625 | 67e08000ca2cf8ae4595bfcce9f1ef2b6001a3cc | /catkin_ws/devel/include/gsdf_msgs/CommContent.h | bd02454bcb7e47db118f747c48d7d7bd60bb05fd | [] | no_license | REGATTE/copter_deep_learning_build | 60e490f1eb2254188f5f160ef837a1a281a1ab19 | cb77b5e6d1591a964c2ef7d3e2ae8ada56ad39c0 | refs/heads/master | 2023-03-03T22:25:05.289131 | 2021-02-17T08:13:57 | 2021-02-17T08:13:57 | 339,652,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,990 | h | // Generated by gencpp from file gsdf_msgs/CommContent.msg
// DO NOT EDIT!
#ifndef GSDF_MSGS_MESSAGE_COMMCONTENT_H
#define GSDF_MSGS_MESSAGE_COMMCONTENT_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace gsdf_msgs
{
template <class ContainerAllocator>
struct CommContent_
{
typedef CommContent_<ContainerAllocator> Type;
CommContent_()
: buf() {
}
CommContent_(const ContainerAllocator& _alloc)
: buf(_alloc) {
(void)_alloc;
}
typedef std::vector<uint8_t, typename ContainerAllocator::template rebind<uint8_t>::other > _buf_type;
_buf_type buf;
typedef boost::shared_ptr< ::gsdf_msgs::CommContent_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::gsdf_msgs::CommContent_<ContainerAllocator> const> ConstPtr;
}; // struct CommContent_
typedef ::gsdf_msgs::CommContent_<std::allocator<void> > CommContent;
typedef boost::shared_ptr< ::gsdf_msgs::CommContent > CommContentPtr;
typedef boost::shared_ptr< ::gsdf_msgs::CommContent const> CommContentConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::gsdf_msgs::CommContent_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::gsdf_msgs::CommContent_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace gsdf_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'gsdf_msgs': ['/home/user/catkin_ws/src/micros_swarm_framework/core/gsdf_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::gsdf_msgs::CommContent_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::gsdf_msgs::CommContent_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::gsdf_msgs::CommContent_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::gsdf_msgs::CommContent_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::gsdf_msgs::CommContent_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::gsdf_msgs::CommContent_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::gsdf_msgs::CommContent_<ContainerAllocator> >
{
static const char* value()
{
return "4f7b5949e76f86d01e96b0e33ba9b5e3";
}
static const char* value(const ::gsdf_msgs::CommContent_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x4f7b5949e76f86d0ULL;
static const uint64_t static_value2 = 0x1e96b0e33ba9b5e3ULL;
};
template<class ContainerAllocator>
struct DataType< ::gsdf_msgs::CommContent_<ContainerAllocator> >
{
static const char* value()
{
return "gsdf_msgs/CommContent";
}
static const char* value(const ::gsdf_msgs::CommContent_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::gsdf_msgs::CommContent_<ContainerAllocator> >
{
static const char* value()
{
return "uint8[] buf\n\
";
}
static const char* value(const ::gsdf_msgs::CommContent_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::gsdf_msgs::CommContent_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.buf);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct CommContent_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::gsdf_msgs::CommContent_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::gsdf_msgs::CommContent_<ContainerAllocator>& v)
{
s << indent << "buf[]" << std::endl;
for (size_t i = 0; i < v.buf.size(); ++i)
{
s << indent << " buf[" << i << "]: ";
Printer<uint8_t>::stream(s, indent + " ", v.buf[i]);
}
}
};
} // namespace message_operations
} // namespace ros
#endif // GSDF_MSGS_MESSAGE_COMMCONTENT_H
| [
"ashok_a380@icloud.com"
] | ashok_a380@icloud.com |
5c409663f00ab8fe727c93052c2479fdeaccaded | 932c79e3c443290924ad4c592ee2959227ca604a | /Searching/twoRepeatedElements.cpp | 4cc642636b489f22a4943f62a2b665d0e2e1478a | [] | no_license | rohanjha613/GeeksForGeeksDSA | beaff45bd4468508a44fbc791fd7205e6eb7da8c | 1549b5f0d451a561977501724596ffefa866435b | refs/heads/main | 2023-08-21T19:33:23.072577 | 2021-10-02T11:20:11 | 2021-10-02T11:20:11 | 410,829,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,029 | cpp | // { Driver Code Starts
//Initial template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution {
public:
//Function to find two repeated elements.
vector<int> twoRepeated (int arr[], int N) {
int first=-1,second=-1;
for(int i=0;i<N+2;i++)
{
if(arr[arr[i]-1] < 0){
if(first==-1)
first=abs(arr[i]);
else
second=abs(arr[i]);
}
else
arr[abs(arr[i])]=-(arr[abs(arr[i])]);
}
return {first,second};
}
};
// { Driver Code Starts.
int main()
{
int t,n;
cin>>t;
while(t--)
{
cin>>n;
int a[n+2];
for(int i=0;i<n+2;i++)
cin>>a[i];
Solution obj;
vector<int> res;
res = obj.twoRepeated(a, n);
cout<<res[0]<<" "<<res[1]<<endl;
}
return 0;
}
// } Driver Code Ends | [
"jharohan613@gmail.com"
] | jharohan613@gmail.com |
30e929bee0eab14ad853a7f4a1619f33fb44b2a9 | 26b44414ec79f1fb6a501ec3a1ff7ba23d12983a | /ICDSMSCE/BasicDataStructure/Timestamp.h | 9f1317423a0698004d84c42056b0d46947a11ed1 | [] | no_license | lwhay/ICDMS | d74d8f894d1b353e8dc00a0e6b98a9545b10077e | 3168d48fec96913a26b8a6a837b38dff1f70c8a3 | refs/heads/master | 2021-01-01T08:21:05.620874 | 2014-03-23T15:10:02 | 2014-03-23T15:10:02 | 17,953,721 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | h | #ifndef _TIME_STAMP_H
#define _TIME_STAMP_H
//#include <boost/date_time/local_time/local_time.hpp>
//#include <boost/date_time/posix_time/posix_time.hpp>
//
////to be replaced with Boost time
//class Time {
//public:
// bool operator == (const Time& rhs) {
// return true;
// }
//
// bool operator > (const Time& rhs) {
// return true;
// }
//};
//
//class TimeStamp {
//public:
// Time start;
// Time end;
//};
namespace Cayuga {
namespace BasicDataStructure {
typedef long long TimeStamp;
} //namespace BasicDataStructure
} //namespace Cayuga
#endif //_TIME_STAMP_H
| [
"lwh@whu.edu.cn"
] | lwh@whu.edu.cn |
6f756cab68f7cfd9bb7c6c0f8d456d54ae8e89fc | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/squid/old_hunk_1193.cpp | a925a13bd9f1ca9f755d1b6acd741d775072c93c | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | if (req_sz >= Config.maxRequestHeaderSize) {
debugs(33, 5, "parseHttpRequest: Too large request");
hp->request_parse_status = Http::scHeaderTooLarge;
return parseHttpRequestAbort(csd, "error:request-too-large");
}
/* Set method_p */
| [
"993273596@qq.com"
] | 993273596@qq.com |
a8fe97307ab1b0f3e8a24eb160bfe7535233024c | 5e29bf3048f53ce6584c814c4b5c003c917187b8 | /202.快乐数.cpp | 3f88802f327515856a9229d96c3e4d210fe8f2fc | [] | no_license | MrZilinXiao/BasicLeetCode | 9a78ad21bfa0580418416c91a1cb0b2b03d58023 | 067679579d9dafe1767a1ad508b4a9d724effcc6 | refs/heads/master | 2020-05-04T22:27:26.597310 | 2019-10-24T01:29:29 | 2019-10-24T01:29:29 | 179,512,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 524 | cpp | /*
* @lc app=leetcode.cn id=202 lang=cpp
*
* [202] 快乐数
*/
class Solution {
public:
bool isHappy(int n) {
int fast = n, slow = n;
do{
slow=squareSum(slow);
fast=squareSum(fast);
fast=squareSum(fast);
}while(fast!=slow);
if(fast==1) return true;
else return false;
}
int squareSum(int v){
int sum = 0;
while(v>0){
sum += (v%10)*(v%10);
v = v / 10;
}
return sum;
}
};
| [
"xiaozilin1@gmail.com"
] | xiaozilin1@gmail.com |
762e231bd5169ba256276804f4b5b55b13d726e8 | a1ec33b19336ec1dfa6632131c55d8e33088ebd0 | /iaimp/aimp_sdk/Sources/Cpp/apiGUI.h | c49c846696f82a390ac96882ae7ed5e19d626ff8 | [
"MIT",
"Apache-2.0"
] | permissive | ark0f/aimp.rs | 24a468f8ce23fd38e526be7900a9bd87a5dda23a | dc2e650dd8b9b7751d40a2ff9b97cfbb3fd18967 | refs/heads/master | 2022-12-06T22:01:54.871684 | 2020-08-20T16:39:26 | 2020-08-20T16:39:26 | 279,051,798 | 0 | 0 | Apache-2.0 | 2020-08-20T16:39:28 | 2020-07-12T11:38:17 | Pascal | UTF-8 | C++ | false | false | 50,485 | h | /************************************************/
/* */
/* AIMP Programming Interface */
/* v4.60 build 2100 */
/* */
/* Artem Izmaylov */
/* (C) 2006-2019 */
/* www.aimp.ru */
/* */
/* Mail: support@aimp.ru */
/* */
/************************************************/
#ifndef apiGUIH
#define apiGUIH
#include <windows.h>
#include <unknwn.h>
#include "apiObjects.h"
#include "apiMenu.h"
static const GUID IID_IAIMPServiceUI = {0x41494D50, 0x5365, 0x7276, 0x69, 0x63, 0x65, 0x55, 0x49, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIDPIAwareness = {0x61756944, 0x5049, 0x4177, 0x61, 0x72, 0x65, 0x6E, 0x65, 0x73, 0x73, 0x00};
static const GUID IID_IAIMPUIBaseButtonnedEdit = {0x61756942, 0x6173, 0x6542, 0x74, 0x6E, 0x45, 0x64, 0x69, 0x74, 0x00, 0x00};
static const GUID IID_IAIMPUIBaseComboBox = {0x61756942, 0x6173, 0x6543, 0x6F, 0x6D, 0x62, 0x6F, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIBaseEdit = {0x61756942, 0x6173, 0x6545, 0x64, 0x69, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIBBCBox = {0x61756942, 0x4243, 0x426F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIBevel = {0x61756942, 0x6576, 0x656C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIBrandBox = {0x61756942, 0x7261, 0x6E64, 0x42, 0x6F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIBrowseFolderDialog = {0x61756942, 0x7277, 0x7346, 0x6C, 0x64, 0x72, 0x44, 0x6C, 0x67, 0x00, 0x00};
static const GUID IID_IAIMPUIButton = {0x61756942, 0x7574, 0x746F, 0x6E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUICategory = {0x61756943, 0x6174, 0x6567, 0x6F, 0x72, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIChangeEvents = {0x61756945, 0x766E, 0x7443, 0x68, 0x61, 0x6E, 0x67, 0x65, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUICheckBox = {0x61756943, 0x6865, 0x636B, 0x42, 0x6F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUICheckComboBox = {0x61756943, 0x6865, 0x636B, 0x65, 0x64, 0x43, 0x6F, 0x6D, 0x62, 0x6F, 0x00};
static const GUID IID_IAIMPUIComboBox = {0x61756943, 0x6F6D, 0x626F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIControl = {0x61756943, 0x6F6E, 0x7472, 0x6F, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIDrawEvents = {0x61756945, 0x766E, 0x7444, 0x72, 0x61, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIEdit = {0x61756945, 0x6469, 0x7400, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIEditButton = {0x61756945, 0x6469, 0x7442, 0x74, 0x6E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIFileDialogs = {0x61756946, 0x696C, 0x6544, 0x6C, 0x67, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIForm = {0x61756946, 0x6F72, 0x6D00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIFormEvents = {0x61756946, 0x6F72, 0x6D45, 0x76, 0x65, 0x6E, 0x74, 0x73, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIFormEvents2 = {0x61756946, 0x6F72, 0x6D45, 0x76, 0x65, 0x6E, 0x74, 0x73, 0x32, 0x00, 0x00};
static const GUID IID_IAIMPUIFormEvents3 = {0x61756946, 0x6F72, 0x6D45, 0x76, 0x65, 0x6E, 0x74, 0x73, 0x33, 0x00, 0x00};
static const GUID IID_IAIMPUIGroupBox = {0x61756947, 0x726F, 0x7570, 0x42, 0x6F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIImage = {0x61756949, 0x6D61, 0x6765, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIImageComboBox = {0x61756949, 0x6D61, 0x6765, 0x43, 0x6F, 0x6D, 0x62, 0x6F, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIImageList = {0x61756949, 0x6D67, 0x4C69, 0x73, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIImageList2 = {0x61756949, 0x6D67, 0x4C69, 0x73, 0x74, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIInputDialog = {0x61756949, 0x6E70, 0x7574, 0x44, 0x6C, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIInputDialogEvents = {0x61756949, 0x6E70, 0x7574, 0x44, 0x6C, 0x67, 0x45, 0x76, 0x6E, 0x74, 0x00};
static const GUID IID_IAIMPUIKeyboardEvents = {0x61756945, 0x766E, 0x744B, 0x65, 0x79, 0x62, 0x6F, 0x61, 0x72, 0x64, 0x00};
static const GUID IID_IAIMPUILabel = {0x6175694C, 0x6162, 0x656C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIMemo = {0x6175694D, 0x656D, 0x6F00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIMenuItem = {0x6175694D, 0x656E, 0x7549, 0x74, 0x65, 0x6D, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIMessageDialog = {0x6175694D, 0x7367, 0x446C, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIMouseEvents = {0x61756945, 0x766E, 0x744D, 0x6F, 0x75, 0x73, 0x65, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIMouseWheelEvents = {0x61756945, 0x766E, 0x744D, 0x6F, 0x75, 0x73, 0x65, 0x57, 0x68, 0x6C, 0x00};
static const GUID IID_IAIMPUIPageControl = {0x61756950, 0x6167, 0x6543, 0x74, 0x72, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIPageControlEvents = {0x61756950, 0x6167, 0x6543, 0x74, 0x72, 0x6C, 0x45, 0x76, 0x6E, 0x74, 0x00};
static const GUID IID_IAIMPUIPaintBox = {0x61756950, 0x6169, 0x6E74, 0x42, 0x6F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIPanel = {0x61756950, 0x616E, 0x656C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIPlacementEvents = {0x61756945, 0x766E, 0x7442, 0x6F, 0x75, 0x6E, 0x64, 0x73, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIPopupMenu = {0x61756950, 0x6F70, 0x7570, 0x4D, 0x65, 0x6E, 0x75, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIPopupMenuEvents = {0x61756945, 0x766E, 0x7450, 0x6F, 0x70, 0x75, 0x70, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIProgressBar = {0x61756950, 0x726F, 0x6772, 0x65, 0x73, 0x73, 0x42, 0x61, 0x72, 0x00, 0x00};
static const GUID IID_IAIMPUIProgressDialog = {0x61756950, 0x726F, 0x6772, 0x65, 0x73, 0x73, 0x44, 0x6C, 0x67, 0x00, 0x00};
static const GUID IID_IAIMPUIProgressDialogEvents = {0x61756950, 0x7267, 0x7273, 0x44, 0x6C, 0x67, 0x45, 0x76, 0x6E, 0x74, 0x00};
static const GUID IID_IAIMPUIRadioBox = {0x61756952, 0x6164, 0x696F, 0x42, 0x6F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIScrollBox = {0x61756953, 0x6372, 0x6F6C, 0x6C, 0x42, 0x6F, 0x78, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUISlider = {0x61756953, 0x6C69, 0x6465, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUISpinEdit = {0x61756953, 0x7069, 0x6E45, 0x64, 0x69, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUISplitter = {0x61756953, 0x706C, 0x6974, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITabControl = {0x61756954, 0x6162, 0x4374, 0x72, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITabControlEvents = {0x61756954, 0x6162, 0x4374, 0x72, 0x6C, 0x45, 0x76, 0x6E, 0x74, 0x73, 0x00};
static const GUID IID_IAIMPUITabSheet = {0x61756954, 0x6162, 0x5368, 0x65, 0x65, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITimeEdit = {0x61756954, 0x696D, 0x6545, 0x64, 0x69, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITreeList = {0x61756954, 0x4C00, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITreeListColumn = {0x61756954, 0x4C43, 0x6F6C, 0x75, 0x6D, 0x6E, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITreeListCustomDrawEvents = {0x61756954, 0x4C44, 0x7261, 0x77, 0x45, 0x76, 0x6E, 0x74, 0x73, 0x00, 0x00};
static const GUID IID_IAIMPUITreeListDragSortingEvents = {0x6169544C, 0x4472, 0x6167, 0x53, 0x6F, 0x72, 0x74, 0x45, 0x76, 0x6E, 0x74};
static const GUID IID_IAIMPUITreeListEvents = {0x61756954, 0x4C45, 0x7665, 0x6E, 0x74, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITreeListGroup = {0x61756954, 0x4C47, 0x726F, 0x75, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITreeListInplaceEditingEvents = {0x61756954, 0x4C45, 0x6474, 0x45, 0x76, 0x6E, 0x74, 0x73, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUITreeListNode = {0x61756954, 0x4C4E, 0x6F64, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIValidationLabel = {0x61756956, 0x616C, 0x6964, 0x4C, 0x61, 0x62, 0x65, 0x6C, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIWinControl = {0x61756957, 0x696E, 0x4374, 0x72, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static const GUID IID_IAIMPUIWndProcEvents = {0x61756957, 0x6E64, 0x5072, 0x6F, 0x63, 0x45, 0x76, 0x6E, 0x74, 0x73, 0x00};
/*----------------------------------------------------------------------------------------------------------------------*/
/* Flags */
/*----------------------------------------------------------------------------------------------------------------------*/
const int AIMPUI_STYLE_LIGHT = 0;
const int AIMPUI_STYLE_DARK = 1;
// Modifiers Flags
const int AIMPUI_FLAGS_MOD_ALT = 1;
const int AIMPUI_FLAGS_MOD_CTRL = 2;
const int AIMPUI_FLAGS_MOD_SHIFT = 4;
// Borders Flags
const int AIMPUI_FLAGS_BORDER_LEFT = 1;
const int AIMPUI_FLAGS_BORDER_TOP = 2;
const int AIMPUI_FLAGS_BORDER_RIGHT = 4;
const int AIMPUI_FLAGS_BORDER_BOTTOM = 8;
// Font Style Flags
const int AIMPUI_FLAGS_FONT_BOLD = 1;
const int AIMPUI_FLAGS_FONT_ITALIC = 2;
const int AIMPUI_FLAGS_FONT_UNDERLINE = 4;
const int AIMPUI_FLAGS_FONT_STRIKEOUT = 8;
// Modal Result Flags
const int AIMPUI_FLAGS_MODALRESULT_NONE = 0;
const int AIMPUI_FLAGS_MODALRESULT_OK = 1;
const int AIMPUI_FLAGS_MODALRESULT_CANCEL = 2;
const int AIMPUI_FLAGS_MODALRESULT_ABORT = 3;
const int AIMPUI_FLAGS_MODALRESULT_RETRY = 4;
const int AIMPUI_FLAGS_MODALRESULT_IGNORE = 5;
const int AIMPUI_FLAGS_MODALRESULT_YES = 6;
const int AIMPUI_FLAGS_MODALRESULT_NO = 7;
const int AIMPUI_FLAGS_MODALRESULT_CLOSE = 8;
const int AIMPUI_FLAGS_MODALRESULT_HELP = 9;
const int AIMPUI_FLAGS_MODALRESULT_TRYAGAIN = 10;
const int AIMPUI_FLAGS_MODALRESULT_CONTINUE = 11;
// Edit Mask Flags
const int AIMPUI_FLAGS_EDITMASK_TEXT = 0;
const int AIMPUI_FLAGS_EDITMASK_INTEGER = 1;
const int AIMPUI_FLAGS_EDITMASK_FLOAT = 2;
// Form's BorderStyle
const int AIMPUI_FLAGS_BORDERSTYLE_SIZEABLE = 0;
const int AIMPUI_FLAGS_BORDERSTYLE_SINGLE = 1;
const int AIMPUI_FLAGS_BORDERSTYLE_DIALOG = 2;
const int AIMPUI_FLAGS_BORDERSTYLE_TOOLWINDOW = 3;
const int AIMPUI_FLAGS_BORDERSTYLE_TOOLWINDOWSIZABLE = 4;
const int AIMPUI_FLAGS_BORDERSTYLE_NONE = 5;
// Form's BorderIcons
const int AIMPUI_FLAGS_BORDERICON_SYSTEMMENU = 1;
const int AIMPUI_FLAGS_BORDERICON_MINIMIZE = 2;
const int AIMPUI_FLAGS_BORDERICON_MAXIMIZE = 4;
// Flags for IAIMPUIBrowseFolderDialog
const int AIMPUI_FLAGS_BROWSEFOLDER_CUSTOMPATHS = 1;
const int AIMPUI_FLAGS_BROWSEFOLDER_MULTISELECT = 2;
// Button Styles
const int AIMPUI_FLAGS_BUTTON_STYLE_NORMAL = 0;
const int AIMPUI_FLAGS_BUTTON_STYLE_DROPDOWN = 1;
const int AIMPUI_FLAGS_BUTTON_STYLE_DROPDOWNBUTTON = 2;
// Flags for IAIMPUITreeListNode.Get
const int AIMPUI_FLAGS_TL_NODE_GET_PARENT = -1;
const int AIMPUI_FLAGS_TL_NODE_GET_NEXTSIBLING = -2;
const int AIMPUI_FLAGS_TL_NODE_GET_PREVSIBLING = -3;
// Flags for IAIMPUITreeList.SortBy
const int AIMPUI_FLAGS_TL_SORTBY_FLAG_AUTO = 0;
const int AIMPUI_FLAGS_TL_SORTBY_FLAG_ASCENDING = 1;
const int AIMPUI_FLAGS_TL_SORTBY_FLAG_DESCENDING = 2;
// Flags for InsertTo for IAIMPUITreeListDragDropEvents
const int AIMPUI_FLAGS_TL_INSERTTO_AFTER = 0;
const int AIMPUI_FLAGS_TL_INSERTTO_BEFORE = 1;
const int AIMPUI_FLAGS_TL_INSERTTO_INTO = 2;
// Flags for AIMPUI_TL_PROPID_GRID_LINES property
const int AIMPUI_FLAGS_TL_GRIDLINE_VERTICAL = 1;
const int AIMPUI_FLAGS_TL_GRIDLINE_HORIZONTAL = 2;
/*----------------------------------------------------------------------------------------------------------------------*/
/* Property IDs */
/*----------------------------------------------------------------------------------------------------------------------*/
// PropID for IAIMPUIControl
const int AIMPUI_CONTROL_PROPID_CUSTOM = 0;
const int AIMPUI_CONTROL_PROPID_ENABLED = 1;
const int AIMPUI_CONTROL_PROPID_HINT = 2;
const int AIMPUI_CONTROL_PROPID_NAME = 3;
const int AIMPUI_CONTROL_PROPID_PARENT = 4;
const int AIMPUI_CONTROL_PROPID_POPUPMENU = 5;
const int AIMPUI_CONTROL_PROPID_VISIBLE = 6;
const int AIMPUI_CONTROL_MAX_PROPID = 20;
// PropID for IAIMPUIWinControl
const int AIMPUI_WINCONTROL_PROPID_FOCUSED = AIMPUI_CONTROL_MAX_PROPID + 1;
const int AIMPUI_WINCONTROL_PROPID_TABORDER = AIMPUI_CONTROL_MAX_PROPID + 2;
const int AIMPUI_WINCONTROL_MAX_PROPID = AIMPUI_CONTROL_MAX_PROPID + 10;
// PropID for IAIMPUIBaseEdit
const int AIMPUI_BASEEDIT_PROPID_BORDERS = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_BASEEDIT_PROPID_MAXLENGTH = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_BASEEDIT_PROPID_READONLY = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_BASEEDIT_PROPID_SELLENGTH = AIMPUI_WINCONTROL_MAX_PROPID + 4;
const int AIMPUI_BASEEDIT_PROPID_SELSTART = AIMPUI_WINCONTROL_MAX_PROPID + 5;
const int AIMPUI_BASEEDIT_PROPID_SELTEXT = AIMPUI_WINCONTROL_MAX_PROPID + 6;
const int AIMPUI_BASEEDIT_PROPID_TEXT = AIMPUI_WINCONTROL_MAX_PROPID + 7;
const int AIMPUI_BASEEDIT_MAX_PROPID = AIMPUI_WINCONTROL_MAX_PROPID + 10;
// PropID for IAIMPUIBBCBox
const int AIMPUI_BBCBOX_PROPID_BORDERS = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_BBCBOX_PROPID_TEXT = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_BBCBOX_PROPID_TRANSPARENT = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_BBCBOX_PROPID_WORDWRAP = AIMPUI_WINCONTROL_MAX_PROPID + 4;
// PropID for IAIMPUIBevel
const int AIMPUI_BEVEL_PROPID_BORDERS = AIMPUI_CONTROL_MAX_PROPID + 1;
// PropID for IAIMPUIBrandBox
const int AIMPUI_BRANDBOX_PROPID_CAPTION = AIMPUI_WINCONTROL_MAX_PROPID + 1;
// PropID for IAIMPUIButton
const int AIMPUI_BUTTON_PROPID_CAPTION = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_BUTTON_PROPID_FOCUSONCLICK = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_BUTTON_PROPID_DEFAULT = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_BUTTON_PROPID_DROPDOWNMENU = AIMPUI_WINCONTROL_MAX_PROPID + 4;
const int AIMPUI_BUTTON_PROPID_IMAGEINDEX = AIMPUI_WINCONTROL_MAX_PROPID + 5;
const int AIMPUI_BUTTON_PROPID_IMAGELIST = AIMPUI_WINCONTROL_MAX_PROPID + 6;
const int AIMPUI_BUTTON_PROPID_MODALRESULT = AIMPUI_WINCONTROL_MAX_PROPID + 7;
const int AIMPUI_BUTTON_PROPID_STYLE = AIMPUI_WINCONTROL_MAX_PROPID + 8;
// PropID for IAIMPUIBaseButtonnedEdit
const int AIMPUI_BUTTONEDEDIT_PROPID_BUTTONSIMAGES = AIMPUI_BASEEDIT_MAX_PROPID + 1;
const int AIMPUI_BUTTONEDEDIT_MAX_PROPID = AIMPUI_BASEEDIT_MAX_PROPID + 10;
// PropID for IAIMPUIEditButton
const int AIMPUI_EDITBUTTON_PROPID_CUSTOM = 0;
const int AIMPUI_EDITBUTTON_PROPID_CAPTION = 1;
const int AIMPUI_EDITBUTTON_PROPID_ENABLED = 2;
const int AIMPUI_EDITBUTTON_PROPID_HINT = 3;
const int AIMPUI_EDITBUTTON_PROPID_INDEX = 4;
const int AIMPUI_EDITBUTTON_PROPID_IMAGEINDEX = 5;
const int AIMPUI_EDITBUTTON_PROPID_VISIBLE = 6;
const int AIMPUI_EDITBUTTON_PROPID_WIDTH = 7;
// PropID for IAIMPUICategory
const int AIMPUI_CATEGORY_PROPID_AUTOSIZE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_CATEGORY_PROPID_CAPTION = AIMPUI_WINCONTROL_MAX_PROPID + 2;
// PropID for IAIMPUICheckBox and IAIMPUIRadioBox
const int AIMPUI_CHECKBOX_PROPID_AUTOSIZE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_CHECKBOX_PROPID_CAPTION = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_CHECKBOX_PROPID_STATE = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_CHECKBOX_PROPID_WORDWRAP = AIMPUI_WINCONTROL_MAX_PROPID + 4;
// PropID for IAIMPUIComboBox
const int AIMPUI_COMBOBOX_PROPID_AUTOCOMPLETE = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 1;
const int AIMPUI_COMBOBOX_PROPID_ITEMINDEX = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 2;
const int AIMPUI_COMBOBOX_PROPID_ITEMOBJECT = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 3;
const int AIMPUI_COMBOBOX_PROPID_TEXT = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 4;
const int AIMPUI_COMBOBOX_PROPID_STYLE = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 5;
// PropID for IAIMPUICheckComboBox
const int AIMPUI_CHECKCOMBO_PROPID_TEXT = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 1;
// PropID for IAIMPUIEdit
const int AIMPUI_EDIT_PROPID_PASSWORDCHAR = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 2;
const int AIMPUI_EDIT_PROPID_TEXTHINT = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 3;
// PropID for IAIMPUIGroupBox
const int AIMPUI_GROUPBOX_PROPID_AUTOSIZE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_GROUPBOX_PROPID_BORDERS = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_GROUPBOX_PROPID_TRANSPARENT = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_GROUPBOX_PROPID_CHECKMODE = AIMPUI_WINCONTROL_MAX_PROPID + 4;
const int AIMPUI_GROUPBOX_PROPID_CHECKED = AIMPUI_WINCONTROL_MAX_PROPID + 5;
const int AIMPUI_GROUPBOX_PROPID_CAPTION = AIMPUI_WINCONTROL_MAX_PROPID + 6;
// PropID for IAIMPUIImage
const int AIMPUI_IMAGE_PROPID_IMAGE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_IMAGE_PROPID_IMAGESTRETCHMODE = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_IMAGE_PROPID_IMAGEINDEX = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_IMAGE_PROPID_IMAGELIST = AIMPUI_WINCONTROL_MAX_PROPID + 4;
// PropID for IAIMPUIImageComboBox
const int AIMPUI_IMAGECOMBOBOX_PROPID_IMAGELIST = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 1;
const int AIMPUI_IMAGECOMBOBOX_PROPID_ITEMINDEX = AIMPUI_BUTTONEDEDIT_MAX_PROPID + 2;
// PropID for IAIMPUILabel
const int AIMPUI_LABEL_PROPID_AUTOSIZE = AIMPUI_CONTROL_MAX_PROPID + 1;
const int AIMPUI_LABEL_PROPID_LINE = AIMPUI_CONTROL_MAX_PROPID + 2;
const int AIMPUI_LABEL_PROPID_TEXT = AIMPUI_CONTROL_MAX_PROPID + 3;
const int AIMPUI_LABEL_PROPID_TEXTALIGN = AIMPUI_CONTROL_MAX_PROPID + 4;
const int AIMPUI_LABEL_PROPID_TEXTALIGNVERT = AIMPUI_CONTROL_MAX_PROPID + 5;
const int AIMPUI_LABEL_PROPID_TEXTCOLOR = AIMPUI_CONTROL_MAX_PROPID + 6;
const int AIMPUI_LABEL_PROPID_TEXTSTYLE = AIMPUI_CONTROL_MAX_PROPID + 7;
const int AIMPUI_LABEL_PROPID_TRANSPARENT = AIMPUI_CONTROL_MAX_PROPID + 8;
const int AIMPUI_LABEL_PROPID_URL = AIMPUI_CONTROL_MAX_PROPID + 9;
const int AIMPUI_LABEL_PROPID_WORDWRAP = AIMPUI_CONTROL_MAX_PROPID + 10;
const int AIMPUI_LABEL_MAX_PROPID = AIMPUI_CONTROL_MAX_PROPID + 20;
// PropID for IAIMPUIMemo
const int AIMPUI_MEMO_PROPID_CARET_XY = AIMPUI_BASEEDIT_MAX_PROPID + 1;
// PropID for IAIMPUITabSheet
const int AIMPUI_TABSHEET_PROPID_CAPTION = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_TABSHEET_PROPID_INDEX = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_TABSHEET_PROPID_VISIBLE = AIMPUI_WINCONTROL_MAX_PROPID + 3;
// PropID for IAIMPUIPageControl
const int AIMPUI_PAGECONTROL_PROPID_ACTIVE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
// PropID for IAIMPUIPanel
const int AIMPUI_PANEL_PROPID_AUTOSIZE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_PANEL_PROPID_BORDERS = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_PANEL_PROPID_TRANSPARENT = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_PANEL_PROPID_PADDING = AIMPUI_WINCONTROL_MAX_PROPID + 4;
// PropID for IAIMPUIProgressBar
const int AIMPUI_PROGRESSBAR_PROPID_INDETERMINATE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_PROGRESSBAR_PROPID_MAX = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_PROGRESSBAR_PROPID_MIN = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_PROGRESSBAR_PROPID_PROGRESS = AIMPUI_WINCONTROL_MAX_PROPID + 4;
// PropID for IAIMPUIScrollBox
const int AIMPUI_SCROLLBOX_PROPID_BORDERS = AIMPUI_WINCONTROL_MAX_PROPID + 1;
// PropID for IAIMPUISlider
const int AIMPUI_SLIDER_PROPID_HORIZONTAL = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_SLIDER_PROPID_MARKS = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_SLIDER_PROPID_PAGESIZE = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_SLIDER_PROPID_TRANSPARENT = AIMPUI_WINCONTROL_MAX_PROPID + 4;
const int AIMPUI_SLIDER_PROPID_VALUE = AIMPUI_WINCONTROL_MAX_PROPID + 5;
const int AIMPUI_SLIDER_PROPID_VALUEDEFAULT = AIMPUI_WINCONTROL_MAX_PROPID + 6;
const int AIMPUI_SLIDER_PROPID_VALUEMAX = AIMPUI_WINCONTROL_MAX_PROPID + 7;
const int AIMPUI_SLIDER_PROPID_VALUEMIN = AIMPUI_WINCONTROL_MAX_PROPID + 8;
// PropID for IAIMPUISplitter
const int AIMPUI_SPLITTER_PROPID_CANHIDE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_SPLITTER_PROPID_CONTROL = AIMPUI_WINCONTROL_MAX_PROPID + 2;
// PropID for IAIMPUISpinEdit
const int AIMPUI_SPINEDIT_PROPID_DISPLAYMASK = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_SPINEDIT_PROPID_INCREMENT = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_SPINEDIT_PROPID_MAXVALUE = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_SPINEDIT_PROPID_MINVALUE = AIMPUI_WINCONTROL_MAX_PROPID + 4;
const int AIMPUI_SPINEDIT_PROPID_VALUE = AIMPUI_WINCONTROL_MAX_PROPID + 5;
const int AIMPUI_SPINEDIT_PROPID_VALUETYPE = AIMPUI_WINCONTROL_MAX_PROPID + 6;
// PropID for IAIMPUITabControl
const int AIMPUI_TABCONTROL_PROPID_ACTIVETABINDEX = AIMPUI_WINCONTROL_MAX_PROPID + 1;
// PropID for IAIMPUITimeEdit
const int AIMPUI_TIMEDIT_PROPID_VALUE = AIMPUI_WINCONTROL_MAX_PROPID + 1;
// PropID for IAIMPUITreeListColumn
const int AIMPUI_TL_COLUMN_PROPID_CAN_RESIZE = 1;
const int AIMPUI_TL_COLUMN_PROPID_CAPTION = 2;
const int AIMPUI_TL_COLUMN_PROPID_DRAWINDEX = 3;
const int AIMPUI_TL_COLUMN_PROPID_IMAGEINDEX = 4;
const int AIMPUI_TL_COLUMN_PROPID_INDEX = 5;
const int AIMPUI_TL_COLUMN_PROPID_TEXT_ALIGNMENT = 6;
const int AIMPUI_TL_COLUMN_PROPID_TEXT_VISIBLE = 7;
const int AIMPUI_TL_COLUMN_PROPID_VISIBLE = 8;
const int AIMPUI_TL_COLUMN_PROPID_WIDTH = 9;
// PropID for IAIMPUITreeListGroup
const int AIMPUI_TL_GROUP_PROPID_CAPTION = 1;
const int AIMPUI_TL_GROUP_PROPID_CHECKSTATE = 2;
const int AIMPUI_TL_GROUP_PROPID_EXPANDED = 3;
const int AIMPUI_TL_GROUP_PROPID_INDEX = 4;
const int AIMPUI_TL_GROUP_PROPID_SELECTED = 5;
// PropID for IAIMPUITreeListNode
const int AIMPUI_TL_NODE_PROPID_ABS_VISIBLE_INDEX = 0;
const int AIMPUI_TL_NODE_PROPID_CHECK_ENABLED = 1;
const int AIMPUI_TL_NODE_PROPID_CHECKED = 2;
const int AIMPUI_TL_NODE_PROPID_CHILDREN_CHECK_STATE = 3;
const int AIMPUI_TL_NODE_PROPID_EXPANDED = 4;
const int AIMPUI_TL_NODE_PROPID_IMAGEINDEX = 5;
const int AIMPUI_TL_NODE_PROPID_INDEX = 6;
const int AIMPUI_TL_NODE_PROPID_LEVEL = 7;
const int AIMPUI_TL_NODE_PROPID_SELECTED = 8;
const int AIMPUI_TL_NODE_PROPID_TAG = 9;
// PropID for IAIMPUITreeList
const int AIMPUI_TL_PROPID_ALLOW_DELETING = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_TL_PROPID_ALLOW_EDITING = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_TL_PROPID_ALLOW_FOCUS_CELLS = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_TL_PROPID_ALLOW_MULTISELECT = AIMPUI_WINCONTROL_MAX_PROPID + 4;
const int AIMPUI_TL_PROPID_ALLOW_REORDER_COLUMNS = AIMPUI_WINCONTROL_MAX_PROPID + 5;
const int AIMPUI_TL_PROPID_ALLOW_SHOWWHIDE_COLUMNS = AIMPUI_WINCONTROL_MAX_PROPID + 6;
const int AIMPUI_TL_PROPID_AUTOCHECK_SUBNODES = AIMPUI_WINCONTROL_MAX_PROPID + 7;
const int AIMPUI_TL_PROPID_BORDERS = AIMPUI_WINCONTROL_MAX_PROPID + 8;
const int AIMPUI_TL_PROPID_CELL_HINTS = AIMPUI_WINCONTROL_MAX_PROPID + 9;
const int AIMPUI_TL_PROPID_CHECKBOXES = AIMPUI_WINCONTROL_MAX_PROPID + 10;
const int AIMPUI_TL_PROPID_COLUMN_AUTOWIDTH = AIMPUI_WINCONTROL_MAX_PROPID + 11;
const int AIMPUI_TL_PROPID_COLUMN_HEIGHT = AIMPUI_WINCONTROL_MAX_PROPID + 12;
const int AIMPUI_TL_PROPID_COLUMN_IMAGES = AIMPUI_WINCONTROL_MAX_PROPID + 13;
const int AIMPUI_TL_PROPID_COLUMN_VISIBLE = AIMPUI_WINCONTROL_MAX_PROPID + 14;
const int AIMPUI_TL_PROPID_DRAG_SORTING = AIMPUI_WINCONTROL_MAX_PROPID + 15;
const int AIMPUI_TL_PROPID_DRAG_SORTING_CHANGE_LEVEL = AIMPUI_WINCONTROL_MAX_PROPID + 16;
const int AIMPUI_TL_PROPID_GRID_LINES = AIMPUI_WINCONTROL_MAX_PROPID + 20;
const int AIMPUI_TL_PROPID_GROUP_HEIGHT = AIMPUI_WINCONTROL_MAX_PROPID + 21;
const int AIMPUI_TL_PROPID_GROUPS = AIMPUI_WINCONTROL_MAX_PROPID + 22;
const int AIMPUI_TL_PROPID_GROUPS_ALLOW_COLLAPSE = AIMPUI_WINCONTROL_MAX_PROPID + 23;
const int AIMPUI_TL_PROPID_GROUPS_FOCUS_ON_CLICK = AIMPUI_WINCONTROL_MAX_PROPID + 24;
const int AIMPUI_TL_PROPID_HOT_TRACK = AIMPUI_WINCONTROL_MAX_PROPID + 25;
const int AIMPUI_TL_PROPID_INCSEARCH_COLUMN_INDEX = AIMPUI_WINCONTROL_MAX_PROPID + 26;
const int AIMPUI_TL_PROPID_NODE_HEIGHT = AIMPUI_WINCONTROL_MAX_PROPID + 27;
const int AIMPUI_TL_PROPID_NODE_IMAGE_ALIGNMENT = AIMPUI_WINCONTROL_MAX_PROPID + 28;
const int AIMPUI_TL_PROPID_NODE_IMAGES = AIMPUI_WINCONTROL_MAX_PROPID + 29;
const int AIMPUI_TL_PROPID_SORTING_MODE = AIMPUI_WINCONTROL_MAX_PROPID + 30;
// PropID for IAIMPUIValidationLabel
const int AIMPUI_VALIDATIONLABEL_PROPID_GLYPH = AIMPUI_LABEL_MAX_PROPID + 1;
// PropID for IAIMPUIForm
const int AIMPUI_FORM_PROPID_BORDERICONS = AIMPUI_WINCONTROL_MAX_PROPID + 1;
const int AIMPUI_FORM_PROPID_BORDERSTYLE = AIMPUI_WINCONTROL_MAX_PROPID + 2;
const int AIMPUI_FORM_PROPID_CAPTION = AIMPUI_WINCONTROL_MAX_PROPID + 3;
const int AIMPUI_FORM_PROPID_CLOSEBYESCAPE = AIMPUI_WINCONTROL_MAX_PROPID + 4;
const int AIMPUI_FORM_PROPID_ICON = AIMPUI_WINCONTROL_MAX_PROPID + 5;
const int AIMPUI_FORM_PROPID_PADDING = AIMPUI_WINCONTROL_MAX_PROPID + 6;
const int AIMPUI_FORM_PROPID_SHOWONTASKBAR = AIMPUI_WINCONTROL_MAX_PROPID + 7;
const int AIMPUI_FORM_PROPID_STYLE = AIMPUI_WINCONTROL_MAX_PROPID + 8;
// PropID for IAIMPUIProgressDialog
const int AIMPUI_PROGRESSDLG_PROPID_CAPTION = 1;
const int AIMPUI_PROGRESSDLG_PROPID_MESSAGE = 2;
const int AIMPUI_PROGRESSDLG_PROPID_SHOW_PROGRESS_ON_TASKBAR = 3;
/*----------------------------------------------------------------------------------------------------------------------*/
/* Basic Events Interfaces */
/*----------------------------------------------------------------------------------------------------------------------*/
enum TAIMPUITextAlignment
{
utaLeftJustify = 0,
utaRightJustify = 1,
utaCenter = 2
};
enum TAIMPUITextVerticalAlignment
{
utvaTop = 0,
utvaBottom = 1,
utvaCenter = 2
};
enum TAIMPUIMouseButton
{
umbLeft = 0,
umbRight = 1,
umbMiddle = 2
};
/* IAIMPUIDPIAwareness */
class IAIMPUIDPIAwareness: public IUnknown
{
public:
virtual BOOL WINAPI IsDPIAware() = 0;
virtual HRESULT WINAPI SetDPIAware(BOOL Value) = 0;
};
/* IAIMPUIChangeEvents */
class IAIMPUIChangeEvents: public IUnknown
{
public:
virtual void WINAPI OnChanged(IUnknown* Sender) = 0;
};
/* IAIMPUIDrawEvents */
class IAIMPUIDrawEvents: public IUnknown
{
public:
virtual void WINAPI OnDraw(IUnknown* Sender, HDC DC, const RECT R) = 0;
};
/* IAIMPUIKeyboardEvents */
class IAIMPUIKeyboardEvents: public IUnknown
{
public:
virtual void WINAPI OnEnter(IUnknown* Sender) = 0;
virtual void WINAPI OnExit(IUnknown* Sender) = 0;
virtual void WINAPI OnKeyDown(IUnknown* Sender, WORD* Key, WORD Modifiers) = 0;
virtual void WINAPI OnKeyPress(IUnknown* Sender, WCHAR* Key) = 0;
virtual void WINAPI OnKeyUp(IUnknown* Sender, WORD* Key, WORD Modifiers) = 0;
};
/* IAIMPUIPopupMenuEvents */
class IAIMPUIPopupMenuEvents: public IUnknown
{
public:
virtual BOOL WINAPI OnContextPopup(IUnknown* Sender, int X, int Y);
};
/* IAIMPUIMouseEvents */
class IAIMPUIMouseEvents: public IUnknown
{
public:
virtual void WINAPI OnMouseDoubleClick(IUnknown* Sender, TAIMPUIMouseButton Button, int X, int Y, WORD Modifiers) = 0;
virtual void WINAPI OnMouseDown(IUnknown* Sender, TAIMPUIMouseButton Button, int X, int Y, WORD Modifiers) = 0;
virtual void WINAPI OnMouseLeave(IUnknown* Sender) = 0;
virtual void WINAPI OnMouseMove(IUnknown* Sender, int X, int Y, WORD Modifiers) = 0;
virtual void WINAPI OnMouseUp(IUnknown* Sender, TAIMPUIMouseButton Button, int X, int Y, WORD Modifiers) = 0;
};
/* IAIMPUIMouseWheelEvents */
class IAIMPUIMouseWheelEvents: public IUnknown
{
public:
virtual BOOL WINAPI OnMouseWheel(IUnknown* Sender, int WheelDelta, int X, int Y, WORD Modifiers) = 0;
};
/* IAIMPUIPlacementEvents */
class IAIMPUIPlacementEvents: public IUnknown
{
public:
virtual void WINAPI OnBoundsChanged(IUnknown* Sender) = 0;
};
/*----------------------------------------------------------------------------------------------------------------------*/
/* Basic Controls Interfaces */
/*----------------------------------------------------------------------------------------------------------------------*/
/* TAIMPUIControlPlacement */
enum TAIMPUIControlAlignment
{
ualNone = 0,
ualTop = 1,
ualBottom = 2,
ualLeft = 3,
ualRight = 4,
ualClient = 5
};
#pragma pack(push, 1)
struct TAIMPUIControlPlacement
{
TAIMPUIControlAlignment Alignment;
RECT AlignmentMargins;
RECT Anchors;
RECT Bounds;
};
/* TAIMPUIControlPlacementConstraints */
struct TAIMPUIControlPlacementConstraints
{
int MaxHeight;
int MaxWidth;
int MinHeight;
int MinWidth;
};
#pragma pack(pop)
/* IAIMPUIControl */
class IAIMPUIControl: public IAIMPPropertyList
{
public:
virtual HRESULT WINAPI GetPlacement(TAIMPUIControlPlacement* Placement) = 0;
virtual HRESULT WINAPI GetPlacementConstraints(TAIMPUIControlPlacementConstraints* Constraints) = 0;
virtual HRESULT WINAPI SetPlacement(TAIMPUIControlPlacement Placement) = 0;
virtual HRESULT WINAPI SetPlacementConstraints(TAIMPUIControlPlacementConstraints Constraints) = 0;
// Coords Translation
virtual HRESULT WINAPI ClientToScreen(POINT* P) = 0;
virtual HRESULT WINAPI ScreenToClient(POINT* P) = 0;
// Drawing
virtual HRESULT WINAPI PaintTo(HDC DC, int X, int Y) = 0;
virtual HRESULT WINAPI Invalidate() = 0;
};
/* IAIMPUIWinControl */
class IAIMPUIWinControl: public IAIMPUIControl
{
public:
virtual HRESULT WINAPI GetControl(int Index, REFIID IID, void** Obj) = 0;
virtual int WINAPI GetControlCount() = 0;
virtual HWND WINAPI GetHandle() = 0;
virtual BOOL WINAPI HasHandle() = 0;
virtual HRESULT WINAPI SetFocus() = 0;
};
/* IAIMPUIWndProcEvents */
class IAIMPUIWndProcEvents: public IUnknown
{
public:
virtual BOOL WINAPI OnBeforeWndProc(DWORD Message, WPARAM ParamW, LPARAM ParamL, LRESULT* Result) = 0;
virtual void WINAPI OnAfterWndProc(DWORD Message, WPARAM ParamW, LPARAM ParamL, LRESULT* Result) = 0;
};
/*----------------------------------------------------------------------------------------------------------------------*/
/* Non-Visual Components Interfaces */
/*----------------------------------------------------------------------------------------------------------------------*/
/* IAIMPUIImageList */
class IAIMPUIImageList: public IUnknown
{
public:
virtual HRESULT WINAPI Add(IAIMPImage* Image) = 0;
virtual HRESULT WINAPI Clear() = 0;
virtual HRESULT WINAPI Delete(int Index) = 0;
virtual HRESULT WINAPI Draw(HDC DC, int Index, int X, int Y, BOOL Enabled) = 0;
virtual HRESULT WINAPI LoadFromResource(HMODULE Instance, WCHAR* ResName, WCHAR* ResType) = 0;
virtual int WINAPI GetCount() = 0;
virtual HRESULT WINAPI GetSize(SIZE* Size) = 0;
virtual HRESULT WINAPI SetSize(SIZE Size) = 0;
};
/* IAIMPUIImageList2 */
class IAIMPUIImageList2: public IAIMPUIImageList
{
public:
virtual HRESULT WINAPI DrawEx(HDC DC, int Index, const RECT R, BOOL Enabled) = 0;
};
/* IAIMPUIMenuItem */
class IAIMPUIMenuItem: public IAIMPMenuItem
{
public:
virtual HRESULT WINAPI Add(IAIMPString* ID, IAIMPUIMenuItem** MenuItem) = 0;
virtual HRESULT WINAPI Delete(int Index) = 0;
virtual HRESULT WINAPI Get(int Index, REFIID IID, void** Obj) = 0;
virtual int WINAPI GetCount() = 0;
};
/* IAIMPUIPopupMenu */
class IAIMPUIPopupMenu: public IUnknown
{
public:
virtual HRESULT WINAPI Add(IAIMPString* ID, IAIMPUIMenuItem** MenuItem) = 0;
virtual HRESULT WINAPI Delete(int Index) = 0;
virtual HRESULT WINAPI DeleteChildren() = 0;
virtual HRESULT WINAPI Get(int index, REFIID IID, void** MenuItem) = 0;
virtual int WINAPI GetCount() = 0;
virtual HRESULT WINAPI Popup(POINT ScreenPoint) = 0;
virtual HRESULT WINAPI Popup2(RECT ScreenRect) = 0;
};
/*----------------------------------------------------------------------------------------------------------------------*/
/* Special Controls and Events Interfaces */
/*----------------------------------------------------------------------------------------------------------------------*/
/* IAIMPUIBaseEdit */
class IAIMPUIBaseEdit: public IAIMPUIWinControl
{
public:
virtual HRESULT WINAPI CopyToClipboard() = 0;
virtual HRESULT WINAPI CutToClipboard() = 0;
virtual HRESULT WINAPI PasteFromClipboard() = 0;
virtual HRESULT WINAPI SelectAll() = 0;
virtual HRESULT WINAPI SelectNone() = 0;
};
/* IAIMPUIBBCBox */
class IAIMPUIBBCBox: public IAIMPUIWinControl
{
};
/* IAIMPUIBevel */
class IAIMPUIBevel: public IAIMPUIControl
{
};
/* IAIMPUIButton */
class IAIMPUIButton: public IAIMPUIWinControl
{
public:
virtual HRESULT WINAPI ShowDropDownMenu() = 0;
};
/* IAIMPUIEditButton */
class IAIMPUIEditButton: public IAIMPPropertyList
{
};
/* IAIMPUIBaseButtonnedEdit */
class IAIMPUIBaseButtonnedEdit: public IAIMPUIBaseEdit
{
public:
virtual HRESULT WINAPI AddButton(IUnknown* EventsHandler, IAIMPUIEditButton** Button) = 0;
virtual HRESULT WINAPI DeleteButton(int Index) = 0;
virtual HRESULT WINAPI DeleteButton2(IAIMPUIEditButton* Button) = 0;
virtual HRESULT WINAPI GetButton(int Index, IAIMPUIEditButton** Button) = 0;
virtual int WINAPI GetButtonCount() = 0;
};
/* IAIMPUIBaseComboBox */
class IAIMPUIBaseComboBox: public IAIMPUIBaseButtonnedEdit
{
public:
virtual HRESULT WINAPI Add(IUnknown* Obj, int ExtraData) = 0;
virtual HRESULT WINAPI Add2(IAIMPObjectList* List) = 0;
virtual HRESULT WINAPI Clear() = 0;
virtual HRESULT WINAPI Delete(int Index) = 0;
virtual HRESULT WINAPI GetItem(int Index, REFIID IID, void** Obj) = 0;
virtual INT WINAPI GetItemCount() = 0;
virtual HRESULT WINAPI SetItem(int Index, IUnknown* Obj) = 0;
};
/* IAIMPUIBrandBox */
class IAIMPUIBrandBox: public IAIMPUIWinControl
{
};
/* IAIMPUICategory */
class IAIMPUICategory: public IAIMPUIWinControl
{
};
/* IAIMPUICheckBox */
class IAIMPUICheckBox: public IAIMPUIWinControl
{
};
/* IAIMPUIComboBox */
class IAIMPUIComboBox: public IAIMPUIBaseComboBox
{
};
/* IAIMPUICheckComboBox */
class IAIMPUICheckComboBox: public IAIMPUIBaseComboBox
{
public:
virtual BOOL WINAPI GetChecked(int Index) = 0;
virtual HRESULT WINAPI SetChecked(int Index, BOOL Value) = 0;
};
/* IAIMPUIEdit */
class IAIMPUIEdit: public IAIMPUIBaseButtonnedEdit
{
};
/* IAIMPUIGroupBox */
class IAIMPUIGroupBox: public IAIMPUIWinControl
{
};
/* IAIMPUIImage */
class IAIMPUIImage: public IAIMPUIControl
{
};
/* IAIMPUIImageComboBox */
class IAIMPUIImageComboBox: public IAIMPUIBaseComboBox
{
public:
virtual int WINAPI GetImageIndex(int Index) = 0;
virtual HRESULT WINAPI SetImageIndex(int Index, int Value) = 0;
};
/* IAIMPUILabel */
class IAIMPUILabel: public IAIMPUIControl
{
};
/* IAIMPUIMemo */
class IAIMPUIMemo: public IAIMPUIBaseEdit
{
public:
virtual HRESULT WINAPI AddLine(IAIMPString* S) = 0;
virtual HRESULT WINAPI Clear() = 0;
virtual HRESULT WINAPI DeleteLine(int Index) = 0;
virtual HRESULT WINAPI InsertLine(int Index, IAIMPString* S) = 0;
virtual HRESULT WINAPI GetLine(int Index, IAIMPString* S) = 0;
virtual int WINAPI GetLineCount() = 0;
virtual HRESULT WINAPI SetLine(int Index, IAIMPString* ) = 0;
// I/O
virtual HRESULT WINAPI LoadFromFile(IAIMPString* FileName) = 0;
virtual HRESULT WINAPI LoadFromStream(IAIMPStream* Stream) = 0;
virtual HRESULT WINAPI SaveToFile(IAIMPString* FileName) = 0;
virtual HRESULT WINAPI SaveToStream(IAIMPStream* Stream) = 0;
};
/* IAIMPUIPaintBox */
class IAIMPUIPaintBox: public IAIMPUIControl
{
};
/* IAIMPUITabSheet */
class IAIMPUITabSheet: public IAIMPUIWinControl
{
};
/* IAIMPUIPageControl */
class IAIMPUIPageControl: public IAIMPUIWinControl
{
public:
virtual HRESULT WINAPI Add(IAIMPString* Name, IAIMPUITabSheet** Page) = 0;
virtual HRESULT WINAPI Delete(int Index) = 0;
virtual HRESULT WINAPI Delete2(IAIMPUITabSheet* Page) = 0;
virtual HRESULT WINAPI Get(int Index, IAIMPUITabSheet** Page) = 0;
virtual int WINAPI GetCount() = 0;
};
/* IAIMPUIPageControlEvents */
class IAIMPUIPageControlEvents: public IUnknown
{
public:
virtual void WINAPI OnActivating(IAIMPUIPageControl* Sender, IAIMPUITabSheet* Page, BOOL* Allow) = 0;
virtual void WINAPI OnActivated(IAIMPUIPageControl* Sender, IAIMPUITabSheet* Page) = 0;
};
/* IAIMPUIPanel */
class IAIMPUIPanel: public IAIMPUIWinControl
{
};
/* IAIMPUIProgressBar */
class IAIMPUIProgressBar: public IAIMPUIControl
{
};
/* IAIMPUIScrollBox */
class IAIMPUIScrollBox: public IAIMPUIWinControl
{
public:
virtual HRESULT WINAPI MakeVisible(IAIMPUIControl* Control) = 0;
};
/* IAIMPUISlider */
class IAIMPUISlider: public IAIMPUIWinControl
{
};
/* IAIMPUISplitter */
class IAIMPUISplitter: public IAIMPUIControl
{
};
/* IAIMPUISpinEdit */
class IAIMPUISpinEdit: public IAIMPUIWinControl
{
};
/* IAIMPUITabControl */
class IAIMPUITabControl: public IAIMPUIWinControl
{
public:
virtual HRESULT WINAPI Add(IAIMPString* S) = 0;
virtual HRESULT WINAPI Delete(int Index) = 0;
virtual HRESULT WINAPI Get(int Index, IAIMPString** Tab) = 0;
virtual int WINAPI GetCount() = 0;
};
/* IAIMPUITabControlEvents */
class IAIMPUITabControlEvents: public IAIMPUIChangeEvents
{
public:
virtual void WINAPI OnActivating(IAIMPUITabControl* Sender, int TabIndex, BOOL* Allow) = 0;
virtual void WINAPI OnActivated(IAIMPUITabControl* Sender, int TabIndex) = 0;
};
/* IAIMPUITimeEdit */
class IAIMPUITimeEdit: public IAIMPUIWinControl
{
};
/* IAIMPUITreeListColumn */
class IAIMPUITreeListColumn: public IAIMPPropertyList
{
};
/* IAIMPUITreeListGroup */
class IAIMPUITreeListGroup: public IAIMPPropertyList
{
public:
virtual HRESULT WINAPI Get(int Index, REFIID IID, void** Obj) = 0;
virtual int WINAPI GetCount() = 0;
};
/* IAIMPUITreeListNode */
class IAIMPUITreeListNode: public IAIMPPropertyList
{
public:
// Nodes
virtual HRESULT WINAPI Add(IAIMPUITreeListNode** Node) = 0;
virtual HRESULT WINAPI ClearChildren() = 0;
virtual HRESULT WINAPI FindByTag(DWORD_PTR Tag, BOOL Recursive, REFIID IID, void** Node) = 0;
virtual HRESULT WINAPI FindByValue(int ColumnIndex, IAIMPString* Value, BOOL Recursive, REFIID IID, void** Node) = 0;
virtual HRESULT WINAPI Get(int Index, REFIID IID, void** Obj) = 0;
virtual int WINAPI GetCount() = 0;
// Values
virtual HRESULT WINAPI ClearValues() = 0;
virtual HRESULT WINAPI GetValue(int Index, IAIMPString** Value) = 0;
virtual HRESULT WINAPI SetValue(int Index, IAIMPString* Value) = 0;
// Groups
virtual HRESULT WINAPI GetGroup(REFIID IID, void** Group) = 0;
};
/* IAIMPUITreeList */
class IAIMPUITreeList: public IAIMPUIWinControl
{
public:
// Columns
virtual HRESULT WINAPI AddColumn(REFIID IID, void** Obj) = 0;
virtual HRESULT WINAPI ClearColumns() = 0;
virtual HRESULT WINAPI DeleteColumn(int Index) = 0;
virtual HRESULT WINAPI GetColumn(int Index, REFIID IID, void** Obj) = 0;
virtual int WINAPI GetColumnCount() = 0;
// Nodes
virtual HRESULT WINAPI Clear() = 0;
virtual HRESULT WINAPI Delete(IAIMPUITreeListNode* Node) = 0;
virtual HRESULT WINAPI GetPath(IAIMPUITreeListNode* Node, IAIMPString** S) = 0;
virtual HRESULT WINAPI GetRootNode(REFIID IID, void** Obj) = 0;
virtual HRESULT WINAPI MakeTop(IAIMPUITreeListNode* Node) = 0;
virtual HRESULT WINAPI MakeVisible(IAIMPUITreeListNode* Node) = 0;
virtual HRESULT WINAPI SetPath(IAIMPString* S) = 0;
// Nodes - Absolute List
virtual HRESULT WINAPI GetAbsoluteVisibleNode(int Index, REFIID IID, void** Obj) = 0;
virtual int WINAPI GetAbsoluteVisibleNodeCount() = 0;
// Nodes - Selection
virtual HRESULT WINAPI DeleteSelected() = 0;
virtual HRESULT WINAPI SelectAll() = 0;
virtual HRESULT WINAPI SelectNone() = 0;
virtual HRESULT WINAPI GetFocused(REFIID IID, void** Obj) = 0;
virtual HRESULT WINAPI SetFocused(IUnknown* Obj) = 0;
virtual HRESULT WINAPI GetSelected(int Index, REFIID IID, void** Obj) = 0;
virtual int WINAPI GetSelectedCount() = 0;
// Inplace Editing
virtual HRESULT WINAPI GetEditingCell(int* ColumnIndex, int* RowIndex) = 0;
virtual HRESULT WINAPI StartEditing(IAIMPUITreeListColumn* Column) = 0;
virtual HRESULT WINAPI StopEditing() = 0;
// Grouping
virtual HRESULT WINAPI GroupBy(IAIMPUITreeListColumn* Column, BOOL ResetPrevGroupingParams) = 0;
virtual HRESULT WINAPI GetGroup(int Index, REFIID IID, void** Obj) = 0;
virtual int WINAPI GetGroupCount() = 0;
virtual HRESULT WINAPI Regroup() = 0;
virtual HRESULT WINAPI ResetGrouppingParams() = 0;
// Sorting
virtual HRESULT WINAPI ResetSortingParams() = 0;
virtual HRESULT WINAPI Resort() = 0;
virtual HRESULT WINAPI SortBy(IAIMPUITreeListColumn* Column, DWORD Flags, BOOL ResetPrevSortingParams) = 0;
// Customized Settings
virtual HRESULT WINAPI ConfigLoad(IAIMPConfig* Config, IAIMPString* Key) = 0;
virtual HRESULT WINAPI ConfigSave(IAIMPConfig* Config, IAIMPString* Key) = 0;
};
/* IAIMPUITreeListDragSortingEvents */
class IAIMPUITreeListDragSortingEvents: public IUnknown
{
public:
virtual void WINAPI OnDragSorting(IAIMPUITreeList* Sender) = 0;
virtual void WINAPI OnDragSortingNodeOver(IAIMPUITreeList* Sender, IAIMPUITreeListNode* Node, DWORD Flags, BOOL* Handled) = 0;
};
/* IAIMPUITreeListCustomDrawEvents */
class IAIMPUITreeListCustomDrawEvents: public IUnknown
{
public:
virtual void WINAPI OnCustomDrawNode(IAIMPUITreeList* Sender, HDC DC, RECT R, IAIMPUITreeListNode* Node, BOOL* Handled) = 0;
virtual void WINAPI OnCustomDrawNodeCell(IAIMPUITreeList* Sender, HDC DC, RECT R, IAIMPUITreeListNode* Node, IAIMPUITreeListColumn* Column, BOOL* Handled) = 0;
virtual void WINAPI OnGetNodeBackground(IAIMPUITreeList* Sender, IAIMPUITreeListNode* Node, DWORD* Color) = 0;
};
/* IAIMPUITreeListInplaceEditingEvents */
class IAIMPUITreeListInplaceEditingEvents: public IUnknown
{
public:
virtual void WINAPI OnEditing(IAIMPUITreeList* Sender, IAIMPUITreeListNode* Node, int ColumnIndex, BOOL* Allow) = 0;
virtual void WINAPI OnEdited(IAIMPUITreeList* Sender, IAIMPUITreeListNode* Node, int ColumnIndex, IAIMPString* Value) = 0;
};
/* IAIMPUITreeListEvents */
class IAIMPUITreeListEvents: public IUnknown
{
public:
virtual void WINAPI OnColumnClick(IAIMPUITreeList* Sender, int ColumnIndex) = 0;
virtual void WINAPI OnFocusedColumnChanged(IAIMPUITreeList* Sender) = 0;
virtual void WINAPI OnFocusedNodeChanged(IAIMPUITreeList* Sender) = 0;
virtual void WINAPI OnNodeChecked(IAIMPUITreeList* Sender, IAIMPUITreeListNode* Node) = 0;
virtual void WINAPI OnNodeDblClicked(IAIMPUITreeList* Sender, IAIMPUITreeListNode* Node) = 0;
virtual void WINAPI OnSelectionChanged(IAIMPUITreeList* Sender) = 0;
virtual void WINAPI OnSorted(IAIMPUITreeList* Sender) = 0;
virtual void WINAPI OnStructChanged(IAIMPUITreeList* Sender) = 0;
};
/* IAIMPUIRadioBox */
class IAIMPUIRadioBox: public IAIMPUICheckBox
{
};
/* IAIMPUIValidationLabel */
class IAIMPUIValidationLabel: public IAIMPUILabel
{
};
/*----------------------------------------------------------------------------------------------------------------------*/
/* Top-Level Window Interfaces */
/*----------------------------------------------------------------------------------------------------------------------*/
/* IAIMPUIForm */
class IAIMPUIForm: public IAIMPUIWinControl
{
public:
virtual HRESULT WINAPI Close() = 0;
virtual HRESULT WINAPI GetFocusedControl(IAIMPUIWinControl** Control) = 0;
virtual HRESULT WINAPI Localize() = 0;
virtual HRESULT WINAPI Release(BOOL Postponed) = 0;
virtual int WINAPI ShowModal() = 0;
};
/* IAIMPUIFormEvents */
class IAIMPUIFormEvents: public IUnknown
{
public:
virtual void WINAPI OnActivated(IAIMPUIForm* Sender) = 0;
virtual void WINAPI OnDeactivated(IAIMPUIForm* Sender) = 0;
virtual void WINAPI OnCreated(IAIMPUIForm* Sender) = 0;
virtual void WINAPI OnDestroyed(IAIMPUIForm* Sender) = 0;
virtual void WINAPI OnCloseQuery(IAIMPUIForm* Sender, BOOL* CanClose) = 0;
virtual void WINAPI OnLocalize(IAIMPUIForm* Sender) = 0;
virtual void WINAPI OnShortCut(IAIMPUIForm* Sender, WORD Key, WORD Modifiers, BOOL* Handled) = 0;
};
/* IAIMPUIFormEvents2 */
class IAIMPUIFormEvents2: public IUnknown
{
public:
virtual void WINAPI OnChangeScale(IAIMPUIForm* Sender, int Multiplier, int Divider) = 0;
};
/* IAIMPUIFormEvents3 */
class IAIMPUIFormEvents3: public IUnknown
{
public:
virtual void WINAPI OnStyleChanged(IAIMPUIForm* Sender, int Style) = 0;
};
/*----------------------------------------------------------------------------------------------------------------------*/
/* Dialogs */
/*----------------------------------------------------------------------------------------------------------------------*/
/* IAIMPUIBrowseFolderDialog */
class IAIMPUIBrowseFolderDialog: public IUnknown
{
public:
virtual HRESULT WINAPI Execute(HWND OwnerWnd, DWORD Flags, IAIMPString* DefaultPath, IAIMPObjectList** Selection) = 0;
};
/* IAIMPUIFileDialogs */
class IAIMPUIFileDialogs: public IUnknown
{
public:
virtual HRESULT WINAPI ExecuteOpenDialog(HWND OwnerWnd, IAIMPString* Caption, IAIMPString* Filter, IAIMPString** FileName) = 0;
virtual HRESULT WINAPI ExecuteOpenDialog2(HWND OwnerWnd, IAIMPString* Caption, IAIMPString* Filter, IAIMPObjectList** Files) = 0;
virtual HRESULT WINAPI ExecuteSaveDialog(HWND OwnerWnd, IAIMPString* Caption, IAIMPString* Filter, IAIMPString** FileName, int* FilterIndex) = 0;
};
/* IAIMPUIInputDialog */
class IAIMPUIInputDialog: public IUnknown
{
public:
virtual HRESULT WINAPI Execute(HWND OwnerWnd, IAIMPString* Caption,
IUnknown* EventsHandler, IAIMPString* Text, VARIANT* Value) = 0;
virtual HRESULT WINAPI Execute2(HWND OwnerWnd, IAIMPString* Caption,
IUnknown* EventsHandler, IAIMPObjectList* TextForValues, VARIANT* Values, int ValueCount) = 0;
};
/* IAIMPUIInputDialogEvents */
class IAIMPUIInputDialogEvents: public IUnknown
{
public:
virtual HRESULT WINAPI OnValidate(VARIANT* Value, int ValueIndex) = 0;
};
/* IAIMPUIMessageDialog */
class IAIMPUIMessageDialog: public IUnknown
{
public:
virtual HRESULT WINAPI Execute(HWND OwnerWnd, IAIMPString* Caption, IAIMPString* Text, DWORD Flags) = 0;
};
/* IAIMPUIProgressDialog */
class IAIMPUIProgressDialog: public IAIMPPropertyList
{
public:
virtual HRESULT WINAPI Finished() = 0;
virtual HRESULT WINAPI Progress(const INT64 Position, INT64 Total, IAIMPString* Text) = 0;
virtual HRESULT WINAPI Started() = 0;
};
/* IAIMPUIProgressDialogEvents */
class IAIMPUIProgressDialogEvents: public IUnknown
{
public:
virtual void WINAPI OnCanceled() = 0;
};
/*----------------------------------------------------------------------------------------------------------------------*/
/* GUI Service */
/*----------------------------------------------------------------------------------------------------------------------*/
const int AIMPUI_SERVICE_CREATEFORM_FLAGS_CHILD = 1;
/* IAIMPServiceUI */
class IAIMPServiceUI: public IUnknown
{
public:
virtual HRESULT WINAPI CreateControl(IAIMPUIForm* Owner, IAIMPUIWinControl* Parent,
IAIMPString* Name, IUnknown* EventsHandler, REFIID IID, void** Control) = 0;
virtual HRESULT WINAPI CreateForm(HWND OwnerWindow, DWORD Flags,
IAIMPString* Name, IUnknown* EventsHandler, IAIMPUIForm** Form) = 0;
virtual HRESULT WINAPI CreateObject(IAIMPUIForm* Owner, IUnknown* EventsHandler, REFIID IID, void** Obj) = 0;
};
#endif // !apiGUIH | [
"arsenylyashenko.3@gmail.com"
] | arsenylyashenko.3@gmail.com |
02fdf6ee9972228a230261ac33cecc5ca195293e | 7443ce3c4ae8242fb7d149b099a296c1f905ef9d | /ui/aura/event_injector.h | 52c17e5b159e5dc9309dca54526a3f838cdd4c28 | [
"BSD-3-Clause"
] | permissive | KiranNiranjan/chromium | fa9f6175dfc4bebab3ee899dd3c63eb94042352f | 03c5be8133ceec5ed57df9fd40f2ffca23eaa179 | refs/heads/master | 2023-02-22T21:51:50.657102 | 2018-08-24T08:35:22 | 2018-08-24T08:35:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 947 | h | // Copyright 2017 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 UI_AURA_EVENT_INJECTOR_H_
#define UI_AURA_EVENT_INJECTOR_H_
#include "services/ws/public/mojom/event_injector.mojom.h"
#include "ui/aura/aura_export.h"
namespace ui {
class Event;
struct EventDispatchDetails;
}
namespace aura {
class WindowTreeHost;
// Used to inject events into the system. In LOCAL mode, it directly injects
// events into the WindowTreeHost, but in MUS mode, it injects events into the
// window-server (over the mojom API).
class AURA_EXPORT EventInjector {
public:
EventInjector();
~EventInjector();
ui::EventDispatchDetails Inject(WindowTreeHost* host, ui::Event* event);
private:
ui::mojom::EventInjectorPtr event_injector_;
DISALLOW_COPY_AND_ASSIGN(EventInjector);
};
} // namespace aura
#endif // UI_AURA_EVENT_INJECTOR_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
d69cab3da3748e3d3249adbfa0e34a9e766a6137 | ba70180c50d2fa42a48b1c54f33e94daea3baa50 | /Sources/Worker/worker.h | 5ec77a2d0acfbe16eaac49c1df7af6904bf6e4ad | [
"MIT"
] | permissive | GaMJun/Sorting-Comparison | f4f043a54a171ca20eeaa636059d717119e0fc33 | b3eef5eb99caa0b9086e73e195e1cca87257da9f | refs/heads/master | 2020-05-27T09:48:19.029002 | 2019-05-25T14:27:19 | 2019-05-25T14:27:19 | 188,572,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | h | //
// Created by gamjun on 22/04/19.
//
#ifndef TRABALHO1_WORKER_H
#define TRABALHO1_WORKER_H
using namespace std;
#include <string>
class Worker {
public:
static void do_work(string archive_name);
};
#endif //TRABALHO1_WORKER_H
| [
"gamjun_@hotmail.com"
] | gamjun_@hotmail.com |
b4c96544a994678ce003ddfe2c5a0c394536922c | bf8a0129ea37647f40e6beea3d333d31ce8105e8 | /src/core/ui/Button.h | 3d23f1c4174bedf061ff746f07bcef35fbbe6aa0 | [] | no_license | cod3rkane/Pandora | b6a9ea8ddd2c7d1eb69ab758b2ba98e3ec341ef6 | 7f840f25035049f0e9921a542ad4af2af635148c | refs/heads/master | 2022-09-13T06:36:32.117792 | 2019-11-11T09:55:42 | 2019-11-11T09:55:42 | 162,340,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 560 | h | #ifndef CGAME_UIBUTTON_H
#define CGAME_UIBUTTON_H
#include <iostream>
#include "CoreComponent.h"
namespace UI {
class Button : public UI::CoreComponent {
std::function<void(void)> callback;
public:
Button(): UI::CoreComponent::CoreComponent() {
UI::CoreComponent::setInteractive(true);
}
void setCallback(const std::function<void(void)>& cb) override ;
void update() override;
void update(double mouseX, double mouseY, bool isMousePressed) override;
};
}
#endif // CGAME_UIBUTTON_H
| [
"jcesar.developer@gmail.com"
] | jcesar.developer@gmail.com |
6b1438618a8477afd50bfacbab7f869d69f330e2 | 6e121b4e100d4ce7c50ebedd195b2152a2b4ab1d | /include/csv_iterator.hpp | a1451bfca1717c3bd7d434eb6965e344ebf8bab1 | [] | no_license | magania/csv_iterator | 4fb01ea0b8c558daeba022cd33cfe2c75d66363b | a8f3c2f7d594f36763600ab285ef94cd0024b33d | refs/heads/master | 2021-01-17T19:09:24.671364 | 2013-11-03T09:57:43 | 2013-11-03T09:57:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,659 | hpp | #define _CSV_ITERATOR_HPP_
#include <string>
#include <istream>
#include <stdexcept>
#include <boost/tuple/tuple.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include "details/csv_helpers.hpp"
namespace csv {
template<class Tuple>
class iterator {
private:
bool m_bad;
std::istream* m_in;
std::string currentLine;
bool m_currentDirty; // Marks that currentResult is no longer valid
Tuple currentResult; // Useful for passing pointers around
public:
/**
* Constructor denoting end of range
*/
iterator() : m_bad(true),m_currentDirty(true) {
}
iterator(std::istream& in)
: m_bad(false), m_in(&in),m_currentDirty(true)
{
this->operator++();
}
Tuple const* operator->(){
if(m_currentDirty){
this->operator*();
}
return ¤tResult;
}
Tuple operator*() throw (boost::bad_lexical_cast,std::out_of_range) {
if(m_currentDirty){
try {
using namespace boost;
typedef tokenizer<escaped_list_separator<char> > Tokens;
Tokens tokens(currentLine);
details::filler<Tuple>::fill(currentResult,tokens.begin(),tokens.end());
} catch (boost::bad_lexical_cast& ex){
m_bad = true;
throw(ex);
} catch (std::out_of_range& ex){
// Exception when not enough columns in the record
m_bad = true;
throw(ex);
}
m_currentDirty = false;
}
return currentResult;
}
bool operator==(const iterator& other) {
return (m_bad == true) && (other.m_bad == true);
}
bool operator!=(const iterator& other) {
return !(*this == other);
}
iterator& operator++() {
bool res = std::getline(*m_in, currentLine);
m_bad = !res;
m_currentDirty = true;
return *this;
}
};
};
#endif
| [
"ancechu@gmail.com"
] | ancechu@gmail.com |
c400ca682772773c8556350504a42508bf2ccfa7 | 1fda514c3060ac74d493f5b706dee12bb9701808 | /leapfrog-game/src/bullet.cpp | 1ea7be5088d44467d0febf6243bb000180a066ea | [] | no_license | stfrha/leapfrog | dade0b55c79b20f93b058e2af75e17c273de1068 | 62e3ead7ae48b2c2ed46c174a194caa3cae8e956 | refs/heads/master | 2022-11-23T17:12:56.011099 | 2022-11-21T22:10:56 | 2022-11-21T22:10:56 | 125,433,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,092 | cpp | #include "bullet.h"
#include "sceneactor.h"
#include "actoruserdata.h"
#include "bodyuserdata.h"
#include "actoruserdata.h"
#include "blastemitter.h"
using namespace oxygine;
Bullet::Bullet(
SceneActor* sceneActor,
b2World* world,
const b2Vec2& pos,
const float angle,
float impulseMagnitude,
b2Vec2& craftSpeed,
int lifetime,
bool bouncy,
int groupIndex) :
m_sceneActor(sceneActor),
m_groupIndex(groupIndex),
m_firstUpdate(true),
m_lifetime(lifetime)
{
setSize(0.75f, 0.75f);
setPosition(PhysDispConvert::convert(pos, 1.0f));
setAnchor(Vector2(0.5f, 0.5f));
setPriority(163);
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position = pos;
b2Body* body = world->CreateBody(&bodyDef);
b2CircleShape shape;
shape.m_radius = 0.5f;
b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 3.0f;
fixtureDef.friction = 0.3f;
fixtureDef.restitution = 0.5f;
fixtureDef.filter.categoryBits = 1;
fixtureDef.filter.maskBits = 65533;
fixtureDef.filter.groupIndex = -groupIndex;
BodyUserData* bud = new BodyUserData();
bud->m_actor = this;
bud->m_collisionType = CollisionEntity::bullet;
fixtureDef.userData = bud;
body->CreateFixture(&fixtureDef);
body->SetUserData(bud);
ActorUserData* aud = new ActorUserData();
aud->m_body = body;
aud->m_parentCo = NULL;
setUserData(aud);
b2Vec2 vel = b2Vec2(impulseMagnitude * cos(angle), impulseMagnitude * sin(angle));
// vel += craftSpeed;
body->SetLinearVelocity(craftSpeed);
body->ApplyLinearImpulseToCenter(vel, true);
}
void Bullet::bulletHit(b2Contact* contact)
{
if (m_sceneActor)
{
m_sceneActor->addMeToDeathList(this);
}
int emitterLifetime = 150;
int particleLifetime = 500;
float particleDistance = 30.0f;
float particleSize = 0.75f;
float blastIntensity = 200.0f;
// Take damage
// m_damage += 1;
//if (m_damage >= 4)
//{
emitterLifetime = 250;
particleLifetime = 500;
particleDistance = 60.0f;
particleSize = 0.9f;
blastIntensity = 300.0f;
b2WorldManifold m;
contact->GetWorldManifold(&m);
if (contact->GetManifold()->pointCount > 0)
{
spBlastEmitter blast = new BlastEmitter(
PhysDispConvert::convert(m.points[0], 1.0f),
blastIntensity, // Intensity, particles / sec
emitterLifetime, // Emitter Lifetime
particleLifetime, // Particle lifetime
particleDistance, // Particle distance
particleSize); // Particle spawn size
blast->attachTo(m_sceneActor);
}
}
void Bullet::doUpdate(const oxygine::UpdateState& us)
{
if (m_firstUpdate)
{
m_deathTime = us.time + m_lifetime;
m_firstUpdate = false;
}
if (us.time >= m_deathTime)
{
if (m_sceneActor)
{
m_sceneActor->addMeToDeathList(this);
}
}
}
| [
"mail@fredrikhoffman.se"
] | mail@fredrikhoffman.se |
98563cb3df8f9750afebcc8dc84b0fca18e625c5 | 52643d9034ebaf530cc192adf60cd04cc59c6b36 | /incompleteChess/main.cpp | 5e3313a4d2236be02413b8647ea97f5ecabd1a58 | [] | no_license | spior/uniProjects | b55740e404a74e5fab91912f7f489d6a52bb7b5f | b46b313be45edf683b5b433138f6875078eea19e | refs/heads/master | 2021-01-21T13:15:08.138816 | 2016-05-26T20:53:37 | 2016-05-26T20:53:37 | 50,751,033 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 6,897 | cpp |
/*
30/01/2016
A chess program that makes you input N and M number of pieces on the board then input their type and position.
After that, it check if they can take any of the other pieces, or if they can be moved.
Incomplete though, only added pawn logic because it was very short notice.
And some other things because I am not sure how they do it in their course.
Completely untested because Visual Studio's consoles can't print cyrilic properly and I was too lazy to convert all of those messages to latin.
But I'm pretty sure it works.
*/
#include <iostream>
using namespace std;
enum fig_type {
TYPE_NONE,
TYPE_ki, // Цар
TYPE_qu, // Царица
TYPE_ro, // Топ
TYPE_bi, // Офицер
TYPE_kn, // Кон
TYPE_pa // Пешка
};
struct fig
{
int team;
fig_type type;
};
void isEndangered(fig board[8][8], int team, int row, int col)
{
if (board[row][col].team != team)
{
cout << "Figurata na tezi koordinati ne e ot Vashiq otbor." << endl;
return;
}
if (board[row][col].team == 0)
{
cout << "Nqma figura na tezi koordinati." << endl;
return;
}
// Тъй като поддържаме само пешки, проверяваме дали пред нас от ляво и дясно има друга фигура.\
Също, вместо да връщаме стойност -- принтираме, защото не знам вие как го правите. Ако искаш си го направи така.
if (row > 0 && board[row - 1][col - 1].team != team)
cout << row - 1 << "," << col - 1;
if (row > 0 && board[row - 1][col + 1].team != team)
cout << row - 1 << "," << col + 1;
}
void moveFig(fig board[8][8], int team, int row, int col, int newRow, int newCol)
{
if (board[row][col].team == 0)
{
cout << "Nqma figura na tezi koordinati." << endl;
return;
}
if (board[row][col].team != team)
{
cout << "Figurata na tezi koordinati ne e ot Vashiq otbor." << endl;
return;
}
// Пешка
if ((team == 1 && newRow == row - 1) ||
(team == 2 && newRow == row + 1))
{
board[newRow][newCol].team = board[row][col].team;
board[newRow][newCol].type = board[row][col].type;
board[row][col].team = 0;
board[row][col].type = TYPE_NONE;
}
else
{
cout << "Figurata ne moje da bude premestena na tezi koordinati." << endl;
return;
}
}
int main()
{
fig board[8][8] = { 0 };
int N = 0, // N - white
M = 0, // M - black
P = 0; // P - requests
cout << "Vavedete broq na figurite na igrach 1: ";
cin >> N;
cout << "Vavedete broq na figurite na igrach 2: ";
cin >> M;
cout << "Vavedete broq na zaqvkite: ";
cin >> P;
if (N > 8 * 2 || N < 0 ||
M > 8 * 2 || M < 0)
{
cout << "Greshen interval. Prekaleno mnogo figuri." << endl;
return 1;
}
// Искаше ми се това да го направя функция, ама викаш да не вдигам очакванията.
for (int doThisTwiceLol = 0; doThisTwiceLol < 2; doThisTwiceLol++)
{
// ( ) Това сте го учили, едноредов if case. Не би трябвало много да направи впечатление.
for (int i = 0; i < (doThisTwiceLol == 0 ? N : M); i++)
{
char input[512] = { 0 };
int row = 0, col = 0;
cout << "Vavedete figura po zadadeniq format: ";
cin >> input;
if (strlen(input) != 4 ||
!isalpha(input[0]) || input[0] < 'a' || input[0] > 'h' || // Първият елемент трябва да е малка буква от 'a' до 'h'
!isdigit(input[1]) || isdigit(input[1]) > 8 || // Вторият елемент трябва да е цифра от 1 до 8
!isalpha(input[2]) || input[2] < 'a' || input[2] > 'z' || // Третият
!isalpha(input[3]) || input[3] < 'a' || input[3] > 'z') // и четвъртият елемент трябва да са букви от 'a' do 'z'
{
cout << "Greshni danni. Molq, vavedete novi." << endl;
i--;
continue;
}
row = input[1] - '0' - 1;
col = 8 - (input[0] - 'a');
if(board[row][col].team > 0)
{
cout << "Greshni danni. Na tova mqsto veche ima figura. Molq, vavedete novi." << endl;
i--;
continue;
}
switch (input[2])
{
case 'k':
if (input[3] == 'i')
board[row][col].type = TYPE_ki;
else if (input[3] == 'n')
board[row][col].type = TYPE_kn;
break;
case 'q':
board[row][col].type = TYPE_qu;
break;
case 'r':
board[row][col].type = TYPE_ro;
break;
case 'b':
board[row][col].type = TYPE_bi;
break;
case 'p':
board[row][col].type = TYPE_pa;
break;
default:
cout << "Greshni danni. Molq, vavedete novi." << endl;
i--;
continue;
break;
}
board[row][col].team = doThisTwiceLol == 0 ? 1 : 2; // Тук също го има.
}
}
for (int i = 0; i < P; i++)
{
cout << "Zaqvka 1: Izvejda zastresheni ot Vasha figura figuri. Molq, vavedete danni za Vasha figura." << endl;
while (1)
{
int team = 0,
row = 0, col = 0;
cout << "Vavedete otbor: ";
cin >> team;
if (team > 1 || team < 0)
{
cout << "Greshen interval. Otborite sa 1 za beli i 2 za cherni. Molq, vavedete nowi danni." << endl;
continue;
}
char input[512] = { 0 };
cout << "Vavedete koordinati: ";
cin >> input;
if (strlen(input) != 4 ||
!isalpha(input[0]) || input[0] < 'a' || input[0] > 'h' ||
!isdigit(input[1]) || isdigit(input[1]) > 8)
{
cout << "Greshni danni. Molq, vavedete novi." << endl;
i--;
continue;
}
row = input[1] - '0' - 1;
col = 8 - (input[0] - 'a');
isEndangered(board, team, row, col);
break;
}
cout << "Zaqvka 2: Premestvane na figura. Molq, vavedete danni za figurata, koqto iskate da premestite." << endl;
while (1)
{
int team = 0,
row = 0, col = 0,
newRow = 0, newCol = 0;
cout << "Vavedete otbor: ";
cin >> team;
if (team > 1 || team < 0)
{
cout << "Greshen interval. Otborite sa 1 za beli i 2 za cherni. Molq, vavedete novi danni." << endl;
continue;
}
char input[512] = { 0 };
cout << "Vavedete koordinati: ";
cin >> input;
if (strlen(input) != 4 ||
!isalpha(input[0]) || input[0] < 'a' || input[0] > 'h' ||
!isdigit(input[1]) || isdigit(input[1]) > 8 )
{
cout << "Greshni danni. Molq, vavedete novi." << endl;
i--;
continue;
}
row = input[1] - '0' - 1;
col = 8 - (input[0] - 'a');
cout << "Vavedete novi koordinati: ";
cin >> input;
if (strlen(input) != 4 ||
!isalpha(input[0]) || input[0] < 'a' || input[0] > 'h' ||
!isdigit(input[1]) || isdigit(input[1]) > 8)
{
cout << "Greshni danni. Molq, vavedete novi." << endl;
i--;
continue;
}
newRow = input[1] - '0' - 1;
newCol = 8 - (input[0] - 'a');
moveFig(board, team, row, col, newRow, newCol);
break;
}
}
system("pause");
return 0;
} | [
"spior@outlook.com"
] | spior@outlook.com |
efdefbb110a309652285050b4f1ececbd982b75a | 30444b3cbeb830a5a0937d43c062eef9b50272f7 | /src/systems/CooldownSystem.cpp | ee1f1e4080e28a22190e2d38d3897c43c8aa35f9 | [
"MIT"
] | permissive | sb-baifeng-sb/tddod | b3f7d6313c94d1f45b79a00aac45f549057b9f9d | d9c711a02e5bbefca4980a754ebfda9dac3cce9b | refs/heads/master | 2020-06-24T12:01:47.774221 | 2019-07-27T01:45:19 | 2019-07-27T01:45:19 | 198,958,229 | 0 | 0 | null | 2019-07-26T06:18:58 | 2019-07-26T06:18:58 | null | UTF-8 | C++ | false | false | 493 | cpp | #include "CooldownSystem.h"
#include "components/Cooldown.h"
#include "components/FindTarget.h"
void updateCooldownSystem(Registry ®istry, float dt)
{
registry.view<Cooldown>().each([®istry, dt](auto entity, Cooldown &cooldown)
{
auto delay = cooldown.delay - dt;
if (delay <= 0.0f)
{
registry.remove<Cooldown>(entity);
registry.assign<FindTarget>(entity);
return;
}
cooldown.delay = delay;
});
}
| [
"daivuk@gmail.com"
] | daivuk@gmail.com |
3d5becdcf9b14ac98b7638399e5c375d1cf49ce4 | d2f326aba2a49e30371e4656213065f4e0f2a458 | /Chef_and_Sorting.cpp | 7aa3d0be055efbfc0958e0241dc937b9dd0a8fda | [] | no_license | ShivaBansfore-JGEC/Codeforces_Contest_Question | 75231a40395b9e768e0af1cfc900eeebd0a7aad9 | ae47bec04f5b2bef8a15ee0fbe06465f4f70ec81 | refs/heads/main | 2023-07-04T11:50:18.840156 | 2021-08-02T16:16:46 | 2021-08-02T16:16:46 | 348,213,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | #include<bits/stdc++.h>
using namespace std;
void solve(){
long long n;
cin>>n;
vector<long long> a(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
long long op=0,eq=0;
for(int i=1;i<n;i++){
if(a[i-1]>a[i]){
op++;
}else if(a[i-1]==a[i]){
eq++;
}
}
long long ans=op;
if(ans>n/2){
ans=n-ans;
ans-=eq;
}
cout<<ans<<endl;
if(op>n/2){
cout<<3<<" "<<n<<" "<<(1ll<<30)-1<<endl;
for(int i=0;i<n;i++){
a[i]^=(1ll<<30)-1;
}
}
for(int i=n-1;i>0;i--){
if(a[i]<a[i-1]){
cout<<2<<" "<<i+1<<" "<<(1ll<<30)-1<<endl;
}
}
}
int main(){
int t;
cin>>t;
while(t--) solve();
return 0;
} | [
"shivabansfore123@gmail.com"
] | shivabansfore123@gmail.com |
a78400a0e96300841e841e29d18b098caf1959bf | 74296c063bd65a1861ae96c23370e8ffb7f3795c | /src/masternode-sync.h | dd7f67ce3f12a0999b2d31b7f53178d2bb0f5144 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | btcreversal/MSC_MASTER_2021 | 977933426ff65c083e8460ce8ce09e38b0f741d6 | 2602ac8dd7724c13149638d1931453222d5b81e7 | refs/heads/main | 2023-07-13T08:43:52.161365 | 2021-08-26T15:52:26 | 2021-08-26T15:52:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,664 | h | // Copyright (c) 2014-2019 The Dash Core developers
// Copyright (c) 2021 The MasterStakeCoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODE_SYNC_H
#define MASTERNODE_SYNC_H
#include "chain.h"
#include "net.h"
class CMasternodeSync;
static const int MASTERNODE_SYNC_FAILED = -1;
static const int MASTERNODE_SYNC_INITIAL = 0; // sync just started, was reset recently or still in IDB
static const int MASTERNODE_SYNC_WAITING = 1; // waiting after initial to see if we can get more headers/blocks
static const int MASTERNODE_SYNC_GOVERNANCE = 4;
static const int MASTERNODE_SYNC_GOVOBJ = 10;
static const int MASTERNODE_SYNC_GOVOBJ_VOTE = 11;
static const int MASTERNODE_SYNC_FINISHED = 999;
static const int MASTERNODE_SYNC_TICK_SECONDS = 6;
static const int MASTERNODE_SYNC_TIMEOUT_SECONDS = 30; // our blocks are 2.5 minutes so 30 seconds should be fine
extern CMasternodeSync masternodeSync;
//
// CMasternodeSync : Sync masternode assets in stages
//
class CMasternodeSync
{
private:
// Keep track of current asset
int nCurrentAsset;
// Count peers we've requested the asset from
int nTriedPeerCount;
// Time when current masternode asset sync started
int64_t nTimeAssetSyncStarted;
// ... last bumped
int64_t nTimeLastBumped;
// ... or failed
int64_t nTimeLastFailure;
void Fail();
public:
CMasternodeSync() { Reset(); }
void SendGovernanceSyncRequest(CNode* pnode, CConnman& connman);
bool IsFailed() { return nCurrentAsset == MASTERNODE_SYNC_FAILED; }
bool IsBlockchainSynced() { return nCurrentAsset > MASTERNODE_SYNC_WAITING; }
bool IsSynced() { return nCurrentAsset == MASTERNODE_SYNC_FINISHED; }
int GetAssetID() { return nCurrentAsset; }
int GetAttempt() { return nTriedPeerCount; }
void BumpAssetLastTime(const std::string& strFuncName);
int64_t GetAssetStartTime() { return nTimeAssetSyncStarted; }
std::string GetAssetName();
std::string GetSyncStatus();
void Reset();
void SwitchToNextAsset(CConnman& connman);
void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv);
void ProcessTick(CConnman& connman);
void AcceptedBlockHeader(const CBlockIndex *pindexNew);
void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman);
void UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman);
void DoMaintenance(CConnman &connman);
};
#endif
| [
"math.bach.com@gmail.com"
] | math.bach.com@gmail.com |
94a366c849fb6e1388459a1e32e1716735e5ac42 | 3d1404442e2b338dd9a74ff1c72b0ac84160faa0 | /Important_Psuedocode/permutations.cpp | 77752f933140eb3c514a6fe07b18fc39e9fca271 | [] | no_license | rishilss99/InterviewBit | e82d9d2317d9cc609612abd18d9f9c52ab4bba1f | bb32c2c1cb3b8c8ad8595b3b7180d5adeeae1fee | refs/heads/master | 2023-04-17T01:52:02.567979 | 2021-04-15T14:24:36 | 2021-04-15T14:24:36 | 286,199,469 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | cpp | void permutations(vector<vector<int>> &set, vector<int> A, int start = 0){
if(start==A.size()-1){
set.push_back(A);
return;
}
for(int i = start; i<A.size(); i++){
swap(A[start],A[i]);
permutations(set, A, start+1);
swap(A[start],A[i]);
}
}
vector<vector<int> > Solution::permute(vector<int> &A) {
vector<vector<int>> ans;
permutations(ans, A);
return ans;
}
| [
"rishil2008@gmail.com"
] | rishil2008@gmail.com |
5971e6f3ef729782f81646aca971f00a0ab8891b | 6f9ae94ce3d41a0d19e1b5f915b7bb2bde7ea9d1 | /muduo/base/CountDownLatch.h | a923fbc264b145f3140d48d532aa3be91a80e3b7 | [
"BSD-3-Clause"
] | permissive | chudongfang/Muduo_Analysis | 75afa002653ef1ccc0695824a26b6351a67fdb05 | df346844296ac9d177948e2bce4aff5782b715f1 | refs/heads/master | 2021-01-20T10:16:09.814748 | 2018-01-01T14:08:24 | 2018-01-01T14:08:24 | 101,626,181 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 820 | h | // Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#ifndef MUDUO_BASE_COUNTDOWNLATCH_H
#define MUDUO_BASE_COUNTDOWNLATCH_H
#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>
#include <boost/noncopyable.hpp>
namespace muduo
{
class CountDownLatch : boost::noncopyable
{
public:
//构造函数,初始化倒计时变量
explicit CountDownLatch(int count);
//等待count_为0
void wait();
//变量减一
void countDown();
//返回变量值
int getCount() const;
private:
mutable MutexLock mutex_;//互斥锁,mutable修饰符表示其可以在任何情况下变化
Condition condition_;//条件变量
int count_; //计时数
};
}
#endif // MUDUO_BASE_COUNTDOWNLATCH_H
| [
"1149669942@qq.com"
] | 1149669942@qq.com |
9131b0d9ebab2d45e6be8b5de24f79daed2ed88c | 1e41e84ddd425628a8725b7186cab5d5463236c8 | /Deskam/Deskam.h | 21c35f5e7c2d28dc6ad9fe3c7528fa3a84a74cd7 | [] | no_license | eakhtar/deskam | 67e218c8291a073ee03694d2914fa7b15aca2ca9 | f530db24304bc748a304ce708108495304b2be89 | refs/heads/master | 2016-08-11T09:22:05.215623 | 2010-03-13T17:39:32 | 2010-03-13T17:39:32 | 43,008,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | h |
// Deskam.h : main header file for the PROJECT_NAME application
//
#pragma once
#include "SharedMemory.h"
#include "DeskamConfig.h"
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CDeskamApp:
// See Deskam.cpp for the implementation of this class
//
class CDeskamApp : public CWinApp
{
public:
CDeskamApp();
DECLARE_MESSAGE_MAP()
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
DeskamGlobalConfig *config();
protected:
SharedMemory mMemory;
};
extern CDeskamApp theApp; | [
"rickytaylor26@72bd7214-2ec1-11df-b28a-19025b8c0740"
] | rickytaylor26@72bd7214-2ec1-11df-b28a-19025b8c0740 |
adbedae4e57827b5e6345ee9ae8037dbe4bf2b72 | 12efef76938e3a4a9789013ee6492deac96f9e85 | /RadioPIC/Receptor_term2/Receptor_term2.cp | 1af25c21219577ade18687f9a2c3198a02ffd736 | [] | no_license | ELuzzi/libusb_radio_MCP2210 | 49d0349f3b3e6e10018356342e78f50fb0978027 | 74ec7d62eb1d0e724d6a1473149c65b9413674a8 | refs/heads/master | 2021-01-21T13:04:16.038387 | 2015-11-03T19:48:34 | 2015-11-03T19:48:34 | 38,726,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,662 | cp | #line 1 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
#line 116 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
sbit CS2 at LATC0_bit;
sbit RST at LATC1_bit;
sbit INT at RC6_bit;
sbit WAKE at LATC2_bit;
sbit CS2_Direction at TRISC0_bit;
sbit RST_Direction at TRISC1_bit;
sbit INT_Direction at TRISC6_bit;
sbit WAKE_Direction at TRISC2_bit;
sbit LCD_RS at RE2_bit;
sbit LCD_EN at RE1_bit;
sbit LCD_D4 at RD4_bit;
sbit LCD_D5 at RD5_bit;
sbit LCD_D6 at RD6_bit;
sbit LCD_D7 at RD7_bit;
sbit LCD_RS_Direction at TRISE2_bit;
sbit LCD_EN_Direction at TRISE1_bit;
sbit LCD_D4_Direction at TRISD4_bit;
sbit LCD_D5_Direction at TRISD5_bit;
sbit LCD_D6_Direction at TRISD6_bit;
sbit LCD_D7_Direction at TRISD7_bit;
const unsigned short int DATA_LENGHT = 5;
const unsigned short int HEADER_LENGHT = 11;
int address_RX_FIFO, address_TX_normal_FIFO;
short int data_RX_FIFO[1 + HEADER_LENGHT + DATA_LENGHT + 2 + 1 + 1], lost_data;
short int ADDRESS_short_1[2], ADDRESS_long_1[8];
short int ADDRESS_short_2[2], ADDRESS_long_2[8];
short int PAN_ID_1[2];
short int PAN_ID_2[2];
short int DATA_RX[DATA_LENGHT], DATA_TX[DATA_LENGHT], data_TX_normal_FIFO[DATA_LENGHT + HEADER_LENGHT + 2];
short int LQI, RSSI2, SEQ_NUMBER;
short int temp1;
#line 160 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void write_ZIGBEE_short(short int address, short int data_r) {
CS2 = 0;
address = ((address << 1) & 0b01111111) | 0x01;
SPI1_Write(address);
SPI1_Write(data_r);
CS2 = 1;
}
short int read_ZIGBEE_short(short int address) {
short int data_r = 0, dummy_data_r = 0;
CS2 = 0;
address = (address << 1) & 0b01111110;
SPI1_Write(address);
data_r = SPI1_Read(dummy_data_r);
CS2 = 1;
return data_r;
}
#line 188 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void write_ZIGBEE_long(int address, short int data_r) {
short int address_high = 0, address_low = 0;
CS2 = 0;
address_high = (((short int)(address >> 3)) & 0b01111111) | 0x80;
address_low = (((short int)(address << 5)) & 0b11100000) | 0x10;
SPI1_Write(address_high);
SPI1_Write(address_low);
SPI1_Write(data_r);
CS2 = 1;
}
short int read_ZIGBEE_long(int address) {
short int data_r = 0, dummy_data_r = 0;
short int address_high = 0, address_low = 0;
CS2 = 0;
address_high = ((short int)(address >> 3) & 0b01111111) | 0x80;
address_low = ((short int)(address << 5) & 0b11100000);
SPI1_Write(address_high);
SPI1_Write(address_low);
data_r = SPI1_Read(dummy_data_r);
CS2 = 1;
return data_r;
}
#line 222 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void start_transmit() {
short int temp = 0;
temp = read_ZIGBEE_short( 0x1B );
temp = temp | 0x01;
write_ZIGBEE_short( 0x1B , temp);
}
#line 233 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void read_RX_FIFO() {
unsigned short int temp = 0;
int i = 0;
temp = read_ZIGBEE_short( 0x39 );
temp = temp | 0x04;
write_ZIGBEE_short( 0x39 , temp);
for(i=0; i<128; i++) {
if(i < (1 + DATA_LENGHT + HEADER_LENGHT + 2 + 1 + 1))
data_RX_FIFO[i] = read_ZIGBEE_long(address_RX_FIFO + i);
if(i >= (1 + DATA_LENGHT + HEADER_LENGHT + 2 + 1 + 1))
lost_data = read_ZIGBEE_long(address_RX_FIFO + i);
}
DATA_RX[0] = data_RX_FIFO[HEADER_LENGHT + 1];
DATA_RX[1] = data_RX_FIFO[HEADER_LENGHT + 2];
DATA_RX[2] = data_RX_FIFO[HEADER_LENGHT + 3];
DATA_RX[3] = data_RX_FIFO[HEADER_LENGHT + 4];
DATA_RX[4] = data_RX_FIFO[HEADER_LENGHT + 5];
LQI = data_RX_FIFO[1 + HEADER_LENGHT + DATA_LENGHT + 2];
RSSI2 = data_RX_FIFO[1 + HEADER_LENGHT + DATA_LENGHT + 3];
temp = read_ZIGBEE_short( 0x39 );
temp = temp & (!0x04);
write_ZIGBEE_short( 0x39 , temp);
}
#line 265 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_ACK(void){
short int temp = 0;
temp = read_ZIGBEE_short( 0x1B );
temp = temp | 0x04;
write_ZIGBEE_short( 0x1B , temp);
}
void set_not_ACK(void){
short int temp = 0;
temp = read_ZIGBEE_short( 0x1B );
temp = temp & (!0x04);
write_ZIGBEE_short( 0x1B , temp);
}
#line 284 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_encrypt(void){
short int temp = 0;
temp = read_ZIGBEE_short( 0x1B );
temp = temp | 0x02;
write_ZIGBEE_short( 0x1B , temp);
}
void set_not_encrypt(void){
short int temp = 0;
temp = read_ZIGBEE_short( 0x1B );
temp = temp & (!0x02);
write_ZIGBEE_short( 0x1B , temp);
}
void write_TX_normal_FIFO() {
int i = 0;
data_TX_normal_FIFO[0] = HEADER_LENGHT;
data_TX_normal_FIFO[1] = HEADER_LENGHT + DATA_LENGHT;
data_TX_normal_FIFO[2] = 0x01;
data_TX_normal_FIFO[3] = 0x88;
data_TX_normal_FIFO[4] = SEQ_NUMBER;
data_TX_normal_FIFO[5] = PAN_ID_2[1];
data_TX_normal_FIFO[6] = PAN_ID_2[0];
data_TX_normal_FIFO[7] = ADDRESS_short_2[0];
data_TX_normal_FIFO[8] = ADDRESS_short_2[1];
data_TX_normal_FIFO[9] = PAN_ID_1[0];
data_TX_normal_FIFO[10] = PAN_ID_1[1];
data_TX_normal_FIFO[11] = ADDRESS_short_1[0];
data_TX_normal_FIFO[12] = ADDRESS_short_1[1];
data_TX_normal_FIFO[13] = DATA_TX[0];
data_TX_normal_FIFO[14] = DATA_TX[1];
data_TX_normal_FIFO[15] = DATA_TX[2];
data_TX_normal_FIFO[16] = DATA_TX[3];
data_TX_normal_FIFO[17] = DATA_TX[4];
for(i = 0; i < (HEADER_LENGHT + DATA_LENGHT + 2); i++) {
write_ZIGBEE_long(address_TX_normal_FIFO + i, data_TX_normal_FIFO[i]);
}
set_ACK();
set_not_encrypt();
start_transmit();
}
#line 338 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void pin_reset() {
RST = 0;
Delay_ms(5);
RST = 1;
Delay_ms(5);
}
void PWR_reset() {
write_ZIGBEE_short( 0x2A , 0x04);
}
void BB_reset() {
write_ZIGBEE_short( 0x2A , 0x02);
}
void MAC_reset() {
write_ZIGBEE_short( 0x2A , 0x01);
}
void software_reset() {
write_ZIGBEE_short( 0x2A , 0x07);
}
void RF_reset() {
short int temp = 0;
temp = read_ZIGBEE_short( 0x36 );
temp = temp | 0x04;
write_ZIGBEE_short( 0x36 , temp);
temp = temp & (!0x04);
write_ZIGBEE_short( 0x36 , temp);
Delay_ms(1);
}
#line 374 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void enable_interrupt() {
write_ZIGBEE_short( 0x32 , 0x00);
}
#line 381 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_channel(short int channel_number) {
if((channel_number > 26) || (channel_number < 11)) channel_number = 11;
switch(channel_number) {
case 11:
write_ZIGBEE_long( 0x200 , 0x02);
break;
case 12:
write_ZIGBEE_long( 0x200 , 0x12);
break;
case 13:
write_ZIGBEE_long( 0x200 , 0x22);
break;
case 14:
write_ZIGBEE_long( 0x200 , 0x32);
break;
case 15:
write_ZIGBEE_long( 0x200 , 0x42);
break;
case 16:
write_ZIGBEE_long( 0x200 , 0x52);
break;
case 17:
write_ZIGBEE_long( 0x200 , 0x62);
break;
case 18:
write_ZIGBEE_long( 0x200 , 0x72);
break;
case 19:
write_ZIGBEE_long( 0x200 , 0x82);
break;
case 20:
write_ZIGBEE_long( 0x200 , 0x92);
break;
case 21:
write_ZIGBEE_long( 0x200 , 0xA2);
break;
case 22:
write_ZIGBEE_long( 0x200 , 0xB2);
break;
case 23:
write_ZIGBEE_long( 0x200 , 0xC2);
break;
case 24:
write_ZIGBEE_long( 0x200 , 0xD2);
break;
case 25:
write_ZIGBEE_long( 0x200 , 0xE2);
break;
case 26:
write_ZIGBEE_long( 0x200 , 0xF2);
break;
}
RF_reset();
}
#line 439 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_CCA_mode(short int CCA_mode) {
short int temp = 0;
switch(CCA_mode) {
case 1: {
temp = read_ZIGBEE_short( 0x3A );
temp = temp | 0x80;
temp = temp & 0xDF;
write_ZIGBEE_short( 0x3A , temp);
write_ZIGBEE_short( 0x3F , 0x60);
}
break;
case 2: {
temp = read_ZIGBEE_short( 0x3A );
temp = temp | 0x40;
temp = temp & 0x7F;
write_ZIGBEE_short( 0x3A , temp);
temp = read_ZIGBEE_short( 0x3A );
temp = temp | 0x38;
temp = temp & 0xFB;
write_ZIGBEE_short( 0x3A , temp);
}
break;
case 3: {
temp = read_ZIGBEE_short( 0x3A );
temp = temp | 0xC0;
write_ZIGBEE_short( 0x3A , temp);
temp = read_ZIGBEE_short( 0x3A );
temp = temp | 0x38;
temp = temp & 0xFB;
write_ZIGBEE_short( 0x3A , temp);
write_ZIGBEE_short( 0x3F , 0x60);
}
break;
}
}
#line 483 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_RSSI_mode(short int RSSI_mode) {
short int temp = 0;
switch(RSSI_mode) {
case 1: {
temp = read_ZIGBEE_short( 0x3E );
temp = temp | 0x80;
write_ZIGBEE_short( 0x3E , temp);
}
break;
case 2:
write_ZIGBEE_short( 0x3E , 0x40);
break;
}
}
#line 503 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void nonbeacon_PAN_coordinator_device() {
short int temp = 0;
temp = read_ZIGBEE_short( 0x00 );
temp = temp | 0x08;
write_ZIGBEE_short( 0x00 , temp);
temp = read_ZIGBEE_short( 0x11 );
temp = temp & 0xDF;
write_ZIGBEE_short( 0x11 , temp);
write_ZIGBEE_short( 0x10 , 0xFF);
}
void nonbeacon_coordinator_device() {
short int temp = 0;
temp = read_ZIGBEE_short( 0x00 );
temp = temp | 0x04;
write_ZIGBEE_short( 0x00 , temp);
temp = read_ZIGBEE_short( 0x11 );
temp = temp & 0xDF;
write_ZIGBEE_short( 0x11 , temp);
write_ZIGBEE_short( 0x10 , 0xFF);
}
void nonbeacon_device() {
short int temp = 0;
temp = read_ZIGBEE_short( 0x00 );
temp = temp & 0xF3;
write_ZIGBEE_short( 0x00 , temp);
temp = read_ZIGBEE_short( 0x11 );
temp = temp & 0xDF;
write_ZIGBEE_short( 0x11 , temp);
}
#line 550 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_IFS_recomended() {
short int temp = 0;
write_ZIGBEE_short( 0x00 , 0x93);
temp = read_ZIGBEE_short( 0x21 );
temp = temp | 0x7C;
write_ZIGBEE_short( 0x21 , temp);
temp = read_ZIGBEE_short( 0x2E );
temp = temp | 0x90;
write_ZIGBEE_short( 0x2E , temp);
temp = read_ZIGBEE_short( 0x27 );
temp = temp | 0x31;
write_ZIGBEE_short( 0x27 , temp);
}
void set_IFS_default() {
short int temp = 0;
write_ZIGBEE_short( 0x00 , 0x75);
temp = read_ZIGBEE_short( 0x21 );
temp = temp | 0x84;
write_ZIGBEE_short( 0x21 , temp);
temp = read_ZIGBEE_short( 0x2E );
temp = temp | 0x50;
write_ZIGBEE_short( 0x2E , temp);
temp = read_ZIGBEE_short( 0x27 );
temp = temp | 0x41;
write_ZIGBEE_short( 0x27 , temp);
}
#line 589 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_reception_mode(short int r_mode) {
short int temp = 0;
switch(r_mode) {
case 1: {
temp = read_ZIGBEE_short( 0x00 );
temp = temp & (!0x03);
write_ZIGBEE_short( 0x00 , temp);
}
break;
case 2: {
temp = read_ZIGBEE_short( 0x00 );
temp = temp & (!0x01);
temp = temp | 0x02;
write_ZIGBEE_short( 0x00 , temp);
}
break;
case 3: {
temp = read_ZIGBEE_short( 0x00 );
temp = temp & (!0x02);
temp = temp | 0x01;
write_ZIGBEE_short( 0x00 , temp);
}
break;
}
}
#line 621 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_frame_format_filter(short int fff_mode) {
short int temp = 0;
switch(fff_mode) {
case 1: {
temp = read_ZIGBEE_short( 0x0D );
temp = temp & (!0x0E);
write_ZIGBEE_short( 0x0D , temp);
}
break;
case 2: {
temp = read_ZIGBEE_short( 0x0D );
temp = temp & (!0x06);
temp = temp | 0x08;
write_ZIGBEE_short( 0x0D , temp);
}
break;
case 3: {
temp = read_ZIGBEE_short( 0x0D );
temp = temp & (!0x0A);
temp = temp | 0x04;
write_ZIGBEE_short( 0x0D , temp);
}
break;
case 4: {
temp = read_ZIGBEE_short( 0x0D );
temp = temp & (!0x0C);
temp = temp | 0x02;
write_ZIGBEE_short( 0x0D , temp);
}
break;
}
}
#line 661 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void flush_RX_FIFO_pointer() {
short int temp;
temp = read_ZIGBEE_short( 0x0D );
temp = temp | 0x01;
write_ZIGBEE_short( 0x0D , temp);
}
#line 672 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_short_address(short int * address) {
write_ZIGBEE_short( 0x03 , address[0]);
write_ZIGBEE_short( 0x04 , address[1]);
}
void set_long_address(short int * address) {
short int i = 0;
for(i = 0; i < 8; i++) {
write_ZIGBEE_short( 0x05 + i, address[i]);
}
}
void set_PAN_ID(short int * address) {
write_ZIGBEE_short( 0x01 , address[0]);
write_ZIGBEE_short( 0x02 , address[1]);
}
#line 693 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_wake_from_pin() {
short int temp = 0;
WAKE = 0;
temp = read_ZIGBEE_short( 0x0D );
temp = temp | 0x60;
write_ZIGBEE_short( 0x0D , temp);
temp = read_ZIGBEE_short( 0x22 );
temp = temp | 0x80;
write_ZIGBEE_short( 0x22 , temp);
}
void pin_wake() {
WAKE = 1;
Delay_ms(5);
}
#line 714 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void enable_PLL() {
write_ZIGBEE_long( 0x202 , 0x80);
}
void disable_PLL() {
write_ZIGBEE_long( 0x202 , 0x00);
}
#line 725 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void set_TX_power(unsigned short int power) {
if((power < 0) || (power > 31))
power = 31;
power = 31 - power;
power = ((power & 0b00011111) << 3) & 0b11111000;
write_ZIGBEE_long( 0x203 , power);
}
#line 736 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
void init_ZIGBEE_basic() {
write_ZIGBEE_short( 0x18 , 0x98);
write_ZIGBEE_short( 0x2E , 0x95);
write_ZIGBEE_long( 0x201 , 0x01);
enable_PLL();
write_ZIGBEE_long( 0x206 , 0x90);
write_ZIGBEE_long( 0x207 , 0x80);
write_ZIGBEE_long( 0x208 , 0x10);
write_ZIGBEE_long( 0x220 , 0x21);
}
void init_ZIGBEE_nonbeacon() {
init_ZIGBEE_basic();
set_CCA_mode(1);
set_RSSI_mode(2);
enable_interrupt();
set_channel(11);
RF_reset();
}
char Debounce_INT() {
char i = 0, j = 0, intn_d = 0;
for(i = 0; i < 5; i++) {
intn_d = INT;
if (intn_d == 1)
j++;
}
if (j > 2)
return 1;
else
return 0;
}
void Initialize() {
short int i = 0;
LQI = 0;
RSSI2 = 0;
SEQ_NUMBER = 0x23;
lost_data = 0;
address_RX_FIFO = 0x300;
address_TX_normal_FIFO = 0;
for (i = 0; i < 2; i++) {
ADDRESS_short_1[i] = 1;
ADDRESS_short_2[i] = 2;
PAN_ID_1[i] = 3;
PAN_ID_2[i] = 3;
}
for (i = 0; i < 8; i++) {
ADDRESS_long_1[i] = 1;
ADDRESS_long_2[i] = 2;
}
ADCON1 = 0x0F;
GIE_bit = 0;
TRISA = 0x00;
TRISB = 0x00;
TRISC = 0x00;
TRISD = 0x00;
CS2_Direction = 0;
RST_Direction = 0;
INT_Direction = 1;
WAKE_Direction = 0;
DATA_TX[0] = 0;
DATA_TX[1] = 0;
DATA_TX[2] = 0;
DATA_TX[3] = 0;
DATA_TX[4] = 0;
PORTD = 0;
LATD = 0;
Delay_ms(15);
Lcd_Init();
Lcd_Cmd(_LCD_CLEAR);
Lcd_Cmd(_LCD_CURSOR_OFF);
SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV4, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH);
pin_reset();
software_reset();
RF_reset();
set_WAKE_from_pin();
set_long_address(ADDRESS_long_2);
set_short_address(ADDRESS_short_2);
set_PAN_ID(PAN_ID_2);
init_ZIGBEE_nonbeacon();
nonbeacon_PAN_coordinator_device();
set_TX_power(31);
set_frame_format_filter(1);
set_reception_mode(1);
pin_wake();
}
void main() {
char dig1=0, dig2=0, dig3=0, degrees=0, battery=0;
char temp = 0;
int trans=1;
Initialize();
while(1){
if(trans == 1){
temp = read_ZIGBEE_short( 0x24 );
delay_ms(100);
DATA_TX[0]=dig1;
DATA_TX[1]=dig2;
DATA_TX[2]=dig3;
DATA_TX[3]=degrees;
DATA_TX[4]=battery;
write_TX_normal_FIFO();
#line 867 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
}
#line 906 "C:/Users/User/Documents/libusb_radio_MCP2210/RadioPIC/Receptor_term2/Receptor_term2.c"
}
}
| [
"dudaluzzi@gmail.com"
] | dudaluzzi@gmail.com |
3e643e7a233276aba4151fdf0e4429aec1ba1f63 | e8d02b8f5e435b6339da726dad150fa56f15f9e1 | /fullscratch_graphics_programming/test_DrawPolygon.cpp | 529bb57649b2ca3a862f067ba6a4b1a776e03084 | [] | no_license | itiut/sutra-copying | 78437387b67d9a8293c0802341ac94ffe7a2d918 | a9ec1573036b51d8dde46bb3aafd7616665d278c | refs/heads/master | 2020-12-24T16:15:42.008471 | 2017-10-17T12:50:43 | 2017-10-17T12:50:43 | 29,052,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | /* -*- compile-command: "g++ -Wall -Wextra -O2 test_DrawPolygon.cpp lib/imgdib.cpp lib/img32.cpp lib/blt.cpp lib/graphics.cpp -lm" -*- */
#include <iostream>
#include <cstdio>
#include "lib/imgdib.h"
#include "lib/graphics.h"
using namespace std;
void Test_DrawPolygon() {
CImageDIB dib(300, 300);
dib.PixelFill(0, 0, 300, 300, 0xffffffff, 255);
CPolyVertex vertexes;
vertexes.Add(60, 240);
vertexes.Add(90, 75);
vertexes.Add(150, 180);
vertexes.Add(240, 30);
vertexes.Add(270, 270);
DrawPolygon(&dib, &vertexes, 0, 255);
dib.WriteBitmap("output_DrawPolygon.bmp");
}
int main () {
Test_DrawPolygon();
}
| [
"t.yuichi111@gmail.com"
] | t.yuichi111@gmail.com |
3ae348faf1fdf572b6b221874e73046347950810 | 247ee1d5b412eab750964115912266cf6ead1bcd | /KirbiDSMx64-OPS/expression.h | 9144e698eb9318f2d8478080f7b280cba88d6201 | [] | no_license | fcccode/KirbiDSMx64-OPS | e0378c44e809da9c3c6928e39aeae909222ff779 | 638e85d5ebed8e68a2dfcba1faff37c8b9c73bb9 | refs/heads/master | 2020-04-01T21:21:20.474822 | 2018-09-29T20:19:16 | 2018-09-29T20:19:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 928 | h | #ifndef EXPRESSION_H
#define EXPRESSION_H
#include <QDialog>
#include <QAbstractButton>
//#include "mainhome.h"
namespace Ui {
class Expression;
}
class Expression : public QDialog
{
Q_OBJECT
public:
explicit Expression(QWidget *parent = 0);
~Expression();
private slots:
void on_lineEdit_textChanged(const QString &arg1);
void on_Expression_windowTitleChanged(const QString &title);
//void on_buttonBox_clicked(QAbstractButton *button);
void on_buttonBox_clicked(QAbstractButton *button);
private:
Ui::Expression *ui;
public:
QString expfil;
/// QString ui1;
QString disdata;
QString infos;
QString regis;
//QString dsmadd;
QString location(QString getpath, QString textdis, QString log, QString regs) {
expfil = getpath;
disdata = textdis;
infos = log;
regis = regs;
return expfil;
}
};
#endif // EXPRESSION_H
| [
"34746778+Kirbiflint50@users.noreply.github.com"
] | 34746778+Kirbiflint50@users.noreply.github.com |
cff5268d6b44eb03cd11d83b5bbf45437d6bab1d | ecab21462fc75df52132b11349d8e7a0dcd3218c | /net/cookies/CookieJarMgr.h | ef1d7a3687fd89d934dfdb6a180641184181ffaf | [
"Apache-2.0"
] | permissive | mensong/MiniBlink | 4688506a0e9e8f0ed5e6d6daaf470255be2a68b8 | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | refs/heads/master | 2023-03-29T04:40:53.198842 | 2021-04-07T01:56:02 | 2021-04-07T01:56:02 | 161,746,209 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 498 | h |
#ifndef net_CookieJarMgr_h
#define net_CookieJarMgr_h
#include <string>
#include <map>
namespace net {
class WebCookieJarImpl;
class CookieJarMgr {
public:
static CookieJarMgr* getInst()
{
if (!m_inst)
m_inst = new CookieJarMgr();
return m_inst;
}
WebCookieJarImpl* createOrGet(const std::string& fullPath);
private:
static CookieJarMgr* m_inst;
std::map<std::string, WebCookieJarImpl*> m_pathToCookies;
};
}
#endif // net_CookieJarMgr_h | [
"mail0668@gmail.com"
] | mail0668@gmail.com |
9aa31379e9062cf5c19794b0560d764257b3f160 | 8e65370be946921a3c6153479704d75a8e2d0289 | /unitymjgvr180/src/main/cpp/Hook/HookGVR/HookGVRTools.h | 963861db50552b966e25cb2a5da7a0c9ac1d2c66 | [] | no_license | Matt-Meng/myrender | 19dfabf7505adadfb8ec7d2d1ad9bf0a8085eb45 | d568f6f3fcad33d18bf8babaf9f1b21dfd3908e0 | refs/heads/master | 2023-06-04T08:38:23.496473 | 2017-11-23T10:28:07 | 2017-11-23T10:28:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,879 | h | #pragma once
#include "../../Base/MojingTypes.h"
#ifdef MJ_OS_ANDROID
// from gvrtyprs.h
typedef struct gvr_context_ gvr_context;
struct gvr_frame;
struct gvr_buffer_viewport_list;
typedef struct gvr_clock_time_point
{
int64_t monotonic_system_time_nanos;
} gvr_clock_time_point;
// end gvrtyprs.h
typedef struct gvr_mat4f
{
float m[4][4];
} gvr_mat4f;
typedef struct gvr_version_ {
int32_t major;
int32_t minor;
int32_t patch;
} gvr_version;
typedef struct gvr_sizei {
int32_t width;
int32_t height;
} gvr_sizei;
#define FN_gvr_get_head_space_from_start_space_rotation "gvr_get_head_space_from_start_space_rotation"
typedef gvr_mat4f (*FP_gvr_get_head_space_from_start_space_rotation)(const gvr_context *gvr, const gvr_clock_time_point time);
#define FN_gvr_reset_tracking "gvr_reset_tracking"// Deprecated
typedef void (*FP_gvr_reset_tracking)(gvr_context *gvr);// Deprecated
#define FN_gvr_recenter_tracking "gvr_recenter_tracking"
typedef void(*FP_gvr_recenter_tracking)( gvr_context *gvr);
#define FN_gvr_get_viewer_model "gvr_get_viewer_model"
typedef const char *(*FP_gvr_get_viewer_model)(const gvr_context *gvr);
#define FN_gvr_get_viewer_vendor "gvr_get_viewer_vendor"
typedef const char *(*FP_gvr_get_viewer_vendor)(const gvr_context *gvr);
#define FN_gvr_get_version_string "gvr_get_version_string"
typedef const char * (*FP_gvr_get_version_string)();
#define FN_gvr_on_surface_created_reprojection_thread "gvr_on_surface_created_reprojection_thread"
typedef int (*FP_gvr_on_surface_created_reprojection_thread)(const gvr_context *gvr);
#define FN_gvr_render_reprojection_thread "gvr_render_reprojection_thread"
typedef int (*FP_gvr_render_reprojection_thread)(const gvr_context *gvr);
#define FN_gvr_get_version "gvr_get_version"
typedef gvr_version (*FP_gvr_get_version)();
#define FN_gvr_initialize_gl "gvr_initialize_gl"
typedef void (*FP_gvr_initialize_gl)(gvr_context* gvr);
#define FN_gvr_frame_bind_buffer "gvr_frame_bind_buffer"
typedef void (*FP_gvr_frame_bind_buffer)(gvr_frame* frame, int32_t index);
#define FN_gvr_frame_unbind "gvr_frame_unbind"
typedef void (*FP_gvr_frame_unbind)(gvr_frame* frame);
#define FN_gvr_is_feature_supported "gvr_is_feature_supported"
typedef bool (*FP_gvr_is_feature_supported)(const gvr_context* gvr, int32_t feature);
#define FN_gvr_frame_submit "gvr_frame_submit"
typedef void(*FP_gvr_frame_submit)(gvr_frame **frame, const gvr_buffer_viewport_list *list, gvr_mat4f head_space_from_start_space);
#define FN_gvr_get_maximum_effective_render_target_size "gvr_get_maximum_effective_render_target_size"
typedef gvr_sizei (*FP_gvr_get_maximum_effective_render_target_size)(const gvr_context* gvr);
#define USING_SVR_SENSOR 0
class HookGVRTools
{
public:
HookGVRTools();
virtual ~HookGVRTools();
static bool Init();
// static gvr_version HOOK_gvr_get_version();
private:
#if USING_SVR_SENSOR
static class CSVRApi m_SVRApi;
#else
static bool m_bSVREnable;
#endif
static bool LoadGVR();
static gvr_mat4f HOOK_gvr_get_head_space_from_start_space_rotation(const gvr_context *gvr, const gvr_clock_time_point time);
static void HOOK_gvr_frame_submit(gvr_frame **frame, const gvr_buffer_viewport_list *list, gvr_mat4f head_space_from_start_space);
// static int HOOK_gvr_on_surface_created_reprojection_thread(const gvr_context *gvr);
// static int HOOK_gvr_render_reprojection_thread(const gvr_context *gvr);
static void HOOK_gvr_initialize_gl(gvr_context* gvr);
static bool HOOK_gvr_is_feature_supported(const gvr_context* gvr, int32_t feature);
static void HOOK_gvr_frame_unbind(gvr_frame* frame);
static void HOOK_gvr_reset_tracking(gvr_context *gvr); // Deprecated
static void HOOK_gvr_recenter_tracking(gvr_context *gvr);
static void * m_hGVR;
static FP_gvr_get_head_space_from_start_space_rotation m_fp_gvr_get_head_space_from_start_space_rotation;
static FP_gvr_frame_submit m_fp_gvr_frame_submit;
static FP_gvr_reset_tracking m_fp_gvr_reset_tracking;// Deprecated
static FP_gvr_recenter_tracking m_fp_gvr_recenter_tracking;
static FP_gvr_get_viewer_model m_fp_gvr_get_viewer_model;
static FP_gvr_get_viewer_vendor m_fp_gvr_get_viewer_vendor;
static FP_gvr_get_version_string m_fp_gvr_get_version_string;
// static FP_gvr_on_surface_created_reprojection_thread m_fp_gvr_on_surface_created_reprojection_thread;
// static FP_gvr_render_reprojection_thread m_fp_gvr_render_reprojection_thread;
static FP_gvr_get_version m_fp_gvr_get_version;
static FP_gvr_initialize_gl m_fp_gvr_initialize_gl;
static FP_gvr_frame_bind_buffer m_fp_gvr_frame_bind_buffer;
static FP_gvr_frame_unbind m_fp_gvr_frame_unbind;
static FP_gvr_is_feature_supported m_fp_gvr_is_feature_supported;
static FP_gvr_get_maximum_effective_render_target_size m_fp_gvr_get_maximum_effective_render_target_size;
};
extern bool g_bEnableDDTracker;
extern float g_fDDHeaderView[16];
#endif | [
"hgl868@126.com"
] | hgl868@126.com |
f54ec73d4941f3855248e8b9feaeea758a1289e7 | 3154bbcece564175aed0dbd91c69cd1de5b55149 | /MOT_Thesis_1551025_1551034/ImageMatching.cpp | bc586eb984fbe464ba7eb9ae7bf3aad861ff57c3 | [] | no_license | omar-Fouad/MOT_Thesis_1551025_1551034 | cd1124644e8f6f3d6cbb65bb064a64bb6c2b5908 | b33d1d3c08dee054961b5bd5e464349a81cd1cb9 | refs/heads/master | 2020-07-16T04:51:56.100019 | 2019-08-06T01:18:34 | 2019-08-06T01:18:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,470 | cpp | #include "ImageMatching.h"
using namespace cv;
int ImageMatching::getBoundingBoxImageMatching(const cv::Mat& preBBoxFrame, const cv::Mat& detectFrame,int firstDetectedId, vector<BoundingBox>& bboxList)
{
const int MIN_MATCH_COUNT = 10;
Mat objectFrame;
vector<KeyPoint> keyPoints1;
vector<KeyPoint> keyPoints2;
Mat descriptor1;
Mat descriptor2;
vector<vector<DMatch> > knn_matches;
const float ratio_thresh = 0.9f;
Rect newBox;
bool isDetect = false;
for (size_t i = 0;i < bboxList.size();i++)
{
if ((firstDetectedId == 2 && bboxList[i].getClassId() == 7) || firstDetectedId == bboxList[i].getClassId())
{
newBox = boxHelper.normalizeCroppedBox(bboxList[i].getRegion(), detectFrame.cols, detectFrame.rows);
objectFrame = detectFrame(newBox);
if (!isDetect)
{
detector->detect(preBBoxFrame, keyPoints1);
if (keyPoints1.size() == 0)
{
continue;
}
briefDescriptor->compute(preBBoxFrame, keyPoints1, descriptor1);
if (descriptor1.empty())
{
continue;
}
isDetect = true;
}
detector->detect(objectFrame, keyPoints2);
if ( keyPoints2.size() == 0) {
continue;
}
briefDescriptor->compute(objectFrame, keyPoints2, descriptor2);
if (descriptor2.empty()) {
continue;
}
matcher->knnMatch(descriptor1, descriptor2, knn_matches, 2);
vector<DMatch> good_matches;
for (size_t i = 0; i < knn_matches.size(); i++)
{
if (knn_matches[i].size() < 2)
{
continue;
}
if (knn_matches[i][0].distance < ratio_thresh * knn_matches[i][1].distance)
{
good_matches.push_back(knn_matches[i][0]);
}
}
//Mat img_matches;
//drawMatches(preBBoxFrame, keyPoints1, objectFrame, keyPoints2, good_matches, img_matches, Scalar::all(-1),
// Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
////-- Show detected matches
//imshow("Good Matches", img_matches);
cout << "Matching Result Value: " << good_matches.size() << endl;
if (good_matches.size() >= MIN_MATCH_COUNT)
{
return i;
}
}
}
//release Mat
if (!objectFrame.empty())
{
objectFrame.release();
}
if (!descriptor1.empty())
{
descriptor1.release();
}
if (!descriptor2.empty())
{
descriptor2.empty();
}
return -1;
}
ImageMatching::ImageMatching()
{
detector = GFTTDetector::create(Config::maxFeatureTrack, 0.001, 10);
briefDescriptor = xfeatures2d::BriefDescriptorExtractor::create();
matcher = BFMatcher::create();
}
| [
"phylieng97@gmail.com"
] | phylieng97@gmail.com |
45d29510b5ea65f01ec8910da6cbe76cb84e5226 | a718c79034d98d34e9def6dc28c122b7e1221d46 | /solutions/998. Maximum Binary Tree IIC++ | be2a23942d78608be327d3db185c35ef76c012ca | [] | no_license | jitasi/leetcode | 7868d5c4e55ac4071629fc5bc40d6aaa00b51452 | a96b48e42d33ab15e58c9ec5a12953dac744eb1c | refs/heads/master | 2020-06-03T08:15:30.825817 | 2019-09-05T00:16:21 | 2019-09-05T00:16:21 | 191,504,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 806 | /* vim: set ft=cpp : */
// Runtime: 4 ms, faster than 99.42% of C++ online submissions for Maximum
// Binary Tree II. Memory Usage: 11.3 MB, less than 87.41% of C++ online
// submissions for Maximum Binary Tree II.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *insertIntoMaxTree(TreeNode *root, int val) {
if (root == nullptr) {
return new TreeNode(val);
}
if (root->val < val) {
TreeNode *new_root = new TreeNode(val);
new_root->left = root;
new_root->right = nullptr;
return new_root;
}
root->right = insertIntoMaxTree(root->right, val);
return root;
}
};
| [
"steven.ge@gmail.com"
] | steven.ge@gmail.com | |
472e7c21ebe94772b833492af98a97984505d643 | bb3917dab2954b514cda9fb3912803f91ec9bb5e | /Predicate.cpp | 91bb90c90c733dc0d2e3cc627d71715e37126155 | [] | no_license | ndriggs/parser | 82d4658e0cc8b197ed9d294148771c634ed1941e | 4861493ff691bd07d029f387bb2ad5840bc15c56 | refs/heads/master | 2022-12-23T18:59:18.614421 | 2020-09-29T15:39:39 | 2020-09-29T15:39:39 | 295,017,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | #include "Predicate.h"
#include <string>
#include <vector>
#include <sstream>
using namespace std;
Predicate::Predicate(){
this->id = "";
}
Predicate::Predicate(string id){
this->id = id;
}
void Predicate::addId(string id){
this->id = id;
}
void Predicate::addParameter(Parameter* p){
parameters.push_back(p);
}
string Predicate::toString(){
stringstream ss;
ss << id << "(";
for(int i = 0; (unsigned)i < parameters.size(); i++){
ss << parameters[i]->toString();
if((unsigned)(i+1) < parameters.size())
ss << ",";
}
ss << ")";
return ss.str();
}
| [
"nathanieldriggs@gmail.com"
] | nathanieldriggs@gmail.com |
803057cfce7681296bf3dd5827d288d93d375899 | 64920237a769821bb39a0cfcca87ab9cc9766d1f | /RTC_DS12887/RTC_DS12887.ino | 0f95902768db577d94bb3e96461970625854c957 | [] | no_license | Reverse-Lab/Arduino-Test | 6c196544d59ac0ec287de1bf3703a24576220c0c | 6ead9b5308dd6da9dabfbc22a0264506058326fd | refs/heads/master | 2023-03-20T19:03:32.576103 | 2021-03-17T13:31:53 | 2021-03-17T13:31:53 | 278,634,095 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,676 | ino |
// DS12887 ADDRESS REGISTERS
const uint8_t REGISTER_SECONDS = B00000000; // Seconds
const uint8_t REGISTER_SECONDS_ALARM = B00000001; // Seconds alarm
const uint8_t REGISTER_MINUTES = B00000010; // Minutes
const uint8_t REGISTER_MINUTES_ALARM = B00000011; // Minutes alarm
const uint8_t REGISTER_HOURS = B00000100; // Hours
const uint8_t REGISTER_HOURS_ALARM = B00000101; // Hours alarm
const uint8_t REGISTER_DOW = B00000110; // Day of week
const uint8_t REGISTER_DOM = B00000111; // Day of month
const uint8_t REGISTER_MONTH = B00001000; // Month
const uint8_t REGISTER_YEAR = B00001001; // Year
const uint8_t REGISTER_A = 0x0A; //B00001010; // REGISTER A
const uint8_t REGISTER_B = 0x0B; //B00001011; // REGISTER B
const uint8_t REGISTER_C = 0x0C; //B00001100; // REGISTER C
const uint8_t REGISTER_D = 0x0D; //B00001101; // REGISTER D
// dataPins = AD0 - AD7
int dataPins[8] = {2, 3, 4, 5, 6, 7, 8, 9};
// int dataPins[8] = {9, 8, 7, 6, 5, 4, 3, 2}; INVERTED
int CS = 10; // SELECT CHIP
int AS = 11; // STROBE ADDRESS
int RW = 12; // HIGH READ LOW WRITE
int DS = 13; // READ
uint8_t seconds;
uint8_t asecs;
uint8_t minutes;
uint8_t amins;
uint8_t hours;
uint8_t ahour;
uint8_t dow;
uint8_t dom;
uint8_t month;
uint8_t year;
uint8_t regA;
uint8_t rebB;
uint8_t rebC;
uint8_t rebD;
uint8_t lastsecs = 0b11111111;
boolean getBit(uint8_t myVarIn, uint8_t whatBit) {
boolean bitState;
bitState = myVarIn & (1 << whatBit);
return bitState;
}
uint8_t setBit(uint8_t myVarIn, uint8_t whatBit, boolean bitState) {
if (bitState) {
myVarIn |= (1 << whatBit);
}
else {
myVarIn &= ~(1 << whatBit);
}
return myVarIn;
}
void setIdle() {
digitalWrite(CS, HIGH);
digitalWrite(AS, HIGH);
digitalWrite(RW, HIGH);
digitalWrite(DS, HIGH);
}
void switchRead() {
for (int i=0; i<7; i++) {
pinMode(dataPins[i], INPUT);
}
}
uint8_t readBusData() {
uint8_t dataBuffer = 0b00000000;
for (int i=0; i<8; i++) {
boolean state = digitalRead(dataPins[i]);
dataBuffer = setBit(dataBuffer, i, state);
}
return dataBuffer;
}
void switchWrite() {
for (int i=0; i<7; i++) {
pinMode(dataPins[i], OUTPUT);
}
}
void writeBusData(uint8_t data) {
for (int i=0; i<8; i++) {
digitalWrite(dataPins[i], getBit(data, i));
}
}
uint8_t getRegisterData(uint8_t registerAddr) {
uint8_t dataBuffer = 0b00000000;
switchRead();
delayMicroseconds(15);
digitalWrite(CS, HIGH); digitalWrite(DS, HIGH);
digitalWrite(AS, LOW);
digitalWrite(AS, HIGH);
//digitalWrite(DS, LOW);
readBusData();
//digitalWrite(DS, HIGH);
//digitalWrite(CS, HIGH);
//return dataBuffer;
}
void getRTCDate() {
seconds = getRegisterData(REGISTER_SECONDS);
minutes = getRegisterData(REGISTER_MINUTES);
hours = getRegisterData(REGISTER_HOURS);
dow = getRegisterData(REGISTER_DOW);
dom = getRegisterData(REGISTER_DOM);
month = getRegisterData(REGISTER_MONTH);
year = getRegisterData(REGISTER_YEAR);
}
void setup() {
pinMode(CS, OUTPUT);
pinMode(AS, OUTPUT);
pinMode(RW, OUTPUT);
pinMode(DS, OUTPUT);
setIdle();
switchRead();
Serial.begin(115200);
}
void loop() {
getRTCDate();
Serial.print("(");
Serial.print(dow);
Serial.print(") ");
Serial.print(month);
Serial.print("/");
Serial.print(dom);
Serial.print("/");
Serial.print(year);
Serial.print(" ");
Serial.print(hours);
Serial.print(":");
Serial.print(minutes);
Serial.print(".");
Serial.println(seconds);
delay(1000);
/*
if (lastsecs != seconds) {
lastsecs = seconds;
for (int i=0; i<8; i++) {
//Serial.print(getBit(seconds, i));
}
}
*/
}
/*
//write dat to addr
void rtc_write(unsigned char addr, unsigned char dat) {
digitalWrite(RTC_CS, LOW); //select the chip
digitalWrite(RTC_RW, HIGH); digitalWrite(RTC_DS, HIGH); //ds/rw high
digitalWrite(RTC_AS, HIGH); //as high
RTC_ADDR_PORT = addr; //output the address
RTC_ADDR_DDR = 0xff; //addr as output
digitalWrite(RTC_AS, LOW); //latch the address
RTC_DELAY(); //Pwel 150ns
digitalWrite(RTC_RW, LOW); //enter write mode
RTC_ADDR_PORT = dat; //write the data
RTC_DELAY(); //Pwel 150ns
digitalWrite(RTC_RW, HIGH); //write the data
digitalWrite(RTC_AS, HIGH); //latch the whole thing
digitalWrite(RTC_CS, HIGH); //unselect the chip
RTC_ADDR_DDR = 0x00; //adr pins default to input
}
*/
| [
"65438732+Reverse-Lab@users.noreply.github.com"
] | 65438732+Reverse-Lab@users.noreply.github.com |
eae8e1485582a876d1d1f6315a7fbf5d273cb0e2 | 71bde7b9e201e744bda1fd4a937da99131a17420 | /source/old_engines/eval/evaluate_kpp_ppt/evaluate_kpp_ppt.cpp | 7412af15295eb7705177e284c446d3579fa4355c | [] | no_license | tttak/YaneuraOu | 527423b5d43c2521efb91f433739c6ffc9eb0949 | 713560be5a0e813d9cce7339491bef0db9b30e28 | refs/heads/master | 2021-06-28T18:07:30.047660 | 2018-01-23T15:18:16 | 2018-01-23T15:18:16 | 74,894,757 | 5 | 1 | null | 2016-11-27T15:02:15 | 2016-11-27T15:02:15 | null | UTF-8 | C++ | false | false | 41,791 | cpp | #include "../shogi.h"
// KPP+PPTの実験用コード。
// ほとんどevaluate_kppt.cppと同じ。
#if defined (EVAL_KPP_PPT)
#include "../shogi.h"
#include <fstream>
#include <iostream>
#include <unordered_set>
#include "evaluate_kpp_ppt.h"
#include "evaluate_io.h"
#include "../evaluate.h"
#include "../position.h"
#include "../misc.h"
#include "../extra/bitop.h"
// 実験中の評価関数を読み込む。(現状非公開)
#if defined (EVAL_EXPERIMENTAL)
#include "experimental/evaluate_experimental.h"
#endif
// EvalShareの機能を使うために必要
#if defined (USE_SHARED_MEMORY_IN_EVAL) && defined(_WIN32)
#include <codecvt> // mkdirするのにwstringが欲しいのでこれが必要
#include <locale> // wstring_convertにこれが必要。
#include <windows.h>
#endif
#if defined(EVAL_LEARN)
#include "../learn/learning_tools.h"
using namespace EvalLearningTools;
#endif
using namespace std;
namespace Eval
{
// 評価関数パラメーター
// 2GBを超える配列は確保できないようなのでポインターにしておき、動的に確保する。
ValuePp(*pp_)[fe_end][fe_end];
ValueKkp(*kkp_)[SQ_NB][SQ_NB][fe_end];
ValueKpp(*kpp_)[SQ_NB][fe_end][fe_end];
// 評価関数ファイルを読み込む
void load_eval_impl()
{
// EvalIOを利用して評価関数ファイルを読み込む。
// ちなみに、inputのところにあるbasic_kppt32()をbasic_kppt16()に変更するとApery(WCSC27)の評価関数ファイルが読み込める。
// また、eval_convert()に渡している引数のinputとoutputを入れ替えるとファイルに書き出すことが出来る。EvalIOマジ、っょぃ。
auto make_name = [&](std::string filename) { return path_combine((string)Options["EvalDir"], filename); };
auto input = EvalIO::EvalInfo::build_kpp_ppt(make_name(PP_BIN), make_name(KKP_BIN), make_name(KPP_BIN));
auto output = EvalIO::EvalInfo::build_kpp_ppt((void*)pp, (void*)kkp, (void*)kpp);
// 評価関数の実験のためにfe_endをbuild_kpp_ppt()の値から変更しているかも知れないので現在のfe_endの値をもとに読み込む。
input.fe_end = output.fe_end = Eval::fe_end;
if (!EvalIO::eval_convert(input, output, nullptr))
goto Error;
{
#if defined(EVAL_LEARN)
// kppのp1==p2のところ、値はゼロとなっていること。
// (差分計算のときにコードの単純化のために参照はするけど学習のときに使いたくないので)
// kppのp1==p2のときはkkpに足しこまれているという考え。
{
const ValueKpp kpp_zero = 0;
float sum = 0;
for (auto sq : SQ)
for (auto p = BONA_PIECE_ZERO; p < fe_end; ++p)
{
sum += abs(kpp[sq][p][p]);
kpp[sq][p][p] = kpp_zero;
}
// cout << "info string sum kp = " << sum << endl;
}
#endif
#if defined(EVAL_LEARN)
// 以前Aperyの評価関数バイナリ、kppのp=0のところでゴミが入っていた。
// 駒落ちなどではここを利用したいので0クリアすべき。
{
const ValueKkp kkp_zero = { 0,0 };
for (auto sq1 : SQ)
for (auto sq2 : SQ)
kkp[sq1][sq2][0] = kkp_zero;
const ValueKpp kpp_zero = 0;
for (auto sq : SQ)
for (BonaPiece p1 = BONA_PIECE_ZERO; p1 < fe_end; ++p1)
{
kpp[sq][p1][0] = kpp_zero;
kpp[sq][0][p1] = kpp_zero;
}
}
#endif
}
// 読み込みは成功した。
return;
Error:;
// 評価関数ファイルの読み込みに失敗した場合、思考を開始しないように抑制したほうがいいと思う。
sync_cout << "\ninfo string Error! open evaluation file failed.\n" << sync_endl;
my_exit();
}
u64 calc_check_sum()
{
u64 sum = 0;
auto add_sum = [&](u32*ptr, size_t t)
{
for (size_t i = 0; i < t; ++i)
sum += ptr[i];
};
// sizeof演算子、2GB以上の配列に対して機能しない。VC++でC2070になる。
// そのため、sizeof(kpp)のようにせず、自前で計算している。
add_sum(reinterpret_cast<u32*>(pp), size_of_pp / sizeof(u32));
add_sum(reinterpret_cast<u32*>(kkp), size_of_kkp / sizeof(u32));
add_sum(reinterpret_cast<u32*>(kpp), size_of_kpp / sizeof(u32));
return sum;
}
void init()
{
#if defined(EVAL_EXPERIMENTAL)
init_eval_experimental();
#endif
}
// 与えられたsize_of_evalサイズの連続したalign 32されているメモリに、kk_,kkp_,kpp_を割り当てる。
void eval_assign(void* ptr)
{
s8* p = (s8*)ptr;
pp_ = (ValuePp(*)[fe_end][fe_end]) (p);
kkp_ = (ValueKkp(*)[SQ_NB][SQ_NB][fe_end]) (p + size_of_pp);
kpp_ = (ValueKpp(*)[SQ_NB][fe_end][fe_end]) (p + size_of_pp + size_of_kkp);
}
void eval_malloc()
{
// benchコマンドなどでOptionsを保存して復元するのでこのときEvalDirが変更されたことになって、
// 評価関数の再読込の必要があるというフラグを立てるため、この関数は2度呼び出されることがある。
if (pp_ != nullptr)
{
aligned_free((void*)pp_);
pp_ = nullptr;
}
// メモリ確保は一回にして、連続性のある確保にする。
// このメモリは、プロセス終了のときに自動開放されることを期待している。
eval_assign(aligned_malloc(size_of_eval, 32));
}
#if defined (USE_SHARED_MEMORY_IN_EVAL) && defined(_WIN32)
// 評価関数の共有を行うための大掛かりな仕組み
// gccでコンパイルするときもWindows環境であれば、これが有効になって欲しいので defined(_WIN32) で判定。
void load_eval()
{
// 評価関数を共有するのか
if (!(bool)Options["EvalShare"])
{
eval_malloc();
load_eval_impl();
// 共有されていないメモリを用いる。
sync_cout << "info string use non-shared eval_memory." << sync_endl;
return;
}
// エンジンのバージョンによって評価関数は一意に定まるものとする。
// Numaで確保する名前を変更しておく。
auto dir_name = (string)Options["EvalDir"];
// Mutex名にbackslashは使えないらしいので、escapeする。念のため'/'もescapeする。
replace(dir_name.begin(), dir_name.end(), '\\', '_');
replace(dir_name.begin(), dir_name.end(), '/', '_');
// wchar_t*が必要なので変換する。
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
cv.from_bytes(dir_name).c_str();
auto mapped_file_name = TEXT("YANEURAOU_KPP_PPT_MMF" ENGINE_VERSION) + cv.from_bytes(dir_name);
auto mutex_name = TEXT("YANEURAOU_KPP_PPT_MUTEX" ENGINE_VERSION) + cv.from_bytes(dir_name);
// プロセス間の排他用mutex
auto hMutex = CreateMutex(NULL, FALSE, mutex_name.c_str());
// ファイルマッピングオブジェクトの処理をプロセス間で排他したい。
WaitForSingleObject(hMutex, INFINITE);
{
// ファイルマッピングオブジェクトの作成
auto hMap = CreateFileMapping(INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE, // | /**SEC_COMMIT/**/ /*SEC_RESERVE/**/,
(u32)(size_of_eval >> 32), (u32)size_of_eval,
mapped_file_name.c_str());
bool already_exists = (GetLastError() == ERROR_ALREADY_EXISTS);
// ビュー
auto shared_eval_ptr = (void *)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, size_of_eval);
// メモリが確保できないときはshared_eval_ptr == null。このチェックをしたほうがいいような..。
if (shared_eval_ptr == nullptr)
{
sync_cout << "info string can't allocate shared eval memory." << sync_endl;
my_exit();
}
else
{
// shared_eval_ptrは、32bytesにalignされていると仮定している。
// Windows環境ではそうなっているっぽいし、このコードはWindows環境専用なので
// とりあえず、良しとする。
ASSERT_LV1(((u64)shared_eval_ptr & 0x1f) == 0);
eval_assign(shared_eval_ptr);
if (!already_exists)
{
// 新規作成されてしまった
// このタイミングで評価関数バイナリを読み込む
load_eval_impl();
sync_cout << "info string created shared eval memory." << sync_endl;
}
else {
// 評価関数バイナリを読み込む必要はない。ファイルマッピングが成功した時点で
// 評価関数バイナリは他のプロセスによって読み込まれていると考えられる。
sync_cout << "info string use shared eval memory." << sync_endl;
}
}
}
ReleaseMutex(hMutex);
// 終了時に本当ならば
// 1) ::ReleaseMutex()
// 2) ::UnmapVieOfFile()
// が必要であるが、1),2)がプロセスが解体されるときに自動でなされるので、この処理は特に入れない。
}
#else
// 評価関数のプロセス間共有を行わないときは、普通に
// load_eval_impl()を呼び出すだけで良い。
void load_eval()
{
eval_malloc();
load_eval_impl();
}
#endif
// KP,KPP,KKPのスケール
const int FV_SCALE = 32;
// 評価関数。全計算。(駒割りは差分)
// 返し値は持たず、計算結果としてpos.state()->sumに値を代入する。
void compute_eval_impl(const Position& pos)
{
// is_ready()で評価関数を読み込み、
// 初期化してからしかcompute_eval()を呼び出すことは出来ない。
ASSERT_LV1(&(pp) != nullptr);
// → 32bit環境だとこの変数、単なるポインタなのでこのassertは意味がないのだが、
// とりあえず開発時に早期に気づくようにこのassertを入れておく。
Square sq_bk = pos.king_square(BLACK);
Square sq_wk = pos.king_square(WHITE);
const auto* ppkppb = kpp[sq_bk];
const auto* ppkppw = kpp[Inv(sq_wk)];
auto& pos_ = *const_cast<Position*>(&pos);
#if !defined (USE_EVAL_MAKE_LIST_FUNCTION)
auto list_fb = pos_.eval_list()->piece_list_fb();
auto list_fw = pos_.eval_list()->piece_list_fw();
#else
// -----------------------------------
// USE_EVAL_MAKE_LIST_FUNCTIONが定義されているときは
// ここでeval_listをコピーして、組み替える。
// -----------------------------------
// バッファを確保してコピー
BonaPiece list_fb[40];
BonaPiece list_fw[40];
memcpy(list_fb, pos_.eval_list()->piece_list_fb(), sizeof(BonaPiece) * 40);
memcpy(list_fw, pos_.eval_list()->piece_list_fw(), sizeof(BonaPiece) * 40);
// ユーザーは、この関数でBonaPiece番号の自由な組み換えを行なうものとする。
make_list_function(pos, list_fb, list_fw);
#endif
int i, j;
BonaPiece k0, k1, l0, l1;
// 評価値の合計
EvalSum sum;
#if defined(USE_SSE2)
// sum.p[0](BKPP)とsum.p[1](WKPP),sum.p[2](PP)をゼロクリア
sum.m[0] = _mm_setzero_si128();
sum.m[1] = _mm_setzero_si128();
#else
sum.p[0][0] = sum.p[0][1] = sum.p[1][0] = sum.p[1][1] = sum.p[2][0] = sum.p[2][1] = 0;
#endif
for (i = 0; i < PIECE_NO_KING; ++i)
{
k0 = list_fb[i];
k1 = list_fw[i];
const auto* pkppb = ppkppb[k0];
const auto* pkppw = ppkppw[k1];
for (j = 0; j < i; ++j)
{
l0 = list_fb[j];
l1 = list_fw[j];
// KPP
sum.p[0][0] += pkppb[l0];
sum.p[1][0] += pkppw[l1];
// PP
sum.p[2] += pp[k0][l0];
}
// KKP
sum.p[2] += kkp[sq_bk][sq_wk][k0];
}
auto st = pos.state();
sum.p[2][0] += st->materialValue * FV_SCALE;
st->sum = sum;
}
// 評価関数。差分計算ではなく全計算する。
// Position::set()で一度だけ呼び出される。(以降は差分計算)
// 手番側から見た評価値を返すので注意。(他の評価関数とは設計がこの点において異なる)
// なので、この関数の最適化は頑張らない。
Value compute_eval(const Position& pos)
{
compute_eval_impl(pos);
return Value(pos.state()->sum.sum(pos.side_to_move()) / FV_SCALE);
}
// 後手玉が移動したときの先手玉に対するの差分
std::array<s32, 2> do_a_black(const Position& pos, const ExtBonaPiece ebp) {
const Square sq_bk = pos.king_square(BLACK);
const auto* list0 = pos.eval_list()->piece_list_fb();
const auto* pkppb = kpp[sq_bk][ebp.fb];
std::array<s32, 2> sum = { { pkppb[list0[0]][0], pkppb[list0[0]][1] } };
for (int i = 1; i < PIECE_NO_KING; ++i) {
sum[0] += pkppb[list0[i]][0];
sum[1] += pkppb[list0[i]][1];
}
return sum;
}
// 先手玉が移動したときの後手玉に対する差分
std::array<s32, 2> do_a_white(const Position& pos, const ExtBonaPiece ebp) {
const Square sq_wk = pos.king_square(WHITE);
const auto* list1 = pos.eval_list()->piece_list_fw();
const auto* pkppw = kpp[Inv(sq_wk)][ebp.fw];
std::array<s32, 2> sum = { { pkppw[list1[0]][0], pkppw[list1[0]][1] } };
for (int i = 1; i < PIECE_NO_KING; ++i) {
sum[0] += pkppw[list1[i]][0];
sum[1] += pkppw[list1[i]][1];
}
return sum;
}
// 玉以外の駒が移動したときの差分
EvalSum do_a_pc(const Position& pos, const ExtBonaPiece ebp) {
/*
移動した駒がm駒あるなら、これらの駒をeval_list()[]のn-1,n-2,…,n-mに移動させて、
for(i=1..m)
do_a_black(pos,n-i)
みたいなことをすべきだが、mはたかだか2なので、
こうはせずに、引きすぎた重複分(kpp[k][n-1][n-2])をあとで加算している。
*/
const Square sq_bk = pos.king_square(BLACK);
const Square sq_wk = pos.king_square(WHITE);
const auto list0 = pos.eval_list()->piece_list_fb();
const auto list1 = pos.eval_list()->piece_list_fw();
EvalSum sum;
#if defined(USE_SSE2)
// sum.p[0](BKPP)とsum.p[1](WKPP),sum.p[2](PP)をゼロクリア
sum.m[0] = _mm_setzero_si128();
sum.m[1] = _mm_setzero_si128();
#else
sum.p[0][0] = sum.p[0][1] = sum.p[1][0] = sum.p[1][1] = sum.p[2][0] = sum.p[2][1] = 0;
#endif
// ToDo :ppの計算
const auto* pkppb = kpp[sq_bk][ebp.fb];
const auto* pkppw = kpp[Inv(sq_wk)][ebp.fw];
// ここ、AVX512なら、_mm512_i32gather_epi32()が使える。
// 気が向いたらコード書く。
#if defined (USE_AVX2)
__m256i zero = _mm256_setzero_si256();
__m256i sum0 = zero;
__m256i sum1 = zero;
int i = 0;
for (; i + 8 < PIECE_NO_KING; i += 8) {
__m256i indexes0 = _mm256_load_si256(reinterpret_cast<const __m256i*>(&list0[i]));
__m256i indexes1 = _mm256_load_si256(reinterpret_cast<const __m256i*>(&list1[i]));
__m256i w0 = _mm256_i32gather_epi32(reinterpret_cast<const int*>(pkppb), indexes0, 4);
__m256i w1 = _mm256_i32gather_epi32(reinterpret_cast<const int*>(pkppw), indexes1, 4);
__m256i w0lo = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(w0, 0));
sum0 = _mm256_add_epi32(sum0, w0lo);
__m256i w0hi = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(w0, 1));
sum0 = _mm256_add_epi32(sum0, w0hi);
__m256i w1lo = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(w1, 0));
sum1 = _mm256_add_epi32(sum1, w1lo);
__m256i w1hi = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(w1, 1));
sum1 = _mm256_add_epi32(sum1, w1hi);
}
for (; i + 4 < PIECE_NO_KING; i += 4) {
__m128i indexes0 = _mm_load_si128(reinterpret_cast<const __m128i*>(&list0[i]));
__m128i indexes1 = _mm_load_si128(reinterpret_cast<const __m128i*>(&list1[i]));
__m128i w0 = _mm_i32gather_epi32(reinterpret_cast<const int*>(pkppb), indexes0, 4);
__m128i w1 = _mm_i32gather_epi32(reinterpret_cast<const int*>(pkppw), indexes1, 4);
__m256i w0lo = _mm256_cvtepi16_epi32(w0);
sum0 = _mm256_add_epi32(sum0, w0lo);
__m256i w1lo = _mm256_cvtepi16_epi32(w1);
sum1 = _mm256_add_epi32(sum1, w1lo);
}
for (; i < PIECE_NO_KING; ++i) {
sum.p[0] += pkppb[list0[i]];
sum.p[1] += pkppw[list1[i]];
}
// sum0とsum0の上位128ビットと下位128ビットを独立して8バイトシフトしたものを足し合わせる
sum0 = _mm256_add_epi32(sum0, _mm256_srli_si256(sum0, 8));
// sum0の上位128ビットと下位128ビットを足しあわせてsum0_128に代入する
__m128i sum0_128 = _mm_add_epi32(_mm256_extracti128_si256(sum0, 0), _mm256_extracti128_si256(sum0, 1));
// sum0_128の下位64ビットをdiff.p[1]にストアする
std::array<int32_t, 2> sum0_array;
_mm_storel_epi64(reinterpret_cast<__m128i*>(&sum0_array), sum0_128);
sum.p[0] += sum0_array;
// sum1とsum1の上位128ビットと下位128ビットを独立して8バイトシフトしたものを足し合わせる
sum1 = _mm256_add_epi32(sum1, _mm256_srli_si256(sum1, 8));
// sum1の上位128ビットと下位128ビットを足しあわせてsum1_128に代入する
__m128i sum1_128 = _mm_add_epi32(_mm256_extracti128_si256(sum1, 0), _mm256_extracti128_si256(sum1, 1));
// sum1_128の下位64ビットをdiff.p[1]にストアする
std::array<int32_t, 2> sum1_array;
_mm_storel_epi64(reinterpret_cast<__m128i*>(&sum1_array), sum1_128);
sum.p[1] += sum1_array;
#elif defined (USE_SSE41)
sum.m[0] = _mm_set_epi32(0, 0, *reinterpret_cast<const s32*>(&pkppw[list1[0]][0]), *reinterpret_cast<const s32*>(&pkppb[list0[0]][0]));
sum.m[0] = _mm_cvtepi16_epi32(sum.m[0]);
for (int i = 1; i < PIECE_NO_KING; ++i) {
__m128i tmp;
tmp = _mm_set_epi32(0, 0, *reinterpret_cast<const s32*>(&pkppw[list1[i]][0]), *reinterpret_cast<const s32*>(&pkppb[list0[i]][0]));
tmp = _mm_cvtepi16_epi32(tmp);
sum.m[0] = _mm_add_epi32(sum.m[0], tmp);
}
#else
sum.p[0][0] = pkppb[list0[0]][0];
sum.p[0][1] = pkppb[list0[0]][1];
sum.p[1][0] = pkppw[list1[0]][0];
sum.p[1][1] = pkppw[list1[0]][1];
for (int i = 1; i < PIECE_NO_KING; ++i) {
sum.p[0] += pkppb[list0[i]];
sum.p[1] += pkppw[list1[i]];
}
#endif
return sum;
}
#if defined (USE_EVAL_HASH)
EvaluateHashTable g_evalTable;
// prefetchする関数も用意しておく。
void prefetch_evalhash(const Key key)
{
prefetch(g_evalTable[key >> 1]);
}
#endif
#if !defined(USE_EVAL_MAKE_LIST_FUNCTION)
void evaluateBody(const Position& pos)
{
// 一つ前のノードからの評価値の差分を計算する。
auto now = pos.state();
auto prev = now->previous;
// nodeごとにevaluate()は呼び出しているので絶対に差分計算できるはず。
// 一つ前のnodeでevaluate()されているはず。
//
// root nodeではprevious == nullptrであるが、root nodeではPosition::set()でcompute_eval()
// を呼び出すので通常この関数が呼び出されることはないのだが、学習関係でこれが出来ないと
// コードが書きにくいのでEVAL_LEARNのときは、このチェックをする。
if (
#if defined (EVAL_LEARN)
prev == nullptr ||
#endif
!prev->sum.evaluated())
{
// 全計算
compute_eval_impl(pos);
return;
// 結果は、pos->state().sumから取り出すべし。
}
// 遡るnodeは一つだけ
// ひとつずつ遡りながらsumKPPがVALUE_NONEでないところまで探してそこからの差分を計算することは出来るが
// 現状、探索部では毎node、evaluate()を呼び出すから問題ない。
auto& dp = now->dirtyPiece;
// 移動させた駒は最大2つある。その数
int moved_piece_num = dp.dirty_num;
auto list0 = pos.eval_list()->piece_list_fb();
auto list1 = pos.eval_list()->piece_list_fw();
auto dirty = dp.pieceNo[0];
// 移動させた駒は王か?
if (dirty >= PIECE_NO_KING)
{
// 前のnodeの評価値からの増分を計算していく。
// (直接この変数に加算していく)
// この意味においてdiffという名前は少々不適切ではあるが。
EvalSum diff = prev->sum;
auto sq_bk = pos.king_square(BLACK);
auto sq_wk = pos.king_square(WHITE);
// ΣKKPは最初から全計算するしかないので初期化する。
diff.p[2] = kk[sq_bk][sq_wk];
diff.p[2][0] += now->materialValue * FV_SCALE;
// 後手玉の移動(片側分のKPPを丸ごと求める)
if (dirty == PIECE_NO_WKING)
{
const auto ppkppw = kpp[Inv(sq_wk)];
// ΣWKPP = 0
diff.p[1][0] = 0;
diff.p[1][1] = 0;
#if defined(USE_AVX2)
__m256i zero = _mm256_setzero_si256();
__m256i diffp1 = zero;
for (int i = 0; i < PIECE_NO_KING; ++i)
{
// KKPの値は、後手側から見た計算だとややこしいので、先手から見た計算でやる。
// 後手から見た場合、kkp[inv(sq_wk)][inv(sq_bk)][k1]になるが、これ次元下げで同じ値を書いているとは限らない。
diff.p[2] += kkp[sq_bk][sq_wk][list0[i]];
const int k1 = list1[i];
const auto* pkppw = ppkppw[k1];
int j = 0;
for (; j + 8 < i; j += 8)
{
// list1[j]から8要素ロードする
__m256i indexes = _mm256_load_si256(reinterpret_cast<const __m256i*>(&list1[j]));
// indexesのオフセットに従い、pkppwから8要素ギャザーする
__m256i w = _mm256_i32gather_epi32(reinterpret_cast<const int*>(pkppw), indexes, 4);
// 下位128ビットを16ビット整数→32ビット整数に変換する
__m256i wlo = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(w, 0));
// diffp1に足し合わせる
diffp1 = _mm256_add_epi32(diffp1, wlo);
// 上位128ビットを16ビット整数→32ビット整数に変換する
__m256i whi = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(w, 1));
// diffp1に足し合わせる
diffp1 = _mm256_add_epi32(diffp1, whi);
}
for (; j + 4 < i; j += 4) {
// list1[j]から4要素ロードする
__m128i indexes = _mm_load_si128(reinterpret_cast<const __m128i*>(&list1[j]));
// indexesのオフセットに従い、pkppwから4要素ギャザーする
__m128i w = _mm_i32gather_epi32(reinterpret_cast<const int*>(pkppw), indexes, 4);
// 16ビット整数→32ビット整数に変換する
__m256i wlo = _mm256_cvtepi16_epi32(w);
// diffp1に足し合わせる
diffp1 = _mm256_add_epi32(diffp1, wlo);
}
for (; j < i; ++j)
{
const int l1 = list1[j];
diff.p[1] += pkppw[l1];
}
}
// diffp1とdiffp1の上位128ビットと下位128ビットを独立して8バイトシフトしたものを足し合わせる
diffp1 = _mm256_add_epi32(diffp1, _mm256_srli_si256(diffp1, 8));
// diffp1の上位128ビットと下位128ビットを足しあわせてdiffp1_128に代入する
__m128i diffp1_128 = _mm_add_epi32(_mm256_extracti128_si256(diffp1, 0), _mm256_extracti128_si256(diffp1, 1));
// diffp1_128の下位64ビットをdiff.p[1]にストアする
std::array<int32_t, 2> diffp1_sum;
_mm_storel_epi64(reinterpret_cast<__m128i*>(&diffp1_sum), diffp1_128);
diff.p[1] += diffp1_sum;
#else
for (int i = 0; i < PIECE_NO_KING; ++i)
{
const int k1 = list1[i];
const auto* pkppw = ppkppw[k1];
for (int j = 0; j < i; ++j)
{
const int l1 = list1[j];
diff.p[1] += pkppw[l1];
}
// KKPのWK分。BKは移動していないから、BK側には影響ない。
// 後手から見たKKP。後手から見ているのでマイナス
diff.p[2][0] -= kkp[Inv(sq_wk)][Inv(sq_bk)][k1][0];
// 後手から見たKKP手番。後手から見るのでマイナスだが、手番は先手から見たスコアを格納するのでさらにマイナスになって、プラス。
diff.p[2][1] += kkp[Inv(sq_wk)][Inv(sq_bk)][k1][1];
}
#endif
// 動かした駒が2つ
if (moved_piece_num == 2)
{
// 瞬間的にeval_listの移動させた駒の番号を変更してしまう。
// こうすることで前nodeのpiece_listを持たなくて済む。
const int listIndex_cap = dp.pieceNo[1];
diff.p[0] += do_a_black(pos, dp.changed_piece[1].new_piece);
list0[listIndex_cap] = dp.changed_piece[1].old_piece.fb;
diff.p[0] -= do_a_black(pos, dp.changed_piece[1].old_piece);
list0[listIndex_cap] = dp.changed_piece[1].new_piece.fb;
}
}
else {
// 先手玉の移動
// さきほどの処理と同様。
const auto* ppkppb = kpp[sq_bk];
diff.p[0][0] = 0;
diff.p[0][1] = 0;
#if defined(USE_AVX2)
__m256i zero = _mm256_setzero_si256();
__m256i diffp0 = zero;
for (int i = 0; i < PIECE_NO_KING; ++i)
{
const int k0 = list0[i];
const auto* pkppb = ppkppb[k0];
// KKP
diff.p[2] += kkp[sq_bk][sq_wk][k0];
int j = 0;
for (; j + 8 < i; j += 8)
{
// list0[j]から8要素ロードする
__m256i indexes = _mm256_load_si256(reinterpret_cast<const __m256i*>(&list0[j]));
// indexesのオフセットに従い、pkppwから8要素ギャザーする
__m256i w = _mm256_i32gather_epi32(reinterpret_cast<const int*>(pkppb), indexes, 4);
// 下位128ビットを16ビット整数→32ビット整数に変換する
__m256i wlo = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(w, 0));
// diffp0に足し合わせる
diffp0 = _mm256_add_epi32(diffp0, wlo);
// 上位128ビットを16ビット整数→32ビット整数に変換する
__m256i whi = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(w, 1));
// diffp0に足し合わせる
diffp0 = _mm256_add_epi32(diffp0, whi);
}
for (; j + 4 < i; j += 4) {
// list0[j]から4要素ロードする
__m128i indexes = _mm_load_si128(reinterpret_cast<const __m128i*>(&list0[j]));
// indexesのオフセットに従い、pkppwから4要素ギャザーする
__m128i w = _mm_i32gather_epi32(reinterpret_cast<const int*>(pkppb), indexes, 4);
// 16ビット整数→32ビット整数に変換する
__m256i wlo = _mm256_cvtepi16_epi32(w);
// diffp0に足し合わせる
diffp0 = _mm256_add_epi32(diffp0, wlo);
}
for (; j < i; ++j)
{
const int l0 = list0[j];
diff.p[0] += pkppb[l0];
}
}
// diffp0とdiffp0の上位128ビットと下位128ビットを独立して8バイトシフトしたものを足し合わせる
diffp0 = _mm256_add_epi32(diffp0, _mm256_srli_si256(diffp0, 8));
// diffp0の上位128ビットと下位128ビットを足しあわせてdiffp0_128に代入する
__m128i diffp0_128 = _mm_add_epi32(_mm256_extracti128_si256(diffp0, 0), _mm256_extracti128_si256(diffp0, 1));
// diffp0_128の下位64ビットをdiff.p[1]にストアする
std::array<int32_t, 2> diffp0_sum;
_mm_storel_epi64(reinterpret_cast<__m128i*>(&diffp0_sum), diffp0_128);
diff.p[0] += diffp0_sum;
#else
for (int i = 0; i < PIECE_NO_KING; ++i)
{
const int k0 = list0[i];
const auto* pkppb = ppkppb[k0];
for (int j = 0; j < i; ++j) {
const int l0 = list0[j];
diff.p[0] += pkppb[l0];
}
diff.p[2] += kkp[sq_bk][sq_wk][k0];
}
#endif
if (moved_piece_num == 2) {
const int listIndex_cap = dp.pieceNo[1];
diff.p[1] += do_a_white(pos, dp.changed_piece[1].new_piece);
list1[listIndex_cap] = dp.changed_piece[1].old_piece.fw;
diff.p[1] -= do_a_white(pos, dp.changed_piece[1].old_piece);
list1[listIndex_cap] = dp.changed_piece[1].new_piece.fw;
}
}
// sumの計算が終わったのでpos.state()->sumに反映させておく。(これがこの関数の返し値に相当する。)
now->sum = diff;
}
else {
// 王以外の駒が移動したケース
// 今回の差分を計算して、そこに加算する。
const int listIndex = dp.pieceNo[0];
auto diff = do_a_pc(pos, dp.changed_piece[0].new_piece);
if (moved_piece_num == 1) {
// 動いた駒が1つ。
list0[listIndex] = dp.changed_piece[0].old_piece.fb;
list1[listIndex] = dp.changed_piece[0].old_piece.fw;
diff -= do_a_pc(pos, dp.changed_piece[0].old_piece);
}
else {
// 動いた駒が2つ。
auto sq_bk = pos.king_square(BLACK);
auto sq_wk = pos.king_square(WHITE);
diff += do_a_pc(pos, dp.changed_piece[1].new_piece);
diff.p[0] -= kpp[sq_bk][dp.changed_piece[0].new_piece.fb][dp.changed_piece[1].new_piece.fb];
diff.p[1] -= kpp[Inv(sq_wk)][dp.changed_piece[0].new_piece.fw][dp.changed_piece[1].new_piece.fw];
const PieceNo listIndex_cap = dp.pieceNo[1];
list0[listIndex_cap] = dp.changed_piece[1].old_piece.fb;
list1[listIndex_cap] = dp.changed_piece[1].old_piece.fw;
list0[listIndex] = dp.changed_piece[0].old_piece.fb;
list1[listIndex] = dp.changed_piece[0].old_piece.fw;
diff -= do_a_pc(pos, dp.changed_piece[0].old_piece);
diff -= do_a_pc(pos, dp.changed_piece[1].old_piece);
diff.p[0] += kpp[sq_bk][dp.changed_piece[0].old_piece.fb][dp.changed_piece[1].old_piece.fb];
diff.p[1] += kpp[Inv(sq_wk)][dp.changed_piece[0].old_piece.fw][dp.changed_piece[1].old_piece.fw];
list0[listIndex_cap] = dp.changed_piece[1].new_piece.fb;
list1[listIndex_cap] = dp.changed_piece[1].new_piece.fw;
}
list0[listIndex] = dp.changed_piece[0].new_piece.fb;
list1[listIndex] = dp.changed_piece[0].new_piece.fw;
// 前nodeからの駒割りの増分を加算。
diff.p[2][0] += (now->materialValue - prev->materialValue) * FV_SCALE;
now->sum = diff + prev->sum;
}
}
#else
// EvalListの組み換えを行なうときは差分計算をせずに(実装するのが大変なため)、毎回全計算を行なう。
void evaluateBody(const Position& pos)
{
compute_eval_impl(pos);
}
#endif // USE_EVAL_MAKE_LIST_FUNCTION
// 評価関数
Value evaluate(const Position& pos)
{
auto st = pos.state();
auto &sum = st->sum;
// すでに計算済(Null Moveなどで)であるなら、それを返す。
if (sum.evaluated())
return Value(sum.sum(pos.side_to_move()) / FV_SCALE);
#if defined(USE_GLOBAL_OPTIONS)
// GlobalOptionsでeval hashを用いない設定になっているなら
// eval hashへの照会をskipする。
if (!GlobalOptions.use_eval_hash)
{
evaluateBody(pos);
ASSERT_LV5(pos.state()->materialValue == Eval::material(pos));
return Value(sum.sum(pos.side_to_move()) / FV_SCALE);
}
#endif
#if defined ( USE_EVAL_HASH )
// 手番を消した局面hash key
const Key keyExcludeTurn = st->key() >> 1;
// evaluate hash tableにはあるかも。
// cout << "EvalSum " << hex << g_evalTable[keyExcludeTurn] << endl;
EvalSum entry = *g_evalTable[keyExcludeTurn]; // atomic にデータを取得する必要がある。
entry.decode();
if (entry.key == keyExcludeTurn)
{
// dbg_hit_on(true);
// あった!
sum = entry;
return Value(entry.sum(pos.side_to_move()) / FV_SCALE);
}
// dbg_hit_on(false);
#endif
// 評価関数本体を呼び出して求める。
evaluateBody(pos);
#if defined ( USE_EVAL_HASH )
// せっかく計算したのでevaluate hash tableに保存しておく。
sum.key = keyExcludeTurn;
sum.encode();
*g_evalTable[keyExcludeTurn] = sum;
#endif
ASSERT_LV5(pos.state()->materialValue == Eval::material(pos));
// 差分計算と非差分計算との計算結果が合致するかのテスト。(さすがに重いのでコメントアウトしておく)
// ASSERT_LV5(Value(st->sum.sum(pos.side_to_move()) / FV_SCALE) == compute_eval(pos));
#if 0
if (!(Value(st->sum.sum(pos.side_to_move()) / FV_SCALE) == compute_eval(pos)))
{
st->sum.p[0][0] = VALUE_NOT_EVALUATED;
evaluateBody(pos);
}
#endif
return Value(sum.sum(pos.side_to_move()) / FV_SCALE);
}
void evaluate_with_no_return(const Position& pos)
{
// 評価関数の実験のときには、どうせ差分計算を行わないので、
// ここでevaluate()を呼ぶのは無駄である。
#if !defined(USE_EVAL_MAKE_LIST_FUNCTION)
// まだ評価値が計算されていないなら
if (!pos.state()->sum.evaluated())
evaluate(pos);
#else
// EvalListの組み換えを行なっているときは通常の差分計算ルーチンが機能しないので
// 差分計算をするための何かをする必要がない。
#endif
}
#if defined(EVAL_LEARN)
// KKのKの値を出力する実験的コード
void kk_stat()
{
EvalLearningTools::init();
auto for_all_sq = [](std::function<void(Square)> func) {
for (int r = RANK_1; r <= RANK_9; ++r)
{
for (int f = FILE_1; f <= FILE_9; ++f)
{
auto sq = (File)f | (Rank)r;
func(sq);
}
cout << endl;
}
cout << endl;
};
// 先手から。
cout << "BK = " << endl;
for_all_sq([](Square sq) {
array<float, 2> sum_kk = { 0,0 };
array<float, 2> sum_kkp = { 0,0 };
array<float, 2> sum_kpp = { 0,0 };
for (auto sq2 = 0; sq2 < SQ_NB; ++sq2)
{
sum_kk += kk[sq][sq2];
for (auto p = 0; p < fe_end; ++p)
sum_kkp += kkp[sq][sq2][p];
}
for (auto p1 = 0; p1 < fe_end; ++p1)
for (auto p2 = 0; p2 < fe_end; ++p2)
sum_kpp += kpp[sq][p1][p2];
for (int i = 0; i < 2; ++i)
{
sum_kk[i] /= SQ_NB;
sum_kkp[i] = 38 * sum_kkp[i] / (fe_end * (int)SQ_NB);
sum_kpp[i] = (38 * 37 / 2) * sum_kpp[i] / (fe_end * (int)fe_end);
}
cout << "{" << (int)sum_kk[0] << ":" << (int)sum_kkp[0] << ":" << (int)sum_kpp[0] << ","
<< (int)sum_kk[1] << ":" << (int)sum_kkp[1] << ":" << (int)sum_kpp[1] << "} ";
});
// 後手から。
cout << "WK = " << endl;
for_all_sq([](Square sq) {
array<float, 2> sum_kk = { 0,0 };
array<float, 2> sum_kkp = { 0,0 };
array<float, 2> sum_kpp = { 0,0 };
for (Square sq2 = SQ_ZERO; sq2 < SQ_NB; ++sq2)
{
sum_kk += kk[sq2][sq];
for (BonaPiece p = BONA_PIECE_ZERO; p < fe_end; ++p)
sum_kkp += kkp[sq2][sq][p];
}
for (BonaPiece p1 = BONA_PIECE_ZERO; p1 < fe_end; ++p1)
for (BonaPiece p2 = BONA_PIECE_ZERO; p2 < fe_end; ++p2)
{
// kpp、invしたときも、手番は先手から見た値なので符号逆にしない
sum_kpp[0] -= kpp[Inv(sq)][inv_piece(p1)][inv_piece(p2)][0];
sum_kpp[1] += kpp[Inv(sq)][inv_piece(p1)][inv_piece(p2)][1];
}
for (int i = 0; i < 2; ++i)
{
sum_kk[i] /= SQ_NB;
sum_kkp[i] = 38 * sum_kkp[i] / (fe_end * (int)SQ_NB);
sum_kpp[i] = (38 * 37 / 2) * sum_kpp[i] / (fe_end * (int)fe_end);
}
cout << "{" << (int)sum_kk[0] << ":" << (int)sum_kkp[0] << ":" << (int)sum_kpp[0] << ","
<< (int)sum_kk[1] << ":" << (int)sum_kkp[1] << ":" << (int)sum_kpp[1] << "} ";
});
}
#endif
// 現在の局面の評価値の内訳を表示する。
void print_eval_stat(Position& pos)
{
cout << "--- EVAL STAT\n";
Square sq_bk = pos.king_square(BLACK);
Square sq_wk = pos.king_square(WHITE);
const auto* ppkppb = kpp[sq_bk];
const auto* ppkppw = kpp[Inv(sq_wk)];
auto& pos_ = *const_cast<Position*>(&pos);
#if !defined (USE_EVAL_MAKE_LIST_FUNCTION)
auto list_fb = pos_.eval_list()->piece_list_fb();
auto list_fw = pos_.eval_list()->piece_list_fw();
#else
// -----------------------------------
// USE_EVAL_MAKE_LIST_FUNCTIONが定義されているときは
// ここでeval_listをコピーして、組み替える。
// -----------------------------------
// バッファを確保してコピー
BonaPiece list_fb[40];
BonaPiece list_fw[40];
memcpy(list_fb, pos_.eval_list()->piece_list_fb(), sizeof(BonaPiece) * 40);
memcpy(list_fw, pos_.eval_list()->piece_list_fw(), sizeof(BonaPiece) * 40);
// ユーザーは、この関数でBonaPiece番号の自由な組み換えを行なうものとする。
make_list_function(pos, list_fb, list_fw);
EvalLearningTools::init();
for (PieceNo i = PIECE_NO_ZERO; i < PIECE_NO_NB; ++i)
{
// 組み替えて異なる番号になったものだけ出力。
auto fb = pos_.eval_list()->piece_list_fb()[i];
auto fw = pos_.eval_list()->piece_list_fw()[i];
auto fb_new = list_fb[i];
auto fw_new = list_fw[i];
// この変換後のfb,fwに対して、きちんと情報が設定されているかの確認。
if (fb != fb_new || fw != fw_new)
std::cout << "PieceNo = " << i << " , fb = " << (int)fb << ":" << fb << " , fw = " << (int)fw << ":" << fw
<< " , fb_new = " << (int)fb_new << " , fw_new = " << (int)fw_new
<< " , mir(fb_new) = " << (int)EvalLearningTools::mir_piece(fb_new)
<< " , mir(fw_new) = " << (int)EvalLearningTools::mir_piece(fw_new)
<< " , inv(fb_new) = " << (int)EvalLearningTools::inv_piece(fb_new)
<< " , inv(fw_new) = " << (int)EvalLearningTools::inv_piece(fw_new)
<< std::endl;
}
#endif
int i, j;
BonaPiece k0, k1, l0, l1;
// 38枚の駒を表示
for (i = 0; i < PIECE_NO_KING; ++i)
cout << int(list_fb[i]) << " = " << list_fb[i] << " , " << int(list_fw[i]) << " = " << list_fw[i] << endl;
// 評価値の合計
EvalSum sum;
#if defined(USE_SSE2)
// sum.p[0](BKPP)とsum.p[1](WKPP),sum.p[2](PP)をゼロクリア
sum.m[0] = _mm_setzero_si128();
sum.m[1] = _mm_setzero_si128();
#else
sum.p[0][0] = sum.p[0][1] = sum.p[1][0] = sum.p[1][1] = sum.p[2][0] = sum.p[2][1] = 0;
#endif
for (i = 0; i < PIECE_NO_KING; ++i)
{
k0 = list_fb[i];
k1 = list_fw[i];
const auto* pkppb = ppkppb[k0];
const auto* pkppw = ppkppw[k1];
for (j = 0; j < i; ++j)
{
l0 = list_fb[j];
l1 = list_fw[j];
sum.p[0][0] += pkppb[l0];
sum.p[1][0] += pkppw[l1];
// PP
sum.p[2] += pp[k0][l0];
cout << "BKPP : " << sq_bk << " " << k0 << " " << l0 << " = " << pkppb[l0] << endl;
cout << "WKPP : " << sq_wk << " " << k1 << " " << l1 << " = " << pkppw[l1] << endl;
cout << "PP : " << k0 << " " << l0 << " = " << pp[k0][l0][0] << " + " << pp[k0][l0][1] << endl;
}
sum.p[2] += kkp[sq_bk][sq_wk][k0];
cout << "KKP : " << sq_bk << " " << sq_wk << " " << k0 << " = " << kkp[sq_bk][sq_wk][k0][0] << " + " << kkp[sq_bk][sq_wk][k0][1] << endl;
}
cout << "Material = " << pos.state()->materialValue << endl;
cout << sum;
cout << "---" << endl;
// KKのKの値を出力する実験的コード
// kk_stat();
}
// とりあえずここに書いておく。あとで移動させるかも。
#if defined(EVAL_LEARN)
// regularize_kk()の下請け
void regularize_kk_impl()
{
EvalLearningTools::init();
typedef array<float, 2> kkt;
array<kkt, SQ_NB> kk_offset, kkp_offset, kpp_offset;
kkt zero = { 0, 0 };
kk_offset.fill(zero);
kkp_offset.fill(zero);
kpp_offset.fill(zero);
for (Square sq = SQ_ZERO; sq < SQ_NB; ++sq)
{
// sq2,p1,p2に依存しないkkの値を求める
kkt sum_kkp = zero;
kkt sum_kpp = zero;
for (Square sq2 = SQ_ZERO; sq2 < SQ_NB; ++sq2)
{
for (BonaPiece p = BONA_PIECE_ZERO; p < fe_end; ++p)
{
sum_kkp += kkp[sq][sq2][p];
//sum_kkp[0] -= kkp[Inv(sq2)][Inv(sq)][EvalLearningTools::inv_piece(p)][0];
//sum_kkp[1] += kkp[Inv(sq2)][Inv(sq)][EvalLearningTools::inv_piece(p)][1];
}
}
for (auto p1 = 0; p1 < fe_end; ++p1)
for (auto p2 = 0; p2 < fe_end; ++p2)
sum_kpp += kpp[sq][p1][p2];
for (int i = 0; i < 2; ++i)
{
// kkpとkppの平均を求める。この分をあとでそれぞれの要素から引く。
kkp_offset[sq][i] = sum_kkp[i] / (fe_end * (int)SQ_NB);
kpp_offset[sq][i] = sum_kpp[i] / (fe_end * (int)fe_end);
// kkpの計算のときにこれが38枚分、重なってくる
// kppの計算のときにこれが38*37/2枚分、重なってくる
kk_offset[sq][i] = 38 * kkp_offset[sq][i] + (38 * 37 / 2) * kpp_offset[sq][i];
}
}
// offsetの計算が終わったので先後にこれを適用してやる。
for (Square sq = SQ_ZERO; sq < SQ_NB; ++sq)
{
for (Square sq2 = SQ_ZERO; sq2 < SQ_NB; ++sq2)
{
kk[sq][sq2] += kk_offset[sq];
// ここむっちゃ計算ややこしいが、これで合っとる。
kk[Inv(sq2)][Inv(sq)][0] -= (int)kk_offset[sq][0];
kk[Inv(sq2)][Inv(sq)][1] += (int)kk_offset[sq][1];
for (auto p = 0; p < fe_end; ++p)
{
// ゼロの要素は書き換えない。(本来値がつくべきでないところを破壊すると困るため)
if (kkp[sq][sq2][p][0])
{
kkp[sq][sq2][p] -= kkp_offset[sq];
kkp[Inv(sq2)][Inv(sq)][inv_piece(BonaPiece(p))][0] += (int)kkp_offset[sq][0];
kkp[Inv(sq2)][Inv(sq)][inv_piece(BonaPiece(p))][1] -= (int)kkp_offset[sq][1];
}
}
}
for (auto p1 = 0; p1 < fe_end; ++p1)
for (auto p2 = 0; p2 < fe_end; ++p2)
// ゼロの要素は書き換えない またp1==0とかp2==0とかp1==p2のところは0になっているべき。
if (kpp[sq][p1][p2][0] && p1 != p2 && p1 && p2)
kpp[sq][p1][p2] -= kpp_offset[sq];
}
}
// KKを正規化する関数。元の評価関数と完全に等価にはならないので注意。
// kkp,kppの値をなるべくゼロに近づけることで、学習中に出現しなかった特徴因子の値(ゼロになっている)が
// 妥当であることを保証しようという考え。
void regularize_kk()
{
kk_stat();
regularize_kk_impl();
kk_stat();
}
#endif
// 評価関数のそれぞれのパラメーターに対して関数fを適用してくれるoperator。
// パラメーターの分析などに用いる。
void foreach_eval_param(std::function<void(s32, s32)>f, int type)
{
// PP
if (type == -1 || type == 0)
{
for (u64 i = 0; i < (u64)fe_end * (u64)fe_end; ++i)
{
auto v = ((ValuePp*)pp)[i];
f(v[0], v[1]);
//if (v[0] == 0) cout << "v[0]==0" << (Square)(i / SQ_NB) << (Square)(i % SQ_NB) << endl;
//if (v[1] == 0) cout << "v[1]==0" << (Square)(i / SQ_NB) << (Square)(i % SQ_NB) << endl;
}
}
// KKP
if (type == -1 || type == 1)
{
for (u64 i = 0; i < (u64)SQ_NB * (u64)SQ_NB * (u64)fe_end; ++i)
{
auto v = ((ValueKkp*)kkp)[i];
f(v[0], v[1]);
}
}
// KPP
if (type == -1 || type == 2)
{
for (u64 i = 0; i < (u64)SQ_NB * (u64)fe_end * (u64)fe_end; ++i)
{
auto v = ((ValueKpp*)kpp)[i];
f(v, 0); /* 手番なしなのでダミーで0を渡しておく */
}
}
}
}
#endif // defined (EVAL_KPP_PPT)
| [
"yaneurao@gmail.com"
] | yaneurao@gmail.com |
dfdab7ead736a163258b78fd64b546a54d1a4f2c | e33ec438fb08f73c437894dd5c896d4632f27f55 | /src/Coroutine.cpp | d2e836863eea43bd43c0ffea98e9f8f6309920a4 | [] | no_license | pswarfound/ff_test | 5d769984dfd6f0971816ba2e05288e712a25f95a | 3014aa6bba21db06ee051b498d5e36fcf46cb92b | refs/heads/master | 2020-04-18T22:55:20.784724 | 2019-02-01T10:21:29 | 2019-02-01T10:21:29 | 167,808,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,327 | cpp | #include <map>
#include "Coroutine.hpp"
#include "libaco/aco.h"
using std::pair;
using std::map;
#define MARK(...) printf("%s %d]", __func__, __LINE__);printf(__VA_ARGS__);printf("\n");
Coroutine::Coroutine(void *main_hwnd, void *sstk)
: m_main_hwnd(main_hwnd), m_sstk(sstk)
{
}
Coroutine::~Coroutine()
{
if (m_hwnd) {
aco_destroy((aco_t *)m_hwnd);
m_hwnd = NULL;
}
}
void Coroutine::routine_proxy(void)
{
Coroutine *cr = (Coroutine *)aco_get_arg();
routine_t fp = (routine_t)cr->m_fp;
fp(cr->m_arg);
cr->m_is_stop = true;
aco_exit();
}
/*
aco_t* aco_create(
aco_t* main_co,
aco_share_stack_t* share_stack,
size_t save_stack_sz,
aco_cofuncp_t fp, void* arg
);
*/
bool Coroutine::create(routine_t routine, void *arg, size_t stack_size)
{
if (m_hwnd) {
return false;
}
m_fp = (void*)routine;
m_arg = arg;
m_hwnd = aco_create((aco_t*)m_main_hwnd, (aco_share_stack_t*)m_sstk, stack_size, routine_proxy, (void*)this);
return m_hwnd == NULL?false:true;
}
void Coroutine::resume()
{
aco_resume((aco_t*)m_hwnd);
}
void Coroutine::yield()
{
aco_yield();
}
bool Coroutine::is_stop()
{
return m_is_stop;
}
template <typename T>
CoroutineFactory<T>::CoroutineFactory(size_t shared_stack_size)
{
aco_thread_init(NULL);
m_hwnd = aco_create(NULL, NULL, 0, NULL, NULL);
m_sstk = aco_share_stack_new(shared_stack_size);
m_map = new std::map<T, Coroutine*>;
}
template <typename T>
CoroutineFactory<T>::~CoroutineFactory()
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
typename map<T, Coroutine*>::iterator iter = cr_map->begin();
while (iter != cr_map->end()) {
delete iter->second;
iter++;
}
aco_share_stack_destroy((aco_share_stack_t*)m_sstk);
aco_destroy((aco_t*)m_hwnd);
cr_map->clear();
delete cr_map;
}
template <typename T>
bool CoroutineFactory<T>::cr_create(routine_t routine, void *arg, size_t stack_size, T &key)
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
if (cr_map->find(key) != cr_map->end()) {
return false;
}
Coroutine *cr = new Coroutine(m_hwnd, m_sstk);
cr->create(routine, arg, stack_size);
bool ret = cr_map->insert(pair<T, Coroutine*>(key, cr)).second;
if (!ret) {
delete cr;
return false;
}
return true;
}
template <typename T>
bool CoroutineFactory<T>::cr_yield(const T&key)
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
typename map<T, Coroutine*>::iterator iter = cr_map->find(key);
if (iter == cr_map->end()) {
return false;
}
iter->second->yield();
return true;
}
template <typename T>
bool CoroutineFactory<T>::cr_resume(const T&key)
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
typename map<T, Coroutine*>::iterator iter = cr_map->find(key);
if (iter == cr_map->end()) {
return false;
}
iter->second->resume();
return true;
}
template <typename T>
bool CoroutineFactory<T>::cr_is_quit(const T &key)
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
typename map<T, Coroutine*>::iterator iter = cr_map->find(key);
if (iter == cr_map->end()) {
return false;
}
return iter->second->is_stop();
}
template <typename T>
bool CoroutineFactory<T>::cr_get(const T &key, Coroutine **cr)
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
typename map<T, Coroutine*>::iterator iter = cr_map->find(key);
if (iter == cr_map->end()) {
return false;
}
*cr = iter->second;
return true;
}
template <typename T>
bool CoroutineFactory<T>::cr_remove(const T &key)
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
typename map<T, Coroutine*>::iterator iter = cr_map->find(key);
if (iter == cr_map->end()) {
return false;
}
delete iter->second;
cr_map->erase(key);
return true;
}
template <typename T>
bool CoroutineFactory<T>::empty(void)
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
return cr_map->empty();
}
template <typename T>
size_t CoroutineFactory<T>::size(void)
{
map<T, Coroutine*> *cr_map = (map<T, Coroutine*>*)m_map;
return cr_map->size();
}
template class CoroutineFactory<int>;
| [
"lin_dy_1201@163.com"
] | lin_dy_1201@163.com |
5bb067bc1e9440df6fdcf49c8415974993948397 | 4ff0ed795d0a8dac894e393c645447b297cff12d | /F6D4230v1-1.00.03-GPL/GPL_src_code/uboot/ToolChain/surfmilo/cross-dev/mips_4KC/usr/include/ncurses/cursesp.h | 88ab47720218307eb203e492f929d977e8f9c878 | [] | no_license | OEM-GPL-Releases/belkin_f6d4230-4_v1000 | e0a6c9d0fa8c837138380aab92cd3c28dc8e53d8 | e7a259a28a6c0e45280548f9e3d7d8726d441a08 | HEAD | 2016-08-12T15:38:12.884747 | 2015-10-26T08:07:40 | 2015-10-26T08:07:40 | 44,952,957 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,926 | h | // * This makes emacs happy -*-Mode: C++;-*-
/****************************************************************************
* Copyright (c) 1998,1999,2000,2001 Free Software Foundation, Inc. *
* *
* 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/****************************************************************************
* Author: Juergen Pfeifer <juergen.pfeifer@gmx.net> 1997 *
****************************************************************************/
#ifndef NCURSES_CURSESP_H_incl
#define NCURSES_CURSESP_H_incl 1
// $Id: cursesp.h,v 1.15 2001/07/14 20:56:18 juergen Exp $
#include <ncurses/cursesw.h>
extern "C" {
# include <ncurses/panel.h>
}
class NCURSES_IMPEXP NCursesPanel : public NCursesWindow {
protected:
PANEL *p;
static NCursesPanel *dummy;
private:
// This structure is used for the panel's user data field to link the
// PANEL* to the C++ object and to provide extra space for a user pointer.
typedef struct {
void* m_user; // the pointer for the user's data
const NCursesPanel* m_back; // backward pointer to C++ object
const PANEL* m_owner; // the panel itself
} UserHook;
void init(); // Initialize the panel object
protected:
void set_user(void *user) {
UserHook* uptr = (UserHook*)::panel_userptr (p);
assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==p);
uptr->m_user = user;
}
// Set the user pointer of the panel.
void *get_user() {
UserHook* uptr = (UserHook*)::panel_userptr (p);
assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==p);
return uptr->m_user;
}
void OnError (int err) const THROWS((NCursesPanelException)) {
if (err==ERR)
THROW(new NCursesPanelException (this, err));
}
// If err is equal to the curses error indicator ERR, an error handler
// is called.
// Get a keystroke. Default implementation calls getch()
virtual int getKey(void);
public:
NCursesPanel(int lines,
int cols,
int begin_y = 0,
int begin_x = 0)
: NCursesWindow(lines,cols,begin_y,begin_x) {
init();
}
// Create a panel with this size starting at the requested position.
NCursesPanel() : NCursesWindow(::stdscr) { init(); }
// This constructor creates the default Panel associated with the
// ::stdscr window
virtual ~NCursesPanel();
// basic manipulation
inline void hide() {
OnError (::hide_panel(p));
}
// Hide the panel. It stays in the stack but becomes invisible.
inline void show() {
OnError (::show_panel(p));
}
// Show the panel, i.e. make it visible.
inline void top() {
OnError (::top_panel(p));
}
// Make this panel the top panel in the stack.
inline void bottom() {
OnError (::bottom_panel(p));
}
// Make this panel the bottom panel in the stack.
// N.B.: The panel associated with ::stdscr is always on the bottom. So
// actually bottom() makes the panel the first above ::stdscr.
virtual int mvwin(int y, int x) {
OnError(::move_panel(p, y, x));
return OK;
}
inline bool hidden() const {
return (::panel_hidden (p) ? TRUE : FALSE);
}
// Return TRUE if the panel is hidden, FALSE otherwise.
/* The functions panel_above() and panel_below() are not reflected in
the NCursesPanel class. The reason for this is, that we cannot
assume that a panel retrieved by those operations is one wrapped
by a C++ class. Although this situation might be handled, we also
need a reverse mapping from PANEL to NCursesPanel which needs some
redesign of the low level stuff. At the moment, we define them in the
interface but they will always produce an error. */
inline NCursesPanel& above() const {
OnError(ERR);
return *dummy;
}
inline NCursesPanel& below() const {
OnError(ERR);
return *dummy;
}
// Those two are rewrites of the corresponding virtual members of
// NCursesWindow
virtual int refresh();
// Propagate all panel changes to the virtual screen and update the
// physical screen.
virtual int noutrefresh();
// Propagate all panel changes to the virtual screen.
static void redraw();
// Redraw all panels.
// decorations
virtual void frame(const char* title=NULL,
const char* btitle=NULL);
// Put a frame around the panel and put the title centered in the top line
// and btitle in the bottom line.
virtual void boldframe(const char* title=NULL,
const char* btitle=NULL);
// Same as frame(), but use highlighted attributes.
virtual void label(const char* topLabel,
const char* bottomLabel);
// Put the title centered in the top line and btitle in the bottom line.
virtual void centertext(int row,const char* label);
// Put the label text centered in the specified row.
};
/* We use templates to provide a typesafe mechanism to associate
* user data with a panel. A NCursesUserPanel<T> is a panel
* associated with some user data of type T.
*/
template<class T> class NCursesUserPanel : public NCursesPanel
{
public:
NCursesUserPanel (int lines,
int cols,
int begin_y = 0,
int begin_x = 0,
const T* p_UserData = (T*)0)
: NCursesPanel (lines, cols, begin_y, begin_x) {
if (p)
set_user ((void *)p_UserData);
};
// This creates an user panel of the requested size with associated
// user data pointed to by p_UserData.
NCursesUserPanel(const T* p_UserData = (T*)0) : NCursesPanel() {
if (p)
set_user((void *)p_UserData);
};
// This creates an user panel associated with the ::stdscr and user data
// pointed to by p_UserData.
virtual ~NCursesUserPanel() {};
T* UserData (void) const {
return (T*)get_user ();
};
// Retrieve the user data associated with the panel.
virtual void setUserData (const T* p_UserData) {
if (p)
set_user ((void *)p_UserData);
}
// Associate the user panel with the user data pointed to by p_UserData.
};
#endif // NCURSES_CURSESP_H_incl
| [
"ultravioletnanokitty@gmail.com"
] | ultravioletnanokitty@gmail.com |
354f02f219507bce3a5827a19b23296a990d2a21 | 0dd9f9321d604cb5d3d9cef8868a19519e644ff5 | /Recover Binary Search Tree.cpp | bb4fa59865b8b41bea11e4e3b61f5517143ad9c9 | [] | no_license | JimberXin/Leetcode | a7dd0e5e60c4713c1e51193b84be1ad708dce602 | bf8e81ca7f82dc0d2da76fabc5975d0ad8506397 | refs/heads/master | 2021-01-18T18:17:48.284467 | 2015-01-10T14:28:18 | 2015-01-10T14:28:18 | 21,634,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | cpp | #include<iostream>
using namespace std;
/*
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
class Solution {
public:
TreeNode* pre, *big,*small;
void InorderTraverse(TreeNode* root) {
if(root == NULL)
return;
InorderTraverse(root ->left);
//********pre root value is bigger, mark s1 and s2 to be swapped
if(pre != NULL && pre->val > root->val) {
if(big == NULL)
{
big = pre;
small = root;
}
else
small = root;
}
pre = root;
InorderTraverse(root->right);
}
void recoverTree(TreeNode *root) {
if(root == NULL)
return;
pre = big = small = NULL;
InorderTraverse(root);
swap(big->val, small->val);
}
TreeNode* createTree() {
int data;
TreeNode* root;
cin >> data;
if( data == -1)
root = NULL;
else
{
root = (TreeNode*)malloc(sizeof(TreeNode));
root -> val = data;
root -> left = createTree();
root -> right = createTree();
}
return root;
}
};
int main() {
Solution s;
TreeNode* root = s.createTree();
s.recoverTree(root);
getchar();
return 0;
}
| [
"jimberxin@gmail.com"
] | jimberxin@gmail.com |
e76a8dbd2913b765c4730c4c98d52c551d16ec45 | cd60c72973024a80f497ead356f8036934b75613 | /miniPIC-crossroads/test/test_single_particle.cpp | 2db4e9f76eb04fef37e8d0ca0b93cdf30e0d18e1 | [] | no_license | npe9/crossroads | 4636357072706c80fba88e12cd9ac1d1d9feb84d | 9e972c4a6d8045b7e4d8bfdca36b3c5366750cc4 | refs/heads/master | 2020-07-03T18:37:32.386705 | 2019-08-12T20:46:56 | 2019-08-12T20:46:56 | 202,006,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,233 | cpp | /**********************************************************************************
Mini-PIC
Copyright (c) 2015, Sandia National Laboratories
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
For questions, comments or contributions contact
Matt Bettencourt, mbetten@sandia.gov
*******************************************************************************/
/*
* test_single_particle.cpp
*
* Created on: Oct 6, 2014
* Author: mbetten
*/
#include <mpi.h>
#include "Kokkos_Core.hpp"
#include <impl/Kokkos_Timer.hpp>
#include "Teuchos_GlobalMPISession.hpp"
#include "types.hpp"
#include "mesh.hpp"
#include "particle_list.hpp"
#include "particle_move.hpp"
#include "particle_fill.hpp"
#include "base_functor.hpp"
#include "data_warehouse.hpp"
#include "test_utils.hpp"
#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_UnitTestHarness.hpp"
#include <string>
Teuchos::RCP<Teuchos::Comm<int> > comm;
std::string mesh_file;
int main(int argc, char *argv[]) {
Teuchos::GlobalMPISession mpiSession(&argc, &argv);
comm = Teuchos::RCP<Teuchos::Comm<int> > (new Teuchos::MpiComm<int>(MPI_COMM_WORLD) );
int result;
{
Kokkos::initialize(argc, argv);
mesh_file = std::string("regular.txt");
result = Teuchos::UnitTestRepository::runUnitTestsFromMain(argc, argv);
Kokkos::finalize();
}
{
Kokkos::initialize(argc, argv);
mesh_file = std::string("mapped.txt");
result = Teuchos::UnitTestRepository::runUnitTestsFromMain(argc, argv);
Kokkos::finalize();
}
return result;
}
TEUCHOS_UNIT_TEST( Int, SingleParticle_SingleStep ) {
DataWarehouse data;
Particle p;
CreateOneParticle(data, mesh_file, p, comm);
VECTOR initial = p.x;
VECTOR v = p.v;
ParticleMove mover(data);
FLOAT dt = 0.1;
mover.set_force_scale(0.0);
Kokkos::fence();
mover.move(dt);
Kokkos::fence();
for (int i=0;i<3; ++i)
p.x[i] = initial[i]+dt*v[i];
if ( data.particles().num_particles()) {
CompareOnDevice comp(p, data.particles(), 0, 1e-12);
bool result = comp.compare();
TEST_EQUALITY_CONST(true, result);
}
}
#if 1
TEUCHOS_UNIT_TEST( Int, SingleParticle_MultiStep ) {
DataWarehouse data;
Particle p;
CreateOneParticle(data, mesh_file, p, comm);
VECTOR initial = p.x;
VECTOR v = p.v;
ParticleMove mover(data);
FLOAT dt = 0.1;
mover.set_force_scale(0.0);
int nsteps = 10;
for (int i=0; i<nsteps; ++i)
mover.move(dt);
for (int i=0;i<3; ++i)
p.x[i] = initial[i]+dt*nsteps*v[i];
if ( data.particles().num_particles()) {
CompareOnDevice comp(p, data.particles(), 0, 1e-12);
bool result = comp.compare();
TEST_EQUALITY_CONST(true, result);
}
}
TEUCHOS_UNIT_TEST( Int, SingleParticle_MultiStep_Reflection ) {
DataWarehouse data;
Particle p;
CreateOneParticle(data, mesh_file, p, comm);
VECTOR initial = p.x;
VECTOR v = p.v;
ParticleMove mover(data);
FLOAT dt = 0.4;
mover.set_force_scale(0.0);
int nsteps = 10;
for (int i=0; i<nsteps; ++i)
mover.move(dt);
for (int idim=0;idim<3; ++idim) {
p.x[idim] = initial[idim]+dt*nsteps*v[idim];
if ( p.x[idim] > 1)
p.x[idim] = 1 - (p.x[idim] - 1);
}
if ( data.particles().num_particles()) {
CompareOnDevice comp(p, data.particles(), 0, 1e-12);
bool result = comp.compare();
TEST_EQUALITY_CONST(true, result);
}
}
TEUCHOS_UNIT_TEST( Int, SingleParticle_MultiStep_Periodic ) {
DataWarehouse data;
Particle p;
CreateOneParticle(data, mesh_file, p, comm, true);
VECTOR initial = p.x;
VECTOR v = p.v;
ParticleMove mover(data);
FLOAT dt = 0.4;
mover.set_force_scale(0.0);
int nsteps = 10;
for (int i=0; i<nsteps; ++i)
mover.move(dt);
for (int idim=0;idim<3; ++idim) {
p.x[idim] = initial[idim]+dt*nsteps*v[idim];
if ( p.x[idim] > 1)
p.x[idim] -= 2;
}
if ( data.particles().num_particles()) {
CompareOnDevice comp(p, data.particles(), 0, 1e-12);
bool result = comp.compare();
TEST_EQUALITY_CONST(true, result);
}
}
//}
#endif
| [
"nevans@sandia.gov"
] | nevans@sandia.gov |
b52c1b5919057536793ca2c70d0de2588c6f6400 | 01a42b69633daf62a2eb3bb70c5b1b6e2639aa5f | /SCUM_UI_ComboBoxWrapper_classes.hpp | 217de009fe324e6ec4a7c760ddd8bf9afa4c9d8f | [] | no_license | Kehczar/scum_sdk | 45db80e46dac736cc7370912ed671fa77fcb95cf | 8d1770b44321a9d0b277e4029551f39b11f15111 | refs/heads/master | 2022-07-25T10:06:20.892750 | 2020-05-21T11:45:36 | 2020-05-21T11:45:36 | 265,826,541 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,932 | hpp | #pragma once
// Scum 3.79.22573 (UE 4.24)
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace Classes
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass UI_ComboBoxWrapper.UI_ComboBoxWrapper_C
// 0x0011 (0x0241 - 0x0230)
class UUI_ComboBoxWrapper_C : public UUserWidget
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0230(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
class UComboBoxString* ComboBox; // 0x0238(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
bool Open; // 0x0240(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass UI_ComboBoxWrapper.UI_ComboBoxWrapper_C");
return ptr;
}
struct FEventReply STATIC_OnPreviewMouseButtonDown(struct FGeometry* MyGeometry, struct FPointerEvent* MouseEvent);
void STATIC_OnMouseLeave(struct FPointerEvent* MouseEvent);
void STATIC_ExecuteUbergraph_UI_ComboBoxWrapper(int* EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"65712402+Kehczar@users.noreply.github.com"
] | 65712402+Kehczar@users.noreply.github.com |
39f47861934f3759d7d5b431e4fa197a2dcba439 | c591b56220405b715c1aaa08692023fca61f22d4 | /Disha/Milestone-2/Level 1/Question-11.cpp | 8073c84c5d7291aeb6a53f8b685a8a7dbec6a153 | [] | no_license | Girl-Code-It/Beginner-CPP-Submissions | ea99a2bcf8377beecba811d813dafc2593ea0ad9 | f6c80a2e08e2fe46b2af1164189272019759935b | refs/heads/master | 2022-07-24T22:37:18.878256 | 2021-11-16T04:43:08 | 2021-11-16T04:43:08 | 263,825,293 | 37 | 105 | null | 2023-06-05T09:16:10 | 2020-05-14T05:39:40 | C++ | UTF-8 | C++ | false | false | 411 | cpp | //Write a program to check whether a entered character is lowercase ( a to z ) or uppercase ( A to Z )
using namespace std;
#include<iostream>
int main()
{
char ch;
cout<<"\n Enter an alphabet : ";
cin>>ch;
if(ch>=97&&ch<=122){
cout<<"\n Entered character is lowercase \n";
}
else if(ch>=67&&ch<=90){
cout<<"\n Entered character is uppercase \n";
}
return 0;
}
| [
"disha2.bhardaj@gmail.com"
] | disha2.bhardaj@gmail.com |
30373afb96e90f2153be5aee0c558e752f6f182c | 66b7d32704550b0c65d43955c942c515ebaa11b0 | /inc/verline.h | 5104f0b6435b3987196b394284eff7b9e8845a62 | [] | no_license | CritStab/MKE | 6ba538662e2ab645aab6aab7ba636ceb4b772bef | f598fe20c27209729d568f39ac51e1b4b13cbd9d | refs/heads/master | 2021-06-11T01:23:22.170477 | 2016-12-22T11:02:02 | 2016-12-22T11:02:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | h | #include "MKE04Z1284.h" // Device header
#include "shape.h"
#include "colors16bit.h"
#ifndef VERLINE_H
#define VERLINE_H
class Verline : public Shape
{
private:
uint16_t x, y, color, length;
uint8_t thick;
public:
Verline (uint16_t x_, uint16_t y_, uint16_t color_, uint16_t length_, uint8_t thick_);
void draw () const override;
};
#endif
| [
"creator83@yandex.ru"
] | creator83@yandex.ru |
296214848d66dd32fc452c8f3586e28f9501dadd | 1c711f642328e5195cbbb61760a83f4a8ff6977a | /assets/src/leetcode/problemset/1189.cpp | 8fb34719de9a1b16c5677a74a4555334f494d3e3 | [] | no_license | liuxueyang/liuxueyang.github.io | 29d85b989e5938e964b70c9616a418e13003212e | 86e10cb6137d930c2ac81f2ae20318eb1354f2b5 | refs/heads/master | 2023-03-07T13:06:17.366563 | 2023-03-01T14:41:41 | 2023-03-01T14:41:41 | 17,851,538 | 2 | 0 | null | 2023-01-31T04:00:56 | 2014-03-18T02:46:21 | C++ | UTF-8 | C++ | false | false | 573 | cpp | #include <string>
using namespace std;
const int INF = 0x3f3f3f3f;
class Solution {
public:
int maxNumberOfBalloons(string text) {
string s = "balloon";
int st[26] {}, sa[26] {}, res = INF;
for (int i = 0; i < s.size(); i++) {
st[s[i] - 'a']++;
}
for (int i = 0; i < text.size(); i++) {
sa[text[i] - 'a']++;
}
for (int i = 0; i < s.size(); i++) {
int k = s[i] - 'a';
int tmp = sa[k] / st[k];
res = min(res, tmp);
}
return res;
}
}; | [
"liuxueyang457@gmail.com"
] | liuxueyang457@gmail.com |
e38617a7a5b09748c505baca82bdded8db75cbee | 936dd249682d239699aa0d4b1457c82412888866 | /include/posix_obj.h | d332c152dcd825be8f9fa5491a27283ddb812618 | [] | no_license | lineCode/ipclib | 1e11984ff7c7498769efbb3e835ba9d7e335c201 | 2e8a678c4c8ceac564fab99a8b5a73ef730ebcd7 | refs/heads/master | 2021-06-27T01:40:08.637899 | 2017-09-09T11:37:24 | 2017-09-09T11:37:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | h | #ifndef _POSIX_OBJ_H_
#define _POSIX_OBJ_H_
#include <string>
#include <sys/stat.h>
#include "result.h"
namespace ipclib {
class Posix_obj {
protected:
static const mode_t DEFAULT_PERMISSION = 0644;
Result init_err;
std::string name;
public:
Posix_obj(const std::string theName);
Result get_initresult() const { return init_err; }
std::string get_posixname() const { return name; }
std::string get_name() const { return name.substr(1, std::string::npos); }
};
}
#endif
| [
"gen.iorio92@gmail.com"
] | gen.iorio92@gmail.com |
97b6ff011b0807e87affa5bc23e86f8d11f0fada | df83d8921c12ca0f5bd9f7a40551b120b1c9e74d | /MS4/ms4_VehicleTester.cpp | ce753c098e9a939de006747e1f331704e4bc0d2f | [] | no_license | yparam98/OOP244-NEW | ef034fe82199426d4d23b5941a6458ee68d6873f | 12c8ae0b9325db8ac262e529749805ba2ad98679 | refs/heads/master | 2022-11-28T23:11:35.980945 | 2020-08-16T03:45:35 | 2020-08-16T03:45:35 | 265,616,215 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,286 | cpp | /* ------------------------------------------------------
Final Project Milestone 4
Module: ReadWritable
Filename: ms4_VehicleTester.cpp
Version 1.0
Author Fardad Soleimanloo
Revision History
-----------------------------------------------------------
Date Reason
2020/7/4 Preliminary release
-----------------------------------------------------------*/
#include <iostream>
#include "Vehicle.h"
using namespace std;
using namespace sdds;
void TestValidations();
void TestOperatorEqualEqual(const Vehicle& A, const Vehicle& B);
void TestIO(Vehicle& V);
int main() {
Vehicle V;
Vehicle C("abcd", "C car");
// you can comment each test to develop your Vehicle step by step:
TestIO(V);
TestOperatorEqualEqual(C, V);
TestValidations();
return 0;
}
void TestIO(Vehicle& V) {
cout << "Invalid Vehicle Printing:" << endl;
cout << V << endl;
cout << "Reading vehicle from console: " << endl;
cout << "Enter:" << endl << "abc<ENTER>" << endl << "abc<ENTER>" << endl;
V.setCsv(false);
cin >> V;
cout << "Printing a Vehicle that is not parked:" << endl;
cout << V << endl;
V.setParkingSpot(12);
cout << "Printing a Vehicle that is parked in the spot number 12:" << endl;
cout << V << endl;
cout << "Reading and Writing Comma Separated values: " << endl;
cout << "Enter: " << endl;
cout << "123,abcd,abcd,<ENTER>" << endl;
V.setCsv(true);
cin >> V;
cin.ignore(1000, '\n');
cout << V << endl;
}
void TestValidations() {
Vehicle* V;
cout << "Construction validations:" << endl;
V = new Vehicle(nullptr, "abc");
cout << *V;
delete V;
V = new Vehicle("123456789", "abc");
cout << *V;
delete V;
V = new Vehicle("", "abc");
cout << *V;
delete V;
V = new Vehicle("ABC", nullptr);
cout << *V;
delete V;
V = new Vehicle("ABC", "");
cout << *V;
delete V;
V = new Vehicle("ABC", "A");
cout << *V;
cout << "Input validations: " << endl;
cout << "Enter: " << endl << "123456789<ENTER>" << endl << "abc<ENTER>" << endl << "abc<ENTER>" << endl;
cin >> *V;
cout << *V << endl;
cout << "Enter: " << endl << "abc<ENTER>" << endl << "a<ENTER>" << endl << "ab<ENTER>" << endl;
cin >> *V;
cout << *V << endl;
cout << "Testing setParkingSpot validation: " << endl << "Valid setting: " <<endl;
V->setParkingSpot(20);
cout << *V << endl;
cout << "invalid setting: " << endl;
V->setParkingSpot(-1);
cout << *V << endl;
delete V;
}
void TestOperatorEqualEqual(const Vehicle& A, const Vehicle& B) {
cout << "opeator== (cstring):" << endl;
if (A == "Abcd") {
cout << "operator== with cstring works" << endl;
}
else {
cout << "Bad Opertor==, fix your code" << endl;
}
cout << "opeator== (Vehicle):" << endl;
if (A == B) {
cout << "operator== with Vehicle works" << endl;
}
else {
cout << "Bad Opertor==, fix your code" << endl;
}
}
/*
Ouput:
Invalid Vehicle Printing:
Invalid Vehicle Object
Reading vehicle from console:
Enter:
abc<ENTER>
abc<ENTER>
Enter Licence Plate Number: abc
Enter Make and Model: abc
Printing a Vehicle that is not parked:
Parking Spot Number: N/A
Licence Plate: ABC
Make and Model: abc
Printing a Vehicle that is parked in the spot number 12:
Parking Spot Number: 12
Licence Plate: ABC
Make and Model: abc
Reading and Writing Comma Separated values:
Enter:
123,abcd,abcd,<ENTER>
123,abcd,abcd,
123,ABCD,abcd,
opeator== (cstring):
operator== with cstring works
opeator== (Vehicle):
operator== with Vehicle works
Construction validations:
Invalid Vehicle Object
Invalid Vehicle Object
Invalid Vehicle Object
Invalid Vehicle Object
Invalid Vehicle Object
Invalid Vehicle Object
Input validations:
Enter:
123456789<ENTER>
abc<ENTER>
abc<ENTER>
Enter Licence Plate Number: 123456789
Invalid Licence Plate, try again: abc
Enter Make and Model: abc
Parking Spot Number: N/A
Licence Plate: ABC
Make and Model: abc
Enter:
abc<ENTER>
a<ENTER>
ab<ENTER>
Enter Licence Plate Number: abc
Enter Make and Model: a
Invalid Make and model, try again: ab
Parking Spot Number: N/A
Licence Plate: ABC
Make and Model: ab
Testing setParkingSpot validation:
Valid setting:
Parking Spot Number: 20
Licence Plate: ABC
Make and Model: ab
invalid setting:
Invalid Vehicle Object
*/ | [
"yathavanparamesh1998@gmail.com"
] | yathavanparamesh1998@gmail.com |
46f059876348cb1b308c455d882105ce06d141a1 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /sgw/src/model/ValidateExpressSyncConfigResult.cc | f17d555febf2ca3d3b02d1753206c552b59b658b | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 2,122 | cc | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/sgw/model/ValidateExpressSyncConfigResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Sgw;
using namespace AlibabaCloud::Sgw::Model;
ValidateExpressSyncConfigResult::ValidateExpressSyncConfigResult() :
ServiceResult()
{}
ValidateExpressSyncConfigResult::ValidateExpressSyncConfigResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ValidateExpressSyncConfigResult::~ValidateExpressSyncConfigResult()
{}
void ValidateExpressSyncConfigResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["IsValid"].isNull())
isValid_ = value["IsValid"].asString() == "true";
if(!value["ValidateMessage"].isNull())
validateMessage_ = value["ValidateMessage"].asString();
}
std::string ValidateExpressSyncConfigResult::getMessage()const
{
return message_;
}
std::string ValidateExpressSyncConfigResult::getValidateMessage()const
{
return validateMessage_;
}
std::string ValidateExpressSyncConfigResult::getCode()const
{
return code_;
}
bool ValidateExpressSyncConfigResult::getSuccess()const
{
return success_;
}
bool ValidateExpressSyncConfigResult::getIsValid()const
{
return isValid_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
c522eff2fa4540e7cfa20174f13f9e3524ea447b | a181a8e4c629a5337e19a6cd1a59007464935bbb | /src/hr/wx_authorise.hpp | 05bda4def0c78d3555a5cd78d4c69dedda8904ab | [] | no_license | ddpub/cafe | 1dfde966cbee6acb1cd622370d4291946dfe41e1 | e7ba88d1c9dcc1e449ebc6a2401c1f21192eac00 | refs/heads/master | 2021-10-27T21:56:56.684590 | 2011-10-02T18:31:19 | 2011-10-02T18:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | hpp | #ifndef DMITRY_DERGACHEV_12_08_2008_WX_AUTHORISE_H
#define DMITRY_DERGACHEV_12_08_2008_WX_AUTHORISE_H
#include "auth_f.h"
#include <connect.hpp>
int wx_mng_auth();
int wx_person_auth();
ksi_client::oracle_session_i* wx_unlock();
#endif
| [
"dmitry.dergachev@gmail.com"
] | dmitry.dergachev@gmail.com |
411cc0ad7f7575aa4d5a6899fa7522f490e26e5b | 88137b65a7e48fbb9ea9d2b54a9809f21fbcb0d3 | /Basic-EED1005/averagee.cpp | 98454e8eb48a73a09b5a9a52461e59b5852b4147 | [] | no_license | OnurcanKoken/Introduction-to-C | db8ed750c6104cfc26120c8c47aad3e76f31dd4c | c87c6e4fe46c7711e903e53e847f6be80cc8ae3f | refs/heads/main | 2023-07-03T23:08:44.362308 | 2021-08-04T03:52:56 | 2021-08-04T03:52:56 | 392,539,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | cpp | #include <stdio.h>
#include <conio.h>
int main(void)
{
int age[10]={24,15,54,35,13,40,38,21,18,32};
float average;
int i;
for(i=0;i<10;i++){
average+=age[i];
}
printf("Average = %.1f",average/10);
getch();
return 0;
}
| [
"onur-koken@hotmail.com"
] | onur-koken@hotmail.com |
5f9704f139700a3cbd34ece4066cd8891062bc46 | 7566801b51c12cf8d55cb8b4c3c973ad57b9d728 | /include/sonar_image_proc/DrawSonar.h | 83e4003b3657d72dcac841ccbea3ae476e39e348 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | mahmoud-a-ali/sonar_image_proc | d96acad603a9480df171342cd4242d935e96cc32 | 127abee851ccf8fb17f530804c1e79e32677233b | refs/heads/master | 2023-04-02T01:42:31.216867 | 2021-03-30T12:20:00 | 2021-03-30T12:20:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | h | #pragma once
#include <memory>
#include <opencv2/core/core.hpp>
#include "sonar_image_proc/ColorMaps.h"
#include "sonar_image_proc/AbstractSonarInterface.h"
namespace sonar_image_proc {
cv::Size calculateImageSize( const sonar_image_proc::AbstractSonarInterface &ping, cv::Size hint, int pixPerRangeBin = 2, float maxRange = -1.0 );
void drawSonar(const sonar_image_proc::AbstractSonarInterface &ping, cv::Mat &mat, const SonarColorMap &colorMap=InfernoColorMap(), float maxRange = -1.0 );
}
| [
"amarburg@uw.edu"
] | amarburg@uw.edu |
cd91cb8ed2d04c64f258234d74c7bc415762b4a0 | 1a811644a0ea8aea9ee61c62eecb4f23eba6fe25 | /Source/MediaInfo/Archive/File_Iso9660.h | 818fb6a89bf9e07f38bae95cd8f670f1dc93825d | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"NCSA",
"LGPL-2.0-or-later",
"curl",
"Zlib",
"GPL-1.0-or-later",
"MPL-2.0",
"Apache-2.0"
] | permissive | MediaArea/MediaInfoLib | 6b9542892996428c4a966bfd8743adc334bb9077 | 731e3b57c1f9dfa84bfccf3396c0485766b65ea2 | refs/heads/master | 2023-09-03T21:03:52.307978 | 2023-08-16T07:49:44 | 2023-08-16T07:49:44 | 22,110,149 | 576 | 209 | BSD-2-Clause | 2023-09-14T13:44:33 | 2014-07-22T15:50:26 | C++ | UTF-8 | C++ | false | false | 2,826 | h | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Information about Iso9660 files
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
#ifndef MediaInfo_File_Iso9660H
#define MediaInfo_File_Iso9660H
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/File__Analyze.h"
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Class File_Iso9660
//***************************************************************************
class File_Iso9660 : public File__Analyze
{
public :
//Constructor/Destructor
~File_Iso9660();
private :
//Streams management
void Streams_Accept();
void Streams_Finish();
//Buffer - File header
void FileHeader_Parse();
//Buffer - Per element
void Header_Parse();
void Data_Parse();
//Elements
void Primary_Volume_Descriptor();
void Primary_Volume_Descriptor2();
void Path_Table();
void Directory();
void File();
//Helpers
void Directory_Record(int32u Size=0, const char* Name=nullptr);
//Temp
int16u Logical_Block_Size;
struct record
{
int32u Location;
int32u Length;
Ztring Name;
int8u Flags;
};
typedef std::map<int32u, std::vector<record> > records; // Key is location of extent
records Records;
set<int32u> Parsed;
set<int32u> NotParsed;
struct file_info
{
record* Record_Current;
Ztring Name;
};
typedef std::map<Ztring, record*> file_infos; // Key is complete file name
file_infos MI_MasterFileInfos;
file_infos MI_DataFileInfos;
std::map<Ztring, MediaInfo_Internal*> MI_MasterFiles; // Key is complete file name
std::map<Ztring, MediaInfo_Internal*> MI_DataFiles; // Key is complete file name
MediaInfo_Internal* MI_Current;
int64u MI_Current_StartOffset;
int64u MI_Current_EndOffset;
int32u Root_Location;
bool HasTag;
#if MEDIAINFO_TRACE
bool Trace_Activated_Save;
#endif //MEDIAINFO_TRACE
//Helpers
void Manage_Files();
bool Manage_File(file_infos& MI_Files);
void Manage_MasterFiles();
void Manage_DataFiles();
};
} //NameSpace
#endif
| [
"jerome@mediaarea.net"
] | jerome@mediaarea.net |
1e4214c4b755428af2a36297c260e4c0c1450d0a | 6c639883043f771b446aa8b5b1a45cc7d0951ca2 | /src/redis_slot.h | 408f9c2310d65a4fde25766521bce693a6830489 | [
"MIT"
] | permissive | raceli/kvrocks | d429193535ad22c8b4d781e54fce35a0540abba9 | 66d5dc0a069c656c648c6603ff1e86645da0ab5d | refs/heads/master | 2020-09-06T13:13:25.862996 | 2019-11-08T08:08:52 | 2019-11-08T08:08:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,329 | h | #pragma once
#include <rocksdb/status.h>
#include <rocksdb/write_batch.h>
#include <rocksdb/db.h>
#include <string>
#include <vector>
#include <thread>
#include "encoding.h"
#include "redis_db.h"
// crc32
#define HASH_SLOTS_MASK 0x000003ff
#define HASH_SLOTS_SIZE (HASH_SLOTS_MASK + 1)
const uint32_t IEEE_POLY = 0xedb88320;
extern uint32_t crc32tab[256];
typedef struct {
uint32_t slot_num;
uint64_t count;
} SlotCount;
typedef struct KeyValue {
std::string key;
int ttl;
std::string value;
} KeyValue;
void CRC32TableInit(uint32_t poly);
void InitCRC32Table();
uint32_t CRC32Update(uint32_t crc, const char *buf, int len);
uint32_t GetSlotNumFromKey(const std::string &key);
std::string GetTagFromKey(const std::string &key);
class SlotInternalKey {
public:
explicit SlotInternalKey(rocksdb::Slice key, uint64_t version);
explicit SlotInternalKey(uint32_t slot_num, uint64_t version);
explicit SlotInternalKey(rocksdb::Slice input);
~SlotInternalKey();
uint64_t GetSlotNum() const;
uint64_t GetVersion() const;
rocksdb::Slice GetKey() const;
void Encode(std::string *out);
bool operator==(const SlotInternalKey &that) const;
private:
uint32_t slot_num_;
uint64_t version_;
rocksdb::Slice key_;
char *buf_;
char prealloc_[256];
};
class SlotMetadata {
public:
uint64_t version;
uint64_t size;
public:
SlotMetadata();
void Encode(std::string *dst) const;
rocksdb::Status Decode(const std::string &bytes);
bool operator==(const SlotMetadata &that) const;
private:
uint64_t generateVersion();
};
class Mutex {
public:
Mutex();
~Mutex();
void Lock();
void Unlock();
void AssertHeld() {}
private:
friend class CondVar;
pthread_mutex_t mu_;
// No copying
Mutex(const Mutex &);
void operator=(const Mutex &);
};
class CondVar {
public:
explicit CondVar(Mutex *mu);
~CondVar();
void Wait();
/*
* timeout is millisecond
* so if you want to wait for 1 s, you should call
* TimeWait(1000);
* return false if timeout
*/
bool TimedWait(uint32_t timeout);
void Signal();
void SignalAll();
private:
pthread_cond_t cv_;
Mutex *mu_;
};
class MutexLock {
public:
explicit MutexLock(Mutex *mu)
: mu_(mu) {
this->mu_->Lock();
}
~MutexLock() { this->mu_->Unlock(); }
private:
Mutex *const mu_;
// No copying allowed
MutexLock(const MutexLock &);
void operator=(const MutexLock &);
};
namespace Redis {
class Slot : public SubKeyScanner {
public:
explicit Slot(Engine::Storage *storage) :
SubKeyScanner(storage, kDefaultNamespace),
slot_metadata_cf_handle_(storage->GetCFHandle("slot_metadata")),
slot_key_cf_handle_(storage->GetCFHandle("slot")) {}
rocksdb::Status GetMetadata(uint32_t slot_num, SlotMetadata *metadata);
Status MigrateOne(const std::string &host, int port, uint64_t timeout, const rocksdb::Slice &key);
Status MigrateOneKey(int sock_fd, const rocksdb::Slice &key);
Status MigrateSlotRandomOne(const std::string &host,
int port,
uint64_t timeout,
uint32_t slot_num);
Status MigrateTagSlot(const std::string &host,
int port,
uint64_t timeout,
uint32_t slot_num,
int *ret);
Status MigrateTag(const std::string &host,
int port,
uint64_t timeout,
const std::string &key,
int *ret);
rocksdb::Status Check();
rocksdb::Status GetInfo(uint32_t start, int count, std::vector<SlotCount> *slot_counts);
rocksdb::Status Del(uint32_t slot_num);
rocksdb::Status AddKey(const Slice &key);
rocksdb::Status DeleteKey(const Slice &key);
rocksdb::Status DeleteAll();
rocksdb::Status Size(uint32_t slot_num, uint64_t *ret);
rocksdb::Status UpdateKeys(const std::vector<std::string> &put_keys,
const std::vector<std::string> &delete_keys,
rocksdb::WriteBatch *updates);
rocksdb::Status IsKeyExist(const Slice &key);
rocksdb::Status Scan(uint32_t slot_num,
const std::string &cursor,
uint64_t limit,
std::vector<std::string> *keys);
rocksdb::Status Restore(const std::vector<KeyValue> &key_values);
Status CheckCodisEnabledStatus(bool enabled);
private:
std::string codis_enabled_status_key_ = "codis_enabled";
rocksdb::ColumnFamilyHandle *slot_metadata_cf_handle_;
rocksdb::ColumnFamilyHandle *slot_key_cf_handle_;
Status generateMigrateCommandComplexKV(const Slice &key, const Metadata &metadata, std::string *output);
};
class SlotsMgrtSenderThread {
public:
explicit SlotsMgrtSenderThread(Engine::Storage *storage) :
slotsmgrt_cond_(&slotsmgrt_cond_mu_),
storage_(storage),
is_migrating_(false) {}
virtual ~SlotsMgrtSenderThread();
Status Start();
void Stop();
void StopMigrateSlot();
void Join();
bool IsStopped() { return stop_; }
Status SlotsMigrateOne(const std::string &key, int *ret);
Status SlotsMigrateBatch(const std::string &ip, int port, uint64_t time_out, uint32_t slot, int keys_num);
Status GetSlotsMigrateResult(uint64_t *moved, uint64_t *remained);
Status GetSlotsMgrtSenderStatus(std::string *ip,
int *port,
uint32_t *slot_num,
bool *migrating,
uint64_t *moved,
uint64_t *remained);
Status SlotsMigrateAsyncCancel();
private:
std::thread t_;
std::mutex db_mu_;
std::mutex ones_mu_;
Mutex slotsmgrt_cond_mu_;
CondVar slotsmgrt_cond_;
bool stop_ = false;
Engine::Storage *storage_;
std::string dest_ip_;
int dest_port_ = 0;
uint64_t timeout_ms_ = 0;
uint32_t slot_num_ = 0;
std::atomic<int> keys_num_{0};
uint64_t moved_keys_num_ = 0; // during one batch moved
uint64_t moved_keys_all_ = 0; // all keys moved in the slot
uint64_t remained_keys_num_ = 0;
bool error_ = false;
std::vector<std::string> migrating_ones_;
std::atomic<bool> is_migrating_;
Status ElectMigrateKeys(std::vector<std::string> *keys);
void loop();
};
} // namespace Redis
| [
"karelrooted@gmail.com"
] | karelrooted@gmail.com |
d560b237a415b293df0f2b25c8fbc62a2df3d4eb | f86cf438dd3f204ae4783e043a426b7f1fce4803 | /src_nodes/leradnode/leradnode.cpp | 9d202988c9a703c69a2b03dcaa17a44a60d5f769 | [] | no_license | tadasamantri/anise_framework | 4143e0de5c656b61cc2843cb7cf998f6d1681739 | 33b2ffdc3c687a0b9d25896a346f7fa062a99663 | refs/heads/master | 2020-12-25T04:54:28.222084 | 2015-08-28T14:54:37 | 2015-08-28T14:54:37 | 42,894,360 | 0 | 0 | null | 2015-09-21T21:22:53 | 2015-09-21T21:22:52 | null | UTF-8 | C++ | false | false | 12,907 | cpp | #include "leradnode.h"
#include "data/datafactory.h"
#include "data/messagedata.h"
#include "tabledata/tabledata.h"
#include <QDebug>
#include <QList>
#include <QFile>
//------------------------------------------------------------------------------
// Constructor and Destructor
CLeradNode::CLeradNode(const CNodeConfig &config, QObject *parent/* = 0*/)
: CNode(config, parent)
{
}
//------------------------------------------------------------------------------
// Public Functions
void CLeradNode::configure(CNodeConfig &config)
{
// Set the node Description
config.setDescription("The LERAD Anomaly Detection Algorithm: "
"Build rules that describe the normal pattern "
"of given data.");
// Add parameters
//config.addFilename("file", "Input File", "File to be read from disk.");
config.addUInt("rseed", "Random Seed", "The random seed to feed the "
"random number generator at the start.", 666);
config.addUInt("sample_size", "Training Samples", "Number of samples to use "
"for training LERAD.", 100);
config.addUInt("pairs_to_match", "Number of Pairs to Match",
"Number of pairs to match for building rules", 1000);
config.addUInt("max_rules_per_pair", "Maximum Rules per Pair",
"Maximum number of rules to create for each pair.", 4);
config.addBool("dump_rules","Dump Generated Rules","Write the rules "
"generated by LERAD to a file.", false);
config.addFilename("rules_file", "Rules Filename", "File where the "
"LERAD rules are written.");
// Add the gates.
config.addInput("in", "table");
config.addOutput("out", "ruleset");
}
//------------------------------------------------------------------------------
// Protected Functions
bool CLeradNode::start()
{
m_ruleset = QSharedPointer<CRulesetData>(
static_cast<CRulesetData *>(createData("ruleset")));
if(!m_ruleset.isNull()) {
return true;
}
else {
return false;
}
}
bool CLeradNode::data(QString gate_name, const CConstDataPointer &data)
{
Q_UNUSED(gate_name);
if(data->getType() == "table") {
// Process table data.
auto table = data.staticCast<const CTableData>();
if(!table.isNull()) {
lerad(table);
}
else {
commitError("out", "LERAD did not receive a valid table.");
}
return true;
}
return false;
}
void CLeradNode::lerad(const QSharedPointer<const CTableData> &table)
{
QString info;
QString warning;
// Seed the algorithm.
qsrand(getConfig().getParameter("rseed")->value.toUInt());
// Helpers for translating nominals to strings and viceversa.
qint32 anything_nominal = m_ruleset->string2nominal("*");
qint32 something_nominal = m_ruleset->string2nominal("?");
// Number of attributes
qint32 attribute_count = table->colCount();
if(attribute_count < 2) {
warning = "LERAD needs at least 2 attributes to create rules.";
qWarning() << warning;
setLogWarning(warning);
return;
}
m_ruleset->attributeCount(attribute_count);
// 2- Read tuples from the table to build a dataset.
QList<QList<Nominal>> dataset;
qint32 rows = table->rowCount();
for(qint32 j = 0; j < rows; ++j) {
// Get the row.
const QList<QVariant> &row = table->getRow(j);
// Iterate the attributes of the row.
Antecedent t;
t.reserve(attribute_count);
for(qint32 i = 0; i < attribute_count; ++i) {
// Convert attribute to nominal.
QString attr = row[i].toString();
qint32 n = m_ruleset->string2nominal(attr);
t.append(n);
}
dataset.append(t);
}
m_ruleset->tuplesCount(dataset.size());
info = "LERAD:: Dataset size: " + QVariant(dataset.size()).toString();
qDebug() << info;
setLogInfo(info);
if(dataset.size() < 2) {
warning = "LERAD:: Cannot work with less than two tuples.";
qWarning() << warning;
setLogWarning(warning);
return;
}
// 3- Select random samples from the dataset for preliminary training.
qint32 sample_size = getConfig().getParameter("sample_size")->value.toInt();
QList<qint32> samples;
samples.reserve(sample_size);
qint32 r = qMin(dataset.size(), sample_size);
for(qint32 i = 0; r > 0 && i < dataset.size(); ++i) {
qint32 rand_num = rnd() % (dataset.size() - i);
if(rand_num < r) {
--r;
samples.append(i);
}
}
// 4- Construct ruleset.
// The key is a rule, coded 0="*", 1="?", 2 or more = constrained
// attribute. Rules are constructed by sampling 2 tuples
// in the dataset and constructing up to 4 rules for 4 randomly
// selected matching attributes in random order where the first is "?"
// and the other 3 are the anteceedents.
qint32 ruleset_size = getConfig().
getParameter("pairs_to_match")->value.toInt();
qint32 max_rules = getConfig().
getParameter("max_rules_per_pair")->value.toInt();
m_ruleset->reserve(ruleset_size * max_rules * 0.85);
Antecedent antecedent;
antecedent.reserve(attribute_count);
for(qint32 j = 0; j < attribute_count; ++j) {
antecedent.append(anything_nominal);
}
for(qint32 i = 0; i < ruleset_size; ++i) {
// Pick random pair of tuples from sample set.
qint32 r1 = rnd() % samples.size();
qint32 r2 = rnd() % (samples.size() - 1);
if(r1 == r2) r2 = samples.size() - 1;
r1 = samples[r1];
r2 = samples[r2];
// Generate rules by matching attribute values.
for(qint32 j = 0; j < attribute_count; ++j) {
antecedent[j] = anything_nominal;
}
qint32 count = 0;
for(qint32 j = 0; j < attribute_count && count < max_rules; ++j) {
qint32 r3 = rnd() % attribute_count;
if(dataset[r1][r3] == dataset[r2][r3]) {
if(count == 0) {
// The first match becomes an consequent (marked with a '?').
antecedent[r3] = something_nominal; // == "?";
count = 1;
// Insert the rule into the ruleset.
m_ruleset->addRule(antecedent);
}
else if(antecedent[r3] == anything_nominal) {
// Other matches are antecedents
antecedent[r3] = dataset[r1][r3];
++count;
// Add new rule.
m_ruleset->addRule(antecedent);
}
}
}
}
info = "LERAD:: Initial Rules: " + QVariant(m_ruleset->size()).toString();
qDebug() << info;
setLogInfo(info);
// 5- Estimate the support of each rule using the samples.
QList<CRule> &ruleset = m_ruleset->getRules();
QList<CRule>::iterator it;
for(it = ruleset.begin(); it != ruleset.end(); ++it) {
qint32 i = 0;
for(; i < samples.size(); ++i) {
qint32 r = samples[i];
qint32 j = 0;
for(; j < attribute_count; ++j) {
// Check if the rule applies.
if((*it).antecedent[j] >= 2 &&
(*it).antecedent[j] != dataset[r][j]) {
break;
}
}
if(j == attribute_count) {
// The rule does apply.
(*it).consequent.add(dataset[r][(*it).i_consequent]);
}
}
}
// 6- Estimate n/r again so that each tuple attribute is predicted by
// only the rule with the highest n/r from before
std::sort(ruleset.begin(), ruleset.end());
QList<QList<bool>> cover;
cover.reserve(sample_size);
for(qint32 i = 0; i < sample_size; ++i) {
QList<bool> tlist;
tlist.reserve(attribute_count);
for(qint32 j = 0; j < attribute_count; ++j) {
tlist.append(false);
}
cover.append(tlist);
}
// If there is a rule predicting attribute database[sample[i]][j].
for(it = ruleset.begin(); it != ruleset.end(); ++it) {
CRule &r = *it;
r.consequent.clear();
for(qint32 j = 0; j < sample_size; ++j) {
if(!cover[j][r.i_consequent] &&
r.matchAntecedents(dataset[samples[j]])) {
r.consequent.add(dataset[samples[j]][r.i_consequent]);
cover[j][r.i_consequent] = true;
}
}
}
// 6.1- Discard unsupported rules
it = ruleset.begin();
while(it != ruleset.end()) {
if(it->consequent.n == 0) {
it = ruleset.erase(it);
}
else {
++it;
}
}
info = "LERAD:: Pruned Rules: " + QVariant(ruleset.size()).toString();
qDebug() << info;
setLogInfo(info);
// 7- Calculate exact support for top rules on entire training set
std::sort(ruleset.begin(), ruleset.end());
// Reset the cover.
cover.clear();
cover.reserve(dataset.size());
for(qint32 i = 0; i < dataset.size(); ++i) {
QList<bool> tlist;
tlist.reserve(attribute_count);
for(qint32 j = 0; j < attribute_count; ++j) {
tlist.append(false);
}
cover.append(tlist);
}
qint32 now = 0;
qint32 validation_index = dataset.size() * 9;
bool rule_deleted = false;
it = ruleset.begin();
while(it != ruleset.end()) {
CRule &rule = *it;
rule.consequent.clear();
now = 0;
rule_deleted = false;
QList<QList<Nominal>>::iterator tuple_it;
qint32 tuple_index = 0;
for(tuple_it = dataset.begin(), tuple_index = 0;
tuple_it != dataset.end();
++tuple_it, ++tuple_index) {
QList<Nominal> &tuple = *tuple_it;
++now;
if(rule.matchAntecedents(tuple)) {
cover[tuple_index][rule.i_consequent] = true;
if(rule.consequent.add(tuple[rule.i_consequent]) == 1) {
// Update time.
rule.consequent.t = now;
// Remove rules that trigger False Positives.
if(tuple_index * 10 > validation_index) {
it = ruleset.erase(it);
rule_deleted = true;
break;
}
}
}
}
if(!rule_deleted) {
++it;
}
}
std::sort(ruleset.begin(), ruleset.end());
// Shall we write the rules to a file?
bool dump_rules = getConfig().getParameter("dump_rules")->value.toBool();
if(dump_rules) {
QString filename = getConfig().getParameter("rules_file")->value.toString();
dumpRules(table->header(), filename);
}
// 8- Print coverage
// qDebug() << "LERAD:: Coverage:";
// for(qint32 i = 0; i < attribute_count; ++i) {
// qint32 count = 0;
// for(qint32 j = 0; j < cover.size(); ++j) {
// if(cover[j][i]) {
// ++count;
// }
// }
// qDebug() << "LERAD::" << table->getHeader()[i] << "=" << count << " ";
// }
// Forward the ruleset.
commit("out", m_ruleset);
// Free memory when possible.
m_ruleset.clear();
}
void CLeradNode::dumpRules(const QList<QString> &header,
const QString &filename)
{
QFile file(filename);
if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QString warning = "LERAD:: Could not write rules to " + filename;
qWarning() << warning;
setLogWarning(warning);
return;
}
QTextStream file_stream(&file);
QList<CRule> &ruleset = m_ruleset->getRules();
QList<QString> &nominals = m_ruleset->getNominals();
qint32 i = 0;
auto it_rule = ruleset.begin();
while(it_rule != ruleset.end()) {
const CRule &rule = *it_rule;
file_stream << i << " "
<< rule.consequent.n << "/" << rule.consequent.values.size()
<< "\tif";
for(qint32 j = 0; j < rule.antecedent.size(); ++j) {
if(rule.antecedent[j] > 1) {
file_stream << " " << header[j] << " = "
<< nominals[rule.antecedent[j]];
}
}
file_stream << " then " << header[rule.i_consequent] << " =";
auto it_val = rule.consequent.values.begin();
while(it_val != rule.consequent.values.end()) {
file_stream << " " << nominals[it_val.key()];
++it_val;
}
file_stream << endl;
++i;
++it_rule;
}
file_stream.flush();
file.close();
}
| [
"carloscg@gmail.com"
] | carloscg@gmail.com |
151047e37fa19384aa27745877859a17419d5e05 | 3fef24a77e918dbae6e7d36f5776f28eb111f7aa | /src/operator/contrib/multi_proposal.cc | cd00e877a11d42663df080dd7c7f26814b8ead1e | [
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Jopyth/BMXNet | db642963c980c79b95476effbb9e98fc370d20a6 | 2d4f7f4553b1103c4309b0f8c4b51d823e234b69 | refs/heads/master | 2020-03-30T01:24:15.004207 | 2018-07-05T12:42:44 | 2018-09-27T11:22:20 | 150,574,165 | 17 | 1 | Apache-2.0 | 2018-09-27T11:09:07 | 2018-09-27T11:09:07 | null | UTF-8 | C++ | false | false | 2,778 | cc | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2017 Microsoft
* Licensed under The Apache-2.0 License [see LICENSE for details]
* \file multi_proposal.cc
* \brief
* \author Xizhou Zhu
*/
#include "./multi_proposal-inl.h"
namespace mxnet {
namespace op {
template<typename xpu>
class MultiProposalOp : public Operator{
public:
explicit MultiProposalOp(MultiProposalParam param) {
this->param_ = param;
}
virtual void Forward(const OpContext &ctx,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &out_data,
const std::vector<TBlob> &aux_states) {
LOG(FATAL) << "not implemented";
}
virtual void Backward(const OpContext &ctx,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &in_data,
const std::vector<TBlob> &out_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &in_grad,
const std::vector<TBlob> &aux_states) {
LOG(FATAL) << "not implemented";
}
private:
MultiProposalParam param_;
}; // class MultiProposalOp
template<>
Operator *CreateOp<cpu>(MultiProposalParam param) {
return new MultiProposalOp<cpu>(param);
}
Operator* MultiProposalProp::CreateOperator(Context ctx) const {
DO_BIND_DISPATCH(CreateOp, param_);
}
DMLC_REGISTER_PARAMETER(MultiProposalParam);
MXNET_REGISTER_OP_PROPERTY(_contrib_MultiProposal, MultiProposalProp)
.describe("Generate region proposals via RPN")
.add_argument("cls_score", "NDArray-or-Symbol", "Score of how likely proposal is object.")
.add_argument("bbox_pred", "NDArray-or-Symbol", "BBox Predicted deltas from anchors for proposals")
.add_argument("im_info", "NDArray-or-Symbol", "Image size and scale.")
.add_arguments(MultiProposalParam::__FIELDS__());
} // namespace op
} // namespace mxnet
| [
"piiswrong@users.noreply.github.com"
] | piiswrong@users.noreply.github.com |
2cbb3e73fa14ec7655a316df3fcb7e88b8b8364c | cc21ea29b28127d4e2a751c11c1108ad01114d29 | /2ºcuatrimestre/MP/sesion10/src/Matriz2D_2_Asignacion_Acceso.cpp | f2e418551cf7300cdda2c2354224d725c0e1fa90 | [] | no_license | AlbitaMoreno/Primero | 46ef749acdaacdb569500dff6108b5f793c12bae | 200d6fb5302e285974f0133a5c6706be409bf191 | refs/heads/master | 2021-01-19T00:44:14.742612 | 2016-11-12T12:20:05 | 2016-11-12T12:20:05 | 73,213,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,280 | cpp | //
// CURSO 2015-2016
// Alba Moreno Ontiveros
//
//Matriz2D_2_Asignacion-Acceso.cpp
//
/***************************************************************************/
#include <iostream>
#include "Matriz2D_2_Asignacion_Acceso.h"
using namespace std;
/********************************************************************************************/
/*******************************************************************************************/
//
// Constructores y destructor
//
/********************************************************************************************/
/*******************************************************************************************/
Matriz2D_2 :: Matriz2D_2(){ //constructor ain argumentos
filas = 0;
columnas= 0;
}
/********************************************************************************************/
/*******************************************************************************************/
Matriz2D_2 :: Matriz2D_2(int cuadrada){ //constructor que crea una matriz rectangular
filas = columnas = cuadrada;
ReservaMem(filas,columnas);
}
/********************************************************************************************/
/*******************************************************************************************/
Matriz2D_2 :: Matriz2D_2(int fils, int cols){ //constructor con dos argumentos
filas = filas;
columnas = cols;
ReservaMem(filas, columnas);
}
/********************************************************************************************/
/*******************************************************************************************/
Matriz2D_2 :: Matriz2D_2(const Matriz2D_2 & otro){
ReservaMem(otro.filas, otro.columnas);
CopiaDatos(otro);
}
/********************************************************************************************/
/*******************************************************************************************/
Matriz2D_2 :: ~Matriz2D_2(){ //destructor
LiberaMem();
}
/********************************************************************************************/
/*******************************************************************************************/
//
// MÉTODOS PÚBLICOS
//
/********************************************************************************************/
/*******************************************************************************************/
bool Matriz2D_2 :: MatrizVacia()const{
return(!datos);
}
/********************************************************************************************/
/*******************************************************************************************/
void Matriz2D_2 :: MismoValor(TipoBase valor){ //si no se le pasa un parámetro tiene un valor por defecto, el 0
for(int i = 0; i < filas;i++){
for(int j = 0; j < columnas; j++){
datos[i][j] = valor;
}
}
}
/********************************************************************************************/
/*******************************************************************************************/
//
// MÉTODOS PRIVADOS
//
/********************************************************************************************/
/*******************************************************************************************/
void Matriz2D_2 :: ReservaMem(int filas, int columnas){
//Primero reservo el vector que apuntará a las filas
datos = new int *[filas];
datos[0] = new int [filas*columnas];
//reservo la memoria para cada fila
for(int i = 1; i < filas;i++)
datos[i] = datos[i-1] + columnas;
}
/********************************************************************************************/
/*******************************************************************************************/
void Matriz2D_2 :: LiberaMem(){
//Libero la memoria que ocupan las filas
if(datos){
//Libero la memoria que ocupan las filas, como estan consecutivas, no tengo que
//hacer un ciclo for
delete [] datos[0];
//Libero la memoria ocupada por el vector datos;
delete [] datos;
}
}
/********************************************************************************************/
/*******************************************************************************************/
void Matriz2D_2 :: CopiaDatos(const Matriz2D_2 &otro){
filas = otro.filas;
columnas = otro.columnas;
for(int i = 0; i < filas; i++){
for(int j = 0; j < columnas; j++)
datos[i][j] = otro.datos[i][j];
}
}
/********************************************************************************************/
/*******************************************************************************************/
//
// SOBRECARGA DE OPERADORES
//
/********************************************************************************************/
/*******************************************************************************************/
Matriz2D_2 & Matriz2D_2 :: operator = (const Matriz2D_2 & otro){
if(this != &otro){
LiberaMem();
ReservaMem(otro.filas, otro.columnas);
CopiaDatos(otro);
}
return(*this);
}
Matriz2D_2 & Matriz2D_2 :: operator = (const TipoBase valor){
LiberaMem();
ReservaMem(filas,columnas);
MismoValor(valor);
return(*this);
}
TipoBase & Matriz2D_2 :: operator () (const int f , const int c){
return(datos[f][c]);
} | [
"albamoreno.ontiveros@gmail.com"
] | albamoreno.ontiveros@gmail.com |
ccaa28e21529accc89b09336395a15807e533f76 | de7e771699065ec21a340ada1060a3cf0bec3091 | /analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseMinimalStemFilter.h | dbe2474761b2e66fe8bfaeba1d5bb2d45e2bdd7b | [] | no_license | sraihan73/Lucene- | 0d7290bacba05c33b8d5762e0a2a30c1ec8cf110 | 1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3 | refs/heads/master | 2020-03-31T07:23:46.505891 | 2018-12-08T14:57:54 | 2018-12-08T14:57:54 | 152,020,180 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,885 | h | #pragma once
#include "../../../../../../../../../core/src/java/org/apache/lucene/analysis/Analyzer.h"
#include "../../../../../../../../../test-framework/src/java/org/apache/lucene/analysis/BaseTokenStreamTestCase.h"
#include "stringhelper.h"
#include <memory>
#include <stdexcept>
#include <string>
#include <deque>
// C++ NOTE: Forward class declarations:
#include "core/src/java/org/apache/lucene/analysis/Analyzer.h"
#include "core/src/java/org/apache/lucene/analysis/TokenStreamComponents.h"
#include "core/src/java/org/apache/lucene/analysis/CharArraySet.h"
/*
* Licensed to the Syed Mamun Raihan (sraihan.com) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* sraihan.com licenses this file to You under GPLv3 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
*
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* 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.
*/
namespace org::apache::lucene::analysis::pt
{
using Analyzer = org::apache::lucene::analysis::Analyzer;
using BaseTokenStreamTestCase =
org::apache::lucene::analysis::BaseTokenStreamTestCase;
// C++ TODO: The Java 'import static' statement cannot be converted to C++:
// import static org.apache.lucene.analysis.VocabularyAssert.*;
/**
* Simple tests for {@link PortugueseMinimalStemFilter}
*/
class TestPortugueseMinimalStemFilter : public BaseTokenStreamTestCase
{
GET_CLASS_NAME(TestPortugueseMinimalStemFilter)
private:
std::shared_ptr<Analyzer> analyzer;
public:
void setUp() override;
private:
class AnalyzerAnonymousInnerClass : public Analyzer
{
GET_CLASS_NAME(AnalyzerAnonymousInnerClass)
private:
std::shared_ptr<TestPortugueseMinimalStemFilter> outerInstance;
public:
AnalyzerAnonymousInnerClass(
std::shared_ptr<TestPortugueseMinimalStemFilter> outerInstance);
protected:
std::shared_ptr<Analyzer::TokenStreamComponents>
createComponents(const std::wstring &fieldName) override;
protected:
std::shared_ptr<AnalyzerAnonymousInnerClass> shared_from_this()
{
return std::static_pointer_cast<AnalyzerAnonymousInnerClass>(
org.apache.lucene.analysis.Analyzer::shared_from_this());
}
};
public:
void tearDown() override;
/**
* Test the example from the paper "Assessing the impact of stemming accuracy
* on information retrieval"
*/
virtual void testExamples() ;
/** Test against a vocabulary from the reference impl */
virtual void testVocabulary() ;
virtual void testKeyword() ;
private:
class AnalyzerAnonymousInnerClass2 : public Analyzer
{
GET_CLASS_NAME(AnalyzerAnonymousInnerClass2)
private:
std::shared_ptr<TestPortugueseMinimalStemFilter> outerInstance;
std::shared_ptr<CharArraySet> exclusionSet;
public:
AnalyzerAnonymousInnerClass2(
std::shared_ptr<TestPortugueseMinimalStemFilter> outerInstance,
std::shared_ptr<CharArraySet> exclusionSet);
protected:
std::shared_ptr<Analyzer::TokenStreamComponents>
createComponents(const std::wstring &fieldName) override;
protected:
std::shared_ptr<AnalyzerAnonymousInnerClass2> shared_from_this()
{
return std::static_pointer_cast<AnalyzerAnonymousInnerClass2>(
org.apache.lucene.analysis.Analyzer::shared_from_this());
}
};
/** blast some random strings through the analyzer */
public:
virtual void testRandomStrings() ;
virtual void testEmptyTerm() ;
private:
class AnalyzerAnonymousInnerClass3 : public Analyzer
{
GET_CLASS_NAME(AnalyzerAnonymousInnerClass3)
private:
std::shared_ptr<TestPortugueseMinimalStemFilter> outerInstance;
public:
AnalyzerAnonymousInnerClass3(
std::shared_ptr<TestPortugueseMinimalStemFilter> outerInstance);
protected:
std::shared_ptr<Analyzer::TokenStreamComponents>
createComponents(const std::wstring &fieldName) override;
protected:
std::shared_ptr<AnalyzerAnonymousInnerClass3> shared_from_this()
{
return std::static_pointer_cast<AnalyzerAnonymousInnerClass3>(
org.apache.lucene.analysis.Analyzer::shared_from_this());
}
};
protected:
std::shared_ptr<TestPortugueseMinimalStemFilter> shared_from_this()
{
return std::static_pointer_cast<TestPortugueseMinimalStemFilter>(
org.apache.lucene.analysis.BaseTokenStreamTestCase::shared_from_this());
}
};
} // #include "core/src/java/org/apache/lucene/analysis/pt/
| [
"smamunr@fedora.localdomain"
] | smamunr@fedora.localdomain |
e0e50cfbef6095e6267b37e28a9fe7a1e9012dd1 | 7163af166893b2bdd710bf652771c09f99106e26 | /OpenSim/Analyses/osimAnalysesDLL.cpp | 32c083796b20a951db84c6fa026d32692b0c15c3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | tgeijten/opensim3-scone | 6b73125c7ca438b26b80b04f55f061e0e7f314cb | ffa32e4e098ef364948781444e4ea7f3bab2e845 | refs/heads/master | 2021-06-20T02:41:28.315713 | 2021-01-28T13:19:08 | 2021-01-28T13:19:08 | 180,564,353 | 1 | 2 | NOASSERTION | 2021-01-14T16:17:41 | 2019-04-10T11:09:17 | C++ | UTF-8 | C++ | false | false | 3,458 | cpp | /* -------------------------------------------------------------------------- *
* OpenSim: osimAnalysesDLL.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Frank C. Anderson *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "osimAnalysesDLL.h"
#include <iostream>
#include "RegisterTypes_osimAnalyses.h"
using namespace std;
//
// Define Plugin_Attach and Plugin_Detach below to be called by both windows and linux
//
static void Plugin_Attach()
{
//cout<<"\n-------------------------------------------------------\n";
//cout<<"Library Analyses...\n";
//cout<<"-------------------------------------------------------\n\n";
}
static void Plugin_Detach()
{
}
//
// The code below handles both windows and linux library entrypoints
//
#if defined(WIN32)
//=============================================================================
// DLL Main Entry Point
//=============================================================================
//_____________________________________________________________________________
/**
* This routine is called when the dll is loaded I believe.
*/
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
Plugin_Attach();
break;
case DLL_PROCESS_DETACH:
Plugin_Detach();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
#elif defined(__linux__)
static void __attribute__((constructor)) Shared_Object_Constructor()
{
Plugin_Attach();
}
static void __attribute__((destructor)) Shared_Object_Destructor()
{
Plugin_Detach();
}
#endif
| [
"tgeijten@gmail.com"
] | tgeijten@gmail.com |
c5f0a4e1b7eb8ba3cea4675d23b2e290b4d08335 | 4b8c6ce034e9078fc6dce2ad5ec3789a4e8e8581 | /Snake/Game.h | e2e05e4f6b98c962e54ab31e8b03023cdc5bdcd9 | [] | no_license | Icaka/Snake | 3160b1db2b272cea5939e248fbb0d104acfb4402 | d64715503b93c9618a5b69231becc110db66d254 | refs/heads/main | 2023-04-17T00:53:03.580330 | 2021-05-10T15:53:09 | 2021-05-10T15:53:09 | 365,374,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | h | #pragma once
#include <SFML/Graphics.hpp>
#include "SnakePart.h"
const int MATRIX_SIZE = 15;
const int STARTING_TAIL = 5;
const int MAX_SNAKE_LENGTH = MATRIX_SIZE * MATRIX_SIZE;
class Game
{
private:
sf::RenderWindow window;
sf::RectangleShape matrix[MATRIX_SIZE][MATRIX_SIZE];
SnakePart head;
int tailLength = STARTING_TAIL;
SnakePart tail[MAX_SNAKE_LENGTH];
//Snake snake;
int directionX;
int directionY;
int applePosX;
int applePosY;
int score;
protected:
void processEvents();
void update();
void render();
void handlePlayerInput(sf::Keyboard::Key);
void moveSnake();
void placeApple();
void eatApple();
bool collides(); // checks for tail bites
public:
Game();
void run();
}; | [
"ico.ezekiev@gmail.com"
] | ico.ezekiev@gmail.com |
a1c1c69876d2634e13f1608bc26e99ebc68f80da | 328d1436f0c7e876506321425a5f3503b6984db0 | /BRDFs/GlossySpecular.cpp | f9a2540843aeb17ac48472ad932afbc140dd97c7 | [] | no_license | ghostec/White2 | d0555d91698a782bb416c4f2139fc2d9afbe299d | f55015691a696342532ecab10656db82e576d48a | refs/heads/master | 2021-01-10T11:18:14.155426 | 2016-01-18T18:05:07 | 2016-01-18T18:05:07 | 46,703,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | cpp | #include <cmath>
#include "GlossySpecular.h"
GlossySpecular::GlossySpecular(void) : BRDF(), ks(0.0), cs(0.0) {}
RGBColor GlossySpecular::f(const ShadeRec& sr, const Vector3D& wo, const Vector3D& wi) const
{
RGBColor L;
float ndotwi = sr.normal * wi;
Vector3D r(-wi + 2.0 * sr.normal * ndotwi);
float rdotwo = r * wo;
if(rdotwo > 0.0) {
L = ks * pow(rdotwo, exp);
}
return L;
}
RGBColor GlossySpecular::sample_f(const ShadeRec& sr, const Vector3D& wo, Vector3D& wi, float& pdf) const
{
return black; // placeholder (ch 24)
}
RGBColor GlossySpecular::rho(const ShadeRec & sr, const Vector3D & wo) const
{
return black;
}
void GlossySpecular::setKs(const float _ks)
{
ks = _ks;
}
void GlossySpecular::setCs(const float r, const float g, const float b)
{
cs = RGBColor(r, g, b);
}
void GlossySpecular::setCs(const float c)
{
cs = RGBColor(c);
}
void GlossySpecular::setCs(const RGBColor& c)
{
cs = c;
}
void GlossySpecular::setExp(const float _exp)
{
exp = _exp;
}
| [
"yuriabrito@gmail.com"
] | yuriabrito@gmail.com |
e60d9c32098d40e9d975ea35a6e79d43aa86c225 | cc2509b0bd337361edf91cc4b67b66d6b4b52738 | /Map/OperationGraduation_V8_10/mini.cpp | 7a832c5b6ecde815e32c3c28e4161d3204088487 | [] | no_license | espinozahector/CIS17B_Rogue_Game | dbd02bba7592eedb19072402fdc070a1282dd0b9 | 155611aca141681accd6b88f59215f95feed7ef2 | refs/heads/master | 2021-01-12T11:58:53.021843 | 2016-12-15T00:34:36 | 2016-12-15T00:34:36 | 68,877,253 | 0 | 0 | null | 2016-09-24T20:30:55 | 2016-09-22T02:36:55 | Makefile | UTF-8 | C++ | false | false | 914 | cpp | #include "mini.h"
mini::mini(QWidget *parent) : QGraphicsView(parent)
{
miniR = 9;
miniC = 9;
lastX = 4;
lastY = 4;
miniScene = new QGraphicsScene();
miniScene->setSceneRect(0,0,350,150);
this->setAttribute(Qt::WA_ShowWithoutActivating);
setFixedSize(350,150);
setScene(miniScene);
buildMini();
}
mini::~mini()
{
}
void mini::buildMini()
{
tile2 = new Tile[81];
for(int i = 0 ;i < miniR;i++)
{
for(int j = 0; j < miniC;j++)
{
tile2[(i*miniC)+j].miniDesign();
tile2[(i*miniC)+j].miniMove(j,i);
tile2[(i*miniC)+j].setAcceptTouchEvents(false);
miniScene->addItem(tile2+((i*miniC)+j));
}
}
tile2[(4*miniC)+4].miniCurrent();
}
void mini::miniUpdate(int x, int y)
{
tile2[(lastX*miniC)+lastY].miniLast();
tile2[(x*miniC)+y].miniCurrent();
lastX = x;
lastY = y;
}
| [
"espinozahector68@gmail.com"
] | espinozahector68@gmail.com |
9b748dfba67eb794ee63b96765ae8f2a75e00e0a | 16a40bab6d139fe4db092b5d2cb3be50625dff98 | /include/rev/CANDigitalInput.h | aa66ac27ffbc01bf1e74f4ccf18c59b1bac6f22b | [] | no_license | medengineer/Phoenix-Linux-SocketCAN-Example | 6eb3036c871e6dc124ad27893b4b7143d68f14a9 | d9e0ce1c6a0f07562ba5ba1c59319d43c8001677 | refs/heads/master | 2021-03-22T13:41:19.038519 | 2020-03-16T02:58:14 | 2020-03-16T02:58:14 | 247,370,220 | 0 | 0 | null | 2020-03-14T23:38:24 | 2020-03-14T23:38:24 | null | UTF-8 | C++ | false | false | 3,107 | h | /*
* Copyright (c) 2018-2020 REV Robotics
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of REV Robotics 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.
*/
#pragma once
#include "rev/CANError.h"
#include "rev/CANEncoder.h"
namespace rev {
class CANSparkMax;
class CANDigitalInput {
public:
enum class LimitSwitch { kForward, kReverse };
enum class LimitSwitchPolarity { kNormallyOpen = 0, kNormallyClosed = 1 };
/**
* Constructs a CANDigitalInput.
*
* @param device The Spark Max to which the limit switch is attached.
* @param limitSwitch Whether this is forward or reverse limit switch.
* @param polarity Whether the limit switch is normally open or normally
* closed.
*/
explicit CANDigitalInput(CANSparkMax& device, LimitSwitch limitSwitch,
LimitSwitchPolarity polarity);
CANDigitalInput(CANDigitalInput&&) = default;
CANDigitalInput& operator=(CANDigitalInput&&) = default;
CANDigitalInput(const CANDigitalInput&) = default;
/**
* Get the value from a digital input channel.
*
* Retrieve the value of a single digital input channel from a motor
* controller. This method will return the state of the limit input
* based on the selected polarity, whether or not it is enabled.
*/
bool Get() const;
/**
* Enables or disables controller shutdown based on limit switch.
*/
CANError EnableLimitSwitch(bool enable);
/**
* Returns true if limit switch is enabled.
*/
bool IsLimitSwitchEnabled();
private:
CANSparkMax* m_device;
LimitSwitch m_limitSwitch = LimitSwitch::kForward;
};
} // namespace rev
| [
"pavelkulik@hotmail.com"
] | pavelkulik@hotmail.com |
d8ae82c0a1fcfc19c24fe0d5c6d3eb6adf27c920 | 20319fabbb69e93f89a48f0819f4a88325852ce7 | /658-2/C.cpp | 4b282b54526d7d089ec7523a04354048f1ddd709 | [] | no_license | richzli/codeforces | 61cc9b1b1f69be61305ec062ed3069e1ee0da6d0 | fefbe3d51da6265148bcc3acdab503e397156d7e | refs/heads/master | 2021-07-18T08:33:40.089418 | 2021-07-14T07:16:28 | 2021-07-14T07:16:28 | 222,715,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,605 | cpp | #include <iostream>
#include <string>
#include <deque>
#include <vector>
using namespace std;
int t, n;
string a, b;
deque<char> A, B;
vector<int> ops;
bool reverse;
int main() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> t;
for (; t>0; t--) {
cin >> n;
cin >> a;
cin >> b;
for (char c : a) {
A.emplace_back(c);
}
for (char c : b) {
B.emplace_back(c);
}
reverse = false;
ops.clear();
while (A.size() > 0) {
if (reverse) {
if (A.front() != B.back()) {
A.pop_front();
B.pop_back();
} else {
reverse = !reverse;
if (A.back() != B.back()) {
ops.emplace_back(1);
}
ops.emplace_back(A.size());
A.pop_back();
B.pop_back();
}
} else {
if (A.back() == B.back()) {
A.pop_back();
B.pop_back();
} else {
reverse = !reverse;
if (A.front() == B.back()) {
ops.emplace_back(1);
}
ops.emplace_back(A.size());
A.pop_front();
B.pop_back();
}
}
}
cout << ops.size() << " ";
for (int i : ops) {
cout << i << " ";
}
cout << "\n";
}
} | [
"richzli01@gmail.com"
] | richzli01@gmail.com |
8b92cafb16c33e3e12dd9afe85de346ed056bbf4 | ed972cfade9539c6d1632f53ce448f410fe1f7ab | /libraries/app/database_api.cpp | a731d0c9d61c3a3eae94a944df91e8422f65d954 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | horsecoin/surfd-master | 042e6a573800ecc726d773fdfdcdca895ef0ee17 | 7892fa91305f84322b96593555d759b21dcb0bc9 | refs/heads/master | 2020-05-02T02:30:08.648667 | 2019-03-27T06:51:04 | 2019-03-27T06:51:04 | 177,705,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71,639 | cpp | #include <surf/app/api_context.hpp>
#include <surf/app/application.hpp>
#include <surf/app/database_api.hpp>
#include <surf/protocol/get_config.hpp>
#include <surf/chain/util/reward.hpp>
#include <fc/bloom_filter.hpp>
#include <fc/smart_ref_impl.hpp>
#include <fc/crypto/hex.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/algorithm/string.hpp>
#include <cctype>
#include <cfenv>
#include <iostream>
#define GET_REQUIRED_FEES_MAX_RECURSION 4
namespace surf { namespace app {
class database_api_impl;
class database_api_impl : public std::enable_shared_from_this<database_api_impl>
{
public:
database_api_impl( const surf::app::api_context& ctx );
~database_api_impl();
// Subscriptions
void set_block_applied_callback( std::function<void(const variant& block_id)> cb );
// Blocks and transactions
optional<block_header> get_block_header(uint32_t block_num)const;
optional<signed_block_api_obj> get_block(uint32_t block_num)const;
vector<applied_operation> get_ops_in_block(uint32_t block_num, bool only_virtual)const;
// Globals
fc::variant_object get_config()const;
dynamic_global_property_api_obj get_dynamic_global_properties()const;
// Keys
vector<set<string>> get_key_references( vector<public_key_type> key )const;
// Accounts
vector< extended_account > get_accounts( vector< string > names )const;
vector<account_id_type> get_account_references( account_id_type account_id )const;
vector<optional<account_api_obj>> lookup_account_names(const vector<string>& account_names)const;
set<string> lookup_accounts(const string& lower_bound_name, uint32_t limit)const;
uint64_t get_account_count()const;
// Witnesses
vector<optional<witness_api_obj>> get_witnesses(const vector<witness_id_type>& witness_ids)const;
fc::optional<witness_api_obj> get_witness_by_account( string account_name )const;
set<account_name_type> lookup_witness_accounts(const string& lower_bound_name, uint32_t limit)const;
uint64_t get_witness_count()const;
// Authority / validation
std::string get_transaction_hex(const signed_transaction& trx)const;
set<public_key_type> get_required_signatures( const signed_transaction& trx, const flat_set<public_key_type>& available_keys )const;
set<public_key_type> get_potential_signatures( const signed_transaction& trx )const;
bool verify_authority( const signed_transaction& trx )const;
bool verify_account_authority( const string& name_or_id, const flat_set<public_key_type>& signers )const;
// signal handlers
void on_applied_block( const chain::signed_block& b );
std::function<void(const fc::variant&)> _block_applied_callback;
surf::chain::database& _db;
std::shared_ptr< surf::follow::follow_api > _follow_api;
boost::signals2::scoped_connection _block_applied_connection;
bool _disable_get_block = false;
};
applied_operation::applied_operation() {}
applied_operation::applied_operation( const operation_object& op_obj )
: trx_id( op_obj.trx_id ),
block( op_obj.block ),
trx_in_block( op_obj.trx_in_block ),
op_in_trx( op_obj.op_in_trx ),
virtual_op( op_obj.virtual_op ),
timestamp( op_obj.timestamp )
{
//fc::raw::unpack( op_obj.serialized_op, op ); // g++ refuses to compile this as ambiguous
op = fc::raw::unpack< operation >( op_obj.serialized_op );
}
void find_accounts( set<string>& accounts, const discussion& d ) {
accounts.insert( d.author );
}
//////////////////////////////////////////////////////////////////////
// //
// Subscriptions //
// //
//////////////////////////////////////////////////////////////////////
void database_api::set_block_applied_callback( std::function<void(const variant& block_id)> cb )
{
my->_db.with_read_lock( [&]()
{
my->set_block_applied_callback( cb );
});
}
void database_api_impl::on_applied_block( const chain::signed_block& b )
{
try
{
_block_applied_callback( fc::variant(signed_block_header(b) ) );
}
catch( ... )
{
_block_applied_connection.release();
}
}
void database_api_impl::set_block_applied_callback( std::function<void(const variant& block_header)> cb )
{
_block_applied_callback = cb;
_block_applied_connection = connect_signal( _db.applied_block, *this, &database_api_impl::on_applied_block );
}
//////////////////////////////////////////////////////////////////////
// //
// Constructors //
// //
//////////////////////////////////////////////////////////////////////
database_api::database_api( const surf::app::api_context& ctx )
: my( new database_api_impl( ctx ) ) {}
database_api::~database_api() {}
database_api_impl::database_api_impl( const surf::app::api_context& ctx )
: _db( *ctx.app.chain_database() )
{
wlog("creating database api ${x}", ("x",int64_t(this)) );
_disable_get_block = ctx.app._disable_get_block;
try
{
ctx.app.get_plugin< follow::follow_plugin >( FOLLOW_PLUGIN_NAME );
_follow_api = std::make_shared< surf::follow::follow_api >( ctx );
}
catch( fc::assert_exception ) { ilog("Follow Plugin not loaded"); }
}
database_api_impl::~database_api_impl()
{
elog("freeing database api ${x}", ("x",int64_t(this)) );
}
void database_api::on_api_startup() {}
//////////////////////////////////////////////////////////////////////
// //
// Blocks and transactions //
// //
//////////////////////////////////////////////////////////////////////
optional<block_header> database_api::get_block_header(uint32_t block_num)const
{
FC_ASSERT( !my->_disable_get_block, "get_block_header is disabled on this node." );
return my->_db.with_read_lock( [&]()
{
return my->get_block_header( block_num );
});
}
optional<block_header> database_api_impl::get_block_header(uint32_t block_num) const
{
auto result = _db.fetch_block_by_number(block_num);
if(result)
return *result;
return {};
}
optional<signed_block_api_obj> database_api::get_block(uint32_t block_num)const
{
FC_ASSERT( !my->_disable_get_block, "get_block is disabled on this node." );
return my->_db.with_read_lock( [&]()
{
return my->get_block( block_num );
});
}
optional<signed_block_api_obj> database_api_impl::get_block(uint32_t block_num)const
{
return _db.fetch_block_by_number(block_num);
}
vector<applied_operation> database_api::get_ops_in_block(uint32_t block_num, bool only_virtual)const
{
return my->_db.with_read_lock( [&]()
{
return my->get_ops_in_block( block_num, only_virtual );
});
}
vector<applied_operation> database_api_impl::get_ops_in_block(uint32_t block_num, bool only_virtual)const
{
const auto& idx = _db.get_index< operation_index >().indices().get< by_location >();
auto itr = idx.lower_bound( block_num );
vector<applied_operation> result;
applied_operation temp;
while( itr != idx.end() && itr->block == block_num )
{
temp = *itr;
if( !only_virtual || is_virtual_operation(temp.op) )
result.push_back(temp);
++itr;
}
return result;
}
//////////////////////////////////////////////////////////////////////
// //
// Globals //
// //
//////////////////////////////////////////////////////////////////////=
fc::variant_object database_api::get_config()const
{
return my->_db.with_read_lock( [&]()
{
return my->get_config();
});
}
fc::variant_object database_api_impl::get_config()const
{
return surf::protocol::get_config();
}
dynamic_global_property_api_obj database_api::get_dynamic_global_properties()const
{
return my->_db.with_read_lock( [&]()
{
return my->get_dynamic_global_properties();
});
}
chain_properties database_api::get_chain_properties()const
{
return my->_db.with_read_lock( [&]()
{
return my->_db.get_witness_schedule_object().median_props;
});
}
dynamic_global_property_api_obj database_api_impl::get_dynamic_global_properties()const
{
return dynamic_global_property_api_obj( _db.get( dynamic_global_property_id_type() ), _db );
}
witness_schedule_api_obj database_api::get_witness_schedule()const
{
return my->_db.with_read_lock( [&]()
{
return my->_db.get(witness_schedule_id_type());
});
}
hardfork_version database_api::get_hardfork_version()const
{
return my->_db.with_read_lock( [&]()
{
return my->_db.get(hardfork_property_id_type()).current_hardfork_version;
});
}
scheduled_hardfork database_api::get_next_scheduled_hardfork() const
{
return my->_db.with_read_lock( [&]()
{
scheduled_hardfork shf;
const auto& hpo = my->_db.get(hardfork_property_id_type());
shf.hf_version = hpo.next_hardfork;
shf.live_time = hpo.next_hardfork_time;
return shf;
});
}
reward_fund_api_obj database_api::get_reward_fund( string name )const
{
return my->_db.with_read_lock( [&]()
{
auto fund = my->_db.find< reward_fund_object, by_name >( name );
FC_ASSERT( fund != nullptr, "Invalid reward fund name" );
return *fund;
});
}
//////////////////////////////////////////////////////////////////////
// //
// Keys //
// //
//////////////////////////////////////////////////////////////////////
vector<set<string>> database_api::get_key_references( vector<public_key_type> key )const
{
return my->_db.with_read_lock( [&]()
{
return my->get_key_references( key );
});
}
/**
* @return all accounts that referr to the key or account id in their owner or active authorities.
*/
vector<set<string>> database_api_impl::get_key_references( vector<public_key_type> keys )const
{
FC_ASSERT( false, "database_api::get_key_references has been deprecated. Please use account_by_key_api::get_key_references instead." );
vector< set<string> > final_result;
return final_result;
}
//////////////////////////////////////////////////////////////////////
// //
// Accounts //
// //
//////////////////////////////////////////////////////////////////////
vector< extended_account > database_api::get_accounts( vector< string > names )const
{
return my->_db.with_read_lock( [&]()
{
return my->get_accounts( names );
});
}
vector< extended_account > database_api_impl::get_accounts( vector< string > names )const
{
const auto& idx = _db.get_index< account_index >().indices().get< by_name >();
const auto& vidx = _db.get_index< witness_vote_index >().indices().get< by_account_witness >();
vector< extended_account > results;
for( auto name: names )
{
auto itr = idx.find( name );
if ( itr != idx.end() )
{
results.push_back( extended_account( *itr, _db ) );
if( _follow_api )
{
results.back().reputation = _follow_api->get_account_reputations( itr->name, 1 )[0].reputation;
}
auto vitr = vidx.lower_bound( boost::make_tuple( itr->id, witness_id_type() ) );
while( vitr != vidx.end() && vitr->account == itr->id ) {
results.back().witness_votes.insert(_db.get(vitr->witness).owner);
++vitr;
}
}
}
return results;
}
vector<account_id_type> database_api::get_account_references( account_id_type account_id )const
{
return my->_db.with_read_lock( [&]()
{
return my->get_account_references( account_id );
});
}
vector<account_id_type> database_api_impl::get_account_references( account_id_type account_id )const
{
/*const auto& idx = _db.get_index<account_index>();
const auto& aidx = dynamic_cast<const primary_index<account_index>&>(idx);
const auto& refs = aidx.get_secondary_index<surf::chain::account_member_index>();
auto itr = refs.account_to_account_memberships.find(account_id);
vector<account_id_type> result;
if( itr != refs.account_to_account_memberships.end() )
{
result.reserve( itr->second.size() );
for( auto item : itr->second ) result.push_back(item);
}
return result;*/
FC_ASSERT( false, "database_api::get_account_references --- Needs to be refactored for surf." );
}
vector<optional<account_api_obj>> database_api::lookup_account_names(const vector<string>& account_names)const
{
return my->_db.with_read_lock( [&]()
{
return my->lookup_account_names( account_names );
});
}
vector<optional<account_api_obj>> database_api_impl::lookup_account_names(const vector<string>& account_names)const
{
vector<optional<account_api_obj> > result;
result.reserve(account_names.size());
for( auto& name : account_names )
{
auto itr = _db.find< account_object, by_name >( name );
if( itr )
{
result.push_back( account_api_obj( *itr, _db ) );
}
else
{
result.push_back( optional< account_api_obj>() );
}
}
return result;
}
set<string> database_api::lookup_accounts(const string& lower_bound_name, uint32_t limit)const
{
return my->_db.with_read_lock( [&]()
{
return my->lookup_accounts( lower_bound_name, limit );
});
}
set<string> database_api_impl::lookup_accounts(const string& lower_bound_name, uint32_t limit)const
{
FC_ASSERT( limit <= 1000 );
const auto& accounts_by_name = _db.get_index<account_index>().indices().get<by_name>();
set<string> result;
for( auto itr = accounts_by_name.lower_bound(lower_bound_name);
limit-- && itr != accounts_by_name.end();
++itr )
{
result.insert(itr->name);
}
return result;
}
uint64_t database_api::get_account_count()const
{
return my->_db.with_read_lock( [&]()
{
return my->get_account_count();
});
}
uint64_t database_api_impl::get_account_count()const
{
return _db.get_index<account_index>().indices().size();
}
vector< owner_authority_history_api_obj > database_api::get_owner_history( string account )const
{
return my->_db.with_read_lock( [&]()
{
vector< owner_authority_history_api_obj > results;
const auto& hist_idx = my->_db.get_index< owner_authority_history_index >().indices().get< by_account >();
auto itr = hist_idx.lower_bound( account );
while( itr != hist_idx.end() && itr->account == account )
{
results.push_back( owner_authority_history_api_obj( *itr ) );
++itr;
}
return results;
});
}
optional< account_recovery_request_api_obj > database_api::get_recovery_request( string account )const
{
return my->_db.with_read_lock( [&]()
{
optional< account_recovery_request_api_obj > result;
const auto& rec_idx = my->_db.get_index< account_recovery_request_index >().indices().get< by_account >();
auto req = rec_idx.find( account );
if( req != rec_idx.end() )
result = account_recovery_request_api_obj( *req );
return result;
});
}
optional< escrow_api_obj > database_api::get_escrow( string from, uint32_t escrow_id )const
{
return my->_db.with_read_lock( [&]()
{
optional< escrow_api_obj > result;
try
{
result = my->_db.get_escrow( from, escrow_id );
}
catch ( ... ) {}
return result;
});
}
vector< withdraw_route > database_api::get_withdraw_routes( string account, withdraw_route_type type )const
{
return my->_db.with_read_lock( [&]()
{
vector< withdraw_route > result;
const auto& acc = my->_db.get_account( account );
if( type == outgoing || type == all )
{
const auto& by_route = my->_db.get_index< withdraw_vesting_route_index >().indices().get< by_withdraw_route >();
auto route = by_route.lower_bound( acc.id );
while( route != by_route.end() && route->from_account == acc.id )
{
withdraw_route r;
r.from_account = account;
r.to_account = my->_db.get( route->to_account ).name;
r.percent = route->percent;
r.auto_vest = route->auto_vest;
result.push_back( r );
++route;
}
}
if( type == incoming || type == all )
{
const auto& by_dest = my->_db.get_index< withdraw_vesting_route_index >().indices().get< by_destination >();
auto route = by_dest.lower_bound( acc.id );
while( route != by_dest.end() && route->to_account == acc.id )
{
withdraw_route r;
r.from_account = my->_db.get( route->from_account ).name;
r.to_account = account;
r.percent = route->percent;
r.auto_vest = route->auto_vest;
result.push_back( r );
++route;
}
}
return result;
});
}
optional< account_bandwidth_api_obj > database_api::get_account_bandwidth( string account, witness::bandwidth_type type )const
{
optional< account_bandwidth_api_obj > result;
if( my->_db.has_index< witness::account_bandwidth_index >() )
{
auto band = my->_db.find< witness::account_bandwidth_object, witness::by_account_bandwidth_type >( boost::make_tuple( account, type ) );
if( band != nullptr )
result = *band;
}
return result;
}
//////////////////////////////////////////////////////////////////////
// //
// Witnesses //
// //
//////////////////////////////////////////////////////////////////////
vector<optional<witness_api_obj>> database_api::get_witnesses(const vector<witness_id_type>& witness_ids)const
{
return my->_db.with_read_lock( [&]()
{
return my->get_witnesses( witness_ids );
});
}
vector<optional<witness_api_obj>> database_api_impl::get_witnesses(const vector<witness_id_type>& witness_ids)const
{
vector<optional<witness_api_obj>> result; result.reserve(witness_ids.size());
std::transform(witness_ids.begin(), witness_ids.end(), std::back_inserter(result),
[this](witness_id_type id) -> optional<witness_api_obj> {
if(auto o = _db.find(id))
return *o;
return {};
});
return result;
}
fc::optional<witness_api_obj> database_api::get_witness_by_account( string account_name ) const
{
return my->_db.with_read_lock( [&]()
{
return my->get_witness_by_account( account_name );
});
}
vector< witness_api_obj > database_api::get_witnesses_by_vote( string from, uint32_t limit )const
{
return my->_db.with_read_lock( [&]()
{
//idump((from)(limit));
FC_ASSERT( limit <= 100 );
vector<witness_api_obj> result;
result.reserve(limit);
const auto& name_idx = my->_db.get_index< witness_index >().indices().get< by_name >();
const auto& vote_idx = my->_db.get_index< witness_index >().indices().get< by_vote_name >();
auto itr = vote_idx.begin();
if( from.size() ) {
auto nameitr = name_idx.find( from );
FC_ASSERT( nameitr != name_idx.end(), "invalid witness name ${n}", ("n",from) );
itr = vote_idx.iterator_to( *nameitr );
}
while( itr != vote_idx.end() &&
result.size() < limit &&
itr->votes > 0 )
{
result.push_back( witness_api_obj( *itr ) );
++itr;
}
return result;
});
}
fc::optional<witness_api_obj> database_api_impl::get_witness_by_account( string account_name ) const
{
const auto& idx = _db.get_index< witness_index >().indices().get< by_name >();
auto itr = idx.find( account_name );
if( itr != idx.end() )
return witness_api_obj( *itr );
return {};
}
set< account_name_type > database_api::lookup_witness_accounts( const string& lower_bound_name, uint32_t limit ) const
{
return my->_db.with_read_lock( [&]()
{
return my->lookup_witness_accounts( lower_bound_name, limit );
});
}
set< account_name_type > database_api_impl::lookup_witness_accounts( const string& lower_bound_name, uint32_t limit ) const
{
FC_ASSERT( limit <= 1000 );
const auto& witnesses_by_id = _db.get_index< witness_index >().indices().get< by_id >();
// get all the names and look them all up, sort them, then figure out what
// records to return. This could be optimized, but we expect the
// number of witnesses to be few and the frequency of calls to be rare
set< account_name_type > witnesses_by_account_name;
for ( const witness_api_obj& witness : witnesses_by_id )
if ( witness.owner >= lower_bound_name ) // we can ignore anything below lower_bound_name
witnesses_by_account_name.insert( witness.owner );
auto end_iter = witnesses_by_account_name.begin();
while ( end_iter != witnesses_by_account_name.end() && limit-- )
++end_iter;
witnesses_by_account_name.erase( end_iter, witnesses_by_account_name.end() );
return witnesses_by_account_name;
}
uint64_t database_api::get_witness_count()const
{
return my->_db.with_read_lock( [&]()
{
return my->get_witness_count();
});
}
uint64_t database_api_impl::get_witness_count()const
{
return _db.get_index<witness_index>().indices().size();
}
//////////////////////////////////////////////////////////////////////
// //
// Authority / validation //
// //
//////////////////////////////////////////////////////////////////////
std::string database_api::get_transaction_hex(const signed_transaction& trx)const
{
return my->_db.with_read_lock( [&]()
{
return my->get_transaction_hex( trx );
});
}
std::string database_api_impl::get_transaction_hex(const signed_transaction& trx)const
{
return fc::to_hex(fc::raw::pack(trx));
}
set<public_key_type> database_api::get_required_signatures( const signed_transaction& trx, const flat_set<public_key_type>& available_keys )const
{
return my->_db.with_read_lock( [&]()
{
return my->get_required_signatures( trx, available_keys );
});
}
set<public_key_type> database_api_impl::get_required_signatures( const signed_transaction& trx, const flat_set<public_key_type>& available_keys )const
{
// wdump((trx)(available_keys));
auto result = trx.get_required_signatures( SURF_CHAIN_ID,
available_keys,
[&]( string account_name ){ return authority( _db.get< account_authority_object, by_account >( account_name ).active ); },
[&]( string account_name ){ return authority( _db.get< account_authority_object, by_account >( account_name ).owner ); },
[&]( string account_name ){ return authority( _db.get< account_authority_object, by_account >( account_name ).posting ); },
SURF_MAX_SIG_CHECK_DEPTH );
// wdump((result));
return result;
}
set<public_key_type> database_api::get_potential_signatures( const signed_transaction& trx )const
{
return my->_db.with_read_lock( [&]()
{
return my->get_potential_signatures( trx );
});
}
set<public_key_type> database_api_impl::get_potential_signatures( const signed_transaction& trx )const
{
// wdump((trx));
set<public_key_type> result;
trx.get_required_signatures(
SURF_CHAIN_ID,
flat_set<public_key_type>(),
[&]( account_name_type account_name )
{
const auto& auth = _db.get< account_authority_object, by_account >(account_name).active;
for( const auto& k : auth.get_keys() )
result.insert(k);
return authority( auth );
},
[&]( account_name_type account_name )
{
const auto& auth = _db.get< account_authority_object, by_account >(account_name).owner;
for( const auto& k : auth.get_keys() )
result.insert(k);
return authority( auth );
},
[&]( account_name_type account_name )
{
const auto& auth = _db.get< account_authority_object, by_account >(account_name).posting;
for( const auto& k : auth.get_keys() )
result.insert(k);
return authority( auth );
},
SURF_MAX_SIG_CHECK_DEPTH
);
// wdump((result));
return result;
}
bool database_api::verify_authority( const signed_transaction& trx ) const
{
return my->_db.with_read_lock( [&]()
{
return my->verify_authority( trx );
});
}
bool database_api_impl::verify_authority( const signed_transaction& trx )const
{
trx.verify_authority( SURF_CHAIN_ID,
[&]( string account_name ){ return authority( _db.get< account_authority_object, by_account >( account_name ).active ); },
[&]( string account_name ){ return authority( _db.get< account_authority_object, by_account >( account_name ).owner ); },
[&]( string account_name ){ return authority( _db.get< account_authority_object, by_account >( account_name ).posting ); },
SURF_MAX_SIG_CHECK_DEPTH );
return true;
}
bool database_api::verify_account_authority( const string& name_or_id, const flat_set<public_key_type>& signers )const
{
return my->_db.with_read_lock( [&]()
{
return my->verify_account_authority( name_or_id, signers );
});
}
bool database_api_impl::verify_account_authority( const string& name, const flat_set<public_key_type>& keys )const
{
FC_ASSERT( name.size() > 0);
auto account = _db.find< account_object, by_name >( name );
FC_ASSERT( account, "no such account" );
/// reuse trx.verify_authority by creating a dummy transfer
signed_transaction trx;
transfer_operation op;
op.from = account->name;
trx.operations.emplace_back(op);
return verify_authority( trx );
}
discussion database_api::get_content( string author, string permlink )const
{
return my->_db.with_read_lock( [&]()
{
const auto& by_permlink_idx = my->_db.get_index< comment_index >().indices().get< by_permlink >();
auto itr = by_permlink_idx.find( boost::make_tuple( author, permlink ) );
if( itr != by_permlink_idx.end() )
{
discussion result(*itr);
set_pending_payout(result);
result.active_votes = get_active_votes( author, permlink );
return result;
}
return discussion();
});
}
vector<vote_state> database_api::get_active_votes( string author, string permlink )const
{
return my->_db.with_read_lock( [&]()
{
vector<vote_state> result;
const auto& comment = my->_db.get_comment( author, permlink );
const auto& idx = my->_db.get_index<comment_vote_index>().indices().get< by_comment_voter >();
comment_id_type cid(comment.id);
auto itr = idx.lower_bound( cid );
while( itr != idx.end() && itr->comment == cid )
{
const auto& vo = my->_db.get(itr->voter);
vote_state vstate;
vstate.voter = vo.name;
vstate.weight = itr->weight;
vstate.rshares = itr->rshares;
vstate.percent = itr->vote_percent;
vstate.time = itr->last_update;
if( my->_follow_api )
{
auto reps = my->_follow_api->get_account_reputations( vo.name, 1 );
if( reps.size() )
vstate.reputation = reps[0].reputation;
}
result.push_back(vstate);
++itr;
}
return result;
});
}
vector<account_vote> database_api::get_account_votes( string voter )const
{
return my->_db.with_read_lock( [&]()
{
vector<account_vote> result;
const auto& voter_acnt = my->_db.get_account(voter);
const auto& idx = my->_db.get_index<comment_vote_index>().indices().get< by_voter_comment >();
account_id_type aid(voter_acnt.id);
auto itr = idx.lower_bound( aid );
auto end = idx.upper_bound( aid );
while( itr != end )
{
const auto& vo = my->_db.get(itr->comment);
account_vote avote;
avote.authorperm = vo.author+"/"+to_string( vo.permlink );
avote.weight = itr->weight;
avote.rshares = itr->rshares;
avote.percent = itr->vote_percent;
avote.time = itr->last_update;
result.push_back(avote);
++itr;
}
return result;
});
}
u256 to256( const fc::uint128& t )
{
u256 result( t.high_bits() );
result <<= 65;
result += t.low_bits();
return result;
}
void database_api::set_pending_payout( discussion& d )const
{
// const auto& props = my->_db.get_dynamic_global_properties();
asset pot;
pot = my->_db.get_reward_fund( my->_db.get_comment( d.author, d.permlink ) ).reward_balance;
u256 total_r2 = 0;
total_r2 = to256( my->_db.get_reward_fund( my->_db.get_comment( d.author, d.permlink ) ).recent_claims );
if( total_r2 > 0 )
{
uint128_t vshares;
const auto& rf = my->_db.get_reward_fund( my->_db.get_comment( d.author, d.permlink ) );
vshares = d.net_rshares.value > 0 ? surf::chain::util::evaluate_reward_curve( d.net_rshares.value, rf.author_reward_curve, rf.content_constant ) : 0;
u256 r2 = to256(vshares); //to256(abs_net_rshares);
r2 *= pot.amount.value;
r2 /= total_r2;
d.pending_payout_value = asset( static_cast<uint64_t>(r2), pot.symbol );
if( my->_follow_api )
{
d.author_reputation = my->_follow_api->get_account_reputations( d.author, 1 )[0].reputation;
}
}
if( d.parent_author != SURF_ROOT_POST_PARENT )
d.cashout_time = my->_db.calculate_discussion_payout_time( my->_db.get< comment_object >( d.id ) );
if( d.body.size() > 1024*128 )
d.body = "body pruned due to size";
if( d.parent_author.size() > 0 && d.body.size() > 1024*16 )
d.body = "comment pruned due to size";
set_url(d);
}
void database_api::set_url( discussion& d )const
{
const comment_api_obj root( my->_db.get< comment_object, by_id >( d.root_comment ) );
d.url = "/" + root.category + "/@" + root.author + "/" + root.permlink;
d.root_title = root.title;
if( root.id != d.id )
d.url += "#@" + d.author + "/" + d.permlink;
}
vector<discussion> database_api::get_content_replies( string author, string permlink )const
{
return my->_db.with_read_lock( [&]()
{
account_name_type acc_name = account_name_type( author );
const auto& by_permlink_idx = my->_db.get_index< comment_index >().indices().get< by_parent >();
auto itr = by_permlink_idx.find( boost::make_tuple( acc_name, permlink ) );
vector<discussion> result;
while( itr != by_permlink_idx.end() && itr->parent_author == author && to_string( itr->parent_permlink ) == permlink )
{
result.push_back( discussion( *itr ) );
set_pending_payout( result.back() );
++itr;
}
return result;
});
}
/**
* This method can be used to fetch replies to an account.
*
* The first call should be (account_to_retrieve replies, "", limit)
* Subsequent calls should be (last_author, last_permlink, limit)
*/
vector<discussion> database_api::get_replies_by_last_update( account_name_type start_parent_author, string start_permlink, uint32_t limit )const
{
return my->_db.with_read_lock( [&]()
{
vector<discussion> result;
#ifndef IS_LOW_MEM
FC_ASSERT( limit <= 100 );
const auto& last_update_idx = my->_db.get_index< comment_index >().indices().get< by_last_update >();
auto itr = last_update_idx.begin();
const account_name_type* parent_author = &start_parent_author;
if( start_permlink.size() )
{
const auto& comment = my->_db.get_comment( start_parent_author, start_permlink );
itr = last_update_idx.iterator_to( comment );
parent_author = &comment.parent_author;
}
else if( start_parent_author.size() )
{
itr = last_update_idx.lower_bound( start_parent_author );
}
result.reserve( limit );
while( itr != last_update_idx.end() && result.size() < limit && itr->parent_author == *parent_author )
{
result.push_back( *itr );
set_pending_payout(result.back());
result.back().active_votes = get_active_votes( itr->author, to_string( itr->permlink ) );
++itr;
}
#endif
return result;
});
}
map< uint32_t, applied_operation > database_api::get_account_history( string account, uint64_t from, uint32_t limit )const
{
return my->_db.with_read_lock( [&]()
{
FC_ASSERT( limit <= 10000, "Limit of ${l} is greater than maxmimum allowed", ("l",limit) );
FC_ASSERT( from >= limit, "From must be greater than limit" );
// idump((account)(from)(limit));
const auto& idx = my->_db.get_index<account_history_index>().indices().get<by_account>();
auto itr = idx.lower_bound( boost::make_tuple( account, from ) );
// if( itr != idx.end() ) idump((*itr));
// auto end = idx.upper_bound( boost::make_tuple( account, std::max( int64_t(0), int64_t(itr->sequence)-limit ) ) );
// if( end != idx.end() ) idump((*end));
uint32_t n = 0;
map<uint32_t, applied_operation> result;
while( true )
{
if( itr == idx.end() )
break;
if( itr->account != account )
break;
if( n >= limit )
break;
result[itr->sequence] = my->_db.get(itr->op);
++itr;
++n;
}
return result;
});
}
vector<pair<string,uint32_t> > database_api::get_tags_used_by_author( const string& author )const {
return my->_db.with_read_lock( [&]()
{
const auto* acnt = my->_db.find_account( author );
FC_ASSERT( acnt != nullptr );
const auto& tidx = my->_db.get_index<tags::author_tag_stats_index>().indices().get<tags::by_author_posts_tag>();
auto itr = tidx.lower_bound( boost::make_tuple( acnt->id, 0 ) );
vector<pair<string,uint32_t> > result;
while( itr != tidx.end() && itr->author == acnt->id && result.size() < 1000 ) {
result.push_back( std::make_pair(itr->tag, itr->total_posts) );
++itr;
}
return result;
} );
}
vector<tag_api_obj> database_api::get_trending_tags( string after, uint32_t limit )const
{
return my->_db.with_read_lock( [&]()
{
limit = std::min( limit, uint32_t(1000) );
vector<tag_api_obj> result;
result.reserve( limit );
const auto& nidx = my->_db.get_index<tags::tag_stats_index>().indices().get<tags::by_tag>();
const auto& ridx = my->_db.get_index<tags::tag_stats_index>().indices().get<tags::by_trending>();
auto itr = ridx.begin();
if( after != "" && nidx.size() )
{
auto nitr = nidx.lower_bound( after );
if( nitr == nidx.end() )
itr = ridx.end();
else
itr = ridx.iterator_to( *nitr );
}
while( itr != ridx.end() && result.size() < limit )
{
result.push_back( tag_api_obj( *itr ) );
++itr;
}
return result;
});
}
discussion database_api::get_discussion( comment_id_type id, uint32_t truncate_body )const
{
discussion d = my->_db.get(id);
set_url( d );
set_pending_payout( d );
d.active_votes = get_active_votes( d.author, d.permlink );
d.body_length = d.body.size();
if( truncate_body ) {
d.body = d.body.substr( 0, truncate_body );
if( !fc::is_utf8( d.body ) )
d.body = fc::prune_invalid_utf8( d.body );
}
return d;
}
template<typename Index, typename StartItr>
vector<discussion> database_api::get_discussions( const discussion_query& query,
const string& tag,
comment_id_type parent,
const Index& tidx, StartItr tidx_itr,
uint32_t truncate_body,
const std::function< bool(const comment_api_obj& ) >& filter,
const std::function< bool(const comment_api_obj& ) >& exit,
const std::function< bool(const tags::tag_object& ) >& tag_exit,
bool ignore_parent
)const
{
// idump((query));
vector<discussion> result;
const auto& cidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_comment>();
comment_id_type start;
if( query.start_author && query.start_permlink ) {
start = my->_db.get_comment( *query.start_author, *query.start_permlink ).id;
auto itr = cidx.find( start );
while( itr != cidx.end() && itr->comment == start ) {
if( itr->tag == tag ) {
tidx_itr = tidx.iterator_to( *itr );
break;
}
++itr;
}
}
uint32_t count = query.limit;
uint64_t itr_count = 0;
uint64_t filter_count = 0;
uint64_t exc_count = 0;
uint64_t max_itr_count = 10 * query.limit;
while( count > 0 && tidx_itr != tidx.end() )
{
++itr_count;
if( itr_count > max_itr_count )
{
wlog( "Maximum iteration count exceeded serving query: ${q}", ("q", query) );
wlog( "count=${count} itr_count=${itr_count} filter_count=${filter_count} exc_count=${exc_count}",
("count", count)("itr_count", itr_count)("filter_count", filter_count)("exc_count", exc_count) );
break;
}
if( tidx_itr->tag != tag || ( !ignore_parent && tidx_itr->parent != parent ) )
break;
try
{
result.push_back( get_discussion( tidx_itr->comment, truncate_body ) );
if( filter( result.back() ) )
{
result.pop_back();
++filter_count;
}
else if( exit( result.back() ) || tag_exit( *tidx_itr ) )
{
result.pop_back();
break;
}
else
--count;
}
catch ( const fc::exception& e )
{
++exc_count;
edump((e.to_detail_string()));
}
++tidx_itr;
}
return result;
}
comment_id_type database_api::get_parent( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
comment_id_type parent;
if( query.parent_author && query.parent_permlink ) {
parent = my->_db.get_comment( *query.parent_author, *query.parent_permlink ).id;
}
return parent;
});
}
vector<discussion> database_api::get_discussions_by_payout( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = get_parent( query );
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_net_rshares>();
auto tidx_itr = tidx.lower_bound( tag );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body, []( const comment_api_obj& c ){ return c.net_rshares <= 0; }, exit_default, tag_exit_default, true );
});
}
vector<discussion> database_api::get_post_discussions_by_payout( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = comment_id_type();
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_reward_fund_net_rshares>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, true ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body, []( const comment_api_obj& c ){ return c.net_rshares <= 0; }, exit_default, tag_exit_default, true );
});
}
vector<discussion> database_api::get_comment_discussions_by_payout( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = comment_id_type(1);
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_reward_fund_net_rshares>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, false ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body, []( const comment_api_obj& c ){ return c.net_rshares <= 0; }, exit_default, tag_exit_default, true );
});
}
vector<discussion> database_api::get_discussions_by_trending( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = get_parent( query );
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_parent_trending>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, parent, std::numeric_limits<double>::max() ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body, []( const comment_api_obj& c ) { return c.net_rshares <= 0; } );
});
}
vector<discussion> database_api::get_discussions_by_created( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = get_parent( query );
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_parent_created>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, parent, fc::time_point_sec::maximum() ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body );
});
}
vector<discussion> database_api::get_discussions_by_active( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = get_parent( query );
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_parent_active>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, parent, fc::time_point_sec::maximum() ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body );
});
}
vector<discussion> database_api::get_discussions_by_cashout( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
vector<discussion> result;
auto tag = fc::to_lower( query.tag );
auto parent = get_parent( query );
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_cashout>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, fc::time_point::now() - fc::minutes(60) ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body, []( const comment_api_obj& c ){ return c.net_rshares < 0; });
});
}
vector<discussion> database_api::get_discussions_by_votes( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = get_parent( query );
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_parent_net_votes>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, parent, std::numeric_limits<int32_t>::max() ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body );
});
}
vector<discussion> database_api::get_discussions_by_children( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = get_parent( query );
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_parent_children>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, parent, std::numeric_limits<int32_t>::max() ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body );
});
}
vector<discussion> database_api::get_discussions_by_hot( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
auto tag = fc::to_lower( query.tag );
auto parent = get_parent( query );
const auto& tidx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_parent_hot>();
auto tidx_itr = tidx.lower_bound( boost::make_tuple( tag, parent, std::numeric_limits<double>::max() ) );
return get_discussions( query, tag, parent, tidx, tidx_itr, query.truncate_body, []( const comment_api_obj& c ) { return c.net_rshares <= 0; } );
});
}
vector<discussion> database_api::get_discussions_by_feed( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
FC_ASSERT( my->_follow_api, "Node is not running the follow plugin" );
auto start_author = query.start_author ? *( query.start_author ) : "";
auto start_permlink = query.start_permlink ? *( query.start_permlink ) : "";
const auto& account = my->_db.get_account( query.tag );
const auto& c_idx = my->_db.get_index< follow::feed_index >().indices().get< follow::by_comment >();
const auto& f_idx = my->_db.get_index< follow::feed_index >().indices().get< follow::by_feed >();
auto feed_itr = f_idx.lower_bound( account.name );
if( start_author.size() || start_permlink.size() )
{
auto start_c = c_idx.find( boost::make_tuple( my->_db.get_comment( start_author, start_permlink ).id, account.name ) );
FC_ASSERT( start_c != c_idx.end(), "Comment is not in account's feed" );
feed_itr = f_idx.iterator_to( *start_c );
}
vector< discussion > result;
result.reserve( query.limit );
while( result.size() < query.limit && feed_itr != f_idx.end() )
{
if( feed_itr->account != account.name )
break;
try
{
result.push_back( get_discussion( feed_itr->comment ) );
if( feed_itr->first_reblogged_by != account_name_type() )
{
result.back().reblogged_by = vector<account_name_type>( feed_itr->reblogged_by.begin(), feed_itr->reblogged_by.end() );
result.back().first_reblogged_by = feed_itr->first_reblogged_by;
result.back().first_reblogged_on = feed_itr->first_reblogged_on;
}
}
catch ( const fc::exception& e )
{
edump((e.to_detail_string()));
}
++feed_itr;
}
return result;
});
}
vector<discussion> database_api::get_discussions_by_blog( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
query.validate();
FC_ASSERT( my->_follow_api, "Node is not running the follow plugin" );
auto start_author = query.start_author ? *( query.start_author ) : "";
auto start_permlink = query.start_permlink ? *( query.start_permlink ) : "";
const auto& account = my->_db.get_account( query.tag );
const auto& tag_idx = my->_db.get_index<tags::tag_index>().indices().get<tags::by_comment>();
const auto& c_idx = my->_db.get_index< follow::blog_index >().indices().get< follow::by_comment >();
const auto& b_idx = my->_db.get_index< follow::blog_index >().indices().get< follow::by_blog >();
auto blog_itr = b_idx.lower_bound( account.name );
if( start_author.size() || start_permlink.size() )
{
auto start_c = c_idx.find( boost::make_tuple( my->_db.get_comment( start_author, start_permlink ).id, account.name ) );
FC_ASSERT( start_c != c_idx.end(), "Comment is not in account's blog" );
blog_itr = b_idx.iterator_to( *start_c );
}
vector< discussion > result;
result.reserve( query.limit );
while( result.size() < query.limit && blog_itr != b_idx.end() )
{
if( blog_itr->account != account.name )
break;
try
{
if( query.select_authors.size() &&
query.select_authors.find( blog_itr->account ) == query.select_authors.end() ) {
++blog_itr;
continue;
}
if( query.select_tags.size() ) {
auto tag_itr = tag_idx.lower_bound( blog_itr->comment );
bool found = false;
while( tag_itr != tag_idx.end() && tag_itr->comment == blog_itr->comment ) {
if( query.select_tags.find( tag_itr->tag ) != query.select_tags.end() ) {
found = true; break;
}
++tag_itr;
}
if( !found ) {
++blog_itr;
continue;
}
}
result.push_back( get_discussion( blog_itr->comment, query.truncate_body ) );
if( blog_itr->reblogged_on > time_point_sec() )
{
result.back().first_reblogged_on = blog_itr->reblogged_on;
}
}
catch ( const fc::exception& e )
{
edump((e.to_detail_string()));
}
++blog_itr;
}
return result;
});
}
vector<discussion> database_api::get_discussions_by_comments( const discussion_query& query )const
{
return my->_db.with_read_lock( [&]()
{
vector< discussion > result;
#ifndef IS_LOW_MEM
query.validate();
FC_ASSERT( query.start_author, "Must get comments for a specific author" );
auto start_author = *( query.start_author );
auto start_permlink = query.start_permlink ? *( query.start_permlink ) : "";
const auto& c_idx = my->_db.get_index< comment_index >().indices().get< by_permlink >();
const auto& t_idx = my->_db.get_index< comment_index >().indices().get< by_author_last_update >();
auto comment_itr = t_idx.lower_bound( start_author );
if( start_permlink.size() )
{
auto start_c = c_idx.find( boost::make_tuple( start_author, start_permlink ) );
FC_ASSERT( start_c != c_idx.end(), "Comment is not in account's comments" );
comment_itr = t_idx.iterator_to( *start_c );
}
result.reserve( query.limit );
while( result.size() < query.limit && comment_itr != t_idx.end() )
{
if( comment_itr->author != start_author )
break;
if( comment_itr->parent_author.size() > 0 )
{
try
{
result.push_back( get_discussion( comment_itr->id ) );
}
catch( const fc::exception& e )
{
edump( (e.to_detail_string() ) );
}
}
++comment_itr;
}
#endif
return result;
});
}
/**
* This call assumes root already stored as part of state, it will
* modify root.replies to contain links to the reply posts and then
* add the reply discussions to the state. This method also fetches
* any accounts referenced by authors.
*
*/
void database_api::recursively_fetch_content( state& _state, discussion& root, set<string>& referenced_accounts )const
{
return my->_db.with_read_lock( [&]()
{
try
{
if( root.author.size() )
referenced_accounts.insert(root.author);
auto replies = get_content_replies( root.author, root.permlink );
for( auto& r : replies )
{
try
{
recursively_fetch_content( _state, r, referenced_accounts );
root.replies.push_back( r.author + "/" + r.permlink );
_state.content[r.author+"/"+r.permlink] = std::move(r);
if( r.author.size() )
referenced_accounts.insert(r.author);
}
catch ( const fc::exception& e )
{
edump((e.to_detail_string()));
}
}
}
FC_CAPTURE_AND_RETHROW( (root.author)(root.permlink) )
});
}
vector<account_name_type> database_api::get_miner_queue()const
{
return my->_db.with_read_lock( [&]()
{
vector<account_name_type> result;
const auto& pow_idx = my->_db.get_index<witness_index>().indices().get<by_pow>();
auto itr = pow_idx.upper_bound(0);
while( itr != pow_idx.end() ) {
if( itr->pow_worker )
result.push_back( itr->owner );
++itr;
}
return result;
});
}
vector< account_name_type > database_api::get_active_witnesses()const
{
return my->_db.with_read_lock( [&]()
{
const auto& wso = my->_db.get_witness_schedule_object();
size_t n = wso.current_shuffled_witnesses.size();
vector< account_name_type > result;
result.reserve( n );
for( size_t i=0; i<n; i++ )
result.push_back( wso.current_shuffled_witnesses[i] );
return result;
});
}
vector<discussion> database_api::get_discussions_by_author_before_date(
string author, string start_permlink, time_point_sec before_date, uint32_t limit )const
{
return my->_db.with_read_lock( [&]()
{
try
{
vector<discussion> result;
#ifndef IS_LOW_MEM
FC_ASSERT( limit <= 100 );
result.reserve( limit );
uint32_t count = 0;
const auto& didx = my->_db.get_index<comment_index>().indices().get<by_author_last_update>();
if( before_date == time_point_sec() )
before_date = time_point_sec::maximum();
auto itr = didx.lower_bound( boost::make_tuple( author, time_point_sec::maximum() ) );
if( start_permlink.size() )
{
const auto& comment = my->_db.get_comment( author, start_permlink );
if( comment.created < before_date )
itr = didx.iterator_to(comment);
}
while( itr != didx.end() && itr->author == author && count < limit )
{
if( itr->parent_author.size() == 0 )
{
result.push_back( *itr );
set_pending_payout( result.back() );
result.back().active_votes = get_active_votes( itr->author, to_string( itr->permlink ) );
++count;
}
++itr;
}
#endif
return result;
}
FC_CAPTURE_AND_RETHROW( (author)(start_permlink)(before_date)(limit) )
});
}
vector< vesting_delegation_api_obj > database_api::get_vesting_delegations( string account, string from, uint32_t limit )const
{
FC_ASSERT( limit <= 1000 );
return my->_db.with_read_lock( [&]()
{
vector< vesting_delegation_api_obj > result;
result.reserve( limit );
const auto& delegation_idx = my->_db.get_index< vesting_delegation_index, by_delegation >();
auto itr = delegation_idx.lower_bound( boost::make_tuple( account, from ) );
while( result.size() < limit && itr != delegation_idx.end() && itr->delegator == account )
{
result.push_back( *itr );
++itr;
}
return result;
});
}
vector< vesting_delegation_expiration_api_obj > database_api::get_expiring_vesting_delegations( string account, time_point_sec from, uint32_t limit )const
{
FC_ASSERT( limit <= 1000 );
return my->_db.with_read_lock( [&]()
{
vector< vesting_delegation_expiration_api_obj > result;
result.reserve( limit );
const auto& exp_idx = my->_db.get_index< vesting_delegation_expiration_index, by_account_expiration >();
auto itr = exp_idx.lower_bound( boost::make_tuple( account, from ) );
while( result.size() < limit && itr != exp_idx.end() && itr->delegator == account )
{
result.push_back( *itr );
++itr;
}
return result;
});
}
state database_api::get_state( string path )const
{
return my->_db.with_read_lock( [&]()
{
state _state;
_state.props = get_dynamic_global_properties();
_state.current_route = path;
try {
if( path.size() && path[0] == '/' )
path = path.substr(1); /// remove '/' from front
if( !path.size() )
path = "trending";
/// FETCH CATEGORY STATE
auto trending_tags = get_trending_tags( std::string(), 50 );
for( const auto& t : trending_tags )
{
_state.tag_idx.trending.push_back( string( t.name ) );
}
/// END FETCH CATEGORY STATE
set<string> accounts;
vector<string> part; part.reserve(4);
boost::split( part, path, boost::is_any_of("/") );
part.resize(std::max( part.size(), size_t(4) ) ); // at least 4
auto tag = fc::to_lower( part[1] );
if( part[0].size() && part[0][0] == '@' ) {
auto acnt = part[0].substr(1);
_state.accounts[acnt] = extended_account( my->_db.get_account(acnt), my->_db );
_state.accounts[acnt].tags_usage = get_tags_used_by_author( acnt );
if( my->_follow_api )
{
_state.accounts[acnt].guest_bloggers = my->_follow_api->get_blog_authors( acnt );
_state.accounts[acnt].reputation = my->_follow_api->get_account_reputations( acnt, 1 )[0].reputation;
}
auto& eacnt = _state.accounts[acnt];
if( part[1] == "transfers" ) {
auto history = get_account_history( acnt, uint64_t(-1), 10000 );
for( auto& item : history ) {
switch( item.second.op.which() ) {
case operation::tag<transfer_to_vesting_operation>::value:
case operation::tag<withdraw_vesting_operation>::value:
case operation::tag<transfer_operation>::value:
case operation::tag<author_reward_operation>::value:
case operation::tag<curation_reward_operation>::value:
case operation::tag<comment_benefactor_reward_operation>::value:
case operation::tag<escrow_transfer_operation>::value:
case operation::tag<escrow_approve_operation>::value:
case operation::tag<escrow_dispute_operation>::value:
case operation::tag<escrow_release_operation>::value:
case operation::tag<claim_reward_balance_operation>::value:
eacnt.transfer_history[item.first] = item.second;
break;
case operation::tag<comment_operation>::value:
// eacnt.post_history[item.first] = item.second;
break;
case operation::tag<vote_operation>::value:
case operation::tag<account_witness_vote_operation>::value:
case operation::tag<account_witness_proxy_operation>::value:
// eacnt.vote_history[item.first] = item.second;
break;
case operation::tag<account_create_operation>::value:
case operation::tag<account_update_operation>::value:
case operation::tag<witness_update_operation>::value:
case operation::tag<custom_operation>::value:
case operation::tag<producer_reward_operation>::value:
default:
eacnt.other_history[item.first] = item.second;
}
}
} else if( part[1] == "recent-replies" ) {
auto replies = get_replies_by_last_update( acnt, "", 50 );
eacnt.recent_replies = vector<string>();
for( const auto& reply : replies ) {
auto reply_ref = reply.author+"/"+reply.permlink;
_state.content[ reply_ref ] = reply;
if( my->_follow_api )
{
_state.accounts[ reply_ref ].reputation = my->_follow_api->get_account_reputations( reply.author, 1 )[0].reputation;
}
eacnt.recent_replies->push_back( reply_ref );
}
}
else if( part[1] == "posts" || part[1] == "comments" )
{
#ifndef IS_LOW_MEM
int count = 0;
const auto& pidx = my->_db.get_index<comment_index>().indices().get<by_author_last_update>();
auto itr = pidx.lower_bound( acnt );
eacnt.comments = vector<string>();
while( itr != pidx.end() && itr->author == acnt && count < 20 )
{
if( itr->parent_author.size() )
{
const auto link = acnt + "/" + to_string( itr->permlink );
eacnt.comments->push_back( link );
_state.content[ link ] = *itr;
set_pending_payout( _state.content[ link ] );
++count;
}
++itr;
}
#endif
}
else if( part[1].size() == 0 || part[1] == "blog" )
{
if( my->_follow_api )
{
auto blog = my->_follow_api->get_blog_entries( eacnt.name, 0, 20 );
eacnt.blog = vector< string >();
for( auto b: blog )
{
const auto link = b.author + "/" + b.permlink;
eacnt.blog->push_back( link );
_state.content[ link ] = my->_db.get_comment( b.author, b.permlink );
set_pending_payout( _state.content[ link ] );
if( b.reblog_on > time_point_sec() )
{
_state.content[ link ].first_reblogged_on = b.reblog_on;
}
}
}
}
else if( part[1].size() == 0 || part[1] == "feed" )
{
if( my->_follow_api )
{
auto feed = my->_follow_api->get_feed_entries( eacnt.name, 0, 20 );
eacnt.feed = vector<string>();
for( auto f: feed )
{
const auto link = f.author + "/" + f.permlink;
eacnt.feed->push_back( link );
_state.content[ link ] = my->_db.get_comment( f.author, f.permlink );
set_pending_payout( _state.content[ link ] );
if( f.reblog_by.size() )
{
if( f.reblog_by.size() )
_state.content[link].first_reblogged_by = f.reblog_by[0];
_state.content[link].reblogged_by = f.reblog_by;
_state.content[link].first_reblogged_on = f.reblog_on;
}
}
}
}
}
/// pull a complete discussion
else if( part[1].size() && part[1][0] == '@' ) {
auto account = part[1].substr( 1 );
auto slug = part[2];
auto key = account +"/" + slug;
auto dis = get_content( account, slug );
recursively_fetch_content( _state, dis, accounts );
_state.content[key] = std::move(dis);
}
else if( part[0] == "witnesses" || part[0] == "~witnesses") {
auto wits = get_witnesses_by_vote( "", 50 );
for( const auto& w : wits ) {
_state.witnesses[w.owner] = w;
}
_state.pow_queue = get_miner_queue();
}
else if( part[0] == "trending" )
{
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_discussions_by_trending( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.trending.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "payout" )
{
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_post_discussions_by_payout( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.payout.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "payout_comments" )
{
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_comment_discussions_by_payout( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.payout_comments.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "responses" ) {
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_discussions_by_children( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.responses.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( !part[0].size() || part[0] == "hot" ) {
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_discussions_by_hot( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.hot.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "votes" ) {
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_discussions_by_votes( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.votes.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "cashout" ) {
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_discussions_by_cashout( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.cashout.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "active" ) {
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_discussions_by_active( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.active.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "created" ) {
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_discussions_by_created( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.created.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "recent" ) {
discussion_query q;
q.tag = tag;
q.limit = 20;
q.truncate_body = 1024;
auto trending_disc = get_discussions_by_created( q );
auto& didx = _state.discussion_idx[tag];
for( const auto& d : trending_disc ) {
auto key = d.author +"/" + d.permlink;
didx.created.push_back( key );
if( d.author.size() ) accounts.insert(d.author);
_state.content[key] = std::move(d);
}
}
else if( part[0] == "tags" )
{
_state.tag_idx.trending.clear();
auto trending_tags = get_trending_tags( std::string(), 250 );
for( const auto& t : trending_tags )
{
string name = t.name;
_state.tag_idx.trending.push_back( name );
_state.tags[ name ] = t;
}
}
else {
elog( "What... no matches" );
}
for( const auto& a : accounts )
{
_state.accounts.erase("");
_state.accounts[a] = extended_account( my->_db.get_account( a ), my->_db );
if( my->_follow_api )
{
_state.accounts[a].reputation = my->_follow_api->get_account_reputations( a, 1 )[0].reputation;
}
}
for( auto& d : _state.content ) {
d.second.active_votes = get_active_votes( d.second.author, d.second.permlink );
}
_state.witness_schedule = my->_db.get_witness_schedule_object();
} catch ( const fc::exception& e ) {
_state.error = e.to_detail_string();
}
return _state;
});
}
annotated_signed_transaction database_api::get_transaction( transaction_id_type id )const
{
#ifdef SKIP_BY_TX_ID
FC_ASSERT( false, "This node's operator has disabled operation indexing by transaction_id" );
#else
return my->_db.with_read_lock( [&](){
const auto& idx = my->_db.get_index<operation_index>().indices().get<by_transaction_id>();
auto itr = idx.lower_bound( id );
if( itr != idx.end() && itr->trx_id == id ) {
auto blk = my->_db.fetch_block_by_number( itr->block );
FC_ASSERT( blk.valid() );
FC_ASSERT( blk->transactions.size() > itr->trx_in_block );
annotated_signed_transaction result = blk->transactions[itr->trx_in_block];
result.block_num = itr->block;
result.transaction_num = itr->trx_in_block;
return result;
}
FC_ASSERT( false, "Unknown Transaction ${t}", ("t",id));
});
#endif
}
} } // surf::app
| [
"nickmthompson@mail.com"
] | nickmthompson@mail.com |
7f83c269740fc9a198d83ec9a3a27269b520cce5 | eb2ecd17bc9e72dc02cf9296e4179fcf81fda353 | /ProjectEuler/ProjectEuler/ConfirmedSolutions.h | 09fe44c195d6ea7866b0629526231cd44a09c5d2 | [] | no_license | Schwarf/MyEP | 35ba27a96aa2887f5d6fe406b9449c7a1ae1c598 | fe978de3c52f4e9f1a26925535897c3ce4158b18 | refs/heads/master | 2020-04-01T07:27:36.737408 | 2018-10-14T15:59:50 | 2018-10-14T15:59:50 | 152,990,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | h | constexpr int Solution7Result = 104743;
constexpr int Solution12Result = 76576500;
constexpr long long int Solution13Result = 5537376230ull;
constexpr int Solution14Result = 837799;
constexpr long long int Solution15Result = 137846528820; // use 40!/20!/20!
constexpr int Solution16Result = 1366;
constexpr int Solution18Result = 1074;
constexpr int Solution20Result = 648;
constexpr int Solution23Result = 4179871;
constexpr int Solution25Result = 4782;
constexpr int Solution67Result = 7273;
| [
"andreas.b.scharf@gmail.com"
] | andreas.b.scharf@gmail.com |
d165a6dc643a84f19237cf7dbcdaf7c91051b51f | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_log_747.cpp | 42335e70b76ee2ce8aa2bc444b1461fd5dc9c86f | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 93 | cpp | archive_set_error(&a->archive, errno,
"Can't read temporary file(%jd)", (intmax_t)rs); | [
"993273596@qq.com"
] | 993273596@qq.com |
17814fc18f7f28fe43f58daec13d8f1e44944117 | 7f45fa54386a7e2bb86b4bcfb04ff0a31d63703c | /algorithms/0553/optimalDivision.cc | d242080313e0c6a849d3ce0ee9e18b2bc6ae1e67 | [] | no_license | ejunjsh/leetcode | e3ca7e30eea89dd345b286264bd64695e5faaf73 | 5aa8d70939acd9180c1e8d351a72b2cfcd4ff04f | refs/heads/master | 2021-08-31T22:19:20.522206 | 2021-08-25T07:47:47 | 2021-08-25T07:47:47 | 160,124,292 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cc | class Solution {
public:
string optimalDivision(vector<int>& nums) {
string ans;
if(!nums.size()) return ans;
ans = to_string(nums[0]);
if(nums.size()==1) return ans;
if(nums.size()==2) return ans + "/" + to_string(nums[1]);
ans += "/(" + to_string(nums[1]);
for(int i = 2; i < nums.size();++i)
ans += "/" + to_string(nums[i]);
ans += ")";
return ans;
}
}; | [
"sjj050121014@163.com"
] | sjj050121014@163.com |
3f0bc01604d5c3d7ac12cbacda5c819703bbca26 | d15974bd9be637c6a9fb334b01799e4aef5a2939 | /atmos-master/src/walletdb.cpp | d50392888fbf5a17242272938cfc27a99a9cdb8d | [
"MIT"
] | permissive | asphyxiating/atmostemp | 1d4b8eda5d0505550036cb74a6e22f89420e16cb | 11ece5f71585b7d6c72925f92460714dfccdbdd3 | refs/heads/master | 2021-01-19T04:28:22.884122 | 2017-04-06T02:08:38 | 2017-04-06T02:08:38 | 87,375,279 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,347 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletdb.h"
#include "base58.h"
#include "protocol.h"
#include "serialize.h"
#include "sync.h"
#include "wallet.h"
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
using namespace std;
using namespace boost;
static uint64_t nAccountingEntryNumber = 0;
extern bool fWalletUnlockStakingOnly;
//
// CWalletDB
//
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
{
nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName);
}
bool CWalletDB::EraseName(const string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress));
}
bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("tx"), hash), wtx);
}
bool CWalletDB::EraseTx(uint256 hash)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("tx"), hash));
}
bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta, false))
return false;
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
const std::vector<unsigned char>& vchCryptedSecret,
const CKeyMetadata &keyMeta)
{
const bool fEraseUnencryptedKey = true;
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta))
return false;
if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false))
return false;
if (fEraseUnencryptedKey)
{
Erase(std::make_pair(std::string("key"), vchPubKey));
Erase(std::make_pair(std::string("wkey"), vchPubKey));
}
return true;
}
bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
}
bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("cscript"), hash), redeemScript, false);
}
bool CWalletDB::WriteBestBlock(const CBlockLocator& locator)
{
nWalletDBUpdated++;
return Write(std::string("bestblock"), locator);
}
bool CWalletDB::ReadBestBlock(CBlockLocator& locator)
{
return Read(std::string("bestblock"), locator);
}
bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext)
{
nWalletDBUpdated++;
return Write(std::string("orderposnext"), nOrderPosNext);
}
bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey)
{
nWalletDBUpdated++;
return Write(std::string("defaultkey"), vchPubKey);
}
bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool)
{
return Read(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::ErasePool(int64_t nPool)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("pool"), nPool));
}
bool CWalletDB::WriteMinVersion(int nVersion)
{
return Write(std::string("minversion"), nVersion);
}
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
{
account.SetNull();
return Read(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
{
return Write(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
{
return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
}
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
{
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
}
int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount)
{
list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
int64_t nCreditDebit = 0;
BOOST_FOREACH (const CAccountingEntry& entry, entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
}
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "acentry")
break;
CAccountingEntry acentry;
ssKey >> acentry.strAccount;
if (!fAllAccounts && acentry.strAccount != strAccount)
break;
ssValue >> acentry;
ssKey >> acentry.nEntryNo;
entries.push_back(acentry);
}
pcursor->close();
}
DBErrors
CWalletDB::ReorderTransactions(CWallet* pwallet)
{
LOCK(pwallet->cs_wallet);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64_t, TxPair > TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
ListAccountCreditDebit("", acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
int64_t& nOrderPosNext = pwallet->nOrderPosNext;
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
WriteOrderPosNext(nOrderPosNext);
return DB_LOAD_OK;
}
class CWalletScanState {
public:
unsigned int nKeys;
unsigned int nCKeys;
unsigned int nKeyMeta;
bool fIsEncrypted;
bool fAnyUnordered;
int nFileVersion;
vector<uint256> vWalletUpgrade;
CWalletScanState() {
nKeys = nCKeys = nKeyMeta = 0;
fIsEncrypted = false;
fAnyUnordered = false;
nFileVersion = 0;
}
};
bool
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
CWalletScanState &wss, string& strType, string& strErr)
{
try {
// Unserialize
// Taking advantage of the fact that pair serialization
// is just the two items serialized one after the other
ssKey >> strType;
if (strType == "name")
{
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()];
}
else if (strType == "tx")
{
uint256 hash;
ssKey >> hash;
CWalletTx& wtx = pwallet->mapWallet[hash];
ssValue >> wtx;
if (wtx.CheckTransaction() && (wtx.GetHash() == hash))
wtx.BindWallet(pwallet);
else
{
pwallet->mapWallet.erase(hash);
return false;
}
// Undo serialize changes in 31600
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
{
if (!ssValue.empty())
{
char fTmp;
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString());
wtx.fTimeReceivedIsTxTime = fTmp;
}
else
{
strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
wtx.fTimeReceivedIsTxTime = 0;
}
wss.vWalletUpgrade.push_back(hash);
}
if (wtx.nOrderPos == -1)
wss.fAnyUnordered = true;
//// debug print
//LogPrintf("LoadWallet %s\n", wtx.GetHash().ToString());
//LogPrintf(" %12d %s %s %s\n",
// wtx.vout[0].nValue,
// DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()),
// wtx.hashBlock.ToString(),
// wtx.mapValue["message"]);
}
else if (strType == "acentry")
{
string strAccount;
ssKey >> strAccount;
uint64_t nNumber;
ssKey >> nNumber;
if (nNumber > nAccountingEntryNumber)
nAccountingEntryNumber = nNumber;
if (!wss.fAnyUnordered)
{
CAccountingEntry acentry;
ssValue >> acentry;
if (acentry.nOrderPos == -1)
wss.fAnyUnordered = true;
}
}
else if (strType == "key" || strType == "wkey")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
if (!vchPubKey.IsValid())
{
strErr = "Error reading wallet database: CPubKey corrupt";
return false;
}
CKey key;
CPrivKey pkey;
uint256 hash = 0;
if (strType == "key")
{
wss.nKeys++;
ssValue >> pkey;
} else {
CWalletKey wkey;
ssValue >> wkey;
pkey = wkey.vchPrivKey;
}
// Old wallets store keys as "key" [pubkey] => [privkey]
// ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
// using EC operations as a checksum.
// Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
// remaining backwards-compatible.
try
{
ssValue >> hash;
}
catch(...){}
bool fSkipCheck = false;
if (hash != 0)
{
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + pkey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
if (Hash(vchKey.begin(), vchKey.end()) != hash)
{
strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
return false;
}
fSkipCheck = true;
}
if (!key.Load(pkey, vchPubKey, fSkipCheck))
{
strErr = "Error reading wallet database: CPrivKey corrupt";
return false;
}
if (!pwallet->LoadKey(key, vchPubKey))
{
strErr = "Error reading wallet database: LoadKey failed";
return false;
}
}
else if (strType == "mkey")
{
unsigned int nID;
ssKey >> nID;
CMasterKey kMasterKey;
ssValue >> kMasterKey;
if(pwallet->mapMasterKeys.count(nID) != 0)
{
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
return false;
}
pwallet->mapMasterKeys[nID] = kMasterKey;
if (pwallet->nMasterKeyMaxID < nID)
pwallet->nMasterKeyMaxID = nID;
}
else if (strType == "ckey")
{
wss.nCKeys++;
vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
{
strErr = "Error reading wallet database: LoadCryptedKey failed";
return false;
}
wss.fIsEncrypted = true;
}
else if (strType == "keymeta")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
CKeyMetadata keyMeta;
ssValue >> keyMeta;
wss.nKeyMeta++;
pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
// find earliest key creation time, as wallet birthday
if (!pwallet->nTimeFirstKey ||
(keyMeta.nCreateTime < pwallet->nTimeFirstKey))
pwallet->nTimeFirstKey = keyMeta.nCreateTime;
}
else if (strType == "defaultkey")
{
ssValue >> pwallet->vchDefaultKey;
}
else if (strType == "pool")
{
int64_t nIndex;
ssKey >> nIndex;
CKeyPool keypool;
ssValue >> keypool;
pwallet->setKeyPool.insert(nIndex);
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (pwallet->mapKeyMetadata.count(keyid) == 0)
pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
else if (strType == "version")
{
ssValue >> wss.nFileVersion;
if (wss.nFileVersion == 10300)
wss.nFileVersion = 300;
}
else if (strType == "cscript")
{
uint160 hash;
ssKey >> hash;
CScript script;
ssValue >> script;
if (!pwallet->LoadCScript(script))
{
strErr = "Error reading wallet database: LoadCScript failed";
return false;
}
}
else if (strType == "orderposnext")
{
ssValue >> pwallet->nOrderPosNext;
}
} catch (...)
{
return false;
}
return true;
}
static bool IsKeyType(string strType)
{
return (strType== "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
}
DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
pwallet->vchDefaultKey = CPubKey();
CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
try {
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
// Try to be tolerant of single corrupt records:
string strType, strErr;
if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
{
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
if (IsKeyType(strType))
result = DB_CORRUPT;
else
{
// Leave other errors alone, if we try to fix them we might make things worse.
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == "tx")
// Rescan if there is a bad transaction record:
SoftSetBoolArg("-rescan", true);
}
}
if (!strErr.empty())
LogPrintf("%s\n", strErr);
}
pcursor->close();
}
catch (boost::thread_interrupted) {
throw;
}
catch (...) {
result = DB_CORRUPT;
}
if (fNoncriticalErrors && result == DB_LOAD_OK)
result = DB_NONCRITICAL_ERROR;
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
if (result != DB_LOAD_OK)
return result;
LogPrintf("nFileVersion = %d\n", wss.nFileVersion);
LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
// nTimeFirstKey is only reliable if all keys have metadata
if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
WriteTx(hash, pwallet->mapWallet[hash]);
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
return DB_NEED_REWRITE;
if (wss.nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
if (wss.fAnyUnordered)
result = ReorderTransactions(pwallet);
return result;
}
void ThreadFlushWalletDB(const string& strFile)
{
// Make this thread recognisable as the wallet flushing thread
RenameThread("atmos-wallet");
static bool fOneThread;
if (fOneThread)
return;
fOneThread = true;
if (!GetBoolArg("-flushwallet", true))
return;
unsigned int nLastSeen = nWalletDBUpdated;
unsigned int nLastFlushed = nWalletDBUpdated;
int64_t nLastWalletUpdate = GetTime();
while (true)
{
MilliSleep(500);
if (nLastSeen != nWalletDBUpdated)
{
nLastSeen = nWalletDBUpdated;
nLastWalletUpdate = GetTime();
}
if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
{
TRY_LOCK(bitdb.cs_db,lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
while (mi != bitdb.mapFileUseCount.end())
{
nRefCount += (*mi).second;
mi++;
}
if (nRefCount == 0)
{
boost::this_thread::interruption_point();
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
if (mi != bitdb.mapFileUseCount.end())
{
LogPrint("db", "Flushing wallet.dat\n");
nLastFlushed = nWalletDBUpdated;
int64_t nStart = GetTimeMillis();
// Flush wallet.dat so it's self contained
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(mi++);
LogPrint("db", "Flushed wallet.dat %dms\n", GetTimeMillis() - nStart);
}
}
}
}
}
}
bool BackupWallet(const CWallet& wallet, const string& strDest)
{
if (!wallet.fFileBacked)
return false;
while (true)
{
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
{
// Flush log data to the dat file
bitdb.CloseDb(wallet.strWalletFile);
bitdb.CheckpointLSN(wallet.strWalletFile);
bitdb.mapFileUseCount.erase(wallet.strWalletFile);
// Copy wallet.dat
filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
filesystem::path pathDest(strDest);
if (filesystem::is_directory(pathDest))
pathDest /= wallet.strWalletFile;
try {
#if BOOST_VERSION >= 104000
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
#else
filesystem::copy_file(pathSrc, pathDest);
#endif
LogPrintf("copied wallet.dat to %s\n", pathDest.string());
return true;
} catch(const filesystem::filesystem_error &e) {
LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what());
return false;
}
}
}
MilliSleep(100);
}
return false;
}
//
// Try to (very carefully!) recover wallet.dat if there is a problem.
//
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
{
// Recovery procedure:
// move wallet.dat to wallet.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to wallet.dat
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
std::string newFilename = strprintf("wallet.%d.bak", now);
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
bool fSuccess = allOK;
Db* pdbCopy = new Db(&dbenv.dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0)
{
LogPrintf("Cannot create database file %s\n", filename);
return false;
}
CWallet dummyWallet;
CWalletScanState wss;
DbTxn* ptxn = dbenv.TxnBegin();
BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
{
if (fOnlyKeys)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
string strType, strErr;
bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
wss, strType, strErr);
if (!IsKeyType(strType))
continue;
if (!fReadOK)
{
LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr);
continue;
}
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
delete pdbCopy;
return fSuccess;
}
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
{
return CWalletDB::Recover(dbenv, filename, false);
}
| [
"asphyxia@novusphere.io"
] | asphyxia@novusphere.io |
e38a537fbc03611fb244fde247c49a66d828d871 | 2f03b49a8948ed0b1cde6fe2b896b71bc008125c | /defenceSolution/defence/Map.h | 0c657c24741bd07eeb8197459510f5cb51aededd | [] | no_license | markus456/peliohjelmointi | 666cccdb1d07e38352904401f44f8f1cd954003b | 196904e4cddc43564edf8e65c5fa9a828de7b443 | refs/heads/master | 2020-04-08T06:30:11.260359 | 2014-05-05T11:48:25 | 2014-05-05T11:48:25 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 604 | h | #include <fstream>
#include <SDL.h>
const int TILE_GRASS = 0;
const int TILE_WATER = 1;
const int TOTAL_TILES = 2; //monta eri tiiltä sheetissä
const int TILE_SIZE = 32; //tiilen koko pikseleinä(neliö), käytetään position määrittämiseen
class Map //alustaa ja piirtää kartan
{
private:
SDL_Surface* terrainTiles; //tiilien kuvat
SDL_Rect gTileClips[TOTAL_TILES]; //tiilien kuvat pilkottuna
public:
Map();
~Map();
void LoadImage(std::string imagename, SDL_Surface* screenSurface); //lataa spritesheetin, eli tiilien kuvat
void setTiles(Tile* tiles[]); //asettaa kartan
}; | [
"markus.makela@metropolia.fi"
] | markus.makela@metropolia.fi |
d0d6fdd3981ffccbcfacaddb3aade7fce368e875 | d66c0c9002a4c32262cd9308fb5a1b3bb6c81523 | /chapter01/1.05.cpp | 93f7edff03d13f988cdcf313fb48fb4a53d78ae6 | [] | no_license | joaorlima/CppPrimer | 02936c473e257bb2e3062197253a15b31e82ec55 | 71600446eae50544d5e333feeb51d1d4dc007561 | refs/heads/master | 2020-03-28T21:26:31.869712 | 2018-09-17T16:41:46 | 2018-09-17T16:41:46 | 149,155,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 299 | cpp | #include <iostream>
int main()
{
std::cout << "Enter two numbers: " << std::endl;
int a = 0, b = 0;
std::cin >> a >> b;
std::cout << "The sum of " << a << std::endl;
std::cout << "and " << b << std::endl;
std::cout << "is equal to " << a + b << std::endl;
return 0;
}
| [
"joao.rlima@hotmail.com"
] | joao.rlima@hotmail.com |
36550c73aebb9c4249afe442250b659a9f33f676 | 049e954758b66dd033cdc696655df1b06886db1e | /zetasql/public/functions/date_time_util_internal.h | 7ee68d78e045bbd49a821015301be8f002b4a053 | [
"Apache-2.0"
] | permissive | SINHASantos/zetasql | b998570e2b8f973ae376389ecde68092490e2ff4 | 54d659fe8682392908d6a823deececa203e7e59b | refs/heads/master | 2023-08-15T01:09:23.818432 | 2023-08-07T23:57:33 | 2023-08-08T00:13:26 | 239,835,555 | 0 | 0 | Apache-2.0 | 2023-09-06T00:02:56 | 2020-02-11T18:34:12 | C++ | UTF-8 | C++ | false | false | 3,418 | h | //
// Copyright 2019 Google 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
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ZETASQL_PUBLIC_FUNCTIONS_DATE_TIME_UTIL_INTERNAL_H_
#define ZETASQL_PUBLIC_FUNCTIONS_DATE_TIME_UTIL_INTERNAL_H_
#include "absl/time/civil_time.h"
namespace zetasql {
namespace functions {
namespace date_time_util_internal {
// If `day` is a `weekday`, return `day`, otherwise return the next
// `weekday`.
inline absl::CivilDay NextWeekdayOrToday(absl::CivilDay day,
absl::Weekday weekday) {
return absl::PrevWeekday(day, weekday) + 7;
}
// If `day` is a `weekday`, return `day`, otherwise return the previous
// `weekday`.
inline absl::CivilDay PrevWeekdayOrToday(absl::CivilDay day,
absl::Weekday weekday) {
return absl::NextWeekday(day, weekday) - 7;
}
// Weeks start on Monday. The 'year' of a given week is defined as
// the Gregorian calendar year of the Thursday of that week.
//
// [See https://en.wikipedia.org/wiki/ISO_week_date]
// Example:
//
// [Gregorian] December 2018
//
// Mon Tue Wed Thu Fri Sat Sun
// 03 04 05 06 07 08 09 -- 2018 Week 49
// 10 11 12 13 14 15 16 -- 2018 Week 50
// 17 18 19 20 21 22 23 -- 2018 Week 51
// 24 26 26 27 28 29 30 -- 2018 Week 52
// 31b 01 02 03a 04 05 06 -- 2019 Week 1
// 07 08 09 10 11 12 13 -- 2019 Week 2
//
// a 2019-01-03 is a Thursday in iso year 2019.
// b 2018-12-31 is the Monday prior to that Thursday, making it the first
// day of the iso year 2019.
//
// Returns the first day of the iso year that `day` is part of. Note, the `year`
// that day is in is defined by the Gregorian year of the Thursday of the same
// week (starting Monday) of that day:
//
// GetIsoYear(day).year() == GetIsoYear(GetFirstDayOfIsoYear(day)).year()
// however, day.year() may not equal GetFirstDayOfIsoYear().year().
absl::CivilDay GetFirstDayOfIsoYear(absl::CivilDay day);
// Returns the last day of the iso year that `day` is part of. Note, the `year`
// that day is in is defined by the Gregorian year of the Thursday of the same
// week (starting Monday) of that day:
//
// GetIsoYear(day).year() == GetIsoYear(GetLastDayOfIsoYear(day)).year()
// however, day.year() may not equal GetLastDayOfIsoYear().year().
absl::CivilDay GetLastDayOfIsoYear(absl::CivilDay day);
// Returns the ISO year for any date between 0001-01-01 and 9999-12-31.
// See above for the definition of a 'year'.
absl::civil_year_t GetIsoYear(absl::CivilDay day);
// Return the ISO week for the given day. Returned values are between 1 and 53
// inclusive.
int GetIsoWeek(absl::CivilDay day);
// Ruturns true if the given year is a leap year, false otherwise.
bool IsLeapYear(int64_t year);
} // namespace date_time_util_internal
} // namespace functions
} // namespace zetasql
#endif // ZETASQL_PUBLIC_FUNCTIONS_DATE_TIME_UTIL_INTERNAL_H_
| [
"matthewbr@google.com"
] | matthewbr@google.com |
e93dc9df7aac176a76c2dc0de85af97bb2310290 | 10e427b3d7d5dead84e76f7961df2acad6e98994 | /source/App/TAppDecoder/TAppDecCfg.cpp | 4082454a09a7c1faff54450165b77b127d90568c | [] | no_license | sgblasi/LRSP | 3da228aa6031765515cbeb6a5cc2006d8d14d4c8 | 9e7b5696c3b3adae8da37f314458a58a3c357129 | refs/heads/master | 2016-09-11T11:44:50.953722 | 2014-06-26T09:17:44 | 2014-06-26T09:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,409 | cpp | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2013, ITU/ISO/IEC
* 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 ITU/ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file TAppDecCfg.cpp
\brief Decoder configuration class
*/
#include <cstdio>
#include <cstring>
#include <string>
#include "TAppDecCfg.h"
#include "TAppCommon/program_options_lite.h"
#include "TLibCommon/TComChromaFormat.h"
#ifdef WIN32
#define strdup _strdup
#endif
using namespace std;
namespace po = df::program_options_lite;
//! \ingroup TAppDecoder
//! \{
// ====================================================================================================================
// Public member functions
// ====================================================================================================================
/** \param argc number of arguments
\param argv array of arguments
*/
Bool TAppDecCfg::parseCfg( Int argc, Char* argv[] )
{
Bool do_help = false;
string cfg_BitstreamFile;
string cfg_ReconFile;
string cfg_TargetDecLayerIdSetFile;
string outputColourSpaceConvert;
po::Options opts;
opts.addOptions()
("help", do_help, false, "this help text")
("BitstreamFile,b", cfg_BitstreamFile, string(""), "bitstream input file name")
("ReconFile,o", cfg_ReconFile, string(""), "reconstructed YUV output file name\n"
"YUV writing is skipped if omitted")
("SkipFrames,s", m_iSkipFrame, 0, "number of frames to skip before random access")
("OutputBitDepth,d", m_outputBitDepth[CHANNEL_TYPE_LUMA], 0, "bit depth of YUV output luma component (default: use 0 for native depth)")
("OutputBitDepthC,d", m_outputBitDepth[CHANNEL_TYPE_CHROMA], 0, "bit depth of YUV output chroma component (default: use 0 for native depth)")
("OutputColourSpaceConvert", outputColourSpaceConvert, string(""), "Colour space conversion to apply to input 444 video. Permitted values are (empty string=UNCHANGED) " + getListOfColourSpaceConverts(false))
("MaxTemporalLayer,t", m_iMaxTemporalLayer, -1, "Maximum Temporal Layer to be decoded. -1 to decode all layers")
("SEIDecodedPictureHash", m_decodedPictureHashSEIEnabled, 1, "Control handling of decoded picture hash SEI messages\n"
"\t1: check hash in SEI messages if available in the bitstream\n"
"\t0: ignore SEI message")
("SEIpictureDigest", m_decodedPictureHashSEIEnabled, 1, "deprecated alias for SEIDecodedPictureHash")
("SEINoDisplay", m_decodedNoDisplaySEIEnabled, true, "Control handling of decoded no display SEI messages")
("TarDecLayerIdSetFile,l", cfg_TargetDecLayerIdSetFile, string(""), "targetDecLayerIdSet file name. The file should include white space separated LayerId values to be decoded. Omitting the option or a value of -1 in the file decodes all layers.")
("RespectDefDispWindow,w", m_respectDefDispWindow, 0, "Only output content inside the default display window\n")
;
po::setDefaults(opts);
const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
{
fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
}
if (argc == 1 || do_help)
{
po::doHelp(cout, opts);
return false;
}
m_outputColourSpaceConvert = stringToInputColourSpaceConvert(outputColourSpaceConvert, false);
if (m_outputColourSpaceConvert>=NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS)
{
fprintf(stderr, "Bad output colour space conversion string\n");
return false;
}
/* convert std::string to c string for compatability */
m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
if (!m_pchBitstreamFile)
{
fprintf(stderr, "No input file specifed, aborting\n");
return false;
}
if ( !cfg_TargetDecLayerIdSetFile.empty() )
{
FILE* targetDecLayerIdSetFile = fopen ( cfg_TargetDecLayerIdSetFile.c_str(), "r" );
if ( targetDecLayerIdSetFile )
{
Bool isLayerIdZeroIncluded = false;
while ( !feof(targetDecLayerIdSetFile) )
{
Int layerIdParsed = 0;
if ( fscanf( targetDecLayerIdSetFile, "%d ", &layerIdParsed ) != 1 )
{
if ( m_targetDecLayerIdSet.size() == 0 )
{
fprintf(stderr, "No LayerId could be parsed in file %s. Decoding all LayerIds as default.\n", cfg_TargetDecLayerIdSetFile.c_str() );
}
break;
}
if ( layerIdParsed == -1 ) // The file includes a -1, which means all LayerIds are to be decoded.
{
m_targetDecLayerIdSet.clear(); // Empty set means decoding all layers.
break;
}
if ( layerIdParsed < 0 || layerIdParsed >= MAX_NUM_LAYER_IDS )
{
fprintf(stderr, "Warning! Parsed LayerId %d is not withing allowed range [0,%d]. Ignoring this value.\n", layerIdParsed, MAX_NUM_LAYER_IDS-1 );
}
else
{
isLayerIdZeroIncluded = layerIdParsed == 0 ? true : isLayerIdZeroIncluded;
m_targetDecLayerIdSet.push_back ( layerIdParsed );
}
}
fclose (targetDecLayerIdSetFile);
if ( m_targetDecLayerIdSet.size() > 0 && !isLayerIdZeroIncluded )
{
fprintf(stderr, "TargetDecLayerIdSet must contain LayerId=0, aborting" );
return false;
}
}
else
{
fprintf(stderr, "File %s could not be opened. Using all LayerIds as default.\n", cfg_TargetDecLayerIdSetFile.c_str() );
}
}
return true;
}
//! \}
| [
"s.blasi@qmul.ac.uk"
] | s.blasi@qmul.ac.uk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.