blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
22e119c49178dd182dbaa1fdf83204efc798e33c | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/115/544/CWE762_Mismatched_Memory_Management_Routines__new_array_free_class_74a.cpp | d1a03b2bc8f1b239670824364ac1c982d618f08e | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,136 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_free_class_74a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_free.label.xml
Template File: sources-sinks-74a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: Allocate data using new []
* GoodSource: Allocate data using malloc()
* Sinks:
* GoodSink: Deallocate data using delete []
* BadSink : Deallocate data using free()
* Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <map>
using namespace std;
namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_class_74
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(map<int, TwoIntsClass *> dataMap);
void bad()
{
TwoIntsClass * data;
map<int, TwoIntsClass *> dataMap;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */
data = new TwoIntsClass[100];
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
badSink(dataMap);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, TwoIntsClass *> dataMap);
static void goodG2B()
{
TwoIntsClass * data;
map<int, TwoIntsClass *> dataMap;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory from the heap using malloc() */
data = (TwoIntsClass *)malloc(100*sizeof(TwoIntsClass));
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
goodG2BSink(dataMap);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(map<int, TwoIntsClass *> dataMap);
static void goodB2G()
{
TwoIntsClass * data;
map<int, TwoIntsClass *> dataMap;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */
data = new TwoIntsClass[100];
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
goodB2GSink(dataMap);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_class_74; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
a05a00472fb8ec725590865f2c0effa4251f2d76 | 859006ded9e1b0cffc7fa410498e3b8b94c9ad78 | /Legacy/HAL/include/HAL/transport/SerialEndpoint.h | cccfc8366aa5f245e73ff56f92197335d5073d4b | [] | no_license | viron11111/sub-2012 | 608795566c5ee621e0c27ff53399dfb58b26ecf5 | 761972b1fdb577c59c693a670605b8aaabe90a4d | refs/heads/master | 2021-01-01T04:48:48.762686 | 2012-10-02T23:47:57 | 2012-10-02T23:47:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | h | #ifndef HAL_SERIALENDPOINT_H
#define HAL_SERIALENDPOINT_H
#include "HAL/transport/BaseStreamEndpoint.h"
namespace subjugator {
class SerialEndpoint : public BaseStreamEndpoint<boost::asio::serial_port> {
public:
SerialEndpoint(const std::string &devicename, int baud, boost::asio::io_service &ioservice);
virtual void open();
private:
std::string devicename;
int baud;
};
}
#endif
| [
"matthewbot@gmail.com"
] | matthewbot@gmail.com |
f44723ac896e250a05918be229fdd7f5550d0e7c | 897f755ac3659c80dcb124dc8b84ce18a076823d | /TouchGFX/generated/fonts/src/Kerning_times_40_1bpp.cpp | d2f643dc5ca905b8cb3cca1a1f8083db39bc5886 | [] | no_license | andersreinholdsson/STM32F767 | a21360e984d3a4d855b78cd89d7997f8dfd2d48f | e8b0909ca7ba3371f47c02297fb1d0509f3f9e8f | refs/heads/main | 2023-04-06T00:25:54.770765 | 2021-04-26T21:42:00 | 2021-04-26T21:42:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,532 | cpp | #include <touchgfx/Font.hpp>
FONT_KERNING_LOCATION_FLASH_PRAGMA
KEEP extern const touchgfx::KerningNode kerning_times_40_1bpp[] FONT_KERNING_LOCATION_FLASH_ATTRIBUTE =
{
{ 0x0041, -2 }, // (First char = [0x0041, A], Second char = [0x0020, ], Kerning dist = -2)
{ 0x0054, -1 }, // (First char = [0x0054, T], Second char = [0x0020, ], Kerning dist = -1)
{ 0x0054, -3 }, // (First char = [0x0054, T], Second char = [0x002E, .], Kerning dist = -3)
{ 0x0072, -2 }, // (First char = [0x0072, r], Second char = [0x002E, .], Kerning dist = -2)
{ 0x0031, -1 }, // (First char = [0x0031, 1], Second char = [0x0031, 1], Kerning dist = -1)
{ 0x0020, -2 }, // (First char = [0x0020, ], Second char = [0x0041, A], Kerning dist = -2)
{ 0x0054, -3 }, // (First char = [0x0054, T], Second char = [0x0041, A], Kerning dist = -3)
{ 0x0020, -1 }, // (First char = [0x0020, ], Second char = [0x0054, T], Kerning dist = -1)
{ 0x0041, -4 }, // (First char = [0x0041, A], Second char = [0x0054, T], Kerning dist = -4)
{ 0x0054, -3 }, // (First char = [0x0054, T], Second char = [0x0061, a], Kerning dist = -3)
{ 0x0054, -3 }, // (First char = [0x0054, T], Second char = [0x0065, e], Kerning dist = -3)
{ 0x0054, -3 }, // (First char = [0x0054, T], Second char = [0x006F, o], Kerning dist = -3)
{ 0x0054, -1 }, // (First char = [0x0054, T], Second char = [0x0072, r], Kerning dist = -1)
{ 0x0054, -1 }, // (First char = [0x0054, T], Second char = [0x0075, u], Kerning dist = -1)
};
| [
"archer.lawrence@kingtigertech.com"
] | archer.lawrence@kingtigertech.com |
a41b096d708b5667b1d55049831f6cce80b59dd1 | a849cebba0364c54b7053b4c96e461ac3c534468 | /mywidget.h | 5d0396257064b73bd9f61ba6d57331b23d504e1a | [] | no_license | saraivaufc/ListaDeCompras | 9b90241186f56b923c2529e050cda724ed50ee45 | 9731db57bd01c3e43d69968b027148f0c3425742 | refs/heads/master | 2020-04-06T06:53:45.579698 | 2014-11-03T07:19:57 | 2014-11-03T07:19:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | h | #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QPainter>
#include <QPrinter>
#include <QPaintEvent>
#include <QPaintEngine>
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
private:
QPrinter* printer;
protected:
void paintEvent(QPaintEvent *);
signals:
public slots:
};
#endif // MYWIDGET_H
| [
"saraiva.ufc@gmail.com"
] | saraiva.ufc@gmail.com |
c03f083fb2743b93ad85e1a48967f2a13296907d | a363b5e64374f299ede8dcb4aaacc4999de5568f | /test/insertionSort/insertionSort_e3.cpp | 2491e2fbdc8553193659a4542014e93ea10341a3 | [] | no_license | educhielle/e3extensions | d6f86ef03b035619cdf8cc051d170a73dfec57c9 | 0a5d1a0b0c9eb2b89e824fcfc909a6a4263e6469 | refs/heads/master | 2021-03-22T05:12:42.606459 | 2017-08-27T12:45:47 | 2017-08-27T12:45:47 | 89,483,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | /* insertion sort ascending order */
#include <iostream>
#include "../../src/e3extensions/secureint.h"
using namespace std;
string libgDir = "./libg.so";
string gFunctionName = "libg";
// swap if the second is greater
void minswp(int *x, int *y) {
if (*x < *y) {
int tmp = *x;
*x = *y;
*y = tmp;
}
}
int gfun(int x, int y) {
return (x <= 0) ? 0 : y;
}
int main(void) {
int n = 20, j;
int array[20] = { 4, 2, 5, 7, 1, 0, 11, 3, 9, 8, 4, 5, 6, 1, 2, 3, 7, 9, 10, 2 };
int *arrayPrev = array;
int *arrayCur = array;
int i = 1;
outer_loop:
j = i;
arrayCur = array + i;
inner_loop:
arrayPrev = arrayCur-1;
minswp(arrayCur, arrayPrev);
j--;
arrayCur--;
if (j != 0) goto inner_loop;
i++;
if (i != n) goto outer_loop;
for (i = 0; i < n; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}
| [
"eduardochiell@gmail.com"
] | eduardochiell@gmail.com |
4b38f59002bec29fa3480088452e86689dabe370 | 0e0a887164b1e5478261faf0ddd33c694f20bdde | /src/caffe/YOLO/image.cpp | ef2daa3e3740e9c0e050f857a50e39e76475ddf2 | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | xyt2008/frcnn | 86882aa0ffa376fa527006bdd32dc311161eeab8 | 32a559e881cceeba09a90ff45ad4aae1dabf92a1 | refs/heads/master | 2020-03-14T20:56:21.930791 | 2019-09-22T11:16:32 | 2019-09-22T11:16:32 | 131,785,765 | 0 | 0 | NOASSERTION | 2019-09-22T11:16:33 | 2018-05-02T02:10:55 | C++ | UTF-8 | C++ | false | false | 5,304 | cpp |
#include "image.h"
#include <opencv2/opencv.hpp>
using namespace cv;
static void rgbgr_image(image im)
{
int i;
for(i = 0; i < im.w*im.h; ++i){
float swap = im.data[i];
im.data[i] = im.data[i+im.w*im.h*2];
im.data[i+im.w*im.h*2] = swap;
}
}
static void ipl_into_image(IplImage* src, image im)
{
unsigned char *data = (unsigned char *)src->imageData;
int h = src->height;
int w = src->width;
int c = src->nChannels;
int step = src->widthStep;
int i, j, k;
for(i = 0; i < h; ++i){
for(k= 0; k < c; ++k){
for(j = 0; j < w; ++j){
im.data[k*w*h + i*w + j] = data[i*step + j*c + k]/255.;
}
}
}
}
static image make_empty_image(int w, int h, int c)
{
image out;
out.data = 0;
out.h = h;
out.w = w;
out.c = c;
return out;
}
static image make_image(int w, int h, int c)
{
image out = make_empty_image(w,h,c);
out.data = (float*)calloc(h*w*c, sizeof(float));
return out;
}
static image ipl_to_image(IplImage* src)
{
int h = src->height;
int w = src->width;
int c = src->nChannels;
image out = make_image(w, h, c);
ipl_into_image(src, out);
return out;
}
image load_image_cv(char *filename, int channels)
{
IplImage* src = 0;
int flag = -1;
if (channels == 0) flag = -1;
else if (channels == 1) flag = 0;
else if (channels == 3) flag = 1;
else {
fprintf(stderr, "OpenCV can't force load with %d channels\n", channels);
}
if( (src = cvLoadImage(filename, flag)) == 0 )
{
fprintf(stderr, "Cannot load image \"%s\"\n", filename);
//char buff[256];
//sprintf(buff, "echo %s >> bad.list", filename);
//system(buff);
return make_image(10,10,3);
//exit(0);
}
image out = ipl_to_image(src);
cvReleaseImage(&src);
rgbgr_image(out);
return out;
}
/*
void free_image(image m)
{
if(m.data){
free(m.data);
}
}
image resize_image(image im, int w, int h)
{
image resized = make_image(w, h, im.c);
image part = make_image(w, im.h, im.c);
int r, c, k;
float w_scale = (float)(im.w - 1) / (w - 1);
float h_scale = (float)(im.h - 1) / (h - 1);
for(k = 0; k < im.c; ++k){
for(r = 0; r < im.h; ++r){
for(c = 0; c < w; ++c){
float val = 0;
if(c == w-1 || im.w == 1){
val = get_pixel(im, im.w-1, r, k);
} else {
float sx = c*w_scale;
int ix = (int) sx;
float dx = sx - ix;
val = (1 - dx) * get_pixel(im, ix, r, k) + dx * get_pixel(im, ix+1, r, k);
}
set_pixel(part, c, r, k, val);
}
}
}
for(k = 0; k < im.c; ++k){
for(r = 0; r < h; ++r){
float sy = r*h_scale;
int iy = (int) sy;
float dy = sy - iy;
for(c = 0; c < w; ++c){
float val = (1-dy) * get_pixel(part, c, iy, k);
set_pixel(resized, c, r, k, val);
}
if(r == h-1 || im.h == 1) continue;
for(c = 0; c < w; ++c){
float val = dy * get_pixel(part, c, iy+1, k);
add_pixel(resized, c, r, k, val);
}
}
}
free_image(part);
return resized;
}
*/
image load_image(char* filename,int w,int h,int c)
{
image out = load_image_cv(filename,c);
if((h && w) && (h != out.h || w != out.w))
{
image resized = resize_image(out,w,h);
free_image(out);
out = resized;
}
return out;
}
image load_image_color(char* filename,int w,int h)
{
return load_image(filename,w,h,3);
}
static void fill_image(image m, float s)
{
int i;
for(i = 0; i < m.h*m.w*m.c; ++i) m.data[i] = s;
}
float get_pixel(image m, int x, int y, int c)
{
assert(x < m.w && y < m.h && c < m.c);
return m.data[c*m.h*m.w + y*m.w + x];
}
void set_pixel(image m, int x, int y, int c, float val)
{
if (x < 0 || y < 0 || c < 0 || x >= m.w || y >= m.h || c >= m.c) return;
assert(x < m.w && y < m.h && c < m.c);
m.data[c*m.h*m.w + y*m.w + x] = val;
}
void add_pixel(image m, int x, int y, int c, float val)
{
assert(x < m.w && y < m.h && c < m.c);
m.data[c*m.h*m.w + y*m.w + x] += val;
}
void embed_image(image source, image dest, int dx, int dy)
{
int x,y,k;
for(k = 0; k < source.c; ++k){
for(y = 0; y < source.h; ++y){
for(x = 0; x < source.w; ++x){
float val = get_pixel(source, x,y,k);
set_pixel(dest, dx+x, dy+y, k, val);
}
}
}
}
image letterbox_image(image im, int w, int h)
{
int new_w = im.w;
int new_h = im.h;
if (((float)w/im.w) < ((float)h/im.h)) {
new_w = w;
new_h = (im.h * w)/im.w;
} else {
new_h = h;
new_w = (im.w * h)/im.h;
}
image resized = resize_image(im, new_w, new_h);
image boxed = make_image(w, h, im.c);
fill_image(boxed, .5);
//int i;
//for(i = 0; i < boxed.w*boxed.h*boxed.c; ++i) boxed.data[i] = 0;
embed_image(resized, boxed, (w-new_w)/2, (h-new_h)/2);
free_image(resized);
return boxed;
}
| [
"fymkang@gmail.com"
] | fymkang@gmail.com |
9c8cf02f0220979de17ba726deacb373a9dee43a | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-3226.cpp | 76ca950abdfe0efe564de00c110090cf8d93c590 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,487 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : c2, c0, c1
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c3*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c3*)(this);
tester2(p2_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, c2, c0
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c4*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active0)
p->f0();
if (p->active2)
p->f2();
if (p->active1)
p->f1();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c3*)(new c3());
ptrs0[2] = (c0*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c3*)(new c3());
ptrs1[2] = (c1*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c3*)(new c3());
ptrs2[2] = (c2*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
for (int i=0;i<1;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
75dc9447a5595dc1adb87c6f3ab65781cde271c7 | 0770d356aeac89873722c004dda96cb7497463cd | /Classes/GameObject/DropEquip.h | 9ecbbb39fcdfb1212e902452cd484136057afc28 | [] | no_license | 37947538/Young3_7 | 687b0423618e7cd6b71c23d188d0c31d90f7726d | c661a4de162a5d153a737b19d2729991b698486c | refs/heads/master | 2021-01-13T00:37:43.689432 | 2016-02-22T09:53:21 | 2016-02-22T09:53:21 | 52,246,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | h | //
// DropEquip.h
// Zombie3_4
// 掉落装备
// Created by jl on 15/7/29.
//
//
#ifndef __Zombie3_4__DropEquip__
#define __Zombie3_4__DropEquip__
#include <stdio.h>
#include "DropObject.h"
class DropEquip : public DropObject
{
public:
DropEquip();
~DropEquip();
static DropEquip* create(int weaponIndex);
CC_SYNTHESIZE(int, m_WeaponIndex, WeaponIndex);
bool init(int weaponIndex);
bool init(Sprite* spr,Sprite* sprbg,Sprite* clip);
virtual DropType getType(){ return DropType::Equip; }; //获取掉落类型
DropEquip* clone(); //克隆
private:
Sprite* spr; //保存组合数据
Sprite* sprbg;
Sprite* clip;
};
#endif /* defined(__Zombie3_4__DropEquip__) */
| [
"37947538@qq.com"
] | 37947538@qq.com |
d4f5caa2733007e0debd2b281c6525ed7e041f0f | 9a3fd403e16941232f9d48c837ebe494b5f34023 | /Source/kwsys/kwsysPlatformTestsCXX.cxx | 9c9bd8c57414ac490b51222024947daf2513ca14 | [
"BSD-3-Clause"
] | permissive | AnomalousMedical/CMake-OldFork | 9f7735199073525ab5f6b9074829af4abffac65b | 1bf1d8d1c8de2f7156a47ecf883408574c031ac1 | refs/heads/master | 2021-06-11T11:15:48.950407 | 2017-03-11T17:07:10 | 2017-03-11T17:07:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,952 | cxx | /*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
// Setup for tests that use result of stl namespace test.
#if defined(KWSYS_STL_HAVE_STD)
# if KWSYS_STL_HAVE_STD
# define kwsys_stl std
# else
# define kwsys_stl
# endif
#endif
// Setup for tests that use iostreams.
#if defined(KWSYS_IOS_USE_ANSI) && defined(KWSYS_IOS_HAVE_STD)
# if defined(_MSC_VER)
# pragma warning (push,1)
# endif
# if KWSYS_IOS_USE_ANSI
# include <iostream>
# else
# include <iostream.h>
# endif
# if defined(_MSC_VER)
# pragma warning (pop)
# endif
# if KWSYS_IOS_HAVE_STD
# define kwsys_ios std
# else
# define kwsys_ios
# endif
#endif
#ifdef TEST_KWSYS_STL_HAVE_STD
#include <list>
void f(std ::list<int>*) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_IOS_USE_ANSI
#include <iosfwd>
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_IOS_HAVE_STD
#include <iosfwd>
void f(std ::ostream*) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_IOS_USE_SSTREAM
#include <sstream>
#if defined(__GNUC__) && __GNUC__ == 2 && __GNUC_MINOR__ == 96
# error "GCC 2.96 stringstream is buggy"
#endif
int main()
{
std ::ostringstream ostr;
ostr << "hello";
if(ostr.str().size() == 5)
{
return 0;
}
return -1;
}
#endif
#ifdef TEST_KWSYS_IOS_USE_STRSTREAM_H
#include <strstream.h>
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_IOS_USE_STRSTREA_H
#include <strstrea.h>
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_STRING_HAVE_OSTREAM
# include <iostream.h>
# include <string>
void f(ostream& os, const kwsys_stl::string& s) { os << s; }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_STRING_HAVE_ISTREAM
# include <iostream.h>
# include <string>
void f(istream& is, kwsys_stl::string& s) { is >> s; }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_STRING_HAVE_NEQ_CHAR
# include <string>
bool f(const kwsys_stl::string& s) { return s != ""; }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_CXX_HAS_CSTDIO
#include <cstdio>
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_CXX_HAS_CSTDDEF
#include <cstddef>
void f(size_t) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_CXX_HAS_LONG_LONG
long long f(long long n) { return n; }
int main()
{
long long n = 0;
return static_cast<int>(f(n));
}
#endif
#ifdef TEST_KWSYS_CXX_HAS___INT64
__int64 f(__int64 n) { return n; }
int main()
{
__int64 n = 0;
return static_cast<int>(f(n));
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_NULL_TEMPLATE_ARGS
template <class T> class A;
template <class T> int f(A<T>&);
template <class T> class A
{
public:
// "friend int f<>(A<T>&)" would conform
friend int f(A<T>&);
private:
int x;
};
template <class T> int f(A<T>& a) { return a.x = 0; }
template int f(A<int>&);
int main()
{
A<int> a;
return f(a);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_MEMBER_TEMPLATES
template <class U>
class A
{
public:
U u;
A(): u(0) {}
template <class V> V m(V* p) { return *p = u; }
};
int main()
{
A<short> a;
int s = 1;
return a.m(&s);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_FULL_SPECIALIZATION
template <class T> struct A {};
template <> struct A<int*>
{
static int f() { return 0; }
};
int main() { return A<int*>::f(); }
#endif
#ifdef TEST_KWSYS_CXX_HAS_ARGUMENT_DEPENDENT_LOOKUP
namespace N
{
class A {};
int f(A*) { return 0; }
}
void f(void*);
int main()
{
N::A* a = 0;
return f(a);
}
#endif
#ifdef TEST_KWSYS_STL_HAS_ITERATOR_TRAITS
#include <iterator>
#include <list>
void f(kwsys_stl::iterator_traits<kwsys_stl::list<int>::iterator>::iterator_category const&) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_HAS_ITERATOR_CATEGORY
#include <iterator>
#include <list>
void f(kwsys_stl::list<int>::iterator x) { kwsys_stl::iterator_category(x); }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_HAS___ITERATOR_CATEGORY
#include <iterator>
#include <list>
void f(kwsys_stl::list<int>::iterator x) { kwsys_stl::__iterator_category(x); }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_TEMPLATE
#include <memory>
template <class Alloc>
void f(const Alloc&)
{
typedef typename Alloc::size_type alloc_size_type;
}
int main()
{
f(kwsys_stl::allocator<char>());
return 0;
}
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_NONTEMPLATE
#include <memory>
void f(kwsys_stl::allocator::size_type const&) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_REBIND
#include <memory>
template <class T, class Alloc>
void f(const T&, const Alloc&)
{
typedef typename Alloc::template rebind<T>::other alloc_type;
}
int main()
{
f(0, kwsys_stl::allocator<char>());
return 0;
}
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_MAX_SIZE_ARGUMENT
#include <memory>
void f(kwsys_stl::allocator<char> const& a)
{
a.max_size(sizeof(int));
}
int main()
{
f(kwsys_stl::allocator<char>());
return 0;
}
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_OBJECTS
#include <vector>
void f(kwsys_stl::vector<int> const& v1)
{
kwsys_stl::vector<int>(1, 1, v1.get_allocator());
}
int main()
{
f(kwsys_stl::vector<int>());
return 0;
}
#endif
#ifdef TEST_KWSYS_STAT_HAS_ST_MTIM
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat stat1;
(void)stat1.st_mtim.tv_sec;
(void)stat1.st_mtim.tv_nsec;
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_SAME_LONG_AND___INT64
void function(long**) {}
int main()
{
__int64** p = 0;
function(p);
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_SAME_LONG_LONG_AND___INT64
void function(long long**) {}
int main()
{
__int64** p = 0;
function(p);
return 0;
}
#endif
#ifdef TEST_KWSYS_CAN_CONVERT_UI64_TO_DOUBLE
void function(double& l, unsigned __int64 const& r)
{
l = static_cast<double>(r);
}
int main()
{
double tTo = 0.0;
unsigned __int64 tFrom = 0;
function(tTo, tFrom);
return 0;
}
#endif
#ifdef TEST_KWSYS_IOS_HAVE_BINARY
int test_binary(int, ...)
{
return 0;
}
int main()
{
return test_binary(1, kwsys_ios::ios::binary);
}
#endif
#ifdef TEST_KWSYS_IOS_HAS_ISTREAM_LONG_LONG
int test_istream(kwsys_ios::istream& is, long long& x)
{
return (is >> x)? 1:0;
}
int main()
{
long long x = 0;
return test_istream(kwsys_ios::cin, x);
}
#endif
#ifdef TEST_KWSYS_IOS_HAS_OSTREAM_LONG_LONG
int test_ostream(kwsys_ios::ostream& os, long long x)
{
return (os << x)? 1:0;
}
int main()
{
long long x = 0;
return test_ostream(kwsys_ios::cout, x);
}
#endif
#ifdef TEST_KWSYS_IOS_HAS_ISTREAM___INT64
int test_istream(kwsys_ios::istream& is, __int64& x)
{
return (is >> x)? 1:0;
}
int main()
{
__int64 x = 0;
return test_istream(kwsys_ios::cin, x);
}
#endif
#ifdef TEST_KWSYS_IOS_HAS_OSTREAM___INT64
int test_ostream(kwsys_ios::ostream& os, __int64 x)
{
return (os << x)? 1:0;
}
int main()
{
__int64 x = 0;
return test_ostream(kwsys_ios::cout, x);
}
#endif
#ifdef TEST_KWSYS_CHAR_IS_SIGNED
/* Return 0 for char signed and 1 for char unsigned. */
int main()
{
unsigned char uc = 255;
return (*reinterpret_cast<char*>(&uc) < 0)?0:1;
}
#endif
#ifdef TEST_KWSYS_LFS_WORKS
/* Return 0 when LFS is available and 1 otherwise. */
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _LARGE_FILES
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#if KWSYS_CXX_HAS_CSTDIO
# include <cstdio>
#endif
#include <stdio.h>
int main(int, char **argv)
{
/* check that off_t can hold 2^63 - 1 and perform basic operations... */
#define OFF_T_64 (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
if (OFF_T_64 % 2147483647 != 1)
return 1;
// stat breaks on SCO OpenServer
struct stat buf;
stat( argv[0], &buf );
if (!S_ISREG(buf.st_mode))
return 2;
FILE *file = fopen( argv[0], "r" );
off_t offset = ftello( file );
fseek( file, offset, SEEK_CUR );
fclose( file );
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_SETENV
#include <stdlib.h>
int main()
{
return setenv("A", "B", 1);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_UNSETENV
#include <stdlib.h>
int main()
{
unsetenv("A");
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
#include <stdlib.h>
int main()
{
char* e = environ[0];
return e? 0:1;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_RLIMIT64
# if defined(KWSYS_HAS_LFS)
# define _LARGEFILE_SOURCE
# define _LARGEFILE64_SOURCE
# define _LARGE_FILES
# define _FILE_OFFSET_BITS 64
# endif
# include <sys/resource.h>
int main()
{
struct rlimit64 rlim;
return getrlimit64(0,&rlim);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_ATOLL
#include <stdlib.h>
int main()
{
const char *str="1024";
return static_cast<int>(atoll(str));
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_ATOL
#include <stdlib.h>
int main()
{
const char *str="1024";
return static_cast<int>(atol(str));
}
#endif
#ifdef TEST_KWSYS_CXX_HAS__ATOI64
#include <stdlib.h>
int main()
{
const char *str="1024";
return static_cast<int>(_atoi64(str));
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_UTIMES
#include <sys/time.h>
int main()
{
struct timeval* current_time = 0;
return utimes("/example", current_time);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_UTIMENSAT
#include <fcntl.h>
#include <sys/stat.h>
int main()
{
struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}};
return utimensat(AT_FDCWD, "/example", times, AT_SYMLINK_NOFOLLOW);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_BACKTRACE
#if defined(__PATHSCALE__) || defined(__PATHCC__) \
|| (defined(__LSB_VERSION__) && (__LSB_VERSION__ < 41))
backtrace doesnt work with this compiler or os
#endif
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
# define _GNU_SOURCE
#endif
#include <execinfo.h>
int main()
{
void *stackSymbols[256];
backtrace(stackSymbols,256);
backtrace_symbols(&stackSymbols[0],1);
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_DLADDR
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
# define _GNU_SOURCE
#endif
#include <dlfcn.h>
int main()
{
Dl_info info;
int ierr=dladdr((void*)main,&info);
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_CXXABI
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
# define _GNU_SOURCE
#endif
#if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5130 \
&& __linux && __SUNPRO_CC_COMPAT == 'G'
# include <iostream>
#endif
#include <cxxabi.h>
int main()
{
int status = 0;
size_t bufferLen = 512;
char buffer[512] = {'\0'};
const char *function="_ZN5kwsys17SystemInformation15GetProgramStackEii";
char *demangledFunction =
abi::__cxa_demangle(function, buffer, &bufferLen, &status);
return status;
}
#endif
#ifdef TEST_KWSYS_CXX_TYPE_INFO
/* Collect fundamental type information and save it to a CMake script. */
/* Include limits.h to get macros indicating long long and __int64.
Note that certain compilers need special macros to define these
macros in limits.h. */
#if defined(_MSC_VER) && !defined(_MSC_EXTENSIONS)
# define _MSC_EXTENSIONS
#endif
#if defined(__GNUC__) && __GNUC__ < 3
# define _GNU_SOURCE
#endif
#include <limits.h>
#include <stdio.h>
#include <string.h>
/* Due to shell differences and limitations of ADD_DEFINITIONS the
KWSYS_CXX_TYPE_INFO_FILE macro will sometimes have double quotes
and sometimes not. This macro will make sure the value is treated
as a double-quoted string. */
#define TO_STRING(x) TO_STRING0(x)
#define TO_STRING0(x) TO_STRING1(x)
#define TO_STRING1(x) #x
void f() {}
int main()
{
/* Construct the output file name. Some preprocessors will add an
extra level of double quotes, so strip them. */
char fbuf[] = TO_STRING(KWSYS_CXX_TYPE_INFO_FILE);
char* fname = fbuf;
if(fname[0] == '"')
{
++fname;
int len = static_cast<int>(strlen(fname));
if(len > 0 && fname[len-1] == '"')
{
fname[len-1] = 0;
}
}
/* Try to open the output file. */
if(FILE* fout = fopen(fname, "w"))
{
/* Set the size of standard types. */
fprintf(fout, "SET(KWSYS_SIZEOF_CHAR %d)\n", static_cast<int>(sizeof(char)));
fprintf(fout, "SET(KWSYS_SIZEOF_SHORT %d)\n", static_cast<int>(sizeof(short)));
fprintf(fout, "SET(KWSYS_SIZEOF_INT %d)\n", static_cast<int>(sizeof(int)));
fprintf(fout, "SET(KWSYS_SIZEOF_LONG %d)\n", static_cast<int>(sizeof(long)));
/* Set the size of some non-standard but common types. */
/* Check for a limits.h macro for long long to see if the type exists. */
#if defined(LLONG_MAX) || defined(LONG_LONG_MAX) || defined(LONGLONG_MAX)
fprintf(fout, "SET(KWSYS_SIZEOF_LONG_LONG %d)\n", static_cast<int>(sizeof(long long)));
#else
fprintf(fout, "SET(KWSYS_SIZEOF_LONG_LONG 0) # No long long available.\n");
#endif
/* Check for a limits.h macro for __int64 to see if the type exists. */
#if defined(_I64_MIN)
fprintf(fout, "SET(KWSYS_SIZEOF___INT64 %d)\n", static_cast<int>(sizeof(__int64)));
#else
fprintf(fout, "SET(KWSYS_SIZEOF___INT64 0) # No __int64 available.\n");
#endif
/* Set the size of some pointer types. */
fprintf(fout, "SET(KWSYS_SIZEOF_PDATA %d)\n", static_cast<int>(sizeof(void*)));
fprintf(fout, "SET(KWSYS_SIZEOF_PFUNC %d)\n", static_cast<int>(sizeof(&f)));
/* Set whether the native type "char" is signed or unsigned. */
unsigned char uc = 255;
fprintf(fout, "SET(KWSYS_CHAR_IS_SIGNED %d)\n",
(*reinterpret_cast<char*>(&uc) < 0)?1:0);
fclose(fout);
return 0;
}
else
{
fprintf(stderr, "Failed to write fundamental type info to \"%s\".\n",
fname);
return 1;
}
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_BORLAND_ASM
int main()
{
int a = 1;
__asm {
xor EBX, EBX;
mov a, EBX;
}
return a;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_BORLAND_ASM_CPUID
int main()
{
int a = 0;
__asm {
xor EAX, EAX;
cpuid;
mov a, EAX;
}
return a;
}
#endif
#ifdef TEST_KWSYS_STL_HAS_WSTRING
#include <string>
void f(std ::wstring*) {}
int main() { return 0; }
#endif
| [
"AndrewPiper@7b0d72ad-f3cb-b44e-b30e-0ca2391ac3a1"
] | AndrewPiper@7b0d72ad-f3cb-b44e-b30e-0ca2391ac3a1 |
0a12c928e0bdc819b44dc946484c35378f6cbd56 | f929a87be3d7acf5cdc136a23408802725902aa5 | /Assignment 3 - Daniel Wormald/OpenGLApplication/MyApplication.h | 56e340ff19c4449bc8f1f3a22dd9a21db2f63189 | [] | no_license | danielwormald/PhysicsAssignment | 0c857a680c379ec5722856e7c8af9c518c57ecf1 | e800a7eb7e19f8f1cc40e74a9d39bb579c563bae | refs/heads/master | 2021-01-10T12:44:46.396214 | 2015-12-03T10:19:10 | 2015-12-03T10:19:10 | 47,314,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,246 | h |
#ifndef MY_APPLICATION
#define MY_APPLICATION
#include "Application.h"
#include "gl_core_4_4.h"
#include "GLFW\glfw3.h"
#include <Gizmos.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "FlyCamera.h"
#include "Object.h"
#include "PhysicsObject.h"
#include "DIYRigidBody.h"
#include "Physics.h"
#include "DIYPhysicScene.h"
#include "Cube.h"
#include "Ball.h"
#include "SphereClass.h"
#include "Ragdoll.h"
#include "ParticleEmitter.h"
#include "ParticleFluidEmitter.h"
#include "Particle.h"
#include "PlayerController.h"
#include "MyControllerHitReport.h"
#include "MyCollisionCallback.h"
#include "TriggerBox.h"
using glm::vec2;
using glm::vec3;
using glm::vec4;
using glm::mat4;
class Camera;
class Physics1;
class DIYPhysicScene;
enum PhysicsType
{
PhysicsScene = 0,
DIYPhysicsScene = 1
};
class MyApplication : public Application
{
public:
virtual void StartUp();
virtual void Update();
virtual void Draw();
virtual void ShutDown();
void GenerateGrid(unsigned int rows, unsigned int cols);
unsigned int m_programID;
//Camera
Camera* m_pCamera;
//Physics
Physics1* m_physics;
PhysicsType type;
//DIYPhysics
DIYPhysicScene* m_DIYPhysics;
private:
float m_previousTime;
int m_ogl_Load;
};
#endif
| [
"dw@rms.com.au"
] | dw@rms.com.au |
0496d5b5123757c2e540d8a462c61105735cf14c | 16bb1ca4f642a3d9132df34c1a7a9afbc69f1ac5 | /TommyGun/Plugins/CodeEditor/ZXDebugFileManager.h | 072dfed564df5f391f13f87183f0a028608375dc | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | tonyt73/TommyGun | 6138b81b447da0b448bcecb893ed46cadcf56c80 | 19e704243bc02500193fe798bd3bee71f75de094 | refs/heads/master | 2023-03-17T10:19:08.971368 | 2023-03-11T23:39:37 | 2023-03-11T23:39:37 | 89,913,869 | 41 | 6 | NOASSERTION | 2023-03-11T22:41:39 | 2017-05-01T10:02:20 | C++ | UTF-8 | C++ | false | false | 969 | h | //---------------------------------------------------------------------------
#ifndef ZXDebugFileManagerH
#define ZXDebugFileManagerH
//- VCL ---------------------------------------------------------------------
#include <Classes.hpp>
//---------------------------------------------------------------------------
#include <map>
//---------------------------------------------------------------------------
class ZXDebugFileManager
{
public:
__fastcall ZXDebugFileManager();
__fastcall ~ZXDebugFileManager();
bool __fastcall LoadDebugFile(const String& DebugFile);
void __fastcall GetLocation(unsigned int Address, String& File, int& Line);
bool __fastcall DoesCodeExistAt(unsigned int Address);
private:
typedef struct
{
String File;
unsigned int Line;
} TFileInfo;
TFileInfo m_DebugMap[65536];
};
//---------------------------------------------------------------------------
#endif
| [
"tonyt73@gmail.com"
] | tonyt73@gmail.com |
f990b02ec508b64fe4c9072ba4a5c8fd4a2b7556 | de07787c195880351b84456627c0b3648cf902db | /util/Logger.h | 892f2528fc1200338631f8b3e710d39b9362a140 | [] | no_license | stevenchen1976/Ionet_echo | 6282051994beb6f8e50c10a75b6049daa5e25127 | cee1dccc8a197863dfd7fe6f4beed819ce5aa5de | refs/heads/master | 2022-03-17T23:47:10.907241 | 2019-05-10T02:50:43 | 2019-05-10T02:50:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | h | #ifndef _LOGGER_
#define _LOGGER_
#include <assert.h>
#include <string>
#include <vector>
#include <iostream>
#include <stdarg.h>
#include "Nocopyable.h"
namespace ionet
{
const int LEVEL_SIZE=5;//默认日志级别为5
class Logger:public nocopyable
{
public:
Logger(){}
enum{TRACE=0,DEBUG,INFO,WARN,ERROR};//定义日志级别
//日志输出函数
static void logging(int level, const std::string &file, int line, const char* fmat,...);
//设置日志级别
static void setCurrentLevel(int level);
private:
//输出流,可以是cout输出到显示器,也可以是ofstream输出到文件
static std::ostream& output;
//当前的日志级别
static int currentLevel;
//日志级别和日志级别字符串的映射
static std::vector<std::string> levelToStr;
};
}
#endif
| [
"972949726@qq.com"
] | 972949726@qq.com |
7e5668fe4679fd3bbdeda55bda290ad120ef03e8 | c690537ba968e144f76a0156ab815c88fad7d1d7 | /codebase/libs/FiltAlgVirtVol/src/include/FiltAlgVirtVol/VirtVolVolumeVirtualMethods.hh | c58b3a248a015b64b90f26a245915d5559bfa7e2 | [
"BSD-3-Clause"
] | permissive | paulyc/lrose-core | 52e9d6f7ae32e6292c0300a252772286f91949e2 | 84cdbbdd94126f6ea43bd69939d0801c7776e997 | refs/heads/master | 2022-08-22T14:08:23.238033 | 2020-05-23T23:50:43 | 2020-05-23T23:50:43 | 265,976,676 | 1 | 0 | NOASSERTION | 2020-05-23T23:50:45 | 2020-05-21T23:54:39 | null | UTF-8 | C++ | false | false | 948 | hh | #ifdef FILTALG_BASE
/**
* Pure virtual, Synchronize inputs for a user defined operation.
* Each user defined operation has it's own particular action,
*
* @param[in] userKey Keyword for the user operation, which the class
* should recognize
* @param[in] names Input data names
*
* @return true if successful
*/
virtual bool
virtVolSynchUserInputs(const std::string &userKey,
const std::vector<std::string> &names) = 0;
#else
/**
* Pure virtual, Synchronize inputs for a user defined operation.
* Each user defined operation has it's own particular action,
*
* @param[in] userKey Keyword for the user operation, which the class
* should recognize
* @param[in] names Input data names
*
* @return true if successful
*/
virtual bool
virtVolSynchUserInputs(const std::string &userKey,
const std::vector<std::string> &names);
#endif
| [
"dixon@ucar.edu"
] | dixon@ucar.edu |
dd5727e18cfaf475983512d40b0674d4ed220099 | 66deb611781cae17567efc4fd3717426d7df5e85 | /bksafevul/src_bksafevul/BeikeUtils/ExpEvaluate.cpp | 573cc489ad9d94fc94a30dfc446049a2a969389b | [
"Apache-2.0",
"LicenseRef-scancode-boost-original"
] | permissive | heguoxing98/knoss-pcmanager | 4671548e14b8b080f2d3a9f678327b06bf9660c9 | 283ca2e3b671caa85590b0f80da2440a3fab7205 | refs/heads/master | 2023-03-19T02:11:01.833194 | 2020-01-03T01:45:24 | 2020-01-03T01:45:24 | 504,422,245 | 1 | 0 | null | 2022-06-17T06:40:03 | 2022-06-17T06:40:02 | null | UTF-8 | C++ | false | false | 11,315 | cpp | /*
Parser - an expression parser
Author: Nick Gammon
http://www.gammon.com.au/
(C) Copyright Nick Gammon 2004. Permission to copy, use, modify, sell and
distribute this software is granted provided this copyright notice appears
in all copies. This software is provided "as is" without express or implied
warranty, and with no claim as to its suitability for any purpose.
Modified 24 October 2005 by Nick Gammon.
1. Changed use of "abs" to "fabs"
2. Changed inclues from math.h and time.h to fmath and ftime
3. Rewrote DoMin and DoMax to inline the computation because of some problems with some libraries.
4. Removed "using namespace std;" and put "std::" in front of std namespace names where appropriate
5. Removed MAKE_STRING macro and inlined the functionality where required.
6. Changed Evaluate function to take its argument by reference.
Thanks to various posters on my forum for suggestions. The relevant post is currently at:
http://www.gammon.com.au/forum/bbshowpost.php?bbsubject_id=4649
*/
#include <vector>
#include "ExpEvaluate.h"
/*
Expression-evaluator
--------------------
Author: Nick Gammon
-------------------
Example usage:
Parser p ("2 + 2 * (3 * 5) + nick");
p.symbols_ ["nick"] = 42;
double v = p.Evaluate ();
double v1 = p.Evaluate ("5 + 6"); // supply new expression and evaluate it
Syntax:
You can use normal algebraic syntax.
Multiply and divide has higher precedence than add and subtract.
You can use parentheses (eg. (2 + 3) * 5 )
Variables can be assigned, and tested. eg. a=24+a*2
Variables can be preloaded:
p.symbols_ ["abc"] = 42;
p.symbols_ ["def"] = 42;
Afterwards they can be retrieved:
x = p.symbols_ ["abc"];
There are 2 predefined symbols, "pi" and "e".
You can use the comma operator to load variables and then use them, eg.
a=42, b=a+6
You can use predefined functions, see below for examples of writing your own.
42 + sqrt (64)
Comparisons
-----------
Comparisons work by returning 1.0 if true, 0.0 if false.
Thus, 2 > 3 would return 0.0
3 > 2 would return 1.0
Similarly, tests for truth (eg. a && b) test whether the values are 0.0 or not.
If test
-------
There is a ternary function: if (truth-test, true-value, false-value)
eg. if (1 < 2, 22, 33) returns 22
Precedence
----------
( ) = - nested brackets, including function calls like sqrt (x), and assignment
* / - multiply, divide
+ - - add and subtract
< <= > >= == != - comparisons
&& || - AND and OR
, - comma operator
Credits:
Based in part on a simple calculator described in "The C++ Programming Language"
by Bjarne Stroustrup, however with considerable enhancements by me, and also based
on my earlier experience in writing Pascal compilers, which had a similar structure.
*/
const CExpEvaluate::TokenType CExpEvaluate::GetToken (const bool ignoreSign)
{
m_word.erase (0, std::string::npos);
// skip spaces
while (*m_pWord && isspace (*m_pWord))
++m_pWord;
m_pWordStart = m_pWord; // remember where word_ starts *now*
// look out for unterminated statements and things
if (*m_pWord == 0 && // we have EOF
m_type == TOKEN_END) // after already detecting it
throw std::runtime_error ("Unexpected end of expression.");
unsigned char cFirstCharacter = *m_pWord; // first character in new word_
if (cFirstCharacter == 0) // stop at end of file
{
m_word = "<end of expression>";
return m_type = TOKEN_END;
}
unsigned char cNextCharacter = *(m_pWord + 1); // 2nd character in new word_
// look for number
if ((!ignoreSign &&
(cFirstCharacter == '+' || cFirstCharacter == '-') &&
isdigit (cNextCharacter)
)
|| isdigit (cFirstCharacter))
{
// skip sign for now
if ((cFirstCharacter == '+' || cFirstCharacter == '-'))
m_pWord++;
while (isdigit (*m_pWord) || *m_pWord == '.')
m_pWord++;
// allow for 1.53158e+15
if (*m_pWord == 'e' || *m_pWord == 'E')
{
m_pWord++; // skip 'e'
if ((*m_pWord == '+' || *m_pWord == '-'))
m_pWord++; // skip sign after e
while (isdigit (*m_pWord)) // now digits after e
m_pWord++;
}
m_word = std::string (m_pWordStart, m_pWord - m_pWordStart);
std::istringstream is (m_word);
// parse std::string into double value
is >> m_value;
if (is.fail () || !is.eof ())
throw std::runtime_error ("Bad numeric literal: " + m_word);
return m_type = TOKEN_NUMBER;
} // end of number found
// special test for 2-character sequences: <= >= == !=
// also +=, -=, /=, *=
if (cNextCharacter == '=')
{
switch (cFirstCharacter)
{
// comparisons
case '=': m_type = TOKEN_EQ; break;
case '<': m_type = TOKEN_LE; break;
case '>': m_type = TOKEN_GE; break;
case '!': m_type = TOKEN_NE; break;
// assignments
case '+': m_type = TOKEN_ASSIGN_ADD; break;
case '-': m_type = TOKEN_ASSIGN_SUB; break;
case '*': m_type = TOKEN_ASSIGN_MUL; break;
case '/': m_type = TOKEN_ASSIGN_DIV; break;
// none of the above
default: m_type = TOKEN_NONE; break;
} // end of switch on cFirstCharacter
if (m_type != TOKEN_NONE)
{
m_word = std::string (m_pWordStart, 2);
m_pWord += 2; // skip both characters
return m_type;
} // end of found one
} // end of *=
switch (cFirstCharacter)
{
case '&': if (cNextCharacter == '&') // &&
{
m_word = std::string (m_pWordStart, 2);
m_pWord += 2; // skip both characters
return m_type = TOKEN_AND;
}
break;
case '|': if (cNextCharacter == '|') // ||
{
m_word = std::string (m_pWordStart, 2);
m_pWord += 2; // skip both characters
return m_type = TOKEN_OR;
}
break;
// single-character symboles
case '=':
case '<':
case '>':
case '+':
case '-':
case '/':
case '*':
case '(':
case ')':
case ',':
case '!':
m_word = std::string (m_pWordStart, 1);
++m_pWord; // skip it
return m_type = TokenType (cFirstCharacter);
} // end of switch on cFirstCharacter
if(cFirstCharacter=='"')
{
const char* pFirst = ++m_pWord;
while(*m_pWord!=0 && *m_pWord!='"')
++ m_pWord;
if(*m_pWord==0)
throw std::runtime_error("string error");
m_word.assign(pFirst, m_pWord-pFirst);
++m_pWord;
return m_type = TOKEN_STRING;
}
if (!isalpha (cFirstCharacter))
{
if (cFirstCharacter < ' ')
{
std::ostringstream s;
s << "Unexpected character (decimal " << int (cFirstCharacter) << ")";
throw std::runtime_error (s.str ());
}
else
throw std::runtime_error ("Unexpected character: " + std::string (1, cFirstCharacter));
}
// we have a word (starting with A-Z) - pull it out
while (isalnum (*m_pWord) || *m_pWord == '_')
++m_pWord;
m_word = std::string (m_pWordStart, m_pWord - m_pWordStart);
return m_type = TOKEN_NAME;
} // end of Parser::GetToken
// change program and evaluate it
const double CExpEvaluate::Evaluate (const std::string & program, Function_EvaluateCallback pfn) // get result
{
// do same stuff constructor did
m_program = program;
m_pWord = m_program.c_str ();
m_type = TOKEN_NONE;
return Evaluate ( pfn );
}
const double CExpEvaluate::Evaluate( Function_EvaluateCallback pfn ) // get result
{
m_pfnCallback = pfn;
double v = CommaList (true);
if (m_type != TOKEN_END)
throw std::runtime_error ("Unexpected text at end of expression: " + std::string (m_pWordStart));
return v;
}
const double CExpEvaluate::CommaList (const bool get) // expr1, expr2
{
double left = Expression (get);
while (true)
{
switch (m_type)
{
case TOKEN_COMMA: left = Expression (true); break; // discard previous value
default: return left;
} // end of switch on type
} // end of loop
} // end of Parser::CommaList
const double CExpEvaluate::Expression (const bool get) // AND and OR
{
double left = Comparison (get);
while (true)
{
switch (m_type)
{
case TOKEN_AND:
{
double d = Comparison (true); // don't want short-circuit evaluation
left = (left != 0.0) && (d != 0.0);
}
break;
case TOKEN_OR:
{
double d = Comparison (true); // don't want short-circuit evaluation
left = (left != 0.0) || (d != 0.0);
}
break;
default: return left;
} // end of switch on type
} // end of loop
} // end of Parser::Expression
const double CExpEvaluate::Comparison (const bool get) // LT, GT, LE, EQ etc.
{
double left = AddSubtract (get);
while (true)
{
switch (m_type)
{
case TOKEN_LT: left = left < AddSubtract (true) ? 1.0 : 0.0; break;
case TOKEN_GT: left = left > AddSubtract (true) ? 1.0 : 0.0; break;
case TOKEN_LE: left = left <= AddSubtract (true) ? 1.0 : 0.0; break;
case TOKEN_GE: left = left >= AddSubtract (true) ? 1.0 : 0.0; break;
case TOKEN_EQ: left = left == AddSubtract (true) ? 1.0 : 0.0; break;
case TOKEN_NE: left = left != AddSubtract (true) ? 1.0 : 0.0; break;
default: return left;
} // end of switch on type
} // end of loop
} // end of Parser::Comparison
const double CExpEvaluate::AddSubtract (const bool get) // add and subtract
{
double left = Term (get);
while (true)
{
switch (m_type)
{
case TOKEN_PLUS: left += Term (true); break;
case TOKEN_MINUS: left -= Term (true); break;
default: return left;
} // end of switch on type
} // end of loop
} // end of Parser::AddSubtract
const double CExpEvaluate::Term (const bool get) // multiply and divide
{
double left = Primary (get);
while (true)
{
switch (m_type)
{
case TOKEN_MULTIPLY:
left *= Primary (true); break;
case TOKEN_DIVIDE:
{
double d = Primary (true);
if (d == 0.0)
throw std::runtime_error ("Divide by zero");
left /= d;
break;
}
default: return left;
} // end of switch on type
} // end of loop
} // end of Parser::Term
const double CExpEvaluate::Primary (const bool get) // primary (base) tokens
{
if (get)
GetToken (); // one-token lookahead
switch (m_type)
{
case TOKEN_NUMBER:
{
double v = m_value;
GetToken (true); // get next one (one-token lookahead)
return v;
}
case TOKEN_NAME:
{
std::string word = m_word;
GetToken (true);
if (m_type == TOKEN_LHPAREN)
{
std::vector<std::string> params;
while(true)
{
GetToken(true);
if(m_type==TOKEN_RHPAREN)
break;
else if(m_type==TOKEN_STRING||m_type==TOKEN_NAME||m_type==TOKEN_NUMBER)
{
params.push_back( m_word );
GetToken( true );
if(m_type==TOKEN_RHPAREN)
break;
else if(m_type!=TOKEN_COMMA)
return 0.0;
}
}
GetToken();
double v = 0.0;
if( m_pfnCallback(word.c_str(), params, v) )
return v;
// evaluation function funname(params)
return v; // and return new value
} // end of switch on type_
}
case TOKEN_MINUS: // unary minus
return - Primary (true);
case TOKEN_NOT: // unary not
return (Primary (true) == 0.0) ? 1.0 : 0.0;;
case TOKEN_LHPAREN:
{
double v = CommaList (true); // inside parens, you could have commas
CheckToken (TOKEN_RHPAREN);
GetToken (); // eat the )
return v;
}
default:
throw std::runtime_error ("Unexpected token: " + m_word);
} // end of switch on type
throw std::runtime_error ("Unexpected token: " + m_word);
} // end of Parser::Primary
| [
"dreamsxin@qq.com"
] | dreamsxin@qq.com |
ef9284be2df2e63ab9afc11e51525d25432ef408 | 383288a72568edbca59c1551711659387afcc250 | /17.5 二进制文件随机读取/random.cpp | 0f00d091c6347b6dfd08a83729dc5172b281076f | [] | no_license | dongfeng86/CppPrimerPlus-SourceCode | caf7ce8867d759cea37a7021f57580a4c58e3213 | 79c3505c67d88d38d6af89ffb0b9588a5461b3a7 | refs/heads/master | 2023-09-04T00:16:33.162076 | 2023-08-25T09:44:39 | 2023-08-25T09:44:39 | 199,538,001 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 3,051 | cpp | /*
本文件主要展示了文件随机访问的应用。随机访问的关键是理解seekp()和seekg()两个函数
*/
#include<iostream>
#include<fstream>
#include<iomanip>
#include<cstdlib>
const int LIM = 20;
struct planet
{
char name[20];
double population;
double g;
};
const char * file = "planets.dat";
inline void Eatline() { while (std::cin.get() != '\n') continue; }
int main()
{
using namespace std;
planet pl;
cout << fixed;
//下面用读写模式打开文档,显示其初始内容
fstream finout;
finout.open(file, ios_base::in | ios_base::out | ios_base::binary);
int ct = 0;
if (finout.is_open())
{
//将输入指针定位到文件开始的地方,注意,在这种文件流模式下,输入和输出指针实际上是一样的
finout.seekg(0);
cout << "Here are the current contents of the"
<< file << " file:\n";
while (finout.read((char *)&pl, sizeof pl))
{
cout << ct++ << ": " << setw(LIM) << pl.name << ": "
<< setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << endl;
}
if (finout.eof())
finout.clear();
else
{
cerr << "Error in reading " << file << ".\n";
exit(EXIT_FAILURE);
}
}
else
{
cerr << file << " could not be opened -- bye.\n";
exit(EXIT_FAILURE);
}
//更改一个条目
cout << "Enter the record number you wish to change:";
long rec;
cin >> rec;
Eatline();
if (rec < 0 || rec >= ct)
{
cerr << "invalid record number -- bye\n";
exit(EXIT_FAILURE);
}
streampos place = rec * sizeof pl; //计算文件指针的偏移量
finout.seekg(place); //将输入指针放置到place这个位置
if (finout.fail())
{
cerr << "Error on attempt seek\n";
exit(EXIT_FAILURE);
}
finout.read((char *)& pl, sizeof pl); //开始在place这个位置读取,注意,随着读取的进行,指针(输入/输出)一直在移动
cout << "your selection:\n";
cout << rec << ":" << setw(LIM) << pl.name << ":"
<< setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << endl;
if (finout.eof())
finout.clear(); //清除eof 标志
cout << "Enter planet name: ";
cin.get(pl.name, LIM);
//Eatline();
cout << "enter planetary population:";
cin >> pl.population;
cout << "enter planet's acceleration of gravity:";
cin >> pl.g;
finout.seekp(place); //将输出指针放置到place这个位置
finout.write((char *)&pl, sizeof pl) << flush;
if (finout.fail())
{
cerr << "Error on attemped write\n";
exit(EXIT_FAILURE);
}
//show revised file
ct = 0;
finout.seekg(0); //将输入指针放置到初始位置
cout << "Here are the new contents of the " << file
<< " file:\n";
while (finout.read((char *)&pl, sizeof pl))
{
cout << ct++ << ": " << setw(LIM) << pl.name << ":"
<< setprecision(0) << setw(12) << pl.population
<< setprecision(2) << setw(6) << pl.g << endl;
}
finout.close();
cout << "Done.\n";
return 0;
} | [
"115949168@qq.com"
] | 115949168@qq.com |
823c47bcde1926c5dc8ca58f889c42ec9b641a29 | 764861302abdfb4b92e84421d2ccb4b32ed7137a | /Zones.h | 9ea4edafbb7736ba199a132d9c15b591d1a4db61 | [] | no_license | Fabian68/bgi | 80d482537ad1109c78792e49fbb1a228acda0cca | a8d97d6364314aba7347fe1ef2a5cab690ad79f4 | refs/heads/master | 2022-12-27T14:17:54.921635 | 2020-09-22T10:07:34 | 2020-09-22T10:07:34 | 227,630,110 | 0 | 1 | null | 2020-07-29T13:18:12 | 2019-12-12T14:50:11 | C++ | UTF-8 | C++ | false | false | 339 | h | #pragma once
#include <fstream>
#include "Equipes.h"
class Zones
{
public:
Zones();
void ecrireZone();
void equipeEnZone(int i,Equipes & E);
void choixNiveau(int i);
int niveauActuel()const;
int niveauMax()const;
int nbPersoJouable()const;
void niveauBattu();
void zoneBattue();
private:
int _niveauActuel;
int _niveauMax;
};
| [
"Fabian@PC-DE-FABIAN"
] | Fabian@PC-DE-FABIAN |
f0d6f47aeb4a40a57b3c5e78ea5b38582bda73b6 | 8e7d99956cd753fa7ce9c749a2519908ab67213f | /dnd/dungeon/jbdungeonpaintergd.cpp | f8cff54de620cd09b1dd3ad731e036e9b5062547 | [
"MIT"
] | permissive | spicyjack/dungeon_src | 28eb7e86a253fd01d407b3cfa3b3effa18bf12d0 | 3b35c84e997fb0f5a1bd2b7da188dda80bc37534 | refs/heads/master | 2021-01-11T11:07:07.222884 | 2016-11-04T16:45:51 | 2016-11-04T16:45:51 | 72,866,876 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,760 | cpp | /* ---------------------------------------------------------------------- *
* This file is in the public domain, and may be used, modified, and
* distributed without restriction (though the author would like to be
* given credit).
* ---------------------------------------------------------------------- *
* JBDungeonPainterGD
*
* Author: Jamis Buck
* Homepage: http://rover.byu.edu/jgb3/generators.html
*
* These routines require the existance of the GD library (available from
* http://www.boutell.com/gd/), as well as any other libraries the GD
* library requires (most notably libpng, libjpeg, and libz).
* ---------------------------------------------------------------------- */
#include <string.h>
#include "jbdungeon.h"
#include "jbdungeonpaintergd.h"
#include "gdfontt.h"
#include "gdfonts.h"
#include "gdfontmb.h"
#include "gdfontl.h"
#include "gdfontg.h"
JBDungeonPainterGD::JBDungeonPainterGD( JBDungeon* dungeon, int gridSize, int border )
: JBDungeonPainter( dungeon, gridSize, border )
{
m_image = gdImageCreate( getCanvasWidth(), getCanvasHeight() );
}
JBDungeonPainterGD::~JBDungeonPainterGD() {
gdImageDestroy( m_image );
}
void JBDungeonPainterGD::m_rectangle( int x1, int y1, int x2, int y2, long color, bool filled ) {
if( filled ) {
gdImageFilledRectangle( m_image, x1, y1, x2, y2, color );
} else {
gdImageRectangle( m_image, x1, y1, x2, y2, color );
}
}
void JBDungeonPainterGD::m_line( int x1, int y1, int x2, int y2, long color ) {
gdImageLine( m_image, x1, y1, x2, y2, color );
}
void JBDungeonPainterGD::m_string( int x, int y, char* text, long color, void* font ) {
gdImageString( m_image, (gdFontPtr)font, x, y, (unsigned char*)text, color );
}
void JBDungeonPainterGD::m_char( int x, int y, char c, long color, void* font ) {
gdImageChar( m_image, (gdFontPtr)font, x, y, c, color );
}
void JBDungeonPainterGD::m_charUp( int x, int y, char c, long color, void* font ) {
gdImageCharUp( m_image, (gdFontPtr)font, x, y, c, color );
}
void* JBDungeonPainterGD::m_selectFontToFit( char* text, int width ) {
gdFontPtr fonts[] = { gdFontGiant, gdFontLarge, gdFontMediumBold, gdFontSmall, gdFontTiny, 0 };
int i;
int length;
length = strlen( text );
for( i = 0; fonts[ i ] != 0; i++ ) {
if( length * fonts[ i ]->w <= width ) {
return (void*)( fonts[ i ] );
}
}
return (void*)( gdFontTiny );
}
long JBDungeonPainterGD::m_allocateColor( int red, int green, int blue ) {
return gdImageColorAllocate( m_image, red, green, blue );
}
int JBDungeonPainterGD::getFontWidth( void* font ) {
gdFontPtr f = (gdFontPtr)font;
return f->w;
}
int JBDungeonPainterGD::getFontHeight( void* font ) {
gdFontPtr f = (gdFontPtr)font;
return f->h;
}
| [
"brian@xaoc.org"
] | brian@xaoc.org |
00ec6bb4a02f2278dc0ff840385a322c1c19f245 | 0ad9ea78b70b8b476693840bfac9dca19d3c959a | /Dependencies/Include/IMGUI/imgui_impl_sdl.cpp | 96fb7fbc8b6d1df5b481ce6562e37831975a0c89 | [
"MIT"
] | permissive | JordiRomagosa/Sonata-Engine | 8e0927109e5c462c6c692d65fef30e57ebe73127 | a1150c9eb8cb672cdd9a4080af458019914f0d81 | refs/heads/master | 2020-09-10T03:55:34.242749 | 2019-11-25T10:36:37 | 2019-11-25T10:36:37 | 221,642,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,714 | cpp | // dear imgui: Platform Binding for SDL2
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
// (Requires: SDL 2.0. Prefer SDL 2.0.4+ for full feature support.)
// Implemented features:
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Clipboard support.
// [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE).
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
// Missing features:
// [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME.
// [ ] Platform: Multi-viewport + Minimized windows seems to break mouse wheel events (at least under Windows).
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2019-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
// 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
// 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls.
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
// 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'.
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples.
// 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter.
// 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText).
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
// 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS.
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h"
#include "imgui_impl_sdl.h"
// SDL
// (the multi-viewports feature requires SDL features supported from SDL 2.0.4+. SDL 2.0.5+ is highly recommended)
#include <SDL/SDL.h>
#include <SDL/SDL_syswm.h>
#if defined(__APPLE__)
#include "TargetConditionals.h"
#endif
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE SDL_VERSION_ATLEAST(2,0,4)
#define SDL_HAS_WINDOW_ALPHA SDL_VERSION_ATLEAST(2,0,5)
#define SDL_HAS_ALWAYS_ON_TOP SDL_VERSION_ATLEAST(2,0,5)
#define SDL_HAS_USABLE_DISPLAY_BOUNDS SDL_VERSION_ATLEAST(2,0,5)
#define SDL_HAS_PER_MONITOR_DPI SDL_VERSION_ATLEAST(2,0,4)
#define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6)
#define SDL_HAS_MOUSE_FOCUS_CLICKTHROUGH SDL_VERSION_ATLEAST(2,0,5)
#if !SDL_HAS_VULKAN
static const Uint32 SDL_WINDOW_VULKAN = 0x10000000;
#endif
// Data
static SDL_Window* g_Window = NULL;
static Uint64 g_Time = 0;
static bool g_MousePressed[3] = { false, false, false };
static SDL_Cursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {};
static char* g_ClipboardTextData = NULL;
// Forward Declarations
static void ImGui_ImplSDL2_InitPlatformInterface(SDL_Window* window, void* sdl_gl_context);
static void ImGui_ImplSDL2_ShutdownPlatformInterface();
static const char* ImGui_ImplSDL2_GetClipboardText(void*)
{
if (g_ClipboardTextData)
SDL_free(g_ClipboardTextData);
g_ClipboardTextData = SDL_GetClipboardText();
return g_ClipboardTextData;
}
static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text)
{
SDL_SetClipboardText(text);
}
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.
bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
{
ImGuiIO& io = ImGui::GetIO();
switch (event->type)
{
case SDL_MOUSEWHEEL:
{
if (event->wheel.x > 0) io.MouseWheelH += 1;
if (event->wheel.x < 0) io.MouseWheelH -= 1;
if (event->wheel.y > 0) io.MouseWheel += 1;
if (event->wheel.y < 0) io.MouseWheel -= 1;
return true;
}
case SDL_MOUSEBUTTONDOWN:
{
if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
return true;
}
case SDL_TEXTINPUT:
{
io.AddInputCharactersUTF8(event->text.text);
return true;
}
case SDL_KEYDOWN:
case SDL_KEYUP:
{
int key = event->key.keysym.scancode;
IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown));
io.KeysDown[key] = (event->type == SDL_KEYDOWN);
io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0);
return true;
}
// Multi-viewport support
case SDL_WINDOWEVENT:
Uint8 window_event = event->window.event;
if (window_event == SDL_WINDOWEVENT_CLOSE || window_event == SDL_WINDOWEVENT_MOVED || window_event == SDL_WINDOWEVENT_RESIZED)
if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)SDL_GetWindowFromID(event->window.windowID)))
{
if (window_event == SDL_WINDOWEVENT_CLOSE)
viewport->PlatformRequestClose = true;
if (window_event == SDL_WINDOWEVENT_MOVED)
viewport->PlatformRequestMove = true;
if (window_event == SDL_WINDOWEVENT_RESIZED)
viewport->PlatformRequestResize = true;
return true;
}
break;
}
return false;
}
static bool ImGui_ImplSDL2_Init(SDL_Window* window, void* sdl_gl_context)
{
g_Window = window;
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
#endif
io.BackendPlatformName = "imgui_impl_sdl";
// Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE;
io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE;
io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN;
io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE;
io.KeyMap[ImGuiKey_KeyPadEnter] = SDL_SCANCODE_RETURN2;
io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A;
io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C;
io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V;
io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X;
io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y;
io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z;
io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
io.ClipboardUserData = NULL;
g_MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
g_MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
g_MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
g_MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
g_MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
g_MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
// Our mouse update function expect PlatformHandle to be filled for the main viewport
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
main_viewport->PlatformHandle = (void*)window;
#if defined(_WIN32)
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (SDL_GetWindowWMInfo(window, &info))
main_viewport->PlatformHandleRaw = info.info.win.window;
#endif
// We need SDL_CaptureMouse(), SDL_GetGlobalMouseState() from SDL 2.0.4+ to support multiple viewports.
// We left the call to ImGui_ImplSDL2_InitPlatformInterface() outside of #ifdef to avoid unused-function warnings.
if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports))
ImGui_ImplSDL2_InitPlatformInterface(window, sdl_gl_context);
return true;
}
bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
{
(void)sdl_gl_context; // Viewport branch will need this.
return ImGui_ImplSDL2_Init(window, sdl_gl_context);
}
bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window)
{
#if !SDL_HAS_VULKAN
IM_ASSERT(0 && "Unsupported");
#endif
return ImGui_ImplSDL2_Init(window, NULL);
}
bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window)
{
#if !defined(_WIN32)
IM_ASSERT(0 && "Unsupported");
#endif
return ImGui_ImplSDL2_Init(window, NULL);
}
void ImGui_ImplSDL2_Shutdown()
{
ImGui_ImplSDL2_ShutdownPlatformInterface();
g_Window = NULL;
// Destroy last known clipboard data
if (g_ClipboardTextData)
SDL_free(g_ClipboardTextData);
g_ClipboardTextData = NULL;
// Destroy SDL mouse cursors
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
SDL_FreeCursor(g_MouseCursors[cursor_n]);
memset(g_MouseCursors, 0, sizeof(g_MouseCursors));
}
// This code is incredibly messy because some of the functions we need for full viewport support are not available in SDL < 2.0.4.
static void ImGui_ImplSDL2_UpdateMousePosAndButtons()
{
ImGuiIO& io = ImGui::GetIO();
io.MouseHoveredViewport = 0;
// [1]
// Only when requested by io.WantSetMousePos: set OS mouse pos from Dear ImGui mouse pos.
// (rarely used, mostly when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
if (io.WantSetMousePos)
{
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
SDL_WarpMouseGlobal((int)io.MousePos.x, (int)io.MousePos.y);
else
#endif
SDL_WarpMouseInWindow(g_Window, (int)io.MousePos.x, (int)io.MousePos.y);
}
else
{
io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
}
// [2]
// Set Dear ImGui mouse pos from OS mouse pos + get buttons. (this is the common behavior)
int mouse_x_local, mouse_y_local;
Uint32 mouse_buttons = SDL_GetMouseState(&mouse_x_local, &mouse_y_local);
io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io.MouseDown[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS)
// SDL 2.0.4 and later has SDL_GetGlobalMouseState() and SDL_CaptureMouse()
int mouse_x_global, mouse_y_global;
SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global);
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
// Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
if (SDL_Window* focused_window = SDL_GetKeyboardFocus())
if (ImGui::FindViewportByPlatformHandle((void*)focused_window) != NULL)
io.MousePos = ImVec2((float)mouse_x_global, (float)mouse_y_global);
}
else
{
// Single-viewport mode: mouse position in client window coordinatesio.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
if (SDL_GetWindowFlags(g_Window) & SDL_WINDOW_INPUT_FOCUS)
{
int window_x, window_y;
SDL_GetWindowPosition(g_Window, &window_x, &window_y);
io.MousePos = ImVec2((float)(mouse_x_global - window_x), (float)(mouse_y_global - window_y));
}
}
// SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger the OS window resize cursor.
// The function is only supported from SDL 2.0.4 (released Jan 2016)
bool any_mouse_button_down = ImGui::IsAnyMouseDown();
SDL_CaptureMouse(any_mouse_button_down ? SDL_TRUE : SDL_FALSE);
#else
// SDL 2.0.3 and before: single-viewport only
if (SDL_GetWindowFlags(g_Window) & SDL_WINDOW_INPUT_FOCUS)
io.MousePos = ImVec2((float)mouse_x_local, (float)mouse_y_local);
#endif
}
static void ImGui_ImplSDL2_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
SDL_ShowCursor(SDL_FALSE);
}
else
{
// Show OS mouse cursor
SDL_SetCursor(g_MouseCursors[imgui_cursor] ? g_MouseCursors[imgui_cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
SDL_ShowCursor(SDL_TRUE);
}
}
static void ImGui_ImplSDL2_UpdateGamepads()
{
ImGuiIO& io = ImGui::GetIO();
memset(io.NavInputs, 0, sizeof(io.NavInputs));
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
// Get gamepad
SDL_GameController* game_controller = SDL_GameControllerOpen(0);
if (!game_controller)
{
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
return;
}
// Update gamepad inputs
#define MAP_BUTTON(NAV_NO, BUTTON_NO) { io.NavInputs[NAV_NO] = (SDL_GameControllerGetButton(game_controller, BUTTON_NO) != 0) ? 1.0f : 0.0f; }
#define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GameControllerGetAxis(game_controller, AXIS_NO) - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; }
const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value.
MAP_BUTTON(ImGuiNavInput_Activate, SDL_CONTROLLER_BUTTON_A); // Cross / A
MAP_BUTTON(ImGuiNavInput_Cancel, SDL_CONTROLLER_BUTTON_B); // Circle / B
MAP_BUTTON(ImGuiNavInput_Menu, SDL_CONTROLLER_BUTTON_X); // Square / X
MAP_BUTTON(ImGuiNavInput_Input, SDL_CONTROLLER_BUTTON_Y); // Triangle / Y
MAP_BUTTON(ImGuiNavInput_DpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); // D-Pad Left
MAP_BUTTON(ImGuiNavInput_DpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); // D-Pad Right
MAP_BUTTON(ImGuiNavInput_DpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); // D-Pad Up
MAP_BUTTON(ImGuiNavInput_DpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); // D-Pad Down
MAP_BUTTON(ImGuiNavInput_FocusPrev, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB
MAP_BUTTON(ImGuiNavInput_FocusNext, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB
MAP_BUTTON(ImGuiNavInput_TweakSlow, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB
MAP_BUTTON(ImGuiNavInput_TweakFast, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB
MAP_ANALOG(ImGuiNavInput_LStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiNavInput_LStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiNavInput_LStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32767);
MAP_ANALOG(ImGuiNavInput_LStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767);
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
#undef MAP_BUTTON
#undef MAP_ANALOG
}
void ImGui_ImplSDL2_NewFrame(SDL_Window* window)
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
SDL_GetWindowSize(window, &w, &h);
SDL_GL_GetDrawableSize(window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
if (w > 0 && h > 0)
io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
// Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
static Uint64 frequency = SDL_GetPerformanceFrequency();
Uint64 current_time = SDL_GetPerformanceCounter();
io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f);
g_Time = current_time;
ImGui_ImplSDL2_UpdateMousePosAndButtons();
ImGui_ImplSDL2_UpdateMouseCursor();
// Update game controllers (if enabled and available)
ImGui_ImplSDL2_UpdateGamepads();
}
//--------------------------------------------------------------------------------------------------------
// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
// This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
//--------------------------------------------------------------------------------------------------------
struct ImGuiViewportDataSDL2
{
SDL_Window* Window;
Uint32 WindowID;
bool WindowOwned;
SDL_GLContext GLContext;
ImGuiViewportDataSDL2() { Window = NULL; WindowID = 0; WindowOwned = false; GLContext = NULL; }
~ImGuiViewportDataSDL2() { IM_ASSERT(Window == NULL && GLContext == NULL); }
};
static void ImGui_ImplSDL2_CreateWindow(ImGuiViewport* viewport)
{
ImGuiViewportDataSDL2* data = IM_NEW(ImGuiViewportDataSDL2)();
viewport->PlatformUserData = data;
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
ImGuiViewportDataSDL2* main_viewport_data = (ImGuiViewportDataSDL2*)main_viewport->PlatformUserData;
// Share GL resources with main context
bool use_opengl = (main_viewport_data->GLContext != NULL);
SDL_GLContext backup_context = NULL;
if (use_opengl)
{
backup_context = SDL_GL_GetCurrentContext();
SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
SDL_GL_MakeCurrent(main_viewport_data->Window, main_viewport_data->GLContext);
}
Uint32 sdl_flags = 0;
sdl_flags |= use_opengl ? SDL_WINDOW_OPENGL : SDL_WINDOW_VULKAN;
sdl_flags |= SDL_GetWindowFlags(g_Window) & SDL_WINDOW_ALLOW_HIGHDPI;
sdl_flags |= SDL_WINDOW_HIDDEN;
sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? SDL_WINDOW_BORDERLESS : 0;
sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? 0 : SDL_WINDOW_RESIZABLE;
#if SDL_HAS_ALWAYS_ON_TOP
sdl_flags |= (viewport->Flags & ImGuiViewportFlags_TopMost) ? SDL_WINDOW_ALWAYS_ON_TOP : 0;
#endif
data->Window = SDL_CreateWindow("No Title Yet", (int)viewport->Pos.x, (int)viewport->Pos.y, (int)viewport->Size.x, (int)viewport->Size.y, sdl_flags);
data->WindowOwned = true;
if (use_opengl)
{
data->GLContext = SDL_GL_CreateContext(data->Window);
SDL_GL_SetSwapInterval(0);
}
if (use_opengl && backup_context)
SDL_GL_MakeCurrent(data->Window, backup_context);
viewport->PlatformHandle = (void*)data->Window;
#if defined(_WIN32)
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (SDL_GetWindowWMInfo(data->Window, &info))
viewport->PlatformHandleRaw = info.info.win.window;
#endif
}
static void ImGui_ImplSDL2_DestroyWindow(ImGuiViewport* viewport)
{
if (ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData)
{
if (data->GLContext && data->WindowOwned)
SDL_GL_DeleteContext(data->GLContext);
if (data->Window && data->WindowOwned)
SDL_DestroyWindow(data->Window);
data->GLContext = NULL;
data->Window = NULL;
IM_DELETE(data);
}
viewport->PlatformUserData = viewport->PlatformHandle = NULL;
}
static void ImGui_ImplSDL2_ShowWindow(ImGuiViewport* viewport)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
#if defined(_WIN32)
HWND hwnd = (HWND)viewport->PlatformHandleRaw;
// SDL hack: Hide icon from task bar
// Note: SDL 2.0.6+ has a SDL_WINDOW_SKIP_TASKBAR flag which is supported under Windows but the way it create the window breaks our seamless transition.
if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon)
{
LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
ex_style &= ~WS_EX_APPWINDOW;
ex_style |= WS_EX_TOOLWINDOW;
::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
}
// SDL hack: SDL always activate/focus windows :/
if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
{
::ShowWindow(hwnd, SW_SHOWNA);
return;
}
#endif
SDL_ShowWindow(data->Window);
}
static ImVec2 ImGui_ImplSDL2_GetWindowPos(ImGuiViewport* viewport)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
int x = 0, y = 0;
SDL_GetWindowPosition(data->Window, &x, &y);
return ImVec2((float)x, (float)y);
}
static void ImGui_ImplSDL2_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
SDL_SetWindowPosition(data->Window, (int)pos.x, (int)pos.y);
}
static ImVec2 ImGui_ImplSDL2_GetWindowSize(ImGuiViewport* viewport)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
int w = 0, h = 0;
SDL_GetWindowSize(data->Window, &w, &h);
return ImVec2((float)w, (float)h);
}
static void ImGui_ImplSDL2_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
SDL_SetWindowSize(data->Window, (int)size.x, (int)size.y);
}
static void ImGui_ImplSDL2_SetWindowTitle(ImGuiViewport* viewport, const char* title)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
SDL_SetWindowTitle(data->Window, title);
}
#if SDL_HAS_WINDOW_ALPHA
static void ImGui_ImplSDL2_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
SDL_SetWindowOpacity(data->Window, alpha);
}
#endif
static void ImGui_ImplSDL2_SetWindowFocus(ImGuiViewport* viewport)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
SDL_RaiseWindow(data->Window);
}
static bool ImGui_ImplSDL2_GetWindowFocus(ImGuiViewport* viewport)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
return (SDL_GetWindowFlags(data->Window) & SDL_WINDOW_INPUT_FOCUS) != 0;
}
static bool ImGui_ImplSDL2_GetWindowMinimized(ImGuiViewport* viewport)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
return (SDL_GetWindowFlags(data->Window) & SDL_WINDOW_MINIMIZED) != 0;
}
static void ImGui_ImplSDL2_RenderWindow(ImGuiViewport* viewport, void*)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
if (data->GLContext)
SDL_GL_MakeCurrent(data->Window, data->GLContext);
}
static void ImGui_ImplSDL2_SwapBuffers(ImGuiViewport* viewport, void*)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
if (data->GLContext)
{
SDL_GL_MakeCurrent(data->Window, data->GLContext);
SDL_GL_SwapWindow(data->Window);
}
}
// Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface)
// SDL is graceful enough to _not_ need <vulkan/vulkan.h> so we can safely include this.
#if SDL_HAS_VULKAN
#include <SDL/SDL_vulkan.h>
static int ImGui_ImplSDL2_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface)
{
ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData;
(void)vk_allocator;
SDL_bool ret = SDL_Vulkan_CreateSurface(data->Window, (VkInstance)vk_instance, (VkSurfaceKHR*)out_vk_surface);
return ret ? 0 : 1; // ret ? VK_SUCCESS : VK_NOT_READY
}
#endif // SDL_HAS_VULKAN
// FIXME-PLATFORM: SDL doesn't have an event to notify the application of display/monitor changes
static void ImGui_ImplSDL2_UpdateMonitors()
{
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
platform_io.Monitors.resize(0);
int display_count = SDL_GetNumVideoDisplays();
for (int n = 0; n < display_count; n++)
{
// Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime.
ImGuiPlatformMonitor monitor;
SDL_Rect r;
SDL_GetDisplayBounds(n, &r);
monitor.MainPos = monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
monitor.MainSize = monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
#if SDL_HAS_USABLE_DISPLAY_BOUNDS
SDL_GetDisplayUsableBounds(n, &r);
monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
#endif
#if SDL_HAS_PER_MONITOR_DPI
float dpi = 0.0f;
if (!SDL_GetDisplayDPI(n, &dpi, NULL, NULL))
monitor.DpiScale = dpi / 96.0f;
#endif
platform_io.Monitors.push_back(monitor);
}
}
static void ImGui_ImplSDL2_InitPlatformInterface(SDL_Window* window, void* sdl_gl_context)
{
// Register platform interface (will be coupled with a renderer interface)
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
platform_io.Platform_CreateWindow = ImGui_ImplSDL2_CreateWindow;
platform_io.Platform_DestroyWindow = ImGui_ImplSDL2_DestroyWindow;
platform_io.Platform_ShowWindow = ImGui_ImplSDL2_ShowWindow;
platform_io.Platform_SetWindowPos = ImGui_ImplSDL2_SetWindowPos;
platform_io.Platform_GetWindowPos = ImGui_ImplSDL2_GetWindowPos;
platform_io.Platform_SetWindowSize = ImGui_ImplSDL2_SetWindowSize;
platform_io.Platform_GetWindowSize = ImGui_ImplSDL2_GetWindowSize;
platform_io.Platform_SetWindowFocus = ImGui_ImplSDL2_SetWindowFocus;
platform_io.Platform_GetWindowFocus = ImGui_ImplSDL2_GetWindowFocus;
platform_io.Platform_GetWindowMinimized = ImGui_ImplSDL2_GetWindowMinimized;
platform_io.Platform_SetWindowTitle = ImGui_ImplSDL2_SetWindowTitle;
platform_io.Platform_RenderWindow = ImGui_ImplSDL2_RenderWindow;
platform_io.Platform_SwapBuffers = ImGui_ImplSDL2_SwapBuffers;
#if SDL_HAS_WINDOW_ALPHA
platform_io.Platform_SetWindowAlpha = ImGui_ImplSDL2_SetWindowAlpha;
#endif
#if SDL_HAS_VULKAN
platform_io.Platform_CreateVkSurface = ImGui_ImplSDL2_CreateVkSurface;
#endif
// SDL2 by default doesn't pass mouse clicks to the application when the click focused a window. This is getting in the way of our interactions and we disable that behavior.
#if SDL_HAS_MOUSE_FOCUS_CLICKTHROUGH
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
#endif
ImGui_ImplSDL2_UpdateMonitors();
// Register main window handle (which is owned by the main application, not by us)
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
ImGuiViewportDataSDL2* data = IM_NEW(ImGuiViewportDataSDL2)();
data->Window = window;
data->WindowID = SDL_GetWindowID(window);
data->WindowOwned = false;
data->GLContext = sdl_gl_context;
main_viewport->PlatformUserData = data;
main_viewport->PlatformHandle = data->Window;
}
static void ImGui_ImplSDL2_ShutdownPlatformInterface()
{
}
| [
"jordi@shiraz.es"
] | jordi@shiraz.es |
4bf18cb39a3d94edde35e2cb2fde59d16af28ed0 | a3ad000cc7dd58cdb04b64acea01b42719099923 | /testgit/cb.cpp | 8a0fb7720261464c6cd13b4a3d4e2a30738c611a | [] | no_license | zheLee1019/C-primer | af64572aa159a311e41eccd4c27bade91dccf293 | 57392782772acd19dba252c2d94710246e153b22 | refs/heads/master | 2020-12-30T13:40:02.411926 | 2018-01-10T12:11:46 | 2018-01-10T12:11:46 | 91,241,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 110 | cpp | #include <iostream>
using namespace std;
int main()
{
cout<<"测试git"<<endl;
return 0;//第四版
}
| [
"nklizhe19@gmail.com"
] | nklizhe19@gmail.com |
5af6d09bf46a44602ff4935da89ac51046cb9fa9 | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/44/41.c | 7a7acfa9705ad4580aeb1ac103458764397a677c | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | c | int fanxu(int n)
{
int m,a[5];
a[4]=n/10000;a[3]=(n/1000)%10;a[2]=(n/100)%10;a[1]=(n/10)%10;a[0]=n%10;
if(a[4]!=0) m=10000*a[0]+1000*a[1]+100*a[2]+10*a[3]+a[4];
else if(a[4]==0&&a[3]!=0) m=1000*a[0]+100*a[1]+10*a[2]+a[3];
else if(a[4]==0&&a[3]==0&&a[2]!=0) m=100*a[0]+10*a[1]+a[2];
else if(a[4]==0&&a[3]==0&&a[2]==0&&a[1]!=0) m=10*a[0]+a[1];
else if(a[4]==0&&a[3]==0&&a[2]==0&&a[1]==0) m=n;
return(m);
}
void main()
{
int b[6],c[6],i;
for(i=0;i<6;i++)
{
scanf("%d",&b[i]);
c[i]=fanxu(b[i]);
}
for(i=0;i<6;i++)
printf("%d\n",c[i]);
} | [
"bdqnghi@gmail.com"
] | bdqnghi@gmail.com |
5cfdc2f3e1c3c17a33dc47bd68c51b815d140418 | 52f64708ba7560f5d16eef95b057a993ab73c787 | /dunjudge/multiples.cpp | d4b993df149384012fafd99319dd15ee9c8d450b | [] | no_license | ckpiyanon/submission | 1c5709755afeba8b5087fa29b12f9c2c931c4b68 | 7b3f546e3c1e10787a24f567c9f2ec1366bbaf5a | refs/heads/master | 2022-10-28T18:42:34.937505 | 2020-06-15T22:00:19 | 2020-06-15T22:00:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 126 | cpp | #include <cstdio>
int main() {
int n, m; scanf("%d %d", &n, &m);
for(int i = 1; i <= m; ++i) printf("%d\n", n * i);
} | [
"30414878+win11905@users.noreply.github.com"
] | 30414878+win11905@users.noreply.github.com |
1c86641a9ab1fc45daa1312e529b194bddde4b74 | 69b4f7c49f18fc193f49275a2d32ffbcbe70471d | /Codeforces/C. The Tag Game.cpp | 839b4d2c0bff9a54d6940d04741f2a2b2815993c | [] | no_license | TD2106/Competitive-Programming | 05f322a14f1e7a1d62633b713f1416ab0c547b3b | 2905c9d5f36909330fc3637f5461aaba8928a154 | refs/heads/master | 2020-04-03T12:59:49.790124 | 2019-09-21T14:51:08 | 2019-09-21T14:51:08 | 155,270,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | cpp | #include <bits/stdc++.h>
#define bug(x) cout << #x << " = " << x << endl
#define pb push_back
#define M 200005
using namespace std;
typedef long long int ll;
int d[M]={0},p[M],lowest[M]={0},n,Ti=0,x,y,b;
bool vis[M]={0};
vector< vector<int> > adj;
void dfs(int u,int parent){
lowest[u]=d[u]=d[parent]+1;
vis[u]=1;
p[u]=parent;
for(int i=0;i<adj[u].size();i++){
if(!vis[adj[u][i]]){
dfs(adj[u][i],u);
lowest[u]=max(lowest[u],lowest[adj[u][i]]);
}
}
}
int main(){
ios_base::sync_with_stdio(0);
cin>>n>>b;
adj.resize(n+1);
for(int i=0;i<n-1;i++){
cin>>x>>y;
adj[x].pb(y);
adj[y].pb(x);
}
dfs(1,0);
x=d[b]/2-1;
while(x--) b=p[b];
Ti=lowest[b];
Ti=2*(Ti-1);
cout<<Ti<<endl;
return 0;
}
| [
"duy.le@ubitec.ch"
] | duy.le@ubitec.ch |
85ba10929b43b033a755f36f4a2cf09eb6d48124 | 1d212c1b67a9a75fbc6843e5eb52b1c6ceb50c29 | /ImageSorter/MainForm.h | d7b8863fa6f9973b3b8f42c14ea52a7f097dfd12 | [] | no_license | Lider123/ImageSorter | 5ade0be7d36fe3d21b775720aa5ed24c4b4a2c19 | 0ebde6d2bb893d7e0faf52dc6da8c54ae7f63ecb | refs/heads/master | 2020-06-21T10:23:35.917213 | 2019-08-14T15:53:21 | 2019-08-14T15:53:21 | 197,420,692 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 18,957 | h | #pragma once
namespace ImageSorter {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
using namespace System::Collections::Generic;
/// <summary>
/// Сводка для MainForm
/// </summary>
public ref class MainForm : public System::Windows::Forms::Form
{
public:
MainForm(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~MainForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::MenuStrip^ menuStrip;
protected:
private: System::Windows::Forms::ToolStripMenuItem^ fileToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ openToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ closeToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ exitToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ toolsToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ orientationSortingToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ sizeFiltrationToolStripMenuItem;
private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog;
private: System::Windows::Forms::StatusStrip^ statusStrip;
private: System::Windows::Forms::ToolStripStatusLabel^ pathToolStripStatusLabel;
private: System::Windows::Forms::ToolStripStatusLabel^ countToolStripStatusLabel;
private: System::Windows::Forms::ToolStripProgressBar^ toolStripProgressBar;
private: System::Windows::Forms::Panel^ mainPanel;
private: System::Windows::Forms::Panel^ buttonsPanel;
private: System::Windows::Forms::PictureBox^ pictureBox;
private: System::Windows::Forms::Button^ buttonNext;
private: System::Windows::Forms::Button^ buttonPrev;
private:
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
void InitializeComponent(void)
{
this->menuStrip = (gcnew System::Windows::Forms::MenuStrip());
this->fileToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->openToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->closeToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->exitToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->toolsToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->orientationSortingToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->sizeFiltrationToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->folderBrowserDialog = (gcnew System::Windows::Forms::FolderBrowserDialog());
this->statusStrip = (gcnew System::Windows::Forms::StatusStrip());
this->pathToolStripStatusLabel = (gcnew System::Windows::Forms::ToolStripStatusLabel());
this->countToolStripStatusLabel = (gcnew System::Windows::Forms::ToolStripStatusLabel());
this->toolStripProgressBar = (gcnew System::Windows::Forms::ToolStripProgressBar());
this->mainPanel = (gcnew System::Windows::Forms::Panel());
this->pictureBox = (gcnew System::Windows::Forms::PictureBox());
this->buttonsPanel = (gcnew System::Windows::Forms::Panel());
this->buttonNext = (gcnew System::Windows::Forms::Button());
this->buttonPrev = (gcnew System::Windows::Forms::Button());
this->menuStrip->SuspendLayout();
this->statusStrip->SuspendLayout();
this->mainPanel->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox))->BeginInit();
this->buttonsPanel->SuspendLayout();
this->SuspendLayout();
//
// menuStrip
//
this->menuStrip->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) {
this->fileToolStripMenuItem,
this->toolsToolStripMenuItem
});
this->menuStrip->Location = System::Drawing::Point(0, 0);
this->menuStrip->Name = L"menuStrip";
this->menuStrip->Size = System::Drawing::Size(800, 24);
this->menuStrip->TabIndex = 0;
this->menuStrip->Text = L"menuStrip";
//
// fileToolStripMenuItem
//
this->fileToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) {
this->openToolStripMenuItem,
this->closeToolStripMenuItem, this->exitToolStripMenuItem
});
this->fileToolStripMenuItem->Name = L"fileToolStripMenuItem";
this->fileToolStripMenuItem->Size = System::Drawing::Size(37, 20);
this->fileToolStripMenuItem->Text = L"File";
//
// openToolStripMenuItem
//
this->openToolStripMenuItem->Name = L"openToolStripMenuItem";
this->openToolStripMenuItem->Size = System::Drawing::Size(112, 22);
this->openToolStripMenuItem->Text = L"Open...";
this->openToolStripMenuItem->Click += gcnew System::EventHandler(this, &MainForm::openToolStripMenuItem_Click);
//
// closeToolStripMenuItem
//
this->closeToolStripMenuItem->Name = L"closeToolStripMenuItem";
this->closeToolStripMenuItem->Size = System::Drawing::Size(112, 22);
this->closeToolStripMenuItem->Text = L"Close";
this->closeToolStripMenuItem->Click += gcnew System::EventHandler(this, &MainForm::closeToolStripMenuItem_Click);
//
// exitToolStripMenuItem
//
this->exitToolStripMenuItem->Name = L"exitToolStripMenuItem";
this->exitToolStripMenuItem->Size = System::Drawing::Size(112, 22);
this->exitToolStripMenuItem->Text = L"Exit";
this->exitToolStripMenuItem->Click += gcnew System::EventHandler(this, &MainForm::exitToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this->toolsToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) {
this->orientationSortingToolStripMenuItem,
this->sizeFiltrationToolStripMenuItem
});
this->toolsToolStripMenuItem->Name = L"toolsToolStripMenuItem";
this->toolsToolStripMenuItem->Size = System::Drawing::Size(48, 20);
this->toolsToolStripMenuItem->Text = L"Tools";
//
// orientationSortingToolStripMenuItem
//
this->orientationSortingToolStripMenuItem->Name = L"orientationSortingToolStripMenuItem";
this->orientationSortingToolStripMenuItem->Size = System::Drawing::Size(174, 22);
this->orientationSortingToolStripMenuItem->Text = L"Orientation sorting";
this->orientationSortingToolStripMenuItem->Click += gcnew System::EventHandler(this, &MainForm::orientationSortingToolStripMenuItem_Click);
//
// sizeFiltrationToolStripMenuItem
//
this->sizeFiltrationToolStripMenuItem->Name = L"sizeFiltrationToolStripMenuItem";
this->sizeFiltrationToolStripMenuItem->Size = System::Drawing::Size(174, 22);
this->sizeFiltrationToolStripMenuItem->Text = L"Size filtration";
this->sizeFiltrationToolStripMenuItem->Click += gcnew System::EventHandler(this, &MainForm::sizeFiltrationToolStripMenuItem_Click);
//
// statusStrip
//
this->statusStrip->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) {
this->pathToolStripStatusLabel,
this->countToolStripStatusLabel, this->toolStripProgressBar
});
this->statusStrip->Location = System::Drawing::Point(0, 578);
this->statusStrip->Name = L"statusStrip";
this->statusStrip->Size = System::Drawing::Size(800, 22);
this->statusStrip->TabIndex = 1;
this->statusStrip->Text = L"statusStrip1";
//
// pathToolStripStatusLabel
//
this->pathToolStripStatusLabel->Name = L"pathToolStripStatusLabel";
this->pathToolStripStatusLabel->Size = System::Drawing::Size(0, 17);
//
// countToolStripStatusLabel
//
this->countToolStripStatusLabel->Name = L"countToolStripStatusLabel";
this->countToolStripStatusLabel->Size = System::Drawing::Size(0, 17);
//
// toolStripProgressBar
//
this->toolStripProgressBar->Name = L"toolStripProgressBar";
this->toolStripProgressBar->Size = System::Drawing::Size(100, 16);
//
// mainPanel
//
this->mainPanel->Controls->Add(this->pictureBox);
this->mainPanel->Controls->Add(this->buttonsPanel);
this->mainPanel->Dock = System::Windows::Forms::DockStyle::Fill;
this->mainPanel->Location = System::Drawing::Point(0, 24);
this->mainPanel->Name = L"mainPanel";
this->mainPanel->Size = System::Drawing::Size(800, 554);
this->mainPanel->TabIndex = 2;
//
// pictureBox
//
this->pictureBox->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)
| System::Windows::Forms::AnchorStyles::Left)
| System::Windows::Forms::AnchorStyles::Right));
this->pictureBox->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Zoom;
this->pictureBox->Location = System::Drawing::Point(0, 0);
this->pictureBox->Name = L"pictureBox";
this->pictureBox->Size = System::Drawing::Size(800, 522);
this->pictureBox->SizeMode = System::Windows::Forms::PictureBoxSizeMode::Zoom;
this->pictureBox->TabIndex = 1;
this->pictureBox->TabStop = false;
//
// buttonsPanel
//
this->buttonsPanel->Controls->Add(this->buttonNext);
this->buttonsPanel->Controls->Add(this->buttonPrev);
this->buttonsPanel->Dock = System::Windows::Forms::DockStyle::Bottom;
this->buttonsPanel->Location = System::Drawing::Point(0, 522);
this->buttonsPanel->Name = L"buttonsPanel";
this->buttonsPanel->Size = System::Drawing::Size(800, 32);
this->buttonsPanel->TabIndex = 0;
//
// buttonNext
//
this->buttonNext->Anchor = System::Windows::Forms::AnchorStyles::Bottom;
this->buttonNext->Location = System::Drawing::Point(413, 3);
this->buttonNext->Name = L"buttonNext";
this->buttonNext->Size = System::Drawing::Size(75, 23);
this->buttonNext->TabIndex = 1;
this->buttonNext->Text = L"next";
this->buttonNext->UseVisualStyleBackColor = true;
this->buttonNext->Click += gcnew System::EventHandler(this, &MainForm::buttonNext_Click);
//
// buttonPrev
//
this->buttonPrev->Anchor = System::Windows::Forms::AnchorStyles::Bottom;
this->buttonPrev->Location = System::Drawing::Point(332, 3);
this->buttonPrev->Name = L"buttonPrev";
this->buttonPrev->Size = System::Drawing::Size(75, 23);
this->buttonPrev->TabIndex = 0;
this->buttonPrev->Text = L"prev";
this->buttonPrev->UseVisualStyleBackColor = true;
this->buttonPrev->Click += gcnew System::EventHandler(this, &MainForm::buttonPrev_Click);
//
// MainForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(800, 600);
this->Controls->Add(this->mainPanel);
this->Controls->Add(this->statusStrip);
this->Controls->Add(this->menuStrip);
this->MainMenuStrip = this->menuStrip;
this->Name = L"MainForm";
this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"ImageSorter";
this->WindowState = System::Windows::Forms::FormWindowState::Maximized;
this->FormClosed += gcnew System::Windows::Forms::FormClosedEventHandler(this, &MainForm::MainForm_FormClosed);
this->Load += gcnew System::EventHandler(this, &MainForm::MainForm_Load);
this->menuStrip->ResumeLayout(false);
this->menuStrip->PerformLayout();
this->statusStrip->ResumeLayout(false);
this->statusStrip->PerformLayout();
this->mainPanel->ResumeLayout(false);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox))->EndInit();
this->buttonsPanel->ResumeLayout(false);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private:
bool folderChosen;
array<String^>^ formats;
DirectoryInfo^ dirInfo;
List<FileInfo^>^ fileInfos;
int counter;
System::Void MainForm_Load(System::Object^ sender, System::EventArgs^ e) {
folderChosen = false;
counter = -1;
formats = gcnew array<String^> { L"*.jpg", L"*.jpeg", L"*.png" };
toolStripProgressBar->Visible = false;
UpdateMenu();
UpdateContentVisibility();
}
void UpdateContentVisibility() {
if (folderChosen && fileInfos != nullptr && fileInfos->Count > 0)
mainPanel->Visible = true;
else
mainPanel->Visible = false;
}
System::Void exitToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
this->Close();
}
System::Void orientationSortingToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
String^ SUFFIX_PORTRAIT = "_portrait";
String^ SUFFIX_LANDSCAPE = "_landscape";
String^ path = folderBrowserDialog->SelectedPath;
toolStripProgressBar->Visible = true;
try {
String^ currDirName = dirInfo->Name;
if (fileInfos->Count > 0) {
toolStripProgressBar->Maximum = fileInfos->Count;
toolStripProgressBar->Value = 0;
dirInfo->CreateSubdirectory(currDirName + SUFFIX_PORTRAIT);
dirInfo->CreateSubdirectory(currDirName + SUFFIX_LANDSCAPE);
for (int i = 0; i < fileInfos->Count; i++) {
FileInfo^ info = fileInfos[i];
Bitmap^ image = gcnew Bitmap(path + "\\" + info->Name);
if (image->Width > image->Height)
writeToFile(path + "\\" + currDirName + SUFFIX_LANDSCAPE + "\\" + info->Name, image);
if (image->Height > image->Width)
writeToFile(path + "\\" + currDirName + SUFFIX_PORTRAIT + "\\" + info->Name, image);
toolStripProgressBar->Increment(1);
}
MessageBox::Show("Sorting complete", "ImageSorter", MessageBoxButtons::OK, MessageBoxIcon::Asterisk);
Console::WriteLine("Sorting complete. Sorted " + fileInfos->Count + " files");
}
else
MessageBox::Show("There are no files in current directory", "ImageSorter", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
}
catch (ArgumentException^ e) {
MessageBox::Show("Error: Wrong path", "ImageSorter", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
Console::WriteLine("Error while sorting");
}
finally {
toolStripProgressBar->Visible = false;
}
}
System::Void sizeFiltrationToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
String^ SUFFIX = "_filtered";
int MIN_HEIGHT = 610;
String^ path = folderBrowserDialog->SelectedPath;
toolStripProgressBar->Visible = true;
try {
String^ currDirName = dirInfo->Name;
if (fileInfos->Count > 0) {
toolStripProgressBar->Maximum = fileInfos->Count;
toolStripProgressBar->Value = 0;
dirInfo->CreateSubdirectory(currDirName + SUFFIX);
for (int i = 0; i < fileInfos->Count; i++) {
FileInfo^ info = fileInfos[i];
Bitmap^ image = gcnew Bitmap(path + "\\" + info->Name);
if (image->Height >= MIN_HEIGHT)
writeToFile(path + "\\" + currDirName + SUFFIX + "\\" + info->Name, image);
toolStripProgressBar->Increment(1);
}
MessageBox::Show("Sorting complete", "ImageSorter", MessageBoxButtons::OK, MessageBoxIcon::Asterisk);
Console::WriteLine("Sorting complete. Sorted " + fileInfos->Count + " files");
}
else
MessageBox::Show("There are no files in current directory", "ImageSorter", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
}
catch (ArgumentException^ e) {
MessageBox::Show("Error: Wrong path", "ImageSorter", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
Console::WriteLine("Error while sorting");
}
finally {
toolStripProgressBar->Visible = false;
}
}
System::Void openToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
System::Windows::Forms::DialogResult result = folderBrowserDialog->ShowDialog();
if (result == System::Windows::Forms::DialogResult::OK) {
folderChosen = true;
UpdateMenu();
SetContent(folderBrowserDialog->SelectedPath);
UpdateContentVisibility();
}
}
void SetContent(String^ path) {
dirInfo = gcnew DirectoryInfo(this->folderBrowserDialog->SelectedPath);
fileInfos = gcnew List<FileInfo^>();
for (int i = 0; i < formats->Length; i++)
fileInfos->AddRange(dirInfo->GetFiles(formats[i]));
if (fileInfos->Count > 0) {
this->pictureBox->Image = Image::FromFile(fileInfos[0]->FullName);
counter = 0;
}
else {
MessageBox::Show("There are no images in selected folder", "ImageSorter", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
counter = -1;
}
this->pathToolStripStatusLabel->Text = this->folderBrowserDialog->SelectedPath;
this->countToolStripStatusLabel->Text = String::Format("{0}/{1}", counter + 1, fileInfos->Count);
}
void RemoveContent() {
UpdateContentVisibility();
this->pathToolStripStatusLabel->Text = L"";
this->countToolStripStatusLabel->Text = L"";
}
void UpdateMenu() {
this->closeToolStripMenuItem->Enabled = this->folderChosen;
this->orientationSortingToolStripMenuItem->Enabled = this->folderChosen;
this->sizeFiltrationToolStripMenuItem->Enabled = this->folderChosen;
}
System::Void closeToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
folderChosen = false;
counter = -1;
fileInfos->Clear();
this->folderBrowserDialog->Reset();
UpdateMenu();
RemoveContent();
}
System::Void writeToFile(String^ path, Bitmap^ image) {
FileStream^ fstream = gcnew FileStream(path, FileMode::Create, FileAccess::Write);
try {
image->Save(fstream, System::Drawing::Imaging::ImageFormat::Jpeg);
}
catch (Exception^ e) {
Console::WriteLine("Failed to create file with the following error: " + e->Message);
}
finally {
fstream->Close();
}
}
System::Void MainForm_FormClosed(System::Object^ sender, System::Windows::Forms::FormClosedEventArgs^ e) {
formats->Clear;
delete dirInfo;
delete fileInfos;
}
System::Void buttonPrev_Click(System::Object^ sender, System::EventArgs^ e) {
counter--;
if (counter < 0)
counter = fileInfos->Count - 1;
this->pictureBox->Image = Image::FromFile(fileInfos[counter]->FullName);
this->countToolStripStatusLabel->Text = String::Format("{0}/{1}", counter + 1, fileInfos->Count);
}
System::Void buttonNext_Click(System::Object^ sender, System::EventArgs^ e) {
counter++;
if (counter >= fileInfos->Count)
counter = 0;
this->pictureBox->Image = Image::FromFile(fileInfos[counter]->FullName);
this->countToolStripStatusLabel->Text = String::Format("{0}/{1}", counter + 1, fileInfos->Count);
}
};
}
| [
"k_babaec@mail.ru"
] | k_babaec@mail.ru |
0acced2c50d182e7aaaf374e1d1f45dcad9472f4 | 22eccce47517b615b0fa80ee0534cbd9cf78580e | /include/myinterleavers.h | 5b51dd5287e92792688809d4ae8a52313eb3b804 | [] | no_license | lhc180/MyLib | 2cbc1d1fd536fc7ac75c73d913d65b16d206bd59 | 953a593a098b36f783990d3c9511ef5a64f9f2b5 | refs/heads/master | 2021-01-18T10:17:51.458276 | 2015-05-22T02:23:15 | 2015-05-22T02:23:15 | 36,134,919 | 0 | 1 | null | 2015-05-23T17:42:47 | 2015-05-23T17:42:46 | null | UTF-8 | C++ | false | false | 2,913 | h | #ifndef MYINTERLEAVERS_H
#define MYINTERLEAVERS_H
#include <itpp/itbase.h>
namespace mylib {
/************************************************************************************
* RandomInterleaver -- ランダムインタリーバを生成する
*
* Arguments:
* length -- インタリーバ長
*
* Return Value:
* itpp::ivec -- ランダムなインデクスの並び
************************************************************************************/
inline itpp::ivec RandomInterleaver(int length)
{
itpp::ivec interleaver = itpp::sort_index(itpp::randu(length));
return interleaver;
}
static bool S_RandomInterleaver(itpp::ivec* output, int size, int spread, int maxTrial = 500)
{
bool success = false;
itpp::ivec interleaver = RandomInterleaver(size);
for (int reverse = 0; reverse < maxTrial; ++reverse){
std::cout << "reverse = " << reverse << '\r' << std::flush;
int pivot;
for (pivot = 0; pivot < size; ++pivot){
int start_i = pivot - spread;
if (start_i < 0){
start_i = 0;
} // if
int swap_i;
for (swap_i = pivot; swap_i < size; ++swap_i){
int criteria = interleaver[swap_i];
int i;
for (i = start_i; i < pivot; ++i){
if (std::abs(interleaver[i] - criteria) < spread){ // スプレッド値より下回ったら次のswap候補を探す
// ここの判定に=付けるかどうかで若干特性変わる
break;
} // if
} // for i
if (i == pivot){ // もしpivotの値まで比較が成功していたら
std::swap(interleaver[pivot], interleaver[swap_i]);
break;
} // if i
} // for swap_i
if (swap_i == size){ // もしpivot以降にswapできる要素が無ければ
break;
} // if
} // for pivot
if (pivot == size){
success = true;
break;
} // if
else{
interleaver = itpp::reverse(interleaver);
} // else
} // for reverse
std::cout << std::endl; // ##
*output = interleaver;
return success;
}
template < typename kind >
itpp::Vec< kind > Interleave(const itpp::Vec< kind >& input, const itpp::ivec& interleaver)
{
assert(input.size() == interleaver.size());
itpp::Vec< kind > output(input.size());
for (int i = 0; i < input.size(); ++i){
output[i] = input[interleaver[i]];
} // for i
return output;
}
template < typename kind >
itpp::Vec< kind >Deinterleave(const itpp::Vec< kind >& input, const itpp::ivec& interleaver)
{
assert(input.size() == interleaver.size());
itpp::Vec< kind > output(input.size());
for (int i = 0; i < input.size(); ++i){
output[interleaver[i]] = input[i];
} // for i
return output;
}
}
#endif
| [
"sticktrix-yoshito@hotmail.co.jp"
] | sticktrix-yoshito@hotmail.co.jp |
d32779de34d4f1dba9b173f04764f01d95ab2ac6 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14710/function14710_schedule_31/function14710_schedule_31_wrapper.cpp | ab6b3432df07a5bcde35f188d436c168ab29fafb | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,145 | cpp | #include "Halide.h"
#include "function14710_schedule_31_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(64);
Halide::Buffer<int32_t> buf01(64, 64, 64);
Halide::Buffer<int32_t> buf02(64, 128, 64);
Halide::Buffer<int32_t> buf03(128, 64, 64);
Halide::Buffer<int32_t> buf0(64, 128, 64, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14710_schedule_31(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14710/function14710_schedule_31/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
b82c574394cc586397a7b96f5c2e9155035fd30c | 77960f8a9d3ab6e2b67349fa13ab8a2aff11ae8c | /src/matrices.h | bfa9e08547b242e0ad72c64efe1d9923af94c799 | [] | no_license | smalikic/B-SCITE | bb000ea17b7e2da8659dff15eaba8a322aa4ab57 | ac520e140a364ae0c774dd30dee919c6b4a93bd4 | refs/heads/master | 2021-10-21T17:14:05.108854 | 2019-03-05T07:26:38 | 2019-03-05T07:26:38 | 110,091,192 | 10 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,880 | h | /*
* matrices.h
*
* Created on: Mar 27, 2015
* Author: jahnka
*/
#include<string.h>
#ifndef MATRICES_H
#define MATRICES_H
double getMaxEntry(double* array, int n);
double getMaxVectorEntry(std::vector<double> list);
double getSumOfVectorElementsExpLog(std::vector<double> list);
int** sumMatrices(int** first, int** second, int n, int m);
int ** transposeMatrix(int** matrix, int n, int m);
void addToMatrix(int** first, int** second, int n, int m);
double** allocate_doubleMatrix(int n, int m);
int** allocate_intMatrix(int n, int m);
bool** allocate_boolMatrix(int n, int m);
double** init_doubleMatrix(int n, int m, double value);
int* init_intArray(int n, int value);
bool* init_boolArray(int n, bool value);
int** init_intMatrix(int n, int m, int value);
bool** init_boolMatrix(int n, int m, bool value);
double* init_doubleArray(int n, double value);
void reset_intMatrix(int** matrix, int n, int m, int value);
void free_boolMatrix(bool** matrix);
void free_intMatrix(int** matrix);
void free_doubleMatrix(double** matrix);
bool** deepCopy_boolMatrix(bool** matrix, int n, int m);
int** deepCopy_intMatrix(int** matrix, int n, int m);
int* deepCopy_intArray(int* array, int n);
double* deepCopy_doubleArray(double* array, int n);
double** deepCopy_doubleMatrix(double** matrix, int n, int m);
void print_boolMatrix(bool** array, int n, int m);
void print_doubleMatrix(double** matrix, int n, int m);
void print_intMatrix(int** matrix, int n, int m, char del);
void print_intArray(int* array, int n);
int* ancMatrixToParVector(bool** anc, int n);
bool identical_boolMatrices(bool** first, bool** second, int n, int m);
void delete_3D_intMatrix(int*** matrix, int n);
void valuesCopy_boolMatrix(bool** source, bool** destination, int n, int m);
std::string ancMatrixToString(bool** ancMatrix, int n);
std::string parVectorToString(int* parVector, int n);
#endif
| [
"smalikic@tasc9003-18.cmpt.sfu.ca"
] | smalikic@tasc9003-18.cmpt.sfu.ca |
193f6903df407fc90db633d10143cc6aaf3bb89b | e5b8c7136e4f67ef05dd18d019eef23adab07a79 | /cli/guard.h | 603dcb94fd1feccbc7333f6d1a630d939d4ecbcb | [] | no_license | rakhimov/nit | 092e847c63510754ca04fdfc7beba0b92114772a | 2f87132c2fa8cc7c4c62f7b55f5e2e340708bede | refs/heads/master | 2020-03-19T02:36:05.280033 | 2018-06-08T20:41:16 | 2018-06-08T20:41:16 | 135,643,187 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 864 | h | #include <exception>
#include <iostream>
#include <boost/exception/all.hpp>
#include <nit/error.h>
/// Guards a main function from exceptions.
///
/// @tparam T Function type returning integer code.
///
/// @param[in] runner The body of the main function.
///
/// @returns The return of the runner if no exceptions are encountered.
/// 1 if an exception is encountered.
template <class T>
int guard(T&& runner) noexcept {
try {
return runner();
} catch (const nit::Error& nit_err) {
std::cerr << boost::diagnostic_information(nit_err);
return 1;
} catch (const boost::exception& boost_err) {
std::cerr << "Unexpected Boost Exception:\n"
<< boost::diagnostic_information(boost_err);
return 1;
} catch (const std::exception& err) {
std::cerr << "Unexpected Exception:\n" << err.what();
return 1;
}
}
| [
"ol.rakhimov@gmail.com"
] | ol.rakhimov@gmail.com |
78e74d45082ce9d926b91c584d220a6defa366c7 | 805f994323b82aaa3d068289b1d3a25e0b4198f0 | /basketball_leadue/Team.h | 06c205588ec879fc50484aafcce084c05b28a0cb | [] | no_license | avishayhajbi/basketball_league | 917144248484517ff7c1fb23e16e7f0b30ba0900 | 4a7c550f8e86d4ce7c36e6fe0cf08a03f5a4c7b2 | refs/heads/master | 2021-03-13T00:02:06.106649 | 2014-01-18T18:41:53 | 2014-01-18T18:41:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | h | #ifndef TEAM_H
#define TEAM_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <assert.h>
using namespace std;
class Team
{
private:
int _gameCounter;
int _leaguePoints;
int _success;
int _fail;
string _teameName;
public:
Team();
Team(string name);
Team(int gameCounter, int leagePoint, int success, int fail, string teamName);
int get_gameConter();
void increment_gameCounter(int num);
int get_leaguePoints();
void increment_leaguePoints(int num);
int get_success();
void set_success(int num);
int get_fail();
void set_fail(int num);
string get_teamName();
void set_teamName(string replace);
};
#endif
| [
"avishayhajbi@gmail.com"
] | avishayhajbi@gmail.com |
92ef5120d24f8459e4f4aa85a72a9cd69742bf2e | ca5f8b6a3684d3b8358acad701191222810cfcd3 | /src/rtda/mm/space.hpp | 553a62ebb2af1b8ed8df511ed26b64750d3a9dc2 | [] | no_license | mikeXwang/JVM | 10830a1cfa22bf4a80931ca420aa3432bf711e1b | d72dbf14f5022c498b5e557df94323e6518e3660 | refs/heads/master | 2021-05-05T20:44:44.556992 | 2017-07-25T03:14:53 | 2017-07-25T03:14:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | hpp | #ifndef __SPACE_HPP_
#define __SPACE_HPP_
class Space {
char* bottom_;
char* top_;
char* end_;
public:
Space(char* bottom, char* end);
char* bottom() { return bottom_; }
char* top() { return top_; }
char* end() { return end_; }
bool contains(char* obj);
char* allocate(size_t size);
void reset();
};
#endif | [
"wyxswjtu@163.com"
] | wyxswjtu@163.com |
e826ae9c2791e824c49b2739c8fd4d427aefb9bf | 446d3cb7e8c8edf2ae0e8b291d2bb09a97362658 | /dtccCommon/src/application/compression/zip/centralDirectoryFileHeader.cpp | 943eade3521279294d20222c77a9ea67d7ec09d1 | [] | no_license | fagan2888/dtccClient | 9768e0877daf7b2d38b9fe4a17845aa1eee92f66 | 8f31829440aefc7b78bc492495d604f36043d8a3 | refs/heads/master | 2021-06-18T17:29:04.646968 | 2017-06-17T00:42:00 | 2017-06-17T00:42:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,172 | cpp | #include "centralDirectoryFileHeader.hpp"
namespace dtcc
{
namespace zip
{
centralDirectoryFileHeader::centralDirectoryFileHeader(std::string::const_iterator it)
{
version v; uint8_t n;
int16_t fileNameLen, extraFieldLen, commentLen;
memcpy(&v, &*it, sizeof(char) * 1);
std::advance(it, 1); memcpy(&n, &*it, sizeof(char) * 1);
version_ = std::make_tuple(v, n);
std::advance(it, 1); memcpy(&minimal_, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&flag_, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&compression_, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&modTime_, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&modDate_, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&crc32_, &*it, sizeof(char) * 4);
std::advance(it, 4); memcpy(&compressSize_, &*it, sizeof(char) * 4);
std::advance(it, 4); memcpy(&uncompressSize_, &*it, sizeof(char) * 4);
std::advance(it, 4); memcpy(&fileNameLen, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&extraFieldLen, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&commentLen, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&diskStartNum_, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&internalAttribute_, &*it, sizeof(char) * 2);
std::advance(it, 2); memcpy(&externalAttribute_, &*it, sizeof(char) * 4);
std::advance(it, 4); memcpy(&offsetLocalHeader_, &*it, sizeof(char) * 4);
std::advance(it, 4);
// copy the variable size fields
name_.resize(fileNameLen);
std::copy(it, it + fileNameLen, name_.begin());
std::advance(it, fileNameLen);
extraField_.resize(extraFieldLen);
std::copy(it, it + extraFieldLen, extraField_.begin());
std::advance(it, extraFieldLen);
fileComment_.resize(commentLen);
std::copy(it, it + commentLen, fileComment_.begin());
std::advance(it, commentLen);
}
uint32_t centralDirectoryFileHeader::offsetLocalHeader() const { return offsetLocalHeader_ ; }
const std::string & centralDirectoryFileHeader::name () const { return name_ ; }
uint32_t centralDirectoryFileHeader::compressSize () const { return compressSize_ ; }
}
} | [
"vermosen.jm@free.fr"
] | vermosen.jm@free.fr |
37b1e7c04a1827ff3cdcd8647242378dd969f88d | 2a8a07443991f75c85148c848774c8b76de18448 | /isv_enclave/isv_enclave.cpp | fab7ea65cc43985a1c9a5e7bf6d997a530b8c8b3 | [] | no_license | harnen/airtnt | 7046ccc55ef8ba0dc4faea61741856e5f9466bbb | 67e0aa9e0a282d9c2c0d87c47db9c287ff4a42a3 | refs/heads/master | 2021-03-30T21:07:44.379892 | 2018-08-23T17:23:35 | 2018-08-23T17:23:35 | 124,552,178 | 2 | 4 | null | 2018-04-25T15:27:06 | 2018-03-09T14:39:33 | C++ | UTF-8 | C++ | false | false | 14,653 | cpp | /*
* Copyright (C) 2011-2018 Intel Corporation. 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 Intel Corporation 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.
*
*/
#include <assert.h>
#include "isv_enclave_t.h"
#include "sgx_tkey_exchange.h"
#include "sgx_tcrypto.h"
#include "string.h"
#include "life.h"
// This is the public EC key of the SP. The corresponding private EC key is
// used by the SP to sign data used in the remote attestation SIGMA protocol
// to sign channel binding data in MSG2. A successful verification of the
// signature confirms the identity of the SP to the ISV app in remote
// attestation secure channel binding. The public EC key should be hardcoded in
// the enclave or delivered in a trustworthy manner. The use of a spoofed public
// EC key in the remote attestation with secure channel binding session may lead
// to a security compromise. Every different SP the enlcave communicates to
// must have a unique SP public key. Delivery of the SP public key is
// determined by the ISV. The TKE SIGMA protocl expects an Elliptical Curve key
// based on NIST P-256
static const sgx_ec256_public_t g_sp_pub_key = {
{
0x72, 0x12, 0x8a, 0x7a, 0x17, 0x52, 0x6e, 0xbf,
0x85, 0xd0, 0x3a, 0x62, 0x37, 0x30, 0xae, 0xad,
0x3e, 0x3d, 0xaa, 0xee, 0x9c, 0x60, 0x73, 0x1d,
0xb0, 0x5b, 0xe8, 0x62, 0x1c, 0x4b, 0xeb, 0x38
},
{
0xd4, 0x81, 0x40, 0xd9, 0x50, 0xe2, 0x57, 0x7b,
0x26, 0xee, 0xb7, 0x41, 0xe7, 0xc6, 0x14, 0xe2,
0x24, 0xb7, 0xbd, 0xc9, 0x03, 0xf2, 0x9a, 0x28,
0xa8, 0x3c, 0xc8, 0x10, 0x11, 0x14, 0x5e, 0x06
}
};
// Used to store the secret passed by the SP in the sample code. The
// size is forced to be 8 bytes. Expected value is
// 0x01,0x02,0x03,0x04,0x0x5,0x0x6,0x0x7
//uint8_t g_secret[18] = {0};
#ifdef SUPPLIED_KEY_DERIVATION
#pragma message ("Supplied key derivation function is used.")
typedef struct _hash_buffer_t
{
uint8_t counter[4];
sgx_ec256_dh_shared_t shared_secret;
uint8_t algorithm_id[4];
} hash_buffer_t;
const char ID_U[] = "SGXRAENCLAVE";
const char ID_V[] = "SGXRASERVER";
// Derive two keys from shared key and key id.
bool derive_key(
const sgx_ec256_dh_shared_t *p_shared_key,
uint8_t key_id,
sgx_ec_key_128bit_t *first_derived_key,
sgx_ec_key_128bit_t *second_derived_key)
{
sgx_status_t sgx_ret = SGX_SUCCESS;
hash_buffer_t hash_buffer;
sgx_sha_state_handle_t sha_context;
sgx_sha256_hash_t key_material;
memset(&hash_buffer, 0, sizeof(hash_buffer_t));
/* counter in big endian */
hash_buffer.counter[3] = key_id;
/*convert from little endian to big endian */
for (size_t i = 0; i < sizeof(sgx_ec256_dh_shared_t); i++)
{
hash_buffer.shared_secret.s[i] = p_shared_key->s[sizeof(p_shared_key->s)-1 - i];
}
sgx_ret = sgx_sha256_init(&sha_context);
if (sgx_ret != SGX_SUCCESS)
{
return false;
}
sgx_ret = sgx_sha256_update((uint8_t*)&hash_buffer, sizeof(hash_buffer_t), sha_context);
if (sgx_ret != SGX_SUCCESS)
{
sgx_sha256_close(sha_context);
return false;
}
sgx_ret = sgx_sha256_update((uint8_t*)&ID_U, sizeof(ID_U), sha_context);
if (sgx_ret != SGX_SUCCESS)
{
sgx_sha256_close(sha_context);
return false;
}
sgx_ret = sgx_sha256_update((uint8_t*)&ID_V, sizeof(ID_V), sha_context);
if (sgx_ret != SGX_SUCCESS)
{
sgx_sha256_close(sha_context);
return false;
}
sgx_ret = sgx_sha256_get_hash(sha_context, &key_material);
if (sgx_ret != SGX_SUCCESS)
{
sgx_sha256_close(sha_context);
return false;
}
sgx_ret = sgx_sha256_close(sha_context);
assert(sizeof(sgx_ec_key_128bit_t)* 2 == sizeof(sgx_sha256_hash_t));
memcpy(first_derived_key, &key_material, sizeof(sgx_ec_key_128bit_t));
memcpy(second_derived_key, (uint8_t*)&key_material + sizeof(sgx_ec_key_128bit_t), sizeof(sgx_ec_key_128bit_t));
// memset here can be optimized away by compiler, so please use memset_s on
// windows for production code and similar functions on other OSes.
memset(&key_material, 0, sizeof(sgx_sha256_hash_t));
return true;
}
//isv defined key derivation function id
#define ISV_KDF_ID 2
typedef enum _derive_key_type_t
{
DERIVE_KEY_SMK_SK = 0,
DERIVE_KEY_MK_VK,
} derive_key_type_t;
sgx_status_t key_derivation(const sgx_ec256_dh_shared_t* shared_key,
uint16_t kdf_id,
sgx_ec_key_128bit_t* smk_key,
sgx_ec_key_128bit_t* sk_key,
sgx_ec_key_128bit_t* mk_key,
sgx_ec_key_128bit_t* vk_key)
{
bool derive_ret = false;
if (NULL == shared_key)
{
return SGX_ERROR_INVALID_PARAMETER;
}
if (ISV_KDF_ID != kdf_id)
{
//fprintf(stderr, "\nError, key derivation id mismatch in [%s].", __FUNCTION__);
return SGX_ERROR_KDF_MISMATCH;
}
derive_ret = derive_key(shared_key, DERIVE_KEY_SMK_SK,
smk_key, sk_key);
if (derive_ret != true)
{
//fprintf(stderr, "\nError, derive key fail in [%s].", __FUNCTION__);
return SGX_ERROR_UNEXPECTED;
}
derive_ret = derive_key(shared_key, DERIVE_KEY_MK_VK,
mk_key, vk_key);
if (derive_ret != true)
{
//fprintf(stderr, "\nError, derive key fail in [%s].", __FUNCTION__);
return SGX_ERROR_UNEXPECTED;
}
return SGX_SUCCESS;
}
#else
#pragma message ("Default key derivation function is used.")
#endif
// This ecall is a wrapper of sgx_ra_init to create the trusted
// KE exchange key context needed for the remote attestation
// SIGMA API's. Input pointers aren't checked since the trusted stubs
// copy them into EPC memory.
//
// @param b_pse Indicates whether the ISV app is using the
// platform services.
// @param p_context Pointer to the location where the returned
// key context is to be copied.
//
// @return Any error return from the create PSE session if b_pse
// is true.
// @return Any error returned from the trusted key exchange API
// for creating a key context.
sgx_status_t enclave_init_ra(
int b_pse,
sgx_ra_context_t *p_context)
{
// isv enclave call to trusted key exchange library.
sgx_status_t ret;
if(b_pse)
{
int busy_retry_times = 2;
do{
ret = sgx_create_pse_session();
}while (ret == SGX_ERROR_BUSY && busy_retry_times--);
if (ret != SGX_SUCCESS)
return ret;
}
#ifdef SUPPLIED_KEY_DERIVATION
ret = sgx_ra_init_ex(&g_sp_pub_key, b_pse, key_derivation, p_context);
#else
ret = sgx_ra_init(&g_sp_pub_key, b_pse, p_context);
#endif
if(b_pse)
{
sgx_close_pse_session();
return ret;
}
return ret;
}
// Closes the tKE key context used during the SIGMA key
// exchange.
//
// @param context The trusted KE library key context.
//
// @return Return value from the key context close API
sgx_status_t SGXAPI enclave_ra_close(
sgx_ra_context_t context)
{
sgx_status_t ret;
ret = sgx_ra_close(context);
return ret;
}
// Verify the mac sent in att_result_msg from the SP using the
// MK key. Input pointers aren't checked since the trusted stubs
// copy them into EPC memory.
//
//
// @param context The trusted KE library key context.
// @param p_message Pointer to the message used to produce MAC
// @param message_size Size in bytes of the message.
// @param p_mac Pointer to the MAC to compare to.
// @param mac_size Size in bytes of the MAC
//
// @return SGX_ERROR_INVALID_PARAMETER - MAC size is incorrect.
// @return Any error produced by tKE API to get SK key.
// @return Any error produced by the AESCMAC function.
// @return SGX_ERROR_MAC_MISMATCH - MAC compare fails.
sgx_status_t verify_att_result_mac(sgx_ra_context_t context,
uint8_t* p_message,
size_t message_size,
uint8_t* p_mac,
size_t mac_size)
{
sgx_status_t ret;
sgx_ec_key_128bit_t mk_key;
if(mac_size != sizeof(sgx_mac_t))
{
ret = SGX_ERROR_INVALID_PARAMETER;
return ret;
}
if(message_size > UINT32_MAX)
{
ret = SGX_ERROR_INVALID_PARAMETER;
return ret;
}
do {
uint8_t mac[SGX_CMAC_MAC_SIZE] = {0};
ret = sgx_ra_get_keys(context, SGX_RA_KEY_MK, &mk_key);
if(SGX_SUCCESS != ret)
{
break;
}
ret = sgx_rijndael128_cmac_msg(&mk_key,
p_message,
(uint32_t)message_size,
&mac);
if(SGX_SUCCESS != ret)
{
break;
}
if(0 == consttime_memequal(p_mac, mac, sizeof(mac)))
{
ret = SGX_ERROR_MAC_MISMATCH;
break;
}
}
while(0);
return ret;
}
// Generate a secret information for the SP encrypted with SK.
// Input pointers aren't checked since the trusted stubs copy
// them into EPC memory.
//
// @param context The trusted KE library key context.
// @param p_secret Message containing the secret.
// @param secret_size Size in bytes of the secret message.
// @param p_gcm_mac The pointer the the AESGCM MAC for the
// message.
//
// @return SGX_ERROR_INVALID_PARAMETER - secret size if
// incorrect.
// @return Any error produced by tKE API to get SK key.
// @return Any error produced by the AESGCM function.
// @return SGX_ERROR_UNEXPECTED - the secret doesn't match the
// expected value.
void simulate(int size, int steps, char* array){
char *fa, *fb, *tt, *tmp;
int i;
tmp=(char*) malloc(size * size * sizeof(char));
fa=array;
fb=tmp;
for(i = 0; i < steps; i++){
evolve(fa, fb, size);
tt = fb; fb = fa; fa = tt;
}
free(tmp);
}
sgx_status_t put_secret_data(
sgx_ra_context_t context,
uint8_t *p_secret,
uint32_t secret_size,
uint8_t *p_gcm_mac,
uint8_t* result,
int* result_size,
sgx_aes_gcm_128bit_key_t* result_key,
sgx_aes_gcm_128bit_tag_t* out_mac)
{
sgx_status_t ret = SGX_SUCCESS;
sgx_ec_key_128bit_t sk_key;
do {
/*
* Decrypt the input
*/
//allocate space for the decrypted input
uint8_t* g_secret = (uint8_t*) malloc(secret_size);
ret = sgx_ra_get_keys(context, SGX_RA_KEY_SK, &sk_key);
if(SGX_SUCCESS != ret)
{
break;
}
uint8_t aes_gcm_iv[12] = {0};
ret = sgx_rijndael128GCM_decrypt(&sk_key,
p_secret,
secret_size,
&g_secret[0],
&aes_gcm_iv[0],
12,
NULL,
0,
(const sgx_aes_gcm_128bit_tag_t *)
(p_gcm_mac));
/*
* Perform the requested computations
*/
life_input_t* input = (life_input_t*) g_secret;
int size = input->size;
int steps = input->steps;
simulate(input->size, input->steps, input->array);
/*
* Encrypt the computed results
*/
*result_size = sizeof(sgx_aes_gcm_128bit_key_t);
//generate a random encryption key
sgx_read_rand((unsigned char*) result_key, sizeof(*result_key));
//initialization vector - we keep it everywhere the same for now
uint8_t result_iv[12] = {0};
uint8_t buf[secret_size];
for(int i = 0; i < SGX_AESGCM_KEY_SIZE; i++){
(*result_key)[i] = i;
}
//encrypt with a random key
sgx_rijndael128GCM_encrypt(result_key,
(uint8_t*) input, //
secret_size, //output is the same size as the input
buf,
&result_iv[0],
12, //recommended value
NULL,
0,
out_mac);
sgx_aes_gcm_128bit_key_t shared_key;
for(int i = 0; i < SGX_AESGCM_KEY_SIZE; i++){
shared_key[i] = 10;
}
//encrypt with the original key derived from remote attestation
sgx_rijndael128GCM_encrypt(&sk_key, //&shared_key,
buf, //(const uint8_t*) input,
secret_size, //output is the same size as the input
result,
&result_iv[0],
12, //recommended value
NULL,
0,
out_mac);
} while(0);
return ret;
}
| [
"mharnen@gmail.com"
] | mharnen@gmail.com |
dc25098a109a1d13671a606842df3bec54ce59ed | 97529d623e1df1c716e1570b98d0f090e736c238 | /primer/chapter_2/constexpr.cpp | bd8daa3028d48b1c0dadeec1ed2163723f6090a3 | [] | no_license | leilei-help/code | 2f83e9a01b3ccb84625b1c8b3e43a07939785dd1 | 3244703afb4eb99ef6e2d77edbd346b3405f64f7 | refs/heads/master | 2022-01-27T00:47:16.339792 | 2018-04-20T12:25:06 | 2018-04-20T12:25:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cpp | #include <iostream>
using namespace std;
// 声明一些可以在编译时期获得的值
// A constexpr specifier used in a function or static member variable
// (since C++17) declaration implies inline.
int main(int argc, char **argv)
{
// A constexpr specifier used in an object declaration implies const
constexpr int a = 1;
cout << a << endl;
// a = 2; //error ,const变量不能被赋值
cout << a << endl;
} | [
"1208266117@qq.com"
] | 1208266117@qq.com |
1a85368aa0a6974cab9c0ed0d71fc5cc57a698bd | 5bef53b0dc9539a4953919f75fde1f0ebd20e9fb | /CF/CONTEST_423D2/A.cpp | 0acc8f4b2c74a1c9d4534dbcb3da6886cea9851d | [] | no_license | atrin-hojjat/CompetetiveProgramingCodes | 54c8b94092f7acf40d379e42e1f2c0fe8dab9b32 | 6a02071c3869b8e7cd873ddf7a3a2d678aec6d91 | refs/heads/master | 2020-11-25T10:51:23.200000 | 2020-10-08T11:12:09 | 2020-10-08T11:12:09 | 228,626,397 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 648 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <math.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int n,a,b,ans = 0,x;
cin >> n >> a >> b;
while(n--){
cin >> x;
if(x==1){
if(a>0)a--;
else if(b>0) b--,a++;
else ans++;
} else {
if(b>0) b--;
else ans+=2;
}
}
cout << ans << endl;
return 0;
}
| [
"magic.h.s.atrin@gmail.com"
] | magic.h.s.atrin@gmail.com |
ab5043a3fd63de2dc55e0e22871bf21b1744b55c | 6464f84880140bbb45ddcd7c21c44e12ec0a29fc | /src/zmq/zmqabstractnotifier.h | 695afe324cd1ad5435597fc3301167d365e0ab1a | [
"MIT"
] | permissive | KazuPay/kazubyte | b783672f1152b2c1f88bdba8f76d997094d2ac8f | ce36b1ef899fe538f0417a263af4f0e3dbfd7233 | refs/heads/master | 2020-04-24T08:02:18.697520 | 2019-02-23T06:50:50 | 2019-02-23T06:50:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | h | // Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef KBYTECOIN_ZMQ_ZMQABSTRACTNOTIFIER_H
#define KBYTECOIN_ZMQ_ZMQABSTRACTNOTIFIER_H
#include "zmqconfig.h"
class CBlockIndex;
class CZMQAbstractNotifier;
typedef CZMQAbstractNotifier* (*CZMQNotifierFactory)();
class CZMQAbstractNotifier
{
public:
CZMQAbstractNotifier() : psocket(0) { }
virtual ~CZMQAbstractNotifier();
template <typename T>
static CZMQAbstractNotifier* Create()
{
return new T();
}
std::string GetType() const { return type; }
void SetType(const std::string &t) { type = t; }
std::string GetAddress() const { return address; }
void SetAddress(const std::string &a) { address = a; }
virtual bool Initialize(void *pcontext) = 0;
virtual void Shutdown() = 0;
virtual bool NotifyBlock(const CBlockIndex *pindex);
virtual bool NotifyTransaction(const CTransaction &transaction);
protected:
void *psocket;
std::string type;
std::string address;
};
#endif // KBYTECOIN_ZMQ_ZMQABSTRACTNOTIFIER_H
| [
"root@www.kazuexplore.com"
] | root@www.kazuexplore.com |
15df3525c3935b49427de0c0035a57d566e2c682 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_patch_hunk_1160.cpp | a76e0ecee1d1efe0bbede01b7c596753dfd1ce5b | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | cpp | void SHA1DCUpdate(SHA1_CTX*, const char*, size_t);
/* obtain SHA-1 hash from SHA-1 context */
/* returns: 0 = no collision detected, otherwise = collision found => warn user for active attack */
int SHA1DCFinal(unsigned char[20], SHA1_CTX*);
-/*
- * Same as SHA1DCFinal, but convert collision attack case into a verbose die().
- */
-void git_SHA1DCFinal(unsigned char [20], SHA1_CTX *);
-
-/*
- * Same as SHA1DCUpdate, but adjust types to match git's usual interface.
- */
-void git_SHA1DCUpdate(SHA1_CTX *ctx, const void *data, unsigned long len);
-
-#define platform_SHA_CTX SHA1_CTX
-#define platform_SHA1_Init SHA1DCInit
-#define platform_SHA1_Update git_SHA1DCUpdate
-#define platform_SHA1_Final git_SHA1DCFinal
-
#if defined(__cplusplus)
}
#endif
-#endif /* SHA1DC_SHA1_H */
+#ifdef SHA1DC_CUSTOM_TRAILING_INCLUDE_SHA1_H
+#include SHA1DC_CUSTOM_TRAILING_INCLUDE_SHA1_H
+#endif
+
+#endif
| [
"993273596@qq.com"
] | 993273596@qq.com |
61b256eb959a7a22f37a3e550ada83ebac124052 | 38c10c01007624cd2056884f25e0d6ab85442194 | /chrome/browser/ui/ash/launcher/browser_status_monitor.h | 1f6348813570df84ddd2d2834bc5d64eccb8737b | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 6,153 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_ASH_LAUNCHER_BROWSER_STATUS_MONITOR_H_
#define CHROME_BROWSER_UI_ASH_LAUNCHER_BROWSER_STATUS_MONITOR_H_
#include <map>
#include <string>
#include "ash/shelf/scoped_observer_with_duplicated_sources.h"
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/scoped_observer.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/browser_tab_strip_tracker.h"
#include "chrome/browser/ui/browser_tab_strip_tracker_delegate.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
#include "ui/aura/window_observer.h"
#include "ui/gfx/display_observer.h"
#include "ui/wm/public/activation_change_observer.h"
namespace aura {
class Window;
namespace client {
class ActivationClient;
}
} // namespace aura
class Browser;
// BrowserStatusMonitor monitors creation/deletion of Browser and its
// TabStripModel to keep the launcher representation up to date as the
// active tab changes.
class BrowserStatusMonitor : public aura::client::ActivationChangeObserver,
public aura::WindowObserver,
public BrowserTabStripTrackerDelegate,
public chrome::BrowserListObserver,
public gfx::DisplayObserver,
public TabStripModelObserver {
public:
explicit BrowserStatusMonitor(ChromeLauncherController* launcher_controller);
~BrowserStatusMonitor() override;
// A function which gets called when the current user has changed.
// Note that this function is called by the ChromeLauncherController to be
// able to do the activation in a proper order - rather then setting an
// observer.
virtual void ActiveUserChanged(const std::string& user_email) {}
// A shortcut to call the ChromeLauncherController's UpdateAppState().
void UpdateAppItemState(content::WebContents* contents,
ChromeLauncherController::AppState app_state);
// A shortcut to call the BrowserShortcutLauncherItemController's
// UpdateBrowserItemState().
void UpdateBrowserItemState();
// aura::client::ActivationChangeObserver overrides:
void OnWindowActivated(
aura::client::ActivationChangeObserver::ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) override;
// aura::WindowObserver overrides:
void OnWindowDestroyed(aura::Window* window) override;
// BrowserTabStripTrackerDelegate overrides:
bool ShouldTrackBrowser(Browser* browser) override;
// chrome::BrowserListObserver overrides:
void OnBrowserAdded(Browser* browser) override;
void OnBrowserRemoved(Browser* browser) override;
// gfx::DisplayObserver overrides:
void OnDisplayAdded(const gfx::Display& new_display) override;
void OnDisplayRemoved(const gfx::Display& old_display) override;
void OnDisplayMetricsChanged(const gfx::Display& display,
uint32_t metrics) override;
// TabStripModelObserver overrides:
void ActiveTabChanged(content::WebContents* old_contents,
content::WebContents* new_contents,
int index,
int reason) override;
void TabReplacedAt(TabStripModel* tab_strip_model,
content::WebContents* old_contents,
content::WebContents* new_contents,
int index) override;
void TabInsertedAt(content::WebContents* contents,
int index,
bool foreground) override;
void TabClosingAt(TabStripModel* tab_strip_mode,
content::WebContents* contents,
int index) override;
// Called from our own |LocalWebContentsObserver| when web contents did go
// away without any other notification. This might happen in case of
// application uninstalls, page crashes, ...).
void WebContentsDestroyed(content::WebContents* web_contents);
protected:
// Add a V1 application to the shelf. This can get overwritten for multi
// profile implementations.
virtual void AddV1AppToShelf(Browser* browser);
// Remove a V1 application from the shelf. This can get overwritten for multi
// profile implementations.
virtual void RemoveV1AppFromShelf(Browser* browser);
// Check if V1 application is currently in the shelf.
bool IsV1AppInShelf(Browser* browser);
private:
class LocalWebContentsObserver;
class SettingsWindowObserver;
typedef std::map<Browser*, std::string> BrowserToAppIDMap;
typedef std::map<content::WebContents*, LocalWebContentsObserver*>
WebContentsToObserverMap;
// Create LocalWebContentsObserver for |contents|.
void AddWebContentsObserver(content::WebContents* contents);
// Remove LocalWebContentsObserver for |contents|.
void RemoveWebContentsObserver(content::WebContents* contents);
// Returns the ShelfID for |contents|.
ash::ShelfID GetShelfIDForWebContents(content::WebContents* contents);
// Sets the shelf id for browsers represented by the browser shortcut item.
void SetShelfIDForBrowserWindowContents(Browser* browser,
content::WebContents* web_contents);
ChromeLauncherController* launcher_controller_;
// Hold all observed activation clients.
ScopedObserverWithDuplicatedSources<aura::client::ActivationClient,
aura::client::ActivationChangeObserver> observed_activation_clients_;
// Hold all observed root windows.
ScopedObserver<aura::Window, aura::WindowObserver> observed_root_windows_;
BrowserToAppIDMap browser_to_app_id_map_;
WebContentsToObserverMap webcontents_to_observer_map_;
scoped_ptr<SettingsWindowObserver> settings_window_observer_;
BrowserTabStripTracker browser_tab_strip_tracker_;
DISALLOW_COPY_AND_ASSIGN(BrowserStatusMonitor);
};
#endif // CHROME_BROWSER_UI_ASH_LAUNCHER_BROWSER_STATUS_MONITOR_H_
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
f14b68907f40a88d4cf4c59dcd3f3cc6aced42c1 | 22204cffab84e7e6907f013a2d45b116ccb0c66d | /src/netbase.cpp | 243524b5790f68c00cce8e5778021f49c51c9ce2 | [
"MIT"
] | permissive | LordSoylent/PrimeStone-2 | bf24751d40d02e14b778e6e29eb2d9a3f9f1ca3f | 6ae3719a45a3ff105a1fe7ca0eb74a979be44def | refs/heads/master | 2020-04-18T21:34:06.721912 | 2019-01-26T19:14:49 | 2019-01-26T19:14:49 | 167,768,307 | 1 | 0 | MIT | 2019-01-27T04:15:02 | 2019-01-27T04:15:02 | null | UTF-8 | C++ | false | false | 43,547 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018-2019 The PrimeStone developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifdef HAVE_CONFIG_H
#include "config/primestone-config.h"
#endif
#include "netbase.h"
#include "hash.h"
#include "sync.h"
#include "uint256.h"
#include "random.h"
#include "util.h"
#include "utilstrencodings.h"
#ifdef HAVE_GETADDRINFO_A
#include <netdb.h>
#endif
#ifndef WIN32
#if HAVE_INET_PTON
#include <arpa/inet.h>
#endif
#include <fcntl.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/thread.hpp>
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
using namespace std;
// Settings
static proxyType proxyInfo[NET_MAX];
static proxyType nameProxy;
static CCriticalSection cs_proxyInfos;
int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
bool fNameLookup = false;
static const unsigned char pchIPv4[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
// Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
enum Network ParseNetwork(std::string net)
{
boost::to_lower(net);
if (net == "ipv4") return NET_IPV4;
if (net == "ipv6") return NET_IPV6;
if (net == "tor" || net == "onion") return NET_TOR;
return NET_UNROUTABLE;
}
std::string GetNetworkName(enum Network net)
{
switch (net) {
case NET_IPV4:
return "ipv4";
case NET_IPV6:
return "ipv6";
case NET_TOR:
return "onion";
default:
return "";
}
}
void SplitHostPort(std::string in, int& portOut, std::string& hostOut)
{
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
bool fBracketed = fHaveColon && (in[0] == '[' && in[colon - 1] == ']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':', colon - 1) != in.npos);
if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) {
int32_t n;
if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
in = in.substr(0, colon);
portOut = n;
}
}
if (in.size() > 0 && in[0] == '[' && in[in.size() - 1] == ']')
hostOut = in.substr(1, in.size() - 2);
else
hostOut = in;
}
bool static LookupIntern(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
vIP.clear();
{
CNetAddr addr;
if (addr.SetSpecial(std::string(pszName))) {
vIP.push_back(addr);
return true;
}
}
#ifdef HAVE_GETADDRINFO_A
struct in_addr ipv4_addr;
#ifdef HAVE_INET_PTON
if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
vIP.push_back(CNetAddr(ipv4_addr));
return true;
}
struct in6_addr ipv6_addr;
if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
vIP.push_back(CNetAddr(ipv6_addr));
return true;
}
#else
ipv4_addr.s_addr = inet_addr(pszName);
if (ipv4_addr.s_addr != INADDR_NONE) {
vIP.push_back(CNetAddr(ipv4_addr));
return true;
}
#endif
#endif
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
aiHint.ai_family = AF_UNSPEC;
#ifdef WIN32
aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
#else
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif
struct addrinfo* aiRes = NULL;
#ifdef HAVE_GETADDRINFO_A
struct gaicb gcb, *query = &gcb;
memset(query, 0, sizeof(struct gaicb));
gcb.ar_name = pszName;
gcb.ar_request = &aiHint;
int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
if (nErr)
return false;
do {
// Should set the timeout limit to a resonable value to avoid
// generating unnecessary checking call during the polling loop,
// while it can still response to stop request quick enough.
// 2 seconds looks fine in our situation.
struct timespec ts = {2, 0};
gai_suspend(&query, 1, &ts);
boost::this_thread::interruption_point();
nErr = gai_error(query);
if (0 == nErr)
aiRes = query->ar_result;
} while (nErr == EAI_INPROGRESS);
#else
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
#endif
if (nErr)
return false;
struct addrinfo* aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) {
if (aiTrav->ai_family == AF_INET) {
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
}
if (aiTrav->ai_family == AF_INET6) {
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
}
aiTrav = aiTrav->ai_next;
}
freeaddrinfo(aiRes);
return (vIP.size() > 0);
}
bool LookupHost(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
std::string strHost(pszName);
if (strHost.empty())
return false;
if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]")) {
strHost = strHost.substr(1, strHost.size() - 2);
}
return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
}
bool Lookup(const char* pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
return false;
int port = portDefault;
std::string hostname = "";
SplitHostPort(std::string(pszName), port, hostname);
std::vector<CNetAddr> vIP;
bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
if (!fRet)
return false;
vAddr.resize(vIP.size());
for (unsigned int i = 0; i < vIP.size(); i++)
vAddr[i] = CService(vIP[i], port);
return true;
}
bool Lookup(const char* pszName, CService& addr, int portDefault, bool fAllowLookup)
{
std::vector<CService> vService;
bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
if (!fRet)
return false;
addr = vService[0];
return true;
}
bool LookupNumeric(const char* pszName, CService& addr, int portDefault)
{
return Lookup(pszName, addr, portDefault, false);
}
struct timeval MillisToTimeval(int64_t nTimeout)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
return timeout;
}
/**
* Read bytes from socket. This will either read the full number of bytes requested
* or return False on error or timeout.
* This function can be interrupted by boost thread interrupt.
*
* @param data Buffer to receive into
* @param len Length of data to receive
* @param timeout Timeout in milliseconds for receive operation
*
* @note This function requires that hSocket is in non-blocking mode.
*/
bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
{
int64_t curTime = GetTimeMillis();
int64_t endTime = curTime + timeout;
// Maximum time to wait in one select call. It will take up until this time (in millis)
// to break off in case of an interruption.
const int64_t maxWait = 1000;
while (len > 0 && curTime < endTime) {
ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
if (ret > 0) {
len -= ret;
data += ret;
} else if (ret == 0) { // Unexpected disconnection
return false;
} else { // Other error or blocking
int nErr = WSAGetLastError();
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
if (!IsSelectableSocket(hSocket)) {
return false;
}
struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
if (nRet == SOCKET_ERROR) {
return false;
}
} else {
return false;
}
}
boost::this_thread::interruption_point();
curTime = GetTimeMillis();
}
return len == 0;
}
struct ProxyCredentials
{
std::string username;
std::string password;
};
/** Connect using SOCKS5 (as described in RFC1928) */
bool static Socks5(string strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
{
LogPrintf("SOCKS5 connecting %s\n", strDest);
if (strDest.size() > 255) {
CloseSocket(hSocket);
return error("Hostname too long");
}
// Accepted authentication methods
std::vector<uint8_t> vSocks5Init;
vSocks5Init.push_back(0x05);
if (auth) {
vSocks5Init.push_back(0x02); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
} else {
vSocks5Init.push_back(0x01); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
}
ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5Init.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
char pchRet1[2];
if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet1[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to initialize");
}
if (pchRet1[1] == 0x02 && auth) {
// Perform username/password authentication (as described in RFC1929)
std::vector<uint8_t> vAuth;
vAuth.push_back(0x01);
if (auth->username.size() > 255 || auth->password.size() > 255)
return error("Proxy username or password too long");
vAuth.push_back(auth->username.size());
vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
vAuth.push_back(auth->password.size());
vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vAuth.size()) {
CloseSocket(hSocket);
return error("Error sending authentication to proxy");
}
LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
char pchRetA[2];
if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy authentication response");
}
if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
CloseSocket(hSocket);
return error("Proxy authentication unsuccesful");
}
} else if (pchRet1[1] == 0x00) {
// Perform no authentication
} else {
CloseSocket(hSocket);
return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
}
std::vector<uint8_t> vSocks5;
vSocks5.push_back(0x05); // VER protocol version
vSocks5.push_back(0x01); // CMD CONNECT
vSocks5.push_back(0x00); // RSV Reserved
vSocks5.push_back(0x03); // ATYP DOMAINNAME
vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
vSocks5.push_back((port >> 8) & 0xFF);
vSocks5.push_back((port >> 0) & 0xFF);
ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
char pchRet2[4];
if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet2[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to accept request");
}
if (pchRet2[1] != 0x00) {
CloseSocket(hSocket);
switch (pchRet2[1]) {
case 0x01:
return error("Proxy error: general failure");
case 0x02:
return error("Proxy error: connection not allowed");
case 0x03:
return error("Proxy error: network unreachable");
case 0x04:
return error("Proxy error: host unreachable");
case 0x05:
return error("Proxy error: connection refused");
case 0x06:
return error("Proxy error: TTL expired");
case 0x07:
return error("Proxy error: protocol error");
case 0x08:
return error("Proxy error: address type not supported");
default:
return error("Proxy error: unknown");
}
}
if (pchRet2[2] != 0x00) {
CloseSocket(hSocket);
return error("Error: malformed proxy response");
}
char pchRet3[256];
switch (pchRet2[3]) {
case 0x01:
ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
break;
case 0x04:
ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
break;
case 0x03: {
ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
if (!ret) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
int nRecv = pchRet3[0];
ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
break;
}
default:
CloseSocket(hSocket);
return error("Error: malformed proxy response");
}
if (!ret) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
LogPrintf("SOCKS5 connected %s\n", strDest);
return true;
}
bool static ConnectSocketDirectly(const CService& addrConnect, SOCKET& hSocketRet, int nTimeout)
{
hSocketRet = INVALID_SOCKET;
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
return false;
}
SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
return false;
#ifdef SO_NOSIGPIPE
int set = 1;
// Different way of disabling SIGPIPE on BSD
setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
// Set to non-blocking
if (!SetSocketNonBlocking(hSocket, true))
return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
int nErr = WSAGetLastError();
// WSAEINVAL is here because some legacy version of winsock uses it
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
struct timeval timeout = MillisToTimeval(nTimeout);
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0) {
LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
CloseSocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR) {
LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
if (nRet != 0) {
LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
CloseSocket(hSocket);
return false;
}
}
#ifdef WIN32
else if (WSAGetLastError() != WSAEISCONN)
#else
else
#endif
{
LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
}
hSocketRet = hSocket;
return true;
}
bool SetProxy(enum Network net, const proxyType &addrProxy)
{
assert(net >= 0 && net < NET_MAX);
if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
proxyInfo[net] = addrProxy;
return true;
}
bool GetProxy(enum Network net, proxyType& proxyInfoOut)
{
assert(net >= 0 && net < NET_MAX);
LOCK(cs_proxyInfos);
if (!proxyInfo[net].IsValid())
return false;
proxyInfoOut = proxyInfo[net];
return true;
}
bool SetNameProxy(const proxyType &addrProxy)
{
if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
nameProxy = addrProxy;
return true;
}
bool GetNameProxy(proxyType &nameProxyOut)
{
LOCK(cs_proxyInfos);
if (!nameProxy.IsValid())
return false;
nameProxyOut = nameProxy;
return true;
}
bool HaveNameProxy()
{
LOCK(cs_proxyInfos);
return nameProxy.IsValid();
}
bool IsProxy(const CNetAddr& addr)
{
LOCK(cs_proxyInfos);
for (int i = 0; i < NET_MAX; i++) {
if (addr == (CNetAddr)proxyInfo[i].proxy)
return true;
}
return false;
}
static bool ConnectThroughProxy(const proxyType &proxy, const std::string strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
SOCKET hSocket = INVALID_SOCKET;
// first connect to proxy server
if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
if (outProxyConnectionFailed)
*outProxyConnectionFailed = true;
return false;
}
// do socks negotiation
if (proxy.randomize_credentials) {
ProxyCredentials random_auth;
random_auth.username = strprintf("%i", insecure_rand());
random_auth.password = strprintf("%i", insecure_rand());
if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
return false;
} else {
if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
return false;
}
hSocketRet = hSocket;
return true;
}
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
proxyType proxy;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
if (GetProxy(addrDest.GetNetwork(), proxy))
return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
else // no proxy needed (none set for target network)
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
}
bool ConnectSocketByName(CService& addr, SOCKET& hSocketRet, const char* pszDest, int portDefault, int nTimeout, bool* outProxyConnectionFailed)
{
string strDest;
int port = portDefault;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
SplitHostPort(string(pszDest), port, strDest);
proxyType nameProxy;
GetNameProxy(nameProxy);
CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
if (addrResolved.IsValid()) {
addr = addrResolved;
return ConnectSocket(addr, hSocketRet, nTimeout);
}
addr = CService("0.0.0.0:0");
if (!HaveNameProxy())
return false;
return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
}
void CNetAddr::Init()
{
memset(ip, 0, sizeof(ip));
}
void CNetAddr::SetIP(const CNetAddr& ipIn)
{
memcpy(ip, ipIn.ip, sizeof(ip));
}
void CNetAddr::SetRaw(Network network, const uint8_t* ip_in)
{
switch (network) {
case NET_IPV4:
memcpy(ip, pchIPv4, 12);
memcpy(ip + 12, ip_in, 4);
break;
case NET_IPV6:
memcpy(ip, ip_in, 16);
break;
default:
assert(!"invalid network");
}
}
static const unsigned char pchOnionCat[] = {0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43};
bool CNetAddr::SetSpecial(const std::string& strName)
{
if (strName.size() > 6 && strName.substr(strName.size() - 6, 6) == ".onion") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
if (vchAddr.size() != 16 - sizeof(pchOnionCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
for (unsigned int i = 0; i < 16 - sizeof(pchOnionCat); i++)
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
return true;
}
return false;
}
CNetAddr::CNetAddr()
{
Init();
}
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
}
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
}
CNetAddr::CNetAddr(const char* pszIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(pszIp, vIP, 1, fAllowLookup))
*this = vIP[0];
}
CNetAddr::CNetAddr(const std::string& strIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
*this = vIP[0];
}
unsigned int CNetAddr::GetByte(int n) const
{
return ip[15 - n];
}
bool CNetAddr::IsIPv4() const
{
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}
bool CNetAddr::IsIPv6() const
{
return (!IsIPv4() && !IsTor());
}
bool CNetAddr::IsRFC1918() const
{
return IsIPv4() && (GetByte(3) == 10 ||
(GetByte(3) == 192 && GetByte(2) == 168) ||
(GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}
bool CNetAddr::IsRFC2544() const
{
return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
}
bool CNetAddr::IsRFC3927() const
{
return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}
bool CNetAddr::IsRFC6598() const
{
return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
}
bool CNetAddr::IsRFC5737() const
{
return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
(GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
(GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
}
bool CNetAddr::IsRFC3849() const
{
return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}
bool CNetAddr::IsRFC3964() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}
bool CNetAddr::IsRFC6052() const
{
static const unsigned char pchRFC6052[] = {0, 0x64, 0xFF, 0x9B, 0, 0, 0, 0, 0, 0, 0, 0};
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}
bool CNetAddr::IsRFC4380() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}
bool CNetAddr::IsRFC4862() const
{
static const unsigned char pchRFC4862[] = {0xFE, 0x80, 0, 0, 0, 0, 0, 0};
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}
bool CNetAddr::IsRFC4193() const
{
return ((GetByte(15) & 0xFE) == 0xFC);
}
bool CNetAddr::IsRFC6145() const
{
static const unsigned char pchRFC6145[] = {0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0};
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}
bool CNetAddr::IsRFC4843() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
}
bool CNetAddr::IsTor() const
{
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}
bool CNetAddr::IsLocal() const
{
// IPv4 loopback
if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
return true;
// IPv6 loopback (::1/128)
static const unsigned char pchLocal[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
if (memcmp(ip, pchLocal, 16) == 0)
return true;
return false;
}
bool CNetAddr::IsMulticast() const
{
return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0) || (GetByte(15) == 0xFF);
}
bool CNetAddr::IsValid() const
{
// Cleanup 3-byte shifted addresses caused by garbage in size field
// of addr messages from versions before 0.2.9 checksum.
// Two consecutive addr messages look like this:
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
// so if the first length field is garbled, it reads the second batch
// of addr misaligned by 3 bytes.
if (memcmp(ip, pchIPv4 + 3, sizeof(pchIPv4) - 3) == 0)
return false;
// unspecified IPv6 address (::/128)
unsigned char ipNone[16] = {};
if (memcmp(ip, ipNone, 16) == 0)
return false;
// documentation IPv6 address
if (IsRFC3849())
return false;
if (IsIPv4()) {
// INADDR_NONE
uint32_t ipNone = INADDR_NONE;
if (memcmp(ip + 12, &ipNone, 4) == 0)
return false;
// 0
ipNone = 0;
if (memcmp(ip + 12, &ipNone, 4) == 0)
return false;
}
return true;
}
bool CNetAddr::IsRoutable() const
{
return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
}
enum Network CNetAddr::GetNetwork() const
{
if (!IsRoutable())
return NET_UNROUTABLE;
if (IsIPv4())
return NET_IPV4;
if (IsTor())
return NET_TOR;
return NET_IPV6;
}
std::string CNetAddr::ToStringIP() const
{
if (IsTor())
return EncodeBase32(&ip[6], 10) + ".onion";
CService serv(*this, 0);
struct sockaddr_storage sockaddr;
socklen_t socklen = sizeof(sockaddr);
if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
char name[1025] = "";
if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
return std::string(name);
}
if (IsIPv4())
return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
else
return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
}
std::string CNetAddr::ToString() const
{
return ToStringIP();
}
bool operator==(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) == 0);
}
bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) != 0);
}
bool operator<(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) < 0);
}
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
if (!IsIPv4())
return false;
memcpy(pipv4Addr, ip + 12, 4);
return true;
}
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
memcpy(pipv6Addr, ip, 16);
return true;
}
// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
std::vector<unsigned char> vchRet;
int nClass = NET_IPV6;
int nStartByte = 0;
int nBits = 16;
// all local addresses belong to the same group
if (IsLocal()) {
nClass = 255;
nBits = 0;
}
// all unroutable addresses belong to the same group
if (!IsRoutable()) {
nClass = NET_UNROUTABLE;
nBits = 0;
}
// for IPv4 addresses, '1' + the 16 higher-order bits of the IP
// includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
else if (IsIPv4() || IsRFC6145() || IsRFC6052()) {
nClass = NET_IPV4;
nStartByte = 12;
}
// for 6to4 tunnelled addresses, use the encapsulated IPv4 address
else if (IsRFC3964()) {
nClass = NET_IPV4;
nStartByte = 2;
}
// for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
else if (IsRFC4380()) {
vchRet.push_back(NET_IPV4);
vchRet.push_back(GetByte(3) ^ 0xFF);
vchRet.push_back(GetByte(2) ^ 0xFF);
return vchRet;
} else if (IsTor()) {
nClass = NET_TOR;
nStartByte = 6;
nBits = 4;
}
// for he.net, use /36 groups
else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
nBits = 36;
// for the rest of the IPv6 network, use /32 groups
else
nBits = 32;
vchRet.push_back(nClass);
while (nBits >= 8) {
vchRet.push_back(GetByte(15 - nStartByte));
nStartByte++;
nBits -= 8;
}
if (nBits > 0)
vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
return vchRet;
}
uint64_t CNetAddr::GetHash() const
{
uint256 hash = Hash(&ip[0], &ip[16]);
uint64_t nRet;
memcpy(&nRet, &hash, sizeof(nRet));
return nRet;
}
// private extensions to enum Network, only returned by GetExtNetwork,
// and only used in GetReachabilityFrom
static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr* addr)
{
if (addr == NULL)
return NET_UNKNOWN;
if (addr->IsRFC4380())
return NET_TEREDO;
return addr->GetNetwork();
}
/** Calculates a metric for how reachable (*this) is from a given partner */
int CNetAddr::GetReachabilityFrom(const CNetAddr* paddrPartner) const
{
enum Reachability {
REACH_UNREACHABLE,
REACH_DEFAULT,
REACH_TEREDO,
REACH_IPV6_WEAK,
REACH_IPV4,
REACH_IPV6_STRONG,
REACH_PRIVATE
};
if (!IsRoutable())
return REACH_UNREACHABLE;
int ourNet = GetExtNetwork(this);
int theirNet = GetExtNetwork(paddrPartner);
bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
switch (theirNet) {
case NET_IPV4:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_IPV4:
return REACH_IPV4;
}
case NET_IPV6:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_TEREDO:
return REACH_TEREDO;
case NET_IPV4:
return REACH_IPV4;
case NET_IPV6:
return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
}
case NET_TOR:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_IPV4:
return REACH_IPV4; // Tor users can connect to IPv4 as well
case NET_TOR:
return REACH_PRIVATE;
}
case NET_TEREDO:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_TEREDO:
return REACH_TEREDO;
case NET_IPV6:
return REACH_IPV6_WEAK;
case NET_IPV4:
return REACH_IPV4;
}
case NET_UNKNOWN:
case NET_UNROUTABLE:
default:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_TEREDO:
return REACH_TEREDO;
case NET_IPV6:
return REACH_IPV6_WEAK;
case NET_IPV4:
return REACH_IPV4;
case NET_TOR:
return REACH_PRIVATE; // either from Tor, or don't care about our address
}
}
}
void CService::Init()
{
port = 0;
}
CService::CService()
{
Init();
}
CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
{
}
CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}
CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
{
}
CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
assert(addr.sin_family == AF_INET);
}
CService::CService(const struct sockaddr_in6& addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
assert(addr.sin6_family == AF_INET6);
}
bool CService::SetSockAddr(const struct sockaddr* paddr)
{
switch (paddr->sa_family) {
case AF_INET:
*this = CService(*(const struct sockaddr_in*)paddr);
return true;
case AF_INET6:
*this = CService(*(const struct sockaddr_in6*)paddr);
return true;
default:
return false;
}
}
CService::CService(const char* pszIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const char* pszIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
*this = ip;
}
CService::CService(const std::string& strIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const std::string& strIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
*this = ip;
}
unsigned short CService::GetPort() const
{
return port;
}
bool operator==(const CService& a, const CService& b)
{
return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
}
bool operator!=(const CService& a, const CService& b)
{
return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
}
bool operator<(const CService& a, const CService& b)
{
return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
}
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t* addrlen) const
{
if (IsIPv4()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
return false;
*addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in* paddrin = (struct sockaddr_in*)paddr;
memset(paddrin, 0, *addrlen);
if (!GetInAddr(&paddrin->sin_addr))
return false;
paddrin->sin_family = AF_INET;
paddrin->sin_port = htons(port);
return true;
}
if (IsIPv6()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
return false;
*addrlen = sizeof(struct sockaddr_in6);
struct sockaddr_in6* paddrin6 = (struct sockaddr_in6*)paddr;
memset(paddrin6, 0, *addrlen);
if (!GetIn6Addr(&paddrin6->sin6_addr))
return false;
paddrin6->sin6_family = AF_INET6;
paddrin6->sin6_port = htons(port);
return true;
}
return false;
}
std::vector<unsigned char> CService::GetKey() const
{
std::vector<unsigned char> vKey;
vKey.resize(18);
memcpy(&vKey[0], ip, 16);
vKey[16] = port / 0x100;
vKey[17] = port & 0x0FF;
return vKey;
}
std::string CService::ToStringPort() const
{
return strprintf("%u", port);
}
std::string CService::ToStringIPPort() const
{
if (IsIPv4() || IsTor()) {
return ToStringIP() + ":" + ToStringPort();
} else {
return "[" + ToStringIP() + "]:" + ToStringPort();
}
}
std::string CService::ToString() const
{
return ToStringIPPort();
}
void CService::SetPort(unsigned short portIn)
{
port = portIn;
}
CSubNet::CSubNet() : valid(false)
{
memset(netmask, 0, sizeof(netmask));
}
CSubNet::CSubNet(const std::string& strSubnet, bool fAllowLookup)
{
size_t slash = strSubnet.find_last_of('/');
std::vector<CNetAddr> vIP;
valid = true;
// Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
memset(netmask, 255, sizeof(netmask));
std::string strAddress = strSubnet.substr(0, slash);
if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup)) {
network = vIP[0];
if (slash != strSubnet.npos) {
std::string strNetmask = strSubnet.substr(slash + 1);
int32_t n;
// IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
const int astartofs = network.IsIPv4() ? 12 : 0;
if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
{
if (n >= 0 && n <= (128 - astartofs * 8)) // Only valid if in range of bits of address
{
n += astartofs * 8;
// Clear bits [n..127]
for (; n < 128; ++n)
netmask[n >> 3] &= ~(1 << (7 - (n & 7)));
} else {
valid = false;
}
} else // If not a valid number, try full netmask syntax
{
if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
{
// Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
// we don't want pchIPv4 to be part of the mask.
for (int x = astartofs; x < 16; ++x)
netmask[x] = vIP[0].ip[x];
} else {
valid = false;
}
}
}
} else {
valid = false;
}
// Normalize network according to netmask
for (int x = 0; x < 16; ++x)
network.ip[x] &= netmask[x];
}
CSubNet::CSubNet(const CNetAddr &addr):
valid(addr.IsValid())
{
memset(netmask, 255, sizeof(netmask));
network = addr;
}
bool CSubNet::Match(const CNetAddr& addr) const
{
if (!valid || !addr.IsValid())
return false;
for (int x = 0; x < 16; ++x)
if ((addr.ip[x] & netmask[x]) != network.ip[x])
return false;
return true;
}
static inline int NetmaskBits(uint8_t x)
{
switch(x) {
case 0x00: return 0; break;
case 0x80: return 1; break;
case 0xc0: return 2; break;
case 0xe0: return 3; break;
case 0xf0: return 4; break;
case 0xf8: return 5; break;
case 0xfc: return 6; break;
case 0xfe: return 7; break;
case 0xff: return 8; break;
default: return -1; break;
}
}
std::string CSubNet::ToString() const
{
/* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */
int cidr = 0;
bool valid_cidr = true;
int n = network.IsIPv4() ? 12 : 0;
for (; n < 16 && netmask[n] == 0xff; ++n)
cidr += 8;
if (n < 16) {
int bits = NetmaskBits(netmask[n]);
if (bits < 0)
valid_cidr = false;
else
cidr += bits;
++n;
}
for (; n < 16 && valid_cidr; ++n)
if (netmask[n] != 0x00)
valid_cidr = false;
/* Format output */
std::string strNetmask;
if (valid_cidr) {
strNetmask = strprintf("%u", cidr);
} else {
if (network.IsIPv4())
strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
else
strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
}
return network.ToString() + "/" + strNetmask;
}
bool CSubNet::IsValid() const
{
return valid;
}
bool operator==(const CSubNet& a, const CSubNet& b)
{
return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
}
bool operator!=(const CSubNet& a, const CSubNet& b)
{
return !(a == b);
}
bool operator<(const CSubNet& a, const CSubNet& b)
{
return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
}
#ifdef WIN32
std::string NetworkErrorString(int err)
{
char buf[256];
buf[0] = 0;
if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, sizeof(buf), NULL)) {
return strprintf("%s (%d)", buf, err);
} else {
return strprintf("Unknown error (%d)", err);
}
}
#else
std::string NetworkErrorString(int err)
{
char buf[256];
const char* s = buf;
buf[0] = 0;
/* Too bad there are two incompatible implementations of the
* thread-safe strerror. */
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
if (strerror_r(err, buf, sizeof(buf)))
buf[0] = 0;
#endif
return strprintf("%s (%d)", s, err);
}
#endif
bool CloseSocket(SOCKET& hSocket)
{
if (hSocket == INVALID_SOCKET)
return false;
#ifdef WIN32
int ret = closesocket(hSocket);
#else
int ret = close(hSocket);
#endif
hSocket = INVALID_SOCKET;
return ret != SOCKET_ERROR;
}
bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
{
if (fNonBlocking) {
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
} else {
#ifdef WIN32
u_long nZero = 0;
if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
}
return true;
}
| [
"laohcs9412@gmail.com"
] | laohcs9412@gmail.com |
707288167b03667536400103fe9d182fb381fd78 | bcdacb31ebb2da2e9da0efe9190a00ff0407edf5 | /算法竞赛/DFS-part of sums problem/main.cpp | 553f45d9cd503c3fa29d59dbc168fd067367b409 | [] | no_license | guohaoyu110/Self-Learning-DataStructure | 08fe60fccb4b48e8503dd95f469ed82f7f109059 | 0d1533f70cf46aa28be5a5be84b9ce6cd4cc5dda | refs/heads/master | 2022-02-22T07:23:21.956554 | 2019-10-12T22:52:02 | 2019-10-12T22:52:02 | 109,500,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp | //部分和问题
#include <iostream>
using namespace std;
const int Maxn=10000;
int a[Maxn];
int n,k;
bool dfs(int i,int sum)
{
if(sum>k) return false;
if(i>=n)
{
if(sum==k)
return 1;
else return 0;
}
if(dfs(i+1,sum)) return true;
if(dfs(i+1,sum+a[i])) return true;
return false;
}
void solve()
{
if(dfs(0,0)) printf("yes!");
else printf("no!");
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cin>>k;
solve();
} | [
"guohaoyu110@gmail.com"
] | guohaoyu110@gmail.com |
d5e429422e9593994e83f014c11be8bbabeb90c6 | d7496dc1edde0fa081f96dc122bb6a08b7f86c88 | /plugin_scl_import/oe_smv_ctrl_block.cpp | 0cc60b30658a65e5ba2ca58d0345db70167befcf | [] | no_license | song-kang/SKHMIProject | e022f50fdefd7ebb551abc064fa801299f93723b | ff20468ed1f1acea03545af24ff38bee00c8ffc8 | refs/heads/master | 2021-08-17T04:24:02.410448 | 2021-08-06T08:59:07 | 2021-08-06T08:59:07 | 126,560,712 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 9,511 | cpp | #include "oe_smv_ctrl_block.h"
#include "view_plugin_scl_import.h"
#include "oe_ied.h"
#include "oe_cpu.h"
#include "oe_group.h"
#include "oe_smv_ap.h"
oe_smv_ctrl_block::oe_smv_ctrl_block(view_plugin_scl_import * scl,QList<XmlObject*> list,oe_group *group)
{
sclImport = scl;
document = list;
m_ied = group->getCpu()->getIed();
m_cpu = group->getCpu();
m_group = group;
}
oe_smv_ctrl_block::~oe_smv_ctrl_block(void)
{
}
void oe_smv_ctrl_block::initParam()
{
ied_no = 0;
cb_no = 0;
cpu_no = 0;
group_no = 0;
cb_name = "";
cb_desc = "";
conf_rev = "";
appid = "";
datset = "";
sv_ena = 0;
smvid = "";
smprate = 0;
nof_asdu = 0;
opt_reftime = 0;
opt_sync = 0;
opt_smprate = 0;
opt_secu = 0;
opt_dataref = 0;
}
bool oe_smv_ctrl_block::execute(QString & error,QString &warnText)
{
XmlObject *cpu_obj = m_cpu->getObject();
if (cpu_obj)
{
QList<XmlObject*> lstSmvCB = cpu_obj->findChildrenDeep("SampledValueControl");
foreach (XmlObject *smv_obj, lstSmvCB)
{
initParam();
if (!insertSmvCB(smv_obj,error,warnText))
return false;
if (group_no) //插入成功,并且组号非零时,处理SMV访问点
{
oe_smv_ap sa(sclImport,document,this);
if (!sa.execute(error,warnText))
return false;
}
}
}
return true;
}
bool oe_smv_ctrl_block::insertSmvCB(XmlObject * object,QString & error,QString &warnText)
{
if (!get_ied_no(object,error,warnText))
return false;
if (!get_cb_no(object,error,warnText))
return false;
if (!get_cpu_no(object,error,warnText))
return false;
if (!get_datset(object,error,warnText))
return false;
if (!get_group_no(object,error,warnText))
return false;
if (!get_cb_name(object,error,warnText))
return false;
if (!get_cb_desc(object,error,warnText))
return false;
if (!get_conf_rev(object,error,warnText))
return false;
if (!get_appid(object,error,warnText))
return false;
if (!get_sv_ena(object,error,warnText))
return false;
if (!get_smvid(object,error,warnText))
return false;
if (!get_smprate(object,error,warnText))
return false;
if (!get_nof_asdu(object,error,warnText))
return false;
if (!get_opt_reftime(object,error,warnText))
return false;
if (!get_opt_sync(object,error,warnText))
return false;
if (!get_opt_smprate(object,error,warnText))
return false;
if (!get_opt_secu(object,error,warnText))
return false;
if (!get_opt_dataref(object,error,warnText))
return false;
if (group_no == 0) //未发现组号,不加入数据库,但不中止
return true;
SString sql;
sql.sprintf("insert into t_oe_smv_ctrl_block (ied_no,cb_no,cpu_no,group_no,cb_name,cb_desc,conf_rev,appid,datset,"
"sv_ena,smvid,smprate,nof_asdu,opt_reftime,opt_sync,opt_smprate,opt_secu,opt_dataref) "
"values (%d,%d,%d,%d,'%s','%s','%s','%s','%s',%d,'%s',%d,%d,%d,%d,%d,%d,%d)",
ied_no,cb_no,cpu_no,group_no,cb_name.data(),cb_desc.data(),conf_rev.data(),appid.data(),datset.data(),
sv_ena,smvid.data(),smprate,nof_asdu,opt_reftime,opt_sync,opt_smprate,opt_secu,opt_dataref);
if (!DB->Execute(sql))
{
error = "SQL语句执行错误:" + sql;
return false;
}
if (m_bMDB && !MDB->Execute(sql))
{
error = "内存库SQL语句执行错误:" + sql;
return false;
}
return true;
}
bool oe_smv_ctrl_block::get_ied_no(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
ied_no = m_ied->getIedNo();
return true;
}
bool oe_smv_ctrl_block::get_cb_no(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
cb_no = m_ied->getSmvCbNo();
cb_no++;
m_ied->setSmvCbNo(cb_no);
return true;
}
bool oe_smv_ctrl_block::get_cpu_no(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
cpu_no = m_cpu->getCpuNo();
return true;
}
bool oe_smv_ctrl_block::get_group_no(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
SString sql;
SRecordset rs;
SString mms_path = m_cpu->getCpuMmsPath()+"$"+ datset;
sql.sprintf("select group_no from t_oe_group where ied_no=%d and cpu_no=%d and mms_path='%s'",
m_ied->getIedNo(),m_cpu->getCpuNo(),mms_path.data());
int cnt = DB->Retrieve(sql,rs);
if (cnt < 0)
{
error = "SQL语句执行错误:" + sql;
return false;
}
else if (cnt == 0)
{
warnText += QString("告警:Ied[%1]-Cpu[%2]的SampledValueControl中datSet[%3]未找到对应组号,请检查。")
.arg(m_cpu->getIedNo()).arg(m_cpu->getCpuNo()).arg(datset.data());
warnText += "\n";
}
else if (cnt > 0)
{
group_no = rs.GetValue(0,0).toInt();
}
return true;
}
bool oe_smv_ctrl_block::get_cb_name(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
cb_name = object->attrib("name").toLocal8Bit().data();
return true;
}
bool oe_smv_ctrl_block::get_cb_desc(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
cb_desc = object->attrib("desc").toLocal8Bit().data();
return true;
}
bool oe_smv_ctrl_block::get_conf_rev(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
conf_rev = object->attrib("confRev").toLocal8Bit().data();
return true;
}
bool oe_smv_ctrl_block::get_appid(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
appid = object->attrib("appID").toLocal8Bit().data();
return true;
}
bool oe_smv_ctrl_block::get_datset(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
datset = object->attrib("datSet").toLocal8Bit().data();
return true;
}
bool oe_smv_ctrl_block::get_sv_ena(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
sv_ena = object->attrib("svEna") == "true" ? 1 : 0;
return true;
}
bool oe_smv_ctrl_block::get_smvid(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
smvid = object->attrib("smvID").toLocal8Bit().data();
return true;
}
bool oe_smv_ctrl_block::get_smprate(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
smprate = object->attrib("smpRate").toInt();
return true;
}
bool oe_smv_ctrl_block::get_nof_asdu(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
nof_asdu = object->attrib("nofASDU").toInt();
return true;
}
bool oe_smv_ctrl_block::get_opt_reftime(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
XmlObject *smv_opt_obj = object->findChild("SmvOpts");
if (smv_opt_obj)
{
opt_reftime = smv_opt_obj->attrib("refreshTime") == "true" ? 1 : 0;
}
else
{
//error = QString("获取Ied:%1 Cpu:%2 Group:%3的SampledValueControl[%4]的SmvOpts失败。")
// .arg(m_cpu->getIedNo()).arg(m_cpu->getCpuNo()).arg(m_group->getGroupNo()).arg(cb_name.data());
//return false;
opt_reftime = 0;
}
return true;
}
bool oe_smv_ctrl_block::get_opt_sync(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
XmlObject *smv_opt_obj = object->findChild("SmvOpts");
if (smv_opt_obj)
{
opt_sync = smv_opt_obj->attrib("sampleSynchronized") == "true" ? 1 : 0;
}
else
{
//error = QString("获取Ied:%1 Cpu:%2 Group:%3的SampledValueControl[%4]的SmvOpts失败。")
// .arg(m_cpu->getIedNo()).arg(m_cpu->getCpuNo()).arg(m_group->getGroupNo()).arg(cb_name.data());
//return false;
opt_sync = 0;
}
return true;
}
bool oe_smv_ctrl_block::get_opt_smprate(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
XmlObject *smv_opt_obj = object->findChild("SmvOpts");
if (smv_opt_obj)
{
opt_smprate = smv_opt_obj->attrib("samleRate") == "true" ? 1 : 0;
}
else
{
//error = QString("获取Ied:%1 Cpu:%2 Group:%3的SampledValueControl[%4]的SmvOpts失败。")
// .arg(m_cpu->getIedNo()).arg(m_cpu->getCpuNo()).arg(m_group->getGroupNo()).arg(cb_name.data());
//return false;
opt_smprate = 0;
}
return true;
}
bool oe_smv_ctrl_block::get_opt_secu(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
XmlObject *smv_opt_obj = object->findChild("SmvOpts");
if (smv_opt_obj)
{
opt_secu = smv_opt_obj->attrib("security") == "true" ? 1 : 0;
}
else
{
//error = QString("获取Ied:%1 Cpu:%2 Group:%3的SampledValueControl[%4]的SmvOpts失败。")
// .arg(m_cpu->getIedNo()).arg(m_cpu->getCpuNo()).arg(m_group->getGroupNo()).arg(cb_name.data());
//return false;
opt_secu = 0;
}
return true;
}
bool oe_smv_ctrl_block::get_opt_dataref(XmlObject * object,QString & error,QString &warnText)
{
S_UNUSED(object);
S_UNUSED(error);
S_UNUSED(warnText);
XmlObject *smv_opt_obj = object->findChild("SmvOpts");
if (smv_opt_obj)
{
opt_dataref = smv_opt_obj->attrib("dataRef") == "true" ? 1 : 0;
}
else
{
//error = QString("获取Ied:%1 Cpu:%2 Group:%3的SampledValueControl[%4]的SmvOpts失败。")
// .arg(m_cpu->getIedNo()).arg(m_cpu->getCpuNo()).arg(m_group->getGroupNo()).arg(cb_name.data());
//return false;
opt_dataref = 0;
}
return true;
}
| [
"13951005719@139.com"
] | 13951005719@139.com |
f6b5dd2b41e157ac02166f01d93732ff004a2934 | 95508238a849c712d5a76cab2b0374528208183f | /src/libserver/css/parse_error.hxx | 458469afc74e44934e84ae0bf46161e4d8744349 | [
"Apache-2.0"
] | permissive | FelixSchwarz/rspamd | cf08be8068689c438cd0d448c7fae590b968740a | 11e5b97f682378449f6aa82f50dfe89ced8e5bb3 | refs/heads/master | 2023-04-01T02:06:25.360512 | 2021-03-31T16:02:00 | 2021-03-31T16:02:00 | 353,408,329 | 0 | 0 | Apache-2.0 | 2021-03-31T15:43:54 | 2021-03-31T15:43:53 | null | UTF-8 | C++ | false | false | 1,357 | hxx | /*-
* Copyright 2021 Vsevolod Stakhov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef RSPAMD_PARSE_ERROR_HXX
#define RSPAMD_PARSE_ERROR_HXX
#include <string>
#include <optional>
namespace rspamd::css {
/*
* Generic parser errors
*/
enum class css_parse_error_type {
PARSE_ERROR_UNKNOWN_OPTION,
PARSE_ERROR_INVALID_SYNTAX,
PARSE_ERROR_BAD_NESTING,
PARSE_ERROR_NYI,
PARSE_ERROR_UNKNOWN_ERROR,
};
struct css_parse_error {
css_parse_error_type type = css_parse_error_type::PARSE_ERROR_UNKNOWN_ERROR;
std::optional<std::string> description;
explicit css_parse_error (css_parse_error_type type, const std::string &description) :
type(type), description(description) {}
explicit css_parse_error (css_parse_error_type type) :
type(type) {}
css_parse_error() = default;
};
}
#endif //RSPAMD_PARSE_ERROR_HXX
| [
"vsevolod@highsecure.ru"
] | vsevolod@highsecure.ru |
714d24223a58f8eb1e3a73f96b5c987c046dbb1c | b1c0300a1c488f22e20e0d1984df12af8f0845e5 | /Engine/src/Engine/Core/Application.cpp | 79b1893bc9e7d5ea35cdc07ed69c4d94b1e8c8cc | [] | no_license | spironan/GameEngineBase | bda73dfa7f4c68c1f51e6d38257b59c45110bd8f | 7da3eb092890a8fc075a3ce610c7cc4077e3470a | refs/heads/master | 2023-07-28T11:42:39.648027 | 2021-06-12T17:17:57 | 2021-06-12T17:17:57 | 365,776,084 | 0 | 1 | null | 2021-09-14T13:18:18 | 2021-05-09T14:45:51 | C++ | UTF-8 | C++ | false | false | 12,828 | cpp | /************************************************************************************//*!
\file Application.cpp
\project INSERT PROJECT NAME
\author Chua Teck Lee, c.tecklee, 390008420
\par email: c.tecklee\@digipen.edu
\date May 05, 2021
\brief Core Application Loop and functionality.
Will be inherited by Sandbox project.
Copyright (C) 2021 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents
without the prior written consent of DigiPen Institute of
Technology is prohibited.
*//*************************************************************************************/
#include "pch.h"
#include "Application.h"
#include "Engine/Core/Input.h"
#include "Engine/Renderer/GraphicsContext.h"
namespace engine
{
Application* Application::s_instance = nullptr;
Application::Application(const std::string& name, CommandLineArgs args)
: m_commandLineArgs{ args }
, m_running{ true }
{
ENGINE_PROFILE_FUNCTION();
ENGINE_ASSERT_MSG(!s_instance, "Application already exist!");
s_instance = this;
m_window = Window::Create(WindowProperties{ name });
//Binds window callback to call Application::OnEvent
m_window->SetEventCallback(ENGINE_BIND_EVENT_FN(Application::OnEvent));
//Retrieve renderer from window
m_renderer = static_cast<GraphicsContext*>(m_window->GetRenderingContext());
m_imGuiLayer = new ImGuiLayer();
PushOverlay(m_imGuiLayer);
/*Initialize Input Management*/
Input::Init();
}
Application::~Application()
{
ENGINE_PROFILE_FUNCTION();
/*Shutdown Input Management*/
Input::ShutDown();
m_layerStack.PopOverlay(m_imGuiLayer);
delete m_imGuiLayer;
delete m_window;
}
void Application::Run()
{
ENGINE_PROFILE_FUNCTION();
//#define DEBUG_APP_LOGS
#ifdef DEBUG_APP_LOGS
{
ENGINE_PROFILE_SCOPE("Application Debug");
#define BASIC_DEBUG_LOGS
#ifdef BASIC_DEBUG_LOGS
// Testing debug
bool pass = true;
ENGINE_ASSERT(true);
//ENGINE_ASSERT(false);
ENGINE_ASSERT_MSG(pass, "failed test case");
//ENGINE_ASSERT_MSG(!pass, "failed test case");
ENGINE_VERIFY(pass);
//ENGINE_VERIFY(!pass);
ENGINE_VERIFY_MSG(pass, "failed test case");
//ENGINE_VERIFY_MSG(!pass, "failed test case");
LOG_ENGINE_TRACE("Trace Log!");
LOG_ENGINE_INFO("Info Log!");
LOG_ENGINE_WARN("Warning Log!");
LOG_ENGINE_ERROR("Error Log!");
LOG_ENGINE_CRITICAL("Critical Log!");
#endif //BASIC_DEBUG_LOG
#define EVENTS_DEBUG_LOG
#ifdef EVENTS_DEBUG_LOG
//Debug log for events
std::vector<engine::Event*> events;
//windows events
engine::WindowResizeEvent resizeEvent{ 1280,720 }; events.push_back(&resizeEvent);
engine::WindowCloseEvent closeEvent{}; events.push_back(&closeEvent);
engine::WindowFocusEvent focusEvent{}; events.push_back(&focusEvent);
engine::WindowLoseFocusEvent loseFocusEvent{}; events.push_back(&loseFocusEvent);
engine::WindowMovedEvent movedEvent{}; events.push_back(&movedEvent);
//keyboard events
engine::KeyPressedEvent keyPressed{ 50 , 1 }; events.push_back(&keyPressed);
engine::KeyReleasedEvent keyReleased{ 50 }; events.push_back(&keyReleased);
engine::KeyTypedEvent keyTyped{ 50 }; events.push_back(&keyTyped);
//mouse events
engine::MouseMovedEvent mouseMoved{ 10, 20 }; events.push_back(&mouseMoved);
engine::MouseButtonPressedEvent mousePressed{ engine::mouse::Button0 }; events.push_back(&mousePressed);
engine::MouseButtonReleasedEvent mouseButtonReleased{ engine::mouse::Button0 }; events.push_back(&mouseButtonReleased);
engine::MouseScrolledEvent mouseScrolled{ 20, 10 }; events.push_back(&mouseScrolled);
std::cout << "EVENTS DEBUG" << std::endl;
std::cout << "INDIVIDUAL EVENT VIEW" << std::endl;
for (engine::Event* e : events)
{
std::cout << "[Event : " << e->ToString() << "]" << std::endl;
std::cout << "EVENT CATEGORY NONE : \t\t\t";
if (e->IsInCategory(engine::EVENT_CATEGORY::NONE))
{
std::cout << "[YES]";
}
else
{
std::cout << "[NO]";
}
std::cout << std::endl;
std::cout << "EVENT CATEGORY APPLICATION : \t\t";
if (e->IsInCategory(engine::EVENT_CATEGORY::APPLICATION))
{
std::cout << "[YES]";
}
else
{
std::cout << "[NO]";
}
std::cout << std::endl;
std::cout << "EVENT CATEGORY INPUT : \t\t\t";
if (e->IsInCategory(engine::EVENT_CATEGORY::INPUT))
{
std::cout << "[YES]";
}
else
{
std::cout << "[NO]";
}
std::cout << std::endl;
std::cout << "EVENT CATEGORY KEYBOARD : \t\t";
if (e->IsInCategory(engine::EVENT_CATEGORY::KEYBOARD))
{
std::cout << "[YES]";
}
else
{
std::cout << "[NO]";
}
std::cout << std::endl;
std::cout << "EVENT CATEGORY MOUSE : \t\t\t";
if (e->IsInCategory(engine::EVENT_CATEGORY::MOUSE))
{
std::cout << "[YES]";
}
else
{
std::cout << "[NO]";
}
std::cout << std::endl;
std::cout << "EVENT CATEGORY MOUSEBUTTON : \t\t";
if (e->IsInCategory(engine::EVENT_CATEGORY::MOUSEBUTTON))
{
std::cout << "[YES]";
}
else
{
std::cout << "[NO]";
}
std::cout << std::endl;
}
std::cout << "\n\n\n\n";
std::cout << "Event CATEGORIC VIEW" << std::endl;
std::cout << "EVENT CATEGORY NONE" << std::endl;
for (engine::Event* e : events)
{
if (e->IsInCategory(engine::EVENT_CATEGORY::NONE))
{
LOG_ENGINE_TRACE(e->ToString());
}
}
std::cout << "EVENT CATEGORY APPLICATION" << std::endl;
for (engine::Event* e : events)
{
if (e->IsInCategory(engine::EVENT_CATEGORY::APPLICATION))
{
LOG_ENGINE_TRACE(e->ToString());
}
}
std::cout << "EVENT CATEGORY INPUT" << std::endl;
for (engine::Event* e : events)
{
if (e->IsInCategory(engine::EVENT_CATEGORY::INPUT))
{
LOG_ENGINE_TRACE(e->ToString());
}
}
std::cout << "EVENT CATEGORY KEYBOARD" << std::endl;
for (engine::Event* e : events)
{
if (e->IsInCategory(engine::EVENT_CATEGORY::KEYBOARD))
{
LOG_ENGINE_TRACE(e->ToString());
}
}
std::cout << "EVENT CATEGORY MOUSE" << std::endl;
for (engine::Event* e : events)
{
if (e->IsInCategory(engine::EVENT_CATEGORY::MOUSE))
{
LOG_ENGINE_TRACE(e->ToString());
}
}
std::cout << "EVENT CATEGORY MOUSEBUTTON" << std::endl;
for (engine::Event* e : events)
{
if (e->IsInCategory(engine::EVENT_CATEGORY::MOUSEBUTTON))
{
LOG_ENGINE_TRACE(e->ToString());
}
}
#endif //EVENT_DEBUG_LOG
}
#endif //DEBUG_APP_LOGS
while (m_running)
{
ENGINE_PROFILE_SCOPE("Runloop");
/*Calculate dt*/
Timestep dt{ m_window->CalcDeltaTime() };
/*Update Input Management here*/
Input::Update();
/* Process input events */
m_window->ProcessEvents();
//whatever the renderer needs to call at the beggining if each frame e.g. clear color
m_renderer->OnUpdateBegin();
// Layerstack update : layers gets drawn first followed by overlays
// starting with the standard layers
{
ENGINE_PROFILE_SCOPE("LayerStack OnUpdate");
for (Layer* layer : m_layerStack)
{
layer->OnUpdate(dt);
}
}
// followed by imgui updates
m_imGuiLayer->Begin();
{
ENGINE_PROFILE_SCOPE("LayerStack OnImGuiUpdate");
for (Layer* layer : m_layerStack)
{
layer->OnImGuiRender();
}
}
m_imGuiLayer->End();
m_window->SwapBuffers();
//m_window->OnUpdate(dt);
}
}
void Application::Close()
{
m_running = false;
}
void Application::OnEvent(Event& e)
{
ENGINE_PROFILE_FUNCTION();
//Log events
//LOG_ENGINE_INFO("{0}", e);
EventDispatcher dispatcher(e);
dispatcher.Dispatch<WindowCloseEvent>(ENGINE_BIND_EVENT_FN(Application::OnWindowClose));
for (auto it = m_layerStack.rbegin(); it != m_layerStack.rend(); ++it)
{
(*it)->OnEvent(e);
// if event is handled, stop propogating
if (e.Handled) break;
}
}
void Application::PushLayer(Layer* layer)
{
ENGINE_PROFILE_FUNCTION();
m_layerStack.PushLayer(layer);
layer->OnAttach();
}
void Application::PushOverlay(Layer* overlay)
{
ENGINE_PROFILE_FUNCTION();
m_layerStack.PushOverlay(overlay);
overlay->OnAttach();
}
bool Application::OnWindowClose(WindowCloseEvent& e)
{
m_running = false;
return true;
}
} | [
"c_tecklee@hotmail.com"
] | c_tecklee@hotmail.com |
b980fbfd1567587c06e667bd45b181fb4d6041e9 | 00bc11b60e1088f22b11bafdd9b1e755aa004c12 | /SRC/3D/SMKTRLS.CPP | d51cb6fef3f3da36414be2e48b4fcb982ac149f2 | [] | no_license | Almahmudrony/BattleOfBritain | 7a29c28eccfad7c9fb5c4082a6a988bcfe9a3d7a | ab87c6c9490c48912f1f6bf65cc5da97d5e0515b | refs/heads/master | 2022-01-11T16:19:14.153102 | 2015-08-11T22:39:41 | 2015-08-11T22:47:57 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 28,061 | cpp | /*
Battle of Britain
Copyright (C) 2000, 2001 Empire Interactive (Europe) Ltd,
677 High Road, North Finchley, London N12 0DA
Please see the document licence.doc for the full licence agreement
2. LICENCE
2.1
Subject to the provisions of this Agreement we now grant to you the
following rights in respect of the Source Code:
2.1.1
the non-exclusive right to Exploit the Source Code and Executable
Code on any medium; and
2.1.2
the non-exclusive right to create and distribute Derivative Works.
2.2
Subject to the provisions of this Agreement we now grant you the
following rights in respect of the Object Code:
2.2.1
the non-exclusive right to Exploit the Object Code on the same
terms and conditions set out in clause 3, provided that any
distribution is done so on the terms of this Agreement and is
accompanied by the Source Code and Executable Code (as
applicable).
3. GENERAL OBLIGATIONS
3.1
In consideration of the licence granted in clause 2.1 you now agree:
3.1.1
that when you distribute the Source Code or Executable Code or
any Derivative Works to Recipients you will also include the
terms of this Agreement;
3.1.2
that when you make the Source Code, Executable Code or any
Derivative Works ("Materials") available to download, you will
ensure that Recipients must accept the terms of this Agreement
before being allowed to download such Materials;
3.1.3
that by Exploiting the Source Code or Executable Code you may
not impose any further restrictions on a Recipient's subsequent
Exploitation of the Source Code or Executable Code other than
those contained in the terms and conditions of this Agreement;
3.1.4
not (and not to allow any third party) to profit or make any
charge for the Source Code, or Executable Code, any
Exploitation of the Source Code or Executable Code, or for any
Derivative Works;
3.1.5
not to place any restrictions on the operability of the Source
Code;
3.1.6
to attach prominent notices to any Derivative Works stating
that you have changed the Source Code or Executable Code and to
include the details anddate of such change; and
3.1.7
not to Exploit the Source Code or Executable Code otherwise than
as expressly permitted by this Agreement.
questions about this file may be asked at bob@rowansoftware.com a
better place to ask is http://www.simhq.com/ or even :-
http://www.simhq.com/cgi-bin/boards/cgi-bin/forumdisplay.cgi?action=topics&forum=Battle+of+Britain&number=40&DaysPrune=20&LastLogin=
*/
//------------------------------------------------------------------------------
//Filename smktrls.cpp
//System
//Author Robert Slater
//Date Wed 9 Feb 2000
//Description
//------------------------------------------------------------------------------
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
// INCLUDE FILES
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
#include "DOSDefs.h"
//#include "MAClib.h"f
#define F_GRAFIX //DAW 05Aug96
//DeadCode RJS 17Oct96 #define F_SOUNDS
#define F_BATTLE
#include "myerror.h"
#include "Palette.h"
#include "myAngles.h"
#include "Worldinc.h"
#include "3DDefs.h"
#include "3DCom.h"
#define MATRIX_CODE_REQ
#include "Matrix.h"
#include "polygon.h" //RJS 02Dec97
#include "fastmath.h"
#include "mymath.h" //RJS 25Jul96
#include "viewsel.h" //RJS 30Aug96
#include "ranges.h"
#include "speed.h" //RJS 01Oct96
#include "shpinstr.h" //RJS 03Jul98
#include "modinst.h" //RJS 03Jul98
#include "imagemap.g"
#include "imagemap.h"
#include "viewsel.h"
#include "smktrls.h"
TrailInfo Smoke_Trails;
void TrailInfo::SetViewPoint(ViewPoint* vpnt)
{
vp = vpnt;
}
void TrailInfo::SetVisibility(float fdx, float fdy, float fdz, float linelen)
{
}
void TrailInfo::CalcCylinder()
{
flipped = false;
if (wasLine)
{
g_lpLib3d->CylinderOffsets(newco[0],newco[0],radius,xoff1,yoff1,dpbacktrans);
xoff1 = yoff1 = 0;
wasLine = false;
}
xoff0 = xoff1;
yoff0 = yoff1;
dpfronttrans = dpbacktrans;
g_lpLib3d->CylinderOffsets(dpfronttrans,newco[1],radius,xoff1,yoff1,dpbacktrans);
if (traillength)
{
// Assume 90 degree FoV cos it's better than nothing...
float fscr_z = 1./dpfronttrans.getPosZ();
float bscr_z = 1./dpbacktrans.getPosZ();
float fscr_x = dpfronttrans.getPosX()*fscr_z;
float fscr_y = dpfronttrans.getPosY()*fscr_z;
float bscr_x = dpbacktrans.getPosX()*bscr_z;
float bscr_y = dpbacktrans.getPosY()*bscr_z;
float av_z = (fscr_z + bscr_z)*.5;
float scaletrail = float(traillength)*av_z;
float dsx = fscr_x-bscr_x;
float dsy = fscr_y-bscr_y;
float linescale;
linescale = (fastMath.FastSqrt(dsx*dsx+dsy*dsy)*100.0) / scaletrail;
fastMath.FloatToInt(&visibility,linescale);
/* SLong cylobscur;
fastMath.FloatToInt(&cylobscur,radius);
cylobscur = (traillength<<16)/cylobscur;
visibility = (visibility*cylobscur)>>16;*/
}
}
void TrailInfo::DuffButNecessary()
{
wasLine = true;
}
void TrailInfo::Init()
{
g_lpLib3d->CylinderOffsets(newco[0],newco[0],radius,xoff1,yoff1,dpbacktrans);
g_lpLib3d->CylinderOffsets(dpbacktrans,newco[1],radius,xoff1,yoff1,dpfronttrans);
wasLine = false;
}
void TrailInfo::CheckNearest()
{
#ifndef _REDO_ME2_
if (dpbacktrans.getPosZ() > dpfronttrans.getPosZ())
{
flipped = true;
bak_vertex0 = vertex0;
bak_vertex1 = vertex1;
bak_WCylStartP=WCylStartP;
bak_WCylEndP=WCylEndP;
bak_xoff0=xoff0;
bak_yoff0=yoff0;
bak_xoff1=xoff1;
bak_yoff1=yoff1;
bak_oldradius=oldradius;
bak_radius=radius;
bak_dpfronttrans = dpfronttrans;
bak_dpbacktrans = dpbacktrans;
dpfronttrans = dpbacktrans;
dpbacktrans = bak_dpfronttrans;
vertex0 = vertex1;
vertex1 = bak_vertex0;
WCylStartP = WCylEndP;
WCylEndP = bak_WCylStartP;
xoff0 = xoff1;
yoff0 = yoff1;
xoff1 = bak_xoff0;
yoff1 = bak_yoff0;
oldradius = radius;
radius = bak_oldradius;
}
#endif
}
void TrailInfo::Restore()
{
if (flipped)
{
vertex0 = bak_vertex0;
vertex1 = bak_vertex1;
WCylStartP = bak_WCylStartP;
WCylEndP = bak_WCylEndP;
xoff0 = bak_xoff0;
yoff0 = bak_yoff0;
xoff1 = bak_xoff1;
yoff1 = bak_yoff1;
oldradius = bak_oldradius;
radius = bak_radius;
dpfronttrans = bak_dpfronttrans;
dpbacktrans = bak_dpbacktrans;
}
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ParticleStreamImapd
//Author Robert Slater
//Date Thu 4 Dec 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void TrailInfo::ParticleStreamImapd()
{
#ifndef _REDO_ME2_
DoPointStruc dopointRoot;
Bool oldcross;
Float RelX, RelY, RelZ;
UWord counter;
SLong xDelta,yDelta;
SLong RandxDelta,RandyDelta;
SLong xDeltCap,yDeltCap;
SWord RSeed;
SLong XoffGap;
SLong YoffGap;
SLong Radius;
ImageMapNumber imapno = (ImageMapNumber) imagemap0;
SWord maxx, maxy;
SLong MaxRadius;
SLong wXStep, wYStep, wZStep;
SLong wXStart, wYStart, wZStart;
SLong MaxDist, Dist;
SLong RadStep;
ULong thetime = 0;
SLong depth;
SLong StartRadius = oldradius;
SLong EndRadius = radius;
DoPointStruc sphco;
const int shiftFactor = 8; //RJS 30Jun00
MaxRadius = StartRadius<<shiftFactor; //RJS 30Jun00
wXStart = WCylStartP->gx;
wYStart = WCylStartP->gy;
wZStart = WCylStartP->gz;
dopointRoot = dpfronttrans;
RelX = dpbacktrans.getPosX() - dpfronttrans.getPosX();
RelY = dpbacktrans.getPosY() - dpfronttrans.getPosY();
RelZ = dpbacktrans.getPosZ() - dpfronttrans.getPosZ();
if (traillength)
{
SLong avradius = (StartRadius + EndRadius)>>1;
avradius++;
// max depth...
depth = traillength / avradius;
depth <<= 7;
depth /= distance;
if (depth <= 0) depth = 1;
RadStep = ((EndRadius - StartRadius)<<shiftFactor)/depth; //RJS 30Jun00
wXStep = (WCylEndP->gx - wXStart) / depth;
wYStep = (WCylEndP->gy - wYStart) / depth;
wZStep = (WCylEndP->gz - wZStart) / depth;
if (vp) thetime = vp->TimeOfDay();
wXStart += thetime;
wYStart += thetime;
wZStart += thetime;
XoffGap = (xoff1 - xoff0)/depth;
YoffGap = (yoff1 - yoff0)/depth;
RelX /= depth;
RelY /= depth;
RelZ /= depth;
xDelta = xoff0;
yDelta = yoff0;
for (counter = 0; counter < depth; counter++)
{
RSeed = SHAPE.Noise(wXStart,wYStart,wZStart);
RandxDelta = RSeed*xDelta;
RandxDelta >>= 7;
RandxDelta -= xDelta;
RandxDelta >>= 2;
RandyDelta = RSeed*yDelta;
RandyDelta >>= 7;
RandyDelta -= yDelta;
RandyDelta >>= 2;
sphco = dopointRoot;
//DEADCODE JON 5/22/00 sphco.incPosX( RandxDelta );
//DEADCODE JON 5/22/00 sphco.incPosY( RandyDelta );
sphco.incPos( RandxDelta, RandyDelta, 0.0 );
RSeed -= 128;
RSeed = (RSeed<0)?-RSeed:RSeed;
RSeed = 128 - RSeed;
Radius = MaxRadius * RSeed;
Radius >>= 8;
Radius += (MaxRadius >> 1);
Radius >>= shiftFactor;
//Draw a sphere...
g_lpLib3d->DrawTransformedSphere(HMATERIAL(Image_Map.GetImageMapPtr(imapno)),sphco,Radius,ANGLES_0Deg,minix0,miniy0,maxix0,maxiy0);//RJS 20Mar00
//DEADCODE JON 5/22/00 dopointRoot.bodyx.f += RelX;
//DEADCODE JON 5/22/00 dopointRoot.bodyy.f += RelY;
//DEADCODE JON 5/22/00 dopointRoot.bodyz.f += RelZ;
dopointRoot.incPos( RelX, RelY, RelZ );
xDelta += XoffGap;
yDelta += YoffGap;
wXStart += wXStep;
wYStart += wYStep;
wZStart += wZStep;
MaxRadius += RadStep;
}
g_lpLib3d->SetGlobal(TOGGLE_GLOBALALPHA,SMOKED_OFF);
}
#endif
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure ParticleCylinderImapd
//Author Robert Slater
//Date Thu 4 Dec 1997
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void TrailInfo::ParticleCylinderImapd()
{
#ifndef _REDO_ME2_
DoPointStruc dopoint0,dopoint1,dopoint2,dopoint3,dopointRoot,dptmp1,dptmp2;
Bool oldcross;
Float RelX, RelY, RelZ;
UWord counter;
SLong xDelta,yDelta;
SLong RandxDelta,RandyDelta;
SLong xDeltCap,yDeltCap;
UWord RSeed;
SLong XoffGap;
SLong YoffGap;
SLong Radius, Radius3d;
ImageMapNumber imapno = (ImageMapNumber) imagemap0;
SWord maxx, maxy;
SLong MaxRadius = maxradius;
SWord HalfRadius = MaxRadius>>1;
SLong wXStep, wYStep, wZStep;
SLong wXStart, wYStart, wZStart;
SLong MaxDist, Dist;
SLong depth;
DoPointStruc sphco;
wXStart = WCylStartP->gx;
wYStart = WCylStartP->gy;
wZStart = WCylStartP->gz;
dopointRoot = dpfronttrans; //RJS 20Mar00
dopoint2 = dpbacktrans; //RJS 20Mar00
RelX = dopoint2.getPosX() - dopointRoot.getPosX();
RelY = dopoint2.getPosY() - dopointRoot.getPosY();
RelZ = dopoint2.getPosZ() - dopointRoot.getPosZ();
if (traillength)
{
Float fDepth;
depth = (traillength*pixpercyl) / HalfRadius;
depth >>= 15;
if (depth <= 0) depth = 1;
fDepth = 1. / Float(depth);
wXStep = (WCylEndP->gx - wXStart) / depth;
wYStep = (WCylEndP->gy - wYStart) / depth;
wZStep = (WCylEndP->gz - wZStart) / depth;
XoffGap = (xoff1 - xoff0)/depth;
YoffGap = (yoff1 - yoff0)/depth;
RelX *= fDepth;
RelY *= fDepth;
RelZ *= fDepth;
xDelta = xoff0;
yDelta = yoff0;
for (counter = 0; counter < depth; counter++)
{
xDeltCap = xDelta << 1;
yDeltCap = yDelta << 1;
RSeed = SHAPE.Noise(wXStart,wYStart,wZStart);
RandxDelta = RSeed * xDeltCap;
RandxDelta >>= 8;
RandxDelta -= xDelta;
RandyDelta = RSeed * yDeltCap;
RandyDelta >>= 8;
RandyDelta -= yDelta;
sphco = dopointRoot;
//DEADCODE JON 5/22/00 sphco.bodyx.f += RandxDelta;
//DEADCODE JON 5/22/00 sphco.bodyy.f += RandyDelta;
sphco.incPos( RandxDelta, RandyDelta, 0.0 ); //RJS 6Jun00
xDeltCap >>= 1;
yDeltCap >>= 1;
xDeltCap = (xDeltCap<0)?-xDeltCap:xDeltCap;
yDeltCap = (yDeltCap<0)?-yDeltCap:yDeltCap;
if (xDeltCap || yDeltCap)
{
if (xDeltCap > yDeltCap)
{
MaxDist = xDeltCap;
Dist = (RandxDelta<0)?-RandxDelta:RandxDelta;
}
else
{
MaxDist = yDeltCap;
Dist = (RandyDelta<0)?-RandyDelta:RandyDelta;
}
Dist = MaxDist - Dist;
Radius = 2 + ((Dist*MaxRadius)/MaxDist);
g_lpLib3d->SetGlobal(TOGGLE_GLOBALALPHA,(Radius*255)/MaxRadius);
g_lpLib3d->DrawTransformedSphere(HMATERIAL(Image_Map.GetImageMapPtr(imapno)),sphco,Radius,ANGLES_0Deg,minix0,miniy0,maxix0,maxiy0);
}
//DEADCODE JON 5/22/00 dopointRoot.bodyx.f += RelX;
//DEADCODE JON 5/22/00 dopointRoot.bodyy.f += RelY;
//DEADCODE JON 5/22/00 dopointRoot.bodyz.f += RelZ;
dopointRoot.incPos( RelX, RelY, RelZ );
xDelta += XoffGap;
yDelta += YoffGap;
wXStart += wXStep; //RJS 12Nov97
wYStart += wYStep; //RJS 12Nov97
wZStart += wZStep; //RJS 12Nov97
}
g_lpLib3d->SetGlobal(TOGGLE_GLOBALALPHA,SMOKED_OFF);
}
#endif
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure imaptrailcylWrapped
//Author Robert Slater
//Date Tue 17 Nov 1998
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void TrailInfo::imaptrailcylWrapped()
{
#ifndef _REDO_ME2_
ULong thewidth, theheight;
DoPointStruc dopoint0,dopoint1,dopoint2,dopoint3,oldpoint,sphco;
//DeadCode RJS 20Oct00 Float xdelt1 = (Float) xoff0;
//DeadCode RJS 20Oct00 Float ydelt1 = (Float) yoff0;
//DeadCode RJS 20Oct00 Float xdelt2 = (Float) xoff1;
//DeadCode RJS 20Oct00 Float ydelt2 = (Float) yoff1;
Bool oldcross;
SLong nopixels;
SLong dx,dy,dz;
Bool dosphere = FALSE;
Bool nocyl = FALSE;
ImageMapDescPtr imptr = Image_Map.GetImageMapPtr((ImageMapNumber)imagemap0);
minix0 = 0;
maxix0 = imptr->w;
dopoint0 = dopoint1 = dpfronttrans; //RJS 20Mar00
oldpoint = dopoint2 = dopoint3 = dpbacktrans; //RJS 20Mar00
if (traillength)
{
dx = dopoint0.getPosX() - dopoint2.getPosX();
dy = dopoint0.getPosY() - dopoint2.getPosY();
dz = dopoint0.getPosZ() - dopoint2.getPosZ();
// Assume 1 pixel is 8 cm...
nopixels = traillength >> 3;
nopixels = nopixels / maxix0;
if (nopixels)
maxix0 = maxix0 * nopixels;
if (visibility > 4) //4% visible
{
if (visibility < 75) //75%
dosphere = TRUE;
}
else
{
nocyl = TRUE;
dosphere = TRUE;
}
if (!nocyl)
g_lpLib3d->DrawTransformedCylinder(HMATERIAL(imptr),dpfronttrans,dpbacktrans,xoff0,yoff0,xoff1,yoff1,minix0,miniy0,maxix0,maxiy0);
if (dosphere && imagemap1)
{
//DeadCode RJS 20Oct00 SLong pooradius = 0.75*radius;
/* if (pooradius)
{
int nospheres = 1 + ((pixpercyl * visibility)>>8);
int i;
Float dxpoo,dypoo,dzpoo;
dxpoo = Float(dx);
dypoo = Float(dy);
dzpoo = Float(dz);
if (nospheres > 8)
nospheres = 8;
dxpoo /= nospheres;
dypoo /= nospheres;
dzpoo /= nospheres;
sphco = oldpoint;
for (i=0; i < nospheres; i++)
{
g_lpLib3d->DrawSphere(HMATERIAL(Image_Map.GetImageMapPtr((ImageMapNumber)imagemap1)),sphco,radius,ANGLES_0Deg,minix1,miniy1,maxix1,maxiy1);
sphco.bodyx.f += dxpoo;
sphco.bodyy.f += dypoo;
sphco.bodyz.f += dzpoo;
}
}*/
g_lpLib3d->DrawTransformedSphere(HMATERIAL(Image_Map.GetImageMapPtr((ImageMapNumber)imagemap1)),dpbacktrans,radius,ANGLES_0Deg,minix1,miniy1,maxix1,maxiy1);//RJS 20Mar00
}
}
else
{
if (imagemap1)
{
sphco = oldpoint;
//DEADCODE JON 5/22/00 sphco.bodyx.f = (dopoint0.bodyx.f + dopoint2.bodyx.f)/2;
//DEADCODE JON 5/22/00 sphco.bodyy.f = (dopoint0.bodyy.f + dopoint2.bodyy.f)/2;
//DEADCODE JON 5/22/00 sphco.bodyz.f = (dopoint0.bodyz.f + dopoint2.bodyz.f)/2;
// D3DVALUE tx, ty, tz;
// tx = ( dopoint0.getPosX() + dopoint2.getPosX() )/2;
// ty = ( dopoint0.getPosY() + dopoint2.getPosY() )/2;
// tz = ( dopoint0.getPosZ() + dopoint2.getPosZ() )/2;
sphco.setPosition(
( dopoint0.getPosX() + dopoint2.getPosX() )/2,//tx,
( dopoint0.getPosY() + dopoint2.getPosY() )/2,//ty,
( dopoint0.getPosZ() + dopoint2.getPosZ() )/2//tz
);
g_lpLib3d->DrawTransformedSphere(HMATERIAL(Image_Map.GetImageMapPtr((ImageMapNumber)imagemap1)),sphco,radius,ANGLES_0Deg,minix1,miniy1,maxix1,maxiy1);
}
}
#endif
}
Bool shape::ClipSphereRatio( DoPointStruc &dp0,
DoPointStruc &dp1,
DoPointStruc &dp2,
DoPointStruc &dp3,
SLong Radius,
SWord wx,
SWord wy,
bool ispivoted )
{
return FALSE;
/*
Bool Clipped = TRUE;
Float Radx = Float(Radius);
Float Rady;
SLong ratio = (wy << 16)/wx;
SLong rady;
rady = (Radius * ratio);
Radx *= SphereXScale;
if (ispivoted)
{
rady >>= 15;
Rady = Float(rady);
Rady *= SphereYScale;
//DeadCode RJS 26May99 if (vp->PolyPitEnabled() || (vp->viewnum.viewmode == VM_InsideCheat))
if (vp->roll) //RJS 26May99
{
SWord sinAng,cosAng;
SLong x0,x1,x2,x3;
SLong y0,y1,y2,y3;
SLong m[4];
SLong nx,ny;
SWord angle = vp->roll;
x0 = -Radx;
y0 = Rady;
x1 = Radx;
y1 = Rady;
x2 = Radx;
y2 = 0;
x3 = -Radx;
y3 = 0;
Math_Lib.high_sin_cos((Angles)angle,sinAng,cosAng);
m[0]=m[3]=SLong(cosAng);
m[1]=SLong(sinAng);
m[2]=-SLong(sinAng);
nx=(m[0]*x0)/ANGLES_FRACT+(m[1]*y0)/ANGLES_FRACT;
ny=(m[2]*x0)/ANGLES_FRACT+(m[3]*y0)/ANGLES_FRACT;
x0 = nx;
y0 = ny;
nx=(m[0]*x1)/ANGLES_FRACT+(m[1]*y1)/ANGLES_FRACT;
ny=(m[2]*x1)/ANGLES_FRACT+(m[3]*y1)/ANGLES_FRACT;
x1 = nx;
y1 = ny;
nx=(m[0]*x2)/ANGLES_FRACT+(m[1]*y2)/ANGLES_FRACT;
ny=(m[2]*x2)/ANGLES_FRACT+(m[3]*y2)/ANGLES_FRACT;
x2 = nx;
y2 = ny;
nx=(m[0]*x3)/ANGLES_FRACT+(m[1]*y3)/ANGLES_FRACT;
ny=(m[2]*x3)/ANGLES_FRACT+(m[3]*y3)/ANGLES_FRACT;
x3 = nx;
y3 = ny;
dp0.bodyx.f += Float(x0);
dp0.bodyy.f += Float(y0);
dp1.bodyx.f += Float(x1);
dp1.bodyy.f += Float(y1);
dp2.bodyx.f += Float(x2);
dp2.bodyy.f += Float(y2);
dp3.bodyx.f += Float(x3);
dp3.bodyy.f += Float(y3);
}
else
{
dp0.bodyx.f -= Radx;
dp0.bodyy.f += Rady;
dp1.bodyx.f += Radx;
dp1.bodyy.f += Rady;
dp2.bodyx.f += Radx;
dp3.bodyx.f -= Radx;
}
}
else
{
rady >>= 16;
Rady = Float(rady);
Rady *= SphereYScale;
dp0.bodyx.f -= Radx;
dp0.bodyy.f += Rady;
dp1.bodyx.f += Radx;
dp1.bodyy.f += Rady;
dp2.bodyx.f += Radx;
dp2.bodyy.f -= Rady;
dp3.bodyx.f -= Radx;
dp3.bodyy.f -= Rady;
}
_matrix.SetClipFlags(dp0);
_matrix.SetClipFlags(dp1);
_matrix.SetClipFlags(dp2);
_matrix.SetClipFlags(dp3);
andedFlags=CF3D_ALL;
andedFlags&=dp0.clipFlags;
andedFlags&=dp1.clipFlags;
andedFlags&=dp2.clipFlags;
andedFlags&=dp3.clipFlags;
if (andedFlags==0)
{
Clipped = FALSE;
if (!doingHW3D)
{
_matrix.body2screen(dp0);
_matrix.body2screen(dp1);
_matrix.body2screen(dp2);
_matrix.body2screen(dp3);
}
}
return(Clipped);
*/
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure DblParticleCylinderImapd
//Author Robert Slater
//Date Mon 20 Dec 1999
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void TrailInfo::DblParticleCylinderImapd()
{
#ifndef _REDO_ME2_
DoPointStruc dopoint2,dopointRoot;
Bool oldcross;
Float RelX, RelY, RelZ;
UWord counter;
SLong xDelta,yDelta;
SLong RandxDelta,RandyDelta;
SLong xDeltCap,yDeltCap;
UWord RSeed;
SLong XoffGap;
SLong YoffGap;
SLong Radius, Radius3d;
ImageMapNumber imapdefaultno = (ImageMapNumber) imagemap0;
ImageMapNumber imap2no = FIREFAD1NO;
ImageMapNumber imapno;
SWord maxx, maxy;
SWord HalfRadius = maxradius*.5;
SLong wXStep, wYStep, wZStep;
SLong wXStart, wYStart, wZStart;
SLong MaxDist, Dist;
SLong depth;
SWord minx = minix0;
SWord miny = miniy0;
DoPointStruc sphco;
maxx = maxix0;
maxy = maxiy0;
wXStart = WCylStartP->gx;
wYStart = WCylStartP->gy;
wZStart = WCylStartP->gz;
dopointRoot = dpfronttrans;
dopoint2 = dpbacktrans;
SLong subcounter;
SLong subincrement;
SLong subframe;
RelX = dopoint2.getPosX() - dopointRoot.getPosX();
RelY = dopoint2.getPosY() - dopointRoot.getPosY();
RelZ = dopoint2.getPosZ() - dopointRoot.getPosZ();
if (traillength)
{
SLong subdepth;
ImageMapDescPtr imptr = Image_Map.GetImageMapPtr(imap2no);
SLong nofx = imptr->w / maxix1;
SLong stepy,stepx;
SWord text_minx[17];
SWord text_miny[17];
SWord text_maxx[17];
SWord text_maxy[17];
for (int tmpframe=0; tmpframe < 16; tmpframe++)
{
stepy = tmpframe / nofx;
stepx = tmpframe - (stepy*nofx);
text_minx[tmpframe] = minix1 + (stepx*maxix1);
text_miny[tmpframe] = miniy1 + (stepy*maxiy1);
text_maxx[tmpframe] = text_minx[tmpframe] + maxix1;
text_maxy[tmpframe] = text_miny[tmpframe] + maxiy1;
}
text_minx[16] = minx;
text_miny[16] = miny;
text_maxx[16] = maxx;
text_maxy[16] = maxy;
depth = (traillength*pixpercyl) / HalfRadius;
depth >>= 15;
if (depth <= 0) depth = 1;
subdepth = depth/3;
if (flipped)
{
subcounter = depth;
subincrement = -1;
}
else
{
subcounter = 0;
subincrement = 1;
}
wXStep = (WCylEndP->gx - wXStart) / depth;
wYStep = (WCylEndP->gy - wYStart) / depth;
wZStep = (WCylEndP->gz - wZStart) / depth;
XoffGap = (xoff1 - xoff0)/depth;
YoffGap = (yoff1 - yoff0)/depth;
Float tmpdepth = 1. / Float(depth);
RelX *= tmpdepth;
RelY *= tmpdepth;
RelZ *= tmpdepth;
xDelta = xoff0;
yDelta = yoff0;
for (counter = 0; counter < depth; counter++)
{
xDeltCap = xDelta << 1;
yDeltCap = yDelta << 1;
RSeed = SHAPE.Noise(wXStart,wYStart,wZStart);
RandxDelta = RSeed * xDeltCap;
RandxDelta >>= 8;
RandxDelta -= xDelta;
RandyDelta = RSeed * yDeltCap;
RandyDelta >>= 8;
RandyDelta -= yDelta;
sphco = dopointRoot;
//DEADCODE JON 5/22/00 sphco.bodyx.f += RandxDelta;
//DEADCODE JON 5/22/00 sphco.bodyy.f += RandyDelta;
sphco.incPos( RandxDelta, RandyDelta, 0.0 );
xDeltCap >>= 1;
yDeltCap >>= 1;
xDeltCap = (xDeltCap<0)?-xDeltCap:xDeltCap;
yDeltCap = (yDeltCap<0)?-yDeltCap:yDeltCap;
if (xDeltCap || yDeltCap)
{
if (xDeltCap > yDeltCap)
{
MaxDist = xDeltCap;
Dist = (RandxDelta<0)?-RandxDelta:RandxDelta;
}
else
{
MaxDist = yDeltCap;
Dist = (RandyDelta<0)?-RandyDelta:RandyDelta;
}
Dist = MaxDist - Dist;
Radius = 2 + ((Dist*maxradius)/MaxDist);
imapno = imapdefaultno;
subframe = 16;
g_lpLib3d->SetGlobal(TOGGLE_GLOBALALPHA,(Radius*255)/maxradius);
if (subcounter < subdepth)
{
RSeed = 255 - RSeed;
RSeed *= subcounter;
RSeed /= subdepth;
if (RSeed < 32)
{
RSeed = SHAPE.Noise(wXStart+subcounter,wYStart+subcounter,wZStart+subcounter);
RSeed = (RSeed*2)>>8;
subframe = (12*subcounter)/subdepth;
subframe += RSeed;
imapno = imap2no;
}
}
g_lpLib3d->DrawTransformedSphere( HMATERIAL(Image_Map.GetImageMapPtr(imapno)),
sphco,
Radius,
ANGLES_0Deg,
text_minx[subframe],
text_miny[subframe],
text_maxx[subframe],
text_maxy[subframe] );
}
//DEADCODE JON 5/22/00 dopointRoot.bodyx.f += RelX;
//DEADCODE JON 5/22/00 dopointRoot.bodyy.f += RelY;
//DEADCODE JON 5/22/00 dopointRoot.bodyz.f += RelZ;
dopointRoot.incPos( RelX, RelY, RelZ );
xDelta += XoffGap;
yDelta += YoffGap;
wXStart += wXStep;
wYStart += wYStep;
wZStart += wZStep;
subcounter += subincrement;
}
g_lpLib3d->SetGlobal(TOGGLE_GLOBALALPHA,SMOKED_OFF);
}
#endif
}
//컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
//Procedure FadeParticleCylinderImapd
//Author Robert Slater
//Date Mon 20 Dec 1999
//
//Description
//
//Inputs
//
//Returns
//
//------------------------------------------------------------------------------
void TrailInfo::FadeParticleCylinderImapd()
{
#ifndef _REDO_ME2_
DoPointStruc sphco,dopoint2,dopointRoot;
Bool oldcross;
Float RelX, RelY, RelZ;
UWord counter;
SLong xDelta,yDelta;
SLong RandxDelta,RandyDelta;
SLong xDeltCap,yDeltCap;
UWord RSeed;
SLong XoffGap;
SLong YoffGap;
SLong Radius, Radius3d;
ImageMapNumber imapno = (ImageMapNumber)imagemap0;
SWord maxx, maxy;
SWord HalfRadius = maxradius*.5;
SLong wXStep, wYStep, wZStep;
SLong wXStart, wYStart, wZStart;
SLong MaxDist, Dist;
SLong depth;
wXStart = WCylStartP->gx;
wYStart = WCylStartP->gy;
wZStart = WCylStartP->gz;
dopointRoot = dpfronttrans;
dopoint2 = dpbacktrans;
SLong subcounter;
SLong subincrement;
RelX = dopoint2.getPosX() - dopointRoot.getPosX();
RelY = dopoint2.getPosY() - dopointRoot.getPosY();
RelZ = dopoint2.getPosZ() - dopointRoot.getPosZ();
if (traillength)
{
SLong realFade;
depth = (traillength*pixpercyl) / HalfRadius;
depth >>= 15;
if (depth <= 0) depth = 1;
if (flipped)
{
subcounter = depth;
subincrement = -1;
}
else
{
subcounter = 0;
subincrement = 1;
}
wXStep = (WCylEndP->gx - wXStart) / depth;
wYStep = (WCylEndP->gy - wYStart) / depth;
wZStep = (WCylEndP->gz - wZStart) / depth;
XoffGap = (xoff1 - xoff0)/depth;
YoffGap = (yoff1 - yoff0)/depth;
Float tmpdepth = 1. / Float(depth);
RelX *= tmpdepth;
RelY *= tmpdepth;
RelZ *= tmpdepth;
xDelta = xoff0;
yDelta = yoff0;
for (counter = 0; counter < depth; counter++)
{
xDeltCap = xDelta << 1;
yDeltCap = yDelta << 1;
RSeed = SHAPE.Noise(wXStart,wYStart,wZStart);
RandxDelta = RSeed * xDeltCap;
RandxDelta >>= 8;
RandxDelta -= xDelta;
RandyDelta = RSeed * yDeltCap;
RandyDelta >>= 8;
RandyDelta -= yDelta;
sphco = dopointRoot;
//DEADCODE JON 5/22/00 sphco.bodyx.f += RandxDelta;
//DEADCODE JON 5/22/00 sphco.bodyy.f += RandyDelta;
sphco.incPos( RandxDelta, RandyDelta, 0.0 );
xDeltCap >>= 1;
yDeltCap >>= 1;
xDeltCap = (xDeltCap<0)?-xDeltCap:xDeltCap;
yDeltCap = (yDeltCap<0)?-yDeltCap:yDeltCap;
if (xDeltCap || yDeltCap)
{
if (xDeltCap > yDeltCap)
{
MaxDist = xDeltCap;
Dist = (RandxDelta<0)?-RandxDelta:RandxDelta;
}
else
{
MaxDist = yDeltCap;
Dist = (RandyDelta<0)?-RandyDelta:RandyDelta;
}
Dist = MaxDist - Dist;
Radius = 2 + ((Dist*maxradius)/MaxDist);
realFade = (Radius*255)/maxradius;
realFade = (realFade*subcounter)/depth;
g_lpLib3d->SetGlobal(TOGGLE_GLOBALALPHA,realFade);
g_lpLib3d->DrawTransformedSphere( HMATERIAL(Image_Map.GetImageMapPtr(imapno)),
sphco,
Radius,
ANGLES_0Deg,
minix0,
miniy0,
maxix0,
maxiy0 );
}
//DEADCODE JON 5/22/00 dopointRoot.bodyx.f += RelX;
//DEADCODE JON 5/22/00 dopointRoot.bodyy.f += RelY;
//DEADCODE JON 5/22/00 dopointRoot.bodyz.f += RelZ;
dopointRoot.incPos( RelX, RelY, RelZ );
xDelta += XoffGap;
yDelta += YoffGap;
wXStart += wXStep;
wYStart += wYStep;
wZStart += wZStep;
subcounter += subincrement;
}
g_lpLib3d->SetGlobal(TOGGLE_GLOBALALPHA,SMOKED_OFF);
}
#endif
}
| [
"hhhh@hotmail.com"
] | hhhh@hotmail.com |
fa0aeea01f471b33638a24129b114de9d6e16a5c | 7283409830d1a8bc51ccfa755774ecebf65e10c8 | /src/blas_like/level3/Symm.cpp | 1e7f8781315667939507bcc332b64b7c74224f74 | [
"BSD-3-Clause"
] | permissive | tkelman/Elemental | 27ac59dabfea2dac03e8f108a10323197426946d | 7678cff392d08b2ecba80c3f8401071538e476f2 | refs/heads/master | 2021-01-21T03:33:40.466965 | 2014-11-27T03:56:16 | 2014-11-27T03:56:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,514 | cpp | /*
Copyright (c) 2009-2014, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"
#include "./Symm/LL.hpp"
#include "./Symm/LU.hpp"
#include "./Symm/RL.hpp"
#include "./Symm/RU.hpp"
namespace El {
template<typename T>
void Symm
( LeftOrRight side, UpperOrLower uplo,
T alpha, const Matrix<T>& A, const Matrix<T>& B, T beta, Matrix<T>& C,
bool conjugate )
{
DEBUG_ONLY(CallStackEntry cse("Symm"))
const char sideChar = LeftOrRightToChar( side );
const char uploChar = UpperOrLowerToChar( uplo );
if( conjugate )
{
blas::Hemm
( sideChar, uploChar, C.Height(), C.Width(),
alpha, A.LockedBuffer(), A.LDim(),
B.LockedBuffer(), B.LDim(),
beta, C.Buffer(), C.LDim() );
}
else
{
blas::Symm
( sideChar, uploChar, C.Height(), C.Width(),
alpha, A.LockedBuffer(), A.LDim(),
B.LockedBuffer(), B.LDim(),
beta, C.Buffer(), C.LDim() );
}
}
template<typename T>
void Symm
( LeftOrRight side, UpperOrLower uplo,
T alpha, const AbstractDistMatrix<T>& A, const AbstractDistMatrix<T>& B,
T beta, AbstractDistMatrix<T>& C, bool conjugate )
{
DEBUG_ONLY(CallStackEntry cse("Symm"))
if( side == LEFT && uplo == LOWER )
symm::LL( alpha, A, B, beta, C, conjugate );
else if( side == LEFT )
symm::LU( alpha, A, B, beta, C, conjugate );
else if( uplo == LOWER )
symm::RL( alpha, A, B, beta, C, conjugate );
else
symm::RU( alpha, A, B, beta, C, conjugate );
}
#define PROTO(T) \
template void Symm \
( LeftOrRight side, UpperOrLower uplo, \
T alpha, const Matrix<T>& A, const Matrix<T>& B, \
T beta, Matrix<T>& C, bool conjugate ); \
template void Symm \
( LeftOrRight side, UpperOrLower uplo, \
T alpha, const AbstractDistMatrix<T>& A, const AbstractDistMatrix<T>& B, \
T beta, AbstractDistMatrix<T>& C, bool conjugate ); \
template void symm::LocalAccumulateLL \
( Orientation orientation, T alpha, \
const DistMatrix<T>& A, \
const DistMatrix<T,MC, STAR>& B_MC_STAR, \
const DistMatrix<T,STAR,MR >& BTrans_STAR_MR, \
DistMatrix<T,MC, STAR>& Z_MC_STAR, \
DistMatrix<T,MR, STAR>& Z_MR_STAR ); \
template void symm::LocalAccumulateLU \
( Orientation orientation, T alpha, \
const DistMatrix<T>& A, \
const DistMatrix<T,MC, STAR>& B_MC_STAR, \
const DistMatrix<T,STAR,MR >& BTrans_STAR_MR, \
DistMatrix<T,MC, STAR>& Z_MC_STAR, \
DistMatrix<T,MR, STAR>& Z_MR_STAR ); \
template void symm::LocalAccumulateRL \
( Orientation orientation, T alpha, \
const DistMatrix<T>& A, \
const DistMatrix<T,STAR,MC >& B_STAR_MC, \
const DistMatrix<T,MR, STAR>& BTrans_MR_STAR, \
DistMatrix<T,MC, STAR>& ZTrans_MC_STAR, \
DistMatrix<T,MR, STAR>& ZTrans_MR_STAR ); \
template void symm::LocalAccumulateRU \
( Orientation orientation, T alpha, \
const DistMatrix<T,MC, MR >& A, \
const DistMatrix<T,STAR,MC >& B_STAR_MC, \
const DistMatrix<T,MR, STAR>& BTrans_MR_STAR, \
DistMatrix<T,MC, STAR>& ZTrans_MC_STAR, \
DistMatrix<T,MR, STAR>& ZTrans_MR_STAR );
#define EL_NO_INT_PROTO
#include "El/macros/Instantiate.h"
} // namespace El
| [
"jpoulson@cc.gatech.edu"
] | jpoulson@cc.gatech.edu |
413f6d6189e4e41e8ea5469fb7903615670ec460 | 5fe059e355ed475ea87b120f63b46045f5643a85 | /src/rpcwallet.cpp | ac9b37e144eabbb7762fad88c79e31960b46f4fe | [
"MIT"
] | permissive | Cloudxtreme/ddCash | 35067047a1544b996b9e414bdf6690888afd658f | 329ef5dcaacf9c0424c9a2f1ce605da5cd56f4d3 | refs/heads/master | 2020-04-23T18:13:41.707397 | 2018-11-29T15:21:46 | 2018-11-29T15:21:46 | 171,359,395 | 1 | 0 | null | 2019-02-18T21:34:47 | 2019-02-18T21:34:46 | null | UTF-8 | C++ | false | false | 131,426 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "core_io.h"
#include "init.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "wallet.h"
#include "walletdb.h"
#include <stdint.h>
#include "libzerocoin/Coin.h"
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include "spork.h"
#include <boost/assign/list_of.hpp>
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted() ? "\nRequires wallet passphrase to be set with walletpassphrase call." : "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked() || pwalletMain->fWalletUnlockAnonymizeOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain(false);
int confirmsTotal = GetIXConfirmations(wtx.GetHash()) + confirms;
entry.push_back(Pair("confirmations", confirmsTotal));
entry.push_back(Pair("bcconfirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms > 0) {
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
}
uint256 hash = wtx.GetHash();
entry.push_back(Pair("txid", hash.GetHex()));
Array conflicts;
BOOST_FOREACH (const uint256& conflict, wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.push_back(Pair("walletconflicts", conflicts));
entry.push_back(Pair("time", wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
BOOST_FOREACH (const PAIRTYPE(string, string) & item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress ( \"account\" )\n"
"\nReturns a new ddCash address for receiving payments.\n"
"If 'account' is specified (recommended), it is added to the address book \n"
"so payments received with the address will be credited to 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The account name for the address to be linked to. if not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
"\nResult:\n"
"\"ddcashaddress\" (string) The new ddcash address\n"
"\nExamples:\n" +
HelpExampleCli("getnewaddress", "") + HelpExampleCli("getnewaddress", "\"\"") + HelpExampleCli("getnewaddress", "\"myaccount\"") + HelpExampleRpc("getnewaddress", "\"myaccount\""));
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBook(keyID, strAccount, "receive");
return CBitcoinAddress(keyID).ToString();
}
Value makekeypair(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
key.MakeNewKey(false);
CPrivKey vchPrivKey = key.GetPrivKey();
Object result;
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey())));
CBitcoinSecret bkey(key);
result.push_back(Pair("PrivKeyBase58",bkey.ToString()));
return result;
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew = false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid()) {
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it) {
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH (const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) {
if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress \"account\"\n"
"\nReturns the current ddCash address for receiving payments to this account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
"\nResult:\n"
"\"ddcashaddress\" (string) The account ddcash address\n"
"\nExamples:\n" +
HelpExampleCli("getaccountaddress", "") + HelpExampleCli("getaccountaddress", "\"\"") + HelpExampleCli("getaccountaddress", "\"myaccount\"") + HelpExampleRpc("getaccountaddress", "\"myaccount\""));
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value getrawchangeaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawchangeaddress\n"
"\nReturns a new ddCash address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n"
"\nResult:\n"
"\"address\" (string) The address\n"
"\nExamples:\n" +
HelpExampleCli("getrawchangeaddress", "") + HelpExampleRpc("getrawchangeaddress", ""));
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
CReserveKey reservekey(pwalletMain);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetID();
return CBitcoinAddress(keyID).ToString();
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount \"ddcashaddress\" \"account\"\n"
"\nSets the account associated with the given address.\n"
"\nArguments:\n"
"1. \"ddcashaddress\" (string, required) The ddcash address to be associated with an account.\n"
"2. \"account\" (string, required) The account to assign the address to.\n"
"\nExamples:\n" +
HelpExampleCli("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"tabby\"") + HelpExampleRpc("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"tabby\""));
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ddCash address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Only add the account if the address is yours.
if (IsMine(*pwalletMain, address.Get())) {
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get())) {
string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
} else
throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount \"ddcashaddress\"\n"
"\nReturns the account associated with the given address.\n"
"\nArguments:\n"
"1. \"ddcashaddress\" (string, required) The ddcash address for account lookup.\n"
"\nResult:\n"
"\"accountname\" (string) the account address\n"
"\nExamples:\n" +
HelpExampleCli("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") + HelpExampleRpc("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\""));
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ddCash address");
string strAccount;
map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
strAccount = (*mi).second.name;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount \"account\"\n"
"\nReturns the list of addresses for the given account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name.\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"ddcashaddress\" (string) a ddcash address associated with the given account\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getaddressesbyaccount", "\"tabby\"") + HelpExampleRpc("getaddressesbyaccount", "\"tabby\""));
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH (const PAIRTYPE(CBitcoinAddress, CAddressBookData) & item, pwalletMain->mapAddressBook) {
const CBitcoinAddress& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, bool fUseIX = false)
{
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
string strError;
if (pwalletMain->IsLocked()) {
strError = "Error: Wallet locked, unable to create transaction!";
LogPrintf("SendMoney() : %s", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
// Parse ddCash address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
if (!pwalletMain->CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError, NULL, ALL_COINS, fUseIX, (CAmount)0)) {
if (nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
LogPrintf("SendMoney() : %s\n", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey, (!fUseIX ? "tx" : "ix")))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress \"ddcashaddress\" amount ( \"comment\" \"comment-to\" )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" +
HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"ddcashaddress\" (string, required) The ddcash address to send to.\n"
"2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n" +
HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1") + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleRpc("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\""));
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ddCash address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, wtx);
return wtx.GetHash().GetHex();
}
Value sendtoaddressix(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddressix \"ddcashaddress\" amount ( \"comment\" \"comment-to\" )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" +
HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"ddcashaddress\" (string, required) The ddcash address to send to.\n"
"2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n" +
HelpExampleCli("sendtoaddressix", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1") + HelpExampleCli("sendtoaddressix", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleRpc("sendtoaddressix", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\""));
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ddCash address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, wtx, true);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n"
"\nResult:\n"
"[\n"
" [\n"
" [\n"
" \"ddcashaddress\", (string) The ddcash address\n"
" amount, (numeric) The amount in btc\n"
" \"account\" (string, optional) The account\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listaddressgroupings", "") + HelpExampleRpc("listaddressgroupings", ""));
Array jsonGroupings;
map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH (set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) {
Array jsonGrouping;
BOOST_FOREACH (CTxDestination address, grouping) {
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage \"ddcashaddress\" \"message\"\n"
"\nSign a message with the private key of an address" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"ddcashaddress\" (string, required) The ddcash address to use for the private key.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n" +
HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n" + HelpExampleCli("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"my message\"") +
"\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"signature\" \"my message\"") +
"\nAs json rpc\n" + HelpExampleRpc("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"my message\""));
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress \"ddcashaddress\" ( minconf )\n"
"\nReturns the total amount received by the given ddcashaddress in transactions with at least minconf confirmations.\n"
"\nArguments:\n"
"1. \"ddcashaddress\" (string, required) The ddcash address for transactions.\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in btc received at this address.\n"
"\nExamples:\n"
"\nThe amount from transactions with at least 1 confirmation\n" +
HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") +
"\nThe amount including unconfirmed transactions, zero confirmations\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 6") +
"\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 6"));
// ddcash address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ddCash address");
CScript scriptPubKey = GetScriptForDestination(address.Get());
if (!IsMine(*pwalletMain, scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount \"account\" ( minconf )\n"
"\nReturns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in btc received for this account.\n"
"\nExamples:\n"
"\nAmount received by the default account with at least 1 confirmation\n" +
HelpExampleCli("getreceivedbyaccount", "\"\"") +
"\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
"\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6"));
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CAmount nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (!IsFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"getbalance ( \"account\" minconf includeWatchonly )\n"
"\nIf account is not specified, returns the server's total available balance (excluding zerocoins).\n"
"If account is specified, returns the balance in the account.\n"
"Note that the account \"\" is not the same as leaving the parameter out.\n"
"The server total may be different to the balance in the default \"\" account.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"amount (numeric) The total amount in btc received for this account.\n"
"\nExamples:\n"
"\nThe total amount in the server across all accounts\n" +
HelpExampleCli("getbalance", "") +
"\nThe total amount in the server across all accounts, with at least 5 confirmations\n" + HelpExampleCli("getbalance", "\"*\" 6") +
"\nThe total amount in the default account with at least 1 confirmation\n" + HelpExampleCli("getbalance", "\"\"") +
"\nThe total amount in the account named tabby with at least 6 confirmations\n" + HelpExampleCli("getbalance", "\"tabby\" 6") +
"\nAs a json rpc call\n" + HelpExampleRpc("getbalance", "\"tabby\", 6"));
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and "getbalance * 1 true" should return the same number
CAmount nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (!IsFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (wtx.GetDepthInMainChain() >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived)
nBalance += r.amount;
}
BOOST_FOREACH (const COutputEntry& s, listSent)
nBalance -= s.amount;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter);
return ValueFromAmount(nBalance);
}
Value getunconfirmedbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n");
return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
"\nMove a specified amount from one account in your wallet to another.\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
"2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
"3. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"4. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
"\nResult:\n"
"true|false (boolean) true if successfull.\n"
"\nExamples:\n"
"\nMove 0.01 btc from the default account to the account named tabby\n" +
HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
"\nMove 0.01 btc timotei to akiko with a comment and funds have 6 confirmations\n" + HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\""));
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
CAmount nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom \"fromaccount\" \"toddcashaddress\" amount ( minconf \"comment\" \"comment-to\" )\n"
"\nSent an amount from an account to a ddcash address.\n"
"The amount is a real and is rounded to the nearest 0.00000001." +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
"2. \"toddcashaddress\" (string, required) The ddcash address to send funds to.\n"
"3. amount (numeric, required) The amount in btc. (transaction fee is added on top).\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"6. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the transaction, \n"
" it is just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
"\nSend 0.01 btc from the default account to the address, must have at least 1 confirmation\n" +
HelpExampleCli("sendfrom", "\"\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01") +
"\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n" + HelpExampleCli("sendfrom", "\"tabby\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01 6 \"donation\" \"seans outpost\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("sendfrom", "\"tabby\", \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.01, 6, \"donation\", \"seans outpost\""));
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ddCash address");
CAmount nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
SendMoney(address.Get(), nAmount, wtx);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" )\n"
"\nSend multiple times. Amounts are double-precision floating point numbers." +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The account to send the funds from, can be \"\" for the default account\n"
"2. \"amounts\" (string, required) A json object with addresses and amounts\n"
" {\n"
" \"address\":amount (numeric) The ddcash address is the key, the numeric amount in btc is the value\n"
" ,...\n"
" }\n"
"3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
"4. \"comment\" (string, optional) A comment\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
"\nExamples:\n"
"\nSend two amounts to two different addresses:\n" +
HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n" + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\" 6 \"testing\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\", 6, \"testing\""));
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, CAmount> > vecSend;
CAmount totalAmount = 0;
BOOST_FOREACH (const Pair& s, sendTo) {
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid ddCash address: ") + s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + s.name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
CAmount nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
// Defined in rpcmisc.cpp
extern CScript _createmultisig_redeemScript(const Array& params);
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3) {
string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
"Each key is a ddCash address or hex-encoded public key.\n"
"If 'account' is specified, assign address to that account.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keysobject\" (string, required) A json array of ddcash addresses or hex-encoded public keys\n"
" [\n"
" \"address\" (string) ddcash address or hex-encoded public key\n"
" ...,\n"
" ]\n"
"3. \"account\" (string, optional) An account to assign the addresses to.\n"
"\nResult:\n"
"\"ddcashaddress\" (string) A ddcash address associated with the keys.\n"
"\nExamples:\n"
"\nAdd a multisig address from 2 addresses\n" +
HelpExampleCli("addmultisigaddress", "2 \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"") +
"\nAs json rpc call\n" + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"");
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBook(innerID, strAccount, "send");
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem {
CAmount nAmount;
int nConf;
int nBCConf;
vector<uint256> txids;
bool fIsWatchonly;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
nBCConf = std::numeric_limits<int>::max();
fIsWatchonly = false;
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain();
int nBCDepth = wtx.GetDepthInMainChain(false);
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
continue;
isminefilter mine = IsMine(*pwalletMain, address);
if (!(mine & filter))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.nBCConf = min(item.nBCConf, nBCDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true;
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH (const PAIRTYPE(CBitcoinAddress, CAddressBookData) & item, pwalletMain->mapAddressBook) {
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second.name;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
CAmount nAmount = 0;
int nConf = std::numeric_limits<int>::max();
int nBCConf = std::numeric_limits<int>::max();
bool fIsWatchonly = false;
if (it != mapTally.end()) {
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
nBCConf = (*it).second.nBCConf;
fIsWatchonly = (*it).second.fIsWatchonly;
}
if (fByAccounts) {
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
item.nBCConf = min(item.nBCConf, nBCConf);
item.fIsWatchonly = fIsWatchonly;
} else {
Object obj;
if (fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
Array transactions;
if (it != mapTally.end()) {
BOOST_FOREACH (const uint256& item, (*it).second.txids) {
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts) {
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) {
CAmount nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
int nBCConf = (*it).second.nBCConf;
Object obj;
if ((*it).second.fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaddress ( minconf includeempty includeWatchonly)\n"
"\nList balances by receiving address.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (numeric, optional, default=false) Whether to include addresses that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : \"true\", (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
" \"account\" : \"accountname\", (string) The account of the receiving address. The default account is \"\".\n"
" \"amount\" : x.xxx, (numeric) The total amount in btc received by the address\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listreceivedbyaddress", "") + HelpExampleCli("listreceivedbyaddress", "6 true") + HelpExampleRpc("listreceivedbyaddress", "6, true, true"));
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaccount ( minconf includeempty includeWatchonly)\n"
"\nList balances by account.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (boolean, optional, default=false) Whether to include accounts that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : \"true\", (bool) Only returned if imported addresses were involved in transaction\n"
" \"account\" : \"accountname\", (string) The account name of the receiving account\n"
" \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listreceivedbyaccount", "") + HelpExampleCli("listreceivedbyaccount", "6 true") + HelpExampleRpc("listreceivedbyaccount", "6, true, true"));
return ListReceived(params, true);
}
static void MaybePushAddress(Object& entry, const CTxDestination& dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret, const isminefilter& filter)
{
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
bool fAllAccounts = (strAccount == string("*"));
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) {
BOOST_FOREACH (const COutputEntry& s, listSent) {
Object entry;
if (involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.destination);
std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("DS");
entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "darksent" : "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
entry.push_back(Pair("vout", s.vout));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived) {
string account;
if (pwalletMain->mapAddressBook.count(r.destination))
account = pwalletMain->mapAddressBook[r.destination].name;
if (fAllAccounts || (account == strAccount)) {
Object entry;
if (involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.destination);
if (wtx.IsCoinBase()) {
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
} else {
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
entry.push_back(Pair("vout", r.vout));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount) {
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 4)
throw runtime_error(
"listtransactions ( \"account\" count from includeWatchonly)\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The account name. If not included, it will list all transactions for all accounts.\n"
" If \"\" is set, it will list transactions for the default account.\n"
"2. count (numeric, optional, default=10) The number of transactions to return\n"
"3. from (numeric, optional, default=0) The number of transactions to skip\n"
"4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"[\n"
" {\n"
" \"account\":\"accountname\", (string) The account name associated with the transaction. \n"
" It will be \"\" for the default account.\n"
" \"address\":\"ddcashaddress\", (string) The ddcash address of the transaction. Not present for \n"
" move transactions (category = move).\n"
" \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
" transaction between accounts, and not associated with an address,\n"
" transaction id or block. 'send' and 'receive' transactions are \n"
" associated with an address, transaction id and block details\n"
" \"amount\": x.xxx, (numeric) The amount in btc. This is negative for the 'send' category, and for the\n"
" 'move' category for moves outbound. It is positive for the 'receive' category,\n"
" and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in btc. This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions.\n"
" \"bcconfirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send'\n"
" and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blockindex\": n, (numeric) The block index containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
" for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n"
" from (for receiving funds, positive amounts), or went to (for sending funds,\n"
" negative amounts).\n"
" }\n"
"]\n"
"\nExamples:\n"
"\nList the most recent 10 transactions in the systems\n" +
HelpExampleCli("listtransactions", "") +
"\nList the most recent 10 transactions for the tabby account\n" + HelpExampleCli("listtransactions", "\"tabby\"") +
"\nList transactions 100 to 120 from the tabby account\n" + HelpExampleCli("listtransactions", "\"tabby\" 20 100") +
"\nAs a json rpc call\n" + HelpExampleRpc("listtransactions", "\"tabby\", 20, 100"));
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 3)
if (params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret, filter);
CAccountingEntry* const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount + nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom + nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listaccounts ( minconf includeWatchonly)\n"
"\nReturns Object that has account names as keys, account balances as values.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
"2. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"{ (json object where keys are account names, and values are numeric balances\n"
" \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n"
" ...\n"
"}\n"
"\nExamples:\n"
"\nList account balances where there at least 1 confirmation\n" +
HelpExampleCli("listaccounts", "") +
"\nList account balances including zero confirmation transactions\n" + HelpExampleCli("listaccounts", "0") +
"\nList account balances for 6 or more confirmations\n" + HelpExampleCli("listaccounts", "6") +
"\nAs json rpc call\n" + HelpExampleRpc("listaccounts", "6"));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
isminefilter includeWatchonly = ISMINE_SPENDABLE;
if (params.size() > 1)
if (params[1].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
map<string, CAmount> mapAccountBalances;
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me
mapAccountBalances[entry.second.name] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
int nDepth = wtx.GetDepthInMainChain();
if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH (const COutputEntry& s, listSent)
mapAccountBalances[strSentAccount] -= s.amount;
if (nDepth >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.destination))
mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount;
else
mapAccountBalances[""] += r.amount;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH (const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH (const PAIRTYPE(string, CAmount) & accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n"
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
"\nArguments:\n"
"1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
"2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n"
"3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')"
"\nResult:\n"
"{\n"
" \"transactions\": [\n"
" \"account\":\"accountname\", (string) The account name associated with the transaction. Will be \"\" for the default account.\n"
" \"address\":\"ddcashaddress\", (string) The ddcash address of the transaction. Not present for move transactions (category = move).\n"
" \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
" \"amount\": x.xxx, (numeric) The amount in btc. This is negative for the 'send' category, and for the 'move' category for moves \n"
" outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in btc. This is negative and only available for the 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockindex\": n, (numeric) The block index containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("listsinceblock", "") + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6") + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6"));
CBlockIndex* pindex = NULL;
int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 0) {
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
BlockMap::iterator it = mapBlockIndex.find(blockId);
if (it != mapBlockIndex.end())
pindex = it->second;
}
if (params.size() > 1) {
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) {
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain(false) < depth)
ListTransactions(tx, "*", 0, true, transactions, filter);
}
CBlockIndex* pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : 0;
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"gettransaction \"txid\" ( includeWatchonly )\n"
"\nGet detailed information about in-wallet transaction <txid>\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n"
"\nResult:\n"
"{\n"
" \"amount\" : x.xxx, (numeric) The transaction amount in btc\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations\n"
" \"blockhash\" : \"hash\", (string) The block hash\n"
" \"blockindex\" : xx, (numeric) The block index\n"
" \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"txid\" : \"transactionid\", (string) The transaction id.\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
" \"details\" : [\n"
" {\n"
" \"account\" : \"accountname\", (string) The account name involved in the transaction, can be \"\" for the default account.\n"
" \"address\" : \"ddcashaddress\", (string) The ddcash address involved in the transaction\n"
" \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
" \"amount\" : x.xxx (numeric) The amount in btc\n"
" \"vout\" : n, (numeric) the vout value\n"
" }\n"
" ,...\n"
" ],\n"
" \"hex\" : \"data\" (string) Raw data for transaction\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true") + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\""));
uint256 hash;
hash.SetHex(params[0].get_str());
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 1)
if (params[1].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
CAmount nCredit = wtx.GetCredit(filter);
CAmount nDebit = wtx.GetDebit(filter);
CAmount nNet = nCredit - nDebit;
CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe(filter))
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details));
string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
entry.push_back(Pair("hex", strHex));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet \"destination\"\n"
"\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
"\nArguments:\n"
"1. \"destination\" (string) The destination directory or file\n"
"\nExamples:\n" +
HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\""));
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill ( newsize )\n"
"\nFills the keypool." +
HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. newsize (numeric, optional, default=100) The new keypool size\n"
"\nExamples:\n" +
HelpExampleCli("keypoolrefill", "") + HelpExampleRpc("keypoolrefill", ""));
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
kpSize = (unsigned int)params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(kpSize);
if (pwalletMain->GetKeyPoolSize() < kpSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->fWalletUnlockAnonymizeOnly = false;
pWallet->Lock();
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase \"passphrase\" timeout ( anonymizeonly )\n"
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending ddCashs\n"
"\nArguments:\n"
"1. \"passphrase\" (string, required) The wallet passphrase\n"
"2. timeout (numeric, required) The time to keep the decryption key in seconds.\n"
"3. anonymizeonly (boolean, optional, default=flase) If is true sending functions are disabled."
"\nNote:\n"
"Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
"time that overrides the old one. A timeout of \"0\" unlocks until the wallet is closed.\n"
"\nExamples:\n"
"\nUnlock the wallet for 60 seconds\n" +
HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
"\nUnlock the wallet for 60 seconds but allow Obfuscation only\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") +
"\nLock the wallet again (before 60 seconds)\n" + HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n" + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60"));
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
bool anonymizeOnly = false;
if (params.size() == 3)
anonymizeOnly = params[2].get_bool();
if (!pwalletMain->IsLocked() && pwalletMain->fWalletUnlockAnonymizeOnly && anonymizeOnly)
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked.");
if (!pwalletMain->Unlock(strWalletPass, anonymizeOnly))
throw JSONRPCError(RPC_WALLET_PASSddCashASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
pwalletMain->TopUpKeyPool();
int64_t nSleepTime = params[1].get_int64();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
if (nSleepTime > 0) {
nWalletUnlockTime = GetTime () + nSleepTime;
RPCRunLater ("lockwallet", boost::bind (LockWallet, pwalletMain), nSleepTime);
}
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
"\nArguments:\n"
"1. \"oldpassphrase\" (string) The current passphrase\n"
"2. \"newpassphrase\" (string) The new passphrase\n"
"\nExamples:\n" +
HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"") + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\""));
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSddCashASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.\n"
"\nExamples:\n"
"\nSet the passphrase for 2 minutes to perform a transaction\n" +
HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
"\nPerform a send (requires passphrase set)\n" + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 1.0") +
"\nClear the passphrase since we are done before 2 minutes is up\n" + HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n" + HelpExampleRpc("walletlock", ""));
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet \"passphrase\"\n"
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior the making these calls.\n"
"Use the walletpassphrase call for this, and then walletlock call.\n"
"If the wallet is already encrypted, use the walletpassphrasechange call.\n"
"Note that this will shutdown the server.\n"
"\nArguments:\n"
"1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
"\nExamples:\n"
"\nEncrypt you wallet\n" +
HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
"\nNow set the passphrase to use the wallet, such as for signing or sending ddCashs\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
"\nNow we can so something like sign\n" + HelpExampleCli("signmessage", "\"ddcashaddress\" \"test message\"") +
"\nNow lock the wallet again by removing the passphrase\n" + HelpExampleCli("walletlock", "") +
"\nAs a json rpc call\n" + HelpExampleRpc("encryptwallet", "\"my pass phrase\""));
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; ddcash server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
Value lockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n"
"\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending ddCashs.\n"
"Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
"is always cleared (by virtue of process exit) when a node stops or fails.\n"
"Also see the listunspent call\n"
"\nArguments:\n"
"1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
"2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n"
" [ (json array of json objects)\n"
" {\n"
" \"txid\":\"id\", (string) The transaction id\n"
" \"vout\": n (numeric) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"true|false (boolean) Whether the command was successful or not\n"
"\nExamples:\n"
"\nList the unspent transactions\n" +
HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\""));
if (params.size() == 1)
RPCTypeCheck(params, list_of(bool_type));
else
RPCTypeCheck(params, list_of(bool_type)(array_type));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
Array outputs = params[1].get_array();
BOOST_FOREACH (Value& output, outputs) {
if (output.type() != obj_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const Object& o = output.get_obj();
RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
Value listlockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id locked\n"
" \"vout\" : n (numeric) The vout value\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
"\nList the unspent transactions\n" +
HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("listlockunspent", ""));
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
Array ret;
BOOST_FOREACH (COutPoint& outpt, vOutpts) {
Object o;
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee amount\n"
"\nSet the transaction fee per kB.\n"
"\nArguments:\n"
"1. amount (numeric, required) The transaction fee in ddCash/kB rounded to the nearest 0.00000001\n"
"\nResult\n"
"true|false (boolean) Returns true if successful\n"
"\nExamples:\n" +
HelpExampleCli("settxfee", "0.00001") + HelpExampleRpc("settxfee", "0.00001"));
// Amount
CAmount nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
payTxFee = CFeeRate(nAmount, 1000);
return true;
}
Value getwalletinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getwalletinfo\n"
"Returns an object containing various wallet state info.\n"
"\nResult:\n"
"{\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total ddCash balance of the wallet\n"
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getwalletinfo", "") + HelpExampleRpc("getwalletinfo", ""));
Object obj;
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size()));
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
return obj;
}
// ppcoin: reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance ( reserve amount )\n"
"\nShow or set the reserve amount not participating in network protection\n"
"If no parameters provided current setting is printed.\n"
"\nArguments:\n"
"1. reserve (boolean, optional) is true or false to turn balance reserve on or off.\n"
"2. amount (numeric, optional) is a real and rounded to cent.\n"
"\nResult:\n"
"{\n"
" \"reserve\": true|false, (boolean) Status of the reserve balance\n"
" \"amount\": x.xxxx (numeric) Amount reserved\n"
"\nExamples:\n" +
HelpExampleCli("reservebalance", "true 5000") + HelpExampleRpc("reservebalance", "true 5000"));
if (params.size() > 0) {
bool fReserve = params[0].get_bool();
if (fReserve) {
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
CAmount nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
nReserveBalance = nAmount;
} else {
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
nReserveBalance = 0;
}
}
Object result;
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// presstab HyperStake
Value setstakesplitthreshold(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"setstakesplitthreshold value\n"
"\nThis will set the output size of your stakes to never be below this number\n"
"\nArguments:\n"
"1. value (numeric, required) Threshold value between 1 and 999999\n"
"\nResult:\n"
"{\n"
" \"threshold\": n, (numeric) Threshold value set\n"
" \"saved\": true|false (boolean) 'true' if successfully saved to the wallet file\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("setstakesplitthreshold", "5000") + HelpExampleRpc("setstakesplitthreshold", "5000"));
uint64_t nStakeSplitThreshold = params[0].get_int();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Unlock wallet to use this feature");
if (nStakeSplitThreshold > 999999)
throw runtime_error("Value out of range, max allowed is 999999");
CWalletDB walletdb(pwalletMain->strWalletFile);
LOCK(pwalletMain->cs_wallet);
{
bool fFileBacked = pwalletMain->fFileBacked;
Object result;
pwalletMain->nStakeSplitThreshold = nStakeSplitThreshold;
result.push_back(Pair("threshold", int(pwalletMain->nStakeSplitThreshold)));
if (fFileBacked) {
walletdb.WriteStakeSplitThreshold(nStakeSplitThreshold);
result.push_back(Pair("saved", "true"));
} else
result.push_back(Pair("saved", "false"));
return result;
}
}
// presstab HyperStake
Value getstakesplitthreshold(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakesplitthreshold\n"
"Returns the threshold for stake splitting\n"
"\nResult:\n"
"n (numeric) Threshold value\n"
"\nExamples:\n" +
HelpExampleCli("getstakesplitthreshold", "") + HelpExampleRpc("getstakesplitthreshold", ""));
return int(pwalletMain->nStakeSplitThreshold);
// return int(mnodeman.CountEnabled());
}
Value autocombinerewards(const Array& params, bool fHelp)
{
bool fEnable;
if (params.size() >= 1)
fEnable = params[0].get_bool();
if (fHelp || params.size() < 1 || (fEnable && params.size() != 2) || params.size() > 2)
throw runtime_error(
"autocombinerewards true|false ( threshold )\n"
"\nWallet will automatically monitor for any coins with value below the threshold amount, and combine them if they reside with the same ddCash address\n"
"When autocombinerewards runs it will create a transaction, and therefore will be subject to transaction fees.\n"
"\nArguments:\n"
"1. true|false (boolean, required) Enable auto combine (true) or disable (false)\n"
"2. threshold (numeric, optional) Threshold amount (default: 0)\n"
"\nExamples:\n" +
HelpExampleCli("autocombinerewards", "true 500") + HelpExampleRpc("autocombinerewards", "true 500"));
CWalletDB walletdb(pwalletMain->strWalletFile);
CAmount nThreshold = 0;
if (fEnable)
nThreshold = params[1].get_int();
pwalletMain->fCombineDust = fEnable;
pwalletMain->nAutoCombineThreshold = nThreshold;
if (!walletdb.WriteAutoCombineSettings(fEnable, nThreshold))
throw runtime_error("Changed settings in wallet but failed to save to database\n");
return Value::null;
}
Array printMultiSend()
{
Array ret;
Object act;
act.push_back(Pair("MultiSendStake Activated?", pwalletMain->fMultiSendStake));
act.push_back(Pair("MultiSendMasternode Activated?", pwalletMain->fMultiSendMasternodeReward));
ret.push_back(act);
if (pwalletMain->vDisabledAddresses.size() >= 1) {
Object disAdd;
for (unsigned int i = 0; i < pwalletMain->vDisabledAddresses.size(); i++) {
disAdd.push_back(Pair("Disabled From Sending", pwalletMain->vDisabledAddresses[i]));
}
ret.push_back(disAdd);
}
ret.push_back("MultiSend Addresses to Send To:");
Object vMS;
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++) {
vMS.push_back(Pair("Address " + boost::lexical_cast<std::string>(i), pwalletMain->vMultiSend[i].first));
vMS.push_back(Pair("Percent", pwalletMain->vMultiSend[i].second));
}
ret.push_back(vMS);
return ret;
}
Array printAddresses()
{
std::vector<COutput> vCoins;
pwalletMain->AvailableCoins(vCoins);
std::map<std::string, double> mapAddresses;
BOOST_FOREACH (const COutput& out, vCoins) {
CTxDestination utxoAddress;
ExtractDestination(out.tx->vout[out.i].scriptPubKey, utxoAddress);
std::string strAdd = CBitcoinAddress(utxoAddress).ToString();
if (mapAddresses.find(strAdd) == mapAddresses.end()) //if strAdd is not already part of the map
mapAddresses[strAdd] = (double)out.tx->vout[out.i].nValue / (double)COIN;
else
mapAddresses[strAdd] += (double)out.tx->vout[out.i].nValue / (double)COIN;
}
Array ret;
for (map<std::string, double>::const_iterator it = mapAddresses.begin(); it != mapAddresses.end(); ++it) {
Object obj;
const std::string* strAdd = &(*it).first;
const double* nBalance = &(*it).second;
obj.push_back(Pair("Address ", *strAdd));
obj.push_back(Pair("Balance ", *nBalance));
ret.push_back(obj);
}
return ret;
}
unsigned int sumMultiSend()
{
unsigned int sum = 0;
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++)
sum += pwalletMain->vMultiSend[i].second;
return sum;
}
Value multisend(const Array& params, bool fHelp)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
bool fFileBacked;
//MultiSend Commands
if (params.size() == 1) {
string strCommand = params[0].get_str();
Object ret;
if (strCommand == "print") {
return printMultiSend();
} else if (strCommand == "printaddress" || strCommand == "printaddresses") {
return printAddresses();
} else if (strCommand == "clear") {
LOCK(pwalletMain->cs_wallet);
{
bool erased = false;
if (pwalletMain->fFileBacked) {
if (walletdb.EraseMultiSend(pwalletMain->vMultiSend))
erased = true;
}
pwalletMain->vMultiSend.clear();
pwalletMain->setMultiSendDisabled();
Object obj;
obj.push_back(Pair("Erased from database", erased));
obj.push_back(Pair("Erased from RAM", true));
return obj;
}
} else if (strCommand == "enablestake" || strCommand == "activatestake") {
if (pwalletMain->vMultiSend.size() < 1)
throw JSONRPCError(RPC_INVALID_REQUEST, "Unable to activate MultiSend, check MultiSend vector");
if (CBitcoinAddress(pwalletMain->vMultiSend[0].first).IsValid()) {
pwalletMain->fMultiSendStake = true;
if (!walletdb.WriteMSettings(true, pwalletMain->fMultiSendMasternodeReward, pwalletMain->nLastMultiSendHeight)) {
Object obj;
obj.push_back(Pair("error", "MultiSend activated but writing settings to DB failed"));
Array arr;
arr.push_back(obj);
arr.push_back(printMultiSend());
return arr;
} else
return printMultiSend();
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to activate MultiSend, check MultiSend vector");
} else if (strCommand == "enablemasternode" || strCommand == "activatemasternode") {
if (pwalletMain->vMultiSend.size() < 1)
throw JSONRPCError(RPC_INVALID_REQUEST, "Unable to activate MultiSend, check MultiSend vector");
if (CBitcoinAddress(pwalletMain->vMultiSend[0].first).IsValid()) {
pwalletMain->fMultiSendMasternodeReward = true;
if (!walletdb.WriteMSettings(pwalletMain->fMultiSendStake, true, pwalletMain->nLastMultiSendHeight)) {
Object obj;
obj.push_back(Pair("error", "MultiSend activated but writing settings to DB failed"));
Array arr;
arr.push_back(obj);
arr.push_back(printMultiSend());
return arr;
} else
return printMultiSend();
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to activate MultiSend, check MultiSend vector");
} else if (strCommand == "disable" || strCommand == "deactivate") {
pwalletMain->setMultiSendDisabled();
if (!walletdb.WriteMSettings(false, false, pwalletMain->nLastMultiSendHeight))
throw JSONRPCError(RPC_DATABASE_ERROR, "MultiSend deactivated but writing settings to DB failed");
return printMultiSend();
} else if (strCommand == "enableall") {
if (!walletdb.EraseMSDisabledAddresses(pwalletMain->vDisabledAddresses))
return "failed to clear old vector from walletDB";
else {
pwalletMain->vDisabledAddresses.clear();
return printMultiSend();
}
}
}
if (params.size() == 2 && params[0].get_str() == "delete") {
int del = boost::lexical_cast<int>(params[1].get_str());
if (!walletdb.EraseMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "failed to delete old MultiSend vector from database");
pwalletMain->vMultiSend.erase(pwalletMain->vMultiSend.begin() + del);
if (!walletdb.WriteMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "walletdb WriteMultiSend failed!");
return printMultiSend();
}
if (params.size() == 2 && params[0].get_str() == "disable") {
std::string disAddress = params[1].get_str();
if (!CBitcoinAddress(disAddress).IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "address you want to disable is not valid");
else {
pwalletMain->vDisabledAddresses.push_back(disAddress);
if (!walletdb.EraseMSDisabledAddresses(pwalletMain->vDisabledAddresses))
throw JSONRPCError(RPC_DATABASE_ERROR, "disabled address from sending, but failed to clear old vector from walletDB");
if (!walletdb.WriteMSDisabledAddresses(pwalletMain->vDisabledAddresses))
throw JSONRPCError(RPC_DATABASE_ERROR, "disabled address from sending, but failed to store it to walletDB");
else
return printMultiSend();
}
}
//if no commands are used
if (fHelp || params.size() != 2)
throw runtime_error(
"multisend <command>\n"
"****************************************************************\n"
"WHAT IS MULTISEND?\n"
"MultiSend allows a user to automatically send a percent of their stake reward to as many addresses as you would like\n"
"The MultiSend transaction is sent when the staked coins mature (100 confirmations)\n"
"****************************************************************\n"
"TO CREATE OR ADD TO THE MULTISEND VECTOR:\n"
"multisend <ddCash Address> <percent>\n"
"This will add a new address to the MultiSend vector\n"
"Percent is a whole number 1 to 100.\n"
"****************************************************************\n"
"MULTISEND COMMANDS (usage: multisend <command>)\n"
" print - displays the current MultiSend vector \n"
" clear - deletes the current MultiSend vector \n"
" enablestake/activatestake - activates the current MultiSend vector to be activated on stake rewards\n"
" enablemasternode/activatemasternode - activates the current MultiSend vector to be activated on masternode rewards\n"
" disable/deactivate - disables the current MultiSend vector \n"
" delete <Address #> - deletes an address from the MultiSend vector \n"
" disable <address> - prevents a specific address from sending MultiSend transactions\n"
" enableall - enables all addresses to be eligible to send MultiSend transactions\n"
"****************************************************************\n");
//if the user is entering a new MultiSend item
string strAddress = params[0].get_str();
CBitcoinAddress address(strAddress);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ddCash address");
if (boost::lexical_cast<int>(params[1].get_str()) < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid percentage");
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
unsigned int nPercent = boost::lexical_cast<unsigned int>(params[1].get_str());
LOCK(pwalletMain->cs_wallet);
{
fFileBacked = pwalletMain->fFileBacked;
//Error if 0 is entered
if (nPercent == 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Sending 0% of stake is not valid");
}
//MultiSend can only send 100% of your stake
if (nPercent + sumMultiSend() > 100)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Failed to add to MultiSend vector, the sum of your MultiSend is greater than 100%");
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++) {
if (pwalletMain->vMultiSend[i].first == strAddress)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Failed to add to MultiSend vector, cannot use the same address twice");
}
if (fFileBacked)
walletdb.EraseMultiSend(pwalletMain->vMultiSend);
std::pair<std::string, int> newMultiSend;
newMultiSend.first = strAddress;
newMultiSend.second = nPercent;
pwalletMain->vMultiSend.push_back(newMultiSend);
if (fFileBacked) {
if (!walletdb.WriteMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "walletdb WriteMultiSend failed!");
}
}
return printMultiSend();
}
Value getzerocoinbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getzerocoinbalance\n"
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
return ValueFromAmount(pwalletMain->GetZerocoinBalance(true));
}
Value listmintedzerocoins(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"listmintedzerocoins\n"
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CZerocoinMint> listPubCoin = walletdb.ListMintedCoins(true, false, true);
Array jsonList;
for (const CZerocoinMint& pubCoinItem : listPubCoin) {
jsonList.push_back(pubCoinItem.GetValue().GetHex());
}
return jsonList;
}
Value listzerocoinamounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"listzerocoinamounts\n"
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CZerocoinMint> listPubCoin = walletdb.ListMintedCoins(true, true, true);
std::map<libzerocoin::CoinDenomination, CAmount> spread;
for (const auto& denom : libzerocoin::zerocoinDenomList)
spread.insert(std::pair<libzerocoin::CoinDenomination, CAmount>(denom, 0));
for (auto& mint : listPubCoin) spread.at(mint.GetDenomination())++;
Array jsonList;
Object val;
for (const auto& m : libzerocoin::zerocoinDenomList) {
stringstream s1;
s1 << "Denomination Value " << libzerocoin::ZerocoinDenominationToInt(m);
stringstream s2;
s2 << spread.at(m) << " coins";
val.push_back(Pair(s1.str(),s2.str()));
}
jsonList.push_back(val);
return jsonList;
}
Value listspentzerocoins(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"listspentzerocoins\n"
+ HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CBigNum> listPubCoin = walletdb.ListSpentCoinsSerial();
Array jsonList;
for (const CBigNum& pubCoinItem : listPubCoin) {
jsonList.push_back(pubCoinItem.GetHex());
}
return jsonList;
}
Value mintzerocoin(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"mintzerocoin <amount>\n"
"Usage: Enter an amount of ddCash to convert to zddCash"
+ HelpRequiringPassphrase());
int64_t nTime = GetTimeMillis();
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE))
throw JSONRPCError(RPC_WALLET_ERROR, "zddCash is currently disabled due to maintenance.");
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
CAmount nAmount = params[0].get_int() * COIN;
CWalletTx wtx;
vector<CZerocoinMint> vMints;
string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
Array arrMints;
for (CZerocoinMint mint : vMints) {
Object m;
m.push_back(Pair("txid", wtx.GetHash().ToString()));
m.push_back(Pair("value", ValueFromAmount(libzerocoin::ZerocoinDenominationToAmount(mint.GetDenomination()))));
m.push_back(Pair("pubcoin", mint.GetValue().GetHex()));
m.push_back(Pair("randomness", mint.GetRandomness().GetHex()));
m.push_back(Pair("serial", mint.GetSerialNumber().GetHex()));
m.push_back(Pair("time", GetTimeMillis() - nTime));
arrMints.push_back(m);
}
return arrMints;
}
Value spendzerocoin(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 5 || params.size() < 4)
throw runtime_error(
"spendzerocoin <amount> <mintchange [true|false]> <minimizechange [true|false]> <securitylevel [1-100]> <address>\n"
"Overview: Convert zddCash (zerocoins) into ddCash. \n"
"amount: amount to spend\n"
"mintchange: if there is left over ddCash (change), the wallet can convert it automatically back to zerocoins [true]\n"
"minimizechange: try to minimize the returning change [false]\n"
"security level: the amount of checkpoints to add to the accumulator. A checkpoint contains 10 blocks worth of zerocoinmints."
"The more checkpoints that are added, the more untraceable the transaction will be. Use [100] to add the maximum amount"
"of checkpoints available. Tip: adding more checkpoints makes the minting process take longer\n"
"address: Send straight to an address or leave the address blank and the wallet will send to a change address. If there is change then"
"an address is required"
+ HelpRequiringPassphrase());
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE))
throw JSONRPCError(RPC_WALLET_ERROR, "zddCash is currently disabled due to maintenance.");
int64_t nTimeStart = GetTimeMillis();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
CAmount nAmount = AmountFromValue(params[0]); // Spending amount
bool fMintChange = params[1].get_bool(); // Mint change to zddCash
bool fMinimizeChange = params[2].get_bool(); // Minimize change
int nSecurityLevel = params[3].get_int(); // Security level
CBitcoinAddress address = CBitcoinAddress(); // Optional sending address. Dummy initialization here.
if (params.size() == 5) {
// Destination address was supplied as params[4]. Optional parameters MUST be at the end
// to avoid type confusion from the JSON interpreter
address = CBitcoinAddress(params[4].get_str());
if(!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid ddCash address");
}
CWalletTx wtx;
vector<CZerocoinMint> vMintsSelected;
CZerocoinSpendReceipt receipt;
bool fSuccess;
if(params.size() == 5) // Spend to supplied destination address
fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtx, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address);
else // Spend to newly generated local address
fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtx, receipt, vMintsSelected, fMintChange, fMinimizeChange);
if (!fSuccess)
throw JSONRPCError(RPC_WALLET_ERROR, receipt.GetStatusMessage());
CAmount nValueIn = 0;
Array arrSpends;
for (CZerocoinSpend spend : receipt.GetSpends()) {
Object obj;
obj.push_back(Pair("denomination", spend.GetDenomination()));
obj.push_back(Pair("pubcoin", spend.GetPubCoin().GetHex()));
obj.push_back(Pair("serial", spend.GetSerial().GetHex()));
uint32_t nChecksum = spend.GetAccumulatorChecksum();
obj.push_back(Pair("acc_checksum", HexStr(BEGIN(nChecksum), END(nChecksum))));
arrSpends.push_back(obj);
nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination());
}
CAmount nValueOut = 0;
Array vout;
for (unsigned int i = 0; i < wtx.vout.size(); i++) {
const CTxOut& txout = wtx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
nValueOut += txout.nValue;
CTxDestination dest;
if(txout.scriptPubKey.IsZerocoinMint())
out.push_back(Pair("address", "zerocoinmint"));
else if(ExtractDestination(txout.scriptPubKey, dest))
out.push_back(Pair("address", CBitcoinAddress(dest).ToString()));
vout.push_back(out);
}
//construct JSON to return
Object ret;
ret.push_back(Pair("txid", wtx.GetHash().ToString()));
ret.push_back(Pair("bytes", (int64_t)wtx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION)));
ret.push_back(Pair("fee", ValueFromAmount(nValueIn - nValueOut)));
ret.push_back(Pair("duration_millis", (GetTimeMillis() - nTimeStart)));
ret.push_back(Pair("spends", arrSpends));
ret.push_back(Pair("outputs", vout));
return ret;
}
Value resetmintzerocoin(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"resetmintzerocoin <extended_search>\n"
"Scan the blockchain for all of the zerocoins that are held in the wallet.dat. Update any meta-data that is incorrect.\n"
"Archive any mints that are not able to be found."
"\nArguments:\n"
"1. \"extended_search\" (bool, optional) Rescan each block of the blockchain looking for your mints. WARNING - may take 30+ minutes!\n"
+ HelpRequiringPassphrase());
bool fExtendedSearch = false;
if (params.size() == 1)
fExtendedSearch = params[0].get_bool();
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CZerocoinMint> listMints = walletdb.ListMintedCoins(false, false, true);
vector<CZerocoinMint> vMintsToFind{ std::make_move_iterator(std::begin(listMints)), std::make_move_iterator(std::end(listMints)) };
vector<CZerocoinMint> vMintsMissing;
vector<CZerocoinMint> vMintsToUpdate;
// search all of our available data for these mints
FindMints(vMintsToFind, vMintsToUpdate, vMintsMissing, fExtendedSearch);
// update the meta data of mints that were marked for updating
Array arrUpdated;
for (CZerocoinMint mint : vMintsToUpdate) {
walletdb.WriteZerocoinMint(mint);
arrUpdated.push_back(mint.GetValue().GetHex());
}
// delete any mints that were unable to be located on the blockchain
Array arrDeleted;
for (CZerocoinMint mint : vMintsMissing) {
arrDeleted.push_back(mint.GetValue().GetHex());
walletdb.ArchiveMintOrphan(mint);
}
Object obj;
obj.push_back(Pair("updated", arrUpdated));
obj.push_back(Pair("archived", arrDeleted));
return obj;
}
Value resetspentzerocoin(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"resetspentzerocoin\n"
"Scan the blockchain for all of the zerocoins that are held in the wallet.dat. Reset mints that are considered spent that did not make it into the blockchain."
+ HelpRequiringPassphrase());
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CZerocoinMint> listMints = walletdb.ListMintedCoins(false, false, false);
list<CZerocoinSpend> listSpends = walletdb.ListSpentCoins();
list<CZerocoinSpend> listUnconfirmedSpends;
for (CZerocoinSpend spend : listSpends) {
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(spend.GetTxHash(), tx, hashBlock)) {
listUnconfirmedSpends.push_back(spend);
continue;
}
//no confirmations
if (hashBlock == 0)
listUnconfirmedSpends.push_back(spend);
}
Object objRet;
Array arrRestored;
for (CZerocoinSpend spend : listUnconfirmedSpends) {
for (CZerocoinMint mint : listMints) {
if (mint.GetSerialNumber() == spend.GetSerial()) {
mint.SetUsed(false);
walletdb.WriteZerocoinMint(mint);
walletdb.EraseZerocoinSpendSerialEntry(spend.GetSerial());
RemoveSerialFromDB(spend.GetSerial());
Object obj;
obj.push_back(Pair("serial", spend.GetSerial().GetHex()));
arrRestored.push_back(obj);
continue;
}
}
}
objRet.push_back(Pair("restored", arrRestored));
return objRet;
}
Value getarchivedzerocoin(const Array& params, bool fHelp)
{
if(fHelp || params.size() != 0)
throw runtime_error(
"getarchivedzerocoin\n"
"Display zerocoins that were archived because they were believed to be orphans."
"Provides enough information to recover mint if it was incorrectly archived."
+ HelpRequiringPassphrase());
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CZerocoinMint> listMints = walletdb.ListArchivedZerocoins();
Array arrRet;
for (const CZerocoinMint mint : listMints) {
Object objMint;
objMint.push_back(Pair("txid", mint.GetTxHash().GetHex()));
objMint.push_back(Pair("denomination", FormatMoney(mint.GetDenominationAsAmount())));
objMint.push_back(Pair("serial", mint.GetSerialNumber().GetHex()));
objMint.push_back(Pair("randomness", mint.GetRandomness().GetHex()));
objMint.push_back(Pair("pubcoin", mint.GetValue().GetHex()));
arrRet.push_back(objMint);
}
return arrRet;
}
Value exportzerocoins(const Array& params, bool fHelp)
{
if(fHelp || params.empty() || params.size() > 2)
throw runtime_error(
"exportzerocoins include_spent ( denomination )\n"
"Exports zerocoin mints that are held by this wallet.dat\n"
"\nArguments:\n"
"1. \"include_spent\" (bool, required) Include mints that have already been spent\n"
"2. \"denomination\" (integer, optional) Export a specific denomination of zddCash\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"d\" : n, (numeric) the mint's zerocoin denomination \n"
" \"p\" : \"pubcoin\", (string) The public coin\n"
" \"s\" : \"serial\", (string) The secret serial number\n"
" \"r\" : \"random\", (string) The secret random number\n"
" \"t\" : \"txid\", (string) The txid that the coin was minted in\n"
" \"h\" : n, (numeric) The height the tx was added to the blockchain\n"
" \"u\" : used (boolean) Whether the mint has been spent\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("exportzerocoins", "false 5") + HelpExampleRpc("exportzerocoins", "false 5"));
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
CWalletDB walletdb(pwalletMain->strWalletFile);
bool fIncludeSpent = params[0].get_bool();
libzerocoin::CoinDenomination denomination = libzerocoin::ZQ_ERROR;
if (params.size() == 2)
denomination = libzerocoin::IntToZerocoinDenomination(params[1].get_int());
list<CZerocoinMint> listMints = walletdb.ListMintedCoins(!fIncludeSpent, false, false);
Array jsonList;
for (const CZerocoinMint mint : listMints) {
if (denomination != libzerocoin::ZQ_ERROR && denomination != mint.GetDenomination())
continue;
Object objMint;
objMint.emplace_back(Pair("d", mint.GetDenomination()));
objMint.emplace_back(Pair("p", mint.GetValue().GetHex()));
objMint.emplace_back(Pair("s", mint.GetSerialNumber().GetHex()));
objMint.emplace_back(Pair("r", mint.GetRandomness().GetHex()));
objMint.emplace_back(Pair("t", mint.GetTxHash().GetHex()));
objMint.emplace_back(Pair("h", mint.GetHeight()));
objMint.emplace_back(Pair("u", mint.IsUsed()));
jsonList.emplace_back(objMint);
}
return jsonList;
}
Value importzerocoins(const Array& params, bool fHelp)
{
if(fHelp || params.size() == 0)
throw runtime_error(
"importzerocoins importdata \n"
"[{\"d\":denomination,\"p\":\"pubcoin_hex\",\"s\":\"serial_hex\",\"r\":\"randomness_hex\",\"t\":\"txid\",\"h\":height, \"u\":used},{\"d\":...}]\n"
"\nImport zerocoin mints.\n"
"Adds raw zerocoin mints to the wallet.dat\n"
"Note it is recommended to use the json export created from the exportzerocoins RPC call\n"
"\nArguments:\n"
"1. \"importdata\" (string, required) A json array of json objects containing zerocoin mints\n"
"\nResult:\n"
"\"added\" (int) the quantity of zerocoin mints that were added\n"
"\"value\" (string) the total zddCash value of zerocoin mints that were added\n"
"\nExamples\n" +
HelpExampleCli("importzerocoins", "\'[{\"d\":100,\"p\":\"mypubcoin\",\"s\":\"myserial\",\"r\":\"randomness_hex\",\"t\":\"mytxid\",\"h\":104923, \"u\":false},{\"d\":5,...}]\'") +
HelpExampleRpc("importzerocoins", "[{\"d\":100,\"p\":\"mypubcoin\",\"s\":\"myserial\",\"r\":\"randomness_hex\",\"t\":\"mytxid\",\"h\":104923, \"u\":false},{\"d\":5,...}]"));
if(pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array arrMints = params[0].get_array();
CWalletDB walletdb(pwalletMain->strWalletFile);
int count = 0;
CAmount nValue = 0;
for (const Value &val : arrMints) {
const Object &o = val.get_obj();
int d = ParseInt(o, "d");
if (d < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, d must be positive");
libzerocoin::CoinDenomination denom = libzerocoin::IntToZerocoinDenomination(d);
CBigNum bnValue = CBigNum(find_value(o, "p").get_str());
CBigNum bnSerial = CBigNum(find_value(o, "s").get_str());
CBigNum bnRandom = CBigNum(find_value(o, "r").get_str());
uint256 txid(find_value(o, "t").get_str());
int nHeight = ParseInt(o, "h");
if (nHeight < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, h must be positive");
bool fUsed = ParseBool(o, "u");
CZerocoinMint mint(denom, bnValue, bnRandom, bnSerial, fUsed);
mint.SetTxHash(txid);
mint.SetHeight(nHeight);
walletdb.WriteZerocoinMint(mint);
count++;
nValue += libzerocoin::ZerocoinDenominationToAmount(denom);
}
Object ret;
ret.emplace_back(Pair("added", count));
ret.emplace_back(Pair("value", FormatMoney(nValue)));
return ret;
}
Value reconsiderzerocoins(const Array& params, bool fHelp)
{
if(fHelp || !params.empty())
throw runtime_error(
"reconsiderzerocoins\n"
"\nCheck archived zddCash list to see if any mints were added to the blockchain.\n"
"\nResult\n"
"[ (array of json objects)\n"
" {\n"
" \"txid\" : txid, (numeric) the mint's zerocoin denomination \n"
" \"denomination\" : \"denom\", (numeric) the mint's zerocoin denomination\n"
" \"pubcoin\" : \"pubcoin\", (string) The mint's public identifier\n"
" \"height\" : n, (numeric) The height the tx was added to the blockchain\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("reconsiderzerocoins", "") + HelpExampleRpc("reconsiderzerocoins", ""));
if(pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED,
"Error: Please enter the wallet passphrase with walletpassphrase first.");
list<CZerocoinMint> listMints;
pwalletMain->ReconsiderZerocoins(listMints);
Array arrRet;
for (const CZerocoinMint mint : listMints) {
Object objMint;
objMint.emplace_back(Pair("txid", mint.GetTxHash().GetHex()));
objMint.emplace_back(Pair("denomination", FormatMoney(mint.GetDenominationAsAmount())));
objMint.emplace_back(Pair("pubcoin", mint.GetValue().GetHex()));
objMint.emplace_back(Pair("height", mint.GetHeight()));
arrRet.emplace_back(objMint);
}
return arrRet;
}
| [
"liamstrong@gmail.com"
] | liamstrong@gmail.com |
b7e7310cf87466f7ec26008736bf59d0c9a989ac | c588d9858ab29067627cc211d0a1602195ed6ed7 | /src/libgeodb/obb.cpp | 31e2a04c86b5125cc8a9428c7084787b2f29ce53 | [] | no_license | ldarren/sg_prototype | 85ddc6c9ccee5d3d404f482b86f70e7a740670b6 | c8a731dc9c35ce1c46b373389eae1ba1244bacdb | refs/heads/master | 2021-01-23T12:05:19.019899 | 2012-04-22T08:23:33 | 2012-04-22T08:23:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 874 | cpp | #include <libgeodb/geodb.h>
using namespace meta;
OrientedBBox::OrientedBBox()
{
memset(&mOBB_, 0, sizeof(GeoBBox));
memset(&mAABB_, 0, sizeof(GeoBBox));
memset(&mPos_, 0, sizeof(GeoCoor));
memset(&mRot_, 0, sizeof(GeoCoor));
memset(&mScale_, 0, sizeof(GeoCoor));
}
OrientedBBox::OrientedBBox(const GeoBBox &box, const GeoCoor &pos, const GeoCoor &rot, const GeoCoor &scale)
{
defineBBox(box, pos, rot, scale);
}
void OrientedBBox::defineBBox(const GeoBBox &box, const GeoCoor &pos, const GeoCoor &rot, const GeoCoor &scale)
{
memcpy(&mPos_, &pos, sizeof(GeoCoor));
memcpy(&mRot_, &rot, sizeof(GeoCoor));
memcpy(&mScale_, &scale, sizeof(GeoCoor));
}
const GeoBBox& OrientedBBox::getOBB() const
{
}
const GeoBBox& OrientedBBox::getAABB() const
{
}
const GeoTagListType& OrientedBBox::filter(const GeoTagListType &raw)
{
}
| [
"ldarren@gmail.com"
] | ldarren@gmail.com |
f405a2e4108d18a1ee29367f6276f086d233b704 | c47c254ca476c1f9969f8f3e89acb4d0618c14b6 | /datasets/github_cpp_10/7/110.cpp | 2f1958ae327e6e152e3adfa7659602945126e143 | [
"BSD-2-Clause"
] | permissive | yijunyu/demo | 5cf4e83f585254a28b31c4a050630b8f661a90c8 | 11c0c84081a3181494b9c469bda42a313c457ad2 | refs/heads/master | 2023-02-22T09:00:12.023083 | 2021-01-25T16:51:40 | 2021-01-25T16:51:40 | 175,939,000 | 3 | 6 | BSD-2-Clause | 2021-01-09T23:00:12 | 2019-03-16T07:13:00 | C | UTF-8 | C++ | false | false | 1,500 | cpp |
#include <iostream>
#include <climits>
#include "sort.hpp"
#include "reddit_info.hpp"
using namespace std;
typedef vector<RedditInfo>::iterator RedditInfoPtr;
void merge(vector<RedditInfo> &A, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
vector<RedditInfo> L(A.begin() + p, A.begin() + p + n1);
vector<RedditInfo> R(A.begin() + q + 1, A.begin() + q + 1 + n2);
RedditInfo inf1;
inf1.total_votes = INT_MAX;
L.push_back(inf1);
RedditInfo inf2;
inf2.total_votes = INT_MAX;
R.push_back(inf2);
int i = 0;
int j = 0;
for(int k = p; k <= r ; k++) {
if(L[i] <= R[j]) {
iter_swap(A.begin() + k, L.begin() + i);
i++;
}
else {
iter_swap(A.begin() + k, R.begin() + j);
j++;
}
}
}
void merge_sort(vector<RedditInfo> &A, int p, int r) {
if(p < r) {
int q = (p + r)/2;
merge_sort(A, p, q);
merge_sort(A, q + 1, r);
merge(A, p, q, r);
}
}
int main(int argc, const char* argv[]) {
if (argc != 2) {
cout << "Usage: sort1 example.csv" << endl;
return 0;
}
vector<RedditInfo> data = import_data(argv[1]);
cout << "Unsorted: " << endl;
RedditInfo::print_header();
print(data);
merge_sort(data, 0, data.size()-1);
cout << "Sorted: " << endl;
RedditInfo::print_header();
print(data);
} | [
"y.yu@open.ac.uk"
] | y.yu@open.ac.uk |
2e04096b2115ab8c38916164978049cc98ba19c3 | 3ae80dbc18ed3e89bedf846d098b2a98d8e4b776 | /header/SSWR/AVIRead/AVIRGenImageForm.h | a4b7570a20ff1a5ffe694c1bdb147bd2dbbeac84 | [] | no_license | sswroom/SClass | deee467349ca249a7401f5d3c177cdf763a253ca | 9a403ec67c6c4dfd2402f19d44c6573e25d4b347 | refs/heads/main | 2023-09-01T07:24:58.907606 | 2023-08-31T11:24:34 | 2023-08-31T11:24:34 | 329,970,172 | 10 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | h | #ifndef _SM_SSWR_AVIREAD_AVIRGENIMAGEFORM
#define _SM_SSWR_AVIREAD_AVIRGENIMAGEFORM
#include "Media/ImageGen/ImageGenMgr.h"
#include "UI/GUIButton.h"
#include "UI/GUIComboBox.h"
#include "UI/GUIForm.h"
#include "UI/GUIGroupBox.h"
#include "UI/GUIRadioButton.h"
#include "UI/GUITextBox.h"
#include "SSWR/AVIRead/AVIRCore.h"
namespace SSWR
{
namespace AVIRead
{
class AVIRGenImageForm : public UI::GUIForm
{
private:
UI::GUIComboBox *cboGenerator;
UI::GUIComboBox *cboColorProfile;
UI::GUITextBox *txtWidth;
UI::GUITextBox *txtHeight;
UI::GUIButton *btnGenerate;
UI::GUIButton *btnCancel;
NotNullPtr<SSWR::AVIRead::AVIRCore> core;
Media::ImageGen::ImageGenMgr *imgGenMgr;
static void __stdcall GenerateClicked(void *userObj);
static void __stdcall CancelClicked(void *userObj);
public:
AVIRGenImageForm(UI::GUIClientControl *parent, NotNullPtr<UI::GUICore> ui, NotNullPtr<SSWR::AVIRead::AVIRCore> core);
virtual ~AVIRGenImageForm();
virtual void OnMonitorChanged();
};
};
};
#endif
| [
"sswroom@yahoo.com"
] | sswroom@yahoo.com |
f1d03c1295bd55d289574ff47e2478ca518e08e8 | f76e43b84e0b624de8aed0a4b9f9bb0a9be22b92 | /src/dag-lib/ModelBase.cpp | aa0971b2ede3e1f03ae778138486ddff72a17d0e | [] | no_license | hansongfang/idb | 8c2603a3b37d55e0f17d9f815c56cfa27b416941 | 5c160553a83548df30fad5bc125cc4f27b01473f | refs/heads/master | 2021-09-13T04:52:29.246968 | 2018-04-25T05:33:26 | 2018-04-25T05:33:26 | 125,979,190 | 8 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,528 | cpp | #include "ModelBase.h"
#include "Log.h"
ModelBase::ModelBase(const char *filename, bool addBackFaces, bool loadNormal)
{
this->loadPly(filename, addBackFaces,loadNormal);
}
ModelBase::~ModelBase()
{
m_indexBuffer.clear();
m_vertexBuffer.clear();
m_vertexPosition3d.clear();
m_triangles.clear();
}
void ModelBase::loadPly( const char* filename, bool addBackFaces /*= false*/,bool addNormal )
{
strcpy(m_modelFullPath, filename);
int nVertices, nIndices;
p_ply ply = ply_open(filename, NULL);
ply_read_header(ply);
nVertices = ply_set_read_cb(ply, "vertex", "x", vertex_cb, (void*)&m_vertexBuffer, PLY_PX);
ply_set_read_cb(ply, "vertex", "y", vertex_cb, (void*)&m_vertexBuffer, PLY_PY);
ply_set_read_cb(ply, "vertex", "z", vertex_cb, (void*)&m_vertexBuffer, PLY_PZ);
if(addNormal){
ply_set_read_cb(ply, "vertex", "nx", vertex_cb, (void*)&m_vertexBuffer, PLY_NX);
ply_set_read_cb(ply, "vertex", "ny", vertex_cb, (void*)&m_vertexBuffer, PLY_NY);
ply_set_read_cb(ply, "vertex", "nz", vertex_cb, (void*)&m_vertexBuffer, PLY_NZ);
}
m_nTriangles = ply_set_read_cb(ply, "face", "vertex_indices", index_cb, (void*)&m_indexBuffer, 0);
nIndices = 3*m_nTriangles;
m_vertexBuffer.resize(nVertices);
m_indexBuffer.reserve(nIndices);
ply_read(ply);
ply_close(ply);
bounds(&m_center, &m_width, &m_height, &m_length, &m_radius, &m_AABB[0]);
m_enableBackFaces = addBackFaces;
if (addBackFaces)
{
m_indexBuffer.reserve(2*nIndices);
for (int i = 0; i < m_nTriangles; ++i)
{
m_indexBuffer.push_back(m_indexBuffer[3*i]);
m_indexBuffer.push_back(m_indexBuffer[3*i + 2]);
m_indexBuffer.push_back(m_indexBuffer[3*i + 1]);
}
m_nTriangles *= 2;
}
//generateNormals();
generateVertices3d();
if(addNormal){
generateVerticeNormal3d();
}
generateTriangles();
}
int ModelBase::vertex_cb( p_ply_argument argument )
{
long i, j;
vector<Vertex>* ver;
ply_get_argument_element(argument, NULL, &i);
ply_get_argument_user_data(argument, (void**)&ver, &j);
j -= PLY_PX;
(*ver)[i].position[j] = (double)ply_get_argument_value(argument);
return 1;
}
int ModelBase::index_cb( p_ply_argument argument )
{
long i, j;
vector<int>* ind;
ply_get_argument_element(argument, NULL, &i);
ply_get_argument_property(argument, NULL, NULL, &j);
ply_get_argument_user_data(argument, (void**)&ind, NULL);
if(j < 0) return 1;
ind->push_back((int)ply_get_argument_value(argument));
return 1;
}
void ModelBase::printSummary()
{
cout << "nVertices=" << getNumberOfIndices() << " nFaces=" << getNumberOfTriangles() << endl;
}
void ModelBase::bounds(Vector3* center, double* width, double* height,
double* length, double* radius, Vector3d* AABB) const
{
/*float xMax = std::numeric_limits<float>::min();
float yMax = std::numeric_limits<float>::min();
float zMax = std::numeric_limits<float>::min();*/
double xMax = -std::numeric_limits<double>::max();
double yMax = -std::numeric_limits<double>::max();
double zMax = -std::numeric_limits<double>::max();
double xMin = std::numeric_limits<double>::max();
double yMin = std::numeric_limits<double>::max();
double zMin = std::numeric_limits<double>::max();
double x = 0.0;
double y = 0.0;
double z = 0.0;
int numVerts = static_cast<int>(m_vertexBuffer.size());
for (int i = 0; i < numVerts; ++i)
{
x = m_vertexBuffer[i].position[0];
y = m_vertexBuffer[i].position[1];
z = m_vertexBuffer[i].position[2];
if (x < xMin)
xMin = x;
if (x > xMax)
xMax = x;
if (y < yMin)
yMin = y;
if (y > yMax)
yMax = y;
if (z < zMin)
zMin = z;
if (z > zMax)
zMax = z;
}
(*center)[0] = (xMin + xMax) / 2.0;
(*center)[1] = (yMin + yMax) / 2.0;
(*center)[2] = (zMin + zMax) / 2.0;
*width = xMax - xMin;
*height = yMax - yMin;
*length = zMax - zMin;
AABB[0] = Vector3d(xMin, yMin, zMin);
AABB[1] = Vector3d(xMax, yMax, zMax);
//*radius = std::max(std::max(*width, *height), *length);
*radius = sqrt(pow(*width, 2.0)+pow(*height,2.0)+pow(*length,2.0))/2.0;
}
Vector3 ModelBase::getCenter() const
{return m_center;}
Vector3d ModelBase::getCenter3d() const
{return Vector3d(m_center[0],m_center[1],m_center[2]);}
double ModelBase::getWidth() const
{return m_width;}
double ModelBase::getHeight() const
{return m_height;}
double ModelBase::getLength() const
{return m_length;}
double ModelBase::getRadius() const
{return m_radius;}
void ModelBase::generateNormals()
{
int totalTriangles = getNumberOfTriangles();
if ( m_enableBackFaces )
totalTriangles /= 2;
int totalVertices = getNumberOfVertices();
const int *pTriangle = 0;
Vertex *pVertex0 = 0;
Vertex *pVertex1 = 0;
Vertex *pVertex2 = 0;
double edge1[3] = {0.0f, 0.0f, 0.0f};
double edge2[3] = {0.0f, 0.0f, 0.0f};
double normal[3] = {0.0f, 0.0f, 0.0f};
double length = 0.0f;
// Initialize all the vertex normals.
for (int i = 0; i < totalVertices; ++i)
{
pVertex0 = &m_vertexBuffer[i];
pVertex0->normal[0] = 0.0f;
pVertex0->normal[1] = 0.0f;
pVertex0->normal[2] = 0.0f;
}
// Calculate the vertex normals.
for (int i = 0; i < totalTriangles; ++i)
{
pTriangle = &m_indexBuffer[i * 3];
pVertex0 = &m_vertexBuffer[pTriangle[0]];
pVertex1 = &m_vertexBuffer[pTriangle[1]];
pVertex2 = &m_vertexBuffer[pTriangle[2]];
// Calculate triangle face normal.
edge1[0] = pVertex1->position[0] - pVertex0->position[0];
edge1[1] = pVertex1->position[1] - pVertex0->position[1];
edge1[2] = pVertex1->position[2] - pVertex0->position[2];
edge2[0] = pVertex2->position[0] - pVertex0->position[0];
edge2[1] = pVertex2->position[1] - pVertex0->position[1];
edge2[2] = pVertex2->position[2] - pVertex0->position[2];
normal[0] = (edge1[1] * edge2[2]) - (edge1[2] * edge2[1]);
normal[1] = (edge1[2] * edge2[0]) - (edge1[0] * edge2[2]);
normal[2] = (edge1[0] * edge2[1]) - (edge1[1] * edge2[0]);
// Accumulate the normals.
pVertex0->normal[0] += normal[0];
pVertex0->normal[1] += normal[1];
pVertex0->normal[2] += normal[2];
pVertex1->normal[0] += normal[0];
pVertex1->normal[1] += normal[1];
pVertex1->normal[2] += normal[2];
pVertex2->normal[0] += normal[0];
pVertex2->normal[1] += normal[1];
pVertex2->normal[2] += normal[2];
}
// Normalize the vertex normals.
for (int i = 0; i < totalVertices; ++i)
{
pVertex0 = &m_vertexBuffer[i];
length = 1.0f / sqrtf(pVertex0->normal[0] * pVertex0->normal[0] +
pVertex0->normal[1] * pVertex0->normal[1] +
pVertex0->normal[2] * pVertex0->normal[2]);
pVertex0->normal[0] *= length;
pVertex0->normal[1] *= length;
pVertex0->normal[2] *= length;
}
}
Vector3d* ModelBase::getAABB() const
{
return (Vector3d*)&m_AABB[0];
}
void ModelBase::generateVertices3d()
{
m_vertexPosition3d.reserve(m_vertexBuffer.size());
for (const auto &v: m_vertexBuffer) {
const auto &pos = v.position;
m_vertexPosition3d.push_back( Vector3d(pos[0], pos[1], pos[2]) );
}
}
void ModelBase::generateVerticeNormal3d()
{
m_vertexNormal3d.reserve(m_vertexBuffer.size());
for (const auto &v: m_vertexBuffer) {
const auto &normal = v.normal;
m_vertexNormal3d.push_back( Vector3d(normal[0], normal[1], normal[2]) );
}
}
void ModelBase::generateTriangles()
{
m_triangles.resize(m_nTriangles);
for (int id = 0; id < m_nTriangles; ++id) {
Triangle &tri = m_triangles[id];
tri._id = id;
for (auto i = 0; i < 3; ++i)
{
auto idx = this->getIndex(id * 3 + i);
tri._vId[i] = idx;
const auto &v = this->getVertex(idx).position;
tri._vertices[i] = Vector3d(v[0], v[1], v[2]);
tri.enrich();
}
}
}
const Triangle &ModelBase::getTriangle(int id) const
{
return m_triangles[id];
}
const vector<Triangle> &ModelBase::getTriangles() const
{
return m_triangles;
}
| [
"shanaf@ust.hk"
] | shanaf@ust.hk |
fa19f8904a7f05e99441cf4a793d7886e92860c6 | ddba92bfd56acc0a4b92f42aab45ff7e5af71ffb | /src/materials/emissive.h | da7b1f1a33315a43f8e0e3e6a5955c10956593e3 | [] | no_license | xueliuxing28/raytracer-3 | 811b69fb1f952352976ea72c430242394a9b0d66 | f0241c5c55401755a4c103ad2aadc18854deda21 | refs/heads/master | 2021-12-15T23:00:35.272719 | 2017-09-10T14:28:58 | 2017-09-10T14:28:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 417 | h | #pragma once
#include "..\material.h"
class Emissive : public Material
{
public:
Emissive(const Vector3& color, float intensity);
virtual bool scatter(const Ray &ray, const Intersection &intersection,
Vector3 &attenuation, Ray &scattered) const override;
virtual Vector3 emit(float u, float v, const Vector3 &point) const override;
Vector3 color;
float intensity;
}; | [
"ruidanielcaridade@gmail.com"
] | ruidanielcaridade@gmail.com |
2ef8fa1598db95d0ea8d1aa6ee1c4205ae588f5d | 79668e1cc702be4af06754429de3188f371eb264 | /policies/DIF/EFCP/DTP/RcvrInactivity/RcvrInactivityPolicyBase.h | 045109e07cbb377a35e907d95f14219121b469ab | [
"MIT"
] | permissive | fatmahrizi/RINA | 3a94edb940f144931bca38dfb3cf74d0a1ad479a | 08192a51dda673a5e5af0c5caf1d45e2b4de6d6e | refs/heads/master | 2020-12-25T23:37:56.787722 | 2015-06-09T12:13:06 | 2015-06-09T12:13:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,428 | h | //
// Copyright © 2014 - 2015 PRISTINE Consortium (http://ict-pristine.eu)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
/**
* @file RcvrInactivityPolicyBase.h
* @author Marcel Marek (imarek@fit.vutbr.cz)
* @date Jan 9, 2015
* @brief
* @detail
*/
#ifndef RCVRINACTIVITYPOLICYBASE_H_
#define RCVRINACTIVITYPOLICYBASE_H_
#include <omnetpp.h>
#include "EFCPPolicy.h"
/*
*
*/
class RcvrInactivityPolicyBase : public EFCPPolicy
{
public:
RcvrInactivityPolicyBase();
virtual ~RcvrInactivityPolicyBase();
// virtual bool run(DTPState* dtpState, DTCPState* dtcpState) = 0;
protected:
virtual void initialize(){};
virtual void handleMessage(cMessage* msg){};
void defaultAction(DTPState* dtpState, DTCPState* dtcpState);
};
#endif /* RCVRINACTIVITYPOLICYBASE_H_ */
| [
"imarek@fit.vutbr.cz"
] | imarek@fit.vutbr.cz |
a7dd6efbc96f60e0df75df0554f9981f2c85aa88 | d546a66ce50bbac86c61906fd9ba5654c1f2c3be | /NCSPCore/HierarchProfile.h | 06430d342202e4bb7829baea6d66a582978f7d27 | [] | no_license | MalcolmMcNeely/NCSP | 30eec5207e14c1acaff4d93f5cfb89068a186b83 | c2cb7130f3051cd257f220cf0be6099b7274eef7 | refs/heads/master | 2020-03-24T19:24:20.804910 | 2018-07-30T20:56:09 | 2018-07-30T20:56:09 | 142,924,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 745 | h | //
// Constraint profile for determining the top level of the story:
// locations, main characters
//
#pragma once
#include "IConstraintProfile.h"
class HierarchProfile : public IConstraintProfile
{
public:
HierarchProfile();
~HierarchProfile();
void Initialise(GWorker* worker, ProfilePackage* package) override;
void Constrain(GWorker* worker, ProfilePackage* package) override;
void Branch(GWorker* worker, ProfilePackage* package) override;
void ReturnOutput(std::ostream& os, const void* worker, const void* package) override;
private:
void ApplyDomains(GWorker* worker, ProfilePackage* package) override;
void DefineValidShotData(GWorker* worker, ProfilePackage* package) override;
int vRows_, vCols_;
};
| [
"malcolm.mcneely.86@gmail.com"
] | malcolm.mcneely.86@gmail.com |
7f6823d15c37b2ea376249fd8da09f4ef6742fce | 180d3d6e383ca1dd4ea9335e605cc53659a8f658 | /language/c++/virtual/virtual-destructor-4.cpp | 8e8d9546a1a9c129d3f820f991dfe15dd7865647 | [] | no_license | wangdingqiao/programmer-evolution-plan | 52f0eca73c3477f8fc822a039320a0b488ec3fa8 | 63b448a35c5668790720d0fe414600510b9fe61a | refs/heads/master | 2020-03-28T07:22:48.590830 | 2019-02-16T03:40:34 | 2019-02-16T03:40:34 | 147,897,279 | 4 | 3 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,221 | cpp | #include <iostream>
#include <vector>
class Base
{
public:
virtual ~Base() // note: virtual
{
}
};
class Derived: public Base
{
private:
int* m_array;
public:
Derived(int length)
{
m_array = new int[length];
}
virtual ~Derived() // note: virtual
{
delete[] m_array;
}
};
class ObjManager
{
public:
void makeObj(const int objCount)
{
for(int i = 1; i <= objCount ; ++i)
{
seqBasePtr.push_back(new Derived(i));
}
}
void releaseObj()
{
for(SeqBasePtr::const_iterator it = seqBasePtr.begin(); it != seqBasePtr.end();++it)
{
Base * base = *it;
if(base)
{
delete base; // µ¼ÖÂÄÚ´æÐ¹Â¶
}
}
seqBasePtr.clear();
}
~ObjManager()
{
releaseObj();
}
private:
typedef std::vector<Base*> SeqBasePtr;
SeqBasePtr seqBasePtr;
};
int main()
{
const int objCount = 10000;
ObjManager objManager;
objManager.makeObj(objCount);
std::cout << "allocate " << objCount << " objects finished, press key to continue:" << std::endl;
char waitkey;
std::cin >> waitkey;
objManager.releaseObj();
std::cout << "deallocate object finished, press key to continue:" << std::endl;
std::cin >> waitkey;
return 0;
} | [
"wangdingqiao@users.noreply.github.com"
] | wangdingqiao@users.noreply.github.com |
37d7fba195db7b100f81e9eba52eb5017b5d8f15 | 9c0938585d2fe076011356f7f972ff666ca7011b | /p3/driver/card.h | 13821bf4c71ec571430627a46b2fd3f0a0f85a23 | [] | no_license | ve280/code-check | 0bae44684daeb89793cce5bbe06ef079a3e2e081 | 8805623f25f625b231f01642746f7b45e3243a5f | refs/heads/master | 2023-07-20T02:19:05.177733 | 2023-07-12T01:58:59 | 2023-07-12T01:58:59 | 193,128,344 | 18 | 14 | null | 2021-07-18T09:12:45 | 2019-06-21T16:19:09 | Python | UTF-8 | C++ | false | false | 594 | h | #ifndef __CARD_H__
#define __CARD_H__
#include <string>
using namespace std;
enum Suit {
SPADES, HEARTS, CLUBS, DIAMONDS
};
enum Spot {
TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,
JACK, QUEEN, KING, ACE
};
enum Team {
SOSBrigade, StardustCrusaders
};
extern const string SuitNames[DIAMONDS + 1];
extern const string SpotNames[ACE+1];
extern const string SOS_Name[5]; // The full name of each member in SOS Brigade
extern const string SC_Name[5]; // The full name of each member in Stardust
struct Card {
Spot spot;
Suit suit;
};
#endif /* __CARD_H__ */
| [
"3357667574@qq.com"
] | 3357667574@qq.com |
fa3fc7db7290b857e5cee2f126ed9a4ad4ff26a9 | 02f5f35c4b182f18916e5aab8fa8f8b37fa6023c | /Person.cpp | 655f5e36ce174c6d73162a58688dbc1a50f31dea | [] | no_license | Mozuha/CS255C | 1551f5006abd90a3d79172b737c027e2e5d5c2c6 | be8c69a8cdc2f8261e4c757d84556599e0c6e21a | refs/heads/master | 2020-12-20T02:51:38.450838 | 2020-05-01T14:43:42 | 2020-05-01T14:43:42 | 235,939,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,355 | cpp | /*
* April 28, 2020
* Mizuki Hashimoto
* Project 12
* This is the source file for the class Person. It contains the code that defines each method of the class.
*/
#include "Person.h"
#include <string>
//constructor
Person::Person(int idValue, string lastNameValue, string firstNameValue, int ageValue) {
setId(idValue);
setLastName(lastNameValue);
setFirstName(firstNameValue);
setAge(ageValue);
}
//setters
void Person::setId(int idValue) {
idNumber = idValue;
}
void Person::setLastName(string lastNameString) {
// copy at most 15 characters from string to lastName
int length = lastNameString.size();
length=(length<15?length:14);
lastNameString.copy( lastName, length );
lastName[ length ] = '\0'; // append null character to lastName
}
void Person::setFirstName(string firstNameString) {
// copy at most 10 characters from string to firstName
int length = firstNameString.size();
length=(length<10?length:9);
firstNameString.copy( firstName, length );
firstName[length] = '\0'; // append null character to firstName
}
void Person::setAge(int ageValue) {
age = ageValue;
}
//getters
int Person::getId() const {
return idNumber;
}
string Person::getLastName() const {
return lastName;
}
string Person::getFirstName() const {
return firstName;
}
int Person::getAge() const {
return age;
}
| [
"mizuki.mikkun.hashimoto@gmail.com"
] | mizuki.mikkun.hashimoto@gmail.com |
9a482b9eedaf98a77d452635386d5a1c429bda30 | c0567340116b43175c1c25f6bb4d8b368ddc72ce | /Include/ParticlesGame/directed_light_no_shadow_casting_material.h | 5536e972a55613243dfb8bff2cd357ab8712b5db | [] | no_license | Goshido/QTOpenGL | 178abdef5de5e4fa9b5a981d031f33a0ed4d42be | 8934a786f446be26a8f28d65ba9ed55ac9dc9a57 | refs/heads/master | 2021-01-19T23:07:47.742148 | 2017-03-03T09:51:20 | 2017-03-03T09:55:22 | 83,784,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | h | #ifndef DIRECTED_LIGHT_NO_SHADOW_CASTING_MATERIAL_H
#define DIRECTED_LIGHT_NO_SHADOW_CASTING_MATERIAL_H
#include <GXEngine/material.h>
#include <GXEngine/texture.h>
namespace particles_game {
class DirectedLightNoShadowCastingMaterial : public gx_engine::Material {
public:
explicit DirectedLightNoShadowCastingMaterial();
~DirectedLightNoShadowCastingMaterial() override;
void bind(const gx_engine::Renderable& activeRenderable) override;
void unbind() override;
void setLightDirectionView(const gx_common::GXVec3& directionView);
void setColor(unsigned char red, unsigned char green, unsigned char blue, float intensity);
void setViewerInverseProjectionMatrix(const gx_common::GXMat4& invProjectionMatrix);
void setControlTextures(gx_engine::Texture& albedo, gx_engine::Texture& emission, gx_engine::Texture& normal,
gx_engine::Texture& cookTorrance, gx_engine::Texture& depth);
private:
GLint _modelViewProjectionMatrixLocation;
GLint _invScreenResolutionLocation;
GLint _invProjectionMatrixLocation;
GLint _hdrColorLocation;
GLint _colorComponentsLocation;
GLint _invLightDirectionViewLocation;
gx_engine::Texture* _albedoTexture;
gx_engine::Texture* _emissionTexture;
gx_engine::Texture* _normalTexture;
gx_engine::Texture* _cookTorranceTexture;
gx_engine::Texture* _depthTexture;
gx_common::GXVec2 _invScreenResolution;
gx_common::GXVec3 _invLightDirectionView;
const gx_common::GXMat4* _invProjectionMatrix;
gx_common::GXVec3 _hdrColor;
gx_common::GXVec4 _colorComponents;
};
} // namespace particles_game
#endif DIRECTED_LIGHT_NO_SHADOW_CASTING_MATERIAL_H
| [
"gmatasimov@expertsolutions.ru"
] | gmatasimov@expertsolutions.ru |
622c71e5c39d4200050711c02e5bc117dab4c33a | 4fc5bb49e94c76642fa1c1946460b805c9797cc1 | /Lista Exercicios 2/3.3.cpp | 14ce42438caa6cf311cde6bae45280389ee014f7 | [] | no_license | bruunofernandz/estruturaDados | 10fdaf56693cab258da8ed61a09cb763e2c7ff9c | cdad48980af95d4317421384752b7e5d36c11ab6 | refs/heads/master | 2020-03-21T16:55:32.380994 | 2018-06-22T00:59:39 | 2018-06-22T00:59:39 | 138,802,657 | 1 | 0 | null | 2018-06-26T23:00:22 | 2018-06-26T23:00:21 | null | ISO-8859-1 | C++ | false | false | 5,748 | cpp | /*
* Lista 2, exercicio 3.1
* Danilo Sicari
*
* Faça um programa para empilhar e desempilhar tarefas a serem feitas. Não há limite para as atividades que
* você pode empilhar. Armazene o nome da tarefa, tempo necessário em horas (inteiro), código da pessoa
* responsável pela tarefa, conforme tabela.
*
* 3.1 - Crie uma função que crie e empilhe vinte tarefas de forma automática.
* 3.2 - Crie uma função que retorne a tarefa com maior tempo necessário para ser realizado.
* 3.3 - Crie uma função que retorne o número de tarefas por pessoa
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <cstring>
using namespace std;
typedef struct{
char nomeTarefa[128];
int tempo;
int codigo;
char responsavel[128];
int qtde;
}TTarefa;
typedef struct node {
TTarefa tarefa;
struct node *next;
} Node;
typedef struct {
Node *top;
int size;
} Pilha;
Pilha* inicializar() {
Pilha *s = (Pilha*)malloc(sizeof(Pilha));
s->size = 0;
s->top = NULL;
}
bool push(Pilha *s, TTarefa *task) {
Node *np;
np = (Node*)malloc(sizeof(Node));
if (np == NULL) {
return false;
}
//memcpy(np->tarefa, task, sizeof(TTarefa));
np->tarefa = *task;
np->next = s->top;
s->top = np;
s->size++;
return true;
}
bool pop(Pilha *s) {
Node *np;
if (s->top == NULL) {
return false;
}
np = s->top;
s->top = np->next;
s->size--;
free(np);
return true;
}
void destruir_pilha(Pilha *s) {
while (s->top != NULL) {
pop(s);
}
pop(s);
free(s);
}
bool imprime_pilha(Pilha *s) {
Node* temp;
if (s->top == NULL) {
return false;
}
temp = s->top;
printf("\n\n# %d \n",s->size);
while(temp!=NULL){
cout << "\nTAREFA: " << temp->tarefa.nomeTarefa << " - Tempo: " << temp->tarefa.tempo << " - Responsavel: " << temp->tarefa.responsavel << " - Codigo: " << temp->tarefa.codigo << endl;
temp = temp->next;
}
printf("\n");
return true;
}
int main() {
Pilha *pilhaTarefas = inicializar();
//o codigo do responsavel pela tarefa nao se repete!!
static int codigoResponsavel = 0;
int opt = 0;
do{
cout << "\n\nTAREFAS DA MAMAE" << endl;
cout << "1 - Inserir nova tarefa" << endl;
cout << "2 - Deletar ultima tarefa" << endl;
cout << "3 - Listar tarefas" << endl;
cout << "4 - Inserir 20 novas tarefas" << endl;
cout << "5 - Retirar 20 tarefas" << endl;
cout << "6 - Tarefa com maior tempo execucao" << endl;
cout << "7 - Tarefas por pessoa" << endl;
cout << "8 - Sair" << endl;
cout << "Digite a opcao desejada: ";
cin >> opt;
if(opt == 1){
TTarefa TODO;
cout << "\n\n -- NOVA TAREFA --" << endl;
cout << "Insira descricao tarefa, sem espaco: ";
cin >> TODO.nomeTarefa;
cout << "Tempo necessario (H)?";
cin >> TODO.tempo;
cout << "Nome responsavel, sem espaco: ";
memset(TODO.responsavel, 0, sizeof(TODO.responsavel));
cin >> TODO.responsavel;
cout << "Codigo responsavel sera: " << ++codigoResponsavel;
TODO.codigo = codigoResponsavel;
push(pilhaTarefas, &TODO);
}
else if(opt == 2){
if(!pop(pilhaTarefas))
cout << "\n\n -- -- -- -- Nao ha tarefas a retirar!! -- -- -- -- " << endl;
}
else if(opt == 3){
if(!imprime_pilha(pilhaTarefas))
cout << "\n\n -- -- -- -- Nao ha tarefas!! -- -- -- -- " << endl;
}
else if(opt == 4){
TTarefa TODO;
for(char i = 0; i < 20; i++)
{
memcpy(&TODO.nomeTarefa, "tarefa", sizeof("tarefa"));
TODO.tempo = i;
memcpy(&TODO.responsavel, "Fulano", sizeof("Fulano"));
TODO.codigo = ++codigoResponsavel;
push(pilhaTarefas, &TODO);
memset(&TODO, 0, sizeof(TTarefa));
}
}
else if(opt == 5){
for(int i = 0; i <= 20; i++)
{
if(!pop(pilhaTarefas))
break;
}
}
else if(opt == 6){
if(pilhaTarefas->top != NULL){
TTarefa maxT;
maxT.tempo = 0;
Node* temp;
temp = pilhaTarefas->top;
for(int i = 0; i <= pilhaTarefas->size; i++)
{
while(temp != NULL){
if(temp->tarefa.tempo > maxT.tempo){
maxT = pilhaTarefas->top->tarefa;
}
temp = temp->next;
}
}
cout << "\nTAREFA COM MAIOR TEMPO: " << maxT.nomeTarefa << " - Tempo: " << maxT.tempo << " - Responsavel: " << maxT.responsavel << " - Codigo: " << maxT.codigo << endl;
}
else
cout << "\n\n -- -- -- -- Nao ha tarefas!! -- -- -- -- " << endl;
}
else if(opt == 7){
char name[128] = {};
int count = 0;
if(pilhaTarefas->top != NULL){
cout << "Nome a pesquisar: ";
cin >> name;
Node* temp;
temp = pilhaTarefas->top;
for(int i = 0; i <= pilhaTarefas->size; i++)
{
while(temp != NULL){
//
//if(temp->tarefa.responsavel == name){
if(strcmp(temp->tarefa.responsavel, name) == 0){
/* int strcmp ( const char * str1, const char * str2 );
* Returns an integral value indicating the relationship between the strings:
* return value indicates
* <0 the first character that does not match has a lower value in ptr1 than in ptr2
* 0 the contents of both strings are equal
* >0 the first character that does not match has a greater value in ptr1 than in ptr2*/
count++;
}
//
temp = temp->next;
}
}
if(count == 0){
cout << "Nao ha tarefas para esta pessoa" << endl;
}
else{
cout << name << " possui: " << count << " tarefas!" << endl;
}
}
else
cout << "\n\n -- -- -- -- Nao ha tarefas!! -- -- -- -- " << endl;
}
else if(opt == 8){
//sair programa
}
else{
cout << "\n Aviso: Opcao Invalida!" << endl;
}
}while(opt!=8);
return 0;
}
| [
"37124989+dsicari@users.noreply.github.com"
] | 37124989+dsicari@users.noreply.github.com |
bff9458894336fa20cf0cf6b20af04fc9637d3bf | 0bcce7a816fbdbae3c7024734e329022418c6259 | /C++Progs/funcintro.cpp | cfbc35dc6224e3def21c307f0673e4608c5f5d51 | [] | no_license | nidhi-pant/Gen-Progs | 620fab185a827994d4bcd2ab57dda8e2e2463034 | fa7388acf67b13aae35c25d75778713ff1b0ad1c | refs/heads/master | 2020-12-29T05:52:56.163631 | 2020-02-05T17:11:39 | 2020-02-05T17:11:39 | 238,479,649 | 0 | 0 | null | 2020-02-05T15:13:17 | 2020-02-05T15:13:16 | null | UTF-8 | C++ | false | false | 533 | cpp | #include<iostream>
using namespace std;
void sayHi()
{
cout<<"Hi I am in the function !"<<endl;
}
int addNumbers(int a,int b)
{
return a+b;
}
double multiplyNumbers(double,double);
int main()
{
int result=0;
double result2=0.0;
cout<<"Hi I am in main!"<<endl;
sayHi();
result = addNumbers(10,5);
cout<<"Result Is : "<<result <<endl;
result2 = multiplyNumbers(10,5);
cout<<"Result Is : "<<result2 <<endl;
return 0;
}
double multiplyNumbers(double a,double b)
{
return a*b;
}
| [
"mnjups30@gmail.com"
] | mnjups30@gmail.com |
88fe94ac4f166863b5f26609932c1881d926a0f1 | 52482fb96fe7f3eed874db7a88c889ecd5bc34c5 | /src/ColorButton.h | 58648d123e8736455e2e6953d68b9f734bab1fcf | [] | no_license | rusingineer/EmulePlus | f3e29ca7ca853feea920c4cb5ffb0d0a13ed236e | 21955cd94d28cebdb3cf9c289f0aafa7a5cf3744 | refs/heads/master | 2021-01-17T11:54:26.925858 | 2016-06-20T12:22:32 | 2016-06-20T12:22:32 | 61,430,884 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,411 | h | //***************************************************************************
//
// AUTHOR: James White (feel free to remove or otherwise mangle any part)
//
// DESCRIPTION: This class is alarmingly similar to the CColourPicker control
// created by Chris Maunder of www.codeproject.com. It is so as it was blatantly
// copied from that class and is entirely dependant on his other great work
// in CColourPopup. I was hoping for (cough.. gag..) a more Microsoft look
// and I think this is pretty close. Hope you like it.
//
// ORIGINAL: http://www.codeproject.com/miscctrl/colour_picker.asp
//
//***************************************************************************
#pragma once
#include "ColourPopup.h"
void AFXAPI DDX_ColorButton(CDataExchange *pDX, int nIDC, COLORREF& crColour);
class CColorButton : public CButton
{
public:
DECLARE_DYNCREATE(CColorButton);
//***********************************************************************
// Name: CColorButton
// Description: Default constructor.
// Parameters: None.
// Return: None.
// Notes: None.
//***********************************************************************
CColorButton(void);
//***********************************************************************
// Name: CColorButton
// Description: Destructor.
// Parameters: None.
// Return: None.
// Notes: None.
//***********************************************************************
virtual ~CColorButton(void);
//***********************************************************************
//** Property Accessors **
//***********************************************************************
__declspec(property(get=GetColor,put=SetColor)) COLORREF Color;
__declspec(property(get=GetDefaultColor,put=SetDefaultColor)) COLORREF DefaultColor;
__declspec(property(get=GetTrackSelection,put=SetTrackSelection)) BOOL TrackSelection;
__declspec(property(put=SetCustomText)) LPCTSTR CustomText;
__declspec(property(put=SetDefaultText)) LPCTSTR DefaultText;
//***********************************************************************
// Name: GetColor
// Description: Returns the current color selected in the control.
// Parameters: void
// Return: COLORREF
// Notes: None.
//***********************************************************************
COLORREF GetColor(void) const;
//***********************************************************************
// Name: SetColor
// Description: Sets the current color selected in the control.
// Parameters: COLORREF Color
// Return: None.
// Notes: None.
//***********************************************************************
void SetColor(COLORREF Color);
//***********************************************************************
// Name: GetDefaultColor
// Description: Returns the color associated with the 'default' selection.
// Parameters: void
// Return: COLORREF
// Notes: None.
//***********************************************************************
COLORREF GetDefaultColor(void) const;
//***********************************************************************
// Name: SetDefaultColor
// Description: Sets the color associated with the 'default' selection.
// The default value is COLOR_APPWORKSPACE.
// Parameters: COLORREF Color
// Return: None.
// Notes: None.
//***********************************************************************
void SetDefaultColor(COLORREF Color);
//***********************************************************************
// Name: SetCustomText
// Description: Sets the text to display in the 'Custom' selection of the
// CColourPicker control, the default text is "More Colors...".
// Parameters: LPCTSTR tszText
// Return: None.
// Notes: None.
//***********************************************************************
void SetCustomText(LPCTSTR tszText);
//***********************************************************************
// Name: SetDefaultText
// Description: Sets the text to display in the 'Default' selection of the
// CColourPicker control, the default text is "Automatic". If
// this value is set to "", the 'Default' selection will not
// be shown.
// Parameters: LPCTSTR tszText
// Return: None.
// Notes: None.
//***********************************************************************
void SetDefaultText(LPCTSTR tszText);
//***********************************************************************
// Name: SetTrackSelection
// Description: Turns on/off the 'Track Selection' option of the control
// which shows the colors during the process of selection.
// Parameters: BOOL bTrack
// Return: None.
// Notes: None.
//***********************************************************************
void SetTrackSelection(BOOL bTrack);
//***********************************************************************
// Name: GetTrackSelection
// Description: Returns the state of the 'Track Selection' option.
// Parameters: void
// Return: BOOL
// Notes: None.
//***********************************************************************
BOOL GetTrackSelection(void) const;
//{{AFX_VIRTUAL(CColorButton)
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
protected:
virtual void PreSubclassWindow();
//}}AFX_VIRTUAL
protected:
//{{AFX_MSG(CColorButton)
afx_msg BOOL OnClicked();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
//}}AFX_MSG
afx_msg LONG OnSelEndOK(UINT lParam, LONG wParam);
afx_msg LONG OnSelEndCancel(UINT lParam, LONG wParam);
afx_msg LONG OnSelChange(UINT lParam, LONG wParam);
//***********************************************************************
// Name: DrawArrow
// Description: None.
// Parameters: CDC* pDC
// RECT* pRect
// int iDirection
// 0 - Down
// 1 - Up
// 2 - Left
// 3 - Right
// Return: static None.
// Notes: None.
//***********************************************************************
static void DrawArrow(CDC* pDC,
RECT* pRect,
int iDirection = 0,
COLORREF clrArrow = RGB(0,0,0));
DECLARE_MESSAGE_MAP()
COLORREF m_Color;
COLORREF m_DefaultColor;
CString m_strDefaultText;
CString m_strCustomText;
BOOL m_bPopupActive;
BOOL m_bTrackSelection;
private:
typedef CButton _Inherited;
};
| [
"makani@inbox.ru"
] | makani@inbox.ru |
aeaef7a1c23622c478060ae5888ef085a6ba46bf | 3ab68d8654fa769b7a864292fe8a2ea0239208c5 | /Segment Tree/LAZY PROPAGATION/1080 - Binary Simulation....T/main.cpp | 13475f7124a039636d71de7a392b2bc2314bc8f8 | [] | no_license | amp1590/Light-OJ | ba7e71e0904bd3b75782aeca5759c29e657b5c99 | 66398fa23a236b7e80317b9c6c3b9c610da1c952 | refs/heads/master | 2021-07-10T04:44:23.019626 | 2017-10-10T10:45:50 | 2017-10-10T10:45:50 | 82,906,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,169 | cpp | #include <bits/stdc++.h>
#define pf printf
#define sf(a) scanf("%d",&a)
#define sfl(a) scanf("%lld",&a)
#define sff(a,b) scanf("%d %d",&a,&b)
#define sffl(a,b) scanf("%lld %lld",&a,&b)
#define sfff(a,b,c) scanf("%d %d %d",&a,&b,&c)
#define sfffl(a,b,c) scanf("%lld %lld %lld",&a,&b,&c)
#define sffff(a,b,c,d) scanf("%d %d %d %d",&a,&b,&c,&d)
#define sffffl(a,b,c,d) scanf("%lld %lld %lld %lld",&a,&b,&c,&d)
#define sfffff(a,b,c,d,e) scanf("%d %d %d %d %d",&a,&b,&c,&d,&e)
#define sfffffl(a,b,c,d,e) scanf("%lld %lld %lld %lld %lld",&a,&b,&c,&d,&e)
#define sfc(a) scanf("%c",&a)
#define ms(a,b) memset(a,b,sizeof(a))
#define pb(a) push_back(a)
#define pbp(a,b) push_back({a,b})
#define db double
#define ft float
#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define sz(x) x.size()
#define qu queue
#define pqu priority_queue
#define vc vector
#define vi vector<int>
#define vll vector<long long>
#define pii pair<int,int>
#define pis pair<int,string>
#define psi pair<string,int>
#define all(x) x.begin(),x.end()
#define CIN ios_base::sync_with_stdio(0); cin.tie(0)
#define max3(a, b, c) max(a, b) > max(b, c) ? max(a, b) : max(b, c)
#define min3(a, b, c) min(a, b) < min(b, c) ? min(a, b) : min(b, c)
#define for0(i,n) for(int i=0;i<n;i++)
#define for1(i,n) for(int i=1;i<=n;i++)
#define forcmp(i,n) for(int i=1;i<n;i++)
#define forrev(i,n) for(int i=n-1; i>=0; i--)
#define forab(i,a,b) for(int i=a;i<=b;i++)
#define forba(i,b,a) for(int i=b;i>=a;i--)
#define stlloop(x) for(__typeof(x.begin()) it=x.begin();it!=x.end();it++)
#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) ((a)*((b)/gcd(a,b)))
#define case1(z) cout<<"Case "<<z<<": "
#define case2(z) printf("Case %d:\n",z)
#define PI acos(-1) //3.14159265358979323846264338328
#define valid(tx,ty) tx>=0 && tx<row && ty>=0 && ty<col
#define intlim 2147483648
#define MAX 1000000
#define inf 100000000
#define mx 100005
/*------------------------------Graph Moves----------------------------*/
//const int fx[]={+1,-1,+0,+0};
//const int fy[]={+0,+0,+1,-1};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; // Kings Move
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; // Kings Move
//const int fx[]={-2, -2, -1, -1, 1, 1, 2, 2}; // Knights Move
//const int fy[]={-1, 1, -2, 2, -2, 2, -1, 1}; // Knights Move
/*---------------------------------------------------------------------*/
using namespace std;
struct data
{
ll prop,sum;
};
bool c;
data tree[3*mx],input[mx];
void build(int node,int low,int high)
{
if(low==high) {tree[node].sum=input[low].sum;return; }
int mid=(low+high)/2;
int left=2*node;
int right=2*node+1;
build(left,low,mid);
build(right,mid+1,high);
}
void pushdown(int node, int low, int high)
{
if(tree[node].prop!=0)
{
int mid=(low+high)/2;
int left=2*node;
int right=2*node+1;
tree[left].prop+=tree[node].prop;
tree[right].prop+=tree[node].prop;
tree[node].prop=0;
}
}
void update(int node, int low, int high, int qlow, int qhigh)
{
if(high<qlow || low>qhigh) return; ///No Overlap
else if(low>=qlow && high<=qhigh) ///Total Overlap
{
tree[node].prop++;
return;
}
pushdown(node,low,high);
int left=node*2;
int right=left+1;
int mid=(low+high)/2;
update(left,low,mid,qlow,qhigh);
update(right,mid+1,high,qlow,qhigh);
}
int query(int node, int low, int high, int qlow, int qhigh)
{
if(high<qlow || low>qhigh) return 0; ///No Overlap
else if(low>=qlow && high<=qhigh) ///Total Overlap
{
if(tree[node].prop%2==1) c= 1-tree[node].sum;
else c= tree[node].sum;
return 0;
}
pushdown(node,low,high);
int left=node*2;
int right=left+1;
int mid=(low+high)/2;
query(left,low,mid,qlow,qhigh);
query(right,mid+1,high,qlow,qhigh);
}
int main()
{
//CIN;
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int t;
sf(t);
for1(z,t)
{
string str;
cin>>str,s;
for0(i,sz(str)) input[i+1].sum=str[i]-'0';
build(1,1,sz(str));
int q,qlow,qhigh,val;
sf(q);
case2(z);
for1(i,q)
{
cin>>s
if(s=="I")
{
sff(qlow,qhigh);
update(1,1,sz(str),qlow,qhigh);
}
else
{
sf(val);
query(1,1,sz(str),val,val);
pf("%d\n",c);
}
}
ms(tree,0);
}
return 0;
}
| [
"arunima1590@gmail.com"
] | arunima1590@gmail.com |
f7e9e78ef3f7113f0589fb8d28517564ba8da3ff | 3dc76228d000d893fccde65e858432257f9243a3 | /Test_regex.cpp | a8e1eca906b52152ddcc2d287ae35e6ab5ecf40e | [
"MIT"
] | permissive | peku33/proZPRd | 63c721fb48b937e02017082cc51c0e72bddd0374 | 632097bc8221116c57b9ae5e76dafd0a63d57fe6 | refs/heads/master | 2016-08-08T12:21:37.989093 | 2015-06-09T23:42:27 | 2015-06-09T23:42:27 | 33,402,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 197 | cpp | #include <iostream>
#include <regex>
int main()
{
std::regex R(".*\\.php$");
std::string Test("alamakota.php");
std::cout << (std::regex_match(Test, R) ? "Y" : "N") << std::endl;
return 0;
} | [
"peku33@gmail.com"
] | peku33@gmail.com |
9bb77bf2306d14daf5819ae7ffe5b51b2c55e7f6 | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /cpdp/include/tencentcloud/cpdp/v20190820/model/QueryTransferDetailResponse.h | 0ddfe823bda25aa139cd03a50417a7ed99d6e07a | [
"Apache-2.0"
] | permissive | caogenwang/tencentcloud-sdk-cpp | 84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d | 6e18ee6622697a1c60a20a509415b0ddb8bdeb75 | refs/heads/master | 2023-08-23T12:37:30.305972 | 2021-11-08T01:18:30 | 2021-11-08T01:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,867 | h | /*
* 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.
*/
#ifndef TENCENTCLOUD_CPDP_V20190820_MODEL_QUERYTRANSFERDETAILRESPONSE_H_
#define TENCENTCLOUD_CPDP_V20190820_MODEL_QUERYTRANSFERDETAILRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Cpdp
{
namespace V20190820
{
namespace Model
{
/**
* QueryTransferDetail返回参数结构体
*/
class QueryTransferDetailResponse : public AbstractModel
{
public:
QueryTransferDetailResponse();
~QueryTransferDetailResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取商户号。
示例值:19300009329
* @return MerchantId 商户号。
示例值:19300009329
*/
std::string GetMerchantId() const;
/**
* 判断参数 MerchantId 是否已赋值
* @return MerchantId 是否已赋值
*/
bool MerchantIdHasBeenSet() const;
/**
* 获取商家批次单号。
商户系统内部的商家批次单号,此参数只能由数字、字母组成,商户系统内部唯一,UTF8编码,最多32个字符。
示例值:plfk2020042013
* @return MerchantBatchNo 商家批次单号。
商户系统内部的商家批次单号,此参数只能由数字、字母组成,商户系统内部唯一,UTF8编码,最多32个字符。
示例值:plfk2020042013
*/
std::string GetMerchantBatchNo() const;
/**
* 判断参数 MerchantBatchNo 是否已赋值
* @return MerchantBatchNo 是否已赋值
*/
bool MerchantBatchNoHasBeenSet() const;
/**
* 获取微信批次单号。
微信商家转账系统返回的唯一标识。
示例值:1030000071100999991182020050700019480001
* @return BatchId 微信批次单号。
微信商家转账系统返回的唯一标识。
示例值:1030000071100999991182020050700019480001
*/
std::string GetBatchId() const;
/**
* 判断参数 BatchId 是否已赋值
* @return BatchId 是否已赋值
*/
bool BatchIdHasBeenSet() const;
/**
* 获取商家明细单号。
商户系统内部的商家明细单号
示例值:plfk2020042013
* @return MerchantDetailNo 商家明细单号。
商户系统内部的商家明细单号
示例值:plfk2020042013
*/
std::string GetMerchantDetailNo() const;
/**
* 判断参数 MerchantDetailNo 是否已赋值
* @return MerchantDetailNo 是否已赋值
*/
bool MerchantDetailNoHasBeenSet() const;
/**
* 获取微信明细单号。
微信区分明细单返回的唯一标识。
示例值:1030000071100999991182020050700019480001
* @return DetailId 微信明细单号。
微信区分明细单返回的唯一标识。
示例值:1030000071100999991182020050700019480001
*/
std::string GetDetailId() const;
/**
* 判断参数 DetailId 是否已赋值
* @return DetailId 是否已赋值
*/
bool DetailIdHasBeenSet() const;
/**
* 获取明细状态。
PROCESSING:转账中,正在处理,结果未明;
SUCCESS:转账成功;
FAIL:转账失败,需要确认失败原因以后,再决定是否重新发起地该笔明细的转账。
示例值:SUCCESS
* @return DetailStatus 明细状态。
PROCESSING:转账中,正在处理,结果未明;
SUCCESS:转账成功;
FAIL:转账失败,需要确认失败原因以后,再决定是否重新发起地该笔明细的转账。
示例值:SUCCESS
*/
std::string GetDetailStatus() const;
/**
* 判断参数 DetailStatus 是否已赋值
* @return DetailStatus 是否已赋值
*/
bool DetailStatusHasBeenSet() const;
/**
* 获取转账金额。
单位为分。
示例值:200
* @return TransferAmount 转账金额。
单位为分。
示例值:200
*/
uint64_t GetTransferAmount() const;
/**
* 判断参数 TransferAmount 是否已赋值
* @return TransferAmount 是否已赋值
*/
bool TransferAmountHasBeenSet() const;
/**
* 获取失败原因。
如果转账失败则有失败原因
ACCOUNT_FROZEN:账户冻结
REAL_NAME_CHECK_FAIL:用户未实名
NAME_NOT_CORRECT:用户姓名校验失败
OPENID_INVALID:Openid校验失败
TRANSFER_QUOTA_EXCEED:超过用户单笔收款额度
DAY_RECEIVED_QUOTA_EXCEED:超过用户单日收款额度
MONTH_RECEIVED_QUOTA_EXCEED:超过用户单月收款额度
DAY_RECEIVED_COUNT_EXCEED:超过用户单日收款次数
PRODUCT_AUTH_CHECK_FAIL:产品权限校验失败
OVERDUE_CLOSE:转账关闭
ID_CARD_NOT_CORRECT:用户身份证校验失败
ACCOUNT_NOT_EXIST:用户账户不存在
TRANSFER_RISK:转账存在风险
示例值:ACCOUNT_FROZEN
注意:此字段可能返回 null,表示取不到有效值。
* @return FailReason 失败原因。
如果转账失败则有失败原因
ACCOUNT_FROZEN:账户冻结
REAL_NAME_CHECK_FAIL:用户未实名
NAME_NOT_CORRECT:用户姓名校验失败
OPENID_INVALID:Openid校验失败
TRANSFER_QUOTA_EXCEED:超过用户单笔收款额度
DAY_RECEIVED_QUOTA_EXCEED:超过用户单日收款额度
MONTH_RECEIVED_QUOTA_EXCEED:超过用户单月收款额度
DAY_RECEIVED_COUNT_EXCEED:超过用户单日收款次数
PRODUCT_AUTH_CHECK_FAIL:产品权限校验失败
OVERDUE_CLOSE:转账关闭
ID_CARD_NOT_CORRECT:用户身份证校验失败
ACCOUNT_NOT_EXIST:用户账户不存在
TRANSFER_RISK:转账存在风险
示例值:ACCOUNT_FROZEN
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetFailReason() const;
/**
* 判断参数 FailReason 是否已赋值
* @return FailReason 是否已赋值
*/
bool FailReasonHasBeenSet() const;
/**
* 获取转账发起时间。
遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
* @return InitiateTime 转账发起时间。
遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetInitiateTime() const;
/**
* 判断参数 InitiateTime 是否已赋值
* @return InitiateTime 是否已赋值
*/
bool InitiateTimeHasBeenSet() const;
/**
* 获取转账更新时间。
遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
* @return UpdateTime 转账更新时间。
遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetUpdateTime() const;
/**
* 判断参数 UpdateTime 是否已赋值
* @return UpdateTime 是否已赋值
*/
bool UpdateTimeHasBeenSet() const;
/**
* 获取用户名。
示例值:张三
注意:此字段可能返回 null,表示取不到有效值。
* @return UserName 用户名。
示例值:张三
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetUserName() const;
/**
* 判断参数 UserName 是否已赋值
* @return UserName 是否已赋值
*/
bool UserNameHasBeenSet() const;
/**
* 获取转账备注。
单条转账备注(微信用户会收到该备注)。UTF8编码,最多32字符。
示例值:2020年4月报销
注意:此字段可能返回 null,表示取不到有效值。
* @return TransferRemark 转账备注。
单条转账备注(微信用户会收到该备注)。UTF8编码,最多32字符。
示例值:2020年4月报销
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetTransferRemark() const;
/**
* 判断参数 TransferRemark 是否已赋值
* @return TransferRemark 是否已赋值
*/
bool TransferRemarkHasBeenSet() const;
/**
* 获取商家绑定公众号APPID。
注意:此字段可能返回 null,表示取不到有效值。
* @return MerchantAppId 商家绑定公众号APPID。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetMerchantAppId() const;
/**
* 判断参数 MerchantAppId 是否已赋值
* @return MerchantAppId 是否已赋值
*/
bool MerchantAppIdHasBeenSet() const;
/**
* 获取用户openId。
注意:此字段可能返回 null,表示取不到有效值。
* @return OpenId 用户openId。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetOpenId() const;
/**
* 判断参数 OpenId 是否已赋值
* @return OpenId 是否已赋值
*/
bool OpenIdHasBeenSet() const;
private:
/**
* 商户号。
示例值:19300009329
*/
std::string m_merchantId;
bool m_merchantIdHasBeenSet;
/**
* 商家批次单号。
商户系统内部的商家批次单号,此参数只能由数字、字母组成,商户系统内部唯一,UTF8编码,最多32个字符。
示例值:plfk2020042013
*/
std::string m_merchantBatchNo;
bool m_merchantBatchNoHasBeenSet;
/**
* 微信批次单号。
微信商家转账系统返回的唯一标识。
示例值:1030000071100999991182020050700019480001
*/
std::string m_batchId;
bool m_batchIdHasBeenSet;
/**
* 商家明细单号。
商户系统内部的商家明细单号
示例值:plfk2020042013
*/
std::string m_merchantDetailNo;
bool m_merchantDetailNoHasBeenSet;
/**
* 微信明细单号。
微信区分明细单返回的唯一标识。
示例值:1030000071100999991182020050700019480001
*/
std::string m_detailId;
bool m_detailIdHasBeenSet;
/**
* 明细状态。
PROCESSING:转账中,正在处理,结果未明;
SUCCESS:转账成功;
FAIL:转账失败,需要确认失败原因以后,再决定是否重新发起地该笔明细的转账。
示例值:SUCCESS
*/
std::string m_detailStatus;
bool m_detailStatusHasBeenSet;
/**
* 转账金额。
单位为分。
示例值:200
*/
uint64_t m_transferAmount;
bool m_transferAmountHasBeenSet;
/**
* 失败原因。
如果转账失败则有失败原因
ACCOUNT_FROZEN:账户冻结
REAL_NAME_CHECK_FAIL:用户未实名
NAME_NOT_CORRECT:用户姓名校验失败
OPENID_INVALID:Openid校验失败
TRANSFER_QUOTA_EXCEED:超过用户单笔收款额度
DAY_RECEIVED_QUOTA_EXCEED:超过用户单日收款额度
MONTH_RECEIVED_QUOTA_EXCEED:超过用户单月收款额度
DAY_RECEIVED_COUNT_EXCEED:超过用户单日收款次数
PRODUCT_AUTH_CHECK_FAIL:产品权限校验失败
OVERDUE_CLOSE:转账关闭
ID_CARD_NOT_CORRECT:用户身份证校验失败
ACCOUNT_NOT_EXIST:用户账户不存在
TRANSFER_RISK:转账存在风险
示例值:ACCOUNT_FROZEN
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_failReason;
bool m_failReasonHasBeenSet;
/**
* 转账发起时间。
遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_initiateTime;
bool m_initiateTimeHasBeenSet;
/**
* 转账更新时间。
遵循rfc3339标准格式。格式为YYYY-MM-DDTHH:mm:ss.sss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss.sss表示时分秒毫秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35.120+08:00表示北京时间2015年05月20日13点29分35秒。
示例值:2015-05-20T13:29:35.120+08:00
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_updateTime;
bool m_updateTimeHasBeenSet;
/**
* 用户名。
示例值:张三
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_userName;
bool m_userNameHasBeenSet;
/**
* 转账备注。
单条转账备注(微信用户会收到该备注)。UTF8编码,最多32字符。
示例值:2020年4月报销
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_transferRemark;
bool m_transferRemarkHasBeenSet;
/**
* 商家绑定公众号APPID。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_merchantAppId;
bool m_merchantAppIdHasBeenSet;
/**
* 用户openId。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_openId;
bool m_openIdHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_CPDP_V20190820_MODEL_QUERYTRANSFERDETAILRESPONSE_H_
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
9a20ec3c26a1131b8db0f2d8da57c08469ca04c7 | 3da738854134e337aedf5adedeb3361d91287df4 | /menu.h | 7b7d3ebc3ed81b9e1eabc65ef49b53638b006279 | [] | no_license | roughiz/checkers-psp-game | 937ee9442e43a71d1f5523732a47c455a5406160 | 3982e103468da0ff47cb6c90466418d934ee609a | refs/heads/master | 2022-08-04T17:31:03.359055 | 2020-05-12T16:37:36 | 2020-05-12T16:37:36 | 263,386,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | h | #ifndef __MENU_H_
#define __MENU_H_
#include <pspkernel.h>
#include <pspctrl.h>
#include "gstate.h"
#include "menuitem.h"
const int MENU_START_Y = 150;
const float MENU_DELAY = 0.25f;
const float MENU_START_DELAY = 0.5f;
class Menu {
private:
int selected;
int menuItems;
u64 thisMenuMove;
u64 lastMenuMove;
u64 startMenuTime;
u32 tickResolution;
gstate gamestate;
MenuItem menuData[10];
public:
Menu(gstate dgstate);
virtual ~Menu();
gstate Run(SceCtrlData &pad);
void AddItem(char *menuText, gstate gs);
};
#endif /*__MENU_H_*/
| [
"roughiz@Desktop.fr"
] | roughiz@Desktop.fr |
5f7fac36e96f463f44ceb21446d7aee7472c7c78 | a9895a1a97c5dd12447c8f96ab7c550f768da6b2 | /examples/udpBasics/udpBasics.ino | d03887518cdef1e5bce730109cd68feab47919bf | [] | no_license | hex705/arduinoOSC | 25c0a3c721022982071f78f56436dd9dc422abc1 | 5ae8181c66f799d28f60f69abe35c68cd55dc7eb | refs/heads/master | 2022-08-28T10:25:11.338101 | 2022-08-10T15:11:59 | 2022-08-10T15:11:59 | 82,565,326 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,818 | ino |
// MESSAGE PROTOCOL OBJECT
#include <OscUDP.h>
// hardware libraries to access use the shield
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// arduino needs us to start ethernet, then start UDP
// http://arduino.cc/en/Reference/EthernetBegin
// Enter a MAC address and IP address for your SHIELD.
// The IP address will be dependent on your local network
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// listeningIP == SHIELD initialization IP
IPAddress listeningIP(141,117,45,176); // you need to set this
// listening -- port
unsigned int listeningPort = 12001; // local port to listen on
// speaking
// set up our destination NODE
NetAddress destination;
IPAddress destinationIP( 141,117,45,82 );
int destinationPort = 12000;
// setup a UDP object
EthernetUDP UDP;
// OUR OSC MESSAGE OBJECT
OscUDP etherOSC;
// timer variable
long timer;
void setup() {
// some local debug -- we can see this in serial port
Serial.begin(9600);
// start ethernet on the shield
Ethernet.begin(mac,listeningIP);
// print Arduino's IP
Serial.println(Ethernet.localIP());
// start UDP object, listening on port listeningPort
UDP.begin(listeningPort);
// set up our communication protocol
// pass the UDP object to OSC
etherOSC.begin(UDP);
// define our destination location
destination.set(destinationIP, destinationPort);
// local hardware setup
pinMode(2, OUTPUT); // note can't use 13 for UDP becasue of shield
Serial.println("starting");
}
void loop() {
// send a message every 100 ms
// avoid using delay() since it just blocks everything
// so here is a simple timer that controls how often we send
long now = millis();
if (now-timer > 100) {
// build a message, start with address pattern
OscMessage msg("/arduinoEthernetSays");
// add a data point (can add many)
msg.add(digitalRead(2)); // <-- this could be any data -- its our LED state
// actually do the sending
etherOSC.send(msg, destination);
// reset the timer
timer = now;
// local debug -- you can get rid of this
Serial.println("send one");
} // end if
// important! non-blocking listen routine
etherOSC.listen(); // if there is data waiting, this will trigger OSC EVENT
}
void oscEvent(OscMessage &m) { // *note the & before msg
// receive a message
Serial.println("got a message");
// in arduino, we plug events in the EVENT method
m.plug("/led", myFunction);
}
void myFunction(OscMessage &m) { // *note the & before msg
// getting to the message data
Serial.println("led");
// getType takes position as a parameter
int value = m.getInt(0);
if (value == 0) digitalWrite(2, LOW);
if (value == 1) digitalWrite(2, HIGH);
}
| [
"steve.daniels@ryerson.ca"
] | steve.daniels@ryerson.ca |
7836d10d56620780e02103fff5741f8f31dfe076 | edfdb97e31c75b7a21704db998023b3d7583f4fb | /iOS/Classes/Native/mscorlib_System_Comparison_1_gen1788700390.h | 245d9c80c1b9bbb7f70b237fc60b3119f2684f5f | [] | no_license | OmnificenceTeam/ICA_Iron_App | b643ab80393e17079031d64fec6fa95de0de0d81 | 7e4c8616ec2e2b358d68d446d4b40d732c085ca9 | refs/heads/master | 2021-07-16T06:53:58.273883 | 2017-10-23T10:52:21 | 2017-10-23T10:52:21 | 107,165,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_MulticastDelegate3201952435.h"
// RogoDigital.Lipsync.BlendSystemUser
struct BlendSystemUser_t526961539;
// System.IAsyncResult
struct IAsyncResult_t1999651008;
// System.AsyncCallback
struct AsyncCallback_t163412349;
// System.Object
struct Il2CppObject;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Comparison`1<RogoDigital.Lipsync.BlendSystemUser>
struct Comparison_1_t1788700390 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"admin@medtrixhealthcare.com"
] | admin@medtrixhealthcare.com |
322d172c0e56339bb5ba9e524c779cab7b658e41 | 7fcbc645c2b03d5c792363d5eaa4bae6a6ecac6b | /jni/main.cpp | 8478992ffeeb76edb436ae46fbf51d8854a2ea45 | [] | no_license | Fuwordy/Blocklauncher-ADDONS | ba9d62bda68998390f0ec3799213279d7c60d59c | 942ca8d846e535f829fc8f31fc3410e988bcd113 | refs/heads/master | 2021-01-01T06:11:55.739344 | 2015-01-08T03:14:40 | 2015-01-08T03:14:40 | 28,945,740 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 343 | cpp | #include <jni.h>
#include <dlfcn.h>
#include <android/log.h>
#include <stdlib.h>
#include <mcpe.h>
#include <Substrate.h>
#define LOG_TAG "fuwordy"
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
LOGI("Hello world!");
return JNI_VERSION_1_2;
}
| [
"Fuwordy@gmail.com"
] | Fuwordy@gmail.com |
c9a70c06e7e3f1f67335f62c3bc51bf73048c4af | 887b19aaff44a6578918fce2a20c40d5aff20619 | /Plugins/Wwise/Source/AudiokineticTools/Private/DetailsCustomization/AkSurfaceReflectorSetDetailsCustomization.cpp | d8eee2f7eb62a069dec2782142f9088de388072c | [] | no_license | TheAmazingZigZag/Camp | 1931aea7bb9145784a8fb6b269f7d1c7fd878e37 | d26761c7df04c67d6e60eb250fdee1f505b1deb4 | refs/heads/master | 2023-04-15T14:22:40.466740 | 2021-04-23T20:15:45 | 2021-04-23T20:15:45 | 360,970,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,910 | cpp | /********************************************************************************
The content of the files in this repository include portions of the AUDIOKINETIC
Wwise Technology released in source code form as part of the SDK package.
Commercial License Usage
Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology
may use these files in accordance with the end user license agreement provided
with the software or, alternatively, in accordance with the terms contained in a
written agreement between you and Audiokinetic Inc.
Copyright (c) 2021 Audiokinetic Inc.
********************************************************************************/
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "AkSurfaceReflectorSetDetailsCustomization.h"
#include "AkSurfaceReflectorSetComponent.h"
#include "AkComponent.h"
#include "DetailLayoutBuilder.h"
#include "DetailCategoryBuilder.h"
#include "DetailWidgetRow.h"
#include "ScopedTransaction.h"
#include "IPropertyUtilities.h"
#include "Widgets/Text/STextBlock.h"
#include "Widgets/Views/SExpanderArrow.h"
#include "Widgets/Input/SButton.h"
#include "GameFramework/Volume.h"
#include "Builders/ConeBuilder.h"
#include "Builders/CubeBuilder.h"
#include "Builders/CurvedStairBuilder.h"
#include "Builders/CylinderBuilder.h"
#include "Builders/LinearStairBuilder.h"
#include "Builders/SpiralStairBuilder.h"
#include "Builders/TetrahedronBuilder.h"
#include "Model.h"
#define LOCTEXT_NAMESPACE "AudiokineticTools"
//////////////////////////////////////////////////////////////////////////
// FAkSurfaceReflectorSetDetailsCustomization
FAkSurfaceReflectorSetDetailsCustomization::FAkSurfaceReflectorSetDetailsCustomization()
{
ReflectorSetBeingCustomized = nullptr;
}
FAkSurfaceReflectorSetDetailsCustomization::~FAkSurfaceReflectorSetDetailsCustomization()
{
if (ReflectorSetBeingCustomized && ReflectorSetBeingCustomized->IsValidLowLevelFast() && ReflectorSetBeingCustomized->GetOnRefreshDetails() )
{
if (ReflectorSetBeingCustomized->GetOnRefreshDetails()->IsBoundToObject(this))
{
ReflectorSetBeingCustomized->ClearOnRefreshDetails();
}
ReflectorSetBeingCustomized = nullptr;
}
}
TSharedRef<IDetailCustomization> FAkSurfaceReflectorSetDetailsCustomization::MakeInstance()
{
return MakeShareable(new FAkSurfaceReflectorSetDetailsCustomization());
}
void FAkSurfaceReflectorSetDetailsCustomization::CustomizeDetails(IDetailLayoutBuilder& DetailLayout)
{
MyDetailLayout = &DetailLayout;
TArray<TWeakObjectPtr<UObject>> ObjectsBeingCustomized;
DetailLayout.GetObjectsBeingCustomized(ObjectsBeingCustomized);
if (ObjectsBeingCustomized.Num() != 1)
{
return;
}
ReflectorSetBeingCustomized = Cast<UAkSurfaceReflectorSetComponent>(ObjectsBeingCustomized[0].Get());
if (ReflectorSetBeingCustomized)
{
SetupGeometryModificationHandlers();
IDetailCategoryBuilder& DetailCategory = DetailLayout.EditCategory("AcousticSurfaces");
auto AcousticPolysPropHandle = DetailLayout.GetProperty("AcousticPolys");
DetailLayout.HideProperty("AcousticPolys");
if (ReflectorSetBeingCustomized->bEnableSurfaceReflectors)
{
DetailCategory.AddCustomRow(LOCTEXT("AkHeader", "Header"))
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.FillWidth(0.05f)
.VAlign(VAlign_Center)
[
SNew(SSpacer)
]
+ SHorizontalBox::Slot()
.FillWidth(0.70f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("AkAcousticTexture", "Acoustic Texture"))
]
+ SHorizontalBox::Slot()
.FillWidth(0.30f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("AkOcclusion", "Occlusion"))
]
+ SHorizontalBox::Slot()
.FillWidth(0.25f)
.Padding(8.0f, 1.0f, 3.0f, 3.0f)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(LOCTEXT("AkEnableSurface", "Enable Surface"))
]
];
for (int i = 0; i < ReflectorSetBeingCustomized->AcousticPolys.Num(); i++)
{
auto CurrentAcousticPolyPropHandle = AcousticPolysPropHandle->AsArray()->GetElement(i);
bool valid1 = CurrentAcousticPolyPropHandle->IsValidHandle();
auto TexturePropertyHandle = CurrentAcousticPolyPropHandle->GetChildHandle("Texture");
bool valid2 = TexturePropertyHandle->IsValidHandle();
auto OcclusionPropertyHandle = CurrentAcousticPolyPropHandle->GetChildHandle("Occlusion");
bool valid3 = OcclusionPropertyHandle->IsValidHandle();
auto EnablePolyPropertyHandle = CurrentAcousticPolyPropHandle->GetChildHandle("EnableSurface");
bool valid4 = EnablePolyPropertyHandle->IsValidHandle();
DetailCategory.AddCustomRow(TexturePropertyHandle->GetPropertyDisplayName())
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.FillWidth(0.05f)
.VAlign(VAlign_Center)
[
SNew(STextBlock)
.Text(FText::AsNumber(i))
]
+ SHorizontalBox::Slot()
.FillWidth(0.70f)
[
TexturePropertyHandle->CreatePropertyValueWidget()
]
+ SHorizontalBox::Slot()
.FillWidth(0.30f)
.Padding(10.0f, 0.0f, 10.0f, 20.0f)
[
OcclusionPropertyHandle->CreatePropertyValueWidget()
]
+ SHorizontalBox::Slot()
.FillWidth(0.25f)
.Padding(8.0f, 1.0f, 3.0f, 1.0f)
.HAlign(HAlign_Center)
[
EnablePolyPropertyHandle->CreatePropertyValueWidget()
]
];
}
}
else
{
DetailLayout.HideCategory("Acoustic Surface Properties");
}
}
}
#define REGISTER_PROPERTY_CHANGED(Class, Property) \
auto Property ## Handle = MyDetailLayout->GetProperty(GET_MEMBER_NAME_CHECKED(Class, Property), Class::StaticClass(), BrushBuilderName); \
if (Property ## Handle->IsValidHandle()) Property ## Handle->SetOnPropertyValueChanged(FSimpleDelegate::CreateSP(this, &FAkSurfaceReflectorSetDetailsCustomization::OnGeometryChanged))
void FAkSurfaceReflectorSetDetailsCustomization::SetupGeometryModificationHandlers()
{
static const FName BrushBuilderName(TEXT("BrushBuilder"));
auto ParentBrush = ReflectorSetBeingCustomized->ParentBrush;
if(!ParentBrush)
return;
auto EnableHandle = MyDetailLayout->GetProperty("bEnableSurfaceReflectors");
EnableHandle->SetOnPropertyValueChanged(FSimpleDelegate::CreateSP(this, &FAkSurfaceReflectorSetDetailsCustomization::OnEnableValueChanged));
// This is to detect if the BrushBuilder changed.
if (ReflectorSetBeingCustomized->AcousticPolys.Num() != ParentBrush->Nodes.Num())
MyDetailLayout->GetPropertyUtilities()->EnqueueDeferredAction(FSimpleDelegate::CreateSP(this, &FAkSurfaceReflectorSetDetailsCustomization::OnGeometryChanged));
// Need to register to a LOT of different properties, because some change the geometry but don't force a refresh of the details panel
AVolume* ParentVolume = Cast<AVolume>(ReflectorSetBeingCustomized->GetOwner());
UClass* BrushBuilderClass = nullptr;
if (ParentVolume && ParentVolume->BrushBuilder)
{
BrushBuilderClass = ParentVolume->BrushBuilder->GetClass();
if (BrushBuilderClass == nullptr)
{
return;
}
}
if (BrushBuilderClass == UConeBuilder::StaticClass())
{
REGISTER_PROPERTY_CHANGED(UConeBuilder, Sides);
REGISTER_PROPERTY_CHANGED(UConeBuilder, Hollow);
}
else if (BrushBuilderClass == UCubeBuilder::StaticClass())
{
REGISTER_PROPERTY_CHANGED(UCubeBuilder, Hollow);
REGISTER_PROPERTY_CHANGED(UCubeBuilder, Tessellated);
}
else if (BrushBuilderClass == UCurvedStairBuilder::StaticClass())
{
REGISTER_PROPERTY_CHANGED(UCurvedStairBuilder, NumSteps);
}
else if (BrushBuilderClass == UCylinderBuilder::StaticClass())
{
REGISTER_PROPERTY_CHANGED(UCylinderBuilder, Sides);
REGISTER_PROPERTY_CHANGED(UCylinderBuilder, Hollow);
}
else if (BrushBuilderClass == ULinearStairBuilder::StaticClass())
{
REGISTER_PROPERTY_CHANGED(ULinearStairBuilder, NumSteps);
}
else if (BrushBuilderClass == USpiralStairBuilder::StaticClass())
{
REGISTER_PROPERTY_CHANGED(USpiralStairBuilder, NumSteps);
}
else if (BrushBuilderClass == UTetrahedronBuilder::StaticClass())
{
REGISTER_PROPERTY_CHANGED(UTetrahedronBuilder, SphereExtrapolation);
}
FOnRefreshDetails DetailsChanged = FOnRefreshDetails::CreateRaw(this, &FAkSurfaceReflectorSetDetailsCustomization::OnEnableValueChanged);
ReflectorSetBeingCustomized->SetOnRefreshDetails(DetailsChanged);
}
void FAkSurfaceReflectorSetDetailsCustomization::OnEnableValueChanged()
{
ReflectorSetBeingCustomized->ClearOnRefreshDetails();
MyDetailLayout->ForceRefreshDetails();
}
void FAkSurfaceReflectorSetDetailsCustomization::OnGeometryChanged()
{
ReflectorSetBeingCustomized->UpdatePolys();
ReflectorSetBeingCustomized->ClearOnRefreshDetails();
}
//////////////////////////////////////////////////////////////////////////
#undef LOCTEXT_NAMESPACE | [
"maxmen30@icloud.com"
] | maxmen30@icloud.com |
627c90a872af9b5030daa60905073119e4dfdd47 | d6ff0a35c6e3daafeff703d088036f32893faed1 | /moba_server/netbus/netbus.cc | 3e5823702d38c5129ca7b5fe7c4c2e84f634681c | [] | no_license | HalfCheng/unity_moba_project | c08678908be5f12ac84c673277ef49a401d3bfa6 | 869c45ea337586e471fa496691cb870b5b143e9a | refs/heads/main | 2023-02-01T23:16:48.261574 | 2020-12-20T15:46:22 | 2020-12-20T15:46:22 | 312,949,474 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,340 | cc | #include "netbus.h"
#include <iostream>
#include <string>
#include "uv.h"
#include "session_uv.h"
#include "ws_protocol.h"
#include "tp_protocol.h"
#include "proto_man.h"
#include "service_man.h"
#include "../utils/logger.h"
#include "session_udp.h"
using namespace std;
#include "../utils/small_allocer.h"
#define my_malloc small_alloc
#define my_free small_free
//#define SERVER_ADDRESS "192.168.1.104"
#define SERVER_ADDRESS "127.0.0.1"
extern "C" {
static void on_uv_udp_send_end(uv_udp_send_t* req, int statuc)
{
if (statuc == 0)
{
my_free(req);
}
}
static void on_recv_client_cmd(session* s, unsigned char* body, int len)
{
struct raw_cmd raw;
if(proto_man::decode_raw_cmd(body, len, &raw))
{
if (!service_man::on_recv_raw_cmd(s, &raw))
{
s->close();
}
}
}
static void on_recv_tcp_data(session_uv* s)
{
unsigned char* pkg_data = (unsigned char*)((s->long_pkg != NULL) ? s->long_pkg : s->recv_buf);
int pkg_size, head_size = 0;
unsigned char* raw_data, *mask = NULL;
while (s->recved > 0)
{
pkg_size = head_size = 0;
if (!tp_protocol::read_header(pkg_data, s->recved, &pkg_size, &head_size))
{
break;
}
if(pkg_size <= head_size)
{
s->close();
break;
}
if (s->recved < pkg_size)
{
break;
}
raw_data = pkg_data + head_size;
on_recv_client_cmd((session*)s, raw_data, pkg_size - head_size);
if (s->recved > pkg_size)
{
memmove(pkg_data, pkg_data + pkg_size, s->recved - pkg_size);
}
s->recved -= pkg_size;
if (0 == s->recved && NULL != s->long_pkg)
{
free(s->long_pkg);
s->long_pkg = NULL;
s->long_pkg_size = 0;
}
}
}
static void on_recv_ws_data(session_uv* s)
{
unsigned char* pkg_data = (unsigned char*)((s->long_pkg != NULL) ? s->long_pkg : s->recv_buf);
int pkg_size, head_size = 0;
unsigned char* raw_data, *mask = NULL;
while (s->recved > 0)
{
pkg_size = head_size = 0;
if (pkg_data[0] == 0x88) //close协议
{
s->close();
break;
}
//pkg_size - head_size = body_size
if (!ws_protocol::read_ws_header(pkg_data, s->recved, &pkg_size, &head_size))
{
break;
}
if (s->recved < pkg_size)
{
break;
}
raw_data = pkg_data + head_size;
mask = raw_data - 4;
ws_protocol::parser_ws_recv_data(raw_data, mask, pkg_size - head_size);
on_recv_client_cmd((session*)s, raw_data, pkg_size - head_size);
if (s->recved > pkg_size)
{
memmove(pkg_data, pkg_data + pkg_size, s->recved - pkg_size);
}
s->recved -= pkg_size;
if (0 == s->recved && NULL != s->long_pkg)
{
free(s->long_pkg);
s->long_pkg = NULL;
s->long_pkg_size = 0;
}
}
}
struct udp_recv_buf
{
char* recv_buf;
size_t max_recv_len;
};
static void udp_uv_alloc_buf(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf)
{
suggested_size = suggested_size < 8096 ? 8096 : suggested_size;
struct udp_recv_buf* udp_buf = (struct udp_recv_buf*)handle->data;
if (udp_buf->max_recv_len < suggested_size)
{
if (udp_buf->recv_buf)
{
free(udp_buf->recv_buf);
udp_buf->recv_buf = NULL;
}
udp_buf->recv_buf = (char*)malloc(suggested_size);
udp_buf->max_recv_len = suggested_size;
}
buf->base = udp_buf->recv_buf;
buf->len = suggested_size;
}
static void uv_alloc_buf(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf)
{
session_uv* s = (session_uv*)handle->data;
if (s->recved < RECV_LEN)
{
*buf = uv_buf_init(s->recv_buf + s->recved, RECV_LEN - s->recved);
}
else
{
if (s->long_pkg == NULL)
{
if (s->socket_type == WS_SOCKET && s->is_ws_shake)
{
//ws > RECV_LEN package
int pkg_size;
int head_size;
ws_protocol::read_ws_header((unsigned char*)s->recv_buf, s->recved, &pkg_size, &head_size);
s->long_pkg_size = pkg_size;
s->long_pkg = (char*)malloc(pkg_size);
memcpy(s->long_pkg, s->recv_buf, s->recved);
}
else
{
// tcp > RECV_LEN's package
int pkg_size;
int head_size;
tp_protocol::read_header((unsigned char*)s->recv_buf, s->recved, &pkg_size, &head_size);
s->long_pkg_size = pkg_size;
s->long_pkg = (char*)malloc(pkg_size);
memcpy(s->long_pkg, s->recv_buf, s->recved);
}
}
*buf = uv_buf_init(s->long_pkg + s->recved, s->long_pkg_size - s->recved);
}
}
static void on_close(uv_handle_t* handle)
{
session_uv* s = (session_uv*)handle->data;
session_uv::destroy(s);
}
static void on_shutdown(uv_shutdown_t* req, int status)
{
uv_close((uv_handle_t*)req->handle, on_close);
}
static void after_uv_udp_recv(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags)
{
if(nread <= 0)
{
return;
}
session_udp udp_s;
udp_s.addr = addr;
udp_s.udp_handle = handle;
uv_ip4_name((struct sockaddr_in*)addr, udp_s.c_address, 32);
udp_s.c_port = ntohs(((struct sockaddr_in*)addr)->sin_port);
on_recv_client_cmd((session*)&udp_s, (unsigned char*)buf->base, nread);
}
static void after_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
{
session_uv* s = (session_uv*)stream->data;
if (nread < 0)
{
s->close();
log_error("client close!!");
return;
}
s->recved += nread;
if (s->socket_type == WS_SOCKET) //websocket
{
if (0 == s->is_ws_shake)
{
if (ws_protocol::ws_shake_hand((session*)s, s->recv_buf, s->recved))
{
s->is_ws_shake = 1;
s->recved = 0;
}
}
else
{
on_recv_ws_data(s);
}
}
else
{//tcpsocket
on_recv_tcp_data(s);
}
}
static void uv_connection(uv_stream_t* server, int status)
{
session_uv* s = session_uv::create();
uv_tcp_t* p_client = &s->tcp_handler;
uv_tcp_init(uv_default_loop(), p_client);
p_client->data = (void*)s;
int ret = uv_accept(server, (uv_stream_t*)p_client);
if (ret != 0)
{
log_error("ERROR to connect!! error_code == %d\n", ret);
return;
}
struct sockaddr_in addrinpeer;
int len = sizeof(sockaddr_in);
ret = uv_tcp_getpeername(p_client, (sockaddr*)&addrinpeer, &len);
if (ret != 0)
{
log_error("ERROR to getaddr!! error_code == %d\n", ret);
}
else
{
uv_ip4_name(&addrinpeer, (char*)s->c_address, 64);
s->c_port = ntohs(addrinpeer.sin_port);
s->socket_type = (int)(server->data);
log_error("new client comming %s:%d\n", s->c_address, s->c_port);
}
uv_read_start((uv_stream_t*)p_client, uv_alloc_buf, after_read);
service_man::on_session_connect(s);
}
}
static netbus g_netbus;
netbus * netbus::instance()
{
return &g_netbus;
}
netbus::netbus()
{
this->udp_handler = NULL;
}
void netbus::tcp_listen(int port)
{
uv_tcp_t* p_listen = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
memset(p_listen, 0, sizeof(uv_tcp_t));
uv_tcp_init(uv_default_loop(), p_listen);
struct sockaddr_in addr;
uv_ip4_addr(SERVER_ADDRESS, port, &addr);
int ret = uv_tcp_bind(p_listen, (const struct sockaddr*)&addr, 0);
if (ret != 0)
{
log_error("bind error");
free(p_listen);
return;
}
uv_listen((uv_stream_t*)p_listen, SOMAXCONN, uv_connection);
p_listen->data = (void*)TCP_SOCKET;
}
void netbus::ws_listen(int port)
{
uv_tcp_t* p_listen = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
memset(p_listen, 0, sizeof(uv_tcp_t));
uv_tcp_init(uv_default_loop(), p_listen);
struct sockaddr_in addr;
uv_ip4_addr(SERVER_ADDRESS, port, &addr);
int ret = uv_tcp_bind(p_listen, (const struct sockaddr*)&addr, 0);
if (ret != 0)
{
log_error("bind error");
free(p_listen);
return;
}
uv_listen((uv_stream_t*)p_listen, SOMAXCONN, uv_connection);
p_listen->data = (void*)WS_SOCKET;
}
void netbus::udp_listen(int port)
{
//只允许启动一个UDPhandle
if(this->udp_handler)
{
return;
}
uv_udp_t* server = (uv_udp_t*)malloc(sizeof(uv_udp_t));
memset(server, 0, sizeof(uv_udp_t));
uv_udp_init(uv_default_loop(), server);
udp_recv_buf* udp_buf = (udp_recv_buf*)malloc(sizeof(struct udp_recv_buf));
memset(udp_buf, 0, sizeof(struct udp_recv_buf));
server->data = udp_buf;
sockaddr_in addr;
uv_ip4_addr(SERVER_ADDRESS, port, &addr);
uv_udp_bind(server, (const struct sockaddr*)&addr, 0);
this->udp_handler = (void*)server;
uv_udp_recv_start(server, udp_uv_alloc_buf, after_uv_udp_recv);
}
void netbus::init()
{
service_man::init();
init_session_allocer();
}
void netbus::run()
{
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
struct connect_cb
{
void(*on_connected)(int err, session *s, void *udata);
void * udata;
};
static void after_connect(uv_connect_t* handle, int status)
{
session_uv* s = (session_uv*)handle->handle->data;
connect_cb* cb = (connect_cb*)handle->data;
if(status)
{
if(cb->on_connected)
{
cb->on_connected(1, NULL, cb->udata);
}
s->close();
free(cb);
free(handle);
return;
}
if (cb->on_connected)
{
cb->on_connected(0, (session*)s, cb->udata);
}
uv_read_start((uv_stream_t*)handle->handle, uv_alloc_buf, after_read);
free(cb);
free(handle);
}
void netbus::tcp_connect(const char * server_ip, int port, void(*on_connected)(int err, session *s, void *udata), void * udata)
{
struct sockaddr_in bind_addr;
int iret = uv_ip4_addr(server_ip, port, &bind_addr);
if(iret)
{
return;
}
session_uv* s = session_uv::create();
uv_tcp_t* client = &s->tcp_handler;
uv_tcp_init(uv_default_loop(), client);
client->data = (void*)s;
s->as_client = 1;
s->socket_type = TCP_SOCKET;
strcpy(s->c_address, server_ip);
s->c_port = port;
uv_connect_t* connect_req = (uv_connect_t*)malloc(sizeof(uv_connect_t));
memset(connect_req, 0, sizeof(uv_connect_t));
//connect_req->type = UV_TCP;
connect_cb* cb = (connect_cb*)malloc(sizeof(connect_cb));
memset(cb, 0, sizeof(connect_cb));
cb->on_connected = on_connected;
cb->udata = udata;
connect_req->data = cb;
iret = uv_tcp_connect(connect_req, client, (struct sockaddr*)&bind_addr, after_connect);
if(iret)
{
return;
}
}
void netbus::udp_send_to(char * ip, int port, unsigned char * body, int len)
{
uv_buf_t w_buf;
w_buf = uv_buf_init((char*)body, len);
uv_udp_send_t* req = (uv_udp_send_t*)my_malloc(sizeof(uv_udp_send_t));
SOCKADDR_IN addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.S_un.S_addr = inet_addr(ip);
uv_udp_send(req, (uv_udp_t*)this->udp_handler, &w_buf, 1, (const struct sockaddr*)&addr, on_uv_udp_send_end);
}
| [
"1770799643@qq.com"
] | 1770799643@qq.com |
42d853c684c89c127f6d8b1325d40307a1a65dae | a3782e3c775c99efc7f818ad5d2177a45c0b2ca7 | /src/optional/HokuyoLaserDriver.hpp | 2fac5a8a5caab5982499b8e766a3dabe24c3b01d | [] | no_license | drietmueller/lib_init | 5c237540e9e9dd4f55963266b0d964a7ce85d878 | f35d38969a40b44a8d2bf579228ea234483618af | refs/heads/master | 2020-12-25T10:36:19.374457 | 2016-06-03T09:47:35 | 2016-06-03T09:47:35 | 60,337,043 | 0 | 0 | null | 2016-06-03T09:43:46 | 2016-06-03T09:43:46 | null | UTF-8 | C++ | false | false | 531 | hpp | #pragma once
#include <lib_init/LaserDriver.hpp>
#include <hokuyo/proxies/Task.hpp>
#include <laser_filter/proxies/Task.hpp>
namespace init
{
class HokuyoLaserDriver : public LaserDriver
{
public:
HokuyoLaserDriver(const std::string &hokuyoTaskName, const std::string &filterTaskName);
virtual bool connect();
virtual OutputProxyPort< base::samples::LaserScan >& getLaserReadingsPort();
protected:
DependentTask<hokuyo::proxies::Task> laserTask;
DependentTask<laser_filter::proxies::Task> filterTask;
};
}
| [
"dhem2012@informatik.uni-bremen.de"
] | dhem2012@informatik.uni-bremen.de |
655ab2d642a7b822304aa9d06547db0a04d8012e | 24f8c1bc84049310ade1ecdea8d041f5aff94bd8 | /C++98/examples/iterator/inserter.cpp | b6e0ab7034f1528be2f5816a4c56c635b2a2a465 | [] | no_license | BartVandewoestyne/Cpp | f10d709aed4bbe03b3cca1778ef8f5b7ec554c54 | 055d3fc61922a29657f48241defcaba744f43d0f | refs/heads/master | 2023-08-22T19:42:32.516681 | 2023-08-03T21:58:02 | 2023-08-03T21:58:02 | 4,518,426 | 126 | 17 | null | null | null | null | UTF-8 | C++ | false | false | 196 | cpp | /*
* References:
*
* [boccara2017] A Minimal Interface: Both Expressive And Fast Code
* https://www.fluentcpp.com/2017/12/05/both-expressive-and-fast-code-provide-minimal-interface/
*/
| [
"Bart.Vandewoestyne@telenet.be"
] | Bart.Vandewoestyne@telenet.be |
c3c5612aeae517eb260f324d74944227fdc3184d | 2c3052b5acaacd732db142fdc946a0ccfa36b121 | /src/operator/tensor/broadcast_reduce_op.h | 75f96f9447b2bc7e248160041d645dbf54a72521 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-2-Clause-Views",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | CynthiaProtector/OD-SGD | c9972d0445fea452c06c8345a33c952f862bd047 | 18e6fba6b4f4fb1254cc2a94e3ef5bbd09f4fbc0 | refs/heads/master | 2022-10-30T04:18:09.482295 | 2019-09-28T02:41:08 | 2019-09-28T02:41:08 | 211,431,343 | 1 | 2 | Apache-2.0 | 2022-10-21T14:02:51 | 2019-09-28T02:20:31 | C++ | UTF-8 | C++ | false | false | 39,655 | h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file elementwise_unary_op-inl.h
* \brief Function definition of elementwise unary operators
*/
#ifndef MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_OP_H_
#define MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_OP_H_
#include <mxnet/operator_util.h>
#include <vector>
#include <utility>
#include <algorithm>
#include "../mshadow_op.h"
#include "../elemwise_op_common.h"
#include "./elemwise_binary_broadcast_op.h"
#include "../mxnet_op.h"
namespace mxnet {
namespace op {
struct ReduceAxesParam : public dmlc::Parameter<ReduceAxesParam> {
TShape axis;
bool keepdims;
bool exclude;
DMLC_DECLARE_PARAMETER(ReduceAxesParam) {
DMLC_DECLARE_FIELD(axis).set_default(TShape())
.describe(R"code(The axis or axes along which to perform the reduction.
The default, `axis=()`, will compute over all elements into a
scalar array with shape `(1,)`.
If `axis` is int, a reduction is performed on a particular axis.
If `axis` is a tuple of ints, a reduction is performed on all the axes
specified in the tuple.
If `exclude` is true, reduction will be performed on the axes that are
NOT in axis instead.
Negative values means indexing from right to left.)code");
DMLC_DECLARE_FIELD(keepdims).set_default(false)
.describe("If this is set to `True`, the reduced axes are left "
"in the result as dimension with size one.");
DMLC_DECLARE_FIELD(exclude).set_default(false)
.describe("Whether to perform reduction on axis that are NOT in axis instead.");
}
};
struct ReduceAxisParam : public dmlc::Parameter<ReduceAxisParam> {
dmlc::optional<int> axis;
bool keepdims;
DMLC_DECLARE_PARAMETER(ReduceAxisParam) {
DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>())
.describe("The axis along which to perform the reduction. "
"Negative values means indexing from right to left. "
"``Requires axis to be set as int, because global reduction "
"is not supported yet.``");
DMLC_DECLARE_FIELD(keepdims).set_default(false)
.describe("If this is set to `True`, the reduced axis is left "
"in the result as dimension with size one.");
}
};
struct PickParam : public dmlc::Parameter<PickParam> {
dmlc::optional<int> axis;
int mode;
bool keepdims;
DMLC_DECLARE_PARAMETER(PickParam) {
DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1))
.describe("int or None. The axis to picking the elements. "
"Negative values means indexing from right to left. "
"If is `None`, the elements in the index w.r.t the "
"flattened input will be picked.");
DMLC_DECLARE_FIELD(keepdims).set_default(false)
.describe("If true, the axis where we pick the elements is left "
"in the result as dimension with size one.");
}
};
struct BroadcastAxesParam : public dmlc::Parameter<BroadcastAxesParam> {
TShape axis;
TShape size;
DMLC_DECLARE_PARAMETER(BroadcastAxesParam) {
DMLC_DECLARE_FIELD(axis).set_default(TShape())
.describe("The axes to perform the broadcasting.");
DMLC_DECLARE_FIELD(size).set_default(TShape())
.describe("Target sizes of the broadcasting axes.");
}
};
struct BroadcastToParam : public dmlc::Parameter<BroadcastToParam> {
TShape shape;
DMLC_DECLARE_PARAMETER(BroadcastToParam) {
DMLC_DECLARE_FIELD(shape).set_default(TShape())
.describe("The shape of the desired array."
" We can set the dim to zero if it's same as the original."
" E.g `A = broadcast_to(B, shape=(10, 0, 0))` "
"has the same meaning as `A = broadcast_axis(B, axis=0, size=10)`.");
}
};
inline int CheckAxis(int axis, int ndim) {
CHECK(axis < ndim && axis >= -ndim)
<< "axis " << axis << " exceeds the input dimension of " << ndim;
return (axis + ndim)%ndim;
}
inline TShape AxisShapeCompact(TShape shape, int *axis, bool allow_2d) {
int ndim = static_cast<int>(shape.ndim());
index_t leading = 1, trailing = 1, M = shape[*axis];
for (int i = 0; i < *axis; ++i) leading *= shape[i];
for (int i = *axis + 1; i < ndim; ++i) trailing *= shape[i];
if (allow_2d && trailing == 1) {
*axis = 1;
return mshadow::Shape2(leading, M);
}
if (allow_2d && leading == 1) {
*axis = 0;
return mshadow::Shape2(M, trailing);
}
*axis = 1;
return mshadow::Shape3(leading, M, trailing);
}
inline TShape ReduceAxisShapeImpl(const TShape& ishape, const dmlc::optional<int>& axis,
bool keepdims) {
if (!axis || ishape.ndim() == 1) {
if (keepdims) {
return TShape(ishape.ndim());
}
return mshadow::Shape1(1);
}
int new_axis = CheckAxis(axis.value(), ishape.ndim());
if (keepdims) {
TShape oshape = ishape;
oshape[new_axis] = 1;
return oshape;
}
TShape oshape(ishape.ndim() - 1);
for (int i = 0; i < new_axis; ++i) oshape[i] = ishape[i];
for (int i = new_axis+1; i < static_cast<int>(ishape.ndim()); ++i) {
oshape[i-1] = ishape[i];
}
return oshape;
}
inline bool ReduceAxisShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape> *in_attrs,
std::vector<TShape> *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
TShape& ishape = (*in_attrs)[0];
if (ishape.ndim() == 0) return false;
const ReduceAxisParam& param = nnvm::get<ReduceAxisParam>(attrs.parsed);
SHAPE_ASSIGN_CHECK(*out_attrs, 0,
ReduceAxisShapeImpl(ishape, param.axis, param.keepdims));
return true;
}
inline TShape ReduceAxesShapeImpl(const TShape& ishape, const TShape& axis,
bool keepdims, bool exclude) {
if (axis.ndim() == 0) {
if (keepdims) {
return TShape(ishape.ndim());
} else {
return TShape(1);
}
}
TShape axes(axis);
for (index_t i = 0; i < axes.ndim(); i++) {
if (axes[i] < 0) {
axes[i] += ishape.ndim();
}
}
std::sort(axes.begin(), axes.end());
for (index_t i = 1; i < axes.ndim(); i++) {
CHECK_LT(axes[i-1], axes[i])
<< "Reduction axes have duplicates "
<< axes;
}
CHECK_LT(axes[axes.ndim()-1], ishape.ndim())
<< "Reduction axis " << axes[axes.ndim()-1]
<< " Exceeds input dimensions " << ishape;
CHECK_GE(axes[0], 0)
<< "Reduction axis " << axis
<< " Exceeds input dimensions " << ishape;
TShape oshape;
if (keepdims) {
oshape = TShape(ishape);
} else if (exclude) {
oshape = TShape(axes.ndim());
} else {
oshape = TShape(std::max<index_t>(1, ishape.ndim() - axes.ndim()));
}
if (keepdims && exclude) {
for (index_t i = 0, j = 0; i < ishape.ndim(); ++i) {
if (j < axes.ndim() && i == axes[j]) {
++j;
continue;
}
oshape[i] = 1;
}
} else if (keepdims) {
for (index_t i = 0; i < axes.ndim(); ++i) {
oshape[axes[i]] = 1;
}
} else if (exclude) {
for (index_t i = 0; i < axes.ndim(); ++i) {
oshape[i] = ishape[axes[i]];
}
} else {
for (index_t i = 0, j = 0, k = 0; i < ishape.ndim(); ++i) {
if (j < axes.ndim() && i == axes[j]) {
++j;
continue;
}
oshape[k++] = ishape[i];
}
}
return oshape;
}
inline bool ReduceAxesShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape> *in_attrs,
std::vector<TShape> *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
if ((*in_attrs)[0].ndim() == 0) return false;
const ReduceAxesParam& param = nnvm::get<ReduceAxesParam>(attrs.parsed);
SHAPE_ASSIGN_CHECK(*out_attrs, 0,
ReduceAxesShapeImpl((*in_attrs)[0], param.axis,
param.keepdims, param.exclude));
return true;
}
inline bool BroadcastAxesShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape> *in_attrs,
std::vector<TShape> *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
if ((*in_attrs)[0].ndim() == 0) return false;
const BroadcastAxesParam& param = nnvm::get<BroadcastAxesParam>(attrs.parsed);
CHECK_EQ(param.axis.ndim() , param.size.ndim());
TShape &ishape = (*in_attrs)[0];
TShape oshape = ishape;
for (index_t i = 0; i < param.axis.ndim(); ++i) {
CHECK_EQ(oshape[param.axis[i]], 1U) << "Broadcasting axis must have size 1";
oshape[param.axis[i]] = param.size[i];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return true;
}
inline bool BroadcastToShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape> *in_attrs,
std::vector<TShape> *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
TShape& ishape = (*in_attrs)[0];
if (ishape.ndim() == 0) return false;
const BroadcastToParam& param = nnvm::get<BroadcastToParam>(attrs.parsed);
CHECK_EQ(ishape.ndim(), param.shape.ndim())
<< "Operand of shape " << ishape << " cannot be broadcasted to " << param.shape;
TShape oshape = param.shape;
for (index_t i = 0; i < ishape.ndim(); ++i) {
if (oshape[i] != 0) {
CHECK(ishape[i] == oshape[i] || ishape[i] == 1)
<< "Array cannot be broadcasted from " << ishape << " to " << param.shape;
} else {
oshape[i] = ishape[i];
}
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return true;
}
inline void BroadcastReduceShapeCompact(const TShape& big, const TShape& small,
TShape *new_big, TShape *new_small) {
index_t idim = std::max<index_t>(big.ndim(), MXNET_SPECIAL_MAX_NDIM);
*new_big = TShape(idim);
*new_small = TShape(idim);
index_t j = 0;
if (small.Size() == 1) {
(*new_big)[j++] = big.Size();
} else {
index_t bprod = 1, sprod = 1;
for (index_t i = 0, k = 0; i < big.ndim(); ++i) {
bool red_axis = big[i] != small[i];
if ((red_axis && sprod > 1) || (!red_axis && bprod != sprod)) {
(*new_big)[j] = bprod;
(*new_small)[j] = sprod;
bprod = sprod = 1; ++j;
}
bprod *= big[i];
if (red_axis) {
++k;
} else {
sprod *= big[i];
}
}
if (bprod > 1 || sprod > 1) {
(*new_big)[j] = bprod;
(*new_small)[j] = sprod;
++j;
}
}
if (j <= 2) {
new_small->assign(&(*new_small)[0], &(*new_small)[2]);
new_big->assign(&(*new_big)[0], &(*new_big)[2]);
} else if (j <= MXNET_SPECIAL_MAX_NDIM) {
new_small->assign(&(*new_small)[0], &(*new_small)[MXNET_SPECIAL_MAX_NDIM]);
new_big->assign(&(*new_big)[0], &(*new_big)[MXNET_SPECIAL_MAX_NDIM]);
} else {
LOG(FATAL) << "Too many reduction axes from " << big << " to " << small;
}
}
inline bool SumOpForwardInferStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const ReduceAxesParam& param = nnvm::get<ReduceAxesParam>(attrs.parsed);
const int in_stype = in_attrs->at(0);
int& out_stype = out_attrs->at(0);
bool dispatched = false;
// sum only supported for CPU for now. TODO: Remove when support for GPU added
const bool invalid_ctx = dev_mask != mshadow::cpu::kDevMask;
const auto dispatch_ex =
invalid_ctx ? DispatchMode::kFComputeFallback : DispatchMode::kFComputeEx;
if (!dispatched && in_stype == kDefaultStorage) {
// When input is dense output storage is set as dense and dispatched to
// dense operator
dispatched = storage_type_assign(&out_stype, kDefaultStorage, dispatch_mode,
DispatchMode::kFCompute);
}
if (!dispatched && in_stype == kCSRStorage &&
(param.axis[0] == 0 || param.axis[0] == 1) && !param.keepdims &&
!param.exclude) {
// If input is csr and axis is 0 or 1, and neither of keepdims or exclude
// are set, dipsatch to sparse operator and output storage is set as dense
dispatched = storage_type_assign(&out_stype, kDefaultStorage, dispatch_mode,
dispatch_ex);
}
if (!dispatched) {
// If input is csr, but keepdims or exclude is set or summing along a axis
// different from 0 or 1
dispatch_fallback(out_attrs, dispatch_mode);
}
if (*dispatch_mode == DispatchMode::kFComputeFallback) {
LogStorageFallback(attrs, dev_mask, in_attrs, out_attrs);
}
return true;
}
template<typename xpu, typename reducer>
void SearchAxisCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mshadow::expr;
const ReduceAxisParam& param = nnvm::get<ReduceAxisParam>(attrs.parsed);
Stream<xpu> *s = ctx.get_stream<xpu>();
if (!param.axis) LOG(FATAL) << "Global reduction not supported yet";
int axis = CheckAxis(param.axis.value(), inputs[0].shape_.ndim());
TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, false);
MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Tensor<xpu, 2, DType> out = outputs[0].get_with_shape<xpu, 2, DType>(
Shape2(shape[0], shape[2]), s);
Tensor<xpu, 3, DType> in = inputs[0].get_with_shape<xpu, 3, DType>(
shape.get<3>(), s);
CHECK(req[0] != kAddTo) << "AddTo is not supported";
ASSIGN_DISPATCH(out, req[0], (reduce_with_axis<reducer, true>(in, 1)));
});
}
template<typename xpu, typename reducer, bool normalize = false>
void ReduceAxesComputeImpl(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs,
const TShape& small) {
using namespace mshadow;
using namespace mshadow::expr;
TShape src_shape, dst_shape;
BroadcastReduceShapeCompact(inputs[0].shape_, small, &src_shape, &dst_shape);
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
const TBlob in_data = inputs[0].reshape(src_shape);
const TBlob out_data = outputs[0].reshape(dst_shape);
BROADCAST_NDIM_SWITCH(dst_shape.ndim(), NDim, {
size_t workspace_size = broadcast::ReduceWorkspaceSize<NDim, DType>(
s, out_data, req[0], in_data);
Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(Shape1(workspace_size), s);
broadcast::Reduce<reducer, NDim, DType, mshadow::op::identity>(
s, out_data, req[0], workspace, in_data);
if (normalize) {
auto out = out_data.FlatTo2D<xpu, DType>(s);
out /= scalar<DType>(src_shape.Size()/dst_shape.Size());
}
});
});
}
template<typename xpu, typename reducer, bool normalize = false>
void ReduceAxesCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
const ReduceAxesParam& param = nnvm::get<ReduceAxesParam>(attrs.parsed);
TShape small;
if (param.keepdims) {
small = outputs[0].shape_;
} else {
small = ReduceAxesShapeImpl(inputs[0].shape_, param.axis, true, param.exclude);
}
ReduceAxesComputeImpl<xpu, reducer, normalize>(attrs, ctx, inputs, req, outputs, small);
}
template <int req, int axis>
struct SumCsrKernel;
template <int req>
/* \brief The number of columns are divided equally among the number of threads
* available.
* Each thread gets a subset of columns. It iterates through all rows for the
* subset of columns.
* In each iteration, it tries to do a binary search for the first column
* index between in_idx[in_indptr[row]] in_idx[in_indptr[row+1]]. After we find
* an index that is equal to the first column or close to the first column,
* it does a linear search for the rest of the indices and adds their data
* to the intermediate sum. At the end of iteration through all
* rows we have the sum along the axis for the subset of columns.
*/
struct SumCsrKernel<req, 0> {
template <typename RType, typename IType, typename DType>
MSHADOW_XINLINE static void Map(int j, DType* out_data,
const RType* in_indptr, const IType* in_idx,
const DType* in_data,
DType* sum,
DType* residual,
RType num_rows,
IType num_cols,
const nnvm::dim_t seg_len) {
const IType seg_start = j * seg_len;
if (seg_start >= num_cols) return;
const IType seg_end = std::min(seg_start + seg_len, num_cols);
for (RType row = 0; row < num_rows; ++row) {
// row specific seg starts
IType row_seg_start = seg_start;
IType row_seg_end = seg_end;
// Cache starting and ending indptr values for the row
IType row_indptr_start = in_indptr[row];
IType row_indptr_end = in_indptr[row + 1] - 1;
if (row_indptr_start == (row_indptr_end + 1)) continue;
// If row_seg_start is less than the first index for the row, move the
// row_seg_start forward
while (row_seg_start < in_idx[row_indptr_start] &&
row_seg_start < row_seg_end) {
row_seg_start++;
}
// If row_seg_start is greater than last index for the row, move on to
// the next row
if (row_seg_start > in_idx[row_indptr_end]) continue;
// Do binary search for row_seg_start between in_idx[in_indptr[i]] and
// in_idx[in_indptr[i + 1]]
IType start = row_indptr_start;
IType end = row_indptr_end;
// Initialize mid with the first indice of the row
IType mid = start;
while (start <= end) {
mid = start + (end - start) / 2;
if (in_idx[mid] == row_seg_start) {
break;
} else if (in_idx[mid] < row_seg_start) {
start = mid + 1;
} else {
end = mid - 1;
}
}
// At this point we have a in_idx[mid] which is close to row_seg_start
// Safety check to make sure mid is a valid indptr value
if (mid < row_indptr_start || mid > row_indptr_end)
mid = row_indptr_start;
// Linear search for nnzs for column subset between row_seg_start
// and row_seg_end
for (IType col = row_seg_start;
col < row_seg_end && mid <= row_indptr_end;) {
if (col == in_idx[mid]) {
mshadow::red::sum::Reduce(sum[col], in_data[mid],
residual[col]);
mid++;
col++;
} else if (in_idx[mid] < col) {
mid++;
} else {
col++;
}
}
}
for (IType col = seg_start; col < seg_end; col++) {
KERNEL_ASSIGN(out_data[col], req, sum[col]);
}
}
};
template <int req>
struct SumCsrKernel<req, 1> {
template <typename RType, typename DType>
MSHADOW_XINLINE static void Map(int i, DType* out_data,
const RType* in_indptr,
const DType* in_data) {
DType sum, residual;
mshadow::red::sum::SetInitValue(sum, residual);
for (RType k = in_indptr[i]; k < in_indptr[i + 1]; k++) {
mshadow::red::sum::Reduce(sum, in_data[k], residual);
}
KERNEL_ASSIGN(out_data[i], req, sum);
}
};
template <typename xpu>
void SumCsrImpl(const nnvm::NodeAttrs& attrs, mshadow::Stream<xpu>* s, const OpContext& ctx,
const NDArray& input, const OpReqType req, NDArray* output) {
if (req == kNullOp) return;
const ReduceAxesParam& param = nnvm::get<ReduceAxesParam>(attrs.parsed);
CHECK_EQ(param.axis.ndim(), 1U) << "sum(csr) only supports axis 0 or 1";
CHECK(param.axis[0] == 0 || param.axis[0] == 1)
<< "sum(csr) only support axis 0 or 1";
CHECK(!param.keepdims) << "keepdims not supported for sparse";
CHECK(!param.exclude) << "exclude not supported for sparse";
int64_t out_data_size = 0;
if (param.axis[0] == 0) {
out_data_size = input.shape()[1];
} else {
out_data_size = input.shape()[0];
}
// only dense output storage type is supported
CHECK_EQ(output->storage_type(), kDefaultStorage);
using namespace mshadow;
using namespace mxnet_op;
using namespace csr;
using nnvm::dim_t;
if (req == kWriteTo || req == kWriteInplace) {
MSHADOW_TYPE_SWITCH(output->data().type_flag_, DType, {
Kernel<set_zero, xpu>::Launch(s, out_data_size,
output->data().dptr<DType>());
})
}
if (!input.storage_initialized()) {
return;
}
if (0 == param.axis[0]) {
MSHADOW_IDX_TYPE_SWITCH(input.aux_type(kIndPtr), RType, {
MSHADOW_IDX_TYPE_SWITCH(input.aux_type(kIdx), IType, {
MSHADOW_TYPE_SWITCH(input.dtype(), DType, {
MXNET_ASSIGN_REQ_SWITCH(req, req_type, {
const RType* in_indptr = input.aux_data(kIndPtr).dptr<RType>();
const IType* in_idx = input.aux_data(kIdx).dptr<IType>();
const DType* in_data = input.data().dptr<DType>();
const RType num_rows = input.shape()[0];
const IType num_cols = input.shape()[1];
dim_t num_threads = mxnet_op::get_num_threads<xpu>(16);
dim_t seg_len = (out_data_size + num_threads - 1) / num_threads;
mshadow::Tensor<xpu, 1, DType> workspace =
ctx.requested[0].get_space_typed<xpu, 1, DType>(
Shape1(2 * out_data_size), s);
mshadow::Tensor<xpu, 1, DType> sum(
reinterpret_cast<DType*>(workspace.dptr_),
Shape1(out_data_size));
mshadow::Tensor<xpu, 1, DType> residual(
reinterpret_cast<DType*>(workspace.dptr_ +
out_data_size),
Shape1(out_data_size));
Kernel<set_zero, xpu>::Launch(s, out_data_size, sum.dptr_);
Kernel<set_zero, xpu>::Launch(s, out_data_size, residual.dptr_);
Kernel<SumCsrKernel<req_type, 0>, xpu>::Launch(
s, num_threads, output->data().dptr<DType>(), in_indptr, in_idx,
in_data, sum.dptr_, residual.dptr_, num_rows, num_cols,
seg_len);
});
});
});
});
} else if (1 == param.axis[0]) {
MSHADOW_IDX_TYPE_SWITCH(input.aux_type(kIndPtr), RType, {
MSHADOW_TYPE_SWITCH(input.dtype(), DType, {
MXNET_ASSIGN_REQ_SWITCH(req, req_type, {
const RType* in_indptr = input.aux_data(kIndPtr).dptr<RType>();
const DType* in_data = input.data().dptr<DType>();
Kernel<SumCsrKernel<req_type, 1>, xpu>::Launch(
s, out_data_size, output->data().dptr<DType>(), in_indptr,
in_data);
});
});
});
}
}
template <typename xpu, typename reducer, bool normalize = false>
void SumOpForwardEx(const nnvm::NodeAttrs& attrs, const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
mshadow::Stream<xpu>* s = ctx.get_stream<xpu>();
const NDArrayStorageType istype = inputs[0].storage_type();
if (istype == kCSRStorage) {
CHECK_EQ(inputs[0].shape().ndim(), 2U)
<< "sum(csr) op only supports 2D ndarray as input";
NDArray output = outputs[0];
SumCsrImpl(attrs, s, ctx, inputs[0], req[0], &output);
} else {
LOG(FATAL) << "Not implemented: "
<< operator_string(attrs, ctx, inputs, req, outputs);
}
}
// works when shape inference of output is given
template<typename xpu, typename OP, bool normalize = false>
void ReduceAxesBackwardUseInOut(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mshadow::expr;
const ReduceAxesParam& param = nnvm::get<ReduceAxesParam>(attrs.parsed);
TShape small;
if (param.keepdims) {
small = inputs[0].shape_;
} else {
small = ReduceAxesShapeImpl(outputs[0].shape_, param.axis, true, param.exclude);
}
TShape src_shape, dst_shape;
BroadcastReduceShapeCompact(outputs[0].shape_, small, &src_shape, &dst_shape);
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
if (dst_shape.ndim() == 2) {
Tensor<xpu, 2, DType> igrad =
outputs[0].get_with_shape<xpu, 2, DType>(src_shape.get<2>(), s);
Tensor<xpu, 2, DType> ograd =
inputs[0].get_with_shape<xpu, 2, DType>(dst_shape.get<2>(), s);
Tensor<xpu, 2, DType> data =
inputs[1].get_with_shape<xpu, 2, DType>(src_shape.get<2>(), s);
Tensor<xpu, 2, DType> out =
inputs[2].get_with_shape<xpu, 2, DType>(dst_shape.get<2>(), s);
ASSIGN_DISPATCH(igrad, req[0],
broadcast_to(ograd, src_shape)*F<OP>(data, broadcast_to(out, src_shape)));
if (normalize) igrad /= scalar<DType>(src_shape.Size()/dst_shape.Size());
} else {
const int ndim = MXNET_SPECIAL_MAX_NDIM;
Tensor<xpu, ndim, DType> igrad =
outputs[0].get_with_shape<xpu, ndim, DType>(src_shape.get<ndim>(), s);
Tensor<xpu, ndim, DType> ograd =
inputs[0].get_with_shape<xpu, ndim, DType>(dst_shape.get<ndim>(), s);
Tensor<xpu, ndim, DType> data =
inputs[1].get_with_shape<xpu, ndim, DType>(src_shape.get<ndim>(), s);
Tensor<xpu, ndim, DType> out =
inputs[2].get_with_shape<xpu, ndim, DType>(dst_shape.get<ndim>(), s);
ASSIGN_DISPATCH(igrad, req[0],
broadcast_to(ograd, src_shape)*F<OP>(data, broadcast_to(out, src_shape)));
if (normalize) igrad /= scalar<DType>(src_shape.Size()/dst_shape.Size());
}
});
}
template<typename xpu>
inline void BroadcastComputeImpl(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs,
const TShape& small) {
using namespace mshadow;
using namespace mshadow::expr;
TShape src_shape, dst_shape;
BroadcastReduceShapeCompact(outputs[0].shape_, small, &dst_shape, &src_shape);
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
if (dst_shape.ndim() == 2) {
Tensor<xpu, 2, DType> out =
outputs[0].get_with_shape<xpu, 2, DType>(dst_shape.get<2>(), s);
Tensor<xpu, 2, DType> data =
inputs[0].get_with_shape<xpu, 2, DType>(src_shape.get<2>(), s);
ASSIGN_DISPATCH(out, req[0], broadcast_to(data, dst_shape));
} else {
const int ndim = MXNET_SPECIAL_MAX_NDIM;
Tensor<xpu, ndim, DType> out =
outputs[0].get_with_shape<xpu, ndim, DType>(dst_shape.get<ndim>(), s);
Tensor<xpu, ndim, DType> data =
inputs[0].get_with_shape<xpu, ndim, DType>(src_shape.get<ndim>(), s);
ASSIGN_DISPATCH(out, req[0], broadcast_to(data, dst_shape));
}
});
}
template<typename xpu>
inline void BroadcastCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
BroadcastComputeImpl<xpu>(attrs, ctx, inputs, req, outputs, inputs[0].shape_);
}
template<typename xpu, bool normalize = false>
inline void ReduceAxesBackwardUseNone(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mshadow::expr;
const ReduceAxesParam& param = nnvm::get<ReduceAxesParam>(attrs.parsed);
TShape small;
if (param.keepdims) {
small = inputs[0].shape_;
} else {
small = ReduceAxesShapeImpl(outputs[0].shape_, param.axis, true, param.exclude);
}
BroadcastComputeImpl<xpu>(attrs, ctx, inputs, req, outputs, small);
if (normalize) {
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Tensor<xpu, 1, DType> igrad = outputs[0].FlatTo1D<xpu, DType>(s);
igrad /= scalar<DType>(outputs[0].Size()/inputs[0].Size());
});
}
}
template<typename PType>
inline void AxesParamParser(nnvm::NodeAttrs* attrs) {
PType param;
param.Init(attrs->dict);
attrs->parsed = std::move(param);
}
struct ReduceGrad {
const char *op_name;
std::vector<nnvm::NodeEntry> operator()(const nnvm::NodePtr& n,
const std::vector<nnvm::NodeEntry>& ograds) {
return MakeNonlossGradNode(
op_name, n,
ograds, {n->inputs[0], nnvm::NodeEntry{n, 0, 0}},
n->attrs.dict);
}
};
template<typename xpu>
void L2NormCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 1, DType> out = outputs[0].get<xpu, 1, DType>(s);
mshadow::Tensor<xpu, 1, DType> in = inputs[0].get_with_shape<xpu, 1, DType>(
mshadow::Shape1(inputs[0].shape_.Size()), s);
mshadow::VectorDot(out, in, in);
ASSIGN_DISPATCH(out, req[0], mshadow::expr::F<mxnet::op::mshadow_op::square_root>(out));
});
}
/*! \brief index element from array along axes */
template<int ndim>
struct pick {
template<typename DType, typename IType>
MSHADOW_XINLINE static void Map(int i, DType* out, const DType* a,
const IType *idx, int M, int stride,
mshadow::Shape<ndim> bshape,
mshadow::Shape<ndim> sshape) {
using namespace broadcast;
int j = static_cast<int>(idx[i]);
if (j < 0) j = 0;
else if (j >= M) j = M-1;
j = ravel(unravel(i, sshape), bshape) + j*stride;
out[i] = a[j];
}
};
/*! \brief index element from array along axes */
template<int ndim>
struct pick_grad {
template<typename DType, typename IType>
MSHADOW_XINLINE static void Map(int i, DType* igrad, const DType* ograd,
const IType *idx, int M, int stride,
mshadow::Shape<ndim> bshape,
mshadow::Shape<ndim> sshape) {
using namespace broadcast;
int j = static_cast<int>(idx[i]);
if (j < 0) j = 0;
else if (j >= M) j = M-1;
j = ravel(unravel(i, sshape), bshape) + j*stride;
igrad[j] += ograd[i];
}
};
inline bool PickOpShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape> *in_attrs,
std::vector<TShape> *out_attrs) {
CHECK_EQ(in_attrs->size(), 2);
CHECK_EQ(out_attrs->size(), 1);
const TShape& ishape = (*in_attrs)[0];
if (ishape.ndim() == 0) return false;
const PickParam& param = nnvm::get<PickParam>(attrs.parsed);
if (!param.axis) LOG(FATAL)
<< "axis=None is not supported by pick yet. Must specify an axis.";
TShape oshape = ReduceAxisShapeImpl(ishape, param.axis, param.keepdims);
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
if (!(*in_attrs)[1].ndim()) return false;
if ((*in_attrs)[1].ndim() == ishape.ndim()) {
SHAPE_ASSIGN_CHECK(*in_attrs, 1,
ReduceAxisShapeImpl(ishape, param.axis, true));
} else {
SHAPE_ASSIGN_CHECK(*in_attrs, 1,
ReduceAxisShapeImpl(ishape, param.axis, false));
}
return true;
}
inline bool PickOpType(const nnvm::NodeAttrs& attrs,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
CHECK_EQ(in_attrs->size(), 2U);
CHECK_EQ(out_attrs->size(), 1U);
CHECK_NE((*in_attrs)[1], -1) << "Index type must be set for pick operator";
TYPE_ASSIGN_CHECK(*out_attrs, 0, (*in_attrs)[0]);
TYPE_ASSIGN_CHECK(*in_attrs, 0, (*out_attrs)[0]);
return (*out_attrs)[0] != -1;
}
template<typename xpu>
void PickOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mxnet_op;
using namespace mshadow;
CHECK_EQ(req[0], kWriteTo);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
const PickParam& param = nnvm::get<PickParam>(attrs.parsed);
const TShape& ishape = inputs[0].shape_;
index_t axis = CheckAxis(param.axis.value(), ishape.ndim());
int leading = 1, trailing = 1, M = ishape[axis];
for (index_t i = 0; i < axis; ++i) leading *= ishape[i];
for (index_t i = axis+1; i < ishape.ndim(); ++i) trailing *= ishape[i];
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { // output type
MSHADOW_TYPE_SWITCH(inputs[1].type_flag_, IType, { // index type
if (trailing == 1) {
Kernel<pick<2>, xpu>::Launch(s, outputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<IType>(),
M, 1, Shape2(leading, M), Shape2(leading, 1));
} else {
Kernel<pick<3>, xpu>::Launch(s, outputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<IType>(),
M, trailing, Shape3(leading, M, trailing),
Shape3(leading, 1, trailing));
}
});
});
}
template<typename xpu>
void PickOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mxnet_op;
using namespace mshadow;
if (req[0] == kNullOp) return;
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
const PickParam& param = nnvm::get<PickParam>(attrs.parsed);
const TShape& ishape = outputs[0].shape_;
const index_t axis = CheckAxis(param.axis.value(), ishape.ndim());
int leading = 1, trailing = 1, M = ishape[axis];
for (index_t i = 0; i < axis; ++i) leading *= ishape[i];
for (index_t i = axis+1; i < ishape.ndim(); ++i) trailing *= ishape[i];
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { // output type
MSHADOW_TYPE_SWITCH(inputs[1].type_flag_, IType, { // index type
if (req[0] != kAddTo) outputs[0].FlatTo1D<xpu, DType>(s) = 0;
if (trailing == 1) {
Kernel<pick_grad<2>, xpu>::Launch(s, inputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<IType>(),
M, 1, Shape2(leading, M), Shape2(leading, 1));
} else {
Kernel<pick_grad<3>, xpu>::Launch(s, inputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<IType>(),
M, trailing, Shape3(leading, M, trailing),
Shape3(leading, 1, trailing));
}
});
});
}
#define MXNET_OPERATOR_REGISTER_REDUCE_AXIS(name) \
NNVM_REGISTER_OP(name) \
.set_num_inputs(1) \
.set_num_outputs(1) \
.set_attr_parser(ParamParser<ReduceAxisParam>) \
.set_attr<nnvm::FInferShape>("FInferShape", ReduceAxisShape) \
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) \
.add_argument("data", "NDArray-or-Symbol", "The input") \
.add_arguments(ReduceAxisParam::__FIELDS__())
#define MXNET_OPERATOR_REGISTER_REDUCE(name) \
NNVM_REGISTER_OP(name) \
.set_num_inputs(1) \
.set_num_outputs(1) \
.set_attr_parser(AxesParamParser<ReduceAxesParam>) \
.set_attr<nnvm::FInferShape>("FInferShape", ReduceAxesShape) \
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) \
.add_argument("data", "NDArray-or-Symbol", "The input") \
.add_arguments(ReduceAxesParam::__FIELDS__())
#define MXNET_OPERATOR_REGISTER_REDUCE_BACKWARD(name) \
NNVM_REGISTER_OP(name) \
.set_num_outputs(1) \
.set_attr_parser(AxesParamParser<ReduceAxesParam>) \
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
#define MXNET_OPERATOR_REGISTER_BROADCAST(name) \
NNVM_REGISTER_OP(name) \
.set_num_inputs(1) \
.set_num_outputs(1) \
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) \
.set_attr<nnvm::FGradient>("FGradient", \
[](const nnvm::NodePtr& n, \
const std::vector<nnvm::NodeEntry>& ograds) { \
return MakeNonlossGradNode("_broadcast_backward", n, ograds, {}, \
{{"keepdims", "true"}}); \
}) \
.add_argument("data", "NDArray-or-Symbol", "The input")
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_OP_H_
| [
"xuyemaovip@nudt.edu.cn"
] | xuyemaovip@nudt.edu.cn |
f811c50c3b992203e05c2406742231535ee30d84 | cfd24a624e74a76098ea3ac94ee68efeb3c3b80b | /LinkedListCycleII.cpp | e2e0f9af8366b89a693cc9471b78aa980aef0465 | [] | no_license | galaxyLi/leetcode | fd2be425f9e7cccbac1e322cdf4a65cc2b8054a6 | d0f85f82a0c8164af3182d054e1045230a11e71a | refs/heads/master | 2020-04-04T21:01:43.865356 | 2014-10-24T09:23:35 | 2014-10-24T09:23:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *p1 = head;
ListNode *p2 = head;
while (true) {
if (!p1 || !p2) return NULL;
p1 = p1->next;
p2 = p2->next;
if (p2) p2 = p2->next;
else return NULL;
if (p1 == p2) break;
}
p1 = head;
while (p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
};
| [
"galaxybinbin@gmail.com"
] | galaxybinbin@gmail.com |
93f19d20ee81dbdca4449cf00ed8609747aaf150 | 9c6f5fbb43a00fdd4838d78b4299cdf2c34e279b | /tdt/cvs/driver/player2_179/player/frame_parser/frame_parser_video_vc1.cpp | 78b68b8cb52f575d9662dccdbc04de9c4b23e083 | [] | no_license | TitanNit/tdt | 90ac830771170abc96255457ef59780687ff0a47 | 22a09713b68c881fd1d4e4f6247b314cd52f4d7a | refs/heads/master | 2021-01-17T09:50:39.729337 | 2016-05-06T13:26:53 | 2016-05-06T13:26:53 | 34,450,580 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 97,518 | cpp | /************************************************************************
COPYRIGHT (C) STMicroelectronics R&D Ltd 2007
Source file name : frame_parser_video_vc1.cpp
Author : Mark C
Implementation of the VC-1 video frame parser class for player 2.
Date Modification Name
---- ------------ --------
01-Mar-07 Created Mark C
************************************************************************/
// /////////////////////////////////////////////////////////////////////
//
// Include any component headers
#include "frame_parser_video_vc1.h"
#include "ring_generic.h"
//#define DUMP_HEADERS
#define REMOVE_ANTI_EMULATION_BYTES
//{{{ Locally defined constants and macros
static BufferDataDescriptor_t Vc1StreamParametersBuffer = BUFFER_VC1_STREAM_PARAMETERS_TYPE;
static BufferDataDescriptor_t Vc1FrameParametersBuffer = BUFFER_VC1_FRAME_PARAMETERS_TYPE;
//
static struct Count_s
{
bool LegalValue;
unsigned int PanScanCountValue;
unsigned int DisplayCount0Value;
unsigned int DisplayCount1Value;
} Counts[] =
{
// ProgSeq Frame TFF RFF
{ true, 1, 1, 0 }, // 0 0 0 0
{ false, 0, 0, 0 }, // 0 0 0 1
{ true, 1, 1, 0 }, // 0 0 1 0
{ false, 0, 0, 0 }, // 0 0 1 1
{ true, 2, 1, 1 }, // 0 1 0 0
{ true, 3, 2, 1 }, // 0 1 0 1
{ true, 2, 1, 1 }, // 0 1 1 0
{ true, 3, 2, 1 }, // 0 1 1 1
{ false, 0, 0, 0 }, // 1 0 0 0
{ false, 0, 0, 0 }, // 1 0 0 1
{ false, 0, 0, 0 }, // 1 0 1 0
{ false, 0, 0, 0 }, // 1 0 1 1
{ true, 1, 1, 0 }, // 1 1 0 0
{ true, 2, 2, 0 }, // 1 1 0 1
{ false, 0, 0, 0 }, // 1 1 1 0
{ true, 3, 3, 0 } // 1 1 1 1
};
#define CountsIndex( PS, F, TFF, RFF) ((((PS) != 0) << 3) | (((F) != 0) << 2) | (((TFF) != 0) << 1) | ((RFF) != 0))
#define Legal( PS, F, TFF, RFF) Counts[CountsIndex(PS, F, TFF, RFF)].LegalValue
#define PanScanCount( PS, F, TFF, RFF) Counts[CountsIndex(PS, F, TFF, RFF)].PanScanCountValue
#define DisplayCount0( PS, F, TFF, RFF) Counts[CountsIndex(PS, F, TFF, RFF)].DisplayCount0Value
#define DisplayCount1( PS, F, TFF, RFF) Counts[CountsIndex(PS, F, TFF, RFF)].DisplayCount1Value
//
#define MIN_LEGAL_ASPECT_RATIO_CODE 1
#define MAX_LEGAL_ASPECT_RATIO_CODE 4
// BEWARE !!!! you cannot declare static initializers of a constructed type such as Rational_t
// the compiler will silently ignore them..........
static unsigned int AspectRatioValues[][2] =
{
{ 0, 1 }, // 0 - Unspecified
{ 1, 1 }, // 1 - Square
{ 11, 12 }, // 2
{ 11, 10 }, // 3
{ 11, 16 }, // 4
{ 33, 40 }, // 5
{ 11, 24 }, // 6
{ 11, 20 }, // 7
{ 11, 32 }, // 8
{ 33, 80 }, // 9
{ 11, 18 }, // 10
{ 11, 15 }, // 11
{ 33, 64 }, // 12
{ 99, 160 }, // 13
{ 0, 1 } // 14 - Reserved
};
#define AspectRatios(N) Rational_t(AspectRatioValues[N][0],AspectRatioValues[N][1])
static unsigned int FieldPicture1[] =
{
VC1_PICTURE_CODING_TYPE_I,
VC1_PICTURE_CODING_TYPE_I,
VC1_PICTURE_CODING_TYPE_P,
VC1_PICTURE_CODING_TYPE_P,
VC1_PICTURE_CODING_TYPE_B,
VC1_PICTURE_CODING_TYPE_B,
VC1_PICTURE_CODING_TYPE_BI,
VC1_PICTURE_CODING_TYPE_BI
};
static unsigned int FieldPicture2[] =
{
VC1_PICTURE_CODING_TYPE_I,
VC1_PICTURE_CODING_TYPE_P,
VC1_PICTURE_CODING_TYPE_I,
VC1_PICTURE_CODING_TYPE_P,
VC1_PICTURE_CODING_TYPE_B,
VC1_PICTURE_CODING_TYPE_BI,
VC1_PICTURE_CODING_TYPE_B,
VC1_PICTURE_CODING_TYPE_BI
};
//
#define MIN_LEGAL_FRAME_RATE_CODE 1
#define MAX_LEGAL_FRAME_RATE_CODE 8
static unsigned int FrameRateValues[][2] =
{
{ 0, 1 }, // Forbidden
{ 24, 1 },
{ 25, 1 },
{ 30, 1 },
{ 50, 1 },
{ 60, 1 },
{ 48, 1 },
{ 72, 1 },
{ 0, 1 }, // Forbidden
{ 24000, 1001 },
{ 25000, 1001 },
{ 30000, 1001 },
{ 50000, 1001 },
{ 60000, 1001 },
{ 48000, 1001 },
{ 72000, 1001 }
};
#define FrameRates(N) Rational_t(FrameRateValues[N][0],FrameRateValues[N][1])
static PictureStructure_t PictureStructures[] =
{
StructureTopField,
StructureBottomField,
StructureBottomField,
StructureTopField,
};
#define DEFAULT_DECODE_TIME_OFFSET 3600 // 40ms in 90Khz ticks
#define MAXIMUM_DECODE_TIME_OFFSET (4 * 90000) // 4s in 90Khz ticks
static const unsigned int ReferenceFramesRequired[VC1_PICTURE_CODING_TYPE_SKIPPED+1] = {0, 0, 1, 2, 0, 1};
static SliceType_t SliceTypeTranslation[] = { INVALID_INDEX, SliceTypeI, SliceTypeP, SliceTypeB, SliceTypeI, INVALID_INDEX };
//#define REFERENCE_FRAMES_NEEDED( CodingType) (CodingType - 1)
#define REFERENCE_FRAMES_NEEDED(CodingType) ReferenceFramesRequired[CodingType]
#define MAX_REFERENCE_FRAMES_FOR_FORWARD_DECODE REFERENCE_FRAMES_NEEDED(VC1_PICTURE_CODING_TYPE_B)
#define Assert(L) if( !(L) ) \
{ \
report ( severity_error, "Assertion fail %s %d\n", __FUNCTION__, __LINE__ );\
Player->MarkStreamUnPlayable( Stream ); \
return FrameParserError; \
}
#define AssertAntiEmulationOk(Text) \
{ \
FrameParserStatus_t Status; \
Status = TestAntiEmulationBuffer(); \
if( Status != FrameParserNoError ) \
{ \
report( severity_error, "FrameParser_VideoVc1_c::%s - Anti Emulation Test fail.\n", Text ); \
Player->MarkStreamUnPlayable( Stream ); \
return FrameParserError; \
} \
}
struct FrameRate_s
{
unsigned int AverageTimePerFrame;
unsigned int FrameRateNumerator;
unsigned int FrameRateDenominator;
};
#define RECOGNISED_FRAME_RATES 12
static const struct FrameRate_s FrameRateList[RECOGNISED_FRAME_RATES] =
{ {416666, 1, 1},
{417083, 1, 2},
{400000, 2, 1},
{333333, 3, 1},
{333666, 3, 2},
{200000, 4, 1},
{166666, 5, 1},
{166833, 5, 2},
{208333, 6, 1},
{208541, 6, 2},
{138888, 7, 1},
{139027, 7, 2},
};
//}}}
//{{{ class constants and macros
const unsigned int FrameParser_VideoVc1_c::BFractionNumerator[23] =
{1, 1, 2, 1, 3, 1, 2, 3, 4, 1, 5, 1, 2, 3, 4, 5, 6, 1, 3, 5, 7, 0, 0};
const unsigned int FrameParser_VideoVc1_c::BFractionDenominator[23] =
{2, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 0, 0};
// See table 36 7.1.1.6
const unsigned char FrameParser_VideoVc1_c::Pquant[32] =
{0,1,2,3,4,5,6,7,8,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,27,29,31};
// See tables 46, 47, 48, 49 7.1.1.32 and 7.1.1.33
const Vc1MvMode_t FrameParser_VideoVc1_c::MvModeLowRate[5] =
{
VC1_MV_MODE_MV_HALF_PEL_BI,
VC1_MV_MODE_MV,
VC1_MV_MODE_MV_HALF_PEL,
VC1_MV_MODE_INTENSITY_COMP,
VC1_MV_MODE_MV_MIXED
};
const Vc1MvMode_t FrameParser_VideoVc1_c::MvModeHighRate[5] =
{
VC1_MV_MODE_MV,
VC1_MV_MODE_MV_MIXED,
VC1_MV_MODE_MV_HALF_PEL,
VC1_MV_MODE_INTENSITY_COMP,
VC1_MV_MODE_MV_HALF_PEL_BI
};
const Vc1MvMode_t FrameParser_VideoVc1_c::MvMode2LowRate[4] =
{
VC1_MV_MODE_MV_HALF_PEL_BI,
VC1_MV_MODE_MV,
VC1_MV_MODE_MV_HALF_PEL,
VC1_MV_MODE_MV_MIXED
};
const Vc1MvMode_t FrameParser_VideoVc1_c::MvMode2HighRate[4] =
{
VC1_MV_MODE_MV,
VC1_MV_MODE_MV_MIXED,
VC1_MV_MODE_MV_HALF_PEL,
VC1_MV_MODE_MV_HALF_PEL_BI
};
//}}}
// /////////////////////////////////////////////////////////////////////////
//
// Locally defined structures
//
// /////////////////////////////////////////////////////////////////////////
//
// Constructor
//
FrameParser_VideoVc1_c::FrameParser_VideoVc1_c (void)
{
Configuration.FrameParserName = "VideoVc1";
Configuration.StreamParametersCount = 32;
Configuration.StreamParametersDescriptor = &Vc1StreamParametersBuffer;
Configuration.FrameParametersCount = 32;
Configuration.FrameParametersDescriptor = &Vc1FrameParametersBuffer;
//
SequenceLayerMetaDataValid = false;
FrameRateValid = false;
memset (&ReferenceFrameList, 0x00, sizeof(ReferenceFrameList_t));
Reset();
}
// /////////////////////////////////////////////////////////////////////////
//
// Destructor
//
FrameParser_VideoVc1_c::~FrameParser_VideoVc1_c (void)
{
Halt();
Reset();
}
//{{{ Reset
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief The Reset function release any resources, and reset all variable
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::Reset (void)
{
memset (&CopyOfStreamParameters, 0x00, sizeof(Vc1StreamParameters_t));
memset (&ReferenceFrameList, 0x00, sizeof(ReferenceFrameList_t));
memset (&FirstFieldPictureHeader, 0x00, sizeof(Vc1VideoPicture_t));
StreamParameters = NULL;
FrameParameters = NULL;
DeferredParsedFrameParameters = NULL;
DeferredParsedVideoParameters = NULL;
FirstDecodeOfFrame = true;
RangeMapValid = false;
RangeMapYFlag = false;
RangeMapY = 0;
RangeMapUVFlag = false;
RangeMapUV = 0;
FrameRateDefaultDen = 1001;
FrameRateDefaultNum = 24000;
return FrameParser_Video_c::Reset();
}
//}}}
//{{{ RegisterOutputBufferRing
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Register the output ring
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::RegisterOutputBufferRing (Ring_t Ring)
{
//
// Clear our parameter pointers
//
StreamParameters = NULL;
FrameParameters = NULL;
DeferredParsedFrameParameters = NULL;
DeferredParsedVideoParameters = NULL;
//
// Pass the call on down (we need the frame parameters count obtained by the lower level function).
//
return FrameParser_Video_c::RegisterOutputBufferRing (Ring);
}
//}}}
//{{{ PrepareReferenceFrameList
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Stream specific function to prepare a reference frame list
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::PrepareReferenceFrameList (void)
{
unsigned int i;
bool SelfReference;
unsigned int ReferenceFramesNeeded;
unsigned int PictureCodingType;
Vc1VideoPicture_t* PictureHeader;
//
// Note we cannot use StreamParameters or FrameParameters to address data directly,
// as these may no longer apply to the frame we are dealing with.
// Particularly if we have seen a sequenece header or group of pictures
// header which belong to the next frame.
//
PictureHeader = &(((Vc1FrameParameters_t *)(ParsedFrameParameters->FrameParameterStructure))->PictureHeader);
PictureCodingType = PictureHeader->ptype;
ReferenceFramesNeeded = REFERENCE_FRAMES_NEEDED(PictureCodingType);
//
// Detect the special case of a second field referencing the first
// this is when we have the field startup condition
// I P P P
// where the first P actually references its own decode buffer.
//
SelfReference = (!PictureHeader->first_field) && (ReferenceFramesNeeded == 1) && (ReferenceFrameList.EntryCount == 0);
//
// Check for sufficient reference frames. We cannot decode otherwise
//
if ((!SelfReference) && (ReferenceFrameList.EntryCount < ReferenceFramesNeeded))
return FrameParserInsufficientReferenceFrames;
ParsedFrameParameters->NumberOfReferenceFrameLists = 1;
ParsedFrameParameters->ReferenceFrameList[0].EntryCount = ReferenceFramesNeeded;
if (SelfReference)
{
ParsedFrameParameters->ReferenceFrameList[0].EntryIndicies[0] = NextDecodeFrameIndex;
}
else
{
for(i=0; i<ReferenceFramesNeeded; i++)
ParsedFrameParameters->ReferenceFrameList[0].EntryIndicies[i] = ReferenceFrameList.EntryIndicies[ReferenceFrameList.EntryCount - ReferenceFramesNeeded + i];
}
//report (severity_info, "Prepare Ref list %d %d - %d %d - %d %d %d\n", ParsedFrameParameters->ReferenceFrameList[0].EntryIndicies[0], ParsedFrameParameters->ReferenceFrameList[0].EntryIndicies[1],
// ReferenceFrameList.EntryIndicies[0], ReferenceFrameList.EntryIndicies[1],
// ReferenceFramesNeeded, ReferenceFrameList.EntryCount, ReferenceFrameList.EntryCount - ReferenceFramesNeeded );
return FrameParserNoError;
}
//}}}
//{{{ ForPlayUpdateReferenceFrameList
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Stream specific function to prepare a reference frame list
/// A reference frame is only recorded as such on the last field, in order to
/// ensure the correct management of reference frames in the codec, the
/// codec is informed immediately of a release on the first field of a field picture.
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::ForPlayUpdateReferenceFrameList (void)
{
unsigned int i;
bool LastField;
if (ParsedFrameParameters->ReferenceFrame)
{
LastField = (ParsedVideoParameters->PictureStructure == StructureFrame) ||
!ParsedFrameParameters->FirstParsedParametersForOutputFrame;
if (LastField)
{
if (ReferenceFrameList.EntryCount >= MAX_REFERENCE_FRAMES_FOR_FORWARD_DECODE)
{
Player->CallInSequence (Stream, SequenceTypeImmediate, TIME_NOT_APPLICABLE, CodecFnReleaseReferenceFrame, ReferenceFrameList.EntryIndicies[0]);
ReferenceFrameList.EntryCount--;
for (i=0; i<ReferenceFrameList.EntryCount; i++)
ReferenceFrameList.EntryIndicies[i] = ReferenceFrameList.EntryIndicies[i+1];
}
ReferenceFrameList.EntryIndicies[ReferenceFrameList.EntryCount++] = ParsedFrameParameters->DecodeFrameIndex;
}
else
{
Player->CallInSequence (Stream, SequenceTypeImmediate, TIME_NOT_APPLICABLE, CodecFnReleaseReferenceFrame, ParsedFrameParameters->DecodeFrameIndex);
}
}
return FrameParserNoError;
}
//}}}
//{{{ RevPlayProcessDecodeStacks
// /////////////////////////////////////////////////////////////////////////
//
// Stream specific override function for processing decode stacks, this
// initializes the post decode ring before passing itno the real
// implementation of this function.
//
FrameParserStatus_t FrameParser_VideoVc1_c::RevPlayProcessDecodeStacks (void)
{
ReverseQueuedPostDecodeSettingsRing->Flush();
return FrameParser_Video_c::RevPlayProcessDecodeStacks();
}
//}}}
//{{{ RevPlayGeneratePostDecodeParameterSettings
// /////////////////////////////////////////////////////////////////////////
//
// Stream specific function to generate the post decode parameter
// settings for reverse play, these consist of the display frame index,
// and presentation time, both of which may be deferred if the information
// is unavailable.
//
// For reverse play, this function will use a simple numbering system,
// Imaging a sequence I B B P B B this should be numbered (in reverse) as
// 3 5 4 0 2 1
// These will be presented to this function in reverse order ( B B P B B I)
// so for non ref frames we ring them, and for ref frames we use the next number
// and then process what is on the ring.
//
FrameParserStatus_t FrameParser_VideoVc1_c::RevPlayGeneratePostDecodeParameterSettings (void)
{
//
// If this is the first decode of a frame then we need display frame indices and presentation timnes
//
if (ParsedFrameParameters->FirstParsedParametersForOutputFrame)
{
//
// If this is not a reference frame then place it on the ring for calculation later
//
if (!ParsedFrameParameters->ReferenceFrame)
{
ReverseQueuedPostDecodeSettingsRing->Insert ((unsigned int)ParsedFrameParameters);
ReverseQueuedPostDecodeSettingsRing->Insert ((unsigned int)ParsedVideoParameters);
}
else
//
// If this is a reference frame then first process it, then process the frames on the ring
//
{
CalculateFrameIndexAndPts (ParsedFrameParameters, ParsedVideoParameters);
while (ReverseQueuedPostDecodeSettingsRing->NonEmpty())
{
ReverseQueuedPostDecodeSettingsRing->Extract ((unsigned int *)&DeferredParsedFrameParameters);
ReverseQueuedPostDecodeSettingsRing->Extract ((unsigned int *)&DeferredParsedVideoParameters);
CalculateFrameIndexAndPts (DeferredParsedFrameParameters, DeferredParsedVideoParameters);
}
}
}
//
return FrameParserNoError;
}
//}}}
//{{{ RevPlayRemoveReferenceFrameFromList
// /////////////////////////////////////////////////////////////////////////
//
// Stream specific function to remove a frame from the reference
// frame list in reverse play.
//
// Note, we only inserted the reference frame in the list on the last
// field but we need to inform the codec we are finished with it on both
// fields (for field pictures).
//
FrameParserStatus_t FrameParser_VideoVc1_c::RevPlayRemoveReferenceFrameFromList (void)
{
bool LastField;
LastField = (ParsedVideoParameters->PictureStructure == StructureFrame) ||
!ParsedFrameParameters->FirstParsedParametersForOutputFrame;
if ((ReferenceFrameList.EntryCount != 0) && LastField)
{
Player->CallInSequence (Stream, SequenceTypeImmediate, TIME_NOT_APPLICABLE, CodecFnReleaseReferenceFrame, ParsedFrameParameters->DecodeFrameIndex);
if (LastField)
ReferenceFrameList.EntryCount--;
}
return FrameParserNoError;
}
//}}}
//{{{ ReadHeaders
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Scan the start code list reading header specific information
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::ReadHeaders (void)
{
unsigned int i;
unsigned int Code;
FrameParserStatus_t Status;
bool FrameReadyForDecode = false;
#if 0
report (severity_info, "Start codes (%d):", StartCodeList->NumberOfStartCodes);
for (i=0; i<StartCodeList->NumberOfStartCodes; i++)
report (severity_info, " %02x(%d)", ExtractStartCodeCode(StartCodeList->StartCodes[i]), ExtractStartCodeOffset(StartCodeList->StartCodes[i]));
report (severity_info, "\n");
#endif
for (i=0; i<StartCodeList->NumberOfStartCodes; i++)
{
Code = StartCodeList->StartCodes[i];
#if defined (REMOVE_ANTI_EMULATION_BYTES)
LoadAntiEmulationBuffer (BufferData + ExtractStartCodeOffset(Code));
CheckAntiEmulationBuffer (METADATA_ANTI_EMULATION_REQUEST);
#else
Bits.SetPointer (BufferData + ExtractStartCodeOffset(Code));
#endif
Bits.FlushUnseen(32);
Status = FrameParserNoError;
if (FrameReadyForDecode && (ExtractStartCodeCode(Code) != VC1_SLICE_START_CODE))
{
Status = CommitFrameForDecode();
FrameReadyForDecode = false;
}
switch (ExtractStartCodeCode(Code))
{
case VC1_FRAME_START_CODE:
//report (severity_info, "VC1_FRAME_START_CODE\n");
// Record the first Picture Header as the start of the data to be decoded.
// In interlaced field streams, Frame Start Code denotes first field.
ParsedFrameParameters->DataOffset = ExtractStartCodeOffset(Code);
if (ReadPictureHeaderAdvancedProfile (1) == FrameParserNoError)
FrameReadyForDecode = true;
break;
case VC1_FIELD_START_CODE:
//report (severity_info, "VC1_FIELD_START_CODE\n");
// Record the first Picture Header as the start of the data to be decoded.
// In interlaced field streams, Field Start Code denotes second field.
// Commit the first field for decode?
// Status = CommitFrameForDecode();
ParsedFrameParameters->DataOffset = ExtractStartCodeOffset(Code);
if (ReadPictureHeaderAdvancedProfile (0) == FrameParserNoError)
FrameReadyForDecode = true;
break;
case VC1_SEQUENCE_HEADER_CODE:
//report (severity_info, "VC1_SEQUENCE_HEADER_CODE\n");
Status = ReadSequenceHeader();
break;
case VC1_SEQUENCE_LAYER_METADATA_START_CODE:
//report (severity_info, "VC1_SEQUENCE_LAYER_METADATA_START_CODE\n");
if (!SequenceLayerMetaDataValid)
Status = ReadSequenceLayerMetadata();
break;
case VC1_SLICE_START_CODE:
//report (severity_info, "VC1_SLICE_START_CODE\n");
// Build a list of the slices in this frame, recording an entry for each
// SLICE_START_CODE as needed by the VC1 decoder.
Status = ReadSliceHeader(ExtractStartCodeOffset(Code));
break;
case VC1_ENTRY_POINT_HEADER_CODE:
//report (severity_info, "VC1_ENTRY_POINT_HEADER_CODE\n");
Status = ReadEntryPointHeader();
break;
case VC1_END_OF_SEQUENCE:
//report (severity_info, "VC1_END_OF_SEQUENCE\n");
break;
case 8:
FrameRateDefaultDen = Bits.Get(32);
FrameRateDefaultNum = Bits.Get(32);
report (severity_error, "Received framerate %d / %d\n", FrameRateDefaultDen, FrameRateDefaultNum);
break;
default:
#if 0
{
unsigned char* Buff = &BufferData[ExtractStartCodeOffset(Code)-12];
report (severity_info, "::::%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
Buff[0], Buff[1], Buff[2], Buff[3], Buff[4], Buff[5], Buff[6], Buff[7],
Buff[8], Buff[9], Buff[10], Buff[11], Buff[12], Buff[13], Buff[14], Buff[15],
Buff[16], Buff[17], Buff[18], Buff[19], Buff[20], Buff[21], Buff[22], Buff[23],
Buff[24], Buff[25], Buff[26], Buff[27], Buff[28], Buff[29], Buff[30], Buff[31]);
}
report (severity_error, "Unknown start code %x\n", ExtractStartCodeCode(Code));
#endif
Status = FrameParserUnhandledHeader;
break;
}
if ((Status != FrameParserNoError) && (Status != FrameParserUnhandledHeader))
return Status;
#if defined (REMOVE_ANTI_EMULATION_BYTES)
// Check that we didn't lose track and overun the anti-emulation buffer
AssertAntiEmulationOk (__FUNCTION__);
#endif
}
// Finished processing all the start codes, send the frame to be decoded.
if (FrameReadyForDecode)
{
Status = CommitFrameForDecode();
FrameReadyForDecode = false;
}
return FrameParserNoError;
}
//}}}
//{{{ ReadSequenceHeader
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Read in a sequence header
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::ReadSequenceHeader (void)
{
FrameParserStatus_t Status;
Vc1VideoSequence_t *Header;
//
if ((StreamParameters != NULL) && (StreamParameters->SequenceHeaderPresent) &&
(StreamParameters->SequenceHeader.profile != VC1_ADVANCED_PROFILE))
{
report (severity_error, "%s: Sequence header only valid for advanced profile\n", __FUNCTION__);
//return FrameParserError;
}
Status = GetNewStreamParameters ((void **)&StreamParameters);
if (Status != FrameParserNoError)
return Status;
StreamParameters->UpdatedSinceLastFrame = true;
Header = &StreamParameters->SequenceHeader;
memset (Header, 0x00, sizeof(Vc1VideoSequence_t));
// clear out entrypoint header - it can only occur after a sequence header
memset (&StreamParameters->EntryPointHeader, 0x00, sizeof(Vc1VideoEntryPoint_t));
//
#if 0
{
unsigned char* Buff;
unsigned int Bib;
Bits.GetPosition(&Buff, &Bib);
Buff -= 8;
report (severity_info, "::::%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
Buff[0], Buff[1], Buff[2], Buff[3], Buff[4], Buff[5], Buff[6], Buff[7],
Buff[8], Buff[9], Buff[10], Buff[11], Buff[12], Buff[13], Buff[14], Buff[15],
Buff[16], Buff[17], Buff[18], Buff[19], Buff[20], Buff[21], Buff[22], Buff[23],
Buff[24], Buff[25], Buff[26], Buff[27], Buff[28], Buff[29], Buff[30], Buff[31]);
}
#endif
if (Bits.Show(2) != VC1_ADVANCED_PROFILE)
{
report (severity_error, "Invalid sequence header\n");
return FrameParserError;
}
Header->profile = Bits.Get(2);
Header->level = Bits.Get(3);
Header->colordiff_format = Bits.Get(2);
Header->frmrtq_postproc = Bits.Get(3);
Header->bitrtq_postproc = Bits.Get(5);
Header->postprocflag = Bits.Get(1);
Header->max_coded_width = (Bits.Get(12)) * 2 + 2;
Header->max_coded_height = (Bits.Get(12)) * 2 + 2;
Header->pulldown = Bits.Get(1);
Header->interlace = Bits.Get(1);
Header->tfcntrflag = Bits.Get(1);
Header->finterpflag = Bits.Get(1);
Header->reserved = Bits.Get(1);
Header->psf = Bits.Get(1);
Header->display_ext = Bits.Get(1);
if (Header->display_ext == 1)
{
Header->disp_horiz_size = Bits.Get(14) + 1;
Header->disp_vert_size = Bits.Get(14) + 1;
Header->aspect_ratio_flag = Bits.Get(1);
if (Header->aspect_ratio_flag == 1)
{
Header->aspect_ratio = Bits.Get(4);
if (Header->aspect_ratio == 15)
{
Header->aspect_horiz_size = Bits.Get(8);
Header->aspect_vert_size = Bits.Get(8);
}
}
Header->frame_rate_flag = Bits.Get(1);
if (Header->frame_rate_flag == 1)
{
Header->frame_rate_ind = Bits.Get(1);
if (Header->frame_rate_ind == 0)
{
Header->frameratenr = Bits.Get(8);
Header->frameratedr = Bits.Get(4);
if (Header->frameratenr > 7)
Header->frameratenr = 0;
if (Header->frameratedr > 2)
Header->frameratedr = 0;
}
else
{
Header->framerateexp = Bits.Get(16);
}
}
Header->color_format_flag = Bits.Get(1);
if (Header->color_format_flag == 1)
{
Header->color_prim = Bits.Get(8);
Header->transfer_char = Bits.Get(8);
Header->matrix_coef = Bits.Get(8);
}
Header->hrd_param_flag = Bits.Get(1);
if (Header->hrd_param_flag == 1)
{
// Hypothetical Reference Decoder Indicator Flag is set, so read the HRD parameters
// from the stream. We are only interested in the number of parameter sets as it affects
// the interpretation of the entry point header.
Header->hrd_num_leaky_buckets = Bits.Get(5);
}
}
StreamParameters->SequenceHeaderPresent = true;
#ifdef DUMP_HEADERS
report (severity_info, "Sequence header :- \n");
report (severity_info, " profile : %6d\n", Header->profile);
report (severity_info, " level : %6d\n", Header->level);
report (severity_info, " colordiff_format : %6d\n", Header->colordiff_format);
report (severity_info, " max_coded_width : %6d\n", Header->max_coded_width);
report (severity_info, " max_coded_height : %6d\n", Header->max_coded_height);
report (severity_info, " pulldown : %6d\n", Header->pulldown);
report (severity_info, " interlace : %6d\n", Header->interlace);
report (severity_info, " tfcntrflag : %6d\n", Header->tfcntrflag);
report (severity_info, " finterpflag : %6d\n", Header->finterpflag);
report (severity_info, " psf : %6d\n", Header->psf);
report (severity_info, " display_ext : %6d\n", Header->display_ext);
report (severity_info, " disp_horiz_size : %6d\n", Header->disp_horiz_size);
report (severity_info, " disp_vert_size : %6d\n", Header->disp_vert_size);
report (severity_info, " aspect_ratio_flag : %6d\n", Header->aspect_ratio_flag);
report (severity_info, " frame_rate_flag : %6d\n", Header->frame_rate_flag);
report (severity_info, " frameratenr : %6d\n", Header->frameratenr);
report (severity_info, " frameratedr : %6d\n", Header->frameratedr);
report (severity_info, " frmrtq_postproc : %6d\n", Header->frmrtq_postproc);
report (severity_info, " bitrtq_postproc : %6d\n", Header->bitrtq_postproc);
report (severity_info, " postprocflag : %6d\n", Header->postprocflag);
report (severity_info, " color_format_flag : %6d\n", Header->color_format_flag);
report (severity_info, " hrd_param_flag : %6d\n", Header->hrd_param_flag);
report (severity_info, " hrd_num_leaky_buckets : %6d\n", Header->hrd_num_leaky_buckets);
#endif
#if defined (REMOVE_ANTI_EMULATION_BYTES)
AssertAntiEmulationOk (__FUNCTION__);
#endif
Assert (Header->level <= VC1_HIGHEST_LEVEL_SUPPORTED);
Assert (Header->max_coded_width <= VC1_MAX_CODED_WIDTH);
Assert (Header->max_coded_height <= VC1_MAX_CODED_HEIGHT);
return FrameParserNoError;
}
//}}}
//{{{ ReadEntryPointHeader
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Read in the Entry Point Layer
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::ReadEntryPointHeader (void)
{
FrameParserStatus_t Status;
Vc1VideoEntryPoint_t *Header;
Vc1VideoSequence_t *SequenceHeader;
//
if ((StreamParameters != NULL) && (StreamParameters->SequenceHeaderPresent) &&
(StreamParameters->SequenceHeader.profile != VC1_ADVANCED_PROFILE))
{
report (severity_error, "%s: Entrypoint header only valid for advanced profile\n", __FUNCTION__);
return FrameParserError;
}
if (StreamParameters == NULL)
{
Status = GetNewStreamParameters ((void **)&StreamParameters);
if (Status != FrameParserNoError)
return Status;
}
SequenceHeader = &StreamParameters->SequenceHeader;
#if 0
{
unsigned char* Buff;
unsigned int Bib;
Bits.GetPosition(&Buff, &Bib);
Buff -= 8;
report (severity_info, "EPH::::%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
Buff[0], Buff[1], Buff[2], Buff[3], Buff[4], Buff[5], Buff[6], Buff[7],
Buff[8], Buff[9], Buff[10], Buff[11], Buff[12], Buff[13], Buff[14], Buff[15],
Buff[16], Buff[17], Buff[18], Buff[19], Buff[20], Buff[21], Buff[22], Buff[23],
Buff[24], Buff[25], Buff[26], Buff[27], Buff[28], Buff[29], Buff[30], Buff[31]);
}
#endif
// StreamParameters->UpdatedSinceLastFrame = true; // Dont set this as it'll invoke MME global params
Header = &StreamParameters->EntryPointHeader;
memset (Header, 0x00, sizeof(Vc1VideoEntryPoint_t));
Header->broken_link = Bits.Get(1);
Header->closed_entry = Bits.Get(1);
Header->panscan_flag = Bits.Get(1);
Header->refdist_flag = Bits.Get(1);
Header->loopfilter = Bits.Get(1);
Header->fastuvmc = Bits.Get(1);
Header->extended_mv = Bits.Get(1);
Header->dquant = Bits.Get(2);
Header->vstransform = Bits.Get(1);
Header->overlap = Bits.Get(1);
Header->quantizer = Bits.Get(2);
if (SequenceHeader->hrd_param_flag == 1)
{
// Skip HRD_FULL[n] for each leaky bucket
unsigned int n;
for (n = 0; n < SequenceHeader->hrd_num_leaky_buckets; n++)
Bits.Get(8);
}
Header->coded_size_flag = Bits.Get(1);
if (Header->coded_size_flag == 1)
{
unsigned int Width = Bits.Get(12);
unsigned int Height = Bits.Get(12);
Header->coded_width = (Width * 2) + 2;
if (Header->coded_width > SequenceHeader->max_coded_width)
{
report (severity_info, "FrameParser_VideoVc1_c::ReadEntryPointHeader: Warning Coded Width %d greater than MaxCodedWidth %d - using %d\n",
Header->coded_width, SequenceHeader->max_coded_width, SequenceHeader->max_coded_width);
Header->coded_width = SequenceHeader->max_coded_width;
}
Header->coded_height = (Height * 2) + 2;
if (Header->coded_height > SequenceHeader->max_coded_height)
{
report (severity_info, "FrameParser_VideoVc1_c::ReadEntryPointHeader: Warning Coded Height %d greater than MaxCodedHeight %d - using %d\n",
Header->coded_height, SequenceHeader->max_coded_height, SequenceHeader->max_coded_height);
Header->coded_height = SequenceHeader->max_coded_height;
}
}
if (Header->extended_mv == 1)
{
Header->extended_dmv = Bits.Get(1);
}
Header->range_mapy_flag = Bits.Get(1);
if (Header->range_mapy_flag == 1)
{
Header->range_mapy = Bits.Get(3);
report (severity_info, "%s: range_mapy : %6d\n", __FUNCTION__, Header->range_mapy);
}
Header->range_mapuv_flag = Bits.Get(1);
if (Header->range_mapuv_flag == 1)
{
Header->range_mapuv = Bits.Get(3);
report (severity_info, "%s: range_mapuv : %6d\n", __FUNCTION__, Header->range_mapuv);
}
if ((Header->closed_entry == 0) && RangeMapValid)
{
Header->range_mapy_flag = RangeMapYFlag;
Header->range_mapy = RangeMapY;
Header->range_mapuv_flag = RangeMapUVFlag;
Header->range_mapuv = RangeMapUV;
}
else
{
RangeMapYFlag = Header->range_mapy_flag;
RangeMapY = Header->range_mapy;
RangeMapUVFlag = Header->range_mapuv_flag;
RangeMapUV = Header->range_mapuv;
RangeMapValid = true;
}
StreamParameters->EntryPointHeaderPresent = true;
#ifdef DUMP_HEADERS
report (severity_note, "EntryPoint header :- \n");
report (severity_info, " broken_link : %6d\n", Header->broken_link);
report (severity_info, " closed_entry : %6d\n", Header->closed_entry);
report (severity_info, " panscan_flag : %6d\n", Header->panscan_flag);
report (severity_info, " refdist_flag : %6d\n", Header->refdist_flag);
report (severity_info, " loopfilter : %6d\n", Header->loopfilter);
report (severity_info, " coded_size_flag : %6d\n", Header->coded_size_flag);
report (severity_info, " coded_width : %6d\n", Header->coded_width);
report (severity_info, " coded_height : %6d\n", Header->coded_height);
report (severity_info, " extended_mv : %6d\n", Header->extended_mv);
report (severity_info, " dquant : %6d\n", Header->dquant);
report (severity_info, " vstransform : %6d\n", Header->vstransform);
report (severity_info, " overlap : %6d\n", Header->overlap);
report (severity_info, " quantizer : %6d\n", Header->quantizer);
report (severity_info, " extended_dmv : %6d\n", Header->extended_dmv);
report (severity_info, " range_mapy_flag : %6d\n", Header->range_mapy_flag);
report (severity_info, " range_mapy : %6d\n", Header->range_mapy);
report (severity_info, " range_mapuv_flag : %6d\n", Header->range_mapuv_flag);
report (severity_info, " range_mapuv : %6d\n", Header->range_mapuv);
#endif
#if defined (REMOVE_ANTI_EMULATION_BYTES)
AssertAntiEmulationOk (__FUNCTION__);
#endif
return FrameParserNoError;
}
//}}}
//{{{ ReadPictureHeaderAdvancedProfile
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Read in a picture header
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::ReadPictureHeaderAdvancedProfile (unsigned int first_field)
{
int Val;
FrameParserStatus_t Status;
Vc1VideoPicture_t* Header;
Vc1VideoSequence_t* SequenceHeader;
Vc1VideoEntryPoint_t* EntryPointHeader;
unsigned char* StartPointer;
unsigned int StartBitsInByte;
//
if ((StreamParameters == NULL) || !StreamParameters->SequenceHeaderPresent)
{
report (severity_error, "FrameParser_VideoVc1_c::ReadPictureHeader - Sequence header not found.\n");
return FrameParserNoStreamParameters;
}
//
if (FrameParameters == NULL)
{
Status = GetNewFrameParameters ((void **)&FrameParameters);
if (Status != FrameParserNoError)
{
report (severity_error, "FrameParser_VideoVc1_c::ReadPictureHeader - Failed to get new frame parameters.\n");
return Status;
}
}
Header = &FrameParameters->PictureHeader;
memset (Header, 0x00, sizeof(Vc1VideoPicture_t));
SequenceHeader = &StreamParameters->SequenceHeader;
EntryPointHeader = &StreamParameters->EntryPointHeader;
//
#if 0
{
unsigned char* Buff;
unsigned int Bib;
static unsigned int PictureNo;
Bits.GetPosition(&Buff, &Bib);
Buff -= 8;
report (severity_info, "Picture %d::::%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
PictureNo++, Buff[0], Buff[1], Buff[2], Buff[3], Buff[4], Buff[5], Buff[6], Buff[7],
Buff[8], Buff[9], Buff[10], Buff[11], Buff[12], Buff[13], Buff[14], Buff[15],
Buff[16], Buff[17], Buff[18], Buff[19], Buff[20], Buff[21], Buff[22], Buff[23],
Buff[24], Buff[25], Buff[26], Buff[27], Buff[28], Buff[29], Buff[30], Buff[31]);
}
#endif
Bits.GetPosition (&StartPointer, &StartBitsInByte);
Header->first_field = first_field; // Determined from FIELD or FRAME start code
if (Header->first_field != 0)
{
if (SequenceHeader->interlace == 1) // 7.1.1.15
{
Val = BitsDotGetVc1VLC(2, VC1_VLC_LEAF_ZERO);
switch (Val)
{
case VC1_VLC_CODE(2, 1, 0x00): // 0b
Header->fcm = VC1_FCM_PROGRESSIVE;
break;
case VC1_VLC_CODE(2, 2, 0x02): // 10b
Header->fcm = VC1_FCM_FRAME_INTERLACED;
break;
case VC1_VLC_CODE(2, 2, 0x03): // 11b
// Use this with either FRAME_SC or FIELD_SC to determine if first
// or second field in a field interlaced picture. Use TFF to then
// identify if it is the top or bottom field.
Header->fcm = VC1_FCM_FIELD_INTERLACED;
break;
default:
report (severity_error, "FrameParser_VideoVc1_c::ReadPictureHeader - Unknown field information.\n");
return FrameParserHeaderSyntaxError;
}
}
if ((SequenceHeader->interlace == 1) && (Header->fcm == VC1_FCM_FIELD_INTERLACED)) // 7.1.1.4
{
Header->fptype = Bits.Get(3);
Header->ptype = FieldPicture1[Header->fptype];
}
else
{
Val = BitsDotGetVc1VLC(4, VC1_VLC_LEAF_ZERO); // Picture Type
switch (Val)
{
case VC1_VLC_CODE(4, 1, 0x00): // 0b
Header->ptype = VC1_PICTURE_CODING_TYPE_P;
break;
case VC1_VLC_CODE(4, 2, 0x02): // 10b
Header->ptype = VC1_PICTURE_CODING_TYPE_B;
break;
case VC1_VLC_CODE(4, 3, 0x06): // 110b
Header->ptype = VC1_PICTURE_CODING_TYPE_I;
break;
case VC1_VLC_CODE(4, 4, 0x0E): // 1110b
Header->ptype = VC1_PICTURE_CODING_TYPE_BI;
break;
case VC1_VLC_CODE(4, 4, 0x0F): // 1111b
Header->ptype = VC1_PICTURE_CODING_TYPE_SKIPPED;
break;
default:
report (severity_error, "FrameParser_VideoVc1_c::ReadPictureHeader - Unknown picture type.\n");
return FrameParserHeaderSyntaxError;
}
}
if ((SequenceHeader->tfcntrflag == 1) && (Header->ptype != VC1_PICTURE_CODING_TYPE_SKIPPED)) // 7.1.1.16
Header->tfcntr = Bits.Get(8); // Temporal Ref Frame Counter
if (SequenceHeader->pulldown == 1) // 7.1.1.17 etc
{
if ((SequenceHeader->interlace == 0) || (SequenceHeader->psf == 1))
{
Header->rptfrm = Bits.Get(2); // Repeat Frame Count
}
else
{
Header->tff = Bits.Get(1); // Top Field First
Header->rff = Bits.Get(1); // Repeat First Field
}
}
else
{
Header->tff = 1; // Defaults to true
}
if (EntryPointHeader->panscan_flag == 1) // 7.1.1.20
{
unsigned int i;
Header->ps_present = Bits.Get(1); // Pan & Scan Flags Present
if (Header->ps_present == 1)
{
// Calculate the number of Pan & Scan Windows - 8.9.1
if ((SequenceHeader->interlace == 1) && (SequenceHeader->psf == 0))
{
if (SequenceHeader->pulldown == 1)
Header->ps_window_count = 2 + Header->rff;
else
Header->ps_window_count = 2;
}
else
{
if (SequenceHeader->pulldown == 1)
Header->ps_window_count = 1 + Header->rptfrm;
else
Header->ps_window_count = 1;
}
for (i=0; i<Header->ps_window_count; i++)
{
Header->ps_hoffset[i] = Bits.Get(18);
Header->ps_voffset[i] = Bits.Get(18);
Header->ps_width[i] = Bits.Get(14);
Header->ps_height[i] = Bits.Get(14);
}
}
}
if (Header->ptype != VC1_PICTURE_CODING_TYPE_SKIPPED)
{
Header->rndctrl = Bits.Get(1); // Rounding Control Bit
if (SequenceHeader->interlace == 1)
Header->uvsamp = Bits.Get(1); // 7.1.1.26
if ((SequenceHeader->interlace == 0) || (Header->fcm == VC1_FCM_PROGRESSIVE))
ReadPictureHeaderProgressive ();
else
{
if (Header->fcm == VC1_FCM_FRAME_INTERLACED)
ReadPictureHeaderInterlacedFrame ();
else
{
unsigned char* EndPointer;
unsigned int EndBitsInByte;
// read remaining common fields for both first and second fields
if ((EntryPointHeader->refdist_flag == 1) && (Header->fptype <= 0x3)) // see 9.1.1.43
{
Header->refdist = Bits.Get(2);
if (Header->refdist == 0x3)
{
unsigned int N;
Val = BitsDotGetVc1VLC(13, VC1_VLC_LEAF_ZERO);
N = VC1_VLC_BITSREAD(13, Val);
Header->refdist = N+2;
}
BackwardRefDist = Header->refdist; // remember ref dist for future b frames
}
if (Header->fptype > 0x3) // B/B, B/BI, BI/B field pairs
{
unsigned int BFraction = Bits.Get(3); // see 7.1.1.14
if (BFraction == 0x07) // 111b
BFraction += Bits.Get(4);
Header->bfraction_numerator = BFractionNumerator[BFraction];
Header->bfraction_denominator = BFractionDenominator[BFraction];
Header->backward_refdist = BackwardRefDist;
}
Bits.GetPosition (&EndPointer, &EndBitsInByte);
Header->picture_layer_size = (((unsigned int)EndPointer - (unsigned int)StartPointer) * 8) + (StartBitsInByte - EndBitsInByte);
// Remember first field picture header for second field then read field specific data
// for first field.
memcpy (&FirstFieldPictureHeader, Header, sizeof (Vc1VideoPicture_t));
ReadPictureHeaderInterlacedField ();
}
}
}
}
else
{
// second field
// Set the picture type of the second field using the fptype we read in the first field
// Copy first field data from saved structure then read field specific data for second field
memcpy (Header, &FirstFieldPictureHeader, sizeof (Vc1VideoPicture_t));
memset (&FirstFieldPictureHeader, 0x00, sizeof (Vc1VideoPicture_t));
Header->ptype = FieldPicture2[Header->fptype];
Header->first_field = 0; // restore after being overwritten by memcpy
Header->ps_window_count = 0; // Pan scan info only with first field
ReadPictureHeaderInterlacedField ();
}
#if 0
switch (Header->ptype)
{
case VC1_PICTURE_CODING_TYPE_P: report (severity_info, "P frame\n"); break;
case VC1_PICTURE_CODING_TYPE_B: report (severity_info, "B frame\n"); break;
case VC1_PICTURE_CODING_TYPE_I: report (severity_info, "I frame\n"); break;
case VC1_PICTURE_CODING_TYPE_SKIPPED: report (severity_info, "Skipped frame\n"); break;
case VC1_PICTURE_CODING_TYPE_BI: report (severity_info, "BI frame\n"); break;
}
#endif
// Field_Picture_Layer starts here OR Frame_Picture continues here.
FrameParameters->PictureHeaderPresent = true;
#ifdef DUMP_HEADERS
report (severity_note, "Picture header :- \n");
report (severity_note, " fcm : %6d\n", Header->fcm);
report (severity_info, " fptype : %6d\n", Header->fptype);
report (severity_note, " ptype : %6d\n", Header->ptype);
report (severity_note, " rptfrm : %6d\n", Header->rptfrm);
report (severity_note, " tfcntr : %6d\n", Header->tfcntr);
report (severity_note, " tff : %6d\n", Header->tff);
report (severity_note, " rff : %6d\n", Header->rff);
report (severity_note, " ps_present : %6d\n", Header->ps_present);
report (severity_info, " bfraction_num : %6d\n", Header->bfraction_numerator);
report (severity_info, " bfraction_den : %6d\n", Header->bfraction_denominator);
report (severity_note, " rndctrl : %6d\n", Header->rndctrl);
report (severity_info, " pqindex : %6d\n", Header->pqindex);
report (severity_info, " halfqp : %6d\n", Header->halfqp);
report (severity_info, " pquant : %6d\n", Header->pquant);
report (severity_info, " pquantizer : %6d\n", Header->pquantizer);
report (severity_info, " refdist : %6d\n", Header->refdist);
report (severity_info, " backward_refdist : %6d\n", Header->backward_refdist);
report (severity_info, " numref : %6d\n", Header->numref);
report (severity_info, " reffield : %6d\n", Header->reffield);
report (severity_info, " postproc : %6d\n", Header->postproc);
report (severity_info, " mvrange : %6d\n", Header->mvrange);
report (severity_info, " respic : %6d\n", Header->respic);
report (severity_info, " mvmode : %6d\n", Header->mvmode);
report (severity_info, " mvmode2 : %6d\n", Header->mvmode2);
report (severity_info, " intensity_comp_field : %6d\n", Header->intensity_comp_field);
report (severity_info, " intensity_comp_top : %6d\n", Header->intensity_comp_top);
report (severity_info, " intensity_comp_bottom : %6d\n", Header->intensity_comp_bottom);
report (severity_info, " first_field : %6d\n", Header->first_field);
#endif
#if defined (REMOVE_ANTI_EMULATION_BYTES)
AssertAntiEmulationOk (__FUNCTION__);
#endif
return FrameParserNoError;
}
//}}}
//{{{ ReadSliceHeader
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Read in a slice header
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::ReadSliceHeader (unsigned int pSlice)
{
FrameParserStatus_t Status;
Vc1VideoSlice_t *Header;
int i;
#if defined (REMOVE_ANTI_EMULATION_BYTES)
CheckAntiEmulationBuffer (SLICE_ANTI_EMULATION_REQUEST);
#endif
if ((StreamParameters == NULL) || !StreamParameters->SequenceHeaderPresent)
{
report (severity_error, "FrameParser_VideoVc1_c::ReadSliceHeader - Appropriate sequence header not found.\n");
return FrameParserNoStreamParameters;
}
//
if (FrameParameters == NULL)
{
Status = GetNewFrameParameters ((void **)&FrameParameters);
if (Status != FrameParserNoError)
return Status;
}
Header = &FrameParameters->SliceHeaderList;
//memset (Header, 0x00, sizeof(Vc1VideoSlice_t));
i = Header->no_slice_headers;
//
Header->slice_start_code[i] = pSlice;
Header->slice_addr[i] = Bits.Get(9);
//
Header->no_slice_headers++;
FrameParameters->SliceHeaderPresent = true;
//
#ifdef DUMP_HEADERS
report (severity_note, "Slice header[%d] :- \n", i);
report (severity_note, " pSlice : %08x\n", pSlice);
report (severity_note, " slice_addr : %08x\n", Header->slice_addr[i]);
#endif
#if defined (REMOVE_ANTI_EMULATION_BYTES)
AssertAntiEmulationOk (__FUNCTION__);
#endif
return FrameParserNoError;
}
//}}}
//{{{ ReadSequenceLayerMetadata
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Read in an abc metadata structure
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::ReadSequenceLayerMetadata (void)
{
FrameParserStatus_t Status;
Vc1VideoSequence_t* SequenceHeader;
Vc1VideoEntryPoint_t* EntryPointHeader;
unsigned int FlagByte = 0;
unsigned int FlagWord = 0;
unsigned int NumFrames = 0;
unsigned int HrdBuffer;
unsigned int HrdRate;
unsigned int FrameRate;
unsigned int Temp;
//
// Conforms to Sequence Layer Data Structure - see table 265 in Annex L
// Must be only one in a stream
//
#if 0
int i;
report (severity_info, "data %d :\n", BufferLength);
for (i=0; i<32; i++)
report (severity_info, " %02x", BufferData[i]);
report (severity_info, "\n");
#endif
if ((StreamParameters != NULL) && (StreamParameters->SequenceHeaderPresent))
{
report (severity_error, "%s: Received Sequence Layer MetaData after previous sequence data\n", __FUNCTION__);
return FrameParserNoError;
}
Status = GetNewStreamParameters ((void **)&StreamParameters);
if (Status != FrameParserNoError)
return Status;
StreamParameters->UpdatedSinceLastFrame = true;
SequenceHeader = &StreamParameters->SequenceHeader;
memset (SequenceHeader, 0x00, sizeof(Vc1VideoSequence_t));
// some values go into the entry point header
EntryPointHeader = &StreamParameters->EntryPointHeader;
memset (EntryPointHeader, 0x00, sizeof(Vc1VideoEntryPoint_t));
NumFrames = Bits.Get (8); // Num frames
NumFrames |= (Bits.Get (8) << 8);
NumFrames |= (Bits.Get (8) << 16);
FlagByte = Bits.Get (8); // 8 bit flag must be 0xc5
if (FlagByte != 0xc5)
{
report (severity_error, "%s: Invalid flag word expected 0xc5 received 0x%02x\n", __FUNCTION__, FlagByte);
return FrameParserError;
}
FlagWord = Bits.Get (8); // must be 0x04
FlagWord |= (Bits.Get (8) << 8);
FlagWord |= (Bits.Get (8) << 16);
FlagWord |= (Bits.Get (8) << 24);
if (FlagWord != 0x04)
{
report (severity_error, "%s: Invalid flag word expected 0x00000004 received 0x%08x\n", __FUNCTION__, FlagWord);
return FrameParserError;
}
// Sequence Header Struct C - see table 263, 264 in Annex J
SequenceHeader->profile = Bits.Get (2); // PROFILE bits 0,1
Temp = Bits.Get(2); // PROFILE bits 2,3
if (SequenceHeader->profile == VC1_ADVANCED_PROFILE)
Temp = Bits.Get(28); // skip the rest
else
{
unsigned int Reserved3;
unsigned int Reserved4;
unsigned int Reserved5;
unsigned int Reserved6;
SequenceHeader->frmrtq_postproc = Bits.Get(3); // FRMRTQ_POSTPROC
SequenceHeader->bitrtq_postproc = Bits.Get(5); // BITRTQ_POSTPROC
EntryPointHeader->loopfilter = Bits.Get(1); // LOOPFILTER
Reserved3 = Bits.Get(1); // Reserved3
SequenceHeader->multires = Bits.Get(1); // MULTIRES
Reserved4 = Bits.Get(1); // Reserved4
EntryPointHeader->fastuvmc = Bits.Get(1); // FASTUVMC
EntryPointHeader->extended_mv = Bits.Get(1); // EXTENDED_MV
EntryPointHeader->dquant = Bits.Get(2); // DQUANT
EntryPointHeader->vstransform = Bits.Get(1); // VSTRANSFORM
Reserved5 = Bits.Get(1); // Reserved5
EntryPointHeader->overlap = Bits.Get(1); // OVERLAP
SequenceHeader->syncmarker = Bits.Get(1); // SYNCMARKER
SequenceHeader->rangered = Bits.Get(1); // RANGERED
SequenceHeader->maxbframes = Bits.Get(3); // MAXBFRAMES
EntryPointHeader->quantizer = Bits.Get(2); // QUANTIZER
SequenceHeader->finterpflag = Bits.Get(1); // FINTERPFLAG
Reserved6 = Bits.Get(1); // Reserved6
if ((Reserved3 != 0) | (Reserved4 != 1) || (Reserved5 != 0) || (Reserved6 != 1))
{
report (severity_error, "%s: Reserved values incorrect\n", __FUNCTION__);
return FrameParserError;
}
}
// Sequence Header Struct A - see table 260 in Annex J
SequenceHeader->max_coded_height = Bits.Get(8); // VERT_SIZE
SequenceHeader->max_coded_height |= (Bits.Get(8) << 8);
SequenceHeader->max_coded_height |= (Bits.Get(8) << 16);
SequenceHeader->max_coded_height |= (Bits.Get(8) << 24);
SequenceHeader->max_coded_width = Bits.Get(8); // VERT_SIZE
SequenceHeader->max_coded_width |= (Bits.Get(8) << 8);
SequenceHeader->max_coded_width |= (Bits.Get(8) << 16);
SequenceHeader->max_coded_width |= (Bits.Get(8) << 24);
FlagWord = Bits.Get(8); // must be 0x0c
FlagWord |= (Bits.Get (8) << 8);
FlagWord |= (Bits.Get (8) << 16);
FlagWord |= (Bits.Get (8) << 24);
if (FlagWord != 0x0c)
{
report (severity_error, "%s: Invalid flag word expected 0x0000000c received 0x%08x\n", __FUNCTION__, FlagWord);
return FrameParserError;
}
// Sequence Header Struct B
SequenceHeader->level = Bits.Get(3); // LEVEL
SequenceHeader->cbr = Bits.Get(1); // CBR
Temp = Bits.Get(4); // RES1
HrdBuffer = Bits.Get(8); // HRD_BUFFER
HrdBuffer |= (Bits.Get(8) << 8);
HrdBuffer |= (Bits.Get(8) << 16);
HrdRate = Bits.Get(8); // HRD_RATE
HrdRate |= (Bits.Get(8) << 8);
HrdRate |= (Bits.Get(8) << 16);
HrdRate |= (Bits.Get(8) << 24);
FrameRate = Bits.Get(8); // FRAMERATE
FrameRate |= (Bits.Get(8) << 8);
FrameRate |= (Bits.Get(8) << 16);
FrameRate |= (Bits.Get(8) << 24);
if ((FrameRate != 0) && (FrameRate != 0xffffffff))
{
int i;
// Value arrives as frame duration in units of 100 nanoseconds (from wmv header)
//SequenceHeader->frame_rate_ind = 1; // Special flag for wmv to indicate
//SequenceHeader->frameratenr = 10000000; // that we should use the frame rate
//SequenceHeader->frameratedr = FrameRate; // values directly
SequenceHeader->frame_rate_flag = 1; // Frame rate present
for (i=0; i < RECOGNISED_FRAME_RATES; i++)
{
int Diff = FrameRate - FrameRateList[i].AverageTimePerFrame;
if ((Diff >= -10) && (Diff <= 10)) // Arbitrarily select range of 1 microsecond
break;
}
if (i < RECOGNISED_FRAME_RATES)
{
SequenceHeader->frameratenr = FrameRateList[i].FrameRateNumerator;
SequenceHeader->frameratedr = FrameRateList[i].FrameRateDenominator;
this->FrameRate = FrameRates(SequenceHeader->frameratenr + ((SequenceHeader->frameratedr-1) << 3));
}
else if (FrameRate < 1000)
{
SequenceHeader->frame_rate_ind = 1;
SequenceHeader->framerateexp = (FrameRate*32)-1; // 6.1.14.4.4
this->FrameRate = Rational_t(SequenceHeader->framerateexp+1, 32);
}
else
{
SequenceHeader->frame_rate_ind = 1;
SequenceHeader->framerateexp = (320000000/FrameRate)-1; // 6.1.14.4.4
this->FrameRate = Rational_t(SequenceHeader->framerateexp+1, 32);
}
FrameRateValid = true;
}
StreamParameters->SequenceHeaderPresent = true;
StreamParameters->EntryPointHeaderPresent = true;
#ifdef DUMP_HEADERS
report (severity_info, "SequenceLayerMetadata :- \n");
report (severity_info, " profile : %6d\n", SequenceHeader->profile);
report (severity_info, " level : %6d\n", SequenceHeader->level);
report (severity_info, " max_coded_width : %6d\n", SequenceHeader->max_coded_width);
report (severity_info, " max_coded_height : %6d\n", SequenceHeader->max_coded_height);
report (severity_info, " interlace : %6d\n", SequenceHeader->interlace);
report (severity_info, " framerate : %6d\n", FrameRate);
report (severity_info, " frameratenr : %6d\n", SequenceHeader->frameratenr);
report (severity_info, " frameratedr : %6d\n", SequenceHeader->frameratedr);
report (severity_info, " frame_rate_flag : %6d\n", SequenceHeader->frame_rate_flag);
report (severity_info, " framerateexp : %6d\n", SequenceHeader->framerateexp);
report (severity_info, " frmrtq_postproc : %6d\n", SequenceHeader->frmrtq_postproc);
report (severity_info, " bitrtq_postproc : %6d\n", SequenceHeader->bitrtq_postproc);
report (severity_info, " loopfilter : %6d\n", EntryPointHeader->loopfilter);
report (severity_info, " multires : %6d\n", SequenceHeader->multires);
report (severity_info, " fastuvmc : %6d\n", EntryPointHeader->fastuvmc);
report (severity_info, " extended_ mv : %6d\n", EntryPointHeader->extended_mv);
report (severity_info, " dquant : %6d\n", EntryPointHeader->dquant);
report (severity_info, " vstransform : %6d\n", EntryPointHeader->vstransform);
report (severity_info, " overlap : %6d\n", EntryPointHeader->overlap);
report (severity_info, " syncmarker : %6d\n", SequenceHeader->syncmarker);
report (severity_info, " rangered : %6d\n", SequenceHeader->rangered);
report (severity_info, " maxbframes : %6d\n", SequenceHeader->maxbframes);
report (severity_info, " quantizer : %6d\n", EntryPointHeader->quantizer);
report (severity_info, " finterpflag : %6d\n", SequenceHeader->finterpflag);
#endif
SequenceLayerMetaDataValid = true;
return FrameParserNoError;
}
//}}}
//{{{ ReadPictureHeaderProgressive
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Read in the remainder of a progressive picture header
///
/// /////////////////////////////////////////////////////////////////////////
void FrameParser_VideoVc1_c::ReadPictureHeaderProgressive (void)
{
Vc1VideoPicture_t* Header;
Vc1VideoSequence_t* SequenceHeader;
Vc1VideoEntryPoint_t* EntryPointHeader;
Header = &FrameParameters->PictureHeader;
SequenceHeader = &StreamParameters->SequenceHeader;
EntryPointHeader = &StreamParameters->EntryPointHeader;
if (SequenceHeader->finterpflag == 1)
Header->interpfrm = Bits.Get(1);
if (Header->ptype == VC1_PICTURE_CODING_TYPE_B)
{
unsigned int BFraction = Bits.Get(3); // 7.1.1.14
if (BFraction == 0x07) // 111b
BFraction += Bits.Get(4);
Header->bfraction_numerator = BFractionNumerator[BFraction];
Header->bfraction_denominator = BFractionDenominator[BFraction];
}
Header->pqindex = Bits.Get(5); // 7.1.1.6
if (Header->pqindex <= 8)
Header->halfqp = Bits.Get(1); // 7.1.1.7
if (EntryPointHeader->quantizer == 0x00) // 7.1.1.8
{
Header->pquant = Pquant[Header->pqindex];
Header->pquantizer = (Header->pqindex <= 8) ? 1 : 0;
}
else
{
Header->pquant = Header->pqindex;
if (EntryPointHeader->quantizer == 0x01) // 7.1.1.8
Header->pquantizer = Bits.Get(1);
}
if (SequenceHeader->postprocflag == 1) // 7.1.1.27
Header->postproc = Bits.Get(2);
// We are not interested in any of the remaining I/BI header information so return
if ((Header->ptype == VC1_PICTURE_CODING_TYPE_I) || (Header->ptype == VC1_PICTURE_CODING_TYPE_BI))
return;
// Leaving just P and B pictures below.
if (EntryPointHeader->extended_mv == 0x01) // 7.1.1.9
{
Header->mvrange = BitsDotGetVc1VLC(3, VC1_VLC_LEAF_ZERO);
Header->mvrange = VC1_VLC_RESULT(3, Header->mvrange);
}
if (Header->ptype == VC1_PICTURE_CODING_TYPE_P)
{
for (Header->mvmode = 0; Header->mvmode < 4; Header->mvmode++) // 7.1.1.32
if (Bits.Get(1) == 0x01)
break;
Header->mvmode = (Header->pquant > 12) ? MvModeLowRate[Header->mvmode] : MvModeHighRate[Header->mvmode];
if (Header->mvmode == VC1_MV_MODE_INTENSITY_COMP)
{
unsigned int LumaScale;
unsigned int LumaShift;
for (Header->mvmode2 = 0; Header->mvmode2 < 3; Header->mvmode2++) // 7.1.1.33
if (Bits.Get(1) == 0x01)
break;
Header->mvmode2 = (Header->pquant > 12) ? MvMode2LowRate[Header->mvmode2] : MvMode2HighRate[Header->mvmode2];
LumaScale = Bits.Get(6); // 7.1.1.34
LumaShift = Bits.Get(6); // 7.1.1.35
Header->intensity_comp_top = (LumaScale << VC1_LUMASCALE_SHIFT) | (LumaShift << VC1_LUMASHIFT_SHIFT);
Header->intensity_comp_bottom = (LumaScale << VC1_LUMASCALE_SHIFT) | (LumaShift << VC1_LUMASHIFT_SHIFT);
Header->intensity_comp_field = VC1_INTENSITY_COMP_BOTH;
}
}
else
Header->mvmode = Bits.Get(1);
}
//}}}
//{{{ ReadPictureHeaderInterlacedFrame
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Read in the remainder of an interlacedFrame picture header
///
/// /////////////////////////////////////////////////////////////////////////
void FrameParser_VideoVc1_c::ReadPictureHeaderInterlacedFrame (void)
{
Vc1VideoPicture_t* Header;
Vc1VideoSequence_t* SequenceHeader;
Vc1VideoEntryPoint_t* EntryPointHeader;
Header = &FrameParameters->PictureHeader;
SequenceHeader = &StreamParameters->SequenceHeader;
EntryPointHeader = &StreamParameters->EntryPointHeader;
Header->pqindex = Bits.Get(5); // 7.1.1.6
if (Header->pqindex <= 8)
Header->halfqp = Bits.Get(1); // 7.1.1.7
if (EntryPointHeader->quantizer == 0x00) // 7.1.1.8
{
Header->pquant = Pquant[Header->pqindex];
Header->pquantizer = (Header->pqindex <= 8) ? 1 : 0;
}
else
{
Header->pquant = Header->pqindex;
if (EntryPointHeader->quantizer == 0x01) // 7.1.1.8
Header->pquantizer = Bits.Get(1);
}
if (SequenceHeader->postprocflag == 1)
Header->postproc = Bits.Get(2); // 7.1.1.27
// We are not interested in any of the remaining I/BI header information so return
if ((Header->ptype == VC1_PICTURE_CODING_TYPE_I) || (Header->ptype == VC1_PICTURE_CODING_TYPE_BI))
return;
if (Header->ptype == VC1_PICTURE_CODING_TYPE_B)
{
unsigned int BFraction = Bits.Get(3); // see 7.1.1.14
if (BFraction == 0x07) // 111b
BFraction += Bits.Get(4);
Header->bfraction_numerator = BFractionNumerator[BFraction];
Header->bfraction_denominator = BFractionDenominator[BFraction];
}
if (EntryPointHeader->extended_mv == 0x01) // 9.1.1.26
{
Header->mvrange = BitsDotGetVc1VLC(3, VC1_VLC_LEAF_ZERO);
Header->mvrange = VC1_VLC_RESULT(3, Header->mvrange);
}
if (EntryPointHeader->extended_dmv == 0x01) // 9.1.1.27
{
Header->dmvrange = BitsDotGetVc1VLC(3, VC1_VLC_LEAF_ZERO);
Header->dmvrange = VC1_VLC_RESULT(3, Header->dmvrange);
}
if (Header->ptype == VC1_PICTURE_CODING_TYPE_P)
{
Bits.Get(1); // 4mvswitch 9.1.1.28
if (Bits.Get(1) == 1) // intensity compensation
{
unsigned int LumaScale;
unsigned int LumaShift;
LumaScale = Bits.Get(6); // 9.1.1.30
LumaShift = Bits.Get(6); // 9.1.1.31
Header->intensity_comp_top = (LumaScale << VC1_LUMASCALE_SHIFT) | (LumaShift << VC1_LUMASHIFT_SHIFT);
Header->intensity_comp_bottom = (LumaScale << VC1_LUMASCALE_SHIFT) | (LumaShift << VC1_LUMASHIFT_SHIFT);
Header->intensity_comp_field = VC1_INTENSITY_COMP_BOTH;
}
}
}
//}}}
//{{{ ReadPictureHeaderInterlacedField
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Read in the remainder of an interlaced field picture header
///
/// /////////////////////////////////////////////////////////////////////////
void FrameParser_VideoVc1_c::ReadPictureHeaderInterlacedField (void)
{
Vc1VideoPicture_t* Header;
Vc1VideoSequence_t* SequenceHeader;
Vc1VideoEntryPoint_t* EntryPointHeader;
unsigned int MvModeBits;
Header = &FrameParameters->PictureHeader;
SequenceHeader = &StreamParameters->SequenceHeader;
EntryPointHeader = &StreamParameters->EntryPointHeader;
Header->pqindex = Bits.Get(5); // 7.1.1.6
if (Header->pqindex <= 8)
Header->halfqp = Bits.Get(1); // 7.1.1.7
if (EntryPointHeader->quantizer == 0x00) // 7.1.1.8
{
Header->pquant = Pquant[Header->pqindex];
Header->pquantizer = (Header->pqindex <= 8) ? 1 : 0;
}
else
{
Header->pquant = Header->pqindex;
if (EntryPointHeader->quantizer == 0x01) // 7.1.1.8
Header->pquantizer = Bits.Get(1);
}
if (SequenceHeader->postprocflag == 0x01)
Header->postproc = Bits.Get(2); // 7.1.1.27
// We are not interested in any of the remaining I/BI header information so return
if ((Header->ptype == VC1_PICTURE_CODING_TYPE_I) || (Header->ptype == VC1_PICTURE_CODING_TYPE_BI))
return;
if (Header->ptype == VC1_PICTURE_CODING_TYPE_P)
{
Header->numref = Bits.Get(1); // 9.1.1.44
if (Header->numref == 0)
Header->reffield = Bits.Get(1); // 9.1.1.45
}
if (EntryPointHeader->extended_mv == 0x01) // 9.1.1.26
{
Header->mvrange = BitsDotGetVc1VLC(3, VC1_VLC_LEAF_ZERO);
Header->mvrange = VC1_VLC_RESULT(3, Header->mvrange);
}
if (EntryPointHeader->extended_dmv == 0x01) // 9.1.1.27
{
Header->dmvrange = BitsDotGetVc1VLC(3, VC1_VLC_LEAF_ZERO);
Header->dmvrange = VC1_VLC_RESULT(3, Header->dmvrange);
}
// B fields do not have intensity compensation values - 9.1.1.46
MvModeBits = (Header->ptype == VC1_PICTURE_CODING_TYPE_P) ? 4 : 3;
for (Header->mvmode = 0; Header->mvmode < MvModeBits; Header->mvmode++) // 9.1.1.46
if (Bits.Get(1) == 0x01)
break;
if (Header->ptype == VC1_PICTURE_CODING_TYPE_P)
{
Header->mvmode = (Header->pquant > 12) ? MvModeLowRate[Header->mvmode] : MvModeHighRate[Header->mvmode];
if (Header->mvmode == VC1_MV_MODE_INTENSITY_COMP)
{
unsigned int LumaScale;
unsigned int LumaShift;
for (Header->mvmode2 = 0; Header->mvmode2 < 3; Header->mvmode2++) // 9.1.1.47
if (Bits.Get(1) == 0x01)
break;
Header->mvmode2 = (Header->pquant > 12) ? MvMode2LowRate[Header->mvmode2] : MvMode2HighRate[Header->mvmode2];
if (Bits.Get(1) == 0x01) // 9.1.1.48
Header->intensity_comp_field = VC1_INTENSITY_COMP_BOTH;
else if (Bits.Get(1) == 0x01)
Header->intensity_comp_field = VC1_INTENSITY_COMP_BOTTOM;
else
Header->intensity_comp_field = VC1_INTENSITY_COMP_TOP;
LumaScale = Bits.Get(6); // 9.1.1.49
LumaShift = Bits.Get(6); // 9.1.1.50
if (Header->intensity_comp_field == VC1_INTENSITY_COMP_BOTTOM)
Header->intensity_comp_bottom = (LumaScale << VC1_LUMASCALE_SHIFT) | (LumaShift << VC1_LUMASHIFT_SHIFT);
else
Header->intensity_comp_top = (LumaScale << VC1_LUMASCALE_SHIFT) | (LumaShift << VC1_LUMASHIFT_SHIFT);
if (Header->intensity_comp_field == VC1_INTENSITY_COMP_BOTH)
{
LumaScale = Bits.Get(6); // 9.1.1.51
LumaShift = Bits.Get(6); // 9.1.1.52
Header->intensity_comp_bottom = (LumaScale << VC1_LUMASCALE_SHIFT) | (LumaShift << VC1_LUMASHIFT_SHIFT);
}
}
}
else
Header->mvmode = (Header->pquant > 12) ? MvMode2LowRate[Header->mvmode] : MvMode2HighRate[Header->mvmode];
}
//}}}
//{{{ CommitFrameForDecode
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Send frame for decode
/// On a first slice code, we should have garnered all the data
/// we require we for a frame decode, this function records that fact.
///
/// /////////////////////////////////////////////////////////////////////////
FrameParserStatus_t FrameParser_VideoVc1_c::CommitFrameForDecode (void)
{
unsigned int i;
bool ProgressiveSequence;
bool FieldSequenceError;
PictureStructure_t PictureStructure;
bool Frame;
bool RepeatFirstField;
bool TopFieldFirst;
unsigned int PanAndScanCount;
Vc1VideoPicture_t *PictureHeader;
Vc1VideoSequence_t *SequenceHeader;
Vc1VideoEntryPoint_t *EntryPointHeader;
SliceType_t SliceType;
MatrixCoefficientsType_t MatrixCoefficients;
//
// Check we have the headers we need
//
if ((StreamParameters == NULL) || !StreamParameters->SequenceHeaderPresent)
{
report (severity_error, "FrameParser_VideoVc1_c::CommitFrameForDecode - Stream parameters unavailable for decode.\n");
return FrameParserNoStreamParameters;
}
if ((FrameParameters == NULL) || !FrameParameters->PictureHeaderPresent)
{
report (severity_error, "FrameParser_VideoVc1_c::CommitFrameForDecode - Frame parameters unavailable for decode (%p).\n", FrameParameters);
return FrameParserPartialFrameParameters;
}
SequenceHeader = &StreamParameters->SequenceHeader;
EntryPointHeader = &StreamParameters->EntryPointHeader;
PictureHeader = &FrameParameters->PictureHeader;
//
// Obtain and check the progressive etc values.
//
SliceType = SliceTypeTranslation[PictureHeader->ptype];
ProgressiveSequence = SequenceHeader->interlace == 0 ? true : false;
if (PictureHeader->fcm == VC1_FCM_FIELD_INTERLACED)
PictureStructure = PictureStructures[(PictureHeader->tff << 1) | PictureHeader->first_field];
else
PictureStructure = StructureFrame;
Frame = PictureStructure == StructureFrame;
RepeatFirstField = PictureHeader->rff;
TopFieldFirst = PictureHeader->tff;
PanAndScanCount = PictureHeader->ps_window_count;
if (!Legal(ProgressiveSequence, Frame, TopFieldFirst, RepeatFirstField))
{
report (severity_error, "FrameParser_VideoVc1_c::CommitFrameForDecode - Illegal combination (%c %c %c %c).\n",
(ProgressiveSequence ? 'T' : 'F'),
(Frame ? 'T' : 'F'),
(RepeatFirstField ? 'T' : 'F'),
(TopFieldFirst ? 'T' : 'F'));
//return FrameParserHeaderSyntaxError;
}
//
// If we are doing field decode check for sequence error, and set appropriate flags
//
FieldSequenceError = (AccumulatedPictureStructure == PictureStructure);
FirstDecodeOfFrame = FieldSequenceError || (AccumulatedPictureStructure == StructureEmpty);
AccumulatedPictureStructure = (FirstDecodeOfFrame && !Frame) ? PictureStructure : StructureEmpty;
if (FieldSequenceError)
{
report (severity_error, "FrameParser_VideoVc1_c::CommitFrameForDecode - Field sequence error detected.\n");
Player->CallInSequence (Stream, SequenceTypeImmediate, TIME_NOT_APPLICABLE, CodecFnOutputPartialDecodeBuffers);
}
//
// Deduce the matrix coefficients for colour conversions.
//
if( SequenceHeader->display_ext && SequenceHeader->color_format_flag )
{
switch( SequenceHeader->matrix_coef )
{
case VC1_MATRIX_COEFFICIENTS_BT709: MatrixCoefficients = MatrixCoefficients_ITU_R_BT709; break;
case VC1_MATRIX_COEFFICIENTS_FCC: MatrixCoefficients = MatrixCoefficients_FCC; break;
case VC1_MATRIX_COEFFICIENTS_BT470_BGI: MatrixCoefficients = MatrixCoefficients_ITU_R_BT470_2_BG; break;
case VC1_MATRIX_COEFFICIENTS_SMPTE_170M: MatrixCoefficients = MatrixCoefficients_SMPTE_170M; break;
case VC1_MATRIX_COEFFICIENTS_SMPTE_240M: MatrixCoefficients = MatrixCoefficients_SMPTE_240M; break;
default:
case VC1_MATRIX_COEFFICIENTS_FORBIDDEN:
case VC1_MATRIX_COEFFICIENTS_RESERVED:
report( severity_error, "FrameParser_VideoVC1_c::CommitFrameForDecode - Forbidden or reserved matrix coefficient code specified (%02x)\n", SequenceHeader->matrix_coef );
// fall through
case VC1_MATRIX_COEFFICIENTS_UNSPECIFIED: MatrixCoefficients = MatrixCoefficients_ITU_R_BT601; break;
}
}
else
{
MatrixCoefficients = MatrixCoefficients_ITU_R_BT601;
}
//
// Nick added this to make vc1 struggle through
//
ParsedFrameParameters->FirstParsedParametersForOutputFrame = FirstDecodeOfFrame;
ParsedFrameParameters->FirstParsedParametersAfterInputJump = FirstDecodeAfterInputJump;
ParsedFrameParameters->SurplusDataInjected = SurplusDataInjected;
ParsedFrameParameters->ContinuousReverseJump = ContinuousReverseJump;
//
// Record the stream and frame parameters into the appropriate structure
//
ParsedFrameParameters->KeyFrame = SliceType == SliceTypeI;
// if (SliceType != SliceTypeI)
// CodedFramePlaybackTimeValid = false;
//report (severity_error, "Slite type %d.\n", PictureHeader->ptype);
if (PictureHeader->ptype != 1) { //SliceType == SliceTypeB || PictureHeader->ptype == VC1_PICTURE_CODING_TYPE_BI) {
// ParsedFrameParameters->NormalizedPlaybackTime = INVALID_TIME;
// CodedFramePlaybackTimeValid = false;
//report (severity_error, "FrameParser_VideoVc1_c::CommitFrameForDecode - B or BI frame, ignoring PTS.\n");
}
ParsedFrameParameters->ReferenceFrame = (SliceType != SliceTypeB) && (PictureHeader->ptype != VC1_PICTURE_CODING_TYPE_BI);
ParsedFrameParameters->IndependentFrame = ParsedFrameParameters->KeyFrame;
ParsedFrameParameters->NewStreamParameters = NewStreamParametersCheck();
ParsedFrameParameters->SizeofStreamParameterStructure = sizeof(Vc1StreamParameters_t);
ParsedFrameParameters->StreamParameterStructure = StreamParameters;
ParsedFrameParameters->NewFrameParameters = true;
ParsedFrameParameters->SizeofFrameParameterStructure = sizeof(Vc1FrameParameters_t);
ParsedFrameParameters->FrameParameterStructure = FrameParameters;
//
if (EntryPointHeader->coded_size_flag == 1)
{
ParsedVideoParameters->Content.Width = EntryPointHeader->coded_width;
ParsedVideoParameters->Content.Height = EntryPointHeader->coded_height;
}
else
{
ParsedVideoParameters->Content.Width = SequenceHeader->max_coded_width;
ParsedVideoParameters->Content.Height = SequenceHeader->max_coded_height;
}
if (SequenceHeader->display_ext == 1)
{
ParsedVideoParameters->Content.DisplayWidth = SequenceHeader->disp_horiz_size;
ParsedVideoParameters->Content.DisplayHeight = SequenceHeader->disp_vert_size;
}
#if 0
else
{
ParsedVideoParameters->Content.DisplayWidth = ParsedVideoParameters->Content.Width;
ParsedVideoParameters->Content.DisplayHeight = ParsedVideoParameters->Content.Height;
}
#endif
if (SequenceHeader->frame_rate_flag == 1)
{
if (SequenceHeader->frame_rate_ind == 0) // (0 - 7) + (1 (1000), or 2 (1001)) = (0 - 15)
ParsedVideoParameters->Content.FrameRate = FrameRates(SequenceHeader->frameratenr + ((SequenceHeader->frameratedr-1) << 3));
else
ParsedVideoParameters->Content.FrameRate = Rational_t((SequenceHeader->framerateexp+1), 32);
}
//else if (SequenceHeader->frame_rate_ind == 1) // this is a special case used by WMV
// ParsedVideoParameters->Content.FrameRate = Rational_t(SequenceHeader->frameratenr, SequenceHeader->frameratedr);
else if (FrameRateValid)
{
ParsedVideoParameters->Content.FrameRate = this->FrameRate;
}
else
{
#warning "Need to calculate frame rates from PTS values"
#if 0
if (PtsPresent)
{
unsigned int PtsDifference = (unsigned int)(Pts - LastPts);
FrameRate = Rational_t (90000, Pts - LastPts);
report (severity_info, "FrameParser_VideoVc1_c::CommitFrameForDecode - No framerate, use PTS (Not Implemented).\n");
FrameRate.IntegerPart(), FrameRate.RemainderDecimal());
}
#endif
//report (severity_error, "FrameParser_VideoVc1_c::CommitFrameForDecode - No framerate in ES.\n");
//ParsedVideoParameters->Content.FrameRate = Rational_t (24000, 1001);
ParsedVideoParameters->Content.FrameRate = Rational_t (FrameRateDefaultNum, FrameRateDefaultDen);
}
ParsedVideoParameters->Content.Progressive = ProgressiveSequence;
ParsedVideoParameters->Content.OverscanAppropriate = false;
if (SequenceHeader->aspect_ratio_flag == 1)
{
if (SequenceHeader->aspect_ratio == 15)
ParsedVideoParameters->Content.PixelAspectRatio = Rational_t (SequenceHeader->aspect_horiz_size, SequenceHeader->aspect_vert_size);
else
ParsedVideoParameters->Content.PixelAspectRatio = AspectRatios(SequenceHeader->aspect_ratio);
}
else if (SequenceHeader->display_ext == 1)
{
// This calculation assumes that the display aspect ratio is 1:1. Therefore to convert to the pixel aspect ratio we
// must multiply by the horizontal pixel count and divide by the vertical pixel count
ParsedVideoParameters->Content.PixelAspectRatio = Rational_t ((ParsedVideoParameters->Content.DisplayHeight * ParsedVideoParameters->Content.Width),
(ParsedVideoParameters->Content.DisplayWidth * ParsedVideoParameters->Content.Height));
}
else
ParsedVideoParameters->Content.PixelAspectRatio = 1;
ParsedVideoParameters->SliceType = SliceType;
ParsedVideoParameters->PictureStructure = PictureStructure;
ParsedVideoParameters->InterlacedFrame = PictureHeader->fcm == VC1_FCM_PROGRESSIVE ? false : true;
ParsedVideoParameters->TopFieldFirst = TopFieldFirst;
ParsedVideoParameters->DisplayCount[0] = DisplayCount0(ProgressiveSequence, Frame, TopFieldFirst, RepeatFirstField);
ParsedVideoParameters->DisplayCount[1] = DisplayCount1(ProgressiveSequence, Frame, TopFieldFirst, RepeatFirstField);
#if 0
static unsigned int FrameNo = 0;
report (severity_info, "%s: (%d, %d, %d, %d) - CountsIndex %d Legal %d PanScanCount %d \n", __FUNCTION__,
ProgressiveSequence, Frame, TopFieldFirst, RepeatFirstField,
CountsIndex(ProgressiveSequence, Frame, TopFieldFirst, RepeatFirstField),
Legal(ProgressiveSequence, Frame, TopFieldFirst, RepeatFirstField),
PanScanCount(ProgressiveSequence, Frame, TopFieldFirst, RepeatFirstField));
report (severity_info, "%s: - DisplayCount0 %d DisplayCount1 %d, FrameNo %d\n", __FUNCTION__,
ParsedVideoParameters->DisplayCount[0], ParsedVideoParameters->DisplayCount[1], FrameNo++);
#endif
ParsedVideoParameters->PanScan.Count = PanAndScanCount;
for (i=0; i<PanAndScanCount; i++)
{
ParsedVideoParameters->PanScan.DisplayCount[i] = 1;
ParsedVideoParameters->PanScan.HorizontalOffset[i] = PictureHeader->ps_hoffset[i];
ParsedVideoParameters->PanScan.VerticalOffset[i] = PictureHeader->ps_voffset[i];
}
//
// Record our claim on both the frame and stream parameters
//
Buffer->AttachBuffer (StreamParametersBuffer);
Buffer->AttachBuffer (FrameParametersBuffer);
//
// We clear the FrameParameters pointer, a new one will be obtained
// before/if we read in headers pertaining to the next frame. This
// will generate an error should I accidentally write code that
// accesses this data when it should not.
//
FrameParameters = NULL;
//
// Finally set the appropriate flag and return
//
FrameToDecode = true;
return FrameParserNoError;
}
//}}}
//{{{ NewStreamParametersCheck
/// /////////////////////////////////////////////////////////////////////////
///
/// \brief Boolean function to evaluate whether or not the stream
/// parameters are new.
///
/// /////////////////////////////////////////////////////////////////////////
bool FrameParser_VideoVc1_c::NewStreamParametersCheck (void)
{
bool Different;
//
// The parameters cannot be new if they have been used before.
//
if (!StreamParameters->UpdatedSinceLastFrame)
return false;
StreamParameters->UpdatedSinceLastFrame = false;
//
// Check for difference using a straightforward comparison to see if the
// stream parameters have changed. (since we zero on allocation simple
// memcmp should be sufficient).
//
Different = memcmp (&CopyOfStreamParameters, StreamParameters, sizeof(Vc1StreamParameters_t)) != 0;
if (Different)
{
memcpy (&CopyOfStreamParameters, StreamParameters, sizeof(Vc1StreamParameters_t));
return true;
}
//
return false;
}
//}}}
//{{{ BitsDotGetVc1VLC
unsigned long FrameParser_VideoVc1_c::BitsDotGetVc1VLC (unsigned long MaxBits, unsigned long LeafNode)
{
unsigned long BitsRead=0;
unsigned long NextBit=0;
unsigned long Result=0;
while (BitsRead < MaxBits)
{
NextBit = Bits.Get(1);
Result = (Result << 1) | NextBit;
BitsRead++;
if (NextBit == LeafNode)
break;
}
Result |= (BitsRead << MaxBits);
//report (severity_info, "%s: Result = %x, BitsRead %d\n", __FUNCTION__, Result, BitsRead);
return (Result);
}
//}}}
| [
"Schischu@u10.4x64"
] | Schischu@u10.4x64 |
4ea52f5c413ebc9a09bc7096ce4532867720a3b2 | 4e48c826ff9d8583e3edd13794cd521c995a8230 | /Patterns/pattern9.cpp | be7d264a3d25b2e0aff028dc61ce5b8779897a6e | [] | no_license | s-h-u-b-h/Placement-Questions | 29918b218d76f5510740c8649f0f857f3a76f090 | 508c789b5c5ce5c3cf497f81e577f9f4dda43fca | refs/heads/master | 2023-03-10T10:49:12.197777 | 2021-02-25T01:36:43 | 2021-02-25T01:36:43 | 342,083,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | cpp | #include<iostream>
using namespace std;
int main()
{
int n;
int i,j,k;
cin>>n;
for(i=0;i<n;i++)
{
for(k= i;k<n;k++)
cout << " ";
for(j=0;j<=i;j++)
cout << "* ";
cout << "\n";
}
return 0;
}
| [
"you@example.com"
] | you@example.com |
1723e4d75121030bfac0a0c74c5decf6a58b249c | 4bab98acf65c4625a8b3c757327a8a386f90dd32 | /ros2-windows/include/example_interfaces/srv/detail/trigger__rosidl_typesupport_fastrtps_cpp.hpp | 1962339f5b3bfdf6484f0af67f723eddafd86e95 | [] | no_license | maojoejoe/Peach-Thinning-GTRI-Agricultural-Robotics-VIP | e2afb08b8d7b3ac075e071e063229f76b25f883a | 8ed707edb72692698f270317113eb215b57ae9f9 | refs/heads/master | 2023-01-15T06:00:22.844468 | 2020-11-25T04:16:15 | 2020-11-25T04:16:15 | 289,108,482 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,691 | hpp | // generated from rosidl_typesupport_fastrtps_cpp/resource/idl__rosidl_typesupport_fastrtps_cpp.hpp.em
// with input from example_interfaces:srv\Trigger.idl
// generated code does not contain a copyright notice
#ifndef EXAMPLE_INTERFACES__SRV__DETAIL__TRIGGER__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_
#define EXAMPLE_INTERFACES__SRV__DETAIL__TRIGGER__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_
#include "rosidl_runtime_c/message_type_support_struct.h"
#include "rosidl_typesupport_interface/macros.h"
#include "example_interfaces/msg/rosidl_typesupport_fastrtps_cpp__visibility_control.h"
#include "example_interfaces/srv/detail/trigger__struct.hpp"
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
# ifdef __clang__
# pragma clang diagnostic ignored "-Wdeprecated-register"
# pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
# endif
#endif
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
#include "fastcdr/Cdr.h"
namespace example_interfaces
{
namespace srv
{
namespace typesupport_fastrtps_cpp
{
bool
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
cdr_serialize(
const example_interfaces::srv::Trigger_Request & ros_message,
eprosima::fastcdr::Cdr & cdr);
bool
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
cdr_deserialize(
eprosima::fastcdr::Cdr & cdr,
example_interfaces::srv::Trigger_Request & ros_message);
size_t
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
get_serialized_size(
const example_interfaces::srv::Trigger_Request & ros_message,
size_t current_alignment);
size_t
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
max_serialized_size_Trigger_Request(
bool & full_bounded,
size_t current_alignment);
} // namespace typesupport_fastrtps_cpp
} // namespace srv
} // namespace example_interfaces
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_cpp, example_interfaces, srv, Trigger_Request)();
#ifdef __cplusplus
}
#endif
// already included above
// #include "rosidl_runtime_c/message_type_support_struct.h"
// already included above
// #include "rosidl_typesupport_interface/macros.h"
// already included above
// #include "example_interfaces/msg/rosidl_typesupport_fastrtps_cpp__visibility_control.h"
// already included above
// #include "example_interfaces/srv/detail/trigger__struct.hpp"
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
# ifdef __clang__
# pragma clang diagnostic ignored "-Wdeprecated-register"
# pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
# endif
#endif
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
// already included above
// #include "fastcdr/Cdr.h"
namespace example_interfaces
{
namespace srv
{
namespace typesupport_fastrtps_cpp
{
bool
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
cdr_serialize(
const example_interfaces::srv::Trigger_Response & ros_message,
eprosima::fastcdr::Cdr & cdr);
bool
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
cdr_deserialize(
eprosima::fastcdr::Cdr & cdr,
example_interfaces::srv::Trigger_Response & ros_message);
size_t
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
get_serialized_size(
const example_interfaces::srv::Trigger_Response & ros_message,
size_t current_alignment);
size_t
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
max_serialized_size_Trigger_Response(
bool & full_bounded,
size_t current_alignment);
} // namespace typesupport_fastrtps_cpp
} // namespace srv
} // namespace example_interfaces
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_cpp, example_interfaces, srv, Trigger_Response)();
#ifdef __cplusplus
}
#endif
#include "rmw/types.h"
#include "rosidl_typesupport_cpp/service_type_support.hpp"
// already included above
// #include "rosidl_typesupport_interface/macros.h"
// already included above
// #include "example_interfaces/msg/rosidl_typesupport_fastrtps_cpp__visibility_control.h"
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_example_interfaces
const rosidl_service_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_fastrtps_cpp, example_interfaces, srv, Trigger)();
#ifdef __cplusplus
}
#endif
#endif // EXAMPLE_INTERFACES__SRV__DETAIL__TRIGGER__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_
| [
"aidencfarrar@gmail.com"
] | aidencfarrar@gmail.com |
52f95c0a45172d26106122b061ac9a5880dbbc9d | be10e9e15feb856b7e554a79efdd68e365ce0177 | /src/cursor.cpp | ec374b7dd2ef43feeea309db863d69a7509f9be6 | [
"MIT"
] | permissive | jasonzhouu/nvui | 469455b0bc14e5cdd5f829963b6d6b7e0a439c16 | a5b2b51c0ae9feb5782153260c62124d6f818e3a | refs/heads/main | 2023-07-18T04:30:36.862120 | 2021-08-30T22:18:23 | 2021-08-30T22:18:23 | 401,692,020 | 1 | 0 | MIT | 2021-08-31T12:18:39 | 2021-08-31T12:18:38 | null | UTF-8 | C++ | false | false | 9,058 | cpp | #include "cursor.hpp"
#include "editor.hpp"
#include "grid.hpp"
#include <fmt/core.h>
#include <fmt/format.h>
#include <QElapsedTimer>
using scalers::time_scaler;
time_scaler Cursor::animation_scaler = scalers::oneminusexpo2negative10;
Cursor::Cursor()
: blinkwait_timer(nullptr),
blinkon_timer(nullptr),
blinkoff_timer(nullptr),
mode_info(10)
{
blinkwait_timer.setSingleShot(true);
blinkon_timer.setSingleShot(true);
blinkoff_timer.setSingleShot(true);
QObject::connect(&blinkwait_timer, &QTimer::timeout, [this]() {
hide();
set_blinkoff_timer(cur_mode.blinkwait);
});
QObject::connect(&blinkon_timer, &QTimer::timeout, [this]() {
hide();
set_blinkoff_timer(cur_mode.blinkoff);
});
QObject::connect(&blinkoff_timer, &QTimer::timeout, [this]() {
show();
set_blinkon_timer(cur_mode.blinkon);
});
}
Cursor::Cursor(EditorArea* ea)
: Cursor()
{
assert(ea);
editor_area = ea;
cursor_animation_timer.callOnTimeout([this] {
auto elapsed_ms = elapsed_timer.elapsed();
cursor_animation_time -= static_cast<float>(elapsed_ms) / 1000.f;
if (cursor_animation_time <= 0.f)
{
cursor_animation_timer.stop();
cur_x = destination_x;
cur_y = destination_y;
}
else
{
auto x_diff = destination_x - old_x;
auto y_diff = destination_y - old_y;
auto duration = editor_area->cursor_animation_duration();
auto animation_left = cursor_animation_time / duration;
float animation_finished = 1.0f - animation_left;
float scaled = animation_scaler(animation_finished);
cur_x = old_x + (x_diff * scaled);
cur_y = old_y + (y_diff * scaled);
}
editor_area->update();
elapsed_timer.start();
});
}
void Cursor::mode_change(const msgpack::object* obj, std::uint32_t size)
{
assert(obj->type == msgpack::type::ARRAY);
const auto& arr = obj->via.array;
assert(arr.size == 2);
const std::string mode_name = arr.ptr[0].as<std::string>();
// Save the old position
if (cur_pos.has_value()) old_mode_idx = cur_mode_idx;
cur_mode_idx = arr.ptr[1].as<std::size_t>();
if (cur_mode_idx >= mode_info.size())
{
return;
}
cur_mode = mode_info.at(cur_mode_idx);
reset_timers();
}
void Cursor::mode_info_set(const msgpack::object* obj, std::uint32_t size)
{
mode_info.clear();
for(std::uint32_t i = 0; i < size; ++i)
{
const msgpack::object& o = obj[i];
assert(o.type == msgpack::type::ARRAY);
const auto& arr = o.via.array;
assert(arr.size == 2);
const bool cursor_style_enabled = arr.ptr[0].as<bool>();
const auto& modes_arr = arr.ptr[1].via.array;
for(std::uint32_t j = 0; j < modes_arr.size; ++j)
{
const msgpack::object_map& map = modes_arr.ptr[j].via.map;
ModeInfo mode {};
for(std::uint32_t k = 0; k < map.size; ++k)
{
const msgpack::object_kv kv = map.ptr[k];
const std::string key = kv.key.as<std::string>();
if (key == "cursor_shape")
{
const std::string shape = kv.val.as<std::string>();
if (shape == "horizontal")
{
mode.cursor_shape = CursorShape::Horizontal;
}
else if (shape == "vertical")
{
mode.cursor_shape = CursorShape::Vertical;
}
else
{
mode.cursor_shape = CursorShape::Block;
}
}
else if (key == "cell_percentage")
{
mode.cell_percentage = kv.val.as<int>();
}
else if (key == "attr_id")
{
mode.attr_id = kv.val.as<int>();
}
else if (key == "attr_id_lm")
{
mode.attr_id_lm = kv.val.as<int>();
}
else if (key == "short_name")
{
mode.short_name = kv.val.as<std::string>();
}
else if (key == "name")
{
mode.name = kv.val.as<std::string>();
}
else if (key == "blinkwait")
{
mode.blinkwait = kv.val.as<int>();
}
else if (key == "blinkon")
{
mode.blinkon = kv.val.as<int>();
}
else if (key == "blinkoff")
{
mode.blinkoff = kv.val.as<int>();
}
}
mode_info.push_back(std::move(mode));
}
}
}
void Cursor::reset_timers() noexcept
{
if (busy()) return;
show();
blinkwait_timer.stop();
blinkoff_timer.stop();
blinkon_timer.stop();
// Blinking works like this:
// First of all, if any of the numbers are 0, then there is no blinking.
if (cur_mode.blinkwait == 0 || cur_mode.blinkoff == 0 || cur_mode.blinkon == 0) return;
// 1. Cursor starts in a solid (visible) state.
// 2. Cursor stays that way for 'blinkon' ms.
// 3. After 'blinkon' ms, the cursor becomes hidden
// 4. Cursor stays that way for 'blinkoff' ms.
// 5. After 'blinkoff' ms, the cursor becomes visible.
// 6. Repeat
// On cursor move,
// 1. The cursor immediately becomes visible.
// 2. The cursor stays that way for 'blinkwait' ms.
// 3. After 'blinkwait' ms, the cursor becomes hidden.
// 4. Repeat the above blinking steps, but starting from step 4.
blinkwait_timer.start(cur_mode.blinkwait);
}
void Cursor::set_blinkoff_timer(int ms) noexcept
{
blinkoff_timer.start(ms);
}
void Cursor::set_blinkon_timer(int ms) noexcept
{
blinkon_timer.start(ms);
}
void Cursor::hide() noexcept
{
if (status != CursorStatus::Hidden && !busy())
{
emit cursor_hidden();
status = CursorStatus::Hidden;
}
}
void Cursor::show() noexcept
{
if (status != CursorStatus::Visible && !busy())
{
emit cursor_visible();
status = CursorStatus::Visible;
}
}
void Cursor::go_to(CursorPos pos)
{
prev_pos = cur_pos;
if (!use_animated_position())
{
cursor_animation_timer.stop();
cur_pos = pos;
}
else
{
cur_pos = pos;
old_x = cur_x;
old_y = cur_y;
destination_x = cur_pos->grid_x + cur_pos->col;
destination_y = cur_pos->grid_y + cur_pos->row;
cursor_animation_time = editor_area->cursor_animation_duration();
auto interval = editor_area->cursor_animation_frametime();
elapsed_timer.start();
if (cursor_animation_timer.interval() != interval)
{
cursor_animation_timer.setInterval(interval);
}
if (!cursor_animation_timer.isActive()) cursor_animation_timer.start();
}
reset_timers();
}
/// Returns a CursorRect containing the cursor rectangle
/// in pixels, based on the row, column, font width, and font height.
static CursorRect get_rect(
const ModeInfo& mode,
float row,
float col,
float font_width,
float font_height,
float caret_extend_top,
float caret_extend_bottom,
float scale = 1.0f
)
{
// These do nothing for now
bool should_draw_text = mode.cursor_shape == CursorShape::Block;
/// Top left coordinates.
QPointF top_left = {col * font_width, row * font_height};
QRectF rect;
/// Depending on the cursor shape, the rectangle it occupies will be different
/// Block and Underline shapes' width will change depending on the scale factor,
/// but not the vertical shape.
switch(mode.cursor_shape)
{
case CursorShape::Block:
{
rect = {top_left.x(), top_left.y(), font_width * scale, font_height};
break;
}
case CursorShape::Vertical:
{
// Rectangle starts at top_left, with a lower width.
float width = (font_width * mode.cell_percentage) / 100.f;
rect = {top_left.x(), top_left.y() - caret_extend_top, width, font_height + caret_extend_top+ caret_extend_bottom};
break;
}
case CursorShape::Horizontal:
{
float height = (font_height * mode.cell_percentage) / 100.f;
float start_y = top_left.y() + font_height - height;
rect = {top_left.x(), start_y, font_width * scale, height};
break;
}
}
return {rect, mode.attr_id, should_draw_text};
}
std::optional<CursorRect> Cursor::rect(float font_width, float font_height, float scale) const noexcept
{
if (!cur_pos.has_value()) return std::nullopt;
float x = cur_pos->grid_x + cur_pos->col;
float y = cur_pos->grid_y + cur_pos->row;
if (use_animated_position())
{
x = cur_x;
y = cur_y;
}
return get_rect(
cur_mode,
y,
x,
font_width, font_height,
caret_extend_top,
caret_extend_bottom,
scale
);
}
std::optional<CursorRect> Cursor::old_rect(float font_width, float font_height) const noexcept
{
if (!prev_pos.has_value()) return std::nullopt;
const auto& old_mode = mode_info.at(old_mode_idx);
return get_rect(
old_mode,
prev_pos->grid_y + prev_pos->row,
prev_pos->grid_x + prev_pos->col,
font_width,
font_height,
caret_extend_top,
caret_extend_bottom,
old_mode_scale
);
}
void Cursor::busy_start()
{
hide();
status = CursorStatus::Busy;
}
void Cursor::busy_stop()
{
status = CursorStatus::Visible;
reset_timers();
}
bool Cursor::use_animated_position() const
{
return editor_area
&& editor_area->animations_enabled()
&& editor_area->cursor_animation_frametime() > 0;
}
| [
"rohit.px02@gmail.com"
] | rohit.px02@gmail.com |
5a59c4779c5730216ce64d7ee95f9b43d6c92f36 | b52e09b14f1b85af7f32e51849288a2d972ccf37 | /CocosWidget/ExpandableListView.h | fed8a4ff3a642d563610a64dd1b46f7a925820d7 | [
"MIT"
] | permissive | LingJiJian/Tui-x | 9bd80b801d9eba7b67223b16f1bad6ecebd20690 | e00e79109db466143ed2b399a8991be4e5fea28f | refs/heads/master | 2016-09-05T14:07:49.984373 | 2016-01-25T10:01:37 | 2016-01-25T10:01:37 | 19,667,247 | 68 | 36 | null | null | null | null | UTF-8 | C++ | false | false | 3,887 | h | /****************************************************************************
Copyright (c) 2014 Lijunlin - Jason lee
Created by Lijunlin - Jason lee on 2014
jason.lee.c@foxmail.com
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCWIDGET_EXPANDABLELISTVIEW_H__
#define __CCWIDGET_EXPANDABLELISTVIEW_H__
#include "cocos2d.h"
#include "WidgetMacros.h"
#include "Widget.h"
#include "ScrollView.h"
#include "WidgetProtocol.h"
#include <vector>
NS_CC_WIDGET_BEGIN
class CExpandableNode;
class CExpandableListView;
/**
* class : CExpandableNode
* author : Jason lee
* email : jason.lee.c@foxmail.com
* descpt : expandable node define
*/
class CExpandableNode: public CLayout
{
public:
CExpandableNode();
virtual ~CExpandableNode();
static CExpandableNode* create();
void insertItemNodeAtLast(Node* pNode);
void insertItemNodeAtFront(Node* pNode);
void removeItemNode(Node* pNode);
void removeItemNodeAtIndex(unsigned int idx);
void removeAllItemNodes();
Node* getItemNodeAtIndex(unsigned int idx);
public:
virtual CWidgetTouchModel onTouchBegan(Touch* pTouch);
virtual void onTouchMoved(Touch* pTouch, float fDuration);
virtual void onTouchEnded(Touch* pTouch, float fDuration);
virtual void onTouchCancelled(Touch* pTouch, float fDuration);
protected:
friend class CExpandableListView;
void setExpanded(bool bExpanded);
bool isExpanded() const;
std::vector<Node*>& getExpandableNodeItemList();
void setExpandableListViewParent(CExpandableListView* pListView);
protected:
bool m_bExpanded;
unsigned int m_nIdx;
std::vector<Node*> m_vExpandableNodeItemList;
CExpandableListView* m_pExpandableListViewParent;
};
/**
* class : CExpandableListView
* author : Jason lee
* email : jason.lee.c@foxmail.com
* descpt : expandable list view define
*/
class CExpandableListView : public CScrollView
{
public:
CExpandableListView();
virtual ~CExpandableListView();
static CExpandableListView* create(const Size& contentSize);
// expand a expandable node by idx
void expand(unsigned int idx);
// collapse a expandable node by idx
void collapse(unsigned int idx);
void insertExpandableNodeAtLast(CExpandableNode* pNode);
void insertExpandableNodeAtFront(CExpandableNode* pNode);
void removeExpandableNode(CExpandableNode* pNode);
void removeExpandableNodeAtIndex(unsigned int idx);
void removeLastExpandableNode();
void removeFrontExpandableNode();
void removeAllExpandableNodes();
Vector<CExpandableNode*> getExpandableNodes();
unsigned int getExpandableNodeCount();
CExpandableNode* getExpandableNodeAtIndex(unsigned int idx);
void reloadData();
protected:
friend class CExpandableNode;
void updateNodesPosition();
protected:
Vector<CExpandableNode*> m_vExpandableNodeList;
};
NS_CC_WIDGET_END
#endif //__CCWIDGET_EXPANDABLELISTVIEW_H__ | [
"342854406@qq.com"
] | 342854406@qq.com |
e0c46dbcdc5b1024129c4875053af7a9ef86311a | 1ec8fb145d9e0f228740ac78a3acd277ee2e0d2e | /newyork.cpp | df281b36bb4bfe4063d5360cb46a9b542cb15409 | [] | no_license | Sadik1603075/code_forces | 853aa8f827c3137c76fd4f43bba03b80544ba88f | a27e809eca383f702c48e29d9795d06d35e9b41b | refs/heads/master | 2022-11-29T05:47:03.885339 | 2020-08-09T06:47:26 | 2020-08-09T06:47:26 | 286,182,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 494 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int i,j,k,l=0,n;
int arr[11];
int sum = 0;
for(i=1;i<11;i++)
{
sum +=5*i;
arr[i] =sum;
//cout<<arr[i]<<" ";
}
scanf("%d%d",&n,&k);
sum = 240 - k;
for(i=1;i<11;i++)
{
if(sum>=arr[i])
{
l++;
}
else
{
break;
}
}
if(l<n)
cout<<l<<endl;
else
cout<<n<<endl;
return 0;
}
| [
"bariksadik@gmail.com"
] | bariksadik@gmail.com |
8c6c5677770b92d8f4b4fa0dda6a998f23a5789a | 5601d1a6e2af8a959114b50c01955bac0f0744ec | /jsoncons/tests/src/converter_tests.cpp | 2e2873f8f31b6a329d69e4d6f652c04273cd88ae | [
"MIT",
"BSL-1.0"
] | permissive | sikkey/testjsoncon | 5140187a21bd6d2fd81319af8537385bc1341543 | 7c486e5d59023e6bafe001734c5f967a2c308cdc | refs/heads/master | 2022-11-12T10:36:32.853684 | 2020-06-28T09:32:53 | 2020-06-28T09:32:53 | 275,550,524 | 0 | 1 | BSL-1.0 | 2020-06-28T09:32:55 | 2020-06-28T09:24:34 | null | UTF-8 | C++ | false | false | 1,698 | cpp | // Copyright 2020 Daniel Parker
// Distributed under Boost license
#include <catch/catch.hpp>
#include <jsoncons/json.hpp>
#include <jsoncons/converter.hpp>
#include <vector>
using namespace jsoncons;
TEST_CASE("convert into list-like")
{
SECTION("from string")
{
converter<std::vector<uint8_t>> convert;
std::vector<uint8_t> expected = {'f','o','o','b','a','r'};
std::error_code ec;
std::vector<uint8_t> v = convert.from(jsoncons::string_view("Zm9vYmFy"), semantic_tag::base64url, ec);
REQUIRE(!ec);
CHECK(v == expected);
}
SECTION("from wstring")
{
converter<std::vector<uint8_t>> convert;
std::vector<uint8_t> expected = { 'f','o','o','b','a','r' };
std::error_code ec;
std::vector<uint8_t> v = convert.from(jsoncons::wstring_view(L"Zm9vYmFy"), semantic_tag::base64url, ec);
REQUIRE(!ec);
CHECK(v == expected);
}
}
TEST_CASE("convert into string")
{
std::vector<uint8_t> bytes = {'f','o','o','b','a','r'};
SECTION("from byte_string into string")
{
converter<std::string> convert;
std::string expected = "Zm9vYmFy";
std::error_code ec;
std::string s = convert.from(byte_string_view(bytes), semantic_tag::base64url, ec);
REQUIRE(!ec);
CHECK(s == expected);
}
SECTION("from byte string into wstring")
{
converter<std::wstring> convert;
std::wstring expected = L"Zm9vYmFy";
std::error_code ec;
std::wstring s = convert.from(byte_string_view(bytes), semantic_tag::base64url, ec);
REQUIRE(!ec);
CHECK(s == expected);
}
}
| [
"7Mersenne@gmail.com"
] | 7Mersenne@gmail.com |
82098ba4ae353ba766339d1b66864b9ab745df1a | 424c69ae80c1328f3882ef7ae012d9aef6817b19 | /PartialSource/QuestGiver.cpp | 72f02739288d70c5bbdafb18ccd8e5c390c431db | [] | no_license | guorenxu/SpiritHero | f722875382995295f42e9da468360fbbfbdd640d | 542682a2dfc94ea97bc666805b7dae3475fa6e84 | refs/heads/master | 2021-01-10T10:57:47.870132 | 2016-01-09T22:37:57 | 2016-01-09T22:37:57 | 49,344,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,434 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "IndieProject.h"
#include "QuestGiver.h"
#include "Alistair.h"
#include "StatusHUDTest.h"
AQuestGiver::AQuestGiver(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
HasGivenQuest = false;
QuestState = LOCKED;
NumQuestsNeeded = 0;
PrimaryActorTick.bCanEverTick = true;
GameName = "";
}
void AQuestGiver::Tick(float deltatime)
{
Super::Tick(deltatime);
for (TActorIterator<AAlistair> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
if (ActorItr->QuestsCompleted >= NumQuestsNeeded && QuestState == LOCKED)
{
QuestState = NOTTAKEN;
}
}
}
void AQuestGiver::GiveQuest(AAlistair* playercharacter, bool forcecomplete)
{
if (!HasGivenQuest)
{
if (!forcecomplete)
{
vector<FString> TextBlock;
FString OptionOne = "Yes, I'm ready for my adventure!";
FString OptionTwo = "No, I'm going to enjoy the view some more.";
if (QuestToGive.QuestID == 3)
{
OptionOne = "Yes, I'm ready for my adventure!";
OptionTwo = "No, I'm going to enjoy the view some more.";
TextBlock.push_back("A brand new day for a brand new adventure! According to this sign, the road leads to a");
TextBlock.push_back("small outpost ahead. Rumor has it though, that there is a dark evil spreading across the");
TextBlock.push_back("region. This is a perfect chance! I should go check the outpost out. Maybe the locals");
TextBlock.push_back("there need help from a brave adventurer like myself!");
}
else if (QuestToGive.QuestID == 2)
{
OptionOne = "Sure thing! I'll do anything for a shiny weapon!";
OptionTwo = "No, I'm not ready for it yet.";
TextBlock.push_back("Alistair: Hi! I'm Alistair!");
TextBlock.push_back("");
TextBlock.push_back("Gingerfoot: Waaah! I can't take it anymore! ");
TextBlock.push_back("");
TextBlock.push_back("Alistair: What's going on? Maybe I can help.");
TextBlock.push_back("");
TextBlock.push_back("Gingerfoot: You? Help? Hah! You don't even have a weapon! Who do you think you are?");
TextBlock.push_back("");
TextBlock.push_back("Alistair: ...");
TextBlock.push_back("");
TextBlock.push_back("Gingerfoot: Tell you what, if you help me water some of my royal plants, I'll give you a");
TextBlock.push_back("sword and shield and consider you for a more important task..");
}
else if (QuestToGive.QuestID == 1)
{
OptionOne = "Take the quest.";
OptionTwo = "I don't want to die yet!";
TextBlock.push_back("The adventurer's board is cluttered with notes indicating various tasks. Most of them have");
TextBlock.push_back("already been completed. One though, catches your eyes. It is a quest to to end the suffering");
TextBlock.push_back("of some of the sprites that have been infected with the evil spread across the land.");
TextBlock.push_back("According to note, anyone who is able to complete the quest will earn attention from the");
TextBlock.push_back("Sprite King himself.");
}
else if (QuestToGive.QuestID == 4)
{
OptionOne = "I'm ready to face the golem!";
OptionTwo = "I don't want to die this young.";
TextBlock.push_back("Alistair: Phew, that was some tiring training.");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: But I'm sure you've learned a lot. In fact, I believe that you are ready for your");
TextBlock.push_back("greatest challenge yet.");
TextBlock.push_back("");
TextBlock.push_back("Alistair: Whatever it is, I would definitely like to give it a try!");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: My scouts have recently discovered that the evil in our land is caused by the");
TextBlock.push_back("prescence of an evil ancient golem to the north. I would like you to destroy him.");
TextBlock.push_back("");
TextBlock.push_back("Alistair: Sounds like a challenge. Anything you want to tell me that can help me in the fight?");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: Be careful. He will be like no foe you've faced before. Use everything I have taught");
TextBlock.push_back("you and you should have a good chance against him.");
TextBlock.push_back("");
TextBlock.push_back("Alistair: Understood. Wish me luck!");
}
DialogueWindow* TheDialogue = new DialogueWindow();
TheDialogue->WindowName = QuestToGive.QuestName;
TheDialogue->BaseInit(playercharacter->PlayerHUD->XButtonTex, playercharacter->PlayerHUD, playercharacter);
TheDialogue->Init();
ImageWindowPart* newimagecomponent = new ImageWindowPart();
newimagecomponent->IsHoverable = true;
newimagecomponent->SizeToDraw = FVector(630.0f, 30.0f, 0.0f);
newimagecomponent->Location = FVector(10.0f, 430.0f, 0.0f);
newimagecomponent->TextureToDraw = playercharacter->PlayerHUD->QuestChoiceTex;
ImageWindowPart* newimagecomponenttwo = new ImageWindowPart();
newimagecomponenttwo->IsHoverable = true;
newimagecomponenttwo->SizeToDraw = FVector(630.0f, 30.0f, 0.0f);
newimagecomponenttwo->Location = FVector(10.0f, 470.0f, 0.0f);
newimagecomponenttwo->TextureToDraw = playercharacter->PlayerHUD->QuestChoiceTex;
TheDialogue->ImageComponents.push_back(newimagecomponent);
TheDialogue->ImageComponents.push_back(newimagecomponenttwo);
TextWindowPart* newtextcomponent = new TextWindowPart();
newtextcomponent->Location = FVector(45.0f, 435.0f, 0.0f);
newtextcomponent->TextColor = FLinearColor(1.0f, 1.0f, 1.0f);
newtextcomponent->TextContent = OptionOne;
newtextcomponent->Font = playercharacter->PlayerHUD->VerdanaFont;
TextWindowPart* newtextcomponenttwo = new TextWindowPart();
newtextcomponenttwo->Location = FVector(45.0f, 475.0f, 0.0f);
newtextcomponenttwo->TextColor = FLinearColor(1.0f, 1.0f, 1.0f);
newtextcomponenttwo->TextContent = OptionTwo;
newtextcomponenttwo->Font = playercharacter->PlayerHUD->VerdanaFont;
for (int i = 0; i < TextBlock.size(); i++)
{
TextWindowPart* newtext = new TextWindowPart();
newtext->Location = FVector(12.0f, i * 20.0f + 35.0f, 0.0f);
newtext->TextColor = FLinearColor(1.0f, 1.0f, 1.0f);
newtext->TextContent = TextBlock[i];
newtext->Font = playercharacter->PlayerHUD->VerdanaFont;
TheDialogue->TextComponents.push_back(newtext);
}
TheDialogue->TextComponents.push_back(newtextcomponent);
TheDialogue->TextComponents.push_back(newtextcomponenttwo);
TheDialogue->TheQuestGiver = this;
bool alreadyexists = false;
int existindex = 0;
for (int i = 0; i < playercharacter->PlayerHUD->WindowVector.size(); i++)
{
if (playercharacter->PlayerHUD->WindowVector[i]->WindowName == QuestToGive.QuestName)
{
alreadyexists = true;
existindex = i;
}
}
if (!alreadyexists)
{
playercharacter->PlayerHUD->WindowVector.push_back(TheDialogue);
PlaySoundAtLocation(playercharacter->PlayerHUD->QuestOpenSound, playercharacter->GetActorLocation());
}
else
{
playercharacter->PlayerHUD->WindowVector[existindex]->IsActive = true;
playercharacter->PlayerHUD->WindowVector[existindex]->ClosingAlpha = 1.0f;
playercharacter->PlayerHUD->WindowVector[existindex]->IsClosing = false;
}
}
else
{
for (int i = 0; i < playercharacter->QuestList.Num(); i++)
{
if (playercharacter->QuestList[i].QuestType == NOQUEST)
{
PlaySoundAtLocation(playercharacter->PlayerHUD->QuestCloseSound, playercharacter->GetActorLocation());
playercharacter->QuestList[i] = QuestToGive;
HasGivenQuest = true;
QuestState = INPROGRESS;
FString questtext = "You have taken the quest '" + QuestToGive.QuestName + "'!";
playercharacter->PlayerHUD->HUDAnnouncements.push_back(
new Announcement(questtext,
FLinearColor(1.0f, 1.0f, 0.4f),
playercharacter->PlayerHUD->DamageFont,
FVector(200.0f, 250.0f, 0.0f)));
break;
}
}
}
}
else
{
if (!forcecomplete)
{
vector<FString> TextBlock;
FString OptionOne = "Yes, I'm ready for my adventure!";
FString OptionTwo = "No, I'm going to enjoy the view some more.";
if (QuestToGive.QuestID == 0)
{
}
else if (QuestToGive.QuestID == 2)
{
OptionOne = "Take the reward. (Unlocks basic attacking)";
OptionTwo = "I'm not ready for the reward yet.";
TextBlock.push_back("Gingerfoot: You did it! Thank you for watering my precious plants!");
TextBlock.push_back("");
TextBlock.push_back("Alistair: That was... Actually much easier than I expected?");
TextBlock.push_back("");
TextBlock.push_back("Gingerfoot: I'm eternally grateful for what you've done! Do you have any idea how hard it is");
TextBlock.push_back("for us sprites to get our tiny arms around a watering can?!");
TextBlock.push_back("");
TextBlock.push_back("Alistair: I see I see.");
TextBlock.push_back("");
TextBlock.push_back("Gingerfoot: Anyhow, here's your sword and shield as promised. I think you should check out the");
TextBlock.push_back("adventurer's board. Maybe there's something on it for someone of your high caliber!");
TextBlock.push_back("");
TextBlock.push_back("Alistair: Will do!");
}
else if (QuestToGive.QuestID == 1)
{
OptionOne = "Take the king's training. (Unlocks skills)";
OptionTwo = "I'm not ready for the reward yet.";
TextBlock.push_back("Alistair: All done!");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: You there! Are you the brave adventurer who defeated the evil sprites lurking");
TextBlock.push_back("in our peaceful woods?");
TextBlock.push_back("");
TextBlock.push_back("Alistair: Yes, I certainly am!");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: I can't believe this day has finally come! Maybe you have a chance at freeing us");
TextBlock.push_back("all. But first, you deserve a reward for all your hard work.");
TextBlock.push_back("");
TextBlock.push_back("Alistair: Oh Great King, what do you have for the likes of me?");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: Personal combat lessons from only the best and greatest, me!");
TextBlock.push_back("");
TextBlock.push_back("Alistair: Wow! I can't wait!");
}
else if (QuestToGive.QuestID == 4)
{
OptionOne = "Thanks for playing! (Restart the game)";
OptionTwo = "I want to stay a while longer...";
TextBlock.push_back("Alistair: It is done! The golem is dead!");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: Hurray! All hail the great hero Alistair! We're finally free! The evil will now start");
TextBlock.push_back("to dissipate.");
TextBlock.push_back("");
TextBlock.push_back("Alistair: Thanks for everything you've taught me. I wouldn't have been able to do it without you.");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: You're most welcome. It's a small price to pay for our forests to finally be clean. So");
TextBlock.push_back("what will you do now?");
TextBlock.push_back("");
TextBlock.push_back("Alistair: I guess I'll continue on my adventures. I feel like my story is just beginning.");
TextBlock.push_back("");
TextBlock.push_back("Sprite King: That may be true. I wish you the best of luck on your future journeys! Don't forget me!");
TextBlock.push_back("");
TextBlock.push_back("Alistair: I won't. You take care for me too, Great King.");
}
DialogueWindow* TheDialogue = new DialogueWindow();
TheDialogue->WindowName = QuestToGive.QuestName + "(C)";
TheDialogue->BaseInit(playercharacter->PlayerHUD->XButtonTex, playercharacter->PlayerHUD, playercharacter);
TheDialogue->Init();
ImageWindowPart* newimagecomponent = new ImageWindowPart();
newimagecomponent->IsHoverable = true;
newimagecomponent->SizeToDraw = FVector(630.0f, 30.0f, 0.0f);
newimagecomponent->Location = FVector(10.0f, 430.0f, 0.0f);
newimagecomponent->TextureToDraw = playercharacter->PlayerHUD->QuestChoiceTex;
ImageWindowPart* newimagecomponenttwo = new ImageWindowPart();
newimagecomponenttwo->IsHoverable = true;
newimagecomponenttwo->SizeToDraw = FVector(630.0f, 30.0f, 0.0f);
newimagecomponenttwo->Location = FVector(10.0f, 470.0f, 0.0f);
newimagecomponenttwo->TextureToDraw = playercharacter->PlayerHUD->QuestChoiceTex;
TheDialogue->ImageComponents.push_back(newimagecomponent);
TheDialogue->ImageComponents.push_back(newimagecomponenttwo);
TextWindowPart* newtextcomponent = new TextWindowPart();
newtextcomponent->Location = FVector(45.0f, 435.0f, 0.0f);
newtextcomponent->TextColor = FLinearColor(1.0f, 1.0f, 1.0f);
newtextcomponent->TextContent = OptionOne;
newtextcomponent->Font = playercharacter->PlayerHUD->VerdanaFont;
TextWindowPart* newtextcomponenttwo = new TextWindowPart();
newtextcomponenttwo->Location = FVector(45.0f, 475.0f, 0.0f);
newtextcomponenttwo->TextColor = FLinearColor(1.0f, 1.0f, 1.0f);
newtextcomponenttwo->TextContent = OptionTwo;
newtextcomponenttwo->Font = playercharacter->PlayerHUD->VerdanaFont;
for (int i = 0; i < TextBlock.size(); i++)
{
TextWindowPart* newtext = new TextWindowPart();
newtext->Location = FVector(12.0f, i * 20.0f + 35.0f, 0.0f);
newtext->TextColor = FLinearColor(1.0f, 1.0f, 1.0f);
newtext->TextContent = TextBlock[i];
newtext->Font = playercharacter->PlayerHUD->VerdanaFont;
TheDialogue->TextComponents.push_back(newtext);
}
TheDialogue->TextComponents.push_back(newtextcomponent);
TheDialogue->TextComponents.push_back(newtextcomponenttwo);
TheDialogue->TheQuestGiver = this;
bool alreadyexists = false;
int existindex = 0;
for (int i = 0; i < playercharacter->PlayerHUD->WindowVector.size(); i++)
{
if (playercharacter->PlayerHUD->WindowVector[i]->WindowName == QuestToGive.QuestName + "(C)")
{
alreadyexists = true;
existindex = i;
}
}
for (int i = 0; i < playercharacter->QuestList.Num(); i++)
{
if (playercharacter->QuestList[i].QuestName == QuestToGive.QuestName)
{
if (playercharacter->QuestList[i].Progress >= playercharacter->QuestList[0].Amount)
{
if (!alreadyexists)
{
playercharacter->PlayerHUD->WindowVector.push_back(TheDialogue);
PlaySoundAtLocation(playercharacter->PlayerHUD->QuestOpenSound, playercharacter->GetActorLocation());
}
else
{
playercharacter->PlayerHUD->WindowVector[existindex]->IsActive = true;
playercharacter->PlayerHUD->WindowVector[existindex]->ClosingAlpha = 1.0f;
playercharacter->PlayerHUD->WindowVector[existindex]->IsClosing = false;
}
}
}
}
}
else
{
for (int i = 0; i < playercharacter->QuestList.Num(); i++)
{
if (playercharacter->QuestList[i].QuestName == QuestToGive.QuestName)
{
if (playercharacter->QuestList[i].Progress >= playercharacter->QuestList[i].Amount)
{
QuestState = COMPLETED;
if (QuestToGive.QuestType == COLLECTQUEST)
{
TakeItems(playercharacter);
}
playercharacter->QuestList[i] = FQuest();
FString questtext = "You have completed the quest '" + QuestToGive.QuestName + "'!";
playercharacter->QuestsCompleted++;
playercharacter->PlayerHUD->HUDAnnouncements.push_back(
new Announcement(questtext,
FLinearColor(1.0f, 1.0f, 0.4f),
playercharacter->PlayerHUD->DamageFont,
FVector(200.0f, 250.0f, 0.0f)));
PlaySoundAtLocation(playercharacter->PlayerHUD->QuestCloseSound, playercharacter->GetActorLocation());
if (QuestToGive.QuestID == 2)
{
playercharacter->AttackUnlocked = true;
}
if (QuestToGive.QuestID == 1)
{
playercharacter->SkillsUnlocked = true;
}
break;
}
}
}
}
}
}
void AQuestGiver::TakeItems(AAlistair* playercharacter)
{
int total = QuestToGive.Amount;
for (int i = 0; i < playercharacter->Inventory.Num(); i++)
{
if (playercharacter->Inventory[i].ID == QuestToGive.ContentID)
{
if (playercharacter->Inventory[i].Quantity >= total)
{
playercharacter->Inventory[i].Quantity -= total;
break;
}
else
{
total -= playercharacter->Inventory[i].Quantity;
playercharacter->Inventory[i].Quantity = 0;
}
}
}
} | [
"guoren.xu@loop.colum.edu"
] | guoren.xu@loop.colum.edu |
99c9a244133d5a0749b1e59cb9e348a0ef422dd9 | aeec67f03514eff7f7f0301dd220131d5e3421f5 | /dist/roslib/rtthread/components/tiny_ros/ros/service_client.h | bd59aa61c38b1fc17bf3c49f913ba9c49b832bf6 | [] | no_license | loulansuiye/tiny-ros | cfe910c26bf6e582c929dec6a3d6a0de0152e0b8 | 3b5f787352e01c8be62c08deb08ab5b78873dcac | refs/heads/master | 2022-04-26T02:40:10.035016 | 2020-04-19T06:18:46 | 2020-04-19T06:18:46 | 257,832,808 | 1 | 0 | null | 2020-04-22T08:03:04 | 2020-04-22T08:03:03 | null | UTF-8 | C++ | false | false | 3,543 | h | /*
* File : service_client.h
* This file is part of tiny_ros
*
* Change Logs:
* Date Author Notes
* 2018-04-24 Pinkie.Fu initial version
*/
#ifndef _TINYROS_SERVICE_CLIENT_H_
#define _TINYROS_SERVICE_CLIENT_H_
#include <stdint.h>
#include <rtthread.h>
#include "tiny_ros/tinyros_msgs/TopicInfo.h"
#include "tiny_ros/ros/publisher.h"
#include "tiny_ros/ros/subscriber.h"
namespace tinyros
{
template<typename MReq , typename MRes>
class ServiceClient : public Subscriber_
{
public:
ServiceClient(const char* topic_name) :
pub(topic_name, &req, tinyros_msgs::TopicInfo::ID_SERVICE_CLIENT + tinyros_msgs::TopicInfo::ID_PUBLISHER)
{
this->negotiated_ = false;
this->srv_flag_ = true;
this->topic_ = topic_name;
this->call_resp = NULL;
this->call_req = NULL;
this->waiting = true;
rt_mutex_init(&mutex_, "sc", RT_IPC_FLAG_FIFO);
rt_mutex_init(&g_mutex_, "gsc", RT_IPC_FLAG_FIFO);
}
virtual bool call(MReq & request, MRes & response, int duration = 3)
{
bool ret = false;
rt_mutex_take(&g_mutex_, RT_WAITING_FOREVER);
rt_mutex_take(&mutex_, RT_WAITING_FOREVER);
do {
if (!pub.nh_->ok()) { break; }
call_req = &request;
call_resp = &response;
rt_mutex_take(gg_mutex_, RT_WAITING_FOREVER);
call_req->setID(gg_id_++);
rt_mutex_release(gg_mutex_);
if (pub.publish(&request) <= 0) { break; }
this->waiting = true;
rt_mutex_release(&mutex_);
int count = (duration * 1000) / 50;
while (this->waiting && count >= 0) {
if (!this->waiting) { ret = true; break; }
if (count == 0) { break; }
rt_thread_delay(50);
count--;
}
if (!ret) {
printf("Service[%s] call_req.id: %u, call timeout", this->topic_, call_req->getID());
}
rt_mutex_take(&mutex_, RT_WAITING_FOREVER);
} while(0);
call_req = NULL; call_resp = NULL;
rt_mutex_release(&g_mutex_);
return ret;
}
// these refer to the subscriber
virtual void callback(unsigned char *data)
{
if (call_resp && call_req) {
rt_mutex_take(&mutex_, RT_WAITING_FOREVER);
if (call_resp && call_req) {
uint32_t req_id = call_req->getID();
uint32_t resp_id = ((uint32_t) (*(data + 0)));
resp_id |= ((uint32_t) (*(data + 1))) << (8 * 1);
resp_id |= ((uint32_t) (*(data + 2))) << (8 * 2);
resp_id |= ((uint32_t) (*(data + 3))) << (8 * 3);
if (req_id == resp_id) {
call_resp->deserialize(data);
this->waiting = false;
}
}
rt_mutex_release(&mutex_);
}
}
virtual const char * getMsgType()
{
return this->resp.getType();
}
virtual const char * getMsgMD5()
{
return this->resp.getMD5();
}
virtual int getEndpointType()
{
return tinyros_msgs::TopicInfo::ID_SERVICE_CLIENT + tinyros_msgs::TopicInfo::ID_SUBSCRIBER;
}
virtual bool negotiated()
{
return (negotiated_ && pub.negotiated_);
}
~ServiceClient() {
rt_mutex_delete(gg_mutex_);
}
MReq req;
MRes resp;
MReq * call_req;
MRes * call_resp;
bool waiting;
Publisher pub;
struct rt_mutex mutex_;
struct rt_mutex g_mutex_;
static uint32_t gg_id_;
static rt_mutex_t gg_mutex_;
};
template<typename MReq , typename MRes>
uint32_t ServiceClient<MReq , MRes>::gg_id_ = 1;
template<typename MReq , typename MRes>
rt_mutex_t ServiceClient<MReq , MRes>::gg_mutex_ = rt_mutex_create("ggsc", RT_IPC_FLAG_FIFO);
}
#endif
| [
"363960870@qq.com"
] | 363960870@qq.com |
aa77b3d4708ea1d7107f04de3809efa002facf61 | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtdeclarative/examples/quick/scenegraph/graph/gridnode.h | fdc4967b8cf4055c376f08f7887238debd12a466 | [
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"LGPL-3.0-only",
"GPL-1.0-or-later",
"GPL-3.0-only",
"Qt-LGPL-exception-1.1",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GFDL-1.3-only",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancode-warranty-discl... | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 2,276 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Qt Company Ltd 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef GRIDNODE_H
#define GRIDNODE_H
#include <QtQuick/QSGGeometryNode>
#include <QtQuick/QSGFlatColorMaterial>
class GridNode : public QSGGeometryNode
{
public:
GridNode();
void setRect(const QRectF &rect);
private:
QSGFlatColorMaterial m_material;
QSGGeometry m_geometry;
};
#endif // GRIDNODE_H
| [
"p_pavlov@wargaming.net"
] | p_pavlov@wargaming.net |
d92de4a6d900421e957c30711341e4927cc8595a | 0d01913f650bc6725b9856b8e969453f1b15ed0b | /Event.cpp | 679698546f924e12ecde4933b03aa38dbcae12d8 | [] | no_license | Lezrith/Synch | 396312560f330a3d863e89058513180a9efde00e | c1b59659f20d8d2424ae81b998646cf5d6994bd8 | refs/heads/master | 2021-01-01T18:11:43.482998 | 2017-03-15T22:28:09 | 2017-03-15T22:28:09 | 78,188,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,057 | cpp | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Event.cpp
* Author: Krzysztof Tomczak
*
* Created on January 3, 2017, 4:39 PM
*/
#include <stdexcept>
#include <vector>
#include "Event.h"
Event::Event() : path(""), pathDst("")
{
}
Event::Event(const Event& orig) : path(orig.path), pathDst(orig.pathDst)
{
}
Event::~Event()
{
}
Event::Event(Path path, Path pathDst, time_t when, bool isDirectory, EventType type) :
path(path), pathDst(pathDst), when(when), isDirectory(isDirectory), type(type)
{
}
Event::Event(Path path, time_t when, bool isDirectory, EventType type) :
path(path), pathDst(""), when(when), isDirectory(isDirectory), type(type)
{
}
string Event::ToString()
{
string result = "";
result += to_string(type) + " ";
result += path.ToString() + " ";
result += to_string(when);
if (isDirectory) result += " dir";
return result;
}
void Event::FromString(string s, int source)
{
this->source = source;
int nextSpace = s.find(" ");
try
{
this->type = static_cast<EventType> (stoi(s.substr(0, nextSpace)));
} catch (const invalid_argument &e)
{
cout << "Tried to make an event from string which does not represent an event: " + s << endl;
}
s = s.substr(nextSpace + 1);
s = this->path.FromString(s);
nextSpace = s.find(" ");
try
{
this->when = stoi(s.substr(0, nextSpace));
} catch (const invalid_argument &e)
{
cout << "Tried to make an event from string which does not represent an event: " + s << endl;
}
if (s.find("dir") != string::npos)
{
this->isDirectory = true;
}
else
{
this->isDirectory = false;
}
}
int Event::GetSource() const
{
return source;
}
Path Event::GetPath() const
{
return path;
}
EventType Event::GetType() const
{
return type;
}
bool Event::IsDirectory() const
{
return isDirectory;
} | [
"franc@debian"
] | franc@debian |
4ea33dbd824681152a068da38d565dbe560dafaf | f7fdf294d8c02cef53735203617e636a573eb056 | /openglShaderTemplate/glm-0.9.5.0/test/core/core_type_mat2x4.cpp | 3d523dd2c99a4e1a07f5d36fb55ead2d051d2eaf | [
"MIT"
] | permissive | dingchao-95/Dice_Game | 89fd8d198ab3be2d5b0e8f6443d55c494cbd52db | a1beeb67d4103cae8be3db7d8b2ccc1b8e8ddd13 | refs/heads/master | 2020-03-31T22:02:13.186198 | 2018-10-11T14:16:38 | 2018-10-11T14:16:38 | 152,602,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,724 | cpp | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2008-08-31
// Updated : 2008-08-31
// Licence : This source is under MIT License
// File : test/core/type_mat2x4.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <glm/vector_relational.hpp>
#include <glm/mat2x4.hpp>
#include <vector>
static int test_operators()
{
glm::mat2x4 l(1.0f);
glm::mat2x4 m(1.0f);
glm::vec2 u(1.0f);
glm::vec4 v(1.0f);
float x = 1.0f;
glm::vec4 a = m * u;
glm::vec2 b = v * m;
glm::mat2x4 n = x / m;
glm::mat2x4 o = m / x;
glm::mat2x4 p = x * m;
glm::mat2x4 q = m * x;
bool R = m != q;
bool S = m == l;
return (S && !R) ? 0 : 1;
}
int test_ctr()
{
int Error(0);
#if(GLM_HAS_INITIALIZER_LISTS)
glm::mat2x4 m0(
glm::vec4(0, 1, 2, 3),
glm::vec4(4, 5, 6, 7));
glm::mat2x4 m1{0, 1, 2, 3, 4, 5, 6, 7};
glm::mat2x4 m2{
{0, 1, 2, 3},
{4, 5, 6, 7}};
for(int i = 0; i < m0.length(); ++i)
Error += glm::all(glm::equal(m0[i], m2[i])) ? 0 : 1;
for(int i = 0; i < m1.length(); ++i)
Error += glm::all(glm::equal(m1[i], m2[i])) ? 0 : 1;
std::vector<glm::mat2x4> v1{
{0, 1, 2, 3, 4, 5, 6, 7},
{0, 1, 2, 3, 4, 5, 6, 7}
};
std::vector<glm::mat2x4> v2{
{
{ 0, 1, 2, 3},
{ 4, 5, 6, 7}
},
{
{ 0, 1, 2, 3},
{ 4, 5, 6, 7}
}
};
#endif//GLM_HAS_INITIALIZER_LISTS
return Error;
}
int main()
{
int Error = 0;
Error += test_ctr();
Error += test_operators();
return Error;
}
| [
"dingchao95@gmail.com"
] | dingchao95@gmail.com |
545356d82933e65c42cc2405421a6907b3805d33 | 3adce1dc1f85a12428fee2cd3c57d5d0a0b091f1 | /src/lib/include/utils/TaskSystem.hpp | b764b114df925d6f1682ea0aa12c65b016bebff1 | [] | no_license | ATTPC/ATTPCFrontEnd | 8d5dee885bfd2727b815bee6a06bea1139ca7f0e | 156e3537e56b98e7b421a8757e2fa3b1e3b08393 | refs/heads/master | 2021-06-12T07:14:18.959107 | 2019-09-04T18:08:18 | 2019-09-04T18:08:18 | 129,452,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,357 | hpp | // Following Sean Parent's implementation in concurrency talk @ NDC 2017
// Some considerations from Mastering the C++17 STL by Arthur O'Dwyer
// Not using pimpl idiom because of templated async
#ifndef TASKSYSTEM_HPP
#define TASKSYSTEM_HPP
#include <utils/NotificationQueue.hpp>
#include <thread>
#include <vector>
#include <functional>
#ifdef UNITTEST
#include <utils/UnitTestable.hpp>
#endif
namespace attpcfe {
#ifdef UNITTEST
class TaskSystem : public UnitTestable<TaskSystem> {
friend struct Test<TaskSystem>;
static void test();
#else
class TaskSystem {
#endif
const unsigned int _count{std::thread::hardware_concurrency()};
const unsigned int _K{3};
std::vector<std::thread> _threads;
std::vector<NotificationQueue> _qs{_count};
std::atomic<unsigned int> _index{0};
public:
TaskSystem();
~TaskSystem();
// Non future returning version of async.
template<typename F, typename... Args>
void async(F&& func, Args&&... args);
// Future returning version of async.
template<typename F, typename... Args>
auto async_get(F&& func, Args&&... args);
// Continuation.
template<typename T, typename F, typename... Args>
auto then(std::future<T>& f, F&& func, Args&&... args);
private:
void run(unsigned int i);
};
}
#include <utils/TaskSystem.inl>
#endif
| [
"niko.znotinside@gmail.com"
] | niko.znotinside@gmail.com |
832d6ce838d7b48082576514f3da7daa84869c0c | eb1187899f1ec2c9b52216cbdbedab13d6915885 | /Source/gameInaWeekPra/mainchar/chickAnim.h | ffcf224095abc5a4fd2e6bdfe66d1754186cfd61 | [] | no_license | kusaflow/chickGame | 4716c9f1a5d609a3427e77557238b86583867281 | feb1b5c3d54ceb474e7e48d57e1ada003efc3467 | refs/heads/master | 2022-12-07T11:55:14.518767 | 2020-08-28T10:51:16 | 2020-08-28T10:51:16 | 284,661,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Animation/AnimInstance.h"
#include "chickAnim.generated.h"
/**
*
*/
UCLASS()
class GAMEINAWEEKPRA_API UchickAnim : public UAnimInstance
{
GENERATED_BODY()
public :
UPROPERTY(BlueprintReadOnly, Category = "kusavar")
int animState = 0;
UFUNCTION(BlueprintCallable, Category = "AnimProperty")
void update();
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Movement")
class Achick* player;
};
| [
"kunalsagar1999@gmail.com"
] | kunalsagar1999@gmail.com |
81c3606bdebae3fbf98694cd505bdc59bd6c7527 | dc1e9b919c0f771336ed61c88b6e4b953588bdc7 | /Documentos/qt_proyectos/visorXtractorUrl/mainwindow.cpp | 55c6ac3ffda5427a8d5eec3391256f1c8866fd68 | [] | no_license | pablomvb/misaplicaciones | 6f4fbb85fe0d61069b082e009da4a61d0382d5b1 | abdf3418d9741d76aa29534a485b3a9c4c5fac4e | refs/heads/master | 2020-06-02T15:05:46.900488 | 2014-09-25T21:47:00 | 2014-09-25T21:47:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | #include "mainwindow.h"
#include <QListWidget>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QListWidget* list = new QListWidget();
list->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
| [
"pablomvb@toshiba"
] | pablomvb@toshiba |
ad809fd88c22e18064235c2cc4ec69ca6e94eb1e | 7afbb1bf03ef4fcdd2fe262b744231f45f9405c9 | /c_plus_plus_white/week_2/avtobusnyie-ostanovki-3.cpp | 603414868ddddecf410068be28e628a0582cf97c | [] | no_license | samikhailov/coursera | b19a10490557cfa40de20d110d86ae80de92009b | e294698b61597a6c487fff7b56b03bb32b7b8c9b | refs/heads/master | 2021-07-14T01:37:15.921986 | 2021-03-03T19:06:01 | 2021-03-03T19:06:01 | 240,074,597 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | cpp | #include <iostream>
#include <string>
#include <set>
#include <map>
using namespace std;
int main() {
int n, q;
string s;
map<set<string>, int> m;
set<string> stops;
cin >> n;
for (int i = 1; i < n + 1; i++) {
stops.clear();
cin >> q;
for (int j = 0; j < q; j++) {
cin >> s;
stops.insert(s);
}
if (m.count(stops) == 1) {
cout << "Already exists for " << m[stops] << endl;
}
else {
m[stops] = m.size() + 1;
cout << "New bus " << m[stops] << endl;
}
}
return 0;
}
| [
"ko_0n@mail.ru"
] | ko_0n@mail.ru |
2e22e4e87f4fc6a0e4581bfd7293ce3de41ef300 | 458e8e86d7784b919a0bb80b6cd6654bc7771e68 | /ontology_model/my_work/agents_c_plus/0.5.0/problem-solver/cxx/factual_knowledge_similarity_calculation/factual_knowledge_similarity_calculation.hpp | 0b82bc9ad7e3d184be15f1c5519c921fc9f2976b | [] | no_license | liwenzu/BSUIR-OSTIS | 50090993810695d0384ef2e0f1225d630370f2f1 | 980d4628567912c816f333fd4c4d5ea7f195cab3 | refs/heads/master | 2022-09-21T06:24:29.684173 | 2022-09-14T19:30:24 | 2022-09-14T19:30:24 | 218,078,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | hpp | /*
* This source file is part of an OSTIS project. For the latest info, see http://ostis.net
* Distributed under the MIT License
* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
*/
#pragma once
#include <sc_memory.h>
#include <sc-memory/cpp/sc_module.hpp>
#include "factual_knowledge_similarity_calculation.generated.hpp"
class Facknowsimcalcu: public ScModule
{
SC_CLASS(LoadOrder(50))
SC_GENERATED_BODY()
virtual sc_result InitializeImpl() override;
virtual sc_result ShutdownImpl() override;
}; | [
"lwzzggml@gmail.com"
] | lwzzggml@gmail.com |
b2c296ccce844e9b38732a16d09eed42d7bd74ae | a2424f0c80a06446c8c9c32ac1e2d63bd7aa1d6b | /Source/SprueKitEditor/Documents/TexGen/TextureGraphExportDialog.cpp | 1b9745e0531496dbe13d6c7d4b13e5f84143a204 | [
"MIT"
] | permissive | caniouff/TexGraph | 6a30852866c7c3a4a278f94bbd65195951badd64 | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | refs/heads/master | 2020-06-26T01:28:15.637110 | 2019-01-27T01:00:43 | 2019-01-27T01:00:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,480 | cpp | #include "TextureGraphExportDialog.h"
#include "../../GlobalAccess.h"
#include "../../Localization/LocalizedWidgets.h"
#include "TextureDocument.h"
#include <EditorLib/DocumentManager.h>
#include <EditorLib/Localization/Localizer.h>
#include <EditorLib/Controls/PathPickerWidget.h>
#include <EditorLib/Settings/Settings.h>
#include <EditorLib/Settings/SettingsPage.h>
#include <EditorLib/Settings/SettingsValue.h>
#include <QBoxLayout>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QDir>
#include <QGroupBox>
#include <QLabel>
#include <QMessageBox>
#include <QProgressDialog>
#include <QPushButton>
namespace SprueEditor
{
TextureGraphExportDialog::TextureGraphExportDialog(QWidget* owner) :
QDialog(owner)
{
setWindowTitle(Localizer::Translate("Export Textures"));
QVBoxLayout* masterLayout = new QVBoxLayout(this);
// Export To
QString path;
if (auto setting = Settings::GetInstance()->GetValue("Texture Graph Export/Export To"))
path = setting->value_.toString();
masterLayout->addWidget(new LocalizedLabel("Export To:"));
PathPickerWidget* exportDir = new PathPickerWidget(true, false);
if (QDir(path).exists())
exportDir->SetPath(path.toStdString());
masterLayout->addWidget(exportDir);
// Naming convention
masterLayout->addWidget(new LocalizedLabel("Naming Convention"));
// TODO get it from settings
QLineEdit* namingConvention = new QLineEdit("%1_%2");
masterLayout->addWidget(namingConvention);
{
QGroupBox* conventionInfo = new QGroupBox();
QVBoxLayout* groupBoxLayout = new QVBoxLayout(conventionInfo);
QLabel* info = new LocalizedLabel("Use '%1' to insert the name of the file, ie. 'MyStoneTex'");
QLabel* info2 = new LocalizedLabel("Use '%3' to insert the type of output, ie. 'albedo'");
groupBoxLayout->addWidget(info);
groupBoxLayout->addWidget(info2);
masterLayout->addWidget(conventionInfo);
}
// Export frmat
masterLayout->addWidget(new LocalizedLabel("Export Format"));
QComboBox* format = new QComboBox();
format->addItem("PNG");
format->addItem("TGA");
format->addItem("HDR");
format->addItem("DDS Compressed (DXT1 or DXT5)");
masterLayout->addWidget(format);
if (auto setting = Settings::GetInstance()->GetValue("Texture Graph Export/Export Format"))
format->setCurrentIndex(setting->value_.toInt());
else
format->setCurrentIndex(0);
// Button box
QDialogButtonBox* buttons = new QDialogButtonBox();
QPushButton* exportButton = new QPushButton("Export");
buttons->addButton(exportButton, QDialogButtonBox::ButtonRole::AcceptRole);
connect(buttons->addButton(QDialogButtonBox::Cancel), &QPushButton::clicked, [=]() {
close();
});
masterLayout->addWidget(buttons);
connect(exportButton, &QPushButton::clicked, [=]() {
QString exportPath = exportDir->GetPath().c_str();
if (exportPath.isEmpty() || !QDir(exportPath).exists())
{
QMessageBox::warning(0x0, Localizer::Translate("Unable to export Textures"), Localizer::Translate("An export directory must be specified to export textures."));
return;
}
QString convention = namingConvention->text();
if (convention.isEmpty())
{
QMessageBox::warning(0x0, Localizer::Translate("Unable to export Textures"), Localizer::Translate("A naming convention must be specified."));
return;
}
if (auto docMan = Global_DocumentManager())
{
if (auto textureDocument = docMan->GetActiveDoc<TextureDocument>())
{
int count = textureDocument->GetExportWorkCount();
QProgressDialog progress("Exporting textures", "Cancel", 0, count);
progress.show();
for (int i = 0;; ++i)
{
if (!textureDocument->WriteTextures(exportPath, convention, i, format->currentIndex()))
break;
if (progress.wasCanceled())
break;
progress.setValue(i + 1);
}
progress.close();
close();
if (auto setting = Settings::GetInstance()->GetValue("Texture Graph Export/Folder to export images into"))
setting->value_ = QString(exportDir->GetPath().c_str());
if (auto setting = Settings::GetInstance()->GetValue("Texture Graph Export/Export Format"))
setting->value_ = format->currentIndex();
}
else
{
QMessageBox::warning(0x0, Localizer::Translate("Unable to export Textures"), Localizer::Translate("A Texture Graph document must be opened in order to export textures."));
return;
}
}
});
}
TextureGraphExportDialog::~TextureGraphExportDialog()
{
}
} | [
"jonathan@jsandusky.com"
] | jonathan@jsandusky.com |
f17b3c0b1ba58b2b16744386ffb9e658697fac3d | 8d8132f96d8886f7558ba24e182680369f1a1259 | /include/TargetAddress.h | ad244a777fc64f6d99178dffb3a295e37d370bd6 | [] | no_license | youseffathy/SIC-XE-Assembler | 23d5baa79741fe8b59e4b25fff6305833b0fc4a2 | 49b24971eb147095955de7636412b3a7ba01497b | refs/heads/main | 2023-03-24T12:54:03.094530 | 2021-03-23T06:50:01 | 2021-03-23T06:50:01 | 350,608,193 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | h | #ifndef TARGETADDRESS_H
#define TARGETADDRESS_H
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include "symbolTable.h"
using namespace std;
class TargetAddress
{
public:
TargetAddress();
string getAddress(string operand);
void setSymbolTable(symbolTable mySymTable);
protected:
private:
};
#endif // TARGETADDRESS_H
| [
"youseffathy760@gmail.com"
] | youseffathy760@gmail.com |
546ed491fe2de53d0fdb08ad06bfbf33817a561a | 2e9750e1e56a685a68c76605d4c466a6e4fa8169 | /OverPoch Trader/cfgServerTrader/NeutralAssaultRifleAmmo.hpp | 12115a99ece12e890e2ef82fbc44fc8715692ec5 | [] | no_license | KingRaymond/OverPochSahrani | 3034c925bebc0dc47f55ad6eed3f775aed8a5b71 | 42217df3d6a9b6cb8e2ea46e02c7a4cbb2f846bb | refs/heads/master | 2016-09-06T10:32:44.248600 | 2014-12-02T10:54:41 | 2014-12-02T10:54:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,080 | hpp | class Category_643 {
class 30Rnd_556x45_Stanag {
type = "trade_items";
buy[] ={750,"Coins"};
sell[] ={70,"Coins"};
};
class 20Rnd_762x51_FNFAL {
type = "trade_items";
buy[] ={950,"Coins"};
sell[] ={85,"Coins"};
};
class 30Rnd_545x39_AK {
type = "trade_items";
buy[] ={550,"Coins"};
sell[] ={55,"Coins"};
};
class 30Rnd_762x39_AK47 {
type = "trade_items";
buy[] ={600,"Coins"};
sell[] ={60,"Coins"};
};
class 30Rnd_762x39_SA58 {
type = "trade_items";
buy[] ={825,"Coins"};
sell[] ={85,"Coins"};
};
};
class Category_609 {
class 30Rnd_556x45_Stanag {
type = "trade_items";
buy[] ={750,"Coins"};
sell[] ={70,"Coins"};
};
class 20Rnd_762x51_FNFAL {
type = "trade_items";
buy[] ={950,"Coins"};
sell[] ={85,"Coins"};
};
class 30Rnd_545x39_AK {
type = "trade_items";
buy[] ={550,"Coins"};
sell[] ={55,"Coins"};
};
class 30Rnd_762x39_AK47 {
type = "trade_items";
buy[] ={600,"Coins"};
sell[] ={60,"Coins"};
};
class 30Rnd_762x39_SA58 {
type = "trade_items";
buy[] ={825,"Coins"};
sell[] ={85,"Coins"};
};
};
| [
"info@silversitemedia.com"
] | info@silversitemedia.com |
013f3acf55a56402eef6e76e8a55a91783dd827d | 74794facdaa1ef5cbdfe6b111aaa0c83305b1f86 | /ui_kit/module/tray/tray_manager.cpp | 7f0e849fcd1fff37eaa99cce91ad7e35f72c9764 | [] | no_license | lineCode/base_dui | 95f1924b005bea4f3321e9de8f82360c2c16d5f6 | 91149bb79c59346a142d84f85b94f91fd29a7478 | refs/heads/master | 2020-03-29T19:11:15.142715 | 2018-09-22T07:46:03 | 2018-09-22T07:46:03 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,973 | cpp | #include "stdafx.h"
#include "tray_manager.h"
const DWORD uTrayIconAnimateID = 0x0001;
#define TRAYICON_ID 1
#define WM_TRAYICON_NOTIFY (WM_USER + 1)
namespace nim_comp
{
static bool bTrayManagerInit = false;
LRESULT TrayManager::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT res = 1;
switch (uMsg)
{
case WM_TRAYICON_NOTIFY:
{
if (TRAYICON_ID != wParam)
break;
if (WM_LBUTTONUP == lParam)
{
TrayManager::GetInstance()->LeftClick();
}
else if (WM_LBUTTONDBLCLK == lParam)
{
TrayManager::GetInstance()->DoubleClick();
}
else if (WM_RBUTTONUP == lParam)
{
TrayManager::GetInstance()->RightClick();
}
break;
}
case WM_TIMER:
{
TrayManager::GetInstance()->OnTimer((UINT)wParam);
break;
}
default:
{
if (uMsg != 0 && uMsg == TrayManager::GetInstance()->GetTaskbarCreatedMsgId())
{
TrayManager::GetInstance()->RestoreTrayIcon();
}
res = ::DefWindowProc(hWnd, uMsg, wParam, lParam);
break;
}}
return res;
}
void TrayManager::LeftClick()
{
for (auto it = left_click_cbs_.cbegin(); it != left_click_cbs_.cend(); it++)
{
if (*it)
{
(*it)();
}
}
}
void TrayManager::RightClick()
{
for (auto it = right_click_cbs_.cbegin(); it != right_click_cbs_.cend(); it++)
{
if (*it)
{
(*it)();
}
}
}
void TrayManager::DoubleClick()
{
for (auto it = double_click_cbs_.cbegin(); it != double_click_cbs_.cend(); it++)
{
if (*it)
{
(*it)();
}
}
}
TrayManager::TrayManager() :
wnd_(NULL),
anim_index_array_(),
index_icon_map_(),
anim_escape_time_(0),
anim_current_index_(0),
icon_(NULL),
tray_icon_text_(L""),
trayicon_msgid_(0)
{
}
TrayManager::~TrayManager()
{
}
void TrayManager::Init()
{
//tray_icon_delegate_ = tray_icon_delegate;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = GetModuleHandleW(NULL);
wndclass.hIcon = NULL;
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = L"nim_tray_icon_class_name";
::RegisterClass(&wndclass);
wnd_ = CreateWindowExW(NULL, L"nim_tray_icon_class_name", L"nim_tray_icon_window_name", WS_POPUP | WS_CHILD,
0, 0, 0, 0, NULL, NULL, GetModuleHandleW(NULL), NULL);
//注册explorer崩溃后重新刷新trayicon
trayicon_msgid_ = ::RegisterWindowMessage(L"TaskbarCreated");
assert(wnd_);
}
void TrayManager::Destroy()
{
NOTIFYICONDATAW tnd = { 0 };
tnd.cbSize = sizeof(NOTIFYICONDATA);
tnd.uFlags = 0;
tnd.hWnd = wnd_;
tnd.uID = TRAYICON_ID;
::Shell_NotifyIcon(NIM_DELETE, &tnd);
}
void TrayManager::RegEventCallback(TrayLeftClick ev, TrayEventType type)
{
switch (type)
{
case TrayEventType_LeftClick:
left_click_cbs_.push_back(ev);
break;
case TrayEventType_RightClick:
right_click_cbs_.push_back(ev);
break;
case TrayEventType_DoubleClick:
double_click_cbs_.push_back(ev);
break;
default:
break;
}
return;
}
void TrayManager::SetTrayIcon(HICON icon, const std::wstring& tray_icon_text)
{
assert(icon);
icon_ = icon;
tray_icon_text_ = tray_icon_text;
ModifyTrayIcon(TRAYICON_ID, WM_TRAYICON_NOTIFY, icon, tray_icon_text);
}
void TrayManager::LoadIconList(int icon_res_start_index, int count)
{
for (int i = 0; i < count; ++i)
{
HICON icon = (HICON)::LoadImage(NULL,
MAKEINTRESOURCE(icon_res_start_index + i),
IMAGE_ICON,
::GetSystemMetrics(SM_CXSMICON),
::GetSystemMetrics(SM_CYSMICON),
LR_DEFAULTCOLOR | LR_SHARED);
assert(icon);
index_icon_map_[icon_res_start_index + i] = icon;
}
}
void TrayManager::SetAnimateTray(const std::vector<int>& aniIndex, int anim_escape_time)
{
ClearAnimateInfo();
anim_index_array_ = aniIndex;
anim_escape_time_ = anim_escape_time;
}
void TrayManager::StartTrayIconAnimate()
{
assert(index_icon_map_.size());
anim_current_index_ = 0;
KillTimer(wnd_, uTrayIconAnimateID);
SetTimer(wnd_, uTrayIconAnimateID, anim_escape_time_, NULL);
}
void TrayManager::StopTrayIconAnimate()
{
KillTimer(wnd_, uTrayIconAnimateID);
}
void TrayManager::ClearAnimateInfo()
{
anim_index_array_.clear();
anim_current_index_ = 0;
anim_escape_time_ = 0;
}
void TrayManager::OnTimer(UINT event_id)
{
switch (event_id)
{
case uTrayIconAnimateID:
if (0 != anim_index_array_.size())
{
anim_current_index_ %= anim_index_array_.size();
SetTrayIconIndex(anim_index_array_[anim_current_index_++]);
}
else
{
StopTrayIconAnimate();
}
break;
default:
{
assert(FALSE);
break;
}}
}
void TrayManager::SetTrayIconIndex(int index)
{
HICON hIcon = index_icon_map_[index];
assert(hIcon);
SetTrayIcon(hIcon, L"");
}
BOOL TrayManager::RestoreTrayIcon()
{
if (!IsWindow(wnd_))
return FALSE;
bTrayManagerInit = false;
SetTrayIcon(icon_, tray_icon_text_);
return TRUE;
}
void TrayManager::ModifyTrayIcon(UINT uTrayID, DWORD dwTrayMsg,
HICON hTrayIcon, const std::wstring &tray_icon_text)
{
NOTIFYICONDATAW tnd = { 0 };
tnd.cbSize = sizeof(NOTIFYICONDATA);
tnd.hWnd = wnd_;
tnd.uID = uTrayID;
tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
tnd.uCallbackMessage = dwTrayMsg;
tnd.hIcon = hTrayIcon;
#ifdef NDEBUG
wcscpy_s(tnd.szTip, 128, tray_icon_text.c_str());
#else
std::wstring debug_text = tray_icon_text + L"[DEBUG]";
wcscpy_s(tnd.szTip, 128, debug_text.c_str());
#endif
if (!bTrayManagerInit)
{
bTrayManagerInit = true;
BOOL res = ::Shell_NotifyIconW(NIM_ADD, &tnd);
//在极端情况下有可能会安装托盘失败,这里再尝试下
if (!res)
{
res = ::Shell_NotifyIconW(NIM_ADD, &tnd);
}
}
else
{
BOOL res = ::Shell_NotifyIcon(NIM_MODIFY, &tnd);
assert(res);
}
}
}
| [
"422795380@qq.com"
] | 422795380@qq.com |
fb7436a1ac52be0d650f45384c22f1b4e1dd98e2 | 17d766a296cc6c72499bba01b82d58f7df747b64 | /ABC_string.cpp | 88a6c9ef1f81df711885b0163f2bd31eef1d7357 | [] | no_license | Kullsno2/C-Cpp-Programs | 1dd7a57cf7e4c70831c5b36566605dc35abdeb67 | 2b81ddc67f22ada291e85bfc377e59e6833e48fb | refs/heads/master | 2021-01-22T21:45:41.214882 | 2015-11-15T11:15:46 | 2015-11-15T11:15:46 | 85,473,174 | 0 | 1 | null | 2017-03-19T12:12:00 | 2017-03-19T12:11:59 | null | UTF-8 | C++ | false | false | 1,074 | cpp | #include<bits/stdc++.h>
#define ll long long
#define p(a) printf("%d\n",a)
#define s(a) scanf("%d",&a)
#define sll(a) scanf("%lld",&a)
#define sl(a) scanf("%ld",&a)
#define rep(a,b,c) for(int c=a ; c<=b ; ++c)
#define pii pair<int , int>
#define vi vector<int>
#define vs vector<string>
#define vi_it vector<int> :: iterator
#define vs_it vector<string> :: iterator
#define mp(a,b) make_pair(a,b)
#define MOD 1000000007
using namespace std ;
ll int power( ll int base, ll int exponent)
{
ll int result = 1;
while (exponent > 0)
{
if (exponent % 2 == 1)
result = (result * base) % MOD;
exponent = exponent >> 1;
base = (base * base) % MOD;
}
//cout<<result<<endl;
return result;
}
ll int mul(ll int n)
{
int k = 2 ,temp=n;
while(k--)
n = (temp+n)%MOD ;
return n ;
}
int main() {
ios :: sync_with_stdio(false);
int t ;
s(t) ;
while(t--)
{
ll int n ; sll(n) ;
if(n<3)
{
cout<<"0"<<endl;
continue;
}
printf("%lld\n",(mul((power(3,n-1) - power(2,n) )+ 1)%MOD)%MOD);
}
return 0;
}
| [
"nanduvinodan2@gmail.com"
] | nanduvinodan2@gmail.com |
07c48e2c5e566ac5344220631594a76b8c1e3621 | 89d6a2628ca7437d6bce6623f6c1d909d0c310df | /tiny/cores/tiny/HardwareSerial.cpp | 3659553833d2afc15786a2986f5c651017eccabd | [] | no_license | cano64/ATTinyCore | fe33ed085e1684bf3a28fb911c7ce6665a810ca4 | 2af21af52aabc828d8a935c20380cddd070252cf | refs/heads/master | 2021-01-17T08:23:16.679044 | 2014-02-06T16:17:41 | 2014-02-06T16:17:41 | 16,379,572 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,740 | cpp | /*
HardwareSerial.cpp - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 23 November 2006 by David A. Mellis
Modified 28 September 2010 by Mark Sproul
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Arduino.h"
#include "wiring_private.h"
// this next line disables the entire HardwareSerial.cpp,
// this is so I can support Attiny series and any other chip without a uart
#if ( defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(LINBRRH)) && !USE_SOFTWARE_SERIAL
#include "HardwareSerial.h"
// Define constants and variables for buffering incoming serial data. We're
// using a ring buffer (I think), in which rx_buffer_head is the index of the
// location to which to write the next incoming character and rx_buffer_tail
// is the index of the location from which to read.
#if (RAMEND < 1000)
#define SERIAL_BUFFER_SIZE 16
#else
#define SERIAL_BUFFER_SIZE 64
#endif
struct ring_buffer
{
unsigned char buffer[SERIAL_BUFFER_SIZE];
byte head;
byte tail;
};
#if defined(UBRRH) || defined(UBRR0H) || defined(LINBRRH)
ring_buffer rx_buffer = { { 0 }, 0, 0 };
ring_buffer tx_buffer = { { 0 }, 0, 0 };
#endif
#if defined(UBRR1H)
ring_buffer rx_buffer1 = { { 0 }, 0, 0 };
ring_buffer tx_buffer1 = { { 0 }, 0, 0 };
#endif
inline void store_char(unsigned char c, ring_buffer *buffer)
{
byte i = (buffer->head + 1) % SERIAL_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
}
#if defined(USART_RX_vect)
SIGNAL(USART_RX_vect)
{
#if defined(UDR0)
unsigned char c = UDR0;
#elif defined(UDR)
unsigned char c = UDR; // atmega8535
#else
#error UDR not defined
#endif
store_char(c, &rx_buffer);
}
#elif defined(SIG_USART0_RECV) && defined(UDR0)
SIGNAL(SIG_USART0_RECV)
{
unsigned char c = UDR0;
store_char(c, &rx_buffer);
}
#elif defined(SIG_UART0_RECV) && defined(UDR0)
SIGNAL(SIG_UART0_RECV)
{
unsigned char c = UDR0;
store_char(c, &rx_buffer);
}
//#elif defined(SIG_USART_RECV)
#elif defined(USART0_RX_vect)
// fixed by Mark Sproul this is on the 644/644p
//SIGNAL(SIG_USART_RECV)
SIGNAL(USART0_RX_vect)
{
#if defined(UDR0)
unsigned char c = UDR0;
#elif defined(UDR)
unsigned char c = UDR; // atmega8, atmega32
#else
#error UDR not defined
#endif
store_char(c, &rx_buffer);
}
#elif defined(SIG_UART_RECV)
// this is for atmega8
SIGNAL(SIG_UART_RECV)
{
#if defined(UDR0)
unsigned char c = UDR0; // atmega645
#elif defined(UDR)
unsigned char c = UDR; // atmega8
#endif
store_char(c, &rx_buffer);
}
#elif defined(LIN_TC_vect)
// this is for attinyX7
SIGNAL(LIN_TC_vect)
{
if(LINSIR & _BV(LRXOK)) {
unsigned char c = LINDAT;
store_char(c, &rx_buffer);
}
if(LINSIR & _BV(LTXOK)){
PINA |= _BV(PINA5);
if (tx_buffer.head == tx_buffer.tail) {
// Buffer empty, so disable interrupts
cbi(LINENIR,LENTXOK);
} else {
// There is more data in the output buffer. Send the next byte
unsigned char c = tx_buffer.buffer[tx_buffer.tail];
tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
LINDAT = c;
}
}
}
#else
#error No interrupt handler for usart 0
#endif
//#if defined(SIG_USART1_RECV)
#if defined(USART1_RX_vect)
//SIGNAL(SIG_USART1_RECV)
SIGNAL(USART1_RX_vect)
{
unsigned char c = UDR1;
store_char(c, &rx_buffer1);
}
#elif defined(SIG_USART1_RECV)
#error SIG_USART1_RECV
#endif
#if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect) && !defined(LIN_TC_vect)
#error "Don't know what the Data Register Empty vector is called for the first UART"
#elif ( defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H))
#if defined(UART0_UDRE_vect)
ISR(UART0_UDRE_vect)
#elif defined(UART_UDRE_vect)
ISR(UART_UDRE_vect)
#elif defined(USART0_UDRE_vect)
ISR(USART0_UDRE_vect)
#elif defined(USART_UDRE_vect)
ISR(USART_UDRE_vect)
#endif
{
if (tx_buffer.head == tx_buffer.tail) {
// Buffer empty, so disable interrupts
#if defined(UCSR0B)
cbi(UCSR0B, UDRIE0);
#else
cbi(UCSRB, UDRIE);
#endif
}
else {
// There is more data in the output buffer. Send the next byte
unsigned char c = tx_buffer.buffer[tx_buffer.tail];
tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
#if defined(UDR0)
UDR0 = c;
#elif defined(UDR)
UDR = c;
#else
#error UDR not defined
#endif
}
}
#endif
#ifdef USART1_UDRE_vect
ISR(USART1_UDRE_vect)
{
if (tx_buffer1.head == tx_buffer1.tail) {
// Buffer empty, so disable interrupts
cbi(UCSR1B, UDRIE1);
}
else {
// There is more data in the output buffer. Send the next byte
unsigned char c = tx_buffer1.buffer[tx_buffer1.tail];
tx_buffer1.tail = (tx_buffer1.tail + 1) % SERIAL_BUFFER_SIZE;
UDR1 = c;
}
}
#endif
// Constructors ////////////////////////////////////////////////////////////////
HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer
#if ( defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H))
,
volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
volatile uint8_t *udr,
uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x
)
{
_rx_buffer = rx_buffer;
_tx_buffer = tx_buffer;
_ubrrh = ubrrh;
_ubrrl = ubrrl;
_ucsra = ucsra;
_ucsrb = ucsrb;
_udr = udr;
_rxen = rxen;
_txen = txen;
_rxcie = rxcie;
_udrie = udrie;
_u2x = u2x;
}
#else
)
{
_rx_buffer = rx_buffer;
_tx_buffer = tx_buffer;
}
#endif
// Public Methods //////////////////////////////////////////////////////////////
void HardwareSerial::begin(long baud)
{
#if ( defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H))
uint16_t baud_setting;
bool use_u2x = true;
#if F_CPU == 16000000UL
// hardcoded exception for compatibility with the bootloader shipped
// with the Duemilanove and previous boards and the firmware on the 8U2
// on the Uno and Mega 2560.
if (baud == 57600) {
use_u2x = false;
}
#endif
try_again:
if (use_u2x) {
*_ucsra = 1 << _u2x;
baud_setting = (F_CPU / 4 / baud - 1) / 2;
} else {
*_ucsra = 0;
baud_setting = (F_CPU / 8 / baud - 1) / 2;
}
if ((baud_setting > 4095) && use_u2x)
{
use_u2x = false;
goto try_again;
}
// assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
*_ubrrh = baud_setting >> 8;
*_ubrrl = baud_setting;
sbi(*_ucsrb, _rxen);
sbi(*_ucsrb, _txen);
sbi(*_ucsrb, _rxcie);
cbi(*_ucsrb, _udrie);
#else
LINCR = (1 << LSWRES);
LINBRR = (((F_CPU * 10L / 16L / baud) + 5L) / 10L) - 1;
LINBTR = (1 << LDISR) | (16 << LBT0);
LINCR = _BV(LENA) | _BV(LCMD2) | _BV(LCMD1) | _BV(LCMD0);
sbi(LINENIR,LENRXOK);
#endif
}
void HardwareSerial::end()
{
while (_tx_buffer->head != _tx_buffer->tail)
;
#if ( defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H))
cbi(*_ucsrb, _rxen);
cbi(*_ucsrb, _txen);
cbi(*_ucsrb, _rxcie);
cbi(*_ucsrb, _udrie);
#else
cbi(LINENIR,LENTXOK);
cbi(LINENIR,LENRXOK);
cbi(LINCR,LENA);
cbi(LINCR,LCMD0);
cbi(LINCR,LCMD1);
cbi(LINCR,LCMD2);
#endif
_rx_buffer->head = _rx_buffer->tail;
}
int HardwareSerial::available(void)
{
return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE;
}
int HardwareSerial::peek(void)
{
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
return _rx_buffer->buffer[_rx_buffer->tail];
}
}
int HardwareSerial::read(void)
{
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
_rx_buffer->tail = (_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE;
return c;
}
}
void HardwareSerial::flush()
{
while (_tx_buffer->head != _tx_buffer->tail)
;
}
size_t HardwareSerial::write(uint8_t c)
{
byte i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE;
// If the output buffer is full, there's nothing for it other than to
// wait for the interrupt handler to empty it a bit
// ???: return 0 here instead?
while (i == _tx_buffer->tail)
;
_tx_buffer->buffer[_tx_buffer->head] = c;
_tx_buffer->head = i;
#if ( defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) )
sbi(*_ucsrb, _udrie);
#else
if(!(LINENIR & _BV(LENTXOK))){
//The buffer was previously empty, so enable TX Complete interrupt and load first byte.
sbi(LINENIR,LENTXOK);
unsigned char c = tx_buffer.buffer[tx_buffer.tail];
tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
LINDAT = c;
}
#endif
return 1;
}
HardwareSerial::operator bool() {
return true;
}
// Preinstantiate Objects //////////////////////////////////////////////////////
#if defined(UBRRH) && defined(UBRRL)
HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X);
#elif defined(UBRR0H) && defined(UBRR0L)
HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0);
#elif defined(LINBRRH)
HardwareSerial Serial(&rx_buffer, &tx_buffer);
#endif
#if defined(UBRR1H)
HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1);
#endif
#elif !USE_SOFTWARE_SERIAL
#warning There is no Hardware UART, and Sofware Serial is not enabled. There will be no serial port.
#endif // whole file
| [
"strange_orange_fish@hotmail.com"
] | strange_orange_fish@hotmail.com |
2adaf413dc17768b35673e00ed1e762b0209a4b7 | f5f02a9f733d293e828a038055b3c33548ac7f16 | /PlantsVsZombies/Plants/Files/Arena.h | 0e647506a7acd111fd15029407336a62bf4bf393 | [] | no_license | pawelsa/PlantsVsZombies-SFML | 19ed5caa50b184b728aa10e49b6cb7d1b38037a4 | 032ac6b8597db176f057aedf465532e5068d468f | refs/heads/master | 2020-03-22T14:54:23.860593 | 2018-07-09T01:06:01 | 2018-07-09T01:06:01 | 140,213,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,520 | h | #pragma once
#include <SFML/Graphics.hpp>
#include "Dimensions.h"
#include "CollisionDetector.h"
#include "Sun.h"
#include "Field.h"
#include "Textures.h"
#include "Mob.h"
#include "NutN.h"
#include "PeaN.h"
#include "PotatoN.h"
#include "SunflowerN.h"
extern Textures *allTextures;
class Arena {
Field *field;
Mob *plants[5][9];
Sun *sun;
void setPlantFieldToNULL() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 9; j++) {
plants[i][j] = NULL;
}
}
}
void displayPlantsAndAttack(sf::RenderWindow *window) {
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 9; x++) {
if (plants[y][x] != NULL) {
plants[y][x]->display(window);
plants[y][x]->attack();
}
}
}
}
void deleteMob(Point position) {
delete plants[position.x][position.y];
plants[position.x][position.y] = NULL;
}
public:
static enum PlantType {
PEA, SUNFLOWER, NUT, POTATO, NONE
};
Arena(Sun *sun) {
field = new Field(9, 5);
setPlantFieldToNULL();
this->sun = sun;
}
void nextFrame(sf::RenderWindow *window) {
field->display(window);
sun->display(window);
displayPlantsAndAttack(window);
}
bool createMob(PlantType type, Point position) {
if (!plants[position.y][position.x] == NULL)
return false;
switch (type) {
case PEA: {
plants[position.y][position.x] = new Pea(position);
return true;
}
case SUNFLOWER: {
plants[position.y][position.x] = new Sunflower(position, sun);
return true;
}
case NUT: {
plants[position.y][position.x] = new Nut(position);
return true;
}
case POTATO: {
plants[position.y][position.x] = new Potato(position);
return true;
}
}
return false;
}
std::vector<Mob*> returnRowOfPlants(int row) {
std::vector<Mob*> takenRow;
for (int x = 0; x < 9; x++) {
if (plants[row][x] != NULL) {
takenRow.push_back(plants[row][x]);
}
}
return takenRow;
}
void updatePlantsRow(std::vector<Mob*> plantsRow, int row) {
for (int x = 0; x < 9; x++) {
plants[row][x] = NULL;
}
for (Mob *plant : plantsRow) {
Point position = CollisionDetector::returnPositionOnArena(plant->returnPosition());
plants[position.y][position.x] = plant;
}
}
sf::FloatRect getBoundsOfMob(Point position) {
if (plants != NULL && plants[position.y][position.x] != NULL)
return plants[position.y][position.x]->returnFloatRect();
return sf::FloatRect();
}
bool isThereMob(Point position) {
return plants[position.x][position.y] == NULL ? false : true;
}
};
| [
"pawel.sapek97@gmail.com"
] | pawel.sapek97@gmail.com |
c3e561eacc2bb46da3026895257dd2f935d9d784 | 9e10da8d018bdccffa476f62f35a3de6f319a9bc | /Algorithm/Unsolved/hd_2.cpp | 474f65e6439bc166eaecf7d7f28186fff16c0e7b | [] | no_license | JinhaJjing/Algorithm | 0de05e82f5680546c6d4f61ee5bb3d50b455ec5d | b931dd9402e7f9a4f7bef34e9ab38bdf8c19d993 | refs/heads/master | 2023-04-01T15:27:17.564298 | 2021-04-16T08:49:37 | 2021-04-16T08:49:37 | 279,781,356 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 2,449 | cpp | // hd_2
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
/*
int solution(vector<string> ip_addrs, vector<string> langs, vector<int> scores) {
int good_participants=0;
vector<string>::iterator iter;
vector<string> ip;
for (int i = 0; i < langs.size(); i++) {
iter= find(ip.begin(), ip.end(), ip_addrs[i]);
if(iter==ip.end())
ip.push_back(ip_addrs[i]);
}
int size = ip.size();
int* count = new int[size]();
for (int i = 0; i < langs.size(); i++) {
for (int j = 0; j < ip.size(); j++) {
if (ip[j].compare(ip_addrs[i]) == 0)//같다
count[j] += 1;
}
}
int student = ip_addrs.size();
bool* students = new bool[student];
string language = "0";
for (int i = 0; i < ip.size(); i++) {
if (count[i] >= 4) {
for (int j = 0; j < ip_addrs.size(); j++) {
if (ip[i].compare(ip_addrs[j]) == 0)
students[j] = false;
}
}
else if (count[i] == 3) {
for (int j = 0; j < ip_addrs.size(); j++) {
if (ip[i].compare(ip_addrs[j]) == 0) {
if (language.compare("0"))
language = langs[j];
else if (language.compare(langs[j]) != 0)//다르면
}
}
}
}
delete[] count;
return good_participants;
}
*/
int solution(vector<string> ip_addrs, vector<string> langs, vector<int> scores) {
//조건1 : 같은IP4명이상 = 모두 부정
//조건2 : 같은IP3명&모두 같은 언어군 = 3명 부정
//조건3 : 같은IP2명&모두 같은 언어군&성적 동일 = 2명 부정
int answer = 0;
vector<string> language = { "C","C++","C#","Java","JavaScript","Python3" };
vector<int> ischeated(100000);
vector<vector<int>> sameIP(100000);
map<string, int> m;
for (int i = 0; i < ip_addrs.size(); i++) {
if (m.find(ip_addrs[i]) != m.end())
m[ip_addrs[i]]++;
}
for (int i = 0; i < ip_addrs.size(); i++) {
if (m[ip_addrs[i]] >= 4)
ischeated[i] = 1;
else if (m[ip_addrs[i]] == 3) {
}
else if (m[ip_addrs[i]] == 2) {
}
}
for (int i = 0; i < langs.size(); i++) {
if (ischeated[i]) answer++;
}
return answer;
}
int main() {
solution({ "5.5.5.5","155.123.124.111","10.16.125.0","155.123.124.111","5.5.5.5","155.123.124.111","10.16.125.0","10.16.125.0" }, { "Java","C++","Python3","C#","Java","C","Python3","JavaScript" }, { 264,197,373,45,294,62,373,373 });
solution({ "7.124.10.0","7.124.10.0","0.0.0.0","7.124.10.0","0.0.0.0","7.124.10.0" }, { "C++","Java","C#","C#","C","Python3" }, { 314,225,45,0,55,400 });
} | [
"horseesroh@naver.com"
] | horseesroh@naver.com |
8d8f58c4fbfb07dc69714d46b5b0bcf7d448c127 | e35c7ba0fc75ac48ed7aff6b2d3a02f662b486d6 | /src/Category.h | a8d2e869c97ede59374164dec7773adfb6cafcfc | [] | no_license | LinzhouLi/File-System | 93cec162cd18801594bccbcd6b216635165ba3e6 | 0004073fe0fac0a9f662eaaf9142752063bdc102 | refs/heads/main | 2023-06-02T01:13:08.607446 | 2021-06-19T14:41:42 | 2021-06-19T14:41:42 | 378,366,922 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,525 | h | #ifndef CATEGORY_H
#define CATEGORY_H
#include "VirtualDisk.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QStack>
class Node
{
public:
FCB* fcb;
Node* firstChild; // 左孩子
Node* nextBrother; // 右兄弟
Node* parent; // 父结点
Node(FCB*);
~Node();
};
class Category
{
private:
Node* root; // 目录根节点
QStack<QJsonArray*> arrStack; // 日志文件控制
QStack<QJsonObject*> objStack; // 日志文件控制
VirtualDisk* disk; // 磁盘类
void _WriteLog(Node* node, QJsonArray* brothers); // 写日志(递归)
void _ReadLog(Node* parentNode, QJsonArray* sons); // 读日志(递归)
void DeleteNode(Node* node); // 删除某单个结点即其在disk上的内容
void FreeCategory(Node* node); // 删除某结点的所有子结点与右兄弟结点(及其子结点) (递归)
public:
Category(Node* root, VirtualDisk* disk); // 初始化,需要传入根结点与disk类指针
~Category();
Node* GetRootNode() { return root; }
void Format(); // 格式化
Node* Search(Node* parentFolder, QString name, int type); // 搜索结点
void Create(Node* parentFolder, FCB* file); // 创建结点
void Delete(Node* parentFolder, QString name, int type); // 删除结点
bool UniqueName(Node* parentFolder, QString name, int type); // 判断文件名是否唯一
bool ReadLog(); // 读日志
bool WriteLog(); // 写日志
};
#endif // CATEGORY_H
| [
"LinzhouLi@outlook.com"
] | LinzhouLi@outlook.com |
1cdeee4d4c0a585bd677ebd43e1a754b5882272a | 550297a6789811cb094d03eb9a5b3e5d21dc41d2 | /main.cpp | 8f132171057a35629f202b2e8a52a1069a1bf7c8 | [] | no_license | Klaudia97b/Desktop | 7d32d96846ab121d41089778d7157c1a4911ab32 | 2580e91fc6dddea0a6c4192ebc923c80b386b070 | refs/heads/master | 2021-04-06T17:57:11.237590 | 2018-03-14T16:43:54 | 2018-03-14T16:43:54 | 125,249,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 428 | cpp | #include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
int i, suma=0;
for(i=10;i<=100;i++)
{
suma=suma+i;
cout << "Nr " << i << " Suma: " << suma << "\n";
}
cout << "10+20...+100+ = " << suma << "\n\n";
system("PAUSE");
return EXIT_SUCCESS;
}
| [
"37377054+Klaudia97b@users.noreply.github.com"
] | 37377054+Klaudia97b@users.noreply.github.com |
cc1da731273d4c16a61fe653e563534bb2360633 | b76c69999c18ab5fef2e145a185834359822b0d4 | /xmlparse/parser.cpp | f239c37c0e75f43916d86c36951a08aa4c97ac37 | [] | no_license | trol53/avsoft-intern-test-task | 1cd3b260414664404e0274e1124b2a2aae3b99f9 | 0fb50bcce8f816da5d3f686ad18e9e7c8df419b6 | refs/heads/main | 2023-07-28T01:04:51.706500 | 2021-09-15T12:34:15 | 2021-09-15T12:34:15 | 401,250,324 | 0 | 0 | null | 2021-09-15T12:34:16 | 2021-08-30T07:12:52 | C++ | UTF-8 | C++ | false | false | 3,372 | cpp | #include "headers/parser.h"
void Parser::Save(std::string& file_name, std::map <Department, std::vector<Employment>>& new_dict){
std::ofstream file(file_name);
file << "<departments>\n";
for (auto node : new_dict){
file << "\t" << dep_head << node.first.name << "\">\n";
file << "\t\t<employments>\n";
for (auto employ : node.second){
file << "\t\t\t" << empl_head << '\n';
employ.save(file);
file << "\t\t\t" << empl_tail << '\n';
}
file << "\t\t</employments>\n";
file << "\t" << dep_tail << '\n';
}
file << "</departments>\n";
}
std::map <Department, std::vector<Employment>> Parser::Load(std::string& file_name){
std::ifstream file(file_name);
if (!file.is_open()){
std::cout << "file not open\n";
return dict;
}
std::string line;
while (getline(file, line)){
line = delete_space(line);
if (line == "<departments>")
continue;
if (line == "</departments>"){
file.close();
return dict;
}
if (dep_head_comp(line)){
std::string name = get_dep_name(line);
Department dep(name);
add_employments(dep, file);
}
line.clear();
}
file.close();
return dict;
}
std::string Parser::delete_space(const std::string& str){
auto iter_b = str.begin();
for (;;iter_b++){
if (*iter_b != ' ' && *iter_b != '\t' && *iter_b != '\r')
break;
}
auto iter_e = str.end();
iter_e--;
for (;;iter_e--){
if (*iter_e != ' ' && *iter_e != '\t' && *iter_e != '\r')
break;
}
std::string res(iter_b, iter_e + 1);
// std::cout << int(res.back());
// res.pop_back();
return res;
}
bool Parser::dep_head_comp(const std::string& str){
if (std::string(str.begin(), str.begin() + 18) == dep_head)
return true;
return false;
}
std::string Parser::get_dep_name(std::string& line){
return std::string(line.begin() + 18, line.end() - 2);
}
void Parser::add_employments(Department dep, std::ifstream& file){
std::vector<Employment> tmp;
for (std::string line; std::getline(file, line);){
line = delete_space(line);
if (line == "<employments>")
continue;
if (line == "</employments>")
break;
if (line == empl_head){
tmp.push_back(add_employment(dep, file));
}
if (line == empl_tail){
continue;
}
}
dep.employments_count = tmp.size();
for (Employment employ : tmp){
dep.average_salary += employ.salary;
}
dep.average_salary /= static_cast<double>(dep.employments_count);
dict.insert({dep, tmp});
}
Employment Parser::add_employment(Department& dep, std::ifstream& file){
std::string line;
Employment employ;
employ.last_name = get_data(file, 9);
employ.first_name = get_data(file, 6);
employ.middle_name = get_data(file, 12);
employ.function = get_data(file, 10);
employ.salary = std::atoi(get_data(file, 8).c_str());
return employ;
}
std::string Parser::get_data(std::ifstream& file, int step){
std::string line;
std::getline(file, line);
line = delete_space(line);
return std::string(line.begin() + step, line.end() - step - 1);
}
| [
"trol53.nek@gmail.com"
] | trol53.nek@gmail.com |
0305760d60d344c2181c2b8491568eaa554fdd65 | 2c6068337b7c49e92901033ab7d023d85dd2fbad | /cpp/36.cpp | 9fdd0d0576d82651c980bbafb9bc5963ddf1fb13 | [] | no_license | r-c-s/projecteuler | c7abd3a3b9e0045ac7b66b6db472992abb6c025d | 44cbb0bea7cf4a2e7d739f2117cff36808a80d7e | refs/heads/master | 2020-05-18T00:44:37.907693 | 2018-05-05T17:00:00 | 2018-05-05T17:00:00 | 35,506,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cpp | /*
#------------------------------------------------------------------------------
# PROJECT EULER
# PROBLEM 36
#------------------------------------------------------------------------------
# The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
#
# Find the sum of all numbers, less than one million, which are palindromic in
# base 10 and base 2.
#
# (Please note that the palindromic number, in either base, may not include
# leading zeros.)
#------------------------------------------------------------------------------
# SOLUTION: 872187
#------------------------------------------------------------------------------
*/
#include <iostream>
#include <sstream>
using namespace std;
string reverse(string);
bool isPalindromicB10(int);
bool isPalindromicB2(int);
string toBinary(int);
string toString(int);
int main(){
int sum = 0;
for(int i = 1; i < 1000000; i++){
if(isPalindromicB10(i) && isPalindromicB2(i)) sum += i;
}
cout << sum << endl;
return 0;
}
string reverse(string s){
string r = "";
for(int i = s.length()-1; i >= 0; i--){
r += s[i];
}
return r;
}
bool isPalindromicB10(int n){
return toString(n) == reverse(toString(n));
}
bool isPalindromicB2(int n){
return toBinary(n) == reverse(toBinary(n));
}
string toString(int n){
stringstream s;
s << n;
return s.str();
}
string toBinary(int n){
string b = "";
while(n > 0){
if(n % 2 == 1) b+= "1";
else b += "0";
n /= 2;
}
return b;
}
| [
"raphaelcorreaesilva@gmail.com"
] | raphaelcorreaesilva@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.