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 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
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 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ae2ba30b43b998c05180e85e3ab8fb5ae29566cf | 30d4903c89cd6653b3de77e339000beaed1afcd9 | /op_sol2.cpp | 008e3155b10667bb18f5104a54de6c44228d3c6e | [] | no_license | mgalang229/LeetCode-Search-Insert-Position | ba78336f63399e47e04679e4713938637911aca7 | 0af2fbe1d72efec3bbbda2b6ba8066e76354524b | refs/heads/main | 2023-02-05T21:16:20.172625 | 2020-12-28T13:22:28 | 2020-12-28T13:22:28 | 325,015,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 205 | cpp | class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
// using lower_bound() function
return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
}
};
| [
"noreply@github.com"
] | mgalang229.noreply@github.com |
bcb965aa4fd0ec64872e656f72201a07c0d2f5de | 1ef627be7b987c195f8201f1a75d7f8ea2fbd102 | /arreglos/8c.cpp | 4866c4a5cc963c8ca0594db3e8138672a2c21f3b | [] | no_license | Alberto-Arias-x64/Segundo_cpp | bf0dfd35cd160a95a95058352619677f6693b5ff | 4170ea47d45dbd9c7bff325f1a4e5140dd7e2d80 | refs/heads/main | 2023-05-04T01:53:36.600725 | 2021-05-28T00:00:51 | 2021-05-28T00:00:51 | 371,406,211 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | cpp | #include<iostream>
#include<math.h>
using namespace std;
main()
{
int fmax[10],n,x;
int i;
n=999;
for(i=1;i<=10;i++)
{
cout<<"ingrese el numero #"<<i<<" ";
cin>>fmax[i];
if(fmax[i]<n)
{
n=fmax[i];
x=i;
}
}
cout<<"el numero menor es "<<n<<endl;
cout<<"este es el elemento numero #"<<x<<" en la lista de numeros";
}
| [
"yugipoi@gmail.com"
] | yugipoi@gmail.com |
343fa8dc5a9d8a6de718da7cbf7e1a4afbdbbd26 | f7c82f2621c3cdb8d51b0a2c094038fe14b78c98 | /sem2/class Complex.cpp | 64b0a17dfb779f43f9bc29ba7553fc00b86da70f | [] | no_license | IslamKyrre/MyAlgorithmsAndDataStructures | 58a54d5b1d122b204ece21ddd3150776e944b5c1 | 4114c94c68f640fb9487c1561978a78fc40ac610 | refs/heads/main | 2023-03-29T04:06:59.186894 | 2021-03-31T11:50:49 | 2021-03-31T11:50:49 | 353,335,411 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,233 | cpp | class C {
public:
double re, im;
double abs() {
return sqrt(re * re + im * im);
}
C() : re(0), im(0) {};
C(double re, double im) : re(re), im(im) {};
explicit C(double re) : re(re), im(0) {};
C(const C &x) {
re = x.re;
im = x.im;
}
};
C operator+(const C &a, const C &b) {
C sum = C(a.re + b.re, a.im + b.im);
return sum;
}
C operator-(const C &a, const C &b) {
C sub = C(a.re - b.re, a.im - b.im);
return sub;
}
C operator*(const C &a, const C &b) {
C mul = C(a.re * b.re - a.im * b.im, a.im * b.re + a.re * b.im);
return mul;
}
C operator/(const C &a, const C &b) {
C div = C((a.re * b.re + a.im * b.im) / (b.re * b.re + b.im * b.im),
(a.im * b.re - a.re * b.im) / (b.re * b.re + b.im * b.im));
return div;
}
bool operator==(const C &a, const C &b) {
return a.re == b.re && a.im == b.im;
}
bool operator!=(const C &a, const C &b) {
return !(a == b);
}
/****************/
C operator+(const double &aa, const C &b) {
C a = C(aa);
return a + b;
}
C operator+(const C &a, const double &bb) {
C b = C(bb);
return a + b;
}
C operator-(const double &aa, const C &b) {
C a = C(aa);
return a - b;
}
C operator-(const C &a, const double &bb) {
C b = C(bb);
return a - b;
}
C operator*(const double &aa, const C &b) {
C a = C(aa);
return a * b;
}
C operator*(const C &a, const double &bb) {
C b = C(bb);
return a * b;
}
C operator/(const double &aa, const C &b) {
C a = C(aa);
return a / b;
}
C operator/(const C &a, const double &bb) {
C b = C(bb);
return a / b;
}
bool operator==(const double &aa, const C &b) {
C a = C(aa);
return a == b;
}
bool operator==(const C &a, const double &bb) {
C b = C(bb);
return a == b;
}
bool operator!=(const double &aa, const C &b) {
C a = C(aa);
return a != b;
}
bool operator!=(const C &a, const double &bb) {
C b = C(bb);
return a != b;
}
/*****/
ostream &operator<<(ostream &out, const C &x) {
cout << x.re << " " << x.im << endl;
return out;
} | [
"noreply@github.com"
] | IslamKyrre.noreply@github.com |
c9e2fda72504009b2c7dc7b92e8ccd633bc8b051 | 1c34dce890845531443f50c309cb14b8803ad1ce | /CHC_Thesis.cxx | 9c42dd167e14759ae5f74d093df9b3d61041ca19 | [] | no_license | kbeick/CHC_Thesis | 703c93b28f42760d13e3013c1a533df71bb12b5b | 66e74f0a6ffe9391a3715a5c776cca96b81b4290 | refs/heads/master | 2021-01-19T20:21:52.114885 | 2014-12-11T03:19:16 | 2014-12-11T03:19:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,603 | cxx | // Kevin Beick's Clark Honors College Thesis Project - 2014
// Author: Kevin Beick
/* Main.cxx
- Run command line interface
- Set parameters
- Construct BVH
- Ray Tracing
- streams evaluation data
- produce image file
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <vtkDataSet.h>
#include <vtkImageData.h>
#include <vtkPNGWriter.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPoints.h>
#include <vtkUnsignedCharArray.h>
#include <vtkFloatArray.h>
#include <vtkCellArray.h>
#include <vtkImageCast.h>
#include <numeric>
#include <cmath>
#include <vector>
#include <string>
#include "globals.h"
#include "BVH.h"
#include "BVH_BottomUpConstructor.h"
#include "BVH_TopDownConstructor.h"
#include "BBox.h"
#include "Ray.h"
#include "Shading.h"
#include "Triangle.h"
#include "utils.h"
#include "objLoader.h"
#include "Stopwatch.h"
#include "Camera.h"
using std::cerr;
using std::cout;
using std::endl;
/* ----------------------------------------------------------------------------- */
/* ---------- PARAMETERIZATION ---------- */
/* ----------------------------------------------------------------------------- */
void
print_params()
{
cerr << "~~~~read in params:" << endl;
cerr << "~~~~constr method is: " << construction_method << endl;
cerr << "~~~~got camera pos: " << campos[0] << ", " << campos[1] << ", " << campos[2] << endl;
}
int
SetConstructionMethod(char* input)
{
int construction_method = -1;
if(strcmp(input, "td")==0) construction_method = TOPDOWN;
else if(strcmp(input, "bu")==0) construction_method = BOTTOMUP;
else{
// cerr << input << endl;
throw std::invalid_argument( "ERROR: Construction method must be either td or bu (top down or bottom up)\n" );
}
return construction_method;
}
Camera*
SetUpCamera()
{
Camera *c = new Camera();
c->near = 1;
c->far = 200;
c->angle = M_PI/6;
c->focus = new Vec3f(0,0,0);
c->up = new Vec3f(0,-1,0);
return c;
}
/* ----------------------------------------------------------------------------- */
/* ---------- IMAGE PRODUCTION ---------- */
/* ----------------------------------------------------------------------------- */
class Screen
{
public:
unsigned char *buffer;
double *depthBuffer;
int width, height;
// return the element number of buffer corresponding to pixel at (c,r)
int pixel(int c, int r){
return 3*( (IMAGE_WIDTH*r)+c );
}
};
vtkImageData *
NewImage(int width, int height)
{
vtkImageData *image = vtkImageData::New();
image->SetDimensions(width, height, 1);
image->SetWholeExtent(0, width-1, 0, height-1, 0, 0);
image->SetUpdateExtent(0, width-1, 0, height-1, 0, 0);
image->SetNumberOfScalarComponents(3);
image->SetScalarType(VTK_UNSIGNED_CHAR);
image->AllocateScalars();
return image;
}
void
WriteImage(vtkImageData *img, const char *filename)
{
std::string full_filename = filename;
full_filename += ".png";
vtkPNGWriter *writer = vtkPNGWriter::New();
writer->SetInput(img);
writer->SetFileName(full_filename.c_str());
writer->Write();
writer->Delete();
}
/* ----------------------------------------------------------------------------- */
/* ---------- MAIN ---------- */
/* ----------------------------------------------------------------------------- */
int main(int argc, char** argv)
{
Stopwatch* stopwatch = new Stopwatch();
/* PREFATORY DATA LOG STUFF */
ofstream data_log;
data_log.open("log_data_output_-_3.txt", ios_base::app);
data_log << "___________________________________\n";
data_log << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
/* SET UP CAMERA */
c = SetUpCamera();
/* HANDLE AND SET PARAMETERS */
if (argc != 9 && argc != 10){ cerr << USAGE_MSG; exit(0);}
cerr << "PROCESSING " << argv[1] << endl;
try{
objReader = new ObjReader(argv[1]);
branching_factor = atoi( argv[2] );
construction_method = SetConstructionMethod(argv[3]);
c->position = new Vec3f(atof(argv[4]),atof(argv[5]),atof(argv[6]));
depthOfTrace = atof(argv[7]);
opacity = atof(argv[8]);
}catch (const std::exception &exc){
// catch anything thrown within try block that derives from std::exception
std::cerr << exc.what();
cerr << USAGE_MSG;
exit(0);
}
data_log << "File: " << argv[1] <<
" Branching Factor: " << branching_factor <<
" Constr Method: " << argv[3] <<
" Campos: " << *c->position <<
" Depth of Trace: " << depthOfTrace <<
" Opacity: " << opacity <<
endl;
char *outFileName;
if(argv[9]){ outFileName = argv[9]; }
else{ outFileName = (char*)"myOutput"; }
EMPTY_NODE_BBOX = new BBox(*c->position * 1.1, *c->position * 1.1);
vtkImageData *image;
Screen* screen = new Screen;
if (PRODUCE_IMAGE){
image = NewImage(IMAGE_WIDTH, IMAGE_HEIGHT);
unsigned char *buffer =
(unsigned char *) image->GetScalarPointer(0,0,0);
int npixels = IMAGE_WIDTH*IMAGE_HEIGHT;
//Initialize buffer to be all black
for (int i = 0 ; i < npixels*3 ; i++)
buffer[i] = 0;
screen->buffer = buffer;
screen->width = IMAGE_WIDTH;
screen->height = IMAGE_HEIGHT;
}
/* GET RAW DATA FROM objReader */
objReader->extractNormals();
numTriangles = objReader->totalTriangles;
data_log << "NUMBER OF TRIANGLES: " << numTriangles << endl;
float* verts;
float* normals;
objReader->getRawData(verts, normals);
tris = new Triangle[numTriangles];
CreateTriangleArray(tris, numTriangles, verts, normals);
/* INITIALIZE BVH */
BVH_Node *root = new BVH_Node();
root->id = 0;
root->parent = NULL;
/* START TIMER */
stopwatch->reset();
/* CALL SPECIFIED BVH CONSTRUCTOR */
if (construction_method == TOPDOWN){
BuildBVH_topdown(tris, root, root->parent, numTriangles, 0);
}
else if (construction_method == BOTTOMUP){
BuildBVH_bottomup(tris, &root, numTriangles);
if(branching_factor!=2){ BVH_Bottomup_Collapser(root); }
}
data_log << "BUILD TIME " << stopwatch->read() << endl;
//cerr << "\nFINISHED BUILDING TREE " << (construction_method == TOPDOWN ? "top down" : "bottom up" ) << endl;
/* GENERATE FLAT ARRAY REP OF BVH */
int flat_array_len;
flat_array = bvhToFlatArray(root, &flat_array_len, branching_factor);
// cerr << "flat_array_len " << flat_array_len << endl;
/* PRINT FLAT ARRAY TO COMMAND LINE */
// for(int a=0; a<flat_array_len; a++){
// if(flat_array[a]==LEAF_FLAG){ cerr << "idx " << a << ": "; }
// cerr << flat_array[a] << endl;
// }
/* ----------------------------------------------------------------------------- */
/* ---------- DO RAY TRACING ---------- */
/* ----------------------------------------------------------------------------- */
printf("\n~~~~~~ RAY TRACING ~~~~~~\n");
int npixels = IMAGE_WIDTH*IMAGE_HEIGHT;
double traversal_times[npixels];
std::vector<int> node_visit_data (npixels, 0);
/* PREP WORK */
Ray* look = RayFromPoints(*c->position, *c->focus);
Vec3f* u = crossProductNormalized(look->unitDir, *c->up);
Vec3f* v = crossProductNormalized(look->unitDir, *u);
Vec3f x = (*u) * (2*tan((c->angle)/2)/IMAGE_WIDTH);
Vec3f y = (*v) * (2*tan((c->angle)/2)/IMAGE_HEIGHT);
/* FOR EACH PIXEL... */
for (int h = 0; h < IMAGE_HEIGHT; h++) {
for (int w = 0; w < IMAGE_WIDTH; w++) {
int pixel = screen->pixel(w,h);
Vec3f x_comp = x*((2*w+1-IMAGE_WIDTH)/2);
Vec3f y_comp = y*((2*h+1-IMAGE_HEIGHT)/2);
/* ---- CALCULATE THE RAY FROM CAMERA TO PIXEL ---- */
Vec3f rayVector = look->unitDir + x_comp + y_comp;
Ray* curRay = new Ray(*c->position, rayVector);
// cerr << "\n\npixel " << w << "," << h << " :: ";
/* ---- TRAVERSE THE BVH ---- */
Vec3f* color = new Vec3f(0,0,0); /* Pixel Color */
stopwatch->reset(); /* Start Timer */
traverseFlatArray(flat_array, 0, curRay, color, depthOfTrace, &node_visit_data[pixel/3]);
/* Record Traversal Time */
traversal_times[w*IMAGE_HEIGHT + h] = stopwatch->read();
// cerr << "traversal complete" <<endl;
if(PRODUCE_IMAGE){
// Assign colors to pixel
screen->buffer[pixel] = color->x;
screen->buffer[pixel+1] = color->y;
screen->buffer[pixel+2] = color->z;
}
delete color;
delete curRay;
}
}
/* LOG EVAL METRICS TO DATA FILE */
double avg_time = std::accumulate(traversal_times,traversal_times+npixels,0.0) / npixels;
data_log << "AVG TRAVERSAL TIME PER PIXEL: " << avg_time << endl;
double avg_num_visits = std::accumulate(node_visit_data.begin(),node_visit_data.end(),0.0) / npixels;
data_log << "AVG # NODES VISTED PER PIXEL: " << avg_num_visits << endl;
if(construction_method == BOTTOMUP){
data_log << "AVG # CHILDREN PER INNER NODE: " << (double)branching_factor - ((double)emptyNodeCount/(double)inner_node_counter) << endl;
}
if( PRODUCE_IMAGE ) WriteImage(image, outFileName) ;
data_log.close();
} | [
"kbeick@zoho.com"
] | kbeick@zoho.com |
bcdbf2b3dca2211c32223e631c780aa087af4346 | 29a4c1e436bc90deaaf7711e468154597fc379b7 | /modules/reduction/include/nt2/toolbox/reduction/function/second.hpp | 1bd06b9b8b93d0359bbfee9e17a238e88a3aa446 | [
"BSL-1.0"
] | permissive | brycelelbach/nt2 | 31bdde2338ebcaa24bb76f542bd0778a620f8e7c | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | refs/heads/master | 2021-01-17T12:41:35.021457 | 2011-04-03T17:37:15 | 2011-04-03T17:37:15 | 1,263,345 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | hpp | //////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_REDUCTION_FUNCTION_SECOND_HPP_INCLUDED
#define NT2_TOOLBOX_REDUCTION_FUNCTION_SECOND_HPP_INCLUDED
#include <nt2/include/simd.hpp>
#include <nt2/include/functor.hpp>
#include <nt2/toolbox/reduction/include.hpp>
namespace nt2 { namespace tag
{
struct second_ {};
}
NT2_FUNCTION_IMPLEMENTATION(tag::second_, second, 1)
}
#include <nt2/toolbox/reduction/function/scalar/second.hpp>
#include NT2_REDUCTION_INCLUDE(second.hpp)
#endif
// modified by jt the 25/12/2010 | [
"jtlapreste@gmail.com"
] | jtlapreste@gmail.com |
d9136c404d12cf09747d66845420feae5a71da28 | 7a7c54ff72cfcb42d1c47f69662820e999775e8f | /c++/232.cpp | 0f2a69cc09303e53f6e3d5b814a37a09c050cea8 | [] | no_license | manito-ming/leetcode | d46da165db835de4c98b2153a4f451ec88e965c2 | 709b482866d86febf242ed56daab5244f4587c98 | refs/heads/master | 2020-04-10T15:17:30.187074 | 2019-03-07T16:10:29 | 2019-03-07T16:10:29 | 161,104,459 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,114 | cpp | #include <iostream>
#include <queue>
#include <vector>
#include <stack>
using namespace std;
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
p.push(x);
}
//获得队首元素的时候,必须先将栈反转,把先进入的元素放在栈顶,这样就符合了队列的先进先出
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (q.empty()) {
while (!p.empty()) {
q.push(p.top());
p.pop();
}
}
int x= q.top();
q.pop();
return x;
}
/** Get the front element. */
int peek() {
if (q.empty()) {
while (!p.empty()) {
q.push(p.top());
p.pop();
}
}
return q.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return p.empty()&&q.empty();
}
private:
stack<int>p,q;
};
int main() {
return 0;
} | [
"1315915230@qq.com"
] | 1315915230@qq.com |
7450ef5d7da5c56e448a9cf69fa3dd89c9b86c91 | 72e59a47eb012891b84b10f9b1bd738f02aa5a9a | /ESEMPI_rseba/STRUCT/prova.cc | 3c0fae93c3e8c6eff3f6e0b81d370bd1f4038504 | [] | no_license | Leonelli/C-plus-plus-works | 8a366f9716284ef804de5c707c5a0904afb217a7 | f4a9971b5391d5864ffcf208a2845c4a224969fe | refs/heads/master | 2020-03-29T17:22:53.737281 | 2019-02-13T16:50:48 | 2019-02-13T16:50:48 | 150,159,156 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | cc | using namespace std;
#include <iostream>
#include <cstring>
const int Nmax = 1000;
struct myarray {
double v[Nmax];
int nelem;
};
double somma (myarray a,int n) {
double res;
if (n==0)
res = a.v[0];
else
res = a.v[n]+somma(a,n-1);
return res;
}
int main () {
myarray a;
// inizializza Myarray
a.nelem=Nmax;
for (int i=0;i<a.nelem;i++) {
a.v[i]=double(i+1.0);
}
cout << "La somma degli elementi dell'array e' " << somma(a,a.nelem-1) << endl;
}
| [
"matteoleonelli99@gmail.com"
] | matteoleonelli99@gmail.com |
65c8518a962fe7fec909d4c1f8cd3ffce23e505b | a7e694066b97d02bd74bc7562d80992837e2ce8b | /Exp13(DFS).cpp | 093c51112ccd5116b6b23a62cd836d501baa8ef7 | [] | no_license | jatinrai/DS-FILE-2018-19 | 7562f4f8bf57ae51111542420015bc8e63868f85 | efde4ffff573ac17f092cfee48f88181c03422d1 | refs/heads/master | 2020-04-01T11:18:47.037343 | 2018-11-14T15:54:43 | 2018-11-14T15:54:43 | 153,156,664 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 665 | cpp | /* Program including all Operations on Graph and illustrate the traversals using DFS and BFS */
using namespace std;
int main(){
int m,n,k,i,j,g[50][50],stack[50],top=-1,visit[50],visited[50],v;
cout<<"enter the vertices"<<endl;
cin>>n;
cout<<"enter the edges"<<endl;
cin>>m;
for(k=1;k<=m;k++){
cout<<"enter the source and destination"<<endl;
cin>>i>>j;
g[i][j]=1;
}
cout<<"enter the source vertex"<<endl;
cin>>v;
cout<<v<<" ";
k=1;
while(k<n){
for (int j=n;j>=1;j--){
if((g[v][j]==1) && visited[j]!=1 && visit[j]!=1){
visit[j]=1;
stack[++top]=j;
}
}
v=stack[top--];
cout<<v<<" ";
k++;
visit[v]=0;
visited[v]=0;
}
}
| [
"noreply@github.com"
] | jatinrai.noreply@github.com |
5de5c136681f1a29ba49125753376e83b858dcc1 | 239994fd79fdec7a4184db3e230828b8347dd997 | /Frost/Vector2f.h | 8eea3b31e974de69e4642790014c69a5b0d48ef3 | [] | no_license | ClericX/Projects | bd0944c6994658b539b61ae90580ee0db440f84c | 9c705315cb16d42a0116f88f156fb748ca46ccfc | refs/heads/master | 2021-01-01T19:42:21.981590 | 2013-03-16T15:49:00 | 2013-03-16T15:49:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 186 | h | #pragma once
#include "DLL.h"
class FROSTAPI Vector2f
{
public:
float x;
float y;
Vector2f(void);
Vector2f(float _x, float _y);
void Set(float _x, float _y);
~Vector2f(void);
}; | [
"clericx@clericx.net"
] | clericx@clericx.net |
cb24f1981bb5642106dfe3259fa696823b846051 | 3fd747b340e5ea8c59ac733abd335c5d033cf812 | /src/gui/daq/coord.h | 2c6d712cc855a318c3f4d970e27f02cf4513cd5e | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | hgamber/qpx-gamma | dd6e2817d744d1415d9022c3f70272f8ad43dfd6 | 4af4dd783e618074791674a018a3ba21c9b9aab1 | refs/heads/master | 2021-10-27T11:50:46.578617 | 2019-04-17T01:24:07 | 2019-04-17T01:24:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,554 | h | /*******************************************************************************
*
* This software was developed at the National Institute of Standards and
* Technology (NIST) by employees of the Federal Government in the course
* of their official duties. Pursuant to title 17 Section 105 of the
* United States Code, this software is not subject to copyright protection
* and is in the public domain. NIST assumes no responsibility whatsoever for
* its use by other parties, and makes no guarantees, expressed or implied,
* about its quality, reliability, or any other characteristic.
*
* Author(s):
* Martin Shetty (NIST)
*
* Description:
* Marker - for marking a channel or energt in a plot
*
******************************************************************************/
#pragma once
#include "calibration.h"
class Coord {
public:
Coord() : bits_(0), energy_(nan("")), bin_(nan("")) {}
void set_energy(double nrg, Qpx::Calibration cali);
void set_bin(double bin, uint16_t bits, Qpx::Calibration cali);
uint16_t bits() const {return bits_;}
double energy() const;
double bin(const uint16_t to_bits) const;
bool null() { return ((bits_ == 0) && std::isnan(bin_) && std::isnan(energy_) ); }
bool operator!= (const Coord& other) const { return (!operator==(other)); }
bool operator== (const Coord& other) const {
if (energy_ != other.energy_) return false;
if (bin(bits_) != other.bin(bits_)) return false;
return true;
}
private:
double energy_;
double bin_;
uint16_t bits_;
};
| [
"martukas@gmail.com"
] | martukas@gmail.com |
cd558d89ecce96dfdd7c48e05f0d17fb75383feb | 8a2fb4d3076f008db245efae540041fc3eace4d6 | /HawkUtil/HawkWebSocket.h | 9197fdb476c0b0a3738b147b53d5dd18b37dd04f | [] | no_license | hawkproject/hawkproject | f536953ef6df199b2b93cee5672fa4a4cca23c36 | e781fd463f24e5a4c54cbd8c2bf34f4d36906ae4 | refs/heads/master | 2021-01-22T09:26:32.063606 | 2014-07-23T10:22:43 | 2014-07-23T10:22:43 | 13,612,604 | 6 | 5 | null | null | null | null | GB18030 | C++ | false | false | 995 | h | #ifndef HAWK_WEBSOCKET_H
#define HAWK_WEBSOCKET_H
#include "HawkSocket.h"
#include "HawkOctetsStream.h"
namespace Hawk
{
/************************************************************************/
/* WebSocket封装 */
/************************************************************************/
class UTIL_API HawkWebSocket : public HawkSocket
{
public:
//构造
HawkWebSocket();
//析构
virtual ~HawkWebSocket();
public:
//握手协议生成(依据请求信息生成握手的相应信息)
static Bool HandShake(const OctetsStream* pHttpReq, OctetsStream* pHttpRep);
protected:
//获取Sec-WebSocket-Key("Sec-WebSocket-Key1: " | "Sec-WebSocket-Key2: ")
static Bool GetSecWebSocketKey(const OctetsStream* pHttpReq, const AString& sKeyType, AString& sSecKey, UChar cFlag = '\r');
//获取8-byte security key
static Bool Get8ByteSecurityKey(const OctetsStream* pHttpReq, UChar* pSecKey);
};
}
#endif
| [
"380269273@qq.com"
] | 380269273@qq.com |
02bb95f36eb22eaff025a7f9a8a6ef48feb004de | 1d64c085dd71c84689768a9aa3aa9a0c7c40548f | /games/my_read.cpp | c392523c8b8ee164f0eb77fb04f0b5f71cf82861 | [
"MIT"
] | permissive | NicolasG31/cpp_arcade | a5265dc699e9e8a22828577cbea3f39f3108cb4e | c6a9dc54ed10ea5300d7bf972c5ee2bee2e58116 | refs/heads/master | 2022-06-04T11:01:36.810774 | 2019-05-10T10:24:17 | 2019-05-10T10:24:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | //
// my_read.cpp for in /home/doremi/rendu/cpp/cpp_arcade/games
//
// Made by Guillaume
// Login <doremi@epitech.net>
//
// Started on Tue Apr 4 13:18:09 2017 Guillaume
// Last update Tue Apr 4 13:29:42 2017 Guillaume
//
#include "my_read.hpp"
my_read::my_read()
{
}
my_read::~my_read()
{
}
int my_read::my_read_mouli(int fd, void *core, long size)
{
return (read(fd, core, size));
}
int my_read::my_write_mouli(int fd, void *core, long size)
{
return (write(fd, core, size));
}
| [
"nicolas.guillon@epitech.eu"
] | nicolas.guillon@epitech.eu |
a028f3bc61b8a49a132f039d86baeb7634a33862 | 6e9b20902f4e232d12e865f192ea5128ae253ba7 | /Fluid/2.1/pointDisplacement | d618c0c834cfb708698a96cec31c72db046ddefe | [] | no_license | abarcaortega/FSI_3 | 1de5ed06ca7731016e5136820aecdc0a74042723 | 016638757f56e7b8b33af4a1af8e0635b88ffbbc | refs/heads/master | 2020-08-03T22:28:04.707884 | 2019-09-30T16:33:31 | 2019-09-30T16:33:31 | 211,905,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,260 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: dev
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class pointVectorField;
location "2.1";
object pointDisplacement;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 0 0 0 0 0];
internalField uniform (0 0 0);
boundaryField
{
inlet
{
type fixedValue;
value uniform (0 0 0);
}
outlet
{
type fixedValue;
value uniform (0 0 0);
}
flap
{
type fixedValue;
value uniform (0 0 0);
}
upperWall
{
type slip;
}
lowerWall
{
type slip;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"aldo.abarca.ortega@gmail.com"
] | aldo.abarca.ortega@gmail.com | |
0d5d503d08603d1e6c0b6f23fe90cc60c2326b85 | c2658b5a3b4e00d836287f22e47af2f4241278bd | /Fraction/Fraction.h | 3b2021ebb89e6c160a004c1a8e36d076c7ac9d5e | [] | no_license | ahmad1598/C-plus-plus | 2fdeac3686e5d33bb46b27968816194369cca816 | 25fb17f62abe946064500eb55839507b6fc5623c | refs/heads/master | 2020-04-27T04:59:58.091937 | 2019-03-06T06:39:23 | 2019-03-06T06:39:23 | 174,070,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | h | /*****************************************
*
* Project : M5 - Fraction Class
* File : Fraction.h
* Name : Ahmad Rasoulpour
* Professor : Robert Baird
* Date : 07 / 06 / 18
******************************************/
class Fraction
{
friend Fraction operator+(const Fraction& f1, const Fraction& f2);
friend Fraction operator-(const Fraction& f1, const Fraction& f2);
friend Fraction operator*(const Fraction& f1, const Fraction& f2);
friend Fraction operator/(const Fraction& f1, const Fraction& f2);
public:
Fraction(); // Set numerator = 1, denominator = 1.
Fraction(int n, int d=1); // constructor with parameters
// acts as conversion constructor
// standard input/output routines
void Input(); // input a fraction from keyboard.
void Show() const; // Display a fraction on screen
// accessors
int GetNumerator() const;
int GetDenominator() const;
// mutator
bool SetValue(int n, int d=1); // set the fraction's value through parameters
double Evaluate() const; // Return the decimal value of a fraction
private:
int numerator; // may be any integer
int denominator; // should always be positive
};
| [
"ahmad.raman83@yahoo.com"
] | ahmad.raman83@yahoo.com |
e5aacfe0c12881506d801e034d5e9d3b51538ef0 | 5b9a1720d88be1ba9b18a0adb2d0ac2bd76c5e42 | /Coba-coba/Code 5.cpp | 5925dc92b81b19f5fa3b1f15e2fcd08b25898878 | [] | no_license | asianjack19/Cpp | 7affaa765c5e5b246e21e4b9df239334362ca470 | acc2cac32921fff56c8d76a43d18ba740a9ed26f | refs/heads/master | 2023-08-14T15:33:29.487550 | 2021-09-18T10:58:27 | 2021-09-18T10:58:27 | 378,959,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155 | cpp | #include <stdio.h>
#include <stdlib.h>
int main() {
char line[0];
gets (line);
printf("Hello,World\n");
printf("%s",line);
return 0;
}
| [
"michaeladriel080801@gmail.com"
] | michaeladriel080801@gmail.com |
0340fd2ab349815015527bdf694a041b86f88d3d | cf7537721caf499b46be56b9932fabb4500b2274 | /include/GCutG.h | ca63b691f0b875fb92bbd0679026b1696c2a29bc | [] | no_license | placebosarah/GRUTinizer | f95c2a93ffb2f55f4a96e28037ecfc019144dddd | 62b1156c6bd39d3bb80283e479f7a6968149a550 | refs/heads/master | 2021-01-11T10:59:45.819686 | 2016-11-02T19:47:30 | 2016-11-02T19:47:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,055 | h | #ifndef GCUTG_H_
#define GCUTG_H_
#include <TCutG.h>
#include <TClass.h>
#include <TString.h>
class GCutG : public TCutG {
public:
GCutG() : TCutG() { }
GCutG(const TCutG &cutg) : TCutG(cutg) { }
GCutG(const char *name,Int_t n=0) : TCutG(name,n) { }
GCutG(const char *name,Int_t n,const Float_t *x,const Float_t *y) : TCutG(name,n,x,y) { }
GCutG(const char *name,Int_t n,const Double_t *x,const Double_t *y) : TCutG(name,n,x,y) { }
~GCutG() { }
virtual void Print(Option_t *opt="") const;
int SaveTo(const char *cutname="",const char* filename="",Option_t* option="update"); // *MENU*
void SetGateMethod(const char* xclass,const char* xmethod,
const char* yclass,const char* ymethod);
bool IsInside(TObject *objx,TObject *objy=0);
Int_t IsInside(Double_t x,Double_t y) const { return TCutG::IsInside(x,y); }
private:
TString fXGateClass;
TString fYGateClass;
TString fXGateMethod;
TString fYGateMethod;
ClassDef(GCutG,1)
};
#endif
| [
"pcbend@gmail.com"
] | pcbend@gmail.com |
ae50ba56f78e3175d378f2ae4999c56d8316a689 | 76d72c6a16a715239729c2b548ca832b7e8bd35e | /LibFFmpegPlayer/LibFFmpegPlayer/FFmpegAudioSpeaker.h | 51718671341ffa9a4798c99d138b80f1443286e2 | [] | no_license | naturehome/C-Test | a4a120b6862e3d4076f28452a7f9e0d3a83c7cd4 | 218f4d899579049017a6bf25cc12eb8fb2fd0168 | refs/heads/master | 2021-01-20T08:22:02.131967 | 2019-01-09T11:31:38 | 2019-01-09T11:31:38 | 90,137,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 322 | h | #pragma once
class FFmpegSynchronizer;
class FFmpegFrameProvider;
class FFmpegAudioSpeaker
{
public:
FFmpegAudioSpeaker(FFmpegFrameProvider& FrameProvider, FFmpegSynchronizer& Synchronizer);
~FFmpegAudioSpeaker();
private:
FFmpegFrameProvider& m_FrameProvider;
FFmpegSynchronizer& m_Synchronizer;
};
| [
"zhangyabin@jiandan100.cn"
] | zhangyabin@jiandan100.cn |
cd8fefa22be8cecf89a1389a60bb2870a1c51191 | f268ef85eb335af1794a669e7f69e3c94d3b3cb0 | /Client/source/feint/pane/markdown/html/headerpraser.h | 4ca943a6daaec44f00968837bcf00e73c000371b | [] | no_license | feint123/Emoji | a67a9a6f7cc2e61bba16f9cb75a18c61c8b5d428 | 9929171c9eb74b9799fd3ab23e35d68c059dcfbf | refs/heads/master | 2020-06-16T18:30:49.915832 | 2017-02-02T07:33:09 | 2017-02-02T07:33:09 | 75,077,349 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | h | #ifndef HEADERPRASER_H
#define HEADERPRASER_H
#include <QString>
class HeaderPraser
{
public:
HeaderPraser();
static QString praser(QString text);
private:
QString hOneReg;
QString hTwoReg;
};
#endif // HEADERPRASER_H
| [
"13479399352zyf@gmail.com"
] | 13479399352zyf@gmail.com |
0ea13e4e0cf10630dce8fe1b211245bad23e6808 | 299648a8c633728662d0b7651cd98afdc28db902 | /src/thirdparty/cefbinary_72/include/wrapper/cef_helpers.h | 0c5820dbb552a0966a3fca24c6c4703996e6f3e0 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | permissive | aardvarkxr/aardvark | 2978277b34c2c3894d6aafc4c590f3bda50f4d43 | 300d0d5e9b872ed839fae932c56eff566967d24b | refs/heads/master | 2023-01-12T18:42:10.705028 | 2021-08-18T04:09:02 | 2021-08-18T04:09:02 | 182,431,653 | 183 | 25 | BSD-3-Clause | 2023-01-07T12:42:14 | 2019-04-20T16:55:30 | TypeScript | UTF-8 | C++ | false | false | 4,385 | h | // Copyright (c) 2014 Marshall A. Greenblatt. 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 Google Inc. nor the name Chromium Embedded
// Framework 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.
//
// ---------------------------------------------------------------------------
//
// The contents of this file are only available to applications that link
// against the libcef_dll_wrapper target.
//
#ifndef CEF_INCLUDE_WRAPPER_CEF_HELPERS_H_
#define CEF_INCLUDE_WRAPPER_CEF_HELPERS_H_
#pragma once
#include <cstring>
#include <string>
#include <vector>
#include "include/base/cef_bind.h"
#include "include/base/cef_logging.h"
#include "include/base/cef_macros.h"
#include "include/cef_task.h"
#define CEF_REQUIRE_UI_THREAD() DCHECK(CefCurrentlyOn(TID_UI));
#define CEF_REQUIRE_IO_THREAD() DCHECK(CefCurrentlyOn(TID_IO));
#define CEF_REQUIRE_FILE_THREAD() DCHECK(CefCurrentlyOn(TID_FILE));
#define CEF_REQUIRE_RENDERER_THREAD() DCHECK(CefCurrentlyOn(TID_RENDERER));
// Use this struct in conjuction with refcounted types to ensure that an
// object is deleted on the specified thread. For example:
//
// class Foo : public base::RefCountedThreadSafe<Foo, CefDeleteOnUIThread> {
// public:
// Foo();
// void DoSomething();
//
// private:
// // Allow deletion via scoped_refptr only.
// friend struct CefDeleteOnThread<TID_UI>;
// friend class base::RefCountedThreadSafe<Foo, CefDeleteOnUIThread>;
//
// virtual ~Foo() {}
// };
//
// base::scoped_refptr<Foo> foo = new Foo();
// foo->DoSomething();
// foo = NULL; // Deletion of |foo| will occur on the UI thread.
//
template <CefThreadId thread>
struct CefDeleteOnThread {
template <typename T>
static void Destruct(const T* x) {
if (CefCurrentlyOn(thread)) {
delete x;
} else {
CefPostTask(thread,
base::Bind(&CefDeleteOnThread<thread>::Destruct<T>, x));
}
}
};
struct CefDeleteOnUIThread : public CefDeleteOnThread<TID_UI> {};
struct CefDeleteOnIOThread : public CefDeleteOnThread<TID_IO> {};
struct CefDeleteOnFileThread : public CefDeleteOnThread<TID_FILE> {};
struct CefDeleteOnRendererThread : public CefDeleteOnThread<TID_RENDERER> {};
///
// Helper class to manage a scoped copy of |argv|.
///
class CefScopedArgArray {
public:
CefScopedArgArray(int argc, char* argv[]) {
// argv should have (argc + 1) elements, the last one always being NULL.
array_ = new char*[argc + 1];
for (int i = 0; i < argc; ++i) {
values_.push_back(argv[i]);
array_[i] = const_cast<char*>(values_[i].c_str());
}
array_[argc] = NULL;
}
~CefScopedArgArray() { delete[] array_; }
char** array() const { return array_; }
private:
char** array_;
// Keep values in a vector separate from |array_| because various users may
// modify |array_| and we still want to clean up memory properly.
std::vector<std::string> values_;
DISALLOW_COPY_AND_ASSIGN(CefScopedArgArray);
};
#endif // CEF_INCLUDE_WRAPPER_CEF_HELPERS_H_
| [
"joe@valvesoftware.com"
] | joe@valvesoftware.com |
cf5b3f227c05ceff1fbaaefdb171c8803c35cf5a | 4dd44b69c18016ec7e42600a2831bb47b5364e92 | /standard_openssl/secp256k1.cpp | 17732396e88a4aaa4c062ea053953080bcdfbe49 | [] | no_license | zzGHzz/EVM_CryptoLIb | 0056c10d178fde4ac9f4ea77620f2191fc858500 | e917e592e1873959660ee0d82245cec3407fba6a | refs/heads/master | 2020-06-19T19:37:11.611223 | 2019-12-20T09:49:23 | 2019-12-20T09:49:23 | 196,844,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,504 | cpp | //
// Created by 王星凯 on 2019-08-08.
//
#include "include/secp256k1.h"
#include <cassert>
#include <iostream>
#include <string>
using namespace std;
void Secp256k1_point::init()
{
group = NULL;
point = NULL;
ctx = NULL;
group = EC_GROUP_new_by_curve_name(NID_secp256k1);
if (!group) {
throw runtime_error("secp256k1_point::init(): NEW CURVE GENERATED FAILED!!");
}
point = EC_POINT_new(group);
if (!point) {
EC_GROUP_free(group);
throw runtime_error("secp256k1_point::init(): NEW POINT GENERATED FAILED!!");
}
ctx = BN_CTX_new();
if (!ctx) {
EC_GROUP_free(group);
EC_POINT_free(point);
throw runtime_error("secp256k1_point::init(): BN_CTX_new FAILED!!");
}
return;
}
Secp256k1_point::Secp256k1_point(const Secp256k1_point& src)
{
init();
if (!EC_GROUP_copy(group, src.group))
throw runtime_error("secp256k1_point::secp256k1_point(copy): EC_GROUP_copy failed!!");
if (!EC_POINT_copy(point, src.point))
throw runtime_error("secp256k1_point::secp256k1_point(copy): EC_POINT_copy failed!!");
}
Secp256k1_point::Secp256k1_point(const vector<unsigned char> &bytes) {
init();
BIGNUM* bn = BN_bin2bn(&bytes[0], bytes.size(), NULL);
if (!bn) {
throw runtime_error("secp256k1_point::secp256k1_point(bin): BN_bin2bn failed!!");
}
if (!EC_POINT_bn2point(group, bn, point, ctx)) {
BN_clear_free(bn);
throw runtime_error("secp256k1_point::secp256k1_point(bin): EC_POINT_bn2point failed!!");
}
}
Secp256k1_point::~Secp256k1_point()
{
if (point)
EC_POINT_free(point);
if (group)
EC_GROUP_free(group);
if (ctx)
BN_CTX_free(ctx);
}
Secp256k1_point& Secp256k1_point::operator=(const Secp256k1_point& rhs)
{
if (!EC_GROUP_copy(group, rhs.group)) throw std::runtime_error("secp256k1_point::operator= - EC_GROUP_copy failed.");
if (!EC_POINT_copy(point, rhs.point)) throw std::runtime_error("secp256k1_point::operator= - EC_POINT_copy failed.");
return *this;
}
vector<unsigned char> Secp256k1_point::toBin() const {
vector<unsigned char> bytes(33);
BIGNUM* bn = BN_new();
if (!bn) {
throw runtime_error("secp256k1_point::toBin: bn_new failed!!");
}
if (!EC_POINT_point2bn(group, point, POINT_CONVERSION_COMPRESSED, bn, ctx)) {
BN_clear_free(bn);
throw runtime_error("secp256k1_point::toBin: point2bin failed!!");
}
assert(BN_num_bytes(bn) == 33);
BN_bn2bin(bn, &bytes[0]);
return bytes;
}
Secp256k1_point& Secp256k1_point::operator+=(const Secp256k1_point& rhs)
{
if (!EC_POINT_add(group, point, point, rhs.point, ctx)) {
throw std::runtime_error("secp256k1_point::operator+= - EC_POINT_add failed.");
}
return *this;
}
Secp256k1_point& Secp256k1_point::operator*=(const vector<unsigned char>& rhs)
{
BIGNUM* bn = BN_bin2bn(&rhs[0], rhs.size(), NULL);
if (!bn) {
throw std::runtime_error("secp256k1_point::operator*= - BN_bin2bn failed.");
}
int rval = EC_POINT_mul(group, point, NULL, point, bn, ctx);
BN_clear_free(bn);
if (rval == 0) {
throw std::runtime_error("secp256k1_point::operator*= - EC_POINT_mul failed.");
}
return *this;
}
// Computes n*G + K where K is this and G is the group generator
//void secp256k1_point::generator_mul(const bytes_t& n)
//{
// BIGNUM* bn = BN_bin2bn(&n[0], n.size(), NULL);
// if (!bn) throw std::runtime_error("secp256k1_point::generator_mul - BN_bin2bn failed.");
//
// //int rval = EC_POINT_mul(group, point, bn, (is_at_infinity() ? NULL : point), BN_value_one(), ctx);
// int rval = EC_POINT_mul(group, point, bn, point, BN_value_one(), ctx);
// BN_clear_free(bn);
//
// if (rval == 0) throw std::runtime_error("secp256k1_point::generator_mul - EC_POINT_mul failed.");
//}
// Sets to n*G
void Secp256k1_point::set_ng(const vector<unsigned char>& n)
{
BIGNUM* bn = BN_bin2bn(&n[0], n.size(), NULL);
if (!bn) throw std::runtime_error("secp256k1_point::set_generator_mul - BN_bin2bn failed.");
int rval = EC_POINT_mul(group, point, bn, NULL, NULL, ctx);
BN_clear_free(bn);
if (rval == 0) throw std::runtime_error("secp256k1_point::set_generator_mul - EC_POINT_mul failed.");
}
void Secp256k1_point::set_O() {
if (!EC_POINT_set_to_infinity(group, point)) {
throw runtime_error("secp256k1_point::set_0: EC_POINT_set_to_infinity failed!!");
}
}
| [
"starshine87@sjtu.edu.cn"
] | starshine87@sjtu.edu.cn |
c4e976384cacd38e0a82e7b95555555bd2ab94b4 | b0dd7779c225971e71ae12c1093dc75ed9889921 | /boost/geometry/algorithms/append.hpp | 9a4e082aed67bb4fbdf69f2e2df150c28aacbb5b | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 6,693 | hpp | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP
#define BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP
#include <boost/range.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/mutable_range.hpp>
#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/algorithms/num_interior_rings.hpp>
#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace append
{
template <typename Geometry, typename Point>
struct append_no_action
{
static inline void apply(Geometry& , Point const& ,
int = 0, int = 0)
{
}
};
template <typename Geometry, typename Point>
struct append_point
{
static inline void apply(Geometry& geometry, Point const& point,
int = 0, int = 0)
{
typename geometry::point_type<Geometry>::type copy;
geometry::detail::conversion::convert_point_to_point(point, copy);
traits::push_back<Geometry>::apply(geometry, copy);
}
};
template <typename Geometry, typename Range>
struct append_range
{
typedef typename boost::range_value<Range>::type point_type;
static inline void apply(Geometry& geometry, Range const& range,
int = 0, int = 0)
{
for (typename boost::range_iterator<Range const>::type
it = boost::begin(range);
it != boost::end(range);
++it)
{
append_point<Geometry, point_type>::apply(geometry, *it);
}
}
};
template <typename Polygon, typename Point>
struct point_to_polygon
{
typedef typename ring_type<Polygon>::type ring_type;
static inline void apply(Polygon& polygon, Point const& point,
int ring_index, int = 0)
{
if (ring_index == -1)
{
append_point<ring_type, Point>::apply(
exterior_ring(polygon), point);
}
else if (ring_index < int(num_interior_rings(polygon)))
{
append_point<ring_type, Point>::apply(
interior_rings(polygon)[ring_index], point);
}
}
};
template <typename Polygon, typename Range>
struct range_to_polygon
{
typedef typename ring_type<Polygon>::type ring_type;
static inline void apply(Polygon& polygon, Range const& range,
int ring_index, int )
{
if (ring_index == -1)
{
append_range<ring_type, Range>::apply(
exterior_ring(polygon), range);
}
else if (ring_index < int(num_interior_rings(polygon)))
{
append_range<ring_type, Range>::apply(
interior_rings(polygon)[ring_index], range);
}
}
};
}} // namespace detail::append
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
namespace splitted_dispatch
{
template <typename Tag, typename Geometry, typename Point>
struct append_point
: detail::append::append_no_action<Geometry, Point>
{};
template <typename Geometry, typename Point>
struct append_point<linestring_tag, Geometry, Point>
: detail::append::append_point<Geometry, Point>
{};
template <typename Geometry, typename Point>
struct append_point<ring_tag, Geometry, Point>
: detail::append::append_point<Geometry, Point>
{};
template <typename Polygon, typename Point>
struct append_point<polygon_tag, Polygon, Point>
: detail::append::point_to_polygon<Polygon, Point>
{};
template <typename Tag, typename Geometry, typename Range>
struct append_range
: detail::append::append_no_action<Geometry, Range>
{};
template <typename Geometry, typename Range>
struct append_range<linestring_tag, Geometry, Range>
: detail::append::append_range<Geometry, Range>
{};
template <typename Geometry, typename Range>
struct append_range<ring_tag, Geometry, Range>
: detail::append::append_range<Geometry, Range>
{};
template <typename Polygon, typename Range>
struct append_range<polygon_tag, Polygon, Range>
: detail::append::range_to_polygon<Polygon, Range>
{};
}
// Default: append a range (or linestring or ring or whatever) to any geometry
template
<
typename Geometry, typename RangeOrPoint,
typename TagRangeOrPoint = typename tag<RangeOrPoint>::type
>
struct append
: splitted_dispatch::append_range<typename tag<Geometry>::type, Geometry, RangeOrPoint>
{};
// Specialization for point to append a point to any geometry
template <typename Geometry, typename RangeOrPoint>
struct append<Geometry, RangeOrPoint, point_tag>
: splitted_dispatch::append_point<typename tag<Geometry>::type, Geometry, RangeOrPoint>
{};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
/*!
\brief Appends one or more points to a linestring, ring, polygon, multi-geometry
\ingroup append
\tparam Geometry \tparam_geometry
\tparam RangeOrPoint Either a range or a point, fullfilling Boost.Range concept or Boost.Geometry Point Concept
\param geometry \param_geometry
\param range_or_point The point or range to add
\param ring_index The index of the ring in case of a polygon:
exterior ring (-1, the default) or interior ring index
\param multi_index Reserved for multi polygons or multi linestrings
\qbk{[include reference/algorithms/append.qbk]}
}
*/
template <typename Geometry, typename RangeOrPoint>
inline void append(Geometry& geometry, RangeOrPoint const& range_or_point,
int ring_index = -1, int multi_index = 0)
{
concept::check<Geometry>();
dispatch::append
<
Geometry,
RangeOrPoint
>::apply(geometry, range_or_point, ring_index, multi_index);
}
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP
| [
"tvaneerd@rim.com"
] | tvaneerd@rim.com |
6cdc32fd851461aaacae4b06b1c9a4267293164c | 0c557860627c2025919fc0871dc29e9cba4d36f1 | /src/data/data_normalization.h | 185059652472b41019cbbdf00c09e2d3acde593c | [
"MIT"
] | permissive | m-colombo/ML.cpp | c6b58d7fae2665f7db40f54c61606bf1a45ce481 | 2f1b3b5ab3487ea47263fbd774af9d5a17779c96 | refs/heads/master | 2021-01-10T07:41:59.773348 | 2016-02-10T13:50:01 | 2016-02-10T13:50:01 | 50,877,606 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,864 | h | //
// data_normalization.h
// XAA1
//
// Created by Michele Colombo on 16/12/2015.
// Copyright (c) 2015 Michele Colombo. All rights reserved.
//
#ifndef __XAA1__data_normalization__
#define __XAA1__data_normalization__
#include "samples.h"
#include "../selection/model_info.h"
//TODO extend for 1-of-k
class DataNormalizer : public ModelInfo{
public:
virtual double normalize(double value) = 0;
virtual double denormalize(double value) = 0;
virtual void setDataSource(Doubles const& values)=0;
virtual ~DataNormalizer()=default;
};
typedef std::shared_ptr<DataNormalizer> DataNormalizerSP;
class MinMaxNormalizer : public DataNormalizer{
public:
MinMaxNormalizer(double min_target, double max_target);
void setDataSource(Doubles const& values) override;
double normalize(double value) override;
double denormalize(double value) override;
std::string getInfo() override {return "MinMax["+std::to_string(min_target)+","+std::to_string(max_target)+"]";}
protected:
double min_target, max_target;
double min_value, max_value;
};
class IdentityNormalizer : public DataNormalizer{
public:
IdentityNormalizer(){};
void setDataSource(Doubles const& values) override {}
double normalize(double value) override {return value;}
double denormalize(double value) override {return value;}
std::string getInfo() override {return "Identity";}
};
class ZNormalizer : public DataNormalizer{
public:
ZNormalizer()=default;
void setDataSource(Doubles const& values) override;
double normalize(double value) override { return (value - mean) / sd;}
double denormalize(double value) override { return (value * sd) + mean;}
std::string getInfo() override {return "Z";}
protected:
double mean, sd;
};
#endif /* defined(__XAA1__data_normalization__) */
| [
"mr.michele.colombo@gmail.com"
] | mr.michele.colombo@gmail.com |
39fdffe4d02e0f07df1992f66ad7987fc0fc7d5d | 048df2b4dc5ad153a36afad33831017800b9b9c7 | /atcoder/joisc2007/joisc2007_mall.cc | d43cb1f10e338dd286f69dd0d5c55733f20189d6 | [] | no_license | fluffyowl/past-submissions | a73e8f5157c647634668c200cd977f4428c6ac7d | 24706da1f79e5595b2f9f2583c736135ea055eb7 | refs/heads/master | 2022-02-21T06:32:43.156817 | 2019-09-16T00:17:50 | 2019-09-16T00:17:50 | 71,639,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,048 | cc | #include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for (int i=0;i<(n);i++)
#define REP2(i,m,n) for (int i=m;i<(n);i++)
typedef long long ll;
int H, W, X, Y;
ll A[1010][1010];
ll B[1010][1010];
ll sum1(int i, int j, int h, int w) {
return A[i + h][j + w] - A[i][j + w] + A[i][j] - A[i + h][j];
}
ll sum2(int i, int j, int h, int w) {
return B[i + h][j + w] - B[i][j + w] + B[i][j] - B[i + h][j];
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
cin >> W >> H >> Y >> X;
REP(i, H) REP(j, W) cin >> A[i+1][j+1];
REP(i, H) REP(j, W) B[i+1][j+1] = A[i+1][j+1] == -1;
REP(i, H+1) REP(j, W) A[i][j+1] += A[i][j];
REP(i, H) REP(j, W+1) A[i+1][j] += A[i][j];
REP(i, H+1) REP(j, W) B[i][j+1] += B[i][j];
REP(i, H) REP(j, W+1) B[i+1][j] += B[i][j];
ll ans = 1LL << 59;
REP(i, H-X+1) REP(j, W-Y+1) if (sum2(i, j, X, Y) == 0) {
ans = min(ans, sum1(i, j, X, Y));
}
cout << ans << endl;
} #include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for (int i=0;i<(n);i++)
#define REP2(i,m,n) for (int i=m;i<(n);i++)
typedef long long ll;
int H, W, X, Y;
ll A[1010][1010];
ll B[1010][1010];
ll sum1(int i, int j, int h, int w) {
return A[i + h][j + w] - A[i][j + w] + A[i][j] - A[i + h][j];
}
ll sum2(int i, int j, int h, int w) {
return B[i + h][j + w] - B[i][j + w] + B[i][j] - B[i + h][j];
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
cin >> W >> H >> Y >> X;
REP(i, H) REP(j, W) cin >> A[i+1][j+1];
REP(i, H) REP(j, W) B[i+1][j+1] = A[i+1][j+1] == -1;
REP(i, H+1) REP(j, W) A[i][j+1] += A[i][j];
REP(i, H) REP(j, W+1) A[i+1][j] += A[i][j];
REP(i, H+1) REP(j, W) B[i][j+1] += B[i][j];
REP(i, H) REP(j, W+1) B[i+1][j] += B[i][j];
ll ans = 1LL << 59;
REP(i, H-X+1) REP(j, W-Y+1) if (sum2(i, j, X, Y) == 0) {
ans = min(ans, sum1(i, j, X, Y));
}
cout << ans << endl;
}
| [
"nebukuro09@gmail.com"
] | nebukuro09@gmail.com |
fc0307a8c665e1bb716e71d735c1a4466219de95 | d54a9f1856eb7aaa18be4855a504a7d1e4623d63 | /server.h | f79f1d4862548923330246762f61a4771192400a | [] | no_license | Mazar1ni/CubanglesServer | 938c1d119705fd8da938e25c0ee3e2e51a5182c5 | 1836d7d9a446b8276deb0355b27626dec1eb20d2 | refs/heads/master | 2020-04-13T22:56:11.432243 | 2018-12-29T08:31:23 | 2018-12-29T08:31:23 | 163,492,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | h | #ifndef SERVER_H
#define SERVER_H
#include <QTcpServer>
class Socket;
class RoomManager;
class SearchGame;
class Server : public QTcpServer
{
public:
Server();
void startServer();
protected:
void incomingConnection(int handle);
public:
QList<Socket*> socketList;
RoomManager* roomManager;
SearchGame* searchGame;
};
#endif // SERVER_H
| [
"xmazarini17@gmail.com"
] | xmazarini17@gmail.com |
fd506a86a89c3d4277e4e8bb0315f89d42cf4f89 | 4da55187c399730f13c5705686f4b9af5d957a3f | /resources/languages/cpp/Motor.cpp | 6881a4b479d17026cf0e033f4436b1114ae3ff22 | [
"Apache-2.0"
] | permissive | Ewenwan/webots | 7111c5587100cf35a9993ab923b39b9e364e680a | 6b7b773d20359a4bcf29ad07384c5cf4698d86d3 | refs/heads/master | 2020-04-17T00:23:54.404153 | 2019-01-16T13:58:12 | 2019-01-16T13:58:12 | 166,048,591 | 2 | 0 | Apache-2.0 | 2019-01-16T13:53:50 | 2019-01-16T13:53:50 | null | UTF-8 | C++ | false | false | 3,941 | cpp | // Copyright 1996-2018 Cyberbotics Ltd.
//
// 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.
#define WB_ALLOW_MIXING_C_AND_CPP_API
#include <webots/device.h>
#include <webots/motor.h>
#include <webots/Brake.hpp>
#include <webots/Motor.hpp>
#include <webots/PositionSensor.hpp>
#include <webots/Robot.hpp>
using namespace webots;
void Motor::setAcceleration(double acceleration) {
wb_motor_set_acceleration(getTag(), acceleration);
}
void Motor::setVelocity(double vel) {
wb_motor_set_velocity(getTag(), vel);
}
void Motor::setControlPID(double p, double i, double d) {
wb_motor_set_control_pid(getTag(), p, i, d);
}
// Force
void Motor::setForce(double force) {
wb_motor_set_force(getTag(), force);
}
void Motor::setAvailableForce(double availableForce) {
wb_motor_set_available_force(getTag(), availableForce);
}
void Motor::enableForceFeedback(int sampling_period) {
wb_motor_enable_force_feedback(getTag(), sampling_period);
}
void Motor::disableForceFeedback() {
wb_motor_disable_force_feedback(getTag());
}
int Motor::getForceFeedbackSamplingPeriod() const {
return wb_motor_get_force_feedback_sampling_period(getTag());
}
double Motor::getForceFeedback() const {
return wb_motor_get_force_feedback(getTag());
}
// Torque
void Motor::setTorque(double torque) {
wb_motor_set_force(getTag(), torque);
}
void Motor::setAvailableTorque(double availableTorque) {
wb_motor_set_available_force(getTag(), availableTorque);
}
double Motor::getTorqueFeedback() const {
return wb_motor_get_force_feedback(getTag());
}
void Motor::enableTorqueFeedback(int sampling_period) {
wb_motor_enable_force_feedback(getTag(), sampling_period);
}
void Motor::disableTorqueFeedback() {
wb_motor_disable_force_feedback(getTag());
}
int Motor::getTorqueFeedbackSamplingPeriod() const {
return wb_motor_get_force_feedback_sampling_period(getTag());
}
void Motor::setPosition(double position) {
wb_motor_set_position(getTag(), position);
}
Motor::Type Motor::getType() const {
return Type(wb_motor_get_type(getTag()));
}
double Motor::getTargetPosition() const {
return wb_motor_get_target_position(getTag());
}
double Motor::getMinPosition() const {
return wb_motor_get_min_position(getTag());
}
double Motor::getMaxPosition() const {
return wb_motor_get_max_position(getTag());
}
double Motor::getVelocity() const {
return wb_motor_get_velocity(getTag());
}
double Motor::getMaxVelocity() const {
return wb_motor_get_max_velocity(getTag());
}
double Motor::getAcceleration() const {
return wb_motor_get_acceleration(getTag());
}
double Motor::getAvailableForce() const {
return wb_motor_get_available_force(getTag());
}
double Motor::getMaxForce() const {
return wb_motor_get_max_force(getTag());
}
double Motor::getAvailableTorque() const {
return wb_motor_get_available_torque(getTag());
}
double Motor::getMaxTorque() const {
return wb_motor_get_max_torque(getTag());
}
Brake *Motor::getBrake() {
if (brake == NULL)
brake = dynamic_cast<Brake *>(Robot::getDevice(getBrakeTag()));
return brake;
}
int Motor::getBrakeTag() const {
return wb_motor_get_brake(getTag());
}
PositionSensor *Motor::getPositionSensor() {
if (positionSensor == NULL)
positionSensor = dynamic_cast<PositionSensor *>(Robot::getDevice(getPositionSensorTag()));
return positionSensor;
}
int Motor::getPositionSensorTag() const {
return wb_motor_get_position_sensor(getTag());
}
| [
"David.Mansolino@cyberbotics.com"
] | David.Mansolino@cyberbotics.com |
6245249e5a339b0c806b464a9d601e2f5a3fccaf | 24cbfe81c4fc15619e1e1862dfbfc6b5f9a3619d | /week-3/izo/izo.cpp | 6044bfbd6c36096224cdbfe3c127f3b6284e9aee | [
"MIT"
] | permissive | amwolff/ALGO2020 | 198322b3b51e02c2ca21d468a22370b8cdd2f91c | 6fc361d999ed12e94eb9f86d190ddaac4916d03a | refs/heads/master | 2021-03-13T10:36:06.789574 | 2020-09-08T21:06:25 | 2020-09-08T21:06:25 | 246,670,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
int main() {
int n;
scanf("%d\n", &n);
vector<int> a(n);
for (size_t i = 0; i < a.size(); i++) {
scanf("%d\n", &a[i]);
}
sort(a.begin(), a.end());
size_t i = 0;
size_t j = a.size() - 1;
int ans = 0;
while (i <= j) {
if (i == j) {
ans += a[i];
break;
}
ans += 2 * a[j];
i++;
j--;
}
printf("%d\n", ans);
return 0;
}
| [
"artur.m.wolff@gmail.com"
] | artur.m.wolff@gmail.com |
866011ecf098ce7a8107eebb0fc68ddc8c13a731 | 9b48da12e8d70fb3d633b988b9c7d63a954434bf | /ECC8.1/Server/kennel/Ecc_Common/opens/snmp++/snmp++/Snmp++/include/snmp_pp/oid_def.h | d898440c7939ea231e84b633b3959779ce4c0d7f | [] | no_license | SiteView/ECC8.1.3 | 446e222e33f37f0bb6b67a9799e1353db6308095 | 7d7d8c7e7d7e7e03fa14f9f0e3ce5e04aacdb033 | refs/heads/master | 2021-01-01T18:07:05.104362 | 2012-08-30T08:58:28 | 2012-08-30T08:58:28 | 4,735,167 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,938 | h | /*_############################################################################
_##
_## oid_def.h
_##
_## SNMP++v3.2.15
_## -----------------------------------------------
_## Copyright (c) 2001-2004 Jochen Katz, Frank Fock
_##
_## This software is based on SNMP++2.6 from Hewlett Packard:
_##
_## Copyright (c) 1996
_## Hewlett-Packard Company
_##
_## ATTENTION: USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS.
_## Permission to use, copy, modify, distribute and/or sell this software
_## and/or its documentation is hereby granted without fee. User agrees
_## to display the above copyright notice and this license notice in all
_## copies of the software and any documentation of the software. User
_## agrees to assume all liability for the use of the software;
_## Hewlett-Packard and Jochen Katz make no representations about the
_## suitability of this software for any purpose. It is provided
_## "AS-IS" without warranty of any kind, either express or implied. User
_## hereby grants a royalty-free license to any and all derivatives based
_## upon this software code base.
_##
_## Stuttgart, Germany, Tue Jan 4 21:42:42 CET 2005
_##
_##########################################################################*/
/*===================================================================
Copyright (c) 1999
Hewlett-Packard Company
ATTENTION: USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS.
Permission to use, copy, modify, distribute and/or sell this software
and/or its documentation is hereby granted without fee. User agrees
to display the above copyright notice and this license notice in all
copies of the software and any documentation of the software. User
agrees to assume all liability for the use of the software; Hewlett-Packard
makes no representations about the suitability of this software for any
purpose. It is provided "AS-IS" without warranty of any kind,either express
or implied. User hereby grants a royalty-free license to any and all
derivatives based upon this software code base.
SNMP++ O I D _ D E F . H
OID_DEF DEFINITIONS
DESCRIPTION:
Some common Oid definitions.
DESIGN + AUTHOR:
Peter E Mellquist
LANGUAGE:
ANSI C++
OPERATING SYSTEMS:
DOS / Windows 3.1
BSD UNIX
=====================================================================*/
// $Id: oid_def.h,v 1.4 2004/03/03 23:11:21 katz Exp $
#ifndef _OID_DEF
#define _OID_DEF
#include "snmp_pp/oid.h"
#ifdef SNMP_PP_NAMESPACE
namespace Snmp_pp {
#endif
/** SMI trap oid def */
class snmpTrapsOid: public Oid {
public:
DLLOPT snmpTrapsOid() : Oid("1.3.6.1.6.3.1.1.5") {};
};
/** SMI Enterprose Oid */
class snmpTrapEnterpriseOid: public Oid {
public:
DLLOPT snmpTrapEnterpriseOid() : Oid("1.3.6.1.6.3.1.1.4.3.0") {};
};
/** SMI Cold Start Oid */
class coldStartOid: public snmpTrapsOid {
public:
DLLOPT coldStartOid() { *this+=".1"; };
};
/** SMI WarmStart Oid */
class warmStartOid: public snmpTrapsOid {
public:
DLLOPT warmStartOid() { *this+=".2"; };
};
/** SMI LinkDown Oid */
class linkDownOid: public snmpTrapsOid {
public:
DLLOPT linkDownOid() { *this+=".3"; };
};
/** SMI LinkUp Oid */
class linkUpOid: public snmpTrapsOid {
public:
DLLOPT linkUpOid() { *this+=".4"; };
};
/** SMI Authentication Failure Oid */
class authenticationFailureOid: public snmpTrapsOid {
public:
DLLOPT authenticationFailureOid() { *this+=".5"; };
};
/** SMI egpneighborloss Oid */
class egpNeighborLossOid: public snmpTrapsOid {
public:
DLLOPT egpNeighborLossOid() { *this+=".6"; };
};
#ifdef SNMP_PP_NAMESPACE
}; // end of namespace Snmp_pp
#endif
#endif // _OID_DEF
| [
"136122085@163.com"
] | 136122085@163.com |
ef43da03c0561e3b11ef2abc78adbe9615f494e6 | 62092f08c00b8d6630276574bf2e1b84bc22a82a | /src/Soundex.h | d56fb7677e157c0b2f5e4741bb79feeeea4f4b80 | [] | no_license | Keunho77/MyTest1 | fed85b0307e3a08e10e00aac35c0173f37ca1d94 | ae14fbe80a64741c9f6fa906a3caa0ec9fd8666b | refs/heads/master | 2021-01-10T16:49:03.279318 | 2015-12-21T09:50:31 | 2015-12-21T09:50:31 | 48,313,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,818 | h |
#ifndef SRC_SOUNDEX_H_
#define SRC_SOUNDEX_H_
#include <iostream>
#include <string>
#include <unordered_map>
class Soundex {
public :
std::string encodedDigit(char letter) const {
const std::unordered_map<char, std::string> encodings {
{'b', "1"},{'f', "1"},{'p', "1"}, {'v', "1"},
{'c', "2"},{'g', "2"},{'j', "2"}, {'k', "2"}, {'q', "2"}, {'s', "2"},{'x', "2"}, {'z', "2"},
{'d', "3"},{'t', "3"},
{'l', "4"},
{'m', "5"},{'n', "5"},
{'r', "6"}
};
auto it = encodings.find(letter);
return it == encodings.end() ? "": it->second;
}
std::string encode(const std::string& word) const {
return zeroPad(head(word) + encodedDigits(tail(word)));
}
private :
std::string head(const std::string& word) const {
return word.substr(0,1);
}
std::string tail(const std::string& word) const {
return word.substr(1);
}
std::string lastDigit(const std::string& encoding) const {
if (encoding.empty()) return "";
return std::string(1, encoding.back());
}
std::string encodedDigits(const std::string& word) const {
// if(word.empty()) return "";
std::string encoding;
for(auto letter:word) {
if(isComplete(encoding)) break;
if(encodedDigit(letter) != lastDigit(encoding))
encoding += encodedDigit(letter);
}
return encoding;
// return encodedDigit(word.front());
}
bool isComplete(const std::string& encoding) const {
return encoding.length() == MaxCodeLength -1;
}
static const size_t MaxCodeLength{4};
std::string zeroPad(const std::string& word) const {
auto zeroNeeded = MaxCodeLength - word.length();
// std::cout << "word is "<< word << ". Zero needed is " << zeroNeeded << std::endl;
return word + std::string(zeroNeeded, '0');
}
/* void test(const char* str) {
// str = "Test";
str[0] = "a";
}*/
};
#endif /* SRC_SOUNDEX_H_ */
| [
"keunho77@gmail.com"
] | keunho77@gmail.com |
d731eab3acddb9beaaae2321b614452b88642726 | 2d5001934fcafacde5c441b9344f1f0d94b9ac3e | /TractionControl.h | 64223e3805c4cb0d22502a4144504077fea88091 | [] | no_license | CircuitBirds-FRC4601/CB1 | 9186d52f321404b2b5427b6a4626eb4f9ef3781c | 7e181e868e85d696cc19e7c384016c22263d66bb | refs/heads/master | 2016-09-05T13:26:49.548552 | 2014-02-28T00:49:22 | 2014-02-28T00:49:22 | 17,270,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 767 | h | #ifndef TRACTIONCONTROL_H_
#define TRACTIONCONTROL_H_
#include "Encoder.h"
#include "Timer.h"
class AugmentedEncoder {
//augments the functionality of an encoder
float acceleration;
float velocity;
float distance;
float delta_v; //change in velocity
float delta_d; //change in distance
float delta_t; //change in time
float distance_per_tick; //distance per tick of the encoder
public:
typedef enum {
k1X, k2X, k4X
} AugEncoderState;
AugmentedEncoder(int a_channel, int b_channel, float d_p_t, bool reverse);
void Start();
void Recalculate();
void Reset();
float GetAcceleration();
float GetVelocity();
float GetDistance();
private:
Encoder *encoder;
Timer *timer;
AugEncoderState mAugEncoderState;
};
#endif // TRACTIONCONTROL_H_
| [
"kyle@kylekthompson.com"
] | kyle@kylekthompson.com |
3af816d18d9737ec3b81a2f999c1e0599c4c1807 | 99f1550e0a3c2e21088e2ffc72bc5dadabb1188f | /ui/UICTRL/Src/Control/RichEdit/OLE/comreole.cpp | 408de8431b882e94a97a25924b96bfe63f65925b | [] | no_license | flymolon/UI2017 | 0d0bb1c173e015e7fe26ada47358b4581f3b0e29 | e7182b19d9227abe6d3f91600e85d13c85917e71 | refs/heads/master | 2020-04-11T01:42:49.336393 | 2017-02-12T04:15:19 | 2017-02-12T04:15:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,463 | cpp | #include "stdafx.h"
#include "comreole.h"
using namespace UI;
namespace UI
{
extern UINT g_cfRichEditUnicodeXmlFormat;
extern UINT CF_HTML;
}
ComREOle::ComREOle()
{
m_pOleObject = NULL;
memset(&m_clsid, 0, sizeof(m_clsid));
}
ComREOle::~ComREOle()
{
SAFE_RELEASE(m_pOleObject);
}
HRESULT ComREOle::GetOleObject(IOleObject** ppOleObject, bool bAddRef)
{
if (NULL == ppOleObject)
return E_INVALIDARG;
if (NULL == m_pOleObject)
return E_FAIL;
*ppOleObject = m_pOleObject;
if (bAddRef)
m_pOleObject->AddRef();
return S_OK;
}
HRESULT ComREOle::GetClipboardData(UINT nClipFormat, __out BSTR* pbstrData)
{
if (nClipFormat == g_cfRichEditUnicodeXmlFormat)
{
WCHAR szText[128] = {0};
WCHAR szGUID[64] = {0};
StringFromCLSID(m_clsid, (LPOLESTR*)&szGUID);
wsprintf(szText, L"<com version=\"1.0\" clsid=\"%s\"/>", szGUID);
*pbstrData = SysAllocString(szText);
return S_OK;
}
return E_FAIL;
}
HRESULT ComREOle::GetClipboardDataEx(IDataObject* pDataObject)
{
return E_FAIL;
}
HRESULT ComREOle::Attach(CLSID clsid)
{
SAFE_RELEASE(m_pOleObject);
m_clsid = clsid;
return ::CoCreateInstance(clsid, NULL, CLSCTX_INPROC, IID_IOleObject, (void**)&m_pOleObject);
}
ULONG STDMETHODCALLTYPE ComREOle::AddRef( void)
{
return AddRefImpl();
}
ULONG STDMETHODCALLTYPE ComREOle::Release( void)
{
return ReleaseImpl();
}
| [
"libo30@lenovo.com"
] | libo30@lenovo.com |
54360296804d2be9024f5b885d22cc53aed0e087 | 97ecedecef3d9dc98e70e6517d11e6b76fa254ba | /main.cpp | 2b3fd40f5298ede461a7e9fbc5dbc983bacc2566 | [] | no_license | gbrlins/BankSimulator | 7c01f143b3b731064011889102397b8605efdabc | 6d87449fd7e43dd9899af536ee31e03f8bda74dc | refs/heads/master | 2021-07-13T00:57:05.463841 | 2017-10-18T23:29:12 | 2017-10-18T23:29:12 | 107,474,172 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | #include <iostream>
#include <stdlib.h>
#include "ATM.h"
#include "Account.h"
#include "User.h"
#include "System.h"
int main ()
{
system("Color 1a");
cout<<endl<<endl;
cout<<" ## ## ## "<<endl;
cout<<" #### # # # ##### # "<<endl;
cout<<" # # # # # # # "<<endl;
cout<<" # ### # ## ## # ## ## # # # ### #### # # "<<endl;
cout<<" # # # ## # ## # # # # #### # # # # # # "<<endl;
cout<<" # ### ### # # # # #### # # # ### # # ## "<<endl;
cout<<" # # # # # # # # # # # # # # # # # # "<<endl;
cout<<" #### #### #### ### ### ### ### ##### #### ### ## ## # "<<endl;
cout<<"\t\t\t\t\t\t\t\t # # # # #"<<endl<<endl;
System();
System u;
u.hello();
u.show_menu();
system("pause");
return 0;
}
| [
"noreply@github.com"
] | gbrlins.noreply@github.com |
f1b75bc5d3625b044c9df80dfcf5f33f5e7de451 | eef2c36fbeeda1f8198e47f462a4815b910f90f9 | /src/Model/CTECList.h | 4fd96a5b3e9c7771b020ec873f0e1c246655b7fa | [] | no_license | RanchBean/NodeProject | 430d3598e52a69dd5c12523279bc2fafa991538a | 96875715c61c4380c8182ad2b3e3a2d8661f8406 | refs/heads/master | 2021-01-10T16:10:02.204024 | 2016-03-02T20:26:01 | 2016-03-02T20:26:01 | 52,994,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | h | /*
* CTECList.h
*
* Created on: Mar 2, 2016
* Author: ethr5627
*/
#ifndef MODEL_CTECLIST_H_
#define MODEL_CTECLIST_H_
#include "ArrayNode.h"
template <class Type>
class CTECList
{
private:
int size;
ArrayNode<Type> * head;
ArrayNode<Type> * end;
void calculateSize();
public:
CTECList(int size);
virtual ~CTECList();
int getSize();
void addToFront(const Type& value);
void addToEnd(const Type& value);
void addAtIndex(int index, const Type& value);
Type getFront();
Type getEnd();
Type getFromIndex(int index);
Type removeFromFront();
Type removeFromEnd();
Type removeFromIndex(int index);
Type set(int index, const Type& value);
};
#endif /* MODEL_CTECLIST_H_ */
| [
"Ethunderson1@gmail.com"
] | Ethunderson1@gmail.com |
6e7f7cb5173b98b2da90b494b8da0b5ec85bf5ae | 6b660cb96baa003de9e18e332b048c0f1fa67ab9 | /External/SDK/Proposal_TheAshenDragon_Chapter4_classes.h | bdac822c037b2471503394a6d8e5b6e985fce7dd | [] | no_license | zanzo420/zSoT-SDK | 1edbff62b3e12695ecf3969537a6d2631a0ff36f | 5e581eb0400061f6e5f93b3affd95001f62d4f7c | refs/heads/main | 2022-07-30T03:35:51.225374 | 2021-07-07T01:07:20 | 2021-07-07T01:07:20 | 383,634,601 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 859 | h | #pragma once
// Name: SoT, Version: 2.2.0.2
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Proposal_TheAshenDragon_Chapter4.Proposal_TheAshenDragon_Chapter4_C
// 0x0000 (FullSize[0x0140] - InheritedSize[0x0140])
class UProposal_TheAshenDragon_Chapter4_C : public UVoyageCheckpointProposalDesc
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Proposal_TheAshenDragon_Chapter4.Proposal_TheAshenDragon_Chapter4_C");
return ptr;
}
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
175aed8f04e7f2a65cba8ded82f42df1f149f38c | d32591b7a6a4b73d13ec530135d60727e737a20e | /GameOfInterview/Map.h | 5dbb0251a1001eea911211a58138372fe1d3323c | [] | no_license | sayidli/Minesweeper | 6323b02eabe6998f5d663d794d83043464676322 | 7db17258a78cdfe48bcde0fc0add505d43a0e4dc | refs/heads/master | 2020-08-28T03:56:21.766348 | 2019-11-01T01:50:46 | 2019-11-01T01:50:46 | 217,580,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 695 | h | //
// Map.h
// GameOfInterview
//
// Created by lipengyao on 2019/10/24.
// Copyright © 2019 lipengyao. All rights reserved.
//
#ifndef Map_h
#define Map_h
#endif /* Map_h */
#include "IMapBase.h"
#include "IPlayerBase.h"
class GameMap:public IMapOperater, public IMapBase
{
public:
GameMap();
//IMapBase
bool virtual create(int row, int col, int bombNum);
bool virtual isEnd();
void virtual showView();
//IMapOperater
void virtual openBox(int row, int col);
void virtual putFlag(int row, int col);
~GameMap();
protected:
vector<vector<char>> mapData_;
vector<vector<char>> mapDataCover_;
bool isContinue = true;
};
| [
"itislipengyao@hotmail.com"
] | itislipengyao@hotmail.com |
6fc82d0557142d5c3bb018cede07d41c0d0c526d | b776ec3da034afa276356667c1b3a3de17aeb3bd | /Game/Source/Physics2D/Box2DManager.cpp | fe288df248ad86f81c04962547442d2637d9c398 | [] | no_license | zrcoy/Ewe | b25865071be738be1ec788f5445bb370d59c825b | 5359a699884ea8915730ddb11e644e05e06f48e1 | refs/heads/master | 2020-04-27T09:04:37.378059 | 2019-03-06T18:56:11 | 2019-03-06T18:56:11 | 174,199,795 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | cpp | #include "GamePCH.h"
#include "Box2DManager.h"
#include "Box2DContactListener.h"
#include "../../Libraries/Box2D/Box2D/Box2D.h"
Box2DManager::Box2DManager()
{
m_pWorld = new b2World( b2Vec2( 0, -10 ) );
m_pContactListener = new Box2DContactListener();
m_pWorld->SetContactListener( m_pContactListener );
}
Box2DManager::~Box2DManager()
{
delete m_pContactListener;
delete m_pWorld;
}
void Box2DManager::Update(float deltatime)
{
m_pWorld->Step( 1/60.0f, 3, 8 );
}
| [
"zhan0472@algonquinlive.com"
] | zhan0472@algonquinlive.com |
5d0f04346e40dab0341ee6c1437504b090d308c0 | 988d2a132be3d3f36a985d848f6d4cc54748d5e7 | /src/Platform.Linux/TimeSourceLinux.cpp | 7a35fc359d233ae2f11f83ed286ff81f80262f1e | [
"MIT"
] | permissive | ValtoForks/pomdog | 24336f3342c51a25a0260144bdc72f6bf0bb4a35 | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | refs/heads/master | 2021-05-03T15:47:12.979889 | 2019-01-04T15:42:05 | 2019-01-04T15:42:05 | 120,486,114 | 0 | 0 | NOASSERTION | 2019-01-04T15:42:06 | 2018-02-06T16:15:53 | C++ | UTF-8 | C++ | false | false | 667 | cpp | // Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#include "TimeSourceLinux.hpp"
#include "Pomdog/Utility/Exception.hpp"
#include <ctime>
namespace Pomdog {
namespace Detail {
namespace Linux {
TimePoint TimeSourceLinux::Now() const
{
struct timespec now;
if (0 != clock_gettime(CLOCK_MONOTONIC, &now)) {
POMDOG_THROW_EXCEPTION(std::runtime_error, "FUS RO DAH");
}
constexpr double nanoScale = (1.0 / 1000000000LL);
return TimePoint { Duration {
static_cast<double>(now.tv_sec) +
static_cast<double>(now.tv_nsec) * nanoScale}};
}
} // namespace Linux
} // namespace Detail
} // namespace Pomdog
| [
"mogemimi@enginetrouble.net"
] | mogemimi@enginetrouble.net |
b2c47231fb28a42dd9c2f4e636cde531d200bb39 | df0dc0fcdcc4d0b62d8d3b596415870d06975972 | /Programacion 2017 - 2018/Programacion 2017/Final Verano/Estudio Final Prog/Drive/C++(la consigna es correr el main)/clase libro/libro/libro.h | f4ef3126f262b7ad8124793303d1ea5e42c7098d | [] | no_license | diego-rico-dk/Programacion-Unlam | 169f1be80ce18eb210f3773515522381b31ae125 | 30cc0781a3f65fd1f5026180055da1ca41dc4ee8 | refs/heads/master | 2022-01-08T21:31:11.371443 | 2019-04-11T03:46:20 | 2019-04-11T03:46:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 499 | h | #ifndef LIBRO_H_INCLUDED
#define LIBRO_H_INCLUDED
#include <iostream>
#include <string.h>
using namespace std;
class Libro
{
private:
char nombre[60];
char autor[50];
int paginas;
public:
Libro(char* nom="El libro de Cosme Fulanito",char* au="Cosme Fulanito" ,int pag=1000);
Libro operator+(const Libro&)const;
bool operator==(const Libro&)const;
friend ostream& operator<<(ostream& out,Libro& libro);
};
#endif // LIBRO_H_INCLUDED
| [
"tocinonaro_juan@yahoo.com.ar"
] | tocinonaro_juan@yahoo.com.ar |
3cc98a8137eaf0e9769a397c534428fb437ec9e5 | 1a17167c38dc9a12c1f72dd0f3ae7288f5cd7da0 | /Source/ThirdParty/angle/third_party/SwiftShader/src/OpenGL/compiler/preprocessor/DirectiveParser.cpp | ed2ec074686ba7efd085667ab56c53fcca3182a0 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"LicenseRef-scancode-khronos",
"BSL-1.0",
"BSD-2-Clause",
"Apache-2.0"
] | permissive | elix22/Urho3D | c57c7ecb58975f51fabb95bcc4330bc5b0812de7 | 99902ae2a867be0d6dbe4c575f9c8c318805ec64 | refs/heads/master | 2023-06-01T01:19:57.155566 | 2021-12-07T16:47:20 | 2021-12-07T17:46:58 | 165,504,739 | 21 | 4 | MIT | 2021-11-05T01:02:08 | 2019-01-13T12:51:17 | C++ | UTF-8 | C++ | false | false | 25,631 | cpp | // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "DirectiveParser.h"
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <sstream>
#include "DiagnosticsBase.h"
#include "DirectiveHandlerBase.h"
#include "ExpressionParser.h"
#include "MacroExpander.h"
#include "Token.h"
#include "Tokenizer.h"
namespace {
enum DirectiveType
{
DIRECTIVE_NONE,
DIRECTIVE_DEFINE,
DIRECTIVE_UNDEF,
DIRECTIVE_IF,
DIRECTIVE_IFDEF,
DIRECTIVE_IFNDEF,
DIRECTIVE_ELSE,
DIRECTIVE_ELIF,
DIRECTIVE_ENDIF,
DIRECTIVE_ERROR,
DIRECTIVE_PRAGMA,
DIRECTIVE_EXTENSION,
DIRECTIVE_VERSION,
DIRECTIVE_LINE
};
} // namespace
static DirectiveType getDirective(const pp::Token *token)
{
static const char kDirectiveDefine[] = "define";
static const char kDirectiveUndef[] = "undef";
static const char kDirectiveIf[] = "if";
static const char kDirectiveIfdef[] = "ifdef";
static const char kDirectiveIfndef[] = "ifndef";
static const char kDirectiveElse[] = "else";
static const char kDirectiveElif[] = "elif";
static const char kDirectiveEndif[] = "endif";
static const char kDirectiveError[] = "error";
static const char kDirectivePragma[] = "pragma";
static const char kDirectiveExtension[] = "extension";
static const char kDirectiveVersion[] = "version";
static const char kDirectiveLine[] = "line";
if (token->type != pp::Token::IDENTIFIER)
return DIRECTIVE_NONE;
if (token->text == kDirectiveDefine)
return DIRECTIVE_DEFINE;
else if (token->text == kDirectiveUndef)
return DIRECTIVE_UNDEF;
else if (token->text == kDirectiveIf)
return DIRECTIVE_IF;
else if (token->text == kDirectiveIfdef)
return DIRECTIVE_IFDEF;
else if (token->text == kDirectiveIfndef)
return DIRECTIVE_IFNDEF;
else if (token->text == kDirectiveElse)
return DIRECTIVE_ELSE;
else if (token->text == kDirectiveElif)
return DIRECTIVE_ELIF;
else if (token->text == kDirectiveEndif)
return DIRECTIVE_ENDIF;
else if (token->text == kDirectiveError)
return DIRECTIVE_ERROR;
else if (token->text == kDirectivePragma)
return DIRECTIVE_PRAGMA;
else if (token->text == kDirectiveExtension)
return DIRECTIVE_EXTENSION;
else if (token->text == kDirectiveVersion)
return DIRECTIVE_VERSION;
else if (token->text == kDirectiveLine)
return DIRECTIVE_LINE;
return DIRECTIVE_NONE;
}
static bool isConditionalDirective(DirectiveType directive)
{
switch (directive)
{
case DIRECTIVE_IF:
case DIRECTIVE_IFDEF:
case DIRECTIVE_IFNDEF:
case DIRECTIVE_ELSE:
case DIRECTIVE_ELIF:
case DIRECTIVE_ENDIF:
return true;
default:
return false;
}
}
// Returns true if the token represents End Of Directive.
static bool isEOD(const pp::Token *token)
{
return (token->type == '\n') || (token->type == pp::Token::LAST);
}
static void skipUntilEOD(pp::Lexer *lexer, pp::Token *token)
{
while(!isEOD(token))
{
lexer->lex(token);
}
}
static bool isMacroNameReserved(const std::string& name)
{
// Names prefixed with "GL_" are reserved.
return (name.substr(0, 3) == "GL_");
}
bool hasDoubleUnderscores(const std::string &name)
{
return (name.find("__") != std::string::npos);
}
static bool isMacroPredefined(const std::string& name,
const pp::MacroSet& macroSet)
{
pp::MacroSet::const_iterator iter = macroSet.find(name);
return iter != macroSet.end() ? iter->second->predefined : false;
}
namespace pp
{
class DefinedParser : public Lexer
{
public:
DefinedParser(Lexer *lexer, const MacroSet *macroSet, Diagnostics *diagnostics)
: mLexer(lexer), mMacroSet(macroSet), mDiagnostics(diagnostics)
{
}
protected:
void lex(Token *token) override
{
const char kDefined[] = "defined";
mLexer->lex(token);
if (token->type != Token::IDENTIFIER)
return;
if (token->text != kDefined)
return;
bool paren = false;
mLexer->lex(token);
if (token->type == '(')
{
paren = true;
mLexer->lex(token);
}
if (token->type != Token::IDENTIFIER)
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN, token->location, token->text);
skipUntilEOD(mLexer, token);
return;
}
MacroSet::const_iterator iter = mMacroSet->find(token->text);
std::string expression = iter != mMacroSet->end() ? "1" : "0";
if (paren)
{
mLexer->lex(token);
if (token->type != ')')
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN,
token->location, token->text);
skipUntilEOD(mLexer, token);
return;
}
}
// We have a valid defined operator.
// Convert the current token into a CONST_INT token.
token->type = Token::CONST_INT;
token->text = expression;
}
private:
Lexer *mLexer;
const MacroSet *mMacroSet;
Diagnostics *mDiagnostics;
};
DirectiveParser::DirectiveParser(Tokenizer *tokenizer,
MacroSet *macroSet,
Diagnostics *diagnostics,
DirectiveHandler *directiveHandler,
int maxMacroExpansionDepth)
: mPastFirstStatement(false),
mSeenNonPreprocessorToken(false),
mTokenizer(tokenizer),
mMacroSet(macroSet),
mDiagnostics(diagnostics),
mDirectiveHandler(directiveHandler),
mShaderVersion(100),
mMaxMacroExpansionDepth(maxMacroExpansionDepth)
{
}
DirectiveParser::~DirectiveParser()
{
}
void DirectiveParser::lex(Token *token)
{
do
{
mTokenizer->lex(token);
if (token->type == Token::PP_HASH)
{
parseDirective(token);
mPastFirstStatement = true;
}
else if (!isEOD(token))
{
mSeenNonPreprocessorToken = true;
}
if (token->type == Token::LAST)
{
if (!mConditionalStack.empty())
{
const ConditionalBlock &block = mConditionalStack.back();
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_UNTERMINATED,
block.location, block.type);
}
break;
}
} while (skipping() || (token->type == '\n'));
mPastFirstStatement = true;
}
void DirectiveParser::parseDirective(Token *token)
{
assert(token->type == Token::PP_HASH);
mTokenizer->lex(token);
if (isEOD(token))
{
// Empty Directive.
return;
}
DirectiveType directive = getDirective(token);
// While in an excluded conditional block/group,
// we only parse conditional directives.
if (skipping() && !isConditionalDirective(directive))
{
skipUntilEOD(mTokenizer, token);
return;
}
switch(directive)
{
case DIRECTIVE_NONE:
mDiagnostics->report(Diagnostics::PP_DIRECTIVE_INVALID_NAME,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
break;
case DIRECTIVE_DEFINE:
parseDefine(token);
break;
case DIRECTIVE_UNDEF:
parseUndef(token);
break;
case DIRECTIVE_IF:
parseIf(token);
break;
case DIRECTIVE_IFDEF:
parseIfdef(token);
break;
case DIRECTIVE_IFNDEF:
parseIfndef(token);
break;
case DIRECTIVE_ELSE:
parseElse(token);
break;
case DIRECTIVE_ELIF:
parseElif(token);
break;
case DIRECTIVE_ENDIF:
parseEndif(token);
break;
case DIRECTIVE_ERROR:
parseError(token);
break;
case DIRECTIVE_PRAGMA:
parsePragma(token);
break;
case DIRECTIVE_EXTENSION:
parseExtension(token);
break;
case DIRECTIVE_VERSION:
parseVersion(token);
break;
case DIRECTIVE_LINE:
parseLine(token);
break;
default:
assert(false);
break;
}
skipUntilEOD(mTokenizer, token);
if (token->type == Token::LAST)
{
mDiagnostics->report(Diagnostics::PP_EOF_IN_DIRECTIVE,
token->location, token->text);
}
}
void DirectiveParser::parseDefine(Token *token)
{
assert(getDirective(token) == DIRECTIVE_DEFINE);
mTokenizer->lex(token);
if (token->type != Token::IDENTIFIER)
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN,
token->location, token->text);
return;
}
if (isMacroPredefined(token->text, *mMacroSet))
{
mDiagnostics->report(Diagnostics::PP_MACRO_PREDEFINED_REDEFINED,
token->location, token->text);
return;
}
if (isMacroNameReserved(token->text))
{
mDiagnostics->report(Diagnostics::PP_MACRO_NAME_RESERVED,
token->location, token->text);
return;
}
// Using double underscores is allowed, but may result in unintended
// behavior, so a warning is issued. At the time of writing this was
// specified in ESSL 3.10, but the intent judging from Khronos
// discussions and dEQP tests was that double underscores should be
// allowed in earlier ESSL versions too.
if (hasDoubleUnderscores(token->text))
{
mDiagnostics->report(Diagnostics::PP_WARNING_MACRO_NAME_RESERVED, token->location,
token->text);
}
std::shared_ptr<Macro> macro = std::make_shared<Macro>();
macro->type = Macro::kTypeObj;
macro->name = token->text;
mTokenizer->lex(token);
if (token->type == '(' && !token->hasLeadingSpace())
{
// Function-like macro. Collect arguments.
macro->type = Macro::kTypeFunc;
do {
mTokenizer->lex(token);
if (token->type != Token::IDENTIFIER)
break;
if (std::find(macro->parameters.begin(), macro->parameters.end(), token->text) != macro->parameters.end())
{
mDiagnostics->report(Diagnostics::PP_MACRO_DUPLICATE_PARAMETER_NAMES,
token->location, token->text);
return;
}
macro->parameters.push_back(token->text);
mTokenizer->lex(token); // Get ','.
} while (token->type == ',');
if (token->type != ')')
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN,
token->location,
token->text);
return;
}
mTokenizer->lex(token); // Get ')'.
}
while ((token->type != '\n') && (token->type != Token::LAST))
{
// Reset the token location because it is unnecessary in replacement
// list. Resetting it also allows us to reuse Token::equals() to
// compare macros.
token->location = SourceLocation();
macro->replacements.push_back(*token);
mTokenizer->lex(token);
}
if (!macro->replacements.empty())
{
// Whitespace preceding the replacement list is not considered part of
// the replacement list for either form of macro.
macro->replacements.front().setHasLeadingSpace(false);
}
// Check for macro redefinition.
MacroSet::const_iterator iter = mMacroSet->find(macro->name);
if (iter != mMacroSet->end() && !macro->equals(*iter->second))
{
mDiagnostics->report(Diagnostics::PP_MACRO_REDEFINED, token->location, macro->name);
return;
}
mMacroSet->insert(std::make_pair(macro->name, macro));
}
void DirectiveParser::parseUndef(Token *token)
{
assert(getDirective(token) == DIRECTIVE_UNDEF);
mTokenizer->lex(token);
if (token->type != Token::IDENTIFIER)
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN,
token->location, token->text);
return;
}
MacroSet::iterator iter = mMacroSet->find(token->text);
if (iter != mMacroSet->end())
{
if (iter->second->predefined)
{
mDiagnostics->report(Diagnostics::PP_MACRO_PREDEFINED_UNDEFINED,
token->location, token->text);
return;
}
else if (iter->second->expansionCount > 0)
{
mDiagnostics->report(Diagnostics::PP_MACRO_UNDEFINED_WHILE_INVOKED,
token->location, token->text);
return;
}
else
{
mMacroSet->erase(iter);
}
}
mTokenizer->lex(token);
if (!isEOD(token))
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN, token->location, token->text);
skipUntilEOD(mTokenizer, token);
}
}
void DirectiveParser::parseIf(Token *token)
{
assert(getDirective(token) == DIRECTIVE_IF);
parseConditionalIf(token);
}
void DirectiveParser::parseIfdef(Token *token)
{
assert(getDirective(token) == DIRECTIVE_IFDEF);
parseConditionalIf(token);
}
void DirectiveParser::parseIfndef(Token *token)
{
assert(getDirective(token) == DIRECTIVE_IFNDEF);
parseConditionalIf(token);
}
void DirectiveParser::parseElse(Token *token)
{
assert(getDirective(token) == DIRECTIVE_ELSE);
if (mConditionalStack.empty())
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_ELSE_WITHOUT_IF,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
return;
}
ConditionalBlock &block = mConditionalStack.back();
if (block.skipBlock)
{
// No diagnostics. Just skip the whole line.
skipUntilEOD(mTokenizer, token);
return;
}
if (block.foundElseGroup)
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_ELSE_AFTER_ELSE,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
return;
}
block.foundElseGroup = true;
block.skipGroup = block.foundValidGroup;
block.foundValidGroup = true;
// Check if there are extra tokens after #else.
mTokenizer->lex(token);
if (!isEOD(token))
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_UNEXPECTED_TOKEN,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
}
}
void DirectiveParser::parseElif(Token *token)
{
assert(getDirective(token) == DIRECTIVE_ELIF);
if (mConditionalStack.empty())
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_ELIF_WITHOUT_IF,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
return;
}
ConditionalBlock &block = mConditionalStack.back();
if (block.skipBlock)
{
// No diagnostics. Just skip the whole line.
skipUntilEOD(mTokenizer, token);
return;
}
if (block.foundElseGroup)
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_ELIF_AFTER_ELSE,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
return;
}
if (block.foundValidGroup)
{
// Do not parse the expression.
// Also be careful not to emit a diagnostic.
block.skipGroup = true;
skipUntilEOD(mTokenizer, token);
return;
}
int expression = parseExpressionIf(token);
block.skipGroup = expression == 0;
block.foundValidGroup = expression != 0;
}
void DirectiveParser::parseEndif(Token *token)
{
assert(getDirective(token) == DIRECTIVE_ENDIF);
if (mConditionalStack.empty())
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_ENDIF_WITHOUT_IF,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
return;
}
mConditionalStack.pop_back();
// Check if there are tokens after #endif.
mTokenizer->lex(token);
if (!isEOD(token))
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_UNEXPECTED_TOKEN,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
}
}
void DirectiveParser::parseError(Token *token)
{
assert(getDirective(token) == DIRECTIVE_ERROR);
std::ostringstream stream;
mTokenizer->lex(token);
while ((token->type != '\n') && (token->type != Token::LAST))
{
stream << *token;
mTokenizer->lex(token);
}
mDirectiveHandler->handleError(token->location, stream.str());
}
// Parses pragma of form: #pragma name[(value)].
void DirectiveParser::parsePragma(Token *token)
{
assert(getDirective(token) == DIRECTIVE_PRAGMA);
enum State
{
PRAGMA_NAME,
LEFT_PAREN,
PRAGMA_VALUE,
RIGHT_PAREN
};
bool valid = true;
std::string name, value;
int state = PRAGMA_NAME;
mTokenizer->lex(token);
bool stdgl = token->text == "STDGL";
if (stdgl)
{
mTokenizer->lex(token);
}
while ((token->type != '\n') && (token->type != Token::LAST))
{
switch(state++)
{
case PRAGMA_NAME:
name = token->text;
valid = valid && (token->type == Token::IDENTIFIER);
break;
case LEFT_PAREN:
valid = valid && (token->type == '(');
break;
case PRAGMA_VALUE:
value = token->text;
valid = valid && (token->type == Token::IDENTIFIER);
break;
case RIGHT_PAREN:
valid = valid && (token->type == ')');
break;
default:
valid = false;
break;
}
mTokenizer->lex(token);
}
valid = valid && ((state == PRAGMA_NAME) || // Empty pragma.
(state == LEFT_PAREN) || // Without value.
(state == RIGHT_PAREN + 1)); // With value.
if (!valid)
{
mDiagnostics->report(Diagnostics::PP_UNRECOGNIZED_PRAGMA, token->location, name);
}
else if (state > PRAGMA_NAME) // Do not notify for empty pragma.
{
mDirectiveHandler->handlePragma(token->location, name, value, stdgl);
}
}
void DirectiveParser::parseExtension(Token *token)
{
assert(getDirective(token) == DIRECTIVE_EXTENSION);
enum State
{
EXT_NAME,
COLON,
EXT_BEHAVIOR
};
bool valid = true;
std::string name, behavior;
int state = EXT_NAME;
mTokenizer->lex(token);
while ((token->type != '\n') && (token->type != Token::LAST))
{
switch (state++)
{
case EXT_NAME:
if (valid && (token->type != Token::IDENTIFIER))
{
mDiagnostics->report(Diagnostics::PP_INVALID_EXTENSION_NAME, token->location,
token->text);
valid = false;
}
if (valid)
name = token->text;
break;
case COLON:
if (valid && (token->type != ':'))
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN, token->location,
token->text);
valid = false;
}
break;
case EXT_BEHAVIOR:
if (valid && (token->type != Token::IDENTIFIER))
{
mDiagnostics->report(Diagnostics::PP_INVALID_EXTENSION_BEHAVIOR,
token->location, token->text);
valid = false;
}
if (valid)
behavior = token->text;
break;
default:
if (valid)
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN, token->location,
token->text);
valid = false;
}
break;
}
mTokenizer->lex(token);
}
if (valid && (state != EXT_BEHAVIOR + 1))
{
mDiagnostics->report(Diagnostics::PP_INVALID_EXTENSION_DIRECTIVE, token->location,
token->text);
valid = false;
}
if (valid && mSeenNonPreprocessorToken)
{
if (mShaderVersion >= 300)
{
mDiagnostics->report(Diagnostics::PP_NON_PP_TOKEN_BEFORE_EXTENSION_ESSL3,
token->location, token->text);
valid = false;
}
else
{
mDiagnostics->report(Diagnostics::PP_NON_PP_TOKEN_BEFORE_EXTENSION_ESSL1,
token->location, token->text);
}
}
if (valid)
mDirectiveHandler->handleExtension(token->location, name, behavior);
}
void DirectiveParser::parseVersion(Token *token)
{
assert(getDirective(token) == DIRECTIVE_VERSION);
if (mPastFirstStatement)
{
mDiagnostics->report(Diagnostics::PP_VERSION_NOT_FIRST_STATEMENT, token->location,
token->text);
skipUntilEOD(mTokenizer, token);
return;
}
enum State
{
VERSION_NUMBER,
VERSION_PROFILE,
VERSION_ENDLINE
};
bool valid = true;
int version = 0;
int state = VERSION_NUMBER;
mTokenizer->lex(token);
while (valid && (token->type != '\n') && (token->type != Token::LAST))
{
switch (state)
{
case VERSION_NUMBER:
if (token->type != Token::CONST_INT)
{
mDiagnostics->report(Diagnostics::PP_INVALID_VERSION_NUMBER,
token->location, token->text);
valid = false;
}
if (valid && !token->iValue(&version))
{
mDiagnostics->report(Diagnostics::PP_INTEGER_OVERFLOW,
token->location, token->text);
valid = false;
}
if (valid)
{
state = (version < 300) ? VERSION_ENDLINE : VERSION_PROFILE;
}
break;
case VERSION_PROFILE:
if (token->type != Token::IDENTIFIER || token->text != "es")
{
mDiagnostics->report(Diagnostics::PP_INVALID_VERSION_DIRECTIVE,
token->location, token->text);
valid = false;
}
state = VERSION_ENDLINE;
break;
default:
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN,
token->location, token->text);
valid = false;
break;
}
mTokenizer->lex(token);
}
if (valid && (state != VERSION_ENDLINE))
{
mDiagnostics->report(Diagnostics::PP_INVALID_VERSION_DIRECTIVE,
token->location, token->text);
valid = false;
}
if (valid && version >= 300 && token->location.line > 1)
{
mDiagnostics->report(Diagnostics::PP_VERSION_NOT_FIRST_LINE_ESSL3, token->location,
token->text);
valid = false;
}
if (valid)
{
mDirectiveHandler->handleVersion(token->location, version);
mShaderVersion = version;
PredefineMacro(mMacroSet, "__VERSION__", version);
}
}
void DirectiveParser::parseLine(Token *token)
{
assert(getDirective(token) == DIRECTIVE_LINE);
bool valid = true;
bool parsedFileNumber = false;
int line = 0, file = 0;
MacroExpander macroExpander(mTokenizer, mMacroSet, mDiagnostics, false, mMaxMacroExpansionDepth);
// Lex the first token after "#line" so we can check it for EOD.
macroExpander.lex(token);
if (isEOD(token))
{
mDiagnostics->report(Diagnostics::PP_INVALID_LINE_DIRECTIVE, token->location, token->text);
valid = false;
}
else
{
ExpressionParser expressionParser(¯oExpander, mDiagnostics);
ExpressionParser::ErrorSettings errorSettings;
// See GLES3 section 12.42
errorSettings.integerLiteralsMustFit32BitSignedRange = true;
errorSettings.unexpectedIdentifier = Diagnostics::PP_INVALID_LINE_NUMBER;
// The first token was lexed earlier to check if it was EOD. Include
// the token in parsing for a second time by setting the
// parsePresetToken flag to true.
expressionParser.parse(token, &line, true, errorSettings, &valid);
if (!isEOD(token) && valid)
{
errorSettings.unexpectedIdentifier = Diagnostics::PP_INVALID_FILE_NUMBER;
// After parsing the line expression expressionParser has also
// advanced to the first token of the file expression - this is the
// token that makes the parser reduce the "input" rule for the line
// expression and stop. So we're using parsePresetToken = true here
// as well.
expressionParser.parse(token, &file, true, errorSettings, &valid);
parsedFileNumber = true;
}
if (!isEOD(token))
{
if (valid)
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN,
token->location, token->text);
valid = false;
}
skipUntilEOD(mTokenizer, token);
}
}
if (valid)
{
mTokenizer->setLineNumber(line);
if (parsedFileNumber)
mTokenizer->setFileNumber(file);
}
}
bool DirectiveParser::skipping() const
{
if (mConditionalStack.empty())
return false;
const ConditionalBlock &block = mConditionalStack.back();
return block.skipBlock || block.skipGroup;
}
void DirectiveParser::parseConditionalIf(Token *token)
{
ConditionalBlock block;
block.type = token->text;
block.location = token->location;
if (skipping())
{
// This conditional block is inside another conditional group
// which is skipped. As a consequence this whole block is skipped.
// Be careful not to parse the conditional expression that might
// emit a diagnostic.
skipUntilEOD(mTokenizer, token);
block.skipBlock = true;
}
else
{
DirectiveType directive = getDirective(token);
int expression = 0;
switch (directive)
{
case DIRECTIVE_IF:
expression = parseExpressionIf(token);
break;
case DIRECTIVE_IFDEF:
expression = parseExpressionIfdef(token);
break;
case DIRECTIVE_IFNDEF:
expression = parseExpressionIfdef(token) == 0 ? 1 : 0;
break;
default:
assert(false);
break;
}
block.skipGroup = expression == 0;
block.foundValidGroup = expression != 0;
}
mConditionalStack.push_back(block);
}
int DirectiveParser::parseExpressionIf(Token *token)
{
assert((getDirective(token) == DIRECTIVE_IF) || (getDirective(token) == DIRECTIVE_ELIF));
DefinedParser definedParser(mTokenizer, mMacroSet, mDiagnostics);
MacroExpander macroExpander(&definedParser, mMacroSet, mDiagnostics, true, mMaxMacroExpansionDepth);
ExpressionParser expressionParser(¯oExpander, mDiagnostics);
int expression = 0;
ExpressionParser::ErrorSettings errorSettings;
errorSettings.integerLiteralsMustFit32BitSignedRange = false;
errorSettings.unexpectedIdentifier = Diagnostics::PP_CONDITIONAL_UNEXPECTED_TOKEN;
bool valid = true;
expressionParser.parse(token, &expression, false, errorSettings, &valid);
// Check if there are tokens after #if expression.
if (!isEOD(token))
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_UNEXPECTED_TOKEN,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
}
return expression;
}
int DirectiveParser::parseExpressionIfdef(Token* token)
{
assert((getDirective(token) == DIRECTIVE_IFDEF) ||
(getDirective(token) == DIRECTIVE_IFNDEF));
mTokenizer->lex(token);
if (token->type != Token::IDENTIFIER)
{
mDiagnostics->report(Diagnostics::PP_UNEXPECTED_TOKEN,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
return 0;
}
MacroSet::const_iterator iter = mMacroSet->find(token->text);
int expression = iter != mMacroSet->end() ? 1 : 0;
// Check if there are tokens after #ifdef expression.
mTokenizer->lex(token);
if (!isEOD(token))
{
mDiagnostics->report(Diagnostics::PP_CONDITIONAL_UNEXPECTED_TOKEN,
token->location, token->text);
skipUntilEOD(mTokenizer, token);
}
return expression;
}
} // namespace pp
| [
"elix22@gmail.com"
] | elix22@gmail.com |
8dc3c21065bf5fcde4b35eec4716dd7eeac5be6d | aeb95623970cf4a93317c38ab4eb27837adff35f | /Array/1252_CellswithOddValuesinaMatrix.cpp | 2c3716e2e285ab32c113f59c2cfcb4a33c95c959 | [] | no_license | CodingOfZero/LeetCode | e153e99b19887d1bc65ab45bd973e7ee3d328ac8 | 06c4b4c506d378144a7d5d1db5d9f4e06999fbe0 | refs/heads/master | 2021-07-20T16:31:56.675310 | 2021-07-05T12:06:31 | 2021-07-05T12:06:31 | 141,298,691 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,296 | cpp | /*
时间:2019年12月20日 16:19:32
题目:Given n and m which are the dimensions of a matrix initialized by zeros
and given an array indices where indices[i] = [ri, ci].
For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1
题意:将ri行加一,ci列加一
*/
#include<vector>
#include<iostream>
using namespace std;
/*
Runtime: 4 ms, faster than 83.07% of C++ online submissions for Cells with Odd Values in a Matrix.
Memory Usage: 9.2 MB, less than 100.00% of C++ online submissions for Cells with Odd Values in a Matrix.
*/
#define MAXN 55
#define MAXM 55
int cells[MAXN][MAXM];
int oddCells_1(int n, int m, vector<vector<int>>& indices) {//直接暴力求解
int odd = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cells[i][j] = 0;
for (size_t i = 0; i < indices.size(); i++) {
int a = indices[i][0];
int b = indices[i][1];
for (int i = 0; i < m; i++)
cells[a][i]++;
for (int i = 0; i < n; i++)
cells[i][b]++;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (cells[i][j] % 2 != 0)
odd++;
return odd;
}
/*
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Cells with Odd Values in a Matrix.
Memory Usage: 9.3 MB, less than 100.00% of C++ online submissions for Cells with Odd Values in a Matrix.
*/
int oddCells_2(int n, int m, vector<vector<int>>& indices) {
vector<int> oddRows;
vector<int> oddCols;
//初始化所有行与列,0是偶数
oddRows.assign(n, 0);
oddCols.assign(m, 0);
for (const auto &elem : indices) {
oddRows[elem[0]] = 1 - oddRows[elem[0]];
oddCols[elem[1]] = 1 - oddCols[elem[1]];
}
//统计奇数的列数
int numOddCols = 0;
for (const auto c : oddCols)//这种写法会比下方速度快
numOddCols += c;
/*for (size_t i = 0; i < oddCols.size(); i++)
if (oddCols[i] == 1)
numOddCols++;*/
int numEvenCols = m - numOddCols;
//输出奇数个数
int Odd = 0;
for (auto r:oddRows)
Odd += r ? numEvenCols : numOddCols;
return Odd;
}
int main() {
vector<vector<int>> indices = { {1,1},{0,0} };
vector<vector<int>> indices2 = { { 0,1 },{ 1,1 } };
int odd1=oddCells_1(2, 2, indices);
int odd2= oddCells_2(2, 3, indices2);
cout << odd2;
}
| [
"895756412@qq.com"
] | 895756412@qq.com |
404b9c1345f96937f4acd9b8392a8434776209f6 | 3879d1ca43c573c209f962182cd1e7f7fe978fbf | /leetcode/328. Odd Even Linked List/328.cpp | 77270284afc81ea2f79021cccca32bc071e5cc56 | [] | no_license | DoctorLai/ACM | 34a5600a5adf22660c5d81b2d8b7a358be537ecf | aefa170f74c55c1230eb6f352770512b1e3f469e | refs/heads/master | 2023-09-01T02:13:01.604508 | 2023-08-31T15:42:07 | 2023-08-31T15:42:07 | 146,173,024 | 62 | 18 | null | 2020-10-11T13:19:57 | 2018-08-26T11:00:36 | C++ | UTF-8 | C++ | false | false | 752 | cpp | // https://helloacm.com/reconnect-the-nodes-in-linked-list-by-odd-even-in-place-odd-even-linked-list/
// https://leetcode.com/problems/odd-even-linked-list/
// MEDIUM, LINKED LIST
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head == nullptr) return NULL;
auto odd = head, even = head->next, evenHead = even;
while (even && even->next) {
odd->next = even->next;
odd = odd->next;
even->next = odd->next;
even = even->next;
}
odd->next = evenHead;
return head;
}
};
| [
"dr.zhihua.lai@gmail.com"
] | dr.zhihua.lai@gmail.com |
cf0ccf0b71eac960ab2777326233c7c1d141cd99 | 7849554c268311afab49d919d68a0deed784c221 | /src/SimulatorApp/org.alljoyn.Notification.Dismisser/pch.h | e985839c4b8302432edad8dc6d8723c6cf32334f | [
"MIT"
] | permissive | dotMorten/AllJoynDeviceSimulator | aa30a73e188c738daa7ba5cc143e7af72c65d005 | b5a7e7198983c0aad02f78d1868a083940f7c57f | refs/heads/master | 2020-12-29T00:30:27.844468 | 2016-08-16T04:13:28 | 2016-08-16T04:13:28 | 49,626,641 | 8 | 5 | null | 2016-08-08T19:45:35 | 2016-01-14T06:08:58 | C++ | UTF-8 | C++ | false | false | 1,804 | h |
//-----------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// Tool: AllJoynCodeGenerator.exe
//
// This tool is located in the Windows 10 SDK and the Windows 10 AllJoyn
// Visual Studio Extension in the Visual Studio Gallery.
//
// The generated code should be packaged in a Windows 10 C++/CX Runtime
// Component which can be consumed in any UWP-supported language using
// APIs that are available in Windows.Devices.AllJoyn.
//
// Using AllJoynCodeGenerator - Invoke the following command with a valid
// Introspection XML file and a writable output directory:
// AllJoynCodeGenerator -i <INPUT XML FILE> -o <OUTPUT DIRECTORY>
// </auto-generated>
//-----------------------------------------------------------------------------
#pragma once
#include <windows.h>
#include <ppltasks.h>
#include <concrt.h>
#include <collection.h>
#include <windows.devices.alljoyn.interop.h>
#include <map>
#include <alljoyn_c/busattachment.h>
#include <alljoyn_c/dbusstddefines.h>
#include <alljoyn_c/AboutData.h>
#include <alljoyn_c/AboutObj.h>
#include <alljoyn_c/AboutObjectDescription.h>
#include "AllJoynHelpers.h"
#include "AllJoynBusObjectManager.h"
#define PROJECT_NAMESPACE org::alljoyn::Notification::Dismisser
#include "DismisserStructures.h"
#include "TypeConversionHelpers.h"
#include "DismisserMethodResults.h"
#include "DismisserEventArgs.h"
#include "IDismisserService.h"
#include "DismisserSignals.h"
#include "DismisserProducer.h"
#include "DismisserWatcher.h"
#include "DismisserConsumer.h"
#include "DismisserServiceEventArgs.h"
#include "DismisserServiceEventAdapter.h" | [
"mnielsen@esri.com"
] | mnielsen@esri.com |
256669f37f053acf3cef320611f5cf6d94c17ec4 | 35e12426b8cd82a766a8ef4d6f14b7b6e5943dd4 | /simulation/humanvector.cpp | 2192b357b9e51688576158e94ad000a98631151c | [] | no_license | demarsis/Panic | 2bcd939907d885b913b6b4be7f6b386037749f94 | 3842655eb5bd51c894e138015362223ab0e60a9d | refs/heads/master | 2021-09-04T03:25:36.060507 | 2018-01-15T08:54:58 | 2018-01-15T08:54:58 | 115,006,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,017 | cpp | #include "humanvector.h"
Directions HumanVector::dirs = Directions(true);
Vector HumanVector::getIntentionVector(HumanPtr &human, FloorPtr &floor)
{
if (!human) return Vector();
if (!floor) return Vector();
std::vector<CellPtr> humanCells = getHumanCells(human, floor);
// get penalties for all directions
std::vector<std::pair<Vector, Penalty>> possibleVectors;
for (const Directions::DirVector &dirvect : dirs.getAllDirections())
{
Penalty pen = getCellsPenalty(floor, humanCells, dirvect.first);
possibleVectors.push_back(std::make_pair(dirvect.second * HUMAN_INTENTION_SPEED_COEFF, pen));
}
if (possibleVectors.empty()) return Vector();
// sort by min penalty
/* std::sort(possibleVectors.begin(), possibleVectors.end(),
[](const std::pair<Vector, Penalty> &left,
const std::pair<Vector, Penalty> &right) -> bool
{
return left.second < right.second;
}
);*/
// search min penalty
Penalty minPenalty = PENALTY_MAX;
for (const std::pair<Vector, Penalty> &pair : possibleVectors)
{
if (minPenalty > pair.second) minPenalty = pair.second;
}
// leave only mins
possibleVectors.erase(std::remove_if(possibleVectors.begin(), possibleVectors.end(),
[minPenalty](const std::pair<Vector, Penalty> &pair)
{
return pair.second > minPenalty;
}),
possibleVectors.end()
);
int rnd = Probability::instance().random(possibleVectors.size());
Vector &result = possibleVectors[rnd].first;
// use speed coeff
result *= human->getSpeedCoeff();
return result;
}
std::vector<CellPtr> HumanVector::getHumanCells(HumanPtr &human, FloorPtr &floor)
{
std::vector<CellPtr> result;
if (!human) return result;
if (!floor) return result;
Position center(human->getPosition().x, human->getPosition().y);
int radius = human->getDiameter() / 2;
Position lefttop(center.x - radius, center.y - radius);
Position rightbottom(center.x + radius, center.y + radius);
for (int x = lefttop.x; x <= rightbottom.x; x++)
{
for (int y = lefttop.y; y <= rightbottom.y; y++)
{
float currentRadius = (x - center.x) * (x - center.x) + (y - center.y) * (y - center.y);
if (currentRadius > radius * radius) continue;
if (!floor->isValidPosition(Position(x, y))) continue;
CellPtr cell = floor->getCell(x, y);
if (cell)
{
result.push_back(cell);
}
}
}
return result;
}
Penalty HumanVector::getCellsPenalty(FloorPtr &floor, const std::vector<CellPtr> &cells, const Position &offset)
{
if (!floor) return PENALTY_ZERO;
Penalty result = 0;
for (const CellPtr &cell : cells)
{
Position pos = cell->getPosition();
pos.x += offset.x;
pos.y += offset.y;
if (!floor->isValidPosition(pos))
{
result += PENALTY_MAX;
continue;
}
CellPtr &offsetedCell = floor->getCell(pos);
if (!offsetedCell)
{
result += PENALTY_MAX;
continue;
}
result += offsetedCell->getAdditionalData().wayPenalty;
}
return result;
}
bool HumanVector::isNewPositionIntersectedWithOther(const HumanPtr &human, const Vector &vec, const HumanPtr &other)
{
// get new position
PositionF pos = human->getPosition();
pos.x += vec.getX();
pos.y += vec.getY();
// other's position
const PositionF &othersPosition = other->getPosition();
// check with others
float squaredLength = (pos.x - othersPosition.x) * (pos.x - othersPosition.x) +
(pos.y - othersPosition.y) * (pos.y - othersPosition.y);
float squaredDiameter = human->getDiameter() / 2 + other->getDiameter() / 2;
squaredDiameter *= squaredDiameter;
// check
if (squaredLength < squaredDiameter) return true;
return false;
}
Vector HumanVector::getPushesVector(const HumanPtr &human, const HumanPtr &other)
{
const PositionF &humanPosition = human->getPosition();
const PositionF &otherPosition = other->getPosition();
float length = sqrt((humanPosition.x - otherPosition.x) * (humanPosition.x - otherPosition.x) +
(humanPosition.y - otherPosition.y) * (humanPosition.y - otherPosition.y));
float radiuses = human->getDiameter() / 2 + other->getDiameter() / 2;
float diff = radiuses - length;
float k = diff / length;
k /= 2;
k *= HUMAN_PUSH_COEFF;
float cx = (humanPosition.x - otherPosition.x) * k;
float cy = (humanPosition.y - otherPosition.y) * k;
return Vector(cx, cy);
}
| [
"demarsis@mail.ru"
] | demarsis@mail.ru |
a2f65fbc834a3532902c96505214ba2362c7863b | 4a3e5419e89dfbd9788a4539740b8ea7321ee7ef | /152/a.cpp | fa919f60ef1c681b36c9a9c357b2d61fae12f726 | [] | no_license | tars0x9752/atcoder | d3cbfefeb5164edab72d87f8feb16e1160c231a2 | 0e54c9a34055e47ae6bb19d4493306e974a50eee | refs/heads/master | 2022-11-19T15:36:17.711849 | 2020-07-19T12:56:31 | 2020-07-19T12:56:31 | 182,626,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int n, m;
cin >> n >> m;
string ans = "Yes";
if (n != m) {
ans = "No";
}
cout << ans << endl;
return 0;
} | [
"46079709+huffhuffman@users.noreply.github.com"
] | 46079709+huffhuffman@users.noreply.github.com |
d3fe5b6bab72bdd3606aeaf978e57ec48ab2584f | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/multimedia/directx/dmusic/dmusic/des8.h | 2638e9a462fc263ba3d784d39e77162faa8c2de1 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,978 | h | //------------------------------------------------------------------------------
//
// des8.h -- Design of DirectX 8 interfaces for DirectMusic
//
// Copyright (c) 1998-1999 Microsoft Corporation
//
//------------------------------------------------------------------------------
//
// Prototypes for new DirectX 8 interfaces for DirectMusic core
//
// This header discusses interfaces which manange wave playback between
// the wave object, the DirectMusic port, and a DirectMusic software synth.
// It does not address communication between the wave track and the wave
// object or the software synth and DirectSound, or directly between the
// wave object and DirectSound.
//
// These interfaces are based on my understanding of our recent hallway
// discussions.
//
// Issues which need futher discussion are marked with XXX.
//
//
//
// New schedule breakdown
//
// 1. Port (synth and WDM)
// a. IDirectMusicPort::DownloadWave
// Code is very similar for WDM or software synth
// i. Get needed information from WO and create IDirectSoundSource 0.5
// ii. If oneshot, track and download header and wave data 3.5
// iii. If streaming, download header 0.5
//
// b. IDirectMusicPort::UnloadWave
// i. Arbitrate with device for 0 refcount of download 1.0
//
// c. IDirectMusicPort::AllocVoice
// i. Allocate voice ID 0.5
// ii. If streaming, allocate preread samples and streaming buffers 2.5
//
// d. Voice Service Thread
// i. Init and shutdown code at port create/destroy 1.0
// ii. Call listed voices every ~100 ms 0.5
//
// e. CDirectMusicVoice::Service
// i. Communicate with device to determine each voice position 0.5
// ii. Calculate how much more wave data is needed 1.0
// iii. Fill wave data from IDirectSoundSource and send to device 1.0
// iv. Determine when playback is complete and stop voice 0.5
//
// f. IDirectMusicVoice::Play
// i. Communicate request to device 0.3
// ii. Send down timestamped preread data 0.3
// iii. Insert into VST 0.3
//
// g. IDirectMusicVoice::Stop
// i. Flag voice as stopped 0.5
// ii. Forward request to device 0.0
//
// h. Setup and connection
//
// i. Move sink code into DSound 3.0
//
//
15.5
//
// Things to change
//
// * We will model the DownloadWave interface after the Download interface
// and will pass things down to the synth as such:
//
// DLH + WAD -> Download header + Wave Articulation Data
// (contains loop points and count, etc.)
//
// DLH + DATA -> Download header + data
//
// * For oneshot data we want to do download refcounting like we do for
// regular DLS downloads. For streams we do not since the data that comes
// down in each download is the next set of data for the device to play.
//
// Download waves first, then wave articulations
// Separate multichannel downloads
// Rotating buffers and refresh for streaming
//
// New generic typedefs and #defines
//
typedef ULONGLONG SAMPLE_TIME; // Sample position w/in stream
typedef SAMPLESPOS *PSAMPLE_TIME;
#define DMUS_DOWNLOADINFO_WAVEARTICULATION 4 // Wave articulation data
#define DMUS_DOWNLOADINFO_STREAMINGWAVE 5 // One chunk of a streaming
// wave
// This is built by the wave object from the 'smpl' chunk embedded in the
// wave file if there is one, else it is just defaults.
//
typedef struct _DMUS_WAVEART
{
DWORD cbSize; // As usual
WSMPL WSMP; // Wave sample as per DLS1
WLOOP WLOOP[1]; // If cSampleCount > 1
} DMUS_WAVEART;
//------------------------------------------------------------------------------
//
// IDirectSoundSource
//
// An IDirectSound source is the interface to what we've been calling the
// viewport object.
//
//
//
interface IDirectSoundSource
{
// Init
//
// Gives the interface of the connected sink
STDMETHOD(Init)
(THIS_
IDirectSoundSink *pSink // Connected sink
);
// GetFormat
//
// Returns the format the source is returning the wave data in
//
STDMETHOD(GetFormat)
(THIS_
LPWAVEFORMATEX *pwfx, // Wave format to fill in
LPDWORD pcbwfx // Size of wave format,
// returns actual size
) PURE;
// Seek
//
// Seek to the given sample position in the stream. May be inexact
// due to accuracy settings of wave object. To account for this
//
STDMETHOD(Seek)
(THIS_
SAMPLEPOS sp // New sample position
) PURE;
// Read
//
// Read the given amount of sample data into the provided buffer starting
// from the read cursor. The read cursor is set with seek and advanced
// with each successive call to Read.
//
STDMETHOD(Read)
(THIS_
LPVOID *ppvBuffer, // Array of pvBuffer's
DWORD cpvBuffer, // and how many are passed in
PSAMPLEPOS pcb // In: number of samples to read
// Out: number of samples read
) PURE;
// GetSize
//
// Returns the size of the entire wave, in bytes, in the requested format
//
STDMETHOD(GetSize)
(THIS_
PULONG *pcb // Out: Bytes in stream
) PURE;
};
//------------------------------------------------------------------------------
//
// IDirectSoundSink
//
// An IDirectSound sink is the interface which feeds itself from one
// IDirectSoundSource. It is based on the IDirectMusicSynthSink interface
//
//
interface IDirectSoundSink
{
// Init
//
// Sets up the source to render from
//
STDMETHOD(Init)
(THIS_
IDirectSoundSource *pSource // The source from which we read
) PURE;
// SetMasterClock
//
// Sets the master clock (reference time) to use
//
STDMETHOD(SetMasterClock)
(THIS_
IReferenceClock *pClock // Master timebase
) PURE;
// GetLatencyClock
//
// Returns the clock which reads latency time, relative to
// the master clock
//
STDMETHOD(GetLatencyClock)
(THIS_
IReferenceClock **ppClock // Returns latency clock
) PURE;
// Activate
//
// Starts or stops rendering
//
STDMETHOD(Activate)
(THIS_
BOOL fEnable // Get ready or stop
) PURE;
// SampleToRefTime
//
// Converts a sample position in the stream to
// master clock time
//
STDMETHOD(SampleToRefTime)
(THIS_
SAMPLE_TIME sp, // Sample time in
REFERENCE_TIME *prt // Reference time out
) PURE;
// RefToSampleTime
//
// Converts a reference time to the nearest
// sample
//
STDMETHOD(RefToSampleTime)
(THIS_
REFERENCE_TIME rt, // Reference time in
SAMPLE_TIME *psp // Sample time out
) PURE;
};
//------------------------------------------------------------------------------
//
// IDirectSoundWave
//
// Public interface for the wave object
//
#define DSWCS_F_DEINTERLEAVED 0x00000001 // Multi-channel data as
// multiple buffers
interface IDirectSoundWave
{
// GetWaveArticulation
//
// Returns wave articulation data, either based on a 'smpl' chunk
// from the wave file or a default.
//
STDMETHOD(GetWaveArticulation)
(THIS_
WAVEARTICULATION *pArticulation // Articulation to fill in
) PURE;
// CreateSource
//
// Creates a new IDirectSoundSource to read wave data from
// this wave
//
STDMEHTOD(CreateSource)
(THIS_
IDirectSoundSource **ppSource // Created viewport object
LPWAVEFORMATEX pwfex, // Desired format
DWORD dwFlags // DSWCS_xxx
) PURE;
};
//------------------------------------------------------------------------------
//
// IDirectMusicPort8
//
//
//
#define DMDLW_STREAM 0x00000001
interface IDirectMusicPort8 extends IDirectMusicPort
{
// DownloadWave
//
// Creates a downloaded wave object representing the wave on this
// port.
//
STDMETHOD(DownloadWave)
(THIS_
IDirectSoundWave *pWave, // Wave object
ULONGLONG rtStart, // Start position (stream only)
DWORD dwFlags, // DMDLW_xxx
IDirectSoundDownloadedWave **ppWave // Returned downloaded wave
) PURE;
// UnloadWave
//
// Releases the downloaded wave object as soon as there are no voices
// left referencing it.
//
STDMETHOD(UnloadWave)
(THIS_
IDirectSoundDownloadedWave *pWave // Wave to unload
) PURE;
// AllocVoice
//
// Allocate one playback instance of the downloaded wave on this
// port.
//
STDMETHOD(AllocVoice)
(THIS_
IDirectSoundDownloadedWave *pWave, // Wave to play on this voice
DWORD dwChannel, // Channel and channel group
DWORD dwChannelGroup, // this voice will play on
SAMPLE_TIME stReadAhead, // How much to read ahead
IDirectMusicVoice **ppVoice // Returned voice
) PURE;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// DownloadWave (normal use)
//
// 1. Application calls GetObject to load segment which contains a wave track.
// This causes GetObject to be called on all related waves, creating wave
// objects for all of them.
//
// 2. Wave track calls SetParam on each wave object to set up author-time
// parameters on the wave. This includes:
// - One-shot versus stream-ness
// - Readahead amount
//
// 3. Application calls SetParam(GUID_Download,...) to force download. As well
// as downloading DLS instruments (band track), the wave track calls
// DownloadWave for every wave to download. (Note: are we using the same GUID
// for download? It doesn't appear that SetParam on a segment is broadcast
// too all tracks, but rather is sent to the first track that understands
// the GUID, or the nth if an index is given. This would mean that
// the application would have to call SetParam twice with the same GUID
// and a different track index if there are both band and wave tracks
// in the segment??
//
// Returned is an IDirectMusicDownloadedWave(DirectSound?) to track the wave.
//
// The following happen during the DownloadWave method call:
//
// 4. The port queries the wave object for the stream-ness and readahead
// properties.
//
// XXX We decided that these things were per wave object, right?
// (As opposed to the viewport). And the wave object already knows them or
// is the right object to provide reasonable defaults.
//
// 5. The port requests a viewport from the wave object in its native format.
//
// 6. The port allocates buffer space. The buffer must be big enough to handle
// the entire wave in the case of the one shot, or at least big enough to
// handle the readahead samples in the streaming case. The streaming buffer
// may be allocated larger, however, if it is going to be used for the
// entire streaming session. Buffer choice here may be affected by the
// underlying port.
//
// I assume we are going to parallel the DLS architecture as much as
// possible here and are going to be able to trigger a downloaded wave
// more than once at the same time. In that case the buffer would have
// to be stored in the _voice_, not the DownloadedWave (except perhaps
// for the readahead which should always be kept around). Is this
// duplication of effort if we're going to be caching in the wave
// object as well?
//
// 7. If the wave is a one-shot, then the port will request the entire data
// for the wave from the viewport and downloads it to the device. At this
// point the viewport is released since the entire data for the wave is in
// the synth. If the wave is streaming, then nothing is done at the device
// level.
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// UnloadWave
//
// This tells the port that the application is done with the wave as soon as
// there are no more voice references to it. Internally it just calls
// Release() on the downloaded wave object. The dlwave object can then no longer
// be used to create voices. However, the dlwave will only really be released
// once all voices that currently use it are released.
//
// This is identical to calling Release() on the dlwave object directly
// (why does it exist?)
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// AllocVoice
//
// Allocate a voice object to play back the a wave on a channel group
//
// This call is simple. All it does it ask the synth for a voice ID (which
// is just a cookie that only has meaning to the synth) and creates the voice
// object.
//
// At this point the download is bound to the channel, since MIDI articulations
// sent to the voice before playback begins will need to know that.
//
// The voice object addref's the downloaded wave object.
//
//------------------------------------------------------------------------------
//
// IDirectMusicVoice
//
// One playback instance of a downloaded wave on a port
//
// Note that since we're already bound to a channel after the voice is
// created, we don't need any methods on the voice object for MIDI
// articulation. That can just go through the normal synth mechanism.
//
interface IDirectMusicVoice
{
public:
// Play
//
STDMETHOD(Play)
(_THIS
REFERENCE_TIME rtStart, // Time to play
REFERENCE_TIME rtStartInWave // XXX Move this
// Where in stream to start
) PURE;
// Should stop be scheduled or immediate?
//
STDMETHOD(Stop)
(_THIS
REFERENCE_TIME rtStop, // When to stop
) PURE;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// QueryInterface(IID_IKsControl)
//
// All of the effects control should be in the DirectSound side now.
// However, IKsControl can still be used as in 6.1 and 7 to determine
// synth caps.
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// Play
//
// XXX I am not sure this is the right place to deal with preread. However,
// we can't deal with it at DownloadWave(), because we don't know at that
// point where to start (the app may play the stream from different
// starting points on different voice). We *could* do it at voice allocation
// time; that would just mean that the stream start position is fixed for
// a particular voice no matter how many times the voice is triggered.
// This is an issue because preread may take some time if decompression is
// taking place and the seek request is far into the wave; it may cause
// problems with low-latency Play commands.
//
// Note that I am delegating the quality versus efficiency flag to private
// communication between the wave object and the wave track or application.
//
// 1. Call Play() on the synth voice ID associated with this voice. If the
// associated wave is a one-shot, this is all that needs to be done.
//
// 2. For a stream, no preread data has been allocated yet. Tell the wave
// object to seek to the given position and preread. Give the preread data
// to the device via StreamVoiceData().
//
// 3. If the associated wave is a stream, insert this voice into the voice
// service list. This will cause push-pull arbiration to be done on the
// voice until it finishes or Stop() is called.
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// Stop
//
// 1. Call Stop() on the synth voice.
//
// 2. If the voice is streaming and not done, pull it from the voice service
// thread.
//
//------------------------------------------------------------------------------
//
// IDirectMusicSynth8
//
// New methods on the synthesizer interface for managing wave playback.
// A parallel to these methods will be needed on a hardware synth, probably
// implemented as a property set.
//
interface IDirectMusicSynth8 extends IDirectMusicSynth
{
public:
STDMETHOD(DownloadWave)
(THIS_
LPHANDLE pHandle, // Returned handle representing DL
LPVOID pvData, // Initial data
// XXX >1 channel -> buffers?
LPBOOL pbFree, // Is port allowed to free data?
BOOL bStream // This is preroll data for a stream
) PURE;
STDMETHOD(UnloadWave)
(THIS_
HANDLE phDownload, // Handle from DownloadWave
HRESULT (CALLBACK *pfnFreeHandle)(HANDLE,HANDLE),
// Callback to call when done
HANDLE hUserData // User data to pass back in
// callback
) PURE;
STDMETHOD(PlayVoice)
(THIS_
REFERENCE_TIME rt, // Time to start playback
DWORD dwVoiceId, // Voice ID allocated by port
DWORD dwChannelGroup, // Channel group and
DWORD dwChannel, // channel to start voice on
DWORD dwDLId // Download ID of the wave to play
// (This will be of the wave
// articulation)
) PURE;
STDMETHOD(StopVoice)
(THIS_
DWORD dwVoice, // Voice to stop
REFERENCE_TIME rt // When to stop
) PURE;
struct VOICE_POSITION
{
ULONGLONG ullSample; // Sample w/in wave
DWORD dwSamplesPerSec; // Playback rate at current pitch
};
STDMETHOD(GetVoicePosition)
(THIS_
HANDLE ahVoice[], // Array of handles to get position
DWORD cbVoice, // Elements in ahVoice and avp
VOICE_POSITION avp[] // Returned voice position
) PURE;
STDMETHOD(StreamVoiceData)
(THIS_
HANDLE hVoice, // Which voice this data is for
LPVOID pvData, // New sample data
DWORD cSamples // Number of samples in pvData
) PURE;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// DownloadWave
//
// This could be the same as Download except that we need to deal with
// the streaming case.
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// UnloadWave
//
// Works just like Unload. In the streaming case, the callback will be
// called after _all_ data in the stream is free. Note that if UnloadWave
// is called while the wave is still playing, this could be quite some
// time.
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// PlayVoice
//
// Schedule the voice to be played. The synth already has the data
// for a oneshot wave, so starting playback is very fast. If the data is
// to be streamed it is the caller's responsibility (i.e. the port) to
// keep the stream fed via StreamVoiceData()
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// StopVoice
//
// Just what it says.
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// GetVoicePosition
//
// This call retrieves the position of a set of voices. For each voice, the
// current sample position relative to the start of the stream and the
// average number of samples per second at the current pitch is returned. This
// gives the caller all the information it needs to stay ahead of the
// voice playback. This call is intended for use on streaming voices.
//
// Note that the playback position is an implication that all data up to the
// point of that sample is done with and the buffer space can be freed. This
// allows recycling of buffers in a streaming wave.
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// StreamVoiceData
//
// This call queues more data for a streaming voice.
//
// XXX This implies that there will be a discontinuity in the memory used
// by the synth mixer. How do we deal with that?
//
//
//------------------------------------------------------------------------------
//
// General questions and discussion
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// What can be underneath a DirectMusic port?
//
// In 6.1 and 7 this was easy; either a SW synth on top of DSound
// (synth port), or a kernel sw synth or hw synth (WDM port). (Not
// counting the dmusic16 code which will not be changing in 8).
//
// What are the scenarios we have now? Does it make sense (or is it even
// possible in light of backwards compat) to change what a port wraps?
// The two scenarios which match the existing ports are:
//
// Scenario: Software synthesizer on top of DirectSound as we have today.
// The hookup logic changes (we're talking n mono busses, etc.) but the
// mechanics do not: the application can still just hand us a DirectSound
// object and we connect it to the bottom of the synthesizer. This still has
// to work with pre-8 applications making the same set of API calls they
// always did, but internally it can be totally different.
// XXX Did we ever expose the IDirectMusicSynthSink and methods for hooking
// it up? Can this change? (It has to...) I _think_ this was a DDK thing...
// The application can also create a DX8 DirectSound buffer with all the
// bells and whistles and have that work as well. We need some (DX8) specific
// mechanism for routing what goes out of the synth into the n mono inputs
// of the DirectSound buffer if it's more than just a legacy stereo buffer.
//
//
// Scenario: We sit on top of a hardware or KM synth on top of *everything*
// else in kernel mode. We need private communication between DirectMusic,
// DirectSound, and SysAudio in order to hook this up, or we need to
// delegate the graph building tasks totally to DirectSound and have it
// deal exlusively with SysAudio connections. The latter is probably the
// way to go. In this case we fail if we cannot get a WDM driver under
// DirectSound to talk to, or if the DirectSound buffer is not totally in
// hardware. (This all argues for having DirectSound be able to instantiate
// the KM synth on top of the buffer rather than arbitrating with DirectMusic
// to do it). We need to define this interface ASAP.
// (Me, Dugan, Mohan, MikeM).
//
//
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
ce8458093056b79223184a041a461b9011c71c30 | eb70adcfcc30ac8301341ccf72ec146de41a1665 | /src/commonjobadder.h | 567c1eb71cbc669ca8278cabef06ad5675586228 | [] | no_license | Beliaf/leechcraft | ff2166070913f2d7ee480f40542ccdf148e49cad | 0823a7d8f85d11bed0b81e61ddb3bf329f9d5d39 | refs/heads/master | 2021-01-18T11:00:38.531356 | 2009-06-14T22:44:13 | 2009-06-14T22:44:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | #ifndef COMMONJOBADDER_H
#define COMMONJOBADDER_H
#include <QDialog>
#include "ui_commonjobadder.h"
namespace LeechCraft
{
class CommonJobAdder : public QDialog,
private Ui::CommonJobAdder
{
Q_OBJECT
public:
CommonJobAdder (QWidget *parent = 0);
virtual ~CommonJobAdder ();
QString GetString () const;
QString GetWhere () const;
private slots:
void on_Browse__released ();
void on_BrowseWhere__released ();
void on_Paste__released ();
};
};
#endif
| [
"0xd34df00d@gmail.com"
] | 0xd34df00d@gmail.com |
2dfff90ac86c2615167ceac368040aaf6006ca9d | 203c4602712963d4b431902ff1a6e1f9da6bd56a | /FiveCardStud.h | 5c38c4464a102479eb094fba081e72dc7579ba00 | [] | no_license | Woogachaka/gcc-fivecardstud | 30872f219bf3f5973219b8324becd7fe7a50fb0a | 307e69cc622d125f142f5027182c4b252f23cad6 | refs/heads/master | 2020-12-11T05:56:18.188708 | 2014-02-20T17:59:56 | 2014-02-20T17:59:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,267 | h | #ifndef __GAME_H
#define __GAME_H
#include "Player.h"
#include "Card.h"
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
class FiveCardStud
{
static const int PLAYER_STARTING_BANK = 100;
static const int ante = 1;
public:
FiveCardStud();
~FiveCardStud();
void setup(int nPlayers); //initiates a game with the set number of players
void play(); // plays multiple rounds until someone runs out of money
void packUp(); // after a game has finished
private:
int getPot() { return pot; } // dollars
void emptyPot() { pot = 0; }
void addPot(int value) { pot += value * 100; }
// implementable
void playRound(); // runs many times per game, one winner per round, goes through a few betting rounds
void performBetting(); // asks for a round of bets, starting from the dealer's left (or next in vector array, first if dealer is last), adding to the pot from player's banks
void shuffleDeck();
// ui functions
void ui_renderPlayerView(int playerId); // renders complete game view as it appears to player, clears screen and prompts for input
void ui_showWinner(int playerId);
std::vector<Player> players;
int dealerId; // contains the index for the player
//UserInterface ui;
std::vector<Card> deck;
int pot;
};
#endif | [
"jv789521@gmail.com"
] | jv789521@gmail.com |
c4f58ecdbb82c5c17e0a16579b6252d5ef97f4e1 | b6fb6785e6689c1e22c30327e690e290e54f57b0 | /MainWindow.cpp | 3c9ba6294f8ca0a64b4518dfa2b5d0cf442c7345 | [] | no_license | MetalStrikerXLR/FQMCv2-GUI-QT | 15ef8dc44d3939b0b69e2a58d7cc9c750f8428d8 | 62176e3d81b8ec50d6e3ce390506b7d482de4429 | refs/heads/master | 2023-08-05T06:44:49.018291 | 2019-11-06T19:49:46 | 2019-11-06T19:49:46 | 404,446,010 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,020 | cpp |
#ifndef MAINWINDOW_CPP
#define MAINWINDOW_CPP
#endif
#include "MainWindow.h"
#include "ui_MainWindow.h"
using namespace std;
MainWindow::MainWindow( QWidget *parent ) :
QMainWindow( parent ),
m_ui( new Ui::MainWindow ),
m_timerId ( 0 ),
m_steps ( 0 ),
m_realTime ( 0.0 )
{
m_ui->setupUi( this );
logtimer = new QTimer(this);
blinkTimer = new QTimer(this);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
m_ui->Connection_Status->setTextFormat(Qt::RichText);
m_ui->Connection_Status->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>Disconnected</span>");
m_ui->Pump_status1->setTextFormat(Qt::RichText);
m_ui->Pump_status2->setTextFormat(Qt::RichText);
m_ui->Valve_status1->setTextFormat(Qt::RichText);
m_ui->Valve_status2->setTextFormat(Qt::RichText);
m_ui->Valve_status3->setTextFormat(Qt::RichText);
m_ui->Valve_status4->setTextFormat(Qt::RichText);
m_ui->Pump_status1->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>OFF</span>");
m_ui->Pump_status2->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>OFF</span>");
m_ui->Valve_status1->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>CLOSED</span>");
m_ui->Valve_status2->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>CLOSED</span>");
m_ui->Valve_status3->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>CLOSED</span>");
m_ui->Valve_status4->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>CLOSED</span>");
m_ui->green_1->hide();
m_ui->green_2->hide();
m_ui->green_3->hide();
m_ui->green_4->hide();
m_ui->green_5->hide();
m_ui->green_6->hide();
m_ui->red_1->hide();
m_ui->red_2->hide();
m_ui->red_3->hide();
m_ui->red_4->hide();
m_ui->red_5->hide();
m_ui->red_6->hide();
redLight_1 = 1;
redLight_2 = 1;
redLight_3 = 1;
redLight_4 = 1;
redLight_5 = 1;
redLight_6 = 1;
m_ui->fuel_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO FUEL</span>");
m_ui->P1_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO PR</span>");
m_ui->P2_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO PR</span>");
m_ui->P3_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO PR</span>");
m_ui->P4_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO PR</span>");
m_ui->temp_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO TEMP</span>");
m_ui->Log_frame->setStyleSheet("#Log_frame { border: 3px solid cyan; }");
scrollbar = m_ui->Log_Display->verticalScrollBar();
///////////////////////////////////////////////////////////////////////////////////////////////////////////
PressureGauge1 = new QcGaugeWidget;
PressureGauge1->addBackground(99);
QcBackgroundItem *bkg1 = PressureGauge1->addBackground(92);
bkg1->clearrColors();
bkg1->addColor(float(0.1),Qt::black);
bkg1->addColor(1.0,Qt::white);
QcBackgroundItem *bkg2 = PressureGauge1->addBackground(88);
bkg2->clearrColors();
bkg2->addColor(float(0.1),Qt::darkGray);
bkg2->addColor(1.0,Qt::darkGray);
PressureGauge1->addArc(55);
PressureGauge1->addDegrees(65)->setValueRange(0,50);
PressureGauge1->addColorBand(50);
PressureGauge1->addValues(75)->setValueRange(0,50);
PressureGauge1->addLabel(65)->setText("T1->T3");
QcLabelItem *lab = PressureGauge1->addLabel(40);
lab->setText("0");
Needle1 = PressureGauge1->addNeedle(60);
Needle1->setLabel(lab);
Needle1->setColor(Qt::black);
Needle1->setValueRange(0,50);
PressureGauge1->addBackground(7);
PressureGauge1->addGlass(88);
m_ui->p1_gauge_layout->addWidget(PressureGauge1);
PressureGauge2 = new QcGaugeWidget;
PressureGauge2->addBackground(99);
QcBackgroundItem *bkg3 = PressureGauge2->addBackground(92);
bkg3->clearrColors();
bkg3->addColor(float(0.1),Qt::black);
bkg3->addColor(1.0,Qt::white);
QcBackgroundItem *bkg4 = PressureGauge2->addBackground(88);
bkg4->clearrColors();
bkg4->addColor(float(0.1),Qt::darkGray);
bkg4->addColor(1.0,Qt::darkGray);
PressureGauge2->addArc(55);
PressureGauge2->addDegrees(65)->setValueRange(0,50);
PressureGauge2->addColorBand(50);
PressureGauge2->addValues(75)->setValueRange(0,50);
PressureGauge2->addLabel(65)->setText("T3->T1");
QcLabelItem *lab2 = PressureGauge2->addLabel(40);
lab2->setText("0");
Needle2 = PressureGauge2->addNeedle(60);
Needle2->setLabel(lab2);
Needle2->setColor(Qt::black);
Needle2->setValueRange(0,50);
PressureGauge2->addBackground(7);
PressureGauge2->addGlass(88);
m_ui->p2_gauge_layout->addWidget(PressureGauge2);
PressureGauge3 = new QcGaugeWidget;
PressureGauge3->addBackground(99);
QcBackgroundItem *bkg5 = PressureGauge3->addBackground(92);
bkg5->clearrColors();
bkg5->addColor(float(0.1),Qt::black);
bkg5->addColor(1.0,Qt::white);
QcBackgroundItem *bkg6 = PressureGauge3->addBackground(88);
bkg6->clearrColors();
bkg6->addColor(float(0.1),Qt::darkGray);
bkg6->addColor(1.0,Qt::darkGray);
PressureGauge3->addArc(55);
PressureGauge3->addDegrees(65)->setValueRange(0,50);
PressureGauge3->addColorBand(50);
PressureGauge3->addValues(75)->setValueRange(0,50);
PressureGauge3->addLabel(65)->setText("VENT-L");
QcLabelItem *lab3 = PressureGauge3->addLabel(40);
lab3->setText("0");
Needle3 = PressureGauge3->addNeedle(60);
Needle3->setLabel(lab3);
Needle3->setColor(Qt::black);
Needle3->setValueRange(0,50);
PressureGauge3->addBackground(7);
PressureGauge3->addGlass(88);
m_ui->p3_gauge_layout->addWidget(PressureGauge3);
PressureGauge4 = new QcGaugeWidget;
PressureGauge4->addBackground(99);
QcBackgroundItem *bkg7 = PressureGauge4->addBackground(92);
bkg7->clearrColors();
bkg7->addColor(float(0.1),Qt::black);
bkg7->addColor(1.0,Qt::white);
QcBackgroundItem *bkg8 = PressureGauge4->addBackground(88);
bkg8->clearrColors();
bkg8->addColor(float(0.1),Qt::darkGray);
bkg8->addColor(1.0,Qt::darkGray);
PressureGauge4->addArc(55);
PressureGauge4->addDegrees(65)->setValueRange(0,50);
PressureGauge4->addColorBand(50);
PressureGauge4->addValues(75)->setValueRange(0,50);
PressureGauge4->addLabel(65)->setText("ENG-L");
QcLabelItem *lab4 = PressureGauge4->addLabel(40);
lab4->setText("0");
Needle4 = PressureGauge4->addNeedle(60);
Needle4->setLabel(lab4);
Needle4->setColor(Qt::black);
Needle4->setValueRange(0,50);
PressureGauge4->addBackground(7);
PressureGauge4->addGlass(88);
m_ui->p4_gauge_layout->addWidget(PressureGauge4);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
connect(logtimer, SIGNAL(timeout()),this, SLOT(updateLog()));
connect(blinkTimer, SIGNAL(timeout()),this, SLOT(blink()));
connect(&TCPsocket, SIGNAL(sendUpdate(float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float)), this, SLOT(applyUpdate(float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float)));
connect(&TCPsocket,SIGNAL(updateConnectionStatus(QString)),this,SLOT(connectionStatus(QString))); // Connection Status Signal
connect(this,SIGNAL(retrySignal()),&TCPsocket,SLOT(retry())); // Retry Button Signal
connect(this, SIGNAL(requestData()),&TCPsocket, SLOT(requestSignal()));
///////////////////////////////////////////////////////////////////////////////////////////////////////////
TCPsocket.moveToThread(&socketThread);
socketThread.start();
emit retrySignal();
///////////////////////////////////////////////////////////////////////////////////////////////////////////
m_timerId = startTimer( 0 );
m_time.start();
logtimer->start(1000);
blinkTimer->start(500);
}
///////////////////////////////// MainWindow Destructor ///////////////////////////////////////////////////////
MainWindow::~MainWindow() // Main Window Destructor
{
socketThread.quit();
socketThread.wait();
cout << "Average time step: " << ( double(m_realTime) ) / ( double(m_steps )) << " s" << endl;
if ( m_timerId ) killTimer( m_timerId );
if ( m_ui )
{
delete m_ui;
}
m_ui = nullptr;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void MainWindow::timerEvent( QTimerEvent *event )
{
/////////////////////////////////
QMainWindow::timerEvent( event );
/////////////////////////////////
float timeStep = m_time.restart();
m_realTime = m_realTime + timeStep / 1000.0f;
emit requestData();
m_ui->Temp_display->display(double(temp));
m_ui->PP1_display->display(double(pres1));
m_ui->PP2_display->display(double(pres2));
m_ui->PP3_display->display(double(pres3));
m_ui->EPP_display->display(double(EnPres));
Needle1->setCurrentValue(pres1);
Needle2->setCurrentValue(pres2);
Needle3->setCurrentValue(pres3);
Needle4->setCurrentValue(EnPres);
m_ui->FWD_vol->display(double(vol1));
m_ui->MID_vol->display(double(vol2));
m_ui->REAR_vol->display(double(vol3));
m_ui->LT_vol_display->display(double(vol4));
m_ui->RT_vol_display->display(double(vol5));
m_ui->Lvl1_display->display(double(lvl1));
m_ui->Lvl2_display->display(double(lvl2));
m_ui->Lvl3_display->display(double(lvl3));
m_ui->Lvl4_display->display(double(lvl4));
m_ui->Lvl5_display->display(double(lvl5));
m_ui->TankFWD->setValue(int(per1));
m_ui->TankMID->setValue(int(per2));
m_ui->TankREAR->setValue(int(per3));
m_ui->RTank->setPercentage(int(per4));
m_ui->LTank->setPercentage(int(per5));
m_ui->TankFWD->setFormat("FWD: "+QString::number(double(per1))+"%"+" | "+QString::number(double(vol1))+"L");
m_ui->TankMID->setFormat("MID: "+QString::number(double(per2))+"%"+" | "+QString::number(double(vol2))+"L");
m_ui->TankREAR->setFormat("REAR: "+QString::number(double(per3))+"%"+" | "+QString::number(double(vol3))+"L");
m_ui->TankFWD->update();
m_ui->TankMID->update();
m_ui->TankREAR->update();
updatePumpandValves();
checkWarnings();
m_ui->datetime_label->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
m_steps++;
}
void MainWindow::applyUpdate(float data1, float data2, float data3, float data4, float data5, float data6, float data7, float data8, float data9, float data10, float data11, float data12, float data13, float data14, float data15, float data16, float data17, float data18, float data19, float data20, float data21, float data22, float data23, float data24, float data25, float data26, float data27, float data28, float data29, float data30, float data31, float data32, float data33, float data34, float data35, float data36, float data37, float data38, float data39, float data40)
{
roll = data1;
pitch = data2;
heading = data3;
temp = data4;
per1 = data5;
per2 = data6;
per3 = data7;
per4 = data8;
per5 = data9;
mass1 = data10;
mass2 = data11;
mass3 = data12;
mass4 = data13;
mass5 = data14;
vol1 = data15;
vol2 = data16;
vol3 = data17;
vol4 = data18;
vol5 = data19;
lvl1 = data20;
lvl2 = data21;
lvl3 = data22;
lvl4 = data23;
lvl5 = data24;
// pressure1 = data;
// pressure2 = data;
// pressure3 = data;
// EPres = data;
// Pump_state1 = data;
// Pump_state2 = data;
// Valve_state1 = data;
// Valve_state2 = data;
// Valve_state3 = data;
// Valve_state4 = data;
// CGx = data;
// CGy = data;
// av_fuel = data;
// ffr = data;
// con_fuel = data;
}
void MainWindow::updateLog()
{
scrollbar->setValue(scrollbar->maximum());
m_ui->Log_Display->insertPlainText(QDateTime::currentDateTime().toString("[yyyy-MM-dd HH:mm:ss] ") + "pitch: " + QString::number(double(pitch)) + ", roll: " + QString::number(double(roll)) + ", heading: " + QString::number(double(heading)) + ", temp: " + QString::number(double(temp)) + ", perFWD: " + QString::number(double(per1)) + ", perMID: " + QString::number(double(per2)) + ", perREAR: " + QString::number(double(per3)) + ", perLT: " + QString::number(double(per4)) + ", perRT: " + QString::number(double(per5)) + ", massFWD: " + QString::number(double(mass1)) + ", massMID: " + QString::number(double(mass2)) + ", massREAR: " + QString::number(double(mass3)) + ", massLT: " + QString::number(double(mass4)) + ", massRT: " + QString::number(double(mass5)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + ", roll: " + QString::number(double(roll)) + "\n");
}
void MainWindow::blink()
{
if(trigger == 0)
{
if(redLight_1 == 1)
{
m_ui->red_1->show();
}
else
{
m_ui->green_1->show();
}
if(redLight_2 == 1)
{
m_ui->red_2->show();
}
else
{
m_ui->green_2->show();
}
if(redLight_3 == 1)
{
m_ui->red_3->show();
}
else
{
m_ui->green_3->show();
}
if(redLight_4 == 1)
{
m_ui->red_4->show();
}
else
{
m_ui->green_4->show();
}
if(redLight_5 == 1)
{
m_ui->red_5->show();
}
else
{
m_ui->green_5->show();
}
if(redLight_6 == 1)
{
m_ui->red_6->show();
}
else
{
m_ui->green_6->show();
}
trigger = 1;
}
else
{
if(redLight_1 == 1)
{
m_ui->red_1->hide();
}
else
{
m_ui->green_1->hide();
}
if(redLight_2 == 1)
{
m_ui->red_2->hide();
}
else
{
m_ui->green_2->hide();
}
if(redLight_3 == 1)
{
m_ui->red_3->hide();
}
else
{
m_ui->green_3->hide();
}
if(redLight_4 == 1)
{
m_ui->red_4->hide();
}
else
{
m_ui->green_4->hide();
}
if(redLight_5 == 1)
{
m_ui->red_5->hide();
}
else
{
m_ui->green_5->hide();
}
if(redLight_6 == 1)
{
m_ui->red_6->hide();
}
else
{
m_ui->green_6->hide();
}
trigger = 0;
}
}
void MainWindow::connectionStatus(QString status)
{
ConnectionStatusLogin = status;
if(status == "Connected")
{
m_ui->Connection_Status->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>Connected</span>");
}
else if(status == "Retrying")
{
m_ui->Connection_Status->setText("<span style=' font-size:14pt; font-weight:600; color:#ffaa00;'>Connecting</span>");
}
else
{
m_ui->Connection_Status->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>Disconnected</span>");
}
}
void MainWindow::updatePumpandValves()
{
if(Pump_state1 == 1)
{
m_ui->Pump_status1->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>ON</span>");
}
else
{
m_ui->Pump_status1->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>OFF</span>");
}
if(Pump_state2 == 1)
{
m_ui->Pump_status2->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>ON</span>");
}
else
{
m_ui->Pump_status2->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>OFF</span>");
}
if(Valve_state1 == 1)
{
m_ui->Valve_status1->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>OPEN</span>");
}
else
{
m_ui->Valve_status1->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>CLOSED</span>");
}
if(Valve_state2 == 1)
{
m_ui->Valve_status2->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>OPEN</span>");
}
else
{
m_ui->Valve_status2->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>CLOSED</span>");
}
if(Valve_state3 == 1)
{
m_ui->Valve_status3->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>OPEN</span>");
}
else
{
m_ui->Valve_status3->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>CLOSED</span>");
}
if(Valve_state4 == 1)
{
m_ui->Valve_status4->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>OPEN</span>");
}
else
{
m_ui->Valve_status4->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>CLOSED</span>");
}
}
void MainWindow::checkWarnings()
{
if(av_fuel <= 70)
{
m_ui->fuel_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO FUEL</span>");
redLight_1 = 1;
}
else
{
m_ui->fuel_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>NORMAL</span>");
redLight_1 = 0;
}
if(pres1 <= 20 && pres1 >= 12)
{
m_ui->P1_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>NORMAL</span>");
redLight_4 = 0;
}
else if(pres1 > 20)
{
m_ui->P1_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>HI PR</span>");
redLight_4 = 1;
}
else
{
m_ui->P1_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO PR</span>");
redLight_4 = 1;
}
if(pres2 <= 20 && pres2 >= 12)
{
m_ui->P2_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>NORMAL</span>");
redLight_5 = 0;
}
else if(pres2 > 20)
{
m_ui->P2_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>HI PR</span>");
redLight_5 = 1;
}
else
{
m_ui->P2_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO PR</span>");
redLight_5 = 1;
}
if(pres3 <= 20 && pres3 >= 12)
{
m_ui->P3_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>NORMAL</span>");
redLight_2 = 0;
}
else if(pres3 > 20)
{
m_ui->P3_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>HI PR</span>");
redLight_2 = 1;
}
else
{
m_ui->P3_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO PR</span>");
redLight_2 = 1;
}
if(EnPres <= 40 && EnPres >= 20)
{
m_ui->P4_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>NORMAL</span>");
redLight_3 = 0;
}
else if(EnPres > 20)
{
m_ui->P4_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>HI PR</span>");
redLight_3 = 1;
}
else
{
m_ui->P4_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO PR</span>");
redLight_3 = 1;
}
if(temp <= 50 && temp >= 0)
{
m_ui->temp_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#00ff00'>NORMAL</span>");
redLight_6 = 0;
}
else if(temp > 50)
{
m_ui->temp_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>HI TEMP</span>");
redLight_6 = 1;
}
else
{
m_ui->temp_status_ind->setText("<span style=' font-size:14pt; font-weight:600; color:#ff0000'>LO TEMP</span>");
redLight_6 = 1;
}
}
void MainWindow::on_Retrybutton_clicked()
{
emit retrySignal();
}
| [
"metal.striker.xlr@gmail.com"
] | metal.striker.xlr@gmail.com |
d7969f24ab4766c0033ea724f765f3afb03f386c | 61223eee05ad0179788931e35f4db59a896a2bd0 | /lib/bbq/NTCSensor.cpp | 997ba1e9c1b0adfc24ff468757ea98cadda04da5 | [
"MIT"
] | permissive | rvt/bbq-controller | 60155717c0ec33b327d74203f14e6ed6ffcc0ae0 | a70f13dfc1c53dc6416fff2fa4ef9e393884dab5 | refs/heads/master | 2022-05-01T23:14:02.520911 | 2022-04-10T18:32:13 | 2022-04-10T18:32:13 | 164,915,821 | 24 | 3 | MIT | 2020-08-19T18:45:53 | 2019-01-09T18:25:35 | C++ | UTF-8 | C++ | false | false | 3,833 | cpp | #include "NTCSensor.h"
#include <math.h>
#ifndef UNIT_TEST
#include <Arduino.h>
#else
extern "C" uint32_t analogRead(uint8_t);
#define INPUT_PULLUP 2
#define A0 0xa0
#endif
constexpr float ZERO_KELVIN = -273.15f;
NTCSensor::NTCSensor(int8_t p_pin, int16_t p_offset, float p_r1, float p_ka, float p_kb, float p_kc) :
NTCSensor(p_pin, false, p_offset, 0.1f, p_r1, p_ka, p_kb, p_kc) {
}
NTCSensor::NTCSensor(int8_t p_pin, bool p_upDownStream, int16_t p_offset, float p_alpha, float p_r1, float p_ka, float p_kb, float p_kc) :
TemperatureSensor(),
m_pin(p_pin),
m_upDownStream(p_upDownStream),
m_offset(p_offset),
m_alpha(p_alpha),
m_r1(p_r1),
m_ka(p_ka),
m_kb(p_kb),
m_kc(p_kc),
m_lastTemp(0.0f),
m_recover(0),
m_state(READY) {
#if defined(ESP32)
analogReadResolution(12);
// These two do not work, possible because we take to much time between start and end??
// analogSetSamples(4);
// analogSetClockDiv(1);
// End
analogSetPinAttenuation(m_pin, ADC_11db); // ADC_11db to measure 0--3.3V
adcAttachPin(m_pin);
#elif defined(ESP8266)
#endif
}
float NTCSensor::get() const {
return m_lastTemp;
}
// Calculations based on https://create.arduino.cc/projecthub/iasonas-christoulakis/make-an-arduino-temperature-sensor-thermistor-tutorial-b26ed3
// With an additional filter
#if defined(ESP32)
void NTCSensor::handle() {
switch (m_state) {
case READY:
adcStart(m_pin);
m_state = BUZY;
m_recover = 0;
break;
case BUZY:
if (!adcBusy(m_pin)) {
m_state = DONE;
} else if (++m_recover == 255) {
m_state = READY;
}
break;
case DONE:
// TODO: SEE https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html
// Iw possible we can read the internal calibration of the reference voltage
m_state = READY;
float R2;
if (m_upDownStream) {
R2 = m_r1 * (4095.0f / (adcEnd(m_pin) + m_offset) - 1.0f);
} else {
R2 = m_r1 / (4095.0f / (adcEnd(m_pin) + m_offset) - 1.0f);
}
float logR2 = log(R2);
float degreesC = m_ka + m_kb * logR2 + m_kc * logR2 * logR2 * logR2;
degreesC = 1.0f / degreesC + ZERO_KELVIN;
// T = (T * 9.0f) / 5.0f + 32.0f;
// float farenheit = ((degreesC * 9) / 5) + 32.
// Filter
m_lastTemp = m_lastTemp + (degreesC - m_lastTemp) * m_alpha;
break;
}
}
#elif defined(ESP8266)
// This portion of code was not tested on ESP2866
void NTCSensor::handle() {
float R2;
if (m_upDownStream) {
R2 = m_r1 * (1023.0f / (analogRead(A0) + m_offset) - 1.0f);
} else {
R2 = m_r1 / (1023.0f / (analogRead(A0) + m_offset) - 1.0f);
}
float logR2 = log(R2);
float degreesC = m_ka + m_kb * logR2 + m_kc * logR2 * logR2 * logR2;
degreesC = 1.0f / degreesC + ZERO_KELVIN;
// T = (T * 9.0f) / 5.0f + 32.0f;
// float farenheit = ((degreesC * 9) / 5) + 32.
// Filter
m_lastTemp = m_lastTemp + (degreesC - m_lastTemp) * m_alpha;
}
#endif
void NTCSensor::calculateSteinhart(float r, float r1, float t1, float r2, float t2, float r3, float t3, float& a, float& b, float& c) {
float l1 = log(r1);
float l2 = log(r2);
float l3 = log(r3);
float y1 = 1.0f / (t1 - ZERO_KELVIN);
float y2 = 1.0f / (t2 - ZERO_KELVIN);
float y3 = 1.0f / (t3 - ZERO_KELVIN);
float g2 = (y2 - y1) / (l2 - l1);
float g3 = (y3 - y1) / (l3 - l1);
c = (g3 - g2) / (l3 - l2) * 1.0f / (l1 + l2 + l3);
b = g2 - c * (l1 * l1 + l1 * l2 + l2 * l2);
a = y1 - (b + l1 * l1 * c) * l1;
}
| [
"github@rvt.dds.nl"
] | github@rvt.dds.nl |
8a19e680a087933748ea5095485f9a8fb18cd0d2 | 0ff6579660ccf6d912bf613f58fab80abcfae87f | /main.cpp | eb7f56a34c59eadaf499753b35d423f2c726825a | [] | no_license | karolinneoc/ElRefPattern | e680e907e5be484fbfa81d69d8fccb0a00ad1db5 | 2c84e4cfe5b34441e9b3f77a7f3404e2cc0d8b37 | refs/heads/master | 2020-08-04T16:41:30.047768 | 2019-10-11T14:03:16 | 2019-10-11T14:03:16 | 212,206,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,405 | cpp | #include "mkl.h"
#include "pzmatrix.h"
#include "TPZPardisoControl.h"
#include "pzcmesh.h"
#include "pzgengrid.h"
#include "TPZMatLaplacian.h"
#include "pzbndcond.h"
#include "pzanalysis.h"
#include "TPZVTKGeoMesh.h"
#include "pzgnode.h"
#include "TPZRefPattern.h"
#include "TPZRefPatternTools.h"
#include "TPZGeoElRefPattern.h"
#include "pzgmesh.h"
enum MMATID {EGroup, Ebc1, Ebc2, Ebc3, Ebc4, Emat1};
int main(){
MElementType element = EQuadrilateral;
bool solve = true;
bool RefinementPattern = false;
int porder = 1;
if(element == EQuadrilateral){
TPZGeoMesh *gmesh = new TPZGeoMesh();
gmesh->NodeVec().Resize(6);
for (int i=0; i<6; i++) {
TPZManVector<REAL,4> x(3,0);
if (i>2) {
x[1]=1;
}
if (i==1 || i==4){
x[0]=1;
} else if (i==2 || i==5){
x[0]=2;
}
TPZGeoNode node;
node.Initialize(x, *gmesh);
gmesh->NodeVec()[i] = node;
// gmesh->NodeVec()[i].SetCoord(i,x);
// gmesh->NodeVec()[i].SetNodeId(i);
}
TPZVec<int64_t> cornerindexes(4,0);
cornerindexes[0]=0;cornerindexes[1]=1;cornerindexes[2]=4;cornerindexes[3]=3;
int64_t index = 0;
TPZGeoEl *gel = gmesh->CreateGeoElement(EQuadrilateral, cornerindexes, EGroup, index);
cornerindexes[0]=1;cornerindexes[1]=2;cornerindexes[2]=5;cornerindexes[3]=4;
index=1;
gel = gmesh->CreateGeoElement(EQuadrilateral, cornerindexes, EGroup, index);
gmesh->BuildConnectivity();
TPZVec<TPZGeoEl *> subel;
gmesh->Element(0)->Divide(subel);
gmesh->BuildConnectivity();
gmesh->Print();
std::ofstream out("Geometry.vtk");
TPZVTKGeoMesh vtk;
vtk.PrintGMeshVTK(gmesh, out, true);
if(RefinementPattern){
TPZGeoMesh *gmesh2 = new TPZGeoMesh(*gmesh);
gmesh2->BuildConnectivity();
int nnodes = gmesh->NNodes();
gmesh->NodeVec().Resize(nnodes +2);
TPZVec<REAL> x(3,0);
x[0]=-0.5;x[1]=-1;
gmesh->NodeVec()[nnodes].Initialize(nnodes, x, *gmesh);
x[0]=0.9;x[1]=1;
gmesh->NodeVec()[nnodes+1].Initialize(nnodes+1, x, *gmesh);
cornerindexes[0]=0;cornerindexes[1]=1;cornerindexes[2]=4;cornerindexes[3]=5;
index = 1;
gmesh->CreateGeoElement(EQuadrilateral, cornerindexes, EGroup, index);
cornerindexes[0]=1;cornerindexes[1]=2;cornerindexes[2]=3;cornerindexes[3]=4;
index = 2;
gmesh->CreateGeoElement(EQuadrilateral, cornerindexes, EGroup, index);
gmesh->Element(1)->SetFather(gmesh->Element(0));
gmesh->Element(2)->SetFather(gmesh->Element(0));
gmesh->BuildConnectivity();
gmesh->Print(std::cout);
std::ofstream out("Geometry.vtk");
TPZVTKGeoMesh vtk;
vtk.PrintGMeshVTK(gmesh, out, true);
TPZRefPattern *ref = new TPZRefPattern(*gmesh);
ref->SetName("Karol");
TPZAutoPointer<TPZRefPattern> autoref(ref);
gRefDBase.InsertRefPattern(autoref);
autoref->InsertPermuted();
auto karol = gRefDBase.FindRefPattern("Karol");
TPZVec<TPZGeoEl *> gelvec;
// gmesh2->Element(0)->SetRefPattern(karol);
gmesh2->Element(0)->Divide(gelvec);
gmesh2->Element(1)->SetRefPattern(karol);
gmesh2->Element(1)->Divide(gelvec);
std::ofstream out2("Geometry2.vtk");
TPZVTKGeoMesh vtk2;
vtk2.PrintGMeshVTK(gmesh2, out2, true);
for(int i=4;i<6;i++){
std::map<int, std::pair<TPZGeoEl *, std::map<int,int> > > neighCorresp;
TPZRefPatternTools::ModelRefPattern(gmesh2->Element(i),neighCorresp);
TPZAutoPointer<TPZRefPattern> ref = TPZRefPatternTools::DragModelPatNodes(gmesh2->Element(i), karol,neighCorresp);
gmesh2->Element(i)->SetRefPattern(ref);
// gmesh2->Element(1)->SetRefPattern();
gmesh2->Element(i)->Divide(gelvec);
std::ofstream out2("Geometry2.vtk");
TPZVTKGeoMesh vtk2;
vtk2.PrintGMeshVTK(gmesh2, out2, true);
}
// for(int i=0;i<600;i++){
// gmesh2->Element(i)->SetRefPattern(karol);
// gmesh2->Element(i)->Divide(gelvec);
// }
std::cout << gmesh2->NElements() << std::endl;
std::ofstream out3("Geometry3.vtk");
TPZVTKGeoMesh vtk3;
vtk3.PrintGMeshVTK(gmesh2, out3, true);
}
if(solve){
gmesh->Element(0)->CreateBCGeoEl(4, -Ebc1);
gmesh->Element(0)->CreateBCGeoEl(6, -Ebc1);
gmesh->Element(0)->CreateBCGeoEl(7, -Ebc1);
gmesh->Element(1)->CreateBCGeoEl(4, -Ebc1);
gmesh->Element(1)->CreateBCGeoEl(5, -Ebc1);
gmesh->Element(1)->CreateBCGeoEl(6, -Ebc1);
TPZCompMesh *cmesh = new TPZCompMesh(gmesh);
cmesh->SetDefaultOrder(porder);
cmesh->SetDimModel(2);
TPZMatLaplacian *matloc = new TPZMatLaplacian(EGroup);
matloc->SetDimension(2);
matloc->SetSymmetric();
TPZMaterial *material;
material = matloc;
int nstate = 1;
TPZFMatrix<STATE> val1(nstate,nstate,0.), val2(nstate,1,0.);
TPZMaterial * BCond1 = material->CreateBC(material,-Ebc1,0, val1, val2);
cmesh->InsertMaterialObject(material);
cmesh->InsertMaterialObject(BCond1);
// cmesh->SetAllCreateFunctionsContinuous();
cmesh->SetAllCreateFunctionsHDiv();
cmesh->AutoBuild();
std::ofstream file("cmeshhdiv.dat");
cmesh->Print(file);
TPZAnalysis * Analysis = new TPZAnalysis(cmesh,true);
Analysis->Run();
TPZFMatrix<REAL> sol = Analysis->Solution();
bool plotshape = true;
if(plotshape)
{
TPZFMatrix<REAL> sol0 = sol;
for (int i=0; i<sol0.Rows() ;i++){
TPZFNMatrix<3,REAL> sol = cmesh->Solution();
sol.Zero();
sol(i,0) = 1;
cmesh->LoadSolution(sol);
Analysis->LoadSolution(sol);
TPZStack<std::string> vecnames,scalnames;
// scalar
scalnames.Push("State");
Analysis->DefineGraphMesh(2, scalnames, vecnames, "../ShapeFunctions.vtk");
Analysis->PostProcess(3);
}
cmesh->LoadSolution(sol0);
Analysis->LoadSolution(sol0);
}
}
} else if (element == ETriangle){
TPZManVector<REAL,4> x0(3,-1.),x1(3,1.),x2(3,1.);
x0[0] = 0;
x0[1] = 0;
x0[2] = 0;
x1[0] = 1;
x1[1] = 0;
x1[2] = 0;
x2[0] = 0;
x2[1] = 1;
x2[2] = 0;
TPZGeoMesh *gmesh = new TPZGeoMesh();
gmesh->NodeVec().Resize(3);
gmesh->NodeVec()[0].SetCoord(x0);
gmesh->NodeVec()[1].SetCoord(x1);
gmesh->NodeVec()[2].SetCoord(x2);
gmesh->NodeVec()[0].SetNodeId(0);
gmesh->NodeVec()[1].SetNodeId(1);
gmesh->NodeVec()[2].SetNodeId(2);
TPZVec<int64_t> cornerindexes(3,0);
cornerindexes[0]=0;cornerindexes[1]=1;cornerindexes[2]=2;
int64_t index = 0;
gmesh->CreateGeoElement(ETriangle, cornerindexes, EGroup, index);
gmesh->BuildConnectivity();
gmesh->Element(0)->CreateBCGeoEl(3, -Ebc1);
gmesh->Element(0)->CreateBCGeoEl(4, -Ebc2);
gmesh->Element(0)->CreateBCGeoEl(5, -Ebc3);
std::ofstream out("Geometry.vtk");
TPZVTKGeoMesh vtk;
vtk.PrintGMeshVTK(gmesh, out, true);
TPZCompMesh *cmesh = new TPZCompMesh(gmesh);
cmesh->SetDefaultOrder(porder);
TPZMatLaplacian *matloc = new TPZMatLaplacian(EGroup);
matloc->SetDimension(2);
matloc->SetSymmetric();
TPZMaterial *material;
material = matloc;
int nstate = 1;
TPZFMatrix<STATE> val1(nstate,nstate,0.), val2(nstate,1,0.);
TPZMaterial * BCond1 = material->CreateBC(material,-Ebc1,0, val1, val2);
TPZMaterial * BCond2 = material->CreateBC(material,-Ebc2,0, val1, val2);
TPZMaterial * BCond3 = material->CreateBC(material,-Ebc3,0, val1, val2);
cmesh->InsertMaterialObject(material);
cmesh->InsertMaterialObject(BCond1);
cmesh->InsertMaterialObject(BCond2);
cmesh->InsertMaterialObject(BCond3);
cmesh->SetAllCreateFunctionsContinuous();
cmesh->AutoBuild();
TPZAnalysis * Analysis = new TPZAnalysis(cmesh,true);
Analysis->Run();
TPZFMatrix<REAL> sol = Analysis->Solution();
bool plotshape = true;
if(plotshape)
{
TPZFMatrix<REAL> sol0 = sol;
for (int i=0; i<sol0.Rows() ;i++){
TPZFNMatrix<3,REAL> sol = cmesh->Solution();
sol.Zero();
sol(i,0) = 1;
cmesh->LoadSolution(sol);
Analysis->LoadSolution(sol);
TPZStack<std::string> vecnames,scalnames;
// scalar
scalnames.Push("State");
Analysis->DefineGraphMesh(2, scalnames, vecnames, "../ShapeFunctions.vtk");
Analysis->PostProcess(3);
}
cmesh->LoadSolution(sol0);
Analysis->LoadSolution(sol0);
}
}
return 0;
}
| [
"30835631+karolinneoc@users.noreply.github.com"
] | 30835631+karolinneoc@users.noreply.github.com |
960e7e2a1d2b61a7bb4282f33b27ff43f961b6d0 | 935fa4f586f4990b506a693dff8945d2b7f9c677 | /afl/net/http/chunkedsink.hpp | 25cee37d8e30f6b88fff2d338e8bafcb8602da5d | [] | no_license | stefanreuther/afl | 8e96be19a502463cdb72b42b6042cdd6869ecf0b | 35d2eb7c6be1a3aebfdf1ce046e6e1310dc7caf8 | refs/heads/master | 2023-07-20T11:12:27.849160 | 2023-05-07T11:03:03 | 2023-05-07T11:03:03 | 69,809,604 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,313 | hpp | /**
* \file afl/net/http/chunkedsink.hpp
* \brief Class afl::net::http::ChunkedSink
*/
#ifndef AFL_AFL_NET_HTTP_CHUNKEDSINK_HPP
#define AFL_AFL_NET_HTTP_CHUNKEDSINK_HPP
#include <memory>
#include "afl/io/datasink.hpp"
#include "afl/io/stream.hpp"
#include "afl/base/uncopyable.hpp"
namespace afl { namespace net { namespace http {
/** HTTP "chunked" encoding decoder.
Decodes a chunked body and gives the decoded data to another DataSink.
Grammar according to RFC 2616:
<pre>
Chunked-Body = *chunk
last-chunk
trailer
CRLF
chunk = chunk-size [ chunk-extension ] CRLF
chunk-data CRLF
chunk-size = 1*HEX
last-chunk = 1*("0") [ chunk-extension ] CRLF
chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
chunk-ext-name = token
chunk-ext-val = token | quoted-string
chunk-data = chunk-size(OCTET)
trailer = *(entity-header CRLF)
</pre>
chunk-extension and trailer are completely ignored. */
class ChunkedSink : public afl::io::DataSink, private afl::base::Uncopyable {
public:
/** Constructor.
\param peer Target sink that receives data. Lifetime must exceed that of the ChunkedSink. */
ChunkedSink(afl::io::DataSink& peer);
/** Destructor. */
virtual ~ChunkedSink();
// DataSink:
virtual bool handleData(afl::base::ConstBytes_t& data);
private:
enum State {
ChunkSize, // reading hex digits
Extension, // skipping to EOL
Payload, // reading payload
PayloadEnd, // reading the CRLF after the payload
Trailer, // reading the file trailer
TrailerHeader, // reading a header in the file trailer
Final // final state reached, not reading anymore
};
State m_state;
afl::io::DataSink& m_peer;
afl::io::Stream::FileSize_t m_size;
};
} } }
#endif
| [
"streu@gmx.de"
] | streu@gmx.de |
1b23acc0c1c2541890b43a70340c04a0fbbfd523 | b42365c7502900abe47669cfce630e360cc9156b | /src/engine/3dsLoader.h | 6a03bbf641cb5e1284f7bd87c3d8d3726ae8a3e1 | [
"BSD-3-Clause"
] | permissive | ycaihua/arbarlith2 | 0686bacfad3414f04a4ce655ea0cad0bd754d53c | 820ffc8c3efcb636eb2c639487815fb9aabdc82e | refs/heads/master | 2020-12-07T02:34:25.117495 | 2010-08-25T03:38:21 | 2010-08-25T03:38:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,670 | h | /*
Author: Andrew Fox
E-Mail: mailto:foxostro@gmail.com
Copyright (c) 2007,2009 Game Creation Society
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Game Creation Society 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 Game Creation Society ``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 Game Creation Society BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _3DSLOADER_H_
#define _3DSLOADER_H_
#include "ModelLoader.h"
namespace Engine {
/** 3DS model loader */
class _3dsLoader : public ModelLoader
{
private:
/**
Loads a model from file
@param fileName The file name of the model
*/
virtual AnimationController* loadFromFile(const string &fileName) const;
/** Attach material data to the model */
class Wrapper
{
private:
vector<Material> materials;
public:
Model model;
void addMaterial(const Material &material)
{
materials.push_back(material); // copy the material
}
Material& getMostRecentMaterial(void)
{
ASSERT(!materials.empty(), "no materials to get");
return materials[materials.size()-1];
}
Material& getMaterial(const string &materialName)
{
ASSERT(!materials.empty(), "no materials to get");
for(size_t i=0; i<materials.size(); ++i)
{
if(materialName == materials[i].getName())
return materials[i];
}
FAIL("failed to retrieve material: " + materialName);
return materials[0]; // return anything at all
}
};
/** structure for 3DS indices (since .3DS stores 4 unsigned shorts) */
struct Indices
{
/** This will hold point1, 2, and 3 index's into the vertex array plus a visible flag */
unsigned short a, b, c, bVisible;
};
/** Generic chunk */
class Chunk : public File
{
public:
/**
Constructs a chunk by reading it out of a parent chunk
@param parentChunk The parent chunk to read the chunk from
*/
Chunk(Chunk &parentChunk);
/**
Constructs a chunk by reading it out of a file
@param file The file to read the chunk from
*/
Chunk(File &file);
/**
Reads a string from file
@param file the file is assumed to be seek'd to the positon of the string
@param s returns the string that was read
@return the number of bytes read (including the null terminator)
*/
int getString(char *s);
/**
get the chunk ID
@return ID
*/
unsigned short int getID(void) const
{
return ID;
}
private:
/** The chunk's ID */
unsigned short int ID;
};
/**
Loads a single model from file
@param fileName File name of the 3DS model
@return Model
*/
Engine::Model loadKeyFrame(const string &fileName) const;
/**
Reads the next large chunk
@param parentChunk The parent chunk
@param wrapper the partially loaded model
*/
void processNextChunk(Chunk &parentChunk, Wrapper &wrapper) const;
/**
Processes the version data
@param file Assumes that the file is seek'd to the data section
@param currentChunk chunk data
*/
void processVersionChunk(Chunk ¤tChunk) const;
/**
Processes the object info data
@param currentChunk chunk data
@param wrapper the partially loaded model
*/
void processObjectInfoChunk(Chunk ¤tChunk, Wrapper &wrapper) const;
/**
Processes the object data
@param currentChunk chunk data
@param wrapper the partially loaded model
*/
void processObjectChunk(Chunk ¤tChunk, Wrapper &wrapper) const;
/**
Processes a material chunk
@param currentChunk chunk data
@param model the partially loaded model
*/
void processMaterialChunk(Chunk &parentChunk, Wrapper &wrapper) const;
/**
Reads the next object chunk
@param currentChunk the current chunk
@param wrapper the partially loaded model
@param mesh the next mesh allocated for the model
*/
void processNextObjectChunk(Chunk ¤tChunk, Wrapper &wrapper, Mesh *mesh) const;
/**
Reads the next material chunk
@param currentChunk chunk data
@param material partially loaded material
*/
void processNextMaterialChunk(Chunk ¤tChunk, Material &material) const;
/**
Reads the objects vertices
@param currentChunk Chunk data
@param mesh partially loaded mesh
*/
void readVertices(Chunk ¤tChunk, Mesh *mesh) const;
/**
Because 3D Studio Max Models with the Z-Axis pointing up, we
need to flip the y values with the z values in our vertices.
That way it will be normal, with Y pointing up.
@param mesh partially loaded mesh
*/
void fixVertices(Mesh *mesh) const;
/**
Truespace defaults to having the front view face the opposite direction on the Z-Axis
It is a lot easier to fix it here than to try to get an artist to fix the models...
@param mesh partially loaded mesh
*/
void fixTrueSpaceVertices(Engine::Model &model) const;
/**
Truespace defaults to having the front view face the opposite direction on the Z-Axis
It is a lot easier to fix it here than to try to get an artist to fix the models...
@param mesh partially loaded mesh
*/
void fixTrueSpaceVertices(Mesh *mesh) const;
/**
Removes and frees degenerate meshes within the model
@param mesh partially loaded mesh
*/
void cullDegenerateMeshes(Engine::Model &model) const;
/**
Generate surface normals for the loaded vertices and faces
@param mesh partially loaded mesh
*/
void generateNormals(Mesh *mesh) const;
/**
Reads the objects face information
@param currentChunk Chunk data
@param wrapper partially loaded mesh
*/
void readVertexIndices(Chunk ¤tChunk, Wrapper &wrapper, Mesh *mesh) const;
/**
Reads the texture coordinates of the object
@param currentChunk Chunk data
@param mesh partially loaded mesh
*/
void readUVCoordinates(Chunk ¤tChunk, Mesh *mesh) const;
/**
Reads in the material name assigned to the object and sets the materialID
@param currentChunk Chunk data
@param wrapper partially loaded model
@param mesh partially loaded mesh
*/
void readObjectMaterial(Chunk ¤tChunk, Wrapper &wrapper, Mesh *mesh) const;
/**
Reads the material name
@param currentChunk chunk data
@param material current material
*/
void readMaterialName(Chunk ¤tChunk, Material &material) const;
/**
Reads the material texture file
@param currentChunk chunk data
@param material current material
*/
void readMaterialMapFile(Chunk ¤tChunk, Material &material) const;
/**
Forces the skin to the specified value
@param model The model to alter
@param skinFileName The filename of the skin
*/
void forceSkin(Engine::Model &model, const string &skinFileName) const;
};
} // namespace Engine
#endif
| [
"foxostro@gmail.com"
] | foxostro@gmail.com |
254d6d7f60970a5ff27be6920180377401c10caf | eaca1e6d0be15e436f029e9279e4db838091dc38 | /Graphs/dft.cpp | 2fc98b72e5f45dbd4d2e2f076bc6e93ce7357697 | [] | no_license | SaketNarayane/Data-Structure-and-Algorithm | 4f4a9ab36237d79b7696b04c197f9741e2422732 | 212242e488d5210e73e9dc39f7a71dfcd2e3846b | refs/heads/master | 2023-03-15T20:22:27.282115 | 2023-03-09T13:52:19 | 2023-03-09T13:52:19 | 101,810,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | cpp | #include<iostream>
#include<list>
using namespace std;
int l1[] = {2,3,5};
list<int>l1 (l1,l1+sizeof(l1)/sizeof (int));
int l2[] = {1,3,4};
list<int>l2 (l2,l2+sizeof(l2)/sizeof (int));
int l3[] = {1,2,4};
list<int>l3 (l3,l3+sizeof(l3)/sizeof (int));
int l4[] = {2,3,5};
list<int>l4 (l4,l4+sizeof(l4)/sizeof (int));
int l5[] = {1,4};
list<int>l5 (l5,l5+sizeof(l5)/sizeof (int));
void DFT(int a)
{
}
int main()
{
// for(list<int>::iterator it = l.begin(); it != l.end(); it++)
// cout<<*it;
return 0;
}
| [
"noreply@github.com"
] | SaketNarayane.noreply@github.com |
42d78e6dc50ba65a998f75af5136b5e53369ab21 | db3562d8fa915393c7ffa760af62647ebccf8212 | /common/src/colorf.hpp | ac84d2e9456baca390f255e7c80870d5ab032be6 | [] | no_license | haoqoo/mir2x | 1269cf2ab70a7664a5565a6a56746cf30cdf0659 | c2fed4e6e4f8c0e40ce6b13c122fc26ef808dab9 | refs/heads/master | 2023-07-08T11:03:12.462614 | 2021-08-08T19:50:00 | 2021-08-08T19:50:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,455 | hpp | /*
* =====================================================================================
*
* Filename: colorf.hpp
* Created: 03/31/2016 19:46:27
* Description:
*
* Version: 1.0
* Revision: none
* Compiler: gcc
*
* Author: ANHONG
* Email: anhonghe@gmail.com
* Organization: USTC
*
* =====================================================================================
*/
#pragma once
#include <array>
#include <cstdint>
#include <SDL2/SDL.h>
namespace colorf
{
constexpr uint32_t R_MASK = 0X000000FF;
constexpr uint32_t G_MASK = 0X0000FF00;
constexpr uint32_t B_MASK = 0X00FF0000;
constexpr uint32_t A_MASK = 0XFF000000;
constexpr int R_SHIFT = 0;
constexpr int G_SHIFT = 8;
constexpr int B_SHIFT = 16;
constexpr int A_SHIFT = 24;
constexpr uint8_t R(uint32_t color) { return (color & R_MASK) >> R_SHIFT; }
constexpr uint8_t G(uint32_t color) { return (color & G_MASK) >> G_SHIFT; }
constexpr uint8_t B(uint32_t color) { return (color & B_MASK) >> B_SHIFT; }
constexpr uint8_t A(uint32_t color) { return (color & A_MASK) >> A_SHIFT; }
constexpr uint32_t R_SHF(uint8_t r) { return (uint32_t)(r) << R_SHIFT; }
constexpr uint32_t G_SHF(uint8_t g) { return (uint32_t)(g) << G_SHIFT; }
constexpr uint32_t B_SHF(uint8_t b) { return (uint32_t)(b) << B_SHIFT; }
constexpr uint32_t A_SHF(uint8_t a) { return (uint32_t)(a) << A_SHIFT; }
constexpr uint32_t RGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
return R_SHF(r) | G_SHF(g) | B_SHF(b) | A_SHF(a);
}
constexpr uint32_t RGB(uint8_t r, uint8_t g, uint8_t b)
{
return R_SHF(r) | G_SHF(g) | B_SHF(b);
}
constexpr uint32_t maskRGB(uint32_t color)
{
return color & (R_MASK | G_MASK | B_MASK);
}
template<typename T> constexpr uint8_t round255(T val)
{
if(val <= T(0)){
return 0;
}
if(val >= T(255)){
return 255;
}
return (uint8_t)(val);
}
constexpr uint32_t RGBA_F(double fr, double fg, double fb, double fa)
{
return RGBA(round255(fr * 255.0), round255(fg * 255.0), round255(fb * 255.0), round255(fa * 255.0));
}
constexpr uint32_t RED = RGB(0XFF, 0X00, 0X00);
constexpr uint32_t GREEN = RGB(0X00, 0XFF, 0X00);
constexpr uint32_t BLUE = RGB(0X00, 0X00, 0XFF);
constexpr uint32_t YELLOW = RGB(0XFF, 0XFF, 0X00);
constexpr uint32_t CYAN = RGB(0X00, 0XFF, 0XFF);
constexpr uint32_t MAGENTA = RGB(0XFF, 0X00, 0XFF);
constexpr uint32_t BLACK = RGB(0X00, 0X00, 0X00);
constexpr uint32_t GREY = RGB(0X80, 0X80, 0X80);
constexpr uint32_t WHITE = RGB(0XFF, 0XFF, 0XFF);
constexpr uint32_t modRGBA(uint32_t origColor, uint32_t modColor)
{
const float r_R = 1.0f * R(modColor) / 255.0;
const float r_G = 1.0f * G(modColor) / 255.0;
const float r_B = 1.0f * B(modColor) / 255.0;
const float r_A = 1.0f * A(modColor) / 255.0;
const auto newR = round255(r_R * R(origColor));
const auto newG = round255(r_G * G(origColor));
const auto newB = round255(r_B * B(origColor));
const auto newA = round255(r_A * A(origColor));
return RGBA(newR, newG, newB, newA);
}
constexpr uint32_t renderRGBA(uint32_t dstColor, uint32_t srcColor)
{
auto dstR = R(dstColor);
auto dstG = G(dstColor);
auto dstB = B(dstColor);
auto dstA = A(dstColor);
auto srcR = R(srcColor);
auto srcG = G(srcColor);
auto srcB = B(srcColor);
auto srcA = A(srcColor);
double fAlpha = srcA / 255.0;
dstR = round255(fAlpha * srcR + (1.0 - fAlpha) * dstR);
dstG = round255(fAlpha * srcG + (1.0 - fAlpha) * dstG);
dstB = round255(fAlpha * srcB + (1.0 - fAlpha) * dstB);
dstA = round255( srcA + (1.0 - fAlpha) * dstA);
return RGBA(dstR, dstG, dstB, dstA);
}
constexpr uint32_t fadeRGBA(uint32_t fromColor, uint32_t toColor, float r)
{
const uint32_t fromR = colorf::R(fromColor);
const uint32_t fromG = colorf::G(fromColor);
const uint32_t fromB = colorf::B(fromColor);
const uint32_t fromA = colorf::A(fromColor);
const uint32_t toR = colorf::R(toColor);
const uint32_t toG = colorf::G(toColor);
const uint32_t toB = colorf::B(toColor);
const uint32_t toA = colorf::A(toColor);
const uint32_t dstR = round255(fromR * (1.0 - r) + toR * r);
const uint32_t dstG = round255(fromG * (1.0 - r) + toG * r);
const uint32_t dstB = round255(fromB * (1.0 - r) + toB * r);
const uint32_t dstA = round255(fromA * (1.0 - r) + toA * r);
return colorf::RGBA(dstR, dstG, dstB, dstA);
}
template<size_t N> std::array<uint32_t, N> gradColor(uint32_t beginColor, uint32_t endColor)
{
static_assert(N >= 2);
std::array<uint32_t, N> result;
const auto beginR = (float)(R(beginColor));
const auto beginG = (float)(G(beginColor));
const auto beginB = (float)(B(beginColor));
const auto beginA = (float)(A(beginColor));
const auto fdR = ((float)(R(endColor)) - beginR) / (N - 1.0);
const auto fdG = ((float)(G(endColor)) - beginG) / (N - 1.0);
const auto fdB = ((float)(B(endColor)) - beginB) / (N - 1.0);
const auto fdA = ((float)(A(endColor)) - beginA) / (N - 1.0);
for(size_t i = 0; i < N; ++i){
result[i] = RGBA(round255(beginR + i * fdR), round255(beginG + i * fdG), round255(beginB + i * fdB), round255(beginA + i * fdA));
}
return result;
}
inline SDL_Color RGBA2SDLColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
SDL_Color color;
color.r = r;
color.g = g;
color.b = b;
color.a = a;
return color;
}
inline SDL_Color RGBA2SDLColor(uint32_t color)
{
return RGBA2SDLColor(colorf::R(color), colorf::G(color), colorf::B(color), colorf::A(color));
}
inline uint32_t SDLColor2RGBA(const SDL_Color &color)
{
return RGBA(color.r, color.g, color.b, color.a);
}
inline uint32_t compColor(uint32_t color)
{
return RGBA(255 - R(color), 255 - G(color), 255 - B(color), 255 - A(color));
}
uint32_t string2RGBA(const char *);
}
| [
"anhonghe@gmail.com"
] | anhonghe@gmail.com |
00b5eb6d4357f4a5db91da1798c3909fb5d8c994 | d3e1f9a07e09953ac689c74ad1f7f1ada982dd77 | /SDK/IStoreProduct_functions.cpp | 40640124ba833e9829fc2e0a56493218f9d472ee | [] | no_license | xnf4o/HSH_SURVIVE_SDK | 5857159731ceda7c06e158711003fbaf22021842 | 2f49c97a5f14b4eadf7dc3387b55c09bc968da66 | refs/heads/main | 2023-04-12T06:52:47.854249 | 2021-04-27T03:13:24 | 2021-04-27T03:13:24 | 361,965,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,296 | cpp | // Name: hsh, Version: 2
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function IStoreProduct.IStoreProduct_C.ShowSoldOut
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool bIsShow (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UIStoreProduct_C::ShowSoldOut(bool bIsShow)
{
static auto fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function IStoreProduct.IStoreProduct_C.ShowSoldOut");
UIStoreProduct_C_ShowSoldOut_Params params;
params.bIsShow = bIsShow;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function IStoreProduct.IStoreProduct_C.RefreshProduct
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FS_StoreProduct Product (BlueprintVisible, BlueprintReadOnly, Parm, HasGetValueTypeHash)
// struct FSlateBrush ImageBG (BlueprintVisible, BlueprintReadOnly, Parm)
// struct FVector2D ImageSize (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FVector2D ImagePosition (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// bool bShowTooltip (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// struct FDateTime EndDate (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, NoDestructor, HasGetValueTypeHash)
// TEnumAsByte<E_GameCurrency_E_GameCurrency> Currency (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// TEnumAsByte<E_StoreType_E_StoreType> StoreType (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UIStoreProduct_C::RefreshProduct(const struct FS_StoreProduct& Product, const struct FSlateBrush& ImageBG, const struct FVector2D& ImageSize, const struct FVector2D& ImagePosition, bool bShowTooltip, const struct FDateTime& EndDate, TEnumAsByte<E_GameCurrency_E_GameCurrency> Currency, TEnumAsByte<E_StoreType_E_StoreType> StoreType)
{
static auto fn = nullptr;
if (!fn)
fn =
UObject::FindObject<UFunction>("Function IStoreProduct.IStoreProduct_C.RefreshProduct");
UIStoreProduct_C_RefreshProduct_Params params;
params.Product = Product;
params.ImageBG = ImageBG;
params.ImageSize = ImageSize;
params.ImagePosition = ImagePosition;
params.bShowTooltip = bShowTooltip;
params.EndDate = EndDate;
params.Currency = Currency;
params.StoreType = StoreType;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"xnf4o@inbox.ru"
] | xnf4o@inbox.ru |
06307c3b6ac9392193252dda8158f0035b447c13 | 6f54db0c47de3c46f2d1fc87e430809768e17c81 | /p13 12用switch实现多分支选择结构/p13 12用switch实现多分支选择结构/p13 12用switch实现多分支选择结构.cpp | 21c94875f33e1e4e5f11933f72378f1c9f8004f0 | [] | no_license | loveyuan2019/Cplusplus | 6ed6115bb39aaa8e8cb20cb9e038c0d53a4b5842 | d2f5b7c06d3b434c90d420bb6d0edaff953ae5c2 | refs/heads/master | 2022-11-22T21:27:01.474687 | 2020-07-31T08:41:57 | 2020-07-31T08:41:57 | 283,985,428 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,479 | cpp | //2020-07-23 星期四 早晨 林业楼小平房
#include<iostream>
using namespace std;
int main(){
//需求1,输入0-6,输出对应的星期,六日输出周末。if语句来实现
int x = 0;
cout << "请输入数字" << endl;
cin >> x;
/*if (x == 1)
{
cout << "今天是星期一" << endl;
}
if (x == 2)
{
cout << "今天是星期二" << endl;
}
if (x == 3)
{
cout << "今天是星期三" << endl;
}
if (x == 4)
{
cout << "今天是星期四" << endl;
}
if (x == 5)
{
cout << "今天是星期五" << endl;
}
if (x == 5)
{
cout << "今天是星期五" << endl;
}
if (x == 6)
{
cout << "今天是星期六" << endl;
}
if (x == 0)
{
cout << "今天是星期日" << endl;
}*/
//需求2,输入0-6,输出对应的星期,六日输出周末。switch语句来实现,如果没有break,如果输入2,会显示星期二及以后的,有则跳出switch
switch (x)
{
case 0:
cout << "今天是星期日" << endl;
cout << "今天是星周末" << endl;
break;
case 1:
cout << "今天是星期一" << endl;
break;
case 2:
cout << "今天是星期二" << endl;
break;
case 3:
cout << "今天是星期三" << endl;
break;
case 4:
cout << "今天是星期四" << endl;
break;
case 5:
cout << "今天是星期五" << endl;
break;
case 6:
cout << "今天是星期六" << endl;
cout << "今天是星周末" << endl;
break;
default:
cout << "您输入的数字有误" << endl;
}
return 0;
} | [
"smywsmyw@163.com"
] | smywsmyw@163.com |
77f15a9ff55ff9fbf9114d3d4d051922d62d3f40 | ceafe49baf1ca92303e67ac65220665138bfc4fb | /BOJ_17837_새로운게임2.cpp | 6efe23d0153038f99f017e771af566f836f2ff29 | [] | no_license | Seung-minnn/BOJ | 15d076dd698ddc0f77a90a3c903df11fcccfdaa8 | c4aca6c0995f0a6b4eea1e1c83aac5e1b1ef8ab1 | refs/heads/master | 2021-07-22T08:55:55.488240 | 2021-01-27T14:52:19 | 2021-01-27T14:52:19 | 237,153,394 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 3,515 | cpp | #include<stdio.h>
#include<vector>
#include<iostream>
#define MAX 12
#define CHESS_MAX 10
using namespace std;
struct circle
{
int x, y, dir;
};
int n, k;
int map[MAX][MAX]; //입력받을 맵을 저장
vector<int> map_state[MAX][MAX]; //좌표에 들어있는 맵의 상태 ex)map_state[0][0]={1,2,}; ->0index가 가장 아래
circle cir[CHESS_MAX];
int dx[] = { 0,0,-1,1 }; //right left up down
int dy[] = { 1,-1,0,0 };
int find_delete_num(int x, int y, int num) {
int cnt = 0;
for (int i = map_state[x][y].size() - 1; i >= 0; i--) {
if (map_state[x][y][i] == num)
break;
cnt++;
}
return cnt + 1;
}
void move_circle(int x, int y, int nx, int ny, int num, int pos, int status) {
//printf("\n%d %d %d %d %d %d %d\n", x, y, nx, ny, num, pos, status);
//4.조건에 맞춰 원판말 이동
if (status == 0) {
for (int i = pos; i < map_state[x][y].size(); i++) {
map_state[nx][ny].push_back(map_state[x][y][i]);
int temp = map_state[x][y][i];
cir[temp].x = nx;
cir[temp].y = ny;
}
int del = find_delete_num(x, y, num);
for (int i = 0; i < del; i++) {
map_state[x][y].pop_back();
}
}
else if (status == 1) {
for (int i = map_state[x][y].size() - 1; i >= pos; i--) {
map_state[nx][ny].push_back(map_state[x][y][i]);
int temp = map_state[x][y][i];
cir[temp].x = nx;
cir[temp].y = ny;
}
int del = find_delete_num(x, y, num);
for (int i = 0; i < del; i++) {
map_state[x][y].pop_back();
}
}
else if (status == 2) {
int dir = cir[num].dir;
if (dir == 0) dir = 1;
else if (dir == 1) dir = 0;
else if (dir == 2) dir = 3;
else if (dir == 3) dir = 2;
cir[num].dir = dir;
int nnx = x + dx[dir];
int nny = y + dy[dir];
if (nnx >= 0 && nny >= 0 && nnx < n&&nny < n) {
if (map[nnx][nny] != 2) move_circle(x, y, nnx, nny, num, pos, map[nnx][nny]);
}
}
}
int find_position(int x, int y, int id) {
//3. 해당 말이 몇 번째에 위치하는지 return
for (int i = 0; i < map_state[x][y].size(); i++) {
if (map_state[x][y][i] == id)
return i;
}
}
int main() {
//1.입력 받기
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &map[i][j]);
}
}
for (int i = 0; i < k; i++) {
int x, y, d;
scanf("%d %d %d", &x, &y, &d);
x--; y--; d--;
cir[i] = { x,y,d };
map_state[x][y].push_back(i);
}
//2. 원판 조건성립할 때까지 이동
bool flag = false;
int round = 0;
while (true) {
if (round > 1000) break;
//printf("%d\n", round);
for (int i = 0; i < k; i++) {
int x = cir[i].x;
int y = cir[i].y;
int dir = cir[i].dir;
int nx = x + dx[dir];
int ny = y + dy[dir];
int pos = find_position(x, y, i);
if (nx >= 0 && ny >= 0 && nx < n&&ny < n) {
move_circle(x, y, nx, ny, i, pos, map[nx][ny]);
}
else {
move_circle(x, y, nx, ny, i, pos, 2);
}
//5. 상태 확인후 종료할 수 있으면 종료
bool check = false;
for (int i = 0; i < k; i++) {
int x = cir[i].x;
int y = cir[i].y;
if (map_state[x][y].size() >= 4) check = true;
}
if (check == true) {
flag = true;
break;
}
}
if (flag == true)
break;
round++;
//printf("===========================================\n");
}
//6. 출력
if (flag == true) {
printf("%d", round + 1);
}
else {
printf("%d", -1);
}
//system("pause");
return 0;
} | [
"noreply@github.com"
] | Seung-minnn.noreply@github.com |
0353e56c6f3e5e79c85bce1a90f43ea0507bd976 | 154ad9b7b26b5c52536bbd83cdaf0a359e6125c3 | /components/sync/js/js_event_handler.h | ec5a3e908040343f066a968b804ccbc79fa6b662 | [
"BSD-3-Clause"
] | permissive | bopopescu/jstrace | 6cc239d57e3a954295b67fa6b8875aabeb64f3e2 | 2069a7b0a2e507a07cd9aacec4d9290a3178b815 | refs/heads/master | 2021-06-14T09:08:34.738245 | 2017-05-03T23:17:06 | 2017-05-03T23:17:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | h | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_JS_JS_EVENT_HANDLER_H_
#define COMPONENTS_SYNC_JS_JS_EVENT_HANDLER_H_
// See README.js for design comments.
#include <string>
#include "components/sync/base/sync_export.h"
namespace syncer {
class JsEventDetails;
// An interface for objects that handle Javascript events (e.g.,
// WebUIs).
class SYNC_EXPORT JsEventHandler {
public:
virtual void HandleJsEvent(const std::string& name,
const JsEventDetails& details) = 0;
protected:
virtual ~JsEventHandler() {}
};
} // namespace syncer
#endif // COMPONENTS_SYNC_JS_JS_EVENT_HANDLER_H_
| [
"zzbthechaos@gmail.com"
] | zzbthechaos@gmail.com |
d19ea66f92953b50e3d7c58e43af0d2b5d2ce530 | eb1517897d7e9e372538b0982223b7ecaaff46b0 | /third_party/blink/renderer/modules/hid/hid.h | 318b581ed45bb2d888f0efbc66649f8145516549 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | jiachengii/chromium | c93e9cfa8fb79d6a0b5e66848dc204e87236252c | ead0d3601849269629ff31de4daed20fce453ba7 | refs/heads/master | 2022-11-16T02:35:53.671352 | 2020-06-13T06:43:44 | 2020-06-13T06:43:44 | 271,964,385 | 0 | 0 | BSD-3-Clause | 2020-06-13T07:47:21 | 2020-06-13T07:47:21 | null | UTF-8 | C++ | false | false | 3,447 | h | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_HID_HID_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_HID_HID_H_
#include "services/device/public/mojom/hid.mojom-blink-forward.h"
#include "third_party/blink/public/mojom/hid/hid.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_wrapper_mode.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_or_worker_scheduler.h"
namespace blink {
class ExecutionContext;
class HIDDevice;
class HIDDeviceRequestOptions;
class ScriptPromiseResolver;
class ScriptState;
class HID : public EventTargetWithInlineData, public ExecutionContextClient {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(HID);
public:
explicit HID(ExecutionContext& context);
~HID() override;
// EventTarget:
ExecutionContext* GetExecutionContext() const override;
const AtomicString& InterfaceName() const override;
// Web-exposed interfaces:
DEFINE_ATTRIBUTE_EVENT_LISTENER(connect, kConnect)
DEFINE_ATTRIBUTE_EVENT_LISTENER(disconnect, kDisconnect)
ScriptPromise getDevices(ScriptState*, ExceptionState&);
ScriptPromise requestDevice(ScriptState*,
const HIDDeviceRequestOptions*,
ExceptionState&);
void Connect(const String& device_guid,
mojo::PendingRemote<device::mojom::blink::HidConnectionClient>
connection_client,
device::mojom::blink::HidManager::ConnectCallback callback);
void Trace(Visitor*) const override;
protected:
// EventTarget:
void AddedEventListener(const AtomicString& event_type,
RegisteredEventListener&) override;
private:
// Returns the HIDDevice matching |info| from |device_cache_|. If the device
// is not in the cache, a new device is created and added to the cache.
HIDDevice* GetOrCreateDevice(device::mojom::blink::HidDeviceInfoPtr info);
// Opens a connection to HidService, or does nothing if the connection is
// already open.
void EnsureServiceConnection();
void OnServiceConnectionError();
void FinishGetDevices(ScriptPromiseResolver*,
Vector<device::mojom::blink::HidDeviceInfoPtr>);
void FinishRequestDevice(ScriptPromiseResolver*,
Vector<device::mojom::blink::HidDeviceInfoPtr>);
HeapMojoRemote<mojom::blink::HidService,
HeapMojoWrapperMode::kWithoutContextObserver>
service_;
HeapHashSet<Member<ScriptPromiseResolver>> get_devices_promises_;
HeapHashSet<Member<ScriptPromiseResolver>> request_device_promises_;
HeapHashMap<String, WeakMember<HIDDevice>> device_cache_;
FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle
feature_handle_for_scheduler_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_HID_HID_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e61bb471f7ef658faa5442de5174bcd167223153 | 560cd3685da109fd6f08dd1264a002d5c2f60e8b | /3DGameEngine/CoreEngine.h | c0118cd6c2154f9cc58590058904f1148543ee43 | [] | no_license | Lars-Haakon/3DOpenGLEngine | 709f6e56f2ef5da0769f3d9bd5ee62ae815e1615 | 72b70f599af87ee1df0385885efcf719ce995902 | refs/heads/master | 2021-05-29T13:33:07.875964 | 2015-02-01T16:02:48 | 2015-02-01T16:02:48 | 30,045,734 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | h | #ifndef COREENGINE_H
#define COREENGINE_H
#include "Window.h"
#include "TestGame.h"
#include <Windows.h>
class CoreEngine
{
public:
double FPS;
CoreEngine(Window *window);
~CoreEngine();
void run(HDC &hdc);
private:
void glInit();
void setProjection(int w, int h);
TestGame *game;
};
#endif | [
"lars-haakon@hotmail.com"
] | lars-haakon@hotmail.com |
23c48612626db0bc806fdd0f79bf61a073d6fd9e | 47610aa612655d17c2d2e88116bff8ce8ebc0a26 | /src/analysis/PandaXEnergyDepositionHit.cc | 36bb662dbb455b04a6041b2063fbd5c395fcfe77 | [] | no_license | Catofes/BambooMC | 6aa154f6ad0a4a305300eef2ff3d26735c4404a4 | 42ab135729ed4ec7d0c90050043a1bce6a9deacb | refs/heads/main | 2020-05-21T19:10:36.629301 | 2016-09-11T01:20:41 | 2016-09-11T01:20:41 | 62,614,871 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,738 | cc | #include "analysis/PandaXEnergyDepositionHit.hh"
G4Allocator<PandaXEnergyDepositionHit> * pandaXEnergyDepositionHitAllocator = new G4Allocator<PandaXEnergyDepositionHit>;
PandaXEnergyDepositionHit::PandaXEnergyDepositionHit()
: _trackId(-1), _parentId(-1), _energy(0), _x(0), _y(0), _z(0),
_type("unknown"), _creatorProcess("unknown"), _depositionProcess("unknown"), _parent("none")
{
}
PandaXEnergyDepositionHit::~PandaXEnergyDepositionHit()
{
}
const PandaXEnergyDepositionHit & PandaXEnergyDepositionHit::operator=(const PandaXEnergyDepositionHit & right)
{
_trackId = right._trackId;
_parentId = right._parentId;
_energy = right._energy;
_x = right._x;
_y = right._y;
_z = right._z;
_t = right._t;
_type = right._type;
_creatorProcess = right._creatorProcess;
_depositionProcess = right._depositionProcess;
_parent = right._parent;
return * this;
}
int PandaXEnergyDepositionHit::operator==(const PandaXEnergyDepositionHit &right) const
{
return ((this == &right)?1:0);
}
int PandaXEnergyDepositionHit::getTrackId () const
{
return _trackId;
}
int PandaXEnergyDepositionHit::getParentId () const
{
return _parentId;
}
double PandaXEnergyDepositionHit::getEnergy() const
{
return _energy;
}
double PandaXEnergyDepositionHit::getX() const
{
return _x;
}
double PandaXEnergyDepositionHit::getY() const
{
return _y;
}
double PandaXEnergyDepositionHit::getZ() const
{
return _z;
}
double PandaXEnergyDepositionHit::getT() const
{
return _t;
}
const string & PandaXEnergyDepositionHit::getType() const
{
return _type;
}
const string & PandaXEnergyDepositionHit::getCreatorProcess() const
{
return _creatorProcess;
}
const string & PandaXEnergyDepositionHit::getDepositionProcess() const
{
return _depositionProcess;
}
const string & PandaXEnergyDepositionHit::getParent() const
{
return _parent;
}
void PandaXEnergyDepositionHit::setTrackId (int id)
{
_trackId = id;
}
void PandaXEnergyDepositionHit::setParentId (int id)
{
_parentId = id;
}
void PandaXEnergyDepositionHit::setEnergy(double energy)
{
_energy = energy;
}
void PandaXEnergyDepositionHit::setX(double x)
{
_x = x;
}
void PandaXEnergyDepositionHit::setY(double y)
{
_y = y;
}
void PandaXEnergyDepositionHit::setZ(double z)
{
_z = z;
}
void PandaXEnergyDepositionHit::setT(double t)
{
_t = t;
}
void PandaXEnergyDepositionHit::setType(const string &type)
{
_type = type;
}
void PandaXEnergyDepositionHit::setCreatorProcess(const string &process)
{
_creatorProcess = process;
}
void PandaXEnergyDepositionHit::setDepositionProcess(const string &process)
{
_depositionProcess = process;
}
void PandaXEnergyDepositionHit::setParent(const string &parent)
{
_parent = parent;
}
| [
"xun.revive@gmail.com"
] | xun.revive@gmail.com |
bcb40063224e0810468c16df0bd35667a4053bdd | c81756dc2f25849f4e6db60bd93a1e20821cb221 | /arduino/sensor2.ino | 8f7fa5c7601d71b7f49aa0ab4d320fa07b18a8c2 | [] | no_license | ivanma9/transfer-HaCK | 3b7d7255296a26209af365cb6291dcf6316c0c66 | da73b02ceabbfeaa2b5e0beecd0fba7836e0b603 | refs/heads/master | 2022-12-22T21:42:33.047542 | 2020-09-21T07:02:28 | 2020-09-21T07:02:28 | 296,490,184 | 0 | 0 | null | 2020-09-19T19:41:36 | 2020-09-18T02:14:07 | C++ | UTF-8 | C++ | false | false | 3,154 | ino | float readSensors() {
long soundTime;
float objDist_FL, objDist_FR, objDist_L, objDist_R;
// FRONT LEFT SENSOR
digitalWrite(trigPinFrontLeft, LOW);
delayMicroseconds(2);
// Trigger the sensor
digitalWrite(trigPinFrontLeft, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinFrontLeft, LOW);
// Read the echoPin, give pulseIn the length of the pulse in microseconds:
soundTime = pulseIn(echoPinFrontLeft, HIGH);
// Distance = Speed * Time, Speed of sound = 0.0343 cm/µs
// Divide by 2 because only the dist to the obj is wanted, not the round trip
objDist_FL = float(soundTime * 0.0343 / 2);
// FRONT RIGHT SENSOR
digitalWrite(trigPinFrontRight, LOW);
delayMicroseconds(2);
digitalWrite(trigPinFrontRight, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinFrontRight, LOW);
soundTime = pulseIn(echoPinFrontRight, HIGH);
objDist_FR = float(soundTime * 0.0343 / 2);
// LEFT SIDE SENSOR
digitalWrite(trigPinLeft, LOW);
delayMicroseconds(2);
digitalWrite(trigPinLeft, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinLeft, LOW);
soundTime = pulseIn(echoPinLeft, HIGH);
objDist_L = float(soundTime * 0.0343 / 2);
// RIGHT SIDE SENSOR
digitalWrite(trigPinRight, LOW);
delayMicroseconds(2);
digitalWrite(trigPinRight, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinRight, LOW);
soundTime = pulseIn(echoPinRight, HIGH);
objDist_R = float(soundTime * 0.0343 / 2);
if (objDist_FL > 10.00 || objDist_FR > 10.00) {
goForward();
}
else {
turnRight(objDist_L);
goForward();
}
// Print the distance on the Serial Monitor (Ctrl+Shift+M):
Serial.print(objDist_FL);
Serial.print(" ");
Serial.print(objDist_FR);
Serial.print(" ");
Serial.print(objDist_L);
Serial.print(" ");
Serial.println(objDist_R);
}
void goForward() {
analogWrite(F_ENA, 255);
analogWrite(F_ENB, 255);
analogWrite(B_ENA, 255);
analogWrite(B_ENB, 255);
digitalWrite(F_IN1, HIGH);
digitalWrite(F_IN2, LOW);
digitalWrite(F_IN3, HIGH);
digitalWrite(F_IN4, LOW);
digitalWrite(B_IN1, HIGH);
digitalWrite(B_IN2, LOW);
digitalWrite(B_IN3, HIGH);
digitalWrite(B_IN4, LOW);
}
void turnRight(int oldDist_L) {
// WHEELS GO FORWARD ON RIGHT SIDE, BACKWARDS ON LEFT SIDE
analogWrite(F_ENA, 255);
analogWrite(F_ENB, 255);
analogWrite(B_ENA, 255);
analogWrite(B_ENB, 255);
bool keepTurning = true;
while (keepTurning){
digitalWrite(F_IN1, LOW);
digitalWrite(F_IN2, HIGH);
digitalWrite(F_IN3, HIGH);
digitalWrite(F_IN4, LOW);
digitalWrite(B_IN1, HIGH);
digitalWrite(B_IN2, LOW);
digitalWrite(B_IN3, LOW);
digitalWrite(B_IN4, HIGH);
// LEFT SIDE SENSOR
long s_time;
float dist;
digitalWrite(trigPinLeft, LOW);
delayMicroseconds(2);
digitalWrite(trigPinLeft, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinLeft, LOW);
s_time = pulseIn(echoPinLeft, HIGH);
dist = float(s_time * 0.0343 / 2);
if (dist - 1 <= oldDist_L)
keepTurning = false;
}
//delay(4940);
}
| [
"noreply@github.com"
] | ivanma9.noreply@github.com |
33c74aabf2479dc0f6f9449c043be342ada7736d | ef9e15db20a82b4d5e22caae4d7a5065a65cff27 | /CPP_99(입출력연산자오버로딩_OverLoading)/CPP_99/main.cpp | 57f5f9f38c7d11bf8702ddc78ce29c78749271e4 | [] | no_license | jinseongbe/cpp_study | 62a0b688a8f6b27f02449686a3a05dd053632f2f | 37be65a75eb33516a4b4434a05975ed61fce7194 | refs/heads/master | 2023-04-10T17:32:03.788508 | 2021-04-18T14:35:07 | 2021-04-18T14:35:07 | 354,449,067 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,596 | cpp | #include <iostream>
#include <fstream>
using namespace std;
class Point
{
private:
double m_x, m_y, m_z;
public:
Point(double x = 0.0, double y = 0.0, double z = 0.0)
: m_x(x), m_y(y), m_z(z)
{}
double getX() { return m_x; }
double getY() { return m_y; }
double getZ() { return m_z; }
void print()
{
cout << m_x << "\t" << m_y << "\t" << m_z << endl;
}
friend std::ostream &operator << (std::ostream &out, const Point &point) // MemberFunction이 아닌 Friend로 사용하는 이유
{ // => 첫번째 파라미터가 Point의 것이 아닌 std::ostream것이기 때문, 즉 첫번쨰 파라미터가 Class자신의 것이여야함!
out << "( " << point.m_x << "\t" << point.m_y << "\t" << point.m_z << " )";
return out;
}
friend std::istream &operator >> (std::istream &in, Point &point) // input이니까 const 쓰면 안되죠~
{
in >> point.m_x >> point.m_y >> point.m_z;
return in;
}
};
int main()
{
Point p1(0.0, 0.1, 0.2), p2(3.4, 1.5, 2.0);
p1.print();
p2.print();
cout << endl;
// 연산자 오버로딩
cout << p1 << endl << p2 << endl;
// file로 출력
ofstream of("out.txt");
of << p1 << endl << p2 << endl;
of.close(); // 알아서 닫고 나가지만 그래도 해주면 성실한 프로그래머!
Point P1, P2;
cin >> P1 >> P2;
cout << P1 << endl << P2;
return 0;
}
| [
"jinseongbe@google.com"
] | jinseongbe@google.com |
0a788e44cf69be301cf8c29dbf56274ba4aa2a56 | 9c92864c827e7e25bb2ccb773e2602d3bef7630e | /URI/URI 1136 - Bingo!.cpp | 81578843b44c38c6f3c30db668a472f4737c40e5 | [
"Unlicense"
] | permissive | pravgcet/competitive_programming | 25a0456c8a8457ef30ec97bc4fb75cffb94dccc1 | 17f27248ee843e424fcad9de3872b768113a7713 | refs/heads/master | 2021-01-21T03:49:28.384786 | 2014-06-23T16:08:40 | 2014-06-23T16:08:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool canCallOutAll(const vector<int>& balls, int n) {
vector<bool> checked(n + 1, false);
checked[0] = true;
for(int i = 0; i < balls.size(); ++i)
for(int j = 0; j < i; ++j)
checked[balls[i] - balls[j]] = true;
for(int i = 0; i < n + 1; ++i)
if (!checked[i])
return false;
return true;
}
int main() {
int n, ballNumber;
while(cin >> n >> ballNumber && n > 0 && ballNumber > 0) {
vector<int> balls(ballNumber);
for(int i = 0; i < ballNumber; ++i)
cin >> balls[i];
sort(balls.begin(), balls.end());
cout << (canCallOutAll(balls, n) ? 'Y' : 'N') << '\n';
}
}
| [
"dancas2@gmail.com"
] | dancas2@gmail.com |
89978454aa36a4889d169dbbe9b5c25ef5c3698d | b85325897c5803c7b928ef64db46bb55c2e04467 | /games/ChessGame.hpp | efebf81dc399be9250126c027104fa20ad54e804 | [
"Apache-2.0"
] | permissive | celrati/BoardFramework | 1b5e4c66f50ff5ee2bb09fd95a070a47b69be10c | 2325ffcaedf1e6b5104a3766bbc5a5281253a741 | refs/heads/master | 2020-08-22T11:37:59.604786 | 2019-10-20T15:51:53 | 2019-10-20T15:51:53 | 216,386,131 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | hpp | #ifndef CHESS_GAME_HPP
#define CHESS_GAME_HPP
#include "../lib/ShortCutUtil.hpp"
#include "../Core/Game.hpp"
#include "boards/ChessBoard.hpp"
#include "../Core/Player.hpp"
#include "../pipe/InputReader.hpp"
#include "rules/ChessRule.hpp"
#include <vector>
#include <utility>
#include "../lib/Position.hpp"
class ChessGame : public Game{
private:
//state_game --
ChessBoard * chessBoard;
Player * player_1;
Player * player_2;
int turn_player;
InputReader<ChessBoard,ChessRule> * inputReader;
vector< pair< Position, Position> > moves_players_list;
public:
ChessGame(int mode); // 1 vs 2 or vs machine
virtual void gameStart();
virtual void gamePause();
virtual void gameStop();
virtual void gameOver();
virtual bool gameLoad();
virtual bool gameSave(string name_file);
virtual void gameRestart();
virtual void printBoard();
virtual void saveMove(char a, char b, char c, char d);
virtual char getMaxColumn();
virtual char getMaxRow();
static void launchGame();
};
#endif | [
"m.charif.achraf@gmail.com"
] | m.charif.achraf@gmail.com |
68c9a892eec3970819f8c2bff34f5a57feb1d679 | 59c94d223c8e1eb1720d608b9fc040af22f09e3a | /zircon/system/ulib/minfs/test/inspector-test.cpp | 660dc0df0919dddf370cec6787a9a94814df75f3 | [
"BSD-3-Clause",
"MIT"
] | permissive | bootingman/fuchsia2 | 67f527712e505c4dca000a9d54d3be1a4def3afa | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | refs/heads/master | 2022-12-25T20:28:37.134803 | 2019-05-14T08:26:08 | 2019-05-14T08:26:08 | 186,606,695 | 1 | 1 | BSD-3-Clause | 2022-12-16T21:17:16 | 2019-05-14T11:17:16 | C++ | UTF-8 | C++ | false | false | 6,899 | cpp | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests minfs inspector behavior.
#include <minfs/inspector.h>
#include "minfs-private.h"
#include "inspector-private.h"
#include <lib/disk-inspector/disk-inspector.h>
#include <zxtest/zxtest.h>
namespace minfs {
namespace {
// Mock InodeManager class to be used in inspector tests.
class MockInodeManager : public InspectableInodeManager {
public:
MockInodeManager();
MockInodeManager(const MockInodeManager&)= delete;
MockInodeManager(MockInodeManager&&) = delete;
MockInodeManager& operator=(const MockInodeManager&) = delete;
MockInodeManager& operator=(MockInodeManager&&) = delete;
void Load(ino_t inode_num, Inode* out) const final;
const Allocator* GetInodeAllocator() const final;
};
MockInodeManager::MockInodeManager() {}
void MockInodeManager::Load(ino_t inode_num, Inode* out) const {}
const Allocator* MockInodeManager::GetInodeAllocator() const {
return nullptr;
}
constexpr Superblock superblock = {};
// Mock Minfs class to be used in inspector tests.
class MockMinfs : public InspectableFilesystem {
public:
MockMinfs() = default;
MockMinfs(const MockMinfs&)= delete;
MockMinfs(MockMinfs&&) = delete;
MockMinfs& operator=(const MockMinfs&) = delete;
MockMinfs& operator=(MockMinfs&&) = delete;
const Superblock& Info() const {
return superblock;
}
const InspectableInodeManager* GetInodeManager() const final {
return nullptr;
}
const Allocator* GetBlockAllocator() const final {
return nullptr;
}
zx_status_t ReadBlock(blk_t start_block_num, void* out_data) const final {
return ZX_OK;
}
};
TEST(InspectorTest, TestRoot) {
auto fs = std::unique_ptr<MockMinfs>(new MockMinfs());
std::unique_ptr<RootObject> root_obj(new RootObject(std::move(fs)));
ASSERT_STR_EQ(kRootName, root_obj->GetName());
ASSERT_EQ(kRootNumElements, root_obj->GetNumElements());
// Superblock.
std::unique_ptr<disk_inspector::DiskObject> obj0 = root_obj->GetElementAt(0);
ASSERT_STR_EQ(kSuperBlockName, obj0->GetName());
ASSERT_EQ(kSuperblockNumElements, obj0->GetNumElements());
// Inode Table.
std::unique_ptr<disk_inspector::DiskObject> obj1 = root_obj->GetElementAt(1);
ASSERT_STR_EQ(kInodeTableName, obj1->GetName());
// Journal info.
std::unique_ptr<disk_inspector::DiskObject> obj2 = root_obj->GetElementAt(2);
ASSERT_STR_EQ(kJournalName, obj2->GetName());
ASSERT_EQ(kJournalNumElements, obj2->GetNumElements());
}
TEST(InspectorTest, TestInodeTable) {
auto inode_table_obj = std::unique_ptr<MockInodeManager>(new MockInodeManager());
std::unique_ptr<InodeTableObject> inode_mgr(new InodeTableObject(inode_table_obj.get(), 2));
ASSERT_STR_EQ(kInodeTableName, inode_mgr->GetName());
ASSERT_EQ(2, inode_mgr->GetNumElements());
std::unique_ptr<disk_inspector::DiskObject> obj0 = inode_mgr->GetElementAt(0);
ASSERT_STR_EQ(kInodeName, obj0->GetName());
ASSERT_EQ(kInodeNumElements, obj0->GetNumElements());
std::unique_ptr<disk_inspector::DiskObject> obj1 = inode_mgr->GetElementAt(1);
ASSERT_STR_EQ(kInodeName, obj1->GetName());
ASSERT_EQ(kInodeNumElements, obj1->GetNumElements());
}
TEST(InspectorTest, TestSuperblock) {
Superblock sb;
sb.magic0 = kMinfsMagic0;
sb.magic1 = kMinfsMagic1;
sb.version = kMinfsVersion;
sb.flags = kMinfsFlagClean;
sb.block_size = kMinfsBlockSize;
sb.inode_size = kMinfsInodeSize;
size_t size;
const void* buffer = nullptr;
std::unique_ptr<SuperBlockObject> superblock(new SuperBlockObject(sb));
ASSERT_STR_EQ(kSuperBlockName, superblock->GetName());
ASSERT_EQ(kSuperblockNumElements, superblock->GetNumElements());
std::unique_ptr<disk_inspector::DiskObject> obj0 = superblock->GetElementAt(0);
obj0->GetValue(&buffer, &size);
ASSERT_EQ(kMinfsMagic0, *(reinterpret_cast<const uint64_t*>(buffer)));
std::unique_ptr<disk_inspector::DiskObject> obj1 = superblock->GetElementAt(1);
obj1->GetValue(&buffer, &size);
ASSERT_EQ(kMinfsMagic1, *(reinterpret_cast<const uint64_t*>(buffer)));
std::unique_ptr<disk_inspector::DiskObject> obj2 = superblock->GetElementAt(2);
obj2->GetValue(&buffer, &size);
ASSERT_EQ(kMinfsVersion, *(reinterpret_cast<const uint32_t*>(buffer)));
std::unique_ptr<disk_inspector::DiskObject> obj3 = superblock->GetElementAt(3);
obj3->GetValue(&buffer, &size);
ASSERT_EQ(kMinfsFlagClean, *(reinterpret_cast<const uint32_t*>(buffer)));
std::unique_ptr<disk_inspector::DiskObject> obj4 = superblock->GetElementAt(4);
obj4->GetValue(&buffer, &size);
ASSERT_EQ(kMinfsBlockSize, *(reinterpret_cast<const uint32_t*>(buffer)));
std::unique_ptr<disk_inspector::DiskObject> obj5 = superblock->GetElementAt(5);
obj5->GetValue(&buffer, &size);
ASSERT_EQ(kMinfsInodeSize, *(reinterpret_cast<const uint32_t*>(buffer)));
}
TEST(InspectorTest, TestJournal) {
JournalInfo jinfo;
jinfo.magic = kJournalMagic;
auto info = std::make_unique <JournalInfo>(jinfo);
std::unique_ptr<JournalObject> journalObj(new JournalObject(std::move(info)));
ASSERT_STR_EQ(kJournalName, journalObj->GetName());
ASSERT_EQ(kJournalNumElements, journalObj->GetNumElements());
size_t size;
const void* buffer = nullptr;
std::unique_ptr<disk_inspector::DiskObject> obj0 = journalObj->GetElementAt(0);
obj0->GetValue(&buffer, &size);
ASSERT_EQ(kJournalMagic, *(reinterpret_cast<const uint64_t*>(buffer)));
}
TEST(InspectorTest, TestInode) {
Inode fileInode;
fileInode.magic = kMinfsMagicFile;
fileInode.size = 10;
fileInode.block_count = 2;
fileInode.link_count = 1;
std::unique_ptr<InodeObject> finodeObj(new InodeObject(fileInode));
ASSERT_STR_EQ(kInodeName, finodeObj->GetName());
ASSERT_EQ(kInodeNumElements, finodeObj->GetNumElements());
size_t size;
const void* buffer = nullptr;
std::unique_ptr<disk_inspector::DiskObject> obj0 = finodeObj->GetElementAt(0);
obj0->GetValue(&buffer, &size);
ASSERT_EQ(kMinfsMagicFile, *(reinterpret_cast<const uint32_t*>(buffer)));
std::unique_ptr<disk_inspector::DiskObject> obj1 = finodeObj->GetElementAt(1);
obj1->GetValue(&buffer, &size);
ASSERT_EQ(10, *(reinterpret_cast<const uint32_t*>(buffer)));
std::unique_ptr<disk_inspector::DiskObject> obj2 = finodeObj->GetElementAt(2);
obj2->GetValue(&buffer, &size);
ASSERT_EQ(2, *(reinterpret_cast<const uint32_t*>(buffer)));
std::unique_ptr<disk_inspector::DiskObject> obj3 = finodeObj->GetElementAt(3);
obj3->GetValue(&buffer, &size);
ASSERT_EQ(1, *(reinterpret_cast<const uint32_t*>(buffer)));
}
} // namespace
} // namespace minfs
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c4f00cc1d7d02b18034c8a9bed299b50a88b8d06 | a19024eb42bbc6f0cc3f9b954a7c632c73b415ff | /src/main.cpp | 1281f6235366a7125d9c21226012302b06123934 | [] | no_license | BillyZhaohengLi/2dShooterGame | a977d5ba431ccff1cb24a650d103fd2040280b57 | d77bb3bda14f4f2f0615d21987668f1953c5ea06 | refs/heads/master | 2020-03-28T13:40:28.987845 | 2018-05-03T04:59:39 | 2018-05-03T04:59:39 | 148,416,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | cpp | #include "ofMain.h"
#include "ofApp.h"
#include "const.h"
//========================================================================
int main( ){
//sets the window to borderless windowed.
//this was done because of weird coordinate issues with openFrameworks;
//in a bordered window, the 0 y coordinate for in-game drawing is located at the
//top of the window hidden under the border while the 0 y coordinate for the mouse
//starts at the bottom of the border, causing undesirable discrepancy between
//the mouse position as it appears in game and where the mouse actually is.
ofGLFWWindowSettings settings;
settings.width = kLevelWidthMultiplier * kWallWidth;
settings.height = kLevelHeightMultiplier * kWallWidth;
settings.decorated = false;
settings.windowMode = OF_WINDOW;
ofCreateWindow(settings); // <-------- setup the GL context
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofSetFrameRate(40);
ofRunApp(new ofApp());
}
| [
"noreply@github.com"
] | BillyZhaohengLi.noreply@github.com |
f865172e89f71fddb2c2ea67cb5cef8b0cf99992 | a0b0eb383ecfeaeed3d2b0271657a0c32472bf8e | /lydsy/4802.cpp | dc803b3b47807cf4026fdda108a0a387bbdc5450 | [
"Apache-2.0"
] | permissive | tangjz/acm-icpc | 45764d717611d545976309f10bebf79c81182b57 | f1f3f15f7ed12c0ece39ad0dd044bfe35df9136d | refs/heads/master | 2023-04-07T10:23:07.075717 | 2022-12-24T15:30:19 | 2022-12-26T06:22:53 | 13,367,317 | 53 | 20 | Apache-2.0 | 2022-12-26T06:22:54 | 2013-10-06T18:57:09 | C++ | UTF-8 | C++ | false | false | 1,716 | cpp | #include <ctime>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef long double DB;
const int maxs = 16, maxm = 1 << 16, maxt = 10;
int cnt, sum;
LL n, pp[maxs], sei[maxs], ans[maxm];
LL mod_add(LL x, LL y, LL p)
{
return (x += y) < p ? x : x - p;
}
LL mod_mul(LL x, LL y, LL p)
{
return (x = x * y - (LL)((DB)x * y / p + 0.001) * p) < 0 ? x + p : x;
}
LL mod_pow(LL x, LL k, LL p)
{
LL ret = 1;
for( ; k > 0; k >>= 1, x = mod_mul(x, x, p))
if(k & 1)
ret = mod_mul(ret, x, p);
return ret;
}
bool miller_rabin(LL n)
{
if(n == 2)
return 1;
if(n < 2 || !(n & 1))
return 0;
LL s = 0, r = n - 1;
for( ; !(r & 1); r >>= 1, ++s);
for(int i = 0; i < maxt; ++i)
{
LL cur = mod_pow(rand() % (n - 2) + 2, r, n), nxt;
for(int j = 0; j < s; ++j)
{
nxt = mod_mul(cur, cur, n);
if(nxt == 1 && cur != 1 && cur != n - 1)
return 0;
cur = nxt;
}
if(cur != 1)
return 0;
}
return 1;
}
LL pollard_rho(LL n)
{
LL x = (LL)rand() * rand() % n, y = x, c = (LL)rand() * rand() % n, r;
for(LL i = 1, k = 2; ; ++i)
{
if(i == k)
{
y = x;
k <<= 1;
}
x = mod_add(mod_mul(x, x, n), c, n);
r = __gcd(abs(y - x), n);
if(r != 1)
return r;
}
}
void decomposition(LL n)
{
if(miller_rabin(n))
{
bool flag = 0;
for(int i = 0; i < cnt; ++i)
if(n == pp[i])
{
flag = 1;
break;
}
if(!flag)
pp[cnt++] = n;
}
else
{
LL fact;
while((fact = pollard_rho(n)) == n);
decomposition(fact);
decomposition(n / fact);
}
}
int main()
{
scanf("%lld", &n);
if(n == 1)
{
puts("1");
return 0;
}
decomposition(n);
for(int i = 0; i < cnt; ++i)
n -= n / pp[i];
printf("%lld\n", n);
return 0;
}
| [
"t251346744@gmail.com"
] | t251346744@gmail.com |
5d7d756f6e4abb226a1ad4c010a3c66e320623d6 | cdea9b673d668c6eda9d90f9c606eeb8cb967d4b | /libs/vm/tests/cpu_tests.cpp | 1c223ca9a98297010e963a7ebd1699d05965c78d | [
"MIT"
] | permissive | tiaanl/emulator | 9965aa39248bfe81bd682b8d3554a23d08e97b49 | a962f5136972a272294795579a2966f1af221f61 | refs/heads/main | 2023-01-22T19:33:55.749535 | 2020-12-08T16:07:36 | 2020-12-08T16:07:36 | 313,039,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 199 | cpp | #include <vm/emulator/cpu.h>
#include <vm/emulator/memory.h>
#include <catch2/catch.hpp>
namespace vm {
TEST_CASE("registers") {
Memory memory;
Bus bus;
CPU cpu(&bus);
}
} // namespace vm
| [
"tiaanl@gmail.com"
] | tiaanl@gmail.com |
730a9289e70893efe3ea3959d3f8c5c6eb3ed405 | 25fa9beca657e1c25ba6096a0f2e017219dd3773 | /include/VBE-Physics2D/Box2D/Dynamics/Joints/b2PulleyJoint.h | 4f986192acfc310d4f3b7a504b5416e4e6080bb0 | [] | no_license | Towerthousand/VBE-Physics2D | 527ec1e4b0f281f3b015cfa5f24031530946cac5 | 129f2db38fc8b0c3b9f6d6f9cf307d9691cb6aaa | refs/heads/master | 2021-01-01T20:01:06.442867 | 2015-01-19T23:38:17 | 2015-01-19T23:38:17 | 27,102,607 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,455 | h | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_PULLEY_JOINT_H
#define B2_PULLEY_JOINT_H
#include <VBE-Physics2D/Box2D/Dynamics/Joints/b2Joint.h>
const float32 b2_minPulleyLength = 2.0f;
/// Pulley joint definition. This requires two ground anchors,
/// two dynamic body anchor points, and a pulley ratio.
struct b2PulleyJointDef : public b2JointDef
{
b2PulleyJointDef()
{
type = e_pulleyJoint;
groundAnchorA.Set(-1.0f, 1.0f);
groundAnchorB.Set(1.0f, 1.0f);
localAnchorA.Set(-1.0f, 0.0f);
localAnchorB.Set(1.0f, 0.0f);
lengthA = 0.0f;
lengthB = 0.0f;
ratio = 1.0f;
collideConnected = true;
}
/// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
void Initialize(b2Body* bodyA, b2Body* bodyB,
const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB,
const b2Vec2& anchorA, const b2Vec2& anchorB,
float32 ratio);
/// The first ground anchor in world coordinates. This point never moves.
b2Vec2 groundAnchorA;
/// The second ground anchor in world coordinates. This point never moves.
b2Vec2 groundAnchorB;
/// The local anchor point relative to bodyA's origin.
b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin.
b2Vec2 localAnchorB;
/// The a reference length for the segment attached to bodyA.
float32 lengthA;
/// The a reference length for the segment attached to bodyB.
float32 lengthB;
/// The pulley ratio, used to simulate a block-and-tackle.
float32 ratio;
};
/// The pulley joint is connected to two bodies and two fixed ground points.
/// The pulley supports a ratio such that:
/// length1 + ratio * length2 <= constant
/// Yes, the force transmitted is scaled by the ratio.
/// Warning: the pulley joint can get a bit squirrelly by itself. They often
/// work better when combined with prismatic joints. You should also cover the
/// the anchor points with static shapes to prevent one side from going to
/// zero length.
class b2PulleyJoint : public b2Joint
{
public:
b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const;
/// Get the first ground anchor.
b2Vec2 GetGroundAnchorA() const;
/// Get the second ground anchor.
b2Vec2 GetGroundAnchorB() const;
/// Get the current length of the segment attached to bodyA.
float32 GetLengthA() const;
/// Get the current length of the segment attached to bodyB.
float32 GetLengthB() const;
/// Get the pulley ratio.
float32 GetRatio() const;
/// Get the current length of the segment attached to bodyA.
float32 GetCurrentLengthA() const;
/// Get the current length of the segment attached to bodyB.
float32 GetCurrentLengthB() const;
/// Dump joint to dmLog
void Dump();
/// Implement b2Joint::ShiftOrigin
void ShiftOrigin(const b2Vec2& newOrigin);
protected:
friend class b2Joint;
b2PulleyJoint(const b2PulleyJointDef* data);
void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data);
b2Vec2 m_groundAnchorA;
b2Vec2 m_groundAnchorB;
float32 m_lengthA;
float32 m_lengthB;
// Solver shared
b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB;
float32 m_constant;
float32 m_ratio;
float32 m_impulse;
// Solver temp
int32 m_indexA;
int32 m_indexB;
b2Vec2 m_uA;
b2Vec2 m_uB;
b2Vec2 m_rA;
b2Vec2 m_rB;
b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB;
float32 m_invMassA;
float32 m_invMassB;
float32 m_invIA;
float32 m_invIB;
float32 m_mass;
};
#endif
| [
"dani.torramilans@gmail.com"
] | dani.torramilans@gmail.com |
358e987560734e48c1fde7eb5421848f162ba774 | 0babb8cbe975befd62e6b4393fdc4a68307ca457 | /ConsoleApplication1/Computer graphics.cpp | bc3e936152afbdb897362880620ac2a01dfc55d2 | [] | no_license | kimujinu/OpenGL | 477ca3d2230fa81d173457754038f115a1b183ec | aa2eac01caac424cdb07979c950c7ecc443c0aee | refs/heads/master | 2020-11-28T10:33:46.828446 | 2019-12-23T16:31:27 | 2019-12-23T16:31:27 | 229,783,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,739 | cpp |
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <GL/glut.h>
void idleFunc();
void displayFunc();
void reshapeFunc(GLsizei width, GLsizei height);
void keyboardFunc(unsigned char, int, int);
void mouseFunc(int button, int state, int x, int y);
void initialize();
void render();
void mirror(GLfloat val);
#define INC_VAL 2.0f
#ifndef M_PI
#define M_PI 3.14159265359
#endif
// width and height of the window
GLsizei g_width = 480;
GLsizei g_height = 360;
// whether to animate
GLboolean g_rotate = GL_TRUE;
// light 0 position
GLfloat g_light0_pos[4] = { 10.0f, 5.0f, 0.0f, 1.0f };
// clipping planes
GLdouble eqn1[4] = { 0.0, 0.0, 1.0, 0.0 };
GLfloat g_inc = 0.0f;
int main(int argc, char ** argv)
{
// initialize GLUT
glutInit(&argc, argv);
// double buffer, use rgb color, enable depth buffer
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH |
GLUT_STENCIL);
// initialize the window size
glutInitWindowSize(g_width, g_height);
// set the window postion
glutInitWindowPosition(100, 100);
// create the window
glutCreateWindow("Mirror Sample");
// set the idle function - called when idle
glutIdleFunc(g_rotate ? idleFunc : NULL);
// set the display function - called when redrawing
glutDisplayFunc(displayFunc);
// set the reshape function - called when client area changes
glutReshapeFunc(reshapeFunc);
// set the keyboard function - called on keyboard events
glutKeyboardFunc(keyboardFunc);
// set the mouse function - called on mouse stuff
glutMouseFunc(mouseFunc);
// do our own initialization
initialize();
// let GLUT handle the current thread from here
glutMainLoop();
return 0;
}
void initialize()
{
// set the GL clear color - use when the color buffer is cleared
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// set the shading model to 'smooth'
glShadeModel(GL_SMOOTH);
// enable depth
glEnable(GL_DEPTH_TEST);
// set the front faces of polygons
glFrontFace(GL_CCW);
// set fill mode
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// set the line width
glLineWidth(2.0f);
// enable lighting
glEnable(GL_LIGHTING);
// enable lighting for front
glLightModeli(GL_FRONT, GL_TRUE);
// material have diffuse and ambient lighting
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
// enable color
glEnable(GL_COLOR_MATERIAL);
// enable light 0
glEnable(GL_LIGHT0);
}
void reshapeFunc(GLsizei w, GLsizei h)
{
// save the new window size
g_width = w; g_height = h;
// map the view port to the client area
glViewport(0, 0, w, h);
// set the matrix mode to project
glMatrixMode(GL_PROJECTION);
// load the identity matrix
glLoadIdentity();
// create the viewing frustum
gluPerspective(45.0, (GLfloat)w / (GLfloat)h, 1.0, 300.0);
// set the matrix mode to modelview
glMatrixMode(GL_MODELVIEW);
// load the identity matrix
glLoadIdentity();
// position the view point
gluLookAt(0.0f, 1.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
}
void keyboardFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 'Q':
case 'q':
exit(1);
break;
}
// do a reshape since g_eye_y might have changed
reshapeFunc(g_width, g_height);
glutPostRedisplay();
}
void mouseFunc(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON)
{
// rotate
if (state == GLUT_DOWN)
g_inc -= INC_VAL;
else
g_inc += INC_VAL;
}
else if (button == GLUT_RIGHT_BUTTON)
{
if (state == GLUT_DOWN)
g_inc += INC_VAL;
else
g_inc -= INC_VAL;
}
else
g_inc = 0.0f;
glutPostRedisplay();
}
void idleFunc()
{
// render the scene
glutPostRedisplay();
}
void displayFunc()
{
static GLfloat angle = 0.0;
GLfloat val = .8f;
GLint buffers = GL_NONE;
// get the current color buffer being drawn to
glGetIntegerv(GL_DRAW_BUFFER, &buffers);
glPushMatrix();
// rotate the viewpoint
glRotatef(angle += g_inc, 0.0f, 1.0f, 0.0f);
// set the clear value
glClearStencil(0x0);
// clear the stencil buffer
glClear(GL_STENCIL_BUFFER_BIT);
// always pass the stencil test
glStencilFunc(GL_ALWAYS, 0x1, 0x1);
// set the operation to modify the stencil buffer
glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
// disable drawing to the color buffer
glDrawBuffer(GL_NONE);
// enable stencil
glEnable(GL_STENCIL_TEST);
// draw the stencil mask
glBegin(GL_QUADS);
mirror(val);
glEnd();
// reenable drawing to color buffer
glDrawBuffer((GLenum)buffers);
// make stencil buffer read only
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// clear the color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// draw the mirror image
glPushMatrix();
// invert image about xy plane
glScalef(1.0f, 1.0f, -1.0f);
// invert the clipping plane based on the view point
if (cos(angle * M_PI / 180.0) < 0.0)
eqn1[2] = -1.0;
else
eqn1[2] = 1.0;
// clip one side of the plane
glClipPlane(GL_CLIP_PLANE0, eqn1);
glEnable(GL_CLIP_PLANE0);
// draw only where the stencil buffer == 1
glStencilFunc(GL_EQUAL, 0x1, 0x1);
// draw the object
render();
// turn off clipping plane
glDisable(GL_CLIP_PLANE0);
glPopMatrix();
// disable the stencil buffer
glDisable(GL_STENCIL_TEST);
// disable drawing to the color buffer
glDrawBuffer(GL_NONE);
// draw the mirror pane into depth buffer -
// to prevent object behind mirror from being render
glBegin(GL_QUADS);
mirror(val);
glEnd();
// enable drawing to the color buffer
glDrawBuffer((GLenum)buffers);
// draw the normal image, without stencil test
glPushMatrix();
render();
glPopMatrix();
// draw the outline of the mirror
glColor3f(0.4f, 0.4f, 1.0f);
glBegin(GL_LINE_LOOP);
mirror(val);
glEnd();
// mirror shine
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glDepthMask(GL_FALSE);
glDepthFunc(GL_LEQUAL);
glDisable(GL_LIGHTING);
glColor4f(1.0f, 1.0f, 1.0f, .2f);
glTranslatef(0.0f, 0.0f, 0.01f * eqn1[2]);
glBegin(GL_QUADS);
mirror(val);
glEnd();
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHTING);
glPopMatrix();
glFlush();
glutSwapBuffers();
}
void mirror(GLfloat val)
{
glVertex3f(val, val, 0.0f);
glVertex3f(-val, val, 0.0f);
glVertex3f(-val, -val, 0.0f);
glVertex3f(val, -val, 0.0f);
}
void render()
{
glLightfv(GL_LIGHT0, GL_POSITION, g_light0_pos);
glPushMatrix();
glColor3f(.4f, 1.0f, .4f);
glTranslatef(0.0f, 0.0f, 2.5f);
glutSolidSphere(0.5, 12, 12);
glTranslatef(0.5f, 0.0f, -0.7f);
glColor3f(1.0f, .4f, .4f);
glutWireTeapot(0.0);
glTranslatef(-0.5f, 0.0f, -0.2f);
glRotatef(-90, 1.0f, 0.0f, 0.0f);
glColor3f(1.0f, 1.0f, .4f);
glutSolidCone(.3, .6, 8, 8);
glPopMatrix();
glPushMatrix();
glTranslatef(0.2f, 0.3f, -2.0f);
glColor3f(.9f, .4f, .9f);
glutWireTeapot(0.5);
glPopMatrix();
}
| [
"dnehd6739@naver.com"
] | dnehd6739@naver.com |
2bde1c403a9a8eb994890ac9c3a53cdb03a6d46f | 3bbf8a6c3d629c6a612d6d33ca220eecdb935e12 | /aws-cpp-sdk-sms-voice/include/aws/sms-voice/model/EventDestination.h | 2e037ba4488a369553bb54ba83ae9a5e20c81ac8 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | julio-gorge/aws-sdk-cpp | a8c067adf072ff43c686a15092e54ad2393cc1d4 | 06b0d54110172b3cf9b3f5602060304e36afd225 | refs/heads/master | 2021-10-22T15:00:07.328784 | 2019-03-11T12:08:52 | 2019-03-11T12:08:52 | 161,850,005 | 0 | 0 | Apache-2.0 | 2018-12-14T23:11:43 | 2018-12-14T23:11:43 | null | UTF-8 | C++ | false | false | 7,654 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/sms-voice/PinpointSMSVoice_EXPORTS.h>
#include <aws/sms-voice/model/CloudWatchLogsDestination.h>
#include <aws/sms-voice/model/KinesisFirehoseDestination.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/sms-voice/model/SnsDestination.h>
#include <aws/sms-voice/model/EventType.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace PinpointSMSVoice
{
namespace Model
{
/**
* An object that defines an event destination.<p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-sms-voice-2018-09-05/EventDestination">AWS
* API Reference</a></p>
*/
class AWS_PINPOINTSMSVOICE_API EventDestination
{
public:
EventDestination();
EventDestination(Aws::Utils::Json::JsonView jsonValue);
EventDestination& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
inline const CloudWatchLogsDestination& GetCloudWatchLogsDestination() const{ return m_cloudWatchLogsDestination; }
inline void SetCloudWatchLogsDestination(const CloudWatchLogsDestination& value) { m_cloudWatchLogsDestinationHasBeenSet = true; m_cloudWatchLogsDestination = value; }
inline void SetCloudWatchLogsDestination(CloudWatchLogsDestination&& value) { m_cloudWatchLogsDestinationHasBeenSet = true; m_cloudWatchLogsDestination = std::move(value); }
inline EventDestination& WithCloudWatchLogsDestination(const CloudWatchLogsDestination& value) { SetCloudWatchLogsDestination(value); return *this;}
inline EventDestination& WithCloudWatchLogsDestination(CloudWatchLogsDestination&& value) { SetCloudWatchLogsDestination(std::move(value)); return *this;}
/**
* Indicates whether or not the event destination is enabled. If the event
* destination is enabled, then Amazon Pinpoint sends response data to the
* specified event destination.
*/
inline bool GetEnabled() const{ return m_enabled; }
/**
* Indicates whether or not the event destination is enabled. If the event
* destination is enabled, then Amazon Pinpoint sends response data to the
* specified event destination.
*/
inline void SetEnabled(bool value) { m_enabledHasBeenSet = true; m_enabled = value; }
/**
* Indicates whether or not the event destination is enabled. If the event
* destination is enabled, then Amazon Pinpoint sends response data to the
* specified event destination.
*/
inline EventDestination& WithEnabled(bool value) { SetEnabled(value); return *this;}
inline const KinesisFirehoseDestination& GetKinesisFirehoseDestination() const{ return m_kinesisFirehoseDestination; }
inline void SetKinesisFirehoseDestination(const KinesisFirehoseDestination& value) { m_kinesisFirehoseDestinationHasBeenSet = true; m_kinesisFirehoseDestination = value; }
inline void SetKinesisFirehoseDestination(KinesisFirehoseDestination&& value) { m_kinesisFirehoseDestinationHasBeenSet = true; m_kinesisFirehoseDestination = std::move(value); }
inline EventDestination& WithKinesisFirehoseDestination(const KinesisFirehoseDestination& value) { SetKinesisFirehoseDestination(value); return *this;}
inline EventDestination& WithKinesisFirehoseDestination(KinesisFirehoseDestination&& value) { SetKinesisFirehoseDestination(std::move(value)); return *this;}
inline const Aws::Vector<EventType>& GetMatchingEventTypes() const{ return m_matchingEventTypes; }
inline void SetMatchingEventTypes(const Aws::Vector<EventType>& value) { m_matchingEventTypesHasBeenSet = true; m_matchingEventTypes = value; }
inline void SetMatchingEventTypes(Aws::Vector<EventType>&& value) { m_matchingEventTypesHasBeenSet = true; m_matchingEventTypes = std::move(value); }
inline EventDestination& WithMatchingEventTypes(const Aws::Vector<EventType>& value) { SetMatchingEventTypes(value); return *this;}
inline EventDestination& WithMatchingEventTypes(Aws::Vector<EventType>&& value) { SetMatchingEventTypes(std::move(value)); return *this;}
inline EventDestination& AddMatchingEventTypes(const EventType& value) { m_matchingEventTypesHasBeenSet = true; m_matchingEventTypes.push_back(value); return *this; }
inline EventDestination& AddMatchingEventTypes(EventType&& value) { m_matchingEventTypesHasBeenSet = true; m_matchingEventTypes.push_back(std::move(value)); return *this; }
/**
* A name that identifies the event destination configuration.
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* A name that identifies the event destination configuration.
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* A name that identifies the event destination configuration.
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* A name that identifies the event destination configuration.
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* A name that identifies the event destination configuration.
*/
inline EventDestination& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* A name that identifies the event destination configuration.
*/
inline EventDestination& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* A name that identifies the event destination configuration.
*/
inline EventDestination& WithName(const char* value) { SetName(value); return *this;}
inline const SnsDestination& GetSnsDestination() const{ return m_snsDestination; }
inline void SetSnsDestination(const SnsDestination& value) { m_snsDestinationHasBeenSet = true; m_snsDestination = value; }
inline void SetSnsDestination(SnsDestination&& value) { m_snsDestinationHasBeenSet = true; m_snsDestination = std::move(value); }
inline EventDestination& WithSnsDestination(const SnsDestination& value) { SetSnsDestination(value); return *this;}
inline EventDestination& WithSnsDestination(SnsDestination&& value) { SetSnsDestination(std::move(value)); return *this;}
private:
CloudWatchLogsDestination m_cloudWatchLogsDestination;
bool m_cloudWatchLogsDestinationHasBeenSet;
bool m_enabled;
bool m_enabledHasBeenSet;
KinesisFirehoseDestination m_kinesisFirehoseDestination;
bool m_kinesisFirehoseDestinationHasBeenSet;
Aws::Vector<EventType> m_matchingEventTypes;
bool m_matchingEventTypesHasBeenSet;
Aws::String m_name;
bool m_nameHasBeenSet;
SnsDestination m_snsDestination;
bool m_snsDestinationHasBeenSet;
};
} // namespace Model
} // namespace PinpointSMSVoice
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
3e65d1676b3dae5173ac46584b67e23e1f19863f | 911ea9deb0418b350531ebed386567c3c784b37d | /HeroscapeEditor/Maths/COLOR.h | 8cabded43734a56783ca328f285d10277c3d4bcd | [] | no_license | dkniffin/virtualscape | 7088ca22a2815f7c1ba22d43671dd192eea77d32 | 7c80625e1b152fb1e7836c83d4165cf79eca1c7d | refs/heads/master | 2020-12-31T03:26:12.985542 | 2014-03-11T16:51:11 | 2014-03-11T16:51:11 | 17,637,322 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,901 | h | //////////////////////////////////////////////////////////////////////////////////////////
// COLOR.h
// Class declaration for an RGBA color
// You may use this code however you wish, but if you do, please credit me and
// provide a link to my website in a readme file or similar
// Downloaded from: www.paulsprojects.net
// Created: 20th July 2002
// Modified: 7th November 2002 - Some speed improvements
// - Removed clamping after adds etc. Do it yourself!
// To enable use with floating point color buffers
// - Corrected lerp (reversed f and 1-f)
// 13th December 2002 - Added default parameter to alpha of Set()
// - Added red, green, blue constant COLORs
//////////////////////////////////////////////////////////////////////////////////////////
#ifndef COLOR_H
#define COLOR_H
class COLOR
{
public:
//constructors
COLOR()
{ r=g=b=a=0.0f; }
COLOR(float newR, float newG, float newB, float newA=0.0f)
{ r=newR; g=newG; b=newB; a=newA; }
COLOR(const float * rhs)
{ r=*rhs; g=*(rhs+1); b=*(rhs+2); a=*(rhs+3); }
COLOR(const COLOR & rhs)
{ r=rhs.r; g=rhs.g; b=rhs.b; a=rhs.a;}
~COLOR() {} //empty
void Set(float newR, float newG, float newB, float newA=0.0f)
{ r=newR; g=newG; b=newB; a=newA; }
//accessors kept for compatability
void SetR(float newR) {r = newR;}
void SetG(float newG) {g = newG;}
void SetB(float newB) {b = newB;}
void SetA(float newA) {a = newA;}
float GetR() const {return r;} //public accessor functions
float GetG() const {return g;} //inline, const
float GetB() const {return b;}
float GetA() const {return a;}
void ClampTo01(void); //clamp all components to [0,1]
void SetBlack(void) {r=g=b=a=1.0f;}
void SetWhite(void) {r=g=b=a=0.0f;}
void SetGrey(float shade) {r=g=b=a=shade;}
//linear interpolate
COLOR lerp(const COLOR & c2, float factor)
{ return (*this)*(1.0f-factor) + c2*factor; }
//binary operators
COLOR operator+(const COLOR & rhs) const
{ return COLOR(r+rhs.r, g+rhs.g, b+rhs.b, a+rhs.a); }
COLOR operator-(const COLOR & rhs) const
{ return COLOR(r-rhs.r, g-rhs.g, b-rhs.b, a-rhs.a); }
COLOR operator*(const COLOR & rhs) const
{ return COLOR(r*rhs.r, g*rhs.g, b*rhs.b, a*rhs.a); }
COLOR operator/(const COLOR & rhs) const
{ return COLOR(r/rhs.r, g/rhs.g, b/rhs.b, a/rhs.a); }
COLOR operator*(const float rhs) const
{ return COLOR(r*rhs, g*rhs, b*rhs, a*rhs); }
COLOR operator/(const float rhs) const
{ return COLOR(r/rhs, g/rhs, b/rhs, a/rhs); }
//multiply by a float, eg 3*c
friend COLOR operator*(float scaleFactor, const COLOR & rhs);
bool operator==(const COLOR & rhs) const;
bool operator!=(const COLOR & rhs) const
{ return !((*this)==rhs); }
//self-add etc
COLOR operator+=(const COLOR & rhs)
{ (*this)=(*this)+rhs; return (*this); }
COLOR operator-=(const COLOR & rhs)
{ (*this)=(*this)-rhs; return (*this); }
COLOR operator*=(const COLOR & rhs)
{ (*this)=(*this)*rhs; return (*this); }
COLOR operator/=(const COLOR & rhs)
{ (*this)=(*this)/rhs; return (*this); }
COLOR operator*=(const float rhs)
{ (*this)=(*this)*rhs; return (*this); }
COLOR operator/=(const float rhs)
{ (*this)=(*this)/rhs; return (*this); }
//unary operators
COLOR operator-(void) const {return COLOR(-r,-g, -b, -a);}
COLOR operator+(void) const {return (*this);}
//cast to pointer to float for glColor4fv etc
operator float* () const {return (float*) this;}
operator const float* () const {return (const float*) this;}
//member variables
float r;
float g;
float b;
float a;
};
const COLOR white(1.0f, 1.0f, 1.0f, 1.0f);
const COLOR black(0.0f, 0.0f, 0.0f, 0.0f);
const COLOR red(1.0f, 0.0f, 0.0f, 1.0f);
const COLOR green(0.0f, 1.0f, 0.0f, 1.0f);
const COLOR blue(0.0f, 0.0f, 1.0f, 1.0f);
const COLOR cyan(0.0f, 1.0f, 1.0f, 1.0f);
const COLOR magenta(1.0f, 0.0f, 1.0f, 1.0f);
const COLOR yellow(1.0f, 1.0f, 0.0f, 1.0f);
#endif //COLOR_H | [
"oddityoverseer13@gmail.com"
] | oddityoverseer13@gmail.com |
a176f963724d34018e27d1db1206f2abd6fdcad0 | 9f7a5e5c6dfce8daa9c6c748c61851a5e8b1464b | /034_QWidget/testWidget01/build/ui_newfile.h | 0d2f41b23d097a20e628a247db58837ee0bde1ec | [] | no_license | jash-git/Jash_QT | fdaf4eb2d6575d19ed17f35c57af25940f80554d | 5e44333512e048649e6b7038428487348fda52aa | refs/heads/master | 2023-05-28T11:24:23.585919 | 2021-06-06T12:43:10 | 2021-06-06T12:43:10 | 372,838,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,224 | h | /********************************************************************************
** Form generated from reading ui file 'newfile.ui'
**
** Created: Sun Aug 22 15:52:29 2010
** by: Qt User Interface Compiler version 4.5.0
**
** WARNING! All changes made in this file will be lost when recompiling ui file!
********************************************************************************/
#ifndef UI_NEWFILE_H
#define UI_NEWFILE_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Form
{
public:
void setupUi(QWidget *Form)
{
if (Form->objectName().isEmpty())
Form->setObjectName(QString::fromUtf8("Form"));
Form->resize(400, 300);
retranslateUi(Form);
QMetaObject::connectSlotsByName(Form);
} // setupUi
void retranslateUi(QWidget *Form)
{
Form->setWindowTitle(QApplication::translate("Form", "Form", 0, QApplication::UnicodeUTF8));
Q_UNUSED(Form);
} // retranslateUi
};
namespace Ui {
class Form: public Ui_Form {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_NEWFILE_H
| [
"jash.liao@gmail.com"
] | jash.liao@gmail.com |
abb31211fca05bdb4d9b5517dff37eba5ef44732 | 3287ddd28c9c8c3e066ce3176018a1e354923cc9 | /RezillaSource/Rezilla_Src/Architecture/CRezillaPlugin.h | c8d06c0a3042a0390e17c40fb19209671677bc50 | [] | no_license | chrisballinger/rezilla | 9e6bf9f0343712fae0a6fd5931259a48e7e5ec2b | 72c4cfd1a2d45565d2b429bd6afff8bf426f5c65 | refs/heads/master | 2021-05-11T09:31:21.967833 | 2018-01-19T04:24:33 | 2018-01-19T04:24:33 | 118,075,864 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,024 | h | // ===========================================================================
// CRezillaPlugin.h
//
// Created: 2005-09-26 09:48:26
// Last modification: 2006-11-25 07:31:00
// Author: Bernard Desgraupes
// e-mail: <bdesgraupes@sourceforge.users.fr>
// www: <http://rezilla.sourceforge.net/>
// (c) Copyright: Bernard Desgraupes, 2005-2006
// All rights reserved.
// ===========================================================================
#ifndef _H_CRezillaPlugin
#define _H_CRezillaPlugin
#pragma once
#include "RezillaPluginInterface.h"
#include <LModelObject.h>
class CRezMap;
class CRezillaPlugin : public LModelObject {
public:
CRezillaPlugin(CFBundleRef inBundleRef);
virtual ~CRezillaPlugin();
OSErr Load();
Boolean IsSupported(ResType inType);
CRezMap * OpenResources();
UInt8 CreateMenus(UInt8 inMenuCount, MenuID * inMenuIDs);
virtual SPluginEditorInterface** GetInterface() {return mInterface;}
virtual CFPlugInRef GetPluginRef() { return mPluginRef;}
virtual short GetRefnum() { return mRefNum;}
UInt32 CountEditTypes() { return mEditTypes.GetCount(); }
// AppleEvents
virtual void MakeSelfSpecifier(
AEDesc& inSuperSpecifier,
AEDesc& outSelfSpecifier) const;
virtual void GetAEProperty(
DescType inProperty,
const AEDesc& inRequestedType,
AEDesc& outPropertyDesc) const;
virtual bool AEPropertyExists(
DescType inProperty) const;
static SInt32 GetAEPosition(const CRezillaPlugin * inPlugin);
// Accessors
TArray<OSType> * GetEditTypes() { return &mEditTypes;}
TArray<LMenu*> * GetMenusList() { return &mMenusList;}
CFStringRef GetName() { return mName;}
UInt32 GetPluginType() { return mPluginType;}
UInt32 GetPluginCreator() { return mPluginCreator;}
UInt32 GetPluginVersion() { return mPluginVersion;}
UInt32 GetPluginRole() { return mPluginRole;}
Boolean IsLoaded() { return mIsLoaded;}
IconRef GetIconRef() { return mIconRef;}
protected:
CFPlugInRef mPluginRef;
short mRefNum;
SPluginEditorInterface ** mInterface;
TArray<OSType> mEditTypes;
TArray<LMenu*> mMenusList;
Boolean mMenusBuilt;
Boolean mIsLoaded; // differed loading
UInt32 mPluginType,
mPluginCreator,
mPluginVersion,
mPluginRole;
CFStringRef mName;
IconRef mIconRef;
private:
void Initialize(CFBundleRef inBundleRef);
};
// ===========================================================================
// Inline function definitions
// ===========================================================================
// ---------------------------------------------------------------------------
// IsSupported [inline] [public]
// ---------------------------------------------------------------------------
inline Boolean
CRezillaPlugin::IsSupported(ResType inType) { return mEditTypes.ContainsItem(inType); }
#endif
| [
"bdesgraupes@a0aff4df-974a-46cd-ba52-22e6818bbca1"
] | bdesgraupes@a0aff4df-974a-46cd-ba52-22e6818bbca1 |
27d5bdf9d25145be58502b632bff8b311b85be28 | cfbe32d3c679487610e0a8e924c33ab6aa64f3d1 | /codeforces/381B.cpp | b1399cf812c2a813d2ac3e0f53e1a88630cc0cf0 | [] | no_license | hophacker/algorithm_coding | 6062fafd00e276baeb5ef92198c6c1dab66b6184 | bfc9a124ed21eabf241590b90105427f0a2b6573 | refs/heads/master | 2020-06-04T00:41:25.378594 | 2014-07-07T00:50:35 | 2014-07-07T00:50:35 | 18,478,412 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,718 | cpp | #include <cmath>
#include <vector>
#include <map>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cassert>
using namespace std;
#define bit(x,i) (x&(1<<i))
#define max(a,b) (a<b?b:a)
#define abs(x) (x<0?-x:x)
#define IN(i,l,r) (l<i&&i<r)
#define LINR(i,l,r) (l<=i&&i<=r)
#define LIN(i,l,r) (l<=i&&i<r)
#define INR(i,l,r) (l<i&&i<r)
#define F(i,L,R) for (int i = L; i < R; i++)
#define FE(i,L,R) for (int i = L; i <= R; i++)
#define FF(i,L,R) for (int i = L; i > R; i--)
#define FFE(i,L,R) for (int i = L; i >= R; i--)
#define char2Int(c) (c-'0')
#define lastEle(vec) vec[vec.size()-1]
#define hBit(msb,n) asm("bsrl %1,%0" : "=r"(msb) : "r"(n))
#define clr(a,x) memset(a,x,sizeof(a))
#define getI(a) scanf("%d", &a)
#define getII(a,b) scanf("%d%d", &a, &b)
#define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c)
#define getS(x) scanf("%s", x);
#define ll long long
#define ui unsigned int
#define us unsigned short
int main ( int argc, char *argv[] ) {
//ios_base::sync_with_stdio(0);
int N;
int a[100010];
int b[100010], bN = 0, c[100010], cN = 1;
getI(N);
F(i,0,N) getI(a[i]);
sort(a, a+N);
int count = 1, total = 1;
c[0] = a[0];
F(i,1,N) {
if (a[i] == a[i-1])
count++;
else count = 1;
if (count == 2){
b[bN++] = a[i];
total++;
} else if (count == 1){
c[cN++] = a[i];
total++;
}
}
if (b[bN-1] == c[cN-1]) total--, bN--;
cout << total << endl;
printf("%d", c[0]);
F(i,1,cN) printf(" %d", c[i]);
FFE(i,bN-1,0) printf(" %d", b[i]);
printf("\n");
return EXIT_SUCCESS;
}
| [
"jokerfeng2010@gmail.com"
] | jokerfeng2010@gmail.com |
111ff6d541f11e05c315b358ba47a6a06000e592 | 958488bc7f3c2044206e0358e56d7690b6ae696c | /c++/test.cpp | 06bf3a1aa590c61723afcaeab5df8520da90e16a | [] | no_license | possientis/Prog | a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4 | d4b3debc37610a88e0dac3ac5914903604fd1d1f | refs/heads/master | 2023-08-17T09:15:17.723600 | 2023-08-11T12:32:59 | 2023-08-11T12:32:59 | 40,361,602 | 3 | 0 | null | 2023-03-27T05:53:58 | 2015-08-07T13:24:19 | Coq | UTF-8 | C++ | false | false | 342 | cpp | #include<functional>
class myclass {
private:
std::function<int(int,int)> func;
public:
myclass(std::function<int(int,int)> func):func(func){}
myclass(const myclass& other):func(other.func){}
int operator()(int a,int b){return func(a,b);};
};
int main(){
myclass a([](int i,int j){ return 2*i + j; });
return 0;
}
| [
"paul_ossientis@riseup.net"
] | paul_ossientis@riseup.net |
c08829a98acf67616a51bd8f99a995f0fe1d2454 | 7869cd658cc2bf4bcaa29d5295f33740c2384bae | /src/opengl/shader.hpp | 882d1a2590076b19a920ced8a4c4bb016d2d759b | [
"MIT"
] | permissive | geaz/emu-chip-8 | 19a5f8d3999c6f4b3648dfa1010d1593b4eadb0f | 82a768e363378d666a7e06245e598f77fa1fd555 | refs/heads/master | 2021-06-19T03:13:15.201775 | 2021-05-17T13:22:55 | 2021-05-17T13:22:55 | 207,106,803 | 35 | 5 | MIT | 2021-05-17T13:22:56 | 2019-09-08T12:06:51 | C++ | UTF-8 | C++ | false | false | 4,587 | hpp | // Shader Loader took from https://learnopengl.com
#pragma once
#ifndef SHADER_H
#define SHADER_H
#include <glad/glad.h>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class Shader
{
public:
Shader() { }
Shader(const char* vertexPath, const char* fragmentPath)
{
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
try
{
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
vShaderFile.close();
fShaderFile.close();
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure e)
{
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
}
const char* vShaderCode = vertexCode.c_str();
const char * fShaderCode = fragmentCode.c_str();
unsigned int vertex, fragment;
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
checkCompileErrors(fragment, "FRAGMENT");
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
glDeleteShader(vertex);
glDeleteShader(fragment);
}
void use()
{
glUseProgram(ID);
}
void setBool(const std::string &name, bool value)
{
int location = glGetUniformLocation(ID, name.c_str());
glUniform1i(location, (int)value);
}
void setInt(const std::string &name, int value)
{
int location = glGetUniformLocation(ID, name.c_str());
glUniform1i(location, value);
}
void setFloat(const std::string &name, float value)
{
int location = glGetUniformLocation(ID, name.c_str());
glUniform1f(location, value);
}
void setVec4(const std::string &name, float value1, float value2, float value3, float value4)
{
int location = glGetUniformLocation(ID, name.c_str());
glUniform4f(location, value1, value2, value3, value4);
}
void setMatrix4(const std::string &name, const glm::mat4 &matrix)
{
int location = glGetUniformLocation(ID, name.c_str());
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(matrix));
}
unsigned int ID;
private:
void checkCompileErrors(unsigned int shader, std::string type)
{
int success;
char infoLog[1024];
if (type != "PROGRAM")
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
}
}
else
{
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
}
}
}
};
#endif
| [
"geaz@users.noreply.github.com"
] | geaz@users.noreply.github.com |
5da31f9d3c8770bf59ab4676c8fc0271a7c24e4e | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /third_party/WebKit/Source/core/dom/NodeIteratorBase.h | e21d76c5b034e50906fa44ac4dbd62ee8eb05178 | [
"BSD-3-Clause",
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 1,896 | h | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* Copyright (C) 2000 Frederik Holljen (frederik.holljen@hig.no)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2004, 2008 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef NodeIteratorBase_h
#define NodeIteratorBase_h
#include "platform/bindings/TraceWrapperMember.h"
#include "platform/heap/Handle.h"
namespace blink {
class ExceptionState;
class Node;
class V8NodeFilterCondition;
class NodeIteratorBase : public GarbageCollectedMixin {
public:
Node* root() const { return root_.Get(); }
unsigned whatToShow() const { return what_to_show_; }
V8NodeFilterCondition* filter() const { return filter_.Get(); }
DECLARE_VIRTUAL_TRACE();
DECLARE_VIRTUAL_TRACE_WRAPPERS();
protected:
NodeIteratorBase(Node*, unsigned what_to_show, V8NodeFilterCondition*);
unsigned AcceptNode(Node*, ExceptionState&) const;
private:
Member<Node> root_;
unsigned what_to_show_;
TraceWrapperMember<V8NodeFilterCondition> filter_;
};
} // namespace blink
#endif // NodeIteratorBase_h
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
c49ade43b9fad7aa56213033fcf5e61aeb435451 | 9c7c58220a546d583e22f8737a59e7cc8bb206e6 | /Project/MyProject/MyProject/Source/MyProject/Private/BaseFrame/Libs/Resource/ResLoad/LoadItem/DataAssetLoadItem.cpp | 2cb73a83ec01edd2b416f37c0d049d80e1050ad9 | [] | no_license | SiCoYu/UE | 7176f9ece890e226f21cf972e5da4c3c4c4bfe41 | 31722c056d40ad362e5c4a0cba53b05f51a19324 | refs/heads/master | 2021-03-08T05:00:32.137142 | 2019-07-03T12:20:25 | 2019-07-03T12:20:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 886 | cpp | #include "MyProject.h"
#include "DataAssetLoadItem.h"
#include "MByteBuffer.h"
//UDataAssetLoadItem::UDataAssetLoadItem(const FObjectInitializer& ObjectInitializer)
// : Super(ObjectInitializer)
//{
//
//}
void UDataAssetLoadItem::loadFile(const FString& Filename)
{
// if the file has some data in it, read it in
if (IFileManager::Get().FileSize(*Filename) >= 0)
{
/*FString Text;
if (FFileHelper::LoadFileToString(Text, *Filename))
{
MByteBuffer* fileBU = new MByteBuffer(Text.GetAllocatedSize());
fileBU->writeBytes(TCHAR_TO_ANSI(Text.GetCharArray().GetData()), 0, Text.GetAllocatedSize());
}*/
TArray<uint8> arrayBuffer;
if (FFileHelper::LoadFileToArray(arrayBuffer, *Filename))
{
MByteBuffer* fileBU = MY_NEW MByteBuffer(arrayBuffer.GetAllocatedSize());
fileBU->writeBytes((char*)(arrayBuffer.GetData()), 0, arrayBuffer.GetAllocatedSize());
}
}
} | [
"kuangben2001@163.com"
] | kuangben2001@163.com |
efe39af88a44b626de390e10f16920f875458c1c | bfa6d5324e2c6551064b36f7ffb9ec5c12877938 | /IEEEXTREME19/strictly.cpp | 18be51521d985872fb67566ed9674bb2e524aaa1 | [] | no_license | Bruno-Mascarenhas/competitive-programming | 6c1ff45418e589601bb347c5a86ff06d59fe1b41 | 93d35ed8abc825673cff57a3540d96f30e6c527b | refs/heads/master | 2021-06-15T05:43:36.961850 | 2021-04-18T05:20:37 | 2021-04-18T05:20:37 | 180,717,967 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,090 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pi 3.1415926535897932384626
#define pb push_back
#define ff first
#define ss second
#define debug(x) cout << #x " = " << (x) << endl
#define DESYNC ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define endl '\n'
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> pii;
typedef vector<pii> vii;
//Compilation flags // g++ -std=c++17 -O3 -Wshadow -Wall -fsanitize=address -fsanitize=undefined -D_GLIBCXX_DEBUG -g
struct point{
int x, y;
point(){};
point(int _x, int _y) : x(_x), y(_y) {};
bool operator<(const point &a) const{
return make_pair(x,y) < make_pair(a.x,a.y);
}
point operator+(const point &a){
return point(x + a.x, y + a.y);
}
point operator-(const point &a){
return point(x - a.x, y - a.y);
}
};
int dot(point a, point b){
return a.x*b.x + a.y*b.y;
}
int cross(point a, point b){
return a.x*b.y - a.y*b.x;
}
bool ccw(point a, point b, point c){
return cross(b-a,c-a) > 0;
}
bool intersect(point a, point b, point c, point d){
if(ccw(a,b,c) != ccw(a,b,d) && ccw(c,d,a) != ccw(c,d,b))
return true;
return false;
}
vector<point> ConvexHull(vector<point> points){
int n = points.size(), k = 0;
sort(points.begin(),points.end());
vector<point> ans(2*n);
for(int i=0; i<n; i++){
while(k>=2 && !ccw(ans[k-2],ans[k-1],points[i])) k--;
ans[k++] = points[i];
}
for(int i=n-2, t=k+1; i>=0; i--){
while(k>=t && !ccw(ans[k-2],ans[k-1],points[i])) k--;
ans[k++] = points[i];
}
ans.resize(k);
return ans;
}
bool onSegment(point a, point b, point c){
int crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y);
if(crossproduct != 0) return false;
int dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y);
if(dotproduct < 0) return false;
int squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y);
if(dotproduct > squaredlengthba) return false;
return true;
}
int n, m;
int32_t main(){
DESYNC;
cin>>n>>m;
vector<point> hull(n), pts(m);
for(auto &x:hull) cin>>x.x>>x.y;
for(auto &x:pts) cin>>x.x>>x.y;
vector<point> polygon = ConvexHull(hull);
int ans=0;
map<pair<point,point>,int> cnt;
for(int i=0; i<m; i++)
for(int j=0; j<m; j++)
if(i!=j){
bool f = 1;
for(int k=1; k<n; k++)
if(intersect(pts[i],pts[j],polygon[k],polygon[k-1]) || onSegment(pts[i],pts[j],polygon[k]) || onSegment(pts[i],pts[j],polygon[k-1])){
f=0; break;
}
if(f){
if(cnt[{pts[i],pts[j]}]==0 && cnt[{pts[j],pts[i]}]==0){
ans++;
cnt[{pts[i],pts[j]}]=1;
//cout<<pts[i].x<<" "<<pts[i].y<<" "<<pts[j].x<<" "<<pts[j].y<<endl;
}
}
}
cout<<ans<<endl;
}
| [
"brunomasck@gmail.com"
] | brunomasck@gmail.com |
59c3436918d76cfe0142242d180624c2a51a5124 | 9f4b1f53e4541ffe546bc2d4607683a5f2cfa2db | /HostKernel/scancontrol/scancontrol.cpp | 6f17c85f370c3d714e3e7654a1d5b2def40ee861 | [] | no_license | CtScanMasters/HostProject | a2a63747719f3e6bbcd8600174e625c735cf9e05 | 4318def9ef836acccb70f2b9e94898a6c0383807 | refs/heads/master | 2020-03-10T20:22:43.881695 | 2018-06-22T18:48:51 | 2018-06-22T18:48:51 | 129,569,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,973 | cpp | #include "scancontrol.h"
#include <QDebug>
#include <QThread>
#include "hardwarecontrol/bcm2835.h"
ScanControl::ScanControl(QObject *parent)
{
setName("ScanControl: ");
logMessage(MSG_INFO, "build");
enableLogging(false);
m_numberOfArrays = 8;
m_numberOfSources = 8;
m_sourceMuxAddress = 127;
m_chipSelectPin1 = BCM2835_SPI_CS1;
m_EN_1 = RPI_V2_GPIO_P1_11;
m_A0_1 = RPI_V2_GPIO_P1_16;
m_A1_1 = RPI_V2_GPIO_P1_13;
m_A2_1 = RPI_V2_GPIO_P1_15;
m_sensorMuxAddress = 128;
m_chipSelectPin0 = BCM2835_SPI_CS0;
m_EN_0 = RPI_V2_GPIO_P1_35;
m_A0_0 = RPI_V2_GPIO_P1_36;
m_A1_0 = RPI_V2_GPIO_P1_37;
m_A2_0 = RPI_V2_GPIO_P1_38;
buildScanControl();
}
void ScanControl::doScan(quint8 startAddress, ScanData &scanData)
{
logMessage(MSG_INFO, QString("doScan: %1").arg(startAddress));
for(quint8 arrayAddress = startAddress; arrayAddress < (startAddress + 4); arrayAddress++)
{
for(quint8 sourceNumber = 0; sourceNumber < m_numberOfSources; sourceNumber++)
{
m_multiplexerSource->setChannel(arrayAddress);
m_sourceArrayManager->setSource(arrayAddress, sourceNumber);
bcm2835_delay(10);
scanData.addArrayScan(arrayAddress, sourceNumber);
m_sensorArrayManager->scanArray(arrayAddress, scanData);
}
m_sourceArrayManager->clearSource(arrayAddress);
}
}
void ScanControl::buildScanControl()
{
m_multiplexerSensor = new Multiplexer(m_sourceMuxAddress, m_EN_0, m_A0_0, m_A1_0, m_A2_0);
m_multiplexerSource = new Multiplexer(m_sensorMuxAddress, m_EN_1, m_A0_1, m_A1_1, m_A2_1);
m_chipSelectManager = new ChipSelectManager(m_multiplexerSource, m_chipSelectPin0, m_multiplexerSensor, m_chipSelectPin1);
m_sourceArrayManager = new SourceArrayManager(m_chipSelectManager);
m_sensorArrayManager = new SensorArrayManager(m_chipSelectManager);
m_sourceArrayManager->initialize();
}
| [
"dvdv@quicknet.nl"
] | dvdv@quicknet.nl |
12836861c1965856f16fc0300b0f5e47f05d5275 | f950882940764ace71e51a1512c16a5ac3bc47bc | /src/GisEngine/GeoDatabase/ShapefileRowCursor.h | bfd2cedc2d665310b0dd0c0049cbd3ef50744ee6 | [] | no_license | ViacheslavN/GIS | 3291a5685b171dc98f6e82595dccc9f235e67bdf | e81b964b866954de9db6ee6977bbdf6635e79200 | refs/heads/master | 2021-01-23T19:45:24.548502 | 2018-03-12T09:55:02 | 2018-03-12T09:55:02 | 22,220,159 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,253 | h | #ifndef GIS_ENGINE_GEO_DATABASE_SHAPEFILEROWCURSOR_H
#define GIS_ENGINE_GEO_DATABASE_SHAPEFILEROWCURSOR_H
#include "GeoDatabase.h"
#include "ShapefileUtils.h"
#include "CursorBase.h"
#include "../../EmbDB/DatasetLite/SpatialDataset.h"
namespace GisEngine
{
namespace GeoDatabase
{
class CShapefileFeatureClass;
class CShapefileRowCursor : ICursorBase<ICursor>
{
public:
typedef ICursorBase<ICursor> TBase;
CShapefileRowCursor(IQueryFilter* filter, bool recycling, CShapefileFeatureClass* fclass);
virtual ~CShapefileRowCursor();
public:
// IRowCursor
virtual bool NextRow(IRowPtr* row);
/*virtual IFieldSetPtr GetFieldSet() const {return IFieldSetPtr();}
virtual IFieldsPtr GetSourceFields() const {return IFieldsPtr();}
virtual bool IsFieldSelected(int index) const {return false;}*/
protected:
bool NextRowEx(IRowPtr* row, IRow* rowCache);
bool EOC();
bool FillRow(IRow* row);
void SimpleNext();
bool AlterShape(CommonLib::CGeoShape* pShape) const;
protected:
//IQueryFilterPtr m_pFilter;
int m_nCurrentRowID;
ShapefileUtils::SHPGuard* m_pShp;
ShapefileUtils::DBFGuard* m_pDbf;
/*std::vector<int> m_vecOids;
std::vector<int>::iterator m_RowIDIt;
IFieldsPtr m_pSourceFields;
std::vector<int> m_vecFieldsExists;
std::vector<int> m_vecActualFieldsIndexes;
std::vector<eDataTypes> m_vecActualFieldsTypes;
IRowPtr m_pCurrentRow;*/
ShapeLib::SHPObject* m_pCacheObject;
CommonLib::IGeoShapePtr m_pCacheShape;
int m_nRecordCount;
/*GisBoundingBox m_Extent;*/
CShapefileFeatureClass* m_pParentFC;
bool m_bInvalidCursor;
DatasetLite::IShapeFileIndexPtr m_pShapeIndex;
DatasetLite::IShapeCursorPtr m_pCursor;
//bool m_bRecycling;
// Spatial Queries
/*GisGeometry::IEnvelopePtr m_pExtentOutput;
GisGeometry::IEnvelopePtr m_pExtentSource;
bool m_bNeedTransform;
int m_nOidFieldIndex;
int m_nShapeFieldIndex;
int m_nAnnoFieldIndex;
eSpatialRel m_spatialRel;*/
};
}
}
#endif | [
"nk.viacheslav@gmail.com"
] | nk.viacheslav@gmail.com |
c339e22d9ec14283043065fc0d6a065ad0a8e130 | 13e692134aca70d66f03325b08384210a5e6fef1 | /process_vcf_seq_utils.h | dcb58dd6a585c7b02f69d62748bd8b7b3689c923 | [] | no_license | millanek/evo | 2fdbb1d026ab4afe7c9936706ac1d39c878a4ef5 | 88e673061f2a67ebd8f51fd4151b18d04e0182c4 | refs/heads/master | 2022-08-05T20:14:30.629362 | 2022-08-03T12:35:13 | 2022-08-03T12:35:13 | 17,292,881 | 7 | 6 | null | 2019-10-01T12:21:19 | 2014-02-28T16:52:16 | C++ | UTF-8 | C++ | false | false | 5,885 | h | //
// process_vcf_seq_utils.h
// process_vcf
//
// Created by Milan Malinsky on 17/10/2013.
// Copyright (c) 2013 Milan Malinsky. All rights reserved.
//
#ifndef process_vcf_process_vcf_seq_utils_h
#define process_vcf_process_vcf_seq_utils_h
#include <iostream>
#include <vector>
#include <map>
#include <sstream>
#include <fstream>
#include "process_vcf_IUPAC.h"
#include "process_vcf_utils.h"
inline void appendGenotypeBaseToString(std::string& toExtend, const std::string& ref, const std::string& alt, const std::vector<char>& genotype, char hetTreatment) {
if (genotype[0] == '0' && genotype[1] == '0')
toExtend.append(ref);
else if (genotype[0] == '1' && genotype[1] == '1')
toExtend.append(alt);
else {
if (hetTreatment == 'r') {
double rn = ((double) rand() / RAND_MAX);
if (rn <= 0.5) {
toExtend.append(ref);
} else {
toExtend.append(alt);
}
} else if(hetTreatment == 'p') {
if (genotype[0] == '0')
toExtend.append(ref);
if (genotype[0] == '1')
toExtend.append(alt);
} else if (hetTreatment == 'i') {
std::string ambiguityBase = getAmbiguityCode(ref, alt);
toExtend.append(ambiguityBase);
} else if (hetTreatment == 'b') {
if (genotype[1] == '0')
toExtend.append(ref);
if (genotype[1] == '1')
toExtend.append(alt);
}
}
}
inline std::vector<std::string> returnGenotypeBaseAndZeroOne(const std::string& ref, const std::string& alt, const std::vector<char>& genotype, char hetTreatment) {
std::vector<std::string> baseZeroOne;
if (genotype[0] == '0' && genotype[1] == '0') {
baseZeroOne.push_back(ref); baseZeroOne.push_back("0");
return baseZeroOne;
} else if (genotype[0] == '1' && genotype[1] == '1') {
baseZeroOne.push_back(alt); baseZeroOne.push_back("1");
return baseZeroOne;
} else if (genotype[0] == '.' && genotype[1] == '.') { // Missing data
baseZeroOne.push_back("."); baseZeroOne.push_back("0");
return baseZeroOne;
} else {
if (hetTreatment == 'r') {
double rn = ((double) rand() / RAND_MAX);
if (rn <= 0.5) {
baseZeroOne.push_back(ref); baseZeroOne.push_back("0");
return baseZeroOne;
} else {
baseZeroOne.push_back(alt); baseZeroOne.push_back("1");
return baseZeroOne;
}
} else if(hetTreatment == 'p') {
if (genotype[0] == '0') {
baseZeroOne.push_back(ref); baseZeroOne.push_back("0");
return baseZeroOne;
} else if (genotype[0] == '1') {
baseZeroOne.push_back(alt); baseZeroOne.push_back("1");
return baseZeroOne;
}
} else if (hetTreatment == 'b') {
if (genotype[1] == '0') {
baseZeroOne.push_back(ref); baseZeroOne.push_back("0");
return baseZeroOne;
} else if (genotype[1] == '1') {
baseZeroOne.push_back(alt); baseZeroOne.push_back("1");
return baseZeroOne;
}
} else {
exit(1);
}
}
exit(1);
}
inline std::string returnGenotypeBaseZeroOne(const std::vector<char>& genotype, char hetTreatment) {
if (genotype[0] == '0' && genotype[1] == '0')
return "0";
else if (genotype[0] == '1' && genotype[1] == '1')
return "1";
else {
if (hetTreatment == 'r') {
double rn = ((double) rand() / RAND_MAX);
if (rn <= 0.5) {
return "0";
} else {
return "1";
}
} else if(hetTreatment == 'p') {
if (genotype[0] == '0')
return "0";
if (genotype[0] == '1')
return "1";
} else if (hetTreatment == 'b') {
if (genotype[1] == '0')
return "0";
if (genotype[1] == '1')
return "1";
} else {
exit(1);
}
}
exit(1);
}
// Read a scaffold from a reference genome fasta file into a single string +
// put the name of the next scaffold into the "nextScaffoldName" variable
inline std::string readScaffold(std::ifstream*& genomeFile, std::string& nextScaffoldName) {
std::string scaffoldString;
scaffoldString.reserve(100000000);
std::string line = "";
while (getline(*genomeFile, line) && line[0] != '>') {
scaffoldString.append(line);
}
if (line[0] == '>')
nextScaffoldName = split(line,' ')[0];
else
nextScaffoldName = "";
return scaffoldString;
}
// Read the last scaffold from a reference genome fasta file into a single string
/*inline std::string readLastScaffold(std::ifstream*& genomeFile) {
std::string scaffoldString;
scaffoldString.reserve(100000000);
std::string line = "";
while (getline(*genomeFile, line) && line[0] != '>') {
scaffoldString.append(line);
}
return scaffoldString;
} */
// Deal with the situation that there are scaffolds without any variable sites
// read through the genome file until the next scaffold to be read is the scaffold referred to in the vcf file
inline void forwardGenomeToScaffold(const std::string& thisInVCF, std::ifstream*& genomeFile, std::string& nextInGenome) {
while (thisInVCF != nextInGenome) {
std::cerr << "Starting to read " << nextInGenome << std::endl;
std::cerr << "No variants in " << nextInGenome << std::endl;
std::string currentScaffoldReference = readScaffold(genomeFile, nextInGenome);
std::cerr << "Finished reading" << std::endl;
nextInGenome.erase(0,1);
}
}
#endif
| [
"millanek@gmail.com"
] | millanek@gmail.com |
754561cd3ab15eb8046ade4292e817a3cb718087 | ec808cdba9c3f953e9bd9605794987e9de75d2a2 | /Homework 3/_SUBMISSION/medium.cpp | b35f594ef1df9e276e836b3e16e306ac79ab19ee | [] | no_license | JohnnyXiangyu/CS_32 | 4d6ff5873e1a9b2fffd350e59f48a9210221dd98 | fc27f7b2081bad5153828ba02ea2527c2aa7495d | refs/heads/master | 2020-05-15T13:55:17.556843 | 2019-06-08T23:54:39 | 2019-06-08T23:54:39 | 182,316,361 | 0 | 0 | null | 2019-06-02T20:33:09 | 2019-04-19T19:37:45 | C++ | UTF-8 | C++ | false | false | 1,684 | cpp | class Medium {
//base class
public:
Medium(string id)
: m_id(id) {}
//important: virtual destructor!
virtual ~Medium() {};
virtual string connect() const = 0; //medium alone have nothing to specify connect
virtual string transmit(string msg) const {
//let's meke this default a text output
string message = "text: " + msg;
return message;
}
string id() const {
return m_id;
}
private:
string m_id; //this is the only data member right?
};
class TwitterAccount : public Medium {
public:
TwitterAccount(string id) //twitter only use text
: Medium(id), m_connect("Tweet") {}
~TwitterAccount() {
cout << "Destroying the Twitter account " << id() << "." << endl;
}
virtual string connect() const {
return m_connect;
}
private:
string m_connect;
};
class Phone : public Medium{
public:
Phone(string id, CallType type) //phone might use text or voice
: Medium(id), m_connect("Call"), m_type(type) {}
~Phone() {
cout << "Destroying the phone " << id() << "." << endl;
}
virtual string connect() const{
return m_connect;
}
virtual string transmit(string msg) const {
string message;
if (m_type == TEXT)
message = "text: " + msg;
else
message = "voice: " + msg;
return message;
}
private:
string m_connect;
CallType m_type;
};
class EmailAccount : public Medium {
public:
EmailAccount(string id) //email will only use text
: Medium(id), m_connect("Email") {}
~EmailAccount() {
cout << "Destroying the email account " << id() << endl;
}
virtual string connect() const {
return m_connect;
}
private:
string m_connect;
}; | [
"noreply@github.com"
] | JohnnyXiangyu.noreply@github.com |
51e259fb0d051a8aed7733bf50f5fdfc7cdb6c70 | e87411251cd274762cfd542eb4a5dd7438d17d32 | /026-050/028_实现strStr()_L/main.cpp | 097023ffd64ca579c5436260bb5c131836f4f3e6 | [] | no_license | 7182514362/leetcode | 2356798bcb0693badd764106fcc341b56f914abc | 45ab9857ee4f4cd3f0e210034a6ab9a88f525837 | refs/heads/main | 2023-03-24T00:51:13.136609 | 2021-03-23T10:35:55 | 2021-03-23T10:35:55 | 350,672,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 190 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
}
};
int main(){
Solution sol;
return 0;
} | [
"2454024733@qq.com"
] | 2454024733@qq.com |
d92ab4ad8700af63a64b1d5a0b3552eb2f49dd0d | c98ec4a9084bad516a092447b2d30af75b0d813b | /mserver/lib/served/mux/variable_matcher.hpp | 2e0eb821a52acf500feadf56c6d6e5f92349af9d | [] | no_license | vmartinezandres/RestApiCPP-Datos2 | 5b98d65fd49e11dfe77bfae8744c40ae4a071c04 | 1c9ad89fd65f145cae4f4368eb07473d9432a786 | refs/heads/main | 2023-04-24T10:48:05.811312 | 2021-05-12T14:52:14 | 2021-05-12T14:52:14 | 359,302,418 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,516 | hpp | /*
* Copyright (C) 2014 MediaSift Ltd.
*
* 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 SERVED_PATH_VAR_MATCHER_HPP
#define SERVED_PATH_VAR_MATCHER_HPP
#include <string>
#include "served/mux/segment_matcher.hpp"
namespace served { namespace mux {
/*
* Matches any non empty path segment.
*
* This segment matcher will match any non empty path segment, and captures the path segment as a
* REST parameter.
*/
class variable_matcher : public segment_matcher
{
const std::string _variable_name;
public:
/*
* Constructs a variable matcher.
*
* The variable matcher contains a variable name for labelling REST parameters.
*
* @param variable_name the name of the REST param this segment matches.
*/
explicit variable_matcher(const std::string & variable);
/*
* Checks that the path segment is not empty.
*
* @param path_segment the segment of path to check.
*
* @return true if the path segment is not empty, false otherwise
*/
virtual bool check_match(const std::string & path_segment) override;
/*
* Appends any parameters extracted from the path segment to a list of params.
*
* This is used to propagate any REST parameters.
*
* @param params the list of parameters to append to
* @param path_segment the segment of path the variable should be extracted from
*/
virtual void get_param(served::parameters & params, const std::string & path_segment) override;
};
} } // mux, served
#endif // SERVED_PATH_VAR_MATCHER_HPP
| [
"noreply@github.com"
] | vmartinezandres.noreply@github.com |
41ac0c8b5c0603ba461c25e151100d769bbfed16 | 08d19b0dcce1d0cf666c538a8ff289f8beca63b8 | /hdmap/ad_map/ad_map_access/impl/tests/generated/ad/map/lane/GeoBorderValidInputRangeTests.cpp | f1a4e3b2570f7720cc4ee052bea6fb03fd8c4a5e | [] | no_license | feiyuxiaoThu/IITS | faf8e84aeb8c4a412bc6f955149f9fdf0dd2d092 | 0f5cd710a6fff1c19795662f8032cb9e22575bd7 | refs/heads/main | 2023-06-26T11:19:22.680078 | 2021-07-29T11:26:59 | 2021-07-29T11:26:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,543 | cpp | /*
* ----------------- BEGIN LICENSE BLOCK ---------------------------------
*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
* ----------------- END LICENSE BLOCK -----------------------------------
*/
/*
* Generated file
*/
#include <gtest/gtest.h>
#include <limits>
#include "ad/map/lane/GeoBorderValidInputRange.hpp"
TEST(GeoBorderValidInputRangeTests, testValidInputRange) {
::ad::map::lane::GeoBorder value;
::ad::map::point::GeoEdge valueLeft;
::ad::map::point::GeoPoint valueLeftElement;
::ad::map::point::Longitude valueLeftElementLongitude(-180);
valueLeftElement.longitude = valueLeftElementLongitude;
::ad::map::point::Latitude valueLeftElementLatitude(-90);
valueLeftElement.latitude = valueLeftElementLatitude;
::ad::map::point::Altitude valueLeftElementAltitude(-11000);
valueLeftElement.altitude = valueLeftElementAltitude;
valueLeft.resize(1, valueLeftElement);
value.left = valueLeft;
::ad::map::point::GeoEdge valueRight;
::ad::map::point::GeoPoint valueRightElement;
::ad::map::point::Longitude valueRightElementLongitude(-180);
valueRightElement.longitude = valueRightElementLongitude;
::ad::map::point::Latitude valueRightElementLatitude(-90);
valueRightElement.latitude = valueRightElementLatitude;
::ad::map::point::Altitude valueRightElementAltitude(-11000);
valueRightElement.altitude = valueRightElementAltitude;
valueRight.resize(1, valueRightElement);
value.right = valueRight;
ASSERT_TRUE(withinValidInputRange(value));
}
| [
"dawei.wang@inceptio.ai"
] | dawei.wang@inceptio.ai |
b753f120b9d6bffdfbfb8c6ba849fa692ca77a85 | 04da161d07c17f192243897450b143f9de765b3c | /src/providers/bttv/BttvLiveUpdates.cpp | f9128b5c792fd1ae0af0b6354b6391a6aedfa7b0 | [
"MIT"
] | permissive | pajlada/chatterino2 | d3db204fb7b38439112258a3fb1dfc583d8ce4cf | e4348a4dfe6a56247b170b29ec2ba71d04f3bb8c | refs/heads/master | 2023-06-01T01:19:01.084755 | 2023-05-07T10:06:43 | 2023-05-07T10:06:43 | 98,934,251 | 8 | 0 | MIT | 2023-04-29T11:34:46 | 2017-07-31T22:11:19 | C++ | UTF-8 | C++ | false | false | 2,509 | cpp | #include "providers/bttv/BttvLiveUpdates.hpp"
#include <QJsonDocument>
#include <utility>
namespace chatterino {
BttvLiveUpdates::BttvLiveUpdates(QString host)
: BasicPubSubManager(std::move(host))
{
}
void BttvLiveUpdates::joinChannel(const QString &channelID,
const QString &userName)
{
if (this->joinedChannels_.insert(channelID).second)
{
this->subscribe({BttvLiveUpdateSubscriptionChannel{channelID}});
this->subscribe({BttvLiveUpdateBroadcastMe{.twitchID = channelID,
.userName = userName}});
}
}
void BttvLiveUpdates::partChannel(const QString &id)
{
if (this->joinedChannels_.erase(id) > 0)
{
this->unsubscribe({BttvLiveUpdateSubscriptionChannel{id}});
}
}
void BttvLiveUpdates::onMessage(
websocketpp::connection_hdl /*hdl*/,
BasicPubSubManager<BttvLiveUpdateSubscription>::WebsocketMessagePtr msg)
{
const auto &payload = QString::fromStdString(msg->get_payload());
QJsonDocument jsonDoc(QJsonDocument::fromJson(payload.toUtf8()));
if (jsonDoc.isNull())
{
qCDebug(chatterinoBttv) << "Failed to parse live update JSON";
return;
}
auto json = jsonDoc.object();
auto eventType = json["name"].toString();
auto eventData = json["data"].toObject();
if (eventType == "emote_create")
{
auto message = BttvLiveUpdateEmoteUpdateAddMessage(eventData);
if (!message.validate())
{
qCDebug(chatterinoBttv) << "Invalid add message" << json;
return;
}
this->signals_.emoteAdded.invoke(message);
}
else if (eventType == "emote_update")
{
auto message = BttvLiveUpdateEmoteUpdateAddMessage(eventData);
if (!message.validate())
{
qCDebug(chatterinoBttv) << "Invalid update message" << json;
return;
}
this->signals_.emoteUpdated.invoke(message);
}
else if (eventType == "emote_delete")
{
auto message = BttvLiveUpdateEmoteRemoveMessage(eventData);
if (!message.validate())
{
qCDebug(chatterinoBttv) << "Invalid deletion message" << json;
return;
}
this->signals_.emoteRemoved.invoke(message);
}
else if (eventType == "lookup_user")
{
// ignored
}
else
{
qCDebug(chatterinoBttv) << "Unhandled event:" << json;
}
}
} // namespace chatterino
| [
"noreply@github.com"
] | pajlada.noreply@github.com |
cb6940110e61d69dcad453507231659c810ae2bb | c901b8389d196012f3cd1a3230ead6c2fc46a89b | /code/Karplus-Strong Synth/Karplus-Strong Synth.ino | 2b8192601855956ba03847efa65c116e3c3e32d6 | [] | no_license | Marquets/SMC-Master-Thesis | 99ec41ec69bf3a40a168a8f334f65e10f0989ac3 | 675ace2cd14dfeb4151baf9b901f69a042bf03a1 | refs/heads/master | 2023-01-31T10:35:27.432119 | 2020-12-17T13:55:57 | 2020-12-17T13:55:57 | 296,834,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,403 | ino | #include <Audio.h>
#include <Wire.h>
#include <SD.h>
#include <SPI.h>
#include <SerialFlash.h>
#include "modularInterpInstrMIDI.h"
#include <ResponsiveAnalogRead.h>
modularInterpInstrMIDI karplus;
AudioOutputI2S out;
AudioControlSGTL5000 audioShield;
AudioAmplifier amp1;
AudioConnection patchCord0(karplus,0,amp1,0);
AudioConnection patchCord1(amp1,0,out,0);
AudioConnection patchCord2(amp1,0,out,1);
//Mux 1 control pins for analog signal (Sig_pin)
const int S0 = 0;
const int S1 = 1;
const int S2 = 2;
const int S3 = 3;
// Mux 1 in "SIG" pin default
const int SIG_PIN = A0;
//Mux 2 control pins for analog signal (Sig_pin)
const int W0 = 19;
const int W1 = 18;
const int W2 = 17;
const int W3 = 16;
// Mux 2 in "SIG" pin default
const int WIG_PIN = 22;
//Array of values for selecting the disered channel of the multiplexers
const boolean muxChannel[16][4] = {
{0, 0, 0, 0}, //channel 0
{1, 0, 0, 0}, //channel 1
{0, 1, 0, 0}, //channel 2
{1, 1, 0, 0}, //channel 3
{0, 0, 1, 0}, //channel 4
{1, 0, 1, 0}, //channel 5
{0, 1, 1, 0}, //channel 6
{1, 1, 1, 0}, //channel 7
{0, 0, 0, 1}, //channel 8
{1, 0, 0, 1}, //channel 9
{0, 1, 0, 1}, //channel 10
{1, 1, 0, 1}, //channel 11
{0, 0, 1, 1}, //channel 12
{1, 0, 1, 1}, //channel 13
{0, 1, 1, 1}, //channel 14
{1, 1, 1, 1} //channel 15
};
float lowestNotes[] = {41.204 * 4, 55 * 4 , 73.416 * 4 , 97.999 * 4};
float previous_note = 0;
float just_intonation[] = {1,(float)256/243,(float)9/8,(float)32/27,(float)81/64,(float)4/3,(float)729/512,(float)3/2,(float)128/81,(float)27/16,(float)16/9,(float)243/128,2};
float shruti[] = {1,(float)256/243,(float)16/15,(float)10/9,(float)9/8,(float)32/27,(float)6/5,(float)5/4,(float)81/64,(float)4/3,(float)27/20,(float)45/32,(float)729/512,(float)3/2,
(float)128/81, (float)8/5, (float) 5/3, (float)27/16, (float)16/9, (float)9/5, (float)15/8, (float)243/128,2};
float quarter_tone[] = {1,(float)33/32,(float)17/16,(float)12/11,(float)9/8,(float)22/19,(float)19/16,(float)11/9,(float)24/19,(float) 22/17,(float)4/3,(float)11/8,(float)17/12,(float)16/11,
(float)3/2, (float)17/11, (float) 19/12, (float)18/11, (float)32/19, (float)16/9, (float)11/6, (float)33/17,2};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
AudioMemory(15);
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(SIG_PIN, INPUT);
pinMode(W0, OUTPUT);
pinMode(W1, OUTPUT);
pinMode(W2, OUTPUT);
pinMode(W3, OUTPUT);
//pinMode(WIG_PIN, INPUT);
digitalWrite(S0, LOW);
digitalWrite(S1, LOW);
digitalWrite(S2, LOW);
digitalWrite(S3, LOW);
digitalWrite(W0, LOW);
digitalWrite(W1, LOW);
digitalWrite(W2, LOW);
digitalWrite(W3, LOW);
audioShield.enable();
audioShield.volume(0.9);
amp1.gain(0.5);
}
void loop() {
// put your main code here, to run repeatedly:
int i = 0;
while( i < 4) {
float freq = 0.0;
// Reading values from sensors and knobs
int index = map(readMux(0 + i*3), 0, 1023,0,12);
float fsr = map(readMux(1 + i*3), 0, 1023, 1.0, 2.0);
float fsr2 = map(readMux(2 + i*3), 0, 1023, -2.0, 1.0);
float pluck = (float) readMux2(6) / 1023;
float body_shape = (float) readMux2(7) / 1023;
float body_scale = (float) readMux2(5) / 1023;
int tonal = map(readMux2(4), 0, 1023, 0, 4);
// Applying the corresponding ratios depending on the tonal system
if ( tonal == 0) {
int index = map(readMux(0 + i*3), 0, 1023,0,12);
freq = lowestNotes[i] * just_intonation[index];
}
else if (tonal == 1) {
int index = map(readMux(0 + i*3), 0, 1023,0,21);
freq = lowestNotes[i] * shruti[index];
}
else if (tonal == 2) {
int index = map(readMux(0 + i*3), 0, 1023,0,22);
freq = lowestNotes[i] * quarter_tone[index];
}
else if (tonal == 3) {
freq = map(readMux(0 + i*3), 0, 1023,lowestNotes[i],lowestNotes[i] + (2 * 12));
}
else if (tonal == 4) {
freq = map(readMux(0 + i*3), 0, 1023,lowestNotes[i],lowestNotes[i] + (2 * 24));
}
if (freq > lowestNotes[i]) {
karplus.setParamValue("gate",1);
karplus.setParamValue("gain",0.5);
karplus.setParamValue("pluckPosition",pluck);
karplus.setParamValue("freq",freq);
//karplus.setParamValue("bend",fsr2);
karplus.setParamValue("shape",body_shape);
karplus.setParamValue("scale",body_scale);
//delay(20);
}
else {
audioShield.disable();
karplus.setParamValue("gain",0);
karplus.setParamValue("gate",0);
i++;
}
}
}
int readMux(byte channel){
byte controlPin[] = {S0, S1, S2, S3};
//byte controlPin2[] = {W0, W1, W2, W3};
for(int i = 0; i < 4; i ++){
digitalWrite(controlPin[i], muxChannel[channel][i]);
}
//read the value at the SIG pin
delayMicroseconds(50);
int val = analogRead(SIG_PIN);
//return the value
return val;
}
int readMux2(byte channel){
byte controlPin[] = {W0, W1, W2, W3};
for(int i = 0; i < 4; i ++){
digitalWrite(controlPin[i], muxChannel[channel][i]);
//Serial.println(muxChannel[channel][i]);
}
//read the value at the SIG pin
delayMicroseconds(50);
int val = analogRead(WIG_PIN);
//Serial.println(val);
//return the value
return val;
}
| [
"marcog07@ucm.es"
] | marcog07@ucm.es |
f6a9cb535c1730f3dc429a80f7ec3287deffac1b | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/alembic/lib/Alembic/AbcCoreOgawa/ArImpl.h | 0f17e1c3350be2dd35f5d7258ad3402b4fefe14a | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 4,386 | h | //-*****************************************************************************
//
// Copyright (c) 2013,
// Sony Pictures Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// 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 Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their 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.
//
//-*****************************************************************************
#ifndef _Alembic_AbcCoreOgawa_ArImpl_h_
#define _Alembic_AbcCoreOgawa_ArImpl_h_
#include <Alembic/AbcCoreOgawa/Foundation.h>
#include <Alembic/AbcCoreOgawa/StreamManager.h>
namespace Alembic {
namespace AbcCoreOgawa {
namespace ALEMBIC_VERSION_NS {
//-*****************************************************************************
class OrData;
//-*****************************************************************************
class ArImpl
: public AbcA::ArchiveReader
, public Alembic::Util::enable_shared_from_this<ArImpl>
{
private:
friend class ReadArchive;
ArImpl( const std::string &iFileName,
size_t iNumStreams=1 );
ArImpl( const std::vector< std::istream * > & iStreams );
public:
virtual ~ArImpl();
//-*************************************************************************
// ABSTRACT FUNCTIONS
//-*************************************************************************
virtual const std::string &getName() const;
virtual const AbcA::MetaData &getMetaData() const;
virtual AbcA::ObjectReaderPtr getTop();
virtual AbcA::TimeSamplingPtr getTimeSampling( Util::uint32_t iIndex );
virtual AbcA::ArchiveReaderPtr asArchivePtr();
virtual AbcA::ReadArraySampleCachePtr getReadArraySampleCachePtr()
{
return AbcA::ReadArraySampleCachePtr();
}
virtual void
setReadArraySampleCachePtr( AbcA::ReadArraySampleCachePtr iPtr )
{
}
virtual AbcA::index_t getMaxNumSamplesForTimeSamplingIndex(
Util::uint32_t iIndex );
virtual Util::uint32_t getNumTimeSamplings()
{
return m_timeSamples.size();
}
virtual Util::int32_t getArchiveVersion()
{
return m_archiveVersion;
}
StreamIDPtr getStreamID();
const std::vector< AbcA::MetaData > & getIndexedMetaData();
private:
void init();
std::string m_fileName;
size_t m_numStreams;
Ogawa::IArchive m_archive;
Alembic::Util::weak_ptr< AbcA::ObjectReader > m_top;
Alembic::Util::shared_ptr < OrData > m_data;
Alembic::Util::mutex m_orlock;
Util::int32_t m_archiveVersion;
std::vector < AbcA::TimeSamplingPtr > m_timeSamples;
std::vector < AbcA::index_t > m_maxSamples;
ObjectHeaderPtr m_header;
StreamManager m_manager;
std::vector< AbcA::MetaData > m_indexMetaData;
};
} // End namespace ALEMBIC_VERSION_NS
using namespace ALEMBIC_VERSION_NS;
} // End namespace AbcCoreOgawa
} // End namespace Alembic
#endif
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
ca2c7f0d9d083451b72bdfb294000b8bd3f6b3aa | 21a221c20313339ac7380f8d92f8006e5435ef1d | /src/arcscripts/src/InstanceScripts/Instance_MagistersTerrace.cpp | 45e252d1dc15d0ebf45bf211e3f4c11f35f5b45a | [] | no_license | AwkwardDev/Descent-core-scripts-3.3.5 | a947a98d0fdedae36a488c542642fcf61472c3d7 | d773b1a41ed3f9f970d81962235e858d0848103f | refs/heads/master | 2021-01-18T10:16:03.750112 | 2014-08-12T16:28:15 | 2014-08-12T16:28:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,671 | cpp | /*
* ArcScripts for ArcEmu MMORPG Server
* Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/>
* Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/>
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
//MagisterTerrace Script
//Bosses
//Selin Firehart Encounter
// Creature Entry's
#define TRASH_FelCrystal 24722
#define BOSS_SelinFireheart 24723
// Normal & Heroic Spells
/*
Mana Rage
Caster: Fel Crystal
Details: Empowers the caster with fel energy, restoring their mana for 10 sec.
Triggers: Increases the target's mana by 10%.
*/
#define FC_MANARAGE 44320
#define FC_MANARAGE_TRIGGER 44321
/*
Fel Explosion
Caster Selin Fireheart
Details: Area of effect damage spell, cast continually until Selin is out of mana
*/
#define SF_FELEXPLOSION 44314
/*
Drain Life
Caster Selin Fireheart
Details: Randomly targeted channeled spell, deals damage and heals Selin.
*/
#define SF_DRAINLIFE 44294
// Heroic Spells
/*
Drain Mana (Heroic Mode Only)
Caster Selin Fireheart
Details: Randomly targeted channeled spell on a player with mana, drain Mana to the player and give it to Selin.
*/
#define SF_DRAINMANA 46153
// Fel Crystal Spawn Locations
static LocationExtra FelCrystals[]={
{225.969f, -20.0775f, -2.9731f, 0.942478f, TRASH_FelCrystal},
{226.314f, 20.2183f, -2.98127f, 5.32325f, TRASH_FelCrystal},
{247.888f, -14.6252f, 3.80777f, 2.33874f, TRASH_FelCrystal},
{248.053f, 14.592f, 3.74882f, 3.94444f, TRASH_FelCrystal},
{263.149f, 0.309245f, 1.32057f, 3.15905f, TRASH_FelCrystal}
};
class SelinFireheartAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(SelinFireheartAI, MoonScriptCreatureAI);
SelinFireheartAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(SF_DRAINLIFE, Target_RandomPlayer, 8, 0, 35);
if(_unit->GetMapMgr()->iInstanceMode == MODE_HEROIC)
AddSpell(SF_DRAINMANA, Target_RandomPlayer, 8, 0, 35);
ManaRage = dbcSpell.LookupEntry(FC_MANARAGE);
ManaRageTrigger = AddSpell(FC_MANARAGE_TRIGGER, Target_Self, 0, 0, 0);
FelExplosion = AddSpell(SF_FELEXPLOSION, Target_Self, 0, 0, 0);
}
void OnCombatStart(Unit* pTarget)
{
/*
Selin Fireheart starts with 0 mana and drains it from the felcrystals in the room
- ToDo: Set it so mana regen is off
*/
_unit->SetUInt32Value(UNIT_FIELD_POWER1, 0);
ParentClass::OnCombatStart(pTarget);
}
/*
During the AIUpdate() Selin will spam FelExplosion until hes out of mana
He will then attempt to gain mana from a FelCrystal thats in the room by running to them
*/
void AIUpdate()
{
// 10% of his mana according to wowhead is 3231 which is whats needed to cast FelExplosion
if(GetManaPercent() < 10 || FelExplosion->mEnabled == false)
Mana();
else if(!IsCasting())// Mana is greater than 10%
CastFelExplosion();
ParentClass::AIUpdate();
}
void Mana()
{
/*
Attempt to get a Fel Crystal and move to it if not in range.
Once in range we get the FelCrystal to cast Mana Rage on Selin
*/
Unit* FelCrystal = NULL;
PreventActions(false);
FelCrystal = FindFelCrystal();
if(!FelCrystal || !FelCrystal->isAlive())
{
PreventActions(true);
FelCrystal = NULL;
return;
}
// Not in range
if(_unit->GetDistance2dSq(FelCrystal) > 100)
{
MoveTo(FelCrystal->GetPositionX(), FelCrystal->GetPositionY(), FelCrystal->GetPositionZ());
FelCrystal = NULL;
return;
}
_unit->GetAIInterface()->StopMovement(0);
if(!FelCrystal->GetCurrentSpell())
FelCrystal->CastSpell(_unit, ManaRage, false);
// Mana Rage giving of mana doesnt work so we give 10%(3231) / AIUpdate() Event.
CastSpellNowNoScheduling(ManaRageTrigger);
uint32 mana = _unit->GetPower(POWER_TYPE_MANA)+3231;
if(mana >= _unit->GetMaxPower(POWER_TYPE_MANA))
mana = _unit->GetMaxPower(POWER_TYPE_MANA);
_unit->SetUInt32Value(UNIT_FIELD_POWER1, mana);
// Re-Enable FelExplosion
if(GetManaPercent() >= 100)
PreventActions(true);
FelCrystal = NULL;
}
void PreventActions(bool Allow)
{
FelExplosion->mEnabled = Allow;
SetAllowMelee(Allow);
SetAllowRanged(Allow);
SetAllowSpell(Allow);
SetAllowTargeting(Allow);
}
Unit* FindFelCrystal()
{
/*
Find a FelCrystal
*/
Unit* FC = NULL;
for(int x=0; x<5; x++)
{
FC = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(FelCrystals[x].x, FelCrystals[x].y, FelCrystals[x].z, FelCrystals[x].addition);
if(!FC || !FC->isAlive() || FC->GetInstanceID() != _unit->GetInstanceID())
FC = NULL;
else
break;
}
return FC;
}
void CastFelExplosion()
{
CastSpellNowNoScheduling(FelExplosion);
// No Idea why the mana isnt taken when the spell is cast so had to manually take it -_-
_unit->SetUInt32Value(UNIT_FIELD_POWER1, _unit->GetPower(POWER_TYPE_MANA) - 3231);
}
SpellEntry* ManaRage;
SpellDesc* ManaRageTrigger;
SpellDesc* FelExplosion;
};
/*
Vexallus
*/
#define BOSS_VEXALLUS 24744
#define CN_PURE_ENERGY 24745
#define VEXALLUS_CHAIN_LIGHTNING 44318
#define VEXALLUS_OVERLOAD 44353
#define VEXALLUS_ARCANE_SHOCK 44319
#define VEXALLUS_SUMMON_PURE_ENERGY 44322
class VexallusAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(VexallusAI, MoonScriptBossAI);
VexallusAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddPhaseSpell( 1, AddSpell( VEXALLUS_CHAIN_LIGHTNING, Target_Current, 19, 0, 8, 0, 0));
AddPhaseSpell( 1, AddSpell( VEXALLUS_ARCANE_SHOCK, Target_ClosestPlayer, 12, 0, 20, 0, 0, true, "Un...con...tainable.", Text_Yell, 12392));
AddPhaseSpell( 2, AddSpell( VEXALLUS_OVERLOAD, Target_Self, 85, 0, 3, 0, 0));
mPureEnergy = AddSpell( VEXALLUS_SUMMON_PURE_ENERGY, Target_Self, 85, 0, 3);
AddEmote( Event_OnTargetDied, "Con...sume.", Text_Yell, 12393);
mSummon = 0;
}
void OnCombatStart(Unit* pTarget)
{
Emote("Drain... life...", Text_Yell, 12389);
SetPhase(1);
ParentClass::OnCombatStart(pTarget);
}
void AIUpdate()
{
if((GetHealthPercent() <= 85 && mSummon == 0) ||
( GetHealthPercent() <= 70 && mSummon == 1 ) ||
( GetHealthPercent() <= 55 && mSummon == 2 ) ||
( GetHealthPercent() <= 40 && mSummon == 3 ) ||
( GetHealthPercent() <= 25 && mSummon == 4 ))
{
CastSpell(mPureEnergy);
++mSummon;
//SpawnCreature(CN_PURE_ENERGY, 231, -207, 6, 0, true);
}
if( GetHealthPercent() <= 10 && GetPhase() == 1 )
SetPhase(2);
ParentClass::AIUpdate();
}
SpellDesc* mPureEnergy;
uint8 mSummon;
};
//Priestess Delrissa
#define BOSS_Priestess_Delrissa 24560
#define PRIESTESS_DELRISSA_DISPEL_MAGIC 27609
#define PRIESTESS_DELRISSA_FLASH_HEAL 17843
#define PRIESTESS_DELRISSA_SHADOWWORD_PAIN 15654
#define PRIESTESS_DELRISSA_POWERWORD_SHIELD 44291
#define PRIESTESS_DELRISSA_RENEW 44174
class Priestess_DelrissaAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(Priestess_DelrissaAI, MoonScriptBossAI);
Priestess_DelrissaAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(PRIESTESS_DELRISSA_DISPEL_MAGIC, Target_RandomFriendly, 35, 0, 5, 0, 30);
AddSpell(PRIESTESS_DELRISSA_FLASH_HEAL, Target_RandomFriendly, 40, 1.5, 7, 0, 40);
AddSpell(PRIESTESS_DELRISSA_SHADOWWORD_PAIN, Target_RandomPlayer, 45, 0, 18, 0, 30);
AddSpell(PRIESTESS_DELRISSA_POWERWORD_SHIELD, Target_RandomFriendly, 32, 0, 15, 0, 40);
AddSpell(PRIESTESS_DELRISSA_RENEW, Target_RandomFriendly, 30, 0, 18, 0, 40);
AddEmote(Event_OnDied, "Not what I had... planned...", Text_Yell, 12397);
mClearHateList = AddTimer(15000);
mKilledPlayers = 0;
};
void OnCombatStart(Unit* pTarget)
{
Emote("Annihilate them!", Text_Yell, 12395);
//AggroRandomUnit(); // Want to aggro random unit ? Set it instead of calling premade
// method that in this case recursively loops this procedure
ParentClass::OnCombatStart(pTarget);
};
void OnTargetDied(Unit* pTarget)
{
if(!pTarget || !pTarget->IsPlayer())
return;
++mKilledPlayers;
if(mKilledPlayers == 1)
Emote("I call that a good start.", Text_Yell, 12405);
else if(mKilledPlayers == 2)
Emote("I could have sworn there were more of you.", Text_Yell, 12407);
else if(mKilledPlayers == 3)
Emote("Not really much of a group, anymore, is it?", Text_Yell, 12409);
else if(mKilledPlayers == 4)
Emote("One is such a lonely number.", Text_Yell, 12410);
else if(mKilledPlayers == 5)
Emote("It's been a kick, really.", Text_Yell, 12411);
ParentClass::OnTargetDied(pTarget);
};
void OnCombatStop(Unit* pTarget)
{
Emote("It's been a kick, really.", Text_Yell, 12411);
mKilledPlayers = 0;
ParentClass::OnCombatStop(pTarget);
};
void AIUpdate()
{
if( IsTimerFinished(mClearHateList) )
{
ClearHateList();
AggroRandomUnit();
ResetTimer(mClearHateList, 15000);
};
ParentClass::AIUpdate();
};
protected:
uint8 mKilledPlayers;
int32 mClearHateList;
};
//Kagani Nightstrike
#define CN_KaganiNightstrike 24557
#define KAGANI_NIGHTSTRIKE_Eviscerate 46189
#define KAGANI_NIGHTSTRIKE_KidneyShot 27615
#define KAGANI_NIGHTSTRIKE_Gouge 12540
class Kagani_NightstrikeAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(Kagani_NightstrikeAI, MoonScriptBossAI);
Kagani_NightstrikeAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(KAGANI_NIGHTSTRIKE_KidneyShot, Target_Current, 80, 0, 25, 0, 30);
AddSpell(KAGANI_NIGHTSTRIKE_Gouge, Target_ClosestPlayer, 20, 0, 18, 0, 30);
AddSpell(KAGANI_NIGHTSTRIKE_Eviscerate, Target_Current, 8, 0, 45, 0, 30);
}
};
//Ellrys Duskhallow
#define CN_EllrysDuskhallow 14558
#define EllrysDuskhallow_Immolate 44267
#define EllrysDuskhallow_ShadowBolt 12471
#define EllrysDuskhallow_CurseofAgony 14875
#define EllrysDuskhallow_Fear 38595
class Ellrys_DuskhallowAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(Ellrys_DuskhallowAI, MoonScriptBossAI);
Ellrys_DuskhallowAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(EllrysDuskhallow_Immolate, Target_Current, 75, 2, 15, 0, 30);
AddSpell(EllrysDuskhallow_ShadowBolt, Target_RandomPlayer, 75, 3, 5, 4, 40);
AddSpell(EllrysDuskhallow_CurseofAgony, Target_RandomPlayer, 75, 0, 4, 0, 30);
AddSpell(EllrysDuskhallow_Fear, Target_RandomPlayer, 75, 1.5, 9, 0, 20);
}
};
//Eramas Brightblaze
#define CN_EramasBrightblaze 24554
#define ERAMAS_BRIGHTBLAZE_KNOCKDOWN 11428
#define ERAMAS_BRIGHTBLAZE_SNAP_KICK 46182
class Eramas_BrightblazeAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(Eramas_BrightblazeAI, MoonScriptBossAI);
Eramas_BrightblazeAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(ERAMAS_BRIGHTBLAZE_KNOCKDOWN, Target_Current, 25, 0, 5, 0, 5);
AddSpell(ERAMAS_BRIGHTBLAZE_SNAP_KICK, Target_SecondMostHated, 40, 0, 2, 0, 5);
}
};
//Yazzai
#define CN_YAZZAI 24561
#define YAZZAI_POLYMORPH 13323
#define YAZZAI_ICE_BLOCK 27619
#define YAZZAI_BLIZZARD 44178
#define YAZZAI_CONE_OF_COLD 38384
#define YAZZAI_FROSTBOLT 15530
class YazzaiAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(YazzaiAI, MoonScriptBossAI);
YazzaiAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(YAZZAI_POLYMORPH, Target_RandomPlayer, 30, 1.5, 16, 0, 30);
AddSpell(YAZZAI_ICE_BLOCK, Target_Self, 20, 0, 300, 0, 1);
AddSpell(YAZZAI_BLIZZARD, Target_RandomPlayer, 25, 0, 20, 0, 30);
AddSpell(YAZZAI_CONE_OF_COLD, Target_Self, 10, 0, 19, 0, 1);
AddSpell(YAZZAI_FROSTBOLT, Target_RandomPlayer, 80, 3, 14, 0, 40);
}
};
//Warlord Salaris
#define CN_WARLORD_SALARIS 24559
#define WARLORD_SALARIS_INTERCEPT 27577
#define WARLORD_SALARIS_DISARM 27581
#define WARLORD_SALARIS_PIERCING_HOWL 23600
#define WARLORD_SALARIS_FRIGHTENING_SHOUT 19134
#define WARLORD_SALARIS_HAMSTRING 27584
//#define WARLORD_SALARIS_BATTLE_SHOUT 27578
#define WARLORD_SALARIS_MORTAL_STRIKE 44268
class Warlord_SalarisAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(Warlord_SalarisAI, MoonScriptBossAI);
Warlord_SalarisAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
//AddSpell(uint32 pSpellId, TargetType pTargetType, float pChance, float pCastTime, int32 pCooldown, float pMinRange, float pMaxRange
AddSpell(WARLORD_SALARIS_INTERCEPT, Target_RandomPlayer , 25, 0, 8, 8, 25 );
AddSpell(WARLORD_SALARIS_DISARM, Target_Current, 100, 0, 60, 0, 5 );
AddSpell(WARLORD_SALARIS_PIERCING_HOWL, Target_Self, 22, 0, 17, 0, 1);
AddSpell(WARLORD_SALARIS_FRIGHTENING_SHOUT, Target_RandomPlayer, 30, 0, 9, 0, 10);
AddSpell(WARLORD_SALARIS_HAMSTRING, Target_ClosestPlayer, 10, 0, 20, 0, 5);
AddSpell(WARLORD_SALARIS_MORTAL_STRIKE, Target_Current, 100, 0, 6, 0, 5);
}
};
//Geraxxas
#define CN_GARAXXAS 24555
#define GARAXXAS_AIMED_SHOT 44271
#define GARAXXAS_SHOOT 15620
#define GARAXXAS_CONCUSSIV_SHOT 27634
#define GARAXXAS_MULTI_SHOT 44285
#define GARAXXAS_WING_CLIP 44286
class GaraxxasAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(GaraxxasAI, MoonScriptBossAI);
GaraxxasAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(GARAXXAS_AIMED_SHOT, Target_RandomPlayer, 90, 3, 6, 5, 35);
AddSpell(GARAXXAS_SHOOT, Target_RandomPlayer, 90, 2.5, 5, 5, 30);
AddSpell(GARAXXAS_CONCUSSIV_SHOT, Target_RandomPlayer, 40, 0, 8, 5, 35);
AddSpell(GARAXXAS_MULTI_SHOT, Target_RandomPlayer, 25, 0, 12, 5, 30);
AddSpell(GARAXXAS_WING_CLIP, Target_Current, 30, 0, 9, 0, 5);
}
};
//Apoko
#define CN_APOKO 24553
#define APOKO_FROST_SHOCK 21401
#define APOKO_LESSER_HEALING_WAVE 44256
#define APOKO_PURGE 27626
class ApokoAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(ApokoAI, MoonScriptCreatureAI);
ApokoAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(APOKO_FROST_SHOCK, Target_RandomPlayer, 40, 0, 8, 0, 20);
AddSpell(APOKO_LESSER_HEALING_WAVE, Target_RandomFriendly, 50, 1.5, 10, 0, 40);
AddSpell(APOKO_PURGE, Target_RandomUnit, 20, 0, 40, 0, 30);
}
};
//Zelfan
#define CN_ZELFAN 24556
#define ZELFAN_GOBLIN_DRAGON_GUN 44272
#define ZELFAN_HIGH_EXPLOSIV_SHEEP 44276
#define ZELFAN_ROCKET_LAUNCH 44137
class ZelfanAI : public MoonScriptCreatureAI
{
MOONSCRIPT_FACTORY_FUNCTION(ZelfanAI, MoonScriptCreatureAI);
ZelfanAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature)
{
AddSpell(ZELFAN_GOBLIN_DRAGON_GUN, Target_Current, 90, 0, 15, 0, 5);
AddSpell(ZELFAN_HIGH_EXPLOSIV_SHEEP, Target_Self, 90, 2, 80);
AddSpell(ZELFAN_ROCKET_LAUNCH, Target_RandomPlayer, 99, 3.5, 60, 0, 45);
}
};
//Trash mobs
//Coilskar Witch
#define CN_COILSKAR_WITCH 24696
#define COILSKAR_WITCH_FORKED_LIGHTNING 46150
#define COILSKAR_WITCH_FROST_ARROW 44639
#define COILSKAR_WITCH_MANA_SHIELD 46151
#define COILSKAR_WITCH_SHOOT 35946
class CoilskarWitchAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(CoilskarWitchAI, MoonScriptBossAI);
CoilskarWitchAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(COILSKAR_WITCH_FORKED_LIGHTNING, Target_Current, 60, 2, 12, 0, 30);
AddSpell(COILSKAR_WITCH_FROST_ARROW, Target_RandomPlayer, 15, 0, 16, 0, 40);
AddSpell(COILSKAR_WITCH_MANA_SHIELD, Target_Self, 6, 0, 40, 0, 0);
AddSpell(COILSKAR_WITCH_SHOOT, Target_RandomPlayer, 75, 1.5, 4, 5, 30);
}
};
//Sister of Torment
#define CN_SISTER_OF_TORMENT 24697
#define SISTER_OF_TORMENT_DEADLY_EMBRACE 44547
#define SISTER_OF_TORMENT_LASH_OF_PAIN 44640
class SisterOfTormentAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(SisterOfTormentAI, MoonScriptBossAI);
SisterOfTormentAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(SISTER_OF_TORMENT_LASH_OF_PAIN, Target_Current, 60, 0, 8, 0, 5);
AddSpell(SISTER_OF_TORMENT_DEADLY_EMBRACE, Target_RandomPlayer, 20, 1.5, 16, 0, 20);
}
};
//Sunblade Blood Knight
#define CN_SB_BLOOD_KNIGHT 24684
#define BLOOD_KNIGHT_HOLY_LIGHT 46029
#define BLOOD_KNIGHT_JUDGEMENT_OF_WRATH 44482
#define BLOOD_KNIGHT_SEAL_OF_WRATH 46030
class SunbladeBloodKnightAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(SunbladeBloodKnightAI, MoonScriptBossAI);
SunbladeBloodKnightAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(BLOOD_KNIGHT_JUDGEMENT_OF_WRATH, Target_Current, 20, 0, 30, 0, 5);
AddSpell(BLOOD_KNIGHT_SEAL_OF_WRATH, Target_Self, 99, 0, 30, 0, 0);
AddSpell(BLOOD_KNIGHT_HOLY_LIGHT, Target_Self, 10, 2, 30, 0, 40);
}
};
//Sunblade Imp
#define CN_SB_IMP 24815
#define IMP_FIREBOLT 44577
class SunbladeImpAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(SunbladeImpAI, MoonScriptBossAI);
SunbladeImpAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(IMP_FIREBOLT, Target_Current, 100, 2, (int32)2.5, 0, 30);
}
};
//Sunblade Mage Guard
#define CN_SB_MAGE_GUARD 24683
#define MAGE_GUARD_GLAVE_THROW 46028
#define MAGE_GUARD_MAGIC_DAMPENING_FIELD 44475
class SunbladeMageGuardAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(SunbladeMageGuardAI, MoonScriptBossAI);
SunbladeMageGuardAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(MAGE_GUARD_GLAVE_THROW, Target_Current, 60, 0, 25, 0, 5);
AddSpell(MAGE_GUARD_MAGIC_DAMPENING_FIELD, Target_RandomPlayer, 20, 1, 35, 0, 20);
}
};
//Sunblade Magister
#define CN_SB_MAGISTER 24685
#define MAGISTER_ARCANE_NOVA 46036
#define MAGISTER_FROSTBOLT 46035
class SunbladeMagisterAI : public MoonScriptBossAI
{
MOONSCRIPT_FACTORY_FUNCTION(SunbladeMagisterAI, MoonScriptBossAI);
SunbladeMagisterAI(Creature* pCreature) : MoonScriptBossAI(pCreature)
{
AddSpell(MAGISTER_FROSTBOLT, Target_Current, 65, 2, 4, 0, 30);
AddSpell(MAGISTER_ARCANE_NOVA, Target_Self, 12, 1.5, 40, 0, 0);
}
};
void SetupMagistersTerrace(ScriptMgr* pScriptMgr)
{
//Bosses
pScriptMgr->register_creature_script(BOSS_SelinFireheart, &SelinFireheartAI::Create);
pScriptMgr->register_creature_script(BOSS_VEXALLUS, &VexallusAI::Create);
pScriptMgr->register_creature_script(BOSS_Priestess_Delrissa, &Priestess_DelrissaAI::Create);
//Priestess Delrissa Encounter Creature AI
pScriptMgr->register_creature_script(CN_KaganiNightstrike, &Kagani_NightstrikeAI::Create);
pScriptMgr->register_creature_script(CN_EllrysDuskhallow, &Ellrys_DuskhallowAI::Create);
pScriptMgr->register_creature_script(CN_EramasBrightblaze, &Eramas_BrightblazeAI::Create);
pScriptMgr->register_creature_script(CN_YAZZAI, &YazzaiAI::Create);
pScriptMgr->register_creature_script(CN_WARLORD_SALARIS, &Warlord_SalarisAI::Create);
pScriptMgr->register_creature_script(CN_GARAXXAS, &GaraxxasAI::Create);
pScriptMgr->register_creature_script(CN_APOKO, &ApokoAI::Create);
pScriptMgr->register_creature_script(CN_ZELFAN, &ZelfanAI::Create);
//Trash Mobs
pScriptMgr->register_creature_script(CN_COILSKAR_WITCH, &CoilskarWitchAI::Create);
pScriptMgr->register_creature_script(CN_SISTER_OF_TORMENT, &SisterOfTormentAI::Create);
pScriptMgr->register_creature_script(CN_SB_IMP, &SunbladeImpAI::Create);
pScriptMgr->register_creature_script(CN_SB_MAGE_GUARD, &SunbladeMageGuardAI::Create);
pScriptMgr->register_creature_script(CN_SB_MAGISTER, &SunbladeMagisterAI::Create);
}
| [
"jozsab1@gmail.com"
] | jozsab1@gmail.com |
a95a4726ef05df980fb52d55a0a0c8a439c07d89 | 3bbc63175bbff8163b5f6b6af94a4499db10a581 | /StuMgr/Mid/RecvThread.h | be9503bbac348b22620cf6555c626e1c38806304 | [] | no_license | chancelee/MyProject | 76f8eb642544a969efbb10fa4e468daeba5b88ef | 62f5825b244f36ed50f6c88868e13670e37281d5 | refs/heads/master | 2021-09-16T01:31:00.158096 | 2018-06-14T10:08:42 | 2018-06-14T10:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | h | // RecvThread.h: interface for the CRecvThread class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_RECVTHREAD_H__FD2FA857_694B_476A_82A1_50FE2DB67F1D__INCLUDED_)
#define AFX_RECVTHREAD_H__FD2FA857_694B_476A_82A1_50FE2DB67F1D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "..\common\ICommand.h"
class CRecvThread : public ICommand
{
public:
CRecvThread(LPVOID lParam, SOCKET socket);
virtual ~CRecvThread();
virtual BOOL Exec();
private:
SOCKET m_sockClient;
LPVOID m_lParam;
};
#endif // !defined(AFX_RECVTHREAD_H__FD2FA857_694B_476A_82A1_50FE2DB67F1D__INCLUDED_)
| [
"styxschip@sina.com"
] | styxschip@sina.com |
31d630bf0802cbe8d6777972ba2de08a7d16b6a7 | 63c637fc2773ef46cd22e08e3334121512c31074 | /3wkSeries/Day1/ELBOW_CASES/elbow_tri/67/U | 0c49a226b21a55317fc2c9b84c5a85ae27a1720c | [] | no_license | asvogel/OpenFOAMEducation | 438f811ad47631a414f6016e643dd12792613828 | a1cf886fb6f9759eada7ecc34e62f97037ffd0e5 | refs/heads/main | 2023-09-03T17:26:24.525385 | 2021-11-05T18:08:49 | 2021-11-05T18:08:49 | 425,034,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,023 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 9
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
format ascii;
class volVectorField;
location "67";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField nonuniform List<vector>
918
(
(0.98516 -0.000507254 0)
(0.00501551 2.96625 0)
(0.00779814 0.888511 0)
(0.979704 0.00214567 0)
(-0.0121508 2.0624 3.76002e-20)
(-0.00704872 2.9488 -2.46022e-18)
(0.819586 1.16311 4.49282e-19)
(0.11566 0.0702736 -1.47368e-20)
(0.999909 -0.000276743 0)
(0.066285 0.731336 0)
(0.0112952 0.509249 0)
(0.732838 -0.00460443 0)
(0.0111099 2.93039 0)
(0.00251242 2.79518 0)
(-0.0179005 3.14916 7.80713e-19)
(-0.0218048 1.91486 8.46605e-21)
(0.282026 0.0499831 1.01778e-18)
(0.188829 1.14255 3.16779e-19)
(0.962725 0.00501674 0)
(0.00739593 0.479553 0)
(-0.0183333 0.0883392 -6.94125e-19)
(1.00197 -0.00497521 0)
(1.00023 -0.00978461 0)
(0.975738 -0.00643884 0)
(0.59843 0.0271489 0)
(0.0148453 2.64145 0)
(-0.014915 2.91002 9.04509e-19)
(0.00965293 0.936083 0)
(-0.0172778 1.17996 0)
(0.0114835 0.918951 0)
(-0.0143196 2.59402 0)
(-0.00109413 2.11665 -3.00294e-20)
(-0.0113419 1.89494 0)
(-0.0206023 2.98761 -8.84059e-23)
(-0.0166846 3.00529 1.91195e-18)
(0.00209747 3.00017 0)
(0.871384 -0.00965503 0)
(0.402724 0.933254 1.8006e-19)
(0.804628 1.17741 -5.13004e-19)
(0.956295 1.02267 5.57397e-19)
(0.67329 1.26922 -1.04105e-19)
(0.674195 1.24357 5.99284e-19)
(0.154023 0.124658 1.43769e-20)
(0.140615 0.0539558 0)
(1.15976 0.562833 0)
(0.128828 0.103979 6.53905e-20)
(0.0904799 0.0597136 -6.78524e-20)
(0.919908 -0.00745785 0)
(1.00027 0.000161336 0)
(0.999909 0.000338582 0)
(1.00363 -0.0077595 0)
(1.00096 -0.000918632 0)
(1.00017 3.70284e-05 0)
(0.0731823 1.82623 -7.72736e-19)
(0.0319521 0.946124 0)
(0.0997825 0.811601 0)
(0.0125018 0.895503 0)
(0.0390267 0.650625 0)
(0.00646731 2.01426 0)
(-0.00356445 0.80096 0)
(0.0117003 0.518792 0)
(-0.0025529 0.791789 0)
(0.00820381 0.499967 0)
(0.841737 -0.0156847 0)
(0.840626 0.0303262 0)
(0.762989 -0.0064826 0)
(0.801872 0.0311015 0)
(0.702155 0.00826204 0)
(0.0146825 3.00041 9.11818e-19)
(0.0114846 3.00807 0)
(0.00610497 3.00274 0)
(0.0135362 2.99737 1.03414e-23)
(0.00796236 2.95848 -1.35519e-18)
(0.0145043 2.98205 0)
(0.0108888 2.90354 0)
(0.024225 2.93089 2.07161e-24)
(0.00474526 2.82511 0)
(0.0302615 2.91661 0)
(-0.00465891 2.7453 0)
(0.305128 3.54205 0)
(-0.131623 3.62268 0)
(0.137684 3.23926 -7.26525e-19)
(-0.013637 2.97766 0)
(-0.0255911 1.98677 0)
(-0.00713227 2.16932 -8.35002e-21)
(-0.0157774 1.92304 2.67842e-21)
(0.346128 0.142874 -3.5345e-19)
(0.312363 0.0286859 -3.43483e-19)
(0.301198 0.148612 -1.05802e-18)
(0.24444 0.0577648 -6.87834e-19)
(0.229239 0.983272 0)
(0.272193 1.29329 -3.68057e-19)
(0.365625 1.22728 6.13828e-19)
(0.987434 0.00857289 0)
(0.941857 0.00582585 0)
(1.0003 0.000581049 0)
(1.00286 0.00930952 0)
(1.00301 0.00847168 -2.7437e-18)
(0.991908 0.00969568 2.07194e-18)
(-0.0100528 0.786207 0)
(0.00879199 0.488733 0)
(-0.0448073 1.00612 0)
(-0.0248684 0.8288 0)
(0.00585597 0.480787 0)
(-0.0292442 0.109287 2.14809e-19)
(0.0652507 0.072562 0)
(0.993554 -0.00837047 0)
(0.954466 -0.00653166 0)
(0.743691 0.0303459 0)
(0.680702 0.0246024 0)
(0.662559 0.0166124 0)
(0.971151 -0.00733572 0)
(0.593122 0.0713726 0)
(0.450922 -0.00991215 1.54105e-18)
(-0.037389 2.86138 6.67001e-19)
(0.0410415 2.90984 0)
(0.0535572 2.88631 0)
(-0.00452549 2.70066 0)
(-0.0131199 2.98526 8.5587e-19)
(-0.0178058 2.89508 0)
(-0.0153706 2.98806 -2.65491e-18)
(-0.0132942 2.92519 9.09053e-19)
(-0.0273202 1.34495 0)
(-0.00321909 1.37394 0)
(-0.00742369 2.13403 4.8447e-22)
(-0.00635448 2.09598 0)
(-0.0238953 1.9024 0)
(0.938629 -0.0073807 0)
(0.857545 -0.00997778 0)
(0.863292 0.00553932 0)
(0.949617 -0.0078082 0)
(0.884082 -0.00819316 0)
(0.514172 1.12619 -2.27381e-19)
(0.56334 1.17722 0)
(0.367332 0.878225 3.36079e-20)
(0.309984 0.736902 0)
(0.917245 1.06014 -1.53771e-19)
(1.03539 0.869398 3.12707e-19)
(0.358392 1.35443 0)
(0.525892 1.32507 0)
(0.548838 1.26384 0)
(0.120967 0.184775 -3.02111e-19)
(0.178375 0.127464 0)
(0.178241 0.0762959 1.91094e-19)
(1.00635 0.924004 0)
(1.08033 0.777925 0)
(1.10547 0.719473 -2.48649e-19)
(1.13917 0.622299 0)
(1.1898 0.406182 5.72833e-20)
(0.957772 -0.00869651 0)
(0.962521 -0.0100304 0)
(0.901769 -0.0079863 0)
(0.984206 -0.0091448 0)
(0.974716 -0.00932999 0)
(0.937141 -0.00637362 0)
(1.00019 0.00234019 0)
(1.0009 0.00141543 0)
(0.999909 0.000855268 0)
(0.0355654 2.07324 4.28208e-19)
(0.118817 1.76908 0)
(0.0181076 2.18714 6.58392e-19)
(0.0461038 1.88039 -5.49101e-19)
(0.106359 1.14843 -2.59401e-19)
(0.0494612 1.02758 0)
(0.143006 0.978663 0)
(0.00396802 0.851442 0)
(0.0160285 0.589104 0)
(-0.00107187 2.24228 -8.27645e-22)
(0.0157721 2.0187 0)
(-0.00196844 2.24475 -2.98479e-20)
(0.00779746 2.0236 4.65541e-20)
(-0.00112364 0.827529 0)
(-0.00397238 0.813068 0)
(0.0103339 0.544639 0)
(-0.00773745 0.78755 0)
(0.00645984 0.489686 0)
(0.938507 0.00980651 0)
(0.850319 -0.0146168 0)
(0.927671 0.000440253 0)
(0.842632 -0.0128787 0)
(0.811919 -0.00268516 0)
(0.89804 0.0232513 0)
(0.872903 0.0280934 0)
(0.788134 -0.00641462 0)
(0.00562792 3.06478 -8.49462e-21)
(0.0167338 3.05779 0)
(0.0146903 2.96901 0)
(0.00865226 2.87615 0)
(0.920731 3.95455 0)
(1.23407 3.28816 9.26507e-19)
(0.0690474 3.06995 0)
(-0.0292006 2.90275 0)
(-0.00856503 1.39577 0)
(-0.0306134 1.69558 0)
(-0.0174233 1.53007 0)
(-0.0301485 2.55223 -8.10599e-21)
(-0.013744 2.24339 0)
(-0.0198604 2.39113 0)
(-0.0017067 1.95034 8.8686e-22)
(-0.00370978 2.24077 -6.7646e-21)
(-0.00549766 2.20451 -2.88901e-21)
(-0.00958477 1.93519 0)
(0.398953 0.124595 5.39924e-19)
(0.361206 0.0180505 -5.29785e-19)
(0.258823 1.58506 0)
(0.277496 0.756316 -3.15672e-19)
(0.177078 1.67236 -1.04832e-18)
(0.225976 1.21996 1.05061e-18)
(0.901995 0.00636038 0)
(0.967386 0.0111377 0)
(0.974536 0.0108153 0)
(0.923287 0.00640794 0)
(-0.00920203 0.785315 0)
(-0.00862619 0.782168 0)
(0.00510365 0.484045 0)
(0.117439 0.089176 6.05619e-19)
(0.104961 0.077385 -7.1666e-19)
(0.0740941 0.0581365 0)
(1.09929 0.0863423 2.7039e-20)
(1.08138 0.0395582 0)
(1.01341 0.0400553 0)
(0.907415 -0.005439 0)
(0.451856 0.105376 0)
(0.511778 0.0873586 -2.46227e-18)
(0.406691 0.0116919 9.20658e-19)
(0.00867297 2.98071 7.16113e-19)
(-0.0328711 2.86525 4.65771e-20)
(0.00362426 3.05022 -1.79881e-20)
(0.0202331 3.04338 6.40246e-19)
(-0.015018 2.99658 2.98574e-20)
(-0.0129489 2.94949 -1.20155e-22)
(-0.0172537 3.01192 -5.5282e-19)
(0.0148689 3.02376 3.99939e-19)
(0.00737632 3.03679 -6.33365e-19)
(0.93407 -0.0011866 0)
(0.939519 -0.00317871 0)
(0.846061 -0.00945988 0)
(0.956508 0.0119277 0)
(0.942604 0.0132908 0)
(0.881567 0.00582302 0)
(0.916235 0.0182213 0)
(0.925656 0.0152589 0)
(0.838522 0.00159651 0)
(0.716616 1.40336 4.03019e-20)
(0.749918 1.51203 0)
(0.181394 0.315265 7.05337e-20)
(0.228533 0.668843 5.67811e-19)
(0.262351 0.720467 -3.31818e-19)
(0.263002 0.521232 6.60237e-19)
(0.346057 0.810928 1.59009e-18)
(0.140519 0.230038 3.75505e-19)
(0.257442 0.150806 7.27874e-19)
(0.215916 0.145146 1.88708e-19)
(0.211914 0.0683222 3.57395e-19)
(1.17884 0.464196 6.39608e-20)
(1.19443 0.257028 5.92499e-20)
(0.010269 2.23577 2.53589e-19)
(0.0403724 1.94854 0)
(0.970793 0.0293923 0)
(0.943429 0.013955 0)
(0.869186 -0.017883 0)
(0.0112262 3.07423 0)
(0.0195966 2.944 1.17052e-18)
(0.0164315 2.95626 0)
(0.00642808 2.85063 -1.16112e-18)
(0.00629378 3.09083 2.83866e-19)
(0.00727491 3.08271 0)
(0.782711 1.81354 -1.58892e-19)
(1.24194 2.48912 4.03775e-19)
(0.764707 1.95287 -1.22937e-18)
(0.0196977 2.98033 -6.1696e-19)
(0.0352854 2.99943 0)
(-0.0343238 2.87681 0)
(-0.00418399 2.22408 -1.3095e-20)
(-0.00328084 2.24512 9.74139e-21)
(0.00100256 1.98547 -7.22038e-21)
(0.278214 1.39434 1.0246e-18)
(0.23881 0.550701 -7.02554e-19)
(0.0638006 1.99793 7.62549e-19)
(0.135299 1.88416 -9.10215e-19)
(0.180221 1.51165 9.49578e-20)
(0.00205937 3.1186 -1.76899e-18)
(0.0164364 3.11794 1.89661e-18)
(-0.00914655 2.98106 7.85824e-19)
(-0.00357618 2.97737 -7.42256e-19)
(-0.0210438 2.88117 -8.00341e-19)
(0.00862517 3.0996 -2.10998e-18)
(0.00226201 3.10636 2.05994e-18)
(0.282094 0.695164 0)
(0.248361 0.684174 -1.18011e-18)
(0.0959326 0.225163 5.23936e-19)
(0.357745 0.938006 1.11226e-18)
(0.195647 0.276051 -1.71484e-18)
(1.186 0.175131 6.27487e-20)
(1.19485 0.311684 0)
(1.17438 0.122817 -6.10052e-21)
(0.00145375 2.25415 -1.47569e-21)
(0.00491112 2.24562 0)
(0.0245916 1.98413 0)
(0.340074 1.30317 -3.67884e-19)
(0.37477 1.1499 -7.99744e-19)
(0.210293 0.37801 1.42587e-18)
(1.00588 -0.0108285 0)
(1.00767 -0.00763373 5.06142e-19)
(-0.0227818 1.32552 0)
(-0.0392157 1.32443 0)
(1.00221 0.00351432 1.81172e-21)
(1.00366 0.00946974 1.03345e-18)
(-0.0184861 2.53671 1.02716e-20)
(-0.023882 2.57934 0)
(0.0345114 3.17706 4.07476e-19)
(0.390626 3.48402 0)
(1.1751 0.663637 -5.7161e-20)
(1.01285 0.0131427 -2.13515e-21)
(1.02134 -0.0102848 0)
(1.0017 0.000130699 7.86508e-23)
(0.113823 1.36983 0)
(0.143778 2.56856 0)
(0.0256087 1.31013 0)
(-0.000155361 2.62026 2.82308e-20)
(-0.0212786 2.5777 3.66127e-21)
(0.998274 0.029458 1.97781e-21)
(1.06313 0.00467414 0)
(1.09766 0.0251535 0)
(-0.02917 1.73846 0)
(-0.0184715 2.57951 0)
(-0.00514271 1.31179 0)
(0.311598 1.48196 -1.68375e-19)
(1.0113 -0.00961516 0)
(1.0094 -0.0149146 0)
(1.00237 0.000753823 6.46837e-19)
(1.00547 -0.00479947 -7.60257e-19)
(1.00118 -0.000969412 0)
(-0.0144896 1.46294 0)
(-0.00727042 1.37424 0)
(-0.00800123 1.42027 0)
(-0.00911572 1.29944 0)
(-0.0188563 1.28659 0)
(-0.00967769 1.26953 0)
(1.03505 -0.00602544 0)
(1.0196 0.0155345 -8.29288e-22)
(0.821289 1.27348 2.60633e-19)
(1.00224 0.000320687 -6.44395e-19)
(1.00406 0.00526197 7.54392e-19)
(1.00118 0.00207567 0)
(1.01273 0.0103637 6.41284e-19)
(1.00798 0.00831438 -7.77017e-19)
(1.00856 0.0146969 0)
(-0.0236534 2.6074 0)
(-0.0256256 2.58694 -1.83727e-20)
(-0.0230132 2.60102 1.30588e-20)
(1.23779 0.268003 5.80024e-19)
(1.16254 0.0871461 0)
(0.0406833 3.0779 -9.11694e-19)
(0.0650128 2.85646 -6.63005e-20)
(0.138617 3.19224 1.39429e-18)
(0.133876 3.22005 -1.96989e-19)
(0.132883 3.23098 0)
(0.0198233 3.13731 2.35242e-19)
(0.0747237 3.16013 8.99088e-19)
(0.0675757 3.18524 -4.43445e-19)
(0.0221762 3.13002 0)
(0.583761 0.282446 0)
(0.51766 0.30171 0)
(1.14652 0.699691 1.29886e-19)
(1.14025 0.821094 -1.13576e-19)
(1.20298 0.586524 0)
(1.23074 0.521037 0)
(1.01604 0.0133783 -1.19536e-18)
(1.01498 0.0142807 1.50056e-18)
(1.02539 -0.0098006 0)
(1.02345 -0.011847 0)
(1.00642 0.00263827 0)
(1.01041 0.00374704 0)
(1.00458 0.00186758 0)
(1.00978 0.00625405 0)
(1.00781 0.00596699 0)
(1.00451 0.00472023 0)
(0.102902 1.36834 0)
(0.0998501 1.33143 0)
(0.133119 1.40539 0)
(0.151153 1.41056 0)
(0.145501 2.59363 0)
(0.185236 2.66383 -4.23402e-19)
(0.101556 2.64896 0)
(0.0852782 2.65184 1.98347e-19)
(0.0387986 2.67478 -1.48766e-19)
(0.013678 1.32178 0)
(0.0215762 1.24478 0)
(0.0183093 1.33188 0)
(0.0359973 1.26906 0)
(0.0042549 1.98377 3.41406e-21)
(-0.020081 2.60538 -1.88577e-20)
(-0.00823512 2.66152 1.38333e-20)
(-0.0181405 2.68082 0)
(-0.0229889 2.61125 -4.71116e-21)
(-0.0231234 2.60617 1.29839e-20)
(0.0131103 1.98215 3.93969e-22)
(-0.00696454 2.39319 2.52996e-20)
(-0.012978 2.41537 -1.5689e-20)
(1.01113 0.0394285 1.2114e-18)
(1.00511 0.0185132 -1.50629e-18)
(1.00415 0.0457471 -1.23331e-18)
(0.977125 0.0364443 1.55201e-18)
(1.06436 0.00849413 0)
(1.04947 -0.00821689 0)
(1.09462 0.0353333 0)
(1.07452 0.0130623 0)
(1.07235 0.00059398 0)
(1.14057 0.0835875 0)
(1.1121 0.0448552 0)
(1.11597 0.0327002 0)
(-0.0254262 2.42966 1.04771e-21)
(-0.0140389 2.01225 0)
(-0.0168084 2.21487 0)
(-0.0203578 2.60013 -1.08192e-20)
(-0.0175641 2.61008 1.89719e-22)
(0.00295825 1.57437 -3.568e-20)
(-0.00602479 1.50256 3.63505e-20)
(-0.0154776 1.39137 0)
(-0.0190699 1.39801 0)
(-0.0241841 1.39265 0)
(-0.00336636 1.31294 0)
(0.00923382 1.23812 0)
(0.386434 1.49931 2.73977e-19)
(0.429711 1.50013 1.45158e-19)
(0.597479 2.44405 -2.40263e-19)
(0.398245 2.54104 7.07171e-19)
(0.349158 2.05269 7.14328e-20)
(1.02108 -0.00810203 0)
(1.01551 -0.00974109 0)
(1.01492 -0.0155013 0)
(1.0074 -0.00107001 0)
(1.00493 -0.000907263 0)
(1.00778 -0.00468261 0)
(1.00927 -0.00360502 0)
(1.01423 -0.0043656 0)
(1.02035 0.0163665 1.17141e-18)
(1.01764 0.015483 -1.49606e-18)
(1.02064 0.018448 -1.18108e-18)
(1.01827 0.016783 1.4744e-18)
(0.784661 1.32475 0)
(0.720963 1.37498 2.46858e-19)
(0.896788 1.22433 9.81117e-20)
(0.942733 1.16946 -1.30556e-19)
(1.15452 2.59951 2.78347e-19)
(0.767522 0.123002 5.9991e-19)
(1.16377 0.109447 0)
(1.21291 0.195072 -4.66797e-19)
(1.20007 0.155717 -1.9874e-20)
(1.00634 0.157484 0)
(0.129039 2.95832 5.30867e-19)
(0.105226 2.86429 -1.15464e-18)
(0.012883 2.3739 7.71186e-19)
(0.0969151 -0.15633 -3.27128e-19)
(0.335508 3.41424 -2.15612e-19)
(0.190684 3.30897 0)
(0.234464 3.34958 2.80804e-19)
(0.239437 3.03093 -1.77529e-18)
(0.333066 3.18925 0)
(0.00582686 3.12113 4.58828e-20)
(0.0155565 3.12986 -5.41797e-19)
(0.0140655 3.12592 7.9741e-19)
(0.034743 3.14008 0)
(0.03325 3.15021 0)
(1.21016 2.59708 0)
(0.546323 0.804208 -5.27655e-19)
(1.06651 0.993963 -8.983e-21)
(1.00122 1.07853 0)
(0.854367 0.97393 -1.09513e-19)
(1.0923 0.895026 2.7909e-20)
(0.310623 0.33433 -8.49171e-19)
(0.657058 0.325039 -1.70099e-20)
(0.554906 0.222325 4.06462e-19)
(0.543194 0.336317 2.97398e-20)
(0.43541 0.275242 -1.1951e-18)
(0.61673 0.325801 0)
(0.710087 0.424671 6.70667e-19)
(0.711094 0.426074 0)
(0.581884 0.340626 0)
(0.508709 0.247575 0)
(0.827166 0.625209 4.09879e-19)
(1.23901 0.290377 -4.881e-19)
(1.23916 0.429275 0)
(1.24744 0.369715 0)
(0.684718 0.195607 6.20145e-19)
(0.873844 0.553773 -3.75159e-19)
(0.77149 0.52667 6.67844e-19)
(0.962913 0.446516 -7.35598e-19)
(1.01915 0.0149829 8.02067e-19)
(1.01755 0.0143592 -8.07988e-19)
(1.0159 0.0153572 0)
(1.03652 -0.00556772 0)
(1.02992 -0.0083541 -7.5702e-19)
(1.02797 -0.0119472 7.49491e-19)
(1.02486 0.0105794 0)
(1.02334 0.0143691 0)
(1.01141 0.00416969 0)
(1.01419 0.00916274 0)
(1.01515 0.00418858 0)
(1.01426 0.00290413 0)
(0.0716636 1.35213 0)
(0.0778539 1.29779 0)
(0.149571 1.38627 9.22124e-21)
(0.28196 1.48045 8.94571e-20)
(0.17741 1.45131 1.88025e-19)
(0.210351 1.45653 -3.06738e-19)
(0.174646 1.41122 0)
(0.136696 1.59916 -7.08224e-20)
(0.117705 1.57818 0)
(0.34551 2.0023 -1.03864e-19)
(0.341814 2.33821 6.14487e-19)
(0.193702 1.46397 6.17382e-20)
(0.268948 1.39661 2.35375e-20)
(0.202564 1.38961 -1.90199e-20)
(0.278273 1.33905 -1.03171e-19)
(0.243011 1.57896 0)
(0.267532 1.6161 1.12328e-19)
(0.0311165 2.25844 -2.92291e-20)
(0.0439592 2.66386 0)
(0.066688 2.39488 1.35938e-19)
(0.0633921 2.41563 0)
(0.0697278 2.66541 -2.19801e-19)
(0.0493283 2.69407 0)
(0.0272594 1.43914 3.26041e-20)
(0.0358592 1.49039 0)
(0.0293476 1.40605 0)
(0.0242909 1.41135 -3.67903e-20)
(0.00065976 2.64783 -1.70159e-20)
(0.0299543 2.6932 1.67045e-19)
(0.010524 2.71836 1.17678e-21)
(0.00392528 1.83692 -3.25569e-21)
(-0.00153618 1.69098 -3.42407e-21)
(0.0111657 1.30092 0)
(0.0202853 1.22085 0)
(0.047276 1.5949 -2.58478e-20)
(0.0334117 1.47147 -3.31227e-20)
(0.0376679 1.53487 4.08994e-20)
(0.0410797 1.61879 0)
(-0.0292184 2.26917 9.60808e-20)
(-0.0302177 2.54712 -4.0312e-20)
(-0.0160535 2.44482 3.93145e-21)
(-0.00282673 1.85285 3.94395e-21)
(-0.0251404 2.49677 2.13253e-21)
(-0.0202039 2.44048 2.51071e-22)
(1.01844 0.0213723 -8.00069e-19)
(1.01457 0.0279631 8.0574e-19)
(1.01313 0.0163601 0)
(1.01083 0.0708744 1.12665e-18)
(0.991868 0.0597045 -1.26159e-18)
(0.950622 0.0568755 1.41017e-18)
(1.01441 0.112236 -1.5034e-19)
(1.04297 -0.00555642 0)
(1.05138 -0.00117029 7.21965e-19)
(1.03924 -0.00974351 -7.2342e-19)
(1.07191 0.0429462 -4.29252e-20)
(1.06504 0.0242198 3.70204e-19)
(1.06336 0.0570599 0)
(1.05402 0.0502869 -1.33118e-19)
(1.03236 0.0428484 0)
(1.02594 0.0398857 0)
(1.02789 0.0137079 0)
(1.02382 0.016344 0)
(1.04042 0.0332188 2.74204e-19)
(1.03897 0.0277482 -6.06381e-19)
(1.05138 0.034657 -2.90621e-19)
(1.04847 0.0347858 -3.20108e-19)
(1.0717 0.0653488 6.24607e-19)
(1.09715 0.0531671 0)
(1.10624 0.0973585 0)
(-0.0248707 2.27422 5.36124e-20)
(-0.024024 2.01778 8.05372e-22)
(-0.0200926 2.02524 0)
(-0.0265373 2.4431 -5.33698e-20)
(-0.0215477 2.39936 -1.80437e-21)
(-0.0327374 2.47074 5.3023e-21)
(-0.0205375 2.61887 -1.16824e-20)
(-0.0227569 2.56078 6.53657e-23)
(-0.0211418 2.51244 -3.12498e-21)
(-0.0157313 2.61298 1.02535e-20)
(-0.0207185 2.61487 -1.0947e-20)
(-0.00584373 1.49632 -6.3495e-22)
(0.00373659 1.62268 -3.37548e-20)
(0.371277 1.44749 -1.15947e-19)
(0.371169 1.38095 3.63889e-20)
(0.661478 1.42564 -2.38819e-19)
(0.528743 1.49283 -1.42794e-19)
(0.587136 1.45823 0)
(0.593257 2.42112 2.06898e-19)
(0.661679 2.41659 3.37456e-19)
(0.411105 2.5105 8.78508e-20)
(0.402329 2.53496 -6.09211e-19)
(0.509954 2.47614 6.13969e-19)
(0.55318 2.45785 0)
(0.487977 2.51533 -5.59202e-19)
(0.248355 2.58754 1.14346e-18)
(0.354681 2.55967 -7.73507e-20)
(0.283914 2.64925 -1.58621e-18)
(0.948033 2.37449 7.26576e-19)
(0.838192 2.37962 0)
(1.01108 0.000529692 2.62409e-20)
(1.01536 -0.00536519 -2.12851e-20)
(1.01767 -0.00347035 -3.88751e-19)
(1.01504 -0.000832381 3.90866e-19)
(1.01246 0.00126935 0)
(0.647758 1.2907 0)
(0.671114 1.18427 0)
(0.785041 1.1027 0)
(0.66421 1.14793 0)
(1.18461 2.61304 5.97356e-20)
(1.07261 2.36036 0)
(0.834108 2.16455 3.83162e-21)
(0.8236 2.43041 0)
(0.921697 2.52418 -4.21496e-19)
(0.956924 2.48028 2.80374e-19)
(0.797905 0.184608 0)
(0.739783 0.157346 1.62822e-19)
(0.907312 0.15216 9.47681e-19)
(0.822944 0.156113 -3.55294e-19)
(0.779255 0.0904137 -1.09485e-18)
(1.08289 0.2418 -8.91268e-19)
(1.00039 0.30444 -1.77705e-20)
(0.928964 0.308123 8.59075e-19)
(1.00774 0.234955 7.21138e-19)
(0.948135 0.199684 -1.25348e-18)
(0.910587 0.203804 1.5675e-19)
(0.948164 0.270655 -3.326e-19)
(0.92614 0.231205 0)
(0.996024 0.19577 6.18233e-19)
(1.04746 0.194806 0)
(1.04504 0.223168 0)
(1.10769 0.121614 2.89651e-19)
(1.07183 0.181563 -1.50331e-20)
(1.07629 0.241769 -1.57708e-19)
(1.10193 0.207706 0)
(1.02331 0.0467393 6.16627e-19)
(1.03931 0.0603788 7.71336e-19)
(1.03451 0.0464712 -6.12329e-19)
(1.04299 0.0680022 -5.17283e-19)
(1.02035 0.0756914 -7.93677e-19)
(0.985471 0.160253 0)
(0.990355 0.106153 0)
(0.965306 0.0747031 -5.01102e-19)
(0.905537 0.098544 1.99377e-19)
(1.04009 0.108137 7.15821e-19)
(1.06974 0.125237 -8.35494e-19)
(1.07649 0.157644 7.46094e-19)
(1.03115 0.151378 0)
(1.07528 0.112697 0)
(1.0543 0.0935172 -3.42473e-19)
(1.04335 0.098132 -5.8435e-19)
(0.57892 1.0554 1.39778e-19)
(0.60429 1.38011 -4.12236e-20)
(1.15445 2.72868 -2.27349e-19)
(1.22008 3.07107 2.01204e-21)
(1.24623 2.71184 -1.23543e-19)
(1.2747 2.69512 -3.18833e-20)
(1.20215 2.33541 -1.1094e-20)
(1.20778 2.97495 -9.36109e-20)
(1.22791 2.94048 2.34547e-19)
(1.21025 3.22394 -1.42793e-19)
(1.36989 2.95485 1.97313e-19)
(1.35862 2.87294 0)
(0.563735 0.812952 -5.0305e-20)
(0.109904 1.22502 5.69647e-19)
(0.557849 0.357386 5.55121e-19)
(0.396901 0.104248 6.02165e-19)
(0.479598 0.315416 6.776e-19)
(0.545313 0.433591 -1.09577e-18)
(0.547259 0.429879 8.97451e-19)
(0.466501 0.314674 -3.40939e-19)
(0.345121 0.242812 7.70719e-19)
(0.709912 0.269393 -3.58146e-19)
(0.669593 0.292349 0)
(0.608641 0.207728 6.61013e-21)
(0.74306 0.507178 3.63503e-19)
(0.721048 0.477805 -1.32153e-18)
(0.623566 0.445488 1.11868e-20)
(0.620617 0.436502 0)
(0.69335 0.717697 3.96307e-19)
(0.855493 0.779248 3.94145e-19)
(0.779115 0.861768 -4.61231e-19)
(0.900968 0.816447 -1.54026e-19)
(0.932037 0.861787 -3.7157e-20)
(0.939121 0.861513 3.8052e-20)
(0.86763 0.6597 -6.78517e-19)
(0.947537 0.713357 1.43018e-19)
(1.00688 0.728467 0)
(0.997903 0.705071 -1.93199e-19)
(1.03015 0.344908 2.11873e-19)
(1.14983 0.306708 2.87348e-19)
(1.07089 0.279129 3.64248e-19)
(1.01941 0.377343 -4.30321e-19)
(1.0677 0.439733 0)
(1.12368 0.421427 0)
(0.923484 0.381153 1.51461e-21)
(0.840002 0.317476 0)
(0.88531 0.313108 4.06519e-19)
(0.910539 0.316735 -8.04879e-21)
(0.957338 0.449957 2.04912e-18)
(0.918424 0.505402 5.27088e-19)
(0.923183 0.471974 -5.61944e-19)
(0.83898 0.459334 6.03009e-19)
(0.823588 0.452239 3.61617e-19)
(0.79562 0.434585 -3.55623e-19)
(1.02742 -0.000189416 6.47604e-19)
(1.02 0.000106343 0)
(1.01855 0.00103225 4.22286e-19)
(1.02174 -0.00150511 -9.56582e-19)
(1.02238 0.00454486 4.64721e-19)
(1.0203 0.011577 -9.73133e-19)
(1.02119 0.0109354 0)
(1.02043 0.0111408 -2.02827e-19)
(1.01593 0.0078681 5.08862e-19)
(1.01658 0.010659 -2.5391e-19)
(1.01728 0.0100076 1.86984e-19)
(0.0299829 1.32654 0)
(0.0364406 1.38088 0)
(0.048836 1.32827 0)
(0.053566 1.27524 0)
(0.0746417 1.40116 -4.98273e-20)
(0.0834017 1.3671 2.2325e-20)
(0.117689 1.54516 -1.41667e-20)
(0.104402 1.38934 -5.70485e-21)
(0.0385188 1.47688 1.77308e-20)
(0.0426357 1.47066 -1.36184e-20)
(0.0670594 1.38756 -1.01333e-20)
(0.0594877 1.38895 4.57329e-20)
(0.0508811 1.36518 6.80149e-21)
(0.0426425 1.38694 3.65558e-21)
(0.107788 2.36326 -1.50118e-19)
(0.0965917 2.41158 0)
(0.1706 2.03732 1.08149e-19)
(0.113403 1.70383 3.95366e-20)
(0.234036 2.03398 -8.97957e-20)
(0.200338 2.42512 0)
(0.262544 2.3751 -6.05763e-19)
(0.302513 2.37279 4.28122e-19)
(0.22912 1.99378 -2.4963e-19)
(0.155323 2.15288 1.69698e-19)
(0.14176 2.26014 0)
(0.0191578 1.87818 4.61173e-21)
(0.00042681 2.38779 -3.39415e-20)
(0.00699531 2.14573 0)
(0.0116532 2.45136 -1.36241e-20)
(0.0286133 2.2943 9.30945e-21)
(0.0152245 1.41827 -7.05325e-21)
(0.0126578 1.39995 1.17543e-19)
(0.012574 1.40644 -3.88897e-20)
(0.0211914 1.41129 -3.26985e-20)
(0.0254706 1.44283 0)
(0.00857829 1.38774 0)
(0.00106317 1.29775 -4.61488e-20)
(0.00480035 1.3796 1.31767e-20)
(0.00853508 1.37941 0)
(0.00666961 1.28956 -3.45221e-20)
(0.0173265 1.21175 7.01269e-20)
(1.04084 0.0121682 0)
(1.04707 0.00839682 -6.77337e-20)
(1.03876 0.0223712 -4.88919e-19)
(1.04861 0.0211713 0)
(1.05253 0.0210313 0)
(1.0364 0.012359 -6.85337e-21)
(1.03101 0.0121871 7.85832e-19)
(1.03166 0.0172147 9.52652e-19)
(1.02549 0.0211288 0)
(1.02218 0.0215496 0)
(1.03527 0.0260995 4.87444e-19)
(1.02561 0.0279148 0)
(1.02358 0.0279755 0)
(-0.0179805 2.02291 0)
(0.000770207 1.6533 -4.37601e-21)
(-0.00453508 1.76066 -3.02723e-20)
(-0.00125246 1.38797 0)
(-0.00650504 1.55438 -1.85393e-20)
(-0.00894696 1.46454 1.15673e-20)
(-0.00596536 1.40147 0)
(0.388535 1.64368 0)
(0.373764 1.30708 -7.13799e-20)
(0.300713 1.34043 0)
(0.425662 1.30593 6.50541e-21)
(0.476356 1.47034 0)
(0.456691 1.41464 2.51667e-20)
(1.0364 2.67522 -1.53602e-20)
(0.968437 2.40323 -9.13178e-19)
(0.921569 2.19154 1.02439e-18)
(0.852213 2.37155 2.41968e-19)
(0.847789 2.48468 0)
(0.917518 2.48085 0)
(0.931381 2.36802 0)
(0.910343 2.35721 -9.44182e-19)
(0.686731 2.44854 -3.94065e-19)
(0.799901 2.438 -9.7647e-20)
(0.810243 2.41217 7.41854e-20)
(0.695548 2.38976 0)
(0.800808 2.3851 0)
(0.758963 2.39849 -3.68634e-19)
(0.767506 2.4744 0)
(0.631299 1.09371 0)
(0.480468 0.900025 -5.12161e-19)
(0.567561 0.944079 -3.2409e-20)
(0.519161 1.03393 0)
(0.519609 0.977024 7.67e-19)
(0.799867 0.884643 -1.29751e-19)
(0.808706 1.02084 0)
(0.783843 0.987126 1.8525e-19)
(0.668074 1.03396 0)
(0.669409 0.9355 0)
(1.16346 2.75183 -2.29802e-19)
(1.14091 2.81515 -9.71249e-20)
(0.928944 2.32926 1.00447e-19)
(0.896742 2.30869 -8.33015e-20)
(1.12904 2.72485 0)
(1.08286 2.69431 1.00219e-19)
(1.08895 2.4783 -3.13708e-19)
(0.983473 2.23132 -3.03756e-20)
(0.49224 1.33038 0)
(0.507986 1.06044 -1.23202e-19)
(0.576424 1.16708 0)
(0.853185 0.249379 0)
(0.759696 0.199556 0)
(0.670661 0.155954 0)
(0.844351 0.251625 -6.39873e-19)
(0.732526 0.242641 3.73566e-19)
(0.92196 0.0903628 -4.11305e-19)
(0.926597 0.132904 0)
(0.913901 0.140804 1.77645e-19)
(0.850343 0.11855 7.1023e-19)
(0.814425 0.0802648 -4.45486e-19)
(1.15564 3.34891 -7.1792e-19)
(1.20458 3.2684 0)
(1.15337 3.37786 -1.48779e-18)
(0.641524 3.53939 1.26228e-18)
(0.863117 3.108 7.17075e-20)
(0.522176 0.799935 6.05136e-19)
(0.423966 0.797339 0)
(0.308088 0.38533 -1.48778e-19)
(0.4725 0.650001 8.56345e-19)
(0.561667 0.360252 -1.95547e-19)
(0.515667 0.465521 2.30866e-19)
(0.674865 0.511621 4.91318e-19)
(0.714002 0.550437 0)
(0.663992 0.574896 0)
(0.629136 0.526054 0)
(1.00837 0.615087 8.82966e-20)
(0.923398 0.554935 -5.13147e-19)
(0.948697 0.586509 3.86554e-19)
(0.979338 0.526556 -3.97288e-19)
(1.0868 0.495122 0)
(1.09519 0.586004 -9.67127e-20)
(0.859324 0.412052 -8.29856e-19)
(0.858198 0.400903 -1.02876e-18)
(0.792762 0.393907 6.39064e-19)
(0.802993 0.377897 -6.48693e-19)
(0.846052 0.337085 -5.19191e-19)
(0.792982 0.337537 6.35101e-19)
(1.02668 0.00612979 -4.93083e-19)
(1.02638 0.00634793 1.0021e-18)
(1.02947 0.00026736 6.27552e-19)
(1.03371 0.00118404 -7.55769e-19)
(1.03383 0.00935202 0)
(1.03007 0.0100554 -1.23054e-18)
(0.0636815 1.64109 1.95187e-20)
(0.0516743 1.5908 0)
(0.0901937 1.69043 1.24605e-19)
(0.0981455 1.6712 -1.10082e-19)
(0.0938951 1.54812 2.5336e-20)
(0.093216 1.54921 0)
(0.0119513 1.6871 0)
(-0.0042689 1.49547 7.38056e-21)
(-0.00208035 1.44134 -6.63987e-21)
(-0.00741807 1.55133 5.36213e-21)
(0.00215669 1.88463 1.1023e-20)
(-0.00969973 1.93756 -1.72607e-21)
(0.496715 1.35731 -2.75014e-19)
(0.490216 1.3577 3.02182e-19)
(0.453076 1.30152 -3.09725e-20)
(0.436332 1.28403 7.71439e-21)
(0.640081 1.30826 0)
(0.555426 1.39862 1.05385e-19)
(0.570793 1.40599 -1.02593e-19)
(0.466731 1.29125 3.01997e-20)
(0.521487 1.24092 0)
(0.573123 1.20374 0)
(0.65362 2.40807 5.7889e-19)
(0.669305 2.44958 1.25929e-18)
(0.713777 2.46026 -8.67733e-19)
(0.609992 2.43408 -2.01791e-19)
(0.559775 2.5245 2.83521e-19)
(0.509058 2.49928 -7.56701e-19)
(0.978175 2.37474 -5.73294e-19)
(1.01233 2.38691 0)
(0.925751 2.16962 -6.58935e-19)
(1.05384 2.67334 0)
(1.05613 2.65995 0)
(0.598738 2.25697 -1.27069e-19)
(1.0366 3.15384 1.28523e-19)
(0.90775 3.02421 -3.17449e-20)
(0.264105 0.847928 0)
(0.290693 0.691249 -3.17203e-19)
(0.460474 0.651119 -3.19009e-19)
(0.378615 2.00131 0)
(0.46219 2.77884 -4.99168e-20)
(0.415773 2.54146 0)
(0.716331 0.66803 -8.37296e-19)
(0.801214 0.685856 1.12161e-18)
(0.821042 0.626867 -1.1082e-18)
(0.693333 0.631132 -1.07328e-19)
(0.748553 0.589125 -4.39939e-19)
(1.00044 2.75275 -9.7746e-20)
(1.04135 2.81395 -1.65155e-19)
(0.631653 2.12069 6.9768e-19)
(0.584151 1.68931 -4.97058e-19)
(0.693584 1.88875 -4.06918e-19)
(0.986657 2.43662 -1.12836e-19)
(0.993668 2.42956 2.962e-19)
(0.649333 1.8221 2.82775e-20)
(0.440848 1.30999 1.44324e-19)
)
;
boundaryField
{
wall-4
{
type noSlip;
}
velocity-inlet-5
{
type fixedValue;
value uniform (1 0 0);
}
velocity-inlet-6
{
type fixedValue;
value uniform (0 3 0);
}
pressure-outlet-7
{
type zeroGradient;
}
wall-8
{
type noSlip;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| [
"avogel1994@gmail.com"
] | avogel1994@gmail.com | |
395a9d8376bf845a34f07440cc310f9290ba2f05 | 7e8c47307531cace46a11861b51f98efa0cfb5cb | /Library/Model.cpp | 28b29c3196e915653c9055466cacd29176d600fd | [] | no_license | AsterNighT/2020CG | 15bca0599cc9ce45cb6d8d83f341c18779bb742c | 4fea0cf6a65f34d5196b8bc554d05e9dfa36d627 | refs/heads/master | 2022-11-05T21:25:59.972138 | 2020-06-22T08:36:18 | 2020-06-22T08:36:18 | 264,388,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,155 | cpp | #include "Model.h"
#include "Scene.h"
#include "Mesh.h"
#include "ModelMaterial.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
Model::Model(Scene& bScene, const std::string& filename, bool flipUVs, const std::string& tangentFileName) : mScene(bScene), mMeshes(), mMaterials(){
Assimp::Importer importer;
UINT flags;
flags = aiProcess_Triangulate | aiProcess_ValidateDataStructure | aiProcess_FixInfacingNormals | aiProcess_GenNormals | aiProcess_JoinIdenticalVertices | aiProcess_PreTransformVertices | aiProcess_GenUVCoords | aiProcess_TransformUVCoords | aiProcess_CalcTangentSpace;
if (flipUVs) {
flags |= aiProcess_FlipUVs;
}
const aiScene* scene = importer.ReadFile(filename, flags);
if (scene->HasMaterials()) {
for (UINT i = 0; i < scene->mNumMaterials; i++) {
mMaterials.push_back(new ModelMaterial(*this, scene->mMaterials[i]));
}
}
if (scene->HasMeshes()) {
for (UINT i = 0; i < scene->mNumMeshes; i++) {
Mesh* mesh;
mesh = new Mesh(*(scene->mMeshes[i]));
mMeshes.push_back(mesh);
}
}
}
Model::~Model() {
for (Mesh* mesh : mMeshes) {
delete mesh;
}
}
Scene& Model::GetScene() {
return mScene;
}
bool Model::HasMeshes() const {
return (mMeshes.size() > 0);
}
bool Model::HasMaterials() const {
return (mMaterials.size() > 0);
}
const std::vector<Mesh*>& Model::Meshes() const {
return mMeshes;
}
const std::vector<ModelMaterial*>& Model::Materials() const {
return mMaterials;
}
std::vector<Item*> Model::loadModel(const std::string& filename, bool flipUVs){
Assimp::Importer importer;
UINT flags;
flags = aiProcess_Triangulate | aiProcess_ValidateDataStructure | aiProcess_FixInfacingNormals | aiProcess_GenNormals | aiProcess_GenUVCoords;
if (flipUVs) {
flags |= aiProcess_FlipUVs;
}
const aiScene* scene = importer.ReadFile(filename, flags);
std::vector<Item*> data;
if (scene->HasMeshes()) {
for (UINT i = 0; i < scene->mNumMeshes; i++) {
Mesh* mesh;
mesh = new Mesh(*(scene->mMeshes[i]));
auto item = new Item();
item->mesh = mesh;
item->name = mesh->Name();
data.emplace_back(item);
}
}
return data;
}
| [
"klxjt99@outlook.com"
] | klxjt99@outlook.com |
586f46cd34b34f49406aab770631c0230733b4b2 | ad3f34546afba57daf888798ad2d29db0361dcca | /T3000/Json-cpp/dist/jsoncpp.cpp | c9e6049bea46ef500d705cecd71aa0e8e1e12a54 | [
"MIT"
] | permissive | temcocontrols/T3000_Building_Automation_System | b7303be5d447cd8d40b1d2424b32b6c7683c2570 | 5fc9204df43aabfe57ccd1a5183b69940d525e2d | refs/heads/master | 2023-08-31T13:37:39.375528 | 2023-08-29T03:30:48 | 2023-08-29T03:30:48 | 6,994,906 | 66 | 62 | MIT | 2023-08-08T12:38:00 | 2012-12-04T05:29:25 | C++ | UTF-8 | C++ | false | false | 163,304 | cpp | /// Json-cpp amalgamated source (http://jsoncpp.sourceforge.net/).
/// It is intended to be used with #include "json/json.h"
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
Baptiste Lepilleur and The JsonCpp Authors explicitly disclaim copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur and
The JsonCpp Authors, and is released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
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.
========================================================================
(END LICENSE TEXT)
The MIT license is compatible with both the GPL and commercial
software, affording one all of the rights of Public Domain with the
minor nuisance of being required to keep the above copyright notice
and license text in the source code. Note also that by accepting the
Public Domain "license" you can re-license your copy using whatever
license you like.
*/
// //////////////////////////////////////////////////////////////////////
// End of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
#include "json/json.h"
#ifndef JSON_IS_AMALGAMATION
#error "Compile with -I PATH_TO_JSON_DIRECTORY"
#endif
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_tool.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include <json/config.h>
#endif
// Also support old flag NO_LOCALE_SUPPORT
#ifdef NO_LOCALE_SUPPORT
#define JSONCPP_NO_LOCALE_SUPPORT
#endif
#ifndef JSONCPP_NO_LOCALE_SUPPORT
#include <clocale>
#endif
/* This header provides common string manipulation support, such as UTF-8,
* portable conversion from/to string...
*
* It is an internal header that must not be exposed.
*/
namespace Json {
static inline char getDecimalPoint() {
#ifdef JSONCPP_NO_LOCALE_SUPPORT
return '\0';
#else
struct lconv* lc = localeconv();
return lc ? *(lc->decimal_point) : '\0';
#endif
}
/// Converts a unicode code-point to UTF-8.
static inline String codePointToUTF8(unsigned int cp) {
String result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
if (cp <= 0x7f) {
result.resize(1);
result[0] = static_cast<char>(cp);
} else if (cp <= 0x7FF) {
result.resize(2);
result[1] = static_cast<char>(0x80 | (0x3f & cp));
result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
} else if (cp <= 0xFFFF) {
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
} else if (cp <= 0x10FFFF) {
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
}
return result;
}
enum {
/// Constant that specify the size of the buffer that must be passed to
/// uintToString.
uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1
};
// Defines a char buffer for use with uintToString().
using UIntToStringBuffer = char[uintToStringBufferSize];
/** Converts an unsigned integer to string.
* @param value Unsigned integer to convert to string
* @param current Input/Output string buffer.
* Must have at least uintToStringBufferSize chars free.
*/
static inline void uintToString(LargestUInt value, char*& current) {
*--current = 0;
do {
*--current = static_cast<char>(value % 10U + static_cast<unsigned>('0'));
value /= 10;
} while (value != 0);
}
/** Change ',' to '.' everywhere in buffer.
*
* We had a sophisticated way, but it did not work in WinCE.
* @see https://github.com/open-source-parsers/jsoncpp/pull/9
*/
template <typename Iter> Iter fixNumericLocale(Iter begin, Iter end) {
for (; begin != end; ++begin) {
if (*begin == ',') {
*begin = '.';
}
}
return begin;
}
template <typename Iter> void fixNumericLocaleInput(Iter begin, Iter end) {
char decimalPoint = getDecimalPoint();
if (decimalPoint == '\0' || decimalPoint == '.') {
return;
}
for (; begin != end; ++begin) {
if (*begin == '.') {
*begin = decimalPoint;
}
}
}
/**
* Return iterator that would be the new end of the range [begin,end), if we
* were to delete zeros in the end of string, but not the last zero before '.'.
*/
template <typename Iter>
Iter fixZerosInTheEnd(Iter begin, Iter end, unsigned int precision) {
for (; begin != end; --end) {
if (*(end - 1) != '0') {
return end;
}
// Don't delete the last zero before the decimal point.
if (begin != (end - 1) && begin != (end - 2) && *(end - 2) == '.') {
if (precision) {
return end;
}
return end - 2;
}
}
return end;
}
} // namespace Json
#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_tool.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_reader.cpp
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2011 Baptiste Lepilleur and The JsonCpp Authors
// Copyright (C) 2016 InfoTeCS JSC. All rights reserved.
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
#include "json_tool.h"
#include <json/assertions.h>
#include <json/reader.h>
#include <json/value.h>
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
#include <istream>
#include <limits>
#include <memory>
#include <set>
#include <sstream>
#include <utility>
#include <cstdio>
#if __cplusplus >= 201103L
#if !defined(sscanf)
#define sscanf std::sscanf
#endif
#endif //__cplusplus
#if defined(_MSC_VER)
#if !defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#endif //_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
#endif //_MSC_VER
#if defined(_MSC_VER)
// Disable warning about strdup being deprecated.
#pragma warning(disable : 4996)
#endif
// Define JSONCPP_DEPRECATED_STACK_LIMIT as an appropriate integer at compile
// time to change the stack limit
#if !defined(JSONCPP_DEPRECATED_STACK_LIMIT)
#define JSONCPP_DEPRECATED_STACK_LIMIT 1000
#endif
static size_t const stackLimit_g =
JSONCPP_DEPRECATED_STACK_LIMIT; // see readValue()
namespace Json {
#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
using CharReaderPtr = std::unique_ptr<CharReader>;
#else
using CharReaderPtr = std::auto_ptr<CharReader>;
#endif
// Implementation of class Features
// ////////////////////////////////
Features::Features() = default;
Features Features::all() { return {}; }
Features Features::strictMode() {
Features features;
features.allowComments_ = false;
features.strictRoot_ = true;
features.allowDroppedNullPlaceholders_ = false;
features.allowNumericKeys_ = false;
return features;
}
// Implementation of class Reader
// ////////////////////////////////
bool Reader::containsNewLine(Reader::Location begin, Reader::Location end) {
return std::any_of(begin, end, [](char b) { return b == '\n' || b == '\r'; });
}
// Class Reader
// //////////////////////////////////////////////////////////////////
Reader::Reader() : features_(Features::all()) {}
Reader::Reader(const Features& features) : features_(features) {}
bool Reader::parse(const std::string& document, Value& root,
bool collectComments) {
document_.assign(document.begin(), document.end());
const char* begin = document_.c_str();
const char* end = begin + document_.length();
return parse(begin, end, root, collectComments);
}
bool Reader::parse(std::istream& is, Value& root, bool collectComments) {
// std::istream_iterator<char> begin(is);
// std::istream_iterator<char> end;
// Those would allow streamed input from a file, if parse() were a
// template function.
// Since String is reference-counted, this at least does not
// create an extra copy.
String doc(std::istreambuf_iterator<char>(is), {});
return parse(doc.data(), doc.data() + doc.size(), root, collectComments);
}
bool Reader::parse(const char* beginDoc, const char* endDoc, Value& root,
bool collectComments) {
if (!features_.allowComments_) {
collectComments = false;
}
begin_ = beginDoc;
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
lastValueEnd_ = nullptr;
lastValue_ = nullptr;
commentsBefore_.clear();
errors_.clear();
while (!nodes_.empty())
nodes_.pop();
nodes_.push(&root);
bool successful = readValue();
Token token;
skipCommentTokens(token);
if (collectComments_ && !commentsBefore_.empty())
root.setComment(commentsBefore_, commentAfter);
if (features_.strictRoot_) {
if (!root.isArray() && !root.isObject()) {
// Set error location to start of doc, ideally should be first token found
// in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError(
"A valid JSON document must be either an array or an object value.",
token);
return false;
}
}
return successful;
}
bool Reader::readValue() {
// readValue() may call itself only if it calls readObject() or ReadArray().
// These methods execute nodes_.push() just before and nodes_.pop)() just
// after calling readValue(). parse() executes one nodes_.push(), so > instead
// of >=.
if (nodes_.size() > stackLimit_g)
throwRuntimeError("Exceeded stackLimit in readValue().");
Token token;
skipCommentTokens(token);
bool successful = true;
if (collectComments_ && !commentsBefore_.empty()) {
currentValue().setComment(commentsBefore_, commentBefore);
commentsBefore_.clear();
}
switch (token.type_) {
case tokenObjectBegin:
successful = readObject(token);
currentValue().setOffsetLimit(current_ - begin_);
break;
case tokenArrayBegin:
successful = readArray(token);
currentValue().setOffsetLimit(current_ - begin_);
break;
case tokenNumber:
successful = decodeNumber(token);
break;
case tokenString:
successful = decodeString(token);
break;
case tokenTrue: {
Value v(true);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenFalse: {
Value v(false);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenNull: {
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenArraySeparator:
case tokenObjectEnd:
case tokenArrayEnd:
if (features_.allowDroppedNullPlaceholders_) {
// "Un-read" the current token and mark the current value as a null
// token.
current_--;
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(current_ - begin_ - 1);
currentValue().setOffsetLimit(current_ - begin_);
break;
} // Else, fall through...
default:
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return addError("Syntax error: value, object or array expected.", token);
}
if (collectComments_) {
lastValueEnd_ = current_;
lastValue_ = ¤tValue();
}
return successful;
}
void Reader::skipCommentTokens(Token& token) {
if (features_.allowComments_) {
do {
readToken(token);
} while (token.type_ == tokenComment);
} else {
readToken(token);
}
}
bool Reader::readToken(Token& token) {
skipSpaces();
token.start_ = current_;
Char c = getNextChar();
bool ok = true;
switch (c) {
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString();
break;
case '/':
token.type_ = tokenComment;
ok = readComment();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
token.type_ = tokenNumber;
readNumber();
break;
case 't':
token.type_ = tokenTrue;
ok = match("rue", 3);
break;
case 'f':
token.type_ = tokenFalse;
ok = match("alse", 4);
break;
case 'n':
token.type_ = tokenNull;
ok = match("ull", 3);
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if (!ok)
token.type_ = tokenError;
token.end_ = current_;
return ok;
}
void Reader::skipSpaces() {
while (current_ != end_) {
Char c = *current_;
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++current_;
else
break;
}
}
bool Reader::match(const Char* pattern, int patternLength) {
if (end_ - current_ < patternLength)
return false;
int index = patternLength;
while (index--)
if (current_[index] != pattern[index])
return false;
current_ += patternLength;
return true;
}
bool Reader::readComment() {
Location commentBegin = current_ - 1;
Char c = getNextChar();
bool successful = false;
if (c == '*')
successful = readCStyleComment();
else if (c == '/')
successful = readCppStyleComment();
if (!successful)
return false;
if (collectComments_) {
CommentPlacement placement = commentBefore;
if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
if (c != '*' || !containsNewLine(commentBegin, current_))
placement = commentAfterOnSameLine;
}
addComment(commentBegin, current_, placement);
}
return true;
}
String Reader::normalizeEOL(Reader::Location begin, Reader::Location end) {
String normalized;
normalized.reserve(static_cast<size_t>(end - begin));
Reader::Location current = begin;
while (current != end) {
char c = *current++;
if (c == '\r') {
if (current != end && *current == '\n')
// convert dos EOL
++current;
// convert Mac EOL
normalized += '\n';
} else {
normalized += c;
}
}
return normalized;
}
void Reader::addComment(Location begin, Location end,
CommentPlacement placement) {
assert(collectComments_);
const String& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
assert(lastValue_ != nullptr);
lastValue_->setComment(normalized, placement);
} else {
commentsBefore_ += normalized;
}
}
bool Reader::readCStyleComment() {
while ((current_ + 1) < end_) {
Char c = getNextChar();
if (c == '*' && *current_ == '/')
break;
}
return getNextChar() == '/';
}
bool Reader::readCppStyleComment() {
while (current_ != end_) {
Char c = getNextChar();
if (c == '\n')
break;
if (c == '\r') {
// Consume DOS EOL. It will be normalized in addComment.
if (current_ != end_ && *current_ == '\n')
getNextChar();
// Break on Moc OS 9 EOL.
break;
}
}
return true;
}
void Reader::readNumber() {
Location p = current_;
char c = '0'; // stopgap for already consumed character
// integral part
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
// fractional part
if (c == '.') {
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
}
// exponential part
if (c == 'e' || c == 'E') {
c = (current_ = p) < end_ ? *p++ : '\0';
if (c == '+' || c == '-')
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
}
}
bool Reader::readString() {
Char c = '\0';
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
getNextChar();
else if (c == '"')
break;
}
return c == '"';
}
bool Reader::readObject(Token& token) {
Token tokenName;
String name;
Value init(objectValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(token.start_ - begin_);
while (readToken(tokenName)) {
bool initialTokenOk = true;
while (tokenName.type_ == tokenComment && initialTokenOk)
initialTokenOk = readToken(tokenName);
if (!initialTokenOk)
break;
if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
return true;
name.clear();
if (tokenName.type_ == tokenString) {
if (!decodeString(tokenName, name))
return recoverFromError(tokenObjectEnd);
} else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
Value numberName;
if (!decodeNumber(tokenName, numberName))
return recoverFromError(tokenObjectEnd);
name = numberName.asString();
} else {
break;
}
Token colon;
if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
return addErrorAndRecover("Missing ':' after object member name", colon,
tokenObjectEnd);
}
Value& value = currentValue()[name];
nodes_.push(&value);
bool ok = readValue();
nodes_.pop();
if (!ok) // error already set
return recoverFromError(tokenObjectEnd);
Token comma;
if (!readToken(comma) ||
(comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment)) {
return addErrorAndRecover("Missing ',' or '}' in object declaration",
comma, tokenObjectEnd);
}
bool finalizeTokenOk = true;
while (comma.type_ == tokenComment && finalizeTokenOk)
finalizeTokenOk = readToken(comma);
if (comma.type_ == tokenObjectEnd)
return true;
}
return addErrorAndRecover("Missing '}' or object member name", tokenName,
tokenObjectEnd);
}
bool Reader::readArray(Token& token) {
Value init(arrayValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(token.start_ - begin_);
skipSpaces();
if (current_ != end_ && *current_ == ']') // empty array
{
Token endArray;
readToken(endArray);
return true;
}
int index = 0;
for (;;) {
Value& value = currentValue()[index++];
nodes_.push(&value);
bool ok = readValue();
nodes_.pop();
if (!ok) // error already set
return recoverFromError(tokenArrayEnd);
Token currentToken;
// Accept Comment after last item in the array.
ok = readToken(currentToken);
while (currentToken.type_ == tokenComment && ok) {
ok = readToken(currentToken);
}
bool badTokenType = (currentToken.type_ != tokenArraySeparator &&
currentToken.type_ != tokenArrayEnd);
if (!ok || badTokenType) {
return addErrorAndRecover("Missing ',' or ']' in array declaration",
currentToken, tokenArrayEnd);
}
if (currentToken.type_ == tokenArrayEnd)
break;
}
return true;
}
bool Reader::decodeNumber(Token& token) {
Value decoded;
if (!decodeNumber(token, decoded))
return false;
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool Reader::decodeNumber(Token& token, Value& decoded) {
// Attempts to parse the number as an integer. If the number is
// larger than the maximum supported value of an integer then
// we decode the number as a double.
Location current = token.start_;
bool isNegative = *current == '-';
if (isNegative)
++current;
// TODO: Help the compiler do the div and mod at compile time or get rid of
// them.
Value::LargestUInt maxIntegerValue =
isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1
: Value::maxLargestUInt;
Value::LargestUInt threshold = maxIntegerValue / 10;
Value::LargestUInt value = 0;
while (current < token.end_) {
Char c = *current++;
if (c < '0' || c > '9')
return decodeDouble(token, decoded);
auto digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
// a) we've only just touched the limit, b) this is the last digit, and
// c) it's small enough to fit in that rounding delta, we're okay.
// Otherwise treat this number as a double to avoid overflow.
if (value > threshold || current != token.end_ ||
digit > maxIntegerValue % 10) {
return decodeDouble(token, decoded);
}
}
value = value * 10 + digit;
}
if (isNegative && value == maxIntegerValue)
decoded = Value::minLargestInt;
else if (isNegative)
decoded = -Value::LargestInt(value);
else if (value <= Value::LargestUInt(Value::maxInt))
decoded = Value::LargestInt(value);
else
decoded = value;
return true;
}
bool Reader::decodeDouble(Token& token) {
Value decoded;
if (!decodeDouble(token, decoded))
return false;
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool Reader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
String buffer(token.start_, token.end_);
IStringStream is(buffer);
if (!(is >> value))
return addError(
"'" + String(token.start_, token.end_) + "' is not a number.", token);
decoded = value;
return true;
}
bool Reader::decodeString(Token& token) {
String decoded_string;
if (!decodeString(token, decoded_string))
return false;
Value decoded(decoded_string);
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool Reader::decodeString(Token& token, String& decoded) {
decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while (current != end) {
Char c = *current++;
if (c == '"')
break;
if (c == '\\') {
if (current == end)
return addError("Empty escape sequence in string", token, current);
Char escape = *current++;
switch (escape) {
case '"':
decoded += '"';
break;
case '/':
decoded += '/';
break;
case '\\':
decoded += '\\';
break;
case 'b':
decoded += '\b';
break;
case 'f':
decoded += '\f';
break;
case 'n':
decoded += '\n';
break;
case 'r':
decoded += '\r';
break;
case 't':
decoded += '\t';
break;
case 'u': {
unsigned int unicode;
if (!decodeUnicodeCodePoint(token, current, end, unicode))
return false;
decoded += codePointToUTF8(unicode);
} break;
default:
return addError("Bad escape sequence in string", token, current);
}
} else {
decoded += c;
}
}
return true;
}
bool Reader::decodeUnicodeCodePoint(Token& token, Location& current,
Location end, unsigned int& unicode) {
if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF) {
// surrogate pairs
if (end - current < 6)
return addError(
"additional six characters expected to parse unicode surrogate pair.",
token, current);
if (*(current++) == '\\' && *(current++) == 'u') {
unsigned int surrogatePair;
if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
} else
return false;
} else
return addError("expecting another \\u token to begin the second half of "
"a unicode surrogate pair",
token, current);
}
return true;
}
bool Reader::decodeUnicodeEscapeSequence(Token& token, Location& current,
Location end,
unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
"Bad unicode escape sequence in string: four digits expected.", token,
current);
int unicode = 0;
for (int index = 0; index < 4; ++index) {
Char c = *current++;
unicode *= 16;
if (c >= '0' && c <= '9')
unicode += c - '0';
else if (c >= 'a' && c <= 'f')
unicode += c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
unicode += c - 'A' + 10;
else
return addError(
"Bad unicode escape sequence in string: hexadecimal digit expected.",
token, current);
}
ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
bool Reader::addError(const String& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back(info);
return false;
}
bool Reader::recoverFromError(TokenType skipUntilToken) {
size_t const errorCount = errors_.size();
Token skip;
for (;;) {
if (!readToken(skip))
errors_.resize(errorCount); // discard errors caused by recovery
if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
break;
}
errors_.resize(errorCount);
return false;
}
bool Reader::addErrorAndRecover(const String& message, Token& token,
TokenType skipUntilToken) {
addError(message, token);
return recoverFromError(skipUntilToken);
}
Value& Reader::currentValue() { return *(nodes_.top()); }
Reader::Char Reader::getNextChar() {
if (current_ == end_)
return 0;
return *current_++;
}
void Reader::getLocationLineAndColumn(Location location, int& line,
int& column) const {
Location current = begin_;
Location lastLineStart = current;
line = 0;
while (current < location && current != end_) {
Char c = *current++;
if (c == '\r') {
if (*current == '\n')
++current;
lastLineStart = current;
++line;
} else if (c == '\n') {
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int(location - lastLineStart) + 1;
++line;
}
String Reader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
jsoncpp_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
return buffer;
}
// Deprecated. Preserved for backward compatibility
String Reader::getFormatedErrorMessages() const {
return getFormattedErrorMessages();
}
String Reader::getFormattedErrorMessages() const {
String formattedMessage;
for (const auto& error : errors_) {
formattedMessage +=
"* " + getLocationLineAndColumn(error.token_.start_) + "\n";
formattedMessage += " " + error.message_ + "\n";
if (error.extra_)
formattedMessage +=
"See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
}
return formattedMessage;
}
std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
std::vector<Reader::StructuredError> allErrors;
for (const auto& error : errors_) {
Reader::StructuredError structured;
structured.offset_start = error.token_.start_ - begin_;
structured.offset_limit = error.token_.end_ - begin_;
structured.message = error.message_;
allErrors.push_back(structured);
}
return allErrors;
}
bool Reader::pushError(const Value& value, const String& message) {
ptrdiff_t const length = end_ - begin_;
if (value.getOffsetStart() > length || value.getOffsetLimit() > length)
return false;
Token token;
token.type_ = tokenError;
token.start_ = begin_ + value.getOffsetStart();
token.end_ = begin_ + value.getOffsetLimit();
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = nullptr;
errors_.push_back(info);
return true;
}
bool Reader::pushError(const Value& value, const String& message,
const Value& extra) {
ptrdiff_t const length = end_ - begin_;
if (value.getOffsetStart() > length || value.getOffsetLimit() > length ||
extra.getOffsetLimit() > length)
return false;
Token token;
token.type_ = tokenError;
token.start_ = begin_ + value.getOffsetStart();
token.end_ = begin_ + value.getOffsetLimit();
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = begin_ + extra.getOffsetStart();
errors_.push_back(info);
return true;
}
bool Reader::good() const { return errors_.empty(); }
// Originally copied from the Features class (now deprecated), used internally
// for features implementation.
class OurFeatures {
public:
static OurFeatures all();
bool allowComments_;
bool allowTrailingCommas_;
bool strictRoot_;
bool allowDroppedNullPlaceholders_;
bool allowNumericKeys_;
bool allowSingleQuotes_;
bool failIfExtra_;
bool rejectDupKeys_;
bool allowSpecialFloats_;
bool skipBom_;
size_t stackLimit_;
}; // OurFeatures
OurFeatures OurFeatures::all() { return {}; }
// Implementation of class Reader
// ////////////////////////////////
// Originally copied from the Reader class (now deprecated), used internally
// for implementing JSON reading.
class OurReader {
public:
using Char = char;
using Location = const Char*;
struct StructuredError {
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
String message;
};
explicit OurReader(OurFeatures const& features);
bool parse(const char* beginDoc, const char* endDoc, Value& root,
bool collectComments = true);
String getFormattedErrorMessages() const;
std::vector<StructuredError> getStructuredErrors() const;
private:
OurReader(OurReader const&); // no impl
void operator=(OurReader const&); // no impl
enum TokenType {
tokenEndOfStream = 0,
tokenObjectBegin,
tokenObjectEnd,
tokenArrayBegin,
tokenArrayEnd,
tokenString,
tokenNumber,
tokenTrue,
tokenFalse,
tokenNull,
tokenNaN,
tokenPosInf,
tokenNegInf,
tokenArraySeparator,
tokenMemberSeparator,
tokenComment,
tokenError
};
class Token {
public:
TokenType type_;
Location start_;
Location end_;
};
class ErrorInfo {
public:
Token token_;
String message_;
Location extra_;
};
using Errors = std::deque<ErrorInfo>;
bool readToken(Token& token);
void skipSpaces();
void skipBom(bool skipBom);
bool match(const Char* pattern, int patternLength);
bool readComment();
bool readCStyleComment(bool* containsNewLineResult);
bool readCppStyleComment();
bool readString();
bool readStringSingleQuote();
bool readNumber(bool checkInf);
bool readValue();
bool readObject(Token& token);
bool readArray(Token& token);
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
bool decodeString(Token& token, String& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
bool decodeUnicodeCodePoint(Token& token, Location& current, Location end,
unsigned int& unicode);
bool decodeUnicodeEscapeSequence(Token& token, Location& current,
Location end, unsigned int& unicode);
bool addError(const String& message, Token& token, Location extra = nullptr);
bool recoverFromError(TokenType skipUntilToken);
bool addErrorAndRecover(const String& message, Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
Value& currentValue();
Char getNextChar();
void getLocationLineAndColumn(Location location, int& line,
int& column) const;
String getLocationLineAndColumn(Location location) const;
void addComment(Location begin, Location end, CommentPlacement placement);
void skipCommentTokens(Token& token);
static String normalizeEOL(Location begin, Location end);
static bool containsNewLine(Location begin, Location end);
using Nodes = std::stack<Value*>;
Nodes nodes_{};
Errors errors_{};
String document_{};
Location begin_ = nullptr;
Location end_ = nullptr;
Location current_ = nullptr;
Location lastValueEnd_ = nullptr;
Value* lastValue_ = nullptr;
bool lastValueHasAComment_ = false;
String commentsBefore_{};
OurFeatures const features_;
bool collectComments_ = false;
}; // OurReader
// complete copy of Read impl, for OurReader
bool OurReader::containsNewLine(OurReader::Location begin,
OurReader::Location end) {
return std::any_of(begin, end, [](char b) { return b == '\n' || b == '\r'; });
}
OurReader::OurReader(OurFeatures const& features) : features_(features) {}
bool OurReader::parse(const char* beginDoc, const char* endDoc, Value& root,
bool collectComments) {
if (!features_.allowComments_) {
collectComments = false;
}
begin_ = beginDoc;
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
lastValueEnd_ = nullptr;
lastValue_ = nullptr;
commentsBefore_.clear();
errors_.clear();
while (!nodes_.empty())
nodes_.pop();
nodes_.push(&root);
// skip byte order mark if it exists at the beginning of the UTF-8 text.
skipBom(features_.skipBom_);
bool successful = readValue();
nodes_.pop();
Token token;
skipCommentTokens(token);
if (features_.failIfExtra_ && (token.type_ != tokenEndOfStream)) {
addError("Extra non-whitespace after JSON value.", token);
return false;
}
if (collectComments_ && !commentsBefore_.empty())
root.setComment(commentsBefore_, commentAfter);
if (features_.strictRoot_) {
if (!root.isArray() && !root.isObject()) {
// Set error location to start of doc, ideally should be first token found
// in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError(
"A valid JSON document must be either an array or an object value.",
token);
return false;
}
}
return successful;
}
bool OurReader::readValue() {
// To preserve the old behaviour we cast size_t to int.
if (nodes_.size() > features_.stackLimit_)
throwRuntimeError("Exceeded stackLimit in readValue().");
Token token;
skipCommentTokens(token);
bool successful = true;
if (collectComments_ && !commentsBefore_.empty()) {
currentValue().setComment(commentsBefore_, commentBefore);
commentsBefore_.clear();
}
switch (token.type_) {
case tokenObjectBegin:
successful = readObject(token);
currentValue().setOffsetLimit(current_ - begin_);
break;
case tokenArrayBegin:
successful = readArray(token);
currentValue().setOffsetLimit(current_ - begin_);
break;
case tokenNumber:
successful = decodeNumber(token);
break;
case tokenString:
successful = decodeString(token);
break;
case tokenTrue: {
Value v(true);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenFalse: {
Value v(false);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenNull: {
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenNaN: {
Value v(std::numeric_limits<double>::quiet_NaN());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenPosInf: {
Value v(std::numeric_limits<double>::infinity());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenNegInf: {
Value v(-std::numeric_limits<double>::infinity());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
} break;
case tokenArraySeparator:
case tokenObjectEnd:
case tokenArrayEnd:
if (features_.allowDroppedNullPlaceholders_) {
// "Un-read" the current token and mark the current value as a null
// token.
current_--;
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(current_ - begin_ - 1);
currentValue().setOffsetLimit(current_ - begin_);
break;
} // else, fall through ...
default:
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return addError("Syntax error: value, object or array expected.", token);
}
if (collectComments_) {
lastValueEnd_ = current_;
lastValueHasAComment_ = false;
lastValue_ = ¤tValue();
}
return successful;
}
void OurReader::skipCommentTokens(Token& token) {
if (features_.allowComments_) {
do {
readToken(token);
} while (token.type_ == tokenComment);
} else {
readToken(token);
}
}
bool OurReader::readToken(Token& token) {
skipSpaces();
token.start_ = current_;
Char c = getNextChar();
bool ok = true;
switch (c) {
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString();
break;
case '\'':
if (features_.allowSingleQuotes_) {
token.type_ = tokenString;
ok = readStringSingleQuote();
} else {
// If we don't allow single quotes, this is a failure case.
ok = false;
}
break;
case '/':
token.type_ = tokenComment;
ok = readComment();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
token.type_ = tokenNumber;
readNumber(false);
break;
case '-':
if (readNumber(true)) {
token.type_ = tokenNumber;
} else {
token.type_ = tokenNegInf;
ok = features_.allowSpecialFloats_ && match("nfinity", 7);
}
break;
case '+':
if (readNumber(true)) {
token.type_ = tokenNumber;
} else {
token.type_ = tokenPosInf;
ok = features_.allowSpecialFloats_ && match("nfinity", 7);
}
break;
case 't':
token.type_ = tokenTrue;
ok = match("rue", 3);
break;
case 'f':
token.type_ = tokenFalse;
ok = match("alse", 4);
break;
case 'n':
token.type_ = tokenNull;
ok = match("ull", 3);
break;
case 'N':
if (features_.allowSpecialFloats_) {
token.type_ = tokenNaN;
ok = match("aN", 2);
} else {
ok = false;
}
break;
case 'I':
if (features_.allowSpecialFloats_) {
token.type_ = tokenPosInf;
ok = match("nfinity", 7);
} else {
ok = false;
}
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if (!ok)
token.type_ = tokenError;
token.end_ = current_;
return ok;
}
void OurReader::skipSpaces() {
while (current_ != end_) {
Char c = *current_;
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++current_;
else
break;
}
}
void OurReader::skipBom(bool skipBom) {
// The default behavior is to skip BOM.
if (skipBom) {
if ((end_ - begin_) >= 3 && strncmp(begin_, "\xEF\xBB\xBF", 3) == 0) {
begin_ += 3;
current_ = begin_;
}
}
}
bool OurReader::match(const Char* pattern, int patternLength) {
if (end_ - current_ < patternLength)
return false;
int index = patternLength;
while (index--)
if (current_[index] != pattern[index])
return false;
current_ += patternLength;
return true;
}
bool OurReader::readComment() {
const Location commentBegin = current_ - 1;
const Char c = getNextChar();
bool successful = false;
bool cStyleWithEmbeddedNewline = false;
const bool isCStyleComment = (c == '*');
const bool isCppStyleComment = (c == '/');
if (isCStyleComment) {
successful = readCStyleComment(&cStyleWithEmbeddedNewline);
} else if (isCppStyleComment) {
successful = readCppStyleComment();
}
if (!successful)
return false;
if (collectComments_) {
CommentPlacement placement = commentBefore;
if (!lastValueHasAComment_) {
if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
if (isCppStyleComment || !cStyleWithEmbeddedNewline) {
placement = commentAfterOnSameLine;
lastValueHasAComment_ = true;
}
}
}
addComment(commentBegin, current_, placement);
}
return true;
}
String OurReader::normalizeEOL(OurReader::Location begin,
OurReader::Location end) {
String normalized;
normalized.reserve(static_cast<size_t>(end - begin));
OurReader::Location current = begin;
while (current != end) {
char c = *current++;
if (c == '\r') {
if (current != end && *current == '\n')
// convert dos EOL
++current;
// convert Mac EOL
normalized += '\n';
} else {
normalized += c;
}
}
return normalized;
}
void OurReader::addComment(Location begin, Location end,
CommentPlacement placement) {
assert(collectComments_);
const String& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
assert(lastValue_ != nullptr);
lastValue_->setComment(normalized, placement);
} else {
commentsBefore_ += normalized;
}
}
bool OurReader::readCStyleComment(bool* containsNewLineResult) {
*containsNewLineResult = false;
while ((current_ + 1) < end_) {
Char c = getNextChar();
if (c == '*' && *current_ == '/')
break;
if (c == '\n')
*containsNewLineResult = true;
}
return getNextChar() == '/';
}
bool OurReader::readCppStyleComment() {
while (current_ != end_) {
Char c = getNextChar();
if (c == '\n')
break;
if (c == '\r') {
// Consume DOS EOL. It will be normalized in addComment.
if (current_ != end_ && *current_ == '\n')
getNextChar();
// Break on Moc OS 9 EOL.
break;
}
}
return true;
}
bool OurReader::readNumber(bool checkInf) {
Location p = current_;
if (checkInf && p != end_ && *p == 'I') {
current_ = ++p;
return false;
}
char c = '0'; // stopgap for already consumed character
// integral part
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
// fractional part
if (c == '.') {
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
}
// exponential part
if (c == 'e' || c == 'E') {
c = (current_ = p) < end_ ? *p++ : '\0';
if (c == '+' || c == '-')
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
}
return true;
}
bool OurReader::readString() {
Char c = 0;
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
getNextChar();
else if (c == '"')
break;
}
return c == '"';
}
bool OurReader::readStringSingleQuote() {
Char c = 0;
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
getNextChar();
else if (c == '\'')
break;
}
return c == '\'';
}
bool OurReader::readObject(Token& token) {
Token tokenName;
String name;
Value init(objectValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(token.start_ - begin_);
while (readToken(tokenName)) {
bool initialTokenOk = true;
while (tokenName.type_ == tokenComment && initialTokenOk)
initialTokenOk = readToken(tokenName);
if (!initialTokenOk)
break;
if (tokenName.type_ == tokenObjectEnd &&
(name.empty() ||
features_.allowTrailingCommas_)) // empty object or trailing comma
return true;
name.clear();
if (tokenName.type_ == tokenString) {
if (!decodeString(tokenName, name))
return recoverFromError(tokenObjectEnd);
} else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
Value numberName;
if (!decodeNumber(tokenName, numberName))
return recoverFromError(tokenObjectEnd);
name = numberName.asString();
} else {
break;
}
if (name.length() >= (1U << 30))
throwRuntimeError("keylength >= 2^30");
if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
String msg = "Duplicate key: '" + name + "'";
return addErrorAndRecover(msg, tokenName, tokenObjectEnd);
}
Token colon;
if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
return addErrorAndRecover("Missing ':' after object member name", colon,
tokenObjectEnd);
}
Value& value = currentValue()[name];
nodes_.push(&value);
bool ok = readValue();
nodes_.pop();
if (!ok) // error already set
return recoverFromError(tokenObjectEnd);
Token comma;
if (!readToken(comma) ||
(comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment)) {
return addErrorAndRecover("Missing ',' or '}' in object declaration",
comma, tokenObjectEnd);
}
bool finalizeTokenOk = true;
while (comma.type_ == tokenComment && finalizeTokenOk)
finalizeTokenOk = readToken(comma);
if (comma.type_ == tokenObjectEnd)
return true;
}
return addErrorAndRecover("Missing '}' or object member name", tokenName,
tokenObjectEnd);
}
bool OurReader::readArray(Token& token) {
Value init(arrayValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(token.start_ - begin_);
int index = 0;
for (;;) {
skipSpaces();
if (current_ != end_ && *current_ == ']' &&
(index == 0 ||
(features_.allowTrailingCommas_ &&
!features_.allowDroppedNullPlaceholders_))) // empty array or trailing
// comma
{
Token endArray;
readToken(endArray);
return true;
}
Value& value = currentValue()[index++];
nodes_.push(&value);
bool ok = readValue();
nodes_.pop();
if (!ok) // error already set
return recoverFromError(tokenArrayEnd);
Token currentToken;
// Accept Comment after last item in the array.
ok = readToken(currentToken);
while (currentToken.type_ == tokenComment && ok) {
ok = readToken(currentToken);
}
bool badTokenType = (currentToken.type_ != tokenArraySeparator &&
currentToken.type_ != tokenArrayEnd);
if (!ok || badTokenType) {
return addErrorAndRecover("Missing ',' or ']' in array declaration",
currentToken, tokenArrayEnd);
}
if (currentToken.type_ == tokenArrayEnd)
break;
}
return true;
}
bool OurReader::decodeNumber(Token& token) {
Value decoded;
if (!decodeNumber(token, decoded))
return false;
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool OurReader::decodeNumber(Token& token, Value& decoded) {
// Attempts to parse the number as an integer. If the number is
// larger than the maximum supported value of an integer then
// we decode the number as a double.
Location current = token.start_;
const bool isNegative = *current == '-';
if (isNegative) {
++current;
}
// We assume we can represent the largest and smallest integer types as
// unsigned integers with separate sign. This is only true if they can fit
// into an unsigned integer.
static_assert(Value::maxLargestInt <= Value::maxLargestUInt,
"Int must be smaller than UInt");
// We need to convert minLargestInt into a positive number. The easiest way
// to do this conversion is to assume our "threshold" value of minLargestInt
// divided by 10 can fit in maxLargestInt when absolute valued. This should
// be a safe assumption.
static_assert(Value::minLargestInt <= -Value::maxLargestInt,
"The absolute value of minLargestInt must be greater than or "
"equal to maxLargestInt");
static_assert(Value::minLargestInt / 10 >= -Value::maxLargestInt,
"The absolute value of minLargestInt must be only 1 magnitude "
"larger than maxLargest Int");
static constexpr Value::LargestUInt positive_threshold =
Value::maxLargestUInt / 10;
static constexpr Value::UInt positive_last_digit = Value::maxLargestUInt % 10;
// For the negative values, we have to be more careful. Since typically
// -Value::minLargestInt will cause an overflow, we first divide by 10 and
// then take the inverse. This assumes that minLargestInt is only a single
// power of 10 different in magnitude, which we check above. For the last
// digit, we take the modulus before negating for the same reason.
static constexpr auto negative_threshold =
Value::LargestUInt(-(Value::minLargestInt / 10));
static constexpr auto negative_last_digit =
Value::UInt(-(Value::minLargestInt % 10));
const Value::LargestUInt threshold =
isNegative ? negative_threshold : positive_threshold;
const Value::UInt max_last_digit =
isNegative ? negative_last_digit : positive_last_digit;
Value::LargestUInt value = 0;
while (current < token.end_) {
Char c = *current++;
if (c < '0' || c > '9')
return decodeDouble(token, decoded);
const auto digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
// a) we've only just touched the limit, meaing value == threshold,
// b) this is the last digit, or
// c) it's small enough to fit in that rounding delta, we're okay.
// Otherwise treat this number as a double to avoid overflow.
if (value > threshold || current != token.end_ ||
digit > max_last_digit) {
return decodeDouble(token, decoded);
}
}
value = value * 10 + digit;
}
if (isNegative) {
// We use the same magnitude assumption here, just in case.
const auto last_digit = static_cast<Value::UInt>(value % 10);
decoded = -Value::LargestInt(value / 10) * 10 - last_digit;
} else if (value <= Value::LargestUInt(Value::maxLargestInt)) {
decoded = Value::LargestInt(value);
} else {
decoded = value;
}
return true;
}
bool OurReader::decodeDouble(Token& token) {
Value decoded;
if (!decodeDouble(token, decoded))
return false;
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool OurReader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
const String buffer(token.start_, token.end_);
IStringStream is(buffer);
if (!(is >> value)) {
return addError(
"'" + String(token.start_, token.end_) + "' is not a number.", token);
}
decoded = value;
return true;
}
bool OurReader::decodeString(Token& token) {
String decoded_string;
if (!decodeString(token, decoded_string))
return false;
Value decoded(decoded_string);
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool OurReader::decodeString(Token& token, String& decoded) {
decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while (current != end) {
Char c = *current++;
if (c == '"')
break;
if (c == '\\') {
if (current == end)
return addError("Empty escape sequence in string", token, current);
Char escape = *current++;
switch (escape) {
case '"':
decoded += '"';
break;
case '/':
decoded += '/';
break;
case '\\':
decoded += '\\';
break;
case 'b':
decoded += '\b';
break;
case 'f':
decoded += '\f';
break;
case 'n':
decoded += '\n';
break;
case 'r':
decoded += '\r';
break;
case 't':
decoded += '\t';
break;
case 'u': {
unsigned int unicode;
if (!decodeUnicodeCodePoint(token, current, end, unicode))
return false;
decoded += codePointToUTF8(unicode);
} break;
default:
return addError("Bad escape sequence in string", token, current);
}
} else {
decoded += c;
}
}
return true;
}
bool OurReader::decodeUnicodeCodePoint(Token& token, Location& current,
Location end, unsigned int& unicode) {
if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF) {
// surrogate pairs
if (end - current < 6)
return addError(
"additional six characters expected to parse unicode surrogate pair.",
token, current);
if (*(current++) == '\\' && *(current++) == 'u') {
unsigned int surrogatePair;
if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
} else
return false;
} else
return addError("expecting another \\u token to begin the second half of "
"a unicode surrogate pair",
token, current);
}
return true;
}
bool OurReader::decodeUnicodeEscapeSequence(Token& token, Location& current,
Location end,
unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
"Bad unicode escape sequence in string: four digits expected.", token,
current);
int unicode = 0;
for (int index = 0; index < 4; ++index) {
Char c = *current++;
unicode *= 16;
if (c >= '0' && c <= '9')
unicode += c - '0';
else if (c >= 'a' && c <= 'f')
unicode += c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
unicode += c - 'A' + 10;
else
return addError(
"Bad unicode escape sequence in string: hexadecimal digit expected.",
token, current);
}
ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
bool OurReader::addError(const String& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back(info);
return false;
}
bool OurReader::recoverFromError(TokenType skipUntilToken) {
size_t errorCount = errors_.size();
Token skip;
for (;;) {
if (!readToken(skip))
errors_.resize(errorCount); // discard errors caused by recovery
if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
break;
}
errors_.resize(errorCount);
return false;
}
bool OurReader::addErrorAndRecover(const String& message, Token& token,
TokenType skipUntilToken) {
addError(message, token);
return recoverFromError(skipUntilToken);
}
Value& OurReader::currentValue() { return *(nodes_.top()); }
OurReader::Char OurReader::getNextChar() {
if (current_ == end_)
return 0;
return *current_++;
}
void OurReader::getLocationLineAndColumn(Location location, int& line,
int& column) const {
Location current = begin_;
Location lastLineStart = current;
line = 0;
while (current < location && current != end_) {
Char c = *current++;
if (c == '\r') {
if (*current == '\n')
++current;
lastLineStart = current;
++line;
} else if (c == '\n') {
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int(location - lastLineStart) + 1;
++line;
}
String OurReader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
jsoncpp_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
return buffer;
}
String OurReader::getFormattedErrorMessages() const {
String formattedMessage;
for (const auto& error : errors_) {
formattedMessage +=
"* " + getLocationLineAndColumn(error.token_.start_) + "\n";
formattedMessage += " " + error.message_ + "\n";
if (error.extra_)
formattedMessage +=
"See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
}
return formattedMessage;
}
std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const {
std::vector<OurReader::StructuredError> allErrors;
for (const auto& error : errors_) {
OurReader::StructuredError structured;
structured.offset_start = error.token_.start_ - begin_;
structured.offset_limit = error.token_.end_ - begin_;
structured.message = error.message_;
allErrors.push_back(structured);
}
return allErrors;
}
class OurCharReader : public CharReader {
bool const collectComments_;
OurReader reader_;
public:
OurCharReader(bool collectComments, OurFeatures const& features)
: collectComments_(collectComments), reader_(features) {}
bool parse(char const* beginDoc, char const* endDoc, Value* root,
String* errs) override {
bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
if (errs) {
*errs = reader_.getFormattedErrorMessages();
}
return ok;
}
};
CharReaderBuilder::CharReaderBuilder() { setDefaults(&settings_); }
CharReaderBuilder::~CharReaderBuilder() = default;
CharReader* CharReaderBuilder::newCharReader() const {
bool collectComments = settings_["collectComments"].asBool();
OurFeatures features = OurFeatures::all();
features.allowComments_ = settings_["allowComments"].asBool();
features.allowTrailingCommas_ = settings_["allowTrailingCommas"].asBool();
features.strictRoot_ = settings_["strictRoot"].asBool();
features.allowDroppedNullPlaceholders_ =
settings_["allowDroppedNullPlaceholders"].asBool();
features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
// Stack limit is always a size_t, so we get this as an unsigned int
// regardless of it we have 64-bit integer support enabled.
features.stackLimit_ = static_cast<size_t>(settings_["stackLimit"].asUInt());
features.failIfExtra_ = settings_["failIfExtra"].asBool();
features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool();
features.skipBom_ = settings_["skipBom"].asBool();
return new OurCharReader(collectComments, features);
}
bool CharReaderBuilder::validate(Json::Value* invalid) const {
static const auto& valid_keys = *new std::set<String>{
"collectComments",
"allowComments",
"allowTrailingCommas",
"strictRoot",
"allowDroppedNullPlaceholders",
"allowNumericKeys",
"allowSingleQuotes",
"stackLimit",
"failIfExtra",
"rejectDupKeys",
"allowSpecialFloats",
"skipBom",
};
for (auto si = settings_.begin(); si != settings_.end(); ++si) {
auto key = si.name();
if (valid_keys.count(key))
continue;
if (invalid)
(*invalid)[key] = *si;
else
return false;
}
return invalid ? invalid->empty() : true;
}
Value& CharReaderBuilder::operator[](const String& key) {
return settings_[key];
}
// static
void CharReaderBuilder::strictMode(Json::Value* settings) {
//! [CharReaderBuilderStrictMode]
(*settings)["allowComments"] = false;
(*settings)["allowTrailingCommas"] = false;
(*settings)["strictRoot"] = true;
(*settings)["allowDroppedNullPlaceholders"] = false;
(*settings)["allowNumericKeys"] = false;
(*settings)["allowSingleQuotes"] = false;
(*settings)["stackLimit"] = 1000;
(*settings)["failIfExtra"] = true;
(*settings)["rejectDupKeys"] = true;
(*settings)["allowSpecialFloats"] = false;
(*settings)["skipBom"] = true;
//! [CharReaderBuilderStrictMode]
}
// static
void CharReaderBuilder::setDefaults(Json::Value* settings) {
//! [CharReaderBuilderDefaults]
(*settings)["collectComments"] = true;
(*settings)["allowComments"] = true;
(*settings)["allowTrailingCommas"] = true;
(*settings)["strictRoot"] = false;
(*settings)["allowDroppedNullPlaceholders"] = false;
(*settings)["allowNumericKeys"] = false;
(*settings)["allowSingleQuotes"] = false;
(*settings)["stackLimit"] = 1000;
(*settings)["failIfExtra"] = false;
(*settings)["rejectDupKeys"] = false;
(*settings)["allowSpecialFloats"] = false;
(*settings)["skipBom"] = true;
//! [CharReaderBuilderDefaults]
}
//////////////////////////////////
// global functions
bool parseFromStream(CharReader::Factory const& fact, IStream& sin, Value* root,
String* errs) {
OStringStream ssin;
ssin << sin.rdbuf();
String doc = ssin.str();
char const* begin = doc.data();
char const* end = begin + doc.size();
// Note that we do not actually need a null-terminator.
CharReaderPtr const reader(fact.newCharReader());
return reader->parse(begin, end, root, errs);
}
IStream& operator>>(IStream& sin, Value& root) {
CharReaderBuilder b;
String errs;
bool ok = parseFromStream(b, sin, &root, &errs);
if (!ok) {
throwRuntimeError(errs);
}
return sin;
}
} // namespace Json
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_reader.cpp
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_valueiterator.inl
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
// included by json_value.cpp
namespace Json {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueIteratorBase
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueIteratorBase::ValueIteratorBase() : current_() {}
ValueIteratorBase::ValueIteratorBase(
const Value::ObjectValues::iterator& current)
: current_(current), isNull_(false) {}
Value& ValueIteratorBase::deref() { return current_->second; }
const Value& ValueIteratorBase::deref() const { return current_->second; }
void ValueIteratorBase::increment() { ++current_; }
void ValueIteratorBase::decrement() { --current_; }
ValueIteratorBase::difference_type
ValueIteratorBase::computeDistance(const SelfType& other) const {
// Iterator for null value are initialized using the default
// constructor, which initialize current_ to the default
// std::map::iterator. As begin() and end() are two instance
// of the default std::map::iterator, they can not be compared.
// To allow this, we handle this comparison specifically.
if (isNull_ && other.isNull_) {
return 0;
}
// Usage of std::distance is not portable (does not compile with Sun Studio 12
// RogueWave STL,
// which is the one used by default).
// Using a portable hand-made version for non random iterator instead:
// return difference_type( std::distance( current_, other.current_ ) );
difference_type myDistance = 0;
for (Value::ObjectValues::iterator it = current_; it != other.current_;
++it) {
++myDistance;
}
return myDistance;
}
bool ValueIteratorBase::isEqual(const SelfType& other) const {
if (isNull_) {
return other.isNull_;
}
return current_ == other.current_;
}
void ValueIteratorBase::copy(const SelfType& other) {
current_ = other.current_;
isNull_ = other.isNull_;
}
Value ValueIteratorBase::key() const {
const Value::CZString czstring = (*current_).first;
if (czstring.data()) {
if (czstring.isStaticString())
return Value(StaticString(czstring.data()));
return Value(czstring.data(), czstring.data() + czstring.length());
}
return Value(czstring.index());
}
UInt ValueIteratorBase::index() const {
const Value::CZString czstring = (*current_).first;
if (!czstring.data())
return czstring.index();
return Value::UInt(-1);
}
String ValueIteratorBase::name() const {
char const* keey;
char const* end;
keey = memberName(&end);
if (!keey)
return String();
return String(keey, end);
}
char const* ValueIteratorBase::memberName() const {
const char* cname = (*current_).first.data();
return cname ? cname : "";
}
char const* ValueIteratorBase::memberName(char const** end) const {
const char* cname = (*current_).first.data();
if (!cname) {
*end = nullptr;
return nullptr;
}
*end = cname + (*current_).first.length();
return cname;
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueConstIterator
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueConstIterator::ValueConstIterator() = default;
ValueConstIterator::ValueConstIterator(
const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
ValueConstIterator::ValueConstIterator(ValueIterator const& other)
: ValueIteratorBase(other) {}
ValueConstIterator& ValueConstIterator::
operator=(const ValueIteratorBase& other) {
copy(other);
return *this;
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueIterator
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueIterator::ValueIterator() = default;
ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
ValueIterator::ValueIterator(const ValueConstIterator& other)
: ValueIteratorBase(other) {
throwRuntimeError("ConstIterator to Iterator should never be allowed.");
}
ValueIterator::ValueIterator(const ValueIterator& other) = default;
ValueIterator& ValueIterator::operator=(const SelfType& other) {
copy(other);
return *this;
}
} // namespace Json
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_valueiterator.inl
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_value.cpp
// //////////////////////////////////////////////////////////////////////
// Copyright 2011 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
#include <json/assertions.h>
#include <json/value.h>
#include <json/writer.h>
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstring>
#include <iostream>
#include <sstream>
#include <utility>
// Provide implementation equivalent of std::snprintf for older _MSC compilers
#if defined(_MSC_VER) && _MSC_VER < 1900
#include <stdarg.h>
static int msvc_pre1900_c99_vsnprintf(char* outBuf, size_t size,
const char* format, va_list ap) {
int count = -1;
if (size != 0)
count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap);
if (count == -1)
count = _vscprintf(format, ap);
return count;
}
int JSON_API msvc_pre1900_c99_snprintf(char* outBuf, size_t size,
const char* format, ...) {
va_list ap;
va_start(ap, format);
const int count = msvc_pre1900_c99_vsnprintf(outBuf, size, format, ap);
va_end(ap);
return count;
}
#endif
// Disable warning C4702 : unreachable code
#if defined(_MSC_VER)
#pragma warning(disable : 4702)
#endif
#define JSON_ASSERT_UNREACHABLE assert(false)
namespace Json {
template <typename T>
static std::unique_ptr<T> cloneUnique(const std::unique_ptr<T>& p) {
std::unique_ptr<T> r;
if (p) {
r = std::unique_ptr<T>(new T(*p));
}
return r;
}
// This is a walkaround to avoid the static initialization of Value::null.
// kNull must be word-aligned to avoid crashing on ARM. We use an alignment of
// 8 (instead of 4) as a bit of future-proofing.
#if defined(__ARMEL__)
#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
#else
#define ALIGNAS(byte_alignment)
#endif
// static
Value const& Value::nullSingleton() {
static Value const nullStatic;
return nullStatic;
}
#if JSON_USE_NULLREF
// for backwards compatibility, we'll leave these global references around, but
// DO NOT use them in JSONCPP library code any more!
// static
Value const& Value::null = Value::nullSingleton();
// static
Value const& Value::nullRef = Value::nullSingleton();
#endif
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
template <typename T, typename U>
static inline bool InRange(double d, T min, U max) {
// The casts can lose precision, but we are looking only for
// an approximate range. Might fail on edge cases though. ~cdunn
return d >= static_cast<double>(min) && d <= static_cast<double>(max);
}
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
static inline double integerToDouble(Json::UInt64 value) {
return static_cast<double>(Int64(value / 2)) * 2.0 +
static_cast<double>(Int64(value & 1));
}
template <typename T> static inline double integerToDouble(T value) {
return static_cast<double>(value);
}
template <typename T, typename U>
static inline bool InRange(double d, T min, U max) {
return d >= integerToDouble(min) && d <= integerToDouble(max);
}
#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
/** Duplicates the specified string value.
* @param value Pointer to the string to duplicate. Must be zero-terminated if
* length is "unknown".
* @param length Length of the value. if equals to unknown, then it will be
* computed using strlen(value).
* @return Pointer on the duplicate instance of string.
*/
static inline char* duplicateStringValue(const char* value, size_t length) {
// Avoid an integer overflow in the call to malloc below by limiting length
// to a sane value.
if (length >= static_cast<size_t>(Value::maxInt))
length = Value::maxInt - 1;
auto newString = static_cast<char*>(malloc(length + 1));
if (newString == nullptr) {
throwRuntimeError("in Json::Value::duplicateStringValue(): "
"Failed to allocate string value buffer");
}
memcpy(newString, value, length);
newString[length] = 0;
return newString;
}
/* Record the length as a prefix.
*/
static inline char* duplicateAndPrefixStringValue(const char* value,
unsigned int length) {
// Avoid an integer overflow in the call to malloc below by limiting length
// to a sane value.
JSON_ASSERT_MESSAGE(length <= static_cast<unsigned>(Value::maxInt) -
sizeof(unsigned) - 1U,
"in Json::Value::duplicateAndPrefixStringValue(): "
"length too big for prefixing");
size_t actualLength = sizeof(length) + length + 1;
auto newString = static_cast<char*>(malloc(actualLength));
if (newString == nullptr) {
throwRuntimeError("in Json::Value::duplicateAndPrefixStringValue(): "
"Failed to allocate string value buffer");
}
*reinterpret_cast<unsigned*>(newString) = length;
memcpy(newString + sizeof(unsigned), value, length);
newString[actualLength - 1U] =
0; // to avoid buffer over-run accidents by users later
return newString;
}
inline static void decodePrefixedString(bool isPrefixed, char const* prefixed,
unsigned* length, char const** value) {
if (!isPrefixed) {
*length = static_cast<unsigned>(strlen(prefixed));
*value = prefixed;
} else {
*length = *reinterpret_cast<unsigned const*>(prefixed);
*value = prefixed + sizeof(unsigned);
}
}
/** Free the string duplicated by
* duplicateStringValue()/duplicateAndPrefixStringValue().
*/
#if JSONCPP_USING_SECURE_MEMORY
static inline void releasePrefixedStringValue(char* value) {
unsigned length = 0;
char const* valueDecoded;
decodePrefixedString(true, value, &length, &valueDecoded);
size_t const size = sizeof(unsigned) + length + 1U;
memset(value, 0, size);
free(value);
}
static inline void releaseStringValue(char* value, unsigned length) {
// length==0 => we allocated the strings memory
size_t size = (length == 0) ? strlen(value) : length;
memset(value, 0, size);
free(value);
}
#else // !JSONCPP_USING_SECURE_MEMORY
static inline void releasePrefixedStringValue(char* value) { free(value); }
static inline void releaseStringValue(char* value, unsigned) { free(value); }
#endif // JSONCPP_USING_SECURE_MEMORY
} // namespace Json
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// ValueInternals...
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
#if !defined(JSON_IS_AMALGAMATION)
#include "json_valueiterator.inl"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
#if JSON_USE_EXCEPTION
Exception::Exception(String msg) : msg_(std::move(msg)) {}
Exception::~Exception() noexcept = default;
char const* Exception::what() const noexcept { return msg_.c_str(); }
RuntimeError::RuntimeError(String const& msg) : Exception(msg) {}
LogicError::LogicError(String const& msg) : Exception(msg) {}
JSONCPP_NORETURN void throwRuntimeError(String const& msg) {
throw RuntimeError(msg);
}
JSONCPP_NORETURN void throwLogicError(String const& msg) {
throw LogicError(msg);
}
#else // !JSON_USE_EXCEPTION
JSONCPP_NORETURN void throwRuntimeError(String const& msg) {
std::cerr << msg << std::endl;
abort();
}
JSONCPP_NORETURN void throwLogicError(String const& msg) {
std::cerr << msg << std::endl;
abort();
}
#endif
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::CZString
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// Notes: policy_ indicates if the string was allocated when
// a string is stored.
Value::CZString::CZString(ArrayIndex index) : cstr_(nullptr), index_(index) {}
Value::CZString::CZString(char const* str, unsigned length,
DuplicationPolicy allocate)
: cstr_(str) {
// allocate != duplicate
storage_.policy_ = allocate & 0x3;
storage_.length_ = length & 0x3FFFFFFF;
}
Value::CZString::CZString(const CZString& other) {
cstr_ = (other.storage_.policy_ != noDuplication && other.cstr_ != nullptr
? duplicateStringValue(other.cstr_, other.storage_.length_)
: other.cstr_);
storage_.policy_ =
static_cast<unsigned>(
other.cstr_
? (static_cast<DuplicationPolicy>(other.storage_.policy_) ==
noDuplication
? noDuplication
: duplicate)
: static_cast<DuplicationPolicy>(other.storage_.policy_)) &
3U;
storage_.length_ = other.storage_.length_;
}
Value::CZString::CZString(CZString&& other) noexcept
: cstr_(other.cstr_), index_(other.index_) {
other.cstr_ = nullptr;
}
Value::CZString::~CZString() {
if (cstr_ && storage_.policy_ == duplicate) {
releaseStringValue(const_cast<char*>(cstr_),
storage_.length_ + 1U); // +1 for null terminating
// character for sake of
// completeness but not actually
// necessary
}
}
void Value::CZString::swap(CZString& other) {
std::swap(cstr_, other.cstr_);
std::swap(index_, other.index_);
}
Value::CZString& Value::CZString::operator=(const CZString& other) {
cstr_ = other.cstr_;
index_ = other.index_;
return *this;
}
Value::CZString& Value::CZString::operator=(CZString&& other) noexcept {
cstr_ = other.cstr_;
index_ = other.index_;
other.cstr_ = nullptr;
return *this;
}
bool Value::CZString::operator<(const CZString& other) const {
if (!cstr_)
return index_ < other.index_;
// return strcmp(cstr_, other.cstr_) < 0;
// Assume both are strings.
unsigned this_len = this->storage_.length_;
unsigned other_len = other.storage_.length_;
unsigned min_len = std::min<unsigned>(this_len, other_len);
JSON_ASSERT(this->cstr_ && other.cstr_);
int comp = memcmp(this->cstr_, other.cstr_, min_len);
if (comp < 0)
return true;
if (comp > 0)
return false;
return (this_len < other_len);
}
bool Value::CZString::operator==(const CZString& other) const {
if (!cstr_)
return index_ == other.index_;
// return strcmp(cstr_, other.cstr_) == 0;
// Assume both are strings.
unsigned this_len = this->storage_.length_;
unsigned other_len = other.storage_.length_;
if (this_len != other_len)
return false;
JSON_ASSERT(this->cstr_ && other.cstr_);
int comp = memcmp(this->cstr_, other.cstr_, this_len);
return comp == 0;
}
ArrayIndex Value::CZString::index() const { return index_; }
// const char* Value::CZString::c_str() const { return cstr_; }
const char* Value::CZString::data() const { return cstr_; }
unsigned Value::CZString::length() const { return storage_.length_; }
bool Value::CZString::isStaticString() const {
return storage_.policy_ == noDuplication;
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::Value
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
/*! \internal Default constructor initialization must be equivalent to:
* memset( this, 0, sizeof(Value) )
* This optimization is used in ValueInternalMap fast allocator.
*/
Value::Value(ValueType type) {
static char const emptyString[] = "";
initBasic(type);
switch (type) {
case nullValue:
break;
case intValue:
case uintValue:
value_.int_ = 0;
break;
case realValue:
value_.real_ = 0.0;
break;
case stringValue:
// allocated_ == false, so this is safe.
value_.string_ = const_cast<char*>(static_cast<char const*>(emptyString));
break;
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues();
break;
case booleanValue:
value_.bool_ = false;
break;
default:
JSON_ASSERT_UNREACHABLE;
}
}
Value::Value(Int value) {
initBasic(intValue);
value_.int_ = value;
}
Value::Value(UInt value) {
initBasic(uintValue);
value_.uint_ = value;
}
#if defined(JSON_HAS_INT64)
Value::Value(Int64 value) {
initBasic(intValue);
value_.int_ = value;
}
Value::Value(UInt64 value) {
initBasic(uintValue);
value_.uint_ = value;
}
#endif // defined(JSON_HAS_INT64)
Value::Value(double value) {
initBasic(realValue);
value_.real_ = value;
}
Value::Value(const char* value) {
initBasic(stringValue, true);
JSON_ASSERT_MESSAGE(value != nullptr,
"Null Value Passed to Value Constructor");
value_.string_ = duplicateAndPrefixStringValue(
value, static_cast<unsigned>(strlen(value)));
}
Value::Value(const char* begin, const char* end) {
initBasic(stringValue, true);
value_.string_ =
duplicateAndPrefixStringValue(begin, static_cast<unsigned>(end - begin));
}
Value::Value(const String& value) {
initBasic(stringValue, true);
value_.string_ = duplicateAndPrefixStringValue(
value.data(), static_cast<unsigned>(value.length()));
}
Value::Value(const StaticString& value) {
initBasic(stringValue);
value_.string_ = const_cast<char*>(value.c_str());
}
Value::Value(bool value) {
initBasic(booleanValue);
value_.bool_ = value;
}
Value::Value(const Value& other) {
dupPayload(other);
dupMeta(other);
}
Value::Value(Value&& other) noexcept {
initBasic(nullValue);
swap(other);
}
Value::~Value() {
releasePayload();
value_.uint_ = 0;
}
Value& Value::operator=(const Value& other) {
Value(other).swap(*this);
return *this;
}
Value& Value::operator=(Value&& other) noexcept {
other.swap(*this);
return *this;
}
void Value::swapPayload(Value& other) {
std::swap(bits_, other.bits_);
std::swap(value_, other.value_);
}
void Value::copyPayload(const Value& other) {
releasePayload();
dupPayload(other);
}
void Value::swap(Value& other) {
swapPayload(other);
std::swap(comments_, other.comments_);
std::swap(start_, other.start_);
std::swap(limit_, other.limit_);
}
void Value::copy(const Value& other) {
copyPayload(other);
dupMeta(other);
}
ValueType Value::type() const {
return static_cast<ValueType>(bits_.value_type_);
}
int Value::compare(const Value& other) const {
if (*this < other)
return -1;
if (*this > other)
return 1;
return 0;
}
bool Value::operator<(const Value& other) const {
int typeDelta = type() - other.type();
if (typeDelta)
return typeDelta < 0;
switch (type()) {
case nullValue:
return false;
case intValue:
return value_.int_ < other.value_.int_;
case uintValue:
return value_.uint_ < other.value_.uint_;
case realValue:
return value_.real_ < other.value_.real_;
case booleanValue:
return value_.bool_ < other.value_.bool_;
case stringValue: {
if ((value_.string_ == nullptr) || (other.value_.string_ == nullptr)) {
return other.value_.string_ != nullptr;
}
unsigned this_len;
unsigned other_len;
char const* this_str;
char const* other_str;
decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
&this_str);
decodePrefixedString(other.isAllocated(), other.value_.string_, &other_len,
&other_str);
unsigned min_len = std::min<unsigned>(this_len, other_len);
JSON_ASSERT(this_str && other_str);
int comp = memcmp(this_str, other_str, min_len);
if (comp < 0)
return true;
if (comp > 0)
return false;
return (this_len < other_len);
}
case arrayValue:
case objectValue: {
auto thisSize = value_.map_->size();
auto otherSize = other.value_.map_->size();
if (thisSize != otherSize)
return thisSize < otherSize;
return (*value_.map_) < (*other.value_.map_);
}
default:
JSON_ASSERT_UNREACHABLE;
}
return false; // unreachable
}
bool Value::operator<=(const Value& other) const { return !(other < *this); }
bool Value::operator>=(const Value& other) const { return !(*this < other); }
bool Value::operator>(const Value& other) const { return other < *this; }
bool Value::operator==(const Value& other) const {
if (type() != other.type())
return false;
switch (type()) {
case nullValue:
return true;
case intValue:
return value_.int_ == other.value_.int_;
case uintValue:
return value_.uint_ == other.value_.uint_;
case realValue:
return value_.real_ == other.value_.real_;
case booleanValue:
return value_.bool_ == other.value_.bool_;
case stringValue: {
if ((value_.string_ == nullptr) || (other.value_.string_ == nullptr)) {
return (value_.string_ == other.value_.string_);
}
unsigned this_len;
unsigned other_len;
char const* this_str;
char const* other_str;
decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
&this_str);
decodePrefixedString(other.isAllocated(), other.value_.string_, &other_len,
&other_str);
if (this_len != other_len)
return false;
JSON_ASSERT(this_str && other_str);
int comp = memcmp(this_str, other_str, this_len);
return comp == 0;
}
case arrayValue:
case objectValue:
return value_.map_->size() == other.value_.map_->size() &&
(*value_.map_) == (*other.value_.map_);
default:
JSON_ASSERT_UNREACHABLE;
}
return false; // unreachable
}
bool Value::operator!=(const Value& other) const { return !(*this == other); }
const char* Value::asCString() const {
JSON_ASSERT_MESSAGE(type() == stringValue,
"in Json::Value::asCString(): requires stringValue");
if (value_.string_ == nullptr)
return nullptr;
unsigned this_len;
char const* this_str;
decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
&this_str);
return this_str;
}
#if JSONCPP_USING_SECURE_MEMORY
unsigned Value::getCStringLength() const {
JSON_ASSERT_MESSAGE(type() == stringValue,
"in Json::Value::asCString(): requires stringValue");
if (value_.string_ == 0)
return 0;
unsigned this_len;
char const* this_str;
decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
&this_str);
return this_len;
}
#endif
bool Value::getString(char const** begin, char const** end) const {
if (type() != stringValue)
return false;
if (value_.string_ == nullptr)
return false;
unsigned length;
decodePrefixedString(this->isAllocated(), this->value_.string_, &length,
begin);
*end = *begin + length;
return true;
}
String Value::asString() const {
switch (type()) {
case nullValue:
return "";
case stringValue: {
if (value_.string_ == nullptr)
return "";
unsigned this_len;
char const* this_str;
decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
&this_str);
return String(this_str, this_len);
}
case booleanValue:
return value_.bool_ ? "true" : "false";
case intValue:
return valueToString(value_.int_);
case uintValue:
return valueToString(value_.uint_);
case realValue:
return valueToString(value_.real_);
default:
JSON_FAIL_MESSAGE("Type is not convertible to string");
}
}
Value::Int Value::asInt() const {
switch (type()) {
case intValue:
JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range");
return Int(value_.int_);
case uintValue:
JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range");
return Int(value_.uint_);
case realValue:
JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt),
"double out of Int range");
return Int(value_.real_);
case nullValue:
return 0;
case booleanValue:
return value_.bool_ ? 1 : 0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to Int.");
}
Value::UInt Value::asUInt() const {
switch (type()) {
case intValue:
JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range");
return UInt(value_.int_);
case uintValue:
JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range");
return UInt(value_.uint_);
case realValue:
JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt),
"double out of UInt range");
return UInt(value_.real_);
case nullValue:
return 0;
case booleanValue:
return value_.bool_ ? 1 : 0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to UInt.");
}
#if defined(JSON_HAS_INT64)
Value::Int64 Value::asInt64() const {
switch (type()) {
case intValue:
return Int64(value_.int_);
case uintValue:
JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range");
return Int64(value_.uint_);
case realValue:
JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64),
"double out of Int64 range");
return Int64(value_.real_);
case nullValue:
return 0;
case booleanValue:
return value_.bool_ ? 1 : 0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to Int64.");
}
Value::UInt64 Value::asUInt64() const {
switch (type()) {
case intValue:
JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range");
return UInt64(value_.int_);
case uintValue:
return UInt64(value_.uint_);
case realValue:
JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64),
"double out of UInt64 range");
return UInt64(value_.real_);
case nullValue:
return 0;
case booleanValue:
return value_.bool_ ? 1 : 0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to UInt64.");
}
#endif // if defined(JSON_HAS_INT64)
LargestInt Value::asLargestInt() const {
#if defined(JSON_NO_INT64)
return asInt();
#else
return asInt64();
#endif
}
LargestUInt Value::asLargestUInt() const {
#if defined(JSON_NO_INT64)
return asUInt();
#else
return asUInt64();
#endif
}
double Value::asDouble() const {
switch (type()) {
case intValue:
return static_cast<double>(value_.int_);
case uintValue:
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
return static_cast<double>(value_.uint_);
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
return integerToDouble(value_.uint_);
#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
case realValue:
return value_.real_;
case nullValue:
return 0.0;
case booleanValue:
return value_.bool_ ? 1.0 : 0.0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to double.");
}
float Value::asFloat() const {
switch (type()) {
case intValue:
return static_cast<float>(value_.int_);
case uintValue:
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
return static_cast<float>(value_.uint_);
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
// This can fail (silently?) if the value is bigger than MAX_FLOAT.
return static_cast<float>(integerToDouble(value_.uint_));
#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
case realValue:
return static_cast<float>(value_.real_);
case nullValue:
return 0.0;
case booleanValue:
return value_.bool_ ? 1.0F : 0.0F;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to float.");
}
bool Value::asBool() const {
switch (type()) {
case booleanValue:
return value_.bool_;
case nullValue:
return false;
case intValue:
return value_.int_ != 0;
case uintValue:
return value_.uint_ != 0;
case realValue: {
// According to JavaScript language zero or NaN is regarded as false
const auto value_classification = std::fpclassify(value_.real_);
return value_classification != FP_ZERO && value_classification != FP_NAN;
}
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to bool.");
}
bool Value::isConvertibleTo(ValueType other) const {
switch (other) {
case nullValue:
return (isNumeric() && asDouble() == 0.0) ||
(type() == booleanValue && !value_.bool_) ||
(type() == stringValue && asString().empty()) ||
(type() == arrayValue && value_.map_->empty()) ||
(type() == objectValue && value_.map_->empty()) ||
type() == nullValue;
case intValue:
return isInt() ||
(type() == realValue && InRange(value_.real_, minInt, maxInt)) ||
type() == booleanValue || type() == nullValue;
case uintValue:
return isUInt() ||
(type() == realValue && InRange(value_.real_, 0, maxUInt)) ||
type() == booleanValue || type() == nullValue;
case realValue:
return isNumeric() || type() == booleanValue || type() == nullValue;
case booleanValue:
return isNumeric() || type() == booleanValue || type() == nullValue;
case stringValue:
return isNumeric() || type() == booleanValue || type() == stringValue ||
type() == nullValue;
case arrayValue:
return type() == arrayValue || type() == nullValue;
case objectValue:
return type() == objectValue || type() == nullValue;
}
JSON_ASSERT_UNREACHABLE;
return false;
}
/// Number of values in array or object
ArrayIndex Value::size() const {
switch (type()) {
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
case stringValue:
return 0;
case arrayValue: // size of the array is highest index + 1
if (!value_.map_->empty()) {
ObjectValues::const_iterator itLast = value_.map_->end();
--itLast;
return (*itLast).first.index() + 1;
}
return 0;
case objectValue:
return ArrayIndex(value_.map_->size());
}
JSON_ASSERT_UNREACHABLE;
return 0; // unreachable;
}
bool Value::empty() const {
if (isNull() || isArray() || isObject())
return size() == 0U;
return false;
}
Value::operator bool() const { return !isNull(); }
void Value::clear() {
JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue ||
type() == objectValue,
"in Json::Value::clear(): requires complex value");
start_ = 0;
limit_ = 0;
switch (type()) {
case arrayValue:
case objectValue:
value_.map_->clear();
break;
default:
break;
}
}
void Value::resize(ArrayIndex newSize) {
JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
"in Json::Value::resize(): requires arrayValue");
if (type() == nullValue)
*this = Value(arrayValue);
ArrayIndex oldSize = size();
if (newSize == 0)
clear();
else if (newSize > oldSize)
for (ArrayIndex i = oldSize; i < newSize; ++i)
(*this)[i];
else {
for (ArrayIndex index = newSize; index < oldSize; ++index) {
value_.map_->erase(index);
}
JSON_ASSERT(size() == newSize);
}
}
Value& Value::operator[](ArrayIndex index) {
JSON_ASSERT_MESSAGE(
type() == nullValue || type() == arrayValue,
"in Json::Value::operator[](ArrayIndex): requires arrayValue");
if (type() == nullValue)
*this = Value(arrayValue);
CZString key(index);
auto it = value_.map_->lower_bound(key);
if (it != value_.map_->end() && (*it).first == key)
return (*it).second;
ObjectValues::value_type defaultValue(key, nullSingleton());
it = value_.map_->insert(it, defaultValue);
return (*it).second;
}
Value& Value::operator[](int index) {
JSON_ASSERT_MESSAGE(
index >= 0,
"in Json::Value::operator[](int index): index cannot be negative");
return (*this)[ArrayIndex(index)];
}
const Value& Value::operator[](ArrayIndex index) const {
JSON_ASSERT_MESSAGE(
type() == nullValue || type() == arrayValue,
"in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
if (type() == nullValue)
return nullSingleton();
CZString key(index);
ObjectValues::const_iterator it = value_.map_->find(key);
if (it == value_.map_->end())
return nullSingleton();
return (*it).second;
}
const Value& Value::operator[](int index) const {
JSON_ASSERT_MESSAGE(
index >= 0,
"in Json::Value::operator[](int index) const: index cannot be negative");
return (*this)[ArrayIndex(index)];
}
void Value::initBasic(ValueType type, bool allocated) {
setType(type);
setIsAllocated(allocated);
comments_ = Comments{};
start_ = 0;
limit_ = 0;
}
void Value::dupPayload(const Value& other) {
setType(other.type());
setIsAllocated(false);
switch (type()) {
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
value_ = other.value_;
break;
case stringValue:
if (other.value_.string_ && other.isAllocated()) {
unsigned len;
char const* str;
decodePrefixedString(other.isAllocated(), other.value_.string_, &len,
&str);
value_.string_ = duplicateAndPrefixStringValue(str, len);
setIsAllocated(true);
} else {
value_.string_ = other.value_.string_;
}
break;
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues(*other.value_.map_);
break;
default:
JSON_ASSERT_UNREACHABLE;
}
}
void Value::releasePayload() {
switch (type()) {
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
break;
case stringValue:
if (isAllocated())
releasePrefixedStringValue(value_.string_);
break;
case arrayValue:
case objectValue:
delete value_.map_;
break;
default:
JSON_ASSERT_UNREACHABLE;
}
}
void Value::dupMeta(const Value& other) {
comments_ = other.comments_;
start_ = other.start_;
limit_ = other.limit_;
}
// Access an object value by name, create a null member if it does not exist.
// @pre Type of '*this' is object or null.
// @param key is null-terminated.
Value& Value::resolveReference(const char* key) {
JSON_ASSERT_MESSAGE(
type() == nullValue || type() == objectValue,
"in Json::Value::resolveReference(): requires objectValue");
if (type() == nullValue)
*this = Value(objectValue);
CZString actualKey(key, static_cast<unsigned>(strlen(key)),
CZString::noDuplication); // NOTE!
auto it = value_.map_->lower_bound(actualKey);
if (it != value_.map_->end() && (*it).first == actualKey)
return (*it).second;
ObjectValues::value_type defaultValue(actualKey, nullSingleton());
it = value_.map_->insert(it, defaultValue);
Value& value = (*it).second;
return value;
}
// @param key is not null-terminated.
Value& Value::resolveReference(char const* key, char const* end) {
JSON_ASSERT_MESSAGE(
type() == nullValue || type() == objectValue,
"in Json::Value::resolveReference(key, end): requires objectValue");
if (type() == nullValue)
*this = Value(objectValue);
CZString actualKey(key, static_cast<unsigned>(end - key),
CZString::duplicateOnCopy);
auto it = value_.map_->lower_bound(actualKey);
if (it != value_.map_->end() && (*it).first == actualKey)
return (*it).second;
ObjectValues::value_type defaultValue(actualKey, nullSingleton());
it = value_.map_->insert(it, defaultValue);
Value& value = (*it).second;
return value;
}
Value Value::get(ArrayIndex index, const Value& defaultValue) const {
const Value* value = &((*this)[index]);
return value == &nullSingleton() ? defaultValue : *value;
}
bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
Value const* Value::find(char const* begin, char const* end) const {
JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
"in Json::Value::find(begin, end): requires "
"objectValue or nullValue");
if (type() == nullValue)
return nullptr;
CZString actualKey(begin, static_cast<unsigned>(end - begin),
CZString::noDuplication);
ObjectValues::const_iterator it = value_.map_->find(actualKey);
if (it == value_.map_->end())
return nullptr;
return &(*it).second;
}
Value* Value::demand(char const* begin, char const* end) {
JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
"in Json::Value::demand(begin, end): requires "
"objectValue or nullValue");
return &resolveReference(begin, end);
}
const Value& Value::operator[](const char* key) const {
Value const* found = find(key, key + strlen(key));
if (!found)
return nullSingleton();
return *found;
}
Value const& Value::operator[](const String& key) const {
Value const* found = find(key.data(), key.data() + key.length());
if (!found)
return nullSingleton();
return *found;
}
Value& Value::operator[](const char* key) {
return resolveReference(key, key + strlen(key));
}
Value& Value::operator[](const String& key) {
return resolveReference(key.data(), key.data() + key.length());
}
Value& Value::operator[](const StaticString& key) {
return resolveReference(key.c_str());
}
Value& Value::append(const Value& value) { return append(Value(value)); }
Value& Value::append(Value&& value) {
JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
"in Json::Value::append: requires arrayValue");
if (type() == nullValue) {
*this = Value(arrayValue);
}
return this->value_.map_->emplace(size(), std::move(value)).first->second;
}
bool Value::insert(ArrayIndex index, const Value& newValue) {
return insert(index, Value(newValue));
}
bool Value::insert(ArrayIndex index, Value&& newValue) {
JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
"in Json::Value::insert: requires arrayValue");
ArrayIndex length = size();
if (index > length) {
return false;
}
for (ArrayIndex i = length; i > index; i--) {
(*this)[i] = std::move((*this)[i - 1]);
}
(*this)[index] = std::move(newValue);
return true;
}
Value Value::get(char const* begin, char const* end,
Value const& defaultValue) const {
Value const* found = find(begin, end);
return !found ? defaultValue : *found;
}
Value Value::get(char const* key, Value const& defaultValue) const {
return get(key, key + strlen(key), defaultValue);
}
Value Value::get(String const& key, Value const& defaultValue) const {
return get(key.data(), key.data() + key.length(), defaultValue);
}
bool Value::removeMember(const char* begin, const char* end, Value* removed) {
if (type() != objectValue) {
return false;
}
CZString actualKey(begin, static_cast<unsigned>(end - begin),
CZString::noDuplication);
auto it = value_.map_->find(actualKey);
if (it == value_.map_->end())
return false;
if (removed)
*removed = std::move(it->second);
value_.map_->erase(it);
return true;
}
bool Value::removeMember(const char* key, Value* removed) {
return removeMember(key, key + strlen(key), removed);
}
bool Value::removeMember(String const& key, Value* removed) {
return removeMember(key.data(), key.data() + key.length(), removed);
}
void Value::removeMember(const char* key) {
JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
"in Json::Value::removeMember(): requires objectValue");
if (type() == nullValue)
return;
CZString actualKey(key, unsigned(strlen(key)), CZString::noDuplication);
value_.map_->erase(actualKey);
}
void Value::removeMember(const String& key) { removeMember(key.c_str()); }
bool Value::removeIndex(ArrayIndex index, Value* removed) {
if (type() != arrayValue) {
return false;
}
CZString key(index);
auto it = value_.map_->find(key);
if (it == value_.map_->end()) {
return false;
}
if (removed)
*removed = it->second;
ArrayIndex oldSize = size();
// shift left all items left, into the place of the "removed"
for (ArrayIndex i = index; i < (oldSize - 1); ++i) {
CZString keey(i);
(*value_.map_)[keey] = (*this)[i + 1];
}
// erase the last one ("leftover")
CZString keyLast(oldSize - 1);
auto itLast = value_.map_->find(keyLast);
value_.map_->erase(itLast);
return true;
}
bool Value::isMember(char const* begin, char const* end) const {
Value const* value = find(begin, end);
return nullptr != value;
}
bool Value::isMember(char const* key) const {
return isMember(key, key + strlen(key));
}
bool Value::isMember(String const& key) const {
return isMember(key.data(), key.data() + key.length());
}
Value::Members Value::getMemberNames() const {
JSON_ASSERT_MESSAGE(
type() == nullValue || type() == objectValue,
"in Json::Value::getMemberNames(), value must be objectValue");
if (type() == nullValue)
return Value::Members();
Members members;
members.reserve(value_.map_->size());
ObjectValues::const_iterator it = value_.map_->begin();
ObjectValues::const_iterator itEnd = value_.map_->end();
for (; it != itEnd; ++it) {
members.push_back(String((*it).first.data(), (*it).first.length()));
}
return members;
}
static bool IsIntegral(double d) {
double integral_part;
return modf(d, &integral_part) == 0.0;
}
bool Value::isNull() const { return type() == nullValue; }
bool Value::isBool() const { return type() == booleanValue; }
bool Value::isInt() const {
switch (type()) {
case intValue:
#if defined(JSON_HAS_INT64)
return value_.int_ >= minInt && value_.int_ <= maxInt;
#else
return true;
#endif
case uintValue:
return value_.uint_ <= UInt(maxInt);
case realValue:
return value_.real_ >= minInt && value_.real_ <= maxInt &&
IsIntegral(value_.real_);
default:
break;
}
return false;
}
bool Value::isUInt() const {
switch (type()) {
case intValue:
#if defined(JSON_HAS_INT64)
return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
#else
return value_.int_ >= 0;
#endif
case uintValue:
#if defined(JSON_HAS_INT64)
return value_.uint_ <= maxUInt;
#else
return true;
#endif
case realValue:
return value_.real_ >= 0 && value_.real_ <= maxUInt &&
IsIntegral(value_.real_);
default:
break;
}
return false;
}
bool Value::isInt64() const {
#if defined(JSON_HAS_INT64)
switch (type()) {
case intValue:
return true;
case uintValue:
return value_.uint_ <= UInt64(maxInt64);
case realValue:
// Note that maxInt64 (= 2^63 - 1) is not exactly representable as a
// double, so double(maxInt64) will be rounded up to 2^63. Therefore we
// require the value to be strictly less than the limit.
return value_.real_ >= double(minInt64) &&
value_.real_ < double(maxInt64) && IsIntegral(value_.real_);
default:
break;
}
#endif // JSON_HAS_INT64
return false;
}
bool Value::isUInt64() const {
#if defined(JSON_HAS_INT64)
switch (type()) {
case intValue:
return value_.int_ >= 0;
case uintValue:
return true;
case realValue:
// Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
// double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
// require the value to be strictly less than the limit.
return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble &&
IsIntegral(value_.real_);
default:
break;
}
#endif // JSON_HAS_INT64
return false;
}
bool Value::isIntegral() const {
switch (type()) {
case intValue:
case uintValue:
return true;
case realValue:
#if defined(JSON_HAS_INT64)
// Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
// double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
// require the value to be strictly less than the limit.
return value_.real_ >= double(minInt64) &&
value_.real_ < maxUInt64AsDouble && IsIntegral(value_.real_);
#else
return value_.real_ >= minInt && value_.real_ <= maxUInt &&
IsIntegral(value_.real_);
#endif // JSON_HAS_INT64
default:
break;
}
return false;
}
bool Value::isDouble() const {
return type() == intValue || type() == uintValue || type() == realValue;
}
bool Value::isNumeric() const { return isDouble(); }
bool Value::isString() const { return type() == stringValue; }
bool Value::isArray() const { return type() == arrayValue; }
bool Value::isObject() const { return type() == objectValue; }
Value::Comments::Comments(const Comments& that)
: ptr_{cloneUnique(that.ptr_)} {}
Value::Comments::Comments(Comments&& that) noexcept
: ptr_{std::move(that.ptr_)} {}
Value::Comments& Value::Comments::operator=(const Comments& that) {
ptr_ = cloneUnique(that.ptr_);
return *this;
}
Value::Comments& Value::Comments::operator=(Comments&& that) noexcept {
ptr_ = std::move(that.ptr_);
return *this;
}
bool Value::Comments::has(CommentPlacement slot) const {
return ptr_ && !(*ptr_)[slot].empty();
}
String Value::Comments::get(CommentPlacement slot) const {
if (!ptr_)
return {};
return (*ptr_)[slot];
}
void Value::Comments::set(CommentPlacement slot, String comment) {
if (slot >= CommentPlacement::numberOfCommentPlacement)
return;
if (!ptr_)
ptr_ = std::unique_ptr<Array>(new Array());
(*ptr_)[slot] = std::move(comment);
}
void Value::setComment(String comment, CommentPlacement placement) {
if (!comment.empty() && (comment.back() == '\n')) {
// Always discard trailing newline, to aid indentation.
comment.pop_back();
}
JSON_ASSERT(!comment.empty());
JSON_ASSERT_MESSAGE(
comment[0] == '\0' || comment[0] == '/',
"in Json::Value::setComment(): Comments must start with /");
comments_.set(placement, std::move(comment));
}
bool Value::hasComment(CommentPlacement placement) const {
return comments_.has(placement);
}
String Value::getComment(CommentPlacement placement) const {
return comments_.get(placement);
}
void Value::setOffsetStart(ptrdiff_t start) { start_ = start; }
void Value::setOffsetLimit(ptrdiff_t limit) { limit_ = limit; }
ptrdiff_t Value::getOffsetStart() const { return start_; }
ptrdiff_t Value::getOffsetLimit() const { return limit_; }
String Value::toStyledString() const {
StreamWriterBuilder builder;
String out = this->hasComment(commentBefore) ? "\n" : "";
out += Json::writeString(builder, *this);
out += '\n';
return out;
}
Value::const_iterator Value::begin() const {
switch (type()) {
case arrayValue:
case objectValue:
if (value_.map_)
return const_iterator(value_.map_->begin());
break;
default:
break;
}
return {};
}
Value::const_iterator Value::end() const {
switch (type()) {
case arrayValue:
case objectValue:
if (value_.map_)
return const_iterator(value_.map_->end());
break;
default:
break;
}
return {};
}
Value::iterator Value::begin() {
switch (type()) {
case arrayValue:
case objectValue:
if (value_.map_)
return iterator(value_.map_->begin());
break;
default:
break;
}
return iterator();
}
Value::iterator Value::end() {
switch (type()) {
case arrayValue:
case objectValue:
if (value_.map_)
return iterator(value_.map_->end());
break;
default:
break;
}
return iterator();
}
// class PathArgument
// //////////////////////////////////////////////////////////////////
PathArgument::PathArgument() = default;
PathArgument::PathArgument(ArrayIndex index)
: index_(index), kind_(kindIndex) {}
PathArgument::PathArgument(const char* key) : key_(key), kind_(kindKey) {}
PathArgument::PathArgument(String key) : key_(std::move(key)), kind_(kindKey) {}
// class Path
// //////////////////////////////////////////////////////////////////
Path::Path(const String& path, const PathArgument& a1, const PathArgument& a2,
const PathArgument& a3, const PathArgument& a4,
const PathArgument& a5) {
InArgs in;
in.reserve(5);
in.push_back(&a1);
in.push_back(&a2);
in.push_back(&a3);
in.push_back(&a4);
in.push_back(&a5);
makePath(path, in);
}
void Path::makePath(const String& path, const InArgs& in) {
const char* current = path.c_str();
const char* end = current + path.length();
auto itInArg = in.begin();
while (current != end) {
if (*current == '[') {
++current;
if (*current == '%')
addPathInArg(path, in, itInArg, PathArgument::kindIndex);
else {
ArrayIndex index = 0;
for (; current != end && *current >= '0' && *current <= '9'; ++current)
index = index * 10 + ArrayIndex(*current - '0');
args_.push_back(index);
}
if (current == end || *++current != ']')
invalidPath(path, int(current - path.c_str()));
} else if (*current == '%') {
addPathInArg(path, in, itInArg, PathArgument::kindKey);
++current;
} else if (*current == '.' || *current == ']') {
++current;
} else {
const char* beginName = current;
while (current != end && !strchr("[.", *current))
++current;
args_.push_back(String(beginName, current));
}
}
}
void Path::addPathInArg(const String& /*path*/, const InArgs& in,
InArgs::const_iterator& itInArg,
PathArgument::Kind kind) {
if (itInArg == in.end()) {
// Error: missing argument %d
} else if ((*itInArg)->kind_ != kind) {
// Error: bad argument type
} else {
args_.push_back(**itInArg++);
}
}
void Path::invalidPath(const String& /*path*/, int /*location*/) {
// Error: invalid path.
}
const Value& Path::resolve(const Value& root) const {
const Value* node = &root;
for (const auto& arg : args_) {
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray() || !node->isValidIndex(arg.index_)) {
// Error: unable to resolve path (array value expected at position... )
return Value::nullSingleton();
}
node = &((*node)[arg.index_]);
} else if (arg.kind_ == PathArgument::kindKey) {
if (!node->isObject()) {
// Error: unable to resolve path (object value expected at position...)
return Value::nullSingleton();
}
node = &((*node)[arg.key_]);
if (node == &Value::nullSingleton()) {
// Error: unable to resolve path (object has no member named '' at
// position...)
return Value::nullSingleton();
}
}
}
return *node;
}
Value Path::resolve(const Value& root, const Value& defaultValue) const {
const Value* node = &root;
for (const auto& arg : args_) {
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray() || !node->isValidIndex(arg.index_))
return defaultValue;
node = &((*node)[arg.index_]);
} else if (arg.kind_ == PathArgument::kindKey) {
if (!node->isObject())
return defaultValue;
node = &((*node)[arg.key_]);
if (node == &Value::nullSingleton())
return defaultValue;
}
}
return *node;
}
Value& Path::make(Value& root) const {
Value* node = &root;
for (const auto& arg : args_) {
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray()) {
// Error: node is not an array at position ...
}
node = &((*node)[arg.index_]);
} else if (arg.kind_ == PathArgument::kindKey) {
if (!node->isObject()) {
// Error: node is not an object at position...
}
node = &((*node)[arg.key_]);
}
}
return *node;
}
} // namespace Json
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_value.cpp
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_writer.cpp
// //////////////////////////////////////////////////////////////////////
// Copyright 2011 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
#include "json_tool.h"
#include <json/writer.h>
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstring>
#include <iomanip>
#include <memory>
#include <set>
#include <sstream>
#include <utility>
#if __cplusplus >= 201103L
#include <cmath>
#include <cstdio>
#if !defined(isnan)
#define isnan std::isnan
#endif
#if !defined(isfinite)
#define isfinite std::isfinite
#endif
#else
#include <cmath>
#include <cstdio>
#if defined(_MSC_VER)
#if !defined(isnan)
#include <float.h>
#define isnan _isnan
#endif
#if !defined(isfinite)
#include <float.h>
#define isfinite _finite
#endif
#if !defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#endif //_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
#endif //_MSC_VER
#if defined(__sun) && defined(__SVR4) // Solaris
#if !defined(isfinite)
#include <ieeefp.h>
#define isfinite finite
#endif
#endif
#if defined(__hpux)
#if !defined(isfinite)
#if defined(__ia64) && !defined(finite)
#define isfinite(x) \
((sizeof(x) == sizeof(float) ? _Isfinitef(x) : _IsFinite(x)))
#endif
#endif
#endif
#if !defined(isnan)
// IEEE standard states that NaN values will not compare to themselves
#define isnan(x) ((x) != (x))
#endif
#if !defined(__APPLE__)
#if !defined(isfinite)
#define isfinite finite
#endif
#endif
#endif
#if defined(_MSC_VER)
// Disable warning about strdup being deprecated.
#pragma warning(disable : 4996)
#endif
namespace Json {
#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
using StreamWriterPtr = std::unique_ptr<StreamWriter>;
#else
using StreamWriterPtr = std::auto_ptr<StreamWriter>;
#endif
String valueToString(LargestInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
if (value == Value::minLargestInt) {
uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
*--current = '-';
} else if (value < 0) {
uintToString(LargestUInt(-value), current);
*--current = '-';
} else {
uintToString(LargestUInt(value), current);
}
assert(current >= buffer);
return current;
}
String valueToString(LargestUInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
uintToString(value, current);
assert(current >= buffer);
return current;
}
#if defined(JSON_HAS_INT64)
String valueToString(Int value) { return valueToString(LargestInt(value)); }
String valueToString(UInt value) { return valueToString(LargestUInt(value)); }
#endif // # if defined(JSON_HAS_INT64)
namespace {
String valueToString(double value, bool useSpecialFloats,
unsigned int precision, PrecisionType precisionType) {
// Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distinguish the
// concepts of reals and integers.
if (!isfinite(value)) {
static const char* const reps[2][3] = {{"NaN", "-Infinity", "Infinity"},
{"null", "-1e+9999", "1e+9999"}};
return reps[useSpecialFloats ? 0 : 1]
[isnan(value) ? 0 : (value < 0) ? 1 : 2];
}
String buffer(size_t(36), '\0');
while (true) {
int len = jsoncpp_snprintf(
&*buffer.begin(), buffer.size(),
(precisionType == PrecisionType::significantDigits) ? "%.*g" : "%.*f",
precision, value);
assert(len >= 0);
auto wouldPrint = static_cast<size_t>(len);
if (wouldPrint >= buffer.size()) {
buffer.resize(wouldPrint + 1);
continue;
}
buffer.resize(wouldPrint);
break;
}
buffer.erase(fixNumericLocale(buffer.begin(), buffer.end()), buffer.end());
// try to ensure we preserve the fact that this was given to us as a double on
// input
if (buffer.find('.') == buffer.npos && buffer.find('e') == buffer.npos) {
buffer += ".0";
}
// strip the zero padding from the right
if (precisionType == PrecisionType::decimalPlaces) {
buffer.erase(fixZerosInTheEnd(buffer.begin(), buffer.end(), precision),
buffer.end());
}
return buffer;
}
} // namespace
String valueToString(double value, unsigned int precision,
PrecisionType precisionType) {
return valueToString(value, false, precision, precisionType);
}
String valueToString(bool value) { return value ? "true" : "false"; }
static bool doesAnyCharRequireEscaping(char const* s, size_t n) {
assert(s || !n);
return std::any_of(s, s + n, [](unsigned char c) {
return c == '\\' || c == '"' || c < 0x20 || c > 0x7F;
});
}
static unsigned int utf8ToCodepoint(const char*& s, const char* e) {
const unsigned int REPLACEMENT_CHARACTER = 0xFFFD;
unsigned int firstByte = static_cast<unsigned char>(*s);
if (firstByte < 0x80)
return firstByte;
if (firstByte < 0xE0) {
if (e - s < 2)
return REPLACEMENT_CHARACTER;
unsigned int calculated =
((firstByte & 0x1F) << 6) | (static_cast<unsigned int>(s[1]) & 0x3F);
s += 1;
// oversized encoded characters are invalid
return calculated < 0x80 ? REPLACEMENT_CHARACTER : calculated;
}
if (firstByte < 0xF0) {
if (e - s < 3)
return REPLACEMENT_CHARACTER;
unsigned int calculated = ((firstByte & 0x0F) << 12) |
((static_cast<unsigned int>(s[1]) & 0x3F) << 6) |
(static_cast<unsigned int>(s[2]) & 0x3F);
s += 2;
// surrogates aren't valid codepoints itself
// shouldn't be UTF-8 encoded
if (calculated >= 0xD800 && calculated <= 0xDFFF)
return REPLACEMENT_CHARACTER;
// oversized encoded characters are invalid
return calculated < 0x800 ? REPLACEMENT_CHARACTER : calculated;
}
if (firstByte < 0xF8) {
if (e - s < 4)
return REPLACEMENT_CHARACTER;
unsigned int calculated = ((firstByte & 0x07) << 18) |
((static_cast<unsigned int>(s[1]) & 0x3F) << 12) |
((static_cast<unsigned int>(s[2]) & 0x3F) << 6) |
(static_cast<unsigned int>(s[3]) & 0x3F);
s += 3;
// oversized encoded characters are invalid
return calculated < 0x10000 ? REPLACEMENT_CHARACTER : calculated;
}
return REPLACEMENT_CHARACTER;
}
static const char hex2[] = "000102030405060708090a0b0c0d0e0f"
"101112131415161718191a1b1c1d1e1f"
"202122232425262728292a2b2c2d2e2f"
"303132333435363738393a3b3c3d3e3f"
"404142434445464748494a4b4c4d4e4f"
"505152535455565758595a5b5c5d5e5f"
"606162636465666768696a6b6c6d6e6f"
"707172737475767778797a7b7c7d7e7f"
"808182838485868788898a8b8c8d8e8f"
"909192939495969798999a9b9c9d9e9f"
"a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
"b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
"c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
"d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
"e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff";
static String toHex16Bit(unsigned int x) {
const unsigned int hi = (x >> 8) & 0xff;
const unsigned int lo = x & 0xff;
String result(4, ' ');
result[0] = hex2[2 * hi];
result[1] = hex2[2 * hi + 1];
result[2] = hex2[2 * lo];
result[3] = hex2[2 * lo + 1];
return result;
}
static void appendRaw(String& result, unsigned ch) {
result += static_cast<char>(ch);
}
static void appendHex(String& result, unsigned ch) {
result.append("\\u").append(toHex16Bit(ch));
}
static String valueToQuotedStringN(const char* value, size_t length,
bool emitUTF8 = false) {
if (value == nullptr)
return "";
if (!doesAnyCharRequireEscaping(value, length))
return String("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to String is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
String::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL
String result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
char const* end = value + length;
for (const char* c = value; c != end; ++c) {
switch (*c) {
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
// case '/':
// Even though \/ is considered a legal escape in JSON, a bare
// slash is also legal, so I see no reason to escape it.
// (I hope I am not misunderstanding something.)
// blep notes: actually escaping \/ may be useful in javascript to avoid </
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
default: {
if (emitUTF8) {
unsigned codepoint = static_cast<unsigned char>(*c);
if (codepoint < 0x20) {
appendHex(result, codepoint);
} else {
appendRaw(result, codepoint);
}
} else {
unsigned codepoint = utf8ToCodepoint(c, end); // modifies `c`
if (codepoint < 0x20) {
appendHex(result, codepoint);
} else if (codepoint < 0x80) {
appendRaw(result, codepoint);
} else if (codepoint < 0x10000) {
// Basic Multilingual Plane
appendHex(result, codepoint);
} else {
// Extended Unicode. Encode 20 bits as a surrogate pair.
codepoint -= 0x10000;
appendHex(result, 0xd800 + ((codepoint >> 10) & 0x3ff));
appendHex(result, 0xdc00 + (codepoint & 0x3ff));
}
}
} break;
}
}
result += "\"";
return result;
}
String valueToQuotedString(const char* value) {
return valueToQuotedStringN(value, strlen(value));
}
// Class Writer
// //////////////////////////////////////////////////////////////////
Writer::~Writer() = default;
// Class FastWriter
// //////////////////////////////////////////////////////////////////
FastWriter::FastWriter()
= default;
void FastWriter::enableYAMLCompatibility() { yamlCompatibilityEnabled_ = true; }
void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
String FastWriter::write(const Value& root) {
document_.clear();
writeValue(root);
if (!omitEndingLineFeed_)
document_ += '\n';
return document_;
}
void FastWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
if (!dropNullPlaceholders_)
document_ += "null";
break;
case intValue:
document_ += valueToString(value.asLargestInt());
break;
case uintValue:
document_ += valueToString(value.asLargestUInt());
break;
case realValue:
document_ += valueToString(value.asDouble());
break;
case stringValue: {
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok)
document_ += valueToQuotedStringN(str, static_cast<size_t>(end - str));
break;
}
case booleanValue:
document_ += valueToString(value.asBool());
break;
case arrayValue: {
document_ += '[';
ArrayIndex size = value.size();
for (ArrayIndex index = 0; index < size; ++index) {
if (index > 0)
document_ += ',';
writeValue(value[index]);
}
document_ += ']';
} break;
case objectValue: {
Value::Members members(value.getMemberNames());
document_ += '{';
for (auto it = members.begin(); it != members.end(); ++it) {
const String& name = *it;
if (it != members.begin())
document_ += ',';
document_ += valueToQuotedStringN(name.data(), name.length());
document_ += yamlCompatibilityEnabled_ ? ": " : ":";
writeValue(value[name]);
}
document_ += '}';
} break;
}
}
// Class StyledWriter
// //////////////////////////////////////////////////////////////////
StyledWriter::StyledWriter() = default;
String StyledWriter::write(const Value& root) {
document_.clear();
addChildValues_ = false;
indentString_.clear();
writeCommentBeforeValue(root);
writeValue(root);
writeCommentAfterValueOnSameLine(root);
document_ += '\n';
return document_;
}
void StyledWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
pushValue("null");
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble()));
break;
case stringValue: {
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok)
pushValue(valueToQuotedStringN(str, static_cast<size_t>(end - str)));
else
pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
auto it = members.begin();
for (;;) {
const String& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
document_ += " : ";
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
document_ += ',';
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void StyledWriter::writeArrayValue(const Value& value) {
size_t size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isArrayMultiLine = isMultilineArray(value);
if (isArrayMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
ArrayIndex index = 0;
for (;;) {
const Value& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
writeIndent();
writeValue(childValue);
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
document_ += ',';
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
} else // output on a single line
{
assert(childValues_.size() == size);
document_ += "[ ";
for (size_t index = 0; index < size; ++index) {
if (index > 0)
document_ += ", ";
document_ += childValues_[index];
}
document_ += " ]";
}
}
}
bool StyledWriter::isMultilineArray(const Value& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
!childValue.empty());
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void StyledWriter::pushValue(const String& value) {
if (addChildValues_)
childValues_.push_back(value);
else
document_ += value;
}
void StyledWriter::writeIndent() {
if (!document_.empty()) {
char last = document_[document_.length() - 1];
if (last == ' ') // already indented
return;
if (last != '\n') // Comments may add new-line
document_ += '\n';
}
document_ += indentString_;
}
void StyledWriter::writeWithIndent(const String& value) {
writeIndent();
document_ += value;
}
void StyledWriter::indent() { indentString_ += String(indentSize_, ' '); }
void StyledWriter::unindent() {
assert(indentString_.size() >= indentSize_);
indentString_.resize(indentString_.size() - indentSize_);
}
void StyledWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
document_ += '\n';
writeIndent();
const String& comment = root.getComment(commentBefore);
String::const_iterator iter = comment.begin();
while (iter != comment.end()) {
document_ += *iter;
if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
writeIndent();
++iter;
}
// Comments are stripped of trailing newlines, so add one here
document_ += '\n';
}
void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
if (root.hasComment(commentAfterOnSameLine))
document_ += " " + root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
document_ += '\n';
document_ += root.getComment(commentAfter);
document_ += '\n';
}
}
bool StyledWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
// Class StyledStreamWriter
// //////////////////////////////////////////////////////////////////
StyledStreamWriter::StyledStreamWriter(String indentation)
: document_(nullptr), indentation_(std::move(indentation)),
addChildValues_(), indented_(false) {}
void StyledStreamWriter::write(OStream& out, const Value& root) {
document_ = &out;
addChildValues_ = false;
indentString_.clear();
indented_ = true;
writeCommentBeforeValue(root);
if (!indented_)
writeIndent();
indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*document_ << "\n";
document_ = nullptr; // Forget the stream, for safety.
}
void StyledStreamWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
pushValue("null");
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble()));
break;
case stringValue: {
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok)
pushValue(valueToQuotedStringN(str, static_cast<size_t>(end - str)));
else
pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
auto it = members.begin();
for (;;) {
const String& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
*document_ << " : ";
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void StyledStreamWriter::writeArrayValue(const Value& value) {
unsigned size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isArrayMultiLine = isMultilineArray(value);
if (isArrayMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
unsigned index = 0;
for (;;) {
const Value& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
if (!indented_)
writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
} else // output on a single line
{
assert(childValues_.size() == size);
*document_ << "[ ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*document_ << ", ";
*document_ << childValues_[index];
}
*document_ << " ]";
}
}
}
bool StyledStreamWriter::isMultilineArray(const Value& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
!childValue.empty());
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void StyledStreamWriter::pushValue(const String& value) {
if (addChildValues_)
childValues_.push_back(value);
else
*document_ << value;
}
void StyledStreamWriter::writeIndent() {
// blep intended this to look at the so-far-written string
// to determine whether we are already indented, but
// with a stream we cannot do that. So we rely on some saved state.
// The caller checks indented_.
*document_ << '\n' << indentString_;
}
void StyledStreamWriter::writeWithIndent(const String& value) {
if (!indented_)
writeIndent();
*document_ << value;
indented_ = false;
}
void StyledStreamWriter::indent() { indentString_ += indentation_; }
void StyledStreamWriter::unindent() {
assert(indentString_.size() >= indentation_.size());
indentString_.resize(indentString_.size() - indentation_.size());
}
void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
if (!indented_)
writeIndent();
const String& comment = root.getComment(commentBefore);
String::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*document_ << *iter;
if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
// writeIndent(); // would include newline
*document_ << indentString_;
++iter;
}
indented_ = false;
}
void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
if (root.hasComment(commentAfterOnSameLine))
*document_ << ' ' << root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
writeIndent();
*document_ << root.getComment(commentAfter);
}
indented_ = false;
}
bool StyledStreamWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
//////////////////////////
// BuiltStyledStreamWriter
/// Scoped enums are not available until C++11.
struct CommentStyle {
/// Decide whether to write comments.
enum Enum {
None, ///< Drop all comments.
Most, ///< Recover odd behavior of previous versions (not implemented yet).
All ///< Keep all comments.
};
};
struct BuiltStyledStreamWriter : public StreamWriter {
BuiltStyledStreamWriter(String indentation, CommentStyle::Enum cs,
String colonSymbol, String nullSymbol,
String endingLineFeedSymbol, bool useSpecialFloats,
bool emitUTF8, unsigned int precision,
PrecisionType precisionType);
int write(Value const& root, OStream* sout) override;
private:
void writeValue(Value const& value);
void writeArrayValue(Value const& value);
bool isMultilineArray(Value const& value);
void pushValue(String const& value);
void writeIndent();
void writeWithIndent(String const& value);
void indent();
void unindent();
void writeCommentBeforeValue(Value const& root);
void writeCommentAfterValueOnSameLine(Value const& root);
static bool hasCommentForValue(const Value& value);
using ChildValues = std::vector<String>;
ChildValues childValues_;
String indentString_;
unsigned int rightMargin_;
String indentation_;
CommentStyle::Enum cs_;
String colonSymbol_;
String nullSymbol_;
String endingLineFeedSymbol_;
bool addChildValues_ : 1;
bool indented_ : 1;
bool useSpecialFloats_ : 1;
bool emitUTF8_ : 1;
unsigned int precision_;
PrecisionType precisionType_;
};
BuiltStyledStreamWriter::BuiltStyledStreamWriter(
String indentation, CommentStyle::Enum cs, String colonSymbol,
String nullSymbol, String endingLineFeedSymbol, bool useSpecialFloats,
bool emitUTF8, unsigned int precision, PrecisionType precisionType)
: rightMargin_(74), indentation_(std::move(indentation)), cs_(cs),
colonSymbol_(std::move(colonSymbol)), nullSymbol_(std::move(nullSymbol)),
endingLineFeedSymbol_(std::move(endingLineFeedSymbol)),
addChildValues_(false), indented_(false),
useSpecialFloats_(useSpecialFloats), emitUTF8_(emitUTF8),
precision_(precision), precisionType_(precisionType) {}
int BuiltStyledStreamWriter::write(Value const& root, OStream* sout) {
sout_ = sout;
addChildValues_ = false;
indented_ = true;
indentString_.clear();
writeCommentBeforeValue(root);
if (!indented_)
writeIndent();
indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*sout_ << endingLineFeedSymbol_;
sout_ = nullptr;
return 0;
}
void BuiltStyledStreamWriter::writeValue(Value const& value) {
switch (value.type()) {
case nullValue:
pushValue(nullSymbol_);
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_,
precisionType_));
break;
case stringValue: {
// Is NULL is possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok)
pushValue(
valueToQuotedStringN(str, static_cast<size_t>(end - str), emitUTF8_));
else
pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
auto it = members.begin();
for (;;) {
String const& name = *it;
Value const& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(
valueToQuotedStringN(name.data(), name.length(), emitUTF8_));
*sout_ << colonSymbol_;
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*sout_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
unsigned size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isMultiLine = (cs_ == CommentStyle::All) || isMultilineArray(value);
if (isMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
unsigned index = 0;
for (;;) {
Value const& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
if (!indented_)
writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*sout_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
} else // output on a single line
{
assert(childValues_.size() == size);
*sout_ << "[";
if (!indentation_.empty())
*sout_ << " ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*sout_ << ((!indentation_.empty()) ? ", " : ",");
*sout_ << childValues_[index];
}
if (!indentation_.empty())
*sout_ << " ";
*sout_ << "]";
}
}
}
bool BuiltStyledStreamWriter::isMultilineArray(Value const& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
Value const& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
!childValue.empty());
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void BuiltStyledStreamWriter::pushValue(String const& value) {
if (addChildValues_)
childValues_.push_back(value);
else
*sout_ << value;
}
void BuiltStyledStreamWriter::writeIndent() {
// blep intended this to look at the so-far-written string
// to determine whether we are already indented, but
// with a stream we cannot do that. So we rely on some saved state.
// The caller checks indented_.
if (!indentation_.empty()) {
// In this case, drop newlines too.
*sout_ << '\n' << indentString_;
}
}
void BuiltStyledStreamWriter::writeWithIndent(String const& value) {
if (!indented_)
writeIndent();
*sout_ << value;
indented_ = false;
}
void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
void BuiltStyledStreamWriter::unindent() {
assert(indentString_.size() >= indentation_.size());
indentString_.resize(indentString_.size() - indentation_.size());
}
void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
if (cs_ == CommentStyle::None)
return;
if (!root.hasComment(commentBefore))
return;
if (!indented_)
writeIndent();
const String& comment = root.getComment(commentBefore);
String::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*sout_ << *iter;
if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
// writeIndent(); // would write extra newline
*sout_ << indentString_;
++iter;
}
indented_ = false;
}
void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(
Value const& root) {
if (cs_ == CommentStyle::None)
return;
if (root.hasComment(commentAfterOnSameLine))
*sout_ << " " + root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
writeIndent();
*sout_ << root.getComment(commentAfter);
}
}
// static
bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
///////////////
// StreamWriter
StreamWriter::StreamWriter() : sout_(nullptr) {}
StreamWriter::~StreamWriter() = default;
StreamWriter::Factory::~Factory() = default;
StreamWriterBuilder::StreamWriterBuilder() { setDefaults(&settings_); }
StreamWriterBuilder::~StreamWriterBuilder() = default;
StreamWriter* StreamWriterBuilder::newStreamWriter() const {
const String indentation = settings_["indentation"].asString();
const String cs_str = settings_["commentStyle"].asString();
const String pt_str = settings_["precisionType"].asString();
const bool eyc = settings_["enableYAMLCompatibility"].asBool();
const bool dnp = settings_["dropNullPlaceholders"].asBool();
const bool usf = settings_["useSpecialFloats"].asBool();
const bool emitUTF8 = settings_["emitUTF8"].asBool();
unsigned int pre = settings_["precision"].asUInt();
CommentStyle::Enum cs = CommentStyle::All;
if (cs_str == "All") {
cs = CommentStyle::All;
} else if (cs_str == "None") {
cs = CommentStyle::None;
} else {
throwRuntimeError("commentStyle must be 'All' or 'None'");
}
PrecisionType precisionType(significantDigits);
if (pt_str == "significant") {
precisionType = PrecisionType::significantDigits;
} else if (pt_str == "decimal") {
precisionType = PrecisionType::decimalPlaces;
} else {
throwRuntimeError("precisionType must be 'significant' or 'decimal'");
}
String colonSymbol = " : ";
if (eyc) {
colonSymbol = ": ";
} else if (indentation.empty()) {
colonSymbol = ":";
}
String nullSymbol = "null";
if (dnp) {
nullSymbol.clear();
}
if (pre > 17)
pre = 17;
String endingLineFeedSymbol;
return new BuiltStyledStreamWriter(indentation, cs, colonSymbol, nullSymbol,
endingLineFeedSymbol, usf, emitUTF8, pre,
precisionType);
}
bool StreamWriterBuilder::validate(Json::Value* invalid) const {
static const auto& valid_keys = *new std::set<String>{
"indentation",
"commentStyle",
"enableYAMLCompatibility",
"dropNullPlaceholders",
"useSpecialFloats",
"emitUTF8",
"precision",
"precisionType",
};
for (auto si = settings_.begin(); si != settings_.end(); ++si) {
auto key = si.name();
if (valid_keys.count(key))
continue;
if (invalid)
(*invalid)[key] = *si;
else
return false;
}
return invalid ? invalid->empty() : true;
}
Value& StreamWriterBuilder::operator[](const String& key) {
return settings_[key];
}
// static
void StreamWriterBuilder::setDefaults(Json::Value* settings) {
//! [StreamWriterBuilderDefaults]
(*settings)["commentStyle"] = "All";
(*settings)["indentation"] = "\t";
(*settings)["enableYAMLCompatibility"] = false;
(*settings)["dropNullPlaceholders"] = false;
(*settings)["useSpecialFloats"] = false;
(*settings)["emitUTF8"] = false;
(*settings)["precision"] = 17;
(*settings)["precisionType"] = "significant";
//! [StreamWriterBuilderDefaults]
}
String writeString(StreamWriter::Factory const& factory, Value const& root) {
OStringStream sout;
StreamWriterPtr const writer(factory.newStreamWriter());
writer->write(root, &sout);
return sout.str();
}
OStream& operator<<(OStream& sout, Value const& root) {
StreamWriterBuilder builder;
StreamWriterPtr const writer(builder.newStreamWriter());
writer->write(root, &sout);
return sout;
}
} // namespace Json
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_writer.cpp
// //////////////////////////////////////////////////////////////////////
| [
"alaa@temcocontrols.com"
] | alaa@temcocontrols.com |
4ef1cff157b71ebeb7e1b59c2642191feca5c23c | 6d54aeccc82dfdc9dc476cd9a5a23d72ff418e2d | /GradingStudents.cpp | ef1008dfb1ce73727bf2f8bc373016d97781198a | [] | no_license | Yashkalyan/Algorithm-Hackerrank-Solutions | 8d060b8cdc8b7ea5d30a21ce8c469de4e466d765 | 486eddc7515898465384bf03424b2e01810e5bd7 | refs/heads/master | 2021-04-10T21:57:03.466559 | 2020-04-01T08:12:52 | 2020-04-01T08:12:52 | 248,969,914 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,704 | cpp | #include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
/*
* Complete the 'gradingStudents' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY grades as parameter.
*/
vector<int> gradingStudents(vector<int> grades) {
int diff;
for(auto i=0;i<grades.size();i++)
{
if(grades[i]>=38)
{
diff=5 - (grades[i]%5);
if(diff<3)
grades[i]+=diff;
}
}
return grades;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string grades_count_temp;
getline(cin, grades_count_temp);
int grades_count = stoi(ltrim(rtrim(grades_count_temp)));
vector<int> grades(grades_count);
for (int i = 0; i < grades_count; i++) {
string grades_item_temp;
getline(cin, grades_item_temp);
int grades_item = stoi(ltrim(rtrim(grades_item_temp)));
grades[i] = grades_item;
}
vector<int> result = gradingStudents(grades);
for (int i = 0; i < result.size(); i++) {
fout << result[i];
if (i != result.size() - 1) {
fout << "\n";
}
}
fout << "\n";
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
| [
"noreply@github.com"
] | Yashkalyan.noreply@github.com |
05653133e4960acb4c4133bbaa100d38b5626c85 | 18a3f93e4b94f4f24ff17280c2820497e019b3db | /geant4/G4GeomTestSegment.hh | 41ed345061c0bb3df9b94ce79695368dc0565998 | [] | no_license | jjzhang166/BOSS_ExternalLibs | 0e381d8420cea17e549d5cae5b04a216fc8a01d7 | 9b3b30f7874ed00a582aa9526c23ca89678bf796 | refs/heads/master | 2023-03-15T22:24:21.249109 | 2020-11-22T15:11:45 | 2020-11-22T15:11:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,203 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// $Id: G4GeomTestSegment.hh,v 1.4 2007/05/11 13:43:59 gcosmo Exp $
// GEANT4 tag $Name: geant4-09-03-patch-01 $
//
// --------------------------------------------------------------------
// GEANT 4 class header file
//
// G4GeomTestSegment
//
// Class description:
//
// Locate all points on a line that intersect a solid,
// and return them in no particular order
// Author: D.C.Williams, UCSC (davidw@scipp.ucsc.edu)
// --------------------------------------------------------------------
#ifndef G4GeomTestSegment_hh
#define G4GeomTestSegment_hh
#include "G4Types.hh"
#include "G4ThreeVector.hh"
#include "G4GeomTestPoint.hh"
#include <vector>
class G4VSolid;
class G4GeomTestLogger;
class G4GeomTestSegment
{
public: // with description
G4GeomTestSegment( const G4VSolid *theSolid,
const G4ThreeVector &theP,
const G4ThreeVector &theV,
G4GeomTestLogger *logger );
// Constructor
const G4VSolid *GetSolid() const;
const G4ThreeVector &GetP() const;
const G4ThreeVector &GetV() const;
const G4GeomTestPoint &GetPoint( G4int i ) const;
G4int GetNumberPoints() const;
// Accessors
private:
void FindPoints( G4GeomTestLogger *logger );
void FindSomePoints( G4GeomTestLogger *logger, G4bool forward );
void PatchInconsistencies( G4GeomTestLogger *logger );
const G4VSolid * solid;
const G4ThreeVector p0,v;
std::vector<G4GeomTestPoint> points;
G4double kCarTolerance;
};
#endif
| [
"r.e.deboer@students.uu.nl"
] | r.e.deboer@students.uu.nl |
57f74df476df092daa5c376a0e60d9059edc2e17 | 2550a0de6c2285d94fd3f42b24f8f2a6696045c3 | /Normal/1082/A.cpp | c449c0bb95600062c2d89dd2390371b27f44317f | [] | no_license | Mohd-3/Codeforces-Solutions | a2b26cf2072de7cdc0d2e754d7f0df0bad50174f | 97b0caf353a811f134a4c0206fd3c74fb4707149 | refs/heads/master | 2020-09-01T22:51:20.581848 | 2019-11-04T00:25:09 | 2019-11-04T00:25:09 | 219,078,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp | #include <bits/stdc++.h>
using namespace std;
int t, n, d, x, y;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d %d %d %d", &n, &x, &y, &d);
int ans = 1e9;
if (abs(x-y)%d == 0) {
ans = min(ans, abs(x-y)/d);
}
if ((y-1)%d == 0) {
ans = min(ans, (x-1+(d-1))/d + ((y-1)/d));
}
if ((n-y)%d == 0) {
ans = min((n-x+(d-1))/d + (n-y)/d, ans);
}
if (ans == 1e9)
printf("-1\n");
else
printf("%d\n", ans);
}
return 0;
}
| [
"mohd@al-abdulhadi.com"
] | mohd@al-abdulhadi.com |
855b4b06d0e2b424188e6f2721b9d217118804b6 | 8b734b0ddef937c222b8d2a50fb511faac52af7b | /SNES_Jukebox/progress_bar.h | c949a9a0571329bad875cbeea68b286fa3710867 | [
"MIT"
] | permissive | rrogovski/snes-jukebox | 82fcd747854cb4d08ec2fe03fc7a88f1f21d210a | 268e7d4b595a9318cd9fbbdd0ce2396a7ceacb5f | refs/heads/master | 2020-03-25T06:10:30.462199 | 2015-10-21T05:15:44 | 2015-10-21T05:35:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,335 | h | #ifndef PROGRESS_BAR_H
#define PROGRESS_BAR_H
#include "jukebox_io.h"
class ProgressBar {
public:
#define PROGRESS_BAR_HEIGHT 8
ProgressBar(Adafruit_ST7735 &lcd_, byte x_, byte y_, byte width_, uint32_t maxProgress_) : lcd(lcd_), x(x_), y(y_), width(width_), maxProgress(maxProgress_) {
currentProgress = 0;
lastProgress = 0;
beginLcdWrite();
lcd.drawRect(x, y, width, PROGRESS_BAR_HEIGHT, ST7735_WHITE);
lcd.fillRect(x + 1, y + 1, width - 2, PROGRESS_BAR_HEIGHT - 2, ST7735_BLACK);
endLcdWrite();
}
void addProgress(uint32_t newProgress) {
currentProgress += newProgress;
if (currentProgress > maxProgress)
currentProgress = maxProgress;
int lastProgressWidth = (int)floor(((float)lastProgress / maxProgress) * (width - 2));
int currentProgressWidth = (int)floor(((float)currentProgress / maxProgress) * (width - 2));
if (currentProgressWidth > lastProgressWidth) {
beginLcdWrite();
lcd.fillRect(x + 1 + lastProgressWidth, y + 1, (currentProgressWidth - lastProgressWidth), PROGRESS_BAR_HEIGHT - 2, ST7735_GREEN);
endLcdWrite();
}
lastProgress = currentProgress;
}
private:
Adafruit_ST7735 &lcd;
byte x;
byte y;
byte width;
uint32_t maxProgress;
uint32_t currentProgress;
uint32_t lastProgress;
};
#endif
| [
"pika242@gmail.com"
] | pika242@gmail.com |
2cd88367dc50d9ca777ee475c4de6d3c4b3123a0 | 99b97e802008e7e578f074e25c0a2f5b85cbd83e | /顺序栈.cpp | 70ba9f655d1457f873fa9f2a0157dfac2ed115e3 | [] | no_license | jx-66/jx | 2f57afbbaa6b2a5f9d7db90d70c77c9733edd63d | 5f51ac9194876d2b62a1afaaf17ef0350c187b90 | refs/heads/main | 2023-01-08T11:14:05.573062 | 2020-11-06T01:37:12 | 2020-11-06T01:37:12 | 309,133,479 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,421 | cpp | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define N 50
typedef char Elemtype;
typedef struct SqStack{
Elemtype *base; //栈底
Elemtype *top; //栈顶
int StackSize;
}SqStack;
//初始化栈
int InitStack(SqStack &s)
{
s.base=(Elemtype*)malloc(sizeof(Elemtype));
if(!s.base) return 0; //分配失败
s.top=s.base;
s.StackSize=N;
}
//销毁栈
int DestroyStack(SqStack &s)
{
}
//清空一个栈
void ClearStack(SqStack &s)
{
s.base=s.top;
}
//判断栈是否为空
bool StackEmpty(SqStack s)
{
if(s.base==s.top) return true;
else return false;
}
//栈中元素的个数
int StackLength(SqStack s)
{
return s.top-s.base;
}
//将元素压入栈
int Push(SqStack &s,Elemtype e)
{
if(s.top-s.base>=N) return 0;//栈已满
*(s.top)=e;
s.top++; //*(s.top++)=e;
return 1;
}
//删除栈顶元素
int Pop(SqStack &s,Elemtype &e)
{
if(s.top-s.base==0) return 0;//栈已为空
--s.top;
e=*(s.top);//e=*(--s.top);
return 1;
}
int main()
{
SqStack s;
InitStack(s);
cout<<"请输入5个元素:";
for(int i=0;i<5;i++)
{
char ch;
cin>>ch;
Elemtype tmp=ch;
Push(s,tmp);
}
cout<<"栈中元素个数:"<<StackLength(s)<<endl;
cout<<"栈中元素:";
for(int i=0;i<4;i++)
{
Elemtype e;
Pop(s,e);
cout<<e;
}
cout<<endl;
cout<<"栈是否为空?"<<StackEmpty(s)<<endl;
ClearStack(s);
cout<<"栈是否为空?"<<StackEmpty(s)<<endl;
return 0;
} | [
"73505853+ZZZzzz175@users.noreply.github.com"
] | 73505853+ZZZzzz175@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.