blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
62d0dc7736c91cbc577893e1d4ce3c954285e475 | 6c4699de64796bde99b9781ce6bcbbde5be4f2a4 | /External/opencv-2.4.6.1/modules/features2d/src/orb.cpp | 8aeea829a859a37b7ded06342fe10c1c5d96dad9 | [] | no_license | simonct/CoreAstro | 3ea33aea2d9dd3ef1f0fbb990b4036c8ab8c6778 | eafd0aea314c427da616e1707a49aaeaf5ea6991 | refs/heads/master | 2020-05-22T04:03:57.706741 | 2014-10-25T07:30:40 | 2014-10-25T07:30:40 | 5,735,802 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,754 | cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/** Authors: Ethan Rublee, Vincent Rabaud, Gary Bradski */
#include "precomp.hpp"
#include <iterator>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace cv
{
const float HARRIS_K = 0.04f;
const int DESCRIPTOR_SIZE = 32;
/**
* Function that computes the Harris responses in a
* blockSize x blockSize patch at given points in an image
*/
static void
HarrisResponses(const Mat& img, vector<KeyPoint>& pts, int blockSize, float harris_k)
{
CV_Assert( img.type() == CV_8UC1 && blockSize*blockSize <= 2048 );
size_t ptidx, ptsize = pts.size();
const uchar* ptr00 = img.ptr<uchar>();
int step = (int)(img.step/img.elemSize1());
int r = blockSize/2;
float scale = (1 << 2) * blockSize * 255.0f;
scale = 1.0f / scale;
float scale_sq_sq = scale * scale * scale * scale;
AutoBuffer<int> ofsbuf(blockSize*blockSize);
int* ofs = ofsbuf;
for( int i = 0; i < blockSize; i++ )
for( int j = 0; j < blockSize; j++ )
ofs[i*blockSize + j] = (int)(i*step + j);
for( ptidx = 0; ptidx < ptsize; ptidx++ )
{
int x0 = cvRound(pts[ptidx].pt.x - r);
int y0 = cvRound(pts[ptidx].pt.y - r);
const uchar* ptr0 = ptr00 + y0*step + x0;
int a = 0, b = 0, c = 0;
for( int k = 0; k < blockSize*blockSize; k++ )
{
const uchar* ptr = ptr0 + ofs[k];
int Ix = (ptr[1] - ptr[-1])*2 + (ptr[-step+1] - ptr[-step-1]) + (ptr[step+1] - ptr[step-1]);
int Iy = (ptr[step] - ptr[-step])*2 + (ptr[step-1] - ptr[-step-1]) + (ptr[step+1] - ptr[-step+1]);
a += Ix*Ix;
b += Iy*Iy;
c += Ix*Iy;
}
pts[ptidx].response = ((float)a * b - (float)c * c -
harris_k * ((float)a + b) * ((float)a + b))*scale_sq_sq;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float IC_Angle(const Mat& image, const int half_k, Point2f pt,
const vector<int> & u_max)
{
int m_01 = 0, m_10 = 0;
const uchar* center = &image.at<uchar> (cvRound(pt.y), cvRound(pt.x));
// Treat the center line differently, v=0
for (int u = -half_k; u <= half_k; ++u)
m_10 += u * center[u];
// Go line by line in the circular patch
int step = (int)image.step1();
for (int v = 1; v <= half_k; ++v)
{
// Proceed over the two lines
int v_sum = 0;
int d = u_max[v];
for (int u = -d; u <= d; ++u)
{
int val_plus = center[u + v*step], val_minus = center[u - v*step];
v_sum += (val_plus - val_minus);
m_10 += u * (val_plus + val_minus);
}
m_01 += v * v_sum;
}
return fastAtan2((float)m_01, (float)m_10);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void computeOrbDescriptor(const KeyPoint& kpt,
const Mat& img, const Point* pattern,
uchar* desc, int dsize, int WTA_K)
{
float angle = kpt.angle;
//angle = cvFloor(angle/12)*12.f;
angle *= (float)(CV_PI/180.f);
float a = (float)cos(angle), b = (float)sin(angle);
const uchar* center = &img.at<uchar>(cvRound(kpt.pt.y), cvRound(kpt.pt.x));
int step = (int)img.step;
#if 1
#define GET_VALUE(idx) \
center[cvRound(pattern[idx].x*b + pattern[idx].y*a)*step + \
cvRound(pattern[idx].x*a - pattern[idx].y*b)]
#else
float x, y;
int ix, iy;
#define GET_VALUE(idx) \
(x = pattern[idx].x*a - pattern[idx].y*b, \
y = pattern[idx].x*b + pattern[idx].y*a, \
ix = cvFloor(x), iy = cvFloor(y), \
x -= ix, y -= iy, \
cvRound(center[iy*step + ix]*(1-x)*(1-y) + center[(iy+1)*step + ix]*(1-x)*y + \
center[iy*step + ix+1]*x*(1-y) + center[(iy+1)*step + ix+1]*x*y))
#endif
if( WTA_K == 2 )
{
for (int i = 0; i < dsize; ++i, pattern += 16)
{
int t0, t1, val;
t0 = GET_VALUE(0); t1 = GET_VALUE(1);
val = t0 < t1;
t0 = GET_VALUE(2); t1 = GET_VALUE(3);
val |= (t0 < t1) << 1;
t0 = GET_VALUE(4); t1 = GET_VALUE(5);
val |= (t0 < t1) << 2;
t0 = GET_VALUE(6); t1 = GET_VALUE(7);
val |= (t0 < t1) << 3;
t0 = GET_VALUE(8); t1 = GET_VALUE(9);
val |= (t0 < t1) << 4;
t0 = GET_VALUE(10); t1 = GET_VALUE(11);
val |= (t0 < t1) << 5;
t0 = GET_VALUE(12); t1 = GET_VALUE(13);
val |= (t0 < t1) << 6;
t0 = GET_VALUE(14); t1 = GET_VALUE(15);
val |= (t0 < t1) << 7;
desc[i] = (uchar)val;
}
}
else if( WTA_K == 3 )
{
for (int i = 0; i < dsize; ++i, pattern += 12)
{
int t0, t1, t2, val;
t0 = GET_VALUE(0); t1 = GET_VALUE(1); t2 = GET_VALUE(2);
val = t2 > t1 ? (t2 > t0 ? 2 : 0) : (t1 > t0);
t0 = GET_VALUE(3); t1 = GET_VALUE(4); t2 = GET_VALUE(5);
val |= (t2 > t1 ? (t2 > t0 ? 2 : 0) : (t1 > t0)) << 2;
t0 = GET_VALUE(6); t1 = GET_VALUE(7); t2 = GET_VALUE(8);
val |= (t2 > t1 ? (t2 > t0 ? 2 : 0) : (t1 > t0)) << 4;
t0 = GET_VALUE(9); t1 = GET_VALUE(10); t2 = GET_VALUE(11);
val |= (t2 > t1 ? (t2 > t0 ? 2 : 0) : (t1 > t0)) << 6;
desc[i] = (uchar)val;
}
}
else if( WTA_K == 4 )
{
for (int i = 0; i < dsize; ++i, pattern += 16)
{
int t0, t1, t2, t3, u, v, k, val;
t0 = GET_VALUE(0); t1 = GET_VALUE(1);
t2 = GET_VALUE(2); t3 = GET_VALUE(3);
u = 0, v = 2;
if( t1 > t0 ) t0 = t1, u = 1;
if( t3 > t2 ) t2 = t3, v = 3;
k = t0 > t2 ? u : v;
val = k;
t0 = GET_VALUE(4); t1 = GET_VALUE(5);
t2 = GET_VALUE(6); t3 = GET_VALUE(7);
u = 0, v = 2;
if( t1 > t0 ) t0 = t1, u = 1;
if( t3 > t2 ) t2 = t3, v = 3;
k = t0 > t2 ? u : v;
val |= k << 2;
t0 = GET_VALUE(8); t1 = GET_VALUE(9);
t2 = GET_VALUE(10); t3 = GET_VALUE(11);
u = 0, v = 2;
if( t1 > t0 ) t0 = t1, u = 1;
if( t3 > t2 ) t2 = t3, v = 3;
k = t0 > t2 ? u : v;
val |= k << 4;
t0 = GET_VALUE(12); t1 = GET_VALUE(13);
t2 = GET_VALUE(14); t3 = GET_VALUE(15);
u = 0, v = 2;
if( t1 > t0 ) t0 = t1, u = 1;
if( t3 > t2 ) t2 = t3, v = 3;
k = t0 > t2 ? u : v;
val |= k << 6;
desc[i] = (uchar)val;
}
}
else
CV_Error( CV_StsBadSize, "Wrong WTA_K. It can be only 2, 3 or 4." );
#undef GET_VALUE
}
static void initializeOrbPattern( const Point* pattern0, vector<Point>& pattern, int ntuples, int tupleSize, int poolSize )
{
RNG rng(0x12345678);
int i, k, k1;
pattern.resize(ntuples*tupleSize);
for( i = 0; i < ntuples; i++ )
{
for( k = 0; k < tupleSize; k++ )
{
for(;;)
{
int idx = rng.uniform(0, poolSize);
Point pt = pattern0[idx];
for( k1 = 0; k1 < k; k1++ )
if( pattern[tupleSize*i + k1] == pt )
break;
if( k1 == k )
{
pattern[tupleSize*i + k] = pt;
break;
}
}
}
}
}
static int bit_pattern_31_[256*4] =
{
8,-3, 9,5/*mean (0), correlation (0)*/,
4,2, 7,-12/*mean (1.12461e-05), correlation (0.0437584)*/,
-11,9, -8,2/*mean (3.37382e-05), correlation (0.0617409)*/,
7,-12, 12,-13/*mean (5.62303e-05), correlation (0.0636977)*/,
2,-13, 2,12/*mean (0.000134953), correlation (0.085099)*/,
1,-7, 1,6/*mean (0.000528565), correlation (0.0857175)*/,
-2,-10, -2,-4/*mean (0.0188821), correlation (0.0985774)*/,
-13,-13, -11,-8/*mean (0.0363135), correlation (0.0899616)*/,
-13,-3, -12,-9/*mean (0.121806), correlation (0.099849)*/,
10,4, 11,9/*mean (0.122065), correlation (0.093285)*/,
-13,-8, -8,-9/*mean (0.162787), correlation (0.0942748)*/,
-11,7, -9,12/*mean (0.21561), correlation (0.0974438)*/,
7,7, 12,6/*mean (0.160583), correlation (0.130064)*/,
-4,-5, -3,0/*mean (0.228171), correlation (0.132998)*/,
-13,2, -12,-3/*mean (0.00997526), correlation (0.145926)*/,
-9,0, -7,5/*mean (0.198234), correlation (0.143636)*/,
12,-6, 12,-1/*mean (0.0676226), correlation (0.16689)*/,
-3,6, -2,12/*mean (0.166847), correlation (0.171682)*/,
-6,-13, -4,-8/*mean (0.101215), correlation (0.179716)*/,
11,-13, 12,-8/*mean (0.200641), correlation (0.192279)*/,
4,7, 5,1/*mean (0.205106), correlation (0.186848)*/,
5,-3, 10,-3/*mean (0.234908), correlation (0.192319)*/,
3,-7, 6,12/*mean (0.0709964), correlation (0.210872)*/,
-8,-7, -6,-2/*mean (0.0939834), correlation (0.212589)*/,
-2,11, -1,-10/*mean (0.127778), correlation (0.20866)*/,
-13,12, -8,10/*mean (0.14783), correlation (0.206356)*/,
-7,3, -5,-3/*mean (0.182141), correlation (0.198942)*/,
-4,2, -3,7/*mean (0.188237), correlation (0.21384)*/,
-10,-12, -6,11/*mean (0.14865), correlation (0.23571)*/,
5,-12, 6,-7/*mean (0.222312), correlation (0.23324)*/,
5,-6, 7,-1/*mean (0.229082), correlation (0.23389)*/,
1,0, 4,-5/*mean (0.241577), correlation (0.215286)*/,
9,11, 11,-13/*mean (0.00338507), correlation (0.251373)*/,
4,7, 4,12/*mean (0.131005), correlation (0.257622)*/,
2,-1, 4,4/*mean (0.152755), correlation (0.255205)*/,
-4,-12, -2,7/*mean (0.182771), correlation (0.244867)*/,
-8,-5, -7,-10/*mean (0.186898), correlation (0.23901)*/,
4,11, 9,12/*mean (0.226226), correlation (0.258255)*/,
0,-8, 1,-13/*mean (0.0897886), correlation (0.274827)*/,
-13,-2, -8,2/*mean (0.148774), correlation (0.28065)*/,
-3,-2, -2,3/*mean (0.153048), correlation (0.283063)*/,
-6,9, -4,-9/*mean (0.169523), correlation (0.278248)*/,
8,12, 10,7/*mean (0.225337), correlation (0.282851)*/,
0,9, 1,3/*mean (0.226687), correlation (0.278734)*/,
7,-5, 11,-10/*mean (0.00693882), correlation (0.305161)*/,
-13,-6, -11,0/*mean (0.0227283), correlation (0.300181)*/,
10,7, 12,1/*mean (0.125517), correlation (0.31089)*/,
-6,-3, -6,12/*mean (0.131748), correlation (0.312779)*/,
10,-9, 12,-4/*mean (0.144827), correlation (0.292797)*/,
-13,8, -8,-12/*mean (0.149202), correlation (0.308918)*/,
-13,0, -8,-4/*mean (0.160909), correlation (0.310013)*/,
3,3, 7,8/*mean (0.177755), correlation (0.309394)*/,
5,7, 10,-7/*mean (0.212337), correlation (0.310315)*/,
-1,7, 1,-12/*mean (0.214429), correlation (0.311933)*/,
3,-10, 5,6/*mean (0.235807), correlation (0.313104)*/,
2,-4, 3,-10/*mean (0.00494827), correlation (0.344948)*/,
-13,0, -13,5/*mean (0.0549145), correlation (0.344675)*/,
-13,-7, -12,12/*mean (0.103385), correlation (0.342715)*/,
-13,3, -11,8/*mean (0.134222), correlation (0.322922)*/,
-7,12, -4,7/*mean (0.153284), correlation (0.337061)*/,
6,-10, 12,8/*mean (0.154881), correlation (0.329257)*/,
-9,-1, -7,-6/*mean (0.200967), correlation (0.33312)*/,
-2,-5, 0,12/*mean (0.201518), correlation (0.340635)*/,
-12,5, -7,5/*mean (0.207805), correlation (0.335631)*/,
3,-10, 8,-13/*mean (0.224438), correlation (0.34504)*/,
-7,-7, -4,5/*mean (0.239361), correlation (0.338053)*/,
-3,-2, -1,-7/*mean (0.240744), correlation (0.344322)*/,
2,9, 5,-11/*mean (0.242949), correlation (0.34145)*/,
-11,-13, -5,-13/*mean (0.244028), correlation (0.336861)*/,
-1,6, 0,-1/*mean (0.247571), correlation (0.343684)*/,
5,-3, 5,2/*mean (0.000697256), correlation (0.357265)*/,
-4,-13, -4,12/*mean (0.00213675), correlation (0.373827)*/,
-9,-6, -9,6/*mean (0.0126856), correlation (0.373938)*/,
-12,-10, -8,-4/*mean (0.0152497), correlation (0.364237)*/,
10,2, 12,-3/*mean (0.0299933), correlation (0.345292)*/,
7,12, 12,12/*mean (0.0307242), correlation (0.366299)*/,
-7,-13, -6,5/*mean (0.0534975), correlation (0.368357)*/,
-4,9, -3,4/*mean (0.099865), correlation (0.372276)*/,
7,-1, 12,2/*mean (0.117083), correlation (0.364529)*/,
-7,6, -5,1/*mean (0.126125), correlation (0.369606)*/,
-13,11, -12,5/*mean (0.130364), correlation (0.358502)*/,
-3,7, -2,-6/*mean (0.131691), correlation (0.375531)*/,
7,-8, 12,-7/*mean (0.160166), correlation (0.379508)*/,
-13,-7, -11,-12/*mean (0.167848), correlation (0.353343)*/,
1,-3, 12,12/*mean (0.183378), correlation (0.371916)*/,
2,-6, 3,0/*mean (0.228711), correlation (0.371761)*/,
-4,3, -2,-13/*mean (0.247211), correlation (0.364063)*/,
-1,-13, 1,9/*mean (0.249325), correlation (0.378139)*/,
7,1, 8,-6/*mean (0.000652272), correlation (0.411682)*/,
1,-1, 3,12/*mean (0.00248538), correlation (0.392988)*/,
9,1, 12,6/*mean (0.0206815), correlation (0.386106)*/,
-1,-9, -1,3/*mean (0.0364485), correlation (0.410752)*/,
-13,-13, -10,5/*mean (0.0376068), correlation (0.398374)*/,
7,7, 10,12/*mean (0.0424202), correlation (0.405663)*/,
12,-5, 12,9/*mean (0.0942645), correlation (0.410422)*/,
6,3, 7,11/*mean (0.1074), correlation (0.413224)*/,
5,-13, 6,10/*mean (0.109256), correlation (0.408646)*/,
2,-12, 2,3/*mean (0.131691), correlation (0.416076)*/,
3,8, 4,-6/*mean (0.165081), correlation (0.417569)*/,
2,6, 12,-13/*mean (0.171874), correlation (0.408471)*/,
9,-12, 10,3/*mean (0.175146), correlation (0.41296)*/,
-8,4, -7,9/*mean (0.183682), correlation (0.402956)*/,
-11,12, -4,-6/*mean (0.184672), correlation (0.416125)*/,
1,12, 2,-8/*mean (0.191487), correlation (0.386696)*/,
6,-9, 7,-4/*mean (0.192668), correlation (0.394771)*/,
2,3, 3,-2/*mean (0.200157), correlation (0.408303)*/,
6,3, 11,0/*mean (0.204588), correlation (0.411762)*/,
3,-3, 8,-8/*mean (0.205904), correlation (0.416294)*/,
7,8, 9,3/*mean (0.213237), correlation (0.409306)*/,
-11,-5, -6,-4/*mean (0.243444), correlation (0.395069)*/,
-10,11, -5,10/*mean (0.247672), correlation (0.413392)*/,
-5,-8, -3,12/*mean (0.24774), correlation (0.411416)*/,
-10,5, -9,0/*mean (0.00213675), correlation (0.454003)*/,
8,-1, 12,-6/*mean (0.0293635), correlation (0.455368)*/,
4,-6, 6,-11/*mean (0.0404971), correlation (0.457393)*/,
-10,12, -8,7/*mean (0.0481107), correlation (0.448364)*/,
4,-2, 6,7/*mean (0.050641), correlation (0.455019)*/,
-2,0, -2,12/*mean (0.0525978), correlation (0.44338)*/,
-5,-8, -5,2/*mean (0.0629667), correlation (0.457096)*/,
7,-6, 10,12/*mean (0.0653846), correlation (0.445623)*/,
-9,-13, -8,-8/*mean (0.0858749), correlation (0.449789)*/,
-5,-13, -5,-2/*mean (0.122402), correlation (0.450201)*/,
8,-8, 9,-13/*mean (0.125416), correlation (0.453224)*/,
-9,-11, -9,0/*mean (0.130128), correlation (0.458724)*/,
1,-8, 1,-2/*mean (0.132467), correlation (0.440133)*/,
7,-4, 9,1/*mean (0.132692), correlation (0.454)*/,
-2,1, -1,-4/*mean (0.135695), correlation (0.455739)*/,
11,-6, 12,-11/*mean (0.142904), correlation (0.446114)*/,
-12,-9, -6,4/*mean (0.146165), correlation (0.451473)*/,
3,7, 7,12/*mean (0.147627), correlation (0.456643)*/,
5,5, 10,8/*mean (0.152901), correlation (0.455036)*/,
0,-4, 2,8/*mean (0.167083), correlation (0.459315)*/,
-9,12, -5,-13/*mean (0.173234), correlation (0.454706)*/,
0,7, 2,12/*mean (0.18312), correlation (0.433855)*/,
-1,2, 1,7/*mean (0.185504), correlation (0.443838)*/,
5,11, 7,-9/*mean (0.185706), correlation (0.451123)*/,
3,5, 6,-8/*mean (0.188968), correlation (0.455808)*/,
-13,-4, -8,9/*mean (0.191667), correlation (0.459128)*/,
-5,9, -3,-3/*mean (0.193196), correlation (0.458364)*/,
-4,-7, -3,-12/*mean (0.196536), correlation (0.455782)*/,
6,5, 8,0/*mean (0.1972), correlation (0.450481)*/,
-7,6, -6,12/*mean (0.199438), correlation (0.458156)*/,
-13,6, -5,-2/*mean (0.211224), correlation (0.449548)*/,
1,-10, 3,10/*mean (0.211718), correlation (0.440606)*/,
4,1, 8,-4/*mean (0.213034), correlation (0.443177)*/,
-2,-2, 2,-13/*mean (0.234334), correlation (0.455304)*/,
2,-12, 12,12/*mean (0.235684), correlation (0.443436)*/,
-2,-13, 0,-6/*mean (0.237674), correlation (0.452525)*/,
4,1, 9,3/*mean (0.23962), correlation (0.444824)*/,
-6,-10, -3,-5/*mean (0.248459), correlation (0.439621)*/,
-3,-13, -1,1/*mean (0.249505), correlation (0.456666)*/,
7,5, 12,-11/*mean (0.00119208), correlation (0.495466)*/,
4,-2, 5,-7/*mean (0.00372245), correlation (0.484214)*/,
-13,9, -9,-5/*mean (0.00741116), correlation (0.499854)*/,
7,1, 8,6/*mean (0.0208952), correlation (0.499773)*/,
7,-8, 7,6/*mean (0.0220085), correlation (0.501609)*/,
-7,-4, -7,1/*mean (0.0233806), correlation (0.496568)*/,
-8,11, -7,-8/*mean (0.0236505), correlation (0.489719)*/,
-13,6, -12,-8/*mean (0.0268781), correlation (0.503487)*/,
2,4, 3,9/*mean (0.0323324), correlation (0.501938)*/,
10,-5, 12,3/*mean (0.0399235), correlation (0.494029)*/,
-6,-5, -6,7/*mean (0.0420153), correlation (0.486579)*/,
8,-3, 9,-8/*mean (0.0548021), correlation (0.484237)*/,
2,-12, 2,8/*mean (0.0616622), correlation (0.496642)*/,
-11,-2, -10,3/*mean (0.0627755), correlation (0.498563)*/,
-12,-13, -7,-9/*mean (0.0829622), correlation (0.495491)*/,
-11,0, -10,-5/*mean (0.0843342), correlation (0.487146)*/,
5,-3, 11,8/*mean (0.0929937), correlation (0.502315)*/,
-2,-13, -1,12/*mean (0.113327), correlation (0.48941)*/,
-1,-8, 0,9/*mean (0.132119), correlation (0.467268)*/,
-13,-11, -12,-5/*mean (0.136269), correlation (0.498771)*/,
-10,-2, -10,11/*mean (0.142173), correlation (0.498714)*/,
-3,9, -2,-13/*mean (0.144141), correlation (0.491973)*/,
2,-3, 3,2/*mean (0.14892), correlation (0.500782)*/,
-9,-13, -4,0/*mean (0.150371), correlation (0.498211)*/,
-4,6, -3,-10/*mean (0.152159), correlation (0.495547)*/,
-4,12, -2,-7/*mean (0.156152), correlation (0.496925)*/,
-6,-11, -4,9/*mean (0.15749), correlation (0.499222)*/,
6,-3, 6,11/*mean (0.159211), correlation (0.503821)*/,
-13,11, -5,5/*mean (0.162427), correlation (0.501907)*/,
11,11, 12,6/*mean (0.16652), correlation (0.497632)*/,
7,-5, 12,-2/*mean (0.169141), correlation (0.484474)*/,
-1,12, 0,7/*mean (0.169456), correlation (0.495339)*/,
-4,-8, -3,-2/*mean (0.171457), correlation (0.487251)*/,
-7,1, -6,7/*mean (0.175), correlation (0.500024)*/,
-13,-12, -8,-13/*mean (0.175866), correlation (0.497523)*/,
-7,-2, -6,-8/*mean (0.178273), correlation (0.501854)*/,
-8,5, -6,-9/*mean (0.181107), correlation (0.494888)*/,
-5,-1, -4,5/*mean (0.190227), correlation (0.482557)*/,
-13,7, -8,10/*mean (0.196739), correlation (0.496503)*/,
1,5, 5,-13/*mean (0.19973), correlation (0.499759)*/,
1,0, 10,-13/*mean (0.204465), correlation (0.49873)*/,
9,12, 10,-1/*mean (0.209334), correlation (0.49063)*/,
5,-8, 10,-9/*mean (0.211134), correlation (0.503011)*/,
-1,11, 1,-13/*mean (0.212), correlation (0.499414)*/,
-9,-3, -6,2/*mean (0.212168), correlation (0.480739)*/,
-1,-10, 1,12/*mean (0.212731), correlation (0.502523)*/,
-13,1, -8,-10/*mean (0.21327), correlation (0.489786)*/,
8,-11, 10,-6/*mean (0.214159), correlation (0.488246)*/,
2,-13, 3,-6/*mean (0.216993), correlation (0.50287)*/,
7,-13, 12,-9/*mean (0.223639), correlation (0.470502)*/,
-10,-10, -5,-7/*mean (0.224089), correlation (0.500852)*/,
-10,-8, -8,-13/*mean (0.228666), correlation (0.502629)*/,
4,-6, 8,5/*mean (0.22906), correlation (0.498305)*/,
3,12, 8,-13/*mean (0.233378), correlation (0.503825)*/,
-4,2, -3,-3/*mean (0.234323), correlation (0.476692)*/,
5,-13, 10,-12/*mean (0.236392), correlation (0.475462)*/,
4,-13, 5,-1/*mean (0.236842), correlation (0.504132)*/,
-9,9, -4,3/*mean (0.236977), correlation (0.497739)*/,
0,3, 3,-9/*mean (0.24314), correlation (0.499398)*/,
-12,1, -6,1/*mean (0.243297), correlation (0.489447)*/,
3,2, 4,-8/*mean (0.00155196), correlation (0.553496)*/,
-10,-10, -10,9/*mean (0.00239541), correlation (0.54297)*/,
8,-13, 12,12/*mean (0.0034413), correlation (0.544361)*/,
-8,-12, -6,-5/*mean (0.003565), correlation (0.551225)*/,
2,2, 3,7/*mean (0.00835583), correlation (0.55285)*/,
10,6, 11,-8/*mean (0.00885065), correlation (0.540913)*/,
6,8, 8,-12/*mean (0.0101552), correlation (0.551085)*/,
-7,10, -6,5/*mean (0.0102227), correlation (0.533635)*/,
-3,-9, -3,9/*mean (0.0110211), correlation (0.543121)*/,
-1,-13, -1,5/*mean (0.0113473), correlation (0.550173)*/,
-3,-7, -3,4/*mean (0.0140913), correlation (0.554774)*/,
-8,-2, -8,3/*mean (0.017049), correlation (0.55461)*/,
4,2, 12,12/*mean (0.01778), correlation (0.546921)*/,
2,-5, 3,11/*mean (0.0224022), correlation (0.549667)*/,
6,-9, 11,-13/*mean (0.029161), correlation (0.546295)*/,
3,-1, 7,12/*mean (0.0303081), correlation (0.548599)*/,
11,-1, 12,4/*mean (0.0355151), correlation (0.523943)*/,
-3,0, -3,6/*mean (0.0417904), correlation (0.543395)*/,
4,-11, 4,12/*mean (0.0487292), correlation (0.542818)*/,
2,-4, 2,1/*mean (0.0575124), correlation (0.554888)*/,
-10,-6, -8,1/*mean (0.0594242), correlation (0.544026)*/,
-13,7, -11,1/*mean (0.0597391), correlation (0.550524)*/,
-13,12, -11,-13/*mean (0.0608974), correlation (0.55383)*/,
6,0, 11,-13/*mean (0.065126), correlation (0.552006)*/,
0,-1, 1,4/*mean (0.074224), correlation (0.546372)*/,
-13,3, -9,-2/*mean (0.0808592), correlation (0.554875)*/,
-9,8, -6,-3/*mean (0.0883378), correlation (0.551178)*/,
-13,-6, -8,-2/*mean (0.0901035), correlation (0.548446)*/,
5,-9, 8,10/*mean (0.0949843), correlation (0.554694)*/,
2,7, 3,-9/*mean (0.0994152), correlation (0.550979)*/,
-1,-6, -1,-1/*mean (0.10045), correlation (0.552714)*/,
9,5, 11,-2/*mean (0.100686), correlation (0.552594)*/,
11,-3, 12,-8/*mean (0.101091), correlation (0.532394)*/,
3,0, 3,5/*mean (0.101147), correlation (0.525576)*/,
-1,4, 0,10/*mean (0.105263), correlation (0.531498)*/,
3,-6, 4,5/*mean (0.110785), correlation (0.540491)*/,
-13,0, -10,5/*mean (0.112798), correlation (0.536582)*/,
5,8, 12,11/*mean (0.114181), correlation (0.555793)*/,
8,9, 9,-6/*mean (0.117431), correlation (0.553763)*/,
7,-4, 8,-12/*mean (0.118522), correlation (0.553452)*/,
-10,4, -10,9/*mean (0.12094), correlation (0.554785)*/,
7,3, 12,4/*mean (0.122582), correlation (0.555825)*/,
9,-7, 10,-2/*mean (0.124978), correlation (0.549846)*/,
7,0, 12,-2/*mean (0.127002), correlation (0.537452)*/,
-1,-6, 0,-11/*mean (0.127148), correlation (0.547401)*/
};
static void makeRandomPattern(int patchSize, Point* pattern, int npoints)
{
RNG rng(0x34985739); // we always start with a fixed seed,
// to make patterns the same on each run
for( int i = 0; i < npoints; i++ )
{
pattern[i].x = rng.uniform(-patchSize/2, patchSize/2+1);
pattern[i].y = rng.uniform(-patchSize/2, patchSize/2+1);
}
}
static inline float getScale(int level, int firstLevel, double scaleFactor)
{
return (float)std::pow(scaleFactor, (double)(level - firstLevel));
}
/** Constructor
* @param detector_params parameters to use
*/
ORB::ORB(int _nfeatures, float _scaleFactor, int _nlevels, int _edgeThreshold,
int _firstLevel, int _WTA_K, int _scoreType, int _patchSize) :
nfeatures(_nfeatures), scaleFactor(_scaleFactor), nlevels(_nlevels),
edgeThreshold(_edgeThreshold), firstLevel(_firstLevel), WTA_K(_WTA_K),
scoreType(_scoreType), patchSize(_patchSize)
{}
int ORB::descriptorSize() const
{
return kBytes;
}
int ORB::descriptorType() const
{
return CV_8U;
}
/** Compute the ORB features and descriptors on an image
* @param img the image to compute the features and descriptors on
* @param mask the mask to apply
* @param keypoints the resulting keypoints
*/
void ORB::operator()(InputArray image, InputArray mask, vector<KeyPoint>& keypoints) const
{
(*this)(image, mask, keypoints, noArray(), false);
}
/** Compute the ORB keypoint orientations
* @param image the image to compute the features and descriptors on
* @param integral_image the integral image of the iamge (can be empty, but the computation will be slower)
* @param scale the scale at which we compute the orientation
* @param keypoints the resulting keypoints
*/
static void computeOrientation(const Mat& image, vector<KeyPoint>& keypoints,
int halfPatchSize, const vector<int>& umax)
{
// Process each keypoint
for (vector<KeyPoint>::iterator keypoint = keypoints.begin(),
keypointEnd = keypoints.end(); keypoint != keypointEnd; ++keypoint)
{
keypoint->angle = IC_Angle(image, halfPatchSize, keypoint->pt, umax);
}
}
/** Compute the ORB keypoints on an image
* @param image_pyramid the image pyramid to compute the features and descriptors on
* @param mask_pyramid the masks to apply at every level
* @param keypoints the resulting keypoints, clustered per level
*/
static void computeKeyPoints(const vector<Mat>& imagePyramid,
const vector<Mat>& maskPyramid,
vector<vector<KeyPoint> >& allKeypoints,
int nfeatures, int firstLevel, double scaleFactor,
int edgeThreshold, int patchSize, int scoreType )
{
int nlevels = (int)imagePyramid.size();
vector<int> nfeaturesPerLevel(nlevels);
// fill the extractors and descriptors for the corresponding scales
float factor = (float)(1.0 / scaleFactor);
float ndesiredFeaturesPerScale = nfeatures*(1 - factor)/(1 - (float)pow((double)factor, (double)nlevels));
int sumFeatures = 0;
for( int level = 0; level < nlevels-1; level++ )
{
nfeaturesPerLevel[level] = cvRound(ndesiredFeaturesPerScale);
sumFeatures += nfeaturesPerLevel[level];
ndesiredFeaturesPerScale *= factor;
}
nfeaturesPerLevel[nlevels-1] = std::max(nfeatures - sumFeatures, 0);
// Make sure we forget about what is too close to the boundary
//edge_threshold_ = std::max(edge_threshold_, patch_size_/2 + kKernelWidth / 2 + 2);
// pre-compute the end of a row in a circular patch
int halfPatchSize = patchSize / 2;
vector<int> umax(halfPatchSize + 2);
int v, v0, vmax = cvFloor(halfPatchSize * sqrt(2.f) / 2 + 1);
int vmin = cvCeil(halfPatchSize * sqrt(2.f) / 2);
for (v = 0; v <= vmax; ++v)
umax[v] = cvRound(sqrt((double)halfPatchSize * halfPatchSize - v * v));
// Make sure we are symmetric
for (v = halfPatchSize, v0 = 0; v >= vmin; --v)
{
while (umax[v0] == umax[v0 + 1])
++v0;
umax[v] = v0;
++v0;
}
allKeypoints.resize(nlevels);
for (int level = 0; level < nlevels; ++level)
{
int featuresNum = nfeaturesPerLevel[level];
allKeypoints[level].reserve(featuresNum*2);
vector<KeyPoint> & keypoints = allKeypoints[level];
// Detect FAST features, 20 is a good threshold
FastFeatureDetector fd(20, true);
fd.detect(imagePyramid[level], keypoints, maskPyramid[level]);
// Remove keypoints very close to the border
KeyPointsFilter::runByImageBorder(keypoints, imagePyramid[level].size(), edgeThreshold);
if( scoreType == ORB::HARRIS_SCORE )
{
// Keep more points than necessary as FAST does not give amazing corners
KeyPointsFilter::retainBest(keypoints, 2 * featuresNum);
// Compute the Harris cornerness (better scoring than FAST)
HarrisResponses(imagePyramid[level], keypoints, 7, HARRIS_K);
}
//cull to the final desired level, using the new Harris scores or the original FAST scores.
KeyPointsFilter::retainBest(keypoints, featuresNum);
float sf = getScale(level, firstLevel, scaleFactor);
// Set the level of the coordinates
for (vector<KeyPoint>::iterator keypoint = keypoints.begin(),
keypointEnd = keypoints.end(); keypoint != keypointEnd; ++keypoint)
{
keypoint->octave = level;
keypoint->size = patchSize*sf;
}
computeOrientation(imagePyramid[level], keypoints, halfPatchSize, umax);
}
}
/** Compute the ORB decriptors
* @param image the image to compute the features and descriptors on
* @param integral_image the integral image of the image (can be empty, but the computation will be slower)
* @param level the scale at which we compute the orientation
* @param keypoints the keypoints to use
* @param descriptors the resulting descriptors
*/
static void computeDescriptors(const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors,
const vector<Point>& pattern, int dsize, int WTA_K)
{
//convert to grayscale if more than one color
CV_Assert(image.type() == CV_8UC1);
//create the descriptor mat, keypoints.size() rows, BYTES cols
descriptors = Mat::zeros((int)keypoints.size(), dsize, CV_8UC1);
for (size_t i = 0; i < keypoints.size(); i++)
computeOrbDescriptor(keypoints[i], image, &pattern[0], descriptors.ptr((int)i), dsize, WTA_K);
}
/** Compute the ORB features and descriptors on an image
* @param img the image to compute the features and descriptors on
* @param mask the mask to apply
* @param keypoints the resulting keypoints
* @param descriptors the resulting descriptors
* @param do_keypoints if true, the keypoints are computed, otherwise used as an input
* @param do_descriptors if true, also computes the descriptors
*/
void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _keypoints,
OutputArray _descriptors, bool useProvidedKeypoints) const
{
CV_Assert(patchSize >= 2);
bool do_keypoints = !useProvidedKeypoints;
bool do_descriptors = _descriptors.needed();
if( (!do_keypoints && !do_descriptors) || _image.empty() )
return;
//ROI handling
const int HARRIS_BLOCK_SIZE = 9;
int halfPatchSize = patchSize / 2;
int border = std::max(edgeThreshold, std::max(halfPatchSize, HARRIS_BLOCK_SIZE/2))+1;
Mat image = _image.getMat(), mask = _mask.getMat();
if( image.type() != CV_8UC1 )
cvtColor(_image, image, CV_BGR2GRAY);
int levelsNum = this->nlevels;
if( !do_keypoints )
{
// if we have pre-computed keypoints, they may use more levels than it is set in parameters
// !!!TODO!!! implement more correct method, independent from the used keypoint detector.
// Namely, the detector should provide correct size of each keypoint. Based on the keypoint size
// and the algorithm used (i.e. BRIEF, running on 31x31 patches) we should compute the approximate
// scale-factor that we need to apply. Then we should cluster all the computed scale-factors and
// for each cluster compute the corresponding image.
//
// In short, ultimately the descriptor should
// ignore octave parameter and deal only with the keypoint size.
levelsNum = 0;
for( size_t i = 0; i < _keypoints.size(); i++ )
levelsNum = std::max(levelsNum, std::max(_keypoints[i].octave, 0));
levelsNum++;
}
// Pre-compute the scale pyramids
vector<Mat> imagePyramid(levelsNum), maskPyramid(levelsNum);
for (int level = 0; level < levelsNum; ++level)
{
float scale = 1/getScale(level, firstLevel, scaleFactor);
Size sz(cvRound(image.cols*scale), cvRound(image.rows*scale));
Size wholeSize(sz.width + border*2, sz.height + border*2);
Mat temp(wholeSize, image.type()), masktemp;
imagePyramid[level] = temp(Rect(border, border, sz.width, sz.height));
if( !mask.empty() )
{
masktemp = Mat(wholeSize, mask.type());
maskPyramid[level] = masktemp(Rect(border, border, sz.width, sz.height));
}
// Compute the resized image
if( level != firstLevel )
{
if( level < firstLevel )
{
resize(image, imagePyramid[level], sz, 0, 0, INTER_LINEAR);
if (!mask.empty())
resize(mask, maskPyramid[level], sz, 0, 0, INTER_LINEAR);
}
else
{
resize(imagePyramid[level-1], imagePyramid[level], sz, 0, 0, INTER_LINEAR);
if (!mask.empty())
{
resize(maskPyramid[level-1], maskPyramid[level], sz, 0, 0, INTER_LINEAR);
threshold(maskPyramid[level], maskPyramid[level], 254, 0, THRESH_TOZERO);
}
}
copyMakeBorder(imagePyramid[level], temp, border, border, border, border,
BORDER_REFLECT_101+BORDER_ISOLATED);
if (!mask.empty())
copyMakeBorder(maskPyramid[level], masktemp, border, border, border, border,
BORDER_CONSTANT+BORDER_ISOLATED);
}
else
{
copyMakeBorder(image, temp, border, border, border, border,
BORDER_REFLECT_101);
if( !mask.empty() )
copyMakeBorder(mask, masktemp, border, border, border, border,
BORDER_CONSTANT+BORDER_ISOLATED);
}
}
// Pre-compute the keypoints (we keep the best over all scales, so this has to be done beforehand
vector < vector<KeyPoint> > allKeypoints;
if( do_keypoints )
{
// Get keypoints, those will be far enough from the border that no check will be required for the descriptor
computeKeyPoints(imagePyramid, maskPyramid, allKeypoints,
nfeatures, firstLevel, scaleFactor,
edgeThreshold, patchSize, scoreType);
// make sure we have the right number of keypoints keypoints
/*vector<KeyPoint> temp;
for (int level = 0; level < n_levels; ++level)
{
vector<KeyPoint>& keypoints = all_keypoints[level];
temp.insert(temp.end(), keypoints.begin(), keypoints.end());
keypoints.clear();
}
KeyPoint::retainBest(temp, n_features_);
for (vector<KeyPoint>::iterator keypoint = temp.begin(),
keypoint_end = temp.end(); keypoint != keypoint_end; ++keypoint)
all_keypoints[keypoint->octave].push_back(*keypoint);*/
}
else
{
// Remove keypoints very close to the border
KeyPointsFilter::runByImageBorder(_keypoints, image.size(), edgeThreshold);
// Cluster the input keypoints depending on the level they were computed at
allKeypoints.resize(levelsNum);
for (vector<KeyPoint>::iterator keypoint = _keypoints.begin(),
keypointEnd = _keypoints.end(); keypoint != keypointEnd; ++keypoint)
allKeypoints[keypoint->octave].push_back(*keypoint);
// Make sure we rescale the coordinates
for (int level = 0; level < levelsNum; ++level)
{
if (level == firstLevel)
continue;
vector<KeyPoint> & keypoints = allKeypoints[level];
float scale = 1/getScale(level, firstLevel, scaleFactor);
for (vector<KeyPoint>::iterator keypoint = keypoints.begin(),
keypointEnd = keypoints.end(); keypoint != keypointEnd; ++keypoint)
keypoint->pt *= scale;
}
}
Mat descriptors;
vector<Point> pattern;
if( do_descriptors )
{
int nkeypoints = 0;
for (int level = 0; level < levelsNum; ++level)
nkeypoints += (int)allKeypoints[level].size();
if( nkeypoints == 0 )
_descriptors.release();
else
{
_descriptors.create(nkeypoints, descriptorSize(), CV_8U);
descriptors = _descriptors.getMat();
}
const int npoints = 512;
Point patternbuf[npoints];
const Point* pattern0 = (const Point*)bit_pattern_31_;
if( patchSize != 31 )
{
pattern0 = patternbuf;
makeRandomPattern(patchSize, patternbuf, npoints);
}
CV_Assert( WTA_K == 2 || WTA_K == 3 || WTA_K == 4 );
if( WTA_K == 2 )
std::copy(pattern0, pattern0 + npoints, std::back_inserter(pattern));
else
{
int ntuples = descriptorSize()*4;
initializeOrbPattern(pattern0, pattern, ntuples, WTA_K, npoints);
}
}
_keypoints.clear();
int offset = 0;
for (int level = 0; level < levelsNum; ++level)
{
// Get the features and compute their orientation
vector<KeyPoint>& keypoints = allKeypoints[level];
int nkeypoints = (int)keypoints.size();
// Compute the descriptors
if (do_descriptors)
{
Mat desc;
if (!descriptors.empty())
{
desc = descriptors.rowRange(offset, offset + nkeypoints);
}
offset += nkeypoints;
// preprocess the resized image
Mat& workingMat = imagePyramid[level];
//boxFilter(working_mat, working_mat, working_mat.depth(), Size(5,5), Point(-1,-1), true, BORDER_REFLECT_101);
GaussianBlur(workingMat, workingMat, Size(7, 7), 2, 2, BORDER_REFLECT_101);
computeDescriptors(workingMat, keypoints, desc, pattern, descriptorSize(), WTA_K);
}
// Copy to the output data
if (level != firstLevel)
{
float scale = getScale(level, firstLevel, scaleFactor);
for (vector<KeyPoint>::iterator keypoint = keypoints.begin(),
keypointEnd = keypoints.end(); keypoint != keypointEnd; ++keypoint)
keypoint->pt *= scale;
}
// And add the keypoints to the output
_keypoints.insert(_keypoints.end(), keypoints.begin(), keypoints.end());
}
}
void ORB::detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask) const
{
(*this)(image, mask, keypoints, noArray(), false);
}
void ORB::computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors) const
{
(*this)(image, Mat(), keypoints, descriptors, true);
}
}
| [
"simon@makotechnology.com"
] | simon@makotechnology.com |
76d65dc2b3c889863a7ca22315059e958ef48b03 | 8f161087c16ac922952f84efb20755b2b38ff799 | /013. 이항계수/code_1_6.cpp | e9e04ebcc09959d0b3262b5f6eca9eebe7b2de00 | [
"MIT"
] | permissive | daejinseok/atsp | 11c1519356b76841c33cfa60d8192c88f7fc1279 | 3c29e6a8deb4c61bf58d9c36ba5481bc632370da | refs/heads/master | 2021-01-01T17:15:09.328954 | 2018-03-31T00:10:23 | 2018-03-31T00:10:23 | 98,035,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 478 | cpp | #include <cstdio>
#include <cstring>
#define M 200
static long long memo[M][M];
long long choose(int n, int r) {
if ( memo[n][r] != -1 ){
return memo[n][r];
}
if( (n == r) || (r == 0) ) {
return memo[n][r] = 1;
}
return memo[n][r] = choose( n-1, r-1 ) + choose( n-1, r );
}
int main(void){
int n, r;
memset(memo, -1, sizeof memo );
printf("input n r:");
scanf("%d %d", &n, &r);
printf("%lld\n", choose(n, r));
} | [
"daejin.seok@gmail.com"
] | daejin.seok@gmail.com |
639f684b057b45aac8220870b4184777b78894b3 | 64b008ca7d2f2291e7a0094a3f9f22db48099168 | /ios/versioned-react-native/ABI37_0_0/ReactNative/ReactCommon/fabric/uimanager/ABI37_0_0ComponentDescriptorRegistry.cpp | 9ef9782d338543cdf5dd4dd47aacbffc3f67a733 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | kojoYeboah53i/expo | bb971d566cd54750030dc431030a8d3045adff82 | 75d1b44ed4c4bbd05d7ec109757a017628c43415 | refs/heads/master | 2021-05-19T04:19:26.747650 | 2020-03-31T05:05:26 | 2020-03-31T05:05:26 | 251,520,515 | 5 | 0 | NOASSERTION | 2020-03-31T06:37:14 | 2020-03-31T06:37:13 | null | UTF-8 | C++ | false | false | 6,112 | cpp | // 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.
#include "ABI37_0_0ComponentDescriptorRegistry.h"
#include <ABI37_0_0React/core/ShadowNodeFragment.h>
#include <ABI37_0_0React/uimanager/primitives.h>
namespace ABI37_0_0facebook {
namespace ABI37_0_0React {
ComponentDescriptorRegistry::ComponentDescriptorRegistry(
ComponentDescriptorParameters const ¶meters)
: parameters_(parameters) {}
void ComponentDescriptorRegistry::add(
ComponentDescriptorProvider componentDescriptorProvider) const {
std::unique_lock<better::shared_mutex> lock(mutex_);
auto componentDescriptor = componentDescriptorProvider.constructor(
parameters_.eventDispatcher, parameters_.contextContainer);
assert(
componentDescriptor->getComponentHandle() ==
componentDescriptorProvider.handle);
assert(
componentDescriptor->getComponentName() ==
componentDescriptorProvider.name);
auto sharedComponentDescriptor = std::shared_ptr<ComponentDescriptor const>(
std::move(componentDescriptor));
_registryByHandle[componentDescriptorProvider.handle] =
sharedComponentDescriptor;
_registryByName[componentDescriptorProvider.name] = sharedComponentDescriptor;
if (strcmp(componentDescriptorProvider.name, "UnimplementedNativeView") ==
0) {
auto *self = const_cast<ComponentDescriptorRegistry *>(this);
self->setFallbackComponentDescriptor(sharedComponentDescriptor);
}
}
void ComponentDescriptorRegistry::remove(
ComponentDescriptorProvider componentDescriptorProvider) const {
std::unique_lock<better::shared_mutex> lock(mutex_);
assert(
_registryByHandle.find(componentDescriptorProvider.handle) !=
_registryByHandle.end());
assert(
_registryByName.find(componentDescriptorProvider.name) !=
_registryByName.end());
_registryByHandle.erase(componentDescriptorProvider.handle);
_registryByName.erase(componentDescriptorProvider.name);
}
void ComponentDescriptorRegistry::registerComponentDescriptor(
SharedComponentDescriptor componentDescriptor) const {
ComponentHandle componentHandle = componentDescriptor->getComponentHandle();
_registryByHandle[componentHandle] = componentDescriptor;
ComponentName componentName = componentDescriptor->getComponentName();
_registryByName[componentName] = componentDescriptor;
}
static std::string componentNameByABI37_0_0ReactViewName(std::string viewName) {
// We need this function only for the transition period;
// eventually, all names will be unified.
std::string rctPrefix("ABI37_0_0RCT");
if (std::mismatch(rctPrefix.begin(), rctPrefix.end(), viewName.begin())
.first == rctPrefix.end()) {
// If `viewName` has "ABI37_0_0RCT" prefix, remove it.
viewName.erase(0, rctPrefix.length());
}
// Fabric uses slightly new names for Text components because of differences
// in semantic.
if (viewName == "Text") {
return "Paragraph";
}
if (viewName == "VirtualText") {
return "Text";
}
if (viewName == "ImageView") {
return "Image";
}
if (viewName == "AndroidHorizontalScrollView") {
return "ScrollView";
}
if (viewName == "RKShimmeringView") {
return "ShimmeringView";
}
if (viewName == "AndroidProgressBar") {
return "ActivityIndicatorView";
}
// We need this temporarily for testing purposes until we have proper
// implementation of core components.
if (viewName == "SinglelineTextInputView" ||
viewName == "MultilineTextInputView" || viewName == "AndroidTextInput" ||
viewName == "SafeAreaView" || viewName == "ScrollContentView" ||
viewName == "AndroidHorizontalScrollContentView" // Android
) {
return "View";
}
return viewName;
}
ComponentDescriptor const &ComponentDescriptorRegistry::at(
std::string const &componentName) const {
std::shared_lock<better::shared_mutex> lock(mutex_);
auto unifiedComponentName = componentNameByABI37_0_0ReactViewName(componentName);
auto it = _registryByName.find(unifiedComponentName);
if (it == _registryByName.end()) {
if (_fallbackComponentDescriptor == nullptr) {
throw std::invalid_argument(
("Unable to find componentDescriptor for " + unifiedComponentName)
.c_str());
}
return *_fallbackComponentDescriptor.get();
}
return *it->second;
}
ComponentDescriptor const &ComponentDescriptorRegistry::at(
ComponentHandle componentHandle) const {
std::shared_lock<better::shared_mutex> lock(mutex_);
return *_registryByHandle.at(componentHandle);
}
SharedShadowNode ComponentDescriptorRegistry::createNode(
Tag tag,
std::string const &viewName,
SurfaceId surfaceId,
folly::dynamic const &propsDynamic,
SharedEventTarget const &eventTarget) const {
auto unifiedComponentName = componentNameByABI37_0_0ReactViewName(viewName);
auto const &componentDescriptor = this->at(unifiedComponentName);
auto const eventEmitter =
componentDescriptor.createEventEmitter(std::move(eventTarget), tag);
auto const props =
componentDescriptor.cloneProps(nullptr, RawProps(propsDynamic));
auto const state = componentDescriptor.createInitialState(
ShadowNodeFragment{surfaceId, tag, props, eventEmitter});
return componentDescriptor.createShadowNode({
/* .tag = */ tag,
/* .surfaceId = */ surfaceId,
/* .props = */ props,
/* .eventEmitter = */ eventEmitter,
/* .children = */ ShadowNodeFragment::childrenPlaceholder(),
/* .localData = */ ShadowNodeFragment::localDataPlaceholder(),
/* .state = */ state,
});
}
void ComponentDescriptorRegistry::setFallbackComponentDescriptor(
SharedComponentDescriptor descriptor) {
_fallbackComponentDescriptor = descriptor;
registerComponentDescriptor(descriptor);
}
ComponentDescriptor::Shared
ComponentDescriptorRegistry::getFallbackComponentDescriptor() const {
return _fallbackComponentDescriptor;
}
} // namespace ABI37_0_0React
} // namespace ABI37_0_0facebook
| [
"noreply@github.com"
] | noreply@github.com |
ea5ff82e116f5ce0948b3ad472128bd197f4ca5d | 557e9f858df6e545cd8b7fa8c3832d4871d86609 | /Snake/Snake/Food.cpp | d116b39d9fc5dc8745d15386cacb5b6a7f13d81b | [] | no_license | Tequ1ia/- | 2f533309a3b18122d6d1baac108e5619c4d5ae77 | f909fdd2484ac2e6335ff699e653d717d4f65c0d | refs/heads/master | 2021-04-19T04:04:25.231838 | 2020-03-24T00:56:41 | 2020-03-24T00:56:41 | 249,578,442 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,619 | cpp | #include "Food.h"
using namespace std;
//构造函数
Food::Food(bool big) {
if (!big) {
coord.x = (rand() % (Game::windows_cols - 40)) + 1;
coord.y = (rand() % (Game::windows_lines - 2)) + 1;
while (coord == Coordinate{ 13, 14 } || coord == Coordinate{ 13, 15 } || coord == Coordinate{ 13, 16 }) {
coord.x = (rand() % (Game::windows_cols - 40)) + 1;
coord.y = (rand() % (Game::windows_lines - 2)) + 1;
}
step = 0;
is_big = false;
}
else {
step = 0;
is_big = true;
exist = false;
}
PrintFood();
}
//在屏幕上输出食物
void Food::PrintFood() {
if (is_big && exist) {
Move_Console(coord.x - 1, coord.y - 1);
cout << "@@@";
Move_Console(coord.x - 1, coord.y);
cout << "@@@";
Move_Console(coord.x - 1, coord.y + 1);
cout << "@@@";
Move_Console(73, 16);
cout << "特殊食物出现中!";
Move_Console(73, 17);
cout << "特殊食物将在:45步后消失";
}
if (!is_big) {
Move_Console(coord);
cout << "@";
}
}
void Food::ClearBigFood() {
if (exist) {
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++) {
Coordinate offset = { i, j };
Move_Console(Coordinate{ i,j } +coord);
cout << " ";
}
}
}
void Food::BigFoodDisappear() {
if (step == 45) {
ClearBigFood();
exist = false;
Move_Console(73, 16);
cout << "特殊食物已消失 ";
Move_Console(73, 17);
cout << " ";
return;
}
if (exist) {
Move_Console(73, 17);
cout << "特殊食物将在:"<< 45 - step << "步后消失";
return;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
e5cb3319387fb7d47b6a8a933665680835803781 | 7d46438a5c36a9dd2c5c648623fb80c155fe52e1 | /assignment_2/Card.h | 1f6ddb4b476b4390635dbf96f7a194fde6b0f7b8 | [] | no_license | mustafapasli/ObjectOrientedProgramingHWs | 22d3a75de901288f58f73caed9bbc8d3af2ba1dd | 1a04694fee08a05cf75275b56c4aca5a55a0705b | refs/heads/master | 2020-04-20T17:18:23.871090 | 2019-02-03T19:47:50 | 2019-02-03T19:47:50 | 168,985,121 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | h | #ifndef CARD_H
#define CARD_H
#include <iostream>
#include <vector>
using namespace std;
class Card{
public:
Card();
bool isOnBoard() const;
void rotateLeft();
void rotateRight();
void displayCard() const;
void convertCardtoArray(); // convert card to 6x12 arrays
void setOnBoard(bool onBoard);
void setArrayCard(const vector <vector <char> > &arrayCard);
const vector< vector< char> > & getArrayCard() const;
private:
int cardWidth;
int cardHeight;
int random(int port) const; // returns random number for port number
bool onBoard;
void generateRandomCard(); // generate random port and path number
char toChar(int number) const { return static_cast<char>(number + 48); }
vector <int> cardPort;
vector <int> cardPath;
vector <vector <char> > arrayCard;
};
#endif //CARD_H
| [
"noreply@github.com"
] | noreply@github.com |
25919db5d2418509225a3e8e1f946c1c7e45f04d | 3c7e68fc49a0205d028fb6862040c202fe071426 | /src/libgeodecomp/geometry/adjacencymanufacturer.h | 81668bf7e04cead8bd6d5181d20d5790984b5bd2 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | valleymouth/libgeodecomp | 0046812fadde48f558397cc0f07bc27ed8f6f743 | 7e6d912e5ade574284d5a3186f940dc6f8b04c13 | refs/heads/master | 2021-08-07T18:53:03.951338 | 2020-04-22T12:15:13 | 2020-04-22T12:15:13 | 180,335,925 | 0 | 0 | BSL-1.0 | 2019-04-09T09:47:47 | 2019-04-09T09:47:43 | null | UTF-8 | C++ | false | false | 1,220 | h | #ifndef LIBGEODECOMP_GEOMETRY_ADJACENCYMANUFACTURER_H
#define LIBGEODECOMP_GEOMETRY_ADJACENCYMANUFACTURER_H
#include <stdexcept>
#include <libgeodecomp/geometry/adjacency.h>
#include <libgeodecomp/geometry/region.h>
#include <libgeodecomp/geometry/regionbasedadjacency.h>
#include <libgeodecomp/misc/sharedptr.h>
namespace LibGeoDecomp {
class RegionBasedAdjacency;
/**
* Wrapper to separate Adjacency creation from the Cell template
* parameter type in Initializers.
*/
template<int DIM>
class AdjacencyManufacturer
{
public:
typedef typename SharedPtr<Adjacency>::Type AdjacencyPtr;
virtual ~AdjacencyManufacturer()
{}
/**
* yields an Adjacency object with all outgoing edges of the node
* set in the given Region.
*/
virtual AdjacencyPtr getAdjacency(const Region<DIM>& region) const = 0;
/**
* Same a getAdjacency, but returns all edges pointing to the
* nodes in the given Region. Also inverts the direction of the
* edges. Used in the PartitionManager to grow inverse rims around
* a region. See UnstructuredTestInitializer for an example.
*/
virtual AdjacencyPtr getReverseAdjacency(const Region<DIM>& region) const = 0;
};
}
#endif
| [
"gentryx@gmx.de"
] | gentryx@gmx.de |
0582ac01283b6362f54e38f4a84438c129e90cd6 | 41786beefb03d7c46d4c71a3659ad64f8e8ea2ea | /src/protocol/iec103/iec103asdu4data.cpp | 39c4ab13eb76bd92c6fc83d101471bf6df93a17d | [] | no_license | fanzcsoft/PDTool | dac070ffcb098928233cb41c67c7bc009f4da77b | 57e635b4954f06d29b735abdb084f1d56653ed6d | refs/heads/main | 2023-04-08T04:50:29.100281 | 2021-04-13T08:48:03 | 2021-04-13T08:48:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,254 | cpp | #include "iec103asdu4data.h"
IEC103Asdu4Data::IEC103Asdu4Data(const MyConfig& Config): IEC103AsduData(Config)
{
scl = 0;
ret = 0;
fan = 0;
}
IEC103Asdu4Data::~IEC103Asdu4Data()
{
}
bool IEC103Asdu4Data::handle(const QByteArray& buff)
{
scl = charTofloat(buff.data() + mLen);
mText.append(CharToHexStr(buff.data() + mLen, 4) + "\t短路位置SCL: " + QString::number(scl) + "\r\n");
mLen += 4;
ret = charTouint(buff.data() + mLen, 2);
mText.append(CharToHexStr(buff.data() + mLen, 2) + "\t相对时间RET: " + QString::number(ret) + "\r\n");
mLen += 2;
fan = charTouint(buff.data() + mLen, 2);
mText.append(CharToHexStr(buff.data() + mLen, 2) + "\t故障序号FAN: " + QString::number(fan) + "\r\n");
mLen += 2;
datetime = charToDateTime(buff.data() + mLen, 4, BINARYTIME2A);
mText.append(timeToText(buff.data() + mLen, 4));
mLen += 4;
mText.append("-----------------------------------------------------------------------------------------------\r\n");
if(mLen > buff.length())
{
mError = QString("\"%1\" %2 [%3行]\r\n%4\r\n").arg(__FILE__).arg(__FUNCTION__).arg(__LINE__).arg(QString("出错!解析所需报文长度(%1)比实际报文长度(%2)长").arg(mLen).arg(buff.length()));
return false;
}
return true;
}
| [
"60013551+whx110123@users.noreply.github.com"
] | 60013551+whx110123@users.noreply.github.com |
446eb529f10043e29e9767bb9e067ac552edecf0 | d347554c4bc24b7e159551007f5683cac8fa97d0 | /cwp/src/back/proto/obelix/CmdChangeSFPL.h | 8eb5711a7b1162ebd5fb0ae6f024d269952f0e34 | [] | no_license | ansartnl/ALPHA | 892065b1476ec9c35e834a3158592332cda4c5f5 | 138ddd981ed5bac882c29f28a065171e51d680cf | refs/heads/main | 2022-12-27T16:15:28.721053 | 2020-10-16T08:58:41 | 2020-10-16T08:58:41 | 304,633,537 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,584 | h | #ifndef CMDCHANGESFPL_H
#define CMDCHANGESFPL_H
#include "proto/TCP/XMLCmd.h"
#include "ListAC.h"
class CMaster;
namespace obelix
{
//! Notifiaction to client about wish to transmist airplane control from another operator(creation)
class CCmdChangeSFPL
: public CXMLCmd
{
public:
/*! \name String constants */
//@{
static const char XML_CMDNAME[];
static const char XML_CHANGE[];
static const char XML_TYPE[];
static const char XML_AIRID[];
static const char XML_FPLID[]; //quint32
static const char XML_CODE[]; //toInt(0, 8)
static const char XML_COPIN[]; //QString
static const char XML_ETOIN[]; //time
static const char XML_COPINFL[];//double
enum Type{Change,ACC,ARR,DEP, Cancel, Edit, SetData, STAR};
//! Constructor
/*!
\param uiAirID airplane identifeir
\param sOLDIMes OLDI message type
*/
CCmdChangeSFPL(Type type);
//! Get airplane identifeir
/*!
\return airplane identifeir
*/
Type GetType();
//! Set the value of an XML attribute
/*!
\param sAttrName attribute name
\param sVal value
*/
template <class T>
void SetValue(const QString& sAttrName, const T& sVal)
{
m_DNChange.setAttribute(sAttrName, sVal);
}
//! Get the value of an XML attribute
/*!
\param sAttrName attribute name
\return value
*/
QString GetValue(const QString& sAttrName);
protected:
//! Constructor for CCmdChangeSFPL
/*!
\param pData smart pointer to CXMLData
*/
explicit CCmdChangeSFPL(const CXMLData::TXMLData& pData);
private:
QDomElement m_DNChange;
QDomAttr m_DAType;
};
//! Notifiaction to client about wish to transmist airplane control from another operator(execution)
class CCmdChangeSFPLExe
: public CCmdChangeSFPL
{
public:
//! Constructor
/*!
\param pData smart pointer to CXMLData
\param refMaster reference to CMaster
*/
CCmdChangeSFPLExe(
const CXMLData::TXMLData& pData,
CMaster& refMaster);
/*! \name Implementation of CXMLCmd interface */
//@{
virtual CXMLResp::TXMLResp Execute();
//@}
private:
CMaster& m_refMaster;
};
}
#endif // CMDCHANGESFPL_H
| [
"50514882+dg-atmsys@users.noreply.github.com"
] | 50514882+dg-atmsys@users.noreply.github.com |
265a1a5cd98d08fdf9268a25f6e0abef5c26d17b | f2c58a07b411660dfd5488fb0adc0287e92646d2 | /WPTelnetDLib/Networking.h | 63e68f1dc6f031540ba547cc66bfbd72b9d24a40 | [
"MIT"
] | permissive | snickler/WPTelnetD | 76656aca2342b9716ed6e4bb71c97e14726e29bd | 69c96d308f3a505e7f91148c90d2de97c424f8f0 | refs/heads/master | 2021-01-17T05:41:59.846649 | 2015-02-13T22:59:48 | 2015-02-13T22:59:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | h | #pragma once
#include "pch.h"
#include<string>
class Connection {
private:
SOCKET _socket;
char _buf[4096];
char _lineBuf[4096];
int _used;
public:
Connection(SOCKET pSocket);
~Connection();
const char * ReadLine();
bool WaitForEnter();
bool WriteLine(std::string pString);
bool Write(int pBytes, char *data);
bool Write(std::string pString);
bool WriteLine(std::wstring pString);
bool WriteLine( const char* pMsg, ...);
bool Write( const char* pMsg, ...);
bool Write(char pChar);
bool WriteLastError();
};
class ListenSocket
{
private:
u_short _port;
SOCKET _socket;
public:
ListenSocket(u_short pPort);
~ListenSocket() ;
bool Start();
SOCKET Accept();
void Stop();
};
| [
"Furball626@gmail.com"
] | Furball626@gmail.com |
c58d99f8ea79c24797fbd5d51ea5216c12c6e662 | e37f73457d585b136598f7c0e005d6c26c390762 | /RL/include/baby_robot3.hpp | 3f2630f3bf7a52d74545fb60001b56e9e29ea41b | [] | no_license | KitauraHiromi/ode_RL | ee6e004fffe26e66bcbb2b21d41fe037ebd76beb | 223e5fd73187719746b932f5c5a0b5ab192ccd44 | refs/heads/master | 2021-03-27T20:49:46.861621 | 2017-03-01T10:58:13 | 2017-03-01T10:58:13 | 76,459,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,117 | hpp | #ifndef __BABY_ROBOT3_IS_USED__
#define __BABY_ROBOT3_IS_USED__
#include <vector>
#include <string>
#include <ode/ode.h>
#include <drawstuff/drawstuff.h>
#include "include/libmesh.hpp"
// the number of links
#define NUM 11
#define DOF 15
#define SHELL_NUM 10
#define MEM_NUM NUM*sizeof(dReal)
#define MEM_DOF DOF*sizeof(dReal)
#define TAC_NUM 1
#define Main_Robot Baby_Robot3
#define __USE_OLD_TACTILE__
#define __USE_JOINT_CILYNDER__
#define __USE_SHELL__
typedef struct {
dBodyID body;
dGeomID geom;
dVector3 value;
} MyObject;
class Baby_Robot3{
public:
//dReal angle_pitch;
dReal ROM[DOF * 2];
//unsigned int dof;
MyObject link[NUM]; // リンク
MyObject joint_cyli[DOF];
MyObject tac_sensor[TAC_NUM];
MyObject outer_shell[SHELL_NUM];
dJointID joint[DOF]; // 関節
dJointID body_join_fix[6];
dJointID limb_join_fix[4];
dJointID outer_shell_fix[SHELL_NUM];
dJointID tac_fix[TAC_NUM];// 触覚固定ジョイント
dReal ANGLE[DOF]; // 関節目標角[deg]
dReal l[NUM]; // リンク長[m]
dReal r[NUM]; // リンク半径[m]
dReal joint_cyli_r;
dReal tac_size[3];
// center of positon
dReal x[NUM]; dReal y[NUM]; dReal z[NUM];
//mass
dReal m_link[NUM];
dReal m_join[DOF];
dReal x1, y1, z1;
dReal anchor_x[DOF]; dReal anchor_y[DOF]; dReal anchor_z[DOF];// 回転中心
dReal axis_x[DOF]; dReal axis_y[DOF]; dReal axis_z[DOF]; // 回転軸
// mass parameter
dMass mass_link[NUM];
dMass mass_join[DOF];
dMass mass_tac[TAC_NUM];
Baby_Robot3(dWorldID, dSpaceID);
~Baby_Robot3();
void Create_tac(dWorldID, dSpaceID);
void Create_link(dWorldID, dSpaceID);
void Create_joint_cyli(dWorldID, dSpaceID);
void Joint_Setting(dWorldID);
void restrict_angle(int);
void control();
bool Is_Tactile(dGeomID);
int Which_Tactile(dGeomID);
bool BodyTactileCollision(dGeomID, dGeomID);
bool BodyBodyCollision(dGeomID, dGeomID);
bool BodyJointCollision(dGeomID, dGeomID);
void command(int);
};
extern Baby_Robot3* robot;
#endif
| [
"kitaura@isi.imi.i.u-tokyo.ac.jp"
] | kitaura@isi.imi.i.u-tokyo.ac.jp |
55f8ef9f5ec4028b0d451837c910c5b8d177e830 | 563def4f397c5e130fb9282d72cbe9a942522f99 | /outdir/nv_small/spec/manual/NVDLA_SDP_reg_c/ordt_pio.cpp | 2a8c21b8f9a25c4f7142886b5d668cd4d1f752dd | [] | no_license | Allahfan/nvdla_change | 8311f581b6776cb531e504d6998ab8da583e36e2 | cadd45ead29ff7a11970dc3f3b19b22e84d43fcb | refs/heads/master | 2020-08-16T00:42:34.123345 | 2019-10-16T01:50:52 | 2019-10-16T01:50:52 | 215,432,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 124,511 | cpp | // Ordt 171103.01 autogenerated file
// Input: NVDLA_SDP.rdl
// Parms: opendla.parms
// Date: Tue Jun 25 16:49:22 CST 2019
//
#include "ordt_pio_common.hpp"
#include "ordt_pio.hpp"
// ------------------ ordt_addr_elem methods ------------------
ordt_addr_elem::ordt_addr_elem(uint64_t _m_startaddress, uint64_t _m_endaddress)
: m_startaddress(_m_startaddress),
m_endaddress(_m_endaddress) {
}
bool ordt_addr_elem::containsAddress(const uint64_t &addr) {
return ((addr >= m_startaddress) && (addr <= m_endaddress));
}
bool ordt_addr_elem::isBelowAddress(const uint64_t &addr) {
return (addr > m_endaddress);
}
bool ordt_addr_elem::isAboveAddress(const uint64_t &addr) {
return (addr < m_startaddress);
}
bool ordt_addr_elem::hasStartAddress(const uint64_t &addr) {
return (addr == m_startaddress);
}
void ordt_addr_elem::update_child_ptrs() {
}
// ------------------ ordt_regset methods ------------------
ordt_addr_elem* ordt_regset::findAddrElem(const uint64_t &addr) {
int lo = 0;
int hi = m_children.size()-1;
int mid = 0;
while (lo <= hi) {
mid = (lo + hi) / 2;
if (m_children[mid]->containsAddress(addr)) {
//outElem = m_children[mid];
return m_children[mid];
}
else if (m_children[mid]->isAboveAddress(addr))
hi = mid - 1;
else
lo = mid + 1;
}
return nullptr;
}
ordt_regset::ordt_regset(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_addr_elem(_m_startaddress, _m_endaddress) {
}
int ordt_regset::write(const uint64_t &addr, const ordt_data &wdata) {
if (this->containsAddress(addr)) {
childElem = this->findAddrElem(addr);
if (childElem != nullptr) { return childElem->write(addr, wdata); }
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in regset\n";
#endif
return 8;
}
int ordt_regset::read(const uint64_t &addr, ordt_data &rdata) {
if (this->containsAddress(addr)) {
childElem = this->findAddrElem(addr);
if (childElem != nullptr) { return childElem->read(addr, rdata); }
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in regset\n";
#endif
rdata.clear();
return 8;
}
// ------------------ ordt_reg methods ------------------
ordt_reg::ordt_reg(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_addr_elem(_m_startaddress, _m_endaddress) {
}
ordt_reg::ordt_reg(const ordt_reg &_old)
: ordt_addr_elem(_old),
m_mutex() {
}
void ordt_reg::write(const ordt_data &wdata) {
}
int ordt_reg::write(const uint64_t &addr, const ordt_data &wdata) {
return 0;
}
void ordt_reg::read(ordt_data &rdata) {
}
int ordt_reg::read(const uint64_t &addr, ordt_data &rdata) {
return 0;
}
// ------------------ ordt_rg_NVDLA_SDP_S_STATUS methods ------------------
ordt_rg_NVDLA_SDP_S_STATUS::ordt_rg_NVDLA_SDP_S_STATUS(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
STATUS_0(0, 2, 0x0, r_std, w_none),
STATUS_1(16, 2, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_S_STATUS::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_STATUS at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_STATUS\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_STATUS::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
STATUS_0.write(wdata);
STATUS_1.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_STATUS::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_STATUS at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_STATUS\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_STATUS::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
STATUS_0.read(rdata);
STATUS_1.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_POINTER methods ------------------
ordt_rg_NVDLA_SDP_S_POINTER::ordt_rg_NVDLA_SDP_S_POINTER(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
PRODUCER(0, 1, 0x0, r_std, w_std),
CONSUMER(16, 1, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_S_POINTER::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_POINTER at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_POINTER\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_POINTER::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
PRODUCER.write(wdata);
CONSUMER.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_POINTER::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_POINTER at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_POINTER\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_POINTER::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
PRODUCER.read(rdata);
CONSUMER.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG::ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_ADDR(0, 10, 0x0, r_std, w_std),
LUT_TABLE_ID(16, 1, 0x0, r_std, w_std),
LUT_ACCESS_TYPE(17, 1, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_ADDR.write(wdata);
LUT_TABLE_ID.write(wdata);
LUT_ACCESS_TYPE.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_ACCESS_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_ADDR.read(rdata);
LUT_TABLE_ID.read(rdata);
LUT_ACCESS_TYPE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA::ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_DATA(0, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_DATA.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_ACCESS_DATA::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_DATA.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_CFG methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_CFG::ordt_rg_NVDLA_SDP_S_LUT_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LE_FUNCTION(0, 1, 0x0, r_std, w_std),
LUT_UFLOW_PRIORITY(4, 1, 0x0, r_std, w_std),
LUT_OFLOW_PRIORITY(5, 1, 0x0, r_std, w_std),
LUT_HYBRID_PRIORITY(6, 1, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LE_FUNCTION.write(wdata);
LUT_UFLOW_PRIORITY.write(wdata);
LUT_OFLOW_PRIORITY.write(wdata);
LUT_HYBRID_PRIORITY.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LE_FUNCTION.read(rdata);
LUT_UFLOW_PRIORITY.read(rdata);
LUT_OFLOW_PRIORITY.read(rdata);
LUT_HYBRID_PRIORITY.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_INFO methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_INFO::ordt_rg_NVDLA_SDP_S_LUT_INFO(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LE_INDEX_OFFSET(0, 8, 0x0, r_std, w_std),
LUT_LE_INDEX_SELECT(8, 8, 0x0, r_std, w_std),
LUT_LO_INDEX_SELECT(16, 8, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_INFO::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_INFO at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_INFO\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_INFO::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LE_INDEX_OFFSET.write(wdata);
LUT_LE_INDEX_SELECT.write(wdata);
LUT_LO_INDEX_SELECT.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_INFO::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_INFO at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_INFO\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_INFO::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LE_INDEX_OFFSET.read(rdata);
LUT_LE_INDEX_SELECT.read(rdata);
LUT_LO_INDEX_SELECT.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_LE_START methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_LE_START::ordt_rg_NVDLA_SDP_S_LUT_LE_START(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LE_START(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_LE_START::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_LE_START at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LE_START\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LE_START::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LE_START.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_LE_START::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_LE_START at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LE_START\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LE_START::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LE_START.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_LE_END methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_LE_END::ordt_rg_NVDLA_SDP_S_LUT_LE_END(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LE_END(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_LE_END::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_LE_END at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LE_END\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LE_END::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LE_END.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_LE_END::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_LE_END at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LE_END\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LE_END::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LE_END.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_LO_START methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_LO_START::ordt_rg_NVDLA_SDP_S_LUT_LO_START(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LO_START(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_LO_START::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_LO_START at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LO_START\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LO_START::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LO_START.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_LO_START::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_LO_START at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LO_START\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LO_START::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LO_START.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_LO_END methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_LO_END::ordt_rg_NVDLA_SDP_S_LUT_LO_END(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LO_END(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_LO_END::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_LO_END at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LO_END\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LO_END::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LO_END.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_LO_END::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_LO_END at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LO_END\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LO_END::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LO_END.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE::ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LE_SLOPE_UFLOW_SCALE(0, 16, 0x0, r_std, w_std),
LUT_LE_SLOPE_OFLOW_SCALE(16, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LE_SLOPE_UFLOW_SCALE.write(wdata);
LUT_LE_SLOPE_OFLOW_SCALE.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SCALE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LE_SLOPE_UFLOW_SCALE.read(rdata);
LUT_LE_SLOPE_OFLOW_SCALE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT::ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LE_SLOPE_UFLOW_SHIFT(0, 5, 0x0, r_std, w_std),
LUT_LE_SLOPE_OFLOW_SHIFT(5, 5, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LE_SLOPE_UFLOW_SHIFT.write(wdata);
LUT_LE_SLOPE_OFLOW_SHIFT.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LE_SLOPE_SHIFT::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LE_SLOPE_UFLOW_SHIFT.read(rdata);
LUT_LE_SLOPE_OFLOW_SHIFT.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE::ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LO_SLOPE_UFLOW_SCALE(0, 16, 0x0, r_std, w_std),
LUT_LO_SLOPE_OFLOW_SCALE(16, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LO_SLOPE_UFLOW_SCALE.write(wdata);
LUT_LO_SLOPE_OFLOW_SCALE.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SCALE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LO_SLOPE_UFLOW_SCALE.read(rdata);
LUT_LO_SLOPE_OFLOW_SCALE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT methods ------------------
ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT::ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LO_SLOPE_UFLOW_SHIFT(0, 5, 0x0, r_std, w_std),
LUT_LO_SLOPE_OFLOW_SHIFT(5, 5, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LO_SLOPE_UFLOW_SHIFT.write(wdata);
LUT_LO_SLOPE_OFLOW_SHIFT.write(wdata);
}
int ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_S_LUT_LO_SLOPE_SHIFT::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LO_SLOPE_UFLOW_SHIFT.read(rdata);
LUT_LO_SLOPE_OFLOW_SHIFT.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_OP_ENABLE methods ------------------
ordt_rg_NVDLA_SDP_D_OP_ENABLE::ordt_rg_NVDLA_SDP_D_OP_ENABLE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
OP_EN(0, 1, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_OP_ENABLE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_OP_ENABLE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_OP_ENABLE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_OP_ENABLE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
OP_EN.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_OP_ENABLE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_OP_ENABLE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_OP_ENABLE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_OP_ENABLE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
OP_EN.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH methods ------------------
ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH::ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
WIDTH(0, 13, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
WIDTH.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DATA_CUBE_WIDTH::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
WIDTH.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT methods ------------------
ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT::ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
HEIGHT(0, 13, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
HEIGHT.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DATA_CUBE_HEIGHT::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
HEIGHT.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL methods ------------------
ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL::ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
CHANNEL(0, 13, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
CHANNEL.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DATA_CUBE_CHANNEL::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
CHANNEL.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW methods ------------------
ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW::ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
DST_BASE_ADDR_LOW(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
DST_BASE_ADDR_LOW.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_LOW::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
DST_BASE_ADDR_LOW.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH methods ------------------
ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH::ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
DST_BASE_ADDR_HIGH(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
DST_BASE_ADDR_HIGH.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_BASE_ADDR_HIGH::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
DST_BASE_ADDR_HIGH.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE methods ------------------
ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE::ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
DST_LINE_STRIDE(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
DST_LINE_STRIDE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_LINE_STRIDE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
DST_LINE_STRIDE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE methods ------------------
ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE::ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
DST_SURFACE_STRIDE(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
DST_SURFACE_STRIDE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_SURFACE_STRIDE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
DST_SURFACE_STRIDE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BS_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BS_CFG::ordt_rg_NVDLA_SDP_D_DP_BS_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BS_BYPASS(0, 1, 0x1, r_std, w_std),
BS_ALU_BYPASS(1, 1, 0x1, r_std, w_std),
BS_ALU_ALGO(2, 2, 0x0, r_std, w_std),
BS_MUL_BYPASS(4, 1, 0x1, r_std, w_std),
BS_MUL_PRELU(5, 1, 0x1, r_std, w_std),
BS_RELU_BYPASS(6, 1, 0x1, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BS_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BS_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BS_BYPASS.write(wdata);
BS_ALU_BYPASS.write(wdata);
BS_ALU_ALGO.write(wdata);
BS_MUL_BYPASS.write(wdata);
BS_MUL_PRELU.write(wdata);
BS_RELU_BYPASS.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BS_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BS_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BS_BYPASS.read(rdata);
BS_ALU_BYPASS.read(rdata);
BS_ALU_ALGO.read(rdata);
BS_MUL_BYPASS.read(rdata);
BS_MUL_PRELU.read(rdata);
BS_RELU_BYPASS.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG::ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BS_ALU_SRC(0, 1, 0x0, r_std, w_std),
BS_ALU_SHIFT_VALUE(8, 6, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BS_ALU_SRC.write(wdata);
BS_ALU_SHIFT_VALUE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_ALU_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BS_ALU_SRC.read(rdata);
BS_ALU_SHIFT_VALUE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE::ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BS_ALU_OPERAND(0, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BS_ALU_OPERAND.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_ALU_SRC_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BS_ALU_OPERAND.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG::ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BS_MUL_SRC(0, 1, 0x0, r_std, w_std),
BS_MUL_SHIFT_VALUE(8, 8, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BS_MUL_SRC.write(wdata);
BS_MUL_SHIFT_VALUE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_MUL_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BS_MUL_SRC.read(rdata);
BS_MUL_SHIFT_VALUE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE::ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BS_MUL_OPERAND(0, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BS_MUL_OPERAND.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BS_MUL_SRC_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BS_MUL_OPERAND.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BN_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BN_CFG::ordt_rg_NVDLA_SDP_D_DP_BN_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BN_BYPASS(0, 1, 0x1, r_std, w_std),
BN_ALU_BYPASS(1, 1, 0x1, r_std, w_std),
BN_ALU_ALGO(2, 2, 0x0, r_std, w_std),
BN_MUL_BYPASS(4, 1, 0x1, r_std, w_std),
BN_MUL_PRELU(5, 1, 0x0, r_std, w_std),
BN_RELU_BYPASS(6, 1, 0x1, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BN_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BN_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BN_BYPASS.write(wdata);
BN_ALU_BYPASS.write(wdata);
BN_ALU_ALGO.write(wdata);
BN_MUL_BYPASS.write(wdata);
BN_MUL_PRELU.write(wdata);
BN_RELU_BYPASS.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BN_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BN_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BN_BYPASS.read(rdata);
BN_ALU_BYPASS.read(rdata);
BN_ALU_ALGO.read(rdata);
BN_MUL_BYPASS.read(rdata);
BN_MUL_PRELU.read(rdata);
BN_RELU_BYPASS.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG::ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BN_ALU_SRC(0, 1, 0x0, r_std, w_std),
BN_ALU_SHIFT_VALUE(8, 6, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BN_ALU_SRC.write(wdata);
BN_ALU_SHIFT_VALUE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_ALU_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BN_ALU_SRC.read(rdata);
BN_ALU_SHIFT_VALUE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE::ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BN_ALU_OPERAND(0, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BN_ALU_OPERAND.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_ALU_SRC_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BN_ALU_OPERAND.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG::ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BN_MUL_SRC(0, 1, 0x0, r_std, w_std),
BN_MUL_SHIFT_VALUE(8, 8, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BN_MUL_SRC.write(wdata);
BN_MUL_SHIFT_VALUE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_MUL_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BN_MUL_SRC.read(rdata);
BN_MUL_SHIFT_VALUE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE::ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
BN_MUL_OPERAND(0, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
BN_MUL_OPERAND.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_BN_MUL_SRC_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
BN_MUL_OPERAND.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_CFG::ordt_rg_NVDLA_SDP_D_DP_EW_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_BYPASS(0, 1, 0x1, r_std, w_std),
EW_ALU_BYPASS(1, 1, 0x1, r_std, w_std),
EW_ALU_ALGO(2, 2, 0x0, r_std, w_std),
EW_MUL_BYPASS(4, 1, 0x1, r_std, w_std),
EW_MUL_PRELU(5, 1, 0x0, r_std, w_std),
EW_LUT_BYPASS(6, 1, 0x1, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_BYPASS.write(wdata);
EW_ALU_BYPASS.write(wdata);
EW_ALU_ALGO.write(wdata);
EW_MUL_BYPASS.write(wdata);
EW_MUL_PRELU.write(wdata);
EW_LUT_BYPASS.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_BYPASS.read(rdata);
EW_ALU_BYPASS.read(rdata);
EW_ALU_ALGO.read(rdata);
EW_MUL_BYPASS.read(rdata);
EW_MUL_PRELU.read(rdata);
EW_LUT_BYPASS.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG::ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_ALU_SRC(0, 1, 0x0, r_std, w_std),
EW_ALU_CVT_BYPASS(1, 1, 0x1, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_ALU_SRC.write(wdata);
EW_ALU_CVT_BYPASS.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_ALU_SRC.read(rdata);
EW_ALU_CVT_BYPASS.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_ALU_OPERAND(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_ALU_OPERAND.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_SRC_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_ALU_OPERAND.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_ALU_CVT_OFFSET(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_ALU_CVT_OFFSET.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_OFFSET_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_ALU_CVT_OFFSET.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_ALU_CVT_SCALE(0, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_ALU_CVT_SCALE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_SCALE_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_ALU_CVT_SCALE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_ALU_CVT_TRUNCATE(0, 6, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_ALU_CVT_TRUNCATE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_ALU_CVT_TRUNCATE_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_ALU_CVT_TRUNCATE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG::ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_MUL_SRC(0, 1, 0x0, r_std, w_std),
EW_MUL_CVT_BYPASS(1, 1, 0x1, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_MUL_SRC.write(wdata);
EW_MUL_CVT_BYPASS.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_MUL_SRC.read(rdata);
EW_MUL_CVT_BYPASS.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_MUL_OPERAND(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_MUL_OPERAND.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_SRC_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_MUL_OPERAND.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_MUL_CVT_OFFSET(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_MUL_CVT_OFFSET.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_OFFSET_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_MUL_CVT_OFFSET.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_MUL_CVT_SCALE(0, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_MUL_CVT_SCALE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_SCALE_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_MUL_CVT_SCALE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_MUL_CVT_TRUNCATE(0, 6, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_MUL_CVT_TRUNCATE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_MUL_CVT_TRUNCATE_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_MUL_CVT_TRUNCATE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE methods ------------------
ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE::ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
EW_TRUNCATE(0, 10, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
EW_TRUNCATE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DP_EW_TRUNCATE_VALUE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
EW_TRUNCATE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG::ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
FLYING_MODE(0, 1, 0x0, r_std, w_std),
OUTPUT_DST(1, 1, 0x0, r_std, w_std),
WINOGRAD(2, 1, 0x0, r_std, w_std),
NAN_TO_ZERO(3, 1, 0x0, r_std, w_std),
BATCH_NUMBER(8, 5, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
FLYING_MODE.write(wdata);
OUTPUT_DST.write(wdata);
WINOGRAD.write(wdata);
NAN_TO_ZERO.write(wdata);
BATCH_NUMBER.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_FEATURE_MODE_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
FLYING_MODE.read(rdata);
OUTPUT_DST.read(rdata);
WINOGRAD.read(rdata);
NAN_TO_ZERO.read(rdata);
BATCH_NUMBER.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DST_DMA_CFG methods ------------------
ordt_rg_NVDLA_SDP_D_DST_DMA_CFG::ordt_rg_NVDLA_SDP_D_DST_DMA_CFG(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
DST_RAM_TYPE(0, 1, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DST_DMA_CFG::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DST_DMA_CFG at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_DMA_CFG\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_DMA_CFG::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
DST_RAM_TYPE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DST_DMA_CFG::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DST_DMA_CFG at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_DMA_CFG\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_DMA_CFG::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
DST_RAM_TYPE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE methods ------------------
ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE::ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
DST_BATCH_STRIDE(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
DST_BATCH_STRIDE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DST_BATCH_STRIDE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
DST_BATCH_STRIDE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_DATA_FORMAT methods ------------------
ordt_rg_NVDLA_SDP_D_DATA_FORMAT::ordt_rg_NVDLA_SDP_D_DATA_FORMAT(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
PROC_PRECISION(0, 2, 0x0, r_std, w_std),
OUT_PRECISION(2, 2, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_DATA_FORMAT::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_DATA_FORMAT at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DATA_FORMAT\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_DATA_FORMAT::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
PROC_PRECISION.write(wdata);
OUT_PRECISION.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_DATA_FORMAT::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_DATA_FORMAT at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_DATA_FORMAT\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_DATA_FORMAT::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
PROC_PRECISION.read(rdata);
OUT_PRECISION.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_CVT_OFFSET methods ------------------
ordt_rg_NVDLA_SDP_D_CVT_OFFSET::ordt_rg_NVDLA_SDP_D_CVT_OFFSET(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
CVT_OFFSET(0, 32, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_CVT_OFFSET::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_CVT_OFFSET at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_CVT_OFFSET\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_CVT_OFFSET::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
CVT_OFFSET.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_CVT_OFFSET::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_CVT_OFFSET at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_CVT_OFFSET\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_CVT_OFFSET::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
CVT_OFFSET.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_CVT_SCALE methods ------------------
ordt_rg_NVDLA_SDP_D_CVT_SCALE::ordt_rg_NVDLA_SDP_D_CVT_SCALE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
CVT_SCALE(0, 16, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_CVT_SCALE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_CVT_SCALE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_CVT_SCALE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_CVT_SCALE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
CVT_SCALE.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_CVT_SCALE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_CVT_SCALE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_CVT_SCALE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_CVT_SCALE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
CVT_SCALE.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_CVT_SHIFT methods ------------------
ordt_rg_NVDLA_SDP_D_CVT_SHIFT::ordt_rg_NVDLA_SDP_D_CVT_SHIFT(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
CVT_SHIFT(0, 6, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_CVT_SHIFT::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_CVT_SHIFT at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_CVT_SHIFT\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_CVT_SHIFT::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
CVT_SHIFT.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_CVT_SHIFT::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_CVT_SHIFT at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_CVT_SHIFT\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_CVT_SHIFT::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
CVT_SHIFT.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_STATUS methods ------------------
ordt_rg_NVDLA_SDP_D_STATUS::ordt_rg_NVDLA_SDP_D_STATUS(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
STATUS_UNEQUAL(0, 1, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_STATUS::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_STATUS at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_STATUS\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_STATUS::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
STATUS_UNEQUAL.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_STATUS::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_STATUS at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_STATUS\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_STATUS::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
STATUS_UNEQUAL.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM methods ------------------
ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM::ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
STATUS_NAN_INPUT_NUM(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
STATUS_NAN_INPUT_NUM.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_STATUS_NAN_INPUT_NUM::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
STATUS_NAN_INPUT_NUM.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM methods ------------------
ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM::ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
STATUS_INF_INPUT_NUM(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
STATUS_INF_INPUT_NUM.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_STATUS_INF_INPUT_NUM::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
STATUS_INF_INPUT_NUM.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM methods ------------------
ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM::ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
STATUS_NAN_OUTPUT_NUM(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
STATUS_NAN_OUTPUT_NUM.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_STATUS_NAN_OUTPUT_NUM::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
STATUS_NAN_OUTPUT_NUM.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_PERF_ENABLE methods ------------------
ordt_rg_NVDLA_SDP_D_PERF_ENABLE::ordt_rg_NVDLA_SDP_D_PERF_ENABLE(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
PERF_DMA_EN(0, 1, 0x0, r_std, w_std),
PERF_LUT_EN(1, 1, 0x0, r_std, w_std),
PERF_SAT_EN(2, 1, 0x0, r_std, w_std),
PERF_NAN_INF_COUNT_EN(3, 1, 0x0, r_std, w_std) {
}
int ordt_rg_NVDLA_SDP_D_PERF_ENABLE::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_PERF_ENABLE at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_ENABLE\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_ENABLE::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
PERF_DMA_EN.write(wdata);
PERF_LUT_EN.write(wdata);
PERF_SAT_EN.write(wdata);
PERF_NAN_INF_COUNT_EN.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_PERF_ENABLE::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_PERF_ENABLE at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_ENABLE\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_ENABLE::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
PERF_DMA_EN.read(rdata);
PERF_LUT_EN.read(rdata);
PERF_SAT_EN.read(rdata);
PERF_NAN_INF_COUNT_EN.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL methods ------------------
ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL::ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
WDMA_STALL(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
WDMA_STALL.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_WDMA_WRITE_STALL::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
WDMA_STALL.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW methods ------------------
ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW::ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_UFLOW(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_UFLOW.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_UFLOW::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_UFLOW.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW methods ------------------
ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW::ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_OFLOW(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_OFLOW.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_OFLOW::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_OFLOW.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION methods ------------------
ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION::ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
OUT_SATURATION(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
OUT_SATURATION.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_OUT_SATURATION::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
OUT_SATURATION.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID methods ------------------
ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID::ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_HYBRID(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_HYBRID.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_HYBRID::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_HYBRID.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT methods ------------------
ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT::ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LE_HIT(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LE_HIT.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_LE_HIT::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LE_HIT.read(rdata);
}
// ------------------ ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT methods ------------------
ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT::ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_reg(_m_startaddress, _m_endaddress),
LUT_LO_HIT(0, 32, 0x0, r_std, w_none) {
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT::write(const uint64_t &addr, const ordt_data &wdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT at addr="<< addr << ", data=" << wdata.to_string() << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->write(wdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> write to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT\n";
#endif
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT::write(const ordt_data &wdata) {
std::lock_guard<std::mutex> m_guard(m_mutex);
LUT_LO_HIT.write(wdata);
}
int ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT::read(const uint64_t &addr, ordt_data &rdata) {
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read of reg ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT at addr="<< addr << "\n";
#endif
if (this->hasStartAddress(addr)) {
this->read(rdata);
return 0;
}
#ifdef ORDT_PIO_VERBOSE
std::cout << "--> read to invalid address " << addr << " in reg ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT\n";
#endif
rdata.clear();
return 8;
}
void ordt_rg_NVDLA_SDP_D_PERF_LUT_LO_HIT::read(ordt_data &rdata) {
rdata.clear();
for (int widx=0; widx<((m_endaddress - m_startaddress + 1)/4); widx++) rdata.push_back(0);
LUT_LO_HIT.read(rdata);
}
// ------------------ ordt_rset_NVDLA_SDP methods ------------------
ordt_rset_NVDLA_SDP::ordt_rset_NVDLA_SDP(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_regset(_m_startaddress, _m_endaddress),
S_STATUS(_m_startaddress + 0x0, _m_startaddress + 0x3),
S_POINTER(_m_startaddress + 0x4, _m_startaddress + 0x7),
S_LUT_ACCESS_CFG(_m_startaddress + 0x8, _m_startaddress + 0xb),
S_LUT_ACCESS_DATA(_m_startaddress + 0xc, _m_startaddress + 0xf),
S_LUT_CFG(_m_startaddress + 0x10, _m_startaddress + 0x13),
S_LUT_INFO(_m_startaddress + 0x14, _m_startaddress + 0x17),
S_LUT_LE_START(_m_startaddress + 0x18, _m_startaddress + 0x1b),
S_LUT_LE_END(_m_startaddress + 0x1c, _m_startaddress + 0x1f),
S_LUT_LO_START(_m_startaddress + 0x20, _m_startaddress + 0x23),
S_LUT_LO_END(_m_startaddress + 0x24, _m_startaddress + 0x27),
S_LUT_LE_SLOPE_SCALE(_m_startaddress + 0x28, _m_startaddress + 0x2b),
S_LUT_LE_SLOPE_SHIFT(_m_startaddress + 0x2c, _m_startaddress + 0x2f),
S_LUT_LO_SLOPE_SCALE(_m_startaddress + 0x30, _m_startaddress + 0x33),
S_LUT_LO_SLOPE_SHIFT(_m_startaddress + 0x34, _m_startaddress + 0x37),
D_OP_ENABLE(_m_startaddress + 0x38, _m_startaddress + 0x3b),
D_DATA_CUBE_WIDTH(_m_startaddress + 0x3c, _m_startaddress + 0x3f),
D_DATA_CUBE_HEIGHT(_m_startaddress + 0x40, _m_startaddress + 0x43),
D_DATA_CUBE_CHANNEL(_m_startaddress + 0x44, _m_startaddress + 0x47),
D_DST_BASE_ADDR_LOW(_m_startaddress + 0x48, _m_startaddress + 0x4b),
D_DST_BASE_ADDR_HIGH(_m_startaddress + 0x4c, _m_startaddress + 0x4f),
D_DST_LINE_STRIDE(_m_startaddress + 0x50, _m_startaddress + 0x53),
D_DST_SURFACE_STRIDE(_m_startaddress + 0x54, _m_startaddress + 0x57),
D_DP_BS_CFG(_m_startaddress + 0x58, _m_startaddress + 0x5b),
D_DP_BS_ALU_CFG(_m_startaddress + 0x5c, _m_startaddress + 0x5f),
D_DP_BS_ALU_SRC_VALUE(_m_startaddress + 0x60, _m_startaddress + 0x63),
D_DP_BS_MUL_CFG(_m_startaddress + 0x64, _m_startaddress + 0x67),
D_DP_BS_MUL_SRC_VALUE(_m_startaddress + 0x68, _m_startaddress + 0x6b),
D_DP_BN_CFG(_m_startaddress + 0x6c, _m_startaddress + 0x6f),
D_DP_BN_ALU_CFG(_m_startaddress + 0x70, _m_startaddress + 0x73),
D_DP_BN_ALU_SRC_VALUE(_m_startaddress + 0x74, _m_startaddress + 0x77),
D_DP_BN_MUL_CFG(_m_startaddress + 0x78, _m_startaddress + 0x7b),
D_DP_BN_MUL_SRC_VALUE(_m_startaddress + 0x7c, _m_startaddress + 0x7f),
D_DP_EW_CFG(_m_startaddress + 0x80, _m_startaddress + 0x83),
D_DP_EW_ALU_CFG(_m_startaddress + 0x84, _m_startaddress + 0x87),
D_DP_EW_ALU_SRC_VALUE(_m_startaddress + 0x88, _m_startaddress + 0x8b),
D_DP_EW_ALU_CVT_OFFSET_VALUE(_m_startaddress + 0x8c, _m_startaddress + 0x8f),
D_DP_EW_ALU_CVT_SCALE_VALUE(_m_startaddress + 0x90, _m_startaddress + 0x93),
D_DP_EW_ALU_CVT_TRUNCATE_VALUE(_m_startaddress + 0x94, _m_startaddress + 0x97),
D_DP_EW_MUL_CFG(_m_startaddress + 0x98, _m_startaddress + 0x9b),
D_DP_EW_MUL_SRC_VALUE(_m_startaddress + 0x9c, _m_startaddress + 0x9f),
D_DP_EW_MUL_CVT_OFFSET_VALUE(_m_startaddress + 0xa0, _m_startaddress + 0xa3),
D_DP_EW_MUL_CVT_SCALE_VALUE(_m_startaddress + 0xa4, _m_startaddress + 0xa7),
D_DP_EW_MUL_CVT_TRUNCATE_VALUE(_m_startaddress + 0xa8, _m_startaddress + 0xab),
D_DP_EW_TRUNCATE_VALUE(_m_startaddress + 0xac, _m_startaddress + 0xaf),
D_FEATURE_MODE_CFG(_m_startaddress + 0xb0, _m_startaddress + 0xb3),
D_DST_DMA_CFG(_m_startaddress + 0xb4, _m_startaddress + 0xb7),
D_DST_BATCH_STRIDE(_m_startaddress + 0xb8, _m_startaddress + 0xbb),
D_DATA_FORMAT(_m_startaddress + 0xbc, _m_startaddress + 0xbf),
D_CVT_OFFSET(_m_startaddress + 0xc0, _m_startaddress + 0xc3),
D_CVT_SCALE(_m_startaddress + 0xc4, _m_startaddress + 0xc7),
D_CVT_SHIFT(_m_startaddress + 0xc8, _m_startaddress + 0xcb),
D_STATUS(_m_startaddress + 0xcc, _m_startaddress + 0xcf),
D_STATUS_NAN_INPUT_NUM(_m_startaddress + 0xd0, _m_startaddress + 0xd3),
D_STATUS_INF_INPUT_NUM(_m_startaddress + 0xd4, _m_startaddress + 0xd7),
D_STATUS_NAN_OUTPUT_NUM(_m_startaddress + 0xd8, _m_startaddress + 0xdb),
D_PERF_ENABLE(_m_startaddress + 0xdc, _m_startaddress + 0xdf),
D_PERF_WDMA_WRITE_STALL(_m_startaddress + 0xe0, _m_startaddress + 0xe3),
D_PERF_LUT_UFLOW(_m_startaddress + 0xe4, _m_startaddress + 0xe7),
D_PERF_LUT_OFLOW(_m_startaddress + 0xe8, _m_startaddress + 0xeb),
D_PERF_OUT_SATURATION(_m_startaddress + 0xec, _m_startaddress + 0xef),
D_PERF_LUT_HYBRID(_m_startaddress + 0xf0, _m_startaddress + 0xf3),
D_PERF_LUT_LE_HIT(_m_startaddress + 0xf4, _m_startaddress + 0xf7),
D_PERF_LUT_LO_HIT(_m_startaddress + 0xf8, _m_startaddress + 0xfb) {
m_children.push_back(&S_STATUS);
m_children.push_back(&S_POINTER);
m_children.push_back(&S_LUT_ACCESS_CFG);
m_children.push_back(&S_LUT_ACCESS_DATA);
m_children.push_back(&S_LUT_CFG);
m_children.push_back(&S_LUT_INFO);
m_children.push_back(&S_LUT_LE_START);
m_children.push_back(&S_LUT_LE_END);
m_children.push_back(&S_LUT_LO_START);
m_children.push_back(&S_LUT_LO_END);
m_children.push_back(&S_LUT_LE_SLOPE_SCALE);
m_children.push_back(&S_LUT_LE_SLOPE_SHIFT);
m_children.push_back(&S_LUT_LO_SLOPE_SCALE);
m_children.push_back(&S_LUT_LO_SLOPE_SHIFT);
m_children.push_back(&D_OP_ENABLE);
m_children.push_back(&D_DATA_CUBE_WIDTH);
m_children.push_back(&D_DATA_CUBE_HEIGHT);
m_children.push_back(&D_DATA_CUBE_CHANNEL);
m_children.push_back(&D_DST_BASE_ADDR_LOW);
m_children.push_back(&D_DST_BASE_ADDR_HIGH);
m_children.push_back(&D_DST_LINE_STRIDE);
m_children.push_back(&D_DST_SURFACE_STRIDE);
m_children.push_back(&D_DP_BS_CFG);
m_children.push_back(&D_DP_BS_ALU_CFG);
m_children.push_back(&D_DP_BS_ALU_SRC_VALUE);
m_children.push_back(&D_DP_BS_MUL_CFG);
m_children.push_back(&D_DP_BS_MUL_SRC_VALUE);
m_children.push_back(&D_DP_BN_CFG);
m_children.push_back(&D_DP_BN_ALU_CFG);
m_children.push_back(&D_DP_BN_ALU_SRC_VALUE);
m_children.push_back(&D_DP_BN_MUL_CFG);
m_children.push_back(&D_DP_BN_MUL_SRC_VALUE);
m_children.push_back(&D_DP_EW_CFG);
m_children.push_back(&D_DP_EW_ALU_CFG);
m_children.push_back(&D_DP_EW_ALU_SRC_VALUE);
m_children.push_back(&D_DP_EW_ALU_CVT_OFFSET_VALUE);
m_children.push_back(&D_DP_EW_ALU_CVT_SCALE_VALUE);
m_children.push_back(&D_DP_EW_ALU_CVT_TRUNCATE_VALUE);
m_children.push_back(&D_DP_EW_MUL_CFG);
m_children.push_back(&D_DP_EW_MUL_SRC_VALUE);
m_children.push_back(&D_DP_EW_MUL_CVT_OFFSET_VALUE);
m_children.push_back(&D_DP_EW_MUL_CVT_SCALE_VALUE);
m_children.push_back(&D_DP_EW_MUL_CVT_TRUNCATE_VALUE);
m_children.push_back(&D_DP_EW_TRUNCATE_VALUE);
m_children.push_back(&D_FEATURE_MODE_CFG);
m_children.push_back(&D_DST_DMA_CFG);
m_children.push_back(&D_DST_BATCH_STRIDE);
m_children.push_back(&D_DATA_FORMAT);
m_children.push_back(&D_CVT_OFFSET);
m_children.push_back(&D_CVT_SCALE);
m_children.push_back(&D_CVT_SHIFT);
m_children.push_back(&D_STATUS);
m_children.push_back(&D_STATUS_NAN_INPUT_NUM);
m_children.push_back(&D_STATUS_INF_INPUT_NUM);
m_children.push_back(&D_STATUS_NAN_OUTPUT_NUM);
m_children.push_back(&D_PERF_ENABLE);
m_children.push_back(&D_PERF_WDMA_WRITE_STALL);
m_children.push_back(&D_PERF_LUT_UFLOW);
m_children.push_back(&D_PERF_LUT_OFLOW);
m_children.push_back(&D_PERF_OUT_SATURATION);
m_children.push_back(&D_PERF_LUT_HYBRID);
m_children.push_back(&D_PERF_LUT_LE_HIT);
m_children.push_back(&D_PERF_LUT_LO_HIT);
}
void ordt_rset_NVDLA_SDP::update_child_ptrs() {
m_children.clear();
m_children.push_back(&S_STATUS);
m_children.push_back(&S_POINTER);
m_children.push_back(&S_LUT_ACCESS_CFG);
m_children.push_back(&S_LUT_ACCESS_DATA);
m_children.push_back(&S_LUT_CFG);
m_children.push_back(&S_LUT_INFO);
m_children.push_back(&S_LUT_LE_START);
m_children.push_back(&S_LUT_LE_END);
m_children.push_back(&S_LUT_LO_START);
m_children.push_back(&S_LUT_LO_END);
m_children.push_back(&S_LUT_LE_SLOPE_SCALE);
m_children.push_back(&S_LUT_LE_SLOPE_SHIFT);
m_children.push_back(&S_LUT_LO_SLOPE_SCALE);
m_children.push_back(&S_LUT_LO_SLOPE_SHIFT);
m_children.push_back(&D_OP_ENABLE);
m_children.push_back(&D_DATA_CUBE_WIDTH);
m_children.push_back(&D_DATA_CUBE_HEIGHT);
m_children.push_back(&D_DATA_CUBE_CHANNEL);
m_children.push_back(&D_DST_BASE_ADDR_LOW);
m_children.push_back(&D_DST_BASE_ADDR_HIGH);
m_children.push_back(&D_DST_LINE_STRIDE);
m_children.push_back(&D_DST_SURFACE_STRIDE);
m_children.push_back(&D_DP_BS_CFG);
m_children.push_back(&D_DP_BS_ALU_CFG);
m_children.push_back(&D_DP_BS_ALU_SRC_VALUE);
m_children.push_back(&D_DP_BS_MUL_CFG);
m_children.push_back(&D_DP_BS_MUL_SRC_VALUE);
m_children.push_back(&D_DP_BN_CFG);
m_children.push_back(&D_DP_BN_ALU_CFG);
m_children.push_back(&D_DP_BN_ALU_SRC_VALUE);
m_children.push_back(&D_DP_BN_MUL_CFG);
m_children.push_back(&D_DP_BN_MUL_SRC_VALUE);
m_children.push_back(&D_DP_EW_CFG);
m_children.push_back(&D_DP_EW_ALU_CFG);
m_children.push_back(&D_DP_EW_ALU_SRC_VALUE);
m_children.push_back(&D_DP_EW_ALU_CVT_OFFSET_VALUE);
m_children.push_back(&D_DP_EW_ALU_CVT_SCALE_VALUE);
m_children.push_back(&D_DP_EW_ALU_CVT_TRUNCATE_VALUE);
m_children.push_back(&D_DP_EW_MUL_CFG);
m_children.push_back(&D_DP_EW_MUL_SRC_VALUE);
m_children.push_back(&D_DP_EW_MUL_CVT_OFFSET_VALUE);
m_children.push_back(&D_DP_EW_MUL_CVT_SCALE_VALUE);
m_children.push_back(&D_DP_EW_MUL_CVT_TRUNCATE_VALUE);
m_children.push_back(&D_DP_EW_TRUNCATE_VALUE);
m_children.push_back(&D_FEATURE_MODE_CFG);
m_children.push_back(&D_DST_DMA_CFG);
m_children.push_back(&D_DST_BATCH_STRIDE);
m_children.push_back(&D_DATA_FORMAT);
m_children.push_back(&D_CVT_OFFSET);
m_children.push_back(&D_CVT_SCALE);
m_children.push_back(&D_CVT_SHIFT);
m_children.push_back(&D_STATUS);
m_children.push_back(&D_STATUS_NAN_INPUT_NUM);
m_children.push_back(&D_STATUS_INF_INPUT_NUM);
m_children.push_back(&D_STATUS_NAN_OUTPUT_NUM);
m_children.push_back(&D_PERF_ENABLE);
m_children.push_back(&D_PERF_WDMA_WRITE_STALL);
m_children.push_back(&D_PERF_LUT_UFLOW);
m_children.push_back(&D_PERF_LUT_OFLOW);
m_children.push_back(&D_PERF_OUT_SATURATION);
m_children.push_back(&D_PERF_LUT_HYBRID);
m_children.push_back(&D_PERF_LUT_LE_HIT);
m_children.push_back(&D_PERF_LUT_LO_HIT);
}
// ------------------ ordt_root methods ------------------
ordt_root::ordt_root()
: ordt_root(0x0, 0x90fb) {
}
ordt_root::ordt_root(uint64_t _m_startaddress, uint64_t _m_endaddress)
: ordt_regset(_m_startaddress, _m_endaddress),
NVDLA_SDP(_m_startaddress + 0x9000, _m_startaddress + 0x90ff) {
m_children.push_back(&NVDLA_SDP);
}
void ordt_root::update_child_ptrs() {
m_children.clear();
m_children.push_back(&NVDLA_SDP);
}
| [
"1978573841@qq.com"
] | 1978573841@qq.com |
392f74bfc3ecfb288f80c1f99d240049ed36abe8 | 6d87fb67073bca6f5fb1a01327a315243ba53564 | /adrians_solution/window.h | 32aa72b3b2ae8d6d8eee30dd368bacc602bbca9a | [] | no_license | Mondobot/Post_office | d49fab691ff16bd0f744d59e4359a4863f5e0474 | 4986488aad86a235315352b08bd0fe94061243c9 | refs/heads/master | 2021-01-22T08:58:59.140222 | 2013-03-24T23:01:52 | 2013-03-24T23:01:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,964 | h | #pragma once
#ifndef WINDOW_H
#define WINDOW_H
#include <iostream>
#include "person.h"
#include "queue.h"
#include "stack.h"
using namespace std;
class WindowStack {
private:
public:
int maxWeight;
int maxSize;
Stack<int> *stack;
int currWeight;
WindowStack(int q, int k) :
maxSize(q), maxWeight(k), currWeight(0) {
stack = new Stack<int>;
}
~WindowStack() {
delete stack;
}
void push(int x) {
if(stack->size() >= maxSize ||
currWeight + x > maxWeight)
emptyStack();
stack->push(x);
currWeight += x;
}
void pop() {
stack->pop();
}
void emptyStack() {
delete stack;
stack = new Stack<int>;
currWeight = 0;
}
// friend ostream& operator<<(ostream&, WindowStack&);
};
ostream& operator<<(ostream& out, WindowStack& ws) {
out << *(ws.stack);
return out;
}
class Window {
private:
public:
Queue<Person> *queue;
WindowStack *windowStack;
int minWeight;
int maxWeight;
Window(int minW, int maxW, int q, int k) :
minWeight(minW), maxWeight(maxW) {
queue = new Queue<Person>;
windowStack = new WindowStack(q, k);
}
~Window() {
delete queue;
delete windowStack;
}
void add(Person x) {
queue->enque(x);
}
void remove() {
queue->deque();
}
Person first() {
return queue->front();
}
void process() {
windowStack->push(first().getWeight());
remove();
}
WindowStack& getStack() {
return *windowStack;
}
Queue<Person>& getQueue() {
return *queue;
}
void emptyStack() {
windowStack->emptyStack();
}
bool acceptPackage() {
return (first().packageWeight >= minWeight &&
first().packageWeight <= maxWeight);
}
int length() {
return queue->queue->size;
}
};
#endif
| [
"bogatu.adrian@gmail.com"
] | bogatu.adrian@gmail.com |
e2aeb12381a8070356c110a99583d44e2b29fa4c | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/ui/dvd/driver/dvdpldrv/Common/EventSender.h | 0f6a65811782af8eeb5b21f5e055f2e0545c4fda | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,840 | h | ////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2000-2001 STMicroelectronics, Inc. All Rights Reserved. //
// HIGHLY CONFIDENTIAL INFORMATION: This source code contains //
// confidential and proprietary information of STMicroelectronics, Inc. //
// This source code is provided to Microsoft Corporation under a written //
// confidentiality agreement between STMicroelectronics and Microsoft. This //
// software may not be reproduced, distributed, modified, disclosed, used, //
// displayed, stored in a retrieval system or transmitted in whole or in part,//
// in any form or by any means, electronic, mechanical, photocopying or //
// otherwise, except as expressly authorized by STMicroelectronics. THE ONLY //
// PERSONS WHO MAY HAVE ACCESS TO THIS SOFTWARE ARE THOSE PERSONS //
// AUTHORIZED BY RAVISENT, WHO HAVE EXECUTED AND DELIVERED A //
// WRITTEN CONFIDENTIALITY AGREEMENT TO STMicroelectronics, IN THE FORM //
// PRESCRIBED BY STMicroelectronics. //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//
// Event Sender Class
//
////////////////////////////////////////////////////////////////////
#ifndef EVENTSENDER_H
#define EVENTSENDER_H
#include "DVDTime.h"
#include "EventDispatcher.h"
#include "library/common/krnlsync.h"
#include "library/common/vddebug.h"
class EventSender
{
protected:
EventDispatcher* pEventDispatcher;
public:
EventSender(EventDispatcher* pNewEventDispatcher);
virtual ~EventSender(void) {}
virtual Error SetEventHandler(DWORD event, DNEEventHandler handler, void * userData)
{
if (pEventDispatcher)
return pEventDispatcher->SetEventHandler(event, handler, userData);
else
GNRAISE(GNR_OBJECT_EMPTY);
}
BOOL EventHasHandler(DWORD event)
{
if (pEventDispatcher)
return pEventDispatcher->EventHasHandler(event);
else
GNRAISE(GNR_OBJECT_EMPTY);
}
Error SendEvent(DWORD event, DWORD info)
{
if (pEventDispatcher)
return pEventDispatcher->SendEvent(event, info);
else
GNRAISE(GNR_OBJECT_EMPTY);
}
void SetEventDispatcher(EventDispatcher* pNewEventDispatcher)
{
pEventDispatcher = pNewEventDispatcher;
}
EventDispatcher* GetEventDispatcher(){ return pEventDispatcher; }
};
#define GNREASSERT_EVENT(cond, event, info) { Error e; if (e = (cond)) { SendEvent(event, info); GNRAISE(e); } }
#endif
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
ed386a3aba21ee3c30a1df659804e07aa9a9e9c4 | 9253319c015bfb171d48c0805a64d2ac0fdaf208 | /src/ExternLibrary.cpp | dffab45bc675ca4215a8cf6d8464c47fd43e88ba | [] | no_license | iangodin/constructor | 5805bc088823f09d04999def69bd2eba4ef9c044 | 78a7e57b583db3cdb37fd5027647a0f80112c50e | refs/heads/master | 2021-01-18T09:47:30.709209 | 2016-06-14T15:36:33 | 2016-06-14T15:36:33 | 10,714,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,979 | cpp | //
// Copyright (c) 2016 Kimball Thurston
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#include "ExternLibrary.h"
#include "PackageSet.h"
#include "Debug.h"
#include <stdexcept>
////////////////////////////////////////
ExternLibrarySet::ExternLibrarySet( void )
: OptionalSource( "__extern_lib__" )
{
}
////////////////////////////////////////
ExternLibrarySet::~ExternLibrarySet( void )
{
}
////////////////////////////////////////
void
ExternLibrarySet::addExternRef( std::string l, std::string v )
{
myExternLibs.emplace_back( std::make_pair( std::move( l ), std::move( v ) ) );
}
////////////////////////////////////////
std::shared_ptr<BuildItem>
ExternLibrarySet::transform( TransformSet &xform ) const
{
std::shared_ptr<BuildItem> ret = xform.getTransform( this );
if ( ret )
return ret;
ret = std::make_shared<BuildItem>( getName(), getDir() );
ret->setUseName( false );
ret->setOutputDir( xform.getOutDir() );
if ( matches( xform ) )
{
DEBUG( "transform ENABLED ExternLibrary " << getName() );
std::set<std::string> tags;
bool ok = true;
std::vector<ItemPtr> extras;
PackageSet &ps = PackageSet::get( xform.getSystem() );
for ( auto &l: myExternLibs )
{
auto elib = ps.find( l.first, l.second, xform.getLibSearchPath(), xform.getPkgSearchPath() );
if ( ! elib )
{
WARNING( "Unable to find external library '" << l.first << "' (version: " << (l.second.empty()?std::string("<any>"):l.second) << ") for system " << xform.getSystem() );
ok = false;
}
else
extras.push_back( elib );
}
if ( ok )
{
if ( ! myDefinitions.empty() )
ret->setVariable( "defines", myDefinitions );
fillBuildItem( ret, xform, tags, true, extras );
}
else if ( isRequired() )
throw std::runtime_error( "Unable to resolve external libraries for required libraries" );
}
xform.recordTransform( this, ret );
return ret;
}
////////////////////////////////////////
| [
"kdt3rd@gmail.com"
] | kdt3rd@gmail.com |
2be360304ab750fd995b0c45c24b78e25cc5a3ef | 08369613577450af45fca5d68e11df03a0ed2999 | /library/modules/core/resource/source/resourcemanager.cpp | c5ee181e71bb383657647a389ab49f7571d66fc6 | [] | no_license | IreNox/tiki3 | 50e81a4a0dd120a37063f8cd6ea3045528350a5a | 2f29b3d7ab30217b3bd46d85ce8ec9032c1c1d54 | refs/heads/master | 2020-04-12T06:34:00.290425 | 2018-05-24T09:37:35 | 2018-05-24T09:37:35 | 12,142,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,233 | cpp |
#include "tiki/resource/resourcemanager.hpp"
#include "tiki/base/debugprop.hpp"
#include "tiki/base/fourcc.hpp"
#include "tiki/io/file.hpp"
#include "tiki/io/path.hpp"
#include "tiki/resource/factorybase.hpp"
#include "tiki/resource/resource.hpp"
#include "tiki/resource/resourcerequest.hpp"
#include "tiki/toollibraries/iassetconverter.hpp"
namespace tiki
{
TIKI_DEBUGPROP_BOOL( s_enableAssetConverterWatch, "EnableAssetConverterWatch", true );
ResourceManager::ResourceManager()
{
#if TIKI_ENABLED( TIKI_ENABLE_ASSET_CONVERTER )
m_pAssetConverter = nullptr;
#endif
}
ResourceManager::~ResourceManager()
{
}
bool ResourceManager::create( const ResourceManagerParameters& params )
{
m_resourceStorage.create( params.maxResourceCount );
m_resourceLoader.create( params.pFileSystem, &m_resourceStorage );
if ( !m_resourceRequests.create( params.maxRequestCount ) )
{
dispose();
return false;
}
m_loadingMutex.create();
if( params.enableMultiThreading )
{
if( !m_loadingThread.create( staticThreadEntry, this, 1024 * 1024, "ResourceManager" ) )
{
dispose();
return false;
}
}
#if TIKI_ENABLED( TIKI_ENABLE_ASSET_CONVERTER )
AssetConverterParamter converterParameters;
converterParameters.sourcePath = "../../../../../content";
converterParameters.outputPath = "../../../../../gamebuild";
converterParameters.forceRebuild = true;
m_pAssetConverter = createAssetConverter();
if ( !m_pAssetConverter->create( converterParameters ) )
{
dispose();
return false;
}
if ( s_enableAssetConverterWatch )
{
m_pAssetConverter->startWatch();
}
#endif
return true;
}
void ResourceManager::dispose()
{
#if TIKI_ENABLED( TIKI_ENABLE_ASSET_CONVERTER )
if ( m_pAssetConverter != nullptr )
{
if ( s_enableAssetConverterWatch )
{
m_pAssetConverter->stopWatch();
}
m_pAssetConverter->dispose();
disposeAssetConverter( m_pAssetConverter );
m_pAssetConverter = nullptr;
}
#endif
if( m_loadingThread.isCreated() )
{
m_loadingThread.requestExit();
m_loadingThread.waitForExit();
m_loadingThread.dispose();
}
m_loadingMutex.dispose();
m_resourceRequests.dispose();
m_resourceLoader.dispose();
m_resourceStorage.dispose();
}
void ResourceManager::update()
{
#if TIKI_ENABLED( TIKI_ENABLE_ASSET_CONVERTER )
if ( m_pAssetConverter != nullptr && s_enableAssetConverterWatch )
{
Array< string > files;
if ( m_pAssetConverter->getChangedFiles( files ) )
{
m_pAssetConverter->lockConversion();
for (uint i = 0u; i < files.getCount(); ++i)
{
const string& file = files[ i ];
const string fileName = path::getFilename( file );
const crc32 resourceKey = crcString( fileName );
Resource* pResource = nullptr;
m_resourceStorage.findResource( &pResource, resourceKey );
if ( pResource != nullptr )
{
const fourcc resourceType = pResource->getType();
const ResourceLoaderResult result = m_resourceLoader.reloadResource( pResource, resourceKey, resourceKey, resourceType );
traceResourceLoadResult( result, fileName.cStr(), resourceKey, resourceType );
}
}
m_pAssetConverter->unlockConversion();
files.dispose();
}
}
#endif
if( !m_loadingThread.isCreated() )
{
while( !m_runningRequests.isEmpty() )
{
ResourceRequest& data = *m_runningRequests.getBegin();
m_runningRequests.removeSortedByValue( data );
updateResourceLoading( &data );
}
}
}
void ResourceManager::registerResourceType( fourcc type, const FactoryContext& factoryContext )
{
m_resourceLoader.registerResourceType( type, factoryContext );
}
void ResourceManager::unregisterResourceType( fourcc type )
{
m_resourceLoader.unregisterResourceType( type );
}
void ResourceManager::unloadGenericResource( const Resource** ppResource )
{
TIKI_ASSERT( ppResource != nullptr );
if ( *ppResource == nullptr )
{
return;
}
m_resourceLoader.unloadResource( *ppResource, (*ppResource)->getType() );
*ppResource = nullptr;
}
void ResourceManager::endResourceLoading( const ResourceRequest& request )
{
TIKI_ASSERT( !request.isLoading() );
m_resourceRequests.removeUnsortedByValue( request );
}
const Resource* ResourceManager::loadGenericResource( const char* pFileName, fourcc type, crc32 resourceKey )
{
const ResourceRequest& request = beginGenericResourceLoading( pFileName, type, resourceKey );
while (request.isLoading())
{
update();
Thread::sleepCurrentThread( 250 );
}
const Resource* pResource = request.m_pResource;
endResourceLoading( request );
return pResource;
}
const ResourceRequest& ResourceManager::beginGenericResourceLoading( const char* pFileName, fourcc type, crc32 resourceKey )
{
TIKI_ASSERT( pFileName != nullptr );
const crc32 crcFileName = crcString( pFileName );
ResourceRequest& request = m_resourceRequests.push();
request.m_fileNameCrc = crcFileName;
request.m_resourceType = type;
request.m_resourceKey = resourceKey;
request.m_pResource = nullptr;
request.m_isLoading = true;
#if TIKI_DISABLED( TIKI_BUILD_MASTER )
request.m_pFileName = pFileName;
#endif
m_loadingMutex.lock();
m_runningRequests.push( request );
m_loadingMutex.unlock();
return request;
}
void ResourceManager::traceResourceLoadResult( ResourceLoaderResult result, const char* pFileName, crc32 resourceKey, fourcc resourceType )
{
switch ( result )
{
case ResourceLoaderResult_Success:
break;
case ResourceLoaderResult_CouldNotAccessFile:
TIKI_TRACE_ERROR( "[resourcemanager] Could not access File: %s\n", pFileName );
break;
case ResourceLoaderResult_CouldNotCreateResource:
TIKI_TRACE_ERROR( "[resourcemanager] Could not create Resource.\n" );
break;
case ResourceLoaderResult_CouldNotInitialize:
TIKI_TRACE_ERROR( "[resourcemanager] Could not initialize Resource.\n" );
break;
case ResourceLoaderResult_FileNotFound:
TIKI_TRACE_ERROR( "[resourcemanager] File not found: %s\n", pFileName );
break;
case ResourceLoaderResult_OutOfMemory:
TIKI_TRACE_ERROR( "[resourcemanager] Out of Memory.\n" );
break;
case ResourceLoaderResult_ResourceNotFound:
TIKI_TRACE_ERROR( "[resourcemanager] Resource not found: %u\n", resourceKey );
break;
case ResourceLoaderResult_UnknownError:
TIKI_TRACE_ERROR( "[resourcemanager] Unknown error.\n" );
break;
case ResourceLoaderResult_WrongFileFormat:
TIKI_TRACE_ERROR( "[resourcemanager] Wrong File format.\n" );
break;
case ResourceLoaderResult_WrongResourceType:
TIKI_TRACE_ERROR( "[resourcemanager] Wrong Resource type: %u\n", resourceType );
break;
default:
TIKI_BREAK( "Case not handle.\n" );
}
}
void ResourceManager::threadEntry( const Thread& thread )
{
while (!thread.isExitRequested())
{
ResourceRequest* pData = nullptr;
m_loadingMutex.lock();
if (!m_runningRequests.isEmpty())
{
pData = &*m_runningRequests.getBegin();
m_runningRequests.removeSortedByValue(*m_runningRequests.getBegin());
}
m_loadingMutex.unlock();
if ( pData == nullptr )
{
Thread::sleepCurrentThread( 500 );
continue;
}
updateResourceLoading( pData );
}
}
int ResourceManager::staticThreadEntry( const Thread& thread )
{
ResourceManager* pManager = (ResourceManager*)thread.getArgument();
pManager->threadEntry( thread );
return 0;
}
void ResourceManager::updateResourceLoading( ResourceRequest* pData )
{
ResourceRequest& request = *pData;
#if TIKI_ENABLED( TIKI_ENABLE_ASSET_CONVERTER )
if( s_enableAssetConverterWatch )
{
m_pAssetConverter->lockConversion();
}
#endif
const ResourceLoaderResult result = m_resourceLoader.loadResource( &request.m_pResource, request.m_fileNameCrc, request.m_resourceKey, request.m_resourceType, true );
const char* pFileName = (request.m_pResource != nullptr ? request.m_pResource->getFileName() : "");
traceResourceLoadResult( result, pFileName, request.m_fileNameCrc, request.m_resourceType );
#if TIKI_ENABLED( TIKI_ENABLE_ASSET_CONVERTER )
if( s_enableAssetConverterWatch )
{
m_pAssetConverter->unlockConversion();
}
#endif
request.m_isLoading = false;
}
} | [
"mail@timboden.de"
] | mail@timboden.de |
2b9d936142b7279c81463ab3f5d48d4c245846f7 | 483d5992960b195c255d2a3bed41bae11744e0ec | /洛谷/P1948.cpp | 16643be938a0e3ac3d8f5a5cea96167c8d01807d | [] | no_license | zcy05331/code-backup | bd2627f461b69778f56b7ef74441802df2f84a58 | 9ef0dd11108a3fe11364266755a84467c64ba099 | refs/heads/master | 2022-04-30T16:30:28.877120 | 2022-04-15T12:27:25 | 2022-04-15T12:27:25 | 241,646,316 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,939 | cpp | #include <bits/stdc++.h>
#define R register
#define ll long long
#define cmax(a, b) ((a < b) ? b : a)
#define cmin(a, b) ((a < b) ? a : b)
#define sum(a, b, mod) ((a + b) % mod)
const int MaxN = 1e5 + 10, MaxM = 2e5 + 10;
struct edge
{
int to, next, dis;
};
struct node
{
int pos, dis;
};
edge e[MaxN];
int n, m, k, cnt;
int head[MaxN], dis[MaxN];
inline void add_edge(int u, int v, int d)
{
++cnt;
e[cnt].to = v;
e[cnt].dis = d;
e[cnt].next = head[u];
head[u] = cnt;
}
inline int read()
{
int x = 0;
char ch = getchar();
while (ch > '9' || ch < '0')
ch = getchar();
while (ch <= '9' && ch >= '0')
x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return x;
}
inline int check(int mid)
{
memset(dis, -1, sizeof(dis));
std::deque<node> q;
q.push_back((node){1, 0});
while (!q.empty())
{
node tmp = q.front();
int u = tmp.pos, d = tmp.dis;
q.pop_front();
if (dis[u] == -1 || (dis[u] != -1 && dis[u] > d))
dis[u] = d;
for (int i = head[u]; i; i = e[i].next)
{
int v = e[i].to, c = 0;
if (~dis[v])
continue;
if (e[i].dis > mid)
c = 1;
if (c)
q.push_back((node){v, d + 1});
else
q.push_front((node){v, d});
}
}
if (dis[n] == -1 || dis[n] > k)
return 0;
return 1;
}
int main()
{
int l = 0, r = 1, tmp;
n = read(), m = read(), k = read();
for (int i = 1; i <= m; i++)
{
int u = read(), v = read(), d = read();
add_edge(u, v, d);
add_edge(v, u, d);
r = cmax(r, d);
}
++r, tmp = r;
while (l < r)
{
int mid = (l + r) >> 1;
if (check(mid))
r = mid;
else
l = mid + 1;
}
printf("%d\n", (r == tmp) ? -1 : l);
return 0;
}
| [
"little_sun0331@qq.com"
] | little_sun0331@qq.com |
dc722e450d1ec2ced80ff3adee54c322d517f873 | cb7ac15343e3b38303334f060cf658e87946c951 | /source/runtime/CoreObject/Public/UObject/ErrorException.h | 1746dbc0e8d8279f8bd8ce8f59c8fe2df6e5903c | [] | no_license | 523793658/Air2.0 | ac07e33273454442936ce2174010ecd287888757 | 9e04d3729a9ce1ee214b58c2296188ec8bf69057 | refs/heads/master | 2021-11-10T16:08:51.077092 | 2021-11-04T13:11:59 | 2021-11-04T13:11:59 | 178,317,006 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "CoreUObjectConfig.h"
#if HACK_HEADER_GENERATOR
#include "Templates/IsValidVariadicFunctionArg.h"
#include "Templates/AndOrNot.h"
/**
* FError
* Set of functions for error reporting
**/
struct COREUOBJECT_API FError
{
/**
* Throws a printf-formatted exception as a const TCHAR*.
*/
template <typename... Types>
UE_NORETURN static void VARARGS Throwf(const TCHAR* Fmt, Types... Args)
{
static_assert(TAnd<TIsValidVariadicFunctionArg<Types>...>::Value, "Invalid argument(s) passed to FError::Throwf");
ThrowfImpl(Fmt, Args...);
}
private:
UE_NORETURN static void VARARGS ThrowfImpl(const TCHAR* Fmt, ...);
};
#endif
| [
"523793658@qq.com"
] | 523793658@qq.com |
d5983fc80f24ed7597eab0394975a650f4f26acf | cfedb89ec20c9e5b209a9a133f1e829f1dc4d5d2 | /code_blocks/test-olymptrade-api/main.cpp | 8146d84f077a74ba8e3aed4dfabf5aed1a354d04 | [
"MIT"
] | permissive | MAW445524/olymptrade-cpp-api | 6c7d0a0ce9bff80e32f67629f4bd560922619769 | 50b3b35d40e644ddcbc4565fa2fa6defd6c56dfd | refs/heads/master | 2023-02-21T03:50:34.855199 | 2021-01-15T00:34:34 | 2021-01-15T00:34:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,229 | cpp | #include <iostream>
#include "olymp-trade-api.hpp"
#include "xtime.hpp"
#include <fstream>
#include <dir.h>
#include <stdlib.h>
#define BUILD_VER 1.0
using json = nlohmann::json;
int main() {
std::cout << "start!" << std::endl;
for(uint32_t i = 0; i < 2; ++i) {
std::cout << "new connect" << std::endl;
olymp_trade::OlympTradeApi<> olymptrade(8080);
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
}
std::cout << "next" << std::endl << std::endl << std::endl;
olymp_trade::OlympTradeApi<> olymptrade(8080);
/* ждем получения настроек */
if(!olymptrade.wait()) return -1;
/* тестируем работу uuid */
std::cout << "uuid: " << olymptrade.get_test_uuid() << std::endl;
std::cout << "account_id_real: " << olymptrade.get_account_id_real() << std::endl;
std::cout << "is_demo: " << olymptrade.demo_account() << std::endl;
/* получаем массив символов */
std::cout << "symbols: " << olymptrade.get_symbol_list().size() << std::endl;
olymptrade.set_demo_account(false);
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << "set_real, d: " << olymptrade.demo_account() << " b: " << olymptrade.get_balance() << std::endl;
olymptrade.set_demo_account(true);
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << "set_demo, d: " << olymptrade.demo_account() << " b: " << olymptrade.get_balance() << std::endl;
int err = olymptrade.open_bo("ETHUSD", 30.0, olymp_trade::BUY, 60,
[&](const olymp_trade::Bet &bet) {
if(bet.bet_status == olymp_trade::BetStatus::UNKNOWN_STATE) {
std::cout << "UNKNOWN_STATE" << std::endl;
} else
if(bet.bet_status == olymp_trade::BetStatus::OPENING_ERROR) {
std::cout << "OPENING_ERROR" << std::endl;
} else
if(bet.bet_status == olymp_trade::BetStatus::WAITING_COMPLETION) {
std::cout << "WAITING_COMPLETION" << std::endl;
} else
if(bet.bet_status == olymp_trade::BetStatus::CHECK_ERROR) {
std::cout << "CHECK_ERROR" << std::endl;
} else
if(bet.bet_status == olymp_trade::BetStatus::WIN) {
std::cout << "WIN" << std::endl;
} else
if(bet.bet_status == olymp_trade::BetStatus::LOSS) {
std::cout << "LOSS" << std::endl;
}
});
if(err != olymp_trade::OK) std::cout << err << std::endl;
/* подпишемся на поток */
std::vector<std::string> symbol_list = {"LTCUSD", "Bitcoin", "ZECUSD"};
olymptrade.subscribe_quotes_stream(symbol_list, 60);
xtime::timestamp_t min_timestamp = olymptrade.get_min_timestamp_symbol("Bitcoin");
std::cout << "Bitcoin min date: " << xtime::get_str_date(min_timestamp) << std::endl;
std::vector<olymp_trade::Candle> candles;
int err_candles = olymptrade.get_historical_data(
"LTCUSD",
xtime::get_timestamp(16,2,2018,0,0,0),
xtime::get_timestamp(16,2,2018,23,59,0),
xtime::SECONDS_IN_MINUTE,
candles);
if(err_candles == olymp_trade::OK) {
for(size_t i = 0; i < candles.size(); ++i) {
std::cout << "hist Bitcoin: "
<< xtime::get_str_date_time(candles[i].timestamp)
<< " c: " << candles[i].close << std::endl;
}
std::cout << "hist candles.size(): " << candles.size() << std::endl;
} else {
std::cout << "err_candles: " << err_candles << std::endl;
}
/* выводим поток котировок */
while(true) {
olymp_trade::Candle candle = olymptrade.get_candle("LTCUSD");
std::cout << "LTCUSD, p: " << olymptrade.get_payout("LTCUSD") << " c: " << candle.close << " t: " << candle.timestamp << std::endl;
std::cout
<< "d: " << olymptrade.demo_account()
<< " b: " << olymptrade.get_balance()
<< " server time: " << xtime::get_str_date_time_ms(olymptrade.get_server_timestamp())
<< std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}
| [
"elektroyar@yandex.ru"
] | elektroyar@yandex.ru |
9e16908579f5f54dee08166d6a6a3a900986bf0f | b30d1af894a9e144ccf510ebaf75af085bf40b9f | /src/umm-solo5.cc | cb900f2daa4e99d8589973dfd743b75ab3b031bb | [] | no_license | SESA/Umm | 834e46d6f7744f83b9e06fc118ae4b7d74417d38 | f9ddee86275e6961856e118d2fc5c3cb41573a9b | refs/heads/master | 2020-03-22T02:18:28.154507 | 2019-04-29T17:16:52 | 2019-04-29T17:16:52 | 139,362,642 | 6 | 1 | null | 2018-08-29T17:05:05 | 2018-07-01T21:14:57 | C++ | UTF-8 | C++ | false | false | 2,511 | cc |
#include "umm-solo5.h"
#include "UmProxy.h"
#include "umm-internal.h"
/*
* Block until timeout_nsecs have passed or I/O is
* possible, whichever is sooner. Returns 1 if I/O is possible, otherwise 0.
*/
void solo5_hypercall_poll(volatile void *arg) {
auto arg_ = (volatile struct ukvm_poll *)arg;
arg_->ret = 0;
// First check if we have data
if (umm::manager->ActiveInstance()->HasData()) {
arg_->ret = 1;
return;
}
// if (arg_->timeout_nsecs > 500000) {
// umm::manager->Block(500000);
// }else{
umm::manager->Block(arg_->timeout_nsecs);
// }
// return from block
if (umm::manager->ActiveInstance()->HasData()) {
arg_->ret = 1;
}
}
void solo5_hypercall_netinfo(volatile void *arg) {
auto arg_ = (volatile struct ukvm_netinfo *)arg;
auto ma = umm::UmProxy::client_internal_macaddr();
arg_->mac_address[0] = ma[0];
arg_->mac_address[1] = ma[1];
arg_->mac_address[2] = ma[2];
arg_->mac_address[3] = ma[3];
arg_->mac_address[4] = ma[4];
arg_->mac_address[5] = ma[5];
}
/* UKVM_HYPERCALL_NETWRITE
struct ukvm_netwrite {
//IN
UKVM_GUEST_PTR(const void *) data;
size_t len;
//OUT
int ret; // amount written
}; */
void solo5_hypercall_netwrite(volatile void *arg) {
auto arg_ = (volatile struct ukvm_netwrite *)arg;
arg_->ret = arg_->len; // confirm the full amount will be sent
void *buf = malloc(arg_->len);
memcpy((void *)buf, arg_->data, arg_->len);
unsigned long len = arg_->len;
// Spawn of outgoing write on new event
ebbrt::event_manager->SpawnLocal(
[buf, len]() {
umm::proxy->ProcessOutgoing(umm::UmProxy::raw_to_iobuf(buf, len));
},
true);
}
/* UKVM_HYPERCALL_NETREAD
struct ukvm_netread {
// IN
UKVM_GUEST_PTR(void *) data;
// IN/OUT
size_t len; // amount read
// OUT
int ret; // 0=OK
}; */
void solo5_hypercall_netread(volatile void *arg) {
auto arg_ = (volatile struct ukvm_netread *)arg;
if (umm::manager->ActiveInstance()->HasData()) {
auto buf = umm::manager->ActiveInstance()->ReadPacket(arg_->len);
kbugon(!buf);
auto buflen = buf->ComputeChainDataLength();
kprintf("solo5 netread len=%d\n", arg_->len);
kbugon(buflen > arg_->len);
auto dp = buf->GetDataPointer();
dp.GetNoAdvance(buflen,
static_cast<uint8_t *>(arg_->data)); // This does a memcpy
arg_->len = buflen;
// arg_->ret is 0 on successful read, 1 otherwise
arg_->ret = 0;
} else {
arg_->ret = 1;
}
return;
}
| [
"jmcadden@bu.edu"
] | jmcadden@bu.edu |
c603215df8fcf4543efeb4915973078800a615ea | 1e32ad208d1442f5a663f3e651c750954dbbdd7f | /Pathfinding/Graph.h | f699fbd7b806b416368ddfe0dc33a95fb7a1c053 | [] | no_license | Aaron0Neill/aStar-Pathfinding | c74e44fe2a129796057e4aa3e67660db6937c804 | 0b523f0496011abcec04396e2c27f5e6f687655d | refs/heads/master | 2023-03-09T15:20:39.757591 | 2021-02-24T21:29:21 | 2021-02-24T21:29:21 | 342,038,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,545 | h | #ifndef GRAPH_H
#define GRAPH_H
#include <list>
#include <queue>
#include <vector>
#include <functional>
#include <stack>
#include "Comparer.h"
template <class NodeType, class ArcType> class GraphArc;
template <class NodeType, class ArcType> class GraphNode;
// ---------------------------------------------------------------------
// Name: Graph
// Description: Manages the nodes and connections (arc) between them
// ---------------------------------------------------------------------
template<class NodeType, class ArcType>
class Graph
{
public:
// typedef the classes to make our lives easier.
typedef GraphArc<NodeType, ArcType> Arc;
typedef GraphNode<NodeType, ArcType> Node;
// Constructor and destructor functions
Graph( int size );
~Graph();
// Accessors
Node * nodeIndex(int index) const
{
return m_nodes.at(index);
}
// Public member functions.
bool addNode( NodeType data, int index );
void removeNode( int index );
bool addArc( int from, int to, ArcType weight );
void removeArc( int from, int to );
Arc* getArc( int from, int to );
void clearMarks();
void depthFirst( Node* node, std::function<void(Node *)> f_visit);
void breadthFirst( Node* node, std::function<void(Node *)> f_visit);
void adaptedBreadthFirst( Node* current, Node* goal );
void ucs(Node* start, Node* dest, std::function<void(Node*)> f_visit, std::vector<Node*>& path);
void aStar(Node* start, Node* dest, std::function<void(Node*)> f_visit, std::vector<Node*>& path);
private:
// ----------------------------------------------------------------
// Description: A container of all the nodes in the graph.
// ----------------------------------------------------------------
std::vector<Node*> m_nodes;
};
// ----------------------------------------------------------------
// Name: Graph
// Description: Constructor, this constructs an empty graph
// Arguments: The maximum number of nodes.
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
Graph<NodeType, ArcType>::Graph( int maxNodes ) : m_nodes( maxNodes, nullptr)
{
}
// ----------------------------------------------------------------
// Name: ~Graph
// Description: destructor, This deletes every node
// Arguments: None.
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
Graph<NodeType, ArcType>::~Graph() {
for( int index = 0; index < m_nodes.size(); index++ )
{
if( m_nodes[index] != nullptr )
{
delete m_nodes.at(index);
}
}
}
// ----------------------------------------------------------------
// Name: addNode
// Description: This adds a node at a given index in the graph.
// Arguments: The first parameter is the data to store in the node.
// The second parameter is the index to store the node.
// Return Value: true if successful
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
bool Graph<NodeType, ArcType>::addNode( NodeType data, int index )
{
bool nodeNotPresent = false;
// find out if a node does not exist at that index.
if ( nullptr == m_nodes.at(index) )
{
nodeNotPresent = true;
// create a new node, put the data in it, and unmark it.
m_nodes.at(index) = new Node;
m_nodes.at(index)->m_data = data;
m_nodes.at(index)->setMarked(false);
}
return nodeNotPresent;
}
// ----------------------------------------------------------------
// Name: removeNode
// Description: This removes a node from the graph
// Arguments: The index of the node to return.
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
void Graph<NodeType, ArcType>::removeNode( int index )
{
// Only proceed if node does exist.
if( nullptr != m_nodes.at(index) )
{
// now find every arc that points to the node that
// is being removed and remove it.
Arc* arc;
// loop through every node
for( int node = 0; node < m_nodes.size(); node++ )
{
// if the node is valid...
if( nullptr != m_nodes.at(node) ) {
// see if the node has an arc pointing to the current node.
arc = m_nodes.at(node)->getArc(m_nodes.at(index) );
}
// if it has an arc pointing to the current node, then
// remove the arc.
if( arc != 0 ) {
removeArc( node, index );
}
}
// now that every arc pointing to the current node has been removed,
// the node can be deleted.
delete m_nodes.at(index);
m_nodes.at(index) = nullptr;
}
}
// ----------------------------------------------------------------
// Name: addArd
// Description: Adds an arc from the first index to the
// second index with the specified weight.
// Arguments: The first argument is the originating node index
// The second argument is the ending node index
// The third argument is the weight of the arc
// Return Value: true on success.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
bool Graph<NodeType, ArcType>::addArc( int from, int to, ArcType weight )
{
bool proceed = true;
// make sure both nodes exist.
if( nullptr == m_nodes.at(from) || nullptr == m_nodes.at(to) )
{
proceed = false;
}
// if an arc already exists we should not proceed
if( m_nodes.at(from)->getArc( m_nodes.at(to) ) != nullptr )
{
proceed = false;
}
if (proceed == true)
{
// add the arc to the "from" node.
m_nodes.at(from)->addArc(m_nodes.at(to), weight );
}
return proceed;
}
// ----------------------------------------------------------------
// Name: removeArc
// Description: This removes the arc from the first index to the second index
// Arguments: The first parameter is the originating node index.
// The second parameter is the ending node index.
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
void Graph<NodeType, ArcType>::removeArc( int from, int to )
{
// Make sure that the node exists before trying to remove
// an arc from it.
bool nodeExists = true;
if( nullptr == m_nodes.at(from) || nullptr == m_nodes.at(to) )
{
nodeExists = false;
}
if (nodeExists == true)
{
// remove the arc.
m_nodes.at(from)->removeArc(m_nodes.at(to) );
}
}
// ----------------------------------------------------------------
// Name: getArc
// Description: Gets a pointer to an arc from the first index
// to the second index.
// Arguments: The first parameter is the originating node index.
// The second parameter is the ending node index.
// Return Value: pointer to the arc, or 0 if it doesn't exist.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
GraphArc<NodeType, ArcType>* Graph<NodeType, ArcType>::getArc( int from, int to )
{
Arc* arc = 0;
// make sure the to and from nodes exist
if( nullptr != m_nodes.at(from) && nullptr != m_nodes.at(to) )
{
arc = m_nodes.at(from)->getArc(m_nodes.at(to) );
}
return arc;
}
// ----------------------------------------------------------------
// Name: clearMarks
// Description: This clears every mark on every node.
// Arguments: None.
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
void Graph<NodeType, ArcType>::clearMarks()
{
for( int index = 0; index < m_nodes.size(); index++ )
{
if( nullptr != m_nodes.at(index) )
{
m_nodes.at(index)->setMarked(false);
}
}
}
// ----------------------------------------------------------------
// Name: depthFirst
// Description: Performs a depth-first traversal on the specified
// node.
// Arguments: The first argument is the starting node
// The second argument is the processing function.
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
void Graph<NodeType, ArcType>::depthFirst( Node* node, std::function<void(Node *)> f_visit )
{
if( nullptr != node ) {
// process the current node and mark it
f_visit( node );
node->setMarked(true);
// go through each connecting node
auto iter = node->arcList().begin();
auto endIter = node->arcList().end();
for( ; iter != endIter; ++iter)
{
// process the linked node if it isn't already marked.
if ( (*iter).node()->marked() == false )
{
depthFirst( (*iter).node(), f_visit);
}
}
}
}
// ----------------------------------------------------------------
// Name: breadthFirst
// Description: Performs a depth-first traversal the starting node
// specified as an input parameter.
// Arguments: The first parameter is the starting node
// The second parameter is the processing function.
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
void Graph<NodeType, ArcType>::breadthFirst( Node* node, std::function<void(Node *)> f_visit)
{
if( nullptr != node )
{
std::queue<Node*> nodeQueue;
// place the first node on the queue, and mark it.
nodeQueue.push( node );
node->setMarked(true);
// loop through the queue while there are nodes in it.
while( nodeQueue.size() != 0 )
{
// process the node at the front of the queue.
f_visit( nodeQueue.front() );
// add all of the child nodes that have not been
// marked into the queue
auto iter = nodeQueue.front()->arcList().begin();
auto endIter = nodeQueue.front()->arcList().end();
for( ; iter != endIter; iter++ )
{
if ( (*iter).node()->marked() == false)
{
// mark the node and add it to the queue.
(*iter).node()->setMarked(true);
nodeQueue.push( (*iter).node() );
}
}
// dequeue the current node.
nodeQueue.pop();
}
}
}
// ----------------------------------------------------------------
// Name: adaptedBreadthFirst
// Description: Performs a breadth-first traversal the starting node
// specified as an input parameter, terminating at the goal.
// Arguments: The first parameter is the starting node.
// The second parameter is the goal node.
// Return Value: None.
// ----------------------------------------------------------------
// * Design and logic was made with the help of:
// Ben Millar - https://github.com/ben-millar *
template<class NodeType, class ArcType>
void Graph<NodeType, ArcType>::adaptedBreadthFirst( Node* current, Node *goal )
{
if (nullptr != current && nullptr != goal)
{
std::queue<Node*> nodes;
nodes.push(current);
current->setMarked(true);
while (!nodes.empty())
{
for (auto arcs : nodes.front()->arcList())
{ // loop through all the lists
if (arcs.node()->marked() == false)
{ // only check unmarked nodes
nodes.push(arcs.node());
nodes.back()->setMarked(true);
nodes.back()->setPrevious(nodes.front());
if (goal == nodes.back())
{//early exit
return;
}
}
}
nodes.pop();
}
}
}
// ----------------------------------------------------------------
// Name: UCS
// Description: Searches through the graph in order to find a path
// Arguments: The first is where the search should start
// The second is the node you are looking for
// The third is a function pointer to the output what node has been visited
// The fourth is the vector that will record the path between the vectors
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
void Graph<NodeType, ArcType>::ucs(Node* start, Node* dest, std::function<void(Node*)> f_visit, std::vector<Node*>& path)
{
for (auto node : m_nodes)
{ // reset the heuristic for all the nodes
node->m_data.m_localDistance = std::numeric_limits<int>::max();
}
std::priority_queue < Node*, std::vector<Node*>, Comparer<Node>> priorQueue; // create the priority queue using a comparer class
start->setPrevious(nullptr); //set the start to point to null so there is a clear stop point
start->m_data.m_localDistance = 0; // set the heuristic as its the start
priorQueue.push(start);
start->setMarked(true);
while (!priorQueue.empty())
{ // constantly loop until the destination is found or all nodes have been checked
for (auto arc : priorQueue.top()->arcList())
{
if (!arc.node()->marked())
{
arc.node()->setMarked(true);
arc.node()->setPrevious(priorQueue.top());
arc.node()->m_data.m_localDistance = priorQueue.top()->m_data.m_localDistance + arc.weight();
priorQueue.push(arc.node());
}
else if(arc.node()->m_data.m_localDistance > priorQueue.top()->m_data.m_localDistance + arc.weight())
{
arc.node()->setPrevious(priorQueue.top());
arc.node()->m_data.m_localDistance = priorQueue.top()->m_data.m_localDistance + arc.weight();
}
if (dest == priorQueue.top())
{
Node* current = priorQueue.top();
while (current != nullptr)
{
path.push_back(current);
current = current->previous();
}
return;
}
}
priorQueue.pop();
}
}
// ----------------------------------------------------------------
// Name: A Star
// Description: Searches through the graph in order to find the shortest path between two points
// Arguments: The first is where the search should start
// The second is the node you are looking for
// The third is a function pointer to the output what node has been visited
// The fourth is the vector that will record the path between the vectors
// Return Value: None.
// ----------------------------------------------------------------
template<class NodeType, class ArcType>
inline void Graph<NodeType, ArcType>::aStar(Node* start, Node* dest, std::function<void(Node*)> f_visit, std::vector<Node*>& path)
{
//lambda distance
auto getDistanceToGoal = [&](Node* current, Node* goal) { return sqrt(pow(goal->m_data.m_location.first - current->m_data.m_location.first, 2) + pow(goal->m_data.m_location.second - current->m_data.m_location.second, 2)); };
// reset all the nodes local and global goals
for (auto node : m_nodes)
{
node->m_data.m_localDistance = std::numeric_limits<int>::max();
node->m_data.m_heuristic = getDistanceToGoal(node, dest);//update the global distance
node->setMarked(false);
node->setPrevious(nullptr);
}
std::priority_queue<Node*, std::vector<Node*>, Comparer<Node>> priorQueue;
//initial setup
start->setMarked(true);
start->m_data.m_localDistance = 0;
priorQueue.push(start);
while (!priorQueue.empty() && dest != priorQueue.top())
{
Node* current = priorQueue.top();
priorQueue.pop();
f_visit(current);
for (auto arc : current->arcList())
{
if (!arc.node()->m_data.m_obstacle)
{ // do nothing if the node is an obstacle
float distance = current->m_data.m_localDistance + arc.weight(); // get the local distance
if (distance < arc.node()->m_data.m_localDistance)
{ // update the parent node and local distance if its shorter than the current local
arc.node()->setPrevious(current); // set the parent
arc.node()->m_data.m_localDistance = distance;
}
if (!arc.node()->marked())
{ // if the node hasnt been marked
arc.node()->setMarked(true); // mark the node
priorQueue.push(arc.node()); // add it to the list
}
}
}
}
Node* current = dest;
std::stack<Node*> invertPath;
while (current != nullptr)
{
invertPath.push(current);
current = current->previous();
}
while (!invertPath.empty())
{
path.push_back(invertPath.top());
invertPath.pop();
}
}
#include "GraphNode.h"
#include "GraphArc.h"
#endif
| [
"c00241596@itcarlow.ie"
] | c00241596@itcarlow.ie |
a858ffefeba772f776b6429f4fea8d28c06fb3f0 | bdb8930cb5849b38bf576800d642d1cda3440d69 | /lib/inherited/IComparable/example.cpp | a22b022e2f718871c067c575299d55c064f54b73 | [] | no_license | pohuing/CppPl | 4aa01ec452cdbf1ec6454475d5b04c5e2e45218d | decce2dc67510a0250333e204504d8a83366857e | refs/heads/master | 2022-11-22T04:36:12.394688 | 2020-07-28T17:35:09 | 2020-07-28T17:35:09 | 268,794,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | cpp | #include <iostream>
#include "IComparable.h"
#include "Point.h"
#include <cmath>
class Point3D : public Point{
public:
Point3D(int x, int y, int z)
: Point(x,y), m_z(z){}
double get_dist() const override{
return sqrt(m_x * m_x + m_y * m_y + m_z * m_z);
}
std::string to_string() const override {
return "(" + std::to_string(m_x) + " " + std::to_string(m_y) + " " + std::to_string(m_z) + ")";
}
int get_z() const {
return m_z;
}
private:
int m_z;
};
void print_all(ComparableCollection& collection){
for(auto& a : collection){
std::cout << ((Point*)(a.get()))->get_dist() << " " << ((Point*)(a.get()))->to_string() << "\n";
}
}
int main(){
auto collection = ComparableCollection();
collection.push_back(std::make_unique<Point>(1,1));
collection.push_back(std::make_unique<Point>(0,0));
print_all(collection);
collection.sort();
print_all(collection);
collection.push_back(std::make_unique<Point3D>(0,0,1));
collection.sort();
print_all(collection);
} | [
"24683548+pohuing@users.noreply.github.com"
] | 24683548+pohuing@users.noreply.github.com |
d72a1d061fc9a7ddeb532796e4c1c17cd4e6a1b0 | caefe2a5f40db81359faf868ed0be8e93c11ec70 | /Image.hpp | 38e43c9df7892670ec7e7b0e676c33603c4a4fef | [] | no_license | PepcyCh/simple-JPEG-IO | ea1b99b7a6da344132faf03ef3aa35b92deaad1e | fe824251ead8dfa65d4fcf5bbd183d0625718d3e | refs/heads/master | 2020-08-31T09:05:11.302359 | 2019-10-31T04:23:25 | 2019-10-31T04:23:25 | 218,655,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | hpp | #pragma once
#include <cstdlib>
#include <vector>
class Image {
public:
Image(size_t width, size_t height);
~Image();
Image(const Image& rhs);
Image& operator=(const Image& rhs);
bool empty() const;
void resize(size_t width, size_t height);
size_t getWidth() const;
size_t getHeight() const;
uint8_t get(int x, int y, int i) const;
uint8_t getR(int x, int y) const;
uint8_t getG(int x, int y) const;
uint8_t getB(int x, int y) const;
uint8_t getA(int x, int y) const;
void setColor(int x, int y, int i, uint8_t v);
void setColor(int x, int y, uint8_t r, uint8_t g, uint8_t b);
void setColor(int x, int y, uint8_t r, uint8_t g, uint8_t b, uint8_t a);
private:
size_t width;
size_t height;
std::vector<uint8_t> data;
};
| [
"pepsich86@163.com"
] | pepsich86@163.com |
071fe4eed28d19e5c556630ff267411e0ed6ad16 | 9f9645d7537f042329dc92d38b2ce8f4c8c41b2b | /Platform_io/oc_pc817_4sw/src/OC.h | 9cc3016d3ec4d5221b0072adaceaa4a37b14a039 | [] | no_license | 23DesignStudio/semi | 29cc94c5d11086b4a6cc48742ac5b2dd9200382c | a47adf800cd8df20991b5a53a058a1167a7eaca2 | refs/heads/master | 2022-12-12T00:13:33.161488 | 2020-04-30T03:30:47 | 2020-04-30T03:30:47 | 193,816,687 | 0 | 0 | null | 2022-12-10T21:50:39 | 2019-06-26T02:40:33 | C++ | UTF-8 | C++ | false | false | 589 | h |
#ifndef OC_H
#define OC_H
#include <Arduino.h>
class OC
{
public:
OC();
~OC();
void setup(byte pin, char key); // define arduino output pin and trigger letter sent from Unity
bool getState(); // get oc state
char getKey(); // get letter defined by Unity
bool check(unsigned long timer, unsigned long &step); // check if time of oc state set to true last longer than step
bool turnOn(unsigned long timer); // set output LOW to turn oc on
bool turnOff();// set output HIGH to turn oc off
private:
byte _pin;
bool _state;
unsigned long _timer;
char _key;
};
#endif
| [
"23design.dev@gmail.com"
] | 23design.dev@gmail.com |
2a55aa9470d4779285ce1bbbade08741023dfa80 | e8e696a23451b92d2788b55a10aa6e955ffa563b | /Problem/01-4/SimpleFunc.cpp | bb81adf85050ca7586ee543327492b6fd689f95a | [] | no_license | roytravel/passion-cpp | 32c81e517fa6c573bc9d16e4bca2b0d98df9077c | a84c0f5b736e182a74f60834eae7e4fc43333af8 | refs/heads/master | 2022-04-16T15:21:18.197877 | 2020-03-16T15:26:11 | 2020-03-16T15:26:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 240 | cpp | #include <iostream>
#include "SimpleFunc.h"
void BestComImpl::SimpleFunc(void)
{
std::cout << "BestCom이 정의한 함수" << std::endl;
}
void ProgComImpl::SimpleFunc(void)
{
std::cout << "ProgCom이 정의한 함수" << std::endl;
}
| [
"roytravel97@gmail.com"
] | roytravel97@gmail.com |
505ad40278aa099d96950cbdc04a4a217594235c | a1d02f65abfd25f9d260ab2b41bee082df669907 | /src/ringct/rctSigs.cpp | a1a5df86cc7c5abb1afde8507ec34274d3e0501e | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | kosowwwa/TroutBucks | 2bbf42d2631b1faff94fcac7eadf86e021490606 | 1e0d2f5446f434a078a40994ea526f1badc9be06 | refs/heads/main | 2023-04-14T13:27:30.514457 | 2021-04-25T14:56:05 | 2021-04-25T14:56:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 69,531 | cpp | // Copyright (c) 2016, Troutbucks Research Labs
//
// Author: Shen Noether <shen.noether@gmx.com>
//
// 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.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "misc_log_ex.h"
#include "misc_language.h"
#include "common/perf_timer.h"
#include "common/threadpool.h"
#include "common/util.h"
#include "rctSigs.h"
#include "bulletproofs.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "cryptonote_config.h"
using namespace crypto;
using namespace std;
#undef TROUTBUCKS_DEFAULT_LOG_CATEGORY
#define TROUTBUCKS_DEFAULT_LOG_CATEGORY "ringct"
#define CHECK_AND_ASSERT_MES_L1(expr, ret, message) {if(!(expr)) {MCERROR("verify", message); return ret;}}
namespace
{
rct::Bulletproof make_dummy_bulletproof(const std::vector<uint64_t> &outamounts, rct::keyV &C, rct::keyV &masks)
{
const size_t n_outs = outamounts.size();
const rct::key I = rct::identity();
size_t nrl = 0;
while ((1u << nrl) < n_outs)
++nrl;
nrl += 6;
C.resize(n_outs);
masks.resize(n_outs);
for (size_t i = 0; i < n_outs; ++i)
{
masks[i] = I;
rct::key sv8, sv;
sv = rct::zero();
sv.bytes[0] = outamounts[i] & 255;
sv.bytes[1] = (outamounts[i] >> 8) & 255;
sv.bytes[2] = (outamounts[i] >> 16) & 255;
sv.bytes[3] = (outamounts[i] >> 24) & 255;
sv.bytes[4] = (outamounts[i] >> 32) & 255;
sv.bytes[5] = (outamounts[i] >> 40) & 255;
sv.bytes[6] = (outamounts[i] >> 48) & 255;
sv.bytes[7] = (outamounts[i] >> 56) & 255;
sc_mul(sv8.bytes, sv.bytes, rct::INV_EIGHT.bytes);
rct::addKeys2(C[i], rct::INV_EIGHT, sv8, rct::H);
}
return rct::Bulletproof{rct::keyV(n_outs, I), I, I, I, I, I, I, rct::keyV(nrl, I), rct::keyV(nrl, I), I, I, I};
}
}
namespace rct {
Bulletproof proveRangeBulletproof(keyV &C, keyV &masks, const std::vector<uint64_t> &amounts, epee::span<const key> sk, hw::device &hwdev)
{
CHECK_AND_ASSERT_THROW_MES(amounts.size() == sk.size(), "Invalid amounts/sk sizes");
masks.resize(amounts.size());
for (size_t i = 0; i < masks.size(); ++i)
masks[i] = hwdev.genCommitmentMask(sk[i]);
Bulletproof proof = bulletproof_PROVE(amounts, masks);
CHECK_AND_ASSERT_THROW_MES(proof.V.size() == amounts.size(), "V does not have the expected size");
C = proof.V;
return proof;
}
bool verBulletproof(const Bulletproof &proof)
{
try { return bulletproof_VERIFY(proof); }
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
bool verBulletproof(const std::vector<const Bulletproof*> &proofs)
{
try { return bulletproof_VERIFY(proofs); }
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
//Borromean (c.f. gmax/andytoshi's paper)
boroSig genBorromean(const key64 x, const key64 P1, const key64 P2, const bits indices) {
key64 L[2], alpha;
auto wiper = epee::misc_utils::create_scope_leave_handler([&](){memwipe(alpha, sizeof(alpha));});
key c;
int naught = 0, prime = 0, ii = 0, jj=0;
boroSig bb;
for (ii = 0 ; ii < 64 ; ii++) {
naught = indices[ii]; prime = (indices[ii] + 1) % 2;
skGen(alpha[ii]);
scalarmultBase(L[naught][ii], alpha[ii]);
if (naught == 0) {
skGen(bb.s1[ii]);
c = hash_to_scalar(L[naught][ii]);
addKeys2(L[prime][ii], bb.s1[ii], c, P2[ii]);
}
}
bb.ee = hash_to_scalar(L[1]); //or L[1]..
key LL, cc;
for (jj = 0 ; jj < 64 ; jj++) {
if (!indices[jj]) {
sc_mulsub(bb.s0[jj].bytes, x[jj].bytes, bb.ee.bytes, alpha[jj].bytes);
} else {
skGen(bb.s0[jj]);
addKeys2(LL, bb.s0[jj], bb.ee, P1[jj]); //different L0
cc = hash_to_scalar(LL);
sc_mulsub(bb.s1[jj].bytes, x[jj].bytes, cc.bytes, alpha[jj].bytes);
}
}
return bb;
}
//see above.
bool verifyBorromean(const boroSig &bb, const ge_p3 P1[64], const ge_p3 P2[64]) {
key64 Lv1; key chash, LL;
int ii = 0;
ge_p2 p2;
for (ii = 0 ; ii < 64 ; ii++) {
// equivalent of: addKeys2(LL, bb.s0[ii], bb.ee, P1[ii]);
ge_double_scalarmult_base_vartime(&p2, bb.ee.bytes, &P1[ii], bb.s0[ii].bytes);
ge_tobytes(LL.bytes, &p2);
chash = hash_to_scalar(LL);
// equivalent of: addKeys2(Lv1[ii], bb.s1[ii], chash, P2[ii]);
ge_double_scalarmult_base_vartime(&p2, chash.bytes, &P2[ii], bb.s1[ii].bytes);
ge_tobytes(Lv1[ii].bytes, &p2);
}
key eeComputed = hash_to_scalar(Lv1); //hash function fine
return equalKeys(eeComputed, bb.ee);
}
bool verifyBorromean(const boroSig &bb, const key64 P1, const key64 P2) {
ge_p3 P1_p3[64], P2_p3[64];
for (size_t i = 0 ; i < 64 ; ++i) {
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P1_p3[i], P1[i].bytes) == 0, false, "point conv failed");
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P2_p3[i], P2[i].bytes) == 0, false, "point conv failed");
}
return verifyBorromean(bb, P1_p3, P2_p3);
}
// Generate a CLSAG signature
// See paper by Goodell et al. (https://eprint.iacr.org/2019/654)
//
// The keys are set as follows:
// P[l] == p*G
// C[l] == z*G
// C[i] == C_nonzero[i] - C_offset (for hashing purposes) for all i
clsag CLSAG_Gen(const key &message, const keyV & P, const key & p, const keyV & C, const key & z, const keyV & C_nonzero, const key & C_offset, const unsigned int l, const multisig_kLRki *kLRki, key *mscout, key *mspout, hw::device &hwdev) {
clsag sig;
size_t n = P.size(); // ring size
CHECK_AND_ASSERT_THROW_MES(n == C.size(), "Signing and commitment key vector sizes must match!");
CHECK_AND_ASSERT_THROW_MES(n == C_nonzero.size(), "Signing and commitment key vector sizes must match!");
CHECK_AND_ASSERT_THROW_MES(l < n, "Signing index out of range!");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
CHECK_AND_ASSERT_THROW_MES((mscout && mspout) || !kLRki, "Multisig pointers are not all present");
// Key images
ge_p3 H_p3;
hash_to_p3(H_p3,P[l]);
key H;
ge_p3_tobytes(H.bytes,&H_p3);
key D;
// Initial values
key a;
key aG;
key aH;
// Multisig
if (kLRki)
{
sig.I = kLRki->ki;
scalarmultKey(D,H,z);
}
else
{
hwdev.clsag_prepare(p,z,sig.I,D,H,a,aG,aH);
}
geDsmp I_precomp;
geDsmp D_precomp;
precomp(I_precomp.k,sig.I);
precomp(D_precomp.k,D);
// Offset key image
scalarmultKey(sig.D,D,INV_EIGHT);
// Aggregation hashes
keyV mu_P_to_hash(2*n+4); // domain, I, D, P, C, C_offset
keyV mu_C_to_hash(2*n+4); // domain, I, D, P, C, C_offset
sc_0(mu_P_to_hash[0].bytes);
memcpy(mu_P_to_hash[0].bytes,config::HASH_KEY_CLSAG_AGG_0,sizeof(config::HASH_KEY_CLSAG_AGG_0)-1);
sc_0(mu_C_to_hash[0].bytes);
memcpy(mu_C_to_hash[0].bytes,config::HASH_KEY_CLSAG_AGG_1,sizeof(config::HASH_KEY_CLSAG_AGG_1)-1);
for (size_t i = 1; i < n+1; ++i) {
mu_P_to_hash[i] = P[i-1];
mu_C_to_hash[i] = P[i-1];
}
for (size_t i = n+1; i < 2*n+1; ++i) {
mu_P_to_hash[i] = C_nonzero[i-n-1];
mu_C_to_hash[i] = C_nonzero[i-n-1];
}
mu_P_to_hash[2*n+1] = sig.I;
mu_P_to_hash[2*n+2] = sig.D;
mu_P_to_hash[2*n+3] = C_offset;
mu_C_to_hash[2*n+1] = sig.I;
mu_C_to_hash[2*n+2] = sig.D;
mu_C_to_hash[2*n+3] = C_offset;
key mu_P, mu_C;
mu_P = hash_to_scalar(mu_P_to_hash);
mu_C = hash_to_scalar(mu_C_to_hash);
// Initial commitment
keyV c_to_hash(2*n+5); // domain, P, C, C_offset, message, aG, aH
key c;
sc_0(c_to_hash[0].bytes);
memcpy(c_to_hash[0].bytes,config::HASH_KEY_CLSAG_ROUND,sizeof(config::HASH_KEY_CLSAG_ROUND)-1);
for (size_t i = 1; i < n+1; ++i)
{
c_to_hash[i] = P[i-1];
c_to_hash[i+n] = C_nonzero[i-1];
}
c_to_hash[2*n+1] = C_offset;
c_to_hash[2*n+2] = message;
// Multisig data is present
if (kLRki)
{
a = kLRki->k;
c_to_hash[2*n+3] = kLRki->L;
c_to_hash[2*n+4] = kLRki->R;
}
else
{
c_to_hash[2*n+3] = aG;
c_to_hash[2*n+4] = aH;
}
hwdev.clsag_hash(c_to_hash,c);
size_t i;
i = (l + 1) % n;
if (i == 0)
copy(sig.c1, c);
// Decoy indices
sig.s = keyV(n);
key c_new;
key L;
key R;
key c_p; // = c[i]*mu_P
key c_c; // = c[i]*mu_C
geDsmp P_precomp;
geDsmp C_precomp;
geDsmp H_precomp;
ge_p3 Hi_p3;
while (i != l) {
sig.s[i] = skGen();
sc_0(c_new.bytes);
sc_mul(c_p.bytes,mu_P.bytes,c.bytes);
sc_mul(c_c.bytes,mu_C.bytes,c.bytes);
// Precompute points
precomp(P_precomp.k,P[i]);
precomp(C_precomp.k,C[i]);
// Compute L
addKeys_aGbBcC(L,sig.s[i],c_p,P_precomp.k,c_c,C_precomp.k);
// Compute R
hash_to_p3(Hi_p3,P[i]);
ge_dsm_precomp(H_precomp.k, &Hi_p3);
addKeys_aAbBcC(R,sig.s[i],H_precomp.k,c_p,I_precomp.k,c_c,D_precomp.k);
c_to_hash[2*n+3] = L;
c_to_hash[2*n+4] = R;
hwdev.clsag_hash(c_to_hash,c_new);
copy(c,c_new);
i = (i + 1) % n;
if (i == 0)
copy(sig.c1,c);
}
// Compute final scalar
hwdev.clsag_sign(c,a,p,z,mu_P,mu_C,sig.s[l]);
memwipe(&a, sizeof(key));
if (mscout)
*mscout = c;
if (mspout)
*mspout = mu_P;
return sig;
}
clsag CLSAG_Gen(const key &message, const keyV & P, const key & p, const keyV & C, const key & z, const keyV & C_nonzero, const key & C_offset, const unsigned int l) {
return CLSAG_Gen(message, P, p, C, z, C_nonzero, C_offset, l, NULL, NULL, NULL, hw::get_device("default"));
}
// MLSAG signatures
// See paper by Noether (https://eprint.iacr.org/2015/1098)
// This generalization allows for some dimensions not to require linkability;
// this is used in practice for commitment data within signatures
// Note that using more than one linkable dimension is not recommended.
mgSig MLSAG_Gen(const key &message, const keyM & pk, const keyV & xx, const multisig_kLRki *kLRki, key *mscout, const unsigned int index, size_t dsRows, hw::device &hwdev) {
mgSig rv;
size_t cols = pk.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 2, "Error! What is c if cols = 1!");
CHECK_AND_ASSERT_THROW_MES(index < cols, "Index out of range");
size_t rows = pk[0].size();
CHECK_AND_ASSERT_THROW_MES(rows >= 1, "Empty pk");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_THROW_MES(pk[i].size() == rows, "pk is not rectangular");
}
CHECK_AND_ASSERT_THROW_MES(xx.size() == rows, "Bad xx size");
CHECK_AND_ASSERT_THROW_MES(dsRows <= rows, "Bad dsRows size");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
CHECK_AND_ASSERT_THROW_MES(!kLRki || dsRows == 1, "Multisig requires exactly 1 dsRows");
size_t i = 0, j = 0, ii = 0;
key c, c_old, L, R, Hi;
ge_p3 Hi_p3;
sc_0(c_old.bytes);
vector<geDsmp> Ip(dsRows);
rv.II = keyV(dsRows);
keyV alpha(rows);
auto wiper = epee::misc_utils::create_scope_leave_handler([&](){memwipe(alpha.data(), alpha.size() * sizeof(alpha[0]));});
keyV aG(rows);
rv.ss = keyM(cols, aG);
keyV aHP(dsRows);
keyV toHash(1 + 3 * dsRows + 2 * (rows - dsRows));
toHash[0] = message;
DP("here1");
for (i = 0; i < dsRows; i++) {
toHash[3 * i + 1] = pk[index][i];
if (kLRki) {
// multisig
alpha[i] = kLRki->k;
toHash[3 * i + 2] = kLRki->L;
toHash[3 * i + 3] = kLRki->R;
rv.II[i] = kLRki->ki;
}
else {
hash_to_p3(Hi_p3, pk[index][i]);
ge_p3_tobytes(Hi.bytes, &Hi_p3);
hwdev.mlsag_prepare(Hi, xx[i], alpha[i] , aG[i] , aHP[i] , rv.II[i]);
toHash[3 * i + 2] = aG[i];
toHash[3 * i + 3] = aHP[i];
}
precomp(Ip[i].k, rv.II[i]);
}
size_t ndsRows = 3 * dsRows; //non Double Spendable Rows (see identity chains paper)
for (i = dsRows, ii = 0 ; i < rows ; i++, ii++) {
skpkGen(alpha[i], aG[i]); //need to save alphas for later..
toHash[ndsRows + 2 * ii + 1] = pk[index][i];
toHash[ndsRows + 2 * ii + 2] = aG[i];
}
hwdev.mlsag_hash(toHash, c_old);
i = (index + 1) % cols;
if (i == 0) {
copy(rv.cc, c_old);
}
while (i != index) {
rv.ss[i] = skvGen(rows);
sc_0(c.bytes);
for (j = 0; j < dsRows; j++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
hash_to_p3(Hi_p3, pk[i][j]);
ge_p3_tobytes(Hi.bytes, &Hi_p3);
addKeys3(R, rv.ss[i][j], Hi, c_old, Ip[j].k);
toHash[3 * j + 1] = pk[i][j];
toHash[3 * j + 2] = L;
toHash[3 * j + 3] = R;
}
for (j = dsRows, ii = 0; j < rows; j++, ii++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
toHash[ndsRows + 2 * ii + 1] = pk[i][j];
toHash[ndsRows + 2 * ii + 2] = L;
}
hwdev.mlsag_hash(toHash, c);
copy(c_old, c);
i = (i + 1) % cols;
if (i == 0) {
copy(rv.cc, c_old);
}
}
hwdev.mlsag_sign(c, xx, alpha, rows, dsRows, rv.ss[index]);
if (mscout)
*mscout = c;
return rv;
}
// MLSAG signatures
// See paper by Noether (https://eprint.iacr.org/2015/1098)
// This generalization allows for some dimensions not to require linkability;
// this is used in practice for commitment data within signatures
// Note that using more than one linkable dimension is not recommended.
bool MLSAG_Ver(const key &message, const keyM & pk, const mgSig & rv, size_t dsRows) {
size_t cols = pk.size();
CHECK_AND_ASSERT_MES(cols >= 2, false, "Signature must contain more than one public key");
size_t rows = pk[0].size();
CHECK_AND_ASSERT_MES(rows >= 1, false, "Bad total row number");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_MES(pk[i].size() == rows, false, "Bad public key matrix dimensions");
}
CHECK_AND_ASSERT_MES(rv.II.size() == dsRows, false, "Wrong number of key images present");
CHECK_AND_ASSERT_MES(rv.ss.size() == cols, false, "Bad scalar matrix dimensions");
for (size_t i = 0; i < cols; ++i) {
CHECK_AND_ASSERT_MES(rv.ss[i].size() == rows, false, "Bad scalar matrix dimensions");
}
CHECK_AND_ASSERT_MES(dsRows <= rows, false, "Non-double-spend rows cannot exceed total rows");
for (size_t i = 0; i < rv.ss.size(); ++i) {
for (size_t j = 0; j < rv.ss[i].size(); ++j) {
CHECK_AND_ASSERT_MES(sc_check(rv.ss[i][j].bytes) == 0, false, "Bad signature scalar");
}
}
CHECK_AND_ASSERT_MES(sc_check(rv.cc.bytes) == 0, false, "Bad initial signature hash");
size_t i = 0, j = 0, ii = 0;
key c, L, R;
key c_old = copy(rv.cc);
vector<geDsmp> Ip(dsRows);
for (i = 0 ; i < dsRows ; i++) {
CHECK_AND_ASSERT_MES(!(rv.II[i] == rct::identity()), false, "Bad key image");
precomp(Ip[i].k, rv.II[i]);
}
size_t ndsRows = 3 * dsRows; // number of dimensions not requiring linkability
keyV toHash(1 + 3 * dsRows + 2 * (rows - dsRows));
toHash[0] = message;
i = 0;
while (i < cols) {
sc_0(c.bytes);
for (j = 0; j < dsRows; j++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
// Compute R directly
ge_p3 hash8_p3;
hash_to_p3(hash8_p3, pk[i][j]);
ge_p2 R_p2;
ge_double_scalarmult_precomp_vartime(&R_p2, rv.ss[i][j].bytes, &hash8_p3, c_old.bytes, Ip[j].k);
ge_tobytes(R.bytes, &R_p2);
toHash[3 * j + 1] = pk[i][j];
toHash[3 * j + 2] = L;
toHash[3 * j + 3] = R;
}
for (j = dsRows, ii = 0 ; j < rows ; j++, ii++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
toHash[ndsRows + 2 * ii + 1] = pk[i][j];
toHash[ndsRows + 2 * ii + 2] = L;
}
c = hash_to_scalar(toHash);
CHECK_AND_ASSERT_MES(!(c == rct::zero()), false, "Bad signature hash");
copy(c_old, c);
i = (i + 1);
}
sc_sub(c.bytes, c_old.bytes, rv.cc.bytes);
return sc_isnonzero(c.bytes) == 0;
}
//proveRange and verRange
//proveRange gives C, and mask such that \sumCi = C
// c.f. https://eprint.iacr.org/2015/1098 section 5.1
// and Ci is a commitment to either 0 or 2^i, i=0,...,63
// thus this proves that "amount" is in [0, 2^64]
// mask is a such that C = aG + bH, and b = amount
//verRange verifies that \sum Ci = C and that each Ci is a commitment to 0 or 2^i
rangeSig proveRange(key & C, key & mask, const xmr_amount & amount) {
sc_0(mask.bytes);
identity(C);
bits b;
d2b(b, amount);
rangeSig sig;
key64 ai;
key64 CiH;
int i = 0;
for (i = 0; i < ATOMS; i++) {
skGen(ai[i]);
if (b[i] == 0) {
scalarmultBase(sig.Ci[i], ai[i]);
}
if (b[i] == 1) {
addKeys1(sig.Ci[i], ai[i], H2[i]);
}
subKeys(CiH[i], sig.Ci[i], H2[i]);
sc_add(mask.bytes, mask.bytes, ai[i].bytes);
addKeys(C, C, sig.Ci[i]);
}
sig.asig = genBorromean(ai, sig.Ci, CiH, b);
return sig;
}
//proveRange and verRange
//proveRange gives C, and mask such that \sumCi = C
// c.f. https://eprint.iacr.org/2015/1098 section 5.1
// and Ci is a commitment to either 0 or 2^i, i=0,...,63
// thus this proves that "amount" is in [0, 2^64]
// mask is a such that C = aG + bH, and b = amount
//verRange verifies that \sum Ci = C and that each Ci is a commitment to 0 or 2^i
bool verRange(const key & C, const rangeSig & as) {
try
{
PERF_TIMER(verRange);
ge_p3 CiH[64], asCi[64];
int i = 0;
ge_p3 Ctmp_p3 = ge_p3_identity;
for (i = 0; i < 64; i++) {
// faster equivalent of:
// subKeys(CiH[i], as.Ci[i], H2[i]);
// addKeys(Ctmp, Ctmp, as.Ci[i]);
ge_cached cached;
ge_p3 p3;
ge_p1p1 p1;
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, H2[i].bytes) == 0, false, "point conv failed");
ge_p3_to_cached(&cached, &p3);
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&asCi[i], as.Ci[i].bytes) == 0, false, "point conv failed");
ge_sub(&p1, &asCi[i], &cached);
ge_p3_to_cached(&cached, &asCi[i]);
ge_p1p1_to_p3(&CiH[i], &p1);
ge_add(&p1, &Ctmp_p3, &cached);
ge_p1p1_to_p3(&Ctmp_p3, &p1);
}
key Ctmp;
ge_p3_tobytes(Ctmp.bytes, &Ctmp_p3);
if (!equalKeys(C, Ctmp))
return false;
if (!verifyBorromean(as.asig, asCi, CiH))
return false;
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
key get_pre_mlsag_hash(const rctSig &rv, hw::device &hwdev)
{
keyV hashes;
hashes.reserve(3);
hashes.push_back(rv.message);
crypto::hash h;
std::stringstream ss;
binary_archive<true> ba(ss);
CHECK_AND_ASSERT_THROW_MES(!rv.mixRing.empty(), "Empty mixRing");
const size_t inputs = is_rct_simple(rv.type) ? rv.mixRing.size() : rv.mixRing[0].size();
const size_t outputs = rv.ecdhInfo.size();
key prehash;
CHECK_AND_ASSERT_THROW_MES(const_cast<rctSig&>(rv).serialize_rctsig_base(ba, inputs, outputs),
"Failed to serialize rctSigBase");
cryptonote::get_blob_hash(ss.str(), h);
hashes.push_back(hash2rct(h));
keyV kv;
if (rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG)
{
kv.reserve((6*2+9) * rv.p.bulletproofs.size());
for (const auto &p: rv.p.bulletproofs)
{
// V are not hashed as they're expanded from outPk.mask
// (and thus hashed as part of rctSigBase above)
kv.push_back(p.A);
kv.push_back(p.S);
kv.push_back(p.T1);
kv.push_back(p.T2);
kv.push_back(p.taux);
kv.push_back(p.mu);
for (size_t n = 0; n < p.L.size(); ++n)
kv.push_back(p.L[n]);
for (size_t n = 0; n < p.R.size(); ++n)
kv.push_back(p.R[n]);
kv.push_back(p.a);
kv.push_back(p.b);
kv.push_back(p.t);
}
}
else
{
kv.reserve((64*3+1) * rv.p.rangeSigs.size());
for (const auto &r: rv.p.rangeSigs)
{
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.asig.s0[n]);
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.asig.s1[n]);
kv.push_back(r.asig.ee);
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.Ci[n]);
}
}
hashes.push_back(cn_fast_hash(kv));
hwdev.mlsag_prehash(ss.str(), inputs, outputs, hashes, rv.outPk, prehash);
return prehash;
}
//Ring-ct MG sigs
//Prove:
// c.f. https://eprint.iacr.org/2015/1098 section 4. definition 10.
// This does the MG sig on the "dest" part of the given key matrix, and
// the last row is the sum of input commitments from that column - sum output commitments
// this shows that sum inputs = sum outputs
//Ver:
// verifies the above sig is created corretly
mgSig proveRctMG(const key &message, const ctkeyM & pubs, const ctkeyV & inSk, const ctkeyV &outSk, const ctkeyV & outPk, const multisig_kLRki *kLRki, key *mscout, unsigned int index, const key &txnFeeKey, hw::device &hwdev) {
//setup vars
size_t cols = pubs.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs");
size_t rows = pubs[0].size();
CHECK_AND_ASSERT_THROW_MES(rows >= 1, "Empty pubs");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_THROW_MES(pubs[i].size() == rows, "pubs is not rectangular");
}
CHECK_AND_ASSERT_THROW_MES(inSk.size() == rows, "Bad inSk size");
CHECK_AND_ASSERT_THROW_MES(outSk.size() == outPk.size(), "Bad outSk/outPk size");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
keyV sk(rows + 1);
keyV tmp(rows + 1);
size_t i = 0, j = 0;
for (i = 0; i < rows + 1; i++) {
sc_0(sk[i].bytes);
identity(tmp[i]);
}
keyM M(cols, tmp);
//create the matrix to mg sig
for (i = 0; i < cols; i++) {
M[i][rows] = identity();
for (j = 0; j < rows; j++) {
M[i][j] = pubs[i][j].dest;
addKeys(M[i][rows], M[i][rows], pubs[i][j].mask); //add input commitments in last row
}
}
sc_0(sk[rows].bytes);
for (j = 0; j < rows; j++) {
sk[j] = copy(inSk[j].dest);
sc_add(sk[rows].bytes, sk[rows].bytes, inSk[j].mask.bytes); //add masks in last row
}
for (i = 0; i < cols; i++) {
for (size_t j = 0; j < outPk.size(); j++) {
subKeys(M[i][rows], M[i][rows], outPk[j].mask); //subtract output Ci's in last row
}
//subtract txn fee output in last row
subKeys(M[i][rows], M[i][rows], txnFeeKey);
}
for (size_t j = 0; j < outPk.size(); j++) {
sc_sub(sk[rows].bytes, sk[rows].bytes, outSk[j].mask.bytes); //subtract output masks in last row..
}
mgSig result = MLSAG_Gen(message, M, sk, kLRki, mscout, index, rows, hwdev);
memwipe(sk.data(), sk.size() * sizeof(key));
return result;
}
//Ring-ct MG sigs Simple
// Simple version for when we assume only
// post rct inputs
// here pubs is a vector of (P, C) length mixin
// inSk is x, a_in corresponding to signing index
// a_out, Cout is for the output commitment
// index is the signing index..
mgSig proveRctMGSimple(const key &message, const ctkeyV & pubs, const ctkey & inSk, const key &a , const key &Cout, const multisig_kLRki *kLRki, key *mscout, unsigned int index, hw::device &hwdev) {
//setup vars
size_t rows = 1;
size_t cols = pubs.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
keyV tmp(rows + 1);
keyV sk(rows + 1);
size_t i;
keyM M(cols, tmp);
sk[0] = copy(inSk.dest);
sc_sub(sk[1].bytes, inSk.mask.bytes, a.bytes);
for (i = 0; i < cols; i++) {
M[i][0] = pubs[i].dest;
subKeys(M[i][1], pubs[i].mask, Cout);
}
mgSig result = MLSAG_Gen(message, M, sk, kLRki, mscout, index, rows, hwdev);
memwipe(sk.data(), sk.size() * sizeof(key));
return result;
}
clsag proveRctCLSAGSimple(const key &message, const ctkeyV &pubs, const ctkey &inSk, const key &a, const key &Cout, const multisig_kLRki *kLRki, key *mscout, key *mspout, unsigned int index, hw::device &hwdev) {
//setup vars
size_t rows = 1;
size_t cols = pubs.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
keyV tmp(rows + 1);
keyV sk(rows + 1);
keyM M(cols, tmp);
keyV P, C, C_nonzero;
P.reserve(pubs.size());
C.reserve(pubs.size());
C_nonzero.reserve(pubs.size());
for (const ctkey &k: pubs)
{
P.push_back(k.dest);
C_nonzero.push_back(k.mask);
rct::key tmp;
subKeys(tmp, k.mask, Cout);
C.push_back(tmp);
}
sk[0] = copy(inSk.dest);
sc_sub(sk[1].bytes, inSk.mask.bytes, a.bytes);
clsag result = CLSAG_Gen(message, P, sk[0], C, sk[1], C_nonzero, Cout, index, kLRki, mscout, mspout, hwdev);
memwipe(sk.data(), sk.size() * sizeof(key));
return result;
}
//Ring-ct MG sigs
//Prove:
// c.f. https://eprint.iacr.org/2015/1098 section 4. definition 10.
// This does the MG sig on the "dest" part of the given key matrix, and
// the last row is the sum of input commitments from that column - sum output commitments
// this shows that sum inputs = sum outputs
//Ver:
// verifies the above sig is created corretly
bool verRctMG(const mgSig &mg, const ctkeyM & pubs, const ctkeyV & outPk, const key &txnFeeKey, const key &message) {
PERF_TIMER(verRctMG);
//setup vars
size_t cols = pubs.size();
CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs");
size_t rows = pubs[0].size();
CHECK_AND_ASSERT_MES(rows >= 1, false, "Empty pubs");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_MES(pubs[i].size() == rows, false, "pubs is not rectangular");
}
keyV tmp(rows + 1);
size_t i = 0, j = 0;
for (i = 0; i < rows + 1; i++) {
identity(tmp[i]);
}
keyM M(cols, tmp);
//create the matrix to mg sig
for (j = 0; j < rows; j++) {
for (i = 0; i < cols; i++) {
M[i][j] = pubs[i][j].dest;
addKeys(M[i][rows], M[i][rows], pubs[i][j].mask); //add Ci in last row
}
}
for (i = 0; i < cols; i++) {
for (j = 0; j < outPk.size(); j++) {
subKeys(M[i][rows], M[i][rows], outPk[j].mask); //subtract output Ci's in last row
}
//subtract txn fee output in last row
subKeys(M[i][rows], M[i][rows], txnFeeKey);
}
return MLSAG_Ver(message, M, mg, rows);
}
//Ring-ct Simple MG sigs
//Ver:
//This does a simplified version, assuming only post Rct
//inputs
bool verRctMGSimple(const key &message, const mgSig &mg, const ctkeyV & pubs, const key & C) {
try
{
PERF_TIMER(verRctMGSimple);
//setup vars
size_t rows = 1;
size_t cols = pubs.size();
CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs");
keyV tmp(rows + 1);
size_t i;
keyM M(cols, tmp);
ge_p3 Cp3;
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&Cp3, C.bytes) == 0, false, "point conv failed");
ge_cached Ccached;
ge_p3_to_cached(&Ccached, &Cp3);
ge_p1p1 p1;
//create the matrix to mg sig
for (i = 0; i < cols; i++) {
M[i][0] = pubs[i].dest;
ge_p3 p3;
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, pubs[i].mask.bytes) == 0, false, "point conv failed");
ge_sub(&p1, &p3, &Ccached);
ge_p1p1_to_p3(&p3, &p1);
ge_p3_tobytes(M[i][1].bytes, &p3);
}
//DP(C);
return MLSAG_Ver(message, M, mg, rows);
}
catch (...) { return false; }
}
bool verRctCLSAGSimple(const key &message, const clsag &sig, const ctkeyV & pubs, const key & C_offset) {
try
{
PERF_TIMER(verRctCLSAGSimple);
const size_t n = pubs.size();
// Check data
CHECK_AND_ASSERT_MES(n >= 1, false, "Empty pubs");
CHECK_AND_ASSERT_MES(n == sig.s.size(), false, "Signature scalar vector is the wrong size!");
for (size_t i = 0; i < n; ++i)
CHECK_AND_ASSERT_MES(sc_check(sig.s[i].bytes) == 0, false, "Bad signature scalar!");
CHECK_AND_ASSERT_MES(sc_check(sig.c1.bytes) == 0, false, "Bad signature commitment!");
CHECK_AND_ASSERT_MES(!(sig.I == rct::identity()), false, "Bad key image!");
// Cache commitment offset for efficient subtraction later
ge_p3 C_offset_p3;
CHECK_AND_ASSERT_MES(ge_frombytes_vartime(&C_offset_p3, C_offset.bytes) == 0, false, "point conv failed");
ge_cached C_offset_cached;
ge_p3_to_cached(&C_offset_cached, &C_offset_p3);
// Prepare key images
key c = copy(sig.c1);
key D_8 = scalarmult8(sig.D);
CHECK_AND_ASSERT_MES(!(D_8 == rct::identity()), false, "Bad auxiliary key image!");
geDsmp I_precomp;
geDsmp D_precomp;
precomp(I_precomp.k,sig.I);
precomp(D_precomp.k,D_8);
// Aggregation hashes
keyV mu_P_to_hash(2*n+4); // domain, I, D, P, C, C_offset
keyV mu_C_to_hash(2*n+4); // domain, I, D, P, C, C_offset
sc_0(mu_P_to_hash[0].bytes);
memcpy(mu_P_to_hash[0].bytes,config::HASH_KEY_CLSAG_AGG_0,sizeof(config::HASH_KEY_CLSAG_AGG_0)-1);
sc_0(mu_C_to_hash[0].bytes);
memcpy(mu_C_to_hash[0].bytes,config::HASH_KEY_CLSAG_AGG_1,sizeof(config::HASH_KEY_CLSAG_AGG_1)-1);
for (size_t i = 1; i < n+1; ++i) {
mu_P_to_hash[i] = pubs[i-1].dest;
mu_C_to_hash[i] = pubs[i-1].dest;
}
for (size_t i = n+1; i < 2*n+1; ++i) {
mu_P_to_hash[i] = pubs[i-n-1].mask;
mu_C_to_hash[i] = pubs[i-n-1].mask;
}
mu_P_to_hash[2*n+1] = sig.I;
mu_P_to_hash[2*n+2] = sig.D;
mu_P_to_hash[2*n+3] = C_offset;
mu_C_to_hash[2*n+1] = sig.I;
mu_C_to_hash[2*n+2] = sig.D;
mu_C_to_hash[2*n+3] = C_offset;
key mu_P, mu_C;
mu_P = hash_to_scalar(mu_P_to_hash);
mu_C = hash_to_scalar(mu_C_to_hash);
// Set up round hash
keyV c_to_hash(2*n+5); // domain, P, C, C_offset, message, L, R
sc_0(c_to_hash[0].bytes);
memcpy(c_to_hash[0].bytes,config::HASH_KEY_CLSAG_ROUND,sizeof(config::HASH_KEY_CLSAG_ROUND)-1);
for (size_t i = 1; i < n+1; ++i)
{
c_to_hash[i] = pubs[i-1].dest;
c_to_hash[i+n] = pubs[i-1].mask;
}
c_to_hash[2*n+1] = C_offset;
c_to_hash[2*n+2] = message;
key c_p; // = c[i]*mu_P
key c_c; // = c[i]*mu_C
key c_new;
key L;
key R;
geDsmp P_precomp;
geDsmp C_precomp;
size_t i = 0;
ge_p3 hash8_p3;
geDsmp hash_precomp;
ge_p3 temp_p3;
ge_p1p1 temp_p1;
while (i < n) {
sc_0(c_new.bytes);
sc_mul(c_p.bytes,mu_P.bytes,c.bytes);
sc_mul(c_c.bytes,mu_C.bytes,c.bytes);
// Precompute points for L/R
precomp(P_precomp.k,pubs[i].dest);
CHECK_AND_ASSERT_MES(ge_frombytes_vartime(&temp_p3, pubs[i].mask.bytes) == 0, false, "point conv failed");
ge_sub(&temp_p1,&temp_p3,&C_offset_cached);
ge_p1p1_to_p3(&temp_p3,&temp_p1);
ge_dsm_precomp(C_precomp.k,&temp_p3);
// Compute L
addKeys_aGbBcC(L,sig.s[i],c_p,P_precomp.k,c_c,C_precomp.k);
// Compute R
hash_to_p3(hash8_p3,pubs[i].dest);
ge_dsm_precomp(hash_precomp.k, &hash8_p3);
addKeys_aAbBcC(R,sig.s[i],hash_precomp.k,c_p,I_precomp.k,c_c,D_precomp.k);
c_to_hash[2*n+3] = L;
c_to_hash[2*n+4] = R;
c_new = hash_to_scalar(c_to_hash);
CHECK_AND_ASSERT_MES(!(c_new == rct::zero()), false, "Bad signature hash");
copy(c,c_new);
i = i + 1;
}
sc_sub(c_new.bytes,c.bytes,sig.c1.bytes);
return sc_isnonzero(c_new.bytes) == 0;
}
catch (...) { return false; }
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
void getKeyFromBlockchain(ctkey & a, size_t reference_index) {
a.mask = pkGen();
a.dest = pkGen();
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" + 1 columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
tuple<ctkeyM, xmr_amount> populateFromBlockchain(ctkeyV inPk, int mixin) {
int rows = inPk.size();
ctkeyM rv(mixin + 1, inPk);
int index = randXmrAmount(mixin);
int i = 0, j = 0;
for (i = 0; i <= mixin; i++) {
if (i != index) {
for (j = 0; j < rows; j++) {
getKeyFromBlockchain(rv[i][j], (size_t)randXmrAmount);
}
}
}
return make_tuple(rv, index);
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
xmr_amount populateFromBlockchainSimple(ctkeyV & mixRing, const ctkey & inPk, int mixin) {
int index = randXmrAmount(mixin);
int i = 0;
for (i = 0; i <= mixin; i++) {
if (i != index) {
getKeyFromBlockchain(mixRing[i], (size_t)randXmrAmount(1000));
} else {
mixRing[i] = inPk;
}
}
return index;
}
//RingCT protocol
//genRct:
// creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the
// columns that are claimed as inputs, and that the sum of inputs = sum of outputs.
// Also contains masked "amount" and "mask" so the receiver can see how much they received
//verRct:
// verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct
//decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1)
// uses the attached ecdh info to find the amounts represented by each output commitment
// must know the destination private key to find the correct amount, else will return a random number
// Note: For txn fees, the last index in the amounts vector should contain that
// Thus the amounts vector will be "one" longer than the destinations vectort
rctSig genRct(const key &message, const ctkeyV & inSk, const keyV & destinations, const vector<xmr_amount> & amounts, const ctkeyM &mixRing, const keyV &amount_keys, const multisig_kLRki *kLRki, multisig_out *msout, unsigned int index, ctkeyV &outSk, const RCTConfig &rct_config, hw::device &hwdev) {
CHECK_AND_ASSERT_THROW_MES(amounts.size() == destinations.size() || amounts.size() == destinations.size() + 1, "Different number of amounts/destinations");
CHECK_AND_ASSERT_THROW_MES(amount_keys.size() == destinations.size(), "Different number of amount_keys/destinations");
CHECK_AND_ASSERT_THROW_MES(index < mixRing.size(), "Bad index into mixRing");
for (size_t n = 0; n < mixRing.size(); ++n) {
CHECK_AND_ASSERT_THROW_MES(mixRing[n].size() == inSk.size(), "Bad mixRing size");
}
CHECK_AND_ASSERT_THROW_MES((kLRki && msout) || (!kLRki && !msout), "Only one of kLRki/msout is present");
CHECK_AND_ASSERT_THROW_MES(inSk.size() < 2, "genRct is not suitable for 2+ rings");
rctSig rv;
rv.type = RCTTypeFull;
rv.message = message;
rv.outPk.resize(destinations.size());
rv.p.rangeSigs.resize(destinations.size());
rv.ecdhInfo.resize(destinations.size());
size_t i = 0;
keyV masks(destinations.size()); //sk mask..
outSk.resize(destinations.size());
for (i = 0; i < destinations.size(); i++) {
//add destination to sig
rv.outPk[i].dest = copy(destinations[i]);
//compute range proof
rv.p.rangeSigs[i] = proveRange(rv.outPk[i].mask, outSk[i].mask, amounts[i]);
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]), "verRange failed on newly created proof");
#endif
//mask amount and mask
rv.ecdhInfo[i].mask = copy(outSk[i].mask);
rv.ecdhInfo[i].amount = d2h(amounts[i]);
hwdev.ecdhEncode(rv.ecdhInfo[i], amount_keys[i], rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG);
}
//set txn fee
if (amounts.size() > destinations.size())
{
rv.txnFee = amounts[destinations.size()];
}
else
{
rv.txnFee = 0;
}
key txnFeeKey = scalarmultH(d2h(rv.txnFee));
rv.mixRing = mixRing;
if (msout)
msout->c.resize(1);
rv.p.MGs.push_back(proveRctMG(get_pre_mlsag_hash(rv, hwdev), rv.mixRing, inSk, outSk, rv.outPk, kLRki, msout ? &msout->c[0] : NULL, index, txnFeeKey,hwdev));
return rv;
}
rctSig genRct(const key &message, const ctkeyV & inSk, const ctkeyV & inPk, const keyV & destinations, const vector<xmr_amount> & amounts, const keyV &amount_keys, const multisig_kLRki *kLRki, multisig_out *msout, const int mixin, const RCTConfig &rct_config, hw::device &hwdev) {
unsigned int index;
ctkeyM mixRing;
ctkeyV outSk;
tie(mixRing, index) = populateFromBlockchain(inPk, mixin);
return genRct(message, inSk, destinations, amounts, mixRing, amount_keys, kLRki, msout, index, outSk, rct_config, hwdev);
}
//RCT simple
//for post-rct only
rctSig genRctSimple(const key &message, const ctkeyV & inSk, const keyV & destinations, const vector<xmr_amount> &inamounts, const vector<xmr_amount> &outamounts, xmr_amount txnFee, const ctkeyM & mixRing, const keyV &amount_keys, const std::vector<multisig_kLRki> *kLRki, multisig_out *msout, const std::vector<unsigned int> & index, ctkeyV &outSk, const RCTConfig &rct_config, hw::device &hwdev) {
const bool bulletproof = rct_config.range_proof_type != RangeProofBorromean;
CHECK_AND_ASSERT_THROW_MES(inamounts.size() > 0, "Empty inamounts");
CHECK_AND_ASSERT_THROW_MES(inamounts.size() == inSk.size(), "Different number of inamounts/inSk");
CHECK_AND_ASSERT_THROW_MES(outamounts.size() == destinations.size(), "Different number of amounts/destinations");
CHECK_AND_ASSERT_THROW_MES(amount_keys.size() == destinations.size(), "Different number of amount_keys/destinations");
CHECK_AND_ASSERT_THROW_MES(index.size() == inSk.size(), "Different number of index/inSk");
CHECK_AND_ASSERT_THROW_MES(mixRing.size() == inSk.size(), "Different number of mixRing/inSk");
for (size_t n = 0; n < mixRing.size(); ++n) {
CHECK_AND_ASSERT_THROW_MES(index[n] < mixRing[n].size(), "Bad index into mixRing");
}
CHECK_AND_ASSERT_THROW_MES((kLRki && msout) || (!kLRki && !msout), "Only one of kLRki/msout is present");
if (kLRki && msout) {
CHECK_AND_ASSERT_THROW_MES(kLRki->size() == inamounts.size(), "Mismatched kLRki/inamounts sizes");
}
rctSig rv;
if (bulletproof)
{
switch (rct_config.bp_version)
{
case 0:
case 3:
rv.type = RCTTypeCLSAG;
break;
case 2:
rv.type = RCTTypeBulletproof2;
break;
case 1:
rv.type = RCTTypeBulletproof;
break;
default:
ASSERT_MES_AND_THROW("Unsupported BP version: " << rct_config.bp_version);
}
}
else
rv.type = RCTTypeSimple;
rv.message = message;
rv.outPk.resize(destinations.size());
if (!bulletproof)
rv.p.rangeSigs.resize(destinations.size());
rv.ecdhInfo.resize(destinations.size());
size_t i;
keyV masks(destinations.size()); //sk mask..
outSk.resize(destinations.size());
for (i = 0; i < destinations.size(); i++) {
//add destination to sig
rv.outPk[i].dest = copy(destinations[i]);
//compute range proof
if (!bulletproof)
rv.p.rangeSigs[i] = proveRange(rv.outPk[i].mask, outSk[i].mask, outamounts[i]);
#ifdef DBG
if (!bulletproof)
CHECK_AND_ASSERT_THROW_MES(verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]), "verRange failed on newly created proof");
#endif
}
rv.p.bulletproofs.clear();
if (bulletproof)
{
size_t n_amounts = outamounts.size();
size_t amounts_proved = 0;
if (rct_config.range_proof_type == RangeProofPaddedBulletproof)
{
rct::keyV C, masks;
if (hwdev.get_mode() == hw::device::TRANSACTION_CREATE_FAKE)
{
// use a fake bulletproof for speed
rv.p.bulletproofs.push_back(make_dummy_bulletproof(outamounts, C, masks));
}
else
{
const epee::span<const key> keys{&amount_keys[0], amount_keys.size()};
rv.p.bulletproofs.push_back(proveRangeBulletproof(C, masks, outamounts, keys, hwdev));
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof");
#endif
}
for (i = 0; i < outamounts.size(); ++i)
{
rv.outPk[i].mask = rct::scalarmult8(C[i]);
outSk[i].mask = masks[i];
}
}
else while (amounts_proved < n_amounts)
{
size_t batch_size = 1;
if (rct_config.range_proof_type == RangeProofMultiOutputBulletproof)
while (batch_size * 2 + amounts_proved <= n_amounts && batch_size * 2 <= BULLETPROOF_MAX_OUTPUTS)
batch_size *= 2;
rct::keyV C, masks;
std::vector<uint64_t> batch_amounts(batch_size);
for (i = 0; i < batch_size; ++i)
batch_amounts[i] = outamounts[i + amounts_proved];
if (hwdev.get_mode() == hw::device::TRANSACTION_CREATE_FAKE)
{
// use a fake bulletproof for speed
rv.p.bulletproofs.push_back(make_dummy_bulletproof(batch_amounts, C, masks));
}
else
{
const epee::span<const key> keys{&amount_keys[amounts_proved], batch_size};
rv.p.bulletproofs.push_back(proveRangeBulletproof(C, masks, batch_amounts, keys, hwdev));
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof");
#endif
}
for (i = 0; i < batch_size; ++i)
{
rv.outPk[i + amounts_proved].mask = rct::scalarmult8(C[i]);
outSk[i + amounts_proved].mask = masks[i];
}
amounts_proved += batch_size;
}
}
key sumout = zero();
for (i = 0; i < outSk.size(); ++i)
{
sc_add(sumout.bytes, outSk[i].mask.bytes, sumout.bytes);
//mask amount and mask
rv.ecdhInfo[i].mask = copy(outSk[i].mask);
rv.ecdhInfo[i].amount = d2h(outamounts[i]);
hwdev.ecdhEncode(rv.ecdhInfo[i], amount_keys[i], rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG);
}
//set txn fee
rv.txnFee = txnFee;
// TODO: unused ??
// key txnFeeKey = scalarmultH(d2h(rv.txnFee));
rv.mixRing = mixRing;
keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts;
pseudoOuts.resize(inamounts.size());
if (rv.type == RCTTypeCLSAG)
rv.p.CLSAGs.resize(inamounts.size());
else
rv.p.MGs.resize(inamounts.size());
key sumpouts = zero(); //sum pseudoOut masks
keyV a(inamounts.size());
for (i = 0 ; i < inamounts.size() - 1; i++) {
skGen(a[i]);
sc_add(sumpouts.bytes, a[i].bytes, sumpouts.bytes);
genC(pseudoOuts[i], a[i], inamounts[i]);
}
sc_sub(a[i].bytes, sumout.bytes, sumpouts.bytes);
genC(pseudoOuts[i], a[i], inamounts[i]);
DP(pseudoOuts[i]);
key full_message = get_pre_mlsag_hash(rv,hwdev);
if (msout)
{
msout->c.resize(inamounts.size());
msout->mu_p.resize(rv.type == RCTTypeCLSAG ? inamounts.size() : 0);
}
for (i = 0 ; i < inamounts.size(); i++)
{
if (rv.type == RCTTypeCLSAG)
{
rv.p.CLSAGs[i] = proveRctCLSAGSimple(full_message, rv.mixRing[i], inSk[i], a[i], pseudoOuts[i], kLRki ? &(*kLRki)[i]: NULL, msout ? &msout->c[i] : NULL, msout ? &msout->mu_p[i] : NULL, index[i], hwdev);
}
else
{
rv.p.MGs[i] = proveRctMGSimple(full_message, rv.mixRing[i], inSk[i], a[i], pseudoOuts[i], kLRki ? &(*kLRki)[i]: NULL, msout ? &msout->c[i] : NULL, index[i], hwdev);
}
}
return rv;
}
rctSig genRctSimple(const key &message, const ctkeyV & inSk, const ctkeyV & inPk, const keyV & destinations, const vector<xmr_amount> &inamounts, const vector<xmr_amount> &outamounts, const keyV &amount_keys, const std::vector<multisig_kLRki> *kLRki, multisig_out *msout, xmr_amount txnFee, unsigned int mixin, const RCTConfig &rct_config, hw::device &hwdev) {
std::vector<unsigned int> index;
index.resize(inPk.size());
ctkeyM mixRing;
ctkeyV outSk;
mixRing.resize(inPk.size());
for (size_t i = 0; i < inPk.size(); ++i) {
mixRing[i].resize(mixin+1);
index[i] = populateFromBlockchainSimple(mixRing[i], inPk[i], mixin);
}
return genRctSimple(message, inSk, destinations, inamounts, outamounts, txnFee, mixRing, amount_keys, kLRki, msout, index, outSk, rct_config, hwdev);
}
//RingCT protocol
//genRct:
// creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the
// columns that are claimed as inputs, and that the sum of inputs = sum of outputs.
// Also contains masked "amount" and "mask" so the receiver can see how much they received
//verRct:
// verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct
//decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1)
// uses the attached ecdh info to find the amounts represented by each output commitment
// must know the destination private key to find the correct amount, else will return a random number
bool verRct(const rctSig & rv, bool semantics) {
PERF_TIMER(verRct);
CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull, false, "verRct called on non-full rctSig");
if (semantics)
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.p.rangeSigs.size(), false, "Mismatched sizes of outPk and rv.p.rangeSigs");
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outPk and rv.ecdhInfo");
CHECK_AND_ASSERT_MES(rv.p.MGs.size() == 1, false, "full rctSig has not one MG");
}
else
{
// semantics check is early, we don't have the MGs resolved yet
}
// some rct ops can throw
try
{
if (semantics) {
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter(tpool);
std::deque<bool> results(rv.outPk.size(), false);
DP("range proofs verified?");
for (size_t i = 0; i < rv.outPk.size(); i++)
tpool.submit(&waiter, [&, i] { results[i] = verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]); });
if (!waiter.wait())
return false;
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("Range proof verified failed for proof " << i);
return false;
}
}
}
if (!semantics) {
//compute txn fee
key txnFeeKey = scalarmultH(d2h(rv.txnFee));
bool mgVerd = verRctMG(rv.p.MGs[0], rv.mixRing, rv.outPk, txnFeeKey, get_pre_mlsag_hash(rv, hw::get_device("default")));
DP("mg sig verified?");
DP(mgVerd);
if (!mgVerd) {
LOG_PRINT_L1("MG signature verification failed");
return false;
}
}
return true;
}
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRct: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRct, but not an actual exception");
return false;
}
}
//ver RingCT simple
//assumes only post-rct style inputs (at least for max anonymity)
bool verRctSemanticsSimple(const std::vector<const rctSig*> & rvv) {
try
{
PERF_TIMER(verRctSemanticsSimple);
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter(tpool);
std::deque<bool> results;
std::vector<const Bulletproof*> proofs;
size_t max_non_bp_proofs = 0, offset = 0;
for (const rctSig *rvp: rvv)
{
CHECK_AND_ASSERT_MES(rvp, false, "rctSig pointer is NULL");
const rctSig &rv = *rvp;
CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG,
false, "verRctSemanticsSimple called on non simple rctSig");
const bool bulletproof = is_rct_bulletproof(rv.type);
if (bulletproof)
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == n_bulletproof_amounts(rv.p.bulletproofs), false, "Mismatched sizes of outPk and bulletproofs");
if (rv.type == RCTTypeCLSAG)
{
CHECK_AND_ASSERT_MES(rv.p.MGs.empty(), false, "MGs are not empty for CLSAG");
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.p.CLSAGs.size(), false, "Mismatched sizes of rv.p.pseudoOuts and rv.p.CLSAGs");
}
else
{
CHECK_AND_ASSERT_MES(rv.p.CLSAGs.empty(), false, "CLSAGs are not empty for MLSAG");
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.p.MGs.size(), false, "Mismatched sizes of rv.p.pseudoOuts and rv.p.MGs");
}
CHECK_AND_ASSERT_MES(rv.pseudoOuts.empty(), false, "rv.pseudoOuts is not empty");
}
else
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.p.rangeSigs.size(), false, "Mismatched sizes of outPk and rv.p.rangeSigs");
CHECK_AND_ASSERT_MES(rv.pseudoOuts.size() == rv.p.MGs.size(), false, "Mismatched sizes of rv.pseudoOuts and rv.p.MGs");
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.empty(), false, "rv.p.pseudoOuts is not empty");
}
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outPk and rv.ecdhInfo");
if (!bulletproof)
max_non_bp_proofs += rv.p.rangeSigs.size();
}
results.resize(max_non_bp_proofs);
for (const rctSig *rvp: rvv)
{
const rctSig &rv = *rvp;
const bool bulletproof = is_rct_bulletproof(rv.type);
const keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts;
rct::keyV masks(rv.outPk.size());
for (size_t i = 0; i < rv.outPk.size(); i++) {
masks[i] = rv.outPk[i].mask;
}
key sumOutpks = addKeys(masks);
DP(sumOutpks);
const key txnFeeKey = scalarmultH(d2h(rv.txnFee));
addKeys(sumOutpks, txnFeeKey, sumOutpks);
key sumPseudoOuts = addKeys(pseudoOuts);
DP(sumPseudoOuts);
//check pseudoOuts vs Outs..
if (!equalKeys(sumPseudoOuts, sumOutpks)) {
LOG_PRINT_L1("Sum check failed");
return false;
}
if (bulletproof)
{
for (size_t i = 0; i < rv.p.bulletproofs.size(); i++)
proofs.push_back(&rv.p.bulletproofs[i]);
}
else
{
for (size_t i = 0; i < rv.p.rangeSigs.size(); i++)
tpool.submit(&waiter, [&, i, offset] { results[i+offset] = verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]); });
offset += rv.p.rangeSigs.size();
}
}
if (!proofs.empty() && !verBulletproof(proofs))
{
LOG_PRINT_L1("Aggregate range proof verified failed");
return false;
}
if (!waiter.wait())
return false;
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("Range proof verified failed for proof " << i);
return false;
}
}
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRctSemanticsSimple: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRctSemanticsSimple, but not an actual exception");
return false;
}
}
bool verRctSemanticsSimple(const rctSig & rv)
{
return verRctSemanticsSimple(std::vector<const rctSig*>(1, &rv));
}
//ver RingCT simple
//assumes only post-rct style inputs (at least for max anonymity)
bool verRctNonSemanticsSimple(const rctSig & rv) {
try
{
PERF_TIMER(verRctNonSemanticsSimple);
CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG,
false, "verRctNonSemanticsSimple called on non simple rctSig");
const bool bulletproof = is_rct_bulletproof(rv.type);
// semantics check is early, and mixRing/MGs aren't resolved yet
if (bulletproof)
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.p.pseudoOuts and mixRing");
else
CHECK_AND_ASSERT_MES(rv.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.pseudoOuts and mixRing");
const size_t threads = std::max(rv.outPk.size(), rv.mixRing.size());
std::deque<bool> results(threads);
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter(tpool);
const keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts;
const key message = get_pre_mlsag_hash(rv, hw::get_device("default"));
results.clear();
results.resize(rv.mixRing.size());
for (size_t i = 0 ; i < rv.mixRing.size() ; i++) {
tpool.submit(&waiter, [&, i] {
if (rv.type == RCTTypeCLSAG)
{
results[i] = verRctCLSAGSimple(message, rv.p.CLSAGs[i], rv.mixRing[i], pseudoOuts[i]);
}
else
results[i] = verRctMGSimple(message, rv.p.MGs[i], rv.mixRing[i], pseudoOuts[i]);
});
}
if (!waiter.wait())
return false;
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("verRctMGSimple/verRctCLSAGSimple failed for input " << i);
return false;
}
}
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRctNonSemanticsSimple: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRctNonSemanticsSimple, but not an actual exception");
return false;
}
}
//RingCT protocol
//genRct:
// creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the
// columns that are claimed as inputs, and that the sum of inputs = sum of outputs.
// Also contains masked "amount" and "mask" so the receiver can see how much they received
//verRct:
// verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct
//decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1)
// uses the attached ecdh info to find the amounts represented by each output commitment
// must know the destination private key to find the correct amount, else will return a random number
xmr_amount decodeRct(const rctSig & rv, const key & sk, unsigned int i, key & mask, hw::device &hwdev) {
CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull, false, "decodeRct called on non-full rctSig");
CHECK_AND_ASSERT_THROW_MES(i < rv.ecdhInfo.size(), "Bad index");
CHECK_AND_ASSERT_THROW_MES(rv.outPk.size() == rv.ecdhInfo.size(), "Mismatched sizes of rv.outPk and rv.ecdhInfo");
//mask amount and mask
ecdhTuple ecdh_info = rv.ecdhInfo[i];
hwdev.ecdhDecode(ecdh_info, sk, rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG);
mask = ecdh_info.mask;
key amount = ecdh_info.amount;
key C = rv.outPk[i].mask;
DP("C");
DP(C);
key Ctmp;
CHECK_AND_ASSERT_THROW_MES(sc_check(mask.bytes) == 0, "warning, bad ECDH mask");
CHECK_AND_ASSERT_THROW_MES(sc_check(amount.bytes) == 0, "warning, bad ECDH amount");
addKeys2(Ctmp, mask, amount, H);
DP("Ctmp");
DP(Ctmp);
if (equalKeys(C, Ctmp) == false) {
CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend");
}
return h2d(amount);
}
xmr_amount decodeRct(const rctSig & rv, const key & sk, unsigned int i, hw::device &hwdev) {
key mask;
return decodeRct(rv, sk, i, mask, hwdev);
}
xmr_amount decodeRctSimple(const rctSig & rv, const key & sk, unsigned int i, key &mask, hw::device &hwdev) {
CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG, false, "decodeRct called on non simple rctSig");
CHECK_AND_ASSERT_THROW_MES(i < rv.ecdhInfo.size(), "Bad index");
CHECK_AND_ASSERT_THROW_MES(rv.outPk.size() == rv.ecdhInfo.size(), "Mismatched sizes of rv.outPk and rv.ecdhInfo");
//mask amount and mask
ecdhTuple ecdh_info = rv.ecdhInfo[i];
hwdev.ecdhDecode(ecdh_info, sk, rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG);
mask = ecdh_info.mask;
key amount = ecdh_info.amount;
key C = rv.outPk[i].mask;
DP("C");
DP(C);
key Ctmp;
CHECK_AND_ASSERT_THROW_MES(sc_check(mask.bytes) == 0, "warning, bad ECDH mask");
CHECK_AND_ASSERT_THROW_MES(sc_check(amount.bytes) == 0, "warning, bad ECDH amount");
addKeys2(Ctmp, mask, amount, H);
DP("Ctmp");
DP(Ctmp);
if (equalKeys(C, Ctmp) == false) {
CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend");
}
return h2d(amount);
}
xmr_amount decodeRctSimple(const rctSig & rv, const key & sk, unsigned int i, hw::device &hwdev) {
key mask;
return decodeRctSimple(rv, sk, i, mask, hwdev);
}
bool signMultisigMLSAG(rctSig &rv, const std::vector<unsigned int> &indices, const keyV &k, const multisig_out &msout, const key &secret_key) {
CHECK_AND_ASSERT_MES(rv.type == RCTTypeFull || rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2,
false, "unsupported rct type");
CHECK_AND_ASSERT_MES(indices.size() == k.size(), false, "Mismatched k/indices sizes");
CHECK_AND_ASSERT_MES(k.size() == rv.p.MGs.size(), false, "Mismatched k/MGs size");
CHECK_AND_ASSERT_MES(k.size() == msout.c.size(), false, "Mismatched k/msout.c size");
CHECK_AND_ASSERT_MES(rv.p.CLSAGs.empty(), false, "CLSAGs not empty for MLSAGs");
if (rv.type == RCTTypeFull)
{
CHECK_AND_ASSERT_MES(rv.p.MGs.size() == 1, false, "MGs not a single element");
}
for (size_t n = 0; n < indices.size(); ++n) {
CHECK_AND_ASSERT_MES(indices[n] < rv.p.MGs[n].ss.size(), false, "Index out of range");
CHECK_AND_ASSERT_MES(!rv.p.MGs[n].ss[indices[n]].empty(), false, "empty ss line");
}
// MLSAG: each player contributes a share to the secret-index ss: k - cc*secret_key_share
// cc: msout.c[n], secret_key_share: secret_key
for (size_t n = 0; n < indices.size(); ++n) {
rct::key diff;
sc_mulsub(diff.bytes, msout.c[n].bytes, secret_key.bytes, k[n].bytes);
sc_add(rv.p.MGs[n].ss[indices[n]][0].bytes, rv.p.MGs[n].ss[indices[n]][0].bytes, diff.bytes);
}
return true;
}
bool signMultisigCLSAG(rctSig &rv, const std::vector<unsigned int> &indices, const keyV &k, const multisig_out &msout, const key &secret_key) {
CHECK_AND_ASSERT_MES(rv.type == RCTTypeCLSAG, false, "unsupported rct type");
CHECK_AND_ASSERT_MES(indices.size() == k.size(), false, "Mismatched k/indices sizes");
CHECK_AND_ASSERT_MES(k.size() == rv.p.CLSAGs.size(), false, "Mismatched k/CLSAGs size");
CHECK_AND_ASSERT_MES(k.size() == msout.c.size(), false, "Mismatched k/msout.c size");
CHECK_AND_ASSERT_MES(rv.p.MGs.empty(), false, "MGs not empty for CLSAGs");
CHECK_AND_ASSERT_MES(msout.c.size() == msout.mu_p.size(), false, "Bad mu_p size");
for (size_t n = 0; n < indices.size(); ++n) {
CHECK_AND_ASSERT_MES(indices[n] < rv.p.CLSAGs[n].s.size(), false, "Index out of range");
}
// CLSAG: each player contributes a share to the secret-index ss: k - cc*mu_p*secret_key_share
// cc: msout.c[n], mu_p, msout.mu_p[n], secret_key_share: secret_key
for (size_t n = 0; n < indices.size(); ++n) {
rct::key diff, sk;
sc_mul(sk.bytes, msout.mu_p[n].bytes, secret_key.bytes);
sc_mulsub(diff.bytes, msout.c[n].bytes, sk.bytes, k[n].bytes);
sc_add(rv.p.CLSAGs[n].s[indices[n]].bytes, rv.p.CLSAGs[n].s[indices[n]].bytes, diff.bytes);
}
return true;
}
bool signMultisig(rctSig &rv, const std::vector<unsigned int> &indices, const keyV &k, const multisig_out &msout, const key &secret_key) {
if (rv.type == RCTTypeCLSAG)
return signMultisigCLSAG(rv, indices, k, msout, secret_key);
else
return signMultisigMLSAG(rv, indices, k, msout, secret_key);
}
}
| [
"76274154+71Zombie@users.noreply.github.com"
] | 76274154+71Zombie@users.noreply.github.com |
524ed1c0f268999faaca502ccde026e81daf51c6 | 99e1b09a00daa8069f5959ba65600a8914bcc7bb | /codetop/Leetcode199.二叉树的右视图.cpp | b6d002ef421cc5513468b2cb859612138d4083b3 | [
"MIT"
] | permissive | agedcat/interview_codehub | 0262093b4cc35365325520c755790d7bd6fa66cb | 0d915934a8d89a10943ef3e0ba8e528948433578 | refs/heads/master | 2023-08-22T05:53:44.554919 | 2021-10-21T09:41:01 | 2021-10-21T09:41:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,139 | cpp | /*
* @lc app=leetcode.cn id=199 lang=cpp
*
* [199] 二叉树的右视图
*/
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
// @lc code=start
/*
//* Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int>res;
if(root==nullptr) return {};
queue<TreeNode*>q;
q.push(root);
while(!q.empty())
{
int size=q.size();
for(int i=0;i<size;i++)
{
TreeNode* node=q.front();
q.pop();
if(i==size-1) res.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
}
return res;
}
};
// @lc code=end
| [
"2324261907@qq.com"
] | 2324261907@qq.com |
411b856e5017f37bfa6a4ffe64e0c77556ad9424 | d8a5d16139b67d57631f9b2d976434b3841448d4 | /Arduino/main/LightAnimationStep.h | 8d56816299d9576daa3c765ba2381ad93ac7611a | [] | no_license | ArthurRibeirox/rng-shrine | 9fddecd5567c4552786df25447fe37fcb3c503b2 | 7e3655c20bcc7fb3d119d0bbd40fbc14f734e61b | refs/heads/master | 2023-06-10T04:10:41.130185 | 2021-06-30T14:01:35 | 2021-06-30T14:01:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | #ifndef LightAnimationStep_h
#define LightAnimationStep_h
#include "FastLED.h"
class LightAnimationStep {
public:
LightAnimationStep(CRGB _startColor, int stepDuration, bool stepShouldLoop = false);
virtual void Start(long millis);
virtual CRGB GetCurrentColor(long millis);
bool ShouldFinish(long millis);
void Finish();
bool shouldLoop;
protected:
int duration;
long startTime;
CRGB startColor;
};
#endif
| [
"arthhur.ribeiro@gmail.com"
] | arthhur.ribeiro@gmail.com |
ec10118dd8d65ee5e65fd2bd2ca7c8504b52f4f6 | 84468e9a35c48e600044ac5518b92565cb964271 | /Tcp_Clinet/build-Tcp_clinet-Desktop_Qt_5_9_9_MSVC2015_64bit-Debug/debug/moc_mywidget.cpp | 3bcfd32bac69a3c1b603f61139c86728e08ed5fc | [] | no_license | yejhinfo/5GTcp | a971068bbbf360eb113f24431a778796468e0a07 | 77d5d0be9006059c57b00a50f1ab0a37a418393e | refs/heads/master | 2023-02-12T13:05:02.700627 | 2021-01-17T07:41:28 | 2021-01-17T07:41:28 | 330,338,969 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,778 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mywidget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.9)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../Tcp_Clinetsample/Tcp_clinet/mywidget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mywidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.9. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_myWidget_t {
QByteArrayData data[5];
char stringdata0[80];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_myWidget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_myWidget_t qt_meta_stringdata_myWidget = {
{
QT_MOC_LITERAL(0, 0, 8), // "myWidget"
QT_MOC_LITERAL(1, 9, 24), // "on_ButtonConnect_clicked"
QT_MOC_LITERAL(2, 34, 0), // ""
QT_MOC_LITERAL(3, 35, 21), // "on_ButtonSend_clicked"
QT_MOC_LITERAL(4, 57, 22) // "on_ButtonClose_clicked"
},
"myWidget\0on_ButtonConnect_clicked\0\0"
"on_ButtonSend_clicked\0on_ButtonClose_clicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_myWidget[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 29, 2, 0x08 /* Private */,
3, 0, 30, 2, 0x08 /* Private */,
4, 0, 31, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void myWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
myWidget *_t = static_cast<myWidget *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->on_ButtonConnect_clicked(); break;
case 1: _t->on_ButtonSend_clicked(); break;
case 2: _t->on_ButtonClose_clicked(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject myWidget::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_myWidget.data,
qt_meta_data_myWidget, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *myWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *myWidget::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_myWidget.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int myWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"yjh@stu.scau.edu.cn"
] | yjh@stu.scau.edu.cn |
6a232039c43ca585f1b49f40b6a3879d2b2f135c | 9178022b8d1dc9f510a950fd6d4c97c5639edf71 | /c++11/iterator/ostreamTest1.cpp | 2856fe31947d68862d436e9906128f4260958775 | [] | no_license | hanhiver/mycpp11 | f71ea9fbcb021763630dd05861c3226eb9457558 | deaebbde07bd153d2cd287af8c1b474f51f5d8a5 | refs/heads/master | 2021-06-21T16:33:29.668467 | 2021-03-23T07:00:09 | 2021-03-23T07:00:09 | 204,598,282 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 465 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
ostream_iterator<int> intWriter(cout, "\n");
*intWriter = 42;
intWriter ++;
*intWriter = 77;
intWriter ++;
*intWriter = -5;
vector<int> coll = {1, 2, 3, 4, 5, 6, 7, 8, 9};
copy(coll.cbegin(), coll.cend(), ostream_iterator<int>(cout));
cout << endl;
copy(coll.cbegin(), coll.cend(), ostream_iterator<int>(cout, " < "));
cout << endl;
} | [
"handongfr@163.com"
] | handongfr@163.com |
20ff558c4159531b0304a410b27846eaea3393a0 | fcebca7c5725c44796d90a7158350e52aa61cc72 | /src/model/tables/MixedTwoPathTable.cpp | a1d67e5b1434c62b6b64faca1f73e95eaa5a19e7 | [] | no_license | kkc-krish/RSiena | c082a0e1c3698bffd68734387347c4de7981698f | 4f9d65392367703150e6285291a9b41d23e647c6 | refs/heads/master | 2020-12-24T19:59:58.649070 | 2013-06-18T00:00:00 | 2013-06-18T00:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,531 | cpp | /******************************************************************************
* SIENA: Simulation Investigation for Empirical Network Analysis
*
* Web: http://www.stats.ox.ac.uk/~snijders/siena/
*
* File: MixedTwoPathTable.cpp
*
* Description: This file contains the implementation of the MixedTwoPathTable
* class.
*****************************************************************************/
#include <R_ext/Print.h>
#include "MixedTwoPathTable.h"
#include "network/IncidentTieIterator.h"
#include "network/CommonNeighborIterator.h"
#include "network/OneModeNetwork.h"
namespace siena
{
// ----------------------------------------------------------------------------
// Section: Initialization
// ----------------------------------------------------------------------------
/**
* Creates a new table for storing two-paths with the specified directions for
* the first and the second tie.
*/
MixedTwoPathTable::MixedTwoPathTable(TwoNetworkCache * pOwner,
Direction firstStepDirection,
Direction secondStepDirection) : MixedEgocentricConfigurationTable(pOwner)
{
this->lfirstStepDirection = firstStepDirection;
this->lsecondStepDirection = secondStepDirection;
}
// ----------------------------------------------------------------------------
// Section: ConfigurationTable implementation
// ----------------------------------------------------------------------------
/**
* Calculates the number of generalized two-paths between the ego and all
* other actors.
*/
void MixedTwoPathTable::calculate()
{
// Reset the counters to zeroes
this->reset();
this->performFirstStep(
this->pFirstNetwork()->outTies(this->ego()));
}
/**
* Performs the first step by iterating over the actors of the given
* iterator and invoking the method for the second step.
*/
template<class Iterator>
void MixedTwoPathTable::performFirstStep(Iterator iter)
{
// TODO: Using templates here is a bad design. It's because
// IncidentTieIterator and CommonNeighborIterator have no
// common base class.
// Try out all possible first steps
while (iter.valid())
{
int middleActor = iter.actor();
iter.next();
this->performSecondStep(
this->pSecondNetwork()->outTies(middleActor));
}
}
/**
* Performs the second step by iterating over the actors of the given
* iterator and incrementing their values that are stored in this table.
*/
template<class Iterator>
void MixedTwoPathTable::performSecondStep(Iterator iter)
{
while (iter.valid())
{
this->ltable[iter.actor()]++;
iter.next();
}
}
}
| [
"csardi.gabor@gmail.com"
] | csardi.gabor@gmail.com |
8809fb0c3388e114aed0e5befa723640ad42aa37 | 327cb9c6448805d69eb1de0c46a9dd5d83ec932b | /Code/led_game_pong/led_game_pong.ino | 89c18c482e004a728baaaf3efedb32bf6323eed9 | [
"MIT"
] | permissive | Jaknil/LED_games | 79667fd34186b297d6234a2d2cd102f06ea44272 | d55dce86a7d4207342a8984b21e3724c30f30af4 | refs/heads/master | 2023-01-11T18:24:02.502409 | 2023-01-06T06:48:26 | 2023-01-06T06:48:26 | 277,350,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,370 | ino | /*
Pong game for a 16x16 adressabel RGB LED matrix.
Uses two encoders as inputs.
My first attempt at using classes for Arduino
Documentation at
https://github.com/Jaknil/LED_games/blob/master/README.md
*/
#include "encoder.h"
#include "timer.h"
#include <FastLED.h>
//Create our encoders, name(leftpin, rightpin)
Encoder ENC1(3,6);
Encoder ENC2(2,5);
//Create timer
Timer drawInterval(50);
//move to ball? note in ball when last updated and use timer internally there?
const int initialBallSpeed = 350;
const int minBallSpeed = 50;
Timer ballSpeed(initialBallSpeed); //increases for each bounce
//Matrix
// Params for width and height
const uint8_t kMatrixWidth = 16;
const uint8_t kMatrixHeight = 16;
const bool kMatrixSerpentineLayout = true;
// Define the array of leds
#define NUM_LEDS (kMatrixWidth * kMatrixHeight)
CRGB leds_plus_safety_pixel[ NUM_LEDS + 1];
CRGB* const leds( leds_plus_safety_pixel + 1);
#define BRIGHTNESS 15
//OUTPUTS
#define DATA_PIN 12
//GAME STARTS HERE
class Ball{
private:
public:
int x = 5;
int y = 7;
int veloX = 1;
int veloY = 1;
int oldX = x;
int oldY = y;
int acc = -50; //how much time to reduce the increment with
void bounceY(){
veloY = veloY*(-1);
}
void inc(){
oldX=x;
x=x+veloX;
oldY=y;
y=y+veloY;
//leave collide wall in, easier for now? split out win lose
if(x>=kMatrixWidth-1 || x==0){
veloX = veloX*(-1);
//Serial.println("game lost, unclear who");
}
if(y>=kMatrixHeight-1 || y==0){
veloY = veloY*(-1);
//Serial.println("Y max/mined");
}
}
//Check collission ball to an line in x direction, starting on objX, objY coord and having i length
bool collide(int objX, int objY, int objLength){
for(int i = 0; i < objLength; i++){
if(x==objX+i && y == objY){
return 1;
}
}
return 0;
}
}
;
class Paddle{
private:
public:
int x = 1;
int oldX = x;
int y = 2;
int leng = 5;
};
//Create the game pieces
Paddle player1;
Paddle player2;
Ball ball1;
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
//Matrix
FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS); // GRB ordering is typical
FastLED.setBrightness( BRIGHTNESS );
FastLED.setMaxPowerInVoltsAndMilliamps(5,500); //500mA max
clearAllLeds(); //
// sanity check delay - allows reprogramming if accidently blowing power w/leds
delay(200);
//setup players
player1.x=1;
player1.y=13;
player2.x=1;
player2.y=2;
}
//Update a value while keeping it inside bounds
int applyBounds(int value, int change, int lowLimit, int highLimit){
//apply change
value = value + change;
//check bounds
if(value < lowLimit){
value = lowLimit;
}
if(value > highLimit){
value = highLimit;
}
return value;
}
void loop() {
if(ballSpeed.expired()){
ball1.inc();
//check collissions in next step by moving paddle towards ball
if(ball1.collide(player1.x-ball1.veloX,player1.y-ball1.veloY,player1.leng)){
ball1.bounceY();
ballSpeed.interval = applyBounds(ballSpeed.interval, ball1.acc,minBallSpeed,initialBallSpeed);
}
else if(ball1.collide(player2.x-ball1.veloX,player2.y-ball1.veloY,player2.leng)){
ball1.bounceY();
ballSpeed.interval = applyBounds(ballSpeed.interval, ball1.acc,minBallSpeed,initialBallSpeed);
}
//update ball positon on led matrix
leds[XYsafe(ball1.oldX,ball1.oldY)]=CRGB::Black; //erase old ball
leds[XYsafe(ball1.x,ball1.y)]=CRGB::Blue; //add new ball
//update paddle to not "loose" leds when paddle goes on top of ball position
fill1(player1.x); //Update paddle pos on led matrix
fill2(player2.x); //Update paddle pos on led matrix
}
//increment the encoders, as fast as possible
ENC1.inc();
ENC2.inc();
if(ENC1.checkTrigger() || ENC2.checkTrigger()){ //when there is new data any encoder
// Set player positions to match encoders
player1.x= ENC1.countFull;
player2.x= ENC2.countFull;
//SUGGESTION: perhaps better to return diff from encoder and keep the bounds in the paddle for a more logical structure?
//make method instead?
fill1(player1.x); //Update paddle pos on led matrix
fill2(player2.x); //Update paddle pos on led matrix
}
if (drawInterval.expired()){ //if enough time passed
FastLED.show();
}
} //END LOOP
//FUNCTIONS
//IN WORK
void drawPlayer(int x,int y, bool kill){
if(kill){
for(int i = 0; i < player1.leng; i++) { //fix length
leds[ XYsafe( i+x, y) ] = CRGB::Black;
}} else{
for(int i = 0; i < player1.leng; i++) {
leds[ XYsafe( i+x, player1.y) ] = CRGB::Yellow;
}
}
}
//Make this work better!! LOOK AT MATRIX DATA, usable or make own from bool?
void fill1(int x){
//delete old paddle
for(int i = 0; i < player1.leng; i++) {
leds[ XYsafe( i+player1.oldX, player1.y) ] = CRGB::Black;
}
//fill new paddle
for(int i = 0; i < player1.leng; i++) {
leds[ XYsafe( i+player1.x, player1.y) ] = CRGB::Red;
}
player1.oldX=x;
}
//Make this work better!! LOOK AT MATRIX DATA, usable or make own from bool?
void fill2(int x){
//delete old paddle
for(int i = 0; i < player1.leng; i++) {
leds[ XYsafe( i+player2.oldX, player2.y) ] = CRGB::Black;
}
//fill new paddle
for(int i = 0; i < player2.leng; i++) {
leds[ XYsafe( i+player2.x, player2.y) ] = CRGB::Red;
}
player2.oldX=x;
}
| [
"jakob.a.nilsson@gmail.com"
] | jakob.a.nilsson@gmail.com |
ba896d524a7e139ce9396304560599537e67b22f | 167a560af8f57f7e4350a199be8b2d9efb97ebcf | /Semestru I/IP/Lab 2/secv_nr_identice/main.cpp | ed5227da30c5335f954e1a3c72f4258c7e90432f | [] | no_license | Andreea15B/Facultate_an_I | 681fe3b33c1917f7d10b45bc2b14f7bc31c58601 | 724d5a74e1b3a5a027cf5cda5b4797c9f3f710cd | refs/heads/master | 2021-01-03T14:44:16.743901 | 2020-02-12T20:45:21 | 2020-02-12T20:45:21 | 240,110,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | cpp | #include <iostream>
#include <fstream>
using namespace std;
ifstream fin("secv.in");
int main()
{
int n,i,a,x,lung=1,l_max=1,ind_max=0,nr;
fin>>n>>a;
for(i=2;i<=n;i++) {
fin>>x;
if(a==x) lung++;
else {
if(lung>l_max) {
l_max=lung;
ind_max=i-lung;
nr=a;
}
lung=1;
}
a=x;
}
cout<<l_max<<" "<<ind_max<<" "<<nr;
return 0;
}
| [
"andreea.bucataru15@yahoo.ro"
] | andreea.bucataru15@yahoo.ro |
f8f0d5b9e915506f6875fa7fee7e59c31afd9b52 | b0dd7779c225971e71ae12c1093dc75ed9889921 | /libs/geometry/test/algorithms/test_simplify.hpp | 585233547363a16cc61781d490f033910c66150f | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 2,981 | hpp | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_TEST_SIMPLIFY_HPP
#define BOOST_GEOMETRY_TEST_SIMPLIFY_HPP
// Test-functionality, shared between single and multi tests
#include <geometry_test_common.hpp>
#include <boost/geometry/algorithms/simplify.hpp>
#include <boost/geometry/algorithms/distance.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/io/wkt/wkt.hpp>
template <typename Tag, typename Geometry>
struct test_inserter
{
static void apply(Geometry& , std::string const& , double )
{}
};
template <typename Geometry>
struct test_inserter<bg::linestring_tag, Geometry>
{
static void apply(Geometry& geometry, std::string const& expected, double distance)
{
Geometry simplified;
bg::detail::simplify::simplify_insert(geometry,
std::back_inserter(simplified), distance);
std::ostringstream out;
out << bg::wkt(simplified);
BOOST_CHECK_EQUAL(out.str(), expected);
}
};
template <typename Geometry>
void test_geometry(std::string const& wkt, std::string const& expected, double distance)
{
Geometry geometry, simplified;
// Generate polygon using only integer coordinates and obvious results
// Polygon is a hexagon, having one extra point (2,1) on a line which should be filtered out.
bg::read_wkt(wkt, geometry);
bg::simplify(geometry, simplified, distance);
{
std::ostringstream out;
out << bg::wkt(simplified);
BOOST_CHECK_MESSAGE(out.str() == expected,
"simplify: " << bg::wkt(geometry)
<< " expected " << expected
<< " got " << bg::wkt(simplified));
}
// Check using user-specified strategy
typedef typename bg::point_type<Geometry>::type point_type;
typedef typename bg::cs_tag<point_type>::type tag;
typedef bg::strategy::distance::projected_point
<
point_type,
point_type
> strategy;
typedef bg::strategy::simplify::douglas_peucker
<
point_type,
strategy
> simplify_strategy_type;
BOOST_CONCEPT_ASSERT( (bg::concept::SimplifyStrategy<simplify_strategy_type>) );
bg::simplify(geometry, simplified, distance, simplify_strategy_type());
{
std::ostringstream out;
out << bg::wkt(simplified);
BOOST_CHECK_EQUAL(out.str(), expected);
}
// Check inserter (if applicable)
test_inserter
<
typename bg::tag<Geometry>::type,
Geometry
>::apply(geometry, expected, distance);
}
#endif
| [
"tvaneerd@rim.com"
] | tvaneerd@rim.com |
795b0fab3e1a0c5b60868de262281f28eb6c73ce | 612325535126eaddebc230d8c27af095c8e5cc2f | /src/net/base/backoff_entry.h | 787ad44ad02b6cf8571fa099ae4e9c93ca03f84b | [
"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 | 5,136 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_BASE_BACKOFF_ENTRY_H_
#define NET_BASE_BACKOFF_ENTRY_H_
#include <stdint.h>
#include "base/macros.h"
#include "base/threading/non_thread_safe.h"
#include "base/time/time.h"
#include "net/base/net_export.h"
namespace base {
class TickClock;
}
namespace net {
// Provides the core logic needed for randomized exponential back-off
// on requests to a given resource, given a back-off policy.
//
// This utility class knows nothing about network specifics; it is
// intended for reuse in various networking scenarios.
class NET_EXPORT BackoffEntry : NON_EXPORTED_BASE(public base::NonThreadSafe) {
public:
// The set of parameters that define a back-off policy. When modifying this,
// increment SERIALIZATION_VERSION_NUMBER in backoff_entry_serializer.cc.
struct Policy {
// Number of initial errors (in sequence) to ignore before applying
// exponential back-off rules.
int num_errors_to_ignore;
// Initial delay. The interpretation of this value depends on
// always_use_initial_delay. It's either how long we wait between
// requests before backoff starts, or how much we delay the first request
// after backoff starts.
int initial_delay_ms;
// Factor by which the waiting time will be multiplied.
double multiply_factor;
// Fuzzing percentage. ex: 10% will spread requests randomly
// between 90%-100% of the calculated time.
double jitter_factor;
// Maximum amount of time we are willing to delay our request, -1
// for no maximum.
int64_t maximum_backoff_ms;
// Time to keep an entry from being discarded even when it
// has no significant state, -1 to never discard.
int64_t entry_lifetime_ms;
// If true, we always use a delay of initial_delay_ms, even before
// we've seen num_errors_to_ignore errors. Otherwise, initial_delay_ms
// is the first delay once we start exponential backoff.
//
// So if we're ignoring 1 error, we'll see (N, N, Nm, Nm^2, ...) if true,
// and (0, 0, N, Nm, ...) when false, where N is initial_backoff_ms and
// m is multiply_factor, assuming we've already seen one success.
bool always_use_initial_delay;
};
// Lifetime of policy must enclose lifetime of BackoffEntry. The
// pointer must be valid but is not dereferenced during construction.
explicit BackoffEntry(const Policy* policy);
// Lifetime of policy and clock must enclose lifetime of BackoffEntry.
// |policy| pointer must be valid but isn't dereferenced during construction.
// |clock| pointer may be null.
BackoffEntry(const Policy* policy, base::TickClock* clock);
virtual ~BackoffEntry();
// Inform this item that a request for the network resource it is
// tracking was made, and whether it failed or succeeded.
void InformOfRequest(bool succeeded);
// Returns true if a request for the resource this item tracks should
// be rejected at the present time due to exponential back-off policy.
bool ShouldRejectRequest() const;
// Returns the absolute time after which this entry (given its present
// state) will no longer reject requests.
base::TimeTicks GetReleaseTime() const;
// Returns the time until a request can be sent (will be zero if the release
// time is in the past).
base::TimeDelta GetTimeUntilRelease() const;
// Converts |backoff_duration| to a release time, by adding it to
// GetTimeTicksNow(), limited by maximum_backoff_ms.
base::TimeTicks BackoffDurationToReleaseTime(
base::TimeDelta backoff_duration) const;
// Causes this object reject requests until the specified absolute time.
// This can be used to e.g. implement support for a Retry-After header.
void SetCustomReleaseTime(const base::TimeTicks& release_time);
// Returns true if this object has no significant state (i.e. you could
// just as well start with a fresh BackoffEntry object), and hasn't
// had for Policy::entry_lifetime_ms.
bool CanDiscard() const;
// Resets this entry to a fresh (as if just constructed) state.
void Reset();
// Returns the failure count for this entry.
int failure_count() const { return failure_count_; }
// Equivalent to TimeTicks::Now(), using clock_ if provided.
base::TimeTicks GetTimeTicksNow() const;
private:
// Calculates when requests should again be allowed through.
base::TimeTicks CalculateReleaseTime() const;
// Timestamp calculated by the exponential back-off algorithm at which we are
// allowed to start sending requests again.
base::TimeTicks exponential_backoff_release_time_;
// Counts request errors; decremented on success.
int failure_count_;
const Policy* const policy_; // Not owned.
base::TickClock* const clock_; // Not owned.
DISALLOW_COPY_AND_ASSIGN(BackoffEntry);
};
} // namespace net
#endif // NET_BASE_BACKOFF_ENTRY_H_
| [
"2100639007@qq.com"
] | 2100639007@qq.com |
74833abcf2eb66660ff5e2151eb7941393ec0e91 | 2dba1dc8e5c62631ad9801222d8a34b72b8a5635 | /UVa Online Judge/volume004/406 Prime Cuts/program.cpp | 0aa44459c802d2837da71bc07d201923ee4e2e0f | [] | no_license | dingswork/Code | f9e875417238efd04294b86c0b4261b4da867923 | 669139b70d0dbc8eae238d52aa7b8c0782fb9003 | refs/heads/master | 2021-01-24T16:52:10.703835 | 2018-02-27T14:07:25 | 2018-02-27T14:07:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,960 | cpp | // Prime Cuts
// UVa ID: 406
// Verdict: Accepted
// Submission Date: 2016-07-13
// UVa Run Time: 0.030s
//
// 版权所有(C)2016,邱秋。metaphysis # yeah dot net
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
ios::sync_with_stdio(false);
vector<bool> primes(2000, true);
for (int i = 2; i <= 1200; i++)
if (primes[i])
for (int j = i + i; j <= 1200; j += i)
primes[j] = false;
vector<int> prime_numbers;
prime_numbers.push_back(1);
for (int i = 2; i <= 1200; i++)
if (primes[i])
prime_numbers.push_back(i);
//for (auto p : prime_numbers) cout << p << " ";
//cout << endl;
int N, C;
while (cin >> N >> C)
{
cout << N << " " << C << ":";
int count = upper_bound(prime_numbers.begin(), prime_numbers.end(), N) - prime_numbers.begin();
int cuts = 0;
if (count % 2 == 0) cuts = 2 * C;
else cuts = 2 * C - 1;
if (cuts >= count)
{
for (int i = 0; i < count; i++)
cout << " " << prime_numbers[i];
cout << endl;
}
else
{
if (count % 2 == 0)
{
for (int i = count / 2 - C; i <= count / 2 + C - 1; i++)
cout << " " << prime_numbers[i];
cout << endl;
}
else
{
for (int i = count / 2 - C + 1; i <= count / 2 + C - 1; i++)
cout << " " << prime_numbers[i];
cout << endl;
}
}
cout << endl;
}
return 0;
}
| [
"metaphysis@yeah.net"
] | metaphysis@yeah.net |
18f7ef78f9a6e8b971236c98ca75443afab3b53d | 0774ffb43d4c5a0427c7dd54c1a796a2c9649af5 | /exercicios_dev-c++/ALGORITMOS/Aula 8/aula8_alg-estruturasDeRepeticaoControleContagemRegressiva.cpp | 886003ed7b0d0d4192adee5da65417a1d418cab6 | [
"Apache-2.0"
] | permissive | lauracarlotta/repositorio_atividades_faculdade | 0d766e0f1f997a1da808c1f2aec421c84a992675 | a906597d7b34ee7a1eef3d00f4b634e7475b6b68 | refs/heads/master | 2022-11-06T07:06:00.803756 | 2020-06-18T19:21:43 | 2020-06-18T19:21:43 | 273,322,121 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 278 | cpp | #include <iostream>
using namespace std;
int main ()
{
int regressiva, contador;
cout << "A partir de que número você quer que comece a contagem regressiva? \n";
cin >> regressiva;
for (contador = regressiva; contador >= 0; contador--)
{
cout << contador << "\n";
}
}
| [
"carlotta.custodio@gmail.com"
] | carlotta.custodio@gmail.com |
7eab5bb721513c40bfc67d83fc90970252882202 | c7114fd0d134c6a2a26ea6824f9df74ff87c7a22 | /WizapplyGameLibrary/GameLibrary/Socket/CSocketTCPServer.cpp | b2e6f491817e96ac9827e8f2d36f97f7c3e256f6 | [] | no_license | ttoApps/wizapply_library_by_cpp_study | 1a420d858c40a45c739c09560091eead681a1ac7 | 33e557429411f19b81700069820b0a5838989837 | refs/heads/master | 2021-03-12T19:55:07.866819 | 2013-02-22T09:45:26 | 2013-02-22T09:45:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | //
// CSocketTCPServer.cpp
// WizapplyGameSDK
//
// Created by on 13/02/03.
// Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//
#include "CSocketTCPServer.h"
| [
"ttoapps@gmail.com"
] | ttoapps@gmail.com |
02447ec784a7953719d8e72aae996f5d7a7dd83a | 777a75e6ed0934c193aece9de4421f8d8db01aac | /src/Providers/UNIXProviders/Hdr8021PService/UNIX_Hdr8021PService_HPUX.hpp | 57e4d9d70480ac7542b7c516227059e3d6d1f9aa | [
"MIT"
] | permissive | brunolauze/openpegasus-providers-old | 20fc13958016e35dc4d87f93d1999db0eae9010a | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | refs/heads/master | 2021-01-01T20:05:44.559362 | 2014-04-30T17:50:06 | 2014-04-30T17:50:06 | 19,132,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,327 | hpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
UNIX_Hdr8021PService::UNIX_Hdr8021PService(void)
{
}
UNIX_Hdr8021PService::~UNIX_Hdr8021PService(void)
{
}
Boolean UNIX_Hdr8021PService::getInstanceID(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
return true;
}
String UNIX_Hdr8021PService::getInstanceID() const
{
return String ("");
}
Boolean UNIX_Hdr8021PService::getCaption(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CAPTION, getCaption());
return true;
}
String UNIX_Hdr8021PService::getCaption() const
{
return String ("");
}
Boolean UNIX_Hdr8021PService::getDescription(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
return true;
}
String UNIX_Hdr8021PService::getDescription() const
{
return String ("");
}
Boolean UNIX_Hdr8021PService::getElementName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
return true;
}
String UNIX_Hdr8021PService::getElementName() const
{
return String("Hdr8021PService");
}
Boolean UNIX_Hdr8021PService::getInstallDate(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTALL_DATE, getInstallDate());
return true;
}
CIMDateTime UNIX_Hdr8021PService::getInstallDate() const
{
struct tm* clock; // create a time structure
time_t val = time(NULL);
clock = gmtime(&(val)); // Get the last modified time and put it into the time structure
return CIMDateTime(
clock->tm_year + 1900,
clock->tm_mon + 1,
clock->tm_mday,
clock->tm_hour,
clock->tm_min,
clock->tm_sec,
0,0,
clock->tm_gmtoff);
}
Boolean UNIX_Hdr8021PService::getName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_NAME, getName());
return true;
}
String UNIX_Hdr8021PService::getName() const
{
return String ("");
}
Boolean UNIX_Hdr8021PService::getOperationalStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OPERATIONAL_STATUS, getOperationalStatus());
return true;
}
Array<Uint16> UNIX_Hdr8021PService::getOperationalStatus() const
{
Array<Uint16> as;
return as;
}
Boolean UNIX_Hdr8021PService::getStatusDescriptions(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STATUS_DESCRIPTIONS, getStatusDescriptions());
return true;
}
Array<String> UNIX_Hdr8021PService::getStatusDescriptions() const
{
Array<String> as;
return as;
}
Boolean UNIX_Hdr8021PService::getStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STATUS, getStatus());
return true;
}
String UNIX_Hdr8021PService::getStatus() const
{
return String(DEFAULT_STATUS);
}
Boolean UNIX_Hdr8021PService::getHealthState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_HEALTH_STATE, getHealthState());
return true;
}
Uint16 UNIX_Hdr8021PService::getHealthState() const
{
return Uint16(DEFAULT_HEALTH_STATE);
}
Boolean UNIX_Hdr8021PService::getCommunicationStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_COMMUNICATION_STATUS, getCommunicationStatus());
return true;
}
Uint16 UNIX_Hdr8021PService::getCommunicationStatus() const
{
return Uint16(0);
}
Boolean UNIX_Hdr8021PService::getDetailedStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DETAILED_STATUS, getDetailedStatus());
return true;
}
Uint16 UNIX_Hdr8021PService::getDetailedStatus() const
{
return Uint16(0);
}
Boolean UNIX_Hdr8021PService::getOperatingStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OPERATING_STATUS, getOperatingStatus());
return true;
}
Uint16 UNIX_Hdr8021PService::getOperatingStatus() const
{
return Uint16(DEFAULT_OPERATING_STATUS);
}
Boolean UNIX_Hdr8021PService::getPrimaryStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_STATUS, getPrimaryStatus());
return true;
}
Uint16 UNIX_Hdr8021PService::getPrimaryStatus() const
{
return Uint16(DEFAULT_PRIMARY_STATUS);
}
Boolean UNIX_Hdr8021PService::getEnabledState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ENABLED_STATE, getEnabledState());
return true;
}
Uint16 UNIX_Hdr8021PService::getEnabledState() const
{
return Uint16(DEFAULT_ENABLED_STATE);
}
Boolean UNIX_Hdr8021PService::getOtherEnabledState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OTHER_ENABLED_STATE, getOtherEnabledState());
return true;
}
String UNIX_Hdr8021PService::getOtherEnabledState() const
{
return String ("");
}
Boolean UNIX_Hdr8021PService::getRequestedState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_REQUESTED_STATE, getRequestedState());
return true;
}
Uint16 UNIX_Hdr8021PService::getRequestedState() const
{
return Uint16(0);
}
Boolean UNIX_Hdr8021PService::getEnabledDefault(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ENABLED_DEFAULT, getEnabledDefault());
return true;
}
Uint16 UNIX_Hdr8021PService::getEnabledDefault() const
{
return Uint16(0);
}
Boolean UNIX_Hdr8021PService::getTimeOfLastStateChange(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_TIME_OF_LAST_STATE_CHANGE, getTimeOfLastStateChange());
return true;
}
CIMDateTime UNIX_Hdr8021PService::getTimeOfLastStateChange() const
{
struct tm* clock; // create a time structure
time_t val = time(NULL);
clock = gmtime(&(val)); // Get the last modified time and put it into the time structure
return CIMDateTime(
clock->tm_year + 1900,
clock->tm_mon + 1,
clock->tm_mday,
clock->tm_hour,
clock->tm_min,
clock->tm_sec,
0,0,
clock->tm_gmtoff);
}
Boolean UNIX_Hdr8021PService::getAvailableRequestedStates(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_AVAILABLE_REQUESTED_STATES, getAvailableRequestedStates());
return true;
}
Array<Uint16> UNIX_Hdr8021PService::getAvailableRequestedStates() const
{
Array<Uint16> as;
return as;
}
Boolean UNIX_Hdr8021PService::getTransitioningToState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_TRANSITIONING_TO_STATE, getTransitioningToState());
return true;
}
Uint16 UNIX_Hdr8021PService::getTransitioningToState() const
{
return Uint16(0);
}
Boolean UNIX_Hdr8021PService::getSystemCreationClassName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SYSTEM_CREATION_CLASS_NAME, getSystemCreationClassName());
return true;
}
String UNIX_Hdr8021PService::getSystemCreationClassName() const
{
return String("UNIX_ComputerSystem");
}
Boolean UNIX_Hdr8021PService::getSystemName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SYSTEM_NAME, getSystemName());
return true;
}
String UNIX_Hdr8021PService::getSystemName() const
{
return CIMHelper::HostName;
}
Boolean UNIX_Hdr8021PService::getCreationClassName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CREATION_CLASS_NAME, getCreationClassName());
return true;
}
String UNIX_Hdr8021PService::getCreationClassName() const
{
return String("UNIX_Hdr8021PService");
}
Boolean UNIX_Hdr8021PService::getPrimaryOwnerName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_OWNER_NAME, getPrimaryOwnerName());
return true;
}
String UNIX_Hdr8021PService::getPrimaryOwnerName() const
{
return String ("");
}
Boolean UNIX_Hdr8021PService::getPrimaryOwnerContact(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_OWNER_CONTACT, getPrimaryOwnerContact());
return true;
}
String UNIX_Hdr8021PService::getPrimaryOwnerContact() const
{
return String ("");
}
Boolean UNIX_Hdr8021PService::getStartMode(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_START_MODE, getStartMode());
return true;
}
String UNIX_Hdr8021PService::getStartMode() const
{
return String ("");
}
Boolean UNIX_Hdr8021PService::getStarted(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STARTED, getStarted());
return true;
}
Boolean UNIX_Hdr8021PService::getStarted() const
{
return Boolean(false);
}
Boolean UNIX_Hdr8021PService::getPriorityValue(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIORITY_VALUE, getPriorityValue());
return true;
}
Uint8 UNIX_Hdr8021PService::getPriorityValue() const
{
return Uint8(0);
}
Boolean UNIX_Hdr8021PService::initialize()
{
return false;
}
Boolean UNIX_Hdr8021PService::load(int &pIndex)
{
return false;
}
Boolean UNIX_Hdr8021PService::finalize()
{
return false;
}
Boolean UNIX_Hdr8021PService::find(Array<CIMKeyBinding> &kbArray)
{
CIMKeyBinding kb;
String systemCreationClassNameKey;
String systemNameKey;
String creationClassNameKey;
String nameKey;
for(Uint32 i = 0; i < kbArray.size(); i++)
{
kb = kbArray[i];
CIMName keyName = kb.getName();
if (keyName.equal(PROPERTY_SYSTEM_CREATION_CLASS_NAME)) systemCreationClassNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_SYSTEM_NAME)) systemNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_CREATION_CLASS_NAME)) creationClassNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_NAME)) nameKey = kb.getValue();
}
/* EXecute find with extracted keys */
return false;
}
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
116aff42d390e062ba410b423095eb116fa66d6b | c3c2701c90bdf0a1f52537b0a6747191369e309d | /1119/1119.cpp | 352ae02acef51b65168bcdb859b1d631bffd46ee | [] | no_license | bzz13/timus | 3c2b845a05cfd716c117fdee832f81e867f0245d | f102d3f10be0e939b96f2bfabac45bf5b763ba32 | refs/heads/master | 2021-06-19T14:02:24.815170 | 2021-02-01T09:12:40 | 2021-02-01T09:12:40 | 47,258,903 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,454 | cpp | #include <iostream>
#include <utility>
#include <stack>
#include <vector>
using namespace std;
void readDiagonals(const int &count, vector<pair<int, int> >* diagonals)
{
int x, y;
for (int i = 0; i < count; ++i)
{
cin >> x >> y;
pair<int, int> p(y - 1, x - 1);
(*diagonals).push_back(p);
}
}
bool containsInDiagonals(pair<int, int> p, vector<pair<int, int> >* diagonals)
{
for (std::vector<pair<int, int> >::iterator it = diagonals->begin(); it != diagonals->end(); ++it)
if (it->first == p.first && it->second == p.second)
return true;
return false;
}
bool containsTopDiagonals(pair<int, int> p, vector<pair<int, int> >* diagonals)
{
for (std::vector<pair<int, int> >::iterator it = diagonals->begin(); it != diagonals->end(); ++it)
if (it->first > p.first && it->second == p.second)
return true;
return false;
}
bool containsRightDiagonals(pair<int, int> p, vector<pair<int, int> >* diagonals)
{
for (std::vector<pair<int, int> >::iterator it = diagonals->begin(); it != diagonals->end(); ++it)
if (it->first == p.first && it->second > p.second)
return true;
return false;
}
int main()
{
int sizeX, sizeY, K;
cin >> sizeX >> sizeY >> K;
if (K == 0)
{
cout << (sizeY + sizeX) * 100;
return 0;
}
double step = 100, stepd = 141.42135623730950488016887242097;
double **weight = new double*[sizeY + 1];
for (int i = 0; i <= sizeY; ++i)
weight[i] = new double[sizeX + 1];
for (int i = 0; i <= sizeY; ++i)
for (int j = 0; j <= sizeX; ++j)
weight[i][j] = 0;
vector<pair<int, int> > diagonals;
readDiagonals(K, &diagonals);
pair<int, int> first(0, 0);
stack<pair<int, int> > stck;
stck.push(first);
while (stck.size() > 0)
{
pair<int, int> tmp = stck.top();
stck.pop();
// if (tmp.first == sizeY && tmp.second == sizeX)
// break;
double w = weight[tmp.first][tmp.second];
bool add = false;
if (tmp.first < sizeY && containsTopDiagonals(tmp, &diagonals))
{
if (weight[tmp.first + 1][tmp.second] == 0 ||
weight[tmp.first + 1][tmp.second] > w + step)
{
weight[tmp.first + 1][tmp.second] = w + step;
stck.push(pair<int, int>(tmp.first + 1, tmp.second));
add = true;
}
}
if (tmp.second < sizeX && containsRightDiagonals(tmp, &diagonals))
{
if (weight[tmp.first][tmp.second + 1] == 0 ||
weight[tmp.first][tmp.second + 1] > w + step)
{
weight[tmp.first][tmp.second + 1] = w + step;
stck.push(pair<int, int>(tmp.first, tmp.second + 1));
add = true;
}
}
if (containsInDiagonals(tmp, &diagonals))
{
if (weight[tmp.first + 1][tmp.second + 1] == 0 ||
weight[tmp.first + 1][tmp.second + 1] > w + stepd)
{
weight[tmp.first + 1][tmp.second + 1] = w + stepd;
stck.push(pair<int, int>(tmp.first + 1, tmp.second + 1));
add = true;
}
}
if (!add)
{
if (tmp.first < sizeY)
{
if (weight[tmp.first + 1][tmp.second] == 0 ||
weight[tmp.first + 1][tmp.second] > w + step)
{
weight[tmp.first + 1][tmp.second] = w + step;
stck.push(pair<int, int>(tmp.first + 1, tmp.second));
}
}
if (tmp.second < sizeX)
{
if (weight[tmp.first][tmp.second + 1] == 0 ||
weight[tmp.first][tmp.second + 1] > w + step)
{
weight[tmp.first][tmp.second + 1] = w + step;
stck.push(pair<int, int>(tmp.first, tmp.second + 1));
}
}
}
}
cout << (int)(weight[sizeY][sizeX] + 0.5);
for (int i = 0; i <= sizeY; ++i)
delete[] weight[i];
delete[] weight;
} | [
"BZz13@skbkontur.ru"
] | BZz13@skbkontur.ru |
6a99b0a4ac0c8e7f501334974bed72019339e7d0 | 641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2 | /third_party/WebKit/Source/platform/fonts/SymbolsIterator.cpp | 99807a3bfc69e73833eb3770e26059e7847acb67 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | massnetwork/mass-browser | 7de0dfc541cbac00ffa7308541394bac1e945b76 | 67526da9358734698c067b7775be491423884339 | refs/heads/master | 2022-12-07T09:01:31.027715 | 2017-01-19T14:29:18 | 2017-01-19T14:29:18 | 73,799,690 | 4 | 4 | BSD-3-Clause | 2022-11-26T11:53:23 | 2016-11-15T09:49:29 | null | UTF-8 | C++ | false | false | 5,393 | cpp | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "SymbolsIterator.h"
#include "wtf/PtrUtil.h"
#include <unicode/uchar.h>
#include <unicode/uniset.h>
namespace blink {
using namespace WTF::Unicode;
SymbolsIterator::SymbolsIterator(const UChar* buffer, unsigned bufferSize)
: m_utf16Iterator(makeUnique<UTF16TextIterator>(buffer, bufferSize)),
m_bufferSize(bufferSize),
m_nextChar(0),
m_atEnd(bufferSize == 0),
m_currentFontFallbackPriority(FontFallbackPriority::Invalid) {}
FontFallbackPriority SymbolsIterator::fontFallbackPriorityForCharacter(
UChar32 codepoint) {
// Those should only be Emoji presentation as combinations of two.
if (Character::isEmojiKeycapBase(codepoint) ||
Character::isRegionalIndicator(codepoint))
return FontFallbackPriority::Text;
if (codepoint == combiningEnclosingKeycapCharacter ||
codepoint == combiningEnclosingCircleBackslashCharacter)
return FontFallbackPriority::EmojiEmoji;
if (Character::isEmojiEmojiDefault(codepoint) ||
Character::isEmojiModifierBase(codepoint) ||
Character::isModifier(codepoint))
return FontFallbackPriority::EmojiEmoji;
if (Character::isEmojiTextDefault(codepoint))
return FontFallbackPriority::EmojiText;
// Here we could segment into Symbols and Math categories as well, similar
// to what the Windows font fallback does. Map the math Unicode and Symbols
// blocks to Text for now since we don't have a good cross-platform way to
// select suitable math fonts.
return FontFallbackPriority::Text;
}
bool SymbolsIterator::consume(unsigned* symbolsLimit,
FontFallbackPriority* fontFallbackPriority) {
if (m_atEnd)
return false;
while (m_utf16Iterator->consume(m_nextChar)) {
m_previousFontFallbackPriority = m_currentFontFallbackPriority;
unsigned iteratorOffset = m_utf16Iterator->offset();
m_utf16Iterator->advance();
// Except at the beginning, ZWJ just carries over the emoji or neutral
// text type, VS15 & VS16 we just carry over as well, since we already
// resolved those through lookahead. Also, don't downgrade to text
// presentation for emoji that are part of a ZWJ sequence, example
// U+1F441 U+200D U+1F5E8, eye (text presentation) + ZWJ + left speech
// bubble, see below.
if ((!(m_nextChar == zeroWidthJoinerCharacter &&
m_previousFontFallbackPriority ==
FontFallbackPriority::EmojiEmoji) &&
m_nextChar != variationSelector15Character &&
m_nextChar != variationSelector16Character &&
!Character::isRegionalIndicator(m_nextChar) &&
!((m_nextChar == leftSpeechBubbleCharacter ||
m_nextChar == rainbowCharacter || m_nextChar == maleSignCharacter ||
m_nextChar == femaleSignCharacter ||
m_nextChar == staffOfAesculapiusCharacter) &&
m_previousFontFallbackPriority ==
FontFallbackPriority::EmojiEmoji)) ||
m_currentFontFallbackPriority == FontFallbackPriority::Invalid) {
m_currentFontFallbackPriority =
fontFallbackPriorityForCharacter(m_nextChar);
}
UChar32 peekChar = 0;
if (m_utf16Iterator->consume(peekChar) && peekChar != 0) {
// Variation Selectors
if (m_currentFontFallbackPriority == FontFallbackPriority::EmojiEmoji &&
peekChar == variationSelector15Character) {
m_currentFontFallbackPriority = FontFallbackPriority::EmojiText;
}
if (m_currentFontFallbackPriority == FontFallbackPriority::EmojiText &&
peekChar == variationSelector16Character) {
m_currentFontFallbackPriority = FontFallbackPriority::EmojiEmoji;
}
// Combining characters Keycap...
if (Character::isEmojiKeycapBase(m_nextChar) &&
peekChar == combiningEnclosingKeycapCharacter) {
m_currentFontFallbackPriority = FontFallbackPriority::EmojiEmoji;
};
// ...and Combining Enclosing Circle Backslash.
if (m_currentFontFallbackPriority == FontFallbackPriority::EmojiText &&
peekChar == combiningEnclosingCircleBackslashCharacter) {
m_currentFontFallbackPriority = FontFallbackPriority::EmojiEmoji;
}
// Regional indicators
if (Character::isRegionalIndicator(m_nextChar) &&
Character::isRegionalIndicator(peekChar)) {
m_currentFontFallbackPriority = FontFallbackPriority::EmojiEmoji;
}
// Upgrade text presentation emoji to emoji presentation when followed by
// ZWJ, Example U+1F441 U+200D U+1F5E8, eye + ZWJ + left speech bubble.
if ((m_nextChar == eyeCharacter ||
m_nextChar == wavingWhiteFlagCharacter) &&
peekChar == zeroWidthJoinerCharacter) {
m_currentFontFallbackPriority = FontFallbackPriority::EmojiEmoji;
}
}
if (m_previousFontFallbackPriority != m_currentFontFallbackPriority &&
(m_previousFontFallbackPriority != FontFallbackPriority::Invalid)) {
*symbolsLimit = iteratorOffset;
*fontFallbackPriority = m_previousFontFallbackPriority;
return true;
}
}
*symbolsLimit = m_bufferSize;
*fontFallbackPriority = m_currentFontFallbackPriority;
m_atEnd = true;
return true;
}
} // namespace blink
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
a61af54c8e925c2333af774a43b4200b16bf257d | a58e4057c052c2f4743236f600d06b5191633ee4 | /lc/178/lc_C.cpp | 957de252cd82d66b1e7249151d5a87f9f65c9255 | [] | no_license | nysanier/cf | d454c6afeaa503b39c78febd42c6c0ac49c8f290 | ced8246c42dcf5d1f63770c466c327d9bc0b8a18 | refs/heads/master | 2020-09-08T01:42:24.193949 | 2020-07-26T09:38:49 | 2020-07-26T09:38:49 | 220,973,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,602 | cpp | #include <bits/stdc++.h>
// #include <bits/extc++.h>
#include "lc.h"
// -------------------------------------------------
namespace {
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// # define DUMP(args...)
class Solution {
ListNode* head_ = nullptr;
bool dfs(ListNode* pl, TreeNode* pt, int k) {
// 检查结束
if (!pl)
return true;
if (!pt)
return false;
DUMP("current", pl->val, pt->val, k);
// 已经找到了head, 继续往下find
if (k > 0 && pl->val && pt->val) {
DUMP("check-left", pt->left);
if (dfs(pl->next, pt->left, k+1)) {
DUMP("check-ok", pt->left);
return true;
}
DUMP("check-right", pt->right);
if (dfs(pl->next, pt->right, k+1)) {
DUMP("check-ok", pt->right);
return true;
}
}
// 首次找到head
if (head_->val == pt->val) {
DUMP("first-left", pt->left);
if (dfs(head_->next, pt->left, 1)) {
DUMP("first-ok", pt->left);
return true;
}
DUMP("first-right", pt->right);
if (dfs(head_->next, pt->right, 1)) {
DUMP("first-ok", pt->right);
return true;
}
}
// 不满足要求, 且没有找到head
DUMP("find-left", pt->left);
if (dfs(head_, pt->left, 0)) {
DUMP("find-ok", pt->left);
return true;
}
DUMP("find-right", pt->right);
if (dfs(head_, pt->right, 0)) {
DUMP("find-ok", pt->right);
return true;
}
DUMP("find-none");
return false;
}
void travel(TreeNode* p, int k) {
if (!p)
return;
DUMP(k, p->val);
travel(p->left, k+1);
travel(p->right, k+1);
}
public:
bool isSubPath(ListNode* head, TreeNode* root) {
// travel(root, 0);
head_ = head;
auto r = dfs(head, root, 0);
return r;
}
};
}
void Init() {}
void Solve() {
using namespace std;
static int idx = 0;
vector<string> in;
std::string out;
lc::Read(in, out);
DUMP("------", idx, in, out);
idx +=1;
#define FUNC isSubPath
#define ARGS head, root
ListNode* head = nullptr;
// {
// auto p1 = new ListNode(1);
// auto p10 = new ListNode(10);
// p1->next = p10;
// head = p1;
// }
{
auto p4 = new ListNode(4);
auto p2 = new ListNode(2);
auto p8 = new ListNode(8);
p4->next = p2;
p2->next = p8;
head = p4;
}
TreeNode* root = nullptr;
// [1,
// 4,4,
// null,2,2,null
// 1,null,6,8,null,null,null,null
// 1,3]
// {
// auto l = new TreeNode(9);
// auto p = new TreeNode(10);
// p->left = l;
// l = p;
// auto r = new TreeNode(1);
// p = new TreeNode(1);
// p->left = l;
// p->right = r;
// r = p;
// p = new TreeNode(1);
// p->right = r;
// root = p;
// }
{
auto l = new TreeNode(1);
auto r = new TreeNode(3);
auto p = new TreeNode(8);
p->left = l;
p->right = r;
r = p;
l = new TreeNode(6);
p = new TreeNode(2);
p->left = l;
p->right = r;
l = p;
p = new TreeNode(4);
p->left = l;
r = p;
p = new TreeNode(1);
p->right = r;
auto p1 = new TreeNode(1);
auto p2 = new TreeNode(2);
auto p4 = new TreeNode(4);
p2->left = p1;
p4->right = p2;
p->left = p4;
root = p;
}
// lc::ParseArg(in[0], head);
// lc::ParseArg(in[1], root);
// DUMP(ARGS);
Solution sol;
auto r = sol.FUNC(ARGS);
DUMP(out, r);
// assert(out == to_string(r));
}
// -------------------------------------------------
int main() {
#ifndef ONLINE_JUDGE
::freopen("../input.txt", "r", stdin);
#endif
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
Init();
int t = 1;
// std::cin >> t;
while (t--) Solve();
return 0;
}
| [
"nysanier@163.com"
] | nysanier@163.com |
6b4e3329c3785e0497cdb7661406a3b226fae4be | ac2516485d1c1e16a86a30eeee9adc138dfde4bf | /examinationroom/src/core/objects/atmosphere.cpp | f89bfbb16c0d1a0cab76bcd351bd2a18f59e22e1 | [] | no_license | cbreak-black/ExaminationRoom | ebee8da293fb2c659366a030cc4ee14553d5ada7 | a3d47201d003257b1a986e8fdec01be5c31cc5e5 | refs/heads/master | 2021-01-19T19:37:47.197485 | 2011-10-14T12:36:00 | 2011-10-14T12:36:00 | 576,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,896 | cpp | /*
* atmosphere.cpp
* ExaminationRoom
*
* Created by CBreak on 02.04.08.
* Copyright 2008 Gerhard Roethlin. All rights reserved.
*
*/
#include "atmosphere.h"
#include "parameter/parameteratmosphere.h"
#include <qgl.h>
#include "glerrortool.h"
#include "luabridge.hpp"
#include "luahelper.h"
namespace luabridge
{
const char * fogModes[] =
{
"Exp",
"Exp2",
"Linear",
0
};
template <>
struct tdstack <Examination::Atmosphere::FogMode>
{
static void push (lua_State *L, Examination::Atmosphere::FogMode data)
{
lua_pushstring(L, fogModes[data]);
}
static Examination::Atmosphere::FogMode get (lua_State *L, int index)
{
return static_cast<Examination::Atmosphere::FogMode>(luaL_checkoption(L, index, 0, fogModes));
}
};
}
namespace Examination
{
Atmosphere::Atmosphere()
{
setMode(Exp);
setStart(0);
setEnd(100);
setDensity(1);
setName("atmosphere");
}
ObjectPtr Atmosphere::clone() const
{
ContainerPtr c(new Atmosphere(*this));
c->clone(this);
return c;
}
Atmosphere::FogMode Atmosphere::mode() const
{
return fogMode_;
}
void Atmosphere::setMode(FogMode fogMode)
{
objectWillChange();
fogMode_ = fogMode;
objectDidChange();
}
float Atmosphere::density() const
{
return density_;
}
void Atmosphere::setDensity(float density)
{
objectWillChange();
density_ = fabs(density);
objectDidChange();
}
float Atmosphere::start() const
{
return start_;
}
void Atmosphere::setStart(float start)
{
objectWillChange();
start_ = start;
objectDidChange();
}
float Atmosphere::end() const
{
return end_;
}
void Atmosphere::setEnd(float end)
{
objectWillChange();
end_ = end;
objectDidChange();
}
// Serialisation
const char * Atmosphere::className_ = "Atmosphere";
std::string Atmosphere::className() const
{
return Atmosphere::className_;
}
std::string Atmosphere::toLua(std::ostream & outStream) const
{
Container::toLua(outStream);
outStream << name() << ":" << "setMode(\"";
switch (mode())
{
case Atmosphere::Exp:
outStream << "Exp";
break;
case Atmosphere::Exp2:
outStream << "Exp2";
break;
case Atmosphere::Linear:
outStream << "Linear";
break;
}
outStream << "\");\n";
outStream << name() << ":" << "setDensity(" << density() << ");\n";
outStream << name() << ":" << "setStart(" << start() << ");\n";
outStream << name() << ":" << "setEnd(" << end() << ");\n";
return name();
}
// LUA
void Atmosphere::registerLuaApi(luabridge::module * m)
{
m->subclass<Atmosphere,Container>(Atmosphere::className_)
.constructor<void (*)()>()
.method("mode", &Atmosphere::mode)
.method("setMode", &Atmosphere::setMode)
.method("density", &Atmosphere::density)
.method("setDensity", &Atmosphere::setDensity)
.method("start", &Atmosphere::start)
.method("setStart", &Atmosphere::setStart)
.method("end", &Atmosphere::end)
.method("setEnd", &Atmosphere::setEnd);
}
std::tr1::shared_ptr<ParameterObject> Atmosphere::createDialog()
{
return std::tr1::shared_ptr<ParameterObject>(new ParameterAtmosphere(sharedPtr()));
}
// Drawing
void Atmosphere::draw(GLWidget * dest) const
{
if (shown())
{
// If not enabled, just draw children and return
if (!enabled())
{
Container::draw(dest);
}
else
{
// Enable fog
glEnable(GL_FOG);
// Set fog state
switch (mode())
{
case Exp:
glFogi(GL_FOG_MODE, GL_EXP);
glFogf(GL_FOG_DENSITY, density_);
break;
case Exp2:
glFogi(GL_FOG_MODE, GL_EXP2);
glFogf(GL_FOG_DENSITY, density_);
break;
case Linear:
glFogi(GL_FOG_MODE, GL_LINEAR);
glFogf(GL_FOG_START, start_);
glFogf(GL_FOG_END, end_);
break;
}
glFogfv(GL_FOG_COLOR, color().vec);
// Draw the contents of this node
GlErrorTool::getErrors("Atmosphere::draw:1", name());
Container::draw(dest);
// Disable fog again
glDisable(GL_FOG);
GlErrorTool::getErrors("Atmosphere::draw:2", name());
}
}
}
}
| [
"git@the-color-black.net"
] | git@the-color-black.net |
5469fab623381f87dfacfe1eef4ec9bbdfe35da6 | e7d7377b40fc431ef2cf8dfa259a611f6acc2c67 | /SampleDump/Cpp/SDK/BP_Cloth6_classes.h | 00ad718de66c19b1dd28a97f80c29ad58499eea9 | [] | no_license | liner0211/uSDK_Generator | ac90211e005c5f744e4f718cd5c8118aab3f8a18 | 9ef122944349d2bad7c0abe5b183534f5b189bd7 | refs/heads/main | 2023-09-02T16:37:22.932365 | 2021-10-31T17:38:03 | 2021-10-31T17:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | #pragma once
// Name: Mordhau, Version: Patch23
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_Cloth6.BP_Cloth6_C
// 0x0000 (FullSize[0x0078] - InheritedSize[0x0078])
class UBP_Cloth6_C : public UMordhauColor
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_Cloth6.BP_Cloth6_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"talon_hq@outlook.com"
] | talon_hq@outlook.com |
4396bbe3bce0195062ba0b50c7ce338099924146 | 91211d13b54a99104740aaa3abea85016005e523 | /2021-PRDC/03_Benchmarks/15_PAND_rep_first/FigaroModelfigaro_15_PAND_rep_first.h | d02ef9dbcf15c83713cb18ab326d1a40beaa14e0 | [] | no_license | moves-rwth/dft-bdmp | 3b832110153581a31b0c1ea7e01337bab71836b1 | 7bbae90c0fa79b2fb62a8e55a01d24e905932344 | refs/heads/master | 2022-06-15T22:10:31.504812 | 2022-06-09T15:03:16 | 2022-06-09T15:03:16 | 196,187,409 | 1 | 1 | null | 2022-06-09T15:03:17 | 2019-07-10T10:48:31 | C++ | UTF-8 | C++ | false | false | 9,586 | h |
#pragma once
#include "storm-figaro/model/FigaroModelTemplate.h"
#include <array>
#include <map>
#include <vector>
#include <sstream>
#include<math.h>
#include <set>
namespace storm{
namespace figaro{
class FigaroProgram_figaro_15_PAND_rep_first: public storm::figaro::FigaroProgram{
public:
FigaroProgram_figaro_15_PAND_rep_first(): FigaroProgram(// std::map<std::string, size_t> mFigaroboolelementindex =
{
{"required_OF_F_1" , 0},
{"already_S_OF_F_1" , 1},
{"S_OF_F_1" , 2},
{"relevant_evt_OF_F_1" , 3},
{"failF_OF_F_1" , 4},
{"required_OF_F_2" , 5},
{"already_S_OF_F_2" , 6},
{"S_OF_F_2" , 7},
{"relevant_evt_OF_F_2" , 8},
{"failF_OF_F_2" , 9},
{"required_OF_F_3" , 10},
{"already_S_OF_F_3" , 11},
{"S_OF_F_3" , 12},
{"relevant_evt_OF_F_3" , 13},
{"failF_OF_F_3" , 14},
{"required_OF_F_4" , 15},
{"already_S_OF_F_4" , 16},
{"S_OF_F_4" , 17},
{"relevant_evt_OF_F_4" , 18},
{"failF_OF_F_4" , 19},
{"required_OF_THEN_1" , 20},
{"already_S_OF_THEN_1" , 21},
{"S_OF_THEN_1" , 22},
{"relevant_evt_OF_THEN_1" , 23},
{"required_OF_THEN_3" , 24},
{"already_S_OF_THEN_3" , 25},
{"S_OF_THEN_3" , 26},
{"relevant_evt_OF_THEN_3" , 27},
{"required_OF_THEN_4" , 28},
{"already_S_OF_THEN_4" , 29},
{"S_OF_THEN_4" , 30},
{"relevant_evt_OF_THEN_4" , 31},
{"required_OF_UE_1" , 32},
{"already_S_OF_UE_1" , 33},
{"S_OF_UE_1" , 34},
{"relevant_evt_OF_UE_1" , 35}},
// std::map<std::string, size_t> mFigaroelementfailureindex =
{ { "exp0",0}},
// std::map<std::string, size_t> mFigarofloatelementindex =
{ },
// std::map<std::string, size_t> mFigarointelementindex =
{ },
// std::map<std::string, size_t> mFigaroenumelementindex =
{ },
// std::map<std::string, size_t> failure_variable_names =
{ "exp0"},
// std::set<std::string> enum_variables_names =
{ },
// std::set<std::string> float_variables_names =
{ },
// std::string const topevent=
"exp0",
// static int const numBoolState =
36 ,
// numBoolFailureState =
1 ,
// static int const numFloatState =
0 ,
// static int const numIntState =
0 ,
// static int const numEnumState =
0 ,
// bool ins_transition_found =
false){}
/* ---------- CODING ENUMERATED VARIABLES STATES ------------ */
enum enum_status {};
// std::array<bool, numBoolState> boolState;
// std::array<bool, numBoolState> backupBoolState;
// std::array<float, numFloatState> floatState;
// std::array<float, numFloatState> backupFloatState;
// std::array<int, numIntState> intState;
// std::array<int, numIntState> backupIntState;
// std::array<int, numEnumState> enumState;
// std::array<int, numEnumState> backupEnumState;
bool REINITIALISATION_OF_required_OF_F_1 ;
bool REINITIALISATION_OF_S_OF_F_1 ;
bool REINITIALISATION_OF_relevant_evt_OF_F_1 ;
bool REINITIALISATION_OF_required_OF_F_2 ;
bool REINITIALISATION_OF_S_OF_F_2 ;
bool REINITIALISATION_OF_relevant_evt_OF_F_2 ;
bool REINITIALISATION_OF_required_OF_F_3 ;
bool REINITIALISATION_OF_S_OF_F_3 ;
bool REINITIALISATION_OF_relevant_evt_OF_F_3 ;
bool REINITIALISATION_OF_required_OF_F_4 ;
bool REINITIALISATION_OF_S_OF_F_4 ;
bool REINITIALISATION_OF_relevant_evt_OF_F_4 ;
bool REINITIALISATION_OF_required_OF_THEN_1 ;
bool REINITIALISATION_OF_S_OF_THEN_1 ;
bool REINITIALISATION_OF_relevant_evt_OF_THEN_1 ;
bool REINITIALISATION_OF_required_OF_THEN_3 ;
bool REINITIALISATION_OF_S_OF_THEN_3 ;
bool REINITIALISATION_OF_relevant_evt_OF_THEN_3 ;
bool REINITIALISATION_OF_required_OF_THEN_4 ;
bool REINITIALISATION_OF_S_OF_THEN_4 ;
bool REINITIALISATION_OF_relevant_evt_OF_THEN_4 ;
bool REINITIALISATION_OF_required_OF_UE_1 ;
bool REINITIALISATION_OF_S_OF_UE_1 ;
bool REINITIALISATION_OF_relevant_evt_OF_UE_1 ;
/* ---------- DECLARATION OF CONSTANTS ------------ */
double const lambda_OF_F_1 = 0.01;
bool const force_relevant_events_OF_THEN_1 = false;
double const mu_OF_F_1 = 0.1;
std::string const calculate_required_OF_F_2 = "fn_fathers_and_trig";
std::string const calculate_required_OF_F_4 = "fn_fathers_and_trig";
std::string const calculate_required_OF_F_3 = "fn_fathers_and_trig";
bool const failF_FROZEN_OF_F_1 = false;
bool const Profil1_OF___ARBRE__EIRM = true;
bool const force_relevant_events_OF_F_2 = false;
bool const force_relevant_events_OF_F_3 = false;
double const lambda_OF_F_2 = 0.01;
bool const force_relevant_events_OF_F_4 = false;
double const lambda_OF_F_3 = 0.01;
std::string const step_down_OF_THEN_3 = "rep_first";
std::string const step_down_OF_THEN_4 = "rep_first";
double const mu_OF_F_2 = 0.1;
double const lambda_OF_F_4 = 0.01;
double const mu_OF_F_3 = 0.1;
std::string const calculate_required_OF_UE_1 = "fn_fathers_and_trig";
double const mu_OF_F_4 = 0.1;
std::string const step_down_OF_THEN_1 = "rep_first";
bool const repairable_system_OF_OPTIONS = true;
std::string const calculate_required_OF_THEN_3 = "fn_fathers_and_trig";
std::string const trimming_option_OF_OPTIONS = "maximum";
std::string const calculate_required_OF_THEN_4 = "fn_fathers_and_trig";
std::string const calculate_required_OF_F_1 = "fn_fathers_and_trig";
bool const failF_FROZEN_OF_F_2 = false;
bool const failF_FROZEN_OF_F_4 = false;
bool const trimming_OF_OPTIONS = false;
bool const failF_FROZEN_OF_F_3 = false;
std::string const calculate_required_OF_THEN_1 = "fn_fathers_and_trig";
bool const force_relevant_events_OF_THEN_3 = false;
bool const force_relevant_events_OF_THEN_4 = false;
bool const force_relevant_events_OF_F_1 = false;
bool const force_relevant_events_OF_UE_1 = true;
/* ---------- DECLARATION OF OCCURRENCE RULES FIRING FLAGS ------------ */
bool FIRE_xx10_OF_F_1;
bool FIRE_xx11_OF_F_1;
bool FIRE_xx10_OF_F_2;
bool FIRE_xx11_OF_F_2;
bool FIRE_xx10_OF_F_3;
bool FIRE_xx11_OF_F_3;
bool FIRE_xx10_OF_F_4;
bool FIRE_xx11_OF_F_4;
int required_OF_F_1 = 0 ;
int already_S_OF_F_1 = 1 ;
int S_OF_F_1 = 2 ;
int relevant_evt_OF_F_1 = 3 ;
int failF_OF_F_1 = 4 ;
int required_OF_F_2 = 5 ;
int already_S_OF_F_2 = 6 ;
int S_OF_F_2 = 7 ;
int relevant_evt_OF_F_2 = 8 ;
int failF_OF_F_2 = 9 ;
int required_OF_F_3 = 10 ;
int already_S_OF_F_3 = 11 ;
int S_OF_F_3 = 12 ;
int relevant_evt_OF_F_3 = 13 ;
int failF_OF_F_3 = 14 ;
int required_OF_F_4 = 15 ;
int already_S_OF_F_4 = 16 ;
int S_OF_F_4 = 17 ;
int relevant_evt_OF_F_4 = 18 ;
int failF_OF_F_4 = 19 ;
int required_OF_THEN_1 = 20 ;
int already_S_OF_THEN_1 = 21 ;
int S_OF_THEN_1 = 22 ;
int relevant_evt_OF_THEN_1 = 23 ;
int required_OF_THEN_3 = 24 ;
int already_S_OF_THEN_3 = 25 ;
int S_OF_THEN_3 = 26 ;
int relevant_evt_OF_THEN_3 = 27 ;
int required_OF_THEN_4 = 28 ;
int already_S_OF_THEN_4 = 29 ;
int S_OF_THEN_4 = 30 ;
int relevant_evt_OF_THEN_4 = 31 ;
int required_OF_UE_1 = 32 ;
int already_S_OF_UE_1 = 33 ;
int S_OF_UE_1 = 34 ;
int relevant_evt_OF_UE_1 = 35 ;
int exp0 = 0 ;
/* ---------- DECLARATION OF FUNCTIONS ------------ */
void init();
void saveCurrentState();
void printState();
void fireOccurrence(int numFire);
std::vector<std::tuple<int, double, std::string, int>> showFireableOccurrences();
void runOnceInteractionStep_initialization();
void runOnceInteractionStep_propagate_effect_S();
void runOnceInteractionStep_propagate_effect_required();
void runOnceInteractionStep_propagate_leaves();
int compareStates();
void doReinitialisations();
void runInteractions();
void printstatetuple();
void fireinsttransitiongroup(std::string);
int_fast64_t stateSize() const;
bool figaromodelhasinstransitions();
};
}
} | [
"shahid.khan@cs.rwth-aachen.de"
] | shahid.khan@cs.rwth-aachen.de |
31d1ecbf57e4bade0906413b41b0a7126bdcd431 | 1d1b5cc7443945a9d1f7b241d470f22026e4d4f2 | /SinusoidalBehavior.cpp | 43a1560a0556a0d0d3a7485ef426d6bf0e827935 | [] | no_license | chelseamanzano/CMPM-265-Particle-System | d6d1583f7fefdaf363debc37f88e7fae518cf5e8 | 93caf73ed8efec032fd0402257bc89d813c593f4 | refs/heads/master | 2020-03-09T04:01:51.263523 | 2018-04-11T22:31:40 | 2018-04-11T22:31:40 | 128,578,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | cpp | #include "SinusoidalBehavior.h"
float SinusoidalBehavior::behavior_at_time(float minValue, float changeValue, float currLifetime, float maxLifetime) {
return -changeValue * cosf(currLifetime/maxLifetime * (M_PI/2)) + changeValue + minValue;
} | [
"camanzan@ucsc.edu"
] | camanzan@ucsc.edu |
a308482bb9c1904a6f1d431e66c2357c945af1c2 | f699576e623d90d2e07d6c43659a805d12b92733 | /WTLOnline-SDK/SDK/WTLOnline_BP_ControllerRatChild_classes.hpp | a0895e3aff9be085723c5c0d498d7d7c7efcfcee | [] | no_license | ue4sdk/WTLOnline-SDK | 2309620c809efeb45ba9ebd2fc528fa2461b9ca0 | ff244cd4118c54ab2048ba0632b59ced111c405c | refs/heads/master | 2022-07-12T13:02:09.999748 | 2019-04-22T08:22:35 | 2019-04-22T08:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,561 | hpp | #pragma once
// Will To Live Online (0.57) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "WTLOnline_BP_ControllerRatChild_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_ControllerRatChild.BP_ControllerRatChild_C
// 0x0017 (0x04F8 - 0x04E1)
class ABP_ControllerRatChild_C : public ABP_MonsterPawnAiControllerBase_C
{
public:
unsigned char UnknownData00[0x7]; // 0x04E1(0x0007) MISSED OFFSET
struct FPointerToUberGraphFrame UberGraphFrame; // 0x04E8(0x0008) (CPF_ZeroConstructor, CPF_Transient, CPF_DuplicateTransient)
class UAIPerceptionComponent* AIPerception; // 0x04F0(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_ControllerRatChild.BP_ControllerRatChild_C"));
return ptr;
}
void UserConstructionScript();
void BndEvt__AIPerception_0_K2Node_ComponentBoundEvent_0_ActorPerceptionUpdatedDelegate__DelegateSignature(class AActor* Actor, const struct FAIStimulus& Stimulus);
void ExecuteUbergraph_BP_ControllerRatChild(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
c762dfe604eb85cec4428ef2992b9557251b3986 | 6b76024eccd7b6d54855b5e5e6ebe048768d96a9 | /blasius_laminar_github/1.4/uniform/time | 132b8cc2faf50bc3887412ef632197d477d5cf38 | [] | no_license | MaSprGit/laminar_BL_OpenFOAM | 93a9fda38fea9f5e913ce2d54d7dbac2a4e606a6 | 50f189f5eb03f7d5a80d3c2d4800b9a343c7b9f7 | refs/heads/main | 2023-03-17T20:32:36.696128 | 2021-03-21T15:27:47 | 2021-03-21T15:27:47 | 350,022,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v2012 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "1.4/uniform";
object time;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
value 1.39999999999997571;
name "1.4";
index 1120;
deltaT 0.00125;
deltaT0 0.00125;
// ************************************************************************* //
| [
"markus.trier@gmail.com"
] | markus.trier@gmail.com | |
6fc1217ca6bbb8e2eb4ab19998427ea16da534d5 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /tdmq/src/v20200217/model/DescribeCmqQueueDetailRequest.cpp | 8ae6eafa4a13ef8bb45371487cf0136b6836ca0e | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 2,024 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tdmq/v20200217/model/DescribeCmqQueueDetailRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tdmq::V20200217::Model;
using namespace std;
DescribeCmqQueueDetailRequest::DescribeCmqQueueDetailRequest() :
m_queueNameHasBeenSet(false)
{
}
string DescribeCmqQueueDetailRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_queueNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "QueueName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_queueName.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DescribeCmqQueueDetailRequest::GetQueueName() const
{
return m_queueName;
}
void DescribeCmqQueueDetailRequest::SetQueueName(const string& _queueName)
{
m_queueName = _queueName;
m_queueNameHasBeenSet = true;
}
bool DescribeCmqQueueDetailRequest::QueueNameHasBeenSet() const
{
return m_queueNameHasBeenSet;
}
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
03ea554ceaf0ee2fd08ffcc1bdbdf10bf12feabc | 216f5252a8df73f8547d6a6c831409c916bae3e5 | /windows_embedded_compact_2013_2015M09/WINCE800/private/winceos/COREOS/core/thunks/tcommctr.cpp | fd27ca973b6a7d07cee9c8d7b2c475581b7e570c | [] | no_license | fanzcsoft/windows_embedded_compact_2013_2015M09 | 845fe834d84d3f0021047bc73d6cf9a75fabb74d | d04b71c517428ed2c73e94caf21a1582b34b18e3 | refs/heads/master | 2022-12-19T02:52:16.222712 | 2020-09-28T20:13:09 | 2020-09-28T20:13:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,070 | cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft shared
// source or premium shared source license agreement under which you licensed
// this source code. If you did not accept the terms of the license agreement,
// you are not authorized to use this source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the SOURCE.RTF on your install media or the root of your tools installation.
// THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
#define WINCOMMCTRLAPI
#include <windows.h>
#include <commctrl.h>
#include <CePtr.hpp>
#include <GweApiSet1.hpp>
extern GweApiSet1_t* pGweApiSet1Entrypoints;
extern "C"
HIMAGELIST
ImageList_Create(
int cx,
int cy,
UINT flags,
int cInitial,
int cGrow
)
{
return (HIMAGELIST)pGweApiSet1Entrypoints->m_pCreate(cx, cy, flags, cInitial, cGrow);
}
extern "C"
BOOL
WINAPI
ImageList_Destroy(
HIMAGELIST himl
)
{
return pGweApiSet1Entrypoints->m_pDestroy(himl);
}
extern "C"
int
WINAPI
ImageList_GetImageCount(
HIMAGELIST himl
)
{
return pGweApiSet1Entrypoints->m_pGetImageCount(himl);
}
extern "C"
int
WINAPI
ImageList_Add(
HIMAGELIST himl,
HBITMAP hbmImage,
HBITMAP hbmMask
)
{
return pGweApiSet1Entrypoints->m_pAdd(himl,hbmImage,hbmMask);
}
extern "C"
int
WINAPI
ImageList_ReplaceIcon(
HIMAGELIST himl,
int i,
HICON hicon
)
{
return pGweApiSet1Entrypoints->m_pReplaceIcon(himl,i,hicon);
}
extern "C"
COLORREF
WINAPI
ImageList_SetBkColor(
HIMAGELIST himl,
COLORREF clrBk
)
{
return pGweApiSet1Entrypoints->m_pSetBkColor(himl,clrBk);
}
extern "C"
COLORREF
WINAPI
ImageList_GetBkColor(
HIMAGELIST himl
)
{
return pGweApiSet1Entrypoints->m_pGetBkColor(himl);
}
extern "C"
BOOL
WINAPI
ImageList_SetOverlayImage(
HIMAGELIST himl,
int iImage,
int iOverlay
)
{
return pGweApiSet1Entrypoints->m_pSetOverlayImage(himl,iImage,iOverlay);
}
extern "C"
BOOL
WINAPI
ImageList_Draw(
HIMAGELIST himl,
int i,
HDC hdcDst,
int x,
int y,
UINT fStyle
)
{
return pGweApiSet1Entrypoints->m_pDraw(himl,i,hdcDst,x,y,fStyle);
}
extern "C"
BOOL
WINAPI
ImageList_Replace(
HIMAGELIST himl,
int i,
HBITMAP hbmImage,
HBITMAP hbmMask
)
{
return pGweApiSet1Entrypoints->m_pReplace(himl,i,hbmImage,hbmMask);
}
extern "C"
int
WINAPI
ImageList_AddMasked(
HIMAGELIST himl,
HBITMAP hbmImage,
COLORREF crMask
)
{
return pGweApiSet1Entrypoints->m_pAddMasked(himl,hbmImage,crMask);
}
extern "C"
BOOL
WINAPI
ImageList_DrawEx(
HIMAGELIST himl,
int i,
HDC hdcDst,
int x,
int y,
int dx,
int dy,
COLORREF rgbBk,
COLORREF rgbFg,
UINT fStyle
)
{
return pGweApiSet1Entrypoints->m_pDrawEx(himl,i,hdcDst,x,y,dx,dy,rgbBk,rgbFg,fStyle);
}
extern "C"
BOOL
WINAPI
ImageList_DrawIndirect(
__in IMAGELISTDRAWPARAMS* pimldp
)
{
return pGweApiSet1Entrypoints->m_pDrawIndirect(pimldp, sizeof(IMAGELISTDRAWPARAMS));
}
extern "C"
BOOL
WINAPI
ImageList_Remove(
HIMAGELIST himl,
int i
)
{
return pGweApiSet1Entrypoints->m_pRemove(himl,i);
}
extern "C"
HICON
WINAPI
ImageList_GetIcon(
HIMAGELIST himl,
int i,
UINT flags
)
{
return pGweApiSet1Entrypoints->m_pGetIcon(himl,i,flags);
}
extern "C"
HIMAGELIST
WINAPI
ImageList_LoadImage(
HINSTANCE hInstance,
__in const WCHAR* pImageName,
int cx,
int cGrow,
COLORREF crMask,
unsigned int uType,
unsigned int uFlags
)
{
DWORD ImageNameResourceID = 0;
if( IS_RESOURCE_ID(pImageName) )
{
ImageNameResourceID = reinterpret_cast<DWORD>(pImageName);
pImageName = NULL;
}
return (HIMAGELIST)pGweApiSet1Entrypoints->m_pLoadImage( hInstance, ImageNameResourceID, pImageName,cx,cGrow,crMask,uType,uFlags);
}
extern "C"
BOOL
WINAPI
ImageList_BeginDrag(
HIMAGELIST himlTrack,
int iTrack,
int dxHotspot,
int dyHotspot
)
{
return pGweApiSet1Entrypoints->m_pBeginDrag(himlTrack,iTrack,dxHotspot,dyHotspot);
}
extern "C"
void
WINAPI
ImageList_EndDrag(
void
)
{
pGweApiSet1Entrypoints->m_pEndDrag();
}
extern "C"
BOOL
WINAPI
ImageList_DragEnter(
HWND hwndLock,
int x,
int y
)
{
return pGweApiSet1Entrypoints->m_pDragEnter(hwndLock,x,y);
}
extern "C"
BOOL
WINAPI
ImageList_DragLeave(
HWND hwndLock
)
{
return pGweApiSet1Entrypoints->m_pDragLeave(hwndLock);
}
extern "C"
BOOL
WINAPI
ImageList_DragMove(
int x,
int y
)
{
return pGweApiSet1Entrypoints->m_pDragMove(x,y);
}
extern "C"
BOOL
WINAPI
ImageList_SetDragCursorImage(
HIMAGELIST himlDrag,
int iDrag,
int dxHotspot,
int dyHotspot
)
{
return pGweApiSet1Entrypoints->m_pSetDragCursorImage(himlDrag,iDrag,dxHotspot,dyHotspot);
}
extern "C"
BOOL
WINAPI
ImageList_DragShowNolock(
BOOL fShow
)
{
return pGweApiSet1Entrypoints->m_pDragShowNolock(fShow);
}
extern "C"
HIMAGELIST
WINAPI
ImageList_GetDragImage(
__out_opt POINT* ppt,
__out_opt POINT* pptHotspot
)
{
return (HIMAGELIST)pGweApiSet1Entrypoints->m_pGetDragImage(ppt,sizeof(POINT),pptHotspot,sizeof(POINT));
}
extern "C"
BOOL
WINAPI
ImageList_GetIconSize(
HIMAGELIST himl,
__out int* cx,
__out int* cy
)
{
return pGweApiSet1Entrypoints->m_pGetIconSize(himl,cx,cy);
}
extern "C"
BOOL
WINAPI
ImageList_SetIconSize(
HIMAGELIST himl,
int cx,
int cy
)
{
return pGweApiSet1Entrypoints->m_pSetIconSize(himl,cx,cy);
}
extern "C"
BOOL
WINAPI
ImageList_GetImageInfo(
HIMAGELIST himl,
int i,
__out IMAGEINFO* pImageInfo
)
{
return pGweApiSet1Entrypoints->m_pGetImageInfo(himl,i,pImageInfo,sizeof(IMAGEINFO));
}
extern "C"
HIMAGELIST
WINAPI
ImageList_Merge(
HIMAGELIST himl1,
int i1,
HIMAGELIST himl2,
int i2,
int dx,
int dy
)
{
return (HIMAGELIST)pGweApiSet1Entrypoints->m_pMerge(himl1, i1, himl2,i2,dx,dy);
}
extern "C"
void
ImageList_CopyDitherImage(
HIMAGELIST himlDest,
WORD iDst,
int xDst,
int yDst,
HIMAGELIST himlSrc,
int iSrc,
UINT fStyle
)
{
pGweApiSet1Entrypoints->m_pCopyDitherImage(himlDest,iDst,xDst,yDst,himlSrc,iSrc,fStyle);
}
extern "C"
BOOL
WINAPI
ImageList_Copy(
HIMAGELIST himlDst,
int iDst,
HIMAGELIST himlSrc,
int iSrc,
UINT uFlags
)
{
return pGweApiSet1Entrypoints->m_pCopy(himlDst, iDst, himlSrc, iSrc, uFlags);
}
extern "C"
HIMAGELIST
WINAPI
ImageList_Duplicate(
HIMAGELIST himl
)
{
return (HIMAGELIST)pGweApiSet1Entrypoints->m_pDuplicate(himl);
}
extern "C"
BOOL
WINAPI
ImageList_SetImageCount(
HIMAGELIST himl,
UINT uNewCount
)
{
return pGweApiSet1Entrypoints->m_pSetImageCount(himl, uNewCount);
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
78f9d499e6841e1535903ef00b411eb8b00190ab | 2eb3b66b421a1f4a18bcb72b69023a3166273ca1 | /LeetCode/LongestConsecutiveSequence.cc | 9deec173b5f912d12a832c85fe80b6edd30b2414 | [] | no_license | johnathan79717/competitive-programming | e1d62016e8b25d8bcb3d003bba6b1d4dc858a62f | 3c8471b7ebb516147705bbbc4316a511f0fe4dc0 | refs/heads/master | 2022-05-07T20:34:21.959511 | 2022-03-31T15:20:28 | 2022-03-31T15:20:28 | 55,674,796 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cc | class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int, int> upto, downto;
unordered_set<int> visited;
int ans = 0;
for(int i : num) {
if(visited.count(i)) continue;
visited.insert(i);
int up = i, down = i;
if(visited.count(i+1))
up = upto[i+1];
if(visited.count(i-1))
down = downto[i-1];
ans = max(ans, up - down + 1);
upto[down] = up;
downto[up] = down;
}
return ans;
}
}; | [
"johnathan79717@gmail.com"
] | johnathan79717@gmail.com |
490c37dfab4ebba78301d378e2ba76f68d80b82f | e51d009c6c6a1633c2c11ea4e89f289ea294ec7e | /xr2-dsgn/sources/xray/stalker2/xbox360/sources/stalker2_xbox360_application.cpp | a82f2214cd5e7951754bdeb66de3d7e54cfdab57 | [] | no_license | avmal0-Cor/xr2-dsgn | a0c726a4d54a2ac8147a36549bc79620fead0090 | 14e9203ee26be7a3cb5ca5da7056ecb53c558c72 | refs/heads/master | 2023-07-03T02:05:00.566892 | 2021-08-06T03:10:53 | 2021-08-06T03:10:53 | 389,939,196 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 709 | cpp | ////////////////////////////////////////////////////////////////////////////
// Created : 26.08.2008
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "stalker2_xbox360_application.h"
#include <xray/engine/api.h>
#include <xray/os_include.h>
using stalker2::application;
void application::initialize( )
{
m_exit_code = 0;
xray::engine::preinitialize ( m_game_proxy, GetCommandLine( ), "stalker2", __DATE__ );
xray::engine::initialize ( );
}
void application::finalize ( )
{
xray::engine::finalize ( );
}
void application::execute ( )
{
xray::engine::execute ( );
} | [
"youalexandrov@icloud.com"
] | youalexandrov@icloud.com |
80ab919e80f08753c45ba7c32582f124b9361697 | 57a358cd438ca01ff51819da75a2504890c6960f | /external/clang/lib/CodeGen/CGClass.cpp | 287d164cb9924bfdfcb7d5f5fef66c604333f47e | [
"NCSA"
] | permissive | xlm04322/android-4.3 | 52801b27e570fa7148b14a7be5c29c4b6ecc5d1d | d035e0af4a5927f615a24780a547cf08a9f6f61e | refs/heads/master | 2022-04-08T10:55:44.941632 | 2015-02-20T10:07:55 | 2015-02-20T10:07:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84,678 | cpp | //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with C++ code generation of classes
//
//===----------------------------------------------------------------------===//
#include "CGBlocks.h"
#include "CGDebugInfo.h"
#include "CGRecordLayout.h"
#include "CodeGenFunction.h"
#include "CGCXXABI.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/TargetBuiltins.h"
#include "clang/Frontend/CodeGenOptions.h"
using namespace clang;
using namespace CodeGen;
static CharUnits
ComputeNonVirtualBaseClassOffset(ASTContext &Context,
const CXXRecordDecl *DerivedClass,
CastExpr::path_const_iterator Start,
CastExpr::path_const_iterator End) {
CharUnits Offset = CharUnits::Zero();
const CXXRecordDecl *RD = DerivedClass;
for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
const CXXBaseSpecifier *Base = *I;
assert(!Base->isVirtual() && "Should not see virtual bases here!");
// Get the layout.
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const CXXRecordDecl *BaseDecl =
cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
// Add the offset.
Offset += Layout.getBaseClassOffset(BaseDecl);
RD = BaseDecl;
}
return Offset;
}
llvm::Constant *
CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd) {
assert(PathBegin != PathEnd && "Base path should not be empty!");
CharUnits Offset =
ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
PathBegin, PathEnd);
if (Offset.isZero())
return 0;
llvm::Type *PtrDiffTy =
Types.ConvertType(getContext().getPointerDiffType());
return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
}
/// Gets the address of a direct base class within a complete object.
/// This should only be used for (1) non-virtual bases or (2) virtual bases
/// when the type is known to be complete (e.g. in complete destructors).
///
/// The object pointed to by 'This' is assumed to be non-null.
llvm::Value *
CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
const CXXRecordDecl *Derived,
const CXXRecordDecl *Base,
bool BaseIsVirtual) {
// 'this' must be a pointer (in some address space) to Derived.
assert(This->getType()->isPointerTy() &&
cast<llvm::PointerType>(This->getType())->getElementType()
== ConvertType(Derived));
// Compute the offset of the virtual base.
CharUnits Offset;
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
if (BaseIsVirtual)
Offset = Layout.getVBaseClassOffset(Base);
else
Offset = Layout.getBaseClassOffset(Base);
// Shift and cast down to the base type.
// TODO: for complete types, this should be possible with a GEP.
llvm::Value *V = This;
if (Offset.isPositive()) {
V = Builder.CreateBitCast(V, Int8PtrTy);
V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
}
V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
return V;
}
static llvm::Value *
ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
CharUnits nonVirtualOffset,
llvm::Value *virtualOffset) {
// Assert that we have something to do.
assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
// Compute the offset from the static and dynamic components.
llvm::Value *baseOffset;
if (!nonVirtualOffset.isZero()) {
baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
nonVirtualOffset.getQuantity());
if (virtualOffset) {
baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
}
} else {
baseOffset = virtualOffset;
}
// Apply the base offset.
ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
return ptr;
}
llvm::Value *
CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
const CXXRecordDecl *Derived,
CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd,
bool NullCheckValue) {
assert(PathBegin != PathEnd && "Base path should not be empty!");
CastExpr::path_const_iterator Start = PathBegin;
const CXXRecordDecl *VBase = 0;
// Sema has done some convenient canonicalization here: if the
// access path involved any virtual steps, the conversion path will
// *start* with a step down to the correct virtual base subobject,
// and hence will not require any further steps.
if ((*Start)->isVirtual()) {
VBase =
cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
++Start;
}
// Compute the static offset of the ultimate destination within its
// allocating subobject (the virtual base, if there is one, or else
// the "complete" object that we see).
CharUnits NonVirtualOffset =
ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
Start, PathEnd);
// If there's a virtual step, we can sometimes "devirtualize" it.
// For now, that's limited to when the derived type is final.
// TODO: "devirtualize" this for accesses to known-complete objects.
if (VBase && Derived->hasAttr<FinalAttr>()) {
const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
NonVirtualOffset += vBaseOffset;
VBase = 0; // we no longer have a virtual step
}
// Get the base pointer type.
llvm::Type *BasePtrTy =
ConvertType((PathEnd[-1])->getType())->getPointerTo();
// If the static offset is zero and we don't have a virtual step,
// just do a bitcast; null checks are unnecessary.
if (NonVirtualOffset.isZero() && !VBase) {
return Builder.CreateBitCast(Value, BasePtrTy);
}
llvm::BasicBlock *origBB = 0;
llvm::BasicBlock *endBB = 0;
// Skip over the offset (and the vtable load) if we're supposed to
// null-check the pointer.
if (NullCheckValue) {
origBB = Builder.GetInsertBlock();
llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
endBB = createBasicBlock("cast.end");
llvm::Value *isNull = Builder.CreateIsNull(Value);
Builder.CreateCondBr(isNull, endBB, notNullBB);
EmitBlock(notNullBB);
}
// Compute the virtual offset.
llvm::Value *VirtualOffset = 0;
if (VBase) {
VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
}
// Apply both offsets.
Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
NonVirtualOffset,
VirtualOffset);
// Cast to the destination type.
Value = Builder.CreateBitCast(Value, BasePtrTy);
// Build a phi if we needed a null check.
if (NullCheckValue) {
llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
Builder.CreateBr(endBB);
EmitBlock(endBB);
llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
PHI->addIncoming(Value, notNullBB);
PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Value = PHI;
}
return Value;
}
llvm::Value *
CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
const CXXRecordDecl *Derived,
CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd,
bool NullCheckValue) {
assert(PathBegin != PathEnd && "Base path should not be empty!");
QualType DerivedTy =
getContext().getCanonicalType(getContext().getTagDeclType(Derived));
llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
llvm::Value *NonVirtualOffset =
CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
if (!NonVirtualOffset) {
// No offset, we can just cast back.
return Builder.CreateBitCast(Value, DerivedPtrTy);
}
llvm::BasicBlock *CastNull = 0;
llvm::BasicBlock *CastNotNull = 0;
llvm::BasicBlock *CastEnd = 0;
if (NullCheckValue) {
CastNull = createBasicBlock("cast.null");
CastNotNull = createBasicBlock("cast.notnull");
CastEnd = createBasicBlock("cast.end");
llvm::Value *IsNull = Builder.CreateIsNull(Value);
Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
EmitBlock(CastNotNull);
}
// Apply the offset.
Value = Builder.CreateBitCast(Value, Int8PtrTy);
Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
"sub.ptr");
// Just cast.
Value = Builder.CreateBitCast(Value, DerivedPtrTy);
if (NullCheckValue) {
Builder.CreateBr(CastEnd);
EmitBlock(CastNull);
Builder.CreateBr(CastEnd);
EmitBlock(CastEnd);
llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
PHI->addIncoming(Value, CastNotNull);
PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
CastNull);
Value = PHI;
}
return Value;
}
llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
bool ForVirtualBase,
bool Delegating) {
if (!CodeGenVTables::needsVTTParameter(GD)) {
// This constructor/destructor does not need a VTT parameter.
return 0;
}
const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
llvm::Value *VTT;
uint64_t SubVTTIndex;
if (Delegating) {
// If this is a delegating constructor call, just load the VTT.
return LoadCXXVTT();
} else if (RD == Base) {
// If the record matches the base, this is the complete ctor/dtor
// variant calling the base variant in a class with virtual bases.
assert(!CodeGenVTables::needsVTTParameter(CurGD) &&
"doing no-op VTT offset in base dtor/ctor?");
assert(!ForVirtualBase && "Can't have same class as virtual base!");
SubVTTIndex = 0;
} else {
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
CharUnits BaseOffset = ForVirtualBase ?
Layout.getVBaseClassOffset(Base) :
Layout.getBaseClassOffset(Base);
SubVTTIndex =
CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
}
if (CodeGenVTables::needsVTTParameter(CurGD)) {
// A VTT parameter was passed to the constructor, use it.
VTT = LoadCXXVTT();
VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
} else {
// We're the complete constructor, so get the VTT by name.
VTT = CGM.getVTables().GetAddrOfVTT(RD);
VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
}
return VTT;
}
namespace {
/// Call the destructor for a direct base class.
struct CallBaseDtor : EHScopeStack::Cleanup {
const CXXRecordDecl *BaseClass;
bool BaseIsVirtual;
CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
: BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
void Emit(CodeGenFunction &CGF, Flags flags) {
const CXXRecordDecl *DerivedClass =
cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
const CXXDestructorDecl *D = BaseClass->getDestructor();
llvm::Value *Addr =
CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
DerivedClass, BaseClass,
BaseIsVirtual);
CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
/*Delegating=*/false, Addr);
}
};
/// A visitor which checks whether an initializer uses 'this' in a
/// way which requires the vtable to be properly set.
struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
bool UsesThis;
DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
// Black-list all explicit and implicit references to 'this'.
//
// Do we need to worry about external references to 'this' derived
// from arbitrary code? If so, then anything which runs arbitrary
// external code might potentially access the vtable.
void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
};
}
static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
DynamicThisUseChecker Checker(C);
Checker.Visit(const_cast<Expr*>(Init));
return Checker.UsesThis;
}
static void EmitBaseInitializer(CodeGenFunction &CGF,
const CXXRecordDecl *ClassDecl,
CXXCtorInitializer *BaseInit,
CXXCtorType CtorType) {
assert(BaseInit->isBaseInitializer() &&
"Must have base initializer!");
llvm::Value *ThisPtr = CGF.LoadCXXThis();
const Type *BaseType = BaseInit->getBaseClass();
CXXRecordDecl *BaseClassDecl =
cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
bool isBaseVirtual = BaseInit->isBaseVirtual();
// The base constructor doesn't construct virtual bases.
if (CtorType == Ctor_Base && isBaseVirtual)
return;
// If the initializer for the base (other than the constructor
// itself) accesses 'this' in any way, we need to initialize the
// vtables.
if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
CGF.InitializeVTablePointers(ClassDecl);
// We can pretend to be a complete class because it only matters for
// virtual bases, and we only do virtual bases for complete ctors.
llvm::Value *V =
CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
BaseClassDecl,
isBaseVirtual);
CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
AggValueSlot AggSlot =
AggValueSlot::forAddr(V, Alignment, Qualifiers(),
AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased);
CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
if (CGF.CGM.getLangOpts().Exceptions &&
!BaseClassDecl->hasTrivialDestructor())
CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
isBaseVirtual);
}
static void EmitAggMemberInitializer(CodeGenFunction &CGF,
LValue LHS,
Expr *Init,
llvm::Value *ArrayIndexVar,
QualType T,
ArrayRef<VarDecl *> ArrayIndexes,
unsigned Index) {
if (Index == ArrayIndexes.size()) {
LValue LV = LHS;
{ // Scope for Cleanups.
CodeGenFunction::RunCleanupsScope Cleanups(CGF);
if (ArrayIndexVar) {
// If we have an array index variable, load it and use it as an offset.
// Then, increment the value.
llvm::Value *Dest = LHS.getAddress();
llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
CGF.Builder.CreateStore(Next, ArrayIndexVar);
// Update the LValue.
LV.setAddress(Dest);
CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
LV.setAlignment(std::min(Align, LV.getAlignment()));
}
switch (CGF.getEvaluationKind(T)) {
case TEK_Scalar:
CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
break;
case TEK_Complex:
CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
break;
case TEK_Aggregate: {
AggValueSlot Slot =
AggValueSlot::forLValue(LV,
AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased);
CGF.EmitAggExpr(Init, Slot);
break;
}
}
}
// Now, outside of the initializer cleanup scope, destroy the backing array
// for a std::initializer_list member.
CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
return;
}
const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
assert(Array && "Array initialization without the array type?");
llvm::Value *IndexVar
= CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
assert(IndexVar && "Array index variable not loaded");
// Initialize this index variable to zero.
llvm::Value* Zero
= llvm::Constant::getNullValue(
CGF.ConvertType(CGF.getContext().getSizeType()));
CGF.Builder.CreateStore(Zero, IndexVar);
// Start the loop with a block that tests the condition.
llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
CGF.EmitBlock(CondBlock);
llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
// Generate: if (loop-index < number-of-elements) fall to the loop body,
// otherwise, go to the block after the for-loop.
uint64_t NumElements = Array->getSize().getZExtValue();
llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
llvm::Value *NumElementsPtr =
llvm::ConstantInt::get(Counter->getType(), NumElements);
llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
"isless");
// If the condition is true, execute the body.
CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
CGF.EmitBlock(ForBody);
llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
{
CodeGenFunction::RunCleanupsScope Cleanups(CGF);
// Inside the loop body recurse to emit the inner loop or, eventually, the
// constructor call.
EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
Array->getElementType(), ArrayIndexes, Index + 1);
}
CGF.EmitBlock(ContinueBlock);
// Emit the increment of the loop counter.
llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
Counter = CGF.Builder.CreateLoad(IndexVar);
NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
CGF.Builder.CreateStore(NextVal, IndexVar);
// Finally, branch back up to the condition for the next iteration.
CGF.EmitBranch(CondBlock);
// Emit the fall-through block.
CGF.EmitBlock(AfterFor, true);
}
static void EmitMemberInitializer(CodeGenFunction &CGF,
const CXXRecordDecl *ClassDecl,
CXXCtorInitializer *MemberInit,
const CXXConstructorDecl *Constructor,
FunctionArgList &Args) {
assert(MemberInit->isAnyMemberInitializer() &&
"Must have member initializer!");
assert(MemberInit->getInit() && "Must have initializer!");
// non-static data member initializers.
FieldDecl *Field = MemberInit->getAnyMember();
QualType FieldType = Field->getType();
llvm::Value *ThisPtr = CGF.LoadCXXThis();
QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
if (MemberInit->isIndirectMemberInitializer()) {
// If we are initializing an anonymous union field, drill down to
// the field.
IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
IEnd = IndirectField->chain_end();
for ( ; I != IEnd; ++I)
LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
} else {
LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
}
// Special case: if we are in a copy or move constructor, and we are copying
// an array of PODs or classes with trivial copy constructors, ignore the
// AST and perform the copy we know is equivalent.
// FIXME: This is hacky at best... if we had a bit more explicit information
// in the AST, we could generalize it more easily.
const ConstantArrayType *Array
= CGF.getContext().getAsConstantArrayType(FieldType);
if (Array && Constructor->isImplicitlyDefined() &&
Constructor->isCopyOrMoveConstructor()) {
QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
if (BaseElementTy.isPODType(CGF.getContext()) ||
(CE && CE->getConstructor()->isTrivial())) {
// Find the source pointer. We know it's the last argument because
// we know we're in an implicit copy constructor.
unsigned SrcArgIndex = Args.size() - 1;
llvm::Value *SrcPtr
= CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
// Copy the aggregate.
CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
LHS.isVolatileQualified());
return;
}
}
ArrayRef<VarDecl *> ArrayIndexes;
if (MemberInit->getNumArrayIndices())
ArrayIndexes = MemberInit->getArrayIndexes();
CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
}
void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
LValue LHS, Expr *Init,
ArrayRef<VarDecl *> ArrayIndexes) {
QualType FieldType = Field->getType();
switch (getEvaluationKind(FieldType)) {
case TEK_Scalar:
if (LHS.isSimple()) {
EmitExprAsInit(Init, Field, LHS, false);
} else {
RValue RHS = RValue::get(EmitScalarExpr(Init));
EmitStoreThroughLValue(RHS, LHS);
}
break;
case TEK_Complex:
EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
break;
case TEK_Aggregate: {
llvm::Value *ArrayIndexVar = 0;
if (ArrayIndexes.size()) {
llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
// The LHS is a pointer to the first object we'll be constructing, as
// a flat array.
QualType BaseElementTy = getContext().getBaseElementType(FieldType);
llvm::Type *BasePtr = ConvertType(BaseElementTy);
BasePtr = llvm::PointerType::getUnqual(BasePtr);
llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
BasePtr);
LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
// Create an array index that will be used to walk over all of the
// objects we're constructing.
ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Builder.CreateStore(Zero, ArrayIndexVar);
// Emit the block variables for the array indices, if any.
for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
EmitAutoVarDecl(*ArrayIndexes[I]);
}
EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
ArrayIndexes, 0);
}
}
// Ensure that we destroy this object if an exception is thrown
// later in the constructor.
QualType::DestructionKind dtorKind = FieldType.isDestructedType();
if (needsEHCleanup(dtorKind))
pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
}
/// Checks whether the given constructor is a valid subject for the
/// complete-to-base constructor delegation optimization, i.e.
/// emitting the complete constructor as a simple call to the base
/// constructor.
static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
// Currently we disable the optimization for classes with virtual
// bases because (1) the addresses of parameter variables need to be
// consistent across all initializers but (2) the delegate function
// call necessarily creates a second copy of the parameter variable.
//
// The limiting example (purely theoretical AFAIK):
// struct A { A(int &c) { c++; } };
// struct B : virtual A {
// B(int count) : A(count) { printf("%d\n", count); }
// };
// ...although even this example could in principle be emitted as a
// delegation since the address of the parameter doesn't escape.
if (Ctor->getParent()->getNumVBases()) {
// TODO: white-list trivial vbase initializers. This case wouldn't
// be subject to the restrictions below.
// TODO: white-list cases where:
// - there are no non-reference parameters to the constructor
// - the initializers don't access any non-reference parameters
// - the initializers don't take the address of non-reference
// parameters
// - etc.
// If we ever add any of the above cases, remember that:
// - function-try-blocks will always blacklist this optimization
// - we need to perform the constructor prologue and cleanup in
// EmitConstructorBody.
return false;
}
// We also disable the optimization for variadic functions because
// it's impossible to "re-pass" varargs.
if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
return false;
// FIXME: Decide if we can do a delegation of a delegating constructor.
if (Ctor->isDelegatingConstructor())
return false;
return true;
}
/// EmitConstructorBody - Emits the body of the current constructor.
void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
CXXCtorType CtorType = CurGD.getCtorType();
// Before we go any further, try the complete->base constructor
// delegation optimization.
if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
CGM.getContext().getTargetInfo().getCXXABI().hasConstructorVariants()) {
if (CGDebugInfo *DI = getDebugInfo())
DI->EmitLocation(Builder, Ctor->getLocEnd());
EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
return;
}
Stmt *Body = Ctor->getBody();
// Enter the function-try-block before the constructor prologue if
// applicable.
bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
if (IsTryBody)
EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
// TODO: in restricted cases, we can emit the vbase initializers of
// a complete ctor and then delegate to the base ctor.
// Emit the constructor prologue, i.e. the base and member
// initializers.
EmitCtorPrologue(Ctor, CtorType, Args);
// Emit the body of the statement.
if (IsTryBody)
EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
else if (Body)
EmitStmt(Body);
// Emit any cleanup blocks associated with the member or base
// initializers, which includes (along the exceptional path) the
// destructors for those members and bases that were fully
// constructed.
PopCleanupBlocks(CleanupDepth);
if (IsTryBody)
ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
}
namespace {
class FieldMemcpyizer {
public:
FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
const VarDecl *SrcRec)
: CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
LastAddedFieldIndex(0) { }
static bool isMemcpyableField(FieldDecl *F) {
Qualifiers Qual = F->getType().getQualifiers();
if (Qual.hasVolatile() || Qual.hasObjCLifetime())
return false;
return true;
}
void addMemcpyableField(FieldDecl *F) {
if (FirstField == 0)
addInitialField(F);
else
addNextField(F);
}
CharUnits getMemcpySize() const {
unsigned LastFieldSize =
LastField->isBitField() ?
LastField->getBitWidthValue(CGF.getContext()) :
CGF.getContext().getTypeSize(LastField->getType());
uint64_t MemcpySizeBits =
LastFieldOffset + LastFieldSize - FirstFieldOffset +
CGF.getContext().getCharWidth() - 1;
CharUnits MemcpySize =
CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
return MemcpySize;
}
void emitMemcpy() {
// Give the subclass a chance to bail out if it feels the memcpy isn't
// worth it (e.g. Hasn't aggregated enough data).
if (FirstField == 0) {
return;
}
CharUnits Alignment;
if (FirstField->isBitField()) {
const CGRecordLayout &RL =
CGF.getTypes().getCGRecordLayout(FirstField->getParent());
const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
} else {
Alignment = CGF.getContext().getDeclAlign(FirstField);
}
assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
Alignment) == 0 && "Bad field alignment.");
CharUnits MemcpySize = getMemcpySize();
QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
llvm::Value *ThisPtr = CGF.LoadCXXThis();
LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
MemcpySize, Alignment);
reset();
}
void reset() {
FirstField = 0;
}
protected:
CodeGenFunction &CGF;
const CXXRecordDecl *ClassDecl;
private:
void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
CharUnits Size, CharUnits Alignment) {
llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
llvm::Type *DBP =
llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
llvm::Type *SBP =
llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
Alignment.getQuantity());
}
void addInitialField(FieldDecl *F) {
FirstField = F;
LastField = F;
FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
LastFieldOffset = FirstFieldOffset;
LastAddedFieldIndex = F->getFieldIndex();
return;
}
void addNextField(FieldDecl *F) {
assert(F->getFieldIndex() == LastAddedFieldIndex + 1 &&
"Cannot aggregate non-contiguous fields.");
LastAddedFieldIndex = F->getFieldIndex();
// The 'first' and 'last' fields are chosen by offset, rather than field
// index. This allows the code to support bitfields, as well as regular
// fields.
uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
if (FOffset < FirstFieldOffset) {
FirstField = F;
FirstFieldOffset = FOffset;
} else if (FOffset > LastFieldOffset) {
LastField = F;
LastFieldOffset = FOffset;
}
}
const VarDecl *SrcRec;
const ASTRecordLayout &RecLayout;
FieldDecl *FirstField;
FieldDecl *LastField;
uint64_t FirstFieldOffset, LastFieldOffset;
unsigned LastAddedFieldIndex;
};
class ConstructorMemcpyizer : public FieldMemcpyizer {
private:
/// Get source argument for copy constructor. Returns null if not a copy
/// constructor.
static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
FunctionArgList &Args) {
if (CD->isCopyOrMoveConstructor() && CD->isImplicitlyDefined())
return Args[Args.size() - 1];
return 0;
}
// Returns true if a CXXCtorInitializer represents a member initialization
// that can be rolled into a memcpy.
bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
if (!MemcpyableCtor)
return false;
FieldDecl *Field = MemberInit->getMember();
assert(Field != 0 && "No field for member init.");
QualType FieldType = Field->getType();
CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
// Bail out on non-POD, not-trivially-constructable members.
if (!(CE && CE->getConstructor()->isTrivial()) &&
!(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
FieldType->isReferenceType()))
return false;
// Bail out on volatile fields.
if (!isMemcpyableField(Field))
return false;
// Otherwise we're good.
return true;
}
public:
ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
FunctionArgList &Args)
: FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
ConstructorDecl(CD),
MemcpyableCtor(CD->isImplicitlyDefined() &&
CD->isCopyOrMoveConstructor() &&
CGF.getLangOpts().getGC() == LangOptions::NonGC),
Args(Args) { }
void addMemberInitializer(CXXCtorInitializer *MemberInit) {
if (isMemberInitMemcpyable(MemberInit)) {
AggregatedInits.push_back(MemberInit);
addMemcpyableField(MemberInit->getMember());
} else {
emitAggregatedInits();
EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
ConstructorDecl, Args);
}
}
void emitAggregatedInits() {
if (AggregatedInits.size() <= 1) {
// This memcpy is too small to be worthwhile. Fall back on default
// codegen.
for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
AggregatedInits[i], ConstructorDecl, Args);
}
reset();
return;
}
pushEHDestructors();
emitMemcpy();
AggregatedInits.clear();
}
void pushEHDestructors() {
llvm::Value *ThisPtr = CGF.LoadCXXThis();
QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
QualType FieldType = AggregatedInits[i]->getMember()->getType();
QualType::DestructionKind dtorKind = FieldType.isDestructedType();
if (CGF.needsEHCleanup(dtorKind))
CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
}
}
void finish() {
emitAggregatedInits();
}
private:
const CXXConstructorDecl *ConstructorDecl;
bool MemcpyableCtor;
FunctionArgList &Args;
SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
};
class AssignmentMemcpyizer : public FieldMemcpyizer {
private:
// Returns the memcpyable field copied by the given statement, if one
// exists. Otherwise r
FieldDecl* getMemcpyableField(Stmt *S) {
if (!AssignmentsMemcpyable)
return 0;
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
// Recognise trivial assignments.
if (BO->getOpcode() != BO_Assign)
return 0;
MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
if (!ME)
return 0;
FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
if (!Field || !isMemcpyableField(Field))
return 0;
Stmt *RHS = BO->getRHS();
if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
RHS = EC->getSubExpr();
if (!RHS)
return 0;
MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
return 0;
return Field;
} else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
if (!(MD && (MD->isCopyAssignmentOperator() ||
MD->isMoveAssignmentOperator()) &&
MD->isTrivial()))
return 0;
MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
if (!IOA)
return 0;
FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
if (!Field || !isMemcpyableField(Field))
return 0;
MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
return 0;
return Field;
} else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
return 0;
Expr *DstPtr = CE->getArg(0);
if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
DstPtr = DC->getSubExpr();
UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
if (!DUO || DUO->getOpcode() != UO_AddrOf)
return 0;
MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
if (!ME)
return 0;
FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
if (!Field || !isMemcpyableField(Field))
return 0;
Expr *SrcPtr = CE->getArg(1);
if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
SrcPtr = SC->getSubExpr();
UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
if (!SUO || SUO->getOpcode() != UO_AddrOf)
return 0;
MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
return 0;
return Field;
}
return 0;
}
bool AssignmentsMemcpyable;
SmallVector<Stmt*, 16> AggregatedStmts;
public:
AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
FunctionArgList &Args)
: FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
assert(Args.size() == 2);
}
void emitAssignment(Stmt *S) {
FieldDecl *F = getMemcpyableField(S);
if (F) {
addMemcpyableField(F);
AggregatedStmts.push_back(S);
} else {
emitAggregatedStmts();
CGF.EmitStmt(S);
}
}
void emitAggregatedStmts() {
if (AggregatedStmts.size() <= 1) {
for (unsigned i = 0; i < AggregatedStmts.size(); ++i)
CGF.EmitStmt(AggregatedStmts[i]);
reset();
}
emitMemcpy();
AggregatedStmts.clear();
}
void finish() {
emitAggregatedStmts();
}
};
}
/// EmitCtorPrologue - This routine generates necessary code to initialize
/// base classes and non-static data members belonging to this constructor.
void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
CXXCtorType CtorType,
FunctionArgList &Args) {
if (CD->isDelegatingConstructor())
return EmitDelegatingCXXConstructorCall(CD, Args);
const CXXRecordDecl *ClassDecl = CD->getParent();
CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
E = CD->init_end();
llvm::BasicBlock *BaseCtorContinueBB = 0;
if (ClassDecl->getNumVBases() &&
!CGM.getTarget().getCXXABI().hasConstructorVariants()) {
// The ABIs that don't have constructor variants need to put a branch
// before the virtual base initialization code.
BaseCtorContinueBB = CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this);
assert(BaseCtorContinueBB);
}
// Virtual base initializers first.
for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
}
if (BaseCtorContinueBB) {
// Complete object handler should continue to the remaining initializers.
Builder.CreateBr(BaseCtorContinueBB);
EmitBlock(BaseCtorContinueBB);
}
// Then, non-virtual base initializers.
for (; B != E && (*B)->isBaseInitializer(); B++) {
assert(!(*B)->isBaseVirtual());
EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
}
InitializeVTablePointers(ClassDecl);
// And finally, initialize class members.
ConstructorMemcpyizer CM(*this, CD, Args);
for (; B != E; B++) {
CXXCtorInitializer *Member = (*B);
assert(!Member->isBaseInitializer());
assert(Member->isAnyMemberInitializer() &&
"Delegating initializer on non-delegating constructor");
CM.addMemberInitializer(Member);
}
CM.finish();
}
static bool
FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
static bool
HasTrivialDestructorBody(ASTContext &Context,
const CXXRecordDecl *BaseClassDecl,
const CXXRecordDecl *MostDerivedClassDecl)
{
// If the destructor is trivial we don't have to check anything else.
if (BaseClassDecl->hasTrivialDestructor())
return true;
if (!BaseClassDecl->getDestructor()->hasTrivialBody())
return false;
// Check fields.
for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
E = BaseClassDecl->field_end(); I != E; ++I) {
const FieldDecl *Field = *I;
if (!FieldHasTrivialDestructorBody(Context, Field))
return false;
}
// Check non-virtual bases.
for (CXXRecordDecl::base_class_const_iterator I =
BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
I != E; ++I) {
if (I->isVirtual())
continue;
const CXXRecordDecl *NonVirtualBase =
cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
if (!HasTrivialDestructorBody(Context, NonVirtualBase,
MostDerivedClassDecl))
return false;
}
if (BaseClassDecl == MostDerivedClassDecl) {
// Check virtual bases.
for (CXXRecordDecl::base_class_const_iterator I =
BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
I != E; ++I) {
const CXXRecordDecl *VirtualBase =
cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
if (!HasTrivialDestructorBody(Context, VirtualBase,
MostDerivedClassDecl))
return false;
}
}
return true;
}
static bool
FieldHasTrivialDestructorBody(ASTContext &Context,
const FieldDecl *Field)
{
QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
if (!RT)
return true;
CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
}
/// CanSkipVTablePointerInitialization - Check whether we need to initialize
/// any vtable pointers before calling this destructor.
static bool CanSkipVTablePointerInitialization(ASTContext &Context,
const CXXDestructorDecl *Dtor) {
if (!Dtor->hasTrivialBody())
return false;
// Check the fields.
const CXXRecordDecl *ClassDecl = Dtor->getParent();
for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
E = ClassDecl->field_end(); I != E; ++I) {
const FieldDecl *Field = *I;
if (!FieldHasTrivialDestructorBody(Context, Field))
return false;
}
return true;
}
/// EmitDestructorBody - Emits the body of the current destructor.
void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
CXXDtorType DtorType = CurGD.getDtorType();
// The call to operator delete in a deleting destructor happens
// outside of the function-try-block, which means it's always
// possible to delegate the destructor body to the complete
// destructor. Do so.
if (DtorType == Dtor_Deleting) {
EnterDtorCleanups(Dtor, Dtor_Deleting);
EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
/*Delegating=*/false, LoadCXXThis());
PopCleanupBlock();
return;
}
Stmt *Body = Dtor->getBody();
// If the body is a function-try-block, enter the try before
// anything else.
bool isTryBody = (Body && isa<CXXTryStmt>(Body));
if (isTryBody)
EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
// Enter the epilogue cleanups.
RunCleanupsScope DtorEpilogue(*this);
// If this is the complete variant, just invoke the base variant;
// the epilogue will destruct the virtual bases. But we can't do
// this optimization if the body is a function-try-block, because
// we'd introduce *two* handler blocks.
switch (DtorType) {
case Dtor_Deleting: llvm_unreachable("already handled deleting case");
case Dtor_Complete:
// Enter the cleanup scopes for virtual bases.
EnterDtorCleanups(Dtor, Dtor_Complete);
if (!isTryBody &&
CGM.getContext().getTargetInfo().getCXXABI().hasDestructorVariants()) {
EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
/*Delegating=*/false, LoadCXXThis());
break;
}
// Fallthrough: act like we're in the base variant.
case Dtor_Base:
// Enter the cleanup scopes for fields and non-virtual bases.
EnterDtorCleanups(Dtor, Dtor_Base);
// Initialize the vtable pointers before entering the body.
if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
InitializeVTablePointers(Dtor->getParent());
if (isTryBody)
EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
else if (Body)
EmitStmt(Body);
else {
assert(Dtor->isImplicit() && "bodyless dtor not implicit");
// nothing to do besides what's in the epilogue
}
// -fapple-kext must inline any call to this dtor into
// the caller's body.
if (getLangOpts().AppleKext)
CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
break;
}
// Jump out through the epilogue cleanups.
DtorEpilogue.ForceCleanup();
// Exit the try if applicable.
if (isTryBody)
ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
}
void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
const Stmt *RootS = AssignOp->getBody();
assert(isa<CompoundStmt>(RootS) &&
"Body of an implicit assignment operator should be compound stmt.");
const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
LexicalScope Scope(*this, RootCS->getSourceRange());
AssignmentMemcpyizer AM(*this, AssignOp, Args);
for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
E = RootCS->body_end();
I != E; ++I) {
AM.emitAssignment(*I);
}
AM.finish();
}
namespace {
/// Call the operator delete associated with the current destructor.
struct CallDtorDelete : EHScopeStack::Cleanup {
CallDtorDelete() {}
void Emit(CodeGenFunction &CGF, Flags flags) {
const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
const CXXRecordDecl *ClassDecl = Dtor->getParent();
CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
CGF.getContext().getTagDeclType(ClassDecl));
}
};
struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
llvm::Value *ShouldDeleteCondition;
public:
CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
: ShouldDeleteCondition(ShouldDeleteCondition) {
assert(ShouldDeleteCondition != NULL);
}
void Emit(CodeGenFunction &CGF, Flags flags) {
llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
llvm::Value *ShouldCallDelete
= CGF.Builder.CreateIsNull(ShouldDeleteCondition);
CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
CGF.EmitBlock(callDeleteBB);
const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
const CXXRecordDecl *ClassDecl = Dtor->getParent();
CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
CGF.getContext().getTagDeclType(ClassDecl));
CGF.Builder.CreateBr(continueBB);
CGF.EmitBlock(continueBB);
}
};
class DestroyField : public EHScopeStack::Cleanup {
const FieldDecl *field;
CodeGenFunction::Destroyer *destroyer;
bool useEHCleanupForArray;
public:
DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
bool useEHCleanupForArray)
: field(field), destroyer(destroyer),
useEHCleanupForArray(useEHCleanupForArray) {}
void Emit(CodeGenFunction &CGF, Flags flags) {
// Find the address of the field.
llvm::Value *thisValue = CGF.LoadCXXThis();
QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
LValue LV = CGF.EmitLValueForField(ThisLV, field);
assert(LV.isSimple());
CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
flags.isForNormalCleanup() && useEHCleanupForArray);
}
};
}
/// EmitDtorEpilogue - Emit all code that comes at the end of class's
/// destructor. This is to call destructors on members and base classes
/// in reverse order of their construction.
void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
CXXDtorType DtorType) {
assert(!DD->isTrivial() &&
"Should not emit dtor epilogue for trivial dtor!");
// The deleting-destructor phase just needs to call the appropriate
// operator delete that Sema picked up.
if (DtorType == Dtor_Deleting) {
assert(DD->getOperatorDelete() &&
"operator delete missing - EmitDtorEpilogue");
if (CXXStructorImplicitParamValue) {
// If there is an implicit param to the deleting dtor, it's a boolean
// telling whether we should call delete at the end of the dtor.
EHStack.pushCleanup<CallDtorDeleteConditional>(
NormalAndEHCleanup, CXXStructorImplicitParamValue);
} else {
EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
}
return;
}
const CXXRecordDecl *ClassDecl = DD->getParent();
// Unions have no bases and do not call field destructors.
if (ClassDecl->isUnion())
return;
// The complete-destructor phase just destructs all the virtual bases.
if (DtorType == Dtor_Complete) {
// We push them in the forward order so that they'll be popped in
// the reverse order.
for (CXXRecordDecl::base_class_const_iterator I =
ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
I != E; ++I) {
const CXXBaseSpecifier &Base = *I;
CXXRecordDecl *BaseClassDecl
= cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
// Ignore trivial destructors.
if (BaseClassDecl->hasTrivialDestructor())
continue;
EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
BaseClassDecl,
/*BaseIsVirtual*/ true);
}
return;
}
assert(DtorType == Dtor_Base);
// Destroy non-virtual bases.
for (CXXRecordDecl::base_class_const_iterator I =
ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
const CXXBaseSpecifier &Base = *I;
// Ignore virtual bases.
if (Base.isVirtual())
continue;
CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
// Ignore trivial destructors.
if (BaseClassDecl->hasTrivialDestructor())
continue;
EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
BaseClassDecl,
/*BaseIsVirtual*/ false);
}
// Destroy direct fields.
SmallVector<const FieldDecl *, 16> FieldDecls;
for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
E = ClassDecl->field_end(); I != E; ++I) {
const FieldDecl *field = *I;
QualType type = field->getType();
QualType::DestructionKind dtorKind = type.isDestructedType();
if (!dtorKind) continue;
// Anonymous union members do not have their destructors called.
const RecordType *RT = type->getAsUnionType();
if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
CleanupKind cleanupKind = getCleanupKind(dtorKind);
EHStack.pushCleanup<DestroyField>(cleanupKind, field,
getDestroyer(dtorKind),
cleanupKind & EHCleanup);
}
}
/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
/// constructor for each of several members of an array.
///
/// \param ctor the constructor to call for each element
/// \param arrayType the type of the array to initialize
/// \param arrayBegin an arrayType*
/// \param zeroInitialize true if each element should be
/// zero-initialized before it is constructed
void
CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
const ConstantArrayType *arrayType,
llvm::Value *arrayBegin,
CallExpr::const_arg_iterator argBegin,
CallExpr::const_arg_iterator argEnd,
bool zeroInitialize) {
QualType elementType;
llvm::Value *numElements =
emitArrayLength(arrayType, elementType, arrayBegin);
EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
argBegin, argEnd, zeroInitialize);
}
/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
/// constructor for each of several members of an array.
///
/// \param ctor the constructor to call for each element
/// \param numElements the number of elements in the array;
/// may be zero
/// \param arrayBegin a T*, where T is the type constructed by ctor
/// \param zeroInitialize true if each element should be
/// zero-initialized before it is constructed
void
CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
llvm::Value *numElements,
llvm::Value *arrayBegin,
CallExpr::const_arg_iterator argBegin,
CallExpr::const_arg_iterator argEnd,
bool zeroInitialize) {
// It's legal for numElements to be zero. This can happen both
// dynamically, because x can be zero in 'new A[x]', and statically,
// because of GCC extensions that permit zero-length arrays. There
// are probably legitimate places where we could assume that this
// doesn't happen, but it's not clear that it's worth it.
llvm::BranchInst *zeroCheckBranch = 0;
// Optimize for a constant count.
llvm::ConstantInt *constantCount
= dyn_cast<llvm::ConstantInt>(numElements);
if (constantCount) {
// Just skip out if the constant count is zero.
if (constantCount->isZero()) return;
// Otherwise, emit the check.
} else {
llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
EmitBlock(loopBB);
}
// Find the end of the array.
llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
"arrayctor.end");
// Enter the loop, setting up a phi for the current location to initialize.
llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
EmitBlock(loopBB);
llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
"arrayctor.cur");
cur->addIncoming(arrayBegin, entryBB);
// Inside the loop body, emit the constructor call on the array element.
QualType type = getContext().getTypeDeclType(ctor->getParent());
// Zero initialize the storage, if requested.
if (zeroInitialize)
EmitNullInitialization(cur, type);
// C++ [class.temporary]p4:
// There are two contexts in which temporaries are destroyed at a different
// point than the end of the full-expression. The first context is when a
// default constructor is called to initialize an element of an array.
// If the constructor has one or more default arguments, the destruction of
// every temporary created in a default argument expression is sequenced
// before the construction of the next array element, if any.
{
RunCleanupsScope Scope(*this);
// Evaluate the constructor and its arguments in a regular
// partial-destroy cleanup.
if (getLangOpts().Exceptions &&
!ctor->getParent()->hasTrivialDestructor()) {
Destroyer *destroyer = destroyCXXObject;
pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
}
EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
/*Delegating=*/false, cur, argBegin, argEnd);
}
// Go to the next element.
llvm::Value *next =
Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
"arrayctor.next");
cur->addIncoming(next, Builder.GetInsertBlock());
// Check whether that's the end of the loop.
llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
Builder.CreateCondBr(done, contBB, loopBB);
// Patch the earlier check to skip over the loop.
if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
EmitBlock(contBB);
}
void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
llvm::Value *addr,
QualType type) {
const RecordType *rtype = type->castAs<RecordType>();
const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
const CXXDestructorDecl *dtor = record->getDestructor();
assert(!dtor->isTrivial());
CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
/*Delegating=*/false, addr);
}
void
CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
CXXCtorType Type, bool ForVirtualBase,
bool Delegating,
llvm::Value *This,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd) {
CGDebugInfo *DI = getDebugInfo();
if (DI &&
CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
// If debug info for this class has not been emitted then this is the
// right time to do so.
const CXXRecordDecl *Parent = D->getParent();
DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
Parent->getLocation());
}
// If this is a trivial constructor, just emit what's needed.
if (D->isTrivial()) {
if (ArgBeg == ArgEnd) {
// Trivial default constructor, no codegen required.
assert(D->isDefaultConstructor() &&
"trivial 0-arg ctor not a default ctor");
return;
}
assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
assert(D->isCopyOrMoveConstructor() &&
"trivial 1-arg ctor not a copy/move ctor");
const Expr *E = (*ArgBeg);
QualType Ty = E->getType();
llvm::Value *Src = EmitLValue(E).getAddress();
EmitAggregateCopy(This, Src, Ty);
return;
}
// Non-trivial constructors are handled in an ABI-specific manner.
CGM.getCXXABI().EmitConstructorCall(*this, D, Type, ForVirtualBase,
Delegating, This, ArgBeg, ArgEnd);
}
void
CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
llvm::Value *This, llvm::Value *Src,
CallExpr::const_arg_iterator ArgBeg,
CallExpr::const_arg_iterator ArgEnd) {
if (D->isTrivial()) {
assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
assert(D->isCopyOrMoveConstructor() &&
"trivial 1-arg ctor not a copy/move ctor");
EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
return;
}
llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
clang::Ctor_Complete);
assert(D->isInstance() &&
"Trying to emit a member call expr on a static method!");
const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
CallArgList Args;
// Push the this ptr.
Args.add(RValue::get(This), D->getThisType(getContext()));
// Push the src ptr.
QualType QT = *(FPT->arg_type_begin());
llvm::Type *t = CGM.getTypes().ConvertType(QT);
Src = Builder.CreateBitCast(Src, t);
Args.add(RValue::get(Src), QT);
// Skip over first argument (Src).
++ArgBeg;
CallExpr::const_arg_iterator Arg = ArgBeg;
for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
assert(Arg != ArgEnd && "Running over edge of argument list!");
EmitCallArg(Args, *Arg, *I);
}
// Either we've emitted all the call args, or we have a call to a
// variadic function.
assert((Arg == ArgEnd || FPT->isVariadic()) &&
"Extra arguments in non-variadic function!");
// If we still have any arguments, emit them using the type of the argument.
for (; Arg != ArgEnd; ++Arg) {
QualType ArgType = Arg->getType();
EmitCallArg(Args, *Arg, ArgType);
}
EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
Callee, ReturnValueSlot(), Args, D);
}
void
CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
CXXCtorType CtorType,
const FunctionArgList &Args) {
CallArgList DelegateArgs;
FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
assert(I != E && "no parameters to constructor");
// this
DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
++I;
// vtt
if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
/*ForVirtualBase=*/false,
/*Delegating=*/true)) {
QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
DelegateArgs.add(RValue::get(VTT), VoidPP);
if (CodeGenVTables::needsVTTParameter(CurGD)) {
assert(I != E && "cannot skip vtt parameter, already done with args");
assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
++I;
}
}
// Explicit arguments.
for (; I != E; ++I) {
const VarDecl *param = *I;
EmitDelegateCallArg(DelegateArgs, param);
}
EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
ReturnValueSlot(), DelegateArgs, Ctor);
}
namespace {
struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
const CXXDestructorDecl *Dtor;
llvm::Value *Addr;
CXXDtorType Type;
CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
CXXDtorType Type)
: Dtor(D), Addr(Addr), Type(Type) {}
void Emit(CodeGenFunction &CGF, Flags flags) {
CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
/*Delegating=*/true, Addr);
}
};
}
void
CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
const FunctionArgList &Args) {
assert(Ctor->isDelegatingConstructor());
llvm::Value *ThisPtr = LoadCXXThis();
QualType Ty = getContext().getTagDeclType(Ctor->getParent());
CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
AggValueSlot AggSlot =
AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased);
EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
const CXXRecordDecl *ClassDecl = Ctor->getParent();
if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
CXXDtorType Type =
CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
ClassDecl->getDestructor(),
ThisPtr, Type);
}
}
void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
CXXDtorType Type,
bool ForVirtualBase,
bool Delegating,
llvm::Value *This) {
llvm::Value *VTT = GetVTTParameter(GlobalDecl(DD, Type),
ForVirtualBase, Delegating);
llvm::Value *Callee = 0;
if (getLangOpts().AppleKext)
Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
DD->getParent());
if (!Callee)
Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
// FIXME: Provide a source location here.
EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
VTT, getContext().getPointerType(getContext().VoidPtrTy),
0, 0);
}
namespace {
struct CallLocalDtor : EHScopeStack::Cleanup {
const CXXDestructorDecl *Dtor;
llvm::Value *Addr;
CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
: Dtor(D), Addr(Addr) {}
void Emit(CodeGenFunction &CGF, Flags flags) {
CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
/*ForVirtualBase=*/false,
/*Delegating=*/false, Addr);
}
};
}
void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
llvm::Value *Addr) {
EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
}
void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
if (!ClassDecl) return;
if (ClassDecl->hasTrivialDestructor()) return;
const CXXDestructorDecl *D = ClassDecl->getDestructor();
assert(D && D->isUsed() && "destructor not marked as used!");
PushDestructorCleanup(D, Addr);
}
llvm::Value *
CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) {
llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
CharUnits VBaseOffsetOffset =
CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
llvm::Value *VBaseOffsetPtr =
Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
"vbase.offset.ptr");
llvm::Type *PtrDiffTy =
ConvertType(getContext().getPointerDiffType());
VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
PtrDiffTy->getPointerTo());
llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
return VBaseOffset;
}
void
CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
const CXXRecordDecl *NearestVBase,
CharUnits OffsetFromNearestVBase,
llvm::Constant *VTable,
const CXXRecordDecl *VTableClass) {
const CXXRecordDecl *RD = Base.getBase();
// Compute the address point.
llvm::Value *VTableAddressPoint;
// Check if we need to use a vtable from the VTT.
if (CodeGenVTables::needsVTTParameter(CurGD) &&
(RD->getNumVBases() || NearestVBase)) {
// Get the secondary vpointer index.
uint64_t VirtualPointerIndex =
CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
/// Load the VTT.
llvm::Value *VTT = LoadCXXVTT();
if (VirtualPointerIndex)
VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
// And load the address point from the VTT.
VTableAddressPoint = Builder.CreateLoad(VTT);
} else {
uint64_t AddressPoint =
CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
VTableAddressPoint =
Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
}
// Compute where to store the address point.
llvm::Value *VirtualOffset = 0;
CharUnits NonVirtualOffset = CharUnits::Zero();
if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
// We need to use the virtual base offset offset because the virtual base
// might have a different offset in the most derived class.
VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
NearestVBase);
NonVirtualOffset = OffsetFromNearestVBase;
} else {
// We can just use the base offset in the complete class.
NonVirtualOffset = Base.getBaseOffset();
}
// Apply the offsets.
llvm::Value *VTableField = LoadCXXThis();
if (!NonVirtualOffset.isZero() || VirtualOffset)
VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
NonVirtualOffset,
VirtualOffset);
// Finally, store the address point.
llvm::Type *AddressPointPtrTy =
VTableAddressPoint->getType()->getPointerTo();
VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
}
void
CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
const CXXRecordDecl *NearestVBase,
CharUnits OffsetFromNearestVBase,
bool BaseIsNonVirtualPrimaryBase,
llvm::Constant *VTable,
const CXXRecordDecl *VTableClass,
VisitedVirtualBasesSetTy& VBases) {
// If this base is a non-virtual primary base the address point has already
// been set.
if (!BaseIsNonVirtualPrimaryBase) {
// Initialize the vtable pointer for this base.
InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
VTable, VTableClass);
}
const CXXRecordDecl *RD = Base.getBase();
// Traverse bases.
for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
E = RD->bases_end(); I != E; ++I) {
CXXRecordDecl *BaseDecl
= cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
// Ignore classes without a vtable.
if (!BaseDecl->isDynamicClass())
continue;
CharUnits BaseOffset;
CharUnits BaseOffsetFromNearestVBase;
bool BaseDeclIsNonVirtualPrimaryBase;
if (I->isVirtual()) {
// Check if we've visited this virtual base before.
if (!VBases.insert(BaseDecl))
continue;
const ASTRecordLayout &Layout =
getContext().getASTRecordLayout(VTableClass);
BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
BaseOffsetFromNearestVBase = CharUnits::Zero();
BaseDeclIsNonVirtualPrimaryBase = false;
} else {
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
BaseOffsetFromNearestVBase =
OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
}
InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
I->isVirtual() ? BaseDecl : NearestVBase,
BaseOffsetFromNearestVBase,
BaseDeclIsNonVirtualPrimaryBase,
VTable, VTableClass, VBases);
}
}
void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
// Ignore classes without a vtable.
if (!RD->isDynamicClass())
return;
// Get the VTable.
llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
// Initialize the vtable pointers for this class and all of its bases.
VisitedVirtualBasesSetTy VBases;
InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
/*NearestVBase=*/0,
/*OffsetFromNearestVBase=*/CharUnits::Zero(),
/*BaseIsNonVirtualPrimaryBase=*/false,
VTable, RD, VBases);
}
llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
llvm::Type *Ty) {
llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
return VTable;
}
static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
const Expr *E = Base;
while (true) {
E = E->IgnoreParens();
if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
if (CE->getCastKind() == CK_DerivedToBase ||
CE->getCastKind() == CK_UncheckedDerivedToBase ||
CE->getCastKind() == CK_NoOp) {
E = CE->getSubExpr();
continue;
}
}
break;
}
QualType DerivedType = E->getType();
if (const PointerType *PTy = DerivedType->getAs<PointerType>())
DerivedType = PTy->getPointeeType();
return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
}
// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
// quite what we want.
static const Expr *skipNoOpCastsAndParens(const Expr *E) {
while (true) {
if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
E = PE->getSubExpr();
continue;
}
if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
if (CE->getCastKind() == CK_NoOp) {
E = CE->getSubExpr();
continue;
}
}
if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
if (UO->getOpcode() == UO_Extension) {
E = UO->getSubExpr();
continue;
}
}
return E;
}
}
/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
/// function call on the given expr can be devirtualized.
static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
const CXXMethodDecl *MD) {
// If the most derived class is marked final, we know that no subclass can
// override this member function and so we can devirtualize it. For example:
//
// struct A { virtual void f(); }
// struct B final : A { };
//
// void f(B *b) {
// b->f();
// }
//
const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
if (MostDerivedClassDecl->hasAttr<FinalAttr>())
return true;
// If the member function is marked 'final', we know that it can't be
// overridden and can therefore devirtualize it.
if (MD->hasAttr<FinalAttr>())
return true;
// Similarly, if the class itself is marked 'final' it can't be overridden
// and we can therefore devirtualize the member function call.
if (MD->getParent()->hasAttr<FinalAttr>())
return true;
Base = skipNoOpCastsAndParens(Base);
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
// This is a record decl. We know the type and can devirtualize it.
return VD->getType()->isRecordType();
}
return false;
}
// We can always devirtualize calls on temporary object expressions.
if (isa<CXXConstructExpr>(Base))
return true;
// And calls on bound temporaries.
if (isa<CXXBindTemporaryExpr>(Base))
return true;
// Check if this is a call expr that returns a record type.
if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
return CE->getCallReturnType()->isRecordType();
// We can't devirtualize the call.
return false;
}
static bool UseVirtualCall(ASTContext &Context,
const CXXOperatorCallExpr *CE,
const CXXMethodDecl *MD) {
if (!MD->isVirtual())
return false;
// When building with -fapple-kext, all calls must go through the vtable since
// the kernel linker can do runtime patching of vtables.
if (Context.getLangOpts().AppleKext)
return true;
return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
}
llvm::Value *
CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
const CXXMethodDecl *MD,
llvm::Value *This) {
llvm::FunctionType *fnType =
CGM.getTypes().GetFunctionType(
CGM.getTypes().arrangeCXXMethodDeclaration(MD));
if (UseVirtualCall(getContext(), E, MD))
return BuildVirtualCall(MD, This, fnType);
return CGM.GetAddrOfFunction(MD, fnType);
}
void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
CallArgList &callArgs) {
// Lookup the call operator
DeclarationName operatorName
= getContext().DeclarationNames.getCXXOperatorName(OO_Call);
CXXMethodDecl *callOperator =
cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
// Get the address of the call operator.
const CGFunctionInfo &calleeFnInfo =
CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
llvm::Value *callee =
CGM.GetAddrOfFunction(GlobalDecl(callOperator),
CGM.getTypes().GetFunctionType(calleeFnInfo));
// Prepare the return slot.
const FunctionProtoType *FPT =
callOperator->getType()->castAs<FunctionProtoType>();
QualType resultType = FPT->getResultType();
ReturnValueSlot returnSlot;
if (!resultType->isVoidType() &&
calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
!hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
// We don't need to separately arrange the call arguments because
// the call can't be variadic anyway --- it's impossible to forward
// variadic arguments.
// Now emit our call.
RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
callArgs, callOperator);
// If necessary, copy the returned value into the slot.
if (!resultType->isVoidType() && returnSlot.isNull())
EmitReturnOfRValue(RV, resultType);
else
EmitBranchThroughCleanup(ReturnBlock);
}
void CodeGenFunction::EmitLambdaBlockInvokeBody() {
const BlockDecl *BD = BlockInfo->getBlockDecl();
const VarDecl *variable = BD->capture_begin()->getVariable();
const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
// Start building arguments for forwarding call
CallArgList CallArgs;
QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
CallArgs.add(RValue::get(ThisPtr), ThisType);
// Add the rest of the parameters.
for (BlockDecl::param_const_iterator I = BD->param_begin(),
E = BD->param_end(); I != E; ++I) {
ParmVarDecl *param = *I;
EmitDelegateCallArg(CallArgs, param);
}
EmitForwardingCallToLambda(Lambda, CallArgs);
}
void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
// FIXME: Making this work correctly is nasty because it requires either
// cloning the body of the call operator or making the call operator forward.
CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
return;
}
EmitFunctionBody(Args);
}
void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
const CXXRecordDecl *Lambda = MD->getParent();
// Start building arguments for forwarding call
CallArgList CallArgs;
QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
CallArgs.add(RValue::get(ThisPtr), ThisType);
// Add the rest of the parameters.
for (FunctionDecl::param_const_iterator I = MD->param_begin(),
E = MD->param_end(); I != E; ++I) {
ParmVarDecl *param = *I;
EmitDelegateCallArg(CallArgs, param);
}
EmitForwardingCallToLambda(Lambda, CallArgs);
}
void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
if (MD->isVariadic()) {
// FIXME: Making this work correctly is nasty because it requires either
// cloning the body of the call operator or making the call operator forward.
CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
return;
}
EmitLambdaDelegatingInvokeBody(MD);
}
| [
"xdtianyu@gmial.com"
] | xdtianyu@gmial.com |
dd3e3854630e5eaca97bf8c6930ae7d2191c4805 | 00555504a585ceef10ee4cc591098cb4930568c9 | /Competitive-Programming-Templates-master/C++_Templates/Segment Tree Lazy Propagation - Range Sum.cpp | d1aa9c589e597d0c98b06fb4a3e41955cb40b9ca | [] | no_license | Arhan13/CPP | 1b82e48538da647b160bc6c55d666d5171ba687b | 475cc5183790a924319b77040035417fae10f2b7 | refs/heads/master | 2022-12-22T09:34:15.868544 | 2020-10-01T04:27:44 | 2020-10-01T04:27:44 | 300,066,145 | 0 | 2 | null | 2020-10-01T04:27:45 | 2020-09-30T21:21:35 | C++ | UTF-8 | C++ | false | false | 1,792 | cpp | // Use Segment Tree with Lazy Propagation - Range Sum
struct Node {
int l, r;
ll val, lazy;
};
struct Seg {
private:
int N;
vector<Node> tree;
public:
Seg(int N) : N(N), tree(N << 2) { }
inline void Push_Up (int idx) {
tree[idx].val = tree[idx << 1].val + tree[idx << 1 | 1].val;
}
inline void Push_Down (int idx) {
if (tree[idx].lazy && tree[idx].l ^ tree[idx].r) {
tree[idx << 1].val += tree[idx].lazy * (tree[idx << 1].r - tree[idx << 1].l + 1);
tree[idx << 1].lazy += tree[idx].lazy;
tree[idx << 1 | 1].val += tree[idx].lazy * (tree[idx << 1 | 1].r - tree[idx << 1 | 1].l + 1);
tree[idx << 1 | 1].lazy += tree[idx].lazy;
tree[idx].lazy = 0;
}
}
inline void Build (int idx, int l, int r) {
tree[idx].l = l, tree[idx].r = r;
if (l == r) {
tree[idx].val = spin[l];
return;
}
int mid = (l + r) >> 1;
Build(idx << 1, l, mid);
Build(idx << 1 | 1, mid + 1, r);
Push_Up(idx);
}
inline void Update (int idx, int l, int r, int val) {
Push_Down(idx);
if (tree[idx].l > r || tree[idx].r < l) return;
if (tree[idx].l >= l && tree[idx].r <= r) {
tree[idx].val += val * (tree[idx].r - tree[idx].l + 1);
tree[idx].lazy += val;
return;
}
Update(idx << 1, l, r, val);
Update(idx << 1 | 1, l, r, val);
Push_Up(idx);
}
inline ll Query (int idx, int l, int r) {
Push_Down(idx);
if (tree[idx].l > r || tree[idx].r < l) return 0;
if (tree[idx].l >= l && tree[idx].r <= r) return tree[idx].val;
return Query(idx << 1, l, r) + Query(idx << 1 | 1, l, r);
}
}; | [
"60483503+Arhan13@users.noreply.github.com"
] | 60483503+Arhan13@users.noreply.github.com |
e0f7f21e4f63ff907f97b8b468429ace9dcbf275 | 055a1b7a111092cb3208d6ee581dd0ed0a4ec887 | /ProgrammingLanguageSlice/cpp-home/std/std_greater.cpp | 7c4f584836efaf4e388fc02d46d120e05aa91b91 | [] | no_license | StrayDragon/MemorySlice | e325456ce47354857b5934b7add1e00cc59b0867 | 057cddc66915dc539e82ee8fd41304e97c35e5b9 | refs/heads/master | 2020-03-27T23:49:43.462343 | 2019-02-02T08:50:54 | 2019-02-02T08:50:54 | 147,350,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 420 | cpp | #include<iostream>
#include<functional>
#include<vector>
using namespace std;
template<class T,class Compare=std::greater<T>>
class A{
Compare comp;
public:
bool g(){
return true;
}
bool f(int a,int b){
return comp(a,b);
}
};
int main(){
A<int> a;
cout << boolalpha << a.f(1,2) << endl << a.f(3,2) << endl;
A<int,less<int>> b;
cout << boolalpha << b.f(1,2) << endl << b.f(3,2) << endl;
return 0;
}
| [
"straydragonl@foxmail.com"
] | straydragonl@foxmail.com |
92a357025283044949ce1a7dd2071cf0247e1741 | b46d497e59bd9fd0f05fc22bc2bc1562dd41f8c2 | /Build/hosClient/ProjectileManager.cpp | 763859ff6a69f40d90aeb57e7168e57ccf92650c | [
"MIT"
] | permissive | Game-institute-1st-While-true/PLUXER | b48c7ade13e449f0f9934d73d768ac7b65a113d8 | 4ec9ad0ccb1bdf4b221afa135482a458f06205b1 | refs/heads/main | 2023-06-21T19:42:38.012520 | 2021-07-13T14:01:05 | 2021-07-13T14:01:05 | 385,570,600 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 3,176 | cpp | #include "ProjectileManager.h"
ProjectileManager::ProjectileManager() : hos::com::Script(L"ProjectileManager")
{
ExecutionOrder = 7;
}
ProjectileManager::~ProjectileManager()
{
while (ProjectileList.size() != 0)
{
ProjectileList.pop_back();
}
}
void ProjectileManager::Reset()
{
}
void ProjectileManager::Awake()
{
// 자식들 목록 가져오기
for (int i = 0; i < m_GameObject->transform->GetChildCount(); i++)
{
ProjectileList.push_back(m_GameObject->transform->GetChild(i)->m_GameObject->GetComponent<Projectile>());
ProjectileList[i]->SetActive(false);
}
}
void ProjectileManager::Update()
{
// 자식들 상태 확인
}
void ProjectileManager::SetProjectile(hos::com::Transform* TF, int attackType)
{
if (attackType == 0)
{
// 비활성화 된 자식 가져오기
for (auto _iter = ProjectileList.begin(); _iter != ProjectileList.end(); _iter++)
{
if (!(*_iter)->GetActive())
{
(*_iter)->m_GameObject->transform->SetPosition(TF->GetPosition() + hos::Vector3(0, 8, 0));
(*_iter)->m_GameObject->transform->SetRotation(hos::Rotator(-90, 0, 0));
(*_iter)->m_GameObject->transform->SetScale(hos::Vector3(1, 1, 1));
(*_iter)->AttackArea->SetActive(true);
(*_iter)->AttackArea->SetDirection(hos::com::CapsuleCollision::DIRECTION_Z);
(*_iter)->SetAttackType(0);
(*_iter)->m_GameObject->transform->GetChild(0)->m_GameObject->SetActive(true);
(*_iter)->SetActive(true);
return;
}
}
}
if (attackType == 1)
{
for (auto _iter = ProjectileList.begin(); _iter != ProjectileList.end(); _iter++)
{
if (!(*_iter)->GetActive())
{
(*_iter)->m_GameObject->transform->SetPosition(TF->GetPosition() + hos::Vector3(0, 1, 0) + TF->GetForward());
(*_iter)->m_GameObject->transform->SetRotation(hos::Rotator(0, 0, 0));
(*_iter)->m_GameObject->transform->SetScale(hos::Vector3(0.5f, 0.5f, 0.5f));
(*_iter)->m_GameObject->transform->SetForward(TF->GetForward());
(*_iter)->AttackArea->SetActive(true);
(*_iter)->AttackArea->SetDirection(hos::com::CapsuleCollision::DIRECTION_Z);
(*_iter)->SetAttackType(1);
(*_iter)->m_GameObject->transform->GetChild(0)->m_GameObject->SetActive(true);
(*_iter)->SetActive(true);
return;
}
}
}
}
void ProjectileManager::ActiveProjectile(int index, int attackType, hos::Vector3 pos, bool btn)
{
// 다를 경우 셋팅을 바꿔준다.
if (btn)
{
ProjectileList[index]->SetAttackType(attackType);
ProjectileList[index]->m_GameObject->transform->SetPosition(pos);
ProjectileList[index]->m_GameObject->transform->SetRotation(hos::Rotator(-90, 0, 0));
ProjectileList[index]->m_GameObject->transform->GetChild(0)->m_GameObject->SetActive(true);
ProjectileList[index]->SetActive(true);
}
else
{
// 오브젝트 비활성화
ProjectileList[index]->m_GameObject->transform->SetPosition(pos);
ProjectileList[index]->m_GameObject->transform->GetChild(0)->m_GameObject->SetActive(false);
ProjectileList[index]->SetActive(false);
}
}
Projectile* ProjectileManager::GetProjectile(int index)
{
if (ProjectileList.size() <= index || index < 0)
return nullptr;
else
{
return ProjectileList[index];
}
}
| [
"mywon1203@gmail.com"
] | mywon1203@gmail.com |
778d6842099bebea486a7f4e17d18f2949ea91b3 | 3519dcccffdb485619955e20e02f836631b185eb | /Lek3/zad2.cpp | 1991a44012857aafe98b831986ff124af6a1bc46 | [] | no_license | ppitu/ZaawansowanyCpp | 2320353675efaabd0aba6e2af8254cc37c616186 | 99d53b033b61d53f9706320a5ad7470f106324dc | refs/heads/main | 2023-04-18T23:19:33.481458 | 2021-04-27T07:22:38 | 2021-04-27T07:22:38 | 357,458,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | cpp | #include <iostream>
template <typename T, typename U>
T convert(U u)
{
return static_cast<T>(u);
}
template <> int convert<int, double> (double u) { return static_cast<int>(u); }
template <> double convert<double, double> (double u) { return u; }
int main()
{
std::cout << convert<int>(3.14) << "\n";
std::cout << convert<double>(3.56) << "\n";
}
| [
"piotr.chmura.1998@o2.pl"
] | piotr.chmura.1998@o2.pl |
319d9dcfb18ca10a216265035c074c72f4321f23 | cbfbcb085686233536198c4e6bbe1c9e998a5053 | /scenario.h | aaf73969caef1fe90e5ced1deec77338c5221df2 | [
"Apache-2.0"
] | permissive | elsewhat/rdr2-mod-scene-director | c69b0815d78029bc41a84371827002c570b15e93 | 5e8ff75cfe040ef5911b80b8a0172172f28ed3d0 | refs/heads/master | 2020-09-27T03:31:33.748073 | 2020-01-07T21:59:45 | 2020-01-07T21:59:45 | 226,418,620 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | h | #pragma once
#include <vector>
struct Scenario
{
char* name;
bool hasEnterAnim;
};
std::vector<Scenario> getAllGTAScenarios(); | [
"dagfinn.parnas@gmail.com"
] | dagfinn.parnas@gmail.com |
34ff95dc8e81e860e20adf3349817f940727dcd5 | 69f4b0830ec7e6bc4ddbbfcd86147fbd5fae74ad | /Moshball/object2.h | edd304b66a2fb8cf8af1ef9ee660e4ee50fa294b | [] | no_license | claytonsuplinski/Moshball | a8e7f8774c2db73aacb456992ddb0aa4b828791a | 17cb5a732dcbff444b88183e33417111fab1a733 | refs/heads/master | 2020-05-30T14:27:06.068737 | 2015-06-14T19:37:40 | 2015-06-14T19:37:40 | 37,426,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,012 | h | /*
Name: Clayton Suplinski
ID: 906 580 2630
CS 559 Project 3
Creates a general textured object
-Taken from demo code
*/
/* Perry Kivolowitz - University of Wisconsin - Madison
Computer Sciences Department
*/
#pragma once
#include <vector>
#include <gl/glew.h>
#include <gl/freeglut.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "vertexattributes2.h"
class Object2
{
public:
Object2();
virtual void TakeDown();
virtual bool Initialize();
virtual void Draw(const glm::mat4 & projection, glm::mat4 modelview, const glm::ivec2 & size, const float time = 0) = 0;
virtual bool PostGLInitialize(GLuint * vertex_array_handle, GLuint * vertex_coordinate_handle, GLsizeiptr sz, const GLvoid * ptr);
virtual ~Object2();
protected:
GLuint vertex_coordinate_handle;
GLuint vertex_array_handle;
bool GLReturnedError(char * s);
std::vector<VertexAttributes> vertices;
std::vector<GLuint> vertex_indices;
private:
void InternalInitialize();
};
| [
"claytonsuplinski@gmail.com"
] | claytonsuplinski@gmail.com |
a2cfdfd549b36afbde13580165e6922e96244493 | e85fdbbea321fbe0ac699d92ab452c515f97d1e9 | /UVa10082.cpp | 9cab113de266030dae85a38195e72ba7b7454f61 | [] | no_license | fanliyong007/acmhomeworks | 3c212b2c74ab43ad16e7fe277093e4df49b3dd27 | 718c3aee1c8c621e2a8699cbf378ddf178b88c63 | refs/heads/master | 2021-01-22T19:58:54.871018 | 2019-09-24T04:57:19 | 2019-09-24T04:57:19 | 85,262,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 908 | cpp | #define local
#include<bits/stdc++.h>
using namespace std;
int main()
{
string word;
string character = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";
while (getline(cin,word))
{
for (int i = 0; i < word.length();i++)
{
if(word[i]==' ')
printf(" ");
else
for (int j = 0; j < character.length();j++)
{
if(word[i]==character[j])
{
printf("%c", character[j - 1]);
break;
}
else if(word[j]=='`'||word[j]=='Q'||word[j]=='A'||word[j]=='Z')
{
printf("%c",word[i]);
break;
}
}
}
printf("\n");
}
#ifdef local
system("pause");
#endif
return 0;
} | [
"fanliyong007@hotmail.com"
] | fanliyong007@hotmail.com |
aa3979a892d0ebda6b670c4f50c084ceba11397e | e3d7e104c08a789396bcb2120793a36a1bce2309 | /regDeps.cpp | e1b3fb181ccae2a1ffbe7aa113750a1724bebfc5 | [] | no_license | lamorgan/EC513 | bab849fc342629a1042df41d979e5ce780841bc2 | 97085d61336231f932e34a2a9fdabc382fb02f55 | refs/heads/master | 2020-03-30T06:42:51.592731 | 2018-09-29T17:41:43 | 2018-09-29T17:41:43 | 150,883,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,367 | cpp | #include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "pin.H"
// Output file name
ofstream OutFile;
// The array storing the spacing frequency between two dependant instructions
UINT64 *dependancySpacing;
UINT32 maxSize;
//arrays holding the registers and the instruction count
UINT32 inst_num = 0;
UINT32 writereg[400]; // picked size that seemed large enough
UINT32 readreg[40];
// This knob sets the output file name
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "result.csv", "specify the output file name");
// This knob will set the maximum spacing between two dependant instructions in the program
KNOB<string> KnobMaxSpacing(KNOB_MODE_WRITEONCE, "pintool", "s", "100", "specify the maximum spacing between two dependant instructions in the program");
// This function allocates the writereg array with the instruction count
VOID AllocateW(UINT32 cnt){
writereg[cnt] = inst_num;
}
// This function is called before every instruction is executed. Have to change
// the code to send in the register names from the Instrumentation function
VOID updateSpacingInfo(UINT32 reg){
UINT32 cnt;
cnt = writereg[reg];
// makes sure the index is within the maxSize
// have to subtract 1 otherwise first index starts at 1 and not 0
if(inst_num-cnt-1 < maxSize){
dependancySpacing[inst_num-cnt-1]++;
}
}
// when a new instruction is encountered the count gets incremented
VOID new_instr() {
inst_num++;
}
// Pin calls this function every time a new instruction is encountered
VOID Instruction(INS ins, VOID *v)
{
// Insert a call to updateSpacingInfo before every instruction.
// You may need to add arguments to the call.
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)new_instr, IARG_END);
UINT32 reg;
REG tmp;
inst_num++;
// loops through the write regs in instruction
UINT32 max_w = INS_MaxNumWRegs(ins);
for(UINT32 i = 0; i < max_w; i++){
tmp = INS_RegW(ins, i);
// if the reg is a partial, it gets the full reg name and sends it to allocate the writereg array
if(REG_is_partialreg(tmp)){
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)AllocateW,IARG_UINT32, (UINT32)REG_FullRegName(tmp), IARG_END);
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)AllocateW,IARG_UINT32, (UINT32)tmp, IARG_END);
}
// REG_EAX enum for the register we are looking at, easier to work with register
// can't send tmp because its a register type not a UINT32
// allocates the writereg array
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)AllocateW,IARG_UINT32, (UINT32)REG_EAX, IARG_END);
}
// loops through the read regs in instruction
UINT32 max_r = INS_MaxNumRRegs(ins);
UINT32 flag;
for(UINT32 i = 0; i < max_r; i++){
reg = (UINT32)INS_RegR(ins, i);
flag = 0;
// loops through read regs in the readreg array
for(UINT32 j = 0;j < i; j++)
// if the current register is the same as any previous register in the instruction flag is set to 1 (don't want to count
// same register in same instruction twice)
if(readreg[j] == reg){
flag = 1;
}
if(flag == 0) {
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)updateSpacingInfo, IARG_UINT32, reg, IARG_END); // calls updateSpacingInfo
readreg[i] = reg; // allocates the readreg array
}
}
}
// This function is called when the application exits
VOID Fini(INT32 code, VOID *v)
{
// Write to a file since cout and cerr maybe closed by the application
OutFile.open(KnobOutputFile.Value().c_str());
OutFile.setf(ios::showbase);
for(UINT32 i = 0; i < maxSize; i++)
OutFile << dependancySpacing[i]<<",";
OutFile.close();
}
// argc, argv are the entire command line, including pin -t <toolname> -- ...
int main(int argc, char * argv[])
{
// Initialize pin
PIN_Init(argc, argv);
printf("Warning: Pin Tool not implemented\n");
maxSize = atoi(KnobMaxSpacing.Value().c_str());
// Initializing depdendancy Spacing
dependancySpacing = new UINT64[maxSize];
// Register Instruction to be called to instrument instructions
INS_AddInstrumentFunction(Instruction, 0);
// Register Fini to be called when the application exits
PIN_AddFiniFunction(Fini, 0);
// Start the program, never returns
PIN_StartProgram();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
d5686ea0d98eb98368e561c6e28ef030877b9588 | 3efc50ba20499cc9948473ee9ed2ccfce257d79a | /data/code-jam/files/3024486_nika_5670781216358400_0_extracted_D.cpp | c8aa4d2dfc4e35d052cbc10b59a08f25658c9f6d | [] | no_license | arthurherbout/crypto_code_detection | 7e10ed03238278690d2d9acaa90fab73e52bab86 | 3c9ff8a4b2e4d341a069956a6259bf9f731adfc0 | refs/heads/master | 2020-07-29T15:34:31.380731 | 2019-12-20T13:52:39 | 2019-12-20T13:52:39 | 209,857,592 | 9 | 4 | null | 2019-12-20T13:52:42 | 2019-09-20T18:35:35 | C | UTF-8 | C++ | false | false | 2,920 | cpp | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <vector>
#include <iostream>
#include <map>
#include <set>
#include <algorithm>
#include <cstring>
#include <queue>
#include <sstream>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define SZ(x) (int)(x.size())
#define F0(i,n) for(int i=0;i<n;i++)
#define F1(i,n) for(int i=1;i<=n;i++)
#define CL(a,x) memset(x, a, sizeof(x))
const int inf = 1000000009;
const double pi = atan(1.0)*4.0;
const double eps = 1e-8;
ll gcd(ll x, ll y) { return y ? gcd(y, x%y) : x; }
int bc(int n) { return n ? bc((n-1)&n)+1 : 0; }
int i, j, k, m, n, l, ans;
char ss[1000002];
int d[5005];
vector<int> adj[5005];
bool cont[100][100][100];
bool conte[81][81][81][81];
vector<int> v;
void dfs(int i, int start, int pr) {
F0(j,SZ(v)) {
cont[start][i][v[j]] = 1;
if (j>0) {
conte[start][i][v[j-1]][v[j]] = 1;
conte[start][i][v[j]][v[j-1]] = 1;
}
}
F0(j,SZ(adj[i])) if (adj[i][j] != pr) {
v.push_back(adj[i][j]);
dfs(adj[i][j], start, i);
v.pop_back();
}
}
int rec(int i, int j, int i0, int j0) {
bool has = false;
F0(k,SZ(adj[j])) {
int l = adj[j][k];
if (!conte[i0][i][j][l] && !conte[j0][j][j][l]) has = true;
}
int best = -inf;
F0(k,SZ(adj[i])) {
int l = adj[i][k];
if (!conte[i0][i][i][l] && !conte[j0][j][i][l]); else continue;
int add = 0;
if (!cont[i0][i][l] && !cont[j0][j][l]) add = d[l];
best = max(best, add-rec(j,l,j0,i0));
}
if (best == -inf) {
if (!has) best = 0;
else best = -rec(j,i,j0,i0);
}
// cout << i << " " << j << " " << i0 << " " << j0 << " " << best << endl;
return best;
}
int sol(int i, int j) {
return rec(i, j, i, j);
}
int main() {
// freopen("x.in", "r", stdin);
freopen("D-small-attempt0.in", "r", stdin);
freopen("D-small-attempt0.out", "w", stdout);
// freopen("D-large.in", "r", stdin);
// freopen("D-large.out", "w", stdout);
int tt, tn; cin >> tn;
F1(tt,tn) {
cerr << tt << endl;
cin >> n;
F1(i,n) adj[i].clear();
F1(i,n) {
cin >> d[i];
}
F1(i,n-1) {
cin >> j;
adj[i].push_back(j);
adj[j].push_back(i);
}
int ans = -inf;
CL(0,cont);
CL(0,conte);
F1(i,n) {
v.clear();
v.push_back(i);
dfs(i, i,-1);
}
F1(i,n) {
int best = inf;
F1(j,n) if (i != j) {
best = min(best, sol(i,j)+d[i]-d[j]);
}
ans = max(ans, best);
}
printf("Case #%d: %d\n", tt, ans);
}
return 0;
}
| [
"arthurherbout@gmail.com"
] | arthurherbout@gmail.com |
6bb3b51468be5b3f1ae279ee5069b17070a88166 | bb680bda181ccecb66560594364194fcda4bde53 | /special.h | 76eb40baf60bdf2a00eafafa6ed6e39f7ba80034 | [] | no_license | sashakolpakov/coxeter | c72369d1d7ba401fb0c87ca86dcb51df33e97639 | 7b5a1f0039511326aeb616afb132a5065886b9d8 | refs/heads/master | 2020-09-27T10:17:25.454076 | 2018-02-26T21:57:36 | 2018-02-26T21:57:36 | 226,493,993 | 1 | 0 | null | 2019-12-07T10:35:52 | 2019-12-07T10:35:51 | null | UTF-8 | C++ | false | false | 449 | h | /*
This is special.h
Coxeter version 3.0 Copyright (C) 2002 Fokko du Cloux
See file main.cpp for full copyright notice
*/
#ifndef SPECIAL_H /* guard against multiple inclusions */
#define SPECIAL_H
#include "globals.h"
#include "commands.h"
namespace special {
using namespace coxeter;
/******** function declarations *********************************************/
void addSpecialCommands(commands::CommandTree* tree);
}
#endif
| [
"tscrimsh at umn.edu"
] | tscrimsh at umn.edu |
ab967c79a35f1fdbddad42b7ecbb56c5276fe9f6 | b84c859bde6b8827000ec4a88b57a58e917583ac | /install_aarch64/lifecycle_msgs/include/lifecycle_msgs/srv/detail/get_available_transitions__traits.hpp | 39309e5bbf90de4befde3a83c768e26f662c7409 | [] | no_license | InigoMonreal/rcc | 743a7e657364a81bcd6d9989a9b807bca9134509 | d02fee05d42767ffba6b706ad0c4e7678bc1afb1 | refs/heads/master | 2022-12-02T21:16:31.993047 | 2020-08-11T13:10:34 | 2020-08-11T13:10:34 | 285,869,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,970 | hpp | // generated from rosidl_generator_cpp/resource/idl__traits.hpp.em
// with input from lifecycle_msgs:srv/GetAvailableTransitions.idl
// generated code does not contain a copyright notice
#ifndef LIFECYCLE_MSGS__SRV__DETAIL__GET_AVAILABLE_TRANSITIONS__TRAITS_HPP_
#define LIFECYCLE_MSGS__SRV__DETAIL__GET_AVAILABLE_TRANSITIONS__TRAITS_HPP_
#include "lifecycle_msgs/srv/detail/get_available_transitions__struct.hpp"
#include <rosidl_runtime_cpp/traits.hpp>
#include <stdint.h>
#include <type_traits>
namespace rosidl_generator_traits
{
template<>
inline const char * data_type<lifecycle_msgs::srv::GetAvailableTransitions_Request>()
{
return "lifecycle_msgs::srv::GetAvailableTransitions_Request";
}
template<>
struct has_fixed_size<lifecycle_msgs::srv::GetAvailableTransitions_Request>
: std::integral_constant<bool, true> {};
template<>
struct has_bounded_size<lifecycle_msgs::srv::GetAvailableTransitions_Request>
: std::integral_constant<bool, true> {};
template<>
struct is_message<lifecycle_msgs::srv::GetAvailableTransitions_Request>
: std::true_type {};
} // namespace rosidl_generator_traits
namespace rosidl_generator_traits
{
template<>
inline const char * data_type<lifecycle_msgs::srv::GetAvailableTransitions_Response>()
{
return "lifecycle_msgs::srv::GetAvailableTransitions_Response";
}
template<>
struct has_fixed_size<lifecycle_msgs::srv::GetAvailableTransitions_Response>
: std::integral_constant<bool, false> {};
template<>
struct has_bounded_size<lifecycle_msgs::srv::GetAvailableTransitions_Response>
: std::integral_constant<bool, false> {};
template<>
struct is_message<lifecycle_msgs::srv::GetAvailableTransitions_Response>
: std::true_type {};
} // namespace rosidl_generator_traits
namespace rosidl_generator_traits
{
template<>
inline const char * data_type<lifecycle_msgs::srv::GetAvailableTransitions>()
{
return "lifecycle_msgs::srv::GetAvailableTransitions";
}
template<>
struct has_fixed_size<lifecycle_msgs::srv::GetAvailableTransitions>
: std::integral_constant<
bool,
has_fixed_size<lifecycle_msgs::srv::GetAvailableTransitions_Request>::value &&
has_fixed_size<lifecycle_msgs::srv::GetAvailableTransitions_Response>::value
>
{
};
template<>
struct has_bounded_size<lifecycle_msgs::srv::GetAvailableTransitions>
: std::integral_constant<
bool,
has_bounded_size<lifecycle_msgs::srv::GetAvailableTransitions_Request>::value &&
has_bounded_size<lifecycle_msgs::srv::GetAvailableTransitions_Response>::value
>
{
};
template<>
struct is_service<lifecycle_msgs::srv::GetAvailableTransitions>
: std::true_type
{
};
template<>
struct is_service_request<lifecycle_msgs::srv::GetAvailableTransitions_Request>
: std::true_type
{
};
template<>
struct is_service_response<lifecycle_msgs::srv::GetAvailableTransitions_Response>
: std::true_type
{
};
} // namespace rosidl_generator_traits
#endif // LIFECYCLE_MSGS__SRV__DETAIL__GET_AVAILABLE_TRANSITIONS__TRAITS_HPP_
| [
"22imonreal@gmail.com"
] | 22imonreal@gmail.com |
28720fcb97bc17fb729d71d8f8ec86db058a436d | 94d440e469c6a986305625e303c5b1ca69545016 | /Most_booked_hotel_room.cpp | bea045a6aba7887f837244a94ec86a5aaab84b22 | [] | no_license | punit156/Google_Interview_Problems | 646309bb410fbd4b11b29183ba1959ecc3581c5d | a0a9715593733d5051caaf5f658509f5ced99e1f | refs/heads/main | 2023-03-04T20:01:35.650377 | 2021-02-09T01:29:13 | 2021-02-09T01:29:13 | 326,508,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,106 | cpp | /*
Problem Statement :-
Given a hotel which has 10 floors [0-9], and each floor has 26 rooms
[A-Z]. '+' sign means room is booked and '-' sign means room is freed.
Find out which room is booked maximum number of times. If multiple
rooms are booked same number of times, return the lexicographically
smaller room number.
Given sequence will be valid. A room can only be freed after it has
been booked and initially all rooms are free.
Ex :- ["+1A", "+3E", "-1A", "+4F", "+1A", "-3E", "+3E"]
Here both 1A and 3E are booked same number of times (2), return 1A.
*/
/*
Tip :- We can ignore the freed rooms, i.e the elements starting with '-'
because ultimately we are counting the maximum room bookings, so only
'+' matters.
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
int main()
{
vector<string> bookings = {"+1A", "-1A", "+4F", "+3E"};
int n = bookings.size();
unordered_map <string, int> hash;
/* Calculate the frequency of all bookings first */
for(auto book : bookings)
{
if(book[0] == '+')
{
string room = book.substr(1); //We don't need the + sign.
hash[room]++;
}
}
string most_booked = "";
int max_freq = 0;
//Iterate over our hashmap to find out the most frequency room.
for(auto it = hash.begin(); it != hash.end(); it++)
{
if(it->second > max_freq)
{
/* If current freq is greater than max_freq, update the
most booked room and the max_freq*/
most_booked = it->first;
max_freq = it->second;
}
else if(it->second == max_freq)
{
/* If current freq is equal to max_freq, update most_booked
only if it is lexicographically greater than current one. */
if(it->first < most_booked)
{
most_booked = it->first;
}
/* No need to update the max_freq, as it is the same */
}
}
cout << most_booked;
return 0;
} | [
"48815774+punit156@users.noreply.github.com"
] | 48815774+punit156@users.noreply.github.com |
25aa8ccc5749b0db8b0686ba8da5616f404ff185 | cd94e4a89afb36b4d03f4808c6001c65217d63d7 | /SpehsEngine/Net/Signaling/SignalingServer.h | c870abeea98a621200d5aed6e8eea8d10d34d9a8 | [] | no_license | Yuuso/SpehsEngine | 61e35a6cc6f800fddd6aa36ad4e3b225c1f222e5 | 04bbddaf7c3d8d597f6b79cd54732506ce0b34cc | refs/heads/master | 2023-08-16T22:59:50.776551 | 2023-08-10T16:35:01 | 2023-08-10T16:35:01 | 51,141,207 | 1 | 1 | null | 2016-09-16T07:11:18 | 2016-02-05T10:49:43 | C++ | UTF-8 | C++ | false | false | 331 | h | #pragma once
#include "SpehsEngine/Net/Port.h"
#include <memory>
namespace se
{
namespace net
{
class IOService;
class SignalingServer
{
public:
SignalingServer(IOService& ioService, const Port& port);
~SignalingServer();
void update();
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
}
}
| [
"pragux@gmail.com"
] | pragux@gmail.com |
5c789d97919084ccd36282688e5ac1a5ca101bf8 | 424d9d65e27cd204cc22e39da3a13710b163f4e7 | /third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h | 5d6357a28f6d95f3e0ae6104f84b894a27d7d240 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | bigben0123/chromium | 7c5f4624ef2dacfaf010203b60f307d4b8e8e76d | 83d9cd5e98b65686d06368f18b4835adbab76d89 | refs/heads/master | 2023-01-10T11:02:26.202776 | 2020-10-30T09:47:16 | 2020-10-30T09:47:16 | 275,543,782 | 0 | 0 | BSD-3-Clause | 2020-10-30T09:47:18 | 2020-06-28T08:45:11 | null | UTF-8 | C++ | false | false | 1,376 | h | // Copyright 2018 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 THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_LAYOUT_NG_TEXT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_LAYOUT_NG_TEXT_H_
#include "third_party/blink/renderer/core/layout/layout_text.h"
namespace blink {
// This overrides the default LayoutText to reference LayoutNGInlineItems
// instead of InlineTextBoxes.
//
class CORE_EXPORT LayoutNGText : public LayoutText {
public:
LayoutNGText(Node* node, scoped_refptr<StringImpl> text)
: LayoutText(node, text) {
NOT_DESTROYED();
}
bool IsOfType(LayoutObjectType type) const override {
NOT_DESTROYED();
return type == kLayoutObjectNGText || LayoutText::IsOfType(type);
}
bool IsLayoutNGObject() const override {
NOT_DESTROYED();
return true;
}
private:
const base::span<NGInlineItem>* GetNGInlineItems() const final {
NOT_DESTROYED();
return &inline_items_;
}
base::span<NGInlineItem>* GetNGInlineItems() final {
NOT_DESTROYED();
return &inline_items_;
}
base::span<NGInlineItem> inline_items_;
};
DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutNGText, IsLayoutNGText());
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_LAYOUT_NG_TEXT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
fcbcc82be402c3a0160358550ecd5481327a4d11 | 73cb3238a06648e35ae375d8aa233d863af96959 | /src/compat/glibc_sanity.cpp | 38210f19c4613961b10aa3582d7327baef6fb510 | [
"MIT"
] | permissive | GenYuanLian/SourceChain | 75b9bc1492979ee0cad65d388bf4e87c437e6a93 | f278529e0a85d7be6aef1fa3989498a7dee70f51 | refs/heads/master | 2021-05-09T07:26:59.667630 | 2018-09-26T07:17:02 | 2018-09-26T07:17:02 | 119,361,549 | 6 | 3 | MIT | 2018-07-27T06:57:35 | 2018-01-29T09:31:00 | C++ | UTF-8 | C++ | false | false | 1,797 | cpp | // Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/srcchain-config.h"
#endif
#include <cstddef>
#if defined(HAVE_SYS_SELECT_H)
#include <sys/select.h>
#endif
extern "C" void* memcpy(void* a, const void* b, size_t c);
void* memcpy_int(void* a, const void* b, size_t c)
{
return memcpy(a, b, c);
}
namespace
{
// trigger: Use the memcpy_int wrapper which calls our internal memcpy.
// A direct call to memcpy may be optimized away by the compiler.
// test: Fill an array with a sequence of integers. memcpy to a new empty array.
// Verify that the arrays are equal. Use an odd size to decrease the odds of
// the call being optimized away.
template <unsigned int T>
bool sanity_test_memcpy()
{
unsigned int memcpy_test[T];
unsigned int memcpy_verify[T] = {};
for (unsigned int i = 0; i != T; ++i)
memcpy_test[i] = i;
memcpy_int(memcpy_verify, memcpy_test, sizeof(memcpy_test));
for (unsigned int i = 0; i != T; ++i) {
if (memcpy_verify[i] != i)
return false;
}
return true;
}
#if defined(HAVE_SYS_SELECT_H)
// trigger: Call FD_SET to trigger __fdelt_chk. FORTIFY_SOURCE must be defined
// as >0 and optimizations must be set to at least -O2.
// test: Add a file descriptor to an empty fd_set. Verify that it has been
// correctly added.
bool sanity_test_fdelt()
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
return FD_ISSET(0, &fds);
}
#endif
} // namespace
bool glibc_sanity_test()
{
#if defined(HAVE_SYS_SELECT_H)
if (!sanity_test_fdelt())
return false;
#endif
return sanity_test_memcpy<1025>();
}
| [
"519747074@qq.com"
] | 519747074@qq.com |
a713877d731f4561ab85e9349b5ee56d7aeb1dcc | d686bf545eb0fd59fdc6709bf3a4f419f6afdd5a | /挑战程序设计竞赛-算法和数据结构/02-搜索/01-线性搜索.cpp | ceab58e4c109834e7bbb2db18346b7296e0827c7 | [] | no_license | lesenelir/Learning-Algorithm-Notes | 06971a438180f6e09165c0ef5541d2288c6c9ad4 | 797df10db05a05a14736aa47a9ebbc681c6e75af | refs/heads/master | 2021-01-09T15:47:34.808135 | 2020-07-11T11:40:44 | 2020-07-11T11:40:44 | 242,361,406 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cpp | #include <cstdio>
#include <iostream>
using namespace std;
const int maxn = 10010;
int S[maxn];
int T[maxn];
bool lineSearch(int S[], int n, int key) {
bool flag = false;
for (int i = 0; i < n; i++) {
if (S[i] == key) {
flag = true;
break;
}
}
return flag;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &S[i]);
}
int q;
scanf("%d", &q);
for (int i = 0; i < q; i++) {
scanf("%d", &T[i]);
}
int count = 0;
for (int i = 0; i < q; i++) {
if (lineSearch(S, n, T[i]) == true) count++;
}
printf("%d\n", count);
return 0;
} | [
"miaomiaobabyzy@gmail.com"
] | miaomiaobabyzy@gmail.com |
575edab0b0578f01adcf5b464bbb4d522005584e | 1e6101e98acc94824a04fe907620b54080baf0dc | /arduino_programs/sketch_for_sensor/gps_v2.0_test_sd/gps_v2.0_test_sd.ino | 70136a82cacc749e2d5332c9501c2f007df52158 | [] | no_license | Ni3nayka/JANZER | ebfc913fbe28cbb94c99f9e03a88c47e4a54b2a3 | 97d8ec3cd6901b6e7616e10cb39776cf473efc90 | refs/heads/master | 2022-11-03T20:58:31.653555 | 2022-10-09T20:06:34 | 2022-10-09T20:06:34 | 224,026,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,031 | ino | #include <SoftwareSerial.h>
SoftwareSerial SoftSerial(8, 9);
//char f[400];
int i = 0;
byte gps_flag = 0;
byte gps_flag2 = 0;
byte fs = 0; // $
byte fz = 0; // ,
byte ft = 0; // .
byte sp = 0; // satellites - спутники
#include <SPI.h>
#include <SD.h>
File file;
char c;
void setup() {
Serial.begin(9600);
SoftSerial.begin(9600);
pinMode(7, OUTPUT);
//while (i < 100) { f[i] = 0; i++; } i = 0;
delay(100);
while(!Serial){;}
if(!SD.begin(10)){ Serial.println("ERROR: SD-card"); }
else { Serial.println("successfull: SD-card"); }
file = SD.open("GPS.txt", FILE_WRITE); // если файла с именем "____.txt" - нет, то он будет создан.
if(file){ // если файл доступен (открыт для записи), то ...
Serial.println("successfull: file is opened");
//kartochka = 1;
}
else {
Serial.println("ERROR: file is not opened");
}
file.println();
if(file){ file.close(); Serial.println("successfull: file is close"); }
digitalWrite(7, 0);
//while (true) {}
}
void loop() {
gps();
i = 0;
// Serial.println();
/*while (f[i] != 0) {
Serial.print(f[i]);
f[i] = 0;
i++;
}*/
i = 0;
//Serial.println("----------------------------------");
}
void gps() {
if(!SD.begin(10)){ Serial.println("ERROR: SD-card"); }
else { Serial.println("successfull: SD-card"); }
file = SD.open("GPS.txt", FILE_WRITE); // если файла с именем "____.txt" - нет, то он будет создан.
if(file){ // если файл доступен (открыт для записи), то ...
Serial.println("successfull: file is opened");
//kartochka = 1;
}
else {
Serial.println("ERROR: file is not opened");
}
file.println();
char F = 0;
byte fl = 0;
long int time_gps = millis();
gps_flag = 1; // <=================================
gps_flag2 = 1;
fs = 0; // $
fz = 0; // ,
ft = 0; // .
sp = 0; // спутники
//vivodln("gps:");
while ((fl < 2) && (time_gps + 2000 > millis())) { // проверка на неполные первые входные данные
if (SoftSerial.available() > 0) {
F = SoftSerial.read();
//Serial.print(F);
time_gps = millis();
fl = 1;
}
if ((millis() > time_gps + 100) && (fl == 1)) {
//Serial.println();
fl++;
time_gps = millis();
}
}
fl = 0;
time_gps = millis();
while ((fl < 2) && (time_gps + 2000 > millis())) {
if (SoftSerial.available() > 0) {
F = SoftSerial.read();
c = F;
gps_mozg(); // <=================================
//f[i] = F; i++; // отладка
//Serial.print(F);
//if(file){ file.print(F); }
time_gps = millis();
fl = 1;
}
if ((millis() > time_gps + 100) && (fl == 1)) {
//Serial.println();
fl++;
time_gps = millis();
}
}
if (gps_flag == 1) { vivod("ERROR: gps"); digitalWrite(13, 0); }
vivodln();
if(file){ file.close(); Serial.println("successfull: file is close"); }
}
void gps_mozg() {
if ((fs == 0)) { Serial.print("gps coordinates: "); file.print("gps coordinates: "); }
if (c == '$') { fs++; ft = 0; fz = 0; }
else if (c == '.') { ft++; }
else if (c == ',') { fz++; }
else if (fs == 1) { // определяем gps координаты
if ((fs == 1) && ((fz == 2) || (fz == 4))) { // ((fz == 1) && (ft == 0)) ||
//if (gps_flag != 9) { Serial.print(c); }
Serial.print(c); file.print(c);
if ((gps_flag == 2) || (gps_flag == 12)) { Serial.print('.'); file.print('.'); }
gps_flag++;
}
else if ((gps_flag == 9) || (gps_flag == 19)) { Serial.print("; "); file.print("; "); gps_flag++; }
}
else if (fs == 3 + sp) {
if ((sp == 0) && (fz == 1)) { // определяем кол-во спутников && (gps_flag == 20)
//gps_flag++;
if (gps_flag != 20) { // т.е. он не определил gps координаты
Serial.print("xxx; xxx; "); file.print("xxx; xxx; "); digitalWrite(13, 0);
}
else { digitalWrite(13, 1); }
Serial.println(); file.println();
Serial.print("gps satellites: "); file.print("gps satellites: ");
gps_flag = 21;
Serial.print(c); file.print(c);
//Serial.println(";");
if (c == '1') { sp = 1; }
else if (c == '2') { sp = 2; }
else if (c == '3') { sp = 3; }
else if (c == '4') { sp = 4; }
else if (c == '5') { sp = 5; }
else if (c == '6') { sp = 6; }
}
else if ((sp > 0) && (((fz == 1) && (ft == 0)) || (fz == 9))) { // определяем время и дату
Serial.print(c); file.print(c);
gps_flag++;
}
if ((gps_flag == 21) || (gps_flag == 30) || (gps_flag == 39)) { // || (gps_flag == 19)
Serial.println("; "); file.println("; ");
if (gps_flag == 21) {
//Serial.println();
Serial.print("gps time: "); file.print("gps time: ");
}
if (gps_flag == 30) {
//Serial.println();
Serial.print("gps date: "); file.print("gps date: ");
}
gps_flag++;
}
else if ((gps_flag == 24) || (gps_flag == 27)) { Serial.print(":"); file.print(":"); gps_flag++; }
else if ((gps_flag == 33) || (gps_flag == 36)) { Serial.print("."); file.print("."); gps_flag++; }
}
}
void vivodi(long int S) {
//Serial.print("file<");
Serial.print(S);
//Serial.print("> ");
if(file){ file.print(S); }
}
void vivodlni(long int S) {
// Serial.print("file<");
Serial.println(S);
//Serial.println("> ");
if(file){ file.println(S); }
}
void vivod(String S) {
//Serial.print("file<");
Serial.print(S);
//Serial.print("> ");
if(file){ file.print(S); }
}
void vivodln(String S) {
//Serial.print("file<");
Serial.println(S);
//Serial.println("> ");
if(file){ file.println(S); }
}
void vivodln() {
//Serial.print("file[endl] ");
Serial.println();
if(file){ file.println(); }
}
| [
"egor_bakay@inbox.ru"
] | egor_bakay@inbox.ru |
0f6405fdcd2ee3719dceb63a88a765342c2695b2 | 91aa07b9197dab8d4d630a0d3093f71ee263ef7b | /ffmpegOut/encode/auo_chapter.cpp | cc96fff179a50d34a806ed1544ae45600db132c5 | [] | no_license | ming-hai/ffmpegOut | 8553a6fa45ef61dd94170fb2ab84faa690b9d146 | 285e788d75a148c1d52e2d5de3e8eadcb571fb68 | refs/heads/master | 2021-01-19T23:18:59.565909 | 2018-03-07T12:06:50 | 2018-03-07T12:06:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,948 | cpp | // -----------------------------------------------------------------------------------------
// ffmpegOut by rigaya
// -----------------------------------------------------------------------------------------
// The MIT License
//
// Copyright (c) 2012-2017 rigaya
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// --------------------------------------------------------------------------------------------
#include <Windows.h>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <iostream>
#include <objbase.h>
#pragma comment(lib, "ole32.lib")
#include <mlang.h>
#include <xmllite.h>
#pragma comment (lib, "xmllite.lib")
#include <shlwapi.h>
#pragma comment (lib, "shlwapi.lib")
#include "auo.h"
#include "auo_util.h"
#include "auo_chapter.h"
using std::vector;
using std::string;
using std::wstring;
chapter_file::chapter_file() {
CoInitialize(NULL);
init();
}
chapter_file::~chapter_file() {
close();
CoUninitialize();
}
void chapter_file::init() {
close();
pImul = nullptr;
filepath = nullptr;
sts = AUO_CHAP_ERR_NONE;
chapter_type = CHAP_TYPE_UNKNOWN;
code_page = CODE_PAGE_UNSET;
duration = 0.0;
}
void chapter_file::close() {
if (chapters.size()) {
std::vector<std::unique_ptr<chapter>>().swap(chapters);
}
if (nullptr != pImul) {
pImul->Release();
}
pImul = nullptr;
}
int chapter_file::file_chapter_type() {
return chapter_type;
}
DWORD chapter_file::file_code_page() {
return code_page;
}
int chapter_file::get_result() {
return sts;
}
int chapter_file::read_file(const char *filepath, DWORD code_page, double duration) {
init();
this->filepath = filepath;
this->code_page = code_page;
this->duration = duration;
return read_file();
}
string chapter_file::to_utf8(wstring string) {
DWORD encMode = 0;
std::string string_utf8;
string_utf8.resize(string.length() * MAX_UTF8_CHAR_LENGTH, '\0');
UINT dst_len = (UINT)string_utf8.size();
if (S_OK != pImul->ConvertString(&encMode, CODE_PAGE_UTF16_LE, CODE_PAGE_UTF8, (BYTE *)&string[0], nullptr, (BYTE *)&string_utf8[0], &dst_len)) {
string_utf8 = "";
} else if (dst_len) {
string_utf8.resize(dst_len);
}
return string_utf8;
}
int chapter_file::write_chapter_apple_header(std::ostream& ostream) {
if (!ostream.good()) {
sts = AUO_CHAP_ERR_NULL_PTR;
return sts;
}
ostream.write((const char *)UTF8_BOM, sizeof(UTF8_BOM));
ostream << to_utf8(
L"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n"
L"<TextStream version=\"1.1\">\r\n"
L"<TextStreamHeader>\r\n"
L"<TextSampleDescription>\r\n"
L"</TextSampleDescription>\r\n"
L"</TextStreamHeader>\r\n");
return sts;
}
//終端 長さも指定する(しないとわけのわからんdurationになる)
int chapter_file::write_chapter_apple_foot(std::ostream& ostream) {
if (!ostream.good()) {
sts = AUO_CHAP_ERR_NULL_PTR;
} else {
int duration_ms = (int)(duration * 1000.0 + 0.5);
if (duration <= 0 && 0 < chapters.size()) {
duration_ms = chapters.back()->get_ms() + 1;
}
ostream << to_utf8(strprintf(
L"<TextSample sampleTime=\"%02d:%02d:%02d.%03d\" text=\"\" />\r\n</TextStream>",
duration_ms / (60*60*1000),
(duration_ms % (60*60*1000)) / (60*1000),
(duration_ms % (60*1000)) / 1000,
duration_ms % 1000
));
}
return sts;
}
int chapter_file::write_chapter_apple(const char *out_filepath) {
std::ofstream ostream(out_filepath, std::ios::out | std::ios::binary);
if (!ostream.good()) {
sts = AUO_CHAP_ERR_FILE_OPEN;
} else {
write_chapter_apple_header(ostream);
for (const auto& chap : chapters) {
ostream << to_utf8(strprintf(
L"<TextSample sampleTime=\"%02d:%02d:%02d.%03d\">%s</TextSample>\r\n",
chap->h, chap->m, chap->s, chap->ms, chap->name.c_str() ));
}
write_chapter_apple_foot(ostream);
ostream.close();
}
return sts;
}
int chapter_file::write_chapter_nero(const char *out_filepath, bool utf8) {
std::ofstream ostream(out_filepath, std::ios::out | std::ios::binary);
if (!ostream.good()) {
sts = AUO_CHAP_ERR_FILE_OPEN;
} else {
if (utf8)
ostream.write((const char *)UTF8_BOM, sizeof(UTF8_BOM));
const DWORD output_codepage = (utf8) ? CODE_PAGE_UTF8 : CODE_PAGE_SJIS;
std::vector<char> char_buffer;
for (DWORD i = 0; i < chapters.size(); i++) {
const auto& chap = chapters[i];
static const char * const KEY_BASE = "CHAPTER";
static const char * const KEY_NAME = "NAME";
const DWORD chapter_name_length = chap->name.length() + 1;
if (char_buffer.size() < chapter_name_length * 4)
char_buffer.resize(chapter_name_length * 4);
std::fill(char_buffer.begin(), char_buffer.end(), 0);
DWORD encMode = 0;
UINT buf_len_in_byte = char_buffer.size();
if (S_OK != pImul->ConvertString(&encMode, CODE_PAGE_UTF16_LE, output_codepage, (BYTE *)chap->name.c_str(), nullptr, (BYTE *)&char_buffer[0], &buf_len_in_byte))
return AUO_CHAP_ERR_CONVERTION;
ostream << strprintf("%s%02d=%02d:%02d:%02d.%03d\r\n", KEY_BASE, i+1, chap->h, chap->m, chap->s, chap->ms);
ostream << strprintf("%s%02d%s=%s\r\n", KEY_BASE, i+1, KEY_NAME, &char_buffer[0]);
}
ostream.close();
}
return sts;
}
int chapter_file::write_file(const char *out_filepath, int out_chapter_type, bool nero_in_utf8) {
if (CHAP_TYPE_UNKNOWN == out_chapter_type) {
out_chapter_type = chapter_type;
} else if (CHAP_TYPE_ANOTHER == out_chapter_type) {
out_chapter_type = (CHAP_TYPE_NERO == chapter_type) ? CHAP_TYPE_APPLE : CHAP_TYPE_NERO;
}
sts = (CHAP_TYPE_NERO == out_chapter_type) ? write_chapter_nero(out_filepath, nero_in_utf8) : write_chapter_apple(out_filepath);
return sts;
}
int chapter_file::overwrite_file(int out_chapter_type, bool nero_in_utf8) {
std::string temp_file = filepath;
temp_file += ".tmp";
for (int i = 0; PathFileExists(temp_file.c_str()); i++) {
temp_file = strprintf("%s.tmp%d", filepath, i);
}
sts = write_file(temp_file.c_str(), out_chapter_type, nero_in_utf8);
if (AUO_CHAP_ERR_NONE != sts) {
remove(temp_file.c_str());
} else {
remove(filepath);
rename(temp_file.c_str(), filepath);
}
return sts;
}
DWORD chapter_file::check_code_page(vector<char>& src, DWORD orig_code_page) {
DetectEncodingInfo dEnc = { 0 };
int denc_count = 1;
int src_buf_len = src.size();
if ( CODE_PAGE_UNSET == orig_code_page //指定があればスキップ
&& CODE_PAGE_UNSET == (dEnc.nCodePage = get_code_page(&src[0], src.size())) //まず主に日本語をチェック
&& S_OK != pImul->DetectInputCodepage(MLDETECTCP_NONE, 0, &src[0], &src_buf_len, &dEnc, &denc_count) //IMultiLanguage2で判定してみる
&& TRUE != fix_ImulL_WesternEurope(&dEnc.nCodePage))
return CODE_PAGE_UNSET;
return dEnc.nCodePage;
}
int chapter_file::get_unicode_data(wstring& wchar_data, vector<char>& src) {
wchar_data.resize(src.size(), 0);
if (code_page == CODE_PAGE_UTF16_LE) {
memcpy(&wchar_data[0], &src[0], src.size());
wchar_data.resize(src.size() / sizeof(wchar_t));
} else {
int start_index = 0;
if (CODE_PAGE_UTF8 == code_page && 0 == memcmp(&src[0], UTF8_BOM, sizeof(UTF8_BOM)))
start_index = sizeof(UTF8_BOM);
DWORD encMode = 0;
UINT src_size = src.size() - start_index;
UINT dst_output_len = wchar_data.size();
if (S_OK != pImul->ConvertStringToUnicode(&encMode, code_page, &src[start_index], &src_size, &wchar_data[0], &dst_output_len)) {
sts = AUO_CHAP_ERR_CONVERTION;
}
wchar_data.resize(dst_output_len);
}
return sts;
}
int chapter_file::get_unicode_data_from_file(wstring& wchar_data) {
using std::ios;
using std::ifstream;
//ファイルを一気に読み込み
vector<char> file_data;
ifstream inputFile(filepath, ios::in | ios::binary);
if (!inputFile.good()) {
sts = AUO_CHAP_ERR_FILE_OPEN;
} else {
file_data.resize((size_t)inputFile.seekg(0, std::ios::end).tellg() + 1, '\0');
inputFile.seekg(0, std::ios::beg).read(&file_data[0], static_cast<std::streamsize>(file_data.size()));
if (0 == file_data.size()) {
sts = AUO_CHAP_ERR_FILE_OPEN;
//文字コード判定
} else if (CODE_PAGE_UNSET == (code_page = check_code_page(file_data, code_page))) {
sts = AUO_CHAP_ERR_CP_DETECT;
} else {
//文字コード変換
sts = get_unicode_data(wchar_data, file_data);
}
}
return sts;
}
int chapter_file::check_chap_type(const wstring& data) {
if (0 == data.length())
sts = CHAP_TYPE_UNKNOWN;
auto pos = data.find(L"CHAPTER");
auto first_pos = pos;
if ( string::npos != pos
&& string::npos != (pos = first_pos = data.find(L"=", pos))
&& string::npos != (pos = data.find_first_of(L"\r\n", pos))
&& string::npos != (pos = data.find_first_not_of(L"\r\n", pos))
&& string::npos != data.substr(pos).find(data.substr(0, first_pos))) {
return CHAP_TYPE_NERO;
}
if ( string::npos != data.find(L"<TextStream")
&& string::npos != data.find(L"<TextSample"))
return CHAP_TYPE_APPLE;
return CHAP_TYPE_UNKNOWN;
}
int chapter_file::check_chap_type_from_file() {
//文字コード変換してファイル内容を取得
if (AUO_CHAP_ERR_NONE != (sts = get_unicode_data_from_file(wchar_filedata))) {
chapter_type = CHAP_TYPE_UNKNOWN;
} else {
chapter_type = check_chap_type(wchar_filedata);
}
return sts;
}
int chapter_file::read_chapter_nero() {
if (0 == wchar_filedata.length() || nullptr == pImul) {
sts = AUO_CHAP_ERR_NULL_PTR;
return sts;
}
//行単位に分解
const wchar_t delim = (string::npos != wchar_filedata.find(L"\n")) ? L'\n' : L'\r'; //適切な改行コードを見つける
auto pw_line = split(wchar_filedata, delim);
//読み取り
static const wchar_t * const CHAP_KEY = L"CHAPTER";
const wchar_t *pw_key[] = { CHAP_KEY, nullptr, nullptr }; // 時間行, 名前行, ダミー
wchar_t *pw_data[2];
const int total_lines = pw_line.size();
for (int i = 0; i < total_lines && !sts; i++) {
//末尾の改行空白を取り除く
pw_line[i] = pw_line[i].substr(0, pw_line[i].find_last_not_of(L"\r\n ") + 1);
if (string::npos == pw_line[i].find(pw_key[i&1], 0, wcslen(pw_key[i&1])))
return AUO_CHAP_ERR_INVALID_FMT;
pw_key[(i&1) + 1] = &pw_line[i][0];//CHAPTER KEY名を保存
pw_data[i&1] = wcschr(&pw_line[i][0], L'=');
*pw_data[i&1] = L'\0'; //CHAPTER KEY名を一つの文字列として扱えるように
pw_data[i&1]++; //データは'='の次から
if (i&1) {
//読み取り
std::unique_ptr<chapter> chap(new chapter());
if ( 4 != swscanf_s(pw_data[0], L"%d:%d:%d:%d", &chap->h, &chap->m, &chap->s, &chap->ms)
&& 4 != swscanf_s(pw_data[0], L"%d:%d:%d.%d", &chap->h, &chap->m, &chap->s, &chap->ms)
&& 4 != swscanf_s(pw_data[0], L"%d:%d.%d.%d", &chap->h, &chap->m, &chap->s, &chap->ms)
&& 4 != swscanf_s(pw_data[0], L"%d.%d.%d.%d", &chap->h, &chap->m, &chap->s, &chap->ms)) {
sts = AUO_CHAP_ERR_INVALID_FMT;
} else {
chap->name = pw_data[1];
chapters.push_back(std::move(chap));
}
}
}
return sts;
}
int chapter_file::read_chapter_apple() {
if (nullptr == filepath || nullptr == pImul) {
sts = AUO_CHAP_ERR_NULL_PTR;
return sts;
}
static const wchar_t * const ELEMENT_NAME = L"TextSample";
static const wchar_t * const ATTRIBUTE_NAME = L"sampleTime";
IXmlReader *pReader = nullptr;
IStream *pStream = nullptr;
CoInitialize(NULL);
if (S_OK != CreateXmlReader(IID_PPV_ARGS(&pReader), NULL))
sts = AUO_CHAP_ERR_INIT_XML_PARSER;
else if (S_OK != SHCreateStreamOnFile(filepath, STGM_READ, &pStream))
sts = AUO_CHAP_ERR_INIT_READ_STREAM;
else if (S_OK != pReader->SetInput(pStream))
sts = AUO_CHAP_ERR_FAIL_SET_STREAM;
else {
const wchar_t *pwLocalName = NULL, *pwValue = NULL;
XmlNodeType nodeType;
int time[4] = { 0 };
bool flag_next_line_is_time = true; //次は時間を取得するべき
while (S_OK == pReader->Read(&nodeType)) {
switch (nodeType) {
case XmlNodeType_Element:
if (S_OK != pReader->GetLocalName(&pwLocalName, NULL))
return AUO_CHAP_ERR_PARSE_XML;
if (wcscmp(ELEMENT_NAME, pwLocalName))
break;
if (S_OK != pReader->MoveToFirstAttribute())
break;
do {
const wchar_t *pwAttributeName = NULL;
const wchar_t *pwAttributeValue = NULL;
if (S_OK != pReader->GetLocalName(&pwAttributeName, NULL))
break;
if (_wcsicmp(ATTRIBUTE_NAME, pwAttributeName))
break;
if (S_OK != pReader->GetValue(&pwAttributeValue, NULL))
break;
//必要ならバッファ拡張(想定される最大限必要なバッファに設定)
if ( 4 != swscanf_s(pwAttributeValue, L"%d:%d:%d:%d\r\n", &time[0], &time[1], &time[2], &time[3])
&& 4 != swscanf_s(pwAttributeValue, L"%d:%d:%d.%d\r\n", &time[0], &time[1], &time[2], &time[3])
&& 4 != swscanf_s(pwAttributeValue, L"%d:%d.%d.%d\r\n", &time[0], &time[1], &time[2], &time[3])
&& 4 != swscanf_s(pwAttributeValue, L"%d.%d.%d.%d\r\n", &time[0], &time[1], &time[2], &time[3]))
return AUO_CHAP_ERR_PARSE_XML;
flag_next_line_is_time = FALSE;
} while (S_OK == pReader->MoveToNextAttribute());
break;
case XmlNodeType_Text:
if (S_OK != pReader->GetValue(&pwValue, NULL))
break;
if (pwLocalName == NULL || wcscmp(pwLocalName, ELEMENT_NAME))
break;
if (flag_next_line_is_time)
break;
//変換
{
std::unique_ptr<chapter> chap(new chapter());
chap->h = time[0];
chap->m = time[1];
chap->s = time[2];
chap->ms = time[3];
chap->name = pwValue;
chapters.push_back(std::move(chap));
flag_next_line_is_time = true;
}
break;
default:
break;
}
}
}
//リソース解放
if (pReader)
pReader->Release();
if (pStream)
pStream->Release();
CoUninitialize();
return sts;
}
int chapter_file::read_chapter() {
if (0 == wchar_filedata.length()) {
if (AUO_CHAP_ERR_NONE != (sts = check_chap_type_from_file())) {
return sts;
}
}
sts = (CHAP_TYPE_NERO == chapter_type) ? read_chapter_nero() : read_chapter_apple();
return sts;
}
int chapter_file::read_file() {
if (S_OK != CoCreateInstance(CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER, IID_IMultiLanguage2, (void**)&pImul) || nullptr == pImul) {
sts = AUO_CHAP_ERR_INIT_IMUL2;
} else {
sts = read_chapter();
}
return sts;
}
void chapter_file::add_dummy_chap_zero_pos() {
if (chapters.size()) {
if (0 != (chapters[0]->h | chapters[0]->m | chapters[0]->s | chapters[0]->ms)) {
std::unique_ptr<chapter> chap(new chapter);
chap->name = L"";
chapters.insert(chapters.begin(), std::move(chap));
}
}
}
void chapter_file::delay_chapter(int delay_ms) {
for (DWORD i = 0; i < chapters.size(); i++) {
DWORD chap_time_ms = chapters[i]->get_ms();
if (chap_time_ms) {
chapters[i]->set_ms(chap_time_ms + delay_ms);
}
}
}
| [
"rigaya34589@live.jp"
] | rigaya34589@live.jp |
e7f62ab7bfc773ffdcd662b9a23974f91a83f73e | 6336483e4cb8bff0f0cf2ecbb70a88c57d6f9c87 | /packages/directxtk_desktop_win10.2022.7.30.1/include/BufferHelpers.h | 9fc4a6e7c84c0630f148f0b51f4da2db191e3e3c | [] | no_license | hoisin/SDXEngine | 8deef9f456bf41ac0c420c5a1498176abc44cb94 | 7d5cb792657a19ef4055f159a1d8d645e950db93 | refs/heads/master | 2022-08-10T19:21:16.553728 | 2022-08-01T20:43:51 | 2022-08-01T20:43:51 | 139,254,558 | 0 | 0 | null | 2022-07-30T14:46:04 | 2018-06-30T14:09:33 | C++ | UTF-8 | C++ | false | false | 5,573 | h | //--------------------------------------------------------------------------------------
// File: BufferHelpers.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include <cassert>
#include <cstddef>
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#include "GraphicsMemory.h"
#else
#include <d3d11_1.h>
#endif
#include <wrl\client.h>
namespace DirectX
{
// Helpers for creating initialized Direct3D buffer resources.
HRESULT __cdecl CreateStaticBuffer(_In_ ID3D11Device* device,
_In_reads_bytes_(count* stride) const void* ptr,
size_t count,
size_t stride,
unsigned int bindFlags,
_COM_Outptr_ ID3D11Buffer** pBuffer) noexcept;
template<typename T>
HRESULT CreateStaticBuffer(_In_ ID3D11Device* device,
_In_reads_(count) T const* data,
size_t count,
unsigned int bindFlags,
_COM_Outptr_ ID3D11Buffer** pBuffer) noexcept
{
return CreateStaticBuffer(device, data, count, sizeof(T), bindFlags, pBuffer);
}
template<typename T>
HRESULT CreateStaticBuffer(_In_ ID3D11Device* device,
T const& data,
unsigned int bindFlags,
_COM_Outptr_ ID3D11Buffer** pBuffer) noexcept
{
return CreateStaticBuffer(device, data.data(), data.size(), sizeof(typename T::value_type), bindFlags, pBuffer);
}
// Helpers for creating texture from memory arrays.
HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device,
size_t width,
DXGI_FORMAT format,
const D3D11_SUBRESOURCE_DATA& initData,
_COM_Outptr_opt_ ID3D11Texture1D** texture,
_COM_Outptr_opt_ ID3D11ShaderResourceView** textureView,
unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept;
HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device,
size_t width, size_t height,
DXGI_FORMAT format,
const D3D11_SUBRESOURCE_DATA& initData,
_COM_Outptr_opt_ ID3D11Texture2D** texture,
_COM_Outptr_opt_ ID3D11ShaderResourceView** textureView,
unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept;
HRESULT __cdecl CreateTextureFromMemory(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDeviceX,
_In_ ID3D11DeviceContextX* d3dContextX,
#else
_In_ ID3D11Device* device,
_In_ ID3D11DeviceContext* d3dContext,
#endif
size_t width, size_t height,
DXGI_FORMAT format,
const D3D11_SUBRESOURCE_DATA& initData,
_COM_Outptr_opt_ ID3D11Texture2D** texture,
_COM_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
HRESULT __cdecl CreateTextureFromMemory(_In_ ID3D11Device* device,
size_t width, size_t height, size_t depth,
DXGI_FORMAT format,
const D3D11_SUBRESOURCE_DATA& initData,
_COM_Outptr_opt_ ID3D11Texture3D** texture,
_COM_Outptr_opt_ ID3D11ShaderResourceView** textureView,
unsigned int bindFlags = D3D11_BIND_SHADER_RESOURCE) noexcept;
// Strongly typed wrapper around a Direct3D constant buffer.
namespace Internal
{
// Base class, not to be used directly: clients should access this via the derived PrimitiveBatch<T>.
class ConstantBufferBase
{
protected:
void __cdecl CreateBuffer(_In_ ID3D11Device* device, size_t bytes, _Outptr_ ID3D11Buffer** pBuffer);
};
}
template<typename T>
class ConstantBuffer : public Internal::ConstantBufferBase
{
public:
// Constructor.
ConstantBuffer() = default;
explicit ConstantBuffer(_In_ ID3D11Device* device) noexcept(false)
{
CreateBuffer(device, sizeof(T), mConstantBuffer.GetAddressOf());
}
ConstantBuffer(ConstantBuffer&&) = default;
ConstantBuffer& operator= (ConstantBuffer&&) = default;
ConstantBuffer(ConstantBuffer const&) = delete;
ConstantBuffer& operator= (ConstantBuffer const&) = delete;
void Create(_In_ ID3D11Device* device)
{
CreateBuffer(device, sizeof(T), mConstantBuffer.ReleaseAndGetAddressOf());
}
// Writes new data into the constant buffer.
#if defined(_XBOX_ONE) && defined(_TITLE)
void __cdecl SetData(_In_ ID3D11DeviceContext* deviceContext, T const& value, void** grfxMemory)
{
assert(grfxMemory != nullptr);
void* ptr = GraphicsMemory::Get().Allocate(deviceContext, sizeof(T), 64);
assert(ptr != nullptr);
*(T*)ptr = value;
*grfxMemory = ptr;
}
#else
void __cdecl SetData(_In_ ID3D11DeviceContext* deviceContext, T const& value) noexcept
{
assert(mConstantBuffer);
D3D11_MAPPED_SUBRESOURCE mappedResource;
if (SUCCEEDED(deviceContext->Map(mConstantBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
{
*static_cast<T*>(mappedResource.pData) = value;
deviceContext->Unmap(mConstantBuffer.Get(), 0);
}
}
#endif // _XBOX_ONE && _TITLE
// Looks up the underlying D3D constant buffer.
ID3D11Buffer* GetBuffer() const noexcept { return mConstantBuffer.Get(); }
private:
Microsoft::WRL::ComPtr<ID3D11Buffer> mConstantBuffer;
};
}
| [
"mwctsang@gmail.com"
] | mwctsang@gmail.com |
c17eb857e2c1673dbbc81e01bafac6f308b411e6 | d0a665202bdb156a8d0c513b41fc3f181cdf23fa | /Software/ESP32/ESP32Modem/OLED.ino | 1dcb644205730a0d000962aadb57c83f39a4731d | [
"MIT"
] | permissive | LeifBloomquist/BeeModem | 2c7c1f38d081dbc5582f5302cf2c10093b261d18 | ed8e6979bc76fee3d0231efa0e21c94a8667601b | refs/heads/master | 2021-06-20T15:25:03.448594 | 2021-03-29T21:15:38 | 2021-03-29T21:15:38 | 201,660,996 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 866 | ino |
void OLED_Init()
{
/*
#ifdef TTGO
pinMode(PIN_OLED_RST, OUTPUT);
digitalWrite(PIN_OLED_RST, LOW); // low to reset OLED
delay(50);
digitalWrite(PIN_OLED_RST, HIGH); // must be high to turn on OLED
#endif
// Start I2C Communication
Wire.begin(PIN_OLED_SDA, PIN_OLED_SCL);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C, false, false))
{
C64.println(F("SSD1306 OLED allocation failed"));
Debug.println(F("DEBUG: SSD1306 OLED allocation failed"));
}
else
{
Debug.println(F("DEBUG: SSD1306 OLED Initialized OK"));
}
// Clear the buffer.
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
*/
}
void DisplayString(const char* message)
{
/* display.clearDisplay();
display.setCursor(0, 10);
display.println(message);
display.display();
*/
}
void DisplayBoth(const char* s)
{
C64.println(s);
DisplayString(s);
} | [
"github@leifbloomquist.net"
] | github@leifbloomquist.net |
854cb4741c6f07725fc06a4df1382f5796428def | fe6a130447abdfe7d3dc4169ae03bce50e508375 | /game_objects/house.cpp | cfca09ae1246ee62b3349afb7304fb5cd49b4389 | [] | no_license | couatl/Mort | dfeadc4f3ded1d8907dc4343f10301ebc93a0161 | 1652078ad39827228216f0c81d3e50587e35a257 | refs/heads/master | 2021-01-25T09:27:05.941822 | 2017-10-02T21:00:40 | 2017-10-02T21:00:40 | 93,841,170 | 4 | 4 | null | 2017-06-27T13:21:47 | 2017-06-09T09:13:53 | C++ | UTF-8 | C++ | false | false | 644 | cpp | #include "house.h"
#include <QPainter>
House::House(int _x, int _y, QGraphicsItem *parent) : QGraphicsItem(parent),
x(_x), y(_y)
{
image = QPixmap(":/rsc/images/house.png");
image = image.scaled(284, 240, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
this->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
}
QRectF House::boundingRect() const
{
return QRectF(x, y, 284, 240);
}
void House::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->drawPixmap(x, y, image);
setTransformOriginPoint(boundingRect().center());
Q_UNUSED(widget);
Q_UNUSED(option);
}
| [
"pryahin.v@gmail.com"
] | pryahin.v@gmail.com |
4307fcc1709e6d1c0e2625f6535805316a048f74 | c00e4bb7b0cfd537377a7f0fc295915a58d87189 | /Trees/2. Tree Traversal/2.1. Level_Order_Traversal_naive.cpp | a653b1892b68bfad7d59a786e39c9156cea841b9 | [] | no_license | palakyadav1807/DSA | 2ed9c1fdf7b00a9e6706e118244ef9adead066e5 | b1f24afe52820015e80987e09c725269d1cb6d57 | refs/heads/master | 2023-04-26T19:39:58.983795 | 2021-05-25T16:46:55 | 2021-05-25T16:46:55 | 346,221,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | /*
Breadth First Traversal using height of tree and function to print nodes at distance k
Time complexity :- O(n*h)
10
/ \
20 30
/ / \
40 5 60
*/
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* left;
Node* right;
Node(int d)
{
data=d;
left=NULL;
right=NULL;
}
};
//Function to find height of the tree
int height(Node* root)
{
if(root==NULL)
{
return 0;
}
return 1+max(height(root->left),height(root->right));
}
//Function to print nodes at distance k
void printNodesAtk(Node* root,int k)
{
if(root==NULL) return;
if(k==1)
{
cout<<(root->data)<<" ";
}
else
{
printNodesAtk(root->left,k-1);
printNodesAtk(root->right,k-1);
}
}
int main()
{
Node* root=new Node(10);
root->left=new Node(20);
root->left->left=new Node(40);
root->right=new Node(30);
root->right->left=new Node(5);
root->right->right=new Node(60);
int h=height(root);
for(int i=1;i<=h;i++)
{
printNodesAtk(root,i);
}
return 0;
}
| [
"palakyadav187@gmail.com"
] | palakyadav187@gmail.com |
548527664f22ef34e6f17a5a480ffeb3dc074607 | 7fd64b86c7e8f63d6238fe93ccf6e62a4b8ebc66 | /codeforces/404/A.cpp | 1c0199556ea970a0aa48908e0dc692814df77d97 | [] | no_license | Mohammad-Yasser/harwest | 775ba71303cc2849f71e82652263f31e79bd8e04 | d01834a9a41c828c8c548a115ecefd77ff2d6adc | refs/heads/master | 2023-02-02T23:37:54.186079 | 2013-09-19T19:28:00 | 2020-12-21T14:30:32 | 323,233,072 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
int n;
cin >> n;
string c[n + 1];
for (int i = 0; i < n; cin >> c[i], ++i)
;
char a = c[0][0], b = c[0][1];
if (a == b) {
cout << "NO";
return 0;
}
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
if (((i == j or i == n - j - 1) && c[i][j] != a)
or (!(i == j or i == n - j - 1) && c[i][j] != b)) {
cout << "NO";
return 0;
}
}
cout << "YES";
}
| [
"mohammadyasser3@gmail.com"
] | mohammadyasser3@gmail.com |
f6ce0032e17f84377d413efe728710d156fc317e | e641bd95bff4a447e25235c265a58df8e7e57c84 | /ui/base/clipboard/clipboard_ozone.cc | 774c8848ddfec836b847a78b059c6cc0e19b567c | [
"BSD-3-Clause"
] | permissive | zaourzag/chromium | e50cb6553b4f30e42f452e666885d511f53604da | 2370de33e232b282bd45faa084e5a8660cb396ed | refs/heads/master | 2023-01-02T08:48:14.707555 | 2020-11-13T13:47:30 | 2020-11-13T13:47:30 | 312,600,463 | 0 | 0 | BSD-3-Clause | 2022-12-23T17:01:30 | 2020-11-13T14:39:10 | null | UTF-8 | C++ | false | false | 23,509 | cc | // Copyright 2018 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 "ui/base/clipboard/clipboard_ozone.h"
#include <limits>
#include <utility>
#include "base/bind.h"
#include "base/containers/flat_map.h"
#include "base/containers/span.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/clipboard/clipboard_buffer.h"
#include "ui/base/clipboard/clipboard_constants.h"
#include "ui/base/clipboard/clipboard_metrics.h"
#include "ui/base/clipboard/clipboard_monitor.h"
#include "ui/base/clipboard/custom_data_helper.h"
#include "ui/base/data_transfer_policy/data_transfer_endpoint.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/ozone/buildflags.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/platform_clipboard.h"
#if defined(OS_CHROMEOS) && BUILDFLAG(OZONE_PLATFORM_X11)
#include "base/command_line.h"
#include "ui/base/clipboard/clipboard_non_backed.h"
#include "ui/base/ui_base_switches.h"
#endif
namespace ui {
namespace {
// The amount of time to wait for a request to complete before aborting it.
constexpr base::TimeDelta kRequestTimeout = base::TimeDelta::FromSeconds(10);
// Depending on the backend, the platform clipboard may or may not be
// available. Should it be absent, we provide a dummy one. It always calls
// back immediately with empty data, and denies ownership of any buffer.
class StubPlatformClipboard : public PlatformClipboard {
public:
StubPlatformClipboard() = default;
~StubPlatformClipboard() override = default;
// PlatformClipboard:
void OfferClipboardData(
ClipboardBuffer buffer,
const PlatformClipboard::DataMap& data_map,
PlatformClipboard::OfferDataClosure callback) override {
std::move(callback).Run();
}
void RequestClipboardData(
ClipboardBuffer buffer,
const std::string& mime_type,
PlatformClipboard::DataMap* data_map,
PlatformClipboard::RequestDataClosure callback) override {
std::move(callback).Run({});
}
void GetAvailableMimeTypes(
ClipboardBuffer buffer,
PlatformClipboard::GetMimeTypesClosure callback) override {
std::move(callback).Run({});
}
bool IsSelectionOwner(ClipboardBuffer buffer) override { return false; }
void SetSequenceNumberUpdateCb(
PlatformClipboard::SequenceNumberUpdateCb cb) override {}
bool IsSelectionBufferAvailable() const override { return false; }
};
} // namespace
// A helper class that uses a request pattern to asynchronously communicate
// with the ozone::PlatformClipboard and fetch clipboard data with the
// specified MIME types.
class ClipboardOzone::AsyncClipboardOzone {
public:
explicit AsyncClipboardOzone(PlatformClipboard* platform_clipboard)
: platform_clipboard_(platform_clipboard), weak_factory_(this) {
DCHECK(platform_clipboard_);
// Set a callback to listen to requests to increase the clipboard sequence
// number.
auto update_sequence_cb =
base::BindRepeating(&AsyncClipboardOzone::UpdateClipboardSequenceNumber,
weak_factory_.GetWeakPtr());
platform_clipboard_->SetSequenceNumberUpdateCb(
std::move(update_sequence_cb));
}
~AsyncClipboardOzone() = default;
bool IsSelectionBufferAvailable() const {
return platform_clipboard_->IsSelectionBufferAvailable();
}
base::span<uint8_t> ReadClipboardDataAndWait(ClipboardBuffer buffer,
const std::string& mime_type) {
// We can use a fastpath if we are the owner of the selection.
if (platform_clipboard_->IsSelectionOwner(buffer)) {
auto it = offered_data_[buffer].find(mime_type);
if (it == offered_data_[buffer].end())
return {};
return base::make_span(it->second->front(), it->second->size());
}
Request request(RequestType::kRead);
request.requested_mime_type = mime_type;
PerformRequestAndWaitForResult(buffer, &request);
offered_data_[buffer] = request.data_map;
auto it = offered_data_[buffer].find(mime_type);
if (it == offered_data_[buffer].end())
return {};
return base::make_span(it->second->front(), it->second->size());
}
std::vector<std::string> RequestMimeTypes(ClipboardBuffer buffer) {
// We can use a fastpath if we are the owner of the selection.
if (platform_clipboard_->IsSelectionOwner(buffer)) {
std::vector<std::string> mime_types;
for (const auto& item : offered_data_[buffer])
mime_types.push_back(item.first);
return mime_types;
}
Request request(RequestType::kGetMime);
PerformRequestAndWaitForResult(buffer, &request);
return request.mime_types;
}
void OfferData(ClipboardBuffer buffer) {
Request request(RequestType::kOffer);
request.data_map = data_to_offer_;
offered_data_[buffer] = std::move(data_to_offer_);
PerformRequestAndWaitForResult(buffer, &request);
UpdateClipboardSequenceNumber(buffer);
}
void Clear(ClipboardBuffer buffer) {
data_to_offer_.clear();
OfferData(buffer);
ClipboardMonitor::GetInstance()->NotifyClipboardDataChanged();
}
void InsertData(std::vector<uint8_t> data,
const std::set<std::string>& mime_types) {
auto wrapped_data = scoped_refptr<base::RefCountedBytes>(
base::RefCountedBytes::TakeVector(&data));
for (const auto& mime_type : mime_types) {
DCHECK_EQ(data_to_offer_.count(mime_type), 0U);
data_to_offer_[mime_type] = wrapped_data;
}
ClipboardMonitor::GetInstance()->NotifyClipboardDataChanged();
}
uint64_t GetSequenceNumber(ClipboardBuffer buffer) {
return clipboard_sequence_number_[buffer];
}
private:
enum class RequestType {
kRead = 0,
kOffer = 1,
kGetMime = 2,
};
// Holds request data to process inquiries from the ClipboardOzone.
struct Request {
explicit Request(RequestType request_type) : type(request_type) {}
~Request() = default;
// Describes the type of the request.
RequestType type;
// A closure that is used to signal the request is processed.
base::OnceClosure finish_closure;
// Used for kRead and kOffer requests. It contains either data offered by
// Chromium to a system clipboard or a read data offered by the system
// clipboard.
PlatformClipboard::DataMap data_map;
// Identifies which mime type the client is interested to read from the
// system clipboard during kRead requests.
std::string requested_mime_type;
// A vector of mime types returned as a result to a kGetMime request to get
// available mime types.
std::vector<std::string> mime_types;
};
void PerformRequestAndWaitForResult(ClipboardBuffer buffer,
Request* request) {
DCHECK(request);
DCHECK(!abort_timer_.IsRunning());
DCHECK(!pending_request_);
pending_request_ = request;
switch (pending_request_->type) {
case (RequestType::kRead):
DispatchReadRequest(buffer, request);
break;
case (RequestType::kOffer):
DispatchOfferRequest(buffer, request);
break;
case (RequestType::kGetMime):
DispatchGetMimeRequest(buffer, request);
break;
}
if (!pending_request_)
return;
// TODO(https://crbug.com/913422): the implementation is known to be
// dangerous, and may cause blocks in ui thread. But base::Clipboard was
// designed to have synchronous APIs rather than asynchronous ones that at
// least two system clipboards on X11 and Wayland provide.
base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
request->finish_closure = run_loop.QuitClosure();
// Set a timeout timer after which the request will be aborted.
abort_timer_.Start(FROM_HERE, kRequestTimeout, this,
&AsyncClipboardOzone::AbortStalledRequest);
run_loop.Run();
}
void AbortStalledRequest() {
if (pending_request_ && pending_request_->finish_closure)
std::move(pending_request_->finish_closure).Run();
}
void DispatchReadRequest(ClipboardBuffer buffer, Request* request) {
auto callback = base::BindOnce(&AsyncClipboardOzone::OnTextRead,
weak_factory_.GetWeakPtr());
platform_clipboard_->RequestClipboardData(
buffer, request->requested_mime_type, &request->data_map,
std::move(callback));
}
void DispatchOfferRequest(ClipboardBuffer buffer, Request* request) {
auto callback = base::BindOnce(&AsyncClipboardOzone::OnOfferDone,
weak_factory_.GetWeakPtr());
platform_clipboard_->OfferClipboardData(buffer, request->data_map,
std::move(callback));
}
void DispatchGetMimeRequest(ClipboardBuffer buffer, Request* request) {
auto callback = base::BindOnce(&AsyncClipboardOzone::OnGotMimeTypes,
weak_factory_.GetWeakPtr());
platform_clipboard_->GetAvailableMimeTypes(buffer, std::move(callback));
}
void OnTextRead(const base::Optional<PlatformClipboard::Data>& data) {
// |data| is already set in request's data_map, so just finish request
// processing.
CompleteRequest();
}
void OnOfferDone() { CompleteRequest(); }
void OnGotMimeTypes(const std::vector<std::string>& mime_types) {
pending_request_->mime_types = std::move(mime_types);
CompleteRequest();
}
void CompleteRequest() {
if (!pending_request_)
return;
abort_timer_.Stop();
if (pending_request_->finish_closure)
std::move(pending_request_->finish_closure).Run();
pending_request_ = nullptr;
}
void UpdateClipboardSequenceNumber(ClipboardBuffer buffer) {
++clipboard_sequence_number_[buffer];
}
// Clipboard data accumulated for writing.
PlatformClipboard::DataMap data_to_offer_;
// Clipboard data that had been offered most recently. Used as a cache to
// read data if we still own it.
base::flat_map<ClipboardBuffer, PlatformClipboard::DataMap> offered_data_;
// A current pending request being processed.
Request* pending_request_ = nullptr;
// Aborts |pending_request| after Request::timeout.
base::RepeatingTimer abort_timer_;
// Provides communication to a system clipboard under ozone level.
PlatformClipboard* const platform_clipboard_ = nullptr;
base::flat_map<ClipboardBuffer, uint64_t> clipboard_sequence_number_;
base::WeakPtrFactory<AsyncClipboardOzone> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(AsyncClipboardOzone);
};
// Uses the factory in the clipboard_linux otherwise.
#if defined(OS_CHROMEOS) || !defined(OS_LINUX)
// Clipboard factory method.
Clipboard* Clipboard::Create() {
// linux-chromeos uses non-backed clipboard by default, but supports ozone x11
// with flag --use-system-clipbboard.
#if defined(OS_CHROMEOS) && BUILDFLAG(OZONE_PLATFORM_X11)
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kUseSystemClipboard)) {
return new ClipboardNonBacked;
}
#endif
return new ClipboardOzone;
}
#endif
// ClipboardOzone implementation.
ClipboardOzone::ClipboardOzone() {
auto* platform_clipboard =
OzonePlatform::GetInstance()->GetPlatformClipboard();
if (platform_clipboard) {
async_clipboard_ozone_ =
std::make_unique<ClipboardOzone::AsyncClipboardOzone>(
platform_clipboard);
} else {
static base::NoDestructor<StubPlatformClipboard> stub_platform_clipboard;
async_clipboard_ozone_ =
std::make_unique<ClipboardOzone::AsyncClipboardOzone>(
stub_platform_clipboard.get());
}
}
ClipboardOzone::~ClipboardOzone() = default;
void ClipboardOzone::OnPreShutdown() {}
uint64_t ClipboardOzone::GetSequenceNumber(ClipboardBuffer buffer) const {
return async_clipboard_ozone_->GetSequenceNumber(buffer);
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
bool ClipboardOzone::IsFormatAvailable(
const ClipboardFormatType& format,
ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst) const {
DCHECK(CalledOnValidThread());
auto available_types = async_clipboard_ozone_->RequestMimeTypes(buffer);
return base::Contains(available_types, format.GetName());
}
void ClipboardOzone::Clear(ClipboardBuffer buffer) {
async_clipboard_ozone_->Clear(buffer);
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadAvailableTypes(
ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst,
std::vector<base::string16>* types) const {
DCHECK(CalledOnValidThread());
DCHECK(types);
types->clear();
auto available_types = async_clipboard_ozone_->RequestMimeTypes(buffer);
for (auto& mime_type : available_types) {
// Special handling for chromium/x-web-custom-data.
// We must read the data and deserialize it to find the list
// of mime types to report.
if (mime_type == ClipboardFormatType::GetWebCustomDataType().GetName()) {
auto data = async_clipboard_ozone_->ReadClipboardDataAndWait(
buffer, ClipboardFormatType::GetWebCustomDataType().GetName());
ReadCustomDataTypes(data.data(), data.size(), types);
} else {
types->push_back(base::UTF8ToUTF16(mime_type));
}
}
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
std::vector<base::string16>
ClipboardOzone::ReadAvailablePlatformSpecificFormatNames(
ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst) const {
DCHECK(CalledOnValidThread());
std::vector<std::string> mime_types =
async_clipboard_ozone_->RequestMimeTypes(buffer);
std::vector<base::string16> types;
types.reserve(mime_types.size());
for (auto& mime_type : mime_types)
types.push_back(base::UTF8ToUTF16(mime_type));
return types;
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadText(ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst,
base::string16* result) const {
DCHECK(CalledOnValidThread());
RecordRead(ClipboardFormatMetric::kText);
auto clipboard_data =
async_clipboard_ozone_->ReadClipboardDataAndWait(buffer, kMimeTypeText);
*result = base::UTF8ToUTF16(base::StringPiece(
reinterpret_cast<char*>(clipboard_data.data()), clipboard_data.size()));
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadAsciiText(ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst,
std::string* result) const {
DCHECK(CalledOnValidThread());
RecordRead(ClipboardFormatMetric::kText);
auto clipboard_data =
async_clipboard_ozone_->ReadClipboardDataAndWait(buffer, kMimeTypeText);
result->assign(clipboard_data.begin(), clipboard_data.end());
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadHTML(ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst,
base::string16* markup,
std::string* src_url,
uint32_t* fragment_start,
uint32_t* fragment_end) const {
DCHECK(CalledOnValidThread());
RecordRead(ClipboardFormatMetric::kHtml);
markup->clear();
if (src_url)
src_url->clear();
*fragment_start = 0;
*fragment_end = 0;
auto clipboard_data =
async_clipboard_ozone_->ReadClipboardDataAndWait(buffer, kMimeTypeHTML);
*markup = base::UTF8ToUTF16(base::StringPiece(
reinterpret_cast<char*>(clipboard_data.data()), clipboard_data.size()));
DCHECK_LE(markup->length(), std::numeric_limits<uint32_t>::max());
*fragment_end = static_cast<uint32_t>(markup->length());
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadSvg(ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst,
base::string16* result) const {
DCHECK(CalledOnValidThread());
RecordRead(ClipboardFormatMetric::kSvg);
auto clipboard_data =
async_clipboard_ozone_->ReadClipboardDataAndWait(buffer, kMimeTypeSvg);
*result = base::UTF8ToUTF16(base::StringPiece(
reinterpret_cast<char*>(clipboard_data.data()), clipboard_data.size()));
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadRTF(ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst,
std::string* result) const {
DCHECK(CalledOnValidThread());
RecordRead(ClipboardFormatMetric::kRtf);
auto clipboard_data =
async_clipboard_ozone_->ReadClipboardDataAndWait(buffer, kMimeTypeRTF);
result->assign(clipboard_data.begin(), clipboard_data.end());
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadImage(ClipboardBuffer buffer,
const DataTransferEndpoint* data_dst,
ReadImageCallback callback) const {
RecordRead(ClipboardFormatMetric::kImage);
std::move(callback).Run(ReadImageInternal(buffer));
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadCustomData(ClipboardBuffer buffer,
const base::string16& type,
const DataTransferEndpoint* data_dst,
base::string16* result) const {
DCHECK(CalledOnValidThread());
RecordRead(ClipboardFormatMetric::kCustomData);
auto custom_data = async_clipboard_ozone_->ReadClipboardDataAndWait(
buffer, kMimeTypeWebCustomData);
ReadCustomDataForType(custom_data.data(), custom_data.size(), type, result);
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadBookmark(const DataTransferEndpoint* data_dst,
base::string16* title,
std::string* url) const {
DCHECK(CalledOnValidThread());
// TODO(msisov): This was left NOTIMPLEMENTED() in all the Linux platforms.
NOTIMPLEMENTED();
}
// TODO(crbug.com/1103194): |data_dst| should be supported.
void ClipboardOzone::ReadData(const ClipboardFormatType& format,
const DataTransferEndpoint* data_dst,
std::string* result) const {
DCHECK(CalledOnValidThread());
RecordRead(ClipboardFormatMetric::kData);
auto clipboard_data = async_clipboard_ozone_->ReadClipboardDataAndWait(
ClipboardBuffer::kCopyPaste, format.GetName());
result->assign(clipboard_data.begin(), clipboard_data.end());
}
bool ClipboardOzone::IsSelectionBufferAvailable() const {
return async_clipboard_ozone_->IsSelectionBufferAvailable();
}
// TODO(crbug.com/1103194): |data_src| should be supported
void ClipboardOzone::WritePortableRepresentations(
ClipboardBuffer buffer,
const ObjectMap& objects,
std::unique_ptr<DataTransferEndpoint> data_src) {
DCHECK(CalledOnValidThread());
for (const auto& object : objects)
DispatchPortableRepresentation(object.first, object.second);
async_clipboard_ozone_->OfferData(buffer);
// Just like Non-Backed/X11 implementation does, copy text data from the
// copy/paste selection to the primary selection.
if (buffer == ClipboardBuffer::kCopyPaste) {
auto text_iter = objects.find(PortableFormat::kText);
if (text_iter != objects.end()) {
const ObjectMapParams& params_vector = text_iter->second;
if (!params_vector.empty()) {
const ObjectMapParam& char_vector = params_vector[0];
if (!char_vector.empty())
WriteText(&char_vector.front(), char_vector.size());
}
async_clipboard_ozone_->OfferData(ClipboardBuffer::kSelection);
}
}
}
// TODO(crbug.com/1103194): |data_src| should be supported
void ClipboardOzone::WritePlatformRepresentations(
ClipboardBuffer buffer,
std::vector<Clipboard::PlatformRepresentation> platform_representations,
std::unique_ptr<DataTransferEndpoint> data_src) {
DCHECK(CalledOnValidThread());
DispatchPlatformRepresentations(std::move(platform_representations));
async_clipboard_ozone_->OfferData(buffer);
}
void ClipboardOzone::WriteText(const char* text_data, size_t text_len) {
std::vector<uint8_t> data(text_data, text_data + text_len);
async_clipboard_ozone_->InsertData(
std::move(data), {kMimeTypeText, kMimeTypeLinuxText, kMimeTypeLinuxString,
kMimeTypeTextUtf8, kMimeTypeLinuxUtf8String});
}
void ClipboardOzone::WriteHTML(const char* markup_data,
size_t markup_len,
const char* url_data,
size_t url_len) {
std::vector<uint8_t> data(markup_data, markup_data + markup_len);
async_clipboard_ozone_->InsertData(std::move(data), {kMimeTypeHTML});
}
void ClipboardOzone::WriteSvg(const char* markup_data, size_t markup_len) {
std::vector<uint8_t> data(markup_data, markup_data + markup_len);
async_clipboard_ozone_->InsertData(std::move(data), {kMimeTypeSvg});
}
void ClipboardOzone::WriteRTF(const char* rtf_data, size_t data_len) {
std::vector<uint8_t> data(rtf_data, rtf_data + data_len);
async_clipboard_ozone_->InsertData(std::move(data), {kMimeTypeRTF});
}
void ClipboardOzone::WriteBookmark(const char* title_data,
size_t title_len,
const char* url_data,
size_t url_len) {
// Writes a Mozilla url (UTF16: URL, newline, title)
base::string16 bookmark =
base::UTF8ToUTF16(base::StringPiece(url_data, url_len)) +
base::ASCIIToUTF16("\n") +
base::UTF8ToUTF16(base::StringPiece(title_data, title_len));
std::vector<uint8_t> data(
reinterpret_cast<const uint8_t*>(bookmark.data()),
reinterpret_cast<const uint8_t*>(bookmark.data() + bookmark.size()));
async_clipboard_ozone_->InsertData(std::move(data), {kMimeTypeMozillaURL});
}
void ClipboardOzone::WriteWebSmartPaste() {
async_clipboard_ozone_->InsertData(std::vector<uint8_t>(),
{kMimeTypeWebkitSmartPaste});
}
void ClipboardOzone::WriteBitmap(const SkBitmap& bitmap) {
std::vector<unsigned char> output;
if (gfx::PNGCodec::FastEncodeBGRASkBitmap(bitmap, false, &output))
async_clipboard_ozone_->InsertData(std::move(output), {kMimeTypePNG});
}
void ClipboardOzone::WriteData(const ClipboardFormatType& format,
const char* data_data,
size_t data_len) {
std::vector<uint8_t> data(data_data, data_data + data_len);
async_clipboard_ozone_->InsertData(std::move(data), {format.GetName()});
}
SkBitmap ClipboardOzone::ReadImageInternal(ClipboardBuffer buffer) const {
DCHECK(CalledOnValidThread());
auto clipboard_data =
async_clipboard_ozone_->ReadClipboardDataAndWait(buffer, kMimeTypePNG);
SkBitmap bitmap;
if (!gfx::PNGCodec::Decode(clipboard_data.data(), clipboard_data.size(),
&bitmap))
return {};
return SkBitmap(bitmap);
}
} // namespace ui
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
deb19bd407ea2ebf60a5a958b6ceea83d0b041f1 | 2dc10608952230c5ab29bd226cc9ead57c5b8705 | /red-ball-game/src/main/c++/red_ball/game/Actor.cpp | ac1c041de150271699bd26c618ecf9f096c81837 | [] | no_license | mikosz/red-ball | a6fadf915dab59ede658a0cacfcff1f00b7dca87 | e5ac6a993a153242f00473089176b1806b97668c | refs/heads/master | 2020-05-04T22:27:56.529294 | 2013-02-13T23:01:48 | 2013-02-13T23:01:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 766 | cpp | #include "Actor.hpp"
#include "red_ball/graphics/ObjFileLoader.hpp"
#include "red_ball/graphics/BasicModel.hpp"
using namespace red_ball;
using namespace red_ball::game;
Actor::Actor(graphics::Direct3DDisplay* display) :
renderingQueue_(display->renderingQueue())
{
graphics::ObjFileLoader loader("red-ball-graphics/src/main/resources/cube.objfile");
model_.reset(new graphics::BasicModel(&display->device(), loader));
modelId_ = renderingQueue_->add(model_);
}
Actor::~Actor() {
renderingQueue_->remove(modelId_);
}
void Actor::update(utils::Timer::Seconds time) {
actionTimeline_.update(time);
}
void Actor::scheduleAction(utils::Timer::Seconds delay, core::actions::ActionPtr action) {
actionTimeline_.schedule(delay, action);
}
| [
"mikoszrrr@gmail.com"
] | mikoszrrr@gmail.com |
fd1a465f63378aa37441cc9232ab1d026f561046 | 907843f7d8c0871eec2850b95a5d2077c14c182a | /utilities/FieldConvert/ProcessModules/ProcessPrintFldNorms.cpp | b623203b684fa8b990db7b6abfe4900fee51ce6b | [
"MIT"
] | permissive | li12242/nektar | 4792c4f8f88992875ecefb590e804e850887ae19 | a31e519cdde5d58d2fa23e0eaedd54ce3ed9fb72 | refs/heads/master | 2020-05-29T12:21:41.203547 | 2015-07-29T14:15:38 | 2015-07-29T14:15:38 | 65,020,427 | 1 | 0 | null | 2016-08-05T13:26:59 | 2016-08-05T13:26:58 | null | UTF-8 | C++ | false | false | 3,121 | cpp | ////////////////////////////////////////////////////////////////////////////////
//
// File: ProcessPrintFldNorms.cpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Prints the L2 and LInf norms of the field variables.
//
////////////////////////////////////////////////////////////////////////////////
#include <string>
#include <iostream>
using namespace std;
#include "ProcessPrintFldNorms.h"
#include <LibUtilities/BasicUtils/SharedArray.hpp>
#include <LibUtilities/BasicUtils/ParseUtils.hpp>
namespace Nektar
{
namespace Utilities
{
ModuleKey ProcessPrintFldNorms::className =
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eProcessModule, "printfldnorms"),
ProcessPrintFldNorms::create,
"Print L2 and LInf norms to stdout.");
ProcessPrintFldNorms::ProcessPrintFldNorms(FieldSharedPtr f)
: ProcessModule(f)
{
}
ProcessPrintFldNorms::~ProcessPrintFldNorms()
{
}
void ProcessPrintFldNorms::Process(po::variables_map &vm)
{
if (m_f->m_verbose)
{
cout << "ProcessPrintFldNorms: Printing norms" << endl;
}
// Evaluate norms and print
for(int j = 0; j < m_f->m_exp.size(); ++j)
{
m_f->m_exp[j]->BwdTrans(m_f->m_exp[j]->GetCoeffs(),
m_f->m_exp[j]->UpdatePhys());
NekDouble L2 = m_f->m_exp[j]->L2 (m_f->m_exp[j]->GetPhys());
NekDouble LInf = m_f->m_exp[j]->Linf(m_f->m_exp[j]->GetPhys());
cout << "L 2 error (variable " << m_f->m_session->GetVariable(j)
<< ") : " << L2 << endl;
cout << "L inf error (variable " << m_f->m_session->GetVariable(j)
<< ") : " << LInf << endl;
}
}
}
}
| [
"c.cantwell@imperial.ac.uk"
] | c.cantwell@imperial.ac.uk |
6a66eebc309653f7c80aaf30cab436d9a2246634 | c268bcfc8fb7e5663dba38df63a8cccc42658af4 | /src/mnb_pred.cpp | ef275025bb32198bea028569bee45d6405eb6c99 | [] | no_license | hao-peng/AppRiskPred | 55e8d9b92d06b750a15511b3176000f802e1ad58 | 908dd93f6f980cd1060f8fa50bf6e8f060420285 | refs/heads/master | 2020-06-02T07:41:29.367072 | 2017-09-21T21:24:54 | 2017-09-21T21:24:54 | 17,194,280 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,149 | cpp | /**********
Prediction for MNB model
Author: Hao Peng (penghATpurdue.edu)
Last updated time: Sep 17, 2015
**********/
#ifdef USE_OMP
#include <omp.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include "asa121.h"
#define OUT_LOOP 8000
#define EPS 1e-10
#define EQUAL(a,b) ((a-b)<EPS && a-b>-EPS)
#define UPDATE_ALPHA 0
#define FIX_ALPHA 1
//#define DEBUG
#define PRIOR
//#define NEW_PRIOR
#define MAX_ESTIMATE 0
#define MEAN_ESTIMATE 1
#define SUM_ESTIMATE 2
int K = 0;
int M = 0;
int L = 0;
int *N = NULL;
int ***R = NULL;
double **mytheta = NULL;
double **r = NULL;
double log_likelihood = 0;
int method = MAX_ESTIMATE;
void load(const char *input) {
char filename[100];
FILE *fp;
strcpy(filename, input);
strcat(filename, "/r");
fp = fopen(filename, "r");
if (fp == NULL) {
printf("cannot open file\n");
exit(-1);
}
fscanf(fp, "%d %d\n", &M, &K);
r = (double **) malloc(sizeof(double*)*M);
N = (int *) malloc(sizeof(int)*M);
for (int m = 0; m < M; m++) {
r[m] = (double *) malloc(sizeof(double)*K);
for (int k = 0; k < K; k++) {
fscanf(fp, "%lf", &r[m][k]);
}
}
fclose(fp);
strcpy(filename, input);
strcat(filename, "/theta");
fp = fopen(filename, "r");
if (fp == NULL) {
printf("cannot open file\n");
exit(-1);
}
fscanf(fp, "%d %d\n", &K, &L);
mytheta = (double **) malloc(sizeof(double *)*K);
for (int k = 0; k < K; k++) {
mytheta[k] = (double *) malloc(sizeof(double)*L);
for (int l = 0; l < L; l++) {
fscanf(fp, "%lf", &mytheta[k][l]);
}
}
fclose(fp);
}
void estimate(char *data, char *output) {
FILE *fp, *ofp;
fp = fopen(data, "r");
if (fp == NULL) {
printf("cannot open file\n");
exit(-1);
}
ofp = fopen(output, "w");
if (ofp == NULL) {
printf("cannot open file\n");
exit(-1);
}
int NN;
fscanf(fp, "%d %d", &NN, &L);
int *newR = (int *) malloc(sizeof(int)*L);
double *p = (double *) malloc(sizeof(double)*M);
double maxP = 0;
for (int i = 0; i < NN; i++){
for (int j = 0; j < L; j++) {
fscanf(fp, "%d", &newR[j]);
}
#pragma omp parallel shared(M,N,K,L,p,newR,r)
{
#pragma omp for schedule(dynamic,3)
for (int m = 0; m < M; m++) {
p[m] = 0;
for (int k = 0; k < K; k++) {
double q = r[m][k];
for (int l = 0; l < L; l++) {
#ifdef NEW_PRIOR
if (l == 56) continue;
#endif
if (newR[l]) {
q *= mytheta[k][l];
} else {
q *= (1 - mytheta[k][l]);
}
}
p[m] += q;
}
}
}
maxP = 0;
if (method == 0) {
for (int m = 0; m < M; m++) {
if (maxP < p[m]) {
maxP = p[m];
}
}
} else if (method == 1) {
for (int m = 0; m < M; m++ ){
maxP += p[m];
}
}
fprintf(ofp, "%e\n", maxP);
}
free(p);
free(newR);
fclose(fp);
}
int main(int argc, char **argv) {
if (argc != 4 && argc != 5) {
printf("Usage: %s input data output [method]\nmethod 0: max\nmode 1: sum", argv[0]);
printf("method: different evaluation stretages for multiple groups\n");
return 0;
}
if (argc == 5) {
method = atoi(argv[4]);
}
printf("load\n");
load(argv[1]);
estimate(argv[2], argv[3]);
return 0;
}
| [
"penghao888@gmail.com"
] | penghao888@gmail.com |
bf4d869afdda274e8757d4266c0f6088ae0ada59 | 678b3f5be6cab189f91279a44aa10a9265655792 | /PA5/PA5/Job.h | ad4ecc9b296c1119da902188dd95cee6ec936896 | [] | no_license | tcripe4/CptS_223 | 0a3938f5ee3135429355fff328cfd48a522a3a97 | 1539109574779509477310853a60b7fec9b1b2c0 | refs/heads/main | 2023-01-21T11:34:41.452375 | 2020-11-25T01:24:21 | 2020-11-25T01:24:21 | 315,794,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 362 | h | #pragma once
using namespace std;
#include <string>
#include <iostream>
class Job
{
public:
Job(int Jobid = 0, string jobdesctiption = "", int procs = 0, int ticks = 0);
int get_jobID();
string get_description();
int get_procs();
int get_ticks();
private:
int JobID;
string JobDescription;
int n_procs;
int n_ticks;
}; | [
"noreply@github.com"
] | noreply@github.com |
1f2c1cf7661ead0ca5155bf781cebd004047de8c | 9226f6db52701722c9bf0d1a3be4f2d17e62440b | /6 semestr/OSiS/Lr5/main.cpp | a6ea2090fd1df05483fe504c35dad681d24be83f | [] | no_license | AshRaven521/BSUIR | d02b5378e27c7bf5763cbe8c30b3e32f5e4e1836 | 9553b86bedaa909aff14f8c8a4e8c59556b05fe9 | refs/heads/master | 2023-07-23T07:37:27.335630 | 2023-07-09T20:51:31 | 2023-07-09T20:51:31 | 243,353,350 | 2 | 3 | null | 2023-08-15T23:59:58 | 2020-02-26T19:58:09 | C# | UTF-8 | C++ | false | false | 660 | cpp | #include <iostream>
#include <unistd.h>
#include <csignal>
#include <sys/wait.h>
int counter = 0;
void signalHandler(int signum)
{
auto c_pid = fork();
if (c_pid)
{
//wait(NULL);
std::cout << "Interrupt signal (" << signum << ") received" << std::endl;
std::cout << "Terminated, counter: " + std::to_string(++counter) + " "
<< "Exit" << std::endl;
exit(EXIT_SUCCESS);
}
}
int main()
{
while (true)
{
signal(SIGTERM, signalHandler);
counter++;
std::cout << "Running, counter: " + std::to_string(counter) << std::endl;
sleep(1);
}
return 0;
}
| [
"ivan.kondrashov.92@mail.ru"
] | ivan.kondrashov.92@mail.ru |
5f3cbc3eb53ac06a310f2c9a1381c084d5fa192e | 4193f7891e93294744bb6764ef6292aad9995ede | /资源管理器定位插件/FileNavigator/stdafx.cpp | 20a5b2a32ed83a0bf6c51872d5461775d42e5e8f | [] | no_license | zoand/myproject | 20321f1c0fe7ed4dcf3762bd546ae8dfbdee1e34 | 9ff3ce264652735a89663eb50c79d7cad3738ba0 | refs/heads/master | 2021-04-27T12:00:15.246429 | 2016-12-26T09:46:41 | 2016-12-26T09:46:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 273 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// FileNavigator.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"821038475@qq.com"
] | 821038475@qq.com |
9dfc3dea51863c654f0040b1d506eec3a9fd2087 | 81b93a8bc16023e31171ce68da0751b3a428696f | /src/third_party/old_higo_adcu/examples/dac_test.cpp | 896c20b79a4d7bfca73f0e6ad587e634b027d0f3 | [] | no_license | github188/agv | 3373b9b86203b0b2b98019abfc1058112eb394e2 | 3577ea7f0b561eb791241327a4c05e325d76808c | refs/heads/master | 2022-04-03T20:29:43.938463 | 2019-12-19T10:22:05 | 2019-12-19T10:22:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,843 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <string.h>
#include <pthread.h>
#include <string>
#include <semaphore.h>
#include <errno.h>
#include "adcuSDK.h"
using namespace std;
pthread_t ReadThread;
void *readLoop(void *pdata)
{
int deviceid = *(int *)pdata;
int packageCounter=0;
while(1)
{
uint8_t buffer[1024];
int length=0;
length = adcuDevRead(deviceid,buffer);
if(length > 0)
{
packageCounter++;
printf("RX %9d:",packageCounter);
for(int i=0;i<length;i++)
{
printf("%02X ",buffer[i]);
}
printf("\n");
}
}
}
int main(int argc,char **argv)
{
int devid;
uint8_t data[100];
int len = 0;
uint32_t delayTime = 0x0FFFFF;
adcuDeviceType deviceType = adcuDAC;
int channel;
adcuSDKInit();
if(argc !=3)
{
printf("please input correct parameters<channelNumber,voltage(mV)>\n");
return 0;
}
channel = atoi(argv[1]);
if(channel <=0 || channel >= ADCU_CHANNEL_MAX)
{
printf("please input correct channel number<%d ~ %d>\n",ADCU_CHANNEL_1,ADCU_CHANNEL_MAX-1);
return 0;
}
adcuDacData dacData;
dacData.voltage_mv = atoi(argv[2]);
if(dacData.voltage_mv < 0 || dacData.voltage_mv>5000)
{
printf("please input correct dac output voltage(mV)<0 ~ 5000>\n");
return 0;
}
len = sizeof(adcuDacData);
memcpy(data,(uint8_t *)&dacData,len);
delayTime = 0x0FFFFF;
devid = adcuDevOpen(deviceType,(adcuDeviceChannel)channel);
pthread_create(&ReadThread, NULL, readLoop, &devid);
int status=0;
while(1)
{
if(adcuDevStatus(devid) == ADCU_DEV_STATUS_ABNORMAL)
{
break;
}
if(adcuDevWrite(devid,data,len) <= 0)
{
printf("main write error\n");
goto __end;
}
sleep(delayTime);
}
__end:
printf("dinit all \n");
adcuDevClose(devid);
adcuSDKDeinit();
}
| [
"sheng.tao@superg.ai"
] | sheng.tao@superg.ai |
fa556132577f09e41f121e607ab3fe98f879da75 | 7954d9642d34cb2cc666cf30c5bd73cd488f4efb | /src/Storages/System/StorageSystemQueryCache.cpp | 0e589b1b1831fe647d6e425c18ba6ce6acee2eb6 | [
"Apache-2.0"
] | permissive | ekonkov/ClickHouse | 771c61bda9e7e644ddd991e8a76c0bc182205a71 | 6434fd8a47a4631a8d7b85229b71a219a74b2b36 | refs/heads/master | 2023-05-01T15:35:09.433480 | 2023-04-26T11:06:10 | 2023-04-26T11:06:10 | 67,151,830 | 1 | 0 | null | 2016-09-01T17:23:33 | 2016-09-01T17:23:32 | null | UTF-8 | C++ | false | false | 1,940 | cpp | #include "StorageSystemQueryCache.h"
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypeDateTime.h>
#include <DataTypes/DataTypesNumber.h>
#include <Interpreters/Cache/QueryCache.h>
#include <Interpreters/Context.h>
namespace DB
{
NamesAndTypesList StorageSystemQueryCache::getNamesAndTypes()
{
return {
{"query", std::make_shared<DataTypeString>()},
{"result_size", std::make_shared<DataTypeUInt64>()},
{"stale", std::make_shared<DataTypeUInt8>()},
{"shared", std::make_shared<DataTypeUInt8>()},
{"compressed", std::make_shared<DataTypeUInt8>()},
{"expires_at", std::make_shared<DataTypeDateTime>()},
{"key_hash", std::make_shared<DataTypeUInt64>()}
};
}
StorageSystemQueryCache::StorageSystemQueryCache(const StorageID & table_id_)
: IStorageSystemOneBlock(table_id_)
{
}
void StorageSystemQueryCache::fillData(MutableColumns & res_columns, ContextPtr context, const SelectQueryInfo &) const
{
auto query_cache = context->getQueryCache();
if (!query_cache)
return;
std::vector<QueryCache::Cache::KeyMapped> content = query_cache->dump();
const String & user_name = context->getUserName();
for (const auto & [key, query_result] : content)
{
/// Showing other user's queries is considered a security risk
if (!key.is_shared && key.user_name != user_name)
continue;
res_columns[0]->insert(key.queryStringFromAst()); /// approximates the original query string
res_columns[1]->insert(QueryCache::QueryResultWeight()(*query_result));
res_columns[2]->insert(key.expires_at < std::chrono::system_clock::now());
res_columns[3]->insert(!key.is_shared);
res_columns[4]->insert(key.is_compressed);
res_columns[5]->insert(std::chrono::system_clock::to_time_t(key.expires_at));
res_columns[6]->insert(key.ast->getTreeHash().first);
}
}
}
| [
"robert@clickhouse.com"
] | robert@clickhouse.com |
3e590a62e6c297cb3a9d1b910baa427061a23dc7 | d278b9acce1667a34e0dd306e02776391b7aaeb6 | /vsomeip/implementation/plugin/src/plugin_manager.cpp | e922fd6e6d6bfa07a9771ebcdc8237e5d412e9d1 | [
"MPL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | permissive | MathewRo/some-ip | 26608531d794e7e82c156ed00b912bf906b39b5f | e57f29872dbe69333c7394b077bbdc87ee321dd7 | refs/heads/master | 2020-06-18T05:37:52.857218 | 2019-07-10T10:52:16 | 2019-07-10T10:52:16 | 196,182,158 | 0 | 0 | BSD-3-Clause | 2019-07-10T10:09:08 | 2019-07-10T10:09:08 | null | UTF-8 | C++ | false | false | 7,235 | cpp | // Copyright (C) 2016-2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <sstream>
#include <vector>
#include <stdlib.h>
#include <iostream>
#ifdef _WIN32
#ifndef _WINSOCKAPI_
#include <Windows.h>
#endif
#else
#include <dlfcn.h>
#endif
#include <vsomeip/plugins/application_plugin.hpp>
#include <vsomeip/plugins/pre_configuration_plugin.hpp>
#include "../include/plugin_manager.hpp"
#include "../../configuration/include/internal.hpp"
#include "../../logging/include/logger.hpp"
#include "../../utility/include/utility.hpp"
namespace vsomeip {
std::shared_ptr<plugin_manager> plugin_manager::the_plugin_manager__ =
std::make_shared<plugin_manager>();
std::shared_ptr<plugin_manager> plugin_manager::get() {
return the_plugin_manager__;
}
plugin_manager::plugin_manager() :
plugins_loaded_(false) {
}
plugin_manager::~plugin_manager() {
handles_.clear();
plugins_.clear();
}
void plugin_manager::load_plugins() {
{
std::lock_guard<std::mutex> its_lock_start_stop(loader_mutex_);
if (plugins_loaded_) {
return;
}
plugins_loaded_ = true;
}
// Get plug-ins libraries from environment
std::vector<std::string> plugins;
const char *its_plugins = getenv(VSOMEIP_ENV_LOAD_PLUGINS);
if (nullptr != its_plugins) {
std::string token;
std::stringstream ss(its_plugins);
while(std::getline(ss, token, ',')) {
plugins.push_back(token);
}
}
std::lock_guard<std::mutex> its_lock_start_stop(plugins_mutex_);
// Load plug-in info from libraries parsed before
for (auto plugin_name : plugins) {
void* handle = load_library(plugin_name);
plugin_init_func its_init_func = reinterpret_cast<plugin_init_func>(
load_symbol(handle, VSOMEIP_PLUGIN_INIT_SYMBOL));
if (its_init_func) {
create_plugin_func its_create_func = (*its_init_func)();
if (its_create_func) {
auto its_plugin = (*its_create_func)();
if (its_plugin) {
handles_[its_plugin->get_plugin_type()][plugin_name] = handle;
switch (its_plugin->get_plugin_type()) {
case plugin_type_e::APPLICATION_PLUGIN:
if (its_plugin->get_plugin_version()
== VSOMEIP_APPLICATION_PLUGIN_VERSION) {
add_plugin(its_plugin, plugin_name);
} else {
VSOMEIP_ERROR << "Plugin version mismatch. "
<< "Ignoring application plugin "
<< its_plugin->get_plugin_name();
}
break;
case plugin_type_e::PRE_CONFIGURATION_PLUGIN:
if (its_plugin->get_plugin_version()
== VSOMEIP_PRE_CONFIGURATION_PLUGIN_VERSION) {
add_plugin(its_plugin, plugin_name);
} else {
VSOMEIP_ERROR << "Plugin version mismatch. Ignoring "
<< "pre-configuration plugin "
<< its_plugin->get_plugin_name();
}
break;
default:
break;
}
}
}
}
}
}
std::shared_ptr<plugin> plugin_manager::get_plugin(plugin_type_e _type, std::string _name) {
std::lock_guard<std::mutex> its_lock_start_stop(plugins_mutex_);
auto its_type = plugins_.find(_type);
if (its_type != plugins_.end()) {
auto its_name = its_type->second.find(_name);
if (its_name != its_type->second.end()) {
return its_name->second;
}
}
return load_plugin(_name, _type, 1);
}
std::shared_ptr<plugin> plugin_manager::load_plugin(const std::string _library,
plugin_type_e _type, uint32_t _version) {
void* handle = load_library(_library);
plugin_init_func its_init_func = reinterpret_cast<plugin_init_func>(
load_symbol(handle, VSOMEIP_PLUGIN_INIT_SYMBOL));
if (its_init_func) {
create_plugin_func its_create_func = (*its_init_func)();
if (its_create_func) {
handles_[_type][_library] = handle;
auto its_plugin = (*its_create_func)();
if (its_plugin) {
if (its_plugin->get_plugin_type() == _type
&& its_plugin->get_plugin_version() == _version) {
add_plugin(its_plugin, _library);
return its_plugin;
} else {
VSOMEIP_ERROR << "Plugin version mismatch. Ignoring plugin "
<< its_plugin->get_plugin_name();
}
}
}
}
return nullptr;
}
bool plugin_manager::unload_plugin(plugin_type_e _type) {
std::lock_guard<std::mutex> its_lock_start_stop(plugins_mutex_);
const auto found_handle = handles_.find(_type);
if (found_handle != handles_.end()) {
for (auto its_name : found_handle->second) {
#ifdef _WIN32
FreeLibrary((HMODULE)its_name.second);
#else
if (dlclose(its_name.second)) {
VSOMEIP_ERROR << "Unloading failed: (" << dlerror() << ")";
}
#endif
}
} else {
VSOMEIP_ERROR << "plugin_manager::unload_plugin didn't find plugin"
<< " type:" << (int)_type;
return false;
}
return plugins_.erase(_type);
}
void plugin_manager::add_plugin(const std::shared_ptr<plugin> &_plugin, const std::string _name) {
plugins_[_plugin->get_plugin_type()][_name] = _plugin;
}
void * plugin_manager::load_library(const std::string &_path) {
#ifdef _WIN32
return LoadLibrary(_path.c_str());
#else
return dlopen(_path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
#endif
}
void * plugin_manager::load_symbol(void * _handle,
const std::string &_symbol) {
void * its_symbol = 0;
#ifdef _WIN32
HINSTANCE hDLL = (HINSTANCE)_handle;
if (hDLL != NULL) {
typedef UINT(CALLBACK* LPFNDLLFUNC1)(DWORD, UINT);
LPFNDLLFUNC1 lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hDLL, _symbol.c_str());
if (!lpfnDllFunc1) {
FreeLibrary(hDLL);
std::cerr << "Loading symbol \"" << _symbol << "\" failed (" << GetLastError() << ")" << std::endl;
}
else {
its_symbol = lpfnDllFunc1;
}
}
#else
if (0 != _handle) {
its_symbol = dlsym(_handle, _symbol.c_str());
const char *dlsym_error = dlerror();
if (dlsym_error) {
VSOMEIP_INFO << "Cannot load symbol : " << _symbol << " : " << dlsym_error;
dlclose(_handle);
}
} else {
VSOMEIP_ERROR << "Loading failed: (" << dlerror() << ")";
}
#endif
return (its_symbol);
}
}
| [
"rohitpmathew@yahoo.co.in"
] | rohitpmathew@yahoo.co.in |
0d5f5d88ef13038c0e8f07f0a2d55395b203cc5e | 460f53717578874392e7762da48a49024140776e | /src/SCC.h | a6749b082041a285e717c1da9f39b1bd6d3c989d | [] | no_license | pstamatop/sigmod-2016 | a691e081533a9cdeb0c2073e7e1c19f90bb482be | 56e7efa2bd419a5bce6b9686b2bac63c2b8868d2 | refs/heads/master | 2020-06-06T00:47:28.127508 | 2019-06-19T16:53:49 | 2019-06-19T16:53:49 | 192,591,114 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | h | #ifndef SCC_H
#define SCC_H
#include "NodeIndex.h"
#include "sizes.h"
struct ComponentCursor{
int index; // current component index
ComponentCursor();
void reset();
};
class Component {
public:
Component(int);
bool addNode(int);
int getId();
int getCount();
int getSize(); //getters for unit testing
void print(); //testing purposes only
int getLastUsed();
void setLastUsed(int);
int getNextIndex();
void setNextIndex(int);
void incrTotalIncludedNodes();
int getTotalIncludedNodes();
int getNode(int);
private:
int id_;
int count_;
int includedNodes_[COMPNODES];
int totalIncludedNodes_;
int size_;
int nextIndex_;
int lastUsed_;
};
class SCC {
public:
SCC();
~SCC();
void init(int);
void addComponent(int, bool);
int searchComponent(int); //returns an index
bool addNode(int, int);
int getCompCount();
void printCompNodes(int); //testing purposes only
int getCount();
void iterateSCC(); //begin an iteration aka reset the cursor
bool nextSSC(); // while in array bounds increment the cursor
Component* getCurrentSCC();// get the current Component (the one that the component cursor points to)
int belongsToComponent(int);
int getNode(int, int, int&, int&);
int getTotalIncludedNodes(int);
private:
Component* components_;
NodeIndex sccIndex_;
ComponentCursor compCursor_;
int compCount_;
int count_;
int* belongsToComponent_;
int size_;
int arraySize_;
};
#endif | [
"pstamatop@gmail.com"
] | pstamatop@gmail.com |
a1f1d4f56d7a4e18da7479765d052536bcb82e1e | 92e7a96c196e563b70f78db321680d830af80a53 | /FastTrader/platformSvr/PlatFormService.cpp | e20ccae9c32c2ec905bb171d529aa5a90d1a3fcd | [] | no_license | alexfordc/zq | 513723341132dd2b01f5ca3debb567b2fd31c033 | a0b05b7416fe68784e072da477e8c869097584e2 | refs/heads/master | 2021-05-25T14:19:37.317957 | 2018-02-24T05:57:23 | 2018-02-24T05:57:23 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 106,239 | cpp | #include "stdafx.h"
#include "PlatFormService.hpp"
#include "DataCenter.hpp"
#include "wx/thread.h"
#include "../inc/Module-Misc2/packagecache.h"
#include "../inc/Module-Misc2/SimpleWriteLog.h"
#include "../inc/Module-Misc2/GlobalConfigMgr.h"
#include "FileOpr.h"
#include "tmpstackbuf.h"
using std::string;
#ifndef LOG_INFO
#if 0
#define LOG_INFO(fmt, ...)
#else
#define LOG_INFO(fmt, ...) \
do{\
if(m_pWriteLog)\
{\
m_pWriteLog->WriteLog_Fmt("CPlatFormService", LOGLEVEL_DEBUGINFO, "[%s][%d]:"fmt, __CUSTOM_FILE__, __LINE__, __VA_ARGS__);\
}\
}while(0)
#endif
#endif
//extern std::map<std::string, int> g_allPlatformID;
#include "TcpPortMap.h"
//****************************************************************************
// 代理服务器的处理:
// 1. socks4/socks4a/socks5: 直接连接socks5:// asp-sim2-front1.financial-trading-platform.com:26205/user:pass@127.0.0.1:10001接口
// 2. http : (1) 首先创建端口映射对象CTcpPortMap 将127.0.0.1:5739映射到http proxy server
// (2) 让ctp连接127.0.0.1:5739
// (3) release ctp时, 注销CTcpPortMap对象
//****************************************************************************
std::string MakeConnectStr(const std::string& addr,const Stru_ProxyServerParam& ProxyParam)
{
string rltstr;
//去掉左右空白和"tcp://"
string deststr=addr;
CTools_Ansi::mytrim(deststr);
int pos=deststr.find("tcp://");
if(pos!=string::npos) deststr=deststr.substr(pos+6);
//代理格式: "socks5://asp-sim2-front1.financial-trading-platform.com:26205/user:pass@127.0.0.1:10001"
//ConnectStr格式: "socks4://10.11.112.172:8888"
//if(!g_pTcpPortMap4HttpProxy)
// g_pTcpPortMap4HttpProxy=new CTcpPortMap();
if(ProxyParam.ProxyType==string("socks4")||
ProxyParam.ProxyType==string("socks4a")||
ProxyParam.ProxyType==string("socks5"))
{
rltstr=
ProxyParam.ProxyType+string("://")+
deststr+string("/")+
ProxyParam.ProxyUser+string(":")+
ProxyParam.ProxyPassword+string("@")+
ProxyParam.ProxyIP+string(":")+
ProxyParam.ProxyPort;
}
else if(ProxyParam.ProxyType==string("http"))
{
CTools_Ansi::PerformWSAStartup();
Stru_IPAddress DestAddr(deststr);
if(!CTcpPortMap::getObj().IsDestAddrExist(DestAddr))
{
Stru_IPAddress BindAddr(string("127.0.0.1:0"));
Stru_IPAddress ProxySvrAddr(ProxyParam.dwProxyIP,ProxyParam.usProxyPort);
CTcpPortMap::Stru_PortMapParam PortMapParam(BindAddr,DestAddr,CTcpPortMap::Map_BypassHttpProxySvr,ProxySvrAddr);
//创建一个端口映射, 绑定地址为127.0.0.1:ProxyParam.PortMapParam.Port
CTcpPortMap::getObj().NewPortMap(PortMapParam);
//让ctp指向127.0.0.1:bindport
char buf[256];
_snprintf(buf,sizeof(buf)-1,"tcp://127.0.0.1:%d",PortMapParam.BindAddr.Port);
rltstr=string(buf);
}
CTools_Ansi::PerformWSACleanup();
}
else rltstr=string("tcp://")+deststr;
return rltstr;
}
class CTradeThread : public wxThread
{
public:
CTradeThread(CPlatFormService& RefPlatFormService)
:wxThread(),
m_PlatFormService(RefPlatFormService),
m_FrontAddrs(RefPlatFormService.m_PlatformParam.TradeFrontAddrs),
m_ProxyParam(RefPlatFormService.m_PlatformParam.ProxyParam)
{
}
// thread execution starts here
virtual void *Entry()
{
if(GlobalConfigManager::m_Test_bLogThreadID)
CFileOpr::getObj().writelocallog("threadid","TID:\t% 8u\tCTradeThread::Entry",GetCurrentThreadId());
m_PlatFormService.m_pTradeApi->SubscribePublicTopic(THOST_TERT_QUICK);
m_PlatFormService.m_pTradeApi->SubscribePrivateTopic(THOST_TERT_QUICK);
std::string addrstr;
for(std::vector<std::string>::iterator it=m_FrontAddrs.begin();it!=m_FrontAddrs.end();++it)
{
addrstr=MakeConnectStr(*it,m_ProxyParam);
// addrstr=string("socks4://180.168.102.193:41205/:@180.169.125.49:8888");
// addrstr=string("http://180.168.102.193:41205/:@61.181.131.102:9999");
m_PlatFormService.m_pTradeApi->RegisterFront(const_cast<char*>(addrstr.c_str()));// 连接前置机
}
m_PlatFormService.m_pTradeApi->Init();
m_PlatFormService.m_pTradeApi->Join();
while(!TestDestroy())//等待CPlatFormService::LogoutTrade主动杀掉此线程
{
wxThread::Sleep(1);
}
return NULL;
}
// called when the thread exits - whether it terminates normally or is
// stopped with Delete() (but not when it is Kill()ed!)
virtual void OnExit()
{
m_PlatFormService.m_pTradeWorkThread = NULL;
}
private:
CPlatFormService& m_PlatFormService;
Stru_ProxyServerParam m_ProxyParam;
std::vector<std::string> m_FrontAddrs;
};
class CQuotThread : public wxThread
{
public:
CQuotThread(CPlatFormService& RefPlatFormService)
:wxThread(),
m_PlatFormService(RefPlatFormService),
m_FrontAddrs(RefPlatFormService.m_PlatformParam.QuotFrontAddrs),
m_ProxyParam(RefPlatFormService.m_PlatformParam.ProxyParam)
{
}
// thread execution starts here
virtual void *Entry()
{
if(GlobalConfigManager::m_Test_bLogThreadID)
CFileOpr::getObj().writelocallog("threadid","TID:\t% 8u\tCQuotThread::Entry",GetCurrentThreadId());
std::string addrstr;
for(std::vector<std::string>::iterator it=m_FrontAddrs.begin();it!=m_FrontAddrs.end();++it)
{
addrstr=MakeConnectStr(*it,m_ProxyParam);
m_PlatFormService.m_pQuotApi->RegisterFront(const_cast<char*>(addrstr.c_str()));// 连接前置机
}
m_PlatFormService.m_pQuotApi->Init();
m_PlatFormService.m_pQuotApi->Join();
while(!TestDestroy())//等待CPlatFormService::LogoutQuot主动杀掉此线程
{
wxThread::Sleep(1);
}
return NULL;
}
// called when the thread exits - whether it terminates normally or is
// stopped with Delete() (but not when it is Kill()ed!)
virtual void OnExit()
{
m_PlatFormService.m_pQuotWorkThread = NULL;
}
private:
CPlatFormService& m_PlatFormService;
Stru_ProxyServerParam m_ProxyParam;
std::vector<std::string> m_FrontAddrs;
};
//仅限于CPlatFormService的成员函数使用
#define CHECK_TRADE_STATUS() \
if(!m_pTradeApi || m_PlatformParam.TradeStatus!=CTPCONNSTATUS_Connected)\
{\
LOG_INFO("交易API还未准备就绪, 可能登入未成功或正在重连");\
return ret;\
}
///用户口令更新请求
/***********************************************************
* return : 0:成功
* -1: 网络连接失败
* -2: 未处理请求超过许可数
* -3: 每秒发送请求数超过许可数
* -999: 其它原因失败
***********************************************************/
int CPlatFormService::ReqUserPasswordUpdate(PlatformStru_UserPasswordUpdate *pUserPasswordUpdate, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
CThostFtdcUserPasswordUpdateField req={0};
strncpy(req.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(req.BrokerID)-1);
strncpy(req.UserID, m_PlatformParam.UserID.c_str(), sizeof(req.UserID)-1);
strncpy(req.NewPassword, pUserPasswordUpdate->NewPassword, sizeof(req.NewPassword)-1);
strncpy(req.OldPassword, pUserPasswordUpdate->OldPassword, sizeof(req.OldPassword)-1);
ret = m_pTradeApi->ReqUserPasswordUpdate(&req, nRequestID);
LOG_INFO("ReqUserPasswordUpdate(用户口令更新请求):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],UserID=[%s],OldPassword=[******],NewPassword=[******]",
ret, nRequestID,
req.BrokerID,
req.UserID);
return ret;
}
///资金账户口令更新请求
int CPlatFormService::ReqTradingAccountPasswordUpdate(PlatformStru_TradingAccountPasswordUpdate *pTradingAccountPasswordUpdate, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
CThostFtdcTradingAccountPasswordUpdateField req={0};
strncpy(req.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(req.BrokerID)-1);
strncpy(req.AccountID, m_PlatformParam.UserID.c_str(), sizeof(req.AccountID)-1);
strncpy(req.OldPassword, pTradingAccountPasswordUpdate->OldPassword, sizeof(req.OldPassword)-1);
strncpy(req.NewPassword, pTradingAccountPasswordUpdate->NewPassword, sizeof(req.NewPassword)-1);
strncpy(req.CurrencyID, pTradingAccountPasswordUpdate->CurrencyID, sizeof(req.CurrencyID)-1);
ret = m_pTradeApi->ReqTradingAccountPasswordUpdate(&req, nRequestID);
LOG_INFO("ReqTradingAccountPasswordUpdate(资金账户口令更新请求):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],AccountID=[%s],OldPassword=[******],NewPassword=[******],CurrencyID=[%s]",
ret, nRequestID,
req.BrokerID,
req.AccountID,
req.CurrencyID);
return ret;
}
///报单录入请求. 返回时pInputOrder中的RequestID, BrokerID, InvestorID, UserID, OrderRef的值被修改为底层确定的值
int CPlatFormService::ReqOrderInsert(PlatformStru_InputOrder *pInputOrder, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
pInputOrder->RequestID = nRequestID;
strncpy(pInputOrder->BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pInputOrder->BrokerID)-1); ///经纪公司代码
strncpy(pInputOrder->InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pInputOrder->InvestorID)-1); ///投资者代码
strncpy(pInputOrder->UserID, m_PlatformParam.UserID.c_str(), sizeof(pInputOrder->UserID)-1); ///用户代码
//pInputOrder->ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
sprintf(pInputOrder->OrderRef,"%12d",++m_CurOrderRef);
CThostFtdcInputOrderField tField = {0};
strcpy(tField.BrokerID, pInputOrder->BrokerID); ///经纪公司代码
strcpy(tField.InvestorID, pInputOrder->InvestorID); ///投资者代码
strcpy(tField.InstrumentID, pInputOrder->InstrumentID); ///合约代码
strcpy(tField.OrderRef, pInputOrder->OrderRef); ///报单引用
strcpy(tField.UserID, pInputOrder->UserID); ///用户代码
tField.OrderPriceType = pInputOrder->OrderPriceType; ///报单价格条件
tField.Direction = pInputOrder->Direction; ///买卖方向
strcpy(tField.CombOffsetFlag, pInputOrder->CombOffsetFlag); ///组合开平标志
strcpy(tField.CombHedgeFlag, pInputOrder->CombHedgeFlag); ///组合投机套保标志
tField.LimitPrice = pInputOrder->LimitPrice; ///价格
tField.VolumeTotalOriginal = pInputOrder->VolumeTotalOriginal; ///数量
tField.TimeCondition = pInputOrder->TimeCondition; ///有效期类型
strcpy(tField.GTDDate, pInputOrder->GTDDate); ///GTD日期
tField.VolumeCondition = pInputOrder->VolumeCondition; ///成交量类型
tField.MinVolume = pInputOrder->MinVolume; ///最小成交量
tField.ContingentCondition = pInputOrder->ContingentCondition; ///触发条件
tField.StopPrice = pInputOrder->StopPrice; ///止损价
tField.ForceCloseReason = pInputOrder->ForceCloseReason; ///强平原因
tField.IsAutoSuspend = pInputOrder->IsAutoSuspend; ///自动挂起标志
strcpy(tField.BusinessUnit, pInputOrder->BusinessUnit); ///业务单元
tField.RequestID = pInputOrder->RequestID; ///请求编号
tField.UserForceClose = pInputOrder->UserForceClose; ///用户强评标志
////对于中金所的组合合约,把HedgeFlag设置为套利
//PlatformStru_InstrumentInfo InstrumentInfo;
//if(pInputOrder->CombHedgeFlag[0]==THOST_FTDC_HF_Speculation&&
// GetInstrumentInfo(string(pInputOrder->InstrumentID),InstrumentInfo)==0&&
// string(InstrumentInfo.ExchangeID)==string("CFFEX")&&
// InstrumentInfo.ProductClass==THOST_FTDC_PC_Combination)
// tField.CombHedgeFlag[0]=THOST_FTDC_HF_Arbitrage;
ret = m_pTradeApi->ReqOrderInsert(&tField, nRequestID);
LOG_INFO("ReqOrderInsert(报单录入请求):ret=[%d],nRequestID=[%d]\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s],\t OrderRef=[%s],\t UserID=[%s],\n"
"\t\t\t OrderPriceType=[%d],\t Direction=[%d],\t CombOffsetFlag=[%s],\t CombHedgeFlag=[%s],\t LimitPrice=[%g],\n"
"\t\t\t VolumeTotalOriginal=[%d],\t TimeCondition=[%d],\t GTDDate=[%s],\t VolumeCondition=[%d],\t MinVolume=[%d],\n"
"\t\t\t ContingentCondition=[%d],\t StopPrice=[%g],\t ForceCloseReason=[%d],\t IsAutoSuspend=[%d],\t BusinessUnit=[%s],\n"
"\t\t\t RequestID=[%d],\t UserForceClose=[%d]",
ret, nRequestID,
pInputOrder->BrokerID, pInputOrder->InvestorID, pInputOrder->InstrumentID, pInputOrder->OrderRef,pInputOrder->UserID,
pInputOrder->OrderPriceType, pInputOrder->Direction, pInputOrder->CombOffsetFlag, pInputOrder->CombHedgeFlag,pInputOrder->LimitPrice,
pInputOrder->VolumeTotalOriginal, pInputOrder->TimeCondition, pInputOrder->GTDDate, pInputOrder->VolumeCondition,pInputOrder->MinVolume,
pInputOrder->ContingentCondition, pInputOrder->StopPrice, pInputOrder->ForceCloseReason, pInputOrder->IsAutoSuspend,pInputOrder->BusinessUnit,
pInputOrder->RequestID, pInputOrder->UserForceClose);
return ret;
}
///预埋单录入请求. 返回时pInputOrder中的RrequestID, BrokerID, InvestorID, UserID, OrderRef的值被修改为底层确定的值
int CPlatFormService::ReqParkedOrderInsert(PlatformStru_ParkedOrder *pParkedOrder, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
pParkedOrder->RequestID = nRequestID;
strncpy(pParkedOrder->BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pParkedOrder->BrokerID)-1); ///经纪公司代码
strncpy(pParkedOrder->InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pParkedOrder->InvestorID)-1); ///投资者代码
strncpy(pParkedOrder->UserID, m_PlatformParam.UserID.c_str(), sizeof(pParkedOrder->UserID)-1); ///用户代码
//pInputOrder->ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
sprintf(pParkedOrder->OrderRef,"%12d",++m_CurOrderRef);
///预埋单
CThostFtdcParkedOrderField req={0};
strncpy(req.BrokerID, pParkedOrder->BrokerID, sizeof(req.BrokerID));///经纪公司代码
strncpy(req.InvestorID, pParkedOrder->InvestorID, sizeof(req.InvestorID));///投资者代码
strncpy(req.InstrumentID, pParkedOrder->InstrumentID, sizeof(req.InstrumentID));///合约代码
strncpy(req.OrderRef, pParkedOrder->OrderRef, sizeof(req.OrderRef));///报单引用
strncpy(req.UserID, pParkedOrder->UserID, sizeof(req.UserID));///用户代码
req.OrderPriceType = pParkedOrder->OrderPriceType;///报单价格条件
req.Direction = pParkedOrder->Direction;///买卖方向
strncpy(req.CombOffsetFlag, pParkedOrder->CombOffsetFlag, sizeof(req.CombOffsetFlag));///组合开平标志
strncpy(req.CombHedgeFlag, pParkedOrder->CombHedgeFlag, sizeof(req.CombHedgeFlag));///组合投机套保标志
req.LimitPrice = pParkedOrder->LimitPrice;///价格
req.VolumeTotalOriginal = pParkedOrder->VolumeTotalOriginal;///数量
req.TimeCondition = pParkedOrder->TimeCondition;///有效期类型
strncpy(req.GTDDate, pParkedOrder->GTDDate, sizeof(req.GTDDate));///GTD日期
req.VolumeCondition = pParkedOrder->VolumeCondition;///成交量类型
req.MinVolume = pParkedOrder->MinVolume;///最小成交量
req.ContingentCondition = pParkedOrder->ContingentCondition;///触发条件
req.StopPrice = pParkedOrder->StopPrice;///止损价
req.ForceCloseReason = pParkedOrder->ForceCloseReason;///强平原因
req.IsAutoSuspend = pParkedOrder->IsAutoSuspend;///自动挂起标志
strncpy(req.BusinessUnit, pParkedOrder->BusinessUnit, sizeof(req.BusinessUnit));///业务单元
req.RequestID = pParkedOrder->RequestID;///请求编号
req.UserForceClose = pParkedOrder->UserForceClose;///用户强评标志
strncpy(req.ExchangeID, pParkedOrder->ExchangeID, sizeof(req.ExchangeID));///交易所代码
strncpy(req.ParkedOrderID, pParkedOrder->ParkedOrderID, sizeof(req.ParkedOrderID));///预埋报单编号
req.UserType = pParkedOrder->UserType;///用户类型
req.Status = pParkedOrder->Status;///预埋单状态
req.ErrorID = pParkedOrder->ErrorID;///错误代码
strncpy(req.ErrorMsg, pParkedOrder->ErrorMsg, sizeof(req.ErrorMsg));///错误信息
ret = m_pTradeApi->ReqParkedOrderInsert(&req, nRequestID);
LOG_INFO("ReqOrderInsert(预埋报单录入请求):ret=[%d],nRequestID=[%d]\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s],\t OrderRef=[%s],\t UserID=[%s],\n"
"\t\t\t OrderPriceType=[%d],\t Direction=[%d],\t CombOffsetFlag=[%s],\t CombHedgeFlag=[%s],\t LimitPrice=[%g],\n"
"\t\t\t VolumeTotalOriginal=[%d],\t TimeCondition=[%d],\t GTDDate=[%s],\t VolumeCondition=[%d],\t MinVolume=[%d],\n"
"\t\t\t ContingentCondition=[%d],\t StopPrice=[%g],\t ForceCloseReason=[%d],\t IsAutoSuspend=[%d],\t BusinessUnit=[%s],\n"
"\t\t\t RequestID=[%d],\t UserForceClose=[%d]",
ret, nRequestID,
pParkedOrder->BrokerID, pParkedOrder->InvestorID, pParkedOrder->InstrumentID, pParkedOrder->OrderRef,pParkedOrder->UserID,
pParkedOrder->OrderPriceType, pParkedOrder->Direction, pParkedOrder->CombOffsetFlag, pParkedOrder->CombHedgeFlag,pParkedOrder->LimitPrice,
pParkedOrder->VolumeTotalOriginal, pParkedOrder->TimeCondition, pParkedOrder->GTDDate, pParkedOrder->VolumeCondition,pParkedOrder->MinVolume,
pParkedOrder->ContingentCondition, pParkedOrder->StopPrice, pParkedOrder->ForceCloseReason, pParkedOrder->IsAutoSuspend,pParkedOrder->BusinessUnit,
pParkedOrder->RequestID, pParkedOrder->UserForceClose);
return ret;
}
///预埋撤单录入请求
int CPlatFormService::ReqParkedOrderAction(PlatformStru_ParkedOrderAction *pParkedOrderAction, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
pParkedOrderAction->Thost.RequestID = nRequestID;
strncpy(pParkedOrderAction->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pParkedOrderAction->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pParkedOrderAction->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pParkedOrderAction->Thost.InvestorID)-1); ///投资者代码
pParkedOrderAction->Thost.ActionFlag = THOST_FTDC_AF_Delete;
ret = m_pTradeApi->ReqParkedOrderAction(&pParkedOrderAction->Thost, nRequestID);
LOG_INFO("ReqParkedOrderAction(预埋撤单录入请求):ret=[%d],nRequestID=[%d]\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t OrderActionRef=[%d],\t OrderRef=[%s],\t RequestID=[%d],\n"
"\t\t\t FrontID=[%d],\t SessionID=[%#x],\t ExchangeID=[%s],\t OrderSysID=[%s],\t ActionFlag=[%d],\n"
"\t\t\t LimitPrice=[%g],\t VolumeChange=[%d],\t UserID=[%s],\t InstrumentID=[%s]",
ret, nRequestID,
pParkedOrderAction->Thost.BrokerID, pParkedOrderAction->Thost.InvestorID, pParkedOrderAction->Thost.OrderActionRef, pParkedOrderAction->Thost.OrderRef,pParkedOrderAction->Thost.RequestID,
pParkedOrderAction->Thost.FrontID, pParkedOrderAction->Thost.SessionID, pParkedOrderAction->Thost.ExchangeID, pParkedOrderAction->Thost.OrderSysID,pParkedOrderAction->Thost.ActionFlag,
pParkedOrderAction->Thost.LimitPrice, pParkedOrderAction->Thost.VolumeChange, pParkedOrderAction->Thost.UserID, pParkedOrderAction->Thost.InstrumentID);
return ret;
}
///报单操作请求
///
int CPlatFormService::ReqOrderAction(PlatformStru_InputOrderAction *pInputOrderAction, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
pInputOrderAction->Thost.RequestID = nRequestID;
strncpy(pInputOrderAction->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pInputOrderAction->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pInputOrderAction->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pInputOrderAction->Thost.InvestorID)-1); ///投资者代码
pInputOrderAction->Thost.ActionFlag = THOST_FTDC_AF_Delete;
ret = m_pTradeApi->ReqOrderAction(&pInputOrderAction->Thost, nRequestID);
LOG_INFO("ReqOrderAction(报单操作请求):ret=[%d],nRequestID=[%d]\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t OrderActionRef=[%d],\t OrderRef=[%s],\t RequestID=[%d],\n"
"\t\t\t FrontID=[%d],\t SessionID=[%#x],\t ExchangeID=[%s],\t OrderSysID=[%s],\t ActionFlag=[%d],\n"
"\t\t\t LimitPrice=[%g],\t VolumeChange=[%d],\t UserID=[%s],\t InstrumentID=[%s]",
ret, nRequestID,
pInputOrderAction->Thost.BrokerID, pInputOrderAction->Thost.InvestorID, pInputOrderAction->Thost.OrderActionRef, pInputOrderAction->Thost.OrderRef,pInputOrderAction->Thost.RequestID,
pInputOrderAction->Thost.FrontID, pInputOrderAction->Thost.SessionID, pInputOrderAction->Thost.ExchangeID, pInputOrderAction->Thost.OrderSysID,pInputOrderAction->Thost.ActionFlag,
pInputOrderAction->Thost.LimitPrice, pInputOrderAction->Thost.VolumeChange, pInputOrderAction->Thost.UserID, pInputOrderAction->Thost.InstrumentID);
return ret;
}
///报单操作请求(撤单)
int CPlatFormService::ReqCancelOrder(const OrderKey& orderkey, int nRequestID)
{
PlatformStru_OrderInfo OrderInfo;
if(!m_pDataCenter->GetOrder(orderkey,OrderInfo))
return -1;
PlatformStru_InputOrderAction ReqData;
ReqData.Thost.FrontID=OrderInfo.FrontID;
ReqData.Thost.SessionID=OrderInfo.SessionID;
memcpy(ReqData.Thost.OrderRef, OrderInfo.OrderRef, sizeof(OrderInfo.OrderRef));
memcpy(ReqData.Thost.OrderSysID, OrderInfo.OrderSysID, sizeof(OrderInfo.OrderSysID));
memcpy(ReqData.Thost.ExchangeID, OrderInfo.ExchangeID, sizeof(OrderInfo.ExchangeID));
memcpy(ReqData.Thost.InstrumentID, OrderInfo.InstrumentID, sizeof(OrderInfo.InstrumentID));
return ReqOrderAction(&ReqData,nRequestID);
}
///查询最大报单数量请求
int CPlatFormService::ReqQueryMaxOrderVolume(PlatformStru_QueryMaxOrderVolume *pQueryMaxOrderVolume, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQueryMaxOrderVolume(&pQueryMaxOrderVolume->Thost, nRequestID);
return ret;
}
///投资者结算结果确认
int CPlatFormService::ReqSettlementInfoConfirm()
{
int ret = -999;
CHECK_TRADE_STATUS();
CThostFtdcSettlementInfoConfirmField req;
memset(&req, 0, sizeof(req));
strcpy(req.BrokerID, m_PlatformParam.BrokerID.c_str());
strcpy(req.InvestorID, m_PlatformParam.InvestorID.c_str());
int nRequestID=m_PlatformParam.RequestID++;
ret = m_pTradeApi->ReqSettlementInfoConfirm(&req, nRequestID);
LOG_INFO("ReqSettlementInfoConfirm(投资者结算结果确认):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t ConfirmDate=[%s],\t ConfirmTime=[%s]",
ret, nRequestID,
req.BrokerID,
req.InvestorID,
req.ConfirmDate,
req.ConfirmTime);
return ret;
}
///请求删除预埋单
int CPlatFormService::ReqRemoveParkedOrder(PlatformStru_RemoveParkedOrder *pRemoveParkedOrder, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pRemoveParkedOrder->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pRemoveParkedOrder->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pRemoveParkedOrder->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pRemoveParkedOrder->Thost.InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqRemoveParkedOrder(&pRemoveParkedOrder->Thost, nRequestID);
LOG_INFO("ReqRemoveParkedOrder(请求删除预埋单):ret=[%d],nRequestID=[%d]\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t ParkedOrderID=[%s]",
ret, nRequestID,
pRemoveParkedOrder->Thost.BrokerID, pRemoveParkedOrder->Thost.InvestorID, pRemoveParkedOrder->Thost.ParkedOrderID);
return ret;
}
///请求删除预埋撤单
int CPlatFormService::ReqRemoveParkedOrderAction(PlatformStru_RemoveParkedOrderAction *pRemoveParkedOrderAction, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pRemoveParkedOrderAction->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pRemoveParkedOrderAction->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pRemoveParkedOrderAction->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pRemoveParkedOrderAction->Thost.InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqRemoveParkedOrderAction(&pRemoveParkedOrderAction->Thost, nRequestID);
LOG_INFO("ReqRemoveParkedOrderAction(请求删除预埋撤单):ret=[%d],nRequestID=[%d]\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t ParkedOrderActionID=[%s]",
ret, nRequestID,
pRemoveParkedOrderAction->Thost.BrokerID, pRemoveParkedOrderAction->Thost.InvestorID, pRemoveParkedOrderAction->Thost.ParkedOrderActionID);
return ret;
}
///请求查询报单
int CPlatFormService::ReqQryOrder(PlatformStru_QryOrder *pQryOrder, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryOrder(&pQryOrder->Thost, nRequestID);
if(ret==0)
m_pDataCenter->ClearMapQryRltOrders();
LOG_INFO("ReqQryOrder(请求查询报单):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s],\t ExchangeID=[%s],\t OrderSysID=[%s],\n"
"\t\t\t InsertTimeStart=[%s],\t InsertTimeEnd=[%s]",
ret, nRequestID,
pQryOrder->Thost.BrokerID,
pQryOrder->Thost.InvestorID,
pQryOrder->Thost.InstrumentID,
pQryOrder->Thost.ExchangeID,
pQryOrder->Thost.OrderSysID,
pQryOrder->Thost.InsertTimeStart,
pQryOrder->Thost.InsertTimeEnd);
return ret;
}
///请求查询成交
int CPlatFormService::ReqQryTrade(PlatformStru_QryTrade *pQryTrade, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
m_pDataCenter->ClearMapQryRltTrades();
ret = m_pTradeApi->ReqQryTrade(&pQryTrade->Thost, nRequestID);
LOG_INFO("ReqQryTrade(请求查询成交):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s],\t ExchangeID=[%s],\t TradeID=[%s],\n"
"\t\t\t TradeTimeStart=[%s],\t TradeTimeEnd=[%s]",
ret, nRequestID,
pQryTrade->Thost.BrokerID,
pQryTrade->Thost.InvestorID,
pQryTrade->Thost.InstrumentID,
pQryTrade->Thost.ExchangeID,
pQryTrade->Thost.TradeID,
pQryTrade->Thost.TradeTimeStart,
pQryTrade->Thost.TradeTimeEnd);
return ret;
}
///请求查询投资者持仓
int CPlatFormService::ReqQryInvestorPosition(PlatformStru_QryInvestorPosition *pQryInvestorPosition, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
CThostFtdcQryInvestorPositionField field;
memset( &field, 0, sizeof(field));
strncpy(field.BrokerID, pQryInvestorPosition->BrokerID,sizeof(field.BrokerID)-1);
strncpy(field.InstrumentID, pQryInvestorPosition->InstrumentID,sizeof(field.InstrumentID)-1);
strncpy(field.InvestorID, pQryInvestorPosition->InvestorID,sizeof(field.InvestorID)-1);
ret = m_pTradeApi->ReqQryInvestorPosition(&field, nRequestID);
if(ret==0)
m_pDataCenter->ClearMapQryRltPositions(std::string(pQryInvestorPosition->InstrumentID));
LOG_INFO("ReqQryInvestorPosition(请求查询投资者持仓):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s]",
ret, nRequestID,
pQryInvestorPosition->BrokerID,
pQryInvestorPosition->InvestorID,
pQryInvestorPosition->InstrumentID);
return ret;
}
///请求查询资金账户
int CPlatFormService::ReqQryTradingAccount(PlatformStru_QryTradingAccount *pQryTradingAccount, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
CThostFtdcQryTradingAccountField QryTradingAccount;
memset(&QryTradingAccount,0,sizeof(QryTradingAccount));
strncpy(QryTradingAccount.BrokerID,pQryTradingAccount->BrokerID,sizeof(QryTradingAccount.BrokerID)-1);
strncpy(QryTradingAccount.InvestorID,pQryTradingAccount->InvestorID,sizeof(QryTradingAccount.InvestorID)-1);
ret = m_pTradeApi->ReqQryTradingAccount(&QryTradingAccount, nRequestID);
LOG_INFO("ReqQryTradingAccount(请求查询资金账户):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s]",
ret, nRequestID,
pQryTradingAccount->BrokerID,
pQryTradingAccount->InvestorID);
return ret;
}
///请求查询投资者
int CPlatFormService::ReqQryInvestor(PlatformStru_QryInvestor *pQryInvestor, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryInvestor->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryInvestor->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pQryInvestor->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryInvestor->Thost.InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryInvestor(&pQryInvestor->Thost, nRequestID);
LOG_INFO("ReqQryInvestor(请求查询投资者):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s]",
ret, nRequestID,
pQryInvestor->Thost.BrokerID,
pQryInvestor->Thost.InvestorID);
return ret;
}
///请求查询交易编码
int CPlatFormService::ReqQryTradingCode(CThostFtdcQryTradingCodeField *pQryTradingCode, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryTradingCode(pQryTradingCode, nRequestID);
return ret;
}
///请求查询合约保证金率
int CPlatFormService::ReqQryInstrumentMarginRate(CThostFtdcQryInstrumentMarginRateField *pQryInstrumentMarginRate, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryInstrumentMarginRate->BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryInstrumentMarginRate->BrokerID)-1); ///经纪公司代码
strncpy(pQryInstrumentMarginRate->InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryInstrumentMarginRate->InvestorID)-1); ///投资者代码
if(pQryInstrumentMarginRate->HedgeFlag==0) pQryInstrumentMarginRate->HedgeFlag=THOST_FTDC_HF_Speculation;
ret = m_pTradeApi->ReqQryInstrumentMarginRate(pQryInstrumentMarginRate, nRequestID);
LOG_INFO("ReqQryInstrumentMarginRate(请求查询合约保证金率):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s],\t HedgeFlag=[%d]",
ret, nRequestID,
pQryInstrumentMarginRate->BrokerID,
pQryInstrumentMarginRate->InvestorID,
pQryInstrumentMarginRate->InstrumentID,
pQryInstrumentMarginRate->HedgeFlag);
return ret;
}
///请求查询合约手续费率
int CPlatFormService::ReqQryInstrumentCommissionRate(CThostFtdcQryInstrumentCommissionRateField *pQryInstrumentCommissionRate, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryInstrumentCommissionRate->BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryInstrumentCommissionRate->BrokerID)-1); ///经纪公司代码
strncpy(pQryInstrumentCommissionRate->InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryInstrumentCommissionRate->InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryInstrumentCommissionRate(pQryInstrumentCommissionRate, nRequestID);
LOG_INFO("ReqQryInstrumentCommissionRate(请求查询合约手续费率):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s]",
ret, nRequestID,
pQryInstrumentCommissionRate->BrokerID,
pQryInstrumentCommissionRate->InvestorID,
pQryInstrumentCommissionRate->InstrumentID);
return ret;
}
#ifdef CTP060300
///请求查询期权合约手续费
int CPlatFormService::ReqQryOptionInstrCommRate(CThostFtdcQryOptionInstrCommRateField *pQryOptionInstrCommRate, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryOptionInstrCommRate->BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryOptionInstrCommRate->BrokerID)-1); ///经纪公司代码
strncpy(pQryOptionInstrCommRate->InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryOptionInstrCommRate->InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryOptionInstrCommRate(pQryOptionInstrCommRate, nRequestID);
LOG_INFO("ReqQryOptionInstrCommRate(请求查询期权合约手续费率):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s]",
ret, nRequestID,
pQryOptionInstrCommRate->BrokerID,
pQryOptionInstrCommRate->InvestorID,
pQryOptionInstrCommRate->InstrumentID);
return ret;
}
///请求查询期权交易成本
int CPlatFormService::ReqQryOptionInstrTradeCost(CThostFtdcQryOptionInstrTradeCostField *pQryOptionInstrTradeCost, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryOptionInstrTradeCost->BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryOptionInstrTradeCost->BrokerID)-1); ///经纪公司代码
strncpy(pQryOptionInstrTradeCost->InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryOptionInstrTradeCost->InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryOptionInstrTradeCost(pQryOptionInstrTradeCost, nRequestID);
LOG_INFO("ReqQryOptionInstrTradeCost(请求查询期权交易成本):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s],\t HedgeFlag=[%d],\t InputPrice=[%g],\t UnderlyingPrice=[%g]",
ret, nRequestID,
pQryOptionInstrTradeCost->BrokerID,
pQryOptionInstrTradeCost->InvestorID,
pQryOptionInstrTradeCost->InstrumentID,
pQryOptionInstrTradeCost->HedgeFlag,
pQryOptionInstrTradeCost->InputPrice,
pQryOptionInstrTradeCost->UnderlyingPrice
);
return ret;
}
#endif
///请求查询交易所
int CPlatFormService::ReqQryExchange(CThostFtdcQryExchangeField *pQryExchange, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryExchange(pQryExchange, nRequestID);
return ret;
}
///请求查询品种
int CPlatFormService::ReqQryProduct(PlatformStru_QryProduct *pQryProduct, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryProduct(&pQryProduct->Thost, nRequestID);
LOG_INFO("ReqQryProduct(请求查询品种):ret=[%d],nRequestID=[%d],\n"
"\t\t\t ProductID=[%s],\t ProductClass=[%d]",
ret, nRequestID,
pQryProduct->Thost.ProductID,
pQryProduct->Thost.ProductClass);
return ret;
}
///请求查询合约
int CPlatFormService::ReqQryInstrument(PlatformStru_QryInstrument *pQryInstrument, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryInstrument(&pQryInstrument->Thost, nRequestID);
LOG_INFO("ReqQryInstrument(请求查询合约):ret=[%d],nRequestID=[%d],\n"
"\t\t\t InstrumentID=[%s],\t ExchangeID=[%s],\t ExchangeInstID=[%s],\tProductID=[%s]",
ret, nRequestID,
pQryInstrument->Thost.InstrumentID,
pQryInstrument->Thost.ExchangeID,
pQryInstrument->Thost.ExchangeInstID,
pQryInstrument->Thost.ProductID);
return ret;
}
///请求查询行情
int CPlatFormService::ReqQryDepthMarketData(PlatformStru_QryDepthMarketData *pQryDepthMarketData, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryDepthMarketData(&(pQryDepthMarketData->Thost), nRequestID);
return ret;
}
///请求查询投资者结算结果
int CPlatFormService::ReqQrySettlementInfo(PlatformStru_QrySettlementInfo *pQrySettlementInfo, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQrySettlementInfo->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQrySettlementInfo->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pQrySettlementInfo->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQrySettlementInfo->Thost.InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqQrySettlementInfo(&pQrySettlementInfo->Thost, nRequestID);
LOG_INFO("ReqQrySettlementInfo(请求查询投资者结算结果):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t TradingDay=[%s]",
ret, nRequestID,
pQrySettlementInfo->Thost.BrokerID,
pQrySettlementInfo->Thost.InvestorID,
pQrySettlementInfo->Thost.TradingDay);
return ret;
}
///请求查询保证金监管系统经纪公司资金账户密钥
int CPlatFormService::ReqQryCFMMCTradingAccountKey(PlatformStru_QryCFMMCTradingAccountKey *pQryCFMMCTradingAccountKey, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
memset(pQryCFMMCTradingAccountKey,0,sizeof(PlatformStru_QryCFMMCTradingAccountKey));
strncpy(pQryCFMMCTradingAccountKey->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryCFMMCTradingAccountKey->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pQryCFMMCTradingAccountKey->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryCFMMCTradingAccountKey->Thost.InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryCFMMCTradingAccountKey(&pQryCFMMCTradingAccountKey->Thost, nRequestID);
LOG_INFO("ReqQryCFMMCTradingAccountKey(请求查询保证金监管系统经纪公司资金账户密钥):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s]",
ret, nRequestID,
pQryCFMMCTradingAccountKey->Thost.BrokerID,
pQryCFMMCTradingAccountKey->Thost.InvestorID);
return ret;
}
///请求查询转帐银行
int CPlatFormService::ReqQryTransferBank(PlatformStru_QryTransferBank *pQryTransferBank, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryTransferBank(&pQryTransferBank->Thost, nRequestID);
return ret;
}
///请求查询投资者持仓明细
int CPlatFormService::ReqQryInvestorPositionDetail(PlatformStru_QryInvestorPositionDetail *pQryInvestorPositionDetail, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
CThostFtdcQryInvestorPositionDetailField QryInvestorPositionDetail;
memset(&QryInvestorPositionDetail,0,sizeof(QryInvestorPositionDetail));
strncpy(QryInvestorPositionDetail.BrokerID,pQryInvestorPositionDetail->BrokerID,sizeof(QryInvestorPositionDetail.BrokerID)-1);
strncpy(QryInvestorPositionDetail.InvestorID,pQryInvestorPositionDetail->InvestorID,sizeof(QryInvestorPositionDetail.InvestorID)-1);
strncpy(QryInvestorPositionDetail.InstrumentID,pQryInvestorPositionDetail->InstrumentID,sizeof(QryInvestorPositionDetail.InstrumentID)-1);
ret = m_pTradeApi->ReqQryInvestorPositionDetail(&QryInvestorPositionDetail, nRequestID);
if(ret==0)
m_pDataCenter->ClearMapQryRltPositionDetails(std::string(pQryInvestorPositionDetail->InstrumentID));
LOG_INFO("ReqQryInvestorPositionDetail(请求查询投资者持仓明细):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s]",
ret, nRequestID,
pQryInvestorPositionDetail->BrokerID,
pQryInvestorPositionDetail->InvestorID,
pQryInvestorPositionDetail->InstrumentID);
return ret;
}
///请求查询客户通知
int CPlatFormService::ReqQryNotice(PlatformStru_QryNotice *pQryNotice, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryNotice(&pQryNotice->Thost, nRequestID);
return ret;
}
///请求查询结算信息确认
int CPlatFormService::ReqQrySettlementInfoConfirm(PlatformStru_QrySettlementInfoConfirm *pQrySettlementInfoConfirm, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQrySettlementInfoConfirm(&pQrySettlementInfoConfirm->Thost, nRequestID);
LOG_INFO("ReqQrySettlementInfoConfirm(请求查询结算信息确认):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s]",
ret, nRequestID,
pQrySettlementInfoConfirm->Thost.BrokerID,
pQrySettlementInfoConfirm->Thost.InvestorID);
return ret;
}
///请求查询投资者持仓明细
int CPlatFormService::ReqQryInvestorPositionCombineDetail(PlatformStru_QryInvestorPositionCombineDetail *pQryInvestorPositionCombineDetail, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
CThostFtdcQryInvestorPositionCombineDetailField QryInvestorPositionCombineDetail;
memset(&QryInvestorPositionCombineDetail,0,sizeof(QryInvestorPositionCombineDetail));
strncpy(QryInvestorPositionCombineDetail.BrokerID,pQryInvestorPositionCombineDetail->BrokerID,sizeof(QryInvestorPositionCombineDetail.BrokerID)-1);
strncpy(QryInvestorPositionCombineDetail.InvestorID,pQryInvestorPositionCombineDetail->InvestorID,sizeof(QryInvestorPositionCombineDetail.InvestorID)-1);
strncpy(QryInvestorPositionCombineDetail.CombInstrumentID,pQryInvestorPositionCombineDetail->CombInstrumentID,sizeof(QryInvestorPositionCombineDetail.CombInstrumentID)-1);
ret = m_pTradeApi->ReqQryInvestorPositionCombineDetail(&QryInvestorPositionCombineDetail, nRequestID);
if(ret==0)
m_pDataCenter->ClearMapQryRltPositionDetailComb(std::string(pQryInvestorPositionCombineDetail->CombInstrumentID));
LOG_INFO("ReqQryInvestorPositionCombineDetail(请求查询投资者组合持仓明细):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t CombInstrumentID=[%s]",
ret, nRequestID,
pQryInvestorPositionCombineDetail->BrokerID,
pQryInvestorPositionCombineDetail->InvestorID,
pQryInvestorPositionCombineDetail->CombInstrumentID);
return ret;
}
///请求查询转帐流水
int CPlatFormService::ReqQryTransferSerial(PlatformStru_QryTransferSerial *pQryTransferSerial, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryTransferSerial->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryTransferSerial->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pQryTransferSerial->Thost.AccountID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryTransferSerial->Thost.AccountID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryTransferSerial(&pQryTransferSerial->Thost, nRequestID);
LOG_INFO("ReqQryTransferSerial(请求查询转帐流水) : ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t AccountID=[%s],\t BankID=[%s]",
ret,nRequestID,
pQryTransferSerial->Thost.BrokerID,
pQryTransferSerial->Thost.AccountID,
pQryTransferSerial->Thost.BankID);
return ret;
}
///请求查询签约银行
int CPlatFormService::ReqQryContractBank(PlatformStru_QryContractBank *pQryContractBank, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryContractBank->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryContractBank->Thost.BrokerID)-1); ///经纪公司代码
ret = m_pTradeApi->ReqQryContractBank(&pQryContractBank->Thost, nRequestID);
LOG_INFO("ReqQryContractBank(请求查询签约银行) : ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t BankID=[%s],\t BankBrchID=[%s]",
ret,nRequestID,
pQryContractBank->Thost.BrokerID,
pQryContractBank->Thost.BankID,
pQryContractBank->Thost.BankBrchID);
return ret;
}
///请求查询银期签约关系
int CPlatFormService::ReqQryAccountregister(PlatformStru_QryAccountRegister *pQryAccountregister, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryAccountregister->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryAccountregister->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pQryAccountregister->Thost.AccountID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryAccountregister->Thost.AccountID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryAccountregister(&pQryAccountregister->Thost, nRequestID);
LOG_INFO("ReqQryAccountregister(请求查询银期签约关系) : ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t AccountID=[%s],\t BankID=[%s]",
ret,nRequestID,
pQryAccountregister->Thost.BrokerID,
pQryAccountregister->Thost.AccountID,
pQryAccountregister->Thost.BankID);
return ret;
}
///请求查询汇率
int CPlatFormService::ReqQryExchangeRate(PlatformStru_QryExchangeRate *pQryExchangeRate, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryExchangeRate->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryExchangeRate->Thost.BrokerID)-1); ///经纪公司代码
ret = m_pTradeApi->ReqQryExchangeRate((CThostFtdcQryExchangeRateField *)&pQryExchangeRate->Thost, nRequestID);
LOG_INFO("ReqQryExchangeRate(请求查询汇率) : ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t FromCurrencyID=[%s],\t ToCurrencyID=[%s]",
ret,nRequestID,
pQryExchangeRate->Thost.BrokerID,
pQryExchangeRate->Thost.FromCurrencyID,
pQryExchangeRate->Thost.ToCurrencyID);
return ret;
}
///请求查询预埋单
int CPlatFormService::ReqQryParkedOrder(PlatformStru_QryParkedOrder *pQryParkedOrder, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryParkedOrder->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryParkedOrder->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pQryParkedOrder->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryParkedOrder->Thost.InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryParkedOrder(&pQryParkedOrder->Thost, nRequestID);
LOG_INFO("ReqQryParkedOrder(请求查询预埋单):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s],\t ExchangeID=[%s]",
ret, nRequestID,
pQryParkedOrder->Thost.BrokerID,
pQryParkedOrder->Thost.InvestorID,
pQryParkedOrder->Thost.InstrumentID,
pQryParkedOrder->Thost.ExchangeID);
return ret;
}
///请求查询预埋撤单
int CPlatFormService::ReqQryParkedOrderAction(PlatformStru_QryParkedOrderAction *pQryParkedOrderAction, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pQryParkedOrderAction->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pQryParkedOrderAction->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pQryParkedOrderAction->Thost.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(pQryParkedOrderAction->Thost.InvestorID)-1); ///投资者代码
ret = m_pTradeApi->ReqQryParkedOrderAction(&pQryParkedOrderAction->Thost, nRequestID);
LOG_INFO("ReqQryParkedOrderAction(请求查询预埋撤单):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],\t InvestorID=[%s],\t InstrumentID=[%s],\t ExchangeID=[%s]",
ret, nRequestID,
pQryParkedOrderAction->Thost.BrokerID,
pQryParkedOrderAction->Thost.InvestorID,
pQryParkedOrderAction->Thost.InstrumentID,
pQryParkedOrderAction->Thost.ExchangeID);
return ret;
}
///请求查询交易通知
int CPlatFormService::ReqQryTradingNotice(CThostFtdcQryTradingNoticeField *pQryTradingNotice, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryTradingNotice(pQryTradingNotice, nRequestID);
return ret;
}
///请求查询经纪公司交易参数
int CPlatFormService::ReqQryBrokerTradingParams(CThostFtdcQryBrokerTradingParamsField *pQryBrokerTradingParams, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryBrokerTradingParams(pQryBrokerTradingParams, nRequestID);
return ret;
}
///请求查询经纪公司交易算法
int CPlatFormService::ReqQryBrokerTradingAlgos(CThostFtdcQryBrokerTradingAlgosField *pQryBrokerTradingAlgos, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqQryBrokerTradingAlgos(pQryBrokerTradingAlgos, nRequestID);
return ret;
}
///期货发起银行资金转期货请求
int CPlatFormService::ReqFromBankToFutureByFuture(PlatformStru_ReqTransfer *pReqTransfer, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pReqTransfer->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pReqTransfer->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pReqTransfer->Thost.AccountID, m_PlatformParam.InvestorID.c_str(), sizeof(pReqTransfer->Thost.AccountID)-1); ///投资者代码
ret = m_pTradeApi->ReqFromBankToFutureByFuture(&pReqTransfer->Thost, nRequestID);
//LOG_INFO("ReqFromBankToFutureByFuture(期货发起银行资金转期货请求) : ret=[%d],nRequestID=[%d],\n"
// "\t\t\t TradeCode=[%s],\t BankID=[%s],\t BankBranchID=[%s],\t BrokerID=[%s],\t BrokerBranchID=[%s],\n"
// "\t\t\t TradeDate=[%s],\t TradeTime=[%s],\t BankSerial=[%s],\t TradingDay=[%s],\t PlateSerial=[%d],\n"
// "\t\t\t LastFragment=[%d],\t SessionID=[%#x],\t CustomerName=[%s],\t IdCardType=[%d],\t IdentifiedCardNo=[%s],\n"
// "\t\t\t CustType=[%d],\t BankAccount=[%s],\t BankPassWord=[%s],\t AccountID=[%s],\t Password=[%s],\n"
// "\t\t\t InstallID=[%d],\t FutureSerial=[%d],\t UserID=[%s],\t VerifyCertNoFlag=[%d],CurrencyID=[%s],\n"
// "\t\t\t TradeAmount=[%g],\t FutureFetchAmount=[%g],\t FeePayFlag=[%d],\t CustFee=[%g],BrokerFee=[%g],\n"
// "\t\t\t Message=[%s],\t Digest=[%s],\t BankAccType=[%d],\t DeviceID=[%s],\t BankSecuAccType=[%d],\n"
// "\t\t\t BrokerIDByBank=[%s],\t BankSecuAcc=[%s],\t BankPwdFlag=[%d],\t SecuPwdFlag=[%d],\t OperNo=[%s],\n"
// "\t\t\t RequestID=[%d],\t TID=[%d],\t TransferStatus=[d]",
// ret,nRequestID,
// pReqTransfer->Thost.TradeCode, pReqTransfer->Thost.BankID,pReqTransfer->Thost.BankBranchID,pReqTransfer->Thost.BrokerID,pReqTransfer->Thost.BrokerBranchID,
// pReqTransfer->Thost.TradeDate, pReqTransfer->Thost.TradeTime,pReqTransfer->Thost.BankSerial,pReqTransfer->Thost.TradingDay,pReqTransfer->Thost.PlateSerial,
// pReqTransfer->Thost.LastFragment, pReqTransfer->Thost.SessionID,pReqTransfer->Thost.CustomerName,pReqTransfer->Thost.IdCardType,pReqTransfer->Thost.IdentifiedCardNo,
// pReqTransfer->Thost.CustType, pReqTransfer->Thost.BankAccount,pReqTransfer->Thost.BankPassWord,pReqTransfer->Thost.AccountID,pReqTransfer->Thost.Password,
// pReqTransfer->Thost.InstallID,pReqTransfer->Thost.FutureSerial, pReqTransfer->Thost.UserID,pReqTransfer->Thost.VerifyCertNoFlag,pReqTransfer->Thost.CurrencyID,
// pReqTransfer->Thost.TradeAmount,pReqTransfer->Thost.FutureFetchAmount, pReqTransfer->Thost.FeePayFlag,pReqTransfer->Thost.CustFee,pReqTransfer->Thost.BrokerFee,
// pReqTransfer->Thost.Message, pReqTransfer->Thost.Digest, pReqTransfer->Thost.BankAccType,pReqTransfer->Thost.DeviceID,pReqTransfer->Thost.BankSecuAccType,
// pReqTransfer->Thost.BrokerIDByBank, pReqTransfer->Thost.BankSecuAcc, pReqTransfer->Thost.BankPwdFlag,pReqTransfer->Thost.SecuPwdFlag,pReqTransfer->Thost.OperNo,
// pReqTransfer->Thost.RequestID, pReqTransfer->Thost.TID, pReqTransfer->Thost.TransferStatus
// );
return ret;
}
///期货发起期货资金转银行请求
int CPlatFormService::ReqFromFutureToBankByFuture(PlatformStru_ReqTransfer *pReqTransfer, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pReqTransfer->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pReqTransfer->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pReqTransfer->Thost.AccountID, m_PlatformParam.InvestorID.c_str(), sizeof(pReqTransfer->Thost.AccountID)-1); ///投资者代码
ret = m_pTradeApi->ReqFromFutureToBankByFuture(&pReqTransfer->Thost, nRequestID);
//LOG_INFO("ReqFromFutureToBankByFuture(期货发起期货资金转银行请求) : ret=[%d],nRequestID=[%d],\n"
// "\t\t\t TradeCode=[%s],\t BankID=[%s],\t BankBranchID=[%s],\t BrokerID=[%s],\t BrokerBranchID=[%s],\n"
// "\t\t\t TradeDate=[%s],\t TradeTime=[%s],\t BankSerial=[%s],\t TradingDay=[%s],\t PlateSerial=[%d],\n"
// "\t\t\t LastFragment=[%d],\t SessionID=[%#x],\t CustomerName=[%s],\t IdCardType=[%d],\t IdentifiedCardNo=[%s],\n"
// "\t\t\t CustType=[%d],\t BankAccount=[%s],\t BankPassWord=[%s],\t AccountID=[%s],\t Password=[%s],\n"
// "\t\t\t InstallID=[%d],\t FutureSerial=[%d],\t UserID=[%s],\t VerifyCertNoFlag=[%d],CurrencyID=[%s],\n"
// "\t\t\t TradeAmount=[%g],\t FutureFetchAmount=[%g],\t FeePayFlag=[%d],\t CustFee=[%g],BrokerFee=[%g],\n"
// "\t\t\t Message=[%s],\t Digest=[%s],\t BankAccType=[%d],\t DeviceID=[%s],\t BankSecuAccType=[%d],\n"
// "\t\t\t BrokerIDByBank=[%s],\t BankSecuAcc=[%s],\t BankPwdFlag=[%d],\t SecuPwdFlag=[%d],\t OperNo=[%s],\n"
// "\t\t\t RequestID=[%d],\t TID=[%d],\t TransferStatus=[d]",
// ret,nRequestID,
// pReqTransfer->Thost.TradeCode, pReqTransfer->Thost.BankID,pReqTransfer->Thost.BankBranchID,pReqTransfer->Thost.BrokerID,pReqTransfer->Thost.BrokerBranchID,
// pReqTransfer->Thost.TradeDate, pReqTransfer->Thost.TradeTime,pReqTransfer->Thost.BankSerial,pReqTransfer->Thost.TradingDay,pReqTransfer->Thost.PlateSerial,
// pReqTransfer->Thost.LastFragment, pReqTransfer->Thost.SessionID,pReqTransfer->Thost.CustomerName,pReqTransfer->Thost.IdCardType,pReqTransfer->Thost.IdentifiedCardNo,
// pReqTransfer->Thost.CustType, pReqTransfer->Thost.BankAccount,pReqTransfer->Thost.BankPassWord,pReqTransfer->Thost.AccountID,pReqTransfer->Thost.Password,
// pReqTransfer->Thost.InstallID,pReqTransfer->Thost.FutureSerial, pReqTransfer->Thost.UserID,pReqTransfer->Thost.VerifyCertNoFlag,pReqTransfer->Thost.CurrencyID,
// pReqTransfer->Thost.TradeAmount,pReqTransfer->Thost.FutureFetchAmount, pReqTransfer->Thost.FeePayFlag,pReqTransfer->Thost.CustFee,pReqTransfer->Thost.BrokerFee,
// pReqTransfer->Thost.Message, pReqTransfer->Thost.Digest, pReqTransfer->Thost.BankAccType,pReqTransfer->Thost.DeviceID,pReqTransfer->Thost.BankSecuAccType,
// pReqTransfer->Thost.BrokerIDByBank, pReqTransfer->Thost.BankSecuAcc, pReqTransfer->Thost.BankPwdFlag,pReqTransfer->Thost.SecuPwdFlag,pReqTransfer->Thost.OperNo,
// pReqTransfer->Thost.RequestID, pReqTransfer->Thost.TID, pReqTransfer->Thost.TransferStatus
// );
return ret;
}
///期货发起查询银行余额请求
int CPlatFormService::ReqQueryBankAccountMoneyByFuture(PlatformStru_ReqQueryAccount *pReqQueryAccount, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
strncpy(pReqQueryAccount->Thost.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(pReqQueryAccount->Thost.BrokerID)-1); ///经纪公司代码
strncpy(pReqQueryAccount->Thost.AccountID, m_PlatformParam.InvestorID.c_str(), sizeof(pReqQueryAccount->Thost.AccountID)-1); ///投资者代码
ret = m_pTradeApi->ReqQueryBankAccountMoneyByFuture(&pReqQueryAccount->Thost, nRequestID);
LOG_INFO("ReqQueryBankAccountMoneyByFuture(期货发起查询银行余额请求) : ret=[%d],nRequestID=[%d],\n"
"\t\t\t TradeCode=[%s],\t BankID=[%s],\t BankBranchID=[%s],\t BrokerID=[%s],\t BrokerBranchID=[%s],\n"
"\t\t\t TradeDate=[%s],\t TradeTime=[%s],\t BankSerial=[%s],\t TradingDay=[%s],\t PlateSerial=[%d],\n"
"\t\t\t LastFragment=[%d],\t SessionID=[%#x],\t CustomerName=[%s],\t IdCardType=[%d],\t IdentifiedCardNo=[%s],\n"
"\t\t\t CustType=[%d],\t BankAccount=[%s],\t BankPassWord=[******],\t AccountID=[%s],\t Password=[******],\n"
"\t\t\t FutureSerial=[%d],\t InstallID=[%d],\t UserID=[%s],\t VerifyCertNoFlag=[%d],CurrencyID=[%s],\n"
"\t\t\t Digest=[%s],\t BankAccType=[%d],\t DeviceID=[%s],\t BankSecuAccType=[%d],BrokerIDByBank=[%s],\n"
"\t\t\t BankSecuAcc=[%s],\t BankPwdFlag=[%d],\t SecuPwdFlag=[%d],\t OperNo=[%s],RequestID=[%d],\n"
"\t\t\t TID=[%d]",
ret,nRequestID,
pReqQueryAccount->Thost.TradeCode, pReqQueryAccount->Thost.BankID,pReqQueryAccount->Thost.BankBranchID,pReqQueryAccount->Thost.BrokerID,pReqQueryAccount->Thost.BrokerBranchID,
pReqQueryAccount->Thost.TradeDate, pReqQueryAccount->Thost.TradeTime,pReqQueryAccount->Thost.BankSerial,pReqQueryAccount->Thost.TradingDay,pReqQueryAccount->Thost.PlateSerial,
pReqQueryAccount->Thost.LastFragment, pReqQueryAccount->Thost.SessionID,pReqQueryAccount->Thost.CustomerName,pReqQueryAccount->Thost.IdCardType,pReqQueryAccount->Thost.IdentifiedCardNo,
pReqQueryAccount->Thost.CustType, pReqQueryAccount->Thost.BankAccount,pReqQueryAccount->Thost.AccountID,
pReqQueryAccount->Thost.FutureSerial, pReqQueryAccount->Thost.InstallID,pReqQueryAccount->Thost.UserID,pReqQueryAccount->Thost.VerifyCertNoFlag,pReqQueryAccount->Thost.CurrencyID,
pReqQueryAccount->Thost.Digest, pReqQueryAccount->Thost.BankAccType,pReqQueryAccount->Thost.DeviceID,pReqQueryAccount->Thost.BankSecuAccType,pReqQueryAccount->Thost.BrokerIDByBank,
pReqQueryAccount->Thost.BankSecuAcc, pReqQueryAccount->Thost.BankPwdFlag,pReqQueryAccount->Thost.SecuPwdFlag,pReqQueryAccount->Thost.OperNo,pReqQueryAccount->Thost.RequestID,
pReqQueryAccount->Thost.TID
);
return ret;
}
int CPlatFormService::SubscribeMarketData(const std::string& InstrumentID)
{
int ret = -999;
if(InstrumentID.empty() ||
!m_pQuotApi ||
m_PlatformParam.QuotStatus!=CTPCONNSTATUS_Connected)
{
LOG_INFO("行情API还未准备就绪, 可能登入未成功或正在重连");
return ret;
}
bool bsub=false;
EnterCriticalSection(&m_CS);
if(m_MarketDataInstrumentID.find(InstrumentID)==m_MarketDataInstrumentID.end())
{
bsub=true;
m_MarketDataInstrumentID.insert(InstrumentID);
}
LeaveCriticalSection(&m_CS);
if(bsub)
{
char *pInstrumentID = const_cast<char*>(InstrumentID.c_str());
ret=m_pQuotApi->SubscribeMarketData(&pInstrumentID, 1);
LOG_INFO("SubscribeMarketData(定制指定合约行情):ret=[%d],InstrumentID=[%s]",
ret, pInstrumentID);
}
return ret;
}
int CPlatFormService::UnSubscribeMarketData(const std::string& InstrumentID)
{
int ret = -999;
if(InstrumentID.empty() ||
!m_pQuotApi ||
m_PlatformParam.QuotStatus!=CTPCONNSTATUS_Connected)
{
LOG_INFO("行情API还未准备就绪, 可能登入未成功或正在重连");
return ret;
}
bool bunsub=false;
EnterCriticalSection(&m_CS);
std::set<std::string>::iterator iter=m_MarketDataInstrumentID.find(InstrumentID);
if(iter!=m_MarketDataInstrumentID.end())
{
bunsub=true;
m_MarketDataInstrumentID.erase(iter);
}
LeaveCriticalSection(&m_CS);
if(bunsub)
{
char *pInstrumentID = const_cast<char*>(InstrumentID.c_str());
ret=m_pQuotApi->UnSubscribeMarketData(&pInstrumentID, 1);
LOG_INFO("UnSubscribeMarketData(取消指定合约行情):ret=[%d],InstrumentID=[%s]",
ret, pInstrumentID);
}
return ret;
}
void CPlatFormService::GetMarketDataInstrumentID(std::set<std::string>& setMarketDataInstrumentID)
{
EnterCriticalSection(&m_CS);
setMarketDataInstrumentID=m_MarketDataInstrumentID;
LeaveCriticalSection(&m_CS);
}
//admin API
int CPlatFormService::LoginTrade(const std::string& InvestorID, const std::string& InvestorPW, const std::string& InvestorNewPwd)
{
LOG_INFO("LoginTrade:InvestorID=[%s],InvestorPW=[******]", InvestorID.c_str());
if(InvestorID.empty() ||
/*InvestorPW.empty() ||*/
m_PlatformParam.BrokerID.empty() ||
m_PlatformParam.UserID.empty()/* ||
m_PlatformParam.UserPW.empty()*/)
{
LOG_INFO("LoginTrade:参数未配置完整");
return -1;
}
if(CTPCONNSTATUS_Connected==m_PlatformParam.TradeStatus)
{
LOG_INFO("LoginTrade:已经登入");
return 0;//已经登入
}
if(CTPCONNSTATUS_Logining==m_PlatformParam.TradeStatus ||
CTPCONNSTATUS_Connecting==m_PlatformParam.TradeStatus
||CTPCONNSTATUS_TradeSettlementInfoConfirming==m_PlatformParam.TradeStatus)
{
LOG_INFO("LoginTrade:正在登入中");
return -2;//正在登入中
}
LogoutTrade();
m_PlatformParam.TradeStatus = CTPCONNSTATUS_Connecting;//正在连接
m_PlatformParam.InvestorID = InvestorID;
m_PlatformParam.InvestorPW = InvestorPW;
//std::map<std::string, int>::iterator it = g_allPlatformID.find(m_PlatformParam.UserID);
//if ( it != g_allPlatformID.end() )
//{
// m_PlatformParam.PlatFormID = it->second;
//}
//else
//{
// m_PlatformParam.PlatFormID = 0;
//}
m_pDataCenter->m_LoginInvestorID=InvestorID;
m_pTradeApi = CThostFtdcTraderApi::CreateFtdcTraderApi();
m_pTradeSpi = new CTraderSpi(*this);
m_pTradeApi->RegisterSpi(static_cast<CThostFtdcTraderSpi*>(m_pTradeSpi));
m_pTradeWorkThread = new CTradeThread(*this);
if(m_pTradeWorkThread->Create(512*1024) != wxTHREAD_NO_ERROR)
LOG_INFO("LoginTrade:创建交易工作线程失败!");
else
LOG_INFO("LoginTrade:创建交易工作线程成功!");
if(m_pTradeWorkThread->Run() != wxTHREAD_NO_ERROR)
{
LOG_INFO("LoginTrade:运行交易工作线程失败!");
return -3;
}
else
{
LOG_INFO("LoginTrade:运行交易工作线程成功!");
}
return 0;
}
int CPlatFormService::LoginQuot(const std::string& InvestorID, const std::string& InvestorPW)
{
LOG_INFO("LoginQuot:InvestorID=[%s],InvestorPW=[******]", InvestorID.c_str());
if(InvestorID.empty() ||
/*InvestorPW.empty() ||*/
m_PlatformParam.BrokerID.empty() ||
m_PlatformParam.UserID.empty()/* ||
m_PlatformParam.UserPW.empty()*/)
{
LOG_INFO("LoginQuot:参数未配置完整");
return -1;
}
if(CTPCONNSTATUS_Connected==m_PlatformParam.QuotStatus)
{
LOG_INFO("LoginQuot:已经登入");
return 0;//已经登入
}
if(CTPCONNSTATUS_Logining==m_PlatformParam.QuotStatus ||
CTPCONNSTATUS_Connecting==m_PlatformParam.QuotStatus )
{
LOG_INFO("LoginQuot:正在登入中");
return -2;//正在登入中
}
LogoutQuot();
m_PlatformParam.QuotStatus = CTPCONNSTATUS_Connecting;//正在连接
//m_PlatformParam.InvestorID = InvestorID;
//m_PlatformParam.InvestorPW = InvestorPW;
m_pQuotApi = CThostFtdcMdApi::CreateFtdcMdApi();
m_pQuotSpi = new CQuotSpi(*this);
m_pQuotApi->RegisterSpi(static_cast<CThostFtdcMdSpi*>(m_pQuotSpi));
m_pQuotWorkThread = new CQuotThread(*this);
if(m_pQuotWorkThread->Create(512*1024) != wxTHREAD_NO_ERROR)
LOG_INFO("LoginQuot:创建行情工作线程失败!");
else
LOG_INFO("LoginQuot:创建行情工作线程成功!");
if(m_pQuotWorkThread->Run() != wxTHREAD_NO_ERROR)
{
LOG_INFO("LoginQuot:运行行情工作线程失败!");
return -3;
}
else
{
LOG_INFO("LoginQuot:运行行情工作线程成功!");
}
return 0;
}
void CPlatFormService::StopThreads(void)
{
if(m_pDataCenter)
m_pDataCenter->Stop();
if(m_pTradeApi)
{
LOG_INFO("开始关闭交易API");
m_PlatformParam.TradeStatus = CTPCONNSTATUS_Disconnecting;
m_pTradeApi->RegisterSpi(NULL);
m_pTradeApi->Release();
m_PlatformParam.TradeStatus = CTPCONNSTATUS_Disconnected;
m_pTradeApi=NULL;
LOG_INFO("完成关闭交易API");
}
if(m_pTradeWorkThread)
{
LOG_INFO("开始关闭交易工作线程");
m_pTradeWorkThread->Delete();
m_pTradeWorkThread=NULL;
LOG_INFO("完成关闭交易工作线程");
}
if(m_pQuotApi)
{
LOG_INFO("开始关闭行情API");
m_PlatformParam.QuotStatus = CTPCONNSTATUS_Disconnecting;
m_pQuotApi->RegisterSpi(NULL);
m_pQuotApi->Release();
m_PlatformParam.QuotStatus = CTPCONNSTATUS_Disconnected;
m_pQuotApi=NULL;
LOG_INFO("完成关闭行情API");
}
if(m_pQuotWorkThread)
{
LOG_INFO("开始关闭行情工作线程");
m_pQuotWorkThread->Delete();
m_pQuotWorkThread=NULL;
LOG_INFO("完成关闭行情工作线程");
}
}
int CPlatFormService::LogoutTrade()
{
//LOG_INFO("LogoutTrade");
if(m_pTradeApi)
{
LOG_INFO("LogoutTrade:关闭交易API");
m_PlatformParam.TradeStatus = CTPCONNSTATUS_Disconnecting;
m_pTradeApi->Release();
m_PlatformParam.TradeStatus = CTPCONNSTATUS_Disconnected;
m_pTradeApi=NULL;
}
if(m_pTradeWorkThread)
{
m_pTradeWorkThread->Delete();
//m_pTradeWorkThread=NULL; //will be set NULL in calling CTradeThread::OnExit()
LOG_INFO("LogoutTrade:关闭交易工作线程");
}
if(m_pTradeSpi)
{
delete m_pTradeSpi;
m_pTradeSpi=NULL;
}
return 0;
}
int CPlatFormService::LogoutQuot()
{
LOG_INFO("LogoutQuot");
if(m_pQuotApi)
{
LOG_INFO("LogoutQuot:关闭行情API");
m_PlatformParam.QuotStatus = CTPCONNSTATUS_Disconnecting;
m_pQuotApi->Release();
m_PlatformParam.QuotStatus = CTPCONNSTATUS_Disconnected;
m_pQuotApi=NULL;
}
if(m_pQuotWorkThread)
{
m_pQuotWorkThread->Delete();
//m_pQuotWorkThread=NULL; //will be set NULL in calling CQuotThread::OnExit()
LOG_INFO("LogoutQuot:关闭行情工作线程");
}
if(m_pQuotSpi)
{
delete m_pQuotSpi;
m_pQuotSpi=NULL;
}
return 0;
}
///密码是否是当前密码
bool CPlatFormService::IsValidInvestorPW(const string& yourPW)
{
return m_PlatformParam.InvestorPW==yourPW ? true : false;
}
bool CPlatFormService::IsValidUserPW(const string& yourPW)
{
return m_PlatformParam.UserPW==yourPW ? true : false;
}
int CPlatFormService::GetBrokerIDUserID(std::string& UserID, std::string& BrokerID,set<string>* accounts)
{
BrokerID=m_PlatformParam.BrokerID;
UserID=m_PlatformParam.UserID;
return 0;
}
int CPlatFormService::SetTradeFrontAddrs(const std::vector<std::string>& TradeAddr)
{
m_PlatformParam.TradeFrontAddrs=TradeAddr;
return 0;
}
int CPlatFormService::SetProxyParam(const Stru_ProxyServerParam& ProxyParam)
{
m_PlatformParam.ProxyParam = ProxyParam;
return 0;
}
int CPlatFormService::SetQuotFrontAddrs(const std::vector<std::string>& QuotAddr)
{
m_PlatformParam.QuotFrontAddrs=QuotAddr;
return 0;
}
int CPlatFormService::SetParticipantInfo(const std::string& BrokerID, const std::string& UserID, const std::string& UserPW, const std::string& OneTimePassword)
{
m_PlatformParam.BrokerID = BrokerID;
m_PlatformParam.UserID = UserID;
m_PlatformParam.UserPW = UserPW;
m_PlatformParam.OneTimePassword=OneTimePassword;
return 0;
}
CPlatFormService::CPlatFormService(CServiceProxy& rServiceProxy)
: m_pWriteLog(NULL)
,m_pTradeApi(NULL)
,m_pTradeSpi(NULL)
,m_pQuotApi(NULL)
,m_pQuotSpi(NULL)
,m_pTradeWorkThread(NULL)
,m_pQuotWorkThread(NULL)
,m_PCache(NULL)
,m_pDataCenter(NULL)
,m_CurOrderRef(0)
,m_CurForQuoteRef(0)
,m_CurExecOrderRef(0)
,m_CurExecOrderActionRef(0)
,m_status(0)
,m_nOrderReqID(0)
,m_bSettlementInfoConfirmed(false)
,m_bInQry(false)
,m_rServiceProxy(rServiceProxy)
{
InitializeCriticalSection(&m_CS);
m_pWriteLog = new zqWriteLog();
m_PCache = new CPackageCache((!IS_MULTIACCOUNT_VERSION?(40*1024*1024):(20*1024*1024)), 1);
m_pDataCenter = new CDataCenter(*m_PCache,this,rServiceProxy.m_PlatformID,rServiceProxy.m_MaxPlatformID);
m_pDataCenter->Start();
m_pTradeApi=NULL;
m_pTradeSpi=NULL;
m_pQuotApi=NULL;
m_pQuotSpi=NULL;
m_pTradeWorkThread=NULL;
m_pQuotWorkThread=NULL;
m_bSettlementInfoConfirmed=false;
memset(&m_ErrorInfoField,0,sizeof(m_ErrorInfoField));
m_nOrderReqID = 0;
}
CPlatFormService::~CPlatFormService()
{
LogoutTrade();
LogoutQuot();
if(m_pDataCenter)
{
m_pDataCenter->Stop();
delete m_pDataCenter;
m_pDataCenter = NULL;
}
if(m_PCache)
{
delete m_PCache;
m_PCache=NULL;
}
if(m_pWriteLog)
{
LOG_INFO("CPlatFormService::~CPlatFormService(析构CPlatFormService对象)");
delete m_pWriteLog;
m_pWriteLog=NULL;
}
DeleteCriticalSection(&m_CS);
}
///用户登录请求
int CPlatFormService::ReqUserLogin(CThostFtdcReqUserLoginField *pReqUserLoginField, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqUserLogin(pReqUserLoginField, nRequestID);
LOG_INFO("ReqUserLogin(用户登录请求):ret=[%d],nRequestID=[%d],\n"
"\t\t\t TradingDay=[%s],\t BrokerID=[%s],\t UserID=[%s],\t Password=[******],\t UserProductInfo=[%s],\n"
"\t\t\t InterfaceProductInfo=[%s],\t ProtocolInfo=[%s]",
ret, nRequestID,
pReqUserLoginField->TradingDay,
pReqUserLoginField->BrokerID,
pReqUserLoginField->UserID,
/*pReqUserLoginField->Password,*/
pReqUserLoginField->UserProductInfo,
pReqUserLoginField->InterfaceProductInfo,
pReqUserLoginField->ProtocolInfo);
return ret;
}
///登出请求
int CPlatFormService::ReqUserLogout(CThostFtdcUserLogoutField *pUserLogout, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
ret = m_pTradeApi->ReqUserLogout(pUserLogout, nRequestID);
LOG_INFO("ReqUserLogout(登出请求):ret=[%d],nRequestID=[%d],\n"
"\t\t\t BrokerID=[%s],UserID=[%s]",
ret, nRequestID,
pUserLogout->BrokerID,
pUserLogout->UserID);
return ret;
}
///定制业务数据
int CPlatFormService::SubscribeBusinessData(BusinessID BID, GUIModuleID GID, GuiCallBackFunc callback, bool sendCurrentInfo)
{
return m_pDataCenter->SubscribeBusinessData(BID, GID, callback, sendCurrentInfo);
}
///取消业务数据的定制
int CPlatFormService::UnSubscribeBusinessData(BusinessID BID, GUIModuleID GID)
{
return m_pDataCenter->UnSubscribeBusinessData(BID, GID);
}
///获取合约列表
int CPlatFormService::GetInstrumentList(std::vector<InstrumentGroupInfo> &outData)
{
int irlt=m_pDataCenter->GetInstrumentList(outData);
return irlt==0?-1:irlt;
}
///获取合约列表
int CPlatFormService::GetInstrumentList(std::set<std::string> &outData,std::string ExchangeID)
{
int irlt=m_pDataCenter->GetInstrumentList(outData,ExchangeID);
return irlt==0?-1:irlt;
}
int CPlatFormService::GetInstrumentList(vector<string> &outData,string ExchangeID)
{
int irlt=m_pDataCenter->GetInstrumentList(outData,ExchangeID);
return irlt==0?-1:irlt;
}
//添加主力合约列表
void CPlatFormService::AddMainInstrumentList(std::string instrument)
{
m_pDataCenter->AddMainInstrumentList(instrument);
}
///获取主力合约列表
int CPlatFormService::GetMainInstrumentList(std::set<std::string> &outData)
{
return m_pDataCenter->GetMainInstrumentList(outData);
}
///设置合约容差列表
void CPlatFormService::SetInstrumentVarietyMap(map<string, string>& inData)
{
m_pDataCenter->SetInstrumentVarietyMap(inData);
}
// 获取合约容差列表
int CPlatFormService::GetInstrumentVarietyMap(map<string, string>& outData)
{
return m_pDataCenter->GetInstrumentVarietyMap(outData);
}
///获取指定品种的合约列表,返回合约个数
int CPlatFormService::GetInstrumentListByProductID(const std::string& ProductID,std::set<std::string> &outData)
{
return m_pDataCenter->GetInstrumentListByProductID(ProductID,outData);
}
int CPlatFormService::GetInstrumentListByProductID(const string& ProductID,vector<string> &outData)
{
return m_pDataCenter->GetInstrumentListByProductID(ProductID,outData);
}
///获取指定合约信息
int CPlatFormService::GetInstrumentInfo(const std::string& InstrumentID, PlatformStru_InstrumentInfo& outData)
{
return m_pDataCenter->GetInstrumentInfo(InstrumentID, outData);
}
bool CPlatFormService::GetLegInstrumentID(const string& strComInstrumentID,
string& strLeg1InstrumentID,
string& strLeg2InstrumentID)
{
return m_pDataCenter->GetLegInstrumentID(strComInstrumentID,strLeg1InstrumentID,strLeg2InstrumentID);
}
///获取包含此单腿合约的组合合约列表
bool CPlatFormService::GetCombInstrumentIDs_IncludeLeg(const std::string& LegInstrument,std::vector<std::string>& vecCombInstruments)
{
return m_pDataCenter->GetCombInstrumentIDs_IncludeLeg(LegInstrument,vecCombInstruments);
}
//设置合约订阅状态
void CPlatFormService::SetSubscribeStatus(const std::string& InstrumentID,int GID,SubscribeMarketDataOper oper)
{
//int oldstatus,newstatus;
EnterCriticalSection(&m_CS);
bool bOriSub=m_SubscribeMap.find(InstrumentID)!=m_SubscribeMap.end();
//if(m_SubscribeMap.find(InstrumentID)!=m_SubscribeMap.end())
// oldstatus=m_SubscribeMap[InstrumentID];
//else oldstatus=0;
switch(oper)
{
case eSubscribeMarketData:
if(!CTools_Ansi::IsKeyValueInMultimap<string, int>(m_SubscribeMap,InstrumentID,GID))
m_SubscribeMap.insert(pair<string, int>(InstrumentID,GID));
//m_SubscribeMap[InstrumentID]|=status;
break;
case eUnsubscribeMarketData:
if(CTools_Ansi::IsKeyValueInMultimap<string, int>(m_SubscribeMap,InstrumentID,GID))
CTools_Ansi::EraseKeyValueInMultimap<string, int>(m_SubscribeMap,InstrumentID,GID);
//m_SubscribeMap[InstrumentID]&=~status;
break;
}
bool bNewSub=m_SubscribeMap.find(InstrumentID)!=m_SubscribeMap.end();
//if(m_SubscribeMap.find(InstrumentID)!=m_SubscribeMap.end())
// newstatus=m_SubscribeMap[InstrumentID];
//else newstatus=0;
LeaveCriticalSection(&m_CS);
if(!bOriSub&&bNewSub)
SubscribeMarketData(InstrumentID);
else if(bOriSub&&!bNewSub)
UnSubscribeMarketData(InstrumentID);
//if(oldstatus==0&&newstatus!=0)
// SubscribeMarketData(InstrumentID);
//else if(oldstatus!=0&&newstatus==0)
// UnSubscribeMarketData(InstrumentID);
}
//退订GID对应的全部合约行情
void CPlatFormService::UnsubscribeMarketDataOfGID(int GID)
{
EnterCriticalSection(&m_CS);
vector<string> InstrumentIDs;
CTools_Ansi::GetKeysInMultimap_MatchValue<string,int>(m_SubscribeMap,GID,InstrumentIDs);
LeaveCriticalSection(&m_CS);
for(int i=0;i<(int)InstrumentIDs.size();i++)
SetSubscribeStatus(InstrumentIDs[i],GID,eUnsubscribeMarketData);
}
//检查GID是否订阅了指定合约的行情
bool CPlatFormService::IsSubscribeMarketDataOfGID(const string& InstrumentID,int GID)
{
EnterCriticalSection(&m_CS);
bool brlt=CTools_Ansi::IsKeyValueInMultimap<string,int>(m_SubscribeMap,InstrumentID,GID);
LeaveCriticalSection(&m_CS);
return brlt;
}
///设置指定合约信息
void CPlatFormService::SetInstrumentInfo(const std::string& InstrumentID, PlatformStru_InstrumentInfo& outData,bool bLast)
{
CTools_Ansi::EraseKeyInMultimap<string, int>(m_SubscribeMap,InstrumentID);
m_pDataCenter->SetInstrumentInfo(InstrumentID, outData, bLast);
}
///获取合约的产品类型, 失败返回-1
char CPlatFormService::GetProductClassType(const std::string& InstrumentID)
{
return m_pDataCenter->GetProductClassType(InstrumentID);
}
///获取合约的ProductID
string CPlatFormService::GetProductID(const string& strInstrumentID)
{
return m_pDataCenter->GetProductID(strInstrumentID);
}
string CPlatFormService::GetExchangeID(const string& strInstrumentID)
{
return m_pDataCenter->GetExchangeID(strInstrumentID);
}
///设置指定品种信息
void CPlatFormService::SetProductInfo(const string& ProductID, PlatformStru_ProductInfo& outData)
{
m_pDataCenter->SetProductInfo(ProductID, outData);
}
///获取品种列表
int CPlatFormService::GetProductList(vector<string> &outData,const string& ExchangeID)
{
return m_pDataCenter->GetProductList(outData,ExchangeID);
}
///获取指定交易所的所有品种-合约
int CPlatFormService::GetProductID_InstrumentIDsByExchangeID(std::map<std::string, std::set<std::string> >& outData,std::string ExchangeID)
{
return m_pDataCenter->GetProductID_InstrumentIDsByExchangeID(outData,ExchangeID);
}
///获取全部交易所的品种合约ID vector<pair<ExchangeID,vector<pair<ProductID,vector<InstrumentID>>>>>
void CPlatFormService::GetExchangeID_ProductID_InstrumentIDs(vector<pair<string,vector<pair<string,vector<string>>>>>& outData)
{
m_pDataCenter->GetExchangeID_ProductID_InstrumentIDs(outData);
}
///获取全部交易所的品种信息 vector<pair<ExchangeID,vector<PlatformStru_ProductInfo>>>
void CPlatFormService::GetExchangeID_ProductInfos(vector<pair<string,vector<PlatformStru_ProductInfo>>>& outData)
{
m_pDataCenter->GetExchangeID_ProductInfos(outData);
}
///根据合约ID获取品种信息
bool CPlatFormService::GetProductInfo(const string& strInstrumentID,PlatformStru_ProductInfo& outData)
{
return m_pDataCenter->GetProductInfo(strInstrumentID,outData);
}
///根据品种ID获取品种信息
bool CPlatFormService::GetProductInfo2(const string& strProductID,PlatformStru_ProductInfo& outData)
{
return m_pDataCenter->GetProductInfo2(strProductID,outData);
}
//获取指定交易所的期权标的物期货品种
int CPlatFormService::GetOptionProductIDsByExchangeID(const string& ExchangeID,vector<string>& outProductIDs)
{
return m_pDataCenter->GetOptionProductIDsByExchangeID(ExchangeID,outProductIDs);
}
//获取指定标的物期货合约对应的期权合约ID,返回目标期权合约的数量。UnderlyingInstrumentID为空则返回全部期权合约
int CPlatFormService::GetOptionInstrumentIDsByUnderlyingInstrumentID(const string& UnderlyingInstrumentID,vector<string>& outOptionInstrumentIDs)
{
return m_pDataCenter->GetOptionInstrumentIDsByUnderlyingInstrumentID(UnderlyingInstrumentID,outOptionInstrumentIDs);
}
//获取指定标的物期货合约对应的看涨期权合约ID数组和看跌期权合约ID数组。UnderlyingInstrumentID为空则返回全部期权合约
void CPlatFormService::GetOptionInstrumentIDsByUnderlyingInstrumentID(const string& UnderlyingInstrumentID,vector<string>& outCallOptionInstrumentIDs,vector<string>& outPutOptionInstrumentIDs)
{
return m_pDataCenter->GetOptionInstrumentIDsByUnderlyingInstrumentID(UnderlyingInstrumentID,outCallOptionInstrumentIDs,outPutOptionInstrumentIDs);
}
//获取所有标的物期货合约
int CPlatFormService::GetAllOptionUnderlyingInstrumentIDs(vector<string>& outUnderlyingInstrumentIDs)
{
return m_pDataCenter->GetAllOptionUnderlyingInstrumentIDs(outUnderlyingInstrumentIDs);
}
int CPlatFormService::GetAllOptionUnderlyingInstrumentIDs(set<string>& outUnderlyingInstrumentIDs)
{
return m_pDataCenter->GetAllOptionUnderlyingInstrumentIDs(outUnderlyingInstrumentIDs);
}
//判断是否是期权标的物期货合约
bool CPlatFormService::IsUnderlyingInstrumentID(const string& InstrumentID)
{
return m_pDataCenter->IsUnderlyingInstrumentID(InstrumentID);
}
///获取合约手续费率
int CPlatFormService::GetCommissionRate(const std::string& InstrumentID, PlatformStru_InstrumentCommissionRate& outData)
{
return m_pDataCenter->GetCommissionRate(InstrumentID, outData);
}
bool CPlatFormService::IsCommissionRateExist(const string& InstrumentID)
{
return m_pDataCenter->IsCommissionRateExist(InstrumentID);
}
///获取合约保证金率
int CPlatFormService::GetMarginRate(const std::string& InstrumentID, PlatformStru_InstrumentMarginRate& outData)
{
return m_pDataCenter->GetMarginRate(InstrumentID, outData);
}
bool CPlatFormService::IsMarginRateExist(const string& InstrumentID)
{
return m_pDataCenter->IsMarginRateExist(InstrumentID);
}
///设置合约手续费率
int CPlatFormService::SetCommissionRate(const std::string& InstrumentID, PlatformStru_InstrumentCommissionRate& outData)
{
return m_pDataCenter->SetCommissionRate(InstrumentID, outData);
}
///设置正在查询手续费率的合约
void CPlatFormService::SetReqCommissionRateInstrumentID(const std::string& InstrumentID)
{
m_pDataCenter->SetReqCommissionRateInstrumentID(InstrumentID);
}
///设置合约保证金率
int CPlatFormService::SetMarginRate(const std::string& InstrumentID, PlatformStru_InstrumentMarginRate& outData)
{
return m_pDataCenter->SetMarginRate(InstrumentID, outData);
}
///获取合约乘数, 成功返回合约乘数, 失败返回-1
int CPlatFormService::GetInstrumentMultiple(const std::string& InstrumentID)
{
return m_pDataCenter->GetInstrumentMultiple(InstrumentID);
}
///获取指定合约行情
int CPlatFormService::GetQuotInfo(const std::string& InstrumentID, PlatformStru_DepthMarketData& outData)
{
return m_pDataCenter->GetQuotInfo(InstrumentID, outData);
}
///获取指定合约旧行情
int CPlatFormService::GetOldQuotInfo(const std::string& InstrumentID, PlatformStru_DepthMarketData& outData)
{
return m_pDataCenter->GetOldQuotInfo(InstrumentID, outData);
}
///获取指定合约的现价, 失败返回无效值
double CPlatFormService::GetCurPrice(const std::string& InstrumentID)
{
return m_pDataCenter->GetCurPrice(InstrumentID);
}
string CPlatFormService::GetTradingDay()
{
return m_pDataCenter->GetTradingDay();
}
bool CPlatFormService::IsTodayPosition( const char* pOpenData )
{
return m_pDataCenter->IsTodayPosition(pOpenData);
}
///获取交易所时间
unsigned long CPlatFormService::GetExchangeTime(const string& ExchangeID,string& time)
{
return m_pDataCenter->GetExchangeTime(ExchangeID,time);
}
///获取交易所日内交易时段, 返回交易时段起始时间对的数组,如{pair("0915","1130"),pair("1300","1515")}等
vector<pair<string,string>> CPlatFormService::GetTradingTimespan(const string& ExchangeID)
{
vector<pair<string,string>> timespan;
if(ExchangeID==string("CFFEX"))
{
timespan.push_back(make_pair("0915","1130"));
timespan.push_back(make_pair("1300","1515"));
}
else if(ExchangeID==string("SHFE")||ExchangeID==string("DCE")||ExchangeID==string("CZCE"))
{
timespan.push_back(make_pair("0900","1015"));
timespan.push_back(make_pair("1030","1130"));
timespan.push_back(make_pair("1300","1500"));
}
return timespan;
}
///获取全部交易所
int CPlatFormService::GetExchangeIDs(vector<string>& outData)
{
return m_pDataCenter->GetExchangeIDs(outData);
}
///设置当前显示的持仓内容. 1:持仓; 2:持仓明细; 3:组合持仓
void CPlatFormService::SetCurrentPositionContent(int PositionContentMode)
{
return m_pDataCenter->SetCurrentPositionContent(PositionContentMode);
}
///获取全部报单
int CPlatFormService::GetAllOrders(std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetAllOrders(outData);
}
///获取全部报单
int CPlatFormService::GetAllOrders2(const std::string& strInstrument,std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetAllOrders2(strInstrument,outData);
}
///获取指定报单
bool CPlatFormService::GetOrder(const OrderKey& inOrderKey,PlatformStru_OrderInfo& outData)
{
return m_pDataCenter->GetOrder(inOrderKey,outData);
}
bool CPlatFormService::GetOrder2(const string& strOrderSysID,PlatformStru_OrderInfo& outData)
{
return m_pDataCenter->GetOrder2(strOrderSysID,outData);
}
int CPlatFormService::GetTriggerOrders(std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetTriggerOrders(outData);
}
///获取合约相关的已触发的报单
int CPlatFormService::GetTriggerOrders2(const std::string& strInstrument,std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetTriggerOrders2(strInstrument,outData);
}
///获取指定已触发的报单
bool CPlatFormService::GetTriggerOrder(const OrderKey& orderkey,PlatformStru_OrderInfo& outData)
{
return m_pDataCenter->GetTriggerOrder(orderkey,outData);
}
///获取已成交报单
int CPlatFormService::GetTradedOrders(std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetTradedOrders(outData);
}
///获取已成交报单
int CPlatFormService::GetTradedOrders2(const std::string& strInstrument,std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetTradedOrders2(strInstrument,outData);
}
///获取指定已成交报单
bool CPlatFormService::GetTradedOrder(const OrderKey& orderkey,PlatformStru_OrderInfo& outData)
{
return m_pDataCenter->GetTradedOrder(orderkey,outData);
}
///获取已撤单和错误报单
int CPlatFormService::GetCanceledOrders(std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetCanceledOrders(outData);
}
///获取已撤单和错误报单
int CPlatFormService::GetCanceledOrders2(const std::string& strInstrument,std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetCanceledOrders2(strInstrument,outData);
}
///获取指定已撤单和错误报单
bool CPlatFormService::GetCanceledOrder(const OrderKey& orderkey,PlatformStru_OrderInfo& outData)
{
return m_pDataCenter->GetCanceledOrder(orderkey,outData);
}
///获取未成交报单
int CPlatFormService::GetWaitOrders(std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetWaitOrders(outData);
}
///获取未成交报单
int CPlatFormService::GetWaitOrders3(const std::string& strInstrument,std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetWaitOrders3(strInstrument,outData);
}
///获取指定合约相关的未成交报单, 不包含手工审核中的报单, 合约是单合约, 报单是对应报单, 或包含该合约的组合报单
int CPlatFormService::GetWaitOrders2(const std::string& strInstrument,std::vector<PlatformStru_OrderInfo>& outData)
{
return m_pDataCenter->GetWaitOrders2(strInstrument,outData);
}
///获取指定未成交报单
bool CPlatFormService::GetWaitOrder(const OrderKey& orderkey,PlatformStru_OrderInfo& outData)
{
return m_pDataCenter->GetWaitOrder(orderkey,outData);
}
int CPlatFormService::GetTradingAccountAvailable(double& fAvailable)
{
return m_pDataCenter->GetTradingAccountAvailable(fAvailable);
}
int CPlatFormService::GetTradingAccountWithdrawQuota(double& fWithdrawQuota)
{
return m_pDataCenter->GetTradingAccountWithdrawQuota(fWithdrawQuota);
}
int CPlatFormService::GetTradingAccountID(char* AccountID,int rltsize)
{
return m_pDataCenter->GetTradingAccountID(AccountID,rltsize);
}
///获取交易资金账户信息
int CPlatFormService::GetTradingAccount(const std::string& strAccount, PlatformStru_TradingAccountInfo& outData)
{
return m_pDataCenter->GetTradingAccount(outData);
}
///获取账户资金文本信息
int CPlatFormService::GetAccountText(std::string& outData,int language)
{
return m_pDataCenter->GetAccountText( outData, language);
}
///请求查询投资者结算结果响应
int CPlatFormService::GetLastSettlementInfo(std::string& outData)
{
return m_pDataCenter->GetLastSettlementInfo(outData);
}
///获取全部成交单
int CPlatFormService::GetAllTrades(std::vector<PlatformStru_TradeInfo>& outData)
{
return m_pDataCenter->GetAllTrades(outData);
}
///获取指定成交信息
bool CPlatFormService::GetTradeInfo(const TradeKey& tradekey, PlatformStru_TradeInfo& outData)
{
return m_pDataCenter->GetTradeInfo(tradekey,outData);
}
///获取指定成交信息
int CPlatFormService::GetTradesOfInstrument(const std::string& strInstrument,std::vector<PlatformStru_TradeInfo>& outData)
{
return m_pDataCenter->GetTradesOfInstrument(strInstrument,outData);
}
int CPlatFormService::GetTradeBriefsOfInstrument(const std::string& strInstrument,std::vector<PlatformStru_TradeInfoBrief>& outData)
{
return m_pDataCenter->GetTradeBriefsOfInstrument(strInstrument,outData);
}
///获取全部成交统计记录
int CPlatFormService::GetAllTradeTotals(std::vector<PlatformStru_TradeTotalInfo>& outData)
{
return m_pDataCenter->GetAllTradeTotals(outData);
}
///获取指定合约的成交统计记录成功返回0, 失败返回-1
int CPlatFormService::GetTradeTotalOfInstrument(const std::string& strInstrument, std::vector<PlatformStru_TradeTotalInfo>& outData)
{
return m_pDataCenter->GetTradeTotalOfInstrument(strInstrument,outData);
}
///获取成交统计
int CPlatFormService::GetAllTradeTotalDatas(vector<TotalInfo>& outData)
{
return m_pDataCenter->GetAllTradeTotalDatas(outData);
}
///在成交统计查找参数rawData
int CPlatFormService::FindIndexFromAllTradeTotalDatas(const PlatformStru_TradeInfo& rawData )
{
return m_pDataCenter->FindIndexFromAllTradeTotalDatas(rawData);
}
int CPlatFormService::GetPositions2(const std::string& strInstrument,
std::set<long>& setFTID,
std::vector<PlatformStru_Position>& outData,
long& lastseq)
{
return m_pDataCenter->GetPositions2(strInstrument,setFTID,outData,lastseq);
}
int CPlatFormService::GetPositions3(const std::string& strInstrument,
std::vector<PlatformStru_Position>& outData,
long& lastseq)
{
return m_pDataCenter->GetPositions3(strInstrument,outData,lastseq);
}
int CPlatFormService::GetPositionDetails3(const std::string& strInstrument,
std::set<long>& setFTID,
std::vector<PlatformStru_PositionDetail>& vecValue,
long& lastseq)
{
return m_pDataCenter->GetPositionDetails3(strInstrument,setFTID,vecValue,lastseq);
}
int CPlatFormService::GetPositionCombs2(const std::string& strInstrument, std::vector<PlatformStru_Position>& outData)
{
return m_pDataCenter->GetPositionCombs2(strInstrument,outData);
}
int CPlatFormService::GetPositions(std::vector<PlatformStru_Position>& outData)
{
return m_pDataCenter->GetPositions(outData);
}
int CPlatFormService::GetPositionDetails(std::vector<PlatformStru_PositionDetail>& outData,long& lastseq)
{
return m_pDataCenter->GetPositionDetails(outData,lastseq);
}
int CPlatFormService::GetPositionCombs(std::vector<PlatformStru_Position>& outData)
{
return m_pDataCenter->GetPositionCombs(outData);
}
bool CPlatFormService::HavePositionDetail(const std::string& strInstrumentID)
{
return m_pDataCenter->HavePositionDetail(strInstrumentID);
}
bool CPlatFormService::HaveCombPositionDetail()
{
return m_pDataCenter->HaveCombPositionDetail();
}
void CPlatFormService::GetDerivedInstrumentID_OnCloseTrade(set<string>& InstrumentIDs)
{
m_pDataCenter->GetDerivedInstrumentID_OnCloseTrade(InstrumentIDs);
}
//获取持仓记录键值列表,返回持仓记录的数量
int CPlatFormService::GetPositionKeySet(std::set<PositionKey> &PositionKeySet)
{
return m_pDataCenter->GetPositionKeySet(PositionKeySet);
}
//获取指定合约, 方向, 投保的持仓数据, 成功返回0, 失败返回-1
int CPlatFormService::GetPositionData(const std::string& strAccount, const std::string& InstrumentID,const char Direction,const char HedgeFlag,PlatformStru_Position& PositionData)
{
return m_pDataCenter->GetPositionData(strAccount,InstrumentID,Direction,HedgeFlag,PositionData);
}
int CPlatFormService::GetWaitOrderVolume(const std::string& strAccount, const std::string &strInstrumentID, const char Direction, char CloseType,const char HedgeFlag)
{
return m_pDataCenter->GetWaitOrderVolume(strAccount,strInstrumentID, Direction, CloseType,HedgeFlag);
}
//获取指定合约指定方向的平仓挂单的平仓量, 返回0表示成功, <0表示失败. 成功时CloseVolume返回平仓单(含强平和本地强平)的手数, CloseTodayVolume返回平今单手数, CloseYesterdayVolume表示平昨单手数
int CPlatFormService::GetCloseOrderVolume(const std::string& strAccount,const std::string &strInstrumentID, const char& Direction,int& CloseVolume,int& CloseTodayVolume,int& CloseYesterdayVolume,const char HedgeFlag)
{
return m_pDataCenter->GetCloseOrderVolume(strAccount,strInstrumentID, Direction,CloseVolume,CloseTodayVolume,CloseYesterdayVolume,HedgeFlag);
}
CTPCONNSTATUS CPlatFormService::GetTradeStatus(void)
{
return m_PlatformParam.TradeStatus;
};
//获取行情连接状态.
CTPCONNSTATUS CPlatFormService::GetQuotStatus(void)
{
return m_PlatformParam.QuotStatus;
};
//获取交易BrokerID.
std::string CPlatFormService::GetTradeBrokerID(void)
{
return m_PlatformParam.BrokerID;
};
//获取交易InvestorID.
std::string CPlatFormService::GetTradeInvestorID(void)
{
return m_PlatformParam.InvestorID;
};
//int CPlatFormService::GetPlatFormID()
//{
// return m_PlatformParam.PlatFormID;
//}
//判断是否需要查询新合约的费率
bool CPlatFormService::IsNeedCheckCommissionRateAndMarginRate(void)
{
return m_pDataCenter->IsNeedCheckCommissionRateAndMarginRate();
}
//清除需要查询新合约费率的标志
void CPlatFormService::SetNeedCheckCommissionRateAndMarginRate(bool bNeedCheck)
{
m_pDataCenter->SetNeedCheckCommissionRateAndMarginRate(bNeedCheck);
}
bool CPlatFormService::IsSettlementInfoConfirmed()
{
return m_bSettlementInfoConfirmed;
}
SERVER_PARAM_CFG& CPlatFormService::GetServerParamCfg()
{
return m_pDataCenter->GetServerParamCfg();
}
//获取客户签约银行信息
int CPlatFormService::GetContractBank(std::map<std::string, PlatformStru_ContractBank>& outData)
{
return m_pDataCenter->GetContractBank(outData);
}
//UI层通知底层, 初始化查询开始或完成
void CPlatFormService::NotifyInitQryStart()
{
m_pDataCenter->NotifyInitQryStart();
}
//UI层通知底层, 初始化查询开始或完成
void CPlatFormService::NotifyInitQrySucc()
{
m_pDataCenter->NotifyInitQrySucc();
}
int CPlatFormService::GetAllOrderFTIDList( std::vector<long>& vec )
{
return m_pDataCenter->GetAllOrderFTIDList(vec);
}
int CPlatFormService::GetAllOrderInfo( long lFTID, PlatformStru_OrderInfo& outData )
{
return m_pDataCenter->GetAllOrderInfo(lFTID, outData);
}
int CPlatFormService::GetAllOrderInfo( OrderKey key, PlatformStru_OrderInfo& outData )
{
return m_pDataCenter->GetAllOrderInfo(key, outData);
}
int CPlatFormService::GetPositionFTIDList( std::vector<long>& vec )
{
return m_pDataCenter->GetPositionFTIDList(vec);
}
int CPlatFormService::GetPositionInfo( long lFTID, PlatformStru_Position& outData )
{
return m_pDataCenter->GetPositionInfo(lFTID, outData);
}
int CPlatFormService::GetPositionInfo( PositionKey key, PlatformStru_Position& outData )
{
return m_pDataCenter->GetPositionInfo(key, outData);
}
int CPlatFormService::GetPositionCombFTIDList( std::vector<long>& vec )
{
return m_pDataCenter->GetPositionCombFTIDList(vec);
}
int CPlatFormService::GetPositionCombInfo( long lFTID, PlatformStru_Position& outData )
{
return m_pDataCenter->GetPositionCombInfo(lFTID, outData);
}
//获取交易连接的FrontID和SessionID. 这两个值在交易登录时由ctp返回
const PlatformStru_LoginInfo& CPlatFormService::GetTradingLoginInfo()
{
return m_pDataCenter->GetTradingLoginInfo();
}
///DataCenter是否已经和底层同步上,可以开始初始化查询了
bool CPlatFormService::IsDataCenterReady(void)
{
return m_pDataCenter ? m_pDataCenter->bRspQrySettlementInfoConfirm : false;
}
vector<string> CPlatFormService::GetCurrencys(const string& BankName,bool bAddUSD,bool bAddCNY)
{
return m_pDataCenter->GetCurrencys(BankName,bAddUSD,bAddCNY);
}
vector<string> CPlatFormService::GetCurrencys(bool bAddUSD,bool bAddCNY)
{
return m_pDataCenter->GetCurrencys(bAddUSD,bAddCNY);
}
///订阅询价通知,OptionInstrumentIDs为空则订阅全部期权合约的询价通知
int CPlatFormService::SubscribeForQuoteRsp(const vector<string>& OptionInstrumentIDs)
{
int ret = -999;
CHECK_TRADE_STATUS();
#ifdef CTP060300
vector<string> InstrumentIDs=OptionInstrumentIDs;
if(InstrumentIDs.empty())
m_pDataCenter->GetOptionInstrumentIDsByUnderlyingInstrumentID(string(""),InstrumentIDs);
for(vector<string>::iterator it=InstrumentIDs.begin();it!=InstrumentIDs.end();)
{
if(m_setOptionInstrumentIDs_SubscribeForQuoteRsp.find(*it)!=m_setOptionInstrumentIDs_SubscribeForQuoteRsp.end())
it=InstrumentIDs.erase(it);
else it++;
}
int cnt=InstrumentIDs.size();
AllocTmpStackBuf(tmpInstrumentIDs,sizeof(char*)*cnt);
for(int i=0;i<cnt;i++)
((char**)(tmpInstrumentIDs.m_pbuf))[i]=const_cast<char*>(InstrumentIDs[i].c_str());
ret = m_pQuotApi->SubscribeForQuoteRsp((char**)(tmpInstrumentIDs.m_pbuf), cnt);
if(ret==0)
{
for(int i=0;i<cnt;i++)
m_setOptionInstrumentIDs_SubscribeForQuoteRsp.insert(InstrumentIDs[i]);
}
LOG_INFO("SubscribeForQuoteRsp(订阅询价通知):ret=[%d],cnt=[%d]",
ret, cnt);
#endif
return ret;
}
///退订询价通知,OptionInstrumentIDs为空则退订全部合约的询价通知
int CPlatFormService::UnSubscribeForQuoteRsp(const vector<string>& OptionInstrumentIDs)
{
int ret = -999;
CHECK_TRADE_STATUS();
#ifdef CTP060300
vector<string> InstrumentIDs=OptionInstrumentIDs;
if(InstrumentIDs.empty())
CTools_Ansi::ConvertSet2Vector(m_setOptionInstrumentIDs_SubscribeForQuoteRsp,InstrumentIDs);
else
{
for(vector<string>::iterator it=InstrumentIDs.begin();it!=InstrumentIDs.end();)
{
if(m_setOptionInstrumentIDs_SubscribeForQuoteRsp.find(*it)==m_setOptionInstrumentIDs_SubscribeForQuoteRsp.end())
it=InstrumentIDs.erase(it);
else it++;
}
}
int cnt=InstrumentIDs.size();
AllocTmpStackBuf(tmpInstrumentIDs,sizeof(char*)*cnt);
for(int i=0;i<cnt;i++)
((char**)(tmpInstrumentIDs.m_pbuf))[i]=const_cast<char*>(InstrumentIDs[i].c_str());
ret = m_pQuotApi->UnSubscribeForQuoteRsp((char**)(tmpInstrumentIDs.m_pbuf), cnt);
if(ret==0)
{
for(int i=0;i<cnt;i++)
{
if(m_setOptionInstrumentIDs_SubscribeForQuoteRsp.find(InstrumentIDs[i])!=m_setOptionInstrumentIDs_SubscribeForQuoteRsp.end())
m_setOptionInstrumentIDs_SubscribeForQuoteRsp.erase(InstrumentIDs[i]);
}
}
LOG_INFO("UnSubscribeForQuoteRsp(退订询价通知):ret=[%d],cnt=[%d]",
ret, cnt);
#endif
return ret;
}
///请求询价录入
///调用者不用管InputForQuote中的BrokerID, InvestorID, UserID, ForQuoteRef这些值。底层自动确定,并返回
int CPlatFormService::ReqForQuoteInsert(PlatformStru_InputForQuoteField& InputForQuote, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
#ifdef CTP060300
strncpy(InputForQuote.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(InputForQuote.BrokerID)-1); ///经纪公司代码
strncpy(InputForQuote.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(InputForQuote.InvestorID)-1); ///投资者代码
strncpy(InputForQuote.UserID, m_PlatformParam.UserID.c_str(), sizeof(InputForQuote.UserID)-1); ///用户代码
sprintf(InputForQuote.ForQuoteRef,"%12d",++m_CurForQuoteRef);
CThostFtdcInputForQuoteField thost;
InputForQuote.ToThost(thost);
ret = m_pTradeApi->ReqForQuoteInsert(&thost, nRequestID);
LOG_INFO("ReqForQuoteInsert(请求询价录入):ret=[%d],nRequestID=[%d]\n%s",
ret, nRequestID,InputForQuote.tostring().c_str());
#endif
return ret;
}
///执行宣告录入请求
///调用者不用管InputExecOrder中的BrokerID, InvestorID, UserID, ExecOrderRef这些值。底层自动确定,并返回
///ExecOrderRef暂时使用报单引用的值进行递增
int CPlatFormService::ReqExecOrderInsert(PlatformStru_InputExecOrderField& InputExecOrder, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
#ifdef CTP060300
InputExecOrder.RequestID=nRequestID;
strncpy(InputExecOrder.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(InputExecOrder.BrokerID)-1); ///经纪公司代码
strncpy(InputExecOrder.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(InputExecOrder.InvestorID)-1); ///投资者代码
strncpy(InputExecOrder.UserID, m_PlatformParam.UserID.c_str(), sizeof(InputExecOrder.UserID)-1); ///用户代码
sprintf(InputExecOrder.ExecOrderRef,"%12d",++m_CurExecOrderRef);
CThostFtdcInputExecOrderField thost;
InputExecOrder.ToThost(thost);
ret = m_pTradeApi->ReqExecOrderInsert(&thost, nRequestID);
LOG_INFO("ReqExecOrderInsert(执行宣告录入请求):ret=[%d],nRequestID=[%d]\n%s",
ret, nRequestID,InputExecOrder.tostring().c_str());
#endif
return ret;
}
///执行宣告操作请求
///调用者不用管InputExecOrderAction中的BrokerID, InvestorID, UserID, ExecOrderActionRef这些值。底层自动确定,并返回
///ExecOrderActionRef暂时使用报单引用的值进行递增
int CPlatFormService::ReqExecOrderAction(PlatformStru_InputExecOrderActionField& InputExecOrderAction, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
#ifdef CTP060300
InputExecOrderAction.RequestID=nRequestID;
strncpy(InputExecOrderAction.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(InputExecOrderAction.BrokerID)-1); ///经纪公司代码
strncpy(InputExecOrderAction.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(InputExecOrderAction.InvestorID)-1); ///投资者代码
strncpy(InputExecOrderAction.UserID, m_PlatformParam.UserID.c_str(), sizeof(InputExecOrderAction.UserID)-1); ///用户代码
InputExecOrderAction.ExecOrderActionRef=++m_CurExecOrderActionRef;
CThostFtdcInputExecOrderActionField thost;
InputExecOrderAction.ToThost(thost);
ret = m_pTradeApi->ReqExecOrderAction(&thost, nRequestID);
LOG_INFO("ReqExecOrderAction(执行宣告操作请求):ret=[%d],nRequestID=[%d]\n%s",
ret, nRequestID,InputExecOrderAction.tostring().c_str());
#endif
return ret;
}
///请求查询执行宣告
///调用者不用管InputForQuote中的BrokerID, InvestorID这些值。底层自动确定,并返回
int CPlatFormService::ReqQryExecOrder(PlatformStru_QryExecOrderField& QryExecOrder, int nRequestID)
{
int ret = -999;
CHECK_TRADE_STATUS();
#ifdef CTP060300
strncpy(QryExecOrder.BrokerID, m_PlatformParam.BrokerID.c_str(), sizeof(QryExecOrder.BrokerID)-1); ///经纪公司代码
strncpy(QryExecOrder.InvestorID, m_PlatformParam.InvestorID.c_str(), sizeof(QryExecOrder.InvestorID)-1); ///投资者代码
CThostFtdcQryExecOrderField thost;
QryExecOrder.ToThost(thost);
ret = m_pTradeApi->ReqQryExecOrder(&thost, nRequestID);
LOG_INFO("ReqQryExecOrder(请求查询执行宣告):ret=[%d],nRequestID=[%d]\n%s",
ret, nRequestID,QryExecOrder.tostring().c_str());
#endif
return ret;
}
| [
"w.z.y2006@163.com"
] | w.z.y2006@163.com |
634e6f1d09c5c498e046a7de5cebf57c854ef13c | ca898fb9689be291543723c8ea132a3ddbb73734 | /src/spotifyconnectmodel.h | 47fe926e0d3745fe5e55b3cb3439c526e84b86aa | [] | no_license | jgueytat/UnofficialSpotify-desktop | f11b80c8205e839006d55701a9bbbc6832377b72 | d7af9fdccc0177ed731cbc110a66744a45f7d472 | refs/heads/master | 2021-03-30T20:51:56.003529 | 2018-03-13T12:25:49 | 2018-03-13T17:18:25 | 124,522,040 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | h | #ifndef SPOTIFYCONNECTMODEL_H
#define SPOTIFYCONNECTMODEL_H
#include "spotifywrapper.h"
#include <QAbstractListModel>
class SpotifyConnectModel : public QAbstractListModel
{
Q_OBJECT
public:
enum ConnectRoles {
IdRole = Qt::UserRole + 1,
IsActiveRole,
IsRestrictedRole,
NameRole,
TypeRole,
VolumePercentRole
};
SpotifyConnectModel(SpotifyWrapper * const spotifyWrapper, QObject *parent = nullptr);
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
signals:
void error(const QString &errorString);
protected:
QHash<int, QByteArray> roleNames() const;
private:
SpotifyWrapper * m_pSpotifyWrapper;
QList<QJsonObject> m_aConnect;
void requestConnect();
};
#endif // SPOTIFYCONNECTMODEL_H
| [
"contact@jgueytat.fr"
] | contact@jgueytat.fr |
7a2b3c24d4b5bbdc045dbbdfd75bbc1dca451671 | 06ce97f87b4b9f6f8802efd2da9b9ac329bd768e | /Project3/src/InitialConditions/threebody.cpp | 58c16338e1843f0e6bc0291b2365c59979d24fac | [] | no_license | trygvels/FYS3150 | 6b6ad4de2d4f8da0c263530e836793299e39ade1 | 0f9b80ffa3c41eed9b0ab9fac9844461b97c9d9c | refs/heads/master | 2021-01-11T03:59:59.094354 | 2016-11-03T14:14:17 | 2016-11-03T14:14:17 | 71,262,334 | 0 | 0 | null | 2016-10-18T15:23:58 | 2016-10-18T15:23:58 | null | UTF-8 | C++ | false | false | 923 | cpp | #include "threebody.h"
#include "../vec3.h"
#include "../system.h"
#include <cmath>
void ThreeBody::setupParticles(System &system) {
/*
* Here, we set uo the particle system for three particles.
* For our project we have one such system:
* The Sun-Earth-Jupiter system
*/
double solar_mass = 1.988544 * pow(10,30);
double earth_mass = 5.97219 * pow(10, 24) / solar_mass;
double jupiter_mass = 1898.13 * pow(10, 24) / solar_mass;
Particle* sun = new Particle(vec3(0,0,0), vec3(0,0,0), 1.0, "Sun");
Particle* earth = new Particle(vec3(1,0,0), vec3(0,2*M_PI,0), earth_mass, "Earth");
Particle* jupiter = new Particle(vec3(5.2,0,0), vec3(5.9024E-04, -7.1587E-03, 1.6542E-05)*365.2422, jupiter_mass, "Jupiter");
system.addParticle(sun);
system.addParticle(earth);
system.addParticle(jupiter);
}
std::string ThreeBody::getName() {
return "Three-body";
}
| [
"sebastwi@uio.no"
] | sebastwi@uio.no |
1e331350c66a1b5c0598b73451e139484cbe9da2 | 1935aa569fafae4a6206998d27102700689fca35 | /EliteArduino2/EliteArduino2.ino | c2d807dfa73b861bb2deee6102165d64c7d2d6da | [
"Apache-2.0"
] | permissive | Maxfojtik/EliteDangeriousNeopixelIntegration | 72ecc9a86516d59ee3ebd4e56f3bd006db0b62af | 451b5fe5bd7f24dcc35a7cbbe5ee452e5f85d5d0 | refs/heads/master | 2021-06-25T08:28:14.957116 | 2021-03-21T01:56:37 | 2021-03-21T01:56:37 | 185,478,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,977 | ino | #include <FastLED.h>
//#####CONFIG VALUES
#define DATA_PINL 3
#define DATA_PINR 4
#define NUM_LEDS 46
#define BRIGHTNESS 255
//#####END CONFIG
CRGB leds[NUM_LEDS];
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void setup() {
Serial.begin(9600);
LEDS.addLeds<WS2812, DATA_PINL, GRB>(leds, NUM_LEDS);
LEDS.addLeds<WS2812,DATA_PINR,GRB>(leds, NUM_LEDS);
LEDS.setBrightness(BRIGHTNESS);
// FastLED.setMaxPowerInVoltsAndMilliamps(5, 100);
pinMode(13, OUTPUT);
digitalWrite(13, false);
}
String complied = "";
int color = 0;
int var = 0;
int var2 = 0;
int var3 = 0;
int mode = 0;
int renderMode = 0;
int spot = 0;
float amount = 0;
float amountH = 0;
int notification = 0;
int notificationVar = 0;
boolean readyToSwitch = false;
boolean statusLed = false;
float cRed = 0;
float cGreen = 0;
float cBlue = 255;
float cRedSpeed = 0;
float cGreenSpeed = 0;
float cBlueSpeed = 0;
int numSteps = 300;
float oldCRed = 0;
float oldCGreen = 0;
float oldCBlue = 0;
int stepCounter = 0;
int spaceSpeed = 4;
float sRed = 255;
float sGreen = 255;
float sBlue = 255;
boolean wasConnected = false;
boolean demo = 0;
long lastSwitch = 0;
boolean demoNotifications = false;
int lastNoti = -1;
long lastFrame = 0;
void loop()
{
if (!Serial)
{
color = 0;
mode = 0;
}
else
{
if (Serial.available() > 0)
{
int proc = Serial.read();
if (proc != 10)
{
complied += char(proc);
}
else
{
parse(complied);
complied = "";
}
}
}
if(demo && millis()-lastSwitch>1000)
{
lastSwitch = millis();
if(!demoNotifications)
{
mode++;
}
if(mode>15)
{
if(!demoNotifications)
{
mode = 4;
spot = 1000;
demoNotifications = true;
amount = .5f;
amountH = .75f;
}
}
}
if(demoNotifications)
{
Serial.println(notification);
if(notification==0)
{
lastNoti++;
if(lastNoti>23)
{
lastNoti = 0;
mode = 0;
demoNotifications = false;
}
else
{
notificationVar = 0;
notification = lastNoti;
}
}
}
if(millis()-lastFrame>16)
{
// Serial.println(millis()-lastFrame);
lastFrame = millis();
render();
}
}
void parse(String thing)//CARGO
{
digitalWrite(13, statusLed);
statusLed = !statusLed;
if (thing == "PING")
{
Serial.println(F("pingElite"));
for(int i = 0; i < NUM_LEDS; i++)
{
leds[i] = CRGB(0, 255, 0);
}
LEDS.show();
delay(100);
for(int i = 0; i < NUM_LEDS; i++)
{
leds[i] = CRGB(0, 0, 0);
}
LEDS.show();
}
else if (thing.equals(F("Startup")))
{
mode = 1;
}
else if (thing.equals(F("MainMenu")))
{
mode = 3;
}
else if (thing.equals(F("LoadGame")))
{
mode = 2;
}
else if (thing.equals(F("Docked")))
{
mode = 3;
}
else if (thing.equals(F("Undocked")))
{
if (mode == 3)
{
spot = 0;
}
mode = 4;
spaceSpeed = 4;
}
else if (thing.equals(F("SupercruiseEntry")))
{
mode = 5;
spaceSpeed = 8;
}
else if (thing.equals(F("Hyper")))
{
mode = 6;
spaceSpeed = -16;
}
else if (thing.equals(F("DockingRequested")))
{
mode = 7;
}
else if (thing.equals(F("DockingGranted")))
{
mode = 8;
}
else if (thing.equals(F("DockingDenied")))
{
mode = 9;
}
else if (thing.equals(F("HeatWarning")))
{
mode = 10;
}
else if (thing.equals(F("AutoDock")))
{
mode = 11;
}
else if (thing.equals(F("LaunchSRV")))
{
mode = 12;
}
else if (thing.equals(F("StartHyper")))
{
var3 = 0;
var2 = 0;
mode = 13;
}
else if (thing.equals(F("StartSuper")))
{
var3 = 0;
var2 = 0;
mode = 14;
}
else if (thing.equals(F("StationServices")))
{
var2 = 0;
mode = 16;
}
else if (thing.equals(F("OutStationServices")))
{
mode = 3;
}
else if (thing.equals(F("AsteroidCracked")))
{
notification = 2;
notificationVar = 0;
}
else if (thing.equals(F("Shutdown")))
{
color = 0;
mode = 0;
}
else if (thing.equals(F("Prospector")))
{
notification = 3;
notificationVar = 0;
}
else if (thing.equals(F("Collection")))
{
notification = 4;
notificationVar = 0;
}
else if (thing.equals(F("ScanStage0")))
{
//notificationVar = 0;
//notification = 5;
}
else if (thing.equals(F("ScanStage1")))
{
notificationVar = 0;
notification = 6;
}
else if (thing.equals(F("ScanStage2")))
{
notificationVar = 0;
notification = 7;
}
else if (thing.equals(F("ScanStageC")))
{
notificationVar = 0;
notification = 8;
}
else if (thing.equals(F("ScanStageW")))
{
notificationVar = 0;
notification = 9;
}
else if (thing.equals(F("ScanCanceled")))
{
if(notification > 4 && notification < 10)
{
notification = 0;
}
}
else if (thing.equals(F("TouchP")))
{
notificationVar = 0;
notification = 10;
}
else if (thing.equals(F("TouchC")))
{
notificationVar = 0;
notification = 11;
}
else if (thing.equals(F("ProspectedAsteroid")))
{
notificationVar = 0;
notification = 12;
}
else if (thing.substring(0, 5).equals(F("Cargo")))
{
notification = 1;
notificationVar = 0;
amount = thing.substring(6).toFloat();
}
else if (thing.substring(0, 1).equals("R"))
{
cRed = thing.substring(2).toFloat();
}
else if (thing.substring(0, 1).equals("G"))
{
cGreen = thing.substring(2).toFloat();
}
else if (thing.substring(0, 1).equals("B"))
{
cBlue = thing.substring(2).toFloat();
}
else if (thing.substring(0, 2).equals("SR"))
{
sRed = thing.substring(3).toFloat();
}
else if (thing.substring(0, 2).equals("SG"))
{
sGreen = thing.substring(3).toFloat();
}
else if (thing.substring(0, 2).equals("SB"))
{
sBlue = thing.substring(3).toFloat();
}
else if (thing.equals(F("Capital")))
{
notificationVar = 0;
notification = 14;
}
else if (thing.substring(0, 6).equals(F("Health")))
{
notification = 13;
notificationVar = -1;
amount = thing.substring(7).toFloat();
}
else if (thing.substring(0, 6).equals(F("HealtH")))
{
amountH = thing.substring(7).toFloat();
}
else if (thing.equals(F("ShieldsUp")))
{
notificationVar = 0;
notification = 15;
}
else if (thing.equals(F("ShieldsDown")))
{
notificationVar = 0;
notification = 16;
}
else if (thing.equals(F("OverH")))
{
notificationVar = 0;
notification = 17;
}
else if (thing.equals(F("CancelN")))
{
notificationVar = 0;
notification = 0;
}
// else if (thing.equals(F("Station")))
// {
// notificationVar = 0;
// notification = 18;
// }
else if (thing.equals(F("FSSDiscoveryScan")))
{
notificationVar = 0;
notification = 19;
}
else if (thing.equals(F("JetConeBoost")))
{
notificationVar = 0;
notification = 20;
}
else if (thing.equals(F("Scooping")))
{
mode = 15;
}
else if (thing.equals(F("MaterialCollected")))
{
notificationVar = 0;
notification = 21;
}
else if (thing.equals(F("WingJoin")))
{
notificationVar = 0;
notification = 22;
}
else if (thing.equals(F("Ounty")))
{
notificationVar = 0;
notification = 23;
}
else if (thing.equals(F("Demo")))
{
demo = !demo;
}
else if (thing.startsWith(F("AAS")))//Arrived At Star
{
oldCRed = cRed;
oldCGreen = cGreen;
oldCBlue = cBlue;
uint32_t color = colorFromClass(thing.substring(3));
Serial.println(color);
cBlue = (color)&0xFF;
cGreen = (color>>8)&0xFF;
cRed = (color>>16)&0xFF;
Serial.println(cRed);
Serial.println(cGreen);
Serial.println(cBlue);
cRedSpeed = (oldCRed-cRed)/numSteps;
cGreenSpeed = (oldCGreen-cGreen)/numSteps;
cBlueSpeed = (oldCBlue-cBlue)/numSteps;
stepCounter = numSteps+700;
}
}
void render()
{
if(stepCounter>0)
{
stepCounter--;
if(stepCounter<numSteps)
{
cRed = cRed+cRedSpeed;
cGreen = cGreen+cGreenSpeed;
cBlue = cBlue+cBlueSpeed;
}
}
else
{
if(oldCRed!=0 || oldCGreen!=0 || oldCBlue!=0)
{
cRed = oldCRed;
cGreen = oldCGreen;
cBlue = oldCBlue;
oldCRed = 0;
oldCGreen = 0;
oldCBlue = 0;
}
}
if (notification == 0)
{
if (renderMode == 0)
{
showc();
}
else if (renderMode == 1)
{
startupPulse();
}
else if (renderMode == 2)
{
loadPulse();
}
else if (renderMode == 3)
{
docked();
}
else if (renderMode == 4)
{
normalSpace();
}
else if (renderMode == 5)
{
superCruise();
}
else if (renderMode == 6)
{
hyper();
}
else if (renderMode == 7)
{
requested();
}
else if (renderMode == 8)
{
granted();
}
else if (renderMode == 9)
{
denied();
}
else if (renderMode == 10)
{
//heatWarning();
}
else if (renderMode == 11)
{
autoDock();
}
else if (renderMode == 12)
{
SRV();
}
else if (renderMode == 13)
{
starthyper();
}
else if (renderMode == 14)
{
startsuper();
}
else if (renderMode == 15)
{
scooping();
}
else if (renderMode == 16)
{
stationServices();
}
if (readyToSwitch && mode != renderMode)
{
Serial.print("Mode to ");
Serial.println(mode);
Serial.flush();
renderMode = mode;
var = 0;
var2 = 0;
var3 = 0;
}
}
else
{
Serial.println(notification);
if (notification == 1)
{
showCargo();
}
else if (notification == 2)
{
astr();
}
else if (notification == 3)
{
renderMode = 4;
mode = 4;
normalSpace();
prospect();
}
else if (notification == 4)
{
renderMode = 4;
mode = 4;
normalSpace();
collect();
}
else if (notification == 5)
{
notification = 0;
//scan(0);
}
else if (notification == 6)
{
scan(0);
}
else if (notification == 7)
{
scan(1);
}
else if (notification == 8)
{
scan(3);
}
else if (notification == 9)
{
scan(4);
}
else if (notification == 10)
{
touch(true);
}
else if (notification == 11)
{
touch(false);
}
else if (notification == 12)
{
prospected();
}
else if (notification == 13)
{
showHealth();
}
else if (notification == 14)
{
capital();
}
else if (notification == 15)
{
shieldsUp();
}
else if (notification == 16)
{
shieldsDown();
}
else if (notification == 17)
{
overHeat();
}
else if (notification == 18)
{
loadStation();
}
else if (notification == 19)
{
discoveryScan();
}
else if (notification == 20)
{
jetConeBoost();
}
else if (notification == 21)
{
material();
}
else if (notification == 22)
{
wingJoin();
}
else if (notification == 23)
{
bounty();
}
}
LEDS.show();
}
uint32_t colorToInt(uint8_t red, uint8_t green, uint8_t blue) {
return (red << 16) | (green << 8) | blue;
}
uint32_t colorFromClass(String star)
{
if(star=="O")
{
return colorToInt(165, 200, 255);
}
else if(star=="B")
{
return colorToInt(127, 165, 248);
}
else if(star=="A")
{
return colorToInt(255, 255, 255);
}
else if(star=="F")
{
return colorToInt(255, 226, 65);
}
else if(star=="G")
{
return colorToInt(255, 226, 0);
}
else if(star=="K")
{
return colorToInt(255, 127, 0);
}
else if(star=="M")
{
return colorToInt(255, 104, 74);
}
else if(star=="A_BlueWhiteSuperGiant")
{
return colorToInt(234, 238, 244);
}
else if(star=="F_WhiteSuperGiant")
{
return colorToInt(252, 240, 133);
}
else if(star=="K_OrangeGiant")
{
return colorToInt(242, 205, 97);
}
else if(star=="M_RedGiant")
{
return colorToInt(255, 104, 74);
}
else if(star=="M_RedSuperGiant")
{
return colorToInt(253, 112, 68);
}
else if(star=="AeBe")
{
return colorToInt(255, 249, 190);
}
else if(star=="TTS")
{
return colorToInt(254, 174, 92);
}
else if(star=="C")
{
return colorToInt(187, 14, 43);
}
else if(star=="CH")
{
return colorToInt(187, 14, 43);
}
else if(star=="CHd")
{
return colorToInt(187, 14, 43);
}
else if(star=="CJ")
{
return colorToInt(252, 127, 62);
}
else if(star=="CN")
{
return colorToInt(248, 159, 64);
}
else if(star=="CS")
{
return colorToInt(248, 159, 64);
}
else if(star=="MS")
{
return colorToInt(252, 144, 69);
}
else if(star=="S")
{
return colorToInt(255, 191, 88);
}
else if(star=="W")
{
return colorToInt(208, 244, 250);
}
else if(star=="WC")
{
return colorToInt(208, 244, 250);
}
else if(star=="WN")
{
return colorToInt(208, 244, 250);
}
else if(star=="WNC")
{
return colorToInt(254, 154, 78);
}
else if(star=="WO")
{
return colorToInt(208, 244, 250);
}
else if(star=="H")
{
return colorToInt(25, 25, 25);
}
else if(star=="SupermassiveBlackHole")
{
return colorToInt(25, 25, 25);
}
else if(star=="N")
{
return colorToInt(51, 107, 254);
}
else if(star.startsWith("D"))
{
return colorToInt(255, 255, 255);
}
else if(star=="L")
{
return colorToInt(255, 0, 0);
}
else if(star=="T")
{
return colorToInt(89, 13, 46);
}
else if(star=="Y")
{
return colorToInt(65, 8, 50);
}
else if(star=="X")
{
return colorToInt(218, 5, 120);
}
return 0;
}
| [
"maxfojtik@bex.net"
] | maxfojtik@bex.net |
e5cdb3440701c0db2604e9a5c0133c0c31cf211c | 63f3401b177e5b5ebb7a575edc2f9e61f0f95881 | /src/asiAlgo/interop/asiAlgo_WriteSTEPWithMeta.h | 74b5c97e01cc7f23cb7bbf9fedfaeca848a6cbd9 | [
"BSD-3-Clause",
"MIT"
] | permissive | sasobadovinac/AnalysisSitus | 09908621cf2d0dbaad4b1b78ff6c6822b71607b1 | 304d39c64258d4fcca888eb8e68144eca50e785a | refs/heads/master | 2020-06-22T22:18:20.861210 | 2019-07-21T15:56:38 | 2019-07-21T15:56:38 | 198,413,774 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,707 | h | //-----------------------------------------------------------------------------
// Created on: 28 May 2019
//-----------------------------------------------------------------------------
// Copyright (c) 2019-present, Sergey Slyadnev
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder(s) nor the
// names of all contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#ifndef asiAlgo_WriteSTEPWithMeta_h
#define asiAlgo_WriteSTEPWithMeta_h
// asiAlgo includes
#include <asiAlgo_WriteSTEPWithMetaInput.h>
// Active Data includes
#include <ActAPI_IAlgorithm.h>
// OCCT includes
#include <MoniTool_DataMapOfShapeTransient.hxx>
#include <STEPConstruct_Styles.hxx>
#include <STEPControl_Writer.hxx>
#include <TopTools_MapOfShape.hxx>
//! STEP writer enriched with possibility to write not only shapes but
//! also some metadata such as colors.
class asiAlgo_WriteSTEPWithMeta : public ActAPI_IAlgorithm
{
public:
// OCCT RTTI
DEFINE_STANDARD_RTTI_INLINE(asiAlgo_WriteSTEPWithMeta, ActAPI_IAlgorithm)
public:
asiAlgo_EXPORT
asiAlgo_WriteSTEPWithMeta(ActAPI_ProgressEntry progress = NULL,
ActAPI_PlotterEntry plotter = NULL);
asiAlgo_EXPORT
asiAlgo_WriteSTEPWithMeta(const Handle(XSControl_WorkSession)& WS,
const bool scratch = true,
ActAPI_ProgressEntry progress = NULL,
ActAPI_PlotterEntry plotter = NULL);
public:
//! Sets input data adaptor.
//! \param[in] input input data provider.
void SetInput(const Handle(asiAlgo_WriteSTEPWithMetaInput)& input)
{
m_input = input;
}
public:
asiAlgo_EXPORT void
Init(const Handle(XSControl_WorkSession)& WS,
const bool scratch = true);
asiAlgo_EXPORT IFSelect_ReturnStatus
Write(const char* filename);
asiAlgo_EXPORT bool
Transfer(const STEPControl_StepModelType mode = STEPControl_AsIs);
asiAlgo_EXPORT bool
Perform(const TCollection_AsciiString& filename);
asiAlgo_EXPORT void
SetColorMode(const bool colormode);
asiAlgo_EXPORT bool
GetColorMode() const;
protected:
asiAlgo_EXPORT bool
transfer(STEPControl_Writer& wr,
const STEPControl_StepModelType mode = STEPControl_AsIs);
asiAlgo_EXPORT bool
writeColors(const Handle(XSControl_WorkSession)& WS);
private:
void makeSTEPStyles(STEPConstruct_Styles& Styles,
const TopoDS_Shape& S,
Handle(StepVisual_StyledItem)& override,
TopTools_MapOfShape& Map,
STEPConstruct_DataMapOfAsciiStringTransient& DPDCs,
STEPConstruct_DataMapOfPointTransient& ColRGBs);
private:
STEPControl_Writer m_writer; //!< Writer (without metadata).
bool m_bColorMode; //!< Color mode (on/off).
MoniTool_DataMapOfShapeTransient m_mapCompMDGPR; //!< Auxiliary map.
//! Input data adaptor.
Handle(asiAlgo_WriteSTEPWithMetaInput) m_input;
};
#endif
| [
"sergey.slyadnev@gmail.com"
] | sergey.slyadnev@gmail.com |
a5122ddbddf48edd1ddfb3499e804d347e0771aa | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/admin/wmi/wbem/winmgmt/stdprov/stdafx.cpp | b09bf33ac5d6eae1312f798e04ead20d733ce2a9 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | cpp | /*++
Copyright (C) 1997-2001 Microsoft Corporation
Module Name:
STDAFX.CPP
Abstract:
History:
a-davj 04-Mar-97 Created.
--*/
// stdafx.cpp : source file that includes just the standard includes
// server2.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
8afe401611c0a9040f002f767f88a6970cbebd02 | 88ba8dd5ded0f860169af1117990ab2e08bbbb67 | /cr_API/API_demo/yuv_tcp_one2n_API/demo/send.cpp | 4630ac6152e3a71eeaed596a277e26e17d5235da | [] | no_license | cr-qren/AllDemo | 1c8683e10626ffff8aef3152aa1b219acf8dc510 | ffea4cba0c7ea36785ed1a9ddbbb0ff8b5e7105d | refs/heads/master | 2020-03-22T10:45:17.563453 | 2018-10-19T08:08:14 | 2018-10-19T08:08:14 | 139,924,965 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 731 | cpp | #include "../cr_tcp_one2n/cr_tcp.h"
#include "../yuvData/yuv_data.h"
int main(int argc, char *argv[])
{
Cr_tcp so("192.168.2.3", 2345, SERVER);
while(!so.isConnect())
{
so.acceptConn();
while(1)
{
YUV_PRAM yuvPram;
yuvPram.Id = 4;
yuvPram.Width = 1920;
yuvPram.Height = 1080;
yuvPram.Channel = 3;
yuvPram.BuffSize = 1920*1080*3;
YUV_DATA yuvData;
yuvData.yuvPram = &yuvPram;
yuvData.yuvBuff = alloc_yuv_mem(yuvPram.BuffSize);
int ret = send_yuv((void *)&so, &yuvData);
free_yuv_mem(yuvData.yuvBuff);
if(ret < 0)
{
fprintf(stderr, "[ Server ] tcp socket break!\n");
break;
}
}
}
return 0;
}
| [
"quan.ren@coreraim.com"
] | quan.ren@coreraim.com |
9ca9238ce2249dbeebca0f1d43c9bcea0f37470d | e48c2718df766fc317c3b816661d6439e8f56039 | /reference_code/fucked_redux_spi_multiplexer.ino | 6a6b37e8430ce458202643507ecdc80359d7ef85 | [] | no_license | dougbtv/werm-cube | f63a3c3603977f65aefc45f7f211bb27ba6ac0e7 | 1f5eb0d050d98631070d9aba90ecf6767ae7e7e2 | refs/heads/master | 2020-05-18T07:24:50.744396 | 2014-03-29T18:15:12 | 2014-03-29T18:15:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,035 | ino | // code for an 24 x 16 array (8 RGB LEDs, 16 columns) as an example
// not all code parts shown, just the highlights
// set up an array for the cathode drives
/* byte cathodeslower[ ] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0,0,0,0,0,0,0,0}; // walking 1 for lower 8 NPNs
byte cathodeshigher[ ] = {0,0,0,0,0,0,0,0,0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80}; // walking 1 for upper 8 NPNs
byte anodes1 [16]; // array to hold 1st 3rd of RGB info
byte anodes2 [16]; // array to hold 2nd 3rd of RGB info
byte anodes3 [16]; // array to hold 3rd 3rd of RGB info
byte columncount;
byte oe = 2; */
#include <SPI.h>
#include <Wire.h>
PROGMEM const int ADDRESS_CONTROLLER1 = 3;
PROGMEM const int ADDRESS_CONTROLLER2 = 4;
PROGMEM const byte PIN_OUTPUTENABLE = A0;
PROGMEM const byte PIN_SLAVESELECT = 10;
PROGMEM const char PIN_GROUND[] = {2,3,4,5,6,7,8,9};
char current_layer = 0;
char last_layer = 7;
unsigned long updateTime=0;
bool once = false;
// -------------------------------- RAIN
int count = 0;
char rain[5][5];
/* array (
array(
active,
x,
y,
max_length,
current_length,
);
); */
PROGMEM const int RAIN_ACTIVE = 0;
PROGMEM const int RAIN_X = 1;
PROGMEM const int RAIN_Y = 2;
PROGMEM const int RAIN_MAXLEN = 3;
PROGMEM const int RAIN_CURLEN = 4;
int currentdrop = 0;
char thincube[8][8];
// ------------------------------------- MODES
char mode = 2;
PROGMEM const char MODE_GAME = 1;
PROGMEM const char MODE_RAIN = 2;
// -------------------------------------- RAIN
bool flasherValue = false;
bool getBit(char number, int position) {
unsigned char bitmask = 1 << position;
return (number & bitmask) ? 1 : 0;
}
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
int cyclenum = 0;
int cyclemax = 125;
PROGMEM const int generateSegmentEvery = 10;
PROGMEM const unsigned char SIZE_Z = 8;
PROGMEM const unsigned char SIZE_X = 8;
PROGMEM const unsigned char SIZE_Y = 8;
PROGMEM const unsigned char SIZE_CUBE = 8;
PROGMEM const unsigned char BUTTON_UP = 1;
PROGMEM const unsigned char BUTTON_LEFT = 2;
PROGMEM const unsigned char BUTTON_DOWN = 3;
PROGMEM const unsigned char BUTTON_RIGHT = 4;
PROGMEM const unsigned char BUTTON_ZDOWN = 5;
PROGMEM const unsigned char BUTTON_ZUP = 6;
PROGMEM const unsigned char BUTTON_SELECT = 7;
PROGMEM const unsigned char BUTTON_START = 8;
// bool cube [SIZE_Z][SIZE_X][SIZE_Y];
PROGMEM const int SIZE_WORM = 16;
// z,x,y
class Worm {
private:
void commitVector(char,char,char); // Actually commit setting the vector based on relativity, handled by setVector.
public:
signed char segment[SIZE_WORM][3]; // What cartesian coordinates make up this worm?
char length; // How long is the worm?
signed char vector[3]; // = {0,0,-1};
signed char relativity[3]; // What's the vector relative to the player?
Worm() {}
Worm(char,char,char,char,char,char,char,char,char,char);
bool containsPoint(char,char,char,bool);
void move();
void generateSegment();
bool setVector(char); // Calculate new vector by direction - handler for commitVector.
};
class Cube {
public:
Worm playerOne;
Worm playerTwo;
// bool coords [SIZE_Z][SIZE_X][SIZE_Y];
char thincube[SIZE_Z][SIZE_X];
void transfer(char);
// void debug(signed char, Worm&, Worm&);
void plotWorm(Worm&);
void clear();
// void renderThin();
bool detectCollision(Worm&,Worm&,bool);
void loop(char,char);
//
void setPoint(bool,char,char,char);
Cube() : playerOne(0,2,3,0,0,1,1,1,1,-1), playerTwo(0,5,4,0,0,-1,1,1,-1,1) {}
// Cube();
// ~Cube(); //
// playerTwo(0,5,4,0,0,-1,1,1,-1,1);
};
Cube cube;
void Cube::setPoint(bool value, char z, char x, char y) {
// Don't set invalid points.
// But essentially allow it to have things "go out of bounds"
if (z < 0 || x < 0 || y < 0 || z > 7 || x > 7 || y > 7) {
return;
}
// Then do your bit logic.
if (value) {
// Set it true.
thincube[(int)z][(int)x] |= 1 << (int)y;
} else {
// Clear it.
thincube[(int)z][(int)x] &= ~(1 << (int)y);
}
}
void Cube::transfer(char zlayer) {
// Serial.println(zlayer, DEC);
for (int i = 0; i < 8; i++) {
SPI.transfer(thincube[zlayer][i]);
}
}
void Cube::loop(char p1_direction, char p2_direction) {
cyclenum++;
/*if (cyclenum >= cyclemax) {
exit(0);
}*/
playerOne.setVector(p1_direction);
playerTwo.setVector(p2_direction);
if (cyclenum % generateSegmentEvery == 0) {
playerOne.generateSegment();
playerTwo.generateSegment();
}
playerOne.move();
playerTwo.move();
// "Render" the cube.
// !bang
clear();
plotWorm(playerOne);
plotWorm(playerTwo);
// renderThin();
// debug(0,playerOne,playerTwo);
// Now that we moved, let's detect a collision.
// Well check one against itself, and the other player.
// And the other player against itself, and the first player.
bool pone_collide = detectCollision(playerOne,playerOne,true);
bool pone_collide_other = detectCollision(playerOne,playerTwo,false);
bool ptwo_collide = detectCollision(playerTwo,playerTwo,true);
bool ptwo_collide_other = detectCollision(playerTwo,playerOne,false);
// Now let's condense these variables into one for each condition.
if (pone_collide_other) {
pone_collide = true;
}
if (ptwo_collide_other) {
ptwo_collide = true;
}
// Now that we know who has collided, we can determine win, loss or tie.
if (pone_collide) {
if (ptwo_collide) {
// Tie.
// // cout << "It's a tie!" << endl;
// exit(0);
} else {
// Player two wins.
// // cout << "Player two wins." << endl;
// `exit(0);
}
} else {
if (ptwo_collide) {
// Player one wins.
// // cout << "Player one wins." << endl;
// exit(0);
} else {
// Game continues.
// ...
}
}
//if (pone_collision == true) {
// // cout << "PLAYER ONE COLLIDES!" << endl;
//}
}
// Tell this:
// First, what worm head am I checking?
// Then, what worm am I looking for a collision with.
// Last, is that worm, the same as the first worm??
bool Cube::detectCollision(Worm& wormhead,Worm& wormtarget,bool within_self = true) {
bool collision = false;
// So take the head of this thing, which we just forced a move on.
// And let's see if it's contained in a worm.
collision = wormtarget.containsPoint(wormhead.segment[0][0],wormhead.segment[0][1],wormhead.segment[0][2],within_self);
return collision;
}
/*
void Cube::renderThin() {
// Cycle the boolean cube and turn it into the thin cube.
// char loaf = 127;
// With the |= bitwise or operator... the format is:
// byte |= value_to_set << position
thincube[0][0] |= 1 << 0;
// printByteBinary(thincube[0][0]);
char temp = 0;
char newval = 0;
for (unsigned int z = 0; z < SIZE_Z; z++) {
for (unsigned int x = 0; x < SIZE_X; x++) {
temp = 0;
for (unsigned int y = 0; y < SIZE_Y; y++) {
newval = 0;
if (coords[z][x][y]) {
newval = 1;
}
temp |= newval << y;
}
thincube[z][x] = temp;
}
}
for (unsigned int z = 0; z < SIZE_Z; z++) {
// // cout << "Layer " << z << endl;
for (unsigned int x = 0; x < SIZE_X; x++) {
// printByteBinary(thincube[z][x]);
}
// // cout << endl;
}
}
*/
// If you don't want a specific layer, send this a -1 for the specific layer.
/*
void Cube::debug(signed char specificlayer, Worm& wormone, Worm& wormtwo) {
// char what[] = "what?";
// printIt(what);
// printInt(sizeof(cube));
char startz = 0;
char endz = SIZE_Z;
if (specificlayer > -1) {
startz = specificlayer;
endz = specificlayer+1;
}
// // cout << endl << "------------------------- Cycle " << cyclenum << endl;
for (int z = startz; z < endz; z++) {
// cout << "Layer (z-coord): " << z << endl;
// cout << endl;
for (unsigned int y = 0; y < SIZE_Y; y++) {
if (y==0) {
// cout << " 0 1 2 3 4 5 6 7" << endl;
// cout << " +----------------" << endl;
}
// cout << y << " | ";
char mark;
for (unsigned int x = 0; x < SIZE_X; x++) {
mark = 'O';
if (coords[z][x][y]) { mark = 'X'; }
// Determine if it's in worm 2...
if (wormtwo.containsPoint(z,x,y,false)) { mark = 'Y'; }
// cout << mark << " ";
}
// cout << endl;
}
}
}
*/
/*
Cube::Cube() {
// cout << "Cube constructor\n";
playerOne(0,2,3,0,0,1,1,1,1,-1);
playerTwo(0,5,4,0,0,-1,1,1,-1,1);
// Cube cube = Cube();
}*/
void Cube::plotWorm(Worm& worm) {
// Lay down the worm(s) onto the cube.
for (int i = 0; i < worm.length; i++) {
setPoint(true,worm.segment[i][0],worm.segment[i][1],worm.segment[i][2]);
}
}
void Cube::clear() {
for (int z = 0; z < 8; z++) {
for (int x = 0; x < 8; x++) {
thincube[z][x] = 0;
}
}
}
Worm::Worm (char z,char x,char y,char vz,char vx, char vy,char initlen,char rel_z, char rel_x, char rel_y) {
// // cout << "Init worm! " << z << "," << x << "," << y << endl;
// Set the first segment.
segment[0][0] = z;
segment[0][1] = x;
segment[0][2] = y;
// Set the relativity
relativity[0] = rel_z; // 1; // Same for all players, going "up" is positive.
relativity[1] = rel_x; // 1; // X going "right" is positive.
relativity[2] = rel_y; // -1; // Y going "up" is negative.
// Set the initial vector.
vector[0] = vz;
vector[1] = vx;
vector[2] = vy;
// Set the length.
length = initlen;
// // cout << (int)segment[0][0] << ",";
// // cout << (int)segment[0][1] << ",";
// // cout << (int)segment[0][2] << "------------------------ WHAT" << endl;
// // cout << segment << "what?" << endl;
}
bool Worm::containsPoint(char z, char x, char y, bool myself) {
bool contains = false;
int start_i = 0;
// In the case we're checking against ourself, we don't wanna check our own head.
if (myself) {
start_i++;
}
for (int i = start_i; i < length; i++) {
if (segment[i][0] == z && segment[i][1] == x && segment[i][2] == y) {
// // cout << "----------- COLLISION! --------------------" << endl;
contains = true;
break;
}
}
return contains;
}
void Worm::generateSegment() {
// Ok, we're ready to generate a new segment.
// Should be as easy as adding to the length.
if (length < (SIZE_WORM-1)) {
length++;
}
}
void Worm::move() {
// Ok go ahead and move that worm along.
// // cout << "-=-=-=-=-= " << sizeof(worm) << endl;
// Move it's segments down to the ends.
for (int i = (SIZE_WORM-1); i > 0; i--) {
segment[i][0] = segment[i-1][0];
segment[i][1] = segment[i-1][1];
segment[i][2] = segment[i-1][2];
}
// Give it a new head, based on it's vector.
segment[0][0] += vector[0];
segment[0][1] += vector[1];
segment[0][2] += vector[2];
// But! You gotta flip it back to the 0th position or the Max-th position if it goes outside the bounds.
for (int i = 0; i < 3; i++) { // We'll magic-number the 3. It's a 3d cube, I'm hard coding that.
if (segment[0][i] >= SIZE_CUBE) {
segment[0][i] = 0;
}
if (segment[0][i] < 0) {
segment[0][i] = SIZE_CUBE-1;
}
}
}
// ---------------------- setVector
// --- Takes a direction as input
// --- and computes new vector.
// --- Returns false if unchanged.
// --- True if vector is changed.
void Worm::commitVector(char z, char x, char y) {
// If the current vector is in the same axis...
// We can't do that, so just return without a move
if (z != 0 && vector[0] != 0) { return; }
if (x != 0 && vector[1] != 0) { return; }
if (y != 0 && vector[2] != 0) { return; }
vector[0] = z * relativity[0];
vector[1] = x * relativity[1];
vector[2] = y * relativity[2];
}
bool Worm::setVector(char indirection) {
// If it's a null direction, we'll return false [e.g. nothing changed]
if (indirection == 0) {
return false;
}
//. signed char newdir = 0;
switch (indirection) {
case BUTTON_UP:
commitVector(0,0,1);
break;
case BUTTON_DOWN:
commitVector(0,0,-1);
break;
case BUTTON_LEFT:
commitVector(0,-1,0);
break;
case BUTTON_RIGHT:
commitVector(0,1,0);
break;
case BUTTON_ZUP:
commitVector(1,0,0);
break;
case BUTTON_ZDOWN:
commitVector(-1,0,0);
break;
}
return true;
}
/*
void printIt(char msg[]) {
// cout << msg << endl;
}
void printInt(int inbound) {
printf("%02d",inbound);
}
*/
char getInput(bool playerone = true) {
char in;
if (playerone) {
Wire.requestFrom(ADDRESS_CONTROLLER1,1);
while (Wire.available()) {
in = Wire.read();
// Serial.print("Controller 1: ");
// Serial.println(controller1);
}
} else {
Wire.requestFrom(ADDRESS_CONTROLLER2,1);
while (Wire.available()) {
in = Wire.read();
// Serial.print("Controller 2: ");
// Serial.println(controller2);
}
}
// cout << "[Player " << player_text << "] Direction:";
// cin >> in;
return in;
}
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
// ------------------------------------------------------------------------------ Werm
void printcube() {
for (int z = 0; z < 8; z++) {
// cout << "Z Layer: " << z << " ------------------ " << endl;
Serial.print("-------------------------------- Z layer: ");
Serial.println(z);
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
//setCube(thincube,true,z,x,y);
bool mybit = getBit(cube.thincube[z][x],y);
if (mybit) {
Serial.print("1");
} else {
Serial.print("0");
}
}
Serial.println();
// cout << endl;
}
Serial.println();
// cout << endl;
}
}
void rainAnimation() {
// Serial.println("check.");
/* flasherValue = !flasherValue;
digitalWrite(A1,flasherValue); */
// set bit.
// thincube[z][x] |= 1 << y;
// So we have to cycle each raindrop, and nip it's top layer if it's hit it's maximum length.
for (int i = 0; i < 5; i++) {
// cout << "iteration: " << i << ": active: " << (int)rain[i][RAIN_ACTIVE] << endl;
if (rain[i][RAIN_ACTIVE]) {
rain[i][RAIN_CURLEN]++;
if (rain[i][RAIN_CURLEN] > rain[i][RAIN_MAXLEN]) {
// Now nips it's top layer back to zero.
//cube.setPoint(false,7,rain[i][RAIN_X],rain[i][RAIN_Y]);
cube.thincube[7][(int)rain[i][RAIN_X]] &= ~(1 << (int)rain[i][RAIN_Y]);
// cout << (int)rain[i][RAIN_X] << " , " << (int)rain[i][RAIN_Y] << " <-------------" << endl;
// printcube();
rain[i][RAIN_ACTIVE] = 0;
// cout << "!!!!!!!!!!!!!!!!!!!! nipped..." << endl;
}
}
}
// Now "rain the cube" by copying the layer from the one above.
// namely, omitting the top layer.
for (int z = 0; z < 7; z++) {
for (int x = 0; x < 8; x++) {
cube.thincube[z][x] = cube.thincube[z+1][x];
}
}
// ------------ CREATE NEW RAINDROP.
if (count == 0 || count % 4 == 0) {
// Make a new drop if there isn't one set on this.
if (!rain[currentdrop][RAIN_ACTIVE]) {
// cout << "current drop: " << currentdrop << endl;
rain[currentdrop][RAIN_X] = (unsigned char)rand() % 7;
rain[currentdrop][RAIN_Y] = (unsigned char)rand() % 7;
rain[currentdrop][RAIN_MAXLEN] = (rand() % 5) + 2;
rain[currentdrop][RAIN_CURLEN] = 1;
rain[currentdrop][RAIN_ACTIVE] = 1;
// int y = rand() % 7;
// cout << (int)rain[currentdrop][RAIN_X] << ", " << (int)rain[currentdrop][RAIN_Y] << endl;
// cout << (int)rain[currentdrop][RAIN_MAXLEN] << " : maxlen" << endl;
// cout << (int)rain[currentdrop][RAIN_CURLEN] << " : maxlen" << endl;
// cube.setPoint(true,7,rain[currentdrop][RAIN_X],rain[currentdrop][RAIN_Y]);
cube.thincube[7][(int)rain[currentdrop][RAIN_X]] |= 1 << (int)rain[currentdrop][RAIN_Y];
}
currentdrop++;
if (currentdrop >= 5) {
currentdrop = 0;
}
}
// cout << "cool" << endl;
count++;
// cout << " LOOP MARKER ------------------------------------ > " << count << endl;
if (count > 10) {
printcube();
Serial.println();
delay(2000);
exit(0);
}
}
// --------------------------------------- END RAIN
void setup(){
Serial.begin(9600);
Wire.begin();
// set the slaveSelectPin as an output:
pinMode(PIN_SLAVESELECT, OUTPUT);
pinMode(PIN_OUTPUTENABLE, OUTPUT);
digitalWrite(PIN_OUTPUTENABLE, LOW);
SPI.begin();
Serial.println("did we do this?");
// set your blinker...
pinMode(A1, OUTPUT);
// this is your ground/transistor array.
for (int i = 0; i < 8; i++) {
pinMode(PIN_GROUND[i], OUTPUT);
}
for (int i = 0; i < 8; i++) {
digitalWrite(PIN_GROUND[i], LOW);
}
// Serial.println("are we getting killed...");
byte test = 0x00;
for (int i = 0; i < 8; i++) {
SPI.transfer(test);
}
// once = true;
Serial.println("finished that.");
}
long next_update = 0;
long next_animation = 0;
const long interval = 1500;
// looked good for rain
// const long animation_interval = 50000;
long animation_interval = 90000;
byte testing = 0xbb;
void loop(){
// delay(2000);
// Serial.println("run marker...");
if (!once) {
}
/* digitalWrite(A1, HIGH); // set the LED on
delay(500); // wait for a second
digitalWrite(A1, LOW); // set the LED off
delay(500); // wait for a second */
if (next_animation <= micros()) {
char p1_direction;// = getInput();
char p2_direction; // = getInput(false);
switch (mode) {
case MODE_GAME:
p1_direction = getInput();
p2_direction = getInput(false);
cube.loop(p1_direction,p2_direction);
break;
case MODE_RAIN:
rainAnimation();
// animation_interval = 250000;
break;
}
next_animation += animation_interval;
/* testing++;
for (int i = 0; i < 8; i++) {
SPI.transfer(testing);
}
next_animation += animation_interval; */
// once = true;
// Serial.println("finished that.");
}
if (next_update <= micros()) {
digitalWrite(PIN_OUTPUTENABLE, HIGH);
// Turn off last layer.
digitalWrite(PIN_GROUND[last_layer],LOW);
// Re-enable.
digitalWrite(PIN_OUTPUTENABLE, LOW);
// send the data.
// cube.transfer(current_layer);
for (int v = 0; v < 8; v++) {
SPI.transfer(cube.thincube[current_layer][v]);
}
// Turn on this layer.
digitalWrite(PIN_GROUND[current_layer],HIGH);
// Set that we're the last layer now.
last_layer = current_layer;
// Now increment the layer, or zip back to 0.
current_layer++;
if (current_layer >= 8) {
current_layer = 0;
}
// When's our next update?
next_update = micros() + interval;
}
}
| [
"douglaskippsmith@gmail.com"
] | douglaskippsmith@gmail.com |
703ae5800888718908a260e06ab7d6e2d7cbe8fd | 42d4d2611ff03f0eac0ab2af4458b80f0a107d0d | /ParadigmEditor/Source/Scene/CameraMoves.cpp | 0cb2eac0fb4696d241863926d90faa94f725781a | [
"MIT"
] | permissive | Nobuna-no/Paradigm-Engine | 68d1c635d3162d09371c042ea95ca4767da11ce6 | 12bfd83da925b3c72e27ac6d441577ff48b0535e | refs/heads/master | 2020-07-04T04:46:44.196267 | 2019-08-14T15:48:59 | 2019-08-14T15:48:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,932 | cpp | #include <EngineFramework\Processor\FCustomBehaviourProcessor.h>
#include <EngineFramework\MetaGear\LowRenderer\FMetaCamera.h>
#include <Include/Scene/CameraMoves.h>
#include <Physics\FTransform.h>
#include <FParadigmEngine.h>
namespace ParadigmEditor
{
void CameraMoves::LateUpdate()
{
ParadigmEngine::EngineFramework::MetaGear::LowRenderer::UMetaCamera* cam = GearedUnit->GetGear<ParadigmEngine::EngineFramework::MetaGear::LowRenderer::UMetaCamera>();
#ifndef _PARADIGM_EDITOR
if (PARADIGM_CONTEXT->IsFocusOn(cam->DisplayTarget))
#endif
{
UMetaTransform* tr = GearedUnit->GetTransform();
float forward = 0;
if (PARADIGM_INPUT->IsKeyDown(cam->DisplayTarget, EKeyCode::W))
forward = 1;
else if (PARADIGM_INPUT->IsKeyDown(cam->DisplayTarget, EKeyCode::S))
forward = -1;
FVector3 velocity = tr->Forward() * forward;
float right = 0;
if (PARADIGM_INPUT->IsKeyDown(cam->DisplayTarget, EKeyCode::D))
right = 1;
else if (PARADIGM_INPUT->IsKeyDown(cam->DisplayTarget, EKeyCode::A))
right = -1;
velocity = velocity + tr->Rightward() * right;
float speed = m_MovementSpeed;
if (PARADIGM_INPUT->IsKeyDown(cam->DisplayTarget, EKeyCode::LeftShift))
speed *= m_SpeedMultiplier;
tr->Position = tr->Position + (speed * velocity * PARADIGM.Time.GetDeltaTime());
UAxis axis = PARADIGM_INPUT->GetAxis(cam->DisplayTarget, EAxisCode::Mouse);
if (PARADIGM_INPUT->IsKeyDown(cam->DisplayTarget, EKeyCode::Mouse_RightClick))
{
PARADIGM_INPUT->SetCursorCaptureMode(cam->DisplayTarget, ECursorCaptureMode::MouseCaptureMode_Locked);
PARADIGM_INPUT->SetActiveCursor(false);
float turnL = (axis.X - m_MouseBuffer.X) * m_RotationSpeed;// * PARADIGM.Time.GetDeltaTime();
float LookU = (axis.Y - m_MouseBuffer.Y) * m_RotationSpeed;// * PARADIGM.Time.GetDeltaTime();
//FPrint::Print("Axis { X : " + FString::ToString(turnL) + "; Y : " + FString::ToString(LookU) + "}");
m_Rotations = FVector3(LookU, turnL , 0) + m_Rotations;
tr->Rotation = FQuaternion::FromEulerAngles(m_Rotations);
}
else if (PARADIGM_INPUT->IsKeyDown(cam->DisplayTarget, EKeyCode::Mouse_LeftClick))
{
float horizontalAngle = cam->FieldOfView * 0.5f * axis.X;
float verticalAngle = cam->FieldOfView * 0.5f * axis.Y;
FVector3 direction = cam->GearedUnit->GetTransform()->Forward() * FQuaternion::FromEulerAngles(verticalAngle, horizontalAngle, 0);
auto result = PARADIGM_PHYSICS.Raycast((UVector3)cam->GearedUnit->GetTransform()->Position, (UVector3)(direction.Normalized() * m_PickingDistance), true);
if (result.Count())
{
UMetaEntity* target = result[0].entity;
}
}
//#ifndef _PARADIGM_EDITOR
else
{
PARADIGM_INPUT->SetCursorCaptureMode(cam->DisplayTarget, ECursorCaptureMode::MouseCaptureMode_Free);
PARADIGM_INPUT->SetActiveCursor(true);
}
//#endif
m_MouseBuffer.X = axis.X;
m_MouseBuffer.Y = axis.Y;
}
}
} | [
"morgansb.hoarau@gmail.com"
] | morgansb.hoarau@gmail.com |
60859416990bdb5b6358d2b37777b108d2aa09b4 | 2362668c14383c0b2eda5b0cc087f282dfa93af4 | /ABC-C/107.cpp | 363a75d1e5ee69a70ac84ed38c215010394d5c1c | [] | no_license | 50m-regent/kyopro | e7a46280e97ae352b9ab1eb4283678c0b8c9175f | 0656c567a4043bfe6ee369238e1399b6f3f17ca3 | refs/heads/master | 2021-06-24T21:59:08.116700 | 2020-11-23T04:25:30 | 2020-11-23T04:25:30 | 171,856,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,657 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<vvll> vvvll;
typedef vector<string> vstr;
typedef pair<ll, ll> pll;
typedef vector<pll> vp;
typedef map<string, ll> mstrll;
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fir first
#define sec second
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define _overload3(_1, _2, _3, name, ...) name
#define _rep(i, n) repi(i, 0, n)
#define repi(i, a, b) for(ll i = ll(a); i < ll(b); i++)
#define rep(...) _overload3(__VA_ARGS__, repi, _rep,)(__VA_ARGS__)
#define each(i, n) for(auto&& i: n)
#define out(x) cout << x
#define print(x) cout << x << '\n'
#define debug(x) cerr << #x << ": " << x << '\n'
ll gcd(ll a, ll b){
return b != 0 ? gcd(b, a % b) : a;
}
ll lcm(ll a, ll b){
return a * b / gcd(a, b);
}
const ll INF = 1e16;
const ll MOD = 1e9 + 7;
ll a, b, c, n, m, x, y, z, w, h, ans = 0, cnt = 0, mx = 0, mn = INF;
string s, t;
vll dx = {-1, 0, 1, 0}, dy = {0, -1, 0, 1};
//vll dx = {-1, 0, 1, -1, 1, -1, 0, 1}, dy = {-1, -1, -1, 0, 0, 1, 1, 1};
signed main(){
cin.tie(0);
ios::sync_with_stdio(false);
while(cin >> n >> m){
vll list;
mn = INF;
rep(i, n){
cin >> a;
list.pb(a);
}
list.pb(0);
sort(all(list));
rep(i, n - m + 1){
cnt = abs(list[i] - list[i + m]) + min(abs(list[i]), abs(list[i + m]));
mins(mn, cnt);
}
print(mn);
}
}
| [
"32361219+50m-regent@users.noreply.github.com"
] | 32361219+50m-regent@users.noreply.github.com |
9715b5bdac3adb1ce492e4b0eb91cf295a5f279b | c354de217b9da9f38e98c392f3d20bcc20dbf5cc | /rotors_gazebo/src/waypoint_publisher_new_automation.cpp | b12d8327d98e1d02b78adc03493069e24aa82919 | [] | no_license | calebh94/rotors_simulator | 51b17636bf8301475410867ab0ea779e270ea52a | 4e419d562a99f01e6f34f1aa215b8c65a712608b | refs/heads/master | 2021-06-10T22:49:28.929289 | 2021-03-12T15:37:03 | 2021-03-12T15:37:03 | 151,878,041 | 0 | 0 | null | 2020-09-22T12:50:02 | 2018-10-06T20:15:30 | C++ | UTF-8 | C++ | false | false | 5,949 | cpp | /*
* Copyright 2015 Fadri Furrer, ASL, ETH Zurich, Switzerland
* Copyright 2015 Michael Burri, ASL, ETH Zurich, Switzerland
* Copyright 2015 Mina Kamel, ASL, ETH Zurich, Switzerland
* Copyright 2015 Janosch Nikolic, ASL, ETH Zurich, Switzerland
* Copyright 2015 Markus Achtelik, ASL, ETH Zurich, Switzerland
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <iostream>
#include <tf/transform_broadcaster.h>
#include <angles/angles.h>
#include <std_msgs/String.h>
#include <sstream>
#include <Eigen/Core>
#include <mav_msgs/conversions.h>
#include <mav_msgs/default_topics.h>
#include <ros/ros.h>
#include <geometry_msgs/Pose.h>
#include <trajectory_msgs/MultiDOFJointTrajectory.h>
using namespace std;
double original_yaw, original_yaw_deg;
double new_x, new_y, new_z, new_yaw;
string img_proc_status;
class WaypointWithTime {
public:
WaypointWithTime()
: yaw(0.0) {
}
WaypointWithTime(float x, float y, float z, float _yaw)
: position(x, y, z), yaw(_yaw) {
}
Eigen::Vector3d position;
double yaw;
};
void procCallback (const std_msgs::String::ConstPtr& msg) {
if (msg->data == "finished") {
img_proc_status = "finished";
ROS_INFO("image process: %s", img_proc_status.c_str());
}
}
// main code
int main(int argc, char** argv) {
ros::init(argc, argv, "waypoint_landing_detection_publisher");
ros::NodeHandle nh;
ros::Publisher trajectory_pub = nh.advertise<trajectory_msgs::MultiDOFJointTrajectory>(mav_msgs::default_topics::COMMAND_TRAJECTORY, 10);
ros::Publisher detector_switch_pub = nh.advertise<std_msgs::String>("/switch_update", 10);
ros::Subscriber img_proc_status_sub;
ROS_INFO("Started waypoint_publisher_new_automation.");
ros::V_string args;
ros::removeROSArgs(argc, argv, args);
std::vector<WaypointWithTime> waypoints;
const float DEG_2_RAD = M_PI / 180.0;
double input_pose_x, input_pose_y, input_pose_z;
double desired_yaw;
trajectory_msgs::MultiDOFJointTrajectory trajectory_msg;
trajectory_msg.header.stamp = ros::Time::now();
input_pose_x = std::stof(args.at(1));
input_pose_y = std::stof(args.at(2));
input_pose_z = std::stof(args.at(3));
desired_yaw = std::stof(args.at(4)) * DEG_2_RAD;
std::ifstream wp_file(args.at(5).c_str());
if (wp_file.is_open()) {
double x, y, z, yaw;
// Only read complete waypoints.
while (wp_file >> x >> y >> z >> yaw) {
waypoints.push_back(WaypointWithTime(x, y, z, yaw * DEG_2_RAD));
}
wp_file.close();
ROS_INFO("Read %d waypoints.", (int) waypoints.size());
} else {
ROS_ERROR_STREAM("Unable to open poses file: " << args.at(5));
return -1;
}
original_yaw = desired_yaw;
original_yaw_deg = std::stof(args.at(4));
Eigen::Vector3d desired_position(input_pose_x, input_pose_y, input_pose_z);
mav_msgs::msgMultiDofJointTrajectoryFromPositionYaw(desired_position, desired_yaw, &trajectory_msg);
while (trajectory_pub.getNumSubscribers() == 0 && ros::ok()) {
ROS_INFO("There is no subscriber available, trying again in 1 second.");
ros::Duration(1.0).sleep();
}
ROS_INFO("Publishing waypoint ON NAMESPACE %s: [%f, %f, %f].", nh.getNamespace().c_str(), desired_position.x(), desired_position.y(), desired_position.z(), original_yaw_deg);
trajectory_pub.publish(trajectory_msg);
ROS_INFO("Begin autonomous operation.");
// turn OFF the landing mark detector
std_msgs::String msg_2;
std::stringstream ss_2;
ss_2 << "off";
msg_2.data = ss_2.str();
detector_switch_pub.publish(msg_2);
ros::Duration(1.0).sleep();
ROS_INFO("Detection switch: OFF.");
for (size_t i = 0; i < waypoints.size(); ++i) {
ROS_INFO("Start the Image Processing.");
ROS_INFO("Detection switch: ON.");
// turn ON the landing mark detector switch
std_msgs::String msg_3;
std::stringstream ss_3;
ss_3 << "on";
msg_3.data = ss_3.str();
detector_switch_pub.publish(msg_3);
ros::Duration(1.0).sleep();
bool img_proc = true;
while (img_proc) {
img_proc_status_sub = nh.subscribe("/process_status", 1, procCallback);
ros::spinOnce();
if (img_proc_status == "finished") {
img_proc = false;
}
}
// update the waypoints to the new x, y, z, and yaw
WaypointWithTime& wp = waypoints[i];
new_x = wp.position.x();
new_y = wp.position.y();
new_z = wp.position.z();
new_yaw = wp.yaw;
ros::Duration(1.0).sleep();
// turn OFF the landing mark detector switch
std_msgs::String msg_4;
std::stringstream ss_4;
ss_4 << "off";
msg_4.data = ss_4.str();
detector_switch_pub.publish(msg_4);
ros::Duration(1.0).sleep();
ROS_INFO("Detection switch: OFF.");
Eigen::Vector3d desired_position_new(new_x, new_y, new_z);
mav_msgs::msgMultiDofJointTrajectoryFromPositionYaw(desired_position_new, new_yaw, &trajectory_msg);
// Wait for some time to create the ros publisher.
ros::Duration(1.0).sleep();
ROS_INFO("Publishing waypoint on namespace %s: [%f, %f, %f, %f].", nh.getNamespace().c_str(),desired_position_new.x(),desired_position_new.y(),desired_position_new.z(),new_yaw);
trajectory_pub.publish(trajectory_msg);
double delay_time = 1.0;
ROS_INFO("Wait for %f seconds for drone fly to the new waypoint.", delay_time);
ros::Duration(1.0).sleep();
}
// ros::spinOnce();
ros::shutdown();
return 0;
}
| [
"charris92@gatech.edu"
] | charris92@gatech.edu |
c8fd1b88cc781430c275309e0419d185c80f4e26 | 8afb02ae2423bfa907bbd17311bcc4a8d3debb0f | /iropt.h | c13d0e71e5f4e6fef9003c1ec55a5efe055b6f63 | [] | no_license | jockm/smallnet | 13c9f33ba200e89412fe3477000d8bfbde8c9b89 | a5fcf5943f9e8e47f0f80b6bd60da4a9032e8b60 | refs/heads/master | 2020-03-26T12:51:37.406033 | 2012-07-27T15:16:44 | 2012-07-27T15:16:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | h | #pragma once
#include "ir.h"
namespace IR {
class IOptimization {
public:
virtual bool optimize(Prog *prog) = 0;
};
class Optimizator {
public:
void optimize(Prog *prog);
};
}
| [
"samsaga2@gmail.com"
] | samsaga2@gmail.com |
42b916aa37d4ed85489a262f15a95f58c5f29dfb | 96ccf2b290d2a289d2f5173a71f58173d457bbf1 | /code_analyser/llvm/tools/clang/lib/ARCMigrate/ObjCMT.cpp | 35739f1f216c872655c32e86ed282c5291f60bff | [
"NCSA"
] | permissive | ProframFiles/cs410-octo-nemesis | b08244b741cb489392ee167afcf1673f41e493d1 | b14e565f32ad401ece41c58d8d3e0bba8c351041 | refs/heads/master | 2016-09-15T19:55:30.173078 | 2013-11-22T10:49:50 | 2013-11-22T10:49:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,956 | cpp | //===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Transforms.h"
#include "clang/ARCMigrate/ARCMTActions.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/FileManager.h"
#include "clang/Edit/Commit.h"
#include "clang/Edit/EditedSource.h"
#include "clang/Edit/EditsReceiver.h"
#include "clang/Edit/Rewriters.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/MultiplexConsumer.h"
#include "clang/Lex/PPConditionalDirectiveRecord.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
#include "clang/AST/Attr.h"
#include "llvm/ADT/SmallString.h"
using namespace clang;
using namespace arcmt;
using namespace ento::objc_retain;
namespace {
class ObjCMigrateASTConsumer : public ASTConsumer {
enum CF_BRIDGING_KIND {
CF_BRIDGING_NONE,
CF_BRIDGING_ENABLE,
CF_BRIDGING_MAY_INCLUDE
};
void migrateDecl(Decl *D);
void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCInterfaceDecl *D);
void migrateProtocolConformance(ASTContext &Ctx,
const ObjCImplementationDecl *ImpDecl);
void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
const TypedefDecl *TypedefDcl);
void migrateMethods(ASTContext &Ctx, ObjCContainerDecl *CDecl);
void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
ObjCMethodDecl *OM);
bool migrateProperty(ASTContext &Ctx, ObjCInterfaceDecl *D, ObjCMethodDecl *OM);
void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
ObjCMethodDecl *OM,
ObjCInstanceTypeFamily OIT_Family = OIT_None);
void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
const FunctionDecl *FuncDecl, bool ResultAnnotated);
void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
void AnnotateImplicitBridging(ASTContext &Ctx);
CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
const FunctionDecl *FuncDecl);
void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
void migrateAddMethodAnnotation(ASTContext &Ctx,
const ObjCMethodDecl *MethodDecl);
public:
std::string MigrateDir;
bool MigrateLiterals;
bool MigrateSubscripting;
bool MigrateProperty;
bool MigrateReadonlyProperty;
unsigned FileId;
OwningPtr<NSAPI> NSAPIObj;
OwningPtr<edit::EditedSource> Editor;
FileRemapper &Remapper;
FileManager &FileMgr;
const PPConditionalDirectiveRecord *PPRec;
Preprocessor &PP;
bool IsOutputFile;
llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
ObjCMigrateASTConsumer(StringRef migrateDir,
bool migrateLiterals,
bool migrateSubscripting,
bool migrateProperty,
bool migrateReadonlyProperty,
FileRemapper &remapper,
FileManager &fileMgr,
const PPConditionalDirectiveRecord *PPRec,
Preprocessor &PP,
bool isOutputFile = false)
: MigrateDir(migrateDir),
MigrateLiterals(migrateLiterals),
MigrateSubscripting(migrateSubscripting),
MigrateProperty(migrateProperty),
MigrateReadonlyProperty(migrateReadonlyProperty),
FileId(0), Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
IsOutputFile(isOutputFile) { }
protected:
virtual void Initialize(ASTContext &Context) {
NSAPIObj.reset(new NSAPI(Context));
Editor.reset(new edit::EditedSource(Context.getSourceManager(),
Context.getLangOpts(),
PPRec));
}
virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
migrateDecl(*I);
return true;
}
virtual void HandleInterestingDecl(DeclGroupRef DG) {
// Ignore decls from the PCH.
}
virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
}
virtual void HandleTranslationUnit(ASTContext &Ctx);
};
}
ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
StringRef migrateDir,
bool migrateLiterals,
bool migrateSubscripting,
bool migrateProperty,
bool migrateReadonlyProperty)
: WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
MigrateProperty(migrateProperty),
MigrateReadonlyProperty(migrateReadonlyProperty),
CompInst(0) {
if (MigrateDir.empty())
MigrateDir = "."; // user current directory if none is given.
}
ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) {
PPConditionalDirectiveRecord *
PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
CompInst->getPreprocessor().addPPCallbacks(PPRec);
ASTConsumer *
WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
MigrateLiterals,
MigrateSubscripting,
MigrateProperty,
MigrateReadonlyProperty,
Remapper,
CompInst->getFileManager(),
PPRec,
CompInst->getPreprocessor());
ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
return new MultiplexConsumer(Consumers);
}
bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
/*ignoreIfFilesChanges=*/true);
CompInst = &CI;
CI.getDiagnostics().setIgnoreAllWarnings(true);
return true;
}
namespace {
class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
ObjCMigrateASTConsumer &Consumer;
ParentMap &PMap;
public:
ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
: Consumer(consumer), PMap(PMap) { }
bool shouldVisitTemplateInstantiations() const { return false; }
bool shouldWalkTypesOfTypeLocs() const { return false; }
bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
if (Consumer.MigrateLiterals) {
edit::Commit commit(*Consumer.Editor);
edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Consumer.Editor->commit(commit);
}
if (Consumer.MigrateSubscripting) {
edit::Commit commit(*Consumer.Editor);
edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
Consumer.Editor->commit(commit);
}
return true;
}
bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
// Do depth first; we want to rewrite the subexpressions first so that if
// we have to move expressions we will move them already rewritten.
for (Stmt::child_range range = E->children(); range; ++range)
if (!TraverseStmt(*range))
return false;
return WalkUpFromObjCMessageExpr(E);
}
};
class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
ObjCMigrateASTConsumer &Consumer;
OwningPtr<ParentMap> PMap;
public:
BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
bool shouldVisitTemplateInstantiations() const { return false; }
bool shouldWalkTypesOfTypeLocs() const { return false; }
bool TraverseStmt(Stmt *S) {
PMap.reset(new ParentMap(S));
ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
return true;
}
};
}
void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
if (!D)
return;
if (isa<ObjCMethodDecl>(D))
return; // Wait for the ObjC container declaration.
BodyMigrator(*this).TraverseDecl(D);
}
static void append_attr(std::string &PropertyString, const char *attr) {
PropertyString += ", ";
PropertyString += attr;
}
static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
const ObjCMethodDecl *Setter,
const NSAPI &NS, edit::Commit &commit,
unsigned LengthOfPrefix) {
ASTContext &Context = NS.getASTContext();
std::string PropertyString = "@property(nonatomic";
std::string PropertyNameString = Getter->getNameAsString();
StringRef PropertyName(PropertyNameString);
if (LengthOfPrefix > 0) {
PropertyString += ", getter=";
PropertyString += PropertyNameString;
}
// Property with no setter may be suggested as a 'readonly' property.
if (!Setter)
append_attr(PropertyString, "readonly");
// Short circuit properties that contain the name "delegate" or "dataSource",
// or have exact name "target" to have unsafe_unretained attribute.
if (PropertyName.equals("target") ||
(PropertyName.find("delegate") != StringRef::npos) ||
(PropertyName.find("dataSource") != StringRef::npos))
append_attr(PropertyString, "unsafe_unretained");
else if (Setter) {
const ParmVarDecl *argDecl = *Setter->param_begin();
QualType ArgType = Context.getCanonicalType(argDecl->getType());
Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
bool RetainableObject = ArgType->isObjCRetainableType();
if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
if (const ObjCObjectPointerType *ObjPtrTy =
ArgType->getAs<ObjCObjectPointerType>()) {
ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
if (IDecl &&
IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
append_attr(PropertyString, "copy");
else
append_attr(PropertyString, "retain");
}
} else if (propertyLifetime == Qualifiers::OCL_Weak)
// TODO. More precise determination of 'weak' attribute requires
// looking into setter's implementation for backing weak ivar.
append_attr(PropertyString, "weak");
else if (RetainableObject)
append_attr(PropertyString, "retain");
}
PropertyString += ')';
QualType RT = Getter->getResultType();
if (!isa<TypedefType>(RT)) {
// strip off any ARC lifetime qualifier.
QualType CanResultTy = Context.getCanonicalType(RT);
if (CanResultTy.getQualifiers().hasObjCLifetime()) {
Qualifiers Qs = CanResultTy.getQualifiers();
Qs.removeObjCLifetime();
RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
}
}
PropertyString += " ";
PropertyString += RT.getAsString(Context.getPrintingPolicy());
PropertyString += " ";
if (LengthOfPrefix > 0) {
// property name must strip off "is" and lower case the first character
// after that; e.g. isContinuous will become continuous.
StringRef PropertyNameStringRef(PropertyNameString);
PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
PropertyNameString = PropertyNameStringRef;
std::string NewPropertyNameString = PropertyNameString;
bool NoLowering = (isUppercase(NewPropertyNameString[0]) &&
NewPropertyNameString.size() > 1 &&
isUppercase(NewPropertyNameString[1]));
if (!NoLowering)
NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
PropertyString += NewPropertyNameString;
}
else
PropertyString += PropertyNameString;
SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
Selector GetterSelector = Getter->getSelector();
SourceLocation EndGetterSelectorLoc =
StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
EndGetterSelectorLoc),
PropertyString);
if (Setter) {
SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
// Get location past ';'
EndLoc = EndLoc.getLocWithOffset(1);
commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
}
return true;
}
void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
ObjCInterfaceDecl *D) {
for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
M != MEnd; ++M) {
ObjCMethodDecl *Method = (*M);
if (!migrateProperty(Ctx, D, Method))
migrateNsReturnsInnerPointer(Ctx, Method);
}
}
static bool
ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
const ObjCImplementationDecl *ImpDecl,
const ObjCInterfaceDecl *IDecl,
ObjCProtocolDecl *Protocol) {
// In auto-synthesis, protocol properties are not synthesized. So,
// a conforming protocol must have its required properties declared
// in class interface.
bool HasAtleastOneRequiredProperty = false;
if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
E = PDecl->prop_end(); P != E; ++P) {
ObjCPropertyDecl *Property = *P;
if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
continue;
HasAtleastOneRequiredProperty = true;
DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
if (R.size() == 0) {
// Relax the rule and look into class's implementation for a synthesize
// or dynamic declaration. Class is implementing a property coming from
// another protocol. This still makes the target protocol as conforming.
if (!ImpDecl->FindPropertyImplDecl(
Property->getDeclName().getAsIdentifierInfo()))
return false;
}
else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
if ((ClassProperty->getPropertyAttributes()
!= Property->getPropertyAttributes()) ||
!Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
return false;
}
else
return false;
}
// At this point, all required properties in this protocol conform to those
// declared in the class.
// Check that class implements the required methods of the protocol too.
bool HasAtleastOneRequiredMethod = false;
if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
if (PDecl->meth_begin() == PDecl->meth_end())
return HasAtleastOneRequiredProperty;
for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
MEnd = PDecl->meth_end(); M != MEnd; ++M) {
ObjCMethodDecl *MD = (*M);
if (MD->isImplicit())
continue;
if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
continue;
DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
if (R.size() == 0)
return false;
bool match = false;
HasAtleastOneRequiredMethod = true;
for (unsigned I = 0, N = R.size(); I != N; ++I)
if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
match = true;
break;
}
if (!match)
return false;
}
}
if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
return true;
return false;
}
static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
const NSAPI &NS, edit::Commit &commit) {
const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
std::string ClassString;
SourceLocation EndLoc =
IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
if (Protocols.empty()) {
ClassString = '<';
for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
ClassString += ConformingProtocols[i]->getNameAsString();
if (i != (e-1))
ClassString += ", ";
}
ClassString += "> ";
}
else {
ClassString = ", ";
for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
ClassString += ConformingProtocols[i]->getNameAsString();
if (i != (e-1))
ClassString += ", ";
}
ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
EndLoc = *PL;
}
commit.insertAfterToken(EndLoc, ClassString);
return true;
}
static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
const TypedefDecl *TypedefDcl,
const NSAPI &NS, edit::Commit &commit,
bool IsNSIntegerType,
bool NSOptions) {
std::string ClassString;
if (NSOptions)
ClassString = "typedef NS_OPTIONS(NSUInteger, ";
else
ClassString =
IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
: "typedef NS_ENUM(NSUInteger, ";
ClassString += TypedefDcl->getIdentifier()->getName();
ClassString += ')';
SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
commit.replace(R, ClassString);
SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
if (!EndOfTypedefLoc.isInvalid()) {
commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
return true;
}
return false;
}
static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
const TypedefDecl *TypedefDcl,
const NSAPI &NS, edit::Commit &commit,
bool IsNSIntegerType) {
std::string ClassString =
IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
ClassString += TypedefDcl->getIdentifier()->getName();
ClassString += ')';
SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
commit.replace(R, ClassString);
SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
commit.remove(SourceRange(TypedefLoc, TypedefLoc));
return true;
}
static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
const EnumDecl *EnumDcl) {
bool PowerOfTwo = true;
bool FoundHexdecimalEnumerator = false;
uint64_t MaxPowerOfTwoVal = 0;
for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
EnumConstantDecl *Enumerator = (*EI);
const Expr *InitExpr = Enumerator->getInitExpr();
if (!InitExpr) {
PowerOfTwo = false;
continue;
}
InitExpr = InitExpr->IgnoreImpCasts();
if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
if (BO->isShiftOp() || BO->isBitwiseOp())
return true;
uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
if (PowerOfTwo && EnumVal) {
if (!llvm::isPowerOf2_64(EnumVal))
PowerOfTwo = false;
else if (EnumVal > MaxPowerOfTwoVal)
MaxPowerOfTwoVal = EnumVal;
}
if (!FoundHexdecimalEnumerator) {
SourceLocation EndLoc = Enumerator->getLocEnd();
Token Tok;
if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
if (Tok.isLiteral() && Tok.getLength() > 2) {
if (const char *StringLit = Tok.getLiteralData())
FoundHexdecimalEnumerator =
(StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
}
}
}
return FoundHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
}
void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
const ObjCImplementationDecl *ImpDecl) {
const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
if (!IDecl || ObjCProtocolDecls.empty())
return;
// Find all implicit conforming protocols for this class
// and make them explicit.
llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
ObjCProtocolDecls.begin(),
E = ObjCProtocolDecls.end(); I != E; ++I)
if (!ExplicitProtocols.count(*I))
PotentialImplicitProtocols.push_back(*I);
if (PotentialImplicitProtocols.empty())
return;
// go through list of non-optional methods and properties in each protocol
// in the PotentialImplicitProtocols list. If class implements every one of the
// methods and properties, then this class conforms to this protocol.
llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
PotentialImplicitProtocols[i]))
ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
if (ConformingProtocols.empty())
return;
// Further reduce number of conforming protocols. If protocol P1 is in the list
// protocol P2 (P2<P1>), No need to include P1.
llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
bool DropIt = false;
ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
if (PDecl == TargetPDecl)
continue;
if (PDecl->lookupProtocolNamed(
TargetPDecl->getDeclName().getAsIdentifierInfo())) {
DropIt = true;
break;
}
}
if (!DropIt)
MinimalConformingProtocols.push_back(TargetPDecl);
}
edit::Commit commit(*Editor);
rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
*NSAPIObj, commit);
Editor->commit(commit);
}
void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
const EnumDecl *EnumDcl,
const TypedefDecl *TypedefDcl) {
if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
!TypedefDcl->getIdentifier())
return;
QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
if (!IsNSIntegerType && !IsNSUIntegerType) {
// Also check for typedef enum {...} TD;
if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
if (EnumTy->getDecl() == EnumDcl) {
bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
if (NSOptions) {
if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
return;
}
else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
return;
edit::Commit commit(*Editor);
rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Editor->commit(commit);
}
}
return;
}
// We may still use NS_OPTIONS based on what we find in the enumertor list.
bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
// NS_ENUM must be available.
if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
return;
// NS_OPTIONS must be available.
if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
return;
edit::Commit commit(*Editor);
rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType, NSOptions);
Editor->commit(commit);
}
static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
ObjCMethodDecl *OM) {
SourceRange R;
std::string ClassString;
if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
TypeLoc TL = TSInfo->getTypeLoc();
R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
ClassString = "instancetype";
}
else {
R = SourceRange(OM->getLocStart(), OM->getLocStart());
ClassString = OM->isInstanceMethod() ? '-' : '+';
ClassString += " (instancetype)";
}
edit::Commit commit(*ASTC.Editor);
commit.replace(R, ClassString);
ASTC.Editor->commit(commit);
}
void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
ObjCContainerDecl *CDecl,
ObjCMethodDecl *OM) {
// bail out early and do not suggest 'instancetype' when the method already
// has a related result type,
if (OM->hasRelatedResultType())
return;
ObjCInstanceTypeFamily OIT_Family =
Selector::getInstTypeMethodFamily(OM->getSelector());
std::string ClassName;
switch (OIT_Family) {
case OIT_None:
migrateFactoryMethod(Ctx, CDecl, OM);
return;
case OIT_Array:
ClassName = "NSArray";
break;
case OIT_Dictionary:
ClassName = "NSDictionary";
break;
case OIT_Singleton:
migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
return;
}
if (!OM->getResultType()->isObjCIdType())
return;
ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
if (!IDecl) {
if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
IDecl = CatDecl->getClassInterface();
else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
IDecl = ImpDecl->getClassInterface();
}
if (!IDecl ||
!IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
migrateFactoryMethod(Ctx, CDecl, OM);
return;
}
ReplaceWithInstancetype(*this, OM);
}
static bool TypeIsInnerPointer(QualType T) {
if (!T->isAnyPointerType())
return false;
if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
T->isBlockPointerType() || ento::coreFoundation::isCFObjectRef(T))
return false;
// Also, typedef-of-pointer-to-incomplete-struct is something that we assume
// is not an innter pointer type.
QualType OrigT = T;
while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
T = TD->getDecl()->getUnderlyingType();
if (OrigT == T || !T->isPointerType())
return true;
const PointerType* PT = T->getAs<PointerType>();
QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
if (UPointeeT->isRecordType()) {
const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
if (!RecordTy->getDecl()->isCompleteDefinition())
return false;
}
return true;
}
bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
ObjCInterfaceDecl *D,
ObjCMethodDecl *Method) {
if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
Method->param_size() != 0)
return false;
// Is this method candidate to be a getter?
QualType GRT = Method->getResultType();
if (GRT->isVoidType())
return false;
// FIXME. Don't know what todo with attributes, skip for now.
if (Method->hasAttrs())
return false;
Selector GetterSelector = Method->getSelector();
IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
Selector SetterSelector =
SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
PP.getSelectorTable(),
getterName);
ObjCMethodDecl *SetterMethod = D->lookupMethod(SetterSelector, true);
unsigned LengthOfPrefix = 0;
if (!SetterMethod) {
// try a different naming convention for getter: isXxxxx
StringRef getterNameString = getterName->getName();
bool IsPrefix = getterNameString.startswith("is");
if ((IsPrefix && !GRT->isObjCRetainableType()) ||
getterNameString.startswith("get")) {
LengthOfPrefix = (IsPrefix ? 2 : 3);
const char *CGetterName = getterNameString.data() + LengthOfPrefix;
// Make sure that first character after "is" or "get" prefix can
// start an identifier.
if (!isIdentifierHead(CGetterName[0]))
return false;
if (CGetterName[0] && isUppercase(CGetterName[0])) {
getterName = &Ctx.Idents.get(CGetterName);
SetterSelector =
SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
PP.getSelectorTable(),
getterName);
SetterMethod = D->lookupMethod(SetterSelector, true);
}
}
}
if (SetterMethod) {
// Is this a valid setter, matching the target getter?
QualType SRT = SetterMethod->getResultType();
if (!SRT->isVoidType())
return false;
const ParmVarDecl *argDecl = *SetterMethod->param_begin();
QualType ArgType = argDecl->getType();
if (!Ctx.hasSameUnqualifiedType(ArgType, GRT) ||
SetterMethod->hasAttrs())
return false;
edit::Commit commit(*Editor);
rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
LengthOfPrefix);
Editor->commit(commit);
return true;
}
else if (MigrateReadonlyProperty) {
// Try a non-void method with no argument (and no setter or property of same name
// as a 'readonly' property.
edit::Commit commit(*Editor);
rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
LengthOfPrefix);
Editor->commit(commit);
return true;
}
return false;
}
void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
ObjCMethodDecl *OM) {
if (OM->hasAttr<ObjCReturnsInnerPointerAttr>())
return;
QualType RT = OM->getResultType();
if (!TypeIsInnerPointer(RT) ||
!Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
return;
edit::Commit commit(*Editor);
commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
Editor->commit(commit);
}
void ObjCMigrateASTConsumer::migrateMethods(ASTContext &Ctx,
ObjCContainerDecl *CDecl) {
// migrate methods which can have instancetype as their result type.
for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
MEnd = CDecl->meth_end();
M != MEnd; ++M) {
ObjCMethodDecl *Method = (*M);
migrateMethodInstanceType(Ctx, CDecl, Method);
}
}
void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
ObjCContainerDecl *CDecl,
ObjCMethodDecl *OM,
ObjCInstanceTypeFamily OIT_Family) {
if (OM->isInstanceMethod() ||
OM->getResultType() == Ctx.getObjCInstanceType() ||
!OM->getResultType()->isObjCIdType())
return;
// Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
// NSYYYNamE with matching names be at least 3 characters long.
ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
if (!IDecl) {
if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
IDecl = CatDecl->getClassInterface();
else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
IDecl = ImpDecl->getClassInterface();
}
if (!IDecl)
return;
std::string StringClassName = IDecl->getName();
StringRef LoweredClassName(StringClassName);
std::string StringLoweredClassName = LoweredClassName.lower();
LoweredClassName = StringLoweredClassName;
IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
// Handle method with no name at its first selector slot; e.g. + (id):(int)x.
if (!MethodIdName)
return;
std::string MethodName = MethodIdName->getName();
if (OIT_Family == OIT_Singleton) {
StringRef STRefMethodName(MethodName);
size_t len = 0;
if (STRefMethodName.startswith("standard"))
len = strlen("standard");
else if (STRefMethodName.startswith("shared"))
len = strlen("shared");
else if (STRefMethodName.startswith("default"))
len = strlen("default");
else
return;
MethodName = STRefMethodName.substr(len);
}
std::string MethodNameSubStr = MethodName.substr(0, 3);
StringRef MethodNamePrefix(MethodNameSubStr);
std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
MethodNamePrefix = StringLoweredMethodNamePrefix;
size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
if (Ix == StringRef::npos)
return;
std::string ClassNamePostfix = LoweredClassName.substr(Ix);
StringRef LoweredMethodName(MethodName);
std::string StringLoweredMethodName = LoweredMethodName.lower();
LoweredMethodName = StringLoweredMethodName;
if (!LoweredMethodName.startswith(ClassNamePostfix))
return;
ReplaceWithInstancetype(*this, OM);
}
static bool IsVoidStarType(QualType Ty) {
if (!Ty->isPointerType())
return false;
while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
Ty = TD->getDecl()->getUnderlyingType();
// Is the type void*?
const PointerType* PT = Ty->getAs<PointerType>();
if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
return true;
return IsVoidStarType(PT->getPointeeType());
}
/// AuditedType - This routine audits the type AT and returns false if it is one of known
/// CF object types or of the "void *" variety. It returns true if we don't care about the type
/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
static bool AuditedType (QualType AT) {
if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
return true;
// FIXME. There isn't much we can say about CF pointer type; or is there?
if (ento::coreFoundation::isCFObjectRef(AT) ||
IsVoidStarType(AT) ||
// If an ObjC object is type, assuming that it is not a CF function and
// that it is an un-audited function.
AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
return false;
// All other pointers are assumed audited as harmless.
return true;
}
void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
if (CFFunctionIBCandidates.empty())
return;
if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
CFFunctionIBCandidates.clear();
FileId = 0;
return;
}
// Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
const Decl *FirstFD = CFFunctionIBCandidates[0];
const Decl *LastFD =
CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
edit::Commit commit(*Editor);
commit.insertBefore(FirstFD->getLocStart(), PragmaString);
PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
SourceLocation EndLoc = LastFD->getLocEnd();
// get location just past end of function location.
EndLoc = PP.getLocForEndOfToken(EndLoc);
if (isa<FunctionDecl>(LastFD)) {
// For Methods, EndLoc points to the ending semcolon. So,
// not of these extra work is needed.
Token Tok;
// get locaiton of token that comes after end of function.
bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
if (!Failed)
EndLoc = Tok.getLocation();
}
commit.insertAfterToken(EndLoc, PragmaString);
Editor->commit(commit);
FileId = 0;
CFFunctionIBCandidates.clear();
}
void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
if (Decl->hasAttr<CFAuditedTransferAttr>()) {
assert(CFFunctionIBCandidates.empty() &&
"Cannot have audited functions/methods inside user "
"provided CF_IMPLICIT_BRIDGING_ENABLE");
return;
}
// Finction must be annotated first.
if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
if (AuditKind == CF_BRIDGING_ENABLE) {
CFFunctionIBCandidates.push_back(Decl);
if (!FileId)
FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
}
else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
if (!CFFunctionIBCandidates.empty()) {
CFFunctionIBCandidates.push_back(Decl);
if (!FileId)
FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
}
}
else
AnnotateImplicitBridging(Ctx);
}
else {
migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
AnnotateImplicitBridging(Ctx);
}
}
void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
const CallEffects &CE,
const FunctionDecl *FuncDecl,
bool ResultAnnotated) {
// Annotate function.
if (!ResultAnnotated) {
RetEffect Ret = CE.getReturnValue();
const char *AnnotationString = 0;
if (Ret.getObjKind() == RetEffect::CF) {
if (Ret.isOwned() &&
Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
AnnotationString = " CF_RETURNS_RETAINED";
else if (Ret.notOwned() &&
Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
AnnotationString = " CF_RETURNS_NOT_RETAINED";
}
else if (Ret.getObjKind() == RetEffect::ObjC) {
if (Ret.isOwned() &&
Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
AnnotationString = " NS_RETURNS_RETAINED";
}
if (AnnotationString) {
edit::Commit commit(*Editor);
commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
Editor->commit(commit);
}
}
llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
unsigned i = 0;
for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
const ParmVarDecl *pd = *pi;
ArgEffect AE = AEArgs[i];
if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
edit::Commit commit(*Editor);
commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
Editor->commit(commit);
}
else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
edit::Commit commit(*Editor);
commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
Editor->commit(commit);
}
}
}
ObjCMigrateASTConsumer::CF_BRIDGING_KIND
ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
ASTContext &Ctx,
const FunctionDecl *FuncDecl) {
if (FuncDecl->hasBody())
return CF_BRIDGING_NONE;
CallEffects CE = CallEffects::getEffect(FuncDecl);
bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
// Trivial case of when funciton is annotated and has no argument.
if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
return CF_BRIDGING_NONE;
bool ReturnCFAudited = false;
if (!FuncIsReturnAnnotated) {
RetEffect Ret = CE.getReturnValue();
if (Ret.getObjKind() == RetEffect::CF &&
(Ret.isOwned() || Ret.notOwned()))
ReturnCFAudited = true;
else if (!AuditedType(FuncDecl->getResultType()))
return CF_BRIDGING_NONE;
}
// At this point result type is audited for potential inclusion.
// Now, how about argument types.
llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
unsigned i = 0;
bool ArgCFAudited = false;
for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
const ParmVarDecl *pd = *pi;
ArgEffect AE = AEArgs[i];
if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
ArgCFAudited = true;
else if (AE == IncRef)
ArgCFAudited = true;
}
else {
QualType AT = pd->getType();
if (!AuditedType(AT)) {
AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
return CF_BRIDGING_NONE;
}
}
}
if (ReturnCFAudited || ArgCFAudited)
return CF_BRIDGING_ENABLE;
return CF_BRIDGING_MAY_INCLUDE;
}
void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
ObjCContainerDecl *CDecl) {
if (!isa<ObjCInterfaceDecl>(CDecl))
return;
// migrate methods which can have instancetype as their result type.
for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
MEnd = CDecl->meth_end();
M != MEnd; ++M) {
ObjCMethodDecl *Method = (*M);
migrateCFAnnotation(Ctx, Method);
}
}
void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
const CallEffects &CE,
const ObjCMethodDecl *MethodDecl,
bool ResultAnnotated) {
// Annotate function.
if (!ResultAnnotated) {
RetEffect Ret = CE.getReturnValue();
const char *AnnotationString = 0;
if (Ret.getObjKind() == RetEffect::CF) {
if (Ret.isOwned() &&
Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
AnnotationString = " CF_RETURNS_RETAINED";
else if (Ret.notOwned() &&
Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
AnnotationString = " CF_RETURNS_NOT_RETAINED";
}
else if (Ret.getObjKind() == RetEffect::ObjC) {
ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
switch (OMF) {
case clang::OMF_alloc:
case clang::OMF_new:
case clang::OMF_copy:
case clang::OMF_init:
case clang::OMF_mutableCopy:
break;
default:
if (Ret.isOwned() &&
Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
AnnotationString = " NS_RETURNS_RETAINED";
break;
}
}
if (AnnotationString) {
edit::Commit commit(*Editor);
commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
Editor->commit(commit);
}
}
llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
unsigned i = 0;
for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
const ParmVarDecl *pd = *pi;
ArgEffect AE = AEArgs[i];
if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
edit::Commit commit(*Editor);
commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
Editor->commit(commit);
}
}
}
void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
ASTContext &Ctx,
const ObjCMethodDecl *MethodDecl) {
if (MethodDecl->hasBody() || MethodDecl->isImplicit())
return;
CallEffects CE = CallEffects::getEffect(MethodDecl);
bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
if (CE.getReceiver() == DecRefMsg &&
!MethodDecl->getAttr<NSConsumesSelfAttr>() &&
MethodDecl->getMethodFamily() != OMF_init &&
MethodDecl->getMethodFamily() != OMF_release &&
Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
edit::Commit commit(*Editor);
commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
Editor->commit(commit);
}
// Trivial case of when funciton is annotated and has no argument.
if (MethodIsReturnAnnotated &&
(MethodDecl->param_begin() == MethodDecl->param_end()))
return;
if (!MethodIsReturnAnnotated) {
RetEffect Ret = CE.getReturnValue();
if ((Ret.getObjKind() == RetEffect::CF ||
Ret.getObjKind() == RetEffect::ObjC) &&
(Ret.isOwned() || Ret.notOwned())) {
AddCFAnnotations(Ctx, CE, MethodDecl, false);
return;
}
else if (!AuditedType(MethodDecl->getResultType()))
return;
}
// At this point result type is either annotated or audited.
// Now, how about argument types.
llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
unsigned i = 0;
for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
const ParmVarDecl *pd = *pi;
ArgEffect AE = AEArgs[i];
if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
!AuditedType(pd->getType())) {
AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
return;
}
}
return;
}
namespace {
class RewritesReceiver : public edit::EditsReceiver {
Rewriter &Rewrite;
public:
RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
virtual void insert(SourceLocation loc, StringRef text) {
Rewrite.InsertText(loc, text);
}
virtual void replace(CharSourceRange range, StringRef text) {
Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
}
};
}
void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
if (MigrateProperty) {
for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
D != DEnd; ++D) {
if (unsigned FID =
PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
if (FileId && FileId != FID) {
assert(!CFFunctionIBCandidates.empty());
AnnotateImplicitBridging(Ctx);
}
if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
migrateObjCInterfaceDecl(Ctx, CDecl);
else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
ObjCProtocolDecls.insert(PDecl);
else if (const ObjCImplementationDecl *ImpDecl =
dyn_cast<ObjCImplementationDecl>(*D))
migrateProtocolConformance(Ctx, ImpDecl);
else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
DeclContext::decl_iterator N = D;
++N;
if (N != DEnd)
if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
migrateNSEnumDecl(Ctx, ED, TD);
}
else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
migrateCFAnnotation(Ctx, FD);
if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
// migrate methods which can have instancetype as their result type.
migrateMethods(Ctx, CDecl);
// annotate methods with CF annotations.
migrateARCSafeAnnotation(Ctx, CDecl);
}
}
AnnotateImplicitBridging(Ctx);
}
Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
RewritesReceiver Rec(rewriter);
Editor->applyRewrites(Rec);
for (Rewriter::buffer_iterator
I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
FileID FID = I->first;
RewriteBuffer &buf = I->second;
const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
assert(file);
SmallString<512> newText;
llvm::raw_svector_ostream vecOS(newText);
buf.write(vecOS);
vecOS.flush();
llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
StringRef(newText.data(), newText.size()), file->getName());
SmallString<64> filePath(file->getName());
FileMgr.FixupRelativePath(filePath);
Remapper.remap(filePath.str(), memBuf);
}
if (IsOutputFile) {
Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
} else {
Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
}
}
bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
CI.getDiagnostics().setIgnoreAllWarnings(true);
return true;
}
ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) {
PPConditionalDirectiveRecord *
PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
CI.getPreprocessor().addPPCallbacks(PPRec);
return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
/*MigrateLiterals=*/true,
/*MigrateSubscripting=*/true,
/*MigrateProperty*/true,
/*MigrateReadonlyProperty*/true,
Remapper,
CI.getFileManager(),
PPRec,
CI.getPreprocessor(),
/*isOutputFile=*/true);
}
| [
"aleksy.jones@gmail.com"
] | aleksy.jones@gmail.com |
3ef007f20ff17695893b6f5d741c81f80df59d60 | 9cf2633f901cf206f712679bd362bb17404345c9 | /As an 8 bits counter/Compteur_74_LS_393.ino | ab5da9ba789c8b6b88fe18068fef00ab48f5b75d | [] | no_license | ThierryBARS/Checks-components-with-Arduino | a1f438d7800d859ad0136ecdb7a579519df4a43d | 3de74a9f38423b5450221c227f02581eab9eba12 | refs/heads/main | 2023-02-16T23:05:10.158262 | 2020-12-22T21:25:26 | 2020-12-22T21:25:26 | 315,695,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,705 | ino | /*
Programme permettant de tester un compteur SN 74 LS 393 N
vue de dessus
_________
| |_| |
1A =| |= VCC
1 CLR =| 7 |= 2A
1QA =| 4 |= 2 CLR
1QB =| LS |= 2QA
1QC =| 3 |= 2QB
1QD =| 9 |= 2QC
Ground =| 3 |= 2QD
|____N____|
Cablage:
VCC = 5V
Ground = 0v
1A = Digital I/O 13 qui sera en OUTPUT (elle fournira
les impulsions a compter). Dans le soft "A_Compter"
1 CLR et 2 CLR seront reli�es ensemble et reli�es �
la sortie Digital I/O 12, et portera le nom "CLR_compteur"
1QD sera reli�e sur 2A (pourtransformer les 2 compteurs 4bs
en 1 compteur 8 bits
1QA, 1QB, 1QC, 1QD, 2QA, 2QB, 2QC, 2QD seront respectivement
reli�es aux Digitals I/O:
2, 3, 4, 5, 6, 7.
Je lai pas commenc� par digital I/O 0 et 1 car elles sont
utilis�es par l'instruction serial en cas d'erreur de comptage
Il faut donc ouvrir le "moniteur serie" pour voir les erreurs
*/
//---------------Sorties------------------------------------
const int A_Compter = 13; // broche envoyant les impulsions a comp
// ter sur 1A du compteur.
const int CLR_compteur = 12; // broche ou le clear est branch�
//---------------Entr�es------------------------------------
const int b0 =2;
const int b1 =3;
const int b2 =4;
const int b3 =5;
const int b4 =6;
const int b5 =7;
const int b6 =8;
const int b7 =9;
const int BtnStartReset = 11; // broche du bouton reset test
//---------------Variables du programme--------------------------------
byte CompteurLogiciel; // Compteur logiciel du nombre d'impulsions
// envoy�es sur 1A via Digital I/O 13
byte LectureCompteur; // Lecture des sorties 1Qx et 2Qx via les ports
// PINB et PIND (car les 8 broches s'�talent sur
// ces 2 ports du fait de ne pas utiliser Digital
// I/O 0 et 1
void remise_a_zero_Compteur(){
digitalWrite(CLR_compteur, HIGH) ;
digitalWrite(CLR_compteur, LOW) ;
CompteurLogiciel=0;
//lit, sous forme d'un octet, les ports PINB et PIND, n'ayant pas
//utilis� les DigitalIO 0 et 1, j'empiete sur le PINB ET PIND
// LectureCompteur=(((PINB)&3)<<6)|((PIND&252)>>2);
LectureCompteur=(((PINB)&3)<<6)|((PIND&252)>>2);
}
void incrementeCompteur(){
digitalWrite(A_Compter, LOW) ;
digitalWrite(A_Compter, HIGH) ;
CompteurLogiciel += 1;
LectureCompteur=(((PINB)&3)<<6)|((PIND&252)>>2);
}
void setup() {
Serial.begin(9600);
pinMode(A_Compter, OUTPUT);
pinMode(CLR_compteur, OUTPUT);
pinMode(b0, INPUT);
pinMode(b1, INPUT);
pinMode(b2, INPUT);
pinMode(b3, INPUT);
pinMode(b4, INPUT);
pinMode(b5, INPUT);
pinMode(b6, INPUT);
pinMode(b7, INPUT);
pinMode(BtnStartReset, INPUT);
delay(20);
remise_a_zero_Compteur();
}
void loop() {
if (digitalRead(BtnStartReset) == 0) {
delay(125);
incrementeCompteur();
//Ci dessous une m�thode plus compr�hensible
//LectureCompteur=digitalRead(b7)*128+digitalRead(b6)*64+digitalRead(b5)*32+digitalRead(b4)*16+digitalRead(b3)*8+digitalRead(b2)*4+digitalRead(b1)*2+digitalRead(b0);
if (CompteurLogiciel != LectureCompteur) {
Serial.print("On a un GROS probleme de comptage => ");
Serial.print(CompteurLogiciel,HEX); Serial.print(" < - > "); Serial.println(LectureCompteur,HEX);
delay(500);
}
}
else if (digitalRead(BtnStartReset) == 1) {
Serial.println("Remise a 0");
remise_a_zero_Compteur();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.