blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7fcd1be7897cfdbeb8dc155a51af69ac0b394112 | ea71f6289415dfeb4b158a68a763515d0fb8f325 | /sketches/KaktusGrow/src/KaktusM.hpp | 134d1beeabe39b48a50e174a00fe1fd069ca7cbd | [] | no_license | ofZach/funkyForms | dc043b9ad7a7cd46bb89887852f6ef192f9635a5 | 3a5b231be5382c1376bffb6890951aada24aded4 | refs/heads/master | 2020-04-06T07:07:21.303408 | 2016-08-28T00:11:45 | 2016-08-28T00:11:45 | 61,383,694 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 896 | hpp | //
// KaktusM.hpp
// KaktusGrow
//
// Created by Zerc on 6/20/16.
//
//
#ifndef KaktusM_hpp
#define KaktusM_hpp
#include "ofMain.h"
#include "Kaktus.hpp"
#include "ofxGui.h"
class KaktusM{
public:
vector<Kaktus> plants;
ofxPanel gui;
void setup(ofVec3f pos){
addKaktus(pos);
}
void addKaktus(ofVec3f pos){
Kaktus k;
k.setup(pos);
plants.push_back(k);
}
void fadeKaktus(){
int last = plants.size()-1;
plants[0].fade();
}
void update(){
for (int i = 0; i < plants.size(); i++) {
plants[i].update();
if(plants[0].opacity<0){
plants.erase(plants.begin());
}
}
}
void drawGui(){
}
void draw(){
for (int i = 0; i < plants.size(); i++) {
plants[i].draw();
}
}
};
#endif /* KaktusM_hpp */
| [
"[email protected]"
] | |
ee0d90104e4d33502e0e57cb3ceaa94890e09b85 | 38ed316428d2b1a1936ecc6bb5ff94867910bcba | /mugsy-seqan/projects/library/seqan/graph_types/graph_iterator_dfs.h | c736a5a67bbb02efeab8b4314ce95885ca5e0793 | [
"Artistic-2.0"
] | permissive | kloetzl/mugsy | f875119b2323bfd93f082acb93a9db5b421cf95f | 8ccdf32858a7a5ab2f7b9b084d2190970feb97ec | refs/heads/master | 2021-05-20T20:59:40.864925 | 2020-04-02T16:17:27 | 2020-04-02T16:17:27 | 252,414,682 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,627 | h | /*==========================================================================
SeqAn - The Library for Sequence Analysis
http://www.seqan.de
============================================================================
Copyright (C) 2007
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
============================================================================
$Id: graph_iterator_dfs.h 1757 2008-02-27 16:26:20Z [email protected] $
==========================================================================*/
#ifndef SEQAN_HEADER_GRAPH_ITERATOR_DFS_H
#define SEQAN_HEADER_GRAPH_ITERATOR_DFS_H
namespace SEQAN_NAMESPACE_MAIN
{
//////////////////////////////////////////////////////////////////////////////
// Graph DfsIterator
//////////////////////////////////////////////////////////////////////////////
/**
.Spec.Dfs Preorder Iterator:
..cat:Graph
..summary:Depth-first search iterator for @Class.Graph@.
..remarks:Preorder means that a vertex is enumerated before its adjacent vertices have been explored.
..signature:Iterator<TGraph, DfsPreorder>
..param.TGraph:A graph.
...type:Class.Graph
..general:Class.Iter
..see:Spec.Vertex Iterator
..see:Spec.Out-Edge Iterator
..see:Spec.Edge Iterator
..see:Spec.Adjacency Iterator
..see:Spec.Bfs Iterator
*/
template<typename TGraph, typename TSpec>
class Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >
{
public:
typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
TGraph const* data_host;
TVertexDescriptor data_source;
String<bool> data_tokenMap; // Which vertices have been visited
String<TVertexDescriptor> data_stack;
void _init() {
resizeVertexMap(*data_host,data_tokenMap);
typedef typename Iterator<String<bool>, Rooted>::Type TIter;
TIter it = begin(data_tokenMap);
for(;!atEnd(it);goNext(it)) {
assignValue(it,false);
}
assignProperty(data_tokenMap, data_source, true);
clear(data_stack);
appendValue(data_stack, data_source, Generous());
}
Iter()
{
SEQAN_CHECKPOINT
}
Iter(TGraph& _graph, TVertexDescriptor v) :
data_host(&_graph),
data_source(v)
{
SEQAN_CHECKPOINT
_init();
}
Iter(Iter const& _iter) :
data_host(_iter.data_host),
data_source(_iter.data_source),
data_tokenMap(_iter.data_tokenMap),
data_stack(_iter.data_stack)
{
SEQAN_CHECKPOINT
}
~Iter() {
SEQAN_CHECKPOINT
}
Iter const& operator = (Iter const & _other) {
SEQAN_CHECKPOINT
if (this == &_other) return *this;
data_host=_other.data_host;
data_source=_other.data_source;
data_tokenMap=_other.data_tokenMap;
data_stack=_other.data_stack;
return *this;
}
//____________________________________________________________________________
};
//////////////////////////////////////////////////////////////////////////////
// Graph InternalDfsIterator - Metafunctions
//////////////////////////////////////////////////////////////////////////////
template<typename TGraph>
struct Iterator<TGraph, DfsPreorder>
{
typedef Iter<TGraph, GraphIterator<InternalDfsIterator<DfsPreorder> > > Type;
};
template<typename TGraph>
struct Iterator<TGraph const, DfsPreorder>
{
typedef Iter<TGraph const, GraphIterator<InternalDfsIterator<DfsPreorder> > > Type;
};
template<typename TGraph, typename TIteratorSpec>
struct Value<Iter<TGraph, GraphIterator<InternalDfsIterator<TIteratorSpec> > > >
{
typedef typename Value<Iter<TGraph, GraphIterator<InternalVertexIterator<TIteratorSpec> > > >::Type Type;
};
template<typename TGraph, typename TIteratorSpec>
struct Value<Iter<TGraph const, GraphIterator<InternalDfsIterator<TIteratorSpec> > > >
{
typedef typename Value<Iter<TGraph const, GraphIterator<InternalVertexIterator<TIteratorSpec> > > >::Type Type;
};
template<typename TGraph, typename TIteratorSpec>
struct Reference<Iter<TGraph, GraphIterator<InternalDfsIterator<TIteratorSpec> > > >
{
typedef typename Reference<Iter<TGraph, GraphIterator<InternalVertexIterator<TIteratorSpec> > > >::Type Type;
};
template<typename TGraph, typename TIteratorSpec>
struct Reference<Iter<TGraph const, GraphIterator<InternalDfsIterator<TIteratorSpec> > > >
{
typedef typename Reference<Iter<TGraph const, GraphIterator<InternalVertexIterator<TIteratorSpec> > > >::Type Type;
};
template<typename TGraph, typename TIteratorSpec>
struct GetValue<Iter<TGraph, GraphIterator<InternalDfsIterator<TIteratorSpec> > > >
{
typedef typename GetValue<Iter<TGraph, GraphIterator<InternalVertexIterator<TIteratorSpec> > > >::Type Type;
};
template<typename TGraph, typename TIteratorSpec>
struct GetValue<Iter<TGraph const, GraphIterator<InternalDfsIterator<TIteratorSpec> > > >
{
typedef typename GetValue<Iter<TGraph const, GraphIterator<InternalVertexIterator<TIteratorSpec> > > >::Type Type;
};
//////////////////////////////////////////////////////////////////////////////
// Graph InternalBfsIterator - Functions
//////////////////////////////////////////////////////////////////////////////
template<typename TGraph, typename TSpec>
inline typename GetValue<Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > > >::Type
getValue(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
return getValue(it.data_stack, length(it.data_stack) - 1);
}
template<typename TGraph, typename TSpec>
inline typename GetValue<Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > > >::Type
value(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
// We don't want vertex ids to be changed
return getValue(it);
}
template<typename TGraph, typename TSpec>
inline typename GetValue<Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > > >::Type
operator * (Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
return value(it);
}
template<typename TGraph, typename TSpec>
inline typename Host<Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > > >::Type const&
hostGraph(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
return *it.data_host;
}
template<typename TGraph, typename TSpec>
inline bool
atBegin(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
if (empty(it.data_stack)) return false;
else return (getValue(it.data_stack, length(it.data_stack) - 1) == it.data_source);
}
template<typename TGraph, typename TSpec>
inline void
goBegin(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
it._init();
}
template<typename TGraph, typename TSpec>
inline bool
atEnd(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
return (empty(it.data_stack));
}
template<typename TGraph, typename TSpec>
inline void
goEnd(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
clear(it.data_stack);
}
template<typename TGraph, typename TSpec>
inline void
goNext(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
if (empty(it.data_stack)) return;
typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
TVertexDescriptor u = getValue(it.data_stack, length(it.data_stack) - 1);
resize(it.data_stack, length(it.data_stack) - 1);
typedef typename Iterator<TGraph, AdjacencyIterator>::Type TAdjacencyIterator;
TAdjacencyIterator itad(*it.data_host,u);
for(;!atEnd(itad);goNext(itad)) {
TVertexDescriptor v = getValue(itad);
if (getProperty(it.data_tokenMap, v) == false) {
assignProperty(it.data_tokenMap, v, true);
appendValue(it.data_stack, v, Generous());
}
}
}
template<typename TGraph, typename TSpec>
inline Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >&
operator ++(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it)
{
SEQAN_CHECKPOINT
goNext(it);
return it;
}
template<typename TGraph, typename TSpec>
inline Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >
operator ++(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it, int)
{
SEQAN_CHECKPOINT
Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > > ret = it;
goNext(it);
return ret;
}
template<typename TGraph, typename TSpec>
inline bool
operator ==(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it1,
Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it2)
{
SEQAN_CHECKPOINT
return ((it1.data_source==it2.data_source) &&
(it1.data_tokenMap==it2.data_tokenMap) &&
(it1.data_stack==it2.data_stack));
}
template<typename TGraph, typename TSpec>
inline bool
operator !=(Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it1,
Iter<TGraph, GraphIterator<InternalDfsIterator<TSpec> > >& it2)
{
SEQAN_CHECKPOINT
return ((it1.data_source!=it2.data_source) ||
(it1.data_tokenMap!=it2.data_tokenMap) ||
(it1.data_stack!=it2.data_stack));
}
}// namespace SEQAN_NAMESPACE_MAIN
#endif //#ifndef SEQAN_HEADER_...
| [
"angiuoli@8aca55ff-8d62-4810-9032-67e444260ce4"
] | angiuoli@8aca55ff-8d62-4810-9032-67e444260ce4 |
217d069195f434fde97f0cbba5a50a878aacac5d | 4d5eb7e1d4c6ac845ff125fab837b679aabac97a | /base/CadmiumErrors.h | 4088cca23fc9ed9e566eb152ae5b7ecba90d5558 | [
"Apache-2.0"
] | permissive | rmarshasatx/NfWebCrypto | bbd916b3ffbb573ed4de49fb062a3e51f3df4415 | 3a83896b1e78823e927386d6b2ecf6442b5f8064 | refs/heads/master | 2021-01-17T15:53:46.783703 | 2013-06-27T03:05:56 | 2013-06-27T03:05:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | h | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef CADMIUMERRORS_H_
#define CADMIUMERRORS_H_
#include <string>
namespace cadmium
{
enum CadErr
{
CAD_ERR_OK = 0,
CAD_ERR_BADARG,
CAD_ERR_KEYDERIVE,
CAD_ERR_NOMETHOD,
CAD_ERR_BADKEYINDEX,
CAD_ERR_BADENCODING, // 5
CAD_ERR_BADKEYNAME,
CAD_ERR_LOSTKEY,
CAD_ERR_STORE,
CAD_ERR_CIPHERERROR,
CAD_ERR_BADIV, // 10
CAD_ERR_DHERROR,
CAD_ERR_UNKNOWN,
CAD_ERR_NOT_INITIALIZED,
CAD_ERR_NOT_IMPLEMENTED,
CAD_ERR_BADCONTEXTNAME,
CAD_ERR_HMACERROR,
CAD_ERR_REGISTERED,
CAD_ERR_REGERROR,
CAD_ERR_UNKNOWN_ALGO,
CAD_ERR_UNSUPPORTED_KEY_ENCODING,
CAD_ERR_KEYGEN,
CAD_ERR_ALREADY_INITIALIZED,
CAD_ERR_INTERNAL,
CAD_ERR_END // sentinel, do not use
};
extern const char * CadErrStr[];
}
#endif /* CADMIUMERRORS_H_ */
| [
"[email protected]"
] | |
be0b9ece56d0197f80925c9e271d8fa0a4a6746c | 15a2f9a1b9a246a429976ad26153c7fa8a8c0e97 | /luogu/p3953.cpp | d69a68007057961ff0440501439ef9d109fdaa00 | [] | no_license | RealFakeAccount/Oi-times | e6e78074df940452f25f83c7e10ddd0f7a7b1215 | 8f9ef3203549b310619cc8eaf14d0f392936c9db | refs/heads/master | 2022-12-31T07:51:56.038465 | 2020-10-17T16:40:22 | 2020-10-17T16:40:22 | 304,764,604 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,053 | cpp | #include <stack>
#include <queue>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int MAXN = 1e5 + 10;
const int MAXK = 50 + 2;
inline int read(){
char ch = getchar(); int x = 0;
while(!isdigit(ch)) ch = getchar();
while(isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
return x;
}
int N, M, K, MOD;
struct edge
{
int to, cost;
};vector<edge> g[MAXN], rg[MAXN];
inline void init(){
for(int i = 0; i <= N; i++) g[i].clear();
for(int i = 0; i <= N; i++) rg[i].clear();
}
inline bool tension(const int &st, int &lg) {
return st < lg ? (lg = st, true) : false;
}
bool is0[MAXN], ins[MAXN];
bool dfs(int u) {
if(ins[u]) return is0[u] = true;
ins[u] = true;
for(int i = 0; i < (int) g[u].size(); i++) {
edge &e = g[u][i];
if(e.cost == 0 && dfs(e.to)) return is0[u] = true;
}
return ins[u] = false;
}
int to_dis[MAXN];
void rdijkstra() {
memset(to_dis, 0x3f, sizeof(to_dis));
priority_queue<P, vector<P>, greater<P> > q;
to_dis[N] = 0, q.push(P(0, N));
while(!q.empty()){
P p = q.top(); q.pop();
int u = p.second;
if(to_dis[u] < p.first) continue;
for(int i = 0; i < (int) rg[u].size(); i++) {
edge &e = rg[u][i];
if(tension(to_dis[u] + e.cost, to_dis[e.to]))
q.push(P(to_dis[e.to], e.to));
}
}
}
struct state
{
int val, k, pos; bool pre0;
bool operator >(const state &rhs) const{
if(val != rhs.val) return val > rhs.val;
return pre0 < rhs.pre0;
}
};
int cnt[MAXN][MAXK], dis[MAXN][MAXK];
int dijkstra() {
memset(cnt, 0, sizeof(cnt));
memset(dis, 0x3f, sizeof(dis));
priority_queue<state, vector<state>, greater<state> > q;
cnt[1][0] = 1, dis[1][0] = 0;
q.push((state) {0, 0, 1, false});
while(!q.empty()) {
state cur = q.top(); q.pop();
int u = cur.pos;
if(dis[u][cur.k] < cur.val) continue;
for(int i = 0; i < (int) g[u].size(); i++) {
edge &e = g[u][i];
int nk = (to_dis[e.to] + e.cost - to_dis[u]) + cur.k;
if(nk > K) continue;
// if(is0[e.to]) return -1;
(cnt[e.to][nk] += cnt[u][cur.k]) %= MOD;
if(tension(dis[u][cur.k] + e.cost, dis[e.to][nk]))
q.push((state){dis[e.to][nk], nk, e.to, e.cost == 0});
}
}
ll ans = 0;
for(int i = 0; i <= K; i++) (ans += cnt[N][i]) %= MOD;
return (int) ans;
}
int main(){
freopen("p3953.in", "r", stdin);
int T; cin>>T;
while(T--){
cin>>N>>M>>K>>MOD; init();
for(int i = 1; i <= M; i++) {
int u = read(), v = read(), c = read();
g[u].push_back((edge){v, c}), rg[v].push_back((edge){u, c});
}
for(int i = 1; i <= N; i++)
if(!ins[i]) dfs(i);
rdijkstra();
printf("%d\n", dijkstra());
}
return 0;
} | [
"[email protected]"
] | |
91eb03f165bc220630c5b3ccff24c8dd57aec472 | 60619a8daa4603fb65f4f86f383a6ddde841e326 | /2014-03-03/e1.cpp | dadc449bd9ce3a90626a859bca1b34033ee1cd37 | [] | no_license | MYREarth/secret-weapon | f4b1d4b995951546b2fb1e40190707a805fb88b5 | 77f3ff1111aafaaae8f56893b78e3be9134437a9 | refs/heads/master | 2020-05-22T02:29:43.024017 | 2015-10-03T08:17:46 | 2015-10-03T08:17:46 | 186,199,326 | 3 | 0 | null | 2019-05-12T01:46:13 | 2019-05-12T01:46:13 | null | UTF-8 | C++ | false | false | 1,947 | cpp | #include <cstdio>
#include <bitset>
using namespace std;
bitset <300> use[500010],assign[500010];
char buf[100000];
int IF[500010],ELSE[500010];
int main()
{
int T;
scanf("%d",&T);
while (T--)
{
int n;
scanf("%d",&n);
if (n>300)
return(1/0);
gets(buf);
int top=0,now=0;
while (1)
{
now++;
gets(buf);
use[now]=use[now-1];
assign[now]=assign[now-1];
if (buf[0]=='a')
{
int x;
sscanf(buf,"a %d",&x);
assign[now].set(x-1);
}
else if (buf[0]=='u')
{
int x;
sscanf(buf,"u %d",&x);
if (!assign[now].test(x-1))
use[now].set(x-1);
}
else if (buf[0]=='i')
{
IF[++top]=now;
ELSE[now]=0;
}
else if (buf[0]=='e' && buf[1]=='l')
{
ELSE[IF[top]]=now-1;
use[now]=use[IF[top]];
assign[now]=assign[IF[top]];
}
else if (top)
{
int x=IF[top--];
if (!ELSE[x])
{
use[now]|=use[x];
assign[now]=assign[x];
}
else
{
int y=ELSE[x];
use[now]|=use[y];
assign[now]&=assign[y];
}
}
else
break;
}
for (int i=0;i<n;i++)
{
if (i)
printf(" ");
if (use[now].test(i))
printf("1");
else if (assign[now].test(i))
printf("-1");
else
printf("0");
}
printf("\n");
}
return(0);
}
| [
"[email protected]"
] | |
2931c06473c067d828b36551686e029e1ab0a805 | 71734273f0efd015e771aeb8026e2cdb045870cc | /cef/tests/cefsimple/simple_handler.h | 1f272ff1fe383605025107ff75ad819c03038f1a | [
"Apache-2.0"
] | permissive | killvxk/miniblink49 | 6efc4ff4a65eaface992d6bf02e537caa9131ed2 | ff3d0e133d18de1748c688b0c0e173965db17033 | refs/heads/master | 2020-03-18T01:43:40.001114 | 2019-04-27T12:11:45 | 2019-04-27T12:11:45 | 134,156,673 | 1 | 0 | MIT | 2019-04-27T12:11:46 | 2018-05-20T14:17:42 | C++ | UTF-8 | C++ | false | false | 2,163 | h | // Copyright (c) 2013 The Chromium Embedded Framework 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 CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_
#define CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_
#include "include/cef_client.h"
#include <list>
class SimpleHandler : public CefClient,
public CefDisplayHandler,
public CefLifeSpanHandler,
public CefLoadHandler {
public:
SimpleHandler();
~SimpleHandler();
// Provide access to the single global instance of this object.
static SimpleHandler* GetInstance();
// CefClient methods:
virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefLoadHandler> GetLoadHandler() OVERRIDE {
return this;
}
// CefDisplayHandler methods:
virtual void OnTitleChange(CefRefPtr<CefBrowser> browser,
const CefString& title) OVERRIDE;
// CefLifeSpanHandler methods:
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE;
virtual bool DoClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefLoadHandler methods:
virtual void OnLoadError(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
ErrorCode errorCode,
const CefString& errorText,
const CefString& failedUrl) OVERRIDE;
// Request that all existing browser windows close.
void CloseAllBrowsers(bool force_close);
bool IsClosing() const { return is_closing_; }
private:
// List of existing browser windows. Only accessed on the CEF UI thread.
typedef std::list<CefRefPtr<CefBrowser> > BrowserList;
BrowserList browser_list_;
bool is_closing_;
// Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(SimpleHandler);
};
#endif // CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_
| [
"[email protected]"
] | |
301ccef8b31942c7ba025f25ca8b53e5f3e16632 | 81c6b750d2a3007386b1c55b7a9129433b57997f | /cis-202/assignment6/SafeStack.h | d1b6d6e346fcb04e2b60b4320e73f6928a01b419 | [] | no_license | josephhyatt/cis_assignments | 2e965ba94d394e295bea047da1b99035a827ce3c | 4c06ad2f4f6820e13a52fdccabf6cb371cf9cde4 | refs/heads/master | 2020-04-22T23:10:23.788918 | 2019-05-30T23:27:40 | 2019-05-30T23:27:40 | 170,732,550 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 786 | h | /*=============================================================================
# Author: Joseph Hyatt - https://github.com/josephhyatt/
# Email: [email protected]
# FileName: SafeStack.h
# Description: Header file declaring functions being used. SafeStack class gives the
implementation of stack with exception when abnormal condition occurs.
=============================================================================*/
#ifndef __SAFESTACK_H
#define __SAFESTACK_H
#include <string>
#include <stack>
#include <iostream>
class SafeStack
{
public:
SafeStack();
int size();
std::string top();
void push(std::string str);
void pop();
bool empty();
private:
std::stack<std::string> s;
};
#endif // __SAFESTACK_H | [
"[email protected]"
] | |
828305468632c0ff05c2f49617a2cd3f600b4798 | 43166165b5e8414e9bfaaf224131f0346cc3c12d | /pr11_4.cpp | c4c170e8ed40dbedca82dcf0ac8ae5de4ed38fe3 | [] | no_license | MISTIKMAKS/lab11_4 | 456205322e11365f1826d609936f6b61110d32ad | 2eab01425db32480a68ff12ede74e48ca4d153a5 | refs/heads/master | 2023-04-15T08:27:20.547227 | 2021-04-28T15:50:46 | 2021-04-28T15:50:46 | 362,525,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,392 | cpp | #include <iostream>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
struct Note
{
string last_name;
string name;
string telephone;
int day;
int month;
int year;
};
void enter_save(char* fname);
void load_print(char* fname);
void telephone_find(char* fname, char* ftelephone);
void sort_binary(char* fname);
int main()
{
char fname[61];
char ftelephone[151];
char ch;
do
{
cout << "--------------------------------\n";
cout << "Main Menu\n";
cout << "Please make your selection\n" << endl;
cout << "[1] - Enter & Save Data\n" << endl;
cout << "[2] - Load & Print Data\n" << endl;
cout << "[3] - Sort Binary\n" << endl;
cout << "[4] - Find Friend By Telephone\n" << endl;
cout << "[0] - Exit\n";
cout << "--------------------------------\n";
cout << "Your Choise: "; cin >> ch;
switch (ch)
{
case '0':
cout << "Goodbye! See Ya Later, Aligator!!!";
break;
case '1':
cout << "You Chosen [1] - Enter & Save Data:\n";
cin.get();
cin.sync();
cout << "Enter file name: "; cin.getline(fname, sizeof(fname));
enter_save(fname);
break;
case '2':
cout << "You Chosen [2] - Load & Print Data:\n";
cin.get();
cin.sync();
cout << "Enter file name: "; cin.getline(fname, sizeof(fname));
load_print(fname);
break;
case '3':
cout << "You Chosen [3] - Sort Binary:\n";
cin.get();
cin.sync();
cout << "Enter file name: "; cin.getline(fname, sizeof(fname));
sort_binary(fname);
load_print(fname);
break;
case '4':
cout << "You Chosen [4] - Find Friend By Telephone:\n";
cin.get();
cin.sync();
cout << "Enter File Name: "; cin.getline(fname, sizeof(fname));
cout << "Enter Telephone Number: "; cin.getline(ftelephone, sizeof(ftelephone));
sort_binary(fname);
telephone_find(fname, ftelephone);
break;
default:
cout << endl;
cout << "--------------------------------\n";
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "[1] - Enter & Save Data\n" << endl;
cout << "[2] - Load & Print Data\n" << endl;
cout << "[3] - Find Friend By Telephone\n" << endl;
cout << "[0] - Exit\n";
cout << "--------------------------------\n";
cout << "Your Choise: "; cin >> ch;
}
} while (ch != '0');
return 0;
}
void enter_save(char* fname)
{
ofstream f(fname, ios::binary);
if (!f)
{
cerr << "Error opening file '" << fname << "'" << endl;
return;
}
Note friends;
char ch;
do
{
cout << endl;
cout << "Last Name: "; cin.sync();
cin >> friends.last_name;
cout << "Name: "; cin.sync();
cin >> friends.name;
cout << "Telephone: ";
cin >> friends.telephone;
cout << "Birthday Day: ";
cin >> friends.day;
cout << "Birthday Month: ";
cin >> friends.month;
cout << "Birthday Year: ";
cin >> friends.year;
if (!f.write((char*)&friends, sizeof(Note)))
{
cerr << "Error writing file." << endl;
}
cout << "Continue? (Y/N) "; cin >> ch;
} while (ch == 'Y' || ch == 'y');
}
void load_print(char* fname)
{
ifstream f(fname, ios::binary);
if (!f)
{
cerr << "Error opening file '" << fname << "'" << endl;
return;
}
Note friends;
while (f.read((char*)&friends, sizeof(Note)))
{
cout << endl;
cout << "Last Name: " << friends.last_name << endl;
cout << "Name: " << friends.name << endl;
cout << "Telephone: " << friends.telephone << endl;
cout << "Birthday Day: " << friends.day << endl;
cout << "Birthday Month: " << friends.month << endl;
cout << "Birthday Year: " << friends.year << endl;
}
}
void telephone_find(char* fname, char* ftelephone)
{
ifstream f(fname, ios::binary);
if (!f)
{
cerr << "Error opening file '" << fname << "'" << endl;
return;
}
Note friends;
while (f.read((char*)&friends, sizeof(Note)))
{
if (friends.telephone == ftelephone) {
cout << endl;
cout << "Found Friend With Telephone (" << ftelephone << ") :" << endl;
cout << endl;
cout << "Last Name: " << friends.last_name << endl;
cout << "Name: " << friends.name << endl;
cout << "Telephone: " << friends.telephone << endl;
cout << "Birthday Day: " << friends.day << endl;
cout << "Birthday Month: " << friends.month << endl;
cout << "Birthday Year: " << friends.year << endl;
}
else
{
cout << "...";
cout << endl;
}
}
}
void sort_binary(char* fname) {
ifstream f(fname, ios::binary);
if (!f)
{
cerr << "Error opening file '" << fname << "'" << endl;
return;
}
else {
f.seekg(0, ios::end);
int size = f.tellg();
size = size / sizeof(Note);
f.seekg(0, ios::beg);
Note* friends = new Note[size];
f.read((char*)friends, size * sizeof(Note));
f.close();
for (int i = 0; i < size - 1; i++) {
for (int j = size - 1; j > i; j--) {
if (friends[j].year < friends[j - 1].year) {
float temp = friends[j].year;
friends[j].year = friends[j - 1].year;
friends[j - 1].year = temp;
}
else if (friends[j].year = friends[j - 1].year) {
if (friends[j].month < friends[j - 1].month) {
float temp = friends[j].month;
friends[j].month = friends[j - 1].month;
friends[j - 1].month = temp;
}
else if (friends[j].month = friends[j - 1].month) {
if (friends[j].day < friends[j - 1].day) {
float temp = friends[j].day;
friends[j].day = friends[j - 1].day;
friends[j - 1].day = temp;
}
}
}
}
}
}
}
| [
"[email protected]"
] | |
e3f1bd42b95bc87aaf502a33416c9079d762a998 | ed1c0eb5c096e2bad70d9913015cbf0464a86b09 | /src/util.hh | ccb1dd7429a67d738cc43045f36ef910740cb371 | [
"MIT"
] | permissive | udbg/cffi-lua | 46c984614cdb7cdb260ea8471507c144eee14b48 | 70a061109d8f9ba36442c27fafc2f6e6c8c7af99 | refs/heads/master | 2023-03-13T01:49:17.886922 | 2021-03-07T19:45:49 | 2021-03-07T19:57:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,055 | hh | /* standard utilities used within the ffi
*
* these are mostly-compliant implementations of the standard c++ containers
* and other utilities, meant to avoid the need for the c++ runtime/standard
* library; they aren't meant to be general purpose and only implement what
* we use, they don't provide documented exception safety guarantees and so
* on either but that's fine since we barely use these at all
*/
#ifndef UTIL_HH
#define UTIL_HH
#include "platform.hh"
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <climits>
#include <cfloat>
/* allocation */
#ifndef _MSC_VER
inline void *operator new(std::size_t, void *p) noexcept { return p; }
inline void *operator new[](std::size_t, void *p) noexcept { return p; }
inline void operator delete(void *, void *) noexcept {}
inline void operator delete[](void *, void *) noexcept {}
#endif
namespace util {
/* type traits */
namespace detail {
template<typename T> struct remove_ref { using type = T; };
template<typename T> struct remove_ref<T &> { using type = T; };
template<typename T> struct remove_ref<T &&> { using type = T; };
}
template<typename T> using remove_ref_t = typename detail::remove_ref<T>::type;
namespace detail {
template<typename T> struct remove_const { using type = T; };
template<typename T> struct remove_const<T const> { using type = T; };
template<typename T> struct remove_volatile { using type = T; };
template<typename T> struct remove_volatile<T volatile> { using type = T; };
}
template<typename T> using remove_const_t =
typename detail::remove_const<T>::type;
template<typename T> using remove_volatile_t =
typename detail::remove_volatile<T>::type;
template<typename T> using remove_cv_t = typename detail::remove_volatile<
typename detail::remove_const<T>::type
>::type;
namespace detail {
template<bool B, typename T, typename F>
struct conditional { using type = T; };
template<typename T, typename F>
struct conditional<false, T, F> { using type = F; };
}
template<bool B, typename T, typename F>
using conditional_t = typename detail::conditional<B, T, F>::type;
namespace detail {
template<typename> struct integral {
static constexpr bool value = false;
};
template<> struct integral<bool> {
static constexpr bool value = true;
};
template<> struct integral<char> {
static constexpr bool value = true;
};
template<> struct integral<char16_t> {
static constexpr bool value = true;
};
template<> struct integral<char32_t> {
static constexpr bool value = true;
};
template<> struct integral<wchar_t> {
static constexpr bool value = true;
};
template<> struct integral<short> {
static constexpr bool value = true;
};
template<> struct integral<int> {
static constexpr bool value = true;
};
template<> struct integral<long> {
static constexpr bool value = true;
};
template<> struct integral<long long> {
static constexpr bool value = true;
};
template<> struct integral<signed char> {
static constexpr bool value = true;
};
template<> struct integral<unsigned char> {
static constexpr bool value = true;
};
template<> struct integral<unsigned short> {
static constexpr bool value = true;
};
template<> struct integral<unsigned int> {
static constexpr bool value = true;
};
template<> struct integral<unsigned long> {
static constexpr bool value = true;
};
template<> struct integral<unsigned long long> {
static constexpr bool value = true;
};
}
template<typename T>
struct is_int {
static constexpr bool value = detail::integral<remove_cv_t<T>>::value;
};
namespace detail {
template<typename> struct fpoint {
static constexpr bool value = false;
};
template<> struct fpoint<float> {
static constexpr bool value = true;
};
template<> struct fpoint<double> {
static constexpr bool value = true;
};
template<> struct fpoint<long double> {
static constexpr bool value = true;
};
}
template<typename T>
struct is_float {
static constexpr bool value = detail::fpoint<remove_cv_t<T>>::value;
};
template<typename T>
struct is_arith {
static constexpr bool value = is_int<T>::value || is_float<T>::value;
};
template<typename T, bool = is_arith<T>::value>
struct is_signed {
static constexpr bool value = T(-1) < T(0);
};
template<typename T>
struct is_signed<T, false> {
static constexpr bool value = false;
};
/* move semantics */
template<typename T>
constexpr inline remove_ref_t<T> &&move(T &&v) noexcept {
return static_cast<remove_ref_t<T> &&>(v);
}
template<typename T>
constexpr inline T &&forward(remove_ref_t<T> &v) noexcept {
return static_cast<T &&>(v);
}
template<typename T>
constexpr inline T &&forward(remove_ref_t<T> &&v) noexcept {
return static_cast<T &&>(v);
}
/* assorted utils */
template<typename T, typename U = T>
constexpr inline T exchange(T &v, U &&nv) {
T ov = move(v);
v = forward<U>(nv);
return ov;
}
template<typename T>
inline void swap(T &a, T &b) {
auto o = move(a);
a = move(b);
b = move(o);
}
template<typename T>
inline T min(T a, T b) {
return (a < b) ? a : b;
}
template<typename T>
inline T max(T a, T b) {
return (a > b) ? a : b;
}
/* basic limits interface */
namespace detail {
template<typename T>
struct int_limits;
template<>
struct int_limits<char> {
static constexpr char min = CHAR_MIN;
static constexpr char max = CHAR_MAX;
};
template<>
struct int_limits<signed char> {
static constexpr signed char min = SCHAR_MIN;
static constexpr signed char max = SCHAR_MAX;
};
template<>
struct int_limits<unsigned char> {
static constexpr unsigned char min = 0;
static constexpr unsigned char max = UCHAR_MAX;
};
template<>
struct int_limits<short> {
static constexpr short min = SHRT_MIN;
static constexpr short max = SHRT_MAX;
};
template<>
struct int_limits<unsigned short> {
static constexpr unsigned short min = 0;
static constexpr unsigned short max = USHRT_MAX;
};
template<>
struct int_limits<int> {
static constexpr int min = INT_MIN;
static constexpr int max = INT_MAX;
};
template<>
struct int_limits<unsigned int> {
static constexpr unsigned int min = 0;
static constexpr unsigned int max = UINT_MAX;
};
template<>
struct int_limits<long> {
static constexpr long min = LONG_MIN;
static constexpr long max = LONG_MAX;
};
template<>
struct int_limits<unsigned long> {
static constexpr unsigned long min = 0;
static constexpr unsigned long max = ULONG_MAX;
};
template<>
struct int_limits<long long> {
static constexpr long long min = LLONG_MIN;
static constexpr long long max = LLONG_MAX;
};
template<>
struct int_limits<unsigned long long> {
static constexpr unsigned long long min = 0;
static constexpr unsigned long long max = ULLONG_MAX;
};
template<typename T, bool I, bool F>
struct limits_base {};
template<typename T>
struct limits_base<T, true, false> {
static constexpr int radix = 2;
static constexpr int digits = CHAR_BIT * sizeof(T) - is_signed<T>::value;
static constexpr T min = int_limits<T>::min;
static constexpr T max = int_limits<T>::max;
};
template<>
struct limits_base<float, false, true> {
static constexpr int radix = FLT_RADIX;
static constexpr int digits = FLT_MANT_DIG;
static constexpr float min = FLT_MIN;
static constexpr float max = FLT_MAX;
};
template<>
struct limits_base<double, false, true> {
static constexpr int radix = FLT_RADIX;
static constexpr int digits = DBL_MANT_DIG;
static constexpr double min = DBL_MIN;
static constexpr double max = DBL_MAX;
};
template<>
struct limits_base<long double, false, true> {
static constexpr int radix = FLT_RADIX;
static constexpr int digits = LDBL_MANT_DIG;
static constexpr long double min = LDBL_MIN;
static constexpr long double max = LDBL_MAX;
};
template<typename T>
struct limits: limits_base<T, is_int<T>::value, is_float<T>::value> {};
}
template<typename T>
inline constexpr int limit_radix() {
return detail::limits<T>::radix;
}
template<typename T>
inline constexpr int limit_digits() {
return detail::limits<T>::digits;
}
template<typename T>
inline constexpr T limit_min() {
return detail::limits<T>::min;
}
template<typename T>
inline constexpr T limit_max() {
return detail::limits<T>::max;
}
/* simple writers for base 10 to avoid printf family */
std::size_t write_i(char *buf, std::size_t bufsize, long long v);
std::size_t write_u(char *buf, std::size_t bufsize, unsigned long long v);
/* a refernce counted object; manages its own memory,
* so it can avoid separately allocating the refcount
*/
template<typename T>
struct rc_obj {
struct construct {};
template<typename ...A>
rc_obj(construct, A &&...cargs) {
auto *np = new unsigned char[sizeof(T) + get_rc_size()];
/* initial acquire */
*reinterpret_cast<std::size_t *>(np) = 1;
/* store */
p_ptr = reinterpret_cast<T *>(np + get_rc_size());
/* construct */
new (p_ptr) T(util::forward<A>(cargs)...);
}
rc_obj(rc_obj const &op): p_ptr{op.p_ptr} {
incr();
}
~rc_obj() {
decr();
}
rc_obj &operator=(rc_obj op) {
swap(op);
return *this;
}
T &operator*() const {
return *p_ptr;
}
T *operator->() const {
return p_ptr;
}
T *get() const {
return p_ptr;
}
explicit operator bool() const {
return (count() > 0);
}
std::size_t count() const {
return *counter();
}
bool unique() const {
return (count() == 1);
}
void release() {
decr();
}
void swap(rc_obj &op) {
util::swap(p_ptr, op.p_ptr);
}
private:
static constexpr std::size_t get_rc_size() {
return (alignof(T) > sizeof(std::size_t))
? alignof(T) : sizeof(std::size_t);
}
std::size_t *counter() const {
auto *op = reinterpret_cast<unsigned char *>(p_ptr) - get_rc_size();
return reinterpret_cast<std::size_t *>(op);
}
void incr() {
++*counter();
}
void decr() {
auto *ptr = counter();
if (!--*ptr) {
p_ptr->~T();
delete[] reinterpret_cast<unsigned char *>(ptr);
}
}
T *p_ptr;
};
template<typename T, typename ...A>
rc_obj<T> make_rc(A &&...args) {
return rc_obj<T>{typename rc_obj<T>::construct{}, util::forward<A>(args)...};
}
/* vector */
template<typename T>
struct vector {
static constexpr std::size_t MIN_SIZE = 4;
vector() {}
~vector() {
drop();
}
vector(vector const &v) { *this = v; }
vector(vector &&v) { *this = move(v); }
vector &operator=(vector const &v) {
shrink(0);
if (v.size() > capacity()) {
reserve(v.size());
}
for (std::size_t i = 0; i < v.size(); ++i) {
push_back(v[i]);
}
return *this;
}
vector &operator=(vector &&v) {
swap(v);
return *this;
}
void push_back(T const &v) {
reserve(p_cap + 1);
new (&p_buf[p_size++]) T(v);
}
void push_back(T &&v) {
reserve(p_cap + 1);
new (&p_buf[p_size++]) T(util::move(v));
}
void pop_back() {
p_buf[p_size - 1].~T();
--p_size;
}
template<typename ...A>
T &emplace_back(A &&...args) {
reserve(p_cap + 1);
new (&p_buf[p_size]) T(util::forward<A>(args)...);
return p_buf[p_size++];
}
void reserve(std::size_t n) {
if (n <= p_cap) {
return;
}
if (n < MIN_SIZE) {
n = MIN_SIZE;
}
T *np = reinterpret_cast<T *>(new unsigned char[n * sizeof(T)]);
if (p_cap) {
for (std::size_t i = 0; i < p_size; ++i) {
new (&np[i]) T(util::move(p_buf[i]));
p_buf[i].~T();
}
delete[] reinterpret_cast<unsigned char *>(p_buf);
}
p_buf = np;
p_cap = n;
}
void shrink(std::size_t n) {
for (std::size_t i = n; i < p_size; ++i) {
p_buf[i].~T();
}
p_size = n;
}
void clear() {
shrink(0);
}
T &operator[](std::size_t i) {
return p_buf[i];
}
T const &operator[](std::size_t i) const {
return p_buf[i];
}
T &front() {
return p_buf[0];
}
T const &front() const {
return p_buf[0];
}
T &back() {
return p_buf[p_size - 1];
}
T const &back() const {
return p_buf[p_size - 1];
}
T *data() {
return p_buf;
}
T const *data() const {
return p_buf;
}
std::size_t size() const {
return p_size;
}
std::size_t capacity() const {
return p_cap;
}
bool empty() const {
return p_size == 0;
}
void swap(vector &v) {
util::swap(p_buf, v.p_buf);
util::swap(p_size, v.p_size);
util::swap(p_cap, v.p_cap);
}
void setlen(std::size_t len) {
p_size = len;
}
void setbuf(T const *data, std::size_t len) {
std::memcpy(p_buf, data, len);
p_size = len;
}
private:
void drop() {
shrink(0);
delete[] reinterpret_cast<unsigned char *>(p_buf);
}
T *p_buf = nullptr;
std::size_t p_size = 0, p_cap = 0;
};
/* string buffer */
struct strbuf {
strbuf() {
/* always terminated */
p_buf.push_back('\0');
}
strbuf(strbuf const &b) {
set(b);
}
strbuf(strbuf &&b): p_buf(util::move(b.p_buf)) {}
strbuf(char const *str, std::size_t n) {
set(str, n);
}
strbuf(char const *str): strbuf(str, std::strlen(str)) {}
~strbuf() {}
strbuf &operator=(char const *str) {
set(str, std::strlen(str));
return *this;
}
strbuf &operator=(strbuf const &b) {
set(b);
return *this;
}
strbuf &operator=(strbuf &&b) {
p_buf = util::move(b.p_buf);
return *this;
}
void push_back(char c) {
p_buf.back() = c;
p_buf.push_back('\0');
}
void pop_back() {
p_buf.pop_back();
p_buf.back() = '\0';
}
void append(char const *str, std::size_t n) {
auto sz = p_buf.size();
p_buf.reserve(sz + n);
std::memcpy(&p_buf[sz - 1], str, n);
p_buf[n + sz - 1] = '\0';
p_buf.setlen(sz + n);
}
void append(char const *str) {
append(str, std::strlen(str));
}
void append(char c) {
push_back(c);
}
void append(strbuf const &b) {
append(b.data(), b.size());
}
void prepend(char const *str, std::size_t n) {
auto sz = p_buf.size();
p_buf.reserve(sz + n);
std::memmove(&p_buf[n], &p_buf[0], sz);
std::memcpy(&p_buf[0], str, n);
p_buf.setlen(sz + n);
}
void prepend(char const *str) {
prepend(str, std::strlen(str));
}
void prepend(char c) {
auto sz = p_buf.size();
p_buf.reserve(sz + 1);
std::memmove(&p_buf[1], &p_buf[0], sz);
p_buf[0] = c;
p_buf.setlen(sz + 1);
}
void prepend(strbuf const &b) {
prepend(b.data(), b.size());
}
void insert(char const *str, std::size_t n, std::size_t idx) {
auto sz = p_buf.size();
p_buf.reserve(sz + n);
std::memmove(&p_buf[idx + n], &p_buf[idx], sz - idx);
std::memcpy(&p_buf[idx], str, n);
p_buf.setlen(sz + n);
}
void insert(char const *str, std::size_t idx) {
insert(str, std::strlen(str), idx);
}
void insert(strbuf const &b, std::size_t idx) {
insert(b.data(), b.size(), idx);
}
void remove(size_t idx, size_t n = 1) {
std::memmove(&p_buf[idx], &p_buf[idx + n], p_buf.size() + 1 - idx - n);
}
void set(char const *str, std::size_t n) {
p_buf.reserve(n + 1);
std::memcpy(&p_buf[0], str, n);
p_buf[n] = '\0';
p_buf.setlen(n + 1);
}
void set(char const *str) {
set(str, std::strlen(str));
}
void set(strbuf const &b) {
set(b.data(), b.size());
}
void reserve(std::size_t n) {
p_buf.reserve(n + 1);
}
void clear() {
p_buf.clear();
p_buf[0] = '\0';
p_buf.setlen(1);
}
char operator[](std::size_t i) const { return p_buf[i]; }
char &operator[](std::size_t i) { return p_buf[i]; }
char front() const { return p_buf.front(); }
char &front() { return p_buf.front(); }
char back() const { return p_buf[size() - 1]; }
char &back() { return p_buf[size() - 1]; }
char const *data() const { return p_buf.data(); }
char *data() { return p_buf.data(); }
std::size_t size() const { return p_buf.size() - 1; }
std::size_t capacity() const { return p_buf.capacity() - 1; }
bool empty() const { return (size() == 0); }
void swap(strbuf &b) {
p_buf.swap(b.p_buf);
}
void setlen(std::size_t n) {
p_buf.setlen(n + 1);
}
util::vector<char> const &raw() const { return p_buf; }
util::vector<char> &raw() { return p_buf; }
private:
util::vector<char> p_buf{};
};
/* hashtable */
template<typename K, typename V, typename HF, typename CF>
struct map {
private:
static constexpr std::size_t CHUNK_SIZE = 64;
static constexpr std::size_t DEFAULT_SIZE = 1024;
struct entry {
K key;
V data;
};
struct bucket {
entry value;
bucket *next;
};
public:
map(std::size_t sz = DEFAULT_SIZE): p_size{sz} {
p_buckets = new bucket *[sz];
std::memset(p_buckets, 0, sz * sizeof(bucket *));
}
~map() {
delete[] p_buckets;
drop_chunks();
}
bool empty() const {
return p_nelems == 0;
}
V &operator[](K const &key) {
std::size_t h;
bucket *b = find_bucket(key, h);
if (!b) {
b = add(h);
b->value.key = key;
}
return b->value.data;
}
V *find(K const &key) const {
std::size_t h;
bucket *b = find_bucket(key, h);
if (!b) {
return nullptr;
}
return &b->value.data;
}
V &insert(K const &key, V const &value) {
std::size_t h;
bucket *b = find_bucket(key, h);
if (!b) {
b = add(h);
b->value.key = key;
b->value.data = value;
}
return b->value.data;
}
void clear() {
if (!p_nelems) {
return;
}
p_nelems = 0;
p_unused = nullptr;
std::memset(p_buckets, 0, p_size * sizeof(bucket *));
drop_chunks();
}
void swap(map &m) {
util::swap(p_size, m.p_size);
util::swap(p_nelems, m.p_nelems);
util::swap(p_buckets, m.p_buckets);
util::swap(p_unused, m.p_unused);
util::swap(p_chunks, m.p_chunks);
}
template<typename F>
void for_each(F &&func) const {
for (std::size_t i = 0; i < p_size; ++i) {
for (bucket *b = p_buckets[i]; b; b = b->next) {
func(b->value.key, b->value.data);
}
}
}
private:
bucket *add(std::size_t hash) {
if (!p_unused) {
chunk *nb = new chunk;
nb->next = p_chunks;
p_chunks = nb;
for (std::size_t i = 0; i < CHUNK_SIZE - 1; ++i) {
nb->buckets[i].next = &nb->buckets[i + 1];
}
nb->buckets[CHUNK_SIZE - 1].next = p_unused;
p_unused = nb->buckets;
}
bucket *b = p_unused;
p_unused = p_unused->next;
b->next = p_buckets[hash];
p_buckets[hash] = b;
++p_nelems;
return b;
}
bucket *find_bucket(K const &key, std::size_t &h) const {
h = HF{}(key) % p_size;
for (bucket *b = p_buckets[h]; b; b = b->next) {
if (CF{}(key, b->value.key)) {
return b;
}
}
return nullptr;
}
void drop_chunks() {
for (chunk *nc; p_chunks; p_chunks = nc) {
nc = p_chunks->next;
delete p_chunks;
}
}
struct chunk {
bucket buckets[CHUNK_SIZE];
chunk *next;
};
std::size_t p_size, p_nelems = 0;
bucket **p_buckets;
bucket *p_unused = nullptr;
chunk *p_chunks = nullptr;
};
#if SIZE_MAX > 0xFFFF
/* fnv1a for 32/64bit values */
template<std::size_t offset_basis, std::size_t prime>
struct fnv1a {
std::size_t operator()(char const *data) const {
std::size_t slen = std::strlen(data);
std::size_t hash = offset_basis;
for (std::size_t i = 0; i < slen; ++i) {
hash ^= std::size_t(data[i]);
hash *= prime;
}
return hash;
}
};
#else
/* pearson hash for smaller values */
static unsigned char const ph_lt[256] = {
167, 49, 207, 184, 90, 134, 74, 211, 215, 76, 109, 126, 222, 97, 231,
1, 132, 204, 149, 249, 166, 33, 237, 100, 141, 186, 191, 112, 151, 203,
69, 87, 65, 80, 157, 95, 58, 59, 82, 115, 171, 192, 24, 244, 225,
223, 102, 189, 164, 119, 216, 174, 68, 133, 7, 10, 159, 31, 255, 150,
41, 169, 161, 43, 245, 235, 16, 94, 81, 162, 103, 53, 110, 135, 228,
86, 114, 144, 156, 241, 2, 253, 195, 128, 22, 105, 199, 250, 64, 13,
178, 63, 99, 39, 190, 130, 163, 30, 122, 18, 168, 83, 220, 71, 129,
84, 3, 208, 155, 9, 242, 170, 51, 143, 56, 158, 176, 172, 148, 55,
227, 254, 247, 224, 50, 93, 54, 210, 206, 234, 218, 229, 61, 26, 107,
32, 196, 217, 248, 138, 154, 212, 96, 40, 209, 38, 101, 73, 88, 125,
175, 187, 34, 62, 118, 66, 113, 46, 238, 42, 202, 0, 179, 67, 47,
20, 152, 165, 17, 89, 48, 123, 219, 70, 91, 120, 177, 188, 145, 104,
92, 98, 44, 108, 4, 37, 139, 11, 214, 52, 221, 29, 75, 19, 35,
124, 185, 28, 201, 230, 198, 131, 116, 153, 77, 72, 45, 226, 146, 12,
137, 21, 147, 25, 27, 180, 240, 200, 243, 194, 15, 183, 181, 233, 213,
232, 136, 14, 252, 121, 85, 111, 106, 127, 197, 251, 205, 8, 60, 246,
140, 160, 239, 36, 6, 5, 142, 79, 57, 173, 182, 193, 117, 236, 23,
78
};
struct pearson {
std::size_t operator()(char const *data) const {
std::size_t slen = std::strlen(data);
std::size_t hash = 0;
auto *udata = reinterpret_cast<unsigned char const *>(data);
for (std::size_t j = 0; j < sizeof(std::size_t); ++j) {
auto h = ph_lt[(udata[0] + j) % 256];
for (std::size_t i = 1; i < slen; ++i) {
h = ph_lt[h ^ udata[i]];
}
hash = ((hash << 8) | h);
}
return hash;
}
};
#endif
#if SIZE_MAX > 0xFFFFFFFF
struct str_hash: fnv1a<14695981039346656037ULL, 1099511628211ULL> {};
#elif SIZE_MAX > 0xFFFF
struct str_hash: fnv1a<2166136261U, 16777619U> {};
#else
struct str_hash: pearson {};
#endif
struct str_equal {
bool operator()(char const *k1, char const *k2) const {
return !std::strcmp(k1, k2);
}
};
template<typename V>
using str_map = map<char const *, V, str_hash, str_equal>;
} /* namespace util */
#endif /* UTIL_HH */
| [
"[email protected]"
] | |
fa902b41d3b4b8765035808c3c47a0210ecd22b1 | b2607b654a17d68700a7eef43e9af8546fd47d3a | /Data/Chapter 07/ClientByState.cpp | 47585b445200e930f1f8631b0c6036521b95f9cd | [] | no_license | Escoozme/cpp-fundamentals-1 | 0673aeeea7cbaf52c1c2dfb2990d95fd0245a0cd | 22eec37be12f04a1d16d9a9ca915119d50773057 | refs/heads/master | 2022-12-15T16:29:15.861037 | 2020-09-14T22:02:04 | 2020-09-14T22:02:04 | 295,542,240 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cpp | // ClientByState.cpp - This program creates a report that lists
// clients with a count of the number of clients for each state.
// Input: client.dat
// Output: Report
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declarations
ifstream fin;
const string TITLE = "\n\nCompany Clients by State of Residence\n\n";
string name = "", city = "", state = "";
int count = 0;
string oldState = "";
bool done;
fin.open("client.dat");
// This is the work done in the getReady() function
cout << TITLE << endl;
fin >> name;
if(!(fin.eof()))
{
fin >> city;
fin >> state;
done = false;
oldState = state;
}
else
done = true;
while(done == false)
{
// This is the work done in the produceReport() function
if(state != oldState)
{
// This is the work done in the controlBreak() function
cout << "\t\t\tCount for " << oldState << " " << count << endl;
count = 0;
oldState = state;
}
cout << name << " " << city << " " << state << endl;
count++;
fin >> name;
if(!(fin.eof()))
{
fin>> city;
fin >> state;
done = false;
}
else
done = true;
}
// This is the work done in the finishUp() function
cout << "\t\t\tCount for " << oldState << " " << count << endl;
fin.close();
return 0;
} // End of main()
| [
"[email protected]"
] | |
0eb5952fec2a73fd2d8f9b80bcfdfbd7d3287735 | 21b97331f1e52fd0207156fb85e3b3ae83788175 | /src/Allocators/TemporaryMappedFileAllocator.cpp | fb9d43a855a81540809aca32b2c8b1a20fe47743 | [] | no_license | bt193/EventDrive | 051e29ff25834efcf8856965a022aed0c6e6293f | 9711d1ee9db35e591d64c9c280a7fdf23a01afe8 | refs/heads/master | 2020-03-15T06:10:14.445165 | 2018-01-22T20:49:57 | 2018-01-22T20:49:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | #include "TemporaryMappedFileAllocator.hpp"
#include "../Segments/MemoryMappedFileSegment.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
TemporaryMappedFileAllocator::TemporaryMappedFileAllocator()
{
strncpy(_buffer, "temp.XXXXXX", sizeof(_buffer));
}
TemporaryMappedFileAllocator::~TemporaryMappedFileAllocator()
{
// unlink(_buffer);
}
int TemporaryMappedFileAllocator::GetFd(char *input)
{
auto fd = mkstemp(_buffer);
unlink(_buffer);
return fd;
} | [
"[email protected]"
] | |
d38c147f992fae0972e56affe26bc47f36aab9fe | f4c43c7aaca0ba3c62ec33e02a9efca37c332c5b | /MockProject_Group1_update_v1.0/Group1_FileExplorer_SourceCode_update_v1.0/FileExplorer_Group1/FileExplorer_Group1.h | 0a3117916c5179442bc79c7db3fe8b4a43cce7a9 | [] | no_license | phamlamnd/mfc_file_explorer | 5e1d9a90ade8e86328f2671800e1ccf5122d86d4 | 221c8f713603b36c5b84d6617030ded9b7323bdc | refs/heads/master | 2022-11-25T12:33:45.819320 | 2018-12-02T02:04:48 | 2018-12-02T02:04:48 | 160,005,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | h |
// FileExplorer_Group1.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CFileExplorer_Group1App:
// See FileExplorer_Group1.cpp for the implementation of this class
//
class CFileExplorer_Group1App : public CWinApp
{
public:
CFileExplorer_Group1App();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CFileExplorer_Group1App theApp; | [
"[email protected]"
] | |
824d0eb8c24d7b32ca33c7b51584cdafdbe67aee | 1e9ddc02de9f7ca2e18ced34c483344afe062ac2 | /Class8Online/ThirdLib/publish/src/SourAudio.cpp | 98b94cc4a4c37ea523b38740c91fec8fcb777c0d | [
"MIT"
] | permissive | GDMiao/Class8 | c0e99aa300c502d17778627e9d24d2d5e2e75ad7 | 3518407da4489bb083e549b5f7b893871aecdc0d | refs/heads/master | 2020-05-21T08:52:03.667747 | 2016-10-24T13:59:02 | 2016-10-24T13:59:02 | 69,264,356 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 821 | cpp | #include "SourAudio.h"
CSourAudio::CSourAudio(string sname):ISourData(SOURCEDEVAUDIO,sname)
{
}
CSourAudio::~CSourAudio()
{
}
bool CSourAudio::GetBuffer(unsigned char** pBuf,unsigned int& nBufSize)
{
return false;
}
bool CSourAudio::SetSourType(int nSourType)
{
return false;
}
bool CSourAudio::SourOpen(void* param)
{
return false;
}
bool CSourAudio::SourClose()
{
return false;
}
// Video Enhancements
bool CSourAudio::AVE_SetID(int nMainValue, int nSubValue, int nParams[2])
{
return false;
}
void CSourAudio::ShowImage(unsigned char* pBuf,unsigned int nBufSize,int nVW,int nVH)
{
}
long CSourAudio::GetDevMicCount()
{
return 0;
}
bool CSourAudio::GetDevMicName(long nIndex,char szName[256])
{
return false;
}
bool CSourAudio::GetActiveing()
{
return false;
} | [
"[email protected]"
] | |
7184a9fff49a600956ffc8e443924902eff7e581 | 3eafabe20db12174787625530e20e93c234cc71c | /3.提高组/2.test/1.a^b.cpp | 67fc668695ea2d7177b5f782d0962694aaa47683 | [] | no_license | Shuttles/HZOJ-C | fe07d83007512ec5d09f35f5ebf0cc027dbfb68c | d581e069fde097ef2c6f4fc4a585c26d1cccd89e | refs/heads/master | 2022-05-11T00:05:25.035140 | 2022-04-09T17:24:28 | 2022-04-09T17:24:28 | 198,056,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 508 | cpp | /*************************************************************************
> File Name: 1.a^b.cpp
> Author:
> Mail:
> Created Time: 日 5/24 19:35:21 2020
************************************************************************/
#include <iostream>
#include <cinttypes>
using namespace std;
int main() {
int64_t a, b, p, temp;
cin >> a >> b >> p;
temp = a;
for (int i = 1; i <= b; i++) {
a %= p;
(i == b) || (a *= temp);
}
cout << a << endl;
return 0;
}
| [
"[email protected]"
] | |
4a826677d952882eaf38c09f0eff58ae170c5138 | 40f83bc94093b0ec462ddb3a2abe9c5e20158ca5 | /youtube/src/core.cpp | 555eb19f99d6eb887d67083a12071b8b4d8d4c2e | [] | no_license | salmabazadd/xplatform | faf5e46333fecafa725a4599759566536a406d97 | d09ed911ce7a3b3699863f8c443a9706935fb1d9 | refs/heads/master | 2023-08-24T08:07:28.258157 | 2021-10-15T18:24:50 | 2021-10-15T18:24:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | cpp | #include "core.h"
namespace Core
{
namespace Util
{
bool isLittleEndian()
{
// 0x00 0x00 0x00 0b0000 0101
uint8_t a = 5;
std::string result = std::bitset<8>(a).to_string();
return (result.back() == '1') ? true : false;
}
void save(const char* file, std::vector<uint8_t>& buffer)
{
std::ofstream out;
out.open(file);
for (unsigned i = 0; i < buffer.size(); i++)
{
out << buffer[i];
}
out.close();
}
std::vector<uint8_t> load(const char* path)
{
std::ifstream in(path, std::ios::binary);
std::vector<uint8_t> result((std::istreambuf_iterator<char>(in)),(std::istreambuf_iterator<char>()));
return result;
}
void retriveNsave(ObjectModel::Root* r)
{
int16_t iterator = 0;
std::vector<uint8_t> buffer(r->getSize());
std::string name = r->getName().substr(0, r->getName().length()).append(".abc");
r->pack(buffer, iterator);
save(name.c_str(), buffer);
}
}
} | [
"[email protected]"
] | |
a5ef6b503b3bdc7fe6eaa74e17c0bc35e91f6fa7 | bee53e6def37420b5606913ce89379a1271d6547 | /STL/Vectors-and-Lists/Project1/MyClass.h | f67c839eb95c192c9b42d34a7509b84f035ba01a | [] | no_license | williamblood/learn-C | fc8e2d83d3ee7ef4b58184de8f1fc645f72f20b2 | 52a0b703b796faec16d4e67c4cb6a3328d265a33 | refs/heads/master | 2020-12-22T19:05:34.969207 | 2020-05-16T01:45:30 | 2020-05-16T01:45:30 | 236,893,483 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 178 | h | #ifndef MYCLASS_H_
#define MYCLASS_H_
template <typename T>
class MyClass
{
public:
MyClass() : first(0), second(0) {}
private:
T first;
T second;
};
#endif // !MYCLASS_H_
| [
"[email protected]"
] | |
63d7f3e8e225ad7c401ccb08aa918ea61f757926 | 4990f93979425234f922c59662bcd6ef86c0c03b | /mot.cpp | 2fe87c51b59b14cbc20df426e75baafe58b3c20e | [] | no_license | shoh2101/IFT339-TP1 | 6d64fa2f2271ddef59408f908d2262f5b5a32865 | 1de3c9d44e98ae1d18bba17a58ac7395de04f965 | refs/heads/master | 2021-01-22T14:11:13.979527 | 2014-09-17T18:22:56 | 2014-09-17T18:22:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 142 | cpp | #include "mot.h"
mot::mot(void)
{
}
mot::~mot(void)
{
}
bool mot::operator==(mot m)
{
}
mot::mot(string)
{
}
mot::mot(uint32_t)
{
}
| [
"[email protected]"
] | |
d0d3be90a2ad60e4d14014644da0e07b4392a31c | 7cd9751c057fcb36b91f67e515aaab0a3e74a709 | /src/materials/Absorption_Opacity_Constant.cc | ac42cc4207c9a4f49b2adc95788f2538c6bedfd0 | [
"MIT"
] | permissive | pgmaginot/DARK_ARTS | 5ce49db05f711835e47780677f0bf02c09e0f655 | f04b0a30dcac911ef06fe0916921020826f5c42b | refs/heads/master | 2016-09-06T18:30:25.652859 | 2015-06-12T19:00:40 | 2015-06-12T19:00:40 | 20,808,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 818 | cc | /** @file Absorption_Opacity_Constant.cc
* @author pmaginot
* @brief Implement the Absorption_Opacity_Constant class
* \f$ \sigma_a = constant\f$
*/
#include "Absorption_Opacity_Constant.h"
Absorption_Opacity_Constant::Absorption_Opacity_Constant(
const Input_Reader& input_reader, const int mat_num) :
m_const{ input_reader.get_abs_double_constant_1(mat_num) }
{
if(m_const < 0. )
{
std::stringstream err;
err << "Invalid absorption opacity constant in material " << mat_num;
throw Dark_Arts_Exception( SUPPORT_OBJECT, err.str() ) ;
}
}
Absorption_Opacity_Constant::~Absorption_Opacity_Constant(){}
double Absorption_Opacity_Constant::get_absorption_opacity(const int group,
const double temperature, const double position)
{
return m_const;
}
| [
"[email protected]"
] | |
2b8566d88f31930b92c4401ea023a45fd324a518 | 17fe08a8e9fce9d0f71f1b6f28192cb7373ab88c | /zookeeper/server/ZooKeeperThread.cpp | 57adf71bda5fb2da4b51aeb937fbef924caeff29 | [
"Apache-2.0"
] | permissive | cxxjava/CxxZookeeper | dcf31c6638afc37c1ebe1ba4351b31c10d991364 | 149677c785627aff839b2102ab265c745882fa52 | refs/heads/master | 2021-01-25T13:23:45.102771 | 2018-10-25T17:33:33 | 2018-10-25T17:33:33 | 123,562,911 | 19 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | /*
* ZooKeeperThread.cpp
*
* Created on: 2017-11-22
* Author: [email protected]
*/
#include "./ZooKeeperThread.hh"
namespace efc {
namespace ezk {
sp<ELogger> ZooKeeperThread::LOG = ELoggerManager::getLogger("ZooKeeperThread");
} /* namespace ezk */
} /* namespace efc */
| [
"[email protected]"
] | |
ba498222df6cb23a57b7604b75902e4e5e66b364 | 06bed8ad5fd60e5bba6297e9870a264bfa91a71d | /Tables/logixtableaction.cpp | 9869b1cffd4dff08918e5b5d00f5011d579c88b8 | [] | no_license | allenck/DecoderPro_app | 43aeb9561fe3fe9753684f7d6d76146097d78e88 | 226c7f245aeb6951528d970f773776d50ae2c1dc | refs/heads/master | 2023-05-12T07:36:18.153909 | 2023-05-10T21:17:40 | 2023-05-10T21:17:40 | 61,044,197 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 80,323 | cpp | #include "logixtableaction.h"
#include "instancemanager.h"
#include "defaultlogix.h"
#include "pickframe.h"
#include "instancemanager.h"
#include "defaultconditionalmanager.h"
#include "conditional.h"
#include "logix.h"
#include "defaultconditional.h"
#include "jtextfield.h"
#include <QMessageBox>
#include "runnable.h"
#include "../LayoutEditor/sensorgroupframe.h"
#include <QVBoxLayout>
#include <QTableView>
#include <QGroupBox>
#include "conditionalvariable.h"
#include "conditionalaction.h"
#include <QComboBox>
#include <QButtonGroup>
#include <QFont>
//#include "defaultusermessagepreferences.h"
#include <QCheckBox>
#include "gridbagconstraints.h"
#include "../LayoutEditor/inputdialog.h"
#include "../LayoutEditor/maintenance.h"
//#include "logixwidget.h"
#include "lroutetableaction.h"
#include <QPushButton>
#include "abstractsignalhead.h"
#include "signalmast.h"
#include "abstractsignalmast.h"
#include "defaultsignalmastmanager.h"
#include "abstractlight.h"
#include "defaultconditionalaction.h"
#include "abstractmemorymanager.h"
#include "abstractlightmanager.h"
#include "defaultconditionalmanager.h"
#include "defaultroutemanager.h"
#include <QStringList>
#include "defaultlogixmanager.h"
#include "abstractsignalheadmanager.h"
#include "proxylightmanager.h"
#include "jmriuserpreferencesmanager.h"
#include "oblock.h"
#include <QLabel>
#include "pushbuttondelegate.h" // for PushButtonItemDelegate
#include <QApplication>
#include <QMenuBar>
#include "flowlayout.h"
#include "htmltextedit.h"
#include <QScrollArea>
#include "joptionpane.h"
#include "fileutil.h"
#include "conditionaltreeedit.h"
#include "conditionallistedit.h"
#include "conditional.h"
#include "box.h"
//LogixTableAction::LogixTableAction(QObject *parent) :
// QObject(parent)
//{
//}
/**
* Swing action to create and register a Logix Table.
* <P>
* Also contains the windows to create, edit, and delete a Logix. Also contains
* the window to define and edit a Conditional::
* <P>
* Most of the text used in this GUI is in LogixTableBundle.properties, accessed
* via rbx, and the remainder of the text is in BeanTableBundle.properties,
* accessed via rb.
*
* Methods and Members for 'state variables' and 'actions' removed to become their
* own objects - 'ConditionalVariable' and 'ConditionalAction' in jmri package.
* Two more types of logic for a Conditional to use in its antecedent have been added
* to the original 'AND'ing all statevariables - 'OR' (i.e. all OR's) and 'MIXED'
* (i.e. general bool statement with any mixture of bool operations).
* The 'OR's an 'AND's types are unambiguous and do not require parentheses.
* The 'Mixed' type uses a TextField for the user to insert parenthees.
* Jan 22, 2009 - Pete Cressman
*
* Conditionals now have two policies to trigger execution of their action lists.
* 1. the previous policy - Trigger on change of state only
* 2. the new default - Trigger on any enabled state calculation
* Jan 15, 2011 - Pete Cressman
*
* @author Dave Duchamp Copyright (C) 2007
* @author Pete Cressman Copyright (C) 2009, 2010, 2011
* @author Matthew Harris copyright (c) 2009
* @version $Revision: 22539 $
*/
///*public*/ class LogixTableAction extends AbstractTableAction {
/**
* Create an action with a specific title.
* <P>
* Note that the argument is the Action title, not the title of the
* resulting frame. Perhaps this should be changed?
*
* @param s
*/
/*public*/ LogixTableAction::LogixTableAction(QString s, QObject *parent) : AbstractTableAction(s, parent)
{
//super(s);
log = new Logger("LogixTableAction");
_conditionalManager = NULL; // set when LogixAction is created
_logixManager = NULL; // set when LogixAction is created
_showReminder = false;
// _suppressReminder = false;
// _suppressIndirectRef = false;
_pickTables = NULL;
// current focus variables
_curLogix = NULL;
// numConditionals = 0;
conditionalRowNumber = 0;
//_curConditional = NULL;
if(parent == NULL)
return;
// Edit variables
// editLogixFrame = NULL;
_inEditMode = false;
_inCopyMode = false;
// _inReorderMode = false;
// _nextInOrder = 0;
// editUserName = new JTextField(20);
// status = new QLabel(" ");
// Add Logix Variables
addLogixFrame = NULL;
_systemName = new JTextField(10);
_addUserName = new JTextField(10);
_addUserName->setMinimumSize(_addUserName->sizeHint());
_autoSystemName = new QCheckBox(tr("Automatically Generate System Name"));
_sysNameLabel = new QLabel(tr("Logix System Name"));
_userNameLabel = new QLabel(tr("Logix User Name"));
prefMgr = (UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager");
systemNameAuto = QString(getClassName())+".AutoSystemName";
// Edit Conditional Variables
// inEditConditionalMode = false;
// editConditionalFrame = NULL;
// conditionalUserName = new JTextField(22);
_actionTableModel = NULL;
_variableTableModel = NULL;
_logicType = Conditional::ALL_AND;
_antecedent = "";
_newItem = false; // marks a new Action or Variable object added
selectionModes = QStringList();
selectionModes << QString("USEMULTI") << QString("USESINGLE") << QString("USECOMBO");
editModes = QStringList();
editModes << QString("LISTEDIT") << QString("TREEEDIT");
_conditionalManager = NULL; // set when LogixAction is created
userFileChooser = new JFileChooser(FileUtil::getUserFilesPath());
_inEditMode = false;
_listEdit = NULL;
_treeEdit = NULL;
_editActionFrame = NULL;
_editVariableFrame = NULL;
//_actionTypeListener = new ActionTypeListener(this);
//actionSignalHeadNameListener = new ActionSignalHeadNameListener(this);
//variableSignalHeadNameListener = new VariableSignalHeadNameListener(this);
//variableSignalTestStateListener = new VariableSignalTestStateListener(this);
// set up managers - no need to use InstanceManager since both managers are
// Default only (internal). We use InstanceManager to get managers for
// compatibility with other facilities.
_logixManager = (LogixManager*)InstanceManager::getNullableDefault("LogixManager");
_conditionalManager = (ConditionalManager*)InstanceManager::getNullableDefault("ConditionalManager");
// disable ourself if there is no Logix manager or no Conditional manager available
if ((_logixManager == NULL) || (_conditionalManager == NULL))
{
setEnabled(false);
}
_saveTargetNames = QSet<QString>();
_saveTargetList = QMap<QString, QList<QString> >();
}
LogixTableAction::LogixTableAction(const LogixTableAction & that) : AbstractTableAction(that.text(), that.parent())
{}
// /*public*/ LogixTableAction() {
// this("Logix Table");
// }
// static /*final*/ ResourceBundle rbx = ResourceBundle
// .getBundle("jmri.jmrit.beantable.LogixTableBundle");
// *********** Methods for Logix Table Window ********************
/**
* Create the JTable DataModel, along with the changes (overrides of
* BeanTableDataModel) for the specific case of a Logix table. Note: Table
* Models for the Conditional table in the Edit Logix window, and the State
* Variable table in the Edit Conditional window are at the end of this
* module.
*/
/*protected*/ void LogixTableAction::createModel()
{
m = new LogixTableModel(this);
AbstractManager* manager = (AbstractManager*)m->getManager()->mself();
connect(manager, SIGNAL(propertyChange(PropertyChangeEvent*)), m, SLOT(propertyChange(PropertyChangeEvent*)));
}
// overlay the state column with the edit column
LogixTableModel::LogixTableModel(LogixTableAction *self)
: BeanTableDataModel(self)
{
this->self = self;
enabledString = tr("Enabled");
init();
}
/*public*/ QVariant LogixTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
if (section == EDITCOL)
return ""; // no heading on "Edit"
if (section == ENABLECOL)
return enabledString;
}
return BeanTableDataModel::headerData(section,orientation, role);
}
///*public*/ Class<?> getColumnClass(int col) {
// if (col == EDITCOL)
// return String.class;
// if (col == ENABLECOL)
// return Boolean.class;
// else
// return super.getColumnClass(col);
//}
/*public*/ int LogixTableModel::getPreferredWidth(int col) {
// override default value for SystemName and UserName columns
if (col == SYSNAMECOL)
return JTextField(12).getPreferredSize().width();
if (col == USERNAMECOL)
return JTextField(17).getPreferredSize().width();
if (col == EDITCOL)
return JTextField(12).getPreferredSize().width();
if (col == ENABLECOL)
return JTextField(5).getPreferredSize().width();
else
return BeanTableDataModel::getPreferredWidth(col);
}
/*public*/ Qt::ItemFlags LogixTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid()) return Qt::NoItemFlags;
if (index.column() == EDITCOL)
return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
if (index.column() == ENABLECOL)
return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
else
return BeanTableDataModel::flags(index);
}
/*public*/ QVariant LogixTableModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::DisplayRole)
{
if (index.column() == EDITCOL)
{
return tr("Select");
}
else return BeanTableDataModel::data(index, role);
}
else
{
if(role == Qt::CheckStateRole)
{
if (index.column() == ENABLECOL)
{
Logix* logix = (Logix*) getBySystemName(data(createIndex(index.row(), SYSNAMECOL),Qt::DisplayRole).toString())->self();
if (logix == NULL)
{
return QVariant();
}
return ((DefaultLogix*)logix)->getEnabled()?Qt::Checked:Qt::Unchecked;
}
}
}
return BeanTableDataModel::data(index, role);
}
/*public*/ bool LogixTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(role == Qt::EditRole)
{
if (index.column() == EDITCOL)
{
// set up to edit
QString sName = sysNameList.at(index.row());
if ( tr("Edit")==(value.toString()) )
{
self->editPressed(sName);
}
else if (tr("Browser")== (value.toString()))
{ // NOI18N
self->conditionalRowNumber = index.row();
self->browserPressed(sName);
}
else if (tr("Copy")==(value.toString()) )
{
self->copyPressed(sName);
}
else if ( tr("Delete")==(value.toString()) )
{
self->deletePressed(sName);
}
return true;
}
else
BeanTableDataModel::setData(index, value, role);
}
if(role == Qt::CheckStateRole)
{
if (index.column() == ENABLECOL)
{
// alternate
Logix* x = (Logix*) getBySystemName(sysNameList.at(index.row()))->self();
bool v = ((DefaultLogix*)x)->getEnabled();
((DefaultLogix*)x)->setEnabled(!v);
return true;
}
else
BeanTableDataModel::setData(index, value, role);
}
return false;
}
/**
* Delete the bean after all the checking has been done.
* <P>
* Deactivate the Logix and remove it's conditionals
*/
void LogixTableModel::doDelete(NamedBean* bean)
{
Logix* l = (Logix*) bean->self();
((DefaultLogix*)l)->deActivateLogix();
// delete the Logix and all its Conditionals
((DefaultLogixManager*)self->_logixManager)->deleteLogix(l);
}
/*protected*/ bool LogixTableModel::matchPropertyName(PropertyChangeEvent* e) {
if (e->getPropertyName()==(enabledString))
return true;
else
return BeanTableDataModel::matchPropertyName(e);
}
/*public*/ AbstractManager *LogixTableModel::getManager()
{
return (AbstractManager*)InstanceManager::getDefault("LogixManager");
//return self->_logixManager;
}
/*public*/ NamedBean* LogixTableModel::getBySystemName(QString name) const {
return ((LogixManager*)InstanceManager::getDefault("LogixManager"))->getBySystemName(
name);
}
/*public*/ NamedBean* LogixTableModel::getByUserName(QString name) {
return ((LogixManager*)InstanceManager::getDefault("LogixManager"))->getByUserName(
name);
}
/*public*/ int LogixTableModel::getDisplayDeleteMsg()
{
return ((UserPreferencesManager*) InstanceManager::getDefault("UserPreferencesManager"))->getMultipleChoiceOption(self->getClassName(),"deleteInUse");
}
/*public*/ void LogixTableModel::setDisplayDeleteMsg(int boo)
{
((UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager"))->setMultipleChoiceOption(self-> getClassName(), "deleteInUse", boo);
}
/*protected*/ QString LogixTableModel::getMasterClassName() { return self->getClassName(); }
/*public*/ void LogixTableModel::configureTable(JTable* table) {
// table.setDefaultRenderer(Boolean.class, new EnablingCheckboxRenderer());
// table.setDefaultRenderer(JComboBox.class, new jmri.jmrit.symbolicprog.ValueRenderer());
// table.setDefaultEditor(JComboBox.class, new jmri.jmrit.symbolicprog.ValueEditor());
BeanTableDataModel::configureTable(table);
}
/**
* Replace delete button with comboBox
*/
/*protected*/ void LogixTableModel::configDeleteColumn(JTable* table) {
// JComboBox editCombo = new JComboBox();
// editCombo->layout()->addWidget(new QLabel("ButtonSelect"));
// editCombo->layout()->addWidget(new QLabel("ButtonEdit"));
// editCombo->layout()->addWidget(new QLabel("ButtonCopy"));
// editCombo->layout()->addWidget(new QLabel("ButtonDelete"));
// TableColumn col = table.getColumnModel().getColumn(BeanTableDataModel.DELETECOL);
// col.setCellEditor(new DefaultCellEditor(editCombo));
QStringList items = QStringList() << tr("Select") << tr("Edit") << tr("Browser") << tr("Copy") << tr("Delete");
table->setItemDelegateForColumn(BeanTableDataModel::DELETECOL, new JComboBoxEditor(items, this));
}
/*protected*/ void LogixTableModel::configValueColumn(JTable */*table*/)
{
// do nothing but override BeanTableDataModel::configValueColumn
}
// Not needed - here for interface compatibility
/*public*/ void LogixTableModel::clickOn(NamedBean* /*t*/) {
}
/*public*/ QString LogixTableModel::getValue(QString /*s*/) const
{
return "";
}
/*protected*/ QString LogixTableModel::getBeanType(){
return tr("Logix");
}
// };
//}
// set title for Logix table
/*protected*/ void LogixTableAction::setTitle() {
f->setTitle(tr("Logix Table"));
}
/**
* Insert 2 table specific menus.
* <p>
* Accounts for the Window and Help menus, which are already added to the
* menu bar as part of the creation of the JFrame, by adding the new menus 2
* places earlier unless the table is part of the ListedTableFrame, which
* adds the Help menu later on.
*
* @param f the JFrame of this table
*/
//@Override
/*public*/ void LogixTableAction::setMenuBar(BeanTableFrame* f) {
loadSelectionMode();
loadEditorMode();
QMenu* menu = new QMenu(tr("Options")); // NOI18N
// menu.setMnemonic(KeyEvent.VK_O);
QMenuBar* menuBar = f->menuBar();
QList<QAction*> actions = menuBar->actions();
int pos = menuBar->actions().count() - 1; // count the number of menus to insert the TableMenus before 'Window' and 'Help'
int offset = 1;
log->debug("setMenuBar number of menu items = " + QString::number(pos)); // NOI18N
for (int i = 0; i <= pos; i++)
{
//if (menuBar.getComponent(i) instanceof JMenu)
if(qobject_cast<QMenu*>(menuBar->actions().at(i)))
{
if (((QMenu*) menuBar->actions().at(i))->title() == (tr("Help")))
{ // NOI18N
offset = -1; // correct for use as part of ListedTableAction where the Help Menu is not yet present
}
}
}
QActionGroup* enableButtonGroup = new QActionGroup(this);
QAction* r = new QAction(tr("Enable All Logix"),this); // NOI18N
r->setCheckable(true);
// r.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// enableAll(true);
// }
// });
connect(r, SIGNAL(triggered(bool)), this, SLOT(enableAll(bool)));
enableButtonGroup->addAction(r);
r->setChecked(true);
menu->addAction(r);
r = new QAction(tr("Disable All Logix"),this); // NOI18N
// r.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// enableAll(false);
// }
// });
connect(r, SIGNAL(triggered(bool)), this, SLOT(enableAll(bool)));
enableButtonGroup->addAction(r);
menu->addAction(r);
menu->addSeparator();
QActionGroup* modeButtonGroup = new QActionGroup(this);
r = new QAction(tr("Use Traditional Pick Lists"), this); // NOI18N
r->setCheckable(true);
// r.addItemListener(new ItemListener() {
// @Override
// public void itemStateChanged(ItemEvent e) {
// setSelectionMode(SelectionMode.USEMULTI);
// }
// });
connect(r, SIGNAL(triggered(bool)), this, SLOT(on_useMulti_triggered()));
modeButtonGroup->addAction(r);
menu->addAction(r);
r->setChecked(_selectionMode == SelectionMode::USEMULTI);
r = new QAction(tr("Use Single Pick Lists"),this); // NOI18N
r->setCheckable(true);
// r.addItemListener(new ItemListener() {
// @Override
// public void itemStateChanged(ItemEvent e) {
// setSelectionMode(SelectionMode.USESINGLE);
// }
// });
connect(r, SIGNAL(triggered()), this , SLOT(on_useSingle_triggered()));
modeButtonGroup->addAction(r);
menu->addAction(r);
r->setChecked(_selectionMode == SelectionMode::USESINGLE);
r = new QAction(tr("Use Combo Name Boxes"), this); // NOI18N
r->setCheckable(true);
// r.addItemListener(new ItemListener() {
// @Override
// public void itemStateChanged(ItemEvent e) {
// setSelectionMode(SelectionMode.USECOMBO);
// }
// });
connect(r, SIGNAL(triggered()), this, SLOT(on_useComboNameBoxes_triggered()));
modeButtonGroup->addAction(r);
menu->addAction(r);
r->setChecked(_selectionMode == SelectionMode::USECOMBO);
menu->addSeparator();
QActionGroup* viewButtonGroup = new QActionGroup(this);
r = new QAction(tr("List Edit"),this); // NOI18N
r->setCheckable(true);
// r.addItemListener(new ItemListener() {
// @Override
// public void itemStateChanged(ItemEvent e) {
// setEditorMode(EditMode.LISTEDIT);
// }
// });
connect(r, SIGNAL(triggered()), this, SLOT(on_listEdit_triggered()));
viewButtonGroup->addAction(r);
menu->addAction(r);
r->setChecked(_editMode == EditMode::LISTEDIT);
r = new QAction(tr("Tree Edit"), this); // NOI18N
r->setCheckable(true);
// r.addItemListener(new ItemListener() {
// @Override
// public void itemStateChanged(ItemEvent e) {
// setEditorMode(EditMode.TREEEDIT);
// }
// });
connect(r, SIGNAL(triggered()), this, SLOT(on_treeEdit_triggered()));
viewButtonGroup->addAction(r);
menu->addAction(r);
r->setChecked(_editMode == EditMode::TREEEDIT);
menuBar->insertMenu(actions.at(pos+offset -1), menu);//menu, pos + offset);
menu = new QMenu(tr("Tools")); // NOI18N
// menu.setMnemonic(KeyEvent.VK_T);
QAction* item = new QAction(tr("Open PickList Tables"), this); // NOI18N
// item.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// openPickListTable();
// }
// });
connect(item, SIGNAL(triggered()), this, SLOT(openPickListTable()));
menu->addAction(item);
item = new QAction(tr("Find Orphans"), this); // NOI18N
// item.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// findOrphansPressed(e);
// }
// });
connect(item, SIGNAL(triggered()),this, SLOT(findOrphansPressed()));
menu->addAction(item);
item = new QAction(tr("Empty Conditionals"), this); // NOI18N
// item.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// findEmptyPressed(e);
// }
// });
connect(item, SIGNAL(triggered()),this, SLOT(findEmptyPressed()));
menu->addAction(item);
item = new QAction(tr("Cross Reference"), this); // NOI18N
// item.addActionListener(new ActionListener() {
// BeanTableFrame parent;
// @Override
// public void actionPerformed(ActionEvent e) {
// new RefDialog(parent);
// }
// ActionListener init(BeanTableFrame f) {
// parent = f;
// return this;
// }
// }.init(f));
CrossReferenceActionListener* listener = new CrossReferenceActionListener(f, this);
connect(item, SIGNAL(triggered()), listener->self(), SLOT(actionPerformed()));
menu->addAction(item);
item = new QAction(tr("Display Where Used"), this); // NOI18N
// item.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// makeWhereUsedWindow();
// }
// });
connect(item, SIGNAL(triggered()), this, SLOT(makeWhereUsedWindow()));
menu->addAction(item);
//menuBar->addMenu(menu, pos + offset + 1); // add this menu to the right of the previous
//menu->insertMenu(actions.at(pos+offset-1), menu);
menuBar->addMenu(menu);
}
CrossReferenceActionListener::CrossReferenceActionListener(BeanTableFrame* frame, LogixTableAction* parent)
{
this->frame = frame;
this->parent = parent;
}
void CrossReferenceActionListener::actionPerformed(JActionEvent *)
{
new RefDialog(frame, parent);
}
void LogixTableAction::on_useMulti_triggered()
{
setSelectionMode(SelectionMode::USEMULTI);
}
void LogixTableAction::on_useSingle_triggered()
{
setSelectionMode(SelectionMode::USESINGLE);
}
void LogixTableAction::on_useComboNameBoxes_triggered()
{
setSelectionMode(SelectionMode::USECOMBO);
}
void LogixTableAction::on_listEdit_triggered()
{
setEditorMode(EditMode::LISTEDIT);
}
void LogixTableAction::on_treeEdit_triggered()
{
setEditorMode(EditMode::TREEEDIT);
}
/**
* Get the saved mode selection, default to the tranditional tabbed pick
* list.
* <p>
* During the menu build process, the corresponding menu item is set to
* selected.
*
* @since 4.7.3
*/
void LogixTableAction::loadSelectionMode()
{
QVariant modeName = ((UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager"))->
getProperty(getClassName(), "Selection Mode"); // NOI18N
if (modeName == QVariant()) {
_selectionMode = SelectionMode::USEMULTI;
} else {
QString currentMode = modeName.toString();
if (currentMode== "USEMULTI") // NOI18N
_selectionMode = SelectionMode::USEMULTI;
else if(currentMode == "USESINGLE") // NOI18N
_selectionMode = SelectionMode::USESINGLE;
else if(currentMode == "USECOMBO") // NOI18N
_selectionMode = SelectionMode::USECOMBO;
else
log->warn(tr("Invalid Logix conditional selection mode value, '%1', returned").arg(currentMode)); // NOI18N
_selectionMode = SelectionMode::USEMULTI;
}
}
/**
* Save the mode selection. Called by menu item change events.
*
* @since 4.7.3
* @param newMode The SelectionMode enum constant
*/
void LogixTableAction::setSelectionMode(SelectionMode newMode) {
_selectionMode = newMode;
((UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager"))->setProperty(getClassName(), "Selection Mode", /*newMode->toString()*/selectionModes.at((int)newMode)); // NOI18N
}
/**
* Get the saved mode selection, default to the tranditional conditional
* list editor
* <p>
* During the menu build process, the corresponding menu item is set to
* selected.
*
* @since 4.9.x
*/
void LogixTableAction::loadEditorMode() {
QVariant modeName = ((UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager"))->
getProperty(getClassName(), "Edit Mode"); // NOI18N
if (modeName == QVariant()) {
_editMode = EditMode::LISTEDIT;
} else {
QString currentMode = modeName.toString();
if (currentMode == "LISTEDIT") // NOI18N
_editMode = EditMode::LISTEDIT;
else if (currentMode == "TREEEDIT") // NOI18N
_editMode = EditMode::TREEEDIT;
else
{
log->warn(tr("Invalid conditional edit mode value, '%1', returned").arg(currentMode)); // NOI18N
_editMode = EditMode::LISTEDIT;
}
}
}
/**
* Save the view mode selection. Called by menu item change events.
*
* @since 4.9.x
* @param newMode The ViewMode enum constant
*/
void LogixTableAction::setEditorMode(EditMode newMode) {
_editMode = newMode;
((UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager"))->setProperty(getClassName(), "Edit Mode", editModes.at((int)newMode)); // NOI18N
}
/**
* Open a new Pick List to drag Actions from to form Logix Conditionals.
*/
void LogixTableAction::openPickListTable() {
if (_pickTables == nullptr) {
_pickTables = new PickFrame(tr("Pick List")); // NOI18N
} else {
_pickTables->setVisible(true);
}
_pickTables->toFront();
}
void LogixTableAction::crossReference_requested()
{
RefDialog* dlg = new RefDialog(f,this);
dlg->exec();
}
void LogixTableAction::findEmptyPressed(ActionEvent* /*e*/) {
Maintenance::findEmptyPressed(f);
}
void LogixTableAction::findOrphansPressed(ActionEvent* /*e*/) {
Maintenance::findOrphansPressed(f);
}
//class RefDialog extends JDialog {
RefDialog::RefDialog(BeanTableFrame *frame, LogixTableAction* action) : JDialog(frame, tr("CrossReference"), true)
{
//super(frame, tr("CrossReference"), true);
this->action = action;
QWidget* extraPanel = new QWidget();
extraPanel->setLayout(new QVBoxLayout(extraPanel));
_devNameField = new JTextField(30);
QWidget* panel = action->makeEditPanel(_devNameField, "Element Name", "System or User name of an element to find where it is referenced.");
QPushButton* referenceButton = new QPushButton(tr("Get References"));
panel->layout()->addWidget(referenceButton);
// referenceButton->layout()->addActionListener(new ActionListener() {
// /*public*/ void actionPerformed(ActionEvent e) {
// deviceReportPressed(e);
// }
// });
connect(referenceButton, SIGNAL(clicked()), this, SLOT(deviceReportPressed()));
panel->layout()->addWidget(referenceButton);
extraPanel->layout()->addWidget(panel);
//setContentPane(extraPanel);
setLayout(new QVBoxLayout());
layout()->addWidget(extraPanel);
adjustSize();
// setLocationRelativeTo((java.awt.Component)_pos);
setVisible(true);
exec();
}
void RefDialog::deviceReportPressed(JActionEvent* /*e*/)
{
Maintenance::deviceReportPressed(_devNameField->text(), NULL);
//dispose();
close();
}
//};
void LogixTableAction::enableAll(bool enable) {
QStringList sysNameList = ((DefaultLogixManager*)_logixManager)->AbstractManager::getSystemNameList();
for (int i=0; i<sysNameList.size(); i++) {
Logix* x = (Logix*)((DefaultLogixManager*)_logixManager)->getBySystemName(sysNameList.at(i))->self();
((DefaultLogix*)x)->setEnabled(enable);
}
}
/*protected*/ QString LogixTableAction::helpTarget() {
return "package.jmri.jmrit.beantable.LogixTable";
}
// /*static*/ /*final*/ int LogixTableAction::STRUT = 10;
// *********** Methods for Add Logix Window ********************
/**
* Responds to the Add button in Logix table Creates and/or initializes the
* Add Logix window
*/
/*protected*/ void LogixTableAction::addPressed(ActionEvent* /*e*/)
{
// possible change
if (!checkFlags(NULL))
{
return;
}
_showReminder = true;
// make an Add Logix Frame
if (addLogixFrame == NULL)
{
QWidget* panel5 = makeAddLogixFrame(tr("Add Logix"), tr("Please enter system name and user name, then","click Create Logix, then add Conditionals."));
// Create Logix
create = new QPushButton(tr("Create Logix"));
// QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// sizePolicy.setVerticalStretch(0);
// sizePolicy.setHorizontalStretch(0);
// sizePolicy.setWidthForHeight(create->sizePolicy().hasHeightForWidth());
// create->setSizePolicy(sizePolicy);
panel5->layout()->addWidget(create);
// create->layout()->addActionListener(new ActionListener() {
// /*public*/ void actionPerformed(ActionEvent e) {
// createPressed(e);
// }
// });
connect(create, SIGNAL(clicked()), this, SLOT(createPressed()));
create->setToolTip(tr("Press to create a new Logix"));
}
addLogixFrame->pack();
addLogixFrame->setVisible(true);
_autoSystemName->setChecked(false);
if(((UserPreferencesManager*) prefMgr)->getSimplePreferenceState(systemNameAuto))
_autoSystemName->setChecked(true);
}
/**
* shared method for window to create or copy Logix
* Returns the button panel
*/
QWidget* LogixTableAction::makeAddLogixFrame(QString titleId, QString messageId1,QString messageId2)
{
addLogixFrame = new JmriJFrameX(titleId,true,true);
addLogixFrame->addHelpMenu(
"package.jmri.jmrit.beantable.LogixAddEdit", true);
addLogixFrame->setLocation(50, 30);
addLogixFrame->setDefaultCloseOperation(JFrame::HIDE_ON_CLOSE);
if(addLogixFrame->centralWidget() == NULL)
{
QWidget* centralWidget = new QWidget();
centralWidget->setLayout(new QVBoxLayout);
addLogixFrame->setCentralWidget(centralWidget);
}
QWidget* contentPane = addLogixFrame->centralWidget();
contentPane->setLayout(new QVBoxLayout(contentPane/*, BoxLayout.Y_AXIS*/));
QWidget* p;
p = new QWidget();
//p->setLayout(new QHBoxLayout());
QGridLayout* g;
p->setLayout(g = new QGridLayout());
GridBagConstraints* c = new GridBagConstraints();
c->gridwidth = 1;
c->gridheight = 1;
c->gridx = 0;
c->gridy = 0;
c->anchor = GridBagConstraints::EAST;
g->addWidget(_sysNameLabel,c->gridy, c->gridx, c->rowSpan(),c->colSpan());
c->gridy = 1;
g->addWidget(_userNameLabel,c->gridy, c->gridx, c->rowSpan(),c->colSpan());
c->gridx = 1;
c->gridy = 0;
c->anchor = GridBagConstraints::WEST;
c->weightx = 1.0;
c->fill = GridBagConstraints::HORIZONTAL; // text field will expand
g->addWidget(_systemName,c->gridy,c->gridx, c->rowSpan(),c->colSpan());
c->gridy = 1;
g->addWidget(_addUserName,c->gridy,c->gridx, c->rowSpan(),c->colSpan());
c->gridx = 2;
c->gridy = 1;
c->anchor = GridBagConstraints::WEST;
c->weightx = 1.0;
c->fill = GridBagConstraints::HORIZONTAL; // text field will expand
c->gridy = 0;
g->addWidget(_autoSystemName,c->gridy,c->gridx, c->rowSpan(),c->colSpan());
_addUserName->setToolTip(tr("Enter user name for new Logix, e.g. Signal 2 Control"));
_systemName->setToolTip(tr("Enter system name for new Logix, e.g.IX13"));
contentPane->layout()->addWidget(p);
// set up message
QWidget* panel3 = new QWidget();
panel3->setLayout(new QVBoxLayout(panel3/*, BoxLayout.Y_AXIS*/));
QWidget* panel31 = new QWidget();
panel31->setLayout(new QHBoxLayout());
QLabel* message1 = new QLabel(messageId1);
panel31->layout()->addWidget(message1);
QWidget* panel32 = new QWidget();
panel32->setLayout(new QHBoxLayout());
QLabel* message2 = new QLabel(messageId2);
panel32->layout()->addWidget(message2);
panel3->layout()->addWidget(panel31);
panel3->layout()->addWidget(panel32);
contentPane->layout()->addWidget(panel3);
// set up create and cancel buttons
QWidget* panel5 = new QWidget();
panel5->setLayout(new QHBoxLayout());
// Cancel
QPushButton* cancel = new QPushButton(tr("Cancel"));
// QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// sizePolicy.setHorizontalStretch(0);
// sizePolicy.setVerticalStretch(0);
// sizePolicy.setHeightForWidth(cancel->sizePolicy().hasHeightForWidth());
// cancel->setSizePolicy(sizePolicy);
panel5->layout()->addWidget(cancel);
// cancel->layout()->addActionListener(new ActionListener() {
// /*public*/ void actionPerformed(ActionEvent e) {
// cancelAddPressed(e);
// }
// });
connect(cancel, SIGNAL(clicked()), this, SLOT(cancelAddPressed()));
cancel->setToolTip(tr("Press to return to Logix Table without any changes"));
// addLogixFrame->addWindowListener(new java.awt.event.WindowAdapter() {
// /*public*/ void windowClosing(java.awt.event.WindowEvent e) {
// cancelAddPressed(NULL);
// }
// });
addLogixFrame->addWindowListener(addLogixFrameWindowListener = new AddLogixFrameWindowListener(this));
((QVBoxLayout*)contentPane->layout())->addWidget(panel5,0,Qt::AlignCenter);
// _autoSystemName->layout()->addWidgetItemListener(
// new ItemListener() {
// /*public*/ void itemStateChanged(ItemEvent e){
// autoSystemName();
// }
// });
connect(_autoSystemName, SIGNAL(toggled(bool)), this, SLOT(autoSystemName()));
return panel5;
}
AddLogixFrameWindowListener::AddLogixFrameWindowListener(LogixTableAction *self)
{
this->self = self;
}
void AddLogixFrameWindowListener::windowClosing(QCloseEvent * e)
{
e->ignore();
self->cancelAddPressed(NULL);
}
void LogixTableAction::autoSystemName(){
if (_autoSystemName->isChecked()){
_systemName->setEnabled(false);
_sysNameLabel->setEnabled(false);
}
else {
_systemName->setEnabled(true);
_sysNameLabel->setEnabled(true);
}
}
/**
* Responds to the Cancel button in Add Logix window Note: Also get there if
* the user closes the Add Logix window
*/
void LogixTableAction::cancelAddPressed(ActionEvent* /*e*/) {
addLogixFrame->setVisible(false);
addLogixFrame->dispose();
addLogixFrame = NULL;
_inCopyMode = false;
if (f!=NULL)
f->setVisible(true);
}
void LogixTableAction::copyPressed(QString sName)
{
if (!checkFlags(sName))
{
return;
}
// Thread t = new Thread() {
// /*public*/ void run() {
// //Thread.yield();
QWidget* panel5 = makeAddLogixFrame(tr("Copy Logix", "Please enter system name and user name"), tr("of target Logix, then click Copy"));
// Create Logix
QPushButton* create = new QPushButton(tr("Copy"));
panel5->layout()->addWidget(create);
// create->layout()->addActionListener(new ActionListener() {
// /*public*/ void actionPerformed(ActionEvent e) {
// copyLogixPressed(e);
// }
// });
addLogixFrame->adjustSize();
addLogixFrame->setVisible(true);
_autoSystemName->setChecked(false);
if(((UserPreferencesManager*)prefMgr)->getSimplePreferenceState(systemNameAuto))
_autoSystemName->setChecked(true);
// }
// };
if (log->isDebugEnabled()) log->debug("copyPressed Thread started for " + sName);
//javax.swing.SwingUtilities.invokeLater(t);
//t.start();
_inCopyMode = true;
_logixSysName = sName;
}
void LogixTableAction::copyLogixPressed(ActionEvent* /*e*/)
{
QString uName = _addUserName->text().trimmed();
if (uName.length()==0)
{
uName = "";
}
Logix* targetLogix;
if(_autoSystemName->isChecked())
{
if (!checkLogixUserName(uName))
return;
targetLogix = _logixManager->createNewLogix(uName);
}
else
{
if (!checkLogixSysName())
{
return;
}
QString sName = _systemName->text().trimmed();
// check if a Logix with this name already exists
bool createLogix = true;
targetLogix = (Logix*)((DefaultLogixManager*)_logixManager)->getBySystemName(sName)->self();
if (targetLogix != NULL)
{
// int result = JOptionPane.showConfirmDialog(f, java.text.MessageFormat.format(
// tr("ConfirmLogixDuplicate"),
// new Object[] {sName, _logixSysName}),
// tr("ConfirmTitle"), JOptionPane.YES_NO_OPTION,
// JOptionPane.QUESTION_MESSAGE);
if (QMessageBox::question(0, tr("Question"), tr("Logix \"%1\" already exists. Do you want copy\nthe Conditionals of Logix \"%2\" into \"%1\"?").arg(sName).arg(_logixSysName),QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
{
return;
}
createLogix = false;
QString userName = ((DefaultLogix*)targetLogix)->getUserName();
if (userName.length() > 0)
{
_addUserName->setText(userName);
uName = userName;
}
}
else if (!checkLogixUserName(uName))
{
return;
}
if (createLogix)
{
// Create the new Logix
targetLogix = ((DefaultLogixManager*)_logixManager)->createNewLogix(sName, uName);
if (targetLogix == NULL)
{
// should never get here unless there is an assignment conflict
log->error("Failure to create Logix with System Name: " + sName);
return;
}
}
else if (targetLogix == NULL)
{
log->error("Error targetLogix is NULL!");
return;
}
else
{
((DefaultLogix*)targetLogix)->setUserName(uName);
}
}
Logix* srcLogic = (Logix*)((DefaultLogixManager*)_logixManager)->getBySystemName(_logixSysName)->self();
for (int i=0; i< ((DefaultLogix*)srcLogic)->getNumConditionals(); i++)
{
QString cSysName = ((DefaultLogix*)srcLogic)->getConditionalByNumberOrder(i);
copyConditionalToLogix(cSysName, srcLogic, targetLogix);
}
cancelAddPressed(NULL);
}
void LogixTableAction::copyConditionalToLogix(QString cSysName, Logix* /*srcLogix*/, Logix* targetLogix)
{
Conditional* cOld = ((DefaultConditionalManager*)_conditionalManager)->getBySystemName(cSysName);
if (cOld == NULL)
{
log->error("Failure to find Conditional with System Name: " + cSysName);
return;
}
QString cOldSysName = ((DefaultConditional*)cOld)->getSystemName();
QString cOldUserName = ((DefaultConditional*)cOld)->getUserName();
// make system name for new conditional
int num = ((DefaultLogix*)targetLogix)->getNumConditionals()+1;
QString cNewSysName = ((DefaultLogix*)targetLogix)->getSystemName() + "C" + QString::number(num);
// add to Logix at the end of the calculate order
QString cNewUserName = tr("Copy of %1").arg(cOldUserName);
if (cOldUserName.length() == 0)
{
cNewUserName += "C"+QString::number(num);
}
do
{
// cNewUserName = JOptionPane.showInputDialog(f, java.text.MessageFormat.format(
// tr("NameConditionalCopy"), new Object[] {
// cOldUserName, cOldSysName, _logixSysName,
// targetLogix.getUserName(), targetLogix.getSystemName()}),
// cNewUserName);
QString msg = tr("Rename the copy of Conditional \"%1\" (%2)\nin Logix %3 being copied into Logix \"%4\" (%5).\nPress Cancel if you don't want to copy this conditional.").arg(cOldUserName).arg(cOldSysName).arg(((DefaultLogix*)targetLogix)->getUserName()).arg(((DefaultLogix*)targetLogix)->getSystemName()).arg(cNewUserName);
InputDialog* dlg = new InputDialog(msg,cNewUserName);
if(dlg->exec() == QDialog::Accepted)
{
cNewUserName = dlg->value();
if (cNewUserName == NULL || cNewUserName.length()==0)
{
return;
}
}
} while (!checkConditionalUserName(cNewUserName, targetLogix) );
while (!checkConditionalSystemName(cNewSysName))
{
cNewSysName = ((DefaultLogix*)targetLogix)->getSystemName() + "C" + QString::number(++num);
}
Conditional* cNew = ((DefaultConditionalManager*)_conditionalManager)->createNewConditional(cNewSysName, cNewUserName);
if (cNew == NULL)
{
// should never get here unless there is an assignment conflict
log->error("Failure to create Conditional with System Name: \""
+ cNewSysName+"\" and User Name: \""+ cNewUserName+"\"");
return;
}
((DefaultConditional*)cNew)->setLogicType(((DefaultConditional*)cOld)->getLogicType(), ((DefaultConditional*)cOld)->getAntecedentExpression());
((DefaultConditional*)cNew)->setStateVariables(((DefaultConditional*)cOld)->getCopyOfStateVariables());
((DefaultConditional*)cNew)->setAction(((DefaultConditional*)cOld)->getCopyOfActions());
((DefaultLogix*)targetLogix)->addConditional(cNewSysName, -1);
// Update where used with the copy results
_saveTargetNames.clear();
QSet<QString> newTargetNames = QSet<QString>();
loadReferenceNames(*cOld->getCopyOfStateVariables(), newTargetNames.toList());
updateWhereUsed(newTargetNames, cNewSysName);
}
bool LogixTableAction::checkLogixUserName(QString uName)
{
// check if a Logix with the same user name exists
if (uName!=NULL && uName.trimmed().length() > 0)
{
Logix* x = (Logix*)((DefaultLogixManager*)_logixManager)->getByUserName(uName)->self();
if (x != NULL)
{
// // Logix with this user name already exists
// javax.swing.JOptionPane.showMessageDialog(addLogixFrame,
// tr("Error3"), tr("ErrorTitle"),
// javax.swing.JOptionPane.ERROR_MESSAGE);
QMessageBox::critical(addLogixFrame, tr("Error"), tr("A Logix with this user name already exists.\nPlease change user name and try again."));
return false;
}
}
return true;
}
bool LogixTableAction::checkLogixSysName()
{
// check validity of Logix system name
QString sName = _systemName->text().trimmed();
if ( (sName.length() < 1))
{
// Entered system name is blank or too short
// javax.swing.JOptionPane.showMessageDialog(addLogixFrame,
// tr("Error8"), tr("ErrorTitle"),
// javax.swing.JOptionPane.ERROR_MESSAGE);
QMessageBox::critical(addLogixFrame, tr("Error"), tr("Invalid system name, or system name not entered./nPlease enter a valid Logix system name (e.g. IX3) and try again."));
return false;
}
if ((sName.length() < 2) || (sName.at(0) != 'I')
|| (sName.at(1) != 'X'))
{
// System name does not begin with IX, prefix IX to it
QString s = sName;
sName = "IX" + s;
}
_systemName->setText(sName);
return true;
}
bool LogixTableAction::checkFlags(QString sName)
{
if (_inEditMode)
{
// Already editing a Logix, ask for completion of that edit
JOptionPane::showMessageDialog(nullptr,
tr("Cannot edit two Logixs at the same time. Please complete edit of Logix \"%1\" and try again.").arg(_curLogix->getSystemName()), tr("Error"),
JOptionPane::ERROR_MESSAGE);
if (_treeEdit != nullptr) {
_treeEdit->bringToFront();
} else if (_listEdit != nullptr) {
_listEdit->bringToFront();
}
return false;
}
if (_inCopyMode) {
// Already editing a Logix, ask for completion of that edit
// javax.swing.JOptionPane.showMessageDialog(editLogixFrame,
// java.text.MessageFormat.format(tr("Error31"),
// new Object[] { _logixSysName }), tr("ErrorTitle"),
// javax.swing.JOptionPane.ERROR_MESSAGE);
QMessageBox::critical(nullptr,tr("Error"), tr("Copy of Logix \"{0}\" in progress. Please complete and try again.").arg(_logixSysName) );
return false;
}
if (sName != "") {
// check if a Logix with this name exists
Logix* x = (Logix*)_logixManager->getBySystemName(sName)->self();
if (x == nullptr) {
// Logix does not exist, so cannot be edited
log->error("No Logix with system name: " + sName);
JOptionPane::showMessageDialog(nullptr, tr("Cannot find a Logix with that system name."), tr("Error"), JOptionPane::ERROR_MESSAGE);
return false;
}
}
return true;
}
/**
* Responds to the Create Logix button in Add Logix window
*/
void LogixTableAction::createPressed(ActionEvent* /*e*/)
{
// possible change
_showReminder = true;
QString sName = "";
QString uName = _addUserName->text().trimmed();
if (uName.length() == 0) {
uName = "";
}
if (_autoSystemName->isChecked())
{
if (!checkLogixUserName(uName)) {
return;
}
_curLogix = _logixManager->createNewLogix(uName);
sName = _curLogix->getSystemName();
}
else
{
if (!checkLogixSysName()) {
return;
}
// Get validated system name
sName = _systemName->text();
// check if a Logix with this name already exists
Logix* x = NULL;
try {
x = (Logix*)_logixManager->getBySystemName(sName)->self();
if(x == NULL) throw new Exception();
} catch (Exception* ex) {
// user input no good
handleCreateException(sName);
return; // without creating
}
if (x != NULL) {
// Logix already exists
JOptionPane::showMessageDialog(addLogixFrame, tr("A Logix with this system name already exists.\nPlease change system name and try again."), tr("Error"), // NOI18N
JOptionPane::ERROR_MESSAGE);
return;
}
if (!checkLogixUserName(uName)) {
return;
}
// Create the new Logix
_curLogix = _logixManager->createNewLogix(sName, uName);
if (_curLogix == NULL) {
// should never get here unless there is an assignment conflict
log->error("Failure to create Logix with System Name: " + sName); // NOI18N
return;
}
}
cancelAddPressed(NULL);
// create the Edit Logix Window
editPressed(sName);
prefMgr = ((UserPreferencesManager*)InstanceManager::getOptionalDefault("UserPreferencesManager"));
if(prefMgr != NULL)
{
prefMgr->setSimplePreferenceState(systemNameAuto, _autoSystemName->isChecked());
};//);
}
void LogixTableAction::handleCreateException(QString sysName) {
JOptionPane::showMessageDialog(addLogixFrame,
tr("ErrorLogixAddFailed %1").arg( // NOI18N
sysName),
tr("Error"), // NOI18N
JOptionPane::ERROR_MESSAGE);
}
// *********** Methods for Edit Logix Window ********************
/**
* Responds to the Edit button pressed in Logix table
*
* @param sName system name of Logix to be edited
*/
void LogixTableAction::editPressed(QString sName) {
_curLogix = (Logix*)_logixManager->getBySystemName(sName)->self();
if (!checkFlags(sName)) {
return;
}
if (sName == (SensorGroupFrame::logixSysName)) {
// Sensor group message
JOptionPane::showMessageDialog(
NULL, tr("Conditionals in Logix \"%1\" (%2) cannot be edited.\nGo to the Sensor Group Table to edit sensor groups.").arg(SensorGroupFrame::logixUserName).arg(SensorGroupFrame::logixSysName), // NOI18N
tr("Warning"), // NOI18N
JOptionPane::WARNING_MESSAGE);
return;
}
// Create a new conditional edit view, add the listener.
if (_editMode == EditMode::TREEEDIT)
{
_treeEdit = new ConditionalTreeEdit(sName);
_inEditMode = true;
_treeEdit->addLogixEventListener(new LTALogixEventListener(sName, this));
// {
// //@Override
// public void logixEventOccurred() {
// String lgxName = sName;
// _treeEdit.logixData.forEach((key, value) -> {
// if (key == ("Finish")) { // NOI18N
// _treeEdit = NULL;
// _inEditMode = false;
// _curLogix.activateLogix();
// f.setVisible(true);
// } else if (key == ("Delete")) { // NOI18N
// deletePressed(value);
// } else if (key == ("chgUname")) { // NOI18N
// Logix x = _logixManager.getBySystemName(lgxName);
// x.setUserName(value);
// m.fireTableDataChanged();
// }
// });
// }
// });
}
else {
_listEdit = new ConditionalListEdit(sName);
_inEditMode = true;
_listEdit->addLogixEventListener(new LTALogixEventListener1(sName, this));
// {
// //@Override
// public void logixEventOccurred() {
// String lgxName = sName;
// _listEdit.logixData.forEach((key, value) -> {
// if (key == ("Finish")) { // NOI18N
// _listEdit = NULL;
// _inEditMode = false;
// _curLogix.activateLogix();
// f.setVisible(true);
// } else if (key == ("Delete")) { // NOI18N
// deletePressed(value);
// } else if (key == ("chgUname")) { // NOI18N
// Logix x = _logixManager.getBySystemName(lgxName);
// x.setUserName(value);
// m.fireTableDataChanged();
// }
// });
// }
// });
}
}
/*public*/ LTALogixEventListener::LTALogixEventListener(QString sName, LogixTableAction *lta) : LogixEventListener((ConditionalEditBase*)lta)
{
this->sName = sName;
this->lta = lta;
}
/*public*/ void LTALogixEventListener::logixEventOccurred() {
QString lgxName = sName;
//_treeEdit.logixData.forEach((key, value) ->
QMapIterator<QString, QString> iter(*lta->_treeEdit->logixData);
while(iter.hasNext())
{
iter.next();
QString key = iter.key();
QString value = iter.value();
if (key == ("Finish")) { // NOI18N
lta->_treeEdit = NULL;
lta->_inEditMode = false;
lta->_curLogix->activateLogix();
lta->f->setVisible(true);
} else if (key == ("Delete")) { // NOI18N
lta->deletePressed(value);
} else if (key == ("chgUname")) { // NOI18N
Logix* x = (Logix*)lta->_logixManager->getBySystemName(lgxName)->self();
x->setUserName(value);
lta->m->fireTableDataChanged();
}
};//);
}
/*public*/ LTALogixEventListener1::LTALogixEventListener1(QString sName, LogixTableAction *lta) : LogixEventListener((ConditionalEditBase*)lta)
{
this->sName = sName;
this->lta = lta;
}
//@Override
/*public*/ void LTALogixEventListener1::logixEventOccurred()
{
QString lgxName = sName;
//_listEdit.logixData.forEach((key, value) ->
if(lta->_listEdit->logixData == nullptr) return;
QMapIterator<QString, QString> iter(*lta->_listEdit->logixData);
while(iter.hasNext())
{
iter.next();
QString key = iter.key();
QString value = iter.value();
if (key == ("Finish")) { // NOI18N
lta->_listEdit = NULL;
lta->_inEditMode = false;
lta->_curLogix->activateLogix();
lta->f->setVisible(true);
} else if (key == ("Delete")) { // NOI18N
lta->deletePressed(value);
} else if (key == ("chgUname")) { // NOI18N
Logix* x = (Logix*)lta->_logixManager->getBySystemName(lgxName)->self();
x->setUserName(value);
lta->m->fireTableDataChanged();
}
};//);
}
/**
* Display reminder to save.
*/
void LogixTableAction::showSaveReminder() {
if (_showReminder) {
if (InstanceManager::getNullableDefault("UserPreferencesManager") != NULL) {
((UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager"))->showInfoMessage(tr("Reminder"), tr("<html>Remember to save your %1 information in your Configuration.<br>(choose Store > Store Configuration... from the File menu)</html>").arg("Logix"),(getClassName()),
"remindSaveLogix"); // NOI18N
}
}
}
/*public*/ void LogixTableAction::setMessagePreferencesDetails()
{
QMap<int,QString>* options = new QMap< int,QString>(/*3*/);
options->insert(0x00, tr("Always Ask"));
options->insert(0x01, tr("Never Delete"));
options->insert(0x02, tr("Delete Without Prompting"));
((UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager"))->setMessageItemDetails(getClassName(), "delete", tr("When Deleting the logix"), options, 0x00);
((UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager"))->setPreferenceItemDetails(getClassName(), "remindSaveLogix", tr("Suppress Save Reminders"));
AbstractTableAction::setMessagePreferencesDetails();
}
void LogixTableAction::deletePressed(ActionEvent */*e*/)
{
deletePressed("");
}
/**
* Respond to the Delete combo selection Logix window or conditional view
* delete request.
*
* @param sName system name of bean to be deleted
*/
void LogixTableAction::deletePressed(QString sName) {
if (!checkFlags(sName)) {
return;
}
if (!checkConditionalReferences(sName)) {
return;
}
/*final*/ Logix* x = (Logix*)_logixManager->getBySystemName(sName)->self();
UserPreferencesManager* p;
p = (UserPreferencesManager*)InstanceManager::getNullableDefault("UserPreferencesManager");
if (p != NULL && p->getMultipleChoiceOption(getClassName(), "delete") == 0x02) { // NOI18N
if (x != NULL) {
_logixManager->deleteLogix(x);
deleteSourceWhereUsed();
}
} else {
/*final*/ JDialog* dialog = new JDialog();
QString msg;
dialog->setTitle(tr("Confirm")); // NOI18N
dialog->setLocationRelativeTo(NULL);
dialog->setDefaultCloseOperation(JFrame::DISPOSE_ON_CLOSE);
QWidget* container = new QWidget();
//container.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
QVBoxLayout* containerLayout;
container->setLayout(containerLayout =new QVBoxLayout()); //container, BoxLayout.Y_AXIS));
msg = tr("Are you sure you want to delete Logix \"%1\"?").arg(sName); // NOI18N
QLabel* question = new QLabel(msg);
//question.setAlignmentX(Component.CENTER_ALIGNMENT);
containerLayout->addWidget(question, 0, Qt::AlignCenter);
QCheckBox* remember = new QCheckBox(tr("MessageRememberSetting")); // NOI18N
//remember->setFont(remember->getFont().deriveFont(10f));
QFont f = remember->font();
f.setPointSizeF(10.);
remember->setFont(f);
//remember.setAlignmentX(Component.CENTER_ALIGNMENT);
QPushButton* yesButton = new QPushButton(tr("Yes")); // NOI18N
QPushButton* noButton = new QPushButton(tr("No")); // NOI18N
QWidget* button = new QWidget();
FlowLayout* buttonLayout = new FlowLayout(button);
//button.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonLayout->addWidget(yesButton);
buttonLayout->addWidget(noButton);
containerLayout->addWidget(button);
// noButton.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// //there is no point in remebering this the user will never be
// //able to delete a bean!
// /*if(remember.isSelected()){
// setDisplayDeleteMsg(0x01);
// }*/
// dialog.dispose();
// }
// });
connect(noButton, SIGNAL(clicked(bool)), this, SLOT(on_noButtonClicked()));
// yesButton.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// if (p != NULL && remember.isSelected()) {
// p.setMultipleChoiceOption(getClassName(), "delete", 0x02); // NOI18N
// }
// if (x != NULL) {
// _logixManager.deleteLogix(x);
// deleteSourceWhereUsed();
// }
// dialog.dispose();
// }
// });
connect(yesButton, SIGNAL(clicked(bool)), this, SLOT(on_yesButtonClicked()));
containerLayout->addWidget(remember);
// container.setAlignmentX(Component.CENTER_ALIGNMENT);
// container.setAlignmentY(Component.CENTER_ALIGNMENT);
dialog->getContentPane()->layout()->addWidget(container);
dialog->pack();
dialog->setModal(true);
dialog->setVisible(true);
}
f->setVisible(true);
}
void LogixTableAction::on_noButtonClicked()
{
//there is no point in remebering this the user will never be
//able to delete a bean!
/*if(remember.isSelected()){
setDisplayDeleteMsg(0x01);
}*/
//dialog->dispose();
dialog->close();
}
void LogixTableAction::on_yesButtonClicked()
{
if (p != NULL && remember->isChecked()) {
p->setMultipleChoiceOption(getClassName(), "delete", 0x02); // NOI18N
}
if (x != NULL) {
_logixManager->deleteLogix(x);
deleteSourceWhereUsed();
}
//dialog.dispose();
dialog->close();
}
/**
* Build a tree set from conditional references.
*
* @since 4.7.4
* @param varList The ConditionalVariable list that might contain
* conditional references
* @param treeSet A tree set to be built from the varList data
*/
void LogixTableAction::loadReferenceNames(QList<ConditionalVariable*> varList, QStringList treeSet) {
treeSet.clear();
for (ConditionalVariable* var : varList) {
if (var->getType() == Conditional::TYPE_CONDITIONAL_TRUE || var->getType() == Conditional::TYPE_CONDITIONAL_FALSE) {
treeSet.append(var->getName());
}
}
}
bool LogixTableAction::checkConditionalUserName(QString uName, Logix* logix) {
if ((uName != NULL) && (!(uName == ("")))) {
Conditional* p = _conditionalManager->getByUserName(logix, uName);
if (p != NULL) {
// Conditional with this user name already exists
log->error("Failure to update Conditional with Duplicate User Name: " // NOI18N
+ uName);
JOptionPane::showMessageDialog(
NULL, tr("New user name is already in use. Cannot update this Conditional.\nPlease change user name and try again."), // NOI18N
tr("Error"), // NOI18N
JOptionPane::ERROR_MESSAGE);
return false;
}
}
return true;
}
/**
* Check form of Conditional systemName.
*
* @param sName system name of bean to be checked
* @return false if sName is empty string or NULL
*/
bool LogixTableAction::checkConditionalSystemName(QString sName) {
if ((sName != NULL) && (!(sName == ("")))) {
Conditional* p = _conditionalManager->getBySystemName(sName);
if (p != NULL) {
return false;
}
} else {
return false;
}
return true;
}
/**
* Check for conditional references
*
* @since 4.7.4
* @param logixName The Logix under consideration
* @return true if no references
*/
bool LogixTableAction::checkConditionalReferences(QString logixName) {
_saveTargetList.clear();
Logix* x = _logixManager->getLogix(logixName);
int numConditionals = x->getNumConditionals();
if (numConditionals > 0) {
for (int i = 0; i < numConditionals; i++) {
QString csName = x->getConditionalByNumberOrder(i);
// If the conditional is a where used source, retain it for later
QList<QString> targetList =((ConditionalManager*) InstanceManager::getDefault("ConditionalManager"))->getTargetList(csName);
if (targetList.size() > 0) {
_saveTargetList.insert(csName, targetList);
}
// If the conditional is a where used target, check scope
QList<QString> refList =((ConditionalManager*) InstanceManager::getDefault("ConditionalManager"))->getWhereUsed(csName);
if (!refList.isEmpty()) {
for (QString refName : refList) {
Logix* xRef = _conditionalManager->getParentLogix(refName);
QString xsName = xRef->getSystemName();
if (logixName == (xsName)) {
// Member of the same Logix
continue;
}
// External references have to be removed before the Logix can be deleted.
Conditional* c = x->getConditional(csName);
Conditional* cRef = xRef->getConditional(refName);
QStringList msgs = QStringList() <<c->getUserName() << c->getSystemName() << cRef->getUserName() <<
cRef->getSystemName()<< xRef->getUserName()<< xRef->getSystemName();
JOptionPane::showMessageDialog(NULL,
tr("Conditional \"%1\" (%2) is a Conditional Variable in the Conditional,\n\"%3\" (%4), of Logix, \"%5\" (%6).\n Please remove that variable first.").arg(msgs.at(0)).arg(msgs.at(1)).arg(msgs.at(2)).arg(msgs.at(3)).arg(msgs.at(4)).arg(msgs.at(5)), // NOI18N
tr("ErrorTitle"), JOptionPane::ERROR_MESSAGE); // NOI18N
return false;
}
}
}
}
return true;
}
/**
* Remove target/source where used entries after a Logix delete
*
* @since 4.7.4
*/
void LogixTableAction::deleteSourceWhereUsed() {
// _saveTargetList.forEach((refName, targetList) -> {
foreach(QString refName, _saveTargetList.keys())
{
QList<QString> targetList = _saveTargetList.value(refName);
for (QString targetName : targetList)
{
((ConditionalManager*)InstanceManager::getDefault("ConditionalManager"))->removeWhereUsed(targetName, refName);
}
}//);
}
/**
* Update the conditional reference where used.
* <p>
* The difference between the saved target names and new target names is
* used to add/remove where used references.
*
* @since 4.7.4
* @param newTargetNames The conditional target names after updating
* @param refName The system name for the referencing conditional
*/
void LogixTableAction::updateWhereUsed(QSet<QString> newTargetNames, QString refName) {
QSet<QString> deleteNames = QSet<QString>(_saveTargetNames);
//deleteNames.removeAll(newTargetNames);
foreach (QString str, newTargetNames)
{
if(deleteNames.contains(str))
deleteNames.remove(str);
}
for (QString deleteName : deleteNames)
{
((ConditionalManager*) InstanceManager::getDefault("ConditionalManager"))->removeWhereUsed(deleteName, refName);
}
QSet<QString> addNames = QSet<QString>(newTargetNames);
//addNames.removeAll(_saveTargetNames);
foreach (QString str, _saveTargetNames)
{
if(addNames.contains(str))
addNames.remove(str);
}
for (QString addName : addNames) {
((ConditionalManager*) InstanceManager::getDefault("ConditionalManager"))->addWhereUsed(addName, refName);
}
}
/**
* Create Variable and Action editing pane center part.
*
* @param comp Field or comboBox to include on sub pane
* @param label property key for label
* @param hint property key for tooltip for this sub pane
* @return JPanel containing interface
*/
QWidget* LogixTableAction::makeEditPanel(QWidget* comp, QString label, QString hint) {
QWidget* panel = new QWidget();
//panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
QVBoxLayout* panelLayout = new QVBoxLayout(panel);
QWidget* p = new QWidget();
QHBoxLayout* pLayout = new QHBoxLayout(p);
pLayout->addWidget(new QLabel(label));
panelLayout->addWidget(p);
if (hint != NULL) {
panel->setToolTip(hint);
}
// comp->setMaximumSize(comp->sizeHint()); // override for text fields
panelLayout->addWidget(comp);
panelLayout->addWidget(Box::createVerticalGlue());
return panel;
}
#if 0
void LogixTableAction::itemStateChanged(int index)
{
compareTypeChanged(index);
_editVariableFrame->adjustSize();
}
void LogixTableAction::variableItemStateChanged(int index)
{
variableTypeChanged(index);
_editVariableFrame->adjustSize();
}
#endif
/***************************** Edit Action Window and methods ***********************/
LTAEditActionFrameWindowListener::LTAEditActionFrameWindowListener(LogixTableAction * /*zlta*/)
{
this->lta = lta;
}
void LTAEditActionFrameWindowListener::windowClosing(QCloseEvent */*e*/)
{
//lta->cancelEditActionPressed();
}
#if 0
void LogixTableAction::on_actionItemType_changed(int select)
{
if (log->isDebugEnabled()) log->debug("_actionItemTypeBoxListener: select= "+select);
actionItemChanged(select);
_editActionFrame->adjustSize();
}
void LogixTableAction::on_actionSetButton_Pressed()
{
validateAction();
// setFileLocation(/*e*/);
}
#endif
/******* Methods shared by Edit Variable and Edit Action Windows **********/
/**
* Validates Action data from Edit Action Window, and transfers it to
* current action object as appropriate
* <P>
* Returns true if all data checks out OK, otherwise false.
* <P>
* Messages are sent to the user for any errors found. This routine returns
* false immediately after finding an error, even if there might be more
* errors.
*/
/**
* Formats time to hh:mm given integer hour and minute
*/
/*public*/ /*static*/ QString LogixTableAction::formatTime(int hour, int minute) {
QString s = "";
QString t = QString::number(hour);
if (t.length() == 2) {
s = t + ":";
} else if (t.length() == 1) {
s = "0" + t + ":";
}
t = QString::number(minute);
if (t.length() == 2) {
s = s + t;
} else if (t.length() == 1) {
s = s + "0" + t;
}
if (s.length() != 5) {
// input error
s = "00:00";
}
return s;
}
/*public*/ QString LogixTableAction::getClassDescription() { return tr("Logix Table"); }
/*protected*/ QString LogixTableAction::getClassName() { return "jmri.jmrit.beantable.LogixTableAction"; }
// From AbstractAction
/**
* Sets whether the {@code Action} is enabled. The default is {@code true}.
*
* @param newValue {@code true} to enable the action, {@code false} to
* disable it
* @see Action#setEnabled
*/
/*public*/ void LogixTableAction::setEnabled(bool newValue)
{
bool oldValue = this->enabled;
if (oldValue != newValue)
{
this->enabled = newValue;
// firePropertyChange("enabled", Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
emit propertyChange("enabled", QVariant(oldValue), QVariant(newValue));
}
}
#if 0
// static /*final*/ org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogixTableAction.class.getName());
//}
/* @(#)LogixTableAction.java */
void LogixTableAction::editConditional(int i )
{
log->debug(tr("edit conditional row %1").arg(i));
editConditionalPressed(i);
}
QString LogixTableAction::getName()
{
return "jmri.jmrit.beantable.LogixTableAction";
}
#endif
//ItemDelegate::ItemDelegate(QStringList items, QObject *parent)
//: QAbstractItemDelegate(parent)
//{
// Items = items;
//}
//QWidget* ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex & /*index*/ ) const
//{
// QComboBox* editor = new QComboBox(parent);
// editor->addItems(Items);
// return editor;
//}
//void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
//{
// QComboBox *comboBox = static_cast<QComboBox*>(editor);
// int value = index.model()->data(index, Qt::EditRole).toUInt();
// comboBox->setCurrentIndex(value);
//}
//void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
//{
// QComboBox *comboBox = static_cast<QComboBox*>(editor);
// model->setData(index, comboBox->currentText(), Qt::EditRole);
//}
//void ItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
//{
// editor->setGeometry(option.rect);
//}
//void ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
//{
// QStyleOptionViewItemV4 myOption = option;
// QString text = Items.at(index.row());
// myOption.text = text;
// QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &myOption, painter);
//}
//QSize ItemDelegate::sizeHint(const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const
//{
// return QSize (80, 100);
//}
// ------------ Methods for Conditional References Window ------------
/**
* Builds the conditional references window when the Conditional Variable
* References menu item is selected.
* <p>
* This is a stand-alone window that can be closed at any time.
*
* @since 4.7.4
*/
void LogixTableAction::makeWhereUsedWindow() {
JmriJFrame* referenceListFrame = new JmriJFrameX(tr("Conditional Variable References"), false, true); // NOI18N
QWidget* contentPane = referenceListFrame->getContentPane();
QVBoxLayout* contentPaneLayout;
contentPane->setLayout(contentPaneLayout = new QVBoxLayout()); //(contentPane, BoxLayout.Y_AXIS));
// build header information
QWidget* panel1 = new QWidget();
FlowLayout* panel1Layout;
panel1->setLayout(panel1Layout = new FlowLayout());//FlowLayout::LEFT, 10, 5));
panel1Layout->addWidget(new QLabel(tr("Target"))); // NOI18N
panel1Layout->addWidget(new QLabel(tr("Source"))); // NOI18N
contentPaneLayout->addWidget(panel1);
// Build the conditional references listing
//QScrollArea* scrollPane = NULL;
HtmlTextEdit* textContent = buildWhereUsedListing();
// scrollPane = new QScrollArea(/*textContent*/);
// scrollPane->setWidget(textContent);
contentPaneLayout->addWidget(/*scrollPane*/textContent);
referenceListFrame->pack();
referenceListFrame->setVisible(true);
}
/**
* Creates a component containing the conditional reference where used list.
* The source is {@link jmri.ConditionalManager#getWhereUsedMap()}
*
* @return a TextArea, empty if reference is not used
* @since 4.7.4
*/
HtmlTextEdit* LogixTableAction::buildWhereUsedListing() {
HtmlTextEdit* condText = new HtmlTextEdit();
condText->setText("");
QMap<QString, QList<QString> > whereUsed = ((ConditionalManager*)InstanceManager::getDefault("ConditionalManager"))->getWhereUsedMap();
//SortedSet<String> targets = new TreeSet<>(whereUsed.keySet());
QStringList targets = whereUsed.keys();
//targets.forEach((target) -> {
foreach(QString target, targets)
{
condText->append("\n" + target + "\t" + getWhereUsedName(target) + " \n");
QList<QString> refNames = whereUsed.value(target);
//refNames.forEach((refName) ->
foreach(QString refName, refNames)
{
condText->append("\t\t" + refName + "\t" + getWhereUsedName(refName) + " \n");
}//);
} //);
//condText->setCaretPosition(0);
condText->setTabStopWidth(2); //setTabSize(2);
condText->setEditable(false);
return condText;
}
QString LogixTableAction::getWhereUsedName(QString cName) {
return _conditionalManager->getBySystemName(cName)->getUserName();
}
// ------------ Methods for Conditional Browser Window ------------
/**
* Responds to the Browse button pressed in Logix table
*
* @param sName The selected Logix system name
*/
void LogixTableAction::browserPressed(QString sName) {
// Logix was found, create the window
_curLogix = (Logix*)_logixManager->getBySystemName(sName)->self();
makeBrowserWindow();
}
/**
* creates and initializes the conditionals browser window
*/
void LogixTableAction::makeBrowserWindow() {
condBrowserFrame = new JmriJFrameX(tr("Conditional Browser"), false, true); // NOI18N
condBrowserFrame->addHelpMenu("package.jmri.jmrit.beantable.LogixAddEdit", true); // NOI18N
QWidget* contentPane = condBrowserFrame->getContentPane();
//contentPane.setLayout(new BorderLayout());
QVBoxLayout* contentPaneLayout = new QVBoxLayout(contentPane);
// LOGIX header information
QWidget* topPanel = new QWidget();
QHBoxLayout* topPanelLayout = new QHBoxLayout(topPanel);
QString tStr = tr("BrowserLogix") + " " + _curLogix->getSystemName() + " " // NOI18N
+ _curLogix->getUserName() + " "
+ ((_curLogix->getEnabled())
? tr("(Enabled)") // NOI18N
: tr("(Disabled)")); // NOI18N
topPanelLayout->addWidget(new QLabel(tStr));
contentPaneLayout->addWidget(topPanel,0, Qt::AlignTop);//, BorderLayout.NORTH);
// Build the conditionals listing
QScrollArea* scrollPane = NULL;
HtmlTextEdit* textContent = buildConditionalListing();
scrollPane = new QScrollArea();//JScrollPane(textContent);
scrollPane->setWidget(textContent);
scrollPane->setWidgetResizable(true);
contentPaneLayout->addWidget(scrollPane);
QWidget* bottomPanel = new QWidget();
//bottomPanel.setLayout(new BorderLayout());
QHBoxLayout* bottomPanelLayout = new QHBoxLayout(bottomPanel);
QPushButton* helpBrowse = new QPushButton(tr("Help")); // NOI18N
bottomPanelLayout->addWidget(helpBrowse, 0, Qt::AlignLeft);//BorderLayout.WEST);
// helpBrowse.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// JOptionPane.showMessageDialog(condBrowserFrame,
// tr("BrowserHelpText"), // NOI18N
// tr("BrowserHelpTitle"), // NOI18N
// JOptionPane.INFORMATION_MESSAGE);
// }
// });
connect(helpBrowse, SIGNAL(clicked()), this, SLOT(on_helpBrowse_triggered()));
QPushButton* saveBrowse = new QPushButton(tr("Save to Text File")); // NOI18N
saveBrowse->setToolTip(tr("Save the browser content to a text file")); // NOI18N
bottomPanelLayout->addWidget(saveBrowse, 0, Qt::AlignRight);//BorderLayout.EAST);
// saveBrowse.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// saveBrowserPressed();
// }
// });
connect(saveBrowse, SIGNAL(clicked()), this, SLOT(saveBrowserPressed()));
contentPaneLayout->addWidget(bottomPanel, 0, Qt::AlignBottom);//BorderLayout.SOUTH);
condBrowserFrame->pack();
condBrowserFrame->setVisible(true);
} // makeBrowserWindow
void LogixTableAction::on_helpBrowse_triggered()
{
JOptionPane::showMessageDialog(condBrowserFrame,
tr("Trigger state variables are indicated by [x].\nThe text file format is based on using a monospace font."), // NOI18N
tr("Browser Help"), // NOI18N
JOptionPane::INFORMATION_MESSAGE);
}
/**
* Save the Logix browser window content to a text file.
*/
void LogixTableAction::saveBrowserPressed() {
userFileChooser->setApproveButtonText(tr("Save Content")); // NOI18N
userFileChooser->setDialogTitle(tr("Save Browser Content")); // NOI18N
// userFileChooser->rescanCurrentDirectory();
// Default to logix system name.txt
userFileChooser->setSelectedFile(new File(_curLogix->getSystemName() + ".txt")); // NOI18N
int retVal = userFileChooser->showSaveDialog(NULL);
if (retVal != JFileChooser::APPROVE_OPTION) {
log->debug("Save browser content stopped, no file selected"); // NOI18N
return; // give up if no file selected or cancel pressed
}
File* file = userFileChooser->getSelectedFile();
log->debug(tr("Save browser content to '%1'").arg(file->toString())); // NOI18N
if (file->exists()) {
// Object[] options = {tr("BrowserSaveDuplicateReplace"), // NOI18N
// tr("BrowserSaveDuplicateAppend"), // NOI18N
// tr("BrowserSaveDuplicateCancel")}; // NOI18N
QVariantList options = QVariantList();
options << "Replace" << "Append" << "Cancel";
int selectedOption = JOptionPane::showOptionDialog(NULL,
tr("File \"%1\" already exists, select Append or Replace").arg( // NOI18N
file->getName()),
tr("Duplicate File"), // NOI18N
JOptionPane::DEFAULT_OPTION,
JOptionPane::WARNING_MESSAGE,
QIcon(), options, options.at(0));
if (selectedOption == 2 || selectedOption == -1) {
log->debug("Save browser content stopped, file replace/append cancelled"); // NOI18N
return; // Cancel selected or dialog box closed
}
if (selectedOption == 0) {
FileUtil::_delete(file); // Replace selected
}
}
// Create the file content
QString tStr = tr("BrowserLogix") + " " + _curLogix->getSystemName() + " " // NOI18N
+ _curLogix->getUserName() + " "
+ ((_curLogix->getEnabled())
? tr("(Enabled)") // NOI18N
: tr("(Disabled)")); // NOI18N
HtmlTextEdit* textContent = buildConditionalListing();
try {
// ADD Logix Header inforation first
FileUtil::appendTextToFile(file, tStr);
FileUtil::appendTextToFile(file, textContent->toPlainText());
} catch (IOException* e) {
log->error(tr("Unable to write browser content to '%1', exception: '%2'").arg(file->toString()).arg(e->getMessage())); // NOI18N
}
}
/**
* Builds a Component representing the current conditionals for the selected
* Logix statement.
*
* @return a TextArea listing existing conditionals; will be empty if there
* are none
*/
HtmlTextEdit* LogixTableAction::buildConditionalListing() {
QString showSystemName,
showCondName,
condName,
operand,
tStr;
QList<ConditionalVariable*>* variableList;
QList<ConditionalAction*>* actionList;
ConditionalVariable* variable;
ConditionalAction* action;
QString _antecedent = "";
HtmlTextEdit* condText = new HtmlTextEdit();
condText->setFont(QFont("Monospace",12));//new Font(Font.MONOSPACED, Font.PLAIN, 12));
condText->setText("");
int numConditionals = _curLogix->getNumConditionals();
for (int rx = 0; rx < numConditionals; rx++)
{
conditionalRowNumber = rx;
Conditional* curConditional = _conditionalManager->getBySystemName(_curLogix->getConditionalByNumberOrder(rx));
variableList = curConditional->getCopyOfStateVariables();
_logixSysName = curConditional->getSystemName();
actionList = curConditional->getCopyOfActions();
showCondName = curConditional->getUserName();
if (showCondName.isNull()) {
showCondName = "";
}
showSystemName = curConditional->getSystemName();
// If no user name for a conditional, create one using C + row number
if (showCondName == ("")) {
showCondName = "C" + QString::number(rx + 1);
}
condText->append("\n " + showSystemName + " " + showCondName + " \n");
if (curConditional->getLogicType() == Conditional::MIXED) {
_antecedent = curConditional->getAntecedentExpression();
condText->append(" " + tr("Antecedent:") + " " + _antecedent + " \n"); // NOI18N
}
for (int i = 0; i < variableList->size(); i++) {
variable = variableList->at(i);
QString varTrigger = (variable->doTriggerActions())
? "[x]" // NOI18N
: "[ ]";
tStr = " " + varTrigger + " ";
tStr = tStr + " R" + QString::number(i + 1) + (i > 8 ? " " : " "); // Makes {Rx}bb or {Rxx}b
condText->append(tStr);
operand = variable->getOpernString();
if (i == 0) { // add the IF to the first conditional
condText->append(tr("IF") + " " + operand + " "); // NOI18N
} else {
condText->append(" " + operand + " ");
}
if (variable->isNegated()) {
condText->append(tr("NOT") + " "); // NOI18N
}
condText->append(variable->toString() + " \n");
} // for _variableList
if (actionList->size() > 0) {
condText->append(" " + tr("THEN") + " \n"); // NOI18N
bool triggerType = curConditional->getTriggerOnChange();
for (int i = 0; i < actionList->size(); i++) {
action = actionList->value(i);
condName = action->description(triggerType);
condText->append(" " + condName + " \n");
} // for _actionList
} else {
condText->append(" " + tr("<no action defined>") + " \n\n"); // NOI18N
}
} // for numConditionals
//condText->setCaretPosition(0);
condText->setTabStopWidth(4);
condText->setEditable(false);
return condText;
} // buildConditionalListing
| [
"[email protected]"
] | |
8b7847ada8d98f26f1e0bb87b303631ce648e134 | e8fa0f503156ffc93d79ce3ed615dfedd742b451 | /2_22.cpp | f5e62e7819de20ddd67ce51c2280f396366a403a | [] | no_license | AlexandrViktorovich/PNRPU_tasks | 22ac7cfbb13d07b8ceab1ea250d7a19354b7923b | 3fa08e1508624da1c37c56f54ce288ee94f8ca15 | refs/heads/master | 2023-03-10T04:12:12.593309 | 2021-02-19T08:05:17 | 2021-02-19T08:05:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 409 | cpp | #include <iostream>
#include <cmath>
using namespace std;
float n;
int number;
float maxi = INT_MIN;
int main()
{
cout << "Enter: ";
cout << endl;
cout << endl;
cin >> n;
cout << endl;
for (int i=1; i<=n; i++)
{
if ((sin(n+i/n)) >= maxi)
{
maxi = sin(n+i/n);
number = i;
}
}
cout << number << " " << maxi;
return 0;
} | [
"[email protected]"
] | |
43753f26ceb7d92fed456e6b524796363c9086f5 | fc8a911e4cba4ec8779ee728415bcaa5b52cc1a6 | /experimental/Pomdog.Experimental/Skeletal2D/SkeletonTransform.hpp | c8a36f73db69c36851c6c343f3b2891a7753e24a | [
"MIT"
] | permissive | CheezBoiger/pomdog | c8c900896dd9d3f778c2f5c7793de2eb65d8b892 | ced80378466716c38d2967c566adf754ae21f8d6 | refs/heads/master | 2021-01-21T10:45:59.474919 | 2017-02-23T05:21:33 | 2017-02-23T05:21:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | hpp | // Copyright (c) 2013-2017 mogemimi. Distributed under the MIT license.
#pragma once
#include "SkeletonPose.hpp"
#include "Pomdog/Math/Matrix3x2.hpp"
#include <vector>
namespace Pomdog {
class SkeletonTransform {
public:
SkeletonPose Pose;
std::vector<Matrix3x2> GlobalPose;
};
} // namespace Pomdog
| [
"[email protected]"
] | |
433dd7781320408ec31ee63ac57c00c494723051 | cb1c73e398f89a990d07b7dc7a624e1652ee33ea | /graph/minimum_spanning_tree_prim.cpp | 71f2f7651218c78d90b7a1ce166b8151b412079a | [] | no_license | TheBestTvarynka/DataStructure | 18bbc8d0e8efa10f835cc9d5be16edb0d1b3b814 | cf6bbaeaa15d0a0c924e9b8898127545be98d9d0 | refs/heads/master | 2020-04-02T00:57:10.005257 | 2019-06-01T20:02:32 | 2019-06-01T20:02:32 | 153,829,608 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,267 | cpp | // вважаємо що граф не орієнтований. задається списками сміжнисті.
// дана реалізація більш оптимальна для розріджених графів.
#include <iostream>
#include <list>
#include <iterator>
#include <fstream>
#include <vector>
using namespace std;
struct Node
{ int to, weight; };
struct edge
{ int from, to, weight; };
class Graph
{
private:
vector<Node> *graph;
int Size;
/////////////////
vector<edge> queue;
vector<Node> *mst; // final minimal spanning tree
bool *used;
public:
Graph(); // constructor build the graph form file
~Graph(); // destructor free memory
void MST_Prim(); // MST - minimal spanning tree
void Insert_queue(edge );
void Insert_mst(edge );
void Print(vector<Node > *);
};
int main()
{
Graph A;
A.MST_Prim();
A.~Graph();
return 0;
}
void Graph::MST_Prim()
{
// починаємо будувати дерево із першого попавшго ребра
// по-ідеї нам все одно із якого починати, тому беремо перше ребро із графа
edge Buff;
Buff.from = 0;
Buff.to = graph[0][0].to;
Buff.weight = graph[0][0].weight;
queue.insert(queue.begin(), Buff);
for (int j = 1; j < graph[0].size(); j++)
{
Buff.to = graph[0][j].to;
Buff.weight = graph[0][j].weight;
Insert_queue(Buff);
}
used[0] = true;
while (queue.size() != 0)
{
while (used[queue[0].to] && queue.size() >= 1)
queue.erase(queue.begin());
if (queue.size() == 0)
{
Print(mst);
return;
}
Insert_mst(queue[0]); // add minimal edge in mst
Buff.from = queue[0].to;
used[queue[0].to] = true; // mart as used
queue.erase(queue.begin()); // delete current (first) edge becouse it in tree
for (int i = 0; i < graph[Buff.from].size(); i++)
{
Buff.to = graph[Buff.from][i].to;
Buff.weight = graph[Buff.from][i].weight;
Insert_queue(Buff);
}
}
}
void Graph::Insert_queue(edge e)
{
if (used[e.to])
return;
int count = 0, size = queue.size();
while (e.weight > queue[count].weight && count < size)
count++;
queue.insert(queue.begin() + count, e);
}
void Graph::Insert_mst(edge e)
{
Node Buff;
Buff.to = e.to;
Buff.weight = e.weight;
mst[e.from].push_back(Buff);
}
void Graph::Print(vector<Node > *St)
{
cout << "-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl;
for (int i = 0; i < Size; i++)
{
cout << i + 1 << " -> ";
for (int v = 0; v < St[i].size(); v++)
cout << "(" << St[i][v].to + 1 << ", " << St[i][v].weight << ") ";
cout << endl;
}
cout << "-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl;
}
Graph::Graph(void)
{
ifstream Input;
int start, end, weight;
Node Buff;
Input.open("List_Input_A (copy)1.txt");
if (!Input.is_open())
{
cout << "Error: Can't find file." << endl;
return;
}
Input >> Size;
graph = new vector<Node >[Size];
mst = new vector<Node >[Size];
used = new bool[Size];
for (int i = 0; i < Size; i++)
used[i] = false;
Input >> start;
while (!Input.eof())
{
Input >> end >> weight;
Buff.to = --end;
Buff.weight = weight;
graph[--start].push_back(Buff);
Input >> start;
}
Input.close();
Print(graph);
}
Graph::~Graph(void)
{
delete [] used;
delete [] graph;
// delete [] mst;
} | [
"[email protected]"
] | |
bacff731cce8f411267f3e64a858facd02abc7b3 | 088d017b2a8e826ecc496032f9393652eed3e0a4 | /LeetCodeStudy/LeetCodeStudy/Q_139.h | 9394e3404323a99d9b7baca482ed05c67376e224 | [] | no_license | Skierhou/LeetCodeStudy | 55970a9fe8236720277ea1e26283aad3addf67f3 | 363513beede99d674f700ed546657a0bebb7b6ad | refs/heads/master | 2023-01-24T21:01:13.204071 | 2020-12-07T05:09:47 | 2020-12-07T05:09:47 | 298,458,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,475 | h | #pragma once
#include "IQuestion.h"
#include <string>
#include <vector>
using namespace std;
//给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
//
//说明:
//
//拆分时可以重复使用字典中的单词。
//你可以假设字典中没有重复的单词。
//示例 1:
//
//输入 : s = "leetcode", wordDict = ["leet", "code"]
//输出 : true
//解释 : 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
//示例 2:
//
//输入 : s = "applepenapple", wordDict = ["apple", "pen"]
//输出 : true
//解释 : 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
//注意你可以重复使用字典中的单词。
//示例 3:
//
//输入 : s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
//输出 : false
//
//来源:力扣(LeetCode)
//链接:https ://leetcode-cn.com/problems/word-break
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Q_139:public IQuestion
{
public:
void Execute() override;
//暴力递归求解,时间复杂度O(n^2)
//思路:每次循环字符串只找最前面列表里存在的子项
bool ans_01(string s, vector<string>& wordDict);
//动态规划求解:时间复杂度O(n^2)
//j<i的情况下,dp[i]=dp[j] && check(substr(j,i))
bool ans_02(string s, vector<string>& wordDict);
};
| [
"[email protected]"
] | |
7f31f693f69fd381f498847b4078fc1a648d3090 | f6d3073fd746a71cb00e8a0d5dc4f42732eca956 | /src/Memoria/Source/Memoria/Private/GameModeState.cpp | 085eda34d696d5cbd01c2dbc3b34a81a628054b5 | [] | no_license | ditan96/rc-memoria | 95f8643e3ac5c1c55a4e6a910932c8e3e39f48b3 | a8c540dab55df000d7d2465ad650cd8dafdbef5f | refs/heads/master | 2022-11-05T15:46:16.783600 | 2019-11-20T04:13:49 | 2019-11-20T04:13:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "GameModeState.h"
void AGameModeState::Init()
{
}
void AGameModeState::OnStateEnter(AGameControllerBase* GameMode)
{
this->GameModeBase = GameMode;
ReceiveOnStateEnter(GameMode);
}
void AGameModeState::OnStateStart(AGameControllerBase* GameMode)
{
ReceiveOnStateStart(GameMode);
}
void AGameModeState::OnStateTick(AGameControllerBase* GameMode, float DeltaTime)
{
ReceiveOnStateTick(GameMode, DeltaTime);
}
void AGameModeState::OnStateStop(AGameControllerBase* GameMode)
{
ReceiveOnStateStop(GameMode);
}
void AGameModeState::OnStateExit(AGameControllerBase* GameMode)
{
ReceiveOnStateExit(GameMode);
}
| [
"[email protected]"
] | |
a99f2386e29038542b0daee4cb0e41d8551fa4b1 | cf49721a548f4bb668283e7e6cfc814e1eab459e | /backend/Server/WebSocket/FrameReader.cpp | 8f310f3b869e84d3041fc804e5e898e4a74ffe36 | [] | no_license | Weaders/LogServer | 40dc735e171cdd1421c54e9f7af4c5c1cca40f20 | 3272deb182af7e31bb61b7195bddd51e49eb8a8b | refs/heads/master | 2020-03-08T23:41:12.697882 | 2018-05-26T14:50:48 | 2018-05-26T14:50:48 | 128,470,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,195 | cpp | #include "FrameReader.h"
namespace Server {
namespace WebSocket {
FrameReader::FrameReader() {}
void FrameReader::clear() {
this->_frameData = Frame();
this->_bytesRead = 0;
}
void FrameReader::read(char byte) {
if (this->_bytesRead == 0) {
this->readFirstByte(byte);
} else if (this->_bytesRead == 1) {
this->readSecondByte(byte);
} else {
if (auto lengthBytes = this->needParseLength()) {
this->_frameData.extendedLength |= (byte << (lengthBytes - 1) * 8);
} else if (auto lengthMask = this->needParseMasking()) {
this->_frameData.maskingKey[4 - lengthMask] = byte;
} else {
if (this->_frameData.mask) {
auto maskingOctet = this->_frameData.payload.size() % 4;
this->_frameData.payload += byte ^ this->_frameData.maskingKey[maskingOctet];
} else {
this->_frameData.payload += byte;
}
}
}
this->_bytesRead++;
}
Frame FrameReader::getFrameData() {
return this->_frameData;
}
void FrameReader::readFirstByte(char byte) {
std::bitset<8> bits(byte);
this->_frameData.fin = bits[7];
this->_frameData.rsv1 = bits[6];
this->_frameData.rsv2 = bits[5];
this->_frameData.rsv3 = bits[4];
this->_frameData.opcode = bits[3] << 3 | bits[2] << 2 | bits[1] << 1 | bits[0];
}
void FrameReader::readSecondByte(char byte) {
std::bitset<8> bits(byte);
this->_frameData.mask = bits[7];
this->_frameData.baseLength = bits[6] << 6 | bits[5] << 5 | bits[4] << 4 | bits[3] << 3 | bits[2] << 2 | bits[1] << 1 | bits[0];
}
size_t FrameReader::needParseLength() {
if (this->_frameData.baseLength == 126 && this->_bytesRead < 4) {
return 4 - this->_bytesRead;
} else if (this->_frameData.baseLength == 127 && this->_bytesRead < 10) {
return 10 - this->_bytesRead;
}
return 0;
}
size_t FrameReader::needParseMasking() {
if (!this->_frameData.mask) {
return 0;
}
if (this->_frameData.baseLength < 126 && this->_bytesRead >= 2 && this->_bytesRead < 6) {
return 6 - this->_bytesRead;
}
if (this->_frameData.baseLength == 126 && this->_bytesRead >= 4 && this->_bytesRead < 8) {
return 8 - this->_bytesRead;
}
if (this->_frameData.baseLength == 127 && this->_bytesRead >= 10 && this->_bytesRead < 14) {
return 14 - this->_bytesRead;
}
return 0;
}
bool FrameReader::isEndRead() {
if (this->_bytesRead <= 2) {
return false;
}
if (this->_frameData.baseLength < 126 && this->_frameData.payload.size() == this->_frameData.baseLength) {
return true;
}
if (this->_frameData.baseLength > 125 && this->_frameData.payload.size() == this->_frameData.extendedLength) {
return true;
}
}
} // namespace WebSocket
} // namespace Server | [
"[email protected]"
] | |
26c09f30b0fdfee58a70b47d0524d7151981a46f | e6b96681b393ae335f2f7aa8db84acc65a3e6c8d | /atcoder.jp/arc026/arc026_3/Main.cpp | e09e005fe12f6a7fd8a9054368b67abdb4ab0948 | [] | no_license | okuraofvegetable/AtCoder | a2e92f5126d5593d01c2c4d471b1a2c08b5d3a0d | dd535c3c1139ce311503e69938611f1d7311046d | refs/heads/master | 2022-02-21T15:19:26.172528 | 2021-03-27T04:04:55 | 2021-03-27T04:04:55 | 249,614,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | cpp | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <complex>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <functional>
#include <iostream>
#include <map>
#include <set>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-9
#define INF 100000000000ll
#define sz(x) ((int)(x).size())
#define fi first
#define sec second
#define SORT(x) sort((x).begin(),(x).end())
#define all(x) (x).begin(),(x).end()
#define EQ(a,b) (abs((a)-(b))<EPS)
const int DAT_SIZE=(1<<20)-1;
struct RMQ//Range Minimum (or Maximum) Query
{
ll seg[DAT_SIZE];
int seed;// 0:Minimum 1:Maxmum
void init()
{
seed=0;
if(seed)memset(seg,0,sizeof(seg));
else for(int i=0;i<DAT_SIZE;i++)seg[i]=INF;
return;
}
ll comp(ll a,ll b)
{
if(seed)return max(a,b);
else return min(a,b);
}
void update(int k,ll x)
{
k+=DAT_SIZE/2;
//seg[k]=x;
seg[k]=comp(seg[k],x);
while(k>0)
{
k=(k-1)/2;
seg[k]=comp(seg[k*2+1],seg[k*2+2]);
}
return;
}
ll query(int a,int b,int k,int l,int r)
{
if(a>=r||b<=l)return seed?0:INF;
else if(a<=l&&r<=b)return seg[k];
else return comp(query(a,b,k*2+1,l,(l+r)/2),query(a,b,k*2+2,(l+r)/2,r));
}
ll query(int a,int b)
{
return query(a,b,0,0,(DAT_SIZE+1)/2);
}
};
int N,L;
struct lamp
{
int l,r,c;
lamp(int l,int r,int c):l(l),r(r),c(c){}
};
bool comp(lamp a,lamp b){return a.l<b.l;}
vector<lamp> vec;
RMQ seg;
int main()
{
scanf("%d %d",&N,&L);
for(int i=0;i<N;i++)
{
int l,r,c;
scanf("%d %d %d",&l,&r,&c);
lamp n(l,r,c);
vec.pb(n);
}
sort(vec.begin(),vec.end(),comp);
seg.init();
seg.update(0,0);
for(int i=0;i<vec.size();i++)
{
ll mi=seg.query(vec[i].l,vec[i].r+1);
seg.update(vec[i].r,mi+vec[i].c);
}
cout << seg.query(L,L+1) << endl;
return 0;
}
| [
"[email protected]"
] | |
88177e185791d2f691c97ac0b21d86debbbc8db8 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /components/password_manager/core/browser/sync_credentials_filter.h | b29c030a78ed2faf21b40f429b66680ba44c8215 | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 2,083 | h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_SYNC_CREDENTIALS_FILTER_H_
#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_SYNC_CREDENTIALS_FILTER_H_
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/macros.h"
#include "components/autofill/core/common/password_form.h"
#include "components/password_manager/core/browser/credentials_filter.h"
#include "components/password_manager/core/browser/password_manager_client.h"
#include "components/sync/driver/sync_service.h"
namespace password_manager {
// The sync- and GAIA- aware implementation of the filter.
class SyncCredentialsFilter : public CredentialsFilter {
public:
using SyncServiceFactoryFunction =
base::RepeatingCallback<const syncer::SyncService*(void)>;
// Implements protection of sync credentials. Uses |client| to get the last
// commited entry URL for a check against GAIA reauth site. Uses the factory
// function repeatedly to get the sync service to pass to sync_util methods.
SyncCredentialsFilter(
PasswordManagerClient* client,
SyncServiceFactoryFunction sync_service_factory_function);
~SyncCredentialsFilter() override;
// CredentialsFilter
bool ShouldSave(const autofill::PasswordForm& form) const override;
bool ShouldSaveGaiaPasswordHash(
const autofill::PasswordForm& form) const override;
bool ShouldSaveEnterprisePasswordHash(
const autofill::PasswordForm& form) const override;
void ReportFormLoginSuccess(
const PasswordFormManager& form_manager) const override;
bool IsSyncAccountEmail(const std::string& username) const override;
private:
PasswordManagerClient* const client_;
const SyncServiceFactoryFunction sync_service_factory_function_;
DISALLOW_COPY_AND_ASSIGN(SyncCredentialsFilter);
};
} // namespace password_manager
#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_SYNC_CREDENTIALS_FILTER_H_
| [
"[email protected]"
] | |
1e3f1ae7951a35df035a2cd1289c8fd11b9bb28f | e5dad8e72f6c89011ae030f8076ac25c365f0b5f | /caret_statistics/StatisticMeanAndDeviation.cxx | d37e7986f541462692d0ce9526cad3db005f87bf | [] | no_license | djsperka/caret | f9a99dc5b88c4ab25edf8b1aa557fe51588c2652 | 153f8e334e0cbe37d14f78c52c935c074b796370 | refs/heads/master | 2023-07-15T19:34:16.565767 | 2020-03-07T00:29:29 | 2020-03-07T00:29:29 | 122,994,146 | 0 | 1 | null | 2018-02-26T16:06:03 | 2018-02-26T16:06:03 | null | UTF-8 | C++ | false | false | 2,948 | cxx |
/*LICENSE_START*/
/*
* Copyright 1995-2002 Washington University School of Medicine
*
* http://brainmap.wustl.edu
*
* This file is part of CARET.
*
* CARET 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.
*
* CARET 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 CARET; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*LICENSE_END*/
#include <cmath>
#include "StatisticDataGroup.h"
#include "StatisticMeanAndDeviation.h"
/**
* constructor.
*/
StatisticMeanAndDeviation::StatisticMeanAndDeviation()
: StatisticAlgorithm("Mean and Deviation")
{
mean = 0.0;
populationSampleDeviation = 0.0;
populationSampleVariance = 0.0;
deviation = 0.0;
variance = 0.0;
sumOfSquares = 0.0;
}
/**
* destructor.
*/
StatisticMeanAndDeviation::~StatisticMeanAndDeviation()
{
}
/**
* generate the mean and deviation.
* Formulas are from:
* A Aron and E Aron
* Statistics for Psychology (2nd Edition)
* Upper Saddle River, NJ
* Prentice Hall
* 1999
*/
void
StatisticMeanAndDeviation::execute() throw (StatisticException)
{
mean = 0.0;
populationSampleDeviation = 0.0;
populationSampleVariance = 0.0;
deviation = 0.0;
variance = 0.0;
sumOfSquares = 0.0;
int totalNumberOfData = 0;
//
// Determine mean
//
double meanSum = 0.0;
for (int i = 0; i < getNumberOfDataGroups(); i++) {
const StatisticDataGroup* sdg = getDataGroup(i);
const float* data = sdg->getPointerToData();
const int numData = sdg->getNumberOfData();
for (int j = 0; j < numData; j++) {
meanSum += data[j];
totalNumberOfData++;
}
}
mean = meanSum / static_cast<float>(totalNumberOfData);
//
// Determine deviation
//
for (int i = 0; i < getNumberOfDataGroups(); i++) {
const StatisticDataGroup* sdg = getDataGroup(i);
const float* data = sdg->getPointerToData();
const int numData = sdg->getNumberOfData();
for (int j = 0; j < numData; j++) {
const double diff = data[j] - mean;
sumOfSquares += (diff * diff);
}
}
if (totalNumberOfData > 1) {
variance = sumOfSquares / static_cast<double>(totalNumberOfData);
deviation = std::sqrt(variance);
populationSampleVariance = sumOfSquares / static_cast<double>(totalNumberOfData - 1);
populationSampleDeviation = std::sqrt(populationSampleVariance);
}
}
| [
"[email protected]"
] | |
6f6ead3d6fbcfef1f01fce90a44a89681f336c37 | 464cd8249cd3b4e6b5901eabc23e2b87ba9e7fab | /After Life/build/Android/Preview/app/src/main/include/Fuse.Triggers.WhileString.h | a5001ec8a7c89212e25e6ecefd5fc3da686e0a39 | [] | no_license | martin-morales/After-Life | 25f95dd5e5b6069355358ff7c9bd5b1bc022ee7c | 932ff16a632048678343f887f4c2fc44a072b9eb | refs/heads/master | 2021-09-23T00:11:32.160761 | 2017-05-26T03:13:26 | 2017-05-26T03:13:26 | 91,754,404 | 0 | 0 | null | 2018-09-18T22:04:13 | 2017-05-19T01:53:31 | C++ | UTF-8 | C++ | false | false | 2,735 | h | // This file was generated based on '../../../Library/Application Support/Fusetools/Packages/Fuse.Triggers/1.0.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IBase-d3bd6f2e.h>
#include <Fuse.Animations.IUnwr-594abe9.h>
#include <Fuse.Binding.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.IPulseTrigger.h>
#include <Fuse.Triggers.WhileValue-1.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.String.h>
namespace g{namespace Fuse{namespace Triggers{struct WhileString;}}}
namespace g{
namespace Fuse{
namespace Triggers{
// public sealed class WhileString :4054
// {
::g::Fuse::Triggers::WhileValue_type* WhileString_typeof();
void WhileString__ctor_7_fn(WhileString* __this);
void WhileString__get_CaseSensitive_fn(WhileString* __this, bool* __retval);
void WhileString__set_CaseSensitive_fn(WhileString* __this, bool* value);
void WhileString__get_Compare_fn(WhileString* __this, uString** __retval);
void WhileString__set_Compare_fn(WhileString* __this, uString* value);
void WhileString__get_Contains_fn(WhileString* __this, uString** __retval);
void WhileString__set_Contains_fn(WhileString* __this, uString* value);
void WhileString__get_Equals_fn(WhileString* __this, uString** __retval);
void WhileString__set_Equals_fn(WhileString* __this, uString* value);
void WhileString__get_IsOn_fn(WhileString* __this, bool* __retval);
void WhileString__get_MaxLength_fn(WhileString* __this, int* __retval);
void WhileString__set_MaxLength_fn(WhileString* __this, int* value);
void WhileString__get_MinLength_fn(WhileString* __this, int* __retval);
void WhileString__set_MinLength_fn(WhileString* __this, int* value);
void WhileString__New2_fn(WhileString** __retval);
void WhileString__get_Test_fn(WhileString* __this, int* __retval);
void WhileString__set_Test_fn(WhileString* __this, int* value);
struct WhileString : ::g::Fuse::Triggers::WhileValue
{
bool _caseSensitive;
uStrong<uString*> _compare;
bool _hasMaxLength;
bool _hasMinLength;
int _maxLength;
int _minLength;
int _test;
void ctor_7();
bool CaseSensitive();
void CaseSensitive(bool value);
uString* Compare();
void Compare(uString* value);
uString* Contains1();
void Contains1(uString* value);
uString* Equals2();
void Equals2(uString* value);
int MaxLength();
void MaxLength(int value);
int MinLength();
void MinLength(int value);
int Test();
void Test(int value);
static WhileString* New2();
};
// }
}}} // ::g::Fuse::Triggers
| [
"[email protected]"
] | |
a61e933f05222ffd66d026dbeaf87b94fc213766 | 199d8b47095b2bd5b86f2425fa1e4ad6457232fd | /src/cc/tools/kfsfileenum_main.cc | cc71069a523227236e61ba6e958ccb93a210b134 | [
"Apache-2.0"
] | permissive | rapoth/kosmosfs | d8fd069dbcdaf17f209d39c020508d2130ea047d | ff3240ef4d4882fe4ebe3bd8d6293ee6d05da009 | refs/heads/master | 2020-12-24T14:01:05.770969 | 2011-12-16T18:48:55 | 2011-12-16T18:48:55 | 32,715,452 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,705 | cc | //---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2008/05/05
//
// Copyright 2008 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// \brief Debug utility to list out where the chunks of a file are.
//----------------------------------------------------------------------------
extern "C" {
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
};
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
#include "common/log.h"
#include "libkfsClient/KfsClient.h"
using namespace KFS;
KfsClientPtr gKfsClient;
int
main(int argc, char **argv)
{
bool help = false;
const char *server = NULL;
const char *filename = NULL;
int port = -1, retval;
char optchar;
bool verboseLogging = false;
KFS::MsgLogger::Init(NULL);
while ((optchar = getopt(argc, argv, "hs:p:f:v")) != -1) {
switch (optchar) {
case 's':
server = optarg;
break;
case 'p':
port = atoi(optarg);
break;
case 'f':
filename = optarg;
break;
case 'h':
help = true;
break;
case 'v':
verboseLogging = true;
break;
default:
KFS_LOG_VA_ERROR("Unrecognized flag %c", optchar);
help = true;
break;
}
}
if (help || (server == NULL) || (port < 0) || (filename == NULL)) {
cout << "Usage: " << argv[0] << " -s <server name> -p <port> -f <path> {-v}"
<< endl;
exit(-1);
}
gKfsClient = getKfsClientFactory()->GetClient(server, port);
if (!gKfsClient) {
cout << "kfs client failed to initialize...exiting" << endl;
exit(-1);
}
if (verboseLogging) {
KFS::MsgLogger::SetLevel(KFS::MsgLogger::kLogLevelDEBUG);
} else {
KFS::MsgLogger::SetLevel(KFS::MsgLogger::kLogLevelINFO);
}
retval = gKfsClient->EnumerateBlocks(filename);
exit(retval);
}
| [
"sriramsrao@8bf026d7-4dfc-6da9-1e29-2836fb35e766"
] | sriramsrao@8bf026d7-4dfc-6da9-1e29-2836fb35e766 |
eebe789fee5560cefbe2aabc798b91c17e075e85 | fafd13145410d343d3234abf35d70a5c8732a854 | /include/netcoworkserver.h | bb9ade33ea43b408c968599672a8819cada0b24a | [
"MIT"
] | permissive | DonRumata710/NetCowork | 518b7529c61b285254c7c8a3c81bcc635d01b600 | e9cff0eebff30a49e9e7b7ded29a145ffcca8f18 | refs/heads/master | 2023-06-09T19:26:13.670239 | 2023-06-07T07:21:41 | 2023-06-07T07:24:16 | 216,255,754 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | h | #ifndef NETCOWORKSERVER_H
#define NETCOWORKSERVER_H
#include "netcoworkprovider.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <set>
#include <memory>
class CreationFilter
{
public:
virtual bool allow(QTcpSocket* socket, uint32_t class_id) = 0;
};
class ClassFilter : public CreationFilter
{
public:
ClassFilter(std::set<uint32_t> _private_classes);
virtual bool allow(QTcpSocket* socket, uint32_t class_id) override;
private:
std::set<uint32_t> private_classes;
};
class NetCoworkServer : public QTcpServer, public NetCoworkProvider
{
Q_OBJECT
public:
NetCoworkServer();
virtual void start(const std::string& address, uint16_t port) override;
virtual void stop() override;
enum class CreationPolicy
{
SERVER_ONLY,
CUSTOM,
ALL
};
void set_creation_policy(CreationPolicy new_policy);
bool set_filter(std::unique_ptr<CreationFilter>);
public slots:
void onNewConnection();
void onDataReady();
protected:
virtual void send_data(Message& data) override;
virtual void send_data(Message&& msg) override;
virtual void respond(Message& msg) override;
virtual void respond(Message&& msg) override;
virtual bool is_server() override;
virtual bool creation_filter(uint32_t class_id) override;
private:
void send_data(const QByteArray& data);
void respond(const QByteArray& data);
private:
std::vector<QTcpSocket*> sockets;
CreationPolicy policy = CreationPolicy::SERVER_ONLY;
std::unique_ptr<CreationFilter> filter;
};
#endif // NETCOWORKSERVER_H
| [
"[email protected]"
] | |
8e6c0d2f4367481da58de99c6b586219689ca21b | 8436240e4b848e3256a1da5b3b95cba843dde3e7 | /Source/CommonUtilities/CommonUtilities/Input/Gamepad.h | 8782e5a6ff022d83d81e04d57baff85e22b09a70 | [] | no_license | jjenber/Network---Specialisation | 77ffcacb30854530e7493d4cdd5add618a479908 | 390df7fac6925e009b36888ce64555b2bb1f16c8 | refs/heads/main | 2023-04-05T22:04:04.419724 | 2021-04-11T07:35:42 | 2021-04-11T07:35:42 | 345,939,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,923 | h | #pragma once
#include <functional>
#include "../Timer/Timer.h"
#include "../Math/Vector2.h"
#include "../Math/Math.hpp"
namespace CommonUtilities
{
constexpr int MAX_NUM_GAMEPADS = 4;
constexpr float DEADZONE_STICK_L = 0.2f;
constexpr float DEADZONE_STICK_R = 0.25f;
enum class Button
{
DPad_Up = 0x0001,
DPad_Down = 0x0002,
DPad_Left = 0x0004,
DPad_Right = 0x0008,
Start = 0x0010,
Back = 0x0020,
LeftStick = 0x0040,
RightStick = 0x0080,
LeftShoulder = 0x0100,
RightShoulder = 0x0200,
A = 0x1000,
B = 0x2000,
X = 0x4000,
Y = 0x8000,
};
enum class Axis
{
LeftStick,
RightStick,
LeftTrigger,
RightTrigger,
};
struct GamepadState
{
Vector2f myLeftStick;
Vector2f myRightStick;
float myLeftTrigger = 0.f;
float myRightTrigger = 0.f;
unsigned short myButtons = 0;
};
class Gamepad
{
friend class InputHandler;
public:
Gamepad();
~Gamepad();
Gamepad(const Gamepad& copy) = delete;
Gamepad(Gamepad&& copy) = delete;
Gamepad& operator=(const Gamepad& copy) = delete;
Gamepad& operator=(Gamepad&& copy) = delete;
bool IsConnected() const;
int GetID() const;
/// Returns true while the user holds down the button.
bool GetButton(Button aButton) const;
/// Returns true during the frame the user starts pressing down the button.
bool GetButtonDown(Button aButton) const;
/// Returns true during the frame the user release the button.
bool GetButtonUp(Button aButton) const;
// Returns the left analog stick with a value between [-1, 1].
const Vector2f& GetStickL() const { return myState.myLeftStick; };
// Returns the right analog stick with a value between [-1, 1].
const Vector2f& GetStickR() const { return myState.myRightStick; };
// Returns the left trigger value between [0, 1].
const float GetTriggerL() const { return myState.myLeftTrigger; };
// Returns the right trigger value between [0, 1].
const float GetTriggerR() const { return myState.myRightTrigger; };
/// Returns the time in seconds since the controller sent or recieved input.
float GetTimeSinceLastStateChange() const;
/// Immediately stop vibration if it is currently on. Otherwise nothing happens.
void StopVibration();
/// Vibrate both motors with an intensity range between [0 - 1]. Stops automatically after time is up. To stop immediately call StopVibration().
void Vibrate(float aIntensity, float aTimeInSeconds);
private:
void Init(const int aUserID);
void ClearState();
/// Call once per update to set the current state as well as store the previous state.
/// Returns true if connected.
bool UpdateState();
std::function<void()> myVibrationUpdate;
GamepadState myState;
GamepadState myPreviousState;
Timer myLastStateChangeTimer;
unsigned long myPacketNumber;
int myID;
bool myIsConnected;
};
}
| [
"[email protected]"
] | |
e938a6f54ba7df7699632f3b48e2f46a2596289d | 612cdc3f9294363e724cd9a76ab5354a10ad3f19 | /Lab 1/Arduino Code/test/test.ino | b3af7e9f87984cea3bbfb5847f9f87ae531af7dc | [] | no_license | velocizachtor/IEEE-Advanced-Project | 44e29235f362f126769ff828af61ce6ac4ff516f | d4262eb6e629dd2c01fb42957edae59f5e8aeee2 | refs/heads/master | 2021-07-22T19:48:05.923362 | 2017-11-02T23:10:50 | 2017-11-02T23:10:50 | 109,328,092 | 0 | 0 | null | 2017-11-02T23:08:05 | 2017-11-02T23:08:04 | null | UTF-8 | C++ | false | false | 494 | ino | void setup() {
// put your setup code here, to run once:
RF24::RF24(9,10) radio;
radio.begin();
radio.setChannel(16);
radio.setPALevel(RF24_PA_MIN);
radio.openReadingPipe(1, 0xc2c2c2c2);
radio.openWritingPipe(0xe7e7e7e7e7);
radio.setCRCLength(RF24_CRC_16);
}
void loop() {
// put your main code here, to run repeatedly:
radio.startListening();
int data[31];
if (radio.available()) {
data = radio.read(&data,sizeof(data));
}
radio.stopListening();
}
}
| [
"[email protected]"
] | |
5ded1e63b853d9995b285e444e8ba5ddb4af48de | 111276eae86edbcdd0f61dd8f6fc19cfa394aa8e | /Lexer/token.cpp | 625c99c2ab15b978d87345876182f9d703680697 | [] | no_license | JasmineJans/Lexer-for-OPL | d1c87ff30a67251fc15c9573f1259e604fe740ca | 1ea8950d47564c7899059f31b9c4b9f79209dfae | refs/heads/master | 2021-01-23T08:14:47.364519 | 2017-03-28T17:32:37 | 2017-03-28T17:32:37 | 86,486,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | cpp | //
// token.cpp
// Lexer
//
// Created by Jasmine Jans on 4/10/16.
// Copyright © 2016 Jasmine Jans. All rights reserved.
//
#include <string>
#include "token.h"
Token::Token() : type(TokenType::EOS), lexeme(""), line(0), column(0)
{
}
Token::Token(TokenType type, std::string lexeme, int line, int column) :
type(type), lexeme(lexeme), line(line), column(column)
{
}
std::string Token::get_lexeme() const
{
return lexeme;
}
TokenType Token::get_type() const
{
return type;
}
int Token::get_line() const
{
return line;
}
int Token::get_column() const
{
return column;
}
| [
"[email protected]"
] | |
e23efddc175b41b24f5be953f70e3f3bf75f56ce | 2b631cb14b185044e4201c9cc8be8219c5ab7556 | /ml/nn/runtime/test/generated/examples/unidirectional_sequence_lstm_batch_major_peephole_projection_bias.example.cpp | 73805856891ee13ecaad9ea4b57ac49e0dd13468 | [
"Apache-2.0"
] | permissive | yuchuangu85/Android-framework-code | 59837ba3e41ebdda7de74ce82e1af2d0367610ce | fb27715328b4b0064b0f4e7b499b8c0f2e728d61 | refs/heads/master | 2020-09-03T09:00:20.642461 | 2019-11-04T16:21:25 | 2019-11-04T16:21:25 | 219,429,555 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 69,617 | cpp | // clang-format off
// Generated file (from: unidirectional_sequence_lstm_batch_major_peephole_projection_bias.mod.py). Do not edit
std::vector<MixedTypedExample>& get_examples() {
static std::vector<MixedTypedExample> examples = {
// Begin of an example
{
.operands = {
//Input(s)
{ // See tools/test_generator/include/TestHarness.h:MixedTyped
// int -> Dimensions map
.operandDimensions = {{0, {2, 4, 5}}, {1, {20, 5}}, {2, {20, 5}}, {3, {20, 5}}, {4, {20, 5}}, {5, {20, 16}}, {6, {20, 16}}, {7, {20, 16}}, {8, {20, 16}}, {9, {20}}, {10, {20}}, {11, {20}}, {12, {20}}, {13, {20}}, {14, {20}}, {15, {20}}, {16, {16, 20}}, {17, {16}}, {18, {2, 16}}, {19, {2, 20}}, {20, {0}}, {21, {0}}, {22, {0}}, {23, {0}}},
// int -> FLOAT32 map
.float32Operands = {{0, {0.787926f, 0.151646f, 0.071352f, 0.118426f, 0.458058f, 0.596268f, 0.998386f, 0.568695f, 0.864524f, 0.571277f, 0.073204f, 0.296072f, 0.743333f, 0.069199f, 0.045348f, 0.867394f, 0.291279f, 0.013714f, 0.482521f, 0.626339f, 0.295743f, 0.544053f, 0.690064f, 0.858138f, 0.497181f, 0.642421f, 0.52426f, 0.134799f, 0.003639f, 0.162482f, 0.640394f, 0.930399f, 0.050782f, 0.432485f, 0.988078f, 0.082922f, 0.563329f, 0.865614f, 0.333232f, 0.259916f}}, {1, {0.021393683f, 0.06124551f, 0.046905167f, -0.014657677f, -0.03149463f, 0.09171803f, 0.14647801f, 0.10797193f, -0.0057968358f, 0.0019193048f, -0.2726754f, 0.10154029f, -0.018539885f, 0.080349885f, -0.10262385f, -0.022599787f, -0.09121155f, -0.008675967f, -0.045206103f, -0.0821282f, -0.008045952f, 0.015478081f, 0.055217247f, 0.038719587f, 0.044153627f, -0.06453243f, 0.05031825f, -0.046935108f, -0.008164439f, 0.014574226f, -0.1671009f, -0.15519552f, -0.16819797f, -0.13971269f, -0.11953059f, 0.25005487f, -0.22790983f, 0.009855087f, -0.028140958f, -0.11200698f, 0.11295408f, -0.0035217577f, 0.054485075f, 0.05184695f, 0.064711206f, 0.10989193f, 0.11674786f, 0.03490607f, 0.07727357f, 0.11390585f, -0.1863375f, -0.1034451f, -0.13945189f, -0.049401227f, -0.18767063f, 0.042483903f, 0.14233552f, 0.13832581f, 0.18350165f, 0.14545603f, -0.028545704f, 0.024939531f, 0.050929718f, 0.0076203286f, -0.0029723682f, -0.042484224f, -0.11827596f, -0.09171104f, -0.10808628f, -0.16327988f, -0.2273378f, -0.0993647f, -0.017155107f, 0.0023917493f, 0.049272764f, 0.0038534778f, 0.054764505f, 0.089753784f, 0.06947234f, 0.08014476f, -0.04544234f, -0.0497073f, -0.07135631f, -0.048929106f, -0.004042012f, -0.009284026f, 0.018042054f, 0.0036860977f, -0.07427302f, -0.11434604f, -0.018995456f, 0.031487543f, 0.012834908f, 0.019977754f, 0.044256654f, -0.39292613f, -0.18519334f, -0.11651281f, -0.06809892f, 0.011373677f}}, {2, {-0.0018401089f, -0.004852237f, 0.03698424f, 0.014181704f, 0.028273236f, -0.016726194f, -0.05249759f, -0.10204261f, 0.00861066f, -0.040979505f, -0.009899187f, 0.01923892f, -0.028177269f, -0.08535103f, -0.14585495f, 0.10662567f, -0.01909731f, -0.017883534f, -0.0047269356f, -0.045103323f, 0.0030784295f, 0.076784775f, 0.07463696f, 0.094531395f, 0.0814421f, -0.12257899f, -0.033945758f, -0.031303465f, 0.045630626f, 0.06843887f, -0.13492945f, -0.012480007f, -0.0811829f, -0.07224499f, -0.09628791f, 0.045100946f, 0.0012300825f, 0.013964662f, 0.099372394f, 0.02543059f, 0.06958324f, 0.034257296f, 0.0482646f, 0.06267997f, 0.052625068f, 0.12784666f, 0.07077897f, 0.025725935f, 0.04165009f, 0.07241905f, 0.018668644f, -0.037377294f, -0.06277783f, -0.08833636f, -0.040120605f, -0.011405586f, -0.007808335f, -0.010301386f, -0.005102167f, 0.027717464f, 0.05483423f, 0.11449111f, 0.11289652f, 0.10939839f, 0.13396506f, -0.08402166f, -0.01901462f, -0.044678304f, -0.07720565f, 0.014350063f, -0.11757958f, -0.0652038f, -0.08185733f, -0.076754324f, -0.092614375f, 0.10405491f, 0.052960336f, 0.035755895f, 0.035839386f, -0.012540553f, 0.036881298f, 0.02913376f, 0.03420159f, 0.05448447f, -0.054523353f, 0.02582715f, 0.02327355f, -0.011857179f, -0.0011980024f, -0.034641717f, -0.026125094f, -0.17582615f, -0.15923657f, -0.27486774f, -0.0006143371f, 0.0001771948f, -8.470171e-05f, 0.02651807f, 0.045790765f, 0.06956496f}}, {3, {-0.04580283f, -0.09549462f, -0.032418985f, -0.06454633f, -0.043528453f, 0.043018587f, -0.049152344f, -0.12418144f, -0.078985475f, -0.07596889f, 0.019484362f, -0.11434962f, -0.0074034138f, -0.06314844f, -0.092981495f, 0.0062155537f, -0.025034338f, -0.0028890965f, 0.048929527f, 0.06235075f, 0.10665918f, -0.032036792f, -0.08505916f, -0.10843358f, -0.13002433f, -0.036816437f, -0.02130134f, -0.016518239f, 0.0047691227f, -0.0025825808f, 0.066017866f, 0.029991534f, -0.10652836f, -0.1037554f, -0.13056071f, -0.03266643f, -0.033702414f, -0.006473424f, -0.04611692f, 0.014419339f, -0.025174323f, 0.0396852f, 0.081777506f, 0.06157468f, 0.10210095f, -0.009658194f, 0.046511717f, 0.03603906f, 0.0069369148f, 0.015960095f, -0.06507666f, 0.09551598f, 0.053568836f, 0.06408714f, 0.12835667f, -0.008714329f, -0.20211966f, -0.12093674f, 0.029450472f, 0.2849013f, -0.029227901f, 0.1164364f, -0.08560263f, 0.09941786f, -0.036999565f, -0.028842626f, -0.0033637602f, -0.017012902f, -0.09720865f, -0.11193351f, -0.029155117f, -0.017936034f, -0.009768936f, -0.04223324f, -0.036159635f, 0.06505112f, -0.021742892f, -0.023377212f, -0.07221364f, -0.06430552f, 0.05453865f, 0.091149814f, 0.06387331f, 0.007518393f, 0.055960953f, 0.069779344f, 0.046411168f, 0.10509911f, 0.07463894f, 0.0075130584f, 0.012850982f, 0.04555431f, 0.056955688f, 0.06555285f, 0.050801456f, -0.009862683f, 0.00826772f, -0.026555609f, -0.0073611983f, -0.0014897042f}}, {4, {-0.0998932f, -0.07201956f, -0.052803773f, -0.15629593f, -0.15001918f, -0.07650751f, 0.02359855f, -0.075155355f, -0.08037709f, -0.15093534f, 0.029517552f, -0.04751393f, 0.010350531f, -0.02664851f, -0.016839722f, -0.023121163f, 0.0077019283f, 0.012851257f, -0.05040649f, -0.0129761f, -0.021737747f, -0.038305793f, -0.06870586f, -0.01481247f, -0.001285394f, 0.10124236f, 0.083122835f, 0.053313006f, -0.062235646f, -0.075637154f, -0.027833903f, 0.029774971f, 0.1130802f, 0.09218906f, 0.09506135f, -0.086665764f, -0.037162706f, -0.038880914f, -0.035832845f, -0.014481564f, -0.09825003f, -0.12048569f, -0.097665586f, -0.05287633f, -0.0964047f, -0.11366429f, 0.035777505f, 0.13568819f, 0.052451383f, 0.050649304f, 0.05798951f, -0.021852335f, -0.099848844f, 0.014740475f, -0.078897946f, 0.04974699f, 0.014160473f, 0.06973932f, 0.04964942f, 0.033364646f, 0.08190124f, 0.025535367f, 0.050893165f, 0.048514254f, 0.06945813f, -0.078907564f, -0.06707616f, -0.11844508f, -0.09986688f, -0.07509403f, 0.06263226f, 0.14925587f, 0.20188436f, 0.12098451f, 0.14639415f, 0.0015017595f, -0.014267382f, -0.03417257f, 0.012711468f, 0.0028300495f, -0.024758482f, -0.05098548f, -0.0821182f, 0.014225672f, 0.021544158f, 0.08949725f, 0.07505268f, -0.0020780868f, 0.04908258f, 0.06476295f, -0.022907063f, 0.027562456f, 0.040185735f, 0.019567577f, -0.015598739f, -0.049097303f, -0.017121866f, -0.083368234f, -0.02332002f, -0.0840956f}}, {5, {-0.001374326f, -0.078856036f, 0.10672688f, 0.029162422f, -0.11585556f, 0.02557986f, -0.13446963f, -0.035785314f, -0.01244275f, 0.025961924f, -0.02337298f, -0.044228926f, -0.055839065f, -0.046598054f, -0.010546039f, -0.06900766f, 0.027239809f, 0.022582639f, -0.013296484f, -0.05459212f, 0.08981f, -0.045407712f, 0.08682226f, -0.06867011f, -0.14390695f, -0.02916037f, 0.000996957f, 0.091420636f, 0.14283475f, -0.07390571f, -0.06402044f, 0.062524505f, -0.093129106f, 0.04860203f, -0.08364217f, -0.08119002f, 0.009352075f, 0.22920375f, 0.0016303885f, 0.11583097f, -0.13732095f, 0.012405723f, -0.07551853f, 0.06343048f, 0.12162708f, -0.031923793f, -0.014335606f, 0.01790974f, -0.10650317f, -0.0724401f, 0.08554849f, -0.05727212f, 0.06556731f, -0.042729504f, -0.043227166f, 0.011683251f, -0.013082158f, -0.029302018f, -0.010899579f, -0.062036745f, -0.022509435f, -0.00964907f, -0.01567329f, 0.04260106f, -0.07787477f, -0.11576462f, 0.017356863f, 0.048673786f, -0.017577527f, -0.05527947f, -0.082487635f, -0.040137455f, -0.10820036f, -0.04666372f, 0.022746278f, -0.07851417f, 0.01068115f, 0.032956902f, 0.022433773f, 0.0026891115f, 0.08944216f, -0.0685835f, 0.010513544f, 0.07228705f, 0.02032331f, -0.059686817f, -0.0005566496f, -0.086984694f, 0.040414046f, -0.1380399f, 0.094208956f, -0.05722982f, 0.012092817f, -0.04989123f, -0.086576f, -0.003399834f, -0.04696032f, -0.045747425f, 0.10091314f, 0.048676282f, -0.029037097f, 0.031399418f, -0.0040285117f, 0.047237843f, 0.09504992f, 0.041799378f, -0.049185462f, -0.031518843f, -0.10516937f, 0.026374253f, 0.10058866f, -0.0033195973f, -0.041975245f, 0.0073591834f, 0.0033782164f, -0.004325073f, -0.10167381f, 0.042500053f, -0.01447153f, 0.06464186f, -0.017142897f, 0.03312627f, 0.009205989f, 0.024138335f, -0.011337001f, 0.035530265f, -0.010912711f, 0.0706555f, -0.005894094f, 0.051841937f, -0.1401738f, -0.02351249f, 0.0365468f, 0.07590991f, 0.08838724f, 0.021681072f, -0.10086113f, 0.019608743f, -0.06195883f, 0.077335775f, 0.023646897f, -0.095322326f, 0.02233014f, 0.09756986f, -0.048691444f, -0.009579111f, 0.07595467f, 0.11480546f, -0.09801813f, 0.019894179f, 0.08502348f, 0.004032281f, 0.037211012f, 0.068537936f, -0.048005626f, -0.091520436f, -0.028379958f, -0.01556313f, 0.06554592f, -0.045599163f, -0.01672207f, -0.020169014f, -0.011877351f, -0.20212261f, 0.010889619f, 0.0047078193f, 0.038385306f, 0.08540671f, -0.017140968f, -0.0035865551f, 0.016678626f, 0.005633034f, 0.015963363f, 0.00871737f, 0.060130805f, 0.028611384f, 0.10109069f, -0.015060172f, -0.07894427f, 0.06401885f, 0.011584063f, -0.024466386f, 0.0047652307f, -0.09041358f, 0.030737216f, -0.0046374933f, 0.14215417f, -0.11823516f, 0.019899689f, 0.006106124f, -0.027092824f, 0.0786356f, 0.05052217f, -0.058925f, -0.011402121f, -0.024987547f, -0.0013661642f, -0.06832946f, -0.015667673f, -0.1083353f, -0.00096863037f, -0.06988685f, -0.053350925f, -0.027275559f, -0.033664223f, -0.07978348f, -0.025200296f, -0.017207067f, -0.058403496f, -0.055697463f, 0.005798788f, 0.12965427f, -0.062582195f, 0.0013350133f, -0.10482091f, 0.0379771f, 0.072521195f, -0.0029455067f, -0.13797039f, -0.03628521f, 0.013806405f, -0.017858358f, -0.01008298f, -0.07700066f, -0.017081132f, 0.019358726f, 0.0027079724f, 0.004635139f, 0.062634714f, -0.02338735f, -0.039547626f, -0.02050681f, 0.03385117f, -0.083611414f, 0.002862572f, -0.09421313f, 0.058618143f, -0.08598433f, 0.00972939f, 0.023867095f, -0.053934585f, -0.023203006f, 0.07452513f, -0.048767887f, -0.07314807f, -0.056307215f, -0.10433547f, -0.06440842f, 0.04328182f, 0.04389765f, -0.020006588f, -0.09076438f, -0.11652589f, -0.021705797f, 0.03345259f, -0.010329105f, -0.025767034f, 0.013057034f, -0.07316461f, -0.10145612f, 0.06358255f, 0.18531723f, 0.07759293f, 0.12006465f, 0.1305557f, 0.058638252f, -0.03393652f, 0.09622831f, -0.16253184f, -2.4580743e-06f, 0.079869635f, -0.070196845f, -0.005644518f, 0.06857898f, -0.12598175f, -0.035084512f, 0.03156317f, -0.12794146f, -0.031963028f, 0.04692781f, 0.030070418f, 0.0071660685f, -0.095516115f, -0.004643372f, 0.040170413f, -0.062104587f, -0.0037324072f, 0.0554317f, 0.08184801f, -0.019164372f, 0.06791302f, 0.034257166f, -0.10307039f, 0.021943003f, 0.046745934f, 0.0790918f, -0.0265588f, -0.007824208f, 0.042546265f, -0.00977924f, -0.0002440307f, -0.017384544f, -0.017990116f, 0.12252321f, -0.014512694f, -0.08251313f, 0.08861942f, 0.13589665f, 0.026351685f, 0.012641483f, 0.07466548f, 0.044301085f, -0.045414884f, -0.051112458f, 0.03444247f, -0.08502782f, -0.04106223f, -0.028126027f, 0.028473156f, 0.10467447f}}, {6, {-0.057784554f, -0.026057621f, -0.068447545f, -0.022581743f, 0.14811787f, 0.10826372f, 0.09471067f, 0.03987225f, -0.0039523416f, 0.00030638507f, 0.053185795f, 0.10572994f, 0.08414449f, -0.022036452f, -0.00066928595f, -0.09203576f, 0.032950465f, -0.10985798f, -0.023809856f, 0.0021431844f, -0.02196096f, -0.00326074f, 0.00058621005f, -0.074678116f, -0.06193199f, 0.055729095f, 0.03736828f, 0.020123724f, 0.061878487f, -0.04729229f, 0.034919553f, -0.07585433f, -0.04421272f, -0.044019096f, 0.085488975f, 0.04058006f, -0.06890133f, -0.030951202f, -0.024628663f, -0.07672815f, 0.034293607f, 0.08556707f, -0.05293577f, -0.033561368f, -0.04899627f, 0.0241671f, 0.015736353f, -0.095442444f, -0.029564252f, 0.016493602f, -0.035026584f, 0.022337519f, -0.026871363f, 0.004780428f, 0.0077918363f, -0.03601621f, 0.016435321f, -0.03263031f, -0.09543275f, -0.047392778f, 0.013454138f, 0.028934088f, 0.01685226f, -0.086110644f, -0.046250615f, -0.01847454f, 0.047608484f, 0.07339695f, 0.034546845f, -0.04881143f, 0.009128804f, -0.08802852f, 0.03761666f, 0.008096139f, -0.014454086f, 0.014361001f, -0.023502491f, -0.0011840804f, -0.07607001f, 0.001856849f, -0.06509276f, -0.006021153f, -0.08570962f, -0.1451793f, 0.060212336f, 0.055259194f, 0.06974018f, 0.049454916f, -0.027794661f, -0.08077226f, -0.016179763f, 0.1169753f, 0.17213494f, -0.0056326236f, -0.053934924f, -0.0124349f, -0.11520337f, 0.05409887f, 0.088759385f, 0.0019655675f, 0.0042065294f, 0.03881498f, 0.019844765f, 0.041858196f, -0.05695512f, 0.047233116f, 0.038937137f, -0.06542224f, 0.014429736f, -0.09719407f, 0.13908425f, -0.05379757f, 0.012321099f, 0.082840554f, -0.029899208f, 0.044217527f, 0.059855383f, 0.07711018f, -0.045319796f, 0.0948846f, -0.011724666f, -0.0033288454f, -0.033542685f, -0.04764985f, -0.13873616f, 0.040668588f, 0.034832682f, -0.015319203f, -0.018715994f, 0.046002675f, 0.0599172f, -0.043107376f, 0.0294216f, -0.002314414f, -0.022424703f, 0.0030315618f, 0.0014641669f, 0.0029166266f, -0.11878115f, 0.013738511f, 0.12375372f, -0.0006038222f, 0.029104086f, 0.087442465f, 0.052958444f, 0.07558703f, 0.04817258f, 0.044462286f, -0.015213451f, -0.08783778f, -0.0561384f, -0.003008196f, 0.047060397f, -0.002058388f, 0.03429439f, -0.018839769f, 0.024734668f, 0.024614193f, -0.042046934f, 0.09597743f, -0.0043254104f, 0.04320769f, 0.0064070094f, -0.0019131786f, -0.02558259f, -0.022822596f, -0.023273505f, -0.02464396f, -0.10991725f, -0.006240552f, 0.0074488563f, 0.024044557f, 0.04383914f, -0.046476185f, 0.028658995f, 0.060410924f, 0.050786525f, 0.009452605f, -0.0073054377f, -0.024810238f, 0.0052906186f, 0.0066939713f, -0.0020913032f, 0.014515517f, 0.015898481f, 0.021362653f, -0.030262267f, 0.016587038f, -0.011442813f, 0.041154444f, -0.007631438f, -0.03423484f, -0.010977775f, 0.036152758f, 0.0066366293f, 0.11915515f, 0.02318443f, -0.041350313f, 0.021485701f, -0.10906167f, -0.028218046f, -0.00954771f, 0.020531068f, -0.11995105f, -0.03672871f, 0.024019798f, 0.014255957f, -0.05221243f, -0.00661567f, -0.04630967f, 0.033188973f, 0.10107534f, -0.014027541f, 0.030796422f, -0.10270911f, -0.035999842f, 0.15443139f, 0.07684145f, 0.036571592f, -0.035900835f, -0.0034699554f, 0.06209149f, 0.015920248f, -0.031122351f, -0.03858649f, 0.01849943f, 0.13872518f, 0.01503974f, 0.069941424f, -0.06948533f, -0.0088794185f, 0.061282158f, -0.047401894f, 0.03100163f, -0.041533746f, -0.10430945f, 0.044574402f, -0.01425562f, -0.024290353f, 0.034563623f, 0.05866852f, 0.023947537f, -0.09445152f, 0.035450947f, 0.02247216f, -0.0042998926f, 0.061146557f, -0.10250651f, 0.020881841f, -0.06747029f, 0.10062043f, -0.0023941975f, 0.03532124f, -0.016341697f, 0.09685456f, -0.016764693f, 0.051808182f, 0.05875331f, -0.04536488f, 0.001626336f, -0.028892258f, -0.01048663f, -0.009793449f, -0.017093895f, 0.010987891f, 0.02357273f, -0.00010856845f, 0.0099760275f, -0.001845119f, -0.03551521f, 0.0018358806f, 0.05763657f, -0.01769146f, 0.040995963f, 0.02235177f, -0.060430344f, 0.11475477f, -0.023854522f, 0.10071741f, 0.0686208f, -0.014250481f, 0.034261297f, 0.047418304f, 0.08562733f, -0.030519066f, 0.0060542435f, 0.014653856f, -0.038836084f, 0.04096551f, 0.032249358f, -0.08355519f, -0.026823482f, 0.056386515f, -0.010401743f, -0.028396193f, 0.08507674f, 0.014410365f, 0.020995233f, 0.17040324f, 0.11511526f, 0.02459721f, 0.0066619175f, 0.025853224f, -0.023133837f, -0.081302024f, 0.017264642f, -0.009585969f, 0.09491168f, -0.051313367f, 0.054532815f, -0.014298593f, 0.10657464f, 0.007076659f, 0.10964551f, 0.0409152f, 0.008275321f, -0.07283536f, 0.07937492f, 0.04192024f, -0.1075027f}}, {7, {-0.037322544f, 0.018592842f, 0.0056175636f, -0.06253426f, 0.055647098f, -0.05713207f, -0.05626563f, 0.005559383f, 0.03375411f, -0.025757805f, -0.088049285f, 0.06017052f, -0.06570978f, 0.007384076f, 0.035123326f, -0.07920549f, 0.053676967f, 0.044480428f, -0.07663568f, 0.0071805613f, 0.08089997f, 0.05143358f, 0.038261272f, 0.03339287f, -0.027673481f, 0.044746667f, 0.028349208f, 0.020090483f, -0.019443132f, -0.030755889f, -0.0040000007f, 0.04465846f, -0.021585021f, 0.0031670958f, 0.0053199246f, -0.056117613f, -0.10893326f, 0.076739706f, -0.08509834f, -0.027997585f, 0.037871376f, 0.01449768f, -0.09002357f, -0.06111149f, -0.046195522f, 0.0422062f, -0.005683705f, -0.1253618f, -0.012925729f, -0.04890792f, 0.06985068f, 0.037654128f, 0.03398274f, -0.004781977f, 0.007032333f, -0.031787455f, 0.010868644f, -0.031489216f, 0.09525667f, 0.013939797f, 0.0058680447f, 0.0167067f, 0.02668468f, -0.04797466f, -0.048885044f, -0.12722108f, 0.035304096f, 0.06554885f, 0.00972396f, -0.039238118f, -0.05159735f, -0.11329045f, 0.1613692f, -0.03750952f, 0.06529313f, -0.071974665f, -0.11769596f, 0.015524369f, -0.0013754242f, -0.12446318f, 0.02786344f, -0.014179351f, 0.005264273f, 0.14376344f, 0.015983658f, 0.03406988f, -0.06939408f, 0.040699873f, 0.02111075f, 0.09669095f, 0.041345075f, -0.08316494f, -0.07684199f, -0.045768797f, 0.032298047f, -0.041805092f, 0.0119405f, 0.0061010392f, 0.12652606f, 0.0064572375f, -0.024950314f, 0.11574242f, 0.04508852f, -0.04335324f, 0.06760663f, -0.027437469f, 0.07216407f, 0.06977076f, -0.05438599f, 0.034033038f, -0.028602652f, 0.05346137f, 0.043184172f, -0.037189785f, 0.10420091f, 0.00882477f, -0.054019816f, -0.074273005f, -0.030617684f, -0.0028467078f, 0.024302477f, -0.0038869337f, 0.005332455f, 0.0013399826f, 0.04361412f, -0.007001822f, 0.09631092f, -0.06702025f, -0.042049985f, -0.035070654f, -0.04103342f, -0.10273396f, 0.0544271f, 0.037184782f, -0.13150354f, -0.0058036847f, -0.008264958f, 0.042035464f, 0.05891794f, 0.029673764f, 0.0063542654f, 0.044788733f, 0.054816857f, 0.062257513f, -0.00093483756f, 0.048938446f, -0.004952862f, -0.007730018f, -0.04043371f, -0.017094059f, 0.07229206f, -0.023670016f, -0.052195564f, -0.025616996f, -0.01520939f, 0.045104615f, -0.007376126f, 0.003533447f, 0.006570588f, 0.056037236f, 0.12436656f, 0.051817212f, 0.028532185f, -0.08686856f, 0.11868599f, 0.07663395f, -0.07323171f, 0.03463402f, -0.050708205f, -0.04458982f, -0.11590894f, 0.021273347f, 0.1251325f, -0.15313013f, -0.12224372f, 0.17228661f, 0.023029093f, 0.086124025f, 0.006445803f, -0.03496501f, 0.028332196f, 0.04449512f, -0.042436164f, -0.026587414f, -0.006041347f, -0.09292539f, -0.05678812f, 0.03897832f, 0.09465633f, 0.008115513f, -0.02171956f, 0.08304309f, 0.071401566f, 0.019622514f, 0.032163795f, -0.004167056f, 0.02295182f, 0.030739572f, 0.056506045f, 0.004612461f, 0.06524936f, 0.059999723f, 0.046395954f, -0.0045512207f, -0.1335546f, -0.030136576f, 0.11584653f, -0.014678886f, 0.0020118146f, -0.09688814f, -0.0790206f, 0.039770417f, -0.0329582f, 0.07922767f, 0.029322514f, 0.026405897f, 0.04207835f, -0.07073373f, 0.063781224f, 0.0859677f, -0.10925287f, -0.07011058f, 0.048005477f, 0.03438226f, -0.09606514f, -0.006669445f, -0.043381985f, 0.04240257f, -0.06955775f, -0.06769346f, 0.043903265f, -0.026784198f, -0.017840602f, 0.024307009f, -0.040079936f, -0.019946516f, 0.045318738f, -0.12233574f, 0.026170589f, 0.0074471775f, 0.15978073f, 0.10185836f, 0.10298046f, -0.015476589f, -0.039390966f, -0.072174534f, 0.0739445f, -0.1211869f, -0.0347889f, -0.07943156f, 0.014809798f, -0.12412325f, -0.0030663363f, 0.039695457f, 0.0647603f, -0.08291318f, -0.018529687f, -0.004423833f, 0.0037507233f, 0.084633216f, -0.01514876f, -0.056505352f, -0.012800942f, -0.06994386f, 0.012962922f, -0.031234352f, 0.07029052f, 0.016418684f, 0.03618972f, 0.055686004f, -0.08663945f, -0.017404709f, -0.054761406f, 0.029065743f, 0.052404847f, 0.020238016f, 0.0048197987f, -0.0214882f, 0.07078733f, 0.013016777f, 0.06262858f, 0.009184685f, 0.020785125f, -0.043904778f, -0.0270329f, -0.03299152f, -0.060088247f, -0.015162964f, -0.001828936f, 0.12642565f, -0.056757294f, 0.013586685f, 0.09232601f, -0.035886683f, 0.06000002f, 0.05229691f, -0.052580316f, -0.082029596f, -0.010794592f, 0.012947712f, -0.036429964f, -0.085508935f, -0.13127148f, -0.017744139f, 0.031502828f, 0.036232427f, -0.031581745f, 0.023051167f, -0.05325106f, -0.03421577f, 0.028793324f, -0.034633752f, -0.009881397f, -0.043551125f, -0.018609839f, 0.0019097115f, -0.008799762f, 0.056595087f, 0.0022273948f, 0.055752404f}}, {8, {0.025825322f, -0.05813119f, 0.09495884f, -0.045984812f, -0.01255415f, -0.0026479573f, -0.08196161f, -0.054914974f, -0.0046604523f, -0.029587349f, -0.044576716f, -0.07480124f, -0.082868785f, 0.023254942f, 0.027502948f, -0.0039728214f, -0.08683098f, -0.08116779f, -0.014675607f, -0.037924774f, -0.023314456f, -0.007401714f, -0.09255757f, 0.029460307f, -0.08829125f, -0.005139627f, -0.08989442f, -0.0555066f, 0.13596267f, -0.025062224f, -0.048351806f, -0.03850004f, 0.07266485f, -0.022414139f, 0.05940088f, 0.075114764f, 0.09597592f, -0.010211725f, -0.0049794707f, -0.011523867f, -0.025980417f, 0.072999895f, 0.11091378f, -0.081685916f, 0.014416728f, 0.043229222f, 0.034178585f, -0.07530371f, 0.035837382f, -0.085607f, -0.007721233f, -0.03287832f, -0.043848954f, -0.06404588f, -0.06632928f, -0.073643476f, 0.008214239f, -0.045984086f, 0.039764922f, 0.03474462f, 0.060612556f, -0.080590084f, 0.049127717f, 0.04151091f, -0.030063879f, 0.008801774f, -0.023021035f, -0.019558564f, 0.05158114f, -0.010947698f, -0.011825728f, 0.0075720972f, 0.0699727f, -0.0039981045f, 0.069350146f, 0.08799282f, 0.016156472f, 0.035502106f, 0.11695009f, 0.006217345f, 0.13392477f, -0.037875112f, 0.025745004f, 0.08940699f, -0.00924166f, 0.0046702605f, -0.036598757f, -0.08811812f, 0.10522024f, -0.032441203f, 0.008176899f, -0.04454919f, 0.07058152f, 0.0067963637f, 0.039206743f, 0.03259838f, 0.03725492f, -0.09515802f, 0.013326398f, -0.052055415f, -0.025676316f, 0.03198509f, -0.015951829f, -0.058556724f, 0.036879618f, 0.043357447f, 0.028362012f, -0.05908629f, 0.0059240665f, -0.04995891f, -0.019187413f, 0.0276265f, -0.01628143f, 0.0025863599f, 0.08800015f, 0.035250366f, -0.022165963f, -0.07328642f, -0.009415526f, -0.07455109f, 0.11690406f, 0.0363299f, 0.07411125f, 0.042103454f, -0.009660886f, 0.019076364f, 0.018299393f, -0.046004917f, 0.08891175f, 0.0431396f, -0.026327137f, -0.051502608f, 0.08979574f, -0.051670972f, 0.04940282f, -0.07491107f, -0.021240504f, 0.022596184f, -0.034280192f, 0.060163025f, -0.058211457f, -0.051837247f, -0.01349775f, -0.04639988f, -0.035936575f, -0.011681591f, 0.064818054f, 0.0073146066f, -0.021745546f, -0.043124277f, -0.06471268f, -0.07053354f, -0.029321948f, -0.05330136f, 0.016933719f, -0.053782392f, 0.13747959f, -0.1361751f, -0.11569455f, 0.0033329215f, 0.05693899f, -0.053219706f, 0.063698f, 0.07977434f, -0.07924483f, 0.06936997f, 0.0034815092f, -0.007305279f, -0.037325785f, -0.07251102f, -0.033633437f, -0.08677009f, 0.091591336f, -0.14165086f, 0.021752775f, 0.019683983f, 0.0011612234f, -0.058154266f, 0.049996935f, 0.0288841f, -0.0024567875f, -0.14345716f, 0.010955264f, -0.10234828f, 0.1183656f, -0.0010731248f, -0.023590032f, -0.072285876f, -0.0724771f, -0.026382286f, -0.0014920527f, 0.042667855f, 0.0018776858f, 0.02986552f, 0.009814309f, 0.0733756f, 0.12289186f, 0.018043943f, -0.0458958f, 0.049412545f, 0.033632483f, 0.05495232f, 0.036686596f, -0.013781798f, -0.010036754f, 0.02576849f, -0.08307328f, 0.010112348f, 0.042521734f, -0.05869831f, -0.071689695f, 0.03876447f, -0.13275425f, -0.0352966f, -0.023077697f, 0.10285965f, 0.084736146f, 0.15568255f, -0.00040734606f, 0.027835453f, -0.10292561f, -0.032401145f, 0.10053256f, -0.026142767f, -0.08271222f, -0.0030240538f, -0.016368777f, 0.1070414f, 0.042672627f, 0.013456989f, -0.0437609f, -0.022309763f, 0.11576483f, 0.04108048f, 0.061026827f, -0.0190714f, -0.0869359f, 0.037901703f, 0.0610107f, 0.07202949f, 0.01675338f, 0.086139716f, -0.08795751f, -0.014898893f, -0.023771819f, -0.01965048f, 0.007955471f, -0.043740474f, 0.03346837f, -0.10549954f, 0.090567775f, 0.042013682f, -0.03176985f, 0.12569028f, -0.02421228f, -0.029526481f, 0.023851605f, 0.031539805f, 0.05292009f, -0.02344001f, -0.07811758f, -0.08834428f, 0.10094801f, 0.16594367f, -0.06861939f, -0.021256343f, -0.041093912f, -0.06669611f, 0.035498552f, 0.021757556f, -0.09302526f, -0.015403468f, -0.06614931f, -0.051798206f, -0.013874718f, 0.03630673f, 0.010412845f, -0.08077351f, 0.046185967f, 0.0035662893f, 0.03541868f, -0.094149634f, -0.034814864f, 0.003128424f, -0.020674974f, -0.03944324f, -0.008110165f, -0.11113267f, 0.08484226f, 0.043586485f, 0.040582247f, 0.0968012f, -0.065249965f, -0.028036479f, 0.0050708856f, 0.0017462453f, 0.0326779f, 0.041296225f, 0.09164146f, -0.047743853f, -0.015952192f, -0.034451712f, 0.084197424f, -0.05347844f, -0.11768019f, 0.085926116f, -0.08251791f, -0.045081906f, 0.0948852f, 0.068401024f, 0.024856757f, 0.06978981f, -0.057309967f, -0.012775832f, -0.0032452994f, 0.01977615f, -0.041040014f, -0.024264973f, 0.063464895f, 0.05431621f}}, {9, {0.040369894f, 0.030746894f, 0.24704495f, 0.018586371f, -0.037586458f, -0.15312155f, -0.11812848f, -0.11465643f, 0.20259799f, 0.11418174f, -0.10116027f, -0.011334949f, 0.12411352f, -0.076769054f, -0.052169047f, 0.21198851f, -0.38871562f, -0.09061183f, -0.09683246f, -0.21929175f}}, {10, {-0.01998659f, -0.15568835f, -0.24248174f, -0.012770197f, 0.041331276f, -0.072311886f, -0.052123554f, -0.0066330447f, -0.043891653f, 0.036225766f, -0.047248036f, 0.021479502f, 0.033189066f, 0.11952997f, -0.020432774f, 0.64658105f, -0.06650122f, -0.03467612f, 0.095340036f, 0.23647355f}}, {11, {0.08286371f, -0.08261836f, -0.51210177f, 0.002913762f, 0.17764764f, -0.5495371f, -0.08460716f, -0.24552552f, 0.030037103f, 0.04123544f, -0.11940523f, 0.007358328f, 0.1890978f, 0.4833202f, -0.34441817f, 0.36312827f, -0.26375428f, 0.1457655f, -0.19724406f, 0.15548733f}}, {12, {0.02234832f, 0.14757581f, 0.18176508f, 0.10380666f, 0.053110216f, -0.06928846f, -0.13942584f, -0.11816189f, 0.19483899f, 0.03652339f, -0.10250295f, 0.036714908f, -0.18426876f, 0.036065217f, 0.21810818f, 0.02383196f, -0.043370757f, 0.08690144f, -0.04444982f, 0.00030581196f}}, {13, {0.035185695f, -0.042891346f, -0.03032477f, 0.23027696f, 0.11098921f, 0.15378423f, 0.09263801f, 0.09790885f, 0.09508917f, 0.061199076f, 0.07665568f, -0.015443159f, -0.03499149f, 0.046190713f, 0.08895977f, 0.10899629f, 0.40694186f, 0.06030037f, 0.012413437f, -0.06108739f}}, {14, {-0.024379363f, 0.0055531194f, 0.23377132f, 0.033463873f, -0.1483596f, -0.10639995f, -0.091433935f, 0.058573797f, -0.06809782f, -0.07889636f, -0.043246906f, -0.09829136f, -0.4279842f, 0.034901652f, 0.18797937f, 0.0075234566f, 0.016178843f, 0.1749513f, 0.13975595f, 0.92058027f}}, {15, {0.046159424f, -0.0012809046f, 0.03563469f, 0.12648113f, 0.027195795f, 0.35373217f, -0.018957434f, 0.008907322f, -0.0762701f, 0.12018895f, 0.04216877f, 0.0022856654f, 0.040952638f, 0.3147856f, 0.08225149f, -0.057416286f, -0.14995944f, -0.008040261f, 0.13208859f, 0.029760877f}}, {16, {-0.009802181f, 0.09401916f, 0.0717386f, -0.13895074f, 0.09641832f, 0.060420845f, 0.08539281f, 0.054285463f, 0.061395317f, 0.034448683f, -0.042991187f, 0.019801661f, -0.16840284f, -0.015726732f, -0.23041931f, -0.024478018f, -0.10959692f, -0.013875541f, 0.18600968f, -0.061274476f, 0.0138165f, -0.08160894f, -0.07661644f, 0.032372914f, 0.16169067f, 0.22465782f, -0.03993472f, -0.004017731f, 0.08633481f, -0.28869787f, 0.08682067f, 0.17240396f, 0.014975425f, 0.056431185f, 0.031037588f, 0.16702051f, 0.0077946745f, 0.15140012f, 0.29405436f, 0.120285f, -0.188994f, -0.027265169f, 0.043389652f, -0.022061434f, 0.014777949f, -0.20203483f, 0.094781205f, 0.19100232f, 0.13987629f, -0.036132768f, -0.06426278f, -0.05108664f, 0.13221376f, 0.009441198f, -0.16715929f, 0.15859416f, -0.040437475f, 0.050779544f, -0.022187516f, 0.012166504f, 0.027685808f, -0.07675938f, -0.0055694645f, -0.09444123f, 0.0046453946f, 0.050794356f, 0.10770313f, -0.20790008f, -0.07149004f, -0.11425117f, 0.008225835f, -0.035802525f, 0.14374903f, 0.15262283f, 0.048710253f, 0.1847461f, -0.007487823f, 0.11000021f, -0.09542012f, 0.22619456f, -0.029149994f, 0.08527916f, 0.009043713f, 0.0042746216f, 0.016261552f, 0.022461696f, 0.12689082f, -0.043589946f, -0.12035478f, -0.08361797f, -0.050666027f, -0.1248618f, -0.1275799f, -0.071875185f, 0.07377272f, 0.09944291f, -0.18897448f, -0.1593054f, -0.06526116f, -0.040107165f, -0.004618631f, -0.067624845f, -0.007576253f, 0.10727444f, 0.041546922f, -0.20424393f, 0.06907816f, 0.050412357f, 0.00724631f, 0.039827548f, 0.12449835f, 0.10747581f, 0.13708383f, 0.09134148f, -0.12617786f, -0.06428341f, 0.09956831f, 0.1208086f, -0.14676677f, -0.0727722f, 0.1126304f, 0.010139365f, 0.015571211f, -0.038128063f, 0.022913318f, -0.042050496f, 0.16842307f, -0.060597885f, 0.10531834f, -0.06411776f, -0.07451711f, -0.03410368f, -0.13393489f, 0.06534304f, 0.003620307f, 0.04490757f, 0.05970546f, 0.05197996f, 0.02839995f, 0.10434969f, -0.013699693f, -0.028353551f, -0.07260381f, 0.047201227f, -0.024575593f, -0.036445823f, 0.07155557f, 0.009672501f, -0.02328883f, 0.009533515f, -0.03606021f, -0.07421458f, -0.028082801f, -0.2678904f, -0.13221288f, 0.18419984f, -0.13012612f, -0.014588381f, -0.035059117f, -0.04824723f, 0.07830115f, -0.056184657f, 0.03277091f, 0.025466874f, 0.14494097f, -0.12522776f, -0.098633975f, -0.10766018f, -0.08317623f, 0.08594209f, 0.07749552f, 0.039474737f, 0.1776665f, -0.07409566f, -0.0477268f, 0.29323658f, 0.10801441f, 0.1154011f, 0.013952499f, 0.10739139f, 0.10708251f, -0.051456142f, 0.0074137426f, -0.10430189f, 0.10034707f, 0.045594677f, 0.0635285f, -0.0715442f, -0.089667566f, -0.10811871f, 0.00026344223f, 0.08298446f, -0.009525053f, 0.006585689f, -0.24567553f, -0.09450807f, 0.09648481f, 0.026996298f, -0.06419476f, -0.04752702f, -0.11063944f, -0.23441927f, -0.17608605f, -0.052156363f, 0.067035615f, 0.19271925f, -0.0032889997f, -0.043264326f, 0.09663576f, -0.057112187f, -0.10100678f, 0.0628376f, 0.04447668f, 0.017961001f, -0.10094388f, -0.10190601f, 0.18335468f, 0.10494553f, -0.052095775f, -0.0026118709f, 0.10539724f, -0.04383912f, -0.042349473f, 0.08438151f, -0.1947263f, 0.02251204f, 0.11216432f, -0.10307853f, 0.17351969f, -0.039091777f, 0.08066188f, -0.00561982f, 0.12633002f, 0.11335965f, -0.0088127935f, -0.019777594f, 0.06864014f, -0.059751723f, 0.016233567f, -0.06894641f, -0.28651384f, -0.004228674f, 0.019708522f, -0.16305895f, -0.07468996f, -0.0855457f, 0.099339016f, -0.07580735f, -0.13775392f, 0.08434318f, 0.08330512f, -0.12131499f, 0.031935584f, 0.09180414f, -0.08876437f, -0.08049874f, 0.008753825f, 0.03498998f, 0.030215185f, 0.03907079f, 0.089751154f, 0.029194152f, -0.03337423f, -0.019092513f, 0.04331237f, 0.04299654f, -0.036394123f, -0.12915532f, 0.09793732f, 0.07512415f, -0.11319543f, -0.032502122f, 0.15661901f, 0.07671967f, -0.005491124f, -0.19379048f, -0.218606f, 0.21448623f, 0.017840758f, 0.1416943f, -0.07051762f, 0.19488361f, 0.02664691f, -0.18104725f, -0.09334311f, 0.15026465f, -0.15493552f, -0.057762887f, -0.11604192f, -0.262013f, -0.01391798f, 0.012185008f, 0.11156489f, -0.07483202f, 0.06693364f, -0.26151478f, 0.046425626f, 0.036540434f, -0.16435726f, 0.17338543f, -0.21401681f, -0.11385144f, -0.08283257f, -0.069031075f, 0.030635102f, 0.010969227f, 0.11109743f, 0.010919218f, 0.027526086f, 0.13519906f, 0.01891392f, -0.046839405f, -0.040167913f, 0.017953383f, -0.09700955f, 0.0061885654f, -0.07000971f, 0.026893595f, -0.038844477f, 0.14543656f}}, {17, {0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f}}, {18, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}}, {19, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}}, {20, {}}, {21, {}}, {22, {}}, {23, {}}},
// int -> INT32 map
.int32Operands = {},
// int -> QUANT8_ASYMM map
.quant8AsymmOperands = {},
// int -> QUANT16_SYMM map
.quant16SymmOperands = {},
// int -> FLOAT16 map
.float16Operands = {},
// int -> BOOL8 map
.bool8Operands = {},
// int -> QUANT8_SYMM_PER_CHANNEL map
.quant8ChannelOperands = {},
// int -> QUANT16_ASYMM map
.quant16AsymmOperands = {},
// int -> QUANT8_SYMM map
.quant8SymmOperands = {},
},
//Output(s)
{ // See tools/test_generator/include/TestHarness.h:MixedTyped
// int -> Dimensions map
.operandDimensions = {{0, {2, 4, 16}}},
// int -> FLOAT32 map
.float32Operands = {{0, {0.0960319489f, 0.229351997f, 0.297207743f, 0.415997744f, 0.491644233f, 0.578822136f, 0.728351235f, 0.788540304f, 0.909073055f, 0.975599587f, 1.08478093f, 1.17409372f, 1.30914319f, 1.4041512f, 1.51714694f, 1.61342025f, 0.0634541437f, 0.190279216f, 0.317923307f, 0.415168911f, 0.458113253f, 0.609743774f, 0.731511116f, 0.795806408f, 0.876155913f, 0.960330188f, 1.12396312f, 1.22149014f, 1.33917773f, 1.43213499f, 1.54139447f, 1.65451813f, 0.0485293195f, 0.160991609f, 0.337073475f, 0.428976893f, 0.459505379f, 0.617044866f, 0.743735075f, 0.790821671f, 0.85271728f, 0.946818829f, 1.12779701f, 1.23345077f, 1.35309088f, 1.44595909f, 1.56173062f, 1.67839324f, 0.0445971154f, 0.156434938f, 0.341761589f, 0.425259203f, 0.449760497f, 0.633765697f, 0.745093822f, 0.791106999f, 0.84820503f, 0.952787101f, 1.13438797f, 1.24063754f, 1.34668994f, 1.44879568f, 1.57038593f, 1.67956686f, 0.0861309841f, 0.228726774f, 0.296653062f, 0.40733397f, 0.47120741f, 0.581307411f, 0.719366193f, 0.788456261f, 0.904226124f, 0.965476751f, 1.10223258f, 1.19042683f, 1.32106233f, 1.41333091f, 1.51509535f, 1.62168002f, 0.0652779415f, 0.18218407f, 0.324066937f, 0.42611438f, 0.47292757f, 0.602282405f, 0.739310443f, 0.791508496f, 0.870626807f, 0.955534995f, 1.10976851f, 1.21598971f, 1.34197009f, 1.43256509f, 1.54804492f, 1.65581059f, 0.0492607877f, 0.169714347f, 0.332315415f, 0.419173867f, 0.44699502f, 0.630063772f, 0.737177074f, 0.792844594f, 0.858417571f, 0.956391335f, 1.13453305f, 1.23976779f, 1.34693861f, 1.4410423f, 1.55988359f, 1.67204297f, 0.0390465111f, 0.15099439f, 0.3439475f, 0.424439192f, 0.444207728f, 0.632501483f, 0.742233515f, 0.791400731f, 0.845713973f, 0.944575012f, 1.14116096f, 1.24791968f, 1.35954499f, 1.45086145f, 1.56633317f, 1.68943977f}}},
// int -> INT32 map
.int32Operands = {},
// int -> QUANT8_ASYMM map
.quant8AsymmOperands = {},
// int -> QUANT16_SYMM map
.quant16SymmOperands = {},
// int -> FLOAT16 map
.float16Operands = {},
// int -> BOOL8 map
.bool8Operands = {},
// int -> QUANT8_SYMM_PER_CHANNEL map
.quant8ChannelOperands = {},
// int -> QUANT16_ASYMM map
.quant16AsymmOperands = {},
// int -> QUANT8_SYMM map
.quant8SymmOperands = {},
}
},
}, // End of an example
};
return examples;
};
std::vector<MixedTypedExample>& get_examples_dynamic_output_shape() {
static std::vector<MixedTypedExample> examples_dynamic_output_shape = {
// Begin of an example
{
.operands = {
//Input(s)
{ // See tools/test_generator/include/TestHarness.h:MixedTyped
// int -> Dimensions map
.operandDimensions = {{0, {2, 4, 5}}, {1, {20, 5}}, {2, {20, 5}}, {3, {20, 5}}, {4, {20, 5}}, {5, {20, 16}}, {6, {20, 16}}, {7, {20, 16}}, {8, {20, 16}}, {9, {20}}, {10, {20}}, {11, {20}}, {12, {20}}, {13, {20}}, {14, {20}}, {15, {20}}, {16, {16, 20}}, {17, {16}}, {18, {2, 16}}, {19, {2, 20}}, {20, {0}}, {21, {0}}, {22, {0}}, {23, {0}}},
// int -> FLOAT32 map
.float32Operands = {{0, {0.787926f, 0.151646f, 0.071352f, 0.118426f, 0.458058f, 0.596268f, 0.998386f, 0.568695f, 0.864524f, 0.571277f, 0.073204f, 0.296072f, 0.743333f, 0.069199f, 0.045348f, 0.867394f, 0.291279f, 0.013714f, 0.482521f, 0.626339f, 0.295743f, 0.544053f, 0.690064f, 0.858138f, 0.497181f, 0.642421f, 0.52426f, 0.134799f, 0.003639f, 0.162482f, 0.640394f, 0.930399f, 0.050782f, 0.432485f, 0.988078f, 0.082922f, 0.563329f, 0.865614f, 0.333232f, 0.259916f}}, {1, {0.021393683f, 0.06124551f, 0.046905167f, -0.014657677f, -0.03149463f, 0.09171803f, 0.14647801f, 0.10797193f, -0.0057968358f, 0.0019193048f, -0.2726754f, 0.10154029f, -0.018539885f, 0.080349885f, -0.10262385f, -0.022599787f, -0.09121155f, -0.008675967f, -0.045206103f, -0.0821282f, -0.008045952f, 0.015478081f, 0.055217247f, 0.038719587f, 0.044153627f, -0.06453243f, 0.05031825f, -0.046935108f, -0.008164439f, 0.014574226f, -0.1671009f, -0.15519552f, -0.16819797f, -0.13971269f, -0.11953059f, 0.25005487f, -0.22790983f, 0.009855087f, -0.028140958f, -0.11200698f, 0.11295408f, -0.0035217577f, 0.054485075f, 0.05184695f, 0.064711206f, 0.10989193f, 0.11674786f, 0.03490607f, 0.07727357f, 0.11390585f, -0.1863375f, -0.1034451f, -0.13945189f, -0.049401227f, -0.18767063f, 0.042483903f, 0.14233552f, 0.13832581f, 0.18350165f, 0.14545603f, -0.028545704f, 0.024939531f, 0.050929718f, 0.0076203286f, -0.0029723682f, -0.042484224f, -0.11827596f, -0.09171104f, -0.10808628f, -0.16327988f, -0.2273378f, -0.0993647f, -0.017155107f, 0.0023917493f, 0.049272764f, 0.0038534778f, 0.054764505f, 0.089753784f, 0.06947234f, 0.08014476f, -0.04544234f, -0.0497073f, -0.07135631f, -0.048929106f, -0.004042012f, -0.009284026f, 0.018042054f, 0.0036860977f, -0.07427302f, -0.11434604f, -0.018995456f, 0.031487543f, 0.012834908f, 0.019977754f, 0.044256654f, -0.39292613f, -0.18519334f, -0.11651281f, -0.06809892f, 0.011373677f}}, {2, {-0.0018401089f, -0.004852237f, 0.03698424f, 0.014181704f, 0.028273236f, -0.016726194f, -0.05249759f, -0.10204261f, 0.00861066f, -0.040979505f, -0.009899187f, 0.01923892f, -0.028177269f, -0.08535103f, -0.14585495f, 0.10662567f, -0.01909731f, -0.017883534f, -0.0047269356f, -0.045103323f, 0.0030784295f, 0.076784775f, 0.07463696f, 0.094531395f, 0.0814421f, -0.12257899f, -0.033945758f, -0.031303465f, 0.045630626f, 0.06843887f, -0.13492945f, -0.012480007f, -0.0811829f, -0.07224499f, -0.09628791f, 0.045100946f, 0.0012300825f, 0.013964662f, 0.099372394f, 0.02543059f, 0.06958324f, 0.034257296f, 0.0482646f, 0.06267997f, 0.052625068f, 0.12784666f, 0.07077897f, 0.025725935f, 0.04165009f, 0.07241905f, 0.018668644f, -0.037377294f, -0.06277783f, -0.08833636f, -0.040120605f, -0.011405586f, -0.007808335f, -0.010301386f, -0.005102167f, 0.027717464f, 0.05483423f, 0.11449111f, 0.11289652f, 0.10939839f, 0.13396506f, -0.08402166f, -0.01901462f, -0.044678304f, -0.07720565f, 0.014350063f, -0.11757958f, -0.0652038f, -0.08185733f, -0.076754324f, -0.092614375f, 0.10405491f, 0.052960336f, 0.035755895f, 0.035839386f, -0.012540553f, 0.036881298f, 0.02913376f, 0.03420159f, 0.05448447f, -0.054523353f, 0.02582715f, 0.02327355f, -0.011857179f, -0.0011980024f, -0.034641717f, -0.026125094f, -0.17582615f, -0.15923657f, -0.27486774f, -0.0006143371f, 0.0001771948f, -8.470171e-05f, 0.02651807f, 0.045790765f, 0.06956496f}}, {3, {-0.04580283f, -0.09549462f, -0.032418985f, -0.06454633f, -0.043528453f, 0.043018587f, -0.049152344f, -0.12418144f, -0.078985475f, -0.07596889f, 0.019484362f, -0.11434962f, -0.0074034138f, -0.06314844f, -0.092981495f, 0.0062155537f, -0.025034338f, -0.0028890965f, 0.048929527f, 0.06235075f, 0.10665918f, -0.032036792f, -0.08505916f, -0.10843358f, -0.13002433f, -0.036816437f, -0.02130134f, -0.016518239f, 0.0047691227f, -0.0025825808f, 0.066017866f, 0.029991534f, -0.10652836f, -0.1037554f, -0.13056071f, -0.03266643f, -0.033702414f, -0.006473424f, -0.04611692f, 0.014419339f, -0.025174323f, 0.0396852f, 0.081777506f, 0.06157468f, 0.10210095f, -0.009658194f, 0.046511717f, 0.03603906f, 0.0069369148f, 0.015960095f, -0.06507666f, 0.09551598f, 0.053568836f, 0.06408714f, 0.12835667f, -0.008714329f, -0.20211966f, -0.12093674f, 0.029450472f, 0.2849013f, -0.029227901f, 0.1164364f, -0.08560263f, 0.09941786f, -0.036999565f, -0.028842626f, -0.0033637602f, -0.017012902f, -0.09720865f, -0.11193351f, -0.029155117f, -0.017936034f, -0.009768936f, -0.04223324f, -0.036159635f, 0.06505112f, -0.021742892f, -0.023377212f, -0.07221364f, -0.06430552f, 0.05453865f, 0.091149814f, 0.06387331f, 0.007518393f, 0.055960953f, 0.069779344f, 0.046411168f, 0.10509911f, 0.07463894f, 0.0075130584f, 0.012850982f, 0.04555431f, 0.056955688f, 0.06555285f, 0.050801456f, -0.009862683f, 0.00826772f, -0.026555609f, -0.0073611983f, -0.0014897042f}}, {4, {-0.0998932f, -0.07201956f, -0.052803773f, -0.15629593f, -0.15001918f, -0.07650751f, 0.02359855f, -0.075155355f, -0.08037709f, -0.15093534f, 0.029517552f, -0.04751393f, 0.010350531f, -0.02664851f, -0.016839722f, -0.023121163f, 0.0077019283f, 0.012851257f, -0.05040649f, -0.0129761f, -0.021737747f, -0.038305793f, -0.06870586f, -0.01481247f, -0.001285394f, 0.10124236f, 0.083122835f, 0.053313006f, -0.062235646f, -0.075637154f, -0.027833903f, 0.029774971f, 0.1130802f, 0.09218906f, 0.09506135f, -0.086665764f, -0.037162706f, -0.038880914f, -0.035832845f, -0.014481564f, -0.09825003f, -0.12048569f, -0.097665586f, -0.05287633f, -0.0964047f, -0.11366429f, 0.035777505f, 0.13568819f, 0.052451383f, 0.050649304f, 0.05798951f, -0.021852335f, -0.099848844f, 0.014740475f, -0.078897946f, 0.04974699f, 0.014160473f, 0.06973932f, 0.04964942f, 0.033364646f, 0.08190124f, 0.025535367f, 0.050893165f, 0.048514254f, 0.06945813f, -0.078907564f, -0.06707616f, -0.11844508f, -0.09986688f, -0.07509403f, 0.06263226f, 0.14925587f, 0.20188436f, 0.12098451f, 0.14639415f, 0.0015017595f, -0.014267382f, -0.03417257f, 0.012711468f, 0.0028300495f, -0.024758482f, -0.05098548f, -0.0821182f, 0.014225672f, 0.021544158f, 0.08949725f, 0.07505268f, -0.0020780868f, 0.04908258f, 0.06476295f, -0.022907063f, 0.027562456f, 0.040185735f, 0.019567577f, -0.015598739f, -0.049097303f, -0.017121866f, -0.083368234f, -0.02332002f, -0.0840956f}}, {5, {-0.001374326f, -0.078856036f, 0.10672688f, 0.029162422f, -0.11585556f, 0.02557986f, -0.13446963f, -0.035785314f, -0.01244275f, 0.025961924f, -0.02337298f, -0.044228926f, -0.055839065f, -0.046598054f, -0.010546039f, -0.06900766f, 0.027239809f, 0.022582639f, -0.013296484f, -0.05459212f, 0.08981f, -0.045407712f, 0.08682226f, -0.06867011f, -0.14390695f, -0.02916037f, 0.000996957f, 0.091420636f, 0.14283475f, -0.07390571f, -0.06402044f, 0.062524505f, -0.093129106f, 0.04860203f, -0.08364217f, -0.08119002f, 0.009352075f, 0.22920375f, 0.0016303885f, 0.11583097f, -0.13732095f, 0.012405723f, -0.07551853f, 0.06343048f, 0.12162708f, -0.031923793f, -0.014335606f, 0.01790974f, -0.10650317f, -0.0724401f, 0.08554849f, -0.05727212f, 0.06556731f, -0.042729504f, -0.043227166f, 0.011683251f, -0.013082158f, -0.029302018f, -0.010899579f, -0.062036745f, -0.022509435f, -0.00964907f, -0.01567329f, 0.04260106f, -0.07787477f, -0.11576462f, 0.017356863f, 0.048673786f, -0.017577527f, -0.05527947f, -0.082487635f, -0.040137455f, -0.10820036f, -0.04666372f, 0.022746278f, -0.07851417f, 0.01068115f, 0.032956902f, 0.022433773f, 0.0026891115f, 0.08944216f, -0.0685835f, 0.010513544f, 0.07228705f, 0.02032331f, -0.059686817f, -0.0005566496f, -0.086984694f, 0.040414046f, -0.1380399f, 0.094208956f, -0.05722982f, 0.012092817f, -0.04989123f, -0.086576f, -0.003399834f, -0.04696032f, -0.045747425f, 0.10091314f, 0.048676282f, -0.029037097f, 0.031399418f, -0.0040285117f, 0.047237843f, 0.09504992f, 0.041799378f, -0.049185462f, -0.031518843f, -0.10516937f, 0.026374253f, 0.10058866f, -0.0033195973f, -0.041975245f, 0.0073591834f, 0.0033782164f, -0.004325073f, -0.10167381f, 0.042500053f, -0.01447153f, 0.06464186f, -0.017142897f, 0.03312627f, 0.009205989f, 0.024138335f, -0.011337001f, 0.035530265f, -0.010912711f, 0.0706555f, -0.005894094f, 0.051841937f, -0.1401738f, -0.02351249f, 0.0365468f, 0.07590991f, 0.08838724f, 0.021681072f, -0.10086113f, 0.019608743f, -0.06195883f, 0.077335775f, 0.023646897f, -0.095322326f, 0.02233014f, 0.09756986f, -0.048691444f, -0.009579111f, 0.07595467f, 0.11480546f, -0.09801813f, 0.019894179f, 0.08502348f, 0.004032281f, 0.037211012f, 0.068537936f, -0.048005626f, -0.091520436f, -0.028379958f, -0.01556313f, 0.06554592f, -0.045599163f, -0.01672207f, -0.020169014f, -0.011877351f, -0.20212261f, 0.010889619f, 0.0047078193f, 0.038385306f, 0.08540671f, -0.017140968f, -0.0035865551f, 0.016678626f, 0.005633034f, 0.015963363f, 0.00871737f, 0.060130805f, 0.028611384f, 0.10109069f, -0.015060172f, -0.07894427f, 0.06401885f, 0.011584063f, -0.024466386f, 0.0047652307f, -0.09041358f, 0.030737216f, -0.0046374933f, 0.14215417f, -0.11823516f, 0.019899689f, 0.006106124f, -0.027092824f, 0.0786356f, 0.05052217f, -0.058925f, -0.011402121f, -0.024987547f, -0.0013661642f, -0.06832946f, -0.015667673f, -0.1083353f, -0.00096863037f, -0.06988685f, -0.053350925f, -0.027275559f, -0.033664223f, -0.07978348f, -0.025200296f, -0.017207067f, -0.058403496f, -0.055697463f, 0.005798788f, 0.12965427f, -0.062582195f, 0.0013350133f, -0.10482091f, 0.0379771f, 0.072521195f, -0.0029455067f, -0.13797039f, -0.03628521f, 0.013806405f, -0.017858358f, -0.01008298f, -0.07700066f, -0.017081132f, 0.019358726f, 0.0027079724f, 0.004635139f, 0.062634714f, -0.02338735f, -0.039547626f, -0.02050681f, 0.03385117f, -0.083611414f, 0.002862572f, -0.09421313f, 0.058618143f, -0.08598433f, 0.00972939f, 0.023867095f, -0.053934585f, -0.023203006f, 0.07452513f, -0.048767887f, -0.07314807f, -0.056307215f, -0.10433547f, -0.06440842f, 0.04328182f, 0.04389765f, -0.020006588f, -0.09076438f, -0.11652589f, -0.021705797f, 0.03345259f, -0.010329105f, -0.025767034f, 0.013057034f, -0.07316461f, -0.10145612f, 0.06358255f, 0.18531723f, 0.07759293f, 0.12006465f, 0.1305557f, 0.058638252f, -0.03393652f, 0.09622831f, -0.16253184f, -2.4580743e-06f, 0.079869635f, -0.070196845f, -0.005644518f, 0.06857898f, -0.12598175f, -0.035084512f, 0.03156317f, -0.12794146f, -0.031963028f, 0.04692781f, 0.030070418f, 0.0071660685f, -0.095516115f, -0.004643372f, 0.040170413f, -0.062104587f, -0.0037324072f, 0.0554317f, 0.08184801f, -0.019164372f, 0.06791302f, 0.034257166f, -0.10307039f, 0.021943003f, 0.046745934f, 0.0790918f, -0.0265588f, -0.007824208f, 0.042546265f, -0.00977924f, -0.0002440307f, -0.017384544f, -0.017990116f, 0.12252321f, -0.014512694f, -0.08251313f, 0.08861942f, 0.13589665f, 0.026351685f, 0.012641483f, 0.07466548f, 0.044301085f, -0.045414884f, -0.051112458f, 0.03444247f, -0.08502782f, -0.04106223f, -0.028126027f, 0.028473156f, 0.10467447f}}, {6, {-0.057784554f, -0.026057621f, -0.068447545f, -0.022581743f, 0.14811787f, 0.10826372f, 0.09471067f, 0.03987225f, -0.0039523416f, 0.00030638507f, 0.053185795f, 0.10572994f, 0.08414449f, -0.022036452f, -0.00066928595f, -0.09203576f, 0.032950465f, -0.10985798f, -0.023809856f, 0.0021431844f, -0.02196096f, -0.00326074f, 0.00058621005f, -0.074678116f, -0.06193199f, 0.055729095f, 0.03736828f, 0.020123724f, 0.061878487f, -0.04729229f, 0.034919553f, -0.07585433f, -0.04421272f, -0.044019096f, 0.085488975f, 0.04058006f, -0.06890133f, -0.030951202f, -0.024628663f, -0.07672815f, 0.034293607f, 0.08556707f, -0.05293577f, -0.033561368f, -0.04899627f, 0.0241671f, 0.015736353f, -0.095442444f, -0.029564252f, 0.016493602f, -0.035026584f, 0.022337519f, -0.026871363f, 0.004780428f, 0.0077918363f, -0.03601621f, 0.016435321f, -0.03263031f, -0.09543275f, -0.047392778f, 0.013454138f, 0.028934088f, 0.01685226f, -0.086110644f, -0.046250615f, -0.01847454f, 0.047608484f, 0.07339695f, 0.034546845f, -0.04881143f, 0.009128804f, -0.08802852f, 0.03761666f, 0.008096139f, -0.014454086f, 0.014361001f, -0.023502491f, -0.0011840804f, -0.07607001f, 0.001856849f, -0.06509276f, -0.006021153f, -0.08570962f, -0.1451793f, 0.060212336f, 0.055259194f, 0.06974018f, 0.049454916f, -0.027794661f, -0.08077226f, -0.016179763f, 0.1169753f, 0.17213494f, -0.0056326236f, -0.053934924f, -0.0124349f, -0.11520337f, 0.05409887f, 0.088759385f, 0.0019655675f, 0.0042065294f, 0.03881498f, 0.019844765f, 0.041858196f, -0.05695512f, 0.047233116f, 0.038937137f, -0.06542224f, 0.014429736f, -0.09719407f, 0.13908425f, -0.05379757f, 0.012321099f, 0.082840554f, -0.029899208f, 0.044217527f, 0.059855383f, 0.07711018f, -0.045319796f, 0.0948846f, -0.011724666f, -0.0033288454f, -0.033542685f, -0.04764985f, -0.13873616f, 0.040668588f, 0.034832682f, -0.015319203f, -0.018715994f, 0.046002675f, 0.0599172f, -0.043107376f, 0.0294216f, -0.002314414f, -0.022424703f, 0.0030315618f, 0.0014641669f, 0.0029166266f, -0.11878115f, 0.013738511f, 0.12375372f, -0.0006038222f, 0.029104086f, 0.087442465f, 0.052958444f, 0.07558703f, 0.04817258f, 0.044462286f, -0.015213451f, -0.08783778f, -0.0561384f, -0.003008196f, 0.047060397f, -0.002058388f, 0.03429439f, -0.018839769f, 0.024734668f, 0.024614193f, -0.042046934f, 0.09597743f, -0.0043254104f, 0.04320769f, 0.0064070094f, -0.0019131786f, -0.02558259f, -0.022822596f, -0.023273505f, -0.02464396f, -0.10991725f, -0.006240552f, 0.0074488563f, 0.024044557f, 0.04383914f, -0.046476185f, 0.028658995f, 0.060410924f, 0.050786525f, 0.009452605f, -0.0073054377f, -0.024810238f, 0.0052906186f, 0.0066939713f, -0.0020913032f, 0.014515517f, 0.015898481f, 0.021362653f, -0.030262267f, 0.016587038f, -0.011442813f, 0.041154444f, -0.007631438f, -0.03423484f, -0.010977775f, 0.036152758f, 0.0066366293f, 0.11915515f, 0.02318443f, -0.041350313f, 0.021485701f, -0.10906167f, -0.028218046f, -0.00954771f, 0.020531068f, -0.11995105f, -0.03672871f, 0.024019798f, 0.014255957f, -0.05221243f, -0.00661567f, -0.04630967f, 0.033188973f, 0.10107534f, -0.014027541f, 0.030796422f, -0.10270911f, -0.035999842f, 0.15443139f, 0.07684145f, 0.036571592f, -0.035900835f, -0.0034699554f, 0.06209149f, 0.015920248f, -0.031122351f, -0.03858649f, 0.01849943f, 0.13872518f, 0.01503974f, 0.069941424f, -0.06948533f, -0.0088794185f, 0.061282158f, -0.047401894f, 0.03100163f, -0.041533746f, -0.10430945f, 0.044574402f, -0.01425562f, -0.024290353f, 0.034563623f, 0.05866852f, 0.023947537f, -0.09445152f, 0.035450947f, 0.02247216f, -0.0042998926f, 0.061146557f, -0.10250651f, 0.020881841f, -0.06747029f, 0.10062043f, -0.0023941975f, 0.03532124f, -0.016341697f, 0.09685456f, -0.016764693f, 0.051808182f, 0.05875331f, -0.04536488f, 0.001626336f, -0.028892258f, -0.01048663f, -0.009793449f, -0.017093895f, 0.010987891f, 0.02357273f, -0.00010856845f, 0.0099760275f, -0.001845119f, -0.03551521f, 0.0018358806f, 0.05763657f, -0.01769146f, 0.040995963f, 0.02235177f, -0.060430344f, 0.11475477f, -0.023854522f, 0.10071741f, 0.0686208f, -0.014250481f, 0.034261297f, 0.047418304f, 0.08562733f, -0.030519066f, 0.0060542435f, 0.014653856f, -0.038836084f, 0.04096551f, 0.032249358f, -0.08355519f, -0.026823482f, 0.056386515f, -0.010401743f, -0.028396193f, 0.08507674f, 0.014410365f, 0.020995233f, 0.17040324f, 0.11511526f, 0.02459721f, 0.0066619175f, 0.025853224f, -0.023133837f, -0.081302024f, 0.017264642f, -0.009585969f, 0.09491168f, -0.051313367f, 0.054532815f, -0.014298593f, 0.10657464f, 0.007076659f, 0.10964551f, 0.0409152f, 0.008275321f, -0.07283536f, 0.07937492f, 0.04192024f, -0.1075027f}}, {7, {-0.037322544f, 0.018592842f, 0.0056175636f, -0.06253426f, 0.055647098f, -0.05713207f, -0.05626563f, 0.005559383f, 0.03375411f, -0.025757805f, -0.088049285f, 0.06017052f, -0.06570978f, 0.007384076f, 0.035123326f, -0.07920549f, 0.053676967f, 0.044480428f, -0.07663568f, 0.0071805613f, 0.08089997f, 0.05143358f, 0.038261272f, 0.03339287f, -0.027673481f, 0.044746667f, 0.028349208f, 0.020090483f, -0.019443132f, -0.030755889f, -0.0040000007f, 0.04465846f, -0.021585021f, 0.0031670958f, 0.0053199246f, -0.056117613f, -0.10893326f, 0.076739706f, -0.08509834f, -0.027997585f, 0.037871376f, 0.01449768f, -0.09002357f, -0.06111149f, -0.046195522f, 0.0422062f, -0.005683705f, -0.1253618f, -0.012925729f, -0.04890792f, 0.06985068f, 0.037654128f, 0.03398274f, -0.004781977f, 0.007032333f, -0.031787455f, 0.010868644f, -0.031489216f, 0.09525667f, 0.013939797f, 0.0058680447f, 0.0167067f, 0.02668468f, -0.04797466f, -0.048885044f, -0.12722108f, 0.035304096f, 0.06554885f, 0.00972396f, -0.039238118f, -0.05159735f, -0.11329045f, 0.1613692f, -0.03750952f, 0.06529313f, -0.071974665f, -0.11769596f, 0.015524369f, -0.0013754242f, -0.12446318f, 0.02786344f, -0.014179351f, 0.005264273f, 0.14376344f, 0.015983658f, 0.03406988f, -0.06939408f, 0.040699873f, 0.02111075f, 0.09669095f, 0.041345075f, -0.08316494f, -0.07684199f, -0.045768797f, 0.032298047f, -0.041805092f, 0.0119405f, 0.0061010392f, 0.12652606f, 0.0064572375f, -0.024950314f, 0.11574242f, 0.04508852f, -0.04335324f, 0.06760663f, -0.027437469f, 0.07216407f, 0.06977076f, -0.05438599f, 0.034033038f, -0.028602652f, 0.05346137f, 0.043184172f, -0.037189785f, 0.10420091f, 0.00882477f, -0.054019816f, -0.074273005f, -0.030617684f, -0.0028467078f, 0.024302477f, -0.0038869337f, 0.005332455f, 0.0013399826f, 0.04361412f, -0.007001822f, 0.09631092f, -0.06702025f, -0.042049985f, -0.035070654f, -0.04103342f, -0.10273396f, 0.0544271f, 0.037184782f, -0.13150354f, -0.0058036847f, -0.008264958f, 0.042035464f, 0.05891794f, 0.029673764f, 0.0063542654f, 0.044788733f, 0.054816857f, 0.062257513f, -0.00093483756f, 0.048938446f, -0.004952862f, -0.007730018f, -0.04043371f, -0.017094059f, 0.07229206f, -0.023670016f, -0.052195564f, -0.025616996f, -0.01520939f, 0.045104615f, -0.007376126f, 0.003533447f, 0.006570588f, 0.056037236f, 0.12436656f, 0.051817212f, 0.028532185f, -0.08686856f, 0.11868599f, 0.07663395f, -0.07323171f, 0.03463402f, -0.050708205f, -0.04458982f, -0.11590894f, 0.021273347f, 0.1251325f, -0.15313013f, -0.12224372f, 0.17228661f, 0.023029093f, 0.086124025f, 0.006445803f, -0.03496501f, 0.028332196f, 0.04449512f, -0.042436164f, -0.026587414f, -0.006041347f, -0.09292539f, -0.05678812f, 0.03897832f, 0.09465633f, 0.008115513f, -0.02171956f, 0.08304309f, 0.071401566f, 0.019622514f, 0.032163795f, -0.004167056f, 0.02295182f, 0.030739572f, 0.056506045f, 0.004612461f, 0.06524936f, 0.059999723f, 0.046395954f, -0.0045512207f, -0.1335546f, -0.030136576f, 0.11584653f, -0.014678886f, 0.0020118146f, -0.09688814f, -0.0790206f, 0.039770417f, -0.0329582f, 0.07922767f, 0.029322514f, 0.026405897f, 0.04207835f, -0.07073373f, 0.063781224f, 0.0859677f, -0.10925287f, -0.07011058f, 0.048005477f, 0.03438226f, -0.09606514f, -0.006669445f, -0.043381985f, 0.04240257f, -0.06955775f, -0.06769346f, 0.043903265f, -0.026784198f, -0.017840602f, 0.024307009f, -0.040079936f, -0.019946516f, 0.045318738f, -0.12233574f, 0.026170589f, 0.0074471775f, 0.15978073f, 0.10185836f, 0.10298046f, -0.015476589f, -0.039390966f, -0.072174534f, 0.0739445f, -0.1211869f, -0.0347889f, -0.07943156f, 0.014809798f, -0.12412325f, -0.0030663363f, 0.039695457f, 0.0647603f, -0.08291318f, -0.018529687f, -0.004423833f, 0.0037507233f, 0.084633216f, -0.01514876f, -0.056505352f, -0.012800942f, -0.06994386f, 0.012962922f, -0.031234352f, 0.07029052f, 0.016418684f, 0.03618972f, 0.055686004f, -0.08663945f, -0.017404709f, -0.054761406f, 0.029065743f, 0.052404847f, 0.020238016f, 0.0048197987f, -0.0214882f, 0.07078733f, 0.013016777f, 0.06262858f, 0.009184685f, 0.020785125f, -0.043904778f, -0.0270329f, -0.03299152f, -0.060088247f, -0.015162964f, -0.001828936f, 0.12642565f, -0.056757294f, 0.013586685f, 0.09232601f, -0.035886683f, 0.06000002f, 0.05229691f, -0.052580316f, -0.082029596f, -0.010794592f, 0.012947712f, -0.036429964f, -0.085508935f, -0.13127148f, -0.017744139f, 0.031502828f, 0.036232427f, -0.031581745f, 0.023051167f, -0.05325106f, -0.03421577f, 0.028793324f, -0.034633752f, -0.009881397f, -0.043551125f, -0.018609839f, 0.0019097115f, -0.008799762f, 0.056595087f, 0.0022273948f, 0.055752404f}}, {8, {0.025825322f, -0.05813119f, 0.09495884f, -0.045984812f, -0.01255415f, -0.0026479573f, -0.08196161f, -0.054914974f, -0.0046604523f, -0.029587349f, -0.044576716f, -0.07480124f, -0.082868785f, 0.023254942f, 0.027502948f, -0.0039728214f, -0.08683098f, -0.08116779f, -0.014675607f, -0.037924774f, -0.023314456f, -0.007401714f, -0.09255757f, 0.029460307f, -0.08829125f, -0.005139627f, -0.08989442f, -0.0555066f, 0.13596267f, -0.025062224f, -0.048351806f, -0.03850004f, 0.07266485f, -0.022414139f, 0.05940088f, 0.075114764f, 0.09597592f, -0.010211725f, -0.0049794707f, -0.011523867f, -0.025980417f, 0.072999895f, 0.11091378f, -0.081685916f, 0.014416728f, 0.043229222f, 0.034178585f, -0.07530371f, 0.035837382f, -0.085607f, -0.007721233f, -0.03287832f, -0.043848954f, -0.06404588f, -0.06632928f, -0.073643476f, 0.008214239f, -0.045984086f, 0.039764922f, 0.03474462f, 0.060612556f, -0.080590084f, 0.049127717f, 0.04151091f, -0.030063879f, 0.008801774f, -0.023021035f, -0.019558564f, 0.05158114f, -0.010947698f, -0.011825728f, 0.0075720972f, 0.0699727f, -0.0039981045f, 0.069350146f, 0.08799282f, 0.016156472f, 0.035502106f, 0.11695009f, 0.006217345f, 0.13392477f, -0.037875112f, 0.025745004f, 0.08940699f, -0.00924166f, 0.0046702605f, -0.036598757f, -0.08811812f, 0.10522024f, -0.032441203f, 0.008176899f, -0.04454919f, 0.07058152f, 0.0067963637f, 0.039206743f, 0.03259838f, 0.03725492f, -0.09515802f, 0.013326398f, -0.052055415f, -0.025676316f, 0.03198509f, -0.015951829f, -0.058556724f, 0.036879618f, 0.043357447f, 0.028362012f, -0.05908629f, 0.0059240665f, -0.04995891f, -0.019187413f, 0.0276265f, -0.01628143f, 0.0025863599f, 0.08800015f, 0.035250366f, -0.022165963f, -0.07328642f, -0.009415526f, -0.07455109f, 0.11690406f, 0.0363299f, 0.07411125f, 0.042103454f, -0.009660886f, 0.019076364f, 0.018299393f, -0.046004917f, 0.08891175f, 0.0431396f, -0.026327137f, -0.051502608f, 0.08979574f, -0.051670972f, 0.04940282f, -0.07491107f, -0.021240504f, 0.022596184f, -0.034280192f, 0.060163025f, -0.058211457f, -0.051837247f, -0.01349775f, -0.04639988f, -0.035936575f, -0.011681591f, 0.064818054f, 0.0073146066f, -0.021745546f, -0.043124277f, -0.06471268f, -0.07053354f, -0.029321948f, -0.05330136f, 0.016933719f, -0.053782392f, 0.13747959f, -0.1361751f, -0.11569455f, 0.0033329215f, 0.05693899f, -0.053219706f, 0.063698f, 0.07977434f, -0.07924483f, 0.06936997f, 0.0034815092f, -0.007305279f, -0.037325785f, -0.07251102f, -0.033633437f, -0.08677009f, 0.091591336f, -0.14165086f, 0.021752775f, 0.019683983f, 0.0011612234f, -0.058154266f, 0.049996935f, 0.0288841f, -0.0024567875f, -0.14345716f, 0.010955264f, -0.10234828f, 0.1183656f, -0.0010731248f, -0.023590032f, -0.072285876f, -0.0724771f, -0.026382286f, -0.0014920527f, 0.042667855f, 0.0018776858f, 0.02986552f, 0.009814309f, 0.0733756f, 0.12289186f, 0.018043943f, -0.0458958f, 0.049412545f, 0.033632483f, 0.05495232f, 0.036686596f, -0.013781798f, -0.010036754f, 0.02576849f, -0.08307328f, 0.010112348f, 0.042521734f, -0.05869831f, -0.071689695f, 0.03876447f, -0.13275425f, -0.0352966f, -0.023077697f, 0.10285965f, 0.084736146f, 0.15568255f, -0.00040734606f, 0.027835453f, -0.10292561f, -0.032401145f, 0.10053256f, -0.026142767f, -0.08271222f, -0.0030240538f, -0.016368777f, 0.1070414f, 0.042672627f, 0.013456989f, -0.0437609f, -0.022309763f, 0.11576483f, 0.04108048f, 0.061026827f, -0.0190714f, -0.0869359f, 0.037901703f, 0.0610107f, 0.07202949f, 0.01675338f, 0.086139716f, -0.08795751f, -0.014898893f, -0.023771819f, -0.01965048f, 0.007955471f, -0.043740474f, 0.03346837f, -0.10549954f, 0.090567775f, 0.042013682f, -0.03176985f, 0.12569028f, -0.02421228f, -0.029526481f, 0.023851605f, 0.031539805f, 0.05292009f, -0.02344001f, -0.07811758f, -0.08834428f, 0.10094801f, 0.16594367f, -0.06861939f, -0.021256343f, -0.041093912f, -0.06669611f, 0.035498552f, 0.021757556f, -0.09302526f, -0.015403468f, -0.06614931f, -0.051798206f, -0.013874718f, 0.03630673f, 0.010412845f, -0.08077351f, 0.046185967f, 0.0035662893f, 0.03541868f, -0.094149634f, -0.034814864f, 0.003128424f, -0.020674974f, -0.03944324f, -0.008110165f, -0.11113267f, 0.08484226f, 0.043586485f, 0.040582247f, 0.0968012f, -0.065249965f, -0.028036479f, 0.0050708856f, 0.0017462453f, 0.0326779f, 0.041296225f, 0.09164146f, -0.047743853f, -0.015952192f, -0.034451712f, 0.084197424f, -0.05347844f, -0.11768019f, 0.085926116f, -0.08251791f, -0.045081906f, 0.0948852f, 0.068401024f, 0.024856757f, 0.06978981f, -0.057309967f, -0.012775832f, -0.0032452994f, 0.01977615f, -0.041040014f, -0.024264973f, 0.063464895f, 0.05431621f}}, {9, {0.040369894f, 0.030746894f, 0.24704495f, 0.018586371f, -0.037586458f, -0.15312155f, -0.11812848f, -0.11465643f, 0.20259799f, 0.11418174f, -0.10116027f, -0.011334949f, 0.12411352f, -0.076769054f, -0.052169047f, 0.21198851f, -0.38871562f, -0.09061183f, -0.09683246f, -0.21929175f}}, {10, {-0.01998659f, -0.15568835f, -0.24248174f, -0.012770197f, 0.041331276f, -0.072311886f, -0.052123554f, -0.0066330447f, -0.043891653f, 0.036225766f, -0.047248036f, 0.021479502f, 0.033189066f, 0.11952997f, -0.020432774f, 0.64658105f, -0.06650122f, -0.03467612f, 0.095340036f, 0.23647355f}}, {11, {0.08286371f, -0.08261836f, -0.51210177f, 0.002913762f, 0.17764764f, -0.5495371f, -0.08460716f, -0.24552552f, 0.030037103f, 0.04123544f, -0.11940523f, 0.007358328f, 0.1890978f, 0.4833202f, -0.34441817f, 0.36312827f, -0.26375428f, 0.1457655f, -0.19724406f, 0.15548733f}}, {12, {0.02234832f, 0.14757581f, 0.18176508f, 0.10380666f, 0.053110216f, -0.06928846f, -0.13942584f, -0.11816189f, 0.19483899f, 0.03652339f, -0.10250295f, 0.036714908f, -0.18426876f, 0.036065217f, 0.21810818f, 0.02383196f, -0.043370757f, 0.08690144f, -0.04444982f, 0.00030581196f}}, {13, {0.035185695f, -0.042891346f, -0.03032477f, 0.23027696f, 0.11098921f, 0.15378423f, 0.09263801f, 0.09790885f, 0.09508917f, 0.061199076f, 0.07665568f, -0.015443159f, -0.03499149f, 0.046190713f, 0.08895977f, 0.10899629f, 0.40694186f, 0.06030037f, 0.012413437f, -0.06108739f}}, {14, {-0.024379363f, 0.0055531194f, 0.23377132f, 0.033463873f, -0.1483596f, -0.10639995f, -0.091433935f, 0.058573797f, -0.06809782f, -0.07889636f, -0.043246906f, -0.09829136f, -0.4279842f, 0.034901652f, 0.18797937f, 0.0075234566f, 0.016178843f, 0.1749513f, 0.13975595f, 0.92058027f}}, {15, {0.046159424f, -0.0012809046f, 0.03563469f, 0.12648113f, 0.027195795f, 0.35373217f, -0.018957434f, 0.008907322f, -0.0762701f, 0.12018895f, 0.04216877f, 0.0022856654f, 0.040952638f, 0.3147856f, 0.08225149f, -0.057416286f, -0.14995944f, -0.008040261f, 0.13208859f, 0.029760877f}}, {16, {-0.009802181f, 0.09401916f, 0.0717386f, -0.13895074f, 0.09641832f, 0.060420845f, 0.08539281f, 0.054285463f, 0.061395317f, 0.034448683f, -0.042991187f, 0.019801661f, -0.16840284f, -0.015726732f, -0.23041931f, -0.024478018f, -0.10959692f, -0.013875541f, 0.18600968f, -0.061274476f, 0.0138165f, -0.08160894f, -0.07661644f, 0.032372914f, 0.16169067f, 0.22465782f, -0.03993472f, -0.004017731f, 0.08633481f, -0.28869787f, 0.08682067f, 0.17240396f, 0.014975425f, 0.056431185f, 0.031037588f, 0.16702051f, 0.0077946745f, 0.15140012f, 0.29405436f, 0.120285f, -0.188994f, -0.027265169f, 0.043389652f, -0.022061434f, 0.014777949f, -0.20203483f, 0.094781205f, 0.19100232f, 0.13987629f, -0.036132768f, -0.06426278f, -0.05108664f, 0.13221376f, 0.009441198f, -0.16715929f, 0.15859416f, -0.040437475f, 0.050779544f, -0.022187516f, 0.012166504f, 0.027685808f, -0.07675938f, -0.0055694645f, -0.09444123f, 0.0046453946f, 0.050794356f, 0.10770313f, -0.20790008f, -0.07149004f, -0.11425117f, 0.008225835f, -0.035802525f, 0.14374903f, 0.15262283f, 0.048710253f, 0.1847461f, -0.007487823f, 0.11000021f, -0.09542012f, 0.22619456f, -0.029149994f, 0.08527916f, 0.009043713f, 0.0042746216f, 0.016261552f, 0.022461696f, 0.12689082f, -0.043589946f, -0.12035478f, -0.08361797f, -0.050666027f, -0.1248618f, -0.1275799f, -0.071875185f, 0.07377272f, 0.09944291f, -0.18897448f, -0.1593054f, -0.06526116f, -0.040107165f, -0.004618631f, -0.067624845f, -0.007576253f, 0.10727444f, 0.041546922f, -0.20424393f, 0.06907816f, 0.050412357f, 0.00724631f, 0.039827548f, 0.12449835f, 0.10747581f, 0.13708383f, 0.09134148f, -0.12617786f, -0.06428341f, 0.09956831f, 0.1208086f, -0.14676677f, -0.0727722f, 0.1126304f, 0.010139365f, 0.015571211f, -0.038128063f, 0.022913318f, -0.042050496f, 0.16842307f, -0.060597885f, 0.10531834f, -0.06411776f, -0.07451711f, -0.03410368f, -0.13393489f, 0.06534304f, 0.003620307f, 0.04490757f, 0.05970546f, 0.05197996f, 0.02839995f, 0.10434969f, -0.013699693f, -0.028353551f, -0.07260381f, 0.047201227f, -0.024575593f, -0.036445823f, 0.07155557f, 0.009672501f, -0.02328883f, 0.009533515f, -0.03606021f, -0.07421458f, -0.028082801f, -0.2678904f, -0.13221288f, 0.18419984f, -0.13012612f, -0.014588381f, -0.035059117f, -0.04824723f, 0.07830115f, -0.056184657f, 0.03277091f, 0.025466874f, 0.14494097f, -0.12522776f, -0.098633975f, -0.10766018f, -0.08317623f, 0.08594209f, 0.07749552f, 0.039474737f, 0.1776665f, -0.07409566f, -0.0477268f, 0.29323658f, 0.10801441f, 0.1154011f, 0.013952499f, 0.10739139f, 0.10708251f, -0.051456142f, 0.0074137426f, -0.10430189f, 0.10034707f, 0.045594677f, 0.0635285f, -0.0715442f, -0.089667566f, -0.10811871f, 0.00026344223f, 0.08298446f, -0.009525053f, 0.006585689f, -0.24567553f, -0.09450807f, 0.09648481f, 0.026996298f, -0.06419476f, -0.04752702f, -0.11063944f, -0.23441927f, -0.17608605f, -0.052156363f, 0.067035615f, 0.19271925f, -0.0032889997f, -0.043264326f, 0.09663576f, -0.057112187f, -0.10100678f, 0.0628376f, 0.04447668f, 0.017961001f, -0.10094388f, -0.10190601f, 0.18335468f, 0.10494553f, -0.052095775f, -0.0026118709f, 0.10539724f, -0.04383912f, -0.042349473f, 0.08438151f, -0.1947263f, 0.02251204f, 0.11216432f, -0.10307853f, 0.17351969f, -0.039091777f, 0.08066188f, -0.00561982f, 0.12633002f, 0.11335965f, -0.0088127935f, -0.019777594f, 0.06864014f, -0.059751723f, 0.016233567f, -0.06894641f, -0.28651384f, -0.004228674f, 0.019708522f, -0.16305895f, -0.07468996f, -0.0855457f, 0.099339016f, -0.07580735f, -0.13775392f, 0.08434318f, 0.08330512f, -0.12131499f, 0.031935584f, 0.09180414f, -0.08876437f, -0.08049874f, 0.008753825f, 0.03498998f, 0.030215185f, 0.03907079f, 0.089751154f, 0.029194152f, -0.03337423f, -0.019092513f, 0.04331237f, 0.04299654f, -0.036394123f, -0.12915532f, 0.09793732f, 0.07512415f, -0.11319543f, -0.032502122f, 0.15661901f, 0.07671967f, -0.005491124f, -0.19379048f, -0.218606f, 0.21448623f, 0.017840758f, 0.1416943f, -0.07051762f, 0.19488361f, 0.02664691f, -0.18104725f, -0.09334311f, 0.15026465f, -0.15493552f, -0.057762887f, -0.11604192f, -0.262013f, -0.01391798f, 0.012185008f, 0.11156489f, -0.07483202f, 0.06693364f, -0.26151478f, 0.046425626f, 0.036540434f, -0.16435726f, 0.17338543f, -0.21401681f, -0.11385144f, -0.08283257f, -0.069031075f, 0.030635102f, 0.010969227f, 0.11109743f, 0.010919218f, 0.027526086f, 0.13519906f, 0.01891392f, -0.046839405f, -0.040167913f, 0.017953383f, -0.09700955f, 0.0061885654f, -0.07000971f, 0.026893595f, -0.038844477f, 0.14543656f}}, {17, {0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f}}, {18, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}}, {19, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}}, {20, {}}, {21, {}}, {22, {}}, {23, {}}},
// int -> INT32 map
.int32Operands = {},
// int -> QUANT8_ASYMM map
.quant8AsymmOperands = {},
// int -> QUANT16_SYMM map
.quant16SymmOperands = {},
// int -> FLOAT16 map
.float16Operands = {},
// int -> BOOL8 map
.bool8Operands = {},
// int -> QUANT8_SYMM_PER_CHANNEL map
.quant8ChannelOperands = {},
// int -> QUANT16_ASYMM map
.quant16AsymmOperands = {},
// int -> QUANT8_SYMM map
.quant8SymmOperands = {},
},
//Output(s)
{ // See tools/test_generator/include/TestHarness.h:MixedTyped
// int -> Dimensions map
.operandDimensions = {{0, {2, 4, 16}}},
// int -> FLOAT32 map
.float32Operands = {{0, {0.0960319489f, 0.229351997f, 0.297207743f, 0.415997744f, 0.491644233f, 0.578822136f, 0.728351235f, 0.788540304f, 0.909073055f, 0.975599587f, 1.08478093f, 1.17409372f, 1.30914319f, 1.4041512f, 1.51714694f, 1.61342025f, 0.0634541437f, 0.190279216f, 0.317923307f, 0.415168911f, 0.458113253f, 0.609743774f, 0.731511116f, 0.795806408f, 0.876155913f, 0.960330188f, 1.12396312f, 1.22149014f, 1.33917773f, 1.43213499f, 1.54139447f, 1.65451813f, 0.0485293195f, 0.160991609f, 0.337073475f, 0.428976893f, 0.459505379f, 0.617044866f, 0.743735075f, 0.790821671f, 0.85271728f, 0.946818829f, 1.12779701f, 1.23345077f, 1.35309088f, 1.44595909f, 1.56173062f, 1.67839324f, 0.0445971154f, 0.156434938f, 0.341761589f, 0.425259203f, 0.449760497f, 0.633765697f, 0.745093822f, 0.791106999f, 0.84820503f, 0.952787101f, 1.13438797f, 1.24063754f, 1.34668994f, 1.44879568f, 1.57038593f, 1.67956686f, 0.0861309841f, 0.228726774f, 0.296653062f, 0.40733397f, 0.47120741f, 0.581307411f, 0.719366193f, 0.788456261f, 0.904226124f, 0.965476751f, 1.10223258f, 1.19042683f, 1.32106233f, 1.41333091f, 1.51509535f, 1.62168002f, 0.0652779415f, 0.18218407f, 0.324066937f, 0.42611438f, 0.47292757f, 0.602282405f, 0.739310443f, 0.791508496f, 0.870626807f, 0.955534995f, 1.10976851f, 1.21598971f, 1.34197009f, 1.43256509f, 1.54804492f, 1.65581059f, 0.0492607877f, 0.169714347f, 0.332315415f, 0.419173867f, 0.44699502f, 0.630063772f, 0.737177074f, 0.792844594f, 0.858417571f, 0.956391335f, 1.13453305f, 1.23976779f, 1.34693861f, 1.4410423f, 1.55988359f, 1.67204297f, 0.0390465111f, 0.15099439f, 0.3439475f, 0.424439192f, 0.444207728f, 0.632501483f, 0.742233515f, 0.791400731f, 0.845713973f, 0.944575012f, 1.14116096f, 1.24791968f, 1.35954499f, 1.45086145f, 1.56633317f, 1.68943977f}}},
// int -> INT32 map
.int32Operands = {},
// int -> QUANT8_ASYMM map
.quant8AsymmOperands = {},
// int -> QUANT16_SYMM map
.quant16SymmOperands = {},
// int -> FLOAT16 map
.float16Operands = {},
// int -> BOOL8 map
.bool8Operands = {},
// int -> QUANT8_SYMM_PER_CHANNEL map
.quant8ChannelOperands = {},
// int -> QUANT16_ASYMM map
.quant16AsymmOperands = {},
// int -> QUANT8_SYMM map
.quant8SymmOperands = {},
}
},
}, // End of an example
};
return examples_dynamic_output_shape;
};
| [
"[email protected]"
] | |
d42e744d52e2be0d77d2647487346bcc2196a01d | 27b1be9ece5642f4c2d5b3930745508c2069888a | /src/libtsduck/plugin/tsAbstractDescrambler.h | fcea86fae993447d04a8f55b176d72600001fdb7 | [
"BSD-2-Clause"
] | permissive | vacing/tsduck | 26dbe9e0a39e6c15e0364d59433eec9466fef18b | ac01b88a8052419bfce9715886d597419fc5fef6 | refs/heads/master | 2020-11-30T00:57:35.128901 | 2019-12-20T22:34:25 | 2019-12-20T22:34:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,482 | h | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2019, Thierry Lelegard
// 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.
//
//----------------------------------------------------------------------------
//!
//! @file
//! Abstract base class for DVB descrambler plugins.
//!
//----------------------------------------------------------------------------
#pragma once
#include "tsPlugin.h"
#include "tsSafePtr.h"
#include "tsSection.h"
#include "tsServiceDiscovery.h"
#include "tsTSScrambling.h"
#include "tsCondition.h"
#include "tsMutex.h"
#include "tsThread.h"
#include "tsMemory.h"
namespace ts {
//!
//! Abstract base class for DVB descrambler plugins.
//! @ingroup plugin
//!
class TSDUCKDLL AbstractDescrambler:
public ProcessorPlugin,
protected PMTHandlerInterface,
protected SectionHandlerInterface
{
TS_NOBUILD_NOCOPY(AbstractDescrambler);
public:
// Implementation of ProcessorPlugin interface.
// If overridden by descrambler subclass, superclass must be explicitly invoked.
virtual bool getOptions() override;
virtual bool start() override;
virtual bool stop() override;
virtual Status processPacket(TSPacket&, TSPacketMetadata&) override;
protected:
//!
//! Default stack usage allocated to CAS-specific processing of an ECM.
//! @see decipherECM()
//!
static const size_t DEFAULT_ECM_THREAD_STACK_USAGE = 128 * 1024;
//!
//! Constructor for subclasses.
//! @param [in] tsp Object to communicate with the Transport Stream Processor main executable.
//! @param [in] description A short one-line description, eg. "Descrambler for 'xyz' CAS".
//! @param [in] syntax A short one-line syntax summary, default: u"[options] [service]".
//! @param [in] stack_usage Stack usage for asynchronous ECM deciphering.
//!
AbstractDescrambler(TSP* tsp,
const UString& description = UString(),
const UString& syntax = u"[options] [service]",
size_t stack_usage = DEFAULT_ECM_THREAD_STACK_USAGE);
//!
//! Check a CA_descriptor from a PMT.
//!
//! Must be implemented by subclasses (concrete descramblers).
//!
//! This method is invoked by the superclass when a CA_descriptor is found in a PMT.
//!
//! The subclass must check if it can descramble ECM's from the corresponding PID.
//! This method shall check two things:
//! - Verify that the CA_system_id is compatible with the concrete descrambler.
//! - Optionally verify that the private part of the CA_descriptor is
//! compatible with, for instance, the capabilities of the smartcard.
//!
//! Example: A CAS may set an operator id in the private part of the
//! CA_descriptor and the smartcard may have returned the list of operators
//! during initialization. If the smartcard cannot manage any operator in
//! the CA_descriptor, this ECM stream is probably for another operator and
//! the descrambler should ignore it.
//!
//! @param [in] cas_id CA_system_id value.
//! @param [in] priv Private part of the CA_descriptor.
//! @return True if the descrambler can manage the ECM from this PID.
//!
virtual bool checkCADescriptor(uint16_t cas_id, const ByteBlock& priv) = 0;
//!
//! Check if the descrambler may decipher an ECM.
//!
//! Must be implemented by subclasses (concrete descramblers).
//!
//! This method is invoked when a new ECM is received from a valid ECM stream
//! which was validated by checkCADescriptor(). This method may perform
//! additional checks on the ECM itself. But this method shall not attempt to
//! decipher the ECM or submit it to a smartcard or perform any time-consuming
//! processing.
//!
//! @param [in] ecm CMT section (typically an ECM).
//! @return False if this ECM cannot be deciphered.
//! True if it may be deciphered, although it may fail when actually submitted.
//! @see decipherECM()
//! @see checkCADescriptor()
//!
virtual bool checkECM(const Section& ecm) = 0;
//!
//! Description of a control word.
//!
class CWData
{
public:
uint8_t scrambling; //!< Scrambling mode, as defined in scrambling_descriptor.
ByteBlock cw; //!< Control word, typically 8 or 16 bytes.
ByteBlock iv; //!< Initialization vector, typically empty or 16 bytes.
//!
//! Constructor.
//! @param [in] mode Scrambling mode.
//!
CWData(uint8_t mode = SCRAMBLING_DVB_CSA2);
};
//!
//! Decipher an ECM, return up to two control words, even and/or odd.
//!
//! Must be implemented by subclasses (concrete descramblers).
//!
//! By default (without -\-synchronous option), this method is executed in the
//! context of a separate thread. It may take any necessary time to process
//! an ECM, including submitting it to a smartcard. This method shall return
//! either an odd CW, even CW or both. Missing CW's shall be empty.
//!
//! @param [in] ecm CMT section (typically an ECM).
//! @param [in,out] cw_even Returned even CW. Empty if the ECM contains no even CW.
//! On input, the scrambling field is set to the current descrambling mode.
//! It output, the scrambling field can be updated if the ECM specifies a new one.
//! @param [in,out] cw_odd Returned odd CW. Empty if the ECM contains no odd CW.
//! On input, the scrambling field is set to the current descrambling mode.
//! It output, the scrambling field can be updated if the ECM specifies a new one.
//! @return True on success, false on error. Missing ECM's (odd or even) in the ECM
//! shall not be considered as errors. Unable to decipher the ECM is an error.
//!
virtual bool decipherECM(const Section& ecm, CWData& cw_even, CWData& cw_odd) = 0;
protected:
//!
//! This hook is invoked when a new PMT is available.
//! Implementation of PMTHandlerInterface.
//! If overridden by a concrete descrambler, the superclass must be explicitly invoked.
//! @param [in] table A reference to the new PMT.
//!
virtual void handlePMT(const PMT& table) override;
//!
//! This hook is invoked when a complete section is available.
//! Implementation of SectionHandlerInterface.
//! If overridden by a concrete descrambler, the superclass must be explicitly invoked.
//! @param [in,out] demux The demux which sends the section.
//! @param [in] section The new section from the demux.
//!
virtual void handleSection(SectionDemux& demux, const Section& section) override;
private:
// Description of a scrambled stream with its possible ECM PID's.
// Each elementary stream in the service can be potentially scrambled.
// Each of them has an entry in _scrambled_streams with the list of valid ECM PID's.
// Here, a stream may have several potential ECM PID's. Although only one ECM stream
// is normally used for a given descrambler configuration, we may not know which one
// to use from the beginning. If the CAS in the subclass is very selective, checkCADescriptor()
// will indicate the precise ECM PID to use. Otherwise, we may have more than one candidate.
// We filter ECM's on all these PID's and we hope that the subclass will indicate which
// ECM's are the right ones in checkECM(). At worst, we try to decipher all ECM's from
// all ECM streams and decipherECM() will fail with ECM's we cannot handle.
class ScrambledStream
{
public:
// Constructor
ScrambledStream() : ecm_pids() {}
std::set<PID> ecm_pids; // PIDs of ECM streams
};
// Map of scrambled streams in the service, indexed by PID.
typedef std::map<PID, ScrambledStream> ScrambledStreamMap;
// Description of an ECM stream
class ECMStream
{
TS_NOBUILD_NOCOPY(ECMStream);
public:
// Constructor
ECMStream(AbstractDescrambler* parent);
TID last_tid; // Last table id (0x80 or 0x81)
TSScrambling scrambling; // Descrambling using CW from the ECM's of this stream.
// -- start of write-protected, read-volatile area --
volatile bool cw_valid; // CW's are valid
volatile bool new_cw_even; // New CW available (even)
volatile bool new_cw_odd; // New CW available (odd)
// -- start of protected area --
bool new_ecm; // New ECM available
Section ecm; // Last received ECM
CWData cw_even; // Last valid CW (even)
CWData cw_odd; // Last valid CW (odd)
// -- end of protected area --
};
typedef SafePtr<ECMStream, NullMutex> ECMStreamPtr;
typedef std::map<PID, ECMStreamPtr> ECMStreamMap;
// ECM deciphering thread
class ECMThread : public Thread
{
TS_NOBUILD_NOCOPY(ECMThread);
public:
// Constructor.
ECMThread(AbstractDescrambler* parent) : _parent(parent) {}
private:
// Thread entry point.
virtual void main() override;
// Link to parent descrambler.
AbstractDescrambler* _parent;
};
// Get the ECM stream for a PID, create it if non existent
ECMStreamPtr getOrCreateECMStream(PID);
// Process one ECM (the one in ECMStream::ecm).
// In asynchronous mode, this method must be invoked with the mutex held. The method
// releases the mutex while deciphering the ECM and relocks it before exiting.
void processECM(ECMStream&);
// Analyze a list of descriptors from the PMT, looking for ECM PID's
void analyzeDescriptors(const DescriptorList& dlist, std::set<PID>& ecm_pids, uint8_t& scrambling);
// Abstract descrambler private data.
bool _use_service; // Descramble a service (ie. not a specific list of PID's).
bool _need_ecm; // We need to get control words from ECM's.
bool _abort; // Error, abort asap.
bool _synchronous; // Synchronous ECM deciphering.
bool _swap_cw; // Swap even/odd CW from ECM.
TSScrambling _scrambling; // Default descrambling (used with fixed control words).
PIDSet _pids; // Explicit PID's to descramble.
ServiceDiscovery _service; // Service to descramble (by name, id or none).
size_t _stack_usage; // Stack usage for ECM deciphering.
SectionDemux _demux; // Section demux to extract ECM's.
ECMStreamMap _ecm_streams; // ECM streams, indexed by PID.
ScrambledStreamMap _scrambled_streams; // Scrambled streams, indexed by PID.
Mutex _mutex; // Exclusive access to protected areas
Condition _ecm_to_do; // Notify thread to process ECM.
ECMThread _ecm_thread; // Thread which deciphers ECM's.
// -- start of protected area --
bool _stop_thread; // Terminate ECM processing thread
// -- end of protected area --
};
}
| [
"[email protected]"
] | |
3d28bfdbd9638004e5250a66c58e4ac5b1231052 | 1390f5b3c26cbcd1b3265e03e5e4b54f3f649edd | /util/usage_io.cpp | 70926876a67c05dac0f4d5a20e8ecdc41b8de254 | [] | no_license | amulya349/codingskill-1 | 6ea24dd304e9c00097991b58f2d3d35363ff37cc | 4cde8224ea1a8d3318c453af94f7c9289131d867 | refs/heads/master | 2021-01-18T14:33:54.080159 | 2013-07-18T07:05:08 | 2013-07-18T07:05:08 | 11,496,448 | 0 | 0 | null | 2015-05-13T08:38:42 | 2013-07-18T07:02:21 | C++ | UTF-8 | C++ | false | false | 303 | cpp | #include "io.h"
#include <vector>
using namespace std;
int main(int argc, char * argv[]) {
int A[] = {-1,0,1,1,2,-1,4};
vector<int> vt = UIO<int>::in(A, sizeof(A)/sizeof(A[0]));
UIO<int>::pr(vt);
vector<vector<int> > vvt;
vvt.push_back(vt);
UIO<int>::pr(vvt);
return 0;
}
| [
"[email protected]"
] | |
085a63fad8a810f8a65650636172aed5b37eaae5 | bc8c075b1eb7628f88dedd2c1acf221ed2ed12f8 | /Seed/Pack.cpp | 22940b440fb74ab7e7aa87bc32fadf36a2f2d0b0 | [] | no_license | HyperGamingSandbox/Seed | 4b896f649adf41f4e965b1b0ad6a0850df55bac6 | 0dcecabb33bcbff5435311724a51904d41c7de03 | refs/heads/master | 2021-09-13T21:24:31.089275 | 2018-05-04T10:47:41 | 2018-05-04T10:47:41 | 111,595,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,593 | cpp | #include <string>
#include <list>
#include "Pack.h"
#include "zlib\zlib.h"
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
char *tchar2char(wchar_t *t) {
auto l = wcslen(t) + 1;
char *s = new char[l];
// wcstombs_s(s, t, wcslen(t) + 1);
size_t sz;
wcstombs_s(&sz, s, l, t, l);
return s;
}
wchar_t *char2tchar(char *s) {
size_t size = strlen(s) + 1;
wchar_t *wbuf = new wchar_t[size];
size_t outSize;
mbstowcs_s(&outSize, wbuf, size, s, size - 1);
return wbuf;
}
namespace Seed {
unsigned char *psig = (unsigned char *)"CoOoLLL pROt3Cti0n !!11";
auto psig_len = strlen((char *)psig);
void _encode(void *b, int l, int *pos) {
auto *bb = (unsigned char *)b;
if ((*pos) >= psig_len) {
*pos = (*pos) % psig_len;
}
while (l--) {
*bb ^= psig[*pos];
(*pos)++;
if ((*pos) >= psig_len) {
(*pos) = 0;
}
bb++;
}
}
void fwrite(void *b, size_t l, FILE *f, int *enc_pos, bool copy = true) {
void *c = NULL;
if (copy) {
void *c = malloc(l);
memcpy(c, b, l);
b = c;
}
_encode(b, (int)l, enc_pos);
::fwrite(b, l, 1, f);
if (c) {
free(c);
}
}
typedef std::list<std::string> FileList;
FileList getFileList(char *dirname) {
FileList fileList;
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
char b[1024];
sprintf_s(b, "%s\\*", dirname);
hFind = FindFirstFile(char2tchar(b), &ffd);
if (INVALID_HANDLE_VALUE == hFind) {
sprintf_s(b, "Error: FindFirstFile(%s)\n", dirname);
OutputDebugStringA(b);
return fileList;
}
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
char *filename = tchar2char(ffd.cFileName);
if (filename[0] != '.') {
sprintf_s(b, "%s\\%s", dirname, filename);
auto list = getFileList(b);
for (auto it = list.begin(), eit = list.end(); it != eit; it++) {
fileList.push_back(*it);
}
}
}
else {
// check for .lua
char *filename = tchar2char(ffd.cFileName);
bool accept = true;
/*
if (wc) {
accept = false;
if (strlen(filename) > strlen(wc) && strcmp(wc, &filename[strlen(filename) - strlen(wc)]) == 0) {
accept = true;
}
}
*/
if (accept) {
sprintf_s(b, "%s\\%s", dirname, filename);
fileList.push_back(b);
/*
list->size = ffd.nFileSizeLow;
list->filename = makecopy(b);
list->next = NULL;
*/
}
}
} while (FindNextFile(hFind, &ffd) != 0);
return fileList;
}
}
Packer::Packer(char *data, long l, int level) {
_data = NULL;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
if (deflateInit(&strm, level) != Z_OK) {
// eprint("error: deflateInit");
return;
}
strm.avail_in = l;
strm.next_in = (Bytef *)data;
_data = new char[l + 1024];
strm.avail_out = l + 1024;
strm.next_out = (Bytef *)_data;
auto r = deflate(&strm, Z_FINISH);
if (!(r == Z_OK || r == Z_STREAM_END)) {
// eprint("error: deflate");
}
_l = (l + 1024) - strm.avail_out;
deflateEnd(&strm);
}
Unpacker::Unpacker(char *dest, long destSize, char *src, long srcSize) {
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
auto ret = inflateInit(&strm);
strm.avail_in = srcSize;
strm.next_in = (Bytef *)src;
strm.avail_out = destSize;
strm.next_out = (Bytef *)dest;
ret = inflate(&strm, Z_NO_FLUSH);
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR;
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
// eprint("error: inflate");
return;
}
(void)inflateEnd(&strm);
}
| [
"[email protected]"
] | |
86983db20b6a63c206e961f090298b6abecd6444 | 7b2f11024f63e1a79054a7366e39198ae39efe86 | /limit_switch_testing/limit_switch_testing.ino | f74f7c2681fb234b35a77100bd38723667bc9ef2 | [] | no_license | apremalal/test-mirror | 2e126e32f7e5bf8af7b35b24b0542f53842a6b0b | caf7512caf61dd4abb88a29ec65e03ee27000d50 | refs/heads/master | 2016-08-04T21:32:04.272632 | 2014-03-05T02:37:19 | 2014-03-05T02:37:19 | 32,306,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | ino | #define LIMIT_SWITCH_X1_PIN 20 //int.3
#define LIMIT_SWITCH_X2_PIN 21 //int.2
#define LIMIT_SWITCH_Y1_PIN 18 //int.5
#define LIMIT_SWITCH_Y2_PIN 19 //int.4
volatile int reachedX1 = LOW, reachedX2 = LOW, reachedY1 = LOW, reachedY2 = LOW;
void setup() {
pinMode(13, OUTPUT);
attachInterrupt(2, stopX2, CHANGE );
attachInterrupt(3, stopX1, CHANGE);
attachInterrupt(4, stopY2, RISING );
attachInterrupt(5, stopY1, RISING );
Serial.begin(9600);
}
void loop()
{
}
void stopX1()
{
reachedX1 = !reachedX1;
Serial.println("X1 changed");
}
void stopX2(){
reachedX2 = !reachedX2;
Serial.println("X2 changed");
}
void stopY1(){
reachedY1 = !reachedY1;
Serial.println("Y1 changed");
}
void stopY2(){
reachedY2 = !reachedY2;
Serial.println("Y2 changed");
}
| [
"[email protected]"
] | |
f6e4ecbaa47d1cf7dcabdb1a9dabed0f38526da4 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_radioactiveLantern_FPV_RIG_AnimBlueprint_B_functions.cpp | 6ab2c3f358f91bc158740532aa64f3db4cc6308d | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,291 | cpp | // ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_radioactiveLantern_FPV_RIG_AnimBlueprint_B_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function radioactiveLantern_FPV_RIG_AnimBlueprint_B.radioactiveLantern_FPV_RIG_AnimBlueprint_B_C.ExecuteUbergraph_radioactiveLantern_FPV_RIG_AnimBlueprint_B
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UradioactiveLantern_FPV_RIG_AnimBlueprint_B_C::ExecuteUbergraph_radioactiveLantern_FPV_RIG_AnimBlueprint_B(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function radioactiveLantern_FPV_RIG_AnimBlueprint_B.radioactiveLantern_FPV_RIG_AnimBlueprint_B_C.ExecuteUbergraph_radioactiveLantern_FPV_RIG_AnimBlueprint_B");
UradioactiveLantern_FPV_RIG_AnimBlueprint_B_C_ExecuteUbergraph_radioactiveLantern_FPV_RIG_AnimBlueprint_B_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
ba09d3ac02e20037a4d75e495af3cd3699e57a43 | 619604cce5455f1048779cc3469dd25b17355f34 | /unit-test/test_loop_flatten.cpp | db5a73d9f41c8bf6232a6321108480dcd8408f05 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | zhongnanfang/ALADDIN | 566a7d58fb665cbd468e4daa51a38f3d916fc33c | 92b3bb6d18f2d40dc8a83017cc6b74d4309319a0 | refs/heads/master | 2021-07-05T00:59:32.170438 | 2017-09-14T04:35:41 | 2017-09-24T04:06:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | cpp | #include "catch.hpp"
#include "DDDG.h"
#include "file_func.h"
#include "Scratchpad.h"
#include "ScratchpadDatapath.h"
SCENARIO("Test loopFlatten w/ pp_scan", "[pp_scan]") {
GIVEN("Test pp_scan w/ Input Size 128, cyclic partition with a factor of 4, "
"loop unrolling with a factor of 4, enable loop pipelining") {
std::string bench("outputs/pp_scan-128");
std::string trace_file("inputs/pp_scan-128-trace.gz");
std::string config_file("inputs/config-pp_scan-p4-u4-P1");
ScratchpadDatapath* acc;
Scratchpad* spad;
acc = new ScratchpadDatapath(bench, trace_file, config_file);
acc->buildDddg();
acc->removeInductionDependence();
acc->removePhiNodes();
acc->initBaseAddress();
acc->scratchpadPartition();
WHEN("Test loopFlatten()") {
acc->loopFlatten();
THEN("Loop increments become LLVM_IR_Move.") {
REQUIRE(acc->getMicroop(16) == LLVM_IR_Move);
REQUIRE(acc->getMicroop(28) == LLVM_IR_Move);
REQUIRE(acc->getMicroop(40) == LLVM_IR_Move);
}
THEN("Branch nodes for flatten loops are isolated.") {
REQUIRE(acc->getNumOfConnectedNodes(18) == 0);
REQUIRE(acc->getNumOfConnectedNodes(30) == 0);
}
}
}
}
| [
"[email protected]"
] | |
f2cde32b964083e294b70b06a6095f1b9db2866b | a174d97f0f0ece7c65ba5b59ce019cf1e84fa89e | /Trees/IsBTBST.cpp | 1f9ea947eb57bda6dbea4fc9d6df26e09346427d | [] | no_license | kumari-jyoti/DataStructures-Algorithms | f34a3c51b256ae72c670459f97dce0aefb694bf7 | 5c42fe8bf4aea118cfbc1cf590bf65184b61a376 | refs/heads/master | 2021-01-10T23:54:54.911066 | 2016-10-17T05:14:44 | 2016-10-17T05:14:44 | 70,785,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,574 | cpp | //Checking if a given binary tree is BST or not
#include<iostream>
using namespace std;
//defining the tree node
struct node{
int data;
node* left;
node* right;
};
//creating new node
node* newNode(int k){
node* p=new node;
p->data=k;
p->left=NULL;
p->right=NULL;
return p;
}
//checking if node is a leaf or not
bool isleaf(node* p){
if(!p->left && !p->right) return true;
return false;
}
//find if the given BT is a BST or not
bool isBST(node* root,int min, int max){//min max defines the range for root
if(!root) return true;//if no root return true
if(isleaf(root)) return true;//if tree is a leaf return true
if(root->data<=max && root->data>=min){
if(isBST(root->left,min,root->data) && isBST(root->right,root->data,max)){//left subtree values should be less than root's value and right subtree values should be greater than root's value
if(!root->right && root->data>root->left->data) return true;//if only left subtree exists, compare just its value
if(!root->left && root->data<root->right->data) return true;//if only right subtree exists, compare just its value
if(root->data>root->left->data && root->data<root->right->data) return true;//else compare with both
}
}
return false;
}
//main function
int main()
{
//input tree
node* root=newNode(10);
root->left=newNode(0);
root->right=newNode(25);
root->left->left=newNode(1);
root->left->right=newNode(21);
root->right->left=newNode(16);
root->right->right=newNode(32);
//define range for the root
int min=-INT_MAX;
int max=INT_MAX;
cout<<isBST(root,min,max);
}
| [
"[email protected]"
] | |
b13d6e81c203a857a2e56a2617963bceca491719 | b1187def63927452c578ed54d864fdc8c7500aa3 | /src/constructs.cpp | 8f470261ed0e4957730ef5f307ae2f57441b937e | [
"MIT"
] | permissive | hkveeranki/Decaf-Compiler | 64fddf337c6d07343d8016cf44f1420257054e28 | 3e60009f9217640b6cd798c4f7b5834f03600bfb | refs/heads/master | 2023-04-29T14:51:16.457268 | 2023-04-17T00:10:57 | 2023-04-17T00:10:57 | 68,755,520 | 11 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,839 | cpp | /**
* Implementation of \ref Constructs class
*/
#include "constructs.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
/**
* Constructor for the class
* Initialises the fields
*/
Constructs::Constructs() {
this->Builder = new IRBuilder<>(Context);
this->loops = new std::stack<loopInfo*>();
errors = 0;
this->TheModule = new Module("Decaf compiler", Context);
this->TheFPM = new llvm::legacy::FunctionPassManager(TheModule);
TheFPM->add(createInstructionCombiningPass());
// Reassociate expressions.
TheFPM->add(createReassociatePass());
// Eliminate Common SubExpressions.
TheFPM->add(createGVNPass());
// Simplify the control flow graph (deleting unreachable blocks, etc).
TheFPM->add(createCFGSimplificationPass());
TheFPM->doInitialization();
}
/**
* Allocates memory for local variables on the stack of the function by creating an alloca instruction
* @param TheFunction Function whose local variable is to allocated memory
* @param VarName name of the variable
* @param type type of the variable
* @return alloca instruction for creating memory for given variable in the given function
*/
AllocaInst *Constructs::CreateEntryBlockAlloca(Function *TheFunction, std::string VarName, std::string type) {
/* Get the builder for current context */
IRBuilder<> TmpB(&TheFunction->getEntryBlock(), TheFunction->getEntryBlock().begin());
AllocaInst *alloca_instruction = nullptr;
if (type == "int") {
alloca_instruction = TmpB.CreateAlloca(Type::getInt32Ty(this->Context), 0, VarName);
} else if (type == "boolean") {
alloca_instruction = TmpB.CreateAlloca(Type::getInt1Ty(this->Context), 0, VarName);
}
return alloca_instruction;
}
| [
"[email protected]"
] | |
982690b8181698a72754164a482658a3893fffaf | 1924dbe6d5281d33094ac3e5496d50c88e5e52a7 | /HW-master/OOP/10-5.cpp | 035058cd4da6f9b959bcd710edc09a5184b97eda | [] | no_license | EeeUnS/study_and_HW | 78a8106cf4260d4475f26c4c215c1558c5c951f7 | ae07aa9598c4592202d940cc6c18c94859dad557 | refs/heads/master | 2020-09-08T19:19:55.687291 | 2020-01-01T16:24:51 | 2020-01-01T16:24:51 | 221,221,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | cpp | #include <iostream>
using namespace std;
template <typename T>
T Sum(T a, T b)
{
T c = a + b;
return c;
}
template <>
int Sum(int a, int b)
{
int c = a * b;
return c;
}
int Sum(double a, double b)
{
int c = a - b;
return c;
}
int main(void)
{
int x = Sum(3, 4);
double y = Sum(1.1, 2.2);
cout << x << endl;
cout << y << endl;
return 0;
} | [
"[email protected]"
] | |
4c4d5b6b96fa7b528c6db8a27c9d22e0a3d64589 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/old_hunk_3030.cpp | 7cb74cbf980c6b7ed2e3998391139a62366d6134 | [] | 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 | 1,196 | cpp | find_conflict(&conflict);
/*
* MERGE_RR records paths with conflicts immediately after merge
* failed. Some of the conflicted paths might have been hand resolved
* in the working tree since then, but the initial run would catch all
* and register their preimages.
*/
for (i = 0; i < conflict.nr; i++) {
const char *path = conflict.items[i].string;
if (!string_list_has_string(rr, path)) {
unsigned char sha1[20];
char *hex;
int ret;
ret = handle_file(path, sha1, NULL);
if (ret < 1)
continue;
hex = xstrdup(sha1_to_hex(sha1));
string_list_insert(rr, path)->util = hex;
if (mkdir_in_gitdir(git_path("rr-cache/%s", hex)))
continue;
handle_file(path, NULL, rerere_path(hex, "preimage"));
fprintf(stderr, "Recorded preimage for '%s'\n", path);
}
}
/*
* Now some of the paths that had conflicts earlier might have been
* hand resolved. Others may be similar to a conflict already that
* was resolved before.
*/
for (i = 0; i < rr->nr; i++) {
int ret;
const char *path = rr->items[i].string;
const char *name = (const char *)rr->items[i].util;
if (has_rerere_resolution(name)) {
if (merge(name, path))
continue;
| [
"[email protected]"
] | |
468d7f2a314f9bf393ef2a39aea8c7198784f560 | 39d6bc56a8b96f4359471e06804544fa6fc04d58 | /QuickSelect.cpp | 40da3a988cfd7779941b285b78a963ad3a7f9a3c | [] | no_license | powrLuis/Sort2 | aca5fe6c1bdd2f1b712a0605a49fd15dbbbb2d11 | ccd092a8ff85af488a1b1831e88855a258608bf2 | refs/heads/master | 2023-07-16T18:44:03.415131 | 2021-09-03T13:25:56 | 2021-09-03T13:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,112 | cpp | #include "QuickSelect.h"
int QuickSelect::partition(std::vector<int> &arr, int piv_index, bool ascendente)
{
int ultimo = arr.size() - 1;
int valor_pivot = arr[piv_index];
arr[piv_index] = arr[ultimo];
arr[ultimo] = valor_pivot;
int storeindex = 0;
if (ascendente)
{
for (size_t i = 0; i < ultimo; i++)
{
if (arr[i] < valor_pivot)
{
int temp = arr[storeindex];
arr[storeindex] = arr[i];
arr[i] = temp;
storeindex++;
}
}
}
else
{
for (size_t i = 0; i < ultimo; i++)
{
if (arr[i] > valor_pivot)
{
int temp = arr[storeindex];
arr[storeindex] = arr[i];
arr[i] = temp;
storeindex++;
}
}
}
int temp = arr[ultimo];
arr[ultimo] = arr[storeindex];
arr[storeindex] = temp;
return storeindex;
}
std::vector<int> QuickSelect::nlargest(int n, std::vector<int> array)
{
if (array.size() == 0)
{
return array;
}
if (array.size() == 1)
{
return array;
}
int pivot_index = array.size() / 2;
pivot_index = partition(array, pivot_index, false);
std::vector<int> v(array.begin(), array.begin() + pivot_index);
if (n == pivot_index)
{
return v;
}
else if (n < pivot_index)
{
return nlargest(n, v);
}
else
{
std::vector<int> v2(array.begin() + pivot_index, array.end());
v2 = nlargest(n - pivot_index, v2);
v.insert(v.end(), v2.begin(), v2.end());
return v;
}
return std::vector<int>();
}
std::vector<int> QuickSelect::nsmallest(int n, std::vector<int> array)
{
if (array.size() == 0)
{
return array;
}
if (array.size() == 1)
{
return array;
}
int pivot_index = array.size() / 2;
pivot_index = partition(array, pivot_index, true);
std::vector<int> v(array.begin(), array.begin() + pivot_index);
if (n == pivot_index)
{
return v;
}
else if (n < pivot_index)
{
return nsmallest(n, v);
}
else
{
std::vector<int> v2(array.begin() + pivot_index, array.end());
v2 = nsmallest(n - pivot_index, v2);
v.insert(v.end(), v2.begin(), v2.end());
return v;
}
return std::vector<int>();
}
int QuickSelect::topk_element(int n, std::vector<int> array)
{
if (array.size() == 0)
{
return -1;
}
if (array.size() == 1)
{
return array[0];
}
int pivot_index = array.size() / 2;
pivot_index = partition(array, pivot_index, false);
if (n == pivot_index)
{
return array[n];
}
else if (n < pivot_index)
{
std::vector<int> v(array.begin(), array.begin() + pivot_index);
return topk_element(n, v);
}
else
{
std::vector<int> v(array.begin() + pivot_index, array.end());
return topk_element(n - pivot_index, v);
}
return 0;
}
int QuickSelect::bottomk_element(int n, std::vector<int> array)
{
if (array.size()==0)
{
return -1;
}
if (array.size()==1)
{
return array[0];
}
int pivot_index = array.size() / 2;
pivot_index = partition(array, pivot_index,true);
if (n==pivot_index)
{
return array[n];
}
else if (n < pivot_index)
{
std::vector<int> v(array.begin(), array.begin() + pivot_index);
return bottomk_element(n, v);
}
else
{
std::vector<int> v(array.begin()+pivot_index, array.end());
return bottomk_element(n-pivot_index, v);
}
return 0;
}
| [
"LRona@POWERDESKTOP"
] | LRona@POWERDESKTOP |
387202c11310d31c1774f4bb51144d07b3b32d1c | e298b5c9d5db878b77b5297344ff6c383a59f193 | /src/cfg/YetiCfg.cpp | b8c75c95f8554a6290c2453833b700638f214a31 | [] | no_license | rabbani2611/sems-yeti | 3d4fc613db57bfa387fc355c46cea41e9fef0263 | 5ba676d204ac76bee0927f32f26b95aad6252af8 | refs/heads/master | 2023-01-23T06:00:30.034862 | 2020-11-26T19:47:50 | 2020-11-26T19:47:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,154 | cpp | #include "YetiCfg.h"
#include "sip/resolver.h"
#include "log.h"
#include "yeti_opts.h"
#include "cfg_helpers.h"
#define LOG_BUF_SIZE 2048
void cfg_reader_error(cfg_t *cfg, const char *fmt, va_list ap)
{
int l = 0;
char buf[LOG_BUF_SIZE];
if(cfg->title) {
//if(cfg->opts->flags & CFGF_TITLE) {
l = snprintf(buf,LOG_BUF_SIZE,"line:%d section '%s'(%s): ",
cfg->line,
cfg->name,
cfg->title);
} else {
l = snprintf(buf,LOG_BUF_SIZE,"line:%d section '%s': ",
cfg->line,
cfg->name);
}
l+= vsnprintf(buf+l,static_cast<size_t>(LOG_BUF_SIZE-l),fmt,ap);
ERROR("%.*s",l,buf);
}
aleg_cdr_headers_t cfg_aleg_cdr_headers;
int add_aleg_cdr_header(cfg_t *cfg, cfg_opt_t *opt, int argc, const char **argv)
{
if(argc != 2) {
ERROR("header(%s,%s): unexpected option args count.\n"
"expected format: header(header_name, string|array)",
argv[0],argv[1]);
return 1;
}
if(cfg_aleg_cdr_headers.add_header(argv[0],argv[1])) {
return 1;
}
return 0;
}
int YetiCfg::configure(const std::string& config_buf, AmConfigReader &am_cfg)
{
dns_handle dh;
cfg_t *cfg = nullptr;
cfg = cfg_init(yeti_opts, CFGF_NONE);
if(!cfg) {
ERROR("failed to init cfg opts");
return -1;
}
cfg_set_error_function(cfg,cfg_reader_error);
switch(cfg_parse_buf(cfg, config_buf.c_str())) {
case CFG_SUCCESS:
break;
case CFG_PARSE_ERROR:
ERROR("failed to parse Yeti configuration");
return -1;
default:
ERROR("unexpected error on Yeti configuring");
return -1;
}
core_options_handling = cfg_getbool(cfg, opt_name_core_options_handling);
pcap_memory_logger = cfg_getbool(cfg, opt_name_pcap_memory_logger);
auth_feedback = cfg_getbool(cfg, opt_name_auth_feedback);
http_events_destination = cfg_getstr(cfg, opt_name_http_events_destination);
aleg_cdr_headers = cfg_aleg_cdr_headers;
serialize_to_amconfig(cfg, am_cfg);
return 0;
}
void YetiCfg::serialize_to_amconfig(cfg_t *y, AmConfigReader &out)
{
cfg_t *c;
add2hash(y,"pop_id","pop_id",out);
add2hash(y,"msg_logger_dir","msg_logger_dir",out);
add2hash(y,"audio_recorder_dir","audio_recorder_dir",out);
add2hash(y,"audio_recorder_compress","audio_recorder_compress",out);
add2hash(y,"log_dir","log_dir",out);
//routing
cfg_t *r = cfg_getsec(y,"routing");
add2hash(r,"routing_schema","schema",out);
add2hash(r,"routing_function","function",out);
add2hash(r,"routing_init_function","init",out);
add2hash(r,"failover_to_slave","failover_to_slave",out);
//master pool
apply_pool_cfg(cfg_getsec(r,"master_pool"),"master_",out);
//slave pool
apply_pool_cfg(cfg_getsec(r,"slave_pool"),"slave_",out);
//cache
c = cfg_getsec(r,"cache");
add2hash(c,"profiles_cache_enabled","enabled",out);
add2hash(c,"profiles_cache_check_interval","check_interval",out);
add2hash(c,"profiles_cache_buckets","buckets",out);
//cdr
c = cfg_getsec(y,"cdr");
add2hash(c,"cdr_failover_to_slave","failover_to_slave",out);
add2hash(c,"failover_to_file","failover_to_file",out);
add2hash(c,"failover_requeue","failover_requeue",out);
add2hash(c,"serialize_dynamic_fields","serialize_dynamic_fields",out);
add2hash(c,"cdr_pool_size","pool_size",out);
add2hash(c,"cdr_dir","dir",out);
add2hash(c,"writecdr_schema","schema",out);
add2hash(c,"writecdr_function","function",out);
add2hash(c,"cdr_check_interval","check_interval",out);
add2hash(c,"cdr_batch_timeout","batch_timeout",out);
add2hash(c,"cdr_batch_size","batch_size",out);
//master
apply_db_cfg(cfg_getsec(c,"master"),"mastercdr_",out);
//slave
apply_db_cfg(cfg_getsec(c,"slave"),"slavecdr_",out);
//resources
c = cfg_getsec(y,"resources");
add2hash(c,"reject_on_cache_error","reject_on_error",out);
//write
apply_redis_pool_cfg(cfg_getsec(c,"write"),"write_redis_",out);
//read
apply_redis_pool_cfg(cfg_getsec(c,"read"),"read_redis_",out);
//registrations
c = cfg_getsec(y,"registrations");
add2hash(c,"reg_check_interval","check_interval",out);
//registrar
c = cfg_getsec(y,"registrar");
add2hash(c,"registrar_enabled","enabled",out);
add2hash(c,"registrar_expires_min","expires_min",out);
add2hash(c,"registrar_expires_max","expires_max",out);
c = cfg_getsec(c, "redis");
add2hash(c,"registrar_redis_host","host",out);
add2hash(c,"registrar_redis_port","port",out);
//rpc
c = cfg_getsec(y,"rpc");
add2hash(c,"calls_show_limit","calls_show_limit",out);
//statistics
c = cfg_getsec(y,"statistics");
c = cfg_getsec(c,"active-calls");
add2hash(c,"active_calls_period","period",out);
c = cfg_getsec(c,"clickhouse");
add2hash(c,"active_calls_clickhouse_table","table",out);
add2hash(c,"active_calls_clickhouse_queue","queue",out);
add2hash(c,"active_calls_clickhouse_buffering","buffering",out);
add2hash(c,"active_calls_clickhouse_allowed_fields","allowed_fields",out);
//auth
c = cfg_getsec(y,"auth");
add2hash(c,"auth_realm","realm",out);
}
| [
"[email protected]"
] | |
5d11c3c543ab1d0a64e6885055e9375f1f4b3954 | 48400e1adfc4a15c917b4fd5c041f8519c16aaad | /Source/TimFantastisk/Shield.cpp | a0ad9f8a6cc5620a23de83b2e7a6bdf7ea83c807 | [] | no_license | SnorreD/TimsEventyr | dc5e81173269ab91b5ce64960dbd794ac37bbf32 | 82d3a0a3d5cfa9f221e9b45a602d4b1ce7561e2a | refs/heads/master | 2020-04-13T17:43:50.145240 | 2017-05-24T12:46:00 | 2017-05-24T12:46:00 | 83,489,591 | 0 | 0 | null | null | null | null | ISO-8859-15 | C++ | false | false | 2,521 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "TimFantastisk.h"
#include "Shield.h"
#include "Bullet.h"
#include "Fiende.h"
#include "Tim.h"
AShield::AShield()
{
PrimaryActorTick.bCanEverTick = true;
RootCapsule = CreateDefaultSubobject<UBoxComponent>(TEXT("MyShield"));
RootComponent = RootCapsule;
RootCapsule->SetRelativeScale3D(FVector(0.5f, 1.5f, 1.5f));
RootCapsule->bGenerateOverlapEvents = true;
RootCapsule->OnComponentBeginOverlap.AddDynamic(this, &AShield::OnOverlap);
}
void AShield::BeginPlay()
{
Super::BeginPlay();
}
void AShield::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
//Skyoldet skal ikke kunne ta evig fort med skade, så det er en nedteller mellom hver gang den kan ta skade.
if (Cooldown == true)
{
CurrentCooldownTime += DeltaTime;
if (CurrentCooldownTime > TotalCooldownTime)
{
Cooldown = false;
CurrentCooldownTime = 0.f;
}
}
}
void AShield::OnOverlap(UPrimitiveComponent* OverlappedComponent, AActor *OtherActor,
UPrimitiveComponent *OtherComponent, int32 OtherBodyIndex,
bool bFromSweep, const FHitResult &SweepResult)
{
//Hvis en fiende treffer skjoldet tar det skade, hvis en kule treffer det tar det skade og reflekterer kulen tilbake. Skjoldets liv vil også bli sendt til en variabel hos spilleren.
if (OtherActor->IsA(AFiende::StaticClass()))
{
if (Cooldown == false)
{
Health = Health - 1.f;
ACharacter* myCharacter = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);
Cast<ATim>(myCharacter)->ShieldHealth = Health;
Cooldown = true;
}
}
//Hvis en kule treffer tauet blir det reflektert tilbake.
else if (OtherActor->IsA(ABullet::StaticClass()))
{
if (Cast<ABullet>(OtherActor)->EnemyBullet == true)
{
if (Cast<ABullet>(OtherActor)->StrongBullet == false)
{
Cast<ABullet>(OtherActor)->EnemyBullet = false;
if (Cast<ABullet>(OtherActor)->Speed > 0)
Cast<ABullet>(OtherActor)->Speed *= -1;
Health -= Cast<ABullet>(OtherActor)->Damage;
ACharacter* myCharacter = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);
Cast<ATim>(myCharacter)->ShieldHealth = Health;
}
//Men hvis kulen er sterk blir skjoldet og kulen ødelagt.
else if (Cast<ABullet>(OtherActor)->StrongBullet == true)
{
Health -= 100.f;
ACharacter* myCharacter = UGameplayStatics::GetPlayerCharacter(GetWorld(), 0);
Cast<ATim>(myCharacter)->ShieldHealth = Health;
OtherActor->Destroy();
}
}
}
if (Health <= 0.f)
{
Destroy();
}
}
| [
"[email protected]"
] | |
a542302da81e8137b22d9f3f30d2fd3a3833b2dd | 3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9 | /cpp/B/B/E/C/D/ABBECD.cpp | 0c6b2c39f24fef87407d5c3caa4e5c60970a760d | [] | no_license | devsisters/2021-NDC-ICECREAM | 7cd09fa2794cbab1ab4702362a37f6ab62638d9b | ac6548f443a75b86d9e9151ff9c1b17c792b2afd | refs/heads/master | 2023-03-19T06:29:03.216461 | 2021-03-10T02:53:14 | 2021-03-10T02:53:14 | 341,872,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 108 | cpp | #include "ABBECD.h"
namespace ABBECD {
std::string run() {
std::string out("ABBECD");
return out;
}
} | [
"[email protected]"
] | |
a7803b188a46d9b1e90a81fddd94389890281af5 | ffb568806e34199501c4ca6b61ac86ee9cc8de2e | /tool_project/SequenceEditor/old_lib/gflib/prog/include/ui/gfl_UI_Types.h | 5933eae354576663a3e43c820d35db2d2a6fcf3f | [] | no_license | Fumikage8/gen7-source | 433fb475695b2d5ffada25a45999f98419b75b6b | f2f572b8355d043beb468004f5e293b490747953 | refs/heads/main | 2023-01-06T00:00:14.171807 | 2020-10-20T18:49:53 | 2020-10-20T18:49:53 | 305,500,113 | 3 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,121 | h | //=============================================================================
/**
* @file gfl_UI_Types.h
* @brief UIシステムで使用する型
* @author obata_toshihiro
* @date 2010.11.08
*/
//=============================================================================
#ifndef __GFL_UI_TYPES_H__
#define __GFL_UI_TYPES_H__
#pragma once
#if GFL_DEBUG
#define GFL_UI_USE_DEBUG_PAD // 定義してあると, デバッグパッドが有効になる
#endif
// SBTS[631] 【ガイドライン】ジャイロセンサの使用の有無について
// GFL_UI_USE_GYROSCOPE定義状態では、 ジャイロセンサーの処理が動作しないようにする。
#ifdef GFL_UI_USE_GYROSCOPE
// GYROSCOPE有効時の処理
#else
// GYROSCOPE無効時の処理
#endif
namespace gfl {
namespace ui {
//-------------------------------------------------------------------------
/**
* @brief 方向キーの入力
*/
//-------------------------------------------------------------------------
enum {
DIR_LEFT = 1<<0,
DIR_RIGHT = 1<<1,
DIR_UP = 1<<2,
DIR_DOWN = 1<<3,
DIR_ALL = DIR_LEFT|DIR_RIGHT|DIR_UP|DIR_DOWN,
};
typedef u8 Direction;
//-------------------------------------------------------------------------
/**
* @brief ボタンID
*/
//-------------------------------------------------------------------------
enum ButtonID
{
BUTTONID_LEFT,
BUTTONID_RIGHT,
BUTTONID_UP,
BUTTONID_DOWN,
BUTTONID_A,
BUTTONID_B,
BUTTONID_X,
BUTTONID_Y,
BUTTONID_L,
BUTTONID_R,
BUTTONID_ZL,
BUTTONID_ZR,
BUTTONID_START,
BUTTONID_SELECT,
BUTTONID_HOME,
BUTTONID_PLUS,
BUTTONID_MINUS,
BUTTONID_INVALID, // 無効値
BUTTON_NUM, // 総数
};
//-------------------------------------------------------------------------
/**
* @brief ボタンの入力状態を表すビットフラグ
*/
//-------------------------------------------------------------------------
enum {
BUTTON_LEFT = 1<<BUTTONID_LEFT,
BUTTON_RIGHT = 1<<BUTTONID_RIGHT,
BUTTON_UP = 1<<BUTTONID_UP,
BUTTON_DOWN = 1<<BUTTONID_DOWN,
BUTTON_A = 1<<BUTTONID_A,
BUTTON_B = 1<<BUTTONID_B,
BUTTON_X = 1<<BUTTONID_X,
BUTTON_Y = 1<<BUTTONID_Y,
BUTTON_L = 1<<BUTTONID_L,
BUTTON_R = 1<<BUTTONID_R,
BUTTON_ZL = 1<<BUTTONID_ZL,
BUTTON_ZR = 1<<BUTTONID_ZR,
BUTTON_START = 1<<BUTTONID_START,
BUTTON_SELECT = 1<<BUTTONID_SELECT,
BUTTON_HOME = 1<<BUTTONID_HOME,
BUTTON_PLUS = 1<<BUTTONID_PLUS,
BUTTON_MINUS = 1<<BUTTONID_MINUS,
BUTTON_INVALID = 1<<BUTTONID_INVALID,
BUTTON_CROSS = BUTTON_LEFT|BUTTON_RIGHT|BUTTON_UP|BUTTON_DOWN,
};
} //namespace ui
} //namespace gfl
#endif // __GFL_UI_TYPES_H__
| [
"[email protected]"
] | |
4f37bc4a2cb4a2889fe856030a3438a65b21180d | 1413e50f1de3c65cd8c2d19af9676a8d896308bd | /src/Token.h | 6c4ce42dd7bf16d56879c77105ca897993914747 | [] | no_license | JulianHinxlage/compiler | fdda6465ba2a635190b35a5b4e27432e08045b27 | 9e3598e88f5da2d692b3521c6a8e7f9436eb2574 | refs/heads/master | 2022-03-31T17:09:43.388646 | 2020-01-13T17:41:05 | 2020-01-13T17:41:05 | 232,810,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | h | //
// Copyright (c) 2020 Julian Hinxlage. All rights reserved.
//
#ifndef COMPILER_TOKEN_H
#define COMPILER_TOKEN_H
#include <string>
class Token {
public:
std::string type;
std::string value;
int file;
int line;
int column;
Token();
Token(const std::string &type, const std::string &value);
Token(const std::string &type, const std::string &value, int line, int column);
};
#endif //COMPILER_TOKEN_H
| [
"[email protected]"
] | |
cfb44de2a9c9a0e9a24ffc578645d99bbcf62bda | 45403c776ffaa960e03150b42ab9912c0ef8bed7 | /build/ui_signverifymessagedialog.h | 6001b0aa1a725d68408b6c859059afd24147b903 | [
"MIT"
] | permissive | insaneinthemembrane/AtcCoin | eaea732c41117d8f4f0eb3a9d79546c2f6d24df6 | 86b53c14002605955a2293b10f33f37cccaa7527 | refs/heads/master | 2020-03-19T05:26:32.083233 | 2018-06-03T19:29:50 | 2018-06-03T19:29:50 | 135,931,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,120 | h | /********************************************************************************
** Form generated from reading UI file 'signverifymessagedialog.ui'
**
** Created by: Qt User Interface Compiler version 4.8.6
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_SIGNVERIFYMESSAGEDIALOG_H
#define UI_SIGNVERIFYMESSAGEDIALOG_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QPushButton>
#include <QtGui/QSpacerItem>
#include <QtGui/QTabWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>
#include "qvalidatedlineedit.h"
QT_BEGIN_NAMESPACE
class Ui_SignVerifyMessageDialog
{
public:
QVBoxLayout *verticalLayout;
QTabWidget *tabWidget;
QWidget *tabSignMessage;
QVBoxLayout *verticalLayout_SM;
QLabel *infoLabel_SM;
QHBoxLayout *horizontalLayout_1_SM;
QValidatedLineEdit *addressIn_SM;
QPushButton *addressBookButton_SM;
QPushButton *pasteButton_SM;
QPlainTextEdit *messageIn_SM;
QLabel *signatureLabel_SM;
QHBoxLayout *horizontalLayout_2_SM;
QLineEdit *signatureOut_SM;
QPushButton *copySignatureButton_SM;
QHBoxLayout *horizontalLayout_3_SM;
QPushButton *signMessageButton_SM;
QPushButton *clearButton_SM;
QSpacerItem *horizontalSpacer_1_SM;
QLabel *statusLabel_SM;
QSpacerItem *horizontalSpacer_2_SM;
QWidget *tabVerifyMessage;
QVBoxLayout *verticalLayout_VM;
QLabel *infoLabel_VM;
QHBoxLayout *horizontalLayout_1_VM;
QValidatedLineEdit *addressIn_VM;
QPushButton *addressBookButton_VM;
QPlainTextEdit *messageIn_VM;
QValidatedLineEdit *signatureIn_VM;
QHBoxLayout *horizontalLayout_2_VM;
QPushButton *verifyMessageButton_VM;
QPushButton *clearButton_VM;
QSpacerItem *horizontalSpacer_1_VM;
QLabel *statusLabel_VM;
QSpacerItem *horizontalSpacer_2_VM;
void setupUi(QDialog *SignVerifyMessageDialog)
{
if (SignVerifyMessageDialog->objectName().isEmpty())
SignVerifyMessageDialog->setObjectName(QString::fromUtf8("SignVerifyMessageDialog"));
SignVerifyMessageDialog->resize(700, 380);
SignVerifyMessageDialog->setModal(true);
verticalLayout = new QVBoxLayout(SignVerifyMessageDialog);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
tabWidget = new QTabWidget(SignVerifyMessageDialog);
tabWidget->setObjectName(QString::fromUtf8("tabWidget"));
tabSignMessage = new QWidget();
tabSignMessage->setObjectName(QString::fromUtf8("tabSignMessage"));
verticalLayout_SM = new QVBoxLayout(tabSignMessage);
verticalLayout_SM->setObjectName(QString::fromUtf8("verticalLayout_SM"));
infoLabel_SM = new QLabel(tabSignMessage);
infoLabel_SM->setObjectName(QString::fromUtf8("infoLabel_SM"));
infoLabel_SM->setTextFormat(Qt::PlainText);
infoLabel_SM->setWordWrap(true);
verticalLayout_SM->addWidget(infoLabel_SM);
horizontalLayout_1_SM = new QHBoxLayout();
horizontalLayout_1_SM->setSpacing(0);
horizontalLayout_1_SM->setObjectName(QString::fromUtf8("horizontalLayout_1_SM"));
addressIn_SM = new QValidatedLineEdit(tabSignMessage);
addressIn_SM->setObjectName(QString::fromUtf8("addressIn_SM"));
addressIn_SM->setMaxLength(34);
horizontalLayout_1_SM->addWidget(addressIn_SM);
addressBookButton_SM = new QPushButton(tabSignMessage);
addressBookButton_SM->setObjectName(QString::fromUtf8("addressBookButton_SM"));
QIcon icon;
icon.addFile(QString::fromUtf8(":/icons/address-book"), QSize(), QIcon::Normal, QIcon::Off);
addressBookButton_SM->setIcon(icon);
addressBookButton_SM->setAutoDefault(false);
horizontalLayout_1_SM->addWidget(addressBookButton_SM);
pasteButton_SM = new QPushButton(tabSignMessage);
pasteButton_SM->setObjectName(QString::fromUtf8("pasteButton_SM"));
QIcon icon1;
icon1.addFile(QString::fromUtf8(":/icons/editpaste"), QSize(), QIcon::Normal, QIcon::Off);
pasteButton_SM->setIcon(icon1);
pasteButton_SM->setAutoDefault(false);
horizontalLayout_1_SM->addWidget(pasteButton_SM);
verticalLayout_SM->addLayout(horizontalLayout_1_SM);
messageIn_SM = new QPlainTextEdit(tabSignMessage);
messageIn_SM->setObjectName(QString::fromUtf8("messageIn_SM"));
verticalLayout_SM->addWidget(messageIn_SM);
signatureLabel_SM = new QLabel(tabSignMessage);
signatureLabel_SM->setObjectName(QString::fromUtf8("signatureLabel_SM"));
signatureLabel_SM->setTextFormat(Qt::PlainText);
verticalLayout_SM->addWidget(signatureLabel_SM);
horizontalLayout_2_SM = new QHBoxLayout();
horizontalLayout_2_SM->setSpacing(0);
horizontalLayout_2_SM->setObjectName(QString::fromUtf8("horizontalLayout_2_SM"));
signatureOut_SM = new QLineEdit(tabSignMessage);
signatureOut_SM->setObjectName(QString::fromUtf8("signatureOut_SM"));
QFont font;
font.setItalic(true);
signatureOut_SM->setFont(font);
signatureOut_SM->setReadOnly(true);
horizontalLayout_2_SM->addWidget(signatureOut_SM);
copySignatureButton_SM = new QPushButton(tabSignMessage);
copySignatureButton_SM->setObjectName(QString::fromUtf8("copySignatureButton_SM"));
QIcon icon2;
icon2.addFile(QString::fromUtf8(":/icons/editcopy"), QSize(), QIcon::Normal, QIcon::Off);
copySignatureButton_SM->setIcon(icon2);
copySignatureButton_SM->setAutoDefault(false);
horizontalLayout_2_SM->addWidget(copySignatureButton_SM);
verticalLayout_SM->addLayout(horizontalLayout_2_SM);
horizontalLayout_3_SM = new QHBoxLayout();
horizontalLayout_3_SM->setObjectName(QString::fromUtf8("horizontalLayout_3_SM"));
signMessageButton_SM = new QPushButton(tabSignMessage);
signMessageButton_SM->setObjectName(QString::fromUtf8("signMessageButton_SM"));
QIcon icon3;
icon3.addFile(QString::fromUtf8(":/icons/edit"), QSize(), QIcon::Normal, QIcon::Off);
signMessageButton_SM->setIcon(icon3);
signMessageButton_SM->setAutoDefault(false);
horizontalLayout_3_SM->addWidget(signMessageButton_SM);
clearButton_SM = new QPushButton(tabSignMessage);
clearButton_SM->setObjectName(QString::fromUtf8("clearButton_SM"));
QIcon icon4;
icon4.addFile(QString::fromUtf8(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off);
clearButton_SM->setIcon(icon4);
clearButton_SM->setAutoDefault(false);
horizontalLayout_3_SM->addWidget(clearButton_SM);
horizontalSpacer_1_SM = new QSpacerItem(40, 48, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3_SM->addItem(horizontalSpacer_1_SM);
statusLabel_SM = new QLabel(tabSignMessage);
statusLabel_SM->setObjectName(QString::fromUtf8("statusLabel_SM"));
QFont font1;
font1.setBold(true);
font1.setWeight(75);
statusLabel_SM->setFont(font1);
statusLabel_SM->setWordWrap(true);
horizontalLayout_3_SM->addWidget(statusLabel_SM);
horizontalSpacer_2_SM = new QSpacerItem(40, 48, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3_SM->addItem(horizontalSpacer_2_SM);
verticalLayout_SM->addLayout(horizontalLayout_3_SM);
tabWidget->addTab(tabSignMessage, QString());
tabVerifyMessage = new QWidget();
tabVerifyMessage->setObjectName(QString::fromUtf8("tabVerifyMessage"));
verticalLayout_VM = new QVBoxLayout(tabVerifyMessage);
verticalLayout_VM->setObjectName(QString::fromUtf8("verticalLayout_VM"));
infoLabel_VM = new QLabel(tabVerifyMessage);
infoLabel_VM->setObjectName(QString::fromUtf8("infoLabel_VM"));
infoLabel_VM->setTextFormat(Qt::PlainText);
infoLabel_VM->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);
infoLabel_VM->setWordWrap(true);
verticalLayout_VM->addWidget(infoLabel_VM);
horizontalLayout_1_VM = new QHBoxLayout();
horizontalLayout_1_VM->setSpacing(0);
horizontalLayout_1_VM->setObjectName(QString::fromUtf8("horizontalLayout_1_VM"));
addressIn_VM = new QValidatedLineEdit(tabVerifyMessage);
addressIn_VM->setObjectName(QString::fromUtf8("addressIn_VM"));
addressIn_VM->setMaxLength(34);
horizontalLayout_1_VM->addWidget(addressIn_VM);
addressBookButton_VM = new QPushButton(tabVerifyMessage);
addressBookButton_VM->setObjectName(QString::fromUtf8("addressBookButton_VM"));
addressBookButton_VM->setIcon(icon);
addressBookButton_VM->setAutoDefault(false);
horizontalLayout_1_VM->addWidget(addressBookButton_VM);
verticalLayout_VM->addLayout(horizontalLayout_1_VM);
messageIn_VM = new QPlainTextEdit(tabVerifyMessage);
messageIn_VM->setObjectName(QString::fromUtf8("messageIn_VM"));
verticalLayout_VM->addWidget(messageIn_VM);
signatureIn_VM = new QValidatedLineEdit(tabVerifyMessage);
signatureIn_VM->setObjectName(QString::fromUtf8("signatureIn_VM"));
verticalLayout_VM->addWidget(signatureIn_VM);
horizontalLayout_2_VM = new QHBoxLayout();
horizontalLayout_2_VM->setObjectName(QString::fromUtf8("horizontalLayout_2_VM"));
verifyMessageButton_VM = new QPushButton(tabVerifyMessage);
verifyMessageButton_VM->setObjectName(QString::fromUtf8("verifyMessageButton_VM"));
QIcon icon5;
icon5.addFile(QString::fromUtf8(":/icons/transaction_0"), QSize(), QIcon::Normal, QIcon::Off);
verifyMessageButton_VM->setIcon(icon5);
verifyMessageButton_VM->setAutoDefault(false);
horizontalLayout_2_VM->addWidget(verifyMessageButton_VM);
clearButton_VM = new QPushButton(tabVerifyMessage);
clearButton_VM->setObjectName(QString::fromUtf8("clearButton_VM"));
clearButton_VM->setIcon(icon4);
clearButton_VM->setAutoDefault(false);
horizontalLayout_2_VM->addWidget(clearButton_VM);
horizontalSpacer_1_VM = new QSpacerItem(40, 48, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2_VM->addItem(horizontalSpacer_1_VM);
statusLabel_VM = new QLabel(tabVerifyMessage);
statusLabel_VM->setObjectName(QString::fromUtf8("statusLabel_VM"));
statusLabel_VM->setFont(font1);
statusLabel_VM->setWordWrap(true);
horizontalLayout_2_VM->addWidget(statusLabel_VM);
horizontalSpacer_2_VM = new QSpacerItem(40, 48, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2_VM->addItem(horizontalSpacer_2_VM);
verticalLayout_VM->addLayout(horizontalLayout_2_VM);
tabWidget->addTab(tabVerifyMessage, QString());
verticalLayout->addWidget(tabWidget);
retranslateUi(SignVerifyMessageDialog);
tabWidget->setCurrentIndex(0);
QMetaObject::connectSlotsByName(SignVerifyMessageDialog);
} // setupUi
void retranslateUi(QDialog *SignVerifyMessageDialog)
{
SignVerifyMessageDialog->setWindowTitle(QApplication::translate("SignVerifyMessageDialog", "Signatures - Sign / Verify a Message", 0, QApplication::UnicodeUTF8));
infoLabel_SM->setText(QApplication::translate("SignVerifyMessageDialog", "You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
addressIn_SM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "The address to sign the message with (e.g. Cer4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
addressBookButton_SM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Choose an address from the address book", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
addressBookButton_SM->setText(QString());
addressBookButton_SM->setShortcut(QApplication::translate("SignVerifyMessageDialog", "Alt+A", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
pasteButton_SM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Paste address from clipboard", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
pasteButton_SM->setText(QString());
pasteButton_SM->setShortcut(QApplication::translate("SignVerifyMessageDialog", "Alt+P", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
messageIn_SM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Enter the message you want to sign here", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
signatureLabel_SM->setText(QApplication::translate("SignVerifyMessageDialog", "Signature", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
copySignatureButton_SM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Copy the current signature to the system clipboard", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
copySignatureButton_SM->setText(QString());
#ifndef QT_NO_TOOLTIP
signMessageButton_SM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Sign the message to prove you own this AtcCoin address", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
signMessageButton_SM->setText(QApplication::translate("SignVerifyMessageDialog", "Sign &Message", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
clearButton_SM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Reset all sign message fields", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
clearButton_SM->setText(QApplication::translate("SignVerifyMessageDialog", "Clear &All", 0, QApplication::UnicodeUTF8));
statusLabel_SM->setText(QString());
tabWidget->setTabText(tabWidget->indexOf(tabSignMessage), QApplication::translate("SignVerifyMessageDialog", "&Sign Message", 0, QApplication::UnicodeUTF8));
infoLabel_VM->setText(QApplication::translate("SignVerifyMessageDialog", "Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
addressIn_VM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "The address the message was signed with (e.g. Ber4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
addressBookButton_VM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Choose an address from the address book", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
addressBookButton_VM->setText(QString());
addressBookButton_VM->setShortcut(QApplication::translate("SignVerifyMessageDialog", "Alt+A", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
verifyMessageButton_VM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Verify the message to ensure it was signed with the specified AtcCoin address", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
verifyMessageButton_VM->setText(QApplication::translate("SignVerifyMessageDialog", "Verify &Message", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
clearButton_VM->setToolTip(QApplication::translate("SignVerifyMessageDialog", "Reset all verify message fields", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
clearButton_VM->setText(QApplication::translate("SignVerifyMessageDialog", "Clear &All", 0, QApplication::UnicodeUTF8));
statusLabel_VM->setText(QString());
tabWidget->setTabText(tabWidget->indexOf(tabVerifyMessage), QApplication::translate("SignVerifyMessageDialog", "&Verify Message", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class SignVerifyMessageDialog: public Ui_SignVerifyMessageDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_SIGNVERIFYMESSAGEDIALOG_H
| [
"[email protected]"
] | |
545e5d59ec222862e2beca49e94ebf56ea97de5d | 383513e0f782735e4ffb3e94b214172e3280363a | /ABC/100/A.cpp | 19d92f15f566eab6e278cab89d836d7ff49040b7 | [] | no_license | face4/AtCoder | e07c123a604f56901b186c41aa318c93b115d8d1 | 9c81387cb0ee7f669b50d5cc591e05c87670ee36 | refs/heads/master | 2021-06-27T01:07:33.806176 | 2020-11-20T03:47:25 | 2020-11-20T03:47:25 | 137,498,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | cpp | #include<iostream>
using namespace std;
int main(){
int a, b;
cin >> a >> b;
if(a > 8 || b > 8){
cout << ":(" << endl;
}else{
cout << "Yay!" << endl;
}
return 0;
} | [
"[email protected]"
] | |
46ab80276e0a7f804ebd5c0d9de04677864a52fb | c6769a12358e53c52fddfdcacb78344d446b1771 | /CastorTree/Analyzer/Run.cc | 25dd938285dbb973e86939dbfe2b4baa28d59dcc | [] | no_license | xueweiphy/UACastor | d8717970b9843adc79513b51ea4c8294d89e40f3 | 91893bfb195ecd980b2afaf28e3fa045bca35745 | refs/heads/master | 2020-12-25T21:13:41.178545 | 2012-11-06T09:57:22 | 2012-11-06T09:57:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,047 | cc | #include <TROOT.h>
#include <TTree.h>
#include <TFile.h>
#include <iostream>
#include <stdio.h>
#include <cstring>
#include "MainAnalyzer.h"
int main(int argc, char *argv[]) {
using namespace std;
printf("argc = %d\n", argc);
for (int i = 0; i<argc; i++){
static int k = 0;
printf("argv[%d] = %s\n", k, argv[k]);
k++;
}
if(argc < 4) {
cout<<"example usage: "<<"./Run \"type\" \"energy\" \"analysis\" "<<endl;
cout<<"type: data - PYTHIA6Z2 - PYTHIA84C - HERWIGpp24"<<endl;
cout<<"energy: 900 - 2760 - 7000"<<endl;
cout<<"analysis: ana - eflow - eflowsubsample - geometry - shower - profile - calib - modulation - trigger - triggersubsample - threshold - signalcut - cuthadronlevel"<<endl;
return(0);
}
TString type = TString(argv[1]);
TString energy = TString(argv[2]);
TString analysis = TString(argv[3]);
bool ana = false;
bool eflow = false;
bool eflowsubsample = false;
bool geometry = false;
bool shower = false;
bool profile = false;
bool calib = false;
bool modulation = false;
bool trigger = false;
bool triggersubsample = false;
bool threshold = false;
bool signalcut = false;
bool cuthadronlevel = false;
if(strcmp(analysis,"ana") == 0) ana = true;
if(strcmp(analysis,"eflow") == 0) eflow = true;
if(strcmp(analysis,"eflowsubsample") == 0) eflowsubsample = true;
if(strcmp(analysis,"geometry") == 0) geometry = true;
if(strcmp(analysis,"shower") == 0) shower = true;
if(strcmp(analysis,"profile") == 0) profile = true;
if(strcmp(analysis,"calib") == 0) calib = true;
if(strcmp(analysis,"modulation") == 0) modulation = true;
if(strcmp(analysis,"trigger") == 0) trigger = true;
if(strcmp(analysis,"triggersubsample") == 0) triggersubsample = true;
if(strcmp(analysis,"threshold") == 0) threshold = true;
if(strcmp(analysis,"signalcut") == 0) signalcut = true;
if(strcmp(analysis,"cuthadronlevel") == 0) cuthadronlevel = true;
TString storagehome_hans = "dcap://maite.iihe.ac.be/pnfs/iihe/cms/store/user/hvanhaev/";
TString storagehome_ben = "dcap://maite.iihe.ac.be/pnfs/iihe/cms/store/user/roland/";
TString dir_ben = "/user/roland/EflowAnalysis/CMSSW_4_2_7/src/UACastor/CastorTree/Result/";
MainAnalyzer* m = new MainAnalyzer();
if (strcmp(type,"data") == 0) {
//-- 900 GeV data
TString subdir_data_MB_900 = "MinimumBias/CastorTree_data_MinBias_Commissioning10-07JunReReco_900GeV_RECOwithCorrector_v7/73f71e7897ec23c1b2bf056fb952105f/";
TString dir_data_MB_900 = storagehome_hans + subdir_data_MB_900;
TString subdir_data_ZB_900 = "ZeroBias/CastorTree_data_ZeroBias_Commissioning10-May19ReReco-v1_900GeV_RECOwithCorrector_v4/995e07837d460c2a00f3dfbda1d76e33/";
TString dir_data_ZB_900 = storagehome_hans + subdir_data_ZB_900;
TString dir_triggersubsample_900 = dir_ben + TString("TriggerSubsample/900GeV/");
TString dir_eflowsubsample_data_900 = storagehome_ben + TString("EflowSubsample/900GeV/data/");
if (strcmp(energy,"900") == 0) {
cout<<"We'll process the 900 GeV data tree now"<<endl;
if(ana) m->makeHistos(dir_data_MB_900,"CastorTree_data_MinBias_Commissioning10-07JunReReco_900GeV_RECOwithCorrector_",true,900);
if(profile) m->makeHistoProfile(dir_data_MB_900,"CastorTree_data_MinBias_Commissioning10-07JunReReco_900GeV_RECOwithCorrector",true,900);
if(calib) m->makeHistoCalib(dir_data_MB_900,"CastorTree_data_MinBias_Commissioning10-07JunReReco_900GeV_RECOwithCorrector_",900);
if(signalcut) m->makeHistoSignalCut(dir_data_MB_900,"CastorTree_data_MinBias_Commissioning10-07JunReReco_900GeV_RECOwithCorrector",true,900);
if(eflow) m->makeHistoEflow(dir_data_MB_900,"CastorTree_data_MinBias_Commissioning10-07JunReReco_900GeV_RECOwithCorrector",type,900,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_data_900,"CastorTree_eflow_subsample",type,900,false);
//-- if(geometry) m->makeHistoGeometry(dir_eflowsubsample_data_900,"CastorTree_eflow_subsample",type,900);
if(geometry) m->makeHistoGeometry(dir_data_MB_900,"CastorTree_data_MinBias_Commissioning10-07JunReReco_900GeV_RECOwithCorrector",type,900);
//-- ZeroBias data
if(trigger) m->makeHistoTrigger(dir_data_ZB_900,"CastorTree_data_ZeroBias_Commissioning10-May19ReReco-v1_900GeV_RECOwithCorrector",true,900,0);
if(triggersubsample) m->makeHistoTrigger(dir_triggersubsample_900,"trigger.subsample.900GeV",true,900,1);
if(threshold) m->makeHistoThreshold(dir_data_ZB_900,"CastorTree_data_ZeroBias_Commissioning10-May19ReReco-v1_900GeV_RECOwithCorrector_",true,900);
}
//-- data 2760 GeV
TString subdir_data_AllPhysics_2760 = "AllPhysics2760/CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector_v9/55561db7062b943bceb45be69d97b57a/";
TString dir_data_AllPhysics_2760 = storagehome_hans + subdir_data_AllPhysics_2760;
TString dir_triggersubsample_2760 = dir_ben + TString("TriggerSubsample/2760GeV/");
TString dir_eflowsubsample_data_2760 = storagehome_ben + TString("EflowSubsample/2760GeV/data/");
if (strcmp(energy,"2760") == 0) {
cout<<"We'll process the 2760 GeV data tree now"<<endl;
//-- allphysics tree (includes ZeroBias data)
if(ana) m->makeHistos(dir_data_AllPhysics_2760,"CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector_1",true,2760);
if(profile) m->makeHistoProfile(dir_data_AllPhysics_2760,"CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector_1",true,2760);
if(calib) m->makeHistoCalib(dir_data_AllPhysics_2760,"CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector_1",2760);
if(signalcut) m->makeHistoSignalCut(dir_data_AllPhysics_2760,"CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector_1",true,2760);
if(eflow) m->makeHistoEflow(dir_data_AllPhysics_2760,"CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector_1",type,2760,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_data_2760,"CastorTree_eflow_subsample",type,2760,false);
//-- if(geometry) m->makeHistoGeometry(dir_eflowsubsample_data_2760,"CastorTree_eflow_subsample",type,2760);
if(geometry) m->makeHistoGeometry(dir_data_AllPhysics_2760,"CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector_1",type,2760);
if(trigger) m->makeHistoTrigger(dir_data_AllPhysics_2760,"CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector",true,2760,0);
if(triggersubsample) m->makeHistoTrigger(dir_triggersubsample_2760,"trigger.subsample.2760GeV",true,2760,1);
if(threshold) m->makeHistoThreshold(dir_data_AllPhysics_2760,"CastorTree_data_AllPhysics2760_Run2011A-16Jul2011-v1_2760GeV_RECOwithCorrector_1",true,2760);
}
//-- data 7000 GeV
TString subdir_data_MB_7000 = "MinimumBias/CastorTree_data_MinBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector_v6/311aeaa893378600647aa0fa9675a48e/";
TString dir_data_MB_7000 = storagehome_hans + subdir_data_MB_7000;
TString subdir_data_ZB_7000 = "ZeroBias/CastorTree_data_ZeroBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector_v4/d5cc4c077bc0d1021fcb3b9f8cab4c07/";
TString dir_data_ZB_7000 = storagehome_hans + subdir_data_ZB_7000;
TString dir_triggersubsample_7000 = dir_ben + TString("TriggerSubsample/7TeV/");
TString dir_eflowsubsample_data_7000 = storagehome_ben + TString("EflowSubsample/7TeV/data/");
if (strcmp(energy,"7000") == 0) {
cout<<"We'll process the 7 TeV data tree now"<<endl;
//-- Minimum Bias data
if(ana) m->makeHistos(dir_data_MB_7000,"CastorTree_data_MinBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector",true,7000);
if(profile) m->makeHistoProfile(dir_data_MB_7000,"CastorTree_data_MinBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector",true,7000);
if(calib) m->makeHistoCalib(dir_data_MB_7000,"CastorTree_data_MinBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector",7000);
if(signalcut) m->makeHistoSignalCut(dir_data_MB_7000,"CastorTree_data_MinBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector_1",true,7000);
if(eflow) m->makeHistoEflow(dir_data_MB_7000,"CastorTree_data_MinBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector",type,7000,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_data_7000,"CastorTree_eflow_subsample",type,7000,false);
//-- if(geometry) m->makeHistoGeometry(dir_eflowsubsample_data_7000,"CastorTree_eflow_subsample",type,7000);
if(geometry) m->makeHistoGeometry(dir_data_MB_7000,"CastorTree_data_MinBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector",type,7000);
//-- Zero Bias data
if(trigger) m->makeHistoTrigger(dir_data_ZB_7000,"CastorTree_data_ZeroBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector",true,7000,0);
if(triggersubsample) m->makeHistoTrigger(dir_triggersubsample_7000,"trigger.subsample.7TeV",true,7000,1);
if(threshold) m->makeHistoThreshold(dir_data_ZB_7000,"CastorTree_data_ZeroBias_Commissioning10-May19ReReco-v1_7TeV_RECOwithCorrector",true,7000);
}
}
if (strcmp(type,"PYTHIA6Z2")==0) {
//-- moca 900 GeV
TString subdir_MC_900 = "MinBias_TuneZ2_900GeV_pythia6_cff_py_GEN_SIM_START311_V2_Dec11_v2/CastorTree_MC_MinBias_TuneZ2_900GeV_pythia6_cff_py_Step3_START42_V11_Dec11_v3/ab9a53788d13cfa8c855cda83f795fbe/";
TString dir_MC_900 = storagehome_hans + subdir_MC_900;
TString dir_eflowsubsample_MC_900 = storagehome_ben + TString("EflowSubsample/900GeV/PYTHIA6Z2/");
if (strcmp(energy,"900")==0) {
cout<<"We'll process the 900 GeV MC tree now"<<endl;
if(ana) m->makeHistos(dir_MC_900,"CastorTree_MC_900GeV_42X",false,900);
if(profile) m->makeHistoProfile(dir_MC_900,"CastorTree_MC_900GeV_42X",false,900);
if(trigger) m->makeHistoTrigger(dir_MC_900,"CastorTree_MC_900GeV_42X",false,900,0);
if(threshold) m->makeHistoThreshold(dir_MC_900,"CastorTree_MC_900GeV_42X",false,900);
if(cuthadronlevel) m->makeHistoCutHadronLevel(dir_MC_900,"CastorTree_MC_900GeV_42X_1",900);
if(eflow) m->makeHistoEflow(dir_MC_900,"CastorTree_MC_900GeV_42X",type,900,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_900,"CastorTree_eflow_subsample",type,900,false);
//-- if(geometry) m->makeHistoGeometry(dir_eflowsubsample_MC_900,"CastorTree_eflow_subsample",type,900);
if(geometry) m->makeHistoGeometry(dir_MC_900,"CastorTree_MC_900GeV_42X",type,900);
if(shower) m->makeHistoShower(dir_MC_900,"CastorTree_MC_900GeV_42X",type,900);
}
//-- moca 2760 GeV
TString subdir_MC_2760 = "MinBias_TuneZ2_2760GeV_pythia6_cff_py_GEN_SIM_START311_V2_Dec11_v2/CastorTree_MC_MinBias_TuneZ2_2760GeV_pythia6_cff_py_Step3_START42_V11_Dec11_v2/95b3059532ea3303b5c4c023bcc2a5dd/";
TString dir_MC_2760 = storagehome_hans + subdir_MC_2760;
TString dir_eflowsubsample_MC_2760 = storagehome_ben + TString("EflowSubsample/2760GeV/PYTHIA6Z2/");
if (strcmp(energy,"2760")==0) {
cout<<"We'll process the 2760 GeV MC tree now"<<endl;
if(ana) m->makeHistos(dir_MC_2760,"CastorTree_MC_2760GeV_42X",false,2760);
if(profile) m->makeHistoProfile(dir_MC_2760,"CastorTree_MC_2760GeV_42X",false,2760);
if(trigger) m->makeHistoTrigger(dir_MC_2760,"CastorTree_MC_2760GeV_42X",false,2760,0);
if(cuthadronlevel) m->makeHistoCutHadronLevel(dir_MC_2760,"CastorTree_MC_2760GeV_42X_",2760);
if(eflow) m->makeHistoEflow(dir_MC_2760,"CastorTree_MC_2760GeV_42X",type,2760,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_2760,"CastorTree_eflow_subsample",type,2760,false);
//-- if(geometry) m->makeHistoGeometry(dir_eflowsubsample_MC_2760,"CastorTree_eflow_subsample",type,2760);
if(geometry) m->makeHistoGeometry(dir_MC_2760,"CastorTree_MC_2760GeV_42X",type,2760);
if(shower) m->makeHistoShower(dir_MC_2760,"CastorTree_MC_2760GeV_42X",type,2760);
}
//-- moca 7000 GeV
TString subdir_MC_7000 = "MinBias_TuneZ2_7TeV_pythia6_cff_py_GEN_SIM_START311_V2_Dec11_v2/CastorTree_MC_MinBias_TuneZ2_7TeV_pythia6_cff_py_Step3_START42_V11_Dec11_v3/3f4f40e814ef79ae1fb43e4fdf4c6377/";
TString dir_MC_7000 = storagehome_hans + subdir_MC_7000;
TString dir_eflowsubsample_MC_7000 = storagehome_ben + TString("EflowSubsample/7TeV/PYTHIA6Z2/");
if (strcmp(energy,"7000")==0) {
cout<<"We'll process the 7 TeV MC tree now"<<endl;
if(ana) m->makeHistos(dir_MC_7000,"CastorTree_MC_7TeV_42X",false,7000);
if(profile) m->makeHistoProfile(dir_MC_7000,"CastorTree_MC_7TeV_42X",false,7000);
if(eflow) m->makeHistoEflow(dir_MC_7000,"CastorTree_MC_7TeV_42X",type,7000,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_7000,"CastorTree_eflow_subsample",type,7000,false);
//-- if(geometry) m->makeHistoGeometry(dir_eflowsubsample_MC_7000,"CastorTree_eflow_subsample",type,7000);
if(geometry) m->makeHistoGeometry(dir_MC_7000,"CastorTree_MC_7TeV_42X",type,7000);
if(shower) m->makeHistoShower(dir_MC_7000,"CastorTree_MC_7TeV_42X",type,7000);
//-- if(profile) m->makeHistoProfile("/user/hvanhaev/Analysis/Eflow/CMSSW_4_2_7/src/UACastor/CastorTree/python/goodcfg/","CastorTree_MC_7TeV_42X_Pythia6_D6T_onlyEM.root",false,7000);
//-- if(profile) m->makeHistoProfile("/user/hvanhaev/Analysis/Eflow/CMSSW_4_2_7/src/UACastor/CastorTree/python/goodcfg/","CastorTree_MC_7TeV_42X_Pythia6_D6T_onlyHAD.root",false,7000);
//-- if(profile) m->makeHistoProfile("/user/roland/EflowAnalysis/CMSSW_4_2_7/src/UACastor/CastorTree/MCTree/","CastorTree_MC_7TeV_42X_Pythia6_D6T_beamtilt.root",false,7000);
if(modulation) m->makeHistoModulation(dir_MC_7000,"CastorTree_MC_7TeV_42X",7000);
if(trigger) m->makeHistoTrigger(dir_MC_7000,"CastorTree_MC_7TeV_42X",false,7000,0);
if(threshold) m->makeHistoThreshold(dir_MC_7000,"CastorTree_MC_7TeV_42X",false,7000);
if(cuthadronlevel) m->makeHistoCutHadronLevel(dir_MC_7000,"CastorTree_MC_7TeV_42X_1",7000);
}
}
if (strcmp(type,"PYTHIA84C")==0) {
//-- moca 900 GeV
TString subdir_MC_900 = "MinBias_Tune4C_900GeV_pythia8_cff_py_GEN_SIM_START311_V2_Dec11_v2/CastorTree_MC_MinBias_Tune4C_900GeV_pythia8_cff_py_Step3_START42_V11_Dec11_v2/ab9a53788d13cfa8c855cda83f795fbe/";
TString dir_MC_900 = storagehome_hans + subdir_MC_900;
TString dir_eflowsubsample_MC_900 = storagehome_ben + TString("EflowSubsample/900GeV/PYTHIA84C/");
if (strcmp(energy,"900")==0) {
cout<<"We'll process the 900 GeV MC tree now"<<endl;
if(eflow) m->makeHistoEflow(dir_MC_900,"CastorTree_MC_900GeV_42X",type,900,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_900,"CastorTree_eflow_subsample",type,900,false);
if(shower) m->makeHistoShower(dir_MC_900,"CastorTree_MC_900GeV_42X",type,900);
}
//-- moca 2760 GeV
TString subdir_MC_2760 = "MinBias_Tune4C_2760GeV_pythia8_cff_py_GEN_SIM_START311_V2_Dec11_v1/CastorTree_MC_MinBias_Tune4C_2760GeV_pythia8_cff_py_Step3_START42_V11_Dec11_v2/95b3059532ea3303b5c4c023bcc2a5dd/";
TString dir_MC_2760 = storagehome_hans + subdir_MC_2760;
TString dir_eflowsubsample_MC_2760 = storagehome_ben + TString("EflowSubsample/2760GeV/PYTHIA84C/");
if (strcmp(energy,"2760")==0) {
cout<<"We'll process the 2760 GeV MC tree now"<<endl;
if(eflow) m->makeHistoEflow(dir_MC_2760,"CastorTree_MC_2760GeV_42X",type,2760,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_2760,"CastorTree_eflow_subsample",type,2760,false);
if(shower) m->makeHistoShower(dir_MC_2760,"CastorTree_MC_2760GeV_42X",type,2760);
}
//-- moca 7000 GeV
TString subdir_MC_7000 = "MinBias_Tune4C_7TeV_pythia8_cff_py_GEN_SIM_START311_V2_Dec11_v1/CastorTree_MC_MinBias_Tune4C_7TeV_pythia8_cff_py_Step3_START42_V11_Dec11_v2/3f4f40e814ef79ae1fb43e4fdf4c6377/";
TString dir_MC_7000 = storagehome_hans + subdir_MC_7000;
TString dir_eflowsubsample_MC_7000 = storagehome_ben + TString("EflowSubsample/7TeV/PYTHIA84C/");
if (strcmp(energy,"7000")==0) {
cout<<"We'll process the 7 TeV MC tree now"<<endl;
if(eflow) m->makeHistoEflow(dir_MC_7000,"CastorTree_MC_7TeV_42X",type,7000,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_7000,"CastorTree_eflow_subsample",type,7000,false);
if(shower) m->makeHistoShower(dir_MC_7000,"CastorTree_MC_7TeV_42X",type,7000);
}
}
if (strcmp(type,"HERWIGpp24")==0) {
//-- moca 900 GeV
TString subdir_MC_900 = "MinBias_900GeV_Herwig_cff_py_GEN_SIM_New/CastorTree_MC_MinBias_900GeV_Herwig_cff_py_Step3_START42_V11_Dec11_v3/ab9a53788d13cfa8c855cda83f795fbe/";
TString dir_MC_900 = storagehome_hans + subdir_MC_900;
TString dir_eflowsubsample_MC_900 = storagehome_ben + TString("EflowSubsample/900GeV/HERWIGpp24/");
if (strcmp(energy,"900")==0) {
cout<<"We'll process the 900 GeV MC tree now"<<endl;
if(eflow) m->makeHistoEflow(dir_MC_900,"CastorTree_MC_900GeV_42X",type,900,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_900,"CastorTree_eflow_subsample",type,900,false);
if(shower) m->makeHistoShower(dir_MC_900,"CastorTree_MC_900GeV_42X",type,900);
}
//-- moca 2760 GeV
TString subdir_MC_2760 = "MinBias_2760GeV_Herwig_cff_py_GEN_SIM_good/CastorTree_MC_MinBias_2760GeV_Herwig_cff_py_Step3_START42_V11_Dec11_v3/95b3059532ea3303b5c4c023bcc2a5dd/";
TString dir_MC_2760 = storagehome_hans + subdir_MC_2760;
TString dir_eflowsubsample_MC_2760 = storagehome_ben + TString("EflowSubsample/2760GeV/HERWIGpp24/");
if (strcmp(energy,"2760")==0) {
cout<<"We'll process the 2760 GeV MC tree now"<<endl;
if(eflow) m->makeHistoEflow(dir_MC_2760,"CastorTree_MC_2760GeV_42X",type,2760,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_2760,"CastorTree_eflow_subsample",type,2760,false);
if(shower) m->makeHistoShower(dir_MC_2760,"CastorTree_MC_2760GeV_42X",type,2760);
}
//-- moca 7000 GeV
TString subdir_MC_7000 = "MinBias_7TeV_Herwig_cff_py_GEN_SIM_New/CastorTree_MC_MinBias_7TeV_Herwig_cff_py_Step3_START42_V11_Dec11_v3/3f4f40e814ef79ae1fb43e4fdf4c6377/";
TString dir_MC_7000 = storagehome_hans + subdir_MC_7000;
TString dir_eflowsubsample_MC_7000 = storagehome_ben + TString("EflowSubsample/7TeV/HERWIGpp24/");
if (strcmp(energy,"7000")==0) {
cout<<"We'll process the 7 TeV MC tree now"<<endl;
if(eflow) m->makeHistoEflow(dir_MC_7000,"CastorTree_MC_7TeV_42X",type,7000,true);
if(eflowsubsample) m->makeHistoEflow(dir_eflowsubsample_MC_7000,"CastorTree_eflow_subsample",type,7000,false);
if(shower) m->makeHistoShower(dir_MC_7000,"CastorTree_MC_7TeV_42X",type,7000);
}
}
delete m;
return(0);
}
| [
""
] | |
090b5ab5cd723149dfbf881c83cebeaa54f1cdad | a2cfb48b64918b9453fe44a2405b9497e1f8f533 | /truss/cpp/examples/block_uart/verification/tests/block_uart.cpp | 8ee6ec89ac8d4e24a0968c7064920461572cfdca | [] | no_license | rekendahl/trusster | c494be1e8f859111e1a879e6160acf3aa911d89a | 9da21c631feec94964ea14a39d5ae72d065f2e88 | refs/heads/master | 2021-01-17T21:43:25.920114 | 2014-01-16T18:54:33 | 2014-01-16T18:54:33 | 4,359,797 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,987 | cpp | /*
Trusster Open Source License version 1.0a (TRUST)
copyright (c) 2006 Mike Mintz and Robert Ekendahl. 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.
* Redistributions in any form must be accompanied by information on how to obtain
complete source code for this software and any accompanying software that uses this software.
The source code must either be included in the distribution or be available in a timely fashion for no more than
the cost of distribution plus a nominal fee, and must be freely redistributable under reasonable and no more
restrictive conditions. For an executable file, complete source code means the source code for all modules it
contains. It does not include source code for modules or files that typically accompany the major components
of the operating system on which the executable file runs.
THIS SOFTWARE IS PROVIDED BY MIKE MINTZ AND ROBERT EKENDAHL ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
OR NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL MIKE MINTZ AND ROBERT EKENDAHL OR ITS CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "block_uart.h"
#include "uart_basic_test_component.h"
#include "uart_bfm.h"
#include "uart_16550_sfm.h"
#include "uart_generator.h"
#include "uart_checker.h"
#include "uart_16550_configuration.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
block_uart::block_uart (testbench* tb, truss::watchdog* w, const std::string& n) :
test_base (n, w), testbench_ (tb),
uart_test_component_ingress_ (new uart::basic_test_component("uart_test_component_ingress", tb->uart_ingress_generator, tb->uart_program_sfm, tb->uart_ingress_checker)),
uart_test_component_egress_ (new uart::basic_test_component("uart_test_component_egress", tb->uart_egress_generator, tb->uart_protocol_bfm, tb->uart_egress_checker))
{
log_ << teal_info << "uart_test new() begin " << teal::endm;
//add configuration default constraints
teal::dictionary::put (tb->uart_configuration->name + "_min_baud", "4800", teal::dictionary::default_only);
teal::dictionary::put (tb->uart_configuration->name + "_min_data_size", "5", teal::dictionary::default_only);
teal::dictionary::put (tb->uart_configuration->name + "_max_data_size", "8", teal::dictionary::default_only);
//add generator default constraints
teal::dictionary::put (tb->uart_egress_generator->name + "_min_word_delay", "1", teal::dictionary::default_only);
teal::dictionary::put (tb->uart_egress_generator->name + "_max_word_delay", "1", teal::dictionary::default_only);
teal::dictionary::put (tb->uart_ingress_generator->name + "_min_word_delay", "1", teal::dictionary::default_only);
teal::dictionary::put (tb->uart_ingress_generator->name + "_max_word_delay", "1", teal::dictionary::default_only);
log_ << teal_info << "uart_test new() end " << teal::endm;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void block_uart::time_zero_setup () {uart_test_component_egress_->time_zero_setup ();}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void block_uart::out_of_reset (reset r) {uart_test_component_egress_->out_of_reset (r);}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void block_uart::randomize () {uart_test_component_egress_->randomize (); uart_test_component_ingress_->randomize ();}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void block_uart::write_to_hardware () {
uart_test_component_egress_->write_to_hardware ();
uart_test_component_ingress_->write_to_hardware ();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void block_uart::start () {
uart_test_component_ingress_->start ();
uart_test_component_egress_->start ();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void block_uart::stop () {uart_test_component_ingress_->stop (); uart_test_component_egress_->stop ();}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void block_uart::wait_for_completion () {
uart_test_component_ingress_->wait_for_completion ();
uart_test_component_egress_->wait_for_completion ();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void block_uart::report (const std::string prefix) const {
uart_test_component_ingress_->report (prefix);
uart_test_component_egress_->report (prefix);
}
| [
"[email protected]"
] | |
ae4fb5957d787e1be427f67e72309409fd602e64 | 0816dd3aa40a231dad8f77423678d99fed610436 | /src/bitcoinrpc.cpp | be39c165916deeb6c388e13c8d4f69c1c1ff0df2 | [
"MIT"
] | permissive | abchains/itchain | 50cd04903a55bae2fb3e35597a47d2d6a62f5cec | 816b035885f4ca9ae4d8b3c0821d2dd93429ad97 | refs/heads/master | 2020-04-02T08:19:26.347879 | 2018-10-22T05:33:06 | 2018-10-22T05:33:06 | 154,082,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,333 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#undef printf
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
#define printf OutputDebugStringF
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
static std::string strRPCUserColonPass;
const Object emptyobj;
void ThreadRPCServer3(void* parg);
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 34452 : 21235;//return GetBoolArg("-testnet", false) ? 30802 : 20802;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"stop <detach>\n"
"<detach> is true or false to detach the database or not for this stop only\n"
"Stop ITchain server (and possibly override the detachdb config value).");
// Shutdown will take long enough that the response should get back
if (params.size() > 0)
bitdb.SetDetach(params[0].get_bool());
StartShutdown();
return "ITchain server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name function safemd unlocked
// ------------------------ ----------------------- ------ --------
{ "help", &help, true, true },
{ "stop", &stop, true, true },
{ "getblockcount", &getblockcount, true, false },
{ "getconnectioncount", &getconnectioncount, true, false },
{ "getpeerinfo", &getpeerinfo, true, false },
{ "getdifficulty", &getdifficulty, true, false },
{ "getgenerate", &getgenerate, true, false },
{ "setgenerate", &setgenerate, true, false },
{ "gethashespersec", &gethashespersec, true, false },
{ "getinfo", &getinfo, true, false },
{ "getmininginfo", &getmininginfo, true, false },
{ "getnewaddress", &getnewaddress, true, false },
{ "getnewpubkey", &getnewpubkey, true, false },
{ "getaccountaddress", &getaccountaddress, true, false },
{ "setaccount", &setaccount, true, false },
{ "getaccount", &getaccount, false, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false },
{ "sendtoaddress", &sendtoaddress, false, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false },
{ "backupwallet", &backupwallet, true, false },
{ "keypoolrefill", &keypoolrefill, true, false },
{ "walletpassphrase", &walletpassphrase, true, false },
{ "walletpassphrasechange", &walletpassphrasechange, false, false },
{ "walletlock", &walletlock, true, false },
{ "encryptwallet", &encryptwallet, false, false },
{ "validateaddress", &validateaddress, true, false },
{ "validatepubkey", &validatepubkey, true, false },
{ "getbalance", &getbalance, false, false },
{ "move", &movecmd, false, false },
{ "sendfrom", &sendfrom, false, false },
{ "sendmany", &sendmany, false, false },
{ "addmultisigaddress", &addmultisigaddress, false, false },
{ "getrawmempool", &getrawmempool, true, false },
{ "getblock", &getblock, false, false },
{ "getblockbynumber", &getblockbynumber, false, false },
{ "getblockhash", &getblockhash, false, false },
{ "gettransaction", &gettransaction, false, false },
{ "listtransactions", &listtransactions, false, false },
{ "listaddressgroupings", &listaddressgroupings, false, false },
{ "signmessage", &signmessage, false, false },
{ "verifymessage", &verifymessage, false, false },
{ "getwork", &getwork, true, false },
{ "getworkex", &getworkex, true, false },
{ "listaccounts", &listaccounts, false, false },
{ "settxfee", &settxfee, false, false },
{ "getblocktemplate", &getblocktemplate, true, false },
{ "submitblock", &submitblock, false, false },
{ "listsinceblock", &listsinceblock, false, false },
{ "dumpprivkey", &dumpprivkey, false, false },
{ "importprivkey", &importprivkey, false, false },
{ "listunspent", &listunspent, false, false },
{ "getrawtransaction", &getrawtransaction, false, false },
{ "createrawtransaction", &createrawtransaction, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false },
{ "signrawtransaction", &signrawtransaction, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false },
{ "getcheckpoint", &getcheckpoint, true, false },
{ "reservebalance", &reservebalance, false, true},
{ "checkwallet", &checkwallet, false, true},
{ "repairwallet", &repairwallet, false, true},
{ "resendtx", &resendtx, false, true},
{ "makekeypair", &makekeypair, false, true},
{ "sendalert", &sendalert, false, false},
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: ITchain-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: ITchain-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: ITchain-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Read header
int nLen = ReadHTTPHeader(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return nStatus;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return strUserPass == strRPCUserColonPass;
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
std::string ipv4addr = address.to_string();
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ThreadRPCServer(void* parg)
{
// Make this thread recognisable as the RPC listener
RenameThread("bitcoin-rpclist");
try
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
ThreadRPCServer2(parg);
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(&e, "ThreadRPCServer()");
} catch (...) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(NULL, "ThreadRPCServer()");
}
printf("ThreadRPCServer exited\n");
}
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted
&& acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn
&& !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
// start HTTP client thread
else if (!NewThread(ThreadRPCServer3, conn)) {
printf("Failed to create RPC server client thread\n");
delete conn;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
void ThreadRPCServer2(void* parg)
{
printf("ThreadRPCServer started\n");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (mapArgs["-rpcpassword"] == "")
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use ITchaind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=bitcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
_("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
const bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
boost::signals2::signal<void ()> StopRequests;
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
while (!fShutdown)
io_service.run_one();
vnThreadsRunning[THREAD_RPCLISTENER]++;
StopRequests();
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
static CCriticalSection cs_THREAD_RPCHANDLER;
void ThreadRPCServer3(void* parg)
{
// Make this thread recognisable as the RPC handler
RenameThread("bitcoin-rpchand");
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]++;
}
AcceptedConnection *conn = (AcceptedConnection *) parg;
bool fRun = true;
loop {
if (fShutdown || !fRun)
{
conn->close();
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
--vnThreadsRunning[THREAD_RPCHANDLER];
}
return;
}
map<string, string> mapHeaders;
string strRequest;
ReadHTTP(conn->stream(), mapHeaders, strRequest);
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
Sleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]--;
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->unlocked)
result = pcmd->actor(params, false);
else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblockbynumber" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...)
{
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| [
"[email protected]"
] | |
0da9995607f8d2a1355b47762ce38a3949dd8cc5 | 35d64c495ab8fd4f3b29067397f33070b9b78fb1 | /DXあほげばりばり/コード/titlelogo.cpp | cc4446b30cbdeebbcd8fea94f0f1aac57b262441 | [] | no_license | sutaa12/Ahoge3D | 7e122afd4b281a0367af5653aff0014b0b6f3fe4 | 8f7e1aafa49c4777c509224d89993ea7c0a0d516 | refs/heads/master | 2020-03-30T11:18:28.842929 | 2015-02-15T00:12:17 | 2015-02-15T00:12:17 | 30,812,846 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 5,815 | cpp | //=============================================================================
//
// タイトル背景 [titlebg.cpp]
// Author : NARITADA SUZUKI
//
//=============================================================================
#include "titlelogo.h"
//*****************************************************************************
// マクロ定義
//*****************************************************************************
#define TEX_TITLELOGO ("data/TEXTURE/titlelogo.png")
#define LOGO_ROT_SPEED (0.05f)
//*****************************************************************************
// プロトタイプ宣言
//*****************************************************************************
void InitVertexTitleLogo(void);
//*****************************************************************************
// グローバル変数
//*****************************************************************************
LPDIRECT3DTEXTURE9 g_pD3DTextureTitleLogo = NULL; // テクスチャへのポインタ
LPDIRECT3DVERTEXBUFFER9 g_pD3DVtxBuffTitleLogo = NULL; // 頂点バッファインターフェースへのポインタ
int g_nTitleCnt;
int g_nLogoButtonCnt;
D3DXVECTOR3 g_fLogoSpeed;
D3DXVECTOR3 g_fLogoPos;
float g_fLogoRot;
//*****************************************************************************
// 初期化処理
//*****************************************************************************
HRESULT InitTitleLogo(void)
{
LPDIRECT3DDEVICE9 pDevice = GetDevice();
g_fLogoRot = 0;
g_fLogoSpeed = D3DXVECTOR3(0,0,0);
g_fLogoPos = D3DXVECTOR3(TITLELOGO_X,TITLELOGO_Y,0);
//頂点情報の設定
if(FAILED(pDevice->CreateVertexBuffer( //頂点バッファ作成
sizeof(VERTEX_2D)*4,
D3DUSAGE_WRITEONLY,
FVF_VERTEX_2D,
D3DPOOL_MANAGED,
&g_pD3DVtxBuffTitleLogo,
NULL)))
{
return E_FAIL;//読み込めなかったらエラー
}
InitVertexTitleLogo();
//テクスチャ読み込み
D3DXCreateTextureFromFile(GetDevice(),
TEX_TITLELOGO,
&g_pD3DTextureTitleLogo);
g_nTitleCnt = 0;
return S_OK;
}
//*****************************************************************************
// 終了処理
//*****************************************************************************
void UninitTitleLogo(void)
{
if(g_pD3DVtxBuffTitleLogo!=NULL)
{
g_pD3DVtxBuffTitleLogo->Release();//初期化
g_pD3DVtxBuffTitleLogo=NULL;
}
if(g_pD3DTextureTitleLogo!=NULL)//空でないなら
{
g_pD3DTextureTitleLogo->Release();
g_pD3DTextureTitleLogo=NULL;//アドレスを空に
}
}
//*****************************************************************************
// 更新処理
//*****************************************************************************
void UpdateTitleLogo(void)
{
g_nTitleCnt++;
VERTEX_2D *pvtx;
g_nTitleCnt = g_nTitleCnt%90;
g_pD3DVtxBuffTitleLogo->Lock(0,0,(void**)&pvtx,0);//頂点の位置をロック
for (int nLoop = 0; nLoop < 4 ; nLoop++)
{
if(g_nTitleCnt >=60)
{
if(g_nTitleCnt%3 == 0)
{
pvtx[nLoop].diffuse = D3DCOLOR_RGBA(20,20,200,255);//色設定
}else{
pvtx[nLoop].diffuse = D3DCOLOR_RGBA(255,255,255,255);//色設定
}
}
}
g_nLogoButtonCnt++;
g_fLogoRot += LOGO_ROT_SPEED;
if(g_fLogoRot<D3DX_PI)
{
g_fLogoRot = D3DX_PI;
}
g_fLogoPos.x -= sinf(g_fLogoRot);
g_fLogoPos.y -= cosf(g_fLogoRot);
//頂点情報の初期化
pvtx[0].vtx = D3DXVECTOR3(g_fLogoPos.x,g_fLogoPos.y,0.0f);//頂点の座標格納
pvtx[1].vtx = D3DXVECTOR3(g_fLogoPos.x + TITLELOGO_W,g_fLogoPos.y,0.0f);//頂点の座標格納
pvtx[2].vtx = D3DXVECTOR3(g_fLogoPos.x,g_fLogoPos.y + TITLELOGO_H,0.0f);//頂点の座標格納
pvtx[3].vtx = D3DXVECTOR3(g_fLogoPos.x + TITLELOGO_W,g_fLogoPos.y+ TITLELOGO_H,0.0f);//頂点の座標格納
g_pD3DVtxBuffTitleLogo->Unlock();//ロックの解除を忘れずに
g_pD3DVtxBuffTitleLogo->Unlock();//ロックの解除を忘れずに
}
//*****************************************************************************
// 描画処理
//*****************************************************************************
void DrawTitleLogo(void)
{
LPDIRECT3DDEVICE9 pDevice = GetDevice();
//ポリゴンの描画
pDevice->SetStreamSource(0,g_pD3DVtxBuffTitleLogo,0,sizeof(VERTEX_2D));//ポリゴンセット
pDevice->SetFVF(FVF_VERTEX_2D); //頂点フォーマットの設定
pDevice->SetTexture(0,g_pD3DTextureTitleLogo);//テクスチャセット
pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, //ポリゴンの設定
0,
2);//個数
}
//*****************************************************************************
// 頂点初期化
//*****************************************************************************
void InitVertexTitleLogo(void)
{
VERTEX_2D *pvtx;
g_pD3DVtxBuffTitleLogo->Lock(0,0,(void**)&pvtx,0);//頂点の位置をロック
//頂点情報の初期化
pvtx[0].vtx = D3DXVECTOR3(g_fLogoPos.x,g_fLogoPos.y,0.0f);//頂点の座標格納
pvtx[1].vtx = D3DXVECTOR3(g_fLogoPos.x + TITLELOGO_W,g_fLogoPos.y,0.0f);//頂点の座標格納
pvtx[2].vtx = D3DXVECTOR3(g_fLogoPos.x,g_fLogoPos.y + TITLELOGO_H,0.0f);//頂点の座標格納
pvtx[3].vtx = D3DXVECTOR3(g_fLogoPos.x + TITLELOGO_W,g_fLogoPos.y+ TITLELOGO_H,0.0f);//頂点の座標格納
pvtx[0].diffuse = D3DCOLOR_RGBA(255,255,255,255); //色設定
pvtx[1].diffuse = D3DCOLOR_RGBA(255,255,255,255); //色設定
pvtx[2].diffuse = D3DCOLOR_RGBA(255,255,255,255); //色設定
pvtx[3].diffuse = D3DCOLOR_RGBA(255,255,255,255); //色設定
pvtx[0].rhw = 1.0f;
pvtx[1].rhw = 1.0f;
pvtx[2].rhw = 1.0f;
pvtx[3].rhw = 1.0f;
pvtx[0].tex = D3DXVECTOR2(0.0f,0.0f);
pvtx[1].tex = D3DXVECTOR2(1.0f, 0.0f);
pvtx[2].tex = D3DXVECTOR2(0.0f,1.0f);
pvtx[3].tex = D3DXVECTOR2(1,1.0f);
g_pD3DVtxBuffTitleLogo->Unlock();//ロックの解除を忘れずに
}
//End Of File | [
"[email protected]"
] | |
732185b2049852f914f87d35ab4c8f2180d1b6fa | 326e178ba6b238797a5a7f7ffc19005b8784201c | /ROS/tello_ros_ws/build/tello_msgs/rosidl_typesupport_fastrtps_c/tello_msgs/srv/tello_action__type_support_c.cpp | 9fcc3ad77a6cb5ee635778465a98ba1c31563af1 | [] | no_license | s1063724/Smart-drone-classification-technology | 9f8e1697ee5ebab3c648e5a203d68c0a9b302623 | 5fa9204f09f44322182c2a2932dbfe0105247792 | refs/heads/master | 2023-02-03T04:53:00.628055 | 2020-12-25T07:10:01 | 2020-12-25T07:10:01 | 265,543,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,065 | cpp | // generated from rosidl_typesupport_fastrtps_c/resource/idl__type_support_c.cpp.em
// with input from tello_msgs:srv/TelloAction.idl
// generated code does not contain a copyright notice
#include "tello_msgs/srv/tello_action__rosidl_typesupport_fastrtps_c.h"
#include <cassert>
#include <limits>
#include <string>
#include "rosidl_typesupport_fastrtps_c/identifier.h"
#include "rosidl_typesupport_fastrtps_c/wstring_conversion.hpp"
#include "rosidl_typesupport_fastrtps_cpp/message_type_support.h"
#include "tello_msgs/msg/rosidl_typesupport_fastrtps_c__visibility_control.h"
#include "tello_msgs/srv/tello_action__struct.h"
#include "tello_msgs/srv/tello_action__functions.h"
#include "fastcdr/Cdr.h"
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
# ifdef __clang__
# pragma clang diagnostic ignored "-Wdeprecated-register"
# pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
# endif
#endif
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
// includes and forward declarations of message dependencies and their conversion functions
#if defined(__cplusplus)
extern "C"
{
#endif
#include "rosidl_generator_c/string.h" // cmd
#include "rosidl_generator_c/string_functions.h" // cmd
// forward declare type support functions
using _TelloAction_Request__ros_msg_type = tello_msgs__srv__TelloAction_Request;
static bool _TelloAction_Request__cdr_serialize(
const void * untyped_ros_message,
eprosima::fastcdr::Cdr & cdr)
{
if (!untyped_ros_message) {
fprintf(stderr, "ros message handle is null\n");
return false;
}
const _TelloAction_Request__ros_msg_type * ros_message = static_cast<const _TelloAction_Request__ros_msg_type *>(untyped_ros_message);
// Field name: cmd
{
const rosidl_generator_c__String * str = &ros_message->cmd;
if (str->capacity == 0 || str->capacity <= str->size) {
fprintf(stderr, "string capacity not greater than size\n");
return false;
}
if (str->data[str->size] != '\0') {
fprintf(stderr, "string not null-terminated\n");
return false;
}
cdr << str->data;
}
return true;
}
static bool _TelloAction_Request__cdr_deserialize(
eprosima::fastcdr::Cdr & cdr,
void * untyped_ros_message)
{
if (!untyped_ros_message) {
fprintf(stderr, "ros message handle is null\n");
return false;
}
_TelloAction_Request__ros_msg_type * ros_message = static_cast<_TelloAction_Request__ros_msg_type *>(untyped_ros_message);
// Field name: cmd
{
std::string tmp;
cdr >> tmp;
if (!ros_message->cmd.data) {
rosidl_generator_c__String__init(&ros_message->cmd);
}
bool succeeded = rosidl_generator_c__String__assign(
&ros_message->cmd,
tmp.c_str());
if (!succeeded) {
fprintf(stderr, "failed to assign string into field 'cmd'\n");
return false;
}
}
return true;
}
ROSIDL_TYPESUPPORT_FASTRTPS_C_PUBLIC_tello_msgs
size_t get_serialized_size_tello_msgs__srv__TelloAction_Request(
const void * untyped_ros_message,
size_t current_alignment)
{
const _TelloAction_Request__ros_msg_type * ros_message = static_cast<const _TelloAction_Request__ros_msg_type *>(untyped_ros_message);
(void)ros_message;
size_t initial_alignment = current_alignment;
const size_t padding = 4;
const size_t wchar_size = 4;
(void)padding;
(void)wchar_size;
// field.name cmd
current_alignment += padding +
eprosima::fastcdr::Cdr::alignment(current_alignment, padding) +
(ros_message->cmd.size + 1);
return current_alignment - initial_alignment;
}
static uint32_t _TelloAction_Request__get_serialized_size(const void * untyped_ros_message)
{
return static_cast<uint32_t>(
get_serialized_size_tello_msgs__srv__TelloAction_Request(
untyped_ros_message, 0));
}
ROSIDL_TYPESUPPORT_FASTRTPS_C_PUBLIC_tello_msgs
size_t max_serialized_size_tello_msgs__srv__TelloAction_Request(
bool & full_bounded,
size_t current_alignment)
{
size_t initial_alignment = current_alignment;
const size_t padding = 4;
const size_t wchar_size = 4;
(void)padding;
(void)wchar_size;
(void)full_bounded;
// member: cmd
{
size_t array_size = 1;
full_bounded = false;
for (size_t index = 0; index < array_size; ++index) {
current_alignment += padding +
eprosima::fastcdr::Cdr::alignment(current_alignment, padding) +
1;
}
}
return current_alignment - initial_alignment;
}
static size_t _TelloAction_Request__max_serialized_size(bool & full_bounded)
{
return max_serialized_size_tello_msgs__srv__TelloAction_Request(
full_bounded, 0);
}
static message_type_support_callbacks_t __callbacks_TelloAction_Request = {
"tello_msgs::srv",
"TelloAction_Request",
_TelloAction_Request__cdr_serialize,
_TelloAction_Request__cdr_deserialize,
_TelloAction_Request__get_serialized_size,
_TelloAction_Request__max_serialized_size
};
static rosidl_message_type_support_t _TelloAction_Request__type_support = {
rosidl_typesupport_fastrtps_c__identifier,
&__callbacks_TelloAction_Request,
get_message_typesupport_handle_function,
};
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, tello_msgs, srv, TelloAction_Request)() {
return &_TelloAction_Request__type_support;
}
#if defined(__cplusplus)
}
#endif
// already included above
// #include <cassert>
// already included above
// #include <limits>
// already included above
// #include <string>
// already included above
// #include "rosidl_typesupport_fastrtps_c/identifier.h"
// already included above
// #include "rosidl_typesupport_fastrtps_c/wstring_conversion.hpp"
// already included above
// #include "rosidl_typesupport_fastrtps_cpp/message_type_support.h"
// already included above
// #include "tello_msgs/msg/rosidl_typesupport_fastrtps_c__visibility_control.h"
// already included above
// #include "tello_msgs/srv/tello_action__struct.h"
// already included above
// #include "tello_msgs/srv/tello_action__functions.h"
// already included above
// #include "fastcdr/Cdr.h"
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
# ifdef __clang__
# pragma clang diagnostic ignored "-Wdeprecated-register"
# pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
# endif
#endif
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
// includes and forward declarations of message dependencies and their conversion functions
#if defined(__cplusplus)
extern "C"
{
#endif
// forward declare type support functions
using _TelloAction_Response__ros_msg_type = tello_msgs__srv__TelloAction_Response;
static bool _TelloAction_Response__cdr_serialize(
const void * untyped_ros_message,
eprosima::fastcdr::Cdr & cdr)
{
if (!untyped_ros_message) {
fprintf(stderr, "ros message handle is null\n");
return false;
}
const _TelloAction_Response__ros_msg_type * ros_message = static_cast<const _TelloAction_Response__ros_msg_type *>(untyped_ros_message);
// Field name: rc
{
cdr << ros_message->rc;
}
return true;
}
static bool _TelloAction_Response__cdr_deserialize(
eprosima::fastcdr::Cdr & cdr,
void * untyped_ros_message)
{
if (!untyped_ros_message) {
fprintf(stderr, "ros message handle is null\n");
return false;
}
_TelloAction_Response__ros_msg_type * ros_message = static_cast<_TelloAction_Response__ros_msg_type *>(untyped_ros_message);
// Field name: rc
{
cdr >> ros_message->rc;
}
return true;
}
ROSIDL_TYPESUPPORT_FASTRTPS_C_PUBLIC_tello_msgs
size_t get_serialized_size_tello_msgs__srv__TelloAction_Response(
const void * untyped_ros_message,
size_t current_alignment)
{
const _TelloAction_Response__ros_msg_type * ros_message = static_cast<const _TelloAction_Response__ros_msg_type *>(untyped_ros_message);
(void)ros_message;
size_t initial_alignment = current_alignment;
const size_t padding = 4;
const size_t wchar_size = 4;
(void)padding;
(void)wchar_size;
// field.name rc
{
size_t item_size = sizeof(ros_message->rc);
current_alignment += item_size +
eprosima::fastcdr::Cdr::alignment(current_alignment, item_size);
}
return current_alignment - initial_alignment;
}
static uint32_t _TelloAction_Response__get_serialized_size(const void * untyped_ros_message)
{
return static_cast<uint32_t>(
get_serialized_size_tello_msgs__srv__TelloAction_Response(
untyped_ros_message, 0));
}
ROSIDL_TYPESUPPORT_FASTRTPS_C_PUBLIC_tello_msgs
size_t max_serialized_size_tello_msgs__srv__TelloAction_Response(
bool & full_bounded,
size_t current_alignment)
{
size_t initial_alignment = current_alignment;
const size_t padding = 4;
const size_t wchar_size = 4;
(void)padding;
(void)wchar_size;
(void)full_bounded;
// member: rc
{
size_t array_size = 1;
current_alignment += array_size * sizeof(uint8_t);
}
return current_alignment - initial_alignment;
}
static size_t _TelloAction_Response__max_serialized_size(bool & full_bounded)
{
return max_serialized_size_tello_msgs__srv__TelloAction_Response(
full_bounded, 0);
}
static message_type_support_callbacks_t __callbacks_TelloAction_Response = {
"tello_msgs::srv",
"TelloAction_Response",
_TelloAction_Response__cdr_serialize,
_TelloAction_Response__cdr_deserialize,
_TelloAction_Response__get_serialized_size,
_TelloAction_Response__max_serialized_size
};
static rosidl_message_type_support_t _TelloAction_Response__type_support = {
rosidl_typesupport_fastrtps_c__identifier,
&__callbacks_TelloAction_Response,
get_message_typesupport_handle_function,
};
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, tello_msgs, srv, TelloAction_Response)() {
return &_TelloAction_Response__type_support;
}
#if defined(__cplusplus)
}
#endif
#include "rosidl_typesupport_fastrtps_cpp/service_type_support.h"
#include "rosidl_typesupport_cpp/service_type_support.hpp"
// already included above
// #include "rosidl_typesupport_fastrtps_c/identifier.h"
// already included above
// #include "tello_msgs/msg/rosidl_typesupport_fastrtps_c__visibility_control.h"
#include "tello_msgs/srv/tello_action.h"
#if defined(__cplusplus)
extern "C"
{
#endif
static service_type_support_callbacks_t TelloAction__callbacks = {
"tello_msgs::srv",
"TelloAction",
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, tello_msgs, srv, TelloAction_Request)(),
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, tello_msgs, srv, TelloAction_Response)(),
};
static rosidl_service_type_support_t TelloAction__handle = {
rosidl_typesupport_fastrtps_c__identifier,
&TelloAction__callbacks,
get_service_typesupport_handle_function,
};
const rosidl_service_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, tello_msgs, srv, TelloAction)() {
return &TelloAction__handle;
}
#if defined(__cplusplus)
}
#endif
| [
"[email protected]"
] | |
03f9f88771d2b1c3934d91c5bf897790adbb87e9 | 1dd825971ed4ec0193445dc9ed72d10618715106 | /examples/extended/electromagnetic/TestEm10/src/EventAction.cc | bdf6c04e243cd1511dc0206a388d78176fa6350f | [] | no_license | gfh16/Geant4 | 4d442e5946eefc855436f4df444c245af7d3aa81 | d4cc6c37106ff519a77df16f8574b2fe4ad9d607 | refs/heads/master | 2021-06-25T22:32:21.104339 | 2020-11-02T13:12:01 | 2020-11-02T13:12:01 | 158,790,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,225 | cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file electromagnetic/TestEm10/src/EventAction.cc
/// \brief Implementation of the EventAction class
//
//
// $Id$
//
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
#include "EventAction.hh"
#include "RunAction.hh"
#include "G4RunManager.hh"
#include "G4Event.hh"
#include "Randomize.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
EventAction::EventAction(RunAction* runAction)
: G4UserEventAction(),
fRunAction(runAction), fVerboseLevel(0)
{
G4RunManager::GetRunManager()->SetPrintProgress(10000);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
EventAction::~EventAction()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
void EventAction::BeginOfEventAction(const G4Event*)
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
void EventAction::EndOfEventAction(const G4Event* event)
{
// save rndm status
if (fRunAction->GetRndmFreq() == 2) {
CLHEP::HepRandom::saveEngineStatus("endOfEvent.rndm");
// show rndm status
G4int eventNb = event->GetEventID();
G4int printModulo = G4RunManager::GetRunManager()->GetPrintProgress();
if (eventNb%printModulo == 0) {
G4cout << "\n---> End of Event: " << eventNb << G4endl;
CLHEP::HepRandom::showEngineStatus();
}
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
| [
"[email protected]"
] | |
c5ff3d35747d455f1ab0f280be779973341bb946 | bbab2cc5fc475d6ce9c9465e0b954ff5b0c75387 | /subversion-1.6.13/subversion/bindings/javahl/native/CommitMessage.cpp | 033390cfb13e796b792f3b993338bf7d8e70af6e | [
"BSD-2-Clause"
] | permissive | RussellBauer/G5_Deps | df4ddff82753281a500d44bcd18a4ba19d1fcf1e | 8918d8ce8d15cc494f499859cfbfe8e66c574acc | refs/heads/master | 2021-04-06T08:58:46.594961 | 2018-03-13T15:55:28 | 2018-03-13T15:55:28 | 125,070,934 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,906 | cpp | /**
* @copyright
* ====================================================================
* Copyright (c) 2003-2004 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file CommitMessage.cpp
* @brief Implementation of the class CommitMessage
*/
#include "CommitMessage.h"
#include "JNIUtil.h"
#include <apr_tables.h>
#include "svn_client.h"
#include "../include/org_tigris_subversion_javahl_CommitItemStateFlags.h"
CommitMessage::CommitMessage(jobject jcommitMessage)
{
m_jcommitMessage = jcommitMessage;
}
CommitMessage::~CommitMessage()
{
// Since the m_jcommitMessage is a global reference, it has to be
// deleted to allow the Java garbage collector to reclaim the
// object.
if (m_jcommitMessage!= NULL)
{
JNIEnv *env = JNIUtil::getEnv();
env->DeleteGlobalRef(m_jcommitMessage);
}
}
CommitMessage *CommitMessage::makeCCommitMessage(jobject jcommitMessage)
{
// If there is no object passed into this method, there is no need
// for a C++ holding object.
if (jcommitMessage == NULL)
return NULL;
// Sanity check, that the passed Java object implements the right
// interface.
JNIEnv *env = JNIUtil::getEnv();
jclass clazz = env->FindClass(JAVA_PACKAGE"/CommitMessage");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
if (!env->IsInstanceOf(jcommitMessage, clazz))
{
env->DeleteLocalRef(clazz);
return NULL;
}
env->DeleteLocalRef(clazz);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
// Since the reference is longer needed then the duration of the
// SVNClient.commtMessage, the local reference has to be converted
// to a global reference.
jobject myCommitMessage = env->NewGlobalRef(jcommitMessage);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
// create & return the holding object
return new CommitMessage(myCommitMessage);
}
/**
* Call the Java callback method to retrieve the commit message
* @param commit_items the array of the items of this commit
* @returns the commit message
*/
jstring
CommitMessage::getCommitMessage(const apr_array_header_t *commit_items)
{
JNIEnv *env = JNIUtil::getEnv();
// create an Java array for the commit items
jclass clazz = env->FindClass(JAVA_PACKAGE"/CommitItem");
if (JNIUtil::isExceptionThrown())
return NULL;
int count = commit_items->nelts;
jobjectArray jitems = env->NewObjectArray(count, clazz, NULL);
if (JNIUtil::isExceptionThrown())
return NULL;
// Java method ids will not change during the time this library is
// loaded, so they can be cached.
// Get the method id for the CommitItem constructor.
static jmethodID midConstructor = 0;
if (midConstructor == 0)
{
midConstructor = env->GetMethodID(clazz, "<init>",
"(Ljava/lang/String;"
"IILjava/lang/String;"
"Ljava/lang/String;J)V");
if (JNIUtil::isExceptionThrown())
return NULL;
}
// get the method if for the CommitMessage callback method
static jmethodID midCallback = 0;
if (midCallback == 0)
{
jclass clazz2 = env->FindClass(JAVA_PACKAGE"/CommitMessage");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
midCallback = env->GetMethodID(clazz2, "getLogMessage",
"([L"JAVA_PACKAGE"/CommitItem;)"
"Ljava/lang/String;");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(clazz2);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
}
// create a Java CommitItem for each of the passed in commit items
for (int i = 0; i < count; ++i)
{
svn_client_commit_item3_t *item =
APR_ARRAY_IDX(commit_items, i, svn_client_commit_item3_t *);
// convert the commit item members to the match Java members
jstring jpath = JNIUtil::makeJString(item->path);
jint jnodeKind = item->kind;
jint jstateFlags = 0;
if (item->state_flags & SVN_CLIENT_COMMIT_ITEM_ADD)
jstateFlags |=
org_tigris_subversion_javahl_CommitItemStateFlags_Add;
if (item->state_flags & SVN_CLIENT_COMMIT_ITEM_DELETE)
jstateFlags |=
org_tigris_subversion_javahl_CommitItemStateFlags_Delete;
if (item->state_flags & SVN_CLIENT_COMMIT_ITEM_TEXT_MODS)
jstateFlags |=
org_tigris_subversion_javahl_CommitItemStateFlags_TextMods;
if (item->state_flags & SVN_CLIENT_COMMIT_ITEM_PROP_MODS)
jstateFlags |=
org_tigris_subversion_javahl_CommitItemStateFlags_PropMods;
if (item->state_flags & SVN_CLIENT_COMMIT_ITEM_IS_COPY)
jstateFlags |=
org_tigris_subversion_javahl_CommitItemStateFlags_IsCopy;
jstring jurl = JNIUtil::makeJString(item->url);
jstring jcopyUrl = JNIUtil::makeJString(item->copyfrom_url);
jlong jcopyRevision = item->revision;
// create the Java object
jobject jitem = env->NewObject(clazz, midConstructor, jpath,
jnodeKind, jstateFlags, jurl,
jcopyUrl, jcopyRevision);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
// release the tempory Java objects
env->DeleteLocalRef(jpath);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jurl);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jcopyUrl);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
// store the Java object into the array
env->SetObjectArrayElement(jitems, i, jitem);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
}
env->DeleteLocalRef(clazz);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
// call the Java callback method
jstring jmessage = (jstring)env->CallObjectMethod(m_jcommitMessage,
midCallback,
jitems);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
// release the Java object array
env->DeleteLocalRef(jitems);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
return jmessage;
}
| [
"[email protected]"
] | |
661077d22430355b2b15dede0d23c8af877d2ffd | 37bf77c75be5e4a1e43ae67c195697b5a9c018c0 | /src/api/js/jseventlistener.h | 4747c8429497b7da6556c268f960d54d55feaccc | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mecctro/wasabi | dbaa656ad71f719fa7b227346dc892058212f96d | 49d293042ce17b0d137b2e4c6fc82a52bdb05091 | refs/heads/master | 2020-12-29T01:11:56.251711 | 2013-09-01T20:08:51 | 2013-09-01T20:08:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 556 | h | #ifndef JSEVENTLISTENER_H
#define JSEVENTLISTENER_H
#include "jsapi.h"
class JSEventListener {
public:
JSEventListener(JSContext *context, jsval function, JSObject *object) {
m_context = context;
m_function = function;
m_object = object;
JS_AddRoot(context, &m_function);
JS_AddRoot(context, &m_object);
}
virtual ~JSEventListener() {
JS_RemoveRoot(m_context, &m_function);
JS_RemoveRoot(m_context, &m_object);
}
JSContext *m_context;
JSObject *m_object;
jsval m_function;
};
#endif
| [
"[email protected]"
] | |
8ee0caa3fc62e1592c1b45aded5d7348a62e5d13 | 3c03b8bbe0b5378430350577c6874a5394cf7358 | /src/TileWorld.h | 0d02905364b07942a202978bd9f37d9317e2be95 | [] | no_license | BrandonSchaefer/TileRenderer | 0981458fa44877f0952681b71a079da9add8981e | 8d687837c2d3bb333eeefc86b1bf1863f12fe721 | refs/heads/master | 2018-12-30T00:40:03.756875 | 2014-12-29T21:29:58 | 2014-12-29T21:29:58 | 28,378,027 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | h | //-*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/* * Copyright (C) CURRENT_YEAR Brandon Scckhaefer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Brandon Schaefer <[email protected]>
*/
#ifndef TILE_WORLD_H
#define TILE_WORLD_H
#include "Directions.h"
#include "Rect.h"
#include "TileTerrain.h"
namespace tile_renderer
{
struct TileWorldSettings
{
float screen_width;
float screen_height;
float offset_x;
float offset_y;
Rect camera;
};
class TileWorld
{
public:
TileWorld(TileWorldSettings const& settings);
Rect CameraRect() const;
Rect WorldRect() const;
void Draw();
void HandleKeyUp(int keysym);
void HandleKeyDown(int keysym);
void HandleMouseUp(int x, int y);
void HandleMouseDown(int x, int y);
void HandleMouseClick(int x, int y);
void HandleMouseMove(int x, int y);
private:
bool MoveWasInvalid() const;
void UpdateCameraMoving();
void CheckIfMouseDownAroundTheEdge(int x, int y);
int screen_width_;
int screen_height_;
Rect camera_rect_;
Rect world_rect_;
TileTerrain terrain_;
float trans_x_;
float trans_y_;
float diff_x_;
float diff_y_;
float zoom_;
float diff_zoom_;
bool mouse_down_;
};
} // namespace tile_renderer
#endif // TILE_WORLD_H
| [
"[email protected]"
] | |
658c9c750f7f35088bc455cf6a13dbbedc3dacec | 638c9b075ac3bfdf3b2d96f1dd786684d7989dcd | /spark/source/SpMatrix.inc | 348b2cb291bc8be7f8883dbb2e9cb78a7f56c89b | [] | no_license | cycle-zz/archives | 4682d6143b9057b21af9845ecbd42d7131750b1b | f92b677342e75e5cb7743a0d1550105058aff8f5 | refs/heads/master | 2021-05-27T21:07:16.240438 | 2010-03-18T08:01:46 | 2010-03-18T08:01:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,084 | inc | // =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>::SpMatrix ()
{
// the matrix is uninitialized
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>::SpMatrix (bool bZero)
{
memset(m_afValues,0,N*N*sizeof(Real));
if ( !bZero )
{
for (int i = 0; i < N; i++)
m_afValues[i][i] = (Real)1.0;
}
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>::SpMatrix (const SpMatrix& rkM)
{
memcpy(m_afValues,rkM.m_afValues,N*N*sizeof(Real));
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>::operator const Real* () const
{
return m_afValues;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>::operator Real* ()
{
return m_afValues;
}
// =============================================================================
template <unsigned int N, class Real>
const Real* SpMatrix<N,Real>::operator[] (unsigned int uiRow) const
{
assert( 0 <= uiRow && uiRow < N );
return &m_afValues[uiRow];
}
// =============================================================================
template <unsigned int N, class Real>
Real* SpMatrix<N,Real>::operator[] (unsigned int uiRow)
{
assert( 0 <= uiRow && uiRow < N );
return &m_afValues[uiRow];
}
// =============================================================================
template <unsigned int N, class Real>
Real SpMatrix<N,Real>::operator() (unsigned int uiRow, unsigned int uiCol) const
{
return m_afValues[uiRow][uiCol];
}
// =============================================================================
template <unsigned int N, class Real>
Real& SpMatrix<N,Real>::operator() (unsigned int uiRow, unsigned int uiCol)
{
return m_afValues[[ uiRow ][ uiCol ]];
}
// =============================================================================
template <unsigned int N, class Real>
void SpMatrix<N,Real>::SetRow (unsigned int uiRow, const Vector<N,Real>& rkV)
{
assert( 0 <= uiRow && uiRow < N );
for (unsigned int uiCol = 0, i = N*uiRow; uiCol < N; uiCol++, i++)
m_afValues[i] = rkV[iCol];
}
// =============================================================================
template <unsigned int N, class Real>
Vector<N,Real> SpMatrix<N,Real>::GetRow (unsigned int uiRow) const
{
assert( 0 <= uiRow && uiRow < N );
Vector<N,Real> kV;
for (unsigned int uiCol = 0, i = N*uiRow; uiCol < N; uiCol++, i++)
kV[iCol] = m_afValues[i];
return kV;
}
// =============================================================================
template <unsigned int N, class Real>
void SpMatrix<N,Real>::SetColumn (unsigned int uiCol, const Vector<N,Real>& rkV)
{
assert( 0 <= uiCol && uiCol < N );
for (unsigned int uiRow = 0, i = uiCol; uiRow < N; uiRow++, i += N)
m_afValues[i] = rkV[iRow];
}
// =============================================================================
template <unsigned int N, class Real>
Vector<N,Real> SpMatrix<N,Real>::GetColumn (unsigned int uiCol) const
{
assert( 0 <= uiCol && uiCol < N );
Vector<N,Real> kV;
for (unsigned int uiRow = 0, i = uiCol; uiRow < N; uiRow++, i += N)
kV[iRow] = m_afValues[i];
return kV;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>& SpMatrix<N,Real>::operator= (const SpMatrix& rkM)
{
memcpy(m_afValues,rkM.m_afValues,N*N*sizeof(Real));
return *this;
}
// =============================================================================
template <unsigned int N, class Real>
bool SpMatrix<N,Real>::operator== (const SpMatrix& rkM) const
{
return memcmp(m_afValues,rkM.m_afValues,N*N*sizeof(Real)) == 0;
}
// =============================================================================
template <unsigned int N, class Real>
bool SpMatrix<N,Real>::operator!= (const SpMatrix& rkM) const
{
return memcmp(m_afValues,rkM.m_afValues,N*N*sizeof(Real)) != 0;
}
// =============================================================================
template <unsigned int N, class Real>
int SpMatrix<N,Real>::compare(const SpMatrix& rkM) const
{
for (int i = 0; i < N*N; i++)
{
unsigned int uiTest0 = *(unsigned int*)&m_afValues[i];
unsigned int uiTest1 = *(unsigned int*)&rkM.m_afValues[i];
if ( uiTest0 < uiTest1 )
return -1;
if ( uiTest0 > uiTest1 )
return +1;
}
return 0;
}
// =============================================================================
template <unsigned int N, class Real>
bool SpMatrix<N,Real>::operator< (const SpMatrix& rkM) const
{
return compare(rkM) < 0;
}
// =============================================================================
template <unsigned int N, class Real>
bool SpMatrix<N,Real>::operator<= (const SpMatrix& rkM) const
{
return compare(rkM) <= 0;
}
// =============================================================================
template <unsigned int N, class Real>
bool SpMatrix<N,Real>::operator> (const SpMatrix& rkM) const
{
return compare(rkM) > 0;
}
// =============================================================================
template <unsigned int N, class Real>
bool SpMatrix<N,Real>::operator>= (const SpMatrix& rkM) const
{
return compare(rkM) >= 0;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real> SpMatrix<N,Real>::operator+ (const SpMatrix& rkM) const
{
SpMatrix<N,Real> kSum;
for (int i = 0; i < N*N; i++)
kSum.m_afValues[i] = m_afValues[i] + rkM.m_afValues[i];
return kSum;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real> SpMatrix<N,Real>::operator- (const SpMatrix& rkM) const
{
SpMatrix<N,Real> kDiff;
for (int i = 0; i < N*N; i++)
kDiff.m_afValues[i] = m_afValues[i] - rkM.m_afValues[i];
return kDiff;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real> SpMatrix<N,Real>::operator* (const SpMatrix& rkM) const
{
SpMatrix<N,Real> kProd;
for (unsigned int uiRow = 0; uiRow < N; uiRow++)
{
for (unsigned int uiCol = 0; uiCol < N; uiCol++)
{
kProd.m_afValues[ uiRow ][ uiCol ] = (Real)0.0f;
for (unsigned int uiMid = 0; uiMid < N; uiMid++)
{
kProd.m_afValues[ uiRow ][ uiCol ] +=
m_afValues[uiRow][uiMid] * rkM.m_afValues[uiMid][uiCol];
}
}
}
return kProd;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real> SpMatrix<N,Real>::operator* (Real fScalar) const
{
SpMatrix<N,Real> kProd;
for (int i = 0; i < N*N; i++)
kProd.m_afValues[i] = fScalar*m_afValues[i];
return kProd;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real> SpMatrix<N,Real>::operator/ (Real fScalar) const
{
SpMatrix<N,Real> kQuot;
int i;
if ( fScalar != (Real)0.0 )
{
Real fInvScalar = ((Real)1.0)/fScalar;
for (i = 0; i < N*N; i++)
kQuot.m_afValues[i] = fInvScalar*m_afValues[i];
}
else
{
for (i = 0; i < N*N; i++)
kQuot.m_afValues[i] = Math<Real>::MAX_REAL;
}
return kQuot;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real> SpMatrix<N,Real>::operator- () const
{
SpMatrix<N,Real> kNeg;
for (int i = 0; i < N*N; i++)
kNeg.m_afValues[i] = -m_afValues[i];
return kNeg;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real> operator* (Real fScalar, const SpMatrix<N,Real>& rkM)
{
SpMatrix<N,Real> kProd;
const Real* afMValue = rkM;
Real* afPValue = kProd;
for (int i = 0; i < N*N; i++)
afPValue[i] = fScalar*afMValue[i];
return kProd;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>& SpMatrix<N,Real>::operator+= (const SpMatrix& rkM)
{
for (int i = 0; i < N*N; i++)
m_afValues[i] += rkM.m_afValues[i];
return *this;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>& SpMatrix<N,Real>::operator-= (const SpMatrix& rkM)
{
for (int i = 0; i < N*N; i++)
m_afValues[i] -= rkM.m_afValues[i];
return *this;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>& SpMatrix<N,Real>::operator*= (Real fScalar)
{
for (int i = 0; i < N*N; i++)
m_afValues[i] *= fScalar;
return *this;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real>& SpMatrix<N,Real>::operator/= (Real fScalar)
{
int i;
if ( fScalar != (Real)0.0 )
{
Real fInvScalar = ((Real)1.0)/fScalar;
for (i = 0; i < N*N; i++)
m_afValues[i] *= fInvScalar;
}
else
{
for (i = 0; i < N*N; i++)
m_afValues[i] = Math<Real>::MAX_REAL;
}
return *this;
}
// =============================================================================
template <unsigned int N, class Real>
SpMatrix<N,Real> SpMatrix<N,Real>::Transpose () const
{
SpMatrix<N,Real> kTranspose;
for (unsigned int uiRow = 0; uiRow < N; uiRow++)
{
for (unsigned int uiCol = 0; uiCol < N; uiCol++)
kTranspose.m_afValues[ uiRow ][ uiCol ] = m_afValues[uiCol][uiRow];
}
return kTranspose;
}
// =============================================================================
template <unsigned int N, class Real>
Vector<N,Real> SpMatrix<N,Real>::operator* (const Vector<N,Real>& rkV) const
{
Vector<N,Real> kProd;
for (unsigned int uiRow = 0; uiRow < N; uiRow++)
{
kProd[iRow] = (Real)0.0;
for (unsigned int uiCol = 0; uiCol < N; uiCol++)
kProd[iRow] += m_afValues[ uiRow ][ uiCol ]*rkV[iCol];
}
return kProd;
}
// =============================================================================
template <unsigned int N, class Real>
Vector<N,Real> operator* (const Vector<N,Real>& rkV,
const SpMatrix<N,Real>& rkM)
{
Vector<N,Real> kProd;
const Real* afMValue = rkM;
Real* afPValue = kProd;
for (unsigned int uiCol = 0; uiCol < N; uiCol++)
{
afPValue[iCol] = (Real)0.0;
for (unsigned int uiRow = 0; uiRow < N; uiRow++)
afPValue[iCol] += rkV[iRow]*afMValue[iCol + N*uiRow];
}
return kProd;
}
// =============================================================================
// =============================================================================
template <class Real>
SpMatrix2<Real>::SpMatrix2 ()
{
// the matrix is uninitialized
}
// =============================================================================
template <class Real>
SpMatrix2<Real>::SpMatrix2 (const SpMatrix2& rkM)
{
memcpy(m_afEntry,rkM.m_afEntry,4*sizeof(Real));
}
// =============================================================================
template <class Real>
SpMatrix2<Real>::SpMatrix2 (const SpMatrix<2,Real>& rkM)
{
memcpy(m_afEntry,(const Real*)rkM,4*sizeof(Real));
}
// =============================================================================
template <class Real>
SpMatrix2<Real>::SpMatrix2 (Real fM00, Real fM01, Real fM10, Real fM11)
{
m_afEntry[0] = fM00;
m_afEntry[1] = fM01;
m_afEntry[2] = fM10;
m_afEntry[3] = fM11;
}
// =============================================================================
template <class Real>
SpMatrix2<Real>::SpMatrix2 (const Real afEntry[4], bool bRowMajor)
{
if ( bRowMajor )
{
memcpy(m_afEntry,afEntry,4*sizeof(Real));
}
else
{
m_afEntry[0] = afEntry[0];
m_afEntry[1] = afEntry[2];
m_afEntry[2] = afEntry[1];
m_afEntry[3] = afEntry[3];
}
}
// =============================================================================
template <class Real>
SpMatrix2<Real>::SpMatrix2 (const Vector2<Real>& rkU,
const Vector2<Real>& rkV, bool bColumns)
{
if ( bColumns )
{
m_afEntry[0] = rkU[0];
m_afEntry[1] = rkV[0];
m_afEntry[2] = rkU[1];
m_afEntry[3] = rkV[1];
}
else
{
m_afEntry[0] = rkU[0];
m_afEntry[1] = rkU[1];
m_afEntry[2] = rkV[0];
m_afEntry[3] = rkV[1];
}
}
// =============================================================================
template <class Real>
SpMatrix2<Real>::SpMatrix2 (const Vector2<Real>* akV, bool bColumns)
{
if ( bColumns )
{
m_afEntry[0] = akV[0][0];
m_afEntry[1] = akV[1][0];
m_afEntry[2] = akV[0][1];
m_afEntry[3] = akV[1][1];
}
else
{
m_afEntry[0] = akV[0][0];
m_afEntry[1] = akV[0][1];
m_afEntry[2] = akV[1][0];
m_afEntry[3] = akV[1][1];
}
}
// =============================================================================
template <class Real>
SpMatrix2<Real>::SpMatrix2 (Real fAngle)
{
m_afEntry[0] = Cosine(fAngle);
m_afEntry[1] = Sine(fAngle);
m_afEntry[2] = m_afEntry[1];
m_afEntry[3] = m_afEntry[0];
}
// =============================================================================
template <class Real>
SpMatrix2<Real>& SpMatrix2<Real>::operator= (const SpMatrix2& rkM)
{
memcpy(m_afEntry,rkM.m_afEntry,4*sizeof(Real));
return *this;
}
// =============================================================================
template <class Real>
SpMatrix2<Real>& SpMatrix2<Real>::operator= (const SpMatrix<2,Real>& rkM)
{
memcpy(m_afEntry,(const Real*)rkM,4*sizeof(Real));
return *this;
}
// =============================================================================
// ============================================================================= | [
"[email protected]"
] | |
c6fbdf3e359611b5a3b4d184991222df6693fa61 | 4bcc9806152542ab43fc2cf47c499424f200896c | /tensorflow/core/kernels/stochastic_cast_op.h | fe8f4b8cdd0be63b6e1146ac30e5ccebe6d695c3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | tensorflow/tensorflow | 906276dbafcc70a941026aa5dc50425ef71ee282 | a7f3934a67900720af3d3b15389551483bee50b8 | refs/heads/master | 2023-08-25T04:24:41.611870 | 2023-08-25T04:06:24 | 2023-08-25T04:14:08 | 45,717,250 | 208,740 | 109,943 | Apache-2.0 | 2023-09-14T20:55:50 | 2015-11-07T01:19:20 | C++ | UTF-8 | C++ | false | false | 5,022 | h | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_KERNELS_STOCHASTIC_CAST_OP_H_
#define TENSORFLOW_CORE_KERNELS_STOCHASTIC_CAST_OP_H_
#include <limits>
#include <type_traits>
#include "third_party/eigen3/Eigen/Core"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/rng_alg.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/random/random_distributions.h"
#include "tensorflow/core/platform/macros.h"
namespace tensorflow {
namespace internal {
// Base class that dispatches random algorithm, key and counter for
// StochasticCast ops.
class StochasticCastOpBase : public OpKernel {
public:
explicit StochasticCastOpBase(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override;
protected:
// Subclasses can implement this rounding kernel with assumption that random
// algorithm, key, counter have been given.
virtual void RoundOff(OpKernelContext* ctx, Algorithm alg, const Tensor& key,
const Tensor& counter, Tensor* output) = 0;
};
} // namespace internal
} // namespace tensorflow
namespace Eigen {
namespace internal {
template <typename Scalar, typename IntResultType, typename Generator>
struct StochasticRoundToIntOp {
static_assert(std::is_integral<IntResultType>::value,
"Integer type expected");
typedef tensorflow::random::UniformDistribution<Generator, Scalar>
Distribution;
const Scalar max =
static_cast<Scalar>(std::numeric_limits<IntResultType>::max());
const Scalar min =
static_cast<Scalar>(std::numeric_limits<IntResultType>::min());
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC explicit StochasticRoundToIntOp(
Generator* g)
: gen(g) {}
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Scalar
operator()(const Scalar& s) const {
if (TF_PREDICT_FALSE(Eigen::numext::isnan(s))) {
return Scalar{0};
}
if (s >= max) {
return max;
}
if (s <= min) {
return min;
}
// Already integer, doesn't need to be rounded.
if (Eigen::numext::floor(s) == s) {
return s;
}
// In order to match comparison-based algorithm on some hardware
// implementations which rounds abs(operand) up when random <
// abs(fractional), we deal with positive and negative operands differently.
// TODO(b/232442915): Revisit RNG multi-threading issue when needed.
Distribution dist;
Scalar random = dist(gen)[0];
if (s < 0) {
return Eigen::numext::floor(s + random);
} else {
return Eigen::numext::floor(s + Scalar{1} - random);
}
}
template <typename Packet>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Packet packetOp(const Packet& p) const {
constexpr size_t kPacketSize =
Eigen::internal::unpacket_traits<Packet>::size;
Scalar unpacked_random[kPacketSize];
Distribution dist;
auto const sample = dist(gen);
for (int i = 0; i < kPacketSize; i += Distribution::kResultElementCount) {
int granularity = std::min(Distribution::kResultElementCount,
static_cast<int>(kPacketSize - i));
std::copy(&sample[0], &sample[0] + granularity, &unpacked_random[i]);
}
Packet random = pload<Packet>(unpacked_random);
Packet rounded =
pselect(pcmp_eq(pfloor(p), p), p,
pselect(pcmp_lt(p, pzero(p)), pfloor(padd(p, random)),
pfloor(padd(p, psub(pset1<Packet>(1), random)))));
// Handles out of range inputs.
Packet result =
pselect(pcmp_le(pset1<Packet>(max), p), pset1<Packet>(max), rounded);
result =
pselect(pcmp_le(p, pset1<Packet>(min)), pset1<Packet>(min), result);
// Handles NaN input.
return pselect(pcmp_eq(p, p), result, pset1<Packet>(0));
}
Generator* gen;
};
template <typename Scalar, typename IntResultType, typename Generator>
struct functor_traits<
StochasticRoundToIntOp<Scalar, IntResultType, Generator>> {
enum {
Cost = 3 * NumTraits<Scalar>::AddCost,
PacketAccess =
packet_traits<Scalar>::HasCmp && packet_traits<Scalar>::HasFloor,
};
};
// TODO(b/232442915): Add support for rounding floats to lower precision floats.
} // namespace internal
} // namespace Eigen
#endif // TENSORFLOW_CORE_KERNELS_STOCHASTIC_CAST_OP_H_
| [
"[email protected]"
] | |
357cf179fe4b1c14ce2f51b15914dd90ca3a79ae | 06da6b59f1040eafd8db3f550f3aab2bcb577c7f | /tests/scene/SceneApp.h | d364643eb32569e4dcd3d732e3c8633bbc6e112b | [
"BSD-2-Clause"
] | permissive | azhirnov/FrameGraph | c254269c6642af02f8dc51014922e6713eb5cd4a | df63368150e1d5298d5f1f447727162e1725e456 | refs/heads/dev | 2023-08-28T12:14:01.165934 | 2021-01-04T19:13:30 | 2021-01-04T20:19:52 | 148,334,704 | 407 | 43 | BSD-2-Clause | 2020-07-04T15:53:37 | 2018-09-11T14:57:19 | C++ | UTF-8 | C++ | false | false | 673 | h | // Copyright (c) 2018-2020, Zhirnov Andrey. For more information see 'LICENSE'
#pragma once
#include "scene/Renderer/IRenderTechnique.h"
#include "scene/SceneManager/ISceneManager.h"
#include "scene/BaseSceneApp.h"
namespace FG
{
//
// Scene Tests Application
//
class SceneApp final : public BaseSceneApp
{
// variables
private:
RenderTechniquePtr _renderTech;
SceneManagerPtr _scene;
// methods
public:
SceneApp ();
~SceneApp ();
bool Initialize ();
// BaseSceneApp
private:
bool DrawScene () override;
// IViewport //
private:
void Prepare (ScenePreRender &) override;
void Draw (RenderQueue &) const override;
};
} // FG
| [
"[email protected]"
] | |
5d65f06d8118bcc45e58ee77ee9f6a6355964e4b | 43e01f6a496dfeb4e66fffbb9b49ed21239bddf4 | /Starter Code GLUT/sceneGraph.h | ff41dfbbeb22ea295d056c55e957864d034c0e3b | [] | no_license | jbartolozzi/CIS460_HW_2 | 9db2698bb813c9de7ea0db4676db190ce2b13867 | dd25712d92d9fb3f16e884eae74a6aa787acd138 | refs/heads/master | 2021-01-19T18:56:17.761432 | 2013-10-16T06:25:56 | 2013-10-16T06:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | h | #ifndef SCENEGRAPH
#define SCENEGRAPH
#include "node.h"
#include <iostream>
#include <fstream>
#include <stack>
class sceneGraph {
private:
enum objTypes {
CHAIR, LAMP, TABLE, FILECABINET
};
public:
vector<objTypes> objectTypes;
vector<glm::vec3> objectColors;
vector<glm::vec2> objectPositions;
vector<float> objectRotations;
vector<glm::vec3> objectsScales;
std::stack<node*> childStack;
float xSize;
float zSize;
int numObjects;
node* root;
node* currentNode;
sceneGraph(char* filename);
void selectNextNode();
char* readNextCharToken();
int readNextIntToken();
float readNextFloatToken();
glm::vec3 readNextVecToken();
void readObjBlock(char* line1, char* line2, char* line3, char* line4, char* line5);
void goToNextNode();
void setFalse(node* in);
};
#endif | [
"[email protected]"
] | |
910cfadd25835f62ddcfdc4eaefcedaae8b1321c | eb27216de2cdeb2c873487f7a641baa9bc073ad7 | /components/query_tiles/internal/tile_fetcher.cc | 7c8843eb996a39f0e3a34bde9c117becb27e2564 | [
"BSD-3-Clause"
] | permissive | romandev/chromium-1 | 2db18656579df33a8326f6032b08dd6fddc6f0e4 | a8aac214b456b6693e04b4e861d98519a56a3f53 | refs/heads/master | 2022-11-18T20:20:55.476447 | 2020-05-18T11:11:01 | 2020-05-18T11:11:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,752 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/query_tiles/internal/tile_fetcher.h"
#include <utility>
#include "components/query_tiles/internal/stats.h"
#include "net/base/url_util.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_status_code.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
namespace query_tiles {
namespace {
const char kRequestContentType[] = "application/x-protobuf";
constexpr net::NetworkTrafficAnnotationTag kQueryTilesFetcherTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("query_tiles_fetcher", R"(
semantics {
sender: "Query Tiles Fetcher"
description:
"Fetches RPC for query tiles on Android NTP and omnibox."
trigger:
"A priodic TileBackgroundTask will always be scheduled to "
"fetch RPC from server, unless the feature is disabled "
"or suspended."
data: "Country code and accepted languages will be sent via "
"the header. No user information is sent."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting: "Disabled if a non-Google search engine is used."
chrome_policy {
DefaultSearchProviderEnabled {
DefaultSearchProviderEnabled: false
}
}
}
)");
class TileFetcherImpl : public TileFetcher {
public:
TileFetcherImpl(
const GURL& url,
const std::string& country_code,
const std::string& accept_languages,
const std::string& api_key,
const std::string& experiment_tag,
const std::string& client_version,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
: url_loader_factory_(url_loader_factory) {
tile_info_request_status_ = TileInfoRequestStatus::kInit;
auto resource_request =
BuildGetRequest(url, country_code, accept_languages, api_key,
experiment_tag, client_version);
url_loader_ = network::SimpleURLLoader::Create(
std::move(resource_request), kQueryTilesFetcherTrafficAnnotation);
}
private:
// TileFetcher implementation.
void StartFetchForTiles(FinishedCallback callback) override {
// TODO(hesen): Estimate max size of response then replace to
// DownloadToString method.
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory_.get(),
base::BindOnce(&TileFetcherImpl::OnDownloadComplete,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
// Build the request to get tile info.
std::unique_ptr<network::ResourceRequest> BuildGetRequest(
const GURL& url,
const std::string& country_code,
const std::string& accept_languages,
const std::string& api_key,
const std::string& experiment_tag,
const std::string& client_version) {
auto request = std::make_unique<network::ResourceRequest>();
request->method = net::HttpRequestHeaders::kGetMethod;
request->headers.SetHeader("x-goog-api-key", api_key);
request->headers.SetHeader("X-Client-Version", client_version);
request->headers.SetHeader(net::HttpRequestHeaders::kContentType,
kRequestContentType);
request->url =
net::AppendOrReplaceQueryParameter(url, "country_code", country_code);
if (!experiment_tag.empty()) {
request->url = net::AppendOrReplaceQueryParameter(
request->url, "experiment_tag", experiment_tag);
}
if (!accept_languages.empty()) {
request->headers.SetHeader(net::HttpRequestHeaders::kAcceptLanguage,
accept_languages);
}
return request;
}
bool ShouldSuspendDueToNetError() {
auto error_code = url_loader_->NetError();
stats::RecordTileFetcherNetErrorCode(error_code);
switch (error_code) {
case net::ERR_BLOCKED_BY_ADMINISTRATOR:
return true;
default:
return false;
}
}
bool ShouldSuspend(int response_code) {
switch (response_code) {
case net::HTTP_NOT_IMPLEMENTED:
case net::HTTP_FORBIDDEN:
return true;
default:
return ShouldSuspendDueToNetError();
}
}
// Called after receiving HTTP response. Processes the response code and net
// error.
void OnDownloadComplete(FinishedCallback callback,
std::unique_ptr<std::string> response_body) {
int response_code = -1;
if (url_loader_->ResponseInfo() && url_loader_->ResponseInfo()->headers)
response_code = url_loader_->ResponseInfo()->headers->response_code();
if (response_code >= 200 && response_code < 300 && response_body) {
tile_info_request_status_ = TileInfoRequestStatus::kSuccess;
} else {
tile_info_request_status_ = ShouldSuspend(response_code)
? TileInfoRequestStatus::kShouldSuspend
: TileInfoRequestStatus::kFailure;
}
stats::RecordTileFetcherResponseCode(response_code);
std::move(callback).Run(tile_info_request_status_,
std::move(response_body));
tile_info_request_status_ = TileInfoRequestStatus::kInit;
}
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
// Simple URL loader to fetch proto from network.
std::unique_ptr<network::SimpleURLLoader> url_loader_;
// Status of the tile info request.
TileInfoRequestStatus tile_info_request_status_;
base::WeakPtrFactory<TileFetcherImpl> weak_ptr_factory_{this};
};
} // namespace
// static
std::unique_ptr<TileFetcher> TileFetcher::Create(
const GURL& url,
const std::string& country_code,
const std::string& accept_languages,
const std::string& api_key,
const std::string& experiment_tag,
const std::string& client_version,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
return std::make_unique<TileFetcherImpl>(url, country_code, accept_languages,
api_key, experiment_tag,
client_version, url_loader_factory);
}
TileFetcher::TileFetcher() = default;
TileFetcher::~TileFetcher() = default;
} // namespace query_tiles
| [
"[email protected]"
] | |
2bab41c6edb8d614eb55c38e50f48c9bbdf070e7 | 2b41b74b182e6657b0998acfce3ccbf03666618e | /algorithms/learn/red_black_tree/main.cpp | f8e98df85438b2372f19398ce9d4a70217076ad3 | [] | no_license | bruceding/leetcode | 2ec29fc66425841d7aedd1c5e867608e26a5628d | 7567cbca7e942da2c647ed10aed307cee532d6f3 | refs/heads/master | 2021-01-21T14:16:09.123170 | 2019-11-17T05:14:48 | 2019-11-17T05:14:48 | 91,822,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,863 | cpp | // red black tree code
#include <iostream>
enum tree_color {RED, BLACK};
struct TreeNode {
int data;
TreeNode *left;
TreeNode *right;
tree_color color;
TreeNode(int x):data(x),left(NULL), right(NULL), color(RED){}
};
class RedBlackBST {
private:
TreeNode *root;
TreeNode* put(TreeNode* h, int data) {
if (h == nullptr) {
// default red color
return new TreeNode(data);
}
if (h->data > data) {
h->left = put(h->left, data);
} else if (h->data < data) {
h->right = put(h->right, data);
} else {
h->data = data;
}
// rotate left node
if (Red(h->right) && !Red(h->left)) {
h = RotateLeft(h);
}
// rotate right
if (Red(h->left) && Red(h->left->left)) {
h = RotateRight(h);
}
if (Red(h->left) && Red(h->right)) {
FlipeColors(h);
}
return h;
}
bool Red(TreeNode *node) {
if (node == nullptr) {
return false;
}
return node->color == RED;
}
TreeNode *RotateLeft( TreeNode *h) {
TreeNode *x = h->right;
h->right = x->left;
x->left = h;
x->color = h->color;
h->color = RED;
return x;
}
TreeNode *RotateRight(TreeNode *h) {
TreeNode *x = h->left;
h->left = x->right;
x->right = h;
x->color = h->color;
h->color = RED;
return x;
}
void FlipeColors(TreeNode *h) {
h->color = RED;
h->left->color = BLACK;
h->right->color = BLACK;
return;
}
public:
RedBlackBST():root(nullptr) {}
TreeNode* get_root() {
return root;
}
// insert data
void insert(int data) {
root = put(root, data);
root->color = BLACK;
}
void inOrder(TreeNode* root) {
if (root == nullptr) return;
inOrder(root->left);
std::cout << root->data << "\t" << root->color << std::endl;
inOrder(root->right);
}
int Min() {
TreeNode *p = Min(root);
return p->data;
}
TreeNode *Min(TreeNode * node) {
if (node->left == nullptr) return node;
return Min(node->left);
}
// destruct func
~RedBlackBST() {
}
};
int main() {
RedBlackBST tree;
tree.insert(7);
tree.insert(3);
tree.insert(1);
tree.insert(2);
tree.insert(15);
tree.insert(9);
tree.insert(20);
tree.inOrder(tree.get_root());
std::cout << tree.Min() << std::endl;
return 0;
}
| [
"[email protected]"
] | |
0793c8e886d55134762693731710d8677f1b5e0b | 97b629e9bd4ff54f65d6d9eb2e0f2db3d8b71129 | /src/qt/blockexplorer.cpp | b3f6bb583dd46b60143a73ff63da138d980d63de | [
"MIT"
] | permissive | vencoin1/Vencoin | 825bb990b39894fd79dd8170fdda688236ea7a36 | d21154b5d8faf3d77421e1272974b27bc3094777 | refs/heads/master | 2020-05-01T04:03:37.080759 | 2019-03-23T08:27:06 | 2019-03-23T08:27:06 | 175,571,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,615 | cpp | #include "blockexplorer.h"
#include "bitcoinunits.h"
#include "chainparams.h"
#include "clientmodel.h"
#include "core_io.h"
#include "guiutil.h"
#include "main.h"
#include "net.h"
#include "txdb.h"
#include "ui_blockexplorer.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include <QDateTime>
#include <QKeyEvent>
#include <QMessageBox>
#include <set>
extern double GetDifficulty(const CBlockIndex* blockindex = NULL);
inline std::string utostr(unsigned int n)
{
return strprintf("%u", n);
}
static std::string makeHRef(const std::string& Str)
{
return "<a href=\"" + Str + "\">" + Str + "</a>";
}
static CAmount getTxIn(const CTransaction& tx)
{
if (tx.IsCoinBase())
return 0;
CAmount Sum = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
Sum += getPrevOut(tx.vin[i].prevout).nValue;
return Sum;
}
static std::string ValueToString(CAmount nValue, bool AllowNegative = false)
{
if (nValue < 0 && !AllowNegative)
return "<span>" + _("unknown") + "</span>";
QString Str = BitcoinUnits::formatWithUnit(BitcoinUnits::VEN, nValue);
if (AllowNegative && nValue > 0)
Str = '+' + Str;
return std::string("<span>") + Str.toUtf8().data() + "</span>";
}
static std::string ScriptToString(const CScript& Script, bool Long = false, bool Highlight = false)
{
if (Script.empty())
return "unknown";
CTxDestination Dest;
CBitcoinAddress Address;
if (ExtractDestination(Script, Dest) && Address.Set(Dest)) {
if (Highlight)
return "<span class=\"addr\">" + Address.ToString() + "</span>";
else
return makeHRef(Address.ToString());
} else
return Long ? "<pre>" + FormatScript(Script) + "</pre>" : _("Non-standard script");
}
static std::string TimeToString(uint64_t Time)
{
QDateTime timestamp;
timestamp.setTime_t(Time);
return timestamp.toString("yyyy-MM-dd hh:mm:ss").toUtf8().data();
}
static std::string makeHTMLTableRow(const std::string* pCells, int n)
{
std::string Result = "<tr>";
for (int i = 0; i < n; i++) {
Result += "<td class=\"d" + utostr(i) + "\">";
Result += pCells[i];
Result += "</td>";
}
Result += "</tr>";
return Result;
}
static const char* table = "<table>";
static std::string makeHTMLTable(const std::string* pCells, int nRows, int nColumns)
{
std::string Table = table;
for (int i = 0; i < nRows; i++)
Table += makeHTMLTableRow(pCells + i * nColumns, nColumns);
Table += "</table>";
return Table;
}
static std::string TxToRow(const CTransaction& tx, const CScript& Highlight = CScript(), const std::string& Prepend = std::string(), int64_t* pSum = NULL)
{
std::string InAmounts, InAddresses, OutAmounts, OutAddresses;
int64_t Delta = 0;
for (unsigned int j = 0; j < tx.vin.size(); j++) {
if (tx.IsCoinBase()) {
InAmounts += ValueToString(tx.GetValueOut());
InAddresses += "coinbase";
} else {
CTxOut PrevOut = getPrevOut(tx.vin[j].prevout);
InAmounts += ValueToString(PrevOut.nValue);
InAddresses += ScriptToString(PrevOut.scriptPubKey, false, PrevOut.scriptPubKey == Highlight).c_str();
if (PrevOut.scriptPubKey == Highlight)
Delta -= PrevOut.nValue;
}
if (j + 1 != tx.vin.size()) {
InAmounts += "<br/>";
InAddresses += "<br/>";
}
}
for (unsigned int j = 0; j < tx.vout.size(); j++) {
CTxOut Out = tx.vout[j];
OutAmounts += ValueToString(Out.nValue);
OutAddresses += ScriptToString(Out.scriptPubKey, false, Out.scriptPubKey == Highlight);
if (Out.scriptPubKey == Highlight)
Delta += Out.nValue;
if (j + 1 != tx.vout.size()) {
OutAmounts += "<br/>";
OutAddresses += "<br/>";
}
}
std::string List[8] =
{
Prepend,
makeHRef(tx.GetHash().GetHex()),
InAddresses,
InAmounts,
OutAddresses,
OutAmounts,
"",
""};
int n = sizeof(List) / sizeof(std::string) - 2;
if (!Highlight.empty()) {
List[n++] = std::string("<font color=\"") + ((Delta > 0) ? "green" : "red") + "\">" + ValueToString(Delta, true) + "</font>";
*pSum += Delta;
List[n++] = ValueToString(*pSum);
return makeHTMLTableRow(List, n);
}
return makeHTMLTableRow(List + 1, n - 1);
}
CTxOut getPrevOut(const COutPoint& out)
{
CTransaction tx;
uint256 hashBlock;
if (GetTransaction(out.hash, tx, hashBlock, true))
return tx.vout[out.n];
return CTxOut();
}
void getNextIn(const COutPoint& Out, uint256& Hash, unsigned int& n)
{
// Hash = 0;
// n = 0;
// if (paddressmap)
// paddressmap->ReadNextIn(Out, Hash, n);
}
const CBlockIndex* getexplorerBlockIndex(int64_t height)
{
std::string hex = getexplorerBlockHash(height);
uint256 hash = uint256S(hex);
return mapBlockIndex[hash];
}
std::string getexplorerBlockHash(int64_t Height)
{
std::string genesisblockhash = "0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818";
CBlockIndex* pindexBest = mapBlockIndex[chainActive.Tip()->GetBlockHash()];
if ((Height < 0) || (Height > pindexBest->nHeight)) {
return genesisblockhash;
}
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[chainActive.Tip()->GetBlockHash()];
while (pblockindex->nHeight > Height)
pblockindex = pblockindex->pprev;
return pblockindex->GetBlockHash().GetHex(); // pblockindex->phashBlock->GetHex();
}
std::string BlockToString(CBlockIndex* pBlock)
{
if (!pBlock)
return "";
CBlock block;
ReadBlockFromDisk(block, pBlock);
CAmount Fees = 0;
CAmount OutVolume = 0;
CAmount Reward = 0;
std::string TxLabels[] = {_("Hash"), _("From"), _("Amount"), _("To"), _("Amount")};
std::string TxContent = table + makeHTMLTableRow(TxLabels, sizeof(TxLabels) / sizeof(std::string));
for (unsigned int i = 0; i < block.vtx.size(); i++) {
const CTransaction& tx = block.vtx[i];
TxContent += TxToRow(tx);
CAmount In = getTxIn(tx);
CAmount Out = tx.GetValueOut();
if (tx.IsCoinBase())
Reward += Out;
else if (In < 0)
Fees = -Params().MaxMoneyOut();
else {
Fees += In - Out;
OutVolume += Out;
}
}
TxContent += "</table>";
CAmount Generated;
if (pBlock->nHeight == 0)
Generated = OutVolume;
else
Generated = GetBlockValue(pBlock->nHeight - 1);
std::string BlockContentCells[] =
{
_("Height"), itostr(pBlock->nHeight),
_("Size"), itostr(GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)),
_("Number of Transactions"), itostr(block.vtx.size()),
_("Value Out"), ValueToString(OutVolume),
_("Fees"), ValueToString(Fees),
_("Generated"), ValueToString(Generated),
_("Timestamp"), TimeToString(block.nTime),
_("Difficulty"), strprintf("%.4f", GetDifficulty(pBlock)),
_("Bits"), utostr(block.nBits),
_("Nonce"), utostr(block.nNonce),
_("Version"), itostr(block.nVersion),
_("Hash"), "<pre>" + block.GetHash().GetHex() + "</pre>",
_("Merkle Root"), "<pre>" + block.hashMerkleRoot.GetHex() + "</pre>",
// _("Hash Whole Block"), "<pre>" + block.hashWholeBlock.GetHex() + "</pre>"
// _("Miner Signature"), "<pre>" + block.MinerSignature.ToString() + "</pre>"
};
std::string BlockContent = makeHTMLTable(BlockContentCells, sizeof(BlockContentCells) / (2 * sizeof(std::string)), 2);
std::string Content;
Content += "<h2><a class=\"nav\" href=";
Content += itostr(pBlock->nHeight - 1);
Content += ">◄ </a>";
Content += _("Block");
Content += " ";
Content += itostr(pBlock->nHeight);
Content += "<a class=\"nav\" href=";
Content += itostr(pBlock->nHeight + 1);
Content += "> ►</a></h2>";
Content += BlockContent;
Content += "</br>";
/*
if (block.nHeight > getThirdHardforkBlock())
{
std::vector<std::string> votes[2];
for (int i = 0; i < 2; i++)
{
for (unsigned int j = 0; j < block.vvotes[i].size(); j++)
{
votes[i].push_back(block.vvotes[i][j].hash.ToString() + ':' + itostr(block.vvotes[i][j].n));
}
}
Content += "<h3>" + _("Votes +") + "</h3>";
Content += makeHTMLTable(&votes[1][0], votes[1].size(), 1);
Content += "</br>";
Content += "<h3>" + _("Votes -") + "</h3>";
Content += makeHTMLTable(&votes[0][0], votes[0].size(), 1);
Content += "</br>";
}
*/
Content += "<h2>" + _("Transactions") + "</h2>";
Content += TxContent;
return Content;
}
std::string TxToString(uint256 BlockHash, const CTransaction& tx)
{
CAmount Input = 0;
CAmount Output = tx.GetValueOut();
std::string InputsContentCells[] = {_("#"), _("Taken from"), _("Address"), _("Amount")};
std::string InputsContent = makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string));
std::string OutputsContentCells[] = {_("#"), _("Redeemed in"), _("Address"), _("Amount")};
std::string OutputsContent = makeHTMLTableRow(OutputsContentCells, sizeof(OutputsContentCells) / sizeof(std::string));
if (tx.IsCoinBase()) {
std::string InputsContentCells[] =
{
"0",
"coinbase",
"-",
ValueToString(Output)};
InputsContent += makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string));
} else
for (unsigned int i = 0; i < tx.vin.size(); i++) {
COutPoint Out = tx.vin[i].prevout;
CTxOut PrevOut = getPrevOut(tx.vin[i].prevout);
if (PrevOut.nValue < 0)
Input = -Params().MaxMoneyOut();
else
Input += PrevOut.nValue;
std::string InputsContentCells[] =
{
itostr(i),
"<span>" + makeHRef(Out.hash.GetHex()) + ":" + itostr(Out.n) + "</span>",
ScriptToString(PrevOut.scriptPubKey, true),
ValueToString(PrevOut.nValue)};
InputsContent += makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string));
}
uint256 TxHash = tx.GetHash();
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& Out = tx.vout[i];
uint256 HashNext = uint256S("0");
unsigned int nNext = 0;
bool fAddrIndex = false;
getNextIn(COutPoint(TxHash, i), HashNext, nNext);
std::string OutputsContentCells[] =
{
itostr(i),
(HashNext == uint256S("0")) ? (fAddrIndex ? _("no") : _("unknown")) : "<span>" + makeHRef(HashNext.GetHex()) + ":" + itostr(nNext) + "</span>",
ScriptToString(Out.scriptPubKey, true),
ValueToString(Out.nValue)};
OutputsContent += makeHTMLTableRow(OutputsContentCells, sizeof(OutputsContentCells) / sizeof(std::string));
}
InputsContent = table + InputsContent + "</table>";
OutputsContent = table + OutputsContent + "</table>";
std::string Hash = TxHash.GetHex();
std::string Labels[] =
{
_("In Block"), "",
_("Size"), itostr(GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)),
_("Input"), tx.IsCoinBase() ? "-" : ValueToString(Input),
_("Output"), ValueToString(Output),
_("Fees"), tx.IsCoinBase() ? "-" : ValueToString(Input - Output),
_("Timestamp"), "",
_("Hash"), "<pre>" + Hash + "</pre>",
};
// std::map<uint256, CBlockIndex*>::iterator iter = mapBlockIndex.find(BlockHash);
BlockMap::iterator iter = mapBlockIndex.find(BlockHash);
if (iter != mapBlockIndex.end()) {
CBlockIndex* pIndex = iter->second;
Labels[0 * 2 + 1] = makeHRef(itostr(pIndex->nHeight));
Labels[5 * 2 + 1] = TimeToString(pIndex->nTime);
}
std::string Content;
Content += "<h2>" + _("Transaction") + " <span>" + Hash + "</span></h2>";
Content += makeHTMLTable(Labels, sizeof(Labels) / (2 * sizeof(std::string)), 2);
Content += "</br>";
Content += "<h3>" + _("Inputs") + "</h3>";
Content += InputsContent;
Content += "</br>";
Content += "<h3>" + _("Outputs") + "</h3>";
Content += OutputsContent;
return Content;
}
std::string AddressToString(const CBitcoinAddress& Address)
{
std::string TxLabels[] =
{
_("Date"),
_("Hash"),
_("From"),
_("Amount"),
_("To"),
_("Amount"),
_("Delta"),
_("Balance")};
std::string TxContent = table + makeHTMLTableRow(TxLabels, sizeof(TxLabels) / sizeof(std::string));
std::set<COutPoint> PrevOuts;
/*
CScript AddressScript;
AddressScript.SetDestination(Address.Get());
CAmount Sum = 0;
bool fAddrIndex = false;
if (!fAddrIndex)
return ""; // it will take too long to find transactions by address
else
{
std::vector<CDiskTxPos> Txs;
paddressmap->GetTxs(Txs, AddressScript.GetID());
BOOST_FOREACH (const CDiskTxPos& pos, Txs)
{
CTransaction tx;
CBlock block;
uint256 bhash = block.GetHash();
GetTransaction(pos.nTxOffset, tx, bhash);
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
continue;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
continue;
std::string Prepend = "<a href=\"" + itostr(pindex->nHeight) + "\">" + TimeToString(pindex->nTime) + "</a>";
TxContent += TxToRow(tx, AddressScript, Prepend, &Sum);
}
}
*/
TxContent += "</table>";
std::string Content;
Content += "<h1 style='color:#000000;'>" + _("Transactions to/from") + " <span>" + Address.ToString() + "</span></h1>";
Content += TxContent;
return Content;
}
BlockExplorer::BlockExplorer(QWidget* parent) : QMainWindow(parent),
ui(new Ui::BlockExplorer),
m_NeverShown(true),
m_HistoryIndex(0)
{
ui->setupUi(this);
this->setStyleSheet(GUIUtil::loadStyleSheet());
connect(ui->pushSearch, SIGNAL(released()), this, SLOT(onSearch()));
connect(ui->content, SIGNAL(linkActivated(const QString&)), this, SLOT(goTo(const QString&)));
connect(ui->back, SIGNAL(released()), this, SLOT(back()));
connect(ui->forward, SIGNAL(released()), this, SLOT(forward()));
}
BlockExplorer::~BlockExplorer()
{
delete ui;
}
void BlockExplorer::keyPressEvent(QKeyEvent* event)
{
switch ((Qt::Key)event->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
onSearch();
return;
default:
return QMainWindow::keyPressEvent(event);
}
}
void BlockExplorer::showEvent(QShowEvent*)
{
if (m_NeverShown) {
m_NeverShown = false;
CBlockIndex* pindexBest = mapBlockIndex[chainActive.Tip()->GetBlockHash()];
setBlock(pindexBest);
QString text = QString("%1").arg(pindexBest->nHeight);
ui->searchBox->setText(text);
m_History.push_back(text);
updateNavButtons();
if (!GetBoolArg("-txindex", false)) {
QString Warning = tr("Not all transactions will be shown. To view all transactions you need to set txindex=1 in the configuration file (venture.conf).");
QMessageBox::warning(this, "VENTURE Core Blockchain Explorer", Warning, QMessageBox::Ok);
}
}
}
bool BlockExplorer::switchTo(const QString& query)
{
bool IsOk;
int64_t AsInt = query.toInt(&IsOk);
// If query is integer, get hash from height
if (IsOk && AsInt >= 0 && AsInt <= chainActive.Tip()->nHeight) {
std::string hex = getexplorerBlockHash(AsInt);
uint256 hash = uint256S(hex);
CBlockIndex* pIndex = mapBlockIndex[hash];
if (pIndex) {
setBlock(pIndex);
return true;
}
}
// If the query is not an integer, assume it is a block hash
uint256 hash = uint256S(query.toUtf8().constData());
// std::map<uint256, CBlockIndex*>::iterator iter = mapBlockIndex.find(hash);
BlockMap::iterator iter = mapBlockIndex.find(hash);
if (iter != mapBlockIndex.end()) {
setBlock(iter->second);
return true;
}
// If the query is neither an integer nor a block hash, assume a transaction hash
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock, true)) {
setContent(TxToString(hashBlock, tx));
return true;
}
// If the query is not an integer, nor a block hash, nor a transaction hash, assume an address
CBitcoinAddress Address;
Address.SetString(query.toUtf8().constData());
if (Address.IsValid()) {
std::string Content = AddressToString(Address);
if (Content.empty())
return false;
setContent(Content);
return true;
}
return false;
}
void BlockExplorer::goTo(const QString& query)
{
if (switchTo(query)) {
ui->searchBox->setText(query);
while (m_History.size() > m_HistoryIndex + 1)
m_History.pop_back();
m_History.push_back(query);
m_HistoryIndex = m_History.size() - 1;
updateNavButtons();
}
}
void BlockExplorer::onSearch()
{
goTo(ui->searchBox->text());
}
void BlockExplorer::setBlock(CBlockIndex* pBlock)
{
setContent(BlockToString(pBlock));
}
void BlockExplorer::setContent(const std::string& Content)
{
QString CSS = "body {font-size:12px; color:#000000; bgcolor:#fafafa;}\n a, span { font-family: monospace; }\n span.addr {color:#000000; font-weight: bold;}\n table tr td {padding: 3px; border: 1px solid black; background-color: #fafafa;}\n td.d0 {font-weight: bold; color:#000000;}\n h2, h3 { white-space:nowrap; color:#000000;}\n a { color:#000000; text-decoration:none; }\n a.nav {color:#000000;}\n";
QString FullContent = "<html><head><style type=\"text/css\">" + CSS + "</style></head>" + "<body>" + Content.c_str() + "</body></html>";
// printf(FullContent.toUtf8());
ui->content->setText(FullContent);
}
void BlockExplorer::back()
{
int NewIndex = m_HistoryIndex - 1;
if (0 <= NewIndex && NewIndex < m_History.size()) {
m_HistoryIndex = NewIndex;
ui->searchBox->setText(m_History[NewIndex]);
switchTo(m_History[NewIndex]);
updateNavButtons();
}
}
void BlockExplorer::forward()
{
int NewIndex = m_HistoryIndex + 1;
if (0 <= NewIndex && NewIndex < m_History.size()) {
m_HistoryIndex = NewIndex;
ui->searchBox->setText(m_History[NewIndex]);
switchTo(m_History[NewIndex]);
updateNavButtons();
}
}
void BlockExplorer::updateNavButtons()
{
ui->back->setEnabled(m_HistoryIndex - 1 >= 0);
ui->forward->setEnabled(m_HistoryIndex + 1 < m_History.size());
}
| [
"[email protected]"
] | |
de53397690f65a20bfbfa83e0a321f6fec801467 | 612325535126eaddebc230d8c27af095c8e5cc2f | /src/net/http2/http2_constants_test_util.h | 774e23eae5065a54540b5d41794e8620d0e2e95d | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/proto-quic_1V94 | 1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673 | feee14d96ee95313f236e0f0e3ff7719246c84f7 | refs/heads/master | 2023-04-01T14:36:53.888576 | 2019-10-17T02:23:04 | 2019-10-17T02:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_HTTP2_HTTP2_CONSTANTS_TEST_UTIL_H_
#define NET_HTTP2_HTTP2_CONSTANTS_TEST_UTIL_H_
#include <vector>
#include "net/http2/http2_constants.h"
namespace net {
namespace test {
// Returns a vector of all supported frame types.
std::vector<Http2FrameType> AllHttp2FrameTypes();
// Returns a vector of all supported frame flags for the specified
// frame type. Empty if the type is unknown.
std::vector<Http2FrameFlag> AllHttp2FrameFlagsForFrameType(Http2FrameType type);
// Returns a vector of all supported RST_STREAM and GOAWAY error codes.
std::vector<Http2ErrorCode> AllHttp2ErrorCodes();
// Returns a vector of all supported parameters in SETTINGS frames.
std::vector<Http2SettingsParameter> AllHttp2SettingsParameters();
// Returns a mask of flags supported for the specified frame type. Returns
// zero for unknown frame types.
uint8_t KnownFlagsMaskForFrameType(Http2FrameType type);
// Returns a mask of flag bits known to be invalid for the frame type.
// For unknown frame types, the mask is zero; i.e., we don't know that any
// are invalid.
uint8_t InvalidFlagMaskForFrameType(Http2FrameType type);
} // namespace test
} // namespace net
#endif // NET_HTTP2_HTTP2_CONSTANTS_TEST_UTIL_H_
| [
"[email protected]"
] | |
555b5fddc1497bc0ed1508a0e71c6135aea8681c | 2b203d0fdeeaccc81a04f619fdb1976bda90b63b | /include/hermes/VM/MallocGC.h | b28dff92265e61f74cc12419bdc3cd707e7ba214 | [
"MIT"
] | permissive | FrenchYeti/hermes | f06dcaa72776da02952584dc101073b213a3d89c | 98f5028619294b6b14cddf5903a0f831d0edef9c | refs/heads/main | 2023-09-03T16:39:26.634066 | 2021-11-13T15:58:23 | 2021-11-13T15:59:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,890 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef HERMES_VM_MALLOCGC_H
#define HERMES_VM_MALLOCGC_H
#include "hermes/Public/GCConfig.h"
#include "hermes/VM/GCBase.h"
#include "hermes/VM/GCCell.h"
#include "hermes/VM/VMExperiments.h"
#include "llvh/ADT/DenseMap.h"
#include "llvh/ADT/DenseSet.h"
#include "llvh/Support/raw_ostream.h"
#include <deque>
#include <limits>
#include <vector>
namespace hermes {
namespace vm {
class MallocGC final : public GCBase {
class CellHeader {
/// If true, then this cell is live. If this is false at the end of a
/// collection, then this cell can be freed. Defaults to false when not in
/// the middle of a collection.
bool marked_ = false;
#ifdef HERMESVM_SANITIZE_HANDLES
/// If non-null, contains a pointer to the new location where this cell will
/// be after the collection is over.
/// Only used in handle sanitization when pointers are moved.
CellHeader *forwardingPtr_ = nullptr;
#endif
/// Storage of the GCCell data is past this point. Needs to be aligned to
/// the alignment of the heap.
static_assert(
alignof(GCCell) <= HeapAlign,
"GCCell's alignment exceeds the alignment requirement of the heap");
alignas(HeapAlign) uint8_t data_[0];
public:
bool isMarked() const {
return marked_;
}
/// Mark a cell as live. Set its new location to \p newLocation.
void mark() {
assert(!isMarked() && "Marking an already marked pointer");
marked_ = true;
}
void markWithForwardingPointer(CellHeader *newLocation) {
mark();
#ifdef HERMESVM_SANITIZE_HANDLES
forwardingPtr_ = newLocation;
#else
llvm_unreachable(
"Trying to add a forwarding pointer outside of handle-san mode");
#endif
}
void unmark() {
assert(isMarked() && "Unmarking an already unmarked pointer");
marked_ = false;
#ifdef HERMESVM_SANITIZE_HANDLES
forwardingPtr_ = nullptr;
#endif
}
GCCell *data() {
return reinterpret_cast<GCCell *>(data_);
}
const GCCell *data() const {
return reinterpret_cast<const GCCell *>(data_);
}
CellHeader *getForwardingPointer() {
assert(isMarked() && "Getting forwarding pointer from unmarked pointer");
#ifdef HERMESVM_SANITIZE_HANDLES
assert(forwardingPtr_ && "Accessing a null forwarding pointer");
return forwardingPtr_;
#else
llvm_unreachable(
"Can't get a forwarding pointer outside of handle-san mode");
#endif
}
static CellHeader *from(GCCell *cell) {
return reinterpret_cast<CellHeader *>(
reinterpret_cast<char *>(cell) - offsetof(CellHeader, data_));
}
static const CellHeader *from(const GCCell *cell) {
return reinterpret_cast<const CellHeader *>(
reinterpret_cast<const char *>(cell) - offsetof(CellHeader, data_));
}
};
/// pointers_ stores all of the objects managed by the GC. If a pointer is not
/// in this set, then it is not a GC pointer, and thus invalid to be collected
/// or marked.
llvh::DenseSet<CellHeader *> pointers_;
/// newPointers_ is the set of live objects at the end of a collection.
/// Pointers are moved from pointers_ to this as they are discovered to be
/// alive.
/// This should be empty between collections.
llvh::DenseSet<CellHeader *> newPointers_;
/// maxSize_ is the absolute highest amount of memory that MallocGC is allowed
/// to allocate.
const gcheapsize_t maxSize_;
/// sizeLimit_ is the point at which a collection should be run.
gcheapsize_t sizeLimit_;
/// allocatedBytes_ is the current amount of memory stored in the heap.
gcheapsize_t allocatedBytes_{0};
public:
/// See comment in GCBase.
class Size final {
public:
explicit Size(const GCConfig &gcConfig)
: Size(gcConfig.getMinHeapSize(), gcConfig.getMaxHeapSize()) {}
Size(gcheapsize_t min, gcheapsize_t max) : min_(min), max_(max) {}
gcheapsize_t min() const {
return min_;
}
gcheapsize_t max() const {
return max_;
}
gcheapsize_t storageFootprint() const;
gcheapsize_t minStorageFootprint() const;
private:
gcheapsize_t min_;
gcheapsize_t max_;
};
MallocGC(
GCCallbacks *gcCallbacks,
PointerBase *pointerBase,
const GCConfig &gcConfig,
std::shared_ptr<CrashManager> crashMgr,
std::shared_ptr<StorageProvider> provider,
experiments::VMExperimentFlags vmExperimentFlags);
~MallocGC();
/// Checks if a requested \p size can fit in the heap. If it can't, a
/// collection occurs. If it still can't after the collection, OOM is
/// declared.
void collectBeforeAlloc(std::string cause, uint32_t size);
/// Allocate a new cell of the specified size \p size by calling alloc.
/// Instantiate an object of type T with constructor arguments \p args in the
/// newly allocated cell.
/// \return a pointer to the newly created object in the GC heap.
template <
typename T,
bool fixedSize = true,
HasFinalizer hasFinalizer = HasFinalizer::No,
LongLived longLived = LongLived::Yes,
class... Args>
inline T *makeA(uint32_t size, Args &&...args);
/// Returns whether an external allocation of the given \p size fits
/// within the maximum heap size. (Note that this does not guarantee that the
/// allocation will "succeed" -- the size plus the used() of the heap may
/// still exceed the max heap size. But if it fails, the allocation can never
/// succeed.)
bool canAllocExternalMemory(uint32_t size) override;
/// Collect all of the dead objects and symbols in the heap. Also invalidate
/// weak pointers that point to dead objects.
void collect(std::string cause, bool canEffectiveOOM = false) override;
static constexpr uint32_t minAllocationSizeImpl() {
// MallocGC imposes no limit on individual allocations.
return 0;
}
static constexpr uint32_t maxAllocationSizeImpl() {
// MallocGC imposes no limit on individual allocations.
return std::numeric_limits<uint32_t>::max();
}
/// Run the finalizers for all heap objects.
void finalizeAll() override;
/// \return true iff this is collecting the entire heap, or false if it is
/// only a portion of the heap.
/// \pre Assumes inGC() is true, or else this has no meaning.
bool inFullCollection() const {
return true;
}
#ifndef NDEBUG
/// See comment in GCBase.
bool calledByGC() const override {
return inGC();
}
/// \return true iff the pointer \p p is controlled by this GC.
bool validPointer(const void *p) const override;
bool dbgContains(const void *p) const override;
/// Returns true if \p cell is the most-recently allocated finalizable object.
bool isMostRecentFinalizableObj(const GCCell *cell) const override;
#endif
/// Same as in superclass GCBase.
virtual void createSnapshot(llvh::raw_ostream &os) override;
void writeBarrier(const GCHermesValue *, HermesValue) {}
void writeBarrier(const GCSmallHermesValue *, SmallHermesValue) {}
void writeBarrier(const GCPointerBase *, const GCCell *) {}
void constructorWriteBarrier(const GCHermesValue *, HermesValue) {}
void constructorWriteBarrier(const GCSmallHermesValue *, SmallHermesValue) {}
void constructorWriteBarrier(const GCPointerBase *, const GCCell *) {}
void writeBarrierRange(const GCHermesValue *, uint32_t) {}
void writeBarrierRange(const GCSmallHermesValue *, uint32_t) {}
void constructorWriteBarrierRange(const GCHermesValue *, uint32_t) {}
void constructorWriteBarrierRange(const GCSmallHermesValue *, uint32_t) {}
void snapshotWriteBarrier(const GCHermesValue *) {}
void snapshotWriteBarrier(const GCSmallHermesValue *) {}
void snapshotWriteBarrier(const GCPointerBase *) {}
void snapshotWriteBarrier(const GCSymbolID *) {}
void snapshotWriteBarrierRange(const GCHermesValue *, uint32_t) {}
void snapshotWriteBarrierRange(const GCSmallHermesValue *, uint32_t) {}
void weakRefReadBarrier(GCCell *) {}
void weakRefReadBarrier(HermesValue) {}
void getHeapInfo(HeapInfo &info) override;
void getHeapInfoWithMallocSize(HeapInfo &info) override;
void getCrashManagerHeapInfo(CrashManager::HeapInformation &info) override;
std::string getKindAsStr() const override;
/// @name Weak references
/// @{
/// Allocate a weak pointer slot for the value given.
/// \pre \p init should not be empty or a native value.
WeakRefSlot *allocWeakSlot(HermesValue init) override;
/// The largest the size of this heap could ever grow to.
size_t maxSize() const {
return maxSize_;
}
/// Iterate over all objects in the heap, and call \p callback on them.
/// \param callback A function to call on each found object.
void forAllObjs(const std::function<void(GCCell *)> &callback) override;
static bool classof(const GCBase *gc) {
return gc->getKind() == HeapKind::MallocGC;
}
/// @}
private:
#ifdef HERMES_SLOW_DEBUG
void checkWellFormed();
void clearUnmarkedPropertyMaps();
#endif
/// Allocate an object in the GC controlled heap with the size to allocate
/// given by \p size.
template <
bool fixedSizeIgnored = true,
HasFinalizer hasFinalizer = HasFinalizer::No>
inline void *alloc(uint32_t size);
/// Initialize a cell with the required basic data for any cell.
inline void initCell(GCCell *cell, uint32_t size);
/// Free a weak pointer slot, which invalidates it.
void freeWeakSlot(WeakRefSlot *slot);
/// See \c GCBase::printStats.
void printStats(JSONEmitter &json) override;
/// Reset the statistics used for reporting GC information.
void resetStats();
/// Sets all weak references to unmarked in preparation for a collection.
void resetWeakReferences();
struct MarkingAcceptor;
class SkipWeakRefsMarkingAcceptor;
struct FullMSCUpdateWeakRootsAcceptor;
/// Continually pops elements from the mark stack of \p acceptor and
/// scans their pointer fields. If such a field points to an
/// unmarked object, mark it and push it on the mark stack.
void drainMarkStack(MarkingAcceptor &acceptor);
/// In the first phase of marking, before this is called, we treat
/// JSWeakMaps specially: when we mark a reachable JSWeakMap, we do
/// not mark from it, but rather save a pointer to it in a vector.
/// Then we call this method, which finds the keys that are
/// reachable, and marks transitively from the corresponding value.
/// This is done carefully, to reach a correct global transitive
/// closure, in cases where keys are reachable only via values of
/// other keys. When this marking is done, entries with unreachable
/// keys are cleared. Normal WeakRef processing at the end of GC
/// will delete the cleared entries from the map.
void completeWeakMapMarking(MarkingAcceptor &acceptor);
/// Update all of the weak references and invalidate the ones that point to
/// dead objects.
void updateWeakReferences();
};
/// @name Inline implementations
/// @{
template <bool fixedSizeIgnored, HasFinalizer hasFinalizer>
inline void *MallocGC::alloc(uint32_t size) {
assert(noAllocLevel_ == 0 && "no alloc allowed right now");
assert(
isSizeHeapAligned(size) &&
"Call to alloc must use a size aligned to HeapAlign");
if (shouldSanitizeHandles()) {
collectBeforeAlloc(kHandleSanCauseForAnalytics, size);
}
// Use subtraction to prevent overflow.
if (LLVM_UNLIKELY(size > sizeLimit_ - allocatedBytes_)) {
collectBeforeAlloc(kNaturalCauseForAnalytics, size);
}
// Add space for the header.
auto *header = new (checkedMalloc(size + sizeof(CellHeader))) CellHeader();
GCCell *mem = header->data();
initCell(mem, size);
// Add to the set of pointers owned by the GC.
pointers_.insert(header);
allocatedBytes_ += size;
totalAllocatedBytes_ += size;
#ifndef NDEBUG
++numAllocatedObjects_;
#endif
return mem;
}
inline bool MallocGC::canAllocExternalMemory(uint32_t size) {
return size <= maxSize_;
}
template <
typename T,
bool fixedSize,
HasFinalizer hasFinalizer,
LongLived longLived,
class... Args>
inline T *MallocGC::makeA(uint32_t size, Args &&...args) {
assert(
isSizeHeapAligned(size) &&
"Call to makeA must use a size aligned to HeapAlign");
// Since there is no old generation in this collector, always forward to the
// normal allocation.
void *mem = alloc<fixedSize, hasFinalizer>(size);
return new (mem) T(std::forward<Args>(args)...);
}
inline void MallocGC::initCell(GCCell *cell, uint32_t size) {
#ifndef NDEBUG
// For debugging, fill with a dead value.
std::fill_n(reinterpret_cast<char *>(cell), size, kInvalidHeapValue);
#endif
}
/// @}
} // namespace vm
} // namespace hermes
#endif
| [
"[email protected]"
] | |
1b56d62609e6ac71545fe99677662a4681dc9561 | dc23eb8e14659ab8bb62001a3b3323cb50c2a8ef | /system/iorap/src/inode2filename/search_directories.h | 8156574f753a6a9ec626c92f00a7113369271a4a | [] | no_license | wudeven/cells-android10 | e49c0c830da7041313289349e160385df5d12ef8 | d18dfa3ab597a37b8b71a14f094ba5b8afc75a93 | refs/heads/master | 2023-08-16T06:47:55.804251 | 2021-10-16T05:41:01 | 2021-10-16T05:41:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,044 | h | // Copyright (C) 2018 The Android Open Source Project
//
// 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 IORAP_SRC_INODE2FILENAME_SEARCH_DIRECTORIES_H_
#define IORAP_SRC_INODE2FILENAME_SEARCH_DIRECTORIES_H_
#include "common/expected.h"
#include "inode2filename/inode.h"
#include "inode2filename/system_call.h"
#include <fruit/fruit.h>
#include <rxcpp/rx.hpp>
namespace iorap::inode2filename {
// Tuple of (Inode -> (Filename|Errno))
struct InodeResult {
// We set this error when all root directories have been searched and
// yet we still could not find a corresponding filename for the inode under search.
static constexpr int kCouldNotFindFilename = -ENOENT;
Inode inode;
// Value: Contains the filename (with a root directory as a prefix).
// Error: Contains the errno, usually -ENOENT or perhaps a security error.
iorap::expected<std::string /*filename*/, int /*errno*/> data;
static InodeResult makeSuccess(Inode inode, std::string filename) {
return InodeResult{inode, std::move(filename)};
}
static InodeResult makeFailure(Inode inode, int err_no) {
return InodeResult{inode, iorap::unexpected{err_no}};
}
constexpr operator bool() const {
return data.has_value();
}
};
enum class SearchMode {
// Test modes:
kInProcessDirect, // Execute the code directly.
kInProcessIpc, // Execute code via IPC layer using multiple threads.
// Shipping mode:
kOutOfProcessIpc, // Execute code via fork+exec with IPC.
// Note: in-process system-wide stat(2)/readdir/etc is blocked by selinux.
// Attempting to call the test modes will fail with -EPERM.
//
// Use fork+exec mode in shipping configurations, which spawns inode2filename
// as a separate command.
};
struct SearchDirectories {
// Type-erased subset of rxcpp::connectable_observable<?>
struct RxAnyConnectable {
// Connects to the underlying observable.
//
// This kicks off the graph, streams begin emitting items.
// This method will block until all items have been fully emitted
// and processed by any subscribers.
virtual void connect() = 0;
virtual ~RxAnyConnectable(){}
};
// Create a cold observable of inode results (a lazy stream) corresponding
// to the inode search list.
//
// A depth-first search is done on each of the root directories (in order),
// until all inodes have been found (or until all directories have been exhausted).
//
// Some internal errors may occur during emission that aren't part of an InodeResult;
// these will be sent to the error logcat and dropped.
//
// Calling this function does not begin the search.
// The returned observable will begin the search after subscribing to it.
//
// The emitted InodeResult stream has these guarantees:
// - All inodes in inode_list will eventually be emitted exactly once in an InodeResult
// - When all inodes are found, directory traversal is halted.
// - The order of emission can be considered arbitrary.
//
// Lifetime rules:
// - The observable must be fully consumed before deleting any of the SearchDirectory's
// borrowed constructor parameters (e.g. the SystemCall).
// - SearchDirectory itself can be deleted at any time after creating an observable.
rxcpp::observable<InodeResult>
FindFilenamesFromInodes(std::vector<std::string> root_directories,
std::vector<Inode> inode_list,
SearchMode mode);
// Create a cold observable of inode results (a lazy stream) corresponding
// to the inode search list.
//
// A depth-first search is done on each of the root directories (in order),
// until all inodes have been found (or until all directories have been exhausted).
//
// Some internal errors may occur during emission that aren't part of an InodeResult;
// these will be sent to the error logcat and dropped.
//
// Calling this function does not begin the search.
// The returned observable will begin the search after subscribing to it.
//
// The emitted InodeResult stream has these guarantees:
// - All inodes in inode_list will eventually be emitted exactly once in an InodeResult
// - When all inodes are found, directory traversal is halted.
// - The order of emission can be considered arbitrary.
//
// Lifetime rules:
// - The observable must be fully consumed before deleting any of the SearchDirectory's
// borrowed constructor parameters (e.g. the SystemCall).
// - SearchDirectory itself can be deleted at any time after creating an observable.
std::pair<rxcpp::observable<InodeResult>, std::unique_ptr<RxAnyConnectable>>
FindFilenamesFromInodesPair(std::vector<std::string> root_directories,
std::vector<Inode> inode_list,
SearchMode mode);
// Any borrowed parameters here can also be borrowed by the observables returned by the above
// member functions.
//
// The observables must be fully consumed within the lifetime of the borrowed parameters.
INJECT(SearchDirectories(borrowed<SystemCall*> system_call))
: system_call_(system_call) {}
// TODO: is there a way to get rid of this second RxAnyConnectable parameter?
private:
// This gets passed around to lazy lambdas, so we must finish consuming any observables
// before the injected system call is deleted.
borrowed<SystemCall*> system_call_;
};
} // namespace iorap::inode2filename
#endif // IORAP_SRC_INODE2FILENAME_SEARCH_DIRECTORIES_H_
| [
"[email protected]"
] | |
885f2ad3ec16e4e34bb3fedd8f50bc6ca4fd8248 | 8535d93ba5dce18cd7eb210a839336479a4fa1ae | /tensorflow/compiler/mlir/tfrt/benchmarks/reduction_benchmark.h | 812d31b4db92233c7b3980fbd1e92f44f14da3a1 | [
"Apache-2.0",
"MIT",
"BSD-2-Clause"
] | permissive | songshan0321/tensorflow | 3ea899db86ac771dcd9379d73be21597a8013ee0 | 6f6b2c49b816255eee701c204edfadf741818c70 | refs/heads/master | 2023-08-14T01:23:51.977409 | 2021-09-28T06:36:46 | 2021-09-28T06:43:06 | 411,170,493 | 0 | 0 | Apache-2.0 | 2021-09-28T06:57:36 | 2021-09-28T06:57:35 | null | UTF-8 | C++ | false | false | 11,025 | h | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_MLIR_TFRT_BENCHMARKS_REDUCTION_BENCHMARK_H_
#define TENSORFLOW_COMPILER_MLIR_TFRT_BENCHMARKS_REDUCTION_BENCHMARK_H_
#include "tensorflow/compiler/mlir/tfrt/benchmarks/benchmark.h"
namespace tensorflow {
// Use type aliases compatible with MLIR type names.
using f32 = float;
ABSL_CONST_INIT extern const bool kStatic;
ABSL_CONST_INIT extern const bool kDynamic;
// This header is a part of the library with private visibility and will be
// used only to build benchmarks for different functions in this folder, so
// it is ok to put convenience using-declarations here.
//
using ::llvm::ArrayRef;
using ::llvm::SmallVector;
using ::llvm::StringRef;
using ::tfrt::AsyncValue;
using ::tfrt::AsyncValuePtr;
using ::tfrt::HostContext;
using ::tfrt::RCReference;
using ::tfrt::RemainingResults;
using ::tfrt::RequestContext;
using ::tfrt::RequestContextBuilder;
using ::tfrt::cpu::jit::Executable;
using ::tfrt::cpu::jit::JitExecutable;
using ::tfrt::cpu::jit::MemrefDesc;
using ::tfrt::cpu::jit::ReturnValueConverter;
// -------------------------------------------------------------------------- //
// Run benchmark by compiling MLIR function using TFRT CPURT API.
// -------------------------------------------------------------------------- //
struct MlirSpec {
MlirSpec(StringRef op_name, StringRef element_type,
SmallVector<bool, 2> input_dynamic,
SmallVector<int32_t, 2> dims_to_reduce)
: op_name(op_name),
element_type(element_type),
input_dynamic(std::move(input_dynamic)),
dims_to_reduce(std::move(dims_to_reduce)) {}
StringRef op_name;
StringRef element_type;
SmallVector<bool, 2> input_dynamic;
SmallVector<int32, 2> dims_to_reduce;
};
std::string GetIR(StringRef op_name, ArrayRef<int64_t> input_shape,
ArrayRef<int64_t> output_shape,
ArrayRef<int32_t> dims_to_reduce, StringRef element_type);
template <typename T, int INPUT_RANK>
void RunReductionMlirBenchmark(::testing::benchmark::State& state,
size_t num_threads, const MlirSpec& spec) {
// Input and output shapes to generate IR.
SmallVector<int64_t, 2> mlir_input_shape, mlir_output_shape;
// Compute input/output shapes and the number of elements.
std::array<ssize_t, INPUT_RANK> input_shape;
int64_t num_elements = 1;
for (int i = 0; i < INPUT_RANK; ++i) {
input_shape[i] = state.range(i);
num_elements *= state.range(i);
mlir_input_shape.push_back(spec.input_dynamic[i] ? kDynSize
: state.range(i));
if (llvm::find(spec.dims_to_reduce, i) == spec.dims_to_reduce.end())
mlir_output_shape.push_back(mlir_input_shape[i]);
}
std::unique_ptr<HostContext> host =
num_threads > 0 ? CreateMultiThreadedHostContext(num_threads)
: CreateSingleThreadedHostContext();
// Compile JIT executable.
auto mlir_input = GetIR(spec.op_name, mlir_input_shape, mlir_output_shape,
spec.dims_to_reduce, spec.element_type);
TfCpuRtPipelineOptions tf_cpurt_opts;
tf_cpurt_opts.codegen_strategy = true;
JitExecutable& jit_executable =
CreateJitExecutable(*host, mlir_input, "main",
/*lower_from_tensorflow=*/true, tf_cpurt_opts);
// Build an ExecutionContext from the HostContext.
llvm::Expected<RCReference<RequestContext>> req_ctx =
RequestContextBuilder(host.get(), /*resource_context=*/nullptr).build();
tfrt::ExecutionContext exec_ctx(std::move(*req_ctx));
// Generate random input data.
Eigen::Tensor<T, INPUT_RANK, Eigen::RowMajor> input =
GenRandomTensor<T, INPUT_RANK>(input_shape);
std::array<MemrefDesc, 1> operands = {TensorToMemrefDesc(input)};
auto result_values = std::array<RCReference<AsyncValue>, 2>{{}};
RemainingResults results(result_values);
// Free memory owned by the returned memrefs.
ReturnValueConverter<ResultConversionCtx> converter(results);
converter.AddConversion(FreeReturnedMemref);
// Get an executable that might be specialized to the operands.
AsyncValuePtr<Executable> executable =
jit_executable.GetExecutable(operands, exec_ctx);
// Wait for the compilation completion.
host->Await({executable.CopyRef()});
CHECK(!executable.IsError())
<< "Failed to get executable: " << StrCat(executable.GetError());
CHECK(!executable->IsAsync()) << "async results are not supported";
// Initialize call frame with MemrefDesc operands.
Executable::CallFrame call_frame;
if (auto err =
executable->InitializeCallFrame(operands, &call_frame, nullptr))
LOG(FATAL) << "Failed to initialize call frame";
for (auto s : state) {
executable->Execute(call_frame, exec_ctx);
if (auto err = executable->ReturnResults(converter, &call_frame))
LOG(FATAL) << "Failed to return compiled kernel results";
}
state.SetItemsProcessed(static_cast<int64_t>(state.iterations()) *
num_elements);
}
// -------------------------------------------------------------------------- //
// Run benchmark using Eigen expression evaluation.
// -------------------------------------------------------------------------- //
template <typename T, int RANK>
struct InitTensor {
static Eigen::Tensor<T, RANK, Eigen::RowMajor> Get(
const std::array<ssize_t, RANK>&);
};
#define INIT_TENSOR(RANK, UNROLL) \
template <typename T> \
struct InitTensor<T, RANK> { \
static Eigen::Tensor<T, RANK, Eigen::RowMajor> Get( \
const std::array<ssize_t, RANK>& shape) { \
Eigen::Tensor<T, RANK, Eigen::RowMajor> dst UNROLL; \
return dst; \
} \
};
template <typename T>
struct InitTensor<T, 0> {
static Eigen::Tensor<T, 0, Eigen::RowMajor> Get(
const std::array<ssize_t, 0>&) {
return Eigen::Tensor<T, 0, Eigen::RowMajor>();
}
};
INIT_TENSOR(1, (shape[0]));
INIT_TENSOR(2, (shape[0], shape[1]));
INIT_TENSOR(3, (shape[0], shape[1], shape[2]));
struct EigenSpec {
explicit EigenSpec(SmallVector<int32_t, 2> dims_to_reduce)
: dims_to_reduce(std::move(dims_to_reduce)) {}
SmallVector<int32_t, 2> dims_to_reduce;
size_t num_threads;
};
template <typename T, int INPUT_RANK, int OUTPUT_RANK>
void RunReductionEigenBenchmark(::testing::benchmark::State& state,
size_t num_threads, const EigenSpec& spec) {
std::array<ssize_t, INPUT_RANK - OUTPUT_RANK> dims_to_reduce;
for (int i = 0; i < dims_to_reduce.size(); ++i) {
dims_to_reduce[i] = spec.dims_to_reduce[i];
}
// Compute input/output shapes and the number of elements.
std::array<ssize_t, INPUT_RANK> input_shape;
std::array<ssize_t, OUTPUT_RANK> output_shape;
int64_t num_elements = 1;
for (int i = 0, j = 0; i < INPUT_RANK; ++i) {
input_shape[i] = state.range(i);
num_elements *= state.range(i);
if (llvm::find(spec.dims_to_reduce, i) == spec.dims_to_reduce.end())
output_shape[j++] = input_shape[i];
}
Eigen::Tensor<T, INPUT_RANK, Eigen::RowMajor> lhs =
GenRandomTensor<T, INPUT_RANK>(input_shape);
Eigen::DefaultDevice singleThreadedDevice;
Eigen::ThreadPool thread_pool(num_threads);
llvm::Optional<Eigen::ThreadPoolDevice> multiThreadedDevice;
if (num_threads > 0) multiThreadedDevice.emplace(&thread_pool, num_threads);
auto dst = InitTensor<T, OUTPUT_RANK>::Get(output_shape);
dst.setZero();
for (auto s : state) {
auto expr = lhs.sum(dims_to_reduce);
using Dst = decltype(dst);
using Expr = decltype(expr);
if (multiThreadedDevice.hasValue()) {
ExecuteAssignOp</*vectorize=*/true, Eigen::ThreadPoolDevice, Dst,
Expr>::run(*multiThreadedDevice, dst, expr);
} else {
ExecuteAssignOp</*vectorize=*/true, Eigen::DefaultDevice, Dst, Expr>::run(
singleThreadedDevice, dst, expr);
}
}
state.SetItemsProcessed(static_cast<int64_t>(state.iterations()) *
num_elements);
}
// -------------------------------------------------------------------------- //
// Macros to dispatch to different shapes.
// -------------------------------------------------------------------------- //
// MLIR benchmarks
#define BM_TFMlir(NAME, TYPE, NUM_THREADS, INPUT_RANK, SPEC) \
static void BM_mlir__##INPUT_RANK##D_##NAME##_##TYPE##_##NUM_THREADS( \
::testing::benchmark::State& state) { \
RunReductionMlirBenchmark<TYPE, INPUT_RANK>(state, NUM_THREADS, SPEC); \
} \
BENCHMARK(BM_mlir__##INPUT_RANK##D_##NAME##_##TYPE##_##NUM_THREADS) \
->MeasureProcessCPUTime()
#define ARGS_1D \
Args({3})->Args({8})->Args({80})->Args({800})->Args({8000})->Args({8131})
#define BM_TFMlir1(NAME, TYPE, NUM_THREADS, SPEC) \
BM_TFMlir(NAME, TYPE, NUM_THREADS, 1, SPEC)->ARGS_1D
#define ARGS_2D \
Args({2, 80}) \
->Args({8, 6}) \
->Args({80, 1}) \
->Args({80, 60}) \
->Args({81, 61}) \
->Args({800, 600}) \
->Args({802, 602})
#define BM_TFMlir2(NAME, TYPE, NUM_THREADS, SPEC) \
BM_TFMlir(NAME, TYPE, NUM_THREADS, 2, SPEC)->ARGS_2D
// Eigen benchmarks
#define BM_Eigen(NAME, TYPE, NUM_THREADS, INPUT_RANK, OUTPUT_RANK, SPEC) \
static void BM_eigen_##INPUT_RANK##D_##NAME##_##TYPE##_##NUM_THREADS( \
::testing::benchmark::State& state) { \
RunReductionEigenBenchmark<TYPE, INPUT_RANK, OUTPUT_RANK>( \
state, NUM_THREADS, SPEC); \
} \
BENCHMARK(BM_eigen_##INPUT_RANK##D_##NAME##_##TYPE##_##NUM_THREADS) \
->MeasureProcessCPUTime()
#define BM_Eigen1(NAME, TYPE, NUM_THREADS) \
BM_Eigen(NAME, TYPE, NUM_THREADS, 1, 0, EigenSpec({0}))->ARGS_1D
#define BM_Eigen2(NAME, TYPE, NUM_THREADS, OUTPUT_RANK, SPEC) \
BM_Eigen(NAME, TYPE, NUM_THREADS, 2, OUTPUT_RANK, SPEC)->ARGS_2D
} // namespace tensorflow
#endif // TENSORFLOW_COMPILER_MLIR_TFRT_BENCHMARKS_REDUCTION_BENCHMARK_H_
| [
"[email protected]"
] | |
72150eceb4872dd21b8e5c7243c014f7d63dac03 | 8aa6f564f4c1998122ac1224ea83596a651bf0dd | /threads_demo/pro_con/pro_con_queue.cpp | ed68f6834561af23557def60f7c19e6690a09b5c | [] | no_license | jinxin123456/aliyun | c71a69a8cc2590f9e159dfe3d5a38ef7201fdb3d | 85d68251f23b84218b2d88d21e5bb218d453a235 | refs/heads/master | 2020-05-25T12:56:33.625062 | 2016-10-03T04:48:31 | 2016-10-03T04:48:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,601 | cpp | #include <semaphore.h>
#include <stdio.h>
#include <pthread.h>
#include <iostream>
#include <vector>
#include <list>
using namespace std;
template<typename T>
class wqueue{
private:
//此队列内部用双端链表实现
list<T> m_queue;
pthread_mutex_t m_mutex;
pthread_cond_t m_condv; //use a mutex and condation variable
public:
T remove(){
pthread_mutex_lock(&m_mutex);
while(m_queue.size()==0){
pthread_cond_wait(&m_condv,&m_mutex);
}
T item = m_queue.front();
m_queue.pop_front();
pthread_mutex_unlock(&m_mutex);
return item;
}
void add(T item){
pthread_mutex_lock(&m_mutex);
m_queue.push_back(item);
pthread_cond_signal(&m_condv);
pthread_mutex_unlock(&m_mutex);
}
int size() { //不是用于等待while-cond中的,而是用于外部获取wqueue的大小
pthread_mutex_lock(&m_mutex);
int size = m_queue.size();
pthread_mutex_unlock(&m_mutex);
return size;
}
};
//线程函数不好作为成员函数,因此作为全局变量吧
wqueue<int>Q;
void* consumer(void * arg){
int i = *((int *)(&arg));
cout<<" [before remove thread : "<<i<<" ] "<<endl;
cout<<"remove item:"<<Q.remove();
cout<<" [after remove thread: "<<i<<" ]"<<endl;
}
void* producer(void *arg){
int item = *((int *)(&arg));
cout<<" before add item:"<<item<<endl;
Q.add(item);
cout<<" after add item"<<item<<endl;
}
int main(){
pthread_t tid[2];
int i;
for(i=0;i<10;i++){
pthread_create(&tid[0],NULL,consumer,(void *)i);
}
for(i=0;i<10;i++){
pthread_create(&tid[0],NULL,producer,(void *)i);
}
pthread_exit(NULL);
return 0;
}
| [
"[email protected]"
] | |
9d8a8c027f4d19b82fb2bcd5e34bd1d0f766f74b | a76729b5c7d609943c17e151560d47515f8567cf | /Week61Test/stdafx.cpp | 6ab7bf07fde37957710343fff0f0dc2881c101ad | [] | no_license | janitha09/LeetCode | 4bf046a3ae81bf59aca124af20d116dfed625312 | 4fd252a23644385eeefa1024baf45c42cb7195fa | refs/heads/master | 2021-01-20T05:28:35.149557 | 2018-04-03T04:01:02 | 2018-04-03T04:01:02 | 101,445,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Week61Test.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
54f6d7082886f522dab53c329bc1848b0958411c | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /data/dataset_2017/dataset_2017_8/sping128/8294486_5681755159789568_sping128.cpp | fdf1a161162fef822086588d10ea92eac2a2089f | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 1,681 | cpp | #include <bits/stdc++.h>
using namespace std;
#define SZ(x) ((int)(x).size())
#define PB(x) push_back(x)
#define MEMSET(x,v) memset(x,v,sizeof(x))
#define REP(i,n) for(int (i)=0;(i)<(n);++(i))
#define x first
#define y second
#define INF (0x3f3f3f3f)
typedef long long LL;
typedef pair<int, int> P2;
template<class A, class B> inline bool mina(A &x, B y) {return (x > y)?(x=y,1):0;}
template<class A, class B> inline bool maxa(A &x, B y) {return (x < y)?(x=y,1):0;}
const int MAXN = 105;
int N, Q;
int E[MAXN], S[MAXN];
LL dist[MAXN][MAXN];
double min_cost[MAXN];
P2 queries[MAXN];
void solve() {
cin >> N >> Q;
REP(i, N) {
cin >> E[i] >> S[i];
min_cost[i] = 1e15;
}
REP(i, N) {
REP(j, N) {
cin >> dist[i][j];
if (dist[i][j] == -1) {
dist[i][j] = INF;
}
}
}
REP(i, Q) {
cin >> queries[i].x >> queries[i].y;
queries[i].x--;
queries[i].y--;
}
REP(k, N) {
REP(i, N) {
REP(j, N) {
mina(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
min_cost[0] = 0.0;
for (int i = 1; i < N; i++) {
for (int j = 0; j < i; j++) {
if (dist[j][i] <= E[j]) {
double nx = min_cost[j] + dist[j][i] * 1.0 / S[j];
mina(min_cost[i], nx);
}
}
}
// cout << queries[0].y << endl;
REP(i, Q) {
printf(" %.9lf", min_cost[queries[i].y]);
}
cout << endl;
}
int main() {
int test;
cin >> test;
REP(tt, test) {
cout << "Case #" << (tt + 1) << ":";
solve();
}
return 0;
}
| [
"[email protected]"
] | |
99ef73f697c29a421bab29eca2548580eb678e8a | 2f743bc5dbbfc14c177bb53b8e2ecc7171e4a6aa | /Interpreter/Function.h | 4ec1582f59759a048af0d623992b740fb499a9d6 | [] | no_license | Alon-Regev/Interpreter | 263c01d44809bb49e30d16bd7459de8f81e274a1 | 45c8fa8e987ac24ce4b81a768b3913b269667f75 | refs/heads/master | 2023-08-02T17:05:51.697901 | 2021-09-22T19:16:36 | 2021-09-22T19:16:36 | 376,809,322 | 2 | 0 | null | 2021-09-22T19:13:24 | 2021-06-14T12:07:09 | C++ | UTF-8 | C++ | false | false | 1,126 | h | #pragma once
#include "Type.h"
#include "Node.h"
#include "Interpreter.h"
#include "Tuple.h"
#include "Block.h"
#include "TypeErrorException.h"
#define FUNCTION "function"
class Interpreter;
class Block;
class Tuple;
struct Parameter
{
std::string name;
std::string type;
};
struct FunctionInstance
{
std::vector<Parameter> parameters;
Block* function;
};
class Function : public Type
{
public:
Function(Interpreter& interpreter);
Function(Type* params, Block* block, std::map<std::string, Type*>& variables);
Function(std::vector<FunctionInstance>& functionInstances, Interpreter& interpreter, Type* thisType);
virtual ~Function();
virtual std::string toString() const { return FUNCTION; }
virtual Type* copy();
void setThis(Type* value, bool deletePrev = true);
// operators
virtual Type* call(Type* other);
virtual Type* assign(Type* other);
virtual Type* extend(Type* other);
virtual Type* extendAssign(Type* other);
private:
std::vector<FunctionInstance> _functionInstances;
Interpreter& _interpreter;
Type* _this = nullptr;
Type* run(FunctionInstance& function, std::vector<Type*>& args);
};
| [
"[email protected]"
] | |
6264d4ffceeb91ccab6dd776d55d8f2b38baf417 | e307545b2420f6162eeab33d02a66662a236e28a | /openCVLibrary/src/main/cpp/src/dsm_strategy/utils/file/text_table_file.cc | 29e68c6bf43392c8952ce96021d3b47113a9bdaa | [] | no_license | BobDeng1974/sd | 7baf7cb9f2f649adce4d5861623c97c0184b2b8d | 984db360fcb4ad60112c68674a0c7ac4ae8402c0 | refs/heads/master | 2020-06-02T22:55:07.930263 | 2019-05-25T04:30:02 | 2019-05-25T04:30:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,257 | cc | #include "text_table_file.h"
#include "file_utils.h"
#include "file_read_write_utils.h"
void TextData::getIdxClear(){
for(size_t i = 0; i < get_idx.size(); i++){
get_idx[i] = -1;
}
}
void TextData::setIdxClear(){
for(size_t i = 0; i < set_idx.size(); i++){
set_idx[i] = -1;
}
}
int64_t TextData::getInt64Value(int idx){
if(-1 == idx)
return int64_data[get_idx[0]];
else if( -2 == idx)
return int64_data[++get_idx[0]];
else if( idx >= max_sizes[0]){
std::cout << "[warning]: idx over!" << std::endl;
return -999999;
}
else
return int64_data[idx];
}
std::string TextData::getStringValue(int idx){
if(-1 == idx)
return string_data[get_idx[1]];
else if( -2 == idx)
return string_data[++get_idx[1]];
else if( idx >= max_sizes[1]){
std::cout << "[warning]: idx over!" << std::endl;
return "";
}
else
return string_data[idx];
}
double TextData::getDoubleValue(int idx){
if(-1 == idx)
return double_data[get_idx[2]];
else if( -2 == idx)
return double_data[++get_idx[2]];
else if( idx >= max_sizes[2]){
std::cout << "[warning]: idx over!" << std::endl;
return -999999.99;
}
else
return double_data[idx];
}
double TextData::getIntValue(int idx){
if(-1 == idx)
return int_data[get_idx[3]];
else if( -2 == idx)
return int_data[++get_idx[3]];
else if( idx >= max_sizes[3]){
std::cout << "[warning]: idx over!" << std::endl;
return -999999;
}
else
return int_data[idx];
}
void TextData::setInt64Value(int64_t value){
int64_data[++set_idx[0]] = value;
}
void TextData::setStringValue(const std::string &value){
string_data[++set_idx[1]] = value;
}
void TextData::setDoubleValue(double value){
double_data[++set_idx[2]] = value;
}
void TextData::setIntValue(int value){
int_data[++set_idx[3]] = value;
}
//////////////////////////////////////////////////
TextTableFile::TextTableFile(const std::string format, const char separate, size_t offset_line):
format_(format),
separate_(separate),
offset_line_(offset_line){
format_count_ = formatAnalyse(format_, format_array_);
cols_ = format_array_.size();
}
bool TextTableFile::loadText(const std::string &filename) {
if(!::loadText2String(filename, lines_, offset_line_))
return false;
std::vector< std::string > array;
text_data_array_.clear();
int64_t int64_data;
std::string string_data;
double double_data;
int int_data;
for(size_t i = 0; i < lines_.size(); i++){
if(lines_[i][0] == '#')
continue;
std::shared_ptr<TextData> text_data = std::make_shared<TextData>(
format_count_[0], format_count_[1],
format_count_[2], format_count_[3]);
split(lines_[i], array, separate_);
std::stringstream ss;
for(size_t j = 0; j < array.size(); ++j){
std::stringstream ss(array[j]);
if(format_array_[j] == "d64"){
ss >> int64_data;
text_data->setInt64Value(int64_data);
}
else if (format_array_[j] == "s"){
string_data = ss.str();
text_data->setStringValue(string_data);
}
else if (format_array_[j] == "f"){
ss >> double_data;
text_data->setDoubleValue(double_data);
}
else if(format_array_[j] == "i"){
ss >> int_data;
text_data->setIntValue(int_data);
}
// std::cout << separate_;
}
text_data_array_.push_back(text_data);
// std::cout << std::endl;
}
// std::cout << "text_data_array_.size:" << text_data_array_.size() << std::endl;
return true;
}
bool TextTableFile::loadNumericText(const std::string &filename){
if(!::loadText2String(filename, lines_, offset_line_))
return false;
for(size_t i = 0; i < format_array_.size(); i++){
if(format_array_[i] == "s"){
std::cout << "[error]: must input numeric text" << std::endl;
return false;
}
}
text_data_array_.clear();
int64_t int64_data;
std::string string_data;
double double_data;
int int_data;
for(size_t i = 0; i < lines_.size(); i++){
if(lines_[i][0] == '#')
continue;
std::shared_ptr<TextData> text_data = std::make_shared<TextData>(
format_count_[0], format_count_[1],
format_count_[2], format_count_[3]);
std::stringstream ss(lines_[i]);
std::cout << lines_[i] << std::endl;
char delimeter;
for(size_t j = 0; j < format_array_.size(); ++j){
// std::cout << array[j] << ",";
if(format_array_[j] == "d64"){
ss >> int64_data >> delimeter;
text_data->setInt64Value(int64_data);
}
else if (format_array_[j] == "s"){
ss >> string_data >> delimeter;
text_data->setStringValue(string_data);
}
else if (format_array_[j] == "f"){
ss >> double_data >> delimeter;
text_data->setDoubleValue(double_data);
}
else if(format_array_[j] == "i"){
ss >> int_data >> delimeter;
text_data->setIntValue(int_data);
}
// std::cout << separate_;
}
text_data_array_.push_back(text_data);
// std::cout << std::endl;
}
return true;
}
bool TextTableFile::saveText(const std::string &filename, int precisions){
std::fstream fs(filename, std::ios::out);
if(!title_.empty())
fs << title_ << std::endl;
for(size_t i = 0; i < text_data_array_.size(); i++){
std::shared_ptr<TextData> &text_data = text_data_array_[i];
text_data->getIdxClear();
for(size_t j = 0; j < format_array_.size(); j++){
if(format_array_[j] == "d64")
fs << text_data->getInt64Value(-2);
if(format_array_[j] == "s")
fs << text_data->getStringValue(-2);
if(format_array_[j] == "f")
fs << text_data->getDoubleValue(-2);
if(format_array_[j] == "i"){
fs.precision(precisions);
fs << text_data->getIntValue(-2);
fs.unsetf( std::ios::fixed );
}
if(j < format_array_.size()-1)
fs << separate_;
}
fs << std::endl;
}
fs.close();
return true;
}
std::shared_ptr<TextData> TextTableFile::getTextData(size_t idx) const{
assert(idx >= 0 && idx < text_data_array_.size());
return text_data_array_[idx];
}
std::string TextTableFile::getLine(size_t idx){
assert(idx >= 0 && idx < lines_.size());
return lines_[idx];
}
bool TextTableFile::getLines(
size_t begin_idx,
size_t end_idx,
std::vector< std::string > &lines){
assert(begin_idx >= 0 && begin_idx < lines_.size());
assert(end_idx >= 1 && end_idx <= lines_.size());
lines.clear();
lines.resize(end_idx - begin_idx);
for(size_t i = 0; i < end_idx; i++)
lines[i] = lines_[i];
return true;
}
int TextTableFile::getIntValue(size_t nrow, int ncols) const{
return text_data_array_[nrow]->getIntValue(ncols);
}
std::string TextTableFile::getStringValue(size_t nrow, int ncols) const{
return text_data_array_[nrow]->getStringValue(ncols);
}
double TextTableFile::getDoubleValue(size_t nrow, int ncols) const{
return text_data_array_[nrow]->getDoubleValue(ncols);
}
int64_t TextTableFile::getInt64Value(size_t nrow, int ncols) const{
return text_data_array_[nrow]->getInt64Value(ncols);
}
void TextTableFile::setRows(size_t rows){
rows_ = rows;
text_data_array_.resize(rows);
for(size_t i = 0; i < rows_; i++){
text_data_array_[i] = std::make_shared<TextData>(format_count_[0],format_count_[1], format_count_[2], format_count_[3]);
}
}
void TextTableFile::setTitle(const std::string &title){
title_ = title;
}
void TextTableFile::setIntValue(size_t nrow, int value){
text_data_array_[nrow]->setIntValue(value);
}
void TextTableFile::setStringValue(size_t nrow, std::string &value){
text_data_array_[nrow]->setStringValue(value);
}
void TextTableFile::setDoubleValue(size_t nrow, double value){
text_data_array_[nrow]->setDoubleValue(value);
}
void TextTableFile::setInt64Value(size_t nrow, int64_t value){
text_data_array_[nrow]->setInt64Value(value);
}
//format_count:int64_t string double int的顺序输出,分别对应%d64, %s, %f, %i
std::vector< int > TextTableFile::formatAnalyse(
const std::string &format,
std::vector< std::string > &format_array) {
split(format, format_array, '%');
std::vector<int> format_count(10, 0);
for(size_t i = 0; i < format_array.size(); ++i){
if(format_array[i] == "d64")
format_count[0]++;
else if(format_array[i] == "s")
format_count[1]++;
else if(format_array[i] == "f")
format_count[2]++;
else if(format_array[i] == "i")
format_count[3]++;
else
std::cout << "invaid format char[%" << format_array[i] << "], please input again!" << std::endl;
}
return format_count;
}
void TextTableFile::print(const std::string &addition){
std::cout << "--------" << addition << "---------" << std::endl;
for(size_t i = 0; i < text_data_array_.size(); i++){
int format_count[10] = {0};
for(size_t j = 0; j < format_array_.size(); j++){
// std::cout << "format_array_[j]:" << format_array_[j] << std::endl;
if(format_array_[j] == "d64")
std::cout << text_data_array_[i]->getInt64Value(format_count[0]++);
if(format_array_[j] == "s")
std::cout << text_data_array_[i]->getStringValue(format_count[1]++);
if(format_array_[j] == "f")
std::cout << text_data_array_[i]->getDoubleValue(format_count[2]++);
if(format_array_[j] == "i")
std::cout << text_data_array_[i]->getIntValue(format_count[3]++);
if(j < format_array_.size()-1)
std::cout << format_array_[j] << separate_;
}
std::cout << format_array_[format_array_.size()-1] << std::endl;
}
std::cout << "++++++++" << addition << "++++++++" << std::endl;
}
| [
"[email protected]"
] | |
5d2a2bf128ba185c1473e09c5e137875cc4d8e8b | 9dd6556da2c1c71e5c322cce277fd83dc145c378 | /src/textsearch/DiffFileSearchEngineSteadily.h | e371e0a2c3e0a5e80ad1605aba3a5b1a1ccc9457 | [
"BSD-3-Clause",
"MIT"
] | permissive | rosneru/ADiffView | 895d42c78786047adf8bbebed822ce7813922ad4 | 70efe6b21afd463bc683e209034a1f6d8e201203 | refs/heads/main | 2023-07-13T01:57:36.361599 | 2023-05-17T13:29:57 | 2023-05-17T13:29:57 | 149,339,769 | 3 | 0 | NOASSERTION | 2021-07-13T09:30:34 | 2018-09-18T19:14:46 | C++ | UTF-8 | C++ | false | false | 989 | h | #ifndef DIFF_FILE_SEARCH_ENGINE_STEADILY_H
#define DIFF_FILE_SEARCH_ENGINE_STEADILY_H
#include <string>
#include <vector>
#include "DiffFileBase.h"
#include "DiffFileSearchResult.h"
/**
* A text search engine that operates on two DiffFiles.
*
* @author Uwe Rosner
* @date 10/04/2021
*/
class DiffFileSearchEngineSteadily
{
public:
DiffFileSearchEngineSteadily(const DiffFileBase& leftFile,
const DiffFileBase& rightFile,
const char* pSearchString);
virtual ~DiffFileSearchEngineSteadily();
size_t getNumResults();
DiffFileSearchResult* getFirstResult(size_t startLineId);
DiffFileSearchResult* getPrevResult();
DiffFileSearchResult* getNextResult();
private:
const DiffFileBase& m_LeftFile;
const DiffFileBase& m_RightFile;
std::string m_SearchString;
std::vector<DiffFileSearchResult*> m_Results;
std::vector<DiffFileSearchResult*>::iterator m_ResultsIterator;
void find();
};
#endif
| [
"[email protected]"
] | |
5c2fdeeceaf6cb54543442f691f4a867e2261af1 | 5b755dd083073896147cd8dbabee8d657a4e7f6f | /MPU9250BasicAHRS/MPU9250BasicAHRS.ino | 672b8c11e2a95c01639df6549b001c8e437c353f | [] | no_license | pavelbobov/raider1 | c0fc4378a093d42f3d1c922c95d88dfd503c1c6a | 8fee9f9acc5731bf5c5f08501e3c31bd3fd5a2f9 | refs/heads/master | 2020-12-26T04:54:54.782982 | 2016-02-25T04:37:38 | 2016-02-25T04:37:38 | 39,704,747 | 1 | 0 | null | 2015-09-17T03:18:34 | 2015-07-25T22:20:31 | C++ | UTF-8 | C++ | false | false | 6,647 | ino | /* MPU9250 Basic Example Code
by: Kris Winer
date: April 1, 2014
license: Beerware - Use this code however you'd like. If you
find it useful you can buy me a beer some time.
Demonstrate basic MPU-9250 functionality including parameterizing the register addresses, initializing the sensor,
getting properly scaled accelerometer, gyroscope, and magnetometer data out. Added display functions to
allow display to on breadboard monitor. Addition of 9 DoF sensor fusion using open source Madgwick and
Mahony filter algorithms. Sketch runs on the 3.3 V 8 MHz Pro Mini and the Teensy 3.1.
SDA and SCL should have external pull-up resistors (to 3.3V).
10k resistors are on the EMSENSR-9250 breakout board.
Hardware setup:
MPU9250 Breakout --------- Arduino
VDD ---------------------- 3.3V
VDDI --------------------- 3.3V
SDA ----------------------- A4
SCL ----------------------- A5
GND ---------------------- GND
Note: The MPU9250 is an I2C sensor and uses the Arduino Wire library.
Because the sensor is not 5V tolerant, we are using a 3.3 V 8 MHz Pro Mini or a 3.3 V Teensy 3.1.
We have disabled the internal pull-ups used by the Wire library in the Wire.h/twi.c utility file.
We are also using the 400 kHz fast I2C mode by setting the TWI_FREQ to 400000L /twi.h utility file.
*/
#include <Wire.h>
#include "MPU9250.h"
MPU9250 mpu;
float ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor data values
float temperature; // Stores the real internal chip temperature in degrees Celsius
uint32_t count = 0, sumCount = 0; // used to control display output rate
//float pitch, yaw, roll;
float sum = 0.0f; // integration interval for both filter schemes
uint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval
uint32_t delt_t = 0; // used to control display output rate
void setup()
{
Serial.begin(38400);
mpu.init();
/*
Serial.println("Mag Calibration: Wave device in a figure eight until done!");
delay(4000);
float dest1[3], dest2[3];
mpu.magcalMPU9250(dest1, dest2);
Serial.println("Soft irons:");
Serial.println(dest1[0]);
Serial.println(dest1[1]);
Serial.println(dest1[2]);
Serial.println("Hard irons:");
Serial.println(dest2[0]);
Serial.println(dest2[1]);
Serial.println(dest2[2]);
Serial.println("Mag Calibration done!");
*/
}
void loop()
{
// Sensors x (y)-axis of the accelerometer is aligned with the y (x)-axis of the magnetometer;
// the magnetometer z-axis (+ down) is opposite to z-axis (+ up) of accelerometer and gyro!
// We have to make some allowance for this orientationmis match in feeding the output to the quaternion filter.
// For the MPU-9250, we have chosen a magnetic rotation that keeps the sensor forward along the x-axis just like
// in the LSM9DS0 sensor. This rotation can be modified to allow any convenient orientation convention.
// This is ok by aircraft orientation standards!
// Pass gyro rate as rad/s
// MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, my, mx, mz);
delay(10);
sumCount += mpu.mahonyQuaternionUpdate();
float now = micros();
float deltat = ((now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
lastUpdate = now;
sum += deltat; // sum for averaging filter update rate
// Serial print and/or display at 0.5 s rate independent of data rates
delt_t = millis() - count;
if (delt_t > 500)
{ // update LCD once per half-second independent of read rate
if(SerialDebug)
{
// Define output variables from updated quaternion---these are Tait-Bryan angles, commonly used in aircraft orientation.
// In this coordinate system, the positive z-axis is down toward Earth.
// Yaw is the angle between Sensor x-axis and Earth magnetic North (or true North if corrected for local declination, looking down on the sensor positive yaw is counterclockwise.
// Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative.
// Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll.
// These arise from the definition of the homogeneous rotation matrix constructed from quaternions.
// Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be
// applied in the correct order which for this configuration is yaw, pitch, and then roll.
// For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links.
float yaw = mpu.getYaw();
float pitch = mpu.getPitch();
float roll = mpu.getRoll();
Serial.print("Yaw, Pitch, Roll: ");
Serial.print(yaw, 2);
Serial.print(", ");
Serial.print(pitch, 2);
Serial.print(", ");
Serial.println(roll, 2);
Serial.print("rate = ");
Serial.print((float)sumCount/sum, 2);
Serial.println(" Hz");
mpu.getTempData(&temperature); // Read the adc values
// Print temperature in degrees Centigrade
Serial.print("Temperature is ");
Serial.print(temperature, 1);
Serial.println(" degrees C"); // Print T values to tenths of s degree C
}
// With these settings the filter is updating at a ~145 Hz rate using the Madgwick scheme and
// >200 Hz using the Mahony scheme even though the display refreshes at only 2 Hz.
// The filter update rate is determined mostly by the mathematical steps in the respective algorithms,
// the processor speed (8 MHz for the 3.3V Pro Mini), and the magnetometer ODR:
// an ODR of 10 Hz for the magnetometer produce the above rates, maximum magnetometer ODR of 100 Hz produces
// filter update rates of 36 - 145 and ~38 Hz for the Madgwick and Mahony schemes, respectively.
// This is presumably because the magnetometer read takes longer than the gyro or accelerometer reads.
// This filter update rate should be fast enough to maintain accurate platform orientation for
// stabilization control of a fast-moving robot or quadcopter. Compare to the update rate of 200 Hz
// produced by the on-board Digital Motion Processor of Invensense's MPU6050 6 DoF and MPU9150 9DoF sensors.
// The 3.3 V 8 MHz Pro Mini is doing pretty well!
//display.setCursor(0, 40); display.print("rt: "); display.print((float) sumCount / sum, 2); display.print(" Hz");
//display.display();
count = millis();
sumCount = 0;
sum = 0;
}
}
| [
"[email protected]"
] | |
9fee0af9d146cf2c093555fda393f9c2b6ba9c19 | 515e447345616288a1e108bdab75fbba3f272c1a | /src/ofxScene.cpp | ed66080815507d23aeeefa35ba4cc381ec298823 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | alptugan/ofxAppUtils | 937c2b97b17c38a86b2b03a3e26a172ccdc10463 | 82d0f4ca2c8705b75c1b97f2716113a23a9733b5 | refs/heads/master | 2021-05-20T03:12:11.415864 | 2018-07-24T10:38:36 | 2018-07-24T10:38:36 | 252,161,447 | 1 | 0 | NOASSERTION | 2020-04-01T11:56:40 | 2020-04-01T11:56:39 | null | UTF-8 | C++ | false | false | 1,668 | cpp | /*
* Copyright (c) 2011 Dan Wilcox <[email protected]>
*
* BSD Simplified License.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*
* See https://github.com/danomatika/ofxAppUtils for documentation
*
*/
#include "ofxScene.h"
#include "ofAppRunner.h"
/// RUNNER SCENE
//--------------------------------------------------------------
ofxScene::RunnerScene::RunnerScene(ofxScene *scene) {
this->scene = scene;
}
//--------------------------------------------------------------
ofxScene::RunnerScene::~RunnerScene() {
if(scene != NULL) {
delete scene;
}
}
//--------------------------------------------------------------
void ofxScene::RunnerScene::setup() {
if(!scene->_bSetup) {
scene->setup();
scene->_bSetup = true;
}
}
//--------------------------------------------------------------
void ofxScene::RunnerScene::update() {
if(!scene->_bSetup || !scene->_bRunning) {
return;
}
// update mouse pos for processing heads
scene->mouseX = ofGetMouseX();
scene->mouseY = ofGetMouseY();
if(scene->_bEntering) {
scene->updateEnter();
scene->_bEnteringFirst = false;
}
else if(scene->_bExiting) {
scene->updateExit();
scene->_bExitingFirst = false;
}
else {
scene->update();
}
}
//--------------------------------------------------------------
void ofxScene::RunnerScene::draw() {
if(!scene->_bSetup) {
return;
}
scene->draw();
}
//--------------------------------------------------------------
void ofxScene::RunnerScene::exit() {
scene->exit();
if(!scene->_bSingleSetup) {
scene->_bSetup = false;
}
}
| [
"[email protected]"
] | |
6d156c79ac91e1e6a969599aa301da4bb3db20b2 | 44f44a72859c8e625af46b5dff4409d38574c277 | /src/netfulfilledman.h | da5ce99798245128f7140fec643847dfb1d64729 | [
"MIT"
] | permissive | DreamTeamCoin3/DT3 | 989e51ceff0ee36f568d257c68bb77b89554e9df | b526188b52e7cac1e5097042feca99b9843896b7 | refs/heads/master | 2020-04-17T09:32:22.140488 | 2019-02-09T12:05:00 | 2019-02-09T12:05:00 | 166,462,063 | 1 | 1 | MIT | 2019-01-27T06:15:52 | 2019-01-18T19:28:51 | null | UTF-8 | C++ | false | false | 1,550 | h | // Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2019 The DreamTeam3 Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef NETFULFILLEDMAN_H
#define NETFULFILLEDMAN_H
#include "netaddress.h"
#include "serialize.h"
#include "sync.h"
class CNetFulfilledRequestManager;
extern CNetFulfilledRequestManager netfulfilledman;
// Fulfilled requests are used to prevent nodes from asking for the same data on sync
// and from being banned for doing so too often.
class CNetFulfilledRequestManager
{
private:
typedef std::map<std::string, int64_t> fulfilledreqmapentry_t;
typedef std::map<CService, fulfilledreqmapentry_t> fulfilledreqmap_t;
//keep track of what node has/was asked for and when
fulfilledreqmap_t mapFulfilledRequests;
CCriticalSection cs_mapFulfilledRequests;
void RemoveFulfilledRequest(const CService& addr, const std::string& strRequest);
public:
CNetFulfilledRequestManager() {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
LOCK(cs_mapFulfilledRequests);
READWRITE(mapFulfilledRequests);
}
void AddFulfilledRequest(const CService& addr, const std::string& strRequest);
bool HasFulfilledRequest(const CService& addr, const std::string& strRequest);
void CheckAndRemove();
void Clear();
std::string ToString() const;
};
#endif
| [
"[email protected]"
] | |
03ea6c6236c61550c146b7fa176896f21a42221c | 696946bc3b2a6ea1766055553e89efb2abf4de87 | /genieSpark_Demo_MultiScreen.ino | fa34e78d4a80b1cc2024bb82fe2ff9112a7ee39f | [] | no_license | dgjohnson/VisiGenie_Spark | 70d15d296a8474e3ccb75b4defbc0482adc05e0f | c7c24accd851b112232fd5ec84fc87380ae13d53 | refs/heads/master | 2021-01-17T16:06:47.303175 | 2014-07-28T03:36:22 | 2014-07-28T03:36:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,506 | ino | #if defined (SPARK)
#include "genieSpark.h"
#else
#include <genieArduino.h>
#endif
// This Demo extends the genieArduino_Demo, by showing how to use more than 1 screen at a time, attached to an Arduino with 2+ Serial Ports.
// This Demo uses the same WS4 Genie program on both displays, in this case, 2x uLCD-32PTU's, and an Arduino Mega.
// NOTE: Both displays must be connected for this demo to function.
// This Demo communicates with 2 4D Systems Displays, configured with ViSi-Genie, utilising the Genie Arduino Library - https://github.com/4dsystems/ViSi-Genie-Arduino-Library.
// The display demo has a slider, a cool gauge, an LED Digits, a string box and a User LED.
// The program receives messages from the Slider0 object on each display using the Reported Events. This is triggered each time the Slider changes on the display, and an event
// is genereated and sent automatically. Reported Events originate from the On-Changed event from the slider itself, set in the Workshop4 software.
// Coolgauge is written to using Write Object, and the String is updated using the Write String command, showing the version of the library.
// The User LED is updated by the Arduino, by first doing a manual read of the User LED and then toggling it based on the state received back.
// As the slider changes, it sends its value to the Arduino (Arduino also polls its value using genie.ReadObject, as above), and the Arduino then
// tells the LED Digit to update its value using genie.WriteObject, but of the other displays LED Digit! So the Slider message goes via the Arduino to the LED Digit
// of the other display.
// Coolgauge is updated via simple timer in the Arduino code, and updates the display with its value.
// The User LED is read using genie.ReadObject, and then updated using genie.WriteObject. It is manually read, it does not use an Event.
// This demo illustrates how to use genie.ReadObject, genie.WriteObject, Reported Messages (Events), genie.WriteStr, genie.WriteContrast, plus supporting functions.
// Application Notes on the 4D Systems Website that are useful to understand this library are found: http://www.4dsystems.com.au/appnotes
// Good App Notes to read are:
// 4D-AN-P4017 - Connecting a 4D Display to an Arduino Host - http://www.4dsystems.com.au/downloads/Application-Notes/4D-AN-P4017_R_1_0.zip
// 4D-AN-P4018 - Writing to Genie Objects Using an Arduino Host - http://www.4dsystems.com.au/downloads/Application-Notes/4D-AN-P4018_R_1_0.zip
// 4D-AN-P4019 - A Simple Digital Voltmeter Application using an Arduino Host - http://www.4dsystems.com.au/downloads/Application-Notes/4D-AN-P4019_R_1_0.zip
// 4D-AN-P4025 - Arduino Danger Shield for Sparkfun Danger Shield - http://www.4dsystems.com.au/downloads/Application-Notes/4D-AN-P4025_R_1_0.zip
Genie display1; // Genie Display 1
Genie display2; // Genie Display 2
#define RESETLINE1 4 // Reset pin attached to Display 1
#define RESETLINE2 2 // Reset pin attached to Display 2
void setup()
{
// Use a Serial Begin and serial port of your choice in your code and use the genie.Begin function to send
// it to the Genie library (see this example below)
// 200K Baud is good for most Arduinos. Galileo should use 115200.
#if defined (SPARK)
Serial1.begin(200000); // Serial0 @ 200000 (200K) Baud
display1.Begin(Serial1); // Use Serial0 for talking to the Genie Library, and to the 4D Systems display #1
Serial2.begin(200000); // Serial1 @ 200000 (200K) Baud
display2.Begin(Serial2); // Use Serial1 for talking to the Genie Library, and to the 4D Systems display #2
#else
Serial.begin(200000); // Serial0 @ 200000 (200K) Baud
display1.Begin(Serial); // Use Serial0 for talking to the Genie Library, and to the 4D Systems display #1
Serial1.begin(200000); // Serial1 @ 200000 (200K) Baud
display2.Begin(Serial1); // Use Serial1 for talking to the Genie Library, and to the 4D Systems display #2
#endif
display1.AttachEventHandler(myGenieEventHandler1); // Attach the user function Event Handler for processing events for display 1
display2.AttachEventHandler(myGenieEventHandler2); // Attach the user function Event Handler for processing events for display 2
// Reset the Displays
// THIS IS IMPORTANT AND CAN PREVENT OUT OF SYNC ISSUES, SLOW SPEED RESPONSE ETC
pinMode(RESETLINE1, OUTPUT); // Set D4 on Arduino to Output to control the reset line to Display 1
pinMode(RESETLINE2, OUTPUT); // Set D2 on Arduino to Output to control the reset line to Display 2
digitalWrite(RESETLINE1, 1); // Reset Display 1
digitalWrite(RESETLINE2, 1); // Reset Display 2
delay(100);
digitalWrite(RESETLINE1, 0); // unReset Display 1
digitalWrite(RESETLINE2, 0); // unReset Display 2
delay (3500); //let the display start up after the reset (This is important)
//Turn the Display on (Contrast) - (Not needed but illustrates how)
//Most Displays, 1 = Display ON, 0 = Display OFF
//For uLCD43, uLCD-70DT, and uLCD-35DT, use 0-15 for Brightness Control, where 0 = Display OFF, though to 15 = Max Brightness ON.
display1.WriteContrast(1); // Display ON
display2.WriteContrast(1); // Display ON
//Write a string to the Display to identify each display
display1.WriteStr(0, "Hello Display 1");
display2.WriteStr(0, "Hello Display 2");
}
void loop()
{
static long waitPeriod = millis(); // Time now
static int gaugeAddVal1 = 1; // Set the value at which the Gauge on Display 1 increases by initially
static int gaugeVal1 = 10; // Starting Value for Gauge on Display 1
static int gaugeAddVal2 = 2; // Set the value at which the Gauge on Display 2 increases by initially
static int gaugeVal2 = 50; // Starting Value for Gauge on Display 2
display1.DoEvents(); // This calls the library each loop to process the queued responses from display 1
display2.DoEvents(); // This calls the library each loop to process the queued responses from display 2
if (millis() >= waitPeriod)
{
// Write to CoolGauge0 with the value in the gaugeVal variable
display1.WriteObject(GENIE_OBJ_COOL_GAUGE, 0, gaugeVal1);
gaugeVal1 += gaugeAddVal1;
if (gaugeVal1 >= 99) gaugeAddVal1 = -1; // If the value is > or = to 99, make gauge decrease in value by 1
if (gaugeVal1 <= 0) gaugeAddVal1 = 1; // If the value is < or = to 0, make gauge increase in value by 1
// The results of this call will be available to myGenieEventHandler() after the display has responded
// Do a manual read from the UserLEd0 object
display1.ReadObject(GENIE_OBJ_USER_LED, 0);
// Write to CoolGauge0 with the value in the gaugeVal variable
display2.WriteObject(GENIE_OBJ_COOL_GAUGE, 0, gaugeVal2);
gaugeVal2 += gaugeAddVal2;
if (gaugeVal2 >= 99) gaugeAddVal2 = -2; // If the value is > or = to 99, make gauge decrease in value by 2
if (gaugeVal2 <= 0) gaugeAddVal2 = 2; // If the value is < or = to 0, make gauge increase in value by 2
// The results of this call will be available to myGenieEventHandler() after the display has responded
// Do a manual read from the UserLed0 object
display1.ReadObject(GENIE_OBJ_USER_LED, 0);
display2.ReadObject(GENIE_OBJ_USER_LED, 0);
waitPeriod = millis() + 50; // rerun this code to update Cool Gauge and Slider in another 50ms time.
}
}
/////////////////////////////////////////////////////////////////////
//
// This is the user's event handler. It is called by the DoEvents()
// when the following conditions are true
//
// The link is in an IDLE state, and
// There is an event to handle
//
// The event can be either a REPORT_EVENT frame sent asynchronously
// from the display or a REPORT_OBJ frame sent by the display in
// response to a READ_OBJ request.
//
// Event Handler Function for Display 1
void myGenieEventHandler1(void)
{
genieFrame Event;
display1.DequeueEvent(&Event); // Remove the next queued event from the buffer, and process it below
//If the cmd received is from a Reported Event (Events triggered from the Events tab of Workshop4 objects)
if (Event.reportObject.cmd == GENIE_REPORT_EVENT)
{
if (Event.reportObject.object == GENIE_OBJ_SLIDER) // If the Reported Message was from a Slider
{
if (Event.reportObject.index == 0) // If Slider0
{
int slider_val = display1.GetEventData(&Event); // Receive the event data from the Slider0
display2.WriteObject(GENIE_OBJ_LED_DIGITS, 0, slider_val); // Write Slider0 value of Display 1 to to LED Digits 0 of Display 2 !
}
}
}
//If the cmd received is from a Reported Object, which occurs if a Read Object (genie.ReadOject) is requested in the main code, reply processed here.
if (Event.reportObject.cmd == GENIE_REPORT_OBJ)
{
if (Event.reportObject.object == GENIE_OBJ_USER_LED) // If the Reported Message was from a User LED
{
if (Event.reportObject.index == 0) // If UserLed0
{
bool UserLed0_val = display1.GetEventData(&Event); // Receive the event data from the UserLed0
UserLed0_val = !UserLed0_val; // Toggle the state of the User LED Variable
display1.WriteObject(GENIE_OBJ_USER_LED, 0, UserLed0_val); // Write UserLed0_val value back to to UserLed0
}
}
}
}
// Event Handler Function for Display 2
void myGenieEventHandler2(void)
{
genieFrame Event;
display2.DequeueEvent(&Event); // Remove the next queued event from the buffer, and process it below
//If the cmd received is from a Reported Event (Events triggered from the Events tab of Workshop4 objects)
if (Event.reportObject.cmd == GENIE_REPORT_EVENT)
{
if (Event.reportObject.object == GENIE_OBJ_SLIDER) // If the Reported Message was from a Slider
{
if (Event.reportObject.index == 0) // If Slider0
{
int slider_val = display2.GetEventData(&Event); // Receive the event data from the Slider0
display1.WriteObject(GENIE_OBJ_LED_DIGITS, 0, slider_val); // Write Slider0 value of Display 2 to to LED Digits 0 of Display 1
}
}
}
//If the cmd received is from a Reported Object, which occurs if a Read Object (genie.ReadOject) is requested in the main code, reply processed here.
if (Event.reportObject.cmd == GENIE_REPORT_OBJ)
{
if (Event.reportObject.object == GENIE_OBJ_USER_LED) // If the Reported Message was from a User LED
{
if (Event.reportObject.index == 0) // If UserLed0
{
bool UserLed0_val = display2.GetEventData(&Event); // Receive the event data from the UserLed0
UserLed0_val = !UserLed0_val; // Toggle the state of the User LED Variable
display2.WriteObject(GENIE_OBJ_USER_LED, 0, UserLed0_val); // Write UserLed0_val value back to to UserLed0
}
}
}
}
//These can be expanded as more objects are added that need to be captured
//Event.reportObject.cmd is used to determine the command of that event, such as an reported event
//Event.reportObject.object is used to determine the object type, such as a Slider
//Event.reportObject.index is used to determine the index of the object, such as Slider0
//genie.GetEventData(&Event) us used to save the data from the Event, into a variable.
| [
"[email protected]"
] | |
2a5b8ee45252eca19a7f8378bc59e28a051efe60 | a4a2574864bc052eea9ca1b3b1095781119d0a95 | /miscutils.h | 7440d4adc4139110db8fadd20d4e2f3918876da4 | [] | no_license | matthewbauer/xib2nib | 87ca7828768a727fbd138bf41f6acca3d44e7fa8 | 844c5b72df91d1f855cc9e4376d1a73f02709ec6 | refs/heads/master | 2021-01-19T10:48:27.932835 | 2017-04-11T07:43:16 | 2017-04-11T07:43:16 | 87,902,156 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,122 | h | //******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#ifndef _MISCUTILS_H_
#define _MISCUTILS_H_
#include "types.h"
String getTime();
double getEpochTime();
template <typename T, unsigned S>
inline unsigned arraySize(const T (&v)[S]) { return S; }
void removeDupes(StringVec& in);
bool checkTelemetryOptIn();
bool isMSFTInternalMachine();
std::string getMachineID();
#endif /* _MISCUTILS_H_ */
| [
"[email protected]"
] | |
15bb43fbad293c7c684dafdbc9eb0ff29c922257 | 384a3c67b9d3547b691fc1e659bb837514cd2ed4 | /LevelEditorTest/Level.h | f5fd9affc04db43093fd07270bc19615eff27ea7 | [] | no_license | EeckhoutJens/Prog4_LevelEditor | 5783688c501b6a72d0f6b357b6592ab392670378 | 102de514c03399c31604d83a89b3ca7173b97f92 | refs/heads/main | 2022-12-31T13:39:54.189424 | 2020-10-16T06:27:34 | 2020-10-16T06:27:34 | 304,539,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | h | #pragma once
#include "Grid.h"
namespace dae
{
class GameObject;
}
class Level
{
public:
Level(float Width, float Height, int rows, int cols);
~Level();
Level(const Level& other) = delete;
Level(Level&& other) = delete;
Level& operator=(const Level& other) = delete;
Level& operator=(Level && other) = delete;
std::shared_ptr<dae::GameObject> CreateNewEnemy(float posX, float posY, GameObjectType type);
Grid* GetGrid() { return m_pGrid; }
void WriteToFile(BinaryWriter& writer, const char* filename);
private:
Grid* m_pGrid;
std::vector<std::shared_ptr<dae::GameObject>> m_pEnemies{};
};
| [
"[email protected]"
] | |
a6bfc7d949241450ba397c5fdb76b253e3edc887 | 26ad4cc35496d364b31396e43a863aee08ef2636 | /SDK/SoT_Title_MA_06_MerchantLieutenant_functions.cpp | 84c83549acdbf47807f7d3d85826f6000ec35576 | [] | no_license | cw100/SoT-SDK | ddb9b19ce6ae623299b2b02dee51c29581537ba1 | 3e6f12384c8e21ed83ef56f00030ca0506d297fb | refs/heads/master | 2020-05-05T12:09:55.938323 | 2019-03-20T14:11:57 | 2019-03-20T14:11:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | cpp | // Sea of Thieves (1.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_Title_MA_06_MerchantLieutenant_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
fccf6ac4a8c10bf270bf7ef0c91986452c5625ed | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/new_hunk_8106.cpp | 32c32cfb8641ec8a115704091a131508653d8ca5 | [] | 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 | 326 | cpp | else {
/* Reading from stdin */
contents_from = "standard input";
mode = 0;
if (strbuf_read(&buf, 0) < 0)
die("read error %s from stdin", strerror(errno));
}
origin->file.ptr = buf.buf;
origin->file.size = buf.len;
pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
commit->util = origin;
/*
| [
"[email protected]"
] | |
01cd813db7c46d6d0928532177d5391918066c2c | e68c1f9134b44ddea144f7efa7523076f3f12d3a | /FinalCode/Wizard_FrostNova_ArrowEffect.h | ed6c9118fd3c84baf413e9a87395aa18df37be9e | [] | no_license | iso5930/Direct-3D-Team-Portfolio | 4ac710ede0c9176702595cba5579af42887611cf | 84e64eb4e91c7e5b4aed77212cd08cfee038fcd3 | refs/heads/master | 2021-08-23T08:15:00.128591 | 2017-12-04T06:14:39 | 2017-12-04T06:14:39 | 112,998,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 517 | h | #pragma once
#include "effect.h"
class CWizard_FrostNova_ArrowEffect : public CEffect
{
private:
D3DXVECTOR3 m_vDir;
float m_fTime;
float m_fDelayTime;
int m_iMode;
public:
virtual void Initialize();
virtual int Update();
virtual void Render();
virtual void Release();
public:
void Mode1();
void Mode2();
public:
explicit CWizard_FrostNova_ArrowEffect(TCHAR* _tszObjKey, OBJ_TYPE _eObjType, CObject* _pOwner, D3DXVECTOR3* _pDir, float _fDelayTime);
virtual ~CWizard_FrostNova_ArrowEffect(void);
}; | [
"[email protected]"
] | |
bdeefaf9675e9cd4c86124c8bab43818ada73372 | 322db0227e38a60db6541f94c305f4460b5f9573 | /51Nod/1967.cpp | 0a2b5073db4ca2f568fbd00d7927ffa8848a92f6 | [] | no_license | miluplay/AlgorithmProblemList | 74eb29ff4810be1f3807d3ca37fe53bd38852b4e | 36327009afe863ad6a25ac80e2ebfddc11ef5cd9 | refs/heads/master | 2022-12-22T06:48:59.098857 | 2020-08-26T09:47:29 | 2020-08-26T09:47:29 | 269,381,987 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | // Link:https://www.51nod.com/Challenge/Problem.html#problemId=1967
#include <iostream>
#define BT ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0);
using namespace std;
int main() { BT
return 0; } | [
"[email protected]"
] | |
5f0c7941cc5c55e77848b098ea89511a479b2e9f | 4c7d4201ca95f5841dae243535b98d99d48df952 | /version1_0/Arduino/develop/Serial/printBoolean/printBoolean.ino | 3644b39b5b6d6db862bbbd69ea8c3016dac30d62 | [
"MIT"
] | permissive | atmelino/MPPT | c09b916fce6f6a7fe95f82e08a9f65b9cf4baa75 | 7db2eab8b8a8679aab2d99a2f4825a6efa0a102c | refs/heads/master | 2022-12-11T01:29:06.878018 | 2019-10-29T03:54:55 | 2019-10-29T03:54:55 | 168,106,771 | 2 | 0 | MIT | 2022-12-10T17:18:28 | 2019-01-29T07:04:25 | C | UTF-8 | C++ | false | false | 481 | ino |
boolean MODE_PWM_MPPT, MODE_PWM_POT, MODE_PWM_SER;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
MODE_PWM_MPPT = true;
}
void loop() {
// put your main code here, to run repeatedly:
//Serial.println(true);
Serial.println(MODE_PWM_MPPT);
Serial.print("Mode MPPT ");
Serial.print(MODE_PWM_MPPT);
Serial.print(" POT ");
Serial.print(MODE_PWM_POT);
Serial.print(" SERIAL ");
Serial.println(MODE_PWM_SER);
delay(1000);
}
| [
"[email protected]"
] | |
58095737c8641c906f49c8ec8374f0dfc0ae88f0 | f9b6a5940859e5a2a72830107b9cd0aabdb086a0 | /IEX/IEX_SkinMesh.cpp | 8a32a3d98c234982010678b0a8ab506314fa8580 | [] | no_license | yopparaisenshi00/GhostPint3 | cf44c06058fafaf7825c26ff7a70d9caed2f3c08 | 70380cc0037648a2a5a58a55292e9c0812721795 | refs/heads/master | 2020-04-25T15:56:21.514056 | 2019-03-01T06:47:35 | 2019-03-01T06:47:35 | 172,893,443 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,924 | cpp | #include "iextreme.h"
//**************************************************************************************************
//
// スキンメッシュ関連
//
//**************************************************************************************************
//*****************************************************************************
// フレーム更新
//*****************************************************************************
void iex3DObj::UpdateSkinMeshFrame( float frame )
{
DWORD i, j;
LPIEXANIME2 lpAnime;
float t;
for( i=0 ; i<NumBone ; i++ ){
lpAnime = &this->lpAnime[i];
// ポーズ設定
if( lpAnime->rotNum == 0 ) CurPose[i] = orgPose[i];
else if( lpAnime->rotNum == 1 ) CurPose[i] = lpAnime->rot[0];
else {
// 回転キー補間
for( j=0 ; j<lpAnime->rotNum-1 ; j++ )
{
// 現在位置検索
if( (frame>=lpAnime->rotFrame[j]) && (frame<lpAnime->rotFrame[j+1]) )
{
// 経過フレーム計算
t = (float)(frame-lpAnime->rotFrame[j]) / (float)(lpAnime->rotFrame[j+1] - lpAnime->rotFrame[j]);
// 補間
CurPose[i] = QuaternionSlerp( lpAnime->rot[j], lpAnime->rot[j+1], t );
break;
}
}
if( j == lpAnime->rotNum-1 ) CurPose[i] = lpAnime->rot[lpAnime->rotNum-1];
}
// 座標設定
if( lpAnime->posNum == 0 ) CurPos[i] = orgPos[i];
else {
// 位置補間
for( j=0 ; j<lpAnime->posNum-1 ; j++ )
{
// 現在位置検索
if( (frame>=lpAnime->posFrame[j]) && (frame<lpAnime->posFrame[j+1]) )
{
// 経過フレーム計算
t = (float)(frame-lpAnime->posFrame[j]) / (float)(lpAnime->posFrame[j+1] - lpAnime->posFrame[j]);
// 補間
CurPos[i] = lpAnime->pos[j] + (lpAnime->pos[j+1]-lpAnime->pos[j])*t;
break;
}
}
if( j == lpAnime->posNum-1 ) CurPos[i] = lpAnime->pos[lpAnime->posNum-1];
}
}
}
//*****************************************************************************
// ボーン行列更新
//*****************************************************************************
void iex3DObj::UpdateBoneMatrix()
{
DWORD i;
// ボーン更新
for( i=0 ; i<NumBone ; i++ )
{
CurPose[i].toMatrix( lpBoneMatrix[i] );
// 位置情報コピー
lpBoneMatrix[i]._41 = CurPos[i].x;
lpBoneMatrix[i]._42 = CurPos[i].y;
lpBoneMatrix[i]._43 = CurPos[i].z;
if( BoneParent[i] != 0xFFFF ) lpBoneMatrix[i] *= lpBoneMatrix[ BoneParent[i] ];
}
for( i=0 ; i<NumBone ; i++ )
{
lpMatrix[i] = lpOffsetMatrix[i] * lpBoneMatrix[i];
}
}
//*****************************************************************************
// スキンメッシュ更新
//*****************************************************************************
void iex3DObj::UpdateSkinMesh()
{
// メッシュ更新
void* pVertex;
lpMesh->LockVertexBuffer( D3DLOCK_DISCARD, &pVertex );
lpSkinInfo->UpdateSkinnedMesh( lpMatrix, NULL, lpVertex, pVertex );
lpMesh->UnlockVertexBuffer();
}
| [
"[email protected]"
] | |
1211e88ae856ec1b0cbfc95d104a6f4981726f05 | 622b76741cfe3b7fd1884fa29f418f1be77e64ce | /Sources/browse.temp[2].cpp | c00b8f9a7133182ec5e7549a4412eea7a0897b40 | [] | no_license | shasa2013/fileman | ac63f3774015504f8917b80d19ac2a7d30a374c7 | bc38a2933ef1779408414ab6d7b8524cf67a92ca | refs/heads/master | 2020-07-05T09:56:59.545294 | 2013-06-12T16:02:58 | 2013-06-12T16:02:58 | 10,646,652 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 9,905 | cpp | #include "browse.h"
BOOL onColumnClick (HWND hDlg, WPARAM wParam, LPARAM lParam)
{
if (lParam == NULL) return FALSE;
NMLISTVIEW* nmlv = (NMLISTVIEW*) lParam;
FmSort sort;
sort.column = nmlv->iSubItem;
sort.dir = TRUE;
sort.separate = TRUE;
sort.hListView = GetDlgItem (hDlg, wParam);
sort.flags = NORM_IGNORECASE | NORM_IGNOREWIDTH;
sort.locale = LOCALE_USER_DEFAULT;
sort.separate = TRUE;
// Сортировать
SendMessage (sort.hListView, LVM_SORTITEMSEX, (WPARAM) &sort, (LPARAM) sortListView);
// Сохранить индекс колонки по которой выполнена сортировка
FmPanelProps* props = (FmPanelProps*) GetProp (sort.hListView, L"Props");
props->sortColumnIndex = sort.column;
return TRUE;
}
INT_PTR onListFinished (HWND hDlg, WPARAM wParam, LPARAM lParam)
{
LTPD* ltpd = (LTPD*) lParam;
HWND hPanel = GetDlgItem (hDlg, ltpd->itemId);
UINT diskListId = (UINT) GetProp (hPanel, L"diskListId");
EnableWindow (GetDlgItem(hDlg, diskListId), TRUE);
SendMessage (hPanel, WM_SETREDRAW, (WPARAM) TRUE, 0);
InvalidateRect (hPanel, NULL, NULL);
removeOperationThread (hPanel);
FmPanelProps* props = (FmPanelProps*) GetProp (hPanel, L"Props");
NMLISTVIEW nmlv = {0};
nmlv.iSubItem = props->sortColumnIndex;
onColumnClick (hDlg, ltpd->itemId, (LPARAM) &nmlv);
delete ltpd;
return 0;
}
BOOL listDirectoryToPanel (HWND hDlg, UINT panelId, UINT fullPathId)
{
// Проверяем что не идёт подсчёт размера файлов
HWND hPanel = GetDlgItem (hDlg, panelId);
if (isOperationThreadExist (hPanel)) return FALSE;
INT countedItem = (INT) GetProp (hPanel, L"Counted item");
if (countedItem > 0)
{
return FALSE;
}
LTPD* ltpd = new LTPD();
SendDlgItemMessage (hDlg, fullPathId, WM_GETTEXT, ltpd->getPathAllocSize(), (LPARAM)ltpd->path);
ltpd->hDlg = hDlg;
ltpd->itemId = panelId;
HANDLE hThread = CreateThread (NULL, NULL, listDirectoryToPanelWorker, ltpd, CREATE_SUSPENDED, NULL);
if (hThread == NULL)
{
delete ltpd;
return FALSE;
}
// Запретить перерисовку
SendDlgItemMessage(ltpd->hDlg, ltpd->itemId, WM_SETREDRAW, (WPARAM) FALSE, 0);
// Сохранить дескриптор потока
setOperationThread (hPanel, hThread, TRUE);
// Запустить поток
return resumeOperationThread (hPanel);
}
DWORD WINAPI listDirectoryToPanelWorker (void* args)
{
BOOL isUpDirPresent; // Флаг, обозначает то что переход на дирректорию выше найден
LTPD* ltpd = (LTPD*) args;
TCHAR str [FM_MAX_PATH];
str [0] = L'\0';
HIMAGELIST hIL = NULL;
LVITEM lvI = {0};
lvI.pszText = str;
lvI.cchTextMax = sizeof(str) / sizeof (str[0]);
// Очистить панель от своих данных
lvI.mask = LVIF_PARAM;
BOOL rc = TRUE;
while (rc)
{
rc = SendDlgItemMessage (ltpd->hDlg, ltpd->itemId, LVM_GETITEM, 0, (LPARAM)&lvI);
if (rc)
{
if (lvI.lParam != NULL)
{
fmLocalFree ((HLOCAL)lvI.lParam);
}
lvI.lParam = NULL;
++ lvI.iItem;
}
}
lvI.mask = LVIF_TEXT | LVIF_IMAGE;
lvI.iItem = 0;
lvI.lParam = 0;
SendDlgItemMessage (ltpd->hDlg, ltpd->itemId, LVM_DELETEALLITEMS, 0, 0);
hIL = (HIMAGELIST) SendDlgItemMessage (ltpd->hDlg, ltpd->itemId, LVM_GETIMAGELIST, (WPARAM)LVSIL_SMALL, 0);
if (hIL == NULL)
{
hIL = ImageList_Create (16, 16, ILC_COLORDDB, 255, 1);
SendDlgItemMessage (ltpd->hDlg, ltpd->itemId, LVM_SETIMAGELIST, LVSIL_SMALL, (LPARAM) hIL);
}
else
{
ImageList_RemoveAll (hIL);
}
WIN32_FIND_DATA findData = {0};
wsprintf (str, L"%s%s", ltpd->path, L"\\*");
HANDLE hFFile = FindFirstFile (str, &findData);
if (hFFile != INVALID_HANDLE_VALUE)
{
isUpDirPresent = findData.cFileName[0] == L'.';
isUpDirPresent &= findData.cFileName[1] == L'.';
isUpDirPresent &= findData.cFileName[2] == L'\0';
if (FM_AFTLV_OK == addFileToListView (ltpd->hDlg, &findData, ltpd->itemId, &lvI))
{
setFileIcon (ltpd->hDlg, ltpd->path, &findData, &lvI, hIL);
lvI.mask = LVIF_IMAGE;
SendDlgItemMessage (ltpd->hDlg, ltpd->itemId, LVM_SETITEM, 0, (LPARAM)&lvI);
// Перейти к следующей строке
++ lvI.iItem;
}
while (FindNextFile (hFFile, &findData))
{
if (!isUpDirPresent)
{
if (lstrcmp (findData.cFileName, L"..") == 0)
{
isUpDirPresent = TRUE;
}
}
if (FM_AFTLV_OK == addFileToListView (ltpd->hDlg, &findData, ltpd->itemId, &lvI))
{
setFileIcon (ltpd->hDlg, ltpd->path, &findData, &lvI, hIL);
lvI.mask = LVIF_IMAGE;
SendDlgItemMessage (ltpd->hDlg, ltpd->itemId, LVM_SETITEM, 0, (LPARAM)&lvI);
++ lvI.iItem;
}
}
FindClose (hFFile);
}
else // Возникла ошибка
{
// Показать List View
wprintfd (L"Возникла ошибка при FindFirstFile('%s', ...)", str);
SendMessage (ltpd->hDlg, FM_LIST_FINISHED, ltpd->itemId, (LPARAM)ltpd);
return 1;
}
// Символ L".." не был найден, значит его надо вставить
if (!isUpDirPresent)
{
// Имя файла L".." и соответствующая иконка
HINSTANCE hInst = (HINSTANCE) GetWindowLong (ltpd->hDlg, GWL_HINSTANCE);
HICON hIcon = LoadIcon (hInst, MAKEINTRESOURCE (IDI_ICON1));
lvI.iItem = 0; // L".." всегда в первой строке
lvI.iImage = ImageList_ReplaceIcon (hIL, lvI.iItem, hIcon);
lvI.iSubItem = FM_COLUMN_NAME; // Колонка названия файлов
lvI.pszText = L"..";
lvI.lParam = NULL;
SendDlgItemMessage (ltpd->hDlg, ltpd->itemId, LVM_INSERTITEM, (WPARAM)0, (LPARAM)&lvI);
DestroyIcon (hIcon);
}
// Сортировать панель
FmPanelProps* props = (FmPanelProps*)GetProp (GetDlgItem(ltpd->hDlg, ltpd->itemId), L"Props");
NMLISTVIEW nmlv = {0};
nmlv.iSubItem = props->sortColumnIndex;
lvI.mask = LVIF_IMAGE;
DWORD cnt = SendDlgItemMessage(ltpd->hDlg, ltpd->itemId, LVM_GETITEMCOUNT, 0, 0);
for (lvI.iItem = 0; lvI.iItem < cnt; ++ lvI.iItem)
{
SendDlgItemMessage (ltpd->hDlg, ltpd->itemId, LVM_GETITEM,0, (LPARAM) &lvI);
wprintfd(L"item:%u image:%u", lvI.iItem, lvI.iImage);
}
SendMessage (ltpd->hDlg, FM_LIST_FINISHED, ltpd->itemId, (LPARAM)ltpd);
return 0;
}
DWORD addFileToListView (HWND hDlg, WIN32_FIND_DATA* findData, UINT itemId, LVITEM* lvI)
{
SYSTEMTIME stUTC;
SYSTEMTIME stLocal;
TCHAR str1 [MAX_PATH];
TCHAR* tmpStr1;
if (lstrcmp(findData->cFileName, L".") == 0)
{
return FM_AFTLV_NO;
}
// Занести данные из findData
lvI->lParam = (LPARAM) fmLocalAlloc (sizeof(WIN32_FIND_DATA));
CopyMemory ((VOID*)lvI->lParam, (const VOID*) findData, sizeof (WIN32_FIND_DATA));
// Создать новую строку
lvI->iSubItem = 0;
lvI->pszText[0] = L'\0';
lvI->mask = LVIF_PARAM;
SendDlgItemMessage (hDlg, itemId, LVM_INSERTITEM, (WPARAM)0, (LPARAM)lvI);
lvI->mask = LVIF_TEXT;
// Файл или папка
if (findData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// если папка
lvI->iSubItem = FM_COLUMN_NAME;
lstrcpy (lvI->pszText, findData->cFileName);
SendDlgItemMessage(hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
lvI->iSubItem = FM_COLUMN_TYPE;
lstrcpy (lvI->pszText, FM_DIRTYPE_STUB);
SendDlgItemMessage(hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
}
else
{
// Если файл, то тип файла
lvI->iSubItem = FM_COLUMN_TYPE;
tmpStr1 = lstrrchr (findData->cFileName, L'.');
if (tmpStr1 != NULL)
{
++ tmpStr1;
lstrcpy (lvI->pszText, tmpStr1);
SendDlgItemMessage (hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
}
// имя файла
lvI->iSubItem = FM_COLUMN_NAME;
lstrcpy (lvI->pszText, findData->cFileName);
lcutrchr (lvI->pszText, L'.');
SendDlgItemMessage(hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
// размер файла
UINT64 fs = findData->nFileSizeLow | (UINT64(findData->nFileSizeHigh) << 32);
StrFormatByteSize (LONGLONG(fs), str1, sizeof (str1) / sizeof (str1[0]));
lvI->iSubItem = FM_COLUMN_SIZE;
lstrcpy (lvI->pszText, str1);
SendDlgItemMessage (hDlg, itemId, LVM_SETITEM, (WPARAM)lvI->iItem, (LPARAM)lvI);
}
// Дата файла или папки
lvI->iSubItem = FM_COLUMN_DATE;
FileTimeToSystemTime(&findData->ftLastWriteTime, &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
wsprintf(str1, L"%02u-%02u-%02u %02u:%02u", stLocal.wYear, stLocal.wMonth,
stLocal.wDay, stLocal.wHour, stLocal.wMinute);
lstrcpy (lvI->pszText, str1);
SendDlgItemMessage (hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
return FM_AFTLV_OK;
}
VOID setFileIcon (HWND hDlg, TCHAR* fileDir, WIN32_FIND_DATA* findData, LVITEM* lvI, HIMAGELIST hIL)
{
SHFILEINFO shfi;
if (lstrcmp (findData->cFileName, L"..") == 0)
{
HINSTANCE hInst = (HINSTANCE) GetWindowLong (hDlg, GWL_HINSTANCE);
shfi.hIcon = LoadIcon (hInst, MAKEINTRESOURCE (IDI_ICON1));
lvI->iImage = ImageList_AddIcon (hIL, shfi.hIcon);
}
else
{
TCHAR fullPath [FM_MAX_PATH];
lstrcpy (fullPath, fileDir);
lstrcat (fullPath, findData->cFileName);
SHGetFileInfo (fullPath, findData->dwFileAttributes, &shfi, sizeof(SHFILEINFO),
SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES | SHGFI_ADDOVERLAYS);
if (shfi.hIcon == NULL)
{
wprintfd (L"Не найдена иконка для файла %s", fullPath);
return;
}
lvI->iImage = ImageList_ReplaceIcon (hIL, -1, shfi.hIcon);
if (lvI->iImage == -1)
{
lvI->iImage = 0;
}
}
DestroyIcon (shfi.hIcon);
return;
}
| [
"[email protected]"
] | |
8080ff7952843fee3933f30126fdb26af9e5dc54 | 7bb00eea506d129c94cede3001d437f4ebc4b16f | /20180420/Include/2d/Segment.h | cb756df11ccc40f56e29f4ba81530601cb10411d | [] | no_license | jhd41/ToolFrame | 3e5c82b5a5c41e1ba844b93c3df6dfc5a41572d9 | 250c7d4371eca95acc1a579f2b861a1c94dfe9e4 | refs/heads/master | 2020-03-15T03:04:58.371922 | 2018-05-03T03:01:10 | 2018-05-03T03:03:05 | 131,933,829 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,064 | h | #pragma once
#include "Macro.h"
//此处的线段为一维线段,仅由2个值表示起点和终点
NS_TOOL_FRAME_BEGIN
class TOOLFRAME_DLL CSegment
{
public:
bool IsContain(float fPosition)const; //是否包含该位置
bool IsContain(const CSegment& seg)const; //是否包含线段
bool IsIntersect(const CSegment& seg)const; //线段是否相交
bool CalIntersect(CSegment& segSub,const CSegment& seg)const;//计算相交区域
float GetLength() const; //获取线段长度
float GetMidPosition()const; //获取线段中点
bool SetSegment(float fPositionBegin,float fPositionEnd);
bool SetSegment(int nPositionBegin,int nPositionEnd);
bool SetSegment(const CSegment& seg);
public:
bool operator == (const CSegment& seg)const;
bool operator != (const CSegment& seg)const;
public:
CSegment(void);
CSegment(float fPositionBegin,float fPositionEnd);
CSegment(int nPositionBegin,int nPositionEnd);
CSegment(const CSegment& seg);
virtual ~CSegment(void);
private:
CFIELD_FLOAT(Begin);
CFIELD_FLOAT(End);
};
NS_TOOL_FRAME_END | [
"[email protected]"
] | |
d56d71fe9a132c748726760bdfbaff09a3f3be4a | 3d0df26b2a7895f61e500f7cd2d792d35c9a86e8 | /base_workspace/cc/backend/memory/ram/default_module.h | bc75706c9ae8011e4c417be08efbbc2ada220cb2 | [] | no_license | turbo-santa/turbo-santa-common | d275540839311e80ce7a3a45d4d73fc203c0fc99 | de2e4df8fb28ddb8568ce35db740bf4155338dbb | refs/heads/master | 2022-07-15T06:45:56.611139 | 2016-05-22T22:43:43 | 2016-05-22T22:43:43 | 23,727,325 | 8 | 4 | null | 2022-10-22T11:17:07 | 2014-09-06T05:08:36 | C++ | UTF-8 | C++ | false | false | 3,551 | h | #ifndef TURBO_SANTA_COMMON_BACK_END_MEMORY_DEFAULT_MODULE_H_
#define TURBO_SANTA_COMMON_BACK_END_MEMORY_DEFAULT_MODULE_H_
#include <memory>
#include "cc/backend/memory/memory_segment.h"
#include "cc/backend/memory/module.h"
#include "cc/backend/memory/ram/echo_segment.h"
#include "cc/backend/memory/ram/ram_segment.h"
// The majority of memory segments are simple and do not require any special
// initialization; they have been collected here.
//
// Other more complicated memory segments have been divested into different
// modules.
//
// The overall memory layout:
// 0x0000 - 0x0100
// rom_bank_0 0x0000 - 0x3fff
// rom_bank_n 0x4000 - 0x7fff
// cartridge_ram 0xa000 - 0xbfff
// vram 0x8000 - 0x9fff
// ram_bank_0 0xc000 - 0xcfff
// ram_bank_n 0xd000 - 0xdfff
// echo 0xe000 - 0xfdff
// oam 0xfe00 - 0xfe9f
// not_usable 0xfea0 - 0xfeff
// interrupt_flag 0xff0f
//
//
// internal_rom_flag 0xff50
// joypad 0xff00
// io_ports 0xff01 - 0xff7f
// high_ram 0xff80 - 0xfffe
// interrupt_enable 0xffff
namespace backend {
namespace memory {
class DefaultModule : public Module {
public:
void Init() {
add_memory_segment(&internal_ram_0_);
add_memory_segment(&internal_ram_1_);
add_memory_segment(&echo_segment_);
add_memory_segment(¬_usable_);
add_memory_segment(&high_ram_);
}
private:
// InternalROM internal_rom_; // 0x0000 - 0x0100
// std::unique_ptr<MBC> mbc_; // rom_bank_0 0x0000 - 0x3fff
// rom_bank_n 0x4000 - 0x7fff
// cartridge_ram 0xa000 - 0xbfff
// VRAMSegment vram_; // vram 0x8000 - 0x9fff
RAMSegment internal_ram_0_ = RAMSegment(0xc000, 0xcfff); // ram_bank_0 0xc000 - 0xcfff
RAMSegment internal_ram_1_ = RAMSegment(0xd000, 0xdfff); // ram_bank_n 0xd000 - 0xdfff
EchoSegment echo_segment_ = EchoSegment(&internal_ram_0_, &internal_ram_1_); // echo 0xe000 - 0xfdff
// OAMSegment oam_segment_; // oam 0xfe00 - 0xfe9f
NullMemorySegment not_usable_ = NullMemorySegment(0xfea0, 0xfeff); // not_usable 0xfea0 - 0xfeff
// InterruptFlag interrupt_flag_; // interrupt_flag 0xff0f
// GraphicsFlags graphics_flags_; //
// DMATransfer dma_transfer_; //
// InternalROMFlag internal_rom_flag_; // internal_rom_flag 0xff50
// JoypadMemory joypad_; // joypad 0xff00
// NullMemorySegment io_ports_ = NullMemorySegment(0xff01, 0xff7f); // io_ports 0xff01 - 0xff7f
RAMSegment high_ram_ = RAMSegment(0xff80, 0xfffe); // high_ram 0xff80 - 0xfffe
// InterruptEnable interrupt_enable_; // interrupt_enable 0xffff
};
} // namespace memory
} // namespace backend
#endif // TURBO_SANTA_COMMON_BACK_END_MEMORY_DEFAULT_MODULE_H_
| [
"[email protected]"
] | |
aabd780ab2b7a77b4610a979fd9bd5ee94f427e9 | 5489208422fde50e5e345ee9b5a13f8c7a76e1e0 | /src/zsyrk.cpp | 4af74e0c28c57ce6c95835f761ce2d41267a131a | [] | no_license | langou/tblas | ef4176f90320a48fbc2d61851b8eedb2405045b0 | a1693c72b38ff77614aeb80ce2aecdef74ff1d0c | refs/heads/master | 2022-12-10T15:15:31.299006 | 2020-09-01T21:07:06 | 2020-09-01T21:07:06 | 292,107,386 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 798 | cpp | #include "blas.h"
#include "syrk.h"
#include <cctype>
#include <utility>
using std::max;
using std::toupper;
using tblas::syrk;
void zsyrk_(const char &Uplo, const char &Trans, const int &n, const int &k, const complex<double> &alpha, complex<double> *A, const int &ldA, const complex<double> &beta, complex<double> *C, const int &ldC)
{
int info=0;
char trans=toupper(Trans);
char uplo=toupper(Uplo);
if((uplo!='U')&&(uplo!='L'))
info=1;
else if((trans!='N')&&(trans!='T'))
info=2;
else if(n<0)
info=3;
else if(k<0)
info=4;
else if(ldA<max(1,(trans=='N')?n:k))
info=7;
else if(ldC<max(1,n))
info=10;
if(info>0)
xerbla_("ZSYRK ",info);
else
syrk(uplo,trans,n,k,alpha,A,ldA,beta,C,ldC);
}
| [
"[email protected]"
] | |
9ae8782dbfc39dff451b8addf671ba63def9923f | acc5e8b53081c8407a64ecc878aead6f8cb554e9 | /ReductionOperation.cpp | 2ab2b730da965171d3412cbcbc6901cc875b25bf | [] | no_license | mcleary/ParallelOrdinaryKriging | 210609513be6c1163d5d3ebcabb65ce1fc54879a | 65806e9e3a739e23ef1ebfe71d702c08ea108c30 | refs/heads/master | 2023-02-23T01:27:32.594897 | 2021-01-29T17:25:32 | 2021-01-29T17:25:32 | 332,309,118 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,274 | cpp |
#include "ReductionOperation.h"
#include <algorithm>
#include <limits>
#include <iostream>
template<class T>
T NeutralElement(ReductionOp Operation)
{
switch (Operation)
{
case ReductionOp::Min:
return std::numeric_limits<T>::max();
case ReductionOp::Max:
return -std::numeric_limits<T>::max();
case ReductionOp::Sum:
return static_cast<T>(0.0);
default:
break;
}
return static_cast<T>(0.0);
}
template<class T>
T Reduce(T Accumulator, T Element, ReductionOp Operation)
{
switch (Operation)
{
case ReductionOp::Min:
Accumulator = (Accumulator < Element) ? Accumulator : Element;
break;
case ReductionOp::Max:
Accumulator = (Accumulator > Element) ? Accumulator : Element;
break;
case ReductionOp::Sum:
Accumulator += Element;
break;
default:
break;
}
return Accumulator;
}
template<class T>
T ReduceCPU(T* Elements, int Count, ReductionOp Operation)
{
T Accumulator = NeutralElement<T>(Operation);
for (int Index = 0; Index < Count; ++Index)
{
const T Element = Elements[Index];
Accumulator = Reduce(Accumulator, Element, Operation);
}
return Accumulator;
}
static PointXYZ ReduceCPU(PointXYZ* Points, int Count, ReductionOp Operation)
{
auto Neutral = NeutralElement<float>(Operation);
PointXYZ Accumulator{ Neutral, Neutral, Neutral };
for (int Index = 0; Index < Count; ++Index)
{
const PointXYZ& Point = Points[Index];
Accumulator.x = Reduce(Accumulator.x, Point.x, Operation);
Accumulator.y = Reduce(Accumulator.y, Point.y, Operation);
Accumulator.z = Reduce(Accumulator.z, Point.z, Operation);
}
return Accumulator;
}
ReductionOperation::ReductionOperation(ComputePlatform& Platform) :
ThePlatform(Platform)
{
ReductionProgram = ThePlatform.CreateProgram("kernels/Reduction.cl");
}
float ReductionOperation::Reduce(cl::CommandQueue Queue, cl::Buffer InputBuffer, int Count, ReductionOp Operator)
{
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
auto DeviceType = Device.getInfo<CL_DEVICE_TYPE>();
DEBUG_OPERATION;
switch (DeviceType)
{
case CL_DEVICE_TYPE_CPU:
return ReduceCPUKernel(Queue, InputBuffer, Count, Operator);
case CL_DEVICE_TYPE_GPU:
return ReduceGPUKernel(Queue, InputBuffer, Count, Operator);
default:
break;
}
return 0.0f;
}
float ReductionOperation::Reduce(cl::Buffer InputBuffer, int Count, ReductionOp Operator)
{
auto Queue = ThePlatform.GetNextCommandQueue();
return Reduce(Queue, InputBuffer, Count, Operator);
}
PointXYZ ReductionOperation::ReducePoints(cl::CommandQueue Queue, cl::Buffer InputBuffer, int NumberOfPoints, ReductionOp Operator)
{
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
auto DeviceType = Device.getInfo<CL_DEVICE_TYPE>();
DEBUG_OPERATION;
switch (DeviceType)
{
case CL_DEVICE_TYPE_CPU:
return ReducePointsCPUKernel(Queue, InputBuffer, NumberOfPoints, Operator);
case CL_DEVICE_TYPE_GPU:
return ReducePointsGPUKernel(Queue, InputBuffer, NumberOfPoints, Operator);
default:
break;
}
return PointXYZ();
}
PointXYZ ReductionOperation::ReducePoints(cl::Buffer InputBuffer, int NumberOfPoints, ReductionOp Operator)
{
auto Queue = ThePlatform.GetNextCommandQueue();
return ReducePoints(Queue, InputBuffer, NumberOfPoints, Operator);
}
double ReductionOperation::ReduceDouble(cl::CommandQueue Queue, cl::Buffer InputBuffer, int Count, ReductionOp Operator)
{
DEBUG_OPERATION;
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
auto DeviceType = Device.getInfo<CL_DEVICE_TYPE>();
DEBUG_OPERATION;
switch (DeviceType)
{
case CL_DEVICE_TYPE_CPU:
return ReduceCPUDoubleKernel(Queue, InputBuffer, Count, Operator);
case CL_DEVICE_TYPE_GPU:
return ReduceGPUDoubleKernel(Queue, InputBuffer, Count, Operator);
default:
break;
}
return 0.0;
}
float ReductionOperation::ReduceCPUKernel(cl::CommandQueue Queue, cl::Buffer InputBuffer, int Count, ReductionOp Operator)
{
auto ReductionKernel = cl::make_kernel<cl::Buffer, int, int, cl::Buffer, int>(ReductionProgram, "ReduceKernel");
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
auto NumberOfBlocks = Device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
int BlockSize = Count / NumberOfBlocks;
if (Count % NumberOfBlocks != 0)
{
BlockSize++;
}
const int ResultBufferSize = sizeof(float) * NumberOfBlocks;
cl::Buffer ResultBuffer(ThePlatform.Context, CL_MEM_WRITE_ONLY, ResultBufferSize);
cl::NDRange GlobalRange(NumberOfBlocks);
cl::NDRange LocalRange(1);
auto Event = ReductionKernel(cl::EnqueueArgs(Queue, GlobalRange, LocalRange), InputBuffer, BlockSize, Count, ResultBuffer, static_cast<int>(Operator));
float* PartialResult = (float*)Queue.enqueueMapBuffer(ResultBuffer, CL_TRUE, CL_MAP_READ, 0, ResultBufferSize);
float Result = ReduceCPU(PartialResult, NumberOfBlocks, Operator);
Queue.enqueueUnmapMemObject(ResultBuffer, PartialResult);
ThePlatform.RecordEvent({ "TotalReduce", "ReduceCPU" }, Event);
return Result;
}
float ReductionOperation::ReduceGPUKernel(cl::CommandQueue Queue, cl::Buffer InputBuffer, int Count, ReductionOp Operator)
{
auto ReductionKernel = cl::make_kernel<cl::Buffer, cl::LocalSpaceArg, int, cl::Buffer, int>(ReductionProgram, "TwoStageReduceKernel");
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
const int NumberOfComputeUnits = Device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
const int NumberOfBlocks = NumberOfComputeUnits * 4;
const int MaxBlockSize = 256;
const int BlockSize = std::max(NumberOfBlocks % MaxBlockSize, 1);
const int NumberOfGroups = std::max(NumberOfBlocks / BlockSize, 1);
const int ResultBufferSize = sizeof(PointXYZ) * NumberOfGroups;
cl::Buffer ResultBuffer(ThePlatform.Context, CL_MEM_WRITE_ONLY, ResultBufferSize);
const int LocalMemSize = BlockSize * sizeof(PointXYZ);
cl::NDRange GlobalRange(NumberOfBlocks);
cl::NDRange LocalRange(BlockSize);
auto Event = ReductionKernel(cl::EnqueueArgs(Queue, GlobalRange, LocalRange), InputBuffer, cl::Local(LocalMemSize), Count, ResultBuffer, static_cast<int>(Operator));
float* PartialResult = (float*)Queue.enqueueMapBuffer(ResultBuffer, CL_TRUE, CL_MAP_READ, 0, ResultBufferSize);
float Result = ReduceCPU(PartialResult, NumberOfGroups, Operator);
Queue.enqueueUnmapMemObject(ResultBuffer, PartialResult);
ThePlatform.RecordEvent({ "Reduce", "ReduceGPU" }, Event);
return Result;
}
PointXYZ ReductionOperation::ReducePointsCPUKernel(cl::CommandQueue Queue, cl::Buffer InputBuffer, int NumberOfPoints, ReductionOp Operator)
{
auto ReductionKernel = cl::make_kernel<cl::Buffer, int, int, cl::Buffer, int>(ReductionProgram, "ReducePointsKernel");
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
auto NumberOfBlocks = Device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
int BlockSize = NumberOfPoints / NumberOfBlocks;
if (NumberOfPoints % NumberOfBlocks != 0)
{
BlockSize++;
}
const int ResultBufferSize = sizeof(PointXYZ) * NumberOfBlocks;
cl::Buffer ResultBuffer(ThePlatform.Context, CL_MEM_WRITE_ONLY, ResultBufferSize);
cl::NDRange GlobalRange(NumberOfBlocks);
cl::NDRange LocalRange(1);
auto Event = ReductionKernel(cl::EnqueueArgs(Queue, GlobalRange, LocalRange), InputBuffer, BlockSize, NumberOfPoints, ResultBuffer, static_cast<int>(Operator));
PointXYZ* PartialResult = (PointXYZ*)Queue.enqueueMapBuffer(ResultBuffer, CL_TRUE, CL_MAP_READ, 0, ResultBufferSize);
auto Result = ReduceCPU(PartialResult, NumberOfBlocks, Operator);
Queue.enqueueUnmapMemObject(ResultBuffer, PartialResult);
ThePlatform.RecordEvent({ "TotalReduce", "ReduceCPU" }, Event);
return Result;
}
PointXYZ ReductionOperation::ReducePointsGPUKernel(cl::CommandQueue Queue, cl::Buffer InputBuffer, int NumberOfPoints, ReductionOp Operator)
{
auto ReductionKernel = cl::make_kernel<cl::Buffer, cl::LocalSpaceArg, int, cl::Buffer, int>(ReductionProgram, "TwoStageReducePointKernel");
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
const int NumberOfComputeUnits = Device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
const int NumberOfBlocks = NumberOfComputeUnits * 4;
const int MaxBlockSize = 256;
const int BlockSize = std::max(NumberOfBlocks % MaxBlockSize, 1);
const int NumberOfGroups = std::max(NumberOfBlocks / BlockSize, 1);
const int ResultBufferSize = sizeof(PointXYZ) * NumberOfGroups;
cl::Buffer ResultBuffer(ThePlatform.Context, CL_MEM_WRITE_ONLY, ResultBufferSize);
const int LocalMemSize = BlockSize * sizeof(PointXYZ);
cl::NDRange GlobalRange(NumberOfBlocks);
cl::NDRange LocalRange(BlockSize);
auto Event = ReductionKernel(cl::EnqueueArgs(Queue, GlobalRange, LocalRange), InputBuffer, cl::Local(LocalMemSize), NumberOfPoints, ResultBuffer, static_cast<int>(Operator));
PointXYZ* PartialResult = (PointXYZ*)Queue.enqueueMapBuffer(ResultBuffer, CL_TRUE, CL_MAP_READ, 0, ResultBufferSize);
auto Result = ReduceCPU(PartialResult, NumberOfGroups, Operator);
Queue.enqueueUnmapMemObject(ResultBuffer, PartialResult);
ThePlatform.RecordEvent({ "TotalReduce", "ReduceGPU" }, Event);
return Result;
}
double ReductionOperation::ReduceCPUDoubleKernel(cl::CommandQueue Queue, cl::Buffer InputBuffer, int Count, ReductionOp Operator)
{
auto ReductionKernel = cl::make_kernel<cl::Buffer, int, int, cl::Buffer, int>(ReductionProgram, "ReduceDoubleKernel");
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
auto NumberOfBlocks = Device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
int BlockSize = Count / NumberOfBlocks;
if (Count % NumberOfBlocks != 0)
{
BlockSize++;
}
const int ResultBufferSize = sizeof(float) * NumberOfBlocks;
cl::Buffer ResultBuffer(ThePlatform.Context, CL_MEM_WRITE_ONLY, ResultBufferSize);
cl::NDRange GlobalRange(NumberOfBlocks);
cl::NDRange LocalRange(1);
auto Event = ReductionKernel(cl::EnqueueArgs(Queue, GlobalRange, LocalRange), InputBuffer, BlockSize, Count, ResultBuffer, static_cast<int>(Operator));
double* PartialResult = (double*) Queue.enqueueMapBuffer(ResultBuffer, CL_TRUE, CL_MAP_READ, 0, ResultBufferSize);
auto Result = ReduceCPU(PartialResult, NumberOfBlocks, Operator);
Queue.enqueueUnmapMemObject(ResultBuffer, PartialResult);
ThePlatform.RecordEvent({ "TotalReduce", "ReduceCPU" }, Event);
return Result;
}
double ReductionOperation::ReduceGPUDoubleKernel(cl::CommandQueue Queue, cl::Buffer InputBuffer, int Count, ReductionOp Operator)
{
auto ReductionKernel = cl::make_kernel<cl::Buffer, cl::LocalSpaceArg, int, cl::Buffer, int>(ReductionProgram, "TwoStageReduceDoubleKernel");
auto Device = Queue.getInfo<CL_QUEUE_DEVICE>();
const int NumberOfComputeUnits = Device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
const int NumberOfBlocks = NumberOfComputeUnits * 4;
const int MaxBlockSize = 256;
const int BlockSize = std::max(NumberOfBlocks % MaxBlockSize, 1);
const int NumberOfGroups = std::max(NumberOfBlocks / BlockSize, 1);
const int ResultBufferSize = sizeof(PointXYZ) * NumberOfGroups;
cl::Buffer ResultBuffer(ThePlatform.Context, CL_MEM_WRITE_ONLY, ResultBufferSize);
const int LocalMemSize = BlockSize * sizeof(PointXYZ);
cl::NDRange GlobalRange(NumberOfBlocks);
cl::NDRange LocalRange(BlockSize);
auto Event = ReductionKernel(cl::EnqueueArgs(Queue, GlobalRange, LocalRange), InputBuffer, cl::Local(LocalMemSize), Count, ResultBuffer, static_cast<int>(Operator));
double* PartialResult = (double*)Queue.enqueueMapBuffer(ResultBuffer, CL_TRUE, CL_MAP_READ, 0, ResultBufferSize);
auto Result = ReduceCPU(PartialResult, NumberOfGroups, Operator);
Queue.enqueueUnmapMemObject(ResultBuffer, PartialResult);
ThePlatform.RecordEvent({ "TotalReduce", "ReduceGPU" }, Event);
return Result;
} | [
"[email protected]"
] | |
6f8181a14ad8a176c68a427c15b9a2e7114f8acb | f6a0496efe3e5c93b68c1df66ce35e1c22c9b7b0 | /Source/LuaObject.cpp | 6e92e42ee79f6ff66bcc7283a70e5e5de2e966b9 | [] | no_license | jhays200/C---Lua-Interpreter | 479cce89eb782b577e0f350bc4c34e8357b75de6 | 9ebf62c0ded847753dec0fc98e62445b234eccd4 | refs/heads/master | 2020-05-18T15:56:23.933827 | 2011-03-10T20:04:38 | 2011-03-10T20:04:38 | 1,462,811 | 7 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 650 | cpp | #include "LuaObject.h"
#include <cstdio>
LuaObject::LuaObject(): m_id("")
{ }
LuaObject::LuaObject(string id): m_id(id)
{ }
LuaObject::~LuaObject()
{ }
LuaObject& LuaObject::operator=( LuaObject& rhs)
{
//error
return *this;
}
void LuaObject::setID(string id)
{
m_id = id;
}
string LuaObject::getID()
{
return m_id;
}
bool LuaObject::operator==(const string & rhs)
{
return m_id == rhs;
}
void LuaObject::DisplayValue()
{
//id value type
printf("%s Nil LuaObject\n", m_id.c_str());
}
int LuaObject::getType()
{
return NIL;
}
LuaObject LuaObject::operator+( LuaObject& rhs)
{
//ERROR
return *this;
} | [
"[email protected]"
] | |
81388085349ec05202b89ed844b204e09fe0eedb | ee92057a8ebc91ba90d8055a9bece25d24211499 | /kattis/bank/bank3.cpp | 30923e660e4e601b33c0fc6c63c19bcc371d5d08 | [] | no_license | KendrickAng/competitive-programming | ce0a4f44f592f295c2f8cd7e854139f18fb8853a | f9768a2020f801b8e4787cc853398b8258a0bf09 | refs/heads/master | 2022-05-29T07:21:32.607089 | 2022-04-24T16:35:14 | 2022-04-24T16:35:14 | 254,402,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | cpp | #include <iostream>
#include <vector>
int main() {
int n, t;
std::cin >> n >> t;
std::vector<int> money{};
money.resize(t+1);
for (int i = 0; i < n; i++) {
int ci, ti;
std::cin >> ci >> ti;
for (int time = ti; time >= 0; time--) {
if (money[time] < ci) {
std::swap(money[time], ci);
}
}
for (auto a: money) std::cout << a << " ";
std::cout << std::endl;
}
int total = 0;
for (auto a: money) {
total += a;
}
std::cout << total << std::endl;
} | [
"[email protected]"
] | |
f3a4b6d0b8891e43ebe42c0c2f96eee89a1cdc95 | f9ad90d4214992a1655fbcb683a72eb13170bdad | /rotate.cpp | 092a5d7c8be1d93691c084ae61fb2cc0a5285b47 | [] | no_license | cyanide1323/Interview | c030ae1d2a7bcd3ee67a268a3333a7315a0ce6e1 | a41ea37a7e47d65ed9c2c7a03b92347e870f2061 | refs/heads/master | 2021-01-20T13:02:50.468524 | 2017-06-27T16:07:23 | 2017-06-27T16:07:23 | 90,437,594 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | cpp | #include <iostream>
using namespace std;
void rotat(int arr[][4],int m,int n){
int i=0,j=0,start_row=0,start_col=0;
while(j<n){
cout<<arr[start_row][j]<<" ";
j++;
}
start_row++;
while(i<m){
cout<<arr[i][j]<<" ";
i++;
}
n--;
while(j>=start_col){
cout<<arr[i][j]<<" ";
j--;
}
m--;
while(i>=start_row){
cout<<arr[i][j]<<" ";
i--;
}
start_row++;
}
int main(){
int m,n; cin>>m>>n; int arr[m][n];
for(int i=0;i<m;i++) for(int j=0;j<n;j++) cin>>arr[i][j];
rotat(arr,m,n);
return 0;
}
| [
"[email protected]"
] |
Subsets and Splits